@sagmans/dsh-provider-extra 0.1.0 → 0.2.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.
package/README.md CHANGED
@@ -44,7 +44,7 @@ These commands remove the profile dependency and bundle activation, not stored c
44
44
  For unreleased work, clone this repository and link the checkout instead:
45
45
 
46
46
  ```sh
47
- git clone https://github.com/assagman/dsh-provider-extra.git
47
+ git clone https://github.com/sagmans/dsh-provider-extra.git
48
48
  cd dsh-provider-extra
49
49
  pnpm install --frozen-lockfile
50
50
  pnpm run check
@@ -56,7 +56,7 @@ Rebuild with `pnpm run build` after source changes, then restart the affected pr
56
56
 
57
57
  ### Optional profile overrides
58
58
 
59
- Defaults use the `opencode-go` and `openai-codex` routes, `OPENCODE_API_KEY`, and the fallback session ID `dsh-provider-extra`.
59
+ Defaults use the `opencode-go` and `openai-codex` routes, `OPENCODE_API_KEY`, the provider sign-in command `dsh-provider-extra-login`, and the fallback session ID `dsh-provider-extra`.
60
60
 
61
61
  To customize them, add an ID-targeted override to `$DSH_HOME/profiles/web/cordis.patch.yml`, `$DSH_HOME/profiles/tui/cordis.patch.yml`, or both. `DSH_HOME` defaults to `~/.dsh`.
62
62
 
@@ -67,6 +67,8 @@ To customize them, add an ID-targeted override to `$DSH_HOME/profiles/web/cordis
67
67
  routeId: opencode-go-session
68
68
  displayName: OpenCode Go (session)
69
69
  # codexEnabled: false
70
+ # loginCommandEnabled: false
71
+ # loginCommandName: dsh-provider-extra-login
70
72
  ```
71
73
 
72
74
  Preserve unrelated profile entries. Do not add a manual `insert` or `name`: the bundle owns plugin activation. Overrides can remain after removal without keeping the plugin active.
@@ -103,14 +105,25 @@ dsh-provider-extra:
103
105
 
104
106
  Each entry clones wire behavior from its template. Later entries win by ID. A catalog-owned ID is not replaced. An unknown template becomes a model diagnostic without disabling the route.
105
107
 
106
- ## Codex sign-in
108
+ ## Provider sign-in
107
109
 
108
- Run the attended login with the same `DSH_HOME` as your harness. An installed package ships the entry point:
110
+ Sign in from the profile you are already using: the plugin registers a command in the harness command palette, and it reaches every provider the installed pi-ai catalog ships a login for — the two routes here, and core's own.
111
+
112
+ ```text
113
+ /dsh-provider-extra-login # pick a provider, then run its sign-in
114
+ /dsh-provider-extra-login openai-codex # skip the picker: that provider's subscription login
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
117
+ ```
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.
120
+
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:
109
122
 
110
123
  ```sh
111
- dsh-provider-extra-login
124
+ "$DSH_HOME/profiles/web/node_modules/.bin/dsh-provider-extra-login"
112
125
  # If the server uses a non-default credentials file:
113
- dsh-provider-extra-login --credentials-path /absolute/path/to/.credentials.yaml
126
+ "$DSH_HOME/profiles/web/node_modules/.bin/dsh-provider-extra-login" --credentials-path /absolute/path/to/.credentials.yaml
114
127
  ```
115
128
 
116
129
  From a source checkout, `pnpm codex:login` runs the same entry point through the TypeScript loader.
@@ -89,15 +89,31 @@ export function terminalInteraction(terminal) {
89
89
  * Run the Codex OAuth login to completion against an already-built Models
90
90
  * collection. The collection carries the harness-backed store, so pi-ai
91
91
  * persists the grant itself; this function only conducts the conversation.
92
- * Secrets stay out of output: success names the provider, never the tokens.
92
+ *
93
+ * The interaction is a parameter rather than a terminal because the attended
94
+ * sign-in has two hosts: the package bin with a human at a prompt, and the
95
+ * server-side command handler, which announces the page and then waits without
96
+ * any terminal at all.
97
+ *
98
+ * @param models - collection holding the catalog Codex provider and the harness store.
99
+ * @param provider - the catalog Codex provider object to sign in with.
100
+ * @param interaction - pi-ai callbacks for this attempt.
101
+ */
102
+ export async function startCodexLogin(models, provider, interaction) {
103
+ models.setProvider(provider);
104
+ await models.login(CODEX_CATALOG_ID, OAUTH_TYPE, interaction);
105
+ }
106
+ /**
107
+ * Conduct the terminal sign-in: the same attempt, driven by readline, plus one
108
+ * closing line. Secrets stay out of output: success names the provider, never
109
+ * the tokens.
93
110
  *
94
111
  * @param models - collection holding the catalog Codex provider and the harness store.
95
112
  * @param provider - the catalog Codex provider object to sign in with.
96
113
  * @param terminal - line I/O for the human attending the sign-in.
97
114
  */
98
115
  export async function runCodexLogin(models, provider, terminal) {
99
- models.setProvider(provider);
100
- await models.login(CODEX_CATALOG_ID, OAUTH_TYPE, terminalInteraction(terminal));
116
+ await startCodexLogin(models, provider, terminalInteraction(terminal));
101
117
  terminal.print('Signed in to OpenAI Codex. The subscription grant is stored; the route serves it with no restart.');
102
118
  }
103
119
  /** A readline-backed terminal over stdin/stdout. */
package/dist/index.js CHANGED
@@ -21,7 +21,7 @@
21
21
  * # routeId: opencode-go # default; keep it out of llm-pi-ai providers
22
22
  * # baseURL: https://opencode.ai/zen/go/v1
23
23
  * # fallbackSessionId: dsh-provider-extra
24
- * # codexEnabled: true # sign in with: dsh-provider-extra-login
24
+ * # codexEnabled: true # sign in with: /dsh-provider-extra-login
25
25
  * # codexRouteId: openai-codex # default; keep it out of llm-pi-ai providers
26
26
  *
27
27
  * @module dsh-provider-extra
@@ -29,8 +29,13 @@
29
29
  import Schema from '@deepseek-ai/schemastery';
30
30
  import { PiAiAdapter } from '@deepseek-ai/dsh-llm-pi-ai';
31
31
  import { LlmError, assertUsableApiKey } from '@deepseek-ai/dsh-llm';
32
+ import { createModels } from '@earendil-works/pi-ai';
33
+ import { builtinProviders } from '@earendil-works/pi-ai/providers/all';
32
34
  import { DEFAULT_EXTRA_MODEL_TEMPLATE, DEFAULT_OPENCODE_API_KEY_ENV, OPENCODE_GO_PROVIDER_ID, buildOpenCodeGoProfile, } from "./opencode-go.js";
33
- import { DEFAULT_CODEX_DISPLAY_NAME, DEFAULT_CODEX_ROUTE_ID, buildCodexProfile, codexApiKey, codexAuth, } from "./codex.js";
35
+ import { DEFAULT_CODEX_DISPLAY_NAME, DEFAULT_CODEX_ROUTE_ID, buildCodexProfile, codexApiKey, codexAuth, recordKeyFor, } from "./codex.js";
36
+ import { DEFAULT_LOGIN_COMMAND_NAME, createLoginCommand } from "./login-command.js";
37
+ import { declareProviderRoute } from "./login-route.js";
38
+ import { PendingCredentialStore, proveApiKey } from "./login-verify.js";
34
39
  /** Settings namespace configuration surfaces address this plugin's section by. */
35
40
  const SETTINGS_NS = 'dsh-provider-extra';
36
41
  export const Config = Schema.object({
@@ -43,6 +48,8 @@ export const Config = Schema.object({
43
48
  codexEnabled: Schema.boolean().default(true),
44
49
  codexRouteId: Schema.string().default(DEFAULT_CODEX_ROUTE_ID),
45
50
  codexDisplayName: Schema.string().default(DEFAULT_CODEX_DISPLAY_NAME),
51
+ loginCommandEnabled: Schema.boolean().default(true),
52
+ loginCommandName: Schema.string().default(DEFAULT_LOGIN_COMMAND_NAME),
46
53
  });
47
54
  export const name = 'dsh-provider-extra';
48
55
  export const inject = ['llm'];
@@ -54,6 +61,43 @@ const extraModelSchema = Schema.object({
54
61
  const SectionSchema = Schema.object({
55
62
  extraModels: Schema.array(extraModelSchema).default([]),
56
63
  });
64
+ /**
65
+ * Every catalog provider that ships an interactive login, in catalog order.
66
+ * The catalog is the authority on how a provider signs in — which methods it
67
+ * offers, and what each is called — so the picker never re-decides that here.
68
+ */
69
+ function loginChoices() {
70
+ const choices = [];
71
+ for (const provider of builtinProviders()) {
72
+ const oauth = provider.auth?.oauth;
73
+ if (oauth?.login !== undefined) {
74
+ choices.push({
75
+ providerId: provider.id,
76
+ providerName: provider.name,
77
+ authType: 'oauth',
78
+ methodLabel: oauth.loginLabel ?? oauth.name,
79
+ });
80
+ }
81
+ const apiKey = provider.auth?.apiKey;
82
+ if (apiKey?.login !== undefined) {
83
+ choices.push({
84
+ providerId: provider.id,
85
+ providerName: provider.name,
86
+ authType: 'api_key',
87
+ methodLabel: apiKey.name,
88
+ });
89
+ }
90
+ }
91
+ return choices;
92
+ }
93
+ /** The catalog provider behind one sign-in choice. */
94
+ function catalogLoginProvider(providerId) {
95
+ const found = builtinProviders().find(provider => provider.id === providerId);
96
+ if (found === undefined) {
97
+ throw new Error('dsh-provider-extra: the installed pi-ai catalog no longer ships provider "' + providerId + '"');
98
+ }
99
+ return found;
100
+ }
57
101
  export function apply(ctx, config) {
58
102
  const route = {
59
103
  provider: config.routeId,
@@ -164,4 +208,67 @@ export function apply(ctx, config) {
164
208
  onChange: () => { },
165
209
  });
166
210
  });
211
+ // The command is the registry-install-friendly half of the attended sign-in:
212
+ // it runs in this process, so the credential lands in the store the routes
213
+ // already read and no bin path or peer tree is involved. It signs into any
214
+ // provider the installed catalog ships a login for, not only the two routes
215
+ // this plugin mounts, because a human asking to sign in means the provider
216
+ // they name and nothing narrower. Profiles without a command registry
217
+ // (headless compositions) keep the package bin.
218
+ if (config.loginCommandEnabled) {
219
+ ctx.inject(['commands'], (commandCtx) => {
220
+ const host = {
221
+ choices: loginChoices,
222
+ login: async (choice, interaction) => {
223
+ const credentials = () => ctx.get('credentials');
224
+ const auth = codexAuth(credentials);
225
+ const models = createModels(auth);
226
+ // pi-ai's collection starts empty: the catalog provider carrying the
227
+ // login implementation has to be handed to it before the flow runs.
228
+ models.setProvider(catalogLoginProvider(choice.providerId));
229
+ if (choice.authType !== 'api_key') {
230
+ await models.login(choice.providerId, choice.authType, interaction);
231
+ return await declareProviderRoute(ctx.get('settings'), choice.providerId);
232
+ }
233
+ // A grant the provider minted proves itself, but a key proves nothing
234
+ // until a request carries it, so the key is spent from a store that
235
+ // forgets and the profile hears of it only once it has been accepted.
236
+ const pending = createModels({ credentials: new PendingCredentialStore(), authContext: auth.authContext });
237
+ pending.setProvider(catalogLoginProvider(choice.providerId));
238
+ const credential = await pending.login(choice.providerId, choice.authType, interaction);
239
+ await proveApiKey(pending, choice.providerId);
240
+ await auth.credentials.modify(choice.providerId, async () => credential);
241
+ // The credential is only reachable through a declared route, so the
242
+ // sign-in is not finished until one exists.
243
+ return await declareProviderRoute(ctx.get('settings'), choice.providerId);
244
+ },
245
+ stored: async (providerId) => {
246
+ const credentials = ctx.get('credentials');
247
+ if (credentials === undefined)
248
+ return undefined;
249
+ const record = await credentials.readRecord(recordKeyFor(providerId));
250
+ if (record === undefined)
251
+ return undefined;
252
+ return record.kind === 'api-key' ? 'api_key' : 'oauth';
253
+ },
254
+ // Resolved per call, never at mount: a composition that mounts no
255
+ // session UI still gets the command, and says so when it runs.
256
+ ask: async (request) => {
257
+ const userQuestions = ctx.get('userQuestions');
258
+ if (userQuestions === undefined) {
259
+ throw new Error('dsh-provider-extra: this composition mounts no session UI that can ask the sign-in questions');
260
+ }
261
+ return await userQuestions.ask({
262
+ questions: [...request.questions],
263
+ agent: request.agent,
264
+ ...request.signal === undefined ? {} : { signal: request.signal },
265
+ });
266
+ },
267
+ };
268
+ commandCtx.commands.register(createLoginCommand(host, config.loginCommandName));
269
+ // Registration is silent otherwise, and the command is the one surface a
270
+ // user cannot see in a config dump: saying it exists is the diagnosis.
271
+ ctx.logger.info('dsh-provider-extra: /' + config.loginCommandName + ' signs in any provider with an interactive login');
272
+ });
273
+ }
167
274
  }
@@ -0,0 +1,400 @@
1
+ /**
2
+ * Provider sign-in from the command palette.
3
+ *
4
+ * The command palette is the only surface a registry install reliably has — a
5
+ * package bin is not on PATH and the tree it resolves through only exists
6
+ * after a boot — so the attended sign-in lives where the human already is. It
7
+ * is deliberately provider-agnostic: the host hands it every installed
8
+ * provider that ships an interactive login, and the command runs whichever
9
+ * one the human picks through pi-ai's own flow, so a new provider in the
10
+ * catalog needs no change here.
11
+ *
12
+ * A sign-in is a conversation, and a command result renders only once the
13
+ * handler settles. The conversation therefore runs through the session UI's
14
+ * question channel: the provider picker, every flow prompt, and the page or
15
+ * device code are asked as questions, and the handler answers with the final
16
+ * verdict only after the credential is stored and observed.
17
+ *
18
+ * @module dsh-provider-extra/login-command
19
+ */
20
+ import { renderEvent } from "./codex-login.js";
21
+ /** Command name a profile gets unless it renames the command. */
22
+ export const DEFAULT_LOGIN_COMMAND_NAME = 'dsh-provider-extra-login';
23
+ /** Input word showing what is already stored instead of starting a sign-in. */
24
+ 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
+ /**
349
+ * Build the provider sign-in command.
350
+ *
351
+ * @param host - the composition's providers, its login runner, and the session UI.
352
+ * @param commandName - registered name, without the leading slash.
353
+ * @returns the registry definition, valid until the profile unloads it.
354
+ */
355
+ export function createLoginCommand(host, commandName) {
356
+ const usage = 'Usage: /' + commandName + ' [<provider-id> [' + OAUTH_WORD + '|' + KEY_WORD + '] | ' + STATUS_WORD + ']';
357
+ return {
358
+ name: commandName,
359
+ description: 'Sign in to a model provider (subscription or API key)',
360
+ input: { hint: 'no input picks a provider, ' + STATUS_WORD + ' lists what is signed in' },
361
+ // The input is a provider id in normal use, but this command is also the
362
+ // one place a human might paste a key: keep the session log out of it.
363
+ recordInput: false,
364
+ handler: async (invocation) => {
365
+ const input = words(invocation.rawInput);
366
+ if (input.length === 1 && input[0] === STATUS_WORD)
367
+ return await statusOf(host);
368
+ if (input.length > 2)
369
+ return { kind: 'error', text: 'dsh-provider-extra: too many arguments. ' + usage };
370
+ const choices = host.choices();
371
+ if (choices.length === 0) {
372
+ return { kind: 'error', text: 'dsh-provider-extra: this composition mounts no provider with an interactive sign-in' };
373
+ }
374
+ let choice;
375
+ if (input.length === 0) {
376
+ try {
377
+ choice = resolveChoice(choices, await host.ask({
378
+ agent: invocation.agent,
379
+ questions: [pickerQuestion(choices)],
380
+ signal: invocation.signal,
381
+ }));
382
+ }
383
+ catch (error) {
384
+ const message = error instanceof Error ? error.message : String(error);
385
+ return { kind: 'error', text: 'dsh-provider-extra: no provider was picked (' + message + '). ' + usage };
386
+ }
387
+ if (choice === undefined)
388
+ return { kind: 'error', text: 'dsh-provider-extra: no provider was picked. ' + usage };
389
+ }
390
+ else {
391
+ choice = choiceByWords(choices, input);
392
+ if (choice === undefined) {
393
+ const known = [...new Set(choices.map(entry => entry.providerId))].join(', ');
394
+ return { kind: 'error', text: 'dsh-provider-extra: no sign-in named "' + input.join(' ') + '". Known providers: ' + known + '. ' + usage };
395
+ }
396
+ }
397
+ return await runChoice(host, invocation, choice);
398
+ },
399
+ };
400
+ }
@@ -0,0 +1,52 @@
1
+ /**
2
+ * Making a signed-in provider reachable.
3
+ *
4
+ * A sign-in stores a credential, but the harness serves a provider only through
5
+ * a route its own pi-ai service has been configured with: signing into a
6
+ * catalog provider the profile never declared stores a key that no request can
7
+ * use, and the first turn then fails with "no adapter registered for provider",
8
+ * which reads as a broken sign-in rather than the missing declaration it is.
9
+ * The write below adds that declaration, because a human who just signed in
10
+ * asked for a provider to work, not for a file to edit.
11
+ *
12
+ * @module dsh-provider-extra/login-route
13
+ */
14
+ /** The namespace the harness pi-ai service owns; its providers dict is the route set. */
15
+ const PI_AI_SETTINGS_NAMESPACE = 'llm-pi-ai';
16
+ /** The dict whose keys are routes, matching that service's configuration shape. */
17
+ const PROVIDERS_FIELD = 'providers';
18
+ /**
19
+ * A catalog route needs no fields of its own: the installed catalog supplies
20
+ * the endpoint, protocol, and models, and the credential is read from the store
21
+ * this command already wrote, so an empty profile is the whole declaration.
22
+ */
23
+ const CATALOG_ROUTE_OVERRIDES = {};
24
+ /** The configured routes, or nothing when no pi-ai service registered the namespace. */
25
+ function configuredProviders(value) {
26
+ if (typeof value !== 'object' || value === null)
27
+ return undefined;
28
+ const providers = value[PROVIDERS_FIELD];
29
+ return typeof providers === 'object' && providers !== null ? providers : undefined;
30
+ }
31
+ /**
32
+ * Give a freshly stored credential a route to be read through.
33
+ *
34
+ * The patch names one provider, so the settings service merges it over the
35
+ * routes a profile already configured and no existing key or override is
36
+ * restated, let alone lost.
37
+ *
38
+ * @param settings - the settings service, absent in a composition that mounts none.
39
+ * @param providerId - the pi-ai catalog provider that was just signed in.
40
+ * @returns whether the route was added, already configured, or cannot exist here.
41
+ */
42
+ export async function declareProviderRoute(settings, providerId) {
43
+ if (settings === undefined)
44
+ return 'unavailable';
45
+ const providers = configuredProviders(settings.get(PI_AI_SETTINGS_NAMESPACE));
46
+ if (providers === undefined)
47
+ return 'unavailable';
48
+ if (providers[providerId] !== undefined)
49
+ return 'present';
50
+ await settings.update(PI_AI_SETTINGS_NAMESPACE, { [PROVIDERS_FIELD]: { [providerId]: CATALOG_ROUTE_OVERRIDES } });
51
+ return 'declared';
52
+ }
@@ -0,0 +1,51 @@
1
+ /** The smallest request that still carries the credential. */
2
+ const PROBE_PROMPT = 'ping';
3
+ /** One token is enough: the reply is never read, only the error channel is. */
4
+ const PROBE_MAX_TOKENS = 1;
5
+ /** A provider that never answers must not hold a sign-in open. */
6
+ const PROBE_TIMEOUT_MS = 20_000;
7
+ const PROBE_TIMEOUT = 'the provider did not answer in time';
8
+ /** Prefix that turns a provider's own words into the sentence a human reads. */
9
+ const REJECTED_PREFIX = 'the provider did not accept this API key: ';
10
+ /**
11
+ * A credential store that forgets.
12
+ *
13
+ * A login writes what it collected as it goes, and the profile's store is the
14
+ * only one pi-ai can be handed, so the sign-in runs against this instead and
15
+ * the real store hears about the key only once the provider has answered for it.
16
+ */
17
+ export class PendingCredentialStore {
18
+ held = new Map();
19
+ async read(providerId) {
20
+ return this.held.get(providerId);
21
+ }
22
+ async list() {
23
+ return [...this.held].map(([providerId, credential]) => ({ providerId, type: credential.type }));
24
+ }
25
+ async modify(providerId, mutate) {
26
+ const next = await mutate(this.held.get(providerId));
27
+ if (next !== undefined)
28
+ this.held.set(providerId, next);
29
+ return next;
30
+ }
31
+ async delete(providerId) {
32
+ this.held.delete(providerId);
33
+ }
34
+ }
35
+ /**
36
+ * Ask the provider whether the credential it was just given works.
37
+ *
38
+ * Throws the provider's own explanation when it refuses, so the human can tell
39
+ * a mistyped key from a key that lacks a plan or a region.
40
+ */
41
+ export async function proveApiKey(models, providerId) {
42
+ 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
+ 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) });
48
+ if (answer.stopReason !== 'error' && answer.stopReason !== 'aborted')
49
+ return;
50
+ throw new Error(REJECTED_PREFIX + (answer.errorMessage ?? PROBE_TIMEOUT));
51
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sagmans/dsh-provider-extra",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
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",
@@ -39,10 +39,10 @@
39
39
  },
40
40
  "repository": {
41
41
  "type": "git",
42
- "url": "git+https://github.com/assagman/dsh-provider-extra.git"
42
+ "url": "git+https://github.com/sagmans/dsh-provider-extra.git"
43
43
  },
44
- "homepage": "https://github.com/assagman/dsh-provider-extra#readme",
45
- "bugs": "https://github.com/assagman/dsh-provider-extra/issues",
44
+ "homepage": "https://github.com/sagmans/dsh-provider-extra#readme",
45
+ "bugs": "https://github.com/sagmans/dsh-provider-extra/issues",
46
46
  "dsh": {
47
47
  "bundle": {
48
48
  "patch": "./cordis.patch.yml"
@@ -68,22 +68,34 @@
68
68
  },
69
69
  "peerDependencies": {
70
70
  "@deepseek-ai/cordis": "^4.0.2",
71
+ "@deepseek-ai/dsh-commands": ">=0.1.5-rc.1 <0.1.6",
71
72
  "@deepseek-ai/dsh-credentials": ">=0.1.5-rc.1 <0.1.6",
72
73
  "@deepseek-ai/dsh-credentials-local": ">=0.1.5-rc.1 <0.1.6",
73
74
  "@deepseek-ai/dsh-llm": ">=0.1.5-rc.1 <0.1.6",
74
75
  "@deepseek-ai/dsh-llm-pi-ai": ">=0.1.5-rc.1 <0.1.6",
75
76
  "@deepseek-ai/dsh-settings": ">=0.1.5-rc.1 <0.1.6",
77
+ "@deepseek-ai/dsh-user-questions": ">=0.1.5-rc.1 <0.1.6",
76
78
  "@deepseek-ai/schemastery": "^3.18.2",
77
79
  "@earendil-works/pi-ai": "^0.85.1"
78
80
  },
81
+ "peerDependenciesMeta": {
82
+ "@deepseek-ai/dsh-commands": {
83
+ "optional": true
84
+ },
85
+ "@deepseek-ai/dsh-user-questions": {
86
+ "optional": true
87
+ }
88
+ },
79
89
  "devDependencies": {
80
90
  "@deepseek-ai/cordis": "4.0.2",
91
+ "@deepseek-ai/dsh-commands": "0.1.5-rc.2",
81
92
  "@deepseek-ai/dsh": "0.1.5-rc.2",
82
93
  "@deepseek-ai/dsh-credentials": "0.1.5-rc.2",
83
94
  "@deepseek-ai/dsh-credentials-local": "0.1.5-rc.2",
84
95
  "@deepseek-ai/dsh-llm": "0.1.5-rc.2",
85
96
  "@deepseek-ai/dsh-llm-pi-ai": "0.1.5-rc.2",
86
97
  "@deepseek-ai/dsh-settings": "0.1.5-rc.2",
98
+ "@deepseek-ai/dsh-user-questions": "0.1.5-rc.2",
87
99
  "@deepseek-ai/schemastery": "3.18.2",
88
100
  "@earendil-works/pi-ai": "0.85.1",
89
101
  "@types/node": "22.20.0",