@abelxiaoxing/cadence 2.0.36 → 2.0.37

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.
@@ -1,365 +1,429 @@
1
- /** Cooperative, bounded readonly investigation. No shell, downloads, raw spill,
2
- * or abandoned Promise.race: every original filesystem operation is joined.
3
- * Not a sandbox. The parent process deadline remains the hard stop for stuck I/O. */
4
- import { constants } from "node:fs";
5
- import { open, opendir, realpath, stat } from "node:fs/promises";
6
- import {
7
- basename,
8
- isAbsolute,
9
- join,
10
- matchesGlob,
11
- relative,
12
- resolve,
13
- sep,
14
- } from "node:path";
1
+ /** Model-facing observation tools and their worker-local resource lifetime.
2
+ * A cursor is one-use navigation, never execution authority or a durable snapshot. */
3
+ import { randomUUID } from "node:crypto";
15
4
  import { Type } from "typebox";
5
+ import { RESEARCH_LIMITS as L, ResearchScan } from "./research-scan.mjs";
16
6
 
17
- export const RESEARCH_LIMITS = {
18
- calls: 64,
19
- toolMs: 30_000,
20
- finishReserveMs: 120_000,
21
- entries: 2000,
22
- depth: 8,
23
- results: 100,
24
- fileBytes: 1024 * 1024,
25
- scanBytes: 8 * 1024 * 1024,
26
- outputBytes: 32 * 1024,
7
+ const object = (value, keys) => {
8
+ if (
9
+ !value ||
10
+ typeof value !== "object" ||
11
+ Array.isArray(value) ||
12
+ Object.keys(value).some((key) => !keys.includes(key))
13
+ )
14
+ throw new Error("Invalid investigation arguments");
15
+ return value;
27
16
  };
28
- const within = (root, path) => {
29
- const p = relative(root, path);
30
- return (
31
- p === "" || (!isAbsolute(p) && p !== ".." && !p.startsWith(`..${sep}`))
32
- );
17
+ const integer = (value, maximum = Number.MAX_SAFE_INTEGER, minimum = 1) => {
18
+ if (!Number.isSafeInteger(value) || value < minimum || value > maximum)
19
+ throw new Error("Invalid investigation range or limit");
20
+ return value;
33
21
  };
34
- class Bound extends Error {}
35
- const STOP =
36
- "Investigation budget reached. Do not retry the same search. Summarize retained evidence, missing coverage and a narrower follow-up for the user.";
37
-
38
- /** Node's same-host monotonic clock, not a child-local performance origin. */
39
- export const researchClock = () => Number(process.hrtime.bigint() / 1_000_000n);
40
-
41
- export function researchTools(cwd, roots, budget, now = researchClock) {
42
- const finishAt =
43
- budget.deadlineMs -
44
- Math.min(RESEARCH_LIMITS.finishReserveMs, budget.timeoutMs / 10);
45
- let calls = 0;
46
- // Resolve only when explicitly used, never during resource discovery.
47
- let selected;
48
- const scope = async () => {
49
- selected ??= (async () => {
50
- const paths = [];
51
- // Sequential originals: a rejected root cannot abandon sibling realpaths.
52
- for (const p of roots.length ? roots : [cwd])
53
- paths.push(await realpath(resolve(cwd, p)));
54
- return paths;
55
- })();
56
- return selected;
22
+ const string = (value, maximum = 4096) => {
23
+ if (
24
+ typeof value !== "string" ||
25
+ !value ||
26
+ value.length > maximum ||
27
+ value.includes("\0")
28
+ )
29
+ throw new Error("Invalid investigation path or pattern");
30
+ return value;
31
+ };
32
+ const array = (value, maximum) => {
33
+ if (!Array.isArray(value) || !value.length || value.length > maximum)
34
+ throw new Error("Invalid investigation batch");
35
+ return value;
36
+ };
37
+ const glob = (value) => {
38
+ string(value, 256);
39
+ if (/[{}()]/u.test(value))
40
+ throw new Error("Use a simple glob without braces or extglobs");
41
+ return value;
42
+ };
43
+ function query(kind, args) {
44
+ const common = ["pageSize", "path"];
45
+ object(args, [
46
+ ...common,
47
+ ...(kind === "read"
48
+ ? ["files", "offset", "limit"]
49
+ : kind === "grep"
50
+ ? ["pattern", "patterns", "glob", "depth", "ignoreCase", "literal"]
51
+ : kind === "find"
52
+ ? ["pattern", "depth"]
53
+ : []),
54
+ ]);
55
+ const result = {
56
+ kind,
57
+ pageSize: integer(args.pageSize ?? L.results, L.results),
57
58
  };
58
- const pathSchema = Type.Optional(
59
- Type.String({
60
- description:
61
- "Path inside the supplied investigation roots; omitted and relative paths use the first root. Never start at / or a parent directory.",
59
+ if (kind === "read") {
60
+ if (
61
+ args.files !== undefined &&
62
+ ["path", "offset", "limit"].some((key) => args[key] !== undefined)
63
+ )
64
+ throw new Error("Select either one file or a file batch");
65
+ const offset = integer(args.offset ?? 1);
66
+ const end =
67
+ args.limit === undefined
68
+ ? Number.MAX_SAFE_INTEGER
69
+ : integer(offset + integer(args.limit) - 1);
70
+ const files =
71
+ args.files === undefined
72
+ ? [{ path: string(args.path), ranges: [{ start: offset, end }] }]
73
+ : array(args.files, L.files);
74
+ let count = 0;
75
+ result.files = files.map((entry) => {
76
+ object(entry, ["path", "ranges"]);
77
+ const ranges = entry.ranges ?? [
78
+ { start: 1, end: Number.MAX_SAFE_INTEGER },
79
+ ];
80
+ return {
81
+ path: string(entry.path),
82
+ ranges: array(ranges, L.ranges).map((range) => {
83
+ object(range, ["start", "end"]);
84
+ if (++count > L.ranges)
85
+ throw new Error("Too many requested line ranges");
86
+ const start = integer(range.start);
87
+ return {
88
+ start,
89
+ end: integer(range.end, Number.MAX_SAFE_INTEGER, start),
90
+ };
91
+ }),
92
+ };
93
+ });
94
+ } else {
95
+ result.path = args.path === undefined ? undefined : string(args.path);
96
+ result.depth = integer(args.depth ?? L.depth, L.depth, 0);
97
+ if (kind === "find") result.glob = glob(args.pattern);
98
+ if (kind === "grep") {
99
+ if (args.literal !== undefined && args.literal !== true)
100
+ throw new Error("Research grep supports literal text only, not regex");
101
+ if (args.ignoreCase !== undefined && typeof args.ignoreCase !== "boolean")
102
+ throw new Error("Invalid case selection");
103
+ if ((args.pattern === undefined) === (args.patterns === undefined))
104
+ throw new Error("Supply one pattern or a patterns array");
105
+ result.ignoreCase = args.ignoreCase === true;
106
+ result.patterns = array(args.patterns ?? [args.pattern], L.patterns).map(
107
+ (pattern) => {
108
+ const text = string(pattern, 256);
109
+ return result.ignoreCase ? text.toLowerCase() : text;
110
+ },
111
+ );
112
+ if (args.glob !== undefined) result.glob = glob(args.glob);
113
+ }
114
+ }
115
+ return result;
116
+ }
117
+
118
+ const path = Type.Optional(
119
+ Type.String({
120
+ minLength: 1,
121
+ maxLength: 4096,
122
+ description:
123
+ "Within the admitted roots; relative paths use the first root.",
124
+ }),
125
+ );
126
+ const pageSize = Type.Optional(
127
+ Type.Integer({ minimum: 1, maximum: L.results }),
128
+ );
129
+ const depth = Type.Optional(Type.Integer({ minimum: 0, maximum: L.depth }));
130
+ const pattern = Type.String({ minLength: 1, maxLength: 256 });
131
+ // Provider function schemas require an object root, not a union of objects.
132
+ // Initial-query versus continuation exclusivity is checked before admission;
133
+ // every field is optional here because a continuation carries no query fields.
134
+ const parameters = (shape) =>
135
+ Type.Partial(
136
+ Type.Object({
137
+ ...shape,
138
+ cursor: Type.String({ minLength: 1, maxLength: 128 }),
139
+ close: Type.Literal(true),
62
140
  }),
141
+ { additionalProperties: false },
63
142
  );
64
- const limitSchema = Type.Optional(
65
- Type.Integer({ minimum: 1, maximum: RESEARCH_LIMITS.results }),
66
- );
67
- const tools = [
68
- {
69
- name: "ls",
70
- description:
71
- "List one directory without per-entry stat calls. Filesystem order, at most 100 entries; use a specific subdirectory to narrow. No recursive listing.",
72
- parameters: Type.Object({ path: pathSchema, limit: limitSchema }),
73
- },
74
- {
75
- name: "find",
76
- description:
77
- "Bounded simple filename glob search (*, **, ?, brackets; no braces/extglobs) inside an investigation root. At most 2000 entries, depth 8, 100 results and 30s cooperative work. Does not follow symlinks; skips .git/node_modules, not backup trees. Does not interpret .gitignore. Partial coverage is explicit; narrow the path rather than repeating.",
78
- parameters: Type.Object({
79
- pattern: Type.String({ minLength: 1, maxLength: 256 }),
80
- path: pathSchema,
81
- limit: limitSchema,
82
- depth: Type.Optional(
83
- Type.Integer({ minimum: 0, maximum: RESEARCH_LIMITS.depth }),
143
+ const definitions = [
144
+ {
145
+ name: "read",
146
+ description:
147
+ "Read UTF-8 text or a batch of file/line ranges. Use path with optional 1-based offset/limit, or files with ranges {start,end}. Overlapping ranges are merged. pageSize bounds one response, not the requested range. Resume a returned cursor instead of rereading a prefix; {cursor,close:true} releases it. Long/binary/invalid text omissions are explicit.",
148
+ parameters: parameters({
149
+ path,
150
+ offset: Type.Optional(Type.Integer({ minimum: 1 })),
151
+ limit: Type.Optional(Type.Integer({ minimum: 1 })),
152
+ files: Type.Optional(
153
+ Type.Array(
154
+ Type.Object(
155
+ {
156
+ path: Type.String(),
157
+ ranges: Type.Optional(
158
+ Type.Array(
159
+ Type.Object({
160
+ start: Type.Integer({ minimum: 1 }),
161
+ end: Type.Integer({ minimum: 1 }),
162
+ }),
163
+ { minItems: 1, maxItems: L.ranges },
164
+ ),
165
+ ),
166
+ },
167
+ { additionalProperties: false },
168
+ ),
169
+ { minItems: 1, maxItems: L.files },
84
170
  ),
85
- }),
86
- },
87
- {
88
- name: "grep",
89
- description:
90
- "Bounded literal text search (not regex). Search a specific file or narrow directory; optional simple filename glob (no braces/extglobs). At most 1MiB per file, 8MiB total, 2000 entries, depth 8, 100 matching lines. Binary files, symlinks and .git/node_modules are not searched; .gitignore is not interpreted. Reports incomplete coverage.",
91
- parameters: Type.Object({
92
- pattern: Type.String({ minLength: 1, maxLength: 256 }),
93
- path: pathSchema,
94
- glob: Type.Optional(Type.String({ maxLength: 256 })),
95
- ignoreCase: Type.Optional(Type.Boolean()),
96
- literal: Type.Optional(Type.Boolean()),
97
- limit: limitSchema,
98
- depth: Type.Optional(
99
- Type.Integer({ minimum: 0, maximum: RESEARCH_LIMITS.depth }),
100
- ),
101
- }),
102
- },
103
- {
104
- name: "read",
105
- description:
106
- "Read a bounded UTF-8 text file within the investigation roots. At most the first 1MiB, 100 requested lines and 32KiB output. Binary/media are not decoded; partial coverage is explicit.",
107
- parameters: Type.Object({
108
- path: Type.String(),
109
- offset: Type.Optional(Type.Integer({ minimum: 1 })),
110
- limit: limitSchema,
111
- }),
171
+ ),
172
+ pageSize,
173
+ }),
174
+ },
175
+ {
176
+ name: "grep",
177
+ description:
178
+ "Search literal text, not regex, in one file or a tree. Supply pattern or patterns (OR; matchedPatterns are zero-based input indexes). Each file is scanned once per query. Optional simple glob, ignoreCase and depth. No symlink traversal, .gitignore interpretation, or .git/node_modules scan. Empty pages with a cursor are progress, NOT absence. Resume with {cursor}, or release with {cursor,close:true}.",
179
+ parameters: parameters({
180
+ path,
181
+ pattern: Type.Optional(pattern),
182
+ patterns: Type.Optional(
183
+ Type.Array(pattern, { minItems: 1, maxItems: L.patterns }),
184
+ ),
185
+ glob: Type.Optional(pattern),
186
+ literal: Type.Optional(Type.Literal(true)),
187
+ ignoreCase: Type.Optional(Type.Boolean()),
188
+ depth,
189
+ pageSize,
190
+ }),
191
+ },
192
+ {
193
+ name: "find",
194
+ description:
195
+ "Find file paths with a simple glob (*, **, ?, brackets; no braces/extglobs). Bounded traversal in filesystem order, skipping tree symlinks and .git/node_modules, not backup trees; .gitignore is not interpreted. Resume actual directory positions with {cursor}; {cursor,close:true} releases them. Coverage/omissions are explicit.",
196
+ parameters: parameters({ path, pattern, depth, pageSize }),
197
+ },
198
+ {
199
+ name: "ls",
200
+ description:
201
+ "List one directory in filesystem order, including entry kinds. Does not follow symlinks or recurse. Continue with the returned {cursor}, not a repeated initial request; {cursor,close:true} releases it.",
202
+ parameters: parameters({ path, pageSize }),
203
+ },
204
+ ];
205
+
206
+ function render(scan, items, state, nextCursor, pausedBy, elapsedMs) {
207
+ const omissions = [...scan.omissions].map(([reason, count]) => ({
208
+ reason,
209
+ count,
210
+ }));
211
+ const details = {
212
+ state,
213
+ nextCursor,
214
+ pausedBy,
215
+ coverage: {
216
+ complete: state === "done" && !omissions.length,
217
+ consistency: "live-filesystem",
218
+ omissions,
112
219
  },
113
- ];
114
- return tools.map((tool) => ({
115
- ...tool,
116
- label: tool.name,
117
- async execute(_id, args, signal) {
118
- if (++calls > RESEARCH_LIMITS.calls || now() >= finishAt)
119
- throw new Error(STOP);
220
+ progress: { ...scan.page, total: { ...scan.total } },
221
+ elapsedMs,
222
+ ...(state === "more" || omissions.length
223
+ ? {
224
+ truncation: {
225
+ reason: [
226
+ ...(pausedBy ? [pausedBy] : []),
227
+ ...omissions.map((o) => o.reason),
228
+ ],
229
+ },
230
+ }
231
+ : {}),
232
+ };
233
+ return {
234
+ content: [{ type: "text", text: JSON.stringify({ items, ...details }) }],
235
+ details,
236
+ };
237
+ }
238
+ const size = (result) => Buffer.byteLength(JSON.stringify(result));
239
+
240
+ export function createResearchTools(workspace, now = () => performance.now()) {
241
+ const scans = new Set();
242
+ const cursors = new Map();
243
+ let closing = false,
244
+ closingOriginal,
245
+ failure;
246
+ const finish = (scan) => {
247
+ scan.finishing ??= (async () => {
248
+ try {
249
+ await scan.close();
250
+ scans.delete(scan);
251
+ } catch {
252
+ failure = new Error("Investigation resource closure failed");
253
+ throw failure;
254
+ }
255
+ })();
256
+ return scan.finishing;
257
+ };
258
+ const stop = async (scan) => {
259
+ scan.stopping = true;
260
+ await scan.active?.catch(() => {});
261
+ await finish(scan);
262
+ };
263
+ const execute = (kind, args, signal) => {
264
+ if (closing || failure)
265
+ return Promise.reject(failure ?? new Error("Investigation tools closed"));
266
+ if (signal?.aborted)
267
+ return Promise.reject(new Error("Investigation canceled"));
268
+ let scan,
269
+ close = false;
270
+ try {
271
+ if (args?.cursor !== undefined) {
272
+ object(args, ["cursor", "close"]);
273
+ if (args.close !== undefined && args.close !== true)
274
+ throw new Error("Invalid cursor operation");
275
+ const token = string(args.cursor, 128);
276
+ scan = cursors.get(token);
277
+ if (scan && scan.query.kind === kind && now() >= scan.expiresAt) {
278
+ cursors.delete(token);
279
+ clearTimeout(scan.timer);
280
+ void stop(scan).catch(() => {
281
+ /* finish retains the closure failure. */
282
+ });
283
+ throw new Error(
284
+ "Investigation cursor expired; start a fresh query explicitly",
285
+ );
286
+ }
287
+ if (!scan || scan.query.kind !== kind)
288
+ throw new Error(
289
+ "Investigation cursor consumed or foreign; start a fresh query explicitly",
290
+ );
291
+ cursors.delete(token);
292
+ clearTimeout(scan.timer);
293
+ close = args.close === true;
294
+ } else {
295
+ const request = query(kind, args);
296
+ if (scans.size >= L.scans)
297
+ throw new Error(
298
+ "Investigation cursor capacity reached; close an unused cursor",
299
+ );
300
+ scan = new ResearchScan(workspace, request);
301
+ scans.add(scan); // Reserve before the first asynchronous filesystem operation.
302
+ }
303
+ } catch (error) {
304
+ return Promise.reject(error);
305
+ }
306
+ const original = (async () => {
120
307
  const startedAt = now();
121
- const deadline = Math.min(finishAt, now() + RESEARCH_LIMITS.toolMs);
122
- const check = () => {
123
- if (signal?.aborted) throw new Error("Investigation canceled");
124
- if (now() >= deadline) throw new Bound("cooperative time limit");
125
- };
126
- const limits = new Set();
127
- const lines = [];
128
- let entries = 0,
129
- bytes = 0,
130
- outputBytes = 0;
131
- const limit = args.limit ?? RESEARCH_LIMITS.results;
132
- if (
133
- !Number.isSafeInteger(limit) ||
134
- limit < 1 ||
135
- limit > RESEARCH_LIMITS.results
136
- )
137
- throw new Error("Invalid result limit");
138
- const depth = args.depth ?? RESEARCH_LIMITS.depth;
139
- if (
140
- !Number.isSafeInteger(depth) ||
141
- depth < 0 ||
142
- depth > RESEARCH_LIMITS.depth
143
- )
144
- throw new Error("Invalid search depth");
145
- const add = (line) => {
146
- if (lines.length >= limit) throw new Bound("result limit");
147
- if (
148
- outputBytes + Buffer.byteLength(line) + 1 >
149
- RESEARCH_LIMITS.outputBytes
150
- )
151
- throw new Bound("output limit");
152
- outputBytes += Buffer.byteLength(line) + 1;
153
- lines.push(line);
154
- };
155
- const read = async (path) => {
156
- check();
157
- const file = await open(
158
- path,
159
- constants.O_RDONLY |
160
- constants.O_NONBLOCK |
161
- (constants.O_NOFOLLOW ?? 0),
162
- );
163
- try {
164
- check();
165
- const info = await file.stat();
166
- if (!info.isFile())
167
- throw new Error("Only regular text files can be read");
168
- const size = Math.min(
169
- RESEARCH_LIMITS.fileBytes,
170
- RESEARCH_LIMITS.scanBytes - bytes,
308
+ scan.begin(signal);
309
+ const items = [];
310
+ const token = randomUUID();
311
+ let done = false,
312
+ pausedBy = null;
313
+ try {
314
+ if (close) {
315
+ await finish(scan);
316
+ return render(
317
+ scan,
318
+ [],
319
+ "closed",
320
+ null,
321
+ null,
322
+ Math.max(0, now() - startedAt),
171
323
  );
172
- if (!size) throw new Bound("aggregate byte limit");
173
- const buffer = Buffer.alloc(size);
174
- let offset = 0;
175
- while (offset < size) {
176
- check();
177
- const result = await file.read(
178
- buffer,
179
- offset,
180
- Math.min(65536, size - offset),
181
- offset,
182
- );
183
- bytes += result.bytesRead;
184
- if (!result.bytesRead) break;
185
- offset += result.bytesRead;
324
+ }
325
+ await scan.validate();
326
+ for (;;) {
327
+ scan.check();
328
+ if (now() - startedAt >= L.toolMs) {
329
+ pausedBy = "cooperative time quantum";
330
+ break;
186
331
  }
187
- check();
188
- // Read actual EOF, not stat.size (virtual/growing files can report zero).
189
- if (offset === size) limits.add("file/aggregate byte limit");
190
- const content = buffer.subarray(0, offset);
191
- if (content.includes(0)) {
192
- limits.add("binary file omitted");
193
- return null;
332
+ const next = scan.pending ?? (await scan.iterator.next());
333
+ scan.pending = undefined;
334
+ scan.check();
335
+ if (next.done) {
336
+ done = true;
337
+ break;
194
338
  }
195
- try {
196
- return new TextDecoder("utf-8", { fatal: true }).decode(content);
197
- } catch {
198
- limits.add("non-UTF-8 or cut UTF-8 file omitted");
199
- return null;
339
+ if (!next.value) continue;
340
+ if (next.value.pause) {
341
+ pausedBy = next.value.pause;
342
+ break;
200
343
  }
201
- } finally {
202
- await file.close();
203
- }
204
- };
205
- const walk = async function* (path, remaining, root) {
206
- check();
207
- const dir = await opendir(path);
208
- try {
209
- for (;;) {
210
- check();
211
- const e = await dir.read();
212
- check();
213
- if (!e) break;
214
- if (++entries > RESEARCH_LIMITS.entries)
215
- throw new Bound("entry limit");
216
- const full = join(path, e.name);
217
- if (e.isSymbolicLink()) {
218
- limits.add("symlink omitted");
344
+ const item = next.value.item;
345
+ const candidate = render(
346
+ scan,
347
+ [...items, item],
348
+ "more",
349
+ token,
350
+ "output quantum",
351
+ 0,
352
+ );
353
+ // Reserve bounded metadata growth (counters/omissions/elapsed) while
354
+ // charging the entire encoded envelope, not just unescaped line text.
355
+ if (size(candidate) > L.outputBytes - 4096) {
356
+ if (!items.length) {
357
+ scan.omit("oversized result omitted");
219
358
  continue;
220
359
  }
221
- if (e.isDirectory()) {
222
- if (e.name === ".git" || e.name === "node_modules") {
223
- limits.add(".git/node_modules omitted");
224
- continue;
225
- }
226
- if (remaining === 0) {
227
- limits.add("depth limit");
228
- continue;
229
- }
230
- try {
231
- yield* walk(full, remaining - 1, root);
232
- } catch (error) {
233
- if (error instanceof Bound || signal?.aborted) throw error;
234
- limits.add("unreadable directory omitted");
235
- }
236
- } else if (e.isFile())
237
- yield {
238
- path: full,
239
- name: relative(root, full).split(sep).join("/"),
240
- };
241
- else limits.add("special file omitted");
360
+ scan.pending = next;
361
+ pausedBy = "output quantum";
362
+ break;
242
363
  }
243
- } finally {
244
- await dir.close();
364
+ if (items.length >= scan.query.pageSize) {
365
+ scan.pending = next;
366
+ pausedBy = "result quantum";
367
+ break;
368
+ }
369
+ items.push(item);
245
370
  }
246
- };
247
- try {
248
- check();
249
- const allowed = await scope();
250
- check();
251
- const target = await realpath(
252
- args.path === undefined ? allowed[0] : resolve(allowed[0], args.path),
371
+ await scan.validate();
372
+ scan.check();
373
+ if (done) await finish(scan);
374
+ const result = render(
375
+ scan,
376
+ items,
377
+ done ? "done" : "more",
378
+ done ? null : token,
379
+ pausedBy,
380
+ Math.max(0, now() - startedAt),
253
381
  );
254
- check();
255
- if (!allowed.some((p) => within(p, target)))
256
- throw new Error(
257
- "Path outside investigation roots. Ask the coordinator to select the specific intended root; do not enumerate parent directories.",
258
- );
259
- const info = await stat(target);
260
- check();
261
- if (tool.name === "ls") {
262
- if (!info.isDirectory()) throw new Error("Select a directory");
263
- const dir = await opendir(target);
264
- try {
265
- for (;;) {
266
- check();
267
- const e = await dir.read();
268
- check();
269
- if (!e) break;
270
- entries++;
271
- add(
272
- `${e.name}${e.isDirectory() ? "/" : e.isSymbolicLink() ? " [symlink; not followed]" : ""}`,
273
- );
274
- }
275
- } finally {
276
- await dir.close();
277
- }
278
- } else if (tool.name === "read") {
279
- const content = await read(target);
280
- const offset = args.offset ?? 1;
281
- if (!Number.isSafeInteger(offset) || offset < 1)
282
- throw new Error("Invalid line offset");
283
- if (content !== null)
284
- for (const line of content.split("\n").slice(offset - 1)) {
285
- check();
286
- add(line);
287
- }
288
- } else {
289
- if (tool.name === "grep" && args.literal === false)
290
- throw new Error(
291
- "Research grep supports literal text only. Supply a literal pattern, not a regex.",
292
- );
293
- const glob = tool.name === "find" ? args.pattern : args.glob;
294
- if (
295
- glob !== undefined &&
296
- (typeof glob !== "string" ||
297
- !glob ||
298
- glob.length > 256 ||
299
- /[{}()]/u.test(glob))
300
- )
301
- throw new Error("Use a simple glob without braces or extglobs");
302
- const pattern = args.ignoreCase
303
- ? args.pattern.toLowerCase()
304
- : args.pattern;
305
- const files = info.isDirectory()
306
- ? walk(target, depth, target)
307
- : [{ path: target, name: basename(target) }];
308
- for await (const file of files) {
309
- check();
310
- if (
311
- glob &&
312
- !matchesGlob(
313
- glob.includes("/") ? file.name : basename(file.name),
314
- glob,
315
- )
316
- )
317
- continue;
318
- if (tool.name === "find") add(file.name);
319
- else {
320
- let content;
321
- try {
322
- content = await read(file.path);
323
- } catch (e) {
324
- if (e instanceof Bound || signal?.aborted) throw e;
325
- limits.add("unreadable file omitted");
326
- continue;
327
- }
328
- if (content === null) continue;
329
- let n = 0;
330
- for (const line of content.split("\n")) {
331
- check();
332
- n++;
333
- if (
334
- (args.ignoreCase ? line.toLowerCase() : line).includes(
335
- pattern,
336
- )
337
- )
338
- add(`${file.name}:${n}: ${line}`);
339
- }
340
- }
341
- }
382
+ if (size(result) > L.outputBytes)
383
+ throw new Error("Investigation reply exceeds bound");
384
+ if (!done) {
385
+ scan.expiresAt = now() + L.idleMs;
386
+ cursors.set(token, scan);
387
+ scan.timer = setTimeout(() => {
388
+ cursors.delete(token);
389
+ void stop(scan).catch(() => {
390
+ /* finish retains the failure and reservation. */
391
+ });
392
+ }, L.idleMs);
393
+ scan.timer.unref();
342
394
  }
343
- } catch (e) {
344
- if (!(e instanceof Bound)) throw e;
345
- limits.add(e.message);
395
+ return result;
396
+ } catch (error) {
397
+ await finish(scan);
398
+ throw error;
346
399
  }
347
- // A bounded prefix is evidence, never proof that the unsearched tree has no match.
348
- const partial = limits.size > 0;
349
- return {
350
- content: [
351
- {
352
- type: "text",
353
- text: `${lines.join("\n") || (partial ? "No results in the inspected portion." : "No results in the requested scope.")}\n\n${partial ? `[Partial coverage: ${[...limits].join(", ")}. Narrow the path; do not infer absence.]` : "[Requested scope inspected.]"}${now() >= finishAt || calls >= RESEARCH_LIMITS.calls ? `\n${STOP}` : ""}`,
354
- },
355
- ],
356
- details: {
357
- elapsedMs: Math.max(0, now() - startedAt),
358
- inspectedEntries: entries,
359
- readBytes: bytes,
360
- ...(partial ? { truncation: { reason: [...limits] } } : {}),
361
- },
362
- };
400
+ })();
401
+ scan.active = original;
402
+ // Return the tracked original. No detached rejecting finally promise.
403
+ return original.finally(() => {
404
+ if (scan.active === original) scan.active = undefined;
405
+ });
406
+ };
407
+ return {
408
+ tools: definitions.map((tool) => ({
409
+ ...tool,
410
+ label: tool.name,
411
+ execute: (_id, args, signal) => execute(tool.name, args, signal),
412
+ })),
413
+ close() {
414
+ if (closingOriginal) return closingOriginal;
415
+ closing = true;
416
+ for (const scan of cursors.values()) clearTimeout(scan.timer);
417
+ cursors.clear();
418
+ closingOriginal = (async () => {
419
+ const outcomes = await Promise.allSettled([...scans].map(stop));
420
+ if (
421
+ failure ||
422
+ outcomes.some((outcome) => outcome.status === "rejected")
423
+ )
424
+ throw failure ?? new Error("Investigation resource closure failed");
425
+ })();
426
+ return closingOriginal;
363
427
  },
364
- }));
428
+ };
365
429
  }