@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
package/src/paths.ts ADDED
@@ -0,0 +1,56 @@
1
+ import { homedir } from "node:os";
2
+ import { isAbsolute, relative, resolve as resolvePath, join, dirname } from "node:path";
3
+
4
+
5
+ function homeBase(): string {
6
+ const envHome = process.env.HOME;
7
+ return envHome && envHome.length > 0 ? envHome : homedir();
8
+ }
9
+
10
+ function configBase(): string {
11
+ if (process.platform !== "win32") {
12
+ const xdg = process.env.XDG_CONFIG_HOME;
13
+ if (xdg && xdg.length > 0) return xdg;
14
+ }
15
+ return join(homeBase(), ".config");
16
+ }
17
+
18
+ export function configDir(): string {
19
+ return join(configBase(), "pi-hashline-edit-pro");
20
+ }
21
+
22
+ export function configPath(): string {
23
+ return join(configDir(), "config.json");
24
+ }
25
+
26
+ export function hashStorePath(): string {
27
+ return join(configDir(), "hash-store.sqlite");
28
+ }
29
+
30
+ export function legacyHashStorePath(): string {
31
+ return join(configDir(), "hash-store.json");
32
+ }
33
+
34
+ export function sessionClaimsDir(): string {
35
+ return join(configDir(), "sessions");
36
+ }
37
+
38
+ export function hashStoreDir(): string {
39
+ return dirname(hashStorePath());
40
+ }
41
+
42
+ function expand(filePath: string): string {
43
+ const home = homeBase();
44
+ if (filePath === "~") return home;
45
+ if (filePath.startsWith("~/")) return home + filePath.slice(1);
46
+ return filePath;
47
+ }
48
+
49
+ export function toCwd(filePath: string, cwd: string): string {
50
+ const expanded = expand(filePath);
51
+ return isAbsolute(expanded) ? expanded : resolvePath(cwd, expanded);
52
+ }
53
+
54
+ export function toDisplayPath(cwd: string, absolutePath: string, fallback?: string): string {
55
+ return relative(cwd, absolutePath).replace(/\\/g, "/") || (fallback ?? absolutePath);
56
+ }
@@ -0,0 +1,133 @@
1
+ import { Type } from "typebox";
2
+ import { isRec, normalizeRequest, rejectUnknownFields, assertNoNul } from "./utils";
3
+
4
+ const replacementLinesSchema = Type.Array(
5
+ Type.String({
6
+ description:
7
+ "One replacement line; never embed \\n inside an element.",
8
+ }),
9
+ {
10
+ description:
11
+ "One string per line. Use [] to delete the range; [\"\"] is a single blank line.",
12
+ },
13
+ );
14
+
15
+ const removeFromSchema = Type.String({
16
+ description:
17
+ "Bare 4-char anchor from a served anchor│content row (the text before the `│` separator), never the row content. Marks the FIRST line to remove (inclusive)",
18
+ });
19
+
20
+ const removeToSchema = Type.String({
21
+ description:
22
+ "Bare 4-char anchor from a served anchor│content row (the text before the `│` separator), never the row content. Marks the LAST line to remove (inclusive)",
23
+ });
24
+ const pathRequiredSchema = Type.String({
25
+ description:
26
+ "Path to the file the anchors were served for; required and must match anchor ownership. Anchors still resolve the target.",
27
+ });
28
+
29
+ export const editToolSchema = Type.Object(
30
+ {
31
+ remove_from: removeFromSchema,
32
+ remove_to: removeToSchema,
33
+ replacement_lines: replacementLinesSchema,
34
+ },
35
+ { additionalProperties: true },
36
+ );
37
+
38
+ export function buildEditToolSchema(requirePath: boolean): typeof editToolSchema {
39
+ if (!requirePath) return editToolSchema;
40
+ return Type.Object(
41
+ {
42
+ path: pathRequiredSchema,
43
+ remove_from: removeFromSchema,
44
+ remove_to: removeToSchema,
45
+ replacement_lines: replacementLinesSchema,
46
+ },
47
+ { additionalProperties: true },
48
+ ) as typeof editToolSchema;
49
+ }
50
+
51
+ export type ReqParams = {
52
+ path?: string;
53
+ remove_from: string;
54
+ remove_to: string;
55
+ replacement_lines: string[];
56
+ };
57
+
58
+ const ROOT_KS = new Set(["path", "remove_from", "remove_to", "replacement_lines"]);
59
+ export function assertReq(request: unknown): asserts request is ReqParams {
60
+ if (!isRec(request)) {
61
+ throw new Error("[E_BAD_SHAPE] Edit request must be an object.");
62
+ }
63
+ rejectUnknownFields(request, ROOT_KS, "Edit request");
64
+ if (request.path !== undefined && typeof request.path !== "string") {
65
+ throw new Error('[E_BAD_SHAPE] Edit request field "path" must be a string when provided.');
66
+ }
67
+ if (
68
+ typeof request.remove_from !== "string" ||
69
+ typeof request.remove_to !== "string" ||
70
+ !Array.isArray(request.replacement_lines) ||
71
+ request.replacement_lines.some((line) => typeof line !== "string")
72
+ ) {
73
+ throw new Error(
74
+ '[E_BAD_SHAPE] Edit request requires "remove_from", "remove_to", and "replacement_lines" (array of strings, one per line; use [] to delete).',
75
+ );
76
+ }
77
+ assertNoNul(request.replacement_lines);
78
+ }
79
+
80
+ export { normalizeRequest as normReq } from "./utils";
81
+
82
+ export function getPreviewInput(args: unknown): { path?: string; remove_from: string; remove_to: string; replacement_lines: string[] } | null {
83
+ let normalized: unknown;
84
+ try {
85
+ normalized = normalizeRequest(args);
86
+ } catch {
87
+ return null;
88
+ }
89
+ if (!isRec(normalized)) return null;
90
+ if (
91
+ typeof normalized.remove_from !== "string" ||
92
+ typeof normalized.remove_to !== "string" ||
93
+ !Array.isArray(normalized.replacement_lines) ||
94
+ normalized.replacement_lines.some((line) => typeof line !== "string")
95
+ ) {
96
+ return null;
97
+ }
98
+ return {
99
+ ...(typeof normalized.path === "string" ? { path: normalized.path } : {}),
100
+ remove_from: normalized.remove_from as string,
101
+ remove_to: normalized.remove_to as string,
102
+ replacement_lines: normalized.replacement_lines as string[],
103
+ };
104
+ }
105
+
106
+ const INSERT_KS = new Set(["path", "anchor", "direction", "lines"]);
107
+
108
+ export interface InsertReq {
109
+ path?: string;
110
+ anchor: string;
111
+ direction: "before" | "after";
112
+ lines: string[];
113
+ }
114
+
115
+ export function assertInsertReq(request: unknown): asserts request is InsertReq {
116
+ if (!isRec(request)) {
117
+ throw new Error("[E_BAD_SHAPE] Insert request must be an object.");
118
+ }
119
+ rejectUnknownFields(request, INSERT_KS, "Insert request");
120
+ if (request.path !== undefined && typeof request.path !== "string") {
121
+ throw new Error('[E_BAD_SHAPE] Insert request field "path" must be a string when provided.');
122
+ }
123
+ if (typeof request.anchor !== "string" || request.anchor.length === 0) {
124
+ throw new Error('[E_BAD_SHAPE] Insert request requires an "anchor" string (4-char anchor from read output).');
125
+ }
126
+ if (request.direction !== "before" && request.direction !== "after") {
127
+ throw new Error('[E_BAD_SHAPE] Insert request "direction" must be "before" or "after".');
128
+ }
129
+ if (!Array.isArray(request.lines) || request.lines.some((line) => typeof line !== "string")) {
130
+ throw new Error('[E_BAD_SHAPE] Insert request requires "lines" as an array of strings, one element per line.');
131
+ }
132
+ assertNoNul(request.lines);
133
+ }
package/src/prompts.ts ADDED
@@ -0,0 +1,13 @@
1
+ import { readFileSync } from "node:fs";
2
+
3
+ export function loadP(relativePath: string): string {
4
+ return readFileSync(new URL(relativePath, import.meta.url), "utf-8").trim();
5
+ }
6
+
7
+ export function loadGuide(relativePath: string): string[] {
8
+ return readFileSync(new URL(relativePath, import.meta.url), "utf-8")
9
+ .split("\n")
10
+ .map((line) => line.trim())
11
+ .filter((line) => line.startsWith("- "))
12
+ .map((line) => line.slice(2));
13
+ }
package/src/read.ts ADDED
@@ -0,0 +1,286 @@
1
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
+ import {
3
+ createReadTool,
4
+ formatSize,
5
+ truncateHead,
6
+ DEFAULT_MAX_BYTES,
7
+ DEFAULT_MAX_LINES,
8
+ type TruncationResult,
9
+ } from "@earendil-works/pi-coding-agent";
10
+ import { Type } from "typebox";
11
+ import { loadFileKindAndText } from "./file-kind";
12
+ import { MAX_OVERSIZED_WARNING_LINES } from "./constants";
13
+ import { readNormFile, safeSnapId } from "./file-reader";
14
+ import { lineHashes, fmtRegion, fmtRow, HASH_SEP, MAX_HASH_LINES } from "./hashline";
15
+ import { toCwd } from "./paths";
16
+ import { abortIf, makePrepareArguments, numberedRead, visLines, splitLines } from "./utils";
17
+ import { loadP, loadGuide } from "./prompts";
18
+ import { withReadPrompts, DEFAULT_EDIT_FLAGS, type EditToolFlags } from "./edit-common";
19
+ import { valAccess } from "./validation";
20
+ import { readConfig } from "./config";
21
+ import { resolveTarget } from "./fs-write";
22
+ import { withAnchorSession, servedForPath, sessionKeyFor } from "./anchor-registry";
23
+ import { serveRows } from "./served";
24
+ import { getAutoReadAllSnapshot } from "./auto-read-all-state";
25
+ import { Text } from "@earendil-works/pi-tui";
26
+ const R_DESC = loadP("../prompts/read.md");
27
+ const R_SNIPPET = loadP("../prompts/read-snippet.md");
28
+ function readGuide(): string[] {
29
+ return loadGuide("../prompts/read-guidelines.md");
30
+ }
31
+ function normPosInt(
32
+ value: number | undefined,
33
+ name: "offset" | "limit",
34
+ ): number | undefined {
35
+ if (value === undefined) {
36
+ return undefined;
37
+ }
38
+
39
+ if (!Number.isInteger(value) || value < 1) {
40
+ throw new Error(`[E_BAD_SHAPE] Read request field "${name}" must be a positive integer.`);
41
+ }
42
+
43
+ return value;
44
+ }
45
+
46
+ export function formatPaginationHint(
47
+ startLine: number,
48
+ endLine: number,
49
+ totalLines: number,
50
+ nextOffset: number,
51
+ byteLimit?: number,
52
+ ): string {
53
+ const sizeSuffix = byteLimit !== undefined ? ` (${formatSize(byteLimit)} limit)` : "";
54
+ return `[Showing lines ${startLine}-${endLine} of ${totalLines}${sizeSuffix}. Use offset=${nextOffset} to continue.]`;
55
+ }
56
+
57
+ export async function fmtReadPreview(
58
+ text: string,
59
+ options: { offset?: number; limit?: number },
60
+ precomputedHashes?: string[],
61
+ path?: string,
62
+ maxLineBytes = DEFAULT_MAX_BYTES,
63
+ maxTruncLines = DEFAULT_MAX_LINES,
64
+ ): Promise<{ text: string; truncation?: TruncationResult; nextOffset?: number; servedHashes: string[] }> {
65
+ const allLines = visLines(text);
66
+ const totalLines = allLines.length;
67
+ const startLine = normPosInt(options.offset, "offset") ?? 1;
68
+ if (totalLines === 0) {
69
+ if (startLine === 1) {
70
+ const allHashes = precomputedHashes ?? await (path ? lineHashes(text, path) : lineHashes(text));
71
+ const emptyLineHash = allHashes[0] ?? "";
72
+ return {
73
+ text: `${emptyLineHash}${HASH_SEP}\n[File is empty. Use replace to insert content.]`,
74
+ servedHashes: emptyLineHash ? [emptyLineHash] : [],
75
+ };
76
+ }
77
+ return {
78
+ text: `Offset ${startLine} is beyond end of file (0 lines). Use replace to insert content.`,
79
+ servedHashes: [],
80
+ };
81
+ }
82
+ if (startLine > totalLines) {
83
+ return {
84
+ text: `Offset ${startLine} is beyond end of file (${totalLines} lines total). Use offset=1 to read from the start, or offset=${totalLines} to read the last line.`,
85
+ servedHashes: [],
86
+ };
87
+ }
88
+
89
+ const limit = normPosInt(options.limit, "limit");
90
+ const endIdx = limit
91
+ ? Math.min(startLine - 1 + limit, totalLines)
92
+ : totalLines;
93
+ const selected = allLines.slice(startLine - 1, endIdx);
94
+ const allHashes = precomputedHashes ?? await (path ? lineHashes(text, path) : lineHashes(text));
95
+ const selectedHashes = allHashes.slice(startLine - 1, endIdx);
96
+ const formatted = fmtRegion(selectedHashes, selected);
97
+ const maxBytes = maxLineBytes;
98
+ const rowSizes = selected.map((line, index) => ({
99
+ lineNumber: startLine + index,
100
+ bytes: Buffer.byteLength(`${selectedHashes[index]}${HASH_SEP}${line}`, "utf-8"),
101
+ }));
102
+ if (rowSizes.some((row) => row.bytes > maxBytes)) {
103
+ const oversized = rowSizes.filter((row) => row.bytes > maxBytes);
104
+ const rows = rowSizes.map((row, index) =>
105
+ row.bytes > maxBytes
106
+ ? fmtRow(selectedHashes[index]!, `[Line ${row.lineNumber} is ${formatSize(row.bytes)}, exceeds ${formatSize(maxBytes)}; content not shown. Use bash: sed -n '${row.lineNumber}p' <path> | head -c ${maxBytes}]`)
107
+ : fmtRegion([selectedHashes[index]!], [selected[index]!]),
108
+ );
109
+ const skippedTruncation = truncateHead(rows.join("\n"), { maxBytes, maxLines: maxTruncLines });
110
+ const shownRowCount = skippedTruncation.content === "" ? 0 : skippedTruncation.content.split("\n").length;
111
+ const lastShownLine = shownRowCount > 0 ? startLine + shownRowCount - 1 : startLine - 1;
112
+ const servedHashes: string[] = [];
113
+ for (let index = 0; index < Math.min(shownRowCount, rows.length); index++) {
114
+ servedHashes.push(selectedHashes[index]!);
115
+ }
116
+ const listed = oversized.slice(0, MAX_OVERSIZED_WARNING_LINES);
117
+ const hiddenCount = oversized.length - listed.length;
118
+ const lineLabel = oversized.length === 1
119
+ ? `Line ${oversized[0]!.lineNumber}`
120
+ : `Lines ${listed.map((row) => row.lineNumber).join(', ')}${hiddenCount > 0 ? `, ... (+${hiddenCount} more)` : ''}`;
121
+ const verb = oversized.length === 1 ? 'exceeds' : 'exceed';
122
+ const addresses = listed.map((row) => `${row.lineNumber}p`).join(';');
123
+ const moreHint = hiddenCount > 0
124
+ ? ` ${hiddenCount} more oversized line(s). Use read with offset to inspect them.`
125
+ : '';
126
+ const warning = `[${lineLabel} ${verb} ${formatSize(maxBytes)}; content not shown. Inspect with bash: sed -n '${addresses}' <path> | head -c ${maxBytes}${moreHint}]`;
127
+ let preview = skippedTruncation.content;
128
+ let nextOffset: number | undefined;
129
+ if (shownRowCount > 0 && (skippedTruncation.truncated || lastShownLine < totalLines)) {
130
+ nextOffset = lastShownLine + 1;
131
+ preview += `\n\n${warning}\n${formatPaginationHint(startLine, lastShownLine, totalLines, nextOffset, skippedTruncation.truncated ? skippedTruncation.maxBytes : undefined)}`;
132
+ } else {
133
+ preview += `\n\n${warning}`;
134
+ }
135
+ return {
136
+ text: preview,
137
+ truncation: skippedTruncation.truncated ? skippedTruncation : undefined,
138
+ ...(nextOffset !== undefined ? { nextOffset } : {}),
139
+ servedHashes,
140
+ };
141
+ }
142
+
143
+ const truncation = truncateHead(formatted, { maxBytes, maxLines: maxTruncLines });
144
+
145
+ let preview = truncation.content;
146
+ let nextOffset: number | undefined;
147
+ const shownCount = truncation.content === "" ? 0 : truncation.content.split("\n").length;
148
+ const servedHashes = selectedHashes.slice(0, shownCount);
149
+ if (truncation.truncated) {
150
+ const endLineDisplay = startLine + truncation.outputLines - 1;
151
+ nextOffset = endLineDisplay + 1;
152
+ if (truncation.truncatedBy === "lines") {
153
+ preview += `\n\n${formatPaginationHint(startLine, endLineDisplay, totalLines, nextOffset)}`;
154
+ } else {
155
+ preview += `\n\n${formatPaginationHint(startLine, endLineDisplay, totalLines, nextOffset, truncation.maxBytes)}`;
156
+ }
157
+ } else if (endIdx < totalLines) {
158
+ nextOffset = endIdx + 1;
159
+ preview += `\n\n${formatPaginationHint(startLine, endIdx, totalLines, nextOffset)}`;
160
+ }
161
+
162
+ return {
163
+ text: preview,
164
+ truncation: truncation.truncated ? truncation : undefined,
165
+ ...(nextOffset !== undefined ? { nextOffset } : {}),
166
+ servedHashes,
167
+ };
168
+ }
169
+
170
+ export function regRead(pi: ExtensionAPI, flags: EditToolFlags = DEFAULT_EDIT_FLAGS): void {
171
+ const prompted = withReadPrompts({ description: R_DESC, snippet: R_SNIPPET, guidelines: readGuide() }, flags);
172
+ pi.registerTool({
173
+ name: "read",
174
+ label: "Read",
175
+ description: prompted.description,
176
+ promptSnippet: prompted.snippet,
177
+ promptGuidelines: prompted.guidelines,
178
+ prepareArguments: makePrepareArguments(),
179
+ parameters: Type.Object({
180
+ path: Type.String({
181
+ description: "Path to the file to read (relative or absolute)",
182
+ }),
183
+ offset: Type.Optional(
184
+ Type.Integer({
185
+ minimum: 1,
186
+ description: "Line number to start reading from (1-indexed)",
187
+ }),
188
+ ),
189
+ limit: Type.Optional(
190
+ Type.Integer({
191
+ minimum: 1,
192
+ description: "Maximum number of lines to read",
193
+ }),
194
+ ),
195
+ }),
196
+ executionMode: "sequential",
197
+ renderResult(result, { isPartial, expanded }, theme, context) {
198
+ if (isPartial) return new Text((theme as unknown as { fg: (a:string,b:string)=>string }).fg("warning", "Reading..."), 0, 0);
199
+ const raw = (result.content?.[0] as { text?: string } | undefined)?.text;
200
+ if (typeof raw !== "string") return new Text("", 0, 0);
201
+ if ((context as unknown as { isError?: boolean }).isError) return new Text((theme as unknown as { fg: (a:string,b:string)=>string }).fg("error", raw), 0, 0);
202
+ const isExpanded = expanded === true || (context as unknown as { expanded?: boolean }).expanded === true;
203
+ if (!isExpanded) return new Text("", 0, 0);
204
+ const details = (result as unknown as { details?: { offset?: number } }).details;
205
+ const off = details?.offset ?? (context as unknown as { args?: { offset?: number } }).args?.offset ?? 1;
206
+ return new Text(numberedRead(raw, off), 0, 0);
207
+ },
208
+
209
+ async execute(_toolCallId, params, signal, _onUpdate, ctx) {
210
+ return withAnchorSession(ctx, async () => {
211
+ const rawPath = params.path;
212
+ const absolutePath = toCwd(rawPath, ctx.cwd);
213
+
214
+ abortIf(signal);
215
+ await valAccess(absolutePath, rawPath);
216
+ const autoReadAllMode = (await readConfig()).autoReadAll ?? "off";
217
+ if (autoReadAllMode !== "off") {
218
+ const canonical = await resolveTarget(absolutePath).catch(() => undefined);
219
+ if (canonical !== undefined) {
220
+ const stored = getAutoReadAllSnapshot(sessionKeyFor(ctx), canonical);
221
+ if (stored !== undefined) {
222
+ const current = await safeSnapId(canonical, "auto-read-all guard");
223
+ if (current !== undefined && current === stored) {
224
+ const served = servedForPath(canonical);
225
+ if (served !== undefined && served.size > 0) {
226
+ throw new Error(`[E_AUTO_READ_ALL] ${rawPath} is unchanged since this session's start-of-session auto-read, so the attached content is still exact. Read succeeds on files that have changed since the full auto read.`);
227
+ }
228
+ }
229
+ }
230
+ }
231
+ }
232
+
233
+ abortIf(signal);
234
+ const file = await loadFileKindAndText(absolutePath, { maxLines: MAX_HASH_LINES, displayPath: rawPath });
235
+ if (file.kind === "image") {
236
+ const builtinRead = createReadTool(ctx.cwd);
237
+ const executeBuiltinRead = builtinRead.execute as unknown as (
238
+ toolCallId: string,
239
+ input: typeof params,
240
+ abortSignal: typeof signal,
241
+ onUpdate: typeof _onUpdate,
242
+ context: typeof ctx,
243
+ ) => ReturnType<typeof builtinRead.execute>;
244
+ return executeBuiltinRead(_toolCallId, params, signal, _onUpdate, ctx);
245
+ }
246
+ const { normalized, fileHashes, hadUtf8DecodeErrors, absolutePath: resolvedPath } = await readNormFile(
247
+ rawPath, ctx.cwd, { signal, preloadedFile: file, maxLines: MAX_HASH_LINES },
248
+ );
249
+ const fileLines = splitLines(normalized);
250
+ const preview = await fmtReadPreview(
251
+ normalized,
252
+ {
253
+ offset: params.offset,
254
+ limit: params.limit,
255
+ },
256
+ fileHashes,
257
+ resolvedPath,
258
+ );
259
+ serveRows(resolvedPath, fileHashes, fileLines, preview.servedHashes);
260
+ const snapshotId = await safeSnapId(absolutePath, "read");
261
+ const previewText =
262
+ hadUtf8DecodeErrors
263
+ ? `${preview.text}\n\n[Non-UTF-8 bytes shown as U+FFFD; editing rewrites the file as UTF-8.]`
264
+ : preview.text;
265
+
266
+ return {
267
+ content: [{ type: "text", text: previewText }],
268
+ details: {
269
+ truncation: preview.truncation,
270
+ snapshotId,
271
+ offset: params.offset ?? 1,
272
+ ...(preview.nextOffset !== undefined
273
+ ? { nextOffset: preview.nextOffset }
274
+ : {}),
275
+ metrics: {
276
+ truncated: !!preview.truncation,
277
+ ...(preview.nextOffset !== undefined
278
+ ? { next_offset: preview.nextOffset }
279
+ : {}),
280
+ },
281
+ },
282
+ };
283
+ });
284
+ },
285
+ });
286
+ }