@criogaid/pi-hashline-edit 0.5.0 → 0.6.0

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 (66) hide show
  1. package/README.md +66 -22
  2. package/package.json +6 -6
  3. package/src/core/apply.test.ts +66 -16
  4. package/src/core/apply.ts +36 -19
  5. package/src/core/lines.ts +3 -3
  6. package/src/core/text.test.ts +30 -1
  7. package/src/core/text.ts +8 -3
  8. package/src/index.ts +2 -0
  9. package/src/integration/forget-grep.test.ts +98 -0
  10. package/src/integration/fusion-dispatch.test.ts +343 -0
  11. package/src/integration/grep-rg.test.ts +466 -111
  12. package/src/integration/large-text.test.ts +3 -5
  13. package/src/integration/mutation-file-types.test.ts +44 -0
  14. package/src/pi/action-fusion.test.ts +158 -79
  15. package/src/pi/action-fusion.ts +105 -34
  16. package/src/pi/anchor-format.test.ts +46 -0
  17. package/src/pi/anchor-format.ts +21 -2
  18. package/src/pi/argument-validation.test.ts +136 -0
  19. package/src/pi/argument-validation.ts +103 -0
  20. package/src/pi/budgets.ts +4 -1
  21. package/src/pi/config.test.ts +1 -0
  22. package/src/pi/config.ts +4 -0
  23. package/src/pi/diagnostic-buffer.test.ts +58 -0
  24. package/src/pi/diagnostic-buffer.ts +59 -0
  25. package/src/pi/directory-sync.test.ts +1 -1
  26. package/src/pi/edit-tool.ts +56 -37
  27. package/src/pi/execute.test.ts +185 -645
  28. package/src/pi/failure-context.test.ts +4 -3
  29. package/src/pi/failure-path.test.ts +3 -3
  30. package/src/pi/file-commit.test.ts +24 -17
  31. package/src/pi/file-commit.ts +36 -9
  32. package/src/pi/file-snapshot.test.ts +24 -0
  33. package/src/pi/forget-tool.ts +268 -0
  34. package/src/pi/forget.test.ts +343 -0
  35. package/src/pi/forget.testing.ts +273 -0
  36. package/src/pi/fusion-card.test.ts +26 -0
  37. package/src/pi/fusion-card.ts +21 -6
  38. package/src/pi/grep-output.ts +82 -55
  39. package/src/pi/grep-render.ts +8 -11
  40. package/src/pi/grep-scope.ts +6 -31
  41. package/src/pi/grep-search.ts +94 -58
  42. package/src/pi/grep-tool.ts +50 -59
  43. package/src/pi/grep.test.ts +412 -208
  44. package/src/pi/mutation-result.test.ts +23 -0
  45. package/src/pi/mutation-runner.ts +8 -4
  46. package/src/pi/path.ts +16 -2
  47. package/src/pi/pi.test.ts +4 -3
  48. package/src/pi/read-tool.ts +59 -27
  49. package/src/pi/read.test.ts +361 -0
  50. package/src/pi/registration.test.ts +121 -4
  51. package/src/pi/render.test.ts +172 -15
  52. package/src/pi/render.ts +28 -5
  53. package/src/pi/replace-tool.ts +18 -27
  54. package/src/pi/replace.test.ts +8 -107
  55. package/src/pi/result-safety.test.ts +123 -149
  56. package/src/pi/rg-match-bytes.ts +95 -0
  57. package/src/pi/rg-process.test.ts +40 -59
  58. package/src/pi/rg-process.ts +8 -5
  59. package/src/pi/rg-text-view.ts +59 -9
  60. package/src/pi/text-stream.test.ts +153 -0
  61. package/src/pi/text-stream.ts +33 -13
  62. package/src/pi/tool-call.testing.ts +50 -0
  63. package/src/pi/tool-prompts.ts +15 -0
  64. package/src/pi/write-tool.ts +19 -26
  65. package/src/pi/write.test.ts +70 -61
  66. package/src/pi/e2e-scenarios.test.ts +0 -360
@@ -22,13 +22,15 @@
22
22
  import { realpath } from "node:fs/promises";
23
23
  import { basename, dirname, resolve } from "node:path";
24
24
  import type { AgentToolResult, AgentToolUpdateCallback } from "@earendil-works/pi-agent-core";
25
- import { createBashToolDefinition, type ExtensionContext } from "@earendil-works/pi-coding-agent";
25
+ import type { ExtensionToolContext } from "@earendil-works/pi-coding-agent";
26
26
  import { Type, type Static, type TObject, type TProperties } from "typebox";
27
27
  import { fileRevision, FileMutationError, type PublicationStatus } from "./file-commit.ts";
28
28
  import { commitFreshness, finalizeMutation, type MutationOutcome } from "./mutation-result.ts";
29
29
  import { errorMessage } from "../core/errors.ts";
30
30
  import { OPERATION_ABORTED, throwIfCancelled } from "./error-text.ts";
31
31
 
32
+ const MILLISECONDS_PER_SECOND = 1_000;
33
+
32
34
  export const THEN_RUN_SUCCEEDED = "[then_run:succeeded]";
33
35
  export const THEN_RUN_FAILED = "[then_run:failed]";
34
36
  export const THEN_RUN_SKIPPED = "[then_run:skipped]";
@@ -70,11 +72,16 @@ export interface ActionFusionProgress extends Omit<ActionFusionDetails, "command
70
72
  reason?: string;
71
73
  /** True only after mutation execution and result generation both succeed. */
72
74
  mutationCompleted: boolean;
75
+ /** Present once a command with an explicit timeout starts; refreshed during silent execution. */
76
+ timing?: { readonly timeoutSeconds: number; readonly remainingSeconds: number };
73
77
  }
74
78
 
75
- type ProgressReporter = (progress: ActionFusionProgress, ctx: ExtensionContext) => void;
79
+ type ProgressReporter = (progress: ActionFusionProgress, ctx: ExtensionToolContext) => void;
80
+
81
+ /** The tools that accept then_run. */
82
+ export type MutationToolName = "edit" | "replace" | "write";
76
83
 
77
- export function createThenRunSchema(description: string) {
84
+ export function createThenRunSchema(tool: MutationToolName) {
78
85
  return Type.Optional(
79
86
  Type.Object(
80
87
  {
@@ -87,32 +94,43 @@ export function createThenRunSchema(description: string) {
87
94
  }),
88
95
  ),
89
96
  },
90
- { description, additionalProperties: false },
97
+ {
98
+ description: `Command to run once after ${tool} succeeds; failure does not roll back the file.`,
99
+ additionalProperties: false,
100
+ },
91
101
  ),
92
102
  );
93
103
  }
94
104
  /** Add the optional then_run field to a mutation schema when Action Fusion is enabled. */
95
105
  export function withThenRunSchema<P extends TProperties>(
96
106
  schema: TObject<P>,
97
- description: string,
107
+ tool: MutationToolName,
98
108
  actionFusion: boolean,
99
109
  ): TObject<P> | TObject<P & { then_run: ReturnType<typeof createThenRunSchema> }> {
100
110
  return actionFusion
101
111
  ? Type.Object(
102
- { ...schema.properties, then_run: createThenRunSchema(description) },
112
+ { ...schema.properties, then_run: createThenRunSchema(tool) },
103
113
  { additionalProperties: false },
104
114
  )
105
115
  : schema;
106
116
  }
107
117
  export type ThenRunInput = NonNullable<Static<ReturnType<typeof createThenRunSchema>>>;
108
118
 
119
+ /** Keep command state independent of its diagnostic text and of file publication. */
120
+ export interface CommandOutcome {
121
+ readonly status: Exclude<CommandStatus, "not_requested" | "skipped">;
122
+ readonly output: string;
123
+ /** Preserve the session tool's request to stop after this tool batch. */
124
+ readonly terminate?: boolean;
125
+ }
126
+
109
127
  type CommandRunner = (
110
128
  toolCallId: string,
111
129
  input: ThenRunInput,
112
130
  signal: AbortSignal | undefined,
113
- ctx: ExtensionContext,
131
+ ctx: ExtensionToolContext,
114
132
  onUpdate?: AgentToolUpdateCallback<unknown>,
115
- ) => Promise<string>;
133
+ ) => Promise<CommandOutcome>;
116
134
 
117
135
  type MutationResult<TDetails> = AgentToolResult<TDetails>;
118
136
  /** Attach the fused outcome to a finalized mutation result, plus optional command text. */
@@ -200,24 +218,39 @@ export class ActionFusionError extends Error {
200
218
  }
201
219
  }
202
220
 
203
- function commandStatus(error: unknown, signal: AbortSignal | undefined): CommandStatus {
204
- if (signal?.aborted) return "cancelled";
205
- return /timeout|timed out/i.test(errorMessage(error)) ? "timeout" : "failed";
206
- }
207
-
208
221
  async function defaultCommandRunner(
209
- toolCallId: string,
222
+ _toolCallId: string,
210
223
  input: ThenRunInput,
211
224
  signal: AbortSignal | undefined,
212
- ctx: ExtensionContext,
225
+ ctx: ExtensionToolContext,
213
226
  onUpdate?: AgentToolUpdateCallback<unknown>,
214
- ): Promise<string> {
215
- const bash = createBashToolDefinition(ctx.cwd);
216
- const result = await bash.execute(`${toolCallId}:then_run`, input, signal, onUpdate, ctx);
217
- return result.content
227
+ ): Promise<CommandOutcome> {
228
+ // Use the session's callable Bash, including overrides, validation, permission
229
+ // hooks and tool_result hooks. Tool failures resolve with isError, not rejection.
230
+ const { result, isError } = await ctx.executeTool("bash", input, { signal, onUpdate });
231
+ const output = result.content
218
232
  .filter((block) => block.type === "text")
219
233
  .map((block) => block.text)
220
234
  .join("\n");
235
+ const command = { output, terminate: result.terminate };
236
+ if (!isError) return { status: "succeeded", ...command };
237
+ if (signal?.aborted) return { status: "cancelled", ...command };
238
+
239
+ const structured = result.structuredContent;
240
+ const hasExitCode =
241
+ structured !== null &&
242
+ typeof structured === "object" &&
243
+ "exit_code" in structured &&
244
+ typeof structured.exit_code === "number";
245
+ // Pi 0.99.1 supplies exit_code for ordinary exits, but serializes a thrown
246
+ // timeout as text. Only recognize its final diagnostic for the requested
247
+ // timeout; a failed command's output may itself mention or quote a timeout.
248
+ const timeoutDiagnostic = `Command timed out after ${input.timeout} seconds`;
249
+ const timedOut =
250
+ !hasExitCode &&
251
+ input.timeout !== undefined &&
252
+ (output === timeoutDiagnostic || output.endsWith(`\n${timeoutDiagnostic}`));
253
+ return { status: timedOut ? "timeout" : "failed", ...command };
221
254
  }
222
255
 
223
256
  async function canonicalQueueKey(path: string): Promise<string> {
@@ -285,11 +318,13 @@ export function createActionFusionExecutor(
285
318
  thenRun: ThenRunInput | undefined;
286
319
  mutate: () => Promise<MutationOutcome<TDetails>>;
287
320
  signal: AbortSignal | undefined;
288
- ctx: ExtensionContext;
321
+ ctx: ExtensionToolContext;
289
322
  onUpdate?: AgentToolUpdateCallback<TDetails>;
290
323
  }): Promise<MutationResult<TDetails>> {
291
324
  let completedMutation: MutationOutcome<TDetails> | undefined;
325
+ let commandTermination: boolean | undefined;
292
326
  let progressFailure: string | undefined;
327
+ let commandTiming: { readonly timeoutSeconds: number; readonly deadlineMs: number } | undefined;
293
328
  const report = (
294
329
  command: ActionFusionProgress["command"],
295
330
  publication: PublicationStatus,
@@ -308,6 +343,17 @@ export function createActionFusionExecutor(
308
343
  output,
309
344
  ...(reason ? { reason } : {}),
310
345
  mutationCompleted: completedMutation !== undefined,
346
+ ...(commandTiming
347
+ ? {
348
+ timing: {
349
+ timeoutSeconds: commandTiming.timeoutSeconds,
350
+ remainingSeconds: Math.max(
351
+ 0,
352
+ Math.ceil((commandTiming.deadlineMs - Date.now()) / MILLISECONDS_PER_SECOND),
353
+ ),
354
+ },
355
+ }
356
+ : {}),
311
357
  };
312
358
  // Display callbacks are observers: their failures must not change publication or command execution.
313
359
  for (const notify of [
@@ -401,26 +447,49 @@ export function createActionFusionExecutor(
401
447
  }
402
448
 
403
449
  report("running", publication, "unchanged");
404
- let output: string;
450
+ let output = "";
451
+ let command: CommandOutcome;
405
452
  let commandError: unknown;
453
+ // The executor owns the heartbeat lifetime; Pi Bash owns timeout and process cleanup.
454
+ let heartbeat: ReturnType<typeof setInterval> | undefined;
406
455
  try {
407
- output = await commandRunner(toolCallId, thenRun, signal, ctx, (partial) => {
408
- const text = partial.content
456
+ command = await commandRunner(toolCallId, thenRun, signal, ctx, (partial) => {
457
+ // Pi Bash emits an initial update even for silent commands. Start its
458
+ // countdown here, after session permission hooks have allowed execution.
459
+ if (!commandTiming && thenRun.timeout !== undefined) {
460
+ commandTiming = {
461
+ timeoutSeconds: thenRun.timeout,
462
+ deadlineMs: Date.now() + thenRun.timeout * MILLISECONDS_PER_SECOND,
463
+ };
464
+ if (onProgress || onUpdate) {
465
+ heartbeat = setInterval(
466
+ () => report("running", publication, "unknown", output),
467
+ MILLISECONDS_PER_SECOND,
468
+ );
469
+ heartbeat.unref();
470
+ }
471
+ }
472
+ output = partial.content
409
473
  .filter((block) => block.type === "text")
410
474
  .map((block) => block.text)
411
475
  .join("\n");
412
- report("running", publication, "unknown", text);
476
+ report("running", publication, "unknown", output);
413
477
  });
478
+ output = command.output;
414
479
  } catch (error) {
415
480
  commandError = error;
416
- output = "";
481
+ output = errorMessage(error);
482
+ command = { status: signal?.aborted ? "cancelled" : "failed", output };
483
+ } finally {
484
+ if (heartbeat) clearInterval(heartbeat);
417
485
  }
486
+ commandTermination = command.terminate;
418
487
  const freshness = await readFreshness(absolutePath, baseline);
419
- if (commandError !== undefined) {
488
+ if (command.status !== "succeeded") {
420
489
  throw new ActionFusionError(
421
490
  "mutation completed; then_run did not complete successfully",
422
- { publication, command: commandStatus(commandError, signal), freshness },
423
- { cause: commandError, commandOutput: errorMessage(commandError) },
491
+ { publication, command: command.status, freshness },
492
+ { cause: commandError ?? output, commandOutput: output },
424
493
  );
425
494
  }
426
495
 
@@ -481,16 +550,18 @@ export function createActionFusionExecutor(
481
550
  throw error;
482
551
  }
483
552
  })
484
- .then((result) =>
485
- progressFailure
553
+ .then((result) => {
554
+ const finalResult =
555
+ commandTermination === undefined ? result : { ...result, terminate: commandTermination };
556
+ return progressFailure
486
557
  ? {
487
- ...result,
558
+ ...finalResult,
488
559
  content: [
489
- ...result.content,
560
+ ...finalResult.content,
490
561
  { type: "text" as const, text: `Progress reporting failed: ${progressFailure}` },
491
562
  ],
492
563
  }
493
- : result,
494
- );
564
+ : finalResult;
565
+ });
495
566
  };
496
567
  }
@@ -6,6 +6,8 @@ import {
6
6
  createAnchorFormatter,
7
7
  parseAnchorToken,
8
8
  parseHashline,
9
+ parseDisplayRow,
10
+ plainRow,
9
11
  } from "./anchor-format.ts";
10
12
 
11
13
  test("anchor formatter binds the supplied hash length and hashes undisplayed content", () => {
@@ -60,3 +62,47 @@ test("display rows accept supported hash lengths and preserve nested anchor-like
60
62
  assert.equal(parseHashline(row), null);
61
63
  }
62
64
  });
65
+
66
+ test("plain rows expose carriage returns without creating editable anchors", () => {
67
+ assert.equal(plainRow(12, "a\rb│12#ABCD│nested"), "12│a␍b│12#ABCD│nested");
68
+ assert.equal(plainRow(1, ""), "1│");
69
+ assert.equal(parseHashline(plainRow(12, "content")), null);
70
+ assert.equal(parseAnchorToken("12"), undefined);
71
+ });
72
+
73
+ test("display row parsing accepts plain and anchored rows without changing their content", () => {
74
+ for (const hashLen of [2, 4, 6, 8]) {
75
+ const anchored = createAnchorFormatter(hashLen).row(12, " nested 7#ABCD│content");
76
+ assert.deepEqual(parseDisplayRow(anchored), {
77
+ lineNo: "12",
78
+ content: " nested 7#ABCD│content",
79
+ });
80
+ assert.deepEqual(parseDisplayRow(anchored), parseHashline(anchored));
81
+ }
82
+ assert.deepEqual(parseDisplayRow("123│ �│7#ABCD│nested"), {
83
+ lineNo: "123",
84
+ content: " �│7#ABCD│nested",
85
+ });
86
+ assert.deepEqual(parseDisplayRow(plainRow(9, "a\rb")), { lineNo: "9", content: "a␍b" });
87
+ assert.deepEqual(parseDisplayRow("1│"), { lineNo: "1", content: "" });
88
+ });
89
+
90
+ test("display row parsing rejects headers, notices, and invalid line references", () => {
91
+ for (const row of [
92
+ "",
93
+ "file.txt · 2 matches",
94
+ "[Invalid UTF-8: plain preview]",
95
+ "No matches found",
96
+ "0│text",
97
+ "01│text",
98
+ "-1│text",
99
+ " 1│text",
100
+ "1:text",
101
+ "0#ABCD│text",
102
+ "01#ABCD│text",
103
+ "1#A│text",
104
+ "1#IIII│text",
105
+ ]) {
106
+ assert.equal(parseDisplayRow(row), null, row);
107
+ }
108
+ });
@@ -9,8 +9,12 @@ export function anchorPattern(hashLen: number): string {
9
9
  return `^${anchorSource(`{${hashLen}}`)}$`;
10
10
  }
11
11
 
12
+ /** Separates a row's line reference from its displayed content. */
13
+ const ROW_SEPARATOR = "│";
12
14
  const ANCHOR_TOKEN = new RegExp(`^${anchorSource("+")}$`);
13
- const HASHLINE_ROW = new RegExp(`^${anchorSource(`{${HASH_LEN_MIN},${HASH_LEN_MAX}}`)}│(.*)$`);
15
+ const HASHLINE_ROW = new RegExp(
16
+ `^${anchorSource(`{${HASH_LEN_MIN},${HASH_LEN_MAX}}`)}${ROW_SEPARATOR}(.*)$`,
17
+ );
14
18
 
15
19
  /** Split a `LINE#HASH` token of any hash length; undefined when the shape is wrong. */
16
20
  export function parseAnchorToken(value: string): { line: number; hash: string } | undefined {
@@ -31,6 +35,16 @@ export function parseHashline(line: string): HashlineRow | null {
31
35
  return match ? { lineNo: match[1], content: match[3] } : null;
32
36
  }
33
37
 
38
+ const PLAIN_ROW = new RegExp(`^([1-9][0-9]*)${ROW_SEPARATOR}(.*)$`);
39
+
40
+ /** Parse an anchored row or a non-editable `LINE│content` row; null for other text. */
41
+ export function parseDisplayRow(line: string): HashlineRow | null {
42
+ const anchored = parseHashline(line);
43
+ if (anchored) return anchored;
44
+ const match = PLAIN_ROW.exec(line);
45
+ return match ? { lineNo: match[1], content: match[2] } : null;
46
+ }
47
+
34
48
  /** Anchor serialization bound to a caller-supplied hash length. */
35
49
  export interface AnchorFormatter {
36
50
  reference(line: number, hash: string): string;
@@ -43,6 +57,11 @@ export function displayCarriageReturns(text: string): string {
43
57
  return text.replace(/\r/g, "␍");
44
58
  }
45
59
 
60
+ /** Non-editable `LINE│content` row for text that cannot carry an anchor. */
61
+ export function plainRow(line: number, displayContent: string): string {
62
+ return `${line}${ROW_SEPARATOR}${displayCarriageReturns(displayContent)}`;
63
+ }
64
+
46
65
  export function createAnchorFormatter(hashLen: number): AnchorFormatter {
47
66
  const reference = (line: number, hash: string) => `${line}#${hash}`;
48
67
  const token = (line: number, content: string) =>
@@ -51,6 +70,6 @@ export function createAnchorFormatter(hashLen: number): AnchorFormatter {
51
70
  token,
52
71
  reference,
53
72
  row: (line, content, displayContent = content) =>
54
- `${token(line, content)}│${displayCarriageReturns(displayContent)}`,
73
+ `${token(line, content)}${ROW_SEPARATOR}${displayCarriageReturns(displayContent)}`,
55
74
  };
56
75
  }
@@ -0,0 +1,136 @@
1
+ import assert from "node:assert/strict";
2
+ import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
3
+ import { tmpdir } from "node:os";
4
+ import { join } from "node:path";
5
+ import { test } from "node:test";
6
+ import { createActionFusionExecutor } from "./action-fusion.ts";
7
+ import { DEFAULT_CONFIG } from "./config.ts";
8
+ import { makeEditOverride } from "./edit-tool.ts";
9
+ import { makeGrepOverride } from "./grep-tool.ts";
10
+ import { makeReadOverride } from "./read-tool.ts";
11
+ import { makeReplaceTool } from "./replace-tool.ts";
12
+ import { makeWriteOverride } from "./write-tool.ts";
13
+ import { callTool } from "./tool-call.testing.ts";
14
+ import { MAX_BLOCK_BYTES } from "./budgets.ts";
15
+ import { POSITIVE_SAFE_INTEGER } from "./schema.ts";
16
+
17
+ const invalidCommand = { command: "", timeout: 0 };
18
+ const anchorHash = "A".repeat(DEFAULT_CONFIG.hashLen);
19
+ const cases = [
20
+ {
21
+ name: "read",
22
+ make: (cwd: string, _fusion: ReturnType<typeof createActionFusionExecutor>) =>
23
+ makeReadOverride(cwd, DEFAULT_CONFIG),
24
+ args: { offset: -1, limit: 0 },
25
+ diagnostics: [
26
+ new RegExp(`\\n - offset:.*>= ${POSITIVE_SAFE_INTEGER.minimum}`),
27
+ new RegExp(`\\n - limit:.*>= ${POSITIVE_SAFE_INTEGER.minimum}`),
28
+ ],
29
+ },
30
+ {
31
+ name: "grep",
32
+ make: (cwd: string, _fusion: ReturnType<typeof createActionFusionExecutor>) =>
33
+ makeGrepOverride(cwd, DEFAULT_CONFIG),
34
+ args: { pattern: [], literal: true, limit: 0, context: -1 },
35
+ diagnostics: [/\n - pattern:/, /\n - limit:/, /\n - context:/],
36
+ },
37
+ {
38
+ name: "edit",
39
+ make: (cwd: string, fusion: ReturnType<typeof createActionFusionExecutor>) =>
40
+ makeEditOverride(cwd, DEFAULT_CONFIG, fusion),
41
+ args: {
42
+ edits: [
43
+ { op: "replace", anchor: `1#${anchorHash}`, body: [] },
44
+ { op: "append", body: ["bad\0", "bad\ud800"] },
45
+ { op: "delete", anchor: `${Number.MAX_SAFE_INTEGER + 1}#${anchorHash}`, end: "1#A" },
46
+ { op: "append", body: [] },
47
+ ],
48
+ then_run: invalidCommand,
49
+ },
50
+ diagnostics: [
51
+ /Invalid argument edits\[0\]\.body:.*delete/,
52
+ /Invalid argument edits\[1\]\.body\[0\]: UNSUPPORTED_TEXT:/,
53
+ /Invalid argument edits\[1\]\.body\[1\]: INVALID_UNICODE:/,
54
+ /Invalid argument edits\[2\]\.anchor:.*safe integer/,
55
+ /Invalid argument edits\[2\]\.end:.*hash/,
56
+ /Invalid argument edits\[3\]\.body:.*empty/,
57
+ /\n - then_run.command:/,
58
+ /\n - then_run.timeout:/,
59
+ ],
60
+ },
61
+ {
62
+ name: "replace",
63
+ make: (cwd: string, fusion: ReturnType<typeof createActionFusionExecutor>) =>
64
+ makeReplaceTool(cwd, DEFAULT_CONFIG, fusion),
65
+ args: {
66
+ replacements: [
67
+ { find: "(", replace: "bad\0", regex: true },
68
+ { find: "[", replace: "bad\ud800", regex: true },
69
+ ],
70
+ then_run: invalidCommand,
71
+ },
72
+ diagnostics: [
73
+ /Invalid argument replacements\[0\]\.replace: UNSUPPORTED_TEXT:/,
74
+ /Invalid argument replacements\[0\]\.find: invalid regex/,
75
+ /Invalid argument replacements\[1\]\.replace: INVALID_UNICODE:/,
76
+ /Invalid argument replacements\[1\]\.find: invalid regex/,
77
+ /\n - then_run.command:/,
78
+ /\n - then_run.timeout:/,
79
+ ],
80
+ },
81
+ {
82
+ name: "write",
83
+ make: (cwd: string, fusion: ReturnType<typeof createActionFusionExecutor>) =>
84
+ makeWriteOverride(cwd, fusion),
85
+ args: { content: "bad\0", mode: "invalid", then_run: invalidCommand },
86
+ diagnostics: [
87
+ /Invalid argument content: UNSUPPORTED_TEXT:/,
88
+ /\n - mode:/,
89
+ /\n - then_run.command:/,
90
+ /\n - then_run.timeout:/,
91
+ ],
92
+ },
93
+ ] as const;
94
+
95
+ for (const scenario of cases) {
96
+ test(`${scenario.name} receives independent argument errors → reports them together without effects`, async (t) => {
97
+ const cwd = await mkdtemp(join(tmpdir(), "hashline-arguments-"));
98
+ t.after(() => rm(cwd, { recursive: true, force: true }));
99
+ const path = join(cwd, "target.txt");
100
+ const original = "original\n";
101
+ await writeFile(path, original);
102
+ let commandRuns = 0;
103
+ const fusion = createActionFusionExecutor(async () => {
104
+ commandRuns++;
105
+ return { status: "succeeded", output: "ran" };
106
+ });
107
+ const tool = scenario.make(cwd, fusion);
108
+ // These values round-trip through JSON exactly as model tool arguments do.
109
+ const args: unknown = JSON.parse(JSON.stringify({ path, ...scenario.args, unexpected: true }));
110
+ await assert.rejects(callTool(tool, args), (error: Error) => {
111
+ for (const diagnostic of [...scenario.diagnostics, /\n - unexpected:/]) {
112
+ assert.match(error.message, diagnostic);
113
+ }
114
+ assert.doesNotMatch(error.message, /\n - path:/);
115
+ assert.doesNotMatch(error.message, /Received arguments:\n/);
116
+ const echoedArgs = [...error.message.matchAll(/^Received arguments: (.+)$/gm)].map((match) =>
117
+ JSON.parse(match[1]),
118
+ );
119
+ assert.deepEqual(echoedArgs.at(-1), { unexpected: true });
120
+ return true;
121
+ });
122
+ assert.equal(await readFile(path, "utf8"), original);
123
+ assert.equal(commandRuns, 0);
124
+ });
125
+ }
126
+
127
+ test("argument diagnostics exceed the shared budget → rejection labels omitted text", async () => {
128
+ const tool = makeEditOverride(process.cwd(), DEFAULT_CONFIG);
129
+ const edits = Array.from({ length: MAX_BLOCK_BYTES }, () => ({ op: "append", body: [] }));
130
+ await assert.rejects(callTool(tool, { path: "", edits }), (error: Error) => {
131
+ assert.ok(Buffer.byteLength(error.message) <= MAX_BLOCK_BYTES);
132
+ assert.match(error.message, /Invalid argument edits\[0\]\.body:/);
133
+ assert.match(error.message, /Diagnostics truncated/);
134
+ return true;
135
+ });
136
+ });
@@ -0,0 +1,103 @@
1
+ /**
2
+ * Shared argument preparation for every tool. Tool checks only report independent
3
+ * field issues; this boundary combines them with Pi's schema diagnostics and throws
4
+ * once. Pi still validates returned arguments in its mandatory tool-call pipeline.
5
+ * Failure diagnostics validate independent top-level fields separately so an invalid
6
+ * union in one field cannot exhaust Pi's error budget for another. Tool schemas have
7
+ * no cross-field constraints. Arguments and TypeBox's process-wide settings are not changed.
8
+ */
9
+ import { validateToolArguments, type ToolCall } from "@earendil-works/pi-ai";
10
+ import { Type, type Static, type TObject, type TSchema } from "typebox";
11
+ import { ObjectOptions } from "typebox/type";
12
+ import { errorMessage } from "../core/errors.ts";
13
+ import { MAX_BLOCK_BYTES } from "./budgets.ts";
14
+ import { DiagnosticBuffer } from "./diagnostic-buffer.ts";
15
+ import { invalidArgument } from "./error-text.ts";
16
+
17
+ export type ReportArgumentIssue = (field: string, reason: string) => void;
18
+ type CheckArguments = (args: unknown, report: ReportArgumentIssue) => void;
19
+
20
+ /** Inspect arrays and the singleton objects Pi may coerce, without changing input. */
21
+ export function argumentItems(value: unknown): readonly unknown[] {
22
+ return Array.isArray(value) ? value : value !== null && typeof value === "object" ? [value] : [];
23
+ }
24
+
25
+ /**
26
+ * Compact the exact argument suffix emitted by Pi 0.99.1's validateToolArguments.
27
+ * If Pi changes that format, preserve its full error unchanged, including multiline JSON.
28
+ */
29
+ function schemaDiagnostic(error: unknown, args: unknown): string {
30
+ const message = errorMessage(error);
31
+ const label = "Received arguments:";
32
+ const suffix = `\n\n${label}\n${JSON.stringify(args, null, 2)}`;
33
+ if (!message.endsWith(suffix)) return message;
34
+ return `${message.slice(0, -suffix.length)}\n${label} ${JSON.stringify(args)}`;
35
+ }
36
+
37
+ export function createArgumentPreparer<T extends TObject>(
38
+ name: string,
39
+ parameters: T,
40
+ check?: CheckArguments,
41
+ ): (args: unknown) => Static<T> {
42
+ const fields = Object.keys(parameters.properties);
43
+ const options = { additionalProperties: ObjectOptions(parameters).additionalProperties };
44
+ const fieldSchemas = fields.map((field) => ({
45
+ field,
46
+ schema: Type.Pick(parameters, [field], options),
47
+ }));
48
+ const unknownFieldsSchema = Type.Omit(parameters, fields, options);
49
+ const validate = (schema: TSchema, args: unknown): unknown =>
50
+ validateToolArguments(
51
+ { name, parameters: schema, description: "" },
52
+ // Pi owns shape checking and coercion at this external boundary.
53
+ {
54
+ type: "toolCall",
55
+ id: "argument-validation",
56
+ name,
57
+ arguments: args as ToolCall["arguments"],
58
+ },
59
+ );
60
+
61
+ return (args) => {
62
+ let checked: unknown = args;
63
+ let schemaFailure: unknown;
64
+ try {
65
+ checked = validate(parameters, args);
66
+ } catch (error) {
67
+ schemaFailure = error;
68
+ }
69
+ const diagnostics = new DiagnosticBuffer(MAX_BLOCK_BYTES);
70
+ let hasIssues = schemaFailure !== undefined;
71
+ check?.(checked, (field, reason) => {
72
+ hasIssues = true;
73
+ diagnostics.append(`${invalidArgument(field, reason).message}\n`);
74
+ });
75
+ if (schemaFailure !== undefined) {
76
+ if (typeof args === "object" && args !== null && !Array.isArray(args)) {
77
+ const entries = Object.entries(args);
78
+ const diagnose = (schema: TSchema, value: unknown) => {
79
+ try {
80
+ validate(schema, value);
81
+ } catch (error) {
82
+ diagnostics.append(`${schemaDiagnostic(error, value)}\n`);
83
+ }
84
+ };
85
+ for (const { field, schema } of fieldSchemas) {
86
+ diagnose(schema, Object.fromEntries(entries.filter(([key]) => key === field)));
87
+ }
88
+ diagnose(
89
+ unknownFieldsSchema,
90
+ Object.fromEntries(entries.filter(([key]) => !fields.includes(key))),
91
+ );
92
+ } else {
93
+ diagnostics.append(schemaDiagnostic(schemaFailure, args));
94
+ }
95
+ diagnostics.append(
96
+ "\nPi limits schema diagnostics within each field; additional errors may remain.\n",
97
+ );
98
+ }
99
+ if (hasIssues) throw new Error(diagnostics.toString().trimEnd(), { cause: schemaFailure });
100
+ // Keep Pi's preparation contract: the framework performs its own coercion next.
101
+ return args as Static<T>;
102
+ };
103
+ }
package/src/pi/budgets.ts CHANGED
@@ -12,7 +12,7 @@
12
12
  /** grep line preview, in UTF-16 units, excluding its partial-line label. */
13
13
  export const GREP_MAX_LINE_LENGTH = 500;
14
14
 
15
- /** Each diagnostic or anchor block: failure details, input-anchor checks, candidate neighborhoods, mutation anchors. */
15
+ /** Each diagnostic or anchor block: argument errors, failure details, input-anchor checks, candidate neighborhoods, mutation anchors. */
16
16
  export const MAX_BLOCK_BYTES = 16 * 1024;
17
17
  /** One recovery-candidate or cited row inside a failure diagnostic. */
18
18
  export const MAX_RECOVERY_CANDIDATE_BYTES = 4 * 1024;
@@ -23,3 +23,6 @@ export const MAX_SEARCH_DIAGNOSTIC_BYTES = 4 * 1024;
23
23
  export function formatKiB(bytes: number): string {
24
24
  return `${bytes / 1024} KiB`;
25
25
  }
26
+
27
+ /** Smallest read or grep text result tagged for forget; smaller ones save too little to be worth forgetting. */
28
+ export const FORGET_MIN_BYTES = 2 * 1024;
@@ -32,6 +32,7 @@ test("defaults come from the settings schema", () => {
32
32
  assert.deepEqual(DEFAULT_CONFIG, {
33
33
  enabled: true,
34
34
  actionFusion: true,
35
+ forget: false,
35
36
  hashLen: 4,
36
37
  shiftRadius: 15,
37
38
  read: { defaultLimit: 500, maxKiB: 256 },
package/src/pi/config.ts CHANGED
@@ -33,6 +33,10 @@ export const configSchema = Type.Object({
33
33
  default: true,
34
34
  description: "Expose optional then_run commands after edit/replace/write.",
35
35
  }),
36
+ forget: Type.Boolean({
37
+ default: false,
38
+ description: "Register forget and tag eligible read/grep results for context removal.",
39
+ }),
36
40
  hashLen: integerSetting(
37
41
  integerRange(HASH_LEN_MIN, HASH_LEN_MAX),
38
42
  4,