@better-fs-tools/write 0.1.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.
Files changed (56) hide show
  1. package/README.md +122 -106
  2. package/dist/bundle/create-fs-tools.d.ts +83 -21
  3. package/dist/bundle/create-fs-tools.js +61 -22
  4. package/dist/bundle/definitions.d.ts +51 -0
  5. package/dist/bundle/definitions.js +42 -0
  6. package/dist/contract/deps.d.ts +13 -5
  7. package/dist/contract/messages.d.ts +0 -23
  8. package/dist/contract/preconditions.d.ts +5 -1
  9. package/dist/contract/preconditions.js +1 -1
  10. package/dist/core/commit.d.ts +0 -1
  11. package/dist/core/commit.js +1 -35
  12. package/dist/core/create-tools.d.ts +9 -9
  13. package/dist/core/create-tools.js +11 -11
  14. package/dist/core/deps.d.ts +4 -4
  15. package/dist/core/deps.js +10 -7
  16. package/dist/core/format.js +1 -15
  17. package/dist/core/hooks.js +1 -8
  18. package/dist/core/load.js +1 -1
  19. package/dist/core/messages.js +8 -11
  20. package/dist/core/patch-hunks.js +31 -3
  21. package/dist/core/patch-pipeline.js +1 -2
  22. package/dist/core/pipeline.js +2 -2
  23. package/dist/core/plan-edit.d.ts +2 -0
  24. package/dist/core/plan-edit.js +3 -3
  25. package/dist/core/precondition.js +2 -13
  26. package/dist/core/record.js +1 -0
  27. package/dist/formatters/default.d.ts +7 -1
  28. package/dist/formatters/default.js +23 -5
  29. package/dist/guards/index.d.ts +9 -3
  30. package/dist/guards/index.js +11 -3
  31. package/dist/guards/non-text.d.ts +5 -1
  32. package/dist/guards/non-text.js +5 -1
  33. package/dist/index.d.ts +3 -3
  34. package/dist/index.js +1 -1
  35. package/dist/matchers/index.d.ts +4 -1
  36. package/dist/matchers/index.js +5 -3
  37. package/dist/matchers/keep-bytes.d.ts +22 -0
  38. package/dist/matchers/keep-bytes.js +51 -0
  39. package/dist/matchers/line-trimmed.d.ts +4 -1
  40. package/dist/matchers/line-trimmed.js +9 -1
  41. package/dist/matchers/normalized.d.ts +2 -1
  42. package/dist/matchers/normalized.js +7 -1
  43. package/dist/signature/definition.d.ts +41 -0
  44. package/dist/signature/definition.js +66 -0
  45. package/dist/signature/edit.d.ts +4 -5
  46. package/dist/signature/edit.js +5 -13
  47. package/dist/signature/index.d.ts +6 -2
  48. package/dist/signature/index.js +4 -2
  49. package/dist/signature/patch.d.ts +4 -1
  50. package/dist/signature/patch.js +4 -1
  51. package/dist/signature/write.d.ts +1 -6
  52. package/dist/signature/write.js +1 -8
  53. package/docs/architecture.md +14 -11
  54. package/docs/hosts.md +134 -55
  55. package/docs/result-schema.md +20 -26
  56. package/package.json +4 -4
@@ -12,7 +12,7 @@ function catalogUsingParam(param) {
12
12
  return `${path} was not found. Check the path and its parent directories.`;
13
13
  },
14
14
  notAFile: ({ path, kind }) => `${path} is a ${kindLabel(kind)}. Only regular files can be changed.`,
15
- dangerousPath: ({ path, detail }) => `${path} belongs to a refused policy class${detail === null ? "" : ` (${detail})`}. Choose another path.`,
15
+ dangerousPath: ({ path, detail }) => `${path} is refused by policy${detail === null ? "" : ` (${detail})`}. Choose another path.`,
16
16
  outsideAllowedRoots: ({ path }) => `${path} is outside every configured allowed root. Choose a path inside the workspace.`,
17
17
  permissionDenied: ({ path }) => `Permission was denied for ${path}.`,
18
18
  guardRefused: ({ guard, path }) => `The ${guard} check refused the change to ${path}.`,
@@ -24,11 +24,10 @@ 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.`,
31
- readBeforeWriteOff: () => "Read-before-write is off: this tool has no state store.",
32
31
  tooLarge: ({ path, what, limit, existing }) => {
33
32
  if (what === "patch") {
34
33
  return `The patch is over the limit of ${limit}. Split it into smaller patches.`;
@@ -71,7 +70,7 @@ function catalogUsingParam(param) {
71
70
  overlap: ({ path, first, second }) => `Edits ${first + 1} and ${second + 1} change overlapping text in ${path}. Merge them into one edit.`,
72
71
  noChange: ({ path }) => `The edits leave ${path} as it is. Check the ${param("newText")} values, or do not send the edit.`,
73
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.`,
74
- 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.`,
75
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.`,
76
75
  patchParse: ({ line, detail }) => `The patch could not be parsed at line ${line}: ${detail}`,
77
76
  patchVerifyHeader: () => "Patch validation failed (no files were modified):",
@@ -85,23 +84,21 @@ function catalogUsingParam(param) {
85
84
  `${path}: hunk ${hunk}: failed to find the expected lines:`,
86
85
  ...lines.map((line) => ` ${line}`),
87
86
  ].join("\n"),
88
- 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.`,
89
88
  patchCommitFailed: ({ path, code, rolledBack, files }) => rolledBack
90
89
  ? `Patch commit failed at ${path} (${code}). The patch was rolled back. No files are changed.`
91
90
  : [
92
91
  `Patch commit failed at ${path} (${code}). Rollback failed, so these files are in a mixed state:`,
93
92
  ...files.map((file) => `${file.state} ${file.path}`),
94
93
  ].join("\n"),
95
- notAtomic: ({ backend }) => `The ${backend} backend does not replace files atomically, so a reader could have seen a partial file.`,
96
- noCompareAndSwap: ({ backend }) => `The ${backend} backend cannot check the file version at the moment of the write. The tool checked it just before.`,
97
- modeNotKept: ({ backend }) => `The ${backend} backend does not keep file modes, so the file's permissions may have changed.`,
98
- directoriesCreated: ({ paths }) => `Created ${paths.length === 1 ? "the directory" : "the directories"} ${paths.join(", ")}.`,
99
94
  userModified: ({ path }) => `The user changed the content before it was written to ${path}. The file holds their version. Read it before changing it again.`,
100
95
  hookRewrote: ({ hook, path }) => `The ${hook} hook rewrote ${path} after the write. Read it again before relying on its text.`,
101
- hookFailed: ({ hook, path }) => `The ${hook} hook failed after ${path} was written. The file is changed.`,
102
- formatterFailed: ({ formatter }) => `The ${formatter} formatter failed, so the default formatter formatted this result.`,
103
96
  };
104
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
+ }
105
102
  function kindLabel(kind) {
106
103
  if (kind === "fifo")
107
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;
@@ -1,5 +1,5 @@
1
1
  import { authorizeAccess, authorizeChanges } from "./authorize.js";
2
- import { addCapabilityNotes, fileChange } from "./commit.js";
2
+ import { fileChange } from "./commit.js";
3
3
  import { commitPatch, deleteChange } from "./commit-patch.js";
4
4
  import { encodePlanned } from "./encode.js";
5
5
  import { formatResult } from "./format.js";
@@ -89,7 +89,6 @@ async function patchStages(scope, deps, request) {
89
89
  rewrittenByHook: false,
90
90
  };
91
91
  }
92
- addCapabilityNotes(scope, fs, plannedStep, file);
93
92
  const base = fileChange(scope, plannedStep, step.bytes, file);
94
93
  const change = source === null ? base : { ...base, movedFrom: source.displayPath };
95
94
  return committedFile(scope, plannedStep, change, file);
@@ -40,10 +40,10 @@ export async function runEdit(deps, input, call, misses) {
40
40
  catch (error) {
41
41
  return formatResult(deps, call, invalidInput(deps, "edit", input, error));
42
42
  }
43
- const { matchers } = deps;
43
+ const { matchers, recovery } = deps;
44
44
  const report = await runSingleFile(deps, request, call, {
45
45
  whenMissing: "not-found",
46
- plan: (scope, target, loaded, pre) => planEdit(scope, { request, matchers, misses }, target, loaded, pre),
46
+ plan: (scope, target, loaded, pre) => planEdit(scope, { request, matchers, recovery, misses }, target, loaded, pre),
47
47
  whenSameBytes: "error",
48
48
  });
49
49
  return formatResult(deps, call, report);
@@ -8,6 +8,8 @@ import type { MutationScope } from "./scope.ts";
8
8
  export interface EditPlanInput {
9
9
  readonly request: EditRequest;
10
10
  readonly matchers: readonly Matcher[];
11
+ /** Turns on already-applied, the closest-region hint, and the repeated-miss note. */
12
+ readonly recovery: boolean;
11
13
  readonly misses: MissCounter;
12
14
  }
13
15
  export declare function planEdit<THost>(scope: MutationScope<THost>, input: EditPlanInput, target: ResolvedTarget, loaded: Loaded | null, pre: PreconditionResult): Planned | "no-change";
@@ -129,7 +129,7 @@ function matchPair(scope, input, target, text, pair, index) {
129
129
  maxMatches,
130
130
  });
131
131
  if (chain === null) {
132
- if (isAlreadyApplied(text, pair.newText))
132
+ if (input.recovery && isAlreadyApplied(text, pair.newText))
133
133
  return "applied";
134
134
  throw noMatchFailure(scope, input, target, text, pair, index);
135
135
  }
@@ -197,8 +197,8 @@ function noMatchFailure(scope, input, target, text, pair, index) {
197
197
  const { messages, limits } = scope.deps;
198
198
  const path = target.requestedPath;
199
199
  const newline = trailingNewline(text, pair.oldText);
200
- const closest = closestRegion(text, pair.oldText, limits.maxHintLines);
201
- const misses = input.misses.miss(target.resolvedPath);
200
+ const closest = input.recovery ? closestRegion(text, pair.oldText, limits.maxHintLines) : null;
201
+ const misses = input.recovery ? input.misses.miss(target.resolvedPath) : 0;
202
202
  if (misses >= 3) {
203
203
  scope.notes.push({
204
204
  code: "repeated-miss",
@@ -11,10 +11,8 @@ export async function checkPrecondition(scope, fs, stat, loaded, requested) {
11
11
  return { precondition: { kind: "absent" }, record: null, mustRematch: false };
12
12
  }
13
13
  const version = { kind: "version", version: loaded.version };
14
- if (preconditions.requireRead === "off")
15
- return { precondition: version, record: null, mustRematch: false };
16
- if (store === null) {
17
- addReadBeforeWriteOffNote(scope, tool);
14
+ // With no store, the check is off. The host chose this, so the model is not told.
15
+ if (preconditions.requireRead === "off" || store === null) {
18
16
  return { precondition: version, record: null, mustRematch: false };
19
17
  }
20
18
  const record = await getUsableRecord(scope, store, stat.resolvedPath, digest?.id ?? null);
@@ -65,12 +63,3 @@ function partialAllowed(policy, tool) {
65
63
  return false;
66
64
  return tool === "edit" || tool === "apply_patch";
67
65
  }
68
- function addReadBeforeWriteOffNote(scope, tool) {
69
- if (scope.notes.some((note) => note.code === "read-before-write-off"))
70
- return;
71
- scope.notes.push({
72
- code: "read-before-write-off",
73
- severity: "warning",
74
- message: scope.deps.messages.readBeforeWriteOff({ tool }),
75
- });
76
- }
@@ -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
  };
@@ -2,15 +2,21 @@ import type { Note } from "@better-fs-tools/read";
2
2
  import type { WriteToolName } from "../contract/context.ts";
3
3
  import type { WriteFormatter } from "../contract/format.ts";
4
4
  export interface WriteFormatterOptions {
5
+ /** Add the numbered lines around each edit to the model text. Default false. */
6
+ readonly snippet?: boolean;
5
7
  /** Line-number prefix for edit snippets. Default: `${line}|`, as the read tool shows. */
6
8
  readonly gutter?: (line: number) => string;
7
9
  /** Add each change's diff to the model text. Default false. */
8
10
  readonly diff?: boolean;
11
+ /** Filter or rewrite a note for the model text. null hides it. Default: show every note. */
12
+ readonly notes?: (note: Note, tool: WriteToolName) => Note | null;
9
13
  /** Default: `[${tool}:${note.code}] ${note.message}`. */
10
14
  readonly noteLine?: (note: Note, tool: WriteToolName) => string;
11
15
  }
12
16
  /**
13
17
  * Formats a result as a line for each file, then the notes. An error shows the
14
- * notes only. "view" mode leaves the notes out.
18
+ * notes only. "view" mode leaves the notes out. `snippet` adds the lines
19
+ * around each edit, and `diff` adds each diff. The `notes` option hides or
20
+ * rewrites a note, as the read tool's formatters do.
15
21
  */
16
22
  export declare function defaultWriteFormatter(options?: WriteFormatterOptions): WriteFormatter<unknown>;
@@ -1,29 +1,35 @@
1
1
  /**
2
2
  * Formats a result as a line for each file, then the notes. An error shows the
3
- * notes only. "view" mode leaves the notes out.
3
+ * notes only. "view" mode leaves the notes out. `snippet` adds the lines
4
+ * around each edit, and `diff` adds each diff. The `notes` option hides or
5
+ * rewrites a note, as the read tool's formatters do.
4
6
  */
5
7
  export function defaultWriteFormatter(options = {}) {
6
8
  if (options === null || typeof options !== "object" || Array.isArray(options)) {
7
9
  throw new TypeError("defaultWriteFormatter options must be an object");
8
10
  }
9
- const { gutter = defaultGutter, diff = false, noteLine = defaultNoteLine } = options;
11
+ const { snippet = false, gutter = defaultGutter, diff = false, notes: filter = showNote, noteLine = defaultNoteLine, } = options;
10
12
  if (typeof gutter !== "function") {
11
13
  throw new TypeError("gutter must be a function");
12
14
  }
15
+ if (typeof snippet !== "boolean")
16
+ throw new TypeError("snippet must be a boolean");
13
17
  if (typeof diff !== "boolean")
14
18
  throw new TypeError("diff must be a boolean");
19
+ if (typeof filter !== "function")
20
+ throw new TypeError("notes must be a function");
15
21
  if (typeof noteLine !== "function")
16
22
  throw new TypeError("noteLine must be a function");
17
23
  return Object.freeze({
18
24
  id: "default",
19
25
  format(report, ctx) {
20
26
  const main = [
21
- ...body(report, gutter, ctx.limits.maxListedMatches),
27
+ ...body(report, snippet ? gutter : null, ctx.limits.maxListedMatches),
22
28
  ...(diff ? diffBlocks(report.changes) : []),
23
29
  ];
24
30
  if (ctx.mode === "view")
25
31
  return main.join("\n");
26
- const notes = report.notes.map((note) => noteLine(note, report.tool));
32
+ const notes = noteLines(report.notes, report.tool, filter, noteLine);
27
33
  if (notes.length === 0)
28
34
  return main.join("\n");
29
35
  if (main.length === 0)
@@ -32,6 +38,18 @@ export function defaultWriteFormatter(options = {}) {
32
38
  },
33
39
  });
34
40
  }
41
+ function noteLines(notes, tool, filter, line) {
42
+ const lines = [];
43
+ for (const note of notes) {
44
+ const shown = filter(note, tool);
45
+ if (shown !== null)
46
+ lines.push(line(shown, tool));
47
+ }
48
+ return lines;
49
+ }
50
+ function showNote(note) {
51
+ return note;
52
+ }
35
53
  function defaultNoteLine(note, tool) {
36
54
  return `[${tool}:${note.code}] ${note.message}`;
37
55
  }
@@ -48,7 +66,7 @@ function body(report, gutter, listed) {
48
66
  if (report.tool === "edit") {
49
67
  return report.changes.flatMap((change) => [
50
68
  editLine(change, listed),
51
- ...snippetLines(change.snippets, gutter),
69
+ ...(gutter === null ? [] : snippetLines(change.snippets, gutter)),
52
70
  ]);
53
71
  }
54
72
  if (report.tool === "apply_patch") {
@@ -6,8 +6,14 @@ export { readPrefixGuard } from "./read-prefix.ts";
6
6
  export { syntaxGuard } from "./syntax.ts";
7
7
  export { truncationNoticeGuard } from "./truncation-notice.ts";
8
8
  /**
9
- * The guards every write tool runs by default, in order: read prefix,
10
- * truncation notice, omission, syntax (JSON), and non-text.
11
- * generatedFileGuard is opt-in.
9
+ * The guards every write tool runs by default: none. Pass guards, for
10
+ * example recommendedGuards(), to turn them on.
12
11
  */
13
12
  export declare function defaultGuards(): readonly Guard<unknown>[];
13
+ /**
14
+ * The guards this package recommends, in order: read prefix, truncation
15
+ * notice, omission, syntax (JSON), and non-text. Each can refuse a write.
16
+ * They are off unless a host passes them as `guards`. generatedFileGuard is
17
+ * not in the list.
18
+ */
19
+ export declare function recommendedGuards(): readonly Guard<unknown>[];
@@ -10,11 +10,19 @@ export { readPrefixGuard } from "./read-prefix.js";
10
10
  export { syntaxGuard } from "./syntax.js";
11
11
  export { truncationNoticeGuard } from "./truncation-notice.js";
12
12
  /**
13
- * The guards every write tool runs by default, in order: read prefix,
14
- * truncation notice, omission, syntax (JSON), and non-text.
15
- * generatedFileGuard is opt-in.
13
+ * The guards every write tool runs by default: none. Pass guards, for
14
+ * example recommendedGuards(), to turn them on.
16
15
  */
17
16
  export function defaultGuards() {
17
+ return Object.freeze([]);
18
+ }
19
+ /**
20
+ * The guards this package recommends, in order: read prefix, truncation
21
+ * notice, omission, syntax (JSON), and non-text. Each can refuse a write.
22
+ * They are off unless a host passes them as `guards`. generatedFileGuard is
23
+ * not in the list.
24
+ */
25
+ export function recommendedGuards() {
18
26
  return Object.freeze([
19
27
  readPrefixGuard(),
20
28
  truncationNoticeGuard(),
@@ -1,3 +1,7 @@
1
1
  import type { Guard } from "../contract/extensions.ts";
2
- /** Refuses new content that the classifiers find is not text, such as a notebook, NUL bytes, or an image. */
2
+ /**
3
+ * Refuses new content that the classifiers find is not text, such as NUL
4
+ * bytes or an image. The default classifiers read a notebook as JSON text.
5
+ * Add notebookClassifier() to the classifiers to refuse notebooks too.
6
+ */
3
7
  export declare function nonTextGuard(): Guard<unknown>;
@@ -1,7 +1,11 @@
1
1
  import { ALLOW, refuse } from "./shared.js";
2
2
  const ENCODER = new TextEncoder();
3
3
  const BOM = Uint8Array.of(0xef, 0xbb, 0xbf);
4
- /** Refuses new content that the classifiers find is not text, such as a notebook, NUL bytes, or an image. */
4
+ /**
5
+ * Refuses new content that the classifiers find is not text, such as NUL
6
+ * bytes or an image. The default classifiers read a notebook as JSON text.
7
+ * Add notebookClassifier() to the classifiers to refuse notebooks too.
8
+ */
5
9
  export function nonTextGuard() {
6
10
  return Object.freeze({
7
11
  id: "non-text",
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";
@@ -18,13 +18,13 @@ export { defaultPreconditions } from "./contract/preconditions.ts";
18
18
  export { blockAnchorMatcher, defaultEditMatchers, defaultPatchMatchers, escapeMatcher, exactMatcher, indentationMatcher, lineTrimmedMatcher, normalizedMatcher, } from "./matchers/index.ts";
19
19
  export { utf8Codec } from "./codecs/index.ts";
20
20
  export { memoryLocks } from "./locks/index.ts";
21
- export { defaultGuards, generatedFileGuard, nonTextGuard, omissionGuard, readPrefixGuard, syntaxGuard, truncationNoticeGuard, } from "./guards/index.ts";
21
+ export { defaultGuards, recommendedGuards, generatedFileGuard, nonTextGuard, omissionGuard, readPrefixGuard, syntaxGuard, truncationNoticeGuard, } from "./guards/index.ts";
22
22
  export { askBeforeWrite, protectPaths, writeAuthorizers } from "./authorize/index.ts";
23
23
  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, FsToolsBashOptions, FsToolsSharedKey, 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";
package/dist/index.js CHANGED
@@ -6,7 +6,7 @@ export { defaultPreconditions } from "./contract/preconditions.js";
6
6
  export { blockAnchorMatcher, defaultEditMatchers, defaultPatchMatchers, escapeMatcher, exactMatcher, indentationMatcher, lineTrimmedMatcher, normalizedMatcher, } from "./matchers/index.js";
7
7
  export { utf8Codec } from "./codecs/index.js";
8
8
  export { memoryLocks } from "./locks/index.js";
9
- export { defaultGuards, generatedFileGuard, nonTextGuard, omissionGuard, readPrefixGuard, syntaxGuard, truncationNoticeGuard, } from "./guards/index.js";
9
+ export { defaultGuards, recommendedGuards, generatedFileGuard, nonTextGuard, omissionGuard, readPrefixGuard, syntaxGuard, truncationNoticeGuard, } from "./guards/index.js";
10
10
  export { askBeforeWrite, protectPaths, writeAuthorizers } from "./authorize/index.js";
11
11
  export { executableShebang, verifyWrite } from "./hooks/index.js";
12
12
  export { defaultWriteFormatter } from "./formatters/index.js";
@@ -5,7 +5,10 @@ export { exactMatcher } from "./exact.ts";
5
5
  export { indentationMatcher } from "./indentation.ts";
6
6
  export { lineTrimmedMatcher } from "./line-trimmed.ts";
7
7
  export { normalizedMatcher } from "./normalized.ts";
8
- /** The matchers the edit tool tries by default, in order: exact, normalized, escape. */
8
+ /**
9
+ * The matchers the edit tool tries by default, in order: exact, normalized.
10
+ * escapeMatcher() and the other matchers are opt-in through `matchers`.
11
+ */
9
12
  export declare function defaultEditMatchers(): readonly Matcher[];
10
13
  /** The matchers the patch tool tries by default, in order: exact, normalized, line-trimmed. */
11
14
  export declare function defaultPatchMatchers(): readonly Matcher[];
@@ -1,4 +1,3 @@
1
- import { escapeMatcher } from "./escape.js";
2
1
  import { exactMatcher } from "./exact.js";
3
2
  import { lineTrimmedMatcher } from "./line-trimmed.js";
4
3
  import { normalizedMatcher } from "./normalized.js";
@@ -8,9 +7,12 @@ export { exactMatcher } from "./exact.js";
8
7
  export { indentationMatcher } from "./indentation.js";
9
8
  export { lineTrimmedMatcher } from "./line-trimmed.js";
10
9
  export { normalizedMatcher } from "./normalized.js";
11
- /** The matchers the edit tool tries by default, in order: exact, normalized, escape. */
10
+ /**
11
+ * The matchers the edit tool tries by default, in order: exact, normalized.
12
+ * escapeMatcher() and the other matchers are opt-in through `matchers`.
13
+ */
12
14
  export function defaultEditMatchers() {
13
- return Object.freeze([exactMatcher(), normalizedMatcher(), escapeMatcher()]);
15
+ return Object.freeze([exactMatcher(), normalizedMatcher()]);
14
16
  }
15
17
  /** The matchers the patch tool tries by default, in order: exact, normalized, line-trimmed. */
16
18
  export function defaultPatchMatchers() {
@@ -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>;