@pal-code/core 0.0.16 → 0.0.18

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.
@@ -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
 
@@ -24,61 +33,28 @@ function randomBase62(len: number): string {
24
33
  return out;
25
34
  }
26
35
 
36
+ /** Header token for N random lowercase hex chars, optionally prefixed.
37
+ * The prefix may not contain `__`, otherwise a composite such as
38
+ * `ses___random:9__ffe___random:14__` parses as one greedy token instead of two.
39
+ */
40
+ const RANDOM_TOKEN = /__random(?::((?:(?!__)[^:])+))?:(\d+)__/g;
41
+
27
42
  /** Expand header-value tokens.
28
43
  * `__sesid__` → `ses_` + 12 lowercase hex + 14 base62
29
44
  * `__random:32__` → 32-char random hex
30
45
  * `__random:ses_:32__` → `ses_` + 32-char random hex
31
- * Anything else is returned unchanged.
46
+ * Tokens also expand when embedded in surrounding literal text, so composite
47
+ * values can interleave fixed and random parts in any order.
48
+ * Anything without a token is returned unchanged.
32
49
  */
33
50
  export function expandRandomValue(val: string): string {
34
51
  if (val === '__sesid__') {
35
52
  return `ses_${randomBytes(6).toString('hex')}${randomBase62(14)}`;
36
53
  }
37
- const m = val.match(/^__random(?::([^:]+))?:(\d+)__$/);
38
- if (!m) return val;
39
- const prefix = m[1] ?? '';
40
- const len = Number(m[2]);
41
- const hex = randomBytes(Math.ceil(len / 2))
42
- .toString('hex')
43
- .slice(0, len);
44
- return prefix + hex;
45
- }
46
-
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;
54
+ return val.replace(RANDOM_TOKEN, (_match, prefix: string | undefined, len: string) => {
55
+ const width = Number(len);
56
+ return (prefix ?? '') + randomBytes(Math.ceil(width / 2)).toString('hex').slice(0, width);
57
+ });
82
58
  }
83
59
 
84
60
  export function createOpenRouterProvider(config: ProviderConfig): Provider {
@@ -90,6 +66,8 @@ class OpenRouterProvider implements Provider {
90
66
  private baseUrl: string;
91
67
  private apiKey: string;
92
68
  private modelPrefix: string;
69
+ private defaultProtocol?: 'chat';
70
+ private modelRoutes: ModelRoute[];
93
71
  /** Static headers (no random tokens). */
94
72
  private baseHeaders: Record<string, string>;
95
73
  /** Headers that may contain __random:…__ tokens — expanded fresh per stream(). */
@@ -107,6 +85,10 @@ class OpenRouterProvider implements Provider {
107
85
  ...(referer ? {'HTTP-Referer': referer} : {}),
108
86
  };
109
87
  this.customHeaders = config.headers ?? {};
88
+ // Routes come from the caller or, for registry providers, the definition.
89
+ const def = getProvider(config.id);
90
+ this.defaultProtocol = config.defaultProtocol ?? def?.defaultProtocol;
91
+ this.modelRoutes = config.modelRoutes ?? def?.modelRoutes ?? [];
110
92
  }
111
93
 
112
94
  /** Compute headers with random tokens expanded fresh (new id per call). */
@@ -116,7 +98,7 @@ class OpenRouterProvider implements Provider {
116
98
  out[k] = expandRandomValue(v);
117
99
  }
118
100
  if (this.apiKey) {
119
- out['Authorization'] = `Bearer ${this.apiKey}`;
101
+ out.Authorization = `Bearer ${this.apiKey}`;
120
102
  }
121
103
  return out;
122
104
  }
@@ -152,184 +134,35 @@ class OpenRouterProvider implements Provider {
152
134
  tools?: ToolDef[];
153
135
  signal?: AbortSignal;
154
136
  }): 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;
137
+ const model = this.modelPrefix ? opts.model.replace(this.modelPrefix, '') : opts.model;
138
+ const route = resolveRoute(
139
+ {defaultProtocol: this.defaultProtocol, modelRoutes: this.modelRoutes},
140
+ model,
141
+ );
142
+ const headers = this.computeHeaders();
143
+
144
+ if (route.protocol === 'responses') {
145
+ yield* streamResponses({
146
+ id: this.id,
147
+ baseUrl: this.baseUrl,
148
+ model,
149
+ messages: opts.messages,
150
+ tools: opts.tools,
151
+ headers,
152
+ signal: opts.signal,
153
+ path: route.path,
154
+ });
155
+ return;
165
156
  }
166
157
 
167
- log('request', {
168
- provider: this.id,
158
+ yield* streamChat({
159
+ id: this.id,
169
160
  baseUrl: this.baseUrl,
170
- model: body.model,
171
- messageCount: opts.messages.length,
172
- toolCount: opts.tools?.length ?? 0,
161
+ model,
173
162
  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),
163
+ tools: opts.tools,
164
+ headers,
180
165
  signal: opts.signal,
181
166
  });
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
167
  }
335
168
  }
@@ -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[] = [
@@ -89,6 +95,29 @@ const BUILTIN_PROVIDERS: ProviderDef[] = [
89
95
  defaultModel: 'deepseek/deepseek-chat',
90
96
  fallbackModels: ['deepseek/deepseek-chat', 'openai/gpt-4o-mini', 'anthropic/claude-sonnet-4'],
91
97
  },
98
+ {
99
+ id: 'zen',
100
+ name: 'OpenCode Zen',
101
+ baseUrl: 'https://opencode.ai/zen/v1',
102
+ envVar: 'OPENCODE_API_KEY',
103
+ modelPrefixes: ['zen', 'opencode'],
104
+ keyPrefixes: ['sk-ot'],
105
+ defaultModel: 'deepseek-v4.1-flash',
106
+ fallbackModels: [
107
+ 'deepseek-v4.1-flash',
108
+ 'glm-5.1',
109
+ 'kimi-k2.6',
110
+ 'minimax-m2.7',
111
+ 'qwen3.8-max',
112
+ 'mimo-v2.6-flash-free',
113
+ ],
114
+ headers: {'User-Agent': 'pal'},
115
+ hint: 'opencode.ai/zen · BYOK',
116
+ alias: 'opencode',
117
+ // Zen serves GPT/Codex/Grok via the Responses API; everything else is
118
+ // OpenAI-compatible Chat Completions.
119
+ modelRoutes: [{pattern: '^(gpt-|codex|grok-|muse-spark)', protocol: 'responses'}],
120
+ },
92
121
  {
93
122
  id: 'openai',
94
123
  name: 'OpenAI',
@@ -139,12 +168,57 @@ export const PROVIDERS: ProviderDef[] = [...BUILTIN_PROVIDERS];
139
168
 
140
169
  /** Aliases accepted as a provider prefix (e.g. `opencode/model` → zen). */
141
170
  const PROVIDER_ALIASES: Record<string, string> = {};
171
+ for (const p of BUILTIN_PROVIDERS) {
172
+ if (p.alias) PROVIDER_ALIASES[p.alias] = p.id;
173
+ }
142
174
 
143
175
  let _customLoaded = false;
144
176
 
145
177
  /**
146
- * Load custom providers from `~/.pal/providers.json` and append them to
147
- * `PROVIDERS`. Safe to call multiple times — only loads once.
178
+ * Merge user-defined providers over the built-ins: a custom entry with an
179
+ * existing id REPLACES the built-in in place (user-wins), while new ids are
180
+ * appended. Returns the merged list plus the alias table the entries declare.
181
+ */
182
+ export function mergeProviders(
183
+ builtins: ProviderDef[],
184
+ customs: ProviderDef[],
185
+ ): {providers: ProviderDef[]; aliases: Record<string, string>} {
186
+ const providers = [...builtins];
187
+ const aliases: Record<string, string> = {};
188
+ for (const entry of customs) {
189
+ if (!entry || typeof entry.id !== 'string' || typeof entry.baseUrl !== 'string') continue;
190
+ const idx = providers.findIndex((p) => p.id === entry.id);
191
+ if (idx >= 0) providers[idx] = entry;
192
+ else providers.push(entry);
193
+ if (entry.alias) aliases[entry.alias] = entry.id;
194
+ }
195
+ return {providers, aliases};
196
+ }
197
+
198
+ /**
199
+ * Resolve the wire protocol + optional path for a bare model id. The first
200
+ * `modelRoutes` pattern that matches wins; otherwise the provider default.
201
+ */
202
+ export function resolveRoute(
203
+ def: {defaultProtocol?: 'chat'; modelRoutes?: ModelRoute[]},
204
+ model: string,
205
+ ): {protocol: 'chat' | 'responses'; path?: string} {
206
+ for (const route of def.modelRoutes ?? []) {
207
+ let matches = false;
208
+ try {
209
+ matches = new RegExp(route.pattern).test(model);
210
+ } catch {
211
+ matches = false;
212
+ }
213
+ if (matches) return {protocol: route.protocol, path: route.path};
214
+ }
215
+ return {protocol: def.defaultProtocol ?? 'chat', path: undefined};
216
+ }
217
+
218
+ /**
219
+ * Load custom providers from `~/.pal/providers.json` and merge them into
220
+ * `PROVIDERS`. Same-id entries replace built-ins; new ones append.
221
+ * Safe to call multiple times — only loads once.
148
222
  */
149
223
  export function loadCustomProviders(): void {
150
224
  if (_customLoaded) return;
@@ -157,14 +231,10 @@ export function loadCustomProviders(): void {
157
231
  const raw = readFileSync(customPath, 'utf-8');
158
232
  const data = JSON.parse(raw);
159
233
  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
- }
234
+ const {providers, aliases} = mergeProviders(PROVIDERS, data as ProviderDef[]);
235
+ PROVIDERS.length = 0;
236
+ PROVIDERS.push(...providers);
237
+ Object.assign(PROVIDER_ALIASES, aliases);
168
238
  }
169
239
  } catch {
170
240
  // No custom providers file or invalid JSON — that's fine.