@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.
- package/package.json +1 -1
- package/src/agent/fallback.ts +47 -19
- package/src/agent/run.ts +40 -7
- package/src/agent/turn.ts +380 -0
- package/src/app-config.ts +148 -0
- package/src/extensions.ts +73 -14
- package/src/index.ts +38 -2
- package/src/lifecycle.ts +16 -0
- package/src/provider/auth.ts +1 -0
- package/src/provider/chat.ts +250 -0
- package/src/provider/index.ts +2 -1
- package/src/provider/openrouter.ts +55 -222
- package/src/provider/registry.ts +80 -10
- package/src/provider/responses.ts +271 -0
- package/src/provider/types.ts +19 -1
- package/src/registry.ts +9 -0
- package/src/runtime/state.ts +81 -0
- package/src/session/store.ts +35 -6
- package/src/session/types.ts +4 -0
- package/src/tools/executor.ts +43 -7
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* CLI configuration.
|
|
3
|
+
*
|
|
4
|
+
* Values come from environment variables, then `~/.pal/config.json`, then
|
|
5
|
+
* built-in defaults. Invalid values are reported and ignored rather than
|
|
6
|
+
* silently producing NaN (which previously flowed into retry backoff and the
|
|
7
|
+
* context limit).
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import {loadPermissionConfig} from './config.js';
|
|
11
|
+
import {readPalConfig} from './provider/auth.js';
|
|
12
|
+
import type {PermissionConfig} from './config.js';
|
|
13
|
+
|
|
14
|
+
export interface Config {
|
|
15
|
+
model: string;
|
|
16
|
+
systemPrompt: string;
|
|
17
|
+
maxToolRounds: number;
|
|
18
|
+
maxRetries: number;
|
|
19
|
+
retryBaseMs: number;
|
|
20
|
+
contextLimit: number;
|
|
21
|
+
reasoningEffort: 'low' | 'medium' | 'high';
|
|
22
|
+
/** Extension package names to load (default: ['@pal-code/web-search']). */
|
|
23
|
+
extensions: string[];
|
|
24
|
+
modelRotation: boolean;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
const DEFAULT_SYSTEM_PROMPT = [
|
|
28
|
+
"pal — a terminal coding agent working in the user's project.",
|
|
29
|
+
'TOOLS: Never guess about files — read them. Batch independent tool calls in one response.',
|
|
30
|
+
'PLAN: For any task needing more than ~2 steps, call `todo` first with the full list and update it as you progress. Keep exactly one item in_progress.',
|
|
31
|
+
'VERIFY: After editing code, run `verify` to confirm nothing broke.',
|
|
32
|
+
"DON'T LOOP: Never repeat a tool call with identical arguments — it cannot give a different result. If something fails twice, change approach or report the blocker.",
|
|
33
|
+
'STOP: Once every todo item is done and the request is satisfied, stop calling tools and reply. Do not re-read files you already have.',
|
|
34
|
+
'DELEGATE: For broad multi-file exploration, use `delegate` to keep your own context small.',
|
|
35
|
+
'Windows shell: the bash tool ALREADY runs inside cmd.exe. Write native commands directly (`dir`, `type`, `findstr`, `where`) and NEVER prefix them with `cmd /c`. Unix commands (`ls`, `cat`, `grep`, `head`, `rm`) do not exist here. Keep commands to a single line without `&&` chains when possible. Be concise; show code only when asked.',
|
|
36
|
+
].join('\n');
|
|
37
|
+
|
|
38
|
+
const EFFORTS = ['low', 'medium', 'high'] as const;
|
|
39
|
+
|
|
40
|
+
/** Parse a non-negative integer env var, warning and falling back when invalid. */
|
|
41
|
+
function intEnv(name: string, fallback: number, min = 0): number {
|
|
42
|
+
const raw = process.env[name]?.trim();
|
|
43
|
+
if (!raw) return fallback;
|
|
44
|
+
if (!/^\d+$/.test(raw)) {
|
|
45
|
+
console.error(`pal: ignoring invalid ${name}=${JSON.stringify(raw)} — using ${fallback}`);
|
|
46
|
+
return fallback;
|
|
47
|
+
}
|
|
48
|
+
const n = Number.parseInt(raw, 10);
|
|
49
|
+
if (n < min) {
|
|
50
|
+
console.error(`pal: ${name}=${n} is below the minimum ${min} — using ${fallback}`);
|
|
51
|
+
return fallback;
|
|
52
|
+
}
|
|
53
|
+
return n;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
function effortEnv(): 'low' | 'medium' | 'high' {
|
|
57
|
+
const raw = process.env.REASONING_EFFORT;
|
|
58
|
+
if (raw === undefined || raw === '') return 'medium';
|
|
59
|
+
if ((EFFORTS as readonly string[]).includes(raw)) return raw as (typeof EFFORTS)[number];
|
|
60
|
+
console.error(`pal: ignoring invalid REASONING_EFFORT=${JSON.stringify(raw)} — using medium`);
|
|
61
|
+
return 'medium';
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function strEnv(name: string, fallback: string): string {
|
|
65
|
+
const raw = process.env[name];
|
|
66
|
+
return raw && raw.trim() ? raw : fallback;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
function boolValue(value: unknown): boolean | undefined {
|
|
70
|
+
if (typeof value === 'boolean') return value;
|
|
71
|
+
if (typeof value !== 'string') return undefined;
|
|
72
|
+
if (/^(1|true|on|yes)$/i.test(value.trim())) return true;
|
|
73
|
+
if (/^(0|false|off|no)$/i.test(value.trim())) return false;
|
|
74
|
+
return undefined;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
function boolEnv(name: string, fallback: boolean): boolean {
|
|
78
|
+
return boolValue(process.env[name]) ?? fallback;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* Read a positive integer out of a config file value.
|
|
83
|
+
*
|
|
84
|
+
* Returns undefined for anything that isn't a finite number at or above `min`,
|
|
85
|
+
* so a typo in `~/.pal/config.json` falls through to the default rather than
|
|
86
|
+
* poisoning the context limit with NaN (which would disable compaction).
|
|
87
|
+
*/
|
|
88
|
+
function intConfig(value: unknown, label: string, min = 1000): number | undefined {
|
|
89
|
+
if (typeof value !== 'number' || !Number.isFinite(value) || value < min) {
|
|
90
|
+
if (value !== undefined) {
|
|
91
|
+
console.error(
|
|
92
|
+
`pal: ignoring invalid ${label}=${JSON.stringify(value)} in config.json — must be a number >= ${min}`,
|
|
93
|
+
);
|
|
94
|
+
}
|
|
95
|
+
return undefined;
|
|
96
|
+
}
|
|
97
|
+
return Math.floor(value);
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
export function loadConfig(): Config {
|
|
101
|
+
const saved = readPalConfig();
|
|
102
|
+
const savedModel =
|
|
103
|
+
typeof saved.model === 'string' && saved.model.trim() ? saved.model : undefined;
|
|
104
|
+
const savedPrompt =
|
|
105
|
+
typeof saved.systemPrompt === 'string' && saved.systemPrompt.trim()
|
|
106
|
+
? saved.systemPrompt
|
|
107
|
+
: undefined;
|
|
108
|
+
|
|
109
|
+
// Extensions: use saved list or default to the shipped set.
|
|
110
|
+
const savedExtensions = Array.isArray(saved.extensions) ? saved.extensions : undefined;
|
|
111
|
+
const extensions = savedExtensions ?? [
|
|
112
|
+
'@pal-code/web-search',
|
|
113
|
+
'@pal-code/agents',
|
|
114
|
+
'@pal-code/mcp',
|
|
115
|
+
];
|
|
116
|
+
|
|
117
|
+
// Context limit: env wins, then config.json, then the built-in default.
|
|
118
|
+
const savedContextLimit = intConfig(saved.contextLimit, 'contextLimit');
|
|
119
|
+
|
|
120
|
+
return {
|
|
121
|
+
model: strEnv('MODEL', strEnv('PAL_MODEL', savedModel ?? 'deepseek/deepseek-chat')),
|
|
122
|
+
systemPrompt: strEnv('SYSTEM_PROMPT', savedPrompt ?? DEFAULT_SYSTEM_PROMPT),
|
|
123
|
+
maxToolRounds: intEnv('MAX_TOOL_ROUNDS', 100, 1),
|
|
124
|
+
maxRetries: intEnv('MAX_RETRIES', 1, 0),
|
|
125
|
+
retryBaseMs: intEnv('RETRY_BASE_MS', 2000, 0),
|
|
126
|
+
contextLimit: intEnv('CONTEXT_LIMIT', savedContextLimit ?? 200_000, 1000),
|
|
127
|
+
reasoningEffort: effortEnv(),
|
|
128
|
+
extensions,
|
|
129
|
+
modelRotation: boolEnv('PAL_MODEL_ROTATION', boolValue(saved.modelRotation) ?? false),
|
|
130
|
+
};
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
// ── Permissions ──────────────────────────────────────────────────────────────
|
|
134
|
+
|
|
135
|
+
let _cachedPermissions: PermissionConfig | null = null;
|
|
136
|
+
|
|
137
|
+
/** Load and cache the merged permission config. Clears cache on /reload. */
|
|
138
|
+
export function loadPermissions(): PermissionConfig {
|
|
139
|
+
if (!_cachedPermissions) {
|
|
140
|
+
_cachedPermissions = loadPermissionConfig();
|
|
141
|
+
}
|
|
142
|
+
return _cachedPermissions;
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/** Clear permission cache (for /reload or testing). */
|
|
146
|
+
export function clearPermissionsCache(): void {
|
|
147
|
+
_cachedPermissions = null;
|
|
148
|
+
}
|
package/src/extensions.ts
CHANGED
|
@@ -76,6 +76,31 @@ export interface ToolExtension {
|
|
|
76
76
|
tools: ToolDef[];
|
|
77
77
|
/** Tool name → handler function mapping. */
|
|
78
78
|
handlers: Record<string, ToolHandler>;
|
|
79
|
+
/**
|
|
80
|
+
* Whether the extension can actually do anything right now — a key is
|
|
81
|
+
* configured, a binary is present, a server is reachable.
|
|
82
|
+
*
|
|
83
|
+
* When this is `false` (or a getter returns `false`), `loadExtensions()`
|
|
84
|
+
* drops the extension completely: no tools, no prompt, no lifecycle hooks,
|
|
85
|
+
* and `LoadedExtensions.unavailable` records why. The agent cannot tell the
|
|
86
|
+
* difference between "installed but inert" and "not installed", which is the
|
|
87
|
+
* point — a configured-but-unusable extension must not add tokens or tempt
|
|
88
|
+
* the model into calling tools that can only fail.
|
|
89
|
+
*
|
|
90
|
+
* Read after `setup()`, so an extension may register a capability first and
|
|
91
|
+
* then decide. Defaults to available.
|
|
92
|
+
*/
|
|
93
|
+
available?: boolean;
|
|
94
|
+
/**
|
|
95
|
+
* Guidance appended to the system prompt while this extension is loaded and
|
|
96
|
+
* available — typically "when to use these tools" advice the tool schemas
|
|
97
|
+
* cannot express.
|
|
98
|
+
*
|
|
99
|
+
* Skipped entirely when the extension is absent or unavailable, and skipped
|
|
100
|
+
* for a primary agent whose `tools` list excludes this extension's tools (a
|
|
101
|
+
* narrowed agent should not be told about tools it cannot call).
|
|
102
|
+
*/
|
|
103
|
+
prompt?: string;
|
|
79
104
|
/**
|
|
80
105
|
* Optional setup hook, called once after the extension loads. Lets an
|
|
81
106
|
* extension register process-wide capabilities that aren't tools — e.g.
|
|
@@ -96,8 +121,19 @@ export interface LoadedExtensions {
|
|
|
96
121
|
handlers: Record<string, ToolHandler>;
|
|
97
122
|
/** Lifecycle handler sets, one entry per extension that declared them. */
|
|
98
123
|
lifecycle: LifecycleHandlers[];
|
|
124
|
+
/**
|
|
125
|
+
* System-prompt fragments, one per loaded-and-available extension that
|
|
126
|
+
* declared one, in load order. Empty when none did.
|
|
127
|
+
*/
|
|
128
|
+
prompts: string[];
|
|
99
129
|
/** Package names that loaded successfully, in input order. */
|
|
100
130
|
loaded: string[];
|
|
131
|
+
/**
|
|
132
|
+
* Package names that loaded but reported themselves unavailable — installed,
|
|
133
|
+
* but with nothing to contribute (missing key, server down). Reported to the
|
|
134
|
+
* UI so the user sees "inactive" rather than a silently missing extension.
|
|
135
|
+
*/
|
|
136
|
+
unavailable: Array<{pkg: string; reason?: string}>;
|
|
101
137
|
/** Package names that failed, with the reason. */
|
|
102
138
|
failed: Array<{pkg: string; reason: string}>;
|
|
103
139
|
}
|
|
@@ -594,7 +630,9 @@ export async function loadExtensions(
|
|
|
594
630
|
const allTools: ToolDef[] = [];
|
|
595
631
|
const allHandlers: Record<string, ToolHandler> = {};
|
|
596
632
|
const allLifecycle: LifecycleHandlers[] = [];
|
|
633
|
+
const allPrompts: string[] = [];
|
|
597
634
|
const loaded: string[] = [];
|
|
635
|
+
const unavailable: Array<{pkg: string; reason?: string}> = [];
|
|
598
636
|
const failed: Array<{pkg: string; reason: string}> = [];
|
|
599
637
|
|
|
600
638
|
// Clear any previously-registered role provider *before* (re)loading. If the
|
|
@@ -620,34 +658,55 @@ export async function loadExtensions(
|
|
|
620
658
|
continue;
|
|
621
659
|
}
|
|
622
660
|
|
|
623
|
-
allTools.push(...ext.tools);
|
|
624
|
-
Object.assign(allHandlers, ext.handlers);
|
|
625
|
-
// Kept per-extension (not merged key-wise like handlers) so one
|
|
626
|
-
// extension's onToolCall cannot clobber another's at load time.
|
|
627
|
-
if (ext.lifecycle && typeof ext.lifecycle === 'object') {
|
|
628
|
-
allLifecycle.push(ext.lifecycle);
|
|
629
|
-
}
|
|
630
|
-
loaded.push(pkg);
|
|
631
|
-
|
|
632
661
|
// Extension-granted capabilities (non-tool) — e.g. the role provider.
|
|
633
662
|
// A failed setup is reported through `failed`, not the console: loading
|
|
634
663
|
// happens after the CLI's TUI starts, and any stdout/stderr write smears
|
|
635
664
|
// the frame.
|
|
665
|
+
//
|
|
666
|
+
// Runs *before* the availability check so an extension may register a
|
|
667
|
+
// capability and then decide whether it is usable (MCP connects, then
|
|
668
|
+
// reports). A failed setup marks it unavailable below.
|
|
669
|
+
let setupError: string | undefined;
|
|
636
670
|
if (typeof ext.setup === 'function') {
|
|
637
671
|
try {
|
|
638
672
|
await ext.setup();
|
|
639
673
|
} catch (err) {
|
|
640
|
-
failed.
|
|
641
|
-
pkg,
|
|
642
|
-
reason: `setup failed — ${err instanceof Error ? err.message : String(err)}`,
|
|
643
|
-
});
|
|
674
|
+
setupError = `setup failed — ${err instanceof Error ? err.message : String(err)}`;
|
|
644
675
|
}
|
|
645
676
|
}
|
|
677
|
+
|
|
678
|
+
// `available` is read here, after setup, so a getter or a setup-time flag
|
|
679
|
+
// is honoured. Anything falsy-but-not-undefined counts as unavailable.
|
|
680
|
+
const isAvailable = setupError === undefined && ext.available !== false;
|
|
681
|
+
|
|
682
|
+
if (!isAvailable) {
|
|
683
|
+
unavailable.push({pkg, reason: setupError});
|
|
684
|
+
continue;
|
|
685
|
+
}
|
|
686
|
+
|
|
687
|
+
allTools.push(...ext.tools);
|
|
688
|
+
Object.assign(allHandlers, ext.handlers);
|
|
689
|
+
// Kept per-extension (not merged key-wise like handlers) so one
|
|
690
|
+
// extension's onToolCall cannot clobber another's at load time.
|
|
691
|
+
if (ext.lifecycle && typeof ext.lifecycle === 'object') {
|
|
692
|
+
allLifecycle.push(ext.lifecycle);
|
|
693
|
+
}
|
|
694
|
+
const prompt = typeof ext.prompt === 'string' ? ext.prompt.trim() : '';
|
|
695
|
+
if (prompt) allPrompts.push(prompt);
|
|
696
|
+
loaded.push(pkg);
|
|
646
697
|
} catch (err) {
|
|
647
698
|
const reason = err instanceof Error ? err.message : String(err);
|
|
648
699
|
failed.push({pkg, reason});
|
|
649
700
|
}
|
|
650
701
|
}
|
|
651
702
|
|
|
652
|
-
return {
|
|
703
|
+
return {
|
|
704
|
+
tools: allTools,
|
|
705
|
+
handlers: allHandlers,
|
|
706
|
+
lifecycle: allLifecycle,
|
|
707
|
+
prompts: allPrompts,
|
|
708
|
+
loaded,
|
|
709
|
+
unavailable,
|
|
710
|
+
failed,
|
|
711
|
+
};
|
|
653
712
|
}
|
package/src/index.ts
CHANGED
|
@@ -1,5 +1,11 @@
|
|
|
1
1
|
// Provider abstraction (preferred)
|
|
2
|
-
export type {
|
|
2
|
+
export type {
|
|
3
|
+
Provider,
|
|
4
|
+
ProviderConfig,
|
|
5
|
+
ProviderModel,
|
|
6
|
+
StreamEvent,
|
|
7
|
+
ModelRoute,
|
|
8
|
+
} from './provider/types.js';
|
|
3
9
|
export {createOpenRouterProvider} from './provider/openrouter.js';
|
|
4
10
|
export {
|
|
5
11
|
resolveAuth,
|
|
@@ -18,6 +24,8 @@ export {
|
|
|
18
24
|
detectProvider,
|
|
19
25
|
providerForModel,
|
|
20
26
|
loadCustomProviders,
|
|
27
|
+
resolveRoute,
|
|
28
|
+
mergeProviders,
|
|
21
29
|
} from './provider/registry.js';
|
|
22
30
|
export type {ProviderDef} from './provider/registry.js';
|
|
23
31
|
|
|
@@ -90,8 +98,31 @@ export type {RoleSpec, RoleKind, RoleProvider, PrimarySpec} from './agent/roles.
|
|
|
90
98
|
export {buildSkillsPrompt, clearSkillsCache, listSkills} from './agent/skills.js';
|
|
91
99
|
export type {Skill} from './agent/skills.js';
|
|
92
100
|
export {clearFileRolesCache} from './agent/file-roles.js';
|
|
101
|
+
export {
|
|
102
|
+
runTurn,
|
|
103
|
+
ensureExtensionsLoaded,
|
|
104
|
+
reloadExtensions,
|
|
105
|
+
isReadOnlyPrimary,
|
|
106
|
+
allowedToolsForPrimary,
|
|
107
|
+
composeSystemPrompt,
|
|
108
|
+
DEFAULT_EXTENSIONS,
|
|
109
|
+
} from './agent/turn.js';
|
|
110
|
+
export type {
|
|
111
|
+
AgentUi,
|
|
112
|
+
Approval,
|
|
113
|
+
ApprovalDecision,
|
|
114
|
+
TurnResult,
|
|
115
|
+
TurnSettings,
|
|
116
|
+
ExtensionStatus,
|
|
117
|
+
McpServerStatus,
|
|
118
|
+
} from './agent/turn.js';
|
|
119
|
+
|
|
120
|
+
export {createSharedState} from './runtime/state.js';
|
|
121
|
+
export type {SharedState, BackgroundAgent, TodoItem} from './runtime/state.js';
|
|
93
122
|
|
|
94
123
|
// Config
|
|
124
|
+
export {loadConfig, loadPermissions, clearPermissionsCache} from './app-config.js';
|
|
125
|
+
export type {Config} from './app-config.js';
|
|
95
126
|
export {loadAgentConfig, isPathIgnored, clearConfigCache, resolveProjectRoot} from './config.js';
|
|
96
127
|
export {
|
|
97
128
|
loadPermissionConfig,
|
|
@@ -139,7 +170,12 @@ export type {
|
|
|
139
170
|
} from './extensions.js';
|
|
140
171
|
|
|
141
172
|
// Extension lifecycle hooks
|
|
142
|
-
export {
|
|
173
|
+
export {
|
|
174
|
+
emitLifecycleEvent,
|
|
175
|
+
getExtensionPrompts,
|
|
176
|
+
registerExtensionLifecycle,
|
|
177
|
+
registerExtensionPrompts,
|
|
178
|
+
} from './lifecycle.js';
|
|
143
179
|
export type {
|
|
144
180
|
TurnContext,
|
|
145
181
|
ToolCallEvent,
|
package/src/lifecycle.ts
CHANGED
|
@@ -79,6 +79,22 @@ export function registerExtensionLifecycle(hooks: readonly LifecycleHandlers[]):
|
|
|
79
79
|
registry.lifecycleHooks = [...hooks];
|
|
80
80
|
}
|
|
81
81
|
|
|
82
|
+
/**
|
|
83
|
+
* Replace the registered extension prompt fragments.
|
|
84
|
+
*
|
|
85
|
+
* Replace, not merge — same reason as lifecycle hooks: a `/reload` that drops
|
|
86
|
+
* an extension, or drops the key that made it available, must not leave its
|
|
87
|
+
* guidance behind in the system prompt.
|
|
88
|
+
*/
|
|
89
|
+
export function registerExtensionPrompts(prompts: readonly string[]): void {
|
|
90
|
+
registry.extensionPrompts = [...prompts];
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** The extension prompt fragments currently registered (read-only view). */
|
|
94
|
+
export function getExtensionPrompts(): string[] {
|
|
95
|
+
return registry.extensionPrompts;
|
|
96
|
+
}
|
|
97
|
+
|
|
82
98
|
/**
|
|
83
99
|
* Notify every registered lifecycle hook for `event`, in registration order.
|
|
84
100
|
*
|
package/src/provider/auth.ts
CHANGED
|
@@ -132,6 +132,7 @@ export function saveKey(providerId: string, apiKey: string): void {
|
|
|
132
132
|
const keys = {...((cfg.keys ?? {}) as Record<string, string>)};
|
|
133
133
|
keys[providerId] = apiKey;
|
|
134
134
|
cfg.keys = keys;
|
|
135
|
+
if (cfg.keyless === providerId) delete cfg.keyless;
|
|
135
136
|
|
|
136
137
|
const p = configPath();
|
|
137
138
|
mkdirSync(dirname(p), {recursive: true});
|
|
@@ -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
|
+
}
|
package/src/provider/index.ts
CHANGED
|
@@ -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';
|