@sagmans/dsh-provider-extra 0.2.0 → 0.2.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 CHANGED
@@ -113,10 +113,10 @@ Sign in from the profile you are already using: the plugin registers a command i
113
113
  /dsh-provider-extra-login # pick a provider, then run its sign-in
114
114
  /dsh-provider-extra-login openai-codex # skip the picker: that provider's subscription login
115
115
  /dsh-provider-extra-login anthropic key # that provider's API-key entry
116
- /dsh-provider-extra-login status # what is stored, provider by provider
116
+ /dsh-provider-extra-login status # how each provider authenticates today
117
117
  ```
118
118
 
119
- The command runs inside the server, so the credential lands in the store the routes read, and it serves the next request with no restart. A provider the profile never declared is declared in the `llm-pi-ai` settings as a bare catalog route, because a stored credential no route reads fails the first turn with `no adapter registered`; the write names one provider, so routes and overrides already configured are untouched, and the success message says when it happened. Subscription flows show the page or device code as a dialog question and then finish on their own; a provider that asks for an API key collects it in the same dialog and spends it on one minimal request before anything is written, so a key the provider refuses is reported and never stored, and the value stays out of the model's context either way. The command reports success only after reading the stored record back, so a flow that resolves without persisting is reported instead of passed off as a sign-in. Runs only in profiles that compose both the command registry and a session UI; set `loginCommandEnabled: false` to omit it.
119
+ The command runs inside the server, so the credential lands in the store the routes read, and it serves the next request with no restart. A provider the profile never declared is declared in the `llm-pi-ai` settings as a bare catalog route, because a stored credential no route reads fails the first turn with `no adapter registered`; the write names one provider, so routes and overrides already configured are untouched, and the success message says when it happened. Subscription flows show the page or device code as a dialog question and then finish on their own; a provider that asks for an API key collects it in the same dialog and spends it on one minimal request before anything is written, so a key the provider refuses is reported and never stored, and the value stays out of the model's context either way. The API-key question's id ends in `:secret`, which is how a surface that understands the marker knows to keep the pasted value out of sight; a surface that does not is left with the wording. The command reports success only after reading the stored record back, so a flow that resolves without persisting is reported instead of passed off as a sign-in. Runs only in profiles that compose both the command registry and a session UI; set `loginCommandEnabled: false` to omit it.
120
120
 
121
121
  Without a command palette — a headless composition, or a sign-in for a server you are not attached to — use the shipped bin instead. It signs into the Codex route only, and needs the same `DSH_HOME` as the harness plus a profile that has booted at least once, because that is what installs the tree the bin resolves the harness packages through:
122
122
 
package/dist/index.js CHANGED
@@ -34,7 +34,7 @@ import { builtinProviders } from '@earendil-works/pi-ai/providers/all';
34
34
  import { DEFAULT_EXTRA_MODEL_TEMPLATE, DEFAULT_OPENCODE_API_KEY_ENV, OPENCODE_GO_PROVIDER_ID, buildOpenCodeGoProfile, } from "./opencode-go.js";
35
35
  import { DEFAULT_CODEX_DISPLAY_NAME, DEFAULT_CODEX_ROUTE_ID, buildCodexProfile, codexApiKey, codexAuth, recordKeyFor, } from "./codex.js";
36
36
  import { DEFAULT_LOGIN_COMMAND_NAME, createLoginCommand } from "./login-command.js";
37
- import { declareProviderRoute } from "./login-route.js";
37
+ import { declareProviderRoute, declaredCredentialRef } from "./login-route.js";
38
38
  import { PendingCredentialStore, proveApiKey } from "./login-verify.js";
39
39
  /** Settings namespace configuration surfaces address this plugin's section by. */
40
40
  const SETTINGS_NS = 'dsh-provider-extra';
@@ -251,6 +251,20 @@ export function apply(ctx, config) {
251
251
  return undefined;
252
252
  return record.kind === 'api-key' ? 'api_key' : 'oauth';
253
253
  },
254
+ reference: async (providerId) => {
255
+ // A route this plugin mounts names its reference in this plugin's
256
+ // config; every other route is whatever llm-pi-ai was configured
257
+ // with, which is the same document a sign-in declares into.
258
+ const ref = declaredCredentialRef(ctx.get('settings'), providerId)
259
+ ?? (providerId === route.provider ? route.apiKeyEnv : undefined);
260
+ if (ref === undefined || ref.length === 0)
261
+ return undefined;
262
+ const credentials = ctx.get('credentials');
263
+ if (credentials === undefined)
264
+ return { ref };
265
+ const info = await credentials.describe(ref);
266
+ return { ref, ...info.configured && info.source !== undefined ? { source: info.source } : {} };
267
+ },
254
268
  // Resolved per call, never at mount: a composition that mounts no
255
269
  // session UI still gets the command, and says so when it runs.
256
270
  ask: async (request) => {
@@ -0,0 +1,247 @@
1
+ /**
2
+ * One attended sign-in, from the first question to the stored credential.
3
+ *
4
+ * pi-ai drives the flow and asks through its own interaction seam; every ask
5
+ * becomes a question the session UI renders, and the page or device code is
6
+ * held open as a question of its own so a flow that is waiting stays visible
7
+ * and cancellable. The attempt owns the deadline, the notices, and the verdict
8
+ * the command finally reports.
9
+ *
10
+ * @module dsh-provider-extra/login-attempt
11
+ */
12
+ import { renderEvent } from "./codex-login.js";
13
+ import { answerLabels, answerText } from "./login-choice.js";
14
+ /** Question ids belong to the caller; the answer echoes them back. */
15
+ const PROMPT_QUESTION_ID = 'prompt';
16
+ const NOTICE_QUESTION_ID = 'notice';
17
+ /**
18
+ * Question id suffix declaring that the typed answer is a credential. The
19
+ * question seam has no field for it, so the id carries the declaration: it is
20
+ * the one caller-owned token that reaches a surface unchanged, and a surface
21
+ * that knows the suffix hides the value instead of guessing from the wording.
22
+ */
23
+ const SECRET_ID_SUFFIX = ':secret';
24
+ /** The id a secret prompt answers to, so its answer is never shown. */
25
+ const SECRET_PROMPT_QUESTION_ID = PROMPT_QUESTION_ID + SECRET_ID_SUFFIX;
26
+ /** Answer labels this command owns, so a decision is never read as typed text. */
27
+ const DONE_LABEL = 'Done';
28
+ const CANCEL_LABEL = 'Cancel';
29
+ /**
30
+ * Caveat rendered with a secret prompt. The answer reaches the provider that
31
+ * issued the key and the credential store, never the model's context, but a
32
+ * session UI can only show what the human types: saying so is the difference
33
+ * between a choice and a trap.
34
+ */
35
+ const SECRET_DETAIL = 'The value is stored in your credential store and sent only to this provider to be checked.';
36
+ /** Guidance added to a page or device-code question, where waiting is the task. */
37
+ const WAIT_DETAIL = 'Finish on that page, then choose Done. The sign-in completes by itself.';
38
+ /**
39
+ * Said when the sign-in had to declare the route. The settings file grew an
40
+ * entry on the human's behalf, and a configuration change they did not make is
41
+ * one they must hear about.
42
+ */
43
+ const DECLARED_ROUTE_NOTICE = ' The provider was added to the llm-pi-ai settings, so its models work now.';
44
+ /** Said when a configured route already carried the sign-in. */
45
+ const PRESENT_ROUTE_NOTICE = ' The credential is stored and the route reads it on its next request.';
46
+ /**
47
+ * Said when nothing here can serve the provider. A stored credential with no
48
+ * route is the state that later fails a turn, so the failure belongs to the
49
+ * sign-in that caused it rather than to a model request the human cannot explain.
50
+ */
51
+ const UNAVAILABLE_ROUTE_NOTICE = ' Nothing in this composition serves its models: mount an llm-pi-ai service to use them.';
52
+ /** Upper bound on one attended attempt, longer than any device code lives. */
53
+ const ATTEMPT_DEADLINE_MS = 15 * 60_000;
54
+ /** Close the waiting question, if one is open, and let its ask settle. */
55
+ async function closeWait(attempt) {
56
+ const open = attempt.wait;
57
+ attempt.wait = undefined;
58
+ if (open === undefined)
59
+ return;
60
+ open.abort.abort();
61
+ await open.settled;
62
+ }
63
+ /**
64
+ * Hold the page or device code open as a question while the flow waits for the
65
+ * human. Answering Done needs no handling — the flow finishes on its own — so
66
+ * only Cancel is read, and the question is withdrawn the moment the flow ends.
67
+ */
68
+ function openWait(host, invocation, choice, attempt) {
69
+ const abort = new AbortController();
70
+ const asked = host.ask({
71
+ agent: invocation.agent,
72
+ questions: [{
73
+ id: NOTICE_QUESTION_ID,
74
+ header: choice.providerName,
75
+ question: 'Finish signing in',
76
+ detail: [...attempt.notices, WAIT_DETAIL].join('\n'),
77
+ options: [{ label: DONE_LABEL }, { label: CANCEL_LABEL }],
78
+ }],
79
+ signal: abort.signal,
80
+ });
81
+ const settled = asked.then((answer) => {
82
+ if (answerLabels(answer, NOTICE_QUESTION_ID).includes(CANCEL_LABEL)) {
83
+ attempt.declined = true;
84
+ attempt.abort.abort();
85
+ }
86
+ }, () => {
87
+ // A withdrawn question is the normal end of an attempt: the flow settled
88
+ // first, or the surface cannot ask. Either way the flow's own outcome rules.
89
+ });
90
+ attempt.wait = { abort, settled };
91
+ }
92
+ /** The question one pi-ai prompt becomes, so the human can answer it. */
93
+ function promptQuestion(prompt, choice) {
94
+ const header = choice.providerName;
95
+ switch (prompt.type) {
96
+ case 'select':
97
+ return {
98
+ id: PROMPT_QUESTION_ID,
99
+ header,
100
+ question: prompt.message,
101
+ options: prompt.options.map(option => ({
102
+ label: option.label,
103
+ ...option.description === undefined ? {} : { description: option.description },
104
+ })),
105
+ };
106
+ case 'secret':
107
+ return {
108
+ id: SECRET_PROMPT_QUESTION_ID,
109
+ header,
110
+ question: prompt.message,
111
+ detail: SECRET_DETAIL + (prompt.placeholder === undefined ? '' : ' ' + prompt.placeholder),
112
+ };
113
+ case 'manual_code':
114
+ return {
115
+ id: PROMPT_QUESTION_ID,
116
+ header,
117
+ question: prompt.message,
118
+ detail: 'Answer here only if the browser did not finish the sign-in.'
119
+ + (prompt.placeholder === undefined ? '' : ' ' + prompt.placeholder),
120
+ };
121
+ case 'text':
122
+ return {
123
+ id: PROMPT_QUESTION_ID,
124
+ header,
125
+ question: prompt.message,
126
+ ...prompt.placeholder === undefined ? {} : { detail: prompt.placeholder },
127
+ };
128
+ }
129
+ }
130
+ /** The id the answer to one prompt echoes back, which declares a secret as one. */
131
+ function promptQuestionId(prompt) {
132
+ return prompt.type === 'secret' ? SECRET_PROMPT_QUESTION_ID : PROMPT_QUESTION_ID;
133
+ }
134
+ /** Answer one pi-ai prompt through the session UI. */
135
+ async function askPrompt(host, invocation, prompt, choice, attempt) {
136
+ const questionId = promptQuestionId(prompt);
137
+ const ask = host.ask({
138
+ agent: invocation.agent,
139
+ questions: [promptQuestion(prompt, choice)],
140
+ signal: attempt.abort.signal,
141
+ });
142
+ if (prompt.type === 'select') {
143
+ const options = prompt.options;
144
+ const answer = await ask;
145
+ for (const label of answerLabels(answer, questionId)) {
146
+ const hit = options.find(option => option.label === label);
147
+ if (hit !== undefined)
148
+ return hit.id;
149
+ }
150
+ // A select answers with an option id, never a position: an answer that
151
+ // names neither is echoed back only when it is an id pi-ai offered.
152
+ const typed = answerText(answer, questionId);
153
+ const byId = options.find(option => option.id === typed);
154
+ if (byId !== undefined)
155
+ return byId.id;
156
+ throw new Error('dsh-provider-extra: answer the sign-in question by choosing one of its options');
157
+ }
158
+ if (prompt.type === 'manual_code' && prompt.signal !== undefined) {
159
+ // The code is optional by design: pi-ai races this prompt against the
160
+ // browser callback and withdraws it when the callback wins. Waiting on
161
+ // the withdrawal instead of demanding a code keeps the callback able to
162
+ // finish the sign-in on its own.
163
+ const withdrawn = new Promise((_, reject) => {
164
+ const lose = () => { reject(new Error('dsh-provider-extra: the browser completed the sign-in')); };
165
+ if (prompt.signal?.aborted === true) {
166
+ lose();
167
+ return;
168
+ }
169
+ prompt.signal?.addEventListener('abort', lose, { once: true });
170
+ });
171
+ const answer = await Promise.race([ask, withdrawn]);
172
+ const typed = answerText(answer, questionId);
173
+ if (typed === undefined)
174
+ throw new Error('dsh-provider-extra: no code was given');
175
+ return typed;
176
+ }
177
+ const answer = await ask;
178
+ const typed = answerText(answer, questionId);
179
+ if (typed === undefined)
180
+ throw new Error('dsh-provider-extra: the sign-in question was left unanswered');
181
+ return typed;
182
+ }
183
+ /** The interaction one attempt hands to pi-ai's login. */
184
+ function attemptInteraction(host, invocation, choice, attempt) {
185
+ return {
186
+ signal: attempt.abort.signal,
187
+ notify: (event) => {
188
+ attempt.notices.push(...renderEvent(event));
189
+ if (attempt.wait === undefined)
190
+ openWait(host, invocation, choice, attempt);
191
+ },
192
+ prompt: async (prompt) => {
193
+ await closeWait(attempt);
194
+ return await askPrompt(host, invocation, prompt, choice, attempt);
195
+ },
196
+ };
197
+ }
198
+ /** What one finished sign-in means, said in terms of whether its models can be reached. */
199
+ function successText(choice, route) {
200
+ const signedIn = 'Signed in to ' + choice.providerName + ' (' + choice.methodLabel + ').';
201
+ if (route === 'declared')
202
+ return signedIn + DECLARED_ROUTE_NOTICE;
203
+ if (route === 'unavailable')
204
+ return signedIn + UNAVAILABLE_ROUTE_NOTICE;
205
+ return signedIn + PRESENT_ROUTE_NOTICE;
206
+ }
207
+ /** Why one attempt ended without a credential, as the human should read it. */
208
+ function describeFailure(error, attempt, choice) {
209
+ if (attempt.declined)
210
+ return 'The ' + choice.providerName + ' sign-in was cancelled.';
211
+ if (attempt.expired)
212
+ return 'The ' + choice.providerName + ' sign-in timed out; start it again to get a fresh code.';
213
+ const message = error instanceof Error ? error.message : String(error);
214
+ return 'The ' + choice.providerName + ' sign-in failed: ' + message;
215
+ }
216
+ /** Run one sign-in end to end: the conversation plus the stored-credential check. */
217
+ export async function runChoice(host, invocation, choice) {
218
+ const attempt = { abort: new AbortController(), notices: [], wait: undefined, declined: false, expired: false };
219
+ const deadline = setTimeout(() => {
220
+ attempt.expired = true;
221
+ attempt.abort.abort();
222
+ }, ATTEMPT_DEADLINE_MS);
223
+ if (typeof deadline === 'object')
224
+ deadline.unref();
225
+ try {
226
+ const route = await host.login(choice, attemptInteraction(host, invocation, choice, attempt));
227
+ await closeWait(attempt);
228
+ // pi-ai persists during login, so resolving is not yet proof: only a
229
+ // record read back is. A flow that resolves without one is a catalog bug
230
+ // the human must hear about rather than a silent no-op sign-in.
231
+ const stored = await host.stored(choice.providerId);
232
+ if (stored === undefined) {
233
+ return {
234
+ kind: 'error',
235
+ text: 'The ' + choice.providerName + ' sign-in reported success but stored no credential; nothing changed.',
236
+ };
237
+ }
238
+ return { kind: 'success', text: successText(choice, route) };
239
+ }
240
+ catch (error) {
241
+ return { kind: 'error', text: describeFailure(error, attempt, choice) };
242
+ }
243
+ finally {
244
+ clearTimeout(deadline);
245
+ await closeWait(attempt);
246
+ }
247
+ }
@@ -0,0 +1,97 @@
1
+ /**
2
+ * The catalog as the picker shows it, and the answers it accepts back.
3
+ *
4
+ * A sign-in starts from whatever the installed catalog ships, and a human
5
+ * answers a choice three ways — a label, a provider id, or free text — so the
6
+ * labels and the resolution that reads them back live together: every path has
7
+ * to land on the same provider-method pair.
8
+ *
9
+ * @module dsh-provider-extra/login-choice
10
+ */
11
+ /** Input word selecting the API-key method when a provider offers both. */
12
+ export const KEY_WORD = 'key';
13
+ /** Input word selecting the subscription method when a provider offers both. */
14
+ export const OAUTH_WORD = 'oauth';
15
+ /** Question ids belong to the caller; the answer echoes them back. */
16
+ const PICKER_QUESTION_ID = 'provider';
17
+ /** Split raw command input into lowercase words. */
18
+ export function words(rawInput) {
19
+ return rawInput.trim().toLowerCase().split(/\s+/u).filter(word => word.length > 0);
20
+ }
21
+ /** The label one choice shows: its provider alone when that provider has a single method. */
22
+ function choiceLabel(choice, shared) {
23
+ if (!shared)
24
+ return choice.providerName;
25
+ // A method label that already names its provider is the whole label: stitching
26
+ // the name onto it again reads as a stutter to the human choosing from it.
27
+ return choice.methodLabel.toLowerCase().includes(choice.providerName.toLowerCase())
28
+ ? choice.methodLabel
29
+ : choice.providerName + ' (' + choice.methodLabel + ')';
30
+ }
31
+ /** The option label for one choice; method labels disambiguate multi-auth providers. */
32
+ function optionLabels(choices) {
33
+ const perProvider = new Map();
34
+ for (const choice of choices) {
35
+ perProvider.set(choice.providerId, (perProvider.get(choice.providerId) ?? 0) + 1);
36
+ }
37
+ return choices.map(choice => choiceLabel(choice, (perProvider.get(choice.providerId) ?? 0) > 1));
38
+ }
39
+ /** The question the picker asks, one option per provider-method pair. */
40
+ export function pickerQuestion(choices) {
41
+ const labels = optionLabels(choices);
42
+ return {
43
+ id: PICKER_QUESTION_ID,
44
+ header: 'Sign in',
45
+ question: 'Which provider do you want to sign in to?',
46
+ options: choices.map((choice, index) => ({
47
+ label: labels[index] ?? choice.providerName,
48
+ description: choice.methodLabel + ' · ' + choice.providerId,
49
+ })),
50
+ };
51
+ }
52
+ /** The free text a single-question answer carries, if any. */
53
+ export function answerText(answer, questionId) {
54
+ const item = answer.answers.find(entry => entry.id === questionId);
55
+ const custom = item?.custom?.trim();
56
+ return custom === undefined || custom.length === 0 ? undefined : custom;
57
+ }
58
+ /** The option labels a single-question answer carries. */
59
+ export function answerLabels(answer, questionId) {
60
+ return answer.answers.find(entry => entry.id === questionId)?.selected ?? [];
61
+ }
62
+ /**
63
+ * Resolve what the picker's answer names: a label first, then free text as a
64
+ * provider id or a method word, so a capable UI that offers "Other" lands on
65
+ * the same choice as the menu.
66
+ */
67
+ export function resolveChoice(choices, answer) {
68
+ const labels = optionLabels(choices);
69
+ for (const label of answerLabels(answer, PICKER_QUESTION_ID)) {
70
+ const index = labels.indexOf(label);
71
+ if (index >= 0)
72
+ return choices[index];
73
+ }
74
+ const text = answerText(answer, PICKER_QUESTION_ID);
75
+ if (text === undefined)
76
+ 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'));
83
+ }
84
+ /** The choice a provider id (and optional method word) names. */
85
+ export function choiceByWords(choices, input) {
86
+ 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)
91
+ return undefined;
92
+ const method = input[1];
93
+ if (method === undefined)
94
+ return named[0];
95
+ const authType = method === KEY_WORD ? 'api_key' : 'oauth';
96
+ return named.find(choice => choice.authType === authType);
97
+ }
@@ -13,338 +13,19 @@
13
13
  * handler settles. The conversation therefore runs through the session UI's
14
14
  * question channel: the provider picker, every flow prompt, and the page or
15
15
  * device code are asked as questions, and the handler answers with the final
16
- * verdict only after the credential is stored and observed.
16
+ * verdict only after the credential is stored and observed. This module owns
17
+ * the command itself; the vocabulary, the picker, the attempt, and the status
18
+ * answer each live in their own module.
17
19
  *
18
20
  * @module dsh-provider-extra/login-command
19
21
  */
20
- import { renderEvent } from "./codex-login.js";
22
+ import { KEY_WORD, OAUTH_WORD, choiceByWords, pickerQuestion, resolveChoice, words } from "./login-choice.js";
23
+ import { runChoice } from "./login-attempt.js";
24
+ import { statusOf } from "./login-status.js";
21
25
  /** Command name a profile gets unless it renames the command. */
22
26
  export const DEFAULT_LOGIN_COMMAND_NAME = 'dsh-provider-extra-login';
23
27
  /** Input word showing what is already stored instead of starting a sign-in. */
24
28
  const STATUS_WORD = 'status';
25
- /** Input word selecting the API-key method when a provider offers both. */
26
- const KEY_WORD = 'key';
27
- /** Input word selecting the subscription method when a provider offers both. */
28
- const OAUTH_WORD = 'oauth';
29
- /** Question ids belong to the caller; the answer echoes them back. */
30
- const PICKER_QUESTION_ID = 'provider';
31
- const NOTICE_QUESTION_ID = 'notice';
32
- const PROMPT_QUESTION_ID = 'prompt';
33
- /** Answer labels this command owns, so a decision is never read as typed text. */
34
- const DONE_LABEL = 'Done';
35
- const CANCEL_LABEL = 'Cancel';
36
- /**
37
- * Caveat rendered with a secret prompt. The answer reaches the provider that
38
- * issued the key and the credential store, never the model's context, but a
39
- * session UI can only show what the human types: saying so is the difference
40
- * between a choice and a trap.
41
- */
42
- const SECRET_DETAIL = 'The value is stored in your credential store and sent only to this provider to be checked.';
43
- /** Guidance added to a page or device-code question, where waiting is the task. */
44
- const WAIT_DETAIL = 'Finish on that page, then choose Done. The sign-in completes by itself.';
45
- /**
46
- * Said when the sign-in had to declare the route. The settings file grew an
47
- * entry on the human's behalf, and a configuration change they did not make is
48
- * one they must hear about.
49
- */
50
- const DECLARED_ROUTE_NOTICE = ' The provider was added to the llm-pi-ai settings, so its models work now.';
51
- /** Said when a configured route already carried the sign-in. */
52
- const PRESENT_ROUTE_NOTICE = ' The credential is stored and the route reads it on its next request.';
53
- /**
54
- * Said when nothing here can serve the provider. A stored credential with no
55
- * route is the state that later fails a turn, so the failure belongs to the
56
- * sign-in that caused it rather than to a model request the human cannot explain.
57
- */
58
- const UNAVAILABLE_ROUTE_NOTICE = ' Nothing in this composition serves its models: mount an llm-pi-ai service to use them.';
59
- /** Upper bound on one attended attempt, longer than any device code lives. */
60
- const ATTEMPT_DEADLINE_MS = 15 * 60_000;
61
- /** Split raw command input into lowercase words. */
62
- function words(rawInput) {
63
- return rawInput.trim().toLowerCase().split(/\s+/u).filter(word => word.length > 0);
64
- }
65
- /** The label one choice shows: its provider alone when that provider has a single method. */
66
- function choiceLabel(choice, shared) {
67
- if (!shared)
68
- return choice.providerName;
69
- // A method label that already names its provider is the whole label: stitching
70
- // the name onto it again reads as a stutter to the human choosing from it.
71
- return choice.methodLabel.toLowerCase().includes(choice.providerName.toLowerCase())
72
- ? choice.methodLabel
73
- : choice.providerName + ' (' + choice.methodLabel + ')';
74
- }
75
- /** The option label for one choice; method labels disambiguate multi-auth providers. */
76
- function optionLabels(choices) {
77
- const perProvider = new Map();
78
- for (const choice of choices) {
79
- perProvider.set(choice.providerId, (perProvider.get(choice.providerId) ?? 0) + 1);
80
- }
81
- return choices.map(choice => choiceLabel(choice, (perProvider.get(choice.providerId) ?? 0) > 1));
82
- }
83
- /** The question the picker asks, one option per provider-method pair. */
84
- function pickerQuestion(choices) {
85
- const labels = optionLabels(choices);
86
- return {
87
- id: PICKER_QUESTION_ID,
88
- header: 'Sign in',
89
- question: 'Which provider do you want to sign in to?',
90
- options: choices.map((choice, index) => ({
91
- label: labels[index] ?? choice.providerName,
92
- description: choice.methodLabel + ' · ' + choice.providerId,
93
- })),
94
- };
95
- }
96
- /** The free text a single-question answer carries, if any. */
97
- function answerText(answer, questionId) {
98
- const item = answer.answers.find(entry => entry.id === questionId);
99
- const custom = item?.custom?.trim();
100
- return custom === undefined || custom.length === 0 ? undefined : custom;
101
- }
102
- /** The option labels a single-question answer carries. */
103
- function answerLabels(answer, questionId) {
104
- return answer.answers.find(entry => entry.id === questionId)?.selected ?? [];
105
- }
106
- /**
107
- * Resolve what the picker's answer names: a label first, then free text as a
108
- * provider id or a method word, so a capable UI that offers "Other" lands on
109
- * the same choice as the menu.
110
- */
111
- function resolveChoice(choices, answer) {
112
- const labels = optionLabels(choices);
113
- for (const label of answerLabels(answer, PICKER_QUESTION_ID)) {
114
- const index = labels.indexOf(label);
115
- if (index >= 0)
116
- return choices[index];
117
- }
118
- const text = answerText(answer, PICKER_QUESTION_ID);
119
- if (text === undefined)
120
- return undefined;
121
- const named = choices.filter(choice => choice.providerId === text.toLowerCase());
122
- if (named.length === 1)
123
- return named[0];
124
- const method = text.toLowerCase().split(/\s+/u)[1] ?? text.toLowerCase();
125
- return named.find(choice => choice.authType === (method === KEY_WORD ? 'api_key' : 'oauth'))
126
- ?? choices.find(choice => choice.authType === (method === KEY_WORD ? 'api_key' : 'oauth'));
127
- }
128
- /** The choice a provider id (and optional method word) names. */
129
- function choiceByWords(choices, input) {
130
- const providerId = input[0];
131
- if (providerId === undefined)
132
- return undefined;
133
- const named = choices.filter(choice => choice.providerId === providerId);
134
- if (named.length === 0)
135
- return undefined;
136
- const method = input[1];
137
- if (method === undefined)
138
- return named[0];
139
- const authType = method === KEY_WORD ? 'api_key' : 'oauth';
140
- return named.find(choice => choice.authType === authType);
141
- }
142
- /** Close the waiting question, if one is open, and let its ask settle. */
143
- async function closeWait(attempt) {
144
- const open = attempt.wait;
145
- attempt.wait = undefined;
146
- if (open === undefined)
147
- return;
148
- open.abort.abort();
149
- await open.settled;
150
- }
151
- /**
152
- * Hold the page or device code open as a question while the flow waits for the
153
- * human. Answering Done needs no handling — the flow finishes on its own — so
154
- * only Cancel is read, and the question is withdrawn the moment the flow ends.
155
- */
156
- function openWait(host, invocation, choice, attempt) {
157
- const abort = new AbortController();
158
- const asked = host.ask({
159
- agent: invocation.agent,
160
- questions: [{
161
- id: NOTICE_QUESTION_ID,
162
- header: choice.providerName,
163
- question: 'Finish signing in',
164
- detail: [...attempt.notices, WAIT_DETAIL].join('\n'),
165
- options: [{ label: DONE_LABEL }, { label: CANCEL_LABEL }],
166
- }],
167
- signal: abort.signal,
168
- });
169
- const settled = asked.then((answer) => {
170
- if (answerLabels(answer, NOTICE_QUESTION_ID).includes(CANCEL_LABEL)) {
171
- attempt.declined = true;
172
- attempt.abort.abort();
173
- }
174
- }, () => {
175
- // A withdrawn question is the normal end of an attempt: the flow settled
176
- // first, or the surface cannot ask. Either way the flow's own outcome rules.
177
- });
178
- attempt.wait = { abort, settled };
179
- }
180
- /** The question one pi-ai prompt becomes, so the human can answer it. */
181
- function promptQuestion(prompt, choice) {
182
- const header = choice.providerName;
183
- switch (prompt.type) {
184
- case 'select':
185
- return {
186
- id: PROMPT_QUESTION_ID,
187
- header,
188
- question: prompt.message,
189
- options: prompt.options.map(option => ({
190
- label: option.label,
191
- ...option.description === undefined ? {} : { description: option.description },
192
- })),
193
- };
194
- case 'secret':
195
- return {
196
- id: PROMPT_QUESTION_ID,
197
- header,
198
- question: prompt.message,
199
- detail: SECRET_DETAIL + (prompt.placeholder === undefined ? '' : ' ' + prompt.placeholder),
200
- };
201
- case 'manual_code':
202
- return {
203
- id: PROMPT_QUESTION_ID,
204
- header,
205
- question: prompt.message,
206
- detail: 'Answer here only if the browser did not finish the sign-in.'
207
- + (prompt.placeholder === undefined ? '' : ' ' + prompt.placeholder),
208
- };
209
- case 'text':
210
- return {
211
- id: PROMPT_QUESTION_ID,
212
- header,
213
- question: prompt.message,
214
- ...prompt.placeholder === undefined ? {} : { detail: prompt.placeholder },
215
- };
216
- }
217
- }
218
- /** Answer one pi-ai prompt through the session UI. */
219
- async function askPrompt(host, invocation, prompt, choice, attempt) {
220
- const ask = host.ask({
221
- agent: invocation.agent,
222
- questions: [promptQuestion(prompt, choice)],
223
- signal: attempt.abort.signal,
224
- });
225
- if (prompt.type === 'select') {
226
- const options = prompt.options;
227
- const answer = await ask;
228
- for (const label of answerLabels(answer, PROMPT_QUESTION_ID)) {
229
- const hit = options.find(option => option.label === label);
230
- if (hit !== undefined)
231
- return hit.id;
232
- }
233
- // A select answers with an option id, never a position: an answer that
234
- // names neither is echoed back only when it is an id pi-ai offered.
235
- const typed = answerText(answer, PROMPT_QUESTION_ID);
236
- const byId = options.find(option => option.id === typed);
237
- if (byId !== undefined)
238
- return byId.id;
239
- throw new Error('dsh-provider-extra: answer the sign-in question by choosing one of its options');
240
- }
241
- if (prompt.type === 'manual_code' && prompt.signal !== undefined) {
242
- // The code is optional by design: pi-ai races this prompt against the
243
- // browser callback and withdraws it when the callback wins. Waiting on
244
- // the withdrawal instead of demanding a code keeps the callback able to
245
- // finish the sign-in on its own.
246
- const withdrawn = new Promise((_, reject) => {
247
- const lose = () => { reject(new Error('dsh-provider-extra: the browser completed the sign-in')); };
248
- if (prompt.signal?.aborted === true) {
249
- lose();
250
- return;
251
- }
252
- prompt.signal?.addEventListener('abort', lose, { once: true });
253
- });
254
- const answer = await Promise.race([ask, withdrawn]);
255
- const typed = answerText(answer, PROMPT_QUESTION_ID);
256
- if (typed === undefined)
257
- throw new Error('dsh-provider-extra: no code was given');
258
- return typed;
259
- }
260
- const answer = await ask;
261
- const typed = answerText(answer, PROMPT_QUESTION_ID);
262
- if (typed === undefined)
263
- throw new Error('dsh-provider-extra: the sign-in question was left unanswered');
264
- return typed;
265
- }
266
- /** The interaction one attempt hands to pi-ai's login. */
267
- function attemptInteraction(host, invocation, choice, attempt) {
268
- return {
269
- signal: attempt.abort.signal,
270
- notify: (event) => {
271
- attempt.notices.push(...renderEvent(event));
272
- if (attempt.wait === undefined)
273
- openWait(host, invocation, choice, attempt);
274
- },
275
- prompt: async (prompt) => {
276
- await closeWait(attempt);
277
- return await askPrompt(host, invocation, prompt, choice, attempt);
278
- },
279
- };
280
- }
281
- /** What one finished sign-in means, said in terms of whether its models can be reached. */
282
- function successText(choice, route) {
283
- const signedIn = 'Signed in to ' + choice.providerName + ' (' + choice.methodLabel + ').';
284
- if (route === 'declared')
285
- return signedIn + DECLARED_ROUTE_NOTICE;
286
- if (route === 'unavailable')
287
- return signedIn + UNAVAILABLE_ROUTE_NOTICE;
288
- return signedIn + PRESENT_ROUTE_NOTICE;
289
- }
290
- /** Why one attempt ended without a credential, as the human should read it. */
291
- function describeFailure(error, attempt, choice) {
292
- if (attempt.declined)
293
- return 'The ' + choice.providerName + ' sign-in was cancelled.';
294
- if (attempt.expired)
295
- return 'The ' + choice.providerName + ' sign-in timed out; start it again to get a fresh code.';
296
- const message = error instanceof Error ? error.message : String(error);
297
- return 'The ' + choice.providerName + ' sign-in failed: ' + message;
298
- }
299
- /** Run one sign-in end to end: the conversation plus the stored-credential check. */
300
- async function runChoice(host, invocation, choice) {
301
- const attempt = { abort: new AbortController(), notices: [], wait: undefined, declined: false, expired: false };
302
- const deadline = setTimeout(() => {
303
- attempt.expired = true;
304
- attempt.abort.abort();
305
- }, ATTEMPT_DEADLINE_MS);
306
- if (typeof deadline === 'object')
307
- deadline.unref();
308
- try {
309
- const route = await host.login(choice, attemptInteraction(host, invocation, choice, attempt));
310
- await closeWait(attempt);
311
- // pi-ai persists during login, so resolving is not yet proof: only a
312
- // record read back is. A flow that resolves without one is a catalog bug
313
- // the human must hear about rather than a silent no-op sign-in.
314
- const stored = await host.stored(choice.providerId);
315
- if (stored === undefined) {
316
- return {
317
- kind: 'error',
318
- text: 'The ' + choice.providerName + ' sign-in reported success but stored no credential; nothing changed.',
319
- };
320
- }
321
- return { kind: 'success', text: successText(choice, route) };
322
- }
323
- catch (error) {
324
- return { kind: 'error', text: describeFailure(error, attempt, choice) };
325
- }
326
- finally {
327
- clearTimeout(deadline);
328
- await closeWait(attempt);
329
- }
330
- }
331
- /** Answer what is already stored, per provider. */
332
- async function statusOf(host) {
333
- const choices = host.choices();
334
- if (choices.length === 0) {
335
- return { kind: 'error', text: 'dsh-provider-extra: this composition mounts no provider with an interactive sign-in' };
336
- }
337
- const seen = new Set();
338
- const lines = [];
339
- for (const choice of choices) {
340
- if (seen.has(choice.providerId))
341
- continue;
342
- seen.add(choice.providerId);
343
- const stored = await host.stored(choice.providerId);
344
- lines.push(' ' + choice.providerName + ' — ' + (stored === undefined ? 'not signed in' : 'signed in (' + stored + ')'));
345
- }
346
- return { kind: 'success', text: ['Provider sign-in status:', ...lines].join('\n') };
347
- }
348
29
  /**
349
30
  * Build the provider sign-in command.
350
31
  *
@@ -0,0 +1,10 @@
1
+ /**
2
+ * The vocabulary the sign-in command and the conversation it runs share.
3
+ *
4
+ * The command flow, the catalog picker, the pi-ai attempt, and the status
5
+ * answer all read the same few shapes; each module depends on this contract
6
+ * rather than on the others, so none of them owns another's interface.
7
+ *
8
+ * @module dsh-provider-extra/login-contract
9
+ */
10
+ export {};
@@ -15,6 +15,8 @@
15
15
  const PI_AI_SETTINGS_NAMESPACE = 'llm-pi-ai';
16
16
  /** The dict whose keys are routes, matching that service's configuration shape. */
17
17
  const PROVIDERS_FIELD = 'providers';
18
+ /** The entry field naming the credential reference a route resolves. */
19
+ const API_KEY_ENV_FIELD = 'apiKeyEnv';
18
20
  /**
19
21
  * A catalog route needs no fields of its own: the installed catalog supplies
20
22
  * the endpoint, protocol, and models, and the credential is read from the store
@@ -28,6 +30,26 @@ function configuredProviders(value) {
28
30
  const providers = value[PROVIDERS_FIELD];
29
31
  return typeof providers === 'object' && providers !== null ? providers : undefined;
30
32
  }
33
+ /**
34
+ * The credential reference one declared route resolves, when its entry names
35
+ * one. A route declared without the field authenticates from the credential
36
+ * store instead, so it has no reference for a caller to report — and a route
37
+ * whose reference is unset never falls back to a stored record, which is why
38
+ * the reference alone answers what that route will use.
39
+ *
40
+ * @param settings - the settings service, absent in a composition that mounts none.
41
+ * @param providerId - the pi-ai catalog provider whose route entry to read.
42
+ * @returns the reference name, or nothing when the route names none.
43
+ */
44
+ export function declaredCredentialRef(settings, providerId) {
45
+ if (settings === undefined)
46
+ return undefined;
47
+ const entry = configuredProviders(settings.get(PI_AI_SETTINGS_NAMESPACE))?.[providerId];
48
+ if (typeof entry !== 'object' || entry === null)
49
+ return undefined;
50
+ const ref = entry[API_KEY_ENV_FIELD];
51
+ return typeof ref === 'string' && ref.length > 0 ? ref : undefined;
52
+ }
31
53
  /**
32
54
  * Give a freshly stored credential a route to be read through.
33
55
  *
@@ -0,0 +1,37 @@
1
+ /**
2
+ * What each provider authenticates with right now.
3
+ *
4
+ * A stored record and a configured route answer different questions, and a
5
+ * human asking for status means the one that decides whether their next turn
6
+ * works: the reference the route resolves, or the credential the sign-in
7
+ * stored. Reporting only the record once hid exactly the state that fails a
8
+ * turn, so the reference is read first.
9
+ *
10
+ * @module dsh-provider-extra/login-status
11
+ */
12
+ /** How one provider authenticates right now, as the human should read it. */
13
+ async function statusLine(host, choice) {
14
+ const reference = await host.reference(choice.providerId);
15
+ if (reference !== undefined) {
16
+ const where = reference.source === undefined ? 'not set' : 'set from ' + reference.source;
17
+ return ' ' + choice.providerName + ' — API key ' + reference.ref + ' (' + where + ')';
18
+ }
19
+ const stored = await host.stored(choice.providerId);
20
+ return ' ' + choice.providerName + ' — ' + (stored === undefined ? 'not signed in' : 'signed in (' + stored + ')');
21
+ }
22
+ /** Answer how each provider authenticates today. */
23
+ export async function statusOf(host) {
24
+ const choices = host.choices();
25
+ if (choices.length === 0) {
26
+ return { kind: 'error', text: 'dsh-provider-extra: this composition mounts no provider with an interactive sign-in' };
27
+ }
28
+ const seen = new Set();
29
+ const lines = [];
30
+ for (const choice of choices) {
31
+ if (seen.has(choice.providerId))
32
+ continue;
33
+ seen.add(choice.providerId);
34
+ lines.push(await statusLine(host, choice));
35
+ }
36
+ return { kind: 'success', text: ['Provider sign-in status:', ...lines].join('\n') };
37
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sagmans/dsh-provider-extra",
3
- "version": "0.2.0",
3
+ "version": "0.2.1",
4
4
  "description": "Extra LLM provider routes for DeepSeek Harness: OpenCode Go with per-session x-opencode-session routing, and OpenAI Codex over ChatGPT-subscription OAuth.",
5
5
  "keywords": [
6
6
  "deepseek-harness",