@better-fs-tools/write 0.2.0 → 0.3.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.
@@ -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 { ApplyPatchToolDeps, EditToolDeps, WriteToolDeps } from "../contract/deps.ts";
3
+ import type { ApplyPatchToolOptions, EditToolOptions, WriteToolOptions } from "../contract/deps.ts";
4
4
  /**
5
- * Creates the edit tool. Takes the same dependencies as createWriteTool, plus
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 dependencies.
7
+ * TypeError on invalid options.
8
8
  */
9
- export declare function createEditTool<THost = undefined>(deps: EditToolDeps<THost> & StateNeedsDigest): EditTool<THost>;
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 dependency replaces its default.
14
+ * the defaults key by key. Every other option replaces its default.
15
15
  */
16
- export declare function createWriteTool<THost = undefined>(deps: WriteToolDeps<THost> & StateNeedsDigest): WriteTool<THost>;
16
+ export declare function createWriteTool<THost = undefined>(options: WriteToolOptions<THost> & StateNeedsDigest): WriteTool<THost>;
17
17
  /**
18
- * Creates the apply_patch tool. Takes the same dependencies as
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 dependencies.
21
+ * Throws TypeError on invalid options.
22
22
  */
23
- export declare function createApplyPatchTool<THost = undefined>(deps: ApplyPatchToolDeps<THost> & StateNeedsDigest): ApplyPatchTool<THost>;
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 dependencies as createWriteTool, plus
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 dependencies.
9
+ * TypeError on invalid options.
10
10
  */
11
- export function createEditTool(deps) {
12
- const resolved = resolveEditDependencies(deps);
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 dependency replaces its default.
26
+ * the defaults key by key. Every other option replaces its default.
27
27
  */
28
- export function createWriteTool(deps) {
29
- const resolved = resolveWriteDependencies(deps, "write");
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 dependencies as
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 dependencies.
42
+ * Throws TypeError on invalid options.
43
43
  */
44
- export function createApplyPatchTool(deps) {
45
- const resolved = resolveApplyPatchDependencies(deps);
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");
@@ -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, ApplyPatchToolDeps, EditDependencies, EditToolDeps, WriteDependencies, WriteToolDeps } from "../contract/deps.ts";
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: WriteToolDeps<THost>, tool: string): WriteDependencies<THost>;
6
- export declare function resolveEditDependencies<THost>(deps: EditToolDeps<THost>): EditDependencies<THost>;
7
- export declare function resolveApplyPatchDependencies<THost>(deps: ApplyPatchToolDeps<THost>): ApplyPatchDependencies<THost>;
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 dependencies must be an object`);
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 dependency: ${key}`);
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 ?? null;
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 dependencies must be an object");
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 dependencies must be an object");
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");
@@ -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. A partial read is not enough for write.`
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 lines ${lines[0]}-${lines[1]} only with the ${matcher} matcher, not exactly. Check the result.`,
73
+ fuzzyMatch: ({ path, index, matcher, lines }) => `Edit ${index + 1} matched ${path} at ${lineSpan(lines)} only with the ${matcher} matcher, not exactly. Check the result.`,
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):",
@@ -84,7 +84,7 @@ function catalogUsingParam(param) {
84
84
  `${path}: hunk ${hunk}: failed to find the expected lines:`,
85
85
  ...lines.map((line) => ` ${line}`),
86
86
  ].join("\n"),
87
- patchFuzzyMatch: ({ path, hunk, matcher, lines }) => `Hunk ${hunk} matched ${path} at lines ${lines[0]}-${lines[1]} only with the ${matcher} matcher, not exactly. Check the result.`,
87
+ patchFuzzyMatch: ({ path, hunk, matcher, lines }) => `Hunk ${hunk} matched ${path} at ${lineSpan(lines)} only with the ${matcher} matcher, not exactly. Check the result.`,
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,10 @@ 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
+ /** Names a span of 1-based lines: "line 4" for one line, "lines 4-6" for more. */
99
+ function lineSpan(lines) {
100
+ return lines[0] === lines[1] ? `line ${lines[0]}` : `lines ${lines[0]}-${lines[1]}`;
101
+ }
98
102
  function kindLabel(kind) {
99
103
  if (kind === "fifo")
100
104
  return "FIFO";
@@ -1,3 +1,4 @@
1
+ import { 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);
@@ -94,20 +95,47 @@ function withoutLastOldLine(body) {
94
95
  copy.splice(last, 1);
95
96
  return copy;
96
97
  }
98
+ /**
99
+ * Context lines keep the file's bytes. In each run of `-` and `+` lines, a
100
+ * `-` line that comes back unchanged as a `+` line keeps them too, and each
101
+ * other `+` line takes the CR of the file line it replaces. A hunk whose
102
+ * old and new lines are the same exists only to change the characters the
103
+ * matcher folded, so its `+` lines are written as given, with the file's CRs.
104
+ */
97
105
  function newLines(body, file, hit) {
106
+ const keepUnchanged = !sameTexts(body.filter((line) => line.kind !== "+"), body.filter((line) => line.kind !== "-"));
98
107
  const lines = [];
108
+ let removedFile = [];
109
+ let removed = [];
110
+ let added = [];
111
+ const flush = () => {
112
+ lines.push(...keepFileLines(removedFile, removed, added, keepUnchanged));
113
+ removedFile = [];
114
+ removed = [];
115
+ added = [];
116
+ };
99
117
  let offset = 0;
100
118
  for (const line of body) {
101
119
  if (line.kind === "+") {
102
- lines.push(line.text);
120
+ added.push(line.text);
103
121
  continue;
104
122
  }
105
- if (line.kind === " ")
106
- lines.push(file.lines[hit.line + offset]);
123
+ const own = file.lines[hit.line + offset];
107
124
  offset += 1;
125
+ if (line.kind === "-") {
126
+ removedFile.push(own);
127
+ removed.push(line.text);
128
+ continue;
129
+ }
130
+ flush();
131
+ lines.push(own);
108
132
  }
133
+ flush();
109
134
  return lines;
110
135
  }
136
+ function sameTexts(old, next) {
137
+ return old.length === next.length && old.every((line, at) => line.text === next[at]?.text);
138
+ }
111
139
  class LineFile {
112
140
  lines;
113
141
  finalNewline;
@@ -38,6 +38,7 @@ export async function recordCommitted(scope, committed) {
38
38
  viewId: contentId ?? "",
39
39
  observedAt: clock().toISOString(),
40
40
  wholeFileVisible: wholeFileVisible(file),
41
+ seenLines: [],
41
42
  totalsExact: true,
42
43
  request: null,
43
44
  };
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 { ApplyPatchDependencies, ApplyPatchToolDeps, EditDependencies, EditToolDeps, WriteDependencies, WriteToolDeps, } from "./contract/deps.ts";
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";
@@ -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 { CreateFsToolsOptions, FsTools, FsToolsApplyPatchOptions, FsToolsBashOptions, FsToolsSharedKey, FsToolsWithApplyPatch, FsToolsWithBash, } from "./bundle/create-fs-tools.ts";
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,22 @@
1
+ /**
2
+ * Builds the new lines for one loose hit so that text the model did not
3
+ * change keeps the file's bytes.
4
+ *
5
+ * - `file` holds the file's own text of the matched lines, `old` the model's
6
+ * text of the same lines, and `next` the model's new lines.
7
+ * - With `keepUnchanged`, the leading and trailing lines where `old` and
8
+ * `next` agree are written from `file`.
9
+ * - Each other new line takes the CR of the file line it replaces, so a
10
+ * mixed-EOL file keeps its CRLF lines. The last new line pairs with the
11
+ * last replaced line when no kept line follows it.
12
+ */
13
+ export declare function keepFileLines(file: readonly string[], old: readonly string[], next: readonly string[], keepUnchanged: boolean): string[];
14
+ /**
15
+ * The `Matcher.adapt` rule for a loose hit in text mode. When the old text and
16
+ * the new text are the same, the edit exists only to change the characters the
17
+ * matcher folded, so the new text is written as given, with the file's CRs.
18
+ * Otherwise the unchanged leading and trailing lines keep the file's bytes.
19
+ * `lined` says whether line N of the region matched line N of the old text;
20
+ * when it did not, the new text is written as given.
21
+ */
22
+ export declare function adaptKeepingBytes(newText: string, region: string, needle: string, lined: (file: readonly string[], old: readonly string[]) => boolean): string;
@@ -0,0 +1,51 @@
1
+ const CR = "\r";
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 function keepFileLines(file, old, next, keepUnchanged) {
15
+ const room = Math.min(old.length, next.length);
16
+ let head = 0;
17
+ if (keepUnchanged) {
18
+ while (head < room && old[head] === next[head])
19
+ head += 1;
20
+ }
21
+ let tail = 0;
22
+ if (keepUnchanged) {
23
+ while (head + tail < room && old.at(-1 - tail) === next.at(-1 - tail))
24
+ tail += 1;
25
+ }
26
+ const replaced = file.slice(head, file.length - tail);
27
+ const written = next.slice(head, next.length - tail);
28
+ const middle = written.map((line, at) => {
29
+ if (replaced.length === 0 || line.endsWith(CR))
30
+ return line;
31
+ const lastWithoutKept = tail === 0 && at === written.length - 1;
32
+ const pair = lastWithoutKept ? replaced.length - 1 : Math.min(at, replaced.length - 1);
33
+ return replaced[pair].endsWith(CR) ? `${line}${CR}` : line;
34
+ });
35
+ return [...file.slice(0, head), ...middle, ...file.slice(file.length - tail)];
36
+ }
37
+ /**
38
+ * The `Matcher.adapt` rule for a loose hit in text mode. When the old text and
39
+ * the new text are the same, the edit exists only to change the characters the
40
+ * matcher folded, so the new text is written as given, with the file's CRs.
41
+ * Otherwise the unchanged leading and trailing lines keep the file's bytes.
42
+ * `lined` says whether line N of the region matched line N of the old text;
43
+ * when it did not, the new text is written as given.
44
+ */
45
+ export function adaptKeepingBytes(newText, region, needle, lined) {
46
+ const file = region.split("\n");
47
+ const old = needle.split("\n");
48
+ if (file.length !== old.length || !lined(file, old))
49
+ return newText;
50
+ return keepFileLines(file, old, newText.split("\n"), newText !== needle).join("\n");
51
+ }
@@ -1,3 +1,6 @@
1
1
  import type { Matcher } from "../contract/matcher.ts";
2
- /** Matches whole lines, ignoring leading and trailing whitespace on each line. */
2
+ /**
3
+ * Matches whole lines, ignoring leading and trailing whitespace on each line.
4
+ * Lines that the new text leaves as they were keep the file's bytes.
5
+ */
3
6
  export declare function lineTrimmedMatcher(): Matcher;
@@ -1,5 +1,9 @@
1
+ import { adaptKeepingBytes } from "./keep-bytes.js";
1
2
  import { LineTable, memoizeLast, needleLines } from "./lines.js";
2
- /** Matches whole lines, ignoring leading and trailing whitespace on each line. */
3
+ /**
4
+ * Matches whole lines, ignoring leading and trailing whitespace on each line.
5
+ * Lines that the new text leaves as they were keep the file's bytes.
6
+ */
3
7
  export function lineTrimmedMatcher() {
4
8
  const table = memoizeLast((text) => new LineTable(text));
5
9
  return Object.freeze({
@@ -28,5 +32,9 @@ export function lineTrimmedMatcher() {
28
32
  }
29
33
  return ranges;
30
34
  },
35
+ adapt: (newText, { haystack, needle, range }) => adaptKeepingBytes(newText, haystack.slice(range.start, range.end), needle, sameTrimmed),
31
36
  });
32
37
  }
38
+ function sameTrimmed(file, old) {
39
+ return file.every((line, at) => line.trim() === (old[at] ?? "").trim());
40
+ }
@@ -2,6 +2,7 @@ import type { Matcher } from "../contract/matcher.ts";
2
2
  /**
3
3
  * Matches while ignoring trailing whitespace, Unicode normalization, curly
4
4
  * quotes, dashes, and special spaces. A match that starts or ends inside one
5
- * folded character is refused.
5
+ * folded character is refused. Lines of the hit that the new text leaves as
6
+ * they were keep the file's bytes, and replaced lines keep the file's CRs.
6
7
  */
7
8
  export declare function normalizedMatcher(): Matcher;
@@ -1,10 +1,12 @@
1
1
  import { FIRST, LAST, fold } from "./fold.js";
2
+ import { adaptKeepingBytes } from "./keep-bytes.js";
2
3
  import { memoizeLast } from "./lines.js";
3
4
  const LF = 10;
4
5
  /**
5
6
  * Matches while ignoring trailing whitespace, Unicode normalization, curly
6
7
  * quotes, dashes, and special spaces. A match that starts or ends inside one
7
- * folded character is refused.
8
+ * folded character is refused. Lines of the hit that the new text leaves as
9
+ * they were keep the file's bytes, and replaced lines keep the file's CRs.
8
10
  */
9
11
  export function normalizedMatcher() {
10
12
  const folded = memoizeLast(fold);
@@ -13,8 +15,12 @@ export function normalizedMatcher() {
13
15
  fuzzy: true,
14
16
  describe: "trailing whitespace, Unicode normalization, curly quotes, dashes, and special spaces",
15
17
  find: (haystack, needle, ctx) => findFolded(haystack, folded(haystack), fold(needle), ctx),
18
+ adapt: (newText, { haystack, needle, range }) => adaptKeepingBytes(newText, haystack.slice(range.start, range.end), needle, sameFolded),
16
19
  });
17
20
  }
21
+ function sameFolded(file, old) {
22
+ return file.every((line, at) => fold(line).text === fold(old[at] ?? "").text);
23
+ }
18
24
  function findFolded(haystack, hay, needle, ctx) {
19
25
  const ranges = [];
20
26
  const text = hay.text;
@@ -0,0 +1,41 @@
1
+ import type { StateNeedsDigest, ToolDefinition } from "@better-fs-tools/read";
2
+ import type { ApplyPatchToolOptions, EditToolOptions, WriteToolOptions } from "../contract/deps.ts";
3
+ import type { ApplyPatchInput, EditInput, WriteInput } from "../contract/input.ts";
4
+ import type { WriteCanonicalParam } from "../contract/messages.ts";
5
+ import type { MutationResult } from "../contract/result.ts";
6
+ import type { EditSignature, MutationSignature, PatchSignature, WriteSignature } from "./contract.ts";
7
+ /** An edit, write, or apply_patch tool bound to its signature. */
8
+ export interface MutationToolDefinition<TInput, THost = undefined> extends ToolDefinition<TInput, MutationResult, THost, WriteCanonicalParam> {
9
+ readonly signature: MutationSignature<TInput>;
10
+ }
11
+ export type EditToolDefinition<THost = undefined> = MutationToolDefinition<EditInput, THost>;
12
+ export type WriteToolDefinition<THost = undefined> = MutationToolDefinition<WriteInput, THost>;
13
+ export type ApplyPatchToolDefinition<THost = undefined> = MutationToolDefinition<ApplyPatchInput, THost>;
14
+ /** The edit tool's options, plus the signature the model sees. */
15
+ export type EditToolDefinitionOptions<THost = undefined> = EditToolOptions<THost> & StateNeedsDigest & {
16
+ /** Default defaultEditSignature({ matchers }), so the description names the matchers. */
17
+ readonly signature?: EditSignature;
18
+ };
19
+ /** The write tool's options, plus the signature the model sees. */
20
+ export type WriteToolDefinitionOptions<THost = undefined> = WriteToolOptions<THost> & StateNeedsDigest & {
21
+ /** Default defaultWriteSignature(). */
22
+ readonly signature?: WriteSignature;
23
+ };
24
+ /** The apply_patch tool's options, plus the signature the model sees. */
25
+ export type ApplyPatchToolDefinitionOptions<THost = undefined> = ApplyPatchToolOptions<THost> & StateNeedsDigest & {
26
+ /** Default defaultPatchSignature(). */
27
+ readonly signature?: PatchSignature;
28
+ };
29
+ /**
30
+ * Creates the edit tool and binds it to a signature. The signature's `param`
31
+ * message goes under `options.messages`, so a host message still wins. Throws
32
+ * TypeError where createEditTool() does.
33
+ */
34
+ export declare function editToolDefinition<THost = undefined>(options: EditToolDefinitionOptions<THost>): EditToolDefinition<THost>;
35
+ /** Creates the write tool and binds it to a signature, as editToolDefinition(). */
36
+ export declare function writeToolDefinition<THost = undefined>(options: WriteToolDefinitionOptions<THost>): WriteToolDefinition<THost>;
37
+ /**
38
+ * Creates the apply_patch tool and binds it to a signature, as
39
+ * editToolDefinition(). A grammar on the signature is copied to the definition.
40
+ */
41
+ export declare function applyPatchToolDefinition<THost = undefined>(options: ApplyPatchToolDefinitionOptions<THost>): ApplyPatchToolDefinition<THost>;
@@ -0,0 +1,66 @@
1
+ import { createApplyPatchTool, createEditTool, createWriteTool } from "../core/create-tools.js";
2
+ import { parseApplyPatchInput, parseEditInput, parseWriteInput } from "../core/input.js";
3
+ import { resolveWriteLimits } from "../core/limits.js";
4
+ import { defaultEditSignature } from "./edit.js";
5
+ import { writeSignatureMessages } from "./messages.js";
6
+ import { defaultPatchSignature } from "./patch.js";
7
+ import { defaultWriteSignature } from "./write.js";
8
+ /**
9
+ * Creates the edit tool and binds it to a signature. The signature's `param`
10
+ * message goes under `options.messages`, so a host message still wins. Throws
11
+ * TypeError where createEditTool() does.
12
+ */
13
+ export function editToolDefinition(options) {
14
+ checkOptions(options, "editToolDefinition");
15
+ const { signature: given, ...rest } = options;
16
+ const signature = given ?? defaultEditSignature(rest.matchers === undefined ? {} : { matchers: rest.matchers });
17
+ const edit = createEditTool({
18
+ ...rest,
19
+ messages: { ...writeSignatureMessages(signature), ...rest.messages },
20
+ });
21
+ return bindMutationTool(signature, edit, parseEditInput, rest.limits);
22
+ }
23
+ /** Creates the write tool and binds it to a signature, as editToolDefinition(). */
24
+ export function writeToolDefinition(options) {
25
+ checkOptions(options, "writeToolDefinition");
26
+ const { signature = defaultWriteSignature(), ...rest } = options;
27
+ const write = createWriteTool({
28
+ ...rest,
29
+ messages: { ...writeSignatureMessages(signature), ...rest.messages },
30
+ });
31
+ return bindMutationTool(signature, write, parseWriteInput, rest.limits);
32
+ }
33
+ /**
34
+ * Creates the apply_patch tool and binds it to a signature, as
35
+ * editToolDefinition(). A grammar on the signature is copied to the definition.
36
+ */
37
+ export function applyPatchToolDefinition(options) {
38
+ checkOptions(options, "applyPatchToolDefinition");
39
+ const { signature = defaultPatchSignature(), ...rest } = options;
40
+ const applyPatch = createApplyPatchTool({
41
+ ...rest,
42
+ messages: { ...writeSignatureMessages(signature), ...rest.messages },
43
+ });
44
+ return bindMutationTool(signature, applyPatch, parseApplyPatchInput, rest.limits);
45
+ }
46
+ function bindMutationTool(signature, tool, parse, limitOverrides) {
47
+ const limits = resolveWriteLimits(limitOverrides);
48
+ return Object.freeze({
49
+ name: signature.name,
50
+ description: signature.description,
51
+ inputSchema: signature.schema,
52
+ ...(signature.grammar === undefined ? {} : { grammar: signature.grammar }),
53
+ signature,
54
+ validate(modelInput) {
55
+ const input = signature.toInput(modelInput);
56
+ parse(input, limits);
57
+ return input;
58
+ },
59
+ execute: async (modelInput, ctx) => tool(signature.toInput(modelInput), ctx),
60
+ });
61
+ }
62
+ function checkOptions(options, label) {
63
+ if (options === null || typeof options !== "object" || Array.isArray(options)) {
64
+ throw new TypeError(`${label} options must be an object`);
65
+ }
66
+ }
@@ -4,13 +4,12 @@ import type { EditSignature } from "./contract.ts";
4
4
  type MatcherOption = {
5
5
  readonly matchers?: readonly Matcher[];
6
6
  };
7
- /** edit({ path, old_string, new_string, replace_all? }). Name "edit". */
8
- export declare function defaultEditSignature(options?: SignatureDocs<"path" | "old_string" | "new_string" | "replace_all"> & MatcherOption): EditSignature;
9
7
  /**
10
- * edit({ filePath, oldString, newString, replaceAll? }). OpenCode and Kilo Code.
11
- * The same as defaultEditSignature with camel-case names.
8
+ * edit({ path, old_string, new_string, replace_all? }). Name "edit". `names`
9
+ * renames any parameter. The description names the fuzzy matchers in
10
+ * `matchers`, which defaults to defaultEditMatchers().
12
11
  */
13
- export declare function camelCaseEditSignature(options?: SignatureDocs<"filePath" | "oldString" | "newString" | "replaceAll"> & MatcherOption): EditSignature;
12
+ export declare function defaultEditSignature(options?: SignatureDocs<"path" | "old_string" | "new_string" | "replace_all"> & MatcherOption): EditSignature;
14
13
  /**
15
14
  * edit({ path, edits: [{ oldText, newText }] }). Pi and Cloudflare Computer.
16
15
  * Has no replaceAll parameter, so no message suggests one.
@@ -5,7 +5,11 @@ const PATH_TEXT = "Path of the file to edit, relative to the working directory o
5
5
  const READ_FIRST = "Read the file with the read tool before you edit it.";
6
6
  const NO_PREFIX = "Copy old text from the file without the line-number prefix the read tool adds.";
7
7
  const USE_WRITE = "To create a file or replace all of its content, use the write tool.";
8
- /** edit({ path, old_string, new_string, replace_all? }). Name "edit". */
8
+ /**
9
+ * edit({ path, old_string, new_string, replace_all? }). Name "edit". `names`
10
+ * renames any parameter. The description names the fuzzy matchers in
11
+ * `matchers`, which defaults to defaultEditMatchers().
12
+ */
9
13
  export function defaultEditSignature(options = {}) {
10
14
  return singleEditSignature(options, "defaultEditSignature", {
11
15
  path: "path",
@@ -14,18 +18,6 @@ export function defaultEditSignature(options = {}) {
14
18
  all: "replace_all",
15
19
  });
16
20
  }
17
- /**
18
- * edit({ filePath, oldString, newString, replaceAll? }). OpenCode and Kilo Code.
19
- * The same as defaultEditSignature with camel-case names.
20
- */
21
- export function camelCaseEditSignature(options = {}) {
22
- return singleEditSignature(options, "camelCaseEditSignature", {
23
- path: "filePath",
24
- old: "oldString",
25
- new: "newString",
26
- all: "replaceAll",
27
- });
28
- }
29
21
  function singleEditSignature(options, label, presetNames) {
30
22
  const checked = checkDocs(options, label, [
31
23
  presetNames.path,
@@ -1,6 +1,10 @@
1
1
  /** The `./signature` subpath: model-facing names, schemas, and descriptions for the three tools. */
2
2
  export type { EditSignature, MutationSignature, PatchSignature, WriteSignature, } from "./contract.ts";
3
- export { camelCaseEditSignature, defaultEditSignature, multiEditSignature } from "./edit.ts";
3
+ export { fsToolDefinitions } from "../bundle/definitions.ts";
4
+ export type { FsToolDefinitions, FsToolDefinitionsOptions } from "../bundle/definitions.ts";
5
+ export { applyPatchToolDefinition, editToolDefinition, writeToolDefinition } from "./definition.ts";
6
+ export type { ApplyPatchToolDefinition, ApplyPatchToolDefinitionOptions, EditToolDefinition, EditToolDefinitionOptions, MutationToolDefinition, WriteToolDefinition, WriteToolDefinitionOptions, } from "./definition.ts";
7
+ export { defaultEditSignature, multiEditSignature } from "./edit.ts";
4
8
  export { writeSignatureMessages } from "./messages.ts";
5
9
  export { defaultPatchSignature, freeformPatchSignature } from "./patch.ts";
6
- export { defaultWriteSignature, snakeCaseWriteSignature } from "./write.ts";
10
+ export { defaultWriteSignature } from "./write.ts";
@@ -1,4 +1,6 @@
1
- export { camelCaseEditSignature, defaultEditSignature, multiEditSignature } from "./edit.js";
1
+ export { fsToolDefinitions } from "../bundle/definitions.js";
2
+ export { applyPatchToolDefinition, editToolDefinition, writeToolDefinition } from "./definition.js";
3
+ export { defaultEditSignature, multiEditSignature } from "./edit.js";
2
4
  export { writeSignatureMessages } from "./messages.js";
3
5
  export { defaultPatchSignature, freeformPatchSignature } from "./patch.js";
4
- export { defaultWriteSignature, snakeCaseWriteSignature } from "./write.js";
6
+ export { defaultWriteSignature } from "./write.js";
@@ -1,6 +1,9 @@
1
1
  import type { SignatureDocs } from "@better-fs-tools/read";
2
2
  import type { PatchSignature } from "./contract.ts";
3
- /** apply_patch({ patch }) as JSON, with a short example in the description. */
3
+ /**
4
+ * apply_patch({ patch }) as JSON, with a short example in the description. For
5
+ * a host with grammar tools, use freeformPatchSignature().
6
+ */
4
7
  export declare function defaultPatchSignature(options?: SignatureDocs<"patch">): PatchSignature;
5
8
  /** defaultPatchSignature plus the Codex Lark grammar, for hosts with grammar tools. */
6
9
  export declare function freeformPatchSignature(options?: SignatureDocs<"patch">): PatchSignature;
@@ -21,7 +21,10 @@ const patchDescription = (patch) => "Apply a patch that adds, updates, moves, or
21
21
  "`*** Move to: <path>` after an Update line to rename the file. Every line of an Add " +
22
22
  "starts with `+`. Every hunk is checked before any file changes: when one fails, no file " +
23
23
  "changes. Read each file you update or delete with the read tool first.";
24
- /** apply_patch({ patch }) as JSON, with a short example in the description. */
24
+ /**
25
+ * apply_patch({ patch }) as JSON, with a short example in the description. For
26
+ * a host with grammar tools, use freeformPatchSignature().
27
+ */
25
28
  export function defaultPatchSignature(options = {}) {
26
29
  return patchSignature(options, "defaultPatchSignature");
27
30
  }