pal-code 0.0.7 → 0.0.10

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 (61) hide show
  1. package/README.md +3 -3
  2. package/SYSTEM.md +3 -3
  3. package/bin/pal-code.js +37 -11
  4. package/package.json +11 -11
  5. package/packages/cli/README.md +2 -2
  6. package/packages/cli/src/commands/ext.ts +1 -1
  7. package/packages/cli/src/commands.ts +1 -1
  8. package/packages/cli/src/components/render-history.ts +2 -2
  9. package/packages/cli/src/config.ts +2 -2
  10. package/packages/cli/src/index.ts +8 -10
  11. package/packages/cli/src/overlays/key-input.ts +1 -1
  12. package/packages/cli/src/overlays/model-picker.ts +2 -2
  13. package/packages/cli/src/overlays/session-picker.ts +1 -1
  14. package/packages/cli/src/overlays/wizard.ts +1 -1
  15. package/packages/cli/src/state.ts +2 -2
  16. package/packages/cli/src/turn.ts +14 -9
  17. package/packages/cli/src/utils/permissions.ts +3 -3
  18. package/packages/cli/src/utils/format.test.ts +0 -167
  19. package/packages/core/src/agent/events.ts +0 -36
  20. package/packages/core/src/agent/fallback.test.ts +0 -99
  21. package/packages/core/src/agent/fallback.ts +0 -344
  22. package/packages/core/src/agent/index.ts +0 -35
  23. package/packages/core/src/agent/protocol.test.ts +0 -136
  24. package/packages/core/src/agent/resume-compaction.test.ts +0 -116
  25. package/packages/core/src/agent/roles.ts +0 -188
  26. package/packages/core/src/agent/run.test.ts +0 -207
  27. package/packages/core/src/agent/run.ts +0 -713
  28. package/packages/core/src/agent/scope.ts +0 -34
  29. package/packages/core/src/agent/todos.ts +0 -66
  30. package/packages/core/src/compaction.protocol.test.ts +0 -90
  31. package/packages/core/src/compaction.test.ts +0 -101
  32. package/packages/core/src/compaction.ts +0 -243
  33. package/packages/core/src/config.test.ts +0 -40
  34. package/packages/core/src/config.ts +0 -387
  35. package/packages/core/src/extensions.ts +0 -178
  36. package/packages/core/src/index.ts +0 -157
  37. package/packages/core/src/logger.ts +0 -54
  38. package/packages/core/src/provider/auth.ts +0 -153
  39. package/packages/core/src/provider/complete.ts +0 -63
  40. package/packages/core/src/provider/index.ts +0 -6
  41. package/packages/core/src/provider/openrouter.test.ts +0 -59
  42. package/packages/core/src/provider/openrouter.ts +0 -304
  43. package/packages/core/src/provider/pick-model.ts +0 -43
  44. package/packages/core/src/provider/registry.ts +0 -222
  45. package/packages/core/src/provider/types.ts +0 -61
  46. package/packages/core/src/repo-map.ts +0 -177
  47. package/packages/core/src/session/index.ts +0 -2
  48. package/packages/core/src/session/migration.test.ts +0 -104
  49. package/packages/core/src/session/store-v2-repair.test.ts +0 -209
  50. package/packages/core/src/session/store.test.ts +0 -235
  51. package/packages/core/src/session/store.ts +0 -677
  52. package/packages/core/src/session/types.ts +0 -72
  53. package/packages/core/src/snapshots.ts +0 -107
  54. package/packages/core/src/tools/definitions.ts +0 -365
  55. package/packages/core/src/tools/executor.test.ts +0 -122
  56. package/packages/core/src/tools/executor.ts +0 -1363
  57. package/packages/core/src/tools/index.ts +0 -5
  58. package/packages/core/src/tools/search.ts +0 -201
  59. package/scripts/postinstall.js +0 -121
  60. package/scripts/preinstall.js +0 -51
  61. package/scripts/sync-version.js +0 -35
@@ -1,72 +0,0 @@
1
- import type {AssistantMsg, ConversationMessage as Message} from '../agent/run.js';
2
-
3
- /**
4
- * Per-message metadata persisted alongside the conversation content.
5
- *
6
- * These fields are only needed for UI repaint — the model never sees them.
7
- * Everything here is optional so older rows (and callers that don't supply
8
- * metadata) keep working.
9
- */
10
- export interface MessageMeta {
11
- /** Tool name, for repainting tool blocks on session resume. */
12
- toolName?: string;
13
- /** Tool outcome, for repainting tool blocks on session resume. */
14
- toolStatus?: 'ok' | 'error';
15
- /** Which agent produced the message, for message-box coloring. */
16
- agentRole?: string;
17
- }
18
-
19
- /** A persisted message row (normalized storage). */
20
- export interface StoredMessage { id: string;
21
- sessionId: string;
22
- /** 1-based order within the session. */
23
- seq: number;
24
- role: string;
25
- content: string;
26
- toolCalls?: AssistantMsg['toolCalls'];
27
- toolCallId?: string;
28
- meta: MessageMeta;
29
- /** Unix epoch milliseconds (absolute; render in the user's local timezone). */
30
- createdAt: number;
31
- }
32
-
33
- /**
34
- * A compaction checkpoint.
35
- *
36
- * Records that the seq range `[fromSeq, toSeq]` was folded into `summary`.
37
- * Messages are NEVER deleted — this is an additive event, which is what makes
38
- * the full transcript available for repaint while the model only sees the tail.
39
- */
40
- export interface CompactionRecord {
41
- id: string;
42
- sessionId: string;
43
- fromSeq: number;
44
- toSeq: number;
45
- summary: string;
46
- createdAt: number;
47
- }
48
-
49
- /** A persisted conversation session. */
50
- export interface Session {
51
- /** UUID v4 identifier. */
52
- id: string;
53
- /** Optional human-readable title (e.g. auto-generated from the first prompt). */
54
- title?: string;
55
- /** Ordered message history. */
56
- messages: Message[];
57
- /** Unix epoch milliseconds when the session was created. */
58
- createdAt: number;
59
- /** Unix epoch milliseconds when the session was last updated. */
60
- updatedAt: number;
61
- /** Accumulated token usage and cost for this session. */
62
- tokenomics: SessionTokenomics;
63
- /** Highest seq already folded into a summary; the model only sees seq > this. */
64
- compactedUptoSeq: number;
65
- }
66
-
67
- export interface SessionTokenomics {
68
- inputTokens: number;
69
- outputTokens: number;
70
- cachedTokens: number;
71
- cost: number;
72
- }
@@ -1,107 +0,0 @@
1
- /**
2
- * File snapshots — copy files before an edit so they can be restored with /undo.
3
- * Stored in ~/.pal/snapshots/ with a manifest.json index.
4
- */
5
-
6
- import {copyFileSync, existsSync, mkdirSync, readFileSync, statSync, writeFileSync} from 'fs';
7
- import {basename, join, resolve} from 'path';
8
-
9
- export interface Snapshot {
10
- id: string;
11
- tool: string;
12
- originalPath: string;
13
- snapshotPath: string;
14
- ts: number;
15
- size: number;
16
- }
17
-
18
- const MAX_ENTRIES = 200;
19
-
20
- function home(): string {
21
- return process.env.USERPROFILE ?? process.env.HOME ?? '.';
22
- }
23
-
24
- function snapDir(): string {
25
- return join(home(), '.pal', 'snapshots');
26
- }
27
-
28
- function manifestPath(): string {
29
- return join(snapDir(), 'manifest.json');
30
- }
31
-
32
- function readManifest(): Snapshot[] {
33
- try {
34
- const raw = readFileSync(manifestPath(), 'utf-8');
35
- const parsed = JSON.parse(raw);
36
- return Array.isArray(parsed) ? (parsed as Snapshot[]) : [];
37
- } catch {
38
- return [];
39
- }
40
- }
41
-
42
- function writeManifest(entries: Snapshot[]): void {
43
- mkdirSync(snapDir(), {recursive: true});
44
- writeFileSync(manifestPath(), JSON.stringify(entries, null, 2), 'utf-8');
45
- }
46
-
47
- /** Copy a file into the snapshot store before it is modified. No-op for new files. */
48
- export function snapshotFile(filePath: string, tool: string): void {
49
- try {
50
- if (!existsSync(filePath)) return; // new file — nothing to back up
51
- const absolute = resolve(filePath);
52
- const dir = snapDir();
53
- mkdirSync(dir, {recursive: true});
54
-
55
- const id = `${Date.now()}-${Math.random().toString(36).slice(2, 6)}`;
56
- const snapshotPath = join(dir, `${id}-${basename(absolute)}`);
57
- copyFileSync(absolute, snapshotPath);
58
-
59
- const entries = readManifest();
60
- entries.push({
61
- id,
62
- tool,
63
- originalPath: absolute,
64
- snapshotPath,
65
- ts: Date.now(),
66
- size: statSync(absolute).size,
67
- });
68
- if (entries.length > MAX_ENTRIES) entries.splice(0, entries.length - MAX_ENTRIES);
69
- writeManifest(entries);
70
- } catch {
71
- /* snapshots must never break a tool call */
72
- }
73
- }
74
-
75
- /** Return the most recent snapshots, newest first. */
76
- export function listSnapshots(limit = 20): Snapshot[] {
77
- return readManifest().slice(-limit).reverse();
78
- }
79
-
80
- /** Restore a snapshot (most recent when no id given) and consume it. */
81
- export function restoreSnapshot(id?: string): {ok: boolean; message: string} {
82
- try {
83
- const entries = readManifest();
84
- if (entries.length === 0) return {ok: false, message: 'No snapshots to restore.'};
85
-
86
- const entry = id ? entries.find((e) => e.id === id) : entries[entries.length - 1];
87
- if (!entry) return {ok: false, message: `Snapshot "${id}" not found.`};
88
- if (!existsSync(entry.snapshotPath)) {
89
- return {ok: false, message: `Snapshot file missing: ${entry.snapshotPath}`};
90
- }
91
-
92
- copyFileSync(entry.snapshotPath, entry.originalPath);
93
-
94
- const idx = entries.indexOf(entry);
95
- entries.splice(idx, 1);
96
- writeManifest(entries);
97
-
98
- const time = new Date(entry.ts).toLocaleTimeString();
99
- return {
100
- ok: true,
101
- message: `Restored ${entry.originalPath} (from ${entry.tool} @ ${time})`,
102
- };
103
- } catch (err) {
104
- const msg = err instanceof Error ? err.message : String(err);
105
- return {ok: false, message: `Restore failed: ${msg}`};
106
- }
107
- }
@@ -1,365 +0,0 @@
1
- /**
2
- * Tool definitions — minimal to minimize token cost.
3
- */
4
-
5
- export interface ToolDef {
6
- type: 'function';
7
- function: {
8
- name: string;
9
- description: string;
10
- parameters: Record<string, unknown>;
11
- };
12
- }
13
-
14
- /**
15
- * Extension tool definitions, registered once by whoever loads extensions.
16
- *
17
- * Core keeps them centrally (rather than threading them through every caller)
18
- * so that `delegate` can hand the *full* toolset to child agents. Without this
19
- * a role like `librarian`, whose tools are all extension-provided, would spawn
20
- * a child with no usable tools at all.
21
- */
22
- let _extensionTools: ToolDef[] = [];
23
-
24
- /** Replace the registered extension tools. Called on load and on `/reload`. */
25
- export function registerExtensionTools(tools: ToolDef[]): void {
26
- _extensionTools = Array.isArray(tools) ? [...tools] : [];
27
- }
28
-
29
- /** The extension tools currently registered (read-only view). */
30
- export function getExtensionTools(): readonly ToolDef[] {
31
- return _extensionTools;
32
- }
33
-
34
- /**
35
- * Get all tools — core tools plus registered extension tools, plus any
36
- * explicitly supplied ones (kept for callers that aren't the registry).
37
- */
38
- export function getAllTools(extra: ToolDef[] = []): ToolDef[] {
39
- return [...CORE_TOOLS, ..._extensionTools, ...extra];
40
- }
41
-
42
- export const CORE_TOOLS: ToolDef[] = [
43
- {
44
- type: 'function',
45
- function: {
46
- name: 'read_file',
47
- description: 'Read file with line numbers.',
48
- parameters: {
49
- type: 'object',
50
- properties: {
51
- path: {type: 'string'},
52
- offset: {type: 'number'},
53
- limit: {type: 'number'},
54
- },
55
- required: ['path'],
56
- },
57
- },
58
- },
59
- {
60
- type: 'function',
61
- function: {
62
- name: 'write_file',
63
- description: 'Create or overwrite file.',
64
- parameters: {
65
- type: 'object',
66
- properties: {
67
- path: {type: 'string'},
68
- content: {type: 'string'},
69
- },
70
- required: ['path', 'content'],
71
- },
72
- },
73
- },
74
- {
75
- type: 'function',
76
- function: {
77
- name: 'edit_file',
78
- description: 'Replace exact string in file.',
79
- parameters: {
80
- type: 'object',
81
- properties: {
82
- path: {type: 'string'},
83
- old_string: {type: 'string'},
84
- new_string: {type: 'string'},
85
- },
86
- required: ['path', 'old_string', 'new_string'],
87
- },
88
- },
89
- },
90
- {
91
- type: 'function',
92
- function: {
93
- name: 'edit_block',
94
- description:
95
- 'Edit a file using SEARCH/REPLACE blocks. Return the exact code to find (SEARCH) and what to replace it with (REPLACE). Multiple blocks allowed.',
96
- parameters: {
97
- type: 'object',
98
- properties: {
99
- path: {type: 'string', description: 'File path'},
100
- edits: {
101
- type: 'string',
102
- description:
103
- 'SEARCH/REPLACE blocks in format:\n<<<<<<< SEARCH\nexact code to find\n=======\nreplacement code\n>>>>>>> REPLACE',
104
- },
105
- },
106
- required: ['path', 'edits'],
107
- },
108
- },
109
- },
110
- {
111
- type: 'function',
112
- function: {
113
- name: 'bash',
114
- description: 'Run shell command.',
115
- parameters: {
116
- type: 'object',
117
- properties: {
118
- command: {type: 'string'},
119
- cwd: {type: 'string'},
120
- },
121
- required: ['command'],
122
- },
123
- },
124
- },
125
- {
126
- type: 'function',
127
- function: {
128
- name: 'list_directory',
129
- description: 'List directory contents.',
130
- parameters: {
131
- type: 'object',
132
- properties: {
133
- path: {type: 'string'},
134
- pattern: {type: 'string'},
135
- },
136
- required: ['path'],
137
- },
138
- },
139
- },
140
- {
141
- type: 'function',
142
- function: {
143
- name: 'grep',
144
- description: 'Regex search file contents.',
145
- parameters: {
146
- type: 'object',
147
- properties: {
148
- pattern: {type: 'string'},
149
- path: {type: 'string'},
150
- include: {type: 'string'},
151
- },
152
- required: ['pattern'],
153
- },
154
- },
155
- },
156
- {
157
- type: 'function',
158
- function: {
159
- name: 'grep_search',
160
- description: 'Fast ripgrep search grouped by file.',
161
- parameters: {
162
- type: 'object',
163
- properties: {
164
- pattern: {type: 'string'},
165
- path: {type: 'string'},
166
- include: {type: 'string'},
167
- limit: {type: 'number'},
168
- },
169
- required: ['pattern'],
170
- },
171
- },
172
- },
173
- {
174
- type: 'function',
175
- function: {
176
- name: 'glob_search',
177
- description: 'Find files by glob pattern.',
178
- parameters: {
179
- type: 'object',
180
- properties: {
181
- pattern: {type: 'string'},
182
- path: {type: 'string'},
183
- limit: {type: 'number'},
184
- },
185
- required: ['pattern'],
186
- },
187
- },
188
- },
189
- {
190
- type: 'function',
191
- function: {
192
- name: 'ast_grep',
193
- description: 'AST structural code search.',
194
- parameters: {
195
- type: 'object',
196
- properties: {
197
- pattern: {type: 'string'},
198
- path: {type: 'string'},
199
- language: {type: 'string'},
200
- },
201
- required: ['pattern', 'path'],
202
- },
203
- },
204
- },
205
- {
206
- type: 'function',
207
- function: {
208
- name: 'repo_map',
209
- description:
210
- 'Get structural overview of source files in a directory. Shows files with their top-level functions, classes, types.',
211
- parameters: {
212
- type: 'object',
213
- properties: {
214
- path: {type: 'string', description: 'Directory path (default: current directory)'},
215
- max_tokens: {type: 'number', description: 'Max tokens for output (default: 1000)'},
216
- },
217
- },
218
- },
219
- },
220
- {
221
- type: 'function',
222
- function: {
223
- name: 'delegate',
224
- description:
225
- 'Delegate a sub-task to a child agent with its own context. Pass `agent` for a read-only specialist (explore, librarian, plan-consultant, plan-reviewer) or `category` for an implementation lane (build, architect, deep, quick, writing, review). Omit both for ad-hoc delegation with default read-only tools.',
226
- parameters: {
227
- type: 'object',
228
- properties: {
229
- task: {
230
- type: 'string',
231
- description: 'Clear description of what the child agent should do',
232
- },
233
- agent: {
234
- type: 'string',
235
- description:
236
- 'Read-only specialist role (e.g. "explore", "librarian"). Mutually exclusive with `category`.',
237
- },
238
- category: {
239
- type: 'string',
240
- description:
241
- 'Implementation lane (e.g. "build", "deep", "architect"). Mutually exclusive with `agent`.',
242
- },
243
- model: {
244
- type: 'string',
245
- description: 'Explicit `provider/model` override. Takes precedence over the role.',
246
- },
247
- reasoning: {
248
- type: 'string',
249
- enum: ['low', 'medium', 'high'],
250
- description: 'Reasoning effort override. Takes precedence over the role.',
251
- },
252
- tools: {
253
- type: 'array',
254
- items: {type: 'string'},
255
- description:
256
- 'Tool names the child may use. Default: read-only tools (read_file, list_directory, grep_search, ast_grep, glob_search).',
257
- },
258
- max_rounds: {
259
- type: 'number',
260
- description: 'Max tool-call rounds for the child (default 5, cap 16)',
261
- },
262
- },
263
- required: ['task'],
264
- },
265
- },
266
- },
267
- {
268
- type: 'function',
269
- function: {
270
- name: 'delegate_parallel',
271
- description:
272
- 'Run several delegates concurrently. Use when sub-tasks are independent (e.g. explore three parts of a codebase, or research + explore at once). Respects the configured max_parallel limit and returns results in input order.',
273
- parameters: {
274
- type: 'object',
275
- properties: {
276
- tasks: {
277
- type: 'array',
278
- description: 'Independent delegates to run at the same time.',
279
- items: {
280
- type: 'object',
281
- properties: {
282
- task: {type: 'string', description: 'Task description'},
283
- agent: {type: 'string', description: 'Read-only specialist role'},
284
- category: {type: 'string', description: 'Implementation lane'},
285
- model: {type: 'string', description: 'Explicit provider/model override'},
286
- },
287
- required: ['task'],
288
- },
289
- },
290
- },
291
- required: ['tasks'],
292
- },
293
- },
294
- },
295
- {
296
- type: 'function',
297
- function: {
298
- name: 'verify',
299
- description:
300
- "Run the project's verification checks (typecheck and/or tests) and return structured pass/fail. Use after edits to confirm nothing broke.",
301
- parameters: {
302
- type: 'object',
303
- properties: {
304
- checks: {
305
- type: 'array',
306
- items: {type: 'string'},
307
- description:
308
- 'Which checks to run: "typescript" (tsc --noEmit) and/or "test" (test script). Default: auto-detect both.',
309
- },
310
- path: {type: 'string', description: 'Project directory (default: current directory)'},
311
- },
312
- },
313
- },
314
- },
315
- {
316
- type: 'function',
317
- function: {
318
- name: 'recall_history',
319
- description:
320
- 'Read transcript that was summarized away by context compaction. When older messages are folded into a checkpoint they stop being sent to you, but they remain on disk — use this to recover exact details (a path, an error, an earlier decision) from that summarized prefix. Returns the raw messages, not a summary.',
321
- parameters: {
322
- type: 'object',
323
- properties: {
324
- offset: {
325
- type: 'number',
326
- description: 'Message index to start from within the summarized prefix (default 0).',
327
- },
328
- limit: {
329
- type: 'number',
330
- description: 'Max messages to return (default 20, max 100).',
331
- },
332
- },
333
- },
334
- },
335
- },
336
- {
337
- type: 'function',
338
- function: {
339
- name: 'todo',
340
- description:
341
- 'Track a multi-step task. Call with the FULL list every time (it replaces the previous plan). Keep exactly one item in_progress, mark items completed as you finish them, and only stop when every item is completed or cancelled. Use this for any task needing more than ~2 steps.',
342
- parameters: {
343
- type: 'object',
344
- properties: {
345
- todos: {
346
- type: 'array',
347
- description: 'The complete, current task list.',
348
- items: {
349
- type: 'object',
350
- properties: {
351
- content: {type: 'string', description: 'Short imperative description of the step'},
352
- status: {
353
- type: 'string',
354
- enum: ['pending', 'in_progress', 'completed', 'cancelled'],
355
- },
356
- },
357
- required: ['content', 'status'],
358
- },
359
- },
360
- },
361
- required: ['todos'],
362
- },
363
- },
364
- },
365
- ];
@@ -1,122 +0,0 @@
1
- import {test, expect, mock} from 'bun:test';
2
- import {writeFile, rm} from 'fs/promises';
3
- import {join} from 'path';
4
- import {executeTool, regexFallback, convertPatternToRegex} from './executor.js';
5
-
6
- const FIXTURE = join(import.meta.dir, '.test-fixture.ts');
7
-
8
- // ── convertPatternToRegex: task-spec conversion examples ──
9
-
10
- test('convertPatternToRegex: console.log($A)', () => {
11
- expect(convertPatternToRegex('console.log($A)')).toBe('console\\.log\\((.+?)\\)');
12
- });
13
-
14
- test('convertPatternToRegex: function $NAME($$$)', () => {
15
- expect(convertPatternToRegex('function $NAME($$$)')).toBe('function\\s+\\w+\\(.*?\\)');
16
- });
17
-
18
- test('convertPatternToRegex: const $VAR = $EXPR', () => {
19
- expect(convertPatternToRegex('const $VAR = $EXPR')).toBe('const\\s+\\w+\\s*=\\s*.+');
20
- });
21
-
22
- test('convertPatternToRegex: unknown meta-variable returns null', () => {
23
- expect(convertPatternToRegex('foo($FOO)')).toBeNull();
24
- });
25
-
26
- // ── regexFallback: output format ──
27
-
28
- test('regexFallback: matches with line numbers and [regex fallback] prefix', () => {
29
- const content = ['const x = 1;', 'console.log(x);', 'console.log("hello");', 'const y = 2;'].join(
30
- '\n',
31
- );
32
- const result = regexFallback('console.log($A)', content, 'test.ts');
33
- expect(result).toContain('[regex fallback]');
34
- expect(result).toContain('Found 2 matches');
35
- expect(result).toContain('test.ts:');
36
- expect(result).toContain('Line 2:');
37
- expect(result).toContain('Line 3:');
38
- });
39
-
40
- test('regexFallback: function pattern matches multiple functions', () => {
41
- const content = 'function foo(a, b) {\n return a + b;\n}\nfunction bar() {}\n';
42
- const result = regexFallback('function $NAME($$$)', content, 'test.ts');
43
- expect(result).toContain('Found 2 matches');
44
- });
45
-
46
- test('regexFallback: const pattern', () => {
47
- const content = 'const foo = 42;\nlet bar = 1;\nconst baz = "x";\n';
48
- const result = regexFallback('const $VAR = $EXPR', content, 'test.ts');
49
- expect(result).toContain('Found 2 matches');
50
- });
51
-
52
- test('regexFallback: unconvertible pattern returns helpful error', () => {
53
- const result = regexFallback('foo($FOO)', 'const x = 1;', 'test.ts');
54
- expect(result).toContain('Could not convert pattern to regex');
55
- });
56
-
57
- test('regexFallback: no matches returns No matches found', () => {
58
- const result = regexFallback('console.log($A)', 'const x = 1;', 'test.ts');
59
- expect(result).toBe('No matches found.');
60
- });
61
-
62
- test('regexFallback: bare $$$ pattern does not hang (zero-length guard)', () => {
63
- const result = regexFallback('$$$', 'hello world', 'test.ts');
64
- expect(result).toContain('Found 1 match');
65
- });
66
-
67
- // ── ast_grep tool end-to-end ──
68
-
69
- test('ast_grep: uses AST-grep when @ast-grep/napi is available', async () => {
70
- await writeFile(FIXTURE, 'const x = 1;\nconsole.log(x);\n');
71
- try {
72
- const result = await executeTool(
73
- 'ast_grep',
74
- JSON.stringify({pattern: 'console.log($A)', path: FIXTURE}),
75
- 'call-1',
76
- );
77
- expect(result.error).toBeFalsy();
78
- expect(result.content).toContain('Found 1 match');
79
- expect(result.content).not.toContain('[regex fallback]');
80
- } finally {
81
- await rm(FIXTURE, {force: true});
82
- }
83
- });
84
-
85
- test('ast_grep: falls back to regex when @ast-grep/napi is unavailable', async () => {
86
- // Run in a subprocess: Bun.mock.module cannot override a module already
87
- // loaded in this process, and mocks leak across test files. A fresh
88
- // subprocess has a clean module cache, so the mock reliably intercepts
89
- // the dynamic import inside ast_grep.
90
- await writeFile(FIXTURE, 'const x = 1;\nconsole.log(x);\n');
91
- try {
92
- const script = `
93
- import {mock} from 'bun:test';
94
- mock.module('@ast-grep/napi', () => ({})); // broken native build: no API
95
- const {executeTool} = await import('./executor.js');
96
- const result = await executeTool(
97
- 'ast_grep',
98
- JSON.stringify({pattern: 'console.log($A)', path: ${JSON.stringify(FIXTURE)}}),
99
- 'call-2',
100
- );
101
- console.log(JSON.stringify(result));
102
- `;
103
- const proc = Bun.spawn(['bun', '-e', script], {
104
- cwd: import.meta.dir,
105
- stdout: 'pipe',
106
- stderr: 'pipe',
107
- });
108
- const [stdout, stderr] = await Promise.all([
109
- new Response(proc.stdout).text(),
110
- new Response(proc.stderr).text(),
111
- ]);
112
- await proc.exited;
113
- expect(proc.exitCode).toBe(0);
114
- const result = JSON.parse(stdout);
115
- expect(result.error).toBeFalsy();
116
- expect(result.content).toContain('[regex fallback]');
117
- expect(result.content).toContain('Found 1 match');
118
- expect(result.content).toContain('console.log(x)');
119
- } finally {
120
- await rm(FIXTURE, {force: true});
121
- }
122
- });