@abelxiaoxing/cadence 2.0.22 → 2.0.24
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/README.de.md +4 -10
- package/README.es.md +4 -10
- package/README.fr.md +4 -10
- package/README.ja.md +4 -10
- package/README.ko.md +4 -10
- package/README.md +5 -13
- package/README.pt-BR.md +4 -10
- package/README.ru.md +4 -10
- package/README.zh-CN.md +4 -12
- package/docs/conversation-mode.md +22 -2
- package/docs/history.md +50 -0
- package/docs/service-management.md +1 -1
- package/package.json +9 -7
- package/src/agent-panel-cadence.ts +4 -4
- package/src/cadence-mode.ts +284 -166
- package/src/coordinator-tools.mjs +9 -0
- package/src/data-shapes.ts +16 -0
- package/src/history-shell.ts +370 -0
- package/src/index.ts +3 -3
- package/src/native-build.ts +1 -1
- package/src/native-client.ts +1 -1
- package/src/native-workflow-history.ts +134 -0
- package/src/operator-cli.mjs +93 -65
- package/src/research-tools.mjs +365 -0
- package/src/sdk-worker.mjs +59 -9
- package/src/service/checkout-lock.ts +142 -0
- package/src/service/contracts/workbench.ts +43 -23
- package/src/service/contracts/workflow.ts +137 -2
- package/src/service/coordination.ts +6 -7
- package/src/service/private-files.ts +2 -1
- package/src/service-cli.mjs +259 -425
- package/src/service-host.mjs +3680 -6048
- package/src/worker-public.mjs +16 -1
- package/src/workspace.ts +302 -0
- package/web/dist/assets/cadence.css +1 -1
- package/web/dist/assets/cadence.js +16 -15
- package/web/dist/manifest.json +7 -7
- package/config/workflow-task.example.json +0 -7
- package/src/plan-proposal.ts +0 -87
- package/src/task-shell.ts +0 -1059
- package/src/task-store.ts +0 -593
- package/src/task-types.ts +0 -184
package/src/operator-cli.mjs
CHANGED
|
@@ -3,37 +3,20 @@
|
|
|
3
3
|
import path from "node:path";
|
|
4
4
|
|
|
5
5
|
// src/task-store.ts
|
|
6
|
-
import {
|
|
7
|
-
import { createHash, randomUUID } from "node:crypto";
|
|
6
|
+
import { createHash as createHash2, randomUUID as randomUUID2 } from "node:crypto";
|
|
8
7
|
import {
|
|
9
|
-
closeSync,
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
fsyncSync,
|
|
13
|
-
lstatSync,
|
|
14
|
-
mkdirSync,
|
|
15
|
-
openSync,
|
|
8
|
+
closeSync as closeSync3,
|
|
9
|
+
fsyncSync as fsyncSync2,
|
|
10
|
+
openSync as openSync3,
|
|
16
11
|
readdirSync,
|
|
17
|
-
readSync,
|
|
18
|
-
realpathSync,
|
|
19
12
|
renameSync,
|
|
20
|
-
unlinkSync,
|
|
21
|
-
writeFileSync
|
|
13
|
+
unlinkSync as unlinkSync2,
|
|
14
|
+
writeFileSync as writeFileSync2
|
|
22
15
|
} from "node:fs";
|
|
23
|
-
import {
|
|
24
|
-
import {
|
|
25
|
-
dirname,
|
|
26
|
-
isAbsolute,
|
|
27
|
-
join,
|
|
28
|
-
parse,
|
|
29
|
-
relative,
|
|
30
|
-
resolve,
|
|
31
|
-
sep
|
|
32
|
-
} from "node:path";
|
|
16
|
+
import { hostname as hostname2 } from "node:os";
|
|
17
|
+
import { join as join3 } from "node:path";
|
|
33
18
|
|
|
34
|
-
// src/
|
|
35
|
-
var TASK_SCHEMA = "cadence-workflow-assistant/1";
|
|
36
|
-
var MAX_RECORD_BYTES = 128 * 1024;
|
|
19
|
+
// src/data-shapes.ts
|
|
37
20
|
function object(value) {
|
|
38
21
|
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
39
22
|
}
|
|
@@ -43,6 +26,9 @@ function boundedString(value, max) {
|
|
|
43
26
|
function validId(value) {
|
|
44
27
|
return /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(value);
|
|
45
28
|
}
|
|
29
|
+
// src/task-types.ts
|
|
30
|
+
var TASK_SCHEMA = "cadence-workflow-assistant/1";
|
|
31
|
+
var MAX_RECORD_BYTES = 128 * 1024;
|
|
46
32
|
function decodeCheck(value) {
|
|
47
33
|
if (!object(value) || !boundedString(value.name, 128) || !value.name.trim() || !boundedString(value.command, 4096) || !value.command.trim() || !Number.isInteger(value.timeoutMs) || Number(value.timeoutMs) < 100 || Number(value.timeoutMs) > 1200000)
|
|
48
34
|
throw new Error("Invalid check definition");
|
|
@@ -111,7 +97,29 @@ function diagnosticText(value, maximum = 4096, secrets = []) {
|
|
|
111
97
|
return bytes.toString("utf8").replace(/\ufffd$/, "") + marker;
|
|
112
98
|
}
|
|
113
99
|
|
|
114
|
-
// src/
|
|
100
|
+
// src/workspace.ts
|
|
101
|
+
import { spawnSync } from "node:child_process";
|
|
102
|
+
import { createHash } from "node:crypto";
|
|
103
|
+
import {
|
|
104
|
+
closeSync,
|
|
105
|
+
constants,
|
|
106
|
+
fstatSync,
|
|
107
|
+
lstatSync,
|
|
108
|
+
mkdirSync,
|
|
109
|
+
openSync,
|
|
110
|
+
readSync,
|
|
111
|
+
realpathSync
|
|
112
|
+
} from "node:fs";
|
|
113
|
+
import { homedir } from "node:os";
|
|
114
|
+
import {
|
|
115
|
+
dirname,
|
|
116
|
+
isAbsolute,
|
|
117
|
+
join,
|
|
118
|
+
parse,
|
|
119
|
+
relative,
|
|
120
|
+
resolve,
|
|
121
|
+
sep
|
|
122
|
+
} from "node:path";
|
|
115
123
|
function parseRecord(data) {
|
|
116
124
|
try {
|
|
117
125
|
return JSON.parse(data.toString("utf8"));
|
|
@@ -247,13 +255,6 @@ function defaultStateHome() {
|
|
|
247
255
|
throw new Error("State home must be absolute");
|
|
248
256
|
return candidate ?? join(homedir(), process.platform === "win32" ? "AppData/Local" : ".local/state");
|
|
249
257
|
}
|
|
250
|
-
function recordText(record) {
|
|
251
|
-
return `${JSON.stringify(record, null, 2)}
|
|
252
|
-
`;
|
|
253
|
-
}
|
|
254
|
-
function contentIdentity(text) {
|
|
255
|
-
return createHash("sha256").update(text).digest("hex");
|
|
256
|
-
}
|
|
257
258
|
function canonicalAmbientRoot(path) {
|
|
258
259
|
const full = resolve(path);
|
|
259
260
|
try {
|
|
@@ -293,29 +294,39 @@ function effectiveWorkspace(requested, stateHome, _home) {
|
|
|
293
294
|
throw new Error("Choose a project outside Cadence private state; no default workspace was created");
|
|
294
295
|
return { workspace: requested, redirected: false };
|
|
295
296
|
}
|
|
296
|
-
|
|
297
|
-
|
|
297
|
+
// src/service/checkout-lock.ts
|
|
298
|
+
import { randomUUID } from "node:crypto";
|
|
299
|
+
import {
|
|
300
|
+
closeSync as closeSync2,
|
|
301
|
+
fsyncSync,
|
|
302
|
+
lstatSync as lstatSync2,
|
|
303
|
+
openSync as openSync2,
|
|
304
|
+
realpathSync as realpathSync2,
|
|
305
|
+
unlinkSync,
|
|
306
|
+
writeFileSync
|
|
307
|
+
} from "node:fs";
|
|
308
|
+
import { hostname } from "node:os";
|
|
309
|
+
import { dirname as dirname2, join as join2 } from "node:path";
|
|
310
|
+
class CheckoutStore {
|
|
298
311
|
root;
|
|
299
|
-
tasks;
|
|
300
312
|
privateRoot;
|
|
301
313
|
constructor(root, stateHome = defaultStateHome()) {
|
|
302
|
-
this.root =
|
|
314
|
+
this.root = realpathSync2(root);
|
|
303
315
|
if (privateWorkspace(this.root, stateHome))
|
|
304
316
|
throw new Error("Private state cannot be a workspace");
|
|
305
|
-
this.tasks = join(this.root, ".cadence", "assistant", "tasks");
|
|
306
317
|
this.privateRoot = privateRootFor(this.root, stateHome);
|
|
307
318
|
if (contains(this.root, this.privateRoot))
|
|
308
319
|
throw new Error("Private state home must be outside the working copy");
|
|
309
320
|
}
|
|
310
321
|
get lockPath() {
|
|
311
|
-
return
|
|
322
|
+
return join2(this.privateRoot, "checkout.lock");
|
|
312
323
|
}
|
|
313
324
|
inspectPrivate() {
|
|
314
|
-
const namespace =
|
|
325
|
+
const namespace = dirname2(this.privateRoot);
|
|
315
326
|
for (const path of [namespace, this.privateRoot]) {
|
|
316
327
|
if (!safeDirectory(path))
|
|
317
328
|
continue;
|
|
318
|
-
const st =
|
|
329
|
+
const st = lstatSync2(path);
|
|
319
330
|
if (process.platform !== "win32" && ((st.mode & 63) !== 0 || process.getuid && st.uid !== process.getuid()))
|
|
320
331
|
throw new Error("Private state permissions refused");
|
|
321
332
|
}
|
|
@@ -325,7 +336,7 @@ class TaskStore {
|
|
|
325
336
|
if (!safeDirectory(this.privateRoot))
|
|
326
337
|
return;
|
|
327
338
|
try {
|
|
328
|
-
const st =
|
|
339
|
+
const st = lstatSync2(path);
|
|
329
340
|
if (!st.isFile() || st.isSymbolicLink() || st.nlink !== 1 || st.size > max || process.platform !== "win32" && ((st.mode & 63) !== 0 || process.getuid && st.uid !== process.getuid()))
|
|
330
341
|
throw new Error("Unsafe private state file");
|
|
331
342
|
} catch (error) {
|
|
@@ -356,7 +367,7 @@ class TaskStore {
|
|
|
356
367
|
};
|
|
357
368
|
let fd;
|
|
358
369
|
try {
|
|
359
|
-
fd = retryWindowsFileOperation(() =>
|
|
370
|
+
fd = retryWindowsFileOperation(() => openSync2(this.lockPath, "wx", 384));
|
|
360
371
|
} catch {
|
|
361
372
|
throw new Error("Checkout busy or unresolved lock; inspect and explicitly recover only a dead owner");
|
|
362
373
|
}
|
|
@@ -364,7 +375,7 @@ class TaskStore {
|
|
|
364
375
|
writeFileSync(fd, JSON.stringify(lock));
|
|
365
376
|
fsyncSync(fd);
|
|
366
377
|
} finally {
|
|
367
|
-
|
|
378
|
+
closeSync2(fd);
|
|
368
379
|
}
|
|
369
380
|
return lock;
|
|
370
381
|
}
|
|
@@ -378,8 +389,24 @@ class TaskStore {
|
|
|
378
389
|
this.assertOwner(lock);
|
|
379
390
|
retryWindowsFileOperation(() => unlinkSync(this.lockPath), () => this.assertOwner(lock));
|
|
380
391
|
}
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
// src/task-store.ts
|
|
395
|
+
function recordText(record) {
|
|
396
|
+
return `${JSON.stringify(record, null, 2)}
|
|
397
|
+
`;
|
|
398
|
+
}
|
|
399
|
+
function contentIdentity(text) {
|
|
400
|
+
return createHash2("sha256").update(text).digest("hex");
|
|
401
|
+
}
|
|
402
|
+
class TaskStore extends CheckoutStore {
|
|
403
|
+
tasks;
|
|
404
|
+
constructor(root, stateHome = defaultStateHome()) {
|
|
405
|
+
super(root, stateHome);
|
|
406
|
+
this.tasks = join3(this.root, ".cadence", "assistant", "tasks");
|
|
407
|
+
}
|
|
381
408
|
recover(expected, acknowledgeEscapedProcesses) {
|
|
382
|
-
if (!acknowledgeEscapedProcesses || expected.host !==
|
|
409
|
+
if (!acknowledgeEscapedProcesses || expected.host !== hostname2())
|
|
383
410
|
throw new Error("Recovery requires informed local-owner confirmation");
|
|
384
411
|
this.assertOwner(expected);
|
|
385
412
|
try {
|
|
@@ -388,7 +415,7 @@ class TaskStore {
|
|
|
388
415
|
if (!object(error) || error.code !== "ESRCH")
|
|
389
416
|
throw new Error("Owner status unknown");
|
|
390
417
|
this.assertOwner(expected);
|
|
391
|
-
|
|
418
|
+
unlinkSync2(this.lockPath);
|
|
392
419
|
return;
|
|
393
420
|
}
|
|
394
421
|
throw new Error("Owner is live; stop it first");
|
|
@@ -399,10 +426,10 @@ class TaskStore {
|
|
|
399
426
|
loadSnapshot(id) {
|
|
400
427
|
if (!validId(id))
|
|
401
428
|
throw new Error("Invalid task id");
|
|
402
|
-
const directory =
|
|
429
|
+
const directory = join3(this.tasks, id);
|
|
403
430
|
if (safeDirectory(directory) && readdirSync(directory).some((name) => name !== "task.json"))
|
|
404
431
|
throw new Error("Unknown task directory content; preserved without reset");
|
|
405
|
-
const data = readBounded(
|
|
432
|
+
const data = readBounded(join3(this.tasks, id, "task.json"), MAX_RECORD_BYTES);
|
|
406
433
|
if (!data)
|
|
407
434
|
return;
|
|
408
435
|
const record = decodeTask(parseRecord(data));
|
|
@@ -431,7 +458,7 @@ class TaskStore {
|
|
|
431
458
|
if (Buffer.byteLength(text) > MAX_RECORD_BYTES)
|
|
432
459
|
throw new Error("Task record limit");
|
|
433
460
|
const lock = held ?? this.acquire();
|
|
434
|
-
if (lock.pid !== process.pid || lock.host !==
|
|
461
|
+
if (lock.pid !== process.pid || lock.host !== hostname2())
|
|
435
462
|
throw new Error("Not the lock owner");
|
|
436
463
|
try {
|
|
437
464
|
this.assertOwner(lock);
|
|
@@ -440,25 +467,25 @@ class TaskStore {
|
|
|
440
467
|
throw new Error("Revision conflict");
|
|
441
468
|
if (current?.identity !== expectedIdentity)
|
|
442
469
|
throw new Error("Task content changed; reopen it");
|
|
443
|
-
const dir =
|
|
470
|
+
const dir = join3(this.tasks, next.id);
|
|
444
471
|
safeDirectory(dir, true);
|
|
445
472
|
if (!current && readdirSync(dir).length)
|
|
446
473
|
throw new Error("Unknown task directory");
|
|
447
|
-
const temporary =
|
|
448
|
-
const fd =
|
|
474
|
+
const temporary = join3(dir, `task.${randomUUID2()}.tmp`);
|
|
475
|
+
const fd = openSync3(temporary, "wx", 384);
|
|
449
476
|
try {
|
|
450
|
-
|
|
451
|
-
|
|
477
|
+
writeFileSync2(fd, text);
|
|
478
|
+
fsyncSync2(fd);
|
|
452
479
|
} finally {
|
|
453
|
-
|
|
480
|
+
closeSync3(fd);
|
|
454
481
|
}
|
|
455
482
|
this.assertOwner(lock);
|
|
456
|
-
const latest = readBounded(
|
|
483
|
+
const latest = readBounded(join3(dir, "task.json"), MAX_RECORD_BYTES);
|
|
457
484
|
if ((latest ? contentIdentity(latest) : undefined) !== expectedIdentity)
|
|
458
485
|
throw new Error("Task content changed; replacement preserved without overwrite");
|
|
459
|
-
retryWindowsFileOperation(() => renameSync(temporary,
|
|
486
|
+
retryWindowsFileOperation(() => renameSync(temporary, join3(dir, "task.json")), () => {
|
|
460
487
|
this.assertOwner(lock);
|
|
461
|
-
const now = readBounded(
|
|
488
|
+
const now = readBounded(join3(dir, "task.json"), MAX_RECORD_BYTES);
|
|
462
489
|
if ((now ? contentIdentity(now) : undefined) !== expectedIdentity)
|
|
463
490
|
throw new Error("Task content changed; replacement preserved without overwrite");
|
|
464
491
|
});
|
|
@@ -469,7 +496,7 @@ class TaskStore {
|
|
|
469
496
|
}
|
|
470
497
|
}
|
|
471
498
|
checks() {
|
|
472
|
-
const data = readBounded(
|
|
499
|
+
const data = readBounded(join3(this.root, ".cadence", "assistant", "config.json"), 32768);
|
|
473
500
|
if (!data)
|
|
474
501
|
return [];
|
|
475
502
|
const value = parseRecord(data);
|
|
@@ -483,16 +510,16 @@ class TaskStore {
|
|
|
483
510
|
readLog(name) {
|
|
484
511
|
if (!/^[a-f0-9-]{36}\.log$/.test(name))
|
|
485
512
|
throw new Error("Invalid diagnostic name");
|
|
486
|
-
this.inspectPrivateFile(
|
|
487
|
-
const data = readBounded(
|
|
513
|
+
this.inspectPrivateFile(join3(this.privateRoot, name), 65536);
|
|
514
|
+
const data = readBounded(join3(this.privateRoot, name), 65536);
|
|
488
515
|
return data ? diagnosticText(data.toString("utf8"), 65536) : "Private diagnostic unavailable";
|
|
489
516
|
}
|
|
490
517
|
writeLog(lock, output) {
|
|
491
|
-
if (lock.pid !== process.pid || lock.host !==
|
|
518
|
+
if (lock.pid !== process.pid || lock.host !== hostname2())
|
|
492
519
|
throw new Error("Not the lock owner");
|
|
493
520
|
this.assertOwner(lock);
|
|
494
|
-
const name = `${
|
|
495
|
-
|
|
521
|
+
const name = `${randomUUID2()}.log`;
|
|
522
|
+
writeFileSync2(join3(this.privateRoot, name), diagnosticText(output, 65536), {
|
|
496
523
|
flag: "wx",
|
|
497
524
|
mode: 384
|
|
498
525
|
});
|
|
@@ -500,6 +527,7 @@ class TaskStore {
|
|
|
500
527
|
}
|
|
501
528
|
}
|
|
502
529
|
var TASK_CONFIG_SCHEMA = "cadence-assistant-checks/1";
|
|
530
|
+
var stores = new WeakMap;
|
|
503
531
|
|
|
504
532
|
// src/operator-tools.ts
|
|
505
533
|
var observed = (cwd) => resolveWorkspace(effectiveWorkspace(cwd).workspace);
|
|
@@ -0,0 +1,365 @@
|
|
|
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";
|
|
15
|
+
import { Type } from "typebox";
|
|
16
|
+
|
|
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,
|
|
27
|
+
};
|
|
28
|
+
const within = (root, path) => {
|
|
29
|
+
const p = relative(root, path);
|
|
30
|
+
return (
|
|
31
|
+
p === "" || (!isAbsolute(p) && p !== ".." && !p.startsWith(`..${sep}`))
|
|
32
|
+
);
|
|
33
|
+
};
|
|
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;
|
|
57
|
+
};
|
|
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.",
|
|
62
|
+
}),
|
|
63
|
+
);
|
|
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 }),
|
|
84
|
+
),
|
|
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
|
+
}),
|
|
112
|
+
},
|
|
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);
|
|
120
|
+
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,
|
|
171
|
+
);
|
|
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;
|
|
186
|
+
}
|
|
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;
|
|
194
|
+
}
|
|
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;
|
|
200
|
+
}
|
|
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");
|
|
219
|
+
continue;
|
|
220
|
+
}
|
|
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");
|
|
242
|
+
}
|
|
243
|
+
} finally {
|
|
244
|
+
await dir.close();
|
|
245
|
+
}
|
|
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),
|
|
253
|
+
);
|
|
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
|
+
}
|
|
342
|
+
}
|
|
343
|
+
} catch (e) {
|
|
344
|
+
if (!(e instanceof Bound)) throw e;
|
|
345
|
+
limits.add(e.message);
|
|
346
|
+
}
|
|
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
|
+
};
|
|
363
|
+
},
|
|
364
|
+
}));
|
|
365
|
+
}
|