@openshain/tools 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ export { MAX_READ_BYTES, standardTools } from "./standard.ts";
package/dist/index.js ADDED
@@ -0,0 +1,2 @@
1
+ // @openshain/tools: Standard tool provider: filesystem, CSV, Markdown, documents, email
2
+ export { MAX_READ_BYTES, standardTools } from "./standard.js";
@@ -0,0 +1,16 @@
1
+ import { type ToolProvider } from "@openshain/core";
2
+ /** Files larger than this are not opened at all. What a tool returns is a window, far smaller. */
3
+ export declare const MAX_READ_BYTES: number;
4
+ /** The same limit on writes, so that nothing a tool writes is too large for a tool to open. */
5
+ export declare const MAX_WRITE_BYTES: number;
6
+ /** The window each observing tool returns when the model does not ask for another one. */
7
+ export declare const DEFAULT_WINDOW: {
8
+ readonly fs_list: 200;
9
+ readonly fs_search: 100;
10
+ readonly fs_read: 200;
11
+ readonly csv_read: 50;
12
+ readonly csv_aggregate: 100;
13
+ readonly markdown_read: 100;
14
+ };
15
+ /** The tools every workspace gets: files, CSV and Markdown, all confined to the workspace. */
16
+ export declare function standardTools(): ToolProvider;
@@ -0,0 +1,669 @@
1
+ import { createHash } from "node:crypto";
2
+ import { constants } from "node:fs";
3
+ import { mkdir, open, readdir, stat } from "node:fs/promises";
4
+ import { dirname, join, relative } from "node:path";
5
+ import { RESERVED_PATHS, resolveWorkspacePath, } from "@openshain/core";
6
+ import { parse } from "csv-parse/sync";
7
+ import { stringify } from "csv-stringify/sync";
8
+ /** Files larger than this are not opened at all. What a tool returns is a window, far smaller. */
9
+ export const MAX_READ_BYTES = 1024 * 1024;
10
+ /** The same limit on writes, so that nothing a tool writes is too large for a tool to open. */
11
+ export const MAX_WRITE_BYTES = MAX_READ_BYTES;
12
+ /** The window each observing tool returns when the model does not ask for another one. */
13
+ export const DEFAULT_WINDOW = {
14
+ fs_list: 200,
15
+ fs_search: 100,
16
+ fs_read: 200,
17
+ csv_read: 50,
18
+ csv_aggregate: 100,
19
+ markdown_read: 100,
20
+ };
21
+ /** fs_search gives up after this many files so that a huge tree cannot stall a Work. */
22
+ const MAX_SEARCH_FILES = 2000;
23
+ /** fs_search returns at most this many characters of a matching line. */
24
+ const MAX_MATCH_TEXT = 200;
25
+ const pathProperty = {
26
+ type: "string",
27
+ description: "Path relative to the workspace root, for example receipts/2026-07.csv.",
28
+ };
29
+ function offsetProperty(unit) {
30
+ return {
31
+ type: "integer",
32
+ minimum: 0,
33
+ default: 0,
34
+ description: `How many ${unit} to skip before the window starts. 0 is the start.`,
35
+ };
36
+ }
37
+ function limitProperty(unit, fallback, maximum) {
38
+ return {
39
+ type: "integer",
40
+ minimum: 1,
41
+ maximum,
42
+ default: fallback,
43
+ description: `How many ${unit} to return at most (default ${fallback}).`,
44
+ };
45
+ }
46
+ const definitions = [
47
+ {
48
+ name: "fs_list",
49
+ description: '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.',
50
+ inputSchema: {
51
+ type: "object",
52
+ properties: {
53
+ path: { ...pathProperty, default: "." },
54
+ pattern: {
55
+ type: "string",
56
+ minLength: 1,
57
+ description: "Wildcard on the entry name, for example *.csv or 2026-*. * matches any run of characters and ? one character.",
58
+ },
59
+ limit: limitProperty("entries", DEFAULT_WINDOW.fs_list, 1000),
60
+ },
61
+ additionalProperties: false,
62
+ },
63
+ effect: "observe",
64
+ },
65
+ {
66
+ name: "fs_search",
67
+ description: "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.",
68
+ inputSchema: {
69
+ type: "object",
70
+ properties: {
71
+ pattern: {
72
+ type: "string",
73
+ minLength: 1,
74
+ description: "Text to look for. * matches any run of characters and ? one character; other characters, including . ( ) [ ] and |, match literally.",
75
+ },
76
+ path: {
77
+ ...pathProperty,
78
+ default: ".",
79
+ description: "Directory or file to search, relative to the workspace root. Defaults to the whole workspace.",
80
+ },
81
+ limit: limitProperty("matches", DEFAULT_WINDOW.fs_search, 1000),
82
+ },
83
+ required: ["pattern"],
84
+ additionalProperties: false,
85
+ },
86
+ effect: "observe",
87
+ },
88
+ {
89
+ name: "fs_read",
90
+ description: "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.",
91
+ inputSchema: {
92
+ type: "object",
93
+ properties: {
94
+ path: pathProperty,
95
+ offset: offsetProperty("lines"),
96
+ limit: limitProperty("lines", DEFAULT_WINDOW.fs_read, 2000),
97
+ },
98
+ required: ["path"],
99
+ additionalProperties: false,
100
+ },
101
+ effect: "observe",
102
+ },
103
+ {
104
+ name: "fs_write",
105
+ description: "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.",
106
+ inputSchema: {
107
+ type: "object",
108
+ properties: { path: pathProperty, content: { type: "string" } },
109
+ required: ["path", "content"],
110
+ additionalProperties: false,
111
+ },
112
+ effect: "mutate",
113
+ },
114
+ {
115
+ name: "csv_read",
116
+ description: "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.",
117
+ inputSchema: {
118
+ type: "object",
119
+ properties: {
120
+ path: pathProperty,
121
+ offset: offsetProperty("rows"),
122
+ limit: limitProperty("rows", DEFAULT_WINDOW.csv_read, 500),
123
+ },
124
+ required: ["path"],
125
+ additionalProperties: false,
126
+ },
127
+ effect: "observe",
128
+ },
129
+ {
130
+ name: "csv_aggregate",
131
+ description: "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.",
132
+ inputSchema: {
133
+ type: "object",
134
+ properties: {
135
+ path: pathProperty,
136
+ group_by: {
137
+ type: "array",
138
+ items: { type: "string" },
139
+ description: "Columns to group the rows by. Omit to treat the whole file as one group.",
140
+ },
141
+ sum: {
142
+ type: "array",
143
+ items: { type: "string" },
144
+ description: "Numeric columns to total.",
145
+ },
146
+ filter: {
147
+ type: "array",
148
+ items: {
149
+ type: "object",
150
+ properties: { column: { type: "string" }, equals: { type: "string" } },
151
+ required: ["column", "equals"],
152
+ additionalProperties: false,
153
+ },
154
+ description: "Keep only the rows where every listed column equals the given value.",
155
+ },
156
+ limit: limitProperty("groups", DEFAULT_WINDOW.csv_aggregate, 1000),
157
+ },
158
+ required: ["path"],
159
+ additionalProperties: false,
160
+ },
161
+ effect: "observe",
162
+ },
163
+ {
164
+ name: "csv_write",
165
+ description: "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.",
166
+ inputSchema: {
167
+ type: "object",
168
+ properties: {
169
+ path: pathProperty,
170
+ rows: {
171
+ type: "array",
172
+ items: { type: "object", additionalProperties: { type: "string" } },
173
+ description: "One object per row. Keys become the header.",
174
+ },
175
+ columns: {
176
+ type: "array",
177
+ items: { type: "string" },
178
+ description: "Column order. Defaults to the keys of the first row.",
179
+ },
180
+ },
181
+ required: ["path", "rows"],
182
+ additionalProperties: false,
183
+ },
184
+ effect: "mutate",
185
+ },
186
+ {
187
+ name: "markdown_read",
188
+ description: "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.",
189
+ inputSchema: {
190
+ type: "object",
191
+ properties: {
192
+ path: pathProperty,
193
+ section: {
194
+ type: "string",
195
+ minLength: 1,
196
+ description: "Text of the heading whose section to return.",
197
+ },
198
+ limit: limitProperty("lines", DEFAULT_WINDOW.markdown_read, 2000),
199
+ },
200
+ required: ["path"],
201
+ additionalProperties: false,
202
+ },
203
+ effect: "observe",
204
+ },
205
+ ];
206
+ /** The tools every workspace gets: files, CSV and Markdown, all confined to the workspace. */
207
+ export function standardTools() {
208
+ return {
209
+ id: "standard",
210
+ listTools: async () => definitions,
211
+ async call(call, ctx) {
212
+ const input = (call.input ?? {});
213
+ const path = typeof input.path === "string" ? input.path : ".";
214
+ switch (call.name) {
215
+ case "fs_list":
216
+ return fsList(ctx, path, nonEmpty(input.pattern), count(input.limit, DEFAULT_WINDOW.fs_list));
217
+ case "fs_search":
218
+ return fsSearch(ctx, path, input);
219
+ case "fs_read":
220
+ return fsRead(ctx, path, count(input.offset, 0), count(input.limit, DEFAULT_WINDOW.fs_read));
221
+ case "fs_write":
222
+ return fsWrite(ctx, path, String(input.content ?? ""));
223
+ case "csv_read":
224
+ return csvRead(ctx, path, count(input.offset, 0), count(input.limit, DEFAULT_WINDOW.csv_read));
225
+ case "csv_aggregate":
226
+ return csvAggregate(ctx, path, input);
227
+ case "csv_write":
228
+ return csvWrite(ctx, path, input.rows, input.columns);
229
+ case "markdown_read":
230
+ return markdownRead(ctx, path, nonEmpty(input.section), count(input.limit, DEFAULT_WINDOW.markdown_read));
231
+ default:
232
+ throw new Error(`the standard tools do not provide "${call.name}"`);
233
+ }
234
+ },
235
+ };
236
+ }
237
+ async function fsList(ctx, path, pattern, limit) {
238
+ const resolved = await resolveWorkspacePath(ctx.workspaceRoot, path);
239
+ const root = await resolveWorkspacePath(ctx.workspaceRoot, ".");
240
+ const matches = pattern === undefined ? () => true : wildcardMatcher(pattern);
241
+ const entries = (await readdir(resolved, { withFileTypes: true }))
242
+ .filter((entry) => visible(entry.name, resolved === root))
243
+ .filter((entry) => matches(entry.name))
244
+ .sort(byName);
245
+ const window = await Promise.all(entries.slice(0, limit).map(async (entry) => {
246
+ if (entry.isDirectory())
247
+ return { name: entry.name, type: "directory" };
248
+ if (!entry.isFile())
249
+ return { name: entry.name, type: "other" };
250
+ const { size } = await stat(join(resolved, entry.name));
251
+ return { name: entry.name, type: "file", size };
252
+ }));
253
+ return json({ path, entries: window, total: entries.length, truncated: window.length < entries.length }, path);
254
+ }
255
+ async function fsSearch(ctx, path, input) {
256
+ const pattern = text(input.pattern) ?? "";
257
+ if (pattern === "")
258
+ return failure("pattern must not be empty");
259
+ const limit = count(input.limit, DEFAULT_WINDOW.fs_search);
260
+ const test = /[*?]/.test(pattern)
261
+ ? wildcardMatcher(`*${pattern}*`)
262
+ : (line) => line.includes(pattern);
263
+ const resolved = await resolveWorkspacePath(ctx.workspaceRoot, path);
264
+ const root = await resolveWorkspacePath(ctx.workspaceRoot, ".");
265
+ const matches = [];
266
+ let filesSearched = 0;
267
+ let filesSkipped = 0;
268
+ let truncated = false;
269
+ const files = (await stat(resolved)).isFile() ? [resolved] : walk(resolved, root);
270
+ search: for await (const file of files) {
271
+ if (filesSearched + filesSkipped >= MAX_SEARCH_FILES) {
272
+ truncated = true;
273
+ break;
274
+ }
275
+ const content = await readSearchable(file);
276
+ if (content === undefined) {
277
+ filesSkipped += 1;
278
+ continue;
279
+ }
280
+ filesSearched += 1;
281
+ const lines = splitLines(content);
282
+ for (let i = 0; i < lines.length; i++) {
283
+ const line = lines[i] ?? "";
284
+ if (!test(line))
285
+ continue;
286
+ if (matches.length >= limit) {
287
+ truncated = true;
288
+ break search;
289
+ }
290
+ matches.push({ path: relative(root, file), line: i + 1, text: clip(line) });
291
+ }
292
+ }
293
+ return json({ pattern, path, matches, filesSearched, filesSkipped, truncated }, path);
294
+ }
295
+ async function fsRead(ctx, path, offset, limit) {
296
+ const content = await readText(ctx, path);
297
+ const lines = splitLines(content);
298
+ const window = lines.slice(offset, offset + limit);
299
+ return {
300
+ content: [
301
+ {
302
+ type: "json",
303
+ value: {
304
+ path,
305
+ offset,
306
+ returned: window.length,
307
+ lines: lines.length,
308
+ truncated: offset + window.length < lines.length,
309
+ bytes: Buffer.byteLength(content, "utf8"),
310
+ },
311
+ },
312
+ { type: "text", text: joinLines(window) },
313
+ ],
314
+ observation: observed(path),
315
+ };
316
+ }
317
+ async function fsWrite(ctx, path, content) {
318
+ const after = await writeText(ctx, path, content);
319
+ return { content: [{ type: "text", text: `wrote ${after.path}` }], after: [after] };
320
+ }
321
+ async function csvRead(ctx, path, offset, limit) {
322
+ const { columns, rows } = await readCsv(ctx, path);
323
+ const window = rows.slice(offset, offset + limit);
324
+ return json({
325
+ path,
326
+ columns,
327
+ rowCount: rows.length,
328
+ offset,
329
+ returned: window.length,
330
+ truncated: offset + window.length < rows.length,
331
+ rows: window,
332
+ }, path);
333
+ }
334
+ async function csvAggregate(ctx, path, input) {
335
+ const groupBy = strings(input.group_by);
336
+ const sums = strings(input.sum);
337
+ const filters = Array.isArray(input.filter)
338
+ ? input.filter.map((f) => ({
339
+ column: String(f.column),
340
+ equals: String(f.equals),
341
+ }))
342
+ : [];
343
+ const limit = count(input.limit, DEFAULT_WINDOW.csv_aggregate);
344
+ const { columns, rows } = await readCsv(ctx, path);
345
+ for (const column of [...groupBy, ...sums, ...filters.map((f) => f.column)]) {
346
+ if (!columns.includes(column)) {
347
+ return failure(`"${path}" has no column "${column}"; its columns are ${columns.join(", ")}`);
348
+ }
349
+ }
350
+ const matched = rows.filter((row) => filters.every((f) => (row[f.column] ?? "") === f.equals));
351
+ const newTotals = () => Object.fromEntries(sums.map((column) => [column, { sum: 0, min: null, max: null, count: 0, skipped: 0 }]));
352
+ const add = (totals, row) => {
353
+ for (const column of sums) {
354
+ const t = totals[column];
355
+ if (t)
356
+ accumulate(t, row[column] ?? "");
357
+ }
358
+ };
359
+ const groups = new Map();
360
+ const overall = newTotals();
361
+ for (const row of matched) {
362
+ const values = groupBy.map((column) => row[column] ?? "");
363
+ const key = JSON.stringify(values);
364
+ let group = groups.get(key);
365
+ if (!group) {
366
+ group = { values, rows: 0, totals: newTotals() };
367
+ groups.set(key, group);
368
+ }
369
+ group.rows += 1;
370
+ add(group.totals, row);
371
+ add(overall, row);
372
+ }
373
+ const tidyTotals = (totals) => Object.fromEntries(Object.entries(totals).map(([column, t]) => [column, { ...t, sum: tidy(t.sum) }]));
374
+ const sorted = [...groups.values()].sort((a, b) => compareValues(a.values, b.values));
375
+ const window = sorted.slice(0, limit).map((group) => ({
376
+ group: Object.fromEntries(groupBy.map((column, i) => [column, group.values[i] ?? ""])),
377
+ rows: group.rows,
378
+ totals: tidyTotals(group.totals),
379
+ }));
380
+ return json({
381
+ path,
382
+ rowCount: rows.length,
383
+ matched: matched.length,
384
+ groupCount: sorted.length,
385
+ groups: window,
386
+ // The same figures over every matched row, so a grand total is never added by hand.
387
+ overall: { rows: matched.length, totals: tidyTotals(overall) },
388
+ truncated: window.length < sorted.length,
389
+ }, path);
390
+ }
391
+ async function csvWrite(ctx, path, rows, columns) {
392
+ if (!Array.isArray(rows))
393
+ throw new Error("rows must be an array of objects");
394
+ const safeRows = rows.map((row) => Object.fromEntries(Object.entries(row).map(([key, value]) => [key, neutralizeFormula(value)])));
395
+ const content = stringify(safeRows, {
396
+ header: true,
397
+ ...(Array.isArray(columns) && { columns: columns }),
398
+ });
399
+ const after = await writeText(ctx, path, content);
400
+ return {
401
+ content: [{ type: "text", text: `wrote ${rows.length} rows to ${after.path}` }],
402
+ after: [after],
403
+ };
404
+ }
405
+ async function markdownRead(ctx, path, section, limit) {
406
+ const lines = splitLines(await readText(ctx, path));
407
+ const headings = outline(lines);
408
+ let from = 0;
409
+ let end = lines.length;
410
+ let picked;
411
+ if (section !== undefined) {
412
+ const heading = headings.find((h) => h.text === section) ?? headings.find((h) => h.text.includes(section));
413
+ if (!heading) {
414
+ const known = headings.map((h) => h.text).join(", ");
415
+ return failure(`"${path}" has no heading matching "${section}"; its headings are: ${known}`);
416
+ }
417
+ const next = headings.find((h) => h.line > heading.line && h.level <= heading.level);
418
+ from = heading.line - 1;
419
+ end = next ? next.line - 1 : lines.length;
420
+ picked = { text: heading.text, level: heading.level, line: heading.line, lines: end - from };
421
+ }
422
+ const window = lines.slice(from, Math.min(end, from + limit));
423
+ return {
424
+ content: [
425
+ {
426
+ type: "json",
427
+ value: {
428
+ path,
429
+ lines: lines.length,
430
+ headings,
431
+ ...(picked && { section: picked }),
432
+ offset: from,
433
+ returned: window.length,
434
+ truncated: from + window.length < end,
435
+ },
436
+ },
437
+ { type: "text", text: joinLines(window) },
438
+ ],
439
+ observation: observed(path),
440
+ };
441
+ }
442
+ /** Headings outside fenced code blocks, with 1-based line numbers. */
443
+ function outline(lines) {
444
+ const headings = [];
445
+ let fence;
446
+ for (let i = 0; i < lines.length; i++) {
447
+ const line = lines[i] ?? "";
448
+ const fenceMatch = /^\s*(`{3,}|~{3,})/.exec(line);
449
+ if (fenceMatch) {
450
+ const marker = fenceMatch[1] ?? "";
451
+ if (!fence)
452
+ fence = marker[0];
453
+ else if (marker[0] === fence)
454
+ fence = undefined;
455
+ continue;
456
+ }
457
+ if (fence)
458
+ continue;
459
+ const match = /^(#{1,6})\s+(.+?)\s*#*\s*$/.exec(line);
460
+ if (match)
461
+ headings.push({ level: match[1]?.length ?? 1, text: match[2] ?? "", line: i + 1 });
462
+ }
463
+ return headings;
464
+ }
465
+ async function readCsv(ctx, path) {
466
+ const content = await readText(ctx, path);
467
+ const records = parse(content, { bom: true, skip_empty_lines: true });
468
+ const [header, ...body] = records;
469
+ const columns = header ?? [];
470
+ const rows = body.map((cells) => Object.fromEntries(columns.map((column, i) => [column, cells[i] ?? ""])));
471
+ return { columns, rows };
472
+ }
473
+ /**
474
+ * Reads a text file through one descriptor: the size check and the read see the same file,
475
+ * so a swap between the two cannot slip a larger file past the limit.
476
+ */
477
+ async function readText(ctx, path) {
478
+ const resolved = await resolveWorkspacePath(ctx.workspaceRoot, path);
479
+ let handle;
480
+ try {
481
+ handle = await open(resolved, "r");
482
+ }
483
+ catch (err) {
484
+ throw new Error(`cannot read "${path}": ${err.code ?? "error"}`);
485
+ }
486
+ try {
487
+ const { size } = await handle.stat();
488
+ if (size > MAX_READ_BYTES) {
489
+ throw new Error(`"${path}" is too large to read (${size} bytes, limit ${MAX_READ_BYTES})`);
490
+ }
491
+ return await handle.readFile("utf8");
492
+ }
493
+ finally {
494
+ await handle.close();
495
+ }
496
+ }
497
+ /** Writes through a descriptor opened with O_NOFOLLOW, so the final component may not be a symlink. */
498
+ async function writeText(ctx, path, content) {
499
+ const bytes = Buffer.byteLength(content, "utf8");
500
+ if (bytes > MAX_WRITE_BYTES) {
501
+ throw new Error(`"${path}" is too large to write (${bytes} bytes, limit ${MAX_WRITE_BYTES})`);
502
+ }
503
+ const resolved = await resolveWorkspacePath(ctx.workspaceRoot, path);
504
+ const root = await resolveWorkspacePath(ctx.workspaceRoot, ".");
505
+ await mkdir(dirname(resolved), { recursive: true });
506
+ const flags = constants.O_WRONLY | constants.O_CREAT | constants.O_TRUNC | (constants.O_NOFOLLOW ?? 0);
507
+ const handle = await open(resolved, flags, 0o644);
508
+ try {
509
+ await handle.writeFile(content, "utf8");
510
+ }
511
+ finally {
512
+ await handle.close();
513
+ }
514
+ return {
515
+ path: relative(root, resolved),
516
+ sha256: createHash("sha256").update(content).digest("hex"),
517
+ };
518
+ }
519
+ /** Regular files below `dir`, in code point order, skipping hidden entries, symlinks and reserved paths. */
520
+ async function* walk(dir, root) {
521
+ const entries = (await readdir(dir, { withFileTypes: true }))
522
+ .filter((entry) => visible(entry.name, dir === root))
523
+ .sort(byName);
524
+ for (const entry of entries) {
525
+ const full = join(dir, entry.name);
526
+ if (entry.isDirectory())
527
+ yield* walk(full, root);
528
+ else if (entry.isFile())
529
+ yield full;
530
+ }
531
+ }
532
+ function visible(name, atRoot) {
533
+ if (name.startsWith("."))
534
+ return false;
535
+ return (!atRoot || !RESERVED_PATHS.some((reserved) => reserved.toLowerCase() === name.toLowerCase()));
536
+ }
537
+ function byName(a, b) {
538
+ return a.name < b.name ? -1 : a.name > b.name ? 1 : 0;
539
+ }
540
+ function compareValues(a, b) {
541
+ for (let i = 0; i < Math.max(a.length, b.length); i++) {
542
+ const x = a[i] ?? "";
543
+ const y = b[i] ?? "";
544
+ if (x !== y)
545
+ return x < y ? -1 : 1;
546
+ }
547
+ return 0;
548
+ }
549
+ /**
550
+ * Matches a whole string against a pattern in which `*` stands for any run of characters and `?`
551
+ * for one character; everything else is literal. Takes time proportional to the pattern times the
552
+ * subject, so a pattern the model writes cannot stall the run the way a backtracking regular
553
+ * expression can.
554
+ */
555
+ function wildcardMatcher(pattern) {
556
+ const p = [...pattern];
557
+ return (subject) => {
558
+ const s = [...subject];
559
+ let pi = 0;
560
+ let si = 0;
561
+ let starP = -1;
562
+ let starS = 0;
563
+ while (si < s.length) {
564
+ if (pi < p.length && (p[pi] === "?" || p[pi] === s[si])) {
565
+ pi += 1;
566
+ si += 1;
567
+ }
568
+ else if (pi < p.length && p[pi] === "*") {
569
+ starP = pi;
570
+ starS = si;
571
+ pi += 1;
572
+ }
573
+ else if (starP >= 0) {
574
+ pi = starP + 1;
575
+ starS += 1;
576
+ si = starS;
577
+ }
578
+ else {
579
+ return false;
580
+ }
581
+ }
582
+ while (pi < p.length && p[pi] === "*")
583
+ pi += 1;
584
+ return pi === p.length;
585
+ };
586
+ }
587
+ /**
588
+ * The text of a file the search may read, or undefined for one it skips: over 1 MiB, or with
589
+ * a NUL byte in the first 8 KiB. Size, head and content all come from one descriptor.
590
+ */
591
+ async function readSearchable(file) {
592
+ const handle = await open(file, "r");
593
+ try {
594
+ if ((await handle.stat()).size > MAX_READ_BYTES)
595
+ return undefined;
596
+ const head = Buffer.alloc(8192);
597
+ const { bytesRead } = await handle.read(head, 0, head.length, 0);
598
+ if (head.subarray(0, bytesRead).includes(0))
599
+ return undefined;
600
+ return await handle.readFile("utf8");
601
+ }
602
+ finally {
603
+ await handle.close();
604
+ }
605
+ }
606
+ /** Cells such as 1,200, ¥300, 123 or -50.5 are numbers; anything else is skipped. */
607
+ function toNumber(cell) {
608
+ const cleaned = cell.normalize("NFKC").replace(/[,¥$\s]/g, "");
609
+ return /^[-+]?(\d+\.?\d*|\.\d+)$/.test(cleaned) ? Number(cleaned) : undefined;
610
+ }
611
+ function accumulate(totals, cell) {
612
+ const value = toNumber(cell);
613
+ if (value === undefined) {
614
+ totals.skipped += 1;
615
+ return;
616
+ }
617
+ totals.sum += value;
618
+ totals.count += 1;
619
+ totals.min = totals.min === null ? value : Math.min(totals.min, value);
620
+ totals.max = totals.max === null ? value : Math.max(totals.max, value);
621
+ }
622
+ /** Hides the noise of binary floating point in a sum of decimals, such as 0.1 + 0.2. Integers stay exact. */
623
+ function tidy(n) {
624
+ return Number.isInteger(n) ? n : Number(n.toPrecision(15));
625
+ }
626
+ /** Lines of a text, without the empty line a trailing newline would add. */
627
+ function splitLines(content) {
628
+ const lines = content.split("\n");
629
+ if (lines.at(-1) === "")
630
+ lines.pop();
631
+ return lines;
632
+ }
633
+ function joinLines(lines) {
634
+ return lines.length === 0 ? "" : `${lines.join("\n")}\n`;
635
+ }
636
+ function clip(line) {
637
+ const chars = [...line];
638
+ return chars.length > MAX_MATCH_TEXT ? `${chars.slice(0, MAX_MATCH_TEXT).join("")}…` : line;
639
+ }
640
+ function text(value) {
641
+ return typeof value === "string" ? value : undefined;
642
+ }
643
+ function nonEmpty(value) {
644
+ return typeof value === "string" && value !== "" ? value : undefined;
645
+ }
646
+ function count(value, fallback) {
647
+ return typeof value === "number" && Number.isInteger(value) && value >= 0 ? value : fallback;
648
+ }
649
+ function strings(value) {
650
+ return Array.isArray(value) ? value.filter((v) => typeof v === "string") : [];
651
+ }
652
+ function json(value, path) {
653
+ return { content: [{ type: "json", value }], observation: observed(path) };
654
+ }
655
+ function failure(message) {
656
+ return { content: [{ type: "text", text: message }], isError: true };
657
+ }
658
+ /**
659
+ * Spreadsheets run a cell that starts with =, +, @ or - as a formula. A leading apostrophe keeps
660
+ * it text. Negative numbers are left alone.
661
+ */
662
+ function neutralizeFormula(value) {
663
+ if (typeof value !== "string")
664
+ return value;
665
+ return /^[=+@\t\r]/.test(value) || /^-(?![0-9.])/.test(value) ? `'${value}` : value;
666
+ }
667
+ function observed(path) {
668
+ return { source: path, retrievedAt: new Date().toISOString() };
669
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@openshain/tools",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "description": "Standard tool provider: filesystem, CSV, Markdown, documents, email",
5
5
  "keywords": [
6
6
  "openshain",
@@ -12,7 +12,7 @@
12
12
  ],
13
13
  "author": "Hiroki Nakatani",
14
14
  "license": "Apache-2.0",
15
- "homepage": "https://github.com/openshain/openshain",
15
+ "homepage": "https://openshain.jp",
16
16
  "repository": {
17
17
  "type": "git",
18
18
  "url": "git+https://github.com/openshain/openshain.git",
@@ -21,23 +21,34 @@
21
21
  "bugs": "https://github.com/openshain/openshain/issues",
22
22
  "type": "module",
23
23
  "engines": {
24
+ "node": ">=22",
24
25
  "bun": ">=1.3"
25
26
  },
26
27
  "files": [
28
+ "dist",
27
29
  "src",
28
30
  "!src/**/*.test.ts",
31
+ "!src/**/*.test.tsx",
29
32
  "README.md",
30
33
  "LICENSE"
31
34
  ],
32
35
  "exports": {
33
- ".": "./src/index.ts"
36
+ ".": {
37
+ "bun": "./src/index.ts",
38
+ "types": "./dist/index.d.ts",
39
+ "import": "./dist/index.js"
40
+ }
34
41
  },
35
- "publishConfig": {
36
- "access": "public"
42
+ "scripts": {
43
+ "build": "../../node_modules/.bin/tsc -p tsconfig.build.json",
44
+ "prepublishOnly": "rm -rf dist && ../../node_modules/.bin/tsc -p tsconfig.build.json"
37
45
  },
38
46
  "dependencies": {
39
- "@openshain/core": "0.1.0",
47
+ "@openshain/core": "0.2.0",
40
48
  "csv-parse": "7.0.2",
41
49
  "csv-stringify": "6.8.3"
50
+ },
51
+ "publishConfig": {
52
+ "access": "public"
42
53
  }
43
54
  }