forked from PrimeIntellect-ai/prime-agent
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathedit.ts
More file actions
533 lines (475 loc) · 17.3 KB
/
Copy pathedit.ts
File metadata and controls
533 lines (475 loc) · 17.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
import type { AgentTool } from "@earendil-works/pi-agent-core";
import { Box, type Component, Container, Spacer, Text, wrapTextWithAnsi } from "@earendil-works/pi-tui";
import { constants } from "fs";
import { access as fsAccess, readFile as fsReadFile, writeFile as fsWriteFile } from "fs/promises";
import { type Static, Type } from "typebox";
import { renderDiff } from "../../modes/interactive/components/diff.js";
import {
countChangedLines,
FILE_CHANGE_DIFF_INDENT,
formatFileChangeSummaryLine,
} from "../../modes/interactive/components/edit-summary.js";
import type { ToolDefinition } from "../extensions/types.js";
import {
applyEditsToNormalizedContent,
computeEditsDiff,
detectLineEnding,
type Edit,
type EditDiffError,
type EditDiffResult,
generateDiffString,
normalizeToLF,
restoreLineEndings,
stripBom,
} from "./edit-diff.js";
import { withFileMutationQueue } from "./file-mutation-queue.js";
import { resolveToCwd } from "./path-utils.js";
import { invalidArgText, shortenPath, str } from "./render-utils.js";
import { wrapToolDefinition } from "./tool-definition-wrapper.js";
type EditPreview = EditDiffResult | EditDiffError;
type EditRenderState = {
callComponent?: EditCallRenderComponent;
};
const replaceEditSchema = Type.Object(
{
oldText: Type.String({
description:
"Exact text for one targeted replacement. It must be unique in the original file and must not overlap with any other edits[].oldText in the same call.",
}),
newText: Type.String({ description: "Replacement text for this targeted edit." }),
},
{ additionalProperties: false },
);
const editSchema = Type.Object(
{
path: Type.String({ description: "Path to the file to edit (relative or absolute)" }),
edits: Type.Array(replaceEditSchema, {
description:
"One or more targeted replacements. Each edit is matched against the original file, not incrementally. Do not include overlapping or nested edits. If two changes touch the same block or nearby lines, merge them into one edit instead.",
}),
},
{ additionalProperties: false },
);
export type EditToolInput = Static<typeof editSchema>;
type LegacyEditToolInput = EditToolInput & {
oldText?: unknown;
newText?: unknown;
};
export interface EditToolDetails {
/** Unified diff of the changes made */
diff: string;
/** Line number of the first change in the new file (for editor navigation) */
firstChangedLine?: number;
}
/**
* Pluggable operations for the edit tool.
* Override these to delegate file editing to remote systems (for example SSH).
*/
export interface EditOperations {
/** Read file contents as a Buffer */
readFile: (absolutePath: string) => Promise<Buffer>;
/** Write content to a file */
writeFile: (absolutePath: string, content: string) => Promise<void>;
/** Check if file is readable and writable (throw if not) */
access: (absolutePath: string) => Promise<void>;
}
const defaultEditOperations: EditOperations = {
readFile: (path) => fsReadFile(path),
writeFile: (path, content) => fsWriteFile(path, content, "utf-8"),
access: (path) => fsAccess(path, constants.R_OK | constants.W_OK),
};
export interface EditToolOptions {
/** Custom operations for file editing. Default: local filesystem */
operations?: EditOperations;
}
function prepareEditArguments(input: unknown): EditToolInput {
if (!input || typeof input !== "object") {
return input as EditToolInput;
}
const args = input as Record<string, unknown>;
// Some models (Opus 4.6, GLM-5.1) send edits as a JSON string instead of an array
if (typeof args.edits === "string") {
try {
const parsed = JSON.parse(args.edits);
if (Array.isArray(parsed)) args.edits = parsed;
} catch {
// Leave non-JSON input for schema validation to reject.
}
}
const legacy = args as LegacyEditToolInput;
if (typeof legacy.oldText !== "string" || typeof legacy.newText !== "string") {
return args as EditToolInput;
}
const edits = Array.isArray(legacy.edits) ? [...legacy.edits] : [];
edits.push({ oldText: legacy.oldText, newText: legacy.newText });
const { oldText: _oldText, newText: _newText, ...rest } = legacy;
return { ...rest, edits } as EditToolInput;
}
function validateEditInput(input: EditToolInput): { path: string; edits: Edit[] } {
if (!Array.isArray(input.edits) || input.edits.length === 0) {
throw new Error("Edit tool input is invalid. edits must contain at least one replacement.");
}
return { path: input.path, edits: input.edits };
}
type RenderableEditArgs = {
path?: string;
file_path?: string;
edits?: Edit[];
oldText?: string;
newText?: string;
};
type EditToolResultLike = {
content: Array<{ type: string; text?: string; data?: string; mimeType?: string }>;
details?: EditToolDetails;
};
type EditCallRenderComponent = Box & {
preview?: EditPreview;
previewArgsKey?: string;
previewPending?: boolean;
settledError?: boolean;
};
function createEditCallRenderComponent(): EditCallRenderComponent {
return Object.assign(new Box(1, 1, (text: string) => text), {
preview: undefined as EditPreview | undefined,
previewArgsKey: undefined as string | undefined,
previewPending: false,
settledError: false,
});
}
function getEditCallRenderComponent(state: EditRenderState, lastComponent: unknown): EditCallRenderComponent {
if (lastComponent instanceof Box) {
const component = lastComponent as EditCallRenderComponent;
state.callComponent = component;
return component;
}
if (state.callComponent) {
return state.callComponent;
}
const component = createEditCallRenderComponent();
state.callComponent = component;
return component;
}
function getRenderablePreviewInput(args: RenderableEditArgs | undefined): { path: string; edits: Edit[] } | null {
if (!args) {
return null;
}
const path = typeof args.path === "string" ? args.path : typeof args.file_path === "string" ? args.file_path : null;
if (!path) {
return null;
}
if (
Array.isArray(args.edits) &&
args.edits.length > 0 &&
args.edits.every((edit) => typeof edit?.oldText === "string" && typeof edit?.newText === "string")
) {
return { path, edits: args.edits };
}
if (typeof args.oldText === "string" && typeof args.newText === "string") {
return { path, edits: [{ oldText: args.oldText, newText: args.newText }] };
}
return null;
}
function formatEditCall(
args: RenderableEditArgs | undefined,
theme: typeof import("../../modes/interactive/theme/theme.js").theme,
): string {
const invalidArg = invalidArgText(theme);
const rawPath = str(args?.file_path ?? args?.path);
const path = rawPath !== null ? shortenPath(rawPath) : null;
const pathDisplay = path === null ? invalidArg : path ? theme.fg("accent", path) : theme.fg("toolOutput", "...");
return `${theme.fg("toolTitle", theme.bold("edit"))} ${pathDisplay}`;
}
function formatEditResult(
args: RenderableEditArgs | undefined,
preview: EditPreview | undefined,
result: EditToolResultLike,
theme: typeof import("../../modes/interactive/theme/theme.js").theme,
isError: boolean,
): string | undefined {
const rawPath = str(args?.file_path ?? args?.path);
const previewDiff = preview && !("error" in preview) ? preview.diff : undefined;
const previewError = preview && "error" in preview ? preview.error : undefined;
if (isError) {
const errorText = result.content
.filter((c) => c.type === "text")
.map((c) => c.text || "")
.join("\n");
if (!errorText || errorText === previewError) {
return undefined;
}
return theme.fg("error", errorText);
}
const resultDiff = result.details?.diff;
if (resultDiff && resultDiff !== previewDiff) {
return renderDiff(resultDiff, { filePath: rawPath ?? undefined });
}
return undefined;
}
function getEditHeaderBg(
preview: EditPreview | undefined,
settledError: boolean | undefined,
theme: typeof import("../../modes/interactive/theme/theme.js").theme,
): (text: string) => string {
if (settledError || (preview && "error" in preview)) {
return (text: string) => theme.bg("toolErrorBg", text);
}
if (preview) {
return (text: string) => theme.bg("toolSuccessBg", text);
}
return (text: string) => theme.bg("toolPendingBg", text);
}
// Width-aware `╰─ <path> +N -M` summary plus optional indented diff rows: the
// summary truncates to one row and wrapped diff lines keep the indent column.
class EditChangeSummaryComponent implements Component {
constructor(
private readonly rawPath: string,
private readonly cwd: string,
private readonly change: { added: number; removed: number },
private readonly diffsExpanded: boolean | undefined,
private readonly diffLines: readonly string[] | undefined,
) {}
render(width: number): string[] {
const safeWidth = Math.max(1, width);
const lines = [formatFileChangeSummaryLine(this.rawPath, this.cwd, this.change, this.diffsExpanded, safeWidth)];
if (this.diffLines !== undefined) {
const indent = FILE_CHANGE_DIFF_INDENT.slice(0, Math.max(0, safeWidth - 1));
const contentWidth = Math.max(1, safeWidth - indent.length);
for (const line of this.diffLines) {
for (const row of wrapTextWithAnsi(line, contentWidth)) {
lines.push(`${indent}${row}`);
}
}
}
return lines;
}
invalidate(): void {}
}
function buildEditCallComponent(
component: EditCallRenderComponent,
args: RenderableEditArgs | undefined,
theme: typeof import("../../modes/interactive/theme/theme.js").theme,
expanded: boolean,
cwd: string,
): EditCallRenderComponent {
component.setBgFn(getEditHeaderBg(component.preview, component.settledError, theme));
component.clear();
component.addChild(new Text(formatEditCall(args, theme), 0, 0));
if (component.preview && "error" in component.preview) {
component.addChild(new Spacer(1));
component.addChild(new Text(theme.fg("error", component.preview.error), 0, 0));
return component;
}
// A failed execution must not present the predicted diff as applied changes.
if (!component.preview || component.settledError) {
return component;
}
// The `╰─ <path> +N -M` summary line renders in both states; ctrl+j only
// attaches or removes the indented diff lines underneath it.
const rawPath = str(args?.file_path ?? args?.path);
const change = countChangedLines(component.preview.diff);
component.addChild(new Spacer(1));
component.addChild(
new EditChangeSummaryComponent(
rawPath ?? "...",
cwd,
change,
// The ctrl+j hint renders on every edit summary row (unlike the ctrl+o
// hint, which the latest tool row owns), matching thinking and
// agent-message hints.
expanded,
expanded ? renderDiff(component.preview.diff).split("\n") : undefined,
),
);
return component;
}
function setEditPreview(
component: EditCallRenderComponent,
preview: EditPreview,
argsKey: string | undefined,
): boolean {
const current = component.preview;
const changed =
current === undefined ||
("error" in current && "error" in preview
? current.error !== preview.error
: "error" in current !== "error" in preview) ||
(!("error" in current) &&
!("error" in preview) &&
(current.diff !== preview.diff || current.firstChangedLine !== preview.firstChangedLine));
component.preview = preview;
component.previewArgsKey = argsKey;
component.previewPending = false;
return changed;
}
export function createEditToolDefinition(
cwd: string,
options?: EditToolOptions,
): ToolDefinition<typeof editSchema, EditToolDetails | undefined, EditRenderState> {
const ops = options?.operations ?? defaultEditOperations;
const definition: ToolDefinition<typeof editSchema, EditToolDetails | undefined, EditRenderState> = {
name: "edit",
label: "edit",
description:
"Edit a single file using exact text replacement. Every edits[].oldText must match a unique, non-overlapping region of the original file. If two changes affect the same block or nearby lines, merge them into one edit instead of emitting overlapping edits. Do not include large unchanged regions just to connect distant changes.",
promptSnippet:
"Make precise file edits with exact text replacement, including multiple disjoint edits in one call",
parameters: editSchema,
renderShell: "self",
prepareArguments: prepareEditArguments,
async execute(_toolCallId, input: EditToolInput, signal?: AbortSignal, _onUpdate?, _ctx?) {
const { path, edits } = validateEditInput(input);
const absolutePath = resolveToCwd(path, cwd);
return withFileMutationQueue(
absolutePath,
() =>
new Promise<{
content: Array<{ type: "text"; text: string }>;
details: EditToolDetails | undefined;
}>((resolve, reject) => {
if (signal?.aborted) {
reject(new Error("Operation aborted"));
return;
}
let aborted = false;
const onAbort = () => {
aborted = true;
reject(new Error("Operation aborted"));
};
if (signal) {
signal.addEventListener("abort", onAbort, { once: true });
}
void (async () => {
try {
try {
await ops.access(absolutePath);
} catch (error: unknown) {
const errorMessage =
error instanceof Error && "code" in error ? `Error code: ${error.code}` : String(error);
if (signal) {
signal.removeEventListener("abort", onAbort);
}
reject(new Error(`Could not edit file: ${path}. ${errorMessage}.`));
return;
}
if (aborted) {
return;
}
const buffer = await ops.readFile(absolutePath);
const rawContent = buffer.toString("utf-8");
if (aborted) {
return;
}
// Strip BOM before matching. The model will not include an invisible BOM in oldText.
const { bom, text: content } = stripBom(rawContent);
const originalEnding = detectLineEnding(content);
const normalizedContent = normalizeToLF(content);
const { baseContent, newContent } = applyEditsToNormalizedContent(
normalizedContent,
edits,
path,
);
if (aborted) {
return;
}
const finalContent = bom + restoreLineEndings(newContent, originalEnding);
await ops.writeFile(absolutePath, finalContent);
if (aborted) {
return;
}
if (signal) {
signal.removeEventListener("abort", onAbort);
}
const diffResult = generateDiffString(baseContent, newContent);
resolve({
content: [
{
type: "text",
text: `Successfully replaced ${edits.length} block(s) in ${path}.`,
},
],
details: { diff: diffResult.diff, firstChangedLine: diffResult.firstChangedLine },
});
} catch (error: unknown) {
if (signal) {
signal.removeEventListener("abort", onAbort);
}
if (!aborted) {
reject(error instanceof Error ? error : new Error(String(error)));
}
}
})();
}),
);
},
renderCall(args, theme, context) {
const component = getEditCallRenderComponent(context.state, context.lastComponent);
const previewInput = getRenderablePreviewInput(args as RenderableEditArgs | undefined);
const argsKey = previewInput
? JSON.stringify({ path: previewInput.path, edits: previewInput.edits })
: undefined;
if (component.previewArgsKey !== argsKey) {
component.preview = undefined;
component.previewArgsKey = argsKey;
component.previewPending = false;
component.settledError = false;
}
if (context.argsComplete && previewInput && !component.preview && !component.previewPending) {
component.previewPending = true;
const requestKey = argsKey;
void computeEditsDiff(previewInput.path, previewInput.edits, context.cwd).then((preview) => {
if (component.previewArgsKey === requestKey) {
setEditPreview(component, preview, requestKey);
context.invalidate();
}
});
}
return buildEditCallComponent(component, args, theme, context.expanded, context.cwd);
},
renderResult(result, _options, theme, context) {
const callComponent = context.state.callComponent;
const previewInput = getRenderablePreviewInput(context.args as RenderableEditArgs | undefined);
const argsKey = previewInput
? JSON.stringify({ path: previewInput.path, edits: previewInput.edits })
: undefined;
const typedResult = result as EditToolResultLike;
const resultDiff = !context.isError ? typedResult.details?.diff : undefined;
let changed = false;
if (callComponent) {
if (typeof resultDiff === "string") {
changed =
setEditPreview(
callComponent,
{ diff: resultDiff, firstChangedLine: typedResult.details?.firstChangedLine },
argsKey,
) || changed;
}
if (callComponent.settledError !== context.isError) {
callComponent.settledError = context.isError;
changed = true;
}
if (changed) {
buildEditCallComponent(
callComponent,
context.args as RenderableEditArgs | undefined,
theme,
context.expanded,
context.cwd,
);
}
}
const output = formatEditResult(context.args, callComponent?.preview, typedResult, theme, context.isError);
const component = (context.lastComponent as Container | undefined) ?? new Container();
component.clear();
if (!output) {
return component;
}
component.addChild(new Spacer(1));
component.addChild(new Text(output, 1, 0));
return component;
},
};
return Object.assign(definition, { replayBuiltInToolName: "edit" as const });
}
export function createEditTool(cwd: string, options?: EditToolOptions): AgentTool<typeof editSchema> {
return wrapToolDefinition(createEditToolDefinition(cwd, options));
}