@better-fs-tools/write 0.1.0 → 0.2.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.
- package/README.md +81 -75
- package/dist/bundle/create-fs-tools.d.ts +28 -6
- package/dist/bundle/create-fs-tools.js +9 -4
- package/dist/contract/deps.d.ts +9 -1
- package/dist/contract/messages.d.ts +0 -23
- package/dist/contract/preconditions.d.ts +5 -1
- package/dist/contract/preconditions.js +1 -1
- package/dist/core/commit.d.ts +0 -1
- package/dist/core/commit.js +1 -35
- package/dist/core/deps.js +4 -1
- package/dist/core/format.js +1 -15
- package/dist/core/hooks.js +1 -8
- package/dist/core/load.js +1 -1
- package/dist/core/messages.js +1 -8
- package/dist/core/patch-pipeline.js +1 -2
- package/dist/core/pipeline.js +2 -2
- package/dist/core/plan-edit.d.ts +2 -0
- package/dist/core/plan-edit.js +3 -3
- package/dist/core/precondition.js +2 -13
- package/dist/formatters/default.d.ts +7 -1
- package/dist/formatters/default.js +23 -5
- package/dist/guards/index.d.ts +9 -3
- package/dist/guards/index.js +11 -3
- package/dist/guards/non-text.d.ts +5 -1
- package/dist/guards/non-text.js +5 -1
- package/dist/index.d.ts +2 -2
- package/dist/index.js +1 -1
- package/dist/matchers/index.d.ts +4 -1
- package/dist/matchers/index.js +5 -3
- package/docs/architecture.md +8 -6
- package/docs/hosts.md +4 -3
- package/docs/result-schema.md +19 -26
- 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,
|
|
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,41 +18,43 @@ 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
|
|
21
|
+
`createFsTools({ fs })` builds `read`, `edit`, and `write` 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()`:
|
|
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,
|
|
31
|
-
|
|
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`,
|
|
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` (one store, not a per-call factory; 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` is a factory, pass the call context, for example `ctx.call` in a bash `afterRun` hook.
|
|
56
58
|
|
|
57
59
|
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.
|
|
58
60
|
|
|
@@ -66,7 +68,7 @@ An unknown option key, a shared key (`fs`, `state`, `digest`, `locks`, or `clock
|
|
|
66
68
|
| 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 |
|
|
67
69
|
| 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
70
|
|
|
69
|
-
The standalone factories (`createNodeEditTool()`, `createAiSdkEditTool()`, `createPiEditTool()`, and the others) default to `state: null`.
|
|
71
|
+
The bundles and the standalone factories (`createNodeEditTool()`, `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()`, `createNodeFsTools()`, `createPiFsTools()`, or `createAiSdkFsTools()`), or pass the same `state`, `digest`, and `locks` to the read tool and the write tools.
|
|
70
72
|
|
|
71
73
|
[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.
|
|
72
74
|
|
|
@@ -74,9 +76,11 @@ The standalone factories (`createNodeEditTool()`, `createAiSdkEditTool()`, `crea
|
|
|
74
76
|
|
|
75
77
|
`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
78
|
|
|
77
|
-
Matching tries `exactMatcher()` first, then `normalizedMatcher()` (trailing whitespace, Unicode normalization, curly quotes, dashes, and special spaces)
|
|
79
|
+
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. `escapeMatcher()` (escape sequences written out), `lineTrimmedMatcher()`, `indentationMatcher()`, and `blockAnchorMatcher()` are opt-in through the `matchers` dependency, for example `matchers: [...defaultEditMatchers(), escapeMatcher()]`.
|
|
80
|
+
|
|
81
|
+
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
82
|
|
|
79
|
-
|
|
83
|
+
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
84
|
|
|
81
85
|
## write
|
|
82
86
|
|
|
@@ -131,52 +135,53 @@ The commit stages every new file when the backend has `stage()`, then publishes
|
|
|
131
135
|
With the read tool's `state` store and a `digest`, the write tools check what the model has seen:
|
|
132
136
|
|
|
133
137
|
- 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
|
|
138
|
+
- 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
139
|
- On a backend with stable identity, the check compares the backend `version`. On every other backend it compares the content hash.
|
|
136
140
|
- 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
141
|
- `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
142
|
- `preconditions: { requireRead: "off" }` turns the check off. `partialRead` and `onStale` change the other two rules.
|
|
139
143
|
|
|
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,
|
|
144
|
+
`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. The result has no note about this, because the model cannot change the host's setup.
|
|
141
145
|
|
|
142
146
|
## Dependencies
|
|
143
147
|
|
|
144
148
|
Every dependency except `fs` has a default. Pass them to `createEditTool()`, `createWriteTool()`, or `createApplyPatchTool()`, or to a host factory.
|
|
145
149
|
|
|
146
|
-
| Dependency | Default
|
|
147
|
-
| --------------- |
|
|
148
|
-
| `fs` | required
|
|
149
|
-
| `state` | `null`
|
|
150
|
-
| `digest` | `null`
|
|
151
|
-
| `locks` | `memoryLocks()`
|
|
152
|
-
| `resolve` | `null`
|
|
153
|
-
| `authorize` | `null`
|
|
154
|
-
| `guards` | `
|
|
155
|
-
| `hooks` | `[]`
|
|
156
|
-
| `matchers` | edit: `defaultEditMatchers()`; patch: `defaultPatchMatchers()`
|
|
157
|
-
| `
|
|
158
|
-
| `
|
|
159
|
-
| `
|
|
160
|
-
| `
|
|
161
|
-
| `
|
|
162
|
-
| `
|
|
163
|
-
| `
|
|
164
|
-
| `
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
|
168
|
-
|
|
|
169
|
-
| `
|
|
170
|
-
| `
|
|
171
|
-
| `
|
|
172
|
-
| `
|
|
173
|
-
| `
|
|
174
|
-
| `
|
|
175
|
-
| `
|
|
176
|
-
| `
|
|
177
|
-
| `
|
|
178
|
-
| `
|
|
179
|
-
| `
|
|
150
|
+
| Dependency | Default | Meaning |
|
|
151
|
+
| --------------- | -------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------- |
|
|
152
|
+
| `fs` | required | A `WritableFileSystem`, or a factory of the call context that runs once for each call |
|
|
153
|
+
| `state` | `null` | The read tool's store, or a factory. Needs `digest` |
|
|
154
|
+
| `digest` | `null` | Content hashes for records and `changes[].after.contentId` |
|
|
155
|
+
| `locks` | `memoryLocks()` | Orders writers to one path inside the process. Share one across the three tools. `timeoutMs` default 30 s |
|
|
156
|
+
| `resolve` | `null` | A read `PathResolver`, for example `unicodeRepair()` |
|
|
157
|
+
| `authorize` | `null` | A `WriteAuthorizer`, or a read `ToolAuthorizer` such as `denyPaths()` |
|
|
158
|
+
| `guards` | `[]` | Checks on each planned change. `recommendedGuards()` gives the five this package recommends |
|
|
159
|
+
| `hooks` | `[]` | Run after each committed file |
|
|
160
|
+
| `matchers` | edit: `defaultEditMatchers()`; patch: `defaultPatchMatchers()` | The match chain, in order |
|
|
161
|
+
| `recovery` | `false` | `edit` only. `true` adds the closest-region hint, `already-applied`, and the `repeated-miss` note |
|
|
162
|
+
| `preconditions` | `{ requireRead: "existing", partialRead: "edit-only", onStale: "reject" }` | Read-before-write rules |
|
|
163
|
+
| `limits` | `defaultWriteLimits` | See below |
|
|
164
|
+
| `messages` | `defaultWriteMessages` | Every model-facing text. Merged key by key |
|
|
165
|
+
| `formatter` | `defaultWriteFormatter()` | Turns the report into content parts. `{ snippet: true }` adds edit snippets, `{ diff: true }` the diff |
|
|
166
|
+
| `classifiers` | the read tool's default classifiers | Refuse a target that is not text before it is decoded |
|
|
167
|
+
| `codecs` | `[utf8Codec()]` | Decode and encode. `utf8Codec` keeps a BOM, CRLF, and mixed line endings |
|
|
168
|
+
| `clock` | `() => new Date()` | Record times |
|
|
169
|
+
| `patchParser` | `codexPatchParser()` | `apply_patch` only |
|
|
170
|
+
|
|
171
|
+
| Limit | Default | Meaning |
|
|
172
|
+
| ------------------ | ------- | ------------------------------------------------------------------------------------------------------------- |
|
|
173
|
+
| `maxFileBytes` | 8 MiB | Bytes of an existing file that any tool loads |
|
|
174
|
+
| `maxWriteBytes` | 8 MiB | Encoded bytes of new content for one file |
|
|
175
|
+
| `maxPatchBytes` | 4 MiB | UTF-8 bytes of patch text |
|
|
176
|
+
| `maxPatchFiles` | 100 | Operations in one patch |
|
|
177
|
+
| `maxEdits` | 100 | Pairs in one edit call |
|
|
178
|
+
| `sampleBytes` | 8 192 | Bytes given to the classifiers and codecs |
|
|
179
|
+
| `snippetLines` | 3 | Context lines around each change in a snippet. The default formatter shows snippets only with `snippet: true` |
|
|
180
|
+
| `maxSnippetLines` | 40 | Snippet lines for one file in the model text |
|
|
181
|
+
| `maxDiffLines` | 2 000 | Lines of unified diff kept in `changes[].diff` |
|
|
182
|
+
| `maxHintLines` | 12 | Lines in a closest-region hint (`recovery: true`) |
|
|
183
|
+
| `maxListedMatches` | 10 | Line numbers listed for an ambiguous match |
|
|
184
|
+
| `maxPatchProblems` | 20 | Problems listed for a failed patch verify |
|
|
180
185
|
|
|
181
186
|
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
187
|
|
|
@@ -224,7 +229,7 @@ An authorizer may allow with `content` for `edit` and `write`. The tool then wri
|
|
|
224
229
|
|
|
225
230
|
## Guards and hooks
|
|
226
231
|
|
|
227
|
-
Guards check each planned change before anything is written. `
|
|
232
|
+
Guards check each planned change before anything is written. No guard runs by default. `recommendedGuards()` gives the five this package recommends, and the `guards` dependency 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
233
|
|
|
229
234
|
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
235
|
|
|
@@ -233,9 +238,9 @@ import { memoryFileSystem } from "@better-fs-tools/fs";
|
|
|
233
238
|
import { textOf } from "@better-fs-tools/read";
|
|
234
239
|
import {
|
|
235
240
|
createWriteTool,
|
|
236
|
-
defaultGuards,
|
|
237
241
|
executableShebang,
|
|
238
242
|
generatedFileGuard,
|
|
243
|
+
recommendedGuards,
|
|
239
244
|
syntaxGuard,
|
|
240
245
|
verifyWrite,
|
|
241
246
|
} from "@better-fs-tools/write";
|
|
@@ -271,9 +276,10 @@ const logChanges: WriteHook<unknown> = {
|
|
|
271
276
|
|
|
272
277
|
const write = createWriteTool({
|
|
273
278
|
fs: memoryFileSystem({ directories: ["/repo"] }),
|
|
274
|
-
//
|
|
279
|
+
// No guards run by default. recommendedGuards() gives the five this
|
|
280
|
+
// package recommends. Passing guards replaces the whole list.
|
|
275
281
|
guards: [
|
|
276
|
-
...
|
|
282
|
+
...recommendedGuards().filter((guard) => guard.id !== "syntax"),
|
|
277
283
|
syntaxGuard({ parsers: { yaml: (text) => void text } }),
|
|
278
284
|
generatedFileGuard(),
|
|
279
285
|
noTabsInYaml,
|
|
@@ -366,26 +372,26 @@ if (result.status === "error") {
|
|
|
366
372
|
} else {
|
|
367
373
|
for (const change of result.changes) {
|
|
368
374
|
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
|
|
375
|
+
console.log(change.diff); // The full unified diff. The model text has only a summary line.
|
|
370
376
|
console.log(change.after?.version); // The backend version after the commit
|
|
371
377
|
}
|
|
372
378
|
}
|
|
373
|
-
//
|
|
374
|
-
console.log(result.notes.map((note) => note.code)); // [
|
|
379
|
+
// Notes for the model, such as fuzzy-match. This plain update has none.
|
|
380
|
+
console.log(result.notes.map((note) => note.code)); // []
|
|
375
381
|
console.log(textOf(result)); // What the model sees
|
|
376
382
|
```
|
|
377
383
|
|
|
378
384
|
## Backends
|
|
379
385
|
|
|
380
|
-
The core
|
|
386
|
+
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
387
|
|
|
382
|
-
| Backend | `
|
|
383
|
-
| -------------------------------- |
|
|
384
|
-
| `memoryFileSystem()` | yes
|
|
385
|
-
| `nodeFileSystem()` | yes
|
|
386
|
-
| `cloudflareShellFileSystem()` | no
|
|
387
|
-
| `cloudflareComputerFileSystem()` |
|
|
388
|
-
| `justBashFileSystem()` | no
|
|
388
|
+
| Backend | `compareAndSwap` | Atomic replace | Keeps the mode | `stage()` | `remove()` |
|
|
389
|
+
| -------------------------------- | ------------------- | -------------- | -------------- | --------- | ---------- |
|
|
390
|
+
| `memoryFileSystem()` | yes | yes | yes | yes | yes |
|
|
391
|
+
| `nodeFileSystem()` | yes, in one process | yes | yes | yes | yes |
|
|
392
|
+
| `cloudflareShellFileSystem()` | no | no | no modes | no | yes |
|
|
393
|
+
| `cloudflareComputerFileSystem()` | no | yes | yes | no | yes |
|
|
394
|
+
| `justBashFileSystem()` | no | no | yes | no | yes |
|
|
389
395
|
|
|
390
396
|
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
397
|
|
|
@@ -393,18 +399,18 @@ Without compare-and-swap, the core checks the version with a fresh `stat` just b
|
|
|
393
399
|
|
|
394
400
|
- `apply_patch` rollback lives in process memory. A crash or a killed process during the commit leaves some files changed and no report.
|
|
395
401
|
- Undoing a create removes the file but leaves the parent folders the create made.
|
|
396
|
-
-
|
|
402
|
+
- 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
403
|
- 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
404
|
- `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
405
|
- 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.
|
|
400
406
|
|
|
401
407
|
## Entries
|
|
402
408
|
|
|
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 `
|
|
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`
|
|
409
|
+
| Entry | Contents |
|
|
410
|
+
| ---------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
411
|
+
| `@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` |
|
|
412
|
+
| `@better-fs-tools/write/patch` | `parsePatch`, `codexPatchParser`, `CODEX_PATCH_GRAMMAR`, and the patch types. The only home of these |
|
|
413
|
+
| `@better-fs-tools/write/signature` | `defaultEditSignature`, `multiEditSignature`, `camelCaseEditSignature`, `defaultWriteSignature`, `snakeCaseWriteSignature`, `defaultPatchSignature`, `freeformPatchSignature`, and `writeSignatureMessages` |
|
|
408
414
|
|
|
409
415
|
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
416
|
|
|
@@ -9,10 +9,15 @@ import type { InvalidateOutcome } from "../state/invalidate.ts";
|
|
|
9
9
|
export type FsToolsSharedKey = "fs" | "state" | "digest" | "locks" | "clock";
|
|
10
10
|
/** The bash tool's options, without the digest and clock that the bundle shares. */
|
|
11
11
|
export type FsToolsBashOptions<THost = undefined> = Omit<ShellToolDeps<THost>, "digest" | "clock">;
|
|
12
|
+
/** The apply_patch tool's options, without the options that the bundle shares. */
|
|
13
|
+
export type FsToolsApplyPatchOptions<THost = undefined> = Omit<Partial<ApplyPatchToolDeps<THost>>, FsToolsSharedKey>;
|
|
12
14
|
export interface CreateFsToolsOptions<THost = undefined> {
|
|
13
15
|
/** Required. A backend, or a factory called once for each call. */
|
|
14
16
|
readonly fs: WritableFileSystem | ((call: ToolCallContext<THost>) => WritableFileSystem);
|
|
15
|
-
/**
|
|
17
|
+
/**
|
|
18
|
+
* Default null: no read-before-write. A store, for example
|
|
19
|
+
* memoryStore({ clock }), turns it on for edit, write, and apply_patch.
|
|
20
|
+
*/
|
|
16
21
|
readonly state?: ReadStateStore | null;
|
|
17
22
|
/** Default sha256Digest(). */
|
|
18
23
|
readonly digest?: Digest;
|
|
@@ -23,7 +28,11 @@ export interface CreateFsToolsOptions<THost = undefined> {
|
|
|
23
28
|
readonly read?: Omit<Partial<ReadToolDeps<THost>>, FsToolsSharedKey>;
|
|
24
29
|
readonly edit?: Omit<Partial<EditToolDeps<THost>>, FsToolsSharedKey>;
|
|
25
30
|
readonly write?: Omit<Partial<WriteToolDeps<THost>>, FsToolsSharedKey>;
|
|
26
|
-
|
|
31
|
+
/**
|
|
32
|
+
* Off by default. `true` or an options object adds an apply_patch tool.
|
|
33
|
+
* `false` is the same as leaving it out.
|
|
34
|
+
*/
|
|
35
|
+
readonly applyPatch?: boolean | FsToolsApplyPatchOptions<THost>;
|
|
27
36
|
/**
|
|
28
37
|
* Off by default. The bash tool's options, with `runner` and `env` required.
|
|
29
38
|
* `false` is the same as leaving it out.
|
|
@@ -34,7 +43,8 @@ export interface FsTools<THost = undefined> {
|
|
|
34
43
|
readonly read: ReadTool<THost>;
|
|
35
44
|
readonly edit: EditTool<THost>;
|
|
36
45
|
readonly write: WriteTool<THost>;
|
|
37
|
-
|
|
46
|
+
/** null unless options.applyPatch is true or an object. */
|
|
47
|
+
readonly applyPatch: ApplyPatchTool<THost> | null;
|
|
38
48
|
/** null unless options.bash is set. It does not share the read state: see invalidate. */
|
|
39
49
|
readonly bash: BashTool<THost> | null;
|
|
40
50
|
readonly fs: CreateFsToolsOptions<THost>["fs"];
|
|
@@ -53,10 +63,15 @@ export interface FsTools<THost = undefined> {
|
|
|
53
63
|
export interface FsToolsWithBash<THost = undefined> extends FsTools<THost> {
|
|
54
64
|
readonly bash: BashTool<THost>;
|
|
55
65
|
}
|
|
66
|
+
/** The result when options.applyPatch is true or an object: applyPatch is there. */
|
|
67
|
+
export interface FsToolsWithApplyPatch<THost = undefined> extends FsTools<THost> {
|
|
68
|
+
readonly applyPatch: ApplyPatchTool<THost>;
|
|
69
|
+
}
|
|
56
70
|
/**
|
|
57
|
-
* Creates read, edit,
|
|
58
|
-
*
|
|
59
|
-
*
|
|
71
|
+
* Creates read, edit, and write tools over one backend, sharing one digest,
|
|
72
|
+
* lock manager, and clock, and the read store when `state` is given. With
|
|
73
|
+
* `applyPatch`, also an apply_patch tool. With `bash`, also a bash tool with
|
|
74
|
+
* the same digest and clock. Needs no Node APIs.
|
|
60
75
|
*
|
|
61
76
|
* A bash command is not limited by the backend's roots and does not update the
|
|
62
77
|
* read state. To make the next edit after a command need a read, call
|
|
@@ -65,7 +80,14 @@ export interface FsToolsWithBash<THost = undefined> extends FsTools<THost> {
|
|
|
65
80
|
* Throws TypeError on an unknown option, a shared option inside a tool's
|
|
66
81
|
* options, or anything a tool factory refuses.
|
|
67
82
|
*/
|
|
83
|
+
export declare function createFsTools<THost = undefined>(options: CreateFsToolsOptions<THost> & {
|
|
84
|
+
readonly bash: FsToolsBashOptions<THost>;
|
|
85
|
+
readonly applyPatch: true | FsToolsApplyPatchOptions<THost>;
|
|
86
|
+
}): FsToolsWithBash<THost> & FsToolsWithApplyPatch<THost>;
|
|
68
87
|
export declare function createFsTools<THost = undefined>(options: CreateFsToolsOptions<THost> & {
|
|
69
88
|
readonly bash: FsToolsBashOptions<THost>;
|
|
70
89
|
}): FsToolsWithBash<THost>;
|
|
90
|
+
export declare function createFsTools<THost = undefined>(options: CreateFsToolsOptions<THost> & {
|
|
91
|
+
readonly applyPatch: true | FsToolsApplyPatchOptions<THost>;
|
|
92
|
+
}): FsToolsWithApplyPatch<THost>;
|
|
71
93
|
export declare function createFsTools<THost = undefined>(options: CreateFsToolsOptions<THost>): FsTools<THost>;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { createReadTool,
|
|
1
|
+
import { createReadTool, sha256Digest } from "@better-fs-tools/read";
|
|
2
2
|
import { createBashTool } from "@better-fs-tools/shell";
|
|
3
3
|
import { createApplyPatchTool, createEditTool, createWriteTool } from "../core/create-tools.js";
|
|
4
4
|
import { isWritable } from "../core/deps.js";
|
|
@@ -33,10 +33,11 @@ export function createFsTools(options) {
|
|
|
33
33
|
checkFsToolsOptions("createFsTools", options, KNOWN_OPTION_KEYS, SHARED_KEYS_BY_TOOL);
|
|
34
34
|
const { fs } = options;
|
|
35
35
|
const clock = options.clock ?? (() => new Date());
|
|
36
|
-
const state = options.state
|
|
36
|
+
const state = options.state ?? null;
|
|
37
37
|
const digest = options.digest ?? sha256Digest();
|
|
38
38
|
const locks = options.locks ?? memoryLocks();
|
|
39
39
|
const shared = { fs, state, digest, clock };
|
|
40
|
+
const applyPatch = options.applyPatch === true ? {} : (options.applyPatch ?? false);
|
|
40
41
|
const bash = options.bash === undefined || options.bash === false ? null : options.bash;
|
|
41
42
|
if (bash === true) {
|
|
42
43
|
throw new TypeError("createFsTools bash must be an object with a runner and an env: the portable bundle has no default runner");
|
|
@@ -45,7 +46,9 @@ export function createFsTools(options) {
|
|
|
45
46
|
read: createReadTool({ ...options.read, ...shared }),
|
|
46
47
|
edit: createEditTool({ ...options.edit, ...shared, locks }),
|
|
47
48
|
write: createWriteTool({ ...options.write, ...shared, locks }),
|
|
48
|
-
applyPatch:
|
|
49
|
+
applyPatch: applyPatch === false
|
|
50
|
+
? null
|
|
51
|
+
: createApplyPatchTool({ ...applyPatch, ...shared, locks }),
|
|
49
52
|
bash: bash === null ? null : createBashTool({ ...bash, digest, clock }),
|
|
50
53
|
fs,
|
|
51
54
|
state,
|
|
@@ -69,7 +72,9 @@ function checkFsToolsOptions(label, options, known, sharedKeys) {
|
|
|
69
72
|
}
|
|
70
73
|
for (const [tool, keys] of Object.entries(sharedKeys)) {
|
|
71
74
|
const part = options[tool];
|
|
72
|
-
if (part === undefined
|
|
75
|
+
if (part === undefined)
|
|
76
|
+
continue;
|
|
77
|
+
if ((tool === "bash" || tool === "applyPatch") && typeof part === "boolean")
|
|
73
78
|
continue;
|
|
74
79
|
if (part === null || typeof part !== "object" || Array.isArray(part)) {
|
|
75
80
|
throw new TypeError(`${label} ${tool} options must be an object`);
|
package/dist/contract/deps.d.ts
CHANGED
|
@@ -29,7 +29,7 @@ export interface WriteDependencies<THost = undefined> {
|
|
|
29
29
|
readonly classifiers: readonly Classifier[];
|
|
30
30
|
/** The first codec that accepts a file decodes it. Non-empty. */
|
|
31
31
|
readonly codecs: readonly Codec[];
|
|
32
|
-
/** Default
|
|
32
|
+
/** Default none. recommendedGuards() gives the guards this package recommends. */
|
|
33
33
|
readonly guards: readonly Guard<THost>[];
|
|
34
34
|
readonly hooks: readonly WriteHook<THost>[];
|
|
35
35
|
readonly formatter: WriteFormatter<THost>;
|
|
@@ -37,6 +37,14 @@ export interface WriteDependencies<THost = undefined> {
|
|
|
37
37
|
export interface EditDependencies<THost = undefined> extends WriteDependencies<THost> {
|
|
38
38
|
/** Ordered. Non-empty. */
|
|
39
39
|
readonly matchers: readonly Matcher[];
|
|
40
|
+
/**
|
|
41
|
+
* Help after a miss. true turns on three extras: a pair whose new text is
|
|
42
|
+
* already in the file and whose old text is not is `already-applied`; a
|
|
43
|
+
* NO_MATCH error shows the closest region of the file; and the third miss
|
|
44
|
+
* in a row on one file adds a `repeated-miss` note. Default false: a miss
|
|
45
|
+
* is a plain NO_MATCH.
|
|
46
|
+
*/
|
|
47
|
+
readonly recovery: boolean;
|
|
40
48
|
}
|
|
41
49
|
export interface ApplyPatchDependencies<THost = undefined> extends WriteDependencies<THost> {
|
|
42
50
|
/** Ordered. Used to find hunk lines. Non-empty. */
|
|
@@ -77,9 +77,6 @@ export interface WriteMessageCatalog extends ToolMessages {
|
|
|
77
77
|
staleRematched(c: {
|
|
78
78
|
path: string;
|
|
79
79
|
}): string;
|
|
80
|
-
readBeforeWriteOff(c: {
|
|
81
|
-
tool: WriteToolName;
|
|
82
|
-
}): string;
|
|
83
80
|
/** `existing` is true when `what` is "content" and the file exists. */
|
|
84
81
|
tooLarge(c: {
|
|
85
82
|
path: string | null;
|
|
@@ -181,18 +178,6 @@ export interface WriteMessageCatalog extends ToolMessages {
|
|
|
181
178
|
readonly state: string;
|
|
182
179
|
}[];
|
|
183
180
|
}): string;
|
|
184
|
-
notAtomic(c: {
|
|
185
|
-
backend: string;
|
|
186
|
-
}): string;
|
|
187
|
-
noCompareAndSwap(c: {
|
|
188
|
-
backend: string;
|
|
189
|
-
}): string;
|
|
190
|
-
modeNotKept(c: {
|
|
191
|
-
backend: string;
|
|
192
|
-
}): string;
|
|
193
|
-
directoriesCreated(c: {
|
|
194
|
-
paths: readonly string[];
|
|
195
|
-
}): string;
|
|
196
181
|
userModified(c: {
|
|
197
182
|
path: string;
|
|
198
183
|
}): string;
|
|
@@ -200,12 +185,4 @@ export interface WriteMessageCatalog extends ToolMessages {
|
|
|
200
185
|
hook: string;
|
|
201
186
|
path: string;
|
|
202
187
|
}): string;
|
|
203
|
-
hookFailed(c: {
|
|
204
|
-
hook: string;
|
|
205
|
-
path: string;
|
|
206
|
-
}): string;
|
|
207
|
-
/** The formatter threw or returned neither a string nor an array. */
|
|
208
|
-
formatterFailed(c: {
|
|
209
|
-
formatter: string;
|
|
210
|
-
}): string;
|
|
211
188
|
}
|
|
@@ -3,7 +3,11 @@ export interface PreconditionPolicy {
|
|
|
3
3
|
readonly requireRead: "existing" | "off";
|
|
4
4
|
/** Which tools accept a record with wholeFileVisible false. "edit-only" means edit and apply_patch. Default "edit-only". */
|
|
5
5
|
readonly partialRead: "edit-only" | "always" | "never";
|
|
6
|
-
/**
|
|
6
|
+
/**
|
|
7
|
+
* edit and apply_patch on a stale record. "reject" fails with STALE.
|
|
8
|
+
* "rematch" tries the old text again on the new content. write always
|
|
9
|
+
* rejects. Default "reject".
|
|
10
|
+
*/
|
|
7
11
|
readonly onStale: "rematch" | "reject";
|
|
8
12
|
}
|
|
9
13
|
export declare const defaultPreconditions: Readonly<PreconditionPolicy>;
|
package/dist/core/commit.d.ts
CHANGED
|
@@ -4,6 +4,5 @@ import type { Planned, ResolvedTarget } from "./planned.ts";
|
|
|
4
4
|
import type { MutationScope } from "./scope.ts";
|
|
5
5
|
export declare function commitOne<THost>(scope: MutationScope<THost>, fs: WritableFileSystem, planned: Planned, bytes: Uint8Array): Promise<MutatedFile>;
|
|
6
6
|
export declare function checkBeforeCommit<THost>(scope: MutationScope<THost>, fs: WritableFileSystem, target: ResolvedTarget, precondition: Precondition): Promise<void>;
|
|
7
|
-
export declare function addCapabilityNotes<THost>(scope: MutationScope<THost>, fs: WritableFileSystem, planned: Planned, file: MutatedFile): void;
|
|
8
7
|
export declare function fileChange<THost>(scope: MutationScope<THost>, planned: Planned, bytes: Uint8Array, file: MutatedFile): FileChange;
|
|
9
8
|
export declare function isMutatedFile(value: unknown): value is MutatedFile;
|
package/dist/core/commit.js
CHANGED
|
@@ -29,7 +29,6 @@ export async function commitOne(scope, fs, planned, bytes) {
|
|
|
29
29
|
if (!isRecord(outcome) || outcome.ok !== true || !isMutatedFile(outcome.file)) {
|
|
30
30
|
throw ioFailure(scope, target.requestedPath, "malformed write outcome");
|
|
31
31
|
}
|
|
32
|
-
addCapabilityNotes(scope, fs, planned, outcome.file);
|
|
33
32
|
return outcome.file;
|
|
34
33
|
}
|
|
35
34
|
export async function checkBeforeCommit(scope, fs, target, precondition) {
|
|
@@ -43,38 +42,6 @@ export async function checkBeforeCommit(scope, fs, target, precondition) {
|
|
|
43
42
|
throw scope.stop("STALE", messages.stale({ tool: scope.tool, path }));
|
|
44
43
|
}
|
|
45
44
|
}
|
|
46
|
-
export function addCapabilityNotes(scope, fs, planned, file) {
|
|
47
|
-
const { messages } = scope.deps;
|
|
48
|
-
const capabilities = fs.writeCapabilities;
|
|
49
|
-
const backend = fs.id;
|
|
50
|
-
const add = (note) => {
|
|
51
|
-
if (!scope.notes.some((existing) => existing.code === note.code))
|
|
52
|
-
scope.notes.push(note);
|
|
53
|
-
};
|
|
54
|
-
if (!capabilities.atomic || !file.atomic) {
|
|
55
|
-
add({ code: "not-atomic", severity: "warning", message: messages.notAtomic({ backend }) });
|
|
56
|
-
}
|
|
57
|
-
if (!capabilities.compareAndSwap) {
|
|
58
|
-
add({
|
|
59
|
-
code: "no-compare-and-swap",
|
|
60
|
-
severity: "info",
|
|
61
|
-
message: messages.noCompareAndSwap({ backend }),
|
|
62
|
-
});
|
|
63
|
-
}
|
|
64
|
-
const replacesExistingFile = planned.precondition.kind !== "absent";
|
|
65
|
-
if (!capabilities.preserveMode && replacesExistingFile) {
|
|
66
|
-
add({ code: "mode-not-kept", severity: "info", message: messages.modeNotKept({ backend }) });
|
|
67
|
-
}
|
|
68
|
-
if (file.createdDirectories.length > 0) {
|
|
69
|
-
const paths = file.createdDirectories;
|
|
70
|
-
scope.notes.push({
|
|
71
|
-
code: "directories-created",
|
|
72
|
-
severity: "info",
|
|
73
|
-
message: messages.directoriesCreated({ paths }),
|
|
74
|
-
data: { paths: [...paths] },
|
|
75
|
-
});
|
|
76
|
-
}
|
|
77
|
-
}
|
|
78
45
|
export function fileChange(scope, planned, bytes, file) {
|
|
79
46
|
const { change, loaded, target } = planned;
|
|
80
47
|
const { digest } = scope.deps;
|
|
@@ -106,6 +73,5 @@ export function isMutatedFile(value) {
|
|
|
106
73
|
return (isRecord(value) &&
|
|
107
74
|
typeof value.resolvedPath === "string" &&
|
|
108
75
|
(value.version === null || typeof value.version === "string") &&
|
|
109
|
-
Array.isArray(value.createdDirectories)
|
|
110
|
-
typeof value.atomic === "boolean");
|
|
76
|
+
Array.isArray(value.createdDirectories));
|
|
111
77
|
}
|
package/dist/core/deps.js
CHANGED
|
@@ -106,13 +106,16 @@ export function resolveWriteDependencies(deps, tool) {
|
|
|
106
106
|
export function resolveEditDependencies(deps) {
|
|
107
107
|
if (!isRecord(deps))
|
|
108
108
|
throw new TypeError("edit tool dependencies must be an object");
|
|
109
|
-
const { matchers = defaultEditMatchers(), ...shared } = deps;
|
|
109
|
+
const { matchers = defaultEditMatchers(), recovery = false, ...shared } = deps;
|
|
110
110
|
if (!Array.isArray(matchers) || matchers.length === 0 || !matchers.every(isMatcher)) {
|
|
111
111
|
throw new TypeError("matchers must be a non-empty array of matchers");
|
|
112
112
|
}
|
|
113
|
+
if (typeof recovery !== "boolean")
|
|
114
|
+
throw new TypeError("recovery must be a boolean");
|
|
113
115
|
return Object.freeze({
|
|
114
116
|
...resolveWriteDependencies(shared, "edit"),
|
|
115
117
|
matchers: Object.freeze([...matchers]),
|
|
118
|
+
recovery,
|
|
116
119
|
});
|
|
117
120
|
}
|
|
118
121
|
export function resolveApplyPatchDependencies(deps) {
|