@di-code/coding-agent 0.1.7 → 0.1.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +54 -567
- package/compositions/base.yml +54 -0
- package/compositions/interactive.yml +14 -0
- package/compositions/json.yml +6 -0
- package/compositions/print.yml +5 -0
- package/compositions/rpc.yml +12 -0
- package/compositions/webui.yml +9 -0
- package/dist/cli.d.ts +22 -1
- package/dist/cli.d.ts.map +1 -1
- package/dist/cli.js +97 -3
- package/dist/cli.js.map +1 -1
- package/dist/composition-loader-entry.d.ts +11 -0
- package/dist/composition-loader-entry.d.ts.map +1 -0
- package/dist/composition-loader-entry.js +12 -0
- package/dist/composition-loader-entry.js.map +1 -0
- package/dist/compositions.d.ts +32 -0
- package/dist/compositions.d.ts.map +1 -0
- package/dist/compositions.js +173 -0
- package/dist/compositions.js.map +1 -0
- package/dist/core/session/session-manager.d.ts +9 -2
- package/dist/core/session/session-manager.d.ts.map +1 -1
- package/dist/core/session/session-manager.js +28 -0
- package/dist/core/session/session-manager.js.map +1 -1
- package/dist/core/session/session-storage.d.ts.map +1 -1
- package/dist/core/session/session-storage.js +20 -3
- package/dist/core/session/session-storage.js.map +1 -1
- package/dist/core/session/types.d.ts +11 -2
- package/dist/core/session/types.d.ts.map +1 -1
- package/dist/core/session/types.js.map +1 -1
- package/dist/core/session-tools.d.ts +5 -0
- package/dist/core/session-tools.d.ts.map +1 -0
- package/dist/core/session-tools.js +17 -0
- package/dist/core/session-tools.js.map +1 -0
- package/dist/core/session.d.ts +19 -7
- package/dist/core/session.d.ts.map +1 -1
- package/dist/core/session.js +71 -39
- package/dist/core/session.js.map +1 -1
- package/dist/core/tools/bash.d.ts +1 -38
- package/dist/core/tools/bash.d.ts.map +1 -1
- package/dist/core/tools/bash.js +1 -207
- package/dist/core/tools/bash.js.map +1 -1
- package/dist/core/tools/edit-diff.d.ts +1 -24
- package/dist/core/tools/edit-diff.d.ts.map +1 -1
- package/dist/core/tools/edit-diff.js +1 -135
- package/dist/core/tools/edit-diff.js.map +1 -1
- package/dist/core/tools/edit.d.ts +1 -26
- package/dist/core/tools/edit.d.ts.map +1 -1
- package/dist/core/tools/edit.js +1 -140
- package/dist/core/tools/edit.js.map +1 -1
- package/dist/core/tools/file-mutation-queue.d.ts +1 -1
- package/dist/core/tools/file-mutation-queue.d.ts.map +1 -1
- package/dist/core/tools/file-mutation-queue.js +1 -23
- package/dist/core/tools/file-mutation-queue.js.map +1 -1
- package/dist/core/tools/file-search.d.ts +1 -13
- package/dist/core/tools/file-search.d.ts.map +1 -1
- package/dist/core/tools/file-search.js +1 -98
- package/dist/core/tools/file-search.js.map +1 -1
- package/dist/core/tools/glob.d.ts +1 -10
- package/dist/core/tools/glob.d.ts.map +1 -1
- package/dist/core/tools/glob.js +1 -43
- package/dist/core/tools/glob.js.map +1 -1
- package/dist/core/tools/grep.d.ts +1 -12
- package/dist/core/tools/grep.d.ts.map +1 -1
- package/dist/core/tools/grep.js +1 -66
- package/dist/core/tools/grep.js.map +1 -1
- package/dist/core/tools/load-skill.d.ts +1 -9
- package/dist/core/tools/load-skill.d.ts.map +1 -1
- package/dist/core/tools/load-skill.js +1 -21
- package/dist/core/tools/load-skill.js.map +1 -1
- package/dist/core/tools/path-boundary.d.ts +1 -4
- package/dist/core/tools/path-boundary.d.ts.map +1 -1
- package/dist/core/tools/path-boundary.js +1 -65
- package/dist/core/tools/path-boundary.js.map +1 -1
- package/dist/core/tools/read.d.ts +1 -16
- package/dist/core/tools/read.d.ts.map +1 -1
- package/dist/core/tools/read.js +1 -131
- package/dist/core/tools/read.js.map +1 -1
- package/dist/core/tools/write.d.ts +1 -16
- package/dist/core/tools/write.d.ts.map +1 -1
- package/dist/core/tools/write.js +1 -44
- package/dist/core/tools/write.js.map +1 -1
- package/dist/entry.js +30 -28
- package/dist/entry.js.map +1 -1
- package/dist/index.d.ts +6 -3
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +6 -3
- package/dist/index.js.map +1 -1
- package/dist/interactive/builtin.d.ts +17 -0
- package/dist/interactive/builtin.d.ts.map +1 -0
- package/dist/interactive/builtin.js +47 -0
- package/dist/interactive/builtin.js.map +1 -0
- package/dist/interactive/controller.d.ts +85 -0
- package/dist/interactive/controller.d.ts.map +1 -0
- package/dist/interactive/controller.js +211 -0
- package/dist/interactive/controller.js.map +1 -0
- package/dist/interactive/index.d.ts +3 -0
- package/dist/interactive/index.d.ts.map +1 -0
- package/dist/interactive/index.js +3 -0
- package/dist/interactive/index.js.map +1 -0
- package/dist/interactive-host-entry.d.ts +7 -0
- package/dist/interactive-host-entry.d.ts.map +1 -0
- package/dist/interactive-host-entry.js +123 -0
- package/dist/interactive-host-entry.js.map +1 -0
- package/dist/interactive-profile.d.ts +18 -0
- package/dist/interactive-profile.d.ts.map +1 -0
- package/dist/interactive-profile.js +290 -0
- package/dist/interactive-profile.js.map +1 -0
- package/dist/interactive-resources-entry.d.ts +7 -0
- package/dist/interactive-resources-entry.d.ts.map +1 -0
- package/dist/interactive-resources-entry.js +42 -0
- package/dist/interactive-resources-entry.js.map +1 -0
- package/dist/legacy-main.d.ts +39 -0
- package/dist/legacy-main.d.ts.map +1 -0
- package/dist/legacy-main.js +611 -0
- package/dist/legacy-main.js.map +1 -0
- package/dist/main.d.ts +15 -34
- package/dist/main.d.ts.map +1 -1
- package/dist/main.js +130 -518
- package/dist/main.js.map +1 -1
- package/dist/mcp/entries.d.ts +42 -0
- package/dist/mcp/entries.d.ts.map +1 -0
- package/dist/mcp/entries.js +98 -0
- package/dist/mcp/entries.js.map +1 -0
- package/dist/mcp-client-entry.d.ts +5 -0
- package/dist/mcp-client-entry.d.ts.map +1 -0
- package/dist/mcp-client-entry.js +6 -0
- package/dist/mcp-client-entry.js.map +1 -0
- package/dist/mcp-config-entry.d.ts +5 -0
- package/dist/mcp-config-entry.d.ts.map +1 -0
- package/dist/mcp-config-entry.js +6 -0
- package/dist/mcp-config-entry.js.map +1 -0
- package/dist/mcp-tools-entry.d.ts +5 -0
- package/dist/mcp-tools-entry.d.ts.map +1 -0
- package/dist/mcp-tools-entry.js +6 -0
- package/dist/mcp-tools-entry.js.map +1 -0
- package/dist/mcp-transport-entry.d.ts +5 -0
- package/dist/mcp-transport-entry.d.ts.map +1 -0
- package/dist/mcp-transport-entry.js +6 -0
- package/dist/mcp-transport-entry.js.map +1 -0
- package/dist/modes/interactive-entry.d.ts +18 -0
- package/dist/modes/interactive-entry.d.ts.map +1 -0
- package/dist/modes/interactive-entry.js +21 -0
- package/dist/modes/interactive-entry.js.map +1 -0
- package/dist/modes/interactive.d.ts +16 -6
- package/dist/modes/interactive.d.ts.map +1 -1
- package/dist/modes/interactive.js +81 -32
- package/dist/modes/interactive.js.map +1 -1
- package/dist/modes/json-entry.d.ts +13 -0
- package/dist/modes/json-entry.d.ts.map +1 -0
- package/dist/modes/json-entry.js +14 -0
- package/dist/modes/json-entry.js.map +1 -0
- package/dist/modes/json.d.ts +4 -1
- package/dist/modes/json.d.ts.map +1 -1
- package/dist/modes/json.js +3 -3
- package/dist/modes/json.js.map +1 -1
- package/dist/modes/print-entry.d.ts +10 -0
- package/dist/modes/print-entry.d.ts.map +1 -0
- package/dist/modes/print-entry.js +11 -0
- package/dist/modes/print-entry.js.map +1 -0
- package/dist/modes/tree-selector.d.ts.map +1 -1
- package/dist/modes/tree-selector.js +4 -0
- package/dist/modes/tree-selector.js.map +1 -1
- package/dist/plugin-dump-composition.d.ts +6 -0
- package/dist/plugin-dump-composition.d.ts.map +1 -0
- package/dist/plugin-dump-composition.js +7 -0
- package/dist/plugin-dump-composition.js.map +1 -0
- package/dist/plugin-inventory.d.ts +7 -0
- package/dist/plugin-inventory.d.ts.map +1 -0
- package/dist/plugin-inventory.js +8 -0
- package/dist/plugin-inventory.js.map +1 -0
- package/dist/plugin-manager.d.ts +6 -0
- package/dist/plugin-manager.d.ts.map +1 -0
- package/dist/plugin-manager.js +7 -0
- package/dist/plugin-manager.js.map +1 -0
- package/dist/plugin-trace.d.ts +6 -0
- package/dist/plugin-trace.d.ts.map +1 -0
- package/dist/plugin-trace.js +7 -0
- package/dist/plugin-trace.js.map +1 -0
- package/dist/plugins/dynamic-broker.d.ts +76 -0
- package/dist/plugins/dynamic-broker.d.ts.map +1 -0
- package/dist/plugins/dynamic-broker.js +852 -0
- package/dist/plugins/dynamic-broker.js.map +1 -0
- package/dist/plugins/profile.d.ts +15 -0
- package/dist/plugins/profile.d.ts.map +1 -0
- package/dist/plugins/profile.js +34 -0
- package/dist/plugins/profile.js.map +1 -0
- package/dist/plugins/runtime-host.d.ts +37 -0
- package/dist/plugins/runtime-host.d.ts.map +1 -0
- package/dist/plugins/runtime-host.js +95 -0
- package/dist/plugins/runtime-host.js.map +1 -0
- package/dist/plugins/trust.d.ts +8 -0
- package/dist/plugins/trust.d.ts.map +1 -0
- package/dist/plugins/trust.js +59 -0
- package/dist/plugins/trust.js.map +1 -0
- package/dist/project-trust-entry.d.ts +15 -0
- package/dist/project-trust-entry.d.ts.map +1 -0
- package/dist/project-trust-entry.js +15 -0
- package/dist/project-trust-entry.js.map +1 -0
- package/dist/rpc/client.d.ts +78 -6
- package/dist/rpc/client.d.ts.map +1 -1
- package/dist/rpc/client.js +172 -4
- package/dist/rpc/client.js.map +1 -1
- package/dist/rpc/dispatcher.d.ts +121 -0
- package/dist/rpc/dispatcher.d.ts.map +1 -0
- package/dist/rpc/dispatcher.js +994 -0
- package/dist/rpc/dispatcher.js.map +1 -0
- package/dist/rpc/index.d.ts +2 -0
- package/dist/rpc/index.d.ts.map +1 -1
- package/dist/rpc/index.js +2 -0
- package/dist/rpc/index.js.map +1 -1
- package/dist/rpc/lifecycle.d.ts +6 -0
- package/dist/rpc/lifecycle.d.ts.map +1 -0
- package/dist/rpc/lifecycle.js +24 -0
- package/dist/rpc/lifecycle.js.map +1 -0
- package/dist/rpc/protocol.d.ts +112 -31
- package/dist/rpc/protocol.d.ts.map +1 -1
- package/dist/rpc/protocol.js +569 -117
- package/dist/rpc/protocol.js.map +1 -1
- package/dist/rpc/server-service.d.ts +7 -0
- package/dist/rpc/server-service.d.ts.map +1 -0
- package/dist/rpc/server-service.js +3 -0
- package/dist/rpc/server-service.js.map +1 -0
- package/dist/rpc/server.d.ts +16 -19
- package/dist/rpc/server.d.ts.map +1 -1
- package/dist/rpc/server.js +59 -115
- package/dist/rpc/server.js.map +1 -1
- package/dist/rpc-client-sdk-entry.d.ts +12 -0
- package/dist/rpc-client-sdk-entry.d.ts.map +1 -0
- package/dist/rpc-client-sdk-entry.js +11 -0
- package/dist/rpc-client-sdk-entry.js.map +1 -0
- package/dist/rpc-entry.js +50 -18
- package/dist/rpc-entry.js.map +1 -1
- package/dist/rpc-server-entry.d.ts +8 -0
- package/dist/rpc-server-entry.d.ts.map +1 -0
- package/dist/rpc-server-entry.js +67 -0
- package/dist/rpc-server-entry.js.map +1 -0
- package/dist/runtime/attachment-store.d.ts +13 -0
- package/dist/runtime/attachment-store.d.ts.map +1 -0
- package/dist/runtime/attachment-store.js +93 -0
- package/dist/runtime/attachment-store.js.map +1 -0
- package/dist/runtime/bootstrap.d.ts +14 -0
- package/dist/runtime/bootstrap.d.ts.map +1 -0
- package/dist/runtime/bootstrap.js +29 -0
- package/dist/runtime/bootstrap.js.map +1 -0
- package/dist/runtime/interactive-host-service.d.ts +22 -0
- package/dist/runtime/interactive-host-service.d.ts.map +1 -0
- package/dist/runtime/interactive-host-service.js +2 -0
- package/dist/runtime/interactive-host-service.js.map +1 -0
- package/dist/runtime/interactive-resource-service.d.ts +11 -0
- package/dist/runtime/interactive-resource-service.d.ts.map +1 -0
- package/dist/runtime/interactive-resource-service.js +3 -0
- package/dist/runtime/interactive-resource-service.js.map +1 -0
- package/dist/runtime/plugin-inventory-entry.d.ts +5 -0
- package/dist/runtime/plugin-inventory-entry.d.ts.map +1 -0
- package/dist/runtime/plugin-inventory-entry.js +18 -0
- package/dist/runtime/plugin-inventory-entry.js.map +1 -0
- package/dist/runtime/plugin-inventory-service.d.ts +8 -0
- package/dist/runtime/plugin-inventory-service.d.ts.map +1 -0
- package/dist/runtime/plugin-inventory-service.js +3 -0
- package/dist/runtime/plugin-inventory-service.js.map +1 -0
- package/dist/runtime/plugin-manager-entry.d.ts +20 -0
- package/dist/runtime/plugin-manager-entry.d.ts.map +1 -0
- package/dist/runtime/plugin-manager-entry.js +96 -0
- package/dist/runtime/plugin-manager-entry.js.map +1 -0
- package/dist/runtime/plugin-observability-entry.d.ts +12 -0
- package/dist/runtime/plugin-observability-entry.d.ts.map +1 -0
- package/dist/runtime/plugin-observability-entry.js +73 -0
- package/dist/runtime/plugin-observability-entry.js.map +1 -0
- package/dist/runtime/product-host.d.ts +91 -0
- package/dist/runtime/product-host.d.ts.map +1 -0
- package/dist/runtime/product-host.js +529 -0
- package/dist/runtime/product-host.js.map +1 -0
- package/dist/runtime/session-factory.d.ts +17 -0
- package/dist/runtime/session-factory.d.ts.map +1 -0
- package/dist/runtime/session-factory.js +75 -0
- package/dist/runtime/session-factory.js.map +1 -0
- package/dist/runtime/session-host.d.ts +152 -0
- package/dist/runtime/session-host.d.ts.map +1 -0
- package/dist/runtime/session-host.js +895 -0
- package/dist/runtime/session-host.js.map +1 -0
- package/dist/runtime-core-entry.d.ts +11 -0
- package/dist/runtime-core-entry.d.ts.map +1 -0
- package/dist/runtime-core-entry.js +9 -0
- package/dist/runtime-core-entry.js.map +1 -0
- package/dist/session-factory-entry.d.ts +7 -0
- package/dist/session-factory-entry.d.ts.map +1 -0
- package/dist/session-factory-entry.js +9 -0
- package/dist/session-factory-entry.js.map +1 -0
- package/dist/session-store-jsonl-entry.d.ts +7 -0
- package/dist/session-store-jsonl-entry.d.ts.map +1 -0
- package/dist/session-store-jsonl-entry.js +33 -0
- package/dist/session-store-jsonl-entry.js.map +1 -0
- package/dist/startup.d.ts +12 -1
- package/dist/startup.d.ts.map +1 -1
- package/dist/startup.js +106 -15
- package/dist/startup.js.map +1 -1
- package/dist/subagents/index.d.ts +2 -0
- package/dist/subagents/index.d.ts.map +1 -0
- package/dist/subagents/index.js +2 -0
- package/dist/subagents/index.js.map +1 -0
- package/dist/subagents/service.d.ts +50 -0
- package/dist/subagents/service.d.ts.map +1 -0
- package/dist/subagents/service.js +521 -0
- package/dist/subagents/service.js.map +1 -0
- package/dist/ui-host.d.ts +125 -0
- package/dist/ui-host.d.ts.map +1 -0
- package/dist/ui-host.js +275 -0
- package/dist/ui-host.js.map +1 -0
- package/dist/web/assets/index-BwfuGMvv.css +1 -0
- package/dist/web/assets/index-DPUaJqFJ.js +41 -0
- package/dist/web/assets/index-DPUaJqFJ.js.map +1 -0
- package/dist/web/index.html +14 -0
- package/dist/web-command.d.ts +11 -0
- package/dist/web-command.d.ts.map +1 -0
- package/dist/web-command.js +114 -0
- package/dist/web-command.js.map +1 -0
- package/dist/web-frontend.d.ts +73 -0
- package/dist/web-frontend.d.ts.map +1 -0
- package/dist/web-frontend.js +249 -0
- package/dist/web-frontend.js.map +1 -0
- package/dist/web.d.ts +254 -0
- package/dist/web.d.ts.map +1 -0
- package/dist/web.js +740 -0
- package/dist/web.js.map +1 -0
- package/dist/webui-entry.d.ts +3 -0
- package/dist/webui-entry.d.ts.map +1 -0
- package/dist/webui-entry.js +73 -0
- package/dist/webui-entry.js.map +1 -0
- package/dist/webui.d.ts +91 -0
- package/dist/webui.d.ts.map +1 -0
- package/dist/webui.js +882 -0
- package/dist/webui.js.map +1 -0
- package/package.json +89 -8
|
@@ -1,136 +1,2 @@
|
|
|
1
|
-
|
|
2
|
-
import * as Diff from "diff";
|
|
3
|
-
import { resolveAllowedFilePath } from "./path-boundary.js";
|
|
4
|
-
function normalizeToLF(text) {
|
|
5
|
-
return text.replaceAll("\r\n", "\n").replaceAll("\r", "\n");
|
|
6
|
-
}
|
|
7
|
-
function stripBom(text) {
|
|
8
|
-
return text.startsWith("\uFEFF") ? text.slice(1) : text;
|
|
9
|
-
}
|
|
10
|
-
function findMatches(content, search) {
|
|
11
|
-
const matches = [];
|
|
12
|
-
let offset = 0;
|
|
13
|
-
while (offset <= content.length - search.length) {
|
|
14
|
-
const index = content.indexOf(search, offset);
|
|
15
|
-
if (index < 0)
|
|
16
|
-
break;
|
|
17
|
-
matches.push(index);
|
|
18
|
-
offset = index + 1;
|
|
19
|
-
}
|
|
20
|
-
return matches;
|
|
21
|
-
}
|
|
22
|
-
function matchEdits(content, edits, path) {
|
|
23
|
-
const matches = edits.map((edit, index) => {
|
|
24
|
-
if (edit.oldText.length === 0)
|
|
25
|
-
throw new Error(`oldText must not be empty in ${path}`);
|
|
26
|
-
const indexes = findMatches(content, edit.oldText);
|
|
27
|
-
if (indexes.length === 0) {
|
|
28
|
-
throw new Error(`Could not find edits[${index}] in ${path}. The oldText must match exactly.`);
|
|
29
|
-
}
|
|
30
|
-
if (indexes.length > 1) {
|
|
31
|
-
throw new Error(`Found ${indexes.length} occurrences of edits[${index}] in ${path}. Each oldText must be unique.`);
|
|
32
|
-
}
|
|
33
|
-
return { ...edit, matchIndex: indexes[0], matchLength: edit.oldText.length };
|
|
34
|
-
});
|
|
35
|
-
const ordered = [...matches].sort((left, right) => left.matchIndex - right.matchIndex);
|
|
36
|
-
for (let index = 1; index < ordered.length; index++) {
|
|
37
|
-
const previous = ordered[index - 1];
|
|
38
|
-
const current = ordered[index];
|
|
39
|
-
if (current.matchIndex < previous.matchIndex + previous.matchLength) {
|
|
40
|
-
throw new Error(`Edits overlap in ${path}. Merge overlapping regions into one edit.`);
|
|
41
|
-
}
|
|
42
|
-
}
|
|
43
|
-
return matches;
|
|
44
|
-
}
|
|
45
|
-
export function applyEditsToContent(content, edits, path) {
|
|
46
|
-
if (edits.length === 0)
|
|
47
|
-
throw new Error(`At least one edit is required for ${path}`);
|
|
48
|
-
const matched = matchEdits(content, edits, path).sort((left, right) => right.matchIndex - left.matchIndex);
|
|
49
|
-
let result = content;
|
|
50
|
-
for (const edit of matched) {
|
|
51
|
-
result = `${result.slice(0, edit.matchIndex)}${edit.newText}${result.slice(edit.matchIndex + edit.matchLength)}`;
|
|
52
|
-
}
|
|
53
|
-
return { baseContent: content, newContent: result };
|
|
54
|
-
}
|
|
55
|
-
/** Generate a standard unified patch for storage/export. */
|
|
56
|
-
export function generateUnifiedPatch(path, oldContent, newContent, contextLines = 4) {
|
|
57
|
-
return Diff.createTwoFilesPatch(path, path, oldContent, newContent, undefined, undefined, {
|
|
58
|
-
context: contextLines,
|
|
59
|
-
headerOptions: Diff.FILE_HEADERS_ONLY,
|
|
60
|
-
});
|
|
61
|
-
}
|
|
62
|
-
/** Generate the line-numbered display diff consumed by the interactive renderer. */
|
|
63
|
-
export function generateDiffString(oldContent, newContent, contextLines = 4) {
|
|
64
|
-
const parts = Diff.diffLines(oldContent, newContent, { newlineIsToken: false });
|
|
65
|
-
const oldLines = oldContent.split("\n");
|
|
66
|
-
const newLines = newContent.split("\n");
|
|
67
|
-
const lineNumWidth = String(Math.max(oldLines.length, newLines.length)).length;
|
|
68
|
-
const output = [];
|
|
69
|
-
let oldLine = 1;
|
|
70
|
-
let newLine = 1;
|
|
71
|
-
let firstChangedLine;
|
|
72
|
-
let changedSeen = false;
|
|
73
|
-
for (let partIndex = 0; partIndex < parts.length; partIndex++) {
|
|
74
|
-
const part = parts[partIndex];
|
|
75
|
-
const lines = part.value.split("\n");
|
|
76
|
-
if (lines.at(-1) === "")
|
|
77
|
-
lines.pop();
|
|
78
|
-
if (part.removed) {
|
|
79
|
-
if (firstChangedLine === undefined && lines.length > 0)
|
|
80
|
-
firstChangedLine = newLine;
|
|
81
|
-
for (const line of lines) {
|
|
82
|
-
output.push(`-${String(oldLine).padStart(lineNumWidth, " ")} ${line}`);
|
|
83
|
-
oldLine += 1;
|
|
84
|
-
}
|
|
85
|
-
changedSeen = true;
|
|
86
|
-
continue;
|
|
87
|
-
}
|
|
88
|
-
if (part.added) {
|
|
89
|
-
if (firstChangedLine === undefined && lines.length > 0)
|
|
90
|
-
firstChangedLine = newLine;
|
|
91
|
-
for (const line of lines) {
|
|
92
|
-
output.push(`+${String(newLine).padStart(lineNumWidth, " ")} ${line}`);
|
|
93
|
-
newLine += 1;
|
|
94
|
-
}
|
|
95
|
-
changedSeen = true;
|
|
96
|
-
continue;
|
|
97
|
-
}
|
|
98
|
-
const changedLater = parts.slice(partIndex + 1).some((candidate) => candidate.added || candidate.removed);
|
|
99
|
-
const visibleIndexes = !changedSeen && !changedLater
|
|
100
|
-
? lines.map((_line, index) => index)
|
|
101
|
-
: !changedSeen && changedLater
|
|
102
|
-
? lines.map((_line, index) => index).slice(-contextLines)
|
|
103
|
-
: changedSeen && changedLater
|
|
104
|
-
? lines.length <= contextLines * 2
|
|
105
|
-
? lines.map((_line, index) => index)
|
|
106
|
-
: [
|
|
107
|
-
...lines.map((_line, index) => index).slice(0, contextLines),
|
|
108
|
-
...lines.map((_line, index) => index).slice(-contextLines),
|
|
109
|
-
]
|
|
110
|
-
: lines.map((_line, index) => index).slice(0, contextLines);
|
|
111
|
-
for (const lineIndex of visibleIndexes) {
|
|
112
|
-
output.push(` ${String(newLine + lineIndex).padStart(lineNumWidth, " ")} ${lines[lineIndex]}`);
|
|
113
|
-
}
|
|
114
|
-
oldLine += lines.length;
|
|
115
|
-
newLine += lines.length;
|
|
116
|
-
}
|
|
117
|
-
return { diff: output.join("\n"), firstChangedLine };
|
|
118
|
-
}
|
|
119
|
-
export async function computeEditsDiff(path, edits, cwd) {
|
|
120
|
-
try {
|
|
121
|
-
const absolutePath = await resolveAllowedFilePath(path, cwd);
|
|
122
|
-
await access(absolutePath, constants.R_OK);
|
|
123
|
-
const rawContent = stripBom(await readFile(absolutePath, "utf8"));
|
|
124
|
-
const baseContent = normalizeToLF(rawContent);
|
|
125
|
-
const applied = applyEditsToContent(baseContent, edits.map((edit) => ({ oldText: normalizeToLF(edit.oldText), newText: normalizeToLF(edit.newText) })), path);
|
|
126
|
-
const display = generateDiffString(applied.baseContent, applied.newContent);
|
|
127
|
-
return {
|
|
128
|
-
...display,
|
|
129
|
-
patch: generateUnifiedPatch(path, applied.baseContent, applied.newContent),
|
|
130
|
-
};
|
|
131
|
-
}
|
|
132
|
-
catch (cause) {
|
|
133
|
-
return { error: cause instanceof Error ? cause.message : String(cause) };
|
|
134
|
-
}
|
|
135
|
-
}
|
|
1
|
+
export * from "@di-code/builtins";
|
|
136
2
|
//# sourceMappingURL=edit-diff.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"edit-diff.js","sourceRoot":"","sources":["../../../src/core/tools/edit-diff.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,SAAS,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AAC/D,OAAO,KAAK,IAAI,MAAM,MAAM,CAAC;AAC7B,OAAO,EAAE,sBAAsB,EAAE,MAAM,oBAAoB,CAAC;AAsB5D,SAAS,aAAa,CAAC,IAAY;IAClC,OAAO,IAAI,CAAC,UAAU,CAAC,MAAM,EAAE,IAAI,CAAC,CAAC,UAAU,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC;AAC7D,CAAC;AAED,SAAS,QAAQ,CAAC,IAAY;IAC7B,OAAO,IAAI,CAAC,UAAU,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC;AACzD,CAAC;AAED,SAAS,WAAW,CAAC,OAAe,EAAE,MAAc;IACnD,MAAM,OAAO,GAAa,EAAE,CAAC;IAC7B,IAAI,MAAM,GAAG,CAAC,CAAC;IACf,OAAO,MAAM,IAAI,OAAO,CAAC,MAAM,GAAG,MAAM,CAAC,MAAM,EAAE,CAAC;QACjD,MAAM,KAAK,GAAG,OAAO,CAAC,OAAO,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;QAC9C,IAAI,KAAK,GAAG,CAAC;YAAE,MAAM;QACrB,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;QACpB,MAAM,GAAG,KAAK,GAAG,CAAC,CAAC;IACpB,CAAC;IACD,OAAO,OA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AAM,CAAC,CAAC,CAAC;QAClE,MAAM,WAAW,GAAG,aAAa,CAAC,UAAU,CAAC,CAAC;QAC9C,MAAM,OAAO,GAAG,mBAAmB,CAClC,WAAW,EACX,KAAK,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC,EAAE,OAAO,EAAE,aAAa,CAAC,IAAI,CAAC,OAAO,CAAC,EAAE,OAAO,EAAE,aAAa,CAAC,IAAI,CAAC,OAAO,CAAC,EAAE,CAAC,CAAC,EACrG,IAAI,CACJ,CAAC;QACF,MAAM,OAAO,GAAG,kBAAkB,CAAC,OAAO,CAAC,WAAW,EAAE,OAAO,CAAC,UAAU,CAAC,CAAC;QAC5E,OAAO;YACN,GAAG,OAAO;YACV,KAAK,EAAE,oBAAoB,CAAC,IAAI,EAAE,OAAO,CAAC,WAAW,EAAE,OAAO,CAAC,UAAU,CAAC;SAC1E,CAAC;IACH,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QAChB,OAAO,EAAE,KAAK,EAAE,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,EAAE,CAAC;IAC1E,CAAC;AACF,CAAC","sourcesContent":["import { access, constants, readFile } from \"node:fs/promises\";\nimport * as Diff from \"diff\";\nimport { resolveAllowedFilePath } from \"./path-boundary.ts\";\n\nexport interface Edit {\n\treadonly oldText: string;\n\treadonly newText: string;\n}\n\nexport interface EditDiffResult {\n\treadonly diff: string;\n\treadonly patch: string;\n\treadonly firstChangedLine?: number;\n}\n\nexport interface EditDiffError {\n\treadonly error: string;\n}\n\ninterface MatchedEdit extends Edit {\n\treadonly matchIndex: number;\n\treadonly matchLength: number;\n}\n\nfunction normalizeToLF(text: string): string {\n\treturn text.replaceAll(\"\\r\\n\", \"\\n\").replaceAll(\"\\r\", \"\\n\");\n}\n\nfunction stripBom(text: string): string {\n\treturn text.startsWith(\"\\uFEFF\") ? text.slice(1) : text;\n}\n\nfunction findMatches(content: string, search: string): number[] {\n\tconst matches: number[] = [];\n\tlet offset = 0;\n\twhile (offset <= content.length - search.length) {\n\t\tconst index = content.indexOf(search, offset);\n\t\tif (index < 0) break;\n\t\tmatches.push(index);\n\t\toffset = index + 1;\n\t}\n\treturn matches;\n}\n\nfunction matchEdits(content: string, edits: readonly Edit[], path: string): MatchedEdit[] {\n\tconst matches = edits.map((edit, index) => {\n\t\tif (edit.oldText.length === 0) throw new Error(`oldText must not be empty in ${path}`);\n\t\tconst indexes = findMatches(content, edit.oldText);\n\t\tif (indexes.length === 0) {\n\t\t\tthrow new Error(`Could not find edits[${index}] in ${path}. The oldText must match exactly.`);\n\t\t}\n\t\tif (indexes.length > 1) {\n\t\t\tthrow new Error(\n\t\t\t\t`Found ${indexes.length} occurrences of edits[${index}] in ${path}. Each oldText must be unique.`,\n\t\t\t);\n\t\t}\n\t\treturn { ...edit, matchIndex: indexes[0], matchLength: edit.oldText.length };\n\t});\n\n\tconst ordered = [...matches].sort((left, right) => left.matchIndex - right.matchIndex);\n\tfor (let index = 1; index < ordered.length; index++) {\n\t\tconst previous = ordered[index - 1];\n\t\tconst current = ordered[index];\n\t\tif (current.matchIndex < previous.matchIndex + previous.matchLength) {\n\t\t\tthrow new Error(`Edits overlap in ${path}. Merge overlapping regions into one edit.`);\n\t\t}\n\t}\n\treturn matches;\n}\n\nexport function applyEditsToContent(\n\tcontent: string,\n\tedits: readonly Edit[],\n\tpath: string,\n): { baseContent: string; newContent: string } {\n\tif (edits.length === 0) throw new Error(`At least one edit is required for ${path}`);\n\tconst matched = matchEdits(content, edits, path).sort((left, right) => right.matchIndex - left.matchIndex);\n\tlet result = content;\n\tfor (const edit of matched) {\n\t\tresult = `${result.slice(0, edit.matchIndex)}${edit.newText}${result.slice(edit.matchIndex + edit.matchLength)}`;\n\t}\n\treturn { baseContent: content, newContent: result };\n}\n\n/** Generate a standard unified patch for storage/export. */\nexport function generateUnifiedPatch(path: string, oldContent: string, newContent: string, contextLines = 4): string {\n\treturn Diff.createTwoFilesPatch(path, path, oldContent, newContent, undefined, undefined, {\n\t\tcontext: contextLines,\n\t\theaderOptions: Diff.FILE_HEADERS_ONLY,\n\t});\n}\n\n/** Generate the line-numbered display diff consumed by the interactive renderer. */\nexport function generateDiffString(\n\toldContent: string,\n\tnewContent: string,\n\tcontextLines = 4,\n): { diff: string; firstChangedLine: number | undefined } {\n\tconst parts = Diff.diffLines(oldContent, newContent, { newlineIsToken: false });\n\tconst oldLines = oldContent.split(\"\\n\");\n\tconst newLines = newContent.split(\"\\n\");\n\tconst lineNumWidth = String(Math.max(oldLines.length, newLines.length)).length;\n\tconst output: string[] = [];\n\tlet oldLine = 1;\n\tlet newLine = 1;\n\tlet firstChangedLine: number | undefined;\n\tlet changedSeen = false;\n\tfor (let partIndex = 0; partIndex < parts.length; partIndex++) {\n\t\tconst part = parts[partIndex];\n\t\tconst lines = part.value.split(\"\\n\");\n\t\tif (lines.at(-1) === \"\") lines.pop();\n\t\tif (part.removed) {\n\t\t\tif (firstChangedLine === undefined && lines.length > 0) firstChangedLine = newLine;\n\t\t\tfor (const line of lines) {\n\t\t\t\toutput.push(`-${String(oldLine).padStart(lineNumWidth, \" \")} ${line}`);\n\t\t\t\toldLine += 1;\n\t\t\t}\n\t\t\tchangedSeen = true;\n\t\t\tcontinue;\n\t\t}\n\t\tif (part.added) {\n\t\t\tif (firstChangedLine === undefined && lines.length > 0) firstChangedLine = newLine;\n\t\t\tfor (const line of lines) {\n\t\t\t\toutput.push(`+${String(newLine).padStart(lineNumWidth, \" \")} ${line}`);\n\t\t\t\tnewLine += 1;\n\t\t\t}\n\t\t\tchangedSeen = true;\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst changedLater = parts.slice(partIndex + 1).some((candidate) => candidate.added || candidate.removed);\n\t\tconst visibleIndexes =\n\t\t\t!changedSeen && !changedLater\n\t\t\t\t? lines.map((_line, index) => index)\n\t\t\t\t: !changedSeen && changedLater\n\t\t\t\t\t? lines.map((_line, index) => index).slice(-contextLines)\n\t\t\t\t\t: changedSeen && changedLater\n\t\t\t\t\t\t? lines.length <= contextLines * 2\n\t\t\t\t\t\t\t? lines.map((_line, index) => index)\n\t\t\t\t\t\t\t: [\n\t\t\t\t\t\t\t\t\t...lines.map((_line, index) => index).slice(0, contextLines),\n\t\t\t\t\t\t\t\t\t...lines.map((_line, index) => index).slice(-contextLines),\n\t\t\t\t\t\t\t\t]\n\t\t\t\t\t\t: lines.map((_line, index) => index).slice(0, contextLines);\n\t\tfor (const lineIndex of visibleIndexes) {\n\t\t\toutput.push(` ${String(newLine + lineIndex).padStart(lineNumWidth, \" \")} ${lines[lineIndex]}`);\n\t\t}\n\t\toldLine += lines.length;\n\t\tnewLine += lines.length;\n\t}\n\n\treturn { diff: output.join(\"\\n\"), firstChangedLine };\n}\n\nexport async function computeEditsDiff(\n\tpath: string,\n\tedits: readonly Edit[],\n\tcwd: string,\n): Promise<EditDiffResult | EditDiffError> {\n\ttry {\n\t\tconst absolutePath = await resolveAllowedFilePath(path, cwd);\n\t\tawait access(absolutePath, constants.R_OK);\n\t\tconst rawContent = stripBom(await readFile(absolutePath, \"utf8\"));\n\t\tconst baseContent = normalizeToLF(rawContent);\n\t\tconst applied = applyEditsToContent(\n\t\t\tbaseContent,\n\t\t\tedits.map((edit) => ({ oldText: normalizeToLF(edit.oldText), newText: normalizeToLF(edit.newText) })),\n\t\t\tpath,\n\t\t);\n\t\tconst display = generateDiffString(applied.baseContent, applied.newContent);\n\t\treturn {\n\t\t\t...display,\n\t\t\tpatch: generateUnifiedPatch(path, applied.baseContent, applied.newContent),\n\t\t};\n\t} catch (cause) {\n\t\treturn { error: cause instanceof Error ? cause.message : String(cause) };\n\t}\n}\n"]}
|
|
1
|
+
{"version":3,"file":"edit-diff.js","sourceRoot":"","sources":["../../../src/core/tools/edit-diff.ts"],"names":[],"mappings":"AAAA,cAAc,mBAAmB,CAAC","sourcesContent":["export * from \"@di-code/builtins\";\n"]}
|
|
@@ -1,27 +1,2 @@
|
|
|
1
|
-
|
|
2
|
-
import { type Static, Type } from "@di-code/ai";
|
|
3
|
-
export declare const editParameters: Type.TObject<{
|
|
4
|
-
path: Type.TString;
|
|
5
|
-
edits: Type.TOptional<Type.TArray<Type.TObject<{
|
|
6
|
-
oldText: Type.TString;
|
|
7
|
-
newText: Type.TString;
|
|
8
|
-
}>>>;
|
|
9
|
-
oldText: Type.TOptional<Type.TString>;
|
|
10
|
-
newText: Type.TOptional<Type.TString>;
|
|
11
|
-
}>;
|
|
12
|
-
export type EditParameters = Static<typeof editParameters>;
|
|
13
|
-
export interface EditOperations {
|
|
14
|
-
readFile(filePath: string): Promise<Buffer>;
|
|
15
|
-
writeFile(filePath: string, content: string): Promise<void>;
|
|
16
|
-
}
|
|
17
|
-
export interface EditToolOptions {
|
|
18
|
-
readonly operations?: EditOperations;
|
|
19
|
-
}
|
|
20
|
-
export interface EditToolDetails {
|
|
21
|
-
readonly diff: string;
|
|
22
|
-
readonly patch: string;
|
|
23
|
-
readonly firstChangedLine?: number;
|
|
24
|
-
}
|
|
25
|
-
export type EditTool = AgentTool<typeof editParameters, ToolExecutionResult<EditToolDetails>>;
|
|
26
|
-
export declare function createEditTool(allowedRoot: string, options?: EditToolOptions): EditTool;
|
|
1
|
+
export * from "@di-code/builtins";
|
|
27
2
|
//# sourceMappingURL=edit.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"edit.d.ts","sourceRoot":"","sources":["../../../src/core/tools/edit.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"edit.d.ts","sourceRoot":"","sources":["../../../src/core/tools/edit.ts"],"names":[],"mappings":"AAAA,cAAc,mBAAmB,CAAC"}
|
package/dist/core/tools/edit.js
CHANGED
|
@@ -1,141 +1,2 @@
|
|
|
1
|
-
|
|
2
|
-
import { Type } from "@di-code/ai";
|
|
3
|
-
import { applyEditsToContent, generateDiffString, generateUnifiedPatch } from "./edit-diff.js";
|
|
4
|
-
import { withFileMutationQueue } from "./file-mutation-queue.js";
|
|
5
|
-
import { resolveAllowedFilePath } from "./path-boundary.js";
|
|
6
|
-
const editItemParameters = Type.Object({
|
|
7
|
-
oldText: Type.String(),
|
|
8
|
-
newText: Type.String(),
|
|
9
|
-
});
|
|
10
|
-
export const editParameters = Type.Object({
|
|
11
|
-
path: Type.String({ minLength: 1 }),
|
|
12
|
-
edits: Type.Optional(Type.Array(editItemParameters, { minItems: 1 })),
|
|
13
|
-
// Compatibility with the original di-code single-edit contract.
|
|
14
|
-
oldText: Type.Optional(Type.String()),
|
|
15
|
-
newText: Type.Optional(Type.String()),
|
|
16
|
-
});
|
|
17
|
-
const defaultEditOperations = {
|
|
18
|
-
async readFile(filePath) {
|
|
19
|
-
return fsReadFile(filePath);
|
|
20
|
-
},
|
|
21
|
-
async writeFile(filePath, content) {
|
|
22
|
-
await fsWriteFile(filePath, content, "utf8");
|
|
23
|
-
},
|
|
24
|
-
};
|
|
25
|
-
function throwIfAborted(signal) {
|
|
26
|
-
if (signal?.aborted)
|
|
27
|
-
throw new Error("Operation aborted");
|
|
28
|
-
}
|
|
29
|
-
function normalizeLineEndings(text) {
|
|
30
|
-
return text.replaceAll("\r\n", "\n").replaceAll("\r", "\n");
|
|
31
|
-
}
|
|
32
|
-
function restoreLineEndings(text, ending) {
|
|
33
|
-
return ending === "\n" ? text : text.replaceAll("\n", "\r\n");
|
|
34
|
-
}
|
|
35
|
-
function detectLineEnding(text) {
|
|
36
|
-
return text.includes("\r\n") ? "\r\n" : "\n";
|
|
37
|
-
}
|
|
38
|
-
function hasUtf8Bom(bytes) {
|
|
39
|
-
return bytes.length >= 3 && bytes[0] === 0xef && bytes[1] === 0xbb && bytes[2] === 0xbf;
|
|
40
|
-
}
|
|
41
|
-
function containsNulByte(bytes) {
|
|
42
|
-
const sampleLength = Math.min(bytes.length, 8 * 1024);
|
|
43
|
-
for (let index = 0; index < sampleLength; index++) {
|
|
44
|
-
if (bytes[index] === 0)
|
|
45
|
-
return true;
|
|
46
|
-
}
|
|
47
|
-
return false;
|
|
48
|
-
}
|
|
49
|
-
function decodeUtf8(bytes, path) {
|
|
50
|
-
const text = bytes.toString("utf8");
|
|
51
|
-
if (!Buffer.from(text, "utf8").equals(bytes))
|
|
52
|
-
throw new Error(`File is not valid UTF-8: ${path}`);
|
|
53
|
-
return text;
|
|
54
|
-
}
|
|
55
|
-
function normalizeEdits(parameters, path) {
|
|
56
|
-
if (parameters.edits) {
|
|
57
|
-
return parameters.edits.map((edit) => ({ oldText: edit.oldText, newText: edit.newText }));
|
|
58
|
-
}
|
|
59
|
-
if (typeof parameters.oldText === "string" && typeof parameters.newText === "string") {
|
|
60
|
-
return [{ oldText: parameters.oldText, newText: parameters.newText }];
|
|
61
|
-
}
|
|
62
|
-
throw new Error(`edit requires edits[] or oldText/newText in ${path}`);
|
|
63
|
-
}
|
|
64
|
-
function legacyError(cause, path, legacy) {
|
|
65
|
-
if (!legacy || !(cause instanceof Error))
|
|
66
|
-
throw cause;
|
|
67
|
-
if (cause.message.includes("oldText must not be empty"))
|
|
68
|
-
throw cause;
|
|
69
|
-
if (cause.message.includes("Could not find edits[0]")) {
|
|
70
|
-
throw new Error(`Text to replace was not found in ${path}`);
|
|
71
|
-
}
|
|
72
|
-
if (cause.message.includes("Found ") && cause.message.includes("occurrences of edits[0]")) {
|
|
73
|
-
throw new Error(`Text to replace is ambiguous in ${path}`);
|
|
74
|
-
}
|
|
75
|
-
throw cause;
|
|
76
|
-
}
|
|
77
|
-
export function createEditTool(allowedRoot, options = {}) {
|
|
78
|
-
const operations = options.operations ?? defaultEditOperations;
|
|
79
|
-
return {
|
|
80
|
-
name: "edit",
|
|
81
|
-
description: "Edit one UTF-8 text file using one or more unique exact replacements in edits[]. Legacy oldText/newText is also accepted.",
|
|
82
|
-
parameters: editParameters,
|
|
83
|
-
async execute(_toolCallId, parameters, signal) {
|
|
84
|
-
throwIfAborted(signal);
|
|
85
|
-
if (parameters.path.length === 0)
|
|
86
|
-
throw new Error("path must not be empty");
|
|
87
|
-
if (parameters.edits === undefined && parameters.oldText === "")
|
|
88
|
-
throw new Error("oldText must not be empty");
|
|
89
|
-
const edits = normalizeEdits(parameters, parameters.path);
|
|
90
|
-
const legacy = parameters.edits === undefined;
|
|
91
|
-
const absolutePath = await resolveAllowedFilePath(parameters.path, allowedRoot);
|
|
92
|
-
return withFileMutationQueue(absolutePath, async () => {
|
|
93
|
-
throwIfAborted(signal);
|
|
94
|
-
const originalBytes = await operations.readFile(absolutePath);
|
|
95
|
-
throwIfAborted(signal);
|
|
96
|
-
if (containsNulByte(originalBytes))
|
|
97
|
-
throw new Error("Binary files are not supported by edit");
|
|
98
|
-
const hasBom = hasUtf8Bom(originalBytes);
|
|
99
|
-
const originalText = decodeUtf8(originalBytes, parameters.path).replace(/^\uFEFF/, "");
|
|
100
|
-
const ending = detectLineEnding(originalText);
|
|
101
|
-
const baseContent = normalizeLineEndings(originalText);
|
|
102
|
-
const normalizedEdits = edits.map((edit) => ({
|
|
103
|
-
oldText: normalizeLineEndings(edit.oldText),
|
|
104
|
-
newText: normalizeLineEndings(edit.newText),
|
|
105
|
-
}));
|
|
106
|
-
let newContent;
|
|
107
|
-
try {
|
|
108
|
-
newContent = applyEditsToContent(baseContent, normalizedEdits, parameters.path).newContent;
|
|
109
|
-
}
|
|
110
|
-
catch (cause) {
|
|
111
|
-
legacyError(cause, parameters.path, legacy);
|
|
112
|
-
}
|
|
113
|
-
throwIfAborted(signal);
|
|
114
|
-
const currentBytes = await operations.readFile(absolutePath);
|
|
115
|
-
throwIfAborted(signal);
|
|
116
|
-
if (!currentBytes.equals(originalBytes)) {
|
|
117
|
-
throw new Error(`File changed during edit: ${parameters.path}`);
|
|
118
|
-
}
|
|
119
|
-
await operations.writeFile(absolutePath, `${hasBom ? "\uFEFF" : ""}${restoreLineEndings(newContent, ending)}`);
|
|
120
|
-
throwIfAborted(signal);
|
|
121
|
-
const display = generateDiffString(baseContent, newContent);
|
|
122
|
-
return {
|
|
123
|
-
content: [
|
|
124
|
-
{
|
|
125
|
-
type: "text",
|
|
126
|
-
text: legacy
|
|
127
|
-
? `Successfully replaced text in ${parameters.path}`
|
|
128
|
-
: `Successfully replaced ${normalizedEdits.length} block(s) in ${parameters.path}.`,
|
|
129
|
-
},
|
|
130
|
-
],
|
|
131
|
-
details: {
|
|
132
|
-
diff: display.diff,
|
|
133
|
-
patch: generateUnifiedPatch(parameters.path, baseContent, newContent),
|
|
134
|
-
...(display.firstChangedLine === undefined ? {} : { firstChangedLine: display.firstChangedLine }),
|
|
135
|
-
},
|
|
136
|
-
};
|
|
137
|
-
});
|
|
138
|
-
},
|
|
139
|
-
};
|
|
140
|
-
}
|
|
1
|
+
export * from "@di-code/builtins";
|
|
141
2
|
//# sourceMappingURL=edit.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"edit.js","sourceRoot":"","sources":["../../../src/core/tools/edit.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,IAAI,UAAU,EAAE,SAAS,IAAI,WAAW,EAAE,MAAM,kBAAkB,CAAC;AAEpF,OAAO,EAAuC,IAAI,EAAE,MAAM,aAAa,CAAC;AACxE,OAAO,EAAE,mBAAmB,EAAa,kBAAkB,EAAE,oBAAoB,EAAE,MAAM,gBAAgB,CAAC;AAC1G,OAAO,EAAE,qBAAqB,EAAE,MAAM,0BAA0B,CAAC;AACjE,OAAO,EAAE,sBAAsB,EAAE,MAAM,oBAAoB,CAAC;AAE5D,MAAM,kBAAkB,GAAG,IAAI,CAAC,MAAM,CAAC;IACtC,OAAO,EAAE,IAAI,CAAC,MAAM,EAAE;IACtB,OAAO,EAAE,IAAI,CAAC,MAAM,EAAE;CACtB,CAAC,CAAC;AAEH,MAAM,CAAC,MAAM,cAAc,GAAG,IAAI,CAAC,MAAM,CAAC;IACzC,IAAI,EAAE,IAAI,CAAC,MAAM,CAAC,EAAE,SAAS,EAAE,CAAC,EAAE,CAAC;IACnC,KAAK,EAAE,IA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AAO,CAAC,gBAAgB,EAAE,CAAC;qBACjG;iBACD,CAAC;YACH,CAAC,CAAC,CAAC;QACJ,CAAC;KACD,CAAC;AACH,CAAC","sourcesContent":["import { readFile as fsReadFile, writeFile as fsWriteFile } from \"node:fs/promises\";\nimport type { AgentTool, ToolExecutionResult } from \"@di-code/agent\";\nimport { type Static, type ToolResultContent, Type } from \"@di-code/ai\";\nimport { applyEditsToContent, type Edit, generateDiffString, generateUnifiedPatch } from \"./edit-diff.ts\";\nimport { withFileMutationQueue } from \"./file-mutation-queue.ts\";\nimport { resolveAllowedFilePath } from \"./path-boundary.ts\";\n\nconst editItemParameters = Type.Object({\n\toldText: Type.String(),\n\tnewText: Type.String(),\n});\n\nexport const editParameters = Type.Object({\n\tpath: Type.String({ minLength: 1 }),\n\tedits: Type.Optional(Type.Array(editItemParameters, { minItems: 1 })),\n\t// Compatibility with the original di-code single-edit contract.\n\toldText: Type.Optional(Type.String()),\n\tnewText: Type.Optional(Type.String()),\n});\n\nexport type EditParameters = Static<typeof editParameters>;\n\nexport interface EditOperations {\n\treadFile(filePath: string): Promise<Buffer>;\n\twriteFile(filePath: string, content: string): Promise<void>;\n}\n\nexport interface EditToolOptions {\n\treadonly operations?: EditOperations;\n}\n\nexport interface EditToolDetails {\n\treadonly diff: string;\n\treadonly patch: string;\n\treadonly firstChangedLine?: number;\n}\n\nexport type EditTool = AgentTool<typeof editParameters, ToolExecutionResult<EditToolDetails>>;\n\nconst defaultEditOperations: EditOperations = {\n\tasync readFile(filePath) {\n\t\treturn fsReadFile(filePath);\n\t},\n\tasync writeFile(filePath, content) {\n\t\tawait fsWriteFile(filePath, content, \"utf8\");\n\t},\n};\n\nfunction throwIfAborted(signal: AbortSignal | undefined): void {\n\tif (signal?.aborted) throw new Error(\"Operation aborted\");\n}\n\nfunction normalizeLineEndings(text: string): string {\n\treturn text.replaceAll(\"\\r\\n\", \"\\n\").replaceAll(\"\\r\", \"\\n\");\n}\n\nfunction restoreLineEndings(text: string, ending: \"\\n\" | \"\\r\\n\"): string {\n\treturn ending === \"\\n\" ? text : text.replaceAll(\"\\n\", \"\\r\\n\");\n}\n\nfunction detectLineEnding(text: string): \"\\n\" | \"\\r\\n\" {\n\treturn text.includes(\"\\r\\n\") ? \"\\r\\n\" : \"\\n\";\n}\n\nfunction hasUtf8Bom(bytes: Buffer): boolean {\n\treturn bytes.length >= 3 && bytes[0] === 0xef && bytes[1] === 0xbb && bytes[2] === 0xbf;\n}\n\nfunction containsNulByte(bytes: Buffer): boolean {\n\tconst sampleLength = Math.min(bytes.length, 8 * 1024);\n\tfor (let index = 0; index < sampleLength; index++) {\n\t\tif (bytes[index] === 0) return true;\n\t}\n\treturn false;\n}\n\nfunction decodeUtf8(bytes: Buffer, path: string): string {\n\tconst text = bytes.toString(\"utf8\");\n\tif (!Buffer.from(text, \"utf8\").equals(bytes)) throw new Error(`File is not valid UTF-8: ${path}`);\n\treturn text;\n}\n\nfunction normalizeEdits(parameters: EditParameters, path: string): Edit[] {\n\tif (parameters.edits) {\n\t\treturn parameters.edits.map((edit) => ({ oldText: edit.oldText, newText: edit.newText }));\n\t}\n\tif (typeof parameters.oldText === \"string\" && typeof parameters.newText === \"string\") {\n\t\treturn [{ oldText: parameters.oldText, newText: parameters.newText }];\n\t}\n\tthrow new Error(`edit requires edits[] or oldText/newText in ${path}`);\n}\n\nfunction legacyError(cause: unknown, path: string, legacy: boolean): never {\n\tif (!legacy || !(cause instanceof Error)) throw cause;\n\tif (cause.message.includes(\"oldText must not be empty\")) throw cause;\n\tif (cause.message.includes(\"Could not find edits[0]\")) {\n\t\tthrow new Error(`Text to replace was not found in ${path}`);\n\t}\n\tif (cause.message.includes(\"Found \") && cause.message.includes(\"occurrences of edits[0]\")) {\n\t\tthrow new Error(`Text to replace is ambiguous in ${path}`);\n\t}\n\tthrow cause;\n}\n\nexport function createEditTool(allowedRoot: string, options: EditToolOptions = {}): EditTool {\n\tconst operations = options.operations ?? defaultEditOperations;\n\n\treturn {\n\t\tname: \"edit\",\n\t\tdescription:\n\t\t\t\"Edit one UTF-8 text file using one or more unique exact replacements in edits[]. Legacy oldText/newText is also accepted.\",\n\t\tparameters: editParameters,\n\t\tasync execute(_toolCallId, parameters, signal): Promise<ToolExecutionResult<EditToolDetails>> {\n\t\t\tthrowIfAborted(signal);\n\t\t\tif (parameters.path.length === 0) throw new Error(\"path must not be empty\");\n\t\t\tif (parameters.edits === undefined && parameters.oldText === \"\") throw new Error(\"oldText must not be empty\");\n\t\t\tconst edits = normalizeEdits(parameters, parameters.path);\n\t\t\tconst legacy = parameters.edits === undefined;\n\t\t\tconst absolutePath = await resolveAllowedFilePath(parameters.path, allowedRoot);\n\n\t\t\treturn withFileMutationQueue(absolutePath, async () => {\n\t\t\t\tthrowIfAborted(signal);\n\t\t\t\tconst originalBytes = await operations.readFile(absolutePath);\n\t\t\t\tthrowIfAborted(signal);\n\t\t\t\tif (containsNulByte(originalBytes)) throw new Error(\"Binary files are not supported by edit\");\n\t\t\t\tconst hasBom = hasUtf8Bom(originalBytes);\n\t\t\t\tconst originalText = decodeUtf8(originalBytes, parameters.path).replace(/^\\uFEFF/, \"\");\n\t\t\t\tconst ending = detectLineEnding(originalText);\n\t\t\t\tconst baseContent = normalizeLineEndings(originalText);\n\t\t\t\tconst normalizedEdits = edits.map((edit) => ({\n\t\t\t\t\toldText: normalizeLineEndings(edit.oldText),\n\t\t\t\t\tnewText: normalizeLineEndings(edit.newText),\n\t\t\t\t}));\n\t\t\t\tlet newContent: string;\n\t\t\t\ttry {\n\t\t\t\t\tnewContent = applyEditsToContent(baseContent, normalizedEdits, parameters.path).newContent;\n\t\t\t\t} catch (cause) {\n\t\t\t\t\tlegacyError(cause, parameters.path, legacy);\n\t\t\t\t}\n\t\t\t\tthrowIfAborted(signal);\n\t\t\t\tconst currentBytes = await operations.readFile(absolutePath);\n\t\t\t\tthrowIfAborted(signal);\n\t\t\t\tif (!currentBytes.equals(originalBytes)) {\n\t\t\t\t\tthrow new Error(`File changed during edit: ${parameters.path}`);\n\t\t\t\t}\n\t\t\t\tawait operations.writeFile(absolutePath, `${hasBom ? \"\\uFEFF\" : \"\"}${restoreLineEndings(newContent, ending)}`);\n\t\t\t\tthrowIfAborted(signal);\n\t\t\t\tconst display = generateDiffString(baseContent, newContent);\n\t\t\t\treturn {\n\t\t\t\t\tcontent: [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\ttext: legacy\n\t\t\t\t\t\t\t\t? `Successfully replaced text in ${parameters.path}`\n\t\t\t\t\t\t\t\t: `Successfully replaced ${normalizedEdits.length} block(s) in ${parameters.path}.`,\n\t\t\t\t\t\t},\n\t\t\t\t\t] satisfies ToolResultContent[],\n\t\t\t\t\tdetails: {\n\t\t\t\t\t\tdiff: display.diff,\n\t\t\t\t\t\tpatch: generateUnifiedPatch(parameters.path, baseContent, newContent),\n\t\t\t\t\t\t...(display.firstChangedLine === undefined ? {} : { firstChangedLine: display.firstChangedLine }),\n\t\t\t\t\t},\n\t\t\t\t};\n\t\t\t});\n\t\t},\n\t};\n}\n"]}
|
|
1
|
+
{"version":3,"file":"edit.js","sourceRoot":"","sources":["../../../src/core/tools/edit.ts"],"names":[],"mappings":"AAAA,cAAc,mBAAmB,CAAC","sourcesContent":["export * from \"@di-code/builtins\";\n"]}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export
|
|
1
|
+
export * from "@di-code/builtins";
|
|
2
2
|
//# sourceMappingURL=file-mutation-queue.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"file-mutation-queue.d.ts","sourceRoot":"","sources":["../../../src/core/tools/file-mutation-queue.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"file-mutation-queue.d.ts","sourceRoot":"","sources":["../../../src/core/tools/file-mutation-queue.ts"],"names":[],"mappings":"AAAA,cAAc,mBAAmB,CAAC"}
|
|
@@ -1,24 +1,2 @@
|
|
|
1
|
-
|
|
2
|
-
const fileMutationQueues = new Map();
|
|
3
|
-
export async function withFileMutationQueue(filePath, operation) {
|
|
4
|
-
const resolvedPath = resolve(filePath);
|
|
5
|
-
const key = process.platform === "win32" ? resolvedPath.toLowerCase() : resolvedPath;
|
|
6
|
-
const currentQueue = fileMutationQueues.get(key) ?? Promise.resolve();
|
|
7
|
-
let releaseNext;
|
|
8
|
-
const nextQueue = new Promise((resolveQueue) => {
|
|
9
|
-
releaseNext = resolveQueue;
|
|
10
|
-
});
|
|
11
|
-
const chainedQueue = currentQueue.then(() => nextQueue);
|
|
12
|
-
fileMutationQueues.set(key, chainedQueue);
|
|
13
|
-
await currentQueue;
|
|
14
|
-
try {
|
|
15
|
-
return await operation();
|
|
16
|
-
}
|
|
17
|
-
finally {
|
|
18
|
-
releaseNext();
|
|
19
|
-
if (fileMutationQueues.get(key) === chainedQueue) {
|
|
20
|
-
fileMutationQueues.delete(key);
|
|
21
|
-
}
|
|
22
|
-
}
|
|
23
|
-
}
|
|
1
|
+
export * from "@di-code/builtins";
|
|
24
2
|
//# sourceMappingURL=file-mutation-queue.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"file-mutation-queue.js","sourceRoot":"","sources":["../../../src/core/tools/file-mutation-queue.ts"],"names":[],"mappings":"AAAA,
|
|
1
|
+
{"version":3,"file":"file-mutation-queue.js","sourceRoot":"","sources":["../../../src/core/tools/file-mutation-queue.ts"],"names":[],"mappings":"AAAA,cAAc,mBAAmB,CAAC","sourcesContent":["export * from \"@di-code/builtins\";\n"]}
|
|
@@ -1,14 +1,2 @@
|
|
|
1
|
-
export
|
|
2
|
-
export declare const DEFAULT_SEARCH_MAX_OUTPUT_BYTES: number;
|
|
3
|
-
export declare const MAX_SEARCH_FILE_BYTES: number;
|
|
4
|
-
export interface SearchFile {
|
|
5
|
-
readonly relativePath: string;
|
|
6
|
-
readonly searchPath: string;
|
|
7
|
-
}
|
|
8
|
-
export declare function assertSearchLimit(name: string, value: number): void;
|
|
9
|
-
export declare function normalizeSearchPattern(pattern: string): string;
|
|
10
|
-
export declare function resolveSearchRoot(inputPath: string | undefined, allowedRoot: string): Promise<string>;
|
|
11
|
-
export declare function walkSearchFiles(rootPath: string, signal?: AbortSignal, displayRootPath?: string): AsyncGenerator<SearchFile, void, undefined>;
|
|
12
|
-
export declare function readSearchText(file: SearchFile, allowedRoot: string, signal?: AbortSignal): Promise<string | undefined>;
|
|
13
|
-
export declare function appendBoundedLine(lines: string[], line: string, maxOutputBytes: number): boolean;
|
|
1
|
+
export * from "@di-code/builtins";
|
|
14
2
|
//# sourceMappingURL=file-search.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"file-search.d.ts","sourceRoot":"","sources":["../../../src/core/tools/file-search.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"file-search.d.ts","sourceRoot":"","sources":["../../../src/core/tools/file-search.ts"],"names":[],"mappings":"AAAA,cAAc,mBAAmB,CAAC"}
|
|
@@ -1,99 +1,2 @@
|
|
|
1
|
-
|
|
2
|
-
import { basename, matchesGlob, relative, resolve, sep } from "node:path";
|
|
3
|
-
import { resolveAllowedExistingPath } from "./path-boundary.js";
|
|
4
|
-
export const DEFAULT_SEARCH_MAX_RESULTS = 200;
|
|
5
|
-
export const DEFAULT_SEARCH_MAX_OUTPUT_BYTES = 50 * 1024;
|
|
6
|
-
export const MAX_SEARCH_FILE_BYTES = 2 * 1024 * 1024;
|
|
7
|
-
export function assertSearchLimit(name, value) {
|
|
8
|
-
if (!Number.isInteger(value) || value < 1)
|
|
9
|
-
throw new Error(`${name} must be a positive integer`);
|
|
10
|
-
}
|
|
11
|
-
export function normalizeSearchPattern(pattern) {
|
|
12
|
-
const normalized = pattern.replaceAll("\\", "/").trim();
|
|
13
|
-
if (normalized.length === 0)
|
|
14
|
-
throw new Error("pattern must not be empty");
|
|
15
|
-
if (normalized.startsWith("/"))
|
|
16
|
-
throw new Error("pattern must be relative to the allowed root");
|
|
17
|
-
try {
|
|
18
|
-
matchesGlob("placeholder", normalized);
|
|
19
|
-
}
|
|
20
|
-
catch (cause) {
|
|
21
|
-
throw new Error(`Invalid glob pattern: ${cause instanceof Error ? cause.message : String(cause)}`);
|
|
22
|
-
}
|
|
23
|
-
return normalized;
|
|
24
|
-
}
|
|
25
|
-
export async function resolveSearchRoot(inputPath, allowedRoot) {
|
|
26
|
-
return resolveAllowedExistingPath(inputPath ?? ".", allowedRoot);
|
|
27
|
-
}
|
|
28
|
-
export async function* walkSearchFiles(rootPath, signal, displayRootPath = rootPath) {
|
|
29
|
-
const traversalRoot = await realpath(rootPath);
|
|
30
|
-
const displayRoot = await realpath(displayRootPath);
|
|
31
|
-
const rootMetadata = await stat(traversalRoot);
|
|
32
|
-
if (rootMetadata.isFile()) {
|
|
33
|
-
yield {
|
|
34
|
-
relativePath: relative(displayRoot, traversalRoot).split(sep).join("/"),
|
|
35
|
-
searchPath: basename(traversalRoot),
|
|
36
|
-
};
|
|
37
|
-
return;
|
|
38
|
-
}
|
|
39
|
-
if (!rootMetadata.isDirectory())
|
|
40
|
-
throw new Error("Search path must be a file or directory");
|
|
41
|
-
const initialEntries = await readDirectoryEntries(traversalRoot);
|
|
42
|
-
const pending = [{ directory: traversalRoot, entries: initialEntries, index: 0 }];
|
|
43
|
-
while (pending.length > 0) {
|
|
44
|
-
if (signal?.aborted)
|
|
45
|
-
throw new Error("Operation aborted");
|
|
46
|
-
const frame = pending[pending.length - 1];
|
|
47
|
-
if (!frame)
|
|
48
|
-
continue;
|
|
49
|
-
const entry = frame.entries[frame.index++];
|
|
50
|
-
if (!entry) {
|
|
51
|
-
pending.pop();
|
|
52
|
-
continue;
|
|
53
|
-
}
|
|
54
|
-
if (entry.isSymbolicLink())
|
|
55
|
-
continue;
|
|
56
|
-
const absolutePath = resolve(frame.directory, entry.name);
|
|
57
|
-
if (entry.isDirectory()) {
|
|
58
|
-
pending.push({ directory: absolutePath, entries: await readDirectoryEntries(absolutePath), index: 0 });
|
|
59
|
-
continue;
|
|
60
|
-
}
|
|
61
|
-
if (!entry.isFile())
|
|
62
|
-
continue;
|
|
63
|
-
const relativePath = relative(displayRoot, absolutePath).split(sep).join("/");
|
|
64
|
-
const searchPath = relative(traversalRoot, absolutePath).split(sep).join("/");
|
|
65
|
-
yield { relativePath, searchPath };
|
|
66
|
-
}
|
|
67
|
-
}
|
|
68
|
-
async function readDirectoryEntries(directory) {
|
|
69
|
-
const entries = await readdir(directory, { withFileTypes: true });
|
|
70
|
-
entries.sort((left, right) => left.name.localeCompare(right.name));
|
|
71
|
-
return entries;
|
|
72
|
-
}
|
|
73
|
-
export async function readSearchText(file, allowedRoot, signal) {
|
|
74
|
-
if (signal?.aborted)
|
|
75
|
-
throw new Error("Operation aborted");
|
|
76
|
-
const safePath = await resolveAllowedExistingPath(file.relativePath, allowedRoot);
|
|
77
|
-
const metadata = await stat(safePath);
|
|
78
|
-
if (!metadata.isFile() || metadata.size > MAX_SEARCH_FILE_BYTES)
|
|
79
|
-
return undefined;
|
|
80
|
-
const buffer = await readFile(safePath);
|
|
81
|
-
if (signal?.aborted)
|
|
82
|
-
throw new Error("Operation aborted");
|
|
83
|
-
const sampleLength = Math.min(buffer.length, 8 * 1024);
|
|
84
|
-
for (let index = 0; index < sampleLength; index++) {
|
|
85
|
-
if (buffer[index] === 0)
|
|
86
|
-
return undefined;
|
|
87
|
-
}
|
|
88
|
-
return buffer.toString("utf8");
|
|
89
|
-
}
|
|
90
|
-
export function appendBoundedLine(lines, line, maxOutputBytes) {
|
|
91
|
-
const separatorBytes = lines.length === 0 ? 0 : 1;
|
|
92
|
-
const nextBytes = Buffer.byteLength(line, "utf8") + separatorBytes;
|
|
93
|
-
const currentBytes = lines.reduce((total, item) => total + Buffer.byteLength(item, "utf8"), 0);
|
|
94
|
-
if (currentBytes + nextBytes > maxOutputBytes)
|
|
95
|
-
return false;
|
|
96
|
-
lines.push(line);
|
|
97
|
-
return true;
|
|
98
|
-
}
|
|
1
|
+
export * from "@di-code/builtins";
|
|
99
2
|
//# sourceMappingURL=file-search.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"file-search.js","sourceRoot":"","sources":["../../../src/core/tools/file-search.ts"],"names":[],"mappings":"AAAA,
|
|
1
|
+
{"version":3,"file":"file-search.js","sourceRoot":"","sources":["../../../src/core/tools/file-search.ts"],"names":[],"mappings":"AAAA,cAAc,mBAAmB,CAAC","sourcesContent":["export * from \"@di-code/builtins\";\n"]}
|
|
@@ -1,11 +1,2 @@
|
|
|
1
|
-
|
|
2
|
-
import { type Static, type ToolResultContent, Type } from "@di-code/ai";
|
|
3
|
-
export declare const globParameters: Type.TObject<{
|
|
4
|
-
pattern: Type.TString;
|
|
5
|
-
path: Type.TOptional<Type.TString>;
|
|
6
|
-
maxResults: Type.TOptional<Type.TInteger>;
|
|
7
|
-
}>;
|
|
8
|
-
export type GlobParameters = Static<typeof globParameters>;
|
|
9
|
-
export type GlobTool = AgentTool<typeof globParameters, ToolResultContent[]>;
|
|
10
|
-
export declare function createGlobTool(allowedRoot: string): GlobTool;
|
|
1
|
+
export * from "@di-code/builtins";
|
|
11
2
|
//# sourceMappingURL=glob.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"glob.d.ts","sourceRoot":"","sources":["../../../src/core/tools/glob.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"glob.d.ts","sourceRoot":"","sources":["../../../src/core/tools/glob.ts"],"names":[],"mappings":"AAAA,cAAc,mBAAmB,CAAC"}
|
package/dist/core/tools/glob.js
CHANGED
|
@@ -1,44 +1,2 @@
|
|
|
1
|
-
|
|
2
|
-
import { Type } from "@di-code/ai";
|
|
3
|
-
import { appendBoundedLine, assertSearchLimit, DEFAULT_SEARCH_MAX_OUTPUT_BYTES, DEFAULT_SEARCH_MAX_RESULTS, normalizeSearchPattern, resolveSearchRoot, walkSearchFiles, } from "./file-search.js";
|
|
4
|
-
export const globParameters = Type.Object({
|
|
5
|
-
pattern: Type.String({ minLength: 1 }),
|
|
6
|
-
path: Type.Optional(Type.String({ minLength: 1 })),
|
|
7
|
-
maxResults: Type.Optional(Type.Integer({ minimum: 1 })),
|
|
8
|
-
});
|
|
9
|
-
export function createGlobTool(allowedRoot) {
|
|
10
|
-
return {
|
|
11
|
-
name: "glob",
|
|
12
|
-
description: "Find files inside the allowed root using a glob pattern such as **/*.ts. Returns sorted relative paths; symlinks are skipped.",
|
|
13
|
-
parameters: globParameters,
|
|
14
|
-
async execute(_toolCallId, parameters, signal) {
|
|
15
|
-
if (signal?.aborted)
|
|
16
|
-
throw new Error("Operation aborted");
|
|
17
|
-
if (parameters.path !== undefined && parameters.path.length === 0)
|
|
18
|
-
throw new Error("path must not be empty");
|
|
19
|
-
const pattern = normalizeSearchPattern(parameters.pattern);
|
|
20
|
-
const maxResults = parameters.maxResults ?? DEFAULT_SEARCH_MAX_RESULTS;
|
|
21
|
-
assertSearchLimit("maxResults", maxResults);
|
|
22
|
-
const root = await resolveSearchRoot(parameters.path, allowedRoot);
|
|
23
|
-
const displayRoot = await resolveSearchRoot(undefined, allowedRoot);
|
|
24
|
-
const lines = [];
|
|
25
|
-
let matched = 0;
|
|
26
|
-
let truncated = false;
|
|
27
|
-
for await (const file of walkSearchFiles(root, signal, displayRoot)) {
|
|
28
|
-
if (!matchesGlob(file.searchPath, pattern))
|
|
29
|
-
continue;
|
|
30
|
-
matched++;
|
|
31
|
-
if (matched > maxResults || !appendBoundedLine(lines, file.relativePath, DEFAULT_SEARCH_MAX_OUTPUT_BYTES)) {
|
|
32
|
-
truncated = true;
|
|
33
|
-
break;
|
|
34
|
-
}
|
|
35
|
-
}
|
|
36
|
-
if (lines.length === 0)
|
|
37
|
-
return [{ type: "text", text: "No files matched." }];
|
|
38
|
-
if (truncated)
|
|
39
|
-
lines.push(`[Results truncated at ${maxResults} matches or 50 KiB.]`);
|
|
40
|
-
return [{ type: "text", text: lines.join("\n") }];
|
|
41
|
-
},
|
|
42
|
-
};
|
|
43
|
-
}
|
|
1
|
+
export * from "@di-code/builtins";
|
|
44
2
|
//# sourceMappingURL=glob.js.map
|