@saturn-universe/tools 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 (53) hide show
  1. package/LICENSE +661 -0
  2. package/dist/container-sandbox.d.ts +168 -0
  3. package/dist/container-sandbox.js +1241 -0
  4. package/dist/counter.d.ts +5 -0
  5. package/dist/counter.js +82 -0
  6. package/dist/data-review.d.ts +4 -0
  7. package/dist/data-review.js +146 -0
  8. package/dist/execution-backend.d.ts +55 -0
  9. package/dist/execution-backend.js +339 -0
  10. package/dist/executor.d.ts +25 -0
  11. package/dist/executor.js +978 -0
  12. package/dist/file-window.d.ts +3 -0
  13. package/dist/file-window.js +12 -0
  14. package/dist/index.d.ts +27 -0
  15. package/dist/index.js +17 -0
  16. package/dist/mcp-headers.d.ts +3 -0
  17. package/dist/mcp-headers.js +51 -0
  18. package/dist/mcp-http.d.ts +3 -0
  19. package/dist/mcp-http.js +253 -0
  20. package/dist/mcp-stdio.d.ts +2 -0
  21. package/dist/mcp-stdio.js +147 -0
  22. package/dist/mcp-wire.d.ts +33 -0
  23. package/dist/mcp-wire.js +85 -0
  24. package/dist/mcp.d.ts +19 -0
  25. package/dist/mcp.js +325 -0
  26. package/dist/path-containment.d.ts +3 -0
  27. package/dist/path-containment.js +11 -0
  28. package/dist/planner.d.ts +3 -0
  29. package/dist/planner.js +162 -0
  30. package/dist/process-manager.d.ts +67 -0
  31. package/dist/process-manager.js +423 -0
  32. package/dist/process-output.d.ts +34 -0
  33. package/dist/process-output.js +162 -0
  34. package/dist/process-worker.d.ts +1 -0
  35. package/dist/process-worker.js +202 -0
  36. package/dist/registry.d.ts +33 -0
  37. package/dist/registry.js +227 -0
  38. package/dist/search.d.ts +9 -0
  39. package/dist/search.js +96 -0
  40. package/dist/team.d.ts +36 -0
  41. package/dist/team.js +284 -0
  42. package/dist/text-patch.d.ts +15 -0
  43. package/dist/text-patch.js +81 -0
  44. package/dist/todo.d.ts +3 -0
  45. package/dist/todo.js +105 -0
  46. package/dist/workspace-discovery.d.ts +42 -0
  47. package/dist/workspace-discovery.js +404 -0
  48. package/dist/workspace-snapshot.d.ts +28 -0
  49. package/dist/workspace-snapshot.js +371 -0
  50. package/dist/workspace.d.ts +22 -0
  51. package/dist/workspace.js +1819 -0
  52. package/package.json +16 -3
  53. package/README.md +0 -3
@@ -0,0 +1,404 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { once } from 'node:events';
3
+ import { constants } from 'node:fs';
4
+ import { lstat, open, opendir, realpath } from 'node:fs/promises';
5
+ import path from 'node:path';
6
+ import { isMainThread, parentPort, Worker, workerData } from 'node:worker_threads';
7
+ import { RuntimeError } from '@saturn-universe/core';
8
+ import { isContainedPath } from './path-containment.js';
9
+ const excluded = /^(\.git|node_modules|\.saturn|\.env)$/i;
10
+ const maxLineChars = 500;
11
+ const maxGrepBytes = 32 * 1024;
12
+ export const maxDiscoveryResults = 1000;
13
+ export const maxContextLines = 5;
14
+ export function isDiscoverablePath(relative) {
15
+ return relative.split(/[\\/]/).every((segment) => !excluded.test(segment));
16
+ }
17
+ const relativePath = (root, target) => path.relative(root, target).split(path.sep).join('/');
18
+ async function* filesBelow(target, signal, rootBound, strictSymlinks = false) {
19
+ signal.throwIfAborted();
20
+ const info = await lstat(target);
21
+ if (strictSymlinks && info.isSymbolicLink()) {
22
+ throw new RuntimeError('SANDBOX_SYMLINK_ESCAPE', 'Symlink escapes sandbox work directory');
23
+ }
24
+ if (info.isFile() && info.nlink === 1) {
25
+ yield { file: target, mtimeMs: info.mtimeMs };
26
+ }
27
+ else if (info.isDirectory()) {
28
+ const real = await realpath(target);
29
+ if (path.relative(target, real) !== '') {
30
+ if (strictSymlinks) {
31
+ throw new RuntimeError('SANDBOX_SYMLINK_ESCAPE', 'Symlink escapes sandbox work directory');
32
+ }
33
+ return;
34
+ }
35
+ if (strictSymlinks && rootBound && !isContainedPath(rootBound, real)) {
36
+ throw new RuntimeError('SANDBOX_SYMLINK_ESCAPE', 'Symlink escapes sandbox work directory');
37
+ }
38
+ for await (const entry of await opendir(target)) {
39
+ signal.throwIfAborted();
40
+ if (!isDiscoverablePath(entry.name))
41
+ continue;
42
+ const childPath = path.join(target, entry.name);
43
+ if (entry.isSymbolicLink()) {
44
+ if (strictSymlinks) {
45
+ const realChild = await realpath(childPath).catch(() => undefined);
46
+ if (!realChild || (rootBound && !isContainedPath(rootBound, realChild))) {
47
+ throw new RuntimeError('SANDBOX_SYMLINK_ESCAPE', 'Symlink escapes sandbox work directory');
48
+ }
49
+ }
50
+ continue;
51
+ }
52
+ if (entry.isDirectory() || entry.isFile()) {
53
+ yield* filesBelow(childPath, signal, rootBound, strictSymlinks);
54
+ }
55
+ }
56
+ }
57
+ }
58
+ export async function globWorkspace({ root, target, strictSymlinks = false }, pattern, limit, signal) {
59
+ const matches = [];
60
+ let totalMatched = 0;
61
+ const mostRecentFirst = (first, second) => second.mtimeMs - first.mtimeMs || first.path.localeCompare(second.path, 'en');
62
+ for await (const { file, mtimeMs } of filesBelow(target, signal, root, strictSymlinks)) {
63
+ if (!path.posix.matchesGlob(relativePath(target, file), pattern))
64
+ continue;
65
+ matches.push({ path: relativePath(root, file), mtimeMs });
66
+ totalMatched++;
67
+ if (matches.length === 2 * limit)
68
+ matches.sort(mostRecentFirst).splice(limit);
69
+ }
70
+ const paths = matches
71
+ .sort(mostRecentFirst)
72
+ .slice(0, limit)
73
+ .map((match) => match.path);
74
+ return { paths, totalMatched, truncated: totalMatched > paths.length };
75
+ }
76
+ function matchesInclude(options, file) {
77
+ const { include } = options;
78
+ if (!include)
79
+ return true;
80
+ const relative = relativePath(options.target, file) || path.basename(file);
81
+ return path.posix.matchesGlob(include.includes('/') ? relative : path.basename(file), include);
82
+ }
83
+ function formatLine(row) {
84
+ const separator = row.kind === 'match' ? ':' : '-';
85
+ return [row.path, row.line, row.text].join(separator);
86
+ }
87
+ export function grepText(result) {
88
+ const summary = result.truncated
89
+ ? `${result.matchCount} matching lines (truncated)`
90
+ : `${result.matchCount} matching lines`;
91
+ return [summary, ...result.lines.map(formatLine)].join('\n');
92
+ }
93
+ function grepOutput(limit) {
94
+ const result = { lines: [], matchCount: 0, truncated: false };
95
+ // Budget for both the display text and the structured rows, including JSON escaping.
96
+ let bytes = 256;
97
+ function add(row, clipped = false) {
98
+ const cost = Buffer.byteLength(JSON.stringify(row)) + Buffer.byteLength(JSON.stringify(formatLine(row))) + 4;
99
+ if ((row.kind === 'match' && result.matchCount >= limit) || bytes + cost > maxGrepBytes) {
100
+ result.truncated = true;
101
+ return false;
102
+ }
103
+ bytes += cost;
104
+ result.lines.push(row);
105
+ if (row.kind === 'match')
106
+ result.matchCount++;
107
+ if (clipped)
108
+ result.truncated = true;
109
+ return true;
110
+ }
111
+ return { result, add };
112
+ }
113
+ function rowText(text) {
114
+ const prefix = text.slice(0, maxLineChars).replace(/[\uD800-\uDBFF]$/, '');
115
+ return { text: prefix, clipped: text.length > maxLineChars };
116
+ }
117
+ async function readSearchText(file, signal, consume) {
118
+ if (path.relative(file, await realpath(file)) !== '')
119
+ return false;
120
+ const handle = await open(file, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
121
+ try {
122
+ const info = await handle.stat();
123
+ if (!info.isFile() || info.nlink !== 1)
124
+ return false;
125
+ const decoder = new TextDecoder('utf-8', { fatal: true });
126
+ for await (const chunk of handle.createReadStream({ signal, autoClose: false })) {
127
+ const bytes = chunk;
128
+ if (bytes.includes(0))
129
+ return false;
130
+ let text;
131
+ try {
132
+ text = decoder.decode(bytes, { stream: true });
133
+ }
134
+ catch {
135
+ return false; // Invalid UTF-8 is treated as binary.
136
+ }
137
+ consume?.(text);
138
+ }
139
+ try {
140
+ decoder.decode();
141
+ }
142
+ catch {
143
+ return false; // An incomplete final code point also makes the file binary.
144
+ }
145
+ const current = await handle.stat();
146
+ return info.size === current.size && info.mtimeMs === current.mtimeMs && info.ctimeMs === current.ctimeMs;
147
+ }
148
+ finally {
149
+ await handle.close();
150
+ }
151
+ }
152
+ async function* ripgrepRecords(stdout) {
153
+ let pending = Buffer.alloc(0);
154
+ let nameEnd = -1;
155
+ for await (const chunk of stdout) {
156
+ pending = Buffer.concat([pending, chunk]);
157
+ for (;;) {
158
+ // NUL terminates the path, which may itself contain a newline on POSIX.
159
+ if (nameEnd < 0)
160
+ nameEnd = pending.indexOf(0);
161
+ if (nameEnd < 0)
162
+ break;
163
+ const end = pending.indexOf(10, nameEnd + 1);
164
+ if (end < 0)
165
+ break;
166
+ yield [pending.toString('utf8', 0, nameEnd), pending.toString('utf8', nameEnd + 1, end)];
167
+ pending = pending.subarray(end + 1);
168
+ nameEnd = -1;
169
+ }
170
+ }
171
+ }
172
+ async function runRipgrep(program, files, options, signal, output) {
173
+ const mappedFiles = program.mapPath ? files.map(program.mapPath) : files;
174
+ const args = [
175
+ '--no-config',
176
+ '--color',
177
+ 'never',
178
+ '--no-heading',
179
+ '--with-filename',
180
+ '--line-number',
181
+ '--null',
182
+ '--sort',
183
+ 'path',
184
+ '--crlf',
185
+ // Keep stdout framed as search records even if rg encounters a binary file.
186
+ // Only files that pass the UTF-8/NUL check below contribute results.
187
+ '--text',
188
+ '--no-context-separator',
189
+ '--max-columns',
190
+ String(4 * (maxLineChars + 1)),
191
+ '--max-columns-preview',
192
+ '--max-count',
193
+ String(options.limit + 1),
194
+ '--context',
195
+ String(options.contextLines),
196
+ ...(options.ignoreCase ? ['--ignore-case'] : []),
197
+ '-e',
198
+ options.pattern,
199
+ '--',
200
+ ...(mappedFiles.length ? mappedFiles : ['-']),
201
+ ];
202
+ const child = program.spawn
203
+ ? program.spawn(args, options.root, signal)
204
+ : spawn(program.filename, args, {
205
+ cwd: options.root,
206
+ signal,
207
+ env: program.env,
208
+ windowsHide: true,
209
+ stdio: ['ignore', 'pipe', 'pipe'],
210
+ });
211
+ const closed = once(child, 'close').then(([code]) => ({ code: code }), (error) => ({ error }));
212
+ let stderr = '';
213
+ child.stderr?.on('data', (chunk) => {
214
+ stderr = (stderr + chunk.toString('utf8')).slice(0, 2048);
215
+ });
216
+ const allowed = new Set(files);
217
+ let currentFile;
218
+ let textFile = false;
219
+ try {
220
+ for await (const [filename, value] of ripgrepRecords(child.stdout)) {
221
+ const file = program.unmapPath ? program.unmapPath(filename) : path.resolve(options.root, filename);
222
+ if (!allowed.has(file))
223
+ continue;
224
+ if (file !== currentFile) {
225
+ currentFile = file;
226
+ textFile = await readSearchText(file, signal);
227
+ }
228
+ if (!textFile)
229
+ continue;
230
+ const match = /^(\d+)([:-])(.*)$/s.exec(value);
231
+ if (!match)
232
+ continue;
233
+ const { text, clipped } = rowText(match[3].replace(/\r$/, ''));
234
+ if (!output.add({
235
+ path: relativePath(options.root, file),
236
+ line: Number(match[1]),
237
+ text,
238
+ kind: match[2] === ':' ? 'match' : 'context',
239
+ }, clipped))
240
+ return false;
241
+ }
242
+ signal.throwIfAborted();
243
+ const exit = await closed;
244
+ if ('error' in exit)
245
+ throw exit.error;
246
+ if (exit.code === 0 || exit.code === 1)
247
+ return true;
248
+ if (stderr.includes('regex parse error'))
249
+ throw new RuntimeError('INVALID_REGEX', stderr.trim());
250
+ throw new RuntimeError('GREP_FAILED', stderr.trim() || 'ripgrep could not complete the search');
251
+ }
252
+ finally {
253
+ if (child.exitCode === null && child.signalCode === null)
254
+ child.kill();
255
+ await closed;
256
+ }
257
+ }
258
+ async function ripgrep(program, options, signal) {
259
+ const output = grepOutput(options.limit);
260
+ let files = [];
261
+ let argumentChars = 0;
262
+ for await (const { file } of filesBelow(options.target, signal, options.root, options.strictSymlinks === true)) {
263
+ if (!matchesInclude(options, file))
264
+ continue;
265
+ // Keep explicit paths below Windows' command-line limit, including quoting and the regex.
266
+ if (files.length && argumentChars + file.length + 3 > 12_000) {
267
+ if (!(await runRipgrep(program, files, options, signal, output)))
268
+ return output.result;
269
+ files = [];
270
+ argumentChars = 0;
271
+ }
272
+ files.push(file);
273
+ argumentChars += file.length + 3;
274
+ }
275
+ await runRipgrep(program, files, options, signal, output);
276
+ return output.result;
277
+ }
278
+ async function nodeGrep(options) {
279
+ const signal = new AbortController().signal;
280
+ const output = grepOutput(options.limit);
281
+ const regex = new RegExp(options.pattern, options.ignoreCase ? 'iu' : 'u');
282
+ for await (const { file } of filesBelow(options.target, signal, options.root, options.strictSymlinks === true)) {
283
+ if (!matchesInclude(options, file))
284
+ continue;
285
+ const filename = relativePath(options.root, file);
286
+ const fileOutput = grepOutput(options.limit - output.result.matchCount);
287
+ const context = [];
288
+ let line = 0;
289
+ let trailingContext = 0;
290
+ let printedThrough = 0;
291
+ let pending = [];
292
+ let full = false;
293
+ function fileOutputLine(text, kind) {
294
+ const preview = rowText(text);
295
+ return { row: { path: filename, line, text: preview.text, kind }, clipped: preview.clipped };
296
+ }
297
+ function add({ row, clipped }) {
298
+ if (full || row.line <= printedThrough)
299
+ return;
300
+ full = !fileOutput.add(row, clipped);
301
+ printedThrough = row.line;
302
+ }
303
+ function consumeLine(text) {
304
+ line++;
305
+ if (regex.test(text)) {
306
+ for (const row of context)
307
+ add(row);
308
+ add(fileOutputLine(text, 'match'));
309
+ trailingContext = options.contextLines;
310
+ }
311
+ else if (trailingContext > 0) {
312
+ add(fileOutputLine(text, 'context'));
313
+ trailingContext--;
314
+ }
315
+ if (options.contextLines) {
316
+ if (context.length === options.contextLines)
317
+ context.shift();
318
+ context.push(fileOutputLine(text, 'context'));
319
+ }
320
+ }
321
+ const textFile = await readSearchText(file, signal, (chunk) => {
322
+ if (full)
323
+ return;
324
+ const parts = chunk.split('\n');
325
+ if (parts.length === 1) {
326
+ pending.push(chunk);
327
+ return;
328
+ }
329
+ // Join an unfinished line once, even when a minified file spans many chunks.
330
+ pending.push(parts[0]);
331
+ parts[0] = pending.join('');
332
+ pending = [parts.pop()];
333
+ for (const part of parts) {
334
+ consumeLine(part.endsWith('\r') ? part.slice(0, -1) : part);
335
+ if (full)
336
+ break;
337
+ }
338
+ });
339
+ if (!textFile)
340
+ continue;
341
+ if (!full) {
342
+ const last = pending.join('');
343
+ if (last)
344
+ consumeLine(last);
345
+ }
346
+ for (const row of fileOutput.result.lines) {
347
+ if (!output.add(row))
348
+ return output.result;
349
+ }
350
+ output.result.truncated ||= fileOutput.result.truncated;
351
+ if (full)
352
+ break;
353
+ }
354
+ return output.result;
355
+ }
356
+ // A JavaScript regex can backtrack indefinitely. Keep it off the Host event loop so abort can terminate it.
357
+ if (!isMainThread && workerData?.workspaceGrep) {
358
+ const port = parentPort;
359
+ void nodeGrep(workerData.workspaceGrep).then((result) => port.postMessage({ result }), (error) => port.postMessage({ invalidRegex: error instanceof SyntaxError }));
360
+ }
361
+ async function grepInWorker(options, signal) {
362
+ signal.throwIfAborted();
363
+ const worker = new Worker(new URL(import.meta.url), {
364
+ execArgv: [],
365
+ workerData: { workspaceGrep: options },
366
+ });
367
+ const abort = () => {
368
+ void worker.terminate();
369
+ };
370
+ signal.addEventListener('abort', abort, { once: true });
371
+ try {
372
+ const [response] = await Promise.race([
373
+ once(worker, 'message'),
374
+ once(worker, 'exit').then(() => {
375
+ signal.throwIfAborted();
376
+ throw new RuntimeError('GREP_FAILED', 'The JavaScript search worker exited unexpectedly');
377
+ }),
378
+ ]);
379
+ if (response.result)
380
+ return response.result;
381
+ if (response.invalidRegex)
382
+ throw new RuntimeError('INVALID_REGEX', 'Invalid JavaScript regular expression');
383
+ throw new RuntimeError('GREP_FAILED', 'The JavaScript search could not complete');
384
+ }
385
+ finally {
386
+ signal.removeEventListener('abort', abort);
387
+ await worker.terminate();
388
+ }
389
+ }
390
+ export async function grepWorkspace(options, signal, program) {
391
+ if (/[\0\r\n]/.test(options.pattern))
392
+ throw new RuntimeError('INVALID_REGEX', 'Use a single-line regular expression without NUL characters');
393
+ if (program) {
394
+ try {
395
+ return await ripgrep(program, options, signal);
396
+ }
397
+ catch (error) {
398
+ if (error.code !== 'ENOENT' ||
399
+ !error.message.startsWith('spawn '))
400
+ throw error;
401
+ }
402
+ }
403
+ return grepInWorker(options, signal);
404
+ }
@@ -0,0 +1,28 @@
1
+ export declare const defaultMaxBranchCopyBytes: number;
2
+ export type BranchWorkspaceMode = 'readonly' | 'isolated';
3
+ export type BranchWorkspaceKind = 'shared_readonly' | 'git_worktree' | 'shallow_copy';
4
+ export interface BranchWorkspaceHandle {
5
+ readonly searchId?: string;
6
+ readonly branchId?: string;
7
+ readonly kind: BranchWorkspaceKind;
8
+ readonly workingDirectory: string;
9
+ readonly baseManifest?: Readonly<Record<string, string>>;
10
+ readonly degradedToReadonly?: boolean;
11
+ readonly degradeReason?: string;
12
+ }
13
+ export interface CreateBranchWorkspaceInput {
14
+ readonly rootDir: string;
15
+ readonly searchId: string;
16
+ readonly branchId: string;
17
+ readonly mode: BranchWorkspaceMode;
18
+ readonly maxCopyBytes?: number;
19
+ }
20
+ export interface WorkspaceSnapshotManager {
21
+ createBranchWorkspace(input: CreateBranchWorkspaceInput): Promise<BranchWorkspaceHandle>;
22
+ mergeBranchWorkspace(handle: BranchWorkspaceHandle, rootDir: string): Promise<{
23
+ readonly mergedFiles: readonly string[];
24
+ }>;
25
+ cleanupBranchWorkspace(handle: BranchWorkspaceHandle, rootDir: string): Promise<void>;
26
+ }
27
+ export declare function isManagedBranchWorkspace(rootDir: string, candidateDir: string): boolean;
28
+ export declare function createWorkspaceSnapshotManager(): WorkspaceSnapshotManager;