ubume 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.
Files changed (182) hide show
  1. package/README.md +88 -0
  2. package/bin/codexa-local-harness-bridge.js +3 -0
  3. package/bin/codexa.js +28 -0
  4. package/bin/ubume-local-harness-bridge.js +325 -0
  5. package/bin/ubume.js +398 -0
  6. package/package.json +66 -0
  7. package/src/app.tsx +5759 -0
  8. package/src/commands/handler.ts +889 -0
  9. package/src/config/appVersion.ts +69 -0
  10. package/src/config/buildInfo.ts +3 -0
  11. package/src/config/launchArgs.ts +196 -0
  12. package/src/config/layeredConfig.ts +853 -0
  13. package/src/config/legacyEnv.ts +16 -0
  14. package/src/config/persistence.ts +377 -0
  15. package/src/config/runtimeConfig.ts +558 -0
  16. package/src/config/settings.ts +405 -0
  17. package/src/config/toml-serialize.ts +109 -0
  18. package/src/config/trustStore.ts +84 -0
  19. package/src/config/updateCheckCache.ts +85 -0
  20. package/src/core/README.md +55 -0
  21. package/src/core/agent/loop.ts +464 -0
  22. package/src/core/agent/protocol.ts +345 -0
  23. package/src/core/agent/tools.ts +423 -0
  24. package/src/core/auth/codexAuth.ts +359 -0
  25. package/src/core/codex/codexExecArgs.ts +166 -0
  26. package/src/core/codex/codexLaunch.ts +163 -0
  27. package/src/core/codex/codexPrompt.ts +429 -0
  28. package/src/core/debug/inputDebug.ts +51 -0
  29. package/src/core/debug/localStreamDebug.ts +50 -0
  30. package/src/core/debug/modelStateDebug.ts +35 -0
  31. package/src/core/executables/antigravityExecutable.ts +48 -0
  32. package/src/core/executables/claudeExecutable.ts +63 -0
  33. package/src/core/executables/codexExecutable.ts +160 -0
  34. package/src/core/executables/executableResolver.ts +164 -0
  35. package/src/core/executables/geminiExecutable.ts +78 -0
  36. package/src/core/models/codexCapabilities.ts +97 -0
  37. package/src/core/models/codexModelCapabilities.ts +624 -0
  38. package/src/core/models/codexModelsCacheSeed.ts +153 -0
  39. package/src/core/models/modelSpecs.ts +303 -0
  40. package/src/core/models/providerModelCache.ts +94 -0
  41. package/src/core/perf/profiler.ts +125 -0
  42. package/src/core/perf/renderDebug.ts +398 -0
  43. package/src/core/process/CommandRunner.ts +280 -0
  44. package/src/core/process/processValidation.ts +111 -0
  45. package/src/core/providerLauncher/launcher.ts +220 -0
  46. package/src/core/providerLauncher/registry.ts +354 -0
  47. package/src/core/providerLauncher/types.ts +95 -0
  48. package/src/core/providerLauncher/workspaceConfig.ts +487 -0
  49. package/src/core/providerRuntime/anthropic.ts +580 -0
  50. package/src/core/providerRuntime/antigravity.ts +500 -0
  51. package/src/core/providerRuntime/capabilityProfile.ts +383 -0
  52. package/src/core/providerRuntime/claudeCodeDiscovery.ts +724 -0
  53. package/src/core/providerRuntime/claudeCodeDiscoveryDebug.ts +55 -0
  54. package/src/core/providerRuntime/codexaCupy.ts +97 -0
  55. package/src/core/providerRuntime/codexaNative.ts +425 -0
  56. package/src/core/providerRuntime/contextMetadata.ts +397 -0
  57. package/src/core/providerRuntime/gemini.ts +789 -0
  58. package/src/core/providerRuntime/lmstudio.ts +118 -0
  59. package/src/core/providerRuntime/local.ts +770 -0
  60. package/src/core/providerRuntime/localHarness/runtime.ts +1090 -0
  61. package/src/core/providerRuntime/localOutputBudget.ts +17 -0
  62. package/src/core/providerRuntime/mistralVibe.ts +667 -0
  63. package/src/core/providerRuntime/models.ts +175 -0
  64. package/src/core/providerRuntime/reasoning.ts +20 -0
  65. package/src/core/providerRuntime/registry.ts +286 -0
  66. package/src/core/providerRuntime/types.ts +142 -0
  67. package/src/core/providerRuntime/unsloth.ts +216 -0
  68. package/src/core/providers/codexJsonStream.ts +305 -0
  69. package/src/core/providers/codexSubprocess.ts +378 -0
  70. package/src/core/providers/codexTranscript.ts +695 -0
  71. package/src/core/providers/openaiNative.ts +13 -0
  72. package/src/core/providers/registry.ts +21 -0
  73. package/src/core/providers/types.ts +91 -0
  74. package/src/core/shared/attachments.ts +101 -0
  75. package/src/core/shared/cleanupFastFail.ts +67 -0
  76. package/src/core/shared/clipboard.ts +24 -0
  77. package/src/core/shared/clipboardImage.ts +111 -0
  78. package/src/core/shared/githubDiagnostics.ts +222 -0
  79. package/src/core/shared/hollowResponseFormat.ts +39 -0
  80. package/src/core/terminal/clearFrameBoundary.ts +852 -0
  81. package/src/core/terminal/frameLock.ts +110 -0
  82. package/src/core/terminal/inkRenderReset.ts +123 -0
  83. package/src/core/terminal/startupClear.ts +20 -0
  84. package/src/core/terminal/terminalCapabilities.ts +100 -0
  85. package/src/core/terminal/terminalControl.ts +169 -0
  86. package/src/core/terminal/terminalSanitize.ts +147 -0
  87. package/src/core/terminal/terminalTitle.ts +400 -0
  88. package/src/core/version/channel.ts +27 -0
  89. package/src/core/version/packageManager.ts +119 -0
  90. package/src/core/version/updateCheck.ts +203 -0
  91. package/src/core/workspace/appData.ts +107 -0
  92. package/src/core/workspace/conversationStore.ts +335 -0
  93. package/src/core/workspace/launchContext.ts +259 -0
  94. package/src/core/workspace/planStorage.ts +135 -0
  95. package/src/core/workspace/projectInstructions.ts +54 -0
  96. package/src/core/workspace/scratchDir.ts +64 -0
  97. package/src/core/workspace/workspaceActivity.ts +384 -0
  98. package/src/core/workspace/workspaceGuard.ts +377 -0
  99. package/src/core/workspace/workspaceRoot.ts +47 -0
  100. package/src/exec.ts +73 -0
  101. package/src/headless/execArgs.ts +296 -0
  102. package/src/headless/execRunner.ts +304 -0
  103. package/src/index.tsx +270 -0
  104. package/src/legacyEnvBootstrap.ts +5 -0
  105. package/src/session/appSession.ts +771 -0
  106. package/src/session/chatLifecycle.ts +994 -0
  107. package/src/session/conversation.ts +107 -0
  108. package/src/session/liveRenderScheduler.ts +214 -0
  109. package/src/session/persistedResponse.ts +93 -0
  110. package/src/session/planFlow.ts +159 -0
  111. package/src/session/planTranscript.ts +19 -0
  112. package/src/session/promptRunSchedule.ts +26 -0
  113. package/src/session/types.ts +234 -0
  114. package/src/test/runtimeTestUtils.ts +14 -0
  115. package/src/types/react-dom.d.ts +3 -0
  116. package/src/ui/chrome/ActivityBars.tsx +68 -0
  117. package/src/ui/chrome/ActivityIndicator.tsx +58 -0
  118. package/src/ui/chrome/AnimatedStatusText.tsx +69 -0
  119. package/src/ui/chrome/AppShell.tsx +474 -0
  120. package/src/ui/chrome/BottomComposer.tsx +1135 -0
  121. package/src/ui/chrome/DashCard.tsx +82 -0
  122. package/src/ui/chrome/RunFooter.tsx +65 -0
  123. package/src/ui/chrome/RuntimeStatusBar.tsx +108 -0
  124. package/src/ui/chrome/Spinner.tsx +25 -0
  125. package/src/ui/chrome/TopHeader.tsx +439 -0
  126. package/src/ui/chrome/UpdateAvailableCard.tsx +42 -0
  127. package/src/ui/chrome/busyStatusAnimation.ts +11 -0
  128. package/src/ui/input/commandNormalize.ts +66 -0
  129. package/src/ui/input/focus.ts +73 -0
  130. package/src/ui/input/imageAttachments.ts +18 -0
  131. package/src/ui/input/inputBuffer.ts +203 -0
  132. package/src/ui/input/pastedContent.ts +75 -0
  133. package/src/ui/input/rawArrowKeys.ts +28 -0
  134. package/src/ui/input/slashCommands.ts +43 -0
  135. package/src/ui/input/useStdinRawModeLease.ts +23 -0
  136. package/src/ui/layout.ts +560 -0
  137. package/src/ui/panels/AttachmentImportPanel.tsx +131 -0
  138. package/src/ui/panels/AuthPanel.tsx +149 -0
  139. package/src/ui/panels/BackendPicker.tsx +28 -0
  140. package/src/ui/panels/ModePicker.tsx +31 -0
  141. package/src/ui/panels/ModelPicker.tsx +31 -0
  142. package/src/ui/panels/ModelPickerScreen.tsx +761 -0
  143. package/src/ui/panels/ModelReasoningPicker.tsx +458 -0
  144. package/src/ui/panels/Panel.tsx +51 -0
  145. package/src/ui/panels/PermissionsPanel.tsx +78 -0
  146. package/src/ui/panels/PlanActionPicker.tsx +187 -0
  147. package/src/ui/panels/ProviderPicker.tsx +753 -0
  148. package/src/ui/panels/ProviderSetupPrompt.tsx +52 -0
  149. package/src/ui/panels/ReasoningPicker.tsx +46 -0
  150. package/src/ui/panels/ResumePicker.tsx +90 -0
  151. package/src/ui/panels/SelectionPanel.tsx +138 -0
  152. package/src/ui/panels/SettingsPanel.tsx +156 -0
  153. package/src/ui/panels/TextEntryPanel.tsx +139 -0
  154. package/src/ui/panels/ThemePicker.tsx +32 -0
  155. package/src/ui/panels/ToolApprovalPanel.tsx +46 -0
  156. package/src/ui/panels/UpdatePromptPanel.tsx +236 -0
  157. package/src/ui/panels/responsivePickerViewport.ts +64 -0
  158. package/src/ui/render/Markdown.tsx +331 -0
  159. package/src/ui/render/diffRenderer.ts +116 -0
  160. package/src/ui/render/logoVariants.ts +113 -0
  161. package/src/ui/render/modeDisplay.ts +52 -0
  162. package/src/ui/render/outputPipeline.ts +64 -0
  163. package/src/ui/render/runtimeDisplay.ts +128 -0
  164. package/src/ui/render/terminalAnswerFormat.ts +128 -0
  165. package/src/ui/render/textLayout.ts +392 -0
  166. package/src/ui/theme.tsx +274 -0
  167. package/src/ui/themeFlow.ts +41 -0
  168. package/src/ui/timeline/ActionRequiredBlock.tsx +38 -0
  169. package/src/ui/timeline/AgentBlock.tsx +130 -0
  170. package/src/ui/timeline/StaticIntroItem.tsx +54 -0
  171. package/src/ui/timeline/ThinkingBlock.tsx +100 -0
  172. package/src/ui/timeline/Timeline.tsx +1410 -0
  173. package/src/ui/timeline/TranscriptShell.tsx +302 -0
  174. package/src/ui/timeline/TurnGroup.tsx +673 -0
  175. package/src/ui/timeline/layoutListWindow.ts +145 -0
  176. package/src/ui/timeline/liveViewportWindow.ts +68 -0
  177. package/src/ui/timeline/progressEntries.ts +156 -0
  178. package/src/ui/timeline/runActivityView.ts +37 -0
  179. package/src/ui/timeline/staticTranscriptCache.ts +174 -0
  180. package/src/ui/timeline/streamCoalesce.ts +53 -0
  181. package/src/ui/timeline/timelineMeasure.ts +3273 -0
  182. package/src/ui/useThrottledValue.ts +31 -0
@@ -0,0 +1,423 @@
1
+ import { existsSync } from "node:fs";
2
+ import { mkdir, readdir, readFile, rm, stat, writeFile } from "node:fs/promises";
3
+ import path from "node:path";
4
+ import type { ResolvedRuntimeConfig } from "../../config/runtimeConfig.js";
5
+ import { runShellCommand, summarizeCommandResult } from "../process/CommandRunner.js";
6
+ import { sanitizeTerminalOutput } from "../terminal/terminalSanitize.js";
7
+ import {
8
+ getShellWorkspaceGuardMessage,
9
+ isPathInsideAllowedRoots,
10
+ resolveWorkspacePath,
11
+ } from "../workspace/workspaceGuard.js";
12
+ import type { AgentToolName } from "./protocol.js";
13
+
14
+ export interface AgentToolContext {
15
+ workspaceRoot: string;
16
+ runtime: ResolvedRuntimeConfig;
17
+ signal?: AbortSignal;
18
+ }
19
+
20
+ export interface AgentToolResult {
21
+ success: boolean;
22
+ tool: AgentToolName;
23
+ path?: string;
24
+ command?: string;
25
+ paths?: string[];
26
+ output?: string;
27
+ stdout?: string;
28
+ stderr?: string;
29
+ exitCode?: number | null;
30
+ durationMs?: number;
31
+ summary?: string;
32
+ error?: string;
33
+ }
34
+
35
+ const MAX_FILE_BYTES = 128 * 1024;
36
+ const MAX_OUTPUT_CHARS = 4_000;
37
+ const MAX_OUTPUT_LINES = 80;
38
+ const SHELL_TIMEOUT_MS = 120_000;
39
+
40
+ const DANGEROUS_SHELL_PATTERNS: RegExp[] = [
41
+ /\brm\s+-[^\n;|&]*r[f]?\b/i,
42
+ /\bsudo\b/i,
43
+ /\bdoas\b/i,
44
+ /\bdd\s+.*\bof=/i,
45
+ /\bmkfs(?:\.[a-z0-9]+)?\b/i,
46
+ /\bshutdown\b/i,
47
+ /\breboot\b/i,
48
+ /\bpoweroff\b/i,
49
+ /\bchmod\s+-R\s+777\b/i,
50
+ /:\(\)\s*\{\s*:\|:\s*&\s*\}\s*;/,
51
+ />\s*\/dev\/(?:sd|hd|nvme|disk)/i,
52
+ ];
53
+
54
+ export function isDangerousShellCommand(command: string): boolean {
55
+ return DANGEROUS_SHELL_PATTERNS.some((pattern) => pattern.test(command));
56
+ }
57
+
58
+ function preview(text: string, maxChars = MAX_OUTPUT_CHARS): string {
59
+ const sanitized = sanitizeTerminalOutput(text);
60
+ return sanitized.length > maxChars ? `${sanitized.slice(0, maxChars)}\n...[truncated]` : sanitized;
61
+ }
62
+
63
+ function trimOutputLines(text: string, preferTail: boolean): string {
64
+ const sanitized = sanitizeTerminalOutput(text).replace(/\r\n/g, "\n").replace(/\r/g, "\n");
65
+ const lines = sanitized.split("\n");
66
+ if (lines.at(-1) === "") lines.pop();
67
+ if (lines.length <= MAX_OUTPUT_LINES) return sanitized;
68
+ const visible = preferTail ? lines.slice(-MAX_OUTPUT_LINES) : lines.slice(0, MAX_OUTPUT_LINES);
69
+ const hidden = lines.length - visible.length;
70
+ const marker = `[...${hidden} line${hidden === 1 ? "" : "s"} truncated; showing ${preferTail ? "last" : "first"} ${MAX_OUTPUT_LINES} lines...]`;
71
+ return preferTail
72
+ ? [marker, ...visible].join("\n")
73
+ : [...visible, marker].join("\n");
74
+ }
75
+
76
+ function stringArg(args: Record<string, unknown>, key: string): string | null {
77
+ const value = args[key];
78
+ return typeof value === "string" && value.trim() ? value : null;
79
+ }
80
+
81
+ function isReadOnly(runtime: ResolvedRuntimeConfig): boolean {
82
+ return runtime.policy.sandboxMode === "read-only";
83
+ }
84
+
85
+ function canWrite(runtime: ResolvedRuntimeConfig): boolean {
86
+ return runtime.policy.sandboxMode === "workspace-write"
87
+ || runtime.policy.sandboxMode === "danger-full-access";
88
+ }
89
+
90
+ function relativeDisplay(workspaceRoot: string, absolutePath: string): string {
91
+ const relative = path.relative(workspaceRoot, absolutePath).split(path.sep).join("/");
92
+ return relative || ".";
93
+ }
94
+
95
+ function hasCargoManifest(workspaceRoot: string): boolean {
96
+ return existsSync(path.join(workspaceRoot, "Cargo.toml"));
97
+ }
98
+
99
+ function rustCommandGuard(command: string, context: AgentToolContext): string | null {
100
+ if (!hasCargoManifest(context.workspaceRoot)) return null;
101
+ const normalized = command.trim().replace(/\s+/g, " ");
102
+ const tokens = normalized.split(" ");
103
+ if (tokens[0] !== "rustc") return null;
104
+
105
+ let targetIndex = 1;
106
+ while (tokens[targetIndex]?.startsWith("-")) targetIndex += 1;
107
+ const target = tokens[targetIndex];
108
+ if (!target?.endsWith(".rs")) return null;
109
+
110
+ const resolved = path.resolve(context.workspaceRoot, target);
111
+ const rootMain = path.join(context.workspaceRoot, "main.rs");
112
+ if (resolved !== rootMain || !existsSync(rootMain)) {
113
+ return "This workspace has Cargo.toml. Use `cargo check` to validate or `cargo run` to run instead of compiling a Rust source file directly with rustc.";
114
+ }
115
+ return null;
116
+ }
117
+
118
+ function resolveAllowedPath(rawPath: string, context: AgentToolContext): { ok: true; absolutePath: string; relativePath: string } | { ok: false; error: string } {
119
+ if (!isPathInsideAllowedRoots(rawPath, context.workspaceRoot, context.runtime.policy.writableRoots)) {
120
+ return { ok: false, error: `Path is outside the workspace: ${rawPath}` };
121
+ }
122
+ const absolutePath = resolveWorkspacePath(rawPath, context.workspaceRoot);
123
+ return {
124
+ ok: true,
125
+ absolutePath,
126
+ relativePath: relativeDisplay(context.workspaceRoot, absolutePath),
127
+ };
128
+ }
129
+
130
+ async function listFiles(args: Record<string, unknown>, context: AgentToolContext): Promise<AgentToolResult> {
131
+ const rawPath = stringArg(args, "path") ?? ".";
132
+ const resolved = resolveAllowedPath(rawPath, context);
133
+ if (!resolved.ok) return { success: false, tool: "list_files", path: rawPath, error: resolved.error };
134
+
135
+ const entries = await readdir(resolved.absolutePath, { withFileTypes: true });
136
+ const names = entries
137
+ .filter((entry) => ![".git", "node_modules", "dist", "build", "coverage"].includes(entry.name))
138
+ .map((entry) => `${entry.name}${entry.isDirectory() ? "/" : ""}`)
139
+ .sort();
140
+ return {
141
+ success: true,
142
+ tool: "list_files",
143
+ path: resolved.relativePath,
144
+ output: names.slice(0, 200).join("\n"),
145
+ summary: `Listed ${names.length} item${names.length === 1 ? "" : "s"}.`,
146
+ };
147
+ }
148
+
149
+ async function readFileTool(args: Record<string, unknown>, context: AgentToolContext): Promise<AgentToolResult> {
150
+ const rawPath = stringArg(args, "path");
151
+ if (!rawPath) return { success: false, tool: "read_file", error: "Missing path." };
152
+ const resolved = resolveAllowedPath(rawPath, context);
153
+ if (!resolved.ok) return { success: false, tool: "read_file", path: rawPath, error: resolved.error };
154
+
155
+ const fileStat = await stat(resolved.absolutePath);
156
+ if (fileStat.size > MAX_FILE_BYTES) {
157
+ return { success: false, tool: "read_file", path: resolved.relativePath, error: "File is too large to read through the agent tool." };
158
+ }
159
+ const content = await readFile(resolved.absolutePath, "utf8");
160
+ return {
161
+ success: true,
162
+ tool: "read_file",
163
+ path: resolved.relativePath,
164
+ output: content,
165
+ summary: `Read ${resolved.relativePath}.`,
166
+ };
167
+ }
168
+
169
+ async function writeFileTool(args: Record<string, unknown>, context: AgentToolContext): Promise<AgentToolResult> {
170
+ if (!canWrite(context.runtime)) {
171
+ return { success: false, tool: "write_file", error: "write_file is blocked by read-only runtime policy." };
172
+ }
173
+ const rawPath = stringArg(args, "path");
174
+ const content = stringArg(args, "content");
175
+ if (!rawPath) return { success: false, tool: "write_file", error: "Missing path." };
176
+ if (content === null) return { success: false, tool: "write_file", path: rawPath, error: "Missing content." };
177
+ const resolved = resolveAllowedPath(rawPath, context);
178
+ if (!resolved.ok) return { success: false, tool: "write_file", path: rawPath, error: resolved.error };
179
+
180
+ await mkdir(path.dirname(resolved.absolutePath), { recursive: true });
181
+ await writeFile(resolved.absolutePath, content, "utf8");
182
+ return {
183
+ success: true,
184
+ tool: "write_file",
185
+ path: resolved.relativePath,
186
+ paths: [resolved.relativePath],
187
+ summary: `Wrote ${resolved.relativePath}.`,
188
+ };
189
+ }
190
+
191
+ function parseApplyPatchPaths(patch: string): string[] {
192
+ const paths: string[] = [];
193
+ for (const line of patch.split(/\r?\n/)) {
194
+ const marker = /^(?:\*\*\* (?:Add|Update|Delete) File:|--- a\/|\+\+\+ b\/)\s*(.+)$/.exec(line);
195
+ if (marker?.[1] && marker[1] !== "/dev/null") {
196
+ paths.push(marker[1].trim());
197
+ }
198
+ }
199
+ return [...new Set(paths)];
200
+ }
201
+
202
+ function applyPatchFormatToContent(before: string, patchLines: string[]): string {
203
+ let contentLines = before.replace(/\r\n/g, "\n").replace(/\r/g, "\n").split("\n");
204
+ if (contentLines.at(-1) === "") contentLines = contentLines.slice(0, -1);
205
+ let cursor = 0;
206
+ let index = 0;
207
+
208
+ while (index < patchLines.length) {
209
+ if (!patchLines[index]?.startsWith("@@")) {
210
+ index += 1;
211
+ continue;
212
+ }
213
+ index += 1;
214
+ const oldLines: string[] = [];
215
+ const newLines: string[] = [];
216
+ while (index < patchLines.length && !patchLines[index]?.startsWith("@@") && !patchLines[index]?.startsWith("*** ")) {
217
+ const line = patchLines[index] ?? "";
218
+ if (line.startsWith(" ")) {
219
+ oldLines.push(line.slice(1));
220
+ newLines.push(line.slice(1));
221
+ } else if (line.startsWith("-")) {
222
+ oldLines.push(line.slice(1));
223
+ } else if (line.startsWith("+")) {
224
+ newLines.push(line.slice(1));
225
+ }
226
+ index += 1;
227
+ }
228
+
229
+ let matchAt = -1;
230
+ for (let candidate = cursor; candidate <= contentLines.length - oldLines.length; candidate += 1) {
231
+ const matches = oldLines.every((line, offset) => contentLines[candidate + offset] === line);
232
+ if (matches) {
233
+ matchAt = candidate;
234
+ break;
235
+ }
236
+ }
237
+ if (matchAt < 0) {
238
+ throw new Error("Patch context did not match the target file.");
239
+ }
240
+ contentLines.splice(matchAt, oldLines.length, ...newLines);
241
+ cursor = matchAt + newLines.length;
242
+ }
243
+
244
+ return `${contentLines.join("\n")}\n`;
245
+ }
246
+
247
+ async function applyPatchFormat(patch: string, context: AgentToolContext): Promise<AgentToolResult> {
248
+ const lines = patch.split(/\r?\n/);
249
+ const changedPaths: string[] = [];
250
+ let index = 0;
251
+
252
+ while (index < lines.length) {
253
+ const add = /^\*\*\* Add File:\s*(.+)$/.exec(lines[index] ?? "");
254
+ const update = /^\*\*\* Update File:\s*(.+)$/.exec(lines[index] ?? "");
255
+ const del = /^\*\*\* Delete File:\s*(.+)$/.exec(lines[index] ?? "");
256
+
257
+ if (add) {
258
+ const resolved = resolveAllowedPath(add[1]!, context);
259
+ if (!resolved.ok) return { success: false, tool: "apply_patch", path: add[1], error: resolved.error };
260
+ index += 1;
261
+ const content: string[] = [];
262
+ while (index < lines.length && !lines[index]?.startsWith("*** ")) {
263
+ const line = lines[index] ?? "";
264
+ if (line.startsWith("+")) content.push(line.slice(1));
265
+ index += 1;
266
+ }
267
+ await mkdir(path.dirname(resolved.absolutePath), { recursive: true });
268
+ await writeFile(resolved.absolutePath, `${content.join("\n")}\n`, "utf8");
269
+ changedPaths.push(resolved.relativePath);
270
+ continue;
271
+ }
272
+
273
+ if (update) {
274
+ const resolved = resolveAllowedPath(update[1]!, context);
275
+ if (!resolved.ok) return { success: false, tool: "apply_patch", path: update[1], error: resolved.error };
276
+ index += 1;
277
+ const patchLines: string[] = [];
278
+ while (index < lines.length && !/^\*\*\* (?:Add|Update|Delete|End)/.test(lines[index] ?? "")) {
279
+ patchLines.push(lines[index] ?? "");
280
+ index += 1;
281
+ }
282
+ const before = await readFile(resolved.absolutePath, "utf8");
283
+ await writeFile(resolved.absolutePath, applyPatchFormatToContent(before, patchLines), "utf8");
284
+ changedPaths.push(resolved.relativePath);
285
+ continue;
286
+ }
287
+
288
+ if (del) {
289
+ const resolved = resolveAllowedPath(del[1]!, context);
290
+ if (!resolved.ok) return { success: false, tool: "apply_patch", path: del[1], error: resolved.error };
291
+ await rm(resolved.absolutePath, { force: true });
292
+ changedPaths.push(resolved.relativePath);
293
+ index += 1;
294
+ continue;
295
+ }
296
+
297
+ index += 1;
298
+ }
299
+
300
+ if (changedPaths.length === 0) {
301
+ return { success: false, tool: "apply_patch", error: "No supported patch operations were found." };
302
+ }
303
+
304
+ return {
305
+ success: true,
306
+ tool: "apply_patch",
307
+ paths: changedPaths,
308
+ summary: `Patched ${changedPaths.join(", ")}.`,
309
+ };
310
+ }
311
+
312
+ async function applyPatchTool(args: Record<string, unknown>, context: AgentToolContext): Promise<AgentToolResult> {
313
+ if (!canWrite(context.runtime)) {
314
+ return { success: false, tool: "apply_patch", error: "apply_patch is blocked by read-only runtime policy." };
315
+ }
316
+ const patch = stringArg(args, "patch");
317
+ if (!patch) return { success: false, tool: "apply_patch", error: "Missing patch." };
318
+
319
+ const explicitPath = stringArg(args, "path");
320
+ const paths = explicitPath ? [explicitPath] : parseApplyPatchPaths(patch);
321
+ for (const patchPath of paths) {
322
+ const resolved = resolveAllowedPath(patchPath, context);
323
+ if (!resolved.ok) return { success: false, tool: "apply_patch", path: patchPath, error: resolved.error };
324
+ }
325
+
326
+ if (!patch.trimStart().startsWith("*** Begin Patch")) {
327
+ return { success: false, tool: "apply_patch", error: "Only *** Begin Patch format is supported by this agent tool." };
328
+ }
329
+
330
+ return applyPatchFormat(patch, context);
331
+ }
332
+
333
+ async function runShellTool(args: Record<string, unknown>, context: AgentToolContext): Promise<AgentToolResult> {
334
+ if (!canWrite(context.runtime) || isReadOnly(context.runtime)) {
335
+ return { success: false, tool: "run_shell", error: "run_shell is blocked by read-only runtime policy." };
336
+ }
337
+ const command = stringArg(args, "command");
338
+ if (!command) return { success: false, tool: "run_shell", error: "Missing command." };
339
+
340
+ if (isDangerousShellCommand(command)) {
341
+ return { success: false, tool: "run_shell", command, error: "Shell command blocked as dangerous." };
342
+ }
343
+ const rustGuard = rustCommandGuard(command, context);
344
+ if (rustGuard) {
345
+ return { success: false, tool: "run_shell", command, exitCode: null, durationMs: 0, stdout: "", stderr: "", error: rustGuard };
346
+ }
347
+ const workspaceGuard = getShellWorkspaceGuardMessage(command, context.workspaceRoot, context.runtime.policy.writableRoots);
348
+ if (workspaceGuard) {
349
+ return { success: false, tool: "run_shell", command, error: workspaceGuard };
350
+ }
351
+
352
+ const runner = runShellCommand(command, {
353
+ cwd: context.workspaceRoot,
354
+ timeoutMs: SHELL_TIMEOUT_MS,
355
+ });
356
+ const cancel = () => runner.cancel();
357
+ context.signal?.addEventListener("abort", cancel, { once: true });
358
+ try {
359
+ const result = await runner.result;
360
+ const success = result.status === "completed" && result.exitCode === 0;
361
+ const stdout = trimOutputLines(result.stdout, !success);
362
+ const stderr = trimOutputLines(result.stderr, !success);
363
+ const output = preview([stdout, stderr].filter(Boolean).join("\n"));
364
+ return {
365
+ success,
366
+ tool: "run_shell",
367
+ command,
368
+ exitCode: result.exitCode,
369
+ durationMs: result.durationMs,
370
+ stdout,
371
+ stderr,
372
+ output,
373
+ summary: summarizeCommandResult(command, result),
374
+ error: success ? undefined : result.userMessage,
375
+ };
376
+ } finally {
377
+ context.signal?.removeEventListener("abort", cancel);
378
+ }
379
+ }
380
+
381
+ async function getWorkspaceInfo(context: AgentToolContext): Promise<AgentToolResult> {
382
+ return {
383
+ success: true,
384
+ tool: "get_workspace_info",
385
+ path: ".",
386
+ output: JSON.stringify({
387
+ workspaceRoot: context.workspaceRoot,
388
+ sandboxMode: context.runtime.policy.sandboxMode,
389
+ writableRoots: context.runtime.policy.writableRoots,
390
+ packageJson: existsSync(path.join(context.workspaceRoot, "package.json")),
391
+ }),
392
+ summary: "Returned workspace info.",
393
+ };
394
+ }
395
+
396
+ export async function executeAgentTool(
397
+ name: AgentToolName,
398
+ args: Record<string, unknown>,
399
+ context: AgentToolContext,
400
+ ): Promise<AgentToolResult> {
401
+ try {
402
+ switch (name) {
403
+ case "list_files":
404
+ return await listFiles(args, context);
405
+ case "read_file":
406
+ return await readFileTool(args, context);
407
+ case "write_file":
408
+ return await writeFileTool(args, context);
409
+ case "apply_patch":
410
+ return await applyPatchTool(args, context);
411
+ case "run_shell":
412
+ return await runShellTool(args, context);
413
+ case "get_workspace_info":
414
+ return await getWorkspaceInfo(context);
415
+ }
416
+ } catch (error) {
417
+ return {
418
+ success: false,
419
+ tool: name,
420
+ error: error instanceof Error ? error.message : String(error),
421
+ };
422
+ }
423
+ }