@better-fs-tools/write 0.0.0-tegami-trusted-publish-setup → 0.1.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/LICENSE +21 -0
- package/README.md +443 -6
- package/dist/authorize/ask-before-write.d.ts +11 -0
- package/dist/authorize/ask-before-write.js +49 -0
- package/dist/authorize/index.d.ts +3 -0
- package/dist/authorize/index.js +3 -0
- package/dist/authorize/protect-paths.d.ts +12 -0
- package/dist/authorize/protect-paths.js +74 -0
- package/dist/authorize/write-authorizers.d.ts +9 -0
- package/dist/authorize/write-authorizers.js +48 -0
- package/dist/bundle/create-fs-tools.d.ts +71 -0
- package/dist/bundle/create-fs-tools.js +125 -0
- package/dist/codecs/index.d.ts +1 -0
- package/dist/codecs/index.js +1 -0
- package/dist/codecs/utf8.d.ts +7 -0
- package/dist/codecs/utf8.js +61 -0
- package/dist/contract/codec.d.ts +26 -0
- package/dist/contract/codec.js +0 -0
- package/dist/contract/context.d.ts +14 -0
- package/dist/contract/context.js +0 -0
- package/dist/contract/deps.d.ts +55 -0
- package/dist/contract/deps.js +0 -0
- package/dist/contract/extensions.d.ts +103 -0
- package/dist/contract/extensions.js +0 -0
- package/dist/contract/format.d.ts +15 -0
- package/dist/contract/format.js +0 -0
- package/dist/contract/input.d.ts +35 -0
- package/dist/contract/input.js +0 -0
- package/dist/contract/limits.d.ts +26 -0
- package/dist/contract/limits.js +0 -0
- package/dist/contract/locks.d.ts +14 -0
- package/dist/contract/locks.js +0 -0
- package/dist/contract/matcher.d.ts +30 -0
- package/dist/contract/matcher.js +0 -0
- package/dist/contract/messages.d.ts +211 -0
- package/dist/contract/messages.js +0 -0
- package/dist/contract/patch.d.ts +50 -0
- package/dist/contract/patch.js +0 -0
- package/dist/contract/preconditions.d.ts +9 -0
- package/dist/contract/preconditions.js +5 -0
- package/dist/contract/result.d.ts +102 -0
- package/dist/contract/result.js +0 -0
- package/dist/core/abort.d.ts +4 -0
- package/dist/core/abort.js +23 -0
- package/dist/core/authorize.d.ts +9 -0
- package/dist/core/authorize.js +87 -0
- package/dist/core/bytes.d.ts +3 -0
- package/dist/core/bytes.js +14 -0
- package/dist/core/commit-patch.d.ts +20 -0
- package/dist/core/commit-patch.js +224 -0
- package/dist/core/commit.d.ts +9 -0
- package/dist/core/commit.js +111 -0
- package/dist/core/create-tools.d.ts +23 -0
- package/dist/core/create-tools.js +54 -0
- package/dist/core/deps.d.ts +11 -0
- package/dist/core/deps.js +207 -0
- package/dist/core/diff.d.ts +10 -0
- package/dist/core/diff.js +221 -0
- package/dist/core/encode.d.ts +3 -0
- package/dist/core/encode.js +26 -0
- package/dist/core/extension-error.d.ts +8 -0
- package/dist/core/extension-error.js +17 -0
- package/dist/core/format.d.ts +4 -0
- package/dist/core/format.js +36 -0
- package/dist/core/guards.d.ts +3 -0
- package/dist/core/guards.js +45 -0
- package/dist/core/hints.d.ts +14 -0
- package/dist/core/hints.js +75 -0
- package/dist/core/hooks.d.ts +15 -0
- package/dist/core/hooks.js +115 -0
- package/dist/core/input.d.ts +20 -0
- package/dist/core/input.js +91 -0
- package/dist/core/limits.d.ts +10 -0
- package/dist/core/limits.js +48 -0
- package/dist/core/line-index.d.ts +10 -0
- package/dist/core/line-index.js +38 -0
- package/dist/core/load.d.ts +14 -0
- package/dist/core/load.js +221 -0
- package/dist/core/lock.d.ts +2 -0
- package/dist/core/lock.js +56 -0
- package/dist/core/match.d.ts +15 -0
- package/dist/core/match.js +66 -0
- package/dist/core/messages.d.ts +8 -0
- package/dist/core/messages.js +147 -0
- package/dist/core/outcomes.d.ts +21 -0
- package/dist/core/outcomes.js +127 -0
- package/dist/core/parse-patch.d.ts +3 -0
- package/dist/core/parse-patch.js +64 -0
- package/dist/core/patch-hunks.d.ts +25 -0
- package/dist/core/patch-hunks.js +177 -0
- package/dist/core/patch-pipeline.d.ts +4 -0
- package/dist/core/patch-pipeline.js +285 -0
- package/dist/core/pipeline.d.ts +22 -0
- package/dist/core/pipeline.js +153 -0
- package/dist/core/plan-edit.d.ts +13 -0
- package/dist/core/plan-edit.js +215 -0
- package/dist/core/plan-patch.d.ts +29 -0
- package/dist/core/plan-patch.js +169 -0
- package/dist/core/plan-write.d.ts +6 -0
- package/dist/core/plan-write.js +27 -0
- package/dist/core/planned.d.ts +35 -0
- package/dist/core/planned.js +36 -0
- package/dist/core/precondition.d.ts +10 -0
- package/dist/core/precondition.js +76 -0
- package/dist/core/record.d.ts +3 -0
- package/dist/core/record.js +58 -0
- package/dist/core/resolve.d.ts +3 -0
- package/dist/core/resolve.js +65 -0
- package/dist/core/scope.d.ts +33 -0
- package/dist/core/scope.js +109 -0
- package/dist/core/snippet.d.ts +4 -0
- package/dist/core/snippet.js +36 -0
- package/dist/core/splice.d.ts +10 -0
- package/dist/core/splice.js +19 -0
- package/dist/core/target.d.ts +10 -0
- package/dist/core/target.js +46 -0
- package/dist/formatters/default.d.ts +16 -0
- package/dist/formatters/default.js +122 -0
- package/dist/formatters/index.d.ts +2 -0
- package/dist/formatters/index.js +1 -0
- package/dist/guards/generated-file.d.ts +10 -0
- package/dist/guards/generated-file.js +39 -0
- package/dist/guards/index.d.ts +13 -0
- package/dist/guards/index.js +25 -0
- package/dist/guards/non-text.d.ts +3 -0
- package/dist/guards/non-text.js +46 -0
- package/dist/guards/omission.d.ts +9 -0
- package/dist/guards/omission.js +48 -0
- package/dist/guards/read-prefix.d.ts +12 -0
- package/dist/guards/read-prefix.js +87 -0
- package/dist/guards/shared.d.ts +11 -0
- package/dist/guards/shared.js +46 -0
- package/dist/guards/syntax.d.ts +10 -0
- package/dist/guards/syntax.js +54 -0
- package/dist/guards/truncation-notice.d.ts +8 -0
- package/dist/guards/truncation-notice.js +32 -0
- package/dist/hooks/executable-shebang.d.ts +9 -0
- package/dist/hooks/executable-shebang.js +46 -0
- package/dist/hooks/index.d.ts +2 -0
- package/dist/hooks/index.js +2 -0
- package/dist/hooks/verify-write.d.ts +9 -0
- package/dist/hooks/verify-write.js +63 -0
- package/dist/index.d.ts +30 -0
- package/dist/index.js +15 -0
- package/dist/locks/index.d.ts +1 -0
- package/dist/locks/index.js +1 -0
- package/dist/locks/memory-locks.d.ts +9 -0
- package/dist/locks/memory-locks.js +94 -0
- package/dist/matchers/block-anchor.d.ts +9 -0
- package/dist/matchers/block-anchor.js +69 -0
- package/dist/matchers/escape.d.ts +6 -0
- package/dist/matchers/escape.js +32 -0
- package/dist/matchers/exact.d.ts +4 -0
- package/dist/matchers/exact.js +29 -0
- package/dist/matchers/fold.d.ts +11 -0
- package/dist/matchers/fold.js +144 -0
- package/dist/matchers/indentation.d.ts +3 -0
- package/dist/matchers/indentation.js +81 -0
- package/dist/matchers/index.d.ts +11 -0
- package/dist/matchers/index.js +18 -0
- package/dist/matchers/line-trimmed.d.ts +3 -0
- package/dist/matchers/line-trimmed.js +32 -0
- package/dist/matchers/lines.d.ts +24 -0
- package/dist/matchers/lines.js +74 -0
- package/dist/matchers/normalized.d.ts +7 -0
- package/dist/matchers/normalized.js +69 -0
- package/dist/patch/grammar.d.ts +5 -0
- package/dist/patch/grammar.js +24 -0
- package/dist/patch/index.d.ts +4 -0
- package/dist/patch/index.js +3 -0
- package/dist/patch/parse.d.ts +11 -0
- package/dist/patch/parse.js +209 -0
- package/dist/signature/contract.d.ts +8 -0
- package/dist/signature/contract.js +0 -0
- package/dist/signature/edit.d.ts +19 -0
- package/dist/signature/edit.js +158 -0
- package/dist/signature/index.d.ts +6 -0
- package/dist/signature/index.js +4 -0
- package/dist/signature/matching.d.ts +3 -0
- package/dist/signature/matching.js +25 -0
- package/dist/signature/messages.d.ts +4 -0
- package/dist/signature/messages.js +9 -0
- package/dist/signature/patch.d.ts +6 -0
- package/dist/signature/patch.js +55 -0
- package/dist/signature/schema.d.ts +19 -0
- package/dist/signature/schema.js +117 -0
- package/dist/signature/write.d.ts +9 -0
- package/dist/signature/write.js +52 -0
- package/dist/state/index.d.ts +2 -0
- package/dist/state/index.js +1 -0
- package/dist/state/invalidate.d.ts +29 -0
- package/dist/state/invalidate.js +37 -0
- package/docs/architecture.md +221 -0
- package/docs/hosts.md +95 -0
- package/docs/result-schema.md +268 -0
- package/package.json +53 -2
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Gareth Andrew
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,6 +1,443 @@
|
|
|
1
|
-
#
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
1
|
+
# @better-fs-tools/write
|
|
2
|
+
|
|
3
|
+
Edit, write, and apply_patch tools for TypeScript agents. They share one mutation core with the read tool in [`@better-fs-tools/read`](https://www.npmjs.com/package/@better-fs-tools/read): the same filesystem contract, the same read store, and the same resolvers and authorizers.
|
|
4
|
+
|
|
5
|
+
- `edit` replaces text in an existing file. Each old text must match once, and every byte outside the matched ranges stays the same.
|
|
6
|
+
- `write` creates a file, or replaces a whole file.
|
|
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
|
+
|
|
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.
|
|
10
|
+
|
|
11
|
+
## Install
|
|
12
|
+
|
|
13
|
+
```sh
|
|
14
|
+
npm install @better-fs-tools/write @better-fs-tools/read @better-fs-tools/fs
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
The package has no peers and imports no `node:` module. It depends on `@better-fs-tools/shell` for the optional bash tool of `createFsTools()`. Add a filesystem package, for example `@better-fs-tools/node`.
|
|
18
|
+
|
|
19
|
+
## Quick start
|
|
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()`:
|
|
22
|
+
|
|
23
|
+
```ts
|
|
24
|
+
import { memoryFileSystem } from "@better-fs-tools/fs";
|
|
25
|
+
import { textOf } from "@better-fs-tools/read";
|
|
26
|
+
import { createFsTools } from "@better-fs-tools/write";
|
|
27
|
+
|
|
28
|
+
const fs = memoryFileSystem({ files: { "/src/app.ts": "export const a = 1;\n" } });
|
|
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.
|
|
36
|
+
|
|
37
|
+
await read({ path: "/src/app.ts" });
|
|
38
|
+
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;
|
|
42
|
+
|
|
43
|
+
const created = await write({ path: "/src/b.ts", content: "export const b = 1;\n" });
|
|
44
|
+
console.log(textOf(created)); // Created /src/b.ts (1 line).
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
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
|
+
|
|
49
|
+
## One bundle for every tool
|
|
50
|
+
|
|
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`.
|
|
52
|
+
|
|
53
|
+
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
|
+
|
|
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.
|
|
56
|
+
|
|
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.
|
|
58
|
+
|
|
59
|
+
## Hosts
|
|
60
|
+
|
|
61
|
+
| Host | Package | Factories |
|
|
62
|
+
| ------------------------------------- | --------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------- |
|
|
63
|
+
| 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()` |
|
|
65
|
+
| 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 |
|
|
67
|
+
| 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
|
+
|
|
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.
|
|
70
|
+
|
|
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.
|
|
72
|
+
|
|
73
|
+
## edit
|
|
74
|
+
|
|
75
|
+
`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
|
+
|
|
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.
|
|
78
|
+
|
|
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`.
|
|
80
|
+
|
|
81
|
+
## write
|
|
82
|
+
|
|
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.
|
|
84
|
+
|
|
85
|
+
## apply_patch
|
|
86
|
+
|
|
87
|
+
`createApplyPatchTool({ fs })` takes a patch between `*** Begin Patch` and `*** End Patch` with `*** Add File`, `*** Update File` (with an optional `*** Move to`), and `*** Delete File` operations. `parsePatch` from `@better-fs-tools/write/patch` accepts a fenced block, a heredoc wrapper, CRLF line breaks, and a missing final newline.
|
|
88
|
+
|
|
89
|
+
```ts
|
|
90
|
+
import { memoryFileSystem } from "@better-fs-tools/fs";
|
|
91
|
+
import { nodeDigest } from "@better-fs-tools/node";
|
|
92
|
+
import { createReadTool, memoryStore, textOf } from "@better-fs-tools/read";
|
|
93
|
+
import { createApplyPatchTool } from "@better-fs-tools/write";
|
|
94
|
+
|
|
95
|
+
const fs = memoryFileSystem({
|
|
96
|
+
files: { "/src/app.ts": "const a = 1;\nconst b = 2;\n", "/src/old.ts": "gone\n" },
|
|
97
|
+
});
|
|
98
|
+
const state = memoryStore();
|
|
99
|
+
const digest = nodeDigest();
|
|
100
|
+
const read = createReadTool({ fs, state, digest });
|
|
101
|
+
const applyPatch = createApplyPatchTool({ fs, state, digest });
|
|
102
|
+
|
|
103
|
+
await read({ path: "/src/app.ts" });
|
|
104
|
+
await read({ path: "/src/old.ts" });
|
|
105
|
+
|
|
106
|
+
const result = await applyPatch({
|
|
107
|
+
patch: `*** Begin Patch
|
|
108
|
+
*** Update File: /src/app.ts
|
|
109
|
+
@@
|
|
110
|
+
const a = 1;
|
|
111
|
+
-const b = 2;
|
|
112
|
+
+const b = 3;
|
|
113
|
+
*** Add File: /src/new.ts
|
|
114
|
+
+export const c = 4;
|
|
115
|
+
*** Delete File: /src/old.ts
|
|
116
|
+
*** End Patch`,
|
|
117
|
+
});
|
|
118
|
+
console.log(textOf(result));
|
|
119
|
+
// Success. Updated the following files:
|
|
120
|
+
// M /src/app.ts
|
|
121
|
+
// A /src/new.ts
|
|
122
|
+
// D /src/old.ts
|
|
123
|
+
```
|
|
124
|
+
|
|
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.
|
|
126
|
+
|
|
127
|
+
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
|
+
|
|
129
|
+
## Read before write
|
|
130
|
+
|
|
131
|
+
With the read tool's `state` store and a `digest`, the write tools check what the model has seen:
|
|
132
|
+
|
|
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.
|
|
135
|
+
- On a backend with stable identity, the check compares the backend `version`. On every other backend it compares the content hash.
|
|
136
|
+
- 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
|
+
- `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
|
+
- `preconditions: { requireRead: "off" }` turns the check off. `partialRead` and `onStale` change the other two rules.
|
|
139
|
+
|
|
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.
|
|
184
|
+
|
|
185
|
+
## Authorize
|
|
186
|
+
|
|
187
|
+
An authorizer runs twice. The access stage runs for each target after `stat` and before any content byte is read, with `change: null`. The change stage runs for each planned change with the diff, after the guards. `writeAuthorizers(...steps)` runs steps left to right. The first deny wins. A read `ToolAuthorizer`, such as `denyPaths()`, is a valid step. On the bash tool, `denyPaths()` sees the working directory, not the files a command touches, so it does not stop `cat .env`. Share one list across the three tools only with that in mind.
|
|
188
|
+
|
|
189
|
+
```ts
|
|
190
|
+
import { memoryFileSystem } from "@better-fs-tools/fs";
|
|
191
|
+
import { denyPaths, textOf } from "@better-fs-tools/read";
|
|
192
|
+
import {
|
|
193
|
+
askBeforeWrite,
|
|
194
|
+
createWriteTool,
|
|
195
|
+
protectPaths,
|
|
196
|
+
writeAuthorizers,
|
|
197
|
+
} from "@better-fs-tools/write";
|
|
198
|
+
|
|
199
|
+
const fs = memoryFileSystem({ directories: ["/repo"] });
|
|
200
|
+
|
|
201
|
+
const write = createWriteTool({
|
|
202
|
+
fs,
|
|
203
|
+
authorize: writeAuthorizers(
|
|
204
|
+
// A tool-neutral authorizer from read works here too. It runs before any content byte is read.
|
|
205
|
+
denyPaths(["**/.env", "**/.env.*"]),
|
|
206
|
+
// AGENTS.md, CLAUDE.md, and .git/** are refused unless `ask` says yes.
|
|
207
|
+
protectPaths(),
|
|
208
|
+
// One question for the whole plan, with every diff.
|
|
209
|
+
askBeforeWrite(async (plan) => {
|
|
210
|
+
for (const change of plan) console.log(change.diff);
|
|
211
|
+
return true; // or false, or { content } with the user's own text
|
|
212
|
+
}),
|
|
213
|
+
),
|
|
214
|
+
});
|
|
215
|
+
|
|
216
|
+
console.log(textOf(await write({ path: "/repo/.env", content: "TOKEN=1\n" })));
|
|
217
|
+
// [write:denied] /repo/.env was refused by policy (the path matches a denied pattern).
|
|
218
|
+
console.log(textOf(await write({ path: "/repo/AGENTS.md", content: "# Rules\n" })));
|
|
219
|
+
// [write:denied] /repo/AGENTS.md was refused by policy (the path is protected).
|
|
220
|
+
console.log((await write({ path: "/repo/notes.md", content: "hello\n" })).status); // "ok"
|
|
221
|
+
```
|
|
222
|
+
|
|
223
|
+
An authorizer may allow with `content` for `edit` and `write`. The tool then writes that text instead, adds a `user-modified` note, and sets `changes[].userModified`. `apply_patch` does not take content.
|
|
224
|
+
|
|
225
|
+
## Guards and hooks
|
|
226
|
+
|
|
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.
|
|
228
|
+
|
|
229
|
+
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
|
+
|
|
231
|
+
```ts
|
|
232
|
+
import { memoryFileSystem } from "@better-fs-tools/fs";
|
|
233
|
+
import { textOf } from "@better-fs-tools/read";
|
|
234
|
+
import {
|
|
235
|
+
createWriteTool,
|
|
236
|
+
defaultGuards,
|
|
237
|
+
executableShebang,
|
|
238
|
+
generatedFileGuard,
|
|
239
|
+
syntaxGuard,
|
|
240
|
+
verifyWrite,
|
|
241
|
+
} from "@better-fs-tools/write";
|
|
242
|
+
import type { Guard, WriteHook } from "@better-fs-tools/write";
|
|
243
|
+
|
|
244
|
+
// A host guard: refuse tabs in new YAML text.
|
|
245
|
+
const noTabsInYaml: Guard<unknown> = {
|
|
246
|
+
id: "no-tabs-in-yaml",
|
|
247
|
+
check(change) {
|
|
248
|
+
const yaml = /\.ya?ml$/u.test(change.resolvedPath);
|
|
249
|
+
if (!yaml || !change.fragments.some((fragment) => fragment.newText.includes("\t"))) {
|
|
250
|
+
return { allow: true };
|
|
251
|
+
}
|
|
252
|
+
return {
|
|
253
|
+
allow: false,
|
|
254
|
+
note: {
|
|
255
|
+
code: "guard-refused",
|
|
256
|
+
severity: "warning",
|
|
257
|
+
message: `${change.displayPath}: YAML does not allow tabs for indentation.`,
|
|
258
|
+
},
|
|
259
|
+
};
|
|
260
|
+
},
|
|
261
|
+
};
|
|
262
|
+
|
|
263
|
+
// A host hook: log each committed change.
|
|
264
|
+
const logChanges: WriteHook<unknown> = {
|
|
265
|
+
id: "log-changes",
|
|
266
|
+
afterWrite(change) {
|
|
267
|
+
console.log(`${change.kind} ${change.path} (+${change.linesAdded} -${change.linesRemoved})`);
|
|
268
|
+
return {};
|
|
269
|
+
},
|
|
270
|
+
};
|
|
271
|
+
|
|
272
|
+
const write = createWriteTool({
|
|
273
|
+
fs: memoryFileSystem({ directories: ["/repo"] }),
|
|
274
|
+
// defaultGuards() is the default. Passing guards replaces the whole list.
|
|
275
|
+
guards: [
|
|
276
|
+
...defaultGuards().filter((guard) => guard.id !== "syntax"),
|
|
277
|
+
syntaxGuard({ parsers: { yaml: (text) => void text } }),
|
|
278
|
+
generatedFileGuard(),
|
|
279
|
+
noTabsInYaml,
|
|
280
|
+
],
|
|
281
|
+
hooks: [executableShebang(), verifyWrite(), logChanges],
|
|
282
|
+
});
|
|
283
|
+
|
|
284
|
+
console.log(textOf(await write({ path: "/repo/ci.yaml", content: "a:\n\tb: 1\n" })));
|
|
285
|
+
// [write:guard-refused] /repo/ci.yaml: YAML does not allow tabs for indentation.
|
|
286
|
+
|
|
287
|
+
console.log(textOf(await write({ path: "/repo/run.sh", content: "#!/bin/sh\necho hi\n" })));
|
|
288
|
+
// create /repo/run.sh (+2 -0)
|
|
289
|
+
// Created /repo/run.sh (2 lines).
|
|
290
|
+
//
|
|
291
|
+
// [write:executable] Made /repo/run.sh executable (mode 755) because it starts with "#!".
|
|
292
|
+
```
|
|
293
|
+
|
|
294
|
+
## Signatures
|
|
295
|
+
|
|
296
|
+
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
|
+
|
|
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.
|
|
299
|
+
|
|
300
|
+
```ts
|
|
301
|
+
import { memoryFileSystem } from "@better-fs-tools/fs";
|
|
302
|
+
import { createEditTool } from "@better-fs-tools/write";
|
|
303
|
+
import {
|
|
304
|
+
camelCaseEditSignature,
|
|
305
|
+
defaultEditSignature,
|
|
306
|
+
freeformPatchSignature,
|
|
307
|
+
multiEditSignature,
|
|
308
|
+
writeSignatureMessages,
|
|
309
|
+
} from "@better-fs-tools/write/signature";
|
|
310
|
+
|
|
311
|
+
// What the model sees: a name, a description, and a JSON Schema.
|
|
312
|
+
const signature = camelCaseEditSignature({ name: "edit_file" });
|
|
313
|
+
console.log(signature.name, Object.keys(signature.schema.properties ?? {}));
|
|
314
|
+
// edit_file [ "filePath", "oldString", "newString", "replaceAll" ]
|
|
315
|
+
|
|
316
|
+
// toInput checks model input and maps it to the core's canonical input.
|
|
317
|
+
console.log(signature.toInput({ filePath: "a.ts", oldString: "x", newString: "y" }));
|
|
318
|
+
// { path: "a.ts", edits: [ { oldText: "x", newText: "y" } ] }
|
|
319
|
+
|
|
320
|
+
// Behind a signature, pass its message names, so errors name filePath, not path.
|
|
321
|
+
const edit = createEditTool({
|
|
322
|
+
fs: memoryFileSystem({ files: { "/a.ts": "x\n" } }),
|
|
323
|
+
messages: writeSignatureMessages(signature),
|
|
324
|
+
});
|
|
325
|
+
export async function run(input: unknown) {
|
|
326
|
+
return edit(signature.toInput(input));
|
|
327
|
+
}
|
|
328
|
+
|
|
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.
|
|
337
|
+
export const renamed = defaultEditSignature({
|
|
338
|
+
names: { path: "file", old_string: "find", new_string: "replace" },
|
|
339
|
+
}); // edit({ file, find, replace, replace_all? })
|
|
340
|
+
```
|
|
341
|
+
|
|
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.
|
|
343
|
+
|
|
344
|
+
## The result
|
|
345
|
+
|
|
346
|
+
Every call returns a `MutationResult`: `tool`, `status` (`ok`, `no-change`, or `error`), `error` on an error result only, with a stable `code`, the `phase` that stopped the call, and the error note's `message`, `changes` with one `FileChange` for each committed file, `notes`, `commit` for a failed patch commit, and `content` for the model. [docs/result-schema.md](docs/result-schema.md) lists every field, code, and note.
|
|
347
|
+
|
|
348
|
+
```ts
|
|
349
|
+
import { memoryFileSystem } from "@better-fs-tools/fs";
|
|
350
|
+
import { textOf } from "@better-fs-tools/read";
|
|
351
|
+
import { createEditTool } from "@better-fs-tools/write";
|
|
352
|
+
import type { MutationResult } from "@better-fs-tools/write";
|
|
353
|
+
|
|
354
|
+
const edit = createEditTool({
|
|
355
|
+
fs: memoryFileSystem({ files: { "/app.ts": "const a = 1;\nconst b = 2;\n" } }),
|
|
356
|
+
});
|
|
357
|
+
|
|
358
|
+
const result: MutationResult = await edit({
|
|
359
|
+
path: "/app.ts",
|
|
360
|
+
edits: [{ oldText: "const b = 2;", newText: "const b = 3;" }],
|
|
361
|
+
});
|
|
362
|
+
|
|
363
|
+
if (result.status === "error") {
|
|
364
|
+
// A stable code, the stage that stopped the call, and the data of the error note.
|
|
365
|
+
console.log(result.error.code, result.error.phase, result.error.data);
|
|
366
|
+
} else {
|
|
367
|
+
for (const change of result.changes) {
|
|
368
|
+
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.
|
|
370
|
+
console.log(change.after?.version); // The backend version after the commit
|
|
371
|
+
}
|
|
372
|
+
}
|
|
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" ]
|
|
375
|
+
console.log(textOf(result)); // What the model sees
|
|
376
|
+
```
|
|
377
|
+
|
|
378
|
+
## Backends
|
|
379
|
+
|
|
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.
|
|
381
|
+
|
|
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 |
|
|
389
|
+
|
|
390
|
+
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
|
+
|
|
392
|
+
## Known limits
|
|
393
|
+
|
|
394
|
+
- `apply_patch` rollback lives in process memory. A crash or a killed process during the commit leaves some files changed and no report.
|
|
395
|
+
- 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.
|
|
397
|
+
- 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
|
+
- `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.
|
|
400
|
+
|
|
401
|
+
## Entries
|
|
402
|
+
|
|
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` |
|
|
408
|
+
|
|
409
|
+
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
|
+
|
|
411
|
+
```ts
|
|
412
|
+
import { compileGlob } from "@better-fs-tools/read";
|
|
413
|
+
import type { ToolAuthorizer } from "@better-fs-tools/read";
|
|
414
|
+
|
|
415
|
+
const generated = compileGlob("**/dist/**");
|
|
416
|
+
|
|
417
|
+
// Tool-neutral: it sees only the fields every tool's target has.
|
|
418
|
+
export const noGenerated: ToolAuthorizer<unknown> = {
|
|
419
|
+
id: "no-generated",
|
|
420
|
+
authorize: (target, ctx) =>
|
|
421
|
+
generated(target.resolvedPath)
|
|
422
|
+
? {
|
|
423
|
+
allow: false,
|
|
424
|
+
note: {
|
|
425
|
+
code: "denied",
|
|
426
|
+
severity: "warning",
|
|
427
|
+
message: ctx.messages.denied({ path: target.requestedPath, detail: "generated" }),
|
|
428
|
+
},
|
|
429
|
+
}
|
|
430
|
+
: { allow: true },
|
|
431
|
+
};
|
|
432
|
+
```
|
|
433
|
+
|
|
434
|
+
## More
|
|
435
|
+
|
|
436
|
+
- [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
|
|
439
|
+
- [`@better-fs-tools/fs`](https://www.npmjs.com/package/@better-fs-tools/fs): the `WritableFileSystem` contract and its conformance suite
|
|
440
|
+
|
|
441
|
+
## License
|
|
442
|
+
|
|
443
|
+
MIT
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import type { PlannedChange, WriteAuthorizer, WriteHookContext } from "../contract/extensions.ts";
|
|
2
|
+
type Answer = boolean | {
|
|
3
|
+
readonly content: string;
|
|
4
|
+
};
|
|
5
|
+
/**
|
|
6
|
+
* Asks `prompt` once for each call, with every planned change, before anything
|
|
7
|
+
* is written. `true` allows. `{ content }` allows with the user's content
|
|
8
|
+
* (edit and write only). `false`, a throw, or anything else denies.
|
|
9
|
+
*/
|
|
10
|
+
export declare function askBeforeWrite<THost>(prompt: (plan: readonly PlannedChange[], ctx: WriteHookContext<THost>) => Promise<Answer>): WriteAuthorizer<THost>;
|
|
11
|
+
export {};
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Asks `prompt` once for each call, with every planned change, before anything
|
|
3
|
+
* is written. `true` allows. `{ content }` allows with the user's content
|
|
4
|
+
* (edit and write only). `false`, a throw, or anything else denies.
|
|
5
|
+
*/
|
|
6
|
+
export function askBeforeWrite(prompt) {
|
|
7
|
+
if (typeof prompt !== "function")
|
|
8
|
+
throw new TypeError("askBeforeWrite takes a prompt function");
|
|
9
|
+
const answers = new WeakMap();
|
|
10
|
+
return Object.freeze({
|
|
11
|
+
id: "ask-before-write",
|
|
12
|
+
async authorize(target, ctx) {
|
|
13
|
+
if (target.change === null)
|
|
14
|
+
return { allow: true };
|
|
15
|
+
let answer = answers.get(ctx.call);
|
|
16
|
+
if (answer === undefined) {
|
|
17
|
+
answer = ask(prompt, target.plan, ctx);
|
|
18
|
+
answers.set(ctx.call, answer);
|
|
19
|
+
}
|
|
20
|
+
const value = await answer;
|
|
21
|
+
if (value === true)
|
|
22
|
+
return { allow: true };
|
|
23
|
+
if (value !== null &&
|
|
24
|
+
typeof value === "object" &&
|
|
25
|
+
typeof value.content === "string") {
|
|
26
|
+
return { allow: true, content: value.content };
|
|
27
|
+
}
|
|
28
|
+
return {
|
|
29
|
+
allow: false,
|
|
30
|
+
note: {
|
|
31
|
+
code: "denied",
|
|
32
|
+
severity: "warning",
|
|
33
|
+
message: ctx.messages.denied({
|
|
34
|
+
path: target.requestedPath,
|
|
35
|
+
detail: "the user did not approve the change",
|
|
36
|
+
}),
|
|
37
|
+
},
|
|
38
|
+
};
|
|
39
|
+
},
|
|
40
|
+
});
|
|
41
|
+
}
|
|
42
|
+
async function ask(prompt, plan, ctx) {
|
|
43
|
+
try {
|
|
44
|
+
return await prompt(plan, ctx);
|
|
45
|
+
}
|
|
46
|
+
catch {
|
|
47
|
+
return false;
|
|
48
|
+
}
|
|
49
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import type { WriteAuthorizer, WriteAuthorizeTarget, WriteHookContext } from "../contract/extensions.ts";
|
|
2
|
+
/**
|
|
3
|
+
* Denies changes to agent instruction files and the git folder, even when
|
|
4
|
+
* every other change is approved. `patterns` are globs matched against the
|
|
5
|
+
* resolved path and the source of a move. With `ask`, the user is asked once
|
|
6
|
+
* for each protected path in a call: `true` allows, and `false`, a throw, or
|
|
7
|
+
* anything else denies.
|
|
8
|
+
*/
|
|
9
|
+
export declare function protectPaths<THost = unknown>(options?: {
|
|
10
|
+
readonly patterns?: readonly string[];
|
|
11
|
+
readonly ask?: (target: WriteAuthorizeTarget, ctx: WriteHookContext<THost>) => Promise<boolean>;
|
|
12
|
+
}): WriteAuthorizer<THost>;
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import { compileGlob } from "@better-fs-tools/read";
|
|
2
|
+
const DEFAULT_PATTERNS = ["**/AGENTS.md", "**/CLAUDE.md", "**/.git/**"];
|
|
3
|
+
const ALLOW = Object.freeze({ allow: true });
|
|
4
|
+
/**
|
|
5
|
+
* Denies changes to agent instruction files and the git folder, even when
|
|
6
|
+
* every other change is approved. `patterns` are globs matched against the
|
|
7
|
+
* resolved path and the source of a move. With `ask`, the user is asked once
|
|
8
|
+
* for each protected path in a call: `true` allows, and `false`, a throw, or
|
|
9
|
+
* anything else denies.
|
|
10
|
+
*/
|
|
11
|
+
export function protectPaths(options = {}) {
|
|
12
|
+
const { patterns = DEFAULT_PATTERNS, ask } = options;
|
|
13
|
+
if (!Array.isArray(patterns) ||
|
|
14
|
+
!patterns.every((pattern) => typeof pattern === "string" && pattern !== "")) {
|
|
15
|
+
throw new TypeError("patterns must be an array of non-empty glob strings");
|
|
16
|
+
}
|
|
17
|
+
if (ask !== undefined && typeof ask !== "function")
|
|
18
|
+
throw new TypeError("ask must be a function");
|
|
19
|
+
const compiled = patterns.map((pattern) => ({ pattern, test: compileGlob(pattern) }));
|
|
20
|
+
const answers = new WeakMap();
|
|
21
|
+
const answer = (path, target, ctx) => {
|
|
22
|
+
let byPath = answers.get(ctx.call);
|
|
23
|
+
if (byPath === undefined) {
|
|
24
|
+
byPath = new Map();
|
|
25
|
+
answers.set(ctx.call, byPath);
|
|
26
|
+
}
|
|
27
|
+
let pending = byPath.get(path);
|
|
28
|
+
if (pending === undefined) {
|
|
29
|
+
pending = asked(ask, target, ctx);
|
|
30
|
+
byPath.set(path, pending);
|
|
31
|
+
}
|
|
32
|
+
return pending;
|
|
33
|
+
};
|
|
34
|
+
return Object.freeze({
|
|
35
|
+
id: "protect-paths",
|
|
36
|
+
async authorize(target, ctx) {
|
|
37
|
+
const paths = [target.resolvedPath];
|
|
38
|
+
if (target.change?.movedFrom != null)
|
|
39
|
+
paths.push(target.change.movedFrom);
|
|
40
|
+
for (const path of paths) {
|
|
41
|
+
const hit = compiled.find((entry) => entry.test(path));
|
|
42
|
+
if (hit === undefined)
|
|
43
|
+
continue;
|
|
44
|
+
if (ask !== undefined && (await answer(path, target, ctx)))
|
|
45
|
+
continue;
|
|
46
|
+
return {
|
|
47
|
+
allow: false,
|
|
48
|
+
note: {
|
|
49
|
+
code: "denied",
|
|
50
|
+
severity: "warning",
|
|
51
|
+
message: ctx.messages.denied({
|
|
52
|
+
path: target.requestedPath,
|
|
53
|
+
detail: ask === undefined
|
|
54
|
+
? "the path is protected"
|
|
55
|
+
: "the path is protected and the user did not approve the change",
|
|
56
|
+
}),
|
|
57
|
+
data: { pattern: hit.pattern },
|
|
58
|
+
},
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
return ALLOW;
|
|
62
|
+
},
|
|
63
|
+
});
|
|
64
|
+
}
|
|
65
|
+
async function asked(ask, target, ctx) {
|
|
66
|
+
if (ask === undefined)
|
|
67
|
+
return false;
|
|
68
|
+
try {
|
|
69
|
+
return (await ask(target, ctx)) === true;
|
|
70
|
+
}
|
|
71
|
+
catch {
|
|
72
|
+
return false;
|
|
73
|
+
}
|
|
74
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import type { WriteAuthorizer } from "../contract/extensions.ts";
|
|
2
|
+
/**
|
|
3
|
+
* Runs authorizers left to right. The first denial wins. Allow notes from
|
|
4
|
+
* every step are kept, and the first replacement `content` wins. No steps
|
|
5
|
+
* allows everything. A step that throws or returns an invalid decision fails
|
|
6
|
+
* the call with EXTENSION_FAILED. A read authorizer such as denyPaths also
|
|
7
|
+
* works as a step.
|
|
8
|
+
*/
|
|
9
|
+
export declare function writeAuthorizers<THost = unknown>(...steps: readonly WriteAuthorizer<NoInfer<THost>>[]): WriteAuthorizer<THost>;
|