@pal-code/core 0.0.10 → 0.0.12

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.
@@ -12,7 +12,7 @@ import {promisify} from 'util';
12
12
 
13
13
  const execAsync = promisify(exec);
14
14
  import {createInterface} from 'readline';
15
- import {dirname, resolve, isAbsolute, sep} from 'path';
15
+ import {dirname, resolve, isAbsolute, sep, extname} from 'path';
16
16
  import {minimatch} from 'minimatch';
17
17
  import {
18
18
  loadAgentConfig,
@@ -23,6 +23,7 @@ import {
23
23
  type ToolConfig,
24
24
  } from '../config.js';
25
25
  import {snapshotFile} from '../snapshots.js';
26
+ import {noteEditedFile} from '../diagnostics.js';
26
27
  import type {ConversationMessage} from '../agent/run.js';
27
28
  import {registry} from '../registry.js';
28
29
 
@@ -40,6 +41,8 @@ function ignorePredicate(config: ToolConfig): (absPath: string) => boolean {
40
41
  }
41
42
  import {log} from '../logger.js';
42
43
  import {emitAgentEvent} from '../agent/events.js';
44
+ import {subagentSpawned, subagentSettled} from '../agent/subagent-status.js';
45
+ import {emitLifecycleEvent} from '../lifecycle.js';
43
46
  import {grepJS, globJS} from './search.js';
44
47
  import {setTodos, formatTodos, type TodoStatus} from '../agent/todos.js';
45
48
 
@@ -159,6 +162,108 @@ export function registerExtensionHandlers(
159
162
  Object.assign(registry.extensionHandlers, handlers);
160
163
  }
161
164
 
165
+ // ═══════════════════════════════════════════════════════════════════════════════
166
+ // Structural edit — ast-grep fallback for edit_file (roadmap #2): locate the
167
+ // node by SHAPE when old_string misses whitespace/format churn, then rebuild
168
+ // it from a rewrite template of $A-style captures. One tool, not a general
169
+ // tree-sitter layer.
170
+ // ═══════════════════════════════════════════════════════════════════════════════
171
+
172
+ type StructuralEditResult = {ok: true; updated: string} | {ok: false; reason: string};
173
+
174
+ /** File-extension → grammar map; mirrors `ast_grep`'s LangMap (napi ships no json/markdown). */
175
+ function structuralLangFor(
176
+ sg: typeof import('@ast-grep/napi'),
177
+ ext: string,
178
+ ): (typeof sg.Lang)[keyof typeof sg.Lang] | null {
179
+ switch (ext) {
180
+ case '.ts':
181
+ case '.mts':
182
+ case '.cts':
183
+ return sg.Lang.TypeScript;
184
+ case '.tsx':
185
+ case '.jsx':
186
+ return sg.Lang.Tsx;
187
+ case '.js':
188
+ case '.mjs':
189
+ case '.cjs':
190
+ return sg.Lang.JavaScript;
191
+ case '.css':
192
+ return sg.Lang.Css;
193
+ case '.html':
194
+ case '.htm':
195
+ return sg.Lang.Html;
196
+ default:
197
+ return null;
198
+ }
199
+ }
200
+
201
+ /** Find `pattern` (exactly one match) and rebuild the node from `rewrite`, substituting `$NAME` captures. */
202
+ async function structuralEdit(opts: {
203
+ content: string;
204
+ filePath: string;
205
+ pattern: string;
206
+ rewrite: string;
207
+ }): Promise<StructuralEditResult> {
208
+ const {content, filePath, pattern, rewrite} = opts;
209
+ if (!rewrite) {
210
+ return {ok: false, reason: 'pattern provided without rewrite'};
211
+ }
212
+
213
+ const ext = extname(filePath).toLowerCase();
214
+ let sg: typeof import('@ast-grep/napi');
215
+ try {
216
+ sg = await import('@ast-grep/napi');
217
+ } catch {
218
+ return {ok: false, reason: '@ast-grep/napi unavailable for structural edit'};
219
+ }
220
+
221
+ const lang = structuralLangFor(sg, ext);
222
+ if (!lang) {
223
+ return {
224
+ ok: false,
225
+ reason: `unsupported file type for structural edit: ${ext || '(no extension)'}`,
226
+ };
227
+ }
228
+
229
+ try {
230
+ const root = sg.parse(lang, content);
231
+ const matches = root.root().findAll(pattern);
232
+ if (matches.length === 0) {
233
+ return {ok: false, reason: `structural pattern not found in ${filePath}`};
234
+ }
235
+ if (matches.length > 1) {
236
+ return {
237
+ ok: false,
238
+ reason: `structural pattern matched ${matches.length} nodes in ${filePath} (must match exactly one)`,
239
+ };
240
+ }
241
+
242
+ const match = matches[0];
243
+ const missing: string[] = [];
244
+ const finalText = rewrite.replace(/\$([A-Z][A-Z0-9_]*)/g, (whole, name) => {
245
+ const captured = match.getMatch(name);
246
+ if (!captured) {
247
+ missing.push(name);
248
+ return whole;
249
+ }
250
+ return captured.text();
251
+ });
252
+ if (missing.length > 0) {
253
+ return {
254
+ ok: false,
255
+ reason: `rewrite references ${missing.map((n) => `$${n}`).join(', ')} not captured by pattern`,
256
+ };
257
+ }
258
+ return {ok: true, updated: root.root().commitEdits([match.replace(finalText)])};
259
+ } catch (err) {
260
+ return {
261
+ ok: false,
262
+ reason: `structural pattern error: ${err instanceof Error ? err.message : String(err)}`,
263
+ };
264
+ }
265
+ }
266
+
162
267
  const tools: Record<
163
268
  string,
164
269
  (args: Record<string, unknown>, config: ToolConfig) => Promise<string>
@@ -220,6 +325,8 @@ const tools: Record<
220
325
  const filePath = String(args.path);
221
326
  const oldString = String(args.old_string);
222
327
  const newString = String(args.new_string);
328
+ const pattern = args.pattern == null ? '' : String(args.pattern);
329
+ const rewrite = args.rewrite == null ? '' : String(args.rewrite);
223
330
 
224
331
  if (isPathIgnored(filePath, config)) {
225
332
  throw new Error(`Cannot edit ${filePath} — matches ignore patterns`);
@@ -231,17 +338,28 @@ const tools: Record<
231
338
  // silent footgun — the model gets "Edited successfully" while the wrong
232
339
  // site was changed.
233
340
  const occurrences = content.split(oldString).length - 1;
234
- if (occurrences === 0) {
235
- throw new Error(`old_string not found in ${filePath}`);
236
- }
237
- if (occurrences > 1) {
238
- throw new Error(
239
- `old_string is not unique in ${filePath} (${occurrences} occurrences). ` +
240
- `Narrow the match to exactly one occurrence.`,
241
- );
341
+ const stringError =
342
+ occurrences === 0
343
+ ? `old_string not found in ${filePath}`
344
+ : occurrences > 1
345
+ ? `old_string is not unique in ${filePath} (${occurrences} occurrences). ` +
346
+ `Narrow the match to exactly one occurrence.`
347
+ : null;
348
+
349
+ let updated: string;
350
+ if (stringError === null) {
351
+ updated = content.replace(oldString, newString);
352
+ } else if (pattern) {
353
+ // Spec: exact string match → ast-grep structural match → combined error.
354
+ const structural = await structuralEdit({content, filePath, pattern, rewrite});
355
+ if (!structural.ok) {
356
+ throw new Error(`${stringError} Structural attempt failed: ${structural.reason}`);
357
+ }
358
+ updated = structural.updated;
359
+ } else {
360
+ throw new Error(stringError);
242
361
  }
243
362
 
244
- const updated = content.replace(oldString, newString);
245
363
  snapshotFile(filePath, 'edit_file');
246
364
  await writeFile(filePath, updated, 'utf-8');
247
365
  return `Edited ${filePath} successfully`;
@@ -919,6 +1037,8 @@ export async function executeTool(
919
1037
  apiKey: string;
920
1038
  baseUrl: string;
921
1039
  keys?: Record<string, string>;
1040
+ headers?: Record<string, string>;
1041
+ systemPromptAppend?: string;
922
1042
  readOnly?: boolean;
923
1043
  allowedTools?: string[];
924
1044
  },
@@ -951,7 +1071,11 @@ export async function executeTool(
951
1071
  }
952
1072
 
953
1073
  try {
954
- const args = (argsStr && argsStr.trim() ? JSON.parse(argsStr) : {}) as Record<string, unknown>;
1074
+ // Strip NULs (model-emitted or resumed-history corruption) before parse —
1075
+ // a raw null byte makes JSON.parse throw and the whole tool call fail.
1076
+ const args = (
1077
+ argsStr && argsStr.trim() ? JSON.parse(argsStr.replaceAll('\u0000', '')) : {}
1078
+ ) as Record<string, unknown>;
955
1079
  const config = loadAgentConfig();
956
1080
  if (providerConfigOverride) {
957
1081
  config.provider = providerConfigOverride;
@@ -980,12 +1104,41 @@ export async function executeTool(
980
1104
  }
981
1105
 
982
1106
  log('tool-call', {name, args: argsStr});
983
- const content = await fn(args, config);
1107
+ const startedAt = Date.now();
1108
+ let content: string;
1109
+ try {
1110
+ content = await fn(args, config);
1111
+ } catch (toolErr) {
1112
+ // The dispatch record must fire for a failed call too — then rethrow so
1113
+ // the outer catch formats the error result exactly as before.
1114
+ await emitLifecycleEvent('onToolCall', {
1115
+ tool: name,
1116
+ args,
1117
+ durationMs: Date.now() - startedAt,
1118
+ success: false,
1119
+ });
1120
+ throw toolErr;
1121
+ }
984
1122
  log('tool-result', {name, error: false, length: content.length});
1123
+ await emitLifecycleEvent('onToolCall', {
1124
+ tool: name,
1125
+ args,
1126
+ durationMs: Date.now() - startedAt,
1127
+ success: true,
1128
+ });
1129
+ // Fire-and-forget: noteEditedFile only schedules a debounced background
1130
+ // check; the handler returns its result without waiting on diagnostics.
1131
+ if (FILE_WRITERS.has(name) && args.path) {
1132
+ noteEditedFile(String(args.path));
1133
+ }
985
1134
  return {toolCallId, content};
986
1135
  } catch (err) {
987
1136
  const msg = err instanceof Error ? err.message : String(err);
988
1137
  log('tool-result', {name, error: true, message: msg});
1138
+ await emitLifecycleEvent('onError', {
1139
+ error: err instanceof Error ? err : new Error(msg),
1140
+ context: `tool:${name}`,
1141
+ });
989
1142
  return {toolCallId, content: `Error executing ${name}: ${msg}`, error: true};
990
1143
  }
991
1144
  }
@@ -1059,6 +1212,12 @@ interface ChildPlan {
1059
1212
  modelSpec?: string;
1060
1213
  /** True when `tools` contains anything that mutates global state. */
1061
1214
  mutating: boolean;
1215
+ /**
1216
+ * Per-role token budget, resolved once from the role provider at plan time.
1217
+ * Plain data: the child's round loop never consults the provider. Absent →
1218
+ * the child runs unbudgeted.
1219
+ */
1220
+ budget?: {roleName: string; limit: number};
1062
1221
  }
1063
1222
 
1064
1223
  interface SpawnArgs {
@@ -1123,6 +1282,14 @@ async function planChild(
1123
1282
  const tools = args.tools ?? role?.tools ?? DEFAULT_CHILD_TOOLS;
1124
1283
  const mutating = isMutatingToolset(tools);
1125
1284
 
1285
+ // Resolve the token budget once, at the delegate call site: the child's
1286
+ // round loop receives plain data and never consults the role provider.
1287
+ let budget: {roleName: string; limit: number} | undefined;
1288
+ if (role) {
1289
+ const limit = registry.roleProvider?.budget?.(role.name);
1290
+ if (limit !== undefined) budget = {roleName: role.name, limit};
1291
+ }
1292
+
1126
1293
  // A read-only parent (e.g. the `plan` agent) must not reach a writer via
1127
1294
  // delegation — otherwise the restriction is trivially bypassed.
1128
1295
  if (mutating && config.provider?.readOnly) {
@@ -1142,6 +1309,7 @@ async function planChild(
1142
1309
  systemPrompt: role?.systemPrompt ?? DEFAULT_CHILD_PROMPT,
1143
1310
  modelSpec: args.model ?? role?.model,
1144
1311
  mutating,
1312
+ budget,
1145
1313
  };
1146
1314
  }
1147
1315
 
@@ -1165,6 +1333,7 @@ async function executeChild(plan: ChildPlan, config: ToolConfig): Promise<string
1165
1333
  id: 'delegate',
1166
1334
  baseUrl: config.provider.baseUrl,
1167
1335
  apiKey: config.provider.apiKey,
1336
+ headers: config.provider.headers,
1168
1337
  });
1169
1338
  const providerCfg = config.provider;
1170
1339
  let childModel = providerCfg.model;
@@ -1200,12 +1369,18 @@ async function executeChild(plan: ChildPlan, config: ToolConfig): Promise<string
1200
1369
 
1201
1370
  // Dynamic import avoids the executor → run → executor import cycle.
1202
1371
  const {runAgent} = await import('../agent/run.js');
1372
+ const {withSystemPromptAppend} = await import('../provider/registry.js');
1203
1373
 
1204
1374
  await provider.init();
1205
1375
 
1206
1376
  let roundText = '';
1207
1377
  let previousText = '';
1208
1378
 
1379
+ // Live-activity counter for the front-end's status line. Spawned strictly
1380
+ // around the child run: everything below passes through the finally, so the
1381
+ // settle is symmetric on success, error, and abort — a leaked count would
1382
+ // leave a permanent phantom "subagents running" line in the UI.
1383
+ subagentSpawned();
1209
1384
  try {
1210
1385
  const childExec = providerCfg.childExecuteTool ?? executeTool;
1211
1386
  for await (const ev of runAgent({
@@ -1213,11 +1388,12 @@ async function executeChild(plan: ChildPlan, config: ToolConfig): Promise<string
1213
1388
  tools: childTools,
1214
1389
  provider,
1215
1390
  model: childModel,
1216
- systemPrompt,
1391
+ systemPrompt: withSystemPromptAppend(systemPrompt, config.provider),
1217
1392
  maxRounds,
1218
1393
  reasoningEffort: reasoning,
1219
1394
  providerConfig: providerCfg,
1220
1395
  executeTool: childExec,
1396
+ budget: plan.budget,
1221
1397
  })) {
1222
1398
  if (ev.type === 'round-start') {
1223
1399
  if (roundText) {
@@ -1236,6 +1412,7 @@ async function executeChild(plan: ChildPlan, config: ToolConfig): Promise<string
1236
1412
  emitAgentEvent({type: 'delegate-done', id: agentId, summary: msg, error: true});
1237
1413
  return `Delegate error: ${msg}`;
1238
1414
  } finally {
1415
+ subagentSettled();
1239
1416
  // Hand the parent's state back, and re-sync the UI (which may have rendered
1240
1417
  // the child's todo list via todos-updated).
1241
1418
  restoreRunScope(scope);
@@ -1262,6 +1439,45 @@ function toSpawnArgs(raw: Record<string, unknown>): SpawnArgs {
1262
1439
  };
1263
1440
  }
1264
1441
 
1442
+ async function spawnArgsMutating(args: SpawnArgs): Promise<boolean> {
1443
+ if (args.tools) return isMutatingToolset(args.tools);
1444
+ if (args.agent) {
1445
+ const {resolveRoleSpec} = await import('../agent/roles.js');
1446
+ const tools = resolveRoleSpec(args.agent, 'agent')?.tools;
1447
+ return isMutatingToolset(tools ?? DEFAULT_CHILD_TOOLS);
1448
+ }
1449
+ if (args.category) {
1450
+ const {resolveRoleSpec} = await import('../agent/roles.js');
1451
+ const tools = resolveRoleSpec(args.category, 'category')?.tools;
1452
+ return isMutatingToolset(tools ?? DEFAULT_CHILD_TOOLS);
1453
+ }
1454
+ return isMutatingToolset(DEFAULT_CHILD_TOOLS);
1455
+ }
1456
+
1457
+ /**
1458
+ * Classify a raw `delegate` / `delegate_parallel` tool call as mutating, for
1459
+ * turn-level scheduling in `run.ts`.
1460
+ *
1461
+ * Mirrors `planChild`'s toolset precedence (explicit `tools` > role config >
1462
+ * read-only default) but needs no `ToolConfig`. Never throws: unparseable args
1463
+ * classify as non-mutating because the handler rejects them before spawning.
1464
+ */
1465
+ export async function delegateCallIsMutating(name: string, argsStr: string): Promise<boolean> {
1466
+ try {
1467
+ const raw = JSON.parse(argsStr) as Record<string, unknown>;
1468
+ if (name === 'delegate_parallel') {
1469
+ const tasks = Array.isArray(raw.tasks) ? raw.tasks : [];
1470
+ for (const t of tasks) {
1471
+ if (await spawnArgsMutating(toSpawnArgs(t as Record<string, unknown>))) return true;
1472
+ }
1473
+ return false;
1474
+ }
1475
+ return await spawnArgsMutating(toSpawnArgs(raw));
1476
+ } catch {
1477
+ return false;
1478
+ }
1479
+ }
1480
+
1265
1481
  /**
1266
1482
  * `planChild`, but a throw becomes an error result instead of propagating.
1267
1483
  * Planning performs dynamic imports, so it can fail for reasons unrelated to