dsh-taskbridge 1.7.1 → 1.8.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.
Files changed (84) hide show
  1. package/CHANGELOG.md +24 -0
  2. package/LICENSE +21 -21
  3. package/README.md +733 -877
  4. package/THIRD_PARTY_NOTICES.txt +23 -23
  5. package/antigravity/agents/dsh-taskbridge.md +32 -0
  6. package/antigravity/skills/dsh-taskbridge/SKILL.md +51 -0
  7. package/codex/dsh-taskbridge.toml +181 -631
  8. package/cordis.patch.yml +6 -6
  9. package/docs/INTRODUCTION.md +122 -295
  10. package/docs/INTRODUCTION.zh.md +134 -279
  11. package/docs/antigravity-integration.md +42 -0
  12. package/docs/auth-contract.md +138 -138
  13. package/docs/claude-code.md +6 -11
  14. package/docs/codex-integration.md +2 -2
  15. package/docs/contracts-stage-b.md +443 -443
  16. package/docs/conversation-placement.md +7 -6
  17. package/docs/plugin-market.md +30 -30
  18. package/docs/redaction-contract.md +170 -170
  19. package/docs/releases/1.7.0.zh.md +11 -11
  20. package/docs/releases/1.8.0.zh.md +16 -0
  21. package/docs/releases/1.8.1.zh.md +24 -0
  22. package/docs/runtime-compatibility.md +1 -1
  23. package/docs/taskbridge-upgrade.md +28 -28
  24. package/docs/taskdispatch-upgrade.md +25 -25
  25. package/docs/workspace-contract.md +538 -538
  26. package/docs/workspace-grouping.md +126 -126
  27. package/icon.svg +1 -1
  28. package/lib/client.d.ts +804 -699
  29. package/lib/client.js +7 -7
  30. package/locale/en.json +1 -1
  31. package/locale/zh.json +1 -1
  32. package/package.json +150 -144
  33. package/src/antigravity/installer.js +1068 -0
  34. package/src/antigravity/seam.js +142 -0
  35. package/src/auth/fence.js +361 -361
  36. package/src/auth/grants.js +789 -789
  37. package/src/client/api.js +266 -3
  38. package/src/client/index.jsx +224 -11
  39. package/src/client/sidebar.jsx +862 -862
  40. package/src/client/styles.js +624 -624
  41. package/src/client/task-cleanup.js +429 -304
  42. package/src/client/task-records-table.jsx +217 -217
  43. package/src/client/task-view.js +307 -307
  44. package/src/client/workspace-groups.js +482 -482
  45. package/src/client/workspaces-browser.jsx +770 -770
  46. package/src/codex/agent-ownership.js +270 -270
  47. package/src/codex/installer.js +6 -0
  48. package/src/codex/toml.js +784 -784
  49. package/src/config/defaults.js +11 -15
  50. package/src/config/redact.js +245 -245
  51. package/src/config/store.js +186 -186
  52. package/src/credentials/seam.js +202 -202
  53. package/src/http/respond.js +6 -5
  54. package/src/http/user-plane.js +83 -1
  55. package/src/index.js +25 -0
  56. package/src/jobs/diagnostics.js +15 -15
  57. package/src/jobs/engine.js +1 -0
  58. package/src/jobs/history.js +1 -1
  59. package/src/jobs/plan-store.js +1103 -1020
  60. package/src/jobs/record-cleanup.js +452 -7
  61. package/src/jobs/review-note.js +63 -63
  62. package/src/jobs/task-descriptions.js +82 -82
  63. package/src/jobs/task-display.js +73 -73
  64. package/src/jobs/task-tree.js +786 -786
  65. package/src/jobs/title.js +134 -134
  66. package/src/mcp/continuation.js +317 -317
  67. package/src/mcp/server.js +34 -27
  68. package/src/mcp/wait.js +34 -15
  69. package/src/model/connectivity.js +371 -371
  70. package/src/model/discovery.js +582 -582
  71. package/src/model/native-catalog.js +68 -68
  72. package/src/model/openai-adapter.js +671 -671
  73. package/src/model/probe.js +264 -264
  74. package/src/model/providers.js +756 -756
  75. package/src/model/routing.js +321 -321
  76. package/src/runtime/agent-runner.js +1 -0
  77. package/src/runtime/permissions.js +1619 -1619
  78. package/src/runtime/question-call.js +162 -162
  79. package/src/runtime/questions.js +909 -909
  80. package/src/runtime/session-placement.js +36 -1
  81. package/src/runtime/worker-prompt.js +61 -55
  82. package/src/workspace/audit.js +775 -775
  83. package/src/workspace/preflight.js +424 -424
  84. package/src/workspace/worktrees.js +833 -679
@@ -1,582 +1,582 @@
1
- // Remote model discovery for one configured provider profile.
2
- //
3
- // This module answers exactly one question: *which model ids does this provider's
4
- // own API say it serves right now?* It is the only place in the plugin that talks
5
- // to a provider over HTTP on the operator's behalf outside a model call, and the
6
- // constraints below are what make that safe.
7
- //
8
- // What it is NOT:
9
- //
10
- // * not a capability authority. An `openai-chat` model list carries ids and
11
- // nothing this build trusts about reasoning support, so every discovered id
12
- // gets `efforts: []`. Guessing `high`/`max` from a model name, or forwarding an
13
- // arbitrary upstream `capabilities`/`reasoning` field, would turn an unverified
14
- // assumption into a routing decision the provider may reject at request time;
15
- // * not a native catalog. `/catalog` (`describeCatalog`) reports what the
16
- // harness can actually resolve for the *configured* models. Discovery can
17
- // succeed for a provider whose native route was never registered, and that
18
- // must not be reported as a routable model list;
19
- // * not a write. Nothing here persists, saves settings, or merges results into
20
- // the operator's document. It returns data; the operator decides.
21
- //
22
- // Security shape of the single upstream request:
23
- //
24
- // * the credential is the *selected profile's* `credentialRef`, resolved through
25
- // the injected DSH credential gateway once, for this request only. No ambient
26
- // environment variable or default provider credential is ever consulted: this
27
- // module has no accessor for either;
28
- // * the value is only ever placed in an `authorization` header. It is never
29
- // returned, stored on a profile, written to a diagnostic, or included in an
30
- // error — a failure is classified into a stable code plus fixed text;
31
- // * `redirect: 'manual'` is deliberate. Following a redirect would replay the
32
- // credential to a host the operator did not configure;
33
- // * the response body is read through a byte-limited reader, so a hostile or
34
- // broken endpoint cannot hold memory or the socket open;
35
- // * only `data[].id` survives parsing. Upstream `owned_by`, headers, messages and
36
- // error bodies are dropped rather than forwarded, so nothing an endpoint
37
- // invents can appear in the operator's UI as if this plugin vouched for it.
38
-
39
- import { LIMITS } from '../config/defaults.js';
40
- import { redactText } from '../config/redact.js';
41
-
42
- /** Stable diagnosis codes for model discovery. */
43
- export const DISCOVERY_CODES = Object.freeze({
44
- // Caller-side refusals (thrown, so the route answers with its own status).
45
- providerUnknown: 'DISCOVERY_PROVIDER_UNKNOWN',
46
- baseUrlInvalid: 'DISCOVERY_BASE_URL_INVALID',
47
- credentialRefMissing: 'DISCOVERY_CREDENTIAL_REF_MISSING',
48
- // Upstream outcomes (reported in the body, never thrown: discovery failing is
49
- // a diagnosis, not a broken request).
50
- credentialSeamUnavailable: 'DISCOVERY_CREDENTIAL_SEAM_UNAVAILABLE',
51
- credentialUnavailable: 'DISCOVERY_CREDENTIAL_UNAVAILABLE',
52
- credentialNotConfigured: 'DISCOVERY_CREDENTIAL_NOT_CONFIGURED',
53
- credentialEmpty: 'DISCOVERY_CREDENTIAL_EMPTY',
54
- authRefused: 'DISCOVERY_AUTH_REFUSED',
55
- httpError: 'DISCOVERY_HTTP_ERROR',
56
- redirectRefused: 'DISCOVERY_REDIRECT_REFUSED',
57
- networkFailed: 'DISCOVERY_NETWORK_FAILED',
58
- timeout: 'DISCOVERY_TIMEOUT',
59
- cancelled: 'DISCOVERY_CANCELLED',
60
- malformedResponse: 'DISCOVERY_MALFORMED_RESPONSE',
61
- bodyTooLarge: 'DISCOVERY_BODY_TOO_LARGE',
62
- });
63
-
64
- /** Optional route hint appended to a base URL. The OpenAI wire path for models. */
65
- export const MODELS_PATH = 'models';
66
-
67
- /**
68
- * Bound on the whole discovery request. A provider that has not answered within
69
- * this window is reported as a timeout instead of holding the settings page.
70
- */
71
- export const DISCOVERY_TIMEOUT_MS = 12_000;
72
-
73
- /** Bound on the upstream body. A model list is small; 1 MiB is generous. */
74
- export const MAX_DISCOVERY_BODY_BYTES = 1024 * 1024;
75
-
76
- /** One model id longer than this is not a model id this build can store. */
77
- export const MAX_MODEL_ID_CHARS = 160;
78
-
79
- /**
80
- * Characters an id may contain. This is exactly the set every protocol this build
81
- * speaks uses (`openai-chat` style ids), and it is also what keeps a hostile id
82
- * from carrying control characters into a settings document, a log line or a
83
- * request body.
84
- */
85
- const MODEL_ID_PATTERN = /^[A-Za-z0-9._:@/+-]+$/u;
86
-
87
- /**
88
- * Build a stable, bounded discovery failure.
89
- *
90
- * The class exists so the route can pass an upstream outcome through without
91
- * re-deriving its code, and so no free-form upstream text can ride along: the
92
- * message and details are fixed strings produced here.
93
- */
94
- export class DiscoveryError extends Error {
95
- /**
96
- * @param {string} code - one of {@link DISCOVERY_CODES}.
97
- * @param {string} message - fixed, operator-facing explanation.
98
- * @param {object} [details] - bounded, non-secret facts (numbers, ids, names).
99
- */
100
- constructor(code, message, details = {}) {
101
- super(message);
102
- this.name = 'DiscoveryError';
103
- this.code = code;
104
- this.details = details;
105
- }
106
- }
107
-
108
- /**
109
- * Join one provider base URL with the model-list path.
110
- *
111
- * The configured base URL has already been normalized by the validator (no query,
112
- * no fragment, no trailing slash), and an openai-compatible base is normally
113
- * `.../v1`. The `/v1` prefix therefore has to survive verbatim: dropping it, or
114
- * inserting the path before it, would address a different endpoint than the one
115
- * the operator configured. A base that already ends in the path segment is used
116
- * as-is rather than doubled.
117
- * @param {string} baseUrl - validated provider base URL.
118
- * @returns {URL} absolute model-list URL.
119
- * @throws {DiscoveryError} when the base URL is not an absolute http(s) URL.
120
- */
121
- export function modelsUrlFor(baseUrl) {
122
- let url;
123
- try {
124
- url = new URL(baseUrl);
125
- } catch {
126
- throw new DiscoveryError(DISCOVERY_CODES.baseUrlInvalid, 'the provider base URL is not an absolute URL');
127
- }
128
- if (url.protocol !== 'http:' && url.protocol !== 'https:') {
129
- throw new DiscoveryError(DISCOVERY_CODES.baseUrlInvalid, 'the provider base URL is not http or https');
130
- }
131
- if (url.username !== '' || url.password !== '' || url.search !== '' || url.hash !== '') {
132
- // Defence in depth: the validator refuses these, and a URL that somehow
133
- // carried one would put something besides the credential in the request URL.
134
- throw new DiscoveryError(DISCOVERY_CODES.baseUrlInvalid, 'the provider base URL carries a query, fragment or credentials');
135
- }
136
- const path = url.pathname.replace(/\/+$/, '');
137
- url.pathname = path.endsWith(`/${MODELS_PATH}`) ? path : `${path}/${MODELS_PATH}`;
138
- url.search = '';
139
- url.hash = '';
140
- return url;
141
- }
142
-
143
- /**
144
- * Whether a candidate string is an id this build can store as a model.
145
- * @param {unknown} value - candidate id.
146
- * @returns {boolean} true when usable.
147
- */
148
- export function isDiscoverableModelId(value) {
149
- return typeof value === 'string'
150
- && value !== ''
151
- && value === value.trim()
152
- && value.length <= MAX_MODEL_ID_CHARS
153
- && MODEL_ID_PATTERN.test(value);
154
- }
155
-
156
- /**
157
- * Parse one OpenAI-compatible model list into bounded, safe ids.
158
- *
159
- * The accepted shape is the documented one — `{ "data": [{ "id": "<id>", ... }] }`
160
- * — and nothing else. An array at the top level, a `models` key, or any other
161
- * provider's spelling is *malformed*, not "close enough": accepting a guess would
162
- * mean publishing ids this build never proved came from the endpoint's list.
163
- *
164
- * Deduplication is first-wins and silent: a repeated id is one model, not an
165
- * error, because some gateways concatenate alias lists. Everything past
166
- * `LIMITS.manualModelsPerProvider` is dropped and reported as a count, so the
167
- * result always fits the settings document it may be merged into.
168
- * @param {unknown} value - parsed JSON body.
169
- * @returns {{ models: { id: string, efforts: string[] }[], duplicates: number, invalid: number, truncated: number }} summary.
170
- * @throws {DiscoveryError} when the body is not a model list at all.
171
- */
172
- export function parseModelList(value) {
173
- if (value === null || typeof value !== 'object' || Array.isArray(value)) {
174
- throw new DiscoveryError(DISCOVERY_CODES.malformedResponse, 'the endpoint did not answer with a JSON object');
175
- }
176
- const data = value.data;
177
- if (!Array.isArray(data)) {
178
- throw new DiscoveryError(DISCOVERY_CODES.malformedResponse, 'the endpoint answered without a "data" array');
179
- }
180
- const models = [];
181
- const seen = new Set();
182
- let duplicates = 0;
183
- let invalid = 0;
184
- let truncated = 0;
185
- for (const entry of data) {
186
- const id = entry !== null && typeof entry === 'object' && !Array.isArray(entry) ? entry.id : undefined;
187
- if (!isDiscoverableModelId(id)) {
188
- // A malformed row is skipped rather than refusing the whole list: one bad
189
- // entry must not hide the ids the endpoint did report correctly.
190
- invalid += 1;
191
- continue;
192
- }
193
- if (seen.has(id)) {
194
- duplicates += 1;
195
- continue;
196
- }
197
- seen.add(id);
198
- if (models.length >= LIMITS.manualModelsPerProvider) {
199
- truncated += 1;
200
- continue;
201
- }
202
- // No capability is read from the response on purpose. An API listing proves
203
- // an id exists, not that it accepts a reasoning effort.
204
- models.push({ id, efforts: [] });
205
- }
206
- if (models.length === 0 && data.length > 0) {
207
- throw new DiscoveryError(DISCOVERY_CODES.malformedResponse, 'the endpoint answered with no usable model id');
208
- }
209
- return { models, duplicates, invalid, truncated };
210
- }
211
-
212
- /**
213
- * Read at most `limit` bytes from a response body.
214
- *
215
- * `response.text()` would buffer whatever the endpoint sends, and a
216
- * `content-length` header is a claim, not a bound. This reads the stream chunk by
217
- * chunk, aborts the reader as soon as the cap is crossed, and always releases the
218
- * body — including on every early-return path below.
219
- * @param {Response} response - fetch response.
220
- * @param {number} limit - byte bound.
221
- * @returns {Promise<{ ok: true, text: string } | { ok: false, code: string }>} outcome.
222
- */
223
- async function readBoundedText(response, limit) {
224
- const declared = Number(response?.headers?.get?.('content-length') ?? NaN);
225
- if (Number.isFinite(declared) && declared > limit) {
226
- await cancelBody(response);
227
- return { ok: false, code: DISCOVERY_CODES.bodyTooLarge };
228
- }
229
- const body = response?.body;
230
- if (body === null || body === undefined || typeof body.getReader !== 'function') {
231
- // A synthetic response (or a runtime without streams) still has text().
232
- try {
233
- const text = typeof response?.text === 'function' ? await response.text() : '';
234
- if (Buffer.byteLength(text, 'utf8') > limit) return { ok: false, code: DISCOVERY_CODES.bodyTooLarge };
235
- return { ok: true, text };
236
- } catch {
237
- return { ok: false, code: DISCOVERY_CODES.malformedResponse };
238
- }
239
- }
240
- const reader = body.getReader();
241
- const chunks = [];
242
- let size = 0;
243
- try {
244
- for (;;) {
245
- const { done, value } = await reader.read();
246
- if (done) break;
247
- const chunk = value instanceof Uint8Array ? value : new Uint8Array(value ?? []);
248
- size += chunk.byteLength;
249
- if (size > limit) {
250
- await reader.cancel().catch(() => undefined);
251
- return { ok: false, code: DISCOVERY_CODES.bodyTooLarge };
252
- }
253
- chunks.push(chunk);
254
- }
255
- } catch (error) {
256
- await reader.cancel().catch(() => undefined);
257
- if (error?.name === 'AbortError') return { ok: false, code: DISCOVERY_CODES.cancelled };
258
- return { ok: false, code: DISCOVERY_CODES.malformedResponse };
259
- }
260
- const merged = new Uint8Array(size);
261
- let offset = 0;
262
- for (const chunk of chunks) {
263
- merged.set(chunk, offset);
264
- offset += chunk.byteLength;
265
- }
266
- return { ok: true, text: Buffer.from(merged).toString('utf8') };
267
- }
268
-
269
- /**
270
- * Release a response body without consuming it.
271
- * @param {Response} response - fetch response.
272
- * @returns {Promise<void>} resolves once the body is released.
273
- */
274
- async function cancelBody(response) {
275
- try {
276
- await response?.body?.cancel?.();
277
- } catch {
278
- // An already-consumed or locked body cannot be cancelled; nothing to do.
279
- }
280
- }
281
-
282
- /**
283
- * Classify one thrown transport failure into a stable discovery outcome.
284
- *
285
- * The caller's signal and the request's own budget are reported separately on
286
- * purpose. `AbortSignal.any()` aborts the combined signal whichever input fired, so
287
- * a combined-signal check would label our own timeout as "the operator cancelled
288
- * it" — a diagnosis that sends an operator looking for a cancellation that never
289
- * happened.
290
- * @param {unknown} error - thrown value from fetch.
291
- * @param {object} signals - `timeoutSignal` and the caller's `callerSignal`.
292
- * @returns {DiscoveryError} stable failure.
293
- */
294
- function classifyTransportError(error, signals = {}) {
295
- if (signals.callerSignal?.aborted === true) {
296
- return new DiscoveryError(DISCOVERY_CODES.cancelled, 'the model list request was cancelled');
297
- }
298
- if (signals.timeoutSignal?.aborted === true
299
- || error?.name === 'TimeoutError'
300
- || error?.name === 'AbortError') {
301
- return new DiscoveryError(DISCOVERY_CODES.timeout, 'the endpoint did not answer in time', {
302
- timeoutMs: DISCOVERY_TIMEOUT_MS,
303
- });
304
- }
305
- // A network failure surfaces the operator's own host and port in its message,
306
- // and some runtimes add the request line. Only the error kind is kept.
307
- return new DiscoveryError(DISCOVERY_CODES.networkFailed, 'the endpoint could not be reached', {
308
- cause: typeof error?.code === 'string' ? error.code : (typeof error?.name === 'string' ? error.name : null),
309
- });
310
- }
311
-
312
- /**
313
- * Retrieve the model list of one configured provider profile.
314
- *
315
- * The credential is resolved through the injected DSH gateway for this request
316
- * only. A profile with no `credentialRef` is refused before any network I/O: an
317
- * unauthenticated list would describe what an endpoint shows a stranger, not what
318
- * this operator's key can use.
319
- * @param {object} input - discovery inputs.
320
- * @param {object} input.provider - validated provider profile (`id`, `baseUrl`, `credentialRef`).
321
- * @param {object} [input.credentials] - DSH credential gateway (`resolve(ref)`).
322
- * @param {(url: URL, init: object) => Promise<Response>} [input.fetchImpl] - transport override for tests.
323
- * @param {AbortSignal} [input.signal] - caller cancellation.
324
- * @param {number} [input.timeoutMs] - caller-tuned bound, never above the default.
325
- * @returns {Promise<object>} `{ ok, models, diagnosis, facts }`.
326
- */
327
- export async function discoverProviderModels(input = {}) {
328
- const provider = input.provider;
329
- if (provider === null || typeof provider !== 'object' || typeof provider.id !== 'string' || provider.id === '') {
330
- throw new DiscoveryError(DISCOVERY_CODES.providerUnknown, 'no provider profile was supplied');
331
- }
332
- const url = modelsUrlFor(provider.baseUrl);
333
- const reference = typeof provider.credentialRef === 'string' && provider.credentialRef !== ''
334
- ? provider.credentialRef
335
- : null;
336
- if (reference === null) {
337
- throw new DiscoveryError(
338
- DISCOVERY_CODES.credentialRefMissing,
339
- `provider ${provider.id} names no credential reference; set one before fetching its model list`,
340
- { providerId: provider.id },
341
- );
342
- }
343
- const credentials = input.credentials ?? null;
344
- if (credentials === null || typeof credentials.resolve !== 'function') {
345
- return failure(new DiscoveryError(
346
- DISCOVERY_CODES.credentialSeamUnavailable,
347
- 'this harness exposes no credential service, so the provider cannot be authenticated',
348
- { reference, providerId: provider.id },
349
- ));
350
- }
351
-
352
- let resolved;
353
- try {
354
- resolved = await credentials.resolve(reference);
355
- } catch (error) {
356
- // The gateway already keeps its own message out of the way; only its code is
357
- // forwarded, and never the value the backend may have echoed.
358
- return failure(new DiscoveryError(
359
- DISCOVERY_CODES.credentialUnavailable,
360
- `credential ${reference} could not be resolved`,
361
- { reference, providerId: provider.id, cause: typeof error?.code === 'string' ? error.code : null },
362
- ));
363
- }
364
- const value = typeof resolved?.value === 'string' ? resolved.value : '';
365
- if (value === '') {
366
- return failure(new DiscoveryError(
367
- DISCOVERY_CODES.credentialNotConfigured,
368
- `credential ${reference} is not configured`,
369
- { reference, providerId: provider.id },
370
- ));
371
- }
372
- if (value.trim() === '') {
373
- return failure(new DiscoveryError(
374
- DISCOVERY_CODES.credentialEmpty,
375
- `credential ${reference} holds no usable value`,
376
- { reference, providerId: provider.id },
377
- ));
378
- }
379
-
380
- const timeoutMs = Number.isInteger(input.timeoutMs) && input.timeoutMs > 0
381
- ? Math.min(input.timeoutMs, DISCOVERY_TIMEOUT_MS)
382
- : DISCOVERY_TIMEOUT_MS;
383
- const timeoutSignal = AbortSignal.timeout(timeoutMs);
384
- const signal = input.signal === undefined || input.signal === null
385
- ? timeoutSignal
386
- : AbortSignal.any([timeoutSignal, input.signal]);
387
- const fetchImpl = typeof input.fetchImpl === 'function'
388
- ? input.fetchImpl
389
- : ((target, init) => globalThis.fetch(target, init));
390
-
391
- let response;
392
- try {
393
- response = await fetchImpl(url, {
394
- method: 'GET',
395
- // Never follow a redirect: the credential must not reach a host the
396
- // operator did not configure.
397
- redirect: 'manual',
398
- headers: {
399
- accept: 'application/json',
400
- authorization: `Bearer ${value}`,
401
- },
402
- signal,
403
- });
404
- } catch (error) {
405
- return failure(classifyTransportError(error, { timeoutSignal, callerSignal: input.signal }));
406
- }
407
-
408
- const status = typeof response?.status === 'number' ? response.status : 0;
409
- if (status >= 300 && status < 400) {
410
- // Even a same-host redirect is refused, and its `location` is not reported:
411
- // the target is the endpoint's business, not the operator's.
412
- await cancelBody(response);
413
- return failure(new DiscoveryError(
414
- DISCOVERY_CODES.redirectRefused,
415
- 'the endpoint answered with a redirect; configure the final base URL instead',
416
- { providerId: provider.id, status },
417
- ));
418
- }
419
- if (status === 401 || status === 403) {
420
- // The upstream body may quote the key back. It is released, never read.
421
- await cancelBody(response);
422
- return failure(new DiscoveryError(
423
- DISCOVERY_CODES.authRefused,
424
- `the endpoint refused the credential (HTTP ${status})`,
425
- { providerId: provider.id, status, reference },
426
- ));
427
- }
428
- if (status < 200 || status >= 300) {
429
- await cancelBody(response);
430
- return failure(new DiscoveryError(
431
- DISCOVERY_CODES.httpError,
432
- `the endpoint answered HTTP ${status}`,
433
- { providerId: provider.id, status },
434
- ));
435
- }
436
-
437
- const read = await readBoundedText(response, MAX_DISCOVERY_BODY_BYTES);
438
- if (read.ok !== true) {
439
- if (read.code === DISCOVERY_CODES.cancelled) {
440
- return failure(classifyTransportError(
441
- Object.assign(new Error('cancelled'), { name: 'AbortError' }),
442
- { timeoutSignal, callerSignal: input.signal },
443
- ));
444
- }
445
- return failure(new DiscoveryError(
446
- read.code,
447
- read.code === DISCOVERY_CODES.bodyTooLarge
448
- ? 'the endpoint answered with more than the accepted body size'
449
- : 'the endpoint response could not be read',
450
- { providerId: provider.id, limitBytes: MAX_DISCOVERY_BODY_BYTES },
451
- ));
452
- }
453
-
454
- let parsed;
455
- try {
456
- parsed = JSON.parse(read.text);
457
- } catch {
458
- // The body itself is not forwarded: it is untrusted text and may be an HTML
459
- // error page quoting the request.
460
- return failure(new DiscoveryError(
461
- DISCOVERY_CODES.malformedResponse,
462
- 'the endpoint answered with something that is not JSON',
463
- { providerId: provider.id },
464
- ));
465
- }
466
-
467
- let summary;
468
- try {
469
- summary = parseModelList(parsed);
470
- } catch (error) {
471
- if (error instanceof DiscoveryError) {
472
- return failure(new DiscoveryError(error.code, error.message, { providerId: provider.id }));
473
- }
474
- return failure(new DiscoveryError(DISCOVERY_CODES.malformedResponse, 'the endpoint answer could not be understood', {
475
- providerId: provider.id,
476
- }));
477
- }
478
-
479
- return {
480
- ok: true,
481
- models: summary.models,
482
- diagnosis: null,
483
- facts: {
484
- providerId: provider.id,
485
- // Named so a caller never has to infer where the list came from.
486
- source: 'remote',
487
- endpoint: url.origin + url.pathname,
488
- status,
489
- received: summary.models.length,
490
- duplicates: summary.duplicates,
491
- invalid: summary.invalid,
492
- truncated: summary.truncated,
493
- // Stated rather than implied, because it is the one thing a list cannot
494
- // prove and the one thing an operator is most likely to assume.
495
- capabilities: 'listing-does-not-establish-reasoning-support',
496
- },
497
- };
498
- }
499
-
500
- /**
501
- * Wrap one upstream failure as a discovery result.
502
- * @param {DiscoveryError} error - stable failure.
503
- * @returns {object} `{ ok: false, models: [], diagnosis, facts }`.
504
- */
505
- function failure(error) {
506
- return {
507
- ok: false,
508
- models: [],
509
- diagnosis: {
510
- code: error.code,
511
- // Fixed text from this module, redacted as a belt-and-braces measure: no
512
- // upstream string ever reaches this field, but a future edit must not be
513
- // able to leak one either.
514
- message: redactText(error.message).slice(0, 300),
515
- details: sanitizeDetails(error.details),
516
- },
517
- facts: { providerId: error.details?.providerId ?? null, source: 'remote' },
518
- };
519
- }
520
-
521
- /**
522
- * Keep only bounded, non-secret detail values.
523
- *
524
- * The detail object is built by this module, so this is a guard against a future
525
- * addition rather than a filter over untrusted input: strings are truncated and
526
- * redacted, and anything else non-primitive is dropped.
527
- * @param {object | undefined} details - candidate details.
528
- * @returns {object} safe details.
529
- */
530
- function sanitizeDetails(details) {
531
- const out = {};
532
- for (const [key, value] of Object.entries(details ?? {})) {
533
- if (typeof value === 'string') {
534
- if (value === '') continue;
535
- out[key] = redactText(value).slice(0, 200);
536
- } else if (typeof value === 'number' || typeof value === 'boolean' || value === null) {
537
- out[key] = value;
538
- }
539
- }
540
- return out;
541
- }
542
-
543
- /**
544
- * Fold a discovered list into the operator's stored declarations, without ever
545
- * weakening what was declared explicitly.
546
- *
547
- * The merge is deliberately asymmetric:
548
- * * an id the document already declares keeps its declared `efforts` and
549
- * `contextWindow` — discovery cannot lend capability, so it cannot take any
550
- * away either;
551
- * * an id that is new to the document is added with `efforts: []`, exactly as
552
- * discovery found it;
553
- * * ids the document declares but the endpoint did not list are kept. A manual
554
- * entry (or a model the endpoint has temporarily dropped) stays configured;
555
- * dropping it would silently delete an operator's work.
556
- * @param {object[]} declared - `provider.models` from the settings document.
557
- * @param {object[]} discovered - `{ id, efforts }` entries from {@link discoverProviderModels}.
558
- * @returns {{ models: object[], added: string[], kept: string[], declaredEffortModelIds: string[] }} merge result.
559
- */
560
- export function mergeDiscoveredModels(declared, discovered) {
561
- const existing = Array.isArray(declared) ? declared : [];
562
- const models = existing.map((model) => ({ ...model }));
563
- const byId = new Map(models.map((model) => [model.id, model]));
564
- const added = [];
565
- const declaredEffortModelIds = [];
566
- for (const model of models) {
567
- if (Array.isArray(model.efforts) && model.efforts.length > 0) declaredEffortModelIds.push(model.id);
568
- }
569
- for (const found of Array.isArray(discovered) ? discovered : []) {
570
- if (!isDiscoverableModelId(found?.id)) continue;
571
- if (byId.has(found.id)) continue;
572
- const entry = { id: found.id, efforts: [] };
573
- models.push(entry);
574
- byId.set(entry.id, entry);
575
- added.push(entry.id);
576
- }
577
- const discoveredIds = new Set((Array.isArray(discovered) ? discovered : []).map((model) => model?.id));
578
- const kept = models
579
- .map((model) => model.id)
580
- .filter((id) => isDiscoverableModelId(id) && !discoveredIds.has(id));
581
- return { models, added, kept, declaredEffortModelIds };
582
- }
1
+ // Remote model discovery for one configured provider profile.
2
+ //
3
+ // This module answers exactly one question: *which model ids does this provider's
4
+ // own API say it serves right now?* It is the only place in the plugin that talks
5
+ // to a provider over HTTP on the operator's behalf outside a model call, and the
6
+ // constraints below are what make that safe.
7
+ //
8
+ // What it is NOT:
9
+ //
10
+ // * not a capability authority. An `openai-chat` model list carries ids and
11
+ // nothing this build trusts about reasoning support, so every discovered id
12
+ // gets `efforts: []`. Guessing `high`/`max` from a model name, or forwarding an
13
+ // arbitrary upstream `capabilities`/`reasoning` field, would turn an unverified
14
+ // assumption into a routing decision the provider may reject at request time;
15
+ // * not a native catalog. `/catalog` (`describeCatalog`) reports what the
16
+ // harness can actually resolve for the *configured* models. Discovery can
17
+ // succeed for a provider whose native route was never registered, and that
18
+ // must not be reported as a routable model list;
19
+ // * not a write. Nothing here persists, saves settings, or merges results into
20
+ // the operator's document. It returns data; the operator decides.
21
+ //
22
+ // Security shape of the single upstream request:
23
+ //
24
+ // * the credential is the *selected profile's* `credentialRef`, resolved through
25
+ // the injected DSH credential gateway once, for this request only. No ambient
26
+ // environment variable or default provider credential is ever consulted: this
27
+ // module has no accessor for either;
28
+ // * the value is only ever placed in an `authorization` header. It is never
29
+ // returned, stored on a profile, written to a diagnostic, or included in an
30
+ // error — a failure is classified into a stable code plus fixed text;
31
+ // * `redirect: 'manual'` is deliberate. Following a redirect would replay the
32
+ // credential to a host the operator did not configure;
33
+ // * the response body is read through a byte-limited reader, so a hostile or
34
+ // broken endpoint cannot hold memory or the socket open;
35
+ // * only `data[].id` survives parsing. Upstream `owned_by`, headers, messages and
36
+ // error bodies are dropped rather than forwarded, so nothing an endpoint
37
+ // invents can appear in the operator's UI as if this plugin vouched for it.
38
+
39
+ import { LIMITS } from '../config/defaults.js';
40
+ import { redactText } from '../config/redact.js';
41
+
42
+ /** Stable diagnosis codes for model discovery. */
43
+ export const DISCOVERY_CODES = Object.freeze({
44
+ // Caller-side refusals (thrown, so the route answers with its own status).
45
+ providerUnknown: 'DISCOVERY_PROVIDER_UNKNOWN',
46
+ baseUrlInvalid: 'DISCOVERY_BASE_URL_INVALID',
47
+ credentialRefMissing: 'DISCOVERY_CREDENTIAL_REF_MISSING',
48
+ // Upstream outcomes (reported in the body, never thrown: discovery failing is
49
+ // a diagnosis, not a broken request).
50
+ credentialSeamUnavailable: 'DISCOVERY_CREDENTIAL_SEAM_UNAVAILABLE',
51
+ credentialUnavailable: 'DISCOVERY_CREDENTIAL_UNAVAILABLE',
52
+ credentialNotConfigured: 'DISCOVERY_CREDENTIAL_NOT_CONFIGURED',
53
+ credentialEmpty: 'DISCOVERY_CREDENTIAL_EMPTY',
54
+ authRefused: 'DISCOVERY_AUTH_REFUSED',
55
+ httpError: 'DISCOVERY_HTTP_ERROR',
56
+ redirectRefused: 'DISCOVERY_REDIRECT_REFUSED',
57
+ networkFailed: 'DISCOVERY_NETWORK_FAILED',
58
+ timeout: 'DISCOVERY_TIMEOUT',
59
+ cancelled: 'DISCOVERY_CANCELLED',
60
+ malformedResponse: 'DISCOVERY_MALFORMED_RESPONSE',
61
+ bodyTooLarge: 'DISCOVERY_BODY_TOO_LARGE',
62
+ });
63
+
64
+ /** Optional route hint appended to a base URL. The OpenAI wire path for models. */
65
+ export const MODELS_PATH = 'models';
66
+
67
+ /**
68
+ * Bound on the whole discovery request. A provider that has not answered within
69
+ * this window is reported as a timeout instead of holding the settings page.
70
+ */
71
+ export const DISCOVERY_TIMEOUT_MS = 12_000;
72
+
73
+ /** Bound on the upstream body. A model list is small; 1 MiB is generous. */
74
+ export const MAX_DISCOVERY_BODY_BYTES = 1024 * 1024;
75
+
76
+ /** One model id longer than this is not a model id this build can store. */
77
+ export const MAX_MODEL_ID_CHARS = 160;
78
+
79
+ /**
80
+ * Characters an id may contain. This is exactly the set every protocol this build
81
+ * speaks uses (`openai-chat` style ids), and it is also what keeps a hostile id
82
+ * from carrying control characters into a settings document, a log line or a
83
+ * request body.
84
+ */
85
+ const MODEL_ID_PATTERN = /^[A-Za-z0-9._:@/+-]+$/u;
86
+
87
+ /**
88
+ * Build a stable, bounded discovery failure.
89
+ *
90
+ * The class exists so the route can pass an upstream outcome through without
91
+ * re-deriving its code, and so no free-form upstream text can ride along: the
92
+ * message and details are fixed strings produced here.
93
+ */
94
+ export class DiscoveryError extends Error {
95
+ /**
96
+ * @param {string} code - one of {@link DISCOVERY_CODES}.
97
+ * @param {string} message - fixed, operator-facing explanation.
98
+ * @param {object} [details] - bounded, non-secret facts (numbers, ids, names).
99
+ */
100
+ constructor(code, message, details = {}) {
101
+ super(message);
102
+ this.name = 'DiscoveryError';
103
+ this.code = code;
104
+ this.details = details;
105
+ }
106
+ }
107
+
108
+ /**
109
+ * Join one provider base URL with the model-list path.
110
+ *
111
+ * The configured base URL has already been normalized by the validator (no query,
112
+ * no fragment, no trailing slash), and an openai-compatible base is normally
113
+ * `.../v1`. The `/v1` prefix therefore has to survive verbatim: dropping it, or
114
+ * inserting the path before it, would address a different endpoint than the one
115
+ * the operator configured. A base that already ends in the path segment is used
116
+ * as-is rather than doubled.
117
+ * @param {string} baseUrl - validated provider base URL.
118
+ * @returns {URL} absolute model-list URL.
119
+ * @throws {DiscoveryError} when the base URL is not an absolute http(s) URL.
120
+ */
121
+ export function modelsUrlFor(baseUrl) {
122
+ let url;
123
+ try {
124
+ url = new URL(baseUrl);
125
+ } catch {
126
+ throw new DiscoveryError(DISCOVERY_CODES.baseUrlInvalid, 'the provider base URL is not an absolute URL');
127
+ }
128
+ if (url.protocol !== 'http:' && url.protocol !== 'https:') {
129
+ throw new DiscoveryError(DISCOVERY_CODES.baseUrlInvalid, 'the provider base URL is not http or https');
130
+ }
131
+ if (url.username !== '' || url.password !== '' || url.search !== '' || url.hash !== '') {
132
+ // Defence in depth: the validator refuses these, and a URL that somehow
133
+ // carried one would put something besides the credential in the request URL.
134
+ throw new DiscoveryError(DISCOVERY_CODES.baseUrlInvalid, 'the provider base URL carries a query, fragment or credentials');
135
+ }
136
+ const path = url.pathname.replace(/\/+$/, '');
137
+ url.pathname = path.endsWith(`/${MODELS_PATH}`) ? path : `${path}/${MODELS_PATH}`;
138
+ url.search = '';
139
+ url.hash = '';
140
+ return url;
141
+ }
142
+
143
+ /**
144
+ * Whether a candidate string is an id this build can store as a model.
145
+ * @param {unknown} value - candidate id.
146
+ * @returns {boolean} true when usable.
147
+ */
148
+ export function isDiscoverableModelId(value) {
149
+ return typeof value === 'string'
150
+ && value !== ''
151
+ && value === value.trim()
152
+ && value.length <= MAX_MODEL_ID_CHARS
153
+ && MODEL_ID_PATTERN.test(value);
154
+ }
155
+
156
+ /**
157
+ * Parse one OpenAI-compatible model list into bounded, safe ids.
158
+ *
159
+ * The accepted shape is the documented one — `{ "data": [{ "id": "<id>", ... }] }`
160
+ * — and nothing else. An array at the top level, a `models` key, or any other
161
+ * provider's spelling is *malformed*, not "close enough": accepting a guess would
162
+ * mean publishing ids this build never proved came from the endpoint's list.
163
+ *
164
+ * Deduplication is first-wins and silent: a repeated id is one model, not an
165
+ * error, because some gateways concatenate alias lists. Everything past
166
+ * `LIMITS.manualModelsPerProvider` is dropped and reported as a count, so the
167
+ * result always fits the settings document it may be merged into.
168
+ * @param {unknown} value - parsed JSON body.
169
+ * @returns {{ models: { id: string, efforts: string[] }[], duplicates: number, invalid: number, truncated: number }} summary.
170
+ * @throws {DiscoveryError} when the body is not a model list at all.
171
+ */
172
+ export function parseModelList(value) {
173
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) {
174
+ throw new DiscoveryError(DISCOVERY_CODES.malformedResponse, 'the endpoint did not answer with a JSON object');
175
+ }
176
+ const data = value.data;
177
+ if (!Array.isArray(data)) {
178
+ throw new DiscoveryError(DISCOVERY_CODES.malformedResponse, 'the endpoint answered without a "data" array');
179
+ }
180
+ const models = [];
181
+ const seen = new Set();
182
+ let duplicates = 0;
183
+ let invalid = 0;
184
+ let truncated = 0;
185
+ for (const entry of data) {
186
+ const id = entry !== null && typeof entry === 'object' && !Array.isArray(entry) ? entry.id : undefined;
187
+ if (!isDiscoverableModelId(id)) {
188
+ // A malformed row is skipped rather than refusing the whole list: one bad
189
+ // entry must not hide the ids the endpoint did report correctly.
190
+ invalid += 1;
191
+ continue;
192
+ }
193
+ if (seen.has(id)) {
194
+ duplicates += 1;
195
+ continue;
196
+ }
197
+ seen.add(id);
198
+ if (models.length >= LIMITS.manualModelsPerProvider) {
199
+ truncated += 1;
200
+ continue;
201
+ }
202
+ // No capability is read from the response on purpose. An API listing proves
203
+ // an id exists, not that it accepts a reasoning effort.
204
+ models.push({ id, efforts: [] });
205
+ }
206
+ if (models.length === 0 && data.length > 0) {
207
+ throw new DiscoveryError(DISCOVERY_CODES.malformedResponse, 'the endpoint answered with no usable model id');
208
+ }
209
+ return { models, duplicates, invalid, truncated };
210
+ }
211
+
212
+ /**
213
+ * Read at most `limit` bytes from a response body.
214
+ *
215
+ * `response.text()` would buffer whatever the endpoint sends, and a
216
+ * `content-length` header is a claim, not a bound. This reads the stream chunk by
217
+ * chunk, aborts the reader as soon as the cap is crossed, and always releases the
218
+ * body — including on every early-return path below.
219
+ * @param {Response} response - fetch response.
220
+ * @param {number} limit - byte bound.
221
+ * @returns {Promise<{ ok: true, text: string } | { ok: false, code: string }>} outcome.
222
+ */
223
+ async function readBoundedText(response, limit) {
224
+ const declared = Number(response?.headers?.get?.('content-length') ?? NaN);
225
+ if (Number.isFinite(declared) && declared > limit) {
226
+ await cancelBody(response);
227
+ return { ok: false, code: DISCOVERY_CODES.bodyTooLarge };
228
+ }
229
+ const body = response?.body;
230
+ if (body === null || body === undefined || typeof body.getReader !== 'function') {
231
+ // A synthetic response (or a runtime without streams) still has text().
232
+ try {
233
+ const text = typeof response?.text === 'function' ? await response.text() : '';
234
+ if (Buffer.byteLength(text, 'utf8') > limit) return { ok: false, code: DISCOVERY_CODES.bodyTooLarge };
235
+ return { ok: true, text };
236
+ } catch {
237
+ return { ok: false, code: DISCOVERY_CODES.malformedResponse };
238
+ }
239
+ }
240
+ const reader = body.getReader();
241
+ const chunks = [];
242
+ let size = 0;
243
+ try {
244
+ for (;;) {
245
+ const { done, value } = await reader.read();
246
+ if (done) break;
247
+ const chunk = value instanceof Uint8Array ? value : new Uint8Array(value ?? []);
248
+ size += chunk.byteLength;
249
+ if (size > limit) {
250
+ await reader.cancel().catch(() => undefined);
251
+ return { ok: false, code: DISCOVERY_CODES.bodyTooLarge };
252
+ }
253
+ chunks.push(chunk);
254
+ }
255
+ } catch (error) {
256
+ await reader.cancel().catch(() => undefined);
257
+ if (error?.name === 'AbortError') return { ok: false, code: DISCOVERY_CODES.cancelled };
258
+ return { ok: false, code: DISCOVERY_CODES.malformedResponse };
259
+ }
260
+ const merged = new Uint8Array(size);
261
+ let offset = 0;
262
+ for (const chunk of chunks) {
263
+ merged.set(chunk, offset);
264
+ offset += chunk.byteLength;
265
+ }
266
+ return { ok: true, text: Buffer.from(merged).toString('utf8') };
267
+ }
268
+
269
+ /**
270
+ * Release a response body without consuming it.
271
+ * @param {Response} response - fetch response.
272
+ * @returns {Promise<void>} resolves once the body is released.
273
+ */
274
+ async function cancelBody(response) {
275
+ try {
276
+ await response?.body?.cancel?.();
277
+ } catch {
278
+ // An already-consumed or locked body cannot be cancelled; nothing to do.
279
+ }
280
+ }
281
+
282
+ /**
283
+ * Classify one thrown transport failure into a stable discovery outcome.
284
+ *
285
+ * The caller's signal and the request's own budget are reported separately on
286
+ * purpose. `AbortSignal.any()` aborts the combined signal whichever input fired, so
287
+ * a combined-signal check would label our own timeout as "the operator cancelled
288
+ * it" — a diagnosis that sends an operator looking for a cancellation that never
289
+ * happened.
290
+ * @param {unknown} error - thrown value from fetch.
291
+ * @param {object} signals - `timeoutSignal` and the caller's `callerSignal`.
292
+ * @returns {DiscoveryError} stable failure.
293
+ */
294
+ function classifyTransportError(error, signals = {}) {
295
+ if (signals.callerSignal?.aborted === true) {
296
+ return new DiscoveryError(DISCOVERY_CODES.cancelled, 'the model list request was cancelled');
297
+ }
298
+ if (signals.timeoutSignal?.aborted === true
299
+ || error?.name === 'TimeoutError'
300
+ || error?.name === 'AbortError') {
301
+ return new DiscoveryError(DISCOVERY_CODES.timeout, 'the endpoint did not answer in time', {
302
+ timeoutMs: DISCOVERY_TIMEOUT_MS,
303
+ });
304
+ }
305
+ // A network failure surfaces the operator's own host and port in its message,
306
+ // and some runtimes add the request line. Only the error kind is kept.
307
+ return new DiscoveryError(DISCOVERY_CODES.networkFailed, 'the endpoint could not be reached', {
308
+ cause: typeof error?.code === 'string' ? error.code : (typeof error?.name === 'string' ? error.name : null),
309
+ });
310
+ }
311
+
312
+ /**
313
+ * Retrieve the model list of one configured provider profile.
314
+ *
315
+ * The credential is resolved through the injected DSH gateway for this request
316
+ * only. A profile with no `credentialRef` is refused before any network I/O: an
317
+ * unauthenticated list would describe what an endpoint shows a stranger, not what
318
+ * this operator's key can use.
319
+ * @param {object} input - discovery inputs.
320
+ * @param {object} input.provider - validated provider profile (`id`, `baseUrl`, `credentialRef`).
321
+ * @param {object} [input.credentials] - DSH credential gateway (`resolve(ref)`).
322
+ * @param {(url: URL, init: object) => Promise<Response>} [input.fetchImpl] - transport override for tests.
323
+ * @param {AbortSignal} [input.signal] - caller cancellation.
324
+ * @param {number} [input.timeoutMs] - caller-tuned bound, never above the default.
325
+ * @returns {Promise<object>} `{ ok, models, diagnosis, facts }`.
326
+ */
327
+ export async function discoverProviderModels(input = {}) {
328
+ const provider = input.provider;
329
+ if (provider === null || typeof provider !== 'object' || typeof provider.id !== 'string' || provider.id === '') {
330
+ throw new DiscoveryError(DISCOVERY_CODES.providerUnknown, 'no provider profile was supplied');
331
+ }
332
+ const url = modelsUrlFor(provider.baseUrl);
333
+ const reference = typeof provider.credentialRef === 'string' && provider.credentialRef !== ''
334
+ ? provider.credentialRef
335
+ : null;
336
+ if (reference === null) {
337
+ throw new DiscoveryError(
338
+ DISCOVERY_CODES.credentialRefMissing,
339
+ `provider ${provider.id} names no credential reference; set one before fetching its model list`,
340
+ { providerId: provider.id },
341
+ );
342
+ }
343
+ const credentials = input.credentials ?? null;
344
+ if (credentials === null || typeof credentials.resolve !== 'function') {
345
+ return failure(new DiscoveryError(
346
+ DISCOVERY_CODES.credentialSeamUnavailable,
347
+ 'this harness exposes no credential service, so the provider cannot be authenticated',
348
+ { reference, providerId: provider.id },
349
+ ));
350
+ }
351
+
352
+ let resolved;
353
+ try {
354
+ resolved = await credentials.resolve(reference);
355
+ } catch (error) {
356
+ // The gateway already keeps its own message out of the way; only its code is
357
+ // forwarded, and never the value the backend may have echoed.
358
+ return failure(new DiscoveryError(
359
+ DISCOVERY_CODES.credentialUnavailable,
360
+ `credential ${reference} could not be resolved`,
361
+ { reference, providerId: provider.id, cause: typeof error?.code === 'string' ? error.code : null },
362
+ ));
363
+ }
364
+ const value = typeof resolved?.value === 'string' ? resolved.value : '';
365
+ if (value === '') {
366
+ return failure(new DiscoveryError(
367
+ DISCOVERY_CODES.credentialNotConfigured,
368
+ `credential ${reference} is not configured`,
369
+ { reference, providerId: provider.id },
370
+ ));
371
+ }
372
+ if (value.trim() === '') {
373
+ return failure(new DiscoveryError(
374
+ DISCOVERY_CODES.credentialEmpty,
375
+ `credential ${reference} holds no usable value`,
376
+ { reference, providerId: provider.id },
377
+ ));
378
+ }
379
+
380
+ const timeoutMs = Number.isInteger(input.timeoutMs) && input.timeoutMs > 0
381
+ ? Math.min(input.timeoutMs, DISCOVERY_TIMEOUT_MS)
382
+ : DISCOVERY_TIMEOUT_MS;
383
+ const timeoutSignal = AbortSignal.timeout(timeoutMs);
384
+ const signal = input.signal === undefined || input.signal === null
385
+ ? timeoutSignal
386
+ : AbortSignal.any([timeoutSignal, input.signal]);
387
+ const fetchImpl = typeof input.fetchImpl === 'function'
388
+ ? input.fetchImpl
389
+ : ((target, init) => globalThis.fetch(target, init));
390
+
391
+ let response;
392
+ try {
393
+ response = await fetchImpl(url, {
394
+ method: 'GET',
395
+ // Never follow a redirect: the credential must not reach a host the
396
+ // operator did not configure.
397
+ redirect: 'manual',
398
+ headers: {
399
+ accept: 'application/json',
400
+ authorization: `Bearer ${value}`,
401
+ },
402
+ signal,
403
+ });
404
+ } catch (error) {
405
+ return failure(classifyTransportError(error, { timeoutSignal, callerSignal: input.signal }));
406
+ }
407
+
408
+ const status = typeof response?.status === 'number' ? response.status : 0;
409
+ if (status >= 300 && status < 400) {
410
+ // Even a same-host redirect is refused, and its `location` is not reported:
411
+ // the target is the endpoint's business, not the operator's.
412
+ await cancelBody(response);
413
+ return failure(new DiscoveryError(
414
+ DISCOVERY_CODES.redirectRefused,
415
+ 'the endpoint answered with a redirect; configure the final base URL instead',
416
+ { providerId: provider.id, status },
417
+ ));
418
+ }
419
+ if (status === 401 || status === 403) {
420
+ // The upstream body may quote the key back. It is released, never read.
421
+ await cancelBody(response);
422
+ return failure(new DiscoveryError(
423
+ DISCOVERY_CODES.authRefused,
424
+ `the endpoint refused the credential (HTTP ${status})`,
425
+ { providerId: provider.id, status, reference },
426
+ ));
427
+ }
428
+ if (status < 200 || status >= 300) {
429
+ await cancelBody(response);
430
+ return failure(new DiscoveryError(
431
+ DISCOVERY_CODES.httpError,
432
+ `the endpoint answered HTTP ${status}`,
433
+ { providerId: provider.id, status },
434
+ ));
435
+ }
436
+
437
+ const read = await readBoundedText(response, MAX_DISCOVERY_BODY_BYTES);
438
+ if (read.ok !== true) {
439
+ if (read.code === DISCOVERY_CODES.cancelled) {
440
+ return failure(classifyTransportError(
441
+ Object.assign(new Error('cancelled'), { name: 'AbortError' }),
442
+ { timeoutSignal, callerSignal: input.signal },
443
+ ));
444
+ }
445
+ return failure(new DiscoveryError(
446
+ read.code,
447
+ read.code === DISCOVERY_CODES.bodyTooLarge
448
+ ? 'the endpoint answered with more than the accepted body size'
449
+ : 'the endpoint response could not be read',
450
+ { providerId: provider.id, limitBytes: MAX_DISCOVERY_BODY_BYTES },
451
+ ));
452
+ }
453
+
454
+ let parsed;
455
+ try {
456
+ parsed = JSON.parse(read.text);
457
+ } catch {
458
+ // The body itself is not forwarded: it is untrusted text and may be an HTML
459
+ // error page quoting the request.
460
+ return failure(new DiscoveryError(
461
+ DISCOVERY_CODES.malformedResponse,
462
+ 'the endpoint answered with something that is not JSON',
463
+ { providerId: provider.id },
464
+ ));
465
+ }
466
+
467
+ let summary;
468
+ try {
469
+ summary = parseModelList(parsed);
470
+ } catch (error) {
471
+ if (error instanceof DiscoveryError) {
472
+ return failure(new DiscoveryError(error.code, error.message, { providerId: provider.id }));
473
+ }
474
+ return failure(new DiscoveryError(DISCOVERY_CODES.malformedResponse, 'the endpoint answer could not be understood', {
475
+ providerId: provider.id,
476
+ }));
477
+ }
478
+
479
+ return {
480
+ ok: true,
481
+ models: summary.models,
482
+ diagnosis: null,
483
+ facts: {
484
+ providerId: provider.id,
485
+ // Named so a caller never has to infer where the list came from.
486
+ source: 'remote',
487
+ endpoint: url.origin + url.pathname,
488
+ status,
489
+ received: summary.models.length,
490
+ duplicates: summary.duplicates,
491
+ invalid: summary.invalid,
492
+ truncated: summary.truncated,
493
+ // Stated rather than implied, because it is the one thing a list cannot
494
+ // prove and the one thing an operator is most likely to assume.
495
+ capabilities: 'listing-does-not-establish-reasoning-support',
496
+ },
497
+ };
498
+ }
499
+
500
+ /**
501
+ * Wrap one upstream failure as a discovery result.
502
+ * @param {DiscoveryError} error - stable failure.
503
+ * @returns {object} `{ ok: false, models: [], diagnosis, facts }`.
504
+ */
505
+ function failure(error) {
506
+ return {
507
+ ok: false,
508
+ models: [],
509
+ diagnosis: {
510
+ code: error.code,
511
+ // Fixed text from this module, redacted as a belt-and-braces measure: no
512
+ // upstream string ever reaches this field, but a future edit must not be
513
+ // able to leak one either.
514
+ message: redactText(error.message).slice(0, 300),
515
+ details: sanitizeDetails(error.details),
516
+ },
517
+ facts: { providerId: error.details?.providerId ?? null, source: 'remote' },
518
+ };
519
+ }
520
+
521
+ /**
522
+ * Keep only bounded, non-secret detail values.
523
+ *
524
+ * The detail object is built by this module, so this is a guard against a future
525
+ * addition rather than a filter over untrusted input: strings are truncated and
526
+ * redacted, and anything else non-primitive is dropped.
527
+ * @param {object | undefined} details - candidate details.
528
+ * @returns {object} safe details.
529
+ */
530
+ function sanitizeDetails(details) {
531
+ const out = {};
532
+ for (const [key, value] of Object.entries(details ?? {})) {
533
+ if (typeof value === 'string') {
534
+ if (value === '') continue;
535
+ out[key] = redactText(value).slice(0, 200);
536
+ } else if (typeof value === 'number' || typeof value === 'boolean' || value === null) {
537
+ out[key] = value;
538
+ }
539
+ }
540
+ return out;
541
+ }
542
+
543
+ /**
544
+ * Fold a discovered list into the operator's stored declarations, without ever
545
+ * weakening what was declared explicitly.
546
+ *
547
+ * The merge is deliberately asymmetric:
548
+ * * an id the document already declares keeps its declared `efforts` and
549
+ * `contextWindow` — discovery cannot lend capability, so it cannot take any
550
+ * away either;
551
+ * * an id that is new to the document is added with `efforts: []`, exactly as
552
+ * discovery found it;
553
+ * * ids the document declares but the endpoint did not list are kept. A manual
554
+ * entry (or a model the endpoint has temporarily dropped) stays configured;
555
+ * dropping it would silently delete an operator's work.
556
+ * @param {object[]} declared - `provider.models` from the settings document.
557
+ * @param {object[]} discovered - `{ id, efforts }` entries from {@link discoverProviderModels}.
558
+ * @returns {{ models: object[], added: string[], kept: string[], declaredEffortModelIds: string[] }} merge result.
559
+ */
560
+ export function mergeDiscoveredModels(declared, discovered) {
561
+ const existing = Array.isArray(declared) ? declared : [];
562
+ const models = existing.map((model) => ({ ...model }));
563
+ const byId = new Map(models.map((model) => [model.id, model]));
564
+ const added = [];
565
+ const declaredEffortModelIds = [];
566
+ for (const model of models) {
567
+ if (Array.isArray(model.efforts) && model.efforts.length > 0) declaredEffortModelIds.push(model.id);
568
+ }
569
+ for (const found of Array.isArray(discovered) ? discovered : []) {
570
+ if (!isDiscoverableModelId(found?.id)) continue;
571
+ if (byId.has(found.id)) continue;
572
+ const entry = { id: found.id, efforts: [] };
573
+ models.push(entry);
574
+ byId.set(entry.id, entry);
575
+ added.push(entry.id);
576
+ }
577
+ const discoveredIds = new Set((Array.isArray(discovered) ? discovered : []).map((model) => model?.id));
578
+ const kept = models
579
+ .map((model) => model.id)
580
+ .filter((id) => isDiscoverableModelId(id) && !discoveredIds.has(id));
581
+ return { models, added, kept, declaredEffortModelIds };
582
+ }