chad-code 1.3.1 → 1.3.3

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 (338) hide show
  1. package/README.md +55 -6
  2. package/chad-code-0.0.0-main-202601090906.tgz +0 -0
  3. package/package.json +35 -97
  4. package/AGENTS.md +0 -27
  5. package/Dockerfile +0 -18
  6. package/README.npm.md +0 -64
  7. package/bunfig.toml +0 -7
  8. package/eslint.config.js +0 -29
  9. package/parsers-config.ts +0 -253
  10. package/script/build.ts +0 -167
  11. package/script/publish-registries.ts +0 -187
  12. package/script/publish.ts +0 -93
  13. package/script/schema.ts +0 -47
  14. package/src/acp/README.md +0 -164
  15. package/src/acp/agent.ts +0 -1086
  16. package/src/acp/session.ts +0 -101
  17. package/src/acp/types.ts +0 -22
  18. package/src/agent/agent.ts +0 -253
  19. package/src/agent/generate.txt +0 -75
  20. package/src/agent/prompt/compaction.txt +0 -12
  21. package/src/agent/prompt/explore.txt +0 -18
  22. package/src/agent/prompt/summary.txt +0 -11
  23. package/src/agent/prompt/title.txt +0 -36
  24. package/src/auth/index.ts +0 -70
  25. package/src/bun/index.ts +0 -130
  26. package/src/bus/bus-event.ts +0 -43
  27. package/src/bus/global.ts +0 -10
  28. package/src/bus/index.ts +0 -105
  29. package/src/cli/bootstrap.ts +0 -17
  30. package/src/cli/cmd/acp.ts +0 -69
  31. package/src/cli/cmd/agent.ts +0 -257
  32. package/src/cli/cmd/auth.ts +0 -132
  33. package/src/cli/cmd/cmd.ts +0 -7
  34. package/src/cli/cmd/debug/agent.ts +0 -28
  35. package/src/cli/cmd/debug/config.ts +0 -15
  36. package/src/cli/cmd/debug/file.ts +0 -91
  37. package/src/cli/cmd/debug/index.ts +0 -45
  38. package/src/cli/cmd/debug/lsp.ts +0 -48
  39. package/src/cli/cmd/debug/ripgrep.ts +0 -83
  40. package/src/cli/cmd/debug/scrap.ts +0 -15
  41. package/src/cli/cmd/debug/skill.ts +0 -15
  42. package/src/cli/cmd/debug/snapshot.ts +0 -48
  43. package/src/cli/cmd/export.ts +0 -88
  44. package/src/cli/cmd/generate.ts +0 -38
  45. package/src/cli/cmd/github.ts +0 -32
  46. package/src/cli/cmd/import.ts +0 -98
  47. package/src/cli/cmd/mcp.ts +0 -670
  48. package/src/cli/cmd/models.ts +0 -42
  49. package/src/cli/cmd/pr.ts +0 -112
  50. package/src/cli/cmd/run.ts +0 -374
  51. package/src/cli/cmd/serve.ts +0 -16
  52. package/src/cli/cmd/session.ts +0 -135
  53. package/src/cli/cmd/stats.ts +0 -402
  54. package/src/cli/cmd/tui/app.tsx +0 -705
  55. package/src/cli/cmd/tui/attach.ts +0 -32
  56. package/src/cli/cmd/tui/component/border.tsx +0 -21
  57. package/src/cli/cmd/tui/component/dialog-agent.tsx +0 -31
  58. package/src/cli/cmd/tui/component/dialog-command.tsx +0 -124
  59. package/src/cli/cmd/tui/component/dialog-mcp.tsx +0 -86
  60. package/src/cli/cmd/tui/component/dialog-model.tsx +0 -232
  61. package/src/cli/cmd/tui/component/dialog-provider.tsx +0 -228
  62. package/src/cli/cmd/tui/component/dialog-session-list.tsx +0 -115
  63. package/src/cli/cmd/tui/component/dialog-session-rename.tsx +0 -31
  64. package/src/cli/cmd/tui/component/dialog-stash.tsx +0 -86
  65. package/src/cli/cmd/tui/component/dialog-status.tsx +0 -162
  66. package/src/cli/cmd/tui/component/dialog-tag.tsx +0 -44
  67. package/src/cli/cmd/tui/component/dialog-theme-list.tsx +0 -50
  68. package/src/cli/cmd/tui/component/did-you-know.tsx +0 -85
  69. package/src/cli/cmd/tui/component/logo.tsx +0 -43
  70. package/src/cli/cmd/tui/component/prompt/autocomplete.tsx +0 -654
  71. package/src/cli/cmd/tui/component/prompt/history.tsx +0 -108
  72. package/src/cli/cmd/tui/component/prompt/index.tsx +0 -1078
  73. package/src/cli/cmd/tui/component/prompt/stash.tsx +0 -101
  74. package/src/cli/cmd/tui/component/textarea-keybindings.ts +0 -73
  75. package/src/cli/cmd/tui/component/tips.ts +0 -92
  76. package/src/cli/cmd/tui/component/todo-item.tsx +0 -32
  77. package/src/cli/cmd/tui/context/args.tsx +0 -14
  78. package/src/cli/cmd/tui/context/directory.ts +0 -13
  79. package/src/cli/cmd/tui/context/exit.tsx +0 -23
  80. package/src/cli/cmd/tui/context/helper.tsx +0 -25
  81. package/src/cli/cmd/tui/context/keybind.tsx +0 -101
  82. package/src/cli/cmd/tui/context/kv.tsx +0 -49
  83. package/src/cli/cmd/tui/context/local.tsx +0 -392
  84. package/src/cli/cmd/tui/context/prompt.tsx +0 -18
  85. package/src/cli/cmd/tui/context/route.tsx +0 -46
  86. package/src/cli/cmd/tui/context/sdk.tsx +0 -75
  87. package/src/cli/cmd/tui/context/sync.tsx +0 -384
  88. package/src/cli/cmd/tui/context/theme/aura.json +0 -69
  89. package/src/cli/cmd/tui/context/theme/ayu.json +0 -80
  90. package/src/cli/cmd/tui/context/theme/catppuccin-frappe.json +0 -233
  91. package/src/cli/cmd/tui/context/theme/catppuccin-macchiato.json +0 -233
  92. package/src/cli/cmd/tui/context/theme/catppuccin.json +0 -112
  93. package/src/cli/cmd/tui/context/theme/chad.json +0 -245
  94. package/src/cli/cmd/tui/context/theme/cobalt2.json +0 -228
  95. package/src/cli/cmd/tui/context/theme/cursor.json +0 -249
  96. package/src/cli/cmd/tui/context/theme/dracula.json +0 -219
  97. package/src/cli/cmd/tui/context/theme/everforest.json +0 -241
  98. package/src/cli/cmd/tui/context/theme/flexoki.json +0 -237
  99. package/src/cli/cmd/tui/context/theme/github.json +0 -233
  100. package/src/cli/cmd/tui/context/theme/gruvbox.json +0 -95
  101. package/src/cli/cmd/tui/context/theme/kanagawa.json +0 -77
  102. package/src/cli/cmd/tui/context/theme/lucent-orng.json +0 -227
  103. package/src/cli/cmd/tui/context/theme/material.json +0 -235
  104. package/src/cli/cmd/tui/context/theme/matrix.json +0 -77
  105. package/src/cli/cmd/tui/context/theme/mercury.json +0 -252
  106. package/src/cli/cmd/tui/context/theme/monokai.json +0 -221
  107. package/src/cli/cmd/tui/context/theme/nightowl.json +0 -221
  108. package/src/cli/cmd/tui/context/theme/nord.json +0 -223
  109. package/src/cli/cmd/tui/context/theme/one-dark.json +0 -84
  110. package/src/cli/cmd/tui/context/theme/orng.json +0 -245
  111. package/src/cli/cmd/tui/context/theme/osaka-jade.json +0 -93
  112. package/src/cli/cmd/tui/context/theme/palenight.json +0 -222
  113. package/src/cli/cmd/tui/context/theme/rosepine.json +0 -234
  114. package/src/cli/cmd/tui/context/theme/solarized.json +0 -223
  115. package/src/cli/cmd/tui/context/theme/synthwave84.json +0 -226
  116. package/src/cli/cmd/tui/context/theme/tokyonight.json +0 -243
  117. package/src/cli/cmd/tui/context/theme/vercel.json +0 -245
  118. package/src/cli/cmd/tui/context/theme/vesper.json +0 -218
  119. package/src/cli/cmd/tui/context/theme/zenburn.json +0 -223
  120. package/src/cli/cmd/tui/context/theme.tsx +0 -1137
  121. package/src/cli/cmd/tui/event.ts +0 -46
  122. package/src/cli/cmd/tui/routes/home.tsx +0 -138
  123. package/src/cli/cmd/tui/routes/session/dialog-fork-from-timeline.tsx +0 -64
  124. package/src/cli/cmd/tui/routes/session/dialog-message.tsx +0 -109
  125. package/src/cli/cmd/tui/routes/session/dialog-subagent.tsx +0 -26
  126. package/src/cli/cmd/tui/routes/session/dialog-timeline.tsx +0 -47
  127. package/src/cli/cmd/tui/routes/session/footer.tsx +0 -88
  128. package/src/cli/cmd/tui/routes/session/header.tsx +0 -125
  129. package/src/cli/cmd/tui/routes/session/index.tsx +0 -1814
  130. package/src/cli/cmd/tui/routes/session/permission.tsx +0 -416
  131. package/src/cli/cmd/tui/routes/session/sidebar.tsx +0 -318
  132. package/src/cli/cmd/tui/spawn.ts +0 -48
  133. package/src/cli/cmd/tui/thread.ts +0 -111
  134. package/src/cli/cmd/tui/ui/dialog-alert.tsx +0 -57
  135. package/src/cli/cmd/tui/ui/dialog-confirm.tsx +0 -83
  136. package/src/cli/cmd/tui/ui/dialog-export-options.tsx +0 -204
  137. package/src/cli/cmd/tui/ui/dialog-help.tsx +0 -38
  138. package/src/cli/cmd/tui/ui/dialog-prompt.tsx +0 -77
  139. package/src/cli/cmd/tui/ui/dialog-select.tsx +0 -345
  140. package/src/cli/cmd/tui/ui/dialog.tsx +0 -171
  141. package/src/cli/cmd/tui/ui/link.tsx +0 -28
  142. package/src/cli/cmd/tui/ui/spinner.ts +0 -368
  143. package/src/cli/cmd/tui/ui/toast.tsx +0 -100
  144. package/src/cli/cmd/tui/util/clipboard.ts +0 -127
  145. package/src/cli/cmd/tui/util/editor.ts +0 -32
  146. package/src/cli/cmd/tui/util/signal.ts +0 -7
  147. package/src/cli/cmd/tui/util/terminal.ts +0 -114
  148. package/src/cli/cmd/tui/util/transcript.ts +0 -98
  149. package/src/cli/cmd/tui/worker.ts +0 -68
  150. package/src/cli/cmd/uninstall.ts +0 -344
  151. package/src/cli/cmd/upgrade.ts +0 -67
  152. package/src/cli/cmd/web.ts +0 -73
  153. package/src/cli/error.ts +0 -56
  154. package/src/cli/network.ts +0 -53
  155. package/src/cli/ui.ts +0 -87
  156. package/src/cli/upgrade.ts +0 -25
  157. package/src/command/index.ts +0 -131
  158. package/src/command/template/initialize.txt +0 -10
  159. package/src/command/template/review.txt +0 -97
  160. package/src/config/config.ts +0 -1124
  161. package/src/config/markdown.ts +0 -41
  162. package/src/env/index.ts +0 -26
  163. package/src/file/ignore.ts +0 -83
  164. package/src/file/index.ts +0 -411
  165. package/src/file/ripgrep.ts +0 -402
  166. package/src/file/time.ts +0 -64
  167. package/src/file/watcher.ts +0 -117
  168. package/src/flag/flag.ts +0 -52
  169. package/src/format/formatter.ts +0 -359
  170. package/src/format/index.ts +0 -137
  171. package/src/global/index.ts +0 -55
  172. package/src/id/id.ts +0 -73
  173. package/src/ide/index.ts +0 -77
  174. package/src/index.ts +0 -159
  175. package/src/installation/index.ts +0 -198
  176. package/src/lsp/client.ts +0 -252
  177. package/src/lsp/index.ts +0 -485
  178. package/src/lsp/language.ts +0 -119
  179. package/src/lsp/server.ts +0 -2023
  180. package/src/mcp/auth.ts +0 -135
  181. package/src/mcp/index.ts +0 -874
  182. package/src/mcp/oauth-callback.ts +0 -200
  183. package/src/mcp/oauth-provider.ts +0 -154
  184. package/src/patch/index.ts +0 -622
  185. package/src/permission/arity.ts +0 -163
  186. package/src/permission/index.ts +0 -210
  187. package/src/permission/next.ts +0 -268
  188. package/src/plugin/index.ts +0 -106
  189. package/src/project/bootstrap.ts +0 -31
  190. package/src/project/instance.ts +0 -78
  191. package/src/project/project.ts +0 -263
  192. package/src/project/state.ts +0 -65
  193. package/src/project/vcs.ts +0 -76
  194. package/src/provider/auth.ts +0 -143
  195. package/src/provider/models-macro.ts +0 -4
  196. package/src/provider/models.ts +0 -77
  197. package/src/provider/provider.ts +0 -516
  198. package/src/provider/transform.ts +0 -114
  199. package/src/pty/index.ts +0 -212
  200. package/src/server/error.ts +0 -36
  201. package/src/server/mdns.ts +0 -57
  202. package/src/server/project.ts +0 -79
  203. package/src/server/server.ts +0 -2866
  204. package/src/server/tui.ts +0 -71
  205. package/src/session/compaction.ts +0 -225
  206. package/src/session/index.ts +0 -469
  207. package/src/session/llm.ts +0 -213
  208. package/src/session/message-v2.ts +0 -742
  209. package/src/session/message.ts +0 -189
  210. package/src/session/processor.ts +0 -402
  211. package/src/session/prompt/anthropic-20250930.txt +0 -166
  212. package/src/session/prompt/anthropic.txt +0 -105
  213. package/src/session/prompt/anthropic_spoof.txt +0 -1
  214. package/src/session/prompt/beast.txt +0 -147
  215. package/src/session/prompt/build-switch.txt +0 -5
  216. package/src/session/prompt/codex.txt +0 -318
  217. package/src/session/prompt/copilot-gpt-5.txt +0 -143
  218. package/src/session/prompt/gemini.txt +0 -155
  219. package/src/session/prompt/max-steps.txt +0 -16
  220. package/src/session/prompt/plan-reminder-anthropic.txt +0 -67
  221. package/src/session/prompt/plan.txt +0 -26
  222. package/src/session/prompt/qwen.txt +0 -109
  223. package/src/session/prompt.ts +0 -1621
  224. package/src/session/retry.ts +0 -90
  225. package/src/session/revert.ts +0 -108
  226. package/src/session/status.ts +0 -76
  227. package/src/session/summary.ts +0 -194
  228. package/src/session/system.ts +0 -108
  229. package/src/session/todo.ts +0 -37
  230. package/src/share/share-next.ts +0 -194
  231. package/src/share/share.ts +0 -23
  232. package/src/shell/shell.ts +0 -67
  233. package/src/skill/index.ts +0 -1
  234. package/src/skill/skill.ts +0 -124
  235. package/src/snapshot/index.ts +0 -197
  236. package/src/storage/storage.ts +0 -226
  237. package/src/tool/bash.ts +0 -262
  238. package/src/tool/bash.txt +0 -116
  239. package/src/tool/batch.ts +0 -175
  240. package/src/tool/batch.txt +0 -24
  241. package/src/tool/codesearch.ts +0 -132
  242. package/src/tool/codesearch.txt +0 -12
  243. package/src/tool/edit.ts +0 -655
  244. package/src/tool/edit.txt +0 -10
  245. package/src/tool/glob.ts +0 -75
  246. package/src/tool/glob.txt +0 -6
  247. package/src/tool/grep.ts +0 -132
  248. package/src/tool/grep.txt +0 -8
  249. package/src/tool/invalid.ts +0 -17
  250. package/src/tool/ls.ts +0 -119
  251. package/src/tool/ls.txt +0 -1
  252. package/src/tool/lsp.ts +0 -94
  253. package/src/tool/lsp.txt +0 -19
  254. package/src/tool/multiedit.ts +0 -46
  255. package/src/tool/multiedit.txt +0 -41
  256. package/src/tool/patch.ts +0 -210
  257. package/src/tool/patch.txt +0 -1
  258. package/src/tool/read.ts +0 -191
  259. package/src/tool/read.txt +0 -12
  260. package/src/tool/registry.ts +0 -137
  261. package/src/tool/skill.ts +0 -77
  262. package/src/tool/task.ts +0 -167
  263. package/src/tool/task.txt +0 -60
  264. package/src/tool/todo.ts +0 -53
  265. package/src/tool/todoread.txt +0 -14
  266. package/src/tool/todowrite.txt +0 -167
  267. package/src/tool/tool.ts +0 -73
  268. package/src/tool/webfetch.ts +0 -182
  269. package/src/tool/webfetch.txt +0 -13
  270. package/src/tool/websearch.ts +0 -144
  271. package/src/tool/websearch.txt +0 -11
  272. package/src/tool/write.ts +0 -84
  273. package/src/tool/write.txt +0 -8
  274. package/src/util/archive.ts +0 -16
  275. package/src/util/color.ts +0 -19
  276. package/src/util/context.ts +0 -25
  277. package/src/util/defer.ts +0 -12
  278. package/src/util/eventloop.ts +0 -20
  279. package/src/util/filesystem.ts +0 -83
  280. package/src/util/fn.ts +0 -11
  281. package/src/util/iife.ts +0 -3
  282. package/src/util/keybind.ts +0 -102
  283. package/src/util/lazy.ts +0 -18
  284. package/src/util/locale.ts +0 -81
  285. package/src/util/lock.ts +0 -98
  286. package/src/util/log.ts +0 -180
  287. package/src/util/queue.ts +0 -32
  288. package/src/util/rpc.ts +0 -42
  289. package/src/util/scrap.ts +0 -10
  290. package/src/util/signal.ts +0 -12
  291. package/src/util/timeout.ts +0 -14
  292. package/src/util/token.ts +0 -7
  293. package/src/util/wildcard.ts +0 -54
  294. package/src/worktree/index.ts +0 -217
  295. package/sst-env.d.ts +0 -9
  296. package/test/agent/agent.test.ts +0 -448
  297. package/test/bun.test.ts +0 -53
  298. package/test/cli/github-action.test.ts +0 -129
  299. package/test/cli/github-remote.test.ts +0 -80
  300. package/test/cli/tui/transcript.test.ts +0 -297
  301. package/test/config/agent-color.test.ts +0 -66
  302. package/test/config/config.test.ts +0 -870
  303. package/test/config/markdown.test.ts +0 -89
  304. package/test/file/ignore.test.ts +0 -10
  305. package/test/file/path-traversal.test.ts +0 -115
  306. package/test/fixture/fixture.ts +0 -45
  307. package/test/fixture/lsp/fake-lsp-server.js +0 -77
  308. package/test/ide/ide.test.ts +0 -82
  309. package/test/keybind.test.ts +0 -421
  310. package/test/lsp/client.test.ts +0 -95
  311. package/test/mcp/headers.test.ts +0 -153
  312. package/test/patch/patch.test.ts +0 -348
  313. package/test/permission/arity.test.ts +0 -33
  314. package/test/permission/next.test.ts +0 -652
  315. package/test/preload.ts +0 -63
  316. package/test/project/project.test.ts +0 -120
  317. package/test/provider/amazon-bedrock.test.ts +0 -236
  318. package/test/provider/provider.test.ts +0 -2127
  319. package/test/provider/transform.test.ts +0 -980
  320. package/test/server/session-select.test.ts +0 -78
  321. package/test/session/compaction.test.ts +0 -251
  322. package/test/session/message-v2.test.ts +0 -570
  323. package/test/session/retry.test.ts +0 -131
  324. package/test/session/revert-compact.test.ts +0 -285
  325. package/test/session/session.test.ts +0 -71
  326. package/test/skill/skill.test.ts +0 -185
  327. package/test/snapshot/snapshot.test.ts +0 -939
  328. package/test/tool/__snapshots__/tool.test.ts.snap +0 -9
  329. package/test/tool/bash.test.ts +0 -232
  330. package/test/tool/grep.test.ts +0 -109
  331. package/test/tool/patch.test.ts +0 -261
  332. package/test/tool/read.test.ts +0 -167
  333. package/test/util/iife.test.ts +0 -36
  334. package/test/util/lazy.test.ts +0 -50
  335. package/test/util/timeout.test.ts +0 -21
  336. package/test/util/wildcard.test.ts +0 -55
  337. package/tsconfig.json +0 -16
  338. /package/{script/postinstall.mjs → postinstall.mjs} +0 -0
@@ -1,622 +0,0 @@
1
- import z from "zod"
2
- import * as path from "path"
3
- import * as fs from "fs/promises"
4
- import { Log } from "../util/log"
5
-
6
- export namespace Patch {
7
- const log = Log.create({ service: "patch" })
8
-
9
- // Schema definitions
10
- export const PatchSchema = z.object({
11
- patchText: z.string().describe("The full patch text that describes all changes to be made"),
12
- })
13
-
14
- export type PatchParams = z.infer<typeof PatchSchema>
15
-
16
- // Core types matching the Rust implementation
17
- export interface ApplyPatchArgs {
18
- patch: string
19
- hunks: Hunk[]
20
- workdir?: string
21
- }
22
-
23
- export type Hunk =
24
- | { type: "add"; path: string; contents: string }
25
- | { type: "delete"; path: string }
26
- | { type: "update"; path: string; move_path?: string; chunks: UpdateFileChunk[] }
27
-
28
- export interface UpdateFileChunk {
29
- old_lines: string[]
30
- new_lines: string[]
31
- change_context?: string
32
- is_end_of_file?: boolean
33
- }
34
-
35
- export interface ApplyPatchAction {
36
- changes: Map<string, ApplyPatchFileChange>
37
- patch: string
38
- cwd: string
39
- }
40
-
41
- export type ApplyPatchFileChange =
42
- | { type: "add"; content: string }
43
- | { type: "delete"; content: string }
44
- | { type: "update"; unified_diff: string; move_path?: string; new_content: string }
45
-
46
- export interface AffectedPaths {
47
- added: string[]
48
- modified: string[]
49
- deleted: string[]
50
- }
51
-
52
- export enum ApplyPatchError {
53
- ParseError = "ParseError",
54
- IoError = "IoError",
55
- ComputeReplacements = "ComputeReplacements",
56
- ImplicitInvocation = "ImplicitInvocation",
57
- }
58
-
59
- export enum MaybeApplyPatch {
60
- Body = "Body",
61
- ShellParseError = "ShellParseError",
62
- PatchParseError = "PatchParseError",
63
- NotApplyPatch = "NotApplyPatch",
64
- }
65
-
66
- export enum MaybeApplyPatchVerified {
67
- Body = "Body",
68
- ShellParseError = "ShellParseError",
69
- CorrectnessError = "CorrectnessError",
70
- NotApplyPatch = "NotApplyPatch",
71
- }
72
-
73
- // Parser implementation
74
- function parsePatchHeader(
75
- lines: string[],
76
- startIdx: number,
77
- ): { filePath: string; movePath?: string; nextIdx: number } | null {
78
- const line = lines[startIdx]
79
-
80
- if (line.startsWith("*** Add File:")) {
81
- const filePath = line.split(":", 2)[1]?.trim()
82
- return filePath ? { filePath, nextIdx: startIdx + 1 } : null
83
- }
84
-
85
- if (line.startsWith("*** Delete File:")) {
86
- const filePath = line.split(":", 2)[1]?.trim()
87
- return filePath ? { filePath, nextIdx: startIdx + 1 } : null
88
- }
89
-
90
- if (line.startsWith("*** Update File:")) {
91
- const filePath = line.split(":", 2)[1]?.trim()
92
- let movePath: string | undefined
93
- let nextIdx = startIdx + 1
94
-
95
- // Check for move directive
96
- if (nextIdx < lines.length && lines[nextIdx].startsWith("*** Move to:")) {
97
- movePath = lines[nextIdx].split(":", 2)[1]?.trim()
98
- nextIdx++
99
- }
100
-
101
- return filePath ? { filePath, movePath, nextIdx } : null
102
- }
103
-
104
- return null
105
- }
106
-
107
- function parseUpdateFileChunks(lines: string[], startIdx: number): { chunks: UpdateFileChunk[]; nextIdx: number } {
108
- const chunks: UpdateFileChunk[] = []
109
- let i = startIdx
110
-
111
- while (i < lines.length && !lines[i].startsWith("***")) {
112
- if (lines[i].startsWith("@@")) {
113
- // Parse context line
114
- const contextLine = lines[i].substring(2).trim()
115
- i++
116
-
117
- const oldLines: string[] = []
118
- const newLines: string[] = []
119
- let isEndOfFile = false
120
-
121
- // Parse change lines
122
- while (i < lines.length && !lines[i].startsWith("@@") && !lines[i].startsWith("***")) {
123
- const changeLine = lines[i]
124
-
125
- if (changeLine === "*** End of File") {
126
- isEndOfFile = true
127
- i++
128
- break
129
- }
130
-
131
- if (changeLine.startsWith(" ")) {
132
- // Keep line - appears in both old and new
133
- const content = changeLine.substring(1)
134
- oldLines.push(content)
135
- newLines.push(content)
136
- } else if (changeLine.startsWith("-")) {
137
- // Remove line - only in old
138
- oldLines.push(changeLine.substring(1))
139
- } else if (changeLine.startsWith("+")) {
140
- // Add line - only in new
141
- newLines.push(changeLine.substring(1))
142
- }
143
-
144
- i++
145
- }
146
-
147
- chunks.push({
148
- old_lines: oldLines,
149
- new_lines: newLines,
150
- change_context: contextLine || undefined,
151
- is_end_of_file: isEndOfFile || undefined,
152
- })
153
- } else {
154
- i++
155
- }
156
- }
157
-
158
- return { chunks, nextIdx: i }
159
- }
160
-
161
- function parseAddFileContent(lines: string[], startIdx: number): { content: string; nextIdx: number } {
162
- let content = ""
163
- let i = startIdx
164
-
165
- while (i < lines.length && !lines[i].startsWith("***")) {
166
- if (lines[i].startsWith("+")) {
167
- content += lines[i].substring(1) + "\n"
168
- }
169
- i++
170
- }
171
-
172
- // Remove trailing newline
173
- if (content.endsWith("\n")) {
174
- content = content.slice(0, -1)
175
- }
176
-
177
- return { content, nextIdx: i }
178
- }
179
-
180
- export function parsePatch(patchText: string): { hunks: Hunk[] } {
181
- const lines = patchText.split("\n")
182
- const hunks: Hunk[] = []
183
- let i = 0
184
-
185
- // Look for Begin/End patch markers
186
- const beginMarker = "*** Begin Patch"
187
- const endMarker = "*** End Patch"
188
-
189
- const beginIdx = lines.findIndex((line) => line.trim() === beginMarker)
190
- const endIdx = lines.findIndex((line) => line.trim() === endMarker)
191
-
192
- if (beginIdx === -1 || endIdx === -1 || beginIdx >= endIdx) {
193
- throw new Error("Invalid patch format: missing Begin/End markers")
194
- }
195
-
196
- // Parse content between markers
197
- i = beginIdx + 1
198
-
199
- while (i < endIdx) {
200
- const header = parsePatchHeader(lines, i)
201
- if (!header) {
202
- i++
203
- continue
204
- }
205
-
206
- if (lines[i].startsWith("*** Add File:")) {
207
- const { content, nextIdx } = parseAddFileContent(lines, header.nextIdx)
208
- hunks.push({
209
- type: "add",
210
- path: header.filePath,
211
- contents: content,
212
- })
213
- i = nextIdx
214
- } else if (lines[i].startsWith("*** Delete File:")) {
215
- hunks.push({
216
- type: "delete",
217
- path: header.filePath,
218
- })
219
- i = header.nextIdx
220
- } else if (lines[i].startsWith("*** Update File:")) {
221
- const { chunks, nextIdx } = parseUpdateFileChunks(lines, header.nextIdx)
222
- hunks.push({
223
- type: "update",
224
- path: header.filePath,
225
- move_path: header.movePath,
226
- chunks,
227
- })
228
- i = nextIdx
229
- } else {
230
- i++
231
- }
232
- }
233
-
234
- return { hunks }
235
- }
236
-
237
- // Apply patch functionality
238
- export function maybeParseApplyPatch(
239
- argv: string[],
240
- ):
241
- | { type: MaybeApplyPatch.Body; args: ApplyPatchArgs }
242
- | { type: MaybeApplyPatch.PatchParseError; error: Error }
243
- | { type: MaybeApplyPatch.NotApplyPatch } {
244
- const APPLY_PATCH_COMMANDS = ["apply_patch", "applypatch"]
245
-
246
- // Direct invocation: apply_patch <patch>
247
- if (argv.length === 2 && APPLY_PATCH_COMMANDS.includes(argv[0])) {
248
- try {
249
- const { hunks } = parsePatch(argv[1])
250
- return {
251
- type: MaybeApplyPatch.Body,
252
- args: {
253
- patch: argv[1],
254
- hunks,
255
- },
256
- }
257
- } catch (error) {
258
- return {
259
- type: MaybeApplyPatch.PatchParseError,
260
- error: error as Error,
261
- }
262
- }
263
- }
264
-
265
- // Bash heredoc form: bash -lc 'apply_patch <<"EOF" ...'
266
- if (argv.length === 3 && argv[0] === "bash" && argv[1] === "-lc") {
267
- // Simple extraction - in real implementation would need proper bash parsing
268
- const script = argv[2]
269
- const heredocMatch = script.match(/apply_patch\s*<<['"](\w+)['"]\s*\n([\s\S]*?)\n\1/)
270
-
271
- if (heredocMatch) {
272
- const patchContent = heredocMatch[2]
273
- try {
274
- const { hunks } = parsePatch(patchContent)
275
- return {
276
- type: MaybeApplyPatch.Body,
277
- args: {
278
- patch: patchContent,
279
- hunks,
280
- },
281
- }
282
- } catch (error) {
283
- return {
284
- type: MaybeApplyPatch.PatchParseError,
285
- error: error as Error,
286
- }
287
- }
288
- }
289
- }
290
-
291
- return { type: MaybeApplyPatch.NotApplyPatch }
292
- }
293
-
294
- // File content manipulation
295
- interface ApplyPatchFileUpdate {
296
- unified_diff: string
297
- content: string
298
- }
299
-
300
- export function deriveNewContentsFromChunks(filePath: string, chunks: UpdateFileChunk[]): ApplyPatchFileUpdate {
301
- // Read original file content
302
- let originalContent: string
303
- try {
304
- originalContent = require("fs").readFileSync(filePath, "utf-8")
305
- } catch (error) {
306
- throw new Error(`Failed to read file ${filePath}: ${error}`)
307
- }
308
-
309
- let originalLines = originalContent.split("\n")
310
-
311
- // Drop trailing empty element for consistent line counting
312
- if (originalLines.length > 0 && originalLines[originalLines.length - 1] === "") {
313
- originalLines.pop()
314
- }
315
-
316
- const replacements = computeReplacements(originalLines, filePath, chunks)
317
- let newLines = applyReplacements(originalLines, replacements)
318
-
319
- // Ensure trailing newline
320
- if (newLines.length === 0 || newLines[newLines.length - 1] !== "") {
321
- newLines.push("")
322
- }
323
-
324
- const newContent = newLines.join("\n")
325
-
326
- // Generate unified diff
327
- const unifiedDiff = generateUnifiedDiff(originalContent, newContent)
328
-
329
- return {
330
- unified_diff: unifiedDiff,
331
- content: newContent,
332
- }
333
- }
334
-
335
- function computeReplacements(
336
- originalLines: string[],
337
- filePath: string,
338
- chunks: UpdateFileChunk[],
339
- ): Array<[number, number, string[]]> {
340
- const replacements: Array<[number, number, string[]]> = []
341
- let lineIndex = 0
342
-
343
- for (const chunk of chunks) {
344
- // Handle context-based seeking
345
- if (chunk.change_context) {
346
- const contextIdx = seekSequence(originalLines, [chunk.change_context], lineIndex)
347
- if (contextIdx === -1) {
348
- throw new Error(`Failed to find context '${chunk.change_context}' in ${filePath}`)
349
- }
350
- lineIndex = contextIdx + 1
351
- }
352
-
353
- // Handle pure addition (no old lines)
354
- if (chunk.old_lines.length === 0) {
355
- const insertionIdx =
356
- originalLines.length > 0 && originalLines[originalLines.length - 1] === ""
357
- ? originalLines.length - 1
358
- : originalLines.length
359
- replacements.push([insertionIdx, 0, chunk.new_lines])
360
- continue
361
- }
362
-
363
- // Try to match old lines in the file
364
- let pattern = chunk.old_lines
365
- let newSlice = chunk.new_lines
366
- let found = seekSequence(originalLines, pattern, lineIndex)
367
-
368
- // Retry without trailing empty line if not found
369
- if (found === -1 && pattern.length > 0 && pattern[pattern.length - 1] === "") {
370
- pattern = pattern.slice(0, -1)
371
- if (newSlice.length > 0 && newSlice[newSlice.length - 1] === "") {
372
- newSlice = newSlice.slice(0, -1)
373
- }
374
- found = seekSequence(originalLines, pattern, lineIndex)
375
- }
376
-
377
- if (found !== -1) {
378
- replacements.push([found, pattern.length, newSlice])
379
- lineIndex = found + pattern.length
380
- } else {
381
- throw new Error(`Failed to find expected lines in ${filePath}:\n${chunk.old_lines.join("\n")}`)
382
- }
383
- }
384
-
385
- // Sort replacements by index to apply in order
386
- replacements.sort((a, b) => a[0] - b[0])
387
-
388
- return replacements
389
- }
390
-
391
- function applyReplacements(lines: string[], replacements: Array<[number, number, string[]]>): string[] {
392
- // Apply replacements in reverse order to avoid index shifting
393
- const result = [...lines]
394
-
395
- for (let i = replacements.length - 1; i >= 0; i--) {
396
- const [startIdx, oldLen, newSegment] = replacements[i]
397
-
398
- // Remove old lines
399
- result.splice(startIdx, oldLen)
400
-
401
- // Insert new lines
402
- for (let j = 0; j < newSegment.length; j++) {
403
- result.splice(startIdx + j, 0, newSegment[j])
404
- }
405
- }
406
-
407
- return result
408
- }
409
-
410
- function seekSequence(lines: string[], pattern: string[], startIndex: number): number {
411
- if (pattern.length === 0) return -1
412
-
413
- // Simple substring search implementation
414
- for (let i = startIndex; i <= lines.length - pattern.length; i++) {
415
- let matches = true
416
-
417
- for (let j = 0; j < pattern.length; j++) {
418
- if (lines[i + j] !== pattern[j]) {
419
- matches = false
420
- break
421
- }
422
- }
423
-
424
- if (matches) {
425
- return i
426
- }
427
- }
428
-
429
- return -1
430
- }
431
-
432
- function generateUnifiedDiff(oldContent: string, newContent: string): string {
433
- const oldLines = oldContent.split("\n")
434
- const newLines = newContent.split("\n")
435
-
436
- // Simple diff generation - in a real implementation you'd use a proper diff algorithm
437
- let diff = "@@ -1 +1 @@\n"
438
-
439
- // Find changes (simplified approach)
440
- const maxLen = Math.max(oldLines.length, newLines.length)
441
- let hasChanges = false
442
-
443
- for (let i = 0; i < maxLen; i++) {
444
- const oldLine = oldLines[i] || ""
445
- const newLine = newLines[i] || ""
446
-
447
- if (oldLine !== newLine) {
448
- if (oldLine) diff += `-${oldLine}\n`
449
- if (newLine) diff += `+${newLine}\n`
450
- hasChanges = true
451
- } else if (oldLine) {
452
- diff += ` ${oldLine}\n`
453
- }
454
- }
455
-
456
- return hasChanges ? diff : ""
457
- }
458
-
459
- // Apply hunks to filesystem
460
- export async function applyHunksToFiles(hunks: Hunk[]): Promise<AffectedPaths> {
461
- if (hunks.length === 0) {
462
- throw new Error("No files were modified.")
463
- }
464
-
465
- const added: string[] = []
466
- const modified: string[] = []
467
- const deleted: string[] = []
468
-
469
- for (const hunk of hunks) {
470
- switch (hunk.type) {
471
- case "add":
472
- // Create parent directories
473
- const addDir = path.dirname(hunk.path)
474
- if (addDir !== "." && addDir !== "/") {
475
- await fs.mkdir(addDir, { recursive: true })
476
- }
477
-
478
- await fs.writeFile(hunk.path, hunk.contents, "utf-8")
479
- added.push(hunk.path)
480
- log.info(`Added file: ${hunk.path}`)
481
- break
482
-
483
- case "delete":
484
- await fs.unlink(hunk.path)
485
- deleted.push(hunk.path)
486
- log.info(`Deleted file: ${hunk.path}`)
487
- break
488
-
489
- case "update":
490
- const fileUpdate = deriveNewContentsFromChunks(hunk.path, hunk.chunks)
491
-
492
- if (hunk.move_path) {
493
- // Handle file move
494
- const moveDir = path.dirname(hunk.move_path)
495
- if (moveDir !== "." && moveDir !== "/") {
496
- await fs.mkdir(moveDir, { recursive: true })
497
- }
498
-
499
- await fs.writeFile(hunk.move_path, fileUpdate.content, "utf-8")
500
- await fs.unlink(hunk.path)
501
- modified.push(hunk.move_path)
502
- log.info(`Moved file: ${hunk.path} -> ${hunk.move_path}`)
503
- } else {
504
- // Regular update
505
- await fs.writeFile(hunk.path, fileUpdate.content, "utf-8")
506
- modified.push(hunk.path)
507
- log.info(`Updated file: ${hunk.path}`)
508
- }
509
- break
510
- }
511
- }
512
-
513
- return { added, modified, deleted }
514
- }
515
-
516
- // Main patch application function
517
- export async function applyPatch(patchText: string): Promise<AffectedPaths> {
518
- const { hunks } = parsePatch(patchText)
519
- return applyHunksToFiles(hunks)
520
- }
521
-
522
- // Async version of maybeParseApplyPatchVerified
523
- export async function maybeParseApplyPatchVerified(
524
- argv: string[],
525
- cwd: string,
526
- ): Promise<
527
- | { type: MaybeApplyPatchVerified.Body; action: ApplyPatchAction }
528
- | { type: MaybeApplyPatchVerified.CorrectnessError; error: Error }
529
- | { type: MaybeApplyPatchVerified.NotApplyPatch }
530
- > {
531
- // Detect implicit patch invocation (raw patch without apply_patch command)
532
- if (argv.length === 1) {
533
- try {
534
- parsePatch(argv[0])
535
- return {
536
- type: MaybeApplyPatchVerified.CorrectnessError,
537
- error: new Error(ApplyPatchError.ImplicitInvocation),
538
- }
539
- } catch {
540
- // Not a patch, continue
541
- }
542
- }
543
-
544
- const result = maybeParseApplyPatch(argv)
545
-
546
- switch (result.type) {
547
- case MaybeApplyPatch.Body:
548
- const { args } = result
549
- const effectiveCwd = args.workdir ? path.resolve(cwd, args.workdir) : cwd
550
- const changes = new Map<string, ApplyPatchFileChange>()
551
-
552
- for (const hunk of args.hunks) {
553
- const resolvedPath = path.resolve(
554
- effectiveCwd,
555
- hunk.type === "update" && hunk.move_path ? hunk.move_path : hunk.path,
556
- )
557
-
558
- switch (hunk.type) {
559
- case "add":
560
- changes.set(resolvedPath, {
561
- type: "add",
562
- content: hunk.contents,
563
- })
564
- break
565
-
566
- case "delete":
567
- // For delete, we need to read the current content
568
- const deletePath = path.resolve(effectiveCwd, hunk.path)
569
- try {
570
- const content = await fs.readFile(deletePath, "utf-8")
571
- changes.set(resolvedPath, {
572
- type: "delete",
573
- content,
574
- })
575
- } catch (error) {
576
- return {
577
- type: MaybeApplyPatchVerified.CorrectnessError,
578
- error: new Error(`Failed to read file for deletion: ${deletePath}`),
579
- }
580
- }
581
- break
582
-
583
- case "update":
584
- const updatePath = path.resolve(effectiveCwd, hunk.path)
585
- try {
586
- const fileUpdate = deriveNewContentsFromChunks(updatePath, hunk.chunks)
587
- changes.set(resolvedPath, {
588
- type: "update",
589
- unified_diff: fileUpdate.unified_diff,
590
- move_path: hunk.move_path ? path.resolve(effectiveCwd, hunk.move_path) : undefined,
591
- new_content: fileUpdate.content,
592
- })
593
- } catch (error) {
594
- return {
595
- type: MaybeApplyPatchVerified.CorrectnessError,
596
- error: error as Error,
597
- }
598
- }
599
- break
600
- }
601
- }
602
-
603
- return {
604
- type: MaybeApplyPatchVerified.Body,
605
- action: {
606
- changes,
607
- patch: args.patch,
608
- cwd: effectiveCwd,
609
- },
610
- }
611
-
612
- case MaybeApplyPatch.PatchParseError:
613
- return {
614
- type: MaybeApplyPatchVerified.CorrectnessError,
615
- error: result.error,
616
- }
617
-
618
- case MaybeApplyPatch.NotApplyPatch:
619
- return { type: MaybeApplyPatchVerified.NotApplyPatch }
620
- }
621
- }
622
- }