@criogaid/pi-hashline-edit 0.13.0 → 0.15.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 (152) hide show
  1. package/README.md +18 -12
  2. package/README.zh-CN.md +18 -12
  3. package/package.json +8 -1
  4. package/src/core/AGENTS.md +3 -1
  5. package/src/core/apply.ts +110 -117
  6. package/src/core/character-set.ts +2 -3
  7. package/src/core/copy-span.ts +15 -0
  8. package/src/core/errors.ts +24 -9
  9. package/src/core/lines.ts +71 -17
  10. package/src/core/ranges.ts +5 -4
  11. package/src/core/replace-schema.ts +3 -1
  12. package/src/core/replace.ts +50 -29
  13. package/src/core/search-analysis.ts +21 -22
  14. package/src/core/search.ts +15 -32
  15. package/src/core/types.ts +3 -0
  16. package/src/index.ts +47 -39
  17. package/src/pi/AGENTS.md +30 -19
  18. package/src/pi/action-fusion.ts +284 -211
  19. package/src/pi/argument-diagnostics.ts +50 -37
  20. package/src/pi/argument-error.ts +2 -2
  21. package/src/pi/argument-validation.ts +163 -66
  22. package/src/pi/budgets.ts +12 -0
  23. package/src/pi/diagnostic-buffer.ts +12 -11
  24. package/src/pi/edit-tool.ts +138 -115
  25. package/src/pi/error-text.ts +10 -2
  26. package/src/pi/failure-context.ts +24 -37
  27. package/src/pi/file-commit.ts +131 -164
  28. package/src/pi/file-read.ts +122 -31
  29. package/src/pi/fusion-arguments.ts +214 -0
  30. package/src/pi/fusion-card.ts +102 -60
  31. package/src/pi/grep-candidates.ts +35 -22
  32. package/src/pi/grep-output.ts +197 -190
  33. package/src/pi/grep-render.ts +22 -13
  34. package/src/pi/grep-reread.ts +7 -6
  35. package/src/pi/grep-scope.ts +31 -16
  36. package/src/pi/grep-search.ts +56 -47
  37. package/src/pi/grep-tool.ts +35 -33
  38. package/src/pi/grep-worker.ts +3 -4
  39. package/src/pi/mutation-diff.ts +238 -0
  40. package/src/pi/mutation-result.ts +102 -79
  41. package/src/pi/mutation-runner.ts +107 -84
  42. package/src/pi/native-bash.ts +41 -0
  43. package/src/pi/path.ts +59 -6
  44. package/src/pi/read-tool.ts +173 -138
  45. package/src/pi/regex-worker.ts +14 -8
  46. package/src/pi/render.ts +101 -54
  47. package/src/pi/replace-regex.ts +1 -1
  48. package/src/pi/replace-tool.ts +14 -7
  49. package/src/pi/report-cause.ts +34 -17
  50. package/src/pi/report-schema.ts +184 -85
  51. package/src/pi/report.ts +133 -64
  52. package/src/pi/rg-process.ts +68 -48
  53. package/src/pi/schema.ts +4 -0
  54. package/src/pi/text-stream.ts +81 -87
  55. package/src/pi/workspace-cwd.js +2 -0
  56. package/src/pi/workspace.ts +46 -0
  57. package/src/pi/write-tool.ts +19 -13
  58. package/src/core/apply.test.ts +0 -644
  59. package/src/core/case-fold.test.ts +0 -35
  60. package/src/core/character-set.test.ts +0 -97
  61. package/src/core/errors.test.ts +0 -39
  62. package/src/core/hash.test.ts +0 -64
  63. package/src/core/lines.test.ts +0 -63
  64. package/src/core/ranges.test.ts +0 -123
  65. package/src/core/replace.test.ts +0 -187
  66. package/src/core/search-analysis.test.ts +0 -210
  67. package/src/core/search-matrix.test.ts +0 -64
  68. package/src/core/search-matrix.testing.ts +0 -171
  69. package/src/core/search.test.ts +0 -132
  70. package/src/core/text.test.ts +0 -52
  71. package/src/integration/config-registration.test.ts +0 -291
  72. package/src/integration/fusion-dispatch.test.ts +0 -320
  73. package/src/integration/grep-errors.test.ts +0 -81
  74. package/src/integration/grep-flags.test.ts +0 -76
  75. package/src/integration/grep-js-completeness.test.ts +0 -278
  76. package/src/integration/grep-line-candidates.test.ts +0 -201
  77. package/src/integration/grep-matrix.test.ts +0 -118
  78. package/src/integration/grep-order.test.ts +0 -78
  79. package/src/integration/grep-path-matrix.test.ts +0 -128
  80. package/src/integration/grep-prefilter-coverage.test.ts +0 -204
  81. package/src/integration/grep-process-limits.test.ts +0 -122
  82. package/src/integration/grep-regex.test.ts +0 -412
  83. package/src/integration/grep-rg.test.ts +0 -1659
  84. package/src/integration/grep-scan-budget.test.ts +0 -111
  85. package/src/integration/grep-translation.test.ts +0 -199
  86. package/src/integration/large-text.test.ts +0 -70
  87. package/src/integration/model-budget-lifecycle.test.ts +0 -186
  88. package/src/integration/mutation-file-types.test.ts +0 -30
  89. package/src/integration/mutation-file-types.testing.ts +0 -33
  90. package/src/integration/npm-package.test.ts +0 -19
  91. package/src/integration/npm-package.testing.ts +0 -243
  92. package/src/integration/publication-read-changes.test.ts +0 -454
  93. package/src/integration/read-changes.test.ts +0 -98
  94. package/src/integration/replace-package.test.ts +0 -22
  95. package/src/integration/replace-package.testing.ts +0 -36
  96. package/src/integration/replace-worker-boundary.test.ts +0 -127
  97. package/src/integration/report-replay.test.ts +0 -91
  98. package/src/integration/utf8-errors.test.ts +0 -46
  99. package/src/pi/action-fusion.test.ts +0 -659
  100. package/src/pi/action-fusion.testing.ts +0 -38
  101. package/src/pi/anchor-format.test.ts +0 -124
  102. package/src/pi/argument-error.testing.ts +0 -46
  103. package/src/pi/argument-format.test.ts +0 -196
  104. package/src/pi/argument-validation.test.ts +0 -1007
  105. package/src/pi/codemode.test.ts +0 -101
  106. package/src/pi/config.test.ts +0 -204
  107. package/src/pi/diagnostic-buffer.test.ts +0 -115
  108. package/src/pi/directory-sync.test.ts +0 -57
  109. package/src/pi/execute.test.ts +0 -1257
  110. package/src/pi/extension-loading.test.ts +0 -14
  111. package/src/pi/extension-loading.testing.ts +0 -3
  112. package/src/pi/failure-context.test.ts +0 -370
  113. package/src/pi/failure-path.test.ts +0 -289
  114. package/src/pi/file-commit.test.ts +0 -628
  115. package/src/pi/file-read.test.ts +0 -29
  116. package/src/pi/file-snapshot.test.ts +0 -22
  117. package/src/pi/fusion-card-interaction.test.ts +0 -143
  118. package/src/pi/fusion-card.test.ts +0 -353
  119. package/src/pi/grep-candidates.test.ts +0 -26
  120. package/src/pi/grep-matrix.test.ts +0 -68
  121. package/src/pi/grep-order.test.ts +0 -447
  122. package/src/pi/grep-output.testing.ts +0 -24
  123. package/src/pi/grep-rg.testing.ts +0 -73
  124. package/src/pi/grep.test.ts +0 -1670
  125. package/src/pi/model-budgets.test.ts +0 -96
  126. package/src/pi/mutation-outcome.testing.ts +0 -20
  127. package/src/pi/mutation-result.test.ts +0 -96
  128. package/src/pi/output-budgets.test.ts +0 -221
  129. package/src/pi/pi.test.ts +0 -158
  130. package/src/pi/read-delegation.test.ts +0 -119
  131. package/src/pi/read.test.ts +0 -735
  132. package/src/pi/regex-worker.test.ts +0 -42
  133. package/src/pi/registration.test.ts +0 -549
  134. package/src/pi/render.test.ts +0 -841
  135. package/src/pi/replace.test.ts +0 -634
  136. package/src/pi/report-failure.testing.ts +0 -27
  137. package/src/pi/report.test.ts +0 -533
  138. package/src/pi/result-safety.test.ts +0 -597
  139. package/src/pi/rg-process.test.ts +0 -133
  140. package/src/pi/rg-regex.test.ts +0 -40
  141. package/src/pi/text-stream.test.ts +0 -281
  142. package/src/pi/tool-call.testing.ts +0 -61
  143. package/src/pi/tool-factories.testing.ts +0 -59
  144. package/src/pi/write.test.ts +0 -256
  145. package/src/testing/extension-loader.testing.ts +0 -24
  146. package/src/testing/installation.testing.ts +0 -77
  147. package/src/testing/process.testing.ts +0 -33
  148. package/src/testing/regex-host.testing.ts +0 -20
  149. package/src/testing/regex-translation-corpus.ts +0 -267
  150. package/src/testing/rg-line-listing.fixture.mjs +0 -7
  151. package/src/testing/run-tests.ts +0 -47
  152. package/src/testing/session.testing.ts +0 -127
@@ -1,4 +1,5 @@
1
1
  /** Failure-only schema projection and structured error aggregation; Pi owns input preparation and acceptance. */
2
+ import type { ValidationError } from "@earendil-works/pi-schema";
2
3
  import {
3
4
  ArrayOptions,
4
5
  IsArray,
@@ -95,7 +96,7 @@ function projectValueSchema(
95
96
  return schema;
96
97
  }
97
98
 
98
- function propertyPath(path: string, key: string): string {
99
+ export function propertyPath(path: string, key: string): string {
99
100
  return /^[A-Za-z_][A-Za-z_0-9]*$/.test(key)
100
101
  ? path
101
102
  ? `${path}.${key}`
@@ -118,6 +119,14 @@ function valuePath(parts: readonly string[], prepared: unknown): string {
118
119
  return path;
119
120
  }
120
121
 
122
+ /** Pi escapes JSON Pointer keys. TypeBox passes additional keys verbatim in its own diagnostics. */
123
+ export function nativeArgumentIssue(error: ValidationError, prepared: unknown): ArgumentIssue {
124
+ const parts = pointerParts(error.path).map((key) =>
125
+ key.replaceAll("~1", "/").replaceAll("~0", "~"),
126
+ );
127
+ return { field: valuePath(parts, prepared) || "$", reason: error.message };
128
+ }
129
+
121
130
  /** One declaration's meaning: its description, labeled with its values when it is a choice. */
122
131
  function explainDeclaration(schema: TSchema): string | undefined {
123
132
  const description: unknown = Reflect.get(schema, "description");
@@ -179,31 +188,21 @@ function aggregateErrors(
179
188
  prepared: unknown,
180
189
  objects: ReadonlyMap<string, TObject>,
181
190
  ): readonly ArgumentIssue[] {
182
- const issues: ArgumentIssue[] = [];
183
- const add = (field: string, reason: string, fix?: string) =>
184
- issues.push(fix === undefined ? { field, reason } : { field, reason, fix });
185
- for (const error of errors) {
191
+ const issues = errors.flatMap((error): ArgumentIssue[] => {
186
192
  const parts = pointerParts(error.instancePath);
187
193
  switch (error.keyword) {
188
194
  case "required": {
189
- for (const key of error.params.requiredProperties)
190
- add(
191
- propertyPath(valuePath(parts, prepared), key),
195
+ const parent = valuePath(parts, prepared);
196
+ return error.params.requiredProperties.map((key) =>
197
+ argumentIssue(
198
+ propertyPath(parent, key),
192
199
  "is required",
193
200
  fieldExplanation(parameters, [...parts, key]),
194
- );
195
- break;
196
- }
197
- case "additionalProperties": {
198
- const path = valuePath(parts, prepared);
199
- const fix = shapeExplanation(objects.get(path));
200
- for (const key of error.params.additionalProperties)
201
- add(propertyPath(path, key), "is not allowed", fix);
202
- break;
201
+ ),
202
+ );
203
203
  }
204
- case "pattern":
205
- add(valuePath(parts, prepared) || "$", error.message, fieldExplanation(parameters, parts));
206
- break;
204
+ case "additionalProperties":
205
+ return undeclaredIssues(valuePath(parts, prepared), error.params.additionalProperties);
207
206
  case "boolean": {
208
207
  // TypeBox emits a false-schema error per unknown key before its grouped error.
209
208
  // Count declared path steps to preserve the entire unknown key, even if it contains '/'.
@@ -213,26 +212,38 @@ function aggregateErrors(
213
212
  (segment) =>
214
213
  segment === "properties" || segment === "items" || segment === "prefixItems",
215
214
  ).length;
216
- const parent = valuePath(parts.slice(0, depth), prepared);
217
- add(
218
- propertyPath(parent, parts.slice(depth).join("/")),
219
- "is not allowed",
220
- shapeExplanation(objects.get(parent)),
221
- );
222
- break;
215
+ return undeclaredIssues(valuePath(parts.slice(0, depth), prepared), [
216
+ parts.slice(depth).join("/"),
217
+ ]);
218
+ }
219
+ case "pattern":
220
+ case "enum": {
221
+ const reason =
222
+ error.keyword === "enum"
223
+ ? `expected one of: ${error.params.allowedValues.map((value) => JSON.stringify(value)).join(", ")}`
224
+ : error.message;
225
+ return [
226
+ argumentIssue(
227
+ valuePath(parts, prepared) || "$",
228
+ reason,
229
+ fieldExplanation(parameters, parts),
230
+ ),
231
+ ];
223
232
  }
224
- case "enum":
225
- add(
226
- valuePath(parts, prepared) || "$",
227
- `expected one of: ${error.params.allowedValues.map((value) => JSON.stringify(value)).join(", ")}`,
228
- fieldExplanation(parameters, parts),
229
- );
230
- break;
231
233
  default:
232
- add(valuePath(parts, prepared) || "$", error.message);
234
+ return [{ field: valuePath(parts, prepared) || "$", reason: error.message }];
233
235
  }
234
- }
236
+ });
235
237
  return combineIssues(issues);
238
+
239
+ function undeclaredIssues(parent: string, keys: readonly string[]): ArgumentIssue[] {
240
+ const fix = shapeExplanation(objects.get(parent));
241
+ return keys.map((key) => argumentIssue(propertyPath(parent, key), "is not allowed", fix));
242
+ }
243
+
244
+ function argumentIssue(field: string, reason: string, fix: string | undefined): ArgumentIssue {
245
+ return fix === undefined ? { field, reason } : { field, reason, fix };
246
+ }
236
247
  }
237
248
 
238
249
  /** Detect native capacity through a terminal error, without importing unbundled TypeBox settings. */
@@ -257,6 +268,9 @@ export function diagnoseArguments(
257
268
  semanticIssues: readonly ArgumentIssue[],
258
269
  schemaFailed: boolean,
259
270
  ): ArgumentDiagnostics {
271
+ // On schema success every path reported by a tool check is applicable.
272
+ if (!schemaFailed) return { issues: combineIssues(semanticIssues), limited: false };
273
+
260
274
  const projection: Projection = {
261
275
  explained: new Set(semanticIssues.map((issue) => issue.field)),
262
276
  applicable: new Set<string>(),
@@ -266,7 +280,6 @@ export function diagnoseArguments(
266
280
  const retained = combineIssues(
267
281
  semanticIssues.filter((issue) => projection.applicable.has(issue.field)),
268
282
  );
269
- if (!schemaFailed) return { issues: retained, limited: false };
270
283
  const batches =
271
284
  IsObject(projected) &&
272
285
  typeof prepared === "object" &&
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * Model-facing argument rejection: an `INVALID_ARGUMENTS` report (report.ts)
3
- * with field issues within one byte budget. Pi raises it before execution,
4
- * so it travels as the thrown message only. Oversized issues are omitted whole.
3
+ * with field issues within one byte budget. The argument boundary throws this report
4
+ * before file access. Pi carries the rejection as text. Oversized issues are omitted whole.
5
5
  */
6
6
  import type { OutputBudgets } from "./budgets.ts";
7
7
  import { renderReport, type ReportText } from "./report.ts";
@@ -1,24 +1,26 @@
1
1
  /**
2
- * Shared tool argument boundary. Pi owns preparation and acceptance; tool checks
3
- * report semantic issues. Failure-only diagnostics use pi-schema's public coercer,
4
- * then project and aggregate the declared schema in argument-diagnostics.ts.
5
- * Pi still validates returned arguments in its mandatory tool-call pipeline.
2
+ * Shared tool argument boundary. Prepare with Pi's schema engine so semantic
3
+ * checks and bounded diagnostics see the same coerced value, including on
4
+ * schema failure. Pi coerces and validates the same observed snapshot.
6
5
  * Tool schemas have no cross-field constraints.
7
6
  */
8
- import { validateToolArguments, type ToolCall } from "@earendil-works/pi-ai";
7
+ import { resolve } from "node:path";
9
8
  import { compile } from "@earendil-works/pi-schema";
10
9
  import { formats } from "@earendil-works/pi-schema/formats";
11
- import type { Static, TObject } from "typebox";
10
+ import { IsArray, IsObject, type Static, type TObject, type TSchema } from "typebox";
12
11
  import { errorMessage } from "../core/errors.ts";
13
12
  import { buildRegex } from "../core/regex.ts";
14
- import { diagnoseArguments } from "./argument-diagnostics.ts";
13
+ import { diagnoseArguments, nativeArgumentIssue, propertyPath } from "./argument-diagnostics.ts";
15
14
  import { formatArgumentError } from "./argument-error.ts";
16
15
  import type { OutputBudgetProvider } from "./budgets.ts";
17
- import type { ArgumentIssue, ReportTool } from "./report-schema.ts";
16
+ import { parseArgumentPath, type ResolvedArgumentPath } from "./path.ts";
17
+ import type { ArgumentIssue } from "./report-schema.ts";
18
18
 
19
19
  /** Report one semantic issue: what is wrong (a fact), and how to correct it when the fact alone does not say. */
20
20
  export type ReportArgumentIssue = (field: string, reason: string, fix?: string) => void;
21
- export type CheckArguments = (args: unknown, report: ReportArgumentIssue) => void;
21
+ export type CheckArguments<Parsed> = (args: unknown, report: ReportArgumentIssue) => () => Parsed;
22
+
23
+ export const noArgumentProduct = () => {};
22
24
 
23
25
  /**
24
26
  * Report V8's diagnostics for a rule's flags and, in regex mode, for each pattern that
@@ -53,68 +55,163 @@ export function checkRegexArguments(
53
55
  }
54
56
  }
55
57
 
56
- /** Inspect arrays and the singleton objects Pi may coerce, without changing input. */
57
- export function argumentItems(value: unknown): readonly unknown[] {
58
- return Array.isArray(value) ? value : value !== null && typeof value === "object" ? [value] : [];
59
- }
60
-
61
- export function createArgumentPreparer<T extends TObject>(
62
- name: ReportTool,
63
- parameters: T,
64
- check: CheckArguments | undefined,
65
- budgets: OutputBudgetProvider,
66
- ): (args: unknown) => Static<T> {
67
- const diagnosticValidator = compile(parameters, {
68
- formats,
69
- coerce: true,
70
- unresolvedRefs: "reject",
71
- });
58
+ /** pi-ai's validateToolArguments compile options. */
59
+ const COMPILE_OPTIONS = { formats, coerce: true, unresolvedRefs: "reject" } as const;
72
60
 
61
+ /**
62
+ * Pi hands renderers a call's raw arguments, also while they stream, and coerces them only for
63
+ * execution. Renderers receive the same coercion on a copy, so a card shows the call that ran;
64
+ * arguments that cannot be coerced stay raw.
65
+ */
66
+ export function createRenderArguments(parameters: TSchema): (args: unknown) => unknown {
67
+ const validator = compile(parameters, COMPILE_OPTIONS);
73
68
  return (args) => {
74
- let checked: unknown = args;
75
- let schemaFailure: unknown;
76
69
  try {
77
- checked = validateToolArguments(
78
- { name, parameters, description: "" },
79
- // Pi owns shape checking and coercion at this external boundary.
80
- {
81
- type: "toolCall",
82
- id: "argument-validation",
83
- name,
84
- arguments: args as ToolCall["arguments"],
85
- },
86
- );
87
- } catch (error) {
88
- schemaFailure = error;
70
+ return validator.coerce(structuredClone(args));
71
+ } catch {
72
+ return args;
89
73
  }
90
- if (schemaFailure !== undefined) {
91
- try {
92
- checked = diagnosticValidator.coerce(structuredClone(args));
93
- } catch {
94
- // Preparation failures retain Pi's original cause in the shared error envelope.
95
- throw new Error(
96
- formatArgumentError(
97
- [{ field: "$", reason: errorMessage(schemaFailure) }],
98
- false,
99
- budgets(),
100
- ),
101
- { cause: schemaFailure },
102
- );
103
- }
74
+ };
75
+ }
76
+
77
+ function parsePathArguments(args: unknown, report: ReportArgumentIssue) {
78
+ const path = (args as { path?: unknown } | null)?.path;
79
+ const locals: { spelling: string; local: string }[] = [];
80
+ const parse = (spelling: unknown, field: string) => {
81
+ if (typeof spelling !== "string") return;
82
+ try {
83
+ locals.push({ spelling, local: parseArgumentPath(spelling) });
84
+ } catch (error) {
85
+ report(field, errorMessage(error));
104
86
  }
105
- const issues: ArgumentIssue[] = [];
106
- check?.(checked, (field, reason, fix) =>
107
- issues.push(fix === undefined ? { field, reason } : { field, reason, fix }),
87
+ };
88
+ if (Array.isArray(path)) path.forEach((spelling, index) => parse(spelling, `path[${index}]`));
89
+ else parse(path, "path");
90
+ return locals;
91
+ }
92
+
93
+ function arrayShapeIssue(
94
+ array: readonly unknown[],
95
+ path: string,
96
+ items?: TSchema,
97
+ ): ArgumentIssue | undefined {
98
+ const keys = Object.keys(array);
99
+ // A clone's own indices are dense if their count and last index agree with length.
100
+ if (
101
+ keys.length !== array.length ||
102
+ (keys.length !== 0 && keys.at(-1) !== String(array.length - 1))
103
+ ) {
104
+ // Indexed keys precede named keys. Their first mismatch locates the first hole.
105
+ const mismatch = keys.findIndex((key, index) => key !== String(index));
106
+ const index = mismatch === -1 ? keys.length : mismatch;
107
+ if (index < array.length)
108
+ return { field: `${path}[${index}]`, reason: "is required; arrays must not have holes" };
109
+ return { field: propertyPath(path, keys[index]), reason: "is not allowed on an array" };
110
+ }
111
+
112
+ if (!IsArray(items) && !IsObject(items)) return undefined;
113
+ for (const [index, item] of array.entries()) {
114
+ const issue = firstArrayIssue(items, item, `${path}[${index}]`);
115
+ if (issue) return issue;
116
+ }
117
+ return undefined;
118
+ }
119
+
120
+ /**
121
+ * Follow declared fields only, so a hook's cyclic object graph cannot drive recursion.
122
+ * Pi wraps a singleton by its item schema, so the singleton is checked there at the caller's path.
123
+ */
124
+ function firstArrayIssue(schema: TSchema, value: unknown, path = ""): ArgumentIssue | undefined {
125
+ if (!(value instanceof Object)) return undefined;
126
+ if (IsArray(schema))
127
+ return Array.isArray(value)
128
+ ? arrayShapeIssue(value, path, schema.items)
129
+ : firstArrayIssue(schema.items, value, path);
130
+ if (Array.isArray(value)) return arrayShapeIssue(value, path);
131
+ if (!IsObject(schema)) return undefined;
132
+ for (const [key, child] of Object.entries(schema.properties)) {
133
+ const issue = firstArrayIssue(child, Reflect.get(value, key), propertyPath(path, key));
134
+ if (issue) return issue;
135
+ }
136
+ return undefined;
137
+ }
138
+
139
+ function withArgumentError<Value>(
140
+ operation: () => Value,
141
+ budgets: OutputBudgetProvider,
142
+ field = "$",
143
+ ): Value {
144
+ try {
145
+ return operation();
146
+ } catch (error) {
147
+ throw new Error(
148
+ formatArgumentError([{ field, reason: errorMessage(error) }], false, budgets()),
149
+ { cause: error },
108
150
  );
109
- // Keep Pi's preparation contract: the framework performs its own coercion next.
110
- if (schemaFailure === undefined && issues.length === 0) return args as Static<T>;
111
- const result = diagnoseArguments(parameters, checked, issues, schemaFailure !== undefined);
112
- const reported =
113
- result.issues.length > 0
114
- ? result.issues
115
- : [{ field: "$", reason: errorMessage(schemaFailure) }];
116
- throw new Error(formatArgumentError(reported, result.limited, budgets()), {
117
- cause: schemaFailure,
118
- });
151
+ }
152
+ }
153
+
154
+ /** Snapshot enumerable call data under the diagnostic budget of the owning operation. */
155
+ export function cloneArguments<Value>(
156
+ args: Value,
157
+ budgets: OutputBudgetProvider,
158
+ field = "$",
159
+ ): Value {
160
+ return withArgumentError(() => structuredClone(args), budgets, field);
161
+ }
162
+
163
+ export function createArgumentBoundary<T extends TObject, Parsed>(
164
+ parameters: T,
165
+ cwd: string,
166
+ budgets: OutputBudgetProvider,
167
+ check: CheckArguments<Parsed>,
168
+ ) {
169
+ const validator = compile(parameters, COMPILE_OPTIONS);
170
+
171
+ function snapshot<Value>(args: Value): Value {
172
+ const copy = cloneArguments(args, budgets);
173
+ const issue = firstArrayIssue(parameters, copy);
174
+ if (issue) throw new Error(formatArgumentError([issue], false, budgets()));
175
+ return copy;
176
+ }
177
+
178
+ function verdict(checked: unknown) {
179
+ const schemaFailed = !withArgumentError(() => validator.check(checked), budgets);
180
+ const issues: ArgumentIssue[] = [];
181
+ const report: ReportArgumentIssue = (field, reason, fix) => {
182
+ issues.push(fix === undefined ? { field, reason } : { field, reason, fix });
183
+ };
184
+ const build = check(checked, report);
185
+ const locals = parsePathArguments(checked, report);
186
+ if (!schemaFailed && issues.length === 0) return { build, locals };
187
+
188
+ const result = diagnoseArguments(parameters, checked, issues, schemaFailed);
189
+ // Pi can reject values that TypeBox does not diagnose, for example near-integers.
190
+ const reasons =
191
+ schemaFailed && result.issues.length === 0
192
+ ? validator.errors(checked).map((error) => nativeArgumentIssue(error, checked))
193
+ : result.issues;
194
+ throw new Error(formatArgumentError(reasons, result.limited, budgets()));
195
+ }
196
+
197
+ return {
198
+ prepareArguments(args: unknown): Static<T> {
199
+ const raw = snapshot(args);
200
+ verdict(withArgumentError(() => validator.coerce(raw), budgets));
201
+ // Coercion is copy-on-write. Pi applies it to this snapshot before passing args to hooks.
202
+ return raw as Static<T>;
203
+ },
204
+ // A tool_call hook can retain and mutate the validated arguments before or during execution.
205
+ // The tool consumes its own checked snapshot of the canonical arguments the last hook left.
206
+ afterHooks(args: unknown) {
207
+ const checked = snapshot(args);
208
+ const { build, locals } = verdict(checked);
209
+ const paths: ResolvedArgumentPath[] = locals.map(({ spelling, local }) => ({
210
+ absolutePath: resolve(cwd, local),
211
+ spelling,
212
+ }));
213
+ // The schema and semantic checks above validate this owned execution snapshot.
214
+ return { args: checked as Static<T>, parsed: build(), paths };
215
+ },
119
216
  };
120
217
  }
package/src/pi/budgets.ts CHANGED
@@ -23,6 +23,18 @@ const MIN_FIELD_BYTES = 128;
23
23
  export const MAX_CONTENT_KIB = 4096;
24
24
  const MAX_CONTENT_BYTES = MAX_CONTENT_KIB * 1024;
25
25
 
26
+ /** The leading entries whose compact JSON array fits `maxBytes`; whole entries are omitted, never cut. */
27
+ export function leadingEntriesWithin<T>(entries: readonly T[], maxBytes: number): T[] {
28
+ const kept: T[] = [];
29
+ let bytes = 1; // Brackets less the comma charged to the first entry.
30
+ for (const entry of entries) {
31
+ bytes += Buffer.byteLength(JSON.stringify(entry)) + 1;
32
+ if (bytes > maxBytes) break;
33
+ kept.push(entry);
34
+ }
35
+ return kept;
36
+ }
37
+
26
38
  // Declared apart so Object.freeze keeps these as numbers rather than literal types.
27
39
  const fallbackBudgets = {
28
40
  readBytes: 64 * 1024,
@@ -5,12 +5,10 @@
5
5
  */
6
6
  import { formatByteSize } from "./budgets.ts";
7
7
 
8
- /** Cut only at UTF-8 boundaries; diagnostics may contain a single oversized line. */
9
- function byteSlice(text: string, maxBytes: number, tail: boolean): string {
10
- const bytes = Buffer.from(text);
11
- let boundary = tail ? Math.max(0, bytes.length - maxBytes) : Math.min(bytes.length, maxBytes);
12
- while (boundary < bytes.length && (bytes[boundary] & 0xc0) === 0x80) boundary += tail ? 1 : -1;
13
- return (tail ? bytes.subarray(boundary) : bytes.subarray(0, boundary)).toString("utf8");
8
+ /** A cut inside a UTF-8 character moves inward, toward the bytes being kept. */
9
+ function utf8Boundary(bytes: Buffer, boundary: number, step: -1 | 1): number {
10
+ while (boundary < bytes.length && (bytes[boundary] & 0xc0) === 0x80) boundary += step;
11
+ return boundary;
14
12
  }
15
13
 
16
14
  export class DiagnosticBuffer {
@@ -37,19 +35,22 @@ export class DiagnosticBuffer {
37
35
  this.head = combined;
38
36
  return;
39
37
  }
40
- this.head = byteSlice(combined, this.headBytes, false);
41
- this.tail = this.truncateTail(combined);
38
+ const bytes = Buffer.from(combined);
39
+ const end = utf8Boundary(bytes, Math.min(bytes.length, this.headBytes), -1);
40
+ this.head = bytes.subarray(0, end).toString("utf8");
41
+ this.tail = this.truncateTail(bytes);
42
42
  this.truncated = true;
43
43
  return;
44
44
  }
45
- this.tail = this.truncateTail(this.tail + text);
45
+ this.tail = this.truncateTail(Buffer.from(this.tail + text));
46
46
  }
47
47
 
48
48
  toString(): string {
49
49
  return this.truncated ? this.head + this.notice + this.tail : this.head;
50
50
  }
51
51
 
52
- private truncateTail(text: string): string {
53
- return byteSlice(text, this.tailBytes, true);
52
+ private truncateTail(bytes: Buffer): string {
53
+ const start = utf8Boundary(bytes, Math.max(0, bytes.length - this.tailBytes), 1);
54
+ return bytes.subarray(start).toString("utf8");
54
55
  }
55
56
  }