saeeol 1.2.1 → 1.2.2

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 (113) hide show
  1. package/package.json +11 -11
  2. package/src/cli/cmd/tui/component/dialog/dialog-agent.tsx +32 -0
  3. package/src/cli/cmd/tui/component/dialog/dialog-command.tsx +190 -0
  4. package/src/cli/cmd/tui/component/dialog/dialog-console-org.tsx +103 -0
  5. package/src/cli/cmd/tui/component/dialog/dialog-go-upsell.tsx +159 -0
  6. package/src/cli/cmd/tui/component/dialog/dialog-mcp.tsx +86 -0
  7. package/src/cli/cmd/tui/component/dialog/dialog-model.tsx +238 -0
  8. package/src/cli/cmd/tui/component/dialog/dialog-provider.tsx +343 -0
  9. package/src/cli/cmd/tui/component/dialog/dialog-session-delete-failed.tsx +103 -0
  10. package/src/cli/cmd/tui/component/dialog/dialog-session-list.tsx +301 -0
  11. package/src/cli/cmd/tui/component/dialog/dialog-session-rename.tsx +35 -0
  12. package/src/cli/cmd/tui/component/dialog/dialog-skill.tsx +37 -0
  13. package/src/cli/cmd/tui/component/dialog/dialog-stash.tsx +87 -0
  14. package/src/cli/cmd/tui/component/dialog/dialog-status.tsx +190 -0
  15. package/src/cli/cmd/tui/component/dialog/dialog-tag.tsx +44 -0
  16. package/src/cli/cmd/tui/component/dialog/dialog-theme-list.tsx +50 -0
  17. package/src/cli/cmd/tui/component/dialog/dialog-variant.tsx +39 -0
  18. package/src/cli/cmd/tui/component/dialog/dialog-workspace-create.tsx +200 -0
  19. package/src/cli/cmd/tui/component/dialog/dialog-workspace-unavailable.tsx +81 -0
  20. package/src/cli/cmd/tui/component/dialog-agent.tsx +1 -32
  21. package/src/cli/cmd/tui/component/dialog-command.tsx +1 -190
  22. package/src/cli/cmd/tui/component/dialog-console-org.tsx +1 -103
  23. package/src/cli/cmd/tui/component/dialog-go-upsell.tsx +1 -159
  24. package/src/cli/cmd/tui/component/dialog-mcp.tsx +1 -86
  25. package/src/cli/cmd/tui/component/dialog-model.tsx +1 -238
  26. package/src/cli/cmd/tui/component/dialog-provider.tsx +1 -343
  27. package/src/cli/cmd/tui/component/dialog-session-delete-failed.tsx +1 -103
  28. package/src/cli/cmd/tui/component/dialog-session-list.tsx +1 -301
  29. package/src/cli/cmd/tui/component/dialog-session-rename.tsx +1 -35
  30. package/src/cli/cmd/tui/component/dialog-skill.tsx +1 -37
  31. package/src/cli/cmd/tui/component/dialog-stash.tsx +1 -87
  32. package/src/cli/cmd/tui/component/dialog-status.tsx +1 -190
  33. package/src/cli/cmd/tui/component/dialog-tag.tsx +1 -44
  34. package/src/cli/cmd/tui/component/dialog-theme-list.tsx +1 -50
  35. package/src/cli/cmd/tui/component/dialog-variant.tsx +1 -39
  36. package/src/cli/cmd/tui/component/dialog-workspace-create.tsx +1 -200
  37. package/src/cli/cmd/tui/component/dialog-workspace-unavailable.tsx +1 -81
  38. package/src/tool/apply_patch.ts +1 -334
  39. package/src/tool/bash.ts +1 -656
  40. package/src/tool/core/external-directory.ts +55 -0
  41. package/src/tool/core/invalid.ts +21 -0
  42. package/src/tool/core/recall.ts +164 -0
  43. package/src/tool/core/recall.txt +12 -0
  44. package/src/tool/core/schema.ts +16 -0
  45. package/src/tool/core/tool.ts +162 -0
  46. package/src/tool/core/truncate.ts +160 -0
  47. package/src/tool/core/truncation-dir.ts +4 -0
  48. package/src/tool/diagnostics.ts +1 -20
  49. package/src/tool/edit-replacers.ts +1 -288
  50. package/src/tool/edit-utils.ts +1 -86
  51. package/src/tool/edit.ts +1 -262
  52. package/src/tool/external-directory.ts +1 -55
  53. package/src/tool/file/apply_patch.ts +334 -0
  54. package/src/tool/file/apply_patch.txt +33 -0
  55. package/src/tool/file/bash.ts +656 -0
  56. package/src/tool/file/bash.txt +119 -0
  57. package/src/tool/file/edit-replacers.ts +288 -0
  58. package/src/tool/file/edit-utils.ts +86 -0
  59. package/src/tool/file/edit.ts +262 -0
  60. package/src/tool/file/edit.txt +10 -0
  61. package/src/tool/file/read.ts +389 -0
  62. package/src/tool/file/read.txt +14 -0
  63. package/src/tool/file/write.ts +114 -0
  64. package/src/tool/file/write.txt +8 -0
  65. package/src/tool/glob.ts +1 -115
  66. package/src/tool/grep.ts +1 -151
  67. package/src/tool/integration/diagnostics.ts +20 -0
  68. package/src/tool/integration/lsp.ts +113 -0
  69. package/src/tool/integration/lsp.txt +24 -0
  70. package/src/tool/integration/mcp-exa.ts +73 -0
  71. package/src/tool/integration/package.ts +168 -0
  72. package/src/tool/integration/registry.ts +375 -0
  73. package/src/tool/invalid.ts +1 -21
  74. package/src/tool/lsp.ts +1 -113
  75. package/src/tool/mcp-exa.ts +1 -73
  76. package/src/tool/package.ts +1 -168
  77. package/src/tool/plan.ts +1 -30
  78. package/src/tool/question.ts +1 -52
  79. package/src/tool/read.ts +1 -389
  80. package/src/tool/recall.ts +1 -164
  81. package/src/tool/registry.ts +1 -375
  82. package/src/tool/schema.ts +1 -16
  83. package/src/tool/search/glob.ts +115 -0
  84. package/src/tool/search/glob.txt +6 -0
  85. package/src/tool/search/grep.ts +151 -0
  86. package/src/tool/search/grep.txt +8 -0
  87. package/src/tool/search/warpgrep.ts +107 -0
  88. package/src/tool/search/warpgrep.txt +10 -0
  89. package/src/tool/search/webfetch.ts +202 -0
  90. package/src/tool/search/webfetch.txt +13 -0
  91. package/src/tool/search/websearch.ts +71 -0
  92. package/src/tool/search/websearch.txt +14 -0
  93. package/src/tool/skill.ts +1 -91
  94. package/src/tool/task.ts +1 -197
  95. package/src/tool/todo.ts +1 -62
  96. package/src/tool/tool.ts +1 -162
  97. package/src/tool/truncate.ts +1 -160
  98. package/src/tool/truncation-dir.ts +1 -4
  99. package/src/tool/warpgrep.ts +1 -107
  100. package/src/tool/webfetch.ts +1 -202
  101. package/src/tool/websearch.ts +1 -71
  102. package/src/tool/workflow/plan-enter.txt +14 -0
  103. package/src/tool/workflow/plan-exit.txt +13 -0
  104. package/src/tool/workflow/plan.ts +30 -0
  105. package/src/tool/workflow/question.ts +52 -0
  106. package/src/tool/workflow/question.txt +11 -0
  107. package/src/tool/workflow/skill.ts +91 -0
  108. package/src/tool/workflow/skill.txt +5 -0
  109. package/src/tool/workflow/task.ts +197 -0
  110. package/src/tool/workflow/task.txt +57 -0
  111. package/src/tool/workflow/todo.ts +62 -0
  112. package/src/tool/workflow/todowrite.txt +167 -0
  113. package/src/tool/write.ts +1 -114
@@ -0,0 +1,119 @@
1
+ Executes a given bash command in a persistent shell session with optional timeout, ensuring proper handling and security measures.
2
+
3
+ Be aware: OS: ${os}, Shell: ${shell}
4
+
5
+ All commands run in the current working directory by default. Use the `workdir` parameter if you need to run a command in a different directory. AVOID using `cd <directory> && <command>` patterns - use `workdir` instead.
6
+
7
+ Use `${tmp}` for temporary work outside the workspace. This directory has already been created, already exists, and is pre-approved for external directory access.
8
+
9
+ IMPORTANT: This tool is for terminal operations like git, npm, docker, etc. DO NOT use it for file operations (reading, writing, editing, searching, finding files) - use the specialized tools for this instead.
10
+
11
+ Before executing the command, please follow these steps:
12
+
13
+ 1. Directory Verification:
14
+ - If the command will create new directories or files, first use `ls` to verify the parent directory exists and is the correct location
15
+ - For example, before running "mkdir foo/bar", first use `ls foo` to check that "foo" exists and is the intended parent directory
16
+
17
+ 2. Command Execution:
18
+ - Always quote file paths that contain spaces with double quotes (e.g., rm "path with spaces/file.txt")
19
+ - Examples of proper quoting:
20
+ - mkdir "/Users/name/My Documents" (correct)
21
+ - mkdir /Users/name/My Documents (incorrect - will fail)
22
+ - python "/path/with spaces/script.py" (correct)
23
+ - python /path/with spaces/script.py (incorrect - will fail)
24
+ - After ensuring proper quoting, execute the command.
25
+ - Capture the output of the command.
26
+
27
+ Usage notes:
28
+ - The command argument is required.
29
+ - You can specify an optional timeout in milliseconds. If not specified, commands will time out after 120000ms (2 minutes).
30
+ - It is very helpful if you write a clear, concise description of what this command does in 5-10 words.
31
+ - If the output exceeds ${maxLines} lines or ${maxBytes} bytes, it will be truncated and the full output will be written to a file. You can use Read with offset/limit to read specific sections or Grep to search the full content. Do NOT use `head`, `tail`, or other truncation commands to limit output; the full output will already be captured to a file for more precise searching.
32
+
33
+ - Avoid using Bash with the `find`, `grep`, `cat`, `head`, `tail`, `sed`, `awk`, or `echo` commands, unless explicitly instructed or when these commands are truly necessary for the task. Instead, always prefer using the dedicated tools for these commands:
34
+ - File search: Use Glob (NOT find or ls)
35
+ - Content search: Use Grep (NOT grep or rg)
36
+ - Read files: Use Read (NOT cat/head/tail)
37
+ - Edit files: Use Edit (NOT sed/awk)
38
+ - Write files: Use Write (NOT echo >/cat <<EOF)
39
+ - Communication: Output text directly (NOT echo/printf)
40
+ - When issuing multiple commands:
41
+ - If the commands are independent and can run in parallel, make multiple Bash tool calls in a single message. For example, if you need to run "git status" and "git diff", send a single message with two Bash tool calls in parallel.
42
+ - ${chaining}
43
+ - Use ';' only when you need to run commands sequentially but don't care if earlier commands fail
44
+ - DO NOT use newlines to separate commands (newlines are ok in quoted strings)
45
+ - AVOID using `cd <directory> && <command>`. Use the `workdir` parameter to change directories instead.
46
+ <good-example>
47
+ Use workdir="/foo/bar" with command: pytest tests
48
+ </good-example>
49
+ <bad-example>
50
+ cd /foo/bar && pytest tests
51
+ </bad-example>
52
+
53
+ # Committing changes with git
54
+
55
+ Only create commits when requested by the user. If unclear, ask first. When the user asks you to create a new git commit, follow these steps carefully:
56
+
57
+ Git Safety Protocol:
58
+ - NEVER update the git config
59
+ - NEVER run destructive/irreversible git commands (like push --force, hard reset, etc) unless the user explicitly requests them
60
+ - NEVER skip hooks (--no-verify, --no-gpg-sign, etc) unless the user explicitly requests it
61
+ - NEVER run force push to main/master, warn the user if they request it
62
+ - Avoid git commit --amend. ONLY use --amend when ALL conditions are met:
63
+ (1) User explicitly requested amend, OR the commit succeeded and pre-commit hooks auto-modified files that need including — verify by checking `git log` that HEAD is the new commit before amending
64
+ (2) HEAD commit was created by you in this conversation (verify: git log -1 --format='%an %ae')
65
+ (3) Commit has NOT been pushed to remote (verify: git status shows "Your branch is ahead")
66
+ - CRITICAL: If commit FAILED or was REJECTED by hook, NEVER amend - fix the issue and create a NEW commit
67
+ - CRITICAL: If you already pushed to remote, NEVER amend unless user explicitly requests it (requires force push)
68
+ - NEVER commit changes unless the user explicitly asks you to. It is VERY IMPORTANT to only commit when explicitly asked, otherwise the user will feel that you are being too proactive.
69
+
70
+ 1. You can call multiple tools in a single response. When multiple independent pieces of information are requested and all commands are likely to succeed, run multiple tool calls in parallel for optimal performance. run the following bash commands in parallel, each using the Bash tool:
71
+ - Run a git status command to see all untracked files.
72
+ - Run a git diff command to see both staged and unstaged changes that will be committed.
73
+ - Run a git log command to see recent commit messages, so that you can follow this repository's commit message style.
74
+ 2. Analyze all staged changes (both previously staged and newly added) and draft a commit message:
75
+ - Summarize the nature of the changes (eg. new feature, enhancement to an existing feature, bug fix, refactoring, test, docs, etc.). Ensure the message accurately reflects the changes and their purpose (i.e. "add" means a wholly new feature, "update" means an enhancement to an existing feature, "fix" means a bug fix, etc.).
76
+ - Do not commit files that likely contain secrets (.env, credentials.json, etc.). Warn the user if they specifically request to commit those files
77
+ - Draft a concise (1-2 sentences) commit message that focuses on the "why" rather than the "what"
78
+ - Ensure it accurately reflects the changes and their purpose
79
+ 3. You can call multiple tools in a single response. When multiple independent pieces of information are requested and all commands are likely to succeed, run multiple tool calls in parallel for optimal performance. run the following commands:
80
+ - Add relevant untracked files to the staging area.
81
+ - Create the commit with a message
82
+ - Run git status after the commit completes to verify success.
83
+ Note: git status depends on the commit completing, so run it sequentially after the commit.
84
+ 4. If the commit fails due to pre-commit hook, fix the issue and create a NEW commit (see amend rules above)
85
+
86
+ Important notes:
87
+ - NEVER run additional commands to read or explore code, besides git bash commands
88
+ - NEVER use the TodoWrite or Task tools
89
+ - DO NOT push to the remote repository unless the user explicitly asks you to do so
90
+ - IMPORTANT: Never use git commands with the -i flag (like git rebase -i or git add -i) since they require interactive input which is not supported.
91
+ - If there are no changes to commit (i.e., no untracked files and no modifications), do not create an empty commit
92
+
93
+ # Creating pull requests
94
+ Use the gh command via the Bash tool for ALL GitHub-related tasks including working with issues, pull requests, checks, and releases. If given a GitHub URL use the gh command to get the information needed.
95
+
96
+ IMPORTANT: When the user asks you to create a pull request, follow these steps carefully:
97
+
98
+ 1. You can call multiple tools in a single response. When multiple independent pieces of information are requested and all commands are likely to succeed, run multiple tool calls in parallel for optimal performance. run the following bash commands in parallel using the Bash tool, in order to understand the current state of the branch since it diverged from the main branch:
99
+ - Run a git status command to see all untracked files
100
+ - Run a git diff command to see both staged and unstaged changes that will be committed
101
+ - Check if the current branch tracks a remote branch and is up to date with the remote, so you know if you need to push to the remote
102
+ - Run a git log command and `git diff [base-branch]...HEAD` to understand the full commit history for the current branch (from the time it diverged from the base branch)
103
+ 2. Analyze all changes that will be included in the pull request, making sure to look at all relevant commits (NOT just the latest commit, but ALL commits that will be included in the pull request!!!), and draft a pull request summary
104
+ 3. You can call multiple tools in a single response. When multiple independent pieces of information are requested and all commands are likely to succeed, run multiple tool calls in parallel for optimal performance. run the following commands in parallel:
105
+ - Create new branch if needed
106
+ - Push to remote with -u flag if needed
107
+ - Create PR using gh pr create with the format below. Use a HEREDOC to pass the body to ensure correct formatting.
108
+ <example>
109
+ gh pr create --title "the pr title" --body "$(cat <<'EOF'
110
+ ## Summary
111
+ <1-3 bullet points>
112
+ </example>
113
+
114
+ Important:
115
+ - DO NOT use the TodoWrite or Task tools
116
+ - Return the PR URL when you're done, so the user can see it
117
+
118
+ # Other common operations
119
+ - View comments on a GitHub PR: gh api repos/foo/bar/pulls/123/comments
@@ -0,0 +1,288 @@
1
+ import { levenshtein, SINGLE_CANDIDATE_SIMILARITY_THRESHOLD, MULTIPLE_CANDIDATES_SIMILARITY_THRESHOLD } from "./edit-utils"
2
+
3
+ export type Replacer = (content: string, find: string) => Generator<string, void, unknown>
4
+
5
+ export const SimpleReplacer: Replacer = function* (_content, find) {
6
+ yield find
7
+ }
8
+
9
+ export const LineTrimmedReplacer: Replacer = function* (content, find) {
10
+ const originalLines = content.split("\n")
11
+ const searchLines = find.split("\n")
12
+ if (searchLines[searchLines.length - 1] === "") {
13
+ searchLines.pop()
14
+ }
15
+ for (let i = 0; i <= originalLines.length - searchLines.length; i++) {
16
+ let matches = true
17
+ for (let j = 0; j < searchLines.length; j++) {
18
+ const originalTrimmed = originalLines[i + j].trim()
19
+ const searchTrimmed = searchLines[j].trim()
20
+ if (originalTrimmed !== searchTrimmed) {
21
+ matches = false
22
+ break
23
+ }
24
+ }
25
+ if (matches) {
26
+ let matchStartIndex = 0
27
+ for (let k = 0; k < i; k++) {
28
+ matchStartIndex += originalLines[k].length + 1
29
+ }
30
+ let matchEndIndex = matchStartIndex
31
+ for (let k = 0; k < searchLines.length; k++) {
32
+ matchEndIndex += originalLines[i + k].length
33
+ if (k < searchLines.length - 1) {
34
+ matchEndIndex += 1
35
+ }
36
+ }
37
+ yield content.substring(matchStartIndex, matchEndIndex)
38
+ }
39
+ }
40
+ }
41
+
42
+ export const BlockAnchorReplacer: Replacer = function* (content, find) {
43
+ const originalLines = content.split("\n")
44
+ const searchLines = find.split("\n")
45
+ if (searchLines.length < 3) return
46
+ if (searchLines[searchLines.length - 1] === "") {
47
+ searchLines.pop()
48
+ }
49
+ const firstLineSearch = searchLines[0].trim()
50
+ const lastLineSearch = searchLines[searchLines.length - 1].trim()
51
+ const searchBlockSize = searchLines.length
52
+ const candidates: Array<{ startLine: number; endLine: number }> = []
53
+ for (let i = 0; i < originalLines.length; i++) {
54
+ if (originalLines[i].trim() !== firstLineSearch) continue
55
+ for (let j = i + 2; j < originalLines.length; j++) {
56
+ if (originalLines[j].trim() === lastLineSearch) {
57
+ candidates.push({ startLine: i, endLine: j })
58
+ break
59
+ }
60
+ }
61
+ }
62
+ if (candidates.length === 0) return
63
+ if (candidates.length === 1) {
64
+ const { startLine, endLine } = candidates[0]
65
+ const actualBlockSize = endLine - startLine + 1
66
+ let similarity = 0
67
+ const linesToCheck = Math.min(searchBlockSize - 2, actualBlockSize - 2)
68
+ if (linesToCheck > 0) {
69
+ for (let j = 1; j < searchBlockSize - 1 && j < actualBlockSize - 1; j++) {
70
+ const originalLine = originalLines[startLine + j].trim()
71
+ const searchLine = searchLines[j].trim()
72
+ const maxLen = Math.max(originalLine.length, searchLine.length)
73
+ if (maxLen === 0) continue
74
+ const distance = levenshtein(originalLine, searchLine)
75
+ similarity += (1 - distance / maxLen) / linesToCheck
76
+ if (similarity >= SINGLE_CANDIDATE_SIMILARITY_THRESHOLD) break
77
+ }
78
+ } else {
79
+ similarity = 1.0
80
+ }
81
+ if (similarity >= SINGLE_CANDIDATE_SIMILARITY_THRESHOLD) {
82
+ let matchStartIndex = 0
83
+ for (let k = 0; k < startLine; k++) {
84
+ matchStartIndex += originalLines[k].length + 1
85
+ }
86
+ let matchEndIndex = matchStartIndex
87
+ for (let k = startLine; k <= endLine; k++) {
88
+ matchEndIndex += originalLines[k].length
89
+ if (k < endLine) matchEndIndex += 1
90
+ }
91
+ yield content.substring(matchStartIndex, matchEndIndex)
92
+ }
93
+ return
94
+ }
95
+ let bestMatch: { startLine: number; endLine: number } | null = null
96
+ let maxSimilarity = -1
97
+ for (const candidate of candidates) {
98
+ const { startLine, endLine } = candidate
99
+ const actualBlockSize = endLine - startLine + 1
100
+ let similarity = 0
101
+ const linesToCheck = Math.min(searchBlockSize - 2, actualBlockSize - 2)
102
+ if (linesToCheck > 0) {
103
+ for (let j = 1; j < searchBlockSize - 1 && j < actualBlockSize - 1; j++) {
104
+ const originalLine = originalLines[startLine + j].trim()
105
+ const searchLine = searchLines[j].trim()
106
+ const maxLen = Math.max(originalLine.length, searchLine.length)
107
+ if (maxLen === 0) continue
108
+ const distance = levenshtein(originalLine, searchLine)
109
+ similarity += 1 - distance / maxLen
110
+ }
111
+ similarity /= linesToCheck
112
+ } else {
113
+ similarity = 1.0
114
+ }
115
+ if (similarity > maxSimilarity) {
116
+ maxSimilarity = similarity
117
+ bestMatch = candidate
118
+ }
119
+ }
120
+ if (maxSimilarity >= MULTIPLE_CANDIDATES_SIMILARITY_THRESHOLD && bestMatch) {
121
+ const { startLine, endLine } = bestMatch
122
+ let matchStartIndex = 0
123
+ for (let k = 0; k < startLine; k++) {
124
+ matchStartIndex += originalLines[k].length + 1
125
+ }
126
+ let matchEndIndex = matchStartIndex
127
+ for (let k = startLine; k <= endLine; k++) {
128
+ matchEndIndex += originalLines[k].length
129
+ if (k < endLine) matchEndIndex += 1
130
+ }
131
+ yield content.substring(matchStartIndex, matchEndIndex)
132
+ }
133
+ }
134
+
135
+ export const WhitespaceNormalizedReplacer: Replacer = function* (content, find) {
136
+ const normalizeWhitespace = (text: string) => text.replace(/\s+/g, " ").trim()
137
+ const normalizedFind = normalizeWhitespace(find)
138
+ const lines = content.split("\n")
139
+ for (let i = 0; i < lines.length; i++) {
140
+ const line = lines[i]
141
+ if (normalizeWhitespace(line) === normalizedFind) {
142
+ yield line
143
+ } else {
144
+ const normalizedLine = normalizeWhitespace(line)
145
+ if (normalizedLine.includes(normalizedFind)) {
146
+ const words = find.trim().split(/\s+/)
147
+ if (words.length > 0) {
148
+ const pattern = words.map((word) => word.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("\\s+")
149
+ try {
150
+ const regex = new RegExp(pattern)
151
+ const match = line.match(regex)
152
+ if (match) yield match[0]
153
+ } catch {
154
+ // Invalid regex pattern, skip
155
+ }
156
+ }
157
+ }
158
+ }
159
+ }
160
+ const findLines = find.split("\n")
161
+ if (findLines.length > 1) {
162
+ for (let i = 0; i <= lines.length - findLines.length; i++) {
163
+ const block = lines.slice(i, i + findLines.length)
164
+ if (normalizeWhitespace(block.join("\n")) === normalizedFind) {
165
+ yield block.join("\n")
166
+ }
167
+ }
168
+ }
169
+ }
170
+
171
+ export const IndentationFlexibleReplacer: Replacer = function* (content, find) {
172
+ const removeIndentation = (text: string) => {
173
+ const lines = text.split("\n")
174
+ const nonEmptyLines = lines.filter((line) => line.trim().length > 0)
175
+ if (nonEmptyLines.length === 0) return text
176
+ const minIndent = Math.min(
177
+ ...nonEmptyLines.map((line) => {
178
+ const match = line.match(/^(\s*)/)
179
+ return match ? match[1].length : 0
180
+ }),
181
+ )
182
+ return lines.map((line) => (line.trim().length === 0 ? line : line.slice(minIndent))).join("\n")
183
+ }
184
+ const normalizedFind = removeIndentation(find)
185
+ const contentLines = content.split("\n")
186
+ const findLines = find.split("\n")
187
+ for (let i = 0; i <= contentLines.length - findLines.length; i++) {
188
+ const block = contentLines.slice(i, i + findLines.length).join("\n")
189
+ if (removeIndentation(block) === normalizedFind) {
190
+ yield block
191
+ }
192
+ }
193
+ }
194
+
195
+ export const EscapeNormalizedReplacer: Replacer = function* (content, find) {
196
+ const unescapeString = (str: string): string => {
197
+ return str.replace(/\\(n|t|r|'|"|`|\\|\n|\$)/g, (_match, capturedChar: string) => {
198
+ switch (capturedChar) {
199
+ case "n": return "\n"
200
+ case "t": return "\t"
201
+ case "r": return "\r"
202
+ case "'": return "'"
203
+ case '"': return '"'
204
+ case "`": return "`"
205
+ case "\\": return "\\"
206
+ case "\n": return "\n"
207
+ case "$": return "$"
208
+ default: return capturedChar
209
+ }
210
+ })
211
+ }
212
+ const unescapedFind = unescapeString(find)
213
+ if (content.includes(unescapedFind)) {
214
+ yield unescapedFind
215
+ }
216
+ const lines = content.split("\n")
217
+ const findLines = unescapedFind.split("\n")
218
+ for (let i = 0; i <= lines.length - findLines.length; i++) {
219
+ const block = lines.slice(i, i + findLines.length).join("\n")
220
+ const unescapedBlock = unescapeString(block)
221
+ if (unescapedBlock === unescapedFind) {
222
+ yield block
223
+ }
224
+ }
225
+ }
226
+
227
+ export const MultiOccurrenceReplacer: Replacer = function* (content, find) {
228
+ let startIndex = 0
229
+ while (true) {
230
+ const index = content.indexOf(find, startIndex)
231
+ if (index === -1) break
232
+ yield find
233
+ startIndex = index + find.length
234
+ }
235
+ }
236
+
237
+ export const TrimmedBoundaryReplacer: Replacer = function* (content, find) {
238
+ const trimmedFind = find.trim()
239
+ if (trimmedFind === find) return
240
+ if (content.includes(trimmedFind)) {
241
+ yield trimmedFind
242
+ }
243
+ const lines = content.split("\n")
244
+ const findLines = find.split("\n")
245
+ for (let i = 0; i <= lines.length - findLines.length; i++) {
246
+ const block = lines.slice(i, i + findLines.length).join("\n")
247
+ if (block.trim() === trimmedFind) {
248
+ yield block
249
+ }
250
+ }
251
+ }
252
+
253
+ export const ContextAwareReplacer: Replacer = function* (content, find) {
254
+ const findLines = find.split("\n")
255
+ if (findLines.length < 3) return
256
+ if (findLines[findLines.length - 1] === "") {
257
+ findLines.pop()
258
+ }
259
+ const contentLines = content.split("\n")
260
+ const firstLine = findLines[0].trim()
261
+ const lastLine = findLines[findLines.length - 1].trim()
262
+ for (let i = 0; i < contentLines.length; i++) {
263
+ if (contentLines[i].trim() !== firstLine) continue
264
+ for (let j = i + 2; j < contentLines.length; j++) {
265
+ if (contentLines[j].trim() === lastLine) {
266
+ const blockLines = contentLines.slice(i, j + 1)
267
+ const block = blockLines.join("\n")
268
+ if (blockLines.length === findLines.length) {
269
+ let matchingLines = 0
270
+ let totalNonEmptyLines = 0
271
+ for (let k = 1; k < blockLines.length - 1; k++) {
272
+ const blockLine = blockLines[k].trim()
273
+ const findLine = findLines[k].trim()
274
+ if (blockLine.length > 0 || findLine.length > 0) {
275
+ totalNonEmptyLines++
276
+ if (blockLine === findLine) matchingLines++
277
+ }
278
+ }
279
+ if (totalNonEmptyLines === 0 || matchingLines / totalNonEmptyLines >= 0.5) {
280
+ yield block
281
+ break
282
+ }
283
+ }
284
+ break
285
+ }
286
+ }
287
+ }
288
+ }
@@ -0,0 +1,86 @@
1
+ import { createTwoFilesPatch, diffLines } from "diff"
2
+ import { Snapshot } from "@/snapshot"
3
+
4
+ export const SINGLE_CANDIDATE_SIMILARITY_THRESHOLD = 0.0
5
+ export const MULTIPLE_CANDIDATES_SIMILARITY_THRESHOLD = 0.3
6
+
7
+ export function levenshtein(a: string, b: string): number {
8
+ if (a === "" || b === "") {
9
+ return Math.max(a.length, b.length)
10
+ }
11
+ const matrix = Array.from({ length: a.length + 1 }, (_, i) =>
12
+ Array.from({ length: b.length + 1 }, (_, j) => (i === 0 ? j : j === 0 ? i : 0)),
13
+ )
14
+ for (let i = 1; i <= a.length; i++) {
15
+ for (let j = 1; j <= b.length; j++) {
16
+ const cost = a[i - 1] === b[j - 1] ? 0 : 1
17
+ matrix[i][j] = Math.min(matrix[i - 1][j] + 1, matrix[i][j - 1] + 1, matrix[i - 1][j - 1] + cost)
18
+ }
19
+ }
20
+ return matrix[a.length][b.length]
21
+ }
22
+
23
+ const MAX_DIFF_CONTENT = 500_000
24
+ export function buildFileDiff(file: string, before: string, after: string): Snapshot.FileDiff {
25
+ const tooLarge = before.length > MAX_DIFF_CONTENT || after.length > MAX_DIFF_CONTENT
26
+ let additions = 0
27
+ let deletions = 0
28
+ if (!tooLarge) {
29
+ for (const change of diffLines(before, after)) {
30
+ if (change.added) additions += change.count || 0
31
+ if (change.removed) deletions += change.count || 0
32
+ }
33
+ }
34
+ return {
35
+ file,
36
+ patch: tooLarge ? "" : createTwoFilesPatch(file, file, before, after),
37
+ additions,
38
+ deletions,
39
+ }
40
+ }
41
+
42
+ export function normalizeLineEndings(text: string): string {
43
+ return text.replaceAll("\r\n", "\n")
44
+ }
45
+
46
+ export function detectLineEnding(text: string): "\n" | "\r\n" {
47
+ return text.includes("\r\n") ? "\r\n" : "\n"
48
+ }
49
+
50
+ export function convertToLineEnding(text: string, ending: "\n" | "\r\n"): string {
51
+ if (ending === "\n") return text
52
+ return text.replaceAll("\n", "\r\n")
53
+ }
54
+
55
+ export function trimDiff(diff: string): string {
56
+ const lines = diff.split("\n")
57
+ const contentLines = lines.filter(
58
+ (line) =>
59
+ (line.startsWith("+") || line.startsWith("-") || line.startsWith(" ")) &&
60
+ !line.startsWith("---") &&
61
+ !line.startsWith("+++"),
62
+ )
63
+ if (contentLines.length === 0) return diff
64
+ let min = Infinity
65
+ for (const line of contentLines) {
66
+ const content = line.slice(1)
67
+ if (content.trim().length > 0) {
68
+ const match = content.match(/^(\s*)/)
69
+ if (match) min = Math.min(min, match[1].length)
70
+ }
71
+ }
72
+ if (min === Infinity || min === 0) return diff
73
+ const trimmedLines = lines.map((line) => {
74
+ if (
75
+ (line.startsWith("+") || line.startsWith("-") || line.startsWith(" ")) &&
76
+ !line.startsWith("---") &&
77
+ !line.startsWith("+++")
78
+ ) {
79
+ const prefix = line[0]
80
+ const content = line.slice(1)
81
+ return prefix + content.slice(min)
82
+ }
83
+ return line
84
+ })
85
+ return trimmedLines.join("\n")
86
+ }