@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.
Files changed (196) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +443 -6
  3. package/dist/authorize/ask-before-write.d.ts +11 -0
  4. package/dist/authorize/ask-before-write.js +49 -0
  5. package/dist/authorize/index.d.ts +3 -0
  6. package/dist/authorize/index.js +3 -0
  7. package/dist/authorize/protect-paths.d.ts +12 -0
  8. package/dist/authorize/protect-paths.js +74 -0
  9. package/dist/authorize/write-authorizers.d.ts +9 -0
  10. package/dist/authorize/write-authorizers.js +48 -0
  11. package/dist/bundle/create-fs-tools.d.ts +71 -0
  12. package/dist/bundle/create-fs-tools.js +125 -0
  13. package/dist/codecs/index.d.ts +1 -0
  14. package/dist/codecs/index.js +1 -0
  15. package/dist/codecs/utf8.d.ts +7 -0
  16. package/dist/codecs/utf8.js +61 -0
  17. package/dist/contract/codec.d.ts +26 -0
  18. package/dist/contract/codec.js +0 -0
  19. package/dist/contract/context.d.ts +14 -0
  20. package/dist/contract/context.js +0 -0
  21. package/dist/contract/deps.d.ts +55 -0
  22. package/dist/contract/deps.js +0 -0
  23. package/dist/contract/extensions.d.ts +103 -0
  24. package/dist/contract/extensions.js +0 -0
  25. package/dist/contract/format.d.ts +15 -0
  26. package/dist/contract/format.js +0 -0
  27. package/dist/contract/input.d.ts +35 -0
  28. package/dist/contract/input.js +0 -0
  29. package/dist/contract/limits.d.ts +26 -0
  30. package/dist/contract/limits.js +0 -0
  31. package/dist/contract/locks.d.ts +14 -0
  32. package/dist/contract/locks.js +0 -0
  33. package/dist/contract/matcher.d.ts +30 -0
  34. package/dist/contract/matcher.js +0 -0
  35. package/dist/contract/messages.d.ts +211 -0
  36. package/dist/contract/messages.js +0 -0
  37. package/dist/contract/patch.d.ts +50 -0
  38. package/dist/contract/patch.js +0 -0
  39. package/dist/contract/preconditions.d.ts +9 -0
  40. package/dist/contract/preconditions.js +5 -0
  41. package/dist/contract/result.d.ts +102 -0
  42. package/dist/contract/result.js +0 -0
  43. package/dist/core/abort.d.ts +4 -0
  44. package/dist/core/abort.js +23 -0
  45. package/dist/core/authorize.d.ts +9 -0
  46. package/dist/core/authorize.js +87 -0
  47. package/dist/core/bytes.d.ts +3 -0
  48. package/dist/core/bytes.js +14 -0
  49. package/dist/core/commit-patch.d.ts +20 -0
  50. package/dist/core/commit-patch.js +224 -0
  51. package/dist/core/commit.d.ts +9 -0
  52. package/dist/core/commit.js +111 -0
  53. package/dist/core/create-tools.d.ts +23 -0
  54. package/dist/core/create-tools.js +54 -0
  55. package/dist/core/deps.d.ts +11 -0
  56. package/dist/core/deps.js +207 -0
  57. package/dist/core/diff.d.ts +10 -0
  58. package/dist/core/diff.js +221 -0
  59. package/dist/core/encode.d.ts +3 -0
  60. package/dist/core/encode.js +26 -0
  61. package/dist/core/extension-error.d.ts +8 -0
  62. package/dist/core/extension-error.js +17 -0
  63. package/dist/core/format.d.ts +4 -0
  64. package/dist/core/format.js +36 -0
  65. package/dist/core/guards.d.ts +3 -0
  66. package/dist/core/guards.js +45 -0
  67. package/dist/core/hints.d.ts +14 -0
  68. package/dist/core/hints.js +75 -0
  69. package/dist/core/hooks.d.ts +15 -0
  70. package/dist/core/hooks.js +115 -0
  71. package/dist/core/input.d.ts +20 -0
  72. package/dist/core/input.js +91 -0
  73. package/dist/core/limits.d.ts +10 -0
  74. package/dist/core/limits.js +48 -0
  75. package/dist/core/line-index.d.ts +10 -0
  76. package/dist/core/line-index.js +38 -0
  77. package/dist/core/load.d.ts +14 -0
  78. package/dist/core/load.js +221 -0
  79. package/dist/core/lock.d.ts +2 -0
  80. package/dist/core/lock.js +56 -0
  81. package/dist/core/match.d.ts +15 -0
  82. package/dist/core/match.js +66 -0
  83. package/dist/core/messages.d.ts +8 -0
  84. package/dist/core/messages.js +147 -0
  85. package/dist/core/outcomes.d.ts +21 -0
  86. package/dist/core/outcomes.js +127 -0
  87. package/dist/core/parse-patch.d.ts +3 -0
  88. package/dist/core/parse-patch.js +64 -0
  89. package/dist/core/patch-hunks.d.ts +25 -0
  90. package/dist/core/patch-hunks.js +177 -0
  91. package/dist/core/patch-pipeline.d.ts +4 -0
  92. package/dist/core/patch-pipeline.js +285 -0
  93. package/dist/core/pipeline.d.ts +22 -0
  94. package/dist/core/pipeline.js +153 -0
  95. package/dist/core/plan-edit.d.ts +13 -0
  96. package/dist/core/plan-edit.js +215 -0
  97. package/dist/core/plan-patch.d.ts +29 -0
  98. package/dist/core/plan-patch.js +169 -0
  99. package/dist/core/plan-write.d.ts +6 -0
  100. package/dist/core/plan-write.js +27 -0
  101. package/dist/core/planned.d.ts +35 -0
  102. package/dist/core/planned.js +36 -0
  103. package/dist/core/precondition.d.ts +10 -0
  104. package/dist/core/precondition.js +76 -0
  105. package/dist/core/record.d.ts +3 -0
  106. package/dist/core/record.js +58 -0
  107. package/dist/core/resolve.d.ts +3 -0
  108. package/dist/core/resolve.js +65 -0
  109. package/dist/core/scope.d.ts +33 -0
  110. package/dist/core/scope.js +109 -0
  111. package/dist/core/snippet.d.ts +4 -0
  112. package/dist/core/snippet.js +36 -0
  113. package/dist/core/splice.d.ts +10 -0
  114. package/dist/core/splice.js +19 -0
  115. package/dist/core/target.d.ts +10 -0
  116. package/dist/core/target.js +46 -0
  117. package/dist/formatters/default.d.ts +16 -0
  118. package/dist/formatters/default.js +122 -0
  119. package/dist/formatters/index.d.ts +2 -0
  120. package/dist/formatters/index.js +1 -0
  121. package/dist/guards/generated-file.d.ts +10 -0
  122. package/dist/guards/generated-file.js +39 -0
  123. package/dist/guards/index.d.ts +13 -0
  124. package/dist/guards/index.js +25 -0
  125. package/dist/guards/non-text.d.ts +3 -0
  126. package/dist/guards/non-text.js +46 -0
  127. package/dist/guards/omission.d.ts +9 -0
  128. package/dist/guards/omission.js +48 -0
  129. package/dist/guards/read-prefix.d.ts +12 -0
  130. package/dist/guards/read-prefix.js +87 -0
  131. package/dist/guards/shared.d.ts +11 -0
  132. package/dist/guards/shared.js +46 -0
  133. package/dist/guards/syntax.d.ts +10 -0
  134. package/dist/guards/syntax.js +54 -0
  135. package/dist/guards/truncation-notice.d.ts +8 -0
  136. package/dist/guards/truncation-notice.js +32 -0
  137. package/dist/hooks/executable-shebang.d.ts +9 -0
  138. package/dist/hooks/executable-shebang.js +46 -0
  139. package/dist/hooks/index.d.ts +2 -0
  140. package/dist/hooks/index.js +2 -0
  141. package/dist/hooks/verify-write.d.ts +9 -0
  142. package/dist/hooks/verify-write.js +63 -0
  143. package/dist/index.d.ts +30 -0
  144. package/dist/index.js +15 -0
  145. package/dist/locks/index.d.ts +1 -0
  146. package/dist/locks/index.js +1 -0
  147. package/dist/locks/memory-locks.d.ts +9 -0
  148. package/dist/locks/memory-locks.js +94 -0
  149. package/dist/matchers/block-anchor.d.ts +9 -0
  150. package/dist/matchers/block-anchor.js +69 -0
  151. package/dist/matchers/escape.d.ts +6 -0
  152. package/dist/matchers/escape.js +32 -0
  153. package/dist/matchers/exact.d.ts +4 -0
  154. package/dist/matchers/exact.js +29 -0
  155. package/dist/matchers/fold.d.ts +11 -0
  156. package/dist/matchers/fold.js +144 -0
  157. package/dist/matchers/indentation.d.ts +3 -0
  158. package/dist/matchers/indentation.js +81 -0
  159. package/dist/matchers/index.d.ts +11 -0
  160. package/dist/matchers/index.js +18 -0
  161. package/dist/matchers/line-trimmed.d.ts +3 -0
  162. package/dist/matchers/line-trimmed.js +32 -0
  163. package/dist/matchers/lines.d.ts +24 -0
  164. package/dist/matchers/lines.js +74 -0
  165. package/dist/matchers/normalized.d.ts +7 -0
  166. package/dist/matchers/normalized.js +69 -0
  167. package/dist/patch/grammar.d.ts +5 -0
  168. package/dist/patch/grammar.js +24 -0
  169. package/dist/patch/index.d.ts +4 -0
  170. package/dist/patch/index.js +3 -0
  171. package/dist/patch/parse.d.ts +11 -0
  172. package/dist/patch/parse.js +209 -0
  173. package/dist/signature/contract.d.ts +8 -0
  174. package/dist/signature/contract.js +0 -0
  175. package/dist/signature/edit.d.ts +19 -0
  176. package/dist/signature/edit.js +158 -0
  177. package/dist/signature/index.d.ts +6 -0
  178. package/dist/signature/index.js +4 -0
  179. package/dist/signature/matching.d.ts +3 -0
  180. package/dist/signature/matching.js +25 -0
  181. package/dist/signature/messages.d.ts +4 -0
  182. package/dist/signature/messages.js +9 -0
  183. package/dist/signature/patch.d.ts +6 -0
  184. package/dist/signature/patch.js +55 -0
  185. package/dist/signature/schema.d.ts +19 -0
  186. package/dist/signature/schema.js +117 -0
  187. package/dist/signature/write.d.ts +9 -0
  188. package/dist/signature/write.js +52 -0
  189. package/dist/state/index.d.ts +2 -0
  190. package/dist/state/index.js +1 -0
  191. package/dist/state/invalidate.d.ts +29 -0
  192. package/dist/state/invalidate.js +37 -0
  193. package/docs/architecture.md +221 -0
  194. package/docs/hosts.md +95 -0
  195. package/docs/result-schema.md +268 -0
  196. package/package.json +53 -2
@@ -0,0 +1,48 @@
1
+ import { stepFailure } from "../core/extension-error.js";
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 function writeAuthorizers(...steps) {
10
+ for (const step of steps) {
11
+ if (step === null || typeof step !== "object" || typeof step.authorize !== "function") {
12
+ throw new TypeError("writeAuthorizers takes authorizers");
13
+ }
14
+ }
15
+ const chain = Object.freeze([...steps]);
16
+ return Object.freeze({
17
+ id: chain.length === 0 ? "allow" : chain.map((step) => step.id).join("+"),
18
+ async authorize(target, ctx) {
19
+ const notes = [];
20
+ let content;
21
+ for (const step of chain) {
22
+ let decision;
23
+ try {
24
+ decision = await step.authorize(target, ctx);
25
+ if (decision === null || typeof decision !== "object") {
26
+ throw new TypeError("not a decision");
27
+ }
28
+ if (decision.allow === false)
29
+ return decision;
30
+ if (decision.allow !== true)
31
+ throw new TypeError("not a decision");
32
+ }
33
+ catch (error) {
34
+ throw stepFailure(step, error);
35
+ }
36
+ if (decision.notes !== undefined)
37
+ notes.push(...decision.notes);
38
+ if (content === undefined && decision.content !== undefined)
39
+ content = decision.content;
40
+ }
41
+ return {
42
+ allow: true,
43
+ ...(notes.length === 0 ? {} : { notes }),
44
+ ...(content === undefined ? {} : { content }),
45
+ };
46
+ },
47
+ });
48
+ }
@@ -0,0 +1,71 @@
1
+ import type { WritableFileSystem } from "@better-fs-tools/fs";
2
+ import type { Clock, Digest, ReadStateStore, ReadTool, ReadToolDeps, ToolCallContext } from "@better-fs-tools/read";
3
+ import type { BashTool, ShellToolDeps } from "@better-fs-tools/shell";
4
+ import type { EditTool, ApplyPatchTool, WriteTool } from "../contract/context.ts";
5
+ import type { ApplyPatchToolDeps, EditToolDeps, WriteToolDeps } from "../contract/deps.ts";
6
+ import type { LockManager } from "../contract/locks.ts";
7
+ import type { InvalidateOutcome } from "../state/invalidate.ts";
8
+ /** Options set once for the whole bundle. A tool's own options cannot set them. */
9
+ export type FsToolsSharedKey = "fs" | "state" | "digest" | "locks" | "clock";
10
+ /** The bash tool's options, without the digest and clock that the bundle shares. */
11
+ export type FsToolsBashOptions<THost = undefined> = Omit<ShellToolDeps<THost>, "digest" | "clock">;
12
+ export interface CreateFsToolsOptions<THost = undefined> {
13
+ /** Required. A backend, or a factory called once for each call. */
14
+ readonly fs: WritableFileSystem | ((call: ToolCallContext<THost>) => WritableFileSystem);
15
+ /** Default: an in-memory store on the bundle clock. null turns read-before-write off. */
16
+ readonly state?: ReadStateStore | null;
17
+ /** Default sha256Digest(). */
18
+ readonly digest?: Digest;
19
+ /** Default memoryLocks(), shared by edit, write, and apply_patch. */
20
+ readonly locks?: LockManager;
21
+ /** Default () => new Date(). */
22
+ readonly clock?: Clock;
23
+ readonly read?: Omit<Partial<ReadToolDeps<THost>>, FsToolsSharedKey>;
24
+ readonly edit?: Omit<Partial<EditToolDeps<THost>>, FsToolsSharedKey>;
25
+ readonly write?: Omit<Partial<WriteToolDeps<THost>>, FsToolsSharedKey>;
26
+ readonly applyPatch?: Omit<Partial<ApplyPatchToolDeps<THost>>, FsToolsSharedKey>;
27
+ /**
28
+ * Off by default. The bash tool's options, with `runner` and `env` required.
29
+ * `false` is the same as leaving it out.
30
+ */
31
+ readonly bash?: false | FsToolsBashOptions<THost>;
32
+ }
33
+ export interface FsTools<THost = undefined> {
34
+ readonly read: ReadTool<THost>;
35
+ readonly edit: EditTool<THost>;
36
+ readonly write: WriteTool<THost>;
37
+ readonly applyPatch: ApplyPatchTool<THost>;
38
+ /** null unless options.bash is set. It does not share the read state: see invalidate. */
39
+ readonly bash: BashTool<THost> | null;
40
+ readonly fs: CreateFsToolsOptions<THost>["fs"];
41
+ readonly state: ReadStateStore | null;
42
+ readonly digest: Digest;
43
+ readonly locks: LockManager;
44
+ readonly clock: Clock;
45
+ /**
46
+ * Deletes the read record for a path, so the next edit or write needs a
47
+ * fresh read. Never throws. When fs is a factory, pass the call context (a
48
+ * hook has it as ctx.call), or the outcome is ok: false.
49
+ */
50
+ invalidate(path: string, call?: ToolCallContext<THost>): Promise<InvalidateOutcome>;
51
+ }
52
+ /** The result when options.bash is an object: bash is there. */
53
+ export interface FsToolsWithBash<THost = undefined> extends FsTools<THost> {
54
+ readonly bash: BashTool<THost>;
55
+ }
56
+ /**
57
+ * Creates read, edit, write, and apply_patch tools over one backend, sharing
58
+ * one read store, digest, lock manager, and clock. With `bash`, also a bash
59
+ * tool with the same digest and clock. Needs no Node APIs.
60
+ *
61
+ * A bash command is not limited by the backend's roots and does not update the
62
+ * read state. To make the next edit after a command need a read, call
63
+ * invalidate(path) from a bash afterRun hook.
64
+ *
65
+ * Throws TypeError on an unknown option, a shared option inside a tool's
66
+ * options, or anything a tool factory refuses.
67
+ */
68
+ export declare function createFsTools<THost = undefined>(options: CreateFsToolsOptions<THost> & {
69
+ readonly bash: FsToolsBashOptions<THost>;
70
+ }): FsToolsWithBash<THost>;
71
+ export declare function createFsTools<THost = undefined>(options: CreateFsToolsOptions<THost>): FsTools<THost>;
@@ -0,0 +1,125 @@
1
+ import { createReadTool, memoryStore, sha256Digest } from "@better-fs-tools/read";
2
+ import { createBashTool } from "@better-fs-tools/shell";
3
+ import { createApplyPatchTool, createEditTool, createWriteTool } from "../core/create-tools.js";
4
+ import { isWritable } from "../core/deps.js";
5
+ import { messageOf } from "../core/outcomes.js";
6
+ import { memoryLocks } from "../locks/index.js";
7
+ import { createInvalidator } from "../state/invalidate.js";
8
+ const KNOWN_OPTION_KEYS = new Set([
9
+ "fs",
10
+ "state",
11
+ "digest",
12
+ "locks",
13
+ "clock",
14
+ "read",
15
+ "edit",
16
+ "write",
17
+ "applyPatch",
18
+ "bash",
19
+ ]);
20
+ const SHARED_KEYS_BY_TOOL = {
21
+ read: ["fs", "state", "digest", "clock"],
22
+ edit: ["fs", "state", "digest", "locks", "clock"],
23
+ write: ["fs", "state", "digest", "locks", "clock"],
24
+ applyPatch: ["fs", "state", "digest", "locks", "clock"],
25
+ bash: ["digest", "clock"],
26
+ };
27
+ const EMPTY_STATE_STORE = Object.freeze({
28
+ get: async () => null,
29
+ put: async () => { },
30
+ delete: async () => { },
31
+ });
32
+ export function createFsTools(options) {
33
+ checkFsToolsOptions("createFsTools", options, KNOWN_OPTION_KEYS, SHARED_KEYS_BY_TOOL);
34
+ const { fs } = options;
35
+ const clock = options.clock ?? (() => new Date());
36
+ const state = options.state === undefined ? memoryStore({ clock }) : options.state;
37
+ const digest = options.digest ?? sha256Digest();
38
+ const locks = options.locks ?? memoryLocks();
39
+ const shared = { fs, state, digest, clock };
40
+ const bash = options.bash === undefined || options.bash === false ? null : options.bash;
41
+ if (bash === true) {
42
+ throw new TypeError("createFsTools bash must be an object with a runner and an env: the portable bundle has no default runner");
43
+ }
44
+ return Object.freeze({
45
+ read: createReadTool({ ...options.read, ...shared }),
46
+ edit: createEditTool({ ...options.edit, ...shared, locks }),
47
+ write: createWriteTool({ ...options.write, ...shared, locks }),
48
+ applyPatch: createApplyPatchTool({ ...options.applyPatch, ...shared, locks }),
49
+ bash: bash === null ? null : createBashTool({ ...bash, digest, clock }),
50
+ fs,
51
+ state,
52
+ digest,
53
+ locks,
54
+ clock,
55
+ invalidate: invalidator(fs, state ?? EMPTY_STATE_STORE),
56
+ });
57
+ }
58
+ function checkFsToolsOptions(label, options, known, sharedKeys) {
59
+ if (options === null || typeof options !== "object" || Array.isArray(options)) {
60
+ throw new TypeError(`${label} options must be an object`);
61
+ }
62
+ for (const key of Object.keys(options)) {
63
+ if (!known.has(key))
64
+ throw new TypeError(`Unknown ${label} option: ${key}`);
65
+ }
66
+ const state = options.state;
67
+ if (state !== undefined && state !== null && !isStore(state)) {
68
+ throw new TypeError(`${label} state must be a read state store or null: a bundle takes one store, not a per-call factory`);
69
+ }
70
+ for (const [tool, keys] of Object.entries(sharedKeys)) {
71
+ const part = options[tool];
72
+ if (part === undefined || (tool === "bash" && typeof part === "boolean"))
73
+ continue;
74
+ if (part === null || typeof part !== "object" || Array.isArray(part)) {
75
+ throw new TypeError(`${label} ${tool} options must be an object`);
76
+ }
77
+ for (const key of keys) {
78
+ if (Object.hasOwn(part, key)) {
79
+ throw new TypeError(`${label} ${tool} options cannot set ${key}: set it once at the top level`);
80
+ }
81
+ }
82
+ }
83
+ }
84
+ function invalidator(fs, state) {
85
+ if (typeof fs !== "function") {
86
+ const fixed = createInvalidator({ fs, state });
87
+ return (path) => fixed(path);
88
+ }
89
+ return async (path, call) => {
90
+ if (call === undefined) {
91
+ return {
92
+ ok: false,
93
+ phase: "stat",
94
+ error: {
95
+ reason: "unsupported",
96
+ detail: "fs is a factory: pass the call context to invalidate(path, call)",
97
+ },
98
+ };
99
+ }
100
+ let backend;
101
+ try {
102
+ backend = fs(call);
103
+ }
104
+ catch (error) {
105
+ return { ok: false, phase: "stat", error: { reason: "io", detail: messageOf(error) } };
106
+ }
107
+ if (!isWritable(backend)) {
108
+ return {
109
+ ok: false,
110
+ phase: "stat",
111
+ error: {
112
+ reason: "unsupported",
113
+ detail: "the fs factory did not return a writable filesystem",
114
+ },
115
+ };
116
+ }
117
+ return createInvalidator({ fs: backend, state })(path);
118
+ };
119
+ }
120
+ function isStore(value) {
121
+ if (value === null || typeof value !== "object")
122
+ return false;
123
+ const store = value;
124
+ return ["get", "put", "delete"].every((key) => typeof store[key] === "function");
125
+ }
@@ -0,0 +1 @@
1
+ export { utf8Codec } from "./utf8.ts";
@@ -0,0 +1 @@
1
+ export { utf8Codec } from "./utf8.js";
@@ -0,0 +1,7 @@
1
+ import type { Codec } from "../contract/codec.ts";
2
+ /**
3
+ * UTF-8 that keeps a file's BOM and line endings. A file whose line breaks are
4
+ * all CRLF is edited as LF and written back as CRLF. Mixed line endings are
5
+ * kept as they are.
6
+ */
7
+ export declare function utf8Codec(): Codec;
@@ -0,0 +1,61 @@
1
+ const BOM = Uint8Array.of(0xef, 0xbb, 0xbf);
2
+ const NEW_FILE_STYLE = Object.freeze({ encoding: "utf-8", bom: false, eol: "keep" });
3
+ /**
4
+ * UTF-8 that keeps a file's BOM and line endings. A file whose line breaks are
5
+ * all CRLF is edited as LF and written back as CRLF. Mixed line endings are
6
+ * kept as they are.
7
+ */
8
+ export function utf8Codec() {
9
+ return Object.freeze({
10
+ id: "utf-8",
11
+ newFileStyle: NEW_FILE_STYLE,
12
+ accepts(sample) {
13
+ try {
14
+ new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(sample.bytes, {
15
+ stream: !sample.complete,
16
+ });
17
+ return true;
18
+ }
19
+ catch {
20
+ return false;
21
+ }
22
+ },
23
+ decode(bytes) {
24
+ const bom = startsWithBom(bytes);
25
+ let raw;
26
+ try {
27
+ raw = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(bom ? bytes.subarray(BOM.byteLength) : bytes);
28
+ }
29
+ catch {
30
+ return { ok: false, detail: "invalid UTF-8" };
31
+ }
32
+ const eol = lineEndings(raw);
33
+ const text = eol === "crlf" ? raw.replaceAll("\r\n", "\n") : raw;
34
+ return { ok: true, text, style: { encoding: "utf-8", bom, eol } };
35
+ },
36
+ encode(text, style) {
37
+ const body = new TextEncoder().encode(style.eol === "crlf" ? text.replaceAll("\n", "\r\n") : text);
38
+ if (!style.bom)
39
+ return body;
40
+ const bytes = new Uint8Array(BOM.byteLength + body.byteLength);
41
+ bytes.set(BOM);
42
+ bytes.set(body, BOM.byteLength);
43
+ return bytes;
44
+ },
45
+ });
46
+ }
47
+ function startsWithBom(bytes) {
48
+ return bytes[0] === BOM[0] && bytes[1] === BOM[1] && bytes[2] === BOM[2];
49
+ }
50
+ function lineEndings(text) {
51
+ let lf = 0;
52
+ let crlf = 0;
53
+ for (let index = text.indexOf("\n"); index !== -1; index = text.indexOf("\n", index + 1)) {
54
+ lf += 1;
55
+ if (index > 0 && text.charCodeAt(index - 1) === 13)
56
+ crlf += 1;
57
+ }
58
+ if (crlf === 0)
59
+ return "lf";
60
+ return crlf === lf ? "crlf" : "keep";
61
+ }
@@ -0,0 +1,26 @@
1
+ import type { ClassificationSample } from "@better-fs-tools/read";
2
+ export interface TextStyle {
3
+ /** For example "utf-8". */
4
+ readonly encoding: string;
5
+ readonly bom: boolean;
6
+ /** "crlf": decode turned every CRLF into LF, encode turns LF back. "keep": no conversion (LF-only, mixed, or new). */
7
+ readonly eol: "lf" | "crlf" | "keep";
8
+ }
9
+ export type DecodeOutcome = {
10
+ readonly ok: true;
11
+ readonly text: string;
12
+ readonly style: TextStyle;
13
+ } | {
14
+ readonly ok: false;
15
+ readonly detail: string;
16
+ };
17
+ export interface Codec {
18
+ readonly id: string;
19
+ /** Whether this codec can decode the file, judged from a sample of its first bytes. Sync. */
20
+ accepts(sample: ClassificationSample): boolean;
21
+ decode(bytes: Uint8Array): DecodeOutcome;
22
+ /** encode(decode(bytes).text, style) must give the same bytes back, or the file is refused as not text. */
23
+ encode(text: string, style: TextStyle): Uint8Array;
24
+ /** Style for a new file. */
25
+ readonly newFileStyle: TextStyle;
26
+ }
File without changes
@@ -0,0 +1,14 @@
1
+ import type { ToolCallContext } from "@better-fs-tools/read";
2
+ import type { ApplyPatchInput, EditInput, WriteInput } from "./input.ts";
3
+ import type { MutationResult } from "./result.ts";
4
+ export type WriteToolName = "edit" | "write" | "apply_patch";
5
+ /**
6
+ * A write tool function. The context argument and its `host` are optional when
7
+ * THost includes undefined, and required otherwise.
8
+ */
9
+ export type MutationTool<TInput, THost = undefined> = undefined extends THost ? (input: TInput, ctx?: Omit<ToolCallContext<THost>, "host"> & {
10
+ readonly host?: THost;
11
+ }) => Promise<MutationResult> : (input: TInput, ctx: ToolCallContext<THost>) => Promise<MutationResult>;
12
+ export type EditTool<THost = undefined> = MutationTool<EditInput, THost>;
13
+ export type WriteTool<THost = undefined> = MutationTool<WriteInput, THost>;
14
+ export type ApplyPatchTool<THost = undefined> = MutationTool<ApplyPatchInput, THost>;
File without changes
@@ -0,0 +1,55 @@
1
+ import type { WritableFileSystem } from "@better-fs-tools/fs";
2
+ import type { Classifier, Clock, Digest, PathResolver, ReadStateStore, ToolCallContext } from "@better-fs-tools/read";
3
+ import type { Codec } from "./codec.ts";
4
+ import type { Guard, WriteAuthorizer, WriteHook } from "./extensions.ts";
5
+ import type { WriteFormatter } from "./format.ts";
6
+ import type { WriteLimits } from "./limits.ts";
7
+ import type { LockManager } from "./locks.ts";
8
+ import type { Matcher } from "./matcher.ts";
9
+ import type { WriteMessageCatalog } from "./messages.ts";
10
+ import type { PatchParser } from "./patch.ts";
11
+ import type { PreconditionPolicy } from "./preconditions.ts";
12
+ export interface WriteDependencies<THost = undefined> {
13
+ /** A filesystem, or a factory called once for each call. */
14
+ readonly fs: WritableFileSystem | ((call: ToolCallContext<THost>) => WritableFileSystem);
15
+ readonly limits: Readonly<WriteLimits>;
16
+ readonly messages: Readonly<WriteMessageCatalog>;
17
+ /** The read tool's resolvers work here. null is identity. */
18
+ readonly resolve: PathResolver<THost> | null;
19
+ /** Approves or refuses each write, before load and again for each planned change. null allows all. */
20
+ readonly authorize: WriteAuthorizer<THost> | null;
21
+ readonly preconditions: Readonly<PreconditionPolicy>;
22
+ /** The read tool's store. A factory runs at most once for each call. null turns read-before-write off. */
23
+ readonly state: ReadStateStore | ((call: ToolCallContext<THost>) => ReadStateStore | null) | null;
24
+ /** Required when state is set. */
25
+ readonly digest: Digest | null;
26
+ readonly clock: Clock;
27
+ readonly locks: LockManager;
28
+ /** Refuse non-text files. Non-empty. */
29
+ readonly classifiers: readonly Classifier[];
30
+ /** The first codec that accepts a file decodes it. Non-empty. */
31
+ readonly codecs: readonly Codec[];
32
+ /** Default defaultGuards(). An empty array turns the guards off. */
33
+ readonly guards: readonly Guard<THost>[];
34
+ readonly hooks: readonly WriteHook<THost>[];
35
+ readonly formatter: WriteFormatter<THost>;
36
+ }
37
+ export interface EditDependencies<THost = undefined> extends WriteDependencies<THost> {
38
+ /** Ordered. Non-empty. */
39
+ readonly matchers: readonly Matcher[];
40
+ }
41
+ export interface ApplyPatchDependencies<THost = undefined> extends WriteDependencies<THost> {
42
+ /** Ordered. Used to find hunk lines. Non-empty. */
43
+ readonly matchers: readonly Matcher[];
44
+ readonly patchParser: PatchParser;
45
+ }
46
+ type ToolDeps<D extends WriteDependencies<never>> = {
47
+ readonly fs: D["fs"];
48
+ readonly limits?: Partial<WriteLimits>;
49
+ readonly messages?: Partial<WriteMessageCatalog>;
50
+ readonly preconditions?: Partial<PreconditionPolicy>;
51
+ } & Partial<Omit<D, "fs" | "limits" | "messages" | "preconditions">>;
52
+ export type WriteToolDeps<THost = undefined> = ToolDeps<WriteDependencies<THost>>;
53
+ export type EditToolDeps<THost = undefined> = ToolDeps<EditDependencies<THost>>;
54
+ export type ApplyPatchToolDeps<THost = undefined> = ToolDeps<ApplyPatchDependencies<THost>>;
55
+ export {};
File without changes
@@ -0,0 +1,103 @@
1
+ import type { WritableFileSystem } from "@better-fs-tools/fs";
2
+ import type { AccessTarget, Classifier, Note, ToolCallContext, ToolHookContext } from "@better-fs-tools/read";
3
+ import type { TextStyle } from "./codec.ts";
4
+ import type { WriteToolName } from "./context.ts";
5
+ import type { MutationRequest } from "./input.ts";
6
+ import type { WriteLimits } from "./limits.ts";
7
+ import type { WriteMessageCatalog } from "./messages.ts";
8
+ import type { FileChange } from "./result.ts";
9
+ /** Given to every write host function. One object for each call. */
10
+ export interface WriteHookContext<THost = undefined> extends ToolHookContext<THost> {
11
+ readonly tool: WriteToolName;
12
+ readonly request: MutationRequest;
13
+ readonly limits: Readonly<WriteLimits>;
14
+ readonly messages: Readonly<WriteMessageCatalog>;
15
+ readonly call: ToolCallContext<THost>;
16
+ }
17
+ /** One file change as guards and authorizers see it, before it is written. */
18
+ export interface PlannedChange {
19
+ readonly tool: WriteToolName;
20
+ readonly kind: "create" | "update" | "delete" | "move";
21
+ readonly requestedPath: string;
22
+ readonly resolvedPath: string;
23
+ readonly displayPath: string;
24
+ /** Resolved path of the move source. null unless kind is "move". */
25
+ readonly movedFrom: string | null;
26
+ /** Decoded text before, in the codec's text space. null for create. */
27
+ readonly before: PlannedText | null;
28
+ /** Decoded text after. null for delete. */
29
+ readonly after: PlannedText | null;
30
+ /** Edit pairs; patch hunks as removed and added text; for write, one fragment with the whole content. */
31
+ readonly fragments: readonly ChangeFragment[];
32
+ readonly linesAdded: number;
33
+ readonly linesRemoved: number;
34
+ readonly diff: string;
35
+ }
36
+ export interface PlannedText {
37
+ readonly text: string;
38
+ readonly style: TextStyle;
39
+ /** Only for before. null without a digest. */
40
+ readonly contentId: string | null;
41
+ readonly version: string | null;
42
+ }
43
+ export interface ChangeFragment {
44
+ readonly oldText: string;
45
+ readonly newText: string;
46
+ }
47
+ export interface WriteAuthorizeTarget extends AccessTarget {
48
+ readonly action: "create" | "update" | "delete" | "move";
49
+ readonly tool: WriteToolName;
50
+ /** null in the access stage, before any content byte is read. */
51
+ readonly change: PlannedChange | null;
52
+ /** Every change in this call, in order. Empty in the access stage. */
53
+ readonly plan: readonly PlannedChange[];
54
+ }
55
+ /** `content` replaces the planned text. Only for edit and write, and only for a planned change. */
56
+ export type WriteAuthorizeDecision = {
57
+ readonly allow: true;
58
+ readonly notes?: readonly Note[];
59
+ readonly content?: string;
60
+ } | {
61
+ readonly allow: false;
62
+ readonly note?: Note;
63
+ };
64
+ /** Runs twice: once for each target before any content byte is read, then once for each planned change. */
65
+ export interface WriteAuthorizer<THost = undefined> {
66
+ readonly id: string;
67
+ readonly authorize: (target: WriteAuthorizeTarget, ctx: WriteHookContext<THost>) => WriteAuthorizeDecision | Promise<WriteAuthorizeDecision>;
68
+ }
69
+ export interface GuardContext<THost = undefined> extends WriteHookContext<THost> {
70
+ readonly classifiers: readonly Classifier[];
71
+ }
72
+ /** A refusal without a note gets the default guardRefused message, as the other decisions do. */
73
+ export type GuardDecision = {
74
+ readonly allow: true;
75
+ readonly notes?: readonly Note[];
76
+ } | {
77
+ readonly allow: false;
78
+ readonly note?: Note;
79
+ };
80
+ export interface Guard<THost = undefined> {
81
+ readonly id: string;
82
+ /** Runs on each planned change, before the authorizer sees it. */
83
+ check(change: PlannedChange, ctx: GuardContext<THost>): GuardDecision | Promise<GuardDecision>;
84
+ }
85
+ export interface AfterWriteContext<THost = undefined> extends WriteHookContext<THost> {
86
+ /** The call's filesystem. Host code may read or rewrite the file through it. */
87
+ readonly fs: WritableFileSystem;
88
+ }
89
+ export interface WriteHookResult {
90
+ readonly notes?: readonly Note[];
91
+ /** true when the hook changed the file, so it is read again before the read state is recorded. */
92
+ readonly rewrote?: boolean;
93
+ }
94
+ export interface WriteHook<THost = undefined> {
95
+ readonly id: string;
96
+ /**
97
+ * Mode bits for a file the call creates, asked just before its commit. The
98
+ * first hook that returns a number wins. null keeps the backend's new-file
99
+ * mode. A replace always keeps the file's mode.
100
+ */
101
+ newFileMode?(change: PlannedChange, ctx: WriteHookContext<THost>): number | null;
102
+ afterWrite(change: FileChange, ctx: AfterWriteContext<THost>): WriteHookResult | Promise<WriteHookResult>;
103
+ }
File without changes
@@ -0,0 +1,15 @@
1
+ import type { ContentPart, Digest, ToolCallContext } from "@better-fs-tools/read";
2
+ import type { WriteLimits } from "./limits.ts";
3
+ import type { MutationReport } from "./result.ts";
4
+ export interface WriteFormatContext<THost = undefined> {
5
+ readonly digest: Digest | null;
6
+ readonly limits: Readonly<WriteLimits>;
7
+ /** "view": body only, no notes. */
8
+ readonly mode: "model" | "view";
9
+ readonly call: ToolCallContext<THost>;
10
+ }
11
+ export interface WriteFormatter<THost = undefined> {
12
+ readonly id: string;
13
+ /** Sync and pure. A string becomes one text part. If it throws, the default format is used with a warning. */
14
+ format(report: MutationReport, ctx: WriteFormatContext<THost>): string | readonly ContentPart[];
15
+ }
File without changes
@@ -0,0 +1,35 @@
1
+ export interface EditPair {
2
+ readonly oldText: string;
3
+ readonly newText: string;
4
+ /** Default false. */
5
+ readonly replaceAll?: boolean;
6
+ }
7
+ /** Edit tool input. A signature sets the model-facing parameter names. */
8
+ export interface EditInput {
9
+ readonly path: string;
10
+ /** One to limits.maxEdits pairs. Matched against one snapshot of the file. */
11
+ readonly edits: readonly EditPair[];
12
+ }
13
+ export interface WriteInput {
14
+ readonly path: string;
15
+ readonly content: string;
16
+ }
17
+ export interface ApplyPatchInput {
18
+ /** Codex patch text. */
19
+ readonly patch: string;
20
+ }
21
+ export interface EditRequest {
22
+ readonly tool: "edit";
23
+ readonly path: string;
24
+ readonly edits: readonly Required<EditPair>[];
25
+ }
26
+ export interface WriteRequest {
27
+ readonly tool: "write";
28
+ readonly path: string;
29
+ readonly content: string;
30
+ }
31
+ export interface ApplyPatchRequest {
32
+ readonly tool: "apply_patch";
33
+ readonly patch: string;
34
+ }
35
+ export type MutationRequest = EditRequest | WriteRequest | ApplyPatchRequest;
File without changes
@@ -0,0 +1,26 @@
1
+ export interface WriteLimits {
2
+ /** Bytes of an existing file that any tool loads. Default 8 MiB. */
3
+ readonly maxFileBytes: number;
4
+ /** Encoded bytes of new content for one file. Default 8 MiB. */
5
+ readonly maxWriteBytes: number;
6
+ /** UTF-8 bytes of patch text. Default 4 MiB (4_194_304). */
7
+ readonly maxPatchBytes: number;
8
+ /** Operations in one patch. Default 100. */
9
+ readonly maxPatchFiles: number;
10
+ /** Pairs in one edit call. Default 100. */
11
+ readonly maxEdits: number;
12
+ /** Bytes given to classifiers and codecs. Default 8_192. */
13
+ readonly sampleBytes: number;
14
+ /** Context lines before and after each change in a snippet. Default 3. */
15
+ readonly snippetLines: number;
16
+ /** Snippet lines for one file in the model text. Default 40. */
17
+ readonly maxSnippetLines: number;
18
+ /** Lines of unified diff kept in FileChange.diff. Default 2_000. */
19
+ readonly maxDiffLines: number;
20
+ /** Lines in a not-found hint. Default 12. */
21
+ readonly maxHintLines: number;
22
+ /** Line numbers listed for an ambiguous match. Default 10. */
23
+ readonly maxListedMatches: number;
24
+ /** Problems listed for a failed patch verify. Default 20. */
25
+ readonly maxPatchProblems: number;
26
+ }
File without changes
@@ -0,0 +1,14 @@
1
+ export type LockOutcome = {
2
+ readonly ok: true;
3
+ release(): void;
4
+ } | {
5
+ readonly ok: false;
6
+ readonly reason: "timeout" | "aborted";
7
+ };
8
+ export interface LockManager {
9
+ readonly id: string;
10
+ /** Takes every key or none. Keys arrive sorted and without duplicates. */
11
+ acquire(keys: readonly string[], options: {
12
+ readonly signal?: AbortSignal;
13
+ }): Promise<LockOutcome>;
14
+ }
File without changes