@openshain/tools 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 ADDED
@@ -0,0 +1,202 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
202
+
package/README.md ADDED
@@ -0,0 +1,7 @@
1
+ # @openshain/tools
2
+
3
+ The standard tool provider of openshain: files, CSV and Markdown, confined to the workspace.
4
+
5
+ Part of [openshain](https://github.com/openshain/openshain). Requires Bun 1.3 or later: the package ships TypeScript source. Documentation, in Japanese, lives in the repository.
6
+
7
+ License: Apache-2.0
package/package.json ADDED
@@ -0,0 +1,43 @@
1
+ {
2
+ "name": "@openshain/tools",
3
+ "version": "0.1.0",
4
+ "description": "Standard tool provider: filesystem, CSV, Markdown, documents, email",
5
+ "keywords": [
6
+ "openshain",
7
+ "agent",
8
+ "runtime",
9
+ "mcp",
10
+ "accounting",
11
+ "japan"
12
+ ],
13
+ "author": "Hiroki Nakatani",
14
+ "license": "Apache-2.0",
15
+ "homepage": "https://github.com/openshain/openshain",
16
+ "repository": {
17
+ "type": "git",
18
+ "url": "git+https://github.com/openshain/openshain.git",
19
+ "directory": "packages/tools"
20
+ },
21
+ "bugs": "https://github.com/openshain/openshain/issues",
22
+ "type": "module",
23
+ "engines": {
24
+ "bun": ">=1.3"
25
+ },
26
+ "files": [
27
+ "src",
28
+ "!src/**/*.test.ts",
29
+ "README.md",
30
+ "LICENSE"
31
+ ],
32
+ "exports": {
33
+ ".": "./src/index.ts"
34
+ },
35
+ "publishConfig": {
36
+ "access": "public"
37
+ },
38
+ "dependencies": {
39
+ "@openshain/core": "0.1.0",
40
+ "csv-parse": "7.0.2",
41
+ "csv-stringify": "6.8.3"
42
+ }
43
+ }
package/src/index.ts ADDED
@@ -0,0 +1,2 @@
1
+ // @openshain/tools: Standard tool provider: filesystem, CSV, Markdown, documents, email
2
+ export { MAX_READ_BYTES, standardTools } from "./standard.ts";
@@ -0,0 +1,800 @@
1
+ import { createHash } from "node:crypto";
2
+ import { constants } from "node:fs";
3
+ import { type FileHandle, mkdir, open, readdir, stat } from "node:fs/promises";
4
+ import { dirname, join, relative } from "node:path";
5
+ import {
6
+ RESERVED_PATHS,
7
+ resolveWorkspacePath,
8
+ type ToolContext,
9
+ type ToolDefinition,
10
+ type ToolProvider,
11
+ type ToolResult,
12
+ } from "@openshain/core";
13
+ import { parse } from "csv-parse/sync";
14
+ import { stringify } from "csv-stringify/sync";
15
+
16
+ /** Files larger than this are not opened at all. What a tool returns is a window, far smaller. */
17
+ export const MAX_READ_BYTES = 1024 * 1024;
18
+ /** The same limit on writes, so that nothing a tool writes is too large for a tool to open. */
19
+ export const MAX_WRITE_BYTES = MAX_READ_BYTES;
20
+
21
+ /** The window each observing tool returns when the model does not ask for another one. */
22
+ export const DEFAULT_WINDOW = {
23
+ fs_list: 200,
24
+ fs_search: 100,
25
+ fs_read: 200,
26
+ csv_read: 50,
27
+ csv_aggregate: 100,
28
+ markdown_read: 100,
29
+ } as const;
30
+
31
+ /** fs_search gives up after this many files so that a huge tree cannot stall a Work. */
32
+ const MAX_SEARCH_FILES = 2000;
33
+ /** fs_search returns at most this many characters of a matching line. */
34
+ const MAX_MATCH_TEXT = 200;
35
+
36
+ const pathProperty = {
37
+ type: "string",
38
+ description: "Path relative to the workspace root, for example receipts/2026-07.csv.",
39
+ };
40
+
41
+ function offsetProperty(unit: string) {
42
+ return {
43
+ type: "integer",
44
+ minimum: 0,
45
+ default: 0,
46
+ description: `How many ${unit} to skip before the window starts. 0 is the start.`,
47
+ };
48
+ }
49
+
50
+ function limitProperty(unit: string, fallback: number, maximum: number) {
51
+ return {
52
+ type: "integer",
53
+ minimum: 1,
54
+ maximum,
55
+ default: fallback,
56
+ description: `How many ${unit} to return at most (default ${fallback}).`,
57
+ };
58
+ }
59
+
60
+ const definitions: ToolDefinition[] = [
61
+ {
62
+ name: "fs_list",
63
+ description:
64
+ 'List one directory inside the workspace ("." is the root). Returns up to limit entries (default 200) with name, type and size in bytes, the total number of entries and whether the list was cut short. pattern keeps only the names matching a glob such as *.csv. Not recursive; to find files by what they contain use fs_search.',
65
+ inputSchema: {
66
+ type: "object",
67
+ properties: {
68
+ path: { ...pathProperty, default: "." },
69
+ pattern: {
70
+ type: "string",
71
+ minLength: 1,
72
+ description:
73
+ "Wildcard on the entry name, for example *.csv or 2026-*. * matches any run of characters and ? one character.",
74
+ },
75
+ limit: limitProperty("entries", DEFAULT_WINDOW.fs_list, 1000),
76
+ },
77
+ additionalProperties: false,
78
+ },
79
+ effect: "observe",
80
+ },
81
+ {
82
+ name: "fs_search",
83
+ description:
84
+ "Search the text files inside the workspace for a pattern. In the pattern, * matches any run of characters and ? one character; everything else matches literally, so it is not a regular expression. Returns up to limit matches (default 100) with the file path, the line number and the matching line, and whether more matches were cut off. path narrows the search to a directory or to a single file. Hidden entries, symlinks, binary files and files over 1 MiB are skipped.",
85
+ inputSchema: {
86
+ type: "object",
87
+ properties: {
88
+ pattern: {
89
+ type: "string",
90
+ minLength: 1,
91
+ description:
92
+ "Text to look for. * matches any run of characters and ? one character; other characters, including . ( ) [ ] and |, match literally.",
93
+ },
94
+ path: {
95
+ ...pathProperty,
96
+ default: ".",
97
+ description:
98
+ "Directory or file to search, relative to the workspace root. Defaults to the whole workspace.",
99
+ },
100
+ limit: limitProperty("matches", DEFAULT_WINDOW.fs_search, 1000),
101
+ },
102
+ required: ["pattern"],
103
+ additionalProperties: false,
104
+ },
105
+ effect: "observe",
106
+ },
107
+ {
108
+ name: "fs_read",
109
+ description:
110
+ "Read a window of lines from a text file inside the workspace. Returns the window (default the first 200 lines) together with the file's line count and whether more lines remain; move the window with offset. For a CSV file use csv_read, and for totals use csv_aggregate rather than paging through the rows.",
111
+ inputSchema: {
112
+ type: "object",
113
+ properties: {
114
+ path: pathProperty,
115
+ offset: offsetProperty("lines"),
116
+ limit: limitProperty("lines", DEFAULT_WINDOW.fs_read, 2000),
117
+ },
118
+ required: ["path"],
119
+ additionalProperties: false,
120
+ },
121
+ effect: "observe",
122
+ },
123
+ {
124
+ name: "fs_write",
125
+ description:
126
+ "Write a text file inside the workspace, creating or replacing it. Up to 1 MiB. Returns the file's path and the hash of its contents.",
127
+ inputSchema: {
128
+ type: "object",
129
+ properties: { path: pathProperty, content: { type: "string" } },
130
+ required: ["path", "content"],
131
+ additionalProperties: false,
132
+ },
133
+ effect: "mutate",
134
+ },
135
+ {
136
+ name: "csv_read",
137
+ description:
138
+ "Read a CSV file with a header row. Returns the column names, the number of data rows and a window of rows (default the first 50) as one object per row; move the window with offset and limit. Use it to see what a file looks like. For sums, counts, minimums or maximums call csv_aggregate instead of reading every row.",
139
+ inputSchema: {
140
+ type: "object",
141
+ properties: {
142
+ path: pathProperty,
143
+ offset: offsetProperty("rows"),
144
+ limit: limitProperty("rows", DEFAULT_WINDOW.csv_read, 500),
145
+ },
146
+ required: ["path"],
147
+ additionalProperties: false,
148
+ },
149
+ effect: "observe",
150
+ },
151
+ {
152
+ name: "csv_aggregate",
153
+ description:
154
+ "Count and total the rows of a CSV file with a header row, over the whole file in one call. group_by names the columns to group by (omit it for a single group), sum names the numeric columns to total, filter keeps only the rows whose columns equal the given values. Returns one entry per group, ordered by the group's values, with its row count and, for each summed column, the sum, min, max, the number of numeric cells and the number of cells skipped as non-numeric; and overall, the same figures over every matched row. Take a grand total from overall instead of adding the groups yourself. Cells such as 1,200, ¥300 or full-width 123 count as numbers.",
155
+ inputSchema: {
156
+ type: "object",
157
+ properties: {
158
+ path: pathProperty,
159
+ group_by: {
160
+ type: "array",
161
+ items: { type: "string" },
162
+ description: "Columns to group the rows by. Omit to treat the whole file as one group.",
163
+ },
164
+ sum: {
165
+ type: "array",
166
+ items: { type: "string" },
167
+ description: "Numeric columns to total.",
168
+ },
169
+ filter: {
170
+ type: "array",
171
+ items: {
172
+ type: "object",
173
+ properties: { column: { type: "string" }, equals: { type: "string" } },
174
+ required: ["column", "equals"],
175
+ additionalProperties: false,
176
+ },
177
+ description: "Keep only the rows where every listed column equals the given value.",
178
+ },
179
+ limit: limitProperty("groups", DEFAULT_WINDOW.csv_aggregate, 1000),
180
+ },
181
+ required: ["path"],
182
+ additionalProperties: false,
183
+ },
184
+ effect: "observe",
185
+ },
186
+ {
187
+ name: "csv_write",
188
+ description:
189
+ "Write rows to a CSV file with a header row, creating or replacing it. Up to 1 MiB. A cell that starts with =, + or @ gets a leading apostrophe so that a spreadsheet does not run it as a formula. Returns the file's path and the hash of its contents.",
190
+ inputSchema: {
191
+ type: "object",
192
+ properties: {
193
+ path: pathProperty,
194
+ rows: {
195
+ type: "array",
196
+ items: { type: "object", additionalProperties: { type: "string" } },
197
+ description: "One object per row. Keys become the header.",
198
+ },
199
+ columns: {
200
+ type: "array",
201
+ items: { type: "string" },
202
+ description: "Column order. Defaults to the keys of the first row.",
203
+ },
204
+ },
205
+ required: ["path", "rows"],
206
+ additionalProperties: false,
207
+ },
208
+ effect: "mutate",
209
+ },
210
+ {
211
+ name: "markdown_read",
212
+ description:
213
+ "Read a Markdown file inside the workspace. Returns the outline of headings with their line numbers and the first lines of the file (default 100). With section set to a heading's text, returns that section instead: from the heading up to the next heading of the same or a higher level. For any other range of lines use fs_read with offset.",
214
+ inputSchema: {
215
+ type: "object",
216
+ properties: {
217
+ path: pathProperty,
218
+ section: {
219
+ type: "string",
220
+ minLength: 1,
221
+ description: "Text of the heading whose section to return.",
222
+ },
223
+ limit: limitProperty("lines", DEFAULT_WINDOW.markdown_read, 2000),
224
+ },
225
+ required: ["path"],
226
+ additionalProperties: false,
227
+ },
228
+ effect: "observe",
229
+ },
230
+ ];
231
+
232
+ /** The tools every workspace gets: files, CSV and Markdown, all confined to the workspace. */
233
+ export function standardTools(): ToolProvider {
234
+ return {
235
+ id: "standard",
236
+ listTools: async () => definitions,
237
+ async call(call, ctx) {
238
+ const input = (call.input ?? {}) as Record<string, unknown>;
239
+ const path = typeof input.path === "string" ? input.path : ".";
240
+ switch (call.name) {
241
+ case "fs_list":
242
+ return fsList(
243
+ ctx,
244
+ path,
245
+ nonEmpty(input.pattern),
246
+ count(input.limit, DEFAULT_WINDOW.fs_list),
247
+ );
248
+ case "fs_search":
249
+ return fsSearch(ctx, path, input);
250
+ case "fs_read":
251
+ return fsRead(
252
+ ctx,
253
+ path,
254
+ count(input.offset, 0),
255
+ count(input.limit, DEFAULT_WINDOW.fs_read),
256
+ );
257
+ case "fs_write":
258
+ return fsWrite(ctx, path, String(input.content ?? ""));
259
+ case "csv_read":
260
+ return csvRead(
261
+ ctx,
262
+ path,
263
+ count(input.offset, 0),
264
+ count(input.limit, DEFAULT_WINDOW.csv_read),
265
+ );
266
+ case "csv_aggregate":
267
+ return csvAggregate(ctx, path, input);
268
+ case "csv_write":
269
+ return csvWrite(ctx, path, input.rows, input.columns);
270
+ case "markdown_read":
271
+ return markdownRead(
272
+ ctx,
273
+ path,
274
+ nonEmpty(input.section),
275
+ count(input.limit, DEFAULT_WINDOW.markdown_read),
276
+ );
277
+ default:
278
+ throw new Error(`the standard tools do not provide "${call.name}"`);
279
+ }
280
+ },
281
+ };
282
+ }
283
+
284
+ async function fsList(
285
+ ctx: ToolContext,
286
+ path: string,
287
+ pattern: string | undefined,
288
+ limit: number,
289
+ ): Promise<ToolResult> {
290
+ const resolved = await resolveWorkspacePath(ctx.workspaceRoot, path);
291
+ const root = await resolveWorkspacePath(ctx.workspaceRoot, ".");
292
+ const matches = pattern === undefined ? () => true : wildcardMatcher(pattern);
293
+ const entries = (await readdir(resolved, { withFileTypes: true }))
294
+ .filter((entry) => visible(entry.name, resolved === root))
295
+ .filter((entry) => matches(entry.name))
296
+ .sort(byName);
297
+ const window = await Promise.all(
298
+ entries.slice(0, limit).map(async (entry) => {
299
+ if (entry.isDirectory()) return { name: entry.name, type: "directory" };
300
+ if (!entry.isFile()) return { name: entry.name, type: "other" };
301
+ const { size } = await stat(join(resolved, entry.name));
302
+ return { name: entry.name, type: "file", size };
303
+ }),
304
+ );
305
+ return json(
306
+ { path, entries: window, total: entries.length, truncated: window.length < entries.length },
307
+ path,
308
+ );
309
+ }
310
+
311
+ async function fsSearch(
312
+ ctx: ToolContext,
313
+ path: string,
314
+ input: Record<string, unknown>,
315
+ ): Promise<ToolResult> {
316
+ const pattern = text(input.pattern) ?? "";
317
+ if (pattern === "") return failure("pattern must not be empty");
318
+ const limit = count(input.limit, DEFAULT_WINDOW.fs_search);
319
+ const test = /[*?]/.test(pattern)
320
+ ? wildcardMatcher(`*${pattern}*`)
321
+ : (line: string) => line.includes(pattern);
322
+
323
+ const resolved = await resolveWorkspacePath(ctx.workspaceRoot, path);
324
+ const root = await resolveWorkspacePath(ctx.workspaceRoot, ".");
325
+ const matches: { path: string; line: number; text: string }[] = [];
326
+ let filesSearched = 0;
327
+ let filesSkipped = 0;
328
+ let truncated = false;
329
+ const files = (await stat(resolved)).isFile() ? [resolved] : walk(resolved, root);
330
+ search: for await (const file of files) {
331
+ if (filesSearched + filesSkipped >= MAX_SEARCH_FILES) {
332
+ truncated = true;
333
+ break;
334
+ }
335
+ const content = await readSearchable(file);
336
+ if (content === undefined) {
337
+ filesSkipped += 1;
338
+ continue;
339
+ }
340
+ filesSearched += 1;
341
+ const lines = splitLines(content);
342
+ for (let i = 0; i < lines.length; i++) {
343
+ const line = lines[i] ?? "";
344
+ if (!test(line)) continue;
345
+ if (matches.length >= limit) {
346
+ truncated = true;
347
+ break search;
348
+ }
349
+ matches.push({ path: relative(root, file), line: i + 1, text: clip(line) });
350
+ }
351
+ }
352
+ return json({ pattern, path, matches, filesSearched, filesSkipped, truncated }, path);
353
+ }
354
+
355
+ async function fsRead(
356
+ ctx: ToolContext,
357
+ path: string,
358
+ offset: number,
359
+ limit: number,
360
+ ): Promise<ToolResult> {
361
+ const content = await readText(ctx, path);
362
+ const lines = splitLines(content);
363
+ const window = lines.slice(offset, offset + limit);
364
+ return {
365
+ content: [
366
+ {
367
+ type: "json",
368
+ value: {
369
+ path,
370
+ offset,
371
+ returned: window.length,
372
+ lines: lines.length,
373
+ truncated: offset + window.length < lines.length,
374
+ bytes: Buffer.byteLength(content, "utf8"),
375
+ },
376
+ },
377
+ { type: "text", text: joinLines(window) },
378
+ ],
379
+ observation: observed(path),
380
+ };
381
+ }
382
+
383
+ async function fsWrite(ctx: ToolContext, path: string, content: string): Promise<ToolResult> {
384
+ const after = await writeText(ctx, path, content);
385
+ return { content: [{ type: "text", text: `wrote ${after.path}` }], after: [after] };
386
+ }
387
+
388
+ async function csvRead(
389
+ ctx: ToolContext,
390
+ path: string,
391
+ offset: number,
392
+ limit: number,
393
+ ): Promise<ToolResult> {
394
+ const { columns, rows } = await readCsv(ctx, path);
395
+ const window = rows.slice(offset, offset + limit);
396
+ return json(
397
+ {
398
+ path,
399
+ columns,
400
+ rowCount: rows.length,
401
+ offset,
402
+ returned: window.length,
403
+ truncated: offset + window.length < rows.length,
404
+ rows: window,
405
+ },
406
+ path,
407
+ );
408
+ }
409
+
410
+ interface Totals {
411
+ sum: number;
412
+ min: number | null;
413
+ max: number | null;
414
+ count: number;
415
+ skipped: number;
416
+ }
417
+
418
+ async function csvAggregate(
419
+ ctx: ToolContext,
420
+ path: string,
421
+ input: Record<string, unknown>,
422
+ ): Promise<ToolResult> {
423
+ const groupBy = strings(input.group_by);
424
+ const sums = strings(input.sum);
425
+ const filters = Array.isArray(input.filter)
426
+ ? (input.filter as { column: unknown; equals: unknown }[]).map((f) => ({
427
+ column: String(f.column),
428
+ equals: String(f.equals),
429
+ }))
430
+ : [];
431
+ const limit = count(input.limit, DEFAULT_WINDOW.csv_aggregate);
432
+ const { columns, rows } = await readCsv(ctx, path);
433
+ for (const column of [...groupBy, ...sums, ...filters.map((f) => f.column)]) {
434
+ if (!columns.includes(column)) {
435
+ return failure(`"${path}" has no column "${column}"; its columns are ${columns.join(", ")}`);
436
+ }
437
+ }
438
+
439
+ const matched = rows.filter((row) => filters.every((f) => (row[f.column] ?? "") === f.equals));
440
+ const newTotals = (): Record<string, Totals> =>
441
+ Object.fromEntries(
442
+ sums.map((column) => [column, { sum: 0, min: null, max: null, count: 0, skipped: 0 }]),
443
+ );
444
+ const add = (totals: Record<string, Totals>, row: Record<string, string>) => {
445
+ for (const column of sums) {
446
+ const t = totals[column];
447
+ if (t) accumulate(t, row[column] ?? "");
448
+ }
449
+ };
450
+ const groups = new Map<
451
+ string,
452
+ { values: string[]; rows: number; totals: Record<string, Totals> }
453
+ >();
454
+ const overall = newTotals();
455
+ for (const row of matched) {
456
+ const values = groupBy.map((column) => row[column] ?? "");
457
+ const key = JSON.stringify(values);
458
+ let group = groups.get(key);
459
+ if (!group) {
460
+ group = { values, rows: 0, totals: newTotals() };
461
+ groups.set(key, group);
462
+ }
463
+ group.rows += 1;
464
+ add(group.totals, row);
465
+ add(overall, row);
466
+ }
467
+
468
+ const tidyTotals = (totals: Record<string, Totals>) =>
469
+ Object.fromEntries(
470
+ Object.entries(totals).map(([column, t]) => [column, { ...t, sum: tidy(t.sum) }]),
471
+ );
472
+ const sorted = [...groups.values()].sort((a, b) => compareValues(a.values, b.values));
473
+ const window = sorted.slice(0, limit).map((group) => ({
474
+ group: Object.fromEntries(groupBy.map((column, i) => [column, group.values[i] ?? ""])),
475
+ rows: group.rows,
476
+ totals: tidyTotals(group.totals),
477
+ }));
478
+ return json(
479
+ {
480
+ path,
481
+ rowCount: rows.length,
482
+ matched: matched.length,
483
+ groupCount: sorted.length,
484
+ groups: window,
485
+ // The same figures over every matched row, so a grand total is never added by hand.
486
+ overall: { rows: matched.length, totals: tidyTotals(overall) },
487
+ truncated: window.length < sorted.length,
488
+ },
489
+ path,
490
+ );
491
+ }
492
+
493
+ async function csvWrite(
494
+ ctx: ToolContext,
495
+ path: string,
496
+ rows: unknown,
497
+ columns: unknown,
498
+ ): Promise<ToolResult> {
499
+ if (!Array.isArray(rows)) throw new Error("rows must be an array of objects");
500
+ const safeRows = (rows as Record<string, unknown>[]).map((row) =>
501
+ Object.fromEntries(Object.entries(row).map(([key, value]) => [key, neutralizeFormula(value)])),
502
+ );
503
+ const content = stringify(safeRows, {
504
+ header: true,
505
+ ...(Array.isArray(columns) && { columns: columns as string[] }),
506
+ });
507
+ const after = await writeText(ctx, path, content);
508
+ return {
509
+ content: [{ type: "text", text: `wrote ${rows.length} rows to ${after.path}` }],
510
+ after: [after],
511
+ };
512
+ }
513
+
514
+ async function markdownRead(
515
+ ctx: ToolContext,
516
+ path: string,
517
+ section: string | undefined,
518
+ limit: number,
519
+ ): Promise<ToolResult> {
520
+ const lines = splitLines(await readText(ctx, path));
521
+ const headings = outline(lines);
522
+ let from = 0;
523
+ let end = lines.length;
524
+ let picked: { text: string; level: number; line: number; lines: number } | undefined;
525
+ if (section !== undefined) {
526
+ const heading =
527
+ headings.find((h) => h.text === section) ?? headings.find((h) => h.text.includes(section));
528
+ if (!heading) {
529
+ const known = headings.map((h) => h.text).join(", ");
530
+ return failure(`"${path}" has no heading matching "${section}"; its headings are: ${known}`);
531
+ }
532
+ const next = headings.find((h) => h.line > heading.line && h.level <= heading.level);
533
+ from = heading.line - 1;
534
+ end = next ? next.line - 1 : lines.length;
535
+ picked = { text: heading.text, level: heading.level, line: heading.line, lines: end - from };
536
+ }
537
+ const window = lines.slice(from, Math.min(end, from + limit));
538
+ return {
539
+ content: [
540
+ {
541
+ type: "json",
542
+ value: {
543
+ path,
544
+ lines: lines.length,
545
+ headings,
546
+ ...(picked && { section: picked }),
547
+ offset: from,
548
+ returned: window.length,
549
+ truncated: from + window.length < end,
550
+ },
551
+ },
552
+ { type: "text", text: joinLines(window) },
553
+ ],
554
+ observation: observed(path),
555
+ };
556
+ }
557
+
558
+ /** Headings outside fenced code blocks, with 1-based line numbers. */
559
+ function outline(lines: string[]): { level: number; text: string; line: number }[] {
560
+ const headings: { level: number; text: string; line: number }[] = [];
561
+ let fence: string | undefined;
562
+ for (let i = 0; i < lines.length; i++) {
563
+ const line = lines[i] ?? "";
564
+ const fenceMatch = /^\s*(`{3,}|~{3,})/.exec(line);
565
+ if (fenceMatch) {
566
+ const marker = fenceMatch[1] ?? "";
567
+ if (!fence) fence = marker[0];
568
+ else if (marker[0] === fence) fence = undefined;
569
+ continue;
570
+ }
571
+ if (fence) continue;
572
+ const match = /^(#{1,6})\s+(.+?)\s*#*\s*$/.exec(line);
573
+ if (match) headings.push({ level: match[1]?.length ?? 1, text: match[2] ?? "", line: i + 1 });
574
+ }
575
+ return headings;
576
+ }
577
+
578
+ async function readCsv(
579
+ ctx: ToolContext,
580
+ path: string,
581
+ ): Promise<{ columns: string[]; rows: Record<string, string>[] }> {
582
+ const content = await readText(ctx, path);
583
+ const records = parse(content, { bom: true, skip_empty_lines: true }) as string[][];
584
+ const [header, ...body] = records;
585
+ const columns = header ?? [];
586
+ const rows = body.map((cells) =>
587
+ Object.fromEntries(columns.map((column, i) => [column, cells[i] ?? ""])),
588
+ );
589
+ return { columns, rows };
590
+ }
591
+
592
+ /**
593
+ * Reads a text file through one descriptor: the size check and the read see the same file,
594
+ * so a swap between the two cannot slip a larger file past the limit.
595
+ */
596
+ async function readText(ctx: ToolContext, path: string): Promise<string> {
597
+ const resolved = await resolveWorkspacePath(ctx.workspaceRoot, path);
598
+ let handle: FileHandle;
599
+ try {
600
+ handle = await open(resolved, "r");
601
+ } catch (err) {
602
+ throw new Error(`cannot read "${path}": ${(err as NodeJS.ErrnoException).code ?? "error"}`);
603
+ }
604
+ try {
605
+ const { size } = await handle.stat();
606
+ if (size > MAX_READ_BYTES) {
607
+ throw new Error(`"${path}" is too large to read (${size} bytes, limit ${MAX_READ_BYTES})`);
608
+ }
609
+ return await handle.readFile("utf8");
610
+ } finally {
611
+ await handle.close();
612
+ }
613
+ }
614
+
615
+ /** Writes through a descriptor opened with O_NOFOLLOW, so the final component may not be a symlink. */
616
+ async function writeText(
617
+ ctx: ToolContext,
618
+ path: string,
619
+ content: string,
620
+ ): Promise<{ path: string; sha256: string }> {
621
+ const bytes = Buffer.byteLength(content, "utf8");
622
+ if (bytes > MAX_WRITE_BYTES) {
623
+ throw new Error(`"${path}" is too large to write (${bytes} bytes, limit ${MAX_WRITE_BYTES})`);
624
+ }
625
+ const resolved = await resolveWorkspacePath(ctx.workspaceRoot, path);
626
+ const root = await resolveWorkspacePath(ctx.workspaceRoot, ".");
627
+ await mkdir(dirname(resolved), { recursive: true });
628
+ const flags =
629
+ constants.O_WRONLY | constants.O_CREAT | constants.O_TRUNC | (constants.O_NOFOLLOW ?? 0);
630
+ const handle = await open(resolved, flags, 0o644);
631
+ try {
632
+ await handle.writeFile(content, "utf8");
633
+ } finally {
634
+ await handle.close();
635
+ }
636
+ return {
637
+ path: relative(root, resolved),
638
+ sha256: createHash("sha256").update(content).digest("hex"),
639
+ };
640
+ }
641
+
642
+ /** Regular files below `dir`, in code point order, skipping hidden entries, symlinks and reserved paths. */
643
+ async function* walk(dir: string, root: string): AsyncGenerator<string> {
644
+ const entries = (await readdir(dir, { withFileTypes: true }))
645
+ .filter((entry) => visible(entry.name, dir === root))
646
+ .sort(byName);
647
+ for (const entry of entries) {
648
+ const full = join(dir, entry.name);
649
+ if (entry.isDirectory()) yield* walk(full, root);
650
+ else if (entry.isFile()) yield full;
651
+ }
652
+ }
653
+
654
+ function visible(name: string, atRoot: boolean): boolean {
655
+ if (name.startsWith(".")) return false;
656
+ return (
657
+ !atRoot || !RESERVED_PATHS.some((reserved) => reserved.toLowerCase() === name.toLowerCase())
658
+ );
659
+ }
660
+
661
+ function byName(a: { name: string }, b: { name: string }): number {
662
+ return a.name < b.name ? -1 : a.name > b.name ? 1 : 0;
663
+ }
664
+
665
+ function compareValues(a: string[], b: string[]): number {
666
+ for (let i = 0; i < Math.max(a.length, b.length); i++) {
667
+ const x = a[i] ?? "";
668
+ const y = b[i] ?? "";
669
+ if (x !== y) return x < y ? -1 : 1;
670
+ }
671
+ return 0;
672
+ }
673
+
674
+ /**
675
+ * Matches a whole string against a pattern in which `*` stands for any run of characters and `?`
676
+ * for one character; everything else is literal. Takes time proportional to the pattern times the
677
+ * subject, so a pattern the model writes cannot stall the run the way a backtracking regular
678
+ * expression can.
679
+ */
680
+ function wildcardMatcher(pattern: string): (subject: string) => boolean {
681
+ const p = [...pattern];
682
+ return (subject) => {
683
+ const s = [...subject];
684
+ let pi = 0;
685
+ let si = 0;
686
+ let starP = -1;
687
+ let starS = 0;
688
+ while (si < s.length) {
689
+ if (pi < p.length && (p[pi] === "?" || p[pi] === s[si])) {
690
+ pi += 1;
691
+ si += 1;
692
+ } else if (pi < p.length && p[pi] === "*") {
693
+ starP = pi;
694
+ starS = si;
695
+ pi += 1;
696
+ } else if (starP >= 0) {
697
+ pi = starP + 1;
698
+ starS += 1;
699
+ si = starS;
700
+ } else {
701
+ return false;
702
+ }
703
+ }
704
+ while (pi < p.length && p[pi] === "*") pi += 1;
705
+ return pi === p.length;
706
+ };
707
+ }
708
+
709
+ /**
710
+ * The text of a file the search may read, or undefined for one it skips: over 1 MiB, or with
711
+ * a NUL byte in the first 8 KiB. Size, head and content all come from one descriptor.
712
+ */
713
+ async function readSearchable(file: string): Promise<string | undefined> {
714
+ const handle = await open(file, "r");
715
+ try {
716
+ if ((await handle.stat()).size > MAX_READ_BYTES) return undefined;
717
+ const head = Buffer.alloc(8192);
718
+ const { bytesRead } = await handle.read(head, 0, head.length, 0);
719
+ if (head.subarray(0, bytesRead).includes(0)) return undefined;
720
+ return await handle.readFile("utf8");
721
+ } finally {
722
+ await handle.close();
723
+ }
724
+ }
725
+
726
+ /** Cells such as 1,200, ¥300, 123 or -50.5 are numbers; anything else is skipped. */
727
+ function toNumber(cell: string): number | undefined {
728
+ const cleaned = cell.normalize("NFKC").replace(/[,¥$\s]/g, "");
729
+ return /^[-+]?(\d+\.?\d*|\.\d+)$/.test(cleaned) ? Number(cleaned) : undefined;
730
+ }
731
+
732
+ function accumulate(totals: Totals, cell: string): void {
733
+ const value = toNumber(cell);
734
+ if (value === undefined) {
735
+ totals.skipped += 1;
736
+ return;
737
+ }
738
+ totals.sum += value;
739
+ totals.count += 1;
740
+ totals.min = totals.min === null ? value : Math.min(totals.min, value);
741
+ totals.max = totals.max === null ? value : Math.max(totals.max, value);
742
+ }
743
+
744
+ /** Hides the noise of binary floating point in a sum of decimals, such as 0.1 + 0.2. Integers stay exact. */
745
+ function tidy(n: number): number {
746
+ return Number.isInteger(n) ? n : Number(n.toPrecision(15));
747
+ }
748
+
749
+ /** Lines of a text, without the empty line a trailing newline would add. */
750
+ function splitLines(content: string): string[] {
751
+ const lines = content.split("\n");
752
+ if (lines.at(-1) === "") lines.pop();
753
+ return lines;
754
+ }
755
+
756
+ function joinLines(lines: string[]): string {
757
+ return lines.length === 0 ? "" : `${lines.join("\n")}\n`;
758
+ }
759
+
760
+ function clip(line: string): string {
761
+ const chars = [...line];
762
+ return chars.length > MAX_MATCH_TEXT ? `${chars.slice(0, MAX_MATCH_TEXT).join("")}…` : line;
763
+ }
764
+
765
+ function text(value: unknown): string | undefined {
766
+ return typeof value === "string" ? value : undefined;
767
+ }
768
+
769
+ function nonEmpty(value: unknown): string | undefined {
770
+ return typeof value === "string" && value !== "" ? value : undefined;
771
+ }
772
+
773
+ function count(value: unknown, fallback: number): number {
774
+ return typeof value === "number" && Number.isInteger(value) && value >= 0 ? value : fallback;
775
+ }
776
+
777
+ function strings(value: unknown): string[] {
778
+ return Array.isArray(value) ? value.filter((v): v is string => typeof v === "string") : [];
779
+ }
780
+
781
+ function json(value: unknown, path: string): ToolResult {
782
+ return { content: [{ type: "json", value }], observation: observed(path) };
783
+ }
784
+
785
+ function failure(message: string): ToolResult {
786
+ return { content: [{ type: "text", text: message }], isError: true };
787
+ }
788
+
789
+ /**
790
+ * Spreadsheets run a cell that starts with =, +, @ or - as a formula. A leading apostrophe keeps
791
+ * it text. Negative numbers are left alone.
792
+ */
793
+ function neutralizeFormula(value: unknown): unknown {
794
+ if (typeof value !== "string") return value;
795
+ return /^[=+@\t\r]/.test(value) || /^-(?![0-9.])/.test(value) ? `'${value}` : value;
796
+ }
797
+
798
+ function observed(path: string): { source: string; retrievedAt: string } {
799
+ return { source: path, retrievedAt: new Date().toISOString() };
800
+ }