@xynogen/pix-edit 0.2.7 → 0.2.9

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.9",
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,258 @@ 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:
150
+ "Fallback only after a hash-anchor edit fails. Exact current source text; must match once.",
151
+ }),
152
+ newText: Type.String({ description: "Replacement text. Empty string deletes." }),
153
+ },
154
+ { additionalProperties: false },
155
+ ),
156
+ { minItems: 1 },
157
+ ),
158
+ ],
159
+ {
160
+ description:
161
+ "Try hash-anchor edits first. Use exact-text edits only after a hash-anchor edit fails. Never mix formats.",
162
+ },
163
+ ),
164
+ },
165
+ { additionalProperties: false },
166
+ );
167
+
168
+ export function prepareHashArguments(input: unknown): unknown {
169
+ if (!input || typeof input !== "object" || Array.isArray(input)) return input;
170
+ const args = { ...input } as Record<string, unknown>;
171
+ if (typeof args.edits === "string") args.edits = JSON.parse(args.edits);
172
+ if (args.edits && typeof args.edits === "object" && !Array.isArray(args.edits))
173
+ args.edits = [args.edits];
174
+ return args;
175
+ }
176
+
177
+ export function editPath(path: string, cwd: string): string {
178
+ let value = path.replace(/[\u00A0\u2000-\u200A\u202F\u205F\u3000]/g, " ").replace(/^@/, "");
179
+ if (
180
+ process.platform === "win32" &&
181
+ value.startsWith("/") &&
182
+ !value.startsWith("//") &&
183
+ !value.includes("\\")
184
+ ) {
185
+ value = value.replace(
186
+ /^\/(?:mnt\/|cygdrive\/)?([a-z])(?:\/(.*))?$/i,
187
+ (_all, drive: string, tail: string | undefined) =>
188
+ `${drive.toUpperCase()}:\\${(tail ?? "").replaceAll("/", "\\")}`,
189
+ );
190
+ }
191
+ value = expandHome(value);
192
+ if (value.startsWith("file://")) value = fileURLToPath(value);
193
+ return resolve(cwd, value);
194
+ }
195
+
196
+ function applyHashEdits(bytes: Buffer, input: unknown) {
197
+ const args = prepareHashArguments(input) as HashParams;
198
+ if (
199
+ !args ||
200
+ typeof args.path !== "string" ||
201
+ !args.path ||
202
+ !Array.isArray(args.edits) ||
203
+ !args.edits.length
204
+ )
205
+ throw new Error("Invalid hashline edit input");
206
+ if (Object.keys(args).some((key) => !["path", "edits"].includes(key)))
207
+ throw new Error("Legacy exact-text fields are not supported");
208
+ const source = decodeLines(bytes);
209
+ const check = (value: unknown) => {
210
+ const parsed = parseAnchor(value);
211
+ const line = source.lines[parsed.line - 1];
212
+ if (!line) throw new Error(`Anchor out of bounds: ${String(value)}`);
213
+ if (hashLine(line.text) !== parsed.hash)
214
+ throw new Error(`Stale anchor: ${String(value)}. Read the file again.`);
215
+ return parsed.line;
216
+ };
217
+ const replacements: Array<{ start: number; end: number; lines: string[] }> = [];
218
+ const gaps = new Map<number, string[]>();
219
+ for (const edit of args.edits) {
220
+ if (
221
+ !edit ||
222
+ typeof edit !== "object" ||
223
+ Object.keys(edit).some((key) => !["op", "pos", "end", "lines"].includes(key))
224
+ )
225
+ throw new Error("Legacy or invalid edit fields");
226
+ if (
227
+ !["replace", "insert_before", "insert_after"].includes(edit.op) ||
228
+ !Array.isArray(edit.lines) ||
229
+ edit.lines.some(
230
+ (line) =>
231
+ typeof line !== "string" ||
232
+ /[\r\n\0]|^[1-9]\d*#[0-9A-F]{3}\|/.test(line) ||
233
+ /[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/u.test(line),
234
+ )
235
+ )
236
+ throw new Error("Invalid edit operation or source lines");
237
+ const start = check(edit.pos);
238
+ if (edit.op === "replace") {
239
+ const end = edit.end === undefined ? start : check(edit.end);
240
+ if (end < start) throw new Error("Reversed replacement range");
241
+ replacements.push({ start, end, lines: edit.lines });
242
+ } else {
243
+ if (edit.end !== undefined) throw new Error("end is only allowed for replace");
244
+ const gap = edit.op === "insert_before" ? start - 1 : start;
245
+ gaps.set(gap, [...(gaps.get(gap) ?? []), ...edit.lines]);
246
+ }
247
+ }
248
+ replacements.sort((a, b) => a.start - b.start);
249
+ for (let i = 0; i < replacements.length; i++) {
250
+ const range = replacements[i]!;
251
+ if (i && replacements[i - 1]!.end >= range.start)
252
+ throw new Error("Overlapping replacement ranges");
253
+ for (const gap of gaps.keys())
254
+ if (gap >= range.start && gap < range.end)
255
+ throw new Error("Insertion overlaps a replacement range");
256
+ }
257
+ const output: SourceLine[] = [];
258
+ const ops: Array<EditOperation & { editLine: number }> = [];
259
+ const append = (lines: string[]) =>
260
+ output.push(...lines.map((text) => ({ text, ending: source.delimiter })));
261
+ let rangeIndex = 0;
262
+ for (let gap = 0; gap <= source.lines.length; ) {
263
+ const insertion = gaps.get(gap);
264
+ if (insertion?.length) {
265
+ const context = source.lines[Math.max(0, gap - 1)]!.text;
266
+ ops.push({
267
+ oldText: context,
268
+ newText:
269
+ gap === 0 ? [...insertion, context].join("\n") : [context, ...insertion].join("\n"),
270
+ editLine: Math.max(1, output.length + (gap === 0 ? 1 : 0)),
271
+ });
272
+ append(insertion);
273
+ }
274
+ if (gap === source.lines.length) break;
275
+ const range = replacements[rangeIndex];
276
+ if (range?.start === gap + 1) {
277
+ ops.push({
278
+ oldText: source.lines
279
+ .slice(gap, range.end)
280
+ .map((line) => line.text)
281
+ .join("\n"),
282
+ newText: range.lines.join("\n"),
283
+ editLine: output.length + 1,
284
+ });
285
+ append(range.lines);
286
+ gap = range.end;
287
+ rangeIndex++;
288
+ } else {
289
+ output.push({ ...source.lines[gap]! });
290
+ gap++;
291
+ }
292
+ }
293
+ for (let i = 0; i < output.length; i++) {
294
+ if (i === output.length - 1)
295
+ output[i]!.ending = source.finalNewline ? output[i]!.ending || source.delimiter : "";
296
+ else if (!output[i]!.ending) output[i]!.ending = source.delimiter;
93
297
  }
298
+ return { content: source.bom + output.map((line) => line.text + line.ending).join(""), ops };
299
+ }
300
+
301
+ function applyExactEdits(bytes: Buffer, args: ExactParams) {
302
+ if (Object.keys(args).some((key) => !["path", "edits"].includes(key)))
303
+ throw new Error("Invalid exact-text edit fields");
304
+ const source = decodeLines(bytes);
305
+ const original = source.lines.map((line) => line.text + line.ending).join("");
306
+ // ponytail: exact bytes only. Add newline normalization only if callers need it.
307
+ const ranges = args.edits
308
+ .map((edit) => {
309
+ if (
310
+ !edit ||
311
+ typeof edit !== "object" ||
312
+ Object.keys(edit).some((key) => !["oldText", "newText"].includes(key)) ||
313
+ typeof edit.oldText !== "string" ||
314
+ !edit.oldText ||
315
+ typeof edit.newText !== "string" ||
316
+ [edit.oldText, edit.newText].some((text) =>
317
+ /\0|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/u.test(text),
318
+ )
319
+ )
320
+ throw new Error("Invalid exact-text edit");
321
+ const start = original.indexOf(edit.oldText);
322
+ if (start < 0) throw new Error("oldText was not found. Use exact source text.");
323
+ if (original.indexOf(edit.oldText, start + 1) >= 0)
324
+ throw new Error("oldText matches more than once. Include more context.");
325
+ return { ...edit, start, end: start + edit.oldText.length };
326
+ })
327
+ .sort((a, b) => a.start - b.start);
328
+ let content = "";
329
+ let offset = 0;
330
+ const ops: Array<EditOperation & { editLine: number }> = [];
331
+ for (const range of ranges) {
332
+ if (range.start < offset) throw new Error("Overlapping exact-text edits");
333
+ content += original.slice(offset, range.start);
334
+ ops.push({
335
+ oldText: range.oldText,
336
+ newText: range.newText,
337
+ editLine: (content.match(/\r\n|\r|\n/g)?.length ?? 0) + 1,
338
+ });
339
+ content += range.newText;
340
+ offset = range.end;
341
+ }
342
+ return { content: source.bom + content + original.slice(offset), ops };
94
343
  }
95
344
 
96
345
  export function summarizeEditOperations(operations: EditOperation[]) {
@@ -119,31 +368,59 @@ export function registerEditTool(
119
368
  pi.registerTool({
120
369
  ...origEdit,
121
370
  name: "edit",
122
- // The edit description and schema already carry these rules. Drop the <rules> copy (~110 tokens/turn).
123
- promptGuidelines: [],
371
+ description:
372
+ "Try hash anchors {op,pos,end?,lines} from read first. Only after a hash-anchor edit fails, use exact text {oldText,newText} from current source; oldText must match once. Never mix formats. 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.",
373
+ parameters: editSchema,
374
+ promptSnippet: "Edit with hash anchors first; exact text only after failure",
375
+ promptGuidelines: [
376
+ "For edit, try hash anchors from read first. Only if the hash-anchor edit fails, fall back to oldText/newText. If the file changed, read the affected region again before using current source text; never guess anchors or overwrite unseen changes.",
377
+ ],
378
+ prepareArguments: prepareHashArguments,
379
+ constrainedSampling: { type: "json_schema", strict: "prefer" },
124
380
  renderShell: "self",
125
381
 
126
382
  async execute(
127
- tid: string,
128
- params: EditParams,
383
+ _tid: string,
384
+ params: EditInput,
129
385
  sig: AbortSignal | undefined,
130
- upd: AgentToolUpdateCallback<unknown> | undefined,
386
+ _upd: AgentToolUpdateCallback<unknown> | undefined,
131
387
  toolCtx: ExtensionContext,
132
388
  ) {
133
- const fp = params.path ?? params.file_path ?? "";
134
- const operations = getEditOperations(params);
389
+ const fp = typeof params?.path === "string" ? params.path : "";
390
+ let operations: Array<EditOperation & { editLine: number }> = [];
135
391
  const fileLang = lang(fp);
136
392
 
137
393
  let result: ToolResultLike;
138
394
  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;
395
+ if (!fp) throw new Error("path must be a nonempty string");
396
+ const absolutePath = editPath(fp, toolCtx?.cwd || cwd);
397
+ result = await withFileMutationQueue(absolutePath, async () => {
398
+ const abort = () => {
399
+ if (sig?.aborted) throw new Error("Operation aborted");
400
+ };
401
+ abort();
402
+ await access(absolutePath, constants.R_OK | constants.W_OK);
403
+ abort();
404
+ const bytes = await readFile(absolutePath);
405
+ abort();
406
+ const args = prepareHashArguments(params) as EditInput;
407
+ if (!Array.isArray(args.edits) || !args.edits.length)
408
+ throw new Error("edits must be a nonempty array");
409
+ const applied = args.edits.every(
410
+ (edit) => edit && typeof edit === "object" && "oldText" in edit,
411
+ )
412
+ ? applyExactEdits(bytes, args as ExactParams)
413
+ : applyHashEdits(bytes, args);
414
+ operations = applied.ops;
415
+ abort();
416
+ // ponytail: in-place writes preserve links and mode, not crash atomicity. Use a separate atomic-write design if needed.
417
+ await writeFile(absolutePath, applied.content, "utf8");
418
+ abort();
419
+ return {
420
+ content: [{ type: "text", text: `Edited ${fp}: ${operations.length} operations.` }],
421
+ details: undefined,
422
+ };
423
+ });
147
424
  } catch (error) {
148
425
  const text = getErrorMessage(error);
149
426
  if (sig?.aborted || /aborted/i.test(text)) throw error;
@@ -172,7 +449,7 @@ export function registerEditTool(
172
449
  setResultDetails(result, {
173
450
  _type: "editInfo",
174
451
  summary,
175
- editLine: opEditLine(fp, op0.newText),
452
+ editLine: op0.editLine,
176
453
  oldContent: op0.oldText,
177
454
  newContent: op0.newText,
178
455
  language: fileLang,
@@ -191,13 +468,17 @@ export function registerEditTool(
191
468
  newContent: op.newText,
192
469
  language: fileLang,
193
470
  filePath: fp,
194
- editLine: opEditLine(fp, op.newText),
471
+ editLine: op.editLine,
195
472
  })),
196
473
  });
197
474
  return result;
198
475
  },
199
476
 
200
- renderCall(args: EditParams, theme: ThemeLike, renderCtx: RenderContextLike<EditRenderState>) {
477
+ renderCall(
478
+ args: EditParams & Partial<HashParams>,
479
+ theme: ThemeLike,
480
+ renderCtx: RenderContextLike<EditRenderState>,
481
+ ) {
201
482
  resolveBaseBackground(theme);
202
483
  const fp = args?.path ?? args?.file_path ?? "";
203
484
  const operations = getEditOperations(args);
@@ -208,8 +489,14 @@ export function registerEditTool(
208
489
  )
209
490
  )
210
491
  return text;
211
- const hdr = `${theme.fg("toolTitle", theme.bold("edit"))} ${theme.fg("dim", sp(fp))}`;
492
+ const hdr = `${formatToolCallTitle(theme, "edit", renderCtx)} ${theme.fg("dim", sp(fp))}`;
212
493
 
494
+ if (Array.isArray(args.edits) && args.edits.some((edit) => "pos" in edit)) {
495
+ text.setText(
496
+ fillToolBackground(dotJoin([hdr, theme.fg("muted", `${args.edits.length} operations`)])),
497
+ );
498
+ return text;
499
+ }
213
500
  if (operations.length === 0) {
214
501
  text.setText(fillToolBackground(hdr));
215
502
  return text;
@@ -222,6 +509,7 @@ export function registerEditTool(
222
509
  [
223
510
  hdr,
224
511
  operations.length > 1 && theme.fg("muted", `${operations.length} edits`),
512
+ theme.fg("muted", "estimate"),
225
513
  coloredSummary,
226
514
  ],
227
515
  paint,
@@ -287,7 +575,7 @@ export function registerEditTool(
287
575
  if (renderCtx.state._edk !== key) {
288
576
  renderCtx.state._edk = key;
289
577
  // 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…");
578
+ renderCtx.state._edt = `${BODY_PAD}${theme.fg("muted", "rendering diff…")}`;
291
579
  const dc = resolveDiffColors(theme);
292
580
  const diff = parseDiff(
293
581
  d.oldContent as string,
@@ -303,11 +591,11 @@ export function registerEditTool(
303
591
  })
304
592
  .catch(() => {
305
593
  if (renderCtx.state._edk !== key) return;
306
- renderCtx.state._edt = ` ${d.summary}`;
594
+ renderCtx.state._edt = `${BODY_PAD}${d.summary}`;
307
595
  renderCtx.invalidate();
308
596
  });
309
597
  }
310
- text.setText(renderCtx.state._edt ?? ` ${d.summary}`);
598
+ text.setText(renderCtx.state._edt ?? `${BODY_PAD}${d.summary}`);
311
599
  return isPartial ? text : completed();
312
600
  }
313
601
 
@@ -318,7 +606,7 @@ export function registerEditTool(
318
606
  if (renderCtx.state._edk !== key) {
319
607
  renderCtx.state._edk = key;
320
608
  // ponytail: call already shows summary; render diffs directly
321
- renderCtx.state._edt = theme.fg("muted", " rendering diff…");
609
+ renderCtx.state._edt = `${BODY_PAD}${theme.fg("muted", "rendering diff…")}`;
322
610
  const dc = resolveDiffColors(theme);
323
611
  Promise.all(
324
612
  (
@@ -335,23 +623,25 @@ export function registerEditTool(
335
623
  )
336
624
  .then((rendered) => {
337
625
  if (renderCtx.state._edk !== key) return;
338
- const body = rendered.join(`\n${theme.fg("muted", " ···")}\n`);
626
+ const body = rendered.join(`\n${`${BODY_PAD}${theme.fg("muted", "···")}`}\n`);
339
627
  renderCtx.state._edt = body;
340
628
  renderCtx.invalidate();
341
629
  })
342
630
  .catch(() => {
343
631
  if (renderCtx.state._edk !== key) return;
344
- renderCtx.state._edt = ` ${d.editCount} edits ${d.summary}`;
632
+ renderCtx.state._edt = `${BODY_PAD}${d.editCount} edits ${d.summary}`;
345
633
  renderCtx.invalidate();
346
634
  });
347
635
  }
348
- text.setText(renderCtx.state._edt ?? ` ${d.editCount} edits ${d.summary}`);
636
+ text.setText(renderCtx.state._edt ?? `${BODY_PAD}${d.editCount} edits ${d.summary}`);
349
637
  return isPartial ? text : completed();
350
638
  }
351
639
 
352
640
  const fallback = result.content?.[0];
353
641
  const fallbackText = fallback && isTextContent(fallback) ? fallback.text : "edited";
354
- text.setText(fillToolBackground(` ${theme.fg("dim", String(fallbackText).slice(0, 120))}`));
642
+ text.setText(
643
+ fillToolBackground(`${BODY_PAD}${theme.fg("dim", String(fallbackText).slice(0, 120))}`),
644
+ );
355
645
  return isPartial ? text : completed();
356
646
  },
357
647
  });
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.");