@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
ts 226 lines 8.86 KB
Raw
1 // @effect-diagnostics nodeBuiltinImport:off - the tool-call normalizer is synchronous
2 import * as NodeFS from "node:fs";
3
4 import { PositiveInt } from "@t3tools/contracts";
5 import { FILE_HEADERS_ONLY, formatPatch, structuredPatch, type StructuredPatchHunk } from "diff";
6 import * as Option from "effect/Option";
7 import * as Schema from "effect/Schema";
8
9 const PRE_EDIT_FILE_LIMIT = 1024 * 1024;
10 // The live preview runs synchronously. One budget covers every chunk in a call: the generic
11 // ACP formatter's edit-distance limit, plus a size limit that skips diffing entirely.
12 const EDIT_DIFF_BUDGET = 1_000;
13 const EDIT_TEXT_BUDGET = 256 * 1024;
14
15 /** The edit is too large to preview cheaply; the turn's checkpoint diff still shows it. */
16 export const ANTIGRAVITY_EDIT_DIFF_OMITTED = Symbol("AntigravityEditDiffOmitted");
17 const SNIPPET_LABEL = " snippet, line unknown";
18
19 /** True when no chunk could be placed; a patch never mixes placed and unplaced chunks. */
20 export function isAntigravitySnippetPatch(patch: string): boolean {
21 return /^@@ .* @@.*$/m.exec(patch)?.[0].endsWith(SNIPPET_LABEL) === true;
22 }
23
24 // The runtime reads a missing, 0 or invalid line as unspecified.
25 const Line = Schema.optional(Schema.Unknown);
26 const decodeLine = Schema.decodeUnknownOption(PositiveInt);
27 const lineOf = (value: unknown) => Option.getOrUndefined(decodeLine(value));
28 const ReplacementChunk = Schema.Struct({
29 TargetContent: Schema.String,
30 ReplacementContent: Schema.String,
31 StartLine: Line,
32 EndLine: Line,
33 });
34 // replace_file_content sends one chunk at the top level; multi_replace_file_content sends a list.
35 const decodeEditInput = Schema.decodeUnknownOption(
36 Schema.Union([
37 Schema.Struct({ ReplacementChunks: Schema.NonEmptyArray(ReplacementChunk) }),
38 ReplacementChunk,
39 ]),
40 );
41 const decodeLocations = Schema.decodeUnknownOption(Schema.Array(Schema.Struct({ line: Line })));
42 // The runtime accepts edit arguments in either casing.
43 const PASCAL_KEYS: Readonly<Record<string, string>> = {
44 replacement_chunks: "ReplacementChunks",
45 target_content: "TargetContent",
46 replacement_content: "ReplacementContent",
47 start_line: "StartLine",
48 end_line: "EndLine",
49 };
50 const pascalKeys = (value: unknown): unknown => {
51 if (Array.isArray(value)) return value.map(pascalKeys);
52 if (typeof value !== "object" || value === null) return value;
53 const fields: Record<string, unknown> = value as Record<string, unknown>;
54 const result: Record<string, unknown> = {};
55 for (const [key, entry] of Object.entries(fields)) {
56 const pascal = PASCAL_KEYS[key];
57 // Like the runtime, a present PascalCase value wins over its snake_case alias.
58 if (pascal === undefined) result[key] ??= pascalKeys(entry);
59 else if (fields[pascal] == null) result[pascal] = pascalKeys(entry);
60 }
61 return result;
62 };
63
64 /** Reads a small file for snippet matching; edits to large or unreadable files stay unlocated. */
65 export function readAntigravityPreEditFile(path: string): string | undefined {
66 try {
67 const stat = NodeFS.statSync(path);
68 return stat.isFile() && stat.size <= PRE_EDIT_FILE_LIMIT
69 ? NodeFS.readFileSync(path, "utf8")
70 : undefined;
71 } catch {
72 return undefined;
73 }
74 }
75
76 /** The line of the snippet's only match starting within `from`..`to`, if it spans whole lines. */
77 function uniqueStartLine(
78 text: string | undefined,
79 snippet: string,
80 from = 1,
81 to = Number.POSITIVE_INFINITY,
82 ): number | undefined {
83 if (text === undefined || snippet === "") return undefined;
84 let found: { readonly line: number; readonly whole: boolean } | undefined;
85 let line = 1;
86 let lineStart = 0;
87 let nextBreak = text.indexOf("\n");
88 for (let index = text.indexOf(snippet); index !== -1; index = text.indexOf(snippet, index + 1)) {
89 while (nextBreak !== -1 && nextBreak < index) {
90 line++;
91 lineStart = nextBreak + 1;
92 nextBreak = text.indexOf("\n", lineStart);
93 }
94 if (line > to) break;
95 if (line < from) continue;
96 if (found !== undefined) return undefined;
97 const end = index + snippet.length;
98 // A hunk replaces whole lines.
99 const whole =
100 index === lineStart && (end === text.length || snippet.endsWith("\n") || text[end] === "\n");
101 found = { line, whole };
102 }
103 return found?.whole === true ? found.line : undefined;
104 }
105
106 function snippetHunks(
107 oldText: string,
108 newText: string,
109 maxEditLength: number,
110 ): StructuredPatchHunk[] | undefined {
111 const before = oldText.replaceAll("\r\n", "\n");
112 const after = newText.replaceAll("\r\n", "\n");
113 // A target without its newline keeps the line's own newline, on both sides.
114 const eol = before.endsWith("\n") ? "" : "\n";
115 return structuredPatch("", "", before + eol, after + eol, undefined, undefined, {
116 maxEditLength,
117 })?.hunks;
118 }
119
120 const changedLines = (hunks: ReadonlyArray<StructuredPatchHunk>) =>
121 hunks.reduce(
122 (total, hunk) =>
123 total + hunk.lines.filter((line) => line.startsWith("+") || line.startsWith("-")).length,
124 0,
125 );
126
127 /**
128 * Antigravity reports replacements as bare old/new snippets. `StartLine` only starts the
129 * runtime's search range, so a chunk is placed at its unique match in the pre-edit file within
130 * that range. All-unplaced chunks get hunks labeled as snippets; a mix is omitted.
131 */
132 export function antigravityEditPatch(input: {
133 readonly path: string;
134 readonly rawInput: unknown;
135 readonly locations?: unknown;
136 /** Pass only while the edit is pending, when the file still holds the old text. */
137 readonly readPreEditFile?: ((path: string) => string | undefined) | undefined;
138 }): string | typeof ANTIGRAVITY_EDIT_DIFF_OMITTED | undefined {
139 const edit = Option.getOrUndefined(decodeEditInput(pascalKeys(input.rawInput)));
140 if (edit === undefined) return undefined;
141 const announced = lineOf(Option.getOrUndefined(decodeLocations(input.locations))?.[0]?.line);
142 const listed = "ReplacementChunks" in edit ? edit.ReplacementChunks : [edit];
143 const chunks = listed.map((chunk) => ({
144 ...chunk,
145 StartLine: lineOf(chunk.StartLine) ?? (listed.length === 1 ? announced : undefined),
146 EndLine: lineOf(chunk.EndLine),
147 }));
148 let file: string | undefined;
149 let fileRead = false;
150 const textSize = chunks.reduce(
151 (total, chunk) => total + chunk.TargetContent.length + chunk.ReplacementContent.length,
152 0,
153 );
154 if (textSize > EDIT_TEXT_BUDGET) return ANTIGRAVITY_EDIT_DIFF_OMITTED;
155 let budget = EDIT_DIFF_BUDGET;
156 const placed: Array<{ readonly start: number; readonly hunks: StructuredPatchHunk[] }> = [];
157 const snippets: StructuredPatchHunk[] = [];
158 for (const chunk of chunks) {
159 // Whether a changed final line break, or a cleared line, splits, joins or removes lines
160 // depends on what follows the match. Only a whole-line delete is certain.
161 const targetEndsLine = chunk.TargetContent.endsWith("\n");
162 if (
163 chunk.ReplacementContent === ""
164 ? !targetEndsLine
165 : targetEndsLine !== chunk.ReplacementContent.endsWith("\n")
166 )
167 return ANTIGRAVITY_EDIT_DIFF_OMITTED;
168 const hunks = snippetHunks(chunk.TargetContent, chunk.ReplacementContent, budget);
169 // A change to the line ending alone leaves no LF hunk to show.
170 if (
171 hunks === undefined ||
172 (hunks.length === 0 && chunk.TargetContent !== chunk.ReplacementContent)
173 )
174 return ANTIGRAVITY_EDIT_DIFF_OMITTED;
175 budget -= changedLines(hunks);
176 if (budget < 0) return ANTIGRAVITY_EDIT_DIFF_OMITTED;
177 let start: number | undefined;
178 if (input.readPreEditFile !== undefined) {
179 // Line numbers do not depend on CRLF, so search with LF on both sides.
180 if (!fileRead) file = input.readPreEditFile(input.path)?.replaceAll("\r\n", "\n");
181 fileRead = true;
182 start = uniqueStartLine(
183 file,
184 chunk.TargetContent.replaceAll("\r\n", "\n"),
185 chunk.StartLine,
186 chunk.EndLine,
187 );
188 }
189 if (start === undefined) snippets.push(...hunks);
190 else placed.push({ start, hunks });
191 }
192 // A placed hunk beside an unplaced one would still number the unplaced one from line 1.
193 if (placed.length > 0 && snippets.length > 0) return ANTIGRAVITY_EDIT_DIFF_OMITTED;
194 let shift = 0;
195 const placedHunks = placed
196 .toSorted((left, right) => left.start - right.start)
197 .flatMap(({ start, hunks }) => {
198 const shifted = hunks.map((hunk) => ({
199 ...hunk,
200 oldStart: hunk.oldStart + start - 1,
201 newStart: hunk.newStart + start - 1 + shift,
202 }));
203 for (const hunk of hunks) shift += hunk.newLines - hunk.oldLines;
204 return shifted;
205 });
206 const section = (hunks: StructuredPatchHunk[]) =>
207 hunks.length === 0
208 ? ""
209 : formatPatch(
210 {
211 oldFileName: input.path,
212 newFileName: input.path,
213 oldHeader: undefined,
214 newHeader: undefined,
215 hunks,
216 },
217 FILE_HEADERS_ONLY,
218 );
219 const patch = [
220 section(placedHunks),
221 section(snippets).replace(/^@@ .* @@$/gm, `$&${SNIPPET_LABEL}`),
222 ]
223 .filter(Boolean)
224 .join("\n");
225 return patch || undefined;
226 }