@pal-code/core 0.0.15 → 0.0.17

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.
@@ -0,0 +1,250 @@
1
+ /**
2
+ * Chat Completions protocol adapter — the OpenAI-compatible streaming wire
3
+ * format used by every built-in provider. Extracted from the provider class so
4
+ * `stream()` can dispatch to another protocol per model.
5
+ */
6
+
7
+ import type {StreamEvent, Usage} from './types.js';
8
+ import {log} from '../logger.js';
9
+
10
+ export interface ToolDef {
11
+ type: 'function';
12
+ function: {
13
+ name: string;
14
+ description: string;
15
+ parameters: Record<string, unknown>;
16
+ };
17
+ }
18
+
19
+ /** Accumulated tool call state during streaming. */
20
+ interface ToolCallAccum {
21
+ id: string;
22
+ name: string;
23
+ arguments: string;
24
+ extra_content?: Record<string, unknown>;
25
+ /** Insertion order — used to emit parallel calls in the order they arrived. */
26
+ seq: number;
27
+ }
28
+
29
+ export interface ChatStreamOptions {
30
+ id: string;
31
+ baseUrl: string;
32
+ /** Bare model id (prefix already stripped). */
33
+ model: string;
34
+ messages: Array<Record<string, unknown>>;
35
+ tools?: ToolDef[];
36
+ headers: Record<string, string>;
37
+ signal?: AbortSignal;
38
+ }
39
+
40
+ /**
41
+ * Pull cache-hit token counts out of an OpenAI-compatible usage object.
42
+ * Field names differ per provider:
43
+ * - DeepSeek: prompt_cache_hit_tokens
44
+ * - OpenAI: prompt_tokens_details.cached_tokens
45
+ * - OpenRouter: prompt_tokens_details.cached_tokens (or cache_read_input_tokens)
46
+ * - Anthropic: cache_read_input_tokens
47
+ * Returns undefined when the provider reports nothing.
48
+ */
49
+ function extractCachedTokens(usage: Record<string, unknown>): number | undefined {
50
+ const direct =
51
+ usage.prompt_cache_hit_tokens ??
52
+ usage.cache_read_input_tokens ??
53
+ (usage.prompt_tokens_details as Record<string, unknown> | undefined)?.cached_tokens;
54
+ return typeof direct === 'number' ? direct : undefined;
55
+ }
56
+
57
+ export async function* streamChat(opts: ChatStreamOptions): AsyncGenerator<StreamEvent> {
58
+ const body: Record<string, unknown> = {
59
+ model: opts.model,
60
+ messages: opts.messages,
61
+ stream: true,
62
+ stream_options: {include_usage: true},
63
+ };
64
+
65
+ // Forward tools if provided — MUST be included in every request with tools
66
+ if (opts.tools && opts.tools.length > 0) {
67
+ body.tools = opts.tools;
68
+ }
69
+
70
+ log('request', {
71
+ provider: opts.id,
72
+ baseUrl: opts.baseUrl,
73
+ model: body.model,
74
+ messageCount: opts.messages.length,
75
+ toolCount: opts.tools?.length ?? 0,
76
+ messages: opts.messages,
77
+ });
78
+
79
+ const res = await fetch(`${opts.baseUrl}/chat/completions`, {
80
+ method: 'POST',
81
+ headers: opts.headers,
82
+ body: JSON.stringify(body),
83
+ signal: opts.signal,
84
+ });
85
+
86
+ if (!res.ok) {
87
+ const err = await res.text();
88
+ log('response-error', {status: res.status, body: err});
89
+ yield {type: 'error', content: `API ${res.status}: ${err}`};
90
+ return;
91
+ }
92
+
93
+ const reader = res.body?.getReader();
94
+ if (!reader) {
95
+ yield {type: 'error', content: 'No response body'};
96
+ return;
97
+ }
98
+
99
+ const decoder = new TextDecoder();
100
+ let buffer = '';
101
+ const toolCallAccumulators = new Map<string, ToolCallAccum>();
102
+ let toolCallSeq = 0;
103
+ let lastUsage: Usage | undefined;
104
+ let finishSeen = false;
105
+
106
+ /** Emit accumulated tool calls in arrival order. */
107
+ const collectToolCalls = (): StreamEvent[] => {
108
+ const ordered = [...toolCallAccumulators.values()].sort((a, b) => a.seq - b.seq);
109
+ const events: StreamEvent[] = [];
110
+ for (const tc of ordered) {
111
+ if (!tc.name) continue;
112
+ events.push({
113
+ type: 'tool_use',
114
+ toolCall: {
115
+ id: tc.id || `call_${Math.random().toString(36).slice(2, 10)}`,
116
+ name: tc.name,
117
+ arguments: tc.arguments || '{}',
118
+ extraContent: tc.extra_content,
119
+ },
120
+ });
121
+ }
122
+ toolCallAccumulators.clear();
123
+ return events;
124
+ };
125
+
126
+ while (true) {
127
+ const {done, value} = await reader.read();
128
+ if (done) break;
129
+
130
+ buffer += decoder.decode(value, {stream: true});
131
+ const lines = buffer.split('\n');
132
+ buffer = lines.pop() ?? '';
133
+
134
+ for (const line of lines) {
135
+ const trimmed = line.trim();
136
+ if (!trimmed.startsWith('data: ')) continue;
137
+ const data = trimmed.slice(6);
138
+ if (data === '[DONE]') continue;
139
+
140
+ try {
141
+ // Providers/gateways occasionally emit raw NUL bytes, which make
142
+ // JSON.parse throw — the catch below would then drop the whole chunk,
143
+ // losing tool-call argument fragments. Strip them before parsing.
144
+ const parsed = JSON.parse(data.replaceAll('\u0000', ''));
145
+ const choice = parsed.choices?.[0];
146
+
147
+ // Extract usage from chunk (Gemini puts it in the last chunk)
148
+ if (parsed.usage) {
149
+ lastUsage = {
150
+ promptTokens: parsed.usage.prompt_tokens ?? 0,
151
+ completionTokens: parsed.usage.completion_tokens ?? 0,
152
+ totalTokens: parsed.usage.total_tokens ?? 0,
153
+ cachedTokens: extractCachedTokens(parsed.usage),
154
+ };
155
+ log('usage', lastUsage);
156
+ }
157
+
158
+ // Usage can also appear without choices (Gemini style)
159
+ if (!choice && parsed.usage) continue;
160
+
161
+ const delta = choice.delta;
162
+
163
+ // Text content — strip escaped NULs that survive JSON.parse
164
+ // (stray null bytes corrupt rendered text and commands downstream).
165
+ if (delta?.content) {
166
+ yield {type: 'text', content: delta.content.replaceAll('\u0000', '')};
167
+ }
168
+
169
+ // Thinking content — DeepSeek-style `reasoning_content` and gateway
170
+ // `reasoning` (string or content-part array). Display-only downstream.
171
+ const thinking = delta?.reasoning_content ?? delta?.reasoning;
172
+ if (typeof thinking === 'string' && thinking) {
173
+ yield {type: 'thinking', content: thinking.replaceAll('\u0000', '')};
174
+ } else if (Array.isArray(thinking)) {
175
+ const text = thinking
176
+ .map((part) => (typeof part === 'string' ? part : part?.text))
177
+ .filter((t): t is string => typeof t === 'string' && t.length > 0)
178
+ .join('');
179
+ if (text) yield {type: 'thinking', content: text.replaceAll('\u0000', '')};
180
+ }
181
+
182
+ // Tool calls — accumulate arguments across chunks.
183
+ // OpenAI/DeepSeek stream one call as [id+name] then [argument fragments],
184
+ // where only `index` repeats across chunks. Some providers (Gemini) have
185
+ // been observed reusing index 0 across parallel calls, so a *new id* on an
186
+ // already-named index starts a fresh accumulator instead of merging.
187
+ if (delta?.tool_calls) {
188
+ for (const tc of delta.tool_calls) {
189
+ const idxKey = String(tc.index ?? 0);
190
+ let existing = toolCallAccumulators.get(idxKey);
191
+
192
+ if (existing && tc.id && existing.id && tc.id !== existing.id) {
193
+ // Same index, different call — park the previous one under a unique key.
194
+ toolCallAccumulators.delete(idxKey);
195
+ toolCallAccumulators.set(`${idxKey}#${existing.seq}`, existing);
196
+ existing = undefined;
197
+ }
198
+
199
+ if (!existing) {
200
+ existing = {
201
+ id: '',
202
+ name: '',
203
+ arguments: '',
204
+ extra_content: undefined,
205
+ seq: toolCallSeq++,
206
+ };
207
+ toolCallAccumulators.set(idxKey, existing);
208
+ }
209
+
210
+ // Strip NULs at the read point: escaped null bytes survive
211
+ // JSON.parse and would otherwise corrupt ids/names/arguments.
212
+ if (tc.id) existing.id = tc.id.replaceAll('\u0000', '');
213
+ if (tc.function?.name) existing.name = tc.function.name.replaceAll('\u0000', '');
214
+ if (tc.function?.arguments)
215
+ existing.arguments += tc.function.arguments.replaceAll('\u0000', '');
216
+ // Capture Gemini's extra_content (contains thought_signature)
217
+ if (tc.extra_content && !existing.extra_content) {
218
+ existing.extra_content = tc.extra_content;
219
+ }
220
+ }
221
+ }
222
+
223
+ // Finish reason — emit accumulated tool calls once, but keep reading:
224
+ // OpenAI-compatible providers send the usage-only chunk *after* the
225
+ // finish_reason chunk, so returning here would drop token usage.
226
+ if (choice.finish_reason === 'tool_calls') {
227
+ for (const ev of collectToolCalls()) yield ev;
228
+ finishSeen = true;
229
+ continue;
230
+ }
231
+
232
+ // Normal finish — also emit any accumulated tool calls
233
+ // (Gemini sends finish_reason="stop" even with tool calls)
234
+ if (choice.finish_reason && choice.finish_reason !== 'length') {
235
+ for (const ev of collectToolCalls()) yield ev;
236
+ finishSeen = true;
237
+ }
238
+ } catch {
239
+ // skip unparseable
240
+ }
241
+ }
242
+ }
243
+
244
+ // Stream ended — emit any tool calls that arrived without a finish_reason,
245
+ // then close with the last usage we saw (usually from the final chunk).
246
+ if (!finishSeen) {
247
+ for (const ev of collectToolCalls()) yield ev;
248
+ }
249
+ yield {type: 'done', usage: lastUsage};
250
+ }
@@ -25,6 +25,25 @@ export interface CompleteResult {
25
25
  usage?: {promptTokens: number; completionTokens: number; cachedTokens?: number};
26
26
  }
27
27
 
28
+ const FREE_TIER_STUB_TOOLS = [
29
+ {
30
+ type: 'function',
31
+ function: {
32
+ name: 'read',
33
+ description: 'Read a file',
34
+ parameters: {type: 'object', properties: {}},
35
+ },
36
+ },
37
+ {
38
+ type: 'function',
39
+ function: {
40
+ name: 'bash',
41
+ description: 'Run a shell command',
42
+ parameters: {type: 'object', properties: {}},
43
+ },
44
+ },
45
+ ];
46
+
28
47
  /**
29
48
  * Run a completion to finish and return the concatenated text.
30
49
  *
@@ -42,7 +61,7 @@ export async function complete(
42
61
  for await (const event of provider.stream({
43
62
  model: opts.model,
44
63
  messages: opts.messages,
45
- tools: [],
64
+ tools: /-free$/.test(opts.model) ? FREE_TIER_STUB_TOOLS : [],
46
65
  signal: opts.signal,
47
66
  ...(opts.params ?? {}),
48
67
  } as never)) {
@@ -1,6 +1,7 @@
1
- export type {Provider, ProviderConfig, ProviderModel, StreamEvent} from './types.js';
1
+ export type {Provider, ProviderConfig, ProviderModel, StreamEvent, ModelRoute} from './types.js';
2
2
  export {createOpenRouterProvider} from './openrouter.js';
3
3
  export {resolveAuth} from './auth.js';
4
4
  export {complete} from './complete.js';
5
5
  export type {CompleteOptions, CompleteResult} from './complete.js';
6
6
  export {pickCheapModel} from './pick-model.js';
7
+ export {resolveRoute, mergeProviders} from './registry.js';
@@ -1,11 +1,20 @@
1
1
  /**
2
2
  * OpenRouter provider — works with free models out of the box.
3
3
  * Supports tool/function calling via OpenAI-compatible format.
4
+ *
5
+ * The wire protocol is chosen per model: chat-completions is the default, and
6
+ * a provider definition may declare `modelRoutes` to send matching models to
7
+ * the Responses adapter instead. A provider with no routes behaves exactly as
8
+ * before.
4
9
  */
5
10
 
6
- import type {Provider, ProviderConfig, ProviderModel, StreamEvent, Usage} from './types.js';
11
+ import type {Provider, ProviderConfig, ProviderModel, StreamEvent, ModelRoute} from './types.js';
7
12
  import {randomBytes} from 'crypto';
8
- import {log} from '../logger.js';
13
+ import {getProvider, resolveRoute} from './registry.js';
14
+ import {streamChat, type ToolDef} from './chat.js';
15
+ import {streamResponses} from './responses.js';
16
+
17
+ export type {ToolDef} from './chat.js';
9
18
 
10
19
  const BASE62 = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
11
20
 
@@ -44,43 +53,6 @@ export function expandRandomValue(val: string): string {
44
53
  return prefix + hex;
45
54
  }
46
55
 
47
- /**
48
- * Pull cache-hit token counts out of an OpenAI-compatible usage object.
49
- * Field names differ per provider:
50
- * - DeepSeek: prompt_cache_hit_tokens
51
- * - OpenAI: prompt_tokens_details.cached_tokens
52
- * - OpenRouter: prompt_tokens_details.cached_tokens (or cache_read_input_tokens)
53
- * - Anthropic: cache_read_input_tokens
54
- * Returns undefined when the provider reports nothing.
55
- */
56
- function extractCachedTokens(usage: Record<string, unknown>): number | undefined {
57
- const direct =
58
- usage.prompt_cache_hit_tokens ??
59
- usage.cache_read_input_tokens ??
60
- (usage.prompt_tokens_details as Record<string, unknown> | undefined)?.cached_tokens;
61
- return typeof direct === 'number' ? direct : undefined;
62
- }
63
-
64
- /** Tool definition in OpenAI function calling format. */
65
- export interface ToolDef {
66
- type: 'function';
67
- function: {
68
- name: string;
69
- description: string;
70
- parameters: Record<string, unknown>;
71
- };
72
- }
73
-
74
- /** Accumulated tool call state during streaming. */
75
- interface ToolCallAccum {
76
- id: string;
77
- name: string;
78
- arguments: string;
79
- extra_content?: Record<string, unknown>;
80
- /** Insertion order — used to emit parallel calls in the order they arrived. */
81
- seq: number;
82
- }
83
-
84
56
  export function createOpenRouterProvider(config: ProviderConfig): Provider {
85
57
  return new OpenRouterProvider(config);
86
58
  }
@@ -90,6 +62,8 @@ class OpenRouterProvider implements Provider {
90
62
  private baseUrl: string;
91
63
  private apiKey: string;
92
64
  private modelPrefix: string;
65
+ private defaultProtocol?: 'chat';
66
+ private modelRoutes: ModelRoute[];
93
67
  /** Static headers (no random tokens). */
94
68
  private baseHeaders: Record<string, string>;
95
69
  /** Headers that may contain __random:…__ tokens — expanded fresh per stream(). */
@@ -107,6 +81,10 @@ class OpenRouterProvider implements Provider {
107
81
  ...(referer ? {'HTTP-Referer': referer} : {}),
108
82
  };
109
83
  this.customHeaders = config.headers ?? {};
84
+ // Routes come from the caller or, for registry providers, the definition.
85
+ const def = getProvider(config.id);
86
+ this.defaultProtocol = config.defaultProtocol ?? def?.defaultProtocol;
87
+ this.modelRoutes = config.modelRoutes ?? def?.modelRoutes ?? [];
110
88
  }
111
89
 
112
90
  /** Compute headers with random tokens expanded fresh (new id per call). */
@@ -116,7 +94,7 @@ class OpenRouterProvider implements Provider {
116
94
  out[k] = expandRandomValue(v);
117
95
  }
118
96
  if (this.apiKey) {
119
- out['Authorization'] = `Bearer ${this.apiKey}`;
97
+ out.Authorization = `Bearer ${this.apiKey}`;
120
98
  }
121
99
  return out;
122
100
  }
@@ -152,184 +130,35 @@ class OpenRouterProvider implements Provider {
152
130
  tools?: ToolDef[];
153
131
  signal?: AbortSignal;
154
132
  }): AsyncGenerator<StreamEvent> {
155
- const body: Record<string, unknown> = {
156
- model: this.modelPrefix ? opts.model.replace(this.modelPrefix, '') : opts.model,
157
- messages: opts.messages,
158
- stream: true,
159
- stream_options: {include_usage: true},
160
- };
161
-
162
- // Forward tools if provided — MUST be included in every request with tools
163
- if (opts.tools && opts.tools.length > 0) {
164
- body.tools = opts.tools;
133
+ const model = this.modelPrefix ? opts.model.replace(this.modelPrefix, '') : opts.model;
134
+ const route = resolveRoute(
135
+ {defaultProtocol: this.defaultProtocol, modelRoutes: this.modelRoutes},
136
+ model,
137
+ );
138
+ const headers = this.computeHeaders();
139
+
140
+ if (route.protocol === 'responses') {
141
+ yield* streamResponses({
142
+ id: this.id,
143
+ baseUrl: this.baseUrl,
144
+ model,
145
+ messages: opts.messages,
146
+ tools: opts.tools,
147
+ headers,
148
+ signal: opts.signal,
149
+ path: route.path,
150
+ });
151
+ return;
165
152
  }
166
153
 
167
- log('request', {
168
- provider: this.id,
154
+ yield* streamChat({
155
+ id: this.id,
169
156
  baseUrl: this.baseUrl,
170
- model: body.model,
171
- messageCount: opts.messages.length,
172
- toolCount: opts.tools?.length ?? 0,
157
+ model,
173
158
  messages: opts.messages,
174
- });
175
-
176
- const res = await fetch(`${this.baseUrl}/chat/completions`, {
177
- method: 'POST',
178
- headers: this.computeHeaders(),
179
- body: JSON.stringify(body),
159
+ tools: opts.tools,
160
+ headers,
180
161
  signal: opts.signal,
181
162
  });
182
-
183
- if (!res.ok) {
184
- const err = await res.text();
185
- log('response-error', {status: res.status, body: err});
186
- yield {type: 'error', content: `API ${res.status}: ${err}`};
187
- return;
188
- }
189
-
190
- const reader = res.body?.getReader();
191
- if (!reader) {
192
- yield {type: 'error', content: 'No response body'};
193
- return;
194
- }
195
-
196
- const decoder = new TextDecoder();
197
- let buffer = '';
198
- const toolCallAccumulators = new Map<string, ToolCallAccum>();
199
- let toolCallSeq = 0;
200
- let lastUsage: Usage | undefined;
201
- let finishSeen = false;
202
-
203
- /** Emit accumulated tool calls in arrival order. */
204
- const collectToolCalls = (): StreamEvent[] => {
205
- const ordered = [...toolCallAccumulators.values()].sort((a, b) => a.seq - b.seq);
206
- const events: StreamEvent[] = [];
207
- for (const tc of ordered) {
208
- if (!tc.name) continue;
209
- events.push({
210
- type: 'tool_use',
211
- toolCall: {
212
- id: tc.id || `call_${Math.random().toString(36).slice(2, 10)}`,
213
- name: tc.name,
214
- arguments: tc.arguments || '{}',
215
- extraContent: tc.extra_content,
216
- },
217
- });
218
- }
219
- toolCallAccumulators.clear();
220
- return events;
221
- };
222
-
223
- while (true) {
224
- const {done, value} = await reader.read();
225
- if (done) break;
226
-
227
- buffer += decoder.decode(value, {stream: true});
228
- const lines = buffer.split('\n');
229
- buffer = lines.pop() ?? '';
230
-
231
- for (const line of lines) {
232
- const trimmed = line.trim();
233
- if (!trimmed.startsWith('data: ')) continue;
234
- const data = trimmed.slice(6);
235
- if (data === '[DONE]') continue;
236
-
237
- try {
238
- // Providers/gateways occasionally emit raw NUL bytes, which make
239
- // JSON.parse throw — the catch below would then drop the whole chunk,
240
- // losing tool-call argument fragments. Strip them before parsing.
241
- const parsed = JSON.parse(data.replaceAll('\u0000', ''));
242
- const choice = parsed.choices?.[0];
243
-
244
- // Extract usage from chunk (Gemini puts it in the last chunk)
245
- if (parsed.usage) {
246
- lastUsage = {
247
- promptTokens: parsed.usage.prompt_tokens ?? 0,
248
- completionTokens: parsed.usage.completion_tokens ?? 0,
249
- totalTokens: parsed.usage.total_tokens ?? 0,
250
- cachedTokens: extractCachedTokens(parsed.usage),
251
- };
252
- log('usage', lastUsage);
253
- }
254
-
255
- // Usage can also appear without choices (Gemini style)
256
- if (!choice && parsed.usage) continue;
257
-
258
- const delta = choice.delta;
259
-
260
- // Text content — strip escaped NULs that survive JSON.parse
261
- // (stray null bytes corrupt rendered text and commands downstream).
262
- if (delta?.content) {
263
- yield {type: 'text', content: delta.content.replaceAll('\u0000', '')};
264
- }
265
-
266
- // Tool calls — accumulate arguments across chunks.
267
- // OpenAI/DeepSeek stream one call as [id+name] then [argument fragments],
268
- // where only `index` repeats across chunks. Some providers (Gemini) have
269
- // been observed reusing index 0 across parallel calls, so a *new id* on an
270
- // already-named index starts a fresh accumulator instead of merging.
271
- if (delta?.tool_calls) {
272
- for (const tc of delta.tool_calls) {
273
- const idxKey = String(tc.index ?? 0);
274
- let existing = toolCallAccumulators.get(idxKey);
275
-
276
- if (existing && tc.id && existing.id && tc.id !== existing.id) {
277
- // Same index, different call — park the previous one under a unique key.
278
- toolCallAccumulators.delete(idxKey);
279
- toolCallAccumulators.set(`${idxKey}#${existing.seq}`, existing);
280
- existing = undefined;
281
- }
282
-
283
- if (!existing) {
284
- existing = {
285
- id: '',
286
- name: '',
287
- arguments: '',
288
- extra_content: undefined,
289
- seq: toolCallSeq++,
290
- };
291
- toolCallAccumulators.set(idxKey, existing);
292
- }
293
-
294
- // Strip NULs at the read point: escaped null bytes survive
295
- // JSON.parse and would otherwise corrupt ids/names/arguments.
296
- if (tc.id) existing.id = tc.id.replaceAll('\u0000', '');
297
- if (tc.function?.name) existing.name = tc.function.name.replaceAll('\u0000', '');
298
- if (tc.function?.arguments)
299
- existing.arguments += tc.function.arguments.replaceAll('\u0000', '');
300
- // Capture Gemini's extra_content (contains thought_signature)
301
- if (tc.extra_content && !existing.extra_content) {
302
- existing.extra_content = tc.extra_content;
303
- }
304
- }
305
- }
306
-
307
- // Finish reason — emit accumulated tool calls once, but keep reading:
308
- // OpenAI-compatible providers send the usage-only chunk *after* the
309
- // finish_reason chunk, so returning here would drop token usage.
310
- if (choice.finish_reason === 'tool_calls') {
311
- for (const ev of collectToolCalls()) yield ev;
312
- finishSeen = true;
313
- continue;
314
- }
315
-
316
- // Normal finish — also emit any accumulated tool calls
317
- // (Gemini sends finish_reason="stop" even with tool calls)
318
- if (choice.finish_reason && choice.finish_reason !== 'length') {
319
- for (const ev of collectToolCalls()) yield ev;
320
- finishSeen = true;
321
- }
322
- } catch {
323
- // skip unparseable
324
- }
325
- }
326
- }
327
-
328
- // Stream ended — emit any tool calls that arrived without a finish_reason,
329
- // then close with the last usage we saw (usually from the final chunk).
330
- if (!finishSeen) {
331
- for (const ev of collectToolCalls()) yield ev;
332
- }
333
- yield {type: 'done', usage: lastUsage};
334
163
  }
335
164
  }
@@ -16,6 +16,8 @@
16
16
  * expands to a fresh session-shaped id (`ses_` + 12 hex + 14 base62).
17
17
  */
18
18
 
19
+ import type {ModelRoute} from './types.js';
20
+
19
21
  export interface ProviderDef {
20
22
  /** Stable id, also the config key. */
21
23
  id: string;
@@ -51,6 +53,10 @@ export interface ProviderDef {
51
53
  alias?: string;
52
54
  /** Prefix to strip from model names before sending to the API (e.g. "opencode/"). */
53
55
  modelPrefix?: string;
56
+ /** Protocol used when no `modelRoutes` pattern matches (default 'chat'). */
57
+ defaultProtocol?: 'chat';
58
+ /** Per-model wire-protocol routing; regex patterns, first match wins. */
59
+ modelRoutes?: ModelRoute[];
54
60
  }
55
61
 
56
62
  const BUILTIN_PROVIDERS: ProviderDef[] = [
@@ -143,8 +149,50 @@ const PROVIDER_ALIASES: Record<string, string> = {};
143
149
  let _customLoaded = false;
144
150
 
145
151
  /**
146
- * Load custom providers from `~/.pal/providers.json` and append them to
147
- * `PROVIDERS`. Safe to call multiple times — only loads once.
152
+ * Merge user-defined providers over the built-ins: a custom entry with an
153
+ * existing id REPLACES the built-in in place (user-wins), while new ids are
154
+ * appended. Returns the merged list plus the alias table the entries declare.
155
+ */
156
+ export function mergeProviders(
157
+ builtins: ProviderDef[],
158
+ customs: ProviderDef[],
159
+ ): {providers: ProviderDef[]; aliases: Record<string, string>} {
160
+ const providers = [...builtins];
161
+ const aliases: Record<string, string> = {};
162
+ for (const entry of customs) {
163
+ if (!entry || typeof entry.id !== 'string' || typeof entry.baseUrl !== 'string') continue;
164
+ const idx = providers.findIndex((p) => p.id === entry.id);
165
+ if (idx >= 0) providers[idx] = entry;
166
+ else providers.push(entry);
167
+ if (entry.alias) aliases[entry.alias] = entry.id;
168
+ }
169
+ return {providers, aliases};
170
+ }
171
+
172
+ /**
173
+ * Resolve the wire protocol + optional path for a bare model id. The first
174
+ * `modelRoutes` pattern that matches wins; otherwise the provider default.
175
+ */
176
+ export function resolveRoute(
177
+ def: {defaultProtocol?: 'chat'; modelRoutes?: ModelRoute[]},
178
+ model: string,
179
+ ): {protocol: 'chat' | 'responses'; path?: string} {
180
+ for (const route of def.modelRoutes ?? []) {
181
+ let matches = false;
182
+ try {
183
+ matches = new RegExp(route.pattern).test(model);
184
+ } catch {
185
+ matches = false;
186
+ }
187
+ if (matches) return {protocol: route.protocol, path: route.path};
188
+ }
189
+ return {protocol: def.defaultProtocol ?? 'chat', path: undefined};
190
+ }
191
+
192
+ /**
193
+ * Load custom providers from `~/.pal/providers.json` and merge them into
194
+ * `PROVIDERS`. Same-id entries replace built-ins; new ones append.
195
+ * Safe to call multiple times — only loads once.
148
196
  */
149
197
  export function loadCustomProviders(): void {
150
198
  if (_customLoaded) return;
@@ -157,14 +205,10 @@ export function loadCustomProviders(): void {
157
205
  const raw = readFileSync(customPath, 'utf-8');
158
206
  const data = JSON.parse(raw);
159
207
  if (Array.isArray(data)) {
160
- for (const entry of data) {
161
- if (entry && typeof entry.id === 'string' && typeof entry.baseUrl === 'string') {
162
- PROVIDERS.push(entry as ProviderDef);
163
- if (entry.alias) {
164
- PROVIDER_ALIASES[entry.alias] = entry.id;
165
- }
166
- }
167
- }
208
+ const {providers, aliases} = mergeProviders(PROVIDERS, data as ProviderDef[]);
209
+ PROVIDERS.length = 0;
210
+ PROVIDERS.push(...providers);
211
+ Object.assign(PROVIDER_ALIASES, aliases);
168
212
  }
169
213
  } catch {
170
214
  // No custom providers file or invalid JSON — that's fine.