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,5 @@
1
+ // Tools
2
+ export {CORE_TOOLS} from './definitions.js';
3
+ export type {ToolDef} from './definitions.js';
4
+ export {executeTool} from './executor.js';
5
+ export type {ToolResult} from './executor.js';
@@ -0,0 +1,201 @@
1
+ /**
2
+ * Cross-platform file walking + content search.
3
+ *
4
+ * Used as a fallback when `rg` (ripgrep) is unavailable — a stock Windows box
5
+ * has neither `rg` nor GNU `grep`, so the agent must still be able to search.
6
+ */
7
+
8
+ import {readdir, readFile} from 'fs/promises';
9
+ import {resolve, join, relative, sep} from 'path';
10
+
11
+ /** Directories that are almost never worth searching. */
12
+ export const DEFAULT_IGNORE = new Set([
13
+ 'node_modules',
14
+ '.git',
15
+ 'dist',
16
+ 'build',
17
+ '.next',
18
+ 'coverage',
19
+ '.zig-cache',
20
+ 'zig-out',
21
+ '.cache',
22
+ 'target',
23
+ '__pycache__',
24
+ ]);
25
+
26
+ /** Skip files larger than this (bytes) — avoids loading binaries/bundles. */
27
+ const MAX_FILE_BYTES = 2_000_000;
28
+
29
+ /** Hard cap on files visited, so a runaway tree can't hang the agent. */
30
+ const MAX_FILES_VISITED = 50_000;
31
+
32
+ /**
33
+ * Walk a directory tree depth-first, yielding file paths.
34
+ *
35
+ * `isIgnored` receives an absolute path and should return true to skip it.
36
+ * Symlinks are never followed (`Dirent` uses lstat semantics, so a linked
37
+ * directory is not reported as a directory) — cycles are impossible.
38
+ */
39
+ export async function* walkFiles(
40
+ root: string,
41
+ ignore: Set<string> = DEFAULT_IGNORE,
42
+ isIgnored?: (absPath: string) => boolean,
43
+ ): AsyncGenerator<string> {
44
+ const stack: string[] = [root];
45
+ let visited = 0;
46
+
47
+ while (stack.length > 0) {
48
+ const dir = stack.pop()!;
49
+ let entries;
50
+ try {
51
+ entries = await readdir(dir, {withFileTypes: true});
52
+ } catch {
53
+ continue; // unreadable dir (permissions) — skip
54
+ }
55
+
56
+ for (const entry of entries) {
57
+ if (visited >= MAX_FILES_VISITED) return;
58
+ const full = join(dir, entry.name);
59
+ if (isIgnored?.(full)) continue;
60
+ if (entry.isDirectory()) {
61
+ if (ignore.has(entry.name)) continue;
62
+ stack.push(full);
63
+ } else if (entry.isFile()) {
64
+ visited++;
65
+ yield full;
66
+ }
67
+ }
68
+ }
69
+ }
70
+
71
+ /** Convert a glob (`**\/*.ts`, `src/*.js`) into an anchored RegExp. */
72
+ export function globToRegExp(glob: string): RegExp {
73
+ const normalized = glob.split(sep).join('/');
74
+ let out = '';
75
+ for (let i = 0; i < normalized.length; i++) {
76
+ const ch = normalized[i];
77
+ if (ch === '*') {
78
+ if (normalized[i + 1] === '*') {
79
+ // `**/` spans directories; a trailing `**` matches everything.
80
+ if (normalized[i + 2] === '/') {
81
+ out += '(?:.*/)?';
82
+ i += 2;
83
+ } else {
84
+ out += '.*';
85
+ i += 1;
86
+ }
87
+ } else {
88
+ out += '[^/]*';
89
+ }
90
+ } else if (ch === '?') {
91
+ out += '[^/]';
92
+ } else if ('+.^${}()|[]\\'.includes(ch)) {
93
+ out += '\\' + ch;
94
+ } else {
95
+ out += ch;
96
+ }
97
+ }
98
+ return new RegExp(out + '$');
99
+ }
100
+
101
+ /** Path relative to cwd, always using forward slashes for stable display. */
102
+ function relPath(p: string): string {
103
+ return relative(process.cwd(), p).split(sep).join('/');
104
+ }
105
+
106
+ export interface GrepOptions {
107
+ pattern: string;
108
+ path: string;
109
+ include?: string;
110
+ limit: number;
111
+ /** Extra predicate so callers can layer `.pal.json` ignore patterns on top. */
112
+ isIgnored?: (absPath: string) => boolean;
113
+ }
114
+
115
+ /** Pure-JS recursive content search (regex per line). */
116
+ export async function grepJS(opts: GrepOptions): Promise<string> {
117
+ let re: RegExp;
118
+ try {
119
+ re = new RegExp(opts.pattern);
120
+ } catch (err) {
121
+ return `Invalid regex: ${err instanceof Error ? err.message : String(err)}`;
122
+ }
123
+
124
+ const includeRe = opts.include ? globToRegExp(opts.include) : null;
125
+ const root = resolve(opts.path);
126
+ const out: string[] = [];
127
+ let matchCount = 0;
128
+ let currentFile = '';
129
+ const hardCap = opts.limit * 5;
130
+
131
+ for await (const file of walkFiles(root, DEFAULT_IGNORE, opts.isIgnored)) {
132
+ const rel = relPath(file);
133
+ if (includeRe && !includeRe.test(rel)) continue;
134
+
135
+ let content: string;
136
+ try {
137
+ content = await readFile(file, 'utf-8');
138
+ } catch {
139
+ continue;
140
+ }
141
+ if (content.length > MAX_FILE_BYTES) continue;
142
+
143
+ const lines = content.split('\n');
144
+ for (let i = 0; i < lines.length; i++) {
145
+ if (!re.test(lines[i])) continue;
146
+ if (rel !== currentFile) {
147
+ if (out.length > 0) out.push('');
148
+ currentFile = rel;
149
+ out.push(rel + ':');
150
+ }
151
+ if (matchCount < opts.limit) {
152
+ out.push(` Line ${i + 1}: ${lines[i].trimEnd()}`);
153
+ }
154
+ matchCount++;
155
+ if (matchCount >= hardCap) break;
156
+ }
157
+ if (matchCount >= hardCap) break;
158
+ }
159
+
160
+ if (matchCount === 0) return 'No matches found.';
161
+ const trunc =
162
+ matchCount > opts.limit
163
+ ? `\n\n[${matchCount} matches found. Showing first ${opts.limit}. Refine the pattern or raise limit.]`
164
+ : '';
165
+ return `Found ${matchCount} match${matchCount !== 1 ? 'es' : ''}${trunc}\n\n${out.join('\n')}`;
166
+ }
167
+
168
+ export interface GlobOptions {
169
+ pattern: string;
170
+ path: string;
171
+ limit: number;
172
+ /** Extra predicate so callers can layer `.pal.json` ignore patterns on top. */
173
+ isIgnored?: (absPath: string) => boolean;
174
+ }
175
+
176
+ /** Pure-JS file discovery by glob pattern. */
177
+ export async function globJS(opts: GlobOptions): Promise<string> {
178
+ const re = globToRegExp(opts.pattern);
179
+ const root = resolve(opts.path);
180
+ const files: string[] = [];
181
+ let hitLimit = false;
182
+
183
+ for await (const file of walkFiles(root, DEFAULT_IGNORE, opts.isIgnored)) {
184
+ const rel = relPath(file);
185
+ const abs = file.split(sep).join('/');
186
+ if (re.test(rel) || re.test(abs)) {
187
+ files.push(rel);
188
+ if (files.length > opts.limit) {
189
+ hitLimit = true;
190
+ break;
191
+ }
192
+ }
193
+ }
194
+
195
+ if (files.length === 0) return 'No files found matching pattern.';
196
+ const display = files.slice(0, opts.limit);
197
+ const trunc = hitLimit
198
+ ? `\n\n[Showing first ${opts.limit} of ${files.length}+ results. Refine the pattern or raise limit.]`
199
+ : '';
200
+ return `Found ${hitLimit ? `${files.length}+` : files.length} file${files.length !== 1 ? 's' : ''}${trunc}\n\n${display.join('\n')}`;
201
+ }
@@ -0,0 +1,121 @@
1
+ #!/usr/bin/env node
2
+
3
+ /**
4
+ * pal-code postinstall script
5
+ *
6
+ * Sets up the pal-code environment:
7
+ * 1. Creates ~/.pal/ directory if missing
8
+ * 2. Initializes config.json if missing
9
+ * 3. Creates extensions directory structure
10
+ * 4. Checks for Bun (needed for extensions)
11
+ * 5. Prints first-run instructions
12
+ */
13
+
14
+ const { execSync } = require('child_process');
15
+ const fs = require('fs');
16
+ const path = require('path');
17
+ const os = require('os');
18
+
19
+ // ─── Paths ───
20
+ const PAL_HOME = path.join(os.homedir(), '.pal');
21
+ const CONFIG_PATH = path.join(PAL_HOME, 'config.json');
22
+ const EXTENSIONS_DIR = path.join(PAL_HOME, 'extensions');
23
+ const EXTENSIONS_PKG = path.join(EXTENSIONS_DIR, 'package.json');
24
+ const SESSIONS_DB = path.join(PAL_HOME, 'sessions.db');
25
+ const MCP_CONFIG = path.join(PAL_HOME, 'mcp.json');
26
+
27
+ // ─── 1. Create ~/.pal/ directory ───
28
+ if (!fs.existsSync(PAL_HOME)) {
29
+ fs.mkdirSync(PAL_HOME, { recursive: true });
30
+ console.log('✓ Created ~/.pal/');
31
+ } else {
32
+ console.log('✓ ~/.pal/ exists');
33
+ }
34
+
35
+ // ─── 2. Initialize config.json if missing ───
36
+ if (!fs.existsSync(CONFIG_PATH)) {
37
+ const defaultConfig = {
38
+ keys: {},
39
+ model: null,
40
+ keyless: null,
41
+ extensions: [],
42
+ };
43
+ fs.writeFileSync(CONFIG_PATH, JSON.stringify(defaultConfig, null, 2));
44
+ console.log('✓ Created ~/.pal/config.json');
45
+ } else {
46
+ // Validate existing config
47
+ try {
48
+ const content = fs.readFileSync(CONFIG_PATH, 'utf8');
49
+ JSON.parse(content);
50
+ console.log('✓ ~/.pal/config.json is valid');
51
+ } catch (e) {
52
+ console.warn(`⚠️ ~/.pal/config.json is invalid: ${e.message}`);
53
+ console.warn(' You may need to fix or delete it.');
54
+ }
55
+ }
56
+
57
+ // ─── 3. Create extensions directory ───
58
+ if (!fs.existsSync(EXTENSIONS_DIR)) {
59
+ fs.mkdirSync(EXTENSIONS_DIR, { recursive: true });
60
+ console.log('✓ Created ~/.pal/extensions/');
61
+ }
62
+
63
+ if (!fs.existsSync(EXTENSIONS_PKG)) {
64
+ const pkg = {
65
+ name: 'pal-extensions',
66
+ private: true,
67
+ description: 'User-installed pal-code extensions',
68
+ };
69
+ fs.writeFileSync(EXTENSIONS_PKG, JSON.stringify(pkg, null, 2));
70
+ console.log('✓ Created ~/.pal/extensions/package.json');
71
+ }
72
+
73
+ // ─── 4. Initialize MCP config if missing ───
74
+ if (!fs.existsSync(MCP_CONFIG)) {
75
+ const mcpConfig = { mcpServers: {} };
76
+ fs.writeFileSync(MCP_CONFIG, JSON.stringify(mcpConfig, null, 2));
77
+ console.log('✓ Created ~/.pal/mcp.json');
78
+ }
79
+
80
+ // ─── 5. Check for Bun (required) ───
81
+ try {
82
+ execSync('bun --version', { stdio: 'ignore' });
83
+ console.log('✓ Bun detected (extensions can be installed)');
84
+ } catch (e) {
85
+ console.error('');
86
+ console.error('╔══════════════════════════════════════════════════════╗');
87
+ console.error('║ pal-code requires Bun to run. ║');
88
+ console.error('║ ║');
89
+ console.error('║ Install Bun first: ║');
90
+ console.error('║ curl -fsSL https://bun.sh/install | bash ║');
91
+ console.error('║ ║');
92
+ console.error('║ Then run: pal ║');
93
+ console.error('║ ║');
94
+ console.error('║ Bun website: https://bun.sh ║');
95
+ console.error('╚══════════════════════════════════════════════════════╝');
96
+ console.error('');
97
+ process.exit(1);
98
+ }
99
+
100
+ // ─── 6. Print summary ───
101
+ console.log('');
102
+ console.log('╔══════════════════════════════════════════╗');
103
+ console.log('║ pal-code installed! 🎉 ║');
104
+ console.log('╠══════════════════════════════════════════╣');
105
+ console.log('║ ║');
106
+ console.log('║ Run: pal ║');
107
+ console.log('║ ║');
108
+ console.log('║ First run starts the setup wizard. ║');
109
+ console.log('║ Pick a provider and enter your API key. ║');
110
+ console.log('║ ║');
111
+ console.log('║ Install extensions: ║');
112
+ console.log('║ pal add @pal/web-search ║');
113
+ console.log('║ pal add @pal/agents ║');
114
+ console.log('║ ║');
115
+ console.log('║ Add MCP servers: ║');
116
+ console.log('║ pal mcp add <name> <command> [args] ║');
117
+ console.log('║ ║');
118
+ console.log('║ Docs: https://github.com/fngadiyo/the-agent');
119
+ console.log('║ ║');
120
+ console.log('╚══════════════════════════════════════════╝');
121
+ console.log('');
@@ -0,0 +1,51 @@
1
+ #!/usr/bin/env node
2
+
3
+ /**
4
+ * pal-code preinstall script
5
+ *
6
+ * Checks prerequisites before installation.
7
+ */
8
+
9
+ const { execSync } = require('child_process');
10
+ const { platform, arch } = require('os');
11
+
12
+ // Supported platforms
13
+ const SUPPORTED = {
14
+ 'darwin-arm64': 'macOS Apple Silicon',
15
+ 'darwin-x64': 'macOS Intel',
16
+ 'linux-x64': 'Linux x64',
17
+ 'linux-arm64': 'Linux ARM64',
18
+ 'win32-x64': 'Windows x64',
19
+ };
20
+
21
+ const key = `${platform()}-${arch()}`;
22
+ const friendly = SUPPORTED[key];
23
+
24
+ if (!friendly) {
25
+ console.warn(`\n⚠️ pal-code: Unsupported platform ${key}`);
26
+ console.warn('Supported platforms:', Object.values(SUPPORTED).join(', '));
27
+ console.warn('pal-code may not work on this platform.\n');
28
+ } else {
29
+ console.log(`✓ pal-code: Platform ${friendly} (${key})`);
30
+ }
31
+
32
+ // Check if bun is available — pal-code requires Bun to run
33
+ try {
34
+ const version = execSync('bun --version', { encoding: 'utf8', stdio: ['pipe', 'pipe', 'pipe'] }).trim();
35
+ console.log(`✓ pal-code: Bun ${version} detected`);
36
+ } catch (e) {
37
+ console.error('');
38
+ console.error('╔══════════════════════════════════════════════════════╗');
39
+ console.error('║ pal-code requires Bun to run. ║');
40
+ console.error('║ ║');
41
+ console.error('║ Install Bun first: ║');
42
+ console.error('║ curl -fsSL https://bun.sh/install | bash ║');
43
+ console.error('║ ║');
44
+ console.error('║ Then install pal-code: ║');
45
+ console.error('║ npm install -g pal-code ║');
46
+ console.error('║ ║');
47
+ console.error('║ Bun website: https://bun.sh ║');
48
+ console.error('╚══════════════════════════════════════════════════════╝');
49
+ console.error('');
50
+ process.exit(1);
51
+ }