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.
Files changed (73) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +169 -0
  3. package/SYSTEM.md +146 -0
  4. package/bin/pal-code.js +131 -0
  5. package/package.json +68 -0
  6. package/packages/cli/README.md +77 -0
  7. package/packages/cli/src/agent-panel.ts +94 -0
  8. package/packages/cli/src/commands/ext.ts +79 -0
  9. package/packages/cli/src/commands/mcp-registry.ts +136 -0
  10. package/packages/cli/src/commands/mcp.ts +186 -0
  11. package/packages/cli/src/commands.ts +153 -0
  12. package/packages/cli/src/components/message-box.ts +35 -0
  13. package/packages/cli/src/components/permission-prompt.ts +185 -0
  14. package/packages/cli/src/components/render-history.ts +143 -0
  15. package/packages/cli/src/components/run-view.ts +256 -0
  16. package/packages/cli/src/components/sidebar.ts +120 -0
  17. package/packages/cli/src/components/status-line.ts +26 -0
  18. package/packages/cli/src/config.ts +107 -0
  19. package/packages/cli/src/index.ts +1606 -0
  20. package/packages/cli/src/overlays/key-input.ts +167 -0
  21. package/packages/cli/src/overlays/model-picker.ts +106 -0
  22. package/packages/cli/src/overlays/session-picker.ts +168 -0
  23. package/packages/cli/src/overlays/wizard.ts +145 -0
  24. package/packages/cli/src/state.ts +133 -0
  25. package/packages/cli/src/theme.ts +88 -0
  26. package/packages/cli/src/turn.ts +266 -0
  27. package/packages/cli/src/utils/cost.ts +111 -0
  28. package/packages/cli/src/utils/format.test.ts +167 -0
  29. package/packages/cli/src/utils/format.ts +248 -0
  30. package/packages/cli/src/utils/highlight.ts +358 -0
  31. package/packages/cli/src/utils/permissions.ts +196 -0
  32. package/packages/core/src/agent/events.ts +36 -0
  33. package/packages/core/src/agent/fallback.test.ts +99 -0
  34. package/packages/core/src/agent/fallback.ts +344 -0
  35. package/packages/core/src/agent/index.ts +35 -0
  36. package/packages/core/src/agent/protocol.test.ts +136 -0
  37. package/packages/core/src/agent/resume-compaction.test.ts +116 -0
  38. package/packages/core/src/agent/roles.ts +188 -0
  39. package/packages/core/src/agent/run.test.ts +207 -0
  40. package/packages/core/src/agent/run.ts +713 -0
  41. package/packages/core/src/agent/scope.ts +34 -0
  42. package/packages/core/src/agent/todos.ts +66 -0
  43. package/packages/core/src/compaction.protocol.test.ts +90 -0
  44. package/packages/core/src/compaction.test.ts +101 -0
  45. package/packages/core/src/compaction.ts +243 -0
  46. package/packages/core/src/config.test.ts +40 -0
  47. package/packages/core/src/config.ts +387 -0
  48. package/packages/core/src/extensions.ts +178 -0
  49. package/packages/core/src/index.ts +157 -0
  50. package/packages/core/src/logger.ts +54 -0
  51. package/packages/core/src/provider/auth.ts +153 -0
  52. package/packages/core/src/provider/complete.ts +63 -0
  53. package/packages/core/src/provider/index.ts +6 -0
  54. package/packages/core/src/provider/openrouter.test.ts +59 -0
  55. package/packages/core/src/provider/openrouter.ts +304 -0
  56. package/packages/core/src/provider/pick-model.ts +43 -0
  57. package/packages/core/src/provider/registry.ts +222 -0
  58. package/packages/core/src/provider/types.ts +61 -0
  59. package/packages/core/src/repo-map.ts +177 -0
  60. package/packages/core/src/session/index.ts +2 -0
  61. package/packages/core/src/session/migration.test.ts +104 -0
  62. package/packages/core/src/session/store-v2-repair.test.ts +209 -0
  63. package/packages/core/src/session/store.test.ts +235 -0
  64. package/packages/core/src/session/store.ts +677 -0
  65. package/packages/core/src/session/types.ts +72 -0
  66. package/packages/core/src/snapshots.ts +107 -0
  67. package/packages/core/src/tools/definitions.ts +365 -0
  68. package/packages/core/src/tools/executor.test.ts +122 -0
  69. package/packages/core/src/tools/executor.ts +1363 -0
  70. package/packages/core/src/tools/index.ts +5 -0
  71. package/packages/core/src/tools/search.ts +201 -0
  72. package/scripts/postinstall.js +121 -0
  73. package/scripts/preinstall.js +51 -0
@@ -0,0 +1,94 @@
1
+ /**
2
+ * Background agents panel — rendered as an overlay, opened with ctrl+b.
3
+ *
4
+ * This module encapsulates the UI for monitoring sub-agent lifecycle events
5
+ * (delegate-start, delegate-done) that are hidden from the main transcript.
6
+ */
7
+
8
+ import {Text} from '@earendil-works/pi-tui';
9
+ import type {TUI, Container, Component} from '@earendil-works/pi-tui';
10
+ import {c} from './theme.js';
11
+ import {state} from './state.js';
12
+
13
+ export interface AgentsPanel {
14
+ label: Text;
15
+ body: Text;
16
+ timer: ReturnType<typeof setInterval>;
17
+ }
18
+
19
+ type EditorLike = Component & {getText(): string; disableSubmit: boolean};
20
+
21
+ function renderBody(body: Text): void {
22
+ if (state.backgroundAgents.length === 0) {
23
+ body.setText(`${c.dim} No sub-agents yet. The delegate tool spawns them.${c.reset}`);
24
+ return;
25
+ }
26
+ const blocks = state.backgroundAgents.map((a) => {
27
+ const icon =
28
+ a.status === 'running'
29
+ ? `${c.yellow}●${c.reset}`
30
+ : a.status === 'done'
31
+ ? `${c.green}✓${c.reset}`
32
+ : `${c.red}✗${c.reset}`;
33
+ const elapsed = (((a.finishedAt ?? Date.now()) - a.startedAt) / 1000).toFixed(0);
34
+ const task = a.task.length > 76 ? a.task.slice(0, 75) + '…' : a.task;
35
+ const tail = a.result
36
+ ? `\n ${c.dim}${a.result.replace(/\s+/g, ' ').slice(0, 140)}${c.reset}`
37
+ : '';
38
+ return ` ${icon} ${c.bold}${a.id}${c.reset} ${c.dim}${a.status} · ${elapsed}s${c.reset}\n ${task}${tail}`;
39
+ });
40
+ body.setText(blocks.join('\n\n'));
41
+ }
42
+
43
+ /**
44
+ * Open the background agents panel, replacing the editor in the editor row.
45
+ * Returns the panel handle so the caller can close it later.
46
+ */
47
+ export function openAgentsPanel(
48
+ tui: TUI,
49
+ messagesContainer: Container,
50
+ editorRow: Container,
51
+ editor: EditorLike,
52
+ ): AgentsPanel {
53
+ state.overlayMode = 'agents';
54
+ editorRow.removeChild(editor);
55
+ const label = new Text(
56
+ `\n${c.bold}Background agents${c.reset} ${c.dim}(ctrl+b / Esc to close)${c.reset}\n`,
57
+ 1,
58
+ 0,
59
+ );
60
+ const body = new Text('', 1, 0);
61
+ messagesContainer.addChild(label);
62
+ messagesContainer.addChild(body);
63
+ renderBody(body);
64
+ // Re-render while open so elapsed time and status stay live.
65
+ const timer = setInterval(() => {
66
+ if (state.overlayMode !== 'agents') {
67
+ clearInterval(timer);
68
+ return;
69
+ }
70
+ renderBody(body);
71
+ tui.requestRender();
72
+ }, 500);
73
+ tui.requestRender();
74
+ return {label, body, timer};
75
+ }
76
+
77
+ /**
78
+ * Close the background agents panel and restore the editor.
79
+ */
80
+ export function closeAgentsPanel(
81
+ tui: TUI,
82
+ panel: AgentsPanel,
83
+ messagesContainer: Container,
84
+ editorRow: Container,
85
+ editor: EditorLike,
86
+ ): void {
87
+ clearInterval(panel.timer);
88
+ messagesContainer.removeChild(panel.label);
89
+ messagesContainer.removeChild(panel.body);
90
+ editorRow.addChild(editor);
91
+ tui.setFocus(editor);
92
+ state.overlayMode = 'none';
93
+ tui.requestRender();
94
+ }
@@ -0,0 +1,79 @@
1
+ /**
2
+ * Extension install/uninstall commands.
3
+ *
4
+ * `pal add <pkg>` runs `bun add <pkg>` inside ~/.pal/extensions/ and
5
+ * registers the package in ~/.pal/config.json.
6
+ * `pal remove <pkg>` does the reverse.
7
+ */
8
+
9
+ import {homedir} from 'node:os';
10
+ import {join} from 'node:path';
11
+ import {existsSync, mkdirSync, readFileSync, writeFileSync} from 'node:fs';
12
+ import {execSync} from 'node:child_process';
13
+ import {readPalConfig, saveSetting} from '@pal/core';
14
+
15
+ const EXTENSIONS_DIR = join(homedir(), '.pal', 'extensions');
16
+
17
+ function ensureExtensionsDir(): void {
18
+ if (!existsSync(EXTENSIONS_DIR)) {
19
+ mkdirSync(EXTENSIONS_DIR, {recursive: true});
20
+ }
21
+ // Ensure package.json exists so bun add works
22
+ const pkgPath = join(EXTENSIONS_DIR, 'package.json');
23
+ if (!existsSync(pkgPath)) {
24
+ writeFileSync(pkgPath, JSON.stringify({name: '.pal-extensions', private: true}, null, 2));
25
+ }
26
+ }
27
+
28
+ function getExtensions(): string[] {
29
+ const config = readPalConfig();
30
+ return Array.isArray(config.extensions) ? (config.extensions as string[]) : [];
31
+ }
32
+
33
+ export interface ExtCommandResult {
34
+ ok: boolean;
35
+ message: string;
36
+ }
37
+
38
+ export function extAdd(pkg: string): ExtCommandResult {
39
+ try {
40
+ ensureExtensionsDir();
41
+
42
+ // Install with bun
43
+ execSync(`bun add ${pkg}`, {cwd: EXTENSIONS_DIR, stdio: 'pipe'});
44
+
45
+ // Register in config
46
+ const extensions = getExtensions();
47
+ if (!extensions.includes(pkg)) {
48
+ extensions.push(pkg);
49
+ saveSetting('extensions', extensions);
50
+ }
51
+
52
+ return {ok: true, message: `Installed ${pkg} and registered in config.`};
53
+ } catch (err) {
54
+ const msg = err instanceof Error ? err.message : String(err);
55
+ return {ok: false, message: `Failed to install ${pkg}: ${msg}`};
56
+ }
57
+ }
58
+
59
+ export function extRemove(pkg: string): ExtCommandResult {
60
+ try {
61
+ // Unregister from config
62
+ const extensions = getExtensions();
63
+ const idx = extensions.indexOf(pkg);
64
+ if (idx !== -1) {
65
+ extensions.splice(idx, 1);
66
+ saveSetting('extensions', extensions);
67
+ }
68
+
69
+ // Uninstall with bun
70
+ if (existsSync(EXTENSIONS_DIR)) {
71
+ execSync(`bun remove ${pkg}`, {cwd: EXTENSIONS_DIR, stdio: 'pipe'});
72
+ }
73
+
74
+ return {ok: true, message: `Removed ${pkg} from config and uninstalled.`};
75
+ } catch (err) {
76
+ const msg = err instanceof Error ? err.message : String(err);
77
+ return {ok: false, message: `Failed to remove ${pkg}: ${msg}`};
78
+ }
79
+ }
@@ -0,0 +1,136 @@
1
+ /**
2
+ * @pal/mcp — Curated MCP server registry.
3
+ *
4
+ * A handpicked list of popular, well-maintained MCP servers. Users can
5
+ * search and browse this registry via /mcp search and /mcp browse.
6
+ *
7
+ * To add a server: append to the REGISTRY array below.
8
+ * Format: { name, description, package, args, tags, url, headers }
9
+ */
10
+
11
+ export interface RegistryEntry {
12
+ /** Display name. */
13
+ name: string;
14
+ /** One-line description. */
15
+ description: string;
16
+ /** npm package to install/run (for local servers). */
17
+ package?: string;
18
+ /** Extra args to pass after npx (beyond the package name). */
19
+ args?: string[];
20
+ /** Remote server URL (for remote servers). */
21
+ url?: string;
22
+ /** HTTP headers for remote servers (e.g. auth tokens). */
23
+ headers?: Record<string, string>;
24
+ /** Tags for search matching. */
25
+ tags: string[];
26
+ }
27
+
28
+ export const REGISTRY: RegistryEntry[] = [
29
+ // --- Remote servers (no package needed) ---
30
+ {
31
+ name: 'Context7',
32
+ description: 'Fetch up-to-date documentation and code examples (requires API key)',
33
+ url: 'https://mcp.context7.com/mcp',
34
+ tags: ['docs', 'documentation', 'context', 'reference', 'remote'],
35
+ },
36
+ {
37
+ name: 'Grep by Vercel',
38
+ description: 'Search code snippets across GitHub repositories',
39
+ url: 'https://mcp.grep.app',
40
+ tags: ['search', 'code', 'github', 'grep', 'remote'],
41
+ },
42
+ {
43
+ name: 'Sentry',
44
+ description: 'Access Sentry error tracking and issue management (requires OAuth)',
45
+ url: 'https://mcp.sentry.dev/mcp',
46
+ tags: ['errors', 'sentry', 'monitoring', 'issues', 'remote'],
47
+ },
48
+ // --- Local servers (npm packages) ---
49
+ {
50
+ name: 'GitHub',
51
+ description: 'Access GitHub repos, issues, PRs, and search code',
52
+ package: '@modelcontextprotocol/server-github',
53
+ tags: ['github', 'git', 'repos', 'issues', 'pr', 'code-search'],
54
+ },
55
+ {
56
+ name: 'Filesystem',
57
+ description: 'Read and write files in allowed directories',
58
+ package: '@modelcontextprotocol/server-filesystem',
59
+ args: ['/path/to/allowed/dir'],
60
+ tags: ['files', 'read', 'write', 'filesystem'],
61
+ },
62
+ {
63
+ name: 'PostgreSQL',
64
+ description: 'Query PostgreSQL databases with read-only SQL',
65
+ package: '@modelcontextprotocol/server-postgres',
66
+ tags: ['postgres', 'postgresql', 'database', 'sql', 'db'],
67
+ },
68
+ {
69
+ name: 'SQLite',
70
+ description: 'Query SQLite databases with read-only SQL',
71
+ package: '@modelcontextprotocol/server-sqlite',
72
+ tags: ['sqlite', 'database', 'sql', 'db'],
73
+ },
74
+ {
75
+ name: 'Brave Search',
76
+ description: 'Web and local search using Brave Search API',
77
+ package: '@modelcontextprotocol/server-brave-search',
78
+ tags: ['search', 'web', 'brave'],
79
+ },
80
+ {
81
+ name: 'Google Maps',
82
+ description: 'Google Maps places, directions, and geocoding',
83
+ package: '@modelcontextprotocol/server-google-maps',
84
+ tags: ['maps', 'google', 'places', 'geocoding', 'directions'],
85
+ },
86
+ {
87
+ name: 'Puppeteer',
88
+ description: 'Browser automation, screenshots, and web scraping',
89
+ package: '@modelcontextprotocol/server-puppeteer',
90
+ tags: ['browser', 'screenshot', 'scraping', 'puppeteer', 'web'],
91
+ },
92
+ {
93
+ name: 'Memory',
94
+ description: 'Knowledge graph-based persistent memory',
95
+ package: '@modelcontextprotocol/server-memory',
96
+ tags: ['memory', 'knowledge-graph', 'persistent'],
97
+ },
98
+ {
99
+ name: 'Sequential Thinking',
100
+ description: 'Step-by-step structured problem solving',
101
+ package: '@modelcontextprotocol/server-sequential-thinking',
102
+ tags: ['thinking', 'reasoning', 'planning'],
103
+ },
104
+ {
105
+ name: 'Fetch',
106
+ description: 'Fetch web pages and convert to markdown',
107
+ package: '@modelcontextprotocol/server-fetch',
108
+ tags: ['fetch', 'http', 'web', 'markdown'],
109
+ },
110
+ {
111
+ name: 'Everything',
112
+ description: 'Reference/test server with all MCP features',
113
+ package: '@modelcontextprotocol/server-everything',
114
+ tags: ['test', 'demo', 'reference', 'everything'],
115
+ },
116
+ {
117
+ name: 'MySQL',
118
+ description: 'Query MySQL databases',
119
+ package: '@cocaxcode/database-mcp',
120
+ tags: ['mysql', 'database', 'sql', 'db'],
121
+ },
122
+ ];
123
+
124
+ /**
125
+ * Search the registry by query string. Matches against name, description,
126
+ * and tags (case-insensitive).
127
+ */
128
+ export function searchRegistry(query: string): RegistryEntry[] {
129
+ const q = query.toLowerCase();
130
+ return REGISTRY.filter(
131
+ (entry) =>
132
+ entry.name.toLowerCase().includes(q) ||
133
+ entry.description.toLowerCase().includes(q) ||
134
+ entry.tags.some((t) => t.includes(q)),
135
+ );
136
+ }
@@ -0,0 +1,186 @@
1
+ /**
2
+ * @pal/mcp — CLI commands for managing MCP server configuration.
3
+ *
4
+ * Subcommands:
5
+ * /mcp add <name> <command> [args...] — Add an MCP server
6
+ * /mcp remove <name> — Remove an MCP server
7
+ * /mcp list — List configured servers
8
+ * /mcp status — Show server connection status
9
+ *
10
+ * Config is written to mcp.json in the project root.
11
+ */
12
+
13
+ import {existsSync, readFileSync, writeFileSync} from 'node:fs';
14
+ import {join, resolve} from 'node:path';
15
+ import {homedir} from 'node:os';
16
+ import type {McpConfig, McpServerConfig} from '@pal/mcp';
17
+
18
+ const CONFIG_FILENAME = 'mcp.json';
19
+
20
+ export interface McpCommandResult {
21
+ ok: boolean;
22
+ message: string;
23
+ }
24
+
25
+ /** Find the mcp.json path (project root preferred, fallback to ~/.pal/). */
26
+ function findConfigPath(): string {
27
+ // Walk up from cwd looking for mcp.json
28
+ let dir = process.cwd();
29
+ while (true) {
30
+ const path = join(dir, CONFIG_FILENAME);
31
+ if (existsSync(path)) return path;
32
+ const parent = resolve(dir, '..');
33
+ if (parent === dir) break;
34
+ dir = parent;
35
+ }
36
+ // Fallback: create in project root (cwd)
37
+ return join(process.cwd(), CONFIG_FILENAME);
38
+ }
39
+
40
+ /** Read existing config or return empty. */
41
+ function readConfig(): McpConfig {
42
+ const path = findConfigPath();
43
+ if (!existsSync(path)) return {mcpServers: {}};
44
+ try {
45
+ const raw = readFileSync(path, 'utf-8');
46
+ const parsed = JSON.parse(raw);
47
+ if (parsed && typeof parsed === 'object' && parsed.mcpServers) {
48
+ return parsed as McpConfig;
49
+ }
50
+ return {mcpServers: {}};
51
+ } catch {
52
+ return {mcpServers: {}};
53
+ }
54
+ }
55
+
56
+ /** Write config to disk. */
57
+ function writeConfig(config: McpConfig): void {
58
+ const path = join(process.cwd(), CONFIG_FILENAME);
59
+ writeFileSync(path, JSON.stringify(config, null, 2) + '\n');
60
+ }
61
+
62
+ /** /mcp add <name> <command> [args...] */
63
+ export function mcpAdd(
64
+ name: string,
65
+ command: string,
66
+ args: string[],
67
+ ): McpCommandResult {
68
+ if (!name) return {ok: false, message: 'Server name is required.'};
69
+ if (!command) return {ok: false, message: 'Command is required (e.g. "npx").'};
70
+
71
+ const config = readConfig();
72
+
73
+ if (config.mcpServers[name]) {
74
+ return {ok: false, message: `Server "${name}" already exists. Use /mcp remove first to replace.`};
75
+ }
76
+
77
+ const serverConfig: McpServerConfig = {
78
+ command,
79
+ args: args.length > 0 ? args : undefined,
80
+ };
81
+
82
+ config.mcpServers[name] = serverConfig;
83
+ writeConfig(config);
84
+
85
+ const argsStr = args.length > 0 ? ` ${args.join(' ')}` : '';
86
+ return {
87
+ ok: true,
88
+ message: `Added MCP server "${name}": ${command}${argsStr}\nRestart pal or run /reload to connect.`,
89
+ };
90
+ }
91
+
92
+ /** /mcp add-remote <name> <url> [--header "Key: Value"] */
93
+ export function mcpAddRemote(
94
+ name: string,
95
+ url: string,
96
+ headers?: Record<string, string>,
97
+ ): McpCommandResult {
98
+ if (!name) return {ok: false, message: 'Server name is required.'};
99
+ if (!url) return {ok: false, message: 'URL is required (e.g. "https://mcp.context7.com/mcp").'};
100
+
101
+ // Validate URL format
102
+ try {
103
+ new URL(url);
104
+ } catch {
105
+ return {ok: false, message: `Invalid URL: ${url}`};
106
+ }
107
+
108
+ const config = readConfig();
109
+
110
+ if (config.mcpServers[name]) {
111
+ return {ok: false, message: `Server "${name}" already exists. Use /mcp remove first to replace.`};
112
+ }
113
+
114
+ const serverConfig: McpServerConfig = {
115
+ url,
116
+ headers: headers && Object.keys(headers).length > 0 ? headers : undefined,
117
+ };
118
+
119
+ config.mcpServers[name] = serverConfig;
120
+ writeConfig(config);
121
+
122
+ return {
123
+ ok: true,
124
+ message: `Added remote MCP server "${name}": ${url}\nRestart pal or run /reload to connect.`,
125
+ };
126
+ }
127
+
128
+ /** /mcp remove <name> */
129
+ export function mcpRemove(name: string): McpCommandResult {
130
+ if (!name) return {ok: false, message: 'Server name is required.'};
131
+
132
+ const config = readConfig();
133
+
134
+ if (!config.mcpServers[name]) {
135
+ return {ok: false, message: `Server "${name}" not found. Use /mcp list to see configured servers.`};
136
+ }
137
+
138
+ delete config.mcpServers[name];
139
+ writeConfig(config);
140
+
141
+ return {
142
+ ok: true,
143
+ message: `Removed MCP server "${name}".\nRestart pal or run /reload to apply.`,
144
+ };
145
+ }
146
+
147
+ /** /mcp list — show configured servers */
148
+ export function mcpList(): string[] {
149
+ const config = readConfig();
150
+ const names = Object.keys(config.mcpServers);
151
+
152
+ if (names.length === 0) {
153
+ return ['No MCP servers configured.', '', 'Use /mcp add <name> <command> [args...] to add a local server.'];
154
+ }
155
+
156
+ const lines: string[] = ['Configured MCP servers:', ''];
157
+ for (const [name, server] of Object.entries(config.mcpServers)) {
158
+ const enabled = server.enabled !== false;
159
+ const status = enabled ? 'enabled' : 'disabled';
160
+ lines.push(` ${name}`);
161
+
162
+ if ('url' in server) {
163
+ // Remote server
164
+ lines.push(` type: remote`);
165
+ lines.push(` url: ${server.url}`);
166
+ if (server.headers) {
167
+ const keys = Object.keys(server.headers);
168
+ lines.push(` headers: ${keys.join(', ')}`);
169
+ }
170
+ } else {
171
+ // Local server
172
+ const argsStr = server.args ? ` ${server.args.join(' ')}` : '';
173
+ lines.push(` type: local`);
174
+ lines.push(` command: ${server.command}${argsStr}`);
175
+ if (server.env) {
176
+ const keys = Object.keys(server.env);
177
+ lines.push(` env: ${keys.join(', ')}`);
178
+ }
179
+ }
180
+
181
+ lines.push(` status: ${status}`);
182
+ lines.push('');
183
+ }
184
+
185
+ return lines;
186
+ }
@@ -0,0 +1,153 @@
1
+ /**
2
+ * Slash-command output renderers.
3
+ *
4
+ * Pure presentation: each takes a container + TUI, appends pi-tui components,
5
+ * and requests a render. No engine logic lives here.
6
+ */
7
+
8
+ import {Text} from '@earendil-works/pi-tui';
9
+ import type {TUI, Container} from '@earendil-works/pi-tui';
10
+
11
+ import {c} from './theme.js';
12
+ import {formatTokens, formatCost} from './utils/cost.js';
13
+ import {isDebugEnabled} from '@pal/core';
14
+
15
+ export function cmdHelp(container: Container, tui: TUI): void {
16
+ container.addChild(new Text('', 0, 0));
17
+ container.addChild(new Text(` ${c.bold}Available commands:${c.reset}`, 1, 0));
18
+ container.addChild(new Text(` ${c.cyan}/help${c.reset} Show this help message`, 1, 0));
19
+ container.addChild(new Text(` ${c.cyan}/exit${c.reset} Save session and quit`, 1, 0));
20
+ container.addChild(
21
+ new Text(` ${c.cyan}/new${c.reset} Start a new session`, 1, 0),
22
+ );
23
+ container.addChild(new Text(` ${c.cyan}/sessions${c.reset} List recent sessions`, 1, 0));
24
+ container.addChild(
25
+ new Text(` ${c.cyan}/undo${c.reset} Restore the file from your last edit`, 1, 0),
26
+ );
27
+ container.addChild(
28
+ new Text(` ${c.cyan}/snapshots${c.reset} List recent file snapshots`, 1, 0),
29
+ );
30
+ container.addChild(
31
+ new Text(` ${c.cyan}ctrl+b${c.reset} Toggle background agent panel`, 1, 0),
32
+ );
33
+ container.addChild(new Text(` ${c.cyan}ctrl+o${c.reset} Expand the last run`, 1, 0));
34
+ container.addChild(
35
+ new Text(` ${c.cyan}esc${c.reset} Interrupt the running turn`, 1, 0),
36
+ );
37
+ container.addChild(new Text(` ${c.cyan}/resume ID${c.reset} Load a previous session`, 1, 0));
38
+ container.addChild(
39
+ new Text(` ${c.cyan}/cost${c.reset} Show token usage and estimated cost`, 1, 0),
40
+ );
41
+ container.addChild(
42
+ new Text(
43
+ ` ${c.cyan}/model${c.reset} Open model selector (arrow keys + type to filter)`,
44
+ 1,
45
+ 0,
46
+ ),
47
+ );
48
+ container.addChild(new Text(` ${c.cyan}/model NAME${c.reset} Set model directly`, 1, 0));
49
+ container.addChild(
50
+ new Text(` ${c.cyan}/key${c.reset} Set API key interactively`, 1, 0),
51
+ );
52
+ container.addChild(
53
+ new Text(` ${c.cyan}/roles${c.reset} List agent roles (agents extension)`, 1, 0),
54
+ );
55
+ container.addChild(
56
+ new Text(
57
+ ` ${c.cyan}/plan${c.reset} [task] Enter read-only plan mode (Tab also cycles)`,
58
+ 1,
59
+ 0,
60
+ ),
61
+ );
62
+ container.addChild(
63
+ new Text(` ${c.cyan}/execute${c.reset} Leave plan mode and implement`, 1, 0),
64
+ );
65
+ container.addChild(
66
+ new Text(` ${c.cyan}/ext add${c.reset} <pkg> Install an extension`, 1, 0),
67
+ );
68
+ container.addChild(
69
+ new Text(` ${c.cyan}/ext remove${c.reset} <pkg> Remove an extension`, 1, 0),
70
+ );
71
+ container.addChild(
72
+ new Text(` ${c.cyan}/ext list${c.reset} List loaded extensions`, 1, 0),
73
+ );
74
+ container.addChild(
75
+ new Text(
76
+ ` ${c.cyan}/mcp add${c.reset} <name> <cmd> [args] Add a local MCP server`,
77
+ 1,
78
+ 0,
79
+ ),
80
+ );
81
+ container.addChild(
82
+ new Text(
83
+ ` ${c.cyan}/mcp add-remote${c.reset} <name> <url> Add a remote MCP server`,
84
+ 1,
85
+ 0,
86
+ ),
87
+ );
88
+ container.addChild(
89
+ new Text(` ${c.cyan}/mcp remove${c.reset} <name> Remove an MCP server`, 1, 0),
90
+ );
91
+ container.addChild(
92
+ new Text(` ${c.cyan}/mcp list${c.reset} List MCP servers`, 1, 0),
93
+ );
94
+ container.addChild(
95
+ new Text(` ${c.cyan}/mcp browse${c.reset} Browse curated MCP servers`, 1, 0),
96
+ );
97
+ container.addChild(
98
+ new Text(` ${c.cyan}/mcp search${c.reset} <q> Search curated MCP servers`, 1, 0),
99
+ );
100
+ container.addChild(
101
+ new Text(` ${c.cyan}/permission${c.reset} Show permission rules and whitelist`, 1, 0),
102
+ );
103
+ if (isDebugEnabled()) {
104
+ container.addChild(
105
+ new Text(` ${c.cyan}/reload${c.reset} Hot-reload extensions (dev)`, 1, 0),
106
+ );
107
+ container.addChild(
108
+ new Text(` ${c.cyan}/restart${c.reset} Restart pal (saves session first)`, 1, 0),
109
+ );
110
+ }
111
+ container.addChild(new Text('', 0, 0));
112
+ container.addChild(new Text(` ${c.bold}Scroll transcript:${c.reset}`, 1, 0));
113
+ container.addChild(
114
+ new Text(
115
+ ` ${c.dim}Mouse wheel · PgUp/PgDn · ↑/↓ (while scrolled) · Home/End · Esc to exit${c.reset}`,
116
+ 1,
117
+ 0,
118
+ ),
119
+ );
120
+ container.addChild(new Text('', 0, 0));
121
+ container.addChild(new Text(` ${c.bold}Copy text:${c.reset}`, 1, 0));
122
+ container.addChild(
123
+ new Text(
124
+ ` ${c.dim}Shift+drag to select (plain drag is captured by mouse scrolling)${c.reset}`,
125
+ 1,
126
+ 0,
127
+ ),
128
+ );
129
+ container.addChild(new Text('', 0, 0));
130
+ tui.requestRender();
131
+ }
132
+
133
+ export function cmdCost(
134
+ totalInput: number,
135
+ totalOutput: number,
136
+ totalCost: number,
137
+ model: string,
138
+ container: Container,
139
+ tui: TUI,
140
+ ): void {
141
+ container.addChild(new Text('', 0, 0));
142
+ container.addChild(new Text(` ${c.bold}Token usage:${c.reset}`, 1, 0));
143
+ container.addChild(new Text(` Input: ${formatTokens(totalInput)} tokens`, 1, 0));
144
+ container.addChild(new Text(` Output: ${formatTokens(totalOutput)} tokens`, 1, 0));
145
+ container.addChild(
146
+ new Text(` Total: ${formatTokens(totalInput + totalOutput)} tokens`, 1, 0),
147
+ );
148
+ container.addChild(
149
+ new Text(` Cost: ${formatCost(totalCost)} (model: ${c.dim}${model}${c.reset})`, 1, 0),
150
+ );
151
+ container.addChild(new Text('', 0, 0));
152
+ tui.requestRender();
153
+ }
@@ -0,0 +1,35 @@
1
+ /**
2
+ * MessageBox — the reflowing user-message block.
3
+ *
4
+ * The box is rendered from the width the TUI hands us at draw time, so a
5
+ * terminal resize (or the sidebar appearing/disappearing) re-wraps existing
6
+ * messages instead of leaving them at their submit-time width.
7
+ */
8
+
9
+ import type {Component} from '@earendil-works/pi-tui';
10
+
11
+ import {userMessageBox} from '../utils/format.js';
12
+ import type {AgentRole} from '../state.js';
13
+
14
+ export class MessageBox implements Component {
15
+ private cached: string[] | null = null;
16
+ private cachedWidth = -1;
17
+
18
+ constructor(
19
+ private readonly text: string,
20
+ private readonly role: AgentRole,
21
+ private readonly timestamp = '',
22
+ ) {}
23
+
24
+ invalidate(): void {
25
+ this.cached = null;
26
+ this.cachedWidth = -1;
27
+ }
28
+
29
+ render(width: number): string[] {
30
+ if (this.cached && this.cachedWidth === width) return this.cached;
31
+ this.cached = userMessageBox(this.text, width, this.role, this.timestamp).split('\n');
32
+ this.cachedWidth = width;
33
+ return this.cached;
34
+ }
35
+ }