@sagmans/dsh-provider-extra 0.8.0 → 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.
@@ -12,17 +12,37 @@ const COMMAND_SERVICE = 'commandUi';
12
12
  const MODEL_SERVICE = 'modelDirectories';
13
13
  const SESSION_SERVICE = 'sessions';
14
14
  const REMOTE_SERVICE = 'remote';
15
- const TIER_REMOTE_SERVICE = REMOTE_SERVICE + '.' + TIER_NAMESPACE;
15
+ const TIER_REMOTE_SERVICE = `${REMOTE_SERVICE}.${TIER_NAMESPACE}`;
16
16
  const UNAVAILABLE = 'Service tiers are unavailable for this model or session';
17
17
  const STALE_ROUTE = 'Model changed; reopen /service-tier before saving';
18
18
  const COMMAND_DESCRIPTION = 'Choose the current model’s shared service tier';
19
19
  const SEARCH_PLACEHOLDER = 'Search service tiers';
20
20
  const NO_RESULTS = 'No matching service tiers';
21
21
  const TIER_IDS = ['auto', 'default', 'priority'];
22
+ /** Sign-in transport lives beside the tier namespace; both are Web-only surfaces. */
23
+ export const AUTH_NAMESPACE = 'providerExtraAuth';
24
+ /** Its own contribution identity: the tier face already claims the package's `host` face. */
25
+ export const AUTH_PACKAGE = `${TIER_PACKAGE}/sign-in`;
26
+ const AUTH_REMOTE_SERVICE = `${REMOTE_SERVICE}.${AUTH_NAMESPACE}`;
27
+ /** The Models page keys provider cards by the adapter family's settings namespace. */
28
+ const PI_AI_SETTINGS_NS = 'llm-pi-ai';
29
+ /** Routes whose OAuth flow this surface offers today; add an id after proving its flow. */
30
+ const SIGN_IN_PROVIDERS = ['openai-codex'];
31
+ /** A restart begins a fresh attempt list; attempts stay addressable while this page polls it. */
32
+ const AUTH_POLL_MS = 400;
33
+ const AUTH_INVALID = 'Invalid sign-in data';
34
+ const AUTH_LIST_ERROR = 'Could not read sign-in state';
35
+ const AUTH_START_ERROR = 'Could not start sign-in';
36
+ const AUTH_POLL_ERROR = 'Sign-in stopped responding; close this panel and try again';
37
+ const AUTH_ANSWER_ERROR = 'Could not deliver that answer';
38
+ const AUTH_COPY_FAILED = 'Copy failed';
39
+ const AUTH_ANSWER_MAX = 8_192;
22
40
  /** Reject extra fields instead of forwarding accidental provider state. */
23
41
  function record(value, keys) {
24
- if (value === null || typeof value !== 'object' || Array.isArray(value)
25
- || Reflect.ownKeys(value).some(key => typeof key !== 'string' || !keys.includes(key)))
42
+ if (value === null ||
43
+ typeof value !== 'object' ||
44
+ Array.isArray(value) ||
45
+ Reflect.ownKeys(value).some((key) => typeof key !== 'string' || !keys.includes(key)))
26
46
  throw new TypeError(INVALID_WIRE);
27
47
  return value;
28
48
  }
@@ -36,7 +56,7 @@ export function parseTierIdentity(value) {
36
56
  export function parseTier(value) {
37
57
  if (value === undefined)
38
58
  return undefined;
39
- if (typeof value !== 'string' || !TIER_IDS.some(id => id === value))
59
+ if (typeof value !== 'string' || !TIER_IDS.some((id) => id === value))
40
60
  throw new TypeError(INVALID_WIRE);
41
61
  return value;
42
62
  }
@@ -45,14 +65,18 @@ export function parseTierView(value) {
45
65
  const input = record(value, ['choices', 'current']);
46
66
  if (!Array.isArray(input.choices))
47
67
  throw new TypeError(INVALID_WIRE);
48
- const choices = input.choices.map(value => {
68
+ const choices = input.choices.map((value) => {
49
69
  const choice = record(value, ['id', 'name', 'description']);
50
70
  const id = parseTier(choice.id);
51
71
  if (id === undefined)
52
72
  throw new TypeError(INVALID_WIRE);
53
- return { id, name: parseTierIdentity(choice.name), description: parseTierIdentity(choice.description) };
73
+ return {
74
+ id,
75
+ name: parseTierIdentity(choice.name),
76
+ description: parseTierIdentity(choice.description),
77
+ };
54
78
  });
55
- const ids = new Set(choices.map(choice => choice.id));
79
+ const ids = new Set(choices.map((choice) => choice.id));
56
80
  if (ids.size !== choices.length)
57
81
  throw new TypeError(INVALID_WIRE);
58
82
  const current = parseTier(input.current);
@@ -70,9 +94,9 @@ function parseVoid(value) {
70
94
  function strict(typeSymbol, parse) {
71
95
  return { mode: 'strict', typeSymbol, create: () => ({ parse }), decode: parse };
72
96
  }
73
- const IDENTITY_CODEC = strict(TIER_PACKAGE + '.TierIdentity', parseTierIdentity);
74
- const TIER_CODEC = strict(TIER_PACKAGE + '.TierSelection', parseTier);
75
- const VIEW_CODEC = strict(TIER_PACKAGE + '.TierView', parseTierView);
97
+ const IDENTITY_CODEC = strict(`${TIER_PACKAGE}.TierIdentity`, parseTierIdentity);
98
+ const TIER_CODEC = strict(`${TIER_PACKAGE}.TierSelection`, parseTier);
99
+ const VIEW_CODEC = strict(`${TIER_PACKAGE}.TierView`, parseTierView);
76
100
  const VOID_CODEC = strict('void', parseVoid);
77
101
  const ROUTE_PARAMETERS = [
78
102
  { name: 'provider', wire: 'provider', source: 'json', codec: IDENTITY_CODEC },
@@ -82,12 +106,231 @@ const ROUTE_PARAMETERS = [
82
106
  export const TIER_CONTRIBUTION = {
83
107
  package: TIER_PACKAGE,
84
108
  descriptors: [
85
- { id: TIER_NAMESPACE + '/describe', service: TIER_NAMESPACE, namespace: TIER_NAMESPACE, method: 'describe',
86
- invocation: { kind: 'direct' }, parameters: ROUTE_PARAMETERS, cancellation: { parameter: 'signal' }, result: VIEW_CODEC },
87
- { id: TIER_NAMESPACE + '/select', service: TIER_NAMESPACE, namespace: TIER_NAMESPACE, method: 'select',
88
- invocation: { kind: 'direct' }, parameters: [...ROUTE_PARAMETERS,
89
- { name: 'tier', wire: 'tier', source: 'json', acceptsUndefined: true, codec: TIER_CODEC }],
90
- cancellation: { parameter: 'signal' }, result: VOID_CODEC },
109
+ {
110
+ id: `${TIER_NAMESPACE}/describe`,
111
+ service: TIER_NAMESPACE,
112
+ namespace: TIER_NAMESPACE,
113
+ method: 'describe',
114
+ invocation: { kind: 'direct' },
115
+ parameters: ROUTE_PARAMETERS,
116
+ cancellation: { parameter: 'signal' },
117
+ result: VIEW_CODEC,
118
+ },
119
+ {
120
+ id: `${TIER_NAMESPACE}/select`,
121
+ service: TIER_NAMESPACE,
122
+ namespace: TIER_NAMESPACE,
123
+ method: 'select',
124
+ invocation: { kind: 'direct' },
125
+ parameters: [
126
+ ...ROUTE_PARAMETERS,
127
+ { name: 'tier', wire: 'tier', source: 'json', acceptsUndefined: true, codec: TIER_CODEC },
128
+ ],
129
+ cancellation: { parameter: 'signal' },
130
+ result: VOID_CODEC,
131
+ },
132
+ ],
133
+ };
134
+ /** Empty or non-text values cannot address an attempt, prompt, or flow. */
135
+ function parseAuthText(value) {
136
+ if (typeof value !== 'string' || value.length === 0)
137
+ throw new TypeError(AUTH_INVALID);
138
+ return value;
139
+ }
140
+ /** Cursors are non-negative frame counts; a fractional or negative one is a bug, not a resume point. */
141
+ function parseAuthCursor(value) {
142
+ if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < 0)
143
+ throw new TypeError(AUTH_INVALID);
144
+ return value;
145
+ }
146
+ /** Booleans cross as booleans; a JSON 0/1 would hide a version skew. */
147
+ function parseAuthBoolean(value) {
148
+ if (typeof value !== 'boolean')
149
+ throw new TypeError(AUTH_INVALID);
150
+ return value;
151
+ }
152
+ /** One notice, with only the fields its frame declares. */
153
+ function parseAuthNotice(value) {
154
+ const input = record(value, ['message', 'url', 'code']);
155
+ return {
156
+ message: parseAuthText(input.message),
157
+ ...(input.url === undefined ? {} : { url: parseAuthText(input.url) }),
158
+ ...(input.code === undefined ? {} : { code: parseAuthText(input.code) }),
159
+ };
160
+ }
161
+ /** One option; the description is display-only context. */
162
+ function parseAuthOption(value) {
163
+ const input = record(value, ['id', 'label', 'description']);
164
+ return {
165
+ id: parseAuthText(input.id),
166
+ label: parseAuthText(input.label),
167
+ ...(input.description === undefined ? {} : { description: parseAuthText(input.description) }),
168
+ };
169
+ }
170
+ /** One prompt; a select must carry choices and the others must not. */
171
+ function parseAuthPrompt(value) {
172
+ const input = record(value, ['promptId', 'kind', 'message', 'placeholder', 'options']);
173
+ const kind = input.kind;
174
+ if (kind !== 'text' && kind !== 'secret' && kind !== 'select')
175
+ throw new TypeError(AUTH_INVALID);
176
+ const base = {
177
+ promptId: parseAuthText(input.promptId),
178
+ kind,
179
+ message: parseAuthText(input.message),
180
+ ...(input.placeholder === undefined ? {} : { placeholder: parseAuthText(input.placeholder) }),
181
+ };
182
+ if (kind !== 'select') {
183
+ if (input.options !== undefined)
184
+ throw new TypeError(AUTH_INVALID);
185
+ return base;
186
+ }
187
+ if (!Array.isArray(input.options) || input.options.length === 0)
188
+ throw new TypeError(AUTH_INVALID);
189
+ return { ...base, options: input.options.map(parseAuthOption) };
190
+ }
191
+ /** One frame; the tag decides which members must be present. */
192
+ function parseAuthEvent(value) {
193
+ const tagged = value !== null && typeof value === 'object' && !Array.isArray(value);
194
+ if (!tagged || !('type' in value))
195
+ throw new TypeError(AUTH_INVALID);
196
+ switch (value.type) {
197
+ case 'notice': {
198
+ const input = record(value, ['type', 'notice']);
199
+ return { type: 'notice', notice: parseAuthNotice(input.notice) };
200
+ }
201
+ case 'prompt': {
202
+ const input = record(value, ['type', 'prompt']);
203
+ return { type: 'prompt', prompt: parseAuthPrompt(input.prompt) };
204
+ }
205
+ case 'prompt-closed': {
206
+ const input = record(value, ['type', 'promptId']);
207
+ return { type: 'prompt-closed', promptId: parseAuthText(input.promptId) };
208
+ }
209
+ case 'settled': {
210
+ const input = record(value, ['type', 'status', 'message']);
211
+ const status = input.status;
212
+ if (status !== 'authorized' && status !== 'cancelled' && status !== 'failed')
213
+ throw new TypeError(AUTH_INVALID);
214
+ return {
215
+ type: 'settled',
216
+ status,
217
+ ...(input.message === undefined ? {} : { message: parseAuthText(input.message) }),
218
+ };
219
+ }
220
+ default:
221
+ throw new TypeError(AUTH_INVALID);
222
+ }
223
+ }
224
+ /** One flow list; a duplicated key would render two controls for one credential. */
225
+ function parseAuthEntries(value) {
226
+ if (!Array.isArray(value))
227
+ throw new TypeError(AUTH_INVALID);
228
+ const entries = value.map((item) => {
229
+ const input = record(item, ['key', 'provider', 'label', 'stored', 'inFlight']);
230
+ return {
231
+ key: parseAuthText(input.key),
232
+ provider: parseAuthText(input.provider),
233
+ label: parseAuthText(input.label),
234
+ stored: parseAuthBoolean(input.stored),
235
+ inFlight: parseAuthBoolean(input.inFlight),
236
+ };
237
+ });
238
+ if (new Set(entries.map((entry) => entry.key)).size !== entries.length)
239
+ throw new TypeError(AUTH_INVALID);
240
+ return entries;
241
+ }
242
+ /** One start result. */
243
+ function parseAuthStart(value) {
244
+ const input = record(value, ['attemptId']);
245
+ return { attemptId: parseAuthText(input.attemptId) };
246
+ }
247
+ /** One poll result; `done` without the settlement frame would strand the panel. */
248
+ function parseAuthPoll(value) {
249
+ const input = record(value, ['cursor', 'events', 'done']);
250
+ if (!Array.isArray(input.events))
251
+ throw new TypeError(AUTH_INVALID);
252
+ const events = input.events.map(parseAuthEvent);
253
+ const done = parseAuthBoolean(input.done);
254
+ if (done && events.at(-1)?.type !== 'settled')
255
+ throw new TypeError(AUTH_INVALID);
256
+ return { cursor: parseAuthCursor(input.cursor), events, done };
257
+ }
258
+ const AUTH_TEXT_CODEC = strict(`${AUTH_PACKAGE}.AuthText`, parseAuthText);
259
+ const AUTH_CURSOR_CODEC = strict(`${AUTH_PACKAGE}.AuthCursor`, parseAuthCursor);
260
+ const AUTH_BOOLEAN_CODEC = strict(`${AUTH_PACKAGE}.AuthBoolean`, parseAuthBoolean);
261
+ const AUTH_ENTRIES_CODEC = strict(`${AUTH_PACKAGE}.AuthEntries`, parseAuthEntries);
262
+ const AUTH_START_CODEC = strict(`${AUTH_PACKAGE}.AuthStart`, parseAuthStart);
263
+ const AUTH_POLL_CODEC = strict(`${AUTH_PACKAGE}.AuthPoll`, parseAuthPoll);
264
+ /** The attempt transport is poll-based so the Host needs no stream descriptor. */
265
+ export const AUTH_CONTRIBUTION = {
266
+ package: AUTH_PACKAGE,
267
+ descriptors: [
268
+ {
269
+ id: `${AUTH_NAMESPACE}/list`,
270
+ service: AUTH_NAMESPACE,
271
+ namespace: AUTH_NAMESPACE,
272
+ method: 'list',
273
+ invocation: { kind: 'direct' },
274
+ parameters: [],
275
+ result: AUTH_ENTRIES_CODEC,
276
+ },
277
+ {
278
+ id: `${AUTH_NAMESPACE}/begin`,
279
+ service: AUTH_NAMESPACE,
280
+ namespace: AUTH_NAMESPACE,
281
+ method: 'begin',
282
+ invocation: { kind: 'direct' },
283
+ parameters: [{ name: 'key', wire: 'key', source: 'json', codec: AUTH_TEXT_CODEC }],
284
+ result: AUTH_START_CODEC,
285
+ },
286
+ {
287
+ id: `${AUTH_NAMESPACE}/poll`,
288
+ service: AUTH_NAMESPACE,
289
+ namespace: AUTH_NAMESPACE,
290
+ method: 'poll',
291
+ invocation: { kind: 'direct' },
292
+ parameters: [
293
+ { name: 'attemptId', wire: 'attemptId', source: 'json', codec: AUTH_TEXT_CODEC },
294
+ { name: 'cursor', wire: 'cursor', source: 'json', codec: AUTH_CURSOR_CODEC },
295
+ ],
296
+ result: AUTH_POLL_CODEC,
297
+ },
298
+ {
299
+ id: `${AUTH_NAMESPACE}/answer`,
300
+ service: AUTH_NAMESPACE,
301
+ namespace: AUTH_NAMESPACE,
302
+ method: 'answer',
303
+ invocation: { kind: 'direct' },
304
+ parameters: [
305
+ { name: 'attemptId', wire: 'attemptId', source: 'json', codec: AUTH_TEXT_CODEC },
306
+ { name: 'promptId', wire: 'promptId', source: 'json', codec: AUTH_TEXT_CODEC },
307
+ { name: 'value', wire: 'value', source: 'json', codec: AUTH_TEXT_CODEC },
308
+ ],
309
+ result: AUTH_BOOLEAN_CODEC,
310
+ },
311
+ {
312
+ id: `${AUTH_NAMESPACE}/decline`,
313
+ service: AUTH_NAMESPACE,
314
+ namespace: AUTH_NAMESPACE,
315
+ method: 'decline',
316
+ invocation: { kind: 'direct' },
317
+ parameters: [
318
+ { name: 'attemptId', wire: 'attemptId', source: 'json', codec: AUTH_TEXT_CODEC },
319
+ { name: 'promptId', wire: 'promptId', source: 'json', codec: AUTH_TEXT_CODEC },
320
+ ],
321
+ result: AUTH_BOOLEAN_CODEC,
322
+ },
323
+ {
324
+ id: `${AUTH_NAMESPACE}/cancel`,
325
+ service: AUTH_NAMESPACE,
326
+ namespace: AUTH_NAMESPACE,
327
+ method: 'cancel',
328
+ invocation: { kind: 'direct' },
329
+ parameters: [
330
+ { name: 'attemptId', wire: 'attemptId', source: 'json', codec: AUTH_TEXT_CODEC },
331
+ ],
332
+ result: VOID_CODEC,
333
+ },
91
334
  ],
92
335
  };
93
336
  /** Remote failures contain transport detail that must not become UI error text. */
@@ -97,9 +340,605 @@ function resultValue(result, message) {
97
340
  const envelope = record(result, ['ok', 'value']);
98
341
  return envelope.value;
99
342
  }
100
- /** Optional injection keeps older hosts inert and scopes command ownership to HMR lifetime. */
343
+ /** Open the menu for the session's current route; any route change after this cancels its rows. */
344
+ async function openTierMenu(menu, session, requestSignal) {
345
+ const opening = new AbortController();
346
+ const signal = AbortSignal.any([requestSignal, menu.lifetime, menu.registered, opening.signal]);
347
+ signal.throwIfAborted();
348
+ if (!menu.available(session))
349
+ return [];
350
+ const directory = menu.models.directoryFor(session.sessionId);
351
+ const current = directory.store.getSnapshot().current;
352
+ // The menu has nothing to offer until the session has chosen a model.
353
+ if (!current)
354
+ return [];
355
+ const provider = parseTierIdentity(current.provider);
356
+ const model = parseTierIdentity(current.model);
357
+ const invalidate = () => {
358
+ const latest = directory.store.getSnapshot().current;
359
+ try {
360
+ if (menu.available(session) &&
361
+ menu.models.directoryFor(session.sessionId) === directory &&
362
+ latest?.provider === provider &&
363
+ latest.model === model)
364
+ return;
365
+ }
366
+ catch {
367
+ /* A removed session scope must not retain permission to write. */
368
+ }
369
+ opening.abort(new Error(STALE_ROUTE));
370
+ };
371
+ const checkRoute = () => {
372
+ invalidate();
373
+ signal.throwIfAborted();
374
+ };
375
+ // A route that changes away and back still invalidates the original billing decision.
376
+ const unsubscribe = directory.store.subscribe(invalidate);
377
+ signal.addEventListener('abort', unsubscribe, { once: true });
378
+ let view;
379
+ try {
380
+ await directory.load();
381
+ checkRoute();
382
+ view = parseTierView(resultValue(await menu.tiers.describe(provider, model, signal), READ_ERROR));
383
+ checkRoute();
384
+ }
385
+ catch {
386
+ const error = signal.aborted ? signal.reason : new Error(READ_ERROR);
387
+ opening.abort();
388
+ throw error;
389
+ }
390
+ if (view.choices.length === 0) {
391
+ opening.abort();
392
+ return [];
393
+ }
394
+ const options = [
395
+ { id: TIER_DEFAULT, label: DEFAULT_LABEL, active: view.current === undefined },
396
+ ...view.choices.map((choice) => ({
397
+ id: choice.id,
398
+ label: choice.name,
399
+ detail: choice.description,
400
+ active: view.current === choice.id,
401
+ })),
402
+ ];
403
+ for (const option of options) {
404
+ const tier = option.id === TIER_DEFAULT ? undefined : option.id;
405
+ menu.selections.set(option, {
406
+ sessionId: session.sessionId,
407
+ async select() {
408
+ checkRoute();
409
+ try {
410
+ parseVoid(resultValue(await menu.tiers.select(provider, model, tier, signal), TIER_SAVE_ERROR));
411
+ }
412
+ catch {
413
+ signal.throwIfAborted();
414
+ throw new Error(TIER_SAVE_ERROR);
415
+ }
416
+ checkRoute();
417
+ // The stock shell does not abort its signal on successful selection.
418
+ opening.abort();
419
+ },
420
+ });
421
+ }
422
+ return options;
423
+ }
424
+ /** Resolve React only when the browser half runs; the Host bundle has no React. */
425
+ function reactRuntime() {
426
+ return require('react');
427
+ }
428
+ /** Only a keyless OAuth route gets a sign-in control; a key field already covers the rest. */
429
+ function signInEligible(props) {
430
+ const entry = props.provider;
431
+ return (entry !== undefined &&
432
+ SIGN_IN_PROVIDERS.includes(entry.provider) &&
433
+ entry.nativeAuth?.oauth === true &&
434
+ (entry.nativeAuth.env?.length ?? 0) === 0);
435
+ }
436
+ /** Keep transport detail out of the panel while still naming what failed. */
437
+ function authFailure(error) {
438
+ if (error instanceof Error && error.message.length > 0)
439
+ return error.message;
440
+ return AUTH_POLL_ERROR;
441
+ }
442
+ const AUTH_STYLES = {
443
+ wrap: { display: 'flex', flexDirection: 'column', gap: '8px', marginTop: '8px' },
444
+ row: { display: 'flex', flexWrap: 'wrap', alignItems: 'center', gap: '8px' },
445
+ button: {
446
+ alignSelf: 'flex-start',
447
+ border: '1px solid var(--dsh-border, #555)',
448
+ borderRadius: '6px',
449
+ background: 'transparent',
450
+ color: 'inherit',
451
+ cursor: 'pointer',
452
+ font: 'inherit',
453
+ padding: '4px 12px',
454
+ },
455
+ primary: {
456
+ alignSelf: 'flex-start',
457
+ border: '1px solid transparent',
458
+ borderRadius: '6px',
459
+ background: 'var(--dsh-accent, #3b82f6)',
460
+ color: 'var(--dsh-accent-foreground, #ffffff)',
461
+ cursor: 'pointer',
462
+ font: 'inherit',
463
+ padding: '4px 12px',
464
+ },
465
+ hint: { opacity: 0.7, fontSize: '0.9em' },
466
+ notice: { margin: 0 },
467
+ error: { color: '#e5484d', margin: 0 },
468
+ field: { display: 'flex', flexDirection: 'column', gap: '6px' },
469
+ input: {
470
+ border: '1px solid currentColor',
471
+ borderRadius: '6px',
472
+ background: 'transparent',
473
+ color: 'inherit',
474
+ font: 'inherit',
475
+ padding: '4px 8px',
476
+ width: '100%',
477
+ },
478
+ link: { color: 'inherit', textDecoration: 'underline', cursor: 'pointer' },
479
+ };
480
+ /** Clipboard access can fail without permission; the label reports which happened. */
481
+ async function copyToClipboard(value) {
482
+ try {
483
+ await navigator.clipboard.writeText(value);
484
+ return 'copied';
485
+ }
486
+ catch {
487
+ return 'failed';
488
+ }
489
+ }
490
+ /** Read and validate the flow list; an unavailable Host reads as no flows. */
491
+ async function readAuthEntries(auth) {
492
+ return parseAuthEntries(resultValue(await auth.list(), AUTH_LIST_ERROR));
493
+ }
494
+ /** Start one attempt and return the handle its poller uses. */
495
+ async function beginAttempt(auth, key) {
496
+ return parseAuthStart(resultValue(await auth.begin(key), AUTH_START_ERROR)).attemptId;
497
+ }
498
+ /** Poll one attempt until it settles or the panel closes. */
499
+ async function pollAttempt(target) {
500
+ let cursor = 0;
501
+ while (target.live()) {
502
+ const poll = parseAuthPoll(resultValue(await target.auth.poll(target.attemptId, cursor), AUTH_POLL_ERROR));
503
+ cursor = poll.cursor;
504
+ for (const event of poll.events)
505
+ target.apply(event);
506
+ if (poll.done)
507
+ return;
508
+ await new Promise((resolve) => {
509
+ setTimeout(resolve, AUTH_POLL_MS);
510
+ });
511
+ }
512
+ }
513
+ /** One notice, with only the actions its own fields warrant. */
514
+ function SignInNotice(props) {
515
+ const { createElement: h } = reactRuntime();
516
+ const { notice } = props;
517
+ return h('div', { style: AUTH_STYLES.field }, [
518
+ h('p', { key: 'message', style: AUTH_STYLES.notice }, notice.message),
519
+ notice.url === undefined
520
+ ? null
521
+ : h('div', { key: 'url', style: AUTH_STYLES.row }, [
522
+ h('a', {
523
+ key: 'open',
524
+ href: notice.url,
525
+ target: '_blank',
526
+ rel: 'noreferrer noopener',
527
+ style: AUTH_STYLES.link,
528
+ }, 'Open sign-in page'),
529
+ h('button', {
530
+ key: 'copy',
531
+ type: 'button',
532
+ style: AUTH_STYLES.button,
533
+ onClick: () => {
534
+ props.onCopy(notice.url ?? '');
535
+ },
536
+ }, props.copy === 'copied'
537
+ ? 'Copied'
538
+ : props.copy === 'failed'
539
+ ? AUTH_COPY_FAILED
540
+ : 'Copy link'),
541
+ ]),
542
+ notice.code === undefined
543
+ ? null
544
+ : h('p', { key: 'code', style: AUTH_STYLES.notice }, `Verification code: ${notice.code}`),
545
+ ]);
546
+ }
547
+ /** One question: choices are buttons, typed answers are an input. */
548
+ function SignInPrompt(props) {
549
+ const { createElement: h } = reactRuntime();
550
+ const { prompt, busy } = props;
551
+ const choices = prompt.kind === 'select'
552
+ ? h('div', { key: 'options', style: AUTH_STYLES.row }, (prompt.options ?? []).map((option) => h('button', {
553
+ key: option.id,
554
+ type: 'button',
555
+ disabled: busy,
556
+ style: AUTH_STYLES.button,
557
+ onClick: () => {
558
+ props.onSubmit(option.id);
559
+ },
560
+ }, option.label)))
561
+ : h('div', { key: 'typed', style: AUTH_STYLES.field }, [
562
+ h('input', {
563
+ key: 'input',
564
+ type: prompt.kind === 'secret' ? 'password' : 'text',
565
+ value: props.answer,
566
+ maxLength: AUTH_ANSWER_MAX,
567
+ placeholder: prompt.placeholder ?? '',
568
+ 'aria-label': prompt.message,
569
+ disabled: busy,
570
+ style: AUTH_STYLES.input,
571
+ onChange: (event) => {
572
+ props.onAnswer(event.target.value);
573
+ },
574
+ onKeyDown: (event) => {
575
+ if (event.key === 'Enter')
576
+ props.onSubmit(props.answer);
577
+ },
578
+ }),
579
+ h('div', { key: 'actions', style: AUTH_STYLES.row }, [
580
+ h('button', {
581
+ key: 'continue',
582
+ type: 'button',
583
+ disabled: busy || props.answer.trim() === '',
584
+ style: AUTH_STYLES.primary,
585
+ onClick: () => {
586
+ props.onSubmit(props.answer);
587
+ },
588
+ }, 'Continue'),
589
+ h('button', {
590
+ key: 'decline',
591
+ type: 'button',
592
+ disabled: busy,
593
+ style: AUTH_STYLES.button,
594
+ onClick: props.onDecline,
595
+ }, 'Decline'),
596
+ ]),
597
+ ]);
598
+ return h('div', { style: AUTH_STYLES.field }, [
599
+ h('p', { key: 'message', style: AUTH_STYLES.notice }, prompt.message),
600
+ choices,
601
+ ]);
602
+ }
603
+ /** The opened panel: instructions, the current question, and the exit. */
604
+ function SignInPanel(props) {
605
+ const { createElement: h } = reactRuntime();
606
+ const running = props.status === 'running';
607
+ const outcome = props.status === 'authorized'
608
+ ? h('p', { key: 'ok', style: AUTH_STYLES.notice }, 'Signed in. No API key was stored.')
609
+ : props.status === 'cancelled'
610
+ ? h('p', { key: 'cancelled', style: AUTH_STYLES.notice }, 'Sign-in was cancelled.')
611
+ : null;
612
+ return h('div', { style: AUTH_STYLES.field }, [
613
+ props.failure === undefined
614
+ ? null
615
+ : h('p', { key: 'failure', style: AUTH_STYLES.error }, props.failure),
616
+ props.notice === undefined
617
+ ? null
618
+ : h(SignInNotice, {
619
+ key: 'notice',
620
+ notice: props.notice,
621
+ copy: props.copy,
622
+ onCopy: props.onCopy,
623
+ }),
624
+ props.prompt === undefined
625
+ ? null
626
+ : h(SignInPrompt, {
627
+ key: 'prompt',
628
+ prompt: props.prompt,
629
+ answer: props.answer,
630
+ busy: props.busy,
631
+ onAnswer: props.onAnswer,
632
+ onSubmit: props.onSubmit,
633
+ onDecline: props.onDecline,
634
+ }),
635
+ running
636
+ ? h('p', { key: 'waiting', style: AUTH_STYLES.hint }, 'Waiting for the provider…')
637
+ : null,
638
+ outcome,
639
+ h('button', { key: 'close', type: 'button', style: AUTH_STYLES.button, onClick: props.onClose }, running ? 'Cancel' : 'Close'),
640
+ ]);
641
+ }
642
+ /** Poll one attempt for as long as the panel is open, reporting failures as a settlement. */
643
+ function useAttemptPolling(auth, attemptId, apply, onFailure) {
644
+ const { useEffect, useRef } = reactRuntime();
645
+ // The callbacks are fresh each render; only the attempt identity may restart
646
+ // the poller, or every frame would replay from cursor zero.
647
+ const sink = useRef(apply);
648
+ sink.current = apply;
649
+ const fail = useRef(onFailure);
650
+ fail.current = onFailure;
651
+ useEffect(() => {
652
+ if (attemptId === undefined)
653
+ return;
654
+ let polling = true;
655
+ void pollAttempt({
656
+ auth,
657
+ attemptId,
658
+ apply: (event) => {
659
+ sink.current(event);
660
+ },
661
+ live: () => polling,
662
+ }).catch((error) => {
663
+ if (polling)
664
+ fail.current(authFailure(error));
665
+ });
666
+ return () => {
667
+ polling = false;
668
+ };
669
+ }, [attemptId, auth]);
670
+ }
671
+ /** Deliver one typed answer; the refusal message is ready for the panel. */
672
+ async function submitAnswer(auth, attemptId, prompt, value) {
673
+ const accepted = parseAuthBoolean(resultValue(await auth.answer(attemptId, prompt.promptId, value), AUTH_ANSWER_ERROR));
674
+ return accepted ? undefined : AUTH_ANSWER_ERROR;
675
+ }
676
+ /** Refuse one question; a transport failure is reported to the caller. */
677
+ async function declineQuestion(auth, attemptId, prompt) {
678
+ await auth.decline(attemptId, prompt.promptId);
679
+ }
680
+ /** The card: a stored-grant summary and the panel an open attempt shows. */
681
+ function ProviderSignInView(props) {
682
+ const { createElement: h } = reactRuntime();
683
+ const stored = props.entry?.stored === true;
684
+ const state = props.entry === undefined
685
+ ? (props.failure ?? 'No sign-in flow is registered for this provider')
686
+ : stored
687
+ ? 'Signed in'
688
+ : 'Sign in with the provider account';
689
+ return h('div', { style: AUTH_STYLES.wrap }, [
690
+ h('div', { key: 'head', style: AUTH_STYLES.row }, [
691
+ h('button', {
692
+ key: 'button',
693
+ type: 'button',
694
+ disabled: props.entry === undefined || props.busy || props.status === 'running',
695
+ onClick: props.onStart,
696
+ style: stored ? AUTH_STYLES.button : AUTH_STYLES.primary,
697
+ }, props.entry === undefined ? 'Sign-in unavailable' : stored ? 'Sign in again' : 'Sign in'),
698
+ h('span', { key: 'state', style: AUTH_STYLES.hint }, state),
699
+ ]),
700
+ props.open
701
+ ? h(SignInPanel, {
702
+ key: 'panel',
703
+ notice: props.notice,
704
+ prompt: props.prompt,
705
+ status: props.status,
706
+ failure: props.failure,
707
+ answer: props.answer,
708
+ busy: props.busy,
709
+ copy: props.copy,
710
+ onAnswer: props.onAnswer,
711
+ onSubmit: props.onSubmit,
712
+ onDecline: props.onDecline,
713
+ onCopy: props.onCopy,
714
+ onClose: props.onClose,
715
+ })
716
+ : null,
717
+ ]);
718
+ }
719
+ /** Load the flow list once per provider and report a failed read. */
720
+ function useFlowEntries(auth, reload, onFailure) {
721
+ const { useEffect, useRef, useState } = reactRuntime();
722
+ const [entries, setEntries] = useState(undefined);
723
+ const fail = useRef(onFailure);
724
+ fail.current = onFailure;
725
+ useEffect(() => {
726
+ let current = true;
727
+ void readAuthEntries(auth).then((list) => {
728
+ if (current)
729
+ setEntries(list);
730
+ }, (error) => {
731
+ if (!current)
732
+ return;
733
+ setEntries([]);
734
+ fail.current(authFailure(error));
735
+ });
736
+ return () => {
737
+ current = false;
738
+ };
739
+ }, [auth, reload]);
740
+ return entries;
741
+ }
742
+ /** Copy feedback, reset after the label has been read. */
743
+ function useCopyFeedback() {
744
+ const { useEffect, useState } = reactRuntime();
745
+ const [copy, setCopy] = useState(undefined);
746
+ useEffect(() => {
747
+ if (copy === undefined)
748
+ return;
749
+ const timer = setTimeout(() => {
750
+ setCopy(undefined);
751
+ }, 2000);
752
+ return () => {
753
+ clearTimeout(timer);
754
+ };
755
+ }, [copy]);
756
+ return {
757
+ copy,
758
+ copyValue: (value) => {
759
+ void copyToClipboard(value).then(setCopy);
760
+ },
761
+ };
762
+ }
763
+ /** Withdraw whatever attempt is still running when the card unmounts. */
764
+ function useCancelOnUnmount(auth, running) {
765
+ const { useEffect, useRef } = reactRuntime();
766
+ const live = useRef(undefined);
767
+ live.current = running;
768
+ useEffect(() => {
769
+ return () => {
770
+ const attempt = live.current;
771
+ if (attempt !== undefined)
772
+ void auth.cancel(attempt);
773
+ };
774
+ }, [auth]);
775
+ }
776
+ const EMPTY_FLOW = { open: false, answer: '', busy: false };
777
+ /** Keep one attempt's visible state in one place, so no handler clears it halfway. */
778
+ function reduceFlow(state, action) {
779
+ switch (action.type) {
780
+ case 'open':
781
+ return {
782
+ ...EMPTY_FLOW,
783
+ open: true,
784
+ busy: true,
785
+ status: 'running',
786
+ };
787
+ case 'busy':
788
+ return { ...state, busy: action.busy };
789
+ case 'started':
790
+ return { ...state, busy: false, attemptId: action.attemptId };
791
+ case 'failed':
792
+ return { ...state, busy: false, status: 'failed', failure: action.message };
793
+ case 'notice':
794
+ return { ...state, notice: action.notice };
795
+ case 'prompt':
796
+ return { ...state, prompt: action.prompt, answer: '' };
797
+ case 'prompt-closed':
798
+ return state.prompt?.promptId === action.promptId ? { ...state, prompt: undefined } : state;
799
+ case 'answer':
800
+ return { ...state, answer: action.value };
801
+ case 'settled':
802
+ return {
803
+ ...state,
804
+ prompt: undefined,
805
+ status: action.status,
806
+ ...(action.status === 'failed' ? { failure: action.message ?? 'Sign-in failed.' } : {}),
807
+ };
808
+ case 'close':
809
+ return EMPTY_FLOW;
810
+ }
811
+ }
812
+ /** Map one polled frame onto its transition. */
813
+ function flowAction(event) {
814
+ if (event.type === 'notice')
815
+ return { type: 'notice', notice: event.notice };
816
+ if (event.type === 'prompt')
817
+ return { type: 'prompt', prompt: event.prompt };
818
+ if (event.type === 'prompt-closed')
819
+ return { type: 'prompt-closed', promptId: event.promptId };
820
+ return {
821
+ type: 'settled',
822
+ status: event.status,
823
+ ...(event.message === undefined ? {} : { message: event.message }),
824
+ };
825
+ }
826
+ /** The clickable face of one provider's stored grant and running attempt. */
827
+ function ProviderSignInCard(props) {
828
+ const { createElement: h, useReducer, useState } = reactRuntime();
829
+ const [ui, dispatch] = useReducer(reduceFlow, EMPTY_FLOW);
830
+ const [reload, setReload] = useState(0);
831
+ const fail = (message) => {
832
+ dispatch({ type: 'failed', message });
833
+ };
834
+ const entries = useFlowEntries(props.auth, reload, fail);
835
+ const entry = entries?.find((candidate) => candidate.provider === props.provider.provider);
836
+ const { copy, copyValue } = useCopyFeedback();
837
+ useCancelOnUnmount(props.auth, ui.status === 'running' ? ui.attemptId : undefined);
838
+ const apply = (event) => {
839
+ dispatch(flowAction(event));
840
+ if (event.type === 'settled' && event.status === 'authorized')
841
+ setReload((value) => value + 1);
842
+ };
843
+ useAttemptPolling(props.auth, ui.attemptId, apply, (message) => {
844
+ dispatch({ type: 'failed', message });
845
+ });
846
+ const start = async () => {
847
+ if (entry === undefined || ui.busy)
848
+ return;
849
+ dispatch({ type: 'open' });
850
+ try {
851
+ dispatch({ type: 'started', attemptId: await beginAttempt(props.auth, entry.key) });
852
+ }
853
+ catch (error) {
854
+ dispatch({ type: 'failed', message: authFailure(error) });
855
+ }
856
+ };
857
+ const close = () => {
858
+ if (ui.status === 'running' && ui.attemptId !== undefined)
859
+ void props.auth.cancel(ui.attemptId);
860
+ dispatch({ type: 'close' });
861
+ };
862
+ const submit = async (value) => {
863
+ const { prompt, attemptId } = ui;
864
+ if (prompt === undefined || attemptId === undefined || ui.busy || value.trim() === '')
865
+ return;
866
+ dispatch({ type: 'busy', busy: true });
867
+ try {
868
+ const refusal = await submitAnswer(props.auth, attemptId, prompt, value);
869
+ if (refusal === undefined) {
870
+ dispatch({ type: 'answer', value: '' });
871
+ dispatch({ type: 'prompt-closed', promptId: prompt.promptId });
872
+ }
873
+ else
874
+ dispatch({ type: 'failed', message: refusal });
875
+ }
876
+ catch (error) {
877
+ dispatch({ type: 'failed', message: authFailure(error) });
878
+ }
879
+ };
880
+ const decline = async () => {
881
+ const { prompt, attemptId } = ui;
882
+ if (prompt === undefined || attemptId === undefined || ui.busy)
883
+ return;
884
+ dispatch({ type: 'busy', busy: true });
885
+ try {
886
+ await declineQuestion(props.auth, attemptId, prompt);
887
+ dispatch({ type: 'prompt-closed', promptId: prompt.promptId });
888
+ }
889
+ catch (error) {
890
+ dispatch({ type: 'failed', message: authFailure(error) });
891
+ }
892
+ };
893
+ return h(ProviderSignInView, {
894
+ entry,
895
+ open: ui.open,
896
+ status: ui.status,
897
+ notice: ui.notice,
898
+ prompt: ui.prompt,
899
+ failure: ui.failure,
900
+ answer: ui.answer,
901
+ busy: ui.busy,
902
+ copy,
903
+ onStart: () => {
904
+ void start();
905
+ },
906
+ onAnswer: (value) => {
907
+ dispatch({ type: 'answer', value });
908
+ },
909
+ onSubmit: (value) => {
910
+ void submit(value);
911
+ },
912
+ onDecline: () => {
913
+ void decline();
914
+ },
915
+ onCopy: copyValue,
916
+ onClose: close,
917
+ });
918
+ }
919
+ /** Bind the card to one page's Remote namespace; eligibility runs before any hook. */
920
+ function createProviderSignIn(auth) {
921
+ return (props) => signInEligible(props)
922
+ ? reactRuntime().createElement(ProviderSignInCard, { ...props, auth })
923
+ : null;
924
+ }
925
+ /** Mount the attempt namespace and register the Models card extension. */
926
+ function applyProviderSignIn(ctx) {
927
+ ctx.inject([REMOTE_SERVICE], (owner) => {
928
+ const remote = owner.get(REMOTE_SERVICE);
929
+ owner.effect(async () => {
930
+ const unmount = await remote.$mount(AUTH_CONTRIBUTION);
931
+ owner.inject(['slots', AUTH_REMOTE_SERVICE], (scope) => {
932
+ const slots = scope.get('slots');
933
+ const auth = scope.get(AUTH_REMOTE_SERVICE);
934
+ slots.inject('settings.models.provider-card', () => slots.register({ name: 'settings.models.provider-card', key: PI_AI_SETTINGS_NS }, createProviderSignIn(auth)));
935
+ });
936
+ return unmount;
937
+ });
938
+ });
939
+ }
101
940
  export function apply(ctx) {
102
- ctx.inject([COMMAND_SERVICE, MODEL_SERVICE, SESSION_SERVICE, REMOTE_SERVICE], owner => {
941
+ ctx.inject([COMMAND_SERVICE, MODEL_SERVICE, SESSION_SERVICE, REMOTE_SERVICE], (owner) => {
103
942
  const command = owner.get(COMMAND_SERVICE);
104
943
  const models = owner.get(MODEL_SERVICE);
105
944
  const sessions = owner.get(SESSION_SERVICE);
@@ -112,17 +951,21 @@ export function apply(ctx) {
112
951
  const state = models.directoryFor(session.sessionId).store.getSnapshot();
113
952
  return state.current !== null && state.routable !== false;
114
953
  };
115
- owner.effect(() => () => { lifetime.abort(); });
954
+ owner.effect(() => () => {
955
+ lifetime.abort();
956
+ });
116
957
  owner.effect(async () => {
117
958
  const unmount = await remote.$mount(TIER_CONTRIBUTION);
118
959
  if (lifetime.signal.aborted)
119
960
  return unmount;
120
961
  try {
121
962
  // The dynamically mounted namespace needs its own declared Cordis dependency.
122
- const registration = owner.inject([TIER_REMOTE_SERVICE], scope => {
963
+ const registration = owner.inject([TIER_REMOTE_SERVICE], (scope) => {
123
964
  const tiers = scope.get(TIER_REMOTE_SERVICE);
124
965
  const registered = new AbortController();
125
- scope.effect(() => () => { registered.abort(); });
966
+ scope.effect(() => () => {
967
+ registered.abort();
968
+ });
126
969
  scope.effect(() => {
127
970
  const unregister = command.register({
128
971
  name: COMMAND_NAME,
@@ -131,72 +974,19 @@ export function apply(ctx) {
131
974
  available,
132
975
  ui: {
133
976
  kind: 'popupSelect',
134
- searchLabels: () => ({ placeholder: SEARCH_PLACEHOLDER, empty: UNAVAILABLE, noResults: NO_RESULTS }),
135
- async options(session, requestSignal) {
136
- const opening = new AbortController();
137
- const signal = AbortSignal.any([requestSignal, lifetime.signal, registered.signal, opening.signal]);
138
- signal.throwIfAborted();
139
- if (!available(session))
140
- return [];
141
- const directory = models.directoryFor(session.sessionId);
142
- const current = directory.store.getSnapshot().current;
143
- const provider = parseTierIdentity(current.provider);
144
- const model = parseTierIdentity(current.model);
145
- const invalidate = () => {
146
- const latest = directory.store.getSnapshot().current;
147
- try {
148
- if (available(session) && models.directoryFor(session.sessionId) === directory
149
- && latest?.provider === provider && latest.model === model)
150
- return;
151
- }
152
- catch { /* A removed session scope must not retain permission to write. */ }
153
- opening.abort(new Error(STALE_ROUTE));
154
- };
155
- const checkRoute = () => { invalidate(); signal.throwIfAborted(); };
156
- // A route that changes away and back still invalidates the original billing decision.
157
- const unsubscribe = directory.store.subscribe(invalidate);
158
- signal.addEventListener('abort', unsubscribe, { once: true });
159
- let view;
160
- try {
161
- await directory.load();
162
- checkRoute();
163
- view = parseTierView(resultValue(await tiers.describe(provider, model, signal), READ_ERROR));
164
- checkRoute();
165
- }
166
- catch {
167
- const error = signal.aborted ? signal.reason : new Error(READ_ERROR);
168
- opening.abort();
169
- throw error;
170
- }
171
- if (view.choices.length === 0) {
172
- opening.abort();
173
- return [];
174
- }
175
- const options = [
176
- { id: TIER_DEFAULT, label: DEFAULT_LABEL, active: view.current === undefined },
177
- ...view.choices.map(choice => ({ id: choice.id, label: choice.name, detail: choice.description, active: view.current === choice.id })),
178
- ];
179
- for (const option of options) {
180
- const tier = option.id === TIER_DEFAULT ? undefined : option.id;
181
- selections.set(option, {
182
- sessionId: session.sessionId,
183
- async select() {
184
- checkRoute();
185
- try {
186
- parseVoid(resultValue(await tiers.select(provider, model, tier, signal), TIER_SAVE_ERROR));
187
- }
188
- catch {
189
- signal.throwIfAborted();
190
- throw new Error(TIER_SAVE_ERROR);
191
- }
192
- checkRoute();
193
- // The stock shell does not abort its signal on successful selection.
194
- opening.abort();
195
- },
196
- });
197
- }
198
- return options;
199
- },
977
+ searchLabels: () => ({
978
+ placeholder: SEARCH_PLACEHOLDER,
979
+ empty: UNAVAILABLE,
980
+ noResults: NO_RESULTS,
981
+ }),
982
+ options: (session, requestSignal) => openTierMenu({
983
+ models,
984
+ tiers,
985
+ selections,
986
+ available,
987
+ lifetime: lifetime.signal,
988
+ registered: registered.signal,
989
+ }, session, requestSignal),
200
990
  async onSelect(option, session) {
201
991
  const selection = selections.get(option);
202
992
  if (selection === undefined || selection.sessionId !== session.sessionId)
@@ -205,11 +995,17 @@ export function apply(ctx) {
205
995
  },
206
996
  },
207
997
  });
208
- return () => { command.dismiss(COMMAND_NAME); unregister(); };
998
+ return () => {
999
+ command.dismiss(COMMAND_NAME);
1000
+ unregister();
1001
+ };
209
1002
  });
210
1003
  });
211
1004
  await registration;
212
- return async () => { await registration.dispose(); await unmount(); };
1005
+ return async () => {
1006
+ await registration.dispose();
1007
+ await unmount();
1008
+ };
213
1009
  }
214
1010
  catch (error) {
215
1011
  await unmount();
@@ -217,4 +1013,5 @@ export function apply(ctx) {
217
1013
  }
218
1014
  });
219
1015
  });
1016
+ applyProviderSignIn(ctx);
220
1017
  }