@better-fs-tools/write 0.0.0-stage → 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 +442 -2
  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 +54 -4
@@ -0,0 +1,209 @@
1
+ const BEGIN = "*** Begin Patch";
2
+ const END = "*** End Patch";
3
+ const END_OF_FILE = "*** End of File";
4
+ const ADD = /^\*\*\* Add File:(.*)$/u;
5
+ const DELETE = /^\*\*\* Delete File:(.*)$/u;
6
+ const UPDATE = /^\*\*\* Update File:(.*)$/u;
7
+ const MOVE = /^\*\*\* Move to:(.*)$/u;
8
+ const ENVIRONMENT = /^\*\*\* Environment ID:/u;
9
+ const FENCE_OPEN = /^```[\w+-]*$/u;
10
+ const FENCE_CLOSE = /^```$/u;
11
+ /** `apply_patch <<'EOF'`, `<<EOF`, or `<<"EOF"`. Group 2 is the tag. */
12
+ const HEREDOC = /^(?:(?:apply_patch|applypatch)\s+)?<<-?\s*(['"]?)([A-Za-z_][A-Za-z0-9_]*)\1$/u;
13
+ class PatchSyntaxError extends Error {
14
+ line;
15
+ detail;
16
+ constructor(line, detail) {
17
+ super(detail);
18
+ this.line = line;
19
+ this.detail = detail;
20
+ }
21
+ }
22
+ /**
23
+ * Parses the Codex patch format. Lenient at the edges: CRLF line breaks,
24
+ * surrounding blank lines, one fenced block, and one heredoc wrapper
25
+ * (`apply_patch <<'EOF'`) are stripped, and a missing final newline is fine.
26
+ * Line numbers in errors and in the plan count lines of the text as given.
27
+ * Never throws.
28
+ */
29
+ export function parsePatch(text) {
30
+ if (typeof text !== "string") {
31
+ return { ok: false, error: { line: 1, detail: "the patch must be a string" } };
32
+ }
33
+ try {
34
+ return { ok: true, plan: { operations: new Parser(text).parse() } };
35
+ }
36
+ catch (error) {
37
+ if (!(error instanceof PatchSyntaxError))
38
+ throw error;
39
+ return { ok: false, error: { line: error.line, detail: error.detail } };
40
+ }
41
+ }
42
+ /** The default patch parser: parsePatch as a PatchParser. */
43
+ export function codexPatchParser() {
44
+ return Object.freeze({ id: "codex", parse: parsePatch });
45
+ }
46
+ class Parser {
47
+ lines;
48
+ bodyStart = 0;
49
+ bodyEnd;
50
+ at = 0;
51
+ constructor(text) {
52
+ this.lines = text.replaceAll("\r\n", "\n").split("\n");
53
+ this.bodyEnd = this.lines.length - 1;
54
+ }
55
+ parse() {
56
+ this.unwrap();
57
+ if (this.bodyStart > this.bodyEnd)
58
+ throw new PatchSyntaxError(1, "the patch is empty");
59
+ if (this.trimmed(this.bodyStart) !== BEGIN) {
60
+ throw new PatchSyntaxError(this.bodyStart + 1, `the first line must be "${BEGIN}"`);
61
+ }
62
+ if (this.bodyEnd === this.bodyStart || this.trimmed(this.bodyEnd) !== END) {
63
+ throw new PatchSyntaxError(this.bodyEnd + 1, `the last line must be "${END}"`);
64
+ }
65
+ const operations = [];
66
+ this.at = this.bodyStart + 1;
67
+ while (this.at < this.bodyEnd) {
68
+ const line = this.trimmed(this.at);
69
+ if (line === "") {
70
+ this.at += 1;
71
+ continue;
72
+ }
73
+ operations.push(this.operation(line));
74
+ }
75
+ if (operations.length === 0) {
76
+ throw new PatchSyntaxError(this.bodyEnd + 1, "the patch has no file operations");
77
+ }
78
+ return operations;
79
+ }
80
+ unwrap() {
81
+ this.trimBlank();
82
+ if (this.bodyStart < this.bodyEnd &&
83
+ FENCE_OPEN.test(this.trimmed(this.bodyStart)) &&
84
+ FENCE_CLOSE.test(this.trimmed(this.bodyEnd))) {
85
+ this.bodyStart += 1;
86
+ this.bodyEnd -= 1;
87
+ this.trimBlank();
88
+ }
89
+ const heredoc = this.bodyStart < this.bodyEnd ? HEREDOC.exec(this.trimmed(this.bodyStart)) : null;
90
+ if (heredoc !== null && this.trimmed(this.bodyEnd) === heredoc[2]) {
91
+ this.bodyStart += 1;
92
+ this.bodyEnd -= 1;
93
+ this.trimBlank();
94
+ }
95
+ }
96
+ trimBlank() {
97
+ while (this.bodyStart <= this.bodyEnd && this.trimmed(this.bodyStart) === "")
98
+ this.bodyStart += 1;
99
+ while (this.bodyEnd >= this.bodyStart && this.trimmed(this.bodyEnd) === "")
100
+ this.bodyEnd -= 1;
101
+ }
102
+ trimmed(index) {
103
+ return (this.lines[index] ?? "").trim();
104
+ }
105
+ raw(index) {
106
+ return this.lines[index] ?? "";
107
+ }
108
+ operation(header) {
109
+ const line = this.at + 1;
110
+ if (ENVIRONMENT.test(header)) {
111
+ throw new PatchSyntaxError(line, "*** Environment ID is not supported. Remove the line.");
112
+ }
113
+ const add = ADD.exec(header);
114
+ if (add !== null)
115
+ return this.add(this.path(add[1], line), line);
116
+ const remove = DELETE.exec(header);
117
+ if (remove !== null) {
118
+ this.at += 1;
119
+ return { kind: "delete", path: this.path(remove[1], line), line };
120
+ }
121
+ const update = UPDATE.exec(header);
122
+ if (update !== null)
123
+ return this.update(this.path(update[1], line), line);
124
+ throw new PatchSyntaxError(line, `${JSON.stringify(header)} is not a valid operation header. Use "*** Add File: <path>", "*** Delete File: <path>", or "*** Update File: <path>".`);
125
+ }
126
+ path(value, line) {
127
+ const path = (value ?? "").trim();
128
+ if (path === "")
129
+ throw new PatchSyntaxError(line, "the file path is empty");
130
+ return path;
131
+ }
132
+ add(path, line) {
133
+ this.at += 1;
134
+ const content = [];
135
+ while (this.at < this.bodyEnd && this.raw(this.at).startsWith("+")) {
136
+ content.push(this.raw(this.at).slice(1));
137
+ this.at += 1;
138
+ }
139
+ if (content.length === 0) {
140
+ throw new PatchSyntaxError(line, `*** Add File: ${path} needs at least one "+" line`);
141
+ }
142
+ return { kind: "add", path, content: `${content.join("\n")}\n`, line };
143
+ }
144
+ update(path, line) {
145
+ this.at += 1;
146
+ let moveTo = null;
147
+ const move = this.at < this.bodyEnd ? MOVE.exec(this.trimmed(this.at)) : null;
148
+ if (move !== null) {
149
+ moveTo = this.path(move[1], this.at + 1);
150
+ this.at += 1;
151
+ }
152
+ const hunks = [];
153
+ while (this.at < this.bodyEnd) {
154
+ const raw = this.raw(this.at);
155
+ if (raw.trim() === "") {
156
+ this.at += 1;
157
+ continue;
158
+ }
159
+ if (raw.startsWith("***"))
160
+ break;
161
+ hunks.push(this.hunk(hunks.length === 0));
162
+ }
163
+ if (hunks.length === 0 && moveTo === null) {
164
+ throw new PatchSyntaxError(line, `*** Update File: ${path} needs at least one hunk or a "*** Move to:" line`);
165
+ }
166
+ return { kind: "update", path, moveTo, hunks, line };
167
+ }
168
+ hunk(isFirstHunk) {
169
+ const line = this.at + 1;
170
+ const head = this.raw(this.at);
171
+ let context = null;
172
+ if (head.trimEnd() === "@@") {
173
+ this.at += 1;
174
+ }
175
+ else if (head.startsWith("@@ ")) {
176
+ context = head.slice(3);
177
+ this.at += 1;
178
+ }
179
+ else if (!isFirstHunk) {
180
+ throw new PatchSyntaxError(line, `a hunk must start with "@@", got ${JSON.stringify(head)}`);
181
+ }
182
+ const lines = [];
183
+ let endOfFile = false;
184
+ while (this.at < this.bodyEnd) {
185
+ const raw = this.raw(this.at);
186
+ if (raw.trimEnd() === END_OF_FILE) {
187
+ if (lines.length === 0)
188
+ throw new PatchSyntaxError(this.at + 1, "the hunk has no lines");
189
+ endOfFile = true;
190
+ this.at += 1;
191
+ break;
192
+ }
193
+ // Codex reads an empty line in a hunk as an empty context line.
194
+ const kind = raw === "" ? " " : raw[0];
195
+ if (kind === " " || kind === "-" || kind === "+") {
196
+ lines.push({ kind, text: raw.slice(1) });
197
+ this.at += 1;
198
+ continue;
199
+ }
200
+ if (lines.length === 0) {
201
+ throw new PatchSyntaxError(this.at + 1, `unexpected line ${JSON.stringify(raw)} in a hunk. Every hunk line starts with " " (context), "-" (removed), or "+" (added).`);
202
+ }
203
+ break;
204
+ }
205
+ if (lines.length === 0)
206
+ throw new PatchSyntaxError(line, "the hunk has no lines");
207
+ return { context, lines, endOfFile, line };
208
+ }
209
+ }
@@ -0,0 +1,8 @@
1
+ import type { ToolSignature } from "@better-fs-tools/read";
2
+ import type { ApplyPatchInput, EditInput, WriteInput } from "../contract/input.ts";
3
+ import type { WriteCanonicalParam } from "../contract/messages.ts";
4
+ /** A write tool's signature: its model-facing name, schema, description, and parameter names. */
5
+ export type MutationSignature<TInput> = ToolSignature<TInput, WriteCanonicalParam>;
6
+ export type EditSignature = MutationSignature<EditInput>;
7
+ export type WriteSignature = MutationSignature<WriteInput>;
8
+ export type PatchSignature = MutationSignature<ApplyPatchInput>;
File without changes
@@ -0,0 +1,19 @@
1
+ import type { SignatureDocs } from "@better-fs-tools/read";
2
+ import type { Matcher } from "../contract/matcher.ts";
3
+ import type { EditSignature } from "./contract.ts";
4
+ type MatcherOption = {
5
+ readonly matchers?: readonly Matcher[];
6
+ };
7
+ /** edit({ path, old_string, new_string, replace_all? }). Name "edit". */
8
+ export declare function defaultEditSignature(options?: SignatureDocs<"path" | "old_string" | "new_string" | "replace_all"> & MatcherOption): EditSignature;
9
+ /**
10
+ * edit({ filePath, oldString, newString, replaceAll? }). OpenCode and Kilo Code.
11
+ * The same as defaultEditSignature with camel-case names.
12
+ */
13
+ export declare function camelCaseEditSignature(options?: SignatureDocs<"filePath" | "oldString" | "newString" | "replaceAll"> & MatcherOption): EditSignature;
14
+ /**
15
+ * edit({ path, edits: [{ oldText, newText }] }). Pi and Cloudflare Computer.
16
+ * Has no replaceAll parameter, so no message suggests one.
17
+ */
18
+ export declare function multiEditSignature(options?: SignatureDocs<"path" | "edits" | "oldText" | "newText"> & MatcherOption): EditSignature;
19
+ export {};
@@ -0,0 +1,158 @@
1
+ import { checkMatchers, matchingSentence } from "./matching.js";
2
+ import { booleanSchema, checkDocs, deepFreeze, objectSchema, pathSchema, readFlag, readObject, readPath, readString, stringSchema, } from "./schema.js";
3
+ const NAME = "edit";
4
+ const PATH_TEXT = "Path of the file to edit, relative to the working directory or absolute within an allowed root.";
5
+ const READ_FIRST = "Read the file with the read tool before you edit it.";
6
+ const NO_PREFIX = "Copy old text from the file without the line-number prefix the read tool adds.";
7
+ const USE_WRITE = "To create a file or replace all of its content, use the write tool.";
8
+ /** edit({ path, old_string, new_string, replace_all? }). Name "edit". */
9
+ export function defaultEditSignature(options = {}) {
10
+ return singleEditSignature(options, "defaultEditSignature", {
11
+ path: "path",
12
+ old: "old_string",
13
+ new: "new_string",
14
+ all: "replace_all",
15
+ });
16
+ }
17
+ /**
18
+ * edit({ filePath, oldString, newString, replaceAll? }). OpenCode and Kilo Code.
19
+ * The same as defaultEditSignature with camel-case names.
20
+ */
21
+ export function camelCaseEditSignature(options = {}) {
22
+ return singleEditSignature(options, "camelCaseEditSignature", {
23
+ path: "filePath",
24
+ old: "oldString",
25
+ new: "newString",
26
+ all: "replaceAll",
27
+ });
28
+ }
29
+ function singleEditSignature(options, label, presetNames) {
30
+ const checked = checkDocs(options, label, [
31
+ presetNames.path,
32
+ presetNames.old,
33
+ presetNames.new,
34
+ presetNames.all,
35
+ ]);
36
+ const { describe } = checked;
37
+ const rename = (param) => checked.names[param] ?? param;
38
+ const names = {
39
+ path: rename(presetNames.path),
40
+ old: rename(presetNames.old),
41
+ new: rename(presetNames.new),
42
+ all: rename(presetNames.all),
43
+ };
44
+ const keys = [names.path, names.old, names.new, names.all];
45
+ const matchers = checkMatchers(options.matchers);
46
+ const schema = deepFreeze(objectSchema([
47
+ [names.path, pathSchema(describe[presetNames.path] ?? PATH_TEXT)],
48
+ [
49
+ names.old,
50
+ stringSchema(describe[presetNames.old] ??
51
+ `Text to replace. It must match one place in the file unless ${names.all} is true.`, true),
52
+ ],
53
+ [
54
+ names.new,
55
+ stringSchema(describe[presetNames.new] ??
56
+ `Replacement text. Send an empty string to delete ${names.old}.`),
57
+ ],
58
+ [
59
+ names.all,
60
+ booleanSchema(describe[presetNames.all] ?? `Replace every place ${names.old} matches. Default false.`),
61
+ ],
62
+ ], [names.path, names.old, names.new]));
63
+ const params = {
64
+ path: names.path,
65
+ oldText: names.old,
66
+ newText: names.new,
67
+ replaceAll: names.all,
68
+ };
69
+ return Object.freeze({
70
+ name: options.name ?? NAME,
71
+ description: options.description ??
72
+ `Edit a text file by replacing text. \`${names.old}\` must match exactly one place in ` +
73
+ `the file: add surrounding lines to make it unique, or set \`${names.all}\` to change ` +
74
+ `every place. ${matchingSentence(matchers, names.old)} ${NO_PREFIX} ${READ_FIRST} ` +
75
+ `After an edit, the same file can be edited again without another read. ${USE_WRITE}`,
76
+ schema,
77
+ toInput(input) {
78
+ const record = readObject(input, "edit input", keys, [names.path, names.old, names.new]);
79
+ const path = readPath(record[names.path], names.path);
80
+ const oldText = readString(record[names.old], names.old, true);
81
+ const newText = readString(record[names.new], names.new);
82
+ const replaceAll = readFlag(record[names.all], names.all);
83
+ const pair = replaceAll === undefined ? { oldText, newText } : { oldText, newText, replaceAll };
84
+ return { path, edits: [pair] };
85
+ },
86
+ param: (name) => params[name] ?? name,
87
+ });
88
+ }
89
+ /**
90
+ * edit({ path, edits: [{ oldText, newText }] }). Pi and Cloudflare Computer.
91
+ * Has no replaceAll parameter, so no message suggests one.
92
+ */
93
+ export function multiEditSignature(options = {}) {
94
+ const { describe, names } = checkDocs(options, "multiEditSignature", [
95
+ "path",
96
+ "edits",
97
+ "oldText",
98
+ "newText",
99
+ ]);
100
+ const keys = [names.path, names.edits];
101
+ const pairKeys = [names.oldText, names.newText];
102
+ const matchers = checkMatchers(options.matchers);
103
+ const pair = objectSchema([
104
+ [
105
+ names.oldText,
106
+ stringSchema(describe.oldText ??
107
+ "Text for one replacement. It must match one place in the original file and must not overlap another edit.", true),
108
+ ],
109
+ [
110
+ names.newText,
111
+ stringSchema(describe.newText ?? `Replacement text. Send an empty string to delete ${names.oldText}.`),
112
+ ],
113
+ ], pairKeys);
114
+ const schema = deepFreeze(objectSchema([
115
+ [names.path, pathSchema(describe.path ?? PATH_TEXT)],
116
+ [
117
+ names.edits,
118
+ {
119
+ type: "array",
120
+ minItems: 1,
121
+ items: pair,
122
+ description: describe.edits ??
123
+ "One or more replacements. Each is matched against the original file, not after earlier edits. Merge nearby changes into one edit.",
124
+ },
125
+ ],
126
+ ], keys));
127
+ const old = `${names.edits}[].${names.oldText}`;
128
+ return Object.freeze({
129
+ name: options.name ?? NAME,
130
+ description: options.description ??
131
+ `Edit a text file with one or more replacements in one call. Each \`${old}\` ` +
132
+ "must match exactly one place in the original file. Edits must not overlap or nest: " +
133
+ `merge nearby changes into one edit. ${matchingSentence(matchers, old)} ` +
134
+ `${NO_PREFIX} ${READ_FIRST} After an edit, the same file can be edited again without ` +
135
+ `another read. ${USE_WRITE}`,
136
+ schema,
137
+ toInput(input) {
138
+ const record = readObject(input, "edit input", keys, keys);
139
+ const path = readPath(record[names.path], names.path);
140
+ const edits = record[names.edits];
141
+ if (!Array.isArray(edits) || edits.length === 0) {
142
+ throw new TypeError(`${names.edits} must be a non-empty array`);
143
+ }
144
+ return {
145
+ path,
146
+ edits: edits.map((entry, index) => {
147
+ const label = `${names.edits}[${index}]`;
148
+ const item = readObject(entry, label, pairKeys, pairKeys, `${label}.`);
149
+ return {
150
+ oldText: readString(item[names.oldText], `${label}.${names.oldText}`, true),
151
+ newText: readString(item[names.newText], `${label}.${names.newText}`),
152
+ };
153
+ }),
154
+ };
155
+ },
156
+ param: (name) => name === "replaceAll" ? "" : (names[name] ?? name),
157
+ });
158
+ }
@@ -0,0 +1,6 @@
1
+ /** The `./signature` subpath: model-facing names, schemas, and descriptions for the three tools. */
2
+ export type { EditSignature, MutationSignature, PatchSignature, WriteSignature, } from "./contract.ts";
3
+ export { camelCaseEditSignature, defaultEditSignature, multiEditSignature } from "./edit.ts";
4
+ export { writeSignatureMessages } from "./messages.ts";
5
+ export { defaultPatchSignature, freeformPatchSignature } from "./patch.ts";
6
+ export { defaultWriteSignature, snakeCaseWriteSignature } from "./write.ts";
@@ -0,0 +1,4 @@
1
+ export { camelCaseEditSignature, defaultEditSignature, multiEditSignature } from "./edit.js";
2
+ export { writeSignatureMessages } from "./messages.js";
3
+ export { defaultPatchSignature, freeformPatchSignature } from "./patch.js";
4
+ export { defaultWriteSignature, snakeCaseWriteSignature } from "./write.js";
@@ -0,0 +1,3 @@
1
+ import type { Matcher } from "../contract/matcher.ts";
2
+ export declare function checkMatchers(matchers: unknown): readonly Matcher[];
3
+ export declare function matchingSentence(matchers: readonly Matcher[], old: string): string;
@@ -0,0 +1,25 @@
1
+ import { defaultEditMatchers } from "../matchers/index.js";
2
+ export function checkMatchers(matchers) {
3
+ if (matchers === undefined)
4
+ return defaultEditMatchers();
5
+ if (!Array.isArray(matchers) || matchers.length === 0) {
6
+ throw new TypeError("matchers must be a non-empty array");
7
+ }
8
+ for (const matcher of matchers) {
9
+ if (matcher === null ||
10
+ typeof matcher !== "object" ||
11
+ typeof matcher.describe !== "string" ||
12
+ typeof matcher.fuzzy !== "boolean") {
13
+ throw new TypeError("each matcher needs a describe string and a fuzzy flag");
14
+ }
15
+ }
16
+ return matchers;
17
+ }
18
+ export function matchingSentence(matchers, old) {
19
+ const folds = [...new Set(matchers.filter((m) => m.fuzzy).map((m) => m.describe))];
20
+ if (folds.length === 0) {
21
+ return `\`${old}\` must match the file exactly, including whitespace and indentation.`;
22
+ }
23
+ return (`\`${old}\` should match the file exactly. When it does not, a close match is used, ` +
24
+ `and the result says so. A close match may differ in: ${folds.join("; ")}.`);
25
+ }
@@ -0,0 +1,4 @@
1
+ import type { WriteMessageCatalog } from "../contract/messages.ts";
2
+ import type { MutationSignature } from "./contract.ts";
3
+ /** The `param` message for a signature's parameter names. Merge it under the host's messages. */
4
+ export declare function writeSignatureMessages(signature: MutationSignature<unknown>): Pick<WriteMessageCatalog, "param">;
@@ -0,0 +1,9 @@
1
+ /** The `param` message for a signature's parameter names. Merge it under the host's messages. */
2
+ export function writeSignatureMessages(signature) {
3
+ if (signature === null ||
4
+ typeof signature !== "object" ||
5
+ typeof signature.param !== "function") {
6
+ throw new TypeError("writeSignatureMessages needs a MutationSignature");
7
+ }
8
+ return Object.freeze({ param: (name) => signature.param(name) });
9
+ }
@@ -0,0 +1,6 @@
1
+ import type { SignatureDocs } from "@better-fs-tools/read";
2
+ import type { PatchSignature } from "./contract.ts";
3
+ /** apply_patch({ patch }) as JSON, with a short example in the description. */
4
+ export declare function defaultPatchSignature(options?: SignatureDocs<"patch">): PatchSignature;
5
+ /** defaultPatchSignature plus the Codex Lark grammar, for hosts with grammar tools. */
6
+ export declare function freeformPatchSignature(options?: SignatureDocs<"patch">): PatchSignature;
@@ -0,0 +1,55 @@
1
+ import { CODEX_PATCH_GRAMMAR } from "../patch/grammar.js";
2
+ import { checkDocs, deepFreeze, nonBlankSchema, objectSchema, readNonBlank, readObject, } from "./schema.js";
3
+ const EXAMPLE = [
4
+ "*** Begin Patch",
5
+ "*** Update File: src/app.ts",
6
+ "@@ export function main() {",
7
+ " const a = 1;",
8
+ "-const b = 2;",
9
+ "+const b = 3;",
10
+ "*** Add File: docs/notes.md",
11
+ "+# Notes",
12
+ "*** Delete File: old.txt",
13
+ "*** End Patch",
14
+ ].join("\n");
15
+ // Says nothing about JSON wrapping, so it fits hosts with and without grammar tools.
16
+ const patchDescription = (patch) => "Apply a patch that adds, updates, moves, or deletes text files. The input is one patch " +
17
+ `text (the \`${patch}\` parameter) in the Codex apply_patch format:\n\n` +
18
+ `${EXAMPLE}\n\n` +
19
+ "In an Update, each line starts with a space (context), `-` (remove), or `+` (add). " +
20
+ "`@@ <line>` names a line above the change to find the right place. Put " +
21
+ "`*** Move to: <path>` after an Update line to rename the file. Every line of an Add " +
22
+ "starts with `+`. Every hunk is checked before any file changes: when one fails, no file " +
23
+ "changes. Read each file you update or delete with the read tool first.";
24
+ /** apply_patch({ patch }) as JSON, with a short example in the description. */
25
+ export function defaultPatchSignature(options = {}) {
26
+ return patchSignature(options, "defaultPatchSignature");
27
+ }
28
+ /** defaultPatchSignature plus the Codex Lark grammar, for hosts with grammar tools. */
29
+ export function freeformPatchSignature(options = {}) {
30
+ return Object.freeze({
31
+ ...patchSignature(options, "freeformPatchSignature"),
32
+ grammar: Object.freeze({ lark: CODEX_PATCH_GRAMMAR }),
33
+ });
34
+ }
35
+ // One required string property, so Pi can use it as a grammar tool.
36
+ function patchSignature(options, label) {
37
+ const { describe, names } = checkDocs(options, label, ["patch"]);
38
+ const keys = [names.patch];
39
+ const schema = deepFreeze(objectSchema([
40
+ [
41
+ names.patch,
42
+ nonBlankSchema(describe.patch ?? "The whole patch, from *** Begin Patch to *** End Patch."),
43
+ ],
44
+ ], keys));
45
+ return Object.freeze({
46
+ name: options.name ?? "apply_patch",
47
+ description: options.description ?? patchDescription(names.patch),
48
+ schema,
49
+ toInput(input) {
50
+ const record = readObject(input, "apply_patch input", keys, keys);
51
+ return { patch: readNonBlank(record[names.patch], names.patch) };
52
+ },
53
+ param: (name) => (name === "patch" ? names.patch : name),
54
+ });
55
+ }
@@ -0,0 +1,19 @@
1
+ import type { JsonObject } from "@better-fs-tools/read";
2
+ export declare const PATH_PATTERN = "^[^\\u0000]*[^\\s\\u0000][^\\u0000]*$";
3
+ export declare const NON_BLANK_PATTERN = "^[\\s\\S]*\\S[\\s\\S]*$";
4
+ export declare function pathSchema(description: string): JsonObject;
5
+ export declare function stringSchema(description: string, nonEmpty?: boolean): JsonObject;
6
+ export declare function nonBlankSchema(description: string): JsonObject;
7
+ export declare function booleanSchema(description: string): JsonObject;
8
+ export declare function objectSchema(properties: readonly (readonly [string, JsonObject])[], required: readonly string[], description?: string): JsonObject;
9
+ export declare function readObject(input: unknown, label: string, keys: readonly string[], required: readonly string[], prefix?: string): Record<string, unknown>;
10
+ export declare function readPath(value: unknown, name: string): string;
11
+ export declare function readString(value: unknown, name: string, nonEmpty?: boolean): string;
12
+ export declare function readNonBlank(value: unknown, name: string): string;
13
+ export declare function readFlag(value: unknown, name: string): boolean | undefined;
14
+ export interface CheckedDocs<TParam extends string> {
15
+ readonly describe: Partial<Record<TParam, string>>;
16
+ readonly names: Readonly<Record<TParam, string>>;
17
+ }
18
+ export declare function checkDocs<TParam extends string>(options: unknown, label: string, params: readonly TParam[]): CheckedDocs<TParam>;
19
+ export declare function deepFreeze<T>(value: T): T;
@@ -0,0 +1,117 @@
1
+ // No lookaround: strict grammar engines may refuse one.
2
+ export const PATH_PATTERN = "^[^\\u0000]*[^\\s\\u0000][^\\u0000]*$";
3
+ const PATH_REGEX = new RegExp(PATH_PATTERN, "u");
4
+ export const NON_BLANK_PATTERN = "^[\\s\\S]*\\S[\\s\\S]*$";
5
+ const NON_BLANK_REGEX = new RegExp(NON_BLANK_PATTERN, "u");
6
+ export function pathSchema(description) {
7
+ return { type: "string", minLength: 1, pattern: PATH_PATTERN, description };
8
+ }
9
+ export function stringSchema(description, nonEmpty = false) {
10
+ return nonEmpty ? { type: "string", minLength: 1, description } : { type: "string", description };
11
+ }
12
+ export function nonBlankSchema(description) {
13
+ return { type: "string", minLength: 1, pattern: NON_BLANK_PATTERN, description };
14
+ }
15
+ export function booleanSchema(description) {
16
+ return { type: "boolean", description };
17
+ }
18
+ export function objectSchema(properties, required, description) {
19
+ return {
20
+ type: "object",
21
+ ...(description === undefined ? {} : { description }),
22
+ additionalProperties: false,
23
+ properties: Object.fromEntries(properties),
24
+ required: [...required],
25
+ };
26
+ }
27
+ export function readObject(input, label, keys, required, prefix = "") {
28
+ if (input === null || typeof input !== "object" || Array.isArray(input)) {
29
+ throw new TypeError(`${label} must be an object with ${keys.join(", ")}`);
30
+ }
31
+ const record = input;
32
+ for (const key of Object.keys(record)) {
33
+ if (!keys.includes(key)) {
34
+ throw new TypeError(`Unknown ${label} key: ${key}. Expected ${keys.join(", ")}`);
35
+ }
36
+ }
37
+ for (const key of required) {
38
+ if (record[key] === undefined)
39
+ throw new TypeError(`${prefix}${key} is required`);
40
+ }
41
+ return record;
42
+ }
43
+ export function readPath(value, name) {
44
+ if (typeof value !== "string" || !PATH_REGEX.test(value)) {
45
+ throw new TypeError(`${name} must be a non-blank string without NUL`);
46
+ }
47
+ return value;
48
+ }
49
+ export function readString(value, name, nonEmpty = false) {
50
+ if (typeof value !== "string")
51
+ throw new TypeError(`${name} must be a string`);
52
+ if (nonEmpty && value.length === 0)
53
+ throw new TypeError(`${name} must not be empty`);
54
+ return value;
55
+ }
56
+ export function readNonBlank(value, name) {
57
+ if (typeof value !== "string" || !NON_BLANK_REGEX.test(value)) {
58
+ throw new TypeError(`${name} must be a non-blank string`);
59
+ }
60
+ return value;
61
+ }
62
+ export function readFlag(value, name) {
63
+ if (value === undefined)
64
+ return undefined;
65
+ if (typeof value !== "boolean")
66
+ throw new TypeError(`${name} must be a boolean`);
67
+ return value;
68
+ }
69
+ export function checkDocs(options, label, params) {
70
+ if (options === null || typeof options !== "object" || Array.isArray(options)) {
71
+ throw new TypeError(`${label} options must be an object`);
72
+ }
73
+ const { name, description, describe = {}, names = {}, } = options;
74
+ if (name !== undefined && (typeof name !== "string" || name.trim() === "")) {
75
+ throw new TypeError(`${label} name must be a non-blank string`);
76
+ }
77
+ if (description !== undefined && typeof description !== "string") {
78
+ throw new TypeError(`${label} description must be a string`);
79
+ }
80
+ checkKeys(describe, "describe", label, params);
81
+ checkKeys(names, "names", label, params);
82
+ const resolved = {};
83
+ const seen = new Set();
84
+ for (const param of params) {
85
+ const value = names[param] ?? param;
86
+ if (value.trim() === "")
87
+ throw new TypeError(`names.${param} must be a non-blank string`);
88
+ if (seen.has(value))
89
+ throw new TypeError(`Parameter name ${value} is used twice`);
90
+ seen.add(value);
91
+ resolved[param] = value;
92
+ }
93
+ return {
94
+ describe: describe,
95
+ names: Object.freeze(resolved),
96
+ };
97
+ }
98
+ function checkKeys(map, key, label, params) {
99
+ if (map === null || typeof map !== "object" || Array.isArray(map)) {
100
+ throw new TypeError(`${label} ${key} must be an object`);
101
+ }
102
+ for (const [param, value] of Object.entries(map)) {
103
+ if (!params.includes(param)) {
104
+ throw new TypeError(`Unknown parameter in ${key}: ${param}. Expected ${params.join(", ")}`);
105
+ }
106
+ if (typeof value !== "string")
107
+ throw new TypeError(`${key}.${param} must be a string`);
108
+ }
109
+ }
110
+ export function deepFreeze(value) {
111
+ if (value !== null && typeof value === "object") {
112
+ for (const child of Object.values(value))
113
+ deepFreeze(child);
114
+ Object.freeze(value);
115
+ }
116
+ return value;
117
+ }