indusagi-coding-agent 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +2249 -0
- package/README.md +546 -0
- package/dist/cli/args.js +282 -0
- package/dist/cli/config-selector.js +30 -0
- package/dist/cli/file-processor.js +78 -0
- package/dist/cli/list-models.js +91 -0
- package/dist/cli/session-picker.js +31 -0
- package/dist/cli.js +10 -0
- package/dist/config.js +158 -0
- package/dist/core/agent-session.js +2097 -0
- package/dist/core/auth-storage.js +278 -0
- package/dist/core/bash-executor.js +211 -0
- package/dist/core/compaction/branch-summarization.js +241 -0
- package/dist/core/compaction/compaction.js +606 -0
- package/dist/core/compaction/index.js +6 -0
- package/dist/core/compaction/utils.js +137 -0
- package/dist/core/diagnostics.js +1 -0
- package/dist/core/event-bus.js +24 -0
- package/dist/core/exec.js +70 -0
- package/dist/core/export-html/ansi-to-html.js +248 -0
- package/dist/core/export-html/index.js +221 -0
- package/dist/core/export-html/template.css +905 -0
- package/dist/core/export-html/template.html +54 -0
- package/dist/core/export-html/template.js +1549 -0
- package/dist/core/export-html/tool-renderer.js +56 -0
- package/dist/core/export-html/vendor/highlight.min.js +1213 -0
- package/dist/core/export-html/vendor/marked.min.js +6 -0
- package/dist/core/extensions/index.js +8 -0
- package/dist/core/extensions/loader.js +395 -0
- package/dist/core/extensions/runner.js +499 -0
- package/dist/core/extensions/types.js +31 -0
- package/dist/core/extensions/wrapper.js +101 -0
- package/dist/core/footer-data-provider.js +133 -0
- package/dist/core/index.js +8 -0
- package/dist/core/keybindings.js +140 -0
- package/dist/core/messages.js +122 -0
- package/dist/core/model-registry.js +454 -0
- package/dist/core/model-resolver.js +309 -0
- package/dist/core/package-manager.js +1142 -0
- package/dist/core/prompt-templates.js +250 -0
- package/dist/core/resource-loader.js +569 -0
- package/dist/core/sdk.js +225 -0
- package/dist/core/session-manager.js +1078 -0
- package/dist/core/settings-manager.js +430 -0
- package/dist/core/skills.js +339 -0
- package/dist/core/system-prompt.js +136 -0
- package/dist/core/timings.js +24 -0
- package/dist/core/tools/bash.js +226 -0
- package/dist/core/tools/edit-diff.js +242 -0
- package/dist/core/tools/edit.js +145 -0
- package/dist/core/tools/find.js +205 -0
- package/dist/core/tools/grep.js +238 -0
- package/dist/core/tools/index.js +60 -0
- package/dist/core/tools/ls.js +117 -0
- package/dist/core/tools/path-utils.js +52 -0
- package/dist/core/tools/read.js +165 -0
- package/dist/core/tools/truncate.js +204 -0
- package/dist/core/tools/write.js +77 -0
- package/dist/index.js +41 -0
- package/dist/main.js +565 -0
- package/dist/migrations.js +260 -0
- package/dist/modes/index.js +7 -0
- package/dist/modes/interactive/components/armin.js +328 -0
- package/dist/modes/interactive/components/assistant-message.js +86 -0
- package/dist/modes/interactive/components/bash-execution.js +155 -0
- package/dist/modes/interactive/components/bordered-loader.js +47 -0
- package/dist/modes/interactive/components/branch-summary-message.js +41 -0
- package/dist/modes/interactive/components/compaction-summary-message.js +42 -0
- package/dist/modes/interactive/components/config-selector.js +458 -0
- package/dist/modes/interactive/components/countdown-timer.js +27 -0
- package/dist/modes/interactive/components/custom-editor.js +61 -0
- package/dist/modes/interactive/components/custom-message.js +80 -0
- package/dist/modes/interactive/components/diff.js +132 -0
- package/dist/modes/interactive/components/dynamic-border.js +19 -0
- package/dist/modes/interactive/components/extension-editor.js +96 -0
- package/dist/modes/interactive/components/extension-input.js +54 -0
- package/dist/modes/interactive/components/extension-selector.js +70 -0
- package/dist/modes/interactive/components/footer.js +213 -0
- package/dist/modes/interactive/components/index.js +31 -0
- package/dist/modes/interactive/components/keybinding-hints.js +60 -0
- package/dist/modes/interactive/components/login-dialog.js +138 -0
- package/dist/modes/interactive/components/model-selector.js +253 -0
- package/dist/modes/interactive/components/oauth-selector.js +91 -0
- package/dist/modes/interactive/components/scoped-models-selector.js +262 -0
- package/dist/modes/interactive/components/session-selector-search.js +145 -0
- package/dist/modes/interactive/components/session-selector.js +698 -0
- package/dist/modes/interactive/components/settings-selector.js +250 -0
- package/dist/modes/interactive/components/show-images-selector.js +33 -0
- package/dist/modes/interactive/components/skill-invocation-message.js +44 -0
- package/dist/modes/interactive/components/theme-selector.js +43 -0
- package/dist/modes/interactive/components/thinking-selector.js +45 -0
- package/dist/modes/interactive/components/tool-execution.js +608 -0
- package/dist/modes/interactive/components/tree-selector.js +892 -0
- package/dist/modes/interactive/components/user-message-selector.js +109 -0
- package/dist/modes/interactive/components/user-message.js +15 -0
- package/dist/modes/interactive/components/visual-truncate.js +32 -0
- package/dist/modes/interactive/interactive-mode.js +3576 -0
- package/dist/modes/interactive/theme/dark.json +85 -0
- package/dist/modes/interactive/theme/light.json +84 -0
- package/dist/modes/interactive/theme/theme-schema.json +335 -0
- package/dist/modes/interactive/theme/theme.js +938 -0
- package/dist/modes/print-mode.js +96 -0
- package/dist/modes/rpc/rpc-client.js +390 -0
- package/dist/modes/rpc/rpc-mode.js +448 -0
- package/dist/modes/rpc/rpc-types.js +7 -0
- package/dist/utils/changelog.js +86 -0
- package/dist/utils/clipboard-image.js +116 -0
- package/dist/utils/clipboard.js +58 -0
- package/dist/utils/frontmatter.js +25 -0
- package/dist/utils/git.js +5 -0
- package/dist/utils/image-convert.js +34 -0
- package/dist/utils/image-resize.js +180 -0
- package/dist/utils/mime.js +25 -0
- package/dist/utils/photon.js +120 -0
- package/dist/utils/shell.js +164 -0
- package/dist/utils/sleep.js +16 -0
- package/dist/utils/tools-manager.js +186 -0
- package/docs/compaction.md +390 -0
- package/docs/custom-provider.md +538 -0
- package/docs/development.md +69 -0
- package/docs/extensions.md +1733 -0
- package/docs/images/doom-extension.png +0 -0
- package/docs/images/interactive-mode.png +0 -0
- package/docs/images/tree-view.png +0 -0
- package/docs/json.md +79 -0
- package/docs/keybindings.md +162 -0
- package/docs/models.md +193 -0
- package/docs/packages.md +163 -0
- package/docs/prompt-templates.md +67 -0
- package/docs/providers.md +147 -0
- package/docs/rpc.md +1048 -0
- package/docs/sdk.md +957 -0
- package/docs/session.md +412 -0
- package/docs/settings.md +216 -0
- package/docs/shell-aliases.md +13 -0
- package/docs/skills.md +226 -0
- package/docs/terminal-setup.md +65 -0
- package/docs/themes.md +295 -0
- package/docs/tree.md +219 -0
- package/docs/tui.md +887 -0
- package/docs/windows.md +17 -0
- package/examples/README.md +25 -0
- package/examples/extensions/README.md +192 -0
- package/examples/extensions/antigravity-image-gen.ts +414 -0
- package/examples/extensions/auto-commit-on-exit.ts +49 -0
- package/examples/extensions/bookmark.ts +50 -0
- package/examples/extensions/claude-rules.ts +86 -0
- package/examples/extensions/confirm-destructive.ts +59 -0
- package/examples/extensions/custom-compaction.ts +115 -0
- package/examples/extensions/custom-footer.ts +65 -0
- package/examples/extensions/custom-header.ts +73 -0
- package/examples/extensions/custom-provider-anthropic/index.ts +605 -0
- package/examples/extensions/custom-provider-anthropic/package-lock.json +24 -0
- package/examples/extensions/custom-provider-anthropic/package.json +19 -0
- package/examples/extensions/custom-provider-gitlab-duo/index.ts +350 -0
- package/examples/extensions/custom-provider-gitlab-duo/package.json +16 -0
- package/examples/extensions/custom-provider-gitlab-duo/test.ts +83 -0
- package/examples/extensions/dirty-repo-guard.ts +56 -0
- package/examples/extensions/doom-overlay/README.md +46 -0
- package/examples/extensions/doom-overlay/doom/build/doom.js +21 -0
- package/examples/extensions/doom-overlay/doom/build/doom.wasm +0 -0
- package/examples/extensions/doom-overlay/doom/build.sh +152 -0
- package/examples/extensions/doom-overlay/doom/doomgeneric_pi.c +72 -0
- package/examples/extensions/doom-overlay/doom-component.ts +133 -0
- package/examples/extensions/doom-overlay/doom-engine.ts +173 -0
- package/examples/extensions/doom-overlay/doom-keys.ts +105 -0
- package/examples/extensions/doom-overlay/index.ts +74 -0
- package/examples/extensions/doom-overlay/wad-finder.ts +51 -0
- package/examples/extensions/event-bus.ts +43 -0
- package/examples/extensions/file-trigger.ts +41 -0
- package/examples/extensions/git-checkpoint.ts +53 -0
- package/examples/extensions/handoff.ts +151 -0
- package/examples/extensions/hello.ts +25 -0
- package/examples/extensions/inline-bash.ts +94 -0
- package/examples/extensions/input-transform.ts +43 -0
- package/examples/extensions/interactive-shell.ts +196 -0
- package/examples/extensions/mac-system-theme.ts +47 -0
- package/examples/extensions/message-renderer.ts +60 -0
- package/examples/extensions/modal-editor.ts +86 -0
- package/examples/extensions/model-status.ts +31 -0
- package/examples/extensions/notify.ts +25 -0
- package/examples/extensions/overlay-qa-tests.ts +882 -0
- package/examples/extensions/overlay-test.ts +151 -0
- package/examples/extensions/permission-gate.ts +34 -0
- package/examples/extensions/pirate.ts +47 -0
- package/examples/extensions/plan-mode/README.md +65 -0
- package/examples/extensions/plan-mode/index.ts +341 -0
- package/examples/extensions/plan-mode/utils.ts +168 -0
- package/examples/extensions/preset.ts +399 -0
- package/examples/extensions/protected-paths.ts +30 -0
- package/examples/extensions/qna.ts +120 -0
- package/examples/extensions/question.ts +265 -0
- package/examples/extensions/questionnaire.ts +428 -0
- package/examples/extensions/rainbow-editor.ts +88 -0
- package/examples/extensions/sandbox/index.ts +318 -0
- package/examples/extensions/sandbox/package-lock.json +92 -0
- package/examples/extensions/sandbox/package.json +19 -0
- package/examples/extensions/send-user-message.ts +97 -0
- package/examples/extensions/session-name.ts +27 -0
- package/examples/extensions/shutdown-command.ts +63 -0
- package/examples/extensions/snake.ts +344 -0
- package/examples/extensions/space-invaders.ts +561 -0
- package/examples/extensions/ssh.ts +220 -0
- package/examples/extensions/status-line.ts +40 -0
- package/examples/extensions/subagent/README.md +172 -0
- package/examples/extensions/subagent/agents/planner.md +37 -0
- package/examples/extensions/subagent/agents/reviewer.md +35 -0
- package/examples/extensions/subagent/agents/scout.md +50 -0
- package/examples/extensions/subagent/agents/worker.md +24 -0
- package/examples/extensions/subagent/agents.ts +127 -0
- package/examples/extensions/subagent/index.ts +964 -0
- package/examples/extensions/subagent/prompts/implement-and-review.md +10 -0
- package/examples/extensions/subagent/prompts/implement.md +10 -0
- package/examples/extensions/subagent/prompts/scout-and-plan.md +9 -0
- package/examples/extensions/summarize.ts +196 -0
- package/examples/extensions/timed-confirm.ts +70 -0
- package/examples/extensions/todo.ts +300 -0
- package/examples/extensions/tool-override.ts +144 -0
- package/examples/extensions/tools.ts +147 -0
- package/examples/extensions/trigger-compact.ts +40 -0
- package/examples/extensions/truncated-tool.ts +193 -0
- package/examples/extensions/widget-placement.ts +17 -0
- package/examples/extensions/with-deps/index.ts +36 -0
- package/examples/extensions/with-deps/package-lock.json +31 -0
- package/examples/extensions/with-deps/package.json +22 -0
- package/examples/sdk/01-minimal.ts +22 -0
- package/examples/sdk/02-custom-model.ts +50 -0
- package/examples/sdk/03-custom-prompt.ts +55 -0
- package/examples/sdk/04-skills.ts +46 -0
- package/examples/sdk/05-tools.ts +56 -0
- package/examples/sdk/06-extensions.ts +88 -0
- package/examples/sdk/07-context-files.ts +40 -0
- package/examples/sdk/08-prompt-templates.ts +47 -0
- package/examples/sdk/09-api-keys-and-oauth.ts +48 -0
- package/examples/sdk/10-settings.ts +38 -0
- package/examples/sdk/11-sessions.ts +48 -0
- package/examples/sdk/12-full-control.ts +82 -0
- package/examples/sdk/13-codex-oauth.ts +37 -0
- package/examples/sdk/README.md +144 -0
- package/package.json +85 -0
|
@@ -0,0 +1,226 @@
|
|
|
1
|
+
import { randomBytes } from "node:crypto";
|
|
2
|
+
import { createWriteStream, existsSync } from "node:fs";
|
|
3
|
+
import { tmpdir } from "node:os";
|
|
4
|
+
import { join } from "node:path";
|
|
5
|
+
import { Type } from "@sinclair/typebox";
|
|
6
|
+
import { spawn } from "child_process";
|
|
7
|
+
import { getShellConfig, getShellEnv, killProcessTree } from "../../utils/shell.js";
|
|
8
|
+
import { DEFAULT_MAX_BYTES, DEFAULT_MAX_LINES, formatSize, truncateTail } from "./truncate.js";
|
|
9
|
+
/**
|
|
10
|
+
* Generate a unique temp file path for bash output
|
|
11
|
+
*/
|
|
12
|
+
function getTempFilePath() {
|
|
13
|
+
const id = randomBytes(8).toString("hex");
|
|
14
|
+
return join(tmpdir(), `indusagi-bash-${id}.log`);
|
|
15
|
+
}
|
|
16
|
+
const bashSchema = Type.Object({
|
|
17
|
+
command: Type.String({ description: "Bash command to execute" }),
|
|
18
|
+
timeout: Type.Optional(Type.Number({ description: "Timeout in seconds (optional, no default timeout)" })),
|
|
19
|
+
});
|
|
20
|
+
/**
|
|
21
|
+
* Default bash operations using local shell
|
|
22
|
+
*/
|
|
23
|
+
const defaultBashOperations = {
|
|
24
|
+
exec: (command, cwd, { onData, signal, timeout }) => {
|
|
25
|
+
return new Promise((resolve, reject) => {
|
|
26
|
+
const { shell, args } = getShellConfig();
|
|
27
|
+
if (!existsSync(cwd)) {
|
|
28
|
+
reject(new Error(`Working directory does not exist: ${cwd}\nCannot execute bash commands.`));
|
|
29
|
+
return;
|
|
30
|
+
}
|
|
31
|
+
const child = spawn(shell, [...args, command], {
|
|
32
|
+
cwd,
|
|
33
|
+
detached: true,
|
|
34
|
+
env: getShellEnv(),
|
|
35
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
36
|
+
});
|
|
37
|
+
let timedOut = false;
|
|
38
|
+
// Set timeout if provided
|
|
39
|
+
let timeoutHandle;
|
|
40
|
+
if (timeout !== undefined && timeout > 0) {
|
|
41
|
+
timeoutHandle = setTimeout(() => {
|
|
42
|
+
timedOut = true;
|
|
43
|
+
if (child.pid) {
|
|
44
|
+
killProcessTree(child.pid);
|
|
45
|
+
}
|
|
46
|
+
}, timeout * 1000);
|
|
47
|
+
}
|
|
48
|
+
// Stream stdout and stderr
|
|
49
|
+
if (child.stdout) {
|
|
50
|
+
child.stdout.on("data", onData);
|
|
51
|
+
}
|
|
52
|
+
if (child.stderr) {
|
|
53
|
+
child.stderr.on("data", onData);
|
|
54
|
+
}
|
|
55
|
+
// Handle shell spawn errors
|
|
56
|
+
child.on("error", (err) => {
|
|
57
|
+
if (timeoutHandle)
|
|
58
|
+
clearTimeout(timeoutHandle);
|
|
59
|
+
if (signal)
|
|
60
|
+
signal.removeEventListener("abort", onAbort);
|
|
61
|
+
reject(err);
|
|
62
|
+
});
|
|
63
|
+
// Handle abort signal - kill entire process tree
|
|
64
|
+
const onAbort = () => {
|
|
65
|
+
if (child.pid) {
|
|
66
|
+
killProcessTree(child.pid);
|
|
67
|
+
}
|
|
68
|
+
};
|
|
69
|
+
if (signal) {
|
|
70
|
+
if (signal.aborted) {
|
|
71
|
+
onAbort();
|
|
72
|
+
}
|
|
73
|
+
else {
|
|
74
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
// Handle process exit
|
|
78
|
+
child.on("close", (code) => {
|
|
79
|
+
if (timeoutHandle)
|
|
80
|
+
clearTimeout(timeoutHandle);
|
|
81
|
+
if (signal)
|
|
82
|
+
signal.removeEventListener("abort", onAbort);
|
|
83
|
+
if (signal?.aborted) {
|
|
84
|
+
reject(new Error("aborted"));
|
|
85
|
+
return;
|
|
86
|
+
}
|
|
87
|
+
if (timedOut) {
|
|
88
|
+
reject(new Error(`timeout:${timeout}`));
|
|
89
|
+
return;
|
|
90
|
+
}
|
|
91
|
+
resolve({ exitCode: code });
|
|
92
|
+
});
|
|
93
|
+
});
|
|
94
|
+
},
|
|
95
|
+
};
|
|
96
|
+
export function createBashTool(cwd, options) {
|
|
97
|
+
const ops = options?.operations ?? defaultBashOperations;
|
|
98
|
+
const commandPrefix = options?.commandPrefix;
|
|
99
|
+
return {
|
|
100
|
+
name: "bash",
|
|
101
|
+
label: "bash",
|
|
102
|
+
description: `Execute a bash command in the current working directory. Returns stdout and stderr. Output is truncated to last ${DEFAULT_MAX_LINES} lines or ${DEFAULT_MAX_BYTES / 1024}KB (whichever is hit first). If truncated, full output is saved to a temp file. Optionally provide a timeout in seconds.`,
|
|
103
|
+
parameters: bashSchema,
|
|
104
|
+
execute: async (_toolCallId, { command, timeout }, signal, onUpdate) => {
|
|
105
|
+
// Apply command prefix if configured (e.g., "shopt -s expand_aliases" for alias support)
|
|
106
|
+
const resolvedCommand = commandPrefix ? `${commandPrefix}\n${command}` : command;
|
|
107
|
+
return new Promise((resolve, reject) => {
|
|
108
|
+
// We'll stream to a temp file if output gets large
|
|
109
|
+
let tempFilePath;
|
|
110
|
+
let tempFileStream;
|
|
111
|
+
let totalBytes = 0;
|
|
112
|
+
// Keep a rolling buffer of the last chunk for tail truncation
|
|
113
|
+
const chunks = [];
|
|
114
|
+
let chunksBytes = 0;
|
|
115
|
+
// Keep more than we need so we have enough for truncation
|
|
116
|
+
const maxChunksBytes = DEFAULT_MAX_BYTES * 2;
|
|
117
|
+
const handleData = (data) => {
|
|
118
|
+
totalBytes += data.length;
|
|
119
|
+
// Start writing to temp file once we exceed the threshold
|
|
120
|
+
if (totalBytes > DEFAULT_MAX_BYTES && !tempFilePath) {
|
|
121
|
+
tempFilePath = getTempFilePath();
|
|
122
|
+
tempFileStream = createWriteStream(tempFilePath);
|
|
123
|
+
// Write all buffered chunks to the file
|
|
124
|
+
for (const chunk of chunks) {
|
|
125
|
+
tempFileStream.write(chunk);
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
// Write to temp file if we have one
|
|
129
|
+
if (tempFileStream) {
|
|
130
|
+
tempFileStream.write(data);
|
|
131
|
+
}
|
|
132
|
+
// Keep rolling buffer of recent data
|
|
133
|
+
chunks.push(data);
|
|
134
|
+
chunksBytes += data.length;
|
|
135
|
+
// Trim old chunks if buffer is too large
|
|
136
|
+
while (chunksBytes > maxChunksBytes && chunks.length > 1) {
|
|
137
|
+
const removed = chunks.shift();
|
|
138
|
+
chunksBytes -= removed.length;
|
|
139
|
+
}
|
|
140
|
+
// Stream partial output to callback (truncated rolling buffer)
|
|
141
|
+
if (onUpdate) {
|
|
142
|
+
const fullBuffer = Buffer.concat(chunks);
|
|
143
|
+
const fullText = fullBuffer.toString("utf-8");
|
|
144
|
+
const truncation = truncateTail(fullText);
|
|
145
|
+
onUpdate({
|
|
146
|
+
content: [{ type: "text", text: truncation.content || "" }],
|
|
147
|
+
details: {
|
|
148
|
+
truncation: truncation.truncated ? truncation : undefined,
|
|
149
|
+
fullOutputPath: tempFilePath,
|
|
150
|
+
},
|
|
151
|
+
});
|
|
152
|
+
}
|
|
153
|
+
};
|
|
154
|
+
ops.exec(resolvedCommand, cwd, { onData: handleData, signal, timeout })
|
|
155
|
+
.then(({ exitCode }) => {
|
|
156
|
+
// Close temp file stream
|
|
157
|
+
if (tempFileStream) {
|
|
158
|
+
tempFileStream.end();
|
|
159
|
+
}
|
|
160
|
+
// Combine all buffered chunks
|
|
161
|
+
const fullBuffer = Buffer.concat(chunks);
|
|
162
|
+
const fullOutput = fullBuffer.toString("utf-8");
|
|
163
|
+
// Apply tail truncation
|
|
164
|
+
const truncation = truncateTail(fullOutput);
|
|
165
|
+
let outputText = truncation.content || "(no output)";
|
|
166
|
+
// Build details with truncation info
|
|
167
|
+
let details;
|
|
168
|
+
if (truncation.truncated) {
|
|
169
|
+
details = {
|
|
170
|
+
truncation,
|
|
171
|
+
fullOutputPath: tempFilePath,
|
|
172
|
+
};
|
|
173
|
+
// Build actionable notice
|
|
174
|
+
const startLine = truncation.totalLines - truncation.outputLines + 1;
|
|
175
|
+
const endLine = truncation.totalLines;
|
|
176
|
+
if (truncation.lastLinePartial) {
|
|
177
|
+
// Edge case: last line alone > 30KB
|
|
178
|
+
const lastLineSize = formatSize(Buffer.byteLength(fullOutput.split("\n").pop() || "", "utf-8"));
|
|
179
|
+
outputText += `\n\n[Showing last ${formatSize(truncation.outputBytes)} of line ${endLine} (line is ${lastLineSize}). Full output: ${tempFilePath}]`;
|
|
180
|
+
}
|
|
181
|
+
else if (truncation.truncatedBy === "lines") {
|
|
182
|
+
outputText += `\n\n[Showing lines ${startLine}-${endLine} of ${truncation.totalLines}. Full output: ${tempFilePath}]`;
|
|
183
|
+
}
|
|
184
|
+
else {
|
|
185
|
+
outputText += `\n\n[Showing lines ${startLine}-${endLine} of ${truncation.totalLines} (${formatSize(DEFAULT_MAX_BYTES)} limit). Full output: ${tempFilePath}]`;
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
if (exitCode !== 0 && exitCode !== null) {
|
|
189
|
+
outputText += `\n\nCommand exited with code ${exitCode}`;
|
|
190
|
+
reject(new Error(outputText));
|
|
191
|
+
}
|
|
192
|
+
else {
|
|
193
|
+
resolve({ content: [{ type: "text", text: outputText }], details });
|
|
194
|
+
}
|
|
195
|
+
})
|
|
196
|
+
.catch((err) => {
|
|
197
|
+
// Close temp file stream
|
|
198
|
+
if (tempFileStream) {
|
|
199
|
+
tempFileStream.end();
|
|
200
|
+
}
|
|
201
|
+
// Combine all buffered chunks for error output
|
|
202
|
+
const fullBuffer = Buffer.concat(chunks);
|
|
203
|
+
let output = fullBuffer.toString("utf-8");
|
|
204
|
+
if (err.message === "aborted") {
|
|
205
|
+
if (output)
|
|
206
|
+
output += "\n\n";
|
|
207
|
+
output += "Command aborted";
|
|
208
|
+
reject(new Error(output));
|
|
209
|
+
}
|
|
210
|
+
else if (err.message.startsWith("timeout:")) {
|
|
211
|
+
const timeoutSecs = err.message.split(":")[1];
|
|
212
|
+
if (output)
|
|
213
|
+
output += "\n\n";
|
|
214
|
+
output += `Command timed out after ${timeoutSecs} seconds`;
|
|
215
|
+
reject(new Error(output));
|
|
216
|
+
}
|
|
217
|
+
else {
|
|
218
|
+
reject(err);
|
|
219
|
+
}
|
|
220
|
+
});
|
|
221
|
+
});
|
|
222
|
+
},
|
|
223
|
+
};
|
|
224
|
+
}
|
|
225
|
+
/** Default bash tool using process.cwd() - for backwards compatibility */
|
|
226
|
+
export const bashTool = createBashTool(process.cwd());
|
|
@@ -0,0 +1,242 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Shared diff computation utilities for the edit tool.
|
|
3
|
+
* Used by both edit.ts (for execution) and tool-execution.ts (for preview rendering).
|
|
4
|
+
*/
|
|
5
|
+
import * as Diff from "diff";
|
|
6
|
+
import { constants } from "fs";
|
|
7
|
+
import { access, readFile } from "fs/promises";
|
|
8
|
+
import { resolveToCwd } from "./path-utils.js";
|
|
9
|
+
export function detectLineEnding(content) {
|
|
10
|
+
const crlfIdx = content.indexOf("\r\n");
|
|
11
|
+
const lfIdx = content.indexOf("\n");
|
|
12
|
+
if (lfIdx === -1)
|
|
13
|
+
return "\n";
|
|
14
|
+
if (crlfIdx === -1)
|
|
15
|
+
return "\n";
|
|
16
|
+
return crlfIdx < lfIdx ? "\r\n" : "\n";
|
|
17
|
+
}
|
|
18
|
+
export function normalizeToLF(text) {
|
|
19
|
+
return text.replace(/\r\n/g, "\n").replace(/\r/g, "\n");
|
|
20
|
+
}
|
|
21
|
+
export function restoreLineEndings(text, ending) {
|
|
22
|
+
return ending === "\r\n" ? text.replace(/\n/g, "\r\n") : text;
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* Normalize text for fuzzy matching. Applies progressive transformations:
|
|
26
|
+
* - Strip trailing whitespace from each line
|
|
27
|
+
* - Normalize smart quotes to ASCII equivalents
|
|
28
|
+
* - Normalize Unicode dashes/hyphens to ASCII hyphen
|
|
29
|
+
* - Normalize special Unicode spaces to regular space
|
|
30
|
+
*/
|
|
31
|
+
export function normalizeForFuzzyMatch(text) {
|
|
32
|
+
return (text
|
|
33
|
+
// Strip trailing whitespace per line
|
|
34
|
+
.split("\n")
|
|
35
|
+
.map((line) => line.trimEnd())
|
|
36
|
+
.join("\n")
|
|
37
|
+
// Smart single quotes → '
|
|
38
|
+
.replace(/[\u2018\u2019\u201A\u201B]/g, "'")
|
|
39
|
+
// Smart double quotes → "
|
|
40
|
+
.replace(/[\u201C\u201D\u201E\u201F]/g, '"')
|
|
41
|
+
// Various dashes/hyphens → -
|
|
42
|
+
// U+2010 hyphen, U+2011 non-breaking hyphen, U+2012 figure dash,
|
|
43
|
+
// U+2013 en-dash, U+2014 em-dash, U+2015 horizontal bar, U+2212 minus
|
|
44
|
+
.replace(/[\u2010\u2011\u2012\u2013\u2014\u2015\u2212]/g, "-")
|
|
45
|
+
// Special spaces → regular space
|
|
46
|
+
// U+00A0 NBSP, U+2002-U+200A various spaces, U+202F narrow NBSP,
|
|
47
|
+
// U+205F medium math space, U+3000 ideographic space
|
|
48
|
+
.replace(/[\u00A0\u2002-\u200A\u202F\u205F\u3000]/g, " "));
|
|
49
|
+
}
|
|
50
|
+
/**
|
|
51
|
+
* Find oldText in content, trying exact match first, then fuzzy match.
|
|
52
|
+
* When fuzzy matching is used, the returned contentForReplacement is the
|
|
53
|
+
* fuzzy-normalized version of the content (trailing whitespace stripped,
|
|
54
|
+
* Unicode quotes/dashes normalized to ASCII).
|
|
55
|
+
*/
|
|
56
|
+
export function fuzzyFindText(content, oldText) {
|
|
57
|
+
// Try exact match first
|
|
58
|
+
const exactIndex = content.indexOf(oldText);
|
|
59
|
+
if (exactIndex !== -1) {
|
|
60
|
+
return {
|
|
61
|
+
found: true,
|
|
62
|
+
index: exactIndex,
|
|
63
|
+
matchLength: oldText.length,
|
|
64
|
+
usedFuzzyMatch: false,
|
|
65
|
+
contentForReplacement: content,
|
|
66
|
+
};
|
|
67
|
+
}
|
|
68
|
+
// Try fuzzy match - work entirely in normalized space
|
|
69
|
+
const fuzzyContent = normalizeForFuzzyMatch(content);
|
|
70
|
+
const fuzzyOldText = normalizeForFuzzyMatch(oldText);
|
|
71
|
+
const fuzzyIndex = fuzzyContent.indexOf(fuzzyOldText);
|
|
72
|
+
if (fuzzyIndex === -1) {
|
|
73
|
+
return {
|
|
74
|
+
found: false,
|
|
75
|
+
index: -1,
|
|
76
|
+
matchLength: 0,
|
|
77
|
+
usedFuzzyMatch: false,
|
|
78
|
+
contentForReplacement: content,
|
|
79
|
+
};
|
|
80
|
+
}
|
|
81
|
+
// When fuzzy matching, we work in the normalized space for replacement.
|
|
82
|
+
// This means the output will have normalized whitespace/quotes/dashes,
|
|
83
|
+
// which is acceptable since we're fixing minor formatting differences anyway.
|
|
84
|
+
return {
|
|
85
|
+
found: true,
|
|
86
|
+
index: fuzzyIndex,
|
|
87
|
+
matchLength: fuzzyOldText.length,
|
|
88
|
+
usedFuzzyMatch: true,
|
|
89
|
+
contentForReplacement: fuzzyContent,
|
|
90
|
+
};
|
|
91
|
+
}
|
|
92
|
+
/** Strip UTF-8 BOM if present, return both the BOM (if any) and the text without it */
|
|
93
|
+
export function stripBom(content) {
|
|
94
|
+
return content.startsWith("\uFEFF") ? { bom: "\uFEFF", text: content.slice(1) } : { bom: "", text: content };
|
|
95
|
+
}
|
|
96
|
+
/**
|
|
97
|
+
* Generate a unified diff string with line numbers and context.
|
|
98
|
+
* Returns both the diff string and the first changed line number (in the new file).
|
|
99
|
+
*/
|
|
100
|
+
export function generateDiffString(oldContent, newContent, contextLines = 4) {
|
|
101
|
+
const parts = Diff.diffLines(oldContent, newContent);
|
|
102
|
+
const output = [];
|
|
103
|
+
const oldLines = oldContent.split("\n");
|
|
104
|
+
const newLines = newContent.split("\n");
|
|
105
|
+
const maxLineNum = Math.max(oldLines.length, newLines.length);
|
|
106
|
+
const lineNumWidth = String(maxLineNum).length;
|
|
107
|
+
let oldLineNum = 1;
|
|
108
|
+
let newLineNum = 1;
|
|
109
|
+
let lastWasChange = false;
|
|
110
|
+
let firstChangedLine;
|
|
111
|
+
for (let i = 0; i < parts.length; i++) {
|
|
112
|
+
const part = parts[i];
|
|
113
|
+
const raw = part.value.split("\n");
|
|
114
|
+
if (raw[raw.length - 1] === "") {
|
|
115
|
+
raw.pop();
|
|
116
|
+
}
|
|
117
|
+
if (part.added || part.removed) {
|
|
118
|
+
// Capture the first changed line (in the new file)
|
|
119
|
+
if (firstChangedLine === undefined) {
|
|
120
|
+
firstChangedLine = newLineNum;
|
|
121
|
+
}
|
|
122
|
+
// Show the change
|
|
123
|
+
for (const line of raw) {
|
|
124
|
+
if (part.added) {
|
|
125
|
+
const lineNum = String(newLineNum).padStart(lineNumWidth, " ");
|
|
126
|
+
output.push(`+${lineNum} ${line}`);
|
|
127
|
+
newLineNum++;
|
|
128
|
+
}
|
|
129
|
+
else {
|
|
130
|
+
// removed
|
|
131
|
+
const lineNum = String(oldLineNum).padStart(lineNumWidth, " ");
|
|
132
|
+
output.push(`-${lineNum} ${line}`);
|
|
133
|
+
oldLineNum++;
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
lastWasChange = true;
|
|
137
|
+
}
|
|
138
|
+
else {
|
|
139
|
+
// Context lines - only show a few before/after changes
|
|
140
|
+
const nextPartIsChange = i < parts.length - 1 && (parts[i + 1].added || parts[i + 1].removed);
|
|
141
|
+
if (lastWasChange || nextPartIsChange) {
|
|
142
|
+
// Show context
|
|
143
|
+
let linesToShow = raw;
|
|
144
|
+
let skipStart = 0;
|
|
145
|
+
let skipEnd = 0;
|
|
146
|
+
if (!lastWasChange) {
|
|
147
|
+
// Show only last N lines as leading context
|
|
148
|
+
skipStart = Math.max(0, raw.length - contextLines);
|
|
149
|
+
linesToShow = raw.slice(skipStart);
|
|
150
|
+
}
|
|
151
|
+
if (!nextPartIsChange && linesToShow.length > contextLines) {
|
|
152
|
+
// Show only first N lines as trailing context
|
|
153
|
+
skipEnd = linesToShow.length - contextLines;
|
|
154
|
+
linesToShow = linesToShow.slice(0, contextLines);
|
|
155
|
+
}
|
|
156
|
+
// Add ellipsis if we skipped lines at start
|
|
157
|
+
if (skipStart > 0) {
|
|
158
|
+
output.push(` ${"".padStart(lineNumWidth, " ")} ...`);
|
|
159
|
+
// Update line numbers for the skipped leading context
|
|
160
|
+
oldLineNum += skipStart;
|
|
161
|
+
newLineNum += skipStart;
|
|
162
|
+
}
|
|
163
|
+
for (const line of linesToShow) {
|
|
164
|
+
const lineNum = String(oldLineNum).padStart(lineNumWidth, " ");
|
|
165
|
+
output.push(` ${lineNum} ${line}`);
|
|
166
|
+
oldLineNum++;
|
|
167
|
+
newLineNum++;
|
|
168
|
+
}
|
|
169
|
+
// Add ellipsis if we skipped lines at end
|
|
170
|
+
if (skipEnd > 0) {
|
|
171
|
+
output.push(` ${"".padStart(lineNumWidth, " ")} ...`);
|
|
172
|
+
// Update line numbers for the skipped trailing context
|
|
173
|
+
oldLineNum += skipEnd;
|
|
174
|
+
newLineNum += skipEnd;
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
else {
|
|
178
|
+
// Skip these context lines entirely
|
|
179
|
+
oldLineNum += raw.length;
|
|
180
|
+
newLineNum += raw.length;
|
|
181
|
+
}
|
|
182
|
+
lastWasChange = false;
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
return { diff: output.join("\n"), firstChangedLine };
|
|
186
|
+
}
|
|
187
|
+
/**
|
|
188
|
+
* Compute the diff for an edit operation without applying it.
|
|
189
|
+
* Used for preview rendering in the TUI before the tool executes.
|
|
190
|
+
*/
|
|
191
|
+
export async function computeEditDiff(path, oldText, newText, cwd) {
|
|
192
|
+
const absolutePath = resolveToCwd(path, cwd);
|
|
193
|
+
try {
|
|
194
|
+
// Check if file exists and is readable
|
|
195
|
+
try {
|
|
196
|
+
await access(absolutePath, constants.R_OK);
|
|
197
|
+
}
|
|
198
|
+
catch {
|
|
199
|
+
return { error: `File not found: ${path}` };
|
|
200
|
+
}
|
|
201
|
+
// Read the file
|
|
202
|
+
const rawContent = await readFile(absolutePath, "utf-8");
|
|
203
|
+
// Strip BOM before matching (LLM won't include invisible BOM in oldText)
|
|
204
|
+
const { text: content } = stripBom(rawContent);
|
|
205
|
+
const normalizedContent = normalizeToLF(content);
|
|
206
|
+
const normalizedOldText = normalizeToLF(oldText);
|
|
207
|
+
const normalizedNewText = normalizeToLF(newText);
|
|
208
|
+
// Find the old text using fuzzy matching (tries exact match first, then fuzzy)
|
|
209
|
+
const matchResult = fuzzyFindText(normalizedContent, normalizedOldText);
|
|
210
|
+
if (!matchResult.found) {
|
|
211
|
+
return {
|
|
212
|
+
error: `Could not find the exact text in ${path}. The old text must match exactly including all whitespace and newlines.`,
|
|
213
|
+
};
|
|
214
|
+
}
|
|
215
|
+
// Count occurrences using fuzzy-normalized content for consistency
|
|
216
|
+
const fuzzyContent = normalizeForFuzzyMatch(normalizedContent);
|
|
217
|
+
const fuzzyOldText = normalizeForFuzzyMatch(normalizedOldText);
|
|
218
|
+
const occurrences = fuzzyContent.split(fuzzyOldText).length - 1;
|
|
219
|
+
if (occurrences > 1) {
|
|
220
|
+
return {
|
|
221
|
+
error: `Found ${occurrences} occurrences of the text in ${path}. The text must be unique. Please provide more context to make it unique.`,
|
|
222
|
+
};
|
|
223
|
+
}
|
|
224
|
+
// Compute the new content using the matched position
|
|
225
|
+
// When fuzzy matching was used, contentForReplacement is the normalized version
|
|
226
|
+
const baseContent = matchResult.contentForReplacement;
|
|
227
|
+
const newContent = baseContent.substring(0, matchResult.index) +
|
|
228
|
+
normalizedNewText +
|
|
229
|
+
baseContent.substring(matchResult.index + matchResult.matchLength);
|
|
230
|
+
// Check if it would actually change anything
|
|
231
|
+
if (baseContent === newContent) {
|
|
232
|
+
return {
|
|
233
|
+
error: `No changes would be made to ${path}. The replacement produces identical content.`,
|
|
234
|
+
};
|
|
235
|
+
}
|
|
236
|
+
// Generate the diff
|
|
237
|
+
return generateDiffString(baseContent, newContent);
|
|
238
|
+
}
|
|
239
|
+
catch (err) {
|
|
240
|
+
return { error: err instanceof Error ? err.message : String(err) };
|
|
241
|
+
}
|
|
242
|
+
}
|
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
import { Type } from "@sinclair/typebox";
|
|
2
|
+
import { constants } from "fs";
|
|
3
|
+
import { access as fsAccess, readFile as fsReadFile, writeFile as fsWriteFile } from "fs/promises";
|
|
4
|
+
import { detectLineEnding, fuzzyFindText, generateDiffString, normalizeForFuzzyMatch, normalizeToLF, restoreLineEndings, stripBom, } from "./edit-diff.js";
|
|
5
|
+
import { resolveToCwd } from "./path-utils.js";
|
|
6
|
+
const editSchema = Type.Object({
|
|
7
|
+
path: Type.String({ description: "Path to the file to edit (relative or absolute)" }),
|
|
8
|
+
oldText: Type.String({ description: "Exact text to find and replace (must match exactly)" }),
|
|
9
|
+
newText: Type.String({ description: "New text to replace the old text with" }),
|
|
10
|
+
});
|
|
11
|
+
const defaultEditOperations = {
|
|
12
|
+
readFile: (path) => fsReadFile(path),
|
|
13
|
+
writeFile: (path, content) => fsWriteFile(path, content, "utf-8"),
|
|
14
|
+
access: (path) => fsAccess(path, constants.R_OK | constants.W_OK),
|
|
15
|
+
};
|
|
16
|
+
export function createEditTool(cwd, options) {
|
|
17
|
+
const ops = options?.operations ?? defaultEditOperations;
|
|
18
|
+
return {
|
|
19
|
+
name: "edit",
|
|
20
|
+
label: "edit",
|
|
21
|
+
description: "Edit a file by replacing exact text. The oldText must match exactly (including whitespace). Use this for precise, surgical edits.",
|
|
22
|
+
parameters: editSchema,
|
|
23
|
+
execute: async (_toolCallId, { path, oldText, newText }, signal) => {
|
|
24
|
+
const absolutePath = resolveToCwd(path, cwd);
|
|
25
|
+
return new Promise((resolve, reject) => {
|
|
26
|
+
// Check if already aborted
|
|
27
|
+
if (signal?.aborted) {
|
|
28
|
+
reject(new Error("Operation aborted"));
|
|
29
|
+
return;
|
|
30
|
+
}
|
|
31
|
+
let aborted = false;
|
|
32
|
+
// Set up abort handler
|
|
33
|
+
const onAbort = () => {
|
|
34
|
+
aborted = true;
|
|
35
|
+
reject(new Error("Operation aborted"));
|
|
36
|
+
};
|
|
37
|
+
if (signal) {
|
|
38
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
39
|
+
}
|
|
40
|
+
// Perform the edit operation
|
|
41
|
+
(async () => {
|
|
42
|
+
try {
|
|
43
|
+
// Check if file exists
|
|
44
|
+
try {
|
|
45
|
+
await ops.access(absolutePath);
|
|
46
|
+
}
|
|
47
|
+
catch {
|
|
48
|
+
if (signal) {
|
|
49
|
+
signal.removeEventListener("abort", onAbort);
|
|
50
|
+
}
|
|
51
|
+
reject(new Error(`File not found: ${path}`));
|
|
52
|
+
return;
|
|
53
|
+
}
|
|
54
|
+
// Check if aborted before reading
|
|
55
|
+
if (aborted) {
|
|
56
|
+
return;
|
|
57
|
+
}
|
|
58
|
+
// Read the file
|
|
59
|
+
const buffer = await ops.readFile(absolutePath);
|
|
60
|
+
const rawContent = buffer.toString("utf-8");
|
|
61
|
+
// Check if aborted after reading
|
|
62
|
+
if (aborted) {
|
|
63
|
+
return;
|
|
64
|
+
}
|
|
65
|
+
// Strip BOM before matching (LLM won't include invisible BOM in oldText)
|
|
66
|
+
const { bom, text: content } = stripBom(rawContent);
|
|
67
|
+
const originalEnding = detectLineEnding(content);
|
|
68
|
+
const normalizedContent = normalizeToLF(content);
|
|
69
|
+
const normalizedOldText = normalizeToLF(oldText);
|
|
70
|
+
const normalizedNewText = normalizeToLF(newText);
|
|
71
|
+
// Find the old text using fuzzy matching (tries exact match first, then fuzzy)
|
|
72
|
+
const matchResult = fuzzyFindText(normalizedContent, normalizedOldText);
|
|
73
|
+
if (!matchResult.found) {
|
|
74
|
+
if (signal) {
|
|
75
|
+
signal.removeEventListener("abort", onAbort);
|
|
76
|
+
}
|
|
77
|
+
reject(new Error(`Could not find the exact text in ${path}. The old text must match exactly including all whitespace and newlines.`));
|
|
78
|
+
return;
|
|
79
|
+
}
|
|
80
|
+
// Count occurrences using fuzzy-normalized content for consistency
|
|
81
|
+
const fuzzyContent = normalizeForFuzzyMatch(normalizedContent);
|
|
82
|
+
const fuzzyOldText = normalizeForFuzzyMatch(normalizedOldText);
|
|
83
|
+
const occurrences = fuzzyContent.split(fuzzyOldText).length - 1;
|
|
84
|
+
if (occurrences > 1) {
|
|
85
|
+
if (signal) {
|
|
86
|
+
signal.removeEventListener("abort", onAbort);
|
|
87
|
+
}
|
|
88
|
+
reject(new Error(`Found ${occurrences} occurrences of the text in ${path}. The text must be unique. Please provide more context to make it unique.`));
|
|
89
|
+
return;
|
|
90
|
+
}
|
|
91
|
+
// Check if aborted before writing
|
|
92
|
+
if (aborted) {
|
|
93
|
+
return;
|
|
94
|
+
}
|
|
95
|
+
// Perform replacement using the matched text position
|
|
96
|
+
// When fuzzy matching was used, contentForReplacement is the normalized version
|
|
97
|
+
const baseContent = matchResult.contentForReplacement;
|
|
98
|
+
const newContent = baseContent.substring(0, matchResult.index) +
|
|
99
|
+
normalizedNewText +
|
|
100
|
+
baseContent.substring(matchResult.index + matchResult.matchLength);
|
|
101
|
+
// Verify the replacement actually changed something
|
|
102
|
+
if (baseContent === newContent) {
|
|
103
|
+
if (signal) {
|
|
104
|
+
signal.removeEventListener("abort", onAbort);
|
|
105
|
+
}
|
|
106
|
+
reject(new Error(`No changes made to ${path}. The replacement produced identical content. This might indicate an issue with special characters or the text not existing as expected.`));
|
|
107
|
+
return;
|
|
108
|
+
}
|
|
109
|
+
const finalContent = bom + restoreLineEndings(newContent, originalEnding);
|
|
110
|
+
await ops.writeFile(absolutePath, finalContent);
|
|
111
|
+
// Check if aborted after writing
|
|
112
|
+
if (aborted) {
|
|
113
|
+
return;
|
|
114
|
+
}
|
|
115
|
+
// Clean up abort handler
|
|
116
|
+
if (signal) {
|
|
117
|
+
signal.removeEventListener("abort", onAbort);
|
|
118
|
+
}
|
|
119
|
+
const diffResult = generateDiffString(baseContent, newContent);
|
|
120
|
+
resolve({
|
|
121
|
+
content: [
|
|
122
|
+
{
|
|
123
|
+
type: "text",
|
|
124
|
+
text: `Successfully replaced text in ${path}.`,
|
|
125
|
+
},
|
|
126
|
+
],
|
|
127
|
+
details: { diff: diffResult.diff, firstChangedLine: diffResult.firstChangedLine },
|
|
128
|
+
});
|
|
129
|
+
}
|
|
130
|
+
catch (error) {
|
|
131
|
+
// Clean up abort handler
|
|
132
|
+
if (signal) {
|
|
133
|
+
signal.removeEventListener("abort", onAbort);
|
|
134
|
+
}
|
|
135
|
+
if (!aborted) {
|
|
136
|
+
reject(error);
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
})();
|
|
140
|
+
});
|
|
141
|
+
},
|
|
142
|
+
};
|
|
143
|
+
}
|
|
144
|
+
/** Default edit tool using process.cwd() - for backwards compatibility */
|
|
145
|
+
export const editTool = createEditTool(process.cwd());
|