@pal-code/core 0.0.15 → 0.0.17

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.
@@ -30,7 +30,7 @@ import {validateRequiredArgs} from './definitions.js';
30
30
 
31
31
  /**
32
32
  * `rg --glob '!pat'` args for each `.pal.json` ignore pattern, so ripgrep
33
- * honours the same ignores as read_file / list_directory.
33
+ * honours the same ignores as read / ls.
34
34
  */
35
35
  function ignoreGlobArgs(config: ToolConfig): string[] {
36
36
  return (config.ignore ?? []).flatMap((p) => ['--glob', `!${p}`]);
@@ -69,10 +69,13 @@ async function execCommand(
69
69
  command: string,
70
70
  timeoutMs: number,
71
71
  cwdOverride?: string,
72
+ signal?: AbortSignal,
72
73
  ): Promise<{stdout: string; stderr: string; exitCode: number}> {
73
74
  const isWin = process.platform === 'win32';
74
75
  const workdir = cwdOverride ?? shellCwd;
75
76
 
77
+ if (signal?.aborted) throw new Error('Command cancelled (aborted by user).');
78
+
76
79
  const proc = Bun.spawn(isWin ? ['cmd', '/d', '/c', command] : ['bash', '-c', command], {
77
80
  stdout: 'pipe',
78
81
  stderr: 'pipe',
@@ -90,17 +93,44 @@ async function execCommand(
90
93
  }
91
94
  }, timeoutMs);
92
95
 
93
- const [stdout, stderr] = await Promise.all([
96
+ let aborted = false;
97
+ let settleAbort: (() => void) | null = null;
98
+ const onAbort = (): void => {
99
+ aborted = true;
100
+ try {
101
+ // SIGTERM gives the child a chance to flush and exit on its own; Windows
102
+ // has no graceful process kill, so it degrades to TerminateProcess there.
103
+ proc.kill(isWin ? undefined : 'SIGTERM');
104
+ } catch {
105
+ // already dead
106
+ }
107
+ settleAbort?.();
108
+ };
109
+ signal?.addEventListener('abort', onAbort, {once: true});
110
+
111
+ const readPipes = Promise.all([
94
112
  new Response(proc.stdout as ReadableStream<Uint8Array>).text(),
95
113
  new Response(proc.stderr as ReadableStream<Uint8Array>).text(),
96
114
  ]);
97
- const exitCode = await proc.exited;
115
+ // Resolves only once an abort lands, so the pipe read can lose the race.
116
+ const abortRace = new Promise<null>((resolve) => {
117
+ if (aborted) resolve(null);
118
+ else settleAbort = () => resolve(null);
119
+ });
120
+
121
+ const pipes = await Promise.race([readPipes, abortRace]);
122
+ const exitCode = aborted ? 143 : await proc.exited;
123
+
98
124
  clearTimeout(timer);
125
+ signal?.removeEventListener('abort', onAbort);
99
126
 
127
+ if (aborted) throw new Error('Command cancelled (aborted by user).');
100
128
  if (timedOut) {
101
129
  throw new Error(`Command timed out after ${timeoutMs}ms`);
102
130
  }
103
131
 
132
+ const [stdout, stderr] = pipes ?? ['', ''];
133
+
104
134
  // Track cwd changes for subsequent calls (only if cd succeeded, no override)
105
135
  const cdMatch = command.match(/^\s*cd\s+(?:\/d\s+)?["']?([^"'\s;&]+)["']?\s*(?:;|&&|$)/);
106
136
  if (cdMatch && exitCode === 0 && !cwdOverride) {
@@ -164,7 +194,7 @@ export function registerExtensionHandlers(
164
194
  }
165
195
 
166
196
  // ═══════════════════════════════════════════════════════════════════════════════
167
- // Structural edit — ast-grep fallback for edit_file (roadmap #2): locate the
197
+ // Structural edit — ast-grep fallback for edit (roadmap #2): locate the
168
198
  // node by SHAPE when old_string misses whitespace/format churn, then rebuild
169
199
  // it from a rewrite template of $A-style captures. One tool, not a general
170
200
  // tree-sitter layer.
@@ -269,7 +299,7 @@ const tools: Record<
269
299
  string,
270
300
  (args: Record<string, unknown>, config: ToolConfig) => Promise<string>
271
301
  > = {
272
- async read_file(args, config) {
302
+ async read(args, config) {
273
303
  const filePath = String(args.path);
274
304
  const offset = args.offset ? Number(args.offset) : undefined;
275
305
  const limit = args.limit ? Number(args.limit) : undefined;
@@ -308,7 +338,7 @@ const tools: Record<
308
338
  return numbered + truncated || '(empty file)';
309
339
  },
310
340
 
311
- async write_file(args, config) {
341
+ async write(args, config) {
312
342
  const filePath = String(args.path);
313
343
  const content = String(args.content);
314
344
 
@@ -317,12 +347,12 @@ const tools: Record<
317
347
  }
318
348
 
319
349
  await mkdir(dirname(filePath), {recursive: true});
320
- snapshotFile(filePath, 'write_file');
350
+ snapshotFile(filePath, 'write');
321
351
  await writeFile(filePath, content, 'utf-8');
322
352
  return `Wrote ${content.length} bytes to ${filePath}`;
323
353
  },
324
354
 
325
- async edit_file(args, config) {
355
+ async edit(args, config) {
326
356
  const filePath = String(args.path);
327
357
  const oldString = String(args.old_string);
328
358
  const newString = String(args.new_string);
@@ -361,7 +391,7 @@ const tools: Record<
361
391
  throw new Error(stringError);
362
392
  }
363
393
 
364
- snapshotFile(filePath, 'edit_file');
394
+ snapshotFile(filePath, 'edit');
365
395
  await writeFile(filePath, updated, 'utf-8');
366
396
  return `Edited ${filePath} successfully`;
367
397
  },
@@ -419,7 +449,7 @@ const tools: Record<
419
449
  return errors.length ? `${result}\n${errors.join('\n')}` : result;
420
450
  },
421
451
 
422
- async bash(args, _config) {
452
+ async bash(args, config) {
423
453
  // This tool already runs every command inside a shell (cmd.exe on Windows,
424
454
  // bash elsewhere). Models frequently add their own wrapper, which breaks on
425
455
  // nested quoting — e.g. `cmd /c "dir /a"` becomes `cmd /d /c cmd /c "dir /a"`
@@ -440,7 +470,7 @@ const tools: Record<
440
470
  }
441
471
 
442
472
  try {
443
- const {stdout, stderr, exitCode} = await execCommand(command, SHELL_TIMEOUT_MS);
473
+ const {stdout, stderr, exitCode} = await execCommand(command, SHELL_TIMEOUT_MS, undefined, config.signal);
444
474
 
445
475
  let output = '';
446
476
  if (stdout) output += stdout;
@@ -455,7 +485,7 @@ const tools: Record<
455
485
  }
456
486
  },
457
487
 
458
- async verify(args, _config) {
488
+ async verify(args, config) {
459
489
  const projectPath = args.path ? resolve(String(args.path)) : shellCwd;
460
490
  const requested = Array.isArray(args.checks) ? args.checks.map(String) : [];
461
491
 
@@ -516,6 +546,7 @@ const tools: Record<
516
546
  'bunx tsc --noEmit 2>&1',
517
547
  120_000,
518
548
  checkRoot,
549
+ config.signal,
519
550
  );
520
551
  const out = (stdout + stderr).trim();
521
552
  if (exitCode === 0) {
@@ -528,7 +559,7 @@ const tools: Record<
528
559
  }
529
560
 
530
561
  if (runTest) {
531
- const {stdout, stderr, exitCode} = await execCommand('bun run test 2>&1', 180_000, checkRoot);
562
+ const {stdout, stderr, exitCode} = await execCommand('bun run test 2>&1', 180_000, checkRoot, config.signal);
532
563
  const out = (stdout + stderr).trim();
533
564
  if (exitCode === 0) {
534
565
  lines.push('✓ test: passed');
@@ -556,7 +587,7 @@ const tools: Record<
556
587
  return formatTodos(list);
557
588
  },
558
589
 
559
- async list_directory(args, config) {
590
+ async ls(args, config) {
560
591
  const dirPath = String(args.path);
561
592
  const pattern = args.pattern ? String(args.pattern) : undefined;
562
593
 
@@ -688,7 +719,7 @@ const tools: Record<
688
719
  });
689
720
  },
690
721
 
691
- async glob_search(args, config) {
722
+ async glob(args, config) {
692
723
  const limit = args.limit ? Number(args.limit) : 100;
693
724
  const searchPath = args.path ? String(args.path) : '.';
694
725
  const rgArgs: string[] = [
@@ -1099,7 +1130,7 @@ export async function executeTool(
1099
1130
  const PROJECT_ROOT = resolveProjectRoot() ?? process.cwd();
1100
1131
  // Only guard tools that actually write files — bash and recall_history are
1101
1132
  // excluded (bash can trivially escape via shell; recall_history is read-only).
1102
- const FILE_WRITERS = new Set(['write_file', 'edit_file', 'edit_block']);
1133
+ const FILE_WRITERS = new Set(['write', 'edit', 'edit_block']);
1103
1134
  if (FILE_WRITERS.has(name) && args.path) {
1104
1135
  const rawPath = String(args.path);
1105
1136
  const resolved = resolve(PROJECT_ROOT, rawPath);
@@ -1160,11 +1191,11 @@ export async function executeTool(
1160
1191
 
1161
1192
  /** Default read-only toolset for ad-hoc (role-less) delegation. */
1162
1193
  const DEFAULT_CHILD_TOOLS = [
1163
- 'read_file',
1164
- 'list_directory',
1194
+ 'read',
1195
+ 'ls',
1165
1196
  'grep_search',
1166
1197
  'ast_grep',
1167
- 'glob_search',
1198
+ 'glob',
1168
1199
  ];
1169
1200
 
1170
1201
  const DEFAULT_CHILD_PROMPT =
@@ -1189,7 +1220,7 @@ const CHILD_MAX_ROUNDS_CAP = 16;
1189
1220
  * here, so it would be scheduled in the parallel phase. Extensions can declare
1190
1221
  * their own by calling `registerMutatingTools`.
1191
1222
  */
1192
- const MUTATING_TOOLS = new Set(['write_file', 'edit_file', 'edit_block', 'bash', 'verify']);
1223
+ const MUTATING_TOOLS = new Set(['write', 'edit', 'edit_block', 'bash', 'verify']);
1193
1224
 
1194
1225
  /**
1195
1226
  * Let an extension declare tools that mutate shared state, so they are
@@ -1548,7 +1579,7 @@ tools.delegate = async (args, config) => {
1548
1579
  *
1549
1580
  * 1. non-mutating children (the default — read-only agents) run in parallel,
1550
1581
  * in chunks of `max_parallel`;
1551
- * 2. mutating children (anything with write_file / edit_file / edit_block /
1582
+ * 2. mutating children (anything with write / edit / edit_block /
1552
1583
  * bash) then run strictly one after another.
1553
1584
  *
1554
1585
  * Phases never overlap, so a child that edits files or changes the shell cwd