@xynogen/pix-edit 0.2.7 → 0.2.8

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.
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@xynogen/pix-edit",
3
- "version": "0.2.7",
4
- "description": "Pi tool — precise text replacement edit with diff rendering",
3
+ "version": "0.2.8",
4
+ "description": "Pi tool \u2014 precise text replacement edit with diff rendering",
5
5
  "type": "module",
6
6
  "main": "src/index.ts",
7
7
  "exports": {
@@ -39,8 +39,8 @@
39
39
  "access": "public"
40
40
  },
41
41
  "dependencies": {
42
- "@xynogen/pix-pretty": "^1.25.0",
43
- "@xynogen/pix-runtime": "^0.12.2"
42
+ "@xynogen/pix-pretty": "^1.30.0",
43
+ "@xynogen/pix-runtime": "^0.13.0"
44
44
  },
45
45
  "peerDependencies": {
46
46
  "@earendil-works/pi-coding-agent": "*",
package/src/edit.ts CHANGED
@@ -1,10 +1,14 @@
1
- import { existsSync, readFileSync } from "node:fs";
1
+ import { constants } from "node:fs";
2
+ import { access, readFile, writeFile } from "node:fs/promises";
3
+ import { resolve } from "node:path";
4
+ import { fileURLToPath } from "node:url";
2
5
  import type {
3
6
  AgentToolUpdateCallback,
4
7
  EditToolInput,
5
8
  ExtensionContext,
6
9
  ToolRenderResultOptions,
7
10
  } from "@earendil-works/pi-coding-agent";
11
+ import { withFileMutationQueue } from "@earendil-works/pi-coding-agent";
8
12
  import { resolveBaseBackground } from "@xynogen/pix-pretty/ansi";
9
13
  import { MAX_RENDER_LINES } from "@xynogen/pix-pretty/config";
10
14
  import type { ToolContext } from "@xynogen/pix-pretty/context";
@@ -28,8 +32,10 @@ import type {
28
32
  ToolResultLike,
29
33
  } from "@xynogen/pix-pretty/types";
30
34
  import {
35
+ BODY_PAD,
31
36
  dotJoin,
32
37
  fillToolBackground,
38
+ formatToolCallTitle,
33
39
  frameToolResult,
34
40
  getErrorMessage,
35
41
  getTextContent,
@@ -42,6 +48,9 @@ import {
42
48
  unframeToolResult,
43
49
  } from "@xynogen/pix-pretty/utils";
44
50
  import { type CollapseState, tickCollapse } from "@xynogen/pix-runtime/collapse";
51
+ import { decodeLines, hashLine, parseAnchor, type SourceLine } from "@xynogen/pix-runtime/hashline";
52
+ import { expandHome } from "@xynogen/pix-runtime/paths";
53
+ import { Type } from "typebox";
45
54
 
46
55
  // ── Helpers ────────────────────────────────────────────────────────────
47
56
 
@@ -79,18 +88,257 @@ export function getEditOperations(input: EditParams): EditOperation[] {
79
88
  return oldText && oldText !== newText ? [{ oldText, newText }] : [];
80
89
  }
81
90
 
82
- // 1-based file line where `needle` begins post-edit, for absolute diff gutters.
83
- // 0 = file unreadable or needle not found (renderer falls back to relative).
84
- // Duplicate identical edits collapse to the first match — acceptable.
85
- function opEditLine(filePath: string, needle: string): number {
86
- try {
87
- if (!filePath || !existsSync(filePath)) return 0;
88
- const f = readFileSync(filePath, "utf-8");
89
- const idx = f.indexOf(needle);
90
- return idx >= 0 ? f.slice(0, idx).split("\n").length : 0;
91
- } catch {
92
- return 0;
91
+ type HashEdit = {
92
+ op: "replace" | "insert_before" | "insert_after";
93
+ pos: string;
94
+ end?: string;
95
+ lines: string[];
96
+ };
97
+ type HashParams = { path: string; edits: HashEdit[] };
98
+ type ExactParams = { path: string; edits: EditOperation[] };
99
+ type EditInput = HashParams | ExactParams;
100
+
101
+ const hashFields = {
102
+ pos: Type.String({
103
+ pattern: "^[1-9][0-9]*#[0-9A-F]{3}$",
104
+ description: "Original LINE#HASH anchor from read",
105
+ }),
106
+ lines: Type.Array(
107
+ Type.String({
108
+ description:
109
+ "One literal source line per item. No newline or LINE#HASH| prefix. Empty array deletes.",
110
+ }),
111
+ ),
112
+ };
113
+ const editSchema = Type.Object(
114
+ {
115
+ path: Type.String({ minLength: 1 }),
116
+ // ponytail: union whole arrays so the schema rejects mixed formats before execution.
117
+ edits: Type.Union(
118
+ [
119
+ Type.Array(
120
+ Type.Union([
121
+ Type.Object(
122
+ {
123
+ op: Type.Literal("replace"),
124
+ ...hashFields,
125
+ end: Type.Optional(
126
+ Type.String({
127
+ pattern: "^[1-9][0-9]*#[0-9A-F]{3}$",
128
+ description: "Inclusive end anchor. Omit for one line.",
129
+ }),
130
+ ),
131
+ },
132
+ { additionalProperties: false },
133
+ ),
134
+ Type.Object(
135
+ {
136
+ op: Type.Union([Type.Literal("insert_before"), Type.Literal("insert_after")]),
137
+ ...hashFields,
138
+ },
139
+ { additionalProperties: false },
140
+ ),
141
+ ]),
142
+ { minItems: 1 },
143
+ ),
144
+ Type.Array(
145
+ Type.Object(
146
+ {
147
+ oldText: Type.String({
148
+ minLength: 1,
149
+ description: "Exact source text. Include enough context to match once.",
150
+ }),
151
+ newText: Type.String({ description: "Replacement text. Empty string deletes." }),
152
+ },
153
+ { additionalProperties: false },
154
+ ),
155
+ { minItems: 1 },
156
+ ),
157
+ ],
158
+ {
159
+ description:
160
+ "Use only hash edits or only exact-text edits in this array. Never mix formats.",
161
+ },
162
+ ),
163
+ },
164
+ { additionalProperties: false },
165
+ );
166
+
167
+ export function prepareHashArguments(input: unknown): unknown {
168
+ if (!input || typeof input !== "object" || Array.isArray(input)) return input;
169
+ const args = { ...input } as Record<string, unknown>;
170
+ if (typeof args.edits === "string") args.edits = JSON.parse(args.edits);
171
+ if (args.edits && typeof args.edits === "object" && !Array.isArray(args.edits))
172
+ args.edits = [args.edits];
173
+ return args;
174
+ }
175
+
176
+ export function editPath(path: string, cwd: string): string {
177
+ let value = path.replace(/[\u00A0\u2000-\u200A\u202F\u205F\u3000]/g, " ").replace(/^@/, "");
178
+ if (
179
+ process.platform === "win32" &&
180
+ value.startsWith("/") &&
181
+ !value.startsWith("//") &&
182
+ !value.includes("\\")
183
+ ) {
184
+ value = value.replace(
185
+ /^\/(?:mnt\/|cygdrive\/)?([a-z])(?:\/(.*))?$/i,
186
+ (_all, drive: string, tail: string | undefined) =>
187
+ `${drive.toUpperCase()}:\\${(tail ?? "").replaceAll("/", "\\")}`,
188
+ );
189
+ }
190
+ value = expandHome(value);
191
+ if (value.startsWith("file://")) value = fileURLToPath(value);
192
+ return resolve(cwd, value);
193
+ }
194
+
195
+ function applyHashEdits(bytes: Buffer, input: unknown) {
196
+ const args = prepareHashArguments(input) as HashParams;
197
+ if (
198
+ !args ||
199
+ typeof args.path !== "string" ||
200
+ !args.path ||
201
+ !Array.isArray(args.edits) ||
202
+ !args.edits.length
203
+ )
204
+ throw new Error("Invalid hashline edit input");
205
+ if (Object.keys(args).some((key) => !["path", "edits"].includes(key)))
206
+ throw new Error("Legacy exact-text fields are not supported");
207
+ const source = decodeLines(bytes);
208
+ const check = (value: unknown) => {
209
+ const parsed = parseAnchor(value);
210
+ const line = source.lines[parsed.line - 1];
211
+ if (!line) throw new Error(`Anchor out of bounds: ${String(value)}`);
212
+ if (hashLine(line.text) !== parsed.hash)
213
+ throw new Error(`Stale anchor: ${String(value)}. Read the file again.`);
214
+ return parsed.line;
215
+ };
216
+ const replacements: Array<{ start: number; end: number; lines: string[] }> = [];
217
+ const gaps = new Map<number, string[]>();
218
+ for (const edit of args.edits) {
219
+ if (
220
+ !edit ||
221
+ typeof edit !== "object" ||
222
+ Object.keys(edit).some((key) => !["op", "pos", "end", "lines"].includes(key))
223
+ )
224
+ throw new Error("Legacy or invalid edit fields");
225
+ if (
226
+ !["replace", "insert_before", "insert_after"].includes(edit.op) ||
227
+ !Array.isArray(edit.lines) ||
228
+ edit.lines.some(
229
+ (line) =>
230
+ typeof line !== "string" ||
231
+ /[\r\n\0]|^[1-9]\d*#[0-9A-F]{3}\|/.test(line) ||
232
+ /[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/u.test(line),
233
+ )
234
+ )
235
+ throw new Error("Invalid edit operation or source lines");
236
+ const start = check(edit.pos);
237
+ if (edit.op === "replace") {
238
+ const end = edit.end === undefined ? start : check(edit.end);
239
+ if (end < start) throw new Error("Reversed replacement range");
240
+ replacements.push({ start, end, lines: edit.lines });
241
+ } else {
242
+ if (edit.end !== undefined) throw new Error("end is only allowed for replace");
243
+ const gap = edit.op === "insert_before" ? start - 1 : start;
244
+ gaps.set(gap, [...(gaps.get(gap) ?? []), ...edit.lines]);
245
+ }
246
+ }
247
+ replacements.sort((a, b) => a.start - b.start);
248
+ for (let i = 0; i < replacements.length; i++) {
249
+ const range = replacements[i]!;
250
+ if (i && replacements[i - 1]!.end >= range.start)
251
+ throw new Error("Overlapping replacement ranges");
252
+ for (const gap of gaps.keys())
253
+ if (gap >= range.start && gap < range.end)
254
+ throw new Error("Insertion overlaps a replacement range");
255
+ }
256
+ const output: SourceLine[] = [];
257
+ const ops: Array<EditOperation & { editLine: number }> = [];
258
+ const append = (lines: string[]) =>
259
+ output.push(...lines.map((text) => ({ text, ending: source.delimiter })));
260
+ let rangeIndex = 0;
261
+ for (let gap = 0; gap <= source.lines.length; ) {
262
+ const insertion = gaps.get(gap);
263
+ if (insertion?.length) {
264
+ const context = source.lines[Math.max(0, gap - 1)]!.text;
265
+ ops.push({
266
+ oldText: context,
267
+ newText:
268
+ gap === 0 ? [...insertion, context].join("\n") : [context, ...insertion].join("\n"),
269
+ editLine: Math.max(1, output.length + (gap === 0 ? 1 : 0)),
270
+ });
271
+ append(insertion);
272
+ }
273
+ if (gap === source.lines.length) break;
274
+ const range = replacements[rangeIndex];
275
+ if (range?.start === gap + 1) {
276
+ ops.push({
277
+ oldText: source.lines
278
+ .slice(gap, range.end)
279
+ .map((line) => line.text)
280
+ .join("\n"),
281
+ newText: range.lines.join("\n"),
282
+ editLine: output.length + 1,
283
+ });
284
+ append(range.lines);
285
+ gap = range.end;
286
+ rangeIndex++;
287
+ } else {
288
+ output.push({ ...source.lines[gap]! });
289
+ gap++;
290
+ }
291
+ }
292
+ for (let i = 0; i < output.length; i++) {
293
+ if (i === output.length - 1)
294
+ output[i]!.ending = source.finalNewline ? output[i]!.ending || source.delimiter : "";
295
+ else if (!output[i]!.ending) output[i]!.ending = source.delimiter;
93
296
  }
297
+ return { content: source.bom + output.map((line) => line.text + line.ending).join(""), ops };
298
+ }
299
+
300
+ function applyExactEdits(bytes: Buffer, args: ExactParams) {
301
+ if (Object.keys(args).some((key) => !["path", "edits"].includes(key)))
302
+ throw new Error("Invalid exact-text edit fields");
303
+ const source = decodeLines(bytes);
304
+ const original = source.lines.map((line) => line.text + line.ending).join("");
305
+ // ponytail: exact bytes only. Add newline normalization only if callers need it.
306
+ const ranges = args.edits
307
+ .map((edit) => {
308
+ if (
309
+ !edit ||
310
+ typeof edit !== "object" ||
311
+ Object.keys(edit).some((key) => !["oldText", "newText"].includes(key)) ||
312
+ typeof edit.oldText !== "string" ||
313
+ !edit.oldText ||
314
+ typeof edit.newText !== "string" ||
315
+ [edit.oldText, edit.newText].some((text) =>
316
+ /\0|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/u.test(text),
317
+ )
318
+ )
319
+ throw new Error("Invalid exact-text edit");
320
+ const start = original.indexOf(edit.oldText);
321
+ if (start < 0) throw new Error("oldText was not found. Use exact source text.");
322
+ if (original.indexOf(edit.oldText, start + 1) >= 0)
323
+ throw new Error("oldText matches more than once. Include more context.");
324
+ return { ...edit, start, end: start + edit.oldText.length };
325
+ })
326
+ .sort((a, b) => a.start - b.start);
327
+ let content = "";
328
+ let offset = 0;
329
+ const ops: Array<EditOperation & { editLine: number }> = [];
330
+ for (const range of ranges) {
331
+ if (range.start < offset) throw new Error("Overlapping exact-text edits");
332
+ content += original.slice(offset, range.start);
333
+ ops.push({
334
+ oldText: range.oldText,
335
+ newText: range.newText,
336
+ editLine: (content.match(/\r\n|\r|\n/g)?.length ?? 0) + 1,
337
+ });
338
+ content += range.newText;
339
+ offset = range.end;
340
+ }
341
+ return { content: source.bom + content + original.slice(offset), ops };
94
342
  }
95
343
 
96
344
  export function summarizeEditOperations(operations: EditOperation[]) {
@@ -119,31 +367,57 @@ export function registerEditTool(
119
367
  pi.registerTool({
120
368
  ...origEdit,
121
369
  name: "edit",
122
- // The edit description and schema already carry these rules. Drop the <rules> copy (~110 tokens/turn).
370
+ description:
371
+ "Edit using one format per call: hash anchors {op,pos,end?,lines} or exact text {oldText,newText}. Exact oldText must match once. All edits target the original file and must not overlap. Hash ops: replace, insert_before, insert_after. Empty lines or newText delete. Insertions may touch range boundaries, not interiors. Same-gap inserts follow input order. Use write for empty files or complete rewrites.",
372
+ parameters: editSchema,
373
+ promptSnippet: "Edit with hash anchors or exact text",
123
374
  promptGuidelines: [],
375
+ prepareArguments: prepareHashArguments,
376
+ constrainedSampling: { type: "json_schema", strict: "prefer" },
124
377
  renderShell: "self",
125
378
 
126
379
  async execute(
127
- tid: string,
128
- params: EditParams,
380
+ _tid: string,
381
+ params: EditInput,
129
382
  sig: AbortSignal | undefined,
130
- upd: AgentToolUpdateCallback<unknown> | undefined,
383
+ _upd: AgentToolUpdateCallback<unknown> | undefined,
131
384
  toolCtx: ExtensionContext,
132
385
  ) {
133
- const fp = params.path ?? params.file_path ?? "";
134
- const operations = getEditOperations(params);
386
+ const fp = typeof params?.path === "string" ? params.path : "";
387
+ let operations: Array<EditOperation & { editLine: number }> = [];
135
388
  const fileLang = lang(fp);
136
389
 
137
390
  let result: ToolResultLike;
138
391
  try {
139
- result = (await origEdit.execute(
140
- tid,
141
- // SAFETY: EditParams preserves the built-in edit schema and only adds legacy aliases.
142
- params as unknown as Parameters<typeof origEdit.execute>[1],
143
- sig,
144
- upd,
145
- toolCtx,
146
- )) as ToolResultLike;
392
+ if (!fp) throw new Error("path must be a nonempty string");
393
+ const absolutePath = editPath(fp, toolCtx?.cwd || cwd);
394
+ result = await withFileMutationQueue(absolutePath, async () => {
395
+ const abort = () => {
396
+ if (sig?.aborted) throw new Error("Operation aborted");
397
+ };
398
+ abort();
399
+ await access(absolutePath, constants.R_OK | constants.W_OK);
400
+ abort();
401
+ const bytes = await readFile(absolutePath);
402
+ abort();
403
+ const args = prepareHashArguments(params) as EditInput;
404
+ if (!Array.isArray(args.edits) || !args.edits.length)
405
+ throw new Error("edits must be a nonempty array");
406
+ const applied = args.edits.every(
407
+ (edit) => edit && typeof edit === "object" && "oldText" in edit,
408
+ )
409
+ ? applyExactEdits(bytes, args as ExactParams)
410
+ : applyHashEdits(bytes, args);
411
+ operations = applied.ops;
412
+ abort();
413
+ // ponytail: in-place writes preserve links and mode, not crash atomicity. Use a separate atomic-write design if needed.
414
+ await writeFile(absolutePath, applied.content, "utf8");
415
+ abort();
416
+ return {
417
+ content: [{ type: "text", text: `Edited ${fp}: ${operations.length} operations.` }],
418
+ details: undefined,
419
+ };
420
+ });
147
421
  } catch (error) {
148
422
  const text = getErrorMessage(error);
149
423
  if (sig?.aborted || /aborted/i.test(text)) throw error;
@@ -172,7 +446,7 @@ export function registerEditTool(
172
446
  setResultDetails(result, {
173
447
  _type: "editInfo",
174
448
  summary,
175
- editLine: opEditLine(fp, op0.newText),
449
+ editLine: op0.editLine,
176
450
  oldContent: op0.oldText,
177
451
  newContent: op0.newText,
178
452
  language: fileLang,
@@ -191,13 +465,17 @@ export function registerEditTool(
191
465
  newContent: op.newText,
192
466
  language: fileLang,
193
467
  filePath: fp,
194
- editLine: opEditLine(fp, op.newText),
468
+ editLine: op.editLine,
195
469
  })),
196
470
  });
197
471
  return result;
198
472
  },
199
473
 
200
- renderCall(args: EditParams, theme: ThemeLike, renderCtx: RenderContextLike<EditRenderState>) {
474
+ renderCall(
475
+ args: EditParams & Partial<HashParams>,
476
+ theme: ThemeLike,
477
+ renderCtx: RenderContextLike<EditRenderState>,
478
+ ) {
201
479
  resolveBaseBackground(theme);
202
480
  const fp = args?.path ?? args?.file_path ?? "";
203
481
  const operations = getEditOperations(args);
@@ -208,8 +486,14 @@ export function registerEditTool(
208
486
  )
209
487
  )
210
488
  return text;
211
- const hdr = `${theme.fg("toolTitle", theme.bold("edit"))} ${theme.fg("dim", sp(fp))}`;
489
+ const hdr = `${formatToolCallTitle(theme, "edit", renderCtx)} ${theme.fg("dim", sp(fp))}`;
212
490
 
491
+ if (Array.isArray(args.edits) && args.edits.some((edit) => "pos" in edit)) {
492
+ text.setText(
493
+ fillToolBackground(dotJoin([hdr, theme.fg("muted", `${args.edits.length} operations`)])),
494
+ );
495
+ return text;
496
+ }
213
497
  if (operations.length === 0) {
214
498
  text.setText(fillToolBackground(hdr));
215
499
  return text;
@@ -222,6 +506,7 @@ export function registerEditTool(
222
506
  [
223
507
  hdr,
224
508
  operations.length > 1 && theme.fg("muted", `${operations.length} edits`),
509
+ theme.fg("muted", "estimate"),
225
510
  coloredSummary,
226
511
  ],
227
512
  paint,
@@ -287,7 +572,7 @@ export function registerEditTool(
287
572
  if (renderCtx.state._edk !== key) {
288
573
  renderCtx.state._edk = key;
289
574
  // ponytail: call already shows `edit <file> <summary>`; don't repeat summary+loc header — gutter carries absolute line
290
- renderCtx.state._edt = theme.fg("muted", " rendering diff…");
575
+ renderCtx.state._edt = `${BODY_PAD}${theme.fg("muted", "rendering diff…")}`;
291
576
  const dc = resolveDiffColors(theme);
292
577
  const diff = parseDiff(
293
578
  d.oldContent as string,
@@ -303,11 +588,11 @@ export function registerEditTool(
303
588
  })
304
589
  .catch(() => {
305
590
  if (renderCtx.state._edk !== key) return;
306
- renderCtx.state._edt = ` ${d.summary}`;
591
+ renderCtx.state._edt = `${BODY_PAD}${d.summary}`;
307
592
  renderCtx.invalidate();
308
593
  });
309
594
  }
310
- text.setText(renderCtx.state._edt ?? ` ${d.summary}`);
595
+ text.setText(renderCtx.state._edt ?? `${BODY_PAD}${d.summary}`);
311
596
  return isPartial ? text : completed();
312
597
  }
313
598
 
@@ -318,7 +603,7 @@ export function registerEditTool(
318
603
  if (renderCtx.state._edk !== key) {
319
604
  renderCtx.state._edk = key;
320
605
  // ponytail: call already shows summary; render diffs directly
321
- renderCtx.state._edt = theme.fg("muted", " rendering diff…");
606
+ renderCtx.state._edt = `${BODY_PAD}${theme.fg("muted", "rendering diff…")}`;
322
607
  const dc = resolveDiffColors(theme);
323
608
  Promise.all(
324
609
  (
@@ -335,23 +620,25 @@ export function registerEditTool(
335
620
  )
336
621
  .then((rendered) => {
337
622
  if (renderCtx.state._edk !== key) return;
338
- const body = rendered.join(`\n${theme.fg("muted", " ···")}\n`);
623
+ const body = rendered.join(`\n${`${BODY_PAD}${theme.fg("muted", "···")}`}\n`);
339
624
  renderCtx.state._edt = body;
340
625
  renderCtx.invalidate();
341
626
  })
342
627
  .catch(() => {
343
628
  if (renderCtx.state._edk !== key) return;
344
- renderCtx.state._edt = ` ${d.editCount} edits ${d.summary}`;
629
+ renderCtx.state._edt = `${BODY_PAD}${d.editCount} edits ${d.summary}`;
345
630
  renderCtx.invalidate();
346
631
  });
347
632
  }
348
- text.setText(renderCtx.state._edt ?? ` ${d.editCount} edits ${d.summary}`);
633
+ text.setText(renderCtx.state._edt ?? `${BODY_PAD}${d.editCount} edits ${d.summary}`);
349
634
  return isPartial ? text : completed();
350
635
  }
351
636
 
352
637
  const fallback = result.content?.[0];
353
638
  const fallbackText = fallback && isTextContent(fallback) ? fallback.text : "edited";
354
- text.setText(fillToolBackground(` ${theme.fg("dim", String(fallbackText).slice(0, 120))}`));
639
+ text.setText(
640
+ fillToolBackground(`${BODY_PAD}${theme.fg("dim", String(fallbackText).slice(0, 120))}`),
641
+ );
355
642
  return isPartial ? text : completed();
356
643
  },
357
644
  });
package/src/extension.ts CHANGED
@@ -9,11 +9,13 @@ import { CursorStore, fffState } from "@xynogen/pix-pretty/fff";
9
9
  import { attachResizeListener, trackInvalidator } from "@xynogen/pix-pretty/resize";
10
10
  import type { PiPrettyApi, ToolFactory } from "@xynogen/pix-pretty/types";
11
11
  import { shortPath, viewportTextConstructor } from "@xynogen/pix-pretty/utils";
12
+ import { initHashline } from "@xynogen/pix-runtime/hashline";
12
13
  import { once } from "@xynogen/pix-runtime/once";
13
14
  import { homeDir } from "@xynogen/pix-runtime/paths";
14
15
  import { registerEditTool } from "./edit.ts";
15
16
 
16
- export default function pixEditExtension(pi: ExtensionAPI): void {
17
+ export default async function pixEditExtension(pi: ExtensionAPI): Promise<void> {
18
+ await initHashline();
17
19
  const prettyPi = pi as unknown as PiPrettyApi;
18
20
  once(pi, "pix-edit", () => {
19
21
  const createEditTool = (createEditToolDefinition ??
@@ -0,0 +1,47 @@
1
+ import assert from "node:assert/strict";
2
+ import { mkdtemp, readFile, writeFile } from "node:fs/promises";
3
+ import { join } from "node:path";
4
+ import { createRequire } from "node:module";
5
+
6
+ const require = createRequire(import.meta.resolve("@earendil-works/pi-coding-agent"));
7
+ const { createJiti } = require("jiti");
8
+
9
+ const jiti = createJiti(import.meta.url, { moduleCache: false });
10
+ const { tempDir } = await jiti.import("@xynogen/pix-runtime/paths");
11
+ const cwd = await mkdtemp(join(tempDir(), "hashline-node-"));
12
+ const file = join(cwd, "sample.ts");
13
+ await writeFile(file, "const retries = 2;\nawait connect();\n");
14
+ const tools = new Map();
15
+ const pi = { registerTool: (tool) => tools.set(tool.name, tool) };
16
+ const readExtension = await jiti.import("../../pix-read/src/extension.ts", { default: true });
17
+ const editExtension = await jiti.import("./extension.ts", { default: true });
18
+ await readExtension(pi);
19
+ await editExtension(pi);
20
+ const state = globalThis.__pixHashline;
21
+ assert.equal(typeof state.h32, "function");
22
+ const read = tools.get("read");
23
+ const edit = tools.get("edit");
24
+ const result = await read.execute("read", { path: file }, undefined, undefined, { cwd });
25
+ assert.equal(result.isError, undefined);
26
+ const pos = result.content[0].text.split("|")[0];
27
+ assert.match(pos, /^1#[0-9A-F]{3}$/);
28
+ assert.equal(result.details.content, "const retries = 2;\nawait connect();");
29
+ const changed = await edit.execute("edit", {
30
+ path: file,
31
+ edits: [{ op: "replace", pos, lines: ["const retries = 5;"] }],
32
+ }, undefined, undefined, { cwd });
33
+ assert.equal(changed.isError, undefined);
34
+ assert.equal(await readFile(file, "utf8"), "const retries = 5;\nawait connect();\n");
35
+ assert.equal(changed.details.editLine, 1);
36
+ const theme = { fg: (_role, text) => text, bold: (text) => text };
37
+ let notify;
38
+ const rendered = new Promise((resolve) => { notify = resolve; });
39
+ const context = { state: {}, expanded: true, isError: false, invalidate: () => notify() };
40
+ const component = edit.renderResult(changed, { isPartial: false }, theme, context);
41
+ await rendered;
42
+ edit.renderResult(changed, { isPartial: false }, theme, { ...context, lastComponent: component });
43
+ const text = component.render(120).join("\n");
44
+ assert.match(text, /retries/);
45
+ assert.match(text, /- -/);
46
+ assert.equal(globalThis.__pixHashline, state);
47
+ console.log("Node Pi extension smoke passed: anchored read, edit, expanded diff, shared WASM.");