@leolastforce/chalice-hashline-edit 0.0.0-stage → 4.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +153 -2
  3. package/index.ts +282 -0
  4. package/package.json +79 -4
  5. package/prompts/find-guidelines.md +2 -0
  6. package/prompts/find-snippet.md +1 -0
  7. package/prompts/find.md +1 -0
  8. package/prompts/grep-guidelines.md +2 -0
  9. package/prompts/grep-snippet.md +1 -0
  10. package/prompts/grep.md +1 -0
  11. package/prompts/insert-guidelines.md +1 -0
  12. package/prompts/insert-snippet.md +1 -0
  13. package/prompts/insert.md +1 -0
  14. package/prompts/read-guidelines.md +2 -0
  15. package/prompts/read-snippet.md +1 -0
  16. package/prompts/read.md +1 -0
  17. package/prompts/replace-guidelines.md +4 -0
  18. package/prompts/replace-snippet.md +1 -0
  19. package/prompts/replace.md +1 -0
  20. package/prompts/undo-last-change-guidelines.md +1 -0
  21. package/prompts/undo-last-change-snippet.md +1 -0
  22. package/prompts/undo-last-change.md +1 -0
  23. package/src/anchor-registry.ts +977 -0
  24. package/src/auto-read-all-state.ts +27 -0
  25. package/src/auto-read-all.ts +477 -0
  26. package/src/batch.ts +767 -0
  27. package/src/commit.ts +137 -0
  28. package/src/config-ui.ts +212 -0
  29. package/src/config.ts +235 -0
  30. package/src/constants.ts +26 -0
  31. package/src/edit-common.ts +206 -0
  32. package/src/file-kind.ts +191 -0
  33. package/src/file-reader.ts +135 -0
  34. package/src/find.ts +244 -0
  35. package/src/fs-write.ts +231 -0
  36. package/src/glob.ts +186 -0
  37. package/src/grep.ts +690 -0
  38. package/src/hash-store/cache.ts +18 -0
  39. package/src/hash-store/retry.ts +44 -0
  40. package/src/hash-store/validation.ts +62 -0
  41. package/src/hash-store.ts +609 -0
  42. package/src/hashline/alphabet.ts +21 -0
  43. package/src/hashline/anchor-table.json +1 -0
  44. package/src/hashline/apply.ts +297 -0
  45. package/src/hashline/hash.ts +119 -0
  46. package/src/hashline/hasher.ts +47 -0
  47. package/src/hashline/index.ts +50 -0
  48. package/src/hashline/parse.ts +84 -0
  49. package/src/hashline/resolve.ts +373 -0
  50. package/src/insert.ts +258 -0
  51. package/src/normalize.ts +27 -0
  52. package/src/paths.ts +56 -0
  53. package/src/payload-contract.ts +133 -0
  54. package/src/prompts.ts +13 -0
  55. package/src/read.ts +286 -0
  56. package/src/replace-diff.ts +610 -0
  57. package/src/replace-render.ts +390 -0
  58. package/src/replace-response.ts +166 -0
  59. package/src/replace-undo.ts +270 -0
  60. package/src/replace.ts +318 -0
  61. package/src/served.ts +36 -0
  62. package/src/utils.ts +387 -0
  63. package/src/validation.ts +45 -0
  64. package/src/write-hook.ts +53 -0
@@ -0,0 +1,270 @@
1
+ import { constants } from "node:fs";
2
+ import { open, stat } from "node:fs/promises";
3
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
4
+ import { withFileMutationQueue } from "@earendil-works/pi-coding-agent";
5
+ import { Type } from "typebox";
6
+ import { loadHashStore, persistSnapshot, upsertUndo, getUndoEntry, deleteUndo, type UndoRecord } from "./hash-store";
7
+ import { servedHashesFromDiff, serveRows } from "./served";
8
+ import { lineChecksum } from "./hashline";
9
+ import { freeAnchors, adoptAnchors, withAnchorSession } from "./anchor-registry";
10
+ import { resolveInCwd, writeAtomic, type FileIdentity } from "./fs-write";
11
+ import { toLF, stripBOM, restoreEndings, type LineEnding } from "./normalize";
12
+ import { genDiff, genPatch, spansFromHashes } from "./replace-diff";
13
+ import { getDiffContextLines } from "./config";
14
+ import { cntDiff, errCode, makePrepareArguments, splitLines } from "./utils";
15
+ import { loadP, loadGuide } from "./prompts";
16
+ import { withUndoPrompts, DEFAULT_EDIT_FLAGS, type EditToolFlags } from "./edit-common";
17
+ import { buildMetrics } from "./replace-response";
18
+ import { renderEditResult, fmtCall } from "./replace-render";
19
+ import { Text } from "@earendil-works/pi-tui";
20
+ import { changedRange, lineHashes } from "./hashline";
21
+ export interface UndoEntry {
22
+ content: string;
23
+ bom: string;
24
+ originalEnding: LineEnding;
25
+ hashes: string[];
26
+ resultContent: string;
27
+ mode?: number;
28
+ }
29
+
30
+ export async function saveUndo(
31
+ path: string,
32
+ entry: UndoEntry,
33
+ ): Promise<{ persisted: boolean; restore: () => Promise<void> }> {
34
+ let previous: UndoRecord | undefined;
35
+ try {
36
+ const store = await loadHashStore();
37
+ previous = getUndoEntry(store, path);
38
+ let mode: number | undefined;
39
+ try {
40
+ mode = (await stat(path)).mode & 0o7777;
41
+ } catch {
42
+ }
43
+ upsertUndo(store, path, {
44
+ content: entry.content,
45
+ bom: entry.bom,
46
+ ending: entry.originalEnding,
47
+ hashes: entry.hashes,
48
+ resultContent: entry.resultContent,
49
+ ...(mode !== undefined ? { mode } : {}),
50
+ });
51
+ } catch (error) {
52
+ console.error("Failed to persist undo entry:", error);
53
+ return { persisted: false, restore: async () => undefined };
54
+ }
55
+ return {
56
+ persisted: true,
57
+ restore: async () => {
58
+ try {
59
+ const store = await loadHashStore();
60
+ if (previous) upsertUndo(store, path, previous);
61
+ else deleteUndo(store, path);
62
+ } catch (error) {
63
+ console.error("Failed to restore previous undo entry:", error);
64
+ }
65
+ },
66
+ };
67
+ }
68
+
69
+ export async function getUndo(path: string): Promise<UndoEntry | undefined> {
70
+ try {
71
+ const store = await loadHashStore();
72
+ const record = getUndoEntry(store, path);
73
+ if (!record) return undefined;
74
+ const originalEnding = record.ending;
75
+ if (originalEnding !== "\r\n" && originalEnding !== "\n" && originalEnding !== "\r") {
76
+ await deleteUndo(store, path);
77
+ return undefined;
78
+ }
79
+ return {
80
+ content: record.content,
81
+ bom: record.bom,
82
+ originalEnding,
83
+ hashes: record.hashes,
84
+ resultContent: record.resultContent,
85
+ ...(record.mode !== undefined ? { mode: record.mode } : {}),
86
+ };
87
+ } catch (error) {
88
+ console.error("Failed to load undo entry:", error);
89
+ return undefined;
90
+ }
91
+ }
92
+
93
+ export async function clearUndo(path: string): Promise<void> {
94
+ try {
95
+ const store = await loadHashStore();
96
+ deleteUndo(store, path);
97
+ } catch (error) {
98
+ console.error("Failed to clear undo entry:", error);
99
+ }
100
+ }
101
+
102
+ function fallbackFileMode(): number {
103
+ return 0o666 & ~process.umask();
104
+ }
105
+
106
+ export function regUndo(pi: ExtensionAPI, flags: EditToolFlags = DEFAULT_EDIT_FLAGS): void {
107
+ const prompted = withUndoPrompts({
108
+ description: loadP("../prompts/undo-last-change.md"),
109
+ snippet: loadP("../prompts/undo-last-change-snippet.md"),
110
+ guidelines: loadGuide("../prompts/undo-last-change-guidelines.md"),
111
+ }, flags);
112
+ pi.registerTool({
113
+ name: "undo_last_change",
114
+ label: "Undo Last Change",
115
+ description: prompted.description,
116
+ promptSnippet: prompted.snippet,
117
+ promptGuidelines: prompted.guidelines,
118
+ prepareArguments: makePrepareArguments(),
119
+ parameters: Type.Object({
120
+ path: Type.String({
121
+ description: "Path to the file to undo",
122
+ }),
123
+ }),
124
+ executionMode: "sequential",
125
+ renderCall(args: any, theme: any, context: any) {
126
+ const text = (context.lastComponent as Text | undefined) ?? new Text("", 0, 0);
127
+ text.setText(fmtCall(args as { path?: string } | undefined, { preview: undefined } as never, context.expanded === true, theme, "undo_last_change"));
128
+ return text;
129
+ },
130
+ renderResult(result, opts, theme, context) {
131
+ return renderEditResult(result as never, opts as { isPartial: boolean; expanded?: boolean }, theme as never, context as never);
132
+ },
133
+ async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
134
+ return withAnchorSession(ctx, async () => {
135
+ const path = params.path;
136
+ if (typeof path !== "string" || path.length === 0) {
137
+ throw new Error('[E_BAD_SHAPE] Undo request requires a non-empty "path" string.');
138
+ }
139
+ const { resolved: mutationTargetPath } = await resolveInCwd(path, ctx.cwd);
140
+
141
+ const undo = await getUndo(mutationTargetPath);
142
+ if (!undo) {
143
+ return {
144
+ content: [
145
+ {
146
+ type: "text",
147
+ text: `No undo history for ${path}.`,
148
+ },
149
+ ],
150
+ isError: true,
151
+ details: {},
152
+ };
153
+ }
154
+
155
+ return withFileMutationQueue(mutationTargetPath, async () => {
156
+ let currentRaw: string | undefined;
157
+ let currentIdentity: FileIdentity | undefined;
158
+ try {
159
+ const noFollow = process.platform === "win32" ? 0 : constants.O_NOFOLLOW;
160
+ const handle = await open(mutationTargetPath, constants.O_RDONLY | noFollow);
161
+ try {
162
+ const { dev, ino } = await handle.stat();
163
+ currentIdentity = { dev, ino };
164
+ currentRaw = await handle.readFile("utf-8");
165
+ } finally {
166
+ await handle.close();
167
+ }
168
+ } catch (error) {
169
+ if (errCode(error) !== "ENOENT") throw error;
170
+ }
171
+
172
+ if (
173
+ currentRaw !== undefined &&
174
+ currentRaw !== undo.bom + restoreEndings(undo.resultContent, undo.originalEnding)
175
+ ) {
176
+ return {
177
+ content: [
178
+ {
179
+ type: "text",
180
+ text: `[E_UNDO_STALE] Cannot undo last change on ${path}: the file was modified after the edit, so nothing was reverted and the file was left untouched. The undo record is kept. Do not edit the file to force the undo. Call read() to inspect the current state.`
181
+ },
182
+ ],
183
+ isError: true,
184
+ details: {},
185
+ };
186
+ }
187
+
188
+ await writeAtomic(
189
+ mutationTargetPath,
190
+ undo.bom + restoreEndings(undo.content, undo.originalEnding),
191
+ currentIdentity,
192
+ undo.mode ?? fallbackFileMode(),
193
+ );
194
+
195
+ const currentNormalized = currentRaw === undefined ? "" : toLF(stripBOM(currentRaw).text);
196
+ const currentHashes = await lineHashes(currentNormalized, mutationTargetPath);
197
+ const diffResult = genDiff(undo.content, undo.resultContent, 0, undefined, undo.hashes, { unlimited: true });
198
+ const linesAddedByReplace = cntDiff(diffResult.diff, "+");
199
+ const linesRemovedByReplace = cntDiff(diffResult.diff, "-");
200
+ const restoredRange = changedRange(currentNormalized, undo.content);
201
+ const undoSpans = spansFromHashes(currentHashes, undo.hashes);
202
+ const undoDiffResult = genDiff(currentNormalized, undo.content, await getDiffContextLines(), undo.hashes, currentHashes, undefined, undoSpans);
203
+ const undoDiff = undoDiffResult.diff;
204
+
205
+ try {
206
+ const store = await loadHashStore();
207
+ const undoLines = splitLines(undo.content);
208
+ persistSnapshot(store, mutationTargetPath, undo.content, undo.hashes, undoLines.map(lineChecksum));
209
+ freeAnchors(mutationTargetPath);
210
+ adoptAnchors(
211
+ mutationTargetPath,
212
+ new Map(undoLines.map((line, i) => [undo.hashes[i]!, lineChecksum(line)])),
213
+ );
214
+ serveRows(
215
+ mutationTargetPath,
216
+ undo.hashes,
217
+ undoLines,
218
+ servedHashesFromDiff(undoDiff),
219
+ );
220
+ } catch (error) {
221
+ console.error("Failed to restore hash store snapshot after undo:", error);
222
+ }
223
+
224
+ await clearUndo(mutationTargetPath);
225
+
226
+ const parts: string[] = [
227
+ `Undone last change on ${path}.`,
228
+ ];
229
+ if (currentRaw === undefined) {
230
+ parts.push("The file was deleted; restored it from undo history.");
231
+ }
232
+ if (linesAddedByReplace > 0 || linesRemovedByReplace > 0) {
233
+ parts.push(
234
+ `Removed ${linesAddedByReplace} line(s), restored ${linesRemovedByReplace} line(s).`,
235
+ );
236
+ }
237
+ parts.push(
238
+ "Call read for fresh anchors.",
239
+ );
240
+
241
+ const patchResult = genPatch(path, currentNormalized, undo.content);
242
+ return {
243
+ content: [
244
+ {
245
+ type: "text",
246
+ text: parts.join("\n"),
247
+ },
248
+ ],
249
+ details: {
250
+ diff: undoDiff,
251
+ diffLineNumbers: undoDiffResult.lineNumbers.map((line) => line ?? null),
252
+ patch: patchResult.patch,
253
+ ...(patchResult.truncated ? { patchTruncated: true as const } : {}),
254
+ metrics: buildMetrics({
255
+ classification: "applied",
256
+ editsAttempted: 1,
257
+ noopEditsCount: 0,
258
+ warningsCount: 0,
259
+ firstChangedLine: restoredRange?.firstChangedLine,
260
+ lastChangedLine: restoredRange?.lastChangedLine,
261
+ addedLines: linesRemovedByReplace,
262
+ removedLines: linesAddedByReplace,
263
+ }),
264
+ },
265
+ };
266
+ });
267
+ });
268
+ },
269
+ });
270
+ }
package/src/replace.ts ADDED
@@ -0,0 +1,318 @@
1
+ import type {
2
+ ExtensionAPI,
3
+ ToolDefinition,
4
+ } from "@earendil-works/pi-coding-agent";
5
+ import { constants } from "node:fs";
6
+ import {
7
+ genDiff,
8
+ type DiffSpan,
9
+ type LineEnding,
10
+ } from "./replace-diff";
11
+ import { readNormFile, type NormFile } from "./file-reader";
12
+ import { editToolSchema, buildEditToolSchema, type ReqParams, assertReq, normReq } from "./payload-contract";
13
+ import { splitLines } from "./utils";
14
+ import { loadP, loadGuide } from "./prompts";
15
+ import { type FileIdentity } from "./fs-write";
16
+ import { applyEdit,
17
+ lineHashes,
18
+ resEdit,
19
+ MAX_HASH_LINES,
20
+ RangeStaleError,
21
+ AnchorMismatchError,
22
+ type HEdit,
23
+ type NEdit,
24
+ } from "./hashline";
25
+ import { type RMetrics } from "./replace-response";
26
+ import {
27
+ type RPreview,
28
+ type RRState,
29
+ } from "./replace-render";
30
+ import { loadHashStore, type HashStore } from "./hash-store";
31
+ import { adoptAnchors, servedForPath, withAnchorSession } from "./anchor-registry";
32
+ import { resolveTarget } from "./fs-write";
33
+ import { toCwd, toDisplayPath } from "./paths";
34
+ import { queuedEdit, editToolBase, editRenderCallWrapper, editRenderResultWrapper, resolveEditTargetWithRequirement, throwIfStrictInput, withReplacePrompts, DEFAULT_EDIT_FLAGS, type EditToolFlags } from "./edit-common";
35
+ import { commitEdit } from "./commit";
36
+ import { batchMemberFor, executeBatchMember, noteBatchFailure } from "./batch";
37
+
38
+ export { editToolSchema, type ReqParams, assertReq };
39
+
40
+ export type ReplaceDetails = {
41
+ diff: string;
42
+ patch?: string;
43
+ patchTruncated?: boolean;
44
+ firstChangedLine?: number;
45
+ snapshotId?: string;
46
+ classification?: "noop";
47
+ metrics?: RMetrics;
48
+ diffLineNumbers?: (number | null)[];
49
+ warnings?: string[];
50
+ batch?: { id: number; size: number; last: boolean; total: number; aborted?: boolean; abortMessage?: string };
51
+ };
52
+
53
+ export interface PipelineResult {
54
+ path: string;
55
+ originalNormalized: string;
56
+ result: string;
57
+ bom: string;
58
+ originalEnding: LineEnding;
59
+ hadUtf8DecodeErrors: boolean;
60
+ warnings: string[];
61
+ noopEdit?: NEdit;
62
+ firstChangedLine?: number;
63
+ lastChangedLine?: number;
64
+ originalHashes: string[];
65
+ resultHashes: string[];
66
+ totalAddedLines: number;
67
+ totalRemovedLines: number;
68
+ identity: FileIdentity;
69
+ spans?: DiffSpan[];
70
+ }
71
+
72
+
73
+ export interface ExecPipelineOptions {
74
+ accessMode?: number;
75
+ signal?: AbortSignal;
76
+ store?: HashStore;
77
+ noPersist?: boolean;
78
+ preloadedNorm?: NormFile;
79
+ }
80
+
81
+ export function hashSpan(hashes: string[], from: string, to: string): [number, number] | undefined {
82
+ const a = hashes.indexOf(from);
83
+ const b = hashes.indexOf(to);
84
+ if (a < 0 || b < 0) return undefined;
85
+ return [Math.min(a, b), Math.max(a, b)];
86
+ }
87
+
88
+ export function spanForEdit(originalHashes: string[], from: string, to: string, resultContent: string): DiffSpan | undefined {
89
+ const span = hashSpan(originalHashes, from, to);
90
+ if (!span) return undefined;
91
+ const replacementCount = splitLines(resultContent).length - (originalHashes.length - (span[1] - span[0] + 1));
92
+ return { start: span[0], end: span[1], replacementCount };
93
+ }
94
+ async function noteAnchorError(absolutePath: string, error: unknown, noPersist?: boolean): Promise<void> {
95
+ if (noPersist === true) return;
96
+ if (error instanceof RangeStaleError) {
97
+ adoptAnchors(absolutePath, error.rangeServedMap);
98
+ } else if (error instanceof AnchorMismatchError) {
99
+ adoptAnchors(absolutePath, error.feedbackMap);
100
+ }
101
+ }
102
+
103
+ function countLineChanges(
104
+ edit: HEdit,
105
+ originalHashes: string[],
106
+ isNoop: boolean,
107
+ ): { totalAddedLines: number; totalRemovedLines: number } {
108
+ if (isNoop) return { totalAddedLines: 0, totalRemovedLines: 0 };
109
+ const span = hashSpan(originalHashes, edit.hash_bounds[0].hash, edit.hash_bounds[1].hash);
110
+ const totalRemovedLines = span ? span[1] - span[0] + 1 : 0;
111
+ return {
112
+ totalAddedLines: edit.content_lines.length,
113
+ totalRemovedLines,
114
+ };
115
+ }
116
+
117
+ export function buildReplaceHEdit(params: ReqParams): { edit: HEdit; warnings: string[] } {
118
+ const editWarnings: string[] = [];
119
+ const edit = resEdit(
120
+ {
121
+ remove_from: params.remove_from,
122
+ remove_to: params.remove_to,
123
+ replacement_lines: params.replacement_lines,
124
+ },
125
+ editWarnings,
126
+ );
127
+ return { edit, warnings: editWarnings };
128
+ }
129
+
130
+ export async function execPipeline(
131
+ targetPath: string,
132
+ params: ReqParams,
133
+ cwd: string,
134
+ options?: ExecPipelineOptions,
135
+ ): Promise<PipelineResult> {
136
+
137
+ const { edit, warnings: editWarnings } = buildReplaceHEdit(params);
138
+ const hashStore = options?.store ?? await loadHashStore();
139
+ const preResolvedPath = await resolveTarget(toCwd(targetPath, cwd));
140
+ const served = servedForPath(preResolvedPath);
141
+ const { normalized: originalNormalized, bom, originalEnding, fileHashes: originalHashes, hadUtf8DecodeErrors, absolutePath, identity } = await readNormFile(
142
+ targetPath, cwd, { signal: options?.signal, accessMode: options?.accessMode, maxLines: MAX_HASH_LINES, store: hashStore, noPersist: options?.noPersist, allocation: options?.noPersist ? "shadow" : "real", preloadedNorm: options?.preloadedNorm },
143
+ );
144
+ const displayPath = toDisplayPath(cwd, absolutePath, targetPath);
145
+
146
+ let anchorResult: ReturnType<typeof applyEdit>;
147
+ try {
148
+ anchorResult = applyEdit(
149
+ originalNormalized,
150
+ edit,
151
+ options?.signal,
152
+ originalHashes,
153
+ displayPath,
154
+ served,
155
+ );
156
+ } catch (error) {
157
+ await noteAnchorError(absolutePath, error, options?.noPersist);
158
+ throw error;
159
+ }
160
+
161
+ const result = anchorResult.content;
162
+ const isNoop = result === originalNormalized;
163
+
164
+ const resultHashes = isNoop
165
+ ? originalHashes
166
+ : await lineHashes(result, absolutePath, {
167
+ content: originalNormalized,
168
+ hashes: originalHashes,
169
+ }, hashStore, false, true);
170
+ const warnings = [...editWarnings, ...(anchorResult.warnings ?? [])];
171
+ await throwIfStrictInput(warnings);
172
+ const { totalAddedLines, totalRemovedLines } = countLineChanges(
173
+ edit, originalHashes, isNoop,
174
+ );
175
+
176
+ const pipeSpan = isNoop ? undefined : spanForEdit(originalHashes, edit.hash_bounds[0].hash, edit.hash_bounds[1].hash, result);
177
+ const pipeSpans = pipeSpan ? [pipeSpan] : undefined;
178
+ return {
179
+ path: displayPath,
180
+ originalNormalized,
181
+ result,
182
+ bom,
183
+ originalEnding,
184
+ hadUtf8DecodeErrors,
185
+ warnings,
186
+ noopEdit: anchorResult.noopEdit,
187
+ firstChangedLine: anchorResult.firstChangedLine,
188
+ lastChangedLine: anchorResult.lastChangedLine,
189
+ resultHashes,
190
+ originalHashes,
191
+ totalAddedLines,
192
+ totalRemovedLines,
193
+ identity,
194
+ ...(pipeSpans ? { spans: pipeSpans } : {}),
195
+ };
196
+ }
197
+
198
+ export function previewFromPipe(pipe: PipelineResult): RPreview {
199
+ if (pipe.originalNormalized === pipe.result) {
200
+ return {
201
+ error: `No changes made to ${pipe.path}. The edit produced identical content.`,
202
+ path: pipe.path,
203
+ };
204
+ }
205
+ const base = genDiff(pipe.originalNormalized, pipe.result, 4, pipe.resultHashes, pipe.originalHashes, undefined, pipe.spans);
206
+ return { diff: base.diff, path: pipe.path };
207
+ }
208
+ export function previewError(error: unknown): RPreview {
209
+ return { error: error instanceof Error ? error.message : String(error) };
210
+ }
211
+ export async function compPreview(
212
+ request: unknown,
213
+ cwd: string,
214
+ signal?: AbortSignal,
215
+ ): Promise<RPreview> {
216
+ try {
217
+ const normalized = normReq(request);
218
+ assertReq(normalized);
219
+ const targetPath = await resolveEditTargetWithRequirement({
220
+ removeFrom: (normalized as ReqParams).remove_from,
221
+ removeTo: (normalized as ReqParams).remove_to,
222
+ providedPath: (normalized as ReqParams).path,
223
+ cwd,
224
+ });
225
+ const pipe = await execPipeline(
226
+ targetPath,
227
+ normalized,
228
+ cwd,
229
+ { accessMode: constants.R_OK, noPersist: true, signal },
230
+ );
231
+ return previewFromPipe(pipe);
232
+ } catch (error: unknown) {
233
+ if (signal?.aborted) throw error;
234
+ return previewError(error);
235
+ }
236
+ }
237
+
238
+ type ToolDef = ToolDefinition<
239
+ any,
240
+ ReplaceDetails,
241
+ RRState
242
+ > & { renderShell?: "default" | "self" };
243
+
244
+ export function buildToolDef(flags: EditToolFlags = DEFAULT_EDIT_FLAGS): ToolDef {
245
+ const prompted = withReplacePrompts({
246
+ description: loadP("../prompts/replace.md"),
247
+ snippet: loadP("../prompts/replace-snippet.md"),
248
+ guidelines: loadGuide("../prompts/replace-guidelines.md"),
249
+ }, flags);
250
+ const parameters = buildEditToolSchema(flags.requirePath);
251
+ return {
252
+ name: "replace",
253
+ label: "Replace",
254
+ description: prompted.description,
255
+ parameters,
256
+ promptSnippet: prompted.snippet,
257
+ promptGuidelines: prompted.guidelines,
258
+ ...editToolBase,
259
+ renderCall: editRenderCallWrapper(compPreview),
260
+ renderResult: editRenderResultWrapper,
261
+ async execute(_toolCallId, params, signal, _onUpdate, ctx) {
262
+ return withAnchorSession(ctx, async () => {
263
+ const canonical = normReq(params);
264
+ assertReq(canonical);
265
+ const normalizedParams = canonical;
266
+ const targetPath = await resolveEditTargetWithRequirement({
267
+ removeFrom: normalizedParams.remove_from,
268
+ removeTo: normalizedParams.remove_to,
269
+ providedPath: normalizedParams.path,
270
+ cwd: ctx.cwd,
271
+ }).catch((error: unknown) => {
272
+ const member = batchMemberFor(_toolCallId);
273
+ if (member) noteBatchFailure(member, error);
274
+ throw error;
275
+ });
276
+ return queuedEdit(targetPath, ctx.cwd, signal, async (absolutePath, mutationTargetPath) => {
277
+ const member = batchMemberFor(_toolCallId);
278
+ if (!member) {
279
+ const pipe = await execPipeline(
280
+ targetPath,
281
+ normalizedParams,
282
+ ctx.cwd,
283
+ { accessMode: constants.R_OK | constants.W_OK, signal },
284
+ );
285
+ return await commitEdit(pipe, {
286
+ path: pipe.path,
287
+ absolutePath,
288
+ mutationTargetPath,
289
+ editAnchors: [normalizedParams.remove_from, normalizedParams.remove_to],
290
+ signal,
291
+ });
292
+ }
293
+ let built: { edit: HEdit; warnings: string[] };
294
+ try {
295
+ built = buildReplaceHEdit(normalizedParams);
296
+ } catch (error) {
297
+ noteBatchFailure(member, error);
298
+ throw error;
299
+ }
300
+ return executeBatchMember({
301
+ kind: "replace",
302
+ member,
303
+ targetPath,
304
+ mutationTargetPath,
305
+ cwd: ctx.cwd,
306
+ signal,
307
+ hedit: built.edit,
308
+ extraWarnings: built.warnings,
309
+ });
310
+ });
311
+ });
312
+ },
313
+ };
314
+ }
315
+
316
+ export function regReplace(pi: ExtensionAPI, flags: EditToolFlags = DEFAULT_EDIT_FLAGS): void {
317
+ pi.registerTool(buildToolDef(flags));
318
+ }
package/src/served.ts ADDED
@@ -0,0 +1,36 @@
1
+ import { HASH_CLASS } from "./hashline/alphabet";
2
+ import { lineChecksum } from "./hashline/hash";
3
+ import { markServed } from "./anchor-registry";
4
+
5
+ const SERVED_DIFF_ROW_RE = new RegExp(`^[+ ](${HASH_CLASS})│`);
6
+
7
+ export function servedHashesFromDiff(diff: string): string[] {
8
+ const hashes: string[] = [];
9
+ for (const line of diff.split("\n")) {
10
+ const match = SERVED_DIFF_ROW_RE.exec(line);
11
+ if (match) hashes.push(match[1]!);
12
+ }
13
+ return hashes;
14
+ }
15
+
16
+ export function buildServedMap(
17
+ fileHashes: string[],
18
+ fileLines: string[],
19
+ wantedHashes: string[],
20
+ ): Array<[string, string]> {
21
+ const index = new Map<string, number>();
22
+ for (let i = 0; i < fileHashes.length; i++) {
23
+ const existing = index.get(fileHashes[i]!);
24
+ if (existing === undefined) index.set(fileHashes[i]!, i);
25
+ }
26
+ const entries: Array<[string, string]> = [];
27
+ for (const hash of wantedHashes) {
28
+ const idx = index.get(hash);
29
+ if (idx !== undefined) entries.push([hash, lineChecksum(fileLines[idx]!)]);
30
+ }
31
+ return entries;
32
+ }
33
+
34
+ export function serveRows(path: string, fileHashes: string[], fileLines: string[], wantedHashes: string[]): void {
35
+ markServed(path, buildServedMap(fileHashes, fileLines, wantedHashes), new Set(fileHashes));
36
+ }