@di-code/coding-agent 0.1.7 → 0.1.8

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 (333) hide show
  1. package/README.md +104 -46
  2. package/compositions/base.yml +54 -0
  3. package/compositions/interactive.yml +14 -0
  4. package/compositions/json.yml +6 -0
  5. package/compositions/print.yml +5 -0
  6. package/compositions/rpc.yml +12 -0
  7. package/compositions/webui.yml +9 -0
  8. package/dist/cli.d.ts +22 -1
  9. package/dist/cli.d.ts.map +1 -1
  10. package/dist/cli.js +97 -3
  11. package/dist/cli.js.map +1 -1
  12. package/dist/composition-loader-entry.d.ts +11 -0
  13. package/dist/composition-loader-entry.d.ts.map +1 -0
  14. package/dist/composition-loader-entry.js +12 -0
  15. package/dist/composition-loader-entry.js.map +1 -0
  16. package/dist/compositions.d.ts +32 -0
  17. package/dist/compositions.d.ts.map +1 -0
  18. package/dist/compositions.js +173 -0
  19. package/dist/compositions.js.map +1 -0
  20. package/dist/core/session/session-manager.d.ts +9 -2
  21. package/dist/core/session/session-manager.d.ts.map +1 -1
  22. package/dist/core/session/session-manager.js +28 -0
  23. package/dist/core/session/session-manager.js.map +1 -1
  24. package/dist/core/session/session-storage.d.ts.map +1 -1
  25. package/dist/core/session/session-storage.js +20 -3
  26. package/dist/core/session/session-storage.js.map +1 -1
  27. package/dist/core/session/types.d.ts +11 -2
  28. package/dist/core/session/types.d.ts.map +1 -1
  29. package/dist/core/session/types.js.map +1 -1
  30. package/dist/core/session-tools.d.ts +5 -0
  31. package/dist/core/session-tools.d.ts.map +1 -0
  32. package/dist/core/session-tools.js +17 -0
  33. package/dist/core/session-tools.js.map +1 -0
  34. package/dist/core/session.d.ts +19 -7
  35. package/dist/core/session.d.ts.map +1 -1
  36. package/dist/core/session.js +71 -39
  37. package/dist/core/session.js.map +1 -1
  38. package/dist/core/tools/bash.d.ts +1 -38
  39. package/dist/core/tools/bash.d.ts.map +1 -1
  40. package/dist/core/tools/bash.js +1 -207
  41. package/dist/core/tools/bash.js.map +1 -1
  42. package/dist/core/tools/edit-diff.d.ts +1 -24
  43. package/dist/core/tools/edit-diff.d.ts.map +1 -1
  44. package/dist/core/tools/edit-diff.js +1 -135
  45. package/dist/core/tools/edit-diff.js.map +1 -1
  46. package/dist/core/tools/edit.d.ts +1 -26
  47. package/dist/core/tools/edit.d.ts.map +1 -1
  48. package/dist/core/tools/edit.js +1 -140
  49. package/dist/core/tools/edit.js.map +1 -1
  50. package/dist/core/tools/file-mutation-queue.d.ts +1 -1
  51. package/dist/core/tools/file-mutation-queue.d.ts.map +1 -1
  52. package/dist/core/tools/file-mutation-queue.js +1 -23
  53. package/dist/core/tools/file-mutation-queue.js.map +1 -1
  54. package/dist/core/tools/file-search.d.ts +1 -13
  55. package/dist/core/tools/file-search.d.ts.map +1 -1
  56. package/dist/core/tools/file-search.js +1 -98
  57. package/dist/core/tools/file-search.js.map +1 -1
  58. package/dist/core/tools/glob.d.ts +1 -10
  59. package/dist/core/tools/glob.d.ts.map +1 -1
  60. package/dist/core/tools/glob.js +1 -43
  61. package/dist/core/tools/glob.js.map +1 -1
  62. package/dist/core/tools/grep.d.ts +1 -12
  63. package/dist/core/tools/grep.d.ts.map +1 -1
  64. package/dist/core/tools/grep.js +1 -66
  65. package/dist/core/tools/grep.js.map +1 -1
  66. package/dist/core/tools/load-skill.d.ts +1 -9
  67. package/dist/core/tools/load-skill.d.ts.map +1 -1
  68. package/dist/core/tools/load-skill.js +1 -21
  69. package/dist/core/tools/load-skill.js.map +1 -1
  70. package/dist/core/tools/path-boundary.d.ts +1 -4
  71. package/dist/core/tools/path-boundary.d.ts.map +1 -1
  72. package/dist/core/tools/path-boundary.js +1 -65
  73. package/dist/core/tools/path-boundary.js.map +1 -1
  74. package/dist/core/tools/read.d.ts +1 -16
  75. package/dist/core/tools/read.d.ts.map +1 -1
  76. package/dist/core/tools/read.js +1 -131
  77. package/dist/core/tools/read.js.map +1 -1
  78. package/dist/core/tools/write.d.ts +1 -16
  79. package/dist/core/tools/write.d.ts.map +1 -1
  80. package/dist/core/tools/write.js +1 -44
  81. package/dist/core/tools/write.js.map +1 -1
  82. package/dist/entry.js +30 -28
  83. package/dist/entry.js.map +1 -1
  84. package/dist/index.d.ts +6 -3
  85. package/dist/index.d.ts.map +1 -1
  86. package/dist/index.js +6 -3
  87. package/dist/index.js.map +1 -1
  88. package/dist/interactive/builtin.d.ts +17 -0
  89. package/dist/interactive/builtin.d.ts.map +1 -0
  90. package/dist/interactive/builtin.js +47 -0
  91. package/dist/interactive/builtin.js.map +1 -0
  92. package/dist/interactive/controller.d.ts +85 -0
  93. package/dist/interactive/controller.d.ts.map +1 -0
  94. package/dist/interactive/controller.js +211 -0
  95. package/dist/interactive/controller.js.map +1 -0
  96. package/dist/interactive/index.d.ts +3 -0
  97. package/dist/interactive/index.d.ts.map +1 -0
  98. package/dist/interactive/index.js +3 -0
  99. package/dist/interactive/index.js.map +1 -0
  100. package/dist/interactive-host-entry.d.ts +7 -0
  101. package/dist/interactive-host-entry.d.ts.map +1 -0
  102. package/dist/interactive-host-entry.js +123 -0
  103. package/dist/interactive-host-entry.js.map +1 -0
  104. package/dist/interactive-profile.d.ts +18 -0
  105. package/dist/interactive-profile.d.ts.map +1 -0
  106. package/dist/interactive-profile.js +290 -0
  107. package/dist/interactive-profile.js.map +1 -0
  108. package/dist/interactive-resources-entry.d.ts +7 -0
  109. package/dist/interactive-resources-entry.d.ts.map +1 -0
  110. package/dist/interactive-resources-entry.js +42 -0
  111. package/dist/interactive-resources-entry.js.map +1 -0
  112. package/dist/legacy-main.d.ts +39 -0
  113. package/dist/legacy-main.d.ts.map +1 -0
  114. package/dist/legacy-main.js +611 -0
  115. package/dist/legacy-main.js.map +1 -0
  116. package/dist/main.d.ts +15 -34
  117. package/dist/main.d.ts.map +1 -1
  118. package/dist/main.js +130 -518
  119. package/dist/main.js.map +1 -1
  120. package/dist/mcp/entries.d.ts +42 -0
  121. package/dist/mcp/entries.d.ts.map +1 -0
  122. package/dist/mcp/entries.js +98 -0
  123. package/dist/mcp/entries.js.map +1 -0
  124. package/dist/mcp-client-entry.d.ts +5 -0
  125. package/dist/mcp-client-entry.d.ts.map +1 -0
  126. package/dist/mcp-client-entry.js +6 -0
  127. package/dist/mcp-client-entry.js.map +1 -0
  128. package/dist/mcp-config-entry.d.ts +5 -0
  129. package/dist/mcp-config-entry.d.ts.map +1 -0
  130. package/dist/mcp-config-entry.js +6 -0
  131. package/dist/mcp-config-entry.js.map +1 -0
  132. package/dist/mcp-tools-entry.d.ts +5 -0
  133. package/dist/mcp-tools-entry.d.ts.map +1 -0
  134. package/dist/mcp-tools-entry.js +6 -0
  135. package/dist/mcp-tools-entry.js.map +1 -0
  136. package/dist/mcp-transport-entry.d.ts +5 -0
  137. package/dist/mcp-transport-entry.d.ts.map +1 -0
  138. package/dist/mcp-transport-entry.js +6 -0
  139. package/dist/mcp-transport-entry.js.map +1 -0
  140. package/dist/modes/interactive-entry.d.ts +18 -0
  141. package/dist/modes/interactive-entry.d.ts.map +1 -0
  142. package/dist/modes/interactive-entry.js +21 -0
  143. package/dist/modes/interactive-entry.js.map +1 -0
  144. package/dist/modes/interactive.d.ts +16 -6
  145. package/dist/modes/interactive.d.ts.map +1 -1
  146. package/dist/modes/interactive.js +81 -32
  147. package/dist/modes/interactive.js.map +1 -1
  148. package/dist/modes/json-entry.d.ts +13 -0
  149. package/dist/modes/json-entry.d.ts.map +1 -0
  150. package/dist/modes/json-entry.js +14 -0
  151. package/dist/modes/json-entry.js.map +1 -0
  152. package/dist/modes/json.d.ts +4 -1
  153. package/dist/modes/json.d.ts.map +1 -1
  154. package/dist/modes/json.js +3 -3
  155. package/dist/modes/json.js.map +1 -1
  156. package/dist/modes/print-entry.d.ts +10 -0
  157. package/dist/modes/print-entry.d.ts.map +1 -0
  158. package/dist/modes/print-entry.js +11 -0
  159. package/dist/modes/print-entry.js.map +1 -0
  160. package/dist/modes/tree-selector.d.ts.map +1 -1
  161. package/dist/modes/tree-selector.js +4 -0
  162. package/dist/modes/tree-selector.js.map +1 -1
  163. package/dist/plugin-dump-composition.d.ts +6 -0
  164. package/dist/plugin-dump-composition.d.ts.map +1 -0
  165. package/dist/plugin-dump-composition.js +7 -0
  166. package/dist/plugin-dump-composition.js.map +1 -0
  167. package/dist/plugin-inventory.d.ts +7 -0
  168. package/dist/plugin-inventory.d.ts.map +1 -0
  169. package/dist/plugin-inventory.js +8 -0
  170. package/dist/plugin-inventory.js.map +1 -0
  171. package/dist/plugin-manager.d.ts +6 -0
  172. package/dist/plugin-manager.d.ts.map +1 -0
  173. package/dist/plugin-manager.js +7 -0
  174. package/dist/plugin-manager.js.map +1 -0
  175. package/dist/plugin-trace.d.ts +6 -0
  176. package/dist/plugin-trace.d.ts.map +1 -0
  177. package/dist/plugin-trace.js +7 -0
  178. package/dist/plugin-trace.js.map +1 -0
  179. package/dist/plugins/dynamic-broker.d.ts +76 -0
  180. package/dist/plugins/dynamic-broker.d.ts.map +1 -0
  181. package/dist/plugins/dynamic-broker.js +852 -0
  182. package/dist/plugins/dynamic-broker.js.map +1 -0
  183. package/dist/plugins/profile.d.ts +15 -0
  184. package/dist/plugins/profile.d.ts.map +1 -0
  185. package/dist/plugins/profile.js +34 -0
  186. package/dist/plugins/profile.js.map +1 -0
  187. package/dist/plugins/runtime-host.d.ts +37 -0
  188. package/dist/plugins/runtime-host.d.ts.map +1 -0
  189. package/dist/plugins/runtime-host.js +95 -0
  190. package/dist/plugins/runtime-host.js.map +1 -0
  191. package/dist/plugins/trust.d.ts +8 -0
  192. package/dist/plugins/trust.d.ts.map +1 -0
  193. package/dist/plugins/trust.js +59 -0
  194. package/dist/plugins/trust.js.map +1 -0
  195. package/dist/project-trust-entry.d.ts +15 -0
  196. package/dist/project-trust-entry.d.ts.map +1 -0
  197. package/dist/project-trust-entry.js +15 -0
  198. package/dist/project-trust-entry.js.map +1 -0
  199. package/dist/rpc/client.d.ts +78 -6
  200. package/dist/rpc/client.d.ts.map +1 -1
  201. package/dist/rpc/client.js +172 -4
  202. package/dist/rpc/client.js.map +1 -1
  203. package/dist/rpc/dispatcher.d.ts +121 -0
  204. package/dist/rpc/dispatcher.d.ts.map +1 -0
  205. package/dist/rpc/dispatcher.js +994 -0
  206. package/dist/rpc/dispatcher.js.map +1 -0
  207. package/dist/rpc/index.d.ts +2 -0
  208. package/dist/rpc/index.d.ts.map +1 -1
  209. package/dist/rpc/index.js +2 -0
  210. package/dist/rpc/index.js.map +1 -1
  211. package/dist/rpc/lifecycle.d.ts +6 -0
  212. package/dist/rpc/lifecycle.d.ts.map +1 -0
  213. package/dist/rpc/lifecycle.js +24 -0
  214. package/dist/rpc/lifecycle.js.map +1 -0
  215. package/dist/rpc/protocol.d.ts +112 -31
  216. package/dist/rpc/protocol.d.ts.map +1 -1
  217. package/dist/rpc/protocol.js +569 -117
  218. package/dist/rpc/protocol.js.map +1 -1
  219. package/dist/rpc/server-service.d.ts +7 -0
  220. package/dist/rpc/server-service.d.ts.map +1 -0
  221. package/dist/rpc/server-service.js +3 -0
  222. package/dist/rpc/server-service.js.map +1 -0
  223. package/dist/rpc/server.d.ts +16 -19
  224. package/dist/rpc/server.d.ts.map +1 -1
  225. package/dist/rpc/server.js +59 -115
  226. package/dist/rpc/server.js.map +1 -1
  227. package/dist/rpc-client-sdk-entry.d.ts +12 -0
  228. package/dist/rpc-client-sdk-entry.d.ts.map +1 -0
  229. package/dist/rpc-client-sdk-entry.js +11 -0
  230. package/dist/rpc-client-sdk-entry.js.map +1 -0
  231. package/dist/rpc-entry.js +50 -18
  232. package/dist/rpc-entry.js.map +1 -1
  233. package/dist/rpc-server-entry.d.ts +8 -0
  234. package/dist/rpc-server-entry.d.ts.map +1 -0
  235. package/dist/rpc-server-entry.js +67 -0
  236. package/dist/rpc-server-entry.js.map +1 -0
  237. package/dist/runtime/attachment-store.d.ts +13 -0
  238. package/dist/runtime/attachment-store.d.ts.map +1 -0
  239. package/dist/runtime/attachment-store.js +93 -0
  240. package/dist/runtime/attachment-store.js.map +1 -0
  241. package/dist/runtime/bootstrap.d.ts +14 -0
  242. package/dist/runtime/bootstrap.d.ts.map +1 -0
  243. package/dist/runtime/bootstrap.js +29 -0
  244. package/dist/runtime/bootstrap.js.map +1 -0
  245. package/dist/runtime/interactive-host-service.d.ts +22 -0
  246. package/dist/runtime/interactive-host-service.d.ts.map +1 -0
  247. package/dist/runtime/interactive-host-service.js +2 -0
  248. package/dist/runtime/interactive-host-service.js.map +1 -0
  249. package/dist/runtime/interactive-resource-service.d.ts +11 -0
  250. package/dist/runtime/interactive-resource-service.d.ts.map +1 -0
  251. package/dist/runtime/interactive-resource-service.js +3 -0
  252. package/dist/runtime/interactive-resource-service.js.map +1 -0
  253. package/dist/runtime/plugin-inventory-entry.d.ts +5 -0
  254. package/dist/runtime/plugin-inventory-entry.d.ts.map +1 -0
  255. package/dist/runtime/plugin-inventory-entry.js +18 -0
  256. package/dist/runtime/plugin-inventory-entry.js.map +1 -0
  257. package/dist/runtime/plugin-inventory-service.d.ts +8 -0
  258. package/dist/runtime/plugin-inventory-service.d.ts.map +1 -0
  259. package/dist/runtime/plugin-inventory-service.js +3 -0
  260. package/dist/runtime/plugin-inventory-service.js.map +1 -0
  261. package/dist/runtime/plugin-manager-entry.d.ts +20 -0
  262. package/dist/runtime/plugin-manager-entry.d.ts.map +1 -0
  263. package/dist/runtime/plugin-manager-entry.js +96 -0
  264. package/dist/runtime/plugin-manager-entry.js.map +1 -0
  265. package/dist/runtime/plugin-observability-entry.d.ts +12 -0
  266. package/dist/runtime/plugin-observability-entry.d.ts.map +1 -0
  267. package/dist/runtime/plugin-observability-entry.js +73 -0
  268. package/dist/runtime/plugin-observability-entry.js.map +1 -0
  269. package/dist/runtime/product-host.d.ts +91 -0
  270. package/dist/runtime/product-host.d.ts.map +1 -0
  271. package/dist/runtime/product-host.js +529 -0
  272. package/dist/runtime/product-host.js.map +1 -0
  273. package/dist/runtime/session-factory.d.ts +17 -0
  274. package/dist/runtime/session-factory.d.ts.map +1 -0
  275. package/dist/runtime/session-factory.js +75 -0
  276. package/dist/runtime/session-factory.js.map +1 -0
  277. package/dist/runtime/session-host.d.ts +152 -0
  278. package/dist/runtime/session-host.d.ts.map +1 -0
  279. package/dist/runtime/session-host.js +895 -0
  280. package/dist/runtime/session-host.js.map +1 -0
  281. package/dist/runtime-core-entry.d.ts +11 -0
  282. package/dist/runtime-core-entry.d.ts.map +1 -0
  283. package/dist/runtime-core-entry.js +9 -0
  284. package/dist/runtime-core-entry.js.map +1 -0
  285. package/dist/session-factory-entry.d.ts +7 -0
  286. package/dist/session-factory-entry.d.ts.map +1 -0
  287. package/dist/session-factory-entry.js +9 -0
  288. package/dist/session-factory-entry.js.map +1 -0
  289. package/dist/session-store-jsonl-entry.d.ts +7 -0
  290. package/dist/session-store-jsonl-entry.d.ts.map +1 -0
  291. package/dist/session-store-jsonl-entry.js +33 -0
  292. package/dist/session-store-jsonl-entry.js.map +1 -0
  293. package/dist/startup.d.ts +12 -1
  294. package/dist/startup.d.ts.map +1 -1
  295. package/dist/startup.js +106 -15
  296. package/dist/startup.js.map +1 -1
  297. package/dist/subagents/index.d.ts +2 -0
  298. package/dist/subagents/index.d.ts.map +1 -0
  299. package/dist/subagents/index.js +2 -0
  300. package/dist/subagents/index.js.map +1 -0
  301. package/dist/subagents/service.d.ts +50 -0
  302. package/dist/subagents/service.d.ts.map +1 -0
  303. package/dist/subagents/service.js +521 -0
  304. package/dist/subagents/service.js.map +1 -0
  305. package/dist/ui-host.d.ts +125 -0
  306. package/dist/ui-host.d.ts.map +1 -0
  307. package/dist/ui-host.js +275 -0
  308. package/dist/ui-host.js.map +1 -0
  309. package/dist/web/assets/index-BwfuGMvv.css +1 -0
  310. package/dist/web/assets/index-DPUaJqFJ.js +41 -0
  311. package/dist/web/assets/index-DPUaJqFJ.js.map +1 -0
  312. package/dist/web/index.html +14 -0
  313. package/dist/web-command.d.ts +11 -0
  314. package/dist/web-command.d.ts.map +1 -0
  315. package/dist/web-command.js +114 -0
  316. package/dist/web-command.js.map +1 -0
  317. package/dist/web-frontend.d.ts +73 -0
  318. package/dist/web-frontend.d.ts.map +1 -0
  319. package/dist/web-frontend.js +249 -0
  320. package/dist/web-frontend.js.map +1 -0
  321. package/dist/web.d.ts +254 -0
  322. package/dist/web.d.ts.map +1 -0
  323. package/dist/web.js +740 -0
  324. package/dist/web.js.map +1 -0
  325. package/dist/webui-entry.d.ts +3 -0
  326. package/dist/webui-entry.d.ts.map +1 -0
  327. package/dist/webui-entry.js +73 -0
  328. package/dist/webui-entry.js.map +1 -0
  329. package/dist/webui.d.ts +91 -0
  330. package/dist/webui.d.ts.map +1 -0
  331. package/dist/webui.js +882 -0
  332. package/dist/webui.js.map +1 -0
  333. package/package.json +89 -8
@@ -1,208 +1,2 @@
1
- import { spawn } from "node:child_process";
2
- import { realpath } from "node:fs/promises";
3
- import { StringDecoder } from "node:string_decoder";
4
- import { Type } from "@di-code/ai";
5
- export const DEFAULT_BASH_TIMEOUT_MS = 30_000;
6
- export const MAX_BASH_TIMEOUT_MS = 300_000;
7
- export const DEFAULT_BASH_MAX_OUTPUT_BYTES = 50 * 1024;
8
- export const bashParameters = Type.Object({
9
- command: Type.String({ minLength: 1 }),
10
- timeoutMs: Type.Optional(Type.Integer({ minimum: 1, maximum: MAX_BASH_TIMEOUT_MS })),
11
- });
12
- function assertTimeout(timeoutMs) {
13
- if (!Number.isInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > MAX_BASH_TIMEOUT_MS) {
14
- throw new Error(`timeoutMs must be an integer between 1 and ${MAX_BASH_TIMEOUT_MS}`);
15
- }
16
- }
17
- function assertMaxOutputBytes(maxOutputBytes) {
18
- if (!Number.isInteger(maxOutputBytes) || maxOutputBytes < 1) {
19
- throw new Error("maxOutputBytes must be a positive integer");
20
- }
21
- }
22
- function createOutputCapture(maxBytes) {
23
- const chunks = [];
24
- let bytes = 0;
25
- let truncated = false;
26
- return {
27
- append(chunk) {
28
- const remaining = maxBytes - bytes;
29
- if (remaining > 0) {
30
- const kept = chunk.subarray(0, remaining);
31
- chunks.push(Buffer.from(kept));
32
- bytes += kept.length;
33
- }
34
- if (chunk.length > remaining)
35
- truncated = true;
36
- },
37
- snapshot() {
38
- const decoder = new StringDecoder("utf8");
39
- return { text: decoder.write(Buffer.concat(chunks, bytes)), truncated };
40
- },
41
- };
42
- }
43
- function createPowerShellScript(command) {
44
- return [
45
- "$OutputEncoding = [Console]::OutputEncoding = [System.Text.UTF8Encoding]::new($false)",
46
- "$script:diCodeSucceeded = $false",
47
- "$script:diCodeExitCode = 0",
48
- "& {",
49
- command,
50
- "$script:diCodeSucceeded = $?",
51
- "$script:diCodeExitCode = $LASTEXITCODE",
52
- "} | Out-Default",
53
- "if ($script:diCodeSucceeded) { exit 0 }",
54
- "if ($script:diCodeExitCode -is [int] -and $script:diCodeExitCode -ne 0) { exit $script:diCodeExitCode }",
55
- "exit 1",
56
- ].join("\n");
57
- }
58
- export function resolveShellRuntime(platform = process.platform) {
59
- if (platform === "win32") {
60
- return {
61
- executable: "powershell.exe",
62
- detached: false,
63
- description: "Execute a Windows PowerShell command in the allowed root with timeout and bounded output. Use PowerShell syntax such as Get-ChildItem and Get-Content; do not use Bash syntax.",
64
- args: (command) => ["-NoLogo", "-NoProfile", "-NonInteractive", "-Command", createPowerShellScript(command)],
65
- };
66
- }
67
- return {
68
- executable: "/bin/sh",
69
- detached: true,
70
- description: "Execute a POSIX shell command using /bin/sh in the allowed root with timeout and bounded output. Use portable POSIX syntax; Bash-only extensions may not be available.",
71
- args: (command) => ["-c", command],
72
- };
73
- }
74
- function waitForProcess(command, cwd, options) {
75
- return new Promise((resolve, reject) => {
76
- if (options.signal?.aborted) {
77
- reject(new Error("Operation aborted"));
78
- return;
79
- }
80
- const runtime = resolveShellRuntime();
81
- const child = spawn(runtime.executable, [...runtime.args(command)], {
82
- cwd,
83
- detached: runtime.detached,
84
- stdio: ["ignore", "pipe", "pipe"],
85
- windowsHide: true,
86
- });
87
- let timedOut = false;
88
- let aborted = false;
89
- let settled = false;
90
- let termination;
91
- const requestTermination = () => {
92
- if (child.pid !== undefined)
93
- termination ??= killProcessTree(child.pid, child);
94
- };
95
- const onAbort = () => {
96
- aborted = true;
97
- requestTermination();
98
- };
99
- const timeout = setTimeout(() => {
100
- timedOut = true;
101
- requestTermination();
102
- }, options.timeoutMs);
103
- options.signal?.addEventListener("abort", onAbort, { once: true });
104
- if (options.signal?.aborted)
105
- onAbort();
106
- child.stdout.on("data", options.onStdout);
107
- child.stderr.on("data", options.onStderr);
108
- const cleanup = () => {
109
- clearTimeout(timeout);
110
- options.signal?.removeEventListener("abort", onAbort);
111
- };
112
- child.once("error", (error) => {
113
- if (settled)
114
- return;
115
- settled = true;
116
- cleanup();
117
- reject(error);
118
- });
119
- child.once("close", (exitCode) => {
120
- if (settled)
121
- return;
122
- settled = true;
123
- cleanup();
124
- void (termination ?? Promise.resolve()).then(() => resolve({ exitCode, timedOut, aborted }), (error) => reject(error));
125
- });
126
- });
127
- }
128
- function waitForChild(child) {
129
- return new Promise((resolve) => {
130
- child.once("error", () => resolve());
131
- child.once("close", () => resolve());
132
- });
133
- }
134
- async function killProcessTree(pid, child) {
135
- if (process.platform === "win32") {
136
- const killer = spawn("taskkill", ["/F", "/T", "/PID", String(pid)], {
137
- stdio: "ignore",
138
- windowsHide: true,
139
- });
140
- await waitForChild(killer);
141
- return;
142
- }
143
- try {
144
- process.kill(-pid, "SIGKILL");
145
- }
146
- catch {
147
- try {
148
- child.kill("SIGKILL");
149
- }
150
- catch {
151
- // The process already exited between the timeout and termination request.
152
- }
153
- }
154
- }
155
- export function createLocalBashOperations() {
156
- return { run: waitForProcess };
157
- }
158
- function formatResult(stdout, stderr, execution) {
159
- const status = {
160
- exitCode: execution.exitCode,
161
- timedOut: execution.timedOut,
162
- aborted: execution.aborted,
163
- stdoutTruncated: stdout.truncated,
164
- stderrTruncated: stderr.truncated,
165
- };
166
- return `stdout:\n${stdout.text || "(empty)"}\n\nstderr:\n${stderr.text || "(empty)"}\n\nstatus: ${JSON.stringify(status)}`;
167
- }
168
- export function createBashTool(allowedRoot, options = {}) {
169
- const operations = options.operations ?? createLocalBashOperations();
170
- const maxOutputBytes = options.maxOutputBytes ?? DEFAULT_BASH_MAX_OUTPUT_BYTES;
171
- const runtime = resolveShellRuntime();
172
- assertMaxOutputBytes(maxOutputBytes);
173
- return {
174
- name: "bash",
175
- description: runtime.description,
176
- parameters: bashParameters,
177
- async execute(_toolCallId, parameters, signal) {
178
- if (signal?.aborted)
179
- throw new Error("Operation aborted");
180
- if (parameters.command.length === 0)
181
- throw new Error("command must not be empty");
182
- const timeoutMs = parameters.timeoutMs ?? DEFAULT_BASH_TIMEOUT_MS;
183
- assertTimeout(timeoutMs);
184
- const cwd = await realpath(allowedRoot);
185
- if (signal?.aborted)
186
- throw new Error("Operation aborted");
187
- const stdout = createOutputCapture(maxOutputBytes);
188
- const stderr = createOutputCapture(maxOutputBytes);
189
- const executionResult = await operations.run(parameters.command, cwd, {
190
- signal,
191
- timeoutMs,
192
- onStdout: (chunk) => stdout.append(chunk),
193
- onStderr: (chunk) => stderr.append(chunk),
194
- });
195
- const execution = signal?.aborted ? { ...executionResult, aborted: true } : executionResult;
196
- const output = formatResult(stdout.snapshot(), stderr.snapshot(), execution);
197
- if (execution.aborted)
198
- throw new Error(`Command aborted\n\n${output}`);
199
- if (execution.timedOut)
200
- throw new Error(`Command timed out after ${timeoutMs} ms\n\n${output}`);
201
- if (execution.exitCode !== 0) {
202
- throw new Error(`Command exited with code ${execution.exitCode ?? "unknown"}\n\n${output}`);
203
- }
204
- return [{ type: "text", text: output }];
205
- },
206
- };
207
- }
1
+ export * from "@di-code/builtins";
208
2
  //# sourceMappingURL=bash.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"bash.js","sourceRoot":"","sources":["../../../src/core/tools/bash.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,MAAM,oBAAoB,CAAC;AAC3C,OAAO,EAAE,QAAQ,EAA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AAU,CAAC,OAAO,EAAE,GAAG,EAAE;gBACrE,MAAM;gBACN,SAAS;gBACT,QAAQ,EAAE,CAAC,KAAK,EAAE,EAAE,CAAC,MAAM,CAAC,MAAM,CAAC,KAAK,CAAC;gBACzC,QAAQ,EAAE,CAAC,KAAK,EAAE,EAAE,CAAC,MAAM,CAAC,MAAM,CAAC,KAAK,CAAC;aACzC,CAAC,CAAC;YACH,MAAM,SAAS,GAAG,MAAM,EAAE,OAAO,CAAC,CAAC,CAAC,EAAE,GAAG,eAAe,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC,eAAe,CAAC;YAC5F,MAAM,MAAM,GAAG,YAAY,CAAC,MAAM,CAAC,QAAQ,EAAE,EAAE,MAAM,CAAC,QAAQ,EAAE,EAAE,SAAS,CAAC,CAAC;YAE7E,IAAI,SAAS,CAAC,OAAO;gBAAE,MAAM,IAAI,KAAK,CAAC,sBAAsB,MAAM,EAAE,CAAC,CAAC;YACvE,IAAI,SAAS,CAAC,QAAQ;gBAAE,MAAM,IAAI,KAAK,CAAC,2BAA2B,SAAS,UAAU,MAAM,EAAE,CAAC,CAAC;YAChG,IAAI,SAAS,CAAC,QAAQ,KAAK,CAAC,EAAE,CAAC;gBAC9B,MAAM,IAAI,KAAK,CAAC,4BAA4B,SAAS,CAAC,QAAQ,IAAI,SAAS,OAAO,MAAM,EAAE,CAAC,CAAC;YAC7F,CAAC;YACD,OAAO,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,CAAC,CAAC;QACzC,CAAC;KACD,CAAC;AACH,CAAC","sourcesContent":["import { spawn } from \"node:child_process\";\nimport { realpath } from \"node:fs/promises\";\nimport { StringDecoder } from \"node:string_decoder\";\nimport type { AgentTool } from \"@di-code/agent\";\nimport { type Static, type ToolResultContent, Type } from \"@di-code/ai\";\n\nexport const DEFAULT_BASH_TIMEOUT_MS = 30_000;\nexport const MAX_BASH_TIMEOUT_MS = 300_000;\nexport const DEFAULT_BASH_MAX_OUTPUT_BYTES = 50 * 1024;\n\nexport const bashParameters = Type.Object({\n\tcommand: Type.String({ minLength: 1 }),\n\ttimeoutMs: Type.Optional(Type.Integer({ minimum: 1, maximum: MAX_BASH_TIMEOUT_MS })),\n});\n\nexport type BashParameters = Static<typeof bashParameters>;\n\nexport interface BashRunOptions {\n\treadonly signal?: AbortSignal;\n\treadonly timeoutMs: number;\n\treadonly onStdout: (chunk: Buffer) => void;\n\treadonly onStderr: (chunk: Buffer) => void;\n}\n\nexport interface BashExecution {\n\treadonly exitCode: number | null;\n\treadonly timedOut: boolean;\n\treadonly aborted: boolean;\n}\n\nexport interface BashOperations {\n\trun(command: string, cwd: string, options: BashRunOptions): Promise<BashExecution>;\n}\n\nexport interface BashToolOptions {\n\treadonly operations?: BashOperations;\n\treadonly maxOutputBytes?: number;\n}\n\nexport type BashTool = AgentTool<typeof bashParameters, ToolResultContent[]>;\n\nexport interface ShellRuntime {\n\treadonly executable: string;\n\treadonly detached: boolean;\n\treadonly description: string;\n\targs(command: string): readonly string[];\n}\n\ninterface OutputSnapshot {\n\treadonly text: string;\n\treadonly truncated: boolean;\n}\n\ninterface BashStatus {\n\treadonly exitCode: number | null;\n\treadonly timedOut: boolean;\n\treadonly aborted: boolean;\n\treadonly stdoutTruncated: boolean;\n\treadonly stderrTruncated: boolean;\n}\n\nfunction assertTimeout(timeoutMs: number): void {\n\tif (!Number.isInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > MAX_BASH_TIMEOUT_MS) {\n\t\tthrow new Error(`timeoutMs must be an integer between 1 and ${MAX_BASH_TIMEOUT_MS}`);\n\t}\n}\n\nfunction assertMaxOutputBytes(maxOutputBytes: number): void {\n\tif (!Number.isInteger(maxOutputBytes) || maxOutputBytes < 1) {\n\t\tthrow new Error(\"maxOutputBytes must be a positive integer\");\n\t}\n}\n\nfunction createOutputCapture(maxBytes: number): {\n\tappend(chunk: Buffer): void;\n\tsnapshot(): OutputSnapshot;\n} {\n\tconst chunks: Buffer[] = [];\n\tlet bytes = 0;\n\tlet truncated = false;\n\n\treturn {\n\t\tappend(chunk) {\n\t\t\tconst remaining = maxBytes - bytes;\n\t\t\tif (remaining > 0) {\n\t\t\t\tconst kept = chunk.subarray(0, remaining);\n\t\t\t\tchunks.push(Buffer.from(kept));\n\t\t\t\tbytes += kept.length;\n\t\t\t}\n\t\t\tif (chunk.length > remaining) truncated = true;\n\t\t},\n\t\tsnapshot() {\n\t\t\tconst decoder = new StringDecoder(\"utf8\");\n\t\t\treturn { text: decoder.write(Buffer.concat(chunks, bytes)), truncated };\n\t\t},\n\t};\n}\n\nfunction createPowerShellScript(command: string): string {\n\treturn [\n\t\t\"$OutputEncoding = [Console]::OutputEncoding = [System.Text.UTF8Encoding]::new($false)\",\n\t\t\"$script:diCodeSucceeded = $false\",\n\t\t\"$script:diCodeExitCode = 0\",\n\t\t\"& {\",\n\t\tcommand,\n\t\t\"$script:diCodeSucceeded = $?\",\n\t\t\"$script:diCodeExitCode = $LASTEXITCODE\",\n\t\t\"} | Out-Default\",\n\t\t\"if ($script:diCodeSucceeded) { exit 0 }\",\n\t\t\"if ($script:diCodeExitCode -is [int] -and $script:diCodeExitCode -ne 0) { exit $script:diCodeExitCode }\",\n\t\t\"exit 1\",\n\t].join(\"\\n\");\n}\n\nexport function resolveShellRuntime(platform: NodeJS.Platform = process.platform): ShellRuntime {\n\tif (platform === \"win32\") {\n\t\treturn {\n\t\t\texecutable: \"powershell.exe\",\n\t\t\tdetached: false,\n\t\t\tdescription:\n\t\t\t\t\"Execute a Windows PowerShell command in the allowed root with timeout and bounded output. Use PowerShell syntax such as Get-ChildItem and Get-Content; do not use Bash syntax.\",\n\t\t\targs: (command) => [\"-NoLogo\", \"-NoProfile\", \"-NonInteractive\", \"-Command\", createPowerShellScript(command)],\n\t\t};\n\t}\n\n\treturn {\n\t\texecutable: \"/bin/sh\",\n\t\tdetached: true,\n\t\tdescription:\n\t\t\t\"Execute a POSIX shell command using /bin/sh in the allowed root with timeout and bounded output. Use portable POSIX syntax; Bash-only extensions may not be available.\",\n\t\targs: (command) => [\"-c\", command],\n\t};\n}\n\nfunction waitForProcess(command: string, cwd: string, options: BashRunOptions): Promise<BashExecution> {\n\treturn new Promise((resolve, reject) => {\n\t\tif (options.signal?.aborted) {\n\t\t\treject(new Error(\"Operation aborted\"));\n\t\t\treturn;\n\t\t}\n\n\t\tconst runtime = resolveShellRuntime();\n\t\tconst child = spawn(runtime.executable, [...runtime.args(command)], {\n\t\t\tcwd,\n\t\t\tdetached: runtime.detached,\n\t\t\tstdio: [\"ignore\", \"pipe\", \"pipe\"],\n\t\t\twindowsHide: true,\n\t\t});\n\n\t\tlet timedOut = false;\n\t\tlet aborted = false;\n\t\tlet settled = false;\n\t\tlet termination: Promise<void> | undefined;\n\n\t\tconst requestTermination = (): void => {\n\t\t\tif (child.pid !== undefined) termination ??= killProcessTree(child.pid, child);\n\t\t};\n\t\tconst onAbort = (): void => {\n\t\t\taborted = true;\n\t\t\trequestTermination();\n\t\t};\n\t\tconst timeout = setTimeout(() => {\n\t\t\ttimedOut = true;\n\t\t\trequestTermination();\n\t\t}, options.timeoutMs);\n\n\t\toptions.signal?.addEventListener(\"abort\", onAbort, { once: true });\n\t\tif (options.signal?.aborted) onAbort();\n\t\tchild.stdout.on(\"data\", options.onStdout);\n\t\tchild.stderr.on(\"data\", options.onStderr);\n\n\t\tconst cleanup = (): void => {\n\t\t\tclearTimeout(timeout);\n\t\t\toptions.signal?.removeEventListener(\"abort\", onAbort);\n\t\t};\n\t\tchild.once(\"error\", (error) => {\n\t\t\tif (settled) return;\n\t\t\tsettled = true;\n\t\t\tcleanup();\n\t\t\treject(error);\n\t\t});\n\t\tchild.once(\"close\", (exitCode) => {\n\t\t\tif (settled) return;\n\t\t\tsettled = true;\n\t\t\tcleanup();\n\t\t\tvoid (termination ?? Promise.resolve()).then(\n\t\t\t\t() => resolve({ exitCode, timedOut, aborted }),\n\t\t\t\t(error: unknown) => reject(error),\n\t\t\t);\n\t\t});\n\t});\n}\n\nfunction waitForChild(child: ReturnType<typeof spawn>): Promise<void> {\n\treturn new Promise((resolve) => {\n\t\tchild.once(\"error\", () => resolve());\n\t\tchild.once(\"close\", () => resolve());\n\t});\n}\n\nasync function killProcessTree(pid: number, child: ReturnType<typeof spawn>): Promise<void> {\n\tif (process.platform === \"win32\") {\n\t\tconst killer = spawn(\"taskkill\", [\"/F\", \"/T\", \"/PID\", String(pid)], {\n\t\t\tstdio: \"ignore\",\n\t\t\twindowsHide: true,\n\t\t});\n\t\tawait waitForChild(killer);\n\t\treturn;\n\t}\n\n\ttry {\n\t\tprocess.kill(-pid, \"SIGKILL\");\n\t} catch {\n\t\ttry {\n\t\t\tchild.kill(\"SIGKILL\");\n\t\t} catch {\n\t\t\t// The process already exited between the timeout and termination request.\n\t\t}\n\t}\n}\n\nexport function createLocalBashOperations(): BashOperations {\n\treturn { run: waitForProcess };\n}\n\nfunction formatResult(stdout: OutputSnapshot, stderr: OutputSnapshot, execution: BashExecution): string {\n\tconst status: BashStatus = {\n\t\texitCode: execution.exitCode,\n\t\ttimedOut: execution.timedOut,\n\t\taborted: execution.aborted,\n\t\tstdoutTruncated: stdout.truncated,\n\t\tstderrTruncated: stderr.truncated,\n\t};\n\treturn `stdout:\\n${stdout.text || \"(empty)\"}\\n\\nstderr:\\n${stderr.text || \"(empty)\"}\\n\\nstatus: ${JSON.stringify(status)}`;\n}\n\nexport function createBashTool(allowedRoot: string, options: BashToolOptions = {}): BashTool {\n\tconst operations = options.operations ?? createLocalBashOperations();\n\tconst maxOutputBytes = options.maxOutputBytes ?? DEFAULT_BASH_MAX_OUTPUT_BYTES;\n\tconst runtime = resolveShellRuntime();\n\tassertMaxOutputBytes(maxOutputBytes);\n\n\treturn {\n\t\tname: \"bash\",\n\t\tdescription: runtime.description,\n\t\tparameters: bashParameters,\n\t\tasync execute(_toolCallId, parameters, signal): Promise<ToolResultContent[]> {\n\t\t\tif (signal?.aborted) throw new Error(\"Operation aborted\");\n\t\t\tif (parameters.command.length === 0) throw new Error(\"command must not be empty\");\n\t\t\tconst timeoutMs = parameters.timeoutMs ?? DEFAULT_BASH_TIMEOUT_MS;\n\t\t\tassertTimeout(timeoutMs);\n\t\t\tconst cwd = await realpath(allowedRoot);\n\t\t\tif (signal?.aborted) throw new Error(\"Operation aborted\");\n\n\t\t\tconst stdout = createOutputCapture(maxOutputBytes);\n\t\t\tconst stderr = createOutputCapture(maxOutputBytes);\n\t\t\tconst executionResult = await operations.run(parameters.command, cwd, {\n\t\t\t\tsignal,\n\t\t\t\ttimeoutMs,\n\t\t\t\tonStdout: (chunk) => stdout.append(chunk),\n\t\t\t\tonStderr: (chunk) => stderr.append(chunk),\n\t\t\t});\n\t\t\tconst execution = signal?.aborted ? { ...executionResult, aborted: true } : executionResult;\n\t\t\tconst output = formatResult(stdout.snapshot(), stderr.snapshot(), execution);\n\n\t\t\tif (execution.aborted) throw new Error(`Command aborted\\n\\n${output}`);\n\t\t\tif (execution.timedOut) throw new Error(`Command timed out after ${timeoutMs} ms\\n\\n${output}`);\n\t\t\tif (execution.exitCode !== 0) {\n\t\t\t\tthrow new Error(`Command exited with code ${execution.exitCode ?? \"unknown\"}\\n\\n${output}`);\n\t\t\t}\n\t\t\treturn [{ type: \"text\", text: output }];\n\t\t},\n\t};\n}\n"]}
1
+ {"version":3,"file":"bash.js","sourceRoot":"","sources":["../../../src/core/tools/bash.ts"],"names":[],"mappings":"AAAA,cAAc,mBAAmB,CAAC","sourcesContent":["export * from \"@di-code/builtins\";\n"]}
@@ -1,25 +1,2 @@
1
- export interface Edit {
2
- readonly oldText: string;
3
- readonly newText: string;
4
- }
5
- export interface EditDiffResult {
6
- readonly diff: string;
7
- readonly patch: string;
8
- readonly firstChangedLine?: number;
9
- }
10
- export interface EditDiffError {
11
- readonly error: string;
12
- }
13
- export declare function applyEditsToContent(content: string, edits: readonly Edit[], path: string): {
14
- baseContent: string;
15
- newContent: string;
16
- };
17
- /** Generate a standard unified patch for storage/export. */
18
- export declare function generateUnifiedPatch(path: string, oldContent: string, newContent: string, contextLines?: number): string;
19
- /** Generate the line-numbered display diff consumed by the interactive renderer. */
20
- export declare function generateDiffString(oldContent: string, newContent: string, contextLines?: number): {
21
- diff: string;
22
- firstChangedLine: number | undefined;
23
- };
24
- export declare function computeEditsDiff(path: string, edits: readonly Edit[], cwd: string): Promise<EditDiffResult | EditDiffError>;
1
+ export * from "@di-code/builtins";
25
2
  //# sourceMappingURL=edit-diff.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"edit-diff.d.ts","sourceRoot":"","sources":["../../../src/core/tools/edit-diff.ts"],"names":[],"mappings":"AAIA,MAAM,WAAW,IAAI;IACpB,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;IACzB,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;CACzB;AAED,MAAM,WAAW,cAAc;IAC9B,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;IACvB,QAAQ,CAAC,gBAAgB,CAAC,EAAE,MAAM,CAAC;CACnC;AAED,MAAM,WAAW,aAAa;IAC7B,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;CACvB;AAqDD,wBAAgB,mBAAmB,CAClC,OAAO,EAAE,MAAM,EACf,KAAK,EAAE,SAAS,IAAI,EAAE,EACtB,IAAI,EAAE,MAAM,GACV;IAAE,WAAW,EAAE,MAAM,CAAC;IAAC,UAAU,EAAE,MAAM,CAAA;CAAE,CAQ7C;AAED,4DAA4D;AAC5D,wBAAgB,oBAAoB,CAAC,IAAI,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,EAAE,YAAY,SAAI,GAAG,MAAM,CAKnH;AAED,oFAAoF;AACpF,wBAAgB,kBAAkB,CACjC,UAAU,EAAE,MAAM,EAClB,UAAU,EAAE,MAAM,EAClB,YAAY,SAAI,GACd;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,gBAAgB,EAAE,MAAM,GAAG,SAAS,CAAA;CAAE,CAuDxD;AAED,wBAAsB,gBAAgB,CACrC,IAAI,EAAE,MAAM,EACZ,KAAK,EAAE,SAAS,IAAI,EAAE,EACtB,GAAG,EAAE,MAAM,GACT,OAAO,CAAC,cAAc,GAAG,aAAa,CAAC,CAmBzC"}
1
+ {"version":3,"file":"edit-diff.d.ts","sourceRoot":"","sources":["../../../src/core/tools/edit-diff.ts"],"names":[],"mappings":"AAAA,cAAc,mBAAmB,CAAC"}
@@ -1,136 +1,2 @@
1
- import { access, constants, readFile } from "node:fs/promises";
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,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;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
- import type { AgentTool, ToolExecutionResult } from "@di-code/agent";
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":"AACA,OAAO,KAAK,EAAE,SAAS,EAAE,mBAAmB,EAAE,MAAM,gBAAgB,CAAC;AACrE,OAAO,EAAE,KAAK,MAAM,EAA0B,IAAI,EAAE,MAAM,aAAa,CAAC;AAUxE,eAAO,MAAM,cAAc;;;;;;;;EAMzB,CAAC;AAEH,MAAM,MAAM,cAAc,GAAG,MAAM,CAAC,OAAO,cAAc,CAAC,CAAC;AAE3D,MAAM,WAAW,cAAc;IAC9B,QAAQ,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC;IAC5C,SAAS,CAAC,QAAQ,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;CAC5D;AAED,MAAM,WAAW,eAAe;IAC/B,QAAQ,CAAC,UAAU,CAAC,EAAE,cAAc,CAAC;CACrC;AAED,MAAM,WAAW,eAAe;IAC/B,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;IACvB,QAAQ,CAAC,gBAAgB,CAAC,EAAE,MAAM,CAAC;CACnC;AAED,MAAM,MAAM,QAAQ,GAAG,SAAS,CAAC,OAAO,cAAc,EAAE,mBAAmB,CAAC,eAAe,CAAC,CAAC,CAAC;AAmE9F,wBAAgB,cAAc,CAAC,WAAW,EAAE,MAAM,EAAE,OAAO,GAAE,eAAoB,GAAG,QAAQ,CA8D3F"}
1
+ {"version":3,"file":"edit.d.ts","sourceRoot":"","sources":["../../../src/core/tools/edit.ts"],"names":[],"mappings":"AAAA,cAAc,mBAAmB,CAAC"}
@@ -1,141 +1,2 @@
1
- import { readFile as fsReadFile, writeFile as fsWriteFile } from "node:fs/promises";
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