@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.
@@ -3,11 +3,33 @@ import { credentialRef } from '@deepseek-ai/dsh-credentials';
3
3
  import { resolveRetryPolicy } from '@deepseek-ai/dsh-llm';
4
4
  import { createProvider } from '@earendil-works/pi-ai';
5
5
  import { builtinProviders } from '@earendil-works/pi-ai/providers/all';
6
- import { PROTOCOL_STREAMS } from "./catalog-protocols.js";
6
+ import { PROTOCOL_STREAMS } from './catalog-protocols.js';
7
7
  const ERROR_PREFIX = 'dsh-provider-extra: catalog ';
8
- const ROUTE_FIELDS = ['id', 'name', 'source', 'api', 'auth', 'models', 'filter', 'baseURL', 'headers', 'transport', 'fallbackSessionId'];
8
+ const ROUTE_FIELDS = [
9
+ 'id',
10
+ 'name',
11
+ 'source',
12
+ 'api',
13
+ 'auth',
14
+ 'models',
15
+ 'filter',
16
+ 'baseURL',
17
+ 'headers',
18
+ 'transport',
19
+ 'fallbackSessionId',
20
+ ];
9
21
  const MODEL_FIELDS = ['id', 'name', 'aliases', 'template', 'metadata', 'defaultMaxTokens'];
10
- const METADATA_FIELDS = ['api', 'reasoning', 'input', 'cost', 'contextWindow', 'maxTokens', 'thinkingLevelMap', 'headers', 'compat'];
22
+ const METADATA_FIELDS = [
23
+ 'api',
24
+ 'reasoning',
25
+ 'input',
26
+ 'cost',
27
+ 'contextWindow',
28
+ 'maxTokens',
29
+ 'thinkingLevelMap',
30
+ 'headers',
31
+ 'compat',
32
+ ];
11
33
  const REQUIRED_METADATA = ['api', 'reasoning', 'input', 'cost', 'contextWindow', 'maxTokens'];
12
34
  const COST_FIELDS = ['input', 'output', 'cacheRead', 'cacheWrite'];
13
35
  const THINKING_LEVELS = ['off', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max'];
@@ -17,43 +39,103 @@ const CODEX_SOURCE = 'openai-codex';
17
39
  const SESSION_HEADER = 'x-opencode-session';
18
40
  const STREAM_IDLE_TIMEOUT_MS = 300_000;
19
41
  const MAX_REQUEST_IMAGE_BYTES = 20 * 1024 * 1024;
42
+ const MAX_REQUEST_IMAGES = 50;
43
+ const IMAGE_OFFLOAD_COUNT_QUANTUM = 10;
20
44
  const REQUEST_IMAGE_PIXEL_BUDGET = 2048 * 2048;
21
45
  const REQUEST_IMAGE_MAX_BYTES = 1024 * 1024;
22
46
  const HTTP_PROTOCOLS = ['http:', 'https:'];
23
47
  const COMPLETIONS_API = 'openai-completions';
24
48
  const RESPONSES_APIS = ['openai-responses', 'azure-openai-responses', 'openai-codex-responses'];
25
49
  const ANTHROPIC_API = 'anthropic-messages';
26
- const COMPLETIONS_FLAGS = ['supportsStore', 'supportsDeveloperRole', 'supportsReasoningEffort', 'supportsUsageInStreaming', 'supportsFinishReason', 'requiresToolResultName', 'requiresAssistantAfterToolResult', 'requiresThinkingAsText', 'requiresReasoningContentOnAssistantMessages', 'zaiToolStream', 'supportsThinkingTokenBudget', 'supportsOpenAIGrammarTools', 'supportsStrictMode', 'sendSessionAffinityHeaders', 'supportsLongCacheRetention'];
27
- const RESPONSES_FLAGS = ['supportsDeveloperRole', 'supportsLongCacheRetention', 'supportsStrictMode', 'supportsOpenAIGrammarTools', 'supportsAdditionalTools', 'supportsToolSearch', 'supportsExplicitPromptCacheMode', 'supportsMaxOutputTokens'];
28
- const ANTHROPIC_FLAGS = ['supportsEagerToolInputStreaming', 'supportsLongCacheRetention', 'sendSessionAffinityHeaders', 'supportsCacheControlOnTools', 'supportsTemperature', 'forceAdaptiveThinking', 'allowEmptySignature', 'supportsStrictTools', 'supportsMidConvoEffort', 'supportsToolReferences'];
50
+ const COMPLETIONS_FLAGS = [
51
+ 'supportsStore',
52
+ 'supportsDeveloperRole',
53
+ 'supportsReasoningEffort',
54
+ 'supportsUsageInStreaming',
55
+ 'supportsFinishReason',
56
+ 'requiresToolResultName',
57
+ 'requiresAssistantAfterToolResult',
58
+ 'requiresThinkingAsText',
59
+ 'requiresReasoningContentOnAssistantMessages',
60
+ 'zaiToolStream',
61
+ 'supportsThinkingTokenBudget',
62
+ 'supportsOpenAIGrammarTools',
63
+ 'supportsStrictMode',
64
+ 'sendSessionAffinityHeaders',
65
+ 'supportsLongCacheRetention',
66
+ ];
67
+ const RESPONSES_FLAGS = [
68
+ 'supportsDeveloperRole',
69
+ 'supportsLongCacheRetention',
70
+ 'supportsStrictMode',
71
+ 'supportsOpenAIGrammarTools',
72
+ 'supportsAdditionalTools',
73
+ 'supportsToolSearch',
74
+ 'supportsExplicitPromptCacheMode',
75
+ 'supportsMaxOutputTokens',
76
+ ];
77
+ const ANTHROPIC_FLAGS = [
78
+ 'supportsEagerToolInputStreaming',
79
+ 'supportsLongCacheRetention',
80
+ 'sendSessionAffinityHeaders',
81
+ 'supportsCacheControlOnTools',
82
+ 'supportsTemperature',
83
+ 'forceAdaptiveThinking',
84
+ 'allowEmptySignature',
85
+ 'supportsStrictTools',
86
+ 'supportsMidConvoEffort',
87
+ 'supportsToolReferences',
88
+ ];
89
+ const FILTER_NEEDS_SOURCE = 'filter expands the catalog of an installed source';
90
+ const PROTOCOL_REQUIRED = 'a route with no installed source must declare its protocol';
29
91
  const COMPAT_ENUMS = {
30
92
  maxTokensField: ['max_completion_tokens', 'max_tokens'],
31
- thinkingFormat: ['openai', 'openrouter', 'deepseek', 'together', 'baseten', 'zai', 'qwen', 'chat-template', 'qwen-chat-template', 'string-thinking', 'ant-ling'],
93
+ thinkingFormat: [
94
+ 'openai',
95
+ 'openrouter',
96
+ 'deepseek',
97
+ 'together',
98
+ 'baseten',
99
+ 'zai',
100
+ 'qwen',
101
+ 'chat-template',
102
+ 'qwen-chat-template',
103
+ 'string-thinking',
104
+ 'ant-ling',
105
+ ],
32
106
  thinkingTokenBudgetField: ['thinking_token_budget', 'thinking_budget', 'thinking_budget_tokens'],
33
- cacheControlFormat: ['anthropic'], deferredToolsMode: ['kimi'],
107
+ cacheControlFormat: ['anthropic'],
108
+ deferredToolsMode: ['kimi'],
34
109
  sessionAffinityFormat: ['openai', 'openai-nosession', 'openrouter'],
35
110
  };
36
111
  /** @internal Consistent paths make invalid declarations repairable before publication. */
37
112
  export function catalogError(path, reason) {
38
- throw new Error(ERROR_PREFIX + path + ': ' + reason);
113
+ throw new Error(`${ERROR_PREFIX + path}: ${reason}`);
39
114
  }
40
115
  /** @internal Unknown fields must fail rather than look applied. */
41
116
  export function catalogRecord(value, fields, path) {
42
- if (value === null || typeof value !== 'object' || Array.isArray(value)
43
- || ![Object.prototype, null].includes(Object.getPrototypeOf(value)))
117
+ if (value === null ||
118
+ typeof value !== 'object' ||
119
+ Array.isArray(value) ||
120
+ ![Object.prototype, null].includes(Object.getPrototypeOf(value)))
44
121
  catalogError(path, 'expected an object');
45
122
  for (const key of Reflect.ownKeys(value)) {
46
123
  if (typeof key !== 'string' || (fields && !fields.includes(key)))
47
- catalogError(path, 'unknown field ' + String(key));
124
+ catalogError(path, `unknown field ${String(key)}`);
48
125
  const descriptor = Object.getOwnPropertyDescriptor(value, key);
49
- if (!('value' in descriptor))
126
+ // A proxy can list a key it then refuses to describe; that is not a plain value either.
127
+ if (descriptor === undefined || !('value' in descriptor))
50
128
  catalogError(path, 'accessors are not configuration values');
51
129
  }
52
130
  return value;
53
131
  }
54
132
  /** @internal IDs and labels cannot hide accidental whitespace or control characters. */
55
133
  export function catalogString(value, path) {
56
- if (typeof value !== 'string' || !value.trim() || value !== value.trim() || /[\u0000-\u001f\u007f]/u.test(value)) {
134
+ if (typeof value !== 'string' ||
135
+ !value.trim() ||
136
+ value !== value.trim() ||
137
+ // biome-ignore lint/suspicious/noControlCharactersInRegex: rejecting control characters is the point of this validation.
138
+ /[\u0000-\u001f\u007f]/u.test(value)) {
57
139
  catalogError(path, 'expected a nonempty string without surrounding whitespace or control characters');
58
140
  }
59
141
  }
@@ -71,17 +153,25 @@ export function catalogMap(entries) {
71
153
  const map = new Map(entries);
72
154
  const view = Object.freeze({
73
155
  size: map.size,
74
- get: (key) => map.get(key), has: (key) => map.has(key),
75
- keys: () => map.keys(), values: () => map.values(), entries: () => map.entries(),
156
+ get: (key) => map.get(key),
157
+ has: (key) => map.has(key),
158
+ keys: () => map.keys(),
159
+ values: () => map.values(),
160
+ entries: () => map.entries(),
76
161
  [Symbol.iterator]: () => map[Symbol.iterator](),
77
162
  forEach: (callback, thisArg) => {
78
- map.forEach((value, key) => callback.call(thisArg, value, key, view));
163
+ map.forEach((value, key) => {
164
+ callback.call(thisArg, value, key, view);
165
+ });
79
166
  },
80
167
  });
81
168
  return view;
82
169
  }
83
170
  function number(value, path, positive = false) {
84
- if (typeof value !== 'number' || !Number.isFinite(value) || value < 0 || (positive && (!Number.isSafeInteger(value) || value === 0))) {
171
+ if (typeof value !== 'number' ||
172
+ !Number.isFinite(value) ||
173
+ value < 0 ||
174
+ (positive && (!Number.isSafeInteger(value) || value === 0))) {
85
175
  catalogError(path, positive ? 'expected a positive safe integer' : 'expected a finite nonnegative number');
86
176
  }
87
177
  }
@@ -110,51 +200,60 @@ function cost(value, path, tier = false) {
110
200
  const fields = [...COST_FIELDS, ...(tier ? ['inputTokensAbove'] : ['tiers'])];
111
201
  const data = catalogRecord(value, fields, path);
112
202
  for (const key of COST_FIELDS)
113
- number(data[key], path + '.' + key);
203
+ number(data[key], `${path}.${key}`);
114
204
  if (tier)
115
- number(data.inputTokensAbove, path + '.inputTokensAbove');
205
+ number(data.inputTokensAbove, `${path}.inputTokensAbove`);
116
206
  else if ('tiers' in data) {
117
207
  if (!Array.isArray(data.tiers))
118
208
  catalogError(path, 'tiers must be an array');
119
209
  for (const entry of data.tiers)
120
- cost(entry, path + '.tiers', true);
210
+ cost(entry, `${path}.tiers`, true);
121
211
  }
122
212
  }
123
213
  /** Only metadata the managed protocols can honor belongs in configuration. */
124
214
  function compat(value, api, path) {
125
- const flags = api === COMPLETIONS_API ? COMPLETIONS_FLAGS : RESPONSES_APIS.includes(api) ? RESPONSES_FLAGS
126
- : api === ANTHROPIC_API ? ANTHROPIC_FLAGS : [];
127
- const enums = api === COMPLETIONS_API ? Object.keys(COMPAT_ENUMS) : RESPONSES_APIS.includes(api) ? ['sessionAffinityFormat'] : [];
215
+ const flags = api === COMPLETIONS_API
216
+ ? COMPLETIONS_FLAGS
217
+ : RESPONSES_APIS.includes(api)
218
+ ? RESPONSES_FLAGS
219
+ : api === ANTHROPIC_API
220
+ ? ANTHROPIC_FLAGS
221
+ : [];
222
+ const enums = api === COMPLETIONS_API
223
+ ? Object.keys(COMPAT_ENUMS)
224
+ : RESPONSES_APIS.includes(api)
225
+ ? ['sessionAffinityFormat']
226
+ : [];
128
227
  const data = catalogRecord(value, [...flags, ...enums], path);
129
228
  for (const [key, member] of Object.entries(data)) {
130
229
  if (flags.includes(key)) {
131
230
  if (typeof member !== 'boolean')
132
- catalogError(path, key + ' must be boolean');
231
+ catalogError(path, `${key} must be boolean`);
133
232
  }
134
- else if (!COMPAT_ENUMS[key].includes(member))
135
- catalogError(path, 'invalid ' + key);
233
+ else if (!COMPAT_ENUMS[key]?.includes(member))
234
+ catalogError(path, `invalid ${key}`);
136
235
  }
137
236
  }
138
237
  function metadata(value, api, path) {
139
238
  const data = catalogRecord(value, METADATA_FIELDS, path);
140
239
  for (const [key, member] of Object.entries(data)) {
141
240
  if (key === 'api')
142
- catalogString(member, path + '.api');
241
+ catalogString(member, `${path}.api`);
143
242
  else if (key === 'reasoning') {
144
243
  if (typeof member !== 'boolean')
145
244
  catalogError(path, 'reasoning must be boolean');
146
245
  }
147
246
  else if (key === 'input') {
148
- const modes = strings(member, path + '.input');
149
- if (!modes.length || modes.some(mode => !['text', 'image'].includes(mode)))
247
+ const modes = strings(member, `${path}.input`);
248
+ if (!modes.length || modes.some((mode) => !['text', 'image'].includes(mode)))
150
249
  catalogError(path, 'invalid input modalities');
151
250
  }
152
251
  else if (key === 'contextWindow' || key === 'maxTokens')
153
- number(member, path + '.' + key, true);
252
+ number(member, `${path}.${key}`, true);
154
253
  else if (key === 'cost')
155
- cost(member, path + '.cost');
254
+ cost(member, `${path}.cost`);
156
255
  else if (key === 'headers')
157
- headers(member, path + '.headers');
256
+ headers(member, `${path}.headers`);
158
257
  else if (key === 'thinkingLevelMap') {
159
258
  for (const level of Object.values(catalogRecord(member, THINKING_LEVELS, path))) {
160
259
  if (level !== null)
@@ -162,7 +261,7 @@ function metadata(value, api, path) {
162
261
  }
163
262
  }
164
263
  else if (key === 'compat')
165
- compat(member, data.api ?? api ?? '', path + '.compat');
264
+ compat(member, data.api ?? api ?? '', `${path}.compat`);
166
265
  }
167
266
  }
168
267
  /** Provider auth contains functions, so structuredClone cannot detach its declaration. */
@@ -178,34 +277,43 @@ function detachedAuth(value) {
178
277
  function routeOptions(options, config) {
179
278
  if (!config.headers && !config.transport && config.source !== GO_SOURCE)
180
279
  return options;
181
- const headers = Object.fromEntries([...Object.entries(config.headers ?? {}), ...Object.entries(options?.headers ?? {})]
182
- .map(([key, value]) => [key.toLowerCase(), value]));
280
+ const headers = Object.fromEntries([...Object.entries(config.headers ?? {}), ...Object.entries(options?.headers ?? {})].map(([key, value]) => [key.toLowerCase(), value]));
183
281
  const sessionId = options?.sessionId ?? config.fallbackSessionId;
184
282
  if (config.source === GO_SOURCE && sessionId !== undefined)
185
283
  headers[SESSION_HEADER] = sessionId;
186
- return { ...options, headers, ...(config.transport === undefined ? {} : { transport: config.transport }) };
284
+ return {
285
+ ...options,
286
+ headers,
287
+ ...(config.transport === undefined ? {} : { transport: config.transport }),
288
+ };
187
289
  }
188
290
  /** `*` is the only wildcard; every other character matches itself. */
189
291
  function patterns(value, path) {
190
292
  const list = strings(value, path);
191
293
  if (list.length === 0)
192
294
  catalogError(path, 'expected at least one pattern');
193
- return list.map(pattern => new RegExp('^' + pattern.split('*').map(part => part.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')).join('.*') + '$'));
295
+ return list.map((pattern) => new RegExp('^' +
296
+ pattern
297
+ .split('*')
298
+ .map((part) => part.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'))
299
+ .join('.*') +
300
+ '$'));
194
301
  }
195
302
  /** Expansion keeps every installed fact, so curating a catalog costs no restatement. */
196
303
  function filteredModels(filter, source, input, path) {
197
304
  const data = catalogRecord(filter, ['include', 'exclude'], path);
198
- const include = 'include' in data ? patterns(data.include, path + '.include') : undefined;
199
- const exclude = 'exclude' in data ? patterns(data.exclude, path + '.exclude') : undefined;
305
+ const include = 'include' in data ? patterns(data.include, `${path}.include`) : undefined;
306
+ const exclude = 'exclude' in data ? patterns(data.exclude, `${path}.exclude`) : undefined;
200
307
  if (include === undefined && exclude === undefined)
201
308
  catalogError(path, 'declare include, exclude, or both');
202
- return source.getModels()
203
- .filter(model => (include === undefined || include.some(pattern => pattern.test(model.id)))
204
- && !(exclude ?? []).some(pattern => pattern.test(model.id)))
205
- .map(model => {
309
+ return source
310
+ .getModels()
311
+ .filter((model) => (include === undefined || include.some((pattern) => pattern.test(model.id))) &&
312
+ !(exclude ?? []).some((pattern) => pattern.test(model.id)))
313
+ .map((model) => {
206
314
  const baseUrl = input.baseURL ?? model.baseUrl ?? source.baseUrl;
207
315
  if (baseUrl === undefined)
208
- catalogError(path, 'model "' + model.id + '" publishes no endpoint; declare baseURL');
316
+ catalogError(path, `model "${model.id}" publishes no endpoint; declare baseURL`);
209
317
  return structuredClone({ ...model, provider: input.id, baseUrl });
210
318
  });
211
319
  }
@@ -223,39 +331,48 @@ function harnessApiKeyAuth(name) {
223
331
  export function buildCatalogProfile(input) {
224
332
  const path = 'provider';
225
333
  const raw = catalogRecord(input, ROUTE_FIELDS, path);
226
- catalogString(raw.id, path + '.id');
227
- catalogString(raw.name, path + '.name');
334
+ catalogString(raw.id, `${path}.id`);
335
+ catalogString(raw.name, `${path}.name`);
228
336
  // No backend list gates a profile: `source` names an installed pi-ai provider and
229
337
  // anything else is the user's own endpoint, whose protocol they declare.
230
- const source = 'source' in raw ? (catalogString(raw.source, path + '.source'), builtinProviders().find(provider => provider.id === raw.source)) : undefined;
338
+ if ('source' in raw)
339
+ catalogString(raw.source, `${path}.source`);
340
+ const source = 'source' in raw ? builtinProviders().find((provider) => provider.id === raw.source) : undefined;
231
341
  if ('source' in raw && source === undefined)
232
- catalogError(path + '.source', 'unknown installed provider ' + raw.source);
233
- const declaredApi = 'api' in raw ? (catalogString(raw.api, path + '.api'), raw.api) : undefined;
342
+ catalogError(`${path}.source`, `unknown installed provider ${raw.source}`);
343
+ if ('api' in raw)
344
+ catalogString(raw.api, `${path}.api`);
345
+ const declaredApi = 'api' in raw ? raw.api : undefined;
234
346
  if (source === undefined) {
235
347
  if (declaredApi === undefined)
236
- catalogError(path + '.api', 'a route with no installed source must declare its protocol');
348
+ catalogError(`${path}.api`, PROTOCOL_REQUIRED);
237
349
  if (!(declaredApi in PROTOCOL_STREAMS))
238
- catalogError(path + '.api', 'unsupported protocol ' + declaredApi + '; this build implements ' + Object.keys(PROTOCOL_STREAMS).join(', '));
350
+ catalogError(`${path}.api`, 'unsupported protocol ' +
351
+ declaredApi +
352
+ '; this build implements ' +
353
+ Object.keys(PROTOCOL_STREAMS).join(', '));
239
354
  }
240
355
  else if (declaredApi !== undefined)
241
- catalogError(path + '.api', 'api belongs to a route with no installed source');
242
- const auth = 'auth' in raw ? catalogRecord(raw.auth, ['apiKeyRef', 'credentialProvider'], path + '.auth') : undefined;
356
+ catalogError(`${path}.api`, 'api belongs to a route with no installed source');
357
+ const auth = 'auth' in raw
358
+ ? catalogRecord(raw.auth, ['apiKeyRef', 'credentialProvider'], `${path}.auth`)
359
+ : undefined;
243
360
  if (auth !== undefined) {
244
361
  if (Object.keys(auth).length !== 1)
245
- catalogError(path + '.auth', 'choose exactly one credential mode');
362
+ catalogError(`${path}.auth`, 'choose exactly one credential mode');
246
363
  if ('apiKeyRef' in auth) {
247
364
  if (source?.id === CODEX_SOURCE)
248
- catalogError(path + '.auth', 'openai-codex requires credentialProvider OAuth');
249
- catalogString(auth.apiKeyRef, path + '.auth.apiKeyRef');
365
+ catalogError(`${path}.auth`, 'openai-codex requires credentialProvider OAuth');
366
+ catalogString(auth.apiKeyRef, `${path}.auth.apiKeyRef`);
250
367
  credentialRef(auth.apiKeyRef);
251
368
  }
252
369
  else if (source === undefined)
253
- catalogError(path + '.auth', 'credentialProvider needs an installed source to own the grant');
370
+ catalogError(`${path}.auth`, 'credentialProvider needs an installed source to own the grant');
254
371
  else if (auth.credentialProvider !== source.id)
255
- catalogError(path + '.auth', 'credentialProvider must equal source');
372
+ catalogError(`${path}.auth`, 'credentialProvider must equal source');
256
373
  }
257
374
  if ('baseURL' in raw) {
258
- catalogString(raw.baseURL, path + '.baseURL');
375
+ catalogString(raw.baseURL, `${path}.baseURL`);
259
376
  let url;
260
377
  try {
261
378
  url = new URL(raw.baseURL);
@@ -267,52 +384,53 @@ export function buildCatalogProfile(input) {
267
384
  catalogError(path, 'invalid baseURL');
268
385
  }
269
386
  if ('headers' in raw)
270
- headers(raw.headers, path + '.headers');
271
- if ('transport' in raw && (!TRANSPORTS.includes(raw.transport) || source?.id !== CODEX_SOURCE)) {
272
- catalogError(path + '.transport', 'transport requires openai-codex and a supported mode');
387
+ headers(raw.headers, `${path}.headers`);
388
+ if ('transport' in raw &&
389
+ (!TRANSPORTS.includes(raw.transport) || source?.id !== CODEX_SOURCE)) {
390
+ catalogError(`${path}.transport`, 'transport requires openai-codex and a supported mode');
273
391
  }
274
392
  if ('fallbackSessionId' in raw) {
275
- catalogString(raw.fallbackSessionId, path + '.fallbackSessionId');
393
+ catalogString(raw.fallbackSessionId, `${path}.fallbackSessionId`);
276
394
  if (source?.id !== GO_SOURCE)
277
395
  catalogError(path, 'fallbackSessionId requires opencode-go source');
278
396
  }
279
397
  if (source === undefined && !('baseURL' in raw))
280
- catalogError(path + '.baseURL', 'a route with no installed source must declare its endpoint');
281
- if (('models' in raw) === ('filter' in raw))
398
+ catalogError(`${path}.baseURL`, 'a route with no installed source must declare its endpoint');
399
+ if ('models' in raw === 'filter' in raw)
282
400
  catalogError(path, 'declare exactly one of models or filter');
283
401
  const declarations = 'filter' in raw ? undefined : raw.models;
284
402
  if (declarations !== undefined && !Array.isArray(declarations))
285
- catalogError(path + '.models', 'expected an explicit array');
403
+ catalogError(`${path}.models`, 'expected an explicit array');
286
404
  if ('filter' in raw && source === undefined)
287
- catalogError(path + '.filter', 'filter expands the catalog of an installed source');
405
+ catalogError(`${path}.filter`, FILTER_NEEDS_SOURCE);
288
406
  const installed = source?.getModels();
289
407
  const names = new Set();
290
408
  const configuredMaxTokens = new Map();
291
409
  const models = declarations === undefined
292
- ? filteredModels(raw.filter, source, input, path + '.filter')
410
+ ? filteredModels(raw.filter, source ?? catalogError(`${path}.filter`, FILTER_NEEDS_SOURCE), input, `${path}.filter`)
293
411
  : declarations.map((entry, index) => {
294
- const declaration = path + ' "' + raw.id + '".models[' + index + ']';
412
+ const declaration = `${path} "${raw.id}".models[${index}]`;
295
413
  const spec = catalogRecord(entry, MODEL_FIELDS, declaration);
296
- catalogString(spec.id, declaration + '.id');
297
- catalogString(spec.name, declaration + '.name');
414
+ catalogString(spec.id, `${declaration}.id`);
415
+ catalogString(spec.name, `${declaration}.name`);
298
416
  // One refused declaration must be repairable from the message alone: an
299
417
  // index into a catalog that runs to dozens of entries names neither the
300
418
  // route nor the model, which is how a stale id a newer line's vendor
301
419
  // dropped reached a reader as provider.models[5].
302
- const location = declaration + ' "' + spec.id + '"';
303
- const aliases = 'aliases' in spec ? strings(spec.aliases, location + '.aliases') : [];
420
+ const location = `${declaration} "${spec.id}"`;
421
+ const aliases = 'aliases' in spec ? strings(spec.aliases, `${location}.aliases`) : [];
304
422
  for (const name of [spec.id, ...aliases]) {
305
423
  if (names.has(name))
306
- catalogError(location, 'duplicate model id or alias ' + name);
424
+ catalogError(location, `duplicate model id or alias ${name}`);
307
425
  names.add(name);
308
426
  }
309
427
  if ('template' in spec)
310
- catalogString(spec.template, location + '.template');
311
- const template = installed?.find(model => model.id === (spec.template ?? spec.id));
428
+ catalogString(spec.template, `${location}.template`);
429
+ const template = installed?.find((model) => model.id === (spec.template ?? spec.id));
312
430
  if ('template' in spec && !template)
313
- catalogError(location, 'unknown template ' + spec.template);
431
+ catalogError(location, `unknown template ${spec.template}`);
314
432
  if ('metadata' in spec)
315
- metadata(spec.metadata, template?.api ?? declaredApi, location + '.metadata');
433
+ metadata(spec.metadata, template?.api ?? declaredApi, `${location}.metadata`);
316
434
  const overrides = spec.metadata;
317
435
  if (!template) {
318
436
  for (const key of REQUIRED_METADATA) {
@@ -320,55 +438,82 @@ export function buildCatalogProfile(input) {
320
438
  if (key === 'api' && declaredApi !== undefined)
321
439
  continue;
322
440
  if (!overrides || !(key in overrides))
323
- catalogError(location, 'unknown model requires complete metadata: missing ' + key);
441
+ catalogError(location, `unknown model requires complete metadata: missing ${key}`);
324
442
  }
325
443
  }
326
444
  if ('defaultMaxTokens' in spec) {
327
- number(spec.defaultMaxTokens, location + '.defaultMaxTokens', true);
445
+ number(spec.defaultMaxTokens, `${location}.defaultMaxTokens`, true);
328
446
  const limit = spec.defaultMaxTokens;
329
- if (limit > (overrides?.maxTokens ?? template.maxTokens)) {
330
- catalogError(location + '.defaultMaxTokens', 'exceeds model maxTokens');
447
+ const maxTokens = overrides?.maxTokens ?? template?.maxTokens;
448
+ if (maxTokens === undefined)
449
+ catalogError(location, 'unknown model requires complete metadata: missing maxTokens');
450
+ if (limit > maxTokens) {
451
+ catalogError(`${location}.defaultMaxTokens`, 'exceeds model maxTokens');
331
452
  }
332
453
  configuredMaxTokens.set(spec.id, limit);
333
454
  }
334
455
  const api = overrides?.api ?? template?.api ?? declaredApi;
335
456
  // Inherited compatibility and thinking metadata belong to the template's protocol.
336
457
  if (template && api !== template.api)
337
- catalogError(location + '.metadata.api', 'cannot change a template-backed protocol');
458
+ catalogError(`${location}.metadata.api`, 'cannot change a template-backed protocol');
338
459
  if (declaredApi !== undefined && api !== declaredApi)
339
- catalogError(location + '.metadata.api', 'a route with no installed source speaks its declared protocol');
340
- if (installed !== undefined && !installed.some(model => model.api === api))
341
- catalogError(location, 'source does not describe API ' + api);
460
+ catalogError(`${location}.metadata.api`, 'a route with no installed source speaks its declared protocol');
461
+ if (installed !== undefined && !installed.some((model) => model.api === api))
462
+ catalogError(location, `source does not describe API ${api}`);
342
463
  const baseUrl = input.baseURL ?? template?.baseUrl ?? source?.baseUrl;
343
464
  if (baseUrl === undefined)
344
465
  catalogError(location, 'unknown model requires provider baseURL');
345
- return freezeCatalogValue(structuredClone({ ...template, ...overrides, id: spec.id, name: spec.name, api, provider: input.id, baseUrl }));
466
+ return freezeCatalogValue(structuredClone({
467
+ ...template,
468
+ ...overrides,
469
+ id: spec.id,
470
+ name: spec.name,
471
+ api,
472
+ provider: input.id,
473
+ baseUrl,
474
+ }));
346
475
  });
347
476
  const config = freezeCatalogValue(structuredClone(input));
348
477
  // A route with no installed source borrows no vendor behavior: pi-ai's own
349
478
  // implementation for the declared protocol streams it, under this route's facts.
350
479
  const routed = source === undefined
351
480
  ? createProvider({
352
- id: config.id, name: config.name, baseUrl: config.baseURL, headers: config.headers,
481
+ id: config.id,
482
+ name: config.name,
483
+ baseUrl: config.baseURL,
484
+ headers: config.headers,
353
485
  auth: { apiKey: harnessApiKeyAuth(config.name) },
354
- models: freezeCatalogValue(models), api: PROTOCOL_STREAMS[declaredApi],
486
+ models: freezeCatalogValue(models),
487
+ api: (declaredApi === undefined ? undefined : PROTOCOL_STREAMS[declaredApi]) ??
488
+ catalogError(`${path}.api`, PROTOCOL_REQUIRED),
355
489
  })
356
490
  : {
357
- id: config.id, name: config.name, baseUrl: config.baseURL ?? source.baseUrl,
491
+ id: config.id,
492
+ name: config.name,
493
+ baseUrl: config.baseURL ?? source.baseUrl,
358
494
  auth: detachedAuth(source.auth),
359
495
  getModels: () => freezeCatalogValue(models),
360
496
  stream: (model, context, options) => source.stream(model, context, routeOptions(options, config)),
361
497
  streamSimple: (model, context, options) => source.streamSimple(model, context, routeOptions(options, config)),
362
498
  };
363
499
  return freezeCatalogValue({
364
- provider: config.id, displayName: config.name,
365
- ...(config.auth !== undefined && 'apiKeyRef' in config.auth ? { apiKeyEnv: credentialRef(config.auth.apiKeyRef) } : {}),
500
+ provider: config.id,
501
+ displayName: config.name,
502
+ ...(config.auth !== undefined && 'apiKeyRef' in config.auth
503
+ ? { apiKeyEnv: credentialRef(config.auth.apiKeyRef) }
504
+ : {}),
366
505
  ...(config.baseURL === undefined ? {} : { baseURL: config.baseURL }),
367
506
  ...(config.headers === undefined ? {} : { headers: config.headers }),
368
507
  ...(config.transport === undefined ? {} : { transport: config.transport }),
369
- streamIdleTimeoutMs: STREAM_IDLE_TIMEOUT_MS, maxRequestImageBytes: MAX_REQUEST_IMAGE_BYTES,
370
- requestImagePixelBudget: REQUEST_IMAGE_PIXEL_BUDGET, requestImageMaxBytes: REQUEST_IMAGE_MAX_BYTES,
508
+ streamIdleTimeoutMs: STREAM_IDLE_TIMEOUT_MS,
509
+ maxRequestImageBytes: MAX_REQUEST_IMAGE_BYTES,
510
+ maxRequestImages: MAX_REQUEST_IMAGES,
511
+ imageOffloadCountQuantum: IMAGE_OFFLOAD_COUNT_QUANTUM,
512
+ requestImagePixelBudget: REQUEST_IMAGE_PIXEL_BUDGET,
513
+ requestImageMaxBytes: REQUEST_IMAGE_MAX_BYTES,
371
514
  retryPolicy: resolveRetryPolicy(undefined, ERROR_PREFIX + config.id),
372
- modelErrors: catalogMap([]), configuredMaxTokens: catalogMap(configuredMaxTokens), piProvider: routed,
515
+ modelErrors: catalogMap([]),
516
+ configuredMaxTokens: catalogMap(configuredMaxTokens),
517
+ piProvider: routed,
373
518
  });
374
519
  }