@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
package/README.md CHANGED
@@ -6,7 +6,7 @@ Edit, write, and apply_patch tools for TypeScript agents. They share one mutatio
6
6
  - `write` creates a file, or replaces a whole file.
7
7
  - `apply_patch` applies a patch in the Codex format to several files, and undoes the files it already changed when a later step fails.
8
8
 
9
- All three refuse to change a file the model has not read, refuse a file that changed since the read, keep a file's BOM and line endings, refuse obvious damage such as pasted line numbers, and say in the result what the backend could not promise.
9
+ All three keep a file's BOM and line endings and say in the result what the backend could not promise. Each extra check is opt-in: with a read store they refuse to change a file the model has not read, or a file that changed since the read, and with `recommendedGuards()` they refuse obvious damage such as pasted line numbers.
10
10
 
11
11
  ## Install
12
12
 
@@ -18,69 +18,77 @@ The package has no peers and imports no `node:` module. It depends on `@better-f
18
18
 
19
19
  ## Quick start
20
20
 
21
- `createFsTools({ fs })` builds all four tools over any `WritableFileSystem`. On Node, `createNodeFsTools()` from [`@better-fs-tools/node`](https://www.npmjs.com/package/@better-fs-tools/node) does the same with a Node filesystem and `nodeDigest()`:
21
+ `createFsTools({ fs })` builds `read`, `edit`, and `write` over any `WritableFileSystem`. On Node, pass `nodeFileSystem()` from [`@better-fs-tools/node`](https://www.npmjs.com/package/@better-fs-tools/node) as `fs`:
22
22
 
23
23
  ```ts
24
24
  import { memoryFileSystem } from "@better-fs-tools/fs";
25
- import { textOf } from "@better-fs-tools/read";
25
+ import { memoryStore, textOf } from "@better-fs-tools/read";
26
26
  import { createFsTools } from "@better-fs-tools/write";
27
27
 
28
28
  const fs = memoryFileSystem({ files: { "/src/app.ts": "export const a = 1;\n" } });
29
29
 
30
- // read, edit, write, and apply_patch with one store, one sha256Digest(), and
31
- // one lock manager, so edit and write know what the model has read.
32
- const { read, edit, write } = createFsTools({ fs });
33
-
34
- console.log(textOf(await edit({ path: "/src/app.ts", edits: [{ oldText: "1", newText: "2" }] })));
35
- // [edit:not-read] Read /src/app.ts with the read tool before changing it.
30
+ // read, edit, and write with one sha256Digest() and one lock manager.
31
+ const { edit, write } = createFsTools({ fs });
36
32
 
37
- await read({ path: "/src/app.ts" });
38
33
  const edited = await edit({ path: "/src/app.ts", edits: [{ oldText: "1", newText: "2" }] });
39
- console.log(textOf(edited));
40
- // Edited /src/app.ts: 1 replacement at line 1.
41
- // 1|export const a = 2;
34
+ console.log(textOf(edited)); // Edited /src/app.ts: 1 replacement at line 1.
42
35
 
43
36
  const created = await write({ path: "/src/b.ts", content: "export const b = 1;\n" });
44
37
  console.log(textOf(created)); // Created /src/b.ts (1 line).
38
+
39
+ // With a read store, edit and write need a read of an existing file first.
40
+ const checked = createFsTools({ fs, state: memoryStore() });
41
+ const bump = { path: "/src/app.ts", edits: [{ oldText: "2", newText: "3" }] };
42
+ console.log(textOf(await checked.edit(bump)));
43
+ // [edit:not-read] Read /src/app.ts with the read tool before changing it.
44
+
45
+ await checked.read({ path: "/src/app.ts" });
46
+ console.log(textOf(await checked.edit(bump))); // Edited /src/app.ts: 1 replacement at line 1.
45
47
  ```
46
48
 
47
49
  A tool call is `tool(input, ctx?)`. `ctx` is the read tool's call context: `{ signal?, callId?, host }`. The core passes the same object to every host function as `ctx.call`.
48
50
 
49
51
  ## One bundle for every tool
50
52
 
51
- `createFsTools(options)` takes a `WritableFileSystem`, or a factory that returns one for each call, and builds `read`, `edit`, `write`, and `apply_patch`. They share one `state` (one store, not a per-call factory; default `memoryStore({ clock })`, `null` turns read-before-write off), one `digest` (default `sha256Digest()`), one `locks` (default `memoryLocks()`), and one `clock`. It imports no `node:` module, so a Worker needs no host digest. Each tool's other options go under `read`, `edit`, `write`, and `applyPatch`.
53
+ `createFsTools(options)` takes a `WritableFileSystem`, or a factory that returns one for each call, and builds `read`, `edit`, and `write`. `applyPatch: true`, or an options object, adds `apply_patch`. The tools share one `state` (a store or a factory of the call; default `null`, so there is no read-before-write; `memoryStore({ clock })` turns it on), one `digest` (default `sha256Digest()`), one `locks` (default `memoryLocks()`), and one `clock`. It imports no `node:` module, so a Worker needs no host digest. Each tool's other options go under `read`, `edit`, `write`, and `applyPatch`.
52
54
 
53
55
  Bash is off unless you ask. `bash: { runner, env, ... }` adds a bash tool from [`@better-fs-tools/shell`](https://www.npmjs.com/package/@better-fs-tools/shell) that gets the same `digest` and `clock`. The allowed roots of the filesystem do not limit a command.
54
56
 
55
- The result also has `state`, `digest`, `locks`, `clock`, and `invalidate(path, call?)`, which deletes the record for a path so the next edit needs a read. It returns an `InvalidateOutcome`. When `fs` is a factory, pass the call context, for example `ctx.call` in a bash `afterRun` hook.
57
+ The result also has `applyPatch` (`null` unless asked for), `state`, `digest`, `locks`, `clock`, and `invalidate(path, call?)`, which deletes the record for a path so the next edit needs a read. It returns an `InvalidateOutcome`. When `fs` or `state` is a factory, pass the call context, for example `ctx.call` in a bash `afterRun` hook.
56
58
 
57
- An unknown option key, a shared key (`fs`, `state`, `digest`, `locks`, or `clock`) inside a tool's options, or `bash: true` throws `TypeError`. `createNodeFsTools()`, `createPiFsTools()`, and `createAiSdkFsTools()` wrap it.
59
+ An unknown option key, a shared key (`fs`, `state`, `digest`, `locks`, or `clock`) inside a tool's options, or `bash: true` throws `TypeError`.
60
+
61
+ `fsToolDefinitions(options)` from `./signature` builds the same bundle with each tool bound to its signature, and every integration bundle is an adapter over it. `editToolDefinition()`, `writeToolDefinition()`, and `applyPatchToolDefinition()` do the same for one tool. A definition has the name, description, and JSON Schema to declare, a `validate` for model input, and an `execute` that maps model input and runs the tool. Use them to connect the tools to a framework of your own.
58
62
 
59
63
  ## Hosts
60
64
 
61
65
  | Host | Package | Factories |
62
66
  | ------------------------------------- | --------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------- |
63
67
  | Any | this package | `createFsTools({ fs })`, `createEditTool()`, `createWriteTool()`, `createApplyPatchTool()` |
64
- | Node or Bun | [`@better-fs-tools/node`](https://www.npmjs.com/package/@better-fs-tools/node) | `createNodeFsTools()`, `createNodeEditTool()`, `createNodeWriteTool()`, `createNodeApplyPatchTool()` |
68
+ | Node or Bun | [`@better-fs-tools/node`](https://www.npmjs.com/package/@better-fs-tools/node) | `nodeFileSystem()` as the `fs` of any tool or bundle |
65
69
  | AI SDK 7 | [`@better-fs-tools/ai-sdk`](https://www.npmjs.com/package/@better-fs-tools/ai-sdk) | `createAiSdkFsTools({ fs })`, `createAiSdkEditTool()`, `createAiSdkWriteTool()`, `createAiSdkApplyPatchTool()` |
66
- | Pi coding agent | [`@better-fs-tools/pi`](https://www.npmjs.com/package/@better-fs-tools/pi) | `createPiFsTools()`, one factory for each tool, and a `pi.extensions` entry |
70
+ | Pi coding agent | [`@better-fs-tools/pi`](https://www.npmjs.com/package/@better-fs-tools/pi) | `createPiFsTools({ fs })`, one factory for each tool, and a `pi.extensions` entry |
71
+ | Pi agent core | [`@better-fs-tools/pi`](https://www.npmjs.com/package/@better-fs-tools/pi) | `createAgentCoreFsTools({ fs })` and one factory for each tool, from `./agent-core` |
72
+ | Pi durable harness | [`@better-fs-tools/pi-durable`](https://www.npmjs.com/package/@better-fs-tools/pi-durable) | `createDurableFsTools({ fs })`, an extension |
67
73
  | Cloudflare Shell, Computer, just-bash | `@better-fs-tools/cloudflare-shell`, `@better-fs-tools/cloudflare-computer`, `@better-fs-tools/just-bash` | Writable filesystems for `createFsTools()`, `createAiSdkFsTools()`, or the single factories |
68
74
 
69
- The standalone factories (`createNodeEditTool()`, `createAiSdkEditTool()`, `createPiEditTool()`, and the others) default to `state: null`. Every update then carries a `read-before-write-off` note. Use a bundle (`createFsTools()`, `createNodeFsTools()`, `createPiFsTools()`, or `createAiSdkFsTools()`), or pass the same `state`, `digest`, and `locks` to the read tool and the write tools.
75
+ The bundles and the single-tool factories (`createEditTool()`, `createAiSdkEditTool()`, `createPiEditTool()`, and the others) all default to `state: null`. The tools then change files that the model has not read, and nothing tells the model. The tool descriptions still ask the model to read first. For the check, pass `state: memoryStore()` to a bundle (`createFsTools()`, `createPiFsTools()`, or `createAiSdkFsTools()`), or pass the same `state`, `digest`, and `locks` to the read tool and the write tools.
70
76
 
71
- [docs/hosts.md](docs/hosts.md) lists the defaults of every bundle and single factory, the default signature of each tool in each host, and what each backend can do.
77
+ Every integration takes the options of the core factories, with the same defaults. [docs/hosts.md](docs/hosts.md) lists the shared defaults, the default signature of each tool, the few host options, a recommended configuration for each host, and what each backend can do.
72
78
 
73
79
  ## edit
74
80
 
75
81
  `createEditTool({ fs })`. The input is a path and one or more `{ oldText, newText, replaceAll? }` pairs, all matched against one snapshot of the file. Each old text must match once, unless `replaceAll` is set. Pairs must not overlap. The replacement is a literal splice: `$&` and `$1` in the new text stay as written.
76
82
 
77
- Matching tries `exactMatcher()` first, then `normalizedMatcher()` (trailing whitespace, Unicode normalization, curly quotes, dashes, and special spaces), then `escapeMatcher()` (escape sequences written out). A loose match gives a `fuzzy-match` note that names the lines. `lineTrimmedMatcher()`, `indentationMatcher()`, and `blockAnchorMatcher()` are opt-in through the `matchers` dependency.
83
+ Matching tries `exactMatcher()` first, then `normalizedMatcher()` (trailing whitespace, Unicode normalization, curly quotes, dashes, and special spaces). A loose match gives a `fuzzy-match` note that names the lines. After a loose match with `normalizedMatcher()` or `lineTrimmedMatcher()`, the leading and trailing lines that the new text leaves as they were keep the file's bytes, and each replaced line keeps the CR of the file line it replaces. When the old text and the new text are the same, the edit can only change the characters that the matcher folded, so the new text is written as given. `escapeMatcher()` (escape sequences written out), `lineTrimmedMatcher()`, `indentationMatcher()`, and `blockAnchorMatcher()` are opt-in through the `matchers` option, for example `matchers: [...defaultEditMatchers(), escapeMatcher()]`.
84
+
85
+ When a pair does not match, the error is `NO_MATCH`, even when the new text is already in the file. `recovery: true` turns on three extras. The error shows the closest region of the file with line numbers. When the new text is already in the file and the old text is not, the pair is `already-applied` and the status is `no-change`. After three misses in a row on one file, the tool adds a `repeated-miss` note that asks the model to read the file again.
78
86
 
79
- When a pair does not match, the error shows the closest region of the file with line numbers. When the new text is already in the file and the old text is not, the pair is `already-applied` and the status is `no-change`. After three misses in a row on one file, the tool adds a `repeated-miss` note that asks the model to read the file again. The model text is a short header and the new lines around each change. The full diff is in `changes[].diff`.
87
+ The model text is one line, for example `Edited src/app.ts: 1 replacement at line 12.` `defaultWriteFormatter({ snippet: true })` adds the numbered lines around each change. The full diff is in `changes[].diff`, and `defaultWriteFormatter({ diff: true })` adds it to the model text.
80
88
 
81
89
  ## write
82
90
 
83
- `createWriteTool({ fs })` creates a missing file, or replaces an existing one. Missing parent folders are created. A replace needs a read of the whole file first. A partial read is not enough. The same content gives `no-change` and writes nothing, so the modification time stays.
91
+ `createWriteTool({ fs })` creates a missing file, or replaces an existing one. Missing parent folders are created. A replace needs a read of the whole file first. Reads in ranges count when together they show every line of the same content. The same content gives `no-change` and writes nothing, so the modification time stays.
84
92
 
85
93
  ## apply_patch
86
94
 
@@ -122,7 +130,7 @@ console.log(textOf(result));
122
130
  // D /src/old.ts
123
131
  ```
124
132
 
125
- Every operation is checked before any file changes. An Add on an existing file, an Update or Delete on a missing file, a move onto an existing file, two operations on one file, and a hunk that does not match all give `PATCH_VERIFY`, with every problem listed. Each hunk matches at the first place after the previous hunk, as Codex does. The chain is `exactMatcher()`, `normalizedMatcher()`, and `lineTrimmedMatcher()` on whole lines. Context lines keep the file's own bytes.
133
+ Every operation is checked before any file changes. An Add on an existing file, an Update or Delete on a missing file, a move onto an existing file, two operations on one file, and a hunk that does not match all give `PATCH_VERIFY`, with every problem listed. Each hunk matches at the first place after the previous hunk, as Codex does. The chain is `exactMatcher()`, `normalizedMatcher()`, and `lineTrimmedMatcher()` on whole lines. Context lines keep the file's own bytes. So does a `-` line that comes back unchanged as a `+` line. Each other `+` line keeps the CR of the file line it replaces, so a CRLF line in a mixed-EOL file stays CRLF. When the old and new lines of a hunk are the same, the hunk can only change the characters that the matcher folded, so its `+` lines are written as given.
126
134
 
127
135
  The commit stages every new file when the backend has `stage()`, then publishes in patch order. Without `stage()` it writes each file in turn. When a step fails, the steps already done are undone from the end, and `result.commit` says so. When an undo step also fails, the code is `PARTIAL_COMMIT` and `result.commit.files` lists the state of every file. A host can pass its own `patchParser` for another patch format.
128
136
 
@@ -130,57 +138,58 @@ The commit stages every new file when the backend has `stage()`, then publishes
130
138
 
131
139
  With the read tool's `state` store and a `digest`, the write tools check what the model has seen:
132
140
 
133
- - An existing file needs a record from a read. `edit` and `apply_patch` accept a partial read. `write` needs a read of the whole file.
134
- - A file that changed since the read gives `STALE`, with one exception: `edit` and `apply_patch` go ahead when every old text still matches exactly once, with a `stale-rematched` note. `write` always refuses.
141
+ - An existing file needs a record from a read. `edit` and `apply_patch` accept a partial read. `write` needs a read of the whole file. Ranged reads of the same content count as a whole read when together they show every line.
142
+ - A file that changed since the read gives `STALE`. With `preconditions: { onStale: "rematch" }`, `edit` and `apply_patch` go ahead when every old text still matches exactly once, with a `stale-rematched` note. `write` always refuses.
135
143
  - On a backend with stable identity, the check compares the backend `version`. On every other backend it compares the content hash.
136
144
  - After a commit, the tool stores a record with `origin: "write"`. A second edit needs no new read. When an authorizer replaced the content, a hook rewrote the file, or an edit went ahead on a stale file, the record says the model has not seen the whole file, so a following `write` needs a read.
137
145
  - `createInvalidator({ fs, state })` returns `invalidate(path)`. Call it when something else, for example a shell tool, may have changed a file. The next edit then needs a read. It never throws. It resolves to an `InvalidateOutcome`: `{ ok: true, resolvedPath, recorded }`, where `recorded` says whether a record was there, or `{ ok: false, phase }` when the stat (`phase: "stat"`, with the backend `error`) or the store (`phase: "state"`, with a `detail`) failed. After `ok: false` the record may still be there.
138
146
  - `preconditions: { requireRead: "off" }` turns the check off. `partialRead` and `onStale` change the other two rules.
139
147
 
140
- `state` without `digest` is a `TypeError`, as in the read tool, and the `StateNeedsDigest` type refuses it at compile time. `state: null` turns the check off, and every update carries a `read-before-write-off` note.
141
-
142
- ## Dependencies
143
-
144
- Every dependency except `fs` has a default. Pass them to `createEditTool()`, `createWriteTool()`, or `createApplyPatchTool()`, or to a host factory.
145
-
146
- | Dependency | Default | Meaning |
147
- | --------------- | --------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------- |
148
- | `fs` | required | A `WritableFileSystem`, or a factory of the call context that runs once for each call |
149
- | `state` | `null` | The read tool's store, or a factory. Needs `digest` |
150
- | `digest` | `null` | Content hashes for records and `changes[].after.contentId` |
151
- | `locks` | `memoryLocks()` | Orders writers to one path inside the process. Share one across the three tools. `timeoutMs` default 30 s |
152
- | `resolve` | `null` | A read `PathResolver`, for example `unicodeRepair()` |
153
- | `authorize` | `null` | A `WriteAuthorizer`, or a read `ToolAuthorizer` such as `denyPaths()` |
154
- | `guards` | `defaultGuards()` | Checks on each planned change. `[]` turns them off |
155
- | `hooks` | `[]` | Run after each committed file |
156
- | `matchers` | edit: `defaultEditMatchers()`; patch: `defaultPatchMatchers()` | The match chain, in order |
157
- | `preconditions` | `{ requireRead: "existing", partialRead: "edit-only", onStale: "rematch" }` | Read-before-write rules |
158
- | `limits` | `defaultWriteLimits` | See below |
159
- | `messages` | `defaultWriteMessages` | Every model-facing text. Merged key by key |
160
- | `formatter` | `defaultWriteFormatter()` | Turns the report into content parts. `{ diff: true }` adds the full diff to the model text |
161
- | `classifiers` | the read tool's default classifiers | Refuse a target that is not text before it is decoded |
162
- | `codecs` | `[utf8Codec()]` | Decode and encode. `utf8Codec` keeps a BOM, CRLF, and mixed line endings |
163
- | `clock` | `() => new Date()` | Record times |
164
- | `patchParser` | `codexPatchParser()` | `apply_patch` only |
165
-
166
- | Limit | Default | Meaning |
167
- | ------------------ | ------- | ---------------------------------------------- |
168
- | `maxFileBytes` | 8 MiB | Bytes of an existing file that any tool loads |
169
- | `maxWriteBytes` | 8 MiB | Encoded bytes of new content for one file |
170
- | `maxPatchBytes` | 4 MiB | UTF-8 bytes of patch text |
171
- | `maxPatchFiles` | 100 | Operations in one patch |
172
- | `maxEdits` | 100 | Pairs in one edit call |
173
- | `sampleBytes` | 8 192 | Bytes given to the classifiers and codecs |
174
- | `snippetLines` | 3 | Context lines around each change in a snippet |
175
- | `maxSnippetLines` | 40 | Snippet lines for one file in the model text |
176
- | `maxDiffLines` | 2 000 | Lines of unified diff kept in `changes[].diff` |
177
- | `maxHintLines` | 12 | Lines in a closest-region hint |
178
- | `maxListedMatches` | 10 | Line numbers listed for an ambiguous match |
179
- | `maxPatchProblems` | 20 | Problems listed for a failed patch verify |
180
-
181
- A `sampleBytes` that you set above `maxFileBytes` throws `TypeError`. When you set only `maxFileBytes` below 8 192, the default `sampleBytes` is lowered to it. The same limits rule holds in read, write, and bash. A per-call value over its ceiling is clamped, with a `clamped` info note. Two limits that you set and that conflict throw `TypeError` when the tool is built. A default that is over a ceiling you set is lowered to that ceiling.
182
-
183
- Every tool has one parse helper with the same pattern: `parseReadInput`, `parseEditInput`, `parseWriteInput`, `parseApplyPatchInput`, and `parseBashInput`. Each takes the canonical input and the resolved limits, returns the request, and throws `TypeError` for input it refuses. The tool turns that throw into `INVALID_INPUT`. A clamp is not an error: the helper returns the clamped value, and the tool adds the `clamped` note.
148
+ `state` with `digest: null` is a `TypeError`, as in the read tool, and the `StateNeedsDigest` type refuses it at compile time. The default digest is `sha256Digest()`. `state: null` turns the check off. The result has no note about this, because the model cannot change the host's setup.
149
+
150
+ ## Options
151
+
152
+ Every option except `fs` has a default. Pass them to `createEditTool()`, `createWriteTool()`, or `createApplyPatchTool()`, or to an integration factory, which has the same defaults.
153
+
154
+ | Option | Default | Meaning |
155
+ | --------------- | -------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------- |
156
+ | `fs` | required | A `WritableFileSystem`, or a factory of the call context that runs once for each call |
157
+ | `state` | `null` | The read tool's store, or a factory. Needs a `digest` |
158
+ | `digest` | `sha256Digest()` | Content hashes for records and `changes[].after.contentId`. `null` turns them off |
159
+ | `locks` | `memoryLocks()` | Orders writers to one path inside the process. Share one across the three tools. `timeoutMs` default 30 s |
160
+ | `resolve` | `null` | A read `PathResolver`, for example `unicodeRepair()` |
161
+ | `authorize` | `null` | A `WriteAuthorizer`, or a read `ToolAuthorizer` such as `denyPaths()` |
162
+ | `guards` | `[]` | Checks on each planned change. `recommendedGuards()` gives the five this package recommends |
163
+ | `hooks` | `[]` | Run after each committed file |
164
+ | `matchers` | edit: `defaultEditMatchers()`; patch: `defaultPatchMatchers()` | The match chain, in order |
165
+ | `recovery` | `false` | `edit` only. `true` adds the closest-region hint, `already-applied`, and the `repeated-miss` note |
166
+ | `preconditions` | `{ requireRead: "existing", partialRead: "edit-only", onStale: "reject" }` | Read-before-write rules |
167
+ | `limits` | `defaultWriteLimits` | See below |
168
+ | `messages` | `defaultWriteMessages` | Every model-facing text. Merged key by key |
169
+ | `formatter` | `defaultWriteFormatter()` | Turns the report into content parts. `{ snippet: true }` adds edit snippets, `{ diff: true }` the diff |
170
+ | `classifiers` | the read tool's default classifiers | Refuse a target that is not text before it is decoded |
171
+ | `codecs` | `[utf8Codec()]` | Decode and encode. `utf8Codec` keeps a BOM, CRLF, and mixed line endings |
172
+ | `clock` | `() => new Date()` | Record times |
173
+ | `patchParser` | `codexPatchParser()` | `apply_patch` only |
174
+
175
+ | Limit | Default | Meaning |
176
+ | ------------------ | ------- | ------------------------------------------------------------------------------------------------------------- |
177
+ | `maxFileBytes` | 8 MiB | Bytes of an existing file that any tool loads |
178
+ | `maxWriteBytes` | 8 MiB | Encoded bytes of new content for one file |
179
+ | `maxPatchBytes` | 4 MiB | UTF-8 bytes of patch text |
180
+ | `maxPatchFiles` | 100 | Operations in one patch |
181
+ | `maxEdits` | 100 | Pairs in one edit call |
182
+ | `sampleBytes` | 8 192 | Bytes given to the classifiers and codecs |
183
+ | `snippetLines` | 3 | Context lines around each change in a snippet. The default formatter shows snippets only with `snippet: true` |
184
+ | `maxSnippetLines` | 40 | Snippet lines for one file in the model text |
185
+ | `maxDiffLines` | 2 000 | Lines of unified diff kept in `changes[].diff` |
186
+ | `maxHintLines` | 12 | Lines in a closest-region hint (`recovery: true`) |
187
+ | `maxListedMatches` | 10 | Line numbers listed for an ambiguous match |
188
+ | `maxPatchProblems` | 20 | Problems listed for a failed patch verify |
189
+
190
+ A `sampleBytes` that you set above `maxFileBytes` throws `TypeError`. When you set only `maxFileBytes` below 8 192, the default `sampleBytes` is lowered to it. The same limits rule holds in read, write, and bash. In read and bash, a per-call value over its ceiling is clamped, with a `clamped` info note. The write tools clamp nothing: an input over a write limit, such as too many edits, gives `INVALID_INPUT`. Two limits that you set and that conflict throw `TypeError` when the tool is built. A default that is over a ceiling you set is lowered to that ceiling.
191
+
192
+ Every tool has one parse helper with the same pattern: `parseReadInput`, `parseEditInput`, `parseWriteInput`, `parseApplyPatchInput`, and `parseBashInput`. Each takes the canonical input and the resolved limits, returns the request, and throws `TypeError` for input it refuses. The tool turns that throw into `INVALID_INPUT`. In read and bash, a clamp is not an error: the helper returns the clamped value, and the tool adds the `clamped` note.
184
193
 
185
194
  ## Authorize
186
195
 
@@ -224,7 +233,7 @@ An authorizer may allow with `content` for `edit` and `write`. The tool then wri
224
233
 
225
234
  ## Guards and hooks
226
235
 
227
- Guards check each planned change before anything is written. `defaultGuards()` is on unless the `guards` dependency replaces it. It refuses new text that carries the read tool's line-number gutter (`readPrefixGuard`), a read note line or clamp marker (`truncationNoticeGuard`), or a placeholder such as `// ... rest of code` in place of real lines (`omissionGuard`). It refuses an update that makes a valid `.json` file invalid (`syntaxGuard`), and new content that the classifiers do not call text (`nonTextGuard`). Each guard lets the near miss through: lines already in the file, a file that was already broken, or a create. `generatedFileGuard()` is opt-in. It refuses updates to files that look generated. A host guard returns `{ allow: true, notes? }` or `{ allow: false, note? }`, as an authorizer does. A refusal without a note gets the `guardRefused` message from the catalog.
236
+ Guards check each planned change before anything is written. No guard runs by default. `recommendedGuards()` gives the five this package recommends, and the `guards` option turns them on. They refuse new text that carries the read tool's line-number gutter (`readPrefixGuard`), a read note line or clamp marker (`truncationNoticeGuard`), or a placeholder such as `// ... rest of code` in place of real lines (`omissionGuard`). It refuses an update that makes a valid `.json` file invalid (`syntaxGuard`), and new content that the classifiers do not call text (`nonTextGuard`). The default classifiers call a notebook JSON text. Pass `classifiers: [notebookClassifier(), ...defaultClassifiers()]` to refuse notebooks on load and in `nonTextGuard`. Each guard lets the near miss through: lines already in the file, a file that was already broken, or a create. `generatedFileGuard()` is opt-in. It refuses updates to files that look generated. A host guard returns `{ allow: true, notes? }` or `{ allow: false, note? }`, as an authorizer does. A refusal without a note gets the `guardRefused` message from the catalog.
228
237
 
229
238
  Hooks run after each committed file. `executableShebang()` gives a new file that starts with `#!` mode `0o755`, through the hook's `newFileMode()`. `verifyWrite()` reads each committed file back and adds a warning when it does not match what was written. A hook failure is a warning note: the file is already committed, so the status stays `ok`.
230
239
 
@@ -233,9 +242,9 @@ import { memoryFileSystem } from "@better-fs-tools/fs";
233
242
  import { textOf } from "@better-fs-tools/read";
234
243
  import {
235
244
  createWriteTool,
236
- defaultGuards,
237
245
  executableShebang,
238
246
  generatedFileGuard,
247
+ recommendedGuards,
239
248
  syntaxGuard,
240
249
  verifyWrite,
241
250
  } from "@better-fs-tools/write";
@@ -271,9 +280,10 @@ const logChanges: WriteHook<unknown> = {
271
280
 
272
281
  const write = createWriteTool({
273
282
  fs: memoryFileSystem({ directories: ["/repo"] }),
274
- // defaultGuards() is the default. Passing guards replaces the whole list.
283
+ // No guards run by default. recommendedGuards() gives the five this
284
+ // package recommends. Passing guards replaces the whole list.
275
285
  guards: [
276
- ...defaultGuards().filter((guard) => guard.id !== "syntax"),
286
+ ...recommendedGuards().filter((guard) => guard.id !== "syntax"),
277
287
  syntaxGuard({ parsers: { yaml: (text) => void text } }),
278
288
  generatedFileGuard(),
279
289
  noTabsInYaml,
@@ -295,13 +305,12 @@ console.log(textOf(await write({ path: "/repo/run.sh", content: "#!/bin/sh\necho
295
305
 
296
306
  A signature is what the model sees: a name, a description, and a JSON Schema. `toInput` checks model input and maps it to the core's canonical input, and `param(name)` gives the host name of a canonical parameter for messages. Every write signature is a `ToolSignature` from `@better-fs-tools/read`, the base that the read and bash signatures share. The host adapters take a `signature` option.
297
307
 
298
- Every preset takes the shared `SignatureDocs` options: `name`, `description`, `describe`, and `names`. `describe` and `names` use the preset's own parameter names as keys, so `camelCaseEditSignature` takes `oldString` and `defaultEditSignature` takes `old_string`. `camelCaseEditSignature` and `snakeCaseWriteSignature` are the default presets with the names two popular hosts use.
308
+ `defaultEditSignature()`, `defaultWriteSignature()`, and `defaultPatchSignature()` build the signatures. Each takes the shared `SignatureDocs` options: `name`, `description`, `describe`, and `names`. `describe` and `names` use the signature's own parameter names as keys, so `defaultEditSignature` takes `old_string`. Two presets give another shape. `multiEditSignature()` gives `edit({ path, edits: [{ oldText, newText }] })`, so the model can send many replacements in one call, up to `limits.maxEdits`. It has no replace-all parameter, so no message suggests one. `freeformPatchSignature()` is `defaultPatchSignature()` with the Codex patch grammar. For any other shape, write your own `EditSignature`, `WriteSignature`, or `PatchSignature`.
299
309
 
300
310
  ```ts
301
311
  import { memoryFileSystem } from "@better-fs-tools/fs";
302
312
  import { createEditTool } from "@better-fs-tools/write";
303
313
  import {
304
- camelCaseEditSignature,
305
314
  defaultEditSignature,
306
315
  freeformPatchSignature,
307
316
  multiEditSignature,
@@ -309,7 +318,15 @@ import {
309
318
  } from "@better-fs-tools/write/signature";
310
319
 
311
320
  // What the model sees: a name, a description, and a JSON Schema.
312
- const signature = camelCaseEditSignature({ name: "edit_file" });
321
+ const signature = defaultEditSignature({
322
+ name: "edit_file",
323
+ names: {
324
+ path: "filePath",
325
+ old_string: "oldString",
326
+ new_string: "newString",
327
+ replace_all: "replaceAll",
328
+ },
329
+ });
313
330
  console.log(signature.name, Object.keys(signature.schema.properties ?? {}));
314
331
  // edit_file [ "filePath", "oldString", "newString", "replaceAll" ]
315
332
 
@@ -326,20 +343,19 @@ export async function run(input: unknown) {
326
343
  return edit(signature.toInput(input));
327
344
  }
328
345
 
329
- // The other presets.
330
- export const presets = [
331
- defaultEditSignature(), // edit({ path, old_string, new_string, replace_all? })
332
- multiEditSignature(), // edit({ path, edits: [{ oldText, newText }] }), Pi's shape
333
- freeformPatchSignature(), // apply_patch({ patch }) plus a Lark grammar for grammar-tool hosts
334
- ];
335
-
336
- // Every preset takes names. The keys are the preset's own parameter names.
346
+ // The names keys are the default signature's own parameter names.
337
347
  export const renamed = defaultEditSignature({
338
348
  names: { path: "file", old_string: "find", new_string: "replace" },
339
349
  }); // edit({ file, find, replace, replace_all? })
350
+
351
+ // Two presets give a shape that names alone cannot give.
352
+ export const presets = [
353
+ multiEditSignature(), // edit({ path, edits: [{ oldText, newText }] }), many replacements in one call
354
+ freeformPatchSignature(), // apply_patch({ patch }) plus the Codex Lark grammar for grammar-tool hosts
355
+ ];
340
356
  ```
341
357
 
342
- `freeformPatchSignature()` adds `grammar.lark`, the Codex patch grammar. The Pi adapter sends it as a grammar tool to models that support one. The AI SDK adapter ignores it and sends the JSON schema.
358
+ `freeformPatchSignature()` adds `grammar.lark`, the Codex patch grammar. The Pi, pi-agent-core, and pi-durable adapters send it as a grammar tool to models that support one. The AI SDK adapter ignores it and sends the JSON schema.
343
359
 
344
360
  ## The result
345
361
 
@@ -366,26 +382,26 @@ if (result.status === "error") {
366
382
  } else {
367
383
  for (const change of result.changes) {
368
384
  console.log(change.kind, change.path, `+${change.linesAdded} -${change.linesRemoved}`);
369
- console.log(change.diff); // The full unified diff. The model text has only a snippet.
385
+ console.log(change.diff); // The full unified diff. The model text has only a summary line.
370
386
  console.log(change.after?.version); // The backend version after the commit
371
387
  }
372
388
  }
373
- // Without a state store, every update carries a read-before-write-off note.
374
- console.log(result.notes.map((note) => note.code)); // [ "read-before-write-off" ]
389
+ // Notes for the model, such as fuzzy-match. This plain update has none.
390
+ console.log(result.notes.map((note) => note.code)); // []
375
391
  console.log(textOf(result)); // What the model sees
376
392
  ```
377
393
 
378
394
  ## Backends
379
395
 
380
- The core adds a note when the backend cannot keep a promise: `not-atomic` when a reader could see a partial file, `no-compare-and-swap` when the backend cannot check the version at the moment of the write, and `mode-not-kept` when a replace may change the file's permissions.
396
+ The core reads one write capability, `compareAndSwap`. The other columns describe each backend for the host developer. The model gets no note about them.
381
397
 
382
- | Backend | `atomic` | `compareAndSwap` | `preserveMode` | `stage()` | `remove()` |
383
- | -------------------------------- | -------- | ------------------- | -------------- | --------- | ---------- |
384
- | `memoryFileSystem()` | yes | yes | yes | yes | yes |
385
- | `nodeFileSystem()` | yes | yes, in one process | yes | yes | yes |
386
- | `cloudflareShellFileSystem()` | no | no | no | no | yes |
387
- | `cloudflareComputerFileSystem()` | yes | no | yes | no | yes |
388
- | `justBashFileSystem()` | no | no | yes | no | yes |
398
+ | Backend | `compareAndSwap` | Atomic replace | Keeps the mode | `stage()` | `remove()` |
399
+ | -------------------------------- | ------------------- | -------------- | -------------- | --------- | ---------- |
400
+ | `memoryFileSystem()` | yes | yes | yes | yes | yes |
401
+ | `nodeFileSystem()` | yes, in one process | yes | yes | yes | yes |
402
+ | `cloudflareShellFileSystem()` | no | no | no modes | no | yes |
403
+ | `cloudflareComputerFileSystem()` | no | yes | yes | no | yes |
404
+ | `justBashFileSystem()` | no | no | yes | no | yes |
389
405
 
390
406
  Without compare-and-swap, the core checks the version with a fresh `stat` just before the write. Another writer can still change the file between that check and the write.
391
407
 
@@ -393,18 +409,18 @@ Without compare-and-swap, the core checks the version with a fresh `stat` just b
393
409
 
394
410
  - `apply_patch` rollback lives in process memory. A crash or a killed process during the commit leaves some files changed and no report.
395
411
  - Undoing a create removes the file but leaves the parent folders the create made.
396
- - The repeated-miss count lives in each tool instance. A host that builds a new tool for each call never sees the `repeated-miss` note.
412
+ - With `recovery: true`, the repeated-miss count lives in each tool instance. A host that builds a new tool for each call never sees the `repeated-miss` note.
397
413
  - After-commit hooks are not raced against the abort signal. A hook that never settles holds the call open. From the first commit step on, the signal is ignored, so a started commit finishes.
398
414
  - `memoryStore()` forgets a read after 30 minutes, and keeps at most 1 000 records. A file read longer ago needs a new read before `edit`, and the result says so (`NOT_READ`).
399
- - A match with a loose matcher writes the model's new text as given. When the normalized matcher matched ASCII quotes against curly quotes, the model's ASCII quotes are written.
415
+ - After a loose match, a line that the model changed is written with the model's characters. When the normalized matcher matched ASCII quotes against curly quotes on that line, the model's ASCII quotes are written. Only whole unchanged lines keep the file's bytes. When a hit changes one line and retypes another line only to fix its lookalike characters, the retyped line keeps the file's bytes. In a mixed-EOL file, a line inserted where no line is replaced gets no CR.
400
416
 
401
417
  ## Entries
402
418
 
403
- | Entry | Contents |
404
- | ---------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
405
- | `@better-fs-tools/write` | `textOf` (the same function as in read and shell, re-exported for convenience), `createFsTools`, `createWriteTool`, `createEditTool`, `createApplyPatchTool`, the matchers, the guards and `defaultGuards`, the mutation core's types, `utf8Codec`, `memoryLocks`, `askBeforeWrite`, `writeAuthorizers`, `protectPaths`, `executableShebang`, `verifyWrite`, `defaultWriteFormatter`, `createInvalidator` |
406
- | `@better-fs-tools/write/patch` | `parsePatch`, `codexPatchParser`, `CODEX_PATCH_GRAMMAR`, and the patch types. The only home of these |
407
- | `@better-fs-tools/write/signature` | `defaultEditSignature`, `multiEditSignature`, `camelCaseEditSignature`, `defaultWriteSignature`, `snakeCaseWriteSignature`, `defaultPatchSignature`, `freeformPatchSignature`, and `writeSignatureMessages` |
419
+ | Entry | Contents |
420
+ | ---------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
421
+ | `@better-fs-tools/write` | `textOf` (the same function as in read and shell, re-exported for convenience), `createFsTools`, `createWriteTool`, `createEditTool`, `createApplyPatchTool`, the matchers, the guards, `defaultGuards` (empty) and `recommendedGuards`, the mutation core's types, `utf8Codec`, `memoryLocks`, `askBeforeWrite`, `writeAuthorizers`, `protectPaths`, `executableShebang`, `verifyWrite`, `defaultWriteFormatter`, `createInvalidator` |
422
+ | `@better-fs-tools/write/patch` | `parsePatch`, `codexPatchParser`, `CODEX_PATCH_GRAMMAR`, and the patch types. The only home of these |
423
+ | `@better-fs-tools/write/signature` | `defaultEditSignature`, `multiEditSignature`, `defaultWriteSignature`, `defaultPatchSignature`, `freeformPatchSignature`, and `writeSignatureMessages` |
408
424
 
409
425
  The package builds on the tool-neutral base types in `@better-fs-tools/read`, such as `ToolCallContext`, `PathResolver`, and `ToolAuthorizer`. An authorizer or resolver typed on them works for the read tool and for the write tools:
410
426
 
@@ -434,8 +450,8 @@ export const noGenerated: ToolAuthorizer<unknown> = {
434
450
  ## More
435
451
 
436
452
  - [docs/architecture.md](docs/architecture.md): the pipeline, the stages, and why they are fixed
437
- - [docs/result-schema.md](docs/result-schema.md): every field of the result, every error code, and every note, plus one table of the statuses and error codes of all five tools
438
- - [docs/hosts.md](docs/hosts.md): the defaults of every host and bundle, and what each backend can do
453
+ - [docs/result-schema.md](docs/result-schema.md): every field of the result, every error code, and every note, plus one table of the statuses and error codes of all five tools. The [write reference](https://better-fs-tools.gandrew.com/reference/write) on the docs site has the same facts
454
+ - [docs/hosts.md](docs/hosts.md): the defaults of every host and bundle, and what each backend can do. [Choose an integration](https://better-fs-tools.gandrew.com/integrations) and [Filesystems](https://better-fs-tools.gandrew.com/filesystems) on the docs site have the same tables
439
455
  - [`@better-fs-tools/fs`](https://www.npmjs.com/package/@better-fs-tools/fs): the `WritableFileSystem` contract and its conformance suite
440
456
 
441
457
  ## License
@@ -1,29 +1,48 @@
1
1
  import type { WritableFileSystem } from "@better-fs-tools/fs";
2
- import type { Clock, Digest, ReadStateStore, ReadTool, ReadToolDeps, ToolCallContext } from "@better-fs-tools/read";
3
- import type { BashTool, ShellToolDeps } from "@better-fs-tools/shell";
2
+ import type { Clock, Digest, ReadStateStore, ReadTool, ReadToolOptions, ToolCallContext } from "@better-fs-tools/read";
3
+ import type { BashTool, BashToolOptions } from "@better-fs-tools/shell";
4
4
  import type { EditTool, ApplyPatchTool, WriteTool } from "../contract/context.ts";
5
- import type { ApplyPatchToolDeps, EditToolDeps, WriteToolDeps } from "../contract/deps.ts";
5
+ import type { ApplyPatchToolOptions, EditToolOptions, WriteToolOptions } from "../contract/deps.ts";
6
6
  import type { LockManager } from "../contract/locks.ts";
7
7
  import type { InvalidateOutcome } from "../state/invalidate.ts";
8
+ /** A read state store, a factory of the call, or null. */
9
+ export type FsToolsState<THost = undefined> = ReadStateStore | ((call: ToolCallContext<THost>) => ReadStateStore | null) | null;
8
10
  /** Options set once for the whole bundle. A tool's own options cannot set them. */
9
11
  export type FsToolsSharedKey = "fs" | "state" | "digest" | "locks" | "clock";
10
12
  /** The bash tool's options, without the digest and clock that the bundle shares. */
11
- export type FsToolsBashOptions<THost = undefined> = Omit<ShellToolDeps<THost>, "digest" | "clock">;
12
- export interface CreateFsToolsOptions<THost = undefined> {
13
+ export type FsToolsBashOptions<THost = undefined> = Omit<BashToolOptions<THost>, "digest" | "clock">;
14
+ /** The read tool's options, without the options that the bundle shares. */
15
+ export type FsToolsReadOptions<THost = undefined> = Omit<Partial<ReadToolOptions<THost>>, FsToolsSharedKey>;
16
+ /** The edit tool's options, without the options that the bundle shares. */
17
+ export type FsToolsEditOptions<THost = undefined> = Omit<Partial<EditToolOptions<THost>>, FsToolsSharedKey>;
18
+ /** The write tool's options, without the options that the bundle shares. */
19
+ export type FsToolsWriteOptions<THost = undefined> = Omit<Partial<WriteToolOptions<THost>>, FsToolsSharedKey>;
20
+ /** The apply_patch tool's options, without the options that the bundle shares. */
21
+ export type FsToolsApplyPatchOptions<THost = undefined> = Omit<Partial<ApplyPatchToolOptions<THost>>, FsToolsSharedKey>;
22
+ export interface FsToolsOptions<THost = undefined> {
13
23
  /** Required. A backend, or a factory called once for each call. */
14
24
  readonly fs: WritableFileSystem | ((call: ToolCallContext<THost>) => WritableFileSystem);
15
- /** Default: an in-memory store on the bundle clock. null turns read-before-write off. */
16
- readonly state?: ReadStateStore | null;
25
+ /**
26
+ * Default null: no read-before-write. A store, for example
27
+ * memoryStore({ clock }), turns it on for edit, write, and apply_patch. A
28
+ * factory gives each call its own store: every tool calls it at most once
29
+ * for each call.
30
+ */
31
+ readonly state?: FsToolsState<THost>;
17
32
  /** Default sha256Digest(). */
18
33
  readonly digest?: Digest;
19
34
  /** Default memoryLocks(), shared by edit, write, and apply_patch. */
20
35
  readonly locks?: LockManager;
21
36
  /** Default () => new Date(). */
22
37
  readonly clock?: Clock;
23
- readonly read?: Omit<Partial<ReadToolDeps<THost>>, FsToolsSharedKey>;
24
- readonly edit?: Omit<Partial<EditToolDeps<THost>>, FsToolsSharedKey>;
25
- readonly write?: Omit<Partial<WriteToolDeps<THost>>, FsToolsSharedKey>;
26
- readonly applyPatch?: Omit<Partial<ApplyPatchToolDeps<THost>>, FsToolsSharedKey>;
38
+ readonly read?: FsToolsReadOptions<THost>;
39
+ readonly edit?: FsToolsEditOptions<THost>;
40
+ readonly write?: FsToolsWriteOptions<THost>;
41
+ /**
42
+ * Off by default. `true` or an options object adds an apply_patch tool.
43
+ * `false` is the same as leaving it out.
44
+ */
45
+ readonly applyPatch?: boolean | FsToolsApplyPatchOptions<THost>;
27
46
  /**
28
47
  * Off by default. The bash tool's options, with `runner` and `env` required.
29
48
  * `false` is the same as leaving it out.
@@ -34,18 +53,19 @@ export interface FsTools<THost = undefined> {
34
53
  readonly read: ReadTool<THost>;
35
54
  readonly edit: EditTool<THost>;
36
55
  readonly write: WriteTool<THost>;
37
- readonly applyPatch: ApplyPatchTool<THost>;
56
+ /** null unless options.applyPatch is true or an object. */
57
+ readonly applyPatch: ApplyPatchTool<THost> | null;
38
58
  /** null unless options.bash is set. It does not share the read state: see invalidate. */
39
59
  readonly bash: BashTool<THost> | null;
40
- readonly fs: CreateFsToolsOptions<THost>["fs"];
41
- readonly state: ReadStateStore | null;
60
+ readonly fs: FsToolsOptions<THost>["fs"];
61
+ readonly state: FsToolsState<THost>;
42
62
  readonly digest: Digest;
43
63
  readonly locks: LockManager;
44
64
  readonly clock: Clock;
45
65
  /**
46
66
  * Deletes the read record for a path, so the next edit or write needs a
47
- * fresh read. Never throws. When fs is a factory, pass the call context (a
48
- * hook has it as ctx.call), or the outcome is ok: false.
67
+ * fresh read. Never throws. When fs or state is a factory, pass the call
68
+ * context (a hook has it as ctx.call), or the outcome is ok: false.
49
69
  */
50
70
  invalidate(path: string, call?: ToolCallContext<THost>): Promise<InvalidateOutcome>;
51
71
  }
@@ -53,10 +73,15 @@ export interface FsTools<THost = undefined> {
53
73
  export interface FsToolsWithBash<THost = undefined> extends FsTools<THost> {
54
74
  readonly bash: BashTool<THost>;
55
75
  }
76
+ /** The result when options.applyPatch is true or an object: applyPatch is there. */
77
+ export interface FsToolsWithApplyPatch<THost = undefined> extends FsTools<THost> {
78
+ readonly applyPatch: ApplyPatchTool<THost>;
79
+ }
56
80
  /**
57
- * Creates read, edit, write, and apply_patch tools over one backend, sharing
58
- * one read store, digest, lock manager, and clock. With `bash`, also a bash
59
- * tool with the same digest and clock. Needs no Node APIs.
81
+ * Creates read, edit, and write tools over one backend, sharing one digest,
82
+ * lock manager, and clock, and the read store when `state` is given. With
83
+ * `applyPatch`, also an apply_patch tool. With `bash`, also a bash tool with
84
+ * the same digest and clock. Needs no Node APIs.
60
85
  *
61
86
  * A bash command is not limited by the backend's roots and does not update the
62
87
  * read state. To make the next edit after a command need a read, call
@@ -65,7 +90,44 @@ export interface FsToolsWithBash<THost = undefined> extends FsTools<THost> {
65
90
  * Throws TypeError on an unknown option, a shared option inside a tool's
66
91
  * options, or anything a tool factory refuses.
67
92
  */
68
- export declare function createFsTools<THost = undefined>(options: CreateFsToolsOptions<THost> & {
93
+ export declare function createFsTools<THost = undefined>(options: FsToolsOptions<THost> & {
94
+ readonly bash: FsToolsBashOptions<THost>;
95
+ readonly applyPatch: true | FsToolsApplyPatchOptions<THost>;
96
+ }): FsToolsWithBash<THost> & FsToolsWithApplyPatch<THost>;
97
+ export declare function createFsTools<THost = undefined>(options: FsToolsOptions<THost> & {
69
98
  readonly bash: FsToolsBashOptions<THost>;
70
99
  }): FsToolsWithBash<THost>;
71
- export declare function createFsTools<THost = undefined>(options: CreateFsToolsOptions<THost>): FsTools<THost>;
100
+ export declare function createFsTools<THost = undefined>(options: FsToolsOptions<THost> & {
101
+ readonly applyPatch: true | FsToolsApplyPatchOptions<THost>;
102
+ }): FsToolsWithApplyPatch<THost>;
103
+ export declare function createFsTools<THost = undefined>(options: FsToolsOptions<THost>): FsTools<THost>;
104
+ /** The option shape that createFsTools() and fsToolDefinitions() share. */
105
+ interface BundleOptions<THost, TApplyPatch, TBash> {
106
+ readonly fs: FsToolsOptions<THost>["fs"];
107
+ readonly state?: FsToolsState<THost>;
108
+ readonly digest?: Digest;
109
+ readonly locks?: LockManager;
110
+ readonly clock?: Clock;
111
+ readonly applyPatch?: boolean | TApplyPatch;
112
+ readonly bash?: false | TBash;
113
+ }
114
+ /** A bundle's shared parts, after the option checks. */
115
+ export interface ResolvedBundle<THost, TApplyPatch, TBash> {
116
+ readonly fs: FsToolsOptions<THost>["fs"];
117
+ readonly state: FsToolsState<THost>;
118
+ readonly digest: Digest;
119
+ readonly locks: LockManager;
120
+ readonly clock: Clock;
121
+ /** The apply_patch options, or null when it is off. */
122
+ readonly applyPatch: Partial<TApplyPatch> | null;
123
+ /** The bash options, or null when it is off. */
124
+ readonly bash: TBash | null;
125
+ readonly invalidate: FsTools<THost>["invalidate"];
126
+ }
127
+ /**
128
+ * Checks the bundle options and resolves the shared defaults. Throws TypeError
129
+ * that names `label` on an unknown key, a shared key inside a tool's options,
130
+ * a malformed state, and bash: true.
131
+ */
132
+ export declare function resolveBundle<THost, TApplyPatch extends object, TBash extends object>(label: string, options: BundleOptions<THost, TApplyPatch, TBash>): ResolvedBundle<THost, TApplyPatch, TBash>;
133
+ export {};