pal-code 0.0.5
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/LICENSE +21 -0
- package/README.md +169 -0
- package/SYSTEM.md +146 -0
- package/bin/pal-code.js +131 -0
- package/package.json +68 -0
- package/packages/cli/README.md +77 -0
- package/packages/cli/src/agent-panel.ts +94 -0
- package/packages/cli/src/commands/ext.ts +79 -0
- package/packages/cli/src/commands/mcp-registry.ts +136 -0
- package/packages/cli/src/commands/mcp.ts +186 -0
- package/packages/cli/src/commands.ts +153 -0
- package/packages/cli/src/components/message-box.ts +35 -0
- package/packages/cli/src/components/permission-prompt.ts +185 -0
- package/packages/cli/src/components/render-history.ts +143 -0
- package/packages/cli/src/components/run-view.ts +256 -0
- package/packages/cli/src/components/sidebar.ts +120 -0
- package/packages/cli/src/components/status-line.ts +26 -0
- package/packages/cli/src/config.ts +107 -0
- package/packages/cli/src/index.ts +1606 -0
- package/packages/cli/src/overlays/key-input.ts +167 -0
- package/packages/cli/src/overlays/model-picker.ts +106 -0
- package/packages/cli/src/overlays/session-picker.ts +168 -0
- package/packages/cli/src/overlays/wizard.ts +145 -0
- package/packages/cli/src/state.ts +133 -0
- package/packages/cli/src/theme.ts +88 -0
- package/packages/cli/src/turn.ts +266 -0
- package/packages/cli/src/utils/cost.ts +111 -0
- package/packages/cli/src/utils/format.test.ts +167 -0
- package/packages/cli/src/utils/format.ts +248 -0
- package/packages/cli/src/utils/highlight.ts +358 -0
- package/packages/cli/src/utils/permissions.ts +196 -0
- package/packages/core/src/agent/events.ts +36 -0
- package/packages/core/src/agent/fallback.test.ts +99 -0
- package/packages/core/src/agent/fallback.ts +344 -0
- package/packages/core/src/agent/index.ts +35 -0
- package/packages/core/src/agent/protocol.test.ts +136 -0
- package/packages/core/src/agent/resume-compaction.test.ts +116 -0
- package/packages/core/src/agent/roles.ts +188 -0
- package/packages/core/src/agent/run.test.ts +207 -0
- package/packages/core/src/agent/run.ts +713 -0
- package/packages/core/src/agent/scope.ts +34 -0
- package/packages/core/src/agent/todos.ts +66 -0
- package/packages/core/src/compaction.protocol.test.ts +90 -0
- package/packages/core/src/compaction.test.ts +101 -0
- package/packages/core/src/compaction.ts +243 -0
- package/packages/core/src/config.test.ts +40 -0
- package/packages/core/src/config.ts +387 -0
- package/packages/core/src/extensions.ts +178 -0
- package/packages/core/src/index.ts +157 -0
- package/packages/core/src/logger.ts +54 -0
- package/packages/core/src/provider/auth.ts +153 -0
- package/packages/core/src/provider/complete.ts +63 -0
- package/packages/core/src/provider/index.ts +6 -0
- package/packages/core/src/provider/openrouter.test.ts +59 -0
- package/packages/core/src/provider/openrouter.ts +304 -0
- package/packages/core/src/provider/pick-model.ts +43 -0
- package/packages/core/src/provider/registry.ts +222 -0
- package/packages/core/src/provider/types.ts +61 -0
- package/packages/core/src/repo-map.ts +177 -0
- package/packages/core/src/session/index.ts +2 -0
- package/packages/core/src/session/migration.test.ts +104 -0
- package/packages/core/src/session/store-v2-repair.test.ts +209 -0
- package/packages/core/src/session/store.test.ts +235 -0
- package/packages/core/src/session/store.ts +677 -0
- package/packages/core/src/session/types.ts +72 -0
- package/packages/core/src/snapshots.ts +107 -0
- package/packages/core/src/tools/definitions.ts +365 -0
- package/packages/core/src/tools/executor.test.ts +122 -0
- package/packages/core/src/tools/executor.ts +1363 -0
- package/packages/core/src/tools/index.ts +5 -0
- package/packages/core/src/tools/search.ts +201 -0
- package/scripts/postinstall.js +121 -0
- package/scripts/preinstall.js +51 -0
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Session-scoped mutable UI state.
|
|
3
|
+
*
|
|
4
|
+
* This is the CLI's single "app state" object. It exists so the pickers, the
|
|
5
|
+
* agents panel, and `main()` can share a few mutable references without every
|
|
6
|
+
* one of them living in the same file — the previous arrangement had these
|
|
7
|
+
* scattered as module-level `let`s in `index.ts`, which made the extraction of
|
|
8
|
+
* any one overlay impossible.
|
|
9
|
+
*
|
|
10
|
+
* Deliberately a plain object rather than exported `let` bindings: importers
|
|
11
|
+
* mutate `state.x` directly, and reads always see the current value (a plain
|
|
12
|
+
* object export is a live reference; a `let` export would be a snapshot at the
|
|
13
|
+
* import site).
|
|
14
|
+
*
|
|
15
|
+
* Only *presentation* state lives here. Anything that decides what the agent
|
|
16
|
+
* does belongs in `@pal/core` (see SYSTEM.md).
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
import type {RunView} from './components/run-view.js';
|
|
20
|
+
import type {PermissionPrompt} from './components/permission-prompt.js';
|
|
21
|
+
|
|
22
|
+
export type OverlayMode = 'none' | 'model-select' | 'key-input' | 'agents' | 'permission';
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* Name of the active **primary agent** (the one the user talks to, cycled with
|
|
26
|
+
* Tab). Populated from the orchestration extension at load time; defaults to
|
|
27
|
+
* 'pal' (the orchestrator) when no extension provides primaries.
|
|
28
|
+
*
|
|
29
|
+
* Not to be confused with a delegation role — see `@pal/core`'s `PrimarySpec`.
|
|
30
|
+
*/
|
|
31
|
+
export type AgentRole = string;
|
|
32
|
+
|
|
33
|
+
export interface BackgroundAgent {
|
|
34
|
+
id: string;
|
|
35
|
+
task: string;
|
|
36
|
+
status: 'running' | 'done' | 'error';
|
|
37
|
+
startedAt: number;
|
|
38
|
+
finishedAt?: number;
|
|
39
|
+
result?: string;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export interface TodoItem {
|
|
43
|
+
content: string;
|
|
44
|
+
status: string;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export interface ExtensionInfo {
|
|
48
|
+
/** Extension package name (e.g. '@pal/web-search'). */
|
|
49
|
+
name: string;
|
|
50
|
+
/** Whether the extension loaded successfully and its tools are available. */
|
|
51
|
+
active: boolean;
|
|
52
|
+
/** Why loading failed, when `active` is false. */
|
|
53
|
+
reason?: string;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export interface McpServerInfo {
|
|
57
|
+
name: string;
|
|
58
|
+
status: 'connected' | 'error' | 'starting';
|
|
59
|
+
toolCount: number;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export interface AppState {
|
|
63
|
+
/** Which overlay (if any) currently owns the editor area. */
|
|
64
|
+
overlayMode: OverlayMode;
|
|
65
|
+
/** Bound by `main()`; re-renders the status line. */
|
|
66
|
+
refreshStatusLine: () => void;
|
|
67
|
+
/** Bound by `main()`; re-renders the sidebar. */
|
|
68
|
+
refreshSidebar: () => void;
|
|
69
|
+
/** Bound by `main()`; re-reads keys and rebuilds the provider after `/key`. */
|
|
70
|
+
reloadKeys: (() => void) | null;
|
|
71
|
+
/** Title of the current session, shown at the top of the sidebar. */
|
|
72
|
+
sessionTitle: string | null;
|
|
73
|
+
/** Latest todo list from the `todos-updated` event. */
|
|
74
|
+
currentTodos: readonly TodoItem[];
|
|
75
|
+
/** Sub-agents spawned by `delegate`, shown in the ctrl+b panel. */
|
|
76
|
+
backgroundAgents: BackgroundAgent[];
|
|
77
|
+
/** The run block for the in-flight turn. */
|
|
78
|
+
activeRun: RunView | null;
|
|
79
|
+
/** Cancels the in-flight turn (Esc). */
|
|
80
|
+
activeAbort: AbortController | null;
|
|
81
|
+
/** The most recently collapsed run, for ctrl+o. */
|
|
82
|
+
lastRun: RunView | null;
|
|
83
|
+
/** Loaded extensions and their status. */
|
|
84
|
+
extensions: ExtensionInfo[];
|
|
85
|
+
/** MCP servers discovered during startup. */
|
|
86
|
+
mcpServers: McpServerInfo[];
|
|
87
|
+
/** Currently selected primary agent (see AgentRole). */
|
|
88
|
+
currentAgentRole: AgentRole;
|
|
89
|
+
/** Bound by `main()`; re-renders the input role indicator after extensions load. */
|
|
90
|
+
refreshRoleIndicator: () => void;
|
|
91
|
+
/** Bound by `main()`; shows the centered permission modal overlay. */
|
|
92
|
+
showPermissionModal: () => void;
|
|
93
|
+
|
|
94
|
+
// ── Permission system ──
|
|
95
|
+
/** Session-scoped "always allow" entries. Cleared on /new. */
|
|
96
|
+
permissionWhitelist: Array<{tool: string; pattern: string}>;
|
|
97
|
+
/** Resolves an async permission prompt (set by main()). Returns 'allow' | 'deny'. */
|
|
98
|
+
permissionResolver: ((allow: boolean) => void) | null;
|
|
99
|
+
/** Context for the current permission overlay (shown in the prompt). */
|
|
100
|
+
pendingPermission: {toolName: string; target: string; summary: string} | null;
|
|
101
|
+
/** The singleton permission prompt component (instantiated by main()). */
|
|
102
|
+
permissionPrompt: PermissionPrompt | null;
|
|
103
|
+
/** Queued permission requests when multiple tool calls need approval at once. */
|
|
104
|
+
permissionQueue: Array<{
|
|
105
|
+
resolver: (allow: boolean) => void;
|
|
106
|
+
toolName: string;
|
|
107
|
+
target: string;
|
|
108
|
+
summary: string;
|
|
109
|
+
}>;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
export const state: AppState = {
|
|
113
|
+
overlayMode: 'none',
|
|
114
|
+
refreshStatusLine: () => {},
|
|
115
|
+
refreshSidebar: () => {},
|
|
116
|
+
reloadKeys: null,
|
|
117
|
+
sessionTitle: null,
|
|
118
|
+
currentTodos: [],
|
|
119
|
+
backgroundAgents: [],
|
|
120
|
+
activeRun: null,
|
|
121
|
+
activeAbort: null,
|
|
122
|
+
lastRun: null,
|
|
123
|
+
extensions: [],
|
|
124
|
+
mcpServers: [],
|
|
125
|
+
currentAgentRole: 'pal',
|
|
126
|
+
refreshRoleIndicator: () => {},
|
|
127
|
+
showPermissionModal: () => {},
|
|
128
|
+
permissionWhitelist: [],
|
|
129
|
+
permissionResolver: null,
|
|
130
|
+
pendingPermission: null,
|
|
131
|
+
permissionPrompt: null,
|
|
132
|
+
permissionQueue: [],
|
|
133
|
+
};
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Colours (raw ANSI — no chalk dependency) and the two pi-tui themes.
|
|
3
|
+
*
|
|
4
|
+
* Pure: no state, no I/O. Every renderer in the CLI pulls from here so the
|
|
5
|
+
* palette stays consistent.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import type {EditorTheme} from '@earendil-works/pi-tui';
|
|
9
|
+
import {highlightCode} from './utils/highlight.js';
|
|
10
|
+
|
|
11
|
+
export const c = {
|
|
12
|
+
reset: '\x1b[0m',
|
|
13
|
+
bold: '\x1b[1m',
|
|
14
|
+
dim: '\x1b[2m',
|
|
15
|
+
italic: '\x1b[3m',
|
|
16
|
+
underline: '\x1b[4m',
|
|
17
|
+
blue: '\x1b[34m',
|
|
18
|
+
green: '\x1b[32m',
|
|
19
|
+
cyan: '\x1b[36m',
|
|
20
|
+
yellow: '\x1b[33m',
|
|
21
|
+
red: '\x1b[31m',
|
|
22
|
+
magenta: '\x1b[35m',
|
|
23
|
+
bright_red: '\x1b[91m',
|
|
24
|
+
bright_green: '\x1b[92m',
|
|
25
|
+
bright_yellow: '\x1b[93m',
|
|
26
|
+
bright_cyan: '\x1b[96m',
|
|
27
|
+
bright_black: '\x1b[90m',
|
|
28
|
+
bright_white: '\x1b[97m',
|
|
29
|
+
};
|
|
30
|
+
|
|
31
|
+
export const markdownTheme = {
|
|
32
|
+
heading: (text: string) => `${c.bold}${c.bright_cyan}${text}${c.reset}`,
|
|
33
|
+
link: (text: string) => `${c.underline}${c.cyan}${text}${c.reset}`,
|
|
34
|
+
linkUrl: (text: string) => `${c.dim}${text}${c.reset}`,
|
|
35
|
+
code: (text: string) => `${c.bold}${c.magenta}${text}${c.reset}`,
|
|
36
|
+
codeBlock: (text: string) => `${c.bright_black}${text}${c.reset}`,
|
|
37
|
+
codeBlockBorder: (text: string) => `${c.dim}${c.bright_black}${text}${c.reset}`,
|
|
38
|
+
quote: (text: string) => `${c.italic}${c.dim}${text}${c.reset}`,
|
|
39
|
+
quoteBorder: (text: string) => `${c.bold}${c.cyan}${text}${c.reset}`,
|
|
40
|
+
hr: (text: string) => `${c.dim}${text}${c.reset}`,
|
|
41
|
+
listBullet: (text: string) => `${c.bold}${c.green}${text}${c.reset}`,
|
|
42
|
+
bold: (text: string) => `${c.bold}${c.bright_white}${text}${c.reset}`,
|
|
43
|
+
italic: (text: string) => `${c.italic}${c.dim}${text}${c.reset}`,
|
|
44
|
+
strikethrough: (text: string) => `${c.dim}${text}${c.reset}`,
|
|
45
|
+
underline: (text: string) => `${c.underline}${text}${c.reset}`,
|
|
46
|
+
highlightCode,
|
|
47
|
+
};
|
|
48
|
+
|
|
49
|
+
/** Fallback display colours for roles that don't declare one. */
|
|
50
|
+
export const agentColors: Record<string, string> = {
|
|
51
|
+
pal: c.cyan,
|
|
52
|
+
plan: c.red,
|
|
53
|
+
planner: c.red,
|
|
54
|
+
explore: c.green,
|
|
55
|
+
build: c.blue,
|
|
56
|
+
review: c.magenta,
|
|
57
|
+
librarian: c.yellow,
|
|
58
|
+
architect: c.bright_cyan,
|
|
59
|
+
};
|
|
60
|
+
|
|
61
|
+
/** Fallback display labels for roles that don't declare one. */
|
|
62
|
+
export const agentLabels: Record<string, string> = {
|
|
63
|
+
pal: 'pal',
|
|
64
|
+
plan: 'plan',
|
|
65
|
+
planner: 'planner',
|
|
66
|
+
explore: 'explore',
|
|
67
|
+
build: 'builder',
|
|
68
|
+
review: 'reviewer',
|
|
69
|
+
librarian: 'librarian',
|
|
70
|
+
architect: 'architect',
|
|
71
|
+
};
|
|
72
|
+
|
|
73
|
+
/** Resolve a theme colour by its key name (e.g. 'cyan'), or the default. */
|
|
74
|
+
export function colorByName(name: string | undefined, fallback = c.cyan): string {
|
|
75
|
+
if (!name) return fallback;
|
|
76
|
+
return (c as Record<string, string>)[name] ?? fallback;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
export const editorTheme: EditorTheme = {
|
|
80
|
+
borderColor: (s) => `${c.dim}${s}${c.reset}`,
|
|
81
|
+
selectList: {
|
|
82
|
+
selectedPrefix: (s) => `${c.bold}${c.green}${s}${c.reset}`,
|
|
83
|
+
selectedText: (s) => `${c.bold}${s}${c.reset}`,
|
|
84
|
+
description: (s) => `${c.dim}${s}${c.reset}`,
|
|
85
|
+
scrollInfo: (s) => `${c.dim}${s}${c.reset}`,
|
|
86
|
+
noMatch: (s) => `${c.dim}${s}${c.reset}`,
|
|
87
|
+
},
|
|
88
|
+
};
|
|
@@ -0,0 +1,266 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* One agent turn: drive `runWithFallback` and translate its events into
|
|
3
|
+
* RunView calls. The reliability policy itself lives in @pal/core.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import {
|
|
7
|
+
getAllTools,
|
|
8
|
+
registerExtensionTools,
|
|
9
|
+
executeTool,
|
|
10
|
+
registerExtensionHandlers,
|
|
11
|
+
loadExtensions,
|
|
12
|
+
runWithFallback,
|
|
13
|
+
shortModel,
|
|
14
|
+
buildRolesPrompt,
|
|
15
|
+
listPrimaries,
|
|
16
|
+
resolvePrimary,
|
|
17
|
+
defaultPrimaryName,
|
|
18
|
+
type Provider,
|
|
19
|
+
type ProviderKeys,
|
|
20
|
+
type ConversationMessage as Message,
|
|
21
|
+
type ToolResult,
|
|
22
|
+
} from '@pal/core';
|
|
23
|
+
import type {TUI, Container} from '@earendil-works/pi-tui';
|
|
24
|
+
|
|
25
|
+
import type {Config} from './config.js';
|
|
26
|
+
import {RunView} from './components/run-view.js';
|
|
27
|
+
import {state} from './state.js';
|
|
28
|
+
import {checkToolPermission} from './utils/permissions.js';
|
|
29
|
+
|
|
30
|
+
export interface TurnResult {
|
|
31
|
+
inputTokens: number;
|
|
32
|
+
outputTokens: number;
|
|
33
|
+
cachedTokens: number;
|
|
34
|
+
/** The model that actually served this turn (may differ from config.model after a fallback). */
|
|
35
|
+
model: string;
|
|
36
|
+
/** Set when this turn compacted older history into a checkpoint. */
|
|
37
|
+
compaction?: {boundary: number; summary: string};
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
let extensionsLoaded = false;
|
|
41
|
+
|
|
42
|
+
/** Default extension set when the user hasn't configured one. */
|
|
43
|
+
export const DEFAULT_EXTENSIONS = ['@pal/web-search', '@pal/agents', '@pal/mcp'];
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Apply a successful load to the process: register tools + handlers centrally,
|
|
47
|
+
* record status for the sidebar, and adopt the configured default primary.
|
|
48
|
+
*/
|
|
49
|
+
async function applyLoaded(
|
|
50
|
+
requested: string[],
|
|
51
|
+
loaded: string[],
|
|
52
|
+
failed: Array<{pkg: string; reason: string}>,
|
|
53
|
+
tools: import('@pal/core').ToolDef[],
|
|
54
|
+
handlers: Record<string, import('@pal/core').ToolHandler>,
|
|
55
|
+
): Promise<void> {
|
|
56
|
+
registerExtensionHandlers(handlers);
|
|
57
|
+
registerExtensionTools(tools);
|
|
58
|
+
|
|
59
|
+
const active = new Set(loaded);
|
|
60
|
+
const failedByPkg = new Map(failed.map((f) => [f.pkg, f.reason]));
|
|
61
|
+
state.extensions = requested.map((pkg) => ({
|
|
62
|
+
name: pkg.replace(/^@pal\//, ''),
|
|
63
|
+
active: active.has(pkg),
|
|
64
|
+
reason: failedByPkg.get(pkg),
|
|
65
|
+
}));
|
|
66
|
+
|
|
67
|
+
// Populate MCP server status for the sidebar (live from manager)
|
|
68
|
+
try {
|
|
69
|
+
const mcpMod = await import('@pal/mcp').catch(() => null);
|
|
70
|
+
if (mcpMod?.mcpManager) {
|
|
71
|
+
state.mcpServers = mcpMod.mcpManager.getServerDetails();
|
|
72
|
+
state.refreshSidebar();
|
|
73
|
+
}
|
|
74
|
+
} catch {
|
|
75
|
+
// MCP extension not available — skip silently
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
// Primaries are registered by the extension's setup hook during load.
|
|
79
|
+
// Adopt the configured default unless the user already picked one.
|
|
80
|
+
const primaries = listPrimaries();
|
|
81
|
+
if (primaries.length > 0 && !primaries.some((p) => p.name === state.currentAgentRole)) {
|
|
82
|
+
state.currentAgentRole = defaultPrimaryName();
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
state.refreshStatusLine();
|
|
86
|
+
state.refreshRoleIndicator();
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
export async function ensureExtensionsLoaded(extensions?: string[]): Promise<void> {
|
|
90
|
+
if (extensionsLoaded) return;
|
|
91
|
+
|
|
92
|
+
const requested = extensions ?? DEFAULT_EXTENSIONS;
|
|
93
|
+
const {tools, handlers, loaded, failed} = await loadExtensions(requested);
|
|
94
|
+
extensionsLoaded = true;
|
|
95
|
+
await applyLoaded(requested, loaded, failed, tools, handlers);
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* Re-import extensions without restarting pal. Called by `/reload`.
|
|
100
|
+
*
|
|
101
|
+
* Uses the loader's `cacheBust` option so edited extension source is picked up.
|
|
102
|
+
* `@pal/core` is not re-imported, so a re-registered role provider lands in the
|
|
103
|
+
* one registry core already holds.
|
|
104
|
+
*/
|
|
105
|
+
export async function reloadExtensions(extensions?: string[]): Promise<number> {
|
|
106
|
+
const requested = extensions ?? DEFAULT_EXTENSIONS;
|
|
107
|
+
const {tools, handlers, loaded, failed} = await loadExtensions(requested, {
|
|
108
|
+
cacheBust: true,
|
|
109
|
+
});
|
|
110
|
+
extensionsLoaded = true;
|
|
111
|
+
await applyLoaded(requested, loaded, failed, tools, handlers);
|
|
112
|
+
return tools.length;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/**
|
|
116
|
+
* Compose the system prompt for a turn: the base prompt, an optional primary
|
|
117
|
+
* agent preamble, and the role-awareness block (only when an orchestration
|
|
118
|
+
* extension registered roles). Every piece is skipped when absent, so users
|
|
119
|
+
* with no extensions pay nothing in tokens.
|
|
120
|
+
*/
|
|
121
|
+
function composeSystemPrompt(base: string, primaryName?: string): string {
|
|
122
|
+
const parts: string[] = [];
|
|
123
|
+
const primary = primaryName ? resolvePrimary(primaryName) : null;
|
|
124
|
+
if (primary?.systemPrompt) parts.push(primary.systemPrompt);
|
|
125
|
+
parts.push(base);
|
|
126
|
+
const roles = buildRolesPrompt();
|
|
127
|
+
if (roles) parts.push(roles);
|
|
128
|
+
return parts.join('\n\n');
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/** Tools the turn may use, narrowed to the primary agent's set when it declares one. */
|
|
132
|
+
function toolsForPrimary(primaryName?: string): import('@pal/core').ToolDef[] {
|
|
133
|
+
const all = getAllTools();
|
|
134
|
+
const primary = primaryName ? resolvePrimary(primaryName) : null;
|
|
135
|
+
if (!primary?.tools) return all;
|
|
136
|
+
const allowed = new Set(primary.tools);
|
|
137
|
+
return all.filter((t) => allowed.has(t.function.name));
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/**
|
|
141
|
+
* Whether the active primary is a read-only agent.
|
|
142
|
+
*
|
|
143
|
+
* A primary that declares a `tools` list is deliberately narrowed (that is how
|
|
144
|
+
* plan mode is enforced); one without is unrestricted. Propagating this stops a
|
|
145
|
+
* read-only turn from reaching a writer through `delegate`.
|
|
146
|
+
*/
|
|
147
|
+
export function isReadOnlyPrimary(primaryName?: string): boolean {
|
|
148
|
+
const primary = primaryName ? resolvePrimary(primaryName) : null;
|
|
149
|
+
return Array.isArray(primary?.tools);
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/**
|
|
153
|
+
* The tool names the turn is permitted to dispatch, or `undefined` when the
|
|
154
|
+
* primary is unrestricted.
|
|
155
|
+
*
|
|
156
|
+
* Returned to core so `executeTool` can enforce it. Filtering the definitions
|
|
157
|
+
* handed to the model is not sufficient on its own — a model can emit a call for
|
|
158
|
+
* a tool it was never offered.
|
|
159
|
+
*/
|
|
160
|
+
export function allowedToolsForPrimary(primaryName?: string): string[] | undefined {
|
|
161
|
+
return resolvePrimary(primaryName ?? '')?.tools;
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/**
|
|
165
|
+
* Permission-gated wrapper around core's `executeTool`. Checks rules before
|
|
166
|
+
* dispatching — if a tool call needs approval, the overlay pauses the turn
|
|
167
|
+
* until the user responds.
|
|
168
|
+
*/
|
|
169
|
+
async function gatedExecuteTool(
|
|
170
|
+
name: string,
|
|
171
|
+
argsStr: string,
|
|
172
|
+
toolCallId: string,
|
|
173
|
+
providerConfigOverride?: {
|
|
174
|
+
model: string;
|
|
175
|
+
apiKey: string;
|
|
176
|
+
baseUrl: string;
|
|
177
|
+
keys?: Record<string, string>;
|
|
178
|
+
readOnly?: boolean;
|
|
179
|
+
allowedTools?: string[];
|
|
180
|
+
},
|
|
181
|
+
): Promise<ToolResult> {
|
|
182
|
+
// Parse args for permission check
|
|
183
|
+
let args: Record<string, unknown> = {};
|
|
184
|
+
try {
|
|
185
|
+
args = argsStr && argsStr.trim() ? JSON.parse(argsStr) : {};
|
|
186
|
+
} catch {
|
|
187
|
+
// If args can't be parsed, let executeTool handle the error
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
const decision = await checkToolPermission(name, args);
|
|
191
|
+
|
|
192
|
+
if (!decision.allowed) {
|
|
193
|
+
return {
|
|
194
|
+
toolCallId,
|
|
195
|
+
content: `Error: ${decision.reason}`,
|
|
196
|
+
error: true,
|
|
197
|
+
};
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
return executeTool(name, argsStr, toolCallId, providerConfigOverride);
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
export async function agentLoop(
|
|
204
|
+
userMessage: string,
|
|
205
|
+
messages: Message[],
|
|
206
|
+
config: Config,
|
|
207
|
+
tui: TUI,
|
|
208
|
+
messagesContainer: Container,
|
|
209
|
+
allKeys: ProviderKeys,
|
|
210
|
+
createProvider: (model: string) => Provider,
|
|
211
|
+
primaryName?: string,
|
|
212
|
+
compactedSeq = 0,
|
|
213
|
+
compactionNote = '',
|
|
214
|
+
): Promise<TurnResult> {
|
|
215
|
+
await ensureExtensionsLoaded(config.extensions);
|
|
216
|
+
|
|
217
|
+
messages.push({role: 'user', content: userMessage});
|
|
218
|
+
|
|
219
|
+
const run = new RunView(messagesContainer, tui, shortModel(config.model));
|
|
220
|
+
state.activeRun = run;
|
|
221
|
+
|
|
222
|
+
let usage = {inputTokens: 0, outputTokens: 0, cachedTokens: 0};
|
|
223
|
+
let activeModel = config.model;
|
|
224
|
+
let compaction: {boundary: number; summary: string} | undefined;
|
|
225
|
+
|
|
226
|
+
for await (const ev of runWithFallback({
|
|
227
|
+
messages,
|
|
228
|
+
tools: toolsForPrimary(primaryName),
|
|
229
|
+
model: config.model,
|
|
230
|
+
systemPrompt: composeSystemPrompt(config.systemPrompt, primaryName),
|
|
231
|
+
maxToolRounds: config.maxToolRounds,
|
|
232
|
+
contextLimit: config.contextLimit,
|
|
233
|
+
reasoningEffort: config.reasoningEffort,
|
|
234
|
+
compactedSeq,
|
|
235
|
+
compactionNote,
|
|
236
|
+
maxRetries: config.maxRetries,
|
|
237
|
+
retryBaseMs: config.retryBaseMs,
|
|
238
|
+
keys: allKeys,
|
|
239
|
+
executeTool: gatedExecuteTool,
|
|
240
|
+
childExecuteTool: gatedExecuteTool,
|
|
241
|
+
signal: state.activeAbort?.signal,
|
|
242
|
+
readOnly: isReadOnlyPrimary(primaryName),
|
|
243
|
+
allowedTools: allowedToolsForPrimary(primaryName),
|
|
244
|
+
createProvider: (spec: string) => createProvider(spec),
|
|
245
|
+
})) {
|
|
246
|
+
if (ev.type === 'model-start') {
|
|
247
|
+
activeModel = ev.model;
|
|
248
|
+
run.setModel(shortModel(ev.model));
|
|
249
|
+
} else if (ev.type === 'round-start') run.beginRound(ev.round, ev.max);
|
|
250
|
+
else if (ev.type === 'text-delta') run.streamText(ev.content);
|
|
251
|
+
else if (ev.type === 'tool-start') run.addTool(ev.id, ev.name, ev.argsSummary);
|
|
252
|
+
else if (ev.type === 'tool-end') run.endTool(ev.id, ev.ok, ev.content);
|
|
253
|
+
else if (ev.type === 'notice') run.notice(ev.text);
|
|
254
|
+
else if (ev.type === 'compacted') compaction = {boundary: ev.boundary, summary: ev.summary};
|
|
255
|
+
else if (ev.type === 'aborted') run.aborted();
|
|
256
|
+
else if (ev.type === 'done') usage = ev.usage;
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
return {
|
|
260
|
+
inputTokens: usage.inputTokens,
|
|
261
|
+
outputTokens: usage.outputTokens,
|
|
262
|
+
cachedTokens: usage.cachedTokens,
|
|
263
|
+
model: activeModel,
|
|
264
|
+
compaction,
|
|
265
|
+
};
|
|
266
|
+
}
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Cost estimation and display formatting.
|
|
3
|
+
*
|
|
4
|
+
* Pricing starts from a small hardcoded table, then merges LiteLLM's public
|
|
5
|
+
* manifest when it can be fetched. Unknown models deliberately price at $0
|
|
6
|
+
* rather than guessing — see `estimateCost`.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
const MODEL_PRICING: Record<string, {input: number; output: number}> = {
|
|
10
|
+
'anthropic/claude-sonnet-4': {input: 3, output: 15},
|
|
11
|
+
'anthropic/claude-3.5-sonnet': {input: 3, output: 15},
|
|
12
|
+
'openai/gpt-4o': {input: 2.5, output: 10},
|
|
13
|
+
'openai/gpt-4o-mini': {input: 0.15, output: 0.6},
|
|
14
|
+
};
|
|
15
|
+
|
|
16
|
+
const COST_MANIFEST_URL =
|
|
17
|
+
'https://raw.githubusercontent.com/BerriAI/litellm/main/model_prices_and_context_window.json';
|
|
18
|
+
|
|
19
|
+
/** Mutable pricing — hardcoded, upgraded by loadCostManifest() when the fetch succeeds. */
|
|
20
|
+
let costManifest: Record<string, {input: number; output: number}> = {...MODEL_PRICING};
|
|
21
|
+
|
|
22
|
+
/** True once the remote manifest has been merged in. */
|
|
23
|
+
let manifestLoaded = false;
|
|
24
|
+
|
|
25
|
+
export function isCostManifestLoaded(): boolean {
|
|
26
|
+
return manifestLoaded;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export async function loadCostManifest(): Promise<Record<string, {input: number; output: number}>> {
|
|
30
|
+
try {
|
|
31
|
+
const res = await fetch(COST_MANIFEST_URL, {signal: AbortSignal.timeout(5000)});
|
|
32
|
+
if (!res.ok) return MODEL_PRICING;
|
|
33
|
+
const data = (await res.json()) as Record<
|
|
34
|
+
string,
|
|
35
|
+
{input_cost_per_token?: number; output_cost_per_token?: number}
|
|
36
|
+
>;
|
|
37
|
+
const manifest: Record<string, {input: number; output: number}> = {};
|
|
38
|
+
for (const [model, info] of Object.entries(data)) {
|
|
39
|
+
if (info && typeof info === 'object' && 'input_cost_per_token' in info) {
|
|
40
|
+
manifest[model] = {
|
|
41
|
+
input: (info.input_cost_per_token ?? 0) * 1_000_000,
|
|
42
|
+
output: (info.output_cost_per_token ?? 0) * 1_000_000,
|
|
43
|
+
};
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
costManifest = {...MODEL_PRICING, ...manifest};
|
|
47
|
+
manifestLoaded = true;
|
|
48
|
+
return costManifest;
|
|
49
|
+
} catch {
|
|
50
|
+
return MODEL_PRICING; // offline / rate-limited — keep the hardcoded table
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** Cached input tokens are billed at roughly 10% of the normal input rate. */
|
|
55
|
+
const CACHE_DISCOUNT = 0.1;
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* Cost in USD for one turn.
|
|
59
|
+
*
|
|
60
|
+
* Tries the full `provider/model` spec, then the bare model name, because
|
|
61
|
+
* manifests key differently. Returns 0 for unknown models and for `*free*`
|
|
62
|
+
* variants — under-reporting beats inventing a number.
|
|
63
|
+
*/
|
|
64
|
+
/**
|
|
65
|
+
* True when we have a price for this model. Unknown models price at $0, so the
|
|
66
|
+
* UI uses this to label the figure as an estimate rather than a real cost.
|
|
67
|
+
*/
|
|
68
|
+
export function isPricedModel(model: string): boolean {
|
|
69
|
+
if (model.includes(':free') || model.includes('-free')) return true;
|
|
70
|
+
const bare = model.includes('/') ? model.split('/').slice(1).join('/') : model;
|
|
71
|
+
return Boolean(costManifest[model] ?? costManifest[bare]);
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
export function estimateCost(
|
|
75
|
+
model: string,
|
|
76
|
+
inputTokens: number,
|
|
77
|
+
outputTokens: number,
|
|
78
|
+
cachedTokens = 0,
|
|
79
|
+
): number {
|
|
80
|
+
if (model.includes(':free') || model.includes('-free')) return 0;
|
|
81
|
+
const bare = model.includes('/') ? model.split('/').slice(1).join('/') : model;
|
|
82
|
+
const pricing = costManifest[model] ?? costManifest[bare];
|
|
83
|
+
if (!pricing) return 0;
|
|
84
|
+
const uncachedInput = Math.max(0, inputTokens - cachedTokens);
|
|
85
|
+
return (
|
|
86
|
+
(uncachedInput / 1_000_000) * pricing.input +
|
|
87
|
+
(cachedTokens / 1_000_000) * pricing.input * CACHE_DISCOUNT +
|
|
88
|
+
(outputTokens / 1_000_000) * pricing.output
|
|
89
|
+
);
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
export function formatTokens(n: number): string {
|
|
93
|
+
if (n >= 10_000_000) return `${Math.round(n / 1_000_000)}M`;
|
|
94
|
+
if (n >= 1_000_000) return `${(n / 1_000_000).toFixed(1)}M`;
|
|
95
|
+
if (n >= 10_000) return `${Math.round(n / 1_000)}k`;
|
|
96
|
+
if (n >= 1_000) return `${(n / 1_000).toFixed(1)}k`;
|
|
97
|
+
return String(n);
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
export function formatCost(cost: number): string {
|
|
101
|
+
if (cost === 0) return '$0.00';
|
|
102
|
+
if (cost < 0.01) return '<$0.01';
|
|
103
|
+
return `$${cost.toFixed(2)}`;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** e.g. "(83% cached)" — share of input tokens served from the provider's prompt cache. */
|
|
107
|
+
export function formatCacheHit(cached: number, total: number): string {
|
|
108
|
+
if (total <= 0 || cached <= 0) return '';
|
|
109
|
+
const pct = Math.min(100, Math.round((cached / total) * 100));
|
|
110
|
+
return `(${pct}% cached)`;
|
|
111
|
+
}
|