@xynogen/pix-edit 0.2.5 → 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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 xynogen
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -28,22 +28,22 @@ Set `collapse.tools.edit: false` to disable for this tool only. See `@xynogen/pi
28
28
  pi install npm:@xynogen/pix-edit
29
29
  ```
30
30
 
31
- > Also included in [`@xynogen/pix-core`](https://www.npmjs.com/package/@xynogen/pix-core):
32
- >
33
- > ```bash
34
- > pi install npm:@xynogen/pix-core
35
- > ```
31
+ > Bundled in [`@xynogen/pix-core`](https://www.npmjs.com/package/@xynogen/pix-core). Install it alone only if you do not use pix-core.
36
32
 
37
33
  ## Full distro
38
34
 
39
- Source: [github.com/xynogen/pix-mono](https://github.com/xynogen/pix-mono)
40
-
41
- To install the complete pix suite (all packages + Pi itself):
35
+ This package is part of [Pix](https://github.com/xynogen/pix-mono). The installer sets up Pi and the full distro. See [Install](https://github.com/xynogen/pix-mono#install) for the notes for each OS.
42
36
 
43
37
  ```bash
38
+ # Linux / macOS
44
39
  curl -fsSL https://raw.githubusercontent.com/xynogen/pix-mono/main/scripts/install.sh | sh
45
40
  ```
46
41
 
42
+ ```powershell
43
+ # Windows
44
+ irm https://raw.githubusercontent.com/xynogen/pix-mono/main/scripts/install.ps1 | iex
45
+ ```
46
+
47
47
  ## License
48
48
 
49
49
  MIT
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@xynogen/pix-edit",
3
- "version": "0.2.5",
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.8.0"
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,9 +32,12 @@ 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,
40
+ getErrorMessage,
34
41
  getTextContent,
35
42
  hideCollapsedToolCall,
36
43
  isTextContent,
@@ -41,6 +48,9 @@ import {
41
48
  unframeToolResult,
42
49
  } from "@xynogen/pix-pretty/utils";
43
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";
44
54
 
45
55
  // ── Helpers ────────────────────────────────────────────────────────────
46
56
 
@@ -78,18 +88,257 @@ export function getEditOperations(input: EditParams): EditOperation[] {
78
88
  return oldText && oldText !== newText ? [{ oldText, newText }] : [];
79
89
  }
80
90
 
81
- // 1-based file line where `needle` begins post-edit, for absolute diff gutters.
82
- // 0 = file unreadable or needle not found (renderer falls back to relative).
83
- // Duplicate identical edits collapse to the first match — acceptable.
84
- function opEditLine(filePath: string, needle: string): number {
85
- try {
86
- if (!filePath || !existsSync(filePath)) return 0;
87
- const f = readFileSync(filePath, "utf-8");
88
- const idx = f.indexOf(needle);
89
- return idx >= 0 ? f.slice(0, idx).split("\n").length : 0;
90
- } catch {
91
- 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;
92
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 };
93
342
  }
94
343
 
95
344
  export function summarizeEditOperations(operations: EditOperation[]) {
@@ -118,31 +367,59 @@ export function registerEditTool(
118
367
  pi.registerTool({
119
368
  ...origEdit,
120
369
  name: "edit",
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",
374
+ promptGuidelines: [],
375
+ prepareArguments: prepareHashArguments,
376
+ constrainedSampling: { type: "json_schema", strict: "prefer" },
121
377
  renderShell: "self",
122
378
 
123
379
  async execute(
124
- tid: string,
125
- params: EditParams,
380
+ _tid: string,
381
+ params: EditInput,
126
382
  sig: AbortSignal | undefined,
127
- upd: AgentToolUpdateCallback<unknown> | undefined,
383
+ _upd: AgentToolUpdateCallback<unknown> | undefined,
128
384
  toolCtx: ExtensionContext,
129
385
  ) {
130
- const fp = params.path ?? params.file_path ?? "";
131
- const operations = getEditOperations(params);
386
+ const fp = typeof params?.path === "string" ? params.path : "";
387
+ let operations: Array<EditOperation & { editLine: number }> = [];
132
388
  const fileLang = lang(fp);
133
389
 
134
390
  let result: ToolResultLike;
135
391
  try {
136
- result = (await origEdit.execute(
137
- tid,
138
- // SAFETY: EditParams preserves the built-in edit schema and only adds legacy aliases.
139
- params as unknown as Parameters<typeof origEdit.execute>[1],
140
- sig,
141
- upd,
142
- toolCtx,
143
- )) 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
+ });
144
421
  } catch (error) {
145
- const text = error instanceof Error ? error.message : String(error);
422
+ const text = getErrorMessage(error);
146
423
  if (sig?.aborted || /aborted/i.test(text)) throw error;
147
424
  return {
148
425
  content: [{ type: "text" as const, text }],
@@ -169,7 +446,7 @@ export function registerEditTool(
169
446
  setResultDetails(result, {
170
447
  _type: "editInfo",
171
448
  summary,
172
- editLine: opEditLine(fp, op0.newText),
449
+ editLine: op0.editLine,
173
450
  oldContent: op0.oldText,
174
451
  newContent: op0.newText,
175
452
  language: fileLang,
@@ -188,13 +465,17 @@ export function registerEditTool(
188
465
  newContent: op.newText,
189
466
  language: fileLang,
190
467
  filePath: fp,
191
- editLine: opEditLine(fp, op.newText),
468
+ editLine: op.editLine,
192
469
  })),
193
470
  });
194
471
  return result;
195
472
  },
196
473
 
197
- renderCall(args: EditParams, theme: ThemeLike, renderCtx: RenderContextLike<EditRenderState>) {
474
+ renderCall(
475
+ args: EditParams & Partial<HashParams>,
476
+ theme: ThemeLike,
477
+ renderCtx: RenderContextLike<EditRenderState>,
478
+ ) {
198
479
  resolveBaseBackground(theme);
199
480
  const fp = args?.path ?? args?.file_path ?? "";
200
481
  const operations = getEditOperations(args);
@@ -205,8 +486,14 @@ export function registerEditTool(
205
486
  )
206
487
  )
207
488
  return text;
208
- 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))}`;
209
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
+ }
210
497
  if (operations.length === 0) {
211
498
  text.setText(fillToolBackground(hdr));
212
499
  return text;
@@ -219,6 +506,7 @@ export function registerEditTool(
219
506
  [
220
507
  hdr,
221
508
  operations.length > 1 && theme.fg("muted", `${operations.length} edits`),
509
+ theme.fg("muted", "estimate"),
222
510
  coloredSummary,
223
511
  ],
224
512
  paint,
@@ -284,7 +572,7 @@ export function registerEditTool(
284
572
  if (renderCtx.state._edk !== key) {
285
573
  renderCtx.state._edk = key;
286
574
  // ponytail: call already shows `edit <file> <summary>`; don't repeat summary+loc header — gutter carries absolute line
287
- renderCtx.state._edt = theme.fg("muted", " rendering diff…");
575
+ renderCtx.state._edt = `${BODY_PAD}${theme.fg("muted", "rendering diff…")}`;
288
576
  const dc = resolveDiffColors(theme);
289
577
  const diff = parseDiff(
290
578
  d.oldContent as string,
@@ -300,11 +588,11 @@ export function registerEditTool(
300
588
  })
301
589
  .catch(() => {
302
590
  if (renderCtx.state._edk !== key) return;
303
- renderCtx.state._edt = ` ${d.summary}`;
591
+ renderCtx.state._edt = `${BODY_PAD}${d.summary}`;
304
592
  renderCtx.invalidate();
305
593
  });
306
594
  }
307
- text.setText(renderCtx.state._edt ?? ` ${d.summary}`);
595
+ text.setText(renderCtx.state._edt ?? `${BODY_PAD}${d.summary}`);
308
596
  return isPartial ? text : completed();
309
597
  }
310
598
 
@@ -315,7 +603,7 @@ export function registerEditTool(
315
603
  if (renderCtx.state._edk !== key) {
316
604
  renderCtx.state._edk = key;
317
605
  // ponytail: call already shows summary; render diffs directly
318
- renderCtx.state._edt = theme.fg("muted", " rendering diff…");
606
+ renderCtx.state._edt = `${BODY_PAD}${theme.fg("muted", "rendering diff…")}`;
319
607
  const dc = resolveDiffColors(theme);
320
608
  Promise.all(
321
609
  (
@@ -332,23 +620,25 @@ export function registerEditTool(
332
620
  )
333
621
  .then((rendered) => {
334
622
  if (renderCtx.state._edk !== key) return;
335
- const body = rendered.join(`\n${theme.fg("muted", " ···")}\n`);
623
+ const body = rendered.join(`\n${`${BODY_PAD}${theme.fg("muted", "···")}`}\n`);
336
624
  renderCtx.state._edt = body;
337
625
  renderCtx.invalidate();
338
626
  })
339
627
  .catch(() => {
340
628
  if (renderCtx.state._edk !== key) return;
341
- renderCtx.state._edt = ` ${d.editCount} edits ${d.summary}`;
629
+ renderCtx.state._edt = `${BODY_PAD}${d.editCount} edits ${d.summary}`;
342
630
  renderCtx.invalidate();
343
631
  });
344
632
  }
345
- text.setText(renderCtx.state._edt ?? ` ${d.editCount} edits ${d.summary}`);
633
+ text.setText(renderCtx.state._edt ?? `${BODY_PAD}${d.editCount} edits ${d.summary}`);
346
634
  return isPartial ? text : completed();
347
635
  }
348
636
 
349
637
  const fallback = result.content?.[0];
350
638
  const fallbackText = fallback && isTextContent(fallback) ? fallback.text : "edited";
351
- 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
+ );
352
642
  return isPartial ? text : completed();
353
643
  },
354
644
  });
package/src/extension.ts CHANGED
@@ -4,29 +4,26 @@ import {
4
4
  type EditToolInput,
5
5
  type ExtensionAPI,
6
6
  } from "@earendil-works/pi-coding-agent";
7
+ import { Text } from "@earendil-works/pi-tui";
7
8
  import { CursorStore, fffState } from "@xynogen/pix-pretty/fff";
8
9
  import { attachResizeListener, trackInvalidator } from "@xynogen/pix-pretty/resize";
9
- import type { PiPrettyApi, TextComponentCtor, ToolFactory } from "@xynogen/pix-pretty/types";
10
+ import type { PiPrettyApi, ToolFactory } from "@xynogen/pix-pretty/types";
10
11
  import { shortPath, viewportTextConstructor } from "@xynogen/pix-pretty/utils";
12
+ import { initHashline } from "@xynogen/pix-runtime/hashline";
11
13
  import { once } from "@xynogen/pix-runtime/once";
12
- import { registerEditTool } from "./edit.js";
14
+ import { homeDir } from "@xynogen/pix-runtime/paths";
15
+ import { registerEditTool } from "./edit.ts";
13
16
 
14
- export default function pixEditExtension(pi: ExtensionAPI): void {
17
+ export default async function pixEditExtension(pi: ExtensionAPI): Promise<void> {
18
+ await initHashline();
15
19
  const prettyPi = pi as unknown as PiPrettyApi;
16
20
  once(pi, "pix-edit", () => {
17
21
  const createEditTool = (createEditToolDefinition ??
18
22
  createEditToolFallback) as unknown as ToolFactory<EditToolInput>;
19
23
  if (!createEditTool) return;
20
24
 
21
- let TextComponent: TextComponentCtor;
22
- try {
23
- TextComponent = require("@earendil-works/pi-tui").Text;
24
- } catch {
25
- return;
26
- }
27
-
28
25
  const cwd = process.cwd();
29
- const home = process.env.HOME ?? "";
26
+ const home = homeDir();
30
27
 
31
28
  attachResizeListener();
32
29
 
@@ -36,7 +33,7 @@ export default function pixEditExtension(pi: ExtensionAPI): void {
36
33
  {
37
34
  cwd,
38
35
  sp: (p: string) => shortPath(cwd, home, p),
39
- TextComponent: viewportTextConstructor(TextComponent),
36
+ TextComponent: viewportTextConstructor(Text),
40
37
  fffState,
41
38
  cursorStore: new CursorStore(),
42
39
  },
@@ -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.");
package/src/index.ts CHANGED
@@ -2,4 +2,4 @@ export {
2
2
  getEditOperations,
3
3
  registerEditTool,
4
4
  summarizeEditOperations,
5
- } from "./edit.js";
5
+ } from "./edit.ts";