@better-fs-tools/write 0.2.0 → 0.3.1
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/README.md +49 -37
- package/dist/bundle/create-fs-tools.d.ts +59 -19
- package/dist/bundle/create-fs-tools.js +56 -22
- package/dist/bundle/definitions.d.ts +51 -0
- package/dist/bundle/definitions.js +42 -0
- package/dist/contract/deps.d.ts +4 -4
- package/dist/contract/messages.d.ts +24 -2
- package/dist/core/create-tools.d.ts +9 -9
- package/dist/core/create-tools.js +11 -11
- package/dist/core/deps.d.ts +4 -4
- package/dist/core/deps.js +6 -6
- package/dist/core/messages.js +47 -5
- package/dist/core/patch-hunks.d.ts +7 -0
- package/dist/core/patch-hunks.js +88 -18
- package/dist/core/plan-edit.js +7 -2
- package/dist/core/plan-patch.js +9 -2
- package/dist/core/record.js +1 -0
- package/dist/index.d.ts +3 -3
- package/dist/matchers/keep-bytes.d.ts +31 -0
- package/dist/matchers/keep-bytes.js +76 -0
- package/dist/matchers/line-trimmed.d.ts +4 -1
- package/dist/matchers/line-trimmed.js +9 -1
- package/dist/matchers/normalized.d.ts +2 -1
- package/dist/matchers/normalized.js +7 -1
- package/dist/signature/definition.d.ts +41 -0
- package/dist/signature/definition.js +66 -0
- package/dist/signature/edit.d.ts +4 -5
- package/dist/signature/edit.js +5 -13
- package/dist/signature/index.d.ts +6 -2
- package/dist/signature/index.js +4 -2
- package/dist/signature/patch.d.ts +4 -1
- package/dist/signature/patch.js +4 -1
- package/dist/signature/write.d.ts +1 -6
- package/dist/signature/write.js +1 -8
- package/docs/architecture.md +8 -6
- package/docs/hosts.md +133 -55
- package/docs/result-schema.md +1 -0
- package/package.json +5 -4
|
@@ -3,6 +3,18 @@ import type { ToolMessages } from "@better-fs-tools/read";
|
|
|
3
3
|
import type { WriteToolName } from "./context.ts";
|
|
4
4
|
import type { WriteErrorCode, WritePhase } from "./result.ts";
|
|
5
5
|
export type WriteCanonicalParam = "path" | "edits" | "oldText" | "newText" | "replaceAll" | "content" | "patch";
|
|
6
|
+
/**
|
|
7
|
+
* What the tool wrote for one loose hit, compared line by line with the
|
|
8
|
+
* model's new lines. Each count is a number of lines.
|
|
9
|
+
*/
|
|
10
|
+
export interface FuzzyWrite {
|
|
11
|
+
/** Lines written with the file's own characters, not the model's. */
|
|
12
|
+
readonly keptLines: number;
|
|
13
|
+
/** Lines that kept the file's CR, which the model's line did not have. */
|
|
14
|
+
readonly keptLineEnds: number;
|
|
15
|
+
/** Lines that the matcher changed in another way, for example a new indentation. */
|
|
16
|
+
readonly adaptedLines: number;
|
|
17
|
+
}
|
|
6
18
|
/**
|
|
7
19
|
* Wording for every note the write tools produce. Text that names a model
|
|
8
20
|
* parameter gets the name from `param(name)`, which a signature overrides.
|
|
@@ -122,11 +134,13 @@ export interface WriteMessageCatalog extends ToolMessages {
|
|
|
122
134
|
path: string;
|
|
123
135
|
index: number;
|
|
124
136
|
}): string;
|
|
137
|
+
/** `written` is optional, so a host's own message can leave it out. */
|
|
125
138
|
fuzzyMatch(c: {
|
|
126
139
|
path: string;
|
|
127
140
|
index: number;
|
|
128
141
|
matcher: string;
|
|
129
142
|
lines: readonly [number, number];
|
|
143
|
+
written?: FuzzyWrite;
|
|
130
144
|
}): string;
|
|
131
145
|
repeatedMiss(c: {
|
|
132
146
|
path: string;
|
|
@@ -155,18 +169,26 @@ export interface WriteMessageCatalog extends ToolMessages {
|
|
|
155
169
|
hunk: number;
|
|
156
170
|
context: string;
|
|
157
171
|
}): string;
|
|
158
|
-
/**
|
|
172
|
+
/**
|
|
173
|
+
* `hunk` is one-based. `from` is the one-based line where the search
|
|
174
|
+
* started. `context` is the one-based line that the `@@` text matched, or
|
|
175
|
+
* null for a bare `@@`. The tool also tried the old lines at that line.
|
|
176
|
+
* Both are optional, so a host's own message can leave them out.
|
|
177
|
+
*/
|
|
159
178
|
patchLinesNotFound(c: {
|
|
160
179
|
path: string;
|
|
161
180
|
hunk: number;
|
|
162
181
|
lines: readonly string[];
|
|
182
|
+
from?: number;
|
|
183
|
+
context?: number | null;
|
|
163
184
|
}): string;
|
|
164
|
-
/** `hunk` is one-based. */
|
|
185
|
+
/** `hunk` is one-based. `written` is optional, as in fuzzyMatch. */
|
|
165
186
|
patchFuzzyMatch(c: {
|
|
166
187
|
path: string;
|
|
167
188
|
hunk: number;
|
|
168
189
|
matcher: string;
|
|
169
190
|
lines: readonly [number, number];
|
|
191
|
+
written?: FuzzyWrite;
|
|
170
192
|
}): string;
|
|
171
193
|
/** `files` is set when the rollback failed: the state of every file the patch targets. */
|
|
172
194
|
patchCommitFailed(c: {
|
|
@@ -1,23 +1,23 @@
|
|
|
1
1
|
import type { ApplyPatchTool, EditTool, WriteTool } from "../contract/context.ts";
|
|
2
2
|
import type { StateNeedsDigest } from "@better-fs-tools/read";
|
|
3
|
-
import type {
|
|
3
|
+
import type { ApplyPatchToolOptions, EditToolOptions, WriteToolOptions } from "../contract/deps.ts";
|
|
4
4
|
/**
|
|
5
|
-
* Creates the edit tool. Takes the same
|
|
5
|
+
* Creates the edit tool. Takes the same options as createWriteTool, plus
|
|
6
6
|
* a non-empty `matchers` list (default defaultEditMatchers()). Throws
|
|
7
|
-
* TypeError on invalid
|
|
7
|
+
* TypeError on invalid options.
|
|
8
8
|
*/
|
|
9
|
-
export declare function createEditTool<THost = undefined>(
|
|
9
|
+
export declare function createEditTool<THost = undefined>(options: EditToolOptions<THost> & StateNeedsDigest): EditTool<THost>;
|
|
10
10
|
/**
|
|
11
11
|
* Creates the write tool. Throws TypeError on an unknown key, a missing fs,
|
|
12
12
|
* an empty classifier or codec list, state without digest, or a malformed
|
|
13
13
|
* limit, message, or policy. limits, messages, and preconditions merge with
|
|
14
|
-
* the defaults key by key. Every other
|
|
14
|
+
* the defaults key by key. Every other option replaces its default.
|
|
15
15
|
*/
|
|
16
|
-
export declare function createWriteTool<THost = undefined>(
|
|
16
|
+
export declare function createWriteTool<THost = undefined>(options: WriteToolOptions<THost> & StateNeedsDigest): WriteTool<THost>;
|
|
17
17
|
/**
|
|
18
|
-
* Creates the apply_patch tool. Takes the same
|
|
18
|
+
* Creates the apply_patch tool. Takes the same options as
|
|
19
19
|
* createWriteTool, plus a non-empty `matchers` list (default
|
|
20
20
|
* defaultPatchMatchers()) and a `patchParser` (default codexPatchParser()).
|
|
21
|
-
* Throws TypeError on invalid
|
|
21
|
+
* Throws TypeError on invalid options.
|
|
22
22
|
*/
|
|
23
|
-
export declare function createApplyPatchTool<THost = undefined>(
|
|
23
|
+
export declare function createApplyPatchTool<THost = undefined>(options: ApplyPatchToolOptions<THost> & StateNeedsDigest): ApplyPatchTool<THost>;
|
|
@@ -4,12 +4,12 @@ import { isRecord } from "./input.js";
|
|
|
4
4
|
import { runApplyPatch } from "./patch-pipeline.js";
|
|
5
5
|
import { runEdit, runWrite } from "./pipeline.js";
|
|
6
6
|
/**
|
|
7
|
-
* Creates the edit tool. Takes the same
|
|
7
|
+
* Creates the edit tool. Takes the same options as createWriteTool, plus
|
|
8
8
|
* a non-empty `matchers` list (default defaultEditMatchers()). Throws
|
|
9
|
-
* TypeError on invalid
|
|
9
|
+
* TypeError on invalid options.
|
|
10
10
|
*/
|
|
11
|
-
export function createEditTool(
|
|
12
|
-
const resolved = resolveEditDependencies(
|
|
11
|
+
export function createEditTool(options) {
|
|
12
|
+
const resolved = resolveEditDependencies(options);
|
|
13
13
|
const misses = new MissCounter();
|
|
14
14
|
const edit = async (input, ctx) => {
|
|
15
15
|
if (ctx !== undefined && !isRecord(ctx))
|
|
@@ -23,10 +23,10 @@ export function createEditTool(deps) {
|
|
|
23
23
|
* Creates the write tool. Throws TypeError on an unknown key, a missing fs,
|
|
24
24
|
* an empty classifier or codec list, state without digest, or a malformed
|
|
25
25
|
* limit, message, or policy. limits, messages, and preconditions merge with
|
|
26
|
-
* the defaults key by key. Every other
|
|
26
|
+
* the defaults key by key. Every other option replaces its default.
|
|
27
27
|
*/
|
|
28
|
-
export function createWriteTool(
|
|
29
|
-
const resolved = resolveWriteDependencies(
|
|
28
|
+
export function createWriteTool(options) {
|
|
29
|
+
const resolved = resolveWriteDependencies(options, "write");
|
|
30
30
|
const write = async (input, ctx) => {
|
|
31
31
|
if (ctx !== undefined && !isRecord(ctx))
|
|
32
32
|
throw new TypeError("write context must be an object");
|
|
@@ -36,13 +36,13 @@ export function createWriteTool(deps) {
|
|
|
36
36
|
return write;
|
|
37
37
|
}
|
|
38
38
|
/**
|
|
39
|
-
* Creates the apply_patch tool. Takes the same
|
|
39
|
+
* Creates the apply_patch tool. Takes the same options as
|
|
40
40
|
* createWriteTool, plus a non-empty `matchers` list (default
|
|
41
41
|
* defaultPatchMatchers()) and a `patchParser` (default codexPatchParser()).
|
|
42
|
-
* Throws TypeError on invalid
|
|
42
|
+
* Throws TypeError on invalid options.
|
|
43
43
|
*/
|
|
44
|
-
export function createApplyPatchTool(
|
|
45
|
-
const resolved = resolveApplyPatchDependencies(
|
|
44
|
+
export function createApplyPatchTool(options) {
|
|
45
|
+
const resolved = resolveApplyPatchDependencies(options);
|
|
46
46
|
const applyPatch = async (input, ctx) => {
|
|
47
47
|
if (ctx !== undefined && !isRecord(ctx)) {
|
|
48
48
|
throw new TypeError("apply_patch context must be an object");
|
package/dist/core/deps.d.ts
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
import type { WritableFileSystem } from "@better-fs-tools/fs";
|
|
2
2
|
import type { ReadStateStore } from "@better-fs-tools/read";
|
|
3
|
-
import type { ApplyPatchDependencies,
|
|
3
|
+
import type { ApplyPatchDependencies, ApplyPatchToolOptions, EditDependencies, EditToolOptions, WriteDependencies, WriteToolOptions } from "../contract/deps.ts";
|
|
4
4
|
import type { PreconditionPolicy } from "../contract/preconditions.ts";
|
|
5
|
-
export declare function resolveWriteDependencies<THost>(deps:
|
|
6
|
-
export declare function resolveEditDependencies<THost>(deps:
|
|
7
|
-
export declare function resolveApplyPatchDependencies<THost>(deps:
|
|
5
|
+
export declare function resolveWriteDependencies<THost>(deps: WriteToolOptions<THost>, tool: string): WriteDependencies<THost>;
|
|
6
|
+
export declare function resolveEditDependencies<THost>(deps: EditToolOptions<THost>): EditDependencies<THost>;
|
|
7
|
+
export declare function resolveApplyPatchDependencies<THost>(deps: ApplyPatchToolOptions<THost>): ApplyPatchDependencies<THost>;
|
|
8
8
|
export declare function resolvePreconditions(overrides?: Partial<PreconditionPolicy>): Readonly<PreconditionPolicy>;
|
|
9
9
|
export declare function isWritable(value: unknown): value is WritableFileSystem;
|
|
10
10
|
export declare function isFileSystem(value: unknown): boolean;
|
package/dist/core/deps.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { isWritableFileSystem } from "@better-fs-tools/fs";
|
|
2
|
-
import { defaultClassifiers } from "@better-fs-tools/read";
|
|
2
|
+
import { defaultClassifiers, sha256Digest } from "@better-fs-tools/read";
|
|
3
3
|
import { utf8Codec } from "../codecs/utf8.js";
|
|
4
4
|
import { defaultPreconditions } from "../contract/preconditions.js";
|
|
5
5
|
import { defaultWriteFormatter } from "../formatters/default.js";
|
|
@@ -29,10 +29,10 @@ const KNOWN = new Set([
|
|
|
29
29
|
]);
|
|
30
30
|
export function resolveWriteDependencies(deps, tool) {
|
|
31
31
|
if (!isRecord(deps))
|
|
32
|
-
throw new TypeError(`${tool} tool
|
|
32
|
+
throw new TypeError(`${tool} tool options must be an object`);
|
|
33
33
|
for (const key of Object.keys(deps)) {
|
|
34
34
|
if (!KNOWN.has(key))
|
|
35
|
-
throw new TypeError(`Unknown ${tool} tool
|
|
35
|
+
throw new TypeError(`Unknown ${tool} tool option: ${key}`);
|
|
36
36
|
}
|
|
37
37
|
const { fs } = deps;
|
|
38
38
|
if (typeof fs !== "function" && !isWritable(fs)) {
|
|
@@ -52,7 +52,7 @@ export function resolveWriteDependencies(deps, tool) {
|
|
|
52
52
|
if (state !== null && typeof state !== "function" && !isStateStore(state)) {
|
|
53
53
|
throw new TypeError("state must be a store, a function that returns one, or null");
|
|
54
54
|
}
|
|
55
|
-
const digest = deps.digest
|
|
55
|
+
const digest = deps.digest === undefined ? sha256Digest() : deps.digest;
|
|
56
56
|
if (digest !== null && !isDigest(digest)) {
|
|
57
57
|
throw new TypeError("digest must have an id, create, and hash, or be null");
|
|
58
58
|
}
|
|
@@ -105,7 +105,7 @@ export function resolveWriteDependencies(deps, tool) {
|
|
|
105
105
|
}
|
|
106
106
|
export function resolveEditDependencies(deps) {
|
|
107
107
|
if (!isRecord(deps))
|
|
108
|
-
throw new TypeError("edit tool
|
|
108
|
+
throw new TypeError("edit tool options must be an object");
|
|
109
109
|
const { matchers = defaultEditMatchers(), recovery = false, ...shared } = deps;
|
|
110
110
|
if (!Array.isArray(matchers) || matchers.length === 0 || !matchers.every(isMatcher)) {
|
|
111
111
|
throw new TypeError("matchers must be a non-empty array of matchers");
|
|
@@ -120,7 +120,7 @@ export function resolveEditDependencies(deps) {
|
|
|
120
120
|
}
|
|
121
121
|
export function resolveApplyPatchDependencies(deps) {
|
|
122
122
|
if (!isRecord(deps))
|
|
123
|
-
throw new TypeError("apply_patch tool
|
|
123
|
+
throw new TypeError("apply_patch tool options must be an object");
|
|
124
124
|
const { matchers = defaultPatchMatchers(), patchParser = codexPatchParser(), ...shared } = deps;
|
|
125
125
|
if (!Array.isArray(matchers) || matchers.length === 0 || !matchers.every(isMatcher)) {
|
|
126
126
|
throw new TypeError("matchers must be a non-empty array of matchers");
|
package/dist/core/messages.js
CHANGED
|
@@ -24,7 +24,7 @@ function catalogUsingParam(param) {
|
|
|
24
24
|
extensionFailed: ({ path, extension, phase }) => `The ${extension} extension failed during the ${phase} phase${path === null ? "" : ` while changing ${path}`}; this is a host problem rather than a property of the file.`,
|
|
25
25
|
lockTimeout: ({ paths }) => `Another change to ${paths.join(", ")} is still running. Retry when it has finished.`,
|
|
26
26
|
notRead: ({ path, wholeFile }) => wholeFile
|
|
27
|
-
? `Read all of ${path} before replacing it.
|
|
27
|
+
? `Read all of ${path} before replacing it. Reads in ranges count when together they show every line.`
|
|
28
28
|
: `Read ${path} with the read tool before changing it.`,
|
|
29
29
|
stale: ({ path }) => `${path} changed since it was last read. Read it again, then retry.`,
|
|
30
30
|
staleRematched: ({ path }) => `${path} changed since it was last read, but every old text still matched exactly once, so the edit was applied.`,
|
|
@@ -70,7 +70,7 @@ function catalogUsingParam(param) {
|
|
|
70
70
|
overlap: ({ path, first, second }) => `Edits ${first + 1} and ${second + 1} change overlapping text in ${path}. Merge them into one edit.`,
|
|
71
71
|
noChange: ({ path }) => `The edits leave ${path} as it is. Check the ${param("newText")} values, or do not send the edit.`,
|
|
72
72
|
alreadyApplied: ({ path, index }) => `Edit ${index + 1} is already applied: the ${param("newText")} is in ${path} and the ${param("oldText")} is not. Do not send this edit again.`,
|
|
73
|
-
fuzzyMatch: ({ path, index, matcher, lines }) => `Edit ${index + 1} matched ${path} at
|
|
73
|
+
fuzzyMatch: ({ path, index, matcher, lines, written }) => `Edit ${index + 1} matched ${path} at ${lineSpan(lines)} only with the ${matcher} matcher, not exactly. The edit is applied.${wroteWhat(matcher, written)}`,
|
|
74
74
|
repeatedMiss: ({ path, misses }) => `This is miss ${misses} in a row on ${path}. Read the file again, include more surrounding lines, or replace the file with the write tool.`,
|
|
75
75
|
patchParse: ({ line, detail }) => `The patch could not be parsed at line ${line}: ${detail}`,
|
|
76
76
|
patchVerifyHeader: () => "Patch validation failed (no files were modified):",
|
|
@@ -80,11 +80,11 @@ function catalogUsingParam(param) {
|
|
|
80
80
|
: `${path} does not exist, so it cannot be deleted.`,
|
|
81
81
|
patchMoveExists: ({ path, from }) => `${path} already exists, so ${from} cannot move there. Choose another path, or delete ${path} first.`,
|
|
82
82
|
patchContextNotFound: ({ path, hunk, context }) => `${path}: hunk ${hunk}: failed to find the context line ${JSON.stringify(context)}.`,
|
|
83
|
-
patchLinesNotFound: ({ path, hunk, lines }) => [
|
|
84
|
-
`${path}: hunk ${hunk}: failed to find the expected lines:`,
|
|
83
|
+
patchLinesNotFound: ({ path, hunk, lines, from, context }) => [
|
|
84
|
+
`${path}: hunk ${hunk}: failed to find the expected lines${searchedWhere(from, context)}:`,
|
|
85
85
|
...lines.map((line) => ` ${line}`),
|
|
86
86
|
].join("\n"),
|
|
87
|
-
patchFuzzyMatch: ({ path, hunk, matcher, lines }) => `Hunk ${hunk} matched ${path} at
|
|
87
|
+
patchFuzzyMatch: ({ path, hunk, matcher, lines, written }) => `Hunk ${hunk} matched ${path} at ${lineSpan(lines)} only with the ${matcher} matcher, not exactly. The hunk is applied.${wroteWhat(matcher, written)}`,
|
|
88
88
|
patchCommitFailed: ({ path, code, rolledBack, files }) => rolledBack
|
|
89
89
|
? `Patch commit failed at ${path} (${code}). The patch was rolled back. No files are changed.`
|
|
90
90
|
: [
|
|
@@ -95,6 +95,48 @@ function catalogUsingParam(param) {
|
|
|
95
95
|
hookRewrote: ({ hook, path }) => `The ${hook} hook rewrote ${path} after the write. Read it again before relying on its text.`,
|
|
96
96
|
};
|
|
97
97
|
}
|
|
98
|
+
/**
|
|
99
|
+
* Says where a hunk's old lines were sought. Nothing for a search of the
|
|
100
|
+
* whole file, so the text stays the Codex text.
|
|
101
|
+
*/
|
|
102
|
+
function searchedWhere(from, context) {
|
|
103
|
+
if (context !== undefined && context !== null) {
|
|
104
|
+
return ` at line ${context}, where the @@ line matched, or from line ${context + 1} on`;
|
|
105
|
+
}
|
|
106
|
+
if (from === undefined || from <= 1)
|
|
107
|
+
return "";
|
|
108
|
+
return ` from line ${from} on, after the previous hunk`;
|
|
109
|
+
}
|
|
110
|
+
/**
|
|
111
|
+
* Says what the tool wrote after a loose match, so the model does not undo
|
|
112
|
+
* a correct change. Each sentence names only what took place for that hit.
|
|
113
|
+
*/
|
|
114
|
+
function wroteWhat(matcher, written) {
|
|
115
|
+
if (written === undefined)
|
|
116
|
+
return "";
|
|
117
|
+
const { keptLines, keptLineEnds, adaptedLines } = written;
|
|
118
|
+
const said = [];
|
|
119
|
+
if (keptLines > 0) {
|
|
120
|
+
said.push(`${lineCount(keptLines, "unchanged line")} kept the file's characters.`);
|
|
121
|
+
}
|
|
122
|
+
if (keptLineEnds > 0) {
|
|
123
|
+
const ends = keptLineEnds === 1 ? "line end" : "line ends";
|
|
124
|
+
said.push(`${lineCount(keptLineEnds, "line")} kept the file's CRLF ${ends}.`);
|
|
125
|
+
}
|
|
126
|
+
if (adaptedLines > 0) {
|
|
127
|
+
said.push(`The ${matcher} matcher changed ${lineCount(adaptedLines, "line")} to fit the file.`);
|
|
128
|
+
}
|
|
129
|
+
if (said.length === 0)
|
|
130
|
+
said.push("The new lines were written as given.");
|
|
131
|
+
return ` ${said.join(" ")}`;
|
|
132
|
+
}
|
|
133
|
+
function lineCount(count, noun) {
|
|
134
|
+
return `${count} ${noun}${count === 1 ? "" : "s"}`;
|
|
135
|
+
}
|
|
136
|
+
/** Names a span of 1-based lines: "line 4" for one line, "lines 4-6" for more. */
|
|
137
|
+
function lineSpan(lines) {
|
|
138
|
+
return lines[0] === lines[1] ? `line ${lines[0]}` : `lines ${lines[0]}-${lines[1]}`;
|
|
139
|
+
}
|
|
98
140
|
function kindLabel(kind) {
|
|
99
141
|
if (kind === "fifo")
|
|
100
142
|
return "FIFO";
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import type { ChangeFragment } from "../contract/extensions.ts";
|
|
2
2
|
import type { Matcher } from "../contract/matcher.ts";
|
|
3
3
|
import type { PatchHunk } from "../contract/patch.ts";
|
|
4
|
+
import type { FuzzyWrite } from "../contract/messages.ts";
|
|
4
5
|
import type { MatchInfo } from "../contract/result.ts";
|
|
5
6
|
import type { MutationScope } from "./scope.ts";
|
|
6
7
|
export type HunkProblem = {
|
|
@@ -11,11 +12,17 @@ export type HunkProblem = {
|
|
|
11
12
|
readonly reason: "lines-not-found";
|
|
12
13
|
readonly hunk: number;
|
|
13
14
|
readonly lines: readonly string[];
|
|
15
|
+
/** Zero-based line where the search for the old lines started. */
|
|
16
|
+
readonly from: number;
|
|
17
|
+
/** Zero-based line that the `@@` text matched, or null for a bare `@@`. */
|
|
18
|
+
readonly context: number | null;
|
|
14
19
|
};
|
|
15
20
|
export type HunksOutcome = {
|
|
16
21
|
readonly ok: true;
|
|
17
22
|
readonly text: string;
|
|
18
23
|
readonly matches: readonly MatchInfo[];
|
|
24
|
+
/** For each match, what the tool wrote compared with the hunk's lines. */
|
|
25
|
+
readonly written: readonly FuzzyWrite[];
|
|
19
26
|
readonly changed: readonly (readonly [number, number])[];
|
|
20
27
|
readonly fragments: readonly ChangeFragment[];
|
|
21
28
|
} | {
|
package/dist/core/patch-hunks.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { describeWrite, keepFileLines } from "../matchers/keep-bytes.js";
|
|
1
2
|
import { findWith } from "./match.js";
|
|
2
3
|
export function applyHunks(scope, matchers, text, hunks) {
|
|
3
4
|
const file = new LineFile(text);
|
|
@@ -5,6 +6,7 @@ export function applyHunks(scope, matchers, text, hunks) {
|
|
|
5
6
|
const found = [];
|
|
6
7
|
let cursor = 0;
|
|
7
8
|
for (const [index, hunk] of hunks.entries()) {
|
|
9
|
+
let context = null;
|
|
8
10
|
if (hunk.context !== null) {
|
|
9
11
|
const hit = file.seek(scope, matchers, [hunk.context], cursor, false);
|
|
10
12
|
if (hit === null) {
|
|
@@ -13,27 +15,33 @@ export function applyHunks(scope, matchers, text, hunks) {
|
|
|
13
15
|
problem: { reason: "context-not-found", hunk: index, context: hunk.context },
|
|
14
16
|
};
|
|
15
17
|
}
|
|
18
|
+
context = hit.line;
|
|
16
19
|
cursor = hit.line + 1;
|
|
17
20
|
}
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
let hit = old.length === 0 ? null : file.seek(scope, matchers, old, cursor, hunk.endOfFile);
|
|
21
|
-
if (hit === null && old.length > 0 && old.at(-1) === "") {
|
|
22
|
-
// A trailing empty old line is often only a blank separator.
|
|
23
|
-
body = withoutLastOldLine(body);
|
|
24
|
-
old = oldLines(body);
|
|
25
|
-
hit = old.length === 0 ? null : file.seek(scope, matchers, old, cursor, hunk.endOfFile);
|
|
26
|
-
}
|
|
27
|
-
if (old.length === 0) {
|
|
21
|
+
const after = findOld(hunk, (old) => file.seek(scope, matchers, old, cursor, hunk.endOfFile));
|
|
22
|
+
if (after.old.length === 0) {
|
|
28
23
|
const insertAt = hunk.context === null ? file.lines.length : cursor;
|
|
29
|
-
replacements.push({ start: insertAt, remove: 0, lines: body.map((line) => line.text) });
|
|
24
|
+
replacements.push({ start: insertAt, remove: 0, lines: after.body.map((line) => line.text) });
|
|
30
25
|
continue;
|
|
31
26
|
}
|
|
27
|
+
// A hunk whose @@ text is its own first old line: the model named the
|
|
28
|
+
// line it changes. Codex looks only below that line; this also tries
|
|
29
|
+
// the line itself, and takes a hit only when it starts there.
|
|
30
|
+
const anchor = context;
|
|
31
|
+
const at = after.hit !== null || anchor === null
|
|
32
|
+
? null
|
|
33
|
+
: findOld(hunk, (old) => file.seekAt(scope, matchers, old, anchor, hunk.endOfFile));
|
|
34
|
+
const { body, old, hit } = at !== null && at.hit !== null ? at : after;
|
|
32
35
|
if (hit === null) {
|
|
33
|
-
return {
|
|
36
|
+
return {
|
|
37
|
+
ok: false,
|
|
38
|
+
problem: { reason: "lines-not-found", hunk: index, lines: old, from: cursor, context },
|
|
39
|
+
};
|
|
34
40
|
}
|
|
35
|
-
|
|
36
|
-
|
|
41
|
+
const lines = newLines(body, file, hit);
|
|
42
|
+
replacements.push({ start: hit.line, remove: old.length, lines });
|
|
43
|
+
const written = describeWrite(file.lines.slice(hit.line, hit.line + old.length), body.filter((line) => line.kind !== "-").map((line) => line.text), lines);
|
|
44
|
+
found.push({ index, hit, size: old.length, written });
|
|
37
45
|
cursor = hit.line + old.length;
|
|
38
46
|
}
|
|
39
47
|
return applyReplacements(file, replacements, found);
|
|
@@ -78,7 +86,22 @@ function applyReplacements(file, replacements, found) {
|
|
|
78
86
|
newText: replacement.lines.join("\n"),
|
|
79
87
|
}));
|
|
80
88
|
const ending = file.finalNewline && result.length > 0 ? "\n" : "";
|
|
81
|
-
|
|
89
|
+
const written = found.map((entry) => entry.written);
|
|
90
|
+
return { ok: true, text: `${result.join("\n")}${ending}`, matches, written, changed, fragments };
|
|
91
|
+
}
|
|
92
|
+
/**
|
|
93
|
+
* Seeks the old lines of a hunk. When they are not found and the last old
|
|
94
|
+
* line is empty, seeks again without it: it is often only a blank separator.
|
|
95
|
+
*/
|
|
96
|
+
function findOld(hunk, seek) {
|
|
97
|
+
const old = oldLines(hunk.lines);
|
|
98
|
+
const hit = old.length === 0 ? null : seek(old);
|
|
99
|
+
if (hit !== null || old.length === 0 || old.at(-1) !== "") {
|
|
100
|
+
return { body: hunk.lines, old, hit };
|
|
101
|
+
}
|
|
102
|
+
const body = withoutLastOldLine(hunk.lines);
|
|
103
|
+
const shorter = oldLines(body);
|
|
104
|
+
return { body, old: shorter, hit: shorter.length === 0 ? null : seek(shorter) };
|
|
82
105
|
}
|
|
83
106
|
function oldLines(body) {
|
|
84
107
|
return body.filter((line) => line.kind !== "+").map((line) => line.text);
|
|
@@ -94,20 +117,47 @@ function withoutLastOldLine(body) {
|
|
|
94
117
|
copy.splice(last, 1);
|
|
95
118
|
return copy;
|
|
96
119
|
}
|
|
120
|
+
/**
|
|
121
|
+
* Context lines keep the file's bytes. In each run of `-` and `+` lines, a
|
|
122
|
+
* `-` line that comes back unchanged as a `+` line keeps them too, and each
|
|
123
|
+
* other `+` line takes the CR of the file line it replaces. A hunk whose
|
|
124
|
+
* old and new lines are the same exists only to change the characters the
|
|
125
|
+
* matcher folded, so its `+` lines are written as given, with the file's CRs.
|
|
126
|
+
*/
|
|
97
127
|
function newLines(body, file, hit) {
|
|
128
|
+
const keepUnchanged = !sameTexts(body.filter((line) => line.kind !== "+"), body.filter((line) => line.kind !== "-"));
|
|
98
129
|
const lines = [];
|
|
130
|
+
let removedFile = [];
|
|
131
|
+
let removed = [];
|
|
132
|
+
let added = [];
|
|
133
|
+
const flush = () => {
|
|
134
|
+
lines.push(...keepFileLines(removedFile, removed, added, keepUnchanged));
|
|
135
|
+
removedFile = [];
|
|
136
|
+
removed = [];
|
|
137
|
+
added = [];
|
|
138
|
+
};
|
|
99
139
|
let offset = 0;
|
|
100
140
|
for (const line of body) {
|
|
101
141
|
if (line.kind === "+") {
|
|
102
|
-
|
|
142
|
+
added.push(line.text);
|
|
103
143
|
continue;
|
|
104
144
|
}
|
|
105
|
-
|
|
106
|
-
lines.push(file.lines[hit.line + offset]);
|
|
145
|
+
const own = file.lines[hit.line + offset];
|
|
107
146
|
offset += 1;
|
|
147
|
+
if (line.kind === "-") {
|
|
148
|
+
removedFile.push(own);
|
|
149
|
+
removed.push(line.text);
|
|
150
|
+
continue;
|
|
151
|
+
}
|
|
152
|
+
flush();
|
|
153
|
+
lines.push(own);
|
|
108
154
|
}
|
|
155
|
+
flush();
|
|
109
156
|
return lines;
|
|
110
157
|
}
|
|
158
|
+
function sameTexts(old, next) {
|
|
159
|
+
return old.length === next.length && old.every((line, at) => line.text === next[at]?.text);
|
|
160
|
+
}
|
|
111
161
|
class LineFile {
|
|
112
162
|
lines;
|
|
113
163
|
finalNewline;
|
|
@@ -156,6 +206,26 @@ class LineFile {
|
|
|
156
206
|
}
|
|
157
207
|
return null;
|
|
158
208
|
}
|
|
209
|
+
/** Like seek(), but takes a hit only when it starts at `line`. */
|
|
210
|
+
seekAt(scope, matchers, wanted, line, endOfFile) {
|
|
211
|
+
const last = this.lines.length - wanted.length;
|
|
212
|
+
if (line > last || (endOfFile && line !== last))
|
|
213
|
+
return null;
|
|
214
|
+
const needle = wanted.map((text) => `${text}\n`).join("");
|
|
215
|
+
for (const matcher of matchers) {
|
|
216
|
+
scope.checkAbort();
|
|
217
|
+
const [range] = findWith(scope, matcher, this.haystack, needle, {
|
|
218
|
+
mode: "lines",
|
|
219
|
+
from: this.lineStartOffsets[line],
|
|
220
|
+
maxMatches: 1,
|
|
221
|
+
});
|
|
222
|
+
if (range === undefined || this.lineAt(range.start) !== line)
|
|
223
|
+
continue;
|
|
224
|
+
if (this.coversWholeLines(range, line, wanted.length))
|
|
225
|
+
return { line, matcher };
|
|
226
|
+
}
|
|
227
|
+
return null;
|
|
228
|
+
}
|
|
159
229
|
coversWholeLines(range, line, count) {
|
|
160
230
|
if (range.refused !== undefined)
|
|
161
231
|
return false;
|
package/dist/core/plan-edit.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { exactMatcher } from "../matchers/exact.js";
|
|
2
|
+
import { describeWrite } from "../matchers/keep-bytes.js";
|
|
2
3
|
import { closestRegion, isAlreadyApplied, trailingNewline } from "./hints.js";
|
|
3
4
|
import { LineIndex } from "./line-index.js";
|
|
4
5
|
import { REPLACE_ALL_CAP, adaptFor, escapeDrift, findWith, runChain, tooWide } from "./match.js";
|
|
@@ -82,9 +83,11 @@ export function planEdit(scope, input, target, loaded, pre) {
|
|
|
82
83
|
replaced: byPair.get(pair.index) ?? [],
|
|
83
84
|
};
|
|
84
85
|
});
|
|
85
|
-
for (const match of matches) {
|
|
86
|
+
for (const [at, match] of matches.entries()) {
|
|
86
87
|
if (!match.fuzzy)
|
|
87
88
|
continue;
|
|
89
|
+
const pair = found[at];
|
|
90
|
+
const first = pair.hits[0];
|
|
88
91
|
scope.notes.push({
|
|
89
92
|
code: "fuzzy-match",
|
|
90
93
|
severity: "info",
|
|
@@ -93,6 +96,7 @@ export function planEdit(scope, input, target, loaded, pre) {
|
|
|
93
96
|
index: match.index,
|
|
94
97
|
matcher: match.matcher,
|
|
95
98
|
lines: match.lines,
|
|
99
|
+
written: describeWrite(text.slice(first.start, first.end).split("\n"), pair.newText.split("\n"), first.text.split("\n")),
|
|
96
100
|
}),
|
|
97
101
|
data: { index: match.index, matcher: match.matcher, lines: [...match.lines] },
|
|
98
102
|
});
|
|
@@ -174,7 +178,7 @@ function matchPair(scope, input, target, text, pair, index) {
|
|
|
174
178
|
}
|
|
175
179
|
return { start: range.start, end: range.end, text: replacement };
|
|
176
180
|
});
|
|
177
|
-
return { index, matcher, hits };
|
|
181
|
+
return { index, matcher, hits, newText: pair.newText };
|
|
178
182
|
}
|
|
179
183
|
function rematchAfterStale(scope, text, pair, index, path) {
|
|
180
184
|
const ranges = findWith(scope, STALE_REMATCH_MATCHER, text, pair.oldText, {
|
|
@@ -191,6 +195,7 @@ function rematchAfterStale(scope, text, pair, index, path) {
|
|
|
191
195
|
index,
|
|
192
196
|
matcher: STALE_REMATCH_MATCHER,
|
|
193
197
|
hits: ranges.map((range) => ({ start: range.start, end: range.end, text: pair.newText })),
|
|
198
|
+
newText: pair.newText,
|
|
194
199
|
};
|
|
195
200
|
}
|
|
196
201
|
function noMatchFailure(scope, input, target, text, pair, index) {
|
package/dist/core/plan-patch.js
CHANGED
|
@@ -66,7 +66,7 @@ export function planPatch(scope, matchers, targets, problems) {
|
|
|
66
66
|
message: messages.staleRematched({ path: main.displayPath }),
|
|
67
67
|
});
|
|
68
68
|
}
|
|
69
|
-
for (const match of outcome.matches) {
|
|
69
|
+
for (const [at, match] of outcome.matches.entries()) {
|
|
70
70
|
if (!match.fuzzy)
|
|
71
71
|
continue;
|
|
72
72
|
scope.notes.push({
|
|
@@ -77,6 +77,7 @@ export function planPatch(scope, matchers, targets, problems) {
|
|
|
77
77
|
hunk: match.index + 1,
|
|
78
78
|
matcher: match.matcher,
|
|
79
79
|
lines: match.lines,
|
|
80
|
+
written: outcome.written[at],
|
|
80
81
|
}),
|
|
81
82
|
data: { path: main.displayPath, hunk: match.index, matcher: match.matcher },
|
|
82
83
|
});
|
|
@@ -107,7 +108,13 @@ function hunkProblem(scope, path, line, problem) {
|
|
|
107
108
|
const hunk = problem.hunk + 1;
|
|
108
109
|
const message = problem.reason === "context-not-found"
|
|
109
110
|
? messages.patchContextNotFound({ path, hunk, context: problem.context })
|
|
110
|
-
: messages.patchLinesNotFound({
|
|
111
|
+
: messages.patchLinesNotFound({
|
|
112
|
+
path,
|
|
113
|
+
hunk,
|
|
114
|
+
lines: problem.lines,
|
|
115
|
+
from: problem.from + 1,
|
|
116
|
+
context: problem.context === null ? null : problem.context + 1,
|
|
117
|
+
});
|
|
111
118
|
return { path, line, reason: problem.reason, message, hunk: problem.hunk };
|
|
112
119
|
}
|
|
113
120
|
function planAdd(scope, target, content) {
|
package/dist/core/record.js
CHANGED
package/dist/index.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
export type { ApplyPatchInput, ApplyPatchRequest, EditInput, EditPair, EditRequest, MutationRequest, WriteInput, WriteRequest, } from "./contract/input.ts";
|
|
2
2
|
export type { ApplyPatchTool, EditTool, MutationTool, WriteTool, WriteToolName, } from "./contract/context.ts";
|
|
3
3
|
export type { CommitFileState, CommitReport, FileChange, FileVersion, MatchInfo, MutationFailure, MutationNoChange, MutationOk, MutationReport, MutationResult, Snippet, WriteError, WriteErrorCode, WritePhase, } from "./contract/result.ts";
|
|
4
|
-
export type {
|
|
4
|
+
export type { ApplyPatchToolOptions, EditToolOptions, WriteToolOptions } from "./contract/deps.ts";
|
|
5
5
|
export type { AfterWriteContext, ChangeFragment, Guard, GuardContext, GuardDecision, PlannedChange, PlannedText, WriteAuthorizeDecision, WriteAuthorizer, WriteAuthorizeTarget, WriteHook, WriteHookContext, WriteHookResult, } from "./contract/extensions.ts";
|
|
6
6
|
export type { Codec, DecodeOutcome, TextStyle } from "./contract/codec.ts";
|
|
7
7
|
export type { Matcher, MatchContext, MatchRange } from "./contract/matcher.ts";
|
|
@@ -9,7 +9,7 @@ export type { LockManager, LockOutcome } from "./contract/locks.ts";
|
|
|
9
9
|
export type { PreconditionPolicy } from "./contract/preconditions.ts";
|
|
10
10
|
export type { WriteFormatContext, WriteFormatter } from "./contract/format.ts";
|
|
11
11
|
export type { WriteLimits } from "./contract/limits.ts";
|
|
12
|
-
export type { WriteCanonicalParam, WriteMessageCatalog } from "./contract/messages.ts";
|
|
12
|
+
export type { FuzzyWrite, WriteCanonicalParam, WriteMessageCatalog } from "./contract/messages.ts";
|
|
13
13
|
export { createApplyPatchTool, createEditTool, createWriteTool } from "./core/create-tools.ts";
|
|
14
14
|
export { parseApplyPatchInput, parseEditInput, parseWriteInput } from "./core/input.ts";
|
|
15
15
|
export { defaultWriteLimits, resolveWriteLimits } from "./core/limits.ts";
|
|
@@ -24,7 +24,7 @@ export { executableShebang, verifyWrite } from "./hooks/index.ts";
|
|
|
24
24
|
export { defaultWriteFormatter } from "./formatters/index.ts";
|
|
25
25
|
export type { WriteFormatterOptions } from "./formatters/index.ts";
|
|
26
26
|
export { createFsTools } from "./bundle/create-fs-tools.ts";
|
|
27
|
-
export type {
|
|
27
|
+
export type { FsToolsOptions, FsTools, FsToolsApplyPatchOptions, FsToolsBashOptions, FsToolsEditOptions, FsToolsReadOptions, FsToolsSharedKey, FsToolsState, FsToolsWithApplyPatch, FsToolsWithBash, FsToolsWriteOptions, } from "./bundle/create-fs-tools.ts";
|
|
28
28
|
export { createInvalidator } from "./state/index.ts";
|
|
29
29
|
export type { Invalidate, InvalidateOutcome } from "./state/index.ts";
|
|
30
30
|
export { textOf } from "@better-fs-tools/read";
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import type { FuzzyWrite } from "../contract/messages.ts";
|
|
2
|
+
/**
|
|
3
|
+
* Builds the new lines for one loose hit so that text the model did not
|
|
4
|
+
* change keeps the file's bytes.
|
|
5
|
+
*
|
|
6
|
+
* - `file` holds the file's own text of the matched lines, `old` the model's
|
|
7
|
+
* text of the same lines, and `next` the model's new lines.
|
|
8
|
+
* - With `keepUnchanged`, the leading and trailing lines where `old` and
|
|
9
|
+
* `next` agree are written from `file`.
|
|
10
|
+
* - Each other new line takes the CR of the file line it replaces, so a
|
|
11
|
+
* mixed-EOL file keeps its CRLF lines. The last new line pairs with the
|
|
12
|
+
* last replaced line when no kept line follows it.
|
|
13
|
+
*/
|
|
14
|
+
export declare function keepFileLines(file: readonly string[], old: readonly string[], next: readonly string[], keepUnchanged: boolean): string[];
|
|
15
|
+
/**
|
|
16
|
+
* The `Matcher.adapt` rule for a loose hit in text mode. When the old text and
|
|
17
|
+
* the new text are the same, the edit exists only to change the characters the
|
|
18
|
+
* matcher folded, so the new text is written as given, with the file's CRs.
|
|
19
|
+
* Otherwise the unchanged leading and trailing lines keep the file's bytes.
|
|
20
|
+
* `lined` says whether line N of the region matched line N of the old text;
|
|
21
|
+
* when it did not, the new text is written as given.
|
|
22
|
+
*/
|
|
23
|
+
export declare function adaptKeepingBytes(newText: string, region: string, needle: string, lined: (file: readonly string[], old: readonly string[]) => boolean): string;
|
|
24
|
+
/**
|
|
25
|
+
* Compares what the tool wrote for one loose hit with the model's new lines,
|
|
26
|
+
* position by position. `file` holds the file's own lines of the hit. A
|
|
27
|
+
* written line that differs from the model's line only by a final CR kept the
|
|
28
|
+
* file's line end. One that is a line of `file` kept the file's characters.
|
|
29
|
+
* Any other difference came from the matcher.
|
|
30
|
+
*/
|
|
31
|
+
export declare function describeWrite(file: readonly string[], given: readonly string[], written: readonly string[]): FuzzyWrite;
|