cerebras-cli 1.0.1 → 1.0.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 (313) hide show
  1. package/cerebras-cli-1.0.0.tgz +0 -0
  2. package/package.json +7 -88
  3. package/AGENTS.md +0 -27
  4. package/Dockerfile +0 -10
  5. package/bunfig.toml +0 -4
  6. package/parsers-config.ts +0 -239
  7. package/script/build.ts +0 -151
  8. package/script/postinstall.mjs +0 -122
  9. package/script/publish.ts +0 -256
  10. package/script/schema.ts +0 -47
  11. package/src/acp/README.md +0 -164
  12. package/src/acp/agent.ts +0 -812
  13. package/src/acp/session.ts +0 -70
  14. package/src/acp/types.ts +0 -22
  15. package/src/agent/agent.ts +0 -310
  16. package/src/agent/generate.txt +0 -75
  17. package/src/auth/index.ts +0 -70
  18. package/src/bun/index.ts +0 -152
  19. package/src/bus/global.ts +0 -10
  20. package/src/bus/index.ts +0 -142
  21. package/src/cli/bootstrap.ts +0 -17
  22. package/src/cli/cmd/acp.ts +0 -88
  23. package/src/cli/cmd/agent.ts +0 -165
  24. package/src/cli/cmd/auth.ts +0 -369
  25. package/src/cli/cmd/cmd.ts +0 -7
  26. package/src/cli/cmd/debug/config.ts +0 -15
  27. package/src/cli/cmd/debug/file.ts +0 -91
  28. package/src/cli/cmd/debug/index.ts +0 -41
  29. package/src/cli/cmd/debug/lsp.ts +0 -47
  30. package/src/cli/cmd/debug/ripgrep.ts +0 -83
  31. package/src/cli/cmd/debug/scrap.ts +0 -15
  32. package/src/cli/cmd/debug/snapshot.ts +0 -48
  33. package/src/cli/cmd/export.ts +0 -88
  34. package/src/cli/cmd/generate.ts +0 -38
  35. package/src/cli/cmd/github.ts +0 -1200
  36. package/src/cli/cmd/import.ts +0 -98
  37. package/src/cli/cmd/mcp.ts +0 -400
  38. package/src/cli/cmd/models.ts +0 -77
  39. package/src/cli/cmd/pr.ts +0 -112
  40. package/src/cli/cmd/run.ts +0 -342
  41. package/src/cli/cmd/serve.ts +0 -31
  42. package/src/cli/cmd/session.ts +0 -106
  43. package/src/cli/cmd/stats.ts +0 -298
  44. package/src/cli/cmd/tui/app.tsx +0 -732
  45. package/src/cli/cmd/tui/attach.ts +0 -25
  46. package/src/cli/cmd/tui/component/border.tsx +0 -21
  47. package/src/cli/cmd/tui/component/dialog-agent.tsx +0 -31
  48. package/src/cli/cmd/tui/component/dialog-command.tsx +0 -124
  49. package/src/cli/cmd/tui/component/dialog-feedback.tsx +0 -160
  50. package/src/cli/cmd/tui/component/dialog-mcp.tsx +0 -86
  51. package/src/cli/cmd/tui/component/dialog-model.tsx +0 -223
  52. package/src/cli/cmd/tui/component/dialog-notification.tsx +0 -78
  53. package/src/cli/cmd/tui/component/dialog-provider.tsx +0 -222
  54. package/src/cli/cmd/tui/component/dialog-session-list.tsx +0 -97
  55. package/src/cli/cmd/tui/component/dialog-session-rename.tsx +0 -31
  56. package/src/cli/cmd/tui/component/dialog-status.tsx +0 -114
  57. package/src/cli/cmd/tui/component/dialog-tag.tsx +0 -44
  58. package/src/cli/cmd/tui/component/dialog-theme-list.tsx +0 -50
  59. package/src/cli/cmd/tui/component/logo.tsx +0 -37
  60. package/src/cli/cmd/tui/component/notification-banner.tsx +0 -58
  61. package/src/cli/cmd/tui/component/prompt/autocomplete.tsx +0 -530
  62. package/src/cli/cmd/tui/component/prompt/history.tsx +0 -107
  63. package/src/cli/cmd/tui/component/prompt/index.tsx +0 -931
  64. package/src/cli/cmd/tui/context/args.tsx +0 -14
  65. package/src/cli/cmd/tui/context/directory.ts +0 -12
  66. package/src/cli/cmd/tui/context/exit.tsx +0 -23
  67. package/src/cli/cmd/tui/context/helper.tsx +0 -25
  68. package/src/cli/cmd/tui/context/keybind.tsx +0 -111
  69. package/src/cli/cmd/tui/context/kv.tsx +0 -49
  70. package/src/cli/cmd/tui/context/local.tsx +0 -339
  71. package/src/cli/cmd/tui/context/prompt.tsx +0 -18
  72. package/src/cli/cmd/tui/context/route.tsx +0 -45
  73. package/src/cli/cmd/tui/context/sdk.tsx +0 -75
  74. package/src/cli/cmd/tui/context/sync.tsx +0 -374
  75. package/src/cli/cmd/tui/context/theme/aura.json +0 -69
  76. package/src/cli/cmd/tui/context/theme/ayu.json +0 -80
  77. package/src/cli/cmd/tui/context/theme/catppuccin-macchiato.json +0 -233
  78. package/src/cli/cmd/tui/context/theme/catppuccin.json +0 -112
  79. package/src/cli/cmd/tui/context/theme/cobalt2.json +0 -228
  80. package/src/cli/cmd/tui/context/theme/dracula.json +0 -219
  81. package/src/cli/cmd/tui/context/theme/everforest.json +0 -241
  82. package/src/cli/cmd/tui/context/theme/flexoki.json +0 -237
  83. package/src/cli/cmd/tui/context/theme/github.json +0 -233
  84. package/src/cli/cmd/tui/context/theme/gruvbox.json +0 -95
  85. package/src/cli/cmd/tui/context/theme/kanagawa.json +0 -77
  86. package/src/cli/cmd/tui/context/theme/material.json +0 -235
  87. package/src/cli/cmd/tui/context/theme/matrix.json +0 -77
  88. package/src/cli/cmd/tui/context/theme/mercury.json +0 -252
  89. package/src/cli/cmd/tui/context/theme/monokai.json +0 -221
  90. package/src/cli/cmd/tui/context/theme/nightowl.json +0 -221
  91. package/src/cli/cmd/tui/context/theme/nord.json +0 -223
  92. package/src/cli/cmd/tui/context/theme/one-dark.json +0 -84
  93. package/src/cli/cmd/tui/context/theme/orng.json +0 -245
  94. package/src/cli/cmd/tui/context/theme/palenight.json +0 -222
  95. package/src/cli/cmd/tui/context/theme/rosepine.json +0 -234
  96. package/src/cli/cmd/tui/context/theme/solarized.json +0 -223
  97. package/src/cli/cmd/tui/context/theme/synthwave84.json +0 -226
  98. package/src/cli/cmd/tui/context/theme/tokyonight.json +0 -243
  99. package/src/cli/cmd/tui/context/theme/vercel.json +0 -245
  100. package/src/cli/cmd/tui/context/theme/vesper.json +0 -218
  101. package/src/cli/cmd/tui/context/theme/zenburn.json +0 -223
  102. package/src/cli/cmd/tui/context/theme.tsx +0 -1077
  103. package/src/cli/cmd/tui/event.ts +0 -39
  104. package/src/cli/cmd/tui/routes/home.tsx +0 -104
  105. package/src/cli/cmd/tui/routes/session/dialog-message.tsx +0 -93
  106. package/src/cli/cmd/tui/routes/session/dialog-timeline.tsx +0 -37
  107. package/src/cli/cmd/tui/routes/session/footer.tsx +0 -76
  108. package/src/cli/cmd/tui/routes/session/header.tsx +0 -183
  109. package/src/cli/cmd/tui/routes/session/index.tsx +0 -1703
  110. package/src/cli/cmd/tui/routes/session/sidebar.tsx +0 -586
  111. package/src/cli/cmd/tui/spawn.ts +0 -60
  112. package/src/cli/cmd/tui/thread.ts +0 -120
  113. package/src/cli/cmd/tui/ui/dialog-alert.tsx +0 -55
  114. package/src/cli/cmd/tui/ui/dialog-confirm.tsx +0 -81
  115. package/src/cli/cmd/tui/ui/dialog-help.tsx +0 -36
  116. package/src/cli/cmd/tui/ui/dialog-prompt.tsx +0 -75
  117. package/src/cli/cmd/tui/ui/dialog-select.tsx +0 -317
  118. package/src/cli/cmd/tui/ui/dialog.tsx +0 -170
  119. package/src/cli/cmd/tui/ui/spinner.ts +0 -368
  120. package/src/cli/cmd/tui/ui/toast.tsx +0 -100
  121. package/src/cli/cmd/tui/util/clipboard.ts +0 -127
  122. package/src/cli/cmd/tui/util/editor.ts +0 -32
  123. package/src/cli/cmd/tui/util/terminal.ts +0 -114
  124. package/src/cli/cmd/tui/worker.ts +0 -63
  125. package/src/cli/cmd/uninstall.ts +0 -344
  126. package/src/cli/cmd/upgrade.ts +0 -67
  127. package/src/cli/cmd/web.ts +0 -84
  128. package/src/cli/error.ts +0 -55
  129. package/src/cli/ui.ts +0 -84
  130. package/src/cli/upgrade.ts +0 -25
  131. package/src/command/index.ts +0 -79
  132. package/src/command/template/initialize.txt +0 -10
  133. package/src/command/template/review.txt +0 -73
  134. package/src/config/config.ts +0 -886
  135. package/src/config/markdown.ts +0 -41
  136. package/src/env/index.ts +0 -26
  137. package/src/file/fzf.ts +0 -124
  138. package/src/file/ignore.ts +0 -83
  139. package/src/file/index.ts +0 -326
  140. package/src/file/ripgrep.ts +0 -391
  141. package/src/file/time.ts +0 -38
  142. package/src/file/watcher.ts +0 -89
  143. package/src/flag/flag.ts +0 -28
  144. package/src/format/formatter.ts +0 -277
  145. package/src/format/index.ts +0 -137
  146. package/src/global/index.ts +0 -52
  147. package/src/id/id.ts +0 -73
  148. package/src/ide/index.ts +0 -75
  149. package/src/index.ts +0 -158
  150. package/src/installation/index.ts +0 -194
  151. package/src/lsp/client.ts +0 -215
  152. package/src/lsp/index.ts +0 -370
  153. package/src/lsp/language.ts +0 -111
  154. package/src/lsp/server.ts +0 -1327
  155. package/src/mcp/auth.ts +0 -82
  156. package/src/mcp/index.ts +0 -576
  157. package/src/mcp/oauth-callback.ts +0 -203
  158. package/src/mcp/oauth-provider.ts +0 -132
  159. package/src/notification/index.ts +0 -101
  160. package/src/patch/index.ts +0 -622
  161. package/src/permission/index.ts +0 -198
  162. package/src/plugin/index.ts +0 -95
  163. package/src/project/bootstrap.ts +0 -31
  164. package/src/project/instance.ts +0 -68
  165. package/src/project/project.ts +0 -133
  166. package/src/project/state.ts +0 -65
  167. package/src/project/vcs.ts +0 -77
  168. package/src/provider/auth.ts +0 -143
  169. package/src/provider/models-macro.ts +0 -11
  170. package/src/provider/models.ts +0 -93
  171. package/src/provider/provider.ts +0 -996
  172. package/src/provider/sdk/openai-compatible/src/README.md +0 -5
  173. package/src/provider/sdk/openai-compatible/src/index.ts +0 -2
  174. package/src/provider/sdk/openai-compatible/src/openai-compatible-provider.ts +0 -100
  175. package/src/provider/sdk/openai-compatible/src/responses/convert-to-openai-responses-input.ts +0 -303
  176. package/src/provider/sdk/openai-compatible/src/responses/map-openai-responses-finish-reason.ts +0 -27
  177. package/src/provider/sdk/openai-compatible/src/responses/openai-config.ts +0 -18
  178. package/src/provider/sdk/openai-compatible/src/responses/openai-error.ts +0 -22
  179. package/src/provider/sdk/openai-compatible/src/responses/openai-responses-api-types.ts +0 -207
  180. package/src/provider/sdk/openai-compatible/src/responses/openai-responses-language-model.ts +0 -1713
  181. package/src/provider/sdk/openai-compatible/src/responses/openai-responses-prepare-tools.ts +0 -177
  182. package/src/provider/sdk/openai-compatible/src/responses/openai-responses-settings.ts +0 -1
  183. package/src/provider/sdk/openai-compatible/src/responses/tool/code-interpreter.ts +0 -88
  184. package/src/provider/sdk/openai-compatible/src/responses/tool/file-search.ts +0 -128
  185. package/src/provider/sdk/openai-compatible/src/responses/tool/image-generation.ts +0 -115
  186. package/src/provider/sdk/openai-compatible/src/responses/tool/local-shell.ts +0 -65
  187. package/src/provider/sdk/openai-compatible/src/responses/tool/web-search-preview.ts +0 -104
  188. package/src/provider/sdk/openai-compatible/src/responses/tool/web-search.ts +0 -103
  189. package/src/provider/transform.ts +0 -406
  190. package/src/pty/index.ts +0 -226
  191. package/src/ratelimit/index.ts +0 -185
  192. package/src/server/error.ts +0 -36
  193. package/src/server/project.ts +0 -50
  194. package/src/server/server.ts +0 -2463
  195. package/src/server/tui.ts +0 -71
  196. package/src/session/compaction.ts +0 -257
  197. package/src/session/index.ts +0 -470
  198. package/src/session/message-v2.ts +0 -641
  199. package/src/session/message.ts +0 -189
  200. package/src/session/processor.ts +0 -443
  201. package/src/session/prompt/anthropic-20250930.txt +0 -166
  202. package/src/session/prompt/anthropic.txt +0 -105
  203. package/src/session/prompt/anthropic_spoof.txt +0 -1
  204. package/src/session/prompt/beast.txt +0 -147
  205. package/src/session/prompt/build-switch.txt +0 -5
  206. package/src/session/prompt/codex.txt +0 -318
  207. package/src/session/prompt/compaction.txt +0 -12
  208. package/src/session/prompt/copilot-gpt-5.txt +0 -143
  209. package/src/session/prompt/gemini.txt +0 -155
  210. package/src/session/prompt/max-steps.txt +0 -16
  211. package/src/session/prompt/plan-reminder-anthropic.txt +0 -67
  212. package/src/session/prompt/plan.txt +0 -26
  213. package/src/session/prompt/polaris.txt +0 -107
  214. package/src/session/prompt/qwen.txt +0 -109
  215. package/src/session/prompt/summarize.txt +0 -4
  216. package/src/session/prompt/title.txt +0 -36
  217. package/src/session/prompt.ts +0 -1541
  218. package/src/session/retry.ts +0 -82
  219. package/src/session/revert.ts +0 -108
  220. package/src/session/status.ts +0 -75
  221. package/src/session/summary.ts +0 -203
  222. package/src/session/system.ts +0 -148
  223. package/src/session/todo.ts +0 -36
  224. package/src/share/share-next.ts +0 -195
  225. package/src/share/share.ts +0 -87
  226. package/src/snapshot/index.ts +0 -197
  227. package/src/storage/storage.ts +0 -226
  228. package/src/telemetry/index.ts +0 -232
  229. package/src/tool/bash.ts +0 -365
  230. package/src/tool/bash.txt +0 -128
  231. package/src/tool/batch.ts +0 -173
  232. package/src/tool/batch.txt +0 -28
  233. package/src/tool/codesearch.ts +0 -138
  234. package/src/tool/codesearch.txt +0 -12
  235. package/src/tool/edit.ts +0 -674
  236. package/src/tool/edit.txt +0 -10
  237. package/src/tool/glob.ts +0 -65
  238. package/src/tool/glob.txt +0 -6
  239. package/src/tool/grep.ts +0 -120
  240. package/src/tool/grep.txt +0 -8
  241. package/src/tool/invalid.ts +0 -17
  242. package/src/tool/ls.ts +0 -110
  243. package/src/tool/ls.txt +0 -1
  244. package/src/tool/lsp-diagnostics.ts +0 -26
  245. package/src/tool/lsp-diagnostics.txt +0 -1
  246. package/src/tool/lsp-hover.ts +0 -31
  247. package/src/tool/lsp-hover.txt +0 -1
  248. package/src/tool/multiedit.ts +0 -46
  249. package/src/tool/multiedit.txt +0 -41
  250. package/src/tool/patch.ts +0 -233
  251. package/src/tool/patch.txt +0 -1
  252. package/src/tool/read.ts +0 -217
  253. package/src/tool/read.txt +0 -12
  254. package/src/tool/registry.ts +0 -148
  255. package/src/tool/task.ts +0 -135
  256. package/src/tool/task.txt +0 -60
  257. package/src/tool/todo.ts +0 -39
  258. package/src/tool/todoread.txt +0 -14
  259. package/src/tool/todowrite.txt +0 -167
  260. package/src/tool/tool.ts +0 -66
  261. package/src/tool/webfetch.ts +0 -187
  262. package/src/tool/webfetch.txt +0 -14
  263. package/src/tool/websearch.ts +0 -150
  264. package/src/tool/websearch.txt +0 -11
  265. package/src/tool/write.ts +0 -99
  266. package/src/tool/write.txt +0 -8
  267. package/src/types/shims.d.ts +0 -3
  268. package/src/util/color.ts +0 -19
  269. package/src/util/context.ts +0 -25
  270. package/src/util/defer.ts +0 -12
  271. package/src/util/eventloop.ts +0 -20
  272. package/src/util/filesystem.ts +0 -69
  273. package/src/util/fn.ts +0 -11
  274. package/src/util/iife.ts +0 -3
  275. package/src/util/keybind.ts +0 -79
  276. package/src/util/lazy.ts +0 -11
  277. package/src/util/locale.ts +0 -81
  278. package/src/util/lock.ts +0 -98
  279. package/src/util/log.ts +0 -177
  280. package/src/util/queue.ts +0 -32
  281. package/src/util/rpc.ts +0 -42
  282. package/src/util/scrap.ts +0 -10
  283. package/src/util/signal.ts +0 -12
  284. package/src/util/timeout.ts +0 -14
  285. package/src/util/token.ts +0 -7
  286. package/src/util/wildcard.ts +0 -54
  287. package/sst-env.d.ts +0 -9
  288. package/test/bun.test.ts +0 -53
  289. package/test/config/agent-color.test.ts +0 -66
  290. package/test/config/config.test.ts +0 -503
  291. package/test/config/markdown.test.ts +0 -89
  292. package/test/file/ignore.test.ts +0 -10
  293. package/test/fixture/fixture.ts +0 -28
  294. package/test/fixture/lsp/fake-lsp-server.js +0 -77
  295. package/test/ide/ide.test.ts +0 -82
  296. package/test/keybind.test.ts +0 -317
  297. package/test/lsp/client.test.ts +0 -95
  298. package/test/patch/patch.test.ts +0 -348
  299. package/test/preload.ts +0 -38
  300. package/test/project/project.test.ts +0 -42
  301. package/test/provider/provider.test.ts +0 -1809
  302. package/test/provider/transform.test.ts +0 -305
  303. package/test/session/retry.test.ts +0 -61
  304. package/test/session/session.test.ts +0 -71
  305. package/test/snapshot/snapshot.test.ts +0 -939
  306. package/test/tool/__snapshots__/tool.test.ts.snap +0 -9
  307. package/test/tool/bash.test.ts +0 -55
  308. package/test/tool/patch.test.ts +0 -259
  309. package/test/util/iife.test.ts +0 -36
  310. package/test/util/lazy.test.ts +0 -50
  311. package/test/util/timeout.test.ts +0 -21
  312. package/test/util/wildcard.test.ts +0 -55
  313. package/tsconfig.json +0 -17
@@ -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
- }