@cydm/pie 4.13.1 → 4.14.1
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/dist/builtin/extensions/ask-user/index.js +4 -4
- package/dist/builtin/extensions/cron/index.js +70 -17
- package/dist/builtin/extensions/im-forward/index.js +8094 -8100
- package/dist/builtin/extensions/mcp-adapter/index.js +86 -81
- package/dist/builtin/extensions/memory/index.js +30 -7
- package/dist/builtin/extensions/pie-ipc/index.js +13 -18
- package/dist/builtin/extensions/pie-proc/README.md +12 -3
- package/dist/builtin/extensions/pie-proc/index.js +145 -96
- package/dist/builtin/extensions/plan-mode/index.js +4 -4
- package/dist/builtin/extensions/subagent/index.js +5 -5
- package/dist/builtin/extensions/todo/index.js +4 -4
- package/dist/chunks/{chunk-6Z54UHXM.js → chunk-2WLKAMOH.js} +21 -16
- package/dist/chunks/{chunk-3F2CSVNH.js → chunk-DJ4LO7PQ.js} +2 -1
- package/dist/chunks/{chunk-MCR4JYI6.js → chunk-IM7DLPPY.js} +74 -8
- package/dist/chunks/{chunk-HSMO2BEA.js → chunk-IQDVL34H.js} +24 -19
- package/dist/chunks/{chunk-DT22BBZL.js → chunk-OQCKDEEE.js} +1 -1
- package/dist/chunks/{chunk-26KRUYZH.js → chunk-SAXKBFX3.js} +1 -1
- package/dist/chunks/{chunk-CCPNHS6B.js → chunk-SYZR74QO.js} +1582 -1570
- package/dist/chunks/{chunk-UCVPNLCO.js → chunk-TNRZEQD5.js} +2 -2
- package/dist/chunks/{chunk-NHWWRE3T.js → chunk-TTSQWGAT.js} +727 -719
- package/dist/chunks/{chunk-XPJHZRTN.js → chunk-X3ZVZB2R.js} +1133 -381
- package/dist/chunks/{host-image-fallback-LGWYQMLA.js → host-image-fallback-AEKY2LSZ.js} +1 -1
- package/dist/chunks/{manager-cli-OTIMAWO6.js → manager-cli-ZV36YNPJ.js} +187 -173
- package/dist/chunks/{memory-git-7SRO5KLB.js → memory-git-G56IXFWU.js} +5 -5
- package/dist/chunks/{model-registry-IWOOAMLZ.js → model-registry-4LM2I6FR.js} +2 -2
- package/dist/chunks/{read-file-understanding-3TYWVOLX.js → read-file-understanding-GTNZHAK5.js} +5 -5
- package/dist/chunks/{src-WA2O2O2V.js → src-3YJ4UVEC.js} +3 -3
- package/dist/chunks/{src-ALHMJZ5R.js → src-APNP4M4N.js} +2 -2
- package/dist/chunks/{src-D2ICRXWW.js → src-T6AUO53N.js} +24 -6
- package/dist/chunks/{src-76Q33OY5.js → src-TNUD7EDH.js} +1 -1
- package/dist/chunks/{test-stream-OVGDTXOY.js → test-stream-EF2DHEHV.js} +1 -1
- package/dist/cli.js +3131 -3013
- package/package.json +1 -1
- package/dist/chunks/{chunk-3GG342QY.js → chunk-TYCKSYUF.js} +19 -19
|
@@ -18,11 +18,11 @@ import {
|
|
|
18
18
|
parseEntryIdSeq,
|
|
19
19
|
readAncestryPage,
|
|
20
20
|
requestInteraction
|
|
21
|
-
} from "./chunk-
|
|
21
|
+
} from "./chunk-SYZR74QO.js";
|
|
22
22
|
import {
|
|
23
23
|
Agent,
|
|
24
24
|
getToolCallerIdentity
|
|
25
|
-
} from "./chunk-
|
|
25
|
+
} from "./chunk-SAXKBFX3.js";
|
|
26
26
|
import {
|
|
27
27
|
ALL_THINKING_LEVELS,
|
|
28
28
|
AssistantMessageEventStream,
|
|
@@ -33,7 +33,7 @@ import {
|
|
|
33
33
|
hashText,
|
|
34
34
|
resolveThinkingSelection,
|
|
35
35
|
streamSimple
|
|
36
|
-
} from "./chunk-
|
|
36
|
+
} from "./chunk-IM7DLPPY.js";
|
|
37
37
|
import {
|
|
38
38
|
Type
|
|
39
39
|
} from "./chunk-XXGYUYXI.js";
|
|
@@ -632,7 +632,7 @@ function createSearchContextTool(getReader) {
|
|
|
632
632
|
}
|
|
633
633
|
scanned++;
|
|
634
634
|
if (scanned % yieldEvery === 0) {
|
|
635
|
-
await new Promise((
|
|
635
|
+
await new Promise((resolve7) => setTimeout(resolve7, 0));
|
|
636
636
|
if (signal?.aborted) throw new Error("History search aborted");
|
|
637
637
|
if (reader.getActiveSessionId() !== session || reader.getHistoryBranchRevision() !== revision) throw new Error("History changed; restart search");
|
|
638
638
|
}
|
|
@@ -1521,13 +1521,13 @@ function checkPlanScope(items, exists, isNew) {
|
|
|
1521
1521
|
const seen = /* @__PURE__ */ new Set();
|
|
1522
1522
|
for (const item of items) {
|
|
1523
1523
|
for (const rawPath of item.files ?? []) {
|
|
1524
|
-
const
|
|
1525
|
-
if (!
|
|
1526
|
-
seen.add(
|
|
1527
|
-
if (isNew(item,
|
|
1528
|
-
if (exists(
|
|
1529
|
-
} else if (!exists(
|
|
1530
|
-
warnings.push({ path:
|
|
1524
|
+
const path12 = String(rawPath ?? "").trim();
|
|
1525
|
+
if (!path12 || seen.has(path12)) continue;
|
|
1526
|
+
seen.add(path12);
|
|
1527
|
+
if (isNew(item, path12)) {
|
|
1528
|
+
if (exists(path12)) warnings.push({ path: path12, kind: "exists" });
|
|
1529
|
+
} else if (!exists(path12)) {
|
|
1530
|
+
warnings.push({ path: path12, kind: "missing" });
|
|
1531
1531
|
}
|
|
1532
1532
|
}
|
|
1533
1533
|
}
|
|
@@ -1649,12 +1649,12 @@ Focus: ${request.question.trim()}` : ""}` },
|
|
|
1649
1649
|
const capability = agentModel.fileCapabilities?.[request.kind];
|
|
1650
1650
|
const audioSupported = request.kind !== "audio" || ["audio/wav", "audio/mpeg", "audio/mp3"].includes(request.mimeType);
|
|
1651
1651
|
if (capability && typeof capability === "object" && capability.supported !== false && capability.nativeInline === true && audioSupported && (!capability.formats || capability.formats.includes(request.mimeType)) && capability.maxDurationSeconds === void 0) {
|
|
1652
|
-
const
|
|
1653
|
-
const size = (await
|
|
1652
|
+
const fs10 = getFileSystem();
|
|
1653
|
+
const size = (await fs10.stat(request.absolutePath)).size;
|
|
1654
1654
|
const cap = Math.min(capability.maxFileSizeMb ?? 15, 15) * 1024 * 1024;
|
|
1655
1655
|
if (size > 0 && size <= cap) {
|
|
1656
1656
|
if (request.signal?.aborted) throw new Error("Operation aborted");
|
|
1657
|
-
const data = await
|
|
1657
|
+
const data = await fs10.readFile(request.absolutePath, "base64");
|
|
1658
1658
|
if (request.signal?.aborted) throw new Error("Operation aborted");
|
|
1659
1659
|
const readBytes = Math.floor(data.length * 3 / 4) - (data.endsWith("==") ? 2 : data.endsWith("=") ? 1 : 0);
|
|
1660
1660
|
if (readBytes > 0 && readBytes <= cap && data) return {
|
|
@@ -1934,11 +1934,11 @@ function isRetryableSubagentFailureFrom(facts) {
|
|
|
1934
1934
|
return remoteClosure || /Request timeout/i.test(message) || /econnreset|econnaborted|etimedout|eai_again|econnrefused|socket hang up|socket disconnected|secure TLS connection|fetch failed|network error|connection reset|premature close|\b(?:408|50[0234]|52[0-69]|530)\b|bad gateway|service unavailable|gateway timeout/i.test(message);
|
|
1935
1935
|
}
|
|
1936
1936
|
function cancellableBackoff(ms, signal) {
|
|
1937
|
-
return new Promise((
|
|
1937
|
+
return new Promise((resolve7) => {
|
|
1938
1938
|
const finish = () => {
|
|
1939
1939
|
clearTimeout(timer);
|
|
1940
1940
|
signal?.removeEventListener("abort", finish);
|
|
1941
|
-
|
|
1941
|
+
resolve7();
|
|
1942
1942
|
};
|
|
1943
1943
|
const timer = setTimeout(finish, ms);
|
|
1944
1944
|
signal?.addEventListener("abort", finish, { once: true });
|
|
@@ -2057,9 +2057,9 @@ async function closeIterator(iterator, hooks, signal) {
|
|
|
2057
2057
|
try {
|
|
2058
2058
|
await Promise.race([
|
|
2059
2059
|
cleanup,
|
|
2060
|
-
new Promise((
|
|
2061
|
-
timer = setTimeout(
|
|
2062
|
-
onAbort = () =>
|
|
2060
|
+
new Promise((resolve7) => {
|
|
2061
|
+
timer = setTimeout(resolve7, waitMs);
|
|
2062
|
+
onAbort = () => resolve7();
|
|
2063
2063
|
signal?.addEventListener("abort", onAbort, { once: true });
|
|
2064
2064
|
})
|
|
2065
2065
|
]);
|
|
@@ -2388,136 +2388,257 @@ function transplantMessages(target, messages) {
|
|
|
2388
2388
|
}
|
|
2389
2389
|
}
|
|
2390
2390
|
|
|
2391
|
-
// ../../packages/shared-headless-capabilities/src/
|
|
2392
|
-
|
|
2393
|
-
|
|
2394
|
-
|
|
2395
|
-
|
|
2396
|
-
function isSubagentOverflowFailure(failure, errorMessage, stopReason) {
|
|
2397
|
-
if (stopReason === "aborted" || stopReason === "length") return false;
|
|
2398
|
-
if (failure?.recovery?.outcome === "overflow") return true;
|
|
2399
|
-
if (failure?.classification?.kind === "context_overflow") return true;
|
|
2400
|
-
if (failure?.remoteFailure?.category === "context_overflow") return true;
|
|
2401
|
-
return Boolean(errorMessage && isDefaultContextOverflowError(errorMessage));
|
|
2402
|
-
}
|
|
2403
|
-
function isSubagentModelFallbackTrigger(errorMessage, failure, stopReason) {
|
|
2404
|
-
if (stopReason === "aborted" || stopReason === "length") return false;
|
|
2405
|
-
const kind = failure?.classification?.kind;
|
|
2406
|
-
if (kind === "user_abort" || kind === "invalid_request" || kind === "context_overflow") return false;
|
|
2407
|
-
if (errorMessage && isDefaultQuotaExhaustedError(errorMessage)) return true;
|
|
2408
|
-
if (kind === "auth_config") return true;
|
|
2409
|
-
if (failure?.recovery?.outcome === "exhausted" && (kind === "provider_transient" || kind === "provider_confirmation" || kind === "transient_network")) {
|
|
2410
|
-
return true;
|
|
2411
|
-
}
|
|
2412
|
-
return false;
|
|
2391
|
+
// ../../packages/shared-headless-capabilities/src/bash-policy-writes.ts
|
|
2392
|
+
function executableName(word) {
|
|
2393
|
+
const normalized = word.replace(/\\/g, "/").toLowerCase();
|
|
2394
|
+
const base = normalized.slice(normalized.lastIndexOf("/") + 1);
|
|
2395
|
+
return base.endsWith(".exe") ? base.slice(0, -4) : base;
|
|
2413
2396
|
}
|
|
2414
|
-
|
|
2415
|
-
|
|
2416
|
-
|
|
2417
|
-
|
|
2418
|
-
|
|
2419
|
-
|
|
2420
|
-
|
|
2421
|
-
|
|
2397
|
+
var LEGACY_FILESYSTEM_WRITE_RE = /(^|[;&|\n])\s*(cp|mv|mkdir|touch|tee|sed|perl)\b/;
|
|
2398
|
+
var FILESYSTEM_WRITE_COMMANDS = /* @__PURE__ */ new Set(["cp", "mv", "mkdir", "touch", "tee", "sed", "perl"]);
|
|
2399
|
+
var SHELL_CONTROL_PREFIXES = /* @__PURE__ */ new Set(["!", "if", "then", "elif", "else", "do", "while", "until", "coproc", "{"]);
|
|
2400
|
+
var WRITE_WRAPPER_NAMES = /* @__PURE__ */ new Set(["env", "command", "exec", "nohup", "setsid", "time", "nice", "timeout", "xargs", "builtin"]);
|
|
2401
|
+
var WRITE_WRAPPER_VALUE_FLAGS = {
|
|
2402
|
+
env: /* @__PURE__ */ new Set(["-u", "--unset", "-C", "--chdir"]),
|
|
2403
|
+
exec: /* @__PURE__ */ new Set(["-a"]),
|
|
2404
|
+
time: /* @__PURE__ */ new Set(["-o", "-f", "--output", "--format"]),
|
|
2405
|
+
nice: /* @__PURE__ */ new Set(["-n", "--adjustment"]),
|
|
2406
|
+
timeout: /* @__PURE__ */ new Set(["-k", "--kill-after", "-s", "--signal"]),
|
|
2407
|
+
xargs: /* @__PURE__ */ new Set(["-a", "-d", "-E", "-I", "-L", "-n", "-P", "-s", "--arg-file", "--delimiter", "--eof", "--replace", "--max-lines", "--max-args", "--max-procs", "--max-chars"])
|
|
2408
|
+
};
|
|
2409
|
+
var STANDALONE_REDIR_RE = /^(?:\d+)?(?:>>?|<<?|<>|>&|<&|&>>?)$/;
|
|
2410
|
+
var INLINE_REDIR_RE = /^(?:\d+)?(?:>>?|<<?|<>|>&|<&|&>>?).+$/;
|
|
2411
|
+
function tokenizeCommandSegments(command, shell) {
|
|
2412
|
+
const escapeChar = shell === "powershell" ? "`" : "\\";
|
|
2413
|
+
const segments = [];
|
|
2414
|
+
const backtickBodies = [];
|
|
2415
|
+
const stack = [
|
|
2416
|
+
{ words: [], current: "", kind: "root", caseDepth: 0 }
|
|
2417
|
+
];
|
|
2418
|
+
const flushWord = () => {
|
|
2419
|
+
const top = stack[stack.length - 1];
|
|
2420
|
+
if (top.current) {
|
|
2421
|
+
if (top.words.length === 0) {
|
|
2422
|
+
const lower = top.current.toLowerCase();
|
|
2423
|
+
if (lower === "case") top.caseDepth += 1;
|
|
2424
|
+
else if (lower === "esac" && top.caseDepth > 0) top.caseDepth -= 1;
|
|
2425
|
+
}
|
|
2426
|
+
top.words.push(top.current);
|
|
2427
|
+
top.current = "";
|
|
2428
|
+
}
|
|
2422
2429
|
};
|
|
2423
|
-
|
|
2424
|
-
|
|
2425
|
-
|
|
2426
|
-
|
|
2427
|
-
|
|
2428
|
-
|
|
2430
|
+
const flushSegment = () => {
|
|
2431
|
+
flushWord();
|
|
2432
|
+
const top = stack[stack.length - 1];
|
|
2433
|
+
if (top.words.length > 0) {
|
|
2434
|
+
segments.push(top.words);
|
|
2435
|
+
top.words = [];
|
|
2429
2436
|
}
|
|
2437
|
+
};
|
|
2438
|
+
const readBacktickBody = (startIndex) => {
|
|
2439
|
+
let body = "";
|
|
2440
|
+
let i = startIndex + 1;
|
|
2441
|
+
for (; i < command.length; i += 1) {
|
|
2442
|
+
const c = command[i];
|
|
2443
|
+
if (c === "\\" && i + 1 < command.length) {
|
|
2444
|
+
const next = command[i + 1];
|
|
2445
|
+
if (next === "\n") {
|
|
2446
|
+
i += 1;
|
|
2447
|
+
continue;
|
|
2448
|
+
}
|
|
2449
|
+
if (next === "`" || next === "$" || next === "\\") {
|
|
2450
|
+
body += next;
|
|
2451
|
+
i += 1;
|
|
2452
|
+
continue;
|
|
2453
|
+
}
|
|
2454
|
+
body += c + next;
|
|
2455
|
+
i += 1;
|
|
2456
|
+
continue;
|
|
2457
|
+
}
|
|
2458
|
+
if (c === "`") break;
|
|
2459
|
+
body += c;
|
|
2460
|
+
}
|
|
2461
|
+
if (body) backtickBodies.push(body);
|
|
2462
|
+
return i;
|
|
2463
|
+
};
|
|
2464
|
+
for (let i = 0; i < command.length; i += 1) {
|
|
2465
|
+
const top = stack[stack.length - 1];
|
|
2466
|
+
const ch = command[i];
|
|
2467
|
+
if (top.quote === "'") {
|
|
2468
|
+
if (ch === "'") top.quote = void 0;
|
|
2469
|
+
else top.current += ch;
|
|
2470
|
+
continue;
|
|
2471
|
+
}
|
|
2472
|
+
if (top.quote === '"') {
|
|
2473
|
+
if (ch === escapeChar && i + 1 < command.length) {
|
|
2474
|
+
if (shell === "bash" && command[i + 1] === "\n") {
|
|
2475
|
+
i += 1;
|
|
2476
|
+
continue;
|
|
2477
|
+
}
|
|
2478
|
+
top.current += command[i + 1];
|
|
2479
|
+
i += 1;
|
|
2480
|
+
continue;
|
|
2481
|
+
}
|
|
2482
|
+
if (ch === '"') {
|
|
2483
|
+
top.quote = void 0;
|
|
2484
|
+
continue;
|
|
2485
|
+
}
|
|
2486
|
+
if (shell === "bash" && ch === "$" && command[i + 1] === "(") {
|
|
2487
|
+
stack.push({ words: [], current: "", kind: "paren", caseDepth: 0 });
|
|
2488
|
+
i += 1;
|
|
2489
|
+
continue;
|
|
2490
|
+
}
|
|
2491
|
+
if (shell === "bash" && ch === "`") {
|
|
2492
|
+
i = readBacktickBody(i);
|
|
2493
|
+
continue;
|
|
2494
|
+
}
|
|
2495
|
+
top.current += ch;
|
|
2496
|
+
continue;
|
|
2497
|
+
}
|
|
2498
|
+
if (ch === escapeChar && i + 1 < command.length) {
|
|
2499
|
+
if (shell === "bash" && command[i + 1] === "\n") {
|
|
2500
|
+
i += 1;
|
|
2501
|
+
continue;
|
|
2502
|
+
}
|
|
2503
|
+
top.current += command[i + 1];
|
|
2504
|
+
i += 1;
|
|
2505
|
+
continue;
|
|
2506
|
+
}
|
|
2507
|
+
if (ch === "'" || ch === '"') {
|
|
2508
|
+
top.quote = ch;
|
|
2509
|
+
continue;
|
|
2510
|
+
}
|
|
2511
|
+
if (shell === "bash" && ch === "`") {
|
|
2512
|
+
flushWord();
|
|
2513
|
+
i = readBacktickBody(i);
|
|
2514
|
+
continue;
|
|
2515
|
+
}
|
|
2516
|
+
if (shell !== "cmd" && ((ch === "$" || ch === "<" || ch === ">") && command[i + 1] === "(")) {
|
|
2517
|
+
flushWord();
|
|
2518
|
+
stack.push({ words: [], current: "", kind: "paren", caseDepth: 0 });
|
|
2519
|
+
i += 1;
|
|
2520
|
+
continue;
|
|
2521
|
+
}
|
|
2522
|
+
if (shell !== "cmd" && ch === "(") {
|
|
2523
|
+
flushWord();
|
|
2524
|
+
stack.push({ words: [], current: "", kind: "paren", caseDepth: 0 });
|
|
2525
|
+
continue;
|
|
2526
|
+
}
|
|
2527
|
+
if (shell !== "cmd" && ch === ")") {
|
|
2528
|
+
flushSegment();
|
|
2529
|
+
if (top.caseDepth === 0 && top.kind === "paren") {
|
|
2530
|
+
stack.pop();
|
|
2531
|
+
if (stack.length > 0 && stack[stack.length - 1].caseDepth > 0) {
|
|
2532
|
+
flushSegment();
|
|
2533
|
+
}
|
|
2534
|
+
}
|
|
2535
|
+
continue;
|
|
2536
|
+
}
|
|
2537
|
+
if (ch === ";" || ch === "\n" || ch === "|") {
|
|
2538
|
+
if (ch === "|" && command[i + 1] === "|") i += 1;
|
|
2539
|
+
flushSegment();
|
|
2540
|
+
continue;
|
|
2541
|
+
}
|
|
2542
|
+
if (ch === "&") {
|
|
2543
|
+
const prev = top.current[top.current.length - 1];
|
|
2544
|
+
if (prev === ">" || prev === "<" || command[i + 1] === ">") {
|
|
2545
|
+
top.current += ch;
|
|
2546
|
+
continue;
|
|
2547
|
+
}
|
|
2548
|
+
if (command[i + 1] === "&") i += 1;
|
|
2549
|
+
flushSegment();
|
|
2550
|
+
continue;
|
|
2551
|
+
}
|
|
2552
|
+
if (/\s/.test(ch)) {
|
|
2553
|
+
flushWord();
|
|
2554
|
+
continue;
|
|
2555
|
+
}
|
|
2556
|
+
top.current += ch;
|
|
2430
2557
|
}
|
|
2431
|
-
|
|
2432
|
-
|
|
2433
|
-
|
|
2434
|
-
return pool[0];
|
|
2435
|
-
}
|
|
2436
|
-
function extractFallbackFailureDetails(lastAssistant, terminalError) {
|
|
2437
|
-
if (!lastAssistant) return void 0;
|
|
2438
|
-
if (lastAssistant.retryable === void 0 && lastAssistant.replayClass === void 0 && lastAssistant.replayEligible === void 0 && lastAssistant.remoteFailure === void 0) {
|
|
2439
|
-
return void 0;
|
|
2558
|
+
while (stack.length > 0) {
|
|
2559
|
+
flushSegment();
|
|
2560
|
+
stack.pop();
|
|
2440
2561
|
}
|
|
2441
|
-
return {
|
|
2442
|
-
errorMessage: terminalError,
|
|
2443
|
-
retryable: lastAssistant.retryable,
|
|
2444
|
-
replayClass: lastAssistant.replayClass,
|
|
2445
|
-
replayEligible: lastAssistant.replayEligible,
|
|
2446
|
-
remoteFailure: lastAssistant.remoteFailure
|
|
2447
|
-
};
|
|
2562
|
+
return { segments, backtickBodies };
|
|
2448
2563
|
}
|
|
2449
|
-
function
|
|
2450
|
-
|
|
2451
|
-
|
|
2452
|
-
|
|
2453
|
-
);
|
|
2454
|
-
}
|
|
2455
|
-
const detail = options.terminalError ? `: ${options.terminalError.slice(0, 200)}` : "";
|
|
2456
|
-
const overflow = isSubagentOverflowFailure(options.subagentFailure, options.terminalError, options.terminalStopReason);
|
|
2457
|
-
const failure = new Error(
|
|
2458
|
-
overflow ? options.compactedOnce ? `Subagent context overflow persisted after automatic compaction${detail}` : `Subagent context overflow requires compaction, but compaction could not complete${detail}` : `Subagent response failed (provider/transport failure before the report was produced, stopReason=${options.terminalStopReason ?? "none"}${options.collectedResponse ? ", partial transcript discarded" : ", no text response"})${detail}`
|
|
2459
|
-
);
|
|
2460
|
-
const carrier = failure;
|
|
2461
|
-
carrier.retryable = options.subagentFailure?.retryable;
|
|
2462
|
-
carrier.replayClass = options.subagentFailure?.replayClass;
|
|
2463
|
-
carrier.subagentFailure = options.subagentFailure;
|
|
2464
|
-
return failure;
|
|
2564
|
+
function splitEnvSplitString(payload) {
|
|
2565
|
+
const normalized = payload.replace(/\\_/g, " ");
|
|
2566
|
+
const { segments } = tokenizeCommandSegments(normalized, "bash");
|
|
2567
|
+
return segments.flat();
|
|
2465
2568
|
}
|
|
2466
|
-
|
|
2467
|
-
|
|
2468
|
-
|
|
2469
|
-
|
|
2470
|
-
|
|
2471
|
-
|
|
2472
|
-
|
|
2473
|
-
const last = rawMessages[end - 1];
|
|
2474
|
-
if (last?.role === "assistant" && (last.stopReason === "error" || last.stopReason === "aborted")) {
|
|
2475
|
-
end -= 1;
|
|
2569
|
+
function segmentHasFilesystemWrite(words, shell, depth = 0) {
|
|
2570
|
+
let index = 0;
|
|
2571
|
+
while (index < words.length) {
|
|
2572
|
+
const word = words[index];
|
|
2573
|
+
const lower = word.toLowerCase();
|
|
2574
|
+
if (SHELL_CONTROL_PREFIXES.has(lower) || shell === "powershell" && (word === "." || word === "&")) {
|
|
2575
|
+
index += 1;
|
|
2476
2576
|
continue;
|
|
2477
2577
|
}
|
|
2478
|
-
|
|
2479
|
-
|
|
2480
|
-
|
|
2481
|
-
const hasPriorTurns = cleaned.some((m) => m.role === "assistant" || m.role === "toolResult");
|
|
2482
|
-
if (cleaned.length === 0 || !hasPriorTurns) {
|
|
2483
|
-
return { compacted: false, newBaseline: 0 };
|
|
2484
|
-
}
|
|
2485
|
-
const controller = new AbortController();
|
|
2486
|
-
const onParentAbort = () => controller.abort();
|
|
2487
|
-
if (options.signal?.aborted) return { compacted: false, newBaseline: 0 };
|
|
2488
|
-
options.signal?.addEventListener("abort", onParentAbort, { once: true });
|
|
2489
|
-
const remainingMs = options.hardDeadlineAt !== void 0 ? Math.max(0, options.hardDeadlineAt - Date.now()) : void 0;
|
|
2490
|
-
if (remainingMs !== void 0 && remainingMs <= 0) {
|
|
2491
|
-
options.signal?.removeEventListener("abort", onParentAbort);
|
|
2492
|
-
return { compacted: false, newBaseline: 0 };
|
|
2493
|
-
}
|
|
2494
|
-
const timer = remainingMs !== void 0 ? setTimeout(() => controller.abort(), Math.min(remainingMs, 6e4)) : void 0;
|
|
2495
|
-
try {
|
|
2496
|
-
let summary;
|
|
2497
|
-
try {
|
|
2498
|
-
summary = options.compactSummaryFn ? await options.compactSummaryFn(cleaned, options.model, options.apiKey, controller.signal) : await createCompactionSummary(cleaned, {
|
|
2499
|
-
model: options.model,
|
|
2500
|
-
apiKey: options.apiKey,
|
|
2501
|
-
signal: controller.signal
|
|
2502
|
-
});
|
|
2503
|
-
} catch (summaryError) {
|
|
2504
|
-
if (controller.signal.aborted || options.signal?.aborted) return { compacted: false, newBaseline: 0 };
|
|
2505
|
-
const summaryMsg = summaryError instanceof Error ? summaryError.message : String(summaryError);
|
|
2506
|
-
if (!isDefaultContextOverflowError(summaryMsg)) return { compacted: false, newBaseline: 0 };
|
|
2507
|
-
summary = await createCompactionSummary(cleaned, { signal: controller.signal });
|
|
2578
|
+
if (STANDALONE_REDIR_RE.test(word)) {
|
|
2579
|
+
index += 2;
|
|
2580
|
+
continue;
|
|
2508
2581
|
}
|
|
2509
|
-
if (
|
|
2510
|
-
|
|
2582
|
+
if (INLINE_REDIR_RE.test(word) || /^[A-Za-z_][A-Za-z0-9_]*=/.test(word)) {
|
|
2583
|
+
index += 1;
|
|
2584
|
+
continue;
|
|
2511
2585
|
}
|
|
2512
|
-
const
|
|
2513
|
-
|
|
2514
|
-
|
|
2515
|
-
|
|
2516
|
-
|
|
2517
|
-
|
|
2518
|
-
if (
|
|
2519
|
-
|
|
2586
|
+
const program = executableName(word);
|
|
2587
|
+
if (FILESYSTEM_WRITE_COMMANDS.has(program)) return true;
|
|
2588
|
+
if (program === "eval") {
|
|
2589
|
+
if (depth >= 2) return true;
|
|
2590
|
+
return hasFilesystemWriteCommand(words.slice(index + 1).join(" "), shell, depth + 1);
|
|
2591
|
+
}
|
|
2592
|
+
if (WRITE_WRAPPER_NAMES.has(program)) {
|
|
2593
|
+
const valueFlags = WRITE_WRAPPER_VALUE_FLAGS[program];
|
|
2594
|
+
index += 1;
|
|
2595
|
+
while (index < words.length) {
|
|
2596
|
+
const arg = words[index];
|
|
2597
|
+
if (arg === "--") {
|
|
2598
|
+
index += 1;
|
|
2599
|
+
break;
|
|
2600
|
+
}
|
|
2601
|
+
if (program === "env") {
|
|
2602
|
+
if (arg === "-S" || arg === "--split-string" || arg.startsWith("-S") || arg.startsWith("--split-string=")) {
|
|
2603
|
+
const separate = arg === "-S" || arg === "--split-string";
|
|
2604
|
+
const splitPayload = separate ? words[index + 1] : arg.startsWith("-S") ? arg.slice(2) : arg.slice("--split-string=".length);
|
|
2605
|
+
if (!splitPayload || depth >= 2) return true;
|
|
2606
|
+
const nextIndex = separate ? index + 2 : index + 1;
|
|
2607
|
+
const expanded = [...splitEnvSplitString(splitPayload), ...words.slice(nextIndex)];
|
|
2608
|
+
return segmentHasFilesystemWrite(expanded, shell, depth + 1) || hasFilesystemWriteCommand(splitPayload.replace(/\\_/g, " "), shell, depth + 1);
|
|
2609
|
+
}
|
|
2610
|
+
if (/^[A-Za-z_][A-Za-z0-9_]*=/.test(arg)) {
|
|
2611
|
+
index += 1;
|
|
2612
|
+
continue;
|
|
2613
|
+
}
|
|
2614
|
+
}
|
|
2615
|
+
if (valueFlags?.has(arg)) {
|
|
2616
|
+
index += 2;
|
|
2617
|
+
continue;
|
|
2618
|
+
}
|
|
2619
|
+
if (arg.startsWith("-")) {
|
|
2620
|
+
index += 1;
|
|
2621
|
+
continue;
|
|
2622
|
+
}
|
|
2623
|
+
break;
|
|
2624
|
+
}
|
|
2625
|
+
if (program === "timeout") index += 1;
|
|
2626
|
+
continue;
|
|
2627
|
+
}
|
|
2628
|
+
return false;
|
|
2520
2629
|
}
|
|
2630
|
+
return false;
|
|
2631
|
+
}
|
|
2632
|
+
function hasFilesystemWriteCommand(command, shell, depth = 0) {
|
|
2633
|
+
const { segments, backtickBodies } = tokenizeCommandSegments(command, shell);
|
|
2634
|
+
for (const words of segments) {
|
|
2635
|
+
if (segmentHasFilesystemWrite(words, shell, depth)) return true;
|
|
2636
|
+
}
|
|
2637
|
+
for (const body of backtickBodies) {
|
|
2638
|
+
if (depth >= 4) return true;
|
|
2639
|
+
if (hasFilesystemWriteCommand(body, shell, depth + 1)) return true;
|
|
2640
|
+
}
|
|
2641
|
+
return false;
|
|
2521
2642
|
}
|
|
2522
2643
|
|
|
2523
2644
|
// ../../packages/shared-headless-capabilities/src/bash-policy.ts
|
|
@@ -2800,11 +2921,172 @@ function resolveStaticCwdTarget(target, cwd, root) {
|
|
|
2800
2921
|
if (resolved !== normalizedRoot && !isStrictDescendant(resolved, normalizedRoot)) return void 0;
|
|
2801
2922
|
return resolved;
|
|
2802
2923
|
}
|
|
2803
|
-
var DYNAMIC_EXECUTION_WARNING = "may execute nested shell or interpreter code";
|
|
2804
|
-
function
|
|
2805
|
-
|
|
2806
|
-
|
|
2807
|
-
|
|
2924
|
+
var DYNAMIC_EXECUTION_WARNING = "may execute nested shell or interpreter code";
|
|
2925
|
+
function stripBashComments(command) {
|
|
2926
|
+
let hasUnquotedHeredoc = false;
|
|
2927
|
+
{
|
|
2928
|
+
let q;
|
|
2929
|
+
for (let i = 0; i < command.length; i += 1) {
|
|
2930
|
+
const c = command[i];
|
|
2931
|
+
if (q) {
|
|
2932
|
+
if (q === '"' && c === "\\" && i + 1 < command.length) {
|
|
2933
|
+
i += 1;
|
|
2934
|
+
continue;
|
|
2935
|
+
}
|
|
2936
|
+
if (c === q) q = void 0;
|
|
2937
|
+
continue;
|
|
2938
|
+
}
|
|
2939
|
+
if (c === "'" || c === '"') {
|
|
2940
|
+
q = c;
|
|
2941
|
+
continue;
|
|
2942
|
+
}
|
|
2943
|
+
if (c === "\\" && i + 1 < command.length) {
|
|
2944
|
+
i += 1;
|
|
2945
|
+
continue;
|
|
2946
|
+
}
|
|
2947
|
+
if (c === "<" && command[i + 1] === "<") {
|
|
2948
|
+
if (command[i + 2] === "<") {
|
|
2949
|
+
i += 2;
|
|
2950
|
+
continue;
|
|
2951
|
+
}
|
|
2952
|
+
hasUnquotedHeredoc = true;
|
|
2953
|
+
break;
|
|
2954
|
+
}
|
|
2955
|
+
}
|
|
2956
|
+
}
|
|
2957
|
+
if (hasUnquotedHeredoc) return command;
|
|
2958
|
+
let result = "";
|
|
2959
|
+
let quote;
|
|
2960
|
+
let inWord = false;
|
|
2961
|
+
let inBacktick = false;
|
|
2962
|
+
let paramExpansionDepth = 0;
|
|
2963
|
+
let cmdSubDepth = 0;
|
|
2964
|
+
for (let index = 0; index < command.length; index += 1) {
|
|
2965
|
+
const char = command[index];
|
|
2966
|
+
if (quote) {
|
|
2967
|
+
result += char;
|
|
2968
|
+
if (quote === '"' && char === "\\" && index + 1 < command.length) {
|
|
2969
|
+
result += command[index + 1];
|
|
2970
|
+
index += 1;
|
|
2971
|
+
continue;
|
|
2972
|
+
}
|
|
2973
|
+
if (char === quote) quote = void 0;
|
|
2974
|
+
continue;
|
|
2975
|
+
}
|
|
2976
|
+
if (char === "'" || char === '"') {
|
|
2977
|
+
quote = char;
|
|
2978
|
+
inWord = true;
|
|
2979
|
+
result += char;
|
|
2980
|
+
continue;
|
|
2981
|
+
}
|
|
2982
|
+
if (char === "\\" && index + 1 < command.length) {
|
|
2983
|
+
const next = command[index + 1];
|
|
2984
|
+
if (next !== "\n") inWord = true;
|
|
2985
|
+
result += char;
|
|
2986
|
+
result += next;
|
|
2987
|
+
index += 1;
|
|
2988
|
+
continue;
|
|
2989
|
+
}
|
|
2990
|
+
if (char === "`") {
|
|
2991
|
+
inBacktick = !inBacktick;
|
|
2992
|
+
inWord = true;
|
|
2993
|
+
result += char;
|
|
2994
|
+
continue;
|
|
2995
|
+
}
|
|
2996
|
+
if (char === "$" && command[index + 1] === "{") {
|
|
2997
|
+
paramExpansionDepth += 1;
|
|
2998
|
+
inWord = true;
|
|
2999
|
+
result += "${";
|
|
3000
|
+
index += 1;
|
|
3001
|
+
continue;
|
|
3002
|
+
}
|
|
3003
|
+
if (char === "$" && command[index + 1] === "(") {
|
|
3004
|
+
cmdSubDepth += 1;
|
|
3005
|
+
inWord = true;
|
|
3006
|
+
result += "$(";
|
|
3007
|
+
index += 1;
|
|
3008
|
+
continue;
|
|
3009
|
+
}
|
|
3010
|
+
if (char === "{" && paramExpansionDepth > 0) {
|
|
3011
|
+
paramExpansionDepth += 1;
|
|
3012
|
+
inWord = true;
|
|
3013
|
+
result += char;
|
|
3014
|
+
continue;
|
|
3015
|
+
}
|
|
3016
|
+
if (char === "(" && cmdSubDepth > 0) {
|
|
3017
|
+
cmdSubDepth += 1;
|
|
3018
|
+
inWord = true;
|
|
3019
|
+
result += char;
|
|
3020
|
+
continue;
|
|
3021
|
+
}
|
|
3022
|
+
if (char === "}" && paramExpansionDepth > 0) {
|
|
3023
|
+
paramExpansionDepth -= 1;
|
|
3024
|
+
inWord = true;
|
|
3025
|
+
result += char;
|
|
3026
|
+
continue;
|
|
3027
|
+
}
|
|
3028
|
+
if (char === ")" && cmdSubDepth > 0) {
|
|
3029
|
+
cmdSubDepth -= 1;
|
|
3030
|
+
inWord = true;
|
|
3031
|
+
result += char;
|
|
3032
|
+
continue;
|
|
3033
|
+
}
|
|
3034
|
+
if (char === "#" && !inWord && !inBacktick && paramExpansionDepth === 0 && cmdSubDepth === 0) {
|
|
3035
|
+
while (index < command.length && command[index] !== "\n") {
|
|
3036
|
+
index += 1;
|
|
3037
|
+
}
|
|
3038
|
+
if (index < command.length && command[index] === "\n") {
|
|
3039
|
+
result += "\n";
|
|
3040
|
+
inWord = false;
|
|
3041
|
+
}
|
|
3042
|
+
continue;
|
|
3043
|
+
}
|
|
3044
|
+
if (/[\s;&|()]/.test(char)) {
|
|
3045
|
+
inWord = false;
|
|
3046
|
+
} else {
|
|
3047
|
+
inWord = true;
|
|
3048
|
+
}
|
|
3049
|
+
result += char;
|
|
3050
|
+
}
|
|
3051
|
+
if (quote || inBacktick || paramExpansionDepth > 0 || cmdSubDepth > 0) {
|
|
3052
|
+
return command;
|
|
3053
|
+
}
|
|
3054
|
+
return result;
|
|
3055
|
+
}
|
|
3056
|
+
var SAFE_PYTHON_TEST_MODULES = /* @__PURE__ */ new Set(["pytest", "unittest"]);
|
|
3057
|
+
var PYTHON_VALUE_OPTIONS = /* @__PURE__ */ new Set(["-W", "-X", "--check-hash-based-pycs"]);
|
|
3058
|
+
var PYTHON_SAFE_BOOL_FLAGS_RE = /^-[BEIOPqSsuv]+$/;
|
|
3059
|
+
function isPythonExecutable(program) {
|
|
3060
|
+
return /^python(?:\d+(?:\.\d+)?)?$/.test(program);
|
|
3061
|
+
}
|
|
3062
|
+
function hasDynamicPythonInvocation(args) {
|
|
3063
|
+
for (let index = 0; index < args.length; index += 1) {
|
|
3064
|
+
const word = args[index];
|
|
3065
|
+
if (word === "--") return false;
|
|
3066
|
+
if (/^-[ce]/i.test(word)) return true;
|
|
3067
|
+
if (/^-m$/i.test(word)) {
|
|
3068
|
+
const mod = args[index + 1]?.toLowerCase();
|
|
3069
|
+
return !(mod && SAFE_PYTHON_TEST_MODULES.has(mod));
|
|
3070
|
+
}
|
|
3071
|
+
if (/^-m.+$/i.test(word)) {
|
|
3072
|
+
const mod = word.slice(2).toLowerCase();
|
|
3073
|
+
return !SAFE_PYTHON_TEST_MODULES.has(mod);
|
|
3074
|
+
}
|
|
3075
|
+
if (PYTHON_VALUE_OPTIONS.has(word)) {
|
|
3076
|
+
if (index + 1 >= args.length) return true;
|
|
3077
|
+
index += 1;
|
|
3078
|
+
continue;
|
|
3079
|
+
}
|
|
3080
|
+
if (/^(?:-W|-X|--check-hash-based-pycs=)/i.test(word)) {
|
|
3081
|
+
continue;
|
|
3082
|
+
}
|
|
3083
|
+
if (PYTHON_SAFE_BOOL_FLAGS_RE.test(word)) {
|
|
3084
|
+
continue;
|
|
3085
|
+
}
|
|
3086
|
+
if (word.startsWith("-")) return true;
|
|
3087
|
+
return false;
|
|
3088
|
+
}
|
|
3089
|
+
return false;
|
|
2808
3090
|
}
|
|
2809
3091
|
function hasDynamicExecutionInvocation(words) {
|
|
2810
3092
|
if (words.length === 0) return false;
|
|
@@ -2823,7 +3105,10 @@ function hasDynamicExecutionInvocation(words) {
|
|
|
2823
3105
|
if (program === "cmd") {
|
|
2824
3106
|
return words.slice(1).some((word) => /^\/(?:c|k)$/i.test(word));
|
|
2825
3107
|
}
|
|
2826
|
-
if (
|
|
3108
|
+
if (isPythonExecutable(program)) {
|
|
3109
|
+
return hasDynamicPythonInvocation(words.slice(1));
|
|
3110
|
+
}
|
|
3111
|
+
if (["perl", "ruby"].includes(program)) {
|
|
2827
3112
|
return words.slice(1).some((word) => /^(?:-c|-e|-m)$/i.test(word));
|
|
2828
3113
|
}
|
|
2829
3114
|
if (program === "node") {
|
|
@@ -2887,13 +3172,14 @@ function isStaticallyScopedRecursiveForceRemove(command, options) {
|
|
|
2887
3172
|
return sawRm;
|
|
2888
3173
|
}
|
|
2889
3174
|
function classifyShellCommand(command, shell = "bash", options) {
|
|
3175
|
+
const inspectedCommand = shell === "bash" ? stripBashComments(command) : command;
|
|
2890
3176
|
const warnings = [];
|
|
2891
3177
|
let commandClass = "unknown_shell";
|
|
2892
3178
|
let destructive = false;
|
|
2893
3179
|
const destructivePatterns = shell === "cmd" ? [...CMD_DESTRUCTIVE_PATTERNS, ...DESTRUCTIVE_PATTERNS] : DESTRUCTIVE_PATTERNS;
|
|
2894
|
-
const removeWarnings = recursiveRemoveWarnings(
|
|
3180
|
+
const removeWarnings = recursiveRemoveWarnings(inspectedCommand);
|
|
2895
3181
|
if (removeWarnings.length > 0) {
|
|
2896
|
-
if (shell === "bash" && isStaticallyScopedRecursiveForceRemove(
|
|
3182
|
+
if (shell === "bash" && isStaticallyScopedRecursiveForceRemove(inspectedCommand, options)) {
|
|
2897
3183
|
commandClass = "filesystem_write";
|
|
2898
3184
|
} else {
|
|
2899
3185
|
warnings.push(...removeWarnings);
|
|
@@ -2901,7 +3187,7 @@ function classifyShellCommand(command, shell = "bash", options) {
|
|
|
2901
3187
|
destructive = true;
|
|
2902
3188
|
}
|
|
2903
3189
|
}
|
|
2904
|
-
const dynamicWarnings = dynamicExecutionWarnings(
|
|
3190
|
+
const dynamicWarnings = dynamicExecutionWarnings(inspectedCommand);
|
|
2905
3191
|
if (dynamicWarnings.length > 0) {
|
|
2906
3192
|
warnings.push(...dynamicWarnings);
|
|
2907
3193
|
commandClass = "unknown_shell";
|
|
@@ -2939,7 +3225,7 @@ function classifyShellCommand(command, shell = "bash", options) {
|
|
|
2939
3225
|
}
|
|
2940
3226
|
}
|
|
2941
3227
|
for (const entry of destructivePatterns) {
|
|
2942
|
-
if (entry.pattern.test(
|
|
3228
|
+
if (entry.pattern.test(inspectedCommand)) {
|
|
2943
3229
|
warnings.push(entry.warning);
|
|
2944
3230
|
commandClass = entry.commandClass;
|
|
2945
3231
|
destructive = true;
|
|
@@ -2948,7 +3234,7 @@ function classifyShellCommand(command, shell = "bash", options) {
|
|
|
2948
3234
|
if (destructive) {
|
|
2949
3235
|
return { commandClass, riskWarnings: [...new Set(warnings)], destructive, requiresPermission: true };
|
|
2950
3236
|
}
|
|
2951
|
-
const normalized =
|
|
3237
|
+
const normalized = inspectedCommand.trim().toLowerCase();
|
|
2952
3238
|
const words = splitCommand(normalized).map(firstWord);
|
|
2953
3239
|
const primary = words[0] || firstWord(normalized);
|
|
2954
3240
|
if (shell === "powershell" && /\b(invoke-webrequest|iwr|invoke-restmethod|irm)\b/.test(normalized)) {
|
|
@@ -2959,12 +3245,12 @@ function classifyShellCommand(command, shell = "bash", options) {
|
|
|
2959
3245
|
commandClass = "filesystem_write";
|
|
2960
3246
|
} else if (/\b(npm|pnpm|yarn|bun)\s+(install|add|remove|update|ci)\b/.test(normalized)) {
|
|
2961
3247
|
commandClass = "package_manager";
|
|
2962
|
-
} else if (/\b(
|
|
2963
|
-
commandClass = "test_or_build";
|
|
2964
|
-
} else if (/\b(curl|wget|http|npx|pip|gem|brew)\b/.test(normalized)) {
|
|
3248
|
+
} else if (/\b(curl|wget|http|npx|pip3?|gem|brew)\b/.test(normalized)) {
|
|
2965
3249
|
commandClass = "network";
|
|
2966
|
-
} else if (
|
|
3250
|
+
} else if (commandClass === "filesystem_write" || LEGACY_FILESYSTEM_WRITE_RE.test(normalized) || hasFilesystemWriteCommand(inspectedCommand, shell)) {
|
|
2967
3251
|
commandClass = "filesystem_write";
|
|
3252
|
+
} else if (/\b(npm|pnpm|yarn|bun|cargo|go|mvn|gradle|pytest|python -m pytest)\s+(run\s+)?(test|build|check|lint|typecheck|verify)\b/.test(normalized) || /(?:^|[;&|\n])\s*(?:[^\s;|&]*\/)?python(?:\d+(?:\.\d+)?)?\s+-m\s*(?:pytest|unittest)\b/.test(normalized) || /(?:^|[;&|\n])\s*(?:[^\s;|&]*\/)?pytest\b/.test(normalized)) {
|
|
3253
|
+
commandClass = "test_or_build";
|
|
2968
3254
|
} else if (["ls", "pwd", "cat", "head", "tail", "grep", "rg", "find", "wc", "git", "diff", "test", "["].includes(primary)) {
|
|
2969
3255
|
commandClass = "diagnostic_read";
|
|
2970
3256
|
}
|
|
@@ -3000,7 +3286,7 @@ function interpretShellExit(command, exitCode) {
|
|
|
3000
3286
|
return { isError: exitCode !== 0, semanticExitMeaning: exitCode === 0 ? "command succeeded" : `command failed with exit code ${exitCode}` };
|
|
3001
3287
|
}
|
|
3002
3288
|
|
|
3003
|
-
// ../../packages/shared-headless-capabilities/src/subagent.ts
|
|
3289
|
+
// ../../packages/shared-headless-capabilities/src/subagent-core.ts
|
|
3004
3290
|
var DEFAULT_SUBAGENT_TIMEOUT_SECONDS = 1200;
|
|
3005
3291
|
var DEFAULT_SUBAGENT_THINKING_LEVEL = "medium";
|
|
3006
3292
|
var SUBAGENT_THINKING_LEVELS = ALL_THINKING_LEVELS;
|
|
@@ -3393,6 +3679,140 @@ async function persistSubagentSession(deps, session, task) {
|
|
|
3393
3679
|
debugLog(deps, "session", "session persist failed", { id: session.id, error: error instanceof Error ? error.message : String(error) });
|
|
3394
3680
|
}
|
|
3395
3681
|
}
|
|
3682
|
+
|
|
3683
|
+
// ../../packages/shared-headless-capabilities/src/subagent-recovery.ts
|
|
3684
|
+
var MAX_SUBAGENT_MODEL_FALLBACKS = 2;
|
|
3685
|
+
function modelCandidateKey(model) {
|
|
3686
|
+
return `${model.provider}/${model.id}`;
|
|
3687
|
+
}
|
|
3688
|
+
function isSubagentOverflowFailure(failure, errorMessage, stopReason) {
|
|
3689
|
+
if (stopReason === "aborted" || stopReason === "length") return false;
|
|
3690
|
+
if (failure?.recovery?.outcome === "overflow") return true;
|
|
3691
|
+
if (failure?.classification?.kind === "context_overflow") return true;
|
|
3692
|
+
if (failure?.remoteFailure?.category === "context_overflow") return true;
|
|
3693
|
+
return Boolean(errorMessage && isDefaultContextOverflowError(errorMessage));
|
|
3694
|
+
}
|
|
3695
|
+
function isSubagentModelFallbackTrigger(errorMessage, failure, stopReason) {
|
|
3696
|
+
if (stopReason === "aborted" || stopReason === "length") return false;
|
|
3697
|
+
const kind = failure?.classification?.kind;
|
|
3698
|
+
if (kind === "user_abort" || kind === "invalid_request" || kind === "context_overflow") return false;
|
|
3699
|
+
if (errorMessage && isDefaultQuotaExhaustedError(errorMessage)) return true;
|
|
3700
|
+
if (kind === "auth_config") return true;
|
|
3701
|
+
if (failure?.recovery?.outcome === "exhausted" && (kind === "provider_transient" || kind === "provider_confirmation" || kind === "transient_network")) {
|
|
3702
|
+
return true;
|
|
3703
|
+
}
|
|
3704
|
+
return false;
|
|
3705
|
+
}
|
|
3706
|
+
function pickNextSubagentFallbackCandidate(options) {
|
|
3707
|
+
const pool = [];
|
|
3708
|
+
const pushCandidate = (candidate) => {
|
|
3709
|
+
if (!candidate?.model || !candidate.apiKey) return;
|
|
3710
|
+
const key = modelCandidateKey(candidate.model);
|
|
3711
|
+
if (options.triedKeys.has(key)) return;
|
|
3712
|
+
if (pool.some((existing) => modelCandidateKey(existing.model) === key)) return;
|
|
3713
|
+
pool.push(candidate);
|
|
3714
|
+
};
|
|
3715
|
+
for (const candidate of options.resolveModelClassCandidates?.(options.modelClass) ?? []) {
|
|
3716
|
+
pushCandidate(candidate);
|
|
3717
|
+
}
|
|
3718
|
+
if (options.modelClass === "light") {
|
|
3719
|
+
for (const candidate of options.resolveModelClassCandidates?.("balanced") ?? []) {
|
|
3720
|
+
pushCandidate(candidate);
|
|
3721
|
+
}
|
|
3722
|
+
}
|
|
3723
|
+
if (options.parentModel && options.parentApiKey) {
|
|
3724
|
+
pushCandidate({ model: options.parentModel, apiKey: options.parentApiKey });
|
|
3725
|
+
}
|
|
3726
|
+
return pool[0];
|
|
3727
|
+
}
|
|
3728
|
+
function extractFallbackFailureDetails(lastAssistant, terminalError) {
|
|
3729
|
+
if (!lastAssistant) return void 0;
|
|
3730
|
+
if (lastAssistant.retryable === void 0 && lastAssistant.replayClass === void 0 && lastAssistant.replayEligible === void 0 && lastAssistant.remoteFailure === void 0) {
|
|
3731
|
+
return void 0;
|
|
3732
|
+
}
|
|
3733
|
+
return {
|
|
3734
|
+
errorMessage: terminalError,
|
|
3735
|
+
retryable: lastAssistant.retryable,
|
|
3736
|
+
replayClass: lastAssistant.replayClass,
|
|
3737
|
+
replayEligible: lastAssistant.replayEligible,
|
|
3738
|
+
remoteFailure: lastAssistant.remoteFailure
|
|
3739
|
+
};
|
|
3740
|
+
}
|
|
3741
|
+
function buildStreamInterruptedError(options) {
|
|
3742
|
+
if (options.terminalStopReason === "length") {
|
|
3743
|
+
return new Error(
|
|
3744
|
+
`Subagent output token limit reached (stopReason=length): the provider cut the final response before the report was produced${options.messages.some(options.messageHasOwnText) ? " (earlier-turn narration discarded)" : ", no text response"}. The output/thinking budget was too small for this task at its reasoning level. Rerun with a narrower task or a lower thinkingLevel.`
|
|
3745
|
+
);
|
|
3746
|
+
}
|
|
3747
|
+
const detail = options.terminalError ? `: ${options.terminalError.slice(0, 200)}` : "";
|
|
3748
|
+
const overflow = isSubagentOverflowFailure(options.subagentFailure, options.terminalError, options.terminalStopReason);
|
|
3749
|
+
const failure = new Error(
|
|
3750
|
+
overflow ? options.compactedOnce ? `Subagent context overflow persisted after automatic compaction${detail}` : `Subagent context overflow requires compaction, but compaction could not complete${detail}` : `Subagent response failed (provider/transport failure before the report was produced, stopReason=${options.terminalStopReason ?? "none"}${options.collectedResponse ? ", partial transcript discarded" : ", no text response"})${detail}`
|
|
3751
|
+
);
|
|
3752
|
+
const carrier = failure;
|
|
3753
|
+
carrier.retryable = options.subagentFailure?.retryable;
|
|
3754
|
+
carrier.replayClass = options.subagentFailure?.replayClass;
|
|
3755
|
+
carrier.subagentFailure = options.subagentFailure;
|
|
3756
|
+
return failure;
|
|
3757
|
+
}
|
|
3758
|
+
async function tryCompactSubagentOverflow(options) {
|
|
3759
|
+
const rawMessages = options.agent.state.messages;
|
|
3760
|
+
if (!Array.isArray(rawMessages) || rawMessages.length === 0) {
|
|
3761
|
+
return { compacted: false, newBaseline: 0 };
|
|
3762
|
+
}
|
|
3763
|
+
let end = rawMessages.length;
|
|
3764
|
+
while (end > 0) {
|
|
3765
|
+
const last = rawMessages[end - 1];
|
|
3766
|
+
if (last?.role === "assistant" && (last.stopReason === "error" || last.stopReason === "aborted")) {
|
|
3767
|
+
end -= 1;
|
|
3768
|
+
continue;
|
|
3769
|
+
}
|
|
3770
|
+
break;
|
|
3771
|
+
}
|
|
3772
|
+
const cleaned = rawMessages.slice(0, end);
|
|
3773
|
+
const hasPriorTurns = cleaned.some((m) => m.role === "assistant" || m.role === "toolResult");
|
|
3774
|
+
if (cleaned.length === 0 || !hasPriorTurns) {
|
|
3775
|
+
return { compacted: false, newBaseline: 0 };
|
|
3776
|
+
}
|
|
3777
|
+
const controller = new AbortController();
|
|
3778
|
+
const onParentAbort = () => controller.abort();
|
|
3779
|
+
if (options.signal?.aborted) return { compacted: false, newBaseline: 0 };
|
|
3780
|
+
options.signal?.addEventListener("abort", onParentAbort, { once: true });
|
|
3781
|
+
const remainingMs = options.hardDeadlineAt !== void 0 ? Math.max(0, options.hardDeadlineAt - Date.now()) : void 0;
|
|
3782
|
+
if (remainingMs !== void 0 && remainingMs <= 0) {
|
|
3783
|
+
options.signal?.removeEventListener("abort", onParentAbort);
|
|
3784
|
+
return { compacted: false, newBaseline: 0 };
|
|
3785
|
+
}
|
|
3786
|
+
const timer = remainingMs !== void 0 ? setTimeout(() => controller.abort(), Math.min(remainingMs, 6e4)) : void 0;
|
|
3787
|
+
try {
|
|
3788
|
+
let summary;
|
|
3789
|
+
try {
|
|
3790
|
+
summary = options.compactSummaryFn ? await options.compactSummaryFn(cleaned, options.model, options.apiKey, controller.signal) : await createCompactionSummary(cleaned, {
|
|
3791
|
+
model: options.model,
|
|
3792
|
+
apiKey: options.apiKey,
|
|
3793
|
+
signal: controller.signal
|
|
3794
|
+
});
|
|
3795
|
+
} catch (summaryError) {
|
|
3796
|
+
if (controller.signal.aborted || options.signal?.aborted) return { compacted: false, newBaseline: 0 };
|
|
3797
|
+
const summaryMsg = summaryError instanceof Error ? summaryError.message : String(summaryError);
|
|
3798
|
+
if (!isDefaultContextOverflowError(summaryMsg)) return { compacted: false, newBaseline: 0 };
|
|
3799
|
+
summary = await createCompactionSummary(cleaned, { signal: controller.signal });
|
|
3800
|
+
}
|
|
3801
|
+
if (!summary.trim() || controller.signal.aborted || options.signal?.aborted) {
|
|
3802
|
+
return { compacted: false, newBaseline: 0 };
|
|
3803
|
+
}
|
|
3804
|
+
const compacted = buildCompactedHistory(collectRealUserMessages(cleaned), summary);
|
|
3805
|
+
transplantMessages(options.agent, compacted);
|
|
3806
|
+
return { compacted: true, newBaseline: compacted.length };
|
|
3807
|
+
} catch {
|
|
3808
|
+
return { compacted: false, newBaseline: 0 };
|
|
3809
|
+
} finally {
|
|
3810
|
+
if (timer) clearTimeout(timer);
|
|
3811
|
+
options.signal?.removeEventListener("abort", onParentAbort);
|
|
3812
|
+
}
|
|
3813
|
+
}
|
|
3814
|
+
|
|
3815
|
+
// ../../packages/shared-headless-capabilities/src/subagent.ts
|
|
3396
3816
|
async function runSubagentWithProgress(deps, task, reportProgress, signal, sessions) {
|
|
3397
3817
|
const startTime = Date.now();
|
|
3398
3818
|
task.status = "running";
|
|
@@ -3708,7 +4128,7 @@ ${DELEGATION_REPORT_INSTRUCTION}`;
|
|
|
3708
4128
|
unsubscribe?.();
|
|
3709
4129
|
if (!agentSettled && settledRun) {
|
|
3710
4130
|
const graceMs = deps.sessionSettleGraceMs ?? 2e3;
|
|
3711
|
-
if (graceMs > 0) await Promise.race([settledRun, new Promise((
|
|
4131
|
+
if (graceMs > 0) await Promise.race([settledRun, new Promise((resolve7) => setTimeout(resolve7, graceMs))]);
|
|
3712
4132
|
}
|
|
3713
4133
|
}
|
|
3714
4134
|
if (hardDeadlineAt !== void 0 && Date.now() >= hardDeadlineAt) {
|
|
@@ -5207,11 +5627,11 @@ function formatCapabilityPolicySummary(tools, context = {}) {
|
|
|
5207
5627
|
import * as nodePath from "node:path";
|
|
5208
5628
|
|
|
5209
5629
|
// ../../packages/shared-headless-capabilities/src/builtin/fs/path-utils.ts
|
|
5210
|
-
function isInAllowlist(
|
|
5630
|
+
function isInAllowlist(path12, allowlistedDirs) {
|
|
5211
5631
|
if (allowlistedDirs.some((dir) => isGlobalFilesystemSentinel(dir))) {
|
|
5212
5632
|
return true;
|
|
5213
5633
|
}
|
|
5214
|
-
const normalized = normalizeForComparison(
|
|
5634
|
+
const normalized = normalizeForComparison(path12);
|
|
5215
5635
|
for (const dir of allowlistedDirs) {
|
|
5216
5636
|
const normalizedDir = normalizeForComparison(dir);
|
|
5217
5637
|
const dirWithSlash = withTrailingSep(normalizedDir);
|
|
@@ -5221,19 +5641,19 @@ function isInAllowlist(path11, allowlistedDirs) {
|
|
|
5221
5641
|
}
|
|
5222
5642
|
return false;
|
|
5223
5643
|
}
|
|
5224
|
-
function normalizeForComparison(
|
|
5225
|
-
const slashNormalized =
|
|
5644
|
+
function normalizeForComparison(path12) {
|
|
5645
|
+
const slashNormalized = path12.replace(/\\/g, "/");
|
|
5226
5646
|
const isWindowsPath = /^[a-zA-Z]:($|\/)/.test(slashNormalized) || /^\/{2}[^/]+\/[^/]+/.test(slashNormalized);
|
|
5227
5647
|
const normalized = slashNormalized.replace(/\/+/g, "/");
|
|
5228
5648
|
if (normalized === "/") return normalized;
|
|
5229
5649
|
const trimmed = normalized.replace(/\/+$/, "");
|
|
5230
5650
|
return isWindowsPath ? trimmed.toLowerCase() : trimmed;
|
|
5231
5651
|
}
|
|
5232
|
-
function isGlobalFilesystemSentinel(
|
|
5233
|
-
return normalizeForComparison(String(
|
|
5652
|
+
function isGlobalFilesystemSentinel(path12) {
|
|
5653
|
+
return normalizeForComparison(String(path12 || "").trim()) === "/";
|
|
5234
5654
|
}
|
|
5235
|
-
function isAbsoluteUserPath(
|
|
5236
|
-
const normalized =
|
|
5655
|
+
function isAbsoluteUserPath(path12) {
|
|
5656
|
+
const normalized = path12.replace(/\\/g, "/");
|
|
5237
5657
|
return /^[a-zA-Z]:\//.test(normalized) || /^\/{2}[^/]+\/[^/]+/.test(normalized);
|
|
5238
5658
|
}
|
|
5239
5659
|
function validateToolPathArgument(filePath) {
|
|
@@ -5248,65 +5668,65 @@ function validateToolPathArgument(filePath) {
|
|
|
5248
5668
|
throw new Error(`Invalid path "${filePath}". The path argument must be a single file path, not multi-line text.`);
|
|
5249
5669
|
}
|
|
5250
5670
|
}
|
|
5251
|
-
function withTrailingSep(
|
|
5252
|
-
return
|
|
5671
|
+
function withTrailingSep(path12) {
|
|
5672
|
+
return path12.endsWith("/") ? path12 : `${path12}/`;
|
|
5253
5673
|
}
|
|
5254
|
-
function isWithinRoot(
|
|
5674
|
+
function isWithinRoot(path12, root) {
|
|
5255
5675
|
if (isGlobalFilesystemSentinel(root)) {
|
|
5256
5676
|
return true;
|
|
5257
5677
|
}
|
|
5258
|
-
const normalizedPath = normalizeForComparison(
|
|
5678
|
+
const normalizedPath = normalizeForComparison(path12);
|
|
5259
5679
|
const normalizedRoot = normalizeForComparison(root);
|
|
5260
5680
|
return normalizedPath === normalizedRoot || normalizedPath.startsWith(withTrailingSep(normalizedRoot));
|
|
5261
5681
|
}
|
|
5262
5682
|
function getAccessRoots(sandboxRoot, options) {
|
|
5263
|
-
const
|
|
5683
|
+
const fs10 = getFileSystem();
|
|
5264
5684
|
const roots = /* @__PURE__ */ new Set();
|
|
5265
|
-
roots.add(
|
|
5685
|
+
roots.add(fs10.normalize(sandboxRoot));
|
|
5266
5686
|
if (options?.accessRoot) {
|
|
5267
|
-
roots.add(
|
|
5687
|
+
roots.add(fs10.normalize(options.accessRoot));
|
|
5268
5688
|
}
|
|
5269
5689
|
for (const root of options?.accessRoots ?? []) {
|
|
5270
5690
|
const trimmed = String(root || "").trim();
|
|
5271
5691
|
if (trimmed) {
|
|
5272
|
-
roots.add(
|
|
5692
|
+
roots.add(fs10.normalize(trimmed));
|
|
5273
5693
|
}
|
|
5274
5694
|
}
|
|
5275
5695
|
return Array.from(roots);
|
|
5276
5696
|
}
|
|
5277
|
-
function isWithinAnyRoot(
|
|
5278
|
-
if (roots.some((root) => isWithinRoot(
|
|
5279
|
-
const
|
|
5280
|
-
if (!
|
|
5281
|
-
const canonical = canonicalizeExistingPath(
|
|
5697
|
+
function isWithinAnyRoot(path12, roots) {
|
|
5698
|
+
if (roots.some((root) => isWithinRoot(path12, root))) return true;
|
|
5699
|
+
const fs10 = getFileSystem();
|
|
5700
|
+
if (!fs10.realpathSync) return false;
|
|
5701
|
+
const canonical = canonicalizeExistingPath(path12);
|
|
5282
5702
|
return roots.some((root) => isWithinRoot(canonical, canonicalizeExistingPath(root)));
|
|
5283
5703
|
}
|
|
5284
5704
|
function canonicalizeExistingPath(pathValue) {
|
|
5285
|
-
const
|
|
5286
|
-
if (!
|
|
5287
|
-
let cursor =
|
|
5705
|
+
const fs10 = getFileSystem();
|
|
5706
|
+
if (!fs10.realpathSync) return fs10.normalize(pathValue);
|
|
5707
|
+
let cursor = fs10.normalize(pathValue);
|
|
5288
5708
|
const suffix = [];
|
|
5289
|
-
while (!
|
|
5290
|
-
if (
|
|
5709
|
+
while (!fs10.existsSync(cursor)) {
|
|
5710
|
+
if (fs10.lstatSync) {
|
|
5291
5711
|
try {
|
|
5292
|
-
if (
|
|
5712
|
+
if (fs10.lstatSync(cursor).isSymbolicLink) {
|
|
5293
5713
|
throw new Error(`Path contains an unresolved symbolic link: ${cursor}`);
|
|
5294
5714
|
}
|
|
5295
5715
|
} catch (error) {
|
|
5296
5716
|
if (error instanceof Error && error.message.startsWith("Path contains an unresolved symbolic link:")) throw error;
|
|
5297
5717
|
}
|
|
5298
5718
|
}
|
|
5299
|
-
const parent =
|
|
5300
|
-
if (parent === cursor) return
|
|
5301
|
-
suffix.unshift(
|
|
5719
|
+
const parent = fs10.dirname(cursor);
|
|
5720
|
+
if (parent === cursor) return fs10.normalize(pathValue);
|
|
5721
|
+
suffix.unshift(fs10.basename(cursor));
|
|
5302
5722
|
cursor = parent;
|
|
5303
5723
|
}
|
|
5304
|
-
const canonicalBase =
|
|
5305
|
-
return suffix.length > 0 ?
|
|
5724
|
+
const canonicalBase = fs10.normalize(fs10.realpathSync(cursor));
|
|
5725
|
+
return suffix.length > 0 ? fs10.resolve(canonicalBase, ...suffix) : canonicalBase;
|
|
5306
5726
|
}
|
|
5307
5727
|
function finalizeResolvedPath(resolved, sandboxRoot, options) {
|
|
5308
|
-
const
|
|
5309
|
-
if (!
|
|
5728
|
+
const fs10 = getFileSystem();
|
|
5729
|
+
if (!fs10.realpathSync || !fs10.isAbsolute(resolved)) return resolved;
|
|
5310
5730
|
const allowlistedDirs = options?.allowlistedDirs ?? [];
|
|
5311
5731
|
if (allowlistedDirs.some((dir) => isGlobalFilesystemSentinel(dir))) return resolved;
|
|
5312
5732
|
const canonical = canonicalizeExistingPath(resolved);
|
|
@@ -5328,7 +5748,7 @@ function getAvailableRoots(options) {
|
|
|
5328
5748
|
if (!options?.roots || options.roots.length === 0) {
|
|
5329
5749
|
return [];
|
|
5330
5750
|
}
|
|
5331
|
-
const
|
|
5751
|
+
const fs10 = getFileSystem();
|
|
5332
5752
|
const seen = /* @__PURE__ */ new Set();
|
|
5333
5753
|
const results = [];
|
|
5334
5754
|
for (const root of options.roots) {
|
|
@@ -5336,14 +5756,14 @@ function getAvailableRoots(options) {
|
|
|
5336
5756
|
continue;
|
|
5337
5757
|
}
|
|
5338
5758
|
const name = root.name.trim();
|
|
5339
|
-
const
|
|
5340
|
-
if (!name || !
|
|
5759
|
+
const path12 = root.path.trim();
|
|
5760
|
+
if (!name || !path12 || seen.has(name)) {
|
|
5341
5761
|
continue;
|
|
5342
5762
|
}
|
|
5343
5763
|
seen.add(name);
|
|
5344
5764
|
results.push({
|
|
5345
5765
|
name,
|
|
5346
|
-
path:
|
|
5766
|
+
path: fs10.normalize(path12),
|
|
5347
5767
|
description: root.description?.trim() || void 0,
|
|
5348
5768
|
defaultPrefixes: Array.isArray(root.defaultPrefixes) ? root.defaultPrefixes.map((prefix) => String(prefix || "").trim()).filter((prefix) => prefix.length > 0) : void 0
|
|
5349
5769
|
});
|
|
@@ -5398,7 +5818,7 @@ function getResolutionRoot(filePath, sandboxRoot, options, rootName) {
|
|
|
5398
5818
|
return findPrefixMatchedRoot(filePath, options) ?? getRootByName(void 0, sandboxRoot, options);
|
|
5399
5819
|
}
|
|
5400
5820
|
function resolveInSandbox(filePath, sandboxRoot, options, rootName) {
|
|
5401
|
-
const
|
|
5821
|
+
const fs10 = getFileSystem();
|
|
5402
5822
|
const allowlistedDirs = options?.allowlistedDirs ?? [];
|
|
5403
5823
|
const accessRoots = getAccessRoots(sandboxRoot, options);
|
|
5404
5824
|
if (!filePath) {
|
|
@@ -5406,8 +5826,8 @@ function resolveInSandbox(filePath, sandboxRoot, options, rootName) {
|
|
|
5406
5826
|
}
|
|
5407
5827
|
validateToolPathArgument(filePath);
|
|
5408
5828
|
const cleaned = filePath.trim().startsWith("@") ? filePath.trim().slice(1) : filePath.trim();
|
|
5409
|
-
if (
|
|
5410
|
-
const normalized =
|
|
5829
|
+
if (fs10.isAbsolute(cleaned) || isAbsoluteUserPath(cleaned)) {
|
|
5830
|
+
const normalized = fs10.normalize(cleaned);
|
|
5411
5831
|
const selectedRoot2 = rootName ? getRootByName(rootName, sandboxRoot, options) : void 0;
|
|
5412
5832
|
if (rootName && !selectedRoot2) {
|
|
5413
5833
|
const available = getAvailableRoots(options).map((root) => root.name).join(", ");
|
|
@@ -5442,7 +5862,7 @@ function resolveInSandbox(filePath, sandboxRoot, options, rootName) {
|
|
|
5442
5862
|
);
|
|
5443
5863
|
}
|
|
5444
5864
|
const resolvedBase = selectedRoot?.path ?? sandboxRoot;
|
|
5445
|
-
const resolved =
|
|
5865
|
+
const resolved = fs10.resolve(resolvedBase, cleaned);
|
|
5446
5866
|
if (selectedRoot) {
|
|
5447
5867
|
if (!isWithinAnyRoot(resolved, [selectedRoot.path])) {
|
|
5448
5868
|
throw new Error(`Path escapes root '${selectedRoot.name}': ${filePath}`);
|
|
@@ -5980,7 +6400,7 @@ function createReadErrorResult(message, details) {
|
|
|
5980
6400
|
};
|
|
5981
6401
|
}
|
|
5982
6402
|
function createReadTool(cwd, options) {
|
|
5983
|
-
const
|
|
6403
|
+
const fs10 = getFileSystem();
|
|
5984
6404
|
const fileObservationState = options?.fileObservationState ?? createFileObservationState();
|
|
5985
6405
|
const callerObservations = /* @__PURE__ */ new WeakMap();
|
|
5986
6406
|
const rootSchema = buildRootParameterSchema(cwd, options);
|
|
@@ -6000,7 +6420,7 @@ function createReadTool(cwd, options) {
|
|
|
6000
6420
|
parameters: readSchema,
|
|
6001
6421
|
execute: async (_toolCallId, rawParams, signal, _onUpdate) => {
|
|
6002
6422
|
const params = rawParams ?? {};
|
|
6003
|
-
const { path:
|
|
6423
|
+
const { path: path12, root, question } = params;
|
|
6004
6424
|
const tail = params.tail;
|
|
6005
6425
|
let offset = params.offset;
|
|
6006
6426
|
let limit = params.limit;
|
|
@@ -6021,7 +6441,7 @@ function createReadTool(cwd, options) {
|
|
|
6021
6441
|
}
|
|
6022
6442
|
let absolutePath;
|
|
6023
6443
|
try {
|
|
6024
|
-
absolutePath = resolveReadPath(
|
|
6444
|
+
absolutePath = resolveReadPath(path12, cwd, options, root);
|
|
6025
6445
|
} catch (error) {
|
|
6026
6446
|
const message = error instanceof Error ? error.message : String(error);
|
|
6027
6447
|
if (/outside sandbox|outside root|escapes sandbox/i.test(message)) {
|
|
@@ -6032,7 +6452,7 @@ function createReadTool(cwd, options) {
|
|
|
6032
6452
|
return createReadErrorResult(message);
|
|
6033
6453
|
}
|
|
6034
6454
|
return new Promise(
|
|
6035
|
-
(
|
|
6455
|
+
(resolve7, reject) => {
|
|
6036
6456
|
if (signal?.aborted) {
|
|
6037
6457
|
reject(new Error("Operation aborted"));
|
|
6038
6458
|
return;
|
|
@@ -6047,26 +6467,26 @@ function createReadTool(cwd, options) {
|
|
|
6047
6467
|
}
|
|
6048
6468
|
(async () => {
|
|
6049
6469
|
try {
|
|
6050
|
-
await
|
|
6470
|
+
await fs10.access(absolutePath);
|
|
6051
6471
|
if (isSpecialDevicePath(absolutePath)) {
|
|
6052
6472
|
throw new Error(`Refusing to read special device path: ${absolutePath}`);
|
|
6053
6473
|
}
|
|
6054
|
-
const stat = await
|
|
6474
|
+
const stat = await fs10.stat(absolutePath);
|
|
6055
6475
|
if (!stat.isFile) {
|
|
6056
6476
|
throw new Error(`Refusing to read non-regular file: ${absolutePath}`);
|
|
6057
6477
|
}
|
|
6058
6478
|
if (aborted) return;
|
|
6059
|
-
const prefix = await
|
|
6479
|
+
const prefix = await fs10.readFilePrefix(absolutePath, BINARY_MAGIC_PREFIX_BYTES);
|
|
6060
6480
|
const magicInfo = detectBinaryMagic(prefix);
|
|
6061
6481
|
let binaryInfo = detectBinaryKind(absolutePath);
|
|
6062
6482
|
if (options?.allowBinary === false) {
|
|
6063
6483
|
binaryInfo = detectTextOnlyBinary(prefix, absolutePath, stat.size > prefix.length);
|
|
6064
6484
|
}
|
|
6065
6485
|
if (options?.allowBinary === false && binaryInfo) {
|
|
6066
|
-
|
|
6486
|
+
resolve7({
|
|
6067
6487
|
content: [{
|
|
6068
6488
|
type: "text",
|
|
6069
|
-
text: `Cannot read ${binaryInfo.kind} file ${
|
|
6489
|
+
text: `Cannot read ${binaryInfo.kind} file ${path12}: this read_file instance accepts text files only.`
|
|
6070
6490
|
}],
|
|
6071
6491
|
details: {
|
|
6072
6492
|
understanding: {
|
|
@@ -6080,9 +6500,9 @@ function createReadTool(cwd, options) {
|
|
|
6080
6500
|
return;
|
|
6081
6501
|
}
|
|
6082
6502
|
if (magicInfo?.kind === "image" && options?.understandFile && (!INLINE_IMAGE_MIME_TYPES.has(magicInfo.mimeType) || stat.size > MAX_INLINE_IMAGE_BYTES)) {
|
|
6083
|
-
|
|
6503
|
+
resolve7(await options.understandFile({
|
|
6084
6504
|
absolutePath,
|
|
6085
|
-
displayPath:
|
|
6505
|
+
displayPath: path12,
|
|
6086
6506
|
mimeType: magicInfo.mimeType,
|
|
6087
6507
|
kind: "image",
|
|
6088
6508
|
question,
|
|
@@ -6091,14 +6511,14 @@ function createReadTool(cwd, options) {
|
|
|
6091
6511
|
return;
|
|
6092
6512
|
}
|
|
6093
6513
|
if (magicInfo?.kind === "image" && INLINE_IMAGE_MIME_TYPES.has(magicInfo.mimeType) && stat.size > MAX_INLINE_IMAGE_BYTES) {
|
|
6094
|
-
throw new Error(`Image file ${
|
|
6514
|
+
throw new Error(`Image file ${path12} is too large to attach (${formatSize(stat.size)}; maximum ${formatSize(MAX_INLINE_IMAGE_BYTES)}).`);
|
|
6095
6515
|
}
|
|
6096
|
-
const imageInfo = options?.allowBinary === false || magicInfo?.kind !== "image" || !INLINE_IMAGE_MIME_TYPES.has(magicInfo.mimeType) ? void 0 : await readImageInfo(absolutePath,
|
|
6516
|
+
const imageInfo = options?.allowBinary === false || magicInfo?.kind !== "image" || !INLINE_IMAGE_MIME_TYPES.has(magicInfo.mimeType) ? void 0 : await readImageInfo(absolutePath, fs10);
|
|
6097
6517
|
if (imageInfo) {
|
|
6098
6518
|
if (options?.understandFile) {
|
|
6099
|
-
|
|
6519
|
+
resolve7(await options.understandFile({
|
|
6100
6520
|
absolutePath,
|
|
6101
|
-
displayPath:
|
|
6521
|
+
displayPath: path12,
|
|
6102
6522
|
mimeType: imageInfo.mimeType,
|
|
6103
6523
|
kind: "image",
|
|
6104
6524
|
question,
|
|
@@ -6108,7 +6528,7 @@ function createReadTool(cwd, options) {
|
|
|
6108
6528
|
return;
|
|
6109
6529
|
}
|
|
6110
6530
|
const dimensionText = imageInfo.width && imageInfo.height ? `, ${imageInfo.width}x${imageInfo.height}` : "";
|
|
6111
|
-
|
|
6531
|
+
resolve7({
|
|
6112
6532
|
content: [
|
|
6113
6533
|
{ type: "text", text: `Read image file [${imageInfo.mimeType}${dimensionText}]. Original image attached as an image block; for very large images, prefer a smaller crop or resized copy before rereading.${question?.trim() ? `
|
|
6114
6534
|
Focus: ${question.trim()}` : ""}` },
|
|
@@ -6126,8 +6546,8 @@ Focus: ${question.trim()}` : ""}` },
|
|
|
6126
6546
|
}
|
|
6127
6547
|
if (magicInfo?.kind === "image") {
|
|
6128
6548
|
const inlineSupported = INLINE_IMAGE_MIME_TYPES.has(magicInfo.mimeType);
|
|
6129
|
-
|
|
6130
|
-
content: [{ type: "text", text: inlineSupported ? `Cannot attach image file ${
|
|
6549
|
+
resolve7({
|
|
6550
|
+
content: [{ type: "text", text: inlineSupported ? `Cannot attach image file ${path12}: the host filesystem bridge returned no usable image data for ${magicInfo.mimeType} (see logs for readImageInfo diagnostics).` : `Cannot attach image file ${path12}: unsupported image payload ${magicInfo.mimeType}.` }],
|
|
6131
6551
|
details: { understanding: { kind: "image", mimeType: magicInfo.mimeType, fallbackReason: inlineSupported ? "image bridge read failed" : "unsupported inline image format" } },
|
|
6132
6552
|
isError: true
|
|
6133
6553
|
});
|
|
@@ -6135,9 +6555,9 @@ Focus: ${question.trim()}` : ""}` },
|
|
|
6135
6555
|
}
|
|
6136
6556
|
const mediaInfo = magicInfo ?? detectUnderstandingKind(absolutePath);
|
|
6137
6557
|
if (mediaInfo && options?.understandFile) {
|
|
6138
|
-
|
|
6558
|
+
resolve7(await options.understandFile({
|
|
6139
6559
|
absolutePath,
|
|
6140
|
-
displayPath:
|
|
6560
|
+
displayPath: path12,
|
|
6141
6561
|
mimeType: mediaInfo.mimeType,
|
|
6142
6562
|
kind: mediaInfo.kind,
|
|
6143
6563
|
question,
|
|
@@ -6146,10 +6566,10 @@ Focus: ${question.trim()}` : ""}` },
|
|
|
6146
6566
|
return;
|
|
6147
6567
|
}
|
|
6148
6568
|
if (mediaInfo) {
|
|
6149
|
-
|
|
6569
|
+
resolve7({
|
|
6150
6570
|
content: [{
|
|
6151
6571
|
type: "text",
|
|
6152
|
-
text: `Cannot read ${mediaInfo.kind} file ${
|
|
6572
|
+
text: `Cannot read ${mediaInfo.kind} file ${path12} semantically: no media understanding handler is configured for ${mediaInfo.mimeType}.`
|
|
6153
6573
|
}],
|
|
6154
6574
|
details: {
|
|
6155
6575
|
understanding: {
|
|
@@ -6164,10 +6584,10 @@ Focus: ${question.trim()}` : ""}` },
|
|
|
6164
6584
|
}
|
|
6165
6585
|
const textBinaryInfo = detectTextOnlyBinary(prefix, absolutePath, stat.size > prefix.length);
|
|
6166
6586
|
if (textBinaryInfo) {
|
|
6167
|
-
|
|
6587
|
+
resolve7({
|
|
6168
6588
|
content: [{
|
|
6169
6589
|
type: "text",
|
|
6170
|
-
text: `Cannot read binary file ${
|
|
6590
|
+
text: `Cannot read binary file ${path12}: ${textBinaryInfo.mimeType}. Use a file-understanding handler for supported media/documents, or inspect metadata with a bounded shell command.`
|
|
6171
6591
|
}],
|
|
6172
6592
|
details: {
|
|
6173
6593
|
understanding: {
|
|
@@ -6189,7 +6609,7 @@ Focus: ${question.trim()}` : ""}` },
|
|
|
6189
6609
|
const effectiveTail = Math.max(1, Math.min(tail, DEFAULT_MAX_LINES - 1));
|
|
6190
6610
|
translatedFromTail = true;
|
|
6191
6611
|
tailEffectiveLines = effectiveTail;
|
|
6192
|
-
range2 = await
|
|
6612
|
+
range2 = await fs10.readTextRange(absolutePath, {
|
|
6193
6613
|
tailLines: effectiveTail,
|
|
6194
6614
|
maxOutputLines: DEFAULT_MAX_LINES,
|
|
6195
6615
|
maxOutputBytes: DEFAULT_MAX_BYTES
|
|
@@ -6204,7 +6624,7 @@ Focus: ${question.trim()}` : ""}` },
|
|
|
6204
6624
|
}
|
|
6205
6625
|
} else {
|
|
6206
6626
|
startLine = offset === void 0 ? 0 : offset - 1;
|
|
6207
|
-
range2 = await
|
|
6627
|
+
range2 = await fs10.readTextRange(absolutePath, {
|
|
6208
6628
|
offsetLine: startLine,
|
|
6209
6629
|
limitLines: limit,
|
|
6210
6630
|
maxOutputLines: DEFAULT_MAX_LINES,
|
|
@@ -6216,8 +6636,8 @@ Focus: ${question.trim()}` : ""}` },
|
|
|
6216
6636
|
const selectedLooksBinary = range2.selectedBytesLookBinary ?? (looksLikeBinaryText(range2.content) || range2.content.includes("\uFFFD"));
|
|
6217
6637
|
const selectedBinary = selectedLooksBinary ? { kind: "document", mimeType: "application/octet-stream" } : void 0;
|
|
6218
6638
|
if (selectedBinary) {
|
|
6219
|
-
|
|
6220
|
-
content: [{ type: "text", text: `Cannot read ${selectedBinary.kind} file ${
|
|
6639
|
+
resolve7({
|
|
6640
|
+
content: [{ type: "text", text: `Cannot read ${selectedBinary.kind} file ${path12}: this read_file instance accepts text files only.` }],
|
|
6221
6641
|
details: { understanding: { ...selectedBinary, fallbackReason: "binary content is disabled for this tool" } },
|
|
6222
6642
|
isError: true
|
|
6223
6643
|
});
|
|
@@ -6270,7 +6690,7 @@ Focus: ${question.trim()}` : ""}` },
|
|
|
6270
6690
|
if (signal) {
|
|
6271
6691
|
signal.removeEventListener("abort", onAbort);
|
|
6272
6692
|
}
|
|
6273
|
-
|
|
6693
|
+
resolve7({
|
|
6274
6694
|
content: [{
|
|
6275
6695
|
type: "text",
|
|
6276
6696
|
text: translatedFromTail ? `File unchanged since previous tail=${tailEffectiveLines} read (last ${tailWindowIncludesPhantom ? range2.selectedLines - 1 : range2.selectedLines} lines, ${range2.totalLines} lines total). Earlier reads still count toward write_file coverage of this file.` : `File unchanged since previous read of this range (offset=${startLineDisplay}${limit === void 0 ? ", no limit" : `, limit=${limit}`}). Earlier reads still count toward write_file coverage of this file. Use a different offset/limit if you need another section.`
|
|
@@ -6368,7 +6788,7 @@ Base directory: ${nodePath.dirname(absolutePath)}
|
|
|
6368
6788
|
if (signal) {
|
|
6369
6789
|
signal.removeEventListener("abort", onAbort);
|
|
6370
6790
|
}
|
|
6371
|
-
|
|
6791
|
+
resolve7({
|
|
6372
6792
|
content: textContent,
|
|
6373
6793
|
details
|
|
6374
6794
|
});
|
|
@@ -6379,7 +6799,7 @@ Base directory: ${nodePath.dirname(absolutePath)}
|
|
|
6379
6799
|
reject(error);
|
|
6380
6800
|
return;
|
|
6381
6801
|
}
|
|
6382
|
-
|
|
6802
|
+
resolve7(createReadErrorResult(message, { path: absolutePath }));
|
|
6383
6803
|
}
|
|
6384
6804
|
} finally {
|
|
6385
6805
|
signal?.removeEventListener("abort", onAbort);
|
|
@@ -6390,8 +6810,8 @@ Base directory: ${nodePath.dirname(absolutePath)}
|
|
|
6390
6810
|
}
|
|
6391
6811
|
};
|
|
6392
6812
|
}
|
|
6393
|
-
function isSpecialDevicePath(
|
|
6394
|
-
const normalized = nodePath.resolve(
|
|
6813
|
+
function isSpecialDevicePath(path12) {
|
|
6814
|
+
const normalized = nodePath.resolve(path12).replace(/\\/g, "/");
|
|
6395
6815
|
return /^\/dev\/(?:zero|random|urandom|full|stdin|stdout|stderr|tty|console)$/.test(normalized) || /^\/dev\/fd\/[0-2]$/.test(normalized) || /^\/proc\/(?:self|\d+)\/fd\/[0-2]$/.test(normalized);
|
|
6396
6816
|
}
|
|
6397
6817
|
function detectUnderstandingKind(filePath) {
|
|
@@ -6532,22 +6952,22 @@ function detectTextOnlyBinary(input, filePath, prefixMayBeTruncated) {
|
|
|
6532
6952
|
if (!looksLikeBinary(input, prefixMayBeTruncated)) return void 0;
|
|
6533
6953
|
return detectBinaryKind(filePath) ?? { kind: "document", mimeType: "application/octet-stream" };
|
|
6534
6954
|
}
|
|
6535
|
-
async function readImageInfo(
|
|
6955
|
+
async function readImageInfo(path12, fs10) {
|
|
6536
6956
|
try {
|
|
6537
6957
|
let base64 = "";
|
|
6538
|
-
if (typeof
|
|
6539
|
-
base64 = await
|
|
6958
|
+
if (typeof fs10.readFile === "function") {
|
|
6959
|
+
base64 = await fs10.readFile(path12, "base64").catch(() => "");
|
|
6540
6960
|
}
|
|
6541
|
-
if (!base64 && typeof
|
|
6542
|
-
base64 =
|
|
6961
|
+
if (!base64 && typeof fs10.readFileSync === "function") {
|
|
6962
|
+
base64 = fs10.readFileSync(path12, "base64");
|
|
6543
6963
|
}
|
|
6544
6964
|
if (!base64) {
|
|
6545
|
-
console.error(`[pie] readImageInfo got empty base64 for ${
|
|
6965
|
+
console.error(`[pie] readImageInfo got empty base64 for ${path12}`);
|
|
6546
6966
|
return void 0;
|
|
6547
6967
|
}
|
|
6548
6968
|
const bytes = decodeBase64ToBytes(base64);
|
|
6549
6969
|
if (bytes.length === 0) {
|
|
6550
|
-
console.error(`[pie] readImageInfo decoded 0 bytes for ${
|
|
6970
|
+
console.error(`[pie] readImageInfo decoded 0 bytes for ${path12} (base64 length ${base64.length})`);
|
|
6551
6971
|
return void 0;
|
|
6552
6972
|
}
|
|
6553
6973
|
const pngMagic = [137, 80, 78, 71, 13, 10, 26, 10];
|
|
@@ -6566,10 +6986,10 @@ async function readImageInfo(path11, fs9) {
|
|
|
6566
6986
|
if (bytes.length >= 12 && asciiAt(bytes, 0, 4) === "RIFF" && asciiAt(bytes, 8, 12 - 8) === "WEBP") {
|
|
6567
6987
|
return { mimeType: "image/webp", base64, ...parseWebpDimensions(bytes) };
|
|
6568
6988
|
}
|
|
6569
|
-
console.error(`[pie] readImageInfo decoded ${bytes.length} bytes for ${
|
|
6989
|
+
console.error(`[pie] readImageInfo decoded ${bytes.length} bytes for ${path12} but no known image signature matched`);
|
|
6570
6990
|
return void 0;
|
|
6571
6991
|
} catch (error) {
|
|
6572
|
-
console.error(`[pie] readImageInfo failed for ${
|
|
6992
|
+
console.error(`[pie] readImageInfo failed for ${path12}: ${error instanceof Error ? error.message : String(error)}`);
|
|
6573
6993
|
return void 0;
|
|
6574
6994
|
}
|
|
6575
6995
|
return void 0;
|
|
@@ -6701,7 +7121,7 @@ function parseWebpDimensions(bytes) {
|
|
|
6701
7121
|
|
|
6702
7122
|
// ../../packages/shared-headless-capabilities/src/builtin/fs/write.ts
|
|
6703
7123
|
function createWriteTool(cwd, options) {
|
|
6704
|
-
const
|
|
7124
|
+
const fs10 = getFileSystem();
|
|
6705
7125
|
const usesExternalFileObservationState = !!options?.fileObservationState;
|
|
6706
7126
|
const fileObservationState = options?.fileObservationState ?? createFileObservationState();
|
|
6707
7127
|
const rootSchema = buildRootParameterSchema(cwd, options);
|
|
@@ -6719,9 +7139,9 @@ function createWriteTool(cwd, options) {
|
|
|
6719
7139
|
execute: async (_toolCallId, rawParams, signal) => {
|
|
6720
7140
|
const { path: filePath, root, content } = rawParams ?? {};
|
|
6721
7141
|
const absolutePath = resolveToCwd(filePath, cwd, options, root);
|
|
6722
|
-
const dir =
|
|
7142
|
+
const dir = fs10.dirname(absolutePath);
|
|
6723
7143
|
return new Promise(
|
|
6724
|
-
(
|
|
7144
|
+
(resolve7, reject) => {
|
|
6725
7145
|
if (signal?.aborted) {
|
|
6726
7146
|
reject(new Error("Operation aborted"));
|
|
6727
7147
|
return;
|
|
@@ -6736,18 +7156,18 @@ function createWriteTool(cwd, options) {
|
|
|
6736
7156
|
}
|
|
6737
7157
|
(async () => {
|
|
6738
7158
|
try {
|
|
6739
|
-
await
|
|
7159
|
+
await fs10.mkdir(dir, { recursive: true });
|
|
6740
7160
|
if (aborted) return;
|
|
6741
7161
|
let fileExists = false;
|
|
6742
7162
|
try {
|
|
6743
|
-
const stat = await
|
|
7163
|
+
const stat = await fs10.stat(absolutePath);
|
|
6744
7164
|
fileExists = stat.isFile;
|
|
6745
7165
|
} catch {
|
|
6746
7166
|
fileExists = false;
|
|
6747
7167
|
}
|
|
6748
7168
|
if (fileExists) {
|
|
6749
|
-
const currentContent = String(await
|
|
6750
|
-
const currentStat = await
|
|
7169
|
+
const currentContent = String(await fs10.readFile(absolutePath, "utf-8"));
|
|
7170
|
+
const currentStat = await fs10.stat(absolutePath);
|
|
6751
7171
|
const currentSnapshot = snapshotFromStatAndContent(currentStat, currentContent);
|
|
6752
7172
|
const observedSnapshot = fileObservationState.getCompleteTextSnapshot(absolutePath);
|
|
6753
7173
|
if (!observedSnapshot) {
|
|
@@ -6763,8 +7183,8 @@ function createWriteTool(cwd, options) {
|
|
|
6763
7183
|
);
|
|
6764
7184
|
}
|
|
6765
7185
|
}
|
|
6766
|
-
await
|
|
6767
|
-
const writtenStat = await
|
|
7186
|
+
await fs10.writeFile(absolutePath, content, "utf-8");
|
|
7187
|
+
const writtenStat = await fs10.stat(absolutePath);
|
|
6768
7188
|
fileObservationState.recordCompleteTextWrite(
|
|
6769
7189
|
absolutePath,
|
|
6770
7190
|
snapshotFromStatAndContent(writtenStat, content)
|
|
@@ -6773,7 +7193,7 @@ function createWriteTool(cwd, options) {
|
|
|
6773
7193
|
if (signal) {
|
|
6774
7194
|
signal.removeEventListener("abort", onAbort);
|
|
6775
7195
|
}
|
|
6776
|
-
|
|
7196
|
+
resolve7({
|
|
6777
7197
|
content: [{ type: "text", text: `Successfully wrote ${writtenStat.size} bytes to ${filePath}` }],
|
|
6778
7198
|
details: void 0
|
|
6779
7199
|
});
|
|
@@ -6892,16 +7312,16 @@ var Diff = class {
|
|
|
6892
7312
|
}
|
|
6893
7313
|
}
|
|
6894
7314
|
}
|
|
6895
|
-
addToPath(
|
|
6896
|
-
const last =
|
|
7315
|
+
addToPath(path12, added, removed, oldPosInc, options) {
|
|
7316
|
+
const last = path12.lastComponent;
|
|
6897
7317
|
if (last && !options.oneChangePerToken && last.added === added && last.removed === removed) {
|
|
6898
7318
|
return {
|
|
6899
|
-
oldPos:
|
|
7319
|
+
oldPos: path12.oldPos + oldPosInc,
|
|
6900
7320
|
lastComponent: { count: last.count + 1, added, removed, previousComponent: last.previousComponent }
|
|
6901
7321
|
};
|
|
6902
7322
|
} else {
|
|
6903
7323
|
return {
|
|
6904
|
-
oldPos:
|
|
7324
|
+
oldPos: path12.oldPos + oldPosInc,
|
|
6905
7325
|
lastComponent: { count: 1, added, removed, previousComponent: last }
|
|
6906
7326
|
};
|
|
6907
7327
|
}
|
|
@@ -7773,8 +8193,8 @@ function generateDiffString(oldContent, newContent, contextLines = 4) {
|
|
|
7773
8193
|
var MAX_EDIT_BLOCKS = 64;
|
|
7774
8194
|
var MAX_EDIT_INPUT_CHARS = 256 * 1024;
|
|
7775
8195
|
function validateEditArgs(params) {
|
|
7776
|
-
const { path:
|
|
7777
|
-
const filePath = typeof
|
|
8196
|
+
const { path: path12, oldText, newText, replaceAll, edits } = params;
|
|
8197
|
+
const filePath = typeof path12 === "string" ? path12.trim() : "";
|
|
7778
8198
|
if (!filePath) {
|
|
7779
8199
|
throw new Error("Invalid edit_file arguments: path cannot be empty. Pass the file path in path and the exact text to replace in oldText.");
|
|
7780
8200
|
}
|
|
@@ -7856,14 +8276,14 @@ function createEditErrorResult(params) {
|
|
|
7856
8276
|
isError: true
|
|
7857
8277
|
};
|
|
7858
8278
|
}
|
|
7859
|
-
function createEditThrownErrorResult(message,
|
|
8279
|
+
function createEditThrownErrorResult(message, path12) {
|
|
7860
8280
|
return {
|
|
7861
8281
|
content: [{ type: "text", text: boundEditOutput(`edit_file failed: ${message}`).text }],
|
|
7862
8282
|
details: {
|
|
7863
8283
|
status: "error",
|
|
7864
8284
|
matchKind: "none",
|
|
7865
8285
|
changed: false,
|
|
7866
|
-
path:
|
|
8286
|
+
path: path12,
|
|
7867
8287
|
diff: "",
|
|
7868
8288
|
oldTextOccurrences: 0,
|
|
7869
8289
|
newTextOccurrences: 0,
|
|
@@ -7876,7 +8296,7 @@ function createEditThrownErrorResult(message, path11) {
|
|
|
7876
8296
|
};
|
|
7877
8297
|
}
|
|
7878
8298
|
function createEditTool(cwd, options) {
|
|
7879
|
-
const
|
|
8299
|
+
const fs10 = getFileSystem();
|
|
7880
8300
|
const fileObservationState = options?.fileObservationState ?? createFileObservationState();
|
|
7881
8301
|
const usesExternalFileObservationState = !!options?.fileObservationState;
|
|
7882
8302
|
const rootSchema = buildRootParameterSchema(cwd, options);
|
|
@@ -7901,17 +8321,17 @@ function createEditTool(cwd, options) {
|
|
|
7901
8321
|
parameters: editSchema,
|
|
7902
8322
|
execute: async (_toolCallId, rawParams, signal) => {
|
|
7903
8323
|
const params = rawParams ?? {};
|
|
7904
|
-
const { path:
|
|
8324
|
+
const { path: path12, root } = params;
|
|
7905
8325
|
let replacements;
|
|
7906
8326
|
let absolutePath;
|
|
7907
8327
|
try {
|
|
7908
8328
|
replacements = validateEditArgs(params);
|
|
7909
|
-
absolutePath = resolveToCwd(
|
|
8329
|
+
absolutePath = resolveToCwd(path12, cwd, options, root);
|
|
7910
8330
|
} catch (error) {
|
|
7911
8331
|
const message = error instanceof Error ? error.message : String(error);
|
|
7912
|
-
return createEditThrownErrorResult(message, typeof
|
|
8332
|
+
return createEditThrownErrorResult(message, typeof path12 === "string" ? path12 : void 0);
|
|
7913
8333
|
}
|
|
7914
|
-
return new Promise((
|
|
8334
|
+
return new Promise((resolve7, reject) => {
|
|
7915
8335
|
if (signal?.aborted) {
|
|
7916
8336
|
reject(new Error("Operation aborted"));
|
|
7917
8337
|
return;
|
|
@@ -7932,10 +8352,10 @@ function createEditTool(cwd, options) {
|
|
|
7932
8352
|
if (aborted || signal?.aborted) throw new Error("Operation aborted");
|
|
7933
8353
|
};
|
|
7934
8354
|
try {
|
|
7935
|
-
await
|
|
8355
|
+
await fs10.access(absolutePath);
|
|
7936
8356
|
} catch {
|
|
7937
8357
|
if (signal) signal.removeEventListener("abort", onAbort);
|
|
7938
|
-
|
|
8358
|
+
resolve7(createEditThrownErrorResult(`File not found: ${path12}`, path12));
|
|
7939
8359
|
return;
|
|
7940
8360
|
}
|
|
7941
8361
|
throwIfAborted();
|
|
@@ -7946,8 +8366,8 @@ function createEditTool(cwd, options) {
|
|
|
7946
8366
|
const lastClear = fileObservationState.getLastClear?.();
|
|
7947
8367
|
const resetNote = lastClear ? ` Note: the session's read ledger was reset by ${lastClear.reason} at ${new Date(lastClear.timestamp).toISOString()} \u2014 if you read this file before that reset, its content is no longer in your context and must be re-read.` : "";
|
|
7948
8368
|
if (signal) signal.removeEventListener("abort", onAbort);
|
|
7949
|
-
|
|
7950
|
-
message: `edit_file blocked: ${
|
|
8369
|
+
resolve7(createEditErrorResult({
|
|
8370
|
+
message: `edit_file blocked: ${path12} has not been read in this session.${resetNote}`,
|
|
7951
8371
|
matchKind: "none",
|
|
7952
8372
|
errorReason: "old_text_not_found",
|
|
7953
8373
|
oldTextOccurrences: 0,
|
|
@@ -7958,7 +8378,7 @@ function createEditTool(cwd, options) {
|
|
|
7958
8378
|
return;
|
|
7959
8379
|
}
|
|
7960
8380
|
}
|
|
7961
|
-
const rawContent = await
|
|
8381
|
+
const rawContent = await fs10.readFile(absolutePath, "utf-8");
|
|
7962
8382
|
throwIfAborted();
|
|
7963
8383
|
const { bom, text: content } = stripBom(rawContent);
|
|
7964
8384
|
const originalEnding = detectLineEnding(content);
|
|
@@ -7985,8 +8405,8 @@ function createEditTool(cwd, options) {
|
|
|
7985
8405
|
if (!matchResult.found) {
|
|
7986
8406
|
if (matchResult.exhausted) {
|
|
7987
8407
|
if (signal) signal.removeEventListener("abort", onAbort);
|
|
7988
|
-
|
|
7989
|
-
message: `Could not match edit ${editIndex + 1} in ${
|
|
8408
|
+
resolve7(createEditErrorResult({
|
|
8409
|
+
message: `Could not match edit ${editIndex + 1} in ${path12} within the relaxed-match budget.`,
|
|
7990
8410
|
matchKind: "none",
|
|
7991
8411
|
errorReason: "match_budget_exhausted",
|
|
7992
8412
|
oldTextOccurrences: 0,
|
|
@@ -7997,8 +8417,8 @@ function createEditTool(cwd, options) {
|
|
|
7997
8417
|
return;
|
|
7998
8418
|
}
|
|
7999
8419
|
if (signal) signal.removeEventListener("abort", onAbort);
|
|
8000
|
-
|
|
8001
|
-
message: `Could not find oldText for edit ${editIndex + 1} in ${
|
|
8420
|
+
resolve7(createEditErrorResult({
|
|
8421
|
+
message: `Could not find oldText for edit ${editIndex + 1} in ${path12}.`,
|
|
8002
8422
|
matchKind: "none",
|
|
8003
8423
|
errorReason: "old_text_not_found",
|
|
8004
8424
|
oldTextOccurrences: 0,
|
|
@@ -8013,8 +8433,8 @@ function createEditTool(cwd, options) {
|
|
|
8013
8433
|
}
|
|
8014
8434
|
if (matchResult.occurrences > 1 && !replacement.replaceAll) {
|
|
8015
8435
|
if (signal) signal.removeEventListener("abort", onAbort);
|
|
8016
|
-
|
|
8017
|
-
message: `Found ${matchResult.occurrences}${matchResult.occurrencesAtLeast ? " or more" : ""} occurrences for edit ${editIndex + 1} in ${
|
|
8436
|
+
resolve7(createEditErrorResult({
|
|
8437
|
+
message: `Found ${matchResult.occurrences}${matchResult.occurrencesAtLeast ? " or more" : ""} occurrences for edit ${editIndex + 1} in ${path12}.`,
|
|
8018
8438
|
matchKind: matchResult.matchKind,
|
|
8019
8439
|
errorReason: "old_text_not_unique",
|
|
8020
8440
|
oldTextOccurrences: matchResult.occurrences,
|
|
@@ -8030,8 +8450,8 @@ function createEditTool(cwd, options) {
|
|
|
8030
8450
|
);
|
|
8031
8451
|
if (changingMatches.length === 0) {
|
|
8032
8452
|
if (signal) signal.removeEventListener("abort", onAbort);
|
|
8033
|
-
|
|
8034
|
-
message: `No changes made for edit ${editIndex + 1} in ${
|
|
8453
|
+
resolve7(createEditErrorResult({
|
|
8454
|
+
message: `No changes made for edit ${editIndex + 1} in ${path12}. Its replacement matches the current file content.`,
|
|
8035
8455
|
matchKind: matchResult.matchKind,
|
|
8036
8456
|
errorReason: "replacement_no_change",
|
|
8037
8457
|
oldTextOccurrences: matchResult.occurrences,
|
|
@@ -8052,9 +8472,9 @@ function createEditTool(cwd, options) {
|
|
|
8052
8472
|
throwIfAborted();
|
|
8053
8473
|
if (workingContent === normalizedContent) {
|
|
8054
8474
|
if (signal) signal.removeEventListener("abort", onAbort);
|
|
8055
|
-
|
|
8475
|
+
resolve7(
|
|
8056
8476
|
createEditErrorResult({
|
|
8057
|
-
message: `No changes made to ${
|
|
8477
|
+
message: `No changes made to ${path12}. The replacement produced identical content.`,
|
|
8058
8478
|
matchKind: plannedKinds.size === 1 ? [...plannedKinds][0] : "mixed",
|
|
8059
8479
|
errorReason: "replacement_no_change",
|
|
8060
8480
|
oldTextOccurrences: totalOldOccurrences,
|
|
@@ -8072,12 +8492,12 @@ function createEditTool(cwd, options) {
|
|
|
8072
8492
|
const diffResult = generateDiffString(normalizedContent, newContent);
|
|
8073
8493
|
throwIfAborted();
|
|
8074
8494
|
committing = true;
|
|
8075
|
-
await
|
|
8495
|
+
await fs10.writeFile(absolutePath, finalContent, "utf-8");
|
|
8076
8496
|
if (signal) signal.removeEventListener("abort", onAbort);
|
|
8077
8497
|
let diagnosticWarning;
|
|
8078
8498
|
try {
|
|
8079
8499
|
if (usesExternalFileObservationState) {
|
|
8080
|
-
const writtenStat = await
|
|
8500
|
+
const writtenStat = await fs10.stat(absolutePath);
|
|
8081
8501
|
const snapshot = snapshotFromStatAndContent(writtenStat, finalContent);
|
|
8082
8502
|
fileObservationState.invalidate(absolutePath);
|
|
8083
8503
|
fileObservationState.recordTextRead(
|
|
@@ -8096,10 +8516,10 @@ function createEditTool(cwd, options) {
|
|
|
8096
8516
|
diagnosticWarning = "Edit saved, but file observation refresh failed; read the file before the next edit.";
|
|
8097
8517
|
}
|
|
8098
8518
|
const matchKind = plannedKinds.size === 1 ? [...plannedKinds][0] : "mixed";
|
|
8099
|
-
const visible = boundEditOutput(`Changed ${
|
|
8519
|
+
const visible = boundEditOutput(`Changed ${path12}: ${replacements.length} edit block${replacements.length === 1 ? "" : "s"}, ${replacedOccurrences} replacement${replacedOccurrences === 1 ? "" : "s"}. First changed line: ${diffResult.firstChangedLine}.
|
|
8100
8520
|
${diagnosticWarning ?? ""}
|
|
8101
8521
|
${diffResult.diff}`);
|
|
8102
|
-
|
|
8522
|
+
resolve7({
|
|
8103
8523
|
content: [
|
|
8104
8524
|
{
|
|
8105
8525
|
type: "text",
|
|
@@ -8110,7 +8530,7 @@ ${diffResult.diff}`);
|
|
|
8110
8530
|
status: "success",
|
|
8111
8531
|
matchKind,
|
|
8112
8532
|
changed: true,
|
|
8113
|
-
path:
|
|
8533
|
+
path: path12,
|
|
8114
8534
|
diff: diffResult.diff,
|
|
8115
8535
|
diffTruncated: diffResult.truncated,
|
|
8116
8536
|
contentTruncated: visible.truncated,
|
|
@@ -8134,7 +8554,7 @@ ${diffResult.diff}`);
|
|
|
8134
8554
|
reject(error);
|
|
8135
8555
|
return;
|
|
8136
8556
|
}
|
|
8137
|
-
|
|
8557
|
+
resolve7(createEditThrownErrorResult(message, path12));
|
|
8138
8558
|
}
|
|
8139
8559
|
}
|
|
8140
8560
|
})();
|
|
@@ -8147,7 +8567,7 @@ ${diffResult.diff}`);
|
|
|
8147
8567
|
var DEFAULT_LIMIT = 500;
|
|
8148
8568
|
var MAX_RESULT_LIMIT = 1e4;
|
|
8149
8569
|
function createLsTool(cwd, options) {
|
|
8150
|
-
const
|
|
8570
|
+
const fs10 = getFileSystem();
|
|
8151
8571
|
const rootSchema = buildRootParameterSchema(cwd, options);
|
|
8152
8572
|
const lsSchema = Type.Object({
|
|
8153
8573
|
path: Type.Optional(Type.String({ description: "Directory to list (default: workspace root). Example: 'Scripts' or 'Data'." })),
|
|
@@ -8162,7 +8582,7 @@ function createLsTool(cwd, options) {
|
|
|
8162
8582
|
parameters: lsSchema,
|
|
8163
8583
|
execute: async (_toolCallId, rawParams, signal) => {
|
|
8164
8584
|
const params = rawParams ?? {};
|
|
8165
|
-
return new Promise((
|
|
8585
|
+
return new Promise((resolve7, reject) => {
|
|
8166
8586
|
if (signal?.aborted) {
|
|
8167
8587
|
reject(new Error("Operation aborted"));
|
|
8168
8588
|
return;
|
|
@@ -8181,14 +8601,14 @@ function createLsTool(cwd, options) {
|
|
|
8181
8601
|
if (!Number.isInteger(effectiveLimit) || effectiveLimit < 1 || effectiveLimit > MAX_RESULT_LIMIT) {
|
|
8182
8602
|
throw new Error(`Invalid list_dir arguments: limit must be between 1 and ${MAX_RESULT_LIMIT}.`);
|
|
8183
8603
|
}
|
|
8184
|
-
if (!await
|
|
8604
|
+
if (!await fs10.exists(targetPath)) {
|
|
8185
8605
|
reject(new Error(`Path not found: ${targetPath}`));
|
|
8186
8606
|
return;
|
|
8187
8607
|
}
|
|
8188
8608
|
let entries;
|
|
8189
8609
|
let directoryLimitReached = false;
|
|
8190
8610
|
try {
|
|
8191
|
-
const directoryRead = await
|
|
8611
|
+
const directoryRead = await fs10.readDirectoryBounded(targetPath, MAX_RESULT_LIMIT, signal);
|
|
8192
8612
|
entries = directoryRead.entries;
|
|
8193
8613
|
directoryLimitReached = directoryRead.limitReached;
|
|
8194
8614
|
} catch (e) {
|
|
@@ -8212,13 +8632,13 @@ function createLsTool(cwd, options) {
|
|
|
8212
8632
|
entryLimitReached = true;
|
|
8213
8633
|
break;
|
|
8214
8634
|
}
|
|
8215
|
-
const fullPath =
|
|
8635
|
+
const fullPath = fs10.join(targetPath, entry);
|
|
8216
8636
|
let suffix = "";
|
|
8217
8637
|
try {
|
|
8218
|
-
const linkStat =
|
|
8638
|
+
const linkStat = fs10.lstatSync?.(fullPath);
|
|
8219
8639
|
if (linkStat?.isSymbolicLink) {
|
|
8220
8640
|
suffix = "@";
|
|
8221
|
-
} else if ((linkStat ?? await
|
|
8641
|
+
} else if ((linkStat ?? await fs10.stat(fullPath)).isDirectory) {
|
|
8222
8642
|
suffix = "/";
|
|
8223
8643
|
}
|
|
8224
8644
|
} catch {
|
|
@@ -8231,7 +8651,7 @@ function createLsTool(cwd, options) {
|
|
|
8231
8651
|
if (results.length === 0) {
|
|
8232
8652
|
const listingIncomplete = skippedEntry || entryLimitReached;
|
|
8233
8653
|
const emptyText = listingIncomplete ? "(no entries could be listed)\n\n[Listing incomplete: some directory entries could not be inspected. Retry or inspect a narrower path]" : "(empty directory)";
|
|
8234
|
-
|
|
8654
|
+
resolve7({
|
|
8235
8655
|
content: [{ type: "text", text: emptyText }],
|
|
8236
8656
|
details: listingIncomplete ? {
|
|
8237
8657
|
listingIncomplete: true,
|
|
@@ -8262,7 +8682,7 @@ function createLsTool(cwd, options) {
|
|
|
8262
8682
|
|
|
8263
8683
|
[${notices.join(". ")}]`;
|
|
8264
8684
|
}
|
|
8265
|
-
|
|
8685
|
+
resolve7({
|
|
8266
8686
|
content: [{ type: "text", text: output }],
|
|
8267
8687
|
details: Object.keys(details).length > 0 ? details : void 0
|
|
8268
8688
|
});
|
|
@@ -8344,17 +8764,17 @@ function parseGitignore(content) {
|
|
|
8344
8764
|
function createEmptyGitignoreMatcher(incomplete = false) {
|
|
8345
8765
|
return Object.assign((_relativePath, _isDirectory) => false, { incomplete, hasRules: false });
|
|
8346
8766
|
}
|
|
8347
|
-
async function loadGitignoreMatcher(rootPath,
|
|
8767
|
+
async function loadGitignoreMatcher(rootPath, fs10, options) {
|
|
8348
8768
|
let rules = [];
|
|
8349
8769
|
let incomplete = false;
|
|
8350
|
-
const filepath =
|
|
8770
|
+
const filepath = fs10.join(rootPath, ".gitignore");
|
|
8351
8771
|
try {
|
|
8352
8772
|
if (options?.signal?.aborted) throw new Error("Operation aborted");
|
|
8353
|
-
if (!await
|
|
8773
|
+
if (!await fs10.exists(filepath)) return createEmptyGitignoreMatcher();
|
|
8354
8774
|
options?.validatePath?.(filepath);
|
|
8355
|
-
const stat = await
|
|
8775
|
+
const stat = await fs10.stat(filepath);
|
|
8356
8776
|
if (!stat.isFile || stat.size > MAX_GITIGNORE_BYTES) return createEmptyGitignoreMatcher(true);
|
|
8357
|
-
const bytes = await
|
|
8777
|
+
const bytes = await fs10.readFilePrefix(filepath, MAX_GITIGNORE_BYTES + 1);
|
|
8358
8778
|
if (options?.signal?.aborted) throw new Error("Operation aborted");
|
|
8359
8779
|
if (bytes.byteLength > MAX_GITIGNORE_BYTES) return createEmptyGitignoreMatcher(true);
|
|
8360
8780
|
const parsed = parseGitignore(new TextDecoder().decode(bytes));
|
|
@@ -10438,8 +10858,8 @@ function waitForFileCompletion(requestId) {
|
|
|
10438
10858
|
if (existing) {
|
|
10439
10859
|
return Promise.resolve(existing);
|
|
10440
10860
|
}
|
|
10441
|
-
return new Promise((
|
|
10442
|
-
store.waiters.set(requestId,
|
|
10861
|
+
return new Promise((resolve7) => {
|
|
10862
|
+
store.waiters.set(requestId, resolve7);
|
|
10443
10863
|
});
|
|
10444
10864
|
}
|
|
10445
10865
|
async function runNativeGrep(searchPath, pattern, globPattern, ignoreCase, literal, contextLines, limit, outputMode, offset, signal) {
|
|
@@ -10557,7 +10977,7 @@ function sortFileSummariesByMtime(files) {
|
|
|
10557
10977
|
return left.relativePath.localeCompare(right.relativePath);
|
|
10558
10978
|
});
|
|
10559
10979
|
}
|
|
10560
|
-
async function collectFilesForGrep(dirPath, globPattern,
|
|
10980
|
+
async function collectFilesForGrep(dirPath, globPattern, fs10, isGitignored = createEmptyGitignoreMatcher(), assertReadablePath = (path12) => path12, signal, fileGlobMatcher) {
|
|
10561
10981
|
const matchesGlob = globPattern === void 0 ? void 0 : fileGlobMatcher ?? createGrepGlobMatcher(globPattern);
|
|
10562
10982
|
const files = [];
|
|
10563
10983
|
const queue = [{ dir: dirPath, relPrefix: "" }];
|
|
@@ -10572,7 +10992,7 @@ async function collectFilesForGrep(dirPath, globPattern, fs9, isGitignored = cre
|
|
|
10572
10992
|
if (signal?.aborted) throw new Error("Operation aborted");
|
|
10573
10993
|
const { dir: requestedDir, relPrefix } = queue.pop();
|
|
10574
10994
|
const dir = assertReadablePath(requestedDir);
|
|
10575
|
-
const canonicalDir =
|
|
10995
|
+
const canonicalDir = fs10.realpathSync ? fs10.normalize(fs10.realpathSync(dir)) : fs10.normalize(dir);
|
|
10576
10996
|
if (visitedDirectories.has(canonicalDir)) continue;
|
|
10577
10997
|
visitedDirectories.add(canonicalDir);
|
|
10578
10998
|
if (++scannedDirectories > maxScannedDirectories) {
|
|
@@ -10583,7 +11003,7 @@ async function collectFilesForGrep(dirPath, globPattern, fs9, isGitignored = cre
|
|
|
10583
11003
|
}
|
|
10584
11004
|
let entries;
|
|
10585
11005
|
try {
|
|
10586
|
-
const directoryRead = await
|
|
11006
|
+
const directoryRead = await fs10.readDirectoryBounded(dir, maxDirectoryEntries, signal);
|
|
10587
11007
|
entries = directoryRead.entries.slice().sort((left, right) => left.localeCompare(right));
|
|
10588
11008
|
if (directoryRead.limitReached) {
|
|
10589
11009
|
incomplete = true;
|
|
@@ -10596,12 +11016,12 @@ async function collectFilesForGrep(dirPath, globPattern, fs9, isGitignored = cre
|
|
|
10596
11016
|
}
|
|
10597
11017
|
for (const entry of entries) {
|
|
10598
11018
|
if (signal?.aborted) throw new Error("Operation aborted");
|
|
10599
|
-
const requestedPath =
|
|
11019
|
+
const requestedPath = fs10.join(dir, entry);
|
|
10600
11020
|
const fullPath = assertReadablePath(requestedPath);
|
|
10601
11021
|
const relPath = relPrefix ? `${relPrefix}/${entry}` : entry;
|
|
10602
11022
|
let stat;
|
|
10603
11023
|
try {
|
|
10604
|
-
stat = await
|
|
11024
|
+
stat = await fs10.stat(fullPath);
|
|
10605
11025
|
} catch {
|
|
10606
11026
|
incomplete = true;
|
|
10607
11027
|
continue;
|
|
@@ -10616,7 +11036,7 @@ async function collectFilesForGrep(dirPath, globPattern, fs9, isGitignored = cre
|
|
|
10616
11036
|
}
|
|
10617
11037
|
} else if (stat.isFile) {
|
|
10618
11038
|
if (isGitignored(relPath, false)) continue;
|
|
10619
|
-
const ext2 =
|
|
11039
|
+
const ext2 = fs10.extname(entry).toLowerCase();
|
|
10620
11040
|
if (BINARY_EXTENSIONS.has(ext2)) continue;
|
|
10621
11041
|
if (matchesGlob && !matchesGlob(relPath)) continue;
|
|
10622
11042
|
files.push(fullPath);
|
|
@@ -10627,7 +11047,7 @@ async function collectFilesForGrep(dirPath, globPattern, fs9, isGitignored = cre
|
|
|
10627
11047
|
return { files, truncated: traversalTruncated, incomplete, ...safetyLimit ? { safetyLimit } : {} };
|
|
10628
11048
|
}
|
|
10629
11049
|
function createGrepTextTool(cwd, options) {
|
|
10630
|
-
const
|
|
11050
|
+
const fs10 = getFileSystem();
|
|
10631
11051
|
const platform = detectPlatform();
|
|
10632
11052
|
const rootSchema = buildRootParameterSchema(cwd, options);
|
|
10633
11053
|
const grepSchema = Type.Object({
|
|
@@ -10680,7 +11100,7 @@ function createGrepTextTool(cwd, options) {
|
|
|
10680
11100
|
isError: true
|
|
10681
11101
|
};
|
|
10682
11102
|
}
|
|
10683
|
-
return new Promise((
|
|
11103
|
+
return new Promise((resolve7, reject) => {
|
|
10684
11104
|
if (signal?.aborted) {
|
|
10685
11105
|
reject(new Error("Operation aborted"));
|
|
10686
11106
|
return;
|
|
@@ -10698,10 +11118,10 @@ function createGrepTextTool(cwd, options) {
|
|
|
10698
11118
|
const ctx = Math.min(normalizeNonNegativeInteger(contextLines, 0, "context"), MAX_GREP_CONTEXT_LINES);
|
|
10699
11119
|
let isDir;
|
|
10700
11120
|
try {
|
|
10701
|
-
const stat = await
|
|
11121
|
+
const stat = await fs10.stat(searchPath);
|
|
10702
11122
|
isDir = stat.isDirectory;
|
|
10703
11123
|
} catch {
|
|
10704
|
-
|
|
11124
|
+
resolve7({
|
|
10705
11125
|
content: [{ type: "text", text: `grep_text failed: Path not found: ${searchPath}
|
|
10706
11126
|
Check the path or search from the workspace root.` }],
|
|
10707
11127
|
details: { searchIncomplete: true, safetyLimit: "io_error" },
|
|
@@ -10709,7 +11129,7 @@ Check the path or search from the workspace root.` }],
|
|
|
10709
11129
|
});
|
|
10710
11130
|
return;
|
|
10711
11131
|
}
|
|
10712
|
-
const isGitignored = await loadGitignoreMatcher(searchPath,
|
|
11132
|
+
const isGitignored = await loadGitignoreMatcher(searchPath, fs10, {
|
|
10713
11133
|
signal,
|
|
10714
11134
|
validatePath: (candidate) => resolveToCwd(candidate, cwd, options, root)
|
|
10715
11135
|
});
|
|
@@ -10732,7 +11152,7 @@ Check the path or search from the workspace root.` }],
|
|
|
10732
11152
|
} else {
|
|
10733
11153
|
}
|
|
10734
11154
|
} catch (e) {
|
|
10735
|
-
|
|
11155
|
+
resolve7({
|
|
10736
11156
|
content: [{ type: "text", text: boundedErrorMessage("grep_text failed: invalid regex pattern", e, "Use literal=true for plain text, or simplify the regex.") }],
|
|
10737
11157
|
details: { searchIncomplete: true, safetyLimit: "io_error" },
|
|
10738
11158
|
isError: true
|
|
@@ -10785,7 +11205,7 @@ Check the path or search from the workspace root.` }],
|
|
|
10785
11205
|
const collection = await collectFilesForGrep(
|
|
10786
11206
|
searchPath,
|
|
10787
11207
|
globPattern,
|
|
10788
|
-
|
|
11208
|
+
fs10,
|
|
10789
11209
|
isGitignored,
|
|
10790
11210
|
(filePath) => resolveToCwd(filePath, cwd, options, root),
|
|
10791
11211
|
signal,
|
|
@@ -10809,7 +11229,7 @@ Check the path or search from the workspace root.` }],
|
|
|
10809
11229
|
let content;
|
|
10810
11230
|
let fileStatBefore;
|
|
10811
11231
|
try {
|
|
10812
|
-
fileStatBefore = await
|
|
11232
|
+
fileStatBefore = await fs10.stat(filePath);
|
|
10813
11233
|
if (textBytesScanned + fileStatBefore.size > MAX_TEXT_GREP_TOTAL_BYTES) {
|
|
10814
11234
|
skippedUnboundedFile = true;
|
|
10815
11235
|
safetyLimit = "total_bytes";
|
|
@@ -10821,7 +11241,7 @@ Check the path or search from the workspace root.` }],
|
|
|
10821
11241
|
safetyLimit ??= "file_size";
|
|
10822
11242
|
continue;
|
|
10823
11243
|
}
|
|
10824
|
-
const inspected = await
|
|
11244
|
+
const inspected = await fs10.readTextRange(filePath, {
|
|
10825
11245
|
offsetLine: 0,
|
|
10826
11246
|
maxOutputLines: MAX_TEXT_GREP_FILE_LINES,
|
|
10827
11247
|
maxOutputBytes: MAX_TEXT_GREP_FILE_BYTES
|
|
@@ -10849,7 +11269,7 @@ Check the path or search from the workspace root.` }],
|
|
|
10849
11269
|
continue;
|
|
10850
11270
|
}
|
|
10851
11271
|
const lines = content.replace(/\r\n/g, "\n").replace(/\r/g, "\n").split("\n");
|
|
10852
|
-
const relativePath = isDir ?
|
|
11272
|
+
const relativePath = isDir ? fs10.relative(searchPath, filePath) : fs10.basename(filePath);
|
|
10853
11273
|
filesScanned++;
|
|
10854
11274
|
let fileMatchCount = 0;
|
|
10855
11275
|
const pageMatchLines = [];
|
|
@@ -10878,7 +11298,7 @@ Check the path or search from the workspace root.` }],
|
|
|
10878
11298
|
contentOutputBudgetReached ||= formatted.outputBudgetReached;
|
|
10879
11299
|
}
|
|
10880
11300
|
if (fileMatchCount > 0) {
|
|
10881
|
-
const fileStat = fileStatBefore ?? await
|
|
11301
|
+
const fileStat = fileStatBefore ?? await fs10.stat(filePath);
|
|
10882
11302
|
fileSummaries.set(filePath, {
|
|
10883
11303
|
filePath,
|
|
10884
11304
|
relativePath,
|
|
@@ -10912,7 +11332,7 @@ Check the path or search from the workspace root.` }],
|
|
|
10912
11332
|
signal?.removeEventListener("abort", onAbort);
|
|
10913
11333
|
if (matchCount === 0) {
|
|
10914
11334
|
const incompleteNotice = skippedUnboundedFile ? "\n\n[Search incomplete: a filesystem safety limit was reached. Narrow the path or glob and search again]" : "";
|
|
10915
|
-
|
|
11335
|
+
resolve7({
|
|
10916
11336
|
content: [{ type: "text", text: `No matches found${incompleteNotice}` }],
|
|
10917
11337
|
details: {
|
|
10918
11338
|
noMatches: true,
|
|
@@ -10967,7 +11387,7 @@ Check the path or search from the workspace root.` }],
|
|
|
10967
11387
|
|
|
10968
11388
|
[${notices.join(". ")}]`;
|
|
10969
11389
|
}
|
|
10970
|
-
|
|
11390
|
+
resolve7({
|
|
10971
11391
|
content: [{ type: "text", text: output }],
|
|
10972
11392
|
details: Object.keys(details).length > 0 ? details : void 0
|
|
10973
11393
|
});
|
|
@@ -10977,7 +11397,7 @@ Check the path or search from the workspace root.` }],
|
|
|
10977
11397
|
reject(err);
|
|
10978
11398
|
return;
|
|
10979
11399
|
}
|
|
10980
|
-
|
|
11400
|
+
resolve7({
|
|
10981
11401
|
content: [{ type: "text", text: boundedErrorMessage("grep_text failed", err, "Check the path/pattern, use literal=true for plain text, or narrow the search.") }],
|
|
10982
11402
|
details: { searchIncomplete: true, safetyLimit: "io_error" },
|
|
10983
11403
|
isError: true
|
|
@@ -11054,8 +11474,8 @@ function waitForFileCompletion2(requestId) {
|
|
|
11054
11474
|
if (existing) {
|
|
11055
11475
|
return Promise.resolve(existing);
|
|
11056
11476
|
}
|
|
11057
|
-
return new Promise((
|
|
11058
|
-
store.waiters.set(requestId,
|
|
11477
|
+
return new Promise((resolve7) => {
|
|
11478
|
+
store.waiters.set(requestId, resolve7);
|
|
11059
11479
|
});
|
|
11060
11480
|
}
|
|
11061
11481
|
async function runNativeFind(searchPath, pattern, limit, signal) {
|
|
@@ -11087,7 +11507,7 @@ async function runNativeFind(searchPath, pattern, limit, signal) {
|
|
|
11087
11507
|
bridge.ReleaseRequest(requestId);
|
|
11088
11508
|
}
|
|
11089
11509
|
}
|
|
11090
|
-
async function globFiles(rootPath, matchesPattern,
|
|
11510
|
+
async function globFiles(rootPath, matchesPattern, fs10, limit, signal, isGitignored = createEmptyGitignoreMatcher(), validatePath = () => {
|
|
11091
11511
|
}, incompleteState = { value: false }) {
|
|
11092
11512
|
const results = [];
|
|
11093
11513
|
const queue = [{ dir: rootPath, relPrefix: "" }];
|
|
@@ -11100,7 +11520,7 @@ async function globFiles(rootPath, matchesPattern, fs9, limit, signal, isGitigno
|
|
|
11100
11520
|
}
|
|
11101
11521
|
const { dir, relPrefix } = queue.shift();
|
|
11102
11522
|
validatePath(dir);
|
|
11103
|
-
const canonicalDir =
|
|
11523
|
+
const canonicalDir = fs10.realpathSync ? fs10.normalize(fs10.realpathSync(dir)) : fs10.normalize(dir);
|
|
11104
11524
|
if (visitedDirectories.has(canonicalDir)) continue;
|
|
11105
11525
|
visitedDirectories.add(canonicalDir);
|
|
11106
11526
|
if (++scannedDirectories > MAX_SCANNED_DIRECTORIES) {
|
|
@@ -11109,7 +11529,7 @@ async function globFiles(rootPath, matchesPattern, fs9, limit, signal, isGitigno
|
|
|
11109
11529
|
}
|
|
11110
11530
|
let entries;
|
|
11111
11531
|
try {
|
|
11112
|
-
const directoryRead = await
|
|
11532
|
+
const directoryRead = await fs10.readDirectoryBounded(dir, MAX_DIRECTORY_ENTRIES, signal);
|
|
11113
11533
|
entries = directoryRead.entries;
|
|
11114
11534
|
if (directoryRead.limitReached) incompleteState.value = true;
|
|
11115
11535
|
} catch {
|
|
@@ -11119,12 +11539,12 @@ async function globFiles(rootPath, matchesPattern, fs9, limit, signal, isGitigno
|
|
|
11119
11539
|
for (const entry of entries) {
|
|
11120
11540
|
if (signal?.aborted) throw new Error("Operation aborted");
|
|
11121
11541
|
if (results.length >= limit) break;
|
|
11122
|
-
const fullPath =
|
|
11542
|
+
const fullPath = fs10.join(dir, entry);
|
|
11123
11543
|
const relPath = relPrefix ? relPrefix + "/" + entry : entry;
|
|
11124
11544
|
validatePath(fullPath);
|
|
11125
11545
|
let stat;
|
|
11126
11546
|
try {
|
|
11127
|
-
stat = await
|
|
11547
|
+
stat = await fs10.stat(fullPath);
|
|
11128
11548
|
} catch {
|
|
11129
11549
|
incompleteState.value = true;
|
|
11130
11550
|
continue;
|
|
@@ -11152,7 +11572,7 @@ async function globFiles(rootPath, matchesPattern, fs9, limit, signal, isGitigno
|
|
|
11152
11572
|
return results;
|
|
11153
11573
|
}
|
|
11154
11574
|
function createFindFilesTool(cwd, options) {
|
|
11155
|
-
const
|
|
11575
|
+
const fs10 = getFileSystem();
|
|
11156
11576
|
const platform = detectPlatform();
|
|
11157
11577
|
const rootSchema = buildRootParameterSchema(cwd, options);
|
|
11158
11578
|
const findSchema = Type.Object({
|
|
@@ -11182,7 +11602,7 @@ function createFindFilesTool(cwd, options) {
|
|
|
11182
11602
|
isError: true
|
|
11183
11603
|
};
|
|
11184
11604
|
}
|
|
11185
|
-
return new Promise((
|
|
11605
|
+
return new Promise((resolve7, reject) => {
|
|
11186
11606
|
if (signal?.aborted) {
|
|
11187
11607
|
reject(new Error("Operation aborted"));
|
|
11188
11608
|
return;
|
|
@@ -11196,14 +11616,14 @@ function createFindFilesTool(cwd, options) {
|
|
|
11196
11616
|
resolveToCwd(candidate, cwd, options, root);
|
|
11197
11617
|
};
|
|
11198
11618
|
const validateReturnedPath = (candidate) => {
|
|
11199
|
-
validateResultPath(
|
|
11619
|
+
validateResultPath(fs10.isAbsolute(candidate) ? candidate : fs10.join(searchPath, candidate));
|
|
11200
11620
|
};
|
|
11201
11621
|
const effectiveLimit = limit ?? DEFAULT_LIMIT3;
|
|
11202
11622
|
if (!Number.isInteger(effectiveLimit) || effectiveLimit < 1 || effectiveLimit > MAX_RESULT_LIMIT2) {
|
|
11203
11623
|
throw new Error(`Invalid find_files arguments: limit must be between 1 and ${MAX_RESULT_LIMIT2}.`);
|
|
11204
11624
|
}
|
|
11205
|
-
if (!await
|
|
11206
|
-
|
|
11625
|
+
if (!await fs10.exists(searchPath)) {
|
|
11626
|
+
resolve7({
|
|
11207
11627
|
content: [{ type: "text", text: `find_files failed: Path not found: ${searchPath}
|
|
11208
11628
|
Check the path or search from the workspace root.` }],
|
|
11209
11629
|
details: { searchIncomplete: true },
|
|
@@ -11214,7 +11634,7 @@ Check the path or search from the workspace root.` }],
|
|
|
11214
11634
|
let results;
|
|
11215
11635
|
let resultLimitReached = false;
|
|
11216
11636
|
const incompleteState = { value: false };
|
|
11217
|
-
const isGitignored = await loadGitignoreMatcher(searchPath,
|
|
11637
|
+
const isGitignored = await loadGitignoreMatcher(searchPath, fs10, { signal, validatePath: validateResultPath });
|
|
11218
11638
|
incompleteState.value ||= isGitignored.incomplete;
|
|
11219
11639
|
if (platform === "puerts" && getNativeFileBridge2() && !isGitignored.hasRules) {
|
|
11220
11640
|
const nativeResult = await runNativeFind(searchPath, pattern, effectiveLimit, signal);
|
|
@@ -11227,12 +11647,12 @@ Check the path or search from the workspace root.` }],
|
|
|
11227
11647
|
`[find_files] path=${searchPath} pattern=${pattern} matches=${results.length} dirs=${nativeResult.ScannedDirectories ?? 0} files=${nativeResult.ScannedFiles ?? 0}`
|
|
11228
11648
|
);
|
|
11229
11649
|
} else if (platform === "node") {
|
|
11230
|
-
const allResults = await globFiles(searchPath, matchesPattern,
|
|
11650
|
+
const allResults = await globFiles(searchPath, matchesPattern, fs10, effectiveLimit + 1, signal, isGitignored, validateResultPath, incompleteState);
|
|
11231
11651
|
incompleteState.value ||= isGitignored.incomplete;
|
|
11232
11652
|
resultLimitReached = allResults.length > effectiveLimit;
|
|
11233
11653
|
results = allResults.slice(0, effectiveLimit);
|
|
11234
11654
|
} else {
|
|
11235
|
-
const allResults = await globFiles(searchPath, matchesPattern,
|
|
11655
|
+
const allResults = await globFiles(searchPath, matchesPattern, fs10, effectiveLimit + 1, signal, isGitignored, validateResultPath, incompleteState);
|
|
11236
11656
|
incompleteState.value ||= isGitignored.incomplete;
|
|
11237
11657
|
resultLimitReached = allResults.length > effectiveLimit;
|
|
11238
11658
|
results = allResults.slice(0, effectiveLimit);
|
|
@@ -11240,7 +11660,7 @@ Check the path or search from the workspace root.` }],
|
|
|
11240
11660
|
signal?.removeEventListener("abort", onAbort);
|
|
11241
11661
|
if (results.length === 0) {
|
|
11242
11662
|
const incompleteNotice = incompleteState.value ? "\n\n[Search incomplete: a filesystem safety limit or I/O error prevented some paths from being inspected. Narrow the path or pattern and search again]" : "";
|
|
11243
|
-
|
|
11663
|
+
resolve7({
|
|
11244
11664
|
content: [{ type: "text", text: `No files found matching pattern${incompleteNotice}` }],
|
|
11245
11665
|
details: {
|
|
11246
11666
|
noMatches: true,
|
|
@@ -11269,7 +11689,7 @@ Check the path or search from the workspace root.` }],
|
|
|
11269
11689
|
if (notices.length > 0) {
|
|
11270
11690
|
resultOutput += "\n\n[" + notices.join(". ") + "]";
|
|
11271
11691
|
}
|
|
11272
|
-
|
|
11692
|
+
resolve7({
|
|
11273
11693
|
content: [{ type: "text", text: resultOutput }],
|
|
11274
11694
|
details: Object.keys(details).length > 0 ? details : void 0
|
|
11275
11695
|
});
|
|
@@ -11280,7 +11700,7 @@ Check the path or search from the workspace root.` }],
|
|
|
11280
11700
|
reject(e);
|
|
11281
11701
|
return;
|
|
11282
11702
|
}
|
|
11283
|
-
|
|
11703
|
+
resolve7({
|
|
11284
11704
|
content: [{ type: "text", text: boundedFindError(e) }],
|
|
11285
11705
|
details: { searchIncomplete: true },
|
|
11286
11706
|
isError: true
|
|
@@ -11854,8 +12274,8 @@ function isSearchPageSource(source) {
|
|
|
11854
12274
|
function isHomepageSource(source) {
|
|
11855
12275
|
const parsed = sourceHostAndPath(source);
|
|
11856
12276
|
if (!parsed) return false;
|
|
11857
|
-
const
|
|
11858
|
-
return
|
|
12277
|
+
const path12 = parsed.path.replace(/\/+$/, "");
|
|
12278
|
+
return path12 === "" || path12 === "/news" || path12 === "/sections/news";
|
|
11859
12279
|
}
|
|
11860
12280
|
function evaluateSearchQuality(search) {
|
|
11861
12281
|
const warnings = [];
|
|
@@ -11887,8 +12307,8 @@ async function runQueuedSearch(model, fn) {
|
|
|
11887
12307
|
const key = `${model.provider}/${model.id}`;
|
|
11888
12308
|
const previous = SEARCH_PROVIDER_QUEUE.get(key) ?? Promise.resolve();
|
|
11889
12309
|
let release;
|
|
11890
|
-
const next = new Promise((
|
|
11891
|
-
release =
|
|
12310
|
+
const next = new Promise((resolve7) => {
|
|
12311
|
+
release = resolve7;
|
|
11892
12312
|
});
|
|
11893
12313
|
const queued = previous.catch(() => void 0).then(() => next);
|
|
11894
12314
|
SEARCH_PROVIDER_QUEUE.set(key, queued);
|
|
@@ -12362,10 +12782,10 @@ function assistantText(message) {
|
|
|
12362
12782
|
async function withAbort(promise, signal) {
|
|
12363
12783
|
if (!signal) return promise;
|
|
12364
12784
|
if (signal.aborted) throw signal.reason ?? new Error("operation aborted");
|
|
12365
|
-
return await new Promise((
|
|
12785
|
+
return await new Promise((resolve7, reject) => {
|
|
12366
12786
|
const onAbort = () => reject(signal.reason ?? new Error("operation aborted"));
|
|
12367
12787
|
signal.addEventListener("abort", onAbort, { once: true });
|
|
12368
|
-
promise.then(
|
|
12788
|
+
promise.then(resolve7, reject).finally(() => signal.removeEventListener("abort", onAbort));
|
|
12369
12789
|
});
|
|
12370
12790
|
}
|
|
12371
12791
|
async function cancelResponseBody(response) {
|
|
@@ -12376,13 +12796,13 @@ async function cancelResponseBody(response) {
|
|
|
12376
12796
|
}
|
|
12377
12797
|
var DISCARD_BODY_GRACE_MS = 250;
|
|
12378
12798
|
async function discardResponseBody(response) {
|
|
12379
|
-
await new Promise((
|
|
12799
|
+
await new Promise((resolve7) => {
|
|
12380
12800
|
let settled = false;
|
|
12381
12801
|
const settle = () => {
|
|
12382
12802
|
if (settled) return;
|
|
12383
12803
|
settled = true;
|
|
12384
12804
|
clearTimeout(timer);
|
|
12385
|
-
|
|
12805
|
+
resolve7();
|
|
12386
12806
|
};
|
|
12387
12807
|
const timer = setTimeout(settle, DISCARD_BODY_GRACE_MS);
|
|
12388
12808
|
try {
|
|
@@ -12721,7 +13141,7 @@ function createSharedWebFetchTool(deps = {}) {
|
|
|
12721
13141
|
};
|
|
12722
13142
|
}
|
|
12723
13143
|
|
|
12724
|
-
// ../../packages/shared-headless-capabilities/src/web-research.ts
|
|
13144
|
+
// ../../packages/shared-headless-capabilities/src/web-research-helpers.ts
|
|
12725
13145
|
var webResearchSchema = Type.Object({
|
|
12726
13146
|
query: Type.Optional(Type.String({
|
|
12727
13147
|
minLength: 2,
|
|
@@ -13097,19 +13517,21 @@ async function runWithDeadline(operation, timeoutMs, message, parentSignal) {
|
|
|
13097
13517
|
const child = createChildSignal(parentSignal);
|
|
13098
13518
|
let timer;
|
|
13099
13519
|
try {
|
|
13100
|
-
return await new Promise((
|
|
13520
|
+
return await new Promise((resolve7, reject) => {
|
|
13101
13521
|
timer = setTimeout(() => {
|
|
13102
13522
|
const error = new Error(message);
|
|
13103
13523
|
child.abort(error);
|
|
13104
13524
|
reject(error);
|
|
13105
13525
|
}, timeoutMs);
|
|
13106
|
-
operation(child.signal).then(
|
|
13526
|
+
operation(child.signal).then(resolve7, reject);
|
|
13107
13527
|
});
|
|
13108
13528
|
} finally {
|
|
13109
13529
|
if (timer) clearTimeout(timer);
|
|
13110
13530
|
child.dispose();
|
|
13111
13531
|
}
|
|
13112
13532
|
}
|
|
13533
|
+
|
|
13534
|
+
// ../../packages/shared-headless-capabilities/src/web-research.ts
|
|
13113
13535
|
function createSharedWebResearchTool(deps) {
|
|
13114
13536
|
const initialHealth = deps.loadProviderHealth?.();
|
|
13115
13537
|
const initialCandidates = deps.resolveToolModelCandidates?.("web_search") ?? [];
|
|
@@ -13727,8 +14149,8 @@ function isWithinProject(fileSystem, projectRoot, candidate) {
|
|
|
13727
14149
|
try {
|
|
13728
14150
|
const canonicalRoot = fileSystem.realpath(projectRoot);
|
|
13729
14151
|
const canonicalCandidate = fileSystem.realpath(candidate);
|
|
13730
|
-
const
|
|
13731
|
-
return
|
|
14152
|
+
const relative4 = path3.relative(canonicalRoot, canonicalCandidate);
|
|
14153
|
+
return relative4 !== ".." && !relative4.startsWith(`..${path3.sep}`) && !path3.isAbsolute(relative4);
|
|
13732
14154
|
} catch {
|
|
13733
14155
|
return false;
|
|
13734
14156
|
}
|
|
@@ -17139,13 +17561,236 @@ function readMemoryFile(store, relativePath) {
|
|
|
17139
17561
|
}
|
|
17140
17562
|
}
|
|
17141
17563
|
|
|
17564
|
+
// ../../packages/shared-headless-capabilities/src/memory/wiki-inbox.ts
|
|
17565
|
+
import * as crypto2 from "node:crypto";
|
|
17566
|
+
import * as fs7 from "node:fs";
|
|
17567
|
+
import * as path9 from "node:path";
|
|
17568
|
+
var MAX_WIKI_INBOX_ITEMS = 200;
|
|
17569
|
+
var VALID_KINDS = /* @__PURE__ */ new Set(["fact", "project", "thread"]);
|
|
17570
|
+
var SAFE_ID_RE = /^[a-zA-Z0-9_-]{1,80}$/;
|
|
17571
|
+
function wikiInboxPath(memoryRoot) {
|
|
17572
|
+
return path9.join(memoryRoot, "inbox");
|
|
17573
|
+
}
|
|
17574
|
+
function spoolFileNameForId(id) {
|
|
17575
|
+
const safe = SAFE_ID_RE.test(id) ? id : crypto2.createHash("sha256").update(id).digest("hex").slice(0, 32);
|
|
17576
|
+
return `${safe}.json`;
|
|
17577
|
+
}
|
|
17578
|
+
function spoolFilePathForId(memoryRoot, id) {
|
|
17579
|
+
return path9.join(wikiInboxPath(memoryRoot), spoolFileNameForId(id));
|
|
17580
|
+
}
|
|
17581
|
+
function assertSafeMemoryPath(memoryRoot, targetPath) {
|
|
17582
|
+
const rootAbs = path9.resolve(memoryRoot);
|
|
17583
|
+
const targetAbs = path9.resolve(targetPath);
|
|
17584
|
+
const rel = path9.relative(rootAbs, targetAbs);
|
|
17585
|
+
if (rel.startsWith("..") || path9.isAbsolute(rel)) {
|
|
17586
|
+
throw new Error(`Wiki inbox path escapes memory root: ${targetPath}`);
|
|
17587
|
+
}
|
|
17588
|
+
if (fs7.existsSync(rootAbs) && fs7.lstatSync(rootAbs).isSymbolicLink()) {
|
|
17589
|
+
throw new Error(`Memory root must not be a symlink: ${rootAbs}`);
|
|
17590
|
+
}
|
|
17591
|
+
const rootReal = fs7.existsSync(rootAbs) ? fs7.realpathSync(rootAbs) : rootAbs;
|
|
17592
|
+
const parts = rel.split(path9.sep).filter(Boolean);
|
|
17593
|
+
let cursor = rootAbs;
|
|
17594
|
+
for (const part of parts) {
|
|
17595
|
+
cursor = path9.join(cursor, part);
|
|
17596
|
+
if (!fs7.existsSync(cursor)) continue;
|
|
17597
|
+
const st = fs7.lstatSync(cursor);
|
|
17598
|
+
if (st.isSymbolicLink()) {
|
|
17599
|
+
throw new Error(`Refusing to traverse symlink in wiki inbox: ${cursor}`);
|
|
17600
|
+
}
|
|
17601
|
+
const real = fs7.realpathSync(cursor);
|
|
17602
|
+
const realRel = path9.relative(rootReal, real);
|
|
17603
|
+
if (realRel.startsWith("..") || path9.isAbsolute(realRel)) {
|
|
17604
|
+
throw new Error(`Wiki inbox realpath escapes memory root: ${cursor}`);
|
|
17605
|
+
}
|
|
17606
|
+
}
|
|
17607
|
+
}
|
|
17608
|
+
function writeFileAtomic(memoryRoot, targetPath, content) {
|
|
17609
|
+
assertSafeMemoryPath(memoryRoot, targetPath);
|
|
17610
|
+
const dir = path9.dirname(targetPath);
|
|
17611
|
+
fs7.mkdirSync(dir, { recursive: true, mode: 448 });
|
|
17612
|
+
assertSafeMemoryPath(memoryRoot, dir);
|
|
17613
|
+
const tmp = path9.join(dir, `.item.${process.pid}.${crypto2.randomBytes(6).toString("hex")}.tmp`);
|
|
17614
|
+
const flags = fs7.constants.O_WRONLY | fs7.constants.O_CREAT | fs7.constants.O_EXCL;
|
|
17615
|
+
const fd = fs7.openSync(tmp, flags, 384);
|
|
17616
|
+
try {
|
|
17617
|
+
fs7.writeFileSync(fd, content, "utf8");
|
|
17618
|
+
fs7.fsyncSync(fd);
|
|
17619
|
+
} catch (error) {
|
|
17620
|
+
try {
|
|
17621
|
+
fs7.closeSync(fd);
|
|
17622
|
+
} catch {
|
|
17623
|
+
}
|
|
17624
|
+
try {
|
|
17625
|
+
fs7.unlinkSync(tmp);
|
|
17626
|
+
} catch {
|
|
17627
|
+
}
|
|
17628
|
+
throw error;
|
|
17629
|
+
}
|
|
17630
|
+
fs7.closeSync(fd);
|
|
17631
|
+
try {
|
|
17632
|
+
fs7.renameSync(tmp, targetPath);
|
|
17633
|
+
} catch (error) {
|
|
17634
|
+
try {
|
|
17635
|
+
fs7.unlinkSync(tmp);
|
|
17636
|
+
} catch {
|
|
17637
|
+
}
|
|
17638
|
+
throw error;
|
|
17639
|
+
}
|
|
17640
|
+
}
|
|
17641
|
+
function normalizeInboxItem(raw) {
|
|
17642
|
+
if (!raw || typeof raw !== "object" || Array.isArray(raw)) return null;
|
|
17643
|
+
const obj = raw;
|
|
17644
|
+
const id = typeof obj.id === "string" ? redactText(obj.id).text.trim().slice(0, 80) : "";
|
|
17645
|
+
const kind = typeof obj.kind === "string" && VALID_KINDS.has(obj.kind) ? obj.kind : null;
|
|
17646
|
+
const text = typeof obj.text === "string" ? redactText(obj.text).text.replace(/\s+/g, " ").trim().slice(0, 400) : "";
|
|
17647
|
+
const quote = typeof obj.quote === "string" ? redactText(obj.quote).text.replace(/\s+/g, " ").trim().slice(0, 400) : "";
|
|
17648
|
+
const sessionId = typeof obj.sessionId === "string" && obj.sessionId.trim() ? redactText(obj.sessionId).text.trim().slice(0, 80) : "session-unbound";
|
|
17649
|
+
const date = typeof obj.date === "string" && /^\d{4}-\d{2}-\d{2}$/.test(obj.date.trim()) ? obj.date.trim() : "";
|
|
17650
|
+
const createdAt = typeof obj.createdAt === "number" && Number.isFinite(obj.createdAt) ? obj.createdAt : Date.now();
|
|
17651
|
+
if (!id || !kind || !text || !quote || !date) return null;
|
|
17652
|
+
const projectKey = typeof obj.projectKey === "string" && obj.projectKey.trim() ? redactText(obj.projectKey).text.trim().slice(0, 128) : void 0;
|
|
17653
|
+
const cwd = typeof obj.cwd === "string" && obj.cwd.trim() ? redactText(obj.cwd).text.trim().slice(0, 512) : void 0;
|
|
17654
|
+
return {
|
|
17655
|
+
id,
|
|
17656
|
+
kind,
|
|
17657
|
+
text,
|
|
17658
|
+
quote,
|
|
17659
|
+
sessionId,
|
|
17660
|
+
date,
|
|
17661
|
+
...projectKey ? { projectKey } : {},
|
|
17662
|
+
...cwd ? { cwd } : {},
|
|
17663
|
+
createdAt
|
|
17664
|
+
};
|
|
17665
|
+
}
|
|
17666
|
+
function dedupeKey(item) {
|
|
17667
|
+
return `${item.kind}\0${item.text}\0${item.projectKey ?? ""}\0${item.cwd ?? ""}`;
|
|
17668
|
+
}
|
|
17669
|
+
function readWikiInbox(memoryRoot) {
|
|
17670
|
+
const dir = wikiInboxPath(memoryRoot);
|
|
17671
|
+
assertSafeMemoryPath(memoryRoot, dir);
|
|
17672
|
+
if (!fs7.existsSync(dir)) return [];
|
|
17673
|
+
let entries;
|
|
17674
|
+
try {
|
|
17675
|
+
entries = fs7.readdirSync(dir);
|
|
17676
|
+
} catch {
|
|
17677
|
+
return [];
|
|
17678
|
+
}
|
|
17679
|
+
const items = [];
|
|
17680
|
+
const seenIds = /* @__PURE__ */ new Set();
|
|
17681
|
+
for (const entry of entries) {
|
|
17682
|
+
if (!entry.endsWith(".json") || entry.startsWith(".")) continue;
|
|
17683
|
+
const fullPath = path9.join(dir, entry);
|
|
17684
|
+
assertSafeMemoryPath(memoryRoot, fullPath);
|
|
17685
|
+
try {
|
|
17686
|
+
const parsed = normalizeInboxItem(JSON.parse(fs7.readFileSync(fullPath, "utf8")));
|
|
17687
|
+
if (!parsed || seenIds.has(parsed.id)) continue;
|
|
17688
|
+
seenIds.add(parsed.id);
|
|
17689
|
+
items.push(parsed);
|
|
17690
|
+
} catch {
|
|
17691
|
+
}
|
|
17692
|
+
}
|
|
17693
|
+
items.sort((a, b) => a.createdAt - b.createdAt || a.id.localeCompare(b.id));
|
|
17694
|
+
return items;
|
|
17695
|
+
}
|
|
17696
|
+
function countWikiInbox(memoryRoot) {
|
|
17697
|
+
try {
|
|
17698
|
+
return readWikiInbox(memoryRoot).length;
|
|
17699
|
+
} catch {
|
|
17700
|
+
return 0;
|
|
17701
|
+
}
|
|
17702
|
+
}
|
|
17703
|
+
function appendWikiInboxItem(memoryRoot, input) {
|
|
17704
|
+
const item = normalizeInboxItem(input);
|
|
17705
|
+
if (!item) return false;
|
|
17706
|
+
const target = spoolFilePathForId(memoryRoot, item.id);
|
|
17707
|
+
writeFileAtomic(memoryRoot, target, JSON.stringify(item) + "\n");
|
|
17708
|
+
try {
|
|
17709
|
+
const existing = readWikiInbox(memoryRoot);
|
|
17710
|
+
const key = dedupeKey(item);
|
|
17711
|
+
const toRemove = [];
|
|
17712
|
+
for (const entry of existing) {
|
|
17713
|
+
if (entry.id !== item.id && dedupeKey(entry) === key) {
|
|
17714
|
+
toRemove.push(entry.id);
|
|
17715
|
+
}
|
|
17716
|
+
}
|
|
17717
|
+
const remaining = existing.filter((entry) => !toRemove.includes(entry.id));
|
|
17718
|
+
if (remaining.length > MAX_WIKI_INBOX_ITEMS) {
|
|
17719
|
+
const overflow = remaining.length - MAX_WIKI_INBOX_ITEMS;
|
|
17720
|
+
for (const old of remaining.slice(0, overflow)) {
|
|
17721
|
+
if (old.id !== item.id) toRemove.push(old.id);
|
|
17722
|
+
}
|
|
17723
|
+
}
|
|
17724
|
+
if (toRemove.length > 0) removeWikiInboxItems(memoryRoot, toRemove);
|
|
17725
|
+
} catch {
|
|
17726
|
+
}
|
|
17727
|
+
return true;
|
|
17728
|
+
}
|
|
17729
|
+
function removeWikiInboxItems(memoryRoot, ids) {
|
|
17730
|
+
const drop = ids instanceof Set ? ids : new Set(ids);
|
|
17731
|
+
if (drop.size === 0) return 0;
|
|
17732
|
+
const dir = wikiInboxPath(memoryRoot);
|
|
17733
|
+
assertSafeMemoryPath(memoryRoot, dir);
|
|
17734
|
+
if (!fs7.existsSync(dir)) return 0;
|
|
17735
|
+
let removed = 0;
|
|
17736
|
+
for (const id of drop) {
|
|
17737
|
+
const target = spoolFilePathForId(memoryRoot, id);
|
|
17738
|
+
assertSafeMemoryPath(memoryRoot, target);
|
|
17739
|
+
try {
|
|
17740
|
+
fs7.unlinkSync(target);
|
|
17741
|
+
removed += 1;
|
|
17742
|
+
} catch (error) {
|
|
17743
|
+
if (error.code !== "ENOENT") {
|
|
17744
|
+
throw error;
|
|
17745
|
+
}
|
|
17746
|
+
}
|
|
17747
|
+
}
|
|
17748
|
+
return removed;
|
|
17749
|
+
}
|
|
17750
|
+
function wikiInboxItemToDreamSignal(item, wikiStore) {
|
|
17751
|
+
const existingPage = wikiStore.findProjectPage(item.projectKey ? [item.projectKey] : void 0, item.cwd);
|
|
17752
|
+
const slugFromCwd = item.cwd ? slugifyWikiName(path9.basename(item.cwd)) : null;
|
|
17753
|
+
const projectSlug = existingPage ? path9.basename(existingPage.relPath, ".md") : slugFromCwd ?? void 0;
|
|
17754
|
+
if (item.kind === "project") {
|
|
17755
|
+
return {
|
|
17756
|
+
kind: "project-state",
|
|
17757
|
+
target: projectSlug ?? "ops",
|
|
17758
|
+
text: item.text,
|
|
17759
|
+
quote: item.quote,
|
|
17760
|
+
sessionId: item.sessionId,
|
|
17761
|
+
date: item.date,
|
|
17762
|
+
...item.projectKey ? { projectKey: item.projectKey } : {}
|
|
17763
|
+
};
|
|
17764
|
+
}
|
|
17765
|
+
if (item.kind === "thread") {
|
|
17766
|
+
return {
|
|
17767
|
+
kind: "open-thread",
|
|
17768
|
+
target: projectSlug ?? "threads",
|
|
17769
|
+
text: item.text,
|
|
17770
|
+
quote: item.quote,
|
|
17771
|
+
sessionId: item.sessionId,
|
|
17772
|
+
date: item.date,
|
|
17773
|
+
...item.projectKey ? { projectKey: item.projectKey } : {}
|
|
17774
|
+
};
|
|
17775
|
+
}
|
|
17776
|
+
return {
|
|
17777
|
+
kind: "ops-state",
|
|
17778
|
+
target: "ops",
|
|
17779
|
+
text: item.text,
|
|
17780
|
+
quote: item.quote,
|
|
17781
|
+
sessionId: item.sessionId,
|
|
17782
|
+
date: item.date,
|
|
17783
|
+
...item.projectKey ? { projectKey: item.projectKey } : {}
|
|
17784
|
+
};
|
|
17785
|
+
}
|
|
17786
|
+
|
|
17142
17787
|
// ../../packages/shared-headless-capabilities/src/memory/wiki-dream.ts
|
|
17143
|
-
import * as
|
|
17144
|
-
import * as
|
|
17788
|
+
import * as fs9 from "node:fs";
|
|
17789
|
+
import * as path11 from "node:path";
|
|
17145
17790
|
|
|
17146
17791
|
// ../../packages/shared-headless-capabilities/src/memory/wiki-dream-gc.ts
|
|
17147
|
-
import * as
|
|
17148
|
-
import * as
|
|
17792
|
+
import * as fs8 from "node:fs";
|
|
17793
|
+
import * as path10 from "node:path";
|
|
17149
17794
|
function extractJsonObject(raw) {
|
|
17150
17795
|
const start = raw.indexOf("{");
|
|
17151
17796
|
const end = raw.lastIndexOf("}");
|
|
@@ -17242,13 +17887,13 @@ async function runWikiGc(deps) {
|
|
|
17242
17887
|
let effectiveTs = updatedTs;
|
|
17243
17888
|
if (!Number.isFinite(effectiveTs)) {
|
|
17244
17889
|
try {
|
|
17245
|
-
effectiveTs =
|
|
17890
|
+
effectiveTs = fs8.statSync(wikiStore.resolvePath(relPath)).mtimeMs;
|
|
17246
17891
|
} catch {
|
|
17247
17892
|
effectiveTs = now;
|
|
17248
17893
|
}
|
|
17249
17894
|
}
|
|
17250
17895
|
if (effectiveTs < cutoffMs) {
|
|
17251
|
-
const slug =
|
|
17896
|
+
const slug = path10.basename(relPath, ".md");
|
|
17252
17897
|
if (wikiStore.archiveProjectPage(slug)) {
|
|
17253
17898
|
archivedInactive.push(slug);
|
|
17254
17899
|
summaries.push(`archived inactive project ${slug} (last updated ${dayOf(effectiveTs)})`);
|
|
@@ -17486,45 +18131,45 @@ async function validateOrRepairUpdates(updates, call, limits, options = {}) {
|
|
|
17486
18131
|
function readLegacyContextForBootstrap(memoryRoot) {
|
|
17487
18132
|
const safeRead = (p, maxChars) => {
|
|
17488
18133
|
try {
|
|
17489
|
-
const raw =
|
|
18134
|
+
const raw = fs9.readFileSync(p, "utf8");
|
|
17490
18135
|
return redactText(raw).text.slice(0, maxChars);
|
|
17491
18136
|
} catch {
|
|
17492
18137
|
return "";
|
|
17493
18138
|
}
|
|
17494
18139
|
};
|
|
17495
|
-
const memoryMd = safeRead(
|
|
17496
|
-
const threadsMd = safeRead(
|
|
17497
|
-
const userMd = safeRead(
|
|
18140
|
+
const memoryMd = safeRead(path11.join(memoryRoot, "MEMORY.md"), 18e3);
|
|
18141
|
+
const threadsMd = safeRead(path11.join(memoryRoot, "THREADS.md"), 6e3);
|
|
18142
|
+
const userMd = safeRead(path11.join(memoryRoot, "USER.md"), 3e3);
|
|
17498
18143
|
const projects = [];
|
|
17499
|
-
const projectsRoot =
|
|
17500
|
-
if (
|
|
17501
|
-
for (const key of
|
|
17502
|
-
const dir =
|
|
18144
|
+
const projectsRoot = path11.join(memoryRoot, "projects");
|
|
18145
|
+
if (fs9.existsSync(projectsRoot)) {
|
|
18146
|
+
for (const key of fs9.readdirSync(projectsRoot).sort()) {
|
|
18147
|
+
const dir = path11.join(projectsRoot, key);
|
|
17503
18148
|
try {
|
|
17504
|
-
if (!
|
|
18149
|
+
if (!fs9.statSync(dir).isDirectory()) continue;
|
|
17505
18150
|
} catch {
|
|
17506
18151
|
continue;
|
|
17507
18152
|
}
|
|
17508
|
-
const content = safeRead(
|
|
18153
|
+
const content = safeRead(path11.join(dir, "MEMORY.md"), 3500);
|
|
17509
18154
|
let meta = {};
|
|
17510
18155
|
try {
|
|
17511
|
-
meta = JSON.parse(
|
|
18156
|
+
meta = JSON.parse(fs9.readFileSync(path11.join(dir, "meta.json"), "utf8"));
|
|
17512
18157
|
} catch {
|
|
17513
18158
|
}
|
|
17514
18159
|
const safeReadableName = typeof meta.readableName === "string" ? redactText(meta.readableName).text : void 0;
|
|
17515
18160
|
const safePath = typeof meta.path === "string" ? redactText(meta.path).text : void 0;
|
|
17516
18161
|
const safeGitUrl = typeof meta.gitUrl === "string" ? redactText(meta.gitUrl).text : void 0;
|
|
17517
18162
|
if (!content.trim() && !safeReadableName && !safePath) continue;
|
|
17518
|
-
const slug = slugifyWikiName(safeReadableName || (safePath ?
|
|
18163
|
+
const slug = slugifyWikiName(safeReadableName || (safePath ? path11.basename(safePath) : key.slice(0, 12)));
|
|
17519
18164
|
projects.push({ key, slug, readableName: safeReadableName, path: safePath, gitUrl: safeGitUrl, content });
|
|
17520
18165
|
}
|
|
17521
18166
|
}
|
|
17522
18167
|
const recentJournals = [];
|
|
17523
|
-
const journalDir =
|
|
17524
|
-
if (
|
|
17525
|
-
const files =
|
|
18168
|
+
const journalDir = path11.join(memoryRoot, "journal");
|
|
18169
|
+
if (fs9.existsSync(journalDir)) {
|
|
18170
|
+
const files = fs9.readdirSync(journalDir).filter((f) => /^\d{4}-\d{2}-\d{2}\.md$/.test(f)).sort().slice(-3);
|
|
17526
18171
|
for (const file of files) {
|
|
17527
|
-
const content = safeRead(
|
|
18172
|
+
const content = safeRead(path11.join(journalDir, file), 1500);
|
|
17528
18173
|
if (content.trim()) recentJournals.push({ date: file.slice(0, -3), content });
|
|
17529
18174
|
}
|
|
17530
18175
|
}
|
|
@@ -17652,7 +18297,8 @@ async function runWikiDream(deps) {
|
|
|
17652
18297
|
log(`[wiki-dream] harvest failed for ${date}: ${String(error)}`);
|
|
17653
18298
|
}
|
|
17654
18299
|
}
|
|
17655
|
-
|
|
18300
|
+
const inboxItems = readWikiInbox(deps.memoryRoot);
|
|
18301
|
+
if (sessions.length === 0 && inboxItems.length === 0) {
|
|
17656
18302
|
const completeDates = deps.dates.filter((d) => !harvestFailedDates.has(d));
|
|
17657
18303
|
if (completeDates.length > 0) wikiStore.recordDreamedDates(completeDates, now);
|
|
17658
18304
|
if (harvestFailedDates.size > 0) {
|
|
@@ -17685,12 +18331,17 @@ async function runWikiDream(deps) {
|
|
|
17685
18331
|
for (const session of sessions) {
|
|
17686
18332
|
const proj = session.cwd ? projectKeyForDir(session.cwd) : void 0;
|
|
17687
18333
|
const existingPage = wikiStore.findProjectPage(proj ? [proj.key] : void 0, session.cwd);
|
|
17688
|
-
const slugHint = existingPage ?
|
|
18334
|
+
const slugHint = existingPage ? path11.basename(existingPage.relPath, ".md") : session.cwd ? slugifyWikiName(path11.basename(session.cwd)) : "ops";
|
|
17689
18335
|
try {
|
|
17690
|
-
const
|
|
18336
|
+
const cacheKey = `${session.date}:${session.sessionId}`;
|
|
18337
|
+
const cached = deps.extractedSignalsCache?.get(cacheKey);
|
|
18338
|
+
const signals = cached ?? await extractDreamSignalsForSession(session, deps.lightCall, {
|
|
17691
18339
|
slug: slugHint,
|
|
17692
18340
|
projectKey: proj?.key
|
|
17693
18341
|
});
|
|
18342
|
+
if (!cached && deps.extractedSignalsCache) {
|
|
18343
|
+
deps.extractedSignalsCache.set(cacheKey, signals);
|
|
18344
|
+
}
|
|
17694
18345
|
signalsBySession.push({ date: session.date, sessionId: session.sessionId, signals: signals.slice(0, MAX_DREAM_SIGNALS) });
|
|
17695
18346
|
const list = succeededByDate.get(session.date) ?? [];
|
|
17696
18347
|
list.push(session.sessionId);
|
|
@@ -17780,13 +18431,27 @@ async function runWikiDream(deps) {
|
|
|
17780
18431
|
deferredSessionCount += 1;
|
|
17781
18432
|
}
|
|
17782
18433
|
}
|
|
17783
|
-
const
|
|
18434
|
+
const packedInboxIds = [];
|
|
18435
|
+
let deferredInboxCount = 0;
|
|
18436
|
+
for (const inboxItem of inboxItems) {
|
|
18437
|
+
const signal = wikiInboxItemToDreamSignal(inboxItem, wikiStore);
|
|
18438
|
+
const pages = targetPagesForSignal(signal);
|
|
18439
|
+
const unionPages = /* @__PURE__ */ new Set([...batchTargetPages, ...pages]);
|
|
18440
|
+
if (batchSignals.length + 1 <= MAX_DREAM_SIGNALS && (unionPages.size <= maxTargetPages || batchSignals.length === 0)) {
|
|
18441
|
+
batchSignals.push(signal);
|
|
18442
|
+
for (const p of pages) batchTargetPages.add(p);
|
|
18443
|
+
packedInboxIds.push(inboxItem.id);
|
|
18444
|
+
} else {
|
|
18445
|
+
deferredInboxCount += 1;
|
|
18446
|
+
}
|
|
18447
|
+
}
|
|
18448
|
+
const totalSignalsCount = signalsBySession.reduce((sum, s) => sum + s.signals.length, 0) + inboxItems.length;
|
|
17784
18449
|
const persistPartialAndCompleteDates = (updatesOverflowed) => {
|
|
17785
18450
|
const completeDates = [];
|
|
17786
18451
|
for (const date of deps.dates) {
|
|
17787
18452
|
const hasHarvestFail = harvestFailedDates.has(date);
|
|
17788
18453
|
const hasExtractFail = (failedByDate.get(date)?.length ?? 0) > 0;
|
|
17789
|
-
const hasDeferred = (deferredSessionsByDate.get(date)?.length ?? 0) > 0;
|
|
18454
|
+
const hasDeferred = (deferredSessionsByDate.get(date)?.length ?? 0) > 0 || deferredInboxCount > 0;
|
|
17790
18455
|
if (!hasHarvestFail && !hasExtractFail && !hasDeferred && !updatesOverflowed) {
|
|
17791
18456
|
completeDates.push(date);
|
|
17792
18457
|
} else if (!updatesOverflowed) {
|
|
@@ -17800,6 +18465,9 @@ async function runWikiDream(deps) {
|
|
|
17800
18465
|
}
|
|
17801
18466
|
}
|
|
17802
18467
|
if (completeDates.length > 0) wikiStore.recordDreamedDates(completeDates, now);
|
|
18468
|
+
if (!updatesOverflowed && packedInboxIds.length > 0) {
|
|
18469
|
+
removeWikiInboxItems(deps.memoryRoot, packedInboxIds);
|
|
18470
|
+
}
|
|
17803
18471
|
};
|
|
17804
18472
|
const formatPartialError = (updatesOverflowed) => {
|
|
17805
18473
|
const parts = [];
|
|
@@ -17810,13 +18478,17 @@ async function runWikiDream(deps) {
|
|
|
17810
18478
|
if (harvestFailedDates.size > 0) {
|
|
17811
18479
|
parts.push(`harvest failed for date(s): ${[...harvestFailedDates].join(", ")}`);
|
|
17812
18480
|
}
|
|
17813
|
-
if (deferredSessionCount > 0 || updatesOverflowed) {
|
|
17814
|
-
|
|
18481
|
+
if (deferredSessionCount > 0 || deferredInboxCount > 0 || updatesOverflowed) {
|
|
18482
|
+
const deferredSummary = [
|
|
18483
|
+
...deferredSessionCount > 0 ? [`${deferredSessionCount} session(s)`] : [],
|
|
18484
|
+
...deferredInboxCount > 0 ? [`${deferredInboxCount} inbox item(s)`] : []
|
|
18485
|
+
].join(" + ") || "0 session(s)";
|
|
18486
|
+
parts.push(`wiki dream batch overflow: ${deferredSummary} deferred${updatesOverflowed ? " (page budget reached)" : ""}`);
|
|
17815
18487
|
}
|
|
17816
18488
|
return parts.join("; ");
|
|
17817
18489
|
};
|
|
17818
18490
|
if (batchSignals.length === 0) {
|
|
17819
|
-
if (allFailedSessions.length === sessions.length) {
|
|
18491
|
+
if (sessions.length > 0 && allFailedSessions.length === sessions.length) {
|
|
17820
18492
|
const lastError = allFailedSessions[allFailedSessions.length - 1]?.error ?? "unknown";
|
|
17821
18493
|
return {
|
|
17822
18494
|
ok: false,
|
|
@@ -17896,7 +18568,8 @@ ${p.content}`).join("\n\n") || "(none yet)"
|
|
|
17896
18568
|
const updatesOverflowed = allNonIndex.length > limits.maxPagesPerDream || parsed.archiveSlugs.length > remainingBudget;
|
|
17897
18569
|
if (filtered.length === 0 && archiveCandidates.length === 0) {
|
|
17898
18570
|
persistPartialAndCompleteDates(updatesOverflowed);
|
|
17899
|
-
const hasIncomplete2 = allFailedSessions.length > 0 || harvestFailedDates.size > 0 || deferredSessionCount > 0 || updatesOverflowed;
|
|
18571
|
+
const hasIncomplete2 = allFailedSessions.length > 0 || harvestFailedDates.size > 0 || deferredSessionCount > 0 || deferredInboxCount > 0 || updatesOverflowed;
|
|
18572
|
+
const mergedCount2 = !updatesOverflowed ? packedInboxIds.length : 0;
|
|
17900
18573
|
return {
|
|
17901
18574
|
ok: !hasIncomplete2,
|
|
17902
18575
|
dates: [...deps.dates],
|
|
@@ -17905,6 +18578,7 @@ ${p.content}`).join("\n\n") || "(none yet)"
|
|
|
17905
18578
|
written: [],
|
|
17906
18579
|
archived: [],
|
|
17907
18580
|
summaries: ["wiki already up to date"],
|
|
18581
|
+
...mergedCount2 > 0 ? { inboxMerged: mergedCount2 } : {},
|
|
17908
18582
|
...allFailedSessions.length > 0 ? { failedSessions: allFailedSessions } : {},
|
|
17909
18583
|
...hasIncomplete2 ? { error: formatPartialError(updatesOverflowed) } : {}
|
|
17910
18584
|
};
|
|
@@ -17964,7 +18638,8 @@ ${p.content}`).join("\n\n") || "(none yet)"
|
|
|
17964
18638
|
}
|
|
17965
18639
|
wikiStore.rebuildIndex(today, limits);
|
|
17966
18640
|
persistPartialAndCompleteDates(updatesOverflowed);
|
|
17967
|
-
const hasIncomplete = allFailedSessions.length > 0 || harvestFailedDates.size > 0 || deferredSessionCount > 0 || updatesOverflowed;
|
|
18641
|
+
const hasIncomplete = allFailedSessions.length > 0 || harvestFailedDates.size > 0 || deferredSessionCount > 0 || deferredInboxCount > 0 || updatesOverflowed;
|
|
18642
|
+
const mergedCount = !updatesOverflowed ? packedInboxIds.length : 0;
|
|
17968
18643
|
return {
|
|
17969
18644
|
ok: !hasIncomplete,
|
|
17970
18645
|
dates: [...deps.dates],
|
|
@@ -17973,6 +18648,7 @@ ${p.content}`).join("\n\n") || "(none yet)"
|
|
|
17973
18648
|
written: [...appliedWritten, "index.md"],
|
|
17974
18649
|
archived,
|
|
17975
18650
|
summaries: summaries.length > 0 ? summaries : ["wiki already up to date"],
|
|
18651
|
+
...mergedCount > 0 ? { inboxMerged: mergedCount } : {},
|
|
17976
18652
|
...allFailedSessions.length > 0 ? { failedSessions: allFailedSessions } : {},
|
|
17977
18653
|
...hasIncomplete ? { error: formatPartialError(updatesOverflowed) } : {}
|
|
17978
18654
|
};
|
|
@@ -17991,6 +18667,73 @@ ${p.content}`).join("\n\n") || "(none yet)"
|
|
|
17991
18667
|
}
|
|
17992
18668
|
}
|
|
17993
18669
|
|
|
18670
|
+
// ../../packages/shared-headless-capabilities/src/memory/wiki-dream-batches.ts
|
|
18671
|
+
var DEFAULT_MAX_DREAM_BATCHES = 6;
|
|
18672
|
+
function progressSignature(wikiStore, memoryRoot) {
|
|
18673
|
+
const meta = wikiStore.readMeta();
|
|
18674
|
+
const dates = [...meta.dreamedDates ?? []].sort().join(",");
|
|
18675
|
+
const sessions = Object.entries(meta.dreamedSessionsByDate ?? {}).sort(([a], [b]) => a.localeCompare(b)).map(([d, ids]) => `${d}:${ids.length}`).join("|");
|
|
18676
|
+
const targets = Object.entries(meta.dreamedTargetsBySession ?? {}).sort(([a], [b]) => a.localeCompare(b)).map(([k, ts]) => `${k}:${ts.length}`).join("|");
|
|
18677
|
+
const inboxRemaining = countWikiInbox(memoryRoot);
|
|
18678
|
+
return `${dates}#${sessions}#${targets}#inbox:${inboxRemaining}`;
|
|
18679
|
+
}
|
|
18680
|
+
function isPureBatchOverflow(res) {
|
|
18681
|
+
if (res.ok) return false;
|
|
18682
|
+
if (!res.error || !res.error.startsWith("wiki dream batch overflow")) return false;
|
|
18683
|
+
if (res.failedSessions && res.failedSessions.length > 0) return false;
|
|
18684
|
+
if (res.violations && res.violations.length > 0) return false;
|
|
18685
|
+
return true;
|
|
18686
|
+
}
|
|
18687
|
+
async function runWikiDreamBatches(deps) {
|
|
18688
|
+
const maxBatches = Math.min(Math.max(1, Math.floor(deps.maxBatches ?? DEFAULT_MAX_DREAM_BATCHES)), 12);
|
|
18689
|
+
const wikiStore = new WikiStore(deps.memoryRoot);
|
|
18690
|
+
const writtenSet = /* @__PURE__ */ new Set();
|
|
18691
|
+
const archivedSet = /* @__PURE__ */ new Set();
|
|
18692
|
+
const summaries = [];
|
|
18693
|
+
let totalSessions = 0;
|
|
18694
|
+
let totalSignals = 0;
|
|
18695
|
+
let totalInboxMerged = 0;
|
|
18696
|
+
let last;
|
|
18697
|
+
let batchesRun = 0;
|
|
18698
|
+
const extractedSignalsCache = /* @__PURE__ */ new Map();
|
|
18699
|
+
for (let pass = 0; pass < maxBatches; pass += 1) {
|
|
18700
|
+
const beforeSig = progressSignature(wikiStore, deps.memoryRoot);
|
|
18701
|
+
const res = await runWikiDream({ ...deps, extractedSignalsCache });
|
|
18702
|
+
batchesRun += 1;
|
|
18703
|
+
last = res;
|
|
18704
|
+
totalSessions += res.sessionsHarvested;
|
|
18705
|
+
totalSignals += res.signalsAuthenticated;
|
|
18706
|
+
totalInboxMerged += res.inboxMerged ?? 0;
|
|
18707
|
+
for (const w of res.written) writtenSet.add(w);
|
|
18708
|
+
for (const a of res.archived) archivedSet.add(a);
|
|
18709
|
+
for (const s of res.summaries) {
|
|
18710
|
+
if (summaries.length < 40 && !summaries.includes(s)) summaries.push(s);
|
|
18711
|
+
}
|
|
18712
|
+
if (!isPureBatchOverflow(res)) {
|
|
18713
|
+
break;
|
|
18714
|
+
}
|
|
18715
|
+
const afterSig = progressSignature(wikiStore, deps.memoryRoot);
|
|
18716
|
+
if (afterSig === beforeSig) {
|
|
18717
|
+
deps.log?.(`[wiki-dream] stopping overflow drain after pass ${batchesRun}: no forward progress`);
|
|
18718
|
+
break;
|
|
18719
|
+
}
|
|
18720
|
+
if (pass + 1 < maxBatches) {
|
|
18721
|
+
deps.log?.(`[wiki-dream] batch ${batchesRun}/${maxBatches} progressed (${res.error}); draining remaining batch`);
|
|
18722
|
+
}
|
|
18723
|
+
}
|
|
18724
|
+
const finalRes = last;
|
|
18725
|
+
return {
|
|
18726
|
+
...finalRes,
|
|
18727
|
+
sessionsHarvested: totalSessions,
|
|
18728
|
+
signalsAuthenticated: totalSignals,
|
|
18729
|
+
written: [...writtenSet],
|
|
18730
|
+
archived: [...archivedSet],
|
|
18731
|
+
summaries,
|
|
18732
|
+
...totalInboxMerged > 0 ? { inboxMerged: totalInboxMerged } : {},
|
|
18733
|
+
batchesRun
|
|
18734
|
+
};
|
|
18735
|
+
}
|
|
18736
|
+
|
|
17994
18737
|
// ../../packages/shared-headless-capabilities/src/memory/session-lookup.ts
|
|
17995
18738
|
var MAX_READ_CHUNK_CHARS = 6e3;
|
|
17996
18739
|
var MAX_SEARCH_SCAN = 256;
|
|
@@ -18442,6 +19185,13 @@ export {
|
|
|
18442
19185
|
WikiStore,
|
|
18443
19186
|
searchMemory,
|
|
18444
19187
|
readMemoryFile,
|
|
19188
|
+
MAX_WIKI_INBOX_ITEMS,
|
|
19189
|
+
wikiInboxPath,
|
|
19190
|
+
readWikiInbox,
|
|
19191
|
+
countWikiInbox,
|
|
19192
|
+
appendWikiInboxItem,
|
|
19193
|
+
removeWikiInboxItems,
|
|
19194
|
+
wikiInboxItemToDreamSignal,
|
|
18445
19195
|
parseWikiDreamOutput,
|
|
18446
19196
|
findExpiredDateAnchors,
|
|
18447
19197
|
runWikiGc,
|
|
@@ -18449,6 +19199,8 @@ export {
|
|
|
18449
19199
|
extractDreamSignalsForSession,
|
|
18450
19200
|
runWikiBootstrap,
|
|
18451
19201
|
runWikiDream,
|
|
19202
|
+
DEFAULT_MAX_DREAM_BATCHES,
|
|
19203
|
+
runWikiDreamBatches,
|
|
18452
19204
|
lookupSessionEvidence,
|
|
18453
19205
|
getSharedCapabilityPromptAdditionsForToolNames
|
|
18454
19206
|
};
|