pal-code 0.0.9 → 0.0.11
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.
- package/README.md +3 -3
- package/SYSTEM.md +3 -3
- package/bin/pal-code.js +37 -11
- package/package.json +7 -14
- package/packages/cli/README.md +2 -2
- package/packages/cli/src/commands/ext.ts +1 -1
- package/packages/cli/src/commands.ts +1 -1
- package/packages/cli/src/components/render-history.ts +2 -2
- package/packages/cli/src/config.ts +2 -2
- package/packages/cli/src/index.ts +7 -7
- package/packages/cli/src/overlays/key-input.ts +1 -1
- package/packages/cli/src/overlays/model-picker.ts +2 -2
- package/packages/cli/src/overlays/session-picker.ts +1 -1
- package/packages/cli/src/overlays/wizard.ts +1 -1
- package/packages/cli/src/state.ts +2 -2
- package/packages/cli/src/turn.ts +16 -9
- package/packages/cli/src/utils/permissions.ts +3 -3
- package/packages/core/src/agent/events.ts +0 -36
- package/packages/core/src/agent/fallback.ts +0 -344
- package/packages/core/src/agent/index.ts +0 -35
- package/packages/core/src/agent/roles.ts +0 -188
- package/packages/core/src/agent/run.ts +0 -713
- package/packages/core/src/agent/scope.ts +0 -34
- package/packages/core/src/agent/todos.ts +0 -66
- package/packages/core/src/compaction.ts +0 -243
- package/packages/core/src/config.ts +0 -387
- package/packages/core/src/extensions.ts +0 -178
- package/packages/core/src/index.ts +0 -157
- package/packages/core/src/logger.ts +0 -54
- package/packages/core/src/provider/auth.ts +0 -153
- package/packages/core/src/provider/complete.ts +0 -63
- package/packages/core/src/provider/index.ts +0 -6
- package/packages/core/src/provider/openrouter.ts +0 -304
- package/packages/core/src/provider/pick-model.ts +0 -43
- package/packages/core/src/provider/registry.ts +0 -222
- package/packages/core/src/provider/types.ts +0 -61
- package/packages/core/src/repo-map.ts +0 -177
- package/packages/core/src/session/index.ts +0 -2
- package/packages/core/src/session/store.ts +0 -677
- package/packages/core/src/session/types.ts +0 -72
- package/packages/core/src/snapshots.ts +0 -107
- package/packages/core/src/tools/definitions.ts +0 -365
- package/packages/core/src/tools/executor.ts +0 -1363
- package/packages/core/src/tools/index.ts +0 -5
- package/packages/core/src/tools/search.ts +0 -201
- package/scripts/postinstall.js +0 -121
- package/scripts/preinstall.js +0 -51
|
@@ -1,304 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* OpenRouter provider — works with free models out of the box.
|
|
3
|
-
* Supports tool/function calling via OpenAI-compatible format.
|
|
4
|
-
*/
|
|
5
|
-
|
|
6
|
-
import type {Provider, ProviderConfig, ProviderModel, StreamEvent, Usage} from './types.js';
|
|
7
|
-
import {randomBytes} from 'crypto';
|
|
8
|
-
import {log} from '../logger.js';
|
|
9
|
-
|
|
10
|
-
/** Expand `__random[:PREFIX]:N__` tokens in header values.
|
|
11
|
-
* `__random:32__` → 32-char random hex
|
|
12
|
-
* `__random:ses_:32__` → `ses_` + 32-char random hex
|
|
13
|
-
*/
|
|
14
|
-
function expandRandomValue(val: string): string {
|
|
15
|
-
const m = val.match(/^__random(?::([^:]+))?:(\d+)__$/);
|
|
16
|
-
if (!m) return val;
|
|
17
|
-
const prefix = m[1] ?? '';
|
|
18
|
-
const len = Number(m[2]);
|
|
19
|
-
const hex = randomBytes(Math.ceil(len / 2)).toString('hex').slice(0, len);
|
|
20
|
-
return prefix + hex;
|
|
21
|
-
}
|
|
22
|
-
|
|
23
|
-
/**
|
|
24
|
-
* Pull cache-hit token counts out of an OpenAI-compatible usage object.
|
|
25
|
-
* Field names differ per provider:
|
|
26
|
-
* - DeepSeek: prompt_cache_hit_tokens
|
|
27
|
-
* - OpenAI: prompt_tokens_details.cached_tokens
|
|
28
|
-
* - OpenRouter: prompt_tokens_details.cached_tokens (or cache_read_input_tokens)
|
|
29
|
-
* - Anthropic: cache_read_input_tokens
|
|
30
|
-
* Returns undefined when the provider reports nothing.
|
|
31
|
-
*/
|
|
32
|
-
function extractCachedTokens(usage: Record<string, unknown>): number | undefined {
|
|
33
|
-
const direct =
|
|
34
|
-
usage.prompt_cache_hit_tokens ??
|
|
35
|
-
usage.cache_read_input_tokens ??
|
|
36
|
-
(usage.prompt_tokens_details as Record<string, unknown> | undefined)?.cached_tokens;
|
|
37
|
-
return typeof direct === 'number' ? direct : undefined;
|
|
38
|
-
}
|
|
39
|
-
|
|
40
|
-
/** Tool definition in OpenAI function calling format. */
|
|
41
|
-
export interface ToolDef {
|
|
42
|
-
type: 'function';
|
|
43
|
-
function: {
|
|
44
|
-
name: string;
|
|
45
|
-
description: string;
|
|
46
|
-
parameters: Record<string, unknown>;
|
|
47
|
-
};
|
|
48
|
-
}
|
|
49
|
-
|
|
50
|
-
/** Accumulated tool call state during streaming. */
|
|
51
|
-
interface ToolCallAccum {
|
|
52
|
-
id: string;
|
|
53
|
-
name: string;
|
|
54
|
-
arguments: string;
|
|
55
|
-
extra_content?: Record<string, unknown>;
|
|
56
|
-
/** Insertion order — used to emit parallel calls in the order they arrived. */
|
|
57
|
-
seq: number;
|
|
58
|
-
}
|
|
59
|
-
|
|
60
|
-
export function createOpenRouterProvider(config: ProviderConfig): Provider {
|
|
61
|
-
return new OpenRouterProvider(config);
|
|
62
|
-
}
|
|
63
|
-
|
|
64
|
-
class OpenRouterProvider implements Provider {
|
|
65
|
-
readonly id = 'openrouter';
|
|
66
|
-
private baseUrl: string;
|
|
67
|
-
private apiKey: string;
|
|
68
|
-
private modelPrefix: string;
|
|
69
|
-
/** Static headers (no random tokens). */
|
|
70
|
-
private baseHeaders: Record<string, string>;
|
|
71
|
-
/** Headers that may contain __random:…__ tokens — expanded fresh per stream(). */
|
|
72
|
-
private customHeaders: Record<string, string>;
|
|
73
|
-
|
|
74
|
-
constructor(config: ProviderConfig) {
|
|
75
|
-
this.baseUrl = config.baseUrl.replace(/\/+$/, '');
|
|
76
|
-
this.apiKey = config.apiKey ?? '';
|
|
77
|
-
this.modelPrefix = config.modelPrefix ?? '';
|
|
78
|
-
// HTTP-Referer is optional OpenRouter attribution; set PAL_REFERER to advertise your app.
|
|
79
|
-
const referer = process.env.PAL_REFERER;
|
|
80
|
-
this.baseHeaders = {
|
|
81
|
-
'Content-Type': 'application/json',
|
|
82
|
-
'X-Title': 'pal',
|
|
83
|
-
...(referer ? {'HTTP-Referer': referer} : {}),
|
|
84
|
-
};
|
|
85
|
-
this.customHeaders = config.headers ?? {};
|
|
86
|
-
}
|
|
87
|
-
|
|
88
|
-
/** Compute headers with random tokens expanded fresh (new id per call). */
|
|
89
|
-
private computeHeaders(): Record<string, string> {
|
|
90
|
-
const out: Record<string, string> = {...this.baseHeaders};
|
|
91
|
-
for (const [k, v] of Object.entries(this.customHeaders)) {
|
|
92
|
-
out[k] = expandRandomValue(v);
|
|
93
|
-
}
|
|
94
|
-
if (this.apiKey) {
|
|
95
|
-
out['Authorization'] = `Bearer ${this.apiKey}`;
|
|
96
|
-
}
|
|
97
|
-
return out;
|
|
98
|
-
}
|
|
99
|
-
|
|
100
|
-
async init(): Promise<void> {
|
|
101
|
-
// Auth is now applied dynamically in computeHeaders().
|
|
102
|
-
}
|
|
103
|
-
|
|
104
|
-
async models(): Promise<ProviderModel[]> {
|
|
105
|
-
const res = await fetch(`${this.baseUrl}/models`, {
|
|
106
|
-
headers: this.computeHeaders(),
|
|
107
|
-
});
|
|
108
|
-
if (!res.ok) throw new Error(`Failed to fetch models: ${res.status}`);
|
|
109
|
-
const data = (await res.json()) as {
|
|
110
|
-
data: Array<{
|
|
111
|
-
id: string;
|
|
112
|
-
name?: string;
|
|
113
|
-
pricing?: {prompt: string; completion: string};
|
|
114
|
-
context_length?: number;
|
|
115
|
-
}>;
|
|
116
|
-
};
|
|
117
|
-
return (data.data ?? []).map((m) => ({
|
|
118
|
-
id: m.id,
|
|
119
|
-
name: m.name ?? m.id,
|
|
120
|
-
contextWindow: m.context_length,
|
|
121
|
-
free: m.pricing?.prompt === '0' && m.pricing?.completion === '0',
|
|
122
|
-
}));
|
|
123
|
-
}
|
|
124
|
-
|
|
125
|
-
async *stream(opts: {
|
|
126
|
-
model: string;
|
|
127
|
-
messages: Array<Record<string, unknown>>;
|
|
128
|
-
tools?: ToolDef[];
|
|
129
|
-
signal?: AbortSignal;
|
|
130
|
-
}): AsyncGenerator<StreamEvent> {
|
|
131
|
-
const body: Record<string, unknown> = {
|
|
132
|
-
model: this.modelPrefix ? opts.model.replace(this.modelPrefix, '') : opts.model,
|
|
133
|
-
messages: opts.messages,
|
|
134
|
-
stream: true,
|
|
135
|
-
stream_options: {include_usage: true},
|
|
136
|
-
};
|
|
137
|
-
|
|
138
|
-
// Forward tools if provided — MUST be included in every request with tools
|
|
139
|
-
if (opts.tools && opts.tools.length > 0) {
|
|
140
|
-
body.tools = opts.tools;
|
|
141
|
-
}
|
|
142
|
-
|
|
143
|
-
log('request', {
|
|
144
|
-
provider: this.id,
|
|
145
|
-
baseUrl: this.baseUrl,
|
|
146
|
-
model: body.model,
|
|
147
|
-
messageCount: opts.messages.length,
|
|
148
|
-
toolCount: opts.tools?.length ?? 0,
|
|
149
|
-
messages: opts.messages,
|
|
150
|
-
});
|
|
151
|
-
|
|
152
|
-
const res = await fetch(`${this.baseUrl}/chat/completions`, {
|
|
153
|
-
method: 'POST',
|
|
154
|
-
headers: this.computeHeaders(),
|
|
155
|
-
body: JSON.stringify(body),
|
|
156
|
-
signal: opts.signal,
|
|
157
|
-
});
|
|
158
|
-
|
|
159
|
-
if (!res.ok) {
|
|
160
|
-
const err = await res.text();
|
|
161
|
-
log('response-error', {status: res.status, body: err});
|
|
162
|
-
yield {type: 'error', content: `API ${res.status}: ${err}`};
|
|
163
|
-
return;
|
|
164
|
-
}
|
|
165
|
-
|
|
166
|
-
const reader = res.body?.getReader();
|
|
167
|
-
if (!reader) {
|
|
168
|
-
yield {type: 'error', content: 'No response body'};
|
|
169
|
-
return;
|
|
170
|
-
}
|
|
171
|
-
|
|
172
|
-
const decoder = new TextDecoder();
|
|
173
|
-
let buffer = '';
|
|
174
|
-
const toolCallAccumulators = new Map<string, ToolCallAccum>();
|
|
175
|
-
let toolCallSeq = 0;
|
|
176
|
-
let lastUsage: Usage | undefined;
|
|
177
|
-
let finishSeen = false;
|
|
178
|
-
|
|
179
|
-
/** Emit accumulated tool calls in arrival order. */
|
|
180
|
-
const collectToolCalls = (): StreamEvent[] => {
|
|
181
|
-
const ordered = [...toolCallAccumulators.values()].sort((a, b) => a.seq - b.seq);
|
|
182
|
-
const events: StreamEvent[] = [];
|
|
183
|
-
for (const tc of ordered) {
|
|
184
|
-
if (!tc.name) continue;
|
|
185
|
-
events.push({
|
|
186
|
-
type: 'tool_use',
|
|
187
|
-
toolCall: {
|
|
188
|
-
id: tc.id || `call_${Math.random().toString(36).slice(2, 10)}`,
|
|
189
|
-
name: tc.name,
|
|
190
|
-
arguments: tc.arguments || '{}',
|
|
191
|
-
extraContent: tc.extra_content,
|
|
192
|
-
},
|
|
193
|
-
});
|
|
194
|
-
}
|
|
195
|
-
toolCallAccumulators.clear();
|
|
196
|
-
return events;
|
|
197
|
-
};
|
|
198
|
-
|
|
199
|
-
while (true) {
|
|
200
|
-
const {done, value} = await reader.read();
|
|
201
|
-
if (done) break;
|
|
202
|
-
|
|
203
|
-
buffer += decoder.decode(value, {stream: true});
|
|
204
|
-
const lines = buffer.split('\n');
|
|
205
|
-
buffer = lines.pop() ?? '';
|
|
206
|
-
|
|
207
|
-
for (const line of lines) {
|
|
208
|
-
const trimmed = line.trim();
|
|
209
|
-
if (!trimmed.startsWith('data: ')) continue;
|
|
210
|
-
const data = trimmed.slice(6);
|
|
211
|
-
if (data === '[DONE]') continue;
|
|
212
|
-
|
|
213
|
-
try {
|
|
214
|
-
const parsed = JSON.parse(data);
|
|
215
|
-
const choice = parsed.choices?.[0];
|
|
216
|
-
|
|
217
|
-
// Extract usage from chunk (Gemini puts it in the last chunk)
|
|
218
|
-
if (parsed.usage) {
|
|
219
|
-
lastUsage = {
|
|
220
|
-
promptTokens: parsed.usage.prompt_tokens ?? 0,
|
|
221
|
-
completionTokens: parsed.usage.completion_tokens ?? 0,
|
|
222
|
-
totalTokens: parsed.usage.total_tokens ?? 0,
|
|
223
|
-
cachedTokens: extractCachedTokens(parsed.usage),
|
|
224
|
-
};
|
|
225
|
-
log('usage', lastUsage);
|
|
226
|
-
}
|
|
227
|
-
|
|
228
|
-
// Usage can also appear without choices (Gemini style)
|
|
229
|
-
if (!choice && parsed.usage) continue;
|
|
230
|
-
|
|
231
|
-
const delta = choice.delta;
|
|
232
|
-
|
|
233
|
-
// Text content
|
|
234
|
-
if (delta?.content) {
|
|
235
|
-
yield {type: 'text', content: delta.content};
|
|
236
|
-
}
|
|
237
|
-
|
|
238
|
-
// Tool calls — accumulate arguments across chunks.
|
|
239
|
-
// OpenAI/DeepSeek stream one call as [id+name] then [argument fragments],
|
|
240
|
-
// where only `index` repeats across chunks. Some providers (Gemini) have
|
|
241
|
-
// been observed reusing index 0 across parallel calls, so a *new id* on an
|
|
242
|
-
// already-named index starts a fresh accumulator instead of merging.
|
|
243
|
-
if (delta?.tool_calls) {
|
|
244
|
-
for (const tc of delta.tool_calls) {
|
|
245
|
-
const idxKey = String(tc.index ?? 0);
|
|
246
|
-
let existing = toolCallAccumulators.get(idxKey);
|
|
247
|
-
|
|
248
|
-
if (existing && tc.id && existing.id && tc.id !== existing.id) {
|
|
249
|
-
// Same index, different call — park the previous one under a unique key.
|
|
250
|
-
toolCallAccumulators.delete(idxKey);
|
|
251
|
-
toolCallAccumulators.set(`${idxKey}#${existing.seq}`, existing);
|
|
252
|
-
existing = undefined;
|
|
253
|
-
}
|
|
254
|
-
|
|
255
|
-
if (!existing) {
|
|
256
|
-
existing = {
|
|
257
|
-
id: '',
|
|
258
|
-
name: '',
|
|
259
|
-
arguments: '',
|
|
260
|
-
extra_content: undefined,
|
|
261
|
-
seq: toolCallSeq++,
|
|
262
|
-
};
|
|
263
|
-
toolCallAccumulators.set(idxKey, existing);
|
|
264
|
-
}
|
|
265
|
-
|
|
266
|
-
if (tc.id) existing.id = tc.id;
|
|
267
|
-
if (tc.function?.name) existing.name = tc.function.name;
|
|
268
|
-
if (tc.function?.arguments) existing.arguments += tc.function.arguments;
|
|
269
|
-
// Capture Gemini's extra_content (contains thought_signature)
|
|
270
|
-
if (tc.extra_content && !existing.extra_content) {
|
|
271
|
-
existing.extra_content = tc.extra_content;
|
|
272
|
-
}
|
|
273
|
-
}
|
|
274
|
-
}
|
|
275
|
-
|
|
276
|
-
// Finish reason — emit accumulated tool calls once, but keep reading:
|
|
277
|
-
// OpenAI-compatible providers send the usage-only chunk *after* the
|
|
278
|
-
// finish_reason chunk, so returning here would drop token usage.
|
|
279
|
-
if (choice.finish_reason === 'tool_calls') {
|
|
280
|
-
for (const ev of collectToolCalls()) yield ev;
|
|
281
|
-
finishSeen = true;
|
|
282
|
-
continue;
|
|
283
|
-
}
|
|
284
|
-
|
|
285
|
-
// Normal finish — also emit any accumulated tool calls
|
|
286
|
-
// (Gemini sends finish_reason="stop" even with tool calls)
|
|
287
|
-
if (choice.finish_reason && choice.finish_reason !== 'length') {
|
|
288
|
-
for (const ev of collectToolCalls()) yield ev;
|
|
289
|
-
finishSeen = true;
|
|
290
|
-
}
|
|
291
|
-
} catch {
|
|
292
|
-
// skip unparseable
|
|
293
|
-
}
|
|
294
|
-
}
|
|
295
|
-
}
|
|
296
|
-
|
|
297
|
-
// Stream ended — emit any tool calls that arrived without a finish_reason,
|
|
298
|
-
// then close with the last usage we saw (usually from the final chunk).
|
|
299
|
-
if (!finishSeen) {
|
|
300
|
-
for (const ev of collectToolCalls()) yield ev;
|
|
301
|
-
}
|
|
302
|
-
yield {type: 'done', usage: lastUsage};
|
|
303
|
-
}
|
|
304
|
-
}
|
|
@@ -1,43 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Pick the cheapest/fastest model a provider offers.
|
|
3
|
-
*
|
|
4
|
-
* Used for utility calls (titles, summaries) where quality barely matters but
|
|
5
|
-
* cost and latency do. Preference order:
|
|
6
|
-
* 1. `free` models
|
|
7
|
-
* 2. lowest combined input+output cost
|
|
8
|
-
* 3. a name heuristic for known small/fast families
|
|
9
|
-
* 4. first model as a last resort
|
|
10
|
-
*/
|
|
11
|
-
|
|
12
|
-
import type {ProviderModel} from './types.js';
|
|
13
|
-
|
|
14
|
-
/** Substrings that mark a model as small/fast across common vendors. */
|
|
15
|
-
const SMALL_HINTS = ['mini', 'flash', 'haiku', 'small', 'lite', 'nano', '8b', '7b', '4b'];
|
|
16
|
-
|
|
17
|
-
export function pickCheapModel(models: readonly ProviderModel[]): string | undefined {
|
|
18
|
-
if (models.length === 0) return undefined;
|
|
19
|
-
|
|
20
|
-
const cost = (m: ProviderModel): number => (m.cost ? m.cost.input + m.cost.output : Number.POSITIVE_INFINITY);
|
|
21
|
-
|
|
22
|
-
const free = models.filter((m) => m.free);
|
|
23
|
-
if (free.length > 0) {
|
|
24
|
-
return [...free].sort((a, b) => cost(a) - cost(b))[0].id;
|
|
25
|
-
}
|
|
26
|
-
|
|
27
|
-
const priced = models.filter((m) => m.cost);
|
|
28
|
-
if (priced.length > 0) {
|
|
29
|
-
const cheapest = [...priced].sort((a, b) => cost(a) - cost(b))[0];
|
|
30
|
-
const hinted = priced.filter((m) =>
|
|
31
|
-
SMALL_HINTS.some((h) => m.id.toLowerCase().includes(h)),
|
|
32
|
-
);
|
|
33
|
-
if (hinted.length > 0) {
|
|
34
|
-
return [...hinted].sort((a, b) => cost(a) - cost(b))[0].id;
|
|
35
|
-
}
|
|
36
|
-
return cheapest.id;
|
|
37
|
-
}
|
|
38
|
-
|
|
39
|
-
const hinted = models.filter((m) => SMALL_HINTS.some((h) => m.id.toLowerCase().includes(h)));
|
|
40
|
-
if (hinted.length > 0) return hinted[0].id;
|
|
41
|
-
|
|
42
|
-
return models[0].id;
|
|
43
|
-
}
|
|
@@ -1,222 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Provider registry — BYOK (Bring Your Own Key) provider definitions.
|
|
3
|
-
*
|
|
4
|
-
* Every provider here speaks the OpenAI-compatible Chat Completions API, so a
|
|
5
|
-
* single adapter (`createOpenRouterProvider`) drives all of them. The registry
|
|
6
|
-
* supplies: base URL, env var, key-prefix detection, default models, and a
|
|
7
|
-
* curated fallback model list for when the provider's /models endpoint fails.
|
|
8
|
-
*
|
|
9
|
-
* Model addressing: `provider/model` (e.g. `deepseek/deepseek-chat`).
|
|
10
|
-
* A bare model name is resolved by pattern or by the default provider.
|
|
11
|
-
*
|
|
12
|
-
* Custom providers can be added via `~/.pal/providers.json` — an array of
|
|
13
|
-
* ProviderDef objects. Use the `headers` field to inject custom HTTP headers
|
|
14
|
-
* (e.g. User-Agent overrides). Header values containing `__random:N__` are
|
|
15
|
-
* expanded to N-character random hex strings at provider init time.
|
|
16
|
-
*/
|
|
17
|
-
|
|
18
|
-
export interface ProviderDef {
|
|
19
|
-
/** Stable id, also the config key. */
|
|
20
|
-
id: string;
|
|
21
|
-
/** Human-readable name for the UI. */
|
|
22
|
-
name: string;
|
|
23
|
-
/** OpenAI-compatible base URL (no trailing slash). */
|
|
24
|
-
baseUrl: string;
|
|
25
|
-
/** Environment variable that overrides the stored key. */
|
|
26
|
-
envVar: string;
|
|
27
|
-
/** Model-name prefixes that route to this provider. */
|
|
28
|
-
modelPrefixes: string[];
|
|
29
|
-
/** API-key prefixes used for auto-detection (most specific first). */
|
|
30
|
-
keyPrefixes: string[];
|
|
31
|
-
/** Default model when none specified. */
|
|
32
|
-
defaultModel: string;
|
|
33
|
-
/** Static curated model ids used when /models cannot be fetched. */
|
|
34
|
-
fallbackModels: string[];
|
|
35
|
-
/** If true, the provider also works without a key (anonymous/free tier). */
|
|
36
|
-
keyOptional?: boolean;
|
|
37
|
-
/** When keyOptional and no real key is set, only show models matching this regex. */
|
|
38
|
-
freeModelPattern?: string;
|
|
39
|
-
/** Custom HTTP headers sent with every request (e.g. User-Agent overrides). */
|
|
40
|
-
headers?: Record<string, string>;
|
|
41
|
-
/** Short hint shown in the provider picker UI. */
|
|
42
|
-
hint?: string;
|
|
43
|
-
/** Provider id alias (e.g. "opencode" → resolves to this provider's id). */
|
|
44
|
-
alias?: string;
|
|
45
|
-
/** Prefix to strip from model names before sending to the API (e.g. "opencode/"). */
|
|
46
|
-
modelPrefix?: string;
|
|
47
|
-
}
|
|
48
|
-
|
|
49
|
-
const BUILTIN_PROVIDERS: ProviderDef[] = [
|
|
50
|
-
{
|
|
51
|
-
id: 'deepseek',
|
|
52
|
-
name: 'DeepSeek',
|
|
53
|
-
baseUrl: 'https://api.deepseek.com/v1',
|
|
54
|
-
envVar: 'DEEPSEEK_API_KEY',
|
|
55
|
-
modelPrefixes: ['deepseek'],
|
|
56
|
-
keyPrefixes: ['sk-'],
|
|
57
|
-
defaultModel: 'deepseek-chat',
|
|
58
|
-
fallbackModels: ['deepseek-chat', 'deepseek-reasoner'],
|
|
59
|
-
},
|
|
60
|
-
{
|
|
61
|
-
id: 'gemini',
|
|
62
|
-
name: 'Google Gemini',
|
|
63
|
-
baseUrl: 'https://generativelanguage.googleapis.com/v1beta/openai',
|
|
64
|
-
envVar: 'GEMINI_API_KEY',
|
|
65
|
-
modelPrefixes: ['gemini', 'models/gemini'],
|
|
66
|
-
keyPrefixes: ['AIza'],
|
|
67
|
-
defaultModel: 'gemini-2.5-flash',
|
|
68
|
-
fallbackModels: [
|
|
69
|
-
'gemini-2.5-flash',
|
|
70
|
-
'gemini-2.5-flash-lite',
|
|
71
|
-
'gemini-2.5-pro',
|
|
72
|
-
'gemini-2.0-flash',
|
|
73
|
-
],
|
|
74
|
-
},
|
|
75
|
-
{
|
|
76
|
-
id: 'openrouter',
|
|
77
|
-
name: 'OpenRouter',
|
|
78
|
-
baseUrl: 'https://openrouter.ai/api/v1',
|
|
79
|
-
envVar: 'OPENROUTER_API_KEY',
|
|
80
|
-
modelPrefixes: [],
|
|
81
|
-
keyPrefixes: ['sk-or-'],
|
|
82
|
-
defaultModel: 'deepseek/deepseek-chat',
|
|
83
|
-
fallbackModels: ['deepseek/deepseek-chat', 'openai/gpt-4o-mini', 'anthropic/claude-sonnet-4'],
|
|
84
|
-
},
|
|
85
|
-
{
|
|
86
|
-
id: 'openai',
|
|
87
|
-
name: 'OpenAI',
|
|
88
|
-
baseUrl: 'https://api.openai.com/v1',
|
|
89
|
-
envVar: 'OPENAI_API_KEY',
|
|
90
|
-
modelPrefixes: ['gpt-', 'o1', 'o3', 'o4'],
|
|
91
|
-
keyPrefixes: ['sk-proj-', 'sk-svcacct-'],
|
|
92
|
-
defaultModel: 'gpt-4o',
|
|
93
|
-
fallbackModels: ['gpt-4o', 'gpt-4o-mini'],
|
|
94
|
-
},
|
|
95
|
-
{
|
|
96
|
-
id: 'groq',
|
|
97
|
-
name: 'Groq',
|
|
98
|
-
baseUrl: 'https://api.groq.com/openai/v1',
|
|
99
|
-
envVar: 'GROQ_API_KEY',
|
|
100
|
-
modelPrefixes: ['llama', 'mixtral', 'qwen'],
|
|
101
|
-
keyPrefixes: ['gsk_'],
|
|
102
|
-
defaultModel: 'llama-3.3-70b-versatile',
|
|
103
|
-
fallbackModels: ['llama-3.3-70b-versatile'],
|
|
104
|
-
},
|
|
105
|
-
{
|
|
106
|
-
id: 'xai',
|
|
107
|
-
name: 'xAI Grok',
|
|
108
|
-
baseUrl: 'https://api.x.ai/v1',
|
|
109
|
-
envVar: 'XAI_API_KEY',
|
|
110
|
-
modelPrefixes: ['grok'],
|
|
111
|
-
keyPrefixes: ['xai-'],
|
|
112
|
-
defaultModel: 'grok-2-latest',
|
|
113
|
-
fallbackModels: ['grok-2-latest'],
|
|
114
|
-
},
|
|
115
|
-
{
|
|
116
|
-
id: 'mistral',
|
|
117
|
-
name: 'Mistral',
|
|
118
|
-
baseUrl: 'https://api.mistral.ai/v1',
|
|
119
|
-
envVar: 'MISTRAL_API_KEY',
|
|
120
|
-
modelPrefixes: ['mistral', 'codestral', 'magistral'],
|
|
121
|
-
keyPrefixes: [],
|
|
122
|
-
defaultModel: 'mistral-large-latest',
|
|
123
|
-
fallbackModels: ['mistral-large-latest', 'mistral-small-latest'],
|
|
124
|
-
},
|
|
125
|
-
];
|
|
126
|
-
|
|
127
|
-
/**
|
|
128
|
-
* Mutable provider list — starts as a copy of built-ins, extended by
|
|
129
|
-
* `loadCustomProviders()` which reads `~/.pal/providers.json`.
|
|
130
|
-
*/
|
|
131
|
-
export const PROVIDERS: ProviderDef[] = [...BUILTIN_PROVIDERS];
|
|
132
|
-
|
|
133
|
-
/** Aliases accepted as a provider prefix (e.g. `opencode/model` → zen). */
|
|
134
|
-
const PROVIDER_ALIASES: Record<string, string> = {};
|
|
135
|
-
|
|
136
|
-
let _customLoaded = false;
|
|
137
|
-
|
|
138
|
-
/**
|
|
139
|
-
* Load custom providers from `~/.pal/providers.json` and append them to
|
|
140
|
-
* `PROVIDERS`. Safe to call multiple times — only loads once.
|
|
141
|
-
*/
|
|
142
|
-
export function loadCustomProviders(): void {
|
|
143
|
-
if (_customLoaded) return;
|
|
144
|
-
_customLoaded = true;
|
|
145
|
-
try {
|
|
146
|
-
const {readFileSync} = require('fs');
|
|
147
|
-
const {join} = require('path');
|
|
148
|
-
const configDir = join(process.env.USERPROFILE ?? process.env.HOME ?? '', '.pal');
|
|
149
|
-
const customPath = join(configDir, 'providers.json');
|
|
150
|
-
const raw = readFileSync(customPath, 'utf-8');
|
|
151
|
-
const data = JSON.parse(raw);
|
|
152
|
-
if (Array.isArray(data)) {
|
|
153
|
-
for (const entry of data) {
|
|
154
|
-
if (entry && typeof entry.id === 'string' && typeof entry.baseUrl === 'string') {
|
|
155
|
-
PROVIDERS.push(entry as ProviderDef);
|
|
156
|
-
if (entry.alias) {
|
|
157
|
-
PROVIDER_ALIASES[entry.alias] = entry.id;
|
|
158
|
-
}
|
|
159
|
-
}
|
|
160
|
-
}
|
|
161
|
-
}
|
|
162
|
-
} catch {
|
|
163
|
-
// No custom providers file or invalid JSON — that's fine.
|
|
164
|
-
}
|
|
165
|
-
}
|
|
166
|
-
|
|
167
|
-
/** Look up a provider definition by id. */
|
|
168
|
-
export function getProvider(id: string): ProviderDef | null {
|
|
169
|
-
const resolved = PROVIDER_ALIASES[id] ?? id;
|
|
170
|
-
return PROVIDERS.find((p) => p.id === resolved) ?? null;
|
|
171
|
-
}
|
|
172
|
-
|
|
173
|
-
/**
|
|
174
|
-
* Detect the provider from an API key's shape.
|
|
175
|
-
* Returns null when the key is ambiguous (caller should ask the user).
|
|
176
|
-
*/
|
|
177
|
-
export function detectProvider(apiKey: string): ProviderDef | null {
|
|
178
|
-
const key = apiKey.trim();
|
|
179
|
-
// Most specific prefixes first
|
|
180
|
-
const ordered = PROVIDERS.flatMap((p) => p.keyPrefixes.map((pre) => ({pre, p}))).sort(
|
|
181
|
-
(a, b) => b.pre.length - a.pre.length,
|
|
182
|
-
);
|
|
183
|
-
for (const {pre, p} of ordered) {
|
|
184
|
-
if (key.startsWith(pre)) return p;
|
|
185
|
-
}
|
|
186
|
-
return null;
|
|
187
|
-
}
|
|
188
|
-
|
|
189
|
-
/**
|
|
190
|
-
* Resolve a model spec to its provider and bare model name.
|
|
191
|
-
* `deepseek/deepseek-chat` → { provider: deepseek, model: deepseek-chat }
|
|
192
|
-
* `gemini-2.5-flash` → { provider: gemini, model: gemini-2.5-flash }
|
|
193
|
-
*/
|
|
194
|
-
export function providerForModel(
|
|
195
|
-
modelSpec: string,
|
|
196
|
-
availableIds: string[] = [],
|
|
197
|
-
): {provider: ProviderDef; model: string} {
|
|
198
|
-
// 1. Explicit `provider/model` prefix (also accepts aliases from PROVIDER_ALIASES)
|
|
199
|
-
const slash = modelSpec.indexOf('/');
|
|
200
|
-
if (slash > 0) {
|
|
201
|
-
const prefix = modelSpec.slice(0, slash);
|
|
202
|
-
const rest = modelSpec.slice(slash + 1);
|
|
203
|
-
const byId = getProvider(prefix);
|
|
204
|
-
if (byId) return {provider: byId, model: rest};
|
|
205
|
-
}
|
|
206
|
-
|
|
207
|
-
// 2. Match by model-name prefix (longest match wins); strip a trailing `/`
|
|
208
|
-
const matches = PROVIDERS.flatMap((p) => p.modelPrefixes.map((mp) => ({mp, p}))).sort(
|
|
209
|
-
(a, b) => b.mp.length - a.mp.length,
|
|
210
|
-
);
|
|
211
|
-
for (const {mp, p} of matches) {
|
|
212
|
-
if (modelSpec === mp) return {provider: p, model: modelSpec};
|
|
213
|
-
if (modelSpec.startsWith(mp + '/')) return {provider: p, model: modelSpec.slice(mp.length + 1)};
|
|
214
|
-
if (!modelSpec.includes('/') && modelSpec.startsWith(mp))
|
|
215
|
-
return {provider: p, model: modelSpec};
|
|
216
|
-
}
|
|
217
|
-
|
|
218
|
-
// 3. Fall back to the first configured provider we have a key for, else Gemini.
|
|
219
|
-
const configured = PROVIDERS.find((p) => availableIds.includes(p.id));
|
|
220
|
-
const fallback = configured ?? getProvider('gemini')!;
|
|
221
|
-
return {provider: fallback, model: modelSpec};
|
|
222
|
-
}
|
|
@@ -1,61 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Provider abstraction — inspired by Pi's pi-ai architecture.
|
|
3
|
-
*
|
|
4
|
-
* A Provider owns: id, auth resolution, models list, streaming.
|
|
5
|
-
* The CLI/engine talks to Provider, not directly to HTTP.
|
|
6
|
-
*/
|
|
7
|
-
|
|
8
|
-
export interface ProviderConfig {
|
|
9
|
-
id: string;
|
|
10
|
-
baseUrl: string;
|
|
11
|
-
apiKey?: string;
|
|
12
|
-
headers?: Record<string, string>;
|
|
13
|
-
/** Prefix to strip from model names before sending to the API (e.g. "opencode/"). */
|
|
14
|
-
modelPrefix?: string;
|
|
15
|
-
}
|
|
16
|
-
|
|
17
|
-
export interface ProviderModel {
|
|
18
|
-
id: string;
|
|
19
|
-
name: string;
|
|
20
|
-
contextWindow?: number;
|
|
21
|
-
maxOutput?: number;
|
|
22
|
-
cost?: {input: number; output: number};
|
|
23
|
-
free?: boolean;
|
|
24
|
-
}
|
|
25
|
-
|
|
26
|
-
export interface Usage {
|
|
27
|
-
promptTokens: number;
|
|
28
|
-
completionTokens: number;
|
|
29
|
-
totalTokens: number;
|
|
30
|
-
/** Tokens served from the provider's prompt cache (DeepSeek/OpenAI/OpenRouter). */
|
|
31
|
-
cachedTokens?: number;
|
|
32
|
-
}
|
|
33
|
-
|
|
34
|
-
export interface StreamEvent {
|
|
35
|
-
type: 'text' | 'tool_use' | 'done' | 'error';
|
|
36
|
-
content?: string;
|
|
37
|
-
toolCall?: {id: string; name: string; arguments: string; extraContent?: Record<string, unknown>};
|
|
38
|
-
usage?: Usage;
|
|
39
|
-
}
|
|
40
|
-
|
|
41
|
-
export interface Provider {
|
|
42
|
-
readonly id: string;
|
|
43
|
-
|
|
44
|
-
/** Initialize the provider (fetch models, validate auth). */
|
|
45
|
-
init(): Promise<void>;
|
|
46
|
-
|
|
47
|
-
/** List available models. */
|
|
48
|
-
models(): Promise<ProviderModel[]>;
|
|
49
|
-
|
|
50
|
-
/** Streaming chat completion. Yields events as SSE chunks arrive. */
|
|
51
|
-
stream(opts: {
|
|
52
|
-
model: string;
|
|
53
|
-
messages: Array<Record<string, unknown>>;
|
|
54
|
-
tools?: Array<{
|
|
55
|
-
type: 'function';
|
|
56
|
-
function: {name: string; description: string; parameters: Record<string, unknown>};
|
|
57
|
-
}>;
|
|
58
|
-
/** Abort signal — cancels the in-flight HTTP request (user interrupt). */
|
|
59
|
-
signal?: AbortSignal;
|
|
60
|
-
}): AsyncGenerator<StreamEvent>;
|
|
61
|
-
}
|