@aria-cli/tools 1.0.12 → 1.0.14

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 (233) hide show
  1. package/dist/index.js +378 -70
  2. package/dist/network-runtime/index.js +8 -12
  3. package/dist-cjs/index.js +400 -435
  4. package/dist-cjs/network-runtime/index.js +8 -172
  5. package/package.json +8 -6
  6. package/dist/.tsbuildinfo +0 -1
  7. package/dist/ask-user-interaction.js +0 -22
  8. package/dist/cache/web-cache.js +0 -66
  9. package/dist/definitions/arion.js +0 -104
  10. package/dist/definitions/browser/browser.js +0 -418
  11. package/dist/definitions/browser/index.js +0 -4
  12. package/dist/definitions/browser/pw-downloads.js +0 -114
  13. package/dist/definitions/browser/pw-interactions.js +0 -199
  14. package/dist/definitions/browser/pw-responses.js +0 -76
  15. package/dist/definitions/browser/pw-session.js +0 -310
  16. package/dist/definitions/browser/pw-shared.js +0 -66
  17. package/dist/definitions/browser/pw-snapshot.js +0 -301
  18. package/dist/definitions/browser/pw-state.js +0 -62
  19. package/dist/definitions/browser/types.js +0 -4
  20. package/dist/definitions/code-intelligence.js +0 -470
  21. package/dist/definitions/core.js +0 -109
  22. package/dist/definitions/delegation.js +0 -512
  23. package/dist/definitions/deploy.js +0 -65
  24. package/dist/definitions/filesystem.js +0 -196
  25. package/dist/definitions/frg.js +0 -63
  26. package/dist/definitions/index.js +0 -20
  27. package/dist/definitions/memory.js +0 -123
  28. package/dist/definitions/messaging.js +0 -625
  29. package/dist/definitions/meta.js +0 -349
  30. package/dist/definitions/network.js +0 -159
  31. package/dist/definitions/outlook.js +0 -277
  32. package/dist/definitions/patch/apply-patch.js +0 -184
  33. package/dist/definitions/patch/fuzzy-match.js +0 -166
  34. package/dist/definitions/patch/index.js +0 -1
  35. package/dist/definitions/patch/patch-parser.js +0 -207
  36. package/dist/definitions/patch/sandbox-paths.js +0 -105
  37. package/dist/definitions/process/index.js +0 -4
  38. package/dist/definitions/process/process-registry.js +0 -213
  39. package/dist/definitions/process/process.js +0 -386
  40. package/dist/definitions/process/pty-keys.js +0 -254
  41. package/dist/definitions/process/session-slug.js +0 -142
  42. package/dist/definitions/quip.js +0 -195
  43. package/dist/definitions/search.js +0 -60
  44. package/dist/definitions/session-history.js +0 -69
  45. package/dist/definitions/shell.js +0 -181
  46. package/dist/definitions/slack.js +0 -180
  47. package/dist/definitions/web.js +0 -109
  48. package/dist/executors/apply-patch.js +0 -901
  49. package/dist/executors/arion.js +0 -119
  50. package/dist/executors/code-intelligence.js +0 -882
  51. package/dist/executors/deploy.js +0 -848
  52. package/dist/executors/filesystem.js +0 -1122
  53. package/dist/executors/frg-freshness.js +0 -576
  54. package/dist/executors/frg.js +0 -298
  55. package/dist/executors/index.js +0 -46
  56. package/dist/executors/learning-meta.js +0 -1146
  57. package/dist/executors/lsp-client.js +0 -296
  58. package/dist/executors/memory.js +0 -750
  59. package/dist/executors/meta.js +0 -220
  60. package/dist/executors/process-registry.js +0 -465
  61. package/dist/executors/pty-session-store.js +0 -30
  62. package/dist/executors/pty.js +0 -271
  63. package/dist/executors/restart.js +0 -119
  64. package/dist/executors/search-freshness.js +0 -195
  65. package/dist/executors/search-types.js +0 -52
  66. package/dist/executors/search.js +0 -66
  67. package/dist/executors/self-diagnose.js +0 -398
  68. package/dist/executors/session-history.js +0 -283
  69. package/dist/executors/shell-safety.js +0 -473
  70. package/dist/executors/shell.js +0 -954
  71. package/dist/executors/utils.js +0 -33
  72. package/dist/executors/web.js +0 -542
  73. package/dist/extraction/content-extraction.js +0 -235
  74. package/dist/extraction/index.js +0 -4
  75. package/dist/headless-control-contract.js +0 -967
  76. package/dist/local-control-http-auth.js +0 -2
  77. package/dist/mcp/client.js +0 -181
  78. package/dist/mcp/connection.js +0 -480
  79. package/dist/mcp/index.js +0 -10
  80. package/dist/mcp/jsonrpc.js +0 -144
  81. package/dist/mcp/types.js +0 -7
  82. package/dist/network-control-adapter.js +0 -72
  83. package/dist/network-runtime/address-types.js +0 -165
  84. package/dist/network-runtime/db-owner-fencing.js +0 -69
  85. package/dist/network-runtime/delivery-receipts.js +0 -267
  86. package/dist/network-runtime/direct-endpoint-authority.js +0 -25
  87. package/dist/network-runtime/local-control-contract.js +0 -627
  88. package/dist/network-runtime/node-store-contract.js +0 -34
  89. package/dist/network-runtime/pair-route-contract.js +0 -77
  90. package/dist/network-runtime/peer-capabilities.js +0 -28
  91. package/dist/network-runtime/peer-principal-ref.js +0 -12
  92. package/dist/network-runtime/peer-state-machine.js +0 -121
  93. package/dist/network-runtime/protocol-schemas.js +0 -205
  94. package/dist/network-runtime/runtime-bootstrap-contract.js +0 -60
  95. package/dist/outlook/desktop-session.js +0 -279
  96. package/dist/policy.js +0 -149
  97. package/dist/providers/brave.js +0 -62
  98. package/dist/providers/duckduckgo.js +0 -176
  99. package/dist/providers/exa.js +0 -63
  100. package/dist/providers/firecrawl.js +0 -55
  101. package/dist/providers/index.js +0 -7
  102. package/dist/providers/jina.js +0 -49
  103. package/dist/providers/router.js +0 -96
  104. package/dist/providers/search-provider.js +0 -32
  105. package/dist/providers/tavily.js +0 -54
  106. package/dist/quip/desktop-session.js +0 -317
  107. package/dist/registry/index.js +0 -1
  108. package/dist/registry/registry.js +0 -756
  109. package/dist/runtime-socket-local-control-client.js +0 -330
  110. package/dist/security/dns-normalization.js +0 -19
  111. package/dist/security/dns-pinning.js +0 -123
  112. package/dist/security/external-content.js +0 -91
  113. package/dist/security/ssrf.js +0 -181
  114. package/dist/slack/desktop-session.js +0 -324
  115. package/dist/tool-factory.js +0 -47
  116. package/dist/types.js +0 -7
  117. package/dist/utils/retry.js +0 -132
  118. package/dist/utils/safe-parse-json.js +0 -160
  119. package/dist/utils/url.js +0 -19
  120. package/dist-cjs/.tsbuildinfo +0 -1
  121. package/dist-cjs/ask-user-interaction.js +0 -27
  122. package/dist-cjs/cache/web-cache.js +0 -70
  123. package/dist-cjs/definitions/arion.js +0 -107
  124. package/dist-cjs/definitions/browser/browser.js +0 -421
  125. package/dist-cjs/definitions/browser/index.js +0 -8
  126. package/dist-cjs/definitions/browser/pw-downloads.js +0 -117
  127. package/dist-cjs/definitions/browser/pw-interactions.js +0 -213
  128. package/dist-cjs/definitions/browser/pw-responses.js +0 -84
  129. package/dist-cjs/definitions/browser/pw-session.js +0 -326
  130. package/dist-cjs/definitions/browser/pw-shared.js +0 -72
  131. package/dist-cjs/definitions/browser/pw-snapshot.js +0 -307
  132. package/dist-cjs/definitions/browser/pw-state.js +0 -70
  133. package/dist-cjs/definitions/browser/types.js +0 -5
  134. package/dist-cjs/definitions/code-intelligence.js +0 -473
  135. package/dist-cjs/definitions/core.js +0 -133
  136. package/dist-cjs/definitions/delegation.js +0 -515
  137. package/dist-cjs/definitions/deploy.js +0 -68
  138. package/dist-cjs/definitions/filesystem.js +0 -199
  139. package/dist-cjs/definitions/frg.js +0 -66
  140. package/dist-cjs/definitions/index.js +0 -43
  141. package/dist-cjs/definitions/memory.js +0 -126
  142. package/dist-cjs/definitions/messaging.js +0 -631
  143. package/dist-cjs/definitions/meta.js +0 -352
  144. package/dist-cjs/definitions/network.js +0 -162
  145. package/dist-cjs/definitions/outlook.js +0 -280
  146. package/dist-cjs/definitions/patch/apply-patch.js +0 -191
  147. package/dist-cjs/definitions/patch/fuzzy-match.js +0 -172
  148. package/dist-cjs/definitions/patch/index.js +0 -5
  149. package/dist-cjs/definitions/patch/patch-parser.js +0 -215
  150. package/dist-cjs/definitions/patch/sandbox-paths.js +0 -113
  151. package/dist-cjs/definitions/process/index.js +0 -8
  152. package/dist-cjs/definitions/process/process-registry.js +0 -231
  153. package/dist-cjs/definitions/process/process.js +0 -389
  154. package/dist-cjs/definitions/process/pty-keys.js +0 -259
  155. package/dist-cjs/definitions/process/session-slug.js +0 -145
  156. package/dist-cjs/definitions/quip.js +0 -198
  157. package/dist-cjs/definitions/search.js +0 -63
  158. package/dist-cjs/definitions/session-history.js +0 -72
  159. package/dist-cjs/definitions/shell.js +0 -184
  160. package/dist-cjs/definitions/slack.js +0 -183
  161. package/dist-cjs/definitions/web.js +0 -112
  162. package/dist-cjs/executors/apply-patch.js +0 -938
  163. package/dist-cjs/executors/arion.js +0 -125
  164. package/dist-cjs/executors/code-intelligence.js +0 -925
  165. package/dist-cjs/executors/deploy.js +0 -869
  166. package/dist-cjs/executors/filesystem.js +0 -1167
  167. package/dist-cjs/executors/frg-freshness.js +0 -627
  168. package/dist-cjs/executors/frg.js +0 -334
  169. package/dist-cjs/executors/index.js +0 -143
  170. package/dist-cjs/executors/learning-meta.js +0 -1165
  171. package/dist-cjs/executors/lsp-client.js +0 -310
  172. package/dist-cjs/executors/memory.js +0 -796
  173. package/dist-cjs/executors/meta.js +0 -226
  174. package/dist-cjs/executors/process-registry.js +0 -469
  175. package/dist-cjs/executors/pty-session-store.js +0 -34
  176. package/dist-cjs/executors/pty.js +0 -312
  177. package/dist-cjs/executors/restart.js +0 -155
  178. package/dist-cjs/executors/search-freshness.js +0 -234
  179. package/dist-cjs/executors/search-types.js +0 -56
  180. package/dist-cjs/executors/search.js +0 -102
  181. package/dist-cjs/executors/self-diagnose.js +0 -434
  182. package/dist-cjs/executors/session-history.js +0 -320
  183. package/dist-cjs/executors/shell-safety.js +0 -478
  184. package/dist-cjs/executors/shell.js +0 -1001
  185. package/dist-cjs/executors/utils.js +0 -73
  186. package/dist-cjs/executors/web.js +0 -547
  187. package/dist-cjs/extraction/content-extraction.js +0 -243
  188. package/dist-cjs/extraction/index.js +0 -8
  189. package/dist-cjs/headless-control-contract.js +0 -972
  190. package/dist-cjs/local-control-http-auth.js +0 -5
  191. package/dist-cjs/mcp/client.js +0 -185
  192. package/dist-cjs/mcp/connection.js +0 -484
  193. package/dist-cjs/mcp/index.js +0 -30
  194. package/dist-cjs/mcp/jsonrpc.js +0 -148
  195. package/dist-cjs/mcp/types.js +0 -8
  196. package/dist-cjs/network-control-adapter.js +0 -77
  197. package/dist-cjs/network-runtime/address-types.js +0 -168
  198. package/dist-cjs/network-runtime/db-owner-fencing.js +0 -76
  199. package/dist-cjs/network-runtime/delivery-receipts.js +0 -276
  200. package/dist-cjs/network-runtime/direct-endpoint-authority.js +0 -29
  201. package/dist-cjs/network-runtime/local-control-contract.js +0 -633
  202. package/dist-cjs/network-runtime/node-store-contract.js +0 -38
  203. package/dist-cjs/network-runtime/pair-route-contract.js +0 -80
  204. package/dist-cjs/network-runtime/peer-capabilities.js +0 -37
  205. package/dist-cjs/network-runtime/peer-principal-ref.js +0 -15
  206. package/dist-cjs/network-runtime/peer-state-machine.js +0 -129
  207. package/dist-cjs/network-runtime/protocol-schemas.js +0 -212
  208. package/dist-cjs/network-runtime/runtime-bootstrap-contract.js +0 -63
  209. package/dist-cjs/outlook/desktop-session.js +0 -318
  210. package/dist-cjs/policy.js +0 -155
  211. package/dist-cjs/providers/brave.js +0 -66
  212. package/dist-cjs/providers/duckduckgo.js +0 -180
  213. package/dist-cjs/providers/exa.js +0 -67
  214. package/dist-cjs/providers/firecrawl.js +0 -59
  215. package/dist-cjs/providers/index.js +0 -17
  216. package/dist-cjs/providers/jina.js +0 -53
  217. package/dist-cjs/providers/router.js +0 -100
  218. package/dist-cjs/providers/search-provider.js +0 -36
  219. package/dist-cjs/providers/tavily.js +0 -58
  220. package/dist-cjs/quip/desktop-session.js +0 -353
  221. package/dist-cjs/registry/index.js +0 -6
  222. package/dist-cjs/registry/registry.js +0 -761
  223. package/dist-cjs/runtime-socket-local-control-client.js +0 -367
  224. package/dist-cjs/security/dns-normalization.js +0 -22
  225. package/dist-cjs/security/dns-pinning.js +0 -160
  226. package/dist-cjs/security/external-content.js +0 -95
  227. package/dist-cjs/security/ssrf.js +0 -221
  228. package/dist-cjs/slack/desktop-session.js +0 -366
  229. package/dist-cjs/tool-factory.js +0 -50
  230. package/dist-cjs/types.js +0 -8
  231. package/dist-cjs/utils/retry.js +0 -169
  232. package/dist-cjs/utils/safe-parse-json.js +0 -164
  233. package/dist-cjs/utils/url.js +0 -23
@@ -1,938 +0,0 @@
1
- "use strict";
2
- /**
3
- * @aria/tools - Apply Patch executor
4
- *
5
- * Parses and applies unified diff patches with:
6
- * - Path traversal protection (SECURITY-CRITICAL)
7
- * - Atomic writes (all-or-nothing application)
8
- * - Fuzzy hunk matching (offset tolerance)
9
- * - CRLF normalization
10
- */
11
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
12
- if (k2 === undefined) k2 = k;
13
- var desc = Object.getOwnPropertyDescriptor(m, k);
14
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
15
- desc = { enumerable: true, get: function() { return m[k]; } };
16
- }
17
- Object.defineProperty(o, k2, desc);
18
- }) : (function(o, m, k, k2) {
19
- if (k2 === undefined) k2 = k;
20
- o[k2] = m[k];
21
- }));
22
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
23
- Object.defineProperty(o, "default", { enumerable: true, value: v });
24
- }) : function(o, v) {
25
- o["default"] = v;
26
- });
27
- var __importStar = (this && this.__importStar) || (function () {
28
- var ownKeys = function(o) {
29
- ownKeys = Object.getOwnPropertyNames || function (o) {
30
- var ar = [];
31
- for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
32
- return ar;
33
- };
34
- return ownKeys(o);
35
- };
36
- return function (mod) {
37
- if (mod && mod.__esModule) return mod;
38
- var result = {};
39
- if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
40
- __setModuleDefault(result, mod);
41
- return result;
42
- };
43
- })();
44
- Object.defineProperty(exports, "__esModule", { value: true });
45
- exports.parseUnifiedDiff = parseUnifiedDiff;
46
- exports.executeApplyPatch = executeApplyPatch;
47
- const crypto = __importStar(require("node:crypto"));
48
- const fs = __importStar(require("node:fs/promises"));
49
- const fsSync = __importStar(require("node:fs"));
50
- const nodePath = __importStar(require("node:path"));
51
- const utils_js_1 = require("./utils.js");
52
- const frg_freshness_js_1 = require("./frg-freshness.js");
53
- const search_freshness_js_1 = require("./search-freshness.js");
54
- function getErrnoCode(err) {
55
- if (typeof err !== "object" || err === null) {
56
- return undefined;
57
- }
58
- const withCode = err;
59
- return typeof withCode.code === "string" ? withCode.code : undefined;
60
- }
61
- // Maximum fuzzy offset when searching for hunk context
62
- const MAX_FUZZ_OFFSET = 3;
63
- const BEGIN_PATCH = "*** Begin Patch";
64
- const END_PATCH = "*** End Patch";
65
- const ADD_FILE = "*** Add File: ";
66
- const DELETE_FILE = "*** Delete File: ";
67
- const UPDATE_FILE = "*** Update File: ";
68
- const MOVE_TO = "*** Move to: ";
69
- const END_OF_FILE = "*** End of File";
70
- // ============================================================================
71
- // Unified Diff Parser
72
- // ============================================================================
73
- /**
74
- * Parse a unified diff string into an array of file diffs.
75
- * Handles standard unified diff and git-style diffs.
76
- */
77
- function parseUnifiedDiff(patch) {
78
- // Normalize CRLF to LF
79
- const normalized = patch.replace(/\r\n/g, "\n");
80
- const lines = normalized.split("\n");
81
- const diffs = [];
82
- let i = 0;
83
- while (i < lines.length) {
84
- const line = lines[i];
85
- // Look for --- header
86
- if (line.startsWith("--- ")) {
87
- // Check for binary diff markers before this point
88
- // (we check later too, but early check is good)
89
- const nextLine = lines[i + 1];
90
- if (!nextLine || !nextLine.startsWith("+++ ")) {
91
- i++;
92
- continue;
93
- }
94
- const oldPath = parseDiffPath(line.slice(4));
95
- const newPath = parseDiffPath(nextLine.slice(4));
96
- i += 2;
97
- // Parse hunks for this file
98
- const hunks = [];
99
- while (i < lines.length) {
100
- const hunkLine = lines[i];
101
- if (hunkLine.startsWith("@@ ")) {
102
- const hunk = parseHunkHeader(hunkLine);
103
- if (!hunk) {
104
- throw new Error(`Invalid hunk header: ${hunkLine}`);
105
- }
106
- i++;
107
- // Collect hunk lines
108
- const hunkLines = [];
109
- let oldSeen = 0;
110
- let newSeen = 0;
111
- while (i < lines.length) {
112
- const l = lines[i];
113
- const prefix = l[0];
114
- if (prefix === " " || prefix === "+" || prefix === "-") {
115
- hunkLines.push(l);
116
- if (prefix === " " || prefix === "-")
117
- oldSeen++;
118
- if (prefix === " " || prefix === "+")
119
- newSeen++;
120
- i++;
121
- // Unified diff hunks define old/new line counts explicitly.
122
- // Stop when we consumed the declared line counts so a following
123
- // file header ("--- ...") is not misread as hunk content.
124
- if (oldSeen >= hunk.oldCount && newSeen >= hunk.newCount) {
125
- break;
126
- }
127
- }
128
- else if (l === "\") {
129
- // Skip this marker — we handle trailing newlines via content
130
- i++;
131
- }
132
- else {
133
- break;
134
- }
135
- }
136
- if (i < lines.length) {
137
- const next = lines[i];
138
- const nextPrefix = next[0];
139
- const looksLikeHunkLine = nextPrefix === " " ||
140
- (nextPrefix === "+" && !next.startsWith("+++ ")) ||
141
- (nextPrefix === "-" && !next.startsWith("--- "));
142
- if (looksLikeHunkLine) {
143
- throw new Error(`Malformed hunk: expected old/new counts ${hunk.oldCount}/${hunk.newCount} but found extra hunk lines`);
144
- }
145
- }
146
- if (oldSeen !== hunk.oldCount || newSeen !== hunk.newCount) {
147
- throw new Error(`Malformed hunk: expected old/new counts ${hunk.oldCount}/${hunk.newCount} but found ${oldSeen}/${newSeen}`);
148
- }
149
- hunks.push({ ...hunk, lines: hunkLines });
150
- }
151
- else if (hunkLine.startsWith("--- ") || hunkLine.startsWith("diff ") || hunkLine === "") {
152
- // Start of next file diff or blank line separator
153
- break;
154
- }
155
- else {
156
- // Skip git diff metadata lines (index, mode, etc.)
157
- i++;
158
- }
159
- }
160
- if (hunks.length > 0 || oldPath === null || newPath === null) {
161
- diffs.push({ oldPath, newPath, hunks });
162
- }
163
- }
164
- else if (line.startsWith("Binary files") || line.startsWith("GIT binary patch")) {
165
- throw new Error(`Binary diffs are not supported: ${line}`);
166
- }
167
- else {
168
- i++;
169
- }
170
- }
171
- return diffs;
172
- }
173
- function buildCountedHunk(lines) {
174
- let oldCount = 0;
175
- let newCount = 0;
176
- for (const line of lines) {
177
- if (line.startsWith(" ") || line.startsWith("-"))
178
- oldCount++;
179
- if (line.startsWith(" ") || line.startsWith("+"))
180
- newCount++;
181
- }
182
- return {
183
- oldStart: 1,
184
- oldCount,
185
- newStart: 1,
186
- newCount,
187
- lines,
188
- };
189
- }
190
- function parseHeaderPath(line, prefix) {
191
- const raw = line.slice(prefix.length).trim();
192
- if (!raw) {
193
- throw new Error(`Missing file path after header: ${prefix.trim()}`);
194
- }
195
- return raw;
196
- }
197
- function parseBeginPatchFormat(patch) {
198
- const lines = normalizePatchText(patch).split("\n");
199
- if ((lines[0] ?? "").trim() !== BEGIN_PATCH) {
200
- throw new Error("Invalid apply_patch envelope: missing *** Begin Patch");
201
- }
202
- const diffs = [];
203
- let i = 1;
204
- while (i < lines.length) {
205
- const line = lines[i] ?? "";
206
- if (line === END_PATCH) {
207
- return diffs;
208
- }
209
- if (line.trim() === "") {
210
- i++;
211
- continue;
212
- }
213
- if (line.startsWith(ADD_FILE)) {
214
- const newPath = parseHeaderPath(line, ADD_FILE);
215
- i++;
216
- const addLines = [];
217
- while (i < lines.length) {
218
- const current = lines[i] ?? "";
219
- if (current.startsWith("*** "))
220
- break;
221
- if (!current.startsWith("+")) {
222
- throw new Error(`Invalid add-file line (must start with '+'): ${current}`);
223
- }
224
- addLines.push(current);
225
- i++;
226
- }
227
- diffs.push({
228
- oldPath: null,
229
- newPath,
230
- hunks: [buildCountedHunk(addLines)],
231
- });
232
- continue;
233
- }
234
- if (line.startsWith(DELETE_FILE)) {
235
- const oldPath = parseHeaderPath(line, DELETE_FILE);
236
- diffs.push({ oldPath, newPath: null, hunks: [] });
237
- i++;
238
- continue;
239
- }
240
- if (line.startsWith(UPDATE_FILE)) {
241
- const oldPath = parseHeaderPath(line, UPDATE_FILE);
242
- i++;
243
- let newPath = oldPath;
244
- if ((lines[i] ?? "").startsWith(MOVE_TO)) {
245
- newPath = parseHeaderPath(lines[i], MOVE_TO);
246
- i++;
247
- }
248
- const hunks = [];
249
- let currentHunkLines = [];
250
- while (i < lines.length) {
251
- const current = lines[i] ?? "";
252
- if (current.startsWith("*** "))
253
- break;
254
- if (current.startsWith("@@")) {
255
- if (currentHunkLines.length > 0) {
256
- hunks.push(buildCountedHunk(currentHunkLines));
257
- currentHunkLines = [];
258
- }
259
- i++;
260
- continue;
261
- }
262
- if (current === END_OF_FILE) {
263
- i++;
264
- continue;
265
- }
266
- if (current.startsWith(" ") || current.startsWith("+") || current.startsWith("-")) {
267
- currentHunkLines.push(current);
268
- i++;
269
- continue;
270
- }
271
- throw new Error(`Invalid update-file line: ${current}`);
272
- }
273
- if (currentHunkLines.length > 0) {
274
- hunks.push(buildCountedHunk(currentHunkLines));
275
- }
276
- if (hunks.length === 0 && oldPath === newPath) {
277
- throw new Error(`Update section has no hunks: ${oldPath}`);
278
- }
279
- diffs.push({ oldPath, newPath, hunks });
280
- continue;
281
- }
282
- throw new Error(`Invalid apply_patch section header: ${line}`);
283
- }
284
- throw new Error("Invalid apply_patch envelope: missing *** End Patch");
285
- }
286
- function normalizePatchText(patch) {
287
- return patch.replace(/\r\n/g, "\n").replace(/\r/g, "\n");
288
- }
289
- function parsePatchInput(patch) {
290
- const normalized = normalizePatchText(patch).trimStart();
291
- if (normalized.startsWith(BEGIN_PATCH)) {
292
- return parseBeginPatchFormat(normalized);
293
- }
294
- return parseUnifiedDiff(normalized);
295
- }
296
- /**
297
- * Parse a file path from a --- or +++ line.
298
- * Strips a/ or b/ git-style prefixes.
299
- * Returns null for /dev/null (new file or deleted file).
300
- */
301
- function parseDiffPath(raw) {
302
- // Remove trailing timestamp (e.g., "2024-01-01 00:00:00.000000000 +0000")
303
- const path = raw.replace(/\t.*$/, "").trim();
304
- if (path === "/dev/null") {
305
- return null;
306
- }
307
- // Strip git-style a/ or b/ prefix
308
- if (path.startsWith("a/") || path.startsWith("b/")) {
309
- return path.slice(2);
310
- }
311
- return path;
312
- }
313
- /**
314
- * Parse a hunk header line: @@ -oldStart,oldCount +newStart,newCount @@
315
- */
316
- function parseHunkHeader(line) {
317
- const match = line.match(/^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/);
318
- if (!match)
319
- return null;
320
- return {
321
- oldStart: parseInt(match[1], 10),
322
- oldCount: match[2] !== undefined ? parseInt(match[2], 10) : 1,
323
- newStart: parseInt(match[3], 10),
324
- newCount: match[4] !== undefined ? parseInt(match[4], 10) : 1,
325
- };
326
- }
327
- // ============================================================================
328
- // Path Validation (SECURITY-CRITICAL)
329
- // ============================================================================
330
- /**
331
- * Validate all paths in a parsed diff against path traversal attacks.
332
- *
333
- * SECURITY: This is the primary defense against malicious patches that
334
- * attempt to write outside the working directory.
335
- */
336
- function validatePatchPaths(diffs, cwd) {
337
- const resolved = new Map();
338
- for (const diff of diffs) {
339
- const paths = [diff.oldPath, diff.newPath].filter((p) => p !== null);
340
- for (const rawPath of paths) {
341
- if (resolved.has(rawPath))
342
- continue;
343
- // 1. Reject absolute paths
344
- if (nodePath.isAbsolute(rawPath)) {
345
- return {
346
- valid: false,
347
- error: `Absolute path not allowed in patch: ${rawPath}`,
348
- };
349
- }
350
- // 2. Reject paths with .. components
351
- const segments = rawPath.split(/[/\\]/);
352
- if (segments.includes("..")) {
353
- return {
354
- valid: false,
355
- error: `Path traversal (..) not allowed in patch: ${rawPath}`,
356
- };
357
- }
358
- // 3. Reject system paths (even though relative shouldn't reach these,
359
- // defense-in-depth against creative path construction)
360
- const systemPrefixes = ["/dev/", "/proc/", "/sys/", "/etc/"];
361
- for (const prefix of systemPrefixes) {
362
- if (rawPath.startsWith(prefix) || rawPath === prefix.slice(0, -1)) {
363
- return {
364
- valid: false,
365
- error: `System path not allowed in patch: ${rawPath}`,
366
- };
367
- }
368
- }
369
- // 4. Resolve relative to cwd
370
- const fullPath = nodePath.resolve(cwd, rawPath);
371
- // 5. Verify the resolved path is within cwd
372
- // Resolve symlinks on cwd to handle platforms where /tmp -> /private/tmp
373
- let realCwd = cwd;
374
- try {
375
- realCwd = fsSync.realpathSync(cwd);
376
- }
377
- catch {
378
- // Fall back to original cwd if it doesn't exist yet
379
- }
380
- // Resolve symlinks on the target path (walk up to nearest existing ancestor)
381
- let realPath = fullPath;
382
- try {
383
- realPath = fsSync.realpathSync(fullPath);
384
- }
385
- catch {
386
- // Path may not exist yet — walk up to find nearest existing ancestor
387
- let current = fullPath;
388
- let suffix = "";
389
- while (current !== nodePath.dirname(current)) {
390
- const parent = nodePath.dirname(current);
391
- suffix = suffix
392
- ? nodePath.join(nodePath.basename(current), suffix)
393
- : nodePath.basename(current);
394
- try {
395
- const realAncestor = fsSync.realpathSync(parent);
396
- realPath = nodePath.join(realAncestor, suffix);
397
- break;
398
- }
399
- catch {
400
- current = parent;
401
- }
402
- }
403
- }
404
- if (!(0, utils_js_1.isPathWithinBase)(realPath, realCwd)) {
405
- return {
406
- valid: false,
407
- error: `Resolved path escapes working directory: ${rawPath} -> ${realPath} (cwd: ${realCwd})`,
408
- };
409
- }
410
- resolved.set(rawPath, realPath);
411
- }
412
- }
413
- return { valid: true, resolved };
414
- }
415
- // ============================================================================
416
- // Windows Drive Letter Detection
417
- // ============================================================================
418
- /**
419
- * Check if a path looks like a Windows drive letter (e.g., C:\, D:/)
420
- */
421
- function isWindowsDrivePath(p) {
422
- return /^[a-zA-Z]:[/\\]/.test(p);
423
- }
424
- // ============================================================================
425
- // Hunk Application
426
- // ============================================================================
427
- /**
428
- * Apply hunks to file content.
429
- * Uses fuzzy matching with a configurable offset tolerance.
430
- *
431
- * Returns the modified content or an error describing what went wrong.
432
- */
433
- function applyHunks(originalContent, hunks, filePath) {
434
- // Normalize CRLF
435
- const normalized = originalContent.replace(/\r\n/g, "\n");
436
- let lines = normalized.split("\n");
437
- // Track cumulative offset from insertions/deletions
438
- let lineOffset = 0;
439
- for (let hunkIdx = 0; hunkIdx < hunks.length; hunkIdx++) {
440
- const hunk = hunks[hunkIdx];
441
- // Extract context and removal lines (lines that must exist in original)
442
- const expectedLines = [];
443
- const newLines = [];
444
- for (const line of hunk.lines) {
445
- const prefix = line[0];
446
- const content = line.slice(1);
447
- if (prefix === " ") {
448
- expectedLines.push(content);
449
- newLines.push(content);
450
- }
451
- else if (prefix === "-") {
452
- expectedLines.push(content);
453
- }
454
- else if (prefix === "+") {
455
- newLines.push(content);
456
- }
457
- }
458
- // Find the position where context matches
459
- const expectedStart = hunk.oldStart - 1 + lineOffset; // Convert 1-based to 0-based
460
- let matchPos = -1;
461
- // Try exact position first, then fuzzy within tolerance
462
- for (let offset = 0; offset <= MAX_FUZZ_OFFSET; offset++) {
463
- for (const dir of [0, 1, -1]) {
464
- const tryPos = expectedStart + offset * (dir === 0 ? 0 : dir);
465
- if (dir === 0 && offset > 0)
466
- continue; // Skip duplicate 0-offset
467
- if (tryPos < 0 || tryPos + expectedLines.length > lines.length)
468
- continue;
469
- let matches = true;
470
- for (let j = 0; j < expectedLines.length; j++) {
471
- if (lines[tryPos + j] !== expectedLines[j]) {
472
- matches = false;
473
- break;
474
- }
475
- }
476
- if (matches) {
477
- matchPos = tryPos;
478
- break;
479
- }
480
- }
481
- if (matchPos >= 0)
482
- break;
483
- }
484
- if (matchPos < 0) {
485
- // Fallback: global scan for context (used by relaxed patch formats where line numbers may be approximate)
486
- const candidates = [];
487
- for (let pos = 0; pos + expectedLines.length <= lines.length; pos++) {
488
- let matches = true;
489
- for (let j = 0; j < expectedLines.length; j++) {
490
- if (lines[pos + j] !== expectedLines[j]) {
491
- matches = false;
492
- break;
493
- }
494
- }
495
- if (matches)
496
- candidates.push(pos);
497
- }
498
- if (candidates.length === 1) {
499
- matchPos = candidates[0];
500
- }
501
- else {
502
- // Build a helpful error message
503
- const contextPreview = expectedLines.slice(0, 3).join("\n ");
504
- const ambiguity = candidates.length > 1
505
- ? `Context matched ${candidates.length} locations; provide more surrounding lines.`
506
- : "Context not found.";
507
- return {
508
- ok: false,
509
- error: `Hunk ${hunkIdx + 1} failed to apply to ${filePath} ` +
510
- `(expected at line ${hunk.oldStart}, searched ±${MAX_FUZZ_OFFSET} lines). ` +
511
- `${ambiguity}\n ${contextPreview}`,
512
- };
513
- }
514
- }
515
- // Apply: replace the matched range with the new lines
516
- lines = [
517
- ...lines.slice(0, matchPos),
518
- ...newLines,
519
- ...lines.slice(matchPos + expectedLines.length),
520
- ];
521
- // Update offset for subsequent hunks
522
- lineOffset += newLines.length - expectedLines.length;
523
- }
524
- return { ok: true, content: lines.join("\n") };
525
- }
526
- // ============================================================================
527
- // Atomic Patch Application
528
- // ============================================================================
529
- /**
530
- * Apply all file diffs atomically.
531
- * Writes to temp files first, then renames on success.
532
- * On any failure, cleans up all temp files.
533
- */
534
- async function applyPatchAtomic(diffs, resolvedPaths) {
535
- const actions = [];
536
- const tempFiles = [];
537
- let totalAdded = 0;
538
- let totalRemoved = 0;
539
- try {
540
- // Phase 1: Compute all file actions (read + apply hunks)
541
- for (const diff of diffs) {
542
- const isNewFile = diff.oldPath === null;
543
- const isDeleteFile = diff.newPath === null;
544
- const sourcePath = diff.oldPath ? resolvedPaths.get(diff.oldPath) : undefined;
545
- const targetPath = diff.newPath ? resolvedPaths.get(diff.newPath) : undefined;
546
- if (isDeleteFile) {
547
- // Deletion: mark for removal
548
- if (!sourcePath) {
549
- return (0, utils_js_1.fail)(`Patch references missing delete source path: ${diff.oldPath}`);
550
- }
551
- let sourceStat;
552
- try {
553
- sourceStat = await fs.stat(sourcePath);
554
- }
555
- catch (err) {
556
- return (0, utils_js_1.fail)(`Cannot delete missing path: ${sourcePath}: ${(0, utils_js_1.getErrorMessage)(err)}`);
557
- }
558
- if (sourceStat.isDirectory()) {
559
- return (0, utils_js_1.fail)(`Patch delete targets a directory (unsupported): ${sourcePath}`);
560
- }
561
- actions.push({ resolvedPath: sourcePath, type: "delete" });
562
- // Count removed lines
563
- for (const hunk of diff.hunks) {
564
- for (const line of hunk.lines) {
565
- if (line.startsWith("-"))
566
- totalRemoved++;
567
- }
568
- }
569
- continue;
570
- }
571
- if (isNewFile) {
572
- if (!targetPath) {
573
- return (0, utils_js_1.fail)(`Patch references missing create target path: ${diff.newPath}`);
574
- }
575
- // New file: build content from additions
576
- const contentLines = [];
577
- for (const hunk of diff.hunks) {
578
- for (const line of hunk.lines) {
579
- if (line.startsWith("+")) {
580
- contentLines.push(line.slice(1));
581
- totalAdded++;
582
- }
583
- }
584
- }
585
- const content = contentLines.join("\n") + "\n";
586
- actions.push({ resolvedPath: targetPath, type: "create", content });
587
- }
588
- else {
589
- if (!sourcePath || !targetPath) {
590
- return (0, utils_js_1.fail)(`Patch references missing update source/target paths: ${diff.oldPath} -> ${diff.newPath}`);
591
- }
592
- // Modify existing file
593
- let originalContent;
594
- try {
595
- originalContent = await fs.readFile(sourcePath, "utf-8");
596
- }
597
- catch (err) {
598
- return (0, utils_js_1.fail)(`Cannot read file for patching: ${sourcePath}: ${(0, utils_js_1.getErrorMessage)(err)}`);
599
- }
600
- const result = applyHunks(originalContent, diff.hunks, diff.newPath);
601
- if (!result.ok) {
602
- return (0, utils_js_1.fail)(result.error);
603
- }
604
- // Count additions and removals
605
- for (const hunk of diff.hunks) {
606
- for (const line of hunk.lines) {
607
- if (line.startsWith("+"))
608
- totalAdded++;
609
- else if (line.startsWith("-"))
610
- totalRemoved++;
611
- }
612
- }
613
- actions.push({
614
- sourcePath,
615
- resolvedPath: targetPath,
616
- type: sourcePath === targetPath ? "modify" : "move",
617
- content: result.content,
618
- });
619
- }
620
- }
621
- // Phase 2: Write all changes to temp files
622
- for (const action of actions) {
623
- if (action.type === "delete")
624
- continue;
625
- const dir = nodePath.dirname(action.resolvedPath);
626
- const base = nodePath.basename(action.resolvedPath);
627
- const suffix = crypto.randomBytes(6).toString("hex");
628
- const tempPath = nodePath.join(dir, `.${base}.patch-${suffix}`);
629
- // Ensure parent directory exists (needed for new files)
630
- await fs.mkdir(dir, { recursive: true });
631
- await fs.writeFile(tempPath, action.content, "utf-8");
632
- tempFiles.push(tempPath);
633
- }
634
- // Phase 3: Atomic rename — all temp files to final destinations
635
- // Back up targets and deletion sources for rollback on failure
636
- const targetBackups = new Map();
637
- const sourceRemovalBackups = new Map();
638
- const appliedTargets = [];
639
- const removedSources = [];
640
- const backupTargetIfExists = async (targetPath) => {
641
- if (targetBackups.has(targetPath)) {
642
- return;
643
- }
644
- const backupSuffix = crypto.randomBytes(6).toString("hex");
645
- const backupPath = targetPath + `.patch-backup-${backupSuffix}`;
646
- try {
647
- await fs.copyFile(targetPath, backupPath);
648
- targetBackups.set(targetPath, backupPath);
649
- }
650
- catch (err) {
651
- const code = getErrnoCode(err);
652
- if (code === "ENOENT") {
653
- return;
654
- }
655
- throw err;
656
- }
657
- };
658
- const backupSourceRemovalPath = async (sourcePath) => {
659
- if (sourceRemovalBackups.has(sourcePath)) {
660
- return;
661
- }
662
- const backupSuffix = crypto.randomBytes(6).toString("hex");
663
- const backupPath = sourcePath + `.patch-source-backup-${backupSuffix}`;
664
- await fs.copyFile(sourcePath, backupPath);
665
- sourceRemovalBackups.set(sourcePath, backupPath);
666
- };
667
- const unlinkSourcePath = async (sourcePath) => {
668
- try {
669
- await fs.unlink(sourcePath);
670
- removedSources.push(sourcePath);
671
- }
672
- catch (err) {
673
- const code = getErrnoCode(err);
674
- // If the path is already gone, desired end-state (removed) is satisfied.
675
- if (code === "ENOENT") {
676
- return;
677
- }
678
- throw err;
679
- }
680
- };
681
- try {
682
- // Backup all existing target files that may be overwritten.
683
- for (const action of actions) {
684
- if (action.type === "delete")
685
- continue;
686
- await backupTargetIfExists(action.resolvedPath);
687
- }
688
- // Backup all files that will be removed (delete + move source path).
689
- for (const action of actions) {
690
- if (action.type === "delete") {
691
- await backupSourceRemovalPath(action.resolvedPath);
692
- continue;
693
- }
694
- if (action.type === "move" &&
695
- action.sourcePath &&
696
- action.sourcePath !== action.resolvedPath) {
697
- await backupSourceRemovalPath(action.sourcePath);
698
- }
699
- }
700
- let tempIdx = 0;
701
- for (const action of actions) {
702
- if (action.type === "delete")
703
- continue;
704
- const tempPath = tempFiles[tempIdx];
705
- await fs.rename(tempPath, action.resolvedPath);
706
- appliedTargets.push(action.resolvedPath);
707
- tempIdx++;
708
- }
709
- // Apply delete/move source removals as part of the same transaction.
710
- for (const action of actions) {
711
- if (action.type === "delete") {
712
- await unlinkSourcePath(action.resolvedPath);
713
- }
714
- else if (action.type === "move" &&
715
- action.sourcePath &&
716
- action.sourcePath !== action.resolvedPath) {
717
- await unlinkSourcePath(action.sourcePath);
718
- }
719
- }
720
- }
721
- catch (renameErr) {
722
- // Rollback: restore backup-backed targets, remove newly-created targets
723
- for (let idx = appliedTargets.length - 1; idx >= 0; idx--) {
724
- const target = appliedTargets[idx];
725
- const backup = targetBackups.get(target);
726
- try {
727
- if (backup) {
728
- await fs.rename(backup, target);
729
- }
730
- else {
731
- await fs.unlink(target);
732
- }
733
- }
734
- catch {
735
- /* best-effort */
736
- }
737
- }
738
- // Rollback removed source paths (delete/move) in reverse order.
739
- for (let idx = removedSources.length - 1; idx >= 0; idx--) {
740
- const sourcePath = removedSources[idx];
741
- const backup = sourceRemovalBackups.get(sourcePath);
742
- if (!backup)
743
- continue;
744
- try {
745
- await fs.rename(backup, sourcePath);
746
- sourceRemovalBackups.delete(sourcePath);
747
- }
748
- catch {
749
- /* best-effort */
750
- }
751
- }
752
- // Clean up any remaining backup files
753
- for (const backup of targetBackups.values()) {
754
- try {
755
- await fs.unlink(backup);
756
- }
757
- catch {
758
- /* best-effort */
759
- }
760
- }
761
- for (const backup of sourceRemovalBackups.values()) {
762
- try {
763
- await fs.unlink(backup);
764
- }
765
- catch {
766
- /* best-effort */
767
- }
768
- }
769
- // Clean up any remaining temp files
770
- for (const tempPath of tempFiles) {
771
- try {
772
- await fs.unlink(tempPath);
773
- }
774
- catch {
775
- /* best-effort */
776
- }
777
- }
778
- throw renameErr; // Will be caught by outer try/catch
779
- }
780
- // Success — clean up backups
781
- for (const backup of targetBackups.values()) {
782
- try {
783
- await fs.unlink(backup);
784
- }
785
- catch {
786
- /* best-effort */
787
- }
788
- }
789
- for (const backup of sourceRemovalBackups.values()) {
790
- try {
791
- await fs.unlink(backup);
792
- }
793
- catch {
794
- /* best-effort */
795
- }
796
- }
797
- // Build summary
798
- const filesChanged = actions.length;
799
- const created = actions.filter((a) => a.type === "create").length;
800
- const modified = actions.filter((a) => a.type === "modify").length;
801
- const deleted = actions.filter((a) => a.type === "delete").length;
802
- const moved = actions.filter((a) => a.type === "move").length;
803
- const parts = [];
804
- if (created > 0)
805
- parts.push(`${created} created`);
806
- if (modified > 0)
807
- parts.push(`${modified} modified`);
808
- if (moved > 0)
809
- parts.push(`${moved} moved`);
810
- if (deleted > 0)
811
- parts.push(`${deleted} deleted`);
812
- const summary = `Patch applied: ${filesChanged} file${filesChanged !== 1 ? "s" : ""} ` +
813
- `(${parts.join(", ")}), +${totalAdded}/-${totalRemoved} lines`;
814
- for (const action of actions) {
815
- if (action.type === "delete") {
816
- (0, frg_freshness_js_1.recordFrgMutation)(action.resolvedPath, "delete");
817
- (0, search_freshness_js_1.recordSearchMutation)(action.resolvedPath, "delete");
818
- }
819
- else {
820
- (0, frg_freshness_js_1.recordFrgMutation)(action.resolvedPath, "write", action.content);
821
- (0, search_freshness_js_1.recordSearchMutation)(action.resolvedPath, "write", action.content);
822
- if (action.type === "move" &&
823
- action.sourcePath &&
824
- action.sourcePath !== action.resolvedPath) {
825
- (0, frg_freshness_js_1.recordFrgMutation)(action.sourcePath, "delete");
826
- (0, search_freshness_js_1.recordSearchMutation)(action.sourcePath, "delete");
827
- }
828
- }
829
- }
830
- return (0, utils_js_1.success)(summary, {
831
- filesChanged,
832
- created,
833
- modified,
834
- moved,
835
- deleted,
836
- linesAdded: totalAdded,
837
- linesRemoved: totalRemoved,
838
- files: actions.map((a) => ({
839
- path: a.type === "move" ? `${a.sourcePath} -> ${a.resolvedPath}` : a.resolvedPath,
840
- action: a.type,
841
- })),
842
- });
843
- }
844
- catch (err) {
845
- // Cleanup: remove all temp files on failure
846
- for (const tempPath of tempFiles) {
847
- try {
848
- await fs.unlink(tempPath);
849
- }
850
- catch {
851
- // Best-effort cleanup
852
- }
853
- }
854
- return (0, utils_js_1.fail)(`Patch application failed: ${(0, utils_js_1.getErrorMessage)(err)}`);
855
- }
856
- }
857
- // ============================================================================
858
- // Main Executor
859
- // ============================================================================
860
- /**
861
- * Execute the apply_patch tool.
862
- *
863
- * Parses a unified diff, validates all paths for security,
864
- * and applies changes atomically.
865
- */
866
- async function executeApplyPatch(input, ctx) {
867
- try {
868
- if (!input.patch || input.patch.trim() === "") {
869
- return (0, utils_js_1.fail)("Patch content is empty");
870
- }
871
- // Size guard: reject patches > 1MB to prevent memory exhaustion
872
- const MAX_PATCH_SIZE = 1_048_576; // 1MB
873
- if (input.patch.length > MAX_PATCH_SIZE) {
874
- return (0, utils_js_1.fail)(`Patch too large: ${input.patch.length} bytes (max: ${MAX_PATCH_SIZE})`);
875
- }
876
- // Determine working directory
877
- const cwd = input.cwd ? nodePath.resolve(ctx.workingDir, input.cwd) : ctx.workingDir;
878
- // SECURITY: Validate cwd is within the working directory
879
- if (input.cwd) {
880
- let realCwd;
881
- try {
882
- realCwd = fsSync.realpathSync(cwd);
883
- }
884
- catch {
885
- return (0, utils_js_1.fail)(`Working directory does not exist: ${cwd}`);
886
- }
887
- let realWorkingDir;
888
- try {
889
- realWorkingDir = fsSync.realpathSync(ctx.workingDir);
890
- }
891
- catch {
892
- return (0, utils_js_1.fail)(`Base working directory does not exist: ${ctx.workingDir}`);
893
- }
894
- if (!(0, utils_js_1.isPathWithinBase)(realCwd, realWorkingDir)) {
895
- return (0, utils_js_1.fail)(`cwd must be within the working directory: ${input.cwd}`);
896
- }
897
- }
898
- // Verify cwd exists and is a directory
899
- try {
900
- const stat = await fs.stat(cwd);
901
- if (!stat.isDirectory()) {
902
- return (0, utils_js_1.fail)(`Working directory is not a directory: ${cwd}`);
903
- }
904
- }
905
- catch {
906
- return (0, utils_js_1.fail)(`Working directory does not exist: ${cwd}`);
907
- }
908
- // Step 1: Parse patch input (unified diff or apply_patch envelope)
909
- let diffs;
910
- try {
911
- diffs = parsePatchInput(input.patch);
912
- }
913
- catch (err) {
914
- return (0, utils_js_1.fail)(`Failed to parse patch: ${(0, utils_js_1.getErrorMessage)(err)}`);
915
- }
916
- if (diffs.length === 0) {
917
- return (0, utils_js_1.fail)("No file diffs found in patch");
918
- }
919
- // Step 2: Validate paths (SECURITY-CRITICAL)
920
- // Check for Windows drive letters in paths (cross-platform safety)
921
- for (const diff of diffs) {
922
- for (const p of [diff.oldPath, diff.newPath]) {
923
- if (p !== null && isWindowsDrivePath(p)) {
924
- return (0, utils_js_1.fail)(`Absolute path not allowed in patch: ${p}`);
925
- }
926
- }
927
- }
928
- const validation = validatePatchPaths(diffs, cwd);
929
- if (!validation.valid) {
930
- return (0, utils_js_1.fail)(validation.error);
931
- }
932
- // Step 3: Apply atomically
933
- return await applyPatchAtomic(diffs, validation.resolved);
934
- }
935
- catch (err) {
936
- return (0, utils_js_1.fail)(`apply_patch failed: ${(0, utils_js_1.getErrorMessage)(err)}`);
937
- }
938
- }