@criogaid/pi-hashline-edit 0.8.0 → 0.9.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.
@@ -22,7 +22,7 @@ import {
22
22
  type ToolRenderResultOptions,
23
23
  } from "@earendil-works/pi-coding-agent";
24
24
  import type { AgentToolUpdateCallback } from "@earendil-works/pi-agent-core";
25
- import { Type, type Static } from "typebox";
25
+ import { Type, type Static, type TLiteral } from "typebox";
26
26
  import {
27
27
  ACTION_FUSION_GUIDELINES,
28
28
  withThenRunDescription,
@@ -36,6 +36,7 @@ import type { HashlineEditConfig } from "./config.ts";
36
36
  import { anchorPattern, createAnchorFormatter, parseAnchorToken } from "./anchor-format.ts";
37
37
  import {
38
38
  formatDiffCounts,
39
+ formatHeaderPath,
39
40
  renderMutationCall,
40
41
  renderMutationResult,
41
42
  type DiffCounts,
@@ -65,90 +66,103 @@ function parseAnchor(value: string | undefined) {
65
66
  return value === undefined ? undefined : parseAnchorToken(value)!;
66
67
  }
67
68
 
68
- /** Edit parameters; anchors must carry exactly `hashLen` hash characters. */
69
+ /** Operation item fields besides `action`. */
70
+ type EditItemField = (typeof EDIT_ANCHOR_FIELDS)[number] | "body";
71
+
72
+ /** What one op does and which item fields it takes; it takes no others. */
73
+ interface EditOpSpec {
74
+ readonly meaning: string;
75
+ readonly required: readonly EditItemField[];
76
+ readonly optional?: readonly EditItemField[];
77
+ /** Destinations, of which exactly one is required. */
78
+ readonly destination?: readonly EditItemField[];
79
+ }
80
+
81
+ const TRANSFER_DESTINATION = ["before", "after"] as const;
82
+
83
+ /** Every op and its fields; the schema states them, and argument checks enforce them. */
84
+ const EDIT_OPS = {
85
+ replace: {
86
+ meaning: "Replace the cited line(s) with body.",
87
+ required: ["anchor", "body"],
88
+ optional: ["end"],
89
+ },
90
+ delete: { meaning: "Delete the cited line(s).", required: ["anchor"], optional: ["end"] },
91
+ insert_after: {
92
+ meaning: "Insert body after the anchor line, which is kept; do not repeat it in body.",
93
+ required: ["anchor", "body"],
94
+ },
95
+ insert_before: {
96
+ meaning: "Insert body before the anchor line, which is kept; do not repeat it in body.",
97
+ required: ["anchor", "body"],
98
+ },
99
+ copy: {
100
+ meaning:
101
+ "Copy the cited line(s), text and indentation unchanged, before or after another original line; use a body edit when either changes.",
102
+ required: ["anchor"],
103
+ optional: ["end"],
104
+ destination: TRANSFER_DESTINATION,
105
+ },
106
+ move: {
107
+ meaning:
108
+ "Move the cited line(s), text and indentation unchanged, before or after another original line, removing the source; use a body edit when either changes.",
109
+ required: ["anchor"],
110
+ optional: ["end"],
111
+ destination: TRANSFER_DESTINATION,
112
+ },
113
+ append: { meaning: "Add body at the end of the file.", required: ["body"] },
114
+ prepend: { meaning: "Add body at the start of the file.", required: ["body"] },
115
+ } as const satisfies Record<string, EditOpSpec>;
116
+ type EditOpName = keyof typeof EDIT_OPS;
117
+ const EDIT_OP_NAMES = Object.keys(EDIT_OPS) as EditOpName[];
118
+
119
+ /** Operations in one call; constrained sampling ends a runaway batch at this bound. */
120
+ const MAX_EDIT_OPS = 64;
121
+
122
+ /** An op's meaning followed by the fields it takes. */
123
+ function describeEditOp({ meaning, required, optional = [], destination }: EditOpSpec): string {
124
+ const takes = [
125
+ ...required,
126
+ ...(destination ? [`exactly one of ${destination.join(" or ")}`] : []),
127
+ ].join(" and ");
128
+ return `${meaning} Takes ${takes}${optional.length ? `; ${optional.join(", ")} is optional` : ""}.`;
129
+ }
130
+
131
+ /**
132
+ * Edit parameters; anchors must carry exactly `hashLen` hash characters. Each
133
+ * operation is one flat object, so providers can constrain sampling to the
134
+ * schema; argument checks enforce which fields each op takes.
135
+ */
69
136
  function buildEditSchema(hashLen: number) {
70
137
  const pattern = anchorPattern(hashLen);
71
- const requiredAnchor = Type.String({
72
- pattern,
73
- description: "LINE#HASH of the target line.",
74
- });
75
- const optionalEnd = Type.Optional(
76
- Type.String({
77
- pattern,
78
- description: "Inclusive last LINE#HASH of the range; omit for one line.",
79
- }),
80
- );
81
- const bodyLines = Type.Array(Type.String({ pattern: "^[^\\r\\n]*$" }), {
82
- minItems: 1,
83
- description: 'New lines, one per element, without CR/LF. At least one; [""] is one blank line.',
84
- });
85
- const transferFields = {
86
- op: Type.Union([Type.Literal("copy"), Type.Literal("move")], {
87
- description:
88
- "Copy, or move (also removes the source), whole lines whose text and indentation stay unchanged; use a body edit when either changes.",
89
- }),
90
- anchor: requiredAnchor,
91
- end: optionalEnd,
92
- };
93
- const editOpSchema = Type.Union([
94
- Type.Object(
95
- {
96
- op: Type.Literal("replace", { description: "Replace the cited line(s) with `body`." }),
97
- anchor: requiredAnchor,
98
- end: optionalEnd,
99
- body: bodyLines,
100
- },
101
- { additionalProperties: false },
102
- ),
103
- Type.Object(
104
- {
105
- op: Type.Literal("delete", { description: "Delete the cited line(s)." }),
106
- anchor: requiredAnchor,
107
- end: optionalEnd,
108
- },
109
- { additionalProperties: false },
110
- ),
111
- Type.Object(
112
- {
113
- op: Type.Union([Type.Literal("insert_after"), Type.Literal("insert_before")], {
138
+ const anchorField = (description: string) => Type.Optional(Type.String({ pattern, description }));
139
+ const editOpSchema = Type.Object(
140
+ {
141
+ // Constrained sampling and some gateways emit keys alphabetically; `action`
142
+ // sorts first, so the operation is chosen before the fields it governs.
143
+ // TypeBox infers a union's static type only from a tuple.
144
+ action: Type.Union(
145
+ EDIT_OP_NAMES.map((op) =>
146
+ Type.Literal(op, { description: describeEditOp(EDIT_OPS[op]) }),
147
+ ) as [TLiteral<EditOpName>, ...TLiteral<EditOpName>[]],
148
+ ),
149
+ anchor: anchorField("LINE#HASH of the target line."),
150
+ end: anchorField("Inclusive last LINE#HASH of the range; omit for one line."),
151
+ body: Type.Optional(
152
+ Type.Array(Type.String({ pattern: "^[^\\r\\n]*$" }), {
153
+ minItems: 1,
114
154
  description:
115
- "Insert body beside the anchor line, which is kept; do not repeat it in body.",
116
- }),
117
- anchor: requiredAnchor,
118
- body: bodyLines,
119
- },
120
- { additionalProperties: false },
121
- ),
122
- Type.Object(
123
- {
124
- ...transferFields,
125
- before: Type.String({
126
- pattern,
127
- description: "Insert captured lines before this original line.",
155
+ 'New lines, one per element, without CR/LF. At least one; [""] is one blank line.',
128
156
  }),
129
- },
130
- { additionalProperties: false },
131
- ),
132
- Type.Object(
133
- {
134
- ...transferFields,
135
- after: Type.String({
136
- pattern,
137
- description: "Insert captured lines after this original line.",
138
- }),
139
- },
140
- { additionalProperties: false },
141
- ),
142
- Type.Object(
143
- {
144
- op: Type.Union([Type.Literal("append"), Type.Literal("prepend")], {
145
- description: "Add body at the end or start of the file.",
146
- }),
147
- body: bodyLines,
148
- },
149
- { additionalProperties: false },
150
- ),
151
- ]);
157
+ ),
158
+ before: anchorField("Insert captured lines before this original line."),
159
+ after: anchorField("Insert captured lines after this original line."),
160
+ },
161
+ {
162
+ additionalProperties: false,
163
+ description: "One operation. Omit, or set to null, each field its action does not take.",
164
+ },
165
+ );
152
166
  return Type.Object(
153
167
  {
154
168
  path: Type.String({
@@ -157,7 +171,8 @@ function buildEditSchema(hashLen: number) {
157
171
  }),
158
172
  edits: Type.Array(editOpSchema, {
159
173
  minItems: 1,
160
- description: `Operations on one snapshot; ranges must not overlap. Insertions at one position, or at the start of a replaced or deleted range, apply in array order before it. Anchors are LINE#HASH with exactly ${hashLen} hash characters. Copy each anchor from read, grep, or edit failure diagnostics; never write a hash you have not seen there. Shell output such as sed, head, or cat has no anchors, so read or grep those lines first.`,
174
+ maxItems: MAX_EDIT_OPS,
175
+ description: `Operations on one snapshot; ranges must not overlap. Each gap between lines takes at most one insertion, copy/move destinations included; insert_after N and insert_before N+1 target the same gap, so put all new lines for a gap in one body. An insertion at the start of a replaced or deleted range goes before it. Anchors are LINE#HASH with exactly ${hashLen} hash characters. Copy each anchor from read, grep, or edit failure diagnostics; never write a hash you have not seen there. Shell output such as sed, head, or cat has no anchors, so read or grep those lines first.`,
161
176
  }),
162
177
  },
163
178
  { additionalProperties: false },
@@ -168,50 +183,86 @@ type EditSchema = ReturnType<typeof buildEditSchema>;
168
183
  type EditParams = Static<EditSchema> & { then_run?: ThenRunInput };
169
184
 
170
185
  type EditOpInput = Static<EditSchema>["edits"][number];
186
+ type EditOpSchema = EditSchema["properties"]["edits"]["items"];
171
187
 
172
188
  /** How to correct edit argument issues; each reason states only what is wrong. */
173
189
  const EDIT_ISSUE_FIX = {
174
- emptyReplace: 'Use {"op":"delete"} to remove lines, or supply the replacement lines.',
190
+ emptyReplace: 'Use {"action":"delete"} to remove lines, or supply the replacement lines.',
175
191
  emptyBody: 'Remove this edit or supply at least one line ([""] for a blank line).',
176
192
  unsafeLine: 'Copy a complete "LINE#HASH" token from the latest tool result.',
177
193
  hashLength: "Read or grep the file for current anchors.",
178
194
  } as const;
179
195
 
180
- /** Report semantic argument issues; malformed shapes remain Pi's schema responsibility. */
181
- function checkEditArguments(args: unknown, hashLen: number, report: ReportArgumentIssue): void {
182
- const raw = (args as { edits?: unknown } | null)?.edits;
183
- const edits = argumentItems(raw);
184
- edits.forEach((op, index) => {
185
- const body = (op as Record<string, unknown> | null)?.body;
186
- if (Array.isArray(body)) {
196
+ /**
197
+ * Report semantic argument issues: the fields each op takes, and field values
198
+ * the schema cannot judge. Malformed shapes remain Pi's schema responsibility;
199
+ * Pi has already removed null optional fields.
200
+ */
201
+ function checkEditArguments(
202
+ args: unknown,
203
+ hashLen: number,
204
+ item: EditOpSchema,
205
+ report: ReportArgumentIssue,
206
+ ): void {
207
+ argumentItems((args as { edits?: unknown } | null)?.edits).forEach((value, index) => {
208
+ if (value === null || typeof value !== "object") return;
209
+ const edit = value as Record<string, unknown>;
210
+ // The schema reports an unknown action; which fields it takes is then unknown.
211
+ if (typeof edit.action !== "string" || !Object.hasOwn(EDIT_OPS, edit.action)) return;
212
+ const name = edit.action as EditOpName;
213
+ const spec: EditOpSpec = EDIT_OPS[name];
214
+ const path = `edits[${index}]`;
215
+ const accepted = new Set([
216
+ ...spec.required,
217
+ ...(spec.optional ?? []),
218
+ ...(spec.destination ?? []),
219
+ ]);
220
+ for (const [field, declaration] of Object.entries(item.properties)) {
221
+ if (field === "action") continue;
222
+ const given = edit[field] !== undefined;
223
+ if (given && !accepted.has(field as EditItemField))
224
+ report(`${path}.${field}`, "is not allowed", `"${name}": ${describeEditOp(spec)}`);
225
+ else if (!given && spec.required.includes(field as EditItemField))
226
+ report(
227
+ `${path}.${field}`,
228
+ `is required for "${name}"`,
229
+ Reflect.get(declaration, "description"),
230
+ );
231
+ }
232
+ if (
233
+ spec.destination &&
234
+ spec.destination.filter((field) => edit[field] !== undefined).length !== 1
235
+ )
236
+ report(path, `expected exactly one of: ${spec.destination.join(", ")}`);
237
+
238
+ const body = edit.body;
239
+ if (accepted.has("body") && Array.isArray(body)) {
187
240
  if (body.length === 0) {
188
241
  report(
189
- `edits[${index}].body`,
242
+ `${path}.body`,
190
243
  "is empty",
191
- (op as Record<string, unknown>).op === "replace"
192
- ? EDIT_ISSUE_FIX.emptyReplace
193
- : EDIT_ISSUE_FIX.emptyBody,
244
+ name === "replace" ? EDIT_ISSUE_FIX.emptyReplace : EDIT_ISSUE_FIX.emptyBody,
194
245
  );
195
246
  }
196
247
  body.forEach((line, lineIndex) => {
197
248
  const unwritable = typeof line === "string" ? unwritableTextError(line) : undefined;
198
- if (unwritable) report(`edits[${index}].body[${lineIndex}]`, unwritable.message);
249
+ if (unwritable) report(`${path}.body[${lineIndex}]`, unwritable.message);
199
250
  });
200
251
  }
201
252
  for (const field of EDIT_ANCHOR_FIELDS) {
202
- const value = (op as Record<string, unknown> | null)?.[field];
203
- if (typeof value !== "string") continue;
204
- const token = parseAnchorToken(value);
253
+ const anchor = edit[field];
254
+ if (!accepted.has(field) || typeof anchor !== "string") continue;
255
+ const token = parseAnchorToken(anchor);
205
256
  if (token && !Number.isSafeInteger(token.line)) {
206
257
  report(
207
- `edits[${index}].${field}`,
258
+ `${path}.${field}`,
208
259
  "line number exceeds the safe integer range",
209
260
  EDIT_ISSUE_FIX.unsafeLine,
210
261
  );
211
262
  }
212
263
  if (token && token.hash.length !== hashLen) {
213
264
  report(
214
- `edits[${index}].${field}`,
265
+ `${path}.${field}`,
215
266
  `has ${token.hash.length} hash characters; hashLen is ${hashLen}`,
216
267
  EDIT_ISSUE_FIX.hashLength,
217
268
  );
@@ -220,32 +271,35 @@ function checkEditArguments(args: unknown, hashLen: number, report: ReportArgume
220
271
  });
221
272
  }
222
273
 
223
- /** Translate validated public operations into core edits, parsing numeric anchor positions. */
274
+ /**
275
+ * Translate validated public operations into core edits, parsing numeric anchor
276
+ * positions. Argument checks guarantee each op carries exactly the fields it takes.
277
+ */
224
278
  function toCoreEdits(ops: readonly EditOpInput[]): Edit[] {
225
279
  return ops.map((op) => {
226
- switch (op.op) {
280
+ switch (op.action) {
227
281
  case "replace":
228
282
  return {
229
283
  op: "replace",
230
- anchor: parseAnchor(op.anchor),
284
+ anchor: parseAnchor(op.anchor!),
231
285
  end: parseAnchor(op.end),
232
- body: op.body,
286
+ body: op.body!,
233
287
  };
234
288
  case "delete":
235
- return { op: "delete", anchor: parseAnchor(op.anchor), end: parseAnchor(op.end) };
289
+ return { op: "delete", anchor: parseAnchor(op.anchor!), end: parseAnchor(op.end) };
236
290
  case "copy":
237
291
  case "move": {
238
- const source = { op: op.op, anchor: parseAnchor(op.anchor), end: parseAnchor(op.end) };
239
- return "before" in op
292
+ const source = { op: op.action, anchor: parseAnchor(op.anchor!), end: parseAnchor(op.end) };
293
+ return op.before !== undefined
240
294
  ? { ...source, before: parseAnchor(op.before) }
241
- : { ...source, after: parseAnchor(op.after) };
295
+ : { ...source, after: parseAnchor(op.after!) };
242
296
  }
243
297
  case "insert_after":
244
298
  case "insert_before":
245
- return { op: op.op, anchor: parseAnchor(op.anchor), body: op.body };
299
+ return { op: op.action, anchor: parseAnchor(op.anchor!), body: op.body! };
246
300
  case "append":
247
301
  case "prepend":
248
- return { op: op.op, body: op.body };
302
+ return { op: op.action, body: op.body! };
249
303
  }
250
304
  });
251
305
  }
@@ -253,11 +307,11 @@ function toCoreEdits(ops: readonly EditOpInput[]): Edit[] {
253
307
  /** Call header with total/per-kind operation counts and the result's diff counts. */
254
308
  function editHeader(args: EditParams, theme: Theme, counts?: DiffCounts): string {
255
309
  let t = theme.fg("toolTitle", theme.bold("edit "));
256
- t += theme.fg("accent", args.path);
310
+ t += formatHeaderPath(args.path, theme);
257
311
  const edits = Array.isArray(args.edits) ? args.edits : [];
258
312
  const n = edits.length;
259
313
  if (n) {
260
- const opCounts: Record<EditOpInput["op"] | "unknown", number> = {
314
+ const opCounts: Record<EditOpName | "unknown", number> = {
261
315
  replace: 0,
262
316
  delete: 0,
263
317
  copy: 0,
@@ -270,7 +324,7 @@ function editHeader(args: EditParams, theme: Theme, counts?: DiffCounts): string
270
324
  };
271
325
  // Renderers receive partial arguments; fixed buckets keep one-pass counting O(1) in space.
272
326
  for (const edit of edits) {
273
- const kind = edit?.op;
327
+ const kind = edit?.action;
274
328
  if (typeof kind === "string" && Object.hasOwn(opCounts, kind)) opCounts[kind]++;
275
329
  else opCounts.unknown++;
276
330
  }
@@ -292,7 +346,8 @@ export function makeEditOverride(
292
346
  ) {
293
347
  // Schema, verification, and recovery use the registered configuration.
294
348
  const { hashLen, shiftRadius } = config;
295
- const parameters = withThenRunSchema(buildEditSchema(hashLen), "edit", fusion !== undefined);
349
+ const schema = buildEditSchema(hashLen);
350
+ const parameters = withThenRunSchema(schema, "edit", fusion !== undefined);
296
351
 
297
352
  return {
298
353
  name: "edit" as const,
@@ -308,10 +363,12 @@ export function makeEditOverride(
308
363
  ...(fusion ? ACTION_FUSION_GUIDELINES : []),
309
364
  ],
310
365
  parameters,
366
+ // Providers that support it bound the batch by the schema while sampling.
367
+ constrainedSampling: { type: "json_schema", strict: "prefer" } as const,
311
368
  prepareArguments: createArgumentPreparer(
312
369
  "edit",
313
370
  parameters,
314
- (args, report) => checkEditArguments(args, hashLen, report),
371
+ (args, report) => checkEditArguments(args, hashLen, schema.properties.edits.items, report),
315
372
  budgets,
316
373
  ),
317
374
  renderShell: "default" as const,