apex-code 0.0.1-alpha.8 → 0.0.4

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 (634) hide show
  1. package/CHANGELOG.md +231 -0
  2. package/README.md +9 -8
  3. package/dist/cli/args.d.ts +26 -1
  4. package/dist/cli/args.d.ts.map +1 -1
  5. package/dist/cli/args.js +72 -10
  6. package/dist/cli/args.js.map +1 -1
  7. package/dist/cli/file-processor.d.ts.map +1 -1
  8. package/dist/cli/file-processor.js +2 -1
  9. package/dist/cli/file-processor.js.map +1 -1
  10. package/dist/cli/mcp-command.d.ts +9 -0
  11. package/dist/cli/mcp-command.d.ts.map +1 -0
  12. package/dist/cli/mcp-command.js +53 -0
  13. package/dist/cli/mcp-command.js.map +1 -0
  14. package/dist/cli/project-trust.d.ts.map +1 -1
  15. package/dist/cli/project-trust.js +3 -1
  16. package/dist/cli/project-trust.js.map +1 -1
  17. package/dist/cli/startup-ui.d.ts.map +1 -1
  18. package/dist/cli/startup-ui.js +2 -1
  19. package/dist/cli/startup-ui.js.map +1 -1
  20. package/dist/cli.d.ts.map +1 -1
  21. package/dist/cli.js +94 -5
  22. package/dist/cli.js.map +1 -1
  23. package/dist/config.d.ts +3 -2
  24. package/dist/config.d.ts.map +1 -1
  25. package/dist/config.js +45 -18
  26. package/dist/config.js.map +1 -1
  27. package/dist/core/agent-session-services.d.ts +3 -0
  28. package/dist/core/agent-session-services.d.ts.map +1 -1
  29. package/dist/core/agent-session-services.js +1 -0
  30. package/dist/core/agent-session-services.js.map +1 -1
  31. package/dist/core/agent-session.d.ts +183 -15
  32. package/dist/core/agent-session.d.ts.map +1 -1
  33. package/dist/core/agent-session.js +728 -117
  34. package/dist/core/agent-session.js.map +1 -1
  35. package/dist/core/auth-storage.d.ts.map +1 -1
  36. package/dist/core/auth-storage.js +6 -7
  37. package/dist/core/auth-storage.js.map +1 -1
  38. package/dist/core/bash-executor.d.ts.map +1 -1
  39. package/dist/core/bash-executor.js +7 -0
  40. package/dist/core/bash-executor.js.map +1 -1
  41. package/dist/core/checkpoints/git-checkpoints.d.ts +39 -0
  42. package/dist/core/checkpoints/git-checkpoints.d.ts.map +1 -0
  43. package/dist/core/checkpoints/git-checkpoints.js +251 -0
  44. package/dist/core/checkpoints/git-checkpoints.js.map +1 -0
  45. package/dist/core/checkpoints/session-checkpoints.d.ts +23 -0
  46. package/dist/core/checkpoints/session-checkpoints.d.ts.map +1 -0
  47. package/dist/core/checkpoints/session-checkpoints.js +36 -0
  48. package/dist/core/checkpoints/session-checkpoints.js.map +1 -0
  49. package/dist/core/compaction/branch-summarization.d.ts.map +1 -1
  50. package/dist/core/compaction/branch-summarization.js +7 -3
  51. package/dist/core/compaction/branch-summarization.js.map +1 -1
  52. package/dist/core/compaction/compaction.d.ts +9 -3
  53. package/dist/core/compaction/compaction.d.ts.map +1 -1
  54. package/dist/core/compaction/compaction.js +59 -36
  55. package/dist/core/compaction/compaction.js.map +1 -1
  56. package/dist/core/defaults.d.ts +1 -0
  57. package/dist/core/defaults.d.ts.map +1 -1
  58. package/dist/core/defaults.js +9 -0
  59. package/dist/core/defaults.js.map +1 -1
  60. package/dist/core/delegation/runtime.d.ts +6 -5
  61. package/dist/core/delegation/runtime.d.ts.map +1 -1
  62. package/dist/core/delegation/runtime.js +4 -3
  63. package/dist/core/delegation/runtime.js.map +1 -1
  64. package/dist/core/durable-state/sqlite.d.ts.map +1 -1
  65. package/dist/core/durable-state/sqlite.js +26 -2
  66. package/dist/core/durable-state/sqlite.js.map +1 -1
  67. package/dist/core/exec.d.ts.map +1 -1
  68. package/dist/core/exec.js +5 -2
  69. package/dist/core/exec.js.map +1 -1
  70. package/dist/core/extensions/index.d.ts +2 -2
  71. package/dist/core/extensions/index.d.ts.map +1 -1
  72. package/dist/core/extensions/index.js +1 -1
  73. package/dist/core/extensions/index.js.map +1 -1
  74. package/dist/core/extensions/loader.d.ts.map +1 -1
  75. package/dist/core/extensions/loader.js +123 -50
  76. package/dist/core/extensions/loader.js.map +1 -1
  77. package/dist/core/extensions/runner.d.ts +5 -0
  78. package/dist/core/extensions/runner.d.ts.map +1 -1
  79. package/dist/core/extensions/runner.js +45 -1
  80. package/dist/core/extensions/runner.js.map +1 -1
  81. package/dist/core/extensions/source-runtime.d.ts +14 -0
  82. package/dist/core/extensions/source-runtime.d.ts.map +1 -0
  83. package/dist/core/extensions/source-runtime.js +56 -0
  84. package/dist/core/extensions/source-runtime.js.map +1 -0
  85. package/dist/core/extensions/types.d.ts +60 -11
  86. package/dist/core/extensions/types.d.ts.map +1 -1
  87. package/dist/core/extensions/types.js +3 -0
  88. package/dist/core/extensions/types.js.map +1 -1
  89. package/dist/core/footer-data-provider.d.ts +1 -1
  90. package/dist/core/footer-data-provider.d.ts.map +1 -1
  91. package/dist/core/footer-data-provider.js +1 -1
  92. package/dist/core/footer-data-provider.js.map +1 -1
  93. package/dist/core/formatter-lifecycle.d.ts +69 -0
  94. package/dist/core/formatter-lifecycle.d.ts.map +1 -0
  95. package/dist/core/formatter-lifecycle.js +360 -0
  96. package/dist/core/formatter-lifecycle.js.map +1 -0
  97. package/dist/core/hooks/command-handler.d.ts +19 -0
  98. package/dist/core/hooks/command-handler.d.ts.map +1 -0
  99. package/dist/core/hooks/command-handler.js +112 -0
  100. package/dist/core/hooks/command-handler.js.map +1 -0
  101. package/dist/core/hooks/http-handler.d.ts +10 -0
  102. package/dist/core/hooks/http-handler.d.ts.map +1 -0
  103. package/dist/core/hooks/http-handler.js +36 -0
  104. package/dist/core/hooks/http-handler.js.map +1 -0
  105. package/dist/core/hooks/loader.d.ts +29 -0
  106. package/dist/core/hooks/loader.d.ts.map +1 -0
  107. package/dist/core/hooks/loader.js +139 -0
  108. package/dist/core/hooks/loader.js.map +1 -0
  109. package/dist/core/hooks/runtime.d.ts +13 -0
  110. package/dist/core/hooks/runtime.d.ts.map +1 -0
  111. package/dist/core/hooks/runtime.js +63 -0
  112. package/dist/core/hooks/runtime.js.map +1 -0
  113. package/dist/core/hooks/types.d.ts +83 -0
  114. package/dist/core/hooks/types.d.ts.map +1 -0
  115. package/dist/core/hooks/types.js +24 -0
  116. package/dist/core/hooks/types.js.map +1 -0
  117. package/dist/core/keybindings.d.ts +20 -19
  118. package/dist/core/keybindings.d.ts.map +1 -1
  119. package/dist/core/keybindings.js +26 -5
  120. package/dist/core/keybindings.js.map +1 -1
  121. package/dist/core/mcp/config.d.ts +16 -0
  122. package/dist/core/mcp/config.d.ts.map +1 -0
  123. package/dist/core/mcp/config.js +166 -0
  124. package/dist/core/mcp/config.js.map +1 -0
  125. package/dist/core/mcp/connector.d.ts +35 -0
  126. package/dist/core/mcp/connector.d.ts.map +1 -0
  127. package/dist/core/mcp/connector.js +105 -0
  128. package/dist/core/mcp/connector.js.map +1 -0
  129. package/dist/core/mcp/contract.d.ts +19 -0
  130. package/dist/core/mcp/contract.d.ts.map +1 -0
  131. package/dist/core/mcp/contract.js +89 -0
  132. package/dist/core/mcp/contract.js.map +1 -0
  133. package/dist/core/mcp/mcp-tool.d.ts +32 -0
  134. package/dist/core/mcp/mcp-tool.d.ts.map +1 -0
  135. package/dist/core/mcp/mcp-tool.js +171 -0
  136. package/dist/core/mcp/mcp-tool.js.map +1 -0
  137. package/dist/core/mcp/metadata-cache.d.ts +29 -0
  138. package/dist/core/mcp/metadata-cache.d.ts.map +1 -0
  139. package/dist/core/mcp/metadata-cache.js +99 -0
  140. package/dist/core/mcp/metadata-cache.js.map +1 -0
  141. package/dist/core/mcp/oauth/authorize.d.ts +21 -0
  142. package/dist/core/mcp/oauth/authorize.d.ts.map +1 -0
  143. package/dist/core/mcp/oauth/authorize.js +32 -0
  144. package/dist/core/mcp/oauth/authorize.js.map +1 -0
  145. package/dist/core/mcp/oauth/discover.d.ts +27 -0
  146. package/dist/core/mcp/oauth/discover.d.ts.map +1 -0
  147. package/dist/core/mcp/oauth/discover.js +116 -0
  148. package/dist/core/mcp/oauth/discover.js.map +1 -0
  149. package/dist/core/mcp/oauth/flow.d.ts +31 -0
  150. package/dist/core/mcp/oauth/flow.d.ts.map +1 -0
  151. package/dist/core/mcp/oauth/flow.js +175 -0
  152. package/dist/core/mcp/oauth/flow.js.map +1 -0
  153. package/dist/core/mcp/oauth/mcp-token.d.ts +51 -0
  154. package/dist/core/mcp/oauth/mcp-token.d.ts.map +1 -0
  155. package/dist/core/mcp/oauth/mcp-token.js +129 -0
  156. package/dist/core/mcp/oauth/mcp-token.js.map +1 -0
  157. package/dist/core/mcp/oauth/pkce.d.ts +12 -0
  158. package/dist/core/mcp/oauth/pkce.d.ts.map +1 -0
  159. package/dist/core/mcp/oauth/pkce.js +11 -0
  160. package/dist/core/mcp/oauth/pkce.js.map +1 -0
  161. package/dist/core/mcp/oauth/register.d.ts +16 -0
  162. package/dist/core/mcp/oauth/register.d.ts.map +1 -0
  163. package/dist/core/mcp/oauth/register.js +42 -0
  164. package/dist/core/mcp/oauth/register.js.map +1 -0
  165. package/dist/core/mcp/oauth/token-client.d.ts +33 -0
  166. package/dist/core/mcp/oauth/token-client.d.ts.map +1 -0
  167. package/dist/core/mcp/oauth/token-client.js +65 -0
  168. package/dist/core/mcp/oauth/token-client.js.map +1 -0
  169. package/dist/core/mcp/runtime.d.ts +20 -0
  170. package/dist/core/mcp/runtime.d.ts.map +1 -0
  171. package/dist/core/mcp/runtime.js +37 -0
  172. package/dist/core/mcp/runtime.js.map +1 -0
  173. package/dist/core/mcp/schema.d.ts +22 -0
  174. package/dist/core/mcp/schema.d.ts.map +1 -0
  175. package/dist/core/mcp/schema.js +20 -0
  176. package/dist/core/mcp/schema.js.map +1 -0
  177. package/dist/core/mcp/server-manager.d.ts +43 -0
  178. package/dist/core/mcp/server-manager.d.ts.map +1 -0
  179. package/dist/core/mcp/server-manager.js +142 -0
  180. package/dist/core/mcp/server-manager.js.map +1 -0
  181. package/dist/core/mcp/types.d.ts +100 -0
  182. package/dist/core/mcp/types.d.ts.map +1 -0
  183. package/dist/core/mcp/types.js +8 -0
  184. package/dist/core/mcp/types.js.map +1 -0
  185. package/dist/core/model-config.d.ts +5 -0
  186. package/dist/core/model-config.d.ts.map +1 -1
  187. package/dist/core/model-config.js +3 -1
  188. package/dist/core/model-config.js.map +1 -1
  189. package/dist/core/model-resolver.d.ts +1 -0
  190. package/dist/core/model-resolver.d.ts.map +1 -1
  191. package/dist/core/model-resolver.js +14 -8
  192. package/dist/core/model-resolver.js.map +1 -1
  193. package/dist/core/models-store.d.ts.map +1 -1
  194. package/dist/core/models-store.js +2 -1
  195. package/dist/core/models-store.js.map +1 -1
  196. package/dist/core/package-manager.d.ts.map +1 -1
  197. package/dist/core/package-manager.js +22 -14
  198. package/dist/core/package-manager.js.map +1 -1
  199. package/dist/core/permissions/gate.d.ts.map +1 -1
  200. package/dist/core/permissions/gate.js +45 -4
  201. package/dist/core/permissions/gate.js.map +1 -1
  202. package/dist/core/permissions/operations.d.ts +20 -0
  203. package/dist/core/permissions/operations.d.ts.map +1 -0
  204. package/dist/core/permissions/operations.js +9 -0
  205. package/dist/core/permissions/operations.js.map +1 -0
  206. package/dist/core/permissions/policy-command.d.ts +42 -0
  207. package/dist/core/permissions/policy-command.d.ts.map +1 -0
  208. package/dist/core/permissions/policy-command.js +44 -0
  209. package/dist/core/permissions/policy-command.js.map +1 -0
  210. package/dist/core/permissions/responder.d.ts +49 -2
  211. package/dist/core/permissions/responder.d.ts.map +1 -1
  212. package/dist/core/permissions/responder.js +20 -8
  213. package/dist/core/permissions/responder.js.map +1 -1
  214. package/dist/core/permissions/rules.d.ts.map +1 -1
  215. package/dist/core/permissions/rules.js +11 -1
  216. package/dist/core/permissions/rules.js.map +1 -1
  217. package/dist/core/permissions/store.d.ts +18 -0
  218. package/dist/core/permissions/store.d.ts.map +1 -1
  219. package/dist/core/permissions/store.js +89 -8
  220. package/dist/core/permissions/store.js.map +1 -1
  221. package/dist/core/pi-manifest.d.ts.map +1 -1
  222. package/dist/core/pi-manifest.js +2 -1
  223. package/dist/core/pi-manifest.js.map +1 -1
  224. package/dist/core/policy-executor.d.ts +47 -0
  225. package/dist/core/policy-executor.d.ts.map +1 -0
  226. package/dist/core/policy-executor.js +228 -0
  227. package/dist/core/policy-executor.js.map +1 -0
  228. package/dist/core/policy-loader.d.ts +72 -0
  229. package/dist/core/policy-loader.d.ts.map +1 -0
  230. package/dist/core/policy-loader.js +195 -0
  231. package/dist/core/policy-loader.js.map +1 -0
  232. package/dist/core/project-trust.d.ts +1 -1
  233. package/dist/core/project-trust.d.ts.map +1 -1
  234. package/dist/core/project-trust.js.map +1 -1
  235. package/dist/core/remote-catalog-provider.d.ts.map +1 -1
  236. package/dist/core/remote-catalog-provider.js +2 -1
  237. package/dist/core/remote-catalog-provider.js.map +1 -1
  238. package/dist/core/resource-loader.d.ts.map +1 -1
  239. package/dist/core/resource-loader.js +3 -2
  240. package/dist/core/resource-loader.js.map +1 -1
  241. package/dist/core/sandbox/bwrap-arguments.d.ts +41 -0
  242. package/dist/core/sandbox/bwrap-arguments.d.ts.map +1 -0
  243. package/dist/core/sandbox/bwrap-arguments.js +136 -0
  244. package/dist/core/sandbox/bwrap-arguments.js.map +1 -0
  245. package/dist/core/sandbox/child-entry.d.ts.map +1 -1
  246. package/dist/core/sandbox/child-entry.js +3 -1
  247. package/dist/core/sandbox/child-entry.js.map +1 -1
  248. package/dist/core/sandbox/cli-launch.d.ts +84 -4
  249. package/dist/core/sandbox/cli-launch.d.ts.map +1 -1
  250. package/dist/core/sandbox/cli-launch.js +115 -16
  251. package/dist/core/sandbox/cli-launch.js.map +1 -1
  252. package/dist/core/sandbox/cli-supervisor.d.ts +2 -0
  253. package/dist/core/sandbox/cli-supervisor.d.ts.map +1 -1
  254. package/dist/core/sandbox/cli-supervisor.js +50 -2
  255. package/dist/core/sandbox/cli-supervisor.js.map +1 -1
  256. package/dist/core/sandbox/full-access.d.ts +28 -0
  257. package/dist/core/sandbox/full-access.d.ts.map +1 -0
  258. package/dist/core/sandbox/full-access.js +63 -0
  259. package/dist/core/sandbox/full-access.js.map +1 -0
  260. package/dist/core/sandbox/git-identity.d.ts +57 -0
  261. package/dist/core/sandbox/git-identity.d.ts.map +1 -0
  262. package/dist/core/sandbox/git-identity.js +78 -0
  263. package/dist/core/sandbox/git-identity.js.map +1 -0
  264. package/dist/core/sandbox/host-approval.d.ts +42 -0
  265. package/dist/core/sandbox/host-approval.d.ts.map +1 -0
  266. package/dist/core/sandbox/host-approval.js +99 -0
  267. package/dist/core/sandbox/host-approval.js.map +1 -0
  268. package/dist/core/sandbox/linux-backend.d.ts +14 -0
  269. package/dist/core/sandbox/linux-backend.d.ts.map +1 -1
  270. package/dist/core/sandbox/linux-backend.js +158 -80
  271. package/dist/core/sandbox/linux-backend.js.map +1 -1
  272. package/dist/core/sandbox/macos-backend.d.ts +5 -0
  273. package/dist/core/sandbox/macos-backend.d.ts.map +1 -1
  274. package/dist/core/sandbox/macos-backend.js +164 -5
  275. package/dist/core/sandbox/macos-backend.js.map +1 -1
  276. package/dist/core/sandbox/network-proxy.d.ts +19 -0
  277. package/dist/core/sandbox/network-proxy.d.ts.map +1 -1
  278. package/dist/core/sandbox/network-proxy.js +93 -19
  279. package/dist/core/sandbox/network-proxy.js.map +1 -1
  280. package/dist/core/sandbox/policy.d.ts +8 -0
  281. package/dist/core/sandbox/policy.d.ts.map +1 -1
  282. package/dist/core/sandbox/policy.js +29 -12
  283. package/dist/core/sandbox/policy.js.map +1 -1
  284. package/dist/core/sandbox/profiles.d.ts +25 -0
  285. package/dist/core/sandbox/profiles.d.ts.map +1 -0
  286. package/dist/core/sandbox/profiles.js +23 -0
  287. package/dist/core/sandbox/profiles.js.map +1 -0
  288. package/dist/core/sandbox/rpc/command-client.d.ts +28 -0
  289. package/dist/core/sandbox/rpc/command-client.d.ts.map +1 -0
  290. package/dist/core/sandbox/rpc/command-client.js +86 -0
  291. package/dist/core/sandbox/rpc/command-client.js.map +1 -0
  292. package/dist/core/sandbox/rpc/command-proxy.d.ts +48 -0
  293. package/dist/core/sandbox/rpc/command-proxy.d.ts.map +1 -0
  294. package/dist/core/sandbox/rpc/command-proxy.js +120 -0
  295. package/dist/core/sandbox/rpc/command-proxy.js.map +1 -0
  296. package/dist/core/sandbox/rpc/credential-proxy.d.ts.map +1 -1
  297. package/dist/core/sandbox/rpc/credential-proxy.js +2 -96
  298. package/dist/core/sandbox/rpc/credential-proxy.js.map +1 -1
  299. package/dist/core/sandbox/rpc/framing.d.ts +35 -0
  300. package/dist/core/sandbox/rpc/framing.d.ts.map +1 -0
  301. package/dist/core/sandbox/rpc/framing.js +114 -0
  302. package/dist/core/sandbox/rpc/framing.js.map +1 -0
  303. package/dist/core/sandbox/rpc/git-credential-helper.d.ts +47 -0
  304. package/dist/core/sandbox/rpc/git-credential-helper.d.ts.map +1 -0
  305. package/dist/core/sandbox/rpc/git-credential-helper.js +222 -0
  306. package/dist/core/sandbox/rpc/git-credential-helper.js.map +1 -0
  307. package/dist/core/sandbox/rpc/git-credential-proxy.d.ts +66 -0
  308. package/dist/core/sandbox/rpc/git-credential-proxy.d.ts.map +1 -0
  309. package/dist/core/sandbox/rpc/git-credential-proxy.js +209 -0
  310. package/dist/core/sandbox/rpc/git-credential-proxy.js.map +1 -0
  311. package/dist/core/sandbox/supervisor-temp.d.ts +18 -0
  312. package/dist/core/sandbox/supervisor-temp.d.ts.map +1 -0
  313. package/dist/core/sandbox/supervisor-temp.js +21 -0
  314. package/dist/core/sandbox/supervisor-temp.js.map +1 -0
  315. package/dist/core/sandbox/supervisor.d.ts +12 -1
  316. package/dist/core/sandbox/supervisor.d.ts.map +1 -1
  317. package/dist/core/sandbox/supervisor.js +15 -1
  318. package/dist/core/sandbox/supervisor.js.map +1 -1
  319. package/dist/core/sandbox/terminal-handoff.d.ts +68 -0
  320. package/dist/core/sandbox/terminal-handoff.d.ts.map +1 -0
  321. package/dist/core/sandbox/terminal-handoff.js +221 -0
  322. package/dist/core/sandbox/terminal-handoff.js.map +1 -0
  323. package/dist/core/sandbox/terminal-size.d.ts +13 -0
  324. package/dist/core/sandbox/terminal-size.d.ts.map +1 -1
  325. package/dist/core/sandbox/terminal-size.js +23 -2
  326. package/dist/core/sandbox/terminal-size.js.map +1 -1
  327. package/dist/core/sdk.d.ts +24 -2
  328. package/dist/core/sdk.d.ts.map +1 -1
  329. package/dist/core/sdk.js +63 -4
  330. package/dist/core/sdk.js.map +1 -1
  331. package/dist/core/session-export.d.ts +4 -0
  332. package/dist/core/session-export.d.ts.map +1 -0
  333. package/dist/core/session-export.js +32 -0
  334. package/dist/core/session-export.js.map +1 -0
  335. package/dist/core/session-manager.d.ts +13 -1
  336. package/dist/core/session-manager.d.ts.map +1 -1
  337. package/dist/core/session-manager.js +34 -6
  338. package/dist/core/session-manager.js.map +1 -1
  339. package/dist/core/settings-diagnostics.d.ts +9 -0
  340. package/dist/core/settings-diagnostics.d.ts.map +1 -0
  341. package/dist/core/settings-diagnostics.js +21 -0
  342. package/dist/core/settings-diagnostics.js.map +1 -0
  343. package/dist/core/settings-manager.d.ts +172 -1
  344. package/dist/core/settings-manager.d.ts.map +1 -1
  345. package/dist/core/settings-manager.js +160 -11
  346. package/dist/core/settings-manager.js.map +1 -1
  347. package/dist/core/skills.d.ts.map +1 -1
  348. package/dist/core/skills.js +51 -33
  349. package/dist/core/skills.js.map +1 -1
  350. package/dist/core/slash-commands.d.ts.map +1 -1
  351. package/dist/core/slash-commands.js +4 -1
  352. package/dist/core/slash-commands.js.map +1 -1
  353. package/dist/core/system-prompt.d.ts.map +1 -1
  354. package/dist/core/system-prompt.js +8 -2
  355. package/dist/core/system-prompt.js.map +1 -1
  356. package/dist/core/tools/background-shell.d.ts +39 -0
  357. package/dist/core/tools/background-shell.d.ts.map +1 -0
  358. package/dist/core/tools/background-shell.js +81 -0
  359. package/dist/core/tools/background-shell.js.map +1 -0
  360. package/dist/core/tools/bash-command-segments.d.ts.map +1 -1
  361. package/dist/core/tools/bash-command-segments.js +2 -0
  362. package/dist/core/tools/bash-command-segments.js.map +1 -1
  363. package/dist/core/tools/bash.d.ts +44 -16
  364. package/dist/core/tools/bash.d.ts.map +1 -1
  365. package/dist/core/tools/bash.js +264 -32
  366. package/dist/core/tools/bash.js.map +1 -1
  367. package/dist/core/tools/contract-snapshot.d.ts +58 -0
  368. package/dist/core/tools/contract-snapshot.d.ts.map +1 -0
  369. package/dist/core/tools/contract-snapshot.js +51 -0
  370. package/dist/core/tools/contract-snapshot.js.map +1 -0
  371. package/dist/core/tools/contract.d.ts +53 -5
  372. package/dist/core/tools/contract.d.ts.map +1 -1
  373. package/dist/core/tools/contract.js +22 -2
  374. package/dist/core/tools/contract.js.map +1 -1
  375. package/dist/core/tools/delegate.d.ts +6 -4
  376. package/dist/core/tools/delegate.d.ts.map +1 -1
  377. package/dist/core/tools/delegate.js +21 -11
  378. package/dist/core/tools/delegate.js.map +1 -1
  379. package/dist/core/tools/edit-diff.d.ts +48 -5
  380. package/dist/core/tools/edit-diff.d.ts.map +1 -1
  381. package/dist/core/tools/edit-diff.js +217 -8
  382. package/dist/core/tools/edit-diff.js.map +1 -1
  383. package/dist/core/tools/edit.d.ts +8 -0
  384. package/dist/core/tools/edit.d.ts.map +1 -1
  385. package/dist/core/tools/edit.js +72 -10
  386. package/dist/core/tools/edit.js.map +1 -1
  387. package/dist/core/tools/find.d.ts.map +1 -1
  388. package/dist/core/tools/find.js +5 -2
  389. package/dist/core/tools/find.js.map +1 -1
  390. package/dist/core/tools/grep.d.ts.map +1 -1
  391. package/dist/core/tools/grep.js +5 -2
  392. package/dist/core/tools/grep.js.map +1 -1
  393. package/dist/core/tools/index.d.ts +14 -2
  394. package/dist/core/tools/index.d.ts.map +1 -1
  395. package/dist/core/tools/index.js +12 -0
  396. package/dist/core/tools/index.js.map +1 -1
  397. package/dist/core/tools/ls.d.ts.map +1 -1
  398. package/dist/core/tools/ls.js +5 -2
  399. package/dist/core/tools/ls.js.map +1 -1
  400. package/dist/core/tools/lsp.d.ts +19 -1
  401. package/dist/core/tools/lsp.d.ts.map +1 -1
  402. package/dist/core/tools/lsp.js +163 -10
  403. package/dist/core/tools/lsp.js.map +1 -1
  404. package/dist/core/tools/path-permission.d.ts +3 -0
  405. package/dist/core/tools/path-permission.d.ts.map +1 -1
  406. package/dist/core/tools/path-permission.js +16 -4
  407. package/dist/core/tools/path-permission.js.map +1 -1
  408. package/dist/core/tools/path-utils.d.ts +27 -2
  409. package/dist/core/tools/path-utils.d.ts.map +1 -1
  410. package/dist/core/tools/path-utils.js +221 -4
  411. package/dist/core/tools/path-utils.js.map +1 -1
  412. package/dist/core/tools/powershell.d.ts +16 -0
  413. package/dist/core/tools/powershell.d.ts.map +1 -0
  414. package/dist/core/tools/powershell.js +39 -0
  415. package/dist/core/tools/powershell.js.map +1 -0
  416. package/dist/core/tools/read.d.ts.map +1 -1
  417. package/dist/core/tools/read.js +20 -11
  418. package/dist/core/tools/read.js.map +1 -1
  419. package/dist/core/tools/test.d.ts +54 -9
  420. package/dist/core/tools/test.d.ts.map +1 -1
  421. package/dist/core/tools/test.js +239 -19
  422. package/dist/core/tools/test.js.map +1 -1
  423. package/dist/core/tools/write.d.ts +7 -0
  424. package/dist/core/tools/write.d.ts.map +1 -1
  425. package/dist/core/tools/write.js +64 -9
  426. package/dist/core/tools/write.js.map +1 -1
  427. package/dist/core/trust-manager.d.ts.map +1 -1
  428. package/dist/core/trust-manager.js +2 -1
  429. package/dist/core/trust-manager.js.map +1 -1
  430. package/dist/core/verification-lifecycle.d.ts +77 -0
  431. package/dist/core/verification-lifecycle.d.ts.map +1 -0
  432. package/dist/core/verification-lifecycle.js +146 -0
  433. package/dist/core/verification-lifecycle.js.map +1 -0
  434. package/dist/core/workspace/artifacts.d.ts +45 -0
  435. package/dist/core/workspace/artifacts.d.ts.map +1 -0
  436. package/dist/core/workspace/artifacts.js +165 -0
  437. package/dist/core/workspace/artifacts.js.map +1 -0
  438. package/dist/core/workspace/comparison.d.ts +27 -0
  439. package/dist/core/workspace/comparison.d.ts.map +1 -0
  440. package/dist/core/workspace/comparison.js +94 -0
  441. package/dist/core/workspace/comparison.js.map +1 -0
  442. package/dist/core/workspace/git-observer.d.ts +48 -0
  443. package/dist/core/workspace/git-observer.d.ts.map +1 -0
  444. package/dist/core/workspace/git-observer.js +346 -0
  445. package/dist/core/workspace/git-observer.js.map +1 -0
  446. package/dist/core/workspace/projection.d.ts +3 -0
  447. package/dist/core/workspace/projection.d.ts.map +1 -0
  448. package/dist/core/workspace/projection.js +56 -0
  449. package/dist/core/workspace/projection.js.map +1 -0
  450. package/dist/core/workspace/state.d.ts +133 -0
  451. package/dist/core/workspace/state.d.ts.map +1 -0
  452. package/dist/core/workspace/state.js +96 -0
  453. package/dist/core/workspace/state.js.map +1 -0
  454. package/dist/extensions/llama/client.d.ts +6 -0
  455. package/dist/extensions/llama/client.d.ts.map +1 -1
  456. package/dist/extensions/llama/client.js +7 -0
  457. package/dist/extensions/llama/client.js.map +1 -1
  458. package/dist/extensions/llama/index.d.ts.map +1 -1
  459. package/dist/extensions/llama/index.js +2 -0
  460. package/dist/extensions/llama/index.js.map +1 -1
  461. package/dist/extensions/llama/provider.d.ts +3 -1
  462. package/dist/extensions/llama/provider.d.ts.map +1 -1
  463. package/dist/extensions/llama/provider.js +29 -4
  464. package/dist/extensions/llama/provider.js.map +1 -1
  465. package/dist/index.d.ts +8 -5
  466. package/dist/index.d.ts.map +1 -1
  467. package/dist/index.js +7 -4
  468. package/dist/index.js.map +1 -1
  469. package/dist/main.d.ts +6 -0
  470. package/dist/main.d.ts.map +1 -1
  471. package/dist/main.js +58 -23
  472. package/dist/main.js.map +1 -1
  473. package/dist/migrations.d.ts.map +1 -1
  474. package/dist/migrations.js +4 -3
  475. package/dist/migrations.js.map +1 -1
  476. package/dist/modes/acp/server.d.ts +55 -0
  477. package/dist/modes/acp/server.d.ts.map +1 -0
  478. package/dist/modes/acp/server.js +244 -0
  479. package/dist/modes/acp/server.js.map +1 -0
  480. package/dist/modes/acp/translate.d.ts +37 -0
  481. package/dist/modes/acp/translate.d.ts.map +1 -0
  482. package/dist/modes/acp/translate.js +50 -0
  483. package/dist/modes/acp/translate.js.map +1 -0
  484. package/dist/modes/index.d.ts +1 -0
  485. package/dist/modes/index.d.ts.map +1 -1
  486. package/dist/modes/index.js +1 -0
  487. package/dist/modes/index.js.map +1 -1
  488. package/dist/modes/interactive/components/assistant-message.d.ts +29 -0
  489. package/dist/modes/interactive/components/assistant-message.d.ts.map +1 -1
  490. package/dist/modes/interactive/components/assistant-message.js +182 -23
  491. package/dist/modes/interactive/components/assistant-message.js.map +1 -1
  492. package/dist/modes/interactive/components/bash-execution.d.ts +7 -0
  493. package/dist/modes/interactive/components/bash-execution.d.ts.map +1 -1
  494. package/dist/modes/interactive/components/bash-execution.js +20 -0
  495. package/dist/modes/interactive/components/bash-execution.js.map +1 -1
  496. package/dist/modes/interactive/components/custom-editor.d.ts +9 -4
  497. package/dist/modes/interactive/components/custom-editor.d.ts.map +1 -1
  498. package/dist/modes/interactive/components/custom-editor.js +20 -9
  499. package/dist/modes/interactive/components/custom-editor.js.map +1 -1
  500. package/dist/modes/interactive/components/extension-selector.d.ts +7 -1
  501. package/dist/modes/interactive/components/extension-selector.d.ts.map +1 -1
  502. package/dist/modes/interactive/components/extension-selector.js +7 -3
  503. package/dist/modes/interactive/components/extension-selector.js.map +1 -1
  504. package/dist/modes/interactive/components/footer.d.ts +19 -0
  505. package/dist/modes/interactive/components/footer.d.ts.map +1 -1
  506. package/dist/modes/interactive/components/footer.js +70 -10
  507. package/dist/modes/interactive/components/footer.js.map +1 -1
  508. package/dist/modes/interactive/components/model-selector.d.ts +10 -3
  509. package/dist/modes/interactive/components/model-selector.d.ts.map +1 -1
  510. package/dist/modes/interactive/components/model-selector.js +56 -14
  511. package/dist/modes/interactive/components/model-selector.js.map +1 -1
  512. package/dist/modes/interactive/components/permission-preview.d.ts +15 -0
  513. package/dist/modes/interactive/components/permission-preview.d.ts.map +1 -0
  514. package/dist/modes/interactive/components/permission-preview.js +33 -0
  515. package/dist/modes/interactive/components/permission-preview.js.map +1 -0
  516. package/dist/modes/interactive/components/session-selector.d.ts.map +1 -1
  517. package/dist/modes/interactive/components/session-selector.js +2 -2
  518. package/dist/modes/interactive/components/session-selector.js.map +1 -1
  519. package/dist/modes/interactive/components/settings-selector.d.ts +9 -2
  520. package/dist/modes/interactive/components/settings-selector.d.ts.map +1 -1
  521. package/dist/modes/interactive/components/settings-selector.js +128 -56
  522. package/dist/modes/interactive/components/settings-selector.js.map +1 -1
  523. package/dist/modes/interactive/components/settings-submenu.d.ts +72 -0
  524. package/dist/modes/interactive/components/settings-submenu.d.ts.map +1 -0
  525. package/dist/modes/interactive/components/settings-submenu.js +165 -0
  526. package/dist/modes/interactive/components/settings-submenu.js.map +1 -0
  527. package/dist/modes/interactive/components/thinking-selector.d.ts +15 -3
  528. package/dist/modes/interactive/components/thinking-selector.d.ts.map +1 -1
  529. package/dist/modes/interactive/components/thinking-selector.js +74 -17
  530. package/dist/modes/interactive/components/thinking-selector.js.map +1 -1
  531. package/dist/modes/interactive/components/tool-execution.d.ts +23 -1
  532. package/dist/modes/interactive/components/tool-execution.d.ts.map +1 -1
  533. package/dist/modes/interactive/components/tool-execution.js +64 -10
  534. package/dist/modes/interactive/components/tool-execution.js.map +1 -1
  535. package/dist/modes/interactive/external-editor.d.ts.map +1 -1
  536. package/dist/modes/interactive/external-editor.js +2 -1
  537. package/dist/modes/interactive/external-editor.js.map +1 -1
  538. package/dist/modes/interactive/interactive-mode.d.ts +45 -0
  539. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  540. package/dist/modes/interactive/interactive-mode.js +395 -43
  541. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  542. package/dist/modes/interactive/theme/theme.d.ts +12 -0
  543. package/dist/modes/interactive/theme/theme.d.ts.map +1 -1
  544. package/dist/modes/interactive/theme/theme.js +20 -9
  545. package/dist/modes/interactive/theme/theme.js.map +1 -1
  546. package/dist/modes/json-event.d.ts +16 -13
  547. package/dist/modes/json-event.d.ts.map +1 -1
  548. package/dist/modes/json-event.js +20 -6
  549. package/dist/modes/json-event.js.map +1 -1
  550. package/dist/modes/print-mode.d.ts.map +1 -1
  551. package/dist/modes/print-mode.js +27 -12
  552. package/dist/modes/print-mode.js.map +1 -1
  553. package/dist/modes/rpc/rpc-client.d.ts +7 -0
  554. package/dist/modes/rpc/rpc-client.d.ts.map +1 -1
  555. package/dist/modes/rpc/rpc-client.js +7 -0
  556. package/dist/modes/rpc/rpc-client.js.map +1 -1
  557. package/dist/modes/rpc/rpc-mode.d.ts.map +1 -1
  558. package/dist/modes/rpc/rpc-mode.js +3 -0
  559. package/dist/modes/rpc/rpc-mode.js.map +1 -1
  560. package/dist/modes/rpc/rpc-types.d.ts +12 -0
  561. package/dist/modes/rpc/rpc-types.d.ts.map +1 -1
  562. package/dist/modes/rpc/rpc-types.js.map +1 -1
  563. package/dist/package-manager-cli.d.ts +1 -0
  564. package/dist/package-manager-cli.d.ts.map +1 -1
  565. package/dist/package-manager-cli.js +196 -10
  566. package/dist/package-manager-cli.js.map +1 -1
  567. package/dist/utils/frontmatter.d.ts.map +1 -1
  568. package/dist/utils/frontmatter.js +2 -1
  569. package/dist/utils/frontmatter.js.map +1 -1
  570. package/dist/utils/management-http.d.ts +5 -3
  571. package/dist/utils/management-http.d.ts.map +1 -1
  572. package/dist/utils/management-http.js +14 -10
  573. package/dist/utils/management-http.js.map +1 -1
  574. package/dist/utils/shell.d.ts +3 -0
  575. package/dist/utils/shell.d.ts.map +1 -1
  576. package/dist/utils/shell.js +23 -9
  577. package/dist/utils/shell.js.map +1 -1
  578. package/dist/utils/syntax-highlight.d.ts +1 -0
  579. package/dist/utils/syntax-highlight.d.ts.map +1 -1
  580. package/dist/utils/syntax-highlight.js +60 -1
  581. package/dist/utils/syntax-highlight.js.map +1 -1
  582. package/dist/utils/text.d.ts +8 -0
  583. package/dist/utils/text.d.ts.map +1 -0
  584. package/dist/utils/text.js +9 -0
  585. package/dist/utils/text.js.map +1 -0
  586. package/dist/utils/version-check.d.ts.map +1 -1
  587. package/dist/utils/version-check.js +6 -4
  588. package/dist/utils/version-check.js.map +1 -1
  589. package/docs/compaction.md +19 -0
  590. package/docs/custom-provider.md +12 -9
  591. package/docs/environment-variables.md +1 -1
  592. package/docs/extensions.md +35 -7
  593. package/docs/json.md +7 -2
  594. package/docs/keybindings.md +9 -9
  595. package/docs/llama-cpp.md +2 -0
  596. package/docs/models.md +8 -2
  597. package/docs/packages.md +2 -2
  598. package/docs/quickstart.md +1 -1
  599. package/docs/rpc.md +32 -3
  600. package/docs/sdk.md +32 -2
  601. package/docs/settings.md +23 -7
  602. package/docs/skills.md +4 -3
  603. package/docs/terminal-setup.md +23 -7
  604. package/docs/usage.md +10 -5
  605. package/docs/windows.md +24 -2
  606. package/examples/extensions/border-status-editor.ts +1 -1
  607. package/examples/extensions/built-in-tool-renderer.ts +8 -4
  608. package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
  609. package/examples/extensions/custom-provider-anthropic/package.json +1 -1
  610. package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  611. package/examples/extensions/git-checkpoint.ts +24 -36
  612. package/examples/extensions/gondolin/package-lock.json +2 -2
  613. package/examples/extensions/gondolin/package.json +1 -1
  614. package/examples/extensions/minimal-mode.ts +2 -2
  615. package/examples/extensions/notify.ts +3 -1
  616. package/examples/extensions/permission-gate.ts +1 -1
  617. package/examples/extensions/plan-mode/index.ts +1 -1
  618. package/examples/extensions/rpc-demo.ts +1 -1
  619. package/examples/extensions/sandbox/package-lock.json +2 -2
  620. package/examples/extensions/sandbox/package.json +1 -1
  621. package/examples/extensions/subagent/README.md +1 -1
  622. package/examples/extensions/subagent/index.ts +6 -1
  623. package/examples/extensions/titlebar-spinner.ts +1 -1
  624. package/examples/extensions/with-deps/package-lock.json +2 -2
  625. package/examples/extensions/with-deps/package.json +1 -1
  626. package/examples/rpc-extension-ui.ts +1 -1
  627. package/examples/sdk/06-extensions.ts +1 -1
  628. package/examples/sdk/README.md +1 -1
  629. package/npm-shrinkwrap.json +439 -405
  630. package/package.json +17 -17
  631. package/dist/server/create-harness.d.ts +0 -26
  632. package/dist/server/create-harness.d.ts.map +0 -1
  633. package/dist/server/create-harness.js +0 -107
  634. package/dist/server/create-harness.js.map +0 -1
@@ -6,6 +6,7 @@
6
6
  * permission, context, evidence), which is what keeps a new tool from silently
7
7
  * defaulting into "unclassified".
8
8
  */
9
+ import { Type } from "typebox";
9
10
  export const ALL_CAPABILITIES = new Set([
10
11
  "fs.read",
11
12
  "fs.write",
@@ -16,8 +17,10 @@ export const ALL_CAPABILITIES = new Set([
16
17
  "state",
17
18
  ]);
18
19
  /**
19
- * Conservative contract for a tool registered without one MCP servers and
20
- * third-party extensions cannot supply a `contract`. Full capability set (so it can
20
+ * Conservative contract for a tool registered without one -- third-party extension
21
+ * tools, which cannot supply a `contract`. MCP tools no longer land here: they reach
22
+ * the model through the built-in `mcp` proxy, whose contract is declared in
23
+ * `core/mcp/contract.ts`. Full capability set (so it can
21
24
  * never widen a delegation ceiling), `ask` by default, never evicted, schema
22
25
  * deferred, emits nothing. Matching is exact-argument only: a foreign tool's rule
23
26
  * authorizes exactly the call it was generated from, never a pattern.
@@ -45,4 +48,21 @@ export function resolveToolContract(lookup, toolName) {
45
48
  export function resolveToolContext(lookup, toolName) {
46
49
  return lookup(toolName) ?? UNCLASSIFIED;
47
50
  }
51
+ /**
52
+ * A tool whose call shapes differ, declared so a provider can still see its fields.
53
+ *
54
+ * `Type.Union` compiles to `{ anyOf: [...] }`, which carries no top-level
55
+ * `properties`. The Anthropic request builder reads `properties` and `required`
56
+ * directly (`anthropic-messages.js`, `legacyInputSchema`), so a union reached the
57
+ * model as an object with no fields at all. It then guessed, and our own
58
+ * validation rejected the guess.
59
+ *
60
+ * The union still decides what is valid. `properties` is advertisement, listing
61
+ * every field across the variants so a provider that ignores `anyOf` has
62
+ * something to work from. It deliberately carries no `required`, because no field
63
+ * is required by every variant.
64
+ */
65
+ export function toolUnion(variants, properties) {
66
+ return Type.Union(variants, { type: "object", properties });
67
+ }
48
68
  //# sourceMappingURL=contract.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"contract.js","sourceRoot":"","sources":["../../../src/core/tools/contract.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AASH,MAAM,CAAC,MAAM,gBAAgB,GAA4B,IAAI,GAAG,CAAa;IAC5E,SAAS;IACT,UAAU;IACV,MAAM;IACN,KAAK;IACL,UAAU;IACV,IAAI;IACJ,OAAO;CACP,CAAC,CAAC;AAgMH;;;;;;;;;;GAUG;AACH,MAAM,CAAC,MAAM,YAAY,GAAmC;IAC3D,YAAY,EAAE,gBAAgB;IAC9B,UAAU,EAAE;QACX,eAAe,EAAE,KAAK;QACtB,OAAO,EAAE,CAAC,WAAW,EAAE,MAAM,EAAE,EAAE,CAAC,WAAW,KAAK,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC;QACxE,QAAQ,EAAE,CAAC,WAAW,EAAE,EAAE,CAAC,eAAe,WAAW,EAAE;QACvD,WAAW,EAAE,CAAC,MAAM,EAAE,EAAE,CAAC,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC;KAC/C;IACD,OAAO,EAAE,EAAE,iBAAiB,EAAE,KAAK,EAAE,WAAW,EAAE,KAAK,EAAE;IACzD,QAAQ,EAAE,EAAE,KAAK,EAAE,IAAI,GAAG,EAAE,EAAE,OAAO,EAAE,GAAG,EAAE,CAAC,EAAE,EAAE;CACjD,CAAC;AAEF,kEAAkE;AAClE,MAAM,UAAU,mBAAmB,CAClC,MAAsD,EACtD,QAAgB,EACD;IACf,OAAO,MAAM,CAAC,QAAQ,CAAC,IAAI,YAAY,CAAC;AAAA,CACxC;AAED,qFAAqF;AACrF,MAAM,UAAU,kBAAkB,CACjC,MAAuE,EACvE,QAAgB,EACgB;IAChC,OAAO,MAAM,CAAC,QAAQ,CAAC,IAAI,YAAY,CAAC;AAAA,CACxC","sourcesContent":["/**\n * The canonical tool contract. Settled by ADR 0010 and specified in full at\n * docs/architecture/contracts.md § 1 — this module implements that shape, it does\n * not redesign it. `contract` is required on every registered tool, and so is every\n * sub-field: a tool cannot compile without answering all four axes (capabilities,\n * permission, context, evidence), which is what keeps a new tool from silently\n * defaulting into \"unclassified\".\n */\n\nimport type { AgentToolResult } from \"apex-code-agent-core\";\nimport type { Static, TSchema } from \"typebox\";\nimport type { ToolDefinition } from \"../extensions/types.ts\";\n\n/** What class of thing a tool does. A set, not a single value — `bash` is `{exec}`. */\nexport type Capability = \"fs.read\" | \"fs.write\" | \"exec\" | \"net\" | \"delegate\" | \"ui\" | \"state\";\n\nexport const ALL_CAPABILITIES: ReadonlySet<Capability> = new Set<Capability>([\n\t\"fs.read\",\n\t\"fs.write\",\n\t\"exec\",\n\t\"net\",\n\t\"delegate\",\n\t\"ui\",\n\t\"state\",\n]);\n\nexport type PermissionBehavior = \"allow\" | \"deny\" | \"ask\";\n\n/**\n * `ruleContent` is interpreted by the tool, never by the rule engine (ADR 0010).\n * That is what lets `Bash(git commit:*)` and `Read(~/.ssh/**)` mean entirely\n * different things while the engine that resolves precedence stays tool-agnostic.\n */\nexport interface PermissionSpec<TParams extends TSchema = TSchema> {\n\t/** Behavior when no rule matches. Read-only tools may default to \"allow\". */\n\tdefaultBehavior: PermissionBehavior;\n\n\t/** Does this call match this rule's content? The tool owns the grammar. */\n\tmatches(ruleContent: string, params: Static<TParams>): boolean;\n\n\t/** Human-readable rendering of a rule, for prompts and denial messages. */\n\tdescribe(ruleContent: string): string;\n\n\t/**\n\t * The rule that would allow this exact call — what \"always allow this\"\n\t * persists. Return null when the call is not generalizable into a rule.\n\t */\n\truleForCall(params: Static<TParams>): string | null;\n}\n\nexport interface ContextSpec {\n\t/**\n\t * True when the result's information is recoverable — the same content can be\n\t * obtained again by re-running the tool or reading the workspace.\n\t *\n\t * ONLY recoverable results may be evicted (Phase 3). A tool whose result cannot\n\t * be regenerated (a nondeterministic command, a consumed one-shot resource)\n\t * must set this false, or eviction would silently destroy information the\n\t * transcript is the only record of.\n\t */\n\tresultRecoverable: boolean;\n\n\t/** Marker substituted for an evicted result. */\n\tevictionMarker?: string;\n\n\t/** Announce by name only; load the parameter schema on demand. */\n\tdeferSchema: boolean;\n\n\t/** Soft cap on result tokens before truncation. */\n\toutputBudgetTokens?: number;\n}\n\nexport type EvidenceKind = \"diff\" | \"test\" | \"command\" | \"manual\" | \"workflow\" | \"diagnostic\";\n\n/** Source-observed command facts. `exitCode` is absent only when execution never began. */\nexport interface CommandEvidenceRecord {\n\tkind: \"command\";\n\tcommand: string;\n\tcwd?: string;\n\texecutable?: string;\n\targv?: string[];\n\texitCode?: number | null;\n}\n\n/** A file mutation is identified by hashes and paths, never raw file or patch contents. */\nexport interface DiffEvidenceRecord {\n\tkind: \"diff\";\n\tpath: string;\n\tpatchHash?: string;\n\tcontentHash?: string;\n\tbyteCount?: number;\n}\n\n/** Zero-filled diagnostic severity buckets for one bounded language-server outcome. */\nexport interface DiagnosticSeverityCounts {\n\terror: number;\n\twarning: number;\n\tinformation: number;\n\thint: number;\n\tunspecified: number;\n\tother: number;\n}\n\n/** Stable durable classification. Free-form server and process errors never enter evidence. */\nexport type DiagnosticUnavailableKind =\n\t| \"no-server\"\n\t| \"disposed\"\n\t| \"unsupported-sync\"\n\t| \"timed-out\"\n\t| \"aborted\"\n\t| \"superseded\"\n\t| \"server-failed\";\n\n/** Bounded post-mutation diagnostic facts, never diagnostic messages or rendered failure reasons. */\nexport type DiagnosticEvidenceRecord =\n\t| {\n\t\t\tkind: \"diagnostic\";\n\t\t\tpath: string;\n\t\t\tstatus: \"ok\";\n\t\t\tserverId: string;\n\t\t\tdiagnosticCount: number;\n\t\t\tseverityCounts: DiagnosticSeverityCounts;\n\t\t\ttruncated: boolean;\n\t }\n\t| {\n\t\t\tkind: \"diagnostic\";\n\t\t\tpath: string;\n\t\t\tstatus: \"unavailable\";\n\t\t\tserverId?: string;\n\t\t\tunavailableKind: DiagnosticUnavailableKind;\n\t };\n\n/** Normalized argv-based test execution facts. */\nexport interface TestEvidenceRecord {\n\tkind: \"test\";\n\tcwd: string;\n\texecutable: string;\n\targv: string[];\n\texitCode: number | null;\n}\n\n/** Explicit human attestation; policy decides how, or whether, it is sufficient. */\nexport interface ManualEvidenceRecord {\n\tkind: \"manual\";\n\tvalue?: unknown;\n\tobserved?: unknown;\n\tstatus?: string;\n}\n\n/** Source facts from approval and delegation workflows. */\nexport interface WorkflowEvidenceRecord {\n\tkind: \"workflow\";\n\tplan?: string;\n\tapproved?: boolean;\n\tagentType?: string;\n\ttask?: string;\n\thandle?: string;\n}\n\n/** A structured source record. Policy is a separate consumer, not an additional variant. */\nexport type EvidenceRecord =\n\t| CommandEvidenceRecord\n\t| DiffEvidenceRecord\n\t| DiagnosticEvidenceRecord\n\t| TestEvidenceRecord\n\t| ManualEvidenceRecord\n\t| WorkflowEvidenceRecord;\n\n/** Durable destination for source-level tool evidence. Policy is deliberately not part of this boundary. */\nexport interface EvidenceSink {\n\trecord(entry: { toolName: string; records: EvidenceRecord[] }): void;\n\trecordDiagnostic?(diagnostic: EvidenceCaptureDiagnostic): void;\n}\n\n/** A capture failure is observable but never changes an already-completed tool result. */\nexport interface EvidenceCaptureDiagnostic {\n\ttoolName: string;\n\treason: string;\n}\n\nexport interface EvidenceSpec<TParams extends TSchema = TSchema, TDetails = unknown> {\n\t/** Kinds this tool can emit. Empty set is valid and explicit. */\n\temits: ReadonlySet<EvidenceKind>;\n\n\t/**\n\t * Derive evidence from a completed call. Runs inside the tool's own execution\n\t * path, with access to what actually happened, not a reconstruction from\n\t * rendered output.\n\t */\n\tcapture(params: Static<TParams>, result: AgentToolResult<TDetails>): EvidenceRecord[];\n}\n\nexport interface ToolContract<TParams extends TSchema = TSchema, TDetails = unknown> {\n\tcapabilities: ReadonlySet<Capability>;\n\tpermission: PermissionSpec<TParams>;\n\tcontext: ContextSpec;\n\tevidence: EvidenceSpec<TParams, TDetails>;\n}\n\n/**\n * Apex Code extends upstream ToolDefinition with exactly one required field.\n *\n * `TState` defaults to `any`, matching upstream `ToolDefinition` exactly (not\n * `unknown`). That default is load-bearing: TypeScript compares two instantiations\n * of the *same* generic interface (here, both rooted in `ToolDefinition`) using each\n * type parameter's declared variance, without expanding `Static<TParams>`\n * structurally — but only when every type argument lines up, including the ones a\n * caller left defaulted. A mismatched default reintroduces a full structural check,\n * where `Static<any>` does not behave like `any`, and breaks every pre-existing\n * `ToolDefinition<any, X>`-typed consumer across the codebase.\n */\nexport interface ApexToolDefinition<TParams extends TSchema = TSchema, TDetails = unknown, TState = any>\n\textends ToolDefinition<TParams, TDetails, TState> {\n\tcontract: ToolContract<TParams, TDetails>;\n}\n\n/**\n * Conservative contract for a tool registered without one — MCP servers and\n * third-party extensions cannot supply a `contract`. Full capability set (so it can\n * never widen a delegation ceiling), `ask` by default, never evicted, schema\n * deferred, emits nothing. Matching is exact-argument only: a foreign tool's rule\n * authorizes exactly the call it was generated from, never a pattern.\n *\n * This must also be reported as unclassified wherever a consumer describes the tool\n * registry (contracts.md invariant 1) — a conservative default nobody can see is\n * indistinguishable from a bug.\n */\nexport const UNCLASSIFIED: ToolContract<TSchema, unknown> = {\n\tcapabilities: ALL_CAPABILITIES,\n\tpermission: {\n\t\tdefaultBehavior: \"ask\",\n\t\tmatches: (ruleContent, params) => ruleContent === JSON.stringify(params),\n\t\tdescribe: (ruleContent) => `Exact call: ${ruleContent}`,\n\t\truleForCall: (params) => JSON.stringify(params),\n\t},\n\tcontext: { resultRecoverable: false, deferSchema: false },\n\tevidence: { emits: new Set(), capture: () => [] },\n};\n\n/** Resolve a complete tool contract for enforcement consumers. */\nexport function resolveToolContract(\n\tlookup: (toolName: string) => ToolContract | undefined,\n\ttoolName: string,\n): ToolContract {\n\treturn lookup(toolName) ?? UNCLASSIFIED;\n}\n\n/** Resolve the context projection using the same canonical foreign-tool fallback. */\nexport function resolveToolContext(\n\tlookup: (toolName: string) => Pick<ToolContract, \"context\"> | undefined,\n\ttoolName: string,\n): Pick<ToolContract, \"context\"> {\n\treturn lookup(toolName) ?? UNCLASSIFIED;\n}\n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AE,UAAmC,EAAE;IACrG,OAAO,IAAI,CAAC,KAAK,CAAC,QAAQ,EAAE,EAAE,IAAI,EAAE,QAAQ,EAAE,UAAU,EAAE,CAAC,CAAC;AAAA,CAC5D","sourcesContent":["/**\n * The canonical tool contract. Settled by ADR 0010 and specified in full at\n * docs/architecture/contracts.md § 1 — this module implements that shape, it does\n * not redesign it. `contract` is required on every registered tool, and so is every\n * sub-field: a tool cannot compile without answering all four axes (capabilities,\n * permission, context, evidence), which is what keeps a new tool from silently\n * defaulting into \"unclassified\".\n */\n\nimport type { AgentToolResult } from \"apex-code-agent-core\";\nimport { type Static, type TSchema, Type } from \"typebox\";\nimport type { ToolDefinition } from \"../extensions/types.ts\";\nimport type { PermissionPreview } from \"../permissions/responder.ts\";\n\n/** What class of thing a tool does. A set, not a single value — `bash` is `{exec}`. */\nexport type Capability = \"fs.read\" | \"fs.write\" | \"exec\" | \"net\" | \"delegate\" | \"ui\" | \"state\";\n\nexport const ALL_CAPABILITIES: ReadonlySet<Capability> = new Set<Capability>([\n\t\"fs.read\",\n\t\"fs.write\",\n\t\"exec\",\n\t\"net\",\n\t\"delegate\",\n\t\"ui\",\n\t\"state\",\n]);\n\nexport type PermissionBehavior = \"allow\" | \"deny\" | \"ask\";\n\n/**\n * `ruleContent` is interpreted by the tool, never by the rule engine (ADR 0010).\n * That is what lets `Bash(git commit:*)` and `Read(~/.ssh/**)` mean entirely\n * different things while the engine that resolves precedence stays tool-agnostic.\n */\nexport interface PermissionSpec<TParams extends TSchema = TSchema> {\n\t/** Behavior when no rule matches. Read-only tools may default to \"allow\". */\n\tdefaultBehavior: PermissionBehavior;\n\n\t/**\n\t * Per-call behavior when no rule matches, for tools whose calls differ in\n\t * nature (bash: launching a command is \"ask\", retrieving or killing an\n\t * already-approved background command is \"allow\"). Return undefined to fall\n\t * back to `defaultBehavior`. Floors and matching rules still outrank it --\n\t * this only replaces the fallthrough, never a rule or a mode floor.\n\t */\n\tdefaultBehaviorFor?(params: Static<TParams>): PermissionBehavior | undefined;\n\n\t/** Prepare canonical operation facts on the validated call before authorization and execution. */\n\tprepareCall?(params: Static<TParams>): void;\n\n\t/**\n\t * Describe, for a human about to approve it, what this call would change.\n\t *\n\t * Called by the gate only once it has resolved to `ask`, so an allowed or denied\n\t * call never pays for it. It must read through the value `prepareCall` stored\n\t * rather than re-deriving a target, which is what keeps the diff the user\n\t * approves and the bytes execution writes the same file (ADR 0029). It must not\n\t * execute the tool, write, or widen what the gate already validated.\n\t */\n\tpreviewCall?(params: Static<TParams>): PermissionPreview;\n\t/** Does this call match this rule's content as an allow rule? */\n\tmatches(ruleContent: string, params: Static<TParams>): boolean;\n\t/** Optional deny matcher. It may identify any prohibited part of a structured call. */\n\tmatchesDeny?(ruleContent: string, params: Static<TParams>): boolean;\n\t/** True when the call contains grammar that cannot be safely authorized by an allow. */\n\tisUnknown?(params: Static<TParams>): boolean;\n\n\t/** Human-readable rendering of a rule, for prompts and denial messages. */\n\tdescribe(ruleContent: string): string;\n\n\t/**\n\t * The rule that would allow this exact call — what \"always allow this\"\n\t * persists. Return null when the call is not generalizable into a rule.\n\t */\n\truleForCall(params: Static<TParams>): string | null;\n}\n\nexport interface ContextSpec {\n\t/**\n\t * True when the result's information is recoverable — the same content can be\n\t * obtained again by re-running the tool or reading the workspace.\n\t *\n\t * ONLY recoverable results may be evicted (Phase 3). A tool whose result cannot\n\t * be regenerated (a nondeterministic command, a consumed one-shot resource)\n\t * must set this false, or eviction would silently destroy information the\n\t * transcript is the only record of.\n\t */\n\tresultRecoverable: boolean;\n\n\t/** Marker substituted for an evicted result. */\n\tevictionMarker?: string;\n\n\t/** Announce by name only; load the parameter schema on demand. */\n\tdeferSchema: boolean;\n\n\t/** Soft cap on result tokens before truncation. */\n\toutputBudgetTokens?: number;\n}\n\nexport type EvidenceKind = \"diff\" | \"test\" | \"command\" | \"manual\" | \"workflow\" | \"diagnostic\";\n\n/** Source-observed command facts. `exitCode` is absent only when execution never began. */\nexport interface CommandEvidenceRecord {\n\tkind: \"command\";\n\tcommand: string;\n\tcwd?: string;\n\texecutable?: string;\n\targv?: string[];\n\texitCode?: number | null;\n}\n\n/** A file mutation is identified by hashes and paths, never raw file or patch contents. */\nexport interface DiffEvidenceRecord {\n\tkind: \"diff\";\n\tpath: string;\n\tpatchHash?: string;\n\tcontentHash?: string;\n\tbyteCount?: number;\n}\n\n/** Zero-filled diagnostic severity buckets for one bounded language-server outcome. */\nexport interface DiagnosticSeverityCounts {\n\terror: number;\n\twarning: number;\n\tinformation: number;\n\thint: number;\n\tunspecified: number;\n\tother: number;\n}\n\n/** Stable durable classification. Free-form server and process errors never enter evidence. */\nexport type DiagnosticUnavailableKind =\n\t| \"no-server\"\n\t| \"disposed\"\n\t| \"unsupported-sync\"\n\t| \"timed-out\"\n\t| \"aborted\"\n\t| \"superseded\"\n\t| \"server-failed\";\n\n/** Bounded post-mutation diagnostic facts, never diagnostic messages or rendered failure reasons. */\nexport type DiagnosticEvidenceRecord =\n\t| {\n\t\t\tkind: \"diagnostic\";\n\t\t\tpath: string;\n\t\t\tstatus: \"ok\";\n\t\t\tserverId: string;\n\t\t\tdiagnosticCount: number;\n\t\t\tseverityCounts: DiagnosticSeverityCounts;\n\t\t\ttruncated: boolean;\n\t }\n\t| {\n\t\t\tkind: \"diagnostic\";\n\t\t\tpath: string;\n\t\t\tstatus: \"unavailable\";\n\t\t\tserverId?: string;\n\t\t\tunavailableKind: DiagnosticUnavailableKind;\n\t };\n\n/** How a `test` run actually ended. */\nexport type TestProcessOutcome = \"exit\" | \"signal\" | \"timeout\" | \"cancelled\" | \"spawn-failed\";\n\n/** Bounded argv-based test execution facts. Full output never enters evidence; it lives in artifacts. */\nexport interface TestEvidenceRecord {\n\tkind: \"test\";\n\tcwd: string;\n\texecutable: string;\n\targv: string[];\n\texitCode: number | null;\n\t/** How the run ended. Unset means a legacy record; derive from `exitCode` when reading. */\n\toutcome?: TestProcessOutcome;\n\t/** True when the model-facing view omitted part of a stream (full output lives in artifacts). */\n\toutputTruncated?: boolean;\n}\n\n/** Explicit human attestation; policy decides how, or whether, it is sufficient. */\nexport interface ManualEvidenceRecord {\n\tkind: \"manual\";\n\tvalue?: unknown;\n\tobserved?: unknown;\n\tstatus?: string;\n}\n\n/** Source facts from approval and delegation workflows. */\nexport interface WorkflowEvidenceRecord {\n\tkind: \"workflow\";\n\tplan?: string;\n\tapproved?: boolean;\n\tagentType?: string;\n\ttask?: string;\n\thandle?: string;\n}\n\n/** A structured source record. Policy is a separate consumer, not an additional variant. */\nexport type EvidenceRecord =\n\t| CommandEvidenceRecord\n\t| DiffEvidenceRecord\n\t| DiagnosticEvidenceRecord\n\t| TestEvidenceRecord\n\t| ManualEvidenceRecord\n\t| WorkflowEvidenceRecord;\n\n/** Durable destination for source-level tool evidence. Policy is deliberately not part of this boundary. */\nexport interface EvidenceSink {\n\trecord(entry: { toolName: string; records: EvidenceRecord[] }): void;\n\trecordDiagnostic?(diagnostic: EvidenceCaptureDiagnostic): void;\n}\n\n/** A capture failure is observable but never changes an already-completed tool result. */\nexport interface EvidenceCaptureDiagnostic {\n\ttoolName: string;\n\treason: string;\n}\n\nexport interface EvidenceSpec<TParams extends TSchema = TSchema, TDetails = unknown> {\n\t/** Kinds this tool can emit. Empty set is valid and explicit. */\n\temits: ReadonlySet<EvidenceKind>;\n\n\t/**\n\t * Derive evidence from a completed call. Runs inside the tool's own execution\n\t * path, with access to what actually happened, not a reconstruction from\n\t * rendered output.\n\t */\n\tcapture(params: Static<TParams>, result: AgentToolResult<TDetails>): EvidenceRecord[];\n}\n\nexport interface ToolContract<TParams extends TSchema = TSchema, TDetails = unknown> {\n\tcapabilities: ReadonlySet<Capability>;\n\tpermission: PermissionSpec<TParams>;\n\tcontext: ContextSpec;\n\tevidence: EvidenceSpec<TParams, TDetails>;\n}\n\n/**\n * Apex Code extends upstream ToolDefinition with exactly one required field.\n *\n * `TState` defaults to `any`, matching upstream `ToolDefinition` exactly (not\n * `unknown`). That default is load-bearing: TypeScript compares two instantiations\n * of the *same* generic interface (here, both rooted in `ToolDefinition`) using each\n * type parameter's declared variance, without expanding `Static<TParams>`\n * structurally — but only when every type argument lines up, including the ones a\n * caller left defaulted. A mismatched default reintroduces a full structural check,\n * where `Static<any>` does not behave like `any`, and breaks every pre-existing\n * `ToolDefinition<any, X>`-typed consumer across the codebase.\n */\nexport interface ApexToolDefinition<TParams extends TSchema = TSchema, TDetails = unknown, TState = any>\n\textends ToolDefinition<TParams, TDetails, TState> {\n\tcontract: ToolContract<TParams, TDetails>;\n}\n\n/**\n * Conservative contract for a tool registered without one -- third-party extension\n * tools, which cannot supply a `contract`. MCP tools no longer land here: they reach\n * the model through the built-in `mcp` proxy, whose contract is declared in\n * `core/mcp/contract.ts`. Full capability set (so it can\n * never widen a delegation ceiling), `ask` by default, never evicted, schema\n * deferred, emits nothing. Matching is exact-argument only: a foreign tool's rule\n * authorizes exactly the call it was generated from, never a pattern.\n *\n * This must also be reported as unclassified wherever a consumer describes the tool\n * registry (contracts.md invariant 1) — a conservative default nobody can see is\n * indistinguishable from a bug.\n */\nexport const UNCLASSIFIED: ToolContract<TSchema, unknown> = {\n\tcapabilities: ALL_CAPABILITIES,\n\tpermission: {\n\t\tdefaultBehavior: \"ask\",\n\t\tmatches: (ruleContent, params) => ruleContent === JSON.stringify(params),\n\t\tdescribe: (ruleContent) => `Exact call: ${ruleContent}`,\n\t\truleForCall: (params) => JSON.stringify(params),\n\t},\n\tcontext: { resultRecoverable: false, deferSchema: false },\n\tevidence: { emits: new Set(), capture: () => [] },\n};\n\n/** Resolve a complete tool contract for enforcement consumers. */\nexport function resolveToolContract(\n\tlookup: (toolName: string) => ToolContract | undefined,\n\ttoolName: string,\n): ToolContract {\n\treturn lookup(toolName) ?? UNCLASSIFIED;\n}\n\n/** Resolve the context projection using the same canonical foreign-tool fallback. */\nexport function resolveToolContext(\n\tlookup: (toolName: string) => Pick<ToolContract, \"context\"> | undefined,\n\ttoolName: string,\n): Pick<ToolContract, \"context\"> {\n\treturn lookup(toolName) ?? UNCLASSIFIED;\n}\n\n/**\n * A tool whose call shapes differ, declared so a provider can still see its fields.\n *\n * `Type.Union` compiles to `{ anyOf: [...] }`, which carries no top-level\n * `properties`. The Anthropic request builder reads `properties` and `required`\n * directly (`anthropic-messages.js`, `legacyInputSchema`), so a union reached the\n * model as an object with no fields at all. It then guessed, and our own\n * validation rejected the guess.\n *\n * The union still decides what is valid. `properties` is advertisement, listing\n * every field across the variants so a provider that ignores `anyOf` has\n * something to work from. It deliberately carries no `required`, because no field\n * is required by every variant.\n */\nexport function toolUnion<T extends TSchema[]>(variants: [...T], properties: Record<string, TSchema>) {\n\treturn Type.Union(variants, { type: \"object\", properties });\n}\n"]}
@@ -1,6 +1,6 @@
1
1
  import { type Static, Type } from "typebox";
2
2
  import type { DelegationRuntimeOptions } from "../delegation/runtime.ts";
3
- import type { ApexToolDefinition } from "./contract.ts";
3
+ import { type ApexToolDefinition } from "./contract.ts";
4
4
  declare const delegateSchema: Type.TUnion<[Type.TObject<{
5
5
  agentType: Type.TString;
6
6
  task: Type.TString;
@@ -21,9 +21,11 @@ export interface DelegateDetails {
21
21
  * real child through the injected `DelegationRuntimeOptions` -- capability ceiling,
22
22
  * derived permission store, and child-session construction all live behind that
23
23
  * injection (ADR 0008), matching the `todo_write`/`tool_schema` convention of
24
- * injecting collaborators rather than reaching for global state. Recursion depth
25
- * (task 5.3), artifact isolation (task 5.4), and real agent discovery (task 5.5,
26
- * replacing the resolver a test or caller injects here) are not yet wired.
24
+ * injecting collaborators rather than reaching for global state. Recursion
25
+ * depth, artifact isolation, and real agent discovery are wired:
26
+ * `../delegation/runtime.ts` bounds depth and roots per-child artifact
27
+ * directories, and `../delegation/agents.ts` supplies production markdown
28
+ * discovery through the injected resolver.
27
29
  */
28
30
  export declare function createDelegateToolDefinition(runtime: DelegationRuntimeOptions): ApexToolDefinition<typeof delegateSchema, DelegateDetails>;
29
31
  export declare function createDelegateTool(runtime: DelegationRuntimeOptions): import("apex-code-agent-core").AgentTool<Type.TUnion<[Type.TObject<{
@@ -1 +1 @@
1
- {"version":3,"file":"delegate.d.ts","sourceRoot":"","sources":["../../../src/core/tools/delegate.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,KAAK,MAAM,EAAE,IAAI,EAAE,MAAM,SAAS,CAAC;AAE5C,OAAO,KAAK,EAAE,wBAAwB,EAAE,MAAM,0BAA0B,CAAC;AAEzE,OAAO,KAAK,EAAE,kBAAkB,EAAkB,MAAM,eAAe,CAAC;AAGxE,QAAA,MAAM,cAAc;;;;;;;IAYlB,CAAC;AAEH,MAAM,MAAM,aAAa,GAAG,MAAM,CAAC,OAAO,cAAc,CAAC,CAAC;AAE1D,MAAM,WAAW,eAAe;IAC/B,SAAS,EAAE,MAAM,CAAC;IAClB,IAAI,EAAE,MAAM,CAAC;IACb,MAAM,EAAE,MAAM,CAAC;IACf,MAAM,CAAC,EAAE,MAAM,CAAC;CAChB;AAgBD;;;;;;;;GAQG;AACH,wBAAgB,4BAA4B,CAC3C,OAAO,EAAE,wBAAwB,GAC/B,kBAAkB,CAAC,OAAO,cAAc,EAAE,eAAe,CAAC,CAiD5D;AAED,wBAAgB,kBAAkB,CAAC,OAAO,EAAE,wBAAwB;;;;;;;uBAEnE","sourcesContent":["import { Text } from \"@earendil-works/pi-tui\";\nimport type { AgentToolResult } from \"apex-code-agent-core\";\nimport { minimatch } from \"minimatch\";\nimport { type Static, Type } from \"typebox\";\nimport type { Theme } from \"../../modes/interactive/theme/theme.ts\";\nimport type { DelegationRuntimeOptions } from \"../delegation/runtime.ts\";\nimport { retrieveDelegationResult, runDelegation } from \"../delegation/runtime.ts\";\nimport type { ApexToolDefinition, EvidenceRecord } from \"./contract.ts\";\nimport { wrapToolDefinition } from \"./tool-definition-wrapper.ts\";\n\nconst delegateSchema = Type.Union([\n\tType.Object({\n\t\tagentType: Type.String({ description: \"The type of subagent to delegate to.\" }),\n\t\ttask: Type.String({ description: \"The task to delegate.\" }),\n\t\tbackground: Type.Optional(\n\t\t\tType.Boolean({ description: \"Return a handle immediately instead of waiting for the child.\" }),\n\t\t),\n\t}),\n\tType.Object({\n\t\tagentType: Type.String({ description: \"The agent type that produced the background result.\" }),\n\t\thandle: Type.String({ description: \"A background delegation handle returned by an earlier call.\" }),\n\t}),\n]);\n\nexport type DelegateInput = Static<typeof delegateSchema>;\n\nexport interface DelegateDetails {\n\tagentType: string;\n\ttask: string;\n\toutput: string;\n\thandle?: string;\n}\n\nfunction formatDelegateCall(input: DelegateInput, theme: Theme): string {\n\tif (\"handle\" in input) {\n\t\treturn `${theme.fg(\"toolTitle\", theme.bold(\"delegate\"))} ${theme.fg(\"accent\", input.agentType)} · retrieve`;\n\t}\n\tconst task = input.task.replace(/\\s+/g, \" \").trim();\n\treturn `${theme.fg(\"toolTitle\", theme.bold(\"delegate\"))} ${theme.fg(\"accent\", input.agentType)} · ${theme.fg(\"toolOutput\", task)}`;\n}\n\nfunction formatDelegateResult(details: DelegateDetails, expanded: boolean, theme: Theme): string {\n\tif (expanded) return theme.fg(\"toolOutput\", details.output);\n\tconst lineCount = details.output ? details.output.split(\"\\n\").length : 0;\n\treturn `${theme.fg(\"accent\", details.agentType)} · ${lineCount} ${lineCount === 1 ? \"line\" : \"lines\"}`;\n}\n\n/**\n * The delegation entry point (task 4.6's contract, task 5.2's execution). Runs a\n * real child through the injected `DelegationRuntimeOptions` -- capability ceiling,\n * derived permission store, and child-session construction all live behind that\n * injection (ADR 0008), matching the `todo_write`/`tool_schema` convention of\n * injecting collaborators rather than reaching for global state. Recursion depth\n * (task 5.3), artifact isolation (task 5.4), and real agent discovery (task 5.5,\n * replacing the resolver a test or caller injects here) are not yet wired.\n */\nexport function createDelegateToolDefinition(\n\truntime: DelegationRuntimeOptions,\n): ApexToolDefinition<typeof delegateSchema, DelegateDetails> {\n\treturn {\n\t\tname: \"delegate\",\n\t\tlabel: \"delegate\",\n\t\tdescription: \"Delegate a task to a subagent.\",\n\t\tparameters: delegateSchema,\n\t\tcontract: {\n\t\t\tcapabilities: new Set([\"delegate\"]),\n\t\t\tpermission: {\n\t\t\t\tdefaultBehavior: \"ask\",\n\t\t\t\tmatches: (ruleContent, params) => minimatch(params.agentType, ruleContent),\n\t\t\t\tdescribe: (ruleContent) => `Delegate to agent types matching \"${ruleContent}\"`,\n\t\t\t\truleForCall: (params) => params.agentType,\n\t\t\t},\n\t\t\tcontext: { resultRecoverable: false, deferSchema: true },\n\t\t\tevidence: {\n\t\t\t\temits: new Set([\"workflow\"]),\n\t\t\t\tcapture: (params): EvidenceRecord[] =>\n\t\t\t\t\t\"task\" in params\n\t\t\t\t\t\t? [{ kind: \"workflow\", agentType: params.agentType, task: params.task }]\n\t\t\t\t\t\t: [{ kind: \"workflow\", agentType: params.agentType, handle: params.handle }],\n\t\t\t},\n\t\t},\n\t\tasync execute(_toolCallId, input: DelegateInput): Promise<AgentToolResult<DelegateDetails>> {\n\t\t\tconst result =\n\t\t\t\t\"task\" in input\n\t\t\t\t\t? await runDelegation(runtime, input.agentType, input.task, { background: input.background })\n\t\t\t\t\t: await retrieveDelegationResult(runtime, input.handle, input.agentType);\n\t\t\treturn {\n\t\t\t\tcontent: [{ type: \"text\", text: result.output }],\n\t\t\t\tdetails: {\n\t\t\t\t\tagentType: result.agentType,\n\t\t\t\t\ttask: result.task,\n\t\t\t\t\toutput: result.output,\n\t\t\t\t\thandle: result.handleId,\n\t\t\t\t},\n\t\t\t};\n\t\t},\n\t\trenderCall(input, theme, context) {\n\t\t\tconst text = (context.lastComponent as Text | undefined) ?? new Text(\"\", 0, 0);\n\t\t\ttext.setText(formatDelegateCall(input, theme));\n\t\t\treturn text;\n\t\t},\n\t\trenderResult(result, options, theme, context) {\n\t\t\tconst text = (context.lastComponent as Text | undefined) ?? new Text(\"\", 0, 0);\n\t\t\ttext.setText(formatDelegateResult(result.details, options.expanded, theme));\n\t\t\treturn text;\n\t\t},\n\t};\n}\n\nexport function createDelegateTool(runtime: DelegationRuntimeOptions) {\n\treturn wrapToolDefinition(createDelegateToolDefinition(runtime));\n}\n"]}
1
+ {"version":3,"file":"delegate.d.ts","sourceRoot":"","sources":["../../../src/core/tools/delegate.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,KAAK,MAAM,EAAE,IAAI,EAAE,MAAM,SAAS,CAAC;AAE5C,OAAO,KAAK,EAAE,wBAAwB,EAAE,MAAM,0BAA0B,CAAC;AAEzE,OAAO,EAAE,KAAK,kBAAkB,EAAkC,MAAM,eAAe,CAAC;AAgBxF,QAAA,MAAM,cAAc;;;;;;;IAUnB,CAAC;AAEF,MAAM,MAAM,aAAa,GAAG,MAAM,CAAC,OAAO,cAAc,CAAC,CAAC;AAE1D,MAAM,WAAW,eAAe;IAC/B,SAAS,EAAE,MAAM,CAAC;IAClB,IAAI,EAAE,MAAM,CAAC;IACb,MAAM,EAAE,MAAM,CAAC;IACf,MAAM,CAAC,EAAE,MAAM,CAAC;CAChB;AAgBD;;;;;;;;;;GAUG;AACH,wBAAgB,4BAA4B,CAC3C,OAAO,EAAE,wBAAwB,GAC/B,kBAAkB,CAAC,OAAO,cAAc,EAAE,eAAe,CAAC,CAiD5D;AAED,wBAAgB,kBAAkB,CAAC,OAAO,EAAE,wBAAwB;;;;;;;uBAEnE","sourcesContent":["import { Text } from \"@earendil-works/pi-tui\";\nimport type { AgentToolResult } from \"apex-code-agent-core\";\nimport { minimatch } from \"minimatch\";\nimport { type Static, Type } from \"typebox\";\nimport type { Theme } from \"../../modes/interactive/theme/theme.ts\";\nimport type { DelegationRuntimeOptions } from \"../delegation/runtime.ts\";\nimport { retrieveDelegationResult, runDelegation } from \"../delegation/runtime.ts\";\nimport { type ApexToolDefinition, type EvidenceRecord, toolUnion } from \"./contract.ts\";\nimport { wrapToolDefinition } from \"./tool-definition-wrapper.ts\";\n\nconst delegateSchemaProperties = {\n\tagentType: Type.String({\n\t\tdescription: \"The subagent type. Required both to launch a task and to retrieve a background result.\",\n\t}),\n\ttask: Type.String({ description: \"The task to delegate. Supply it to launch a delegation.\" }),\n\tbackground: Type.Optional(\n\t\tType.Boolean({ description: \"Return a handle immediately instead of waiting for the child.\" }),\n\t),\n\thandle: Type.String({\n\t\tdescription: \"A background delegation handle returned by an earlier call. Supply it to retrieve the result.\",\n\t}),\n};\n\nconst delegateSchema = toolUnion(\n\t[\n\t\tType.Object({\n\t\t\tagentType: Type.String(),\n\t\t\ttask: Type.String(),\n\t\t\tbackground: Type.Optional(Type.Boolean()),\n\t\t}),\n\t\tType.Object({ agentType: Type.String(), handle: Type.String() }),\n\t],\n\tdelegateSchemaProperties,\n);\n\nexport type DelegateInput = Static<typeof delegateSchema>;\n\nexport interface DelegateDetails {\n\tagentType: string;\n\ttask: string;\n\toutput: string;\n\thandle?: string;\n}\n\nfunction formatDelegateCall(input: DelegateInput, theme: Theme): string {\n\tif (\"handle\" in input) {\n\t\treturn `${theme.fg(\"toolTitle\", theme.bold(\"delegate\"))} ${theme.fg(\"accent\", input.agentType)} · retrieve`;\n\t}\n\tconst task = input.task.replace(/\\s+/g, \" \").trim();\n\treturn `${theme.fg(\"toolTitle\", theme.bold(\"delegate\"))} ${theme.fg(\"accent\", input.agentType)} · ${theme.fg(\"toolOutput\", task)}`;\n}\n\nfunction formatDelegateResult(details: DelegateDetails, expanded: boolean, theme: Theme): string {\n\tif (expanded) return theme.fg(\"toolOutput\", details.output);\n\tconst lineCount = details.output ? details.output.split(\"\\n\").length : 0;\n\treturn `${theme.fg(\"accent\", details.agentType)} · ${lineCount} ${lineCount === 1 ? \"line\" : \"lines\"}`;\n}\n\n/**\n * The delegation entry point (task 4.6's contract, task 5.2's execution). Runs a\n * real child through the injected `DelegationRuntimeOptions` -- capability ceiling,\n * derived permission store, and child-session construction all live behind that\n * injection (ADR 0008), matching the `todo_write`/`tool_schema` convention of\n * injecting collaborators rather than reaching for global state. Recursion\n * depth, artifact isolation, and real agent discovery are wired:\n * `../delegation/runtime.ts` bounds depth and roots per-child artifact\n * directories, and `../delegation/agents.ts` supplies production markdown\n * discovery through the injected resolver.\n */\nexport function createDelegateToolDefinition(\n\truntime: DelegationRuntimeOptions,\n): ApexToolDefinition<typeof delegateSchema, DelegateDetails> {\n\treturn {\n\t\tname: \"delegate\",\n\t\tlabel: \"delegate\",\n\t\tdescription: \"Delegate a task to a subagent.\",\n\t\tparameters: delegateSchema,\n\t\tcontract: {\n\t\t\tcapabilities: new Set([\"delegate\"]),\n\t\t\tpermission: {\n\t\t\t\tdefaultBehavior: \"ask\",\n\t\t\t\tmatches: (ruleContent, params) => minimatch(params.agentType, ruleContent),\n\t\t\t\tdescribe: (ruleContent) => `Delegate to agent types matching \"${ruleContent}\"`,\n\t\t\t\truleForCall: (params) => params.agentType,\n\t\t\t},\n\t\t\tcontext: { resultRecoverable: false, deferSchema: true },\n\t\t\tevidence: {\n\t\t\t\temits: new Set([\"workflow\"]),\n\t\t\t\tcapture: (params): EvidenceRecord[] =>\n\t\t\t\t\t\"task\" in params\n\t\t\t\t\t\t? [{ kind: \"workflow\", agentType: params.agentType, task: params.task }]\n\t\t\t\t\t\t: [{ kind: \"workflow\", agentType: params.agentType, handle: params.handle }],\n\t\t\t},\n\t\t},\n\t\tasync execute(_toolCallId, input: DelegateInput): Promise<AgentToolResult<DelegateDetails>> {\n\t\t\tconst result =\n\t\t\t\t\"task\" in input\n\t\t\t\t\t? await runDelegation(runtime, input.agentType, input.task, { background: input.background })\n\t\t\t\t\t: await retrieveDelegationResult(runtime, input.handle, input.agentType);\n\t\t\treturn {\n\t\t\t\tcontent: [{ type: \"text\", text: result.output }],\n\t\t\t\tdetails: {\n\t\t\t\t\tagentType: result.agentType,\n\t\t\t\t\ttask: result.task,\n\t\t\t\t\toutput: result.output,\n\t\t\t\t\thandle: result.handleId,\n\t\t\t\t},\n\t\t\t};\n\t\t},\n\t\trenderCall(input, theme, context) {\n\t\t\tconst text = (context.lastComponent as Text | undefined) ?? new Text(\"\", 0, 0);\n\t\t\ttext.setText(formatDelegateCall(input, theme));\n\t\t\treturn text;\n\t\t},\n\t\trenderResult(result, options, theme, context) {\n\t\t\tconst text = (context.lastComponent as Text | undefined) ?? new Text(\"\", 0, 0);\n\t\t\ttext.setText(formatDelegateResult(result.details, options.expanded, theme));\n\t\t\treturn text;\n\t\t},\n\t};\n}\n\nexport function createDelegateTool(runtime: DelegationRuntimeOptions) {\n\treturn wrapToolDefinition(createDelegateToolDefinition(runtime));\n}\n"]}
@@ -2,18 +2,26 @@ import { Text } from "@earendil-works/pi-tui";
2
2
  import { minimatch } from "minimatch";
3
3
  import { Type } from "typebox";
4
4
  import { retrieveDelegationResult, runDelegation } from "../delegation/runtime.js";
5
+ import { toolUnion } from "./contract.js";
5
6
  import { wrapToolDefinition } from "./tool-definition-wrapper.js";
6
- const delegateSchema = Type.Union([
7
- Type.Object({
8
- agentType: Type.String({ description: "The type of subagent to delegate to." }),
9
- task: Type.String({ description: "The task to delegate." }),
10
- background: Type.Optional(Type.Boolean({ description: "Return a handle immediately instead of waiting for the child." })),
7
+ const delegateSchemaProperties = {
8
+ agentType: Type.String({
9
+ description: "The subagent type. Required both to launch a task and to retrieve a background result.",
10
+ }),
11
+ task: Type.String({ description: "The task to delegate. Supply it to launch a delegation." }),
12
+ background: Type.Optional(Type.Boolean({ description: "Return a handle immediately instead of waiting for the child." })),
13
+ handle: Type.String({
14
+ description: "A background delegation handle returned by an earlier call. Supply it to retrieve the result.",
11
15
  }),
16
+ };
17
+ const delegateSchema = toolUnion([
12
18
  Type.Object({
13
- agentType: Type.String({ description: "The agent type that produced the background result." }),
14
- handle: Type.String({ description: "A background delegation handle returned by an earlier call." }),
19
+ agentType: Type.String(),
20
+ task: Type.String(),
21
+ background: Type.Optional(Type.Boolean()),
15
22
  }),
16
- ]);
23
+ Type.Object({ agentType: Type.String(), handle: Type.String() }),
24
+ ], delegateSchemaProperties);
17
25
  function formatDelegateCall(input, theme) {
18
26
  if ("handle" in input) {
19
27
  return `${theme.fg("toolTitle", theme.bold("delegate"))} ${theme.fg("accent", input.agentType)} · retrieve`;
@@ -32,9 +40,11 @@ function formatDelegateResult(details, expanded, theme) {
32
40
  * real child through the injected `DelegationRuntimeOptions` -- capability ceiling,
33
41
  * derived permission store, and child-session construction all live behind that
34
42
  * injection (ADR 0008), matching the `todo_write`/`tool_schema` convention of
35
- * injecting collaborators rather than reaching for global state. Recursion depth
36
- * (task 5.3), artifact isolation (task 5.4), and real agent discovery (task 5.5,
37
- * replacing the resolver a test or caller injects here) are not yet wired.
43
+ * injecting collaborators rather than reaching for global state. Recursion
44
+ * depth, artifact isolation, and real agent discovery are wired:
45
+ * `../delegation/runtime.ts` bounds depth and roots per-child artifact
46
+ * directories, and `../delegation/agents.ts` supplies production markdown
47
+ * discovery through the injected resolver.
38
48
  */
39
49
  export function createDelegateToolDefinition(runtime) {
40
50
  return {
@@ -1 +1 @@
1
- {"version":3,"file":"delegate.js","sourceRoot":"","sources":["../../../src/core/tools/delegate.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,wBAAwB,CAAC;AAE9C,OAAO,EAAE,SAAS,EAAE,MAAM,WAAW,CAAC;AACtC,OAAO,EAAe,IAAI,EAAE,MAAM,SAAS,CAAC;AAG5C,OAAO,EAAE,wBAAwB,EAAE,aAAa,EAAE,MAAM,0BAA0B,CAAC;AAEnF,OAAO,EAAE,kBAAkB,EAAE,MAAM,8BAA8B,CAAC;AAElE,MAAM,cAAc,GAAG,IAAI,CAAC,KAAK,CAAC;IACjC,IAAI,CAAC,MAAM,CAAC;QACX,SAAS,EAAE,IAAI,CAAC,MAAM,CAAC,EAAE,WAAW,EAAE,sCAAsC,EAAE,CAAC;QAC/E,IAAI,EAAE,IAAI,CAAC,MAAM,CAAC,EAAE,WAAW,EAAE,uBAAuB,EAAE,CAAC;QAC3D,UAAU,EAAE,IAAI,CAAC,QAAQ,CACxB,IAAI,CAAC,OAAO,CAAC,EAAE,WAAW,EAAE,+DAA+D,EAAE,CAAC,CAC9F;KACD,CAAC;IACF,IAAI,CAAC,MAAM,CAAC;QACX,SAAS,EAAE,IA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;IACrE,OAAO,kBAAkB,CAAC,4BAA4B,CAAC,OAAO,CAAC,CAAC,CAAC;AAAA,CACjE","sourcesContent":["import { Text } from \"@earendil-works/pi-tui\";\nimport type { AgentToolResult } from \"apex-code-agent-core\";\nimport { minimatch } from \"minimatch\";\nimport { type Static, Type } from \"typebox\";\nimport type { Theme } from \"../../modes/interactive/theme/theme.ts\";\nimport type { DelegationRuntimeOptions } from \"../delegation/runtime.ts\";\nimport { retrieveDelegationResult, runDelegation } from \"../delegation/runtime.ts\";\nimport type { ApexToolDefinition, EvidenceRecord } from \"./contract.ts\";\nimport { wrapToolDefinition } from \"./tool-definition-wrapper.ts\";\n\nconst delegateSchema = Type.Union([\n\tType.Object({\n\t\tagentType: Type.String({ description: \"The type of subagent to delegate to.\" }),\n\t\ttask: Type.String({ description: \"The task to delegate.\" }),\n\t\tbackground: Type.Optional(\n\t\t\tType.Boolean({ description: \"Return a handle immediately instead of waiting for the child.\" }),\n\t\t),\n\t}),\n\tType.Object({\n\t\tagentType: Type.String({ description: \"The agent type that produced the background result.\" }),\n\t\thandle: Type.String({ description: \"A background delegation handle returned by an earlier call.\" }),\n\t}),\n]);\n\nexport type DelegateInput = Static<typeof delegateSchema>;\n\nexport interface DelegateDetails {\n\tagentType: string;\n\ttask: string;\n\toutput: string;\n\thandle?: string;\n}\n\nfunction formatDelegateCall(input: DelegateInput, theme: Theme): string {\n\tif (\"handle\" in input) {\n\t\treturn `${theme.fg(\"toolTitle\", theme.bold(\"delegate\"))} ${theme.fg(\"accent\", input.agentType)} · retrieve`;\n\t}\n\tconst task = input.task.replace(/\\s+/g, \" \").trim();\n\treturn `${theme.fg(\"toolTitle\", theme.bold(\"delegate\"))} ${theme.fg(\"accent\", input.agentType)} · ${theme.fg(\"toolOutput\", task)}`;\n}\n\nfunction formatDelegateResult(details: DelegateDetails, expanded: boolean, theme: Theme): string {\n\tif (expanded) return theme.fg(\"toolOutput\", details.output);\n\tconst lineCount = details.output ? details.output.split(\"\\n\").length : 0;\n\treturn `${theme.fg(\"accent\", details.agentType)} · ${lineCount} ${lineCount === 1 ? \"line\" : \"lines\"}`;\n}\n\n/**\n * The delegation entry point (task 4.6's contract, task 5.2's execution). Runs a\n * real child through the injected `DelegationRuntimeOptions` -- capability ceiling,\n * derived permission store, and child-session construction all live behind that\n * injection (ADR 0008), matching the `todo_write`/`tool_schema` convention of\n * injecting collaborators rather than reaching for global state. Recursion depth\n * (task 5.3), artifact isolation (task 5.4), and real agent discovery (task 5.5,\n * replacing the resolver a test or caller injects here) are not yet wired.\n */\nexport function createDelegateToolDefinition(\n\truntime: DelegationRuntimeOptions,\n): ApexToolDefinition<typeof delegateSchema, DelegateDetails> {\n\treturn {\n\t\tname: \"delegate\",\n\t\tlabel: \"delegate\",\n\t\tdescription: \"Delegate a task to a subagent.\",\n\t\tparameters: delegateSchema,\n\t\tcontract: {\n\t\t\tcapabilities: new Set([\"delegate\"]),\n\t\t\tpermission: {\n\t\t\t\tdefaultBehavior: \"ask\",\n\t\t\t\tmatches: (ruleContent, params) => minimatch(params.agentType, ruleContent),\n\t\t\t\tdescribe: (ruleContent) => `Delegate to agent types matching \"${ruleContent}\"`,\n\t\t\t\truleForCall: (params) => params.agentType,\n\t\t\t},\n\t\t\tcontext: { resultRecoverable: false, deferSchema: true },\n\t\t\tevidence: {\n\t\t\t\temits: new Set([\"workflow\"]),\n\t\t\t\tcapture: (params): EvidenceRecord[] =>\n\t\t\t\t\t\"task\" in params\n\t\t\t\t\t\t? [{ kind: \"workflow\", agentType: params.agentType, task: params.task }]\n\t\t\t\t\t\t: [{ kind: \"workflow\", agentType: params.agentType, handle: params.handle }],\n\t\t\t},\n\t\t},\n\t\tasync execute(_toolCallId, input: DelegateInput): Promise<AgentToolResult<DelegateDetails>> {\n\t\t\tconst result =\n\t\t\t\t\"task\" in input\n\t\t\t\t\t? await runDelegation(runtime, input.agentType, input.task, { background: input.background })\n\t\t\t\t\t: await retrieveDelegationResult(runtime, input.handle, input.agentType);\n\t\t\treturn {\n\t\t\t\tcontent: [{ type: \"text\", text: result.output }],\n\t\t\t\tdetails: {\n\t\t\t\t\tagentType: result.agentType,\n\t\t\t\t\ttask: result.task,\n\t\t\t\t\toutput: result.output,\n\t\t\t\t\thandle: result.handleId,\n\t\t\t\t},\n\t\t\t};\n\t\t},\n\t\trenderCall(input, theme, context) {\n\t\t\tconst text = (context.lastComponent as Text | undefined) ?? new Text(\"\", 0, 0);\n\t\t\ttext.setText(formatDelegateCall(input, theme));\n\t\t\treturn text;\n\t\t},\n\t\trenderResult(result, options, theme, context) {\n\t\t\tconst text = (context.lastComponent as Text | undefined) ?? new Text(\"\", 0, 0);\n\t\t\ttext.setText(formatDelegateResult(result.details, options.expanded, theme));\n\t\t\treturn text;\n\t\t},\n\t};\n}\n\nexport function createDelegateTool(runtime: DelegationRuntimeOptions) {\n\treturn wrapToolDefinition(createDelegateToolDefinition(runtime));\n}\n"]}
1
+ {"version":3,"file":"delegate.js","sourceRoot":"","sources":["../../../src/core/tools/delegate.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,wBAAwB,CAAC;AAE9C,OAAO,EAAE,SAAS,EAAE,MAAM,WAAW,CAAC;AACtC,OAAO,EAAe,IAAI,EAAE,MAAM,SAAS,CAAC;AAG5C,OAAO,EAAE,wBAAwB,EAAE,aAAa,EAAE,MAAM,0BAA0B,CAAC;AACnF,OAAO,EAAgD,SAAS,EAAE,MAAM,eAAe,CAAC;AACxF,OAAO,EAAE,kBAAkB,EAAE,MAAM,8BAA8B,CAAC;AAElE,MAAM,wBAAwB,GAAG;IAChC,SAAS,EAAE,IAAI,CAAC,MAAM,CAAC;QACtB,WAAW,EAAE,wFAAwF;KACrG,CAAC;IACF,IAAI,EAAE,IAAI,CAAC,MAAM,CAAC,EAAE,WAAW,EAAE,yDAAyD,EAAE,CAAC;IAC7F,UAAU,EAAE,IAAI,CAAC,QAAQ,CACxB,IAAI,CAAC,OAAO,CAAC,EAAE,WAAW,EAAE,+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O,EAAE;YAC7C,MAAM,IAAI,GAAI,OAAO,CAAC,aAAkC,IAAI,IAAI,IAAI,CAAC,EAAE,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC;YAC/E,IAAI,CAAC,OAAO,CAAC,oBAAoB,CAAC,MAAM,CAAC,OAAO,EAAE,OAAO,CAAC,QAAQ,EAAE,KAAK,CAAC,CAAC,CAAC;YAC5E,OAAO,IAAI,CAAC;QAAA,CACZ;KACD,CAAC;AAAA,CACF;AAED,MAAM,UAAU,kBAAkB,CAAC,OAAiC,EAAE;IACrE,OAAO,kBAAkB,CAAC,4BAA4B,CAAC,OAAO,CAAC,CAAC,CAAC;AAAA,CACjE","sourcesContent":["import { Text } from \"@earendil-works/pi-tui\";\nimport type { AgentToolResult } from \"apex-code-agent-core\";\nimport { minimatch } from \"minimatch\";\nimport { type Static, Type } from \"typebox\";\nimport type { Theme } from \"../../modes/interactive/theme/theme.ts\";\nimport type { DelegationRuntimeOptions } from \"../delegation/runtime.ts\";\nimport { retrieveDelegationResult, runDelegation } from \"../delegation/runtime.ts\";\nimport { type ApexToolDefinition, type EvidenceRecord, toolUnion } from \"./contract.ts\";\nimport { wrapToolDefinition } from \"./tool-definition-wrapper.ts\";\n\nconst delegateSchemaProperties = {\n\tagentType: Type.String({\n\t\tdescription: \"The subagent type. Required both to launch a task and to retrieve a background result.\",\n\t}),\n\ttask: Type.String({ description: \"The task to delegate. Supply it to launch a delegation.\" }),\n\tbackground: Type.Optional(\n\t\tType.Boolean({ description: \"Return a handle immediately instead of waiting for the child.\" }),\n\t),\n\thandle: Type.String({\n\t\tdescription: \"A background delegation handle returned by an earlier call. Supply it to retrieve the result.\",\n\t}),\n};\n\nconst delegateSchema = toolUnion(\n\t[\n\t\tType.Object({\n\t\t\tagentType: Type.String(),\n\t\t\ttask: Type.String(),\n\t\t\tbackground: Type.Optional(Type.Boolean()),\n\t\t}),\n\t\tType.Object({ agentType: Type.String(), handle: Type.String() }),\n\t],\n\tdelegateSchemaProperties,\n);\n\nexport type DelegateInput = Static<typeof delegateSchema>;\n\nexport interface DelegateDetails {\n\tagentType: string;\n\ttask: string;\n\toutput: string;\n\thandle?: string;\n}\n\nfunction formatDelegateCall(input: DelegateInput, theme: Theme): string {\n\tif (\"handle\" in input) {\n\t\treturn `${theme.fg(\"toolTitle\", theme.bold(\"delegate\"))} ${theme.fg(\"accent\", input.agentType)} · retrieve`;\n\t}\n\tconst task = input.task.replace(/\\s+/g, \" \").trim();\n\treturn `${theme.fg(\"toolTitle\", theme.bold(\"delegate\"))} ${theme.fg(\"accent\", input.agentType)} · ${theme.fg(\"toolOutput\", task)}`;\n}\n\nfunction formatDelegateResult(details: DelegateDetails, expanded: boolean, theme: Theme): string {\n\tif (expanded) return theme.fg(\"toolOutput\", details.output);\n\tconst lineCount = details.output ? details.output.split(\"\\n\").length : 0;\n\treturn `${theme.fg(\"accent\", details.agentType)} · ${lineCount} ${lineCount === 1 ? \"line\" : \"lines\"}`;\n}\n\n/**\n * The delegation entry point (task 4.6's contract, task 5.2's execution). Runs a\n * real child through the injected `DelegationRuntimeOptions` -- capability ceiling,\n * derived permission store, and child-session construction all live behind that\n * injection (ADR 0008), matching the `todo_write`/`tool_schema` convention of\n * injecting collaborators rather than reaching for global state. Recursion\n * depth, artifact isolation, and real agent discovery are wired:\n * `../delegation/runtime.ts` bounds depth and roots per-child artifact\n * directories, and `../delegation/agents.ts` supplies production markdown\n * discovery through the injected resolver.\n */\nexport function createDelegateToolDefinition(\n\truntime: DelegationRuntimeOptions,\n): ApexToolDefinition<typeof delegateSchema, DelegateDetails> {\n\treturn {\n\t\tname: \"delegate\",\n\t\tlabel: \"delegate\",\n\t\tdescription: \"Delegate a task to a subagent.\",\n\t\tparameters: delegateSchema,\n\t\tcontract: {\n\t\t\tcapabilities: new Set([\"delegate\"]),\n\t\t\tpermission: {\n\t\t\t\tdefaultBehavior: \"ask\",\n\t\t\t\tmatches: (ruleContent, params) => minimatch(params.agentType, ruleContent),\n\t\t\t\tdescribe: (ruleContent) => `Delegate to agent types matching \"${ruleContent}\"`,\n\t\t\t\truleForCall: (params) => params.agentType,\n\t\t\t},\n\t\t\tcontext: { resultRecoverable: false, deferSchema: true },\n\t\t\tevidence: {\n\t\t\t\temits: new Set([\"workflow\"]),\n\t\t\t\tcapture: (params): EvidenceRecord[] =>\n\t\t\t\t\t\"task\" in params\n\t\t\t\t\t\t? [{ kind: \"workflow\", agentType: params.agentType, task: params.task }]\n\t\t\t\t\t\t: [{ kind: \"workflow\", agentType: params.agentType, handle: params.handle }],\n\t\t\t},\n\t\t},\n\t\tasync execute(_toolCallId, input: DelegateInput): Promise<AgentToolResult<DelegateDetails>> {\n\t\t\tconst result =\n\t\t\t\t\"task\" in input\n\t\t\t\t\t? await runDelegation(runtime, input.agentType, input.task, { background: input.background })\n\t\t\t\t\t: await retrieveDelegationResult(runtime, input.handle, input.agentType);\n\t\t\treturn {\n\t\t\t\tcontent: [{ type: \"text\", text: result.output }],\n\t\t\t\tdetails: {\n\t\t\t\t\tagentType: result.agentType,\n\t\t\t\t\ttask: result.task,\n\t\t\t\t\toutput: result.output,\n\t\t\t\t\thandle: result.handleId,\n\t\t\t\t},\n\t\t\t};\n\t\t},\n\t\trenderCall(input, theme, context) {\n\t\t\tconst text = (context.lastComponent as Text | undefined) ?? new Text(\"\", 0, 0);\n\t\t\ttext.setText(formatDelegateCall(input, theme));\n\t\t\treturn text;\n\t\t},\n\t\trenderResult(result, options, theme, context) {\n\t\t\tconst text = (context.lastComponent as Text | undefined) ?? new Text(\"\", 0, 0);\n\t\t\ttext.setText(formatDelegateResult(result.details, options.expanded, theme));\n\t\t\treturn text;\n\t\t},\n\t};\n}\n\nexport function createDelegateTool(runtime: DelegationRuntimeOptions) {\n\treturn wrapToolDefinition(createDelegateToolDefinition(runtime));\n}\n"]}
@@ -60,11 +60,46 @@ export interface AppliedEditsResult {
60
60
  * Unicode quotes/dashes normalized to ASCII).
61
61
  */
62
62
  export declare function fuzzyFindText(content: string, oldText: string): FuzzyMatchResult;
63
- /** Strip UTF-8 BOM if present, return both the BOM (if any) and the text without it */
64
- export declare function stripBom(content: string): {
65
- bom: string;
66
- text: string;
67
- };
63
+ /**
64
+ * Explicit budgets for the advisory edit-failure diagnostics below. Diagnostics
65
+ * are a best-effort hint, never an apply path, so every dimension of the scan
66
+ * is bounded and the ordinary failure is returned untouched when a bound is
67
+ * exceeded (spec 2026-09-01-tool-reliability-and-execution-budgets.md § 2).
68
+ */
69
+ export declare const EDIT_DIAGNOSTIC_MAX_FILE_BYTES = 1048576;
70
+ export declare const EDIT_DIAGNOSTIC_MAX_TARGET_BYTES = 65536;
71
+ export declare const EDIT_DIAGNOSTIC_MAX_CANDIDATES = 3;
72
+ export declare const EDIT_DIAGNOSTIC_MAX_SCAN_WINDOWS = 20000;
73
+ export declare const EDIT_DIAGNOSTIC_MAX_OCCURRENCES = 5;
74
+ export declare const EDIT_DIAGNOSTIC_SNIPPET_LINE_CHARS = 160;
75
+ export interface EditCandidateLocation {
76
+ /** 1-based, inclusive. */
77
+ startLine: number;
78
+ /** 1-based, inclusive. */
79
+ endLine: number;
80
+ /** Bigram Dice similarity against the failed target, rounded to two decimals. */
81
+ similarity: number;
82
+ /** Bounded snippet of the candidate source lines, each line-numbered. */
83
+ snippet: string;
84
+ }
85
+ /**
86
+ * Advisory diagnostics attached to a failed edit match. These describe where a
87
+ * target almost matched or where duplicates live; they are never a replacement
88
+ * location and must never be applied.
89
+ */
90
+ export interface EditFailureDiagnostics {
91
+ kind: "missing-match" | "duplicate-match";
92
+ candidates: EditCandidateLocation[];
93
+ /** 1-based source lines of up to EDIT_DIAGNOSTIC_MAX_OCCURRENCES duplicates. */
94
+ occurrenceLines: number[];
95
+ omittedOccurrences: number;
96
+ /** True when the scan stopped at a work or time bound before finishing. */
97
+ scanTruncated: boolean;
98
+ /** Set when scanning was unsafe or oversized; no candidates are reported. */
99
+ unavailableReason?: string;
100
+ }
101
+ /** Render advisory diagnostics as an error-message appendix. Empty when there is nothing to say. */
102
+ export declare function formatEditFailureDiagnostics(diagnostics: EditFailureDiagnostics | undefined): string;
68
103
  /**
69
104
  * Apply one or more exact-text replacements to LF-normalized content.
70
105
  *
@@ -97,6 +132,14 @@ export interface EditDiffError {
97
132
  * Used for preview rendering in the TUI before the tool executes.
98
133
  */
99
134
  export declare function computeEditsDiff(path: string, edits: Edit[], cwd: string): Promise<EditDiffResult | EditDiffError>;
135
+ /**
136
+ * The half of `computeEditsDiff` that does not choose which bytes to read.
137
+ *
138
+ * The permission preview must describe the operation the gate authorized rather
139
+ * than whatever the pathname resolves to a second time, so it supplies content
140
+ * read through the prepared operation and calls this (ADR 0029).
141
+ */
142
+ export declare function computeEditsDiffFromContent(path: string, rawContent: string, edits: Edit[]): EditDiffResult | EditDiffError;
100
143
  /**
101
144
  * Compute the diff for a single edit operation without applying it.
102
145
  * Kept as a convenience wrapper for single-edit callers.
@@ -1 +1 @@
1
- {"version":3,"file":"edit-diff.d.ts","sourceRoot":"","sources":["../../../src/core/tools/edit-diff.ts"],"names":[],"mappings":"AAAA;;GAEG;AAOH,wBAAgB,gBAAgB,CAAC,OAAO,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,CAM/D;AAED,wBAAgB,aAAa,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAElD;AAED,wBAAgB,kBAAkB,CAAC,IAAI,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,IAAI,GAAG,MAAM,CAE9E;AAED;;;;;;GAMG;AACH,wBAAgB,sBAAsB,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAqB3D;AAWD,UAAU,WAAW;IACpB,SAAS,EAAE,MAAM,CAAC;IAClB,UAAU,EAAE,MAAM,CAAC;IACnB,WAAW,EAAE,MAAM,CAAC;IACpB,OAAO,EAAE,MAAM,CAAC;CAChB;AAED,KAAK,eAAe,GAAG,IAAI,CAAC,WAAW,EAAE,YAAY,GAAG,aAAa,GAAG,SAAS,CAAC,CAAC;AAiDnF;;;;;;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AC;IAAC,gBAAgB,EAAE,MAAM,GAAG,SAAS,CAAA;CAAE,CAuHxD;AAED,MAAM,WAAW,cAAc;IAC9B,IAAI,EAAE,MAAM,CAAC;IACb,gBAAgB,EAAE,MAAM,GAAG,SAAS,CAAC;CACrC;AAED,MAAM,WAAW,aAAa;IAC7B,KAAK,EAAE,MAAM,CAAC;CACd;AAED;;;GAGG;AACH,wBAAsB,gBAAgB,CACrC,IAAI,EAAE,MAAM,EACZ,KAAK,EAAE,IAAI,EAAE,EACb,GAAG,EAAE,MAAM,GACT,OAAO,CAAC,cAAc,GAAG,aAAa,CAAC,CAyBzC;AAED;;;GAGG;AACH,wBAAsB,eAAe,CACpC,IAAI,EAAE,MAAM,EACZ,OAAO,EAAE,MAAM,EACf,OAAO,EAAE,MAAM,EACf,GAAG,EAAE,MAAM,GACT,OAAO,CAAC,cAAc,GAAG,aAAa,CAAC,CAEzC","sourcesContent":["/**\n * Shared diff computation utilities for the edit and similar tools.\n */\n\nimport * as Diff from \"diff\";\nimport { constants } from \"fs\";\nimport { access, readFile } from \"fs/promises\";\nimport { resolveToCwd } from \"./path-utils.ts\";\n\nexport function detectLineEnding(content: string): \"\\r\\n\" | \"\\n\" {\n\tconst crlfIdx = content.indexOf(\"\\r\\n\");\n\tconst lfIdx = content.indexOf(\"\\n\");\n\tif (lfIdx === -1) return \"\\n\";\n\tif (crlfIdx === -1) return \"\\n\";\n\treturn crlfIdx < lfIdx ? \"\\r\\n\" : \"\\n\";\n}\n\nexport function normalizeToLF(text: string): string {\n\treturn text.replace(/\\r\\n/g, \"\\n\").replace(/\\r/g, \"\\n\");\n}\n\nexport function restoreLineEndings(text: string, ending: \"\\r\\n\" | \"\\n\"): string {\n\treturn ending === \"\\r\\n\" ? text.replace(/\\n/g, \"\\r\\n\") : text;\n}\n\n/**\n * Normalize text for fuzzy matching. Applies progressive transformations:\n * - Strip trailing whitespace from each line\n * - Normalize smart quotes to ASCII equivalents\n * - Normalize Unicode dashes/hyphens to ASCII hyphen\n * - Normalize special Unicode spaces to regular space\n */\nexport function normalizeForFuzzyMatch(text: string): string {\n\treturn (\n\t\ttext\n\t\t\t.normalize(\"NFKC\")\n\t\t\t// Strip trailing whitespace per line\n\t\t\t.split(\"\\n\")\n\t\t\t.map((line) => line.trimEnd())\n\t\t\t.join(\"\\n\")\n\t\t\t// Smart single quotes → '\n\t\t\t.replace(/[\\u2018\\u2019\\u201A\\u201B]/g, \"'\")\n\t\t\t// Smart double quotes → \"\n\t\t\t.replace(/[\\u201C\\u201D\\u201E\\u201F]/g, '\"')\n\t\t\t// Various dashes/hyphens → -\n\t\t\t// U+2010 hyphen, U+2011 non-breaking hyphen, U+2012 figure dash,\n\t\t\t// U+2013 en-dash, U+2014 em-dash, U+2015 horizontal bar, U+2212 minus\n\t\t\t.replace(/[\\u2010\\u2011\\u2012\\u2013\\u2014\\u2015\\u2212]/g, \"-\")\n\t\t\t// Special spaces → regular space\n\t\t\t// U+00A0 NBSP, U+2002-U+200A various spaces, U+202F narrow NBSP,\n\t\t\t// U+205F medium math space, U+3000 ideographic space\n\t\t\t.replace(/[\\u00A0\\u2002-\\u200A\\u202F\\u205F\\u3000]/g, \" \")\n\t);\n}\n\nfunction splitLinesWithEndings(content: string): string[] {\n\treturn content.match(/[^\\n]*\\n|[^\\n]+/g) ?? [];\n}\n\ninterface LineSpan {\n\tstart: number;\n\tend: number;\n}\n\ninterface MatchedEdit {\n\teditIndex: number;\n\tmatchIndex: number;\n\tmatchLength: number;\n\tnewText: string;\n}\n\ntype TextReplacement = Pick<MatchedEdit, \"matchIndex\" | \"matchLength\" | \"newText\">;\n\nfunction getLineSpans(content: string): LineSpan[] {\n\tlet offset = 0;\n\treturn splitLinesWithEndings(content).map((line) => {\n\t\tconst span = { start: offset, end: offset + line.length };\n\t\toffset = span.end;\n\t\treturn span;\n\t});\n}\n\nfunction getReplacementLineRange(lines: LineSpan[], replacement: TextReplacement) {\n\tconst replacementStart = replacement.matchIndex;\n\tconst replacementEnd = replacement.matchIndex + replacement.matchLength;\n\n\tlet startLine = -1;\n\tfor (let i = 0; i < lines.length; i++) {\n\t\tconst line = lines[i];\n\t\tif (replacementStart >= line.start && replacementStart < line.end) {\n\t\t\tstartLine = i;\n\t\t\tbreak;\n\t\t}\n\t}\n\tif (startLine === -1) {\n\t\tthrow new Error(\"Replacement range is outside the base content.\");\n\t}\n\n\tlet endLine = startLine;\n\twhile (endLine < lines.length && lines[endLine].end < replacementEnd) {\n\t\tendLine++;\n\t}\n\tif (endLine >= lines.length) {\n\t\tthrow new Error(\"Replacement range is outside the base content.\");\n\t}\n\n\treturn { startLine, endLine: endLine + 1 };\n}\n\nfunction applyReplacements(content: string, replacements: TextReplacement[], offset = 0): string {\n\tlet result = content;\n\tfor (let i = replacements.length - 1; i >= 0; i--) {\n\t\tconst replacement = replacements[i];\n\t\tconst matchIndex = replacement.matchIndex - offset;\n\t\tresult =\n\t\t\tresult.substring(0, matchIndex) + replacement.newText + result.substring(matchIndex + replacement.matchLength);\n\t}\n\treturn result;\n}\n\n/**\n * Apply replacements matched against `baseContent` to `originalContent` while\n * preserving unchanged line blocks from the original.\n *\n * This is useful when `baseContent` is a normalized view of the original. Each\n * replacement is widened to the lines it actually touches, those touched lines\n * are rewritten from the normalized base, and all other lines are copied back\n * from `originalContent`. The actual replacement ranges drive preservation so\n * duplicate normalized lines cannot be aligned to the wrong occurrence.\n */\nexport function applyReplacementsPreservingUnchangedLines(\n\toriginalContent: string,\n\tbaseContent: string,\n\treplacements: TextReplacement[],\n): string {\n\tconst originalLines = splitLinesWithEndings(originalContent);\n\tconst baseLines = getLineSpans(baseContent);\n\tif (originalLines.length !== baseLines.length) {\n\t\tthrow new Error(\"Cannot preserve unchanged lines because the base content has a different line count.\");\n\t}\n\n\tconst groups: Array<{ startLine: number; endLine: number; replacements: TextReplacement[] }> = [];\n\tconst sortedReplacements = [...replacements].sort((a, b) => a.matchIndex - b.matchIndex);\n\tfor (const replacement of sortedReplacements) {\n\t\tconst range = getReplacementLineRange(baseLines, replacement);\n\t\tconst current = groups[groups.length - 1];\n\t\tif (current && range.startLine < current.endLine) {\n\t\t\tcurrent.endLine = Math.max(current.endLine, range.endLine);\n\t\t\tcurrent.replacements.push(replacement);\n\t\t\tcontinue;\n\t\t}\n\t\tgroups.push({ ...range, replacements: [replacement] });\n\t}\n\n\tlet originalLineIndex = 0;\n\tlet result = \"\";\n\tfor (const group of groups) {\n\t\tresult += originalLines.slice(originalLineIndex, group.startLine).join(\"\");\n\n\t\tconst groupStartOffset = baseLines[group.startLine].start;\n\t\tconst groupEndOffset = baseLines[group.endLine - 1].end;\n\t\tresult += applyReplacements(\n\t\t\tbaseContent.slice(groupStartOffset, groupEndOffset),\n\t\t\tgroup.replacements,\n\t\t\tgroupStartOffset,\n\t\t);\n\t\toriginalLineIndex = group.endLine;\n\t}\n\tresult += originalLines.slice(originalLineIndex).join(\"\");\n\n\treturn result;\n}\n\nexport interface FuzzyMatchResult {\n\t/** Whether a match was found */\n\tfound: boolean;\n\t/** The index where the match starts (in the content that should be used for replacement) */\n\tindex: number;\n\t/** Length of the matched text */\n\tmatchLength: number;\n\t/** Whether fuzzy matching was used (false = exact match) */\n\tusedFuzzyMatch: boolean;\n\t/**\n\t * The content to use for replacement operations.\n\t * When exact match: original content. When fuzzy match: normalized content.\n\t */\n\tcontentForReplacement: string;\n}\n\nexport interface Edit {\n\toldText: string;\n\tnewText: string;\n}\n\nexport interface AppliedEditsResult {\n\tbaseContent: string;\n\tnewContent: string;\n}\n\n/**\n * Find oldText in content, trying exact match first, then fuzzy match.\n * When fuzzy matching is used, the returned contentForReplacement is the\n * fuzzy-normalized version of the content (trailing whitespace stripped,\n * Unicode quotes/dashes normalized to ASCII).\n */\nexport function fuzzyFindText(content: string, oldText: string): FuzzyMatchResult {\n\t// Try exact match first\n\tconst exactIndex = content.indexOf(oldText);\n\tif (exactIndex !== -1) {\n\t\treturn {\n\t\t\tfound: true,\n\t\t\tindex: exactIndex,\n\t\t\tmatchLength: oldText.length,\n\t\t\tusedFuzzyMatch: false,\n\t\t\tcontentForReplacement: content,\n\t\t};\n\t}\n\n\t// Try fuzzy match - work entirely in normalized space\n\tconst fuzzyContent = normalizeForFuzzyMatch(content);\n\tconst fuzzyOldText = normalizeForFuzzyMatch(oldText);\n\tconst fuzzyIndex = fuzzyContent.indexOf(fuzzyOldText);\n\n\tif (fuzzyIndex === -1) {\n\t\treturn {\n\t\t\tfound: false,\n\t\t\tindex: -1,\n\t\t\tmatchLength: 0,\n\t\t\tusedFuzzyMatch: false,\n\t\t\tcontentForReplacement: content,\n\t\t};\n\t}\n\n\t// When fuzzy matching, return offsets in normalized space. Callers can use\n\t// the normalized content to compute replacements, then decide how much of\n\t// that normalized output should be written back.\n\treturn {\n\t\tfound: true,\n\t\tindex: fuzzyIndex,\n\t\tmatchLength: fuzzyOldText.length,\n\t\tusedFuzzyMatch: true,\n\t\tcontentForReplacement: fuzzyContent,\n\t};\n}\n\n/** Strip UTF-8 BOM if present, return both the BOM (if any) and the text without it */\nexport function stripBom(content: string): { bom: string; text: string } {\n\treturn content.startsWith(\"\\uFEFF\") ? { bom: \"\\uFEFF\", text: content.slice(1) } : { bom: \"\", text: content };\n}\n\nfunction countOccurrences(content: string, oldText: string): number {\n\tconst fuzzyContent = normalizeForFuzzyMatch(content);\n\tconst fuzzyOldText = normalizeForFuzzyMatch(oldText);\n\treturn fuzzyContent.split(fuzzyOldText).length - 1;\n}\n\nfunction getNotFoundError(path: string, editIndex: number, totalEdits: number): Error {\n\tif (totalEdits === 1) {\n\t\treturn new Error(\n\t\t\t`Could not find the exact text in ${path}. The old text must match exactly including all whitespace and newlines.`,\n\t\t);\n\t}\n\treturn new Error(\n\t\t`Could not find edits[${editIndex}] in ${path}. The oldText must match exactly including all whitespace and newlines.`,\n\t);\n}\n\nfunction getDuplicateError(path: string, editIndex: number, totalEdits: number, occurrences: number): Error {\n\tif (totalEdits === 1) {\n\t\treturn new Error(\n\t\t\t`Found ${occurrences} occurrences of the text in ${path}. The text must be unique. Please provide more context to make it unique.`,\n\t\t);\n\t}\n\treturn new Error(\n\t\t`Found ${occurrences} occurrences of edits[${editIndex}] in ${path}. Each oldText must be unique. Please provide more context to make it unique.`,\n\t);\n}\n\nfunction getEmptyOldTextError(path: string, editIndex: number, totalEdits: number): Error {\n\tif (totalEdits === 1) {\n\t\treturn new Error(`oldText must not be empty in ${path}.`);\n\t}\n\treturn new Error(`edits[${editIndex}].oldText must not be empty in ${path}.`);\n}\n\nfunction getNoChangeError(path: string, totalEdits: number): Error {\n\tif (totalEdits === 1) {\n\t\treturn new Error(\n\t\t\t`No changes made to ${path}. The replacement produced identical content. This might indicate an issue with special characters or the text not existing as expected.`,\n\t\t);\n\t}\n\treturn new Error(`No changes made to ${path}. The replacements produced identical content.`);\n}\n\n/**\n * Apply one or more exact-text replacements to LF-normalized content.\n *\n * All edits are matched against the same original content. Replacements are\n * then applied in reverse order so offsets remain stable. If any edit needs\n * fuzzy matching, the operation runs in fuzzy-normalized content space and then\n * overlays those line-level changes onto the original content so unchanged line\n * blocks keep their original bytes.\n */\nexport function applyEditsToNormalizedContent(\n\tnormalizedContent: string,\n\tedits: Edit[],\n\tpath: string,\n): AppliedEditsResult {\n\tconst normalizedEdits = edits.map((edit) => ({\n\t\toldText: normalizeToLF(edit.oldText),\n\t\tnewText: normalizeToLF(edit.newText),\n\t}));\n\n\tfor (let i = 0; i < normalizedEdits.length; i++) {\n\t\tif (normalizedEdits[i].oldText.length === 0) {\n\t\t\tthrow getEmptyOldTextError(path, i, normalizedEdits.length);\n\t\t}\n\t}\n\n\tconst initialMatches = normalizedEdits.map((edit) => fuzzyFindText(normalizedContent, edit.oldText));\n\tconst usedFuzzyMatch = initialMatches.some((match) => match.usedFuzzyMatch);\n\tconst replacementBaseContent = usedFuzzyMatch ? normalizeForFuzzyMatch(normalizedContent) : normalizedContent;\n\n\tconst matchedEdits: MatchedEdit[] = [];\n\tfor (let i = 0; i < normalizedEdits.length; i++) {\n\t\tconst edit = normalizedEdits[i];\n\t\tconst matchResult = fuzzyFindText(replacementBaseContent, edit.oldText);\n\t\tif (!matchResult.found) {\n\t\t\tthrow getNotFoundError(path, i, normalizedEdits.length);\n\t\t}\n\n\t\tconst occurrences = countOccurrences(replacementBaseContent, edit.oldText);\n\t\tif (occurrences > 1) {\n\t\t\tthrow getDuplicateError(path, i, normalizedEdits.length, occurrences);\n\t\t}\n\n\t\tmatchedEdits.push({\n\t\t\teditIndex: i,\n\t\t\tmatchIndex: matchResult.index,\n\t\t\tmatchLength: matchResult.matchLength,\n\t\t\tnewText: edit.newText,\n\t\t});\n\t}\n\n\tmatchedEdits.sort((a, b) => a.matchIndex - b.matchIndex);\n\tfor (let i = 1; i < matchedEdits.length; i++) {\n\t\tconst previous = matchedEdits[i - 1];\n\t\tconst current = matchedEdits[i];\n\t\tif (previous.matchIndex + previous.matchLength > current.matchIndex) {\n\t\t\tthrow new Error(\n\t\t\t\t`edits[${previous.editIndex}] and edits[${current.editIndex}] overlap in ${path}. Merge them into one edit or target disjoint regions.`,\n\t\t\t);\n\t\t}\n\t}\n\n\tconst baseContent = normalizedContent;\n\tconst newContent = usedFuzzyMatch\n\t\t? applyReplacementsPreservingUnchangedLines(normalizedContent, replacementBaseContent, matchedEdits)\n\t\t: applyReplacements(replacementBaseContent, matchedEdits);\n\n\tif (baseContent === newContent) {\n\t\tthrow getNoChangeError(path, normalizedEdits.length);\n\t}\n\n\treturn { baseContent, newContent };\n}\n\n/** Generate a standard unified patch. */\nexport function generateUnifiedPatch(path: string, oldContent: string, newContent: string, contextLines = 4): string {\n\treturn Diff.createTwoFilesPatch(path, path, oldContent, newContent, undefined, undefined, {\n\t\tcontext: contextLines,\n\t\theaderOptions: Diff.FILE_HEADERS_ONLY,\n\t});\n}\n\n/**\n * Generate a display-oriented diff string with line numbers and context.\n * Returns both the diff string and the first changed line number (in the new file).\n */\nexport function generateDiffString(\n\toldContent: string,\n\tnewContent: string,\n\tcontextLines = 4,\n): { diff: string; firstChangedLine: number | undefined } {\n\tconst parts = Diff.diffLines(oldContent, newContent);\n\tconst output: string[] = [];\n\n\tconst oldLines = oldContent.split(\"\\n\");\n\tconst newLines = newContent.split(\"\\n\");\n\tconst maxLineNum = Math.max(oldLines.length, newLines.length);\n\tconst lineNumWidth = String(maxLineNum).length;\n\n\tlet oldLineNum = 1;\n\tlet newLineNum = 1;\n\tlet lastWasChange = false;\n\tlet firstChangedLine: number | undefined;\n\n\tfor (let i = 0; i < parts.length; i++) {\n\t\tconst part = parts[i];\n\t\tconst raw = part.value.split(\"\\n\");\n\t\tif (raw[raw.length - 1] === \"\") {\n\t\t\traw.pop();\n\t\t}\n\n\t\tif (part.added || part.removed) {\n\t\t\t// Capture the first changed line (in the new file)\n\t\t\tif (firstChangedLine === undefined) {\n\t\t\t\tfirstChangedLine = newLineNum;\n\t\t\t}\n\n\t\t\t// Show the change\n\t\t\tfor (const line of raw) {\n\t\t\t\tif (part.added) {\n\t\t\t\t\tconst lineNum = String(newLineNum).padStart(lineNumWidth, \" \");\n\t\t\t\t\toutput.push(`+${lineNum} ${line}`);\n\t\t\t\t\tnewLineNum++;\n\t\t\t\t} else {\n\t\t\t\t\t// removed\n\t\t\t\t\tconst lineNum = String(oldLineNum).padStart(lineNumWidth, \" \");\n\t\t\t\t\toutput.push(`-${lineNum} ${line}`);\n\t\t\t\t\toldLineNum++;\n\t\t\t\t}\n\t\t\t}\n\t\t\tlastWasChange = true;\n\t\t} else {\n\t\t\t// Context lines - only show a few before/after changes\n\t\t\tconst nextPartIsChange = i < parts.length - 1 && (parts[i + 1].added || parts[i + 1].removed);\n\t\t\tconst hasLeadingChange = lastWasChange;\n\t\t\tconst hasTrailingChange = nextPartIsChange;\n\n\t\t\tif (hasLeadingChange && hasTrailingChange) {\n\t\t\t\tif (raw.length <= contextLines * 2) {\n\t\t\t\t\tfor (const line of raw) {\n\t\t\t\t\t\tconst lineNum = String(oldLineNum).padStart(lineNumWidth, \" \");\n\t\t\t\t\t\toutput.push(` ${lineNum} ${line}`);\n\t\t\t\t\t\toldLineNum++;\n\t\t\t\t\t\tnewLineNum++;\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tconst leadingLines = raw.slice(0, contextLines);\n\t\t\t\t\tconst trailingLines = raw.slice(raw.length - contextLines);\n\t\t\t\t\tconst skippedLines = raw.length - leadingLines.length - trailingLines.length;\n\n\t\t\t\t\tfor (const line of leadingLines) {\n\t\t\t\t\t\tconst lineNum = String(oldLineNum).padStart(lineNumWidth, \" \");\n\t\t\t\t\t\toutput.push(` ${lineNum} ${line}`);\n\t\t\t\t\t\toldLineNum++;\n\t\t\t\t\t\tnewLineNum++;\n\t\t\t\t\t}\n\n\t\t\t\t\toutput.push(` ${\"\".padStart(lineNumWidth, \" \")} ...`);\n\t\t\t\t\toldLineNum += skippedLines;\n\t\t\t\t\tnewLineNum += skippedLines;\n\n\t\t\t\t\tfor (const line of trailingLines) {\n\t\t\t\t\t\tconst lineNum = String(oldLineNum).padStart(lineNumWidth, \" \");\n\t\t\t\t\t\toutput.push(` ${lineNum} ${line}`);\n\t\t\t\t\t\toldLineNum++;\n\t\t\t\t\t\tnewLineNum++;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else if (hasLeadingChange) {\n\t\t\t\tconst shownLines = raw.slice(0, contextLines);\n\t\t\t\tconst skippedLines = raw.length - shownLines.length;\n\n\t\t\t\tfor (const line of shownLines) {\n\t\t\t\t\tconst lineNum = String(oldLineNum).padStart(lineNumWidth, \" \");\n\t\t\t\t\toutput.push(` ${lineNum} ${line}`);\n\t\t\t\t\toldLineNum++;\n\t\t\t\t\tnewLineNum++;\n\t\t\t\t}\n\n\t\t\t\tif (skippedLines > 0) {\n\t\t\t\t\toutput.push(` ${\"\".padStart(lineNumWidth, \" \")} ...`);\n\t\t\t\t\toldLineNum += skippedLines;\n\t\t\t\t\tnewLineNum += skippedLines;\n\t\t\t\t}\n\t\t\t} else if (hasTrailingChange) {\n\t\t\t\tconst skippedLines = Math.max(0, raw.length - contextLines);\n\t\t\t\tif (skippedLines > 0) {\n\t\t\t\t\toutput.push(` ${\"\".padStart(lineNumWidth, \" \")} ...`);\n\t\t\t\t\toldLineNum += skippedLines;\n\t\t\t\t\tnewLineNum += skippedLines;\n\t\t\t\t}\n\n\t\t\t\tfor (const line of raw.slice(skippedLines)) {\n\t\t\t\t\tconst lineNum = String(oldLineNum).padStart(lineNumWidth, \" \");\n\t\t\t\t\toutput.push(` ${lineNum} ${line}`);\n\t\t\t\t\toldLineNum++;\n\t\t\t\t\tnewLineNum++;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t// Skip these context lines entirely\n\t\t\t\toldLineNum += raw.length;\n\t\t\t\tnewLineNum += raw.length;\n\t\t\t}\n\n\t\t\tlastWasChange = false;\n\t\t}\n\t}\n\n\treturn { diff: output.join(\"\\n\"), firstChangedLine };\n}\n\nexport interface EditDiffResult {\n\tdiff: string;\n\tfirstChangedLine: number | undefined;\n}\n\nexport interface EditDiffError {\n\terror: string;\n}\n\n/**\n * Compute the diff for one or more edit operations without applying them.\n * Used for preview rendering in the TUI before the tool executes.\n */\nexport async function computeEditsDiff(\n\tpath: string,\n\tedits: Edit[],\n\tcwd: string,\n): Promise<EditDiffResult | EditDiffError> {\n\tconst absolutePath = resolveToCwd(path, cwd);\n\n\ttry {\n\t\t// Check if file exists and is readable\n\t\ttry {\n\t\t\tawait access(absolutePath, constants.R_OK);\n\t\t} catch (error: unknown) {\n\t\t\tconst errorMessage = error instanceof Error && \"code\" in error ? `Error code: ${error.code}` : String(error);\n\t\t\treturn { error: `Could not edit file: ${path}. ${errorMessage}.` };\n\t\t}\n\n\t\t// Read the file\n\t\tconst rawContent = await readFile(absolutePath, \"utf-8\");\n\n\t\t// Strip BOM before matching (LLM won't include invisible BOM in oldText)\n\t\tconst { text: content } = stripBom(rawContent);\n\t\tconst normalizedContent = normalizeToLF(content);\n\t\tconst { baseContent, newContent } = applyEditsToNormalizedContent(normalizedContent, edits, path);\n\n\t\t// Generate the diff\n\t\treturn generateDiffString(baseContent, newContent);\n\t} catch (err) {\n\t\treturn { error: err instanceof Error ? err.message : String(err) };\n\t}\n}\n\n/**\n * Compute the diff for a single edit operation without applying it.\n * Kept as a convenience wrapper for single-edit callers.\n */\nexport async function computeEditDiff(\n\tpath: string,\n\toldText: string,\n\tnewText: string,\n\tcwd: string,\n): Promise<EditDiffResult | EditDiffError> {\n\treturn computeEditsDiff(path, [{ oldText, newText }], cwd);\n}\n"]}
1
+ {"version":3,"file":"edit-diff.d.ts","sourceRoot":"","sources":["../../../src/core/tools/edit-diff.ts"],"names":[],"mappings":"AAAA;;GAEG;AAQH,wBAAgB,gBAAgB,CAAC,OAAO,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,CAM/D;AAED,wBAAgB,aAAa,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAElD;AAED,wBAAgB,kBAAkB,CAAC,IAAI,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,IAAI,GAAG,MAAM,CAE9E;AAED;;;;;;GAMG;AACH,wBAAgB,sBAAsB,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAqB3D;AAWD,UAAU,WAAW;IACpB,SAAS,EAAE,MAAM,CAAC;IAClB,UAAU,EAAE,MAAM,CAAC;IACnB,WAAW,EAAE,MAAM,CAAC;IACpB,OAAO,EAAE,MAAM,CAAC;CAChB;AAED,KAAK,eAAe,GAAG,IAAI,CAAC,WAAW,EAAE,YAAY,GAAG,aAAa,GAAG,SAAS,CAAC,CAAC;AAiDnF;;;;;;;;;GASG;AACH,wBAAgB,yCAAyC,CACxD,eAAe,EAAE,MAAM,EACvB,WAAW,EAAE,MAAM,EACnB,YAAY,EAAE,eAAe,EAAE,GAC7B,MAAM,CAqCR;AAED,MAAM,WAAW,gBAAgB;IAChC,gCAAgC;IAChC,KAAK,EAAE,OAAO,CAAC;IACf,4FAA4F;IAC5F,KAAK,EAAE,MAAM,CAAC;IACd,iCAAiC;IACjC,WAAW,EA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,sBAAsB,GAAG,SAAS,GAAG,MAAM,CA4BpG;AA6CD;;;;;;;;GAQG;AACH,wBAAgB,6BAA6B,CAC5C,iBAAiB,EAAE,MAAM,EACzB,KAAK,EAAE,IAAI,EAAE,EACb,IAAI,EAAE,MAAM,GACV,kBAAkB,CAoEpB;AAED,yCAAyC;AACzC,wBAAgB,oBAAoB,CAAC,IAAI,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,EAAE,YAAY,SAAI,GAAG,MAAM,CAKnH;AAED;;;GAGG;AACH,wBAAgB,kBAAkB,CACjC,UAAU,EAAE,MAAM,EAClB,UAAU,EAAE,MAAM,EAClB,YAAY,SAAI,GACd;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,gBAAgB,EAAE,MAAM,GAAG,SAAS,CAAA;CAAE,CAuHxD;AAED,MAAM,WAAW,cAAc;IAC9B,IAAI,EAAE,MAAM,CAAC;IACb,gBAAgB,EAAE,MAAM,GAAG,SAAS,CAAC;CACrC;AAED,MAAM,WAAW,aAAa;IAC7B,KAAK,EAAE,MAAM,CAAC;CACd;AAED;;;GAGG;AACH,wBAAsB,gBAAgB,CACrC,IAAI,EAAE,MAAM,EACZ,KAAK,EAAE,IAAI,EAAE,EACb,GAAG,EAAE,MAAM,GACT,OAAO,CAAC,cAAc,GAAG,aAAa,CAAC,CAkBzC;AAED;;;;;;GAMG;AACH,wBAAgB,2BAA2B,CAC1C,IAAI,EAAE,MAAM,EACZ,UAAU,EAAE,MAAM,EAClB,KAAK,EAAE,IAAI,EAAE,GACX,cAAc,GAAG,aAAa,CAUhC;AAED;;;GAGG;AACH,wBAAsB,eAAe,CACpC,IAAI,EAAE,MAAM,EACZ,OAAO,EAAE,MAAM,EACf,OAAO,EAAE,MAAM,EACf,GAAG,EAAE,MAAM,GACT,OAAO,CAAC,cAAc,GAAG,aAAa,CAAC,CAEzC","sourcesContent":["/**\n * Shared diff computation utilities for the edit and similar tools.\n */\n\nimport * as Diff from \"diff\";\nimport { constants } from \"fs\";\nimport { access, readFile } from \"fs/promises\";\nimport { splitBom } from \"../../utils/text.ts\";\nimport { resolveToCwd } from \"./path-utils.ts\";\n\nexport function detectLineEnding(content: string): \"\\r\\n\" | \"\\n\" {\n\tconst crlfIdx = content.indexOf(\"\\r\\n\");\n\tconst lfIdx = content.indexOf(\"\\n\");\n\tif (lfIdx === -1) return \"\\n\";\n\tif (crlfIdx === -1) return \"\\n\";\n\treturn crlfIdx < lfIdx ? \"\\r\\n\" : \"\\n\";\n}\n\nexport function normalizeToLF(text: string): string {\n\treturn text.replace(/\\r\\n/g, \"\\n\").replace(/\\r/g, \"\\n\");\n}\n\nexport function restoreLineEndings(text: string, ending: \"\\r\\n\" | \"\\n\"): string {\n\treturn ending === \"\\r\\n\" ? text.replace(/\\n/g, \"\\r\\n\") : text;\n}\n\n/**\n * Normalize text for fuzzy matching. Applies progressive transformations:\n * - Strip trailing whitespace from each line\n * - Normalize smart quotes to ASCII equivalents\n * - Normalize Unicode dashes/hyphens to ASCII hyphen\n * - Normalize special Unicode spaces to regular space\n */\nexport function normalizeForFuzzyMatch(text: string): string {\n\treturn (\n\t\ttext\n\t\t\t.normalize(\"NFKC\")\n\t\t\t// Strip trailing whitespace per line\n\t\t\t.split(\"\\n\")\n\t\t\t.map((line) => line.trimEnd())\n\t\t\t.join(\"\\n\")\n\t\t\t// Smart single quotes → '\n\t\t\t.replace(/[\\u2018\\u2019\\u201A\\u201B]/g, \"'\")\n\t\t\t// Smart double quotes → \"\n\t\t\t.replace(/[\\u201C\\u201D\\u201E\\u201F]/g, '\"')\n\t\t\t// Various dashes/hyphens → -\n\t\t\t// U+2010 hyphen, U+2011 non-breaking hyphen, U+2012 figure dash,\n\t\t\t// U+2013 en-dash, U+2014 em-dash, U+2015 horizontal bar, U+2212 minus\n\t\t\t.replace(/[\\u2010\\u2011\\u2012\\u2013\\u2014\\u2015\\u2212]/g, \"-\")\n\t\t\t// Special spaces → regular space\n\t\t\t// U+00A0 NBSP, U+2002-U+200A various spaces, U+202F narrow NBSP,\n\t\t\t// U+205F medium math space, U+3000 ideographic space\n\t\t\t.replace(/[\\u00A0\\u2002-\\u200A\\u202F\\u205F\\u3000]/g, \" \")\n\t);\n}\n\nfunction splitLinesWithEndings(content: string): string[] {\n\treturn content.match(/[^\\n]*\\n|[^\\n]+/g) ?? [];\n}\n\ninterface LineSpan {\n\tstart: number;\n\tend: number;\n}\n\ninterface MatchedEdit {\n\teditIndex: number;\n\tmatchIndex: number;\n\tmatchLength: number;\n\tnewText: string;\n}\n\ntype TextReplacement = Pick<MatchedEdit, \"matchIndex\" | \"matchLength\" | \"newText\">;\n\nfunction getLineSpans(content: string): LineSpan[] {\n\tlet offset = 0;\n\treturn splitLinesWithEndings(content).map((line) => {\n\t\tconst span = { start: offset, end: offset + line.length };\n\t\toffset = span.end;\n\t\treturn span;\n\t});\n}\n\nfunction getReplacementLineRange(lines: LineSpan[], replacement: TextReplacement) {\n\tconst replacementStart = replacement.matchIndex;\n\tconst replacementEnd = replacement.matchIndex + replacement.matchLength;\n\n\tlet startLine = -1;\n\tfor (let i = 0; i < lines.length; i++) {\n\t\tconst line = lines[i];\n\t\tif (replacementStart >= line.start && replacementStart < line.end) {\n\t\t\tstartLine = i;\n\t\t\tbreak;\n\t\t}\n\t}\n\tif (startLine === -1) {\n\t\tthrow new Error(\"Replacement range is outside the base content.\");\n\t}\n\n\tlet endLine = startLine;\n\twhile (endLine < lines.length && lines[endLine].end < replacementEnd) {\n\t\tendLine++;\n\t}\n\tif (endLine >= lines.length) {\n\t\tthrow new Error(\"Replacement range is outside the base content.\");\n\t}\n\n\treturn { startLine, endLine: endLine + 1 };\n}\n\nfunction applyReplacements(content: string, replacements: TextReplacement[], offset = 0): string {\n\tlet result = content;\n\tfor (let i = replacements.length - 1; i >= 0; i--) {\n\t\tconst replacement = replacements[i];\n\t\tconst matchIndex = replacement.matchIndex - offset;\n\t\tresult =\n\t\t\tresult.substring(0, matchIndex) + replacement.newText + result.substring(matchIndex + replacement.matchLength);\n\t}\n\treturn result;\n}\n\n/**\n * Apply replacements matched against `baseContent` to `originalContent` while\n * preserving unchanged line blocks from the original.\n *\n * This is useful when `baseContent` is a normalized view of the original. Each\n * replacement is widened to the lines it actually touches, those touched lines\n * are rewritten from the normalized base, and all other lines are copied back\n * from `originalContent`. The actual replacement ranges drive preservation so\n * duplicate normalized lines cannot be aligned to the wrong occurrence.\n */\nexport function applyReplacementsPreservingUnchangedLines(\n\toriginalContent: string,\n\tbaseContent: string,\n\treplacements: TextReplacement[],\n): string {\n\tconst originalLines = splitLinesWithEndings(originalContent);\n\tconst baseLines = getLineSpans(baseContent);\n\tif (originalLines.length !== baseLines.length) {\n\t\tthrow new Error(\"Cannot preserve unchanged lines because the base content has a different line count.\");\n\t}\n\n\tconst groups: Array<{ startLine: number; endLine: number; replacements: TextReplacement[] }> = [];\n\tconst sortedReplacements = [...replacements].sort((a, b) => a.matchIndex - b.matchIndex);\n\tfor (const replacement of sortedReplacements) {\n\t\tconst range = getReplacementLineRange(baseLines, replacement);\n\t\tconst current = groups[groups.length - 1];\n\t\tif (current && range.startLine < current.endLine) {\n\t\t\tcurrent.endLine = Math.max(current.endLine, range.endLine);\n\t\t\tcurrent.replacements.push(replacement);\n\t\t\tcontinue;\n\t\t}\n\t\tgroups.push({ ...range, replacements: [replacement] });\n\t}\n\n\tlet originalLineIndex = 0;\n\tlet result = \"\";\n\tfor (const group of groups) {\n\t\tresult += originalLines.slice(originalLineIndex, group.startLine).join(\"\");\n\n\t\tconst groupStartOffset = baseLines[group.startLine].start;\n\t\tconst groupEndOffset = baseLines[group.endLine - 1].end;\n\t\tresult += applyReplacements(\n\t\t\tbaseContent.slice(groupStartOffset, groupEndOffset),\n\t\t\tgroup.replacements,\n\t\t\tgroupStartOffset,\n\t\t);\n\t\toriginalLineIndex = group.endLine;\n\t}\n\tresult += originalLines.slice(originalLineIndex).join(\"\");\n\n\treturn result;\n}\n\nexport interface FuzzyMatchResult {\n\t/** Whether a match was found */\n\tfound: boolean;\n\t/** The index where the match starts (in the content that should be used for replacement) */\n\tindex: number;\n\t/** Length of the matched text */\n\tmatchLength: number;\n\t/** Whether fuzzy matching was used (false = exact match) */\n\tusedFuzzyMatch: boolean;\n\t/**\n\t * The content to use for replacement operations.\n\t * When exact match: original content. When fuzzy match: normalized content.\n\t */\n\tcontentForReplacement: string;\n}\n\nexport interface Edit {\n\toldText: string;\n\tnewText: string;\n}\n\nexport interface AppliedEditsResult {\n\tbaseContent: string;\n\tnewContent: string;\n}\n\n/**\n * Find oldText in content, trying exact match first, then fuzzy match.\n * When fuzzy matching is used, the returned contentForReplacement is the\n * fuzzy-normalized version of the content (trailing whitespace stripped,\n * Unicode quotes/dashes normalized to ASCII).\n */\nexport function fuzzyFindText(content: string, oldText: string): FuzzyMatchResult {\n\t// Try exact match first\n\tconst exactIndex = content.indexOf(oldText);\n\tif (exactIndex !== -1) {\n\t\treturn {\n\t\t\tfound: true,\n\t\t\tindex: exactIndex,\n\t\t\tmatchLength: oldText.length,\n\t\t\tusedFuzzyMatch: false,\n\t\t\tcontentForReplacement: content,\n\t\t};\n\t}\n\n\t// Try fuzzy match - work entirely in normalized space\n\tconst fuzzyContent = normalizeForFuzzyMatch(content);\n\tconst fuzzyOldText = normalizeForFuzzyMatch(oldText);\n\tconst fuzzyIndex = fuzzyContent.indexOf(fuzzyOldText);\n\n\tif (fuzzyIndex === -1) {\n\t\treturn {\n\t\t\tfound: false,\n\t\t\tindex: -1,\n\t\t\tmatchLength: 0,\n\t\t\tusedFuzzyMatch: false,\n\t\t\tcontentForReplacement: content,\n\t\t};\n\t}\n\n\t// When fuzzy matching, return offsets in normalized space. Callers can use\n\t// the normalized content to compute replacements, then decide how much of\n\t// that normalized output should be written back.\n\treturn {\n\t\tfound: true,\n\t\tindex: fuzzyIndex,\n\t\tmatchLength: fuzzyOldText.length,\n\t\tusedFuzzyMatch: true,\n\t\tcontentForReplacement: fuzzyContent,\n\t};\n}\n\nfunction countOccurrences(content: string, oldText: string): number {\n\tconst fuzzyContent = normalizeForFuzzyMatch(content);\n\tconst fuzzyOldText = normalizeForFuzzyMatch(oldText);\n\treturn fuzzyContent.split(fuzzyOldText).length - 1;\n}\n\n/**\n * Explicit budgets for the advisory edit-failure diagnostics below. Diagnostics\n * are a best-effort hint, never an apply path, so every dimension of the scan\n * is bounded and the ordinary failure is returned untouched when a bound is\n * exceeded (spec 2026-09-01-tool-reliability-and-execution-budgets.md § 2).\n */\nexport const EDIT_DIAGNOSTIC_MAX_FILE_BYTES = 1_048_576;\nexport const EDIT_DIAGNOSTIC_MAX_TARGET_BYTES = 65_536;\nexport const EDIT_DIAGNOSTIC_MAX_CANDIDATES = 3;\nexport const EDIT_DIAGNOSTIC_MAX_SCAN_WINDOWS = 20_000;\nexport const EDIT_DIAGNOSTIC_MAX_OCCURRENCES = 5;\nexport const EDIT_DIAGNOSTIC_SNIPPET_LINE_CHARS = 160;\n\nconst EDIT_DIAGNOSTIC_MIN_SIMILARITY = 0.2;\nconst EDIT_DIAGNOSTIC_SCAN_BUDGET_MS = 50;\nconst EDIT_DIAGNOSTIC_MAX_OCCURRENCE_STEPS = 10_000;\n\nexport interface EditCandidateLocation {\n\t/** 1-based, inclusive. */\n\tstartLine: number;\n\t/** 1-based, inclusive. */\n\tendLine: number;\n\t/** Bigram Dice similarity against the failed target, rounded to two decimals. */\n\tsimilarity: number;\n\t/** Bounded snippet of the candidate source lines, each line-numbered. */\n\tsnippet: string;\n}\n\n/**\n * Advisory diagnostics attached to a failed edit match. These describe where a\n * target almost matched or where duplicates live; they are never a replacement\n * location and must never be applied.\n */\nexport interface EditFailureDiagnostics {\n\tkind: \"missing-match\" | \"duplicate-match\";\n\tcandidates: EditCandidateLocation[];\n\t/** 1-based source lines of up to EDIT_DIAGNOSTIC_MAX_OCCURRENCES duplicates. */\n\toccurrenceLines: number[];\n\tomittedOccurrences: number;\n\t/** True when the scan stopped at a work or time bound before finishing. */\n\tscanTruncated: boolean;\n\t/** Set when scanning was unsafe or oversized; no candidates are reported. */\n\tunavailableReason?: string;\n}\n\nfunction unavailableDiagnostics(kind: EditFailureDiagnostics[\"kind\"], reason: string): EditFailureDiagnostics {\n\treturn {\n\t\tkind,\n\t\tcandidates: [],\n\t\toccurrenceLines: [],\n\t\tomittedOccurrences: 0,\n\t\tscanTruncated: false,\n\t\tunavailableReason: reason,\n\t};\n}\n\nfunction isDiagnosticScannable(\n\tkind: EditFailureDiagnostics[\"kind\"],\n\tcontent: string,\n\ttarget: string,\n): EditFailureDiagnostics | undefined {\n\tif (Buffer.byteLength(content, \"utf-8\") > EDIT_DIAGNOSTIC_MAX_FILE_BYTES) {\n\t\treturn unavailableDiagnostics(\n\t\t\tkind,\n\t\t\t`advisory diagnostic scan skipped: file exceeds the ${EDIT_DIAGNOSTIC_MAX_FILE_BYTES}-byte diagnostic budget`,\n\t\t);\n\t}\n\tif (Buffer.byteLength(target, \"utf-8\") > EDIT_DIAGNOSTIC_MAX_TARGET_BYTES) {\n\t\treturn unavailableDiagnostics(\n\t\t\tkind,\n\t\t\t`advisory diagnostic scan skipped: oldText exceeds the ${EDIT_DIAGNOSTIC_MAX_TARGET_BYTES}-byte diagnostic budget`,\n\t\t);\n\t}\n\treturn undefined;\n}\n\nfunction bigrams(text: string): Set<string> {\n\tconst result = new Set<string>();\n\tfor (let i = 0; i < text.length - 1; i++) {\n\t\tresult.add(text.slice(i, i + 2));\n\t}\n\treturn result;\n}\n\nfunction diceSimilarity(a: Set<string>, b: Set<string>): number {\n\tif (a.size === 0 && b.size === 0) return 1;\n\tif (a.size === 0 || b.size === 0) return 0;\n\tlet intersection = 0;\n\tfor (const gram of a) {\n\t\tif (b.has(gram)) intersection++;\n\t}\n\treturn (2 * intersection) / (a.size + b.size);\n}\n\nfunction truncateSnippetLine(line: string): string {\n\tif (line.length <= EDIT_DIAGNOSTIC_SNIPPET_LINE_CHARS) return line;\n\treturn `${line.slice(0, EDIT_DIAGNOSTIC_SNIPPET_LINE_CHARS)}…`;\n}\n\nfunction buildSnippet(lines: string[], startLine: number, lineCount: number): string {\n\tconst shown = Math.min(lineCount, 5);\n\tconst parts: string[] = [];\n\tfor (let i = 0; i < shown; i++) {\n\t\tparts.push(`${startLine + i + 1} | ${truncateSnippetLine(lines[startLine + i] ?? \"\")}`);\n\t}\n\treturn parts.join(\"\\n\");\n}\n\n/**\n * Find the closest line windows to a failed target. Purely advisory: the result\n * names locations so the caller can retry with better context, and is never a\n * replacement specification.\n */\nfunction scanMissingMatchCandidates(content: string, target: string): EditFailureDiagnostics {\n\tconst blocked = isDiagnosticScannable(\"missing-match\", content, target);\n\tif (blocked) return blocked;\n\n\tconst lines = content.split(\"\\n\");\n\tconst windowSize = Math.max(1, target.split(\"\\n\").length);\n\tconst windowCount = lines.length - windowSize + 1;\n\tconst deadline = Date.now() + EDIT_DIAGNOSTIC_SCAN_BUDGET_MS;\n\tconst targetGrams = bigrams(target);\n\n\tconst best: Array<{ startLine: number; similarity: number }> = [];\n\tlet windowsScanned = 0;\n\tlet scanTruncated = false;\n\tfor (let start = 0; start < windowCount; start++) {\n\t\tif (windowsScanned >= EDIT_DIAGNOSTIC_MAX_SCAN_WINDOWS || (start % 512 === 0 && Date.now() > deadline)) {\n\t\t\tscanTruncated = true;\n\t\t\tbreak;\n\t\t}\n\t\twindowsScanned++;\n\t\tconst windowGrams = bigrams(lines.slice(start, start + windowSize).join(\"\\n\"));\n\t\tconst similarity = diceSimilarity(targetGrams, windowGrams);\n\t\tif (similarity < EDIT_DIAGNOSTIC_MIN_SIMILARITY) continue;\n\t\tif (best.length < EDIT_DIAGNOSTIC_MAX_CANDIDATES || similarity > best[best.length - 1].similarity) {\n\t\t\tbest.push({ startLine: start, similarity });\n\t\t\tbest.sort((a, b) => b.similarity - a.similarity);\n\t\t\tif (best.length > EDIT_DIAGNOSTIC_MAX_CANDIDATES) best.pop();\n\t\t}\n\t}\n\n\treturn {\n\t\tkind: \"missing-match\",\n\t\tcandidates: best.map((entry) => ({\n\t\t\tstartLine: entry.startLine + 1,\n\t\t\tendLine: entry.startLine + windowSize,\n\t\t\tsimilarity: Math.round(entry.similarity * 100) / 100,\n\t\t\tsnippet: buildSnippet(lines, entry.startLine, windowSize),\n\t\t})),\n\t\toccurrenceLines: [],\n\t\tomittedOccurrences: 0,\n\t\tscanTruncated,\n\t};\n}\n\nfunction lineNumberForOffset(lineStarts: number[], offset: number): number {\n\tlet low = 0;\n\tlet high = lineStarts.length - 1;\n\twhile (low < high) {\n\t\tconst mid = Math.ceil((low + high) / 2);\n\t\tif (lineStarts[mid] <= offset) low = mid;\n\t\telse high = mid - 1;\n\t}\n\treturn low + 1;\n}\n\n/** List bounded 1-based source lines for duplicate occurrences. Advisory only. */\nfunction scanDuplicateOccurrences(content: string, target: string): EditFailureDiagnostics {\n\tconst blocked = isDiagnosticScannable(\"duplicate-match\", content, target);\n\tif (blocked) return blocked;\n\n\tconst lines = content.split(\"\\n\");\n\tconst lineStarts: number[] = [];\n\tlet offset = 0;\n\tfor (const line of lines) {\n\t\tlineStarts.push(offset);\n\t\toffset += line.length + 1;\n\t}\n\n\tconst occurrenceLines: number[] = [];\n\tlet total = 0;\n\tlet truncated = false;\n\tlet searchFrom = 0;\n\twhile (target.length > 0) {\n\t\tconst index = content.indexOf(target, searchFrom);\n\t\tif (index === -1) break;\n\t\ttotal++;\n\t\tif (occurrenceLines.length < EDIT_DIAGNOSTIC_MAX_OCCURRENCES) {\n\t\t\toccurrenceLines.push(lineNumberForOffset(lineStarts, index));\n\t\t}\n\t\tsearchFrom = index + target.length;\n\t\tif (total >= EDIT_DIAGNOSTIC_MAX_OCCURRENCE_STEPS) {\n\t\t\ttruncated = true;\n\t\t\tbreak;\n\t\t}\n\t}\n\n\treturn {\n\t\tkind: \"duplicate-match\",\n\t\tcandidates: [],\n\t\toccurrenceLines,\n\t\tomittedOccurrences: Math.max(0, total - occurrenceLines.length),\n\t\tscanTruncated: truncated,\n\t};\n}\n\n/** Render advisory diagnostics as an error-message appendix. Empty when there is nothing to say. */\nexport function formatEditFailureDiagnostics(diagnostics: EditFailureDiagnostics | undefined): string {\n\tif (!diagnostics) return \"\";\n\tif (diagnostics.unavailableReason) {\n\t\treturn `\\n\\n(${diagnostics.unavailableReason}.)`;\n\t}\n\tconst sections: string[] = [];\n\tif (diagnostics.kind === \"duplicate-match\" && diagnostics.occurrenceLines.length > 0) {\n\t\tconst more = diagnostics.omittedOccurrences > 0 ? ` (+${diagnostics.omittedOccurrences} more)` : \"\";\n\t\tsections.push(`Advisory occurrence lines (not applied): ${diagnostics.occurrenceLines.join(\", \")}${more}`);\n\t}\n\tif (diagnostics.kind === \"missing-match\" && diagnostics.candidates.length > 0) {\n\t\tconst parts = [\"Advisory closest matches (not applied):\"];\n\t\tfor (const candidate of diagnostics.candidates) {\n\t\t\tparts.push(\n\t\t\t\t` lines ${candidate.startLine}-${candidate.endLine} (${Math.round(candidate.similarity * 100)}% similar)`,\n\t\t\t);\n\t\t\tfor (const line of candidate.snippet.split(\"\\n\")) {\n\t\t\t\tparts.push(` ${line}`);\n\t\t\t}\n\t\t}\n\t\tsections.push(parts.join(\"\\n\"));\n\t}\n\tif (diagnostics.scanTruncated) {\n\t\tsections.push(\n\t\t\t`(Advisory location scan truncated after ${EDIT_DIAGNOSTIC_MAX_SCAN_WINDOWS} windows; remaining locations were not examined.)`,\n\t\t);\n\t}\n\treturn sections.length > 0 ? `\\n\\n${sections.join(\"\\n\")}` : \"\";\n}\n\nfunction appendEditDiagnostics(error: Error, diagnostics: EditFailureDiagnostics): Error {\n\terror.message += formatEditFailureDiagnostics(diagnostics);\n\treturn error;\n}\n\nfunction getNotFoundError(path: string, editIndex: number, totalEdits: number): Error {\n\tif (totalEdits === 1) {\n\t\treturn new Error(\n\t\t\t`Could not find the exact text in ${path}. The old text must match exactly including all whitespace and newlines.`,\n\t\t);\n\t}\n\treturn new Error(\n\t\t`Could not find edits[${editIndex}] in ${path}. The oldText must match exactly including all whitespace and newlines.`,\n\t);\n}\n\nfunction getDuplicateError(path: string, editIndex: number, totalEdits: number, occurrences: number): Error {\n\tif (totalEdits === 1) {\n\t\treturn new Error(\n\t\t\t`Found ${occurrences} occurrences of the text in ${path}. The text must be unique. Please provide more context to make it unique.`,\n\t\t);\n\t}\n\treturn new Error(\n\t\t`Found ${occurrences} occurrences of edits[${editIndex}] in ${path}. Each oldText must be unique. Please provide more context to make it unique.`,\n\t);\n}\n\nfunction getEmptyOldTextError(path: string, editIndex: number, totalEdits: number): Error {\n\tif (totalEdits === 1) {\n\t\treturn new Error(`oldText must not be empty in ${path}.`);\n\t}\n\treturn new Error(`edits[${editIndex}].oldText must not be empty in ${path}.`);\n}\n\nfunction getNoChangeError(path: string, totalEdits: number): Error {\n\tif (totalEdits === 1) {\n\t\treturn new Error(\n\t\t\t`No changes made to ${path}. The replacement produced identical content. This might indicate an issue with special characters or the text not existing as expected.`,\n\t\t);\n\t}\n\treturn new Error(`No changes made to ${path}. The replacements produced identical content.`);\n}\n\n/**\n * Apply one or more exact-text replacements to LF-normalized content.\n *\n * All edits are matched against the same original content. Replacements are\n * then applied in reverse order so offsets remain stable. If any edit needs\n * fuzzy matching, the operation runs in fuzzy-normalized content space and then\n * overlays those line-level changes onto the original content so unchanged line\n * blocks keep their original bytes.\n */\nexport function applyEditsToNormalizedContent(\n\tnormalizedContent: string,\n\tedits: Edit[],\n\tpath: string,\n): AppliedEditsResult {\n\tconst normalizedEdits = edits.map((edit) => ({\n\t\toldText: normalizeToLF(edit.oldText),\n\t\tnewText: normalizeToLF(edit.newText),\n\t}));\n\n\tfor (let i = 0; i < normalizedEdits.length; i++) {\n\t\tif (normalizedEdits[i].oldText.length === 0) {\n\t\t\tthrow getEmptyOldTextError(path, i, normalizedEdits.length);\n\t\t}\n\t}\n\n\tconst initialMatches = normalizedEdits.map((edit) => fuzzyFindText(normalizedContent, edit.oldText));\n\tconst usedFuzzyMatch = initialMatches.some((match) => match.usedFuzzyMatch);\n\tconst replacementBaseContent = usedFuzzyMatch ? normalizeForFuzzyMatch(normalizedContent) : normalizedContent;\n\n\tconst matchedEdits: MatchedEdit[] = [];\n\tfor (let i = 0; i < normalizedEdits.length; i++) {\n\t\tconst edit = normalizedEdits[i];\n\t\tconst matchResult = fuzzyFindText(replacementBaseContent, edit.oldText);\n\t\tif (!matchResult.found) {\n\t\t\t// Advisory only: candidates name near-miss locations but never supply a\n\t\t\t// replacement. Matching above remains the only apply path.\n\t\t\tconst diagnosticTarget = usedFuzzyMatch ? normalizeForFuzzyMatch(edit.oldText) : edit.oldText;\n\t\t\tthrow appendEditDiagnostics(\n\t\t\t\tgetNotFoundError(path, i, normalizedEdits.length),\n\t\t\t\tscanMissingMatchCandidates(replacementBaseContent, diagnosticTarget),\n\t\t\t);\n\t\t}\n\n\t\tconst occurrences = countOccurrences(replacementBaseContent, edit.oldText);\n\t\tif (occurrences > 1) {\n\t\t\tconst diagnosticTarget = usedFuzzyMatch ? normalizeForFuzzyMatch(edit.oldText) : edit.oldText;\n\t\t\tthrow appendEditDiagnostics(\n\t\t\t\tgetDuplicateError(path, i, normalizedEdits.length, occurrences),\n\t\t\t\tscanDuplicateOccurrences(replacementBaseContent, diagnosticTarget),\n\t\t\t);\n\t\t}\n\n\t\tmatchedEdits.push({\n\t\t\teditIndex: i,\n\t\t\tmatchIndex: matchResult.index,\n\t\t\tmatchLength: matchResult.matchLength,\n\t\t\tnewText: edit.newText,\n\t\t});\n\t}\n\n\tmatchedEdits.sort((a, b) => a.matchIndex - b.matchIndex);\n\tfor (let i = 1; i < matchedEdits.length; i++) {\n\t\tconst previous = matchedEdits[i - 1];\n\t\tconst current = matchedEdits[i];\n\t\tif (previous.matchIndex + previous.matchLength > current.matchIndex) {\n\t\t\tthrow new Error(\n\t\t\t\t`edits[${previous.editIndex}] and edits[${current.editIndex}] overlap in ${path}. Merge them into one edit or target disjoint regions.`,\n\t\t\t);\n\t\t}\n\t}\n\n\tconst baseContent = normalizedContent;\n\tconst newContent = usedFuzzyMatch\n\t\t? applyReplacementsPreservingUnchangedLines(normalizedContent, replacementBaseContent, matchedEdits)\n\t\t: applyReplacements(replacementBaseContent, matchedEdits);\n\n\tif (baseContent === newContent) {\n\t\tthrow getNoChangeError(path, normalizedEdits.length);\n\t}\n\n\treturn { baseContent, newContent };\n}\n\n/** Generate a standard unified patch. */\nexport function generateUnifiedPatch(path: string, oldContent: string, newContent: string, contextLines = 4): string {\n\treturn Diff.createTwoFilesPatch(path, path, oldContent, newContent, undefined, undefined, {\n\t\tcontext: contextLines,\n\t\theaderOptions: Diff.FILE_HEADERS_ONLY,\n\t});\n}\n\n/**\n * Generate a display-oriented diff string with line numbers and context.\n * Returns both the diff string and the first changed line number (in the new file).\n */\nexport function generateDiffString(\n\toldContent: string,\n\tnewContent: string,\n\tcontextLines = 4,\n): { diff: string; firstChangedLine: number | undefined } {\n\tconst parts = Diff.diffLines(oldContent, newContent);\n\tconst output: string[] = [];\n\n\tconst oldLines = oldContent.split(\"\\n\");\n\tconst newLines = newContent.split(\"\\n\");\n\tconst maxLineNum = Math.max(oldLines.length, newLines.length);\n\tconst lineNumWidth = String(maxLineNum).length;\n\n\tlet oldLineNum = 1;\n\tlet newLineNum = 1;\n\tlet lastWasChange = false;\n\tlet firstChangedLine: number | undefined;\n\n\tfor (let i = 0; i < parts.length; i++) {\n\t\tconst part = parts[i];\n\t\tconst raw = part.value.split(\"\\n\");\n\t\tif (raw[raw.length - 1] === \"\") {\n\t\t\traw.pop();\n\t\t}\n\n\t\tif (part.added || part.removed) {\n\t\t\t// Capture the first changed line (in the new file)\n\t\t\tif (firstChangedLine === undefined) {\n\t\t\t\tfirstChangedLine = newLineNum;\n\t\t\t}\n\n\t\t\t// Show the change\n\t\t\tfor (const line of raw) {\n\t\t\t\tif (part.added) {\n\t\t\t\t\tconst lineNum = String(newLineNum).padStart(lineNumWidth, \" \");\n\t\t\t\t\toutput.push(`+${lineNum} ${line}`);\n\t\t\t\t\tnewLineNum++;\n\t\t\t\t} else {\n\t\t\t\t\t// removed\n\t\t\t\t\tconst lineNum = String(oldLineNum).padStart(lineNumWidth, \" \");\n\t\t\t\t\toutput.push(`-${lineNum} ${line}`);\n\t\t\t\t\toldLineNum++;\n\t\t\t\t}\n\t\t\t}\n\t\t\tlastWasChange = true;\n\t\t} else {\n\t\t\t// Context lines - only show a few before/after changes\n\t\t\tconst nextPartIsChange = i < parts.length - 1 && (parts[i + 1].added || parts[i + 1].removed);\n\t\t\tconst hasLeadingChange = lastWasChange;\n\t\t\tconst hasTrailingChange = nextPartIsChange;\n\n\t\t\tif (hasLeadingChange && hasTrailingChange) {\n\t\t\t\tif (raw.length <= contextLines * 2) {\n\t\t\t\t\tfor (const line of raw) {\n\t\t\t\t\t\tconst lineNum = String(oldLineNum).padStart(lineNumWidth, \" \");\n\t\t\t\t\t\toutput.push(` ${lineNum} ${line}`);\n\t\t\t\t\t\toldLineNum++;\n\t\t\t\t\t\tnewLineNum++;\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tconst leadingLines = raw.slice(0, contextLines);\n\t\t\t\t\tconst trailingLines = raw.slice(raw.length - contextLines);\n\t\t\t\t\tconst skippedLines = raw.length - leadingLines.length - trailingLines.length;\n\n\t\t\t\t\tfor (const line of leadingLines) {\n\t\t\t\t\t\tconst lineNum = String(oldLineNum).padStart(lineNumWidth, \" \");\n\t\t\t\t\t\toutput.push(` ${lineNum} ${line}`);\n\t\t\t\t\t\toldLineNum++;\n\t\t\t\t\t\tnewLineNum++;\n\t\t\t\t\t}\n\n\t\t\t\t\toutput.push(` ${\"\".padStart(lineNumWidth, \" \")} ...`);\n\t\t\t\t\toldLineNum += skippedLines;\n\t\t\t\t\tnewLineNum += skippedLines;\n\n\t\t\t\t\tfor (const line of trailingLines) {\n\t\t\t\t\t\tconst lineNum = String(oldLineNum).padStart(lineNumWidth, \" \");\n\t\t\t\t\t\toutput.push(` ${lineNum} ${line}`);\n\t\t\t\t\t\toldLineNum++;\n\t\t\t\t\t\tnewLineNum++;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else if (hasLeadingChange) {\n\t\t\t\tconst shownLines = raw.slice(0, contextLines);\n\t\t\t\tconst skippedLines = raw.length - shownLines.length;\n\n\t\t\t\tfor (const line of shownLines) {\n\t\t\t\t\tconst lineNum = String(oldLineNum).padStart(lineNumWidth, \" \");\n\t\t\t\t\toutput.push(` ${lineNum} ${line}`);\n\t\t\t\t\toldLineNum++;\n\t\t\t\t\tnewLineNum++;\n\t\t\t\t}\n\n\t\t\t\tif (skippedLines > 0) {\n\t\t\t\t\toutput.push(` ${\"\".padStart(lineNumWidth, \" \")} ...`);\n\t\t\t\t\toldLineNum += skippedLines;\n\t\t\t\t\tnewLineNum += skippedLines;\n\t\t\t\t}\n\t\t\t} else if (hasTrailingChange) {\n\t\t\t\tconst skippedLines = Math.max(0, raw.length - contextLines);\n\t\t\t\tif (skippedLines > 0) {\n\t\t\t\t\toutput.push(` ${\"\".padStart(lineNumWidth, \" \")} ...`);\n\t\t\t\t\toldLineNum += skippedLines;\n\t\t\t\t\tnewLineNum += skippedLines;\n\t\t\t\t}\n\n\t\t\t\tfor (const line of raw.slice(skippedLines)) {\n\t\t\t\t\tconst lineNum = String(oldLineNum).padStart(lineNumWidth, \" \");\n\t\t\t\t\toutput.push(` ${lineNum} ${line}`);\n\t\t\t\t\toldLineNum++;\n\t\t\t\t\tnewLineNum++;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t// Skip these context lines entirely\n\t\t\t\toldLineNum += raw.length;\n\t\t\t\tnewLineNum += raw.length;\n\t\t\t}\n\n\t\t\tlastWasChange = false;\n\t\t}\n\t}\n\n\treturn { diff: output.join(\"\\n\"), firstChangedLine };\n}\n\nexport interface EditDiffResult {\n\tdiff: string;\n\tfirstChangedLine: number | undefined;\n}\n\nexport interface EditDiffError {\n\terror: string;\n}\n\n/**\n * Compute the diff for one or more edit operations without applying them.\n * Used for preview rendering in the TUI before the tool executes.\n */\nexport async function computeEditsDiff(\n\tpath: string,\n\tedits: Edit[],\n\tcwd: string,\n): Promise<EditDiffResult | EditDiffError> {\n\tconst absolutePath = resolveToCwd(path, cwd);\n\n\ttry {\n\t\t// Check if file exists and is readable\n\t\ttry {\n\t\t\tawait access(absolutePath, constants.R_OK);\n\t\t} catch (error: unknown) {\n\t\t\tconst errorMessage = error instanceof Error && \"code\" in error ? `Error code: ${error.code}` : String(error);\n\t\t\treturn { error: `Could not edit file: ${path}. ${errorMessage}.` };\n\t\t}\n\n\t\t// Read the file\n\t\tconst rawContent = await readFile(absolutePath, \"utf-8\");\n\t\treturn computeEditsDiffFromContent(path, rawContent, edits);\n\t} catch (err) {\n\t\treturn { error: err instanceof Error ? err.message : String(err) };\n\t}\n}\n\n/**\n * The half of `computeEditsDiff` that does not choose which bytes to read.\n *\n * The permission preview must describe the operation the gate authorized rather\n * than whatever the pathname resolves to a second time, so it supplies content\n * read through the prepared operation and calls this (ADR 0029).\n */\nexport function computeEditsDiffFromContent(\n\tpath: string,\n\trawContent: string,\n\tedits: Edit[],\n): EditDiffResult | EditDiffError {\n\ttry {\n\t\t// Strip BOM before matching (LLM won't include invisible BOM in oldText)\n\t\tconst { text: content } = splitBom(rawContent);\n\t\tconst normalizedContent = normalizeToLF(content);\n\t\tconst { baseContent, newContent } = applyEditsToNormalizedContent(normalizedContent, edits, path);\n\t\treturn generateDiffString(baseContent, newContent);\n\t} catch (err) {\n\t\treturn { error: err instanceof Error ? err.message : String(err) };\n\t}\n}\n\n/**\n * Compute the diff for a single edit operation without applying it.\n * Kept as a convenience wrapper for single-edit callers.\n */\nexport async function computeEditDiff(\n\tpath: string,\n\toldText: string,\n\tnewText: string,\n\tcwd: string,\n): Promise<EditDiffResult | EditDiffError> {\n\treturn computeEditsDiff(path, [{ oldText, newText }], cwd);\n}\n"]}