@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.
- package/LICENSE +21 -0
- package/README.md +153 -2
- package/index.ts +282 -0
- package/package.json +79 -4
- package/prompts/find-guidelines.md +2 -0
- package/prompts/find-snippet.md +1 -0
- package/prompts/find.md +1 -0
- package/prompts/grep-guidelines.md +2 -0
- package/prompts/grep-snippet.md +1 -0
- package/prompts/grep.md +1 -0
- package/prompts/insert-guidelines.md +1 -0
- package/prompts/insert-snippet.md +1 -0
- package/prompts/insert.md +1 -0
- package/prompts/read-guidelines.md +2 -0
- package/prompts/read-snippet.md +1 -0
- package/prompts/read.md +1 -0
- package/prompts/replace-guidelines.md +4 -0
- package/prompts/replace-snippet.md +1 -0
- package/prompts/replace.md +1 -0
- package/prompts/undo-last-change-guidelines.md +1 -0
- package/prompts/undo-last-change-snippet.md +1 -0
- package/prompts/undo-last-change.md +1 -0
- package/src/anchor-registry.ts +977 -0
- package/src/auto-read-all-state.ts +27 -0
- package/src/auto-read-all.ts +477 -0
- package/src/batch.ts +767 -0
- package/src/commit.ts +137 -0
- package/src/config-ui.ts +212 -0
- package/src/config.ts +235 -0
- package/src/constants.ts +26 -0
- package/src/edit-common.ts +206 -0
- package/src/file-kind.ts +191 -0
- package/src/file-reader.ts +135 -0
- package/src/find.ts +244 -0
- package/src/fs-write.ts +231 -0
- package/src/glob.ts +186 -0
- package/src/grep.ts +690 -0
- package/src/hash-store/cache.ts +18 -0
- package/src/hash-store/retry.ts +44 -0
- package/src/hash-store/validation.ts +62 -0
- package/src/hash-store.ts +609 -0
- package/src/hashline/alphabet.ts +21 -0
- package/src/hashline/anchor-table.json +1 -0
- package/src/hashline/apply.ts +297 -0
- package/src/hashline/hash.ts +119 -0
- package/src/hashline/hasher.ts +47 -0
- package/src/hashline/index.ts +50 -0
- package/src/hashline/parse.ts +84 -0
- package/src/hashline/resolve.ts +373 -0
- package/src/insert.ts +258 -0
- package/src/normalize.ts +27 -0
- package/src/paths.ts +56 -0
- package/src/payload-contract.ts +133 -0
- package/src/prompts.ts +13 -0
- package/src/read.ts +286 -0
- package/src/replace-diff.ts +610 -0
- package/src/replace-render.ts +390 -0
- package/src/replace-response.ts +166 -0
- package/src/replace-undo.ts +270 -0
- package/src/replace.ts +318 -0
- package/src/served.ts +36 -0
- package/src/utils.ts +387 -0
- package/src/validation.ts +45 -0
- package/src/write-hook.ts +53 -0
package/src/utils.ts
ADDED
|
@@ -0,0 +1,387 @@
|
|
|
1
|
+
import { NUL_CONTENT_MSG, MAX_BYTES } from "./constants";
|
|
2
|
+
import { HASH_CLASS } from "./hashline/alphabet";
|
|
3
|
+
|
|
4
|
+
export function isRec(value: unknown): value is Record<string, unknown> {
|
|
5
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
export function normalizeFilePath(record: Record<string, unknown>): void {
|
|
9
|
+
if (typeof record.path !== "string" && typeof record.file_path === "string") {
|
|
10
|
+
record.path = record.file_path;
|
|
11
|
+
delete record.file_path;
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export function normalizeAnchors(record: Record<string, unknown>): void {
|
|
16
|
+
if (typeof record.remove_from !== "string" && typeof record.replace_from === "string") {
|
|
17
|
+
record.remove_from = record.replace_from;
|
|
18
|
+
delete record.replace_from;
|
|
19
|
+
}
|
|
20
|
+
if (typeof record.remove_to !== "string" && typeof record.replace_to === "string") {
|
|
21
|
+
record.remove_to = record.replace_to;
|
|
22
|
+
delete record.replace_to;
|
|
23
|
+
}
|
|
24
|
+
if (typeof record.remove_from !== "string" && typeof record.from === "string") {
|
|
25
|
+
record.remove_from = record.from;
|
|
26
|
+
delete record.from;
|
|
27
|
+
}
|
|
28
|
+
if (typeof record.remove_to !== "string" && typeof record.to === "string") {
|
|
29
|
+
record.remove_to = record.to;
|
|
30
|
+
delete record.to;
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export function normalizeRequest(input: unknown): unknown {
|
|
35
|
+
if (!isRec(input)) return input;
|
|
36
|
+
const record: Record<string, unknown> = { ...input };
|
|
37
|
+
normalizeFilePath(record);
|
|
38
|
+
normalizeAnchors(record);
|
|
39
|
+
normalizeEditLines(record);
|
|
40
|
+
return record;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export function makePrepareArguments(): (args: unknown) => any {
|
|
44
|
+
return normalizeRequest;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export function splitLines(text: string): string[] {
|
|
48
|
+
if (text.length === 0) return [""];
|
|
49
|
+
const lines = text.split("\n");
|
|
50
|
+
return text.endsWith("\n") ? lines.slice(0, -1) : lines;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export function visLines(text: string): string[] {
|
|
54
|
+
return text.length === 0 ? [] : splitLines(text);
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
export function rejectUnknownFields(
|
|
59
|
+
obj: Record<string, unknown>,
|
|
60
|
+
allowed: Set<string>,
|
|
61
|
+
label: string,
|
|
62
|
+
hint?: string,
|
|
63
|
+
): void {
|
|
64
|
+
const unknown = Object.keys(obj).filter((key) => !allowed.has(key));
|
|
65
|
+
if (unknown.length > 0) {
|
|
66
|
+
const suffix = hint ? ` ${hint}` : "";
|
|
67
|
+
throw new Error(
|
|
68
|
+
`[E_BAD_SHAPE] ${label} contains unknown or unsupported fields: ${unknown.join(", ")}.${suffix}`,
|
|
69
|
+
);
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
export function cntDiff(diff: string, marker: "+" | "-"): number {
|
|
74
|
+
if (!diff) return 0;
|
|
75
|
+
let count = 0;
|
|
76
|
+
for (const line of diff.split("\n")) {
|
|
77
|
+
if (
|
|
78
|
+
line.startsWith(marker) &&
|
|
79
|
+
!line.startsWith(`${marker}${marker}${marker}`)
|
|
80
|
+
) {
|
|
81
|
+
count += 1;
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
return count;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
export function abortIf(signal?: AbortSignal): void {
|
|
88
|
+
if (signal?.aborted) throw new Error("Operation aborted");
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
export function assertNoNul(lines: string[]): void {
|
|
92
|
+
if (lines.some((line) => line.includes("\0"))) throw new Error(NUL_CONTENT_MSG);
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
export function errCode(error: unknown): string | undefined {
|
|
96
|
+
if (error instanceof Error) {
|
|
97
|
+
return (error as NodeJS.ErrnoException).code;
|
|
98
|
+
}
|
|
99
|
+
return undefined;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
export function lastNonEmptyIndex(lines: string[]): number {
|
|
103
|
+
for (let i = lines.length - 1; i >= 0; i--) {
|
|
104
|
+
if (lines[i]!.length > 0) return i;
|
|
105
|
+
}
|
|
106
|
+
return -1;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
export function firstNonEmptyIndex(lines: string[]): number {
|
|
110
|
+
for (let i = 0; i < lines.length; i++) {
|
|
111
|
+
if (lines[i]!.length > 0) return i;
|
|
112
|
+
}
|
|
113
|
+
return -1;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
export function lastNonEmpty(lines: string[]): string | undefined {
|
|
117
|
+
const idx = lastNonEmptyIndex(lines);
|
|
118
|
+
return idx >= 0 ? lines[idx] : undefined;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
export function firstNonEmpty(lines: string[]): string | undefined {
|
|
122
|
+
const idx = firstNonEmptyIndex(lines);
|
|
123
|
+
return idx >= 0 ? lines[idx] : undefined;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
export function truncateToBytes(s: string, maxBytes: number): string {
|
|
127
|
+
if (Buffer.byteLength(s, "utf-8") <= maxBytes) return s;
|
|
128
|
+
let out = "";
|
|
129
|
+
let bytes = 0;
|
|
130
|
+
for (const ch of s) {
|
|
131
|
+
const chBytes = Buffer.byteLength(ch, "utf-8");
|
|
132
|
+
if (bytes + chBytes > maxBytes) break;
|
|
133
|
+
out += ch;
|
|
134
|
+
bytes += chBytes;
|
|
135
|
+
}
|
|
136
|
+
return out;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
export function getCached<K, V>(map: Map<K, V>, key: K, compute: (key: K) => V): V {
|
|
140
|
+
if (map.has(key)) return map.get(key)!;
|
|
141
|
+
const v = compute(key);
|
|
142
|
+
map.set(key, v);
|
|
143
|
+
return v;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
const HASH_ROW_RE = new RegExp(`^${HASH_CLASS}│`);
|
|
147
|
+
|
|
148
|
+
export function isHashRow(line: string): boolean {
|
|
149
|
+
return HASH_ROW_RE.test(line);
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
export function gutterWidth(max: number, fallback: number): number {
|
|
153
|
+
return String(max || fallback).length;
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
function formatGutter(n: number, width: number): string {
|
|
157
|
+
return String(n).padStart(width) + " │ ";
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
function blankGutter(width: number): string {
|
|
161
|
+
return " ".repeat(width) + " │ ";
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
export function numberedRead(text: string, offset: number): string {
|
|
165
|
+
const lines = text.split("\n");
|
|
166
|
+
const hashLines = lines.filter(isHashRow).length;
|
|
167
|
+
const max = hashLines > 0 ? offset + hashLines - 1 : offset;
|
|
168
|
+
const width = gutterWidth(max, offset);
|
|
169
|
+
let n = offset;
|
|
170
|
+
return lines.map((line) => {
|
|
171
|
+
if (!isHashRow(line)) return line;
|
|
172
|
+
const prefix = formatGutter(n++, width);
|
|
173
|
+
return prefix + line;
|
|
174
|
+
}).join("\n");
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
export function withLineNumbers(text: string, numbers: (number | null | undefined)[]): string {
|
|
178
|
+
const lines = text.split("\n");
|
|
179
|
+
const nums = numbers ?? [];
|
|
180
|
+
const max = nums.reduce<number>((m, n) => n !== undefined && n !== null && n > m ? n : m, 0);
|
|
181
|
+
const width = gutterWidth(max, lines.length);
|
|
182
|
+
return lines.map((line, i) => {
|
|
183
|
+
const n = nums[i];
|
|
184
|
+
const prefix = n !== undefined && n !== null ? formatGutter(n, width) : blankGutter(width);
|
|
185
|
+
return prefix + line;
|
|
186
|
+
}).join("\n");
|
|
187
|
+
}
|
|
188
|
+
export function clipLine(line: string, maxLen = 200): string {
|
|
189
|
+
const flat = line.replace(/\n/g, "\\n");
|
|
190
|
+
return flat.length > maxLen ? `${flat.slice(0, maxLen)}...` : flat;
|
|
191
|
+
}
|
|
192
|
+
export function assertLineLimit(content: string, displayPath: string, limit: number): void {
|
|
193
|
+
const count = splitLines(content).length;
|
|
194
|
+
if (count > limit) throw new Error(formatLineLimit(displayPath, limit, count));
|
|
195
|
+
}
|
|
196
|
+
export function assertByteLimit(content: string, displayPath: string, limit = MAX_BYTES): void {
|
|
197
|
+
if (Buffer.byteLength(content, "utf-8") > limit) {
|
|
198
|
+
throw new Error(`[E_FILE_TOO_LARGE] File is too large: ${displayPath} (exceeds the ${limit / (1024 * 1024)}MB size limit). For very large files, use write.`);
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
export function lineLimitMoreThanMessage(displayPath: string, limit: number): string {
|
|
202
|
+
return formatLineLimit(displayPath, limit, undefined);
|
|
203
|
+
}
|
|
204
|
+
function formatLineLimit(displayPath: string, limit: number, count: number | undefined): string {
|
|
205
|
+
const detail = count === undefined ? `has more than ${limit}` : `has ${count}`;
|
|
206
|
+
return `[E_FILE_TOO_LARGE] ${displayPath} ${detail} lines, exceeding the ${limit}-line hashline limit. For very large files, use write.`;
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
function stripCodeFence(text: string): string {
|
|
210
|
+
const trimmed = text.trim();
|
|
211
|
+
const fenced = /^```[^\n]*\n([\s\S]*?)\n?```$/.exec(trimmed);
|
|
212
|
+
return fenced ? fenced[1]!.trim() : trimmed;
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
function arrayLiteralEnd(text: string): number {
|
|
216
|
+
let depth = 0;
|
|
217
|
+
let quote: string | undefined;
|
|
218
|
+
let escaped = false;
|
|
219
|
+
for (let index = 0; index < text.length; index++) {
|
|
220
|
+
const char = text[index]!;
|
|
221
|
+
if (escaped) {
|
|
222
|
+
escaped = false;
|
|
223
|
+
continue;
|
|
224
|
+
}
|
|
225
|
+
if (char === "\\") {
|
|
226
|
+
escaped = true;
|
|
227
|
+
continue;
|
|
228
|
+
}
|
|
229
|
+
if (quote !== undefined) {
|
|
230
|
+
if (char === quote) quote = undefined;
|
|
231
|
+
continue;
|
|
232
|
+
}
|
|
233
|
+
if (char === '"' || char === "'") {
|
|
234
|
+
quote = char;
|
|
235
|
+
continue;
|
|
236
|
+
}
|
|
237
|
+
if (char === "[") depth += 1;
|
|
238
|
+
else if (char === "]") {
|
|
239
|
+
depth -= 1;
|
|
240
|
+
if (depth === 0) return index + 1;
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
return -1;
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
function stripTrailingMemberCall(text: string): string {
|
|
247
|
+
if (!text.startsWith("[")) return text;
|
|
248
|
+
const end = arrayLiteralEnd(text);
|
|
249
|
+
if (end < 0) return text;
|
|
250
|
+
const rest = text.slice(end);
|
|
251
|
+
if (rest.trim().length === 0) return text;
|
|
252
|
+
if (!rest.trimStart().startsWith(".") || !rest.trimEnd().endsWith(")")) return text;
|
|
253
|
+
return text.slice(0, end);
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
function jsonStringArray(text: string): string[] | undefined {
|
|
257
|
+
try {
|
|
258
|
+
const parsed: unknown = JSON.parse(text);
|
|
259
|
+
if (Array.isArray(parsed) && parsed.every((entry) => typeof entry === "string")) {
|
|
260
|
+
return parsed as string[];
|
|
261
|
+
}
|
|
262
|
+
} catch {
|
|
263
|
+
}
|
|
264
|
+
return undefined;
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
function decodeEscape(char: string): string | undefined {
|
|
268
|
+
switch (char) {
|
|
269
|
+
case "\"": return "\"";
|
|
270
|
+
case "'": return "'";
|
|
271
|
+
case "\\": return "\\";
|
|
272
|
+
case "/": return "/";
|
|
273
|
+
case "b": return "\b";
|
|
274
|
+
case "f": return "\f";
|
|
275
|
+
case "n": return "\n";
|
|
276
|
+
case "r": return "\r";
|
|
277
|
+
case "t": return "\t";
|
|
278
|
+
default: return undefined;
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
function scanQuotedSegment(inner: string, start: number): { value: string; next: number } | undefined {
|
|
283
|
+
const quote = inner[start]!;
|
|
284
|
+
let out = "";
|
|
285
|
+
let index = start + 1;
|
|
286
|
+
while (index < inner.length) {
|
|
287
|
+
const char = inner[index]!;
|
|
288
|
+
if (char === "\\") {
|
|
289
|
+
const escaped = inner[index + 1];
|
|
290
|
+
if (escaped === undefined) return undefined;
|
|
291
|
+
if (escaped === "u") {
|
|
292
|
+
const hex = inner.slice(index + 2, index + 6);
|
|
293
|
+
if (!/^[0-9a-fA-F]{4}$/.test(hex)) return undefined;
|
|
294
|
+
out += String.fromCharCode(Number.parseInt(hex, 16));
|
|
295
|
+
index += 6;
|
|
296
|
+
continue;
|
|
297
|
+
}
|
|
298
|
+
const decoded = decodeEscape(escaped);
|
|
299
|
+
if (decoded === undefined) return undefined;
|
|
300
|
+
out += decoded;
|
|
301
|
+
index += 2;
|
|
302
|
+
continue;
|
|
303
|
+
}
|
|
304
|
+
if (char === quote) return { value: out, next: index + 1 };
|
|
305
|
+
out += char;
|
|
306
|
+
index += 1;
|
|
307
|
+
}
|
|
308
|
+
return undefined;
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
function scanArrayText(inner: string): string[] | undefined {
|
|
312
|
+
const values: string[] = [];
|
|
313
|
+
let index = 0;
|
|
314
|
+
while (index < inner.length && /\s/.test(inner[index]!)) index += 1;
|
|
315
|
+
if (index >= inner.length) return [];
|
|
316
|
+
for (;;) {
|
|
317
|
+
if (inner[index] !== "\"" && inner[index] !== "'") return undefined;
|
|
318
|
+
const segment = scanQuotedSegment(inner, index);
|
|
319
|
+
if (!segment) return undefined;
|
|
320
|
+
values.push(segment.value);
|
|
321
|
+
index = segment.next;
|
|
322
|
+
while (index < inner.length && /\s/.test(inner[index]!)) index += 1;
|
|
323
|
+
if (index >= inner.length) return values;
|
|
324
|
+
if (inner[index] !== ",") return undefined;
|
|
325
|
+
index += 1;
|
|
326
|
+
while (index < inner.length && /\s/.test(inner[index]!)) index += 1;
|
|
327
|
+
if (index >= inner.length) return values;
|
|
328
|
+
}
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
function decodeArrayText(value: unknown): string[] | undefined {
|
|
332
|
+
if (typeof value !== "string") return undefined;
|
|
333
|
+
const trimmed = stripTrailingMemberCall(stripCodeFence(value));
|
|
334
|
+
if (!trimmed.startsWith("[") || !trimmed.endsWith("]")) return undefined;
|
|
335
|
+
const decoded = jsonStringArray(trimmed);
|
|
336
|
+
if (decoded !== undefined && decoded.length > 0) return decoded;
|
|
337
|
+
const scanned = scanArrayText(trimmed.slice(1, -1));
|
|
338
|
+
return scanned !== undefined && scanned.length > 0 ? scanned : undefined;
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
function looksLikeStringArray(value: unknown): boolean {
|
|
342
|
+
if (typeof value !== "string") return false;
|
|
343
|
+
const trimmed = stripTrailingMemberCall(stripCodeFence(value));
|
|
344
|
+
return /^\[\s*['"]/.test(trimmed) && !trimmed.endsWith("].");
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
export function decodeStringArray(value: unknown, warnings?: string[], label = "replacement_lines"): string[] | undefined {
|
|
348
|
+
const candidate = typeof value === "string"
|
|
349
|
+
? value
|
|
350
|
+
: Array.isArray(value) && value.length === 1 && typeof value[0] === "string"
|
|
351
|
+
? value[0]
|
|
352
|
+
: undefined;
|
|
353
|
+
if (candidate === undefined) return undefined;
|
|
354
|
+
const decoded = decodeArrayText(candidate);
|
|
355
|
+
if (decoded !== undefined) {
|
|
356
|
+
return decoded;
|
|
357
|
+
}
|
|
358
|
+
if (looksLikeStringArray(candidate)) {
|
|
359
|
+
warnings?.push(`[W_BAD_SHAPE] ${label} looked like a JSON array but could not be parsed; kept as one literal line: ${clipLine(candidate, 60)}`);
|
|
360
|
+
}
|
|
361
|
+
return undefined;
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
function splitEditLines(text: string): string[] {
|
|
365
|
+
return text.replace(/\r\n/g, "\n").replace(/\r/g, "\n").split("\n");
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
function normalizeLineFieldValue(value: unknown): string[] | undefined {
|
|
369
|
+
const candidate = typeof value === "string"
|
|
370
|
+
? value
|
|
371
|
+
: Array.isArray(value) && value.length === 1 && typeof value[0] === "string"
|
|
372
|
+
? value[0]
|
|
373
|
+
: undefined;
|
|
374
|
+
if (candidate === undefined) return undefined;
|
|
375
|
+
const decoded = decodeStringArray(candidate);
|
|
376
|
+
if (decoded !== undefined) return decoded;
|
|
377
|
+
if (/^\[\s*\]$/.test(stripTrailingMemberCall(stripCodeFence(candidate)))) return [];
|
|
378
|
+
return splitEditLines(candidate);
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
function normalizeEditLines(record: Record<string, unknown>): void {
|
|
382
|
+
for (const key of ["replacement_lines", "lines"]) {
|
|
383
|
+
if (!(key in record)) continue;
|
|
384
|
+
const lines = normalizeLineFieldValue(record[key]);
|
|
385
|
+
if (lines !== undefined) record[key] = lines;
|
|
386
|
+
}
|
|
387
|
+
}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import { constants } from "node:fs";
|
|
2
|
+
import { access as fsAccess } from "node:fs/promises";
|
|
3
|
+
import type { LFile } from "./file-kind";
|
|
4
|
+
import type { FileIdentity } from "./fs-write";
|
|
5
|
+
import { errCode } from "./utils";
|
|
6
|
+
|
|
7
|
+
export async function valAccess(
|
|
8
|
+
absolutePath: string,
|
|
9
|
+
path: string,
|
|
10
|
+
accessMode: number = constants.R_OK,
|
|
11
|
+
): Promise<void> {
|
|
12
|
+
try {
|
|
13
|
+
await fsAccess(absolutePath, accessMode);
|
|
14
|
+
} catch (error: unknown) {
|
|
15
|
+
const code = errCode(error);
|
|
16
|
+
if (code === "ENOENT") {
|
|
17
|
+
throw new Error(`[E_NOT_FOUND] File not found: ${path}`);
|
|
18
|
+
}
|
|
19
|
+
if (code === "EACCES" || code === "EPERM") {
|
|
20
|
+
const accessLabel = accessMode & constants.W_OK ? "not writable" : "not readable";
|
|
21
|
+
throw new Error(`[E_ACCESS] File is ${accessLabel}: ${path}`);
|
|
22
|
+
}
|
|
23
|
+
if (code === "ELOOP") {
|
|
24
|
+
throw new Error(`[E_ACCESS] Too many symbolic links while resolving: ${path}`);
|
|
25
|
+
}
|
|
26
|
+
throw new Error(`[E_ACCESS] Cannot access file: ${path}`);
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export function valKind(file: LFile, path: string): asserts file is { kind: "text"; text: string; identity?: FileIdentity; hadUtf8DecodeErrors?: true } {
|
|
31
|
+
if (file.kind === "directory") {
|
|
32
|
+
throw new Error(`[E_NOT_TEXT] Path is a directory: ${path}. Use ls to inspect directories.`);
|
|
33
|
+
}
|
|
34
|
+
if (file.kind === "binary") {
|
|
35
|
+
throw new Error(`[E_NOT_TEXT] Path is a binary file: ${path} (${file.description}).`);
|
|
36
|
+
}
|
|
37
|
+
if (file.kind === "image") {
|
|
38
|
+
throw new Error(`[E_NOT_TEXT] Path is an image file: ${path}.`);
|
|
39
|
+
}
|
|
40
|
+
if (file.kind === "too_large") {
|
|
41
|
+
throw new Error(
|
|
42
|
+
`[E_FILE_TOO_LARGE] File is too large: ${path} (${file.description}). For very large files, use write.`,
|
|
43
|
+
);
|
|
44
|
+
}
|
|
45
|
+
}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
import { HASH_CLASS } from "./hashline/alphabet";
|
|
3
|
+
import { HASH_SEP } from "./hashline/hash";
|
|
4
|
+
import { servedForPath, withAnchorSession } from "./anchor-registry";
|
|
5
|
+
import { resolveInCwd } from "./fs-write";
|
|
6
|
+
import { abortIf, splitLines, isRec, normalizeFilePath } from "./utils";
|
|
7
|
+
|
|
8
|
+
const HASH_ECHO_RE = new RegExp(`^(?: *[0-9]+ ${HASH_SEP} )?[+ -]?(${HASH_CLASS})${HASH_SEP}`);
|
|
9
|
+
|
|
10
|
+
function searchEcho(lines: string[], served: ReadonlyMap<string, string> | ReadonlySet<string>): { line: number; hash: string } | undefined {
|
|
11
|
+
for (let i = 0; i < lines.length; i++) {
|
|
12
|
+
const match = HASH_ECHO_RE.exec(lines[i]!);
|
|
13
|
+
if (match && served.has(match[1]! as never)) return { line: i + 1, hash: match[1]! };
|
|
14
|
+
}
|
|
15
|
+
return undefined;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export function findServedHashEcho(content: string, served: ReadonlyMap<string, string> | ReadonlySet<string>): { line: number; hash: string } | undefined {
|
|
19
|
+
return searchEcho(splitLines(content), served);
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export async function servedHashEchoDenial(rawPath: string, content: string, cwd: string, signal?: AbortSignal): Promise<string | undefined> {
|
|
23
|
+
abortIf(signal);
|
|
24
|
+
const { resolved } = await resolveInCwd(rawPath, cwd);
|
|
25
|
+
abortIf(signal);
|
|
26
|
+
const served = servedForPath(resolved);
|
|
27
|
+
if (!served || served.size === 0) return undefined;
|
|
28
|
+
const echo = findServedHashEcho(content, served);
|
|
29
|
+
if (!echo) return undefined;
|
|
30
|
+
return `[E_WRITE_HASH_ECHO] Refused write to ${rawPath}: line ${echo.line} contains the copied ${echo.hash}${HASH_SEP} anchor served for this file. Remove the copied anchors and retry.`;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export function registerWriteHook(pi: ExtensionAPI): void {
|
|
34
|
+
pi.on("tool_call", async (event, ctx) => withAnchorSession(ctx, async () => {
|
|
35
|
+
if (event.toolName !== "write") return;
|
|
36
|
+
const input = event.input as Record<string, unknown> | undefined;
|
|
37
|
+
if (!input || !isRec(input)) return;
|
|
38
|
+
const normalized = { ...input };
|
|
39
|
+
normalizeFilePath(normalized);
|
|
40
|
+
const rawPath = normalized.path as unknown;
|
|
41
|
+
const content = normalized.content as unknown;
|
|
42
|
+
if (typeof rawPath !== "string" || typeof content !== "string") return;
|
|
43
|
+
const signal = ctx.signal;
|
|
44
|
+
try {
|
|
45
|
+
const reason = await servedHashEchoDenial(rawPath, content, ctx.cwd, signal);
|
|
46
|
+
if (reason !== undefined) return { block: true, reason };
|
|
47
|
+
} catch (error) {
|
|
48
|
+
if (signal?.aborted) throw error;
|
|
49
|
+
console.error("write hook failed:", error);
|
|
50
|
+
}
|
|
51
|
+
return;
|
|
52
|
+
}));
|
|
53
|
+
}
|