@picassohq/cli 1.0.3 → 1.0.4

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 (40) hide show
  1. package/dist/build-info.json +1 -1
  2. package/dist/index.js +1591 -1251
  3. package/package.json +1 -1
  4. package/runtime/engine-manifest.json +22 -11
  5. package/runtime/packages/picasso-compaction/cordis.patch.yml +4 -0
  6. package/runtime/packages/picasso-compaction/index.js +623 -0
  7. package/runtime/packages/picasso-compaction/package.json +27 -0
  8. package/runtime/packages/picasso-lean-context/argument-repair.js +422 -0
  9. package/runtime/packages/picasso-lean-context/index.js +23 -2
  10. package/runtime/packages/picasso-model-router/connections.js +49 -3
  11. package/runtime/packages/picasso-model-router/index.js +32 -1
  12. package/runtime/packages/picasso-model-router/package.json +3 -1
  13. package/runtime/packages/picasso-model-router/thinking-default.js +212 -0
  14. package/runtime/packages/picasso-web-search/backends.js +245 -195
  15. package/runtime/packages/picasso-web-search/config.js +75 -27
  16. package/runtime/packages/picasso-web-search/cordis.patch.yml +2 -1
  17. package/runtime/packages/picasso-web-search/failure.js +7 -1
  18. package/runtime/packages/picasso-web-search/index.js +7 -5
  19. package/runtime/packages/picasso-web-search/package.json +6 -0
  20. package/runtime/packages/picasso-web-search/requests.js +339 -0
  21. package/runtime/packages/picasso-web-search/router.js +17 -12
  22. package/runtime/plugins/picasso-compaction/index.js +623 -0
  23. package/runtime/plugins/picasso-compaction/package.json +27 -0
  24. package/runtime/plugins/picasso-lean-context/argument-repair.js +422 -0
  25. package/runtime/plugins/picasso-lean-context/index.js +23 -2
  26. package/runtime/plugins/picasso-model-router/connections.js +49 -3
  27. package/runtime/plugins/picasso-model-router/index.js +32 -1
  28. package/runtime/plugins/picasso-model-router/package.json +3 -1
  29. package/runtime/plugins/picasso-model-router/thinking-default.js +212 -0
  30. package/runtime/plugins/picasso-provider-models/index.js +236 -4
  31. package/runtime/plugins/picasso-web-search/backends.js +245 -195
  32. package/runtime/plugins/picasso-web-search/config.js +75 -27
  33. package/runtime/plugins/picasso-web-search/failure.js +7 -1
  34. package/runtime/plugins/picasso-web-search/index.js +7 -5
  35. package/runtime/plugins/picasso-web-search/package.json +6 -0
  36. package/runtime/plugins/picasso-web-search/requests.js +339 -0
  37. package/runtime/plugins/picasso-web-search/router.js +17 -12
  38. package/runtime/relay/main.mjs +2776 -1494
  39. package/runtime/relay/model-listing.mjs +337 -26
  40. package/runtime/relay/versions-routes.mjs +65 -3
@@ -0,0 +1,212 @@
1
+ // A request for a model that cannot run with thinking off never leaves without a thinking level.
2
+ //
3
+ // The clients choose a level before they send (the TUI's `launchEffortOption`, the Mac's `ModelReasoning.swift`), but a
4
+ // request can reach the engine with none: a headless `picasso run`, a subagent, a schedule, a thread created by another
5
+ // client. For a model whose provider refuses "no thinking" the adapter then sends thinking disabled and the provider
6
+ // answers 400 (Z.ai code 1210: "This model always engages in thinking and cannot be disabled; please use low, high, or
7
+ // max"). `agent/pre-step` (index.js) therefore fills the step's level in the engine, on both surfaces.
8
+ //
9
+ // The rule is the one both clients follow (`@picasso/shared-home/model-reasoning`, `resolveReasoningLevel`), for the
10
+ // case with no pick in this chat:
11
+ //
12
+ // a model always thinks when the person's shared file lists it (`alwaysThinks`, learned from a provider 400), or
13
+ // its id is a known family (FAMILIES), or the levels the engine reports leave out off
14
+ // its level is the level saved for this model (`efforts["<route>/<model>"]`), else the default for every
15
+ // model (`defaultEffort`), each moved to the nearest level the model offers; else the
16
+ // model's own default; else the lowest level it offers; `high` when nothing is known
17
+ //
18
+ // A model that can run without thinking is left exactly as it was sent (no level stays no level), so this adds nothing
19
+ // to any request that worked before.
20
+ //
21
+ // A level the model does not offer is never sent either (owner 2026-11-17: a level saved for one connection's model,
22
+ // carried onto the managed route's model of the same name, failed every prompt with `does not support reasoning
23
+ // effort "max"`). When the engine reports the model's levels, a level it lacks moves to the nearest one it offers, and
24
+ // a model with no levels at all gets none (`supportedThinkingLevel`). A model the engine cannot describe keeps what
25
+ // was sent. OFF_LEVELS, LEVEL_ORDER and FAMILIES restate
26
+ // `packages/shared-home/src/model-reasoning.json`; test/thinking-default.test.mjs fails when they drift from it.
27
+
28
+ export const OFF_LEVELS = Object.freeze(['off', 'none', 'disabled', 'minimal-off']);
29
+ export const LEVEL_ORDER = Object.freeze(['minimal', 'low', 'medium', 'high', 'xhigh', 'max']);
30
+ export const FAMILIES = Object.freeze([
31
+ Object.freeze({ id: 'zai-glm-5.3', model: '(?:^|[^a-z0-9])glm-5[.p-]3(?![0-9])' }),
32
+ Object.freeze({ id: 'gemini-pro', model: '(?:^|[^a-z0-9])gemini-(?:2\\.5|[3-9](?:\\.[0-9]+)?)-pro(?![a-z0-9])|(?:^|[^a-z0-9])gemini-pro-latest(?![a-z0-9])' }),
33
+ Object.freeze({ id: 'minimax-m3.1-flash', model: '(?:^|[^a-z0-9])minimax-m3[.p]1-flash(?![a-z0-9])' }),
34
+ ]);
35
+
36
+ const familyPatterns = FAMILIES.map((family) => new RegExp(family.model, 'iu'));
37
+ const nonEmpty = (value) => typeof value === 'string' && value.length > 0;
38
+ const isRecord = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
39
+
40
+ /** Words that mean "no thinking". */
41
+ export const isOffLevel = (level) => nonEmpty(level) && OFF_LEVELS.includes(level.toLowerCase());
42
+
43
+ /**
44
+ * Whether a model must never run with thinking off. `offered`: the levels the engine reports (undefined = unknown,
45
+ * [] = the model has no reasoning); `learned`: the shared file's `alwaysThinks` refs.
46
+ */
47
+ export function modelAlwaysThinks({ provider, model, offered, learned }) {
48
+ if (Array.isArray(learned) && learned.includes(`${provider}/${model}`)) return true;
49
+ if (familyPatterns.some((pattern) => pattern.test(model))) return true;
50
+ return Array.isArray(offered) && offered.length > 0 && !offered.some(isOffLevel);
51
+ }
52
+
53
+ const rank = (level) => LEVEL_ORDER.indexOf(level.toLowerCase());
54
+
55
+ /** The offered thinking level nearest `level` (exact first, then by level order; ties go to the higher one). */
56
+ function nearest(level, offered) {
57
+ if (isOffLevel(level)) return undefined;
58
+ if (offered === undefined) return level;
59
+ const allowed = offered.filter((id) => !isOffLevel(id));
60
+ const exact = allowed.find((id) => id.toLowerCase() === level.toLowerCase());
61
+ if (exact !== undefined) return exact;
62
+ const wanted = rank(level);
63
+ if (wanted < 0) return undefined;
64
+ let best;
65
+ for (const id of allowed) {
66
+ const at = rank(id);
67
+ if (at < 0) continue;
68
+ const distance = Math.abs(at - wanted);
69
+ if (best === undefined || distance < best.distance || (distance === best.distance && at > best.rank)) best = { id, distance, rank: at };
70
+ }
71
+ return best?.id;
72
+ }
73
+
74
+ /**
75
+ * What an explicit `level` becomes on a model that offers `offered` (the engine's levels; undefined = unknown):
76
+ * undefined = send it as it is, a string = send that level instead (the nearest one offered, ties up), null = send no
77
+ * level (the model has no reasoning, or nothing near it). An off word on a model that offers no off word is left to
78
+ * `requiredThinkingLevel` (the model always thinks).
79
+ */
80
+ export function supportedThinkingLevel(level, offered) {
81
+ if (!nonEmpty(level) || !Array.isArray(offered)) return undefined;
82
+ if (offered.length === 0) return null;
83
+ const exact = offered.find((id) => id.toLowerCase() === level.toLowerCase());
84
+ if (exact !== undefined) return exact === level ? undefined : exact;
85
+ if (isOffLevel(level)) return offered.find(isOffLevel);
86
+ return nearest(level, offered) ?? null;
87
+ }
88
+
89
+ /**
90
+ * The level a request with no usable level must carry, or undefined when it needs none (the model can run without
91
+ * thinking, or has no reasoning at all). `settings`: the shared model-connections document (`efforts`, `defaultEffort`,
92
+ * `alwaysThinks`); `catalogueDefault`: the model's own default level as the engine reports it.
93
+ */
94
+ export function requiredThinkingLevel({ provider, model, offered, catalogueDefault, settings }) {
95
+ if (!nonEmpty(provider) || !nonEmpty(model)) return undefined;
96
+ if (Array.isArray(offered) && offered.length === 0) return undefined;
97
+ const saved = isRecord(settings) ? settings : {};
98
+ if (!modelAlwaysThinks({ provider, model, offered, learned: saved.alwaysThinks })) return undefined;
99
+ const perModel = isRecord(saved.efforts) ? saved.efforts[`${provider}/${model}`] : undefined;
100
+ for (const level of [perModel, saved.defaultEffort]) {
101
+ if (!nonEmpty(level)) continue;
102
+ const usable = nearest(level, offered);
103
+ if (usable !== undefined) return usable;
104
+ }
105
+ if (nonEmpty(catalogueDefault) && !isOffLevel(catalogueDefault) && (offered === undefined || offered.includes(catalogueDefault))) return catalogueDefault;
106
+ if (offered !== undefined) return offered.find((id) => !isOffLevel(id));
107
+ return 'high';
108
+ }
109
+
110
+ /**
111
+ * The `agent/pre-step` guard. `deps`: `{ llm: () => registry | undefined, settings: () => document, log }`. The levels
112
+ * a model offers are asked of the engine once per model (`resolveModelInfo`); a model the engine cannot describe is
113
+ * decided by the shared file and the known families alone.
114
+ */
115
+ export function createThinkingGuard({ llm, settings, log = () => {} }) {
116
+ const known = new Map();
117
+ /** `<route>/<model>/<level>` corrections already logged (once each, not every step). */
118
+ const corrected = new Set();
119
+
120
+ async function describe(provider, model) {
121
+ const ref = `${provider}/${model}`;
122
+ if (known.has(ref)) return known.get(ref);
123
+ let described;
124
+ try {
125
+ const registry = llm();
126
+ if (registry !== undefined && registry !== null && typeof registry.resolveModelInfo === 'function') {
127
+ const info = await registry.resolveModelInfo(provider, model);
128
+ const efforts = Array.isArray(info?.reasoning?.efforts) ? info.reasoning.efforts.map((effort) => effort?.id).filter(nonEmpty) : [];
129
+ const fallback = info?.reasoning?.defaultEffort;
130
+ described = { offered: efforts, ...(nonEmpty(fallback) ? { catalogueDefault: fallback } : {}) };
131
+ known.set(ref, described);
132
+ }
133
+ } catch {
134
+ described = undefined; // not cached: the engine may be able to describe it on a later step
135
+ }
136
+ return described;
137
+ }
138
+
139
+ return {
140
+ /** The level this step's selection needs and does not have; undefined when it is fine as it is. */
141
+ async levelFor(selection) {
142
+ if (!isRecord(selection) || !nonEmpty(selection.provider) || !nonEmpty(selection.model)) return undefined;
143
+ if (nonEmpty(selection.reasoningEffort) && !isOffLevel(selection.reasoningEffort)) return undefined;
144
+ const described = await describe(selection.provider, selection.model);
145
+ let saved;
146
+ try {
147
+ saved = settings();
148
+ } catch {
149
+ saved = undefined;
150
+ }
151
+ return requiredThinkingLevel({
152
+ provider: selection.provider,
153
+ model: selection.model,
154
+ ...(described === undefined ? {} : { offered: described.offered }),
155
+ ...(described?.catalogueDefault === undefined ? {} : { catalogueDefault: described.catalogueDefault }),
156
+ settings: saved,
157
+ });
158
+ },
159
+
160
+ /**
161
+ * The step's explicit level checked against the levels the engine reports for its model (see
162
+ * `supportedThinkingLevel`); undefined when there is nothing to change.
163
+ */
164
+ async correctionFor(selection) {
165
+ if (!isRecord(selection) || !nonEmpty(selection.provider) || !nonEmpty(selection.model) || !nonEmpty(selection.reasoningEffort)) return undefined;
166
+ const described = await describe(selection.provider, selection.model);
167
+ return supportedThinkingLevel(selection.reasoningEffort, described?.offered);
168
+ },
169
+
170
+ /** Sets the level on the step's own selection object (what the engine sends this step). True when it changed. */
171
+ async apply(selection) {
172
+ const correction = await this.correctionFor(selection);
173
+ if (correction !== undefined) {
174
+ const was = selection.reasoningEffort;
175
+ try {
176
+ if (correction === null) delete selection.reasoningEffort;
177
+ else selection.reasoningEffort = correction;
178
+ } catch (error) {
179
+ log(`picasso-model-router: the thinking level for ${selection.provider}/${selection.model} could not be corrected (${error instanceof Error ? error.message : String(error)}).`);
180
+ return false;
181
+ }
182
+ if (selection.reasoningEffort === was) return false;
183
+ const ref = `${selection.provider}/${selection.model}/${was}`;
184
+ if (!corrected.has(ref)) {
185
+ corrected.add(ref);
186
+ log(`picasso-model-router: ${selection.provider}/${selection.model} does not offer thinking level "${was}"; ${correction === null ? 'sending none' : `sending "${correction}"`}.`);
187
+ }
188
+ // A model that always thinks still gets a level when the correction left it with none.
189
+ if (correction === null) {
190
+ const required = await this.levelFor(selection);
191
+ if (required !== undefined) {
192
+ try {
193
+ selection.reasoningEffort = required;
194
+ } catch {
195
+ // left with none: the model's own default
196
+ }
197
+ }
198
+ }
199
+ return true;
200
+ }
201
+ const level = await this.levelFor(selection);
202
+ if (level === undefined) return false;
203
+ try {
204
+ selection.reasoningEffort = level;
205
+ } catch (error) {
206
+ log(`picasso-model-router: the thinking level for ${selection.provider}/${selection.model} could not be set (${error instanceof Error ? error.message : String(error)}).`);
207
+ return false;
208
+ }
209
+ return selection.reasoningEffort === level;
210
+ },
211
+ };
212
+ }
@@ -7,7 +7,13 @@
7
7
  // list {provider} finds the route in dsh's configurable-provider directory (`ctx.llm.listConfigurableProviders`),
8
8
  // reads its profile from settings (endpoint, protocol, headers, `apiKeyEnv`), resolves the key
9
9
  // through `ctx.credentials` (the path llm-pi-ai's `resolveApiKey` takes), GETs the listing and
10
- // returns only `{models:[{id, contextWindow?, reasoningEfforts?:[level…]}], authenticated}`.
10
+ // returns only `{models:[{id, contextWindow?, maxOutput?, input?, reasoningEfforts?:[level…]}],
11
+ // authenticated}`.
12
+ // check {provider} tries the route's stored key against a free, authenticated endpoint of the route (its account
13
+ // endpoint where one is known, else its model listing, which counts only when the same listing
14
+ // refuses a request with no key) and returns `{provider, state, reason?, status?, via?,
15
+ // sameKeyAs}`. It never sends a generation request, so it costs nothing; when no free endpoint
16
+ // can tell a good key from a bad one the answer is `not-tested`, never `working`.
11
17
  // The key is sent only to the route's own configured endpoint (never a caller-supplied URL), never returned, logged or
12
18
  // put in an error; a reply that would contain it is refused.
13
19
  //
@@ -124,7 +130,8 @@ export function advertisedLevels(entry, api) {
124
130
 
125
131
  /**
126
132
  * A listing body (`{data:[…]}`, Gemini's native `{models:[{name:"models/<id>",…}]}` or `{models:{id:{…}}}`) as
127
- * `[{id, contextWindow?, reasoningEfforts?}]`, or undefined.
133
+ * `[{id, contextWindow?, maxOutput?, input?, reasoningEfforts?}]`, or undefined. `input` is `['text','image']` when the
134
+ * entry lists an image input modality, `['text']` when it lists others only, absent when it lists none.
128
135
  */
129
136
  export function parseListing(body, api, options = {}) {
130
137
  let listed;
@@ -141,8 +148,17 @@ export function parseListing(body, api, options = {}) {
141
148
  const id = options.stripModelsPrefix === true ? named?.replace(/^models\//u, '') : named;
142
149
  if (!id || !chatCapable({ ...raw, id })) return [];
143
150
  const contextWindow = capacity(raw.context_window, raw.context_length, raw.contextWindow, raw.max_input_tokens, raw.max_context_length, raw.inputTokenLimit, isRecord(raw.limit) ? raw.limit.context : undefined, isRecord(raw.top_provider) ? raw.top_provider.context_length : undefined, propertyValues(raw.properties).context_window);
151
+ const top = isRecord(raw.top_provider) ? raw.top_provider : {};
152
+ const maxOutput = capacity(raw.max_output_tokens, raw.max_completion_tokens, raw.outputTokenLimit, raw.maxOutput, raw.max_tokens, isRecord(raw.limit) ? raw.limit.output : undefined, top.max_completion_tokens);
153
+ const input = listedInput(raw);
144
154
  const reasoningEfforts = advertisedLevels(raw, api);
145
- return [{ id, ...(contextWindow !== undefined ? { contextWindow } : {}), ...(reasoningEfforts ? { reasoningEfforts } : {}) }];
155
+ return [{
156
+ id,
157
+ ...(contextWindow !== undefined ? { contextWindow } : {}),
158
+ ...(maxOutput !== undefined ? { maxOutput } : {}),
159
+ ...(input !== undefined ? { input } : {}),
160
+ ...(reasoningEfforts ? { reasoningEfforts } : {}),
161
+ }];
146
162
  });
147
163
  return mergeModels([], models);
148
164
  }
@@ -157,6 +173,17 @@ function mergeModels(earlier, later) {
157
173
  return [...byId.values()];
158
174
  }
159
175
 
176
+ /** The input modalities a listing entry states (mirrors the relay's `listedInput`). */
177
+ function listedInput(raw) {
178
+ const architecture = isRecord(raw.architecture) ? raw.architecture : {};
179
+ const modalities = isRecord(raw.modalities) ? raw.modalities : {};
180
+ const stated = [raw.input_modalities, architecture.input_modalities, raw.supported_input_types, modalities.input].find(
181
+ (value) => Array.isArray(value) && value.some((item) => typeof item === 'string'),
182
+ );
183
+ if (stated === undefined) return undefined;
184
+ return stated.some((item) => typeof item === 'string' && item.toLowerCase() === 'image') ? ['text', 'image'] : ['text'];
185
+ }
186
+
160
187
  /** Workers AI's `properties: [{property_id, value}]` as numbers by name. */
161
188
  function propertyValues(value) {
162
189
  const out = {};
@@ -335,6 +362,170 @@ export class ProviderModels {
335
362
  return reply;
336
363
  }
337
364
 
365
+ /**
366
+ * `providerModels/check {provider}` → `{provider, state, reason?, status?, via?, sameKeyAs}`: whether the route's
367
+ * stored key is accepted, asked of an endpoint that costs nothing.
368
+ * state `working` (an authenticated request succeeded where one without the key is refused),
369
+ * `key-rejected` (401/403), `out-of-credit` (402, or the provider's own balance/quota answer),
370
+ * `unreachable` (no answer, 429 or 5xx), `not-tested` (nothing free could tell).
371
+ * reason why, as a code: `invalid` | `refused` | `rate-limited` | `provider-error` | `no-answer` | `no-key` |
372
+ * `no-key-reference` | `key-unreadable` | `no-endpoint` | `no-listing` | `open-listing` | `inconclusive`.
373
+ * via `account` | `models`: which endpoint answered.
374
+ * sameKeyAs other providers whose stored key is this very value (`[{provider, name}]`); values are compared here
375
+ * and never returned.
376
+ * No response text is ever returned: a provider's error body can repeat the key.
377
+ */
378
+ async check(provider) {
379
+ const route = requireString(provider, 'provider');
380
+ const entries = this.directory();
381
+ const entry = entries.find((candidate) => candidate.provider === route);
382
+ if (!entry) throw new ProviderModelsError('not-found', `No provider named ${route}.`, { provider: route });
383
+ const profile = this.profile(entry);
384
+ const answer = (state, fields = {}, sameKeyAs = []) => ({ provider: route, state, ...fields, sameKeyAs });
385
+ const refs = keyRefs(profile, entry);
386
+ if (refs.length === 0) return answer('not-tested', { reason: 'no-key-reference' });
387
+ let held;
388
+ try {
389
+ held = await this.heldKey(refs);
390
+ } catch {
391
+ return answer('not-tested', { reason: 'key-unreadable' });
392
+ }
393
+ if (held === undefined) return answer('not-tested', { reason: 'no-key' });
394
+ const { ref, key } = held;
395
+ const sameKeyAs = await this.sameKeyAs(entries, entry, ref, key);
396
+ if (/[^\x21-\x7e]/.test(key)) return answer('key-rejected', { reason: 'invalid' }, sameKeyAs);
397
+ const baseURL = text(profile.baseURL) ?? text(entry.defaultBaseURL) ?? (await this.cloudflareEndpoint(route));
398
+ if (!baseURL || !/^https?:\/\//i.test(baseURL)) return answer('not-tested', { reason: 'no-endpoint' }, sameKeyAs);
399
+ const api = text(profile.api) ?? 'openai-completions';
400
+ const headers = (withKey) => {
401
+ const out = new Headers();
402
+ if (isRecord(profile.headers)) for (const [header, value] of Object.entries(profile.headers)) if (typeof value === 'string') out.set(header, value);
403
+ out.set('accept', 'application/json');
404
+ if (api === 'anthropic-messages') out.set('anthropic-version', ANTHROPIC_VERSION);
405
+ if (!withKey) return out;
406
+ if (api === 'anthropic-messages') out.set('x-api-key', key);
407
+ else if (isGeminiNative(baseURL)) out.set('x-goog-api-key', key);
408
+ else out.set('authorization', `Bearer ${key}`);
409
+ return out;
410
+ };
411
+ const failed = (probe, via) => {
412
+ if (probe.status === undefined) return answer('unreachable', { reason: 'no-answer', via }, sameKeyAs);
413
+ const fields = { status: probe.status, via };
414
+ if (probe.status === 402 || SPENT_WORDING.test(probe.body)) return answer('out-of-credit', fields, sameKeyAs);
415
+ if (probe.status === 401 || probe.status === 403) return answer('key-rejected', { reason: INVALID_KEY_WORDING.test(probe.body) ? 'invalid' : 'refused', ...fields }, sameKeyAs);
416
+ if (probe.status === 429) return answer('unreachable', { reason: 'rate-limited', ...fields }, sameKeyAs);
417
+ if (probe.status >= 500) return answer('unreachable', { reason: 'provider-error', ...fields }, sameKeyAs);
418
+ return undefined;
419
+ };
420
+
421
+ // An account endpoint needs the key by definition and says whether there is credit left.
422
+ const account = accountEndpoint(baseURL);
423
+ if (account !== undefined) {
424
+ const probe = await this.probe(account.url, headers(true));
425
+ if (probe.status !== undefined && probe.status >= 200 && probe.status < 300) {
426
+ const spent = account.spent(parseJson(probe.body));
427
+ return answer(spent ? 'out-of-credit' : 'working', { status: probe.status, via: 'account' }, sameKeyAs);
428
+ }
429
+ const verdict = failed(probe, 'account');
430
+ if (verdict !== undefined) return verdict;
431
+ }
432
+
433
+ const listing = listingUrl(baseURL, api);
434
+ const withKey = await this.probe(listing, headers(true));
435
+ if (withKey.status === undefined || withKey.status < 200 || withKey.status >= 300) {
436
+ return failed(withKey, 'models') ?? answer('not-tested', { reason: 'no-listing', status: withKey.status, via: 'models' }, sameKeyAs);
437
+ }
438
+ if (parseListing(parseJson(withKey.body), api, { stripModelsPrefix: isGeminiHost(baseURL) }) === undefined) {
439
+ return answer('not-tested', { reason: 'no-listing', via: 'models' }, sameKeyAs);
440
+ }
441
+ // A listing anyone can read proves nothing about the key: it counts only when the same request without the key is refused.
442
+ const withoutKey = await this.probe(listing, headers(false));
443
+ if (withoutKey.status !== undefined && withoutKey.status >= 200 && withoutKey.status < 300) return answer('not-tested', { reason: 'open-listing', via: 'models' }, sameKeyAs);
444
+ if (withoutKey.status === 401 || withoutKey.status === 403) return answer('working', { status: withKey.status, via: 'models' }, sameKeyAs);
445
+ return answer('not-tested', { reason: 'inconclusive', via: 'models' }, sameKeyAs);
446
+ }
447
+
448
+ /** One GET, same-origin redirects only → `{status, body}` (body capped, for wording only), or `{}` when nothing answered. */
449
+ async probe(url, headers) {
450
+ let target = url;
451
+ for (let hop = 0; hop <= MAX_REDIRECTS; hop += 1) {
452
+ let response;
453
+ try {
454
+ response = await this.fetch(target, { method: 'GET', headers, redirect: 'manual', signal: AbortSignal.timeout(LISTING_TIMEOUT_MS) });
455
+ } catch {
456
+ return {};
457
+ }
458
+ const location = response.status >= 300 && response.status < 400 ? response.headers.get('location') : null;
459
+ if (location === null) {
460
+ let body = '';
461
+ try {
462
+ body = (await readCapped(response, MAX_LISTING_BYTES)) ?? '';
463
+ } catch {
464
+ body = '';
465
+ }
466
+ return { status: response.status, body };
467
+ }
468
+ await response.body?.cancel().catch(() => undefined);
469
+ let next;
470
+ try {
471
+ next = new URL(location, target);
472
+ } catch {
473
+ return {};
474
+ }
475
+ // The key rides in a header the runtime would forward: only the same origin is followed.
476
+ if (next.origin !== new URL(target).origin) return {};
477
+ target = next.href;
478
+ }
479
+ return {};
480
+ }
481
+
482
+ /** The first of `refs` the credential store holds → `{ref, key}`; undefined when it holds none. Throws when unreadable. */
483
+ async heldKey(refs) {
484
+ const credentials = this.credentials();
485
+ if (!credentials || typeof credentials.resolve !== 'function') throw new ProviderModelsError('unavailable', 'dsh\'s credentials service is not mounted.');
486
+ for (const ref of refs) {
487
+ const hit = await credentials.resolve(ref);
488
+ const value = typeof hit?.value === 'string' ? hit.value.trim() : '';
489
+ if (value) return { ref, key: value };
490
+ }
491
+ return undefined;
492
+ }
493
+
494
+ /**
495
+ * Other routes whose stored key is the very value this route holds (a key pasted into the wrong provider is the
496
+ * usual cause of an "invalid key" answer). Routes of the same service (the two Prism routes) and routes naming the
497
+ * same reference are left out. Values are compared, never returned.
498
+ */
499
+ async sameKeyAs(entries, entry, ref, key) {
500
+ const service = (id) => String(id ?? '').replace(/^kiro-/u, '');
501
+ const credentials = this.credentials();
502
+ const out = [];
503
+ for (const other of entries) {
504
+ if (other.provider === entry.provider || service(other.provider) === service(entry.provider)) continue;
505
+ let otherProfile;
506
+ try {
507
+ otherProfile = this.profile(other);
508
+ } catch {
509
+ continue;
510
+ }
511
+ for (const otherRef of keyRefs(otherProfile, other)) {
512
+ if (otherRef === ref) continue;
513
+ let hit;
514
+ try {
515
+ hit = await credentials.resolve(otherRef);
516
+ } catch {
517
+ continue;
518
+ }
519
+ if (typeof hit?.value === 'string' && hit.value.trim() === key) {
520
+ out.push({ provider: other.provider, name: text(other.displayName) ?? other.provider });
521
+ break;
522
+ }
523
+ }
524
+ if (out.length >= 3) break;
525
+ }
526
+ return out;
527
+ }
528
+
338
529
  /**
339
530
  * A Workers AI route stores its account as the credential `CLOUDFLARE_ACCOUNT_ID` and no endpoint (each catalog model
340
531
  * carries its own account URL), so its listing endpoint is built from that credential. Undefined for any other route,
@@ -390,7 +581,48 @@ export class ProviderModels {
390
581
  }
391
582
  }
392
583
 
393
- const REMOTE_METHODS = ['list'];
584
+ /** The credential references a route's key can be stored under: the profile's `apiKeyEnv`, then the route's own (`nativeAuth.env`). */
585
+ function keyRefs(profile, entry) {
586
+ const native = isRecord(entry.nativeAuth) && Array.isArray(entry.nativeAuth.env) ? entry.nativeAuth.env : [];
587
+ return [...new Set([text(profile.apiKeyEnv), ...native.map(text)].filter((ref) => ref !== undefined))];
588
+ }
589
+
590
+ /** A provider's wording for a spent balance or allowance (mirrors @picasso/model-router's quota and billing wording). */
591
+ const SPENT_WORDING = /\binsufficient[\s_-]+(?:quota|balance|credits?|funds)\b|\b(?:quota|usage[\s_-]+limit)[\s_-]+(?:exceeded|exhausted|reached)\b|\bexceed(?:ed|s)?[\s_-]+(?:(?:your|the)[\s_-]+)?(?:current[\s_-]+)?quota\b|\b(?:balance|credits?)[\s_-]+(?:exhausted|depleted)\b|\bout[\s_-]+of[\s_-]+(?:credits?|budget)\b|\bpayment[\s_-]+required\b/i;
592
+ /** A provider's own wording for a key it does not recognise (mirrors @picasso/model-router's). */
593
+ const INVALID_KEY_WORDING = /\b(?:invalid|incorrect|unrecogni[sz]ed|malformed)[\s_-]*(?:api[\s_-]*)?key\b|\binvalid_api_key\b|\bapi[\s_-]*key[\s_-]*(?:is[\s_-]*)?(?:invalid|not[\s_-]*valid|incorrect)\b/iu;
594
+
595
+ function parseJson(raw) {
596
+ try {
597
+ return JSON.parse(raw);
598
+ } catch {
599
+ return undefined;
600
+ }
601
+ }
602
+
603
+ /**
604
+ * A free endpoint that only answers a valid key and reports the account's credit, for the hosts that document one:
605
+ * DeepSeek's `GET /user/balance` (`is_available`) and OpenRouter's `GET /api/v1/key` (`data.limit_remaining`).
606
+ * `spent(body)` is true when the provider says nothing is left.
607
+ */
608
+ export function accountEndpoint(baseURL) {
609
+ let host;
610
+ try {
611
+ host = new URL(baseURL).hostname;
612
+ } catch {
613
+ return undefined;
614
+ }
615
+ if (host === 'api.deepseek.com') return { url: 'https://api.deepseek.com/user/balance', spent: (body) => isRecord(body) && body.is_available === false };
616
+ if (host === 'openrouter.ai') {
617
+ return {
618
+ url: 'https://openrouter.ai/api/v1/key',
619
+ spent: (body) => isRecord(body) && isRecord(body.data) && typeof body.data.limit_remaining === 'number' && body.data.limit_remaining <= 0,
620
+ };
621
+ }
622
+ return undefined;
623
+ }
624
+
625
+ const REMOTE_METHODS = ['list', 'check'];
394
626
 
395
627
  Object.defineProperty(ProviderModels.prototype, REMOTE_METHOD_DESCRIPTOR, {
396
628
  configurable: true,