@cydm/pie 4.3.7 → 4.3.12
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 +1 -1
- package/dist/builtin/extensions/cron/index.js +112 -8
- package/dist/builtin/extensions/im-forward/README.md +17 -1
- package/dist/builtin/extensions/im-forward/index.js +918 -347
- package/dist/builtin/extensions/mcp-adapter/index.js +2 -2
- package/dist/builtin/extensions/memory/index.js +10 -3
- package/dist/builtin/extensions/pie-ipc/index.js +179 -378
- package/dist/builtin/extensions/pie-proc/index.js +36 -4
- package/dist/builtin/extensions/plan-mode/index.js +6 -5
- package/dist/builtin/extensions/subagent/index.js +15 -5
- package/dist/builtin/extensions/todo/index.js +6 -2
- package/dist/chunks/{chunk-N3BWFAMZ.js → chunk-EGNGHINP.js} +521 -161
- package/dist/chunks/{chunk-BJ4XN5VX.js → chunk-GY47MKCJ.js} +13 -8
- package/dist/chunks/{chunk-2SAFRLFJ.js → chunk-I7PBXG5Q.js} +1 -1
- package/dist/chunks/{chunk-WZLO5V2X.js → chunk-N5B5IGJ6.js} +355 -231
- package/dist/chunks/{manager-cli-QNMCCIFG.js → manager-cli-4Z6RZ7F4.js} +195 -205
- package/dist/chunks/{src-UVULNQOO.js → src-V2M7FLWY.js} +7 -1
- package/dist/cli.js +143 -20
- package/package.json +2 -2
|
@@ -607,7 +607,7 @@ function createSearchContextTool(getReader) {
|
|
|
607
607
|
}
|
|
608
608
|
scanned++;
|
|
609
609
|
if (scanned % 16 === 0) {
|
|
610
|
-
await new Promise((
|
|
610
|
+
await new Promise((resolve5) => setTimeout(resolve5, 0));
|
|
611
611
|
if (signal?.aborted) throw new Error("History search aborted");
|
|
612
612
|
if (reader.getActiveSessionId() !== session || reader.getHistoryBranchRevision() !== revision) throw new Error("History changed; restart search");
|
|
613
613
|
}
|
|
@@ -1495,13 +1495,13 @@ function checkPlanScope(items, exists, isNew) {
|
|
|
1495
1495
|
const seen = /* @__PURE__ */ new Set();
|
|
1496
1496
|
for (const item of items) {
|
|
1497
1497
|
for (const rawPath of item.files ?? []) {
|
|
1498
|
-
const
|
|
1499
|
-
if (!
|
|
1500
|
-
seen.add(
|
|
1501
|
-
if (isNew(item,
|
|
1502
|
-
if (exists(
|
|
1503
|
-
} else if (!exists(
|
|
1504
|
-
warnings.push({ path:
|
|
1498
|
+
const path9 = String(rawPath ?? "").trim();
|
|
1499
|
+
if (!path9 || seen.has(path9)) continue;
|
|
1500
|
+
seen.add(path9);
|
|
1501
|
+
if (isNew(item, path9)) {
|
|
1502
|
+
if (exists(path9)) warnings.push({ path: path9, kind: "exists" });
|
|
1503
|
+
} else if (!exists(path9)) {
|
|
1504
|
+
warnings.push({ path: path9, kind: "missing" });
|
|
1505
1505
|
}
|
|
1506
1506
|
}
|
|
1507
1507
|
}
|
|
@@ -1623,12 +1623,12 @@ Focus: ${request.question.trim()}` : ""}` },
|
|
|
1623
1623
|
const capability = agentModel.fileCapabilities?.[request.kind];
|
|
1624
1624
|
const audioSupported = request.kind !== "audio" || ["audio/wav", "audio/mpeg", "audio/mp3"].includes(request.mimeType);
|
|
1625
1625
|
if (capability && typeof capability === "object" && capability.supported !== false && capability.nativeInline === true && audioSupported && (!capability.formats || capability.formats.includes(request.mimeType)) && capability.maxDurationSeconds === void 0) {
|
|
1626
|
-
const
|
|
1627
|
-
const size = (await
|
|
1626
|
+
const fs7 = getFileSystem();
|
|
1627
|
+
const size = (await fs7.stat(request.absolutePath)).size;
|
|
1628
1628
|
const cap = Math.min(capability.maxFileSizeMb ?? 15, 15) * 1024 * 1024;
|
|
1629
1629
|
if (size > 0 && size <= cap) {
|
|
1630
1630
|
if (request.signal?.aborted) throw new Error("Operation aborted");
|
|
1631
|
-
const data = await
|
|
1631
|
+
const data = await fs7.readFile(request.absolutePath, "base64");
|
|
1632
1632
|
if (request.signal?.aborted) throw new Error("Operation aborted");
|
|
1633
1633
|
const readBytes = Math.floor(data.length * 3 / 4) - (data.endsWith("==") ? 2 : data.endsWith("=") ? 1 : 0);
|
|
1634
1634
|
if (readBytes > 0 && readBytes <= cap && data) return {
|
|
@@ -1906,11 +1906,11 @@ function isRetryableSubagentFailureFrom(facts) {
|
|
|
1906
1906
|
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|\b50[0234]\b|bad gateway|service unavailable/i.test(message);
|
|
1907
1907
|
}
|
|
1908
1908
|
function cancellableBackoff(ms, signal) {
|
|
1909
|
-
return new Promise((
|
|
1909
|
+
return new Promise((resolve5) => {
|
|
1910
1910
|
const finish = () => {
|
|
1911
1911
|
clearTimeout(timer);
|
|
1912
1912
|
signal?.removeEventListener("abort", finish);
|
|
1913
|
-
|
|
1913
|
+
resolve5();
|
|
1914
1914
|
};
|
|
1915
1915
|
const timer = setTimeout(finish, ms);
|
|
1916
1916
|
signal?.addEventListener("abort", finish, { once: true });
|
|
@@ -2029,9 +2029,9 @@ async function closeIterator(iterator, hooks, signal) {
|
|
|
2029
2029
|
try {
|
|
2030
2030
|
await Promise.race([
|
|
2031
2031
|
cleanup,
|
|
2032
|
-
new Promise((
|
|
2033
|
-
timer = setTimeout(
|
|
2034
|
-
onAbort = () =>
|
|
2032
|
+
new Promise((resolve5) => {
|
|
2033
|
+
timer = setTimeout(resolve5, waitMs);
|
|
2034
|
+
onAbort = () => resolve5();
|
|
2035
2035
|
signal?.addEventListener("abort", onAbort, { once: true });
|
|
2036
2036
|
})
|
|
2037
2037
|
]);
|
|
@@ -3527,7 +3527,7 @@ ${DELEGATION_REPORT_INSTRUCTION}`;
|
|
|
3527
3527
|
if (graceMs > 0) {
|
|
3528
3528
|
await Promise.race([
|
|
3529
3529
|
settledRun,
|
|
3530
|
-
new Promise((
|
|
3530
|
+
new Promise((resolve5) => setTimeout(resolve5, graceMs))
|
|
3531
3531
|
]);
|
|
3532
3532
|
}
|
|
3533
3533
|
}
|
|
@@ -5007,11 +5007,11 @@ function formatCapabilityPolicySummary(tools, context = {}) {
|
|
|
5007
5007
|
import * as nodePath from "node:path";
|
|
5008
5008
|
|
|
5009
5009
|
// ../../packages/shared-headless-capabilities/src/builtin/fs/path-utils.ts
|
|
5010
|
-
function isInAllowlist(
|
|
5010
|
+
function isInAllowlist(path9, allowlistedDirs) {
|
|
5011
5011
|
if (allowlistedDirs.some((dir) => isGlobalFilesystemSentinel(dir))) {
|
|
5012
5012
|
return true;
|
|
5013
5013
|
}
|
|
5014
|
-
const normalized = normalizeForComparison(
|
|
5014
|
+
const normalized = normalizeForComparison(path9);
|
|
5015
5015
|
for (const dir of allowlistedDirs) {
|
|
5016
5016
|
const normalizedDir = normalizeForComparison(dir);
|
|
5017
5017
|
const dirWithSlash = withTrailingSep(normalizedDir);
|
|
@@ -5021,19 +5021,19 @@ function isInAllowlist(path8, allowlistedDirs) {
|
|
|
5021
5021
|
}
|
|
5022
5022
|
return false;
|
|
5023
5023
|
}
|
|
5024
|
-
function normalizeForComparison(
|
|
5025
|
-
const slashNormalized =
|
|
5024
|
+
function normalizeForComparison(path9) {
|
|
5025
|
+
const slashNormalized = path9.replace(/\\/g, "/");
|
|
5026
5026
|
const isWindowsPath = /^[a-zA-Z]:($|\/)/.test(slashNormalized) || /^\/{2}[^/]+\/[^/]+/.test(slashNormalized);
|
|
5027
5027
|
const normalized = slashNormalized.replace(/\/+/g, "/");
|
|
5028
5028
|
if (normalized === "/") return normalized;
|
|
5029
5029
|
const trimmed = normalized.replace(/\/+$/, "");
|
|
5030
5030
|
return isWindowsPath ? trimmed.toLowerCase() : trimmed;
|
|
5031
5031
|
}
|
|
5032
|
-
function isGlobalFilesystemSentinel(
|
|
5033
|
-
return normalizeForComparison(String(
|
|
5032
|
+
function isGlobalFilesystemSentinel(path9) {
|
|
5033
|
+
return normalizeForComparison(String(path9 || "").trim()) === "/";
|
|
5034
5034
|
}
|
|
5035
|
-
function isAbsoluteUserPath(
|
|
5036
|
-
const normalized =
|
|
5035
|
+
function isAbsoluteUserPath(path9) {
|
|
5036
|
+
const normalized = path9.replace(/\\/g, "/");
|
|
5037
5037
|
return /^[a-zA-Z]:\//.test(normalized) || /^\/{2}[^/]+\/[^/]+/.test(normalized);
|
|
5038
5038
|
}
|
|
5039
5039
|
function validateToolPathArgument(filePath) {
|
|
@@ -5048,65 +5048,65 @@ function validateToolPathArgument(filePath) {
|
|
|
5048
5048
|
throw new Error(`Invalid path "${filePath}". The path argument must be a single file path, not multi-line text.`);
|
|
5049
5049
|
}
|
|
5050
5050
|
}
|
|
5051
|
-
function withTrailingSep(
|
|
5052
|
-
return
|
|
5051
|
+
function withTrailingSep(path9) {
|
|
5052
|
+
return path9.endsWith("/") ? path9 : `${path9}/`;
|
|
5053
5053
|
}
|
|
5054
|
-
function isWithinRoot(
|
|
5054
|
+
function isWithinRoot(path9, root) {
|
|
5055
5055
|
if (isGlobalFilesystemSentinel(root)) {
|
|
5056
5056
|
return true;
|
|
5057
5057
|
}
|
|
5058
|
-
const normalizedPath = normalizeForComparison(
|
|
5058
|
+
const normalizedPath = normalizeForComparison(path9);
|
|
5059
5059
|
const normalizedRoot = normalizeForComparison(root);
|
|
5060
5060
|
return normalizedPath === normalizedRoot || normalizedPath.startsWith(withTrailingSep(normalizedRoot));
|
|
5061
5061
|
}
|
|
5062
5062
|
function getAccessRoots(sandboxRoot, options) {
|
|
5063
|
-
const
|
|
5063
|
+
const fs7 = getFileSystem();
|
|
5064
5064
|
const roots = /* @__PURE__ */ new Set();
|
|
5065
|
-
roots.add(
|
|
5065
|
+
roots.add(fs7.normalize(sandboxRoot));
|
|
5066
5066
|
if (options?.accessRoot) {
|
|
5067
|
-
roots.add(
|
|
5067
|
+
roots.add(fs7.normalize(options.accessRoot));
|
|
5068
5068
|
}
|
|
5069
5069
|
for (const root of options?.accessRoots ?? []) {
|
|
5070
5070
|
const trimmed = String(root || "").trim();
|
|
5071
5071
|
if (trimmed) {
|
|
5072
|
-
roots.add(
|
|
5072
|
+
roots.add(fs7.normalize(trimmed));
|
|
5073
5073
|
}
|
|
5074
5074
|
}
|
|
5075
5075
|
return Array.from(roots);
|
|
5076
5076
|
}
|
|
5077
|
-
function isWithinAnyRoot(
|
|
5078
|
-
if (roots.some((root) => isWithinRoot(
|
|
5079
|
-
const
|
|
5080
|
-
if (!
|
|
5081
|
-
const canonical = canonicalizeExistingPath(
|
|
5077
|
+
function isWithinAnyRoot(path9, roots) {
|
|
5078
|
+
if (roots.some((root) => isWithinRoot(path9, root))) return true;
|
|
5079
|
+
const fs7 = getFileSystem();
|
|
5080
|
+
if (!fs7.realpathSync) return false;
|
|
5081
|
+
const canonical = canonicalizeExistingPath(path9);
|
|
5082
5082
|
return roots.some((root) => isWithinRoot(canonical, canonicalizeExistingPath(root)));
|
|
5083
5083
|
}
|
|
5084
5084
|
function canonicalizeExistingPath(pathValue) {
|
|
5085
|
-
const
|
|
5086
|
-
if (!
|
|
5087
|
-
let cursor =
|
|
5085
|
+
const fs7 = getFileSystem();
|
|
5086
|
+
if (!fs7.realpathSync) return fs7.normalize(pathValue);
|
|
5087
|
+
let cursor = fs7.normalize(pathValue);
|
|
5088
5088
|
const suffix = [];
|
|
5089
|
-
while (!
|
|
5090
|
-
if (
|
|
5089
|
+
while (!fs7.existsSync(cursor)) {
|
|
5090
|
+
if (fs7.lstatSync) {
|
|
5091
5091
|
try {
|
|
5092
|
-
if (
|
|
5092
|
+
if (fs7.lstatSync(cursor).isSymbolicLink) {
|
|
5093
5093
|
throw new Error(`Path contains an unresolved symbolic link: ${cursor}`);
|
|
5094
5094
|
}
|
|
5095
5095
|
} catch (error) {
|
|
5096
5096
|
if (error instanceof Error && error.message.startsWith("Path contains an unresolved symbolic link:")) throw error;
|
|
5097
5097
|
}
|
|
5098
5098
|
}
|
|
5099
|
-
const parent =
|
|
5100
|
-
if (parent === cursor) return
|
|
5101
|
-
suffix.unshift(
|
|
5099
|
+
const parent = fs7.dirname(cursor);
|
|
5100
|
+
if (parent === cursor) return fs7.normalize(pathValue);
|
|
5101
|
+
suffix.unshift(fs7.basename(cursor));
|
|
5102
5102
|
cursor = parent;
|
|
5103
5103
|
}
|
|
5104
|
-
const canonicalBase =
|
|
5105
|
-
return suffix.length > 0 ?
|
|
5104
|
+
const canonicalBase = fs7.normalize(fs7.realpathSync(cursor));
|
|
5105
|
+
return suffix.length > 0 ? fs7.resolve(canonicalBase, ...suffix) : canonicalBase;
|
|
5106
5106
|
}
|
|
5107
5107
|
function finalizeResolvedPath(resolved, sandboxRoot, options) {
|
|
5108
|
-
const
|
|
5109
|
-
if (!
|
|
5108
|
+
const fs7 = getFileSystem();
|
|
5109
|
+
if (!fs7.realpathSync || !fs7.isAbsolute(resolved)) return resolved;
|
|
5110
5110
|
const allowlistedDirs = options?.allowlistedDirs ?? [];
|
|
5111
5111
|
if (allowlistedDirs.some((dir) => isGlobalFilesystemSentinel(dir))) return resolved;
|
|
5112
5112
|
const canonical = canonicalizeExistingPath(resolved);
|
|
@@ -5128,7 +5128,7 @@ function getAvailableRoots(options) {
|
|
|
5128
5128
|
if (!options?.roots || options.roots.length === 0) {
|
|
5129
5129
|
return [];
|
|
5130
5130
|
}
|
|
5131
|
-
const
|
|
5131
|
+
const fs7 = getFileSystem();
|
|
5132
5132
|
const seen = /* @__PURE__ */ new Set();
|
|
5133
5133
|
const results = [];
|
|
5134
5134
|
for (const root of options.roots) {
|
|
@@ -5136,14 +5136,14 @@ function getAvailableRoots(options) {
|
|
|
5136
5136
|
continue;
|
|
5137
5137
|
}
|
|
5138
5138
|
const name = root.name.trim();
|
|
5139
|
-
const
|
|
5140
|
-
if (!name || !
|
|
5139
|
+
const path9 = root.path.trim();
|
|
5140
|
+
if (!name || !path9 || seen.has(name)) {
|
|
5141
5141
|
continue;
|
|
5142
5142
|
}
|
|
5143
5143
|
seen.add(name);
|
|
5144
5144
|
results.push({
|
|
5145
5145
|
name,
|
|
5146
|
-
path:
|
|
5146
|
+
path: fs7.normalize(path9),
|
|
5147
5147
|
description: root.description?.trim() || void 0,
|
|
5148
5148
|
defaultPrefixes: Array.isArray(root.defaultPrefixes) ? root.defaultPrefixes.map((prefix) => String(prefix || "").trim()).filter((prefix) => prefix.length > 0) : void 0
|
|
5149
5149
|
});
|
|
@@ -5198,7 +5198,7 @@ function getResolutionRoot(filePath, sandboxRoot, options, rootName) {
|
|
|
5198
5198
|
return findPrefixMatchedRoot(filePath, options) ?? getRootByName(void 0, sandboxRoot, options);
|
|
5199
5199
|
}
|
|
5200
5200
|
function resolveInSandbox(filePath, sandboxRoot, options, rootName) {
|
|
5201
|
-
const
|
|
5201
|
+
const fs7 = getFileSystem();
|
|
5202
5202
|
const allowlistedDirs = options?.allowlistedDirs ?? [];
|
|
5203
5203
|
const accessRoots = getAccessRoots(sandboxRoot, options);
|
|
5204
5204
|
if (!filePath) {
|
|
@@ -5206,8 +5206,8 @@ function resolveInSandbox(filePath, sandboxRoot, options, rootName) {
|
|
|
5206
5206
|
}
|
|
5207
5207
|
validateToolPathArgument(filePath);
|
|
5208
5208
|
const cleaned = filePath.trim().startsWith("@") ? filePath.trim().slice(1) : filePath.trim();
|
|
5209
|
-
if (
|
|
5210
|
-
const normalized =
|
|
5209
|
+
if (fs7.isAbsolute(cleaned) || isAbsoluteUserPath(cleaned)) {
|
|
5210
|
+
const normalized = fs7.normalize(cleaned);
|
|
5211
5211
|
const selectedRoot2 = rootName ? getRootByName(rootName, sandboxRoot, options) : void 0;
|
|
5212
5212
|
if (rootName && !selectedRoot2) {
|
|
5213
5213
|
const available = getAvailableRoots(options).map((root) => root.name).join(", ");
|
|
@@ -5242,7 +5242,7 @@ function resolveInSandbox(filePath, sandboxRoot, options, rootName) {
|
|
|
5242
5242
|
);
|
|
5243
5243
|
}
|
|
5244
5244
|
const resolvedBase = selectedRoot?.path ?? sandboxRoot;
|
|
5245
|
-
const resolved =
|
|
5245
|
+
const resolved = fs7.resolve(resolvedBase, cleaned);
|
|
5246
5246
|
if (selectedRoot) {
|
|
5247
5247
|
if (!isWithinAnyRoot(resolved, [selectedRoot.path])) {
|
|
5248
5248
|
throw new Error(`Path escapes root '${selectedRoot.name}': ${filePath}`);
|
|
@@ -5780,7 +5780,7 @@ function createReadErrorResult(message, details) {
|
|
|
5780
5780
|
};
|
|
5781
5781
|
}
|
|
5782
5782
|
function createReadTool(cwd, options) {
|
|
5783
|
-
const
|
|
5783
|
+
const fs7 = getFileSystem();
|
|
5784
5784
|
const fileObservationState = options?.fileObservationState ?? createFileObservationState();
|
|
5785
5785
|
const callerObservations = /* @__PURE__ */ new WeakMap();
|
|
5786
5786
|
const rootSchema = buildRootParameterSchema(cwd, options);
|
|
@@ -5799,7 +5799,7 @@ function createReadTool(cwd, options) {
|
|
|
5799
5799
|
description: `Read a file's contents. Use this before editing, and use offset/limit for large files, or tail=N to read the last N lines when the line count is unknown. Images are attached for the current model when it supports vision; otherwise a configured file-understanding service analyzes them. Video, audio, and documents require a configured understanding service. Pass question to specify what to focus on; it does not force a separate model request. Example: read_file path='Scripts/PlayerController.cs' or read_file path='Data/config.json'. ${pathResolutionDescription} For text files, output is truncated to ${DEFAULT_MAX_LINES} lines or ${DEFAULT_MAX_BYTES / 1024}KB (whichever is hit first). When you need the full file, continue with a larger offset until complete.`,
|
|
5800
5800
|
parameters: readSchema,
|
|
5801
5801
|
execute: async (_toolCallId, params, signal, _onUpdate) => {
|
|
5802
|
-
const { path:
|
|
5802
|
+
const { path: path9, root, question } = params;
|
|
5803
5803
|
const tail = params.tail;
|
|
5804
5804
|
let offset = params.offset;
|
|
5805
5805
|
let limit = params.limit;
|
|
@@ -5820,7 +5820,7 @@ function createReadTool(cwd, options) {
|
|
|
5820
5820
|
}
|
|
5821
5821
|
let absolutePath;
|
|
5822
5822
|
try {
|
|
5823
|
-
absolutePath = resolveReadPath(
|
|
5823
|
+
absolutePath = resolveReadPath(path9, cwd, options, root);
|
|
5824
5824
|
} catch (error) {
|
|
5825
5825
|
const message = error instanceof Error ? error.message : String(error);
|
|
5826
5826
|
if (/outside sandbox|outside root|escapes sandbox/i.test(message)) {
|
|
@@ -5831,7 +5831,7 @@ function createReadTool(cwd, options) {
|
|
|
5831
5831
|
return createReadErrorResult(message);
|
|
5832
5832
|
}
|
|
5833
5833
|
return new Promise(
|
|
5834
|
-
(
|
|
5834
|
+
(resolve5, reject) => {
|
|
5835
5835
|
if (signal?.aborted) {
|
|
5836
5836
|
reject(new Error("Operation aborted"));
|
|
5837
5837
|
return;
|
|
@@ -5846,26 +5846,26 @@ function createReadTool(cwd, options) {
|
|
|
5846
5846
|
}
|
|
5847
5847
|
(async () => {
|
|
5848
5848
|
try {
|
|
5849
|
-
await
|
|
5849
|
+
await fs7.access(absolutePath);
|
|
5850
5850
|
if (isSpecialDevicePath(absolutePath)) {
|
|
5851
5851
|
throw new Error(`Refusing to read special device path: ${absolutePath}`);
|
|
5852
5852
|
}
|
|
5853
|
-
const stat = await
|
|
5853
|
+
const stat = await fs7.stat(absolutePath);
|
|
5854
5854
|
if (!stat.isFile) {
|
|
5855
5855
|
throw new Error(`Refusing to read non-regular file: ${absolutePath}`);
|
|
5856
5856
|
}
|
|
5857
5857
|
if (aborted) return;
|
|
5858
|
-
const prefix = await
|
|
5858
|
+
const prefix = await fs7.readFilePrefix(absolutePath, BINARY_MAGIC_PREFIX_BYTES);
|
|
5859
5859
|
const magicInfo = detectBinaryMagic(prefix);
|
|
5860
5860
|
let binaryInfo = detectBinaryKind(absolutePath);
|
|
5861
5861
|
if (options?.allowBinary === false) {
|
|
5862
5862
|
binaryInfo = detectTextOnlyBinary(prefix, absolutePath, stat.size > prefix.length);
|
|
5863
5863
|
}
|
|
5864
5864
|
if (options?.allowBinary === false && binaryInfo) {
|
|
5865
|
-
|
|
5865
|
+
resolve5({
|
|
5866
5866
|
content: [{
|
|
5867
5867
|
type: "text",
|
|
5868
|
-
text: `Cannot read ${binaryInfo.kind} file ${
|
|
5868
|
+
text: `Cannot read ${binaryInfo.kind} file ${path9}: this read_file instance accepts text files only.`
|
|
5869
5869
|
}],
|
|
5870
5870
|
details: {
|
|
5871
5871
|
understanding: {
|
|
@@ -5879,9 +5879,9 @@ function createReadTool(cwd, options) {
|
|
|
5879
5879
|
return;
|
|
5880
5880
|
}
|
|
5881
5881
|
if (magicInfo?.kind === "image" && options?.understandFile && (!INLINE_IMAGE_MIME_TYPES.has(magicInfo.mimeType) || stat.size > MAX_INLINE_IMAGE_BYTES)) {
|
|
5882
|
-
|
|
5882
|
+
resolve5(await options.understandFile({
|
|
5883
5883
|
absolutePath,
|
|
5884
|
-
displayPath:
|
|
5884
|
+
displayPath: path9,
|
|
5885
5885
|
mimeType: magicInfo.mimeType,
|
|
5886
5886
|
kind: "image",
|
|
5887
5887
|
question,
|
|
@@ -5890,14 +5890,14 @@ function createReadTool(cwd, options) {
|
|
|
5890
5890
|
return;
|
|
5891
5891
|
}
|
|
5892
5892
|
if (magicInfo?.kind === "image" && INLINE_IMAGE_MIME_TYPES.has(magicInfo.mimeType) && stat.size > MAX_INLINE_IMAGE_BYTES) {
|
|
5893
|
-
throw new Error(`Image file ${
|
|
5893
|
+
throw new Error(`Image file ${path9} is too large to attach (${formatSize(stat.size)}; maximum ${formatSize(MAX_INLINE_IMAGE_BYTES)}).`);
|
|
5894
5894
|
}
|
|
5895
|
-
const imageInfo = options?.allowBinary === false || magicInfo?.kind !== "image" || !INLINE_IMAGE_MIME_TYPES.has(magicInfo.mimeType) ? void 0 : await readImageInfo(absolutePath,
|
|
5895
|
+
const imageInfo = options?.allowBinary === false || magicInfo?.kind !== "image" || !INLINE_IMAGE_MIME_TYPES.has(magicInfo.mimeType) ? void 0 : await readImageInfo(absolutePath, fs7);
|
|
5896
5896
|
if (imageInfo) {
|
|
5897
5897
|
if (options?.understandFile) {
|
|
5898
|
-
|
|
5898
|
+
resolve5(await options.understandFile({
|
|
5899
5899
|
absolutePath,
|
|
5900
|
-
displayPath:
|
|
5900
|
+
displayPath: path9,
|
|
5901
5901
|
mimeType: imageInfo.mimeType,
|
|
5902
5902
|
kind: "image",
|
|
5903
5903
|
question,
|
|
@@ -5907,7 +5907,7 @@ function createReadTool(cwd, options) {
|
|
|
5907
5907
|
return;
|
|
5908
5908
|
}
|
|
5909
5909
|
const dimensionText = imageInfo.width && imageInfo.height ? `, ${imageInfo.width}x${imageInfo.height}` : "";
|
|
5910
|
-
|
|
5910
|
+
resolve5({
|
|
5911
5911
|
content: [
|
|
5912
5912
|
{ 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() ? `
|
|
5913
5913
|
Focus: ${question.trim()}` : ""}` },
|
|
@@ -5925,8 +5925,8 @@ Focus: ${question.trim()}` : ""}` },
|
|
|
5925
5925
|
}
|
|
5926
5926
|
if (magicInfo?.kind === "image") {
|
|
5927
5927
|
const inlineSupported = INLINE_IMAGE_MIME_TYPES.has(magicInfo.mimeType);
|
|
5928
|
-
|
|
5929
|
-
content: [{ type: "text", text: inlineSupported ? `Cannot attach image file ${
|
|
5928
|
+
resolve5({
|
|
5929
|
+
content: [{ type: "text", text: inlineSupported ? `Cannot attach image file ${path9}: the host filesystem bridge returned no usable image data for ${magicInfo.mimeType} (see logs for readImageInfo diagnostics).` : `Cannot attach image file ${path9}: unsupported image payload ${magicInfo.mimeType}.` }],
|
|
5930
5930
|
details: { understanding: { kind: "image", mimeType: magicInfo.mimeType, fallbackReason: inlineSupported ? "image bridge read failed" : "unsupported inline image format" } },
|
|
5931
5931
|
isError: true
|
|
5932
5932
|
});
|
|
@@ -5934,9 +5934,9 @@ Focus: ${question.trim()}` : ""}` },
|
|
|
5934
5934
|
}
|
|
5935
5935
|
const mediaInfo = magicInfo ?? detectUnderstandingKind(absolutePath);
|
|
5936
5936
|
if (mediaInfo && options?.understandFile) {
|
|
5937
|
-
|
|
5937
|
+
resolve5(await options.understandFile({
|
|
5938
5938
|
absolutePath,
|
|
5939
|
-
displayPath:
|
|
5939
|
+
displayPath: path9,
|
|
5940
5940
|
mimeType: mediaInfo.mimeType,
|
|
5941
5941
|
kind: mediaInfo.kind,
|
|
5942
5942
|
question,
|
|
@@ -5945,10 +5945,10 @@ Focus: ${question.trim()}` : ""}` },
|
|
|
5945
5945
|
return;
|
|
5946
5946
|
}
|
|
5947
5947
|
if (mediaInfo) {
|
|
5948
|
-
|
|
5948
|
+
resolve5({
|
|
5949
5949
|
content: [{
|
|
5950
5950
|
type: "text",
|
|
5951
|
-
text: `Cannot read ${mediaInfo.kind} file ${
|
|
5951
|
+
text: `Cannot read ${mediaInfo.kind} file ${path9} semantically: no media understanding handler is configured for ${mediaInfo.mimeType}.`
|
|
5952
5952
|
}],
|
|
5953
5953
|
details: {
|
|
5954
5954
|
understanding: {
|
|
@@ -5963,10 +5963,10 @@ Focus: ${question.trim()}` : ""}` },
|
|
|
5963
5963
|
}
|
|
5964
5964
|
const textBinaryInfo = detectTextOnlyBinary(prefix, absolutePath, stat.size > prefix.length);
|
|
5965
5965
|
if (textBinaryInfo) {
|
|
5966
|
-
|
|
5966
|
+
resolve5({
|
|
5967
5967
|
content: [{
|
|
5968
5968
|
type: "text",
|
|
5969
|
-
text: `Cannot read binary file ${
|
|
5969
|
+
text: `Cannot read binary file ${path9}: ${textBinaryInfo.mimeType}. Use a file-understanding handler for supported media/documents, or inspect metadata with a bounded shell command.`
|
|
5970
5970
|
}],
|
|
5971
5971
|
details: {
|
|
5972
5972
|
understanding: {
|
|
@@ -5988,7 +5988,7 @@ Focus: ${question.trim()}` : ""}` },
|
|
|
5988
5988
|
const effectiveTail = Math.max(1, Math.min(tail, DEFAULT_MAX_LINES - 1));
|
|
5989
5989
|
translatedFromTail = true;
|
|
5990
5990
|
tailEffectiveLines = effectiveTail;
|
|
5991
|
-
range2 = await
|
|
5991
|
+
range2 = await fs7.readTextRange(absolutePath, {
|
|
5992
5992
|
tailLines: effectiveTail,
|
|
5993
5993
|
maxOutputLines: DEFAULT_MAX_LINES,
|
|
5994
5994
|
maxOutputBytes: DEFAULT_MAX_BYTES
|
|
@@ -6003,7 +6003,7 @@ Focus: ${question.trim()}` : ""}` },
|
|
|
6003
6003
|
}
|
|
6004
6004
|
} else {
|
|
6005
6005
|
startLine = offset === void 0 ? 0 : offset - 1;
|
|
6006
|
-
range2 = await
|
|
6006
|
+
range2 = await fs7.readTextRange(absolutePath, {
|
|
6007
6007
|
offsetLine: startLine,
|
|
6008
6008
|
limitLines: limit,
|
|
6009
6009
|
maxOutputLines: DEFAULT_MAX_LINES,
|
|
@@ -6015,8 +6015,8 @@ Focus: ${question.trim()}` : ""}` },
|
|
|
6015
6015
|
const selectedLooksBinary = range2.selectedBytesLookBinary ?? (looksLikeBinaryText(range2.content) || range2.content.includes("\uFFFD"));
|
|
6016
6016
|
const selectedBinary = selectedLooksBinary ? { kind: "document", mimeType: "application/octet-stream" } : void 0;
|
|
6017
6017
|
if (selectedBinary) {
|
|
6018
|
-
|
|
6019
|
-
content: [{ type: "text", text: `Cannot read ${selectedBinary.kind} file ${
|
|
6018
|
+
resolve5({
|
|
6019
|
+
content: [{ type: "text", text: `Cannot read ${selectedBinary.kind} file ${path9}: this read_file instance accepts text files only.` }],
|
|
6020
6020
|
details: { understanding: { ...selectedBinary, fallbackReason: "binary content is disabled for this tool" } },
|
|
6021
6021
|
isError: true
|
|
6022
6022
|
});
|
|
@@ -6069,7 +6069,7 @@ Focus: ${question.trim()}` : ""}` },
|
|
|
6069
6069
|
if (signal) {
|
|
6070
6070
|
signal.removeEventListener("abort", onAbort);
|
|
6071
6071
|
}
|
|
6072
|
-
|
|
6072
|
+
resolve5({
|
|
6073
6073
|
content: [{
|
|
6074
6074
|
type: "text",
|
|
6075
6075
|
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.`
|
|
@@ -6167,7 +6167,7 @@ Base directory: ${nodePath.dirname(absolutePath)}
|
|
|
6167
6167
|
if (signal) {
|
|
6168
6168
|
signal.removeEventListener("abort", onAbort);
|
|
6169
6169
|
}
|
|
6170
|
-
|
|
6170
|
+
resolve5({
|
|
6171
6171
|
content: textContent,
|
|
6172
6172
|
details
|
|
6173
6173
|
});
|
|
@@ -6178,7 +6178,7 @@ Base directory: ${nodePath.dirname(absolutePath)}
|
|
|
6178
6178
|
reject(error);
|
|
6179
6179
|
return;
|
|
6180
6180
|
}
|
|
6181
|
-
|
|
6181
|
+
resolve5(createReadErrorResult(message, { path: absolutePath }));
|
|
6182
6182
|
}
|
|
6183
6183
|
} finally {
|
|
6184
6184
|
signal?.removeEventListener("abort", onAbort);
|
|
@@ -6189,8 +6189,8 @@ Base directory: ${nodePath.dirname(absolutePath)}
|
|
|
6189
6189
|
}
|
|
6190
6190
|
};
|
|
6191
6191
|
}
|
|
6192
|
-
function isSpecialDevicePath(
|
|
6193
|
-
const normalized = nodePath.resolve(
|
|
6192
|
+
function isSpecialDevicePath(path9) {
|
|
6193
|
+
const normalized = nodePath.resolve(path9).replace(/\\/g, "/");
|
|
6194
6194
|
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);
|
|
6195
6195
|
}
|
|
6196
6196
|
function detectUnderstandingKind(filePath) {
|
|
@@ -6331,22 +6331,22 @@ function detectTextOnlyBinary(input, filePath, prefixMayBeTruncated) {
|
|
|
6331
6331
|
if (!looksLikeBinary(input, prefixMayBeTruncated)) return void 0;
|
|
6332
6332
|
return detectBinaryKind(filePath) ?? { kind: "document", mimeType: "application/octet-stream" };
|
|
6333
6333
|
}
|
|
6334
|
-
async function readImageInfo(
|
|
6334
|
+
async function readImageInfo(path9, fs7) {
|
|
6335
6335
|
try {
|
|
6336
6336
|
let base64 = "";
|
|
6337
|
-
if (typeof
|
|
6338
|
-
base64 = await
|
|
6337
|
+
if (typeof fs7.readFile === "function") {
|
|
6338
|
+
base64 = await fs7.readFile(path9, "base64").catch(() => "");
|
|
6339
6339
|
}
|
|
6340
|
-
if (!base64 && typeof
|
|
6341
|
-
base64 =
|
|
6340
|
+
if (!base64 && typeof fs7.readFileSync === "function") {
|
|
6341
|
+
base64 = fs7.readFileSync(path9, "base64");
|
|
6342
6342
|
}
|
|
6343
6343
|
if (!base64) {
|
|
6344
|
-
console.error(`[pie] readImageInfo got empty base64 for ${
|
|
6344
|
+
console.error(`[pie] readImageInfo got empty base64 for ${path9}`);
|
|
6345
6345
|
return void 0;
|
|
6346
6346
|
}
|
|
6347
6347
|
const bytes = decodeBase64ToBytes(base64);
|
|
6348
6348
|
if (bytes.length === 0) {
|
|
6349
|
-
console.error(`[pie] readImageInfo decoded 0 bytes for ${
|
|
6349
|
+
console.error(`[pie] readImageInfo decoded 0 bytes for ${path9} (base64 length ${base64.length})`);
|
|
6350
6350
|
return void 0;
|
|
6351
6351
|
}
|
|
6352
6352
|
const pngMagic = [137, 80, 78, 71, 13, 10, 26, 10];
|
|
@@ -6365,10 +6365,10 @@ async function readImageInfo(path8, fs6) {
|
|
|
6365
6365
|
if (bytes.length >= 12 && asciiAt(bytes, 0, 4) === "RIFF" && asciiAt(bytes, 8, 12 - 8) === "WEBP") {
|
|
6366
6366
|
return { mimeType: "image/webp", base64, ...parseWebpDimensions(bytes) };
|
|
6367
6367
|
}
|
|
6368
|
-
console.error(`[pie] readImageInfo decoded ${bytes.length} bytes for ${
|
|
6368
|
+
console.error(`[pie] readImageInfo decoded ${bytes.length} bytes for ${path9} but no known image signature matched`);
|
|
6369
6369
|
return void 0;
|
|
6370
6370
|
} catch (error) {
|
|
6371
|
-
console.error(`[pie] readImageInfo failed for ${
|
|
6371
|
+
console.error(`[pie] readImageInfo failed for ${path9}: ${error instanceof Error ? error.message : String(error)}`);
|
|
6372
6372
|
return void 0;
|
|
6373
6373
|
}
|
|
6374
6374
|
return void 0;
|
|
@@ -6500,7 +6500,7 @@ function parseWebpDimensions(bytes) {
|
|
|
6500
6500
|
|
|
6501
6501
|
// ../../packages/shared-headless-capabilities/src/builtin/fs/write.ts
|
|
6502
6502
|
function createWriteTool(cwd, options) {
|
|
6503
|
-
const
|
|
6503
|
+
const fs7 = getFileSystem();
|
|
6504
6504
|
const usesExternalFileObservationState = !!options?.fileObservationState;
|
|
6505
6505
|
const fileObservationState = options?.fileObservationState ?? createFileObservationState();
|
|
6506
6506
|
const rootSchema = buildRootParameterSchema(cwd, options);
|
|
@@ -6518,9 +6518,9 @@ function createWriteTool(cwd, options) {
|
|
|
6518
6518
|
execute: async (_toolCallId, params, signal) => {
|
|
6519
6519
|
const { path: filePath, root, content } = params;
|
|
6520
6520
|
const absolutePath = resolveToCwd(filePath, cwd, options, root);
|
|
6521
|
-
const dir =
|
|
6521
|
+
const dir = fs7.dirname(absolutePath);
|
|
6522
6522
|
return new Promise(
|
|
6523
|
-
(
|
|
6523
|
+
(resolve5, reject) => {
|
|
6524
6524
|
if (signal?.aborted) {
|
|
6525
6525
|
reject(new Error("Operation aborted"));
|
|
6526
6526
|
return;
|
|
@@ -6535,18 +6535,18 @@ function createWriteTool(cwd, options) {
|
|
|
6535
6535
|
}
|
|
6536
6536
|
(async () => {
|
|
6537
6537
|
try {
|
|
6538
|
-
await
|
|
6538
|
+
await fs7.mkdir(dir, { recursive: true });
|
|
6539
6539
|
if (aborted) return;
|
|
6540
6540
|
let fileExists = false;
|
|
6541
6541
|
try {
|
|
6542
|
-
const stat = await
|
|
6542
|
+
const stat = await fs7.stat(absolutePath);
|
|
6543
6543
|
fileExists = stat.isFile;
|
|
6544
6544
|
} catch {
|
|
6545
6545
|
fileExists = false;
|
|
6546
6546
|
}
|
|
6547
6547
|
if (fileExists) {
|
|
6548
|
-
const currentContent = String(await
|
|
6549
|
-
const currentStat = await
|
|
6548
|
+
const currentContent = String(await fs7.readFile(absolutePath, "utf-8"));
|
|
6549
|
+
const currentStat = await fs7.stat(absolutePath);
|
|
6550
6550
|
const currentSnapshot = snapshotFromStatAndContent(currentStat, currentContent);
|
|
6551
6551
|
const observedSnapshot = fileObservationState.getCompleteTextSnapshot(absolutePath);
|
|
6552
6552
|
if (!observedSnapshot) {
|
|
@@ -6562,8 +6562,8 @@ function createWriteTool(cwd, options) {
|
|
|
6562
6562
|
);
|
|
6563
6563
|
}
|
|
6564
6564
|
}
|
|
6565
|
-
await
|
|
6566
|
-
const writtenStat = await
|
|
6565
|
+
await fs7.writeFile(absolutePath, content, "utf-8");
|
|
6566
|
+
const writtenStat = await fs7.stat(absolutePath);
|
|
6567
6567
|
fileObservationState.recordCompleteTextWrite(
|
|
6568
6568
|
absolutePath,
|
|
6569
6569
|
snapshotFromStatAndContent(writtenStat, content)
|
|
@@ -6572,7 +6572,7 @@ function createWriteTool(cwd, options) {
|
|
|
6572
6572
|
if (signal) {
|
|
6573
6573
|
signal.removeEventListener("abort", onAbort);
|
|
6574
6574
|
}
|
|
6575
|
-
|
|
6575
|
+
resolve5({
|
|
6576
6576
|
content: [{ type: "text", text: `Successfully wrote ${writtenStat.size} bytes to ${filePath}` }],
|
|
6577
6577
|
details: void 0
|
|
6578
6578
|
});
|
|
@@ -6691,16 +6691,16 @@ var Diff = class {
|
|
|
6691
6691
|
}
|
|
6692
6692
|
}
|
|
6693
6693
|
}
|
|
6694
|
-
addToPath(
|
|
6695
|
-
const last =
|
|
6694
|
+
addToPath(path9, added, removed, oldPosInc, options) {
|
|
6695
|
+
const last = path9.lastComponent;
|
|
6696
6696
|
if (last && !options.oneChangePerToken && last.added === added && last.removed === removed) {
|
|
6697
6697
|
return {
|
|
6698
|
-
oldPos:
|
|
6698
|
+
oldPos: path9.oldPos + oldPosInc,
|
|
6699
6699
|
lastComponent: { count: last.count + 1, added, removed, previousComponent: last.previousComponent }
|
|
6700
6700
|
};
|
|
6701
6701
|
} else {
|
|
6702
6702
|
return {
|
|
6703
|
-
oldPos:
|
|
6703
|
+
oldPos: path9.oldPos + oldPosInc,
|
|
6704
6704
|
lastComponent: { count: 1, added, removed, previousComponent: last }
|
|
6705
6705
|
};
|
|
6706
6706
|
}
|
|
@@ -7572,8 +7572,8 @@ function generateDiffString(oldContent, newContent, contextLines = 4) {
|
|
|
7572
7572
|
var MAX_EDIT_BLOCKS = 64;
|
|
7573
7573
|
var MAX_EDIT_INPUT_CHARS = 256 * 1024;
|
|
7574
7574
|
function validateEditArgs(params) {
|
|
7575
|
-
const { path:
|
|
7576
|
-
const filePath = typeof
|
|
7575
|
+
const { path: path9, oldText, newText, replaceAll, edits } = params;
|
|
7576
|
+
const filePath = typeof path9 === "string" ? path9.trim() : "";
|
|
7577
7577
|
if (!filePath) {
|
|
7578
7578
|
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.");
|
|
7579
7579
|
}
|
|
@@ -7655,14 +7655,14 @@ function createEditErrorResult(params) {
|
|
|
7655
7655
|
isError: true
|
|
7656
7656
|
};
|
|
7657
7657
|
}
|
|
7658
|
-
function createEditThrownErrorResult(message,
|
|
7658
|
+
function createEditThrownErrorResult(message, path9) {
|
|
7659
7659
|
return {
|
|
7660
7660
|
content: [{ type: "text", text: boundEditOutput(`edit_file failed: ${message}`).text }],
|
|
7661
7661
|
details: {
|
|
7662
7662
|
status: "error",
|
|
7663
7663
|
matchKind: "none",
|
|
7664
7664
|
changed: false,
|
|
7665
|
-
path:
|
|
7665
|
+
path: path9,
|
|
7666
7666
|
diff: "",
|
|
7667
7667
|
oldTextOccurrences: 0,
|
|
7668
7668
|
newTextOccurrences: 0,
|
|
@@ -7675,7 +7675,7 @@ function createEditThrownErrorResult(message, path8) {
|
|
|
7675
7675
|
};
|
|
7676
7676
|
}
|
|
7677
7677
|
function createEditTool(cwd, options) {
|
|
7678
|
-
const
|
|
7678
|
+
const fs7 = getFileSystem();
|
|
7679
7679
|
const fileObservationState = options?.fileObservationState ?? createFileObservationState();
|
|
7680
7680
|
const usesExternalFileObservationState = !!options?.fileObservationState;
|
|
7681
7681
|
const rootSchema = buildRootParameterSchema(cwd, options);
|
|
@@ -7699,17 +7699,17 @@ function createEditTool(cwd, options) {
|
|
|
7699
7699
|
description: `Make precise exact-text replacements in one file. For multiple changes in the same file, put all replacements in one edits[] call \u2014 they apply in order, so later edits can target what earlier ones just changed. ${pathResolutionDescription}`,
|
|
7700
7700
|
parameters: editSchema,
|
|
7701
7701
|
execute: async (_toolCallId, params, signal) => {
|
|
7702
|
-
const { path:
|
|
7702
|
+
const { path: path9, root } = params;
|
|
7703
7703
|
let replacements;
|
|
7704
7704
|
let absolutePath;
|
|
7705
7705
|
try {
|
|
7706
7706
|
replacements = validateEditArgs(params);
|
|
7707
|
-
absolutePath = resolveToCwd(
|
|
7707
|
+
absolutePath = resolveToCwd(path9, cwd, options, root);
|
|
7708
7708
|
} catch (error) {
|
|
7709
7709
|
const message = error instanceof Error ? error.message : String(error);
|
|
7710
|
-
return createEditThrownErrorResult(message, typeof
|
|
7710
|
+
return createEditThrownErrorResult(message, typeof path9 === "string" ? path9 : void 0);
|
|
7711
7711
|
}
|
|
7712
|
-
return new Promise((
|
|
7712
|
+
return new Promise((resolve5, reject) => {
|
|
7713
7713
|
if (signal?.aborted) {
|
|
7714
7714
|
reject(new Error("Operation aborted"));
|
|
7715
7715
|
return;
|
|
@@ -7730,10 +7730,10 @@ function createEditTool(cwd, options) {
|
|
|
7730
7730
|
if (aborted || signal?.aborted) throw new Error("Operation aborted");
|
|
7731
7731
|
};
|
|
7732
7732
|
try {
|
|
7733
|
-
await
|
|
7733
|
+
await fs7.access(absolutePath);
|
|
7734
7734
|
} catch {
|
|
7735
7735
|
if (signal) signal.removeEventListener("abort", onAbort);
|
|
7736
|
-
|
|
7736
|
+
resolve5(createEditThrownErrorResult(`File not found: ${path9}`, path9));
|
|
7737
7737
|
return;
|
|
7738
7738
|
}
|
|
7739
7739
|
throwIfAborted();
|
|
@@ -7744,8 +7744,8 @@ function createEditTool(cwd, options) {
|
|
|
7744
7744
|
const lastClear = fileObservationState.getLastClear?.();
|
|
7745
7745
|
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.` : "";
|
|
7746
7746
|
if (signal) signal.removeEventListener("abort", onAbort);
|
|
7747
|
-
|
|
7748
|
-
message: `edit_file blocked: ${
|
|
7747
|
+
resolve5(createEditErrorResult({
|
|
7748
|
+
message: `edit_file blocked: ${path9} has not been read in this session.${resetNote}`,
|
|
7749
7749
|
matchKind: "none",
|
|
7750
7750
|
errorReason: "old_text_not_found",
|
|
7751
7751
|
oldTextOccurrences: 0,
|
|
@@ -7756,7 +7756,7 @@ function createEditTool(cwd, options) {
|
|
|
7756
7756
|
return;
|
|
7757
7757
|
}
|
|
7758
7758
|
}
|
|
7759
|
-
const rawContent = await
|
|
7759
|
+
const rawContent = await fs7.readFile(absolutePath, "utf-8");
|
|
7760
7760
|
throwIfAborted();
|
|
7761
7761
|
const { bom, text: content } = stripBom(rawContent);
|
|
7762
7762
|
const originalEnding = detectLineEnding(content);
|
|
@@ -7783,8 +7783,8 @@ function createEditTool(cwd, options) {
|
|
|
7783
7783
|
if (!matchResult.found) {
|
|
7784
7784
|
if (matchResult.exhausted) {
|
|
7785
7785
|
if (signal) signal.removeEventListener("abort", onAbort);
|
|
7786
|
-
|
|
7787
|
-
message: `Could not match edit ${editIndex + 1} in ${
|
|
7786
|
+
resolve5(createEditErrorResult({
|
|
7787
|
+
message: `Could not match edit ${editIndex + 1} in ${path9} within the relaxed-match budget.`,
|
|
7788
7788
|
matchKind: "none",
|
|
7789
7789
|
errorReason: "match_budget_exhausted",
|
|
7790
7790
|
oldTextOccurrences: 0,
|
|
@@ -7795,8 +7795,8 @@ function createEditTool(cwd, options) {
|
|
|
7795
7795
|
return;
|
|
7796
7796
|
}
|
|
7797
7797
|
if (signal) signal.removeEventListener("abort", onAbort);
|
|
7798
|
-
|
|
7799
|
-
message: `Could not find oldText for edit ${editIndex + 1} in ${
|
|
7798
|
+
resolve5(createEditErrorResult({
|
|
7799
|
+
message: `Could not find oldText for edit ${editIndex + 1} in ${path9}.`,
|
|
7800
7800
|
matchKind: "none",
|
|
7801
7801
|
errorReason: "old_text_not_found",
|
|
7802
7802
|
oldTextOccurrences: 0,
|
|
@@ -7811,8 +7811,8 @@ function createEditTool(cwd, options) {
|
|
|
7811
7811
|
}
|
|
7812
7812
|
if (matchResult.occurrences > 1 && !replacement.replaceAll) {
|
|
7813
7813
|
if (signal) signal.removeEventListener("abort", onAbort);
|
|
7814
|
-
|
|
7815
|
-
message: `Found ${matchResult.occurrences}${matchResult.occurrencesAtLeast ? " or more" : ""} occurrences for edit ${editIndex + 1} in ${
|
|
7814
|
+
resolve5(createEditErrorResult({
|
|
7815
|
+
message: `Found ${matchResult.occurrences}${matchResult.occurrencesAtLeast ? " or more" : ""} occurrences for edit ${editIndex + 1} in ${path9}.`,
|
|
7816
7816
|
matchKind: matchResult.matchKind,
|
|
7817
7817
|
errorReason: "old_text_not_unique",
|
|
7818
7818
|
oldTextOccurrences: matchResult.occurrences,
|
|
@@ -7828,8 +7828,8 @@ function createEditTool(cwd, options) {
|
|
|
7828
7828
|
);
|
|
7829
7829
|
if (changingMatches.length === 0) {
|
|
7830
7830
|
if (signal) signal.removeEventListener("abort", onAbort);
|
|
7831
|
-
|
|
7832
|
-
message: `No changes made for edit ${editIndex + 1} in ${
|
|
7831
|
+
resolve5(createEditErrorResult({
|
|
7832
|
+
message: `No changes made for edit ${editIndex + 1} in ${path9}. Its replacement matches the current file content.`,
|
|
7833
7833
|
matchKind: matchResult.matchKind,
|
|
7834
7834
|
errorReason: "replacement_no_change",
|
|
7835
7835
|
oldTextOccurrences: matchResult.occurrences,
|
|
@@ -7850,9 +7850,9 @@ function createEditTool(cwd, options) {
|
|
|
7850
7850
|
throwIfAborted();
|
|
7851
7851
|
if (workingContent === normalizedContent) {
|
|
7852
7852
|
if (signal) signal.removeEventListener("abort", onAbort);
|
|
7853
|
-
|
|
7853
|
+
resolve5(
|
|
7854
7854
|
createEditErrorResult({
|
|
7855
|
-
message: `No changes made to ${
|
|
7855
|
+
message: `No changes made to ${path9}. The replacement produced identical content.`,
|
|
7856
7856
|
matchKind: plannedKinds.size === 1 ? [...plannedKinds][0] : "mixed",
|
|
7857
7857
|
errorReason: "replacement_no_change",
|
|
7858
7858
|
oldTextOccurrences: totalOldOccurrences,
|
|
@@ -7870,12 +7870,12 @@ function createEditTool(cwd, options) {
|
|
|
7870
7870
|
const diffResult = generateDiffString(normalizedContent, newContent);
|
|
7871
7871
|
throwIfAborted();
|
|
7872
7872
|
committing = true;
|
|
7873
|
-
await
|
|
7873
|
+
await fs7.writeFile(absolutePath, finalContent, "utf-8");
|
|
7874
7874
|
if (signal) signal.removeEventListener("abort", onAbort);
|
|
7875
7875
|
let diagnosticWarning;
|
|
7876
7876
|
try {
|
|
7877
7877
|
if (usesExternalFileObservationState) {
|
|
7878
|
-
const writtenStat = await
|
|
7878
|
+
const writtenStat = await fs7.stat(absolutePath);
|
|
7879
7879
|
const snapshot = snapshotFromStatAndContent(writtenStat, finalContent);
|
|
7880
7880
|
fileObservationState.invalidate(absolutePath);
|
|
7881
7881
|
fileObservationState.recordTextRead(
|
|
@@ -7894,10 +7894,10 @@ function createEditTool(cwd, options) {
|
|
|
7894
7894
|
diagnosticWarning = "Edit saved, but file observation refresh failed; read the file before the next edit.";
|
|
7895
7895
|
}
|
|
7896
7896
|
const matchKind = plannedKinds.size === 1 ? [...plannedKinds][0] : "mixed";
|
|
7897
|
-
const visible = boundEditOutput(`Changed ${
|
|
7897
|
+
const visible = boundEditOutput(`Changed ${path9}: ${replacements.length} edit block${replacements.length === 1 ? "" : "s"}, ${replacedOccurrences} replacement${replacedOccurrences === 1 ? "" : "s"}. First changed line: ${diffResult.firstChangedLine}.
|
|
7898
7898
|
${diagnosticWarning ?? ""}
|
|
7899
7899
|
${diffResult.diff}`);
|
|
7900
|
-
|
|
7900
|
+
resolve5({
|
|
7901
7901
|
content: [
|
|
7902
7902
|
{
|
|
7903
7903
|
type: "text",
|
|
@@ -7908,7 +7908,7 @@ ${diffResult.diff}`);
|
|
|
7908
7908
|
status: "success",
|
|
7909
7909
|
matchKind,
|
|
7910
7910
|
changed: true,
|
|
7911
|
-
path:
|
|
7911
|
+
path: path9,
|
|
7912
7912
|
diff: diffResult.diff,
|
|
7913
7913
|
diffTruncated: diffResult.truncated,
|
|
7914
7914
|
contentTruncated: visible.truncated,
|
|
@@ -7932,7 +7932,7 @@ ${diffResult.diff}`);
|
|
|
7932
7932
|
reject(error);
|
|
7933
7933
|
return;
|
|
7934
7934
|
}
|
|
7935
|
-
|
|
7935
|
+
resolve5(createEditThrownErrorResult(message, path9));
|
|
7936
7936
|
}
|
|
7937
7937
|
}
|
|
7938
7938
|
})();
|
|
@@ -7945,7 +7945,7 @@ ${diffResult.diff}`);
|
|
|
7945
7945
|
var DEFAULT_LIMIT = 500;
|
|
7946
7946
|
var MAX_RESULT_LIMIT = 1e4;
|
|
7947
7947
|
function createLsTool(cwd, options) {
|
|
7948
|
-
const
|
|
7948
|
+
const fs7 = getFileSystem();
|
|
7949
7949
|
const rootSchema = buildRootParameterSchema(cwd, options);
|
|
7950
7950
|
const lsSchema = Type.Object({
|
|
7951
7951
|
path: Type.Optional(Type.String({ description: "Directory to list (default: workspace root). Example: 'Scripts' or 'Data'." })),
|
|
@@ -7959,7 +7959,7 @@ function createLsTool(cwd, options) {
|
|
|
7959
7959
|
description: `List directory contents. Use this to inspect folders before reading or writing files. Example: list_dir path='Scripts' or list_dir path='Data'. ${pathResolutionDescription} Returns entries sorted alphabetically, with '/' suffix for directories. Includes dotfiles. Output is truncated to ${DEFAULT_LIMIT} entries or ${DEFAULT_MAX_BYTES / 1024}KB (whichever is hit first).`,
|
|
7960
7960
|
parameters: lsSchema,
|
|
7961
7961
|
execute: async (_toolCallId, params, signal) => {
|
|
7962
|
-
return new Promise((
|
|
7962
|
+
return new Promise((resolve5, reject) => {
|
|
7963
7963
|
if (signal?.aborted) {
|
|
7964
7964
|
reject(new Error("Operation aborted"));
|
|
7965
7965
|
return;
|
|
@@ -7978,14 +7978,14 @@ function createLsTool(cwd, options) {
|
|
|
7978
7978
|
if (!Number.isInteger(effectiveLimit) || effectiveLimit < 1 || effectiveLimit > MAX_RESULT_LIMIT) {
|
|
7979
7979
|
throw new Error(`Invalid list_dir arguments: limit must be between 1 and ${MAX_RESULT_LIMIT}.`);
|
|
7980
7980
|
}
|
|
7981
|
-
if (!await
|
|
7981
|
+
if (!await fs7.exists(targetPath)) {
|
|
7982
7982
|
reject(new Error(`Path not found: ${targetPath}`));
|
|
7983
7983
|
return;
|
|
7984
7984
|
}
|
|
7985
7985
|
let entries;
|
|
7986
7986
|
let directoryLimitReached = false;
|
|
7987
7987
|
try {
|
|
7988
|
-
const directoryRead = await
|
|
7988
|
+
const directoryRead = await fs7.readDirectoryBounded(targetPath, MAX_RESULT_LIMIT, signal);
|
|
7989
7989
|
entries = directoryRead.entries;
|
|
7990
7990
|
directoryLimitReached = directoryRead.limitReached;
|
|
7991
7991
|
} catch (e) {
|
|
@@ -8009,13 +8009,13 @@ function createLsTool(cwd, options) {
|
|
|
8009
8009
|
entryLimitReached = true;
|
|
8010
8010
|
break;
|
|
8011
8011
|
}
|
|
8012
|
-
const fullPath =
|
|
8012
|
+
const fullPath = fs7.join(targetPath, entry);
|
|
8013
8013
|
let suffix = "";
|
|
8014
8014
|
try {
|
|
8015
|
-
const linkStat =
|
|
8015
|
+
const linkStat = fs7.lstatSync?.(fullPath);
|
|
8016
8016
|
if (linkStat?.isSymbolicLink) {
|
|
8017
8017
|
suffix = "@";
|
|
8018
|
-
} else if ((linkStat ?? await
|
|
8018
|
+
} else if ((linkStat ?? await fs7.stat(fullPath)).isDirectory) {
|
|
8019
8019
|
suffix = "/";
|
|
8020
8020
|
}
|
|
8021
8021
|
} catch {
|
|
@@ -8028,7 +8028,7 @@ function createLsTool(cwd, options) {
|
|
|
8028
8028
|
if (results.length === 0) {
|
|
8029
8029
|
const listingIncomplete = skippedEntry || entryLimitReached;
|
|
8030
8030
|
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)";
|
|
8031
|
-
|
|
8031
|
+
resolve5({
|
|
8032
8032
|
content: [{ type: "text", text: emptyText }],
|
|
8033
8033
|
details: listingIncomplete ? {
|
|
8034
8034
|
listingIncomplete: true,
|
|
@@ -8059,7 +8059,7 @@ function createLsTool(cwd, options) {
|
|
|
8059
8059
|
|
|
8060
8060
|
[${notices.join(". ")}]`;
|
|
8061
8061
|
}
|
|
8062
|
-
|
|
8062
|
+
resolve5({
|
|
8063
8063
|
content: [{ type: "text", text: output }],
|
|
8064
8064
|
details: Object.keys(details).length > 0 ? details : void 0
|
|
8065
8065
|
});
|
|
@@ -8141,17 +8141,17 @@ function parseGitignore(content) {
|
|
|
8141
8141
|
function createEmptyGitignoreMatcher(incomplete = false) {
|
|
8142
8142
|
return Object.assign((_relativePath, _isDirectory) => false, { incomplete, hasRules: false });
|
|
8143
8143
|
}
|
|
8144
|
-
async function loadGitignoreMatcher(rootPath,
|
|
8144
|
+
async function loadGitignoreMatcher(rootPath, fs7, options) {
|
|
8145
8145
|
let rules = [];
|
|
8146
8146
|
let incomplete = false;
|
|
8147
|
-
const filepath =
|
|
8147
|
+
const filepath = fs7.join(rootPath, ".gitignore");
|
|
8148
8148
|
try {
|
|
8149
8149
|
if (options?.signal?.aborted) throw new Error("Operation aborted");
|
|
8150
|
-
if (!await
|
|
8150
|
+
if (!await fs7.exists(filepath)) return createEmptyGitignoreMatcher();
|
|
8151
8151
|
options?.validatePath?.(filepath);
|
|
8152
|
-
const stat = await
|
|
8152
|
+
const stat = await fs7.stat(filepath);
|
|
8153
8153
|
if (!stat.isFile || stat.size > MAX_GITIGNORE_BYTES) return createEmptyGitignoreMatcher(true);
|
|
8154
|
-
const bytes = await
|
|
8154
|
+
const bytes = await fs7.readFilePrefix(filepath, MAX_GITIGNORE_BYTES + 1);
|
|
8155
8155
|
if (options?.signal?.aborted) throw new Error("Operation aborted");
|
|
8156
8156
|
if (bytes.byteLength > MAX_GITIGNORE_BYTES) return createEmptyGitignoreMatcher(true);
|
|
8157
8157
|
const parsed = parseGitignore(new TextDecoder().decode(bytes));
|
|
@@ -10235,8 +10235,8 @@ function waitForFileCompletion(requestId) {
|
|
|
10235
10235
|
if (existing) {
|
|
10236
10236
|
return Promise.resolve(existing);
|
|
10237
10237
|
}
|
|
10238
|
-
return new Promise((
|
|
10239
|
-
store.waiters.set(requestId,
|
|
10238
|
+
return new Promise((resolve5) => {
|
|
10239
|
+
store.waiters.set(requestId, resolve5);
|
|
10240
10240
|
});
|
|
10241
10241
|
}
|
|
10242
10242
|
async function runNativeGrep(searchPath, pattern, globPattern, ignoreCase, literal, contextLines, limit, outputMode, offset, signal) {
|
|
@@ -10353,7 +10353,7 @@ function sortFileSummariesByMtime(files) {
|
|
|
10353
10353
|
return left.relativePath.localeCompare(right.relativePath);
|
|
10354
10354
|
});
|
|
10355
10355
|
}
|
|
10356
|
-
async function collectFilesForGrep(dirPath, globPattern,
|
|
10356
|
+
async function collectFilesForGrep(dirPath, globPattern, fs7, isGitignored = createEmptyGitignoreMatcher(), assertReadablePath = (path9) => path9, signal, fileGlobMatcher) {
|
|
10357
10357
|
const matchesGlob = globPattern === void 0 ? void 0 : fileGlobMatcher ?? createGrepGlobMatcher(globPattern);
|
|
10358
10358
|
const files = [];
|
|
10359
10359
|
const queue = [{ dir: dirPath, relPrefix: "" }];
|
|
@@ -10368,7 +10368,7 @@ async function collectFilesForGrep(dirPath, globPattern, fs6, isGitignored = cre
|
|
|
10368
10368
|
if (signal?.aborted) throw new Error("Operation aborted");
|
|
10369
10369
|
const { dir: requestedDir, relPrefix } = queue.pop();
|
|
10370
10370
|
const dir = assertReadablePath(requestedDir);
|
|
10371
|
-
const canonicalDir =
|
|
10371
|
+
const canonicalDir = fs7.realpathSync ? fs7.normalize(fs7.realpathSync(dir)) : fs7.normalize(dir);
|
|
10372
10372
|
if (visitedDirectories.has(canonicalDir)) continue;
|
|
10373
10373
|
visitedDirectories.add(canonicalDir);
|
|
10374
10374
|
if (++scannedDirectories > maxScannedDirectories) {
|
|
@@ -10379,7 +10379,7 @@ async function collectFilesForGrep(dirPath, globPattern, fs6, isGitignored = cre
|
|
|
10379
10379
|
}
|
|
10380
10380
|
let entries;
|
|
10381
10381
|
try {
|
|
10382
|
-
const directoryRead = await
|
|
10382
|
+
const directoryRead = await fs7.readDirectoryBounded(dir, maxDirectoryEntries, signal);
|
|
10383
10383
|
entries = directoryRead.entries.slice().sort((left, right) => left.localeCompare(right));
|
|
10384
10384
|
if (directoryRead.limitReached) {
|
|
10385
10385
|
incomplete = true;
|
|
@@ -10392,12 +10392,12 @@ async function collectFilesForGrep(dirPath, globPattern, fs6, isGitignored = cre
|
|
|
10392
10392
|
}
|
|
10393
10393
|
for (const entry of entries) {
|
|
10394
10394
|
if (signal?.aborted) throw new Error("Operation aborted");
|
|
10395
|
-
const requestedPath =
|
|
10395
|
+
const requestedPath = fs7.join(dir, entry);
|
|
10396
10396
|
const fullPath = assertReadablePath(requestedPath);
|
|
10397
10397
|
const relPath = relPrefix ? `${relPrefix}/${entry}` : entry;
|
|
10398
10398
|
let stat;
|
|
10399
10399
|
try {
|
|
10400
|
-
stat = await
|
|
10400
|
+
stat = await fs7.stat(fullPath);
|
|
10401
10401
|
} catch {
|
|
10402
10402
|
incomplete = true;
|
|
10403
10403
|
continue;
|
|
@@ -10412,7 +10412,7 @@ async function collectFilesForGrep(dirPath, globPattern, fs6, isGitignored = cre
|
|
|
10412
10412
|
}
|
|
10413
10413
|
} else if (stat.isFile) {
|
|
10414
10414
|
if (isGitignored(relPath, false)) continue;
|
|
10415
|
-
const ext2 =
|
|
10415
|
+
const ext2 = fs7.extname(entry).toLowerCase();
|
|
10416
10416
|
if (BINARY_EXTENSIONS.has(ext2)) continue;
|
|
10417
10417
|
if (matchesGlob && !matchesGlob(relPath)) continue;
|
|
10418
10418
|
files.push(fullPath);
|
|
@@ -10423,7 +10423,7 @@ async function collectFilesForGrep(dirPath, globPattern, fs6, isGitignored = cre
|
|
|
10423
10423
|
return { files, truncated: traversalTruncated, incomplete, ...safetyLimit ? { safetyLimit } : {} };
|
|
10424
10424
|
}
|
|
10425
10425
|
function createGrepTextTool(cwd, options) {
|
|
10426
|
-
const
|
|
10426
|
+
const fs7 = getFileSystem();
|
|
10427
10427
|
const platform = detectPlatform();
|
|
10428
10428
|
const rootSchema = buildRootParameterSchema(cwd, options);
|
|
10429
10429
|
const grepSchema = Type.Object({
|
|
@@ -10476,7 +10476,7 @@ function createGrepTextTool(cwd, options) {
|
|
|
10476
10476
|
isError: true
|
|
10477
10477
|
};
|
|
10478
10478
|
}
|
|
10479
|
-
return new Promise((
|
|
10479
|
+
return new Promise((resolve5, reject) => {
|
|
10480
10480
|
if (signal?.aborted) {
|
|
10481
10481
|
reject(new Error("Operation aborted"));
|
|
10482
10482
|
return;
|
|
@@ -10494,10 +10494,10 @@ function createGrepTextTool(cwd, options) {
|
|
|
10494
10494
|
const ctx = Math.min(normalizeNonNegativeInteger(contextLines, 0, "context"), MAX_GREP_CONTEXT_LINES);
|
|
10495
10495
|
let isDir;
|
|
10496
10496
|
try {
|
|
10497
|
-
const stat = await
|
|
10497
|
+
const stat = await fs7.stat(searchPath);
|
|
10498
10498
|
isDir = stat.isDirectory;
|
|
10499
10499
|
} catch {
|
|
10500
|
-
|
|
10500
|
+
resolve5({
|
|
10501
10501
|
content: [{ type: "text", text: `grep_text failed: Path not found: ${searchPath}
|
|
10502
10502
|
Check the path or search from the workspace root.` }],
|
|
10503
10503
|
details: { searchIncomplete: true, safetyLimit: "io_error" },
|
|
@@ -10505,7 +10505,7 @@ Check the path or search from the workspace root.` }],
|
|
|
10505
10505
|
});
|
|
10506
10506
|
return;
|
|
10507
10507
|
}
|
|
10508
|
-
const isGitignored = await loadGitignoreMatcher(searchPath,
|
|
10508
|
+
const isGitignored = await loadGitignoreMatcher(searchPath, fs7, {
|
|
10509
10509
|
signal,
|
|
10510
10510
|
validatePath: (candidate) => resolveToCwd(candidate, cwd, options, root)
|
|
10511
10511
|
});
|
|
@@ -10528,7 +10528,7 @@ Check the path or search from the workspace root.` }],
|
|
|
10528
10528
|
} else {
|
|
10529
10529
|
}
|
|
10530
10530
|
} catch (e) {
|
|
10531
|
-
|
|
10531
|
+
resolve5({
|
|
10532
10532
|
content: [{ type: "text", text: boundedErrorMessage("grep_text failed: invalid regex pattern", e, "Use literal=true for plain text, or simplify the regex.") }],
|
|
10533
10533
|
details: { searchIncomplete: true, safetyLimit: "io_error" },
|
|
10534
10534
|
isError: true
|
|
@@ -10581,7 +10581,7 @@ Check the path or search from the workspace root.` }],
|
|
|
10581
10581
|
const collection = await collectFilesForGrep(
|
|
10582
10582
|
searchPath,
|
|
10583
10583
|
globPattern,
|
|
10584
|
-
|
|
10584
|
+
fs7,
|
|
10585
10585
|
isGitignored,
|
|
10586
10586
|
(filePath) => resolveToCwd(filePath, cwd, options, root),
|
|
10587
10587
|
signal,
|
|
@@ -10605,7 +10605,7 @@ Check the path or search from the workspace root.` }],
|
|
|
10605
10605
|
let content;
|
|
10606
10606
|
let fileStatBefore;
|
|
10607
10607
|
try {
|
|
10608
|
-
fileStatBefore = await
|
|
10608
|
+
fileStatBefore = await fs7.stat(filePath);
|
|
10609
10609
|
if (textBytesScanned + fileStatBefore.size > MAX_TEXT_GREP_TOTAL_BYTES) {
|
|
10610
10610
|
skippedUnboundedFile = true;
|
|
10611
10611
|
safetyLimit = "total_bytes";
|
|
@@ -10617,7 +10617,7 @@ Check the path or search from the workspace root.` }],
|
|
|
10617
10617
|
safetyLimit ??= "file_size";
|
|
10618
10618
|
continue;
|
|
10619
10619
|
}
|
|
10620
|
-
const inspected = await
|
|
10620
|
+
const inspected = await fs7.readTextRange(filePath, {
|
|
10621
10621
|
offsetLine: 0,
|
|
10622
10622
|
maxOutputLines: MAX_TEXT_GREP_FILE_LINES,
|
|
10623
10623
|
maxOutputBytes: MAX_TEXT_GREP_FILE_BYTES
|
|
@@ -10645,7 +10645,7 @@ Check the path or search from the workspace root.` }],
|
|
|
10645
10645
|
continue;
|
|
10646
10646
|
}
|
|
10647
10647
|
const lines = content.replace(/\r\n/g, "\n").replace(/\r/g, "\n").split("\n");
|
|
10648
|
-
const relativePath = isDir ?
|
|
10648
|
+
const relativePath = isDir ? fs7.relative(searchPath, filePath) : fs7.basename(filePath);
|
|
10649
10649
|
filesScanned++;
|
|
10650
10650
|
let fileMatchCount = 0;
|
|
10651
10651
|
const pageMatchLines = [];
|
|
@@ -10674,7 +10674,7 @@ Check the path or search from the workspace root.` }],
|
|
|
10674
10674
|
contentOutputBudgetReached ||= formatted.outputBudgetReached;
|
|
10675
10675
|
}
|
|
10676
10676
|
if (fileMatchCount > 0) {
|
|
10677
|
-
const fileStat = fileStatBefore ?? await
|
|
10677
|
+
const fileStat = fileStatBefore ?? await fs7.stat(filePath);
|
|
10678
10678
|
fileSummaries.set(filePath, {
|
|
10679
10679
|
filePath,
|
|
10680
10680
|
relativePath,
|
|
@@ -10708,7 +10708,7 @@ Check the path or search from the workspace root.` }],
|
|
|
10708
10708
|
signal?.removeEventListener("abort", onAbort);
|
|
10709
10709
|
if (matchCount === 0) {
|
|
10710
10710
|
const incompleteNotice = skippedUnboundedFile ? "\n\n[Search incomplete: a filesystem safety limit was reached. Narrow the path or glob and search again]" : "";
|
|
10711
|
-
|
|
10711
|
+
resolve5({
|
|
10712
10712
|
content: [{ type: "text", text: `No matches found${incompleteNotice}` }],
|
|
10713
10713
|
details: {
|
|
10714
10714
|
noMatches: true,
|
|
@@ -10763,7 +10763,7 @@ Check the path or search from the workspace root.` }],
|
|
|
10763
10763
|
|
|
10764
10764
|
[${notices.join(". ")}]`;
|
|
10765
10765
|
}
|
|
10766
|
-
|
|
10766
|
+
resolve5({
|
|
10767
10767
|
content: [{ type: "text", text: output }],
|
|
10768
10768
|
details: Object.keys(details).length > 0 ? details : void 0
|
|
10769
10769
|
});
|
|
@@ -10773,7 +10773,7 @@ Check the path or search from the workspace root.` }],
|
|
|
10773
10773
|
reject(err);
|
|
10774
10774
|
return;
|
|
10775
10775
|
}
|
|
10776
|
-
|
|
10776
|
+
resolve5({
|
|
10777
10777
|
content: [{ type: "text", text: boundedErrorMessage("grep_text failed", err, "Check the path/pattern, use literal=true for plain text, or narrow the search.") }],
|
|
10778
10778
|
details: { searchIncomplete: true, safetyLimit: "io_error" },
|
|
10779
10779
|
isError: true
|
|
@@ -10850,8 +10850,8 @@ function waitForFileCompletion2(requestId) {
|
|
|
10850
10850
|
if (existing) {
|
|
10851
10851
|
return Promise.resolve(existing);
|
|
10852
10852
|
}
|
|
10853
|
-
return new Promise((
|
|
10854
|
-
store.waiters.set(requestId,
|
|
10853
|
+
return new Promise((resolve5) => {
|
|
10854
|
+
store.waiters.set(requestId, resolve5);
|
|
10855
10855
|
});
|
|
10856
10856
|
}
|
|
10857
10857
|
async function runNativeFind(searchPath, pattern, limit, signal) {
|
|
@@ -10883,7 +10883,7 @@ async function runNativeFind(searchPath, pattern, limit, signal) {
|
|
|
10883
10883
|
bridge.ReleaseRequest(requestId);
|
|
10884
10884
|
}
|
|
10885
10885
|
}
|
|
10886
|
-
async function globFiles(rootPath, matchesPattern,
|
|
10886
|
+
async function globFiles(rootPath, matchesPattern, fs7, limit, signal, isGitignored = createEmptyGitignoreMatcher(), validatePath = () => {
|
|
10887
10887
|
}, incompleteState = { value: false }) {
|
|
10888
10888
|
const results = [];
|
|
10889
10889
|
const queue = [{ dir: rootPath, relPrefix: "" }];
|
|
@@ -10896,7 +10896,7 @@ async function globFiles(rootPath, matchesPattern, fs6, limit, signal, isGitigno
|
|
|
10896
10896
|
}
|
|
10897
10897
|
const { dir, relPrefix } = queue.shift();
|
|
10898
10898
|
validatePath(dir);
|
|
10899
|
-
const canonicalDir =
|
|
10899
|
+
const canonicalDir = fs7.realpathSync ? fs7.normalize(fs7.realpathSync(dir)) : fs7.normalize(dir);
|
|
10900
10900
|
if (visitedDirectories.has(canonicalDir)) continue;
|
|
10901
10901
|
visitedDirectories.add(canonicalDir);
|
|
10902
10902
|
if (++scannedDirectories > MAX_SCANNED_DIRECTORIES) {
|
|
@@ -10905,7 +10905,7 @@ async function globFiles(rootPath, matchesPattern, fs6, limit, signal, isGitigno
|
|
|
10905
10905
|
}
|
|
10906
10906
|
let entries;
|
|
10907
10907
|
try {
|
|
10908
|
-
const directoryRead = await
|
|
10908
|
+
const directoryRead = await fs7.readDirectoryBounded(dir, MAX_DIRECTORY_ENTRIES, signal);
|
|
10909
10909
|
entries = directoryRead.entries;
|
|
10910
10910
|
if (directoryRead.limitReached) incompleteState.value = true;
|
|
10911
10911
|
} catch {
|
|
@@ -10915,12 +10915,12 @@ async function globFiles(rootPath, matchesPattern, fs6, limit, signal, isGitigno
|
|
|
10915
10915
|
for (const entry of entries) {
|
|
10916
10916
|
if (signal?.aborted) throw new Error("Operation aborted");
|
|
10917
10917
|
if (results.length >= limit) break;
|
|
10918
|
-
const fullPath =
|
|
10918
|
+
const fullPath = fs7.join(dir, entry);
|
|
10919
10919
|
const relPath = relPrefix ? relPrefix + "/" + entry : entry;
|
|
10920
10920
|
validatePath(fullPath);
|
|
10921
10921
|
let stat;
|
|
10922
10922
|
try {
|
|
10923
|
-
stat = await
|
|
10923
|
+
stat = await fs7.stat(fullPath);
|
|
10924
10924
|
} catch {
|
|
10925
10925
|
incompleteState.value = true;
|
|
10926
10926
|
continue;
|
|
@@ -10948,7 +10948,7 @@ async function globFiles(rootPath, matchesPattern, fs6, limit, signal, isGitigno
|
|
|
10948
10948
|
return results;
|
|
10949
10949
|
}
|
|
10950
10950
|
function createFindFilesTool(cwd, options) {
|
|
10951
|
-
const
|
|
10951
|
+
const fs7 = getFileSystem();
|
|
10952
10952
|
const platform = detectPlatform();
|
|
10953
10953
|
const rootSchema = buildRootParameterSchema(cwd, options);
|
|
10954
10954
|
const findSchema = Type.Object({
|
|
@@ -10978,7 +10978,7 @@ function createFindFilesTool(cwd, options) {
|
|
|
10978
10978
|
isError: true
|
|
10979
10979
|
};
|
|
10980
10980
|
}
|
|
10981
|
-
return new Promise((
|
|
10981
|
+
return new Promise((resolve5, reject) => {
|
|
10982
10982
|
if (signal?.aborted) {
|
|
10983
10983
|
reject(new Error("Operation aborted"));
|
|
10984
10984
|
return;
|
|
@@ -10992,14 +10992,14 @@ function createFindFilesTool(cwd, options) {
|
|
|
10992
10992
|
resolveToCwd(candidate, cwd, options, root);
|
|
10993
10993
|
};
|
|
10994
10994
|
const validateReturnedPath = (candidate) => {
|
|
10995
|
-
validateResultPath(
|
|
10995
|
+
validateResultPath(fs7.isAbsolute(candidate) ? candidate : fs7.join(searchPath, candidate));
|
|
10996
10996
|
};
|
|
10997
10997
|
const effectiveLimit = limit ?? DEFAULT_LIMIT3;
|
|
10998
10998
|
if (!Number.isInteger(effectiveLimit) || effectiveLimit < 1 || effectiveLimit > MAX_RESULT_LIMIT2) {
|
|
10999
10999
|
throw new Error(`Invalid find_files arguments: limit must be between 1 and ${MAX_RESULT_LIMIT2}.`);
|
|
11000
11000
|
}
|
|
11001
|
-
if (!await
|
|
11002
|
-
|
|
11001
|
+
if (!await fs7.exists(searchPath)) {
|
|
11002
|
+
resolve5({
|
|
11003
11003
|
content: [{ type: "text", text: `find_files failed: Path not found: ${searchPath}
|
|
11004
11004
|
Check the path or search from the workspace root.` }],
|
|
11005
11005
|
details: { searchIncomplete: true },
|
|
@@ -11010,7 +11010,7 @@ Check the path or search from the workspace root.` }],
|
|
|
11010
11010
|
let results;
|
|
11011
11011
|
let resultLimitReached = false;
|
|
11012
11012
|
const incompleteState = { value: false };
|
|
11013
|
-
const isGitignored = await loadGitignoreMatcher(searchPath,
|
|
11013
|
+
const isGitignored = await loadGitignoreMatcher(searchPath, fs7, { signal, validatePath: validateResultPath });
|
|
11014
11014
|
incompleteState.value ||= isGitignored.incomplete;
|
|
11015
11015
|
if (platform === "puerts" && getNativeFileBridge2() && !isGitignored.hasRules) {
|
|
11016
11016
|
const nativeResult = await runNativeFind(searchPath, pattern, effectiveLimit, signal);
|
|
@@ -11023,12 +11023,12 @@ Check the path or search from the workspace root.` }],
|
|
|
11023
11023
|
`[find_files] path=${searchPath} pattern=${pattern} matches=${results.length} dirs=${nativeResult.ScannedDirectories ?? 0} files=${nativeResult.ScannedFiles ?? 0}`
|
|
11024
11024
|
);
|
|
11025
11025
|
} else if (platform === "node") {
|
|
11026
|
-
const allResults = await globFiles(searchPath, matchesPattern,
|
|
11026
|
+
const allResults = await globFiles(searchPath, matchesPattern, fs7, effectiveLimit + 1, signal, isGitignored, validateResultPath, incompleteState);
|
|
11027
11027
|
incompleteState.value ||= isGitignored.incomplete;
|
|
11028
11028
|
resultLimitReached = allResults.length > effectiveLimit;
|
|
11029
11029
|
results = allResults.slice(0, effectiveLimit);
|
|
11030
11030
|
} else {
|
|
11031
|
-
const allResults = await globFiles(searchPath, matchesPattern,
|
|
11031
|
+
const allResults = await globFiles(searchPath, matchesPattern, fs7, effectiveLimit + 1, signal, isGitignored, validateResultPath, incompleteState);
|
|
11032
11032
|
incompleteState.value ||= isGitignored.incomplete;
|
|
11033
11033
|
resultLimitReached = allResults.length > effectiveLimit;
|
|
11034
11034
|
results = allResults.slice(0, effectiveLimit);
|
|
@@ -11036,7 +11036,7 @@ Check the path or search from the workspace root.` }],
|
|
|
11036
11036
|
signal?.removeEventListener("abort", onAbort);
|
|
11037
11037
|
if (results.length === 0) {
|
|
11038
11038
|
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]" : "";
|
|
11039
|
-
|
|
11039
|
+
resolve5({
|
|
11040
11040
|
content: [{ type: "text", text: `No files found matching pattern${incompleteNotice}` }],
|
|
11041
11041
|
details: {
|
|
11042
11042
|
noMatches: true,
|
|
@@ -11065,7 +11065,7 @@ Check the path or search from the workspace root.` }],
|
|
|
11065
11065
|
if (notices.length > 0) {
|
|
11066
11066
|
resultOutput += "\n\n[" + notices.join(". ") + "]";
|
|
11067
11067
|
}
|
|
11068
|
-
|
|
11068
|
+
resolve5({
|
|
11069
11069
|
content: [{ type: "text", text: resultOutput }],
|
|
11070
11070
|
details: Object.keys(details).length > 0 ? details : void 0
|
|
11071
11071
|
});
|
|
@@ -11076,7 +11076,7 @@ Check the path or search from the workspace root.` }],
|
|
|
11076
11076
|
reject(e);
|
|
11077
11077
|
return;
|
|
11078
11078
|
}
|
|
11079
|
-
|
|
11079
|
+
resolve5({
|
|
11080
11080
|
content: [{ type: "text", text: boundedFindError(e) }],
|
|
11081
11081
|
details: { searchIncomplete: true },
|
|
11082
11082
|
isError: true
|
|
@@ -11650,8 +11650,8 @@ function isSearchPageSource(source) {
|
|
|
11650
11650
|
function isHomepageSource(source) {
|
|
11651
11651
|
const parsed = sourceHostAndPath(source);
|
|
11652
11652
|
if (!parsed) return false;
|
|
11653
|
-
const
|
|
11654
|
-
return
|
|
11653
|
+
const path9 = parsed.path.replace(/\/+$/, "");
|
|
11654
|
+
return path9 === "" || path9 === "/news" || path9 === "/sections/news";
|
|
11655
11655
|
}
|
|
11656
11656
|
function evaluateSearchQuality(search) {
|
|
11657
11657
|
const warnings = [];
|
|
@@ -11683,8 +11683,8 @@ async function runQueuedSearch(model, fn) {
|
|
|
11683
11683
|
const key = `${model.provider}/${model.id}`;
|
|
11684
11684
|
const previous = SEARCH_PROVIDER_QUEUE.get(key) ?? Promise.resolve();
|
|
11685
11685
|
let release;
|
|
11686
|
-
const next = new Promise((
|
|
11687
|
-
release =
|
|
11686
|
+
const next = new Promise((resolve5) => {
|
|
11687
|
+
release = resolve5;
|
|
11688
11688
|
});
|
|
11689
11689
|
const queued = previous.catch(() => void 0).then(() => next);
|
|
11690
11690
|
SEARCH_PROVIDER_QUEUE.set(key, queued);
|
|
@@ -12158,10 +12158,10 @@ function assistantText(message) {
|
|
|
12158
12158
|
async function withAbort(promise, signal) {
|
|
12159
12159
|
if (!signal) return promise;
|
|
12160
12160
|
if (signal.aborted) throw signal.reason ?? new Error("operation aborted");
|
|
12161
|
-
return await new Promise((
|
|
12161
|
+
return await new Promise((resolve5, reject) => {
|
|
12162
12162
|
const onAbort = () => reject(signal.reason ?? new Error("operation aborted"));
|
|
12163
12163
|
signal.addEventListener("abort", onAbort, { once: true });
|
|
12164
|
-
promise.then(
|
|
12164
|
+
promise.then(resolve5, reject).finally(() => signal.removeEventListener("abort", onAbort));
|
|
12165
12165
|
});
|
|
12166
12166
|
}
|
|
12167
12167
|
async function cancelResponseBody(response) {
|
|
@@ -12172,13 +12172,13 @@ async function cancelResponseBody(response) {
|
|
|
12172
12172
|
}
|
|
12173
12173
|
var DISCARD_BODY_GRACE_MS = 250;
|
|
12174
12174
|
async function discardResponseBody(response) {
|
|
12175
|
-
await new Promise((
|
|
12175
|
+
await new Promise((resolve5) => {
|
|
12176
12176
|
let settled = false;
|
|
12177
12177
|
const settle = () => {
|
|
12178
12178
|
if (settled) return;
|
|
12179
12179
|
settled = true;
|
|
12180
12180
|
clearTimeout(timer);
|
|
12181
|
-
|
|
12181
|
+
resolve5();
|
|
12182
12182
|
};
|
|
12183
12183
|
const timer = setTimeout(settle, DISCARD_BODY_GRACE_MS);
|
|
12184
12184
|
try {
|
|
@@ -12893,13 +12893,13 @@ async function runWithDeadline(operation, timeoutMs, message, parentSignal) {
|
|
|
12893
12893
|
const child = createChildSignal(parentSignal);
|
|
12894
12894
|
let timer;
|
|
12895
12895
|
try {
|
|
12896
|
-
return await new Promise((
|
|
12896
|
+
return await new Promise((resolve5, reject) => {
|
|
12897
12897
|
timer = setTimeout(() => {
|
|
12898
12898
|
const error = new Error(message);
|
|
12899
12899
|
child.abort(error);
|
|
12900
12900
|
reject(error);
|
|
12901
12901
|
}, timeoutMs);
|
|
12902
|
-
operation(child.signal).then(
|
|
12902
|
+
operation(child.signal).then(resolve5, reject);
|
|
12903
12903
|
});
|
|
12904
12904
|
} finally {
|
|
12905
12905
|
if (timer) clearTimeout(timer);
|
|
@@ -14883,6 +14883,7 @@ function harvestSessionsForDate(store, date, options = {}) {
|
|
|
14883
14883
|
const prefilter = storeSupportsSummaries(store);
|
|
14884
14884
|
const results = [];
|
|
14885
14885
|
for (const sessionId of store.list()) {
|
|
14886
|
+
if (isInfrastructureSession(sessionId)) continue;
|
|
14886
14887
|
const metadata = store.getMetadata(sessionId);
|
|
14887
14888
|
if (!metadata) continue;
|
|
14888
14889
|
if (options.cwdFilter && !options.cwdFilter(typeof metadata.cwd === "string" ? metadata.cwd : void 0)) {
|
|
@@ -14940,6 +14941,9 @@ function datesBetween(fromTs, toTs) {
|
|
|
14940
14941
|
}
|
|
14941
14942
|
return dates;
|
|
14942
14943
|
}
|
|
14944
|
+
function isInfrastructureSession(sessionId) {
|
|
14945
|
+
return sessionId.startsWith("concierge-") || sessionId.startsWith("manager-") || sessionId.startsWith("pie-proc-");
|
|
14946
|
+
}
|
|
14943
14947
|
|
|
14944
14948
|
// ../../packages/shared-headless-capabilities/src/memory/distill.ts
|
|
14945
14949
|
function buildDistillPrompt(session) {
|
|
@@ -14988,6 +14992,33 @@ function extractJsonArray(response) {
|
|
|
14988
14992
|
if (start === -1 || end === -1 || end <= start) return null;
|
|
14989
14993
|
return response.slice(start, end + 1);
|
|
14990
14994
|
}
|
|
14995
|
+
function buildRetireSuggestions(entries, now = Date.now()) {
|
|
14996
|
+
return entries.filter((entry) => {
|
|
14997
|
+
if (typeof entry.retiredAt === "number") return false;
|
|
14998
|
+
if (entry.provenance === "user-attested") return false;
|
|
14999
|
+
const inj = entry.injectedCount ?? 0;
|
|
15000
|
+
const cons = entry.consumedCount ?? 0;
|
|
15001
|
+
const idleMs = now - (entry.lastAccessed || entry.created);
|
|
15002
|
+
return inj >= 10 && cons === 0 && idleMs >= 30 * 24 * 3600 * 1e3;
|
|
15003
|
+
}).sort((a, b) => (b.injectedCount ?? 0) - (a.injectedCount ?? 0)).slice(0, 10).map((entry) => ({
|
|
15004
|
+
id: entry.id,
|
|
15005
|
+
text: entry.text.length > 90 ? `${entry.text.slice(0, 90)}\u2026` : entry.text,
|
|
15006
|
+
injectedCount: entry.injectedCount ?? 0,
|
|
15007
|
+
consumedCount: entry.consumedCount ?? 0,
|
|
15008
|
+
lastAccessed: entry.lastAccessed || entry.created
|
|
15009
|
+
}));
|
|
15010
|
+
}
|
|
15011
|
+
function appendRetireSection(journal, suggestions) {
|
|
15012
|
+
if (suggestions.length === 0) return journal;
|
|
15013
|
+
const lines = [
|
|
15014
|
+
"",
|
|
15015
|
+
"## Retire suggestions (zero-consumption aging)",
|
|
15016
|
+
"These entries were injected >=10 times, never used, and idle >=30 days. Review and retire manually \u2014 suggestions only, nothing was changed.",
|
|
15017
|
+
...suggestions.map((s) => `- ${s.id}: ${s.text} (inj ${s.injectedCount}/cons ${s.consumedCount})`)
|
|
15018
|
+
];
|
|
15019
|
+
return `${journal}${lines.join("\n")}
|
|
15020
|
+
`;
|
|
15021
|
+
}
|
|
14991
15022
|
async function distillSession(session, call) {
|
|
14992
15023
|
const response = await call(buildDistillPrompt(session), { system: DISTILL_SYSTEM });
|
|
14993
15024
|
return parseDistillResponse(response);
|
|
@@ -15468,20 +15499,88 @@ function readMemoryFile(store, relativePath) {
|
|
|
15468
15499
|
}
|
|
15469
15500
|
|
|
15470
15501
|
// ../../packages/shared-headless-capabilities/src/memory/engine.ts
|
|
15502
|
+
import * as fs6 from "node:fs";
|
|
15503
|
+
import * as path8 from "node:path";
|
|
15504
|
+
|
|
15505
|
+
// ../../packages/shared-headless-capabilities/src/memory/ledger.ts
|
|
15471
15506
|
import * as fs5 from "node:fs";
|
|
15472
15507
|
import * as path7 from "node:path";
|
|
15508
|
+
import { randomUUID } from "node:crypto";
|
|
15509
|
+
var FILE = "evidence-ledger.json";
|
|
15510
|
+
var DAYS = 7;
|
|
15511
|
+
var MAX_CLUSTERS = 128;
|
|
15512
|
+
var MAX_SESSIONS = 8;
|
|
15513
|
+
var MAX_BYTES = 8 * 1024 * 1024;
|
|
15514
|
+
var validDate = (s) => typeof s === "string" && /^\d{4}-\d{2}-\d{2}$/.test(s) && Number.isFinite(Date.parse(s)) && new Date(s).toISOString().slice(0, 10) === s;
|
|
15515
|
+
var cutoffFor = (date) => new Date(Date.parse(date) - (DAYS - 1) * 864e5).toISOString().slice(0, 10);
|
|
15516
|
+
function decode(value) {
|
|
15517
|
+
const empty = { version: 1, days: [] };
|
|
15518
|
+
if (!value || typeof value !== "object") return empty;
|
|
15519
|
+
const data = value;
|
|
15520
|
+
if (data.version !== 1 || !Array.isArray(data.days) || data.days.length > DAYS) return empty;
|
|
15521
|
+
for (const day of data.days) {
|
|
15522
|
+
if (!day || !validDate(day.date) || !Array.isArray(day.clusters) || day.clusters.length > MAX_CLUSTERS) return empty;
|
|
15523
|
+
for (const c of day.clusters) {
|
|
15524
|
+
if (!c || !["preference", "fact", "thread", "project"].includes(c.kind) || typeof c.text !== "string" || !c.text.trim() || c.text.length > 240 || typeof c.key !== "string" || c.key.length > 80 || c.projectKey !== void 0 && typeof c.projectKey !== "string" || !Array.isArray(c.sessions) || c.sessions.length > MAX_SESSIONS) return empty;
|
|
15525
|
+
if (c.sessions.some((pair) => !Array.isArray(pair) || pair.length !== 2 || typeof pair[0] !== "string" || !pair[0] || !Array.isArray(pair[1]) || pair[1].length === 0 || pair[1].length > 2 || pair[1].some((q) => typeof q !== "string" || !q || q.length > 240))) return empty;
|
|
15526
|
+
}
|
|
15527
|
+
}
|
|
15528
|
+
return data;
|
|
15529
|
+
}
|
|
15530
|
+
function encode(c) {
|
|
15531
|
+
return {
|
|
15532
|
+
key: normalizeForClustering(redactText(c.text).text).slice(0, 80),
|
|
15533
|
+
kind: c.kind,
|
|
15534
|
+
text: redactText(c.text).text.slice(0, 240),
|
|
15535
|
+
...c.projectKey ? { projectKey: c.projectKey } : {},
|
|
15536
|
+
sessions: [...c.sessions].slice(0, MAX_SESSIONS).map(([id, quotes]) => [id, [...new Set(quotes)].slice(0, 2).map((q) => redactText(q).text.slice(0, 240))])
|
|
15537
|
+
};
|
|
15538
|
+
}
|
|
15539
|
+
function prepareEvidenceLedger(dir, date, today) {
|
|
15540
|
+
if (!validDate(date)) throw new Error("invalid evidence date");
|
|
15541
|
+
const file = path7.join(dir, FILE);
|
|
15542
|
+
let ledger = { version: 1, days: [] };
|
|
15543
|
+
try {
|
|
15544
|
+
if (fs5.statSync(file).size <= MAX_BYTES) ledger = decode(JSON.parse(fs5.readFileSync(file, "utf8")));
|
|
15545
|
+
} catch (error) {
|
|
15546
|
+
if (!(error instanceof SyntaxError) && error.code !== "ENOENT") throw error;
|
|
15547
|
+
}
|
|
15548
|
+
const cutoff = cutoffFor(date);
|
|
15549
|
+
const prior = ledger.days.filter((day) => day.date < date && day.date >= cutoff);
|
|
15550
|
+
const clusters = today.map((c) => ({ ...c, sessions: new Map([...c.sessions].map(([id, quotes]) => [id, [...quotes]])) }));
|
|
15551
|
+
for (const c of clusters) {
|
|
15552
|
+
for (const day of prior) for (const old of day.clusters) {
|
|
15553
|
+
if (old.kind !== c.kind || (old.projectKey ?? "") !== (c.projectKey ?? "") || !equivalentAssertions(old.text, c.text)) continue;
|
|
15554
|
+
for (const [id, quotes] of old.sessions) c.sessions.set(id, [.../* @__PURE__ */ new Set([...c.sessions.get(id) ?? [], ...quotes])].slice(0, 2));
|
|
15555
|
+
}
|
|
15556
|
+
}
|
|
15557
|
+
const latest = ledger.days.reduce((max, day) => day.date > max ? day.date : max, date);
|
|
15558
|
+
const days = [...ledger.days.filter((day) => day.date !== date), { date, clusters: today.slice(0, MAX_CLUSTERS).map(encode) }].filter((day) => day.date >= cutoffFor(latest)).sort((a, b) => a.date.localeCompare(b.date));
|
|
15559
|
+
return { clusters, write() {
|
|
15560
|
+
fs5.mkdirSync(dir, { recursive: true });
|
|
15561
|
+
const tmp = `${file}.${randomUUID()}.tmp`;
|
|
15562
|
+
try {
|
|
15563
|
+
fs5.writeFileSync(tmp, JSON.stringify({ version: 1, days }), { mode: 384 });
|
|
15564
|
+
fs5.renameSync(tmp, file);
|
|
15565
|
+
} finally {
|
|
15566
|
+
fs5.rmSync(tmp, { force: true });
|
|
15567
|
+
}
|
|
15568
|
+
} };
|
|
15569
|
+
}
|
|
15570
|
+
|
|
15571
|
+
// ../../packages/shared-headless-capabilities/src/memory/engine.ts
|
|
15473
15572
|
var inFlight = /* @__PURE__ */ new Set();
|
|
15474
15573
|
function boundedCall(call, timeoutMs, label) {
|
|
15475
15574
|
if (!timeoutMs || timeoutMs <= 0) return call;
|
|
15476
15575
|
return async (prompt, options) => {
|
|
15477
15576
|
let timer;
|
|
15478
15577
|
try {
|
|
15479
|
-
return await new Promise((
|
|
15578
|
+
return await new Promise((resolve5, reject) => {
|
|
15480
15579
|
timer = setTimeout(() => reject(new Error(`${label} timed out after ${timeoutMs}ms`)), timeoutMs);
|
|
15481
15580
|
Promise.resolve(call(prompt, options)).then(
|
|
15482
15581
|
(value) => {
|
|
15483
15582
|
clearTimeout(timer);
|
|
15484
|
-
|
|
15583
|
+
resolve5(value);
|
|
15485
15584
|
},
|
|
15486
15585
|
(error) => {
|
|
15487
15586
|
clearTimeout(timer);
|
|
@@ -15500,7 +15599,7 @@ function boundedCall(call, timeoutMs, label) {
|
|
|
15500
15599
|
var GATED_PATCH_FILE = ".gated-patches.json";
|
|
15501
15600
|
function loadGatedPatches(store) {
|
|
15502
15601
|
try {
|
|
15503
|
-
const raw =
|
|
15602
|
+
const raw = fs6.readFileSync(path8.join(store.dir, GATED_PATCH_FILE), "utf8");
|
|
15504
15603
|
const parsed = JSON.parse(raw);
|
|
15505
15604
|
return Array.isArray(parsed) ? parsed : [];
|
|
15506
15605
|
} catch {
|
|
@@ -15517,9 +15616,9 @@ async function runDistillation(deps, date) {
|
|
|
15517
15616
|
if (deps.memoryStore.hasRun(date)) {
|
|
15518
15617
|
return { date, status: "skipped-ran", sessions: 0, patchOps: 0, journalWritten: false };
|
|
15519
15618
|
}
|
|
15520
|
-
const flightKey =
|
|
15619
|
+
const flightKey = path8.resolve(deps.memoryStore.dir);
|
|
15521
15620
|
if (inFlight.has(flightKey)) {
|
|
15522
|
-
return
|
|
15621
|
+
return failure(date, new Error("distillation for this memory root is already running; retry dates oldest-first"), "busy");
|
|
15523
15622
|
}
|
|
15524
15623
|
inFlight.add(flightKey);
|
|
15525
15624
|
try {
|
|
@@ -15557,16 +15656,30 @@ async function runDistillationInner(deps, date, log, now) {
|
|
|
15557
15656
|
if (session.cwd) projectKeys.set(session.sessionId, projectKeyForDir(session.cwd).key);
|
|
15558
15657
|
}
|
|
15559
15658
|
const clusters = clusterCandidates(distilled, projectKeys);
|
|
15560
|
-
const
|
|
15561
|
-
|
|
15562
|
-
|
|
15563
|
-
|
|
15564
|
-
synthesized
|
|
15565
|
-
|
|
15566
|
-
|
|
15567
|
-
|
|
15659
|
+
const prepare = () => {
|
|
15660
|
+
const ledger = prepareEvidenceLedger(deps.memoryStore.dir, date, clusters);
|
|
15661
|
+
const { passed: passed2, rejected: rejected2 } = gateClusters(ledger.clusters, limits);
|
|
15662
|
+
const entriesBefore = deps.memoryStore.loadEntries();
|
|
15663
|
+
const synthesized = synthesizePatch({ date, clusters: passed2, existingEntries: entriesBefore, projectKeys, limits, now: now() });
|
|
15664
|
+
const refreshedIds = new Set(synthesized.ops.filter((op) => op.op === "update").map((op) => op.id));
|
|
15665
|
+
const retention2 = buildRetentionOps(entriesBefore, limits, now(), refreshedIds);
|
|
15666
|
+
const ops = [...synthesized.ops, ...retention2].slice(0, Math.max(limits.maxPatchOps, 3));
|
|
15667
|
+
return { ledger, passed: passed2, rejected: rejected2, retention: retention2, ops };
|
|
15668
|
+
};
|
|
15669
|
+
let preview;
|
|
15670
|
+
try {
|
|
15671
|
+
preview = deps.memoryStore.transaction(prepare);
|
|
15672
|
+
} catch (error) {
|
|
15673
|
+
return failure(date, error, "evidence");
|
|
15674
|
+
}
|
|
15675
|
+
const { passed, rejected, retention } = preview;
|
|
15568
15676
|
const language = detectLanguage(sessions);
|
|
15569
15677
|
let journalWritten = false;
|
|
15678
|
+
const retiringNow = new Set(retention.filter((op) => op.op === "retire").map((op) => op.id));
|
|
15679
|
+
const retireSuggestions = buildRetireSuggestions(
|
|
15680
|
+
deps.memoryStore.loadEntries().filter((entry) => !retiringNow.has(entry.id)),
|
|
15681
|
+
now()
|
|
15682
|
+
);
|
|
15570
15683
|
try {
|
|
15571
15684
|
const narrative = await writeJournalNarrative({
|
|
15572
15685
|
sessions,
|
|
@@ -15575,10 +15688,10 @@ async function runDistillationInner(deps, date, log, now) {
|
|
|
15575
15688
|
language,
|
|
15576
15689
|
call: balancedCall
|
|
15577
15690
|
});
|
|
15578
|
-
deps.memoryStore.writeJournal(date, `# ${date}
|
|
15691
|
+
deps.memoryStore.writeJournal(date, redactText(appendRetireSection(`# ${date}
|
|
15579
15692
|
|
|
15580
|
-
${
|
|
15581
|
-
|
|
15693
|
+
${narrative.trim()}
|
|
15694
|
+
`, retireSuggestions)).text);
|
|
15582
15695
|
journalWritten = true;
|
|
15583
15696
|
} catch (error) {
|
|
15584
15697
|
log(`[memory] journal narrative failed: ${String(error)}`);
|
|
@@ -15589,7 +15702,7 @@ ${redactText(narrative).text.trim()}
|
|
|
15589
15702
|
"",
|
|
15590
15703
|
...rejected.length > 0 ? ["## Below-gate observations", ...rejected.map((entry) => `- [${entry.cluster.kind}] ${entry.cluster.text} (${entry.reason})`)] : []
|
|
15591
15704
|
].join("\n");
|
|
15592
|
-
deps.memoryStore.writeJournal(date, redactText(digest).text);
|
|
15705
|
+
deps.memoryStore.writeJournal(date, redactText(appendRetireSection(digest, retireSuggestions)).text);
|
|
15593
15706
|
journalWritten = true;
|
|
15594
15707
|
}
|
|
15595
15708
|
try {
|
|
@@ -15597,6 +15710,8 @@ ${redactText(narrative).text.trim()}
|
|
|
15597
15710
|
if (deps.memoryStore.hasRun(date)) {
|
|
15598
15711
|
return { date, status: "skipped-ran", patchOps: 0 };
|
|
15599
15712
|
}
|
|
15713
|
+
const { ledger, ops } = prepare();
|
|
15714
|
+
ledger.write();
|
|
15600
15715
|
if (deps.gated) {
|
|
15601
15716
|
if (ops.length === 0) {
|
|
15602
15717
|
recordCheckpoint(deps.memoryStore, date, 0, false, now());
|
|
@@ -15655,19 +15770,25 @@ function applyNextGatedPatch(store) {
|
|
|
15655
15770
|
persistQueue(store, queue.slice(1));
|
|
15656
15771
|
return { applied: 0 };
|
|
15657
15772
|
}
|
|
15658
|
-
const
|
|
15773
|
+
const current = store.loadEntries();
|
|
15774
|
+
const ops = patch.ops.map((op) => {
|
|
15775
|
+
if (op.op !== "add") return op;
|
|
15776
|
+
const hit = current.find((entry) => entry.kind === op.entry.kind && (entry.projectKey ?? "") === (op.entry.projectKey ?? "") && equivalentAssertions(entry.text, op.entry.text));
|
|
15777
|
+
return hit ? { op: "update", id: hit.id, text: hit.text, evidence: op.entry.evidence, expectText: hit.text } : op;
|
|
15778
|
+
});
|
|
15779
|
+
const result = store.applyPatch({ ...patch, ops }, { gated: true });
|
|
15659
15780
|
persistQueue(store, queue.slice(1));
|
|
15660
15781
|
return { applied: result.applied };
|
|
15661
15782
|
});
|
|
15662
15783
|
}
|
|
15663
15784
|
function persistQueue(store, queue) {
|
|
15664
|
-
const target =
|
|
15785
|
+
const target = path8.join(store.dir, GATED_PATCH_FILE);
|
|
15665
15786
|
if (queue.length === 0) {
|
|
15666
|
-
|
|
15787
|
+
fs6.rmSync(target, { force: true });
|
|
15667
15788
|
} else {
|
|
15668
15789
|
const tmp = `${target}.${process.pid}.${Date.now().toString(36)}.tmp`;
|
|
15669
|
-
|
|
15670
|
-
|
|
15790
|
+
fs6.writeFileSync(tmp, JSON.stringify(queue, null, " "));
|
|
15791
|
+
fs6.renameSync(tmp, target);
|
|
15671
15792
|
}
|
|
15672
15793
|
}
|
|
15673
15794
|
async function runCatchUp(deps, days = 2) {
|
|
@@ -15879,9 +16000,12 @@ export {
|
|
|
15879
16000
|
nearDuplicate,
|
|
15880
16001
|
harvestSessionsForDate,
|
|
15881
16002
|
datesBetween,
|
|
16003
|
+
isInfrastructureSession,
|
|
15882
16004
|
buildDistillPrompt,
|
|
15883
16005
|
DISTILL_SYSTEM,
|
|
15884
16006
|
parseDistillResponse,
|
|
16007
|
+
buildRetireSuggestions,
|
|
16008
|
+
appendRetireSection,
|
|
15885
16009
|
distillSession,
|
|
15886
16010
|
clusterCandidates,
|
|
15887
16011
|
gateClusters,
|