@pal-code/core 0.0.17 → 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/turn.ts +380 -0
- package/src/app-config.ts +148 -0
- package/src/extensions.ts +73 -14
- package/src/index.ts +29 -1
- package/src/lifecycle.ts +16 -0
- package/src/provider/auth.ts +1 -0
- package/src/provider/openrouter.ts +13 -9
- package/src/provider/registry.ts +26 -0
- package/src/registry.ts +9 -0
- package/src/runtime/state.ts +81 -0
- package/src/tools/executor.ts +6 -1
package/package.json
CHANGED
package/src/agent/fallback.ts
CHANGED
|
@@ -6,6 +6,8 @@
|
|
|
6
6
|
* only renders the events this yields.
|
|
7
7
|
*
|
|
8
8
|
* Strategy: same provider first (same rate-limit pool), then cross-provider.
|
|
9
|
+
* Rotation is opt-in (`rotate`); by default a failing turn retries the selected
|
|
10
|
+
* model and then reports the error instead of silently switching models.
|
|
9
11
|
* - quota exhausted → switch immediately (retrying burns RPM for nothing)
|
|
10
12
|
* - rate limited → exponential backoff, `maxRetries` attempts, then switch
|
|
11
13
|
* - other retryable → backoff, `maxRetries` attempts, then switch
|
|
@@ -170,6 +172,11 @@ export interface RunWithFallbackOptions {
|
|
|
170
172
|
maxRetries?: number;
|
|
171
173
|
/** Base backoff in ms; doubles each attempt (default 2000). */
|
|
172
174
|
retryBaseMs?: number;
|
|
175
|
+
/**
|
|
176
|
+
* Try other models/providers when the selected one fails (default false).
|
|
177
|
+
* Core also retries the same model; this only controls rotation.
|
|
178
|
+
*/
|
|
179
|
+
rotate?: boolean;
|
|
173
180
|
keys: ProviderKeys;
|
|
174
181
|
executeTool: RunAgentOptions['executeTool'];
|
|
175
182
|
/**
|
|
@@ -220,6 +227,7 @@ export async function* runWithFallback(
|
|
|
220
227
|
compactionNote,
|
|
221
228
|
maxRetries = 1,
|
|
222
229
|
retryBaseMs = 2000,
|
|
230
|
+
rotate = false,
|
|
223
231
|
keys,
|
|
224
232
|
executeTool,
|
|
225
233
|
childExecuteTool,
|
|
@@ -232,22 +240,24 @@ export async function* runWithFallback(
|
|
|
232
240
|
|
|
233
241
|
const {provider: baseDef, model: baseModel} = providerForModel(model, Object.keys(keys));
|
|
234
242
|
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
243
|
+
const modelsToTry = [model];
|
|
244
|
+
if (rotate) {
|
|
245
|
+
// Same provider: other models from its live list. Never invented — if the
|
|
246
|
+
// fetch failed there are simply no same-provider fallbacks.
|
|
247
|
+
if (providerAccessible(baseDef, keys)) {
|
|
248
|
+
const ids = await resolveModelIds(baseDef, keys[baseDef.id] ?? '');
|
|
249
|
+
for (const id of ids) {
|
|
250
|
+
if (id !== baseModel) modelsToTry.push(`${baseDef.id}/${id}`);
|
|
251
|
+
}
|
|
242
252
|
}
|
|
243
|
-
}
|
|
244
253
|
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
254
|
+
// Cross provider: only accessible providers, at their default model.
|
|
255
|
+
for (const p of PROVIDERS) {
|
|
256
|
+
if (p.id !== baseDef.id && providerAccessible(p, keys)) {
|
|
257
|
+
modelsToTry.push(`${p.id}/${p.defaultModel}`);
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
}
|
|
251
261
|
|
|
252
262
|
// Track consecutive quota exhaustion per provider. If ALL models from a
|
|
253
263
|
// provider share the same quota pool (e.g. Zen free tier), short-circuit
|
|
@@ -315,11 +325,13 @@ export async function* runWithFallback(
|
|
|
315
325
|
const msg = err instanceof Error ? err.message : String(err);
|
|
316
326
|
|
|
317
327
|
if (isQuotaExhausted(msg)) {
|
|
328
|
+
quotaExhaustedProviders.add(modelDef.id);
|
|
318
329
|
yield {
|
|
319
330
|
type: 'notice',
|
|
320
|
-
text:
|
|
331
|
+
text: rotate
|
|
332
|
+
? `${modelSpec} quota exhausted — skipping remaining ${modelDef.id} models`
|
|
333
|
+
: `${modelSpec} quota exhausted — /rotation switches models automatically`,
|
|
321
334
|
};
|
|
322
|
-
quotaExhaustedProviders.add(modelDef.id);
|
|
323
335
|
break; // next model (from a different provider)
|
|
324
336
|
}
|
|
325
337
|
|
|
@@ -333,7 +345,12 @@ export async function* runWithFallback(
|
|
|
333
345
|
await sleep(delay);
|
|
334
346
|
continue;
|
|
335
347
|
}
|
|
336
|
-
yield {
|
|
348
|
+
yield {
|
|
349
|
+
type: 'notice',
|
|
350
|
+
text: rotate
|
|
351
|
+
? `${modelSpec} exhausted, trying next…`
|
|
352
|
+
: `${modelSpec} rate-limited — /rotation tries the next model`,
|
|
353
|
+
};
|
|
337
354
|
break;
|
|
338
355
|
}
|
|
339
356
|
|
|
@@ -342,6 +359,12 @@ export async function* runWithFallback(
|
|
|
342
359
|
await sleep(retryBaseMs * 2 ** attempt);
|
|
343
360
|
continue;
|
|
344
361
|
}
|
|
362
|
+
yield {
|
|
363
|
+
type: 'notice',
|
|
364
|
+
text: rotate
|
|
365
|
+
? `${modelSpec} unavailable, trying next…`
|
|
366
|
+
: `${modelSpec} unavailable — /rotation tries the next model`,
|
|
367
|
+
};
|
|
345
368
|
break;
|
|
346
369
|
}
|
|
347
370
|
|
|
@@ -350,6 +373,11 @@ export async function* runWithFallback(
|
|
|
350
373
|
}
|
|
351
374
|
}
|
|
352
375
|
|
|
353
|
-
yield {
|
|
354
|
-
|
|
376
|
+
yield {
|
|
377
|
+
type: 'notice',
|
|
378
|
+
text: rotate
|
|
379
|
+
? 'All models failed (rate limits). Try again in a few minutes.'
|
|
380
|
+
: `${model} failed — /rotation tries other models automatically`,
|
|
381
|
+
};
|
|
382
|
+
throw new Error(rotate ? 'All models failed' : `Model failed: ${model}`);
|
|
355
383
|
}
|
|
@@ -0,0 +1,380 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* One agent turn: drive `runWithFallback` and translate its events into a
|
|
3
|
+
* caller-supplied UI port. The orchestrator is UI-agnostic — the TUI and the
|
|
4
|
+
* WebSocket/desktop frontends are both adapters over `AgentUi`.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import {importExtensionModule, loadExtensions} from '../extensions.js';
|
|
8
|
+
import type {LoadedExtensions} from '../extensions.js';
|
|
9
|
+
import {registerExtensionLifecycle} from '../lifecycle.js';
|
|
10
|
+
import type {ProviderKeys} from '../provider/auth.js';
|
|
11
|
+
import type {Provider} from '../provider/types.js';
|
|
12
|
+
import type {ExtensionStatus, McpServerStatus} from '../runtime/state.js';
|
|
13
|
+
|
|
14
|
+
export type {ExtensionStatus, McpServerStatus} from '../runtime/state.js';
|
|
15
|
+
import {getExtensionPrompts, registerExtensionPrompts} from '../lifecycle.js';
|
|
16
|
+
import {
|
|
17
|
+
CORE_TOOLS,
|
|
18
|
+
getAllTools,
|
|
19
|
+
getExtensionTools,
|
|
20
|
+
registerExtensionTools,
|
|
21
|
+
validateRequiredArgs,
|
|
22
|
+
} from '../tools/definitions.js';
|
|
23
|
+
import type {ToolDef} from '../tools/definitions.js';
|
|
24
|
+
import {executeTool, registerExtensionHandlers} from '../tools/executor.js';
|
|
25
|
+
import type {ToolResult} from '../tools/executor.js';
|
|
26
|
+
import {clearFileRolesCache} from './file-roles.js';
|
|
27
|
+
import {runWithFallback, shortModel} from './fallback.js';
|
|
28
|
+
import {buildRolesPrompt, defaultPrimaryName, listPrimaries, resolvePrimary} from './roles.js';
|
|
29
|
+
import type {ConversationMessage} from './run.js';
|
|
30
|
+
import {buildSkillsPrompt, clearSkillsCache} from './skills.js';
|
|
31
|
+
|
|
32
|
+
export interface TurnResult {
|
|
33
|
+
inputTokens: number;
|
|
34
|
+
outputTokens: number;
|
|
35
|
+
cachedTokens: number;
|
|
36
|
+
/** The model that actually served this turn (may differ from settings.model after a fallback). */
|
|
37
|
+
model: string;
|
|
38
|
+
/** Checkpoints this turn produced (auto-compaction can fire more than once). */
|
|
39
|
+
compactions: Array<{boundary: number; summarized: number; summary: string}>;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** The configuration a single turn needs. The CLI Config is structurally compatible. */
|
|
43
|
+
export interface TurnSettings {
|
|
44
|
+
model: string;
|
|
45
|
+
systemPrompt: string;
|
|
46
|
+
maxToolRounds: number;
|
|
47
|
+
maxRetries: number;
|
|
48
|
+
retryBaseMs: number;
|
|
49
|
+
contextLimit: number;
|
|
50
|
+
reasoningEffort: 'low' | 'medium' | 'high';
|
|
51
|
+
modelRotation: boolean;
|
|
52
|
+
extensions: string[];
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* Everything a turn reports to its frontend. Implementations must be cheap:
|
|
57
|
+
* the loop calls these once per stream event.
|
|
58
|
+
*/
|
|
59
|
+
export interface AgentUi {
|
|
60
|
+
startRun(model: string): void;
|
|
61
|
+
setModel(model: string): void;
|
|
62
|
+
beginRound(round: number, max: number): void;
|
|
63
|
+
text(delta: string): void;
|
|
64
|
+
thinking(delta: string): void;
|
|
65
|
+
toolStart(id: string, name: string, argsSummary: string): void;
|
|
66
|
+
toolEnd(id: string, ok: boolean, content: string): void;
|
|
67
|
+
notice(text: string): void;
|
|
68
|
+
aborted(): void;
|
|
69
|
+
extensions?(extensions: ExtensionStatus[]): void;
|
|
70
|
+
mcpServers?(servers: McpServerStatus[]): void;
|
|
71
|
+
primary?(name: string): void;
|
|
72
|
+
/** Called after extension loading finishes, so the frontend can repaint state. */
|
|
73
|
+
ready?(): void;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
export type ApprovalDecision = 'allow' | 'deny';
|
|
77
|
+
|
|
78
|
+
/** Ask the frontend whether a tool call may run. */
|
|
79
|
+
export type Approval = (
|
|
80
|
+
toolName: string,
|
|
81
|
+
args: Record<string, unknown>,
|
|
82
|
+
) => Promise<ApprovalDecision>;
|
|
83
|
+
|
|
84
|
+
/** Default extension set when the user hasn't configured one. */
|
|
85
|
+
export const DEFAULT_EXTENSIONS = ['@pal-code/web-search', '@pal-code/agents', '@pal-code/mcp'];
|
|
86
|
+
|
|
87
|
+
let extensionsLoaded = false;
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* Apply a successful load to the process: register tools, handlers and
|
|
91
|
+
* lifecycle hooks centrally, then publish the resulting state to the UI port.
|
|
92
|
+
*/
|
|
93
|
+
async function applyLoaded(
|
|
94
|
+
requested: string[],
|
|
95
|
+
result: LoadedExtensions,
|
|
96
|
+
ui: AgentUi,
|
|
97
|
+
currentPrimary?: string,
|
|
98
|
+
): Promise<void> {
|
|
99
|
+
registerExtensionHandlers(result.handlers);
|
|
100
|
+
registerExtensionTools(result.tools);
|
|
101
|
+
registerExtensionLifecycle(result.lifecycle);
|
|
102
|
+
registerExtensionPrompts(result.prompts);
|
|
103
|
+
|
|
104
|
+
const active = new Set(result.loaded);
|
|
105
|
+
const failedByPkg = new Map(result.failed.map((f) => [f.pkg, f.reason]));
|
|
106
|
+
const unavailableByPkg = new Map(result.unavailable.map((u) => [u.pkg, u.reason]));
|
|
107
|
+
ui.extensions?.(
|
|
108
|
+
requested.map((pkg) => {
|
|
109
|
+
// "Loaded but inert" is not a failure: the package worked, it just has
|
|
110
|
+
// nothing to contribute (no key). Kept distinct so the UI does not cry
|
|
111
|
+
// wolf in red about a deliberate state.
|
|
112
|
+
const status = active.has(pkg)
|
|
113
|
+
? 'active'
|
|
114
|
+
: failedByPkg.has(pkg)
|
|
115
|
+
? 'failed'
|
|
116
|
+
: 'inactive';
|
|
117
|
+
return {
|
|
118
|
+
name: pkg.replace(/^@pal-code\//, ''),
|
|
119
|
+
active: status === 'active',
|
|
120
|
+
status,
|
|
121
|
+
reason: failedByPkg.get(pkg) ?? unavailableByPkg.get(pkg) ?? undefined,
|
|
122
|
+
};
|
|
123
|
+
}),
|
|
124
|
+
);
|
|
125
|
+
|
|
126
|
+
// Populate MCP server status live from the manager. Resolved through core
|
|
127
|
+
// so `pal add` installs (under ~/.pal/extensions/node_modules) and compiled
|
|
128
|
+
// binaries both resolve correctly.
|
|
129
|
+
try {
|
|
130
|
+
const mcpMod = (await importExtensionModule('@pal-code/mcp')) as {
|
|
131
|
+
mcpManager?: {getServerDetails(): McpServerStatus[]};
|
|
132
|
+
};
|
|
133
|
+
if (mcpMod?.mcpManager) ui.mcpServers?.(mcpMod.mcpManager.getServerDetails());
|
|
134
|
+
} catch {
|
|
135
|
+
// MCP extension not available — skip silently
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
// Primaries are registered by the extension's setup hook during load.
|
|
139
|
+
// Adopt the configured default unless the caller already picked one.
|
|
140
|
+
const primaries = listPrimaries();
|
|
141
|
+
if (primaries.length > 0 && !primaries.some((p) => p.name === currentPrimary)) {
|
|
142
|
+
ui.primary?.(defaultPrimaryName());
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
ui.ready?.();
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
export async function ensureExtensionsLoaded(
|
|
149
|
+
extensions: string[] | undefined,
|
|
150
|
+
ui: AgentUi,
|
|
151
|
+
currentPrimary?: string,
|
|
152
|
+
): Promise<void> {
|
|
153
|
+
if (extensionsLoaded) return;
|
|
154
|
+
|
|
155
|
+
const requested = extensions ?? DEFAULT_EXTENSIONS;
|
|
156
|
+
const result = await loadExtensions(requested);
|
|
157
|
+
extensionsLoaded = true;
|
|
158
|
+
await applyLoaded(requested, result, ui, currentPrimary);
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/**
|
|
162
|
+
* Re-import extensions without restarting the process. Uses the loader's
|
|
163
|
+
* `cacheBust` option so edited extension source is picked up.
|
|
164
|
+
*/
|
|
165
|
+
export async function reloadExtensions(
|
|
166
|
+
extensions: string[] | undefined,
|
|
167
|
+
ui: AgentUi,
|
|
168
|
+
currentPrimary?: string,
|
|
169
|
+
): Promise<number> {
|
|
170
|
+
const requested = extensions ?? DEFAULT_EXTENSIONS;
|
|
171
|
+
const result = await loadExtensions(requested, {cacheBust: true});
|
|
172
|
+
extensionsLoaded = true;
|
|
173
|
+
clearFileRolesCache();
|
|
174
|
+
clearSkillsCache();
|
|
175
|
+
await applyLoaded(requested, result, ui, currentPrimary);
|
|
176
|
+
return result.tools.length;
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
/**
|
|
180
|
+
* Compose the system prompt for a turn: the base prompt, an optional primary
|
|
181
|
+
* agent preamble, the role-awareness block, the skill listing (only when
|
|
182
|
+
* skill files exist), and any guidance contributed by loaded extensions.
|
|
183
|
+
* Every piece is skipped when absent, so users with no extensions or skills pay
|
|
184
|
+
* nothing in tokens.
|
|
185
|
+
*/
|
|
186
|
+
export function composeSystemPrompt(base: string, primaryName?: string): string {
|
|
187
|
+
const parts: string[] = [];
|
|
188
|
+
const primary = primaryName ? resolvePrimary(primaryName) : null;
|
|
189
|
+
if (primary?.systemPrompt) parts.push(primary.systemPrompt);
|
|
190
|
+
parts.push(base);
|
|
191
|
+
const roles = buildRolesPrompt();
|
|
192
|
+
if (roles) parts.push(roles);
|
|
193
|
+
const skills = buildSkillsPrompt();
|
|
194
|
+
if (skills) parts.push(skills);
|
|
195
|
+
// Placed last on purpose: it is the most specific, most actionable guidance,
|
|
196
|
+
// and it describes tools the model has already seen in its tool list.
|
|
197
|
+
const extensionPrompts = extensionPromptsFor(primary);
|
|
198
|
+
if (extensionPrompts) parts.push(extensionPrompts);
|
|
199
|
+
return parts.join('\n\n');
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
/**
|
|
203
|
+
* Extension guidance for the active primary, or `''` when there is none.
|
|
204
|
+
*
|
|
205
|
+
* A primary that declares a `tools` list is deliberately narrowed (that is how
|
|
206
|
+
* plan mode is enforced). Guidance is withheld unless at least one of the
|
|
207
|
+
* primary's tools actually came from an extension — otherwise a read-only agent
|
|
208
|
+
* would be told about tools it cannot call, which is precisely the wasted
|
|
209
|
+
* attention this mechanism exists to avoid.
|
|
210
|
+
*
|
|
211
|
+
* The narrowing check is coarse by necessity: prompts and tools are collected
|
|
212
|
+
* independently, so this cannot attribute a specific fragment to a specific
|
|
213
|
+
* tool. Extension tools are simply "registered tools that are not core tools".
|
|
214
|
+
*/
|
|
215
|
+
function extensionPromptsFor(primary: {
|
|
216
|
+
tools?: readonly string[];
|
|
217
|
+
} | null): string {
|
|
218
|
+
const prompts = getExtensionPrompts();
|
|
219
|
+
if (prompts.length === 0) return '';
|
|
220
|
+
|
|
221
|
+
if (primary?.tools) {
|
|
222
|
+
const coreNames = new Set(CORE_TOOLS.map((t) => t.function.name));
|
|
223
|
+
const extensionTools = getExtensionTools().filter((t) => !coreNames.has(t.function.name));
|
|
224
|
+
const reachesExtensions = extensionTools.some((t) => primary.tools?.includes(t.function.name));
|
|
225
|
+
if (!reachesExtensions) return '';
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
return prompts.join('\n\n');
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
/** Tools the turn may use, narrowed to the primary agent's set when it declares one. */
|
|
232
|
+
export function toolsForPrimary(primaryName?: string): ToolDef[] {
|
|
233
|
+
const all = getAllTools();
|
|
234
|
+
const primary = primaryName ? resolvePrimary(primaryName) : null;
|
|
235
|
+
if (!primary?.tools) return all;
|
|
236
|
+
const allowed = new Set(primary.tools);
|
|
237
|
+
return all.filter((t) => allowed.has(t.function.name));
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
/**
|
|
241
|
+
* Whether the active primary is a read-only agent.
|
|
242
|
+
*
|
|
243
|
+
* A primary that declares a `tools` list is deliberately narrowed (that is how
|
|
244
|
+
* plan mode is enforced); one without is unrestricted. Propagating this stops a
|
|
245
|
+
* read-only turn from reaching a writer through `delegate`.
|
|
246
|
+
*/
|
|
247
|
+
export function isReadOnlyPrimary(primaryName?: string): boolean {
|
|
248
|
+
const primary = primaryName ? resolvePrimary(primaryName) : null;
|
|
249
|
+
return Array.isArray(primary?.tools);
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
/**
|
|
253
|
+
* The tool names the turn is permitted to dispatch, or `undefined` when the
|
|
254
|
+
* primary is unrestricted. Returned to core so `executeTool` can enforce it.
|
|
255
|
+
*/
|
|
256
|
+
export function allowedToolsForPrimary(primaryName?: string): string[] | undefined {
|
|
257
|
+
return resolvePrimary(primaryName ?? '')?.tools;
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
/** Permission-gated wrapper around `executeTool`. */
|
|
261
|
+
async function gatedExecuteTool(
|
|
262
|
+
name: string,
|
|
263
|
+
argsStr: string,
|
|
264
|
+
toolCallId: string,
|
|
265
|
+
approve: Approval,
|
|
266
|
+
providerConfigOverride?: {
|
|
267
|
+
model: string;
|
|
268
|
+
apiKey: string;
|
|
269
|
+
baseUrl: string;
|
|
270
|
+
keys?: Record<string, string>;
|
|
271
|
+
headers?: Record<string, string>;
|
|
272
|
+
systemPromptAppend?: string;
|
|
273
|
+
readOnly?: boolean;
|
|
274
|
+
allowedTools?: string[];
|
|
275
|
+
},
|
|
276
|
+
signal?: AbortSignal,
|
|
277
|
+
): Promise<ToolResult> {
|
|
278
|
+
let args: Record<string, unknown> = {};
|
|
279
|
+
try {
|
|
280
|
+
args = argsStr && argsStr.trim() ? JSON.parse(argsStr) : {};
|
|
281
|
+
} catch {
|
|
282
|
+
// If args can't be parsed, let executeTool handle the error.
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
// Reject schema-incomplete calls before the permission gate, so a call
|
|
286
|
+
// missing required arguments can't trigger an approval prompt and then fail.
|
|
287
|
+
const validationError = validateRequiredArgs(name, args);
|
|
288
|
+
if (validationError) {
|
|
289
|
+
return {toolCallId, content: validationError, error: true};
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
const decision = await approve(name, args);
|
|
293
|
+
if (decision === 'deny') {
|
|
294
|
+
return {toolCallId, content: `Error: Permission denied for ${name}.`, error: true};
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
return executeTool(name, argsStr, toolCallId, providerConfigOverride, signal);
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
/**
|
|
301
|
+
* Run one user turn against the shared agent loop. All UI effects go through
|
|
302
|
+
* `ui`; all approval decisions go through `approve`.
|
|
303
|
+
*/
|
|
304
|
+
export async function runTurn(
|
|
305
|
+
userMessage: string,
|
|
306
|
+
messages: ConversationMessage[],
|
|
307
|
+
settings: TurnSettings,
|
|
308
|
+
allKeys: ProviderKeys,
|
|
309
|
+
createProvider: (model: string) => Provider,
|
|
310
|
+
ui: AgentUi,
|
|
311
|
+
approve: Approval,
|
|
312
|
+
primaryName?: string,
|
|
313
|
+
compactedSeq = 0,
|
|
314
|
+
compactionNote = '',
|
|
315
|
+
signal?: AbortSignal,
|
|
316
|
+
): Promise<TurnResult> {
|
|
317
|
+
await ensureExtensionsLoaded(settings.extensions, ui, primaryName);
|
|
318
|
+
|
|
319
|
+
messages.push({role: 'user', content: userMessage});
|
|
320
|
+
|
|
321
|
+
ui.startRun(shortModel(settings.model));
|
|
322
|
+
|
|
323
|
+
let usage = {inputTokens: 0, outputTokens: 0, cachedTokens: 0};
|
|
324
|
+
let activeModel = settings.model;
|
|
325
|
+
const compactions: TurnResult['compactions'] = [];
|
|
326
|
+
|
|
327
|
+
for await (const ev of runWithFallback({
|
|
328
|
+
messages,
|
|
329
|
+
tools: toolsForPrimary(primaryName),
|
|
330
|
+
model: settings.model,
|
|
331
|
+
systemPrompt: composeSystemPrompt(settings.systemPrompt, primaryName),
|
|
332
|
+
maxToolRounds: settings.maxToolRounds,
|
|
333
|
+
contextLimit: settings.contextLimit,
|
|
334
|
+
reasoningEffort: settings.reasoningEffort,
|
|
335
|
+
compactedSeq,
|
|
336
|
+
compactionNote,
|
|
337
|
+
maxRetries: settings.maxRetries,
|
|
338
|
+
retryBaseMs: settings.retryBaseMs,
|
|
339
|
+
rotate: settings.modelRotation,
|
|
340
|
+
keys: allKeys,
|
|
341
|
+
executeTool: (name, argsStr, toolCallId, override, signal) =>
|
|
342
|
+
gatedExecuteTool(name, argsStr, toolCallId, approve, override, signal),
|
|
343
|
+
childExecuteTool: (name, argsStr, toolCallId, override, signal) =>
|
|
344
|
+
gatedExecuteTool(name, argsStr, toolCallId, approve, override, signal),
|
|
345
|
+
signal,
|
|
346
|
+
primary: primaryName,
|
|
347
|
+
readOnly: isReadOnlyPrimary(primaryName),
|
|
348
|
+
allowedTools: allowedToolsForPrimary(primaryName),
|
|
349
|
+
createProvider: (spec: string) => createProvider(spec),
|
|
350
|
+
})) {
|
|
351
|
+
if (ev.type === 'model-start') {
|
|
352
|
+
activeModel = ev.model;
|
|
353
|
+
ui.setModel(shortModel(ev.model));
|
|
354
|
+
} else if (ev.type === 'round-start') ui.beginRound(ev.round, ev.max);
|
|
355
|
+
else if (ev.type === 'text-delta') ui.text(ev.content);
|
|
356
|
+
else if (ev.type === 'thinking-delta') ui.thinking(ev.content);
|
|
357
|
+
else if (ev.type === 'tool-start') ui.toolStart(ev.id, ev.name, ev.argsSummary);
|
|
358
|
+
else if (ev.type === 'tool-end') ui.toolEnd(ev.id, ev.ok, ev.content);
|
|
359
|
+
else if (ev.type === 'notice') {
|
|
360
|
+
// The compaction notice is superseded by the caller's green transcript
|
|
361
|
+
// line; the dim inline copy vanished with the run block's collapse.
|
|
362
|
+
if (!ev.text.startsWith('Context compacted')) ui.notice(ev.text);
|
|
363
|
+
} else if (ev.type === 'compacted') {
|
|
364
|
+
compactions.push({
|
|
365
|
+
boundary: ev.boundary,
|
|
366
|
+
summarized: ev.summarized,
|
|
367
|
+
summary: ev.summary,
|
|
368
|
+
});
|
|
369
|
+
} else if (ev.type === 'aborted') ui.aborted();
|
|
370
|
+
else if (ev.type === 'done') usage = ev.usage;
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
return {
|
|
374
|
+
inputTokens: usage.inputTokens,
|
|
375
|
+
outputTokens: usage.outputTokens,
|
|
376
|
+
cachedTokens: usage.cachedTokens,
|
|
377
|
+
model: activeModel,
|
|
378
|
+
compactions,
|
|
379
|
+
};
|
|
380
|
+
}
|
|
@@ -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
|
@@ -98,8 +98,31 @@ export type {RoleSpec, RoleKind, RoleProvider, PrimarySpec} from './agent/roles.
|
|
|
98
98
|
export {buildSkillsPrompt, clearSkillsCache, listSkills} from './agent/skills.js';
|
|
99
99
|
export type {Skill} from './agent/skills.js';
|
|
100
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';
|
|
101
122
|
|
|
102
123
|
// Config
|
|
124
|
+
export {loadConfig, loadPermissions, clearPermissionsCache} from './app-config.js';
|
|
125
|
+
export type {Config} from './app-config.js';
|
|
103
126
|
export {loadAgentConfig, isPathIgnored, clearConfigCache, resolveProjectRoot} from './config.js';
|
|
104
127
|
export {
|
|
105
128
|
loadPermissionConfig,
|
|
@@ -147,7 +170,12 @@ export type {
|
|
|
147
170
|
} from './extensions.js';
|
|
148
171
|
|
|
149
172
|
// Extension lifecycle hooks
|
|
150
|
-
export {
|
|
173
|
+
export {
|
|
174
|
+
emitLifecycleEvent,
|
|
175
|
+
getExtensionPrompts,
|
|
176
|
+
registerExtensionLifecycle,
|
|
177
|
+
registerExtensionPrompts,
|
|
178
|
+
} from './lifecycle.js';
|
|
151
179
|
export type {
|
|
152
180
|
TurnContext,
|
|
153
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});
|
|
@@ -33,24 +33,28 @@ function randomBase62(len: number): string {
|
|
|
33
33
|
return out;
|
|
34
34
|
}
|
|
35
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
|
+
|
|
36
42
|
/** Expand header-value tokens.
|
|
37
43
|
* `__sesid__` → `ses_` + 12 lowercase hex + 14 base62
|
|
38
44
|
* `__random:32__` → 32-char random hex
|
|
39
45
|
* `__random:ses_:32__` → `ses_` + 32-char random hex
|
|
40
|
-
*
|
|
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.
|
|
41
49
|
*/
|
|
42
50
|
export function expandRandomValue(val: string): string {
|
|
43
51
|
if (val === '__sesid__') {
|
|
44
52
|
return `ses_${randomBytes(6).toString('hex')}${randomBase62(14)}`;
|
|
45
53
|
}
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
const hex = randomBytes(Math.ceil(len / 2))
|
|
51
|
-
.toString('hex')
|
|
52
|
-
.slice(0, len);
|
|
53
|
-
return prefix + hex;
|
|
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
|
+
});
|
|
54
58
|
}
|
|
55
59
|
|
|
56
60
|
export function createOpenRouterProvider(config: ProviderConfig): Provider {
|
package/src/provider/registry.ts
CHANGED
|
@@ -95,6 +95,29 @@ const BUILTIN_PROVIDERS: ProviderDef[] = [
|
|
|
95
95
|
defaultModel: 'deepseek/deepseek-chat',
|
|
96
96
|
fallbackModels: ['deepseek/deepseek-chat', 'openai/gpt-4o-mini', 'anthropic/claude-sonnet-4'],
|
|
97
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
|
+
},
|
|
98
121
|
{
|
|
99
122
|
id: 'openai',
|
|
100
123
|
name: 'OpenAI',
|
|
@@ -145,6 +168,9 @@ export const PROVIDERS: ProviderDef[] = [...BUILTIN_PROVIDERS];
|
|
|
145
168
|
|
|
146
169
|
/** Aliases accepted as a provider prefix (e.g. `opencode/model` → zen). */
|
|
147
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
|
+
}
|
|
148
174
|
|
|
149
175
|
let _customLoaded = false;
|
|
150
176
|
|
package/src/registry.ts
CHANGED
|
@@ -46,6 +46,14 @@ export interface CoreRegistry {
|
|
|
46
46
|
extensionHandlers: Record<string, ToolHandlerFn>;
|
|
47
47
|
/** Lifecycle hooks declared by loaded extensions (roadmap #6). */
|
|
48
48
|
lifecycleHooks: LifecycleHandlers[];
|
|
49
|
+
/**
|
|
50
|
+
* System-prompt fragments from loaded, available extensions.
|
|
51
|
+
*
|
|
52
|
+
* Lives here rather than in a module-level variable for the reason in the
|
|
53
|
+
* file header: `composeSystemPrompt()` runs in pal's copy of core, while the
|
|
54
|
+
* extension that contributed the fragment resolved its own copy.
|
|
55
|
+
*/
|
|
56
|
+
extensionPrompts: string[];
|
|
49
57
|
}
|
|
50
58
|
|
|
51
59
|
const KEY = '__pal_core_registry__';
|
|
@@ -61,4 +69,5 @@ export const registry: CoreRegistry = (store[KEY] ??= {
|
|
|
61
69
|
extensionTools: [],
|
|
62
70
|
extensionHandlers: {},
|
|
63
71
|
lifecycleHooks: [],
|
|
72
|
+
extensionPrompts: [],
|
|
64
73
|
});
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Shared, frontend-agnostic app state.
|
|
3
|
+
*
|
|
4
|
+
* The TUI and the WebSocket/desktop frontends each own an instance of this
|
|
5
|
+
* shape. Contract types live here so no frontend has to import another's state
|
|
6
|
+
* module or re-declare the same interfaces.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import type {SessionTokenomics} from '../session/types.js';
|
|
10
|
+
|
|
11
|
+
export interface BackgroundAgent {
|
|
12
|
+
id: string;
|
|
13
|
+
task: string;
|
|
14
|
+
status: 'running' | 'done' | 'error';
|
|
15
|
+
startedAt: number;
|
|
16
|
+
finishedAt?: number;
|
|
17
|
+
result?: string;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export interface TodoItem {
|
|
21
|
+
content: string;
|
|
22
|
+
status: string;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export interface ExtensionStatus {
|
|
26
|
+
/** Extension package name without the scope (e.g. 'web-search'). */
|
|
27
|
+
name: string;
|
|
28
|
+
/** True when the extension loaded and contributed something. */
|
|
29
|
+
active: boolean;
|
|
30
|
+
/**
|
|
31
|
+
* Why the extension is not active, if it is not.
|
|
32
|
+
*
|
|
33
|
+
* - `'inactive'` — loaded fine but reported itself unavailable (no key, no
|
|
34
|
+
* server). Not an error; nothing for the user to fix except configuration.
|
|
35
|
+
* - `'failed'` — the package could not be imported, or its setup threw.
|
|
36
|
+
*
|
|
37
|
+
* Only meaningful when `active` is false.
|
|
38
|
+
*/
|
|
39
|
+
status: 'active' | 'inactive' | 'failed';
|
|
40
|
+
/** Human-readable detail for `status`, when there is one. */
|
|
41
|
+
reason?: string;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export interface McpServerStatus {
|
|
45
|
+
name: string;
|
|
46
|
+
status: 'connected' | 'error' | 'starting';
|
|
47
|
+
toolCount: number;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export interface SharedState {
|
|
51
|
+
/** Title of the current session, shown by the frontend. */
|
|
52
|
+
sessionTitle: string | null;
|
|
53
|
+
/** Latest todo list from the `todos-updated` event. */
|
|
54
|
+
currentTodos: readonly TodoItem[];
|
|
55
|
+
/** Sub-agents spawned by `delegate`. */
|
|
56
|
+
backgroundAgents: BackgroundAgent[];
|
|
57
|
+
/** Loaded extensions and their status. */
|
|
58
|
+
extensions: ExtensionStatus[];
|
|
59
|
+
/** MCP servers discovered during startup. */
|
|
60
|
+
mcpServers: McpServerStatus[];
|
|
61
|
+
/** Currently selected primary agent. */
|
|
62
|
+
currentAgentRole: string;
|
|
63
|
+
/** Session-scoped "always allow" permission entries. Cleared on /new. */
|
|
64
|
+
permissionWhitelist: Array<{tool: string; pattern: string}>;
|
|
65
|
+
/** Accumulated token usage and cost for the current session. */
|
|
66
|
+
sessionTokenomics: SessionTokenomics;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** Fresh state with independent arrays/objects — safe for a new frontend. */
|
|
70
|
+
export function createSharedState(): SharedState {
|
|
71
|
+
return {
|
|
72
|
+
sessionTitle: null,
|
|
73
|
+
currentTodos: [],
|
|
74
|
+
backgroundAgents: [],
|
|
75
|
+
extensions: [],
|
|
76
|
+
mcpServers: [],
|
|
77
|
+
currentAgentRole: 'pal',
|
|
78
|
+
permissionWhitelist: [],
|
|
79
|
+
sessionTokenomics: {inputTokens: 0, outputTokens: 0, cachedTokens: 0, cost: 0},
|
|
80
|
+
};
|
|
81
|
+
}
|
package/src/tools/executor.ts
CHANGED
|
@@ -346,7 +346,12 @@ const tools: Record<
|
|
|
346
346
|
throw new Error(`Cannot write to ${filePath} — matches ignore patterns`);
|
|
347
347
|
}
|
|
348
348
|
|
|
349
|
-
|
|
349
|
+
// A bare relative path (`pal.json`, `.check.cjs`) has dirname `'.'`, and Bun
|
|
350
|
+
// throws `EEXIST` on `mkdir('.')` — the directory obviously already exists.
|
|
351
|
+
// Left unguarded this turns every such write into a failed tool call the
|
|
352
|
+
// model then retries, which reads as a stuck agent rather than a bad path.
|
|
353
|
+
const dir = dirname(filePath);
|
|
354
|
+
if (dir !== '' && dir !== '.') await mkdir(dir, {recursive: true});
|
|
350
355
|
snapshotFile(filePath, 'write');
|
|
351
356
|
await writeFile(filePath, content, 'utf-8');
|
|
352
357
|
return `Wrote ${content.length} bytes to ${filePath}`;
|