pal-code 0.0.17 → 0.0.19

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,298 +0,0 @@
1
- /**
2
- * One agent turn: drive `runWithFallback` and translate its events into
3
- * RunView calls. The reliability policy itself lives in @pal-code/core.
4
- */
5
-
6
- import {
7
- getAllTools,
8
- validateRequiredArgs,
9
- registerExtensionTools,
10
- executeTool,
11
- registerExtensionHandlers,
12
- registerExtensionLifecycle,
13
- loadExtensions,
14
- importExtensionModule,
15
- runWithFallback,
16
- shortModel,
17
- buildRolesPrompt,
18
- buildSkillsPrompt,
19
- clearFileRolesCache,
20
- clearSkillsCache,
21
- listPrimaries,
22
- resolvePrimary,
23
- defaultPrimaryName,
24
- type Provider,
25
- type ProviderKeys,
26
- type ConversationMessage as Message,
27
- type LoadedExtensions,
28
- type ToolResult,
29
- } from '@pal-code/core';
30
- import type {TUI, Container} from '@earendil-works/pi-tui';
31
-
32
- import type {Config} from './config.js';
33
- import {RunView} from './components/run-view.js';
34
- import {state, type McpServerInfo} from './state.js';
35
- import {checkToolPermission} from './utils/permissions.js';
36
-
37
- export interface TurnResult {
38
- inputTokens: number;
39
- outputTokens: number;
40
- cachedTokens: number;
41
- /** The model that actually served this turn (may differ from config.model after a fallback). */
42
- model: string;
43
- /** Checkpoints this turn produced (auto-compaction can fire more than once). */
44
- compactions: Array<{boundary: number; summarized: number; summary: string}>;
45
- }
46
-
47
- let extensionsLoaded = false;
48
-
49
- /** Default extension set when the user hasn't configured one. */
50
- export const DEFAULT_EXTENSIONS = ['@pal-code/web-search', '@pal-code/agents', '@pal-code/mcp'];
51
-
52
- /**
53
- * Apply a successful load to the process: register tools, handlers and
54
- * lifecycle hooks centrally, record status for the sidebar, and adopt the
55
- * configured default primary.
56
- */
57
- async function applyLoaded(requested: string[], result: LoadedExtensions): Promise<void> {
58
- registerExtensionHandlers(result.handlers);
59
- registerExtensionTools(result.tools);
60
- registerExtensionLifecycle(result.lifecycle);
61
-
62
- const active = new Set(result.loaded);
63
- const failedByPkg = new Map(result.failed.map((f) => [f.pkg, f.reason]));
64
- state.extensions = requested.map((pkg) => ({
65
- name: pkg.replace(/^@pal-code\//, ''),
66
- active: active.has(pkg),
67
- reason: failedByPkg.get(pkg),
68
- }));
69
-
70
- // Populate MCP server status for the sidebar (live from manager).
71
- //
72
- // Resolved through core rather than a bare import: `pal add` installs the
73
- // extension under ~/.pal/extensions/node_modules, which a plain
74
- // `import('@pal-code/mcp')` from here would not search. `importExtensionModule`
75
- // also handles the compiled binary, where that bare import cannot resolve at
76
- // all — treating that as "not installed" would leave the server list empty.
77
- try {
78
- const mcpMod = (await importExtensionModule('@pal-code/mcp')) as {
79
- mcpManager?: {getServerDetails(): McpServerInfo[]};
80
- };
81
- if (mcpMod?.mcpManager) {
82
- state.mcpServers = mcpMod.mcpManager.getServerDetails();
83
- state.refreshSidebar();
84
- }
85
- } catch {
86
- // MCP extension not available — skip silently
87
- }
88
-
89
- // Primaries are registered by the extension's setup hook during load.
90
- // Adopt the configured default unless the user already picked one.
91
- const primaries = listPrimaries();
92
- if (primaries.length > 0 && !primaries.some((p) => p.name === state.currentAgentRole)) {
93
- state.currentAgentRole = defaultPrimaryName();
94
- }
95
-
96
- state.refreshStatusLine();
97
- state.refreshRoleIndicator();
98
- }
99
-
100
- export async function ensureExtensionsLoaded(extensions?: string[]): Promise<void> {
101
- if (extensionsLoaded) return;
102
-
103
- const requested = extensions ?? DEFAULT_EXTENSIONS;
104
- const result = await loadExtensions(requested);
105
- extensionsLoaded = true;
106
- await applyLoaded(requested, result);
107
- }
108
-
109
- /**
110
- * Re-import extensions without restarting pal. Called by `/reload`.
111
- *
112
- * Uses the loader's `cacheBust` option so edited extension source is picked up.
113
- * `@pal-code/core` is not re-imported, so a re-registered role provider lands in the
114
- * one registry core already holds.
115
- */
116
- export async function reloadExtensions(extensions?: string[]): Promise<number> {
117
- const requested = extensions ?? DEFAULT_EXTENSIONS;
118
- const result = await loadExtensions(requested, {
119
- cacheBust: true,
120
- });
121
- extensionsLoaded = true;
122
- clearFileRolesCache();
123
- clearSkillsCache();
124
- await applyLoaded(requested, result);
125
- return result.tools.length;
126
- }
127
-
128
- /**
129
- * Compose the system prompt for a turn: the base prompt, an optional primary
130
- * agent preamble, the role-awareness block, and the skill listing (only when
131
- * skill files exist). Every piece is skipped when absent, so users with no
132
- * extensions or skills pay nothing in tokens.
133
- */
134
- function composeSystemPrompt(base: string, primaryName?: string): string {
135
- const parts: string[] = [];
136
- const primary = primaryName ? resolvePrimary(primaryName) : null;
137
- if (primary?.systemPrompt) parts.push(primary.systemPrompt);
138
- parts.push(base);
139
- const roles = buildRolesPrompt();
140
- if (roles) parts.push(roles);
141
- const skills = buildSkillsPrompt();
142
- if (skills) parts.push(skills);
143
- return parts.join('\n\n');
144
- }
145
-
146
- /** Tools the turn may use, narrowed to the primary agent's set when it declares one. */
147
- function toolsForPrimary(primaryName?: string): import('@pal-code/core').ToolDef[] {
148
- const all = getAllTools();
149
- const primary = primaryName ? resolvePrimary(primaryName) : null;
150
- if (!primary?.tools) return all;
151
- const allowed = new Set(primary.tools);
152
- return all.filter((t) => allowed.has(t.function.name));
153
- }
154
-
155
- /**
156
- * Whether the active primary is a read-only agent.
157
- *
158
- * A primary that declares a `tools` list is deliberately narrowed (that is how
159
- * plan mode is enforced); one without is unrestricted. Propagating this stops a
160
- * read-only turn from reaching a writer through `delegate`.
161
- */
162
- export function isReadOnlyPrimary(primaryName?: string): boolean {
163
- const primary = primaryName ? resolvePrimary(primaryName) : null;
164
- return Array.isArray(primary?.tools);
165
- }
166
-
167
- /**
168
- * The tool names the turn is permitted to dispatch, or `undefined` when the
169
- * primary is unrestricted.
170
- *
171
- * Returned to core so `executeTool` can enforce it. Filtering the definitions
172
- * handed to the model is not sufficient on its own — a model can emit a call for
173
- * a tool it was never offered.
174
- */
175
- export function allowedToolsForPrimary(primaryName?: string): string[] | undefined {
176
- return resolvePrimary(primaryName ?? '')?.tools;
177
- }
178
-
179
- /**
180
- * Permission-gated wrapper around core's `executeTool`. Checks rules before
181
- * dispatching — if a tool call needs approval, the overlay pauses the turn
182
- * until the user responds.
183
- */
184
- async function gatedExecuteTool(
185
- name: string,
186
- argsStr: string,
187
- toolCallId: string,
188
- providerConfigOverride?: {
189
- model: string;
190
- apiKey: string;
191
- baseUrl: string;
192
- keys?: Record<string, string>;
193
- headers?: Record<string, string>;
194
- systemPromptAppend?: string;
195
- readOnly?: boolean;
196
- allowedTools?: string[];
197
- },
198
- signal?: AbortSignal,
199
- ): Promise<ToolResult> {
200
- // Parse args for permission check
201
- let args: Record<string, unknown> = {};
202
- try {
203
- args = argsStr && argsStr.trim() ? JSON.parse(argsStr) : {};
204
- } catch {
205
- // If args can't be parsed, let executeTool handle the error
206
- }
207
-
208
- // Reject schema-incomplete calls before the permission gate, so a call
209
- // missing required arguments can't trigger an approval prompt and then fail.
210
- const validationError = validateRequiredArgs(name, args);
211
- if (validationError) {
212
- return {toolCallId, content: validationError, error: true};
213
- }
214
-
215
- const decision = await checkToolPermission(name, args);
216
-
217
- if (!decision.allowed) {
218
- return {
219
- toolCallId,
220
- content: `Error: ${decision.reason}`,
221
- error: true,
222
- };
223
- }
224
-
225
- return executeTool(name, argsStr, toolCallId, providerConfigOverride, signal);
226
- }
227
-
228
- export async function agentLoop(
229
- userMessage: string,
230
- messages: Message[],
231
- config: Config,
232
- tui: TUI,
233
- messagesContainer: Container,
234
- allKeys: ProviderKeys,
235
- createProvider: (model: string) => Provider,
236
- primaryName?: string,
237
- compactedSeq = 0,
238
- compactionNote = '',
239
- ): Promise<TurnResult> {
240
- await ensureExtensionsLoaded(config.extensions);
241
-
242
- messages.push({role: 'user', content: userMessage});
243
-
244
- const run = new RunView(messagesContainer, tui, shortModel(config.model));
245
- state.activeRun = run;
246
-
247
- let usage = {inputTokens: 0, outputTokens: 0, cachedTokens: 0};
248
- let activeModel = config.model;
249
- const compactions: TurnResult['compactions'] = [];
250
-
251
- for await (const ev of runWithFallback({
252
- messages,
253
- tools: toolsForPrimary(primaryName),
254
- model: config.model,
255
- systemPrompt: composeSystemPrompt(config.systemPrompt, primaryName),
256
- maxToolRounds: config.maxToolRounds,
257
- contextLimit: config.contextLimit,
258
- reasoningEffort: config.reasoningEffort,
259
- compactedSeq,
260
- compactionNote,
261
- maxRetries: config.maxRetries,
262
- retryBaseMs: config.retryBaseMs,
263
- keys: allKeys,
264
- executeTool: gatedExecuteTool,
265
- childExecuteTool: gatedExecuteTool,
266
- signal: state.activeAbort?.signal,
267
- primary: primaryName,
268
- readOnly: isReadOnlyPrimary(primaryName),
269
- allowedTools: allowedToolsForPrimary(primaryName),
270
- createProvider: (spec: string) => createProvider(spec),
271
- })) {
272
- if (ev.type === 'model-start') {
273
- activeModel = ev.model;
274
- run.setModel(shortModel(ev.model));
275
- } else if (ev.type === 'round-start') run.beginRound(ev.round, ev.max);
276
- else if (ev.type === 'text-delta') run.streamText(ev.content);
277
- else if (ev.type === 'thinking-delta') run.streamThinking(ev.content);
278
- else if (ev.type === 'tool-start') run.addTool(ev.id, ev.name, ev.argsSummary);
279
- else if (ev.type === 'tool-end') run.endTool(ev.id, ev.ok, ev.content);
280
- else if (ev.type === 'notice') {
281
- // The compaction notice is superseded by the green transcript line the
282
- // caller prints after the turn — this dim inline copy vanished with the
283
- // run block's collapse, which is why auto-compaction looked silent.
284
- if (!ev.text.startsWith('Context compacted')) run.notice(ev.text);
285
- } else if (ev.type === 'compacted') {
286
- compactions.push({boundary: ev.boundary, summarized: ev.summarized, summary: ev.summary});
287
- } else if (ev.type === 'aborted') run.aborted();
288
- else if (ev.type === 'done') usage = ev.usage;
289
- }
290
-
291
- return {
292
- inputTokens: usage.inputTokens,
293
- outputTokens: usage.outputTokens,
294
- cachedTokens: usage.cachedTokens,
295
- model: activeModel,
296
- compactions,
297
- };
298
- }