@cydm/pie 4.13.1 → 4.14.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/builtin/extensions/ask-user/index.js +2 -2
- package/dist/builtin/extensions/im-forward/index.js +8092 -8098
- package/dist/builtin/extensions/mcp-adapter/index.js +86 -81
- package/dist/builtin/extensions/memory/index.js +28 -5
- package/dist/builtin/extensions/pie-ipc/index.js +13 -18
- package/dist/builtin/extensions/pie-proc/index.js +61 -55
- package/dist/builtin/extensions/plan-mode/index.js +2 -2
- package/dist/builtin/extensions/subagent/index.js +3 -3
- package/dist/builtin/extensions/todo/index.js +2 -2
- package/dist/chunks/{chunk-6Z54UHXM.js → chunk-BOQIGMGQ.js} +20 -15
- package/dist/chunks/{chunk-XPJHZRTN.js → chunk-EZZTMDWZ.js} +712 -378
- package/dist/chunks/{chunk-HSMO2BEA.js → chunk-FD3KBPDR.js} +23 -18
- package/dist/chunks/{chunk-3F2CSVNH.js → chunk-IK2FR2YF.js} +2 -1
- package/dist/chunks/{chunk-CCPNHS6B.js → chunk-JJH77AUU.js} +1578 -1566
- package/dist/chunks/{chunk-DT22BBZL.js → chunk-JKO42HZW.js} +1 -1
- package/dist/chunks/{chunk-UCVPNLCO.js → chunk-KGWKRO7Z.js} +1 -1
- package/dist/chunks/{chunk-NHWWRE3T.js → chunk-UYDS75SI.js} +725 -718
- package/dist/chunks/{host-image-fallback-LGWYQMLA.js → host-image-fallback-LPHB5CTL.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-ZJN6SPIU.js} +3 -3
- package/dist/chunks/{model-registry-IWOOAMLZ.js → model-registry-GLBIUOJR.js} +1 -1
- package/dist/chunks/{read-file-understanding-3TYWVOLX.js → read-file-understanding-DFJPTTSB.js} +3 -3
- package/dist/chunks/{src-WA2O2O2V.js → src-KZ7YID3I.js} +1 -1
- package/dist/chunks/{src-D2ICRXWW.js → src-LEXKDSFV.js} +22 -4
- package/dist/cli.js +2859 -2741
- package/package.json +1 -1
- package/dist/chunks/{chunk-3GG342QY.js → chunk-TYCKSYUF.js} +19 -19
|
@@ -18,7 +18,7 @@ import {
|
|
|
18
18
|
parseEntryIdSeq,
|
|
19
19
|
readAncestryPage,
|
|
20
20
|
requestInteraction
|
|
21
|
-
} from "./chunk-
|
|
21
|
+
} from "./chunk-JJH77AUU.js";
|
|
22
22
|
import {
|
|
23
23
|
Agent,
|
|
24
24
|
getToolCallerIdentity
|
|
@@ -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,138 +2388,6 @@ function transplantMessages(target, messages) {
|
|
|
2388
2388
|
}
|
|
2389
2389
|
}
|
|
2390
2390
|
|
|
2391
|
-
// ../../packages/shared-headless-capabilities/src/subagent-recovery.ts
|
|
2392
|
-
var MAX_SUBAGENT_MODEL_FALLBACKS = 2;
|
|
2393
|
-
function modelCandidateKey(model) {
|
|
2394
|
-
return `${model.provider}/${model.id}`;
|
|
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;
|
|
2413
|
-
}
|
|
2414
|
-
function pickNextSubagentFallbackCandidate(options) {
|
|
2415
|
-
const pool = [];
|
|
2416
|
-
const pushCandidate = (candidate) => {
|
|
2417
|
-
if (!candidate?.model || !candidate.apiKey) return;
|
|
2418
|
-
const key = modelCandidateKey(candidate.model);
|
|
2419
|
-
if (options.triedKeys.has(key)) return;
|
|
2420
|
-
if (pool.some((existing) => modelCandidateKey(existing.model) === key)) return;
|
|
2421
|
-
pool.push(candidate);
|
|
2422
|
-
};
|
|
2423
|
-
for (const candidate of options.resolveModelClassCandidates?.(options.modelClass) ?? []) {
|
|
2424
|
-
pushCandidate(candidate);
|
|
2425
|
-
}
|
|
2426
|
-
if (options.modelClass === "light") {
|
|
2427
|
-
for (const candidate of options.resolveModelClassCandidates?.("balanced") ?? []) {
|
|
2428
|
-
pushCandidate(candidate);
|
|
2429
|
-
}
|
|
2430
|
-
}
|
|
2431
|
-
if (options.parentModel && options.parentApiKey) {
|
|
2432
|
-
pushCandidate({ model: options.parentModel, apiKey: options.parentApiKey });
|
|
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;
|
|
2440
|
-
}
|
|
2441
|
-
return {
|
|
2442
|
-
errorMessage: terminalError,
|
|
2443
|
-
retryable: lastAssistant.retryable,
|
|
2444
|
-
replayClass: lastAssistant.replayClass,
|
|
2445
|
-
replayEligible: lastAssistant.replayEligible,
|
|
2446
|
-
remoteFailure: lastAssistant.remoteFailure
|
|
2447
|
-
};
|
|
2448
|
-
}
|
|
2449
|
-
function buildStreamInterruptedError(options) {
|
|
2450
|
-
if (options.terminalStopReason === "length") {
|
|
2451
|
-
return new Error(
|
|
2452
|
-
`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.`
|
|
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;
|
|
2465
|
-
}
|
|
2466
|
-
async function tryCompactSubagentOverflow(options) {
|
|
2467
|
-
const rawMessages = options.agent.state.messages;
|
|
2468
|
-
if (!Array.isArray(rawMessages) || rawMessages.length === 0) {
|
|
2469
|
-
return { compacted: false, newBaseline: 0 };
|
|
2470
|
-
}
|
|
2471
|
-
let end = rawMessages.length;
|
|
2472
|
-
while (end > 0) {
|
|
2473
|
-
const last = rawMessages[end - 1];
|
|
2474
|
-
if (last?.role === "assistant" && (last.stopReason === "error" || last.stopReason === "aborted")) {
|
|
2475
|
-
end -= 1;
|
|
2476
|
-
continue;
|
|
2477
|
-
}
|
|
2478
|
-
break;
|
|
2479
|
-
}
|
|
2480
|
-
const cleaned = rawMessages.slice(0, end);
|
|
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 });
|
|
2508
|
-
}
|
|
2509
|
-
if (!summary.trim() || controller.signal.aborted || options.signal?.aborted) {
|
|
2510
|
-
return { compacted: false, newBaseline: 0 };
|
|
2511
|
-
}
|
|
2512
|
-
const compacted = buildCompactedHistory(collectRealUserMessages(cleaned), summary);
|
|
2513
|
-
transplantMessages(options.agent, compacted);
|
|
2514
|
-
return { compacted: true, newBaseline: compacted.length };
|
|
2515
|
-
} catch {
|
|
2516
|
-
return { compacted: false, newBaseline: 0 };
|
|
2517
|
-
} finally {
|
|
2518
|
-
if (timer) clearTimeout(timer);
|
|
2519
|
-
options.signal?.removeEventListener("abort", onParentAbort);
|
|
2520
|
-
}
|
|
2521
|
-
}
|
|
2522
|
-
|
|
2523
2391
|
// ../../packages/shared-headless-capabilities/src/bash-policy.ts
|
|
2524
2392
|
var DESTRUCTIVE_PATTERNS = [
|
|
2525
2393
|
{ pattern: /\bgit\s+reset\s+--hard\b/, warning: "may discard uncommitted changes", commandClass: "git_destructive" },
|
|
@@ -3000,7 +2868,7 @@ function interpretShellExit(command, exitCode) {
|
|
|
3000
2868
|
return { isError: exitCode !== 0, semanticExitMeaning: exitCode === 0 ? "command succeeded" : `command failed with exit code ${exitCode}` };
|
|
3001
2869
|
}
|
|
3002
2870
|
|
|
3003
|
-
// ../../packages/shared-headless-capabilities/src/subagent.ts
|
|
2871
|
+
// ../../packages/shared-headless-capabilities/src/subagent-core.ts
|
|
3004
2872
|
var DEFAULT_SUBAGENT_TIMEOUT_SECONDS = 1200;
|
|
3005
2873
|
var DEFAULT_SUBAGENT_THINKING_LEVEL = "medium";
|
|
3006
2874
|
var SUBAGENT_THINKING_LEVELS = ALL_THINKING_LEVELS;
|
|
@@ -3393,6 +3261,140 @@ async function persistSubagentSession(deps, session, task) {
|
|
|
3393
3261
|
debugLog(deps, "session", "session persist failed", { id: session.id, error: error instanceof Error ? error.message : String(error) });
|
|
3394
3262
|
}
|
|
3395
3263
|
}
|
|
3264
|
+
|
|
3265
|
+
// ../../packages/shared-headless-capabilities/src/subagent-recovery.ts
|
|
3266
|
+
var MAX_SUBAGENT_MODEL_FALLBACKS = 2;
|
|
3267
|
+
function modelCandidateKey(model) {
|
|
3268
|
+
return `${model.provider}/${model.id}`;
|
|
3269
|
+
}
|
|
3270
|
+
function isSubagentOverflowFailure(failure, errorMessage, stopReason) {
|
|
3271
|
+
if (stopReason === "aborted" || stopReason === "length") return false;
|
|
3272
|
+
if (failure?.recovery?.outcome === "overflow") return true;
|
|
3273
|
+
if (failure?.classification?.kind === "context_overflow") return true;
|
|
3274
|
+
if (failure?.remoteFailure?.category === "context_overflow") return true;
|
|
3275
|
+
return Boolean(errorMessage && isDefaultContextOverflowError(errorMessage));
|
|
3276
|
+
}
|
|
3277
|
+
function isSubagentModelFallbackTrigger(errorMessage, failure, stopReason) {
|
|
3278
|
+
if (stopReason === "aborted" || stopReason === "length") return false;
|
|
3279
|
+
const kind = failure?.classification?.kind;
|
|
3280
|
+
if (kind === "user_abort" || kind === "invalid_request" || kind === "context_overflow") return false;
|
|
3281
|
+
if (errorMessage && isDefaultQuotaExhaustedError(errorMessage)) return true;
|
|
3282
|
+
if (kind === "auth_config") return true;
|
|
3283
|
+
if (failure?.recovery?.outcome === "exhausted" && (kind === "provider_transient" || kind === "provider_confirmation" || kind === "transient_network")) {
|
|
3284
|
+
return true;
|
|
3285
|
+
}
|
|
3286
|
+
return false;
|
|
3287
|
+
}
|
|
3288
|
+
function pickNextSubagentFallbackCandidate(options) {
|
|
3289
|
+
const pool = [];
|
|
3290
|
+
const pushCandidate = (candidate) => {
|
|
3291
|
+
if (!candidate?.model || !candidate.apiKey) return;
|
|
3292
|
+
const key = modelCandidateKey(candidate.model);
|
|
3293
|
+
if (options.triedKeys.has(key)) return;
|
|
3294
|
+
if (pool.some((existing) => modelCandidateKey(existing.model) === key)) return;
|
|
3295
|
+
pool.push(candidate);
|
|
3296
|
+
};
|
|
3297
|
+
for (const candidate of options.resolveModelClassCandidates?.(options.modelClass) ?? []) {
|
|
3298
|
+
pushCandidate(candidate);
|
|
3299
|
+
}
|
|
3300
|
+
if (options.modelClass === "light") {
|
|
3301
|
+
for (const candidate of options.resolveModelClassCandidates?.("balanced") ?? []) {
|
|
3302
|
+
pushCandidate(candidate);
|
|
3303
|
+
}
|
|
3304
|
+
}
|
|
3305
|
+
if (options.parentModel && options.parentApiKey) {
|
|
3306
|
+
pushCandidate({ model: options.parentModel, apiKey: options.parentApiKey });
|
|
3307
|
+
}
|
|
3308
|
+
return pool[0];
|
|
3309
|
+
}
|
|
3310
|
+
function extractFallbackFailureDetails(lastAssistant, terminalError) {
|
|
3311
|
+
if (!lastAssistant) return void 0;
|
|
3312
|
+
if (lastAssistant.retryable === void 0 && lastAssistant.replayClass === void 0 && lastAssistant.replayEligible === void 0 && lastAssistant.remoteFailure === void 0) {
|
|
3313
|
+
return void 0;
|
|
3314
|
+
}
|
|
3315
|
+
return {
|
|
3316
|
+
errorMessage: terminalError,
|
|
3317
|
+
retryable: lastAssistant.retryable,
|
|
3318
|
+
replayClass: lastAssistant.replayClass,
|
|
3319
|
+
replayEligible: lastAssistant.replayEligible,
|
|
3320
|
+
remoteFailure: lastAssistant.remoteFailure
|
|
3321
|
+
};
|
|
3322
|
+
}
|
|
3323
|
+
function buildStreamInterruptedError(options) {
|
|
3324
|
+
if (options.terminalStopReason === "length") {
|
|
3325
|
+
return new Error(
|
|
3326
|
+
`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.`
|
|
3327
|
+
);
|
|
3328
|
+
}
|
|
3329
|
+
const detail = options.terminalError ? `: ${options.terminalError.slice(0, 200)}` : "";
|
|
3330
|
+
const overflow = isSubagentOverflowFailure(options.subagentFailure, options.terminalError, options.terminalStopReason);
|
|
3331
|
+
const failure = new Error(
|
|
3332
|
+
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}`
|
|
3333
|
+
);
|
|
3334
|
+
const carrier = failure;
|
|
3335
|
+
carrier.retryable = options.subagentFailure?.retryable;
|
|
3336
|
+
carrier.replayClass = options.subagentFailure?.replayClass;
|
|
3337
|
+
carrier.subagentFailure = options.subagentFailure;
|
|
3338
|
+
return failure;
|
|
3339
|
+
}
|
|
3340
|
+
async function tryCompactSubagentOverflow(options) {
|
|
3341
|
+
const rawMessages = options.agent.state.messages;
|
|
3342
|
+
if (!Array.isArray(rawMessages) || rawMessages.length === 0) {
|
|
3343
|
+
return { compacted: false, newBaseline: 0 };
|
|
3344
|
+
}
|
|
3345
|
+
let end = rawMessages.length;
|
|
3346
|
+
while (end > 0) {
|
|
3347
|
+
const last = rawMessages[end - 1];
|
|
3348
|
+
if (last?.role === "assistant" && (last.stopReason === "error" || last.stopReason === "aborted")) {
|
|
3349
|
+
end -= 1;
|
|
3350
|
+
continue;
|
|
3351
|
+
}
|
|
3352
|
+
break;
|
|
3353
|
+
}
|
|
3354
|
+
const cleaned = rawMessages.slice(0, end);
|
|
3355
|
+
const hasPriorTurns = cleaned.some((m) => m.role === "assistant" || m.role === "toolResult");
|
|
3356
|
+
if (cleaned.length === 0 || !hasPriorTurns) {
|
|
3357
|
+
return { compacted: false, newBaseline: 0 };
|
|
3358
|
+
}
|
|
3359
|
+
const controller = new AbortController();
|
|
3360
|
+
const onParentAbort = () => controller.abort();
|
|
3361
|
+
if (options.signal?.aborted) return { compacted: false, newBaseline: 0 };
|
|
3362
|
+
options.signal?.addEventListener("abort", onParentAbort, { once: true });
|
|
3363
|
+
const remainingMs = options.hardDeadlineAt !== void 0 ? Math.max(0, options.hardDeadlineAt - Date.now()) : void 0;
|
|
3364
|
+
if (remainingMs !== void 0 && remainingMs <= 0) {
|
|
3365
|
+
options.signal?.removeEventListener("abort", onParentAbort);
|
|
3366
|
+
return { compacted: false, newBaseline: 0 };
|
|
3367
|
+
}
|
|
3368
|
+
const timer = remainingMs !== void 0 ? setTimeout(() => controller.abort(), Math.min(remainingMs, 6e4)) : void 0;
|
|
3369
|
+
try {
|
|
3370
|
+
let summary;
|
|
3371
|
+
try {
|
|
3372
|
+
summary = options.compactSummaryFn ? await options.compactSummaryFn(cleaned, options.model, options.apiKey, controller.signal) : await createCompactionSummary(cleaned, {
|
|
3373
|
+
model: options.model,
|
|
3374
|
+
apiKey: options.apiKey,
|
|
3375
|
+
signal: controller.signal
|
|
3376
|
+
});
|
|
3377
|
+
} catch (summaryError) {
|
|
3378
|
+
if (controller.signal.aborted || options.signal?.aborted) return { compacted: false, newBaseline: 0 };
|
|
3379
|
+
const summaryMsg = summaryError instanceof Error ? summaryError.message : String(summaryError);
|
|
3380
|
+
if (!isDefaultContextOverflowError(summaryMsg)) return { compacted: false, newBaseline: 0 };
|
|
3381
|
+
summary = await createCompactionSummary(cleaned, { signal: controller.signal });
|
|
3382
|
+
}
|
|
3383
|
+
if (!summary.trim() || controller.signal.aborted || options.signal?.aborted) {
|
|
3384
|
+
return { compacted: false, newBaseline: 0 };
|
|
3385
|
+
}
|
|
3386
|
+
const compacted = buildCompactedHistory(collectRealUserMessages(cleaned), summary);
|
|
3387
|
+
transplantMessages(options.agent, compacted);
|
|
3388
|
+
return { compacted: true, newBaseline: compacted.length };
|
|
3389
|
+
} catch {
|
|
3390
|
+
return { compacted: false, newBaseline: 0 };
|
|
3391
|
+
} finally {
|
|
3392
|
+
if (timer) clearTimeout(timer);
|
|
3393
|
+
options.signal?.removeEventListener("abort", onParentAbort);
|
|
3394
|
+
}
|
|
3395
|
+
}
|
|
3396
|
+
|
|
3397
|
+
// ../../packages/shared-headless-capabilities/src/subagent.ts
|
|
3396
3398
|
async function runSubagentWithProgress(deps, task, reportProgress, signal, sessions) {
|
|
3397
3399
|
const startTime = Date.now();
|
|
3398
3400
|
task.status = "running";
|
|
@@ -3708,7 +3710,7 @@ ${DELEGATION_REPORT_INSTRUCTION}`;
|
|
|
3708
3710
|
unsubscribe?.();
|
|
3709
3711
|
if (!agentSettled && settledRun) {
|
|
3710
3712
|
const graceMs = deps.sessionSettleGraceMs ?? 2e3;
|
|
3711
|
-
if (graceMs > 0) await Promise.race([settledRun, new Promise((
|
|
3713
|
+
if (graceMs > 0) await Promise.race([settledRun, new Promise((resolve7) => setTimeout(resolve7, graceMs))]);
|
|
3712
3714
|
}
|
|
3713
3715
|
}
|
|
3714
3716
|
if (hardDeadlineAt !== void 0 && Date.now() >= hardDeadlineAt) {
|
|
@@ -5207,11 +5209,11 @@ function formatCapabilityPolicySummary(tools, context = {}) {
|
|
|
5207
5209
|
import * as nodePath from "node:path";
|
|
5208
5210
|
|
|
5209
5211
|
// ../../packages/shared-headless-capabilities/src/builtin/fs/path-utils.ts
|
|
5210
|
-
function isInAllowlist(
|
|
5212
|
+
function isInAllowlist(path12, allowlistedDirs) {
|
|
5211
5213
|
if (allowlistedDirs.some((dir) => isGlobalFilesystemSentinel(dir))) {
|
|
5212
5214
|
return true;
|
|
5213
5215
|
}
|
|
5214
|
-
const normalized = normalizeForComparison(
|
|
5216
|
+
const normalized = normalizeForComparison(path12);
|
|
5215
5217
|
for (const dir of allowlistedDirs) {
|
|
5216
5218
|
const normalizedDir = normalizeForComparison(dir);
|
|
5217
5219
|
const dirWithSlash = withTrailingSep(normalizedDir);
|
|
@@ -5221,19 +5223,19 @@ function isInAllowlist(path11, allowlistedDirs) {
|
|
|
5221
5223
|
}
|
|
5222
5224
|
return false;
|
|
5223
5225
|
}
|
|
5224
|
-
function normalizeForComparison(
|
|
5225
|
-
const slashNormalized =
|
|
5226
|
+
function normalizeForComparison(path12) {
|
|
5227
|
+
const slashNormalized = path12.replace(/\\/g, "/");
|
|
5226
5228
|
const isWindowsPath = /^[a-zA-Z]:($|\/)/.test(slashNormalized) || /^\/{2}[^/]+\/[^/]+/.test(slashNormalized);
|
|
5227
5229
|
const normalized = slashNormalized.replace(/\/+/g, "/");
|
|
5228
5230
|
if (normalized === "/") return normalized;
|
|
5229
5231
|
const trimmed = normalized.replace(/\/+$/, "");
|
|
5230
5232
|
return isWindowsPath ? trimmed.toLowerCase() : trimmed;
|
|
5231
5233
|
}
|
|
5232
|
-
function isGlobalFilesystemSentinel(
|
|
5233
|
-
return normalizeForComparison(String(
|
|
5234
|
+
function isGlobalFilesystemSentinel(path12) {
|
|
5235
|
+
return normalizeForComparison(String(path12 || "").trim()) === "/";
|
|
5234
5236
|
}
|
|
5235
|
-
function isAbsoluteUserPath(
|
|
5236
|
-
const normalized =
|
|
5237
|
+
function isAbsoluteUserPath(path12) {
|
|
5238
|
+
const normalized = path12.replace(/\\/g, "/");
|
|
5237
5239
|
return /^[a-zA-Z]:\//.test(normalized) || /^\/{2}[^/]+\/[^/]+/.test(normalized);
|
|
5238
5240
|
}
|
|
5239
5241
|
function validateToolPathArgument(filePath) {
|
|
@@ -5248,65 +5250,65 @@ function validateToolPathArgument(filePath) {
|
|
|
5248
5250
|
throw new Error(`Invalid path "${filePath}". The path argument must be a single file path, not multi-line text.`);
|
|
5249
5251
|
}
|
|
5250
5252
|
}
|
|
5251
|
-
function withTrailingSep(
|
|
5252
|
-
return
|
|
5253
|
+
function withTrailingSep(path12) {
|
|
5254
|
+
return path12.endsWith("/") ? path12 : `${path12}/`;
|
|
5253
5255
|
}
|
|
5254
|
-
function isWithinRoot(
|
|
5256
|
+
function isWithinRoot(path12, root) {
|
|
5255
5257
|
if (isGlobalFilesystemSentinel(root)) {
|
|
5256
5258
|
return true;
|
|
5257
5259
|
}
|
|
5258
|
-
const normalizedPath = normalizeForComparison(
|
|
5260
|
+
const normalizedPath = normalizeForComparison(path12);
|
|
5259
5261
|
const normalizedRoot = normalizeForComparison(root);
|
|
5260
5262
|
return normalizedPath === normalizedRoot || normalizedPath.startsWith(withTrailingSep(normalizedRoot));
|
|
5261
5263
|
}
|
|
5262
5264
|
function getAccessRoots(sandboxRoot, options) {
|
|
5263
|
-
const
|
|
5265
|
+
const fs10 = getFileSystem();
|
|
5264
5266
|
const roots = /* @__PURE__ */ new Set();
|
|
5265
|
-
roots.add(
|
|
5267
|
+
roots.add(fs10.normalize(sandboxRoot));
|
|
5266
5268
|
if (options?.accessRoot) {
|
|
5267
|
-
roots.add(
|
|
5269
|
+
roots.add(fs10.normalize(options.accessRoot));
|
|
5268
5270
|
}
|
|
5269
5271
|
for (const root of options?.accessRoots ?? []) {
|
|
5270
5272
|
const trimmed = String(root || "").trim();
|
|
5271
5273
|
if (trimmed) {
|
|
5272
|
-
roots.add(
|
|
5274
|
+
roots.add(fs10.normalize(trimmed));
|
|
5273
5275
|
}
|
|
5274
5276
|
}
|
|
5275
5277
|
return Array.from(roots);
|
|
5276
5278
|
}
|
|
5277
|
-
function isWithinAnyRoot(
|
|
5278
|
-
if (roots.some((root) => isWithinRoot(
|
|
5279
|
-
const
|
|
5280
|
-
if (!
|
|
5281
|
-
const canonical = canonicalizeExistingPath(
|
|
5279
|
+
function isWithinAnyRoot(path12, roots) {
|
|
5280
|
+
if (roots.some((root) => isWithinRoot(path12, root))) return true;
|
|
5281
|
+
const fs10 = getFileSystem();
|
|
5282
|
+
if (!fs10.realpathSync) return false;
|
|
5283
|
+
const canonical = canonicalizeExistingPath(path12);
|
|
5282
5284
|
return roots.some((root) => isWithinRoot(canonical, canonicalizeExistingPath(root)));
|
|
5283
5285
|
}
|
|
5284
5286
|
function canonicalizeExistingPath(pathValue) {
|
|
5285
|
-
const
|
|
5286
|
-
if (!
|
|
5287
|
-
let cursor =
|
|
5287
|
+
const fs10 = getFileSystem();
|
|
5288
|
+
if (!fs10.realpathSync) return fs10.normalize(pathValue);
|
|
5289
|
+
let cursor = fs10.normalize(pathValue);
|
|
5288
5290
|
const suffix = [];
|
|
5289
|
-
while (!
|
|
5290
|
-
if (
|
|
5291
|
+
while (!fs10.existsSync(cursor)) {
|
|
5292
|
+
if (fs10.lstatSync) {
|
|
5291
5293
|
try {
|
|
5292
|
-
if (
|
|
5294
|
+
if (fs10.lstatSync(cursor).isSymbolicLink) {
|
|
5293
5295
|
throw new Error(`Path contains an unresolved symbolic link: ${cursor}`);
|
|
5294
5296
|
}
|
|
5295
5297
|
} catch (error) {
|
|
5296
5298
|
if (error instanceof Error && error.message.startsWith("Path contains an unresolved symbolic link:")) throw error;
|
|
5297
5299
|
}
|
|
5298
5300
|
}
|
|
5299
|
-
const parent =
|
|
5300
|
-
if (parent === cursor) return
|
|
5301
|
-
suffix.unshift(
|
|
5301
|
+
const parent = fs10.dirname(cursor);
|
|
5302
|
+
if (parent === cursor) return fs10.normalize(pathValue);
|
|
5303
|
+
suffix.unshift(fs10.basename(cursor));
|
|
5302
5304
|
cursor = parent;
|
|
5303
5305
|
}
|
|
5304
|
-
const canonicalBase =
|
|
5305
|
-
return suffix.length > 0 ?
|
|
5306
|
+
const canonicalBase = fs10.normalize(fs10.realpathSync(cursor));
|
|
5307
|
+
return suffix.length > 0 ? fs10.resolve(canonicalBase, ...suffix) : canonicalBase;
|
|
5306
5308
|
}
|
|
5307
5309
|
function finalizeResolvedPath(resolved, sandboxRoot, options) {
|
|
5308
|
-
const
|
|
5309
|
-
if (!
|
|
5310
|
+
const fs10 = getFileSystem();
|
|
5311
|
+
if (!fs10.realpathSync || !fs10.isAbsolute(resolved)) return resolved;
|
|
5310
5312
|
const allowlistedDirs = options?.allowlistedDirs ?? [];
|
|
5311
5313
|
if (allowlistedDirs.some((dir) => isGlobalFilesystemSentinel(dir))) return resolved;
|
|
5312
5314
|
const canonical = canonicalizeExistingPath(resolved);
|
|
@@ -5328,7 +5330,7 @@ function getAvailableRoots(options) {
|
|
|
5328
5330
|
if (!options?.roots || options.roots.length === 0) {
|
|
5329
5331
|
return [];
|
|
5330
5332
|
}
|
|
5331
|
-
const
|
|
5333
|
+
const fs10 = getFileSystem();
|
|
5332
5334
|
const seen = /* @__PURE__ */ new Set();
|
|
5333
5335
|
const results = [];
|
|
5334
5336
|
for (const root of options.roots) {
|
|
@@ -5336,14 +5338,14 @@ function getAvailableRoots(options) {
|
|
|
5336
5338
|
continue;
|
|
5337
5339
|
}
|
|
5338
5340
|
const name = root.name.trim();
|
|
5339
|
-
const
|
|
5340
|
-
if (!name || !
|
|
5341
|
+
const path12 = root.path.trim();
|
|
5342
|
+
if (!name || !path12 || seen.has(name)) {
|
|
5341
5343
|
continue;
|
|
5342
5344
|
}
|
|
5343
5345
|
seen.add(name);
|
|
5344
5346
|
results.push({
|
|
5345
5347
|
name,
|
|
5346
|
-
path:
|
|
5348
|
+
path: fs10.normalize(path12),
|
|
5347
5349
|
description: root.description?.trim() || void 0,
|
|
5348
5350
|
defaultPrefixes: Array.isArray(root.defaultPrefixes) ? root.defaultPrefixes.map((prefix) => String(prefix || "").trim()).filter((prefix) => prefix.length > 0) : void 0
|
|
5349
5351
|
});
|
|
@@ -5398,7 +5400,7 @@ function getResolutionRoot(filePath, sandboxRoot, options, rootName) {
|
|
|
5398
5400
|
return findPrefixMatchedRoot(filePath, options) ?? getRootByName(void 0, sandboxRoot, options);
|
|
5399
5401
|
}
|
|
5400
5402
|
function resolveInSandbox(filePath, sandboxRoot, options, rootName) {
|
|
5401
|
-
const
|
|
5403
|
+
const fs10 = getFileSystem();
|
|
5402
5404
|
const allowlistedDirs = options?.allowlistedDirs ?? [];
|
|
5403
5405
|
const accessRoots = getAccessRoots(sandboxRoot, options);
|
|
5404
5406
|
if (!filePath) {
|
|
@@ -5406,8 +5408,8 @@ function resolveInSandbox(filePath, sandboxRoot, options, rootName) {
|
|
|
5406
5408
|
}
|
|
5407
5409
|
validateToolPathArgument(filePath);
|
|
5408
5410
|
const cleaned = filePath.trim().startsWith("@") ? filePath.trim().slice(1) : filePath.trim();
|
|
5409
|
-
if (
|
|
5410
|
-
const normalized =
|
|
5411
|
+
if (fs10.isAbsolute(cleaned) || isAbsoluteUserPath(cleaned)) {
|
|
5412
|
+
const normalized = fs10.normalize(cleaned);
|
|
5411
5413
|
const selectedRoot2 = rootName ? getRootByName(rootName, sandboxRoot, options) : void 0;
|
|
5412
5414
|
if (rootName && !selectedRoot2) {
|
|
5413
5415
|
const available = getAvailableRoots(options).map((root) => root.name).join(", ");
|
|
@@ -5442,7 +5444,7 @@ function resolveInSandbox(filePath, sandboxRoot, options, rootName) {
|
|
|
5442
5444
|
);
|
|
5443
5445
|
}
|
|
5444
5446
|
const resolvedBase = selectedRoot?.path ?? sandboxRoot;
|
|
5445
|
-
const resolved =
|
|
5447
|
+
const resolved = fs10.resolve(resolvedBase, cleaned);
|
|
5446
5448
|
if (selectedRoot) {
|
|
5447
5449
|
if (!isWithinAnyRoot(resolved, [selectedRoot.path])) {
|
|
5448
5450
|
throw new Error(`Path escapes root '${selectedRoot.name}': ${filePath}`);
|
|
@@ -5980,7 +5982,7 @@ function createReadErrorResult(message, details) {
|
|
|
5980
5982
|
};
|
|
5981
5983
|
}
|
|
5982
5984
|
function createReadTool(cwd, options) {
|
|
5983
|
-
const
|
|
5985
|
+
const fs10 = getFileSystem();
|
|
5984
5986
|
const fileObservationState = options?.fileObservationState ?? createFileObservationState();
|
|
5985
5987
|
const callerObservations = /* @__PURE__ */ new WeakMap();
|
|
5986
5988
|
const rootSchema = buildRootParameterSchema(cwd, options);
|
|
@@ -6000,7 +6002,7 @@ function createReadTool(cwd, options) {
|
|
|
6000
6002
|
parameters: readSchema,
|
|
6001
6003
|
execute: async (_toolCallId, rawParams, signal, _onUpdate) => {
|
|
6002
6004
|
const params = rawParams ?? {};
|
|
6003
|
-
const { path:
|
|
6005
|
+
const { path: path12, root, question } = params;
|
|
6004
6006
|
const tail = params.tail;
|
|
6005
6007
|
let offset = params.offset;
|
|
6006
6008
|
let limit = params.limit;
|
|
@@ -6021,7 +6023,7 @@ function createReadTool(cwd, options) {
|
|
|
6021
6023
|
}
|
|
6022
6024
|
let absolutePath;
|
|
6023
6025
|
try {
|
|
6024
|
-
absolutePath = resolveReadPath(
|
|
6026
|
+
absolutePath = resolveReadPath(path12, cwd, options, root);
|
|
6025
6027
|
} catch (error) {
|
|
6026
6028
|
const message = error instanceof Error ? error.message : String(error);
|
|
6027
6029
|
if (/outside sandbox|outside root|escapes sandbox/i.test(message)) {
|
|
@@ -6032,7 +6034,7 @@ function createReadTool(cwd, options) {
|
|
|
6032
6034
|
return createReadErrorResult(message);
|
|
6033
6035
|
}
|
|
6034
6036
|
return new Promise(
|
|
6035
|
-
(
|
|
6037
|
+
(resolve7, reject) => {
|
|
6036
6038
|
if (signal?.aborted) {
|
|
6037
6039
|
reject(new Error("Operation aborted"));
|
|
6038
6040
|
return;
|
|
@@ -6047,26 +6049,26 @@ function createReadTool(cwd, options) {
|
|
|
6047
6049
|
}
|
|
6048
6050
|
(async () => {
|
|
6049
6051
|
try {
|
|
6050
|
-
await
|
|
6052
|
+
await fs10.access(absolutePath);
|
|
6051
6053
|
if (isSpecialDevicePath(absolutePath)) {
|
|
6052
6054
|
throw new Error(`Refusing to read special device path: ${absolutePath}`);
|
|
6053
6055
|
}
|
|
6054
|
-
const stat = await
|
|
6056
|
+
const stat = await fs10.stat(absolutePath);
|
|
6055
6057
|
if (!stat.isFile) {
|
|
6056
6058
|
throw new Error(`Refusing to read non-regular file: ${absolutePath}`);
|
|
6057
6059
|
}
|
|
6058
6060
|
if (aborted) return;
|
|
6059
|
-
const prefix = await
|
|
6061
|
+
const prefix = await fs10.readFilePrefix(absolutePath, BINARY_MAGIC_PREFIX_BYTES);
|
|
6060
6062
|
const magicInfo = detectBinaryMagic(prefix);
|
|
6061
6063
|
let binaryInfo = detectBinaryKind(absolutePath);
|
|
6062
6064
|
if (options?.allowBinary === false) {
|
|
6063
6065
|
binaryInfo = detectTextOnlyBinary(prefix, absolutePath, stat.size > prefix.length);
|
|
6064
6066
|
}
|
|
6065
6067
|
if (options?.allowBinary === false && binaryInfo) {
|
|
6066
|
-
|
|
6068
|
+
resolve7({
|
|
6067
6069
|
content: [{
|
|
6068
6070
|
type: "text",
|
|
6069
|
-
text: `Cannot read ${binaryInfo.kind} file ${
|
|
6071
|
+
text: `Cannot read ${binaryInfo.kind} file ${path12}: this read_file instance accepts text files only.`
|
|
6070
6072
|
}],
|
|
6071
6073
|
details: {
|
|
6072
6074
|
understanding: {
|
|
@@ -6080,9 +6082,9 @@ function createReadTool(cwd, options) {
|
|
|
6080
6082
|
return;
|
|
6081
6083
|
}
|
|
6082
6084
|
if (magicInfo?.kind === "image" && options?.understandFile && (!INLINE_IMAGE_MIME_TYPES.has(magicInfo.mimeType) || stat.size > MAX_INLINE_IMAGE_BYTES)) {
|
|
6083
|
-
|
|
6085
|
+
resolve7(await options.understandFile({
|
|
6084
6086
|
absolutePath,
|
|
6085
|
-
displayPath:
|
|
6087
|
+
displayPath: path12,
|
|
6086
6088
|
mimeType: magicInfo.mimeType,
|
|
6087
6089
|
kind: "image",
|
|
6088
6090
|
question,
|
|
@@ -6091,14 +6093,14 @@ function createReadTool(cwd, options) {
|
|
|
6091
6093
|
return;
|
|
6092
6094
|
}
|
|
6093
6095
|
if (magicInfo?.kind === "image" && INLINE_IMAGE_MIME_TYPES.has(magicInfo.mimeType) && stat.size > MAX_INLINE_IMAGE_BYTES) {
|
|
6094
|
-
throw new Error(`Image file ${
|
|
6096
|
+
throw new Error(`Image file ${path12} is too large to attach (${formatSize(stat.size)}; maximum ${formatSize(MAX_INLINE_IMAGE_BYTES)}).`);
|
|
6095
6097
|
}
|
|
6096
|
-
const imageInfo = options?.allowBinary === false || magicInfo?.kind !== "image" || !INLINE_IMAGE_MIME_TYPES.has(magicInfo.mimeType) ? void 0 : await readImageInfo(absolutePath,
|
|
6098
|
+
const imageInfo = options?.allowBinary === false || magicInfo?.kind !== "image" || !INLINE_IMAGE_MIME_TYPES.has(magicInfo.mimeType) ? void 0 : await readImageInfo(absolutePath, fs10);
|
|
6097
6099
|
if (imageInfo) {
|
|
6098
6100
|
if (options?.understandFile) {
|
|
6099
|
-
|
|
6101
|
+
resolve7(await options.understandFile({
|
|
6100
6102
|
absolutePath,
|
|
6101
|
-
displayPath:
|
|
6103
|
+
displayPath: path12,
|
|
6102
6104
|
mimeType: imageInfo.mimeType,
|
|
6103
6105
|
kind: "image",
|
|
6104
6106
|
question,
|
|
@@ -6108,7 +6110,7 @@ function createReadTool(cwd, options) {
|
|
|
6108
6110
|
return;
|
|
6109
6111
|
}
|
|
6110
6112
|
const dimensionText = imageInfo.width && imageInfo.height ? `, ${imageInfo.width}x${imageInfo.height}` : "";
|
|
6111
|
-
|
|
6113
|
+
resolve7({
|
|
6112
6114
|
content: [
|
|
6113
6115
|
{ 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
6116
|
Focus: ${question.trim()}` : ""}` },
|
|
@@ -6126,8 +6128,8 @@ Focus: ${question.trim()}` : ""}` },
|
|
|
6126
6128
|
}
|
|
6127
6129
|
if (magicInfo?.kind === "image") {
|
|
6128
6130
|
const inlineSupported = INLINE_IMAGE_MIME_TYPES.has(magicInfo.mimeType);
|
|
6129
|
-
|
|
6130
|
-
content: [{ type: "text", text: inlineSupported ? `Cannot attach image file ${
|
|
6131
|
+
resolve7({
|
|
6132
|
+
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
6133
|
details: { understanding: { kind: "image", mimeType: magicInfo.mimeType, fallbackReason: inlineSupported ? "image bridge read failed" : "unsupported inline image format" } },
|
|
6132
6134
|
isError: true
|
|
6133
6135
|
});
|
|
@@ -6135,9 +6137,9 @@ Focus: ${question.trim()}` : ""}` },
|
|
|
6135
6137
|
}
|
|
6136
6138
|
const mediaInfo = magicInfo ?? detectUnderstandingKind(absolutePath);
|
|
6137
6139
|
if (mediaInfo && options?.understandFile) {
|
|
6138
|
-
|
|
6140
|
+
resolve7(await options.understandFile({
|
|
6139
6141
|
absolutePath,
|
|
6140
|
-
displayPath:
|
|
6142
|
+
displayPath: path12,
|
|
6141
6143
|
mimeType: mediaInfo.mimeType,
|
|
6142
6144
|
kind: mediaInfo.kind,
|
|
6143
6145
|
question,
|
|
@@ -6146,10 +6148,10 @@ Focus: ${question.trim()}` : ""}` },
|
|
|
6146
6148
|
return;
|
|
6147
6149
|
}
|
|
6148
6150
|
if (mediaInfo) {
|
|
6149
|
-
|
|
6151
|
+
resolve7({
|
|
6150
6152
|
content: [{
|
|
6151
6153
|
type: "text",
|
|
6152
|
-
text: `Cannot read ${mediaInfo.kind} file ${
|
|
6154
|
+
text: `Cannot read ${mediaInfo.kind} file ${path12} semantically: no media understanding handler is configured for ${mediaInfo.mimeType}.`
|
|
6153
6155
|
}],
|
|
6154
6156
|
details: {
|
|
6155
6157
|
understanding: {
|
|
@@ -6164,10 +6166,10 @@ Focus: ${question.trim()}` : ""}` },
|
|
|
6164
6166
|
}
|
|
6165
6167
|
const textBinaryInfo = detectTextOnlyBinary(prefix, absolutePath, stat.size > prefix.length);
|
|
6166
6168
|
if (textBinaryInfo) {
|
|
6167
|
-
|
|
6169
|
+
resolve7({
|
|
6168
6170
|
content: [{
|
|
6169
6171
|
type: "text",
|
|
6170
|
-
text: `Cannot read binary file ${
|
|
6172
|
+
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
6173
|
}],
|
|
6172
6174
|
details: {
|
|
6173
6175
|
understanding: {
|
|
@@ -6189,7 +6191,7 @@ Focus: ${question.trim()}` : ""}` },
|
|
|
6189
6191
|
const effectiveTail = Math.max(1, Math.min(tail, DEFAULT_MAX_LINES - 1));
|
|
6190
6192
|
translatedFromTail = true;
|
|
6191
6193
|
tailEffectiveLines = effectiveTail;
|
|
6192
|
-
range2 = await
|
|
6194
|
+
range2 = await fs10.readTextRange(absolutePath, {
|
|
6193
6195
|
tailLines: effectiveTail,
|
|
6194
6196
|
maxOutputLines: DEFAULT_MAX_LINES,
|
|
6195
6197
|
maxOutputBytes: DEFAULT_MAX_BYTES
|
|
@@ -6204,7 +6206,7 @@ Focus: ${question.trim()}` : ""}` },
|
|
|
6204
6206
|
}
|
|
6205
6207
|
} else {
|
|
6206
6208
|
startLine = offset === void 0 ? 0 : offset - 1;
|
|
6207
|
-
range2 = await
|
|
6209
|
+
range2 = await fs10.readTextRange(absolutePath, {
|
|
6208
6210
|
offsetLine: startLine,
|
|
6209
6211
|
limitLines: limit,
|
|
6210
6212
|
maxOutputLines: DEFAULT_MAX_LINES,
|
|
@@ -6216,8 +6218,8 @@ Focus: ${question.trim()}` : ""}` },
|
|
|
6216
6218
|
const selectedLooksBinary = range2.selectedBytesLookBinary ?? (looksLikeBinaryText(range2.content) || range2.content.includes("\uFFFD"));
|
|
6217
6219
|
const selectedBinary = selectedLooksBinary ? { kind: "document", mimeType: "application/octet-stream" } : void 0;
|
|
6218
6220
|
if (selectedBinary) {
|
|
6219
|
-
|
|
6220
|
-
content: [{ type: "text", text: `Cannot read ${selectedBinary.kind} file ${
|
|
6221
|
+
resolve7({
|
|
6222
|
+
content: [{ type: "text", text: `Cannot read ${selectedBinary.kind} file ${path12}: this read_file instance accepts text files only.` }],
|
|
6221
6223
|
details: { understanding: { ...selectedBinary, fallbackReason: "binary content is disabled for this tool" } },
|
|
6222
6224
|
isError: true
|
|
6223
6225
|
});
|
|
@@ -6270,7 +6272,7 @@ Focus: ${question.trim()}` : ""}` },
|
|
|
6270
6272
|
if (signal) {
|
|
6271
6273
|
signal.removeEventListener("abort", onAbort);
|
|
6272
6274
|
}
|
|
6273
|
-
|
|
6275
|
+
resolve7({
|
|
6274
6276
|
content: [{
|
|
6275
6277
|
type: "text",
|
|
6276
6278
|
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 +6370,7 @@ Base directory: ${nodePath.dirname(absolutePath)}
|
|
|
6368
6370
|
if (signal) {
|
|
6369
6371
|
signal.removeEventListener("abort", onAbort);
|
|
6370
6372
|
}
|
|
6371
|
-
|
|
6373
|
+
resolve7({
|
|
6372
6374
|
content: textContent,
|
|
6373
6375
|
details
|
|
6374
6376
|
});
|
|
@@ -6379,7 +6381,7 @@ Base directory: ${nodePath.dirname(absolutePath)}
|
|
|
6379
6381
|
reject(error);
|
|
6380
6382
|
return;
|
|
6381
6383
|
}
|
|
6382
|
-
|
|
6384
|
+
resolve7(createReadErrorResult(message, { path: absolutePath }));
|
|
6383
6385
|
}
|
|
6384
6386
|
} finally {
|
|
6385
6387
|
signal?.removeEventListener("abort", onAbort);
|
|
@@ -6390,8 +6392,8 @@ Base directory: ${nodePath.dirname(absolutePath)}
|
|
|
6390
6392
|
}
|
|
6391
6393
|
};
|
|
6392
6394
|
}
|
|
6393
|
-
function isSpecialDevicePath(
|
|
6394
|
-
const normalized = nodePath.resolve(
|
|
6395
|
+
function isSpecialDevicePath(path12) {
|
|
6396
|
+
const normalized = nodePath.resolve(path12).replace(/\\/g, "/");
|
|
6395
6397
|
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
6398
|
}
|
|
6397
6399
|
function detectUnderstandingKind(filePath) {
|
|
@@ -6532,22 +6534,22 @@ function detectTextOnlyBinary(input, filePath, prefixMayBeTruncated) {
|
|
|
6532
6534
|
if (!looksLikeBinary(input, prefixMayBeTruncated)) return void 0;
|
|
6533
6535
|
return detectBinaryKind(filePath) ?? { kind: "document", mimeType: "application/octet-stream" };
|
|
6534
6536
|
}
|
|
6535
|
-
async function readImageInfo(
|
|
6537
|
+
async function readImageInfo(path12, fs10) {
|
|
6536
6538
|
try {
|
|
6537
6539
|
let base64 = "";
|
|
6538
|
-
if (typeof
|
|
6539
|
-
base64 = await
|
|
6540
|
+
if (typeof fs10.readFile === "function") {
|
|
6541
|
+
base64 = await fs10.readFile(path12, "base64").catch(() => "");
|
|
6540
6542
|
}
|
|
6541
|
-
if (!base64 && typeof
|
|
6542
|
-
base64 =
|
|
6543
|
+
if (!base64 && typeof fs10.readFileSync === "function") {
|
|
6544
|
+
base64 = fs10.readFileSync(path12, "base64");
|
|
6543
6545
|
}
|
|
6544
6546
|
if (!base64) {
|
|
6545
|
-
console.error(`[pie] readImageInfo got empty base64 for ${
|
|
6547
|
+
console.error(`[pie] readImageInfo got empty base64 for ${path12}`);
|
|
6546
6548
|
return void 0;
|
|
6547
6549
|
}
|
|
6548
6550
|
const bytes = decodeBase64ToBytes(base64);
|
|
6549
6551
|
if (bytes.length === 0) {
|
|
6550
|
-
console.error(`[pie] readImageInfo decoded 0 bytes for ${
|
|
6552
|
+
console.error(`[pie] readImageInfo decoded 0 bytes for ${path12} (base64 length ${base64.length})`);
|
|
6551
6553
|
return void 0;
|
|
6552
6554
|
}
|
|
6553
6555
|
const pngMagic = [137, 80, 78, 71, 13, 10, 26, 10];
|
|
@@ -6566,10 +6568,10 @@ async function readImageInfo(path11, fs9) {
|
|
|
6566
6568
|
if (bytes.length >= 12 && asciiAt(bytes, 0, 4) === "RIFF" && asciiAt(bytes, 8, 12 - 8) === "WEBP") {
|
|
6567
6569
|
return { mimeType: "image/webp", base64, ...parseWebpDimensions(bytes) };
|
|
6568
6570
|
}
|
|
6569
|
-
console.error(`[pie] readImageInfo decoded ${bytes.length} bytes for ${
|
|
6571
|
+
console.error(`[pie] readImageInfo decoded ${bytes.length} bytes for ${path12} but no known image signature matched`);
|
|
6570
6572
|
return void 0;
|
|
6571
6573
|
} catch (error) {
|
|
6572
|
-
console.error(`[pie] readImageInfo failed for ${
|
|
6574
|
+
console.error(`[pie] readImageInfo failed for ${path12}: ${error instanceof Error ? error.message : String(error)}`);
|
|
6573
6575
|
return void 0;
|
|
6574
6576
|
}
|
|
6575
6577
|
return void 0;
|
|
@@ -6701,7 +6703,7 @@ function parseWebpDimensions(bytes) {
|
|
|
6701
6703
|
|
|
6702
6704
|
// ../../packages/shared-headless-capabilities/src/builtin/fs/write.ts
|
|
6703
6705
|
function createWriteTool(cwd, options) {
|
|
6704
|
-
const
|
|
6706
|
+
const fs10 = getFileSystem();
|
|
6705
6707
|
const usesExternalFileObservationState = !!options?.fileObservationState;
|
|
6706
6708
|
const fileObservationState = options?.fileObservationState ?? createFileObservationState();
|
|
6707
6709
|
const rootSchema = buildRootParameterSchema(cwd, options);
|
|
@@ -6719,9 +6721,9 @@ function createWriteTool(cwd, options) {
|
|
|
6719
6721
|
execute: async (_toolCallId, rawParams, signal) => {
|
|
6720
6722
|
const { path: filePath, root, content } = rawParams ?? {};
|
|
6721
6723
|
const absolutePath = resolveToCwd(filePath, cwd, options, root);
|
|
6722
|
-
const dir =
|
|
6724
|
+
const dir = fs10.dirname(absolutePath);
|
|
6723
6725
|
return new Promise(
|
|
6724
|
-
(
|
|
6726
|
+
(resolve7, reject) => {
|
|
6725
6727
|
if (signal?.aborted) {
|
|
6726
6728
|
reject(new Error("Operation aborted"));
|
|
6727
6729
|
return;
|
|
@@ -6736,18 +6738,18 @@ function createWriteTool(cwd, options) {
|
|
|
6736
6738
|
}
|
|
6737
6739
|
(async () => {
|
|
6738
6740
|
try {
|
|
6739
|
-
await
|
|
6741
|
+
await fs10.mkdir(dir, { recursive: true });
|
|
6740
6742
|
if (aborted) return;
|
|
6741
6743
|
let fileExists = false;
|
|
6742
6744
|
try {
|
|
6743
|
-
const stat = await
|
|
6745
|
+
const stat = await fs10.stat(absolutePath);
|
|
6744
6746
|
fileExists = stat.isFile;
|
|
6745
6747
|
} catch {
|
|
6746
6748
|
fileExists = false;
|
|
6747
6749
|
}
|
|
6748
6750
|
if (fileExists) {
|
|
6749
|
-
const currentContent = String(await
|
|
6750
|
-
const currentStat = await
|
|
6751
|
+
const currentContent = String(await fs10.readFile(absolutePath, "utf-8"));
|
|
6752
|
+
const currentStat = await fs10.stat(absolutePath);
|
|
6751
6753
|
const currentSnapshot = snapshotFromStatAndContent(currentStat, currentContent);
|
|
6752
6754
|
const observedSnapshot = fileObservationState.getCompleteTextSnapshot(absolutePath);
|
|
6753
6755
|
if (!observedSnapshot) {
|
|
@@ -6763,8 +6765,8 @@ function createWriteTool(cwd, options) {
|
|
|
6763
6765
|
);
|
|
6764
6766
|
}
|
|
6765
6767
|
}
|
|
6766
|
-
await
|
|
6767
|
-
const writtenStat = await
|
|
6768
|
+
await fs10.writeFile(absolutePath, content, "utf-8");
|
|
6769
|
+
const writtenStat = await fs10.stat(absolutePath);
|
|
6768
6770
|
fileObservationState.recordCompleteTextWrite(
|
|
6769
6771
|
absolutePath,
|
|
6770
6772
|
snapshotFromStatAndContent(writtenStat, content)
|
|
@@ -6773,7 +6775,7 @@ function createWriteTool(cwd, options) {
|
|
|
6773
6775
|
if (signal) {
|
|
6774
6776
|
signal.removeEventListener("abort", onAbort);
|
|
6775
6777
|
}
|
|
6776
|
-
|
|
6778
|
+
resolve7({
|
|
6777
6779
|
content: [{ type: "text", text: `Successfully wrote ${writtenStat.size} bytes to ${filePath}` }],
|
|
6778
6780
|
details: void 0
|
|
6779
6781
|
});
|
|
@@ -6892,16 +6894,16 @@ var Diff = class {
|
|
|
6892
6894
|
}
|
|
6893
6895
|
}
|
|
6894
6896
|
}
|
|
6895
|
-
addToPath(
|
|
6896
|
-
const last =
|
|
6897
|
+
addToPath(path12, added, removed, oldPosInc, options) {
|
|
6898
|
+
const last = path12.lastComponent;
|
|
6897
6899
|
if (last && !options.oneChangePerToken && last.added === added && last.removed === removed) {
|
|
6898
6900
|
return {
|
|
6899
|
-
oldPos:
|
|
6901
|
+
oldPos: path12.oldPos + oldPosInc,
|
|
6900
6902
|
lastComponent: { count: last.count + 1, added, removed, previousComponent: last.previousComponent }
|
|
6901
6903
|
};
|
|
6902
6904
|
} else {
|
|
6903
6905
|
return {
|
|
6904
|
-
oldPos:
|
|
6906
|
+
oldPos: path12.oldPos + oldPosInc,
|
|
6905
6907
|
lastComponent: { count: 1, added, removed, previousComponent: last }
|
|
6906
6908
|
};
|
|
6907
6909
|
}
|
|
@@ -7773,8 +7775,8 @@ function generateDiffString(oldContent, newContent, contextLines = 4) {
|
|
|
7773
7775
|
var MAX_EDIT_BLOCKS = 64;
|
|
7774
7776
|
var MAX_EDIT_INPUT_CHARS = 256 * 1024;
|
|
7775
7777
|
function validateEditArgs(params) {
|
|
7776
|
-
const { path:
|
|
7777
|
-
const filePath = typeof
|
|
7778
|
+
const { path: path12, oldText, newText, replaceAll, edits } = params;
|
|
7779
|
+
const filePath = typeof path12 === "string" ? path12.trim() : "";
|
|
7778
7780
|
if (!filePath) {
|
|
7779
7781
|
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
7782
|
}
|
|
@@ -7856,14 +7858,14 @@ function createEditErrorResult(params) {
|
|
|
7856
7858
|
isError: true
|
|
7857
7859
|
};
|
|
7858
7860
|
}
|
|
7859
|
-
function createEditThrownErrorResult(message,
|
|
7861
|
+
function createEditThrownErrorResult(message, path12) {
|
|
7860
7862
|
return {
|
|
7861
7863
|
content: [{ type: "text", text: boundEditOutput(`edit_file failed: ${message}`).text }],
|
|
7862
7864
|
details: {
|
|
7863
7865
|
status: "error",
|
|
7864
7866
|
matchKind: "none",
|
|
7865
7867
|
changed: false,
|
|
7866
|
-
path:
|
|
7868
|
+
path: path12,
|
|
7867
7869
|
diff: "",
|
|
7868
7870
|
oldTextOccurrences: 0,
|
|
7869
7871
|
newTextOccurrences: 0,
|
|
@@ -7876,7 +7878,7 @@ function createEditThrownErrorResult(message, path11) {
|
|
|
7876
7878
|
};
|
|
7877
7879
|
}
|
|
7878
7880
|
function createEditTool(cwd, options) {
|
|
7879
|
-
const
|
|
7881
|
+
const fs10 = getFileSystem();
|
|
7880
7882
|
const fileObservationState = options?.fileObservationState ?? createFileObservationState();
|
|
7881
7883
|
const usesExternalFileObservationState = !!options?.fileObservationState;
|
|
7882
7884
|
const rootSchema = buildRootParameterSchema(cwd, options);
|
|
@@ -7901,17 +7903,17 @@ function createEditTool(cwd, options) {
|
|
|
7901
7903
|
parameters: editSchema,
|
|
7902
7904
|
execute: async (_toolCallId, rawParams, signal) => {
|
|
7903
7905
|
const params = rawParams ?? {};
|
|
7904
|
-
const { path:
|
|
7906
|
+
const { path: path12, root } = params;
|
|
7905
7907
|
let replacements;
|
|
7906
7908
|
let absolutePath;
|
|
7907
7909
|
try {
|
|
7908
7910
|
replacements = validateEditArgs(params);
|
|
7909
|
-
absolutePath = resolveToCwd(
|
|
7911
|
+
absolutePath = resolveToCwd(path12, cwd, options, root);
|
|
7910
7912
|
} catch (error) {
|
|
7911
7913
|
const message = error instanceof Error ? error.message : String(error);
|
|
7912
|
-
return createEditThrownErrorResult(message, typeof
|
|
7914
|
+
return createEditThrownErrorResult(message, typeof path12 === "string" ? path12 : void 0);
|
|
7913
7915
|
}
|
|
7914
|
-
return new Promise((
|
|
7916
|
+
return new Promise((resolve7, reject) => {
|
|
7915
7917
|
if (signal?.aborted) {
|
|
7916
7918
|
reject(new Error("Operation aborted"));
|
|
7917
7919
|
return;
|
|
@@ -7932,10 +7934,10 @@ function createEditTool(cwd, options) {
|
|
|
7932
7934
|
if (aborted || signal?.aborted) throw new Error("Operation aborted");
|
|
7933
7935
|
};
|
|
7934
7936
|
try {
|
|
7935
|
-
await
|
|
7937
|
+
await fs10.access(absolutePath);
|
|
7936
7938
|
} catch {
|
|
7937
7939
|
if (signal) signal.removeEventListener("abort", onAbort);
|
|
7938
|
-
|
|
7940
|
+
resolve7(createEditThrownErrorResult(`File not found: ${path12}`, path12));
|
|
7939
7941
|
return;
|
|
7940
7942
|
}
|
|
7941
7943
|
throwIfAborted();
|
|
@@ -7946,8 +7948,8 @@ function createEditTool(cwd, options) {
|
|
|
7946
7948
|
const lastClear = fileObservationState.getLastClear?.();
|
|
7947
7949
|
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
7950
|
if (signal) signal.removeEventListener("abort", onAbort);
|
|
7949
|
-
|
|
7950
|
-
message: `edit_file blocked: ${
|
|
7951
|
+
resolve7(createEditErrorResult({
|
|
7952
|
+
message: `edit_file blocked: ${path12} has not been read in this session.${resetNote}`,
|
|
7951
7953
|
matchKind: "none",
|
|
7952
7954
|
errorReason: "old_text_not_found",
|
|
7953
7955
|
oldTextOccurrences: 0,
|
|
@@ -7958,7 +7960,7 @@ function createEditTool(cwd, options) {
|
|
|
7958
7960
|
return;
|
|
7959
7961
|
}
|
|
7960
7962
|
}
|
|
7961
|
-
const rawContent = await
|
|
7963
|
+
const rawContent = await fs10.readFile(absolutePath, "utf-8");
|
|
7962
7964
|
throwIfAborted();
|
|
7963
7965
|
const { bom, text: content } = stripBom(rawContent);
|
|
7964
7966
|
const originalEnding = detectLineEnding(content);
|
|
@@ -7985,8 +7987,8 @@ function createEditTool(cwd, options) {
|
|
|
7985
7987
|
if (!matchResult.found) {
|
|
7986
7988
|
if (matchResult.exhausted) {
|
|
7987
7989
|
if (signal) signal.removeEventListener("abort", onAbort);
|
|
7988
|
-
|
|
7989
|
-
message: `Could not match edit ${editIndex + 1} in ${
|
|
7990
|
+
resolve7(createEditErrorResult({
|
|
7991
|
+
message: `Could not match edit ${editIndex + 1} in ${path12} within the relaxed-match budget.`,
|
|
7990
7992
|
matchKind: "none",
|
|
7991
7993
|
errorReason: "match_budget_exhausted",
|
|
7992
7994
|
oldTextOccurrences: 0,
|
|
@@ -7997,8 +7999,8 @@ function createEditTool(cwd, options) {
|
|
|
7997
7999
|
return;
|
|
7998
8000
|
}
|
|
7999
8001
|
if (signal) signal.removeEventListener("abort", onAbort);
|
|
8000
|
-
|
|
8001
|
-
message: `Could not find oldText for edit ${editIndex + 1} in ${
|
|
8002
|
+
resolve7(createEditErrorResult({
|
|
8003
|
+
message: `Could not find oldText for edit ${editIndex + 1} in ${path12}.`,
|
|
8002
8004
|
matchKind: "none",
|
|
8003
8005
|
errorReason: "old_text_not_found",
|
|
8004
8006
|
oldTextOccurrences: 0,
|
|
@@ -8013,8 +8015,8 @@ function createEditTool(cwd, options) {
|
|
|
8013
8015
|
}
|
|
8014
8016
|
if (matchResult.occurrences > 1 && !replacement.replaceAll) {
|
|
8015
8017
|
if (signal) signal.removeEventListener("abort", onAbort);
|
|
8016
|
-
|
|
8017
|
-
message: `Found ${matchResult.occurrences}${matchResult.occurrencesAtLeast ? " or more" : ""} occurrences for edit ${editIndex + 1} in ${
|
|
8018
|
+
resolve7(createEditErrorResult({
|
|
8019
|
+
message: `Found ${matchResult.occurrences}${matchResult.occurrencesAtLeast ? " or more" : ""} occurrences for edit ${editIndex + 1} in ${path12}.`,
|
|
8018
8020
|
matchKind: matchResult.matchKind,
|
|
8019
8021
|
errorReason: "old_text_not_unique",
|
|
8020
8022
|
oldTextOccurrences: matchResult.occurrences,
|
|
@@ -8030,8 +8032,8 @@ function createEditTool(cwd, options) {
|
|
|
8030
8032
|
);
|
|
8031
8033
|
if (changingMatches.length === 0) {
|
|
8032
8034
|
if (signal) signal.removeEventListener("abort", onAbort);
|
|
8033
|
-
|
|
8034
|
-
message: `No changes made for edit ${editIndex + 1} in ${
|
|
8035
|
+
resolve7(createEditErrorResult({
|
|
8036
|
+
message: `No changes made for edit ${editIndex + 1} in ${path12}. Its replacement matches the current file content.`,
|
|
8035
8037
|
matchKind: matchResult.matchKind,
|
|
8036
8038
|
errorReason: "replacement_no_change",
|
|
8037
8039
|
oldTextOccurrences: matchResult.occurrences,
|
|
@@ -8052,9 +8054,9 @@ function createEditTool(cwd, options) {
|
|
|
8052
8054
|
throwIfAborted();
|
|
8053
8055
|
if (workingContent === normalizedContent) {
|
|
8054
8056
|
if (signal) signal.removeEventListener("abort", onAbort);
|
|
8055
|
-
|
|
8057
|
+
resolve7(
|
|
8056
8058
|
createEditErrorResult({
|
|
8057
|
-
message: `No changes made to ${
|
|
8059
|
+
message: `No changes made to ${path12}. The replacement produced identical content.`,
|
|
8058
8060
|
matchKind: plannedKinds.size === 1 ? [...plannedKinds][0] : "mixed",
|
|
8059
8061
|
errorReason: "replacement_no_change",
|
|
8060
8062
|
oldTextOccurrences: totalOldOccurrences,
|
|
@@ -8072,12 +8074,12 @@ function createEditTool(cwd, options) {
|
|
|
8072
8074
|
const diffResult = generateDiffString(normalizedContent, newContent);
|
|
8073
8075
|
throwIfAborted();
|
|
8074
8076
|
committing = true;
|
|
8075
|
-
await
|
|
8077
|
+
await fs10.writeFile(absolutePath, finalContent, "utf-8");
|
|
8076
8078
|
if (signal) signal.removeEventListener("abort", onAbort);
|
|
8077
8079
|
let diagnosticWarning;
|
|
8078
8080
|
try {
|
|
8079
8081
|
if (usesExternalFileObservationState) {
|
|
8080
|
-
const writtenStat = await
|
|
8082
|
+
const writtenStat = await fs10.stat(absolutePath);
|
|
8081
8083
|
const snapshot = snapshotFromStatAndContent(writtenStat, finalContent);
|
|
8082
8084
|
fileObservationState.invalidate(absolutePath);
|
|
8083
8085
|
fileObservationState.recordTextRead(
|
|
@@ -8096,10 +8098,10 @@ function createEditTool(cwd, options) {
|
|
|
8096
8098
|
diagnosticWarning = "Edit saved, but file observation refresh failed; read the file before the next edit.";
|
|
8097
8099
|
}
|
|
8098
8100
|
const matchKind = plannedKinds.size === 1 ? [...plannedKinds][0] : "mixed";
|
|
8099
|
-
const visible = boundEditOutput(`Changed ${
|
|
8101
|
+
const visible = boundEditOutput(`Changed ${path12}: ${replacements.length} edit block${replacements.length === 1 ? "" : "s"}, ${replacedOccurrences} replacement${replacedOccurrences === 1 ? "" : "s"}. First changed line: ${diffResult.firstChangedLine}.
|
|
8100
8102
|
${diagnosticWarning ?? ""}
|
|
8101
8103
|
${diffResult.diff}`);
|
|
8102
|
-
|
|
8104
|
+
resolve7({
|
|
8103
8105
|
content: [
|
|
8104
8106
|
{
|
|
8105
8107
|
type: "text",
|
|
@@ -8110,7 +8112,7 @@ ${diffResult.diff}`);
|
|
|
8110
8112
|
status: "success",
|
|
8111
8113
|
matchKind,
|
|
8112
8114
|
changed: true,
|
|
8113
|
-
path:
|
|
8115
|
+
path: path12,
|
|
8114
8116
|
diff: diffResult.diff,
|
|
8115
8117
|
diffTruncated: diffResult.truncated,
|
|
8116
8118
|
contentTruncated: visible.truncated,
|
|
@@ -8134,7 +8136,7 @@ ${diffResult.diff}`);
|
|
|
8134
8136
|
reject(error);
|
|
8135
8137
|
return;
|
|
8136
8138
|
}
|
|
8137
|
-
|
|
8139
|
+
resolve7(createEditThrownErrorResult(message, path12));
|
|
8138
8140
|
}
|
|
8139
8141
|
}
|
|
8140
8142
|
})();
|
|
@@ -8147,7 +8149,7 @@ ${diffResult.diff}`);
|
|
|
8147
8149
|
var DEFAULT_LIMIT = 500;
|
|
8148
8150
|
var MAX_RESULT_LIMIT = 1e4;
|
|
8149
8151
|
function createLsTool(cwd, options) {
|
|
8150
|
-
const
|
|
8152
|
+
const fs10 = getFileSystem();
|
|
8151
8153
|
const rootSchema = buildRootParameterSchema(cwd, options);
|
|
8152
8154
|
const lsSchema = Type.Object({
|
|
8153
8155
|
path: Type.Optional(Type.String({ description: "Directory to list (default: workspace root). Example: 'Scripts' or 'Data'." })),
|
|
@@ -8162,7 +8164,7 @@ function createLsTool(cwd, options) {
|
|
|
8162
8164
|
parameters: lsSchema,
|
|
8163
8165
|
execute: async (_toolCallId, rawParams, signal) => {
|
|
8164
8166
|
const params = rawParams ?? {};
|
|
8165
|
-
return new Promise((
|
|
8167
|
+
return new Promise((resolve7, reject) => {
|
|
8166
8168
|
if (signal?.aborted) {
|
|
8167
8169
|
reject(new Error("Operation aborted"));
|
|
8168
8170
|
return;
|
|
@@ -8181,14 +8183,14 @@ function createLsTool(cwd, options) {
|
|
|
8181
8183
|
if (!Number.isInteger(effectiveLimit) || effectiveLimit < 1 || effectiveLimit > MAX_RESULT_LIMIT) {
|
|
8182
8184
|
throw new Error(`Invalid list_dir arguments: limit must be between 1 and ${MAX_RESULT_LIMIT}.`);
|
|
8183
8185
|
}
|
|
8184
|
-
if (!await
|
|
8186
|
+
if (!await fs10.exists(targetPath)) {
|
|
8185
8187
|
reject(new Error(`Path not found: ${targetPath}`));
|
|
8186
8188
|
return;
|
|
8187
8189
|
}
|
|
8188
8190
|
let entries;
|
|
8189
8191
|
let directoryLimitReached = false;
|
|
8190
8192
|
try {
|
|
8191
|
-
const directoryRead = await
|
|
8193
|
+
const directoryRead = await fs10.readDirectoryBounded(targetPath, MAX_RESULT_LIMIT, signal);
|
|
8192
8194
|
entries = directoryRead.entries;
|
|
8193
8195
|
directoryLimitReached = directoryRead.limitReached;
|
|
8194
8196
|
} catch (e) {
|
|
@@ -8212,13 +8214,13 @@ function createLsTool(cwd, options) {
|
|
|
8212
8214
|
entryLimitReached = true;
|
|
8213
8215
|
break;
|
|
8214
8216
|
}
|
|
8215
|
-
const fullPath =
|
|
8217
|
+
const fullPath = fs10.join(targetPath, entry);
|
|
8216
8218
|
let suffix = "";
|
|
8217
8219
|
try {
|
|
8218
|
-
const linkStat =
|
|
8220
|
+
const linkStat = fs10.lstatSync?.(fullPath);
|
|
8219
8221
|
if (linkStat?.isSymbolicLink) {
|
|
8220
8222
|
suffix = "@";
|
|
8221
|
-
} else if ((linkStat ?? await
|
|
8223
|
+
} else if ((linkStat ?? await fs10.stat(fullPath)).isDirectory) {
|
|
8222
8224
|
suffix = "/";
|
|
8223
8225
|
}
|
|
8224
8226
|
} catch {
|
|
@@ -8231,7 +8233,7 @@ function createLsTool(cwd, options) {
|
|
|
8231
8233
|
if (results.length === 0) {
|
|
8232
8234
|
const listingIncomplete = skippedEntry || entryLimitReached;
|
|
8233
8235
|
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
|
-
|
|
8236
|
+
resolve7({
|
|
8235
8237
|
content: [{ type: "text", text: emptyText }],
|
|
8236
8238
|
details: listingIncomplete ? {
|
|
8237
8239
|
listingIncomplete: true,
|
|
@@ -8262,7 +8264,7 @@ function createLsTool(cwd, options) {
|
|
|
8262
8264
|
|
|
8263
8265
|
[${notices.join(". ")}]`;
|
|
8264
8266
|
}
|
|
8265
|
-
|
|
8267
|
+
resolve7({
|
|
8266
8268
|
content: [{ type: "text", text: output }],
|
|
8267
8269
|
details: Object.keys(details).length > 0 ? details : void 0
|
|
8268
8270
|
});
|
|
@@ -8344,17 +8346,17 @@ function parseGitignore(content) {
|
|
|
8344
8346
|
function createEmptyGitignoreMatcher(incomplete = false) {
|
|
8345
8347
|
return Object.assign((_relativePath, _isDirectory) => false, { incomplete, hasRules: false });
|
|
8346
8348
|
}
|
|
8347
|
-
async function loadGitignoreMatcher(rootPath,
|
|
8349
|
+
async function loadGitignoreMatcher(rootPath, fs10, options) {
|
|
8348
8350
|
let rules = [];
|
|
8349
8351
|
let incomplete = false;
|
|
8350
|
-
const filepath =
|
|
8352
|
+
const filepath = fs10.join(rootPath, ".gitignore");
|
|
8351
8353
|
try {
|
|
8352
8354
|
if (options?.signal?.aborted) throw new Error("Operation aborted");
|
|
8353
|
-
if (!await
|
|
8355
|
+
if (!await fs10.exists(filepath)) return createEmptyGitignoreMatcher();
|
|
8354
8356
|
options?.validatePath?.(filepath);
|
|
8355
|
-
const stat = await
|
|
8357
|
+
const stat = await fs10.stat(filepath);
|
|
8356
8358
|
if (!stat.isFile || stat.size > MAX_GITIGNORE_BYTES) return createEmptyGitignoreMatcher(true);
|
|
8357
|
-
const bytes = await
|
|
8359
|
+
const bytes = await fs10.readFilePrefix(filepath, MAX_GITIGNORE_BYTES + 1);
|
|
8358
8360
|
if (options?.signal?.aborted) throw new Error("Operation aborted");
|
|
8359
8361
|
if (bytes.byteLength > MAX_GITIGNORE_BYTES) return createEmptyGitignoreMatcher(true);
|
|
8360
8362
|
const parsed = parseGitignore(new TextDecoder().decode(bytes));
|
|
@@ -10438,8 +10440,8 @@ function waitForFileCompletion(requestId) {
|
|
|
10438
10440
|
if (existing) {
|
|
10439
10441
|
return Promise.resolve(existing);
|
|
10440
10442
|
}
|
|
10441
|
-
return new Promise((
|
|
10442
|
-
store.waiters.set(requestId,
|
|
10443
|
+
return new Promise((resolve7) => {
|
|
10444
|
+
store.waiters.set(requestId, resolve7);
|
|
10443
10445
|
});
|
|
10444
10446
|
}
|
|
10445
10447
|
async function runNativeGrep(searchPath, pattern, globPattern, ignoreCase, literal, contextLines, limit, outputMode, offset, signal) {
|
|
@@ -10557,7 +10559,7 @@ function sortFileSummariesByMtime(files) {
|
|
|
10557
10559
|
return left.relativePath.localeCompare(right.relativePath);
|
|
10558
10560
|
});
|
|
10559
10561
|
}
|
|
10560
|
-
async function collectFilesForGrep(dirPath, globPattern,
|
|
10562
|
+
async function collectFilesForGrep(dirPath, globPattern, fs10, isGitignored = createEmptyGitignoreMatcher(), assertReadablePath = (path12) => path12, signal, fileGlobMatcher) {
|
|
10561
10563
|
const matchesGlob = globPattern === void 0 ? void 0 : fileGlobMatcher ?? createGrepGlobMatcher(globPattern);
|
|
10562
10564
|
const files = [];
|
|
10563
10565
|
const queue = [{ dir: dirPath, relPrefix: "" }];
|
|
@@ -10572,7 +10574,7 @@ async function collectFilesForGrep(dirPath, globPattern, fs9, isGitignored = cre
|
|
|
10572
10574
|
if (signal?.aborted) throw new Error("Operation aborted");
|
|
10573
10575
|
const { dir: requestedDir, relPrefix } = queue.pop();
|
|
10574
10576
|
const dir = assertReadablePath(requestedDir);
|
|
10575
|
-
const canonicalDir =
|
|
10577
|
+
const canonicalDir = fs10.realpathSync ? fs10.normalize(fs10.realpathSync(dir)) : fs10.normalize(dir);
|
|
10576
10578
|
if (visitedDirectories.has(canonicalDir)) continue;
|
|
10577
10579
|
visitedDirectories.add(canonicalDir);
|
|
10578
10580
|
if (++scannedDirectories > maxScannedDirectories) {
|
|
@@ -10583,7 +10585,7 @@ async function collectFilesForGrep(dirPath, globPattern, fs9, isGitignored = cre
|
|
|
10583
10585
|
}
|
|
10584
10586
|
let entries;
|
|
10585
10587
|
try {
|
|
10586
|
-
const directoryRead = await
|
|
10588
|
+
const directoryRead = await fs10.readDirectoryBounded(dir, maxDirectoryEntries, signal);
|
|
10587
10589
|
entries = directoryRead.entries.slice().sort((left, right) => left.localeCompare(right));
|
|
10588
10590
|
if (directoryRead.limitReached) {
|
|
10589
10591
|
incomplete = true;
|
|
@@ -10596,12 +10598,12 @@ async function collectFilesForGrep(dirPath, globPattern, fs9, isGitignored = cre
|
|
|
10596
10598
|
}
|
|
10597
10599
|
for (const entry of entries) {
|
|
10598
10600
|
if (signal?.aborted) throw new Error("Operation aborted");
|
|
10599
|
-
const requestedPath =
|
|
10601
|
+
const requestedPath = fs10.join(dir, entry);
|
|
10600
10602
|
const fullPath = assertReadablePath(requestedPath);
|
|
10601
10603
|
const relPath = relPrefix ? `${relPrefix}/${entry}` : entry;
|
|
10602
10604
|
let stat;
|
|
10603
10605
|
try {
|
|
10604
|
-
stat = await
|
|
10606
|
+
stat = await fs10.stat(fullPath);
|
|
10605
10607
|
} catch {
|
|
10606
10608
|
incomplete = true;
|
|
10607
10609
|
continue;
|
|
@@ -10616,7 +10618,7 @@ async function collectFilesForGrep(dirPath, globPattern, fs9, isGitignored = cre
|
|
|
10616
10618
|
}
|
|
10617
10619
|
} else if (stat.isFile) {
|
|
10618
10620
|
if (isGitignored(relPath, false)) continue;
|
|
10619
|
-
const ext2 =
|
|
10621
|
+
const ext2 = fs10.extname(entry).toLowerCase();
|
|
10620
10622
|
if (BINARY_EXTENSIONS.has(ext2)) continue;
|
|
10621
10623
|
if (matchesGlob && !matchesGlob(relPath)) continue;
|
|
10622
10624
|
files.push(fullPath);
|
|
@@ -10627,7 +10629,7 @@ async function collectFilesForGrep(dirPath, globPattern, fs9, isGitignored = cre
|
|
|
10627
10629
|
return { files, truncated: traversalTruncated, incomplete, ...safetyLimit ? { safetyLimit } : {} };
|
|
10628
10630
|
}
|
|
10629
10631
|
function createGrepTextTool(cwd, options) {
|
|
10630
|
-
const
|
|
10632
|
+
const fs10 = getFileSystem();
|
|
10631
10633
|
const platform = detectPlatform();
|
|
10632
10634
|
const rootSchema = buildRootParameterSchema(cwd, options);
|
|
10633
10635
|
const grepSchema = Type.Object({
|
|
@@ -10680,7 +10682,7 @@ function createGrepTextTool(cwd, options) {
|
|
|
10680
10682
|
isError: true
|
|
10681
10683
|
};
|
|
10682
10684
|
}
|
|
10683
|
-
return new Promise((
|
|
10685
|
+
return new Promise((resolve7, reject) => {
|
|
10684
10686
|
if (signal?.aborted) {
|
|
10685
10687
|
reject(new Error("Operation aborted"));
|
|
10686
10688
|
return;
|
|
@@ -10698,10 +10700,10 @@ function createGrepTextTool(cwd, options) {
|
|
|
10698
10700
|
const ctx = Math.min(normalizeNonNegativeInteger(contextLines, 0, "context"), MAX_GREP_CONTEXT_LINES);
|
|
10699
10701
|
let isDir;
|
|
10700
10702
|
try {
|
|
10701
|
-
const stat = await
|
|
10703
|
+
const stat = await fs10.stat(searchPath);
|
|
10702
10704
|
isDir = stat.isDirectory;
|
|
10703
10705
|
} catch {
|
|
10704
|
-
|
|
10706
|
+
resolve7({
|
|
10705
10707
|
content: [{ type: "text", text: `grep_text failed: Path not found: ${searchPath}
|
|
10706
10708
|
Check the path or search from the workspace root.` }],
|
|
10707
10709
|
details: { searchIncomplete: true, safetyLimit: "io_error" },
|
|
@@ -10709,7 +10711,7 @@ Check the path or search from the workspace root.` }],
|
|
|
10709
10711
|
});
|
|
10710
10712
|
return;
|
|
10711
10713
|
}
|
|
10712
|
-
const isGitignored = await loadGitignoreMatcher(searchPath,
|
|
10714
|
+
const isGitignored = await loadGitignoreMatcher(searchPath, fs10, {
|
|
10713
10715
|
signal,
|
|
10714
10716
|
validatePath: (candidate) => resolveToCwd(candidate, cwd, options, root)
|
|
10715
10717
|
});
|
|
@@ -10732,7 +10734,7 @@ Check the path or search from the workspace root.` }],
|
|
|
10732
10734
|
} else {
|
|
10733
10735
|
}
|
|
10734
10736
|
} catch (e) {
|
|
10735
|
-
|
|
10737
|
+
resolve7({
|
|
10736
10738
|
content: [{ type: "text", text: boundedErrorMessage("grep_text failed: invalid regex pattern", e, "Use literal=true for plain text, or simplify the regex.") }],
|
|
10737
10739
|
details: { searchIncomplete: true, safetyLimit: "io_error" },
|
|
10738
10740
|
isError: true
|
|
@@ -10785,7 +10787,7 @@ Check the path or search from the workspace root.` }],
|
|
|
10785
10787
|
const collection = await collectFilesForGrep(
|
|
10786
10788
|
searchPath,
|
|
10787
10789
|
globPattern,
|
|
10788
|
-
|
|
10790
|
+
fs10,
|
|
10789
10791
|
isGitignored,
|
|
10790
10792
|
(filePath) => resolveToCwd(filePath, cwd, options, root),
|
|
10791
10793
|
signal,
|
|
@@ -10809,7 +10811,7 @@ Check the path or search from the workspace root.` }],
|
|
|
10809
10811
|
let content;
|
|
10810
10812
|
let fileStatBefore;
|
|
10811
10813
|
try {
|
|
10812
|
-
fileStatBefore = await
|
|
10814
|
+
fileStatBefore = await fs10.stat(filePath);
|
|
10813
10815
|
if (textBytesScanned + fileStatBefore.size > MAX_TEXT_GREP_TOTAL_BYTES) {
|
|
10814
10816
|
skippedUnboundedFile = true;
|
|
10815
10817
|
safetyLimit = "total_bytes";
|
|
@@ -10821,7 +10823,7 @@ Check the path or search from the workspace root.` }],
|
|
|
10821
10823
|
safetyLimit ??= "file_size";
|
|
10822
10824
|
continue;
|
|
10823
10825
|
}
|
|
10824
|
-
const inspected = await
|
|
10826
|
+
const inspected = await fs10.readTextRange(filePath, {
|
|
10825
10827
|
offsetLine: 0,
|
|
10826
10828
|
maxOutputLines: MAX_TEXT_GREP_FILE_LINES,
|
|
10827
10829
|
maxOutputBytes: MAX_TEXT_GREP_FILE_BYTES
|
|
@@ -10849,7 +10851,7 @@ Check the path or search from the workspace root.` }],
|
|
|
10849
10851
|
continue;
|
|
10850
10852
|
}
|
|
10851
10853
|
const lines = content.replace(/\r\n/g, "\n").replace(/\r/g, "\n").split("\n");
|
|
10852
|
-
const relativePath = isDir ?
|
|
10854
|
+
const relativePath = isDir ? fs10.relative(searchPath, filePath) : fs10.basename(filePath);
|
|
10853
10855
|
filesScanned++;
|
|
10854
10856
|
let fileMatchCount = 0;
|
|
10855
10857
|
const pageMatchLines = [];
|
|
@@ -10878,7 +10880,7 @@ Check the path or search from the workspace root.` }],
|
|
|
10878
10880
|
contentOutputBudgetReached ||= formatted.outputBudgetReached;
|
|
10879
10881
|
}
|
|
10880
10882
|
if (fileMatchCount > 0) {
|
|
10881
|
-
const fileStat = fileStatBefore ?? await
|
|
10883
|
+
const fileStat = fileStatBefore ?? await fs10.stat(filePath);
|
|
10882
10884
|
fileSummaries.set(filePath, {
|
|
10883
10885
|
filePath,
|
|
10884
10886
|
relativePath,
|
|
@@ -10912,7 +10914,7 @@ Check the path or search from the workspace root.` }],
|
|
|
10912
10914
|
signal?.removeEventListener("abort", onAbort);
|
|
10913
10915
|
if (matchCount === 0) {
|
|
10914
10916
|
const incompleteNotice = skippedUnboundedFile ? "\n\n[Search incomplete: a filesystem safety limit was reached. Narrow the path or glob and search again]" : "";
|
|
10915
|
-
|
|
10917
|
+
resolve7({
|
|
10916
10918
|
content: [{ type: "text", text: `No matches found${incompleteNotice}` }],
|
|
10917
10919
|
details: {
|
|
10918
10920
|
noMatches: true,
|
|
@@ -10967,7 +10969,7 @@ Check the path or search from the workspace root.` }],
|
|
|
10967
10969
|
|
|
10968
10970
|
[${notices.join(". ")}]`;
|
|
10969
10971
|
}
|
|
10970
|
-
|
|
10972
|
+
resolve7({
|
|
10971
10973
|
content: [{ type: "text", text: output }],
|
|
10972
10974
|
details: Object.keys(details).length > 0 ? details : void 0
|
|
10973
10975
|
});
|
|
@@ -10977,7 +10979,7 @@ Check the path or search from the workspace root.` }],
|
|
|
10977
10979
|
reject(err);
|
|
10978
10980
|
return;
|
|
10979
10981
|
}
|
|
10980
|
-
|
|
10982
|
+
resolve7({
|
|
10981
10983
|
content: [{ type: "text", text: boundedErrorMessage("grep_text failed", err, "Check the path/pattern, use literal=true for plain text, or narrow the search.") }],
|
|
10982
10984
|
details: { searchIncomplete: true, safetyLimit: "io_error" },
|
|
10983
10985
|
isError: true
|
|
@@ -11054,8 +11056,8 @@ function waitForFileCompletion2(requestId) {
|
|
|
11054
11056
|
if (existing) {
|
|
11055
11057
|
return Promise.resolve(existing);
|
|
11056
11058
|
}
|
|
11057
|
-
return new Promise((
|
|
11058
|
-
store.waiters.set(requestId,
|
|
11059
|
+
return new Promise((resolve7) => {
|
|
11060
|
+
store.waiters.set(requestId, resolve7);
|
|
11059
11061
|
});
|
|
11060
11062
|
}
|
|
11061
11063
|
async function runNativeFind(searchPath, pattern, limit, signal) {
|
|
@@ -11087,7 +11089,7 @@ async function runNativeFind(searchPath, pattern, limit, signal) {
|
|
|
11087
11089
|
bridge.ReleaseRequest(requestId);
|
|
11088
11090
|
}
|
|
11089
11091
|
}
|
|
11090
|
-
async function globFiles(rootPath, matchesPattern,
|
|
11092
|
+
async function globFiles(rootPath, matchesPattern, fs10, limit, signal, isGitignored = createEmptyGitignoreMatcher(), validatePath = () => {
|
|
11091
11093
|
}, incompleteState = { value: false }) {
|
|
11092
11094
|
const results = [];
|
|
11093
11095
|
const queue = [{ dir: rootPath, relPrefix: "" }];
|
|
@@ -11100,7 +11102,7 @@ async function globFiles(rootPath, matchesPattern, fs9, limit, signal, isGitigno
|
|
|
11100
11102
|
}
|
|
11101
11103
|
const { dir, relPrefix } = queue.shift();
|
|
11102
11104
|
validatePath(dir);
|
|
11103
|
-
const canonicalDir =
|
|
11105
|
+
const canonicalDir = fs10.realpathSync ? fs10.normalize(fs10.realpathSync(dir)) : fs10.normalize(dir);
|
|
11104
11106
|
if (visitedDirectories.has(canonicalDir)) continue;
|
|
11105
11107
|
visitedDirectories.add(canonicalDir);
|
|
11106
11108
|
if (++scannedDirectories > MAX_SCANNED_DIRECTORIES) {
|
|
@@ -11109,7 +11111,7 @@ async function globFiles(rootPath, matchesPattern, fs9, limit, signal, isGitigno
|
|
|
11109
11111
|
}
|
|
11110
11112
|
let entries;
|
|
11111
11113
|
try {
|
|
11112
|
-
const directoryRead = await
|
|
11114
|
+
const directoryRead = await fs10.readDirectoryBounded(dir, MAX_DIRECTORY_ENTRIES, signal);
|
|
11113
11115
|
entries = directoryRead.entries;
|
|
11114
11116
|
if (directoryRead.limitReached) incompleteState.value = true;
|
|
11115
11117
|
} catch {
|
|
@@ -11119,12 +11121,12 @@ async function globFiles(rootPath, matchesPattern, fs9, limit, signal, isGitigno
|
|
|
11119
11121
|
for (const entry of entries) {
|
|
11120
11122
|
if (signal?.aborted) throw new Error("Operation aborted");
|
|
11121
11123
|
if (results.length >= limit) break;
|
|
11122
|
-
const fullPath =
|
|
11124
|
+
const fullPath = fs10.join(dir, entry);
|
|
11123
11125
|
const relPath = relPrefix ? relPrefix + "/" + entry : entry;
|
|
11124
11126
|
validatePath(fullPath);
|
|
11125
11127
|
let stat;
|
|
11126
11128
|
try {
|
|
11127
|
-
stat = await
|
|
11129
|
+
stat = await fs10.stat(fullPath);
|
|
11128
11130
|
} catch {
|
|
11129
11131
|
incompleteState.value = true;
|
|
11130
11132
|
continue;
|
|
@@ -11152,7 +11154,7 @@ async function globFiles(rootPath, matchesPattern, fs9, limit, signal, isGitigno
|
|
|
11152
11154
|
return results;
|
|
11153
11155
|
}
|
|
11154
11156
|
function createFindFilesTool(cwd, options) {
|
|
11155
|
-
const
|
|
11157
|
+
const fs10 = getFileSystem();
|
|
11156
11158
|
const platform = detectPlatform();
|
|
11157
11159
|
const rootSchema = buildRootParameterSchema(cwd, options);
|
|
11158
11160
|
const findSchema = Type.Object({
|
|
@@ -11182,7 +11184,7 @@ function createFindFilesTool(cwd, options) {
|
|
|
11182
11184
|
isError: true
|
|
11183
11185
|
};
|
|
11184
11186
|
}
|
|
11185
|
-
return new Promise((
|
|
11187
|
+
return new Promise((resolve7, reject) => {
|
|
11186
11188
|
if (signal?.aborted) {
|
|
11187
11189
|
reject(new Error("Operation aborted"));
|
|
11188
11190
|
return;
|
|
@@ -11196,14 +11198,14 @@ function createFindFilesTool(cwd, options) {
|
|
|
11196
11198
|
resolveToCwd(candidate, cwd, options, root);
|
|
11197
11199
|
};
|
|
11198
11200
|
const validateReturnedPath = (candidate) => {
|
|
11199
|
-
validateResultPath(
|
|
11201
|
+
validateResultPath(fs10.isAbsolute(candidate) ? candidate : fs10.join(searchPath, candidate));
|
|
11200
11202
|
};
|
|
11201
11203
|
const effectiveLimit = limit ?? DEFAULT_LIMIT3;
|
|
11202
11204
|
if (!Number.isInteger(effectiveLimit) || effectiveLimit < 1 || effectiveLimit > MAX_RESULT_LIMIT2) {
|
|
11203
11205
|
throw new Error(`Invalid find_files arguments: limit must be between 1 and ${MAX_RESULT_LIMIT2}.`);
|
|
11204
11206
|
}
|
|
11205
|
-
if (!await
|
|
11206
|
-
|
|
11207
|
+
if (!await fs10.exists(searchPath)) {
|
|
11208
|
+
resolve7({
|
|
11207
11209
|
content: [{ type: "text", text: `find_files failed: Path not found: ${searchPath}
|
|
11208
11210
|
Check the path or search from the workspace root.` }],
|
|
11209
11211
|
details: { searchIncomplete: true },
|
|
@@ -11214,7 +11216,7 @@ Check the path or search from the workspace root.` }],
|
|
|
11214
11216
|
let results;
|
|
11215
11217
|
let resultLimitReached = false;
|
|
11216
11218
|
const incompleteState = { value: false };
|
|
11217
|
-
const isGitignored = await loadGitignoreMatcher(searchPath,
|
|
11219
|
+
const isGitignored = await loadGitignoreMatcher(searchPath, fs10, { signal, validatePath: validateResultPath });
|
|
11218
11220
|
incompleteState.value ||= isGitignored.incomplete;
|
|
11219
11221
|
if (platform === "puerts" && getNativeFileBridge2() && !isGitignored.hasRules) {
|
|
11220
11222
|
const nativeResult = await runNativeFind(searchPath, pattern, effectiveLimit, signal);
|
|
@@ -11227,12 +11229,12 @@ Check the path or search from the workspace root.` }],
|
|
|
11227
11229
|
`[find_files] path=${searchPath} pattern=${pattern} matches=${results.length} dirs=${nativeResult.ScannedDirectories ?? 0} files=${nativeResult.ScannedFiles ?? 0}`
|
|
11228
11230
|
);
|
|
11229
11231
|
} else if (platform === "node") {
|
|
11230
|
-
const allResults = await globFiles(searchPath, matchesPattern,
|
|
11232
|
+
const allResults = await globFiles(searchPath, matchesPattern, fs10, effectiveLimit + 1, signal, isGitignored, validateResultPath, incompleteState);
|
|
11231
11233
|
incompleteState.value ||= isGitignored.incomplete;
|
|
11232
11234
|
resultLimitReached = allResults.length > effectiveLimit;
|
|
11233
11235
|
results = allResults.slice(0, effectiveLimit);
|
|
11234
11236
|
} else {
|
|
11235
|
-
const allResults = await globFiles(searchPath, matchesPattern,
|
|
11237
|
+
const allResults = await globFiles(searchPath, matchesPattern, fs10, effectiveLimit + 1, signal, isGitignored, validateResultPath, incompleteState);
|
|
11236
11238
|
incompleteState.value ||= isGitignored.incomplete;
|
|
11237
11239
|
resultLimitReached = allResults.length > effectiveLimit;
|
|
11238
11240
|
results = allResults.slice(0, effectiveLimit);
|
|
@@ -11240,7 +11242,7 @@ Check the path or search from the workspace root.` }],
|
|
|
11240
11242
|
signal?.removeEventListener("abort", onAbort);
|
|
11241
11243
|
if (results.length === 0) {
|
|
11242
11244
|
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
|
-
|
|
11245
|
+
resolve7({
|
|
11244
11246
|
content: [{ type: "text", text: `No files found matching pattern${incompleteNotice}` }],
|
|
11245
11247
|
details: {
|
|
11246
11248
|
noMatches: true,
|
|
@@ -11269,7 +11271,7 @@ Check the path or search from the workspace root.` }],
|
|
|
11269
11271
|
if (notices.length > 0) {
|
|
11270
11272
|
resultOutput += "\n\n[" + notices.join(". ") + "]";
|
|
11271
11273
|
}
|
|
11272
|
-
|
|
11274
|
+
resolve7({
|
|
11273
11275
|
content: [{ type: "text", text: resultOutput }],
|
|
11274
11276
|
details: Object.keys(details).length > 0 ? details : void 0
|
|
11275
11277
|
});
|
|
@@ -11280,7 +11282,7 @@ Check the path or search from the workspace root.` }],
|
|
|
11280
11282
|
reject(e);
|
|
11281
11283
|
return;
|
|
11282
11284
|
}
|
|
11283
|
-
|
|
11285
|
+
resolve7({
|
|
11284
11286
|
content: [{ type: "text", text: boundedFindError(e) }],
|
|
11285
11287
|
details: { searchIncomplete: true },
|
|
11286
11288
|
isError: true
|
|
@@ -11854,8 +11856,8 @@ function isSearchPageSource(source) {
|
|
|
11854
11856
|
function isHomepageSource(source) {
|
|
11855
11857
|
const parsed = sourceHostAndPath(source);
|
|
11856
11858
|
if (!parsed) return false;
|
|
11857
|
-
const
|
|
11858
|
-
return
|
|
11859
|
+
const path12 = parsed.path.replace(/\/+$/, "");
|
|
11860
|
+
return path12 === "" || path12 === "/news" || path12 === "/sections/news";
|
|
11859
11861
|
}
|
|
11860
11862
|
function evaluateSearchQuality(search) {
|
|
11861
11863
|
const warnings = [];
|
|
@@ -11887,8 +11889,8 @@ async function runQueuedSearch(model, fn) {
|
|
|
11887
11889
|
const key = `${model.provider}/${model.id}`;
|
|
11888
11890
|
const previous = SEARCH_PROVIDER_QUEUE.get(key) ?? Promise.resolve();
|
|
11889
11891
|
let release;
|
|
11890
|
-
const next = new Promise((
|
|
11891
|
-
release =
|
|
11892
|
+
const next = new Promise((resolve7) => {
|
|
11893
|
+
release = resolve7;
|
|
11892
11894
|
});
|
|
11893
11895
|
const queued = previous.catch(() => void 0).then(() => next);
|
|
11894
11896
|
SEARCH_PROVIDER_QUEUE.set(key, queued);
|
|
@@ -12362,10 +12364,10 @@ function assistantText(message) {
|
|
|
12362
12364
|
async function withAbort(promise, signal) {
|
|
12363
12365
|
if (!signal) return promise;
|
|
12364
12366
|
if (signal.aborted) throw signal.reason ?? new Error("operation aborted");
|
|
12365
|
-
return await new Promise((
|
|
12367
|
+
return await new Promise((resolve7, reject) => {
|
|
12366
12368
|
const onAbort = () => reject(signal.reason ?? new Error("operation aborted"));
|
|
12367
12369
|
signal.addEventListener("abort", onAbort, { once: true });
|
|
12368
|
-
promise.then(
|
|
12370
|
+
promise.then(resolve7, reject).finally(() => signal.removeEventListener("abort", onAbort));
|
|
12369
12371
|
});
|
|
12370
12372
|
}
|
|
12371
12373
|
async function cancelResponseBody(response) {
|
|
@@ -12376,13 +12378,13 @@ async function cancelResponseBody(response) {
|
|
|
12376
12378
|
}
|
|
12377
12379
|
var DISCARD_BODY_GRACE_MS = 250;
|
|
12378
12380
|
async function discardResponseBody(response) {
|
|
12379
|
-
await new Promise((
|
|
12381
|
+
await new Promise((resolve7) => {
|
|
12380
12382
|
let settled = false;
|
|
12381
12383
|
const settle = () => {
|
|
12382
12384
|
if (settled) return;
|
|
12383
12385
|
settled = true;
|
|
12384
12386
|
clearTimeout(timer);
|
|
12385
|
-
|
|
12387
|
+
resolve7();
|
|
12386
12388
|
};
|
|
12387
12389
|
const timer = setTimeout(settle, DISCARD_BODY_GRACE_MS);
|
|
12388
12390
|
try {
|
|
@@ -12721,7 +12723,7 @@ function createSharedWebFetchTool(deps = {}) {
|
|
|
12721
12723
|
};
|
|
12722
12724
|
}
|
|
12723
12725
|
|
|
12724
|
-
// ../../packages/shared-headless-capabilities/src/web-research.ts
|
|
12726
|
+
// ../../packages/shared-headless-capabilities/src/web-research-helpers.ts
|
|
12725
12727
|
var webResearchSchema = Type.Object({
|
|
12726
12728
|
query: Type.Optional(Type.String({
|
|
12727
12729
|
minLength: 2,
|
|
@@ -13097,19 +13099,21 @@ async function runWithDeadline(operation, timeoutMs, message, parentSignal) {
|
|
|
13097
13099
|
const child = createChildSignal(parentSignal);
|
|
13098
13100
|
let timer;
|
|
13099
13101
|
try {
|
|
13100
|
-
return await new Promise((
|
|
13102
|
+
return await new Promise((resolve7, reject) => {
|
|
13101
13103
|
timer = setTimeout(() => {
|
|
13102
13104
|
const error = new Error(message);
|
|
13103
13105
|
child.abort(error);
|
|
13104
13106
|
reject(error);
|
|
13105
13107
|
}, timeoutMs);
|
|
13106
|
-
operation(child.signal).then(
|
|
13108
|
+
operation(child.signal).then(resolve7, reject);
|
|
13107
13109
|
});
|
|
13108
13110
|
} finally {
|
|
13109
13111
|
if (timer) clearTimeout(timer);
|
|
13110
13112
|
child.dispose();
|
|
13111
13113
|
}
|
|
13112
13114
|
}
|
|
13115
|
+
|
|
13116
|
+
// ../../packages/shared-headless-capabilities/src/web-research.ts
|
|
13113
13117
|
function createSharedWebResearchTool(deps) {
|
|
13114
13118
|
const initialHealth = deps.loadProviderHealth?.();
|
|
13115
13119
|
const initialCandidates = deps.resolveToolModelCandidates?.("web_search") ?? [];
|
|
@@ -13727,8 +13731,8 @@ function isWithinProject(fileSystem, projectRoot, candidate) {
|
|
|
13727
13731
|
try {
|
|
13728
13732
|
const canonicalRoot = fileSystem.realpath(projectRoot);
|
|
13729
13733
|
const canonicalCandidate = fileSystem.realpath(candidate);
|
|
13730
|
-
const
|
|
13731
|
-
return
|
|
13734
|
+
const relative4 = path3.relative(canonicalRoot, canonicalCandidate);
|
|
13735
|
+
return relative4 !== ".." && !relative4.startsWith(`..${path3.sep}`) && !path3.isAbsolute(relative4);
|
|
13732
13736
|
} catch {
|
|
13733
13737
|
return false;
|
|
13734
13738
|
}
|
|
@@ -17139,13 +17143,236 @@ function readMemoryFile(store, relativePath) {
|
|
|
17139
17143
|
}
|
|
17140
17144
|
}
|
|
17141
17145
|
|
|
17146
|
+
// ../../packages/shared-headless-capabilities/src/memory/wiki-inbox.ts
|
|
17147
|
+
import * as crypto2 from "node:crypto";
|
|
17148
|
+
import * as fs7 from "node:fs";
|
|
17149
|
+
import * as path9 from "node:path";
|
|
17150
|
+
var MAX_WIKI_INBOX_ITEMS = 200;
|
|
17151
|
+
var VALID_KINDS = /* @__PURE__ */ new Set(["fact", "project", "thread"]);
|
|
17152
|
+
var SAFE_ID_RE = /^[a-zA-Z0-9_-]{1,80}$/;
|
|
17153
|
+
function wikiInboxPath(memoryRoot) {
|
|
17154
|
+
return path9.join(memoryRoot, "inbox");
|
|
17155
|
+
}
|
|
17156
|
+
function spoolFileNameForId(id) {
|
|
17157
|
+
const safe = SAFE_ID_RE.test(id) ? id : crypto2.createHash("sha256").update(id).digest("hex").slice(0, 32);
|
|
17158
|
+
return `${safe}.json`;
|
|
17159
|
+
}
|
|
17160
|
+
function spoolFilePathForId(memoryRoot, id) {
|
|
17161
|
+
return path9.join(wikiInboxPath(memoryRoot), spoolFileNameForId(id));
|
|
17162
|
+
}
|
|
17163
|
+
function assertSafeMemoryPath(memoryRoot, targetPath) {
|
|
17164
|
+
const rootAbs = path9.resolve(memoryRoot);
|
|
17165
|
+
const targetAbs = path9.resolve(targetPath);
|
|
17166
|
+
const rel = path9.relative(rootAbs, targetAbs);
|
|
17167
|
+
if (rel.startsWith("..") || path9.isAbsolute(rel)) {
|
|
17168
|
+
throw new Error(`Wiki inbox path escapes memory root: ${targetPath}`);
|
|
17169
|
+
}
|
|
17170
|
+
if (fs7.existsSync(rootAbs) && fs7.lstatSync(rootAbs).isSymbolicLink()) {
|
|
17171
|
+
throw new Error(`Memory root must not be a symlink: ${rootAbs}`);
|
|
17172
|
+
}
|
|
17173
|
+
const rootReal = fs7.existsSync(rootAbs) ? fs7.realpathSync(rootAbs) : rootAbs;
|
|
17174
|
+
const parts = rel.split(path9.sep).filter(Boolean);
|
|
17175
|
+
let cursor = rootAbs;
|
|
17176
|
+
for (const part of parts) {
|
|
17177
|
+
cursor = path9.join(cursor, part);
|
|
17178
|
+
if (!fs7.existsSync(cursor)) continue;
|
|
17179
|
+
const st = fs7.lstatSync(cursor);
|
|
17180
|
+
if (st.isSymbolicLink()) {
|
|
17181
|
+
throw new Error(`Refusing to traverse symlink in wiki inbox: ${cursor}`);
|
|
17182
|
+
}
|
|
17183
|
+
const real = fs7.realpathSync(cursor);
|
|
17184
|
+
const realRel = path9.relative(rootReal, real);
|
|
17185
|
+
if (realRel.startsWith("..") || path9.isAbsolute(realRel)) {
|
|
17186
|
+
throw new Error(`Wiki inbox realpath escapes memory root: ${cursor}`);
|
|
17187
|
+
}
|
|
17188
|
+
}
|
|
17189
|
+
}
|
|
17190
|
+
function writeFileAtomic(memoryRoot, targetPath, content) {
|
|
17191
|
+
assertSafeMemoryPath(memoryRoot, targetPath);
|
|
17192
|
+
const dir = path9.dirname(targetPath);
|
|
17193
|
+
fs7.mkdirSync(dir, { recursive: true, mode: 448 });
|
|
17194
|
+
assertSafeMemoryPath(memoryRoot, dir);
|
|
17195
|
+
const tmp = path9.join(dir, `.item.${process.pid}.${crypto2.randomBytes(6).toString("hex")}.tmp`);
|
|
17196
|
+
const flags = fs7.constants.O_WRONLY | fs7.constants.O_CREAT | fs7.constants.O_EXCL;
|
|
17197
|
+
const fd = fs7.openSync(tmp, flags, 384);
|
|
17198
|
+
try {
|
|
17199
|
+
fs7.writeFileSync(fd, content, "utf8");
|
|
17200
|
+
fs7.fsyncSync(fd);
|
|
17201
|
+
} catch (error) {
|
|
17202
|
+
try {
|
|
17203
|
+
fs7.closeSync(fd);
|
|
17204
|
+
} catch {
|
|
17205
|
+
}
|
|
17206
|
+
try {
|
|
17207
|
+
fs7.unlinkSync(tmp);
|
|
17208
|
+
} catch {
|
|
17209
|
+
}
|
|
17210
|
+
throw error;
|
|
17211
|
+
}
|
|
17212
|
+
fs7.closeSync(fd);
|
|
17213
|
+
try {
|
|
17214
|
+
fs7.renameSync(tmp, targetPath);
|
|
17215
|
+
} catch (error) {
|
|
17216
|
+
try {
|
|
17217
|
+
fs7.unlinkSync(tmp);
|
|
17218
|
+
} catch {
|
|
17219
|
+
}
|
|
17220
|
+
throw error;
|
|
17221
|
+
}
|
|
17222
|
+
}
|
|
17223
|
+
function normalizeInboxItem(raw) {
|
|
17224
|
+
if (!raw || typeof raw !== "object" || Array.isArray(raw)) return null;
|
|
17225
|
+
const obj = raw;
|
|
17226
|
+
const id = typeof obj.id === "string" ? redactText(obj.id).text.trim().slice(0, 80) : "";
|
|
17227
|
+
const kind = typeof obj.kind === "string" && VALID_KINDS.has(obj.kind) ? obj.kind : null;
|
|
17228
|
+
const text = typeof obj.text === "string" ? redactText(obj.text).text.replace(/\s+/g, " ").trim().slice(0, 400) : "";
|
|
17229
|
+
const quote = typeof obj.quote === "string" ? redactText(obj.quote).text.replace(/\s+/g, " ").trim().slice(0, 400) : "";
|
|
17230
|
+
const sessionId = typeof obj.sessionId === "string" && obj.sessionId.trim() ? redactText(obj.sessionId).text.trim().slice(0, 80) : "session-unbound";
|
|
17231
|
+
const date = typeof obj.date === "string" && /^\d{4}-\d{2}-\d{2}$/.test(obj.date.trim()) ? obj.date.trim() : "";
|
|
17232
|
+
const createdAt = typeof obj.createdAt === "number" && Number.isFinite(obj.createdAt) ? obj.createdAt : Date.now();
|
|
17233
|
+
if (!id || !kind || !text || !quote || !date) return null;
|
|
17234
|
+
const projectKey = typeof obj.projectKey === "string" && obj.projectKey.trim() ? redactText(obj.projectKey).text.trim().slice(0, 128) : void 0;
|
|
17235
|
+
const cwd = typeof obj.cwd === "string" && obj.cwd.trim() ? redactText(obj.cwd).text.trim().slice(0, 512) : void 0;
|
|
17236
|
+
return {
|
|
17237
|
+
id,
|
|
17238
|
+
kind,
|
|
17239
|
+
text,
|
|
17240
|
+
quote,
|
|
17241
|
+
sessionId,
|
|
17242
|
+
date,
|
|
17243
|
+
...projectKey ? { projectKey } : {},
|
|
17244
|
+
...cwd ? { cwd } : {},
|
|
17245
|
+
createdAt
|
|
17246
|
+
};
|
|
17247
|
+
}
|
|
17248
|
+
function dedupeKey(item) {
|
|
17249
|
+
return `${item.kind}\0${item.text}\0${item.projectKey ?? ""}\0${item.cwd ?? ""}`;
|
|
17250
|
+
}
|
|
17251
|
+
function readWikiInbox(memoryRoot) {
|
|
17252
|
+
const dir = wikiInboxPath(memoryRoot);
|
|
17253
|
+
assertSafeMemoryPath(memoryRoot, dir);
|
|
17254
|
+
if (!fs7.existsSync(dir)) return [];
|
|
17255
|
+
let entries;
|
|
17256
|
+
try {
|
|
17257
|
+
entries = fs7.readdirSync(dir);
|
|
17258
|
+
} catch {
|
|
17259
|
+
return [];
|
|
17260
|
+
}
|
|
17261
|
+
const items = [];
|
|
17262
|
+
const seenIds = /* @__PURE__ */ new Set();
|
|
17263
|
+
for (const entry of entries) {
|
|
17264
|
+
if (!entry.endsWith(".json") || entry.startsWith(".")) continue;
|
|
17265
|
+
const fullPath = path9.join(dir, entry);
|
|
17266
|
+
assertSafeMemoryPath(memoryRoot, fullPath);
|
|
17267
|
+
try {
|
|
17268
|
+
const parsed = normalizeInboxItem(JSON.parse(fs7.readFileSync(fullPath, "utf8")));
|
|
17269
|
+
if (!parsed || seenIds.has(parsed.id)) continue;
|
|
17270
|
+
seenIds.add(parsed.id);
|
|
17271
|
+
items.push(parsed);
|
|
17272
|
+
} catch {
|
|
17273
|
+
}
|
|
17274
|
+
}
|
|
17275
|
+
items.sort((a, b) => a.createdAt - b.createdAt || a.id.localeCompare(b.id));
|
|
17276
|
+
return items;
|
|
17277
|
+
}
|
|
17278
|
+
function countWikiInbox(memoryRoot) {
|
|
17279
|
+
try {
|
|
17280
|
+
return readWikiInbox(memoryRoot).length;
|
|
17281
|
+
} catch {
|
|
17282
|
+
return 0;
|
|
17283
|
+
}
|
|
17284
|
+
}
|
|
17285
|
+
function appendWikiInboxItem(memoryRoot, input) {
|
|
17286
|
+
const item = normalizeInboxItem(input);
|
|
17287
|
+
if (!item) return false;
|
|
17288
|
+
const target = spoolFilePathForId(memoryRoot, item.id);
|
|
17289
|
+
writeFileAtomic(memoryRoot, target, JSON.stringify(item) + "\n");
|
|
17290
|
+
try {
|
|
17291
|
+
const existing = readWikiInbox(memoryRoot);
|
|
17292
|
+
const key = dedupeKey(item);
|
|
17293
|
+
const toRemove = [];
|
|
17294
|
+
for (const entry of existing) {
|
|
17295
|
+
if (entry.id !== item.id && dedupeKey(entry) === key) {
|
|
17296
|
+
toRemove.push(entry.id);
|
|
17297
|
+
}
|
|
17298
|
+
}
|
|
17299
|
+
const remaining = existing.filter((entry) => !toRemove.includes(entry.id));
|
|
17300
|
+
if (remaining.length > MAX_WIKI_INBOX_ITEMS) {
|
|
17301
|
+
const overflow = remaining.length - MAX_WIKI_INBOX_ITEMS;
|
|
17302
|
+
for (const old of remaining.slice(0, overflow)) {
|
|
17303
|
+
if (old.id !== item.id) toRemove.push(old.id);
|
|
17304
|
+
}
|
|
17305
|
+
}
|
|
17306
|
+
if (toRemove.length > 0) removeWikiInboxItems(memoryRoot, toRemove);
|
|
17307
|
+
} catch {
|
|
17308
|
+
}
|
|
17309
|
+
return true;
|
|
17310
|
+
}
|
|
17311
|
+
function removeWikiInboxItems(memoryRoot, ids) {
|
|
17312
|
+
const drop = ids instanceof Set ? ids : new Set(ids);
|
|
17313
|
+
if (drop.size === 0) return 0;
|
|
17314
|
+
const dir = wikiInboxPath(memoryRoot);
|
|
17315
|
+
assertSafeMemoryPath(memoryRoot, dir);
|
|
17316
|
+
if (!fs7.existsSync(dir)) return 0;
|
|
17317
|
+
let removed = 0;
|
|
17318
|
+
for (const id of drop) {
|
|
17319
|
+
const target = spoolFilePathForId(memoryRoot, id);
|
|
17320
|
+
assertSafeMemoryPath(memoryRoot, target);
|
|
17321
|
+
try {
|
|
17322
|
+
fs7.unlinkSync(target);
|
|
17323
|
+
removed += 1;
|
|
17324
|
+
} catch (error) {
|
|
17325
|
+
if (error.code !== "ENOENT") {
|
|
17326
|
+
throw error;
|
|
17327
|
+
}
|
|
17328
|
+
}
|
|
17329
|
+
}
|
|
17330
|
+
return removed;
|
|
17331
|
+
}
|
|
17332
|
+
function wikiInboxItemToDreamSignal(item, wikiStore) {
|
|
17333
|
+
const existingPage = wikiStore.findProjectPage(item.projectKey ? [item.projectKey] : void 0, item.cwd);
|
|
17334
|
+
const slugFromCwd = item.cwd ? slugifyWikiName(path9.basename(item.cwd)) : null;
|
|
17335
|
+
const projectSlug = existingPage ? path9.basename(existingPage.relPath, ".md") : slugFromCwd ?? void 0;
|
|
17336
|
+
if (item.kind === "project") {
|
|
17337
|
+
return {
|
|
17338
|
+
kind: "project-state",
|
|
17339
|
+
target: projectSlug ?? "ops",
|
|
17340
|
+
text: item.text,
|
|
17341
|
+
quote: item.quote,
|
|
17342
|
+
sessionId: item.sessionId,
|
|
17343
|
+
date: item.date,
|
|
17344
|
+
...item.projectKey ? { projectKey: item.projectKey } : {}
|
|
17345
|
+
};
|
|
17346
|
+
}
|
|
17347
|
+
if (item.kind === "thread") {
|
|
17348
|
+
return {
|
|
17349
|
+
kind: "open-thread",
|
|
17350
|
+
target: projectSlug ?? "threads",
|
|
17351
|
+
text: item.text,
|
|
17352
|
+
quote: item.quote,
|
|
17353
|
+
sessionId: item.sessionId,
|
|
17354
|
+
date: item.date,
|
|
17355
|
+
...item.projectKey ? { projectKey: item.projectKey } : {}
|
|
17356
|
+
};
|
|
17357
|
+
}
|
|
17358
|
+
return {
|
|
17359
|
+
kind: "ops-state",
|
|
17360
|
+
target: "ops",
|
|
17361
|
+
text: item.text,
|
|
17362
|
+
quote: item.quote,
|
|
17363
|
+
sessionId: item.sessionId,
|
|
17364
|
+
date: item.date,
|
|
17365
|
+
...item.projectKey ? { projectKey: item.projectKey } : {}
|
|
17366
|
+
};
|
|
17367
|
+
}
|
|
17368
|
+
|
|
17142
17369
|
// ../../packages/shared-headless-capabilities/src/memory/wiki-dream.ts
|
|
17143
|
-
import * as
|
|
17144
|
-
import * as
|
|
17370
|
+
import * as fs9 from "node:fs";
|
|
17371
|
+
import * as path11 from "node:path";
|
|
17145
17372
|
|
|
17146
17373
|
// ../../packages/shared-headless-capabilities/src/memory/wiki-dream-gc.ts
|
|
17147
|
-
import * as
|
|
17148
|
-
import * as
|
|
17374
|
+
import * as fs8 from "node:fs";
|
|
17375
|
+
import * as path10 from "node:path";
|
|
17149
17376
|
function extractJsonObject(raw) {
|
|
17150
17377
|
const start = raw.indexOf("{");
|
|
17151
17378
|
const end = raw.lastIndexOf("}");
|
|
@@ -17242,13 +17469,13 @@ async function runWikiGc(deps) {
|
|
|
17242
17469
|
let effectiveTs = updatedTs;
|
|
17243
17470
|
if (!Number.isFinite(effectiveTs)) {
|
|
17244
17471
|
try {
|
|
17245
|
-
effectiveTs =
|
|
17472
|
+
effectiveTs = fs8.statSync(wikiStore.resolvePath(relPath)).mtimeMs;
|
|
17246
17473
|
} catch {
|
|
17247
17474
|
effectiveTs = now;
|
|
17248
17475
|
}
|
|
17249
17476
|
}
|
|
17250
17477
|
if (effectiveTs < cutoffMs) {
|
|
17251
|
-
const slug =
|
|
17478
|
+
const slug = path10.basename(relPath, ".md");
|
|
17252
17479
|
if (wikiStore.archiveProjectPage(slug)) {
|
|
17253
17480
|
archivedInactive.push(slug);
|
|
17254
17481
|
summaries.push(`archived inactive project ${slug} (last updated ${dayOf(effectiveTs)})`);
|
|
@@ -17486,45 +17713,45 @@ async function validateOrRepairUpdates(updates, call, limits, options = {}) {
|
|
|
17486
17713
|
function readLegacyContextForBootstrap(memoryRoot) {
|
|
17487
17714
|
const safeRead = (p, maxChars) => {
|
|
17488
17715
|
try {
|
|
17489
|
-
const raw =
|
|
17716
|
+
const raw = fs9.readFileSync(p, "utf8");
|
|
17490
17717
|
return redactText(raw).text.slice(0, maxChars);
|
|
17491
17718
|
} catch {
|
|
17492
17719
|
return "";
|
|
17493
17720
|
}
|
|
17494
17721
|
};
|
|
17495
|
-
const memoryMd = safeRead(
|
|
17496
|
-
const threadsMd = safeRead(
|
|
17497
|
-
const userMd = safeRead(
|
|
17722
|
+
const memoryMd = safeRead(path11.join(memoryRoot, "MEMORY.md"), 18e3);
|
|
17723
|
+
const threadsMd = safeRead(path11.join(memoryRoot, "THREADS.md"), 6e3);
|
|
17724
|
+
const userMd = safeRead(path11.join(memoryRoot, "USER.md"), 3e3);
|
|
17498
17725
|
const projects = [];
|
|
17499
|
-
const projectsRoot =
|
|
17500
|
-
if (
|
|
17501
|
-
for (const key of
|
|
17502
|
-
const dir =
|
|
17726
|
+
const projectsRoot = path11.join(memoryRoot, "projects");
|
|
17727
|
+
if (fs9.existsSync(projectsRoot)) {
|
|
17728
|
+
for (const key of fs9.readdirSync(projectsRoot).sort()) {
|
|
17729
|
+
const dir = path11.join(projectsRoot, key);
|
|
17503
17730
|
try {
|
|
17504
|
-
if (!
|
|
17731
|
+
if (!fs9.statSync(dir).isDirectory()) continue;
|
|
17505
17732
|
} catch {
|
|
17506
17733
|
continue;
|
|
17507
17734
|
}
|
|
17508
|
-
const content = safeRead(
|
|
17735
|
+
const content = safeRead(path11.join(dir, "MEMORY.md"), 3500);
|
|
17509
17736
|
let meta = {};
|
|
17510
17737
|
try {
|
|
17511
|
-
meta = JSON.parse(
|
|
17738
|
+
meta = JSON.parse(fs9.readFileSync(path11.join(dir, "meta.json"), "utf8"));
|
|
17512
17739
|
} catch {
|
|
17513
17740
|
}
|
|
17514
17741
|
const safeReadableName = typeof meta.readableName === "string" ? redactText(meta.readableName).text : void 0;
|
|
17515
17742
|
const safePath = typeof meta.path === "string" ? redactText(meta.path).text : void 0;
|
|
17516
17743
|
const safeGitUrl = typeof meta.gitUrl === "string" ? redactText(meta.gitUrl).text : void 0;
|
|
17517
17744
|
if (!content.trim() && !safeReadableName && !safePath) continue;
|
|
17518
|
-
const slug = slugifyWikiName(safeReadableName || (safePath ?
|
|
17745
|
+
const slug = slugifyWikiName(safeReadableName || (safePath ? path11.basename(safePath) : key.slice(0, 12)));
|
|
17519
17746
|
projects.push({ key, slug, readableName: safeReadableName, path: safePath, gitUrl: safeGitUrl, content });
|
|
17520
17747
|
}
|
|
17521
17748
|
}
|
|
17522
17749
|
const recentJournals = [];
|
|
17523
|
-
const journalDir =
|
|
17524
|
-
if (
|
|
17525
|
-
const files =
|
|
17750
|
+
const journalDir = path11.join(memoryRoot, "journal");
|
|
17751
|
+
if (fs9.existsSync(journalDir)) {
|
|
17752
|
+
const files = fs9.readdirSync(journalDir).filter((f) => /^\d{4}-\d{2}-\d{2}\.md$/.test(f)).sort().slice(-3);
|
|
17526
17753
|
for (const file of files) {
|
|
17527
|
-
const content = safeRead(
|
|
17754
|
+
const content = safeRead(path11.join(journalDir, file), 1500);
|
|
17528
17755
|
if (content.trim()) recentJournals.push({ date: file.slice(0, -3), content });
|
|
17529
17756
|
}
|
|
17530
17757
|
}
|
|
@@ -17652,7 +17879,8 @@ async function runWikiDream(deps) {
|
|
|
17652
17879
|
log(`[wiki-dream] harvest failed for ${date}: ${String(error)}`);
|
|
17653
17880
|
}
|
|
17654
17881
|
}
|
|
17655
|
-
|
|
17882
|
+
const inboxItems = readWikiInbox(deps.memoryRoot);
|
|
17883
|
+
if (sessions.length === 0 && inboxItems.length === 0) {
|
|
17656
17884
|
const completeDates = deps.dates.filter((d) => !harvestFailedDates.has(d));
|
|
17657
17885
|
if (completeDates.length > 0) wikiStore.recordDreamedDates(completeDates, now);
|
|
17658
17886
|
if (harvestFailedDates.size > 0) {
|
|
@@ -17685,12 +17913,17 @@ async function runWikiDream(deps) {
|
|
|
17685
17913
|
for (const session of sessions) {
|
|
17686
17914
|
const proj = session.cwd ? projectKeyForDir(session.cwd) : void 0;
|
|
17687
17915
|
const existingPage = wikiStore.findProjectPage(proj ? [proj.key] : void 0, session.cwd);
|
|
17688
|
-
const slugHint = existingPage ?
|
|
17916
|
+
const slugHint = existingPage ? path11.basename(existingPage.relPath, ".md") : session.cwd ? slugifyWikiName(path11.basename(session.cwd)) : "ops";
|
|
17689
17917
|
try {
|
|
17690
|
-
const
|
|
17918
|
+
const cacheKey = `${session.date}:${session.sessionId}`;
|
|
17919
|
+
const cached = deps.extractedSignalsCache?.get(cacheKey);
|
|
17920
|
+
const signals = cached ?? await extractDreamSignalsForSession(session, deps.lightCall, {
|
|
17691
17921
|
slug: slugHint,
|
|
17692
17922
|
projectKey: proj?.key
|
|
17693
17923
|
});
|
|
17924
|
+
if (!cached && deps.extractedSignalsCache) {
|
|
17925
|
+
deps.extractedSignalsCache.set(cacheKey, signals);
|
|
17926
|
+
}
|
|
17694
17927
|
signalsBySession.push({ date: session.date, sessionId: session.sessionId, signals: signals.slice(0, MAX_DREAM_SIGNALS) });
|
|
17695
17928
|
const list = succeededByDate.get(session.date) ?? [];
|
|
17696
17929
|
list.push(session.sessionId);
|
|
@@ -17780,13 +18013,27 @@ async function runWikiDream(deps) {
|
|
|
17780
18013
|
deferredSessionCount += 1;
|
|
17781
18014
|
}
|
|
17782
18015
|
}
|
|
17783
|
-
const
|
|
18016
|
+
const packedInboxIds = [];
|
|
18017
|
+
let deferredInboxCount = 0;
|
|
18018
|
+
for (const inboxItem of inboxItems) {
|
|
18019
|
+
const signal = wikiInboxItemToDreamSignal(inboxItem, wikiStore);
|
|
18020
|
+
const pages = targetPagesForSignal(signal);
|
|
18021
|
+
const unionPages = /* @__PURE__ */ new Set([...batchTargetPages, ...pages]);
|
|
18022
|
+
if (batchSignals.length + 1 <= MAX_DREAM_SIGNALS && (unionPages.size <= maxTargetPages || batchSignals.length === 0)) {
|
|
18023
|
+
batchSignals.push(signal);
|
|
18024
|
+
for (const p of pages) batchTargetPages.add(p);
|
|
18025
|
+
packedInboxIds.push(inboxItem.id);
|
|
18026
|
+
} else {
|
|
18027
|
+
deferredInboxCount += 1;
|
|
18028
|
+
}
|
|
18029
|
+
}
|
|
18030
|
+
const totalSignalsCount = signalsBySession.reduce((sum, s) => sum + s.signals.length, 0) + inboxItems.length;
|
|
17784
18031
|
const persistPartialAndCompleteDates = (updatesOverflowed) => {
|
|
17785
18032
|
const completeDates = [];
|
|
17786
18033
|
for (const date of deps.dates) {
|
|
17787
18034
|
const hasHarvestFail = harvestFailedDates.has(date);
|
|
17788
18035
|
const hasExtractFail = (failedByDate.get(date)?.length ?? 0) > 0;
|
|
17789
|
-
const hasDeferred = (deferredSessionsByDate.get(date)?.length ?? 0) > 0;
|
|
18036
|
+
const hasDeferred = (deferredSessionsByDate.get(date)?.length ?? 0) > 0 || deferredInboxCount > 0;
|
|
17790
18037
|
if (!hasHarvestFail && !hasExtractFail && !hasDeferred && !updatesOverflowed) {
|
|
17791
18038
|
completeDates.push(date);
|
|
17792
18039
|
} else if (!updatesOverflowed) {
|
|
@@ -17800,6 +18047,9 @@ async function runWikiDream(deps) {
|
|
|
17800
18047
|
}
|
|
17801
18048
|
}
|
|
17802
18049
|
if (completeDates.length > 0) wikiStore.recordDreamedDates(completeDates, now);
|
|
18050
|
+
if (!updatesOverflowed && packedInboxIds.length > 0) {
|
|
18051
|
+
removeWikiInboxItems(deps.memoryRoot, packedInboxIds);
|
|
18052
|
+
}
|
|
17803
18053
|
};
|
|
17804
18054
|
const formatPartialError = (updatesOverflowed) => {
|
|
17805
18055
|
const parts = [];
|
|
@@ -17810,13 +18060,17 @@ async function runWikiDream(deps) {
|
|
|
17810
18060
|
if (harvestFailedDates.size > 0) {
|
|
17811
18061
|
parts.push(`harvest failed for date(s): ${[...harvestFailedDates].join(", ")}`);
|
|
17812
18062
|
}
|
|
17813
|
-
if (deferredSessionCount > 0 || updatesOverflowed) {
|
|
17814
|
-
|
|
18063
|
+
if (deferredSessionCount > 0 || deferredInboxCount > 0 || updatesOverflowed) {
|
|
18064
|
+
const deferredSummary = [
|
|
18065
|
+
...deferredSessionCount > 0 ? [`${deferredSessionCount} session(s)`] : [],
|
|
18066
|
+
...deferredInboxCount > 0 ? [`${deferredInboxCount} inbox item(s)`] : []
|
|
18067
|
+
].join(" + ") || "0 session(s)";
|
|
18068
|
+
parts.push(`wiki dream batch overflow: ${deferredSummary} deferred${updatesOverflowed ? " (page budget reached)" : ""}`);
|
|
17815
18069
|
}
|
|
17816
18070
|
return parts.join("; ");
|
|
17817
18071
|
};
|
|
17818
18072
|
if (batchSignals.length === 0) {
|
|
17819
|
-
if (allFailedSessions.length === sessions.length) {
|
|
18073
|
+
if (sessions.length > 0 && allFailedSessions.length === sessions.length) {
|
|
17820
18074
|
const lastError = allFailedSessions[allFailedSessions.length - 1]?.error ?? "unknown";
|
|
17821
18075
|
return {
|
|
17822
18076
|
ok: false,
|
|
@@ -17896,7 +18150,8 @@ ${p.content}`).join("\n\n") || "(none yet)"
|
|
|
17896
18150
|
const updatesOverflowed = allNonIndex.length > limits.maxPagesPerDream || parsed.archiveSlugs.length > remainingBudget;
|
|
17897
18151
|
if (filtered.length === 0 && archiveCandidates.length === 0) {
|
|
17898
18152
|
persistPartialAndCompleteDates(updatesOverflowed);
|
|
17899
|
-
const hasIncomplete2 = allFailedSessions.length > 0 || harvestFailedDates.size > 0 || deferredSessionCount > 0 || updatesOverflowed;
|
|
18153
|
+
const hasIncomplete2 = allFailedSessions.length > 0 || harvestFailedDates.size > 0 || deferredSessionCount > 0 || deferredInboxCount > 0 || updatesOverflowed;
|
|
18154
|
+
const mergedCount2 = !updatesOverflowed ? packedInboxIds.length : 0;
|
|
17900
18155
|
return {
|
|
17901
18156
|
ok: !hasIncomplete2,
|
|
17902
18157
|
dates: [...deps.dates],
|
|
@@ -17905,6 +18160,7 @@ ${p.content}`).join("\n\n") || "(none yet)"
|
|
|
17905
18160
|
written: [],
|
|
17906
18161
|
archived: [],
|
|
17907
18162
|
summaries: ["wiki already up to date"],
|
|
18163
|
+
...mergedCount2 > 0 ? { inboxMerged: mergedCount2 } : {},
|
|
17908
18164
|
...allFailedSessions.length > 0 ? { failedSessions: allFailedSessions } : {},
|
|
17909
18165
|
...hasIncomplete2 ? { error: formatPartialError(updatesOverflowed) } : {}
|
|
17910
18166
|
};
|
|
@@ -17964,7 +18220,8 @@ ${p.content}`).join("\n\n") || "(none yet)"
|
|
|
17964
18220
|
}
|
|
17965
18221
|
wikiStore.rebuildIndex(today, limits);
|
|
17966
18222
|
persistPartialAndCompleteDates(updatesOverflowed);
|
|
17967
|
-
const hasIncomplete = allFailedSessions.length > 0 || harvestFailedDates.size > 0 || deferredSessionCount > 0 || updatesOverflowed;
|
|
18223
|
+
const hasIncomplete = allFailedSessions.length > 0 || harvestFailedDates.size > 0 || deferredSessionCount > 0 || deferredInboxCount > 0 || updatesOverflowed;
|
|
18224
|
+
const mergedCount = !updatesOverflowed ? packedInboxIds.length : 0;
|
|
17968
18225
|
return {
|
|
17969
18226
|
ok: !hasIncomplete,
|
|
17970
18227
|
dates: [...deps.dates],
|
|
@@ -17973,6 +18230,7 @@ ${p.content}`).join("\n\n") || "(none yet)"
|
|
|
17973
18230
|
written: [...appliedWritten, "index.md"],
|
|
17974
18231
|
archived,
|
|
17975
18232
|
summaries: summaries.length > 0 ? summaries : ["wiki already up to date"],
|
|
18233
|
+
...mergedCount > 0 ? { inboxMerged: mergedCount } : {},
|
|
17976
18234
|
...allFailedSessions.length > 0 ? { failedSessions: allFailedSessions } : {},
|
|
17977
18235
|
...hasIncomplete ? { error: formatPartialError(updatesOverflowed) } : {}
|
|
17978
18236
|
};
|
|
@@ -17991,6 +18249,73 @@ ${p.content}`).join("\n\n") || "(none yet)"
|
|
|
17991
18249
|
}
|
|
17992
18250
|
}
|
|
17993
18251
|
|
|
18252
|
+
// ../../packages/shared-headless-capabilities/src/memory/wiki-dream-batches.ts
|
|
18253
|
+
var DEFAULT_MAX_DREAM_BATCHES = 6;
|
|
18254
|
+
function progressSignature(wikiStore, memoryRoot) {
|
|
18255
|
+
const meta = wikiStore.readMeta();
|
|
18256
|
+
const dates = [...meta.dreamedDates ?? []].sort().join(",");
|
|
18257
|
+
const sessions = Object.entries(meta.dreamedSessionsByDate ?? {}).sort(([a], [b]) => a.localeCompare(b)).map(([d, ids]) => `${d}:${ids.length}`).join("|");
|
|
18258
|
+
const targets = Object.entries(meta.dreamedTargetsBySession ?? {}).sort(([a], [b]) => a.localeCompare(b)).map(([k, ts]) => `${k}:${ts.length}`).join("|");
|
|
18259
|
+
const inboxRemaining = countWikiInbox(memoryRoot);
|
|
18260
|
+
return `${dates}#${sessions}#${targets}#inbox:${inboxRemaining}`;
|
|
18261
|
+
}
|
|
18262
|
+
function isPureBatchOverflow(res) {
|
|
18263
|
+
if (res.ok) return false;
|
|
18264
|
+
if (!res.error || !res.error.startsWith("wiki dream batch overflow")) return false;
|
|
18265
|
+
if (res.failedSessions && res.failedSessions.length > 0) return false;
|
|
18266
|
+
if (res.violations && res.violations.length > 0) return false;
|
|
18267
|
+
return true;
|
|
18268
|
+
}
|
|
18269
|
+
async function runWikiDreamBatches(deps) {
|
|
18270
|
+
const maxBatches = Math.min(Math.max(1, Math.floor(deps.maxBatches ?? DEFAULT_MAX_DREAM_BATCHES)), 12);
|
|
18271
|
+
const wikiStore = new WikiStore(deps.memoryRoot);
|
|
18272
|
+
const writtenSet = /* @__PURE__ */ new Set();
|
|
18273
|
+
const archivedSet = /* @__PURE__ */ new Set();
|
|
18274
|
+
const summaries = [];
|
|
18275
|
+
let totalSessions = 0;
|
|
18276
|
+
let totalSignals = 0;
|
|
18277
|
+
let totalInboxMerged = 0;
|
|
18278
|
+
let last;
|
|
18279
|
+
let batchesRun = 0;
|
|
18280
|
+
const extractedSignalsCache = /* @__PURE__ */ new Map();
|
|
18281
|
+
for (let pass = 0; pass < maxBatches; pass += 1) {
|
|
18282
|
+
const beforeSig = progressSignature(wikiStore, deps.memoryRoot);
|
|
18283
|
+
const res = await runWikiDream({ ...deps, extractedSignalsCache });
|
|
18284
|
+
batchesRun += 1;
|
|
18285
|
+
last = res;
|
|
18286
|
+
totalSessions += res.sessionsHarvested;
|
|
18287
|
+
totalSignals += res.signalsAuthenticated;
|
|
18288
|
+
totalInboxMerged += res.inboxMerged ?? 0;
|
|
18289
|
+
for (const w of res.written) writtenSet.add(w);
|
|
18290
|
+
for (const a of res.archived) archivedSet.add(a);
|
|
18291
|
+
for (const s of res.summaries) {
|
|
18292
|
+
if (summaries.length < 40 && !summaries.includes(s)) summaries.push(s);
|
|
18293
|
+
}
|
|
18294
|
+
if (!isPureBatchOverflow(res)) {
|
|
18295
|
+
break;
|
|
18296
|
+
}
|
|
18297
|
+
const afterSig = progressSignature(wikiStore, deps.memoryRoot);
|
|
18298
|
+
if (afterSig === beforeSig) {
|
|
18299
|
+
deps.log?.(`[wiki-dream] stopping overflow drain after pass ${batchesRun}: no forward progress`);
|
|
18300
|
+
break;
|
|
18301
|
+
}
|
|
18302
|
+
if (pass + 1 < maxBatches) {
|
|
18303
|
+
deps.log?.(`[wiki-dream] batch ${batchesRun}/${maxBatches} progressed (${res.error}); draining remaining batch`);
|
|
18304
|
+
}
|
|
18305
|
+
}
|
|
18306
|
+
const finalRes = last;
|
|
18307
|
+
return {
|
|
18308
|
+
...finalRes,
|
|
18309
|
+
sessionsHarvested: totalSessions,
|
|
18310
|
+
signalsAuthenticated: totalSignals,
|
|
18311
|
+
written: [...writtenSet],
|
|
18312
|
+
archived: [...archivedSet],
|
|
18313
|
+
summaries,
|
|
18314
|
+
...totalInboxMerged > 0 ? { inboxMerged: totalInboxMerged } : {},
|
|
18315
|
+
batchesRun
|
|
18316
|
+
};
|
|
18317
|
+
}
|
|
18318
|
+
|
|
17994
18319
|
// ../../packages/shared-headless-capabilities/src/memory/session-lookup.ts
|
|
17995
18320
|
var MAX_READ_CHUNK_CHARS = 6e3;
|
|
17996
18321
|
var MAX_SEARCH_SCAN = 256;
|
|
@@ -18442,6 +18767,13 @@ export {
|
|
|
18442
18767
|
WikiStore,
|
|
18443
18768
|
searchMemory,
|
|
18444
18769
|
readMemoryFile,
|
|
18770
|
+
MAX_WIKI_INBOX_ITEMS,
|
|
18771
|
+
wikiInboxPath,
|
|
18772
|
+
readWikiInbox,
|
|
18773
|
+
countWikiInbox,
|
|
18774
|
+
appendWikiInboxItem,
|
|
18775
|
+
removeWikiInboxItems,
|
|
18776
|
+
wikiInboxItemToDreamSignal,
|
|
18445
18777
|
parseWikiDreamOutput,
|
|
18446
18778
|
findExpiredDateAnchors,
|
|
18447
18779
|
runWikiGc,
|
|
@@ -18449,6 +18781,8 @@ export {
|
|
|
18449
18781
|
extractDreamSignalsForSession,
|
|
18450
18782
|
runWikiBootstrap,
|
|
18451
18783
|
runWikiDream,
|
|
18784
|
+
DEFAULT_MAX_DREAM_BATCHES,
|
|
18785
|
+
runWikiDreamBatches,
|
|
18452
18786
|
lookupSessionEvidence,
|
|
18453
18787
|
getSharedCapabilityPromptAdditionsForToolNames
|
|
18454
18788
|
};
|