pi-agent-ide 0.6.1 → 0.6.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (210) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/README.md +82 -30
  3. package/assets/summary/debugging.png +0 -0
  4. package/assets/summary/editing.png +0 -0
  5. package/assets/summary/read.png +0 -0
  6. package/assets/summary/search-and-replace.png +0 -0
  7. package/assets/summary/search.png +0 -0
  8. package/assets/summary/settings.png +0 -0
  9. package/assets/summary/terminal.png +0 -0
  10. package/assets/summary/thumbs/debugging.png +0 -0
  11. package/assets/summary/thumbs/editing.png +0 -0
  12. package/assets/summary/thumbs/read.png +0 -0
  13. package/assets/summary/thumbs/search-and-replace.png +0 -0
  14. package/assets/summary/thumbs/search.png +0 -0
  15. package/assets/summary/thumbs/settings.png +0 -0
  16. package/assets/summary/thumbs/terminal.png +0 -0
  17. package/assets/summary/thumbs/user_terminal.png +0 -0
  18. package/assets/summary/user_terminal.png +0 -0
  19. package/dist/{chunk-4KUFOHWP.js → chunk-3E2NTWCN.js} +1 -1
  20. package/dist/chunk-7WCZOO5I.js +1 -0
  21. package/dist/chunk-CEX3VOJ7.js +2 -0
  22. package/dist/{chunk-2527OQ4Y.js → chunk-HMLH43ZS.js} +1 -1
  23. package/dist/chunk-LVWMWWWF.js +28 -0
  24. package/dist/{chunk-HKMBQLEK.js → chunk-QDLTO5PH.js} +1 -1
  25. package/dist/{chunk-Z3VC3S2T.js → chunk-QIK2E64R.js} +1 -1
  26. package/dist/chunk-T7CZIACQ.js +27 -0
  27. package/dist/chunk-VXD6FZP5.js +5 -0
  28. package/dist/entry-1.js +1 -1
  29. package/dist/entry-2.js +1 -1
  30. package/dist/entry-31.js +8 -7
  31. package/dist/entry-34.js +1 -1
  32. package/dist/entry-36.js +1 -1
  33. package/dist/entry-37.js +1 -1
  34. package/dist/entry-51.js +9 -10
  35. package/dist/entry-53.js +1 -1
  36. package/dist/entry-54.js +1 -1
  37. package/dist/entry-55.js +1 -1
  38. package/dist/entry-56.js +1 -1
  39. package/dist/entry-57.js +1 -1
  40. package/dist/entry-58.js +1 -1
  41. package/dist/entry-59.js +1 -1
  42. package/dist/entry-60.js +1 -0
  43. package/dist/entry-61.js +1 -1
  44. package/dist/entry-63.js +1 -1
  45. package/dist/entry-64.js +0 -1
  46. package/dist/entry-65.js +1 -1
  47. package/dist/entry-66.js +1 -1
  48. package/dist/entry-67.js +1 -1
  49. package/dist/entry-68.js +1 -1
  50. package/dist/entry-69.js +1 -0
  51. package/dist/entry-70.js +1 -1
  52. package/dist/entry-72.js +1 -1
  53. package/dist/entry-73.js +0 -1
  54. package/dist/entry-74.js +1 -1
  55. package/dist/entry-75.js +1 -315
  56. package/dist/entry-76.js +1 -30
  57. package/dist/entry-77.js +315 -2
  58. package/dist/entry-78.js +30 -1
  59. package/dist/entry-79.js +2 -1
  60. package/dist/entry-80.js +1 -3
  61. package/dist/entry-81.js +1 -3
  62. package/dist/entry-82.js +3 -1
  63. package/dist/entry-83.js +3 -1
  64. package/dist/entry-84.js +1 -1
  65. package/dist/entry-85.js +1 -0
  66. package/dist/entry-86.js +1 -0
  67. package/dist/pi-agent-ide.js +1 -1
  68. package/docs/agent-guides/debugger.md +1 -1
  69. package/docs/agent-guides/terminal.md +1 -1
  70. package/node_modules/pi-agent-doctor/package.json +1 -1
  71. package/node_modules/pi-agent-documentation/package.json +1 -1
  72. package/node_modules/pi-agent-filesystem/package.json +6 -6
  73. package/node_modules/pi-agent-filesystem-image/package.json +3 -3
  74. package/node_modules/pi-agent-filesystem-jq/package.json +5 -5
  75. package/node_modules/pi-agent-filesystem-pdf/package.json +3 -3
  76. package/node_modules/pi-agent-filesystem-text/package.json +3 -3
  77. package/node_modules/pi-agent-ide-ast/package.json +10 -9
  78. package/node_modules/pi-agent-ide-ast/src/search-presentation.ts +117 -0
  79. package/node_modules/pi-agent-ide-ast/src/search-resolver.ts +20 -2
  80. package/node_modules/pi-agent-ide-changes/package.json +7 -7
  81. package/node_modules/pi-agent-ide-formatter/package.json +3 -3
  82. package/node_modules/pi-agent-ide-languages/package.json +2 -2
  83. package/node_modules/pi-agent-ide-lint/package.json +7 -7
  84. package/node_modules/pi-agent-ide-lsp/package.json +9 -9
  85. package/node_modules/pi-agent-image/package.json +2 -2
  86. package/node_modules/pi-agent-invariant/package.json +1 -1
  87. package/node_modules/pi-agent-pdf/package.json +2 -2
  88. package/node_modules/pi-agent-read/package.json +7 -7
  89. package/node_modules/pi-agent-resource/package.json +1 -1
  90. package/node_modules/pi-agent-search/package.json +4 -4
  91. package/node_modules/pi-agent-search-text/package.json +14 -6
  92. package/node_modules/pi-agent-search-text/runtime/entry-54.js +1 -0
  93. package/node_modules/pi-agent-search-text/src/persisted-result.ts +9 -7
  94. package/node_modules/pi-agent-search-text/src/search-renderer.ts +10 -4
  95. package/node_modules/pi-agent-search-text/src/search-result.ts +8 -1
  96. package/node_modules/pi-agent-text/package.json +3 -3
  97. package/node_modules/pi-agent-text-anchor-constant/package.json +4 -4
  98. package/node_modules/pi-agent-text-anchor-exact/package.json +5 -5
  99. package/node_modules/pi-agent-text-anchor-line-hash/package.json +7 -7
  100. package/node_modules/pi-agent-text-anchor-line-hash/runtime/entry-60.js +2 -0
  101. package/node_modules/pi-agent-text-editor/package.json +26 -26
  102. package/node_modules/pi-agent-text-editor/runtime/entry-75.js +0 -1
  103. package/node_modules/pi-agent-text-editor/runtime/entry-76.js +1 -0
  104. package/node_modules/pi-agent-text-editor-renderer/package.json +6 -6
  105. package/node_modules/pi-agent-text-editor-renderer/runtime/entry-78.js +2 -0
  106. package/node_modules/pi-agent-text-editor-stale-anchor/package.json +5 -5
  107. package/node_modules/pi-agent-text-editor-stale-anchor/runtime/entry-79.js +2 -0
  108. package/node_modules/pi-agent-tool-call-interception/package.json +3 -3
  109. package/node_modules/pi-agent-tool-call-interception/runtime/entry-80.js +1 -0
  110. package/node_modules/pi-agent-tool-ui/package.json +2 -2
  111. package/node_modules/pi-agent-tool-ui/runtime/entry-81.js +1 -0
  112. package/node_modules/pi-agent-web/package.json +7 -7
  113. package/node_modules/pi-agent-web-html/package.json +3 -3
  114. package/node_modules/pi-agent-web-image/package.json +4 -4
  115. package/node_modules/pi-agent-web-pdf/package.json +4 -4
  116. package/node_modules/pi-agent-web-pdf/runtime/entry-85.js +2 -0
  117. package/node_modules/pi-agent-web-text/package.json +4 -4
  118. package/node_modules/pi-agent-web-text/runtime/entry-86.js +2 -0
  119. package/package.json +35 -35
  120. package/src/api/plugin-protocol.ts +10 -4
  121. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/package.json +6 -6
  122. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-image/package.json +3 -3
  123. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-jq/package.json +5 -5
  124. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-pdf/package.json +3 -3
  125. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-text/package.json +3 -3
  126. package/src/extensions/pi-agent-read/extensions/pi-agent-web/package.json +7 -7
  127. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-html/package.json +3 -3
  128. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-image/package.json +4 -4
  129. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-pdf/package.json +4 -4
  130. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-pdf/runtime/entry-85.js +2 -0
  131. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-text/package.json +4 -4
  132. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-text/runtime/entry-86.js +2 -0
  133. package/src/extensions/pi-agent-read/extensions/pi-agent-web/runtime/entry-82.js +2 -0
  134. package/src/extensions/pi-agent-read/package.json +7 -7
  135. package/src/extensions/pi-agent-search/package.json +4 -4
  136. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/package.json +14 -6
  137. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/runtime/entry-53.js +1 -0
  138. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/runtime/entry-54.js +1 -0
  139. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/src/persisted-result.ts +9 -7
  140. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/src/search-renderer.ts +10 -4
  141. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/src/search-result.ts +8 -1
  142. package/src/extensions/pi-agent-text-editor/package.json +26 -26
  143. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-constant/package.json +4 -4
  144. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-exact/package.json +5 -5
  145. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-line-hash/package.json +7 -7
  146. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-line-hash/runtime/entry-59.js +1 -0
  147. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-line-hash/runtime/entry-60.js +2 -0
  148. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-renderer/package.json +6 -6
  149. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-renderer/runtime/entry-78.js +2 -0
  150. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-stale-anchor/package.json +5 -5
  151. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-stale-anchor/runtime/entry-79.js +2 -0
  152. package/src/extensions/pi-agent-text-editor/runtime/entry-75.js +0 -1
  153. package/src/extensions/pi-agent-text-editor/runtime/entry-76.js +1 -0
  154. package/src/extensions/pi-agent-text-editor/runtime/entry-77.js +2 -0
  155. package/src/plugins/pi-agent-ide-ast/package.json +10 -9
  156. package/src/plugins/pi-agent-ide-ast/src/search-presentation.ts +117 -0
  157. package/src/plugins/pi-agent-ide-ast/src/search-resolver.ts +20 -2
  158. package/src/plugins/pi-agent-ide-changes/package.json +7 -7
  159. package/src/plugins/pi-agent-ide-debugger/index.ts +32 -10
  160. package/src/plugins/pi-agent-ide-debugger/src/renderer.ts +10 -1
  161. package/src/plugins/pi-agent-ide-debugger/src/session-manager.ts +39 -0
  162. package/src/plugins/pi-agent-ide-debugger/src/ui.ts +42 -5
  163. package/src/plugins/pi-agent-ide-formatter/package.json +3 -3
  164. package/src/plugins/pi-agent-ide-languages/package.json +2 -2
  165. package/src/plugins/pi-agent-ide-lint/package.json +7 -7
  166. package/src/plugins/pi-agent-ide-lsp/package.json +9 -9
  167. package/src/plugins/pi-agent-ide-terminal/src/resources.ts +88 -9
  168. package/src/plugins/pi-agent-ide-terminal/src/screen-image.ts +6 -2
  169. package/src/plugins/pi-agent-ide-vision/index.ts +2 -1
  170. package/src/plugins/pi-agent-ide-vision/src/vision.ts +17 -3
  171. package/assets/gallery/apply-editing.png +0 -0
  172. package/assets/gallery/debugging.png +0 -0
  173. package/assets/gallery/read-web.png +0 -0
  174. package/assets/gallery/search-replace.png +0 -0
  175. package/assets/gallery/terminal.png +0 -0
  176. package/assets/gallery/tool-editing.png +0 -0
  177. package/dist/chunk-4LDOV7QS.js +0 -28
  178. package/dist/chunk-I6Y3W4X6.js +0 -27
  179. package/dist/chunk-YEQOQMU7.js +0 -5
  180. package/node_modules/pi-agent-text-anchor-constant/runtime/entry-54.js +0 -2
  181. package/node_modules/pi-agent-text-editor/runtime/entry-60.js +0 -1
  182. package/node_modules/pi-agent-text-editor-renderer/runtime/entry-76.js +0 -2
  183. package/node_modules/pi-agent-tool-call-interception/runtime/entry-78.js +0 -1
  184. package/node_modules/pi-agent-tool-ui/runtime/entry-79.js +0 -1
  185. package/node_modules/pi-agent-web/runtime/entry-80.js +0 -2
  186. package/node_modules/pi-agent-web-html/runtime/entry-81.js +0 -2
  187. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-html/runtime/entry-81.js +0 -2
  188. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-image/runtime/entry-82.js +0 -2
  189. package/src/extensions/pi-agent-read/extensions/pi-agent-web/runtime/entry-80.js +0 -2
  190. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-constant/runtime/entry-54.js +0 -2
  191. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-exact/runtime/entry-55.js +0 -1
  192. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-renderer/runtime/entry-76.js +0 -2
  193. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-stale-anchor/runtime/entry-77.js +0 -2
  194. package/src/extensions/pi-agent-text-editor/runtime/entry-59.js +0 -1
  195. package/src/extensions/pi-agent-text-editor/runtime/entry-60.js +0 -1
  196. /package/node_modules/{pi-agent-text → pi-agent-search-text}/runtime/entry-53.js +0 -0
  197. /package/node_modules/{pi-agent-text-anchor-exact → pi-agent-text}/runtime/entry-55.js +0 -0
  198. /package/node_modules/{pi-agent-text-anchor-exact → pi-agent-text-anchor-constant}/runtime/entry-56.js +0 -0
  199. /package/node_modules/{pi-agent-text-anchor-line-hash → pi-agent-text-anchor-exact}/runtime/entry-57.js +0 -0
  200. /package/node_modules/{pi-agent-text-anchor-line-hash → pi-agent-text-anchor-exact}/runtime/entry-58.js +0 -0
  201. /package/node_modules/{pi-agent-text-editor → pi-agent-text-anchor-line-hash}/runtime/entry-59.js +0 -0
  202. /package/node_modules/{pi-agent-text-editor-stale-anchor → pi-agent-text-editor}/runtime/entry-77.js +0 -0
  203. /package/node_modules/{pi-agent-web-image → pi-agent-web}/runtime/entry-82.js +0 -0
  204. /package/node_modules/{pi-agent-web-pdf → pi-agent-web-html}/runtime/entry-83.js +0 -0
  205. /package/node_modules/{pi-agent-web-text → pi-agent-web-image}/runtime/entry-84.js +0 -0
  206. /package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/{pi-agent-web-pdf → pi-agent-web-html}/runtime/entry-83.js +0 -0
  207. /package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/{pi-agent-web-text → pi-agent-web-image}/runtime/entry-84.js +0 -0
  208. /package/src/extensions/pi-agent-text-editor/plugins/{pi-agent-text-anchor-exact → pi-agent-text-anchor-constant}/runtime/entry-56.js +0 -0
  209. /package/src/extensions/pi-agent-text-editor/plugins/{pi-agent-text-anchor-line-hash → pi-agent-text-anchor-exact}/runtime/entry-57.js +0 -0
  210. /package/src/extensions/pi-agent-text-editor/plugins/{pi-agent-text-anchor-line-hash → pi-agent-text-anchor-exact}/runtime/entry-58.js +0 -0
package/dist/entry-77.js CHANGED
@@ -1,2 +1,315 @@
1
- import{b as O}from"./chunk-YHADTHQM.js";import{a as I}from"./chunk-4LUW26BX.js";import{a as S}from"./chunk-MBUXFKIW.js";import{a as A}from"./chunk-AWXVJ5AC.js";import"./chunk-GIRAEVUJ.js";import{a as M}from"./chunk-L7JMDDSD.js";import{a as w,b as C}from"./chunk-O6LE42GK.js";import"./chunk-YHUTTZC6.js";import{a as k}from"./chunk-6CZO43OH.js";import{a as P,b as E}from"./chunk-OBNING2A.js";import"./chunk-S3ZPXWX7.js";import"./chunk-5VSE5X5R.js";import{a as x}from"./chunk-ZC65Z3CK.js";import{a as m}from"./chunk-EI7MMDWY.js";var R="\0",v="";async function D(t){let o,n={protocol:P,apiVersion:E,id:"text-editor-stale-anchor",setup(i){o=i}},a={protocol:w,apiVersion:C,id:"text-editor-stale-anchor",setup(i){let d=$(t,i,()=>{if(o===void 0)throw new Error("pi-agent-read is unavailable");return o});I(t,d.handler),i.onMutationTool(d.add)}};await Promise.all([k(t,n),M(t,a)])}m(D,"registerTextEditorStaleAnchor");function $(t,o,n){let a=new Map,i=[],d=new Map,c=new Map,u={name:"text-editor-stale-anchor-inspection",blockExecution:!0,toolNames:i,async intercept(e){let s=a.get(e.toolCall.name);if(s===void 0)return;let r=e.partialArgs??e.args,f=H(r,e,d,s.source.field,s.source.inherited?O(t)?.source:void 0);if(f===void 0)return;let T=await V(o,n(),e,s,r,f,c);if(T!==void 0)return T;let g=s.pair?.every(p=>{let l=s.anchors?.find(h=>h.field===p);return l!==void 0&&A(l,r[p])})===!0?new Set(s.pair):new Set;for(let p of s.anchors??[]){if(g.has(p.field))continue;let l=r[p.field];if(!A(p,l))continue;let h=r[p.sourceField],_=typeof h=="string"?h:f,y=await b(o,n(),e,p.field,_,[l],[p.kinds],c);if(y!==void 0)return y}},onContentEnd(e){c.delete(e)},onAbort(e){c.delete(e),d.delete(e)},onAgentEnd(){c.clear(),d.clear()}};return{handler:u,add(e){(e.anchors?.length??0)>0&&(a.set(e.name,e),i.push(e.name),I(t,u))}}}m($,"createHandler");function H(t,o,n,a,i){let d=t[a];if(typeof d=="string")return o.contentIndex!==void 0&&n.set(o.contentIndex,d),d;if(o.contentIndex!==void 0)for(let c=o.contentIndex-1;c>=0;c-=1){let u=n.get(c);if(u!==void 0)return t[a]=u,u}return i!==void 0&&(t[a]=i),i}m(H,"resolveSource");async function V(t,o,n,a,i,d,c){if(a.pair===void 0)return;let[u,e]=a.pair,s=i[u],r=i[e];if(typeof s!="string"||typeof r!="string")return;let f=a.anchors?.find(({field:g})=>g===u),T=a.anchors?.find(({field:g})=>g===e);if(!(f===void 0||T===void 0)&&!(!A(f,s)||!A(T,r)))return b(t,o,n,e,d,[s,r],[f.kinds,T.kinds],c)}m(V,"inspectAnchorPair");async function b(t,o,n,a,i,d,c,u){let e=n.contentIndex??-1,s=`${i}${R}${d.join(R)}${R}${c.map(l=>l.join(v)).join(R)}`,r=u.get(e)?.get(s);if(r===void 0){let l=await t.inspectTextAnchors({source:i,anchors:d,kinds:c,cwd:n.cwd,...n.signal!==void 0&&{signal:n.signal}}),h=u.get(e)??new Map;h.set(s,l),u.set(e,h),r=l}if(r.kind==="valid")return;if(r.kind==="failed")return j(n.toolCall.name,i,r.reason);if(r.rejectionCode!=="stale")return;let f=r.anchorIndex,g=(r.contextRange===void 0?void 0:await o.read({path:i,views:["anchors"],...r.contextRange},{cwd:n.cwd,...n.signal!==void 0&&{signal:n.signal}}))?.content.filter(l=>l.type==="text").map(l=>l.text).join(`
2
- `),p={guardId:"stale-anchor",effect:"not-applied",toolName:n.toolCall.name,field:a,path:i,anchor:x(d[f]),...!(g===void 0||g.length===0)&&{context:g}};return L(p,r.reason)}m(b,"inspectAnchors");function j(t,o,n){return{annotation:{kind:"blocked",reason:n},message:{customType:"text-editor-resolver-block",content:`[SYSTEM] ${t} blocked: ${n}`,display:!1,details:{guardId:"resolver",effect:"not-applied",toolName:t,source:o,reason:n}}}}m(j,"makeResolverBlockResult");function L(t,o){return{annotation:{kind:"stale-anchor"},message:{customType:"text-editor-stale-anchor-block",content:S(t,o),display:!1,details:t}}}m(L,"makeBlockResult");export{D as default};
1
+ import{a as Ct}from"./chunk-J34VKQGJ.js";import{a as fe,b as Xe,c as Ke}from"./chunk-AWXVJ5AC.js";import{a as Ge,b as ze,c as bt}from"./chunk-YHADTHQM.js";import{b as At,c as xn}from"./chunk-4LUW26BX.js";import{a as St}from"./chunk-U22JNO6N.js";import{a as Cn}from"./chunk-MBUXFKIW.js";import"./chunk-4U2GUKNJ.js";import{a as Tn,b as Rn,c as wn,d as En,e as vn,f as An,h as bn,j as Sn}from"./chunk-YT42LKFV.js";import{a as qe,d as ee}from"./chunk-ITSNK5YG.js";import{a as V}from"./chunk-GUTQ3PWL.js";import{b as Se,f as Et,g as vt}from"./chunk-GIRAEVUJ.js";import{e as xt,f as en}from"./chunk-T7I2VX3J.js";import{b as sn,c as an,e as cn,f as dn,g as ln,h as We,i as be,j as un,k as pn,l as fn}from"./chunk-FEDVTZJG.js";import{a as He,b as Ve,c as _,d as B,e as tn,f as nn,g as Ae,h as Rt,i as wt,j as rn,m as on}from"./chunk-O6LE42GK.js";import{a as Tt}from"./chunk-FA6BKC5Y.js";import"./chunk-NNCZYO4Q.js";import"./chunk-VCTK4JSN.js";import"./chunk-YHUTTZC6.js";import{a as je}from"./chunk-6CZO43OH.js";import{a as _e,b as Be}from"./chunk-OBNING2A.js";import{b as z,e as Ue}from"./chunk-S3ZPXWX7.js";import"./chunk-ROXXK6TW.js";import{a as yn}from"./chunk-KII2JQC5.js";import{a as hn}from"./chunk-ZTYWHL2F.js";import{a as gn,b as mn}from"./chunk-7UGNGK7Y.js";import{b as Yt,d as De,f as Jt,g as Qt,h as Zt,l as yt,m as se}from"./chunk-5VSE5X5R.js";import{a as S}from"./chunk-ZC65Z3CK.js";import{a as c}from"./chunk-EI7MMDWY.js";import{Type as wo}from"typebox";function kt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}c(kt,"isRecord");function Eo(e){if(kt(e))return typeof e.name=="string"?e.name:kt(e.function)&&typeof e.function.name=="string"?e.function.name:void 0}c(Eo,"toolName");function kn(e){e.registerTool({name:"edit",label:"edit",description:"",promptGuidelines:["Use the smallest useful source view: reuse sufficient content and anchors, search for known text, or inspect structure when locating a declaration. Read nearby context when boundaries are unclear; resolve ambiguity rather than guessing.","Use an available anchor when it selects exactly the intended text; otherwise use minimal unique exact text. Keep the edit limited to the intended content.","When search broadens to separate words, treat its results as location hints. Refine the query before using those matches for replacement.","Use standalone mutation tools in one assistant-response batch when each change is known in advance and does not depend on another change. This is the default for several independent edits in one file or across files. Every call is evaluated against the original file snapshots. Combine overlapping changes into one mutation. Use Apply only when edits require computation, conditions, selection composition, checkpoints, or one coherent cross-file transaction. Check each batch result and retry only unapplied changes."],parameters:wo.Object({},{additionalProperties:!1}),execute(){throw new Error("edit is not available.")}}),e.on("before_provider_request",t=>{if(!(!kt(t.payload)||!Array.isArray(t.payload.tools)))return{...t.payload,tools:t.payload.tools.filter(n=>Eo(n)!=="edit")}})}c(kn,"registerBuiltinEditFilter");var Pn=new WeakMap;function Mn(e,t){Pn.set(e,t)}c(Mn,"setTextAnchorRecoveryReader");function In(e,t,n){return Pn.get(e)?.(t,n)}c(In,"readTextAnchorRecovery");import{diffLines as vo}from"diff";function On(e,t={}){let n=e.source?`${e.source}:`:"",r=t.includeAnchor===!1||e.anchor===void 0?"":`${e.anchor} \u2014 `;return`[${e.severity.toUpperCase()}] ${r}${n}${e.code}: ${e.message}`}c(On,"formatHint");var $n=5,Ao=5,Ln={error:0,warning:1,info:2,hint:3};function Nn(e,t){let n=e.data.afterDocument,r=e.data.snapshot?.content??e.data.beforeContentMap?.[t]??void 0,o=e.data.afterContent??n?.content;if(r===void 0||o===void 0)return So(e,t);let s=Ot(o),i=Math.max(1,s.length),a=Pt(r,o,i),d=Mt(e,o,i,a),l=Ce(d,i),u=e.hints.filter(x=>x.source==="compiler"&&x.severity==="error"),p=It(u,l),h=Ce([...d,...p.filter(x=>!ge(x.line,l)).map(x=>({start:x.line,end:x.line}))],i),f=a.filter(x=>x.kind==="added").length,m=a.filter(x=>x.kind==="removed").length,y=[`${t} +${f} -${m}`],w=new Set(p),g=e.data.scopeMarkers??{};for(let x=0;x<h.length;x+=1){x>0&&y.push("...");let R=S(h[x]);for(let E of a){if(!ko(E,R))continue;if(E.kind==="removed"){y.push({marker:"-",prefix:"|",content:E.text});continue}if(n!==void 0){let M=n.lines[S(E.afterLine)-1],T=M?.presentation?.prefix??"",k=M?.presentation?.suffix??"",P=Ye(S(E.afterLine),e.hints,l,w),C=P.length>0?` ${P.join(" ")}`:"";y.push({marker:E.kind==="added"?"+":" ",prefix:T,content:E.text,suffix:`${k}${C}`});continue}let v=S(E.afterLine),I=Ye(v,e.hints,l,w,g[String(v)]??g[v]),A=I.length>0?` ${I.join(" ")}`:"";y.push({marker:E.kind==="added"?"+":" ",prefix:"|",content:E.text,suffix:A})}}return Dn(y)}c(Nn,"renderAgentDiff");function Dn(e){let t=Zt(e.filter(bo)),n=0;return e.map(r=>typeof r=="string"?r:S(t[n++]))}c(Dn,"renderDiffEntries");function bo(e){return typeof e!="string"}c(bo,"isPresentedTextRow");function So(e,t){let r=(e.diffs.find(a=>Mo(a)===t)??e.diffs[0]??"").split(`
2
+ `).filter(a=>!a.startsWith("--- ")&&!a.startsWith("+++ ")&&!a.startsWith("@@ ")&&!a.startsWith("\\ No newline")),o=r.filter(a=>a.startsWith("+")).length,s=r.filter(a=>a.startsWith("-")).length,i=[`${t} +${o} -${s}`];for(let a of r){let d=a[0];if(d!=="+"&&d!=="-"&&d!==" "){i.push(a);continue}i.push({marker:d,prefix:"|",content:a.slice(1)})}return Dn(i)}c(So,"renderUnavailableSourceDiff");function Pt(e,t,n){let r=[],o=1,s=1;for(let i of vo(e,t))for(let a of Po(i.value))if(i.added)r.push({kind:"added",text:a,afterLine:s,positionLine:s}),s+=1;else if(i.removed){let d=Math.max(1,Math.min(s,n));r.push({kind:"removed",text:a,beforeLine:o,positionLine:d}),o+=1}else r.push({kind:"context",text:a,beforeLine:o,afterLine:s,positionLine:s}),o+=1,s+=1;return r}c(Pt,"buildDiffLines");function Mt(e,t,n,r){let o=e.data.rawChanges??[];if(o.length>0)return o.map(i=>({start:Fn(t,i.fromB),end:Fn(t,Math.max(i.fromB,i.toB-(i.toB>i.fromB?1:0)))}));let s=r.filter(i=>i.kind!=="context").map(i=>i.positionLine);return s.length===0?[]:[{start:Math.max(1,Math.min(...s)),end:Math.min(n,Math.max(...s))}]}c(Mt,"editRanges");function Ce(e,t){if(t===0)return[];let n=e.map(o=>({start:Math.max(1,Math.min(t,o.start)-$n),end:Math.min(t,Math.max(o.start,o.end)+$n)})).sort((o,s)=>o.start-s.start);if(n.length===0)return[];let r=[S(n[0])];for(let o of n.slice(1)){let s=S(r.at(-1));o.start<=s.end+1?s.end=Math.max(s.end,o.end):r.push(o)}return r}c(Ce,"expandAndMerge");function It(e,t){let n=e.filter(o=>ge(o.line,t)).sort((o,s)=>o.line-s.line),r=e.filter(o=>!ge(o.line,t)).sort(Co);return[...n,...r.slice(0,Math.max(0,Ao-n.length))]}c(It,"selectSyntaxHints");function Co(e,t){return Ln[e.severity]-Ln[t.severity]||e.line-t.line||e.column-t.column||e.code.localeCompare(t.code)}c(Co,"compareHints");function Ye(e,t,n,r,o){let s=[];o!==void 0&&o.length>0&&s.push(`<!-- ${o.join(" ")} -->`);let i=ge(e,n),a=t.filter(d=>d.line===e&&(i||r.has(d)));return a.length>0&&s.push(`<!-- lsp: ${a.map(d=>On(d,{includeAnchor:!1})).join(" | ")} -->`),s}c(Ye,"metadataForLine");function ko(e,t){return e.positionLine>=t.start&&e.positionLine<=t.end}c(ko,"isDiffLineVisible");function ge(e,t){return t.some(n=>e>=n.start&&e<=n.end)}c(ge,"isLineVisible");function Fn(e,t){let n=Math.max(0,Math.min(e.length,t));return e.slice(0,n).split(`
3
+ `).length}c(Fn,"lineAtOffset");function Ot(e){if(e.length===0)return[];let t=e.replaceAll(`\r
4
+ `,`
5
+ `).replaceAll("\r",`
6
+ `);return t.endsWith(`
7
+ `)?t.slice(0,-1).split(`
8
+ `):t.split(`
9
+ `)}c(Ot,"splitLines");function Po(e){if(e.length===0)return[];let n=e.replaceAll(`\r
10
+ `,`
11
+ `).replaceAll("\r",`
12
+ `).split(`
13
+ `);return n.at(-1)===""&&n.pop(),n}c(Po,"splitPartLines");function Mo(e){return/^--- (.+)$/m.exec(e)?.[1]}c(Mo,"extractDiffPath");function _n(e){if(e.length===0)return;let t=[],n=new Map,r=[],o=0;for(let s of e){let i=s.data.operations,a=s.data.rawChanges;if(!s.ok||s.isPartial||s.warnings.length>0||s.errors.length>0||(s.data.hints?.length??0)>0||(s.data.diffStatuses?.length??0)>0||!s.path||!i?.length||i.some(l=>l.operation!=="replace")||!a?.length||i.reduce((l,u)=>l+u.changes,0)!==a.length)return;let d=[];for(let l of a){let u=JSON.stringify([l.removedText,l.insertedText]),p=n.get(u);p===void 0&&(p=t.length,n.set(u,p),t.push({removedText:l.removedText,insertedText:l.insertedText,count:0}));let h=t[p];if(h===void 0)throw new Error("Missing replacement group");h.count++,d[p]=(d[p]??0)+1,o++}r.push({path:s.path,groups:d,formatting:s.data.formatting?.status??"not-reported"})}if(t.length!==o)return{groups:t,files:r,changes:o}}c(_n,"groupReplacements");function Bn(e){return[`Applied ${e.changes} replacements in ${e.files.length} files.`,"Exact applied replacements (before any additional formatting; not a full final-file view):",...e.groups.map((t,n)=>`G${n+1}: ${JSON.stringify(t.removedText)} -> ${JSON.stringify(t.insertedText)} (${t.count} replacements)`),"Files (complete):",...e.files.map(t=>`${t.path}: ${t.groups.flatMap((n,r)=>n?[`G${r+1} x ${n}`]:[]).join(", ")}; formatting: ${t.formatting}`)].join(`
14
+ `)}c(Bn,"renderGroupedReplacements");function jn(e,t){let n=e.data.snapshot?.content??e.data.beforeContentMap?.[t],r=e.data.afterContent??e.data.afterDocument?.content;if(n==null||r===void 0)return[t];let o=Ot(r),s=Math.max(1,o.length),i=Pt(n,r,s),a=Mt(e,r,s,i),d=Ce(a,s),l=e.hints.filter(m=>m.source==="compiler"&&m.severity==="error"),u=It(l,d),p=Ce([...a,...u.filter(m=>!ge(m.line,d)).map(m=>({start:m.line,end:m.line}))],s),h=new Set(u),f=[t];for(let m=0;m<p.length;m+=1){m>0&&f.push("...");let y=S(p[m]);f.push(`Final text, lines ${y.start}\u2013${y.end}:`);for(let w=y.start;w<=y.end;w+=1){let g=o[w-1]??"",x=Ye(w,e.hints,d,h),R=x.length===0?"":` ${x.join(" ")}`,E=e.data.resultPresentation==="major-anchor"?e.data.afterDocument?.lines[w-1]?.presentation?.prefix??"":"";f.push(`${E}${g}${R}`)}}return f}c(jn,"renderFinalStateFragment");var X=class{static{c(this,"FileMutationAgentResult")}results;constructor(t){this.results=Array.isArray(t)?t:[t]}toText(){let t=_n(this.results);return t!==void 0?Bn(t):Array.from(this.results,r=>this.formatSingle(r)).join(`
15
+
16
+ `)}toTextContent(){return{type:"text",text:this.toText()}}formatSingle(t){return t.isPartial?"gate progress":t.ok?t.diffs.length===0&&t.files.length===0?"<empty-result>":this.formatSuccess(t):this.formatFailure(t)}formatFailure(t){if(t.errors.some(i=>i.code==="STALE_ANCHOR")&&t.staleEdits.length>0&&!t.staleDiagnostic)return this.formatStaleFailure(t);let n=[`EDIT_FAILED (${t.errors.length} error${t.errors.length===1?"":"s"})`,""];if(t.path&&n.push(`Path: ${t.path}`),t.editRange){let i=t.editRange.end.anchor==="?"?t.editRange.start.anchor:t.editRange.end.anchor;n.push(`Requested range: ${t.editRange.start.anchor} .. ${i}`)}if(t.failurePoint&&n.push(`Failure point: ${t.failurePoint}`),t.expectedAnchor&&n.push(`Expected anchor: ${t.expectedAnchor}`),t.currentAnchor&&n.push(`Current anchor: ${t.currentAnchor}`),(t.internalErrorType||t.internalErrorMessage)&&(n.push(`Internal error type: ${t.internalErrorType??"unknown"}`),n.push(`Internal error message: ${t.internalErrorMessage??"unknown"}`),n.push("Operator hint: this is a tool bug, not an agent edit mistake."),n.push("")),t.recovery){n.push("Recovery:");for(let i of t.recovery.split(`
17
+ `))n.push(` ${i}`);n.push("")}if(t.freshAnchors&&t.freshAnchors.length>0){n.push("Fresh nearby anchors:");for(let i of t.freshAnchors)n.push(` ${i}`)}for(let i of t.diffs){let a=/^--- (.+)$/m.exec(i)?.[1]??t.path??"<unknown file>";n.push(...Nn(t,a))}if(t.files.length>0){let i=t.createdFiles,a=t.overwrittenFiles;if(i.length>0){n.push(""),n.push("Created:");for(let d of i){let l=d.size===void 0?"":` (${d.size} bytes)`;n.push(` ${d.path}${l}`)}}if(a.length>0){n.push(""),n.push("Edited:");for(let d of a)n.push(` ${d.path}`)}}let r=t.warnings.filter(i=>i.severity==="syntax"),o=t.warnings.filter(i=>i.severity==="diagnostic");if(r.length>0){n.push(""),n.push("Syntax diagnostics:");for(let i of r)for(let a of i.messages)n.push(` ${a}`)}if(r.length===0&&o.length>0){n.push(""),n.push("Diagnostics:");for(let i of o)for(let a of i.messages)n.push(` ${a}`)}if(t.proposedDiff&&n.push("","Proposed diff was not applied:",t.proposedDiff),t.editIndex!==void 0&&n.push("",`Edit index: ${t.editIndex}`),t.editIndices!==void 0&&t.editIndices.length>0&&n.push("",`Edit indices: ${t.editIndices.join(", ")}`),t.staleDiagnostic){let i=t.staleDiagnostic;if(n.push("",`target: ${t.path??"?"}`),n.push(`line: ${i.lineNumber}`,""),n.push("expected:"),n.push(` ${i.expected.lineNumber}#${i.expected.hash} (original text unavailable)`),n.push("","current:"),n.push(` ${i.current.lineNumber}#${i.current.hash} ${i.current.text}`),n.push("",`anchor_hash_changed: ${i.anchorHashChanged}`),i.currentContext.length>0){n.push("","current_context:");for(let a of i.currentContext){let d=a.lineNumber===i.lineNumber?">>":" ";n.push(` ${d} ${a.lineNumber}#${a.hash} ${a.text}`)}}}let s=t.errors.some(i=>i.code==="MUTATION_REJECTED");t.fileChangedStatement!==void 0?n.push("",t.fileChangedStatement):s||n.push("","No file was changed.");for(let i of t.errors){n.push("");let a=i.code==="MUTATION_REJECTED";a||n.push(`Failed: ${i.code??"ERROR"}`),i.path&&i.path!==t.path&&n.push(`${a?"":" "}Path: ${i.path}`),i.reason&&n.push(`${a?"":" "}Reason: ${i.reason}`)}return t.hints.length>0&&(n.push(""),n.push("---"),n.push("LSP diagnostics detected. You MUST fix all LSP issues before the result is accepted.")),n.join(`
18
+ `)}formatStaleFailure(t){let n=["EDIT_FAILED",""];if(t.staleEdits.length>0){n.push(`All ${t.staleEdits.length} edits have stale anchors:`);for(let r of t.staleEdits)n.push(`edits[${r.index}]: STALE_ANCHOR (${r.failurePoint})`);n.push("")}if(t.freshAnchors&&t.freshAnchors.length>0){n.push("Current nearby anchors:");for(let r of t.freshAnchors)n.push(` ${r}`)}return n.join(`
19
+ `)}formatSuccess(t){let n=t.data.operations??[],r={replace:"Replaced selected text",insert:"Inserted new text",delete:"Deleted selected text",copy:"Copied selected text",move:"Moved selected text",write:"Wrote file content",undo:"Restored file content",stage:"Staged selected changes",unstage:"Unstaged selected changes"},o=[n.length===0?"Changes applied.":n.map(({operation:s,changes:i})=>`${r[s]??`Applied ${s}`}: ${i} text change(s) in this file.`).join(`
20
+ `),`Formatting: ${t.data.formatting?.status??"not-reported"}${t.data.formatting?.formatter===void 0?"":` (${t.data.formatting.formatter})`}.`];for(let s of t.data.diffStatuses??[])o.push(s.text);for(let s of t.diffs){let i=/^--- (.+)$/m.exec(s)?.[1]??t.path??"<unknown file>";o.push(jn(t,i).join(`
21
+ `))}if(t.diffs.length===0)for(let s of t.files)o.push(s.path);return o.join(`
22
+
23
+ `)}};var Un=new WeakMap;function Qe(e){return Un.get(e)}c(Qe,"resolvedTextAnchorType");var N=class extends Error{constructor(n,r,o,s,i,a,d){super(n,o);this.resolverId=r;this.rejection=s;this.recovery=i;this.recoverAgain=a;this.originalRecoveryContext=d}static{c(this,"TextAnchorResolutionError")}async refreshRecovery(n){let r=n===void 0?this.originalRecoveryContext:n;this.recoverAgain!==void 0&&r!==void 0&&(this.recovery=await this.recoverAgain(r))}},Je=class{static{c(this,"TextAnchorRegistry")}#e=[];add(t){if(typeof t.kind!="string"||t.kind.trim().length===0)throw new TypeError("Text anchor resolver kind must be a non-empty string");let n=t.resolver.id;if(this.#e.some(({resolver:r})=>r.id===n))throw new Error(`Text anchor resolver ${n} is already registered`);if(t.type==="major"&&this.#e.some(({type:r})=>r==="major"))throw new Error("A major text anchor resolver is already registered");this.#e.push({resolver:t.resolver,...t.resources!==void 0&&{resources:t.resources},kind:t.kind,type:t.type,priority:t.priority??0,order:this.#e.length,describeInPrompt:t.describeInPrompt??!0})}assertCanAdd(t){let n=new Set(this.#e.map(({resolver:o})=>o.id)),r=this.#e.some(({type:o})=>o==="major");for(let o of t){if(typeof o.kind!="string"||o.kind.trim().length===0)throw new TypeError("Text anchor resolver kind must be a non-empty string");if(n.has(o.resolver.id))throw new Error(`Text anchor resolver ${o.resolver.id} is already registered`);if(n.add(o.resolver.id),o.type==="major"){if(r)throw new Error("A major text anchor resolver is already registered");r=!0}}}snapshot(){return new $t([...this.#e].sort((t,n)=>t.priority-n.priority||t.order-n.order))}renderPromptSection(t){let n=this.#e.filter(({describeInPrompt:r,kind:o})=>r&&(t===void 0||t.has(o))).map(({resolver:r})=>Oo(r)).filter(r=>r!==void 0);return n.length===0?void 0:["Text editor anchors:",...n,"Pass structured anchors exactly as shown."].join(`
24
+ `)}},$t=class{constructor(t){this.resolvers=t}static{c(this,"TextAnchorRegistrySnapshot")}async inspect(t,n,r){for(let o=0;o<t.length;o+=1)try{await this.resolve(S(t[o]),r,new Set(n[o]))}catch(s){return s instanceof N?s.rejection===void 0?{kind:"invalid",anchorIndex:o,reason:s.message}:{kind:"invalid",anchorIndex:o,reason:s.rejection.reason,rejectionCode:s.rejection.code,...s.rejection.contextRange!==void 0&&{contextRange:s.rejection.contextRange}}:{kind:"failed",reason:"Text anchor resolution failed",cause:s}}return{kind:"valid"}}async resolveResources(t,n,r){for(let{kind:o,resolver:s,resources:i}of this.resolvers){if(i===void 0||r!==void 0&&!r.has(o))continue;let a;try{a=await i.tryResolve(t,n)}catch(d){throw new N(`Text anchor resource resolver ${s.id} failed for "${t}"`,s.id,{cause:d})}if(!rn(a))throw new N(`Text anchor resource resolver ${s.id} returned an invalid result for "${t}"`,s.id,{cause:a});if(a.kind!=="not-handled"){if(a.kind==="failed")throw new N(`Text anchor resource resolver ${s.id} failed for "${t}"`,s.id,{cause:a.error});if(a.kind==="rejected")throw new N(a.rejection.reason,s.id,void 0,a.rejection);return a.targets}}}async resolve(t,n,r){if(n.lines.length===0)throw new N(`Anchor "${t}" cannot resolve in an empty file`);for(let{kind:o,resolver:s,type:i}of this.resolvers){if(r!==void 0&&!r.has(o))continue;let a,d;try{if(d=s.normalize?.(t)??t,typeof d!="string"||d.length===0)throw new TypeError("Text anchor normalization must return non-empty text");a=await s.tryResolve(d,n)}catch(l){throw new N(`Text anchor resolver ${s.id} failed for "${t}"`,s.id,{cause:l})}if(!Jt(a))throw new N(`Text anchor resolver ${s.id} returned an invalid result for "${t}"`,s.id,{cause:a});if(a.kind!=="not-handled"){if(a.kind==="failed")throw new N(`Text anchor resolver ${s.id} failed for "${t}"`,s.id,{cause:a.error});if(a.kind==="rejected"){let l=s.recover===void 0?void 0:u=>$o(s,d,a.rejection,u);throw new N(a.rejection.reason,s.id,void 0,a.rejection,void 0,l,n)}if(a.anchor.value!==d||a.anchor.lineNumber>n.lines.length)throw new N(`Text anchor resolver ${s.id} resolved "${t}" outside the current text`,s.id,{cause:a});if(V.is(a.anchor)&&!Io(a.anchor,n))throw new N(`Text anchor resolver ${s.id} resolved "${t}" outside the current text`,s.id,{cause:a});return Yt(a.anchor,s,s.id),Un.set(a.anchor,i),a.anchor}}throw new N(`No text anchor resolver handled "${t}"`)}};function Io(e,t){return e.source!==t.source?!1:e.ranges.every(n=>{let r=t.lines[n.start.lineNumber-1],o=t.lines[n.end.lineNumber-1],s=o===void 0&&n.end.lineNumber===t.lines.length+1&&n.end.column===0&&/(?:\r\n|\r|\n)$/u.test(t.content);return r!==void 0&&(o!==void 0||s)&&n.start.column<=r.length&&(s||n.end.column<=(o?.length??-1))})}c(Io,"isSelectionWithinContext");function Oo(e){let t=typeof e.description=="string"?e.description:e.description();if(t!==void 0){if(typeof t!="string"||t.trim().length===0)throw new TypeError(`Text anchor resolver ${e.id} description must be non-empty text`);return`- ${t.trim().replaceAll(`
25
+ `," ")}`}}c(Oo,"renderResolverDescription");async function $o(e,t,n,r){if(e.recover===void 0)return{kind:"unavailable"};try{let o=await e.recover(t,{...r,rejection:n});return Qt(o)&&Lo(o,r)?o:{kind:"failed",error:new Error(`Text anchor resolver ${e.id} returned invalid recovery`)}}catch(o){return{kind:"failed",error:o}}}c($o,"runAnchorRecovery");function Lo(e,t){return e.kind!=="candidates"||e.total<e.candidates.length?e.kind!=="candidates":e.candidates.every(({rank:n,range:r},o)=>{let s=t.lines[r.start.lineNumber-1],i=t.lines[r.end.lineNumber-1];return n===o+1&&s!==void 0&&i!==void 0&&r.start.column<=s.length&&r.end.column<=i.length&&(r.start.lineNumber<r.end.lineNumber||r.start.column<=r.end.column)})}c(Lo,"recoveryFitsContext");import{ChangeSet as Fo,Text as Hn}from"@codemirror/state";var me=class{constructor(t){this.content=t;this.#e=Do(t),this.#t=t.includes(`\r
26
+ `)?`\r
27
+ `:`
28
+ `}static{c(this,"TextChangeDocument")}#e;#t;get length(){return this.content.length}lineRange(t,n){let r=Math.min(t,n),o=Math.max(t,n);return this.#n(r),this.#n(o),{from:S(this.#e[r-1]),to:this.#e[o]??this.content.length}}range(t,n,r,o){let s=this.#i(t,n),i=this.#i(r,o);if(i<s)throw new RangeError(`Text range ${s}-${i} is reversed.`);return{from:s,to:i}}text(t){return this.#s(t),this.content.slice(t.from,t.to)}replaceLines(t,n,r){let o=this.lineRange(t,n);return{...o,insert:this.#o(o,r)}}deleteLines(t,n){let r=this.lineRange(t,n);return r.to===this.content.length&&r.from>0&&!ke(this.content)?{from:jo(this.content,r.from),to:r.to,insert:""}:{...r,insert:""}}insertBeforeLine(t,n){this.#n(t);let r=S(this.#e[t-1]);return{from:r,to:r,insert:this.#r(n)}}insertAfterLine(t,n){this.#n(t);let r=this.#e[t];if(r!==void 0)return{from:r,to:r,insert:this.#r(n)};let o=this.content.length>0&&!ke(this.content)?this.#t:"";return{from:this.content.length,to:this.content.length,insert:o+Bo(n)}}replaceAll(t){return{from:0,to:this.content.length,insert:t}}#o(t,n){let r=this.text(t);return ke(r)&&!ke(n)?n+S(_o(r)):n}#r(t){return ke(t)?t:t+this.#t}#i(t,n){if(this.#n(t),!Number.isInteger(n)||n<0)throw new RangeError(`Column ${n} is outside line ${t}.`);let r=S(this.#e[t-1]),o=this.#e[t],s=o??this.content.length;if(o!==void 0&&(s-=1,this.content[s-1]==="\r"&&(s-=1)),r+n>s)throw new RangeError(`Column ${n} is outside line ${t}.`);return r+n}#n(t){if(!Number.isInteger(t)||t<1||t>this.#e.length)throw new RangeError(`Line ${t} is outside the document.`)}#s(t){if(t.from<0||t.to<t.from||t.to>this.content.length)throw new RangeError(`Text range ${t.from}-${t.to} is outside the document.`)}};function U(e,t,n=!1){let r=t.map((a,d)=>({change:a,index:d})).sort((a,d)=>a.change.from-d.change.from||a.index-d.index).map(({change:a})=>a);if(No(e.length,r),!(n&&e.length===0)&&r.some(a=>e.slice(a.from,a.to)===a.insert))throw new Error("Text changes must change the document.");let o=Hn.of([e]),s=Fo.of(r.map(a=>({...a,insert:Hn.of([a.insert])})),o.length),i=[];return s.iterChanges((a,d,l,u,p)=>{i.push({fromBefore:a,toBefore:d,fromAfter:l,toAfter:u,removedText:e.slice(a,d),insertedText:p.toString()})}),{content:s.apply(o).toString(),changes:i}}c(U,"applyTextChanges");function No(e,t){let n;for(let r of t){if(!Number.isInteger(r.from)||!Number.isInteger(r.to)||r.from<0||r.to<r.from||r.to>e)throw new RangeError(`Text change ${r.from}-${r.to} is outside the document.`);if(n!==void 0&&(r.from<n.from||r.from<n.to))throw new Error("Text changes must be ordered and must not overlap.");n=r}}c(No,"validateChanges");function Do(e){let t=[0],n=/\r\n|\n/gu,r;for(;(r=n.exec(e))!==null;)t.push(r.index+r[0].length);return t}c(Do,"findLineStarts");function ke(e){return e.endsWith(`
29
+ `)}c(ke,"endsWithLineBreak");function _o(e){return e.endsWith(`\r
30
+ `)?`\r
31
+ `:e.endsWith(`
32
+ `)?`
33
+ `:void 0}c(_o,"lineBreakOf");function Bo(e){return e.replace(/(?:\r\n|\n)$/u,"")}c(Bo,"removeTrailingLineBreak");function jo(e,t){return e[t-2]==="\r"&&e[t-1]===`
34
+ `?t-2:t-1}c(jo,"previousLineBreakStart");var Ze=class{static{c(this,"BatchExecutionJournal")}entries;constructor(t){this.entries=new Map(t.map(n=>[n,{callId:n,state:"pending",recovered:!1}]))}reporter(t=!1){return{start:c(n=>{this.transition(n,{state:"running",recovered:t})},"start"),complete:c((n,r)=>{this.transition(n,{state:"completed",result:r,recovered:t})},"complete"),fail:c((n,r)=>{this.transition(n,{state:`failed-${r.effect}`,failure:r,...r.result!==void 0&&{result:r.result},recovered:t})},"fail")}}block(t,n,r){this.transition(t,{state:"blocked",result:n,blockedDetails:r,recovered:!1})}skip(t,n){this.transition(t,{state:"failed-not-applied",failure:{error:new Error(n),effect:"not-applied"},recovered:!1,reason:n})}markRunningUnknown(t){for(let n of this.entries.values())n.state==="running"&&this.transition(n.callId,{state:"failed-unknown",failure:{error:t,effect:"unknown"},recovered:n.recovered})}get(t){let n=this.entries.get(t);if(!n)throw new Error(`Unknown batch call ${t}.`);return n}snapshot(){return[...this.entries.values()].map(t=>({...t}))}transition(t,n){if(!this.entries.has(t))throw new Error(`Unknown batch call ${t}.`);this.entries.set(t,{callId:t,...n})}};function ne(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}c(ne,"isObjectNotArray");var Pe=new Map,Vn=new WeakMap,et=new Map;function Xn(e){et.set(e.callId,e);let t=Pe.get(e.callId);t?.blockedCalls.every(n=>n.callId!==e.callId)&&(t.blockedCalls.push(e),t.journal.block(e.callId,e.result,e.details))}c(Xn,"registerBlockedToolCall");function Uo(){Pe.clear(),et.clear()}c(Uo,"clearCoordinatorCalls");function Wn(e){if(!(!ne(e)||e.type!=="toolCall"||typeof e.id!="string"||typeof e.name!="string")&&ne(e.arguments))return{id:e.id,name:e.name,arguments:e.arguments}}c(Wn,"asRawToolCall");function qn(e,t){return e.definitions.find(n=>n.sourceTools.includes(t))}c(qn,"definitionFor");function Gn(e,t){t.renderArgumentPatch!==void 0&&e.onRenderArguments?.(t.call.id,t.renderArgumentPatch)}c(Gn,"publishRenderArguments");function zn(e,t,n){if(!ne(t)||t.role!=="assistant"||!Array.isArray(t.content))return;let r=t.content,o,s;for(let i=0;i<r.length;){let a=Wn(r[i]),d=a?qn(e,a.name):void 0,l=a&&d?d.resolveCall(a,o===d?s:void 0):void 0;if(!d||!l){o=void 0,s=void 0,i+=1;continue}Gn(d,l);let u=[l],p=i+1;for(;p<r.length;){let f=Wn(r[p]);if(!f||qn(e,f.name)!==d)break;let m=d.resolveCall(f,S(u.at(-1)).state);if(!m)break;Gn(d,m),u.push(m),p+=1}let h=S(u.at(-1));if(n&&u.length>=2){let f=u.map(({call:g})=>g),m=new Ze(f.map(g=>g.id)),y=f.flatMap(g=>{let x=et.get(g.id);return x===void 0?[]:[x]}),w={definition:d,candidates:u,calls:f,carrierId:h.call.id,batchId:`${String(Date.now())}-${String(e.nextBatchId++)}`,remainingCallIds:new Set(f.map(g=>g.id)),journal:m,blockedCalls:y};for(let g of y)m.block(g.callId,g.result,g.details);for(let g of f)Pe.set(g.id,w)}o=d,s=h.state,i=p}}c(zn,"rewriteMessage");function Ho(e,t){let n=t.payload;if(!ne(n)||!Array.isArray(n.tools))return;let r=new Set(e.definitions.map(o=>o.syntheticTool));return{...n,tools:n.tools.filter(o=>{if(!ne(o))return!0;let s=typeof o.name=="string"?o.name:void 0,i=ne(o.function)&&typeof o.function.name=="string"?o.function.name:void 0;return s===void 0&&i===void 0?!0:(s===void 0||!r.has(s))&&(i===void 0||!r.has(i))})}}c(Ho,"filterProviderTools");function Vo(e,t,n){let r=ne(e.details)?e.details:{};return{...e,details:{...r,agenticIdeBatch:{batchId:t,calls:n}}}}c(Vo,"markBatchResult");function Wo(e){return e.calls.map(t=>({id:t.id,name:t.name}))}c(Wo,"batchDisplayCalls");function qo(e,t,n,r){return e.execution??=(async()=>{let o,s;try{let a=e.candidates.filter(({call:u})=>e.journal.get(u.id).state!=="blocked"),d=e.definition.buildArguments(a);o=await e.definition.execute(e.carrierId,d,t,n,r,e.journal.reporter());let l=e.definition.splitResult?.(o,e.calls,e.candidates);for(let[u,p]of l??[])e.journal.get(u).state==="completed"&&e.journal.reporter().complete(u,p)}catch(a){s=a,e.journal.markRunningUnknown(a)}await Go(e,t,r);let i=zo(e,s);return o===void 0?{perCallResults:i}:{aggregate:o,perCallResults:i}})(),e.execution}c(qo,"ensureBatchExecution");async function Go(e,t,n){let r=e.definition.recovery;if(!r)return;let o={batchId:e.batchId,calls:e.calls,candidates:e.candidates,journal:e.journal.snapshot(),blockedCalls:e.blockedCalls,cwd:n.cwd,signal:t,ctx:n},s=new Set(r.select(o)),i=e.candidates.filter(({call:a})=>{let d=e.journal.get(a.id).state;return s.has(a.id)&&(d==="pending"||d==="failed-not-applied")});if(i.length!==0)try{let a=await r.execute({...o,selected:i,reporter:e.journal.reporter(!0)});for(let[d,l]of a.results)i.some(({call:u})=>u.id===d)?e.journal.reporter(!0).complete(d,l):e.journal.get(d).state==="completed"&&e.journal.reporter().complete(d,l);for(let[d,l]of a.skipped??[])e.journal.skip(d,l)}catch(a){for(let{call:d}of i){let l=e.journal.get(d.id).state;(l==="pending"||l==="running"||l==="failed-not-applied")&&e.journal.reporter(!0).fail(d.id,{error:a,effect:l==="running"?"unknown":"not-applied"})}}}c(Go,"recoverBatch");function zo(e,t){return new Map(e.calls.map(n=>{let r=e.journal.get(n.id);if(r.result){let i=ne(r.result.details)?r.result.details:{};return[n.id,{...r.result,details:{...i,batchRecovery:{batchId:e.batchId,state:r.state,recovered:r.recovered,...r.reason!==void 0&&{reason:r.reason}}}}]}let o=r.failure?.error??t??r.reason,s=o instanceof Error?o.message:typeof o=="string"?o:"call did not execute";return[n.id,{content:[{type:"text",text:`${n.name} failed: ${s}`}],details:{batchRecovery:{batchId:e.batchId,state:r.state,recovered:r.recovered,...r.reason!==void 0&&{reason:r.reason}}},isError:!0}]}))}c(zo,"finalBatchResults");function Xo(e,t){if(e.remainingCallIds.delete(t),!(e.remainingCallIds.size>0))for(let n of e.calls)Pe.delete(n.id),et.delete(n.id)}c(Xo,"releaseBatchCall");async function Kn(e,t,n,r,o){let s=Pe.get(e);if(!s)return t();try{if(s.definition.splitResult===void 0&&s.carrierId!==e)return{content:[{type:"text",text:""}],details:{agenticIdeBatchSuppressed:!0}};let i=await qo(s,n,r,o);if(s.definition.splitResult!==void 0){let a=i.perCallResults?.get(e);if(!a)throw new Error(`Missing split batch result for tool call ${e}.`);return Vo(a,s.batchId,Wo(s))}return i.aggregate?i.aggregate:await t()}finally{Xo(s,e)}}c(Kn,"executeWithBatchCoordinator");function Ko(e){let t=Vn.get(e);if(!t){let n={definitions:[],registered:!1,nextBatchId:1};Vn.set(e,n),t=n}return t.registered||(t.registered=!0,e.on("message_update",n=>{zn(t,n.message,!1)}),e.on("message_end",n=>{zn(t,n.message,!0)}),e.on("before_provider_request",n=>Ho(t,n)),e.on("agent_end",()=>{Uo()})),t}c(Ko,"coordinatorFor");function Yn(e,t){let n=Ko(e),r={sourceTools:t.sourceTools,syntheticTool:t.syntheticTool,resolveCall:c((o,s)=>t.resolveCall(o,s),"resolveCall"),buildArguments:c(o=>t.buildArguments(o),"buildArguments"),execute:t.execute,...t.onRenderArguments!==void 0&&{onRenderArguments:t.onRenderArguments},...t.recovery!==void 0&&{recovery:t.recovery},...t.splitResult!==void 0&&{splitResult:c((o,s,i)=>S(t.splitResult)(o,s,i),"splitResult")}};n.definitions.push(r)}c(Yn,"registerToolBatch");function Yo(e){return e.data.inputPath??e.data.path??e.files[0]?.path??e.errors[0]?.path}c(Yo,"resultPath");function Zn(e,t){let n=e.details,r=Jn(t,n?.results??[],n?.callIdsByResult??[]),o=Jn(t,n?.displayResults??n?.results??[],n?.callIdsByDisplayResult??n?.callIdsByResult??[]);return new Map(t.map(s=>{let i=Qn(r.get(s.id)??[]),a=Qn(o.get(s.id)??[]);return[s.id,{content:i.length===0?[{type:"text",text:"Batch edit applied; the final file result is in the last successful tool call for that file."}]:[new X(i).toTextContent()],details:{results:a}}]}))}c(Zn,"splitTextBatchResult");function Jn(e,t,n){let r=new Map(e.map(o=>[o.id,[]]));for(let[o,s]of t.entries()){let i=n[o];i!==void 0&&r.get(i)?.push(s)}return r}c(Jn,"groupResultsByCall");function Qn(e){let t=new Map,n=[];for(let o of e){let s=Yo(o);if(s===void 0||!o.ok){n.push(o);continue}let i=t.get(s)??[];i.push(o),t.set(s,i)}return[...[...t].map(([o,s])=>Jo(o,s)),...n]}c(Qn,"coalesceResults");function Jo(e,t){let n=S(t[0]),r=S(t.at(-1)),o=n.beforeContentMap?.[e],s=r.data.afterContent;if(t.length===1||typeof o!="string"||typeof s!="string")return r;let i=qe(e,o,s),a=n.files.find(l=>l.path===e),d=r.files.find(l=>l.path===e);return new ee({...r.data,diffs:[i.diff],files:[a??d??{path:e,action:"edited"}],editCount:t.reduce((l,u)=>l+(u.editCount??0),0),addedLines:i.stats.added,removedLines:i.stats.removed,beforeContentMap:{...r.beforeContentMap,[e]:o},afterContent:s,afterDocument:r.data.afterDocument,warnings:t.flatMap(l=>l.warnings),hints:t.flatMap(l=>l.hints)})}c(Jo,"mergePathResults");var J=class extends Error{constructor(n,r,o,s,i){super(i.message,{cause:i});this.toolName=n;this.field=r;this.source=o;this.anchor=s;this.resolution=i}static{c(this,"TextMutationAnchorResolutionError")}},ae=class extends AggregateError{constructor(n){super(n,`${n.length} text anchors could not resolve`);this.failures=n}static{c(this,"TextMutationAnchorAggregateError")}};function Me(e,t,n,r,o){return e instanceof N?new J(t,n,r,o,e):e}c(Me,"contextualizeTextMutationAnchorError");import Qo from"node:path";import{AsyncLocalStorage as Zo}from"node:async_hooks";import{Value as Da}from"typebox/value";import{defineTool as ei}from"@earendil-works/pi-coding-agent";function er(e,t){return e===void 0||typeof t.path!="string"||t.path.length===0||t.path.startsWith("SEARCH#")||["start","end","targetStart","targetEnd"].some(n=>n in t)?!1:e==="delete"||typeof t.target=="string"&&t.target.length>0}c(er,"isWholeFileInvocation");async function tr(e,t,n,r,o){let s=await e.enqueueFileOperation(()=>En(t,n,o.cwd,r),r),i;if(s.ok&&s.target!==void 0)try{await e.postProcessFile(s.target,{cwd:o.cwd,signal:r})}catch(a){i=a instanceof Error?a.message:String(a)}return{content:[{type:"text",text:[`${t}: ${s.effect}`,s.path,s.target===void 0?void 0:`Target: ${s.target}`,i===void 0?void 0:`Post-processing failed: ${i}`,s.error===void 0?void 0:`${s.error.code}: ${s.error.message}`].filter(a=>a!==void 0).join(`
35
+ `)}],details:{results:[],metadata:{semanticAction:{...s,...i===void 0?{}:{postProcessingError:i},source:s.path}}}}}c(tr,"executeWholeFileTool");function ir(e,t,n,r){let o=e.getToolRenderer(t.name),s=o?.renderCall,i=o?.renderResult,a=vt(ei({name:t.name,label:t.name,promptSnippet:t.promptSnippet,promptGuidelines:t.promptGuidelines===void 0?void 0:[...t.promptGuidelines],description:t.description,parameters:t.parameters,prepareArguments:c(d=>ti(t.parameters,d,t.source.inherited?t.source.field:void 0,r(),t.anchors??[],t.wholeFileOperation!==void 0),"prepareArguments"),...o?.renderShell!==void 0&&{renderShell:o.renderShell},...s!==void 0&&{renderCall:c((...d)=>(e.getToolRenderer(t.name)?.renderCall??s)(...d),"renderCall")},...i!==void 0&&{renderResult:c((...d)=>(e.getToolRenderer(t.name)?.renderResult??i)(...d),"renderResult")},async execute(d,l,u,p,h){let f=l;if(t.direct?.matches(f)===!0)try{let y=await t.direct.execute({cwd:h.cwd,...u!==void 0&&{signal:u}},f);return{content:[{type:"text",text:y.summary}],details:{results:[],metadata:{semanticAction:{...y.data,source:y.source}}}}}catch(y){let w=y!==null&&typeof y=="object"&&"code"in y?String(y.code):"DIRECT_MUTATION_FAILED";return ce("transaction"in f?String(f.transaction):"",w,y instanceof Error?y.message:String(y),"not-applied")}return er(t.wholeFileOperation,f)?tr(e,t.wholeFileOperation,f,u,h):ur(d,c(()=>si(e,t,f,u,h,(y,w)=>n.resolveArguments(d,{[Se]:{[y]:w}}),r()),"directExecute"),u,p,h)}}),n);return Object.defineProperty(a,"description",{enumerable:!0,get(){return[t.description,t.source.inherited?t.wholeFileOperation===void 0?`When ${t.source.field} is omitted, the tool can reuse the file identified by the supplied anchor, the last read, or the preceding edit in the same batch.`:`When ${t.source.field} is omitted, the tool can reuse the file identified by a supplied text anchor.`:""].filter(Boolean).join(`
36
+ `)}}),a}c(ir,"createTextTool");function ti(e,t,n,r,o,s){let i=t!==null&&typeof t=="object"&&!Array.isArray(t)?{...t}:{},a=e.required,d=e.properties,l=o.some(u=>fe(u,i[u.field]));if(n!==void 0&&!(n in i)&&r!==void 0&&!l&&!s&&(i[n]=r),Array.isArray(a))for(let u of a)typeof u=="string"&&!(u in i)&&d?.[u]?.type==="string"&&(i[u]="");return i}c(ti,"prepareGuardedArguments");async function sr(e,t,n,r,o){let s=new Map,i=new Map,a=new Set,d=new Map,l=new Set,u=[...new Set((t.anchors??[]).flatMap(g=>g.kinds))],p=c(async(g,x,R)=>{try{return await e.resolveTextAnchorResources(g,u,r)}catch(E){throw Me(E,t.name,x,R,g)}},"resolveTargets");for(let g of t.anchors??[]){let x=n[g.field];if(!fe(g,x))continue;let R=await p(x,g.field,typeof n[g.sourceField]=="string"?String(n[g.sourceField]):"");if(R===void 0)continue;s.set(g.field,R);let E=i.get(g.sourceField);if(E!==void 0&&!ni(E,R))throw new Error(`Incompatible targets for ${g.sourceField}.`);i.set(g.sourceField,Lt(i.get(g.sourceField)??[],R))}for(let g of[t.source,...t.source.targets??[]]){let x=n[g.field];if(typeof x!="string"||x.length===0)continue;let R=await p(x,g.field,x);R!==void 0&&(a.add(g.field),d.set(g.field,R),i.set(g.field,Lt(i.get(g.field)??[],R)))}let h=new Map,f=[t.source,...t.source.targets??[]];for(let g of f){let x=n[g.field],R=typeof x=="string"&&x.length>0?x:void 0,E="fallbackTo"in g?h.get(g.fallbackTo):void 0,v=i.get(g.field);if(v!==void 0){if(R!==void 0&&!a.has(g.field)){let M=v.filter(T=>cr(R,T.source,r.cwd));if(M.length===0)throw new Error(`Anchor does not belong to ${R}.`);M.length!==v.length&&(v=M,i.set(g.field,M),l.add(g.field))}h.set(g.field,S(v[0]).source);continue}let I=g.field===t.source.field&&t.source.inherited===!0&&!(g.field in n)?o:void 0,A=R??E??I;if(A===void 0)throw new Error(`${g.field} is required`);h.set(g.field,A)}let m=new Map,y=new Map;for(let g of t.anchors??[]){let x=d.get(g.sourceField),R=t.anchors?.find(I=>I.sourceField===g.sourceField),E=fe(g,n[g.field]),v=a.has(g.sourceField);!E&&!v||x!==void 0&&v&&g.field===R?.field&&y.set(g.field,x)}for(let g of t.anchors??[]){let x=s.get(g.field),R=n[g.field];if(typeof R=="string"&&!fe(g,R))continue;let E=h.get(g.sourceField);if(x!==void 0)m.set(g.field,E!==void 0&&(x.length===1||l.has(g.sourceField))?[E]:[...new Set(x.map(v=>v.source))]);else if(E!==void 0){let v=i.get(g.sourceField),I=n[g.field];m.set(g.field,v!==void 0&&typeof I=="string"&&I.length>0?[...new Set(v.map(A=>A.source))]:[E])}}let w=[...i.values()].flat().reduce((g,x)=>Lt(g,[x]),[]);return{fields:h,anchors:m,implicitTargets:y,targets:w,resources:[...new Set([...h.values(),...w.map(g=>g.source)])]}}c(sr,"resolveMutationSources");function ni(e,t){let n=new Set(e.map(o=>o.source)),r=new Set(t.map(o=>o.source));return n.size===r.size&&[...n].every(o=>r.has(o))}c(ni,"sameTargetSources");function Lt(e,t){let n=new Map;for(let r of[...e,...t]){let o=n.get(r.source);if(o===void 0){n.set(r.source,r);continue}if(o.expectedContent!==void 0&&r.expectedContent!==void 0&&o.expectedContent!==r.expectedContent)throw new Error("Selections refer to different source revisions. Read the source again.");let s=[...o.ranges??[],...r.ranges??[]];n.set(r.source,{source:r.source,expectedContent:r.expectedContent??o.expectedContent,...s.length>0&&{ranges:ar(s)}})}return[...n.values()]}c(Lt,"mergeTargets");function ar(e){let t=new Map;for(let n of e){let r=JSON.stringify({start:n.start,end:n.end}),o=t.get(r);t.set(r,{...n,...o?.linewise===!0||n.linewise===!0?{linewise:!0}:{}})}return[...t.values()]}c(ar,"deduplicateRanges");function ri(e,t){let n=e.split(/\r\n|\r|\n/u),r=n[t-1];if(r===void 0)throw new Error(`Position anchor line ${t} is outside the source.`);let o=t<n.length;return{start:{lineNumber:t,column:0},end:o?{lineNumber:t+1,column:0}:{lineNumber:t,column:r.length},linewise:!0}}c(ri,"naturalLineSelection");function oi(e,t,n,r){let o=new Set([...n.keys(),...r.keys()]);return new Map([...o].map(s=>{let i=n.get(s),a=r.get(s);if(i===void 0)return[s,S(a)];if(a===void 0)return[s,i];let l=[...(V.is(i)?i:new V(t,s,[ri(e(s).content,i.lineNumber)])).ranges,...a.ranges].sort((p,h)=>p.start.lineNumber-h.start.lineNumber||p.start.column-h.start.column),u=ar(l);for(let p=1;p<u.length;p++){let h=S(u[p-1]),f=S(u[p]);if(f.start.lineNumber<h.end.lineNumber||f.start.lineNumber===h.end.lineNumber&&f.start.column<h.end.column)throw new Error(`Anchor ${t} selections overlap or are ambiguous.`)}return[s,new V(t,s,u)]}))}c(oi,"mergeResolvedAnchors");function Ft(e,t,n,r,o,s,i){let a=new Map([...o].map(([f,m])=>[f,new me(m)])),d=new Map,l=new Set,u=c(f=>{let m=r.fields.get(f);if(m===void 0)throw new Error(`Unknown mutation source field ${f}`);return m},"sourceFor"),p=c(f=>{let m=a.get(f);if(m===void 0)throw new Error(`Unknown mutation resource ${f}`);return m},"documentFor"),h=c(f=>{let m=d.get(f);if(m!==void 0)return m;let y=(async()=>{let w=(e.anchors??[]).find(v=>v.field===f),g=t[f],x=r.anchors.get(f),R=r.implicitTargets.get(f);if(w===void 0)throw new Error(`Mutation tool ${e.name} tried to resolve undeclared anchor ${f}`);let E=typeof g=="string"&&x!==void 0?new Map(await Promise.all(x.map(async v=>{try{let I=await s(v,g,w.kinds);Qe(I)==="major"&&l.add(v);let A=De(I,g,{source:v,anchor:I});return i?.(f,{kind:"resolved",full:A.full,compact:A.compact,resolverId:A.resolverId}),[v,I]}catch(I){throw i?.(f,{kind:"failed"}),Me(I,e.name,f,v,g)}}))):void 0;if(R!==void 0){let v=new Map(R.map(I=>[I.source,new V(f,I.source,I.ranges??[])]));return E===void 0?v:oi(p,f,E,v)}if(E===void 0)throw new Error(`Mutation tool ${e.name} tried to resolve undeclared anchor ${f}`);return E})();return d.set(f,y),y},"resolveAnchors");return{cwd:n.cwd,...n.signal!==void 0&&{signal:n.signal},sourceDocument:p(u(e.source.field)),sourceFor:u,documentFor:p,targetDocument(f){if((e.source.targets??[]).every(m=>m.field!==f))throw new Error(`Mutation tool ${e.name} tried to access undeclared target ${f}`);return p(u(f))},resolveAnchors:h,async resolveAnchor(f){let m=await h(f);if(m.size!==1)throw new Error(`Anchor ${f} selects multiple resources; use an operation that supports a search set.`);return S(m.values().next().value)},resultPresentationFor(f){return[...l].some(m=>cr(m,f,n.cwd))?"major-anchor":"plain"}}}c(Ft,"createMutationContext");function nr(e,t){return{...e,resultPresentations:new Map([...e.edits.keys()].map(n=>[n,t.resultPresentationFor(n)]))}}c(nr,"withResultPresentations");var ii=new Set(["replace","delete","insert","copy","move"]);async function Ie(e,t,n){if(!ii.has(e.name))return;let r=[];if(await Promise.all((e.anchors??[]).map(async o=>{if(fe(o,t[o.field]))try{await n.resolveAnchors(o.field)}catch(s){if(s instanceof J){r.push(s);return}throw s}})),r.length>0)throw new ae(r)}c(Ie,"preflightMutationAnchors");function cr(e,t,n){return rr(e,n)===rr(t,n)}c(cr,"sameResource");function rr(e,t){if(/^[a-z][a-z\d+.-]*:\/\//iu.test(e))return e;let n=e.startsWith("@")?e.slice(1):e;return Qo.resolve(t,n)}c(rr,"resourceIdentity");async function dr(e,t){let n=e.getMutationTools().find(r=>r.name===t.tool);if(n===void 0)return{kind:"failed",reason:`Unknown mutation tool ${t.tool}`};try{let r=await sr(e,n,t.input,t),o=e.getSemanticMutationHandler(n.name,t.input);return await e.previewTexts(r.resources.map(s=>({source:s,read:!0,...o===void 0?n.name==="write"&&{allowReadFailure:!0}:{requireWrite:!1}})),{cwd:t.cwd,...t.signal!==void 0&&{signal:t.signal}},async(s,i)=>{let a=Ft(n,t.input,t,r,s,i);if(await Ie(n,t.input,a),o!==void 0)return{changes:new Map,result:{edits:new Map}};let d=await n.mutate(a,t.input);return{changes:new Map([...d.edits].map(([l,u])=>[l,u.changes])),result:d}})}catch(r){return{kind:"failed",reason:r instanceof Error?r.message:String(r)}}}c(dr,"previewTextMutation");async function si(e,t,n,r,o,s,i){let a=await ai(e,t,n,r,o,s,i),d=await ci(e,a.pipeline,a.source,o,t.name);return a.pipeline.kind==="completed"&&a.pipeline.state.metadata!==void 0?{...d,details:{...d.details,metadata:a.pipeline.state.metadata}}:d}c(si,"executeTextMutation");async function ai(e,t,n,r,o,s,i){let a=Ke(t,n);return{pipeline:await e.executeEdit(t.name,{cwd:o.cwd,input:n,...r!==void 0&&{signal:r}},async l=>{try{if(l.editPlan!==void 0){let f=l.editPlan;if(f.files.length===0||new Set(f.files.map(y=>y.source)).size!==f.files.length)throw new Error("Semantic edit plan must contain distinct source files.");let m=await e.editTexts(f.files.map(y=>({source:y.source,read:!0})),{cwd:l.cwd,intent:t.intent??"edit",...l.signal!==void 0&&{signal:l.signal}},y=>{for(let g of f.files)if(y.get(g.source)!==g.expectedContent)throw new Error("A semantic edit source changed. Resolve the symbol again before retrying.");let w=new Map(f.files.map(g=>[g.source,{changes:g.changes,action:"edited"}]));return Promise.resolve({changes:new Map(f.files.map(g=>[g.source,g.changes])),result:{edits:w,resultPresentations:new Map(f.files.map(g=>[g.source,"plain"]))}})});return await or(m,S(f.files[0]).source)}let u=await sr(e,t,l.input,l,i),p=e.getSemanticMutationHandler(t.name,l.input);if(p!==void 0)return await e.editTexts(u.resources.map(f=>({source:f,read:!0,requireWrite:!1})),{cwd:l.cwd,intent:t.intent??"edit",...l.signal!==void 0&&{signal:l.signal}},async(f,m)=>{for(let g of u.targets)if(g.expectedContent!==void 0&&f.get(g.source)!==g.expectedContent)throw new Error("The selected source changed before the semantic action. Resolve it again.");let y=Ft(t,l.input,l,u,f,m,s);await Ie(t,l.input,y);let w=await p.execute(y,l.input);return{changes:new Map,result:nr({edits:new Map,semanticAction:w},y),resourceEffect:!0}});let h=await e.editTexts(u.resources.map(f=>({source:f,read:!0,...t.name==="write"&&{allowReadFailure:!0}})),{cwd:l.cwd,intent:t.intent??"edit",...l.signal!==void 0&&{signal:l.signal}},async(f,m)=>{for(let x of u.targets)if(x.expectedContent!==void 0&&f.get(x.source)!==x.expectedContent)throw new Error("The selected source changed before editing. Resolve the symbol again.");let y=Ft(t,l.input,l,u,f,m,s);await Ie(t,l.input,y);let w=await t.mutate(y,l.input),g=nr(w,y);return{changes:new Map([...w.edits].map(([x,R])=>[x,R.changes])),result:g}});return await or(h,Ke(t,l.input))}catch(u){return fi(Ke(t,l.input),"INVALID_REQUEST",mi(u),u)}}),source:a}}c(ai,"executeTextMutationPipeline");var ec=new Zo;function lr(e,t){let n=new Map,r=t[e.source.field];if(typeof r!="string"||r.length===0)throw new Error(`${e.source.field} is required`);n.set(e.source.field,r);for(let o of e.source.targets??[]){let s=t[o.field],i=n.get(o.fallbackTo),a=typeof s=="string"&&s.length>0?s:i;if(a===void 0)throw new Error(`${o.field} is required`);n.set(o.field,a)}return n}c(lr,"mutationSources");function tt(e,t,n,r=e.after.content,o="plain",s=1,i=[],a){let d=e.before.content,l=e.after.content,u=U(d,n.changes,d.length===0),p=qe(t,d,r),h=e.postEditContributions.map(m=>m.data).find(fn),f=u.changes.map((m,y)=>({editIndex:y,fromA:m.fromBefore,toA:m.toBefore,fromB:m.fromAfter,toB:m.toAfter,removedText:m.removedText,insertedText:m.insertedText}));return new ee({...h,...a===void 0?{}:{diffPeerRanges:a},operations:i,diffStatuses:e.postEditContributions.map(m=>m.data).filter(be).flatMap(m=>m.diffStatuses),formatting:e.postEditContributions.map(m=>m.data).findLast(We)?.formatting??{status:"not-reported"},ok:!0,path:t,diffs:[p.diff],files:[{path:t,action:n.action}],editCount:s,addedLines:p.stats.added,removedLines:p.stats.removed,beforeContentMap:{[t]:d},afterContent:l,rawChanges:f,afterDocument:e.after,resultPresentation:o})}c(tt,"buildSuccessfulTextMutationResult");async function or(e,t){if(e.kind==="failed"||e.result.afterWrite===void 0)return e;try{return await e.result.afterWrite(),e}catch(n){return{kind:"failed",failure:{code:"POST_WRITE_FAILED",source:t,message:`Post-write action failed for ${t}`,cause:n},completed:e.resources.map(r=>r.source)}}}c(or,"completeTextMutation");async function ci(e,t,n,r,o){if(t.kind==="failed")return ce(n,t.failure.code,t.failure.message,"not-applied");let s=t.state.result;if(!gi(s))return ce(n,"INVALID_RESULT","Text editor returned an invalid edit result.","unknown");if(s.kind==="failed"){let l=await Nt(e,s.failure,r);if(l!==void 0)return l;let u=s.completed.length===0?"":` Completed writes: ${s.completed.join(", ")}.`,p=s.completed.length===0?"not-applied":"applied",h=`${s.failure.message.replace(/[.!?]+$/u,"")}.${u}`;return ce(n,s.failure.code,h,p)}let i=s.result;if(i.semanticAction!==void 0)return{content:[{type:"text",text:i.semanticAction.summary}],details:{results:[],metadata:{semanticAction:{...i.semanticAction.data,source:i.semanticAction.source}}}};let d=s.resources.flatMap(l=>{let u=l.source,p=i.edits.get(u);return p===void 0?[]:[tt(l,u,p,void 0,i.resultPresentations.get(u)??"plain",1,[{operation:o,changes:p.changes.length}])]}).map(l=>di(l,t.state.metadata));return{content:[new X(d).toTextContent()],details:{results:d}}}c(ci,"buildToolResult");function di(e,t){return be(t)?new ee({...e.data,diffStatuses:[...e.data.diffStatuses??[],...t.diffStatuses]}):e}c(di,"withPipelineStatuses");async function li(e){return e.resolution.recovery===void 0&&await e.resolution.refreshRecovery(),e.resolution.recovery}c(li,"resolveAnchorRecovery");async function Nt(e,t,n){if(t.cause instanceof ae){let f=await Promise.all(t.cause.failures.map(g=>Nt(e,{...t,source:g.source,cause:g},n))),m=[],y=[],w=[];for(let g of f)if(g!==void 0){m.push(...g.details.results??[]),y.push(...g.details.anchorRecoveries??[]);for(let x of g.content)x.type==="text"&&w.push(x.text)}return m.length===0?void 0:{content:[{type:"text",text:w.join(`
37
+
38
+ `)}],details:{results:m,anchorRecoveries:y}}}if(!(t.cause instanceof J))return;let r=t.cause,o=r.resolution,s=await li(r);if(s?.kind==="timed-out")return ce(r.source,t.code,`${t.message}; recovery timed out`,"not-applied");let i=s?.kind==="candidates"?pi(s.candidates.map(({range:f})=>f),e.recoveryContextLines()):o.rejection?.contextRange===void 0?[]:[o.rejection.contextRange];if(i.length===0)return;let a=await Promise.all(i.map(f=>In(e,{path:r.source,...f},{cwd:n.cwd,...n.signal!==void 0&&{signal:n.signal}}))),d=[];for(let f of a){if(f===void 0||f.isError===!0)return;d.push(...f.content.filter(m=>m.type==="text").map(m=>m.text))}let l=new ee({ok:!1,path:r.source,errors:[{path:r.source,code:t.code,reason:t.message}]}),u=d.join(`
39
+ `),p=o.rejection?.code;return{content:[{type:"text",text:p==="stale"?Cn({guardId:"stale-anchor",effect:"not-applied",toolName:r.toolName,field:r.field,path:r.source,anchor:r.anchor,...u.length>0&&{context:u}},o.message):ui(r,p,o.message,u)}],details:{results:[l],effect:"not-applied",anchorRecovery:!0,...s?.kind==="candidates"&&{anchorRecoveries:[{field:r.field,path:r.source,anchor:r.anchor,total:s.total,candidates:s.candidates}]}}}}c(Nt,"anchorFailureToolResult");function ui(e,t,n,r){let o=t==="ambiguous"?"is ambiguous":t==="missing"?"was not found":t==="invalid"?"is invalid":"could not be resolved",s=t==="ambiguous"?"Use a unique text span or one of the candidate anchors below.":"If the intended text is represented below, use its candidate anchor. Otherwise, reread the relevant section and choose a current anchor.",i=r.length===0?"":`
40
+
41
+ ${r}`;return`[SYSTEM] ${e.toolName} blocked: ${e.field} anchor "${e.anchor}" ${o}. ${s} (${n})${i}`}c(ui,"formatRejectedAnchorMessage");function pi(e,t){let n=e.map(o=>({offset:Math.max(1,o.start.lineNumber-t),limit:o.end.lineNumber-o.start.lineNumber+1+t*2})).sort((o,s)=>o.offset-s.offset),r=[];for(let o of n){let s=r[r.length-1];if(s===void 0||o.offset>s.offset+s.limit){r.push(o);continue}let i=Math.max(s.offset+s.limit,o.offset+o.limit);r[r.length-1]={offset:s.offset,limit:i-s.offset}}return r}c(pi,"recoveryWindows");async function Oe(e,t,n,r="not-applied"){return r==="not-applied"?await Nt(e,t,n)??ce(t.source,t.code,t.message,r):ce(t.source,t.code,t.message,r)}c(Oe,"buildFailedTextMutationResult");function ce(e,t,n,r){let o=new ee({ok:!1,path:e,errors:[{path:e,code:t,reason:n}]});return{content:[new X(o).toTextContent()],details:{results:[o],effect:r}}}c(ce,"failureToolResult");function fi(e,t,n,r){return{kind:"failed",failure:{code:t,source:e,message:n,...r!==void 0&&{cause:r}},completed:[]}}c(fi,"failedResourceEdit");function gi(e){return typeof e=="object"&&e!==null&&(e.kind==="completed"||e.kind==="failed")}c(gi,"isResourcesEditOutcome");function mi(e){return e instanceof Error?e.message:String(e)}c(mi,"errorMessage");var fr=new WeakMap;function gr(e,t){fr.set(e,t)}c(gr,"setTextEditBatchRenderArgumentSink");function mr(e,t){let n=[],r=new Map,o=c((i,a)=>fr.get(t)?.(i,a),"renderArguments"),s={sourceTools:n,syntheticTool:"__pi_agent_text_editor_batch",resolveCall(i,a){let d=r.get(i.name);if(d===void 0||[d.source.field,...(d.source.targets??[]).map(f=>f.field),...(d.anchors??[]).map(f=>f.field)].some(f=>{let m=i.arguments[f];return typeof m=="string"&&/^[a-z][a-z\d+.-]+:/iu.test(m)&&!m.startsWith("file://")}))return;let u=i.arguments[d.source.field],p=!(typeof u=="string"&&u.length>0)&&d.source.inherited?a?.source:void 0,h=typeof u=="string"&&u.length>0?u:p;return h===void 0?void 0:{call:i,state:{source:h,registration:d},...p!==void 0&&{renderArgumentPatch:{[d.source.field]:p}}}},buildArguments(i){return{edits:i.map(({call:d,state:l})=>({...d.arguments,[l.registration.source.field]:l.source,callId:d.id,op:l.registration.name,path:l.source}))}},execute:c((i,a,d,l,u,p)=>hi(t,r,a,d,l,u,p,o),"execute"),splitResult:Zn,onRenderArguments:o};t.onMutationTool(i=>{r.set(i.name,i),n.push(i.name)}),xn(e,Xn),Yn(e,s)}c(mr,"registerTextEditBatching");async function hi(e,t,n,r,o,s,i,a){let d=n.edits.map(A=>{let M=t.get(A.op);if(M===void 0)throw new Error(`Unknown text mutation tool: ${A.op}.`);let{callId:T,op:k,...P}=A;return{callId:T,input:P,registration:M,sources:lr(M,P)}}),l=new Set(d.map(({registration:A})=>A.intent??"edit")),u=l.size>1?"mixed":l.values().next().value??"edit",p=new Map;for(let A of d){for(let M of A.sources.values()){let T=p.get(M),k=A.registration.name==="write"&&M===A.sources.get(A.registration.source.field);p.set(M,{source:M,read:!0,...(T?.allowReadFailure===!0||k)&&{allowReadFailure:!0}})}i.start(A.callId)}let h;try{h=await e.editTexts([...p.values()],{cwd:s.cwd,intent:u,...r!==void 0&&{signal:r}},async(A,M)=>{let T=[],k=[],P=new Map;if(n.expectedContent!==void 0)for(let[C,O]of n.expectedContent){if(!A.has(C))throw new Error(`Snapshot source ${C} is not part of this edit batch.`);if(A.get(C)!==O)throw new Error(`Snapshot source ${C} changed before the edit batch.`)}for(let C of d){let O=c(F=>{let j=C.sources.get(F);if(j===void 0)throw new Error(`Unknown mutation source field ${F}`);return j},"sourceFor"),b=c(F=>{let j=A.get(F);if(j===void 0)throw new Error(`Unknown mutation resource ${F}`);return new me(j)},"documentFor"),$=new Set,L=c((F,j)=>{a(C.callId,{[Se]:{[F]:j}})},"publishAnchorRenderPatch"),K=c(async F=>{let j=(C.registration.anchors??[]).find(Y=>Y.field===F),H=C.input[F],G=j===void 0?void 0:C.sources.get(j.sourceField);if(j===void 0||typeof H!="string"||G===void 0)throw L(F,{kind:"failed"}),new Error(`Unable to resolve mutation anchor ${F}`);try{let Y=await M(G,H,j.kinds);Qe(Y)==="major"&&$.add(G);let ve=De(Y,H,{source:G,anchor:Y});return L(F,{kind:"resolved",full:ve.full,compact:ve.compact,resolverId:ve.resolverId}),new Map([[G,Y]])}catch(Y){throw L(F,{kind:"failed"}),Me(Y,C.registration.name,F,G,H)}},"resolveAnchors");try{let F={cwd:s.cwd,...r!==void 0&&{signal:r},sourceDocument:b(O(C.registration.source.field)),sourceFor:O,documentFor:b,targetDocument:c(H=>b(O(H)),"targetDocument"),resolveAnchors:K,async resolveAnchor(H){let G=await K(H);return S(G.values().next().value)}};await Ie(C.registration,C.input,F);let j=await C.registration.mutate(F,C.input);for(let[H,G]of j.edits){let Y=P.get(H)??[];if(G.changes.some(ve=>Y.some(Ro=>xi(Ro,ve))))throw new Error(`Text mutation ${C.callId} overlaps an earlier successful mutation.`)}T.push({callId:C.callId,mutation:{...j,operation:C.registration.name,resultPresentations:new Map([...j.edits.keys()].map(H=>[H,$.has(H)?"major-anchor":"plain"]))}});for(let[H,G]of j.edits)P.set(H,[...P.get(H)??[],...G.changes])}catch(F){if(n.failureMode==="abort")throw F;k.push({callId:C.callId,source:C.sources.get(C.registration.source.field)??"",error:F,effect:"not-applied"})}}return{changes:P,result:{mutations:T,failures:k}}})}catch(A){return pr(e,d.map(({callId:M})=>M),A,s,i)}if(h.kind==="failed")return pr(e,d.map(({callId:A})=>A),h.failure,s,i);let f=[],m=[...h.result.failures];for(let A of h.result.mutations)try{await A.mutation.afterWrite?.(),f.push(A)}catch(M){m.push({callId:A.callId,source:A.mutation.edits.keys().next().value??"",error:M,effect:"applied"})}let y=[],w=[],g=[],x=[],R=new Map,E=new Map,v=new Map,I=new Map;for(let{callId:A,mutation:M}of f){v.set(A,[]);let T=[...M.edits].flatMap(([k,P])=>{let C=h.resources.find(b=>b.source===k);if(C===void 0)return[];let O=U(C.before.content,P.changes).content;return[tt(C,k,P,O,M.resultPresentations.get(k)??"plain",1,[{operation:M.operation,changes:P.changes.length}],f.flatMap(b=>b.callId===A?[]:(b.mutation.edits.get(k)?.changes??[]).map(({from:$,to:L,insert:K})=>({from:$,to:L,insert:K}))))]});I.set(A,T),g.push(...T),x.push(...T.map(()=>A));for(let k of M.edits.keys())R.set(k,A),E.set(k,M.resultPresentations.get(k)??"plain")}for(let[A,M]of R){let T=h.resources.find(C=>C.source===A),k=h.result.mutations.flatMap(({mutation:C})=>{let O=C.edits.get(A);return O===void 0?[]:[O]});if(T===void 0||k.length===0)continue;let P=tt(T,A,{changes:k.flatMap(C=>C.changes),action:k.some(C=>C.action==="overwritten")?"overwritten":"edited"},T.after.content,E.get(A)??"plain",k.length,f.flatMap(({mutation:C})=>{let O=C.edits.get(A);return O===void 0?[]:[{operation:C.operation,changes:O.changes.length}]}));v.get(M)?.push(P),y.push(P),w.push(M)}for(let{callId:A}of f){let M=v.get(A)??[],T=I.get(A)??[];i.complete(A,Dt(M,M.map(()=>A),T,T.map(()=>A)))}for(let A of m){let M=A.error instanceof ae?A.error.failures:A.error instanceof J?[A.error]:[];for(let P of M){let C=h.resources.find(({source:O})=>O===P.source);C!==void 0&&await P.resolution.refreshRecovery({source:C.source,content:C.after.content,lines:C.after.lines.map(({content:O})=>O),cwd:s.cwd,...r!==void 0&&{signal:r}})}let T=await Oe(e,{code:A.effect==="applied"?"POST_WRITE_FAILED":"INVALID_REQUEST",source:A.source,message:hr(A.error),cause:A.error},s,A.effect),k=T.details.results??[];i.fail(A.callId,{error:A.error,effect:A.effect,result:T}),y.push(...k),w.push(...k.map(()=>A.callId)),g.push(...k),x.push(...k.map(()=>A.callId))}return o?.({content:[{type:"text",text:"post-edit progress"}],details:{results:[...y],callIdsByResult:[...w],displayResults:[...g],callIdsByDisplayResult:[...x]}}),Dt(y,w,g,x)}c(hi,"executeRegisteredTextBatch");async function pr(e,t,n,r,o){let s=n,i=yi(n)?n:{code:"INVALID_REQUEST",source:"",message:hr(s),cause:s},a=t[0],d=await Oe(e,i,r);for(let u of t)o.fail(u,{error:s,effect:"not-applied",...u===a&&{result:d}});let l=d.details.results??[];return Dt(l,l.map(()=>a??""))}c(pr,"failTextBatch");function yi(e){return typeof e=="object"&&e!==null&&typeof e.code=="string"&&typeof e.source=="string"&&typeof e.message=="string"}c(yi,"isTextResourceEditFailure");function xi(e,t){return e.from===e.to&&t.from===t.to?!1:e.from===e.to?e.from>t.from&&e.from<t.to:t.from===t.to?t.from>e.from&&t.from<e.to:e.from<t.to&&t.from<e.to}c(xi,"textChangesConflict");function hr(e){return e instanceof Error?e.message:String(e)}c(hr,"errorMessage");function Dt(e,t,n=e,r=t){return{content:[new X(e).toTextContent()],details:{results:e,callIdsByResult:t,displayResults:n,callIdsByDisplayResult:r}}}c(Dt,"textBatchResult");function ur(e,t,n,r,o){return Kn(e,t,n,r,o)}c(ur,"executeTextToolWithBatch");import{lstat as Ii,readFile as br}from"node:fs/promises";import Sr from"node:path";import{readFileSync as Ti}from"node:fs";import Ri from"node:path";function Tr(e){let t=Ri.join(e,".pi","pi-agent-ide","text-editor.json"),n;try{n=JSON.parse(Ti(t,"utf8"))}catch(i){if(Ei(i))return{contextLines:15,timeoutMs:2e3,sections:{}};throw new Error(`Invalid text editor config at ${t}`,{cause:i})}let r=yr(n,"text editor config");if(wi(r,["recovery"],"text editor config"),r.recovery===void 0)return{contextLines:15,timeoutMs:2e3,sections:{}};let o=yr(r.recovery,"recovery"),s=Object.fromEntries(Object.entries(o).filter(([i])=>i!=="contextLines"&&i!=="timeoutMs"));return{contextLines:xr(o.contextLines,"contextLines",0,20,15),timeoutMs:xr(o.timeoutMs,"timeoutMs",1,1e4,2e3),sections:s}}c(Tr,"loadTextEditorConfig");function Rr(e,t){if(t.length===0)throw new TypeError("Recovery config section name must be non-empty");return{contextLines:e.contextLines,timeoutMs:e.timeoutMs,settings:e.sections[t]}}c(Rr,"recoverySection");function yr(e,t){if(typeof e!="object"||e===null||Array.isArray(e))throw new TypeError(`${t} must be an object`);return Object.fromEntries(Object.entries(e))}c(yr,"record");function wi(e,t,n){let r=Object.keys(e).find(o=>!t.includes(o));if(r!==void 0)throw new TypeError(`${n} contains unknown key ${r}`)}c(wi,"assertKeys");function xr(e,t,n,r,o){if(e===void 0)return o;if(!Number.isInteger(e)||typeof e!="number"||e<n||e>r)throw new RangeError(`${t} must be an integer between ${n} and ${r}`);return e}c(xr,"integer");function Ei(e){return typeof e=="object"&&e!==null&&"code"in e&&e.code==="ENOENT"}c(Ei,"isMissingFile");import{createHash as vr,randomBytes as vi}from"node:crypto";import{lstat as Ai,mkdir as bi,readFile as Si,rm as Ci,writeFile as ki}from"node:fs/promises";import $e from"node:path";var rt=class{static{c(this,"ApplyUndoStore")}#e=new Map;#t;constructor(t=Pi){this.#t=t}async record(t){let n=new Set(t.map(s=>$e.normalize(s.path)));this.invalidate(n);let r=await Promise.all(t.map(async s=>({...s,after:await Er(s.path)}))),o=`APPLY#${vi(6).toString("hex").toUpperCase()}`;return this.#e.set(o,{paths:r}),o}observeTextChange(t,n,r,o){let s=$e.normalize(t);if(o==="final"){let i=wr(n);for(let a of this.#e.values()){let d=a.paths.find(l=>$e.normalize(l.path)===s);d?.after===i&&(d.after=wr(r))}return}this.invalidate(new Set([s]))}invalidate(t){for(let[n,r]of this.#e)r.paths.some(o=>t.has($e.normalize(o.path)))&&this.#e.delete(n)}has(t){return this.#e.has(t)}async restore(t){let n=this.#e.get(t);if(n===void 0)throw nt("APPLY_UNDO_UNAVAILABLE",`No undo receipt is available for ${t}.`);for(let o of n.paths)if(await Er(o.path)!==o.after)throw this.#e.delete(t),nt("APPLY_UNDO_STALE",`${o.path} changed after ${t}; refusing to overwrite newer content.`);let r=await Promise.all(n.paths.map(o=>Ar(o.path)));try{for(let o of n.paths)await this.#t(o)}catch(o){let s=[];for(let i of r)try{await this.#t(i)}catch(a){s.push(`${i.path}: ${a instanceof Error?a.message:String(a)}`)}throw Object.assign(nt("APPLY_UNDO_FAILED",o instanceof Error?o.message:String(o)),{rollbackErrors:s})}return this.#e.delete(t),{transaction:t,restored:n.paths.map(o=>o.path)}}};async function Ar(e){try{let t=await Ai(e);if(!t.isFile()||t.isSymbolicLink())throw nt("INVALID_FILE_TYPE",`${e} is not a regular file.`);return{path:e,existed:!0,bytes:await Si(e)}}catch(t){if(Mi(t,"ENOENT"))return{path:e,existed:!1};throw t}}c(Ar,"save");function wr(e){return`file:${vr("sha256").update(e).digest("hex")}`}c(wr,"textFingerprint");async function Er(e){let t=await Ar(e);return t.existed?`file:${vr("sha256").update(t.bytes??new Uint8Array).digest("hex")}`:"absent"}c(Er,"fingerprint");async function Pi(e){if(!e.existed){await Ci(e.path,{force:!0});return}await bi($e.dirname(e.path),{recursive:!0}),await ki(e.path,e.bytes??new Uint8Array)}c(Pi,"restoreState");function nt(e,t){return Object.assign(new Error(t),{code:e})}c(nt,"coded");function Mi(e,t){return e!==null&&typeof e=="object"&&"code"in e&&e.code===t}c(Mi,"hasCode");function Ir(e){let t=Tr(process.cwd()),n=[],r=new Je,o=[],s=[],i=[],a=new Map,d=new Set,l=new Map,u=[],p=[],h=new Set,f=new Map,m=new Set,y=new Set,w=new rt;y.add(T=>{w.observeTextChange(Sr.resolve(T.cwd,T.resourceSource),T.before.content,T.after.content,T.postProcessing??"complete")});let g=[],x=new Map,R=new Map,E=Promise.resolve(),v=Promise.resolve(),I=c((T,k)=>{let P=v.then(()=>(k?.throwIfAborted(),T()));return v=P.then(()=>{},()=>{}),P},"enqueueMutation"),A=c(T=>{_i(T,n,o,s,u,p);let k=new Set,P=new Set;for(let b of T.scriptIndexOperations??[]){if(!["stage","unstage"].includes(b.name)||typeof b.execute!="function"||R.has(b.name)||P.has(b.name))throw new Error(`Invalid or duplicate script index operation ${b.name}`);P.add(b.name)}for(let b of T.mutationTools??[]){if(Xe(b),f.has(b.name)||k.has(b.name))throw new Error(`Mutation tool ${b.name} is already registered`);k.add(b.name)}for(let b of T.toolRenderers??[])if(!Ct(b))throw new TypeError("Plugin provided an invalid text editor tool renderer");r.assertCanAdd(T.anchorResolvers.map(({registration:b})=>b));let C=T.presenters??[],O=new Set(i.map(({registration:b})=>b.presenter.id));for(let b of C){if(!yt(b.registration))throw new TypeError(`Plugin ${b.pluginId} provided an invalid text presenter`);if(O.has(b.registration.presenter.id))throw new Error(`Text presenter ${b.registration.presenter.id} is already registered`);O.add(b.registration.presenter.id)}for(let b of T.resolvers)n.push({resolver:b.registration.resolver,priority:b.registration.priority??0,order:n.length});for(let b of T.anchorResolvers)r.add(b.registration);for(let b of C)i.push({...b,order:i.length});o.push(...T.handlers),s.push(...T.semanticHandlers??[]);for(let b of T.scriptIndexOperations??[])R.set(b.name,b);g.push(...T.mutationGuards??[]),u.push(...T.promptContributions),p.push(...T.writablePromptContributions);for(let b of T.toolRenderers??[]){let $=x.get(b.tool);x.set(b.tool,zi($,b))}for(let b of T.tools)h.add(b);for(let b of T.mutationTools??[])Mr(b,f,h,m,e,M);for(let b of T.mutationToolListeners??[])Pr(b,f),m.add(b);for(let b of T.editCompletionListeners??[])y.add(b)},"registerContributions"),M={recordApplyUndo(T){return w.record(T)},restoreApplyUndo(T,k){return I(()=>w.restore(T),k)},hasApplyUndo(T){return w.has(T)},async postProcessFile(T,k){await I(async()=>{let P=Sr.resolve(k.cwd,T),C=await Ii(P).catch(()=>{});if(!C?.isFile()||C.isSymbolicLink())return;let O=await br(P),b=O.toString("utf8");O.includes(0)||!Buffer.from(b).equals(O)||await st({requestedSource:P,outcomeSource:P,resource:{source:P,async read(){return[{type:"text",text:await br(P,"utf8")}]}},resolvedBy:"filesystem",existed:!0,before:se(P,b),requestedText:b,context:k,presenters:[...i],postEditHandlers:[...a.values()],editCompletionListeners:[...y],result:void 0})},k.signal)},enqueueFileOperation:I,addAnchorResolver(T){if(!wt(T))throw new TypeError("Invalid text anchor resolver");r.add(T)},addMutationTool(T){Mr(T,f,h,m,e,M)},getMutationTools(){return[...f.values()]},onMutationTool(T){return Pr(T,f),m.add(T),()=>m.delete(T)},onDidEdit(T){return y.add(T),()=>y.delete(T)},getScriptIndexOperation(T){return R.get(T)},getSemanticMutationHandler(T,k){let P=s.filter(C=>C.tool===T&&C.handler.matches(k));if(P.length>1)throw new Error(`More than one semantic handler accepted ${T}`);return P[0]?.handler},getToolRenderer(T){return x.get(T)},inspectTextAnchors(T){return Cr(T,[...n],r.snapshot())},resolveTextAnchorResources(T,k,P){return r.snapshot().resolveResources(T,P,new Set(k))},textTargetResolver(){return{id:"text-editor-anchors",tryResolve:c(async(T,k)=>{let P=await r.snapshot().resolveResources(T,k);return P===void 0?{kind:"not-handled"}:{kind:"resolved",targets:P}},"tryResolve")}},resolveAnchorInText(T){let k={source:T.source,content:T.content,lines:T.content.length===0?[]:T.content.split(/\r?\n/u),cwd:T.cwd,...T.signal!==void 0&&{signal:T.signal}};return r.snapshot().resolve(T.value,k,T.kinds===void 0?void 0:new Set(T.kinds))},editText(T,k,P){let C=[...n].sort((b,$)=>b.priority-$.priority||b.order-$.order),O=[...i].sort((b,$)=>(b.registration.priority??0)-($.registration.priority??0)||b.order-$.order);return I(()=>Li(T,k,C,r.snapshot(),O,[...a.values()],[...y],P),k.signal)},editTexts(T,k,P){let C=[...n].sort((b,$)=>b.priority-$.priority||b.order-$.order),O=[...i].sort((b,$)=>(b.registration.priority??0)-($.registration.priority??0)||b.order-$.order);return I(()=>$i(T,k,C,r.snapshot(),O,[...a.values()],[...y],[...g],P),k.signal)},previewTexts(T,k,P){let C=[...n].sort((O,b)=>O.priority-b.priority||O.order-b.order);return Oi(T,k,C,r.snapshot(),P)},async executeEdit(T,k,P){if(!Ae(T))throw new Error(`Unsupported text editor tool ${String(T)}`);let C=o.filter(F=>F.tool===T),O=await Fi(k,C,T);if(O.kind==="failed")return O;let b=await P(O.state),$={...O.state,result:b},L=await kr("text-edit",$,C,T);if(L.kind==="failed")return L;let K=await kr("text-post-edit",L.state,C,T);return K.kind==="failed"?K:{kind:"completed",state:K.state}},registerPostEditHandler(T){if(!un(T))throw new TypeError("Invalid text editor post-edit handler registration");if(a.has(T.id))throw new Error(`Post-edit handler ${T.id} is already registered`);return a.set(T.id,T),()=>{a.get(T.id)===T&&a.delete(T.id)}},registerTool(T){if(!Ae(T))throw new TypeError("Invalid text editor tool ID");h.add(T)},registerPlugin(T){let k=Ni(T);if(k!==void 0)return Promise.reject(k);let P=l.get(T.id);if(P?.plugin===T)return P.ready;if(P!==void 0)return Promise.reject(new Error(`Plugin ${T.id} is already registered`));let C={status:"pending"},O=Di(T.id,A,L=>Cr(L,[...n],r.snapshot()),L=>M.onMutationTool(L),L=>M.onDidEdit(L),L=>dr(M,L),L=>Rr(t,L),(L,K)=>M.restoreApplyUndo(L,K)),b=E.then(async()=>{try{await T.setup(O.api),O.commit(),C.status="active";return}catch(L){throw O.close(),L}}),$={lifecycle:C,plugin:T,ready:b};return l.set(T.id,$),d.add(b),E=b.catch(()=>{}),b.then(()=>{d.delete(b)},()=>{d.delete(b),l.get(T.id)===$&&l.delete(T.id)}),b},recoveryContextLines(){return t.contextLines},renderGeneralPromptGuideline(T){let k=[],P=[];for(let O of l.values()){if(O.lifecycle.status!=="active")continue;let b=p.find(L=>L.pluginId===O.plugin.id);if(b===void 0)continue;let $=Vi(b.description);$!==void 0&&P.push(Wi(O.plugin.id,$))}P.length>0&&k.push(["Text edits support these writable resources:",...P].join(`
42
+ `));let C=r.renderPromptSection(T);return C!==void 0&&k.push(C),k.length===0?void 0:qi(k.join(`
43
+
44
+ `))},renderToolPromptGuideline(T){let k=[];for(let P of l.values()){if(P.lifecycle.status!=="active")continue;let C=u.find(O=>O.pluginId===P.plugin.id&&O.tool===T);C!==void 0&&k.push(C.description)}return k.length===0?void 0:k.join(`
45
+ `)},async waitForPendingPlugins(){await Promise.all(d)}};return M}c(Ir,"createTextEditorCore");async function Cr(e,t,n){let r={cwd:e.cwd,...e.signal!==void 0&&{signal:e.signal}};for(let{resolver:o}of[...t].sort((s,i)=>s.priority-i.priority||s.order-i.order)){let s;try{s=await o.tryResolve(e.source,r)}catch(d){return{kind:"failed",reason:`Resolver ${o.id} failed`,cause:d}}if(!Ue(s))return{kind:"failed",reason:`Resolver ${o.id} returned an invalid result`,cause:s};if(s.kind==="not-handled")continue;if(s.kind==="failed")return{kind:"failed",reason:`Resolver ${o.id} failed`,cause:s.error};let{resource:i}=s;if(i.read===void 0)return{kind:"failed",reason:`Resource ${i.source} is not readable text`};let a;try{a=await i.read(e.signal===void 0?{}:{signal:e.signal})}catch(d){return{kind:"failed",reason:`Unable to read ${i.source}`,cause:d}}return!z(a)||a.length!==1||a[0].type!=="text"?{kind:"failed",reason:`Resource ${i.source} is not readable text`,cause:a}:n.inspect(e.anchors,e.kinds,{source:i.source,content:a[0].text,lines:a[0].text.length===0?[]:a[0].text.split(/\r?\n/u),cwd:e.cwd,...e.signal!==void 0&&{signal:e.signal}})}return{kind:"failed",reason:`No resolver handled ${e.source}`}}c(Cr,"inspectTextResource");async function Oi(e,t,n,r,o){try{let s=new Map(e.map(p=>[p.source,p])),i=[...s.keys()];if(i.length===0||i.some(p=>p.length===0))return{kind:"failed",reason:"No source was provided"};let a=new Map;for(let p of i){let h=S(s.get(p)),f=await Or(p,h.read,h.allowReadFailure??!1,h.requireWrite??!0,t,n);if("failure"in f)return{kind:"failed",reason:f.failure.message};a.set(p,f)}let d=new Map([...a].map(([p,h])=>[p,h.before.content])),l=await o(d,(p,h,f)=>{let m=a.get(p);if(m===void 0)throw new Error(`Anchor refers to undeclared resource ${p}`);return r.resolve(h,m.anchorContext,f===void 0?void 0:new Set(f))});return{kind:"completed",resources:i.map(p=>{let h=S(a.get(p)),f=l.changes.get(p),m=f===void 0?{content:h.before.content,changes:[]}:U(h.before.content,f,!h.existed);return{path:p,existed:h.existed,beforeRanges:m.changes.map(({fromBefore:y,toBefore:w})=>({from:y,to:w})),...h.resource.link!==void 0&&{link:h.resource.link},beforeContent:h.before.content,afterContent:m.content,ranges:m.changes.map(({fromAfter:y,toAfter:w})=>({from:y,to:w}))}})}}catch(s){return{kind:"failed",reason:s instanceof Error?s.message:String(s)}}}c(Oi,"previewTextResources");async function $i(e,t,n,r,o,s,i,a,d){let l=new Map(e.map(R=>[R.source,R])),u=[...l.keys()];if(u.length===0||u.some(R=>R.length===0))return{kind:"failed",failure:{code:"INVALID_REQUEST",source:u.find(E=>E.length===0)??"",message:"No source was provided"},completed:[]};let p=new Map;for(let R of u){let E=S(l.get(R)),v=await Or(R,E.read,E.allowReadFailure??!1,E.requireWrite??!0,t,n);if("failure"in v)return{kind:"failed",failure:v.failure,completed:[]};p.set(R,v)}let h=new Map([...p].map(([R,E])=>[R,E.before.content])),f=await d(h,(R,E,v)=>{let I=p.get(R);if(I===void 0)throw new Error(`Anchor refers to undeclared resource ${R}`);return r.resolve(E,I.anchorContext,v===void 0?void 0:new Set(v))});if(f.resourceEffect===!0)return f.changes.size!==0?{kind:"failed",failure:{code:"INVALID_WRITE_CONTENT",source:u[0]??"",message:"A resource effect cannot also contain document changes"},completed:[]}:{kind:"completed",resources:[],result:f.result};for(let R of f.changes.keys())if(!p.has(R))return{kind:"failed",failure:{code:"INVALID_WRITE_CONTENT",source:R,message:`Text edit produced an undeclared resource ${R}`},completed:[]};let m=new Map;for(let[R,E]of f.changes){let v=S(p.get(R));m.set(R,U(v.before.content,E,!v.existed))}let y={resources:u.flatMap(R=>{let E=S(p.get(R)),v=m.get(R);return v===void 0||E.existed&&v.content===E.before.content?[]:[{source:E.resource.source,existed:E.existed,before:E.before,after:se(E.resource.source,v.content),changes:v.changes}]})};for(let R of a){let E;try{E=await R.guard(y,t)}catch(v){return{kind:"failed",failure:{code:"PLUGIN_FAILED",source:u[0]??"",message:`Mutation guard ${R.id} failed`,cause:v},completed:[]}}if(E.kind==="rejected")return{kind:"failed",failure:{code:"MUTATION_REJECTED",source:y.resources[0]?.source??u[0]??"",message:E.rejection.message},completed:[]}}let w=[],g=[],x=[];for(let R of u){let E=m.get(R)?.content,v=S(p.get(R));if(E===void 0||v.existed&&E===v.before.content)continue;let I=[{type:"text",text:E}];if(!z(I))return{kind:"failed",failure:{code:"INVALID_WRITE_CONTENT",source:R,message:`Text edit for ${R} produced invalid content`},completed:w};try{await S(v.resource.write)(I,t.signal===void 0?{}:{signal:t.signal})}catch(A){let M=[];for(let T of[R,...g].reverse()){let k=S(p.get(T));try{await S(k.resource.write)([{type:"text",text:k.before.content}],{})}catch{M.push(T)}}return{kind:"failed",failure:{code:"WRITE_FAILED",source:R,resolverId:v.resolverId,message:M.length===0?`Unable to write ${R}; completed writes were rolled back`:`Unable to write ${R}; rollback failed for ${M.join(", ")}`,cause:A},completed:M}}g.push(R),w.push(R)}return await sn(async()=>{for(let R of g){let E=S(m.get(R)).content,v=S(p.get(R));x.push(await st({requestedSource:v.requestedSource,outcomeSource:v.requestedSource,resource:v.resource,resolvedBy:v.resolverId,existed:v.existed,before:v.before,requestedText:E,context:t,presenters:o,postEditHandlers:s,editCompletionListeners:i,result:f.result}))}}),{kind:"completed",resources:x,result:f.result}}c($i,"editTextResources");async function Or(e,t,n,r,o,s){for(let{resolver:i}of s){let a;try{a=await i.tryResolve(e,o)}catch(p){return{failure:{code:"RESOLVE_FAILED",source:e,resolverId:i.id,message:`Resolver ${i.id} failed`,cause:p}}}if(!Ue(a))return{failure:{code:"INVALID_RESOLVER_RESULT",source:e,resolverId:i.id,message:`Resolver ${i.id} returned an invalid result`,cause:a}};if(a.kind==="not-handled")continue;if(a.kind==="failed")return{failure:{code:"RESOLVE_FAILED",source:e,resolverId:i.id,message:`Resolver ${i.id} failed`,cause:a.error}};if(r&&a.resource.write===void 0||t&&a.resource.read===void 0)return{failure:{code:"UNSUPPORTED_CAPABILITY",source:a.resource.source,resolverId:i.id,message:`Resource ${a.resource.source} does not support text editing`}};let d="",l=t;if(t){let p;try{p=await S(a.resource.read)(o.signal===void 0?{}:{signal:o.signal})}catch(h){if(!n)return{failure:{code:"READ_FAILED",source:a.resource.source,resolverId:i.id,message:`Unable to read ${a.resource.source}`,cause:h}};l=!1,p=[{type:"text",text:""}]}if(!z(p)||p.length!==1||p[0].type!=="text")return{failure:{code:"UNSUPPORTED_CONTENT",source:a.resource.source,resolverId:i.id,message:`Resource ${a.resource.source} is not editable text`,cause:p}};d=p[0].text}let u=se(a.resource.source,d);return{requestedSource:e,resource:a.resource,resolverId:i.id,existed:l,before:u,anchorContext:{source:a.resource.source,content:u.content,lines:u.lines.map(p=>p.content),cwd:o.cwd,...o.signal!==void 0&&{signal:o.signal}}}}return{failure:{code:"NO_RESOLVER",source:e,message:`No resolver handled ${e}`}}}c(Or,"prepareTextResource");async function st(e){let t=e.resource.skipPostEdit===!0;if(!t&&e.postProcessingFinal&&!e.context.signal?.aborted&&e.resource.read){let p=await e.resource.read(e.context.signal?{signal:e.context.signal}:{});if(!z(p)||p.length!==1||p[0].type!=="text"||p[0].text!==e.requestedText)throw Object.assign(new Error(`Resource changed before final post-processing: ${e.resource.source}`),{code:"POST_EDIT_STALE"})}let n=!t&&!e.postProcessingFinal&&an(e.resource.source,()=>st({...e,postProcessingFinal:!0})),r=se(e.resource.source,e.requestedText),o={source:e.requestedSource,resourceSource:e.resource.source,resolvedBy:e.resolvedBy,cwd:e.context.cwd,before:e.before,requestedAfter:r,...e.context.signal!==void 0&&{signal:e.context.signal}},s=n?[{id:"post-edit-scope",data:{formatting:{status:"deferred"}}}]:[];for(let p of t||n||e.context.signal?.aborted?[]:e.postEditHandlers)try{let h=await p.handler(o);h!==void 0&&s.push({id:p.id,data:h})}catch{}let i=e.requestedText;if(!t&&e.resource.read!==void 0)try{let p=await e.resource.read(e.context.signal===void 0?{}:{signal:e.context.signal});z(p)&&p.length===1&&p[0].type==="text"&&(i=p[0].text)}catch{}let a=se(e.resource.source,i),d={source:e.requestedSource,resourceSource:e.resource.source,resolvedBy:e.resolvedBy,cwd:e.context.cwd,existed:e.existed,before:e.postProcessingFinal?r:e.before,after:a,intent:e.context.intent??"edit",postProcessing:n?"deferred":e.postProcessingFinal?"final":"complete"};for(let p of e.editCompletionListeners)try{let h=await p(d);h!==void 0&&h.feedback.trim().length>0&&s.push({id:"after-edit",data:{diffStatuses:[{text:h.feedback,tone:h.tone==="info"?"muted":h.tone}]}})}catch{}let l=a,u={purpose:"edit-diff",source:e.resource.source,cwd:e.context.cwd,resolvedBy:e.resolvedBy,...e.context.signal!==void 0&&{signal:e.context.signal}};for(let{registration:p}of e.context.signal?.aborted?[]:e.presenters)l=await p.presenter.present(l,u);return{kind:"completed",source:e.outcomeSource,resolvedBy:e.resolvedBy,before:e.before,after:l,result:e.result,postEditContributions:s}}c(st,"finalizeTextResource");async function Li(e,t,n,r,o,s,i,a){if(e.length===0)return{kind:"failed",failure:{code:"INVALID_REQUEST",source:e,message:"No source was provided"}};for(let{resolver:d}of n){let l;try{l=await d.tryResolve(e,t)}catch(g){return{kind:"failed",failure:{code:"RESOLVE_FAILED",source:e,resolverId:d.id,message:`Resolver ${d.id} failed`,cause:g}}}if(!Ue(l))return{kind:"failed",failure:{code:"INVALID_RESOLVER_RESULT",source:e,resolverId:d.id,message:`Resolver ${d.id} returned an invalid result`,cause:l}};if(l.kind==="not-handled")continue;if(l.kind==="failed")return{kind:"failed",failure:{code:"RESOLVE_FAILED",source:e,resolverId:d.id,message:`Resolver ${d.id} failed`,cause:l.error}};let u=l.resource;if(u.read===void 0||u.write===void 0)return{kind:"failed",failure:{code:"UNSUPPORTED_CAPABILITY",source:u.source,resolverId:d.id,message:`Resource ${u.source} does not support text editing`}};let p;try{p=await u.read({...t.signal!==void 0&&{signal:t.signal}})}catch(g){return{kind:"failed",failure:{code:"READ_FAILED",source:u.source,resolverId:d.id,message:`Unable to read ${u.source}`,cause:g}}}if(!z(p))return{kind:"failed",failure:{code:"INVALID_RESOURCE_CONTENT",source:u.source,resolverId:d.id,message:`Resource ${u.source} returned invalid content`,cause:p}};let h=p[0];if(p.length!==1||h.type!=="text")return{kind:"failed",failure:{code:"UNSUPPORTED_CONTENT",source:u.source,resolverId:d.id,message:`Resource ${u.source} is not editable text`}};let f=se(u.source,h.text),m={source:u.source,content:f.content,lines:f.lines.map(g=>g.content),cwd:t.cwd,...t.signal!==void 0&&{signal:t.signal}},y=await a(h.text,(g,x)=>r.resolve(g,m,x===void 0?void 0:new Set(x))),w=[{type:"text",text:y.text}];if(!z(w))return{kind:"failed",failure:{code:"INVALID_WRITE_CONTENT",source:u.source,resolverId:d.id,message:`Text edit for ${u.source} produced invalid content`,cause:y}};try{await u.write(w,{...t.signal!==void 0&&{signal:t.signal}})}catch(g){return{kind:"failed",failure:{code:"WRITE_FAILED",source:u.source,resolverId:d.id,message:`Unable to write ${u.source}`,cause:g}}}return st({requestedSource:e,outcomeSource:u.source,resource:u,resolvedBy:d.id,existed:!0,before:f,requestedText:y.text,context:t,presenters:o,postEditHandlers:s,editCompletionListeners:i,result:y.result})}return{kind:"failed",failure:{code:"NO_RESOLVER",source:e,message:`No resolver handled ${e}`}}}c(Li,"editTextResource");async function Fi(e,t,n){let r=e;for(let o of t)if(o.registration.stage==="text-pre-edit")try{r=await o.registration.handler(r)}catch(s){return{kind:"failed",failure:$r(o.pluginId,n,"text-pre-edit",s)}}return{kind:"completed",state:r}}c(Fi,"runPreEditHandlers");async function kr(e,t,n,r){let o=t;for(let s of n)if(s.registration.stage===e)try{o=await s.registration.handler(o)}catch(i){return{kind:"failed",failure:$r(s.pluginId,r,e,i)}}return{kind:"completed",state:o}}c(kr,"runResultHandlers");function $r(e,t,n,r){return{code:"PLUGIN_FAILED",pluginId:e,tool:t,stage:n,message:`Plugin ${e} failed during ${n}: ${r instanceof Error?r.message:String(r)}`,cause:r}}c($r,"pluginFailure");function Ni(e){if(e.protocol!==He)return new Error(`Plugin ${e.id} uses an unsupported protocol`);if(e.apiVersion!==Ve)return new Error(`Plugin ${e.id} uses an unsupported API version`);if(e.id.trim().length===0)return new Error("Plugin ID must not be empty")}c(Ni,"getPluginValidationError");function Di(e,t,n,r,o,s,i,a){let d={resolvers:[],anchorResolvers:[],presenters:[],handlers:[],semanticHandlers:[],promptContributions:[],writablePromptContributions:[],tools:[],mutationTools:[],mutationToolListeners:[],editCompletionListeners:[],mutationGuards:[],toolRenderers:[],scriptIndexOperations:[]},l="setup",u=c(()=>{if(l==="closed")throw new Error(`Plugin ${e} API is closed`)},"assertAvailable"),p=c(f=>({addSemanticHandler(m){if(u(),typeof m.matches!="function"||typeof m.execute!="function")throw new TypeError(`Plugin ${e} provided an invalid semantic handler for ${f}`);let y={pluginId:e,handler:m,tool:f};if(l==="setup"){let w=S(d.semanticHandlers);if(w.some(g=>g.pluginId===e&&g.tool===f))throw new Error(`Plugin ${e} already provides a semantic handler for ${f}`);w.push(y);return}t({resolvers:[],anchorResolvers:[],handlers:[],semanticHandlers:[y],promptContributions:[],writablePromptContributions:[],tools:[]})},addHandler(m){if(u(),!St(m))throw new TypeError(`Plugin ${e} provided an invalid handler for ${f}`);let y={pluginId:e,registration:m,tool:f};if(l==="setup"){ji(d.handlers,y),d.handlers.push(y);return}t({resolvers:[],anchorResolvers:[],handlers:[y],promptContributions:[],writablePromptContributions:[],tools:[]})},describe(m){u();let y={description:_t(`Plugin prompt description for ${f}`,m),pluginId:e,tool:f};if(l==="setup"){Ui(d.promptContributions,y),d.promptContributions.push(y);return}t({resolvers:[],anchorResolvers:[],handlers:[],promptContributions:[y],writablePromptContributions:[],tools:[]})}}),"createToolApi");return{api:{restoreApplyUndo:a,addMutationTool(f){if(u(),Xe(f),l==="setup"){S(d.mutationTools).push(f);return}t({resolvers:[],anchorResolvers:[],handlers:[],promptContributions:[],writablePromptContributions:[],tools:[],mutationTools:[f]})},addScriptIndexOperation(f){if(u(),l==="setup"){S(d.scriptIndexOperations).push(f);return}t({resolvers:[],anchorResolvers:[],handlers:[],promptContributions:[],writablePromptContributions:[],tools:[],scriptIndexOperations:[f]})},addToolRenderer(f){if(u(),!Ct(f))throw new TypeError(`Plugin ${e} provided an invalid text editor tool renderer`);if(l==="setup"){S(d.toolRenderers).push(f);return}t({resolvers:[],anchorResolvers:[],handlers:[],promptContributions:[],writablePromptContributions:[],tools:[],toolRenderers:[f]})},addMutationGuard(f){if(u(),f.id.trim().length===0||typeof f.guard!="function")throw new TypeError(`Plugin ${e} provided an invalid mutation guard`);if(l==="setup"){S(d.mutationGuards).push(f);return}t({resolvers:[],anchorResolvers:[],handlers:[],promptContributions:[],writablePromptContributions:[],tools:[],mutationGuards:[f]})},onMutationTool(f){return u(),l==="setup"?(S(d.mutationToolListeners).push(f),()=>{let m=S(d.mutationToolListeners).indexOf(f);m!==-1&&S(d.mutationToolListeners).splice(m,1)}):r(f)},onDidEdit(f){if(u(),typeof f!="function")throw new TypeError(`Plugin ${e} provided an invalid edit completion listener`);return l==="setup"?(S(d.editCompletionListeners).push(f),()=>{let m=S(d.editCompletionListeners).indexOf(f);m!==-1&&S(d.editCompletionListeners).splice(m,1)}):o(f)},inspectTextAnchors(f){return u(),n(f)},recoveryConfig(f){return u(),i(f)},previewMutation(f){return u(),s(f)},addResolver(f){if(u(),!Rt(f))throw new TypeError(`Plugin ${e} provided an invalid resource resolver`);let m={pluginId:e,registration:f};if(l==="setup"){Bi(d.resolvers,m),d.resolvers.push(m);return}t({resolvers:[m],anchorResolvers:[],handlers:[],promptContributions:[],writablePromptContributions:[],tools:[]})},addAnchorResolver(f){if(u(),!wt(f))throw new TypeError(`Plugin ${e} provided an invalid text anchor resolver`);let m={pluginId:e,registration:f};if(l==="setup"){d.anchorResolvers.push(m);return}t({resolvers:[],anchorResolvers:[m],handlers:[],promptContributions:[],writablePromptContributions:[],tools:[]})},addTextPresenter(f){if(u(),!yt(f))throw new TypeError(`Plugin ${e} provided an invalid text presenter`);let m={pluginId:e,registration:f};if(l==="setup"){S(d.presenters).push(m);return}t({resolvers:[],anchorResolvers:[],presenters:[m],handlers:[],promptContributions:[],writablePromptContributions:[],tools:[]})},describe(f){if(u(),d.writablePromptContributions.length>0)throw new Error(`Plugin ${e} provides more than one writable resource description`);let m={description:Hi(f),pluginId:e};if(l==="setup"){d.writablePromptContributions.push(m);return}t({resolvers:[],anchorResolvers:[],handlers:[],promptContributions:[],writablePromptContributions:[m],tools:[]})},tool(f){if(u(),!Ae(f))throw new Error(`Plugin ${e} provided an invalid tool ID`);return l==="setup"?d.tools.includes(f)||d.tools.push(f):t({resolvers:[],anchorResolvers:[],handlers:[],promptContributions:[],writablePromptContributions:[],tools:[f]}),p(f)}},close(){l="closed"},commit(){if(l!=="setup")throw new Error(`Plugin ${e} setup contributions cannot be committed`);t(d),l="active"}}}c(Di,"createPluginContributionController");function _i(e,t,n,r,o,s){let i=new Set(t.map(({resolver:p})=>p.id));for(let p of e.resolvers){if(!Rt(p.registration))throw new TypeError(`Plugin ${p.pluginId} provided an invalid resource resolver`);let h=p.registration.resolver.id;if(i.has(h))throw new Error(`Resource resolver ${h} is already registered`);i.add(h)}let a=new Set(r.map(p=>`${p.pluginId}\0${p.tool}`));for(let p of e.semanticHandlers??[]){if(typeof p.handler.matches!="function"||typeof p.handler.execute!="function")throw new TypeError(`Plugin ${p.pluginId} provided an invalid semantic handler`);let h=`${p.pluginId}\0${p.tool}`;if(a.has(h))throw new Error(`Plugin ${p.pluginId} already provides a semantic handler for ${p.tool}`);a.add(h)}let d=new Set(n.map(ot));for(let p of e.handlers){if(!St(p.registration))throw new TypeError(`Plugin ${p.pluginId} provided an invalid handler for ${p.tool}`);let h=ot(p);if(d.has(h))throw new Error(`Plugin ${p.pluginId} already handles ${p.registration.stage} for ${p.tool}`);d.add(h)}let l=new Set(o.map(it));for(let p of e.promptContributions){let h=it(p);if(l.has(h))throw new Error(`Plugin ${p.pluginId} describes ${p.tool} more than once`);l.add(h)}let u=new Set(s.map(({pluginId:p})=>p));for(let p of e.writablePromptContributions){if(u.has(p.pluginId))throw new Error(`Plugin ${p.pluginId} provides more than one writable resource description`);u.add(p.pluginId)}for(let p of e.tools)if(!Ae(p))throw new TypeError("Plugin provided an invalid tool ID")}c(_i,"validateContributionDraft");function Bi(e,t){let n=t.registration.resolver.id;if(e.some(r=>r.registration.resolver.id===n))throw new Error(`Resource resolver ${n} is already registered`)}c(Bi,"assertNoDraftResolver");function ji(e,t){if(e.some(n=>ot(n)===ot(t)))throw new Error(`Plugin ${t.pluginId} already handles ${t.registration.stage} for ${t.tool}`)}c(ji,"assertNoDraftHandler");function Ui(e,t){if(e.some(n=>it(n)===it(t)))throw new Error(`Plugin ${t.pluginId} describes ${t.tool} more than once`)}c(Ui,"assertNoDraftDescription");function ot(e){return`${e.pluginId}\0${e.tool}\0${e.registration.stage}`}c(ot,"handlerKey");function it(e){return`${e.pluginId}\0${e.tool}`}c(it,"descriptionKey");function Hi(e){if(typeof e=="string")return _t("Writable resource prompt description",e);if(typeof e=="function")return e;throw new TypeError("Writable resource prompt description must be a string or callback")}c(Hi,"normalizeDescriptionSource");function Vi(e){if(typeof e=="string")return e;let t=e();return t===void 0?void 0:_t("Writable resource prompt description",t)}c(Vi,"renderDescriptionSource");function _t(e,t){if(typeof t!="string")throw new TypeError(`${e} must be a string`);let n=t.replaceAll(`\r
46
+ `,`
47
+ `).replaceAll("\r",`
48
+ `).split(`
49
+ `).map(o=>o.trimEnd());for(;n[0]?.trim().length===0;)n.shift();for(;n.at(-1)?.trim().length===0;)n.pop();let r=n.join(`
50
+ `);if(r.trim().length===0)throw new Error(`${e} is empty`);return r}c(_t,"normalizeDescription");function Wi(e,t){let[n,...r]=t.split(`
51
+ `);return[`- \`${Gi(e)}\` \u2014 ${n??""}`,...r.map(o=>` ${o}`)].join(`
52
+ `)}c(Wi,"renderPromptEntry");function qi(e){let[t,...n]=e.split(`
53
+ `);return[t??"",...n.map(r=>r.length===0?r:` ${r}`)].join(`
54
+ `)}c(qi,"indentGuidelineContinuation");function Gi(e){return e.replaceAll("`","\\`")}c(Gi,"escapeInlineCode");function zi(e,t){if(t.matches!==void 0){let i=t.renderCall,a=t.renderResult,d=e?.renderCall,l=e?.renderResult;return{...e,tool:t.tool,...i===void 0?{}:d===void 0?{renderCall:i}:{renderCall:c((...u)=>t.matches?.(u[0],"call")===!0?i(...u):d(...u),"renderCall")},...a===void 0?{}:l===void 0?{renderResult:a}:{renderResult:c((...u)=>t.matches?.(u[0],"result")===!0?a(...u):l(...u),"renderResult")}}}let n=t.fallback===!0?{...t,...e,tool:t.tool}:{...e,...t,tool:t.tool},{fallback:r,matches:o,...s}=n;return s}c(zi,"mergeToolRenderer");function Pr(e,t){for(let n of t.values())e(n)}c(Pr,"replayMutationTools");function Mr(e,t,n,r,o,s){if(Xe(e),t.has(e.name))throw new Error(`Mutation tool ${e.name} is already registered`);t.set(e.name,e),n.add(e.name);for(let i of r)i(e);o?.(e,s)}c(Mr,"addMutationRegistration");var Lr=5;function Fr(e){return{id:"text-editor-anchors",async resolve(t){let n;try{n=await e.resolveAnchorInText({source:t.source,content:t.text.content,value:t.fragment,cwd:t.cwd,...t.signal!==void 0&&{signal:t.signal}})}catch(r){return r instanceof N&&await r.refreshRecovery(),{kind:"failed",message:Ki(r)}}return{kind:"resolved",originLine:Xi(n)}}}}c(Fr,"createReadFragmentResolver");function Xi(e){return V.is(e)?S(e.ranges[0]).start.lineNumber:e.lineNumber}c(Xi,"anchorOriginLine");function Ki(e){if(!(e instanceof N))return e instanceof Error?e.message:String(e);let t=[e.message],n=e.recovery;if(n?.kind==="candidates"&&n.candidates.length>0){for(let o of n.candidates.slice(0,Lr))t.push(`Candidate: line ${o.range.start.lineNumber}`);let r=n.total-Math.min(n.candidates.length,Lr);r>0&&t.push(`(+${r} more candidates)`)}return t.join(`
55
+ `)}c(Ki,"describeAnchorError");import{format as Yi}from"oxfmt";async function Nr(e){try{let t=await Yi("apply.js",e,{printWidth:90});return t.errors.length===0?t.code.trimEnd():e}catch{return e}}c(Nr,"formatApplySource");var Ji=`
56
+ Read-only helpers use the standalone-tool arguments: read({...}), search({...}), and diff({before, after}). Their results are recorded automatically.
57
+
58
+ Transactional helpers:
59
+ open(path | {path, views?}); file.find(text); file.select(searchMatch); file.between(start, end, {inside?, lines?}); file.line(first, last?); file.start(); file.end(); file.before(selection); file.after(selection); file.slice(selection, start?, end?); file.union(...selections); file.within(candidates, scopes); file.linesOf(selection); file.replace(selection, text); file.remove(selection); file.insertBefore(selection, text); file.insertAfter(selection, text); file.flush(); file.delete(); replace(selection, text); remove(selection); insertBefore(selection, text); insertAfter(selection, text); copy(source, destination); move(source, destination); createFile(path, content); deleteFile(path); copyFile(path, target, {overwrite?}); moveFile(path, target, {overwrite?}); flush().
60
+
61
+ Selections are immutable and snapshot-bound. Use slice to select occurrences by position, union to combine non-overlapping sets, within to keep candidates contained by scopes, and linesOf to expand matches to whole lines. between accepts strings or SelectionSets as either boundary; {lines:true} expands through both containing lines. Prefer it for blocks identified by content; use line(first,last) only for exact verified line bounds. Use start/end or before/after as zero-width destinations when copy or move should insert instead of replace. Normal completion commits staged operations once; a thrown script commits none. flush() commits every staged operation; file.flush() commits only independent operations for that file while cross-file transfers stay pending. Successful checkpoints can return an APPLY# receipt. Failed operations report structured errors and do not silently guess a recovery.
62
+ `;function Dr(){return Ji}c(Dr,"applyHelperGuide");import{Type as so}from"typebox";import{Value as Yr}from"typebox/value";import{isDeepStrictEqual as Qi}from"node:util";var at=class{static{c(this,"ApplyResults")}#e=new Map;#t=[];#o=new Set;#r=new Map;#i=!1;#n=new Map;rememberMutation(t,n){this.#n.set(t,n)}mutationPresentation(t){return this.#n.get(t)}mutationValues(){return[...this.#e.values()].filter(({kind:t})=>t==="mutation").map(({value:t})=>t)}record(t,n,r,o){if(this.#e.has(t))throw new Error(`Duplicate operation identity: ${t}`);this.#e.set(t,{id:t,kind:n,value:r,...o===void 0?{}:{presentation:o}}),this.#i||=n==="mutation"}addOperation(t){let n=S(this.#e.get(t));this.#o.has(t)||(this.#o.add(t),this.#t.push({kind:"operation",id:t,value:n.value,...n.presentation===void 0?{}:{presentation:n.presentation}}))}add(t,n){let r=n===void 0?void 0:this.#e.get(n);r!==void 0&&Qi(r.value,t)?this.addOperation(r.id):this.addValue(t)}addValue(t){this.#t.push({kind:"value",value:t})}updateFile(t,n,r){let o=this.#r.get(t);this.#r.set(t,{source:t,before:o===void 0?n:o.before,after:r})}forgetFile(t){this.#r.delete(t),this.#n.delete(t)}select(){return{explicit:[...this.#t],automatic:[...this.#e.values()].filter(({id:t,kind:n})=>!this.#o.has(t)&&(!this.#i||n==="mutation")),files:[...this.#r.values()]}}};var ct=class{static{c(this,"ApplyQueue")}#e=Promise.resolve();#t=!1;submit(t){if(this.#t)return Promise.reject(new Error("Apply execution has ended"));let n=this.#e.then(()=>{if(this.#t)throw new Error("Apply execution has ended");return t()});return this.#e=n.then(()=>{},()=>{}),n}async close(){this.#t=!0,await this.#e}};var _r=["read","search","diff","editorOpen","editorResolve","editorApply"],Zi=2147483647;function Br(){return _r}c(Br,"getApplyOperations");async function jr(e,t,n,r,o=_r){let{createRunner:s,getHostFunctionContext:i}=await import("run"),a=new ct,d=Object.fromEntries(o.map(l=>[l,u=>{let p=i();return a.submit(async()=>{p.abortSignal.throwIfAborted();try{return{ok:!0,value:await t.execute(l,u,p.abortSignal,p.requestId),id:p.requestId}}catch(h){return{ok:!1,error:Le(h)}}})}]));try{await s({syncHostFunctions:{__apply:{...d,result:c((u,p)=>a.submit(()=>t.result(u,p)),"result")}}}).run({source:`${ts(o)}
63
+ await (async () => {
64
+ ${e}
65
+ })();
66
+ __finishApplyScript();`,abortSignal:n,limits:{...r,timeoutMs:r?.timeoutMs??Zi}})}finally{await a.close()}}c(jr,"executeApplySource");function Le(e){if(!(e instanceof Error))return{code:"OPERATION_FAILED",message:String(e)};let t="code"in e&&typeof e.code=="string"?e.code:void 0;return{code:t==="RUN_USER_SOURCE_ERROR"?es(e.message):t??"OPERATION_FAILED",message:e.message,..."details"in e?{details:e.details}:{}}}c(Le,"serializeApplyError");function es(e){return/Expected exactly one (?:match|end marker)/u.test(e)?e.endsWith("found 0")?"NOT_FOUND":"AMBIGUOUS_MATCH":e==="No matches"?"NOT_FOUND":e==="Search match is stale"?"STALE_SELECTION":e==="Editor handle belongs to a committed transaction"?"STALE_EDITOR":e==="union() selections overlap"||e==="Expected a SelectionSet"?"INVALID_SELECTION":e==="SelectionSet belongs to another file"?"CROSS_FILE_SELECTION":e==="SelectionSet belongs to a stale snapshot"?"STALE_SELECTION":/^(?:Invalid line range|Line range is outside document)$/u.test(e)?"INVALID_SELECTION":"RUN_USER_SOURCE_ERROR"}c(es,"applyGuestErrorCode");function ts(e){let t=e.filter(n=>n==="read"||n==="search"||n==="diff");return`const { ${t.join(", ")}, open, createFile, deleteFile, copyFile, moveFile, replace, remove, insertBefore, insertAfter, copy, move, flush, __finishApplyScript } = (() => {
67
+
68
+ const invoke = (name, args) => {
69
+ const response = __apply[name](args);
70
+ if (!response.ok) throw Object.assign(new Error(response.error.message), response.error);
71
+
72
+ return response.value;
73
+ };
74
+ let snapshots = new Map();
75
+ let operations = [];
76
+ const assertCurrent = (document) => {
77
+ if (!snapshots.has(document.id)) throw Object.assign(new Error("Editor handle belongs to an unavailable snapshot"), {code: "STALE_EDITOR"});
78
+ };
79
+ const selection = (document, from, to, linewise = false) => Object.freeze({document: document.id, from, to, text: document.content.slice(from, to), ...(linewise && {linewise: true})});
80
+ const selectionSet = (document, ranges, provenance) => {
81
+ const set = ranges.map(({from, to, linewise}) => selection(document, from, to, linewise === true));
82
+ Object.defineProperties(set, {document: {value: document.id}, generation: {value: document.generation}, provenance: {value: provenance}, text: {value: set.map((item) => item.text).join("")}});
83
+ return Object.freeze(set);
84
+ };
85
+ const occurrences = (content, needle) => {
86
+ if (typeof needle !== "string" || needle.length === 0) throw new Error("Find text must be non-empty");
87
+ const found = [];
88
+ for (let from = content.indexOf(needle); from >= 0; from = content.indexOf(needle, from + needle.length)) found.push(from);
89
+ return found;
90
+ };
91
+ const selectionError = (code, message) => Object.assign(new Error(message), {code});
92
+ const assertSet = (document, set) => {
93
+ if (!Array.isArray(set)) throw selectionError("INVALID_SELECTION", "Expected a SelectionSet");
94
+ if (set.document !== document.id) throw selectionError("CROSS_FILE_SELECTION", "SelectionSet belongs to another file");
95
+ if (set.generation !== document.generation) throw selectionError("STALE_SELECTION", "SelectionSet belongs to a stale snapshot");
96
+ return set;
97
+ };
98
+ const boundarySet = (document, value) => {
99
+ if (typeof value !== "string") return assertSet(document, value);
100
+ const ranges = occurrences(document.content, value).map((from) => ({from, to: from + value.length}));
101
+ return selectionSet(document, ranges, {kind: "exact", query: value});
102
+ };
103
+ const lineRange = (document, item) => {
104
+ const from = document.content.lastIndexOf("\\n", Math.max(0, item.from - 1)) + 1;
105
+ const newline = document.content.indexOf("\\n", Math.max(item.from, item.to - 1));
106
+ return {from, to: newline < 0 ? document.content.length : newline + 1, linewise: true};
107
+ };
108
+ const targetSet = (document, target) => {
109
+ if (typeof target !== "string") return target;
110
+ const resolved = invoke("editorResolve", {snapshot: {id: document.id, source: document.source, content: document.content}, query: target});
111
+ return selectionSet(document, resolved.selections, {kind: "exact", query: target, warning: resolved.warning});
112
+ };
113
+ const stage = (document, target, text, edge) => {
114
+ const selected = targetSet(document, target);
115
+ if (!Array.isArray(selected) || selected.document !== document.id) throw new Error("SelectionSet belongs to another file");
116
+ if (selected.generation !== document.generation) throw Object.assign(new Error("SelectionSet belongs to a stale snapshot"), {code:"STALE_SELECTION"});
117
+ if (selected.length === 0) { operations.push({kind: "warning", document: document.id, query: selected.provenance?.query, warning: selected.provenance?.warning}); return; }
118
+ for (const range of selected) {
119
+ const point = edge === "before" ? range.from : edge === "after" ? range.to : undefined;
120
+ let insert = text;
121
+ if (point !== undefined && range.linewise === true) {
122
+ const ending = /(?:\\r\\n|\\r|\\n)$/u.exec(range.text)?.[0];
123
+ const separator = ending ?? (document.content.includes("\\r\\n") ? "\\r\\n" : "\\n");
124
+ if (edge === "after" && ending === undefined) insert = separator + insert;
125
+ else if (!/(?:\\r\\n|\\r|\\n)$/u.test(insert)) insert += separator;
126
+ }
127
+ operations.push({kind: "replace", selection: point === undefined ? range : selection(document, point, point), text: insert});
128
+ }
129
+ };
130
+ const stageTransfer = (kind, source, destination) => {
131
+ for (const set of [source, destination]) {
132
+ const document = snapshots.get(set?.document);
133
+ if (!Array.isArray(set) || document === undefined || set.generation !== document.generation) throw Object.assign(new Error("SelectionSet belongs to a stale or unopened snapshot"), {code:"STALE_SELECTION"});
134
+ }
135
+ const empty = source.length === 0 ? source : destination.length === 0 ? destination : undefined;
136
+ if (empty !== undefined) { operations.push({kind:"warning", document:empty.document, query:empty.provenance?.query, warning:empty.provenance?.warning}); return; }
137
+ operations.push({kind, sources:[...source], destinations:[...destination], text:source.map((item) => item.text).join("")});
138
+ };
139
+ const stageSet = (target, text, edge) => {
140
+ const document = snapshots.get(target?.document);
141
+ if (document === undefined) throw selectionError("STALE_SELECTION", "SelectionSet belongs to a stale or unopened snapshot");
142
+ stage(document, target, text, edge);
143
+ };
144
+ const refreshSnapshots = (value) => {
145
+ for (const refreshed of value?.snapshots ?? []) {
146
+ const document = snapshots.get(refreshed.id);
147
+ if (document !== undefined && refreshed.unavailable === true) snapshots.delete(refreshed.id);
148
+ else if (document !== undefined) {
149
+ document.source = refreshed.source;
150
+ document.content = refreshed.content;
151
+ document.lines = refreshed.lines;
152
+ document.generation += 1;
153
+ }
154
+ }
155
+ };
156
+ const commit = (selected) => {
157
+ if (selected.length === 0) return undefined;
158
+ const value = invoke("editorApply", {snapshots: [...snapshots.values()].map(({id, source, content}) => ({id, source, content})), operations: selected});
159
+ refreshSnapshots(value);
160
+ return value;
161
+ };
162
+ const flushDocument = (document) => {
163
+ assertCurrent(document);
164
+ const participatesInTransfer = operations.some((operation) =>
165
+ (operation.kind === "text-copy" || operation.kind === "text-move") &&
166
+ [...operation.sources, ...operation.destinations].some((item) => item.document === document.id));
167
+ if (participatesInTransfer) return undefined;
168
+ const selected = [];
169
+ const remaining = [];
170
+ for (const operation of operations) {
171
+ const belongs =
172
+ (operation.kind === "replace" && operation.selection.document === document.id) ||
173
+ (operation.kind === "warning" && operation.document === document.id) ||
174
+ (operation.kind === "delete" && operation.path === document.source);
175
+ (belongs ? selected : remaining).push(operation);
176
+ }
177
+ operations = remaining;
178
+ return commit(selected);
179
+ };
180
+ const makeDocument = (snapshot) => {
181
+ const document = {id: snapshot.id, source: snapshot.source, content: snapshot.content, lines: snapshot.lines, generation: 0};
182
+ snapshots.set(document.id, document);
183
+ const api = {
184
+ get source() { return document.source; },
185
+ get content() { return document.content; },
186
+ get lines() { return document.lines; },
187
+ find: (text) => { assertCurrent(document); const ranges = occurrences(document.content, text).map((from) => ({from, to: from + text.length})); if (ranges.length > 0) return selectionSet(document, ranges, {kind: "exact", query: text}); const resolved = invoke("editorResolve", {snapshot: {id: document.id, source: document.source, content: document.content}, query: text}); return selectionSet(document, [], {kind: "exact", query: text, warning: resolved.warning}); },
188
+ between: (start, end, options = {}) => {
189
+ assertCurrent(document);
190
+ if (options.inside === true && options.lines === true) throw selectionError("INVALID_SELECTION", "between() cannot combine inside and lines");
191
+ const starts = boundarySet(document, start);
192
+ const ends = boundarySet(document, end);
193
+ const ranges = [];
194
+ let cursor = 0;
195
+ for (const left of starts) {
196
+ if (left.from < cursor) continue;
197
+ const right = ends.find((candidate) => candidate.from >= left.to);
198
+ if (right === undefined) break;
199
+ const range = options.lines === true
200
+ ? {from: lineRange(document, left).from, to: lineRange(document, right).to, linewise: true}
201
+ : {
202
+ from: options.inside === true ? left.to : left.from,
203
+ to: options.inside === true ? right.from : right.to,
204
+ linewise: options.inside !== true && left.linewise === true && right.linewise === true,
205
+ };
206
+ ranges.push(range);
207
+ cursor = right.to;
208
+ }
209
+ return selectionSet(document, ranges, {kind: "between"});
210
+ },
211
+ slice: (set, start, end) => {
212
+ assertCurrent(document);
213
+ const selected = assertSet(document, set);
214
+ return selectionSet(document, selected.slice(start, end), {kind: "slice", source: selected.provenance, start, end, warning: selected.provenance?.warning});
215
+ },
216
+ union: (...sets) => {
217
+ assertCurrent(document);
218
+ const ranges = sets.flatMap((set) => [...assertSet(document, set)]).sort((left, right) => left.from - right.from || left.to - right.to);
219
+ const unique = ranges.filter((range, index) => index === 0 || range.from !== ranges[index - 1].from || range.to !== ranges[index - 1].to);
220
+ for (let index = 1; index < unique.length; index += 1) {
221
+ if (unique[index].from < unique[index - 1].to) throw selectionError("INVALID_SELECTION", "union() selections overlap");
222
+ }
223
+ return selectionSet(document, unique, {kind: "union", sources: sets.map((set) => set.provenance), warning: sets.find((set) => set.provenance?.warning)?.provenance.warning});
224
+ },
225
+ within: (candidates, scopes) => {
226
+ assertCurrent(document);
227
+ const selected = assertSet(document, candidates);
228
+ const containers = assertSet(document, scopes);
229
+ const ranges = selected.filter((candidate) => containers.some((scope) => scope.from <= candidate.from && candidate.to <= scope.to));
230
+ return selectionSet(document, ranges, {kind: "within", source: selected.provenance, scopes: containers.provenance, warning: selected.provenance?.warning ?? containers.provenance?.warning});
231
+ },
232
+ linesOf: (set) => {
233
+ assertCurrent(document);
234
+ const selected = assertSet(document, set);
235
+ const ranges = selected.map((item) => lineRange(document, item)).sort((left, right) => left.from - right.from);
236
+ const unique = ranges.filter((range, index) => index === 0 || range.from !== ranges[index - 1].from || range.to !== ranges[index - 1].to);
237
+ return selectionSet(document, unique, {kind: "linesOf", source: selected.provenance, warning: selected.provenance?.warning});
238
+ },
239
+ select: (match) => {
240
+ assertCurrent(document);
241
+ const candidate = match?.selection ?? match;
242
+ if (!candidate || typeof candidate !== "object") throw new Error("select() requires a search match");
243
+ if (candidate.source && candidate.source !== document.source) throw new Error("Search match belongs to another file");
244
+ const starts = [0];
245
+ for (let index = 0; index < document.content.length; index += 1) if (document.content[index] === "\\n") starts.push(index + 1);
246
+ const startLine = candidate.lineNumber;
247
+ const endLine = candidate.endLineNumber ?? startLine;
248
+ if (!Number.isInteger(startLine) || !Number.isInteger(endLine)) throw new Error("Search match has no text range");
249
+ const from = starts[startLine - 1] + candidate.startColumn;
250
+ const to = starts[endLine - 1] + candidate.endColumn;
251
+ const selected = selection(document, from, to);
252
+ if (typeof candidate.matchedText === "string" && selected.text !== candidate.matchedText) throw Object.assign(new Error("Search match is stale"), {code: "STALE_SELECTION"});
253
+ return selectionSet(document, [selected]);
254
+ },
255
+ line: (first, last = first) => {
256
+ assertCurrent(document);
257
+ if (!Number.isInteger(first) || !Number.isInteger(last) || first < 1 || last < first) throw new RangeError("Invalid line range");
258
+ const starts = [0];
259
+ for (let index = 0; index < document.content.length; index += 1) if (document.content[index] === "\\n") starts.push(index + 1);
260
+ if (last > starts.length) throw new RangeError("Line range is outside document");
261
+ return selectionSet(document, [{from: starts[first - 1], to: starts[last] === undefined ? document.content.length : starts[last], linewise: true}], {kind: "line", first, last});
262
+ },
263
+ start: () => { assertCurrent(document); return selectionSet(document, [{from: 0, to: 0, linewise: true}], {kind: "start"}); },
264
+ end: () => { assertCurrent(document); const point = document.content.length; return selectionSet(document, [{from: point, to: point, linewise: true}], {kind: "end"}); },
265
+ before: (set) => { assertCurrent(document); const selected = assertSet(document, set); return selectionSet(document, selected.map((item) => ({from: item.from, to: item.from, linewise: item.linewise === true})), {kind: "before", source: selected.provenance}); },
266
+ after: (set) => { assertCurrent(document); const selected = assertSet(document, set); return selectionSet(document, selected.map((item) => ({from: item.to, to: item.to, linewise: item.linewise === true})), {kind: "after", source: selected.provenance}); },
267
+ replace: (target, text) => { assertCurrent(document); stage(document, target, String(text)); },
268
+ remove: (target) => { assertCurrent(document); stage(document, target, ""); },
269
+ insertBefore: (target, text) => { assertCurrent(document); stage(document, target, String(text), "before"); },
270
+ insertAfter: (target, text) => { assertCurrent(document); stage(document, target, String(text), "after"); },
271
+ flush: () => flushDocument(document),
272
+ delete: () => { assertCurrent(document); operations.push({kind: "delete", path: document.source}); },
273
+ };
274
+ return Object.freeze(api);
275
+ };
276
+ const api = {
277
+ ${t.map(n=>`${n}: (args) => invoke(${JSON.stringify(n)}, args)`).join(`,
278
+ `)},
279
+ open: (path) => makeDocument(invoke("editorOpen", typeof path === "string" ? {path} : path)),
280
+ createFile: (path, content) => operations.push({kind: "create", path, content: String(content)}),
281
+ deleteFile: (path) => operations.push({kind: "delete", path}),
282
+ copyFile: (path, target, options = {}) => operations.push({kind: "copy", path, target, overwrite: options.overwrite === true}),
283
+ moveFile: (path, target, options = {}) => operations.push({kind: "move", path, target, overwrite: options.overwrite === true}),
284
+ replace: (target, text) => stageSet(target, String(text)),
285
+ remove: (target) => stageSet(target, ""),
286
+ insertBefore: (target, text) => stageSet(target, String(text), "before"),
287
+ insertAfter: (target, text) => stageSet(target, String(text), "after"),
288
+ copy: (source, destination) => stageTransfer("text-copy", source, destination),
289
+ move: (source, destination) => stageTransfer("text-move", source, destination),
290
+ flush: () => {
291
+ if (operations.length === 0) return undefined;
292
+ const pending = operations;
293
+ operations = [];
294
+ return commit(pending);
295
+ },
296
+
297
+ __finishApplyScript: () => { if (operations.length > 0) return api.flush(); },
298
+ };
299
+ return api;
300
+ })();`}c(ts,"guestBindings");import{lstat as ns,mkdir as Vr,readFile as dt,rm as Wr,writeFile as rs}from"node:fs/promises";import W from"node:path";import Ur from"fs-extra";async function qr(e,t,n,r,o={}){let s=us(t);if(s.operations.length===0)throw D("flush() requires at least one staged change");let i=new Map(s.snapshots.map(w=>[w.id,w]));if(i.size!==s.snapshots.length)throw D("Duplicate editor snapshot id");let a=new Map,d=new Set,l=new Map,u=[],p=[],h=r.cwd,f=new Set;for(let[w,g]of s.operations.entries()){let x=zr(g,i,h);if(f.has(w))continue;if(g.kind==="replace"){let E=[];for(let v=w;v<s.operations.length;v+=1){let I=s.operations[v];if(I?.kind!=="replace"||I.selection.document!==g.selection.document)break;E.push({index:v,operation:I})}if(E.length>1){for(let I of E)f.add(I.index);let v=await os(E,i,a,e,h,n,o);for(let I of v.saved)l.has(I.path)||l.set(I.path,I);u.push(...v.files),p.push(...v.operations);continue}}if(g.kind==="warning"){p.push({index:w,kind:"warning",status:"warning",effect:"not-applied",resources:x,warning:ls(g)});continue}if(x.some(E=>d.has(E))){p.push({index:w,kind:g.kind,status:"blocked",effect:"unknown",resources:x,error:{code:"DEPENDENCY_UNKNOWN",message:"A prior operation left a required resource in an unknown state."}});continue}if(g.kind==="replace"){let E=i.get(g.selection.document);if((E===void 0?[]:a.get(E.source)??[]).some(I=>lt(I,g.selection))){p.push(ye(w,g,x,D(`Overlapping selection in ${E?.source??"unknown snapshot"}`)));continue}}let R=[];try{await is(g,i,a,h),R=await Promise.all(x.map(Xr));let E=await ss(g,i,a,e,h,n);for(let v of R)l.has(v.path)||l.set(v.path,v);u.push(...E),p.push({index:w,kind:g.kind,status:"applied",effect:"applied",resources:x})}catch(E){let v=await Kr(R,o.restorePath);if(v.length>0){for(let I of x)d.add(I);p.push({index:w,kind:g.kind,status:"unknown",effect:"unknown",resources:x,error:Vt(E,v)})}else p.push(ye(w,g,x,E))}}let m=p.some(({effect:w})=>w==="applied"),y=m?await e.recordApplyUndo([...l.values()]):void 0;return{operation:"apply",ok:p.length>0&&p.every(({status:w})=>w==="applied"),effect:d.size>0?"unknown":m?"applied":"not-applied",...y===void 0?{}:{transaction:y},files:u,completed:[...new Set(p.filter(({effect:w})=>w==="applied").flatMap(({resources:w})=>w))],errors:p.flatMap(w=>w.status==="warning"||w.error===void 0?[]:[{source:w.resources.join(", "),...w.error}]),operations:p}}c(qr,"executeEditorTransaction");async function os(e,t,n,r,o,s,i){let a=S(e[0]),d=t.get(a.operation.selection.document),l=zr(a.operation,t,o);if(d===void 0)return{saved:[],files:[],operations:e.map(({index:x,operation:R})=>ye(x,R,l,D("Selection belongs to an unknown editor snapshot")))};let u=n.get(d.source)??[],p=[],h=new Map;for(let{index:x,operation:R}of e)try{if(jt(R,d),u.some(E=>lt(E,R.selection))||p.some(E=>lt(E,R.selection)))throw D(`Overlapping selection in ${d.source}`);p.push({from:R.selection.from,to:R.selection.to,insert:Gr(R.selection,R.text)})}catch(E){h.set(x,ye(x,R,l,E))}if(p.length===0)return{saved:[],files:[],operations:e.map(({index:x})=>S(h.get(x)))};let f=U(d.content,u).content,m;try{if(m=await dt(d.source,"utf8"),m!==f)throw de(d.source)}catch(x){for(let{index:R,operation:E}of e)h.has(R)||h.set(R,ye(R,E,l,x));return{saved:[],files:[],operations:e.map(({index:R})=>S(h.get(R)))}}let y=[await Xr(d.source)],w=[...u,...p],g=U(d.content,w);try{await Bt(r,d.source,f,g.content,o,s,!1),n.set(d.source,w);for(let{index:x,operation:R}of e)h.has(x)||h.set(x,{index:x,kind:R.kind,status:"applied",effect:"applied",resources:l});return{saved:y,files:[{source:d.source,before:f,after:g.content,action:"edited",changes:g.changes.map((x,R)=>({editIndex:R,fromA:x.fromBefore,toA:x.toBefore,fromB:x.fromAfter,toB:x.toAfter,removedText:x.removedText,insertedText:x.insertedText})),formatting:{status:"not-reported"}}],operations:e.map(({index:x})=>S(h.get(x)))}}catch(x){let R=await Kr(y,i.restorePath);for(let{index:E,operation:v}of e)h.has(E)||h.set(E,R.length===0?ye(E,v,l,x):{index:E,kind:v.kind,status:"unknown",effect:"unknown",resources:l,error:Vt(x,R)});return{saved:R.length===0?[]:y,files:[],operations:e.map(({index:E})=>S(h.get(E)))}}}c(os,"executeReplacementBatch");async function is(e,t,n,r){if(e.kind==="warning")return;if(e.kind==="text-copy"||e.kind==="text-move"){let d=e.kind==="text-move"?[...e.destinations,...e.sources]:[...e.destinations];for(let l of[...e.sources,...e.destinations])jt({kind:"replace",selection:l,text:""},t.get(l.document));for(let[l,u]of d.entries()){let p=S(t.get(u.document));if((n.get(p.source)??[]).some(f=>lt(f,u))||d.slice(0,l).some(f=>f.document===u.document&&as(f,u)))throw D(`Overlapping selection in ${p.source}`)}for(let l of new Set([...e.sources,...e.destinations].map(({document:u})=>u))){let u=S(t.get(l)),p=U(u.content,n.get(u.source)??[]).content,h;try{h=await dt(u.source,"utf8")}catch{throw de(u.source)}if(h!==p)throw de(u.source)}return}if(e.kind==="replace"){let d=t.get(e.selection.document);jt(e,d);let l=U(d.content,n.get(d.source)??[]).content,u;try{u=await dt(d.source,"utf8")}catch{throw de(d.source)}if(u!==l)throw de(d.source);return}let o=W.resolve(r,e.path),s=await Ht(o);if(e.kind==="create"){if(s!==void 0)throw D(`Create target exists: ${e.path}`);return}if(s===void 0)throw D(`Source does not exist: ${e.path}`);if(!s.isFile()||s.isSymbolicLink())throw D(`${o} is not a regular file`);if(e.kind==="delete")return;let i=W.resolve(r,e.target??"");if(o===i)throw D("Source and target are the same file");let a=await Ht(i);if(a!==void 0&&(!a.isFile()||a.isSymbolicLink()))throw D(`${i} is not a regular file`);if(a!==void 0&&e.overwrite!==!0)throw D(`Target exists: ${e.target}`)}c(is,"validateOperation");async function ss(e,t,n,r,o,s){if(e.kind==="warning")return[];if(e.kind==="text-copy"||e.kind==="text-move")return ds(e,t,n,r,o,s);if(e.kind==="replace"){let i=t.get(e.selection.document);if(i===void 0)throw D("Selection belongs to an unknown editor snapshot");let a=n.get(i.source)??[],d=[...a,{from:e.selection.from,to:e.selection.to,insert:Gr(e.selection,e.text)}],l=U(i.content,a).content,u=U(i.content,d);return await Bt(r,i.source,l,u.content,o,s,!1),n.set(i.source,d),[{source:i.source,before:l,after:u.content,action:"edited",changes:u.changes.map((p,h)=>({editIndex:h,fromA:p.fromBefore,toA:p.toBefore,fromB:p.fromAfter,toB:p.toAfter,removedText:p.removedText,insertedText:p.insertedText})),formatting:{status:"not-reported"}}]}if(e.kind==="create"){let i=W.resolve(o,e.path);return await Bt(r,i,"",e.content,o,s,!0),[{source:i,before:null,after:e.content,action:"created",changes:[],formatting:{status:"not-reported"}}]}if(await ps(e,o),(e.kind==="delete"||e.kind==="move")&&cn(W.resolve(o,e.path)),e.target!==void 0){let i=W.resolve(o,e.target);await Ht(i)!==void 0&&await r.postProcessFile(i,{cwd:o,signal:s})}return[]}c(ss,"executeOperation");function Gr(e,t){return t.length===0||e.linewise!==!0||/(?:\r\n|\r|\n)$/u.test(t)?t:t+(/(?:\r\n|\r|\n)$/u.exec(e.text)?.[0]??"")}c(Gr,"preserveLineEnding");function as(e,t){return e.from<t.to&&t.from<e.to}c(as,"rangesOverlap");function cs(e,t,n){if(t.from!==t.to||t.linewise!==!0||n.length===0)return n;let r=e.content.includes(`\r
301
+ `)?`\r
302
+ `:`
303
+ `,o=e.content.slice(0,t.from),s=e.content.slice(t.to),i=o.length>0&&!/(?:\r\n|\r|\n)$/u.test(o)?r:"",a=s.length>0&&!/(?:\r\n|\r|\n)$/u.test(n)?r:"";return i+n+a}c(cs,"transferInsert");async function ds(e,t,n,r,o,s){let i=new Map;for(let h of e.destinations){let f=S(t.get(h.document)),m=i.get(f.source)??[];m.push({from:h.from,to:h.to,insert:cs(f,h,e.text)}),i.set(f.source,m)}if(e.kind==="text-move")for(let h of e.sources){let f=S(t.get(h.document)),m=i.get(f.source)??[];m.push({from:h.from,to:h.to,insert:""}),i.set(f.source,m)}let a=[...i.keys()],d=new Map(a.map(h=>{let f=S([...t.values()].find(m=>m.source===h));return[h,U(f.content,n.get(h)??[]).content]})),l=new Map,u=await r.editTexts(a.map(h=>({source:h,read:!0})),{cwd:o,signal:s,intent:"edit"},h=>{let f=new Map;for(let m of a){if(h.get(m)!==d.get(m))throw de(m);let y=[...n.get(m)??[],...i.get(m)??[]],w=S([...t.values()].find(g=>g.source===m));l.set(m,U(w.content,y).content),f.set(m,i.get(m)??[])}return{changes:f,result:void 0}});if(u.kind==="failed")throw u.failure.cause instanceof Error?u.failure.cause:new Error(u.failure.message);let p=[];for(let h of a){let f=S([...t.values()].find(w=>w.source===h)),m=[...n.get(h)??[],...i.get(h)??[]];n.set(h,m);let y=U(f.content,m);p.push({source:h,before:S(d.get(h)),after:S(l.get(h)),action:"edited",changes:y.changes.map((w,g)=>({editIndex:g,fromA:w.fromBefore,toA:w.toBefore,fromB:w.fromAfter,toB:w.toAfter,removedText:w.removedText,insertedText:w.insertedText})),formatting:{status:"not-reported"}})}return p}c(ds,"executeTextTransfer");async function Bt(e,t,n,r,o,s,i){let a=await e.editTexts([{source:t,read:!0,...i&&{allowReadFailure:!0}}],{cwd:o,signal:s,intent:"edit"},d=>{if((d.get(t)??"")!==n)throw de(t);return{changes:new Map([[t,[{from:0,to:n.length,insert:r}]]]),result:void 0}});if(a.kind==="failed")throw a.failure.cause instanceof Error?a.failure.cause:new Error(a.failure.message)}c(Bt,"editOne");function jt(e,t){if(t===void 0)throw D("Selection belongs to an unknown editor snapshot");let{from:n,to:r,text:o}=e.selection;if(!Number.isInteger(n)||!Number.isInteger(r)||n<0||r<n||r>t.content.length)throw D(`Selection ${n}-${r} is outside ${t.source}`);if(t.content.slice(n,r)!==o)throw D(`Selection text does not match ${t.source}`)}c(jt,"validateSelection");function lt(e,t){return t.from<e.to&&e.from<t.to}c(lt,"overlaps");function zr(e,t,n){if(e.kind==="text-copy"||e.kind==="text-move")return[...new Set([...e.sources,...e.destinations].flatMap(r=>{let o=t.get(r.document);return o===void 0?[]:[W.resolve(n,o.source)]}))];if(e.kind==="warning"){let r=t.get(e.document);return r===void 0?[]:[W.resolve(n,r.source)]}if(e.kind==="replace"){let r=t.get(e.selection.document);return r===void 0?[]:[W.resolve(n,r.source)]}return[W.resolve(n,e.path),..."target"in e&&e.target!==void 0?[W.resolve(n,e.target)]:[]]}c(zr,"operationResources");function ls(e){if(e.warning!==null&&typeof e.warning=="object"){let t=e.warning;return{code:typeof t.code=="string"?t.code:"EMPTY_SELECTION",message:typeof t.message=="string"?t.message:"SelectionSet is empty; no edit was applied.",...t.presentation!==void 0&&{presentation:t.presentation}}}return{code:"EMPTY_SELECTION",message:e.query===void 0?"SelectionSet is empty; no edit was applied.":`SelectionSet for "${e.query}" is empty; no edit was applied.`}}c(ls,"warningDetails");function ye(e,t,n,r){return{index:e,kind:t.kind,status:"failed",effect:"not-applied",resources:n,error:Vt(r)}}c(ye,"failed");function Vt(e,t=[]){let n=e!==null&&typeof e=="object"&&"code"in e?String(e.code):"OPERATION_FAILED",r=e instanceof Error?e.message:String(e);return{code:t.length?"ROLLBACK_INCOMPLETE":n,message:t.length?`${r}; rollback failed: ${t.join("; ")}`:r}}c(Vt,"codedError");function us(e){let t=Fe(e,"flush() transaction"),n=Ut(t.snapshots,"snapshots").map((o,s)=>{let i=Fe(o,`snapshot ${s+1}`);return{id:Q(i.id,"snapshot id"),source:Q(i.source,"snapshot source"),content:he(i.content,"snapshot content")}}),r=Ut(t.operations,"operations").map((o,s)=>{let i=Fe(o,`operation ${s+1}`),a=Q(i.kind,"operation kind");if(a==="replace"){let d=Fe(i.selection,"selection");return{kind:a,selection:{document:Q(d.document,"selection document"),from:ut(d.from,"selection from"),to:ut(d.to,"selection to"),text:he(d.text,"selection text"),...d.linewise===!0&&{linewise:!0}},text:he(i.text,"replacement text")}}if(a==="text-copy"||a==="text-move")return{kind:a,sources:Hr(i.sources,"transfer sources"),destinations:Hr(i.destinations,"transfer destinations"),text:he(i.text,"transfer text")};if(a==="warning")return{kind:a,document:Q(i.document,"warning document"),...typeof i.query=="string"&&{query:i.query},...i.warning!==void 0&&{warning:i.warning}};if(a==="create")return{kind:a,path:Q(i.path,"create path"),content:he(i.content,"create content")};if(a==="delete")return{kind:a,path:Q(i.path,"delete path")};if(a==="copy"||a==="move")return{kind:a,path:Q(i.path,`${a} path`),target:Q(i.target,`${a} target`),...i.overwrite===!0&&{overwrite:!0}};throw D(`Unknown transaction operation: ${a}`)});return{snapshots:n,operations:r}}c(us,"parseRequest");function Hr(e,t){return Ut(e,t).map((n,r)=>{let o=Fe(n,`${t} ${r+1}`);return{document:Q(o.document,"selection document"),from:ut(o.from,"selection from"),to:ut(o.to,"selection to"),text:he(o.text,"selection text"),...o.linewise===!0&&{linewise:!0}}})}c(Hr,"selections");function Fe(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw D(`${t} must be an object`);return e}c(Fe,"record");function Ut(e,t){if(!Array.isArray(e))throw D(`${t} must be an array`);return e}c(Ut,"array");function Q(e,t){if(typeof e!="string"||e.length===0)throw D(`${t} must be a non-empty string`);return e}c(Q,"string");function he(e,t){if(typeof e!="string")throw D(`${t} must be a string`);return e}c(he,"text");function ut(e,t){if(!Number.isInteger(e))throw D(`${t} must be an integer`);return e}c(ut,"integer");async function ps(e,t){let n=W.resolve(t,e.path);if(e.kind==="delete"){await Wr(n);return}let r=W.resolve(t,e.target??"");await Vr(W.dirname(r),{recursive:!0}),e.kind==="copy"?await Ur.copy(n,r,{overwrite:e.overwrite===!0,errorOnExist:!0}):await Ur.move(n,r,{overwrite:e.overwrite===!0})}c(ps,"performFileOperation");async function Xr(e){try{return{path:e,existed:!0,bytes:await dt(e)}}catch(t){if(pt(t,"ENOENT"))return{path:e,existed:!1};throw t}}c(Xr,"savePath");async function Kr(e,t=fs){let n=[];for(let r of[...e].reverse())try{await t(r)}catch(o){if(!r.existed&&(pt(o,"ENOENT")||pt(o,"ENOTDIR")))continue;n.push(`${r.path}: ${o instanceof Error?o.message:String(o)}`)}return n}c(Kr,"rollback");async function fs(e){e.existed?(await Vr(W.dirname(e.path),{recursive:!0}),await rs(e.path,e.bytes??new Uint8Array)):await Wr(e.path,{force:!0})}c(fs,"restoreSavedPath");async function Ht(e){try{return await ns(e)}catch(t){if(pt(t,"ENOENT"))return;throw t}}c(Ht,"optionalStat");function pt(e,t){return e!==null&&typeof e=="object"&&"code"in e&&e.code===t}c(pt,"isCode");function D(e){return Object.assign(new Error(e),{code:"INVALID_TRANSACTION"})}c(D,"invalid");function de(e){return Object.assign(new Error(`Snapshot changed before flush(): ${e}`),{code:"STALE_SNAPSHOT"})}c(de,"stale");function Qr(e,t){let n=new at,r=dn(),o=e.lastResolvedSource,s={async execute(i,a,d,l){let u=i,p=u==="read"||u==="search"||u==="diff"||u==="editorOpen"?"read":"mutation",h=!1,f=c(async()=>{let m=a,y=m.snapshot,w=y?.content;if(y===void 0||typeof y.id!="string"||typeof y.source!="string"||typeof w!="string"||typeof m.query!="string")throw le("INVALID_ARGUMENTS","Invalid mutation-target resolution request");let g;try{g=await e.editor.resolveAnchorInText({source:y.source,content:w,value:m.query,cwd:t.cwd,signal:d})}catch(R){if(!(R instanceof N))throw R;let E=new J("apply","target",y.source,m.query,R),v=await Oe(e.editor,{code:"RESOLVE_FAILED",source:y.source,message:R.message,cause:E},{...t,signal:d});return{selections:[],warning:{code:"EMPTY_SELECTION",message:v.content.filter(I=>I.type==="text").map(I=>I.text).join(`
304
+ `),presentation:{anchorRecoveries:v.details.anchorRecoveries}}}}let x=gs(w);if(!V.is(g)){let R=x[g.lineNumber-1];if(R===void 0)throw le("INVALID_SELECTION","Anchor line is outside the opened snapshot");let E=x[g.lineNumber]??w.length;return{selections:[{document:y.id,from:R,to:E,text:w.slice(R,E),linewise:!0}]}}return{selections:g.ranges.map(R=>{let E=Jr(x,R.start.lineNumber,R.start.column),v=Jr(x,R.end.lineNumber,R.end.column);return{document:y.id,from:E,to:v,text:w.slice(E,v),...R.linewise===!0&&{linewise:!0}}})}},"resolveMutationTarget");if(u==="editorResolve")return await f();try{if(u==="editorApply"){let x;try{x=await qr(e.editor,a,d,t)}catch(A){let M=A!==null&&typeof A=="object"&&"details"in A?A.details:void 0;if(M!==null&&typeof M=="object"&&"files"in M&&Array.isArray(M.files))for(let T of M.files)typeof T=="string"&&r.forget(T);throw A}let R=a.snapshots??[],E=new Set([...x.files.map(A=>A.source),...x.completed]),v=await Promise.all(R.filter(A=>E.has(A.source)).map(async A=>{let M=await e.read.read({path:A.source},{cwd:t.cwd,signal:d},"script"),T=M.script;return!M.isError&&T?.kind==="text"&&typeof T.content=="string"?{id:A.id,source:M.details.source??T.source,content:T.content,lines:T.lines}:{id:A.id,unavailable:!0}})),I={...x,snapshots:v};n.record(l,"mutation",I),h=!0;for(let A of x.files)n.updateFile(A.source,A.before,A.after),o=A.source;return I}if(u==="editorOpen"){if(!Yr.Check(Tt,a))throw le("INVALID_ARGUMENTS","Invalid arguments for open");let x=await e.read.read(a,{cwd:t.cwd,signal:d},"script"),R=x.script;if(x.isError||x.details.resolvedBy!=="filesystem"||R?.kind!=="text"||typeof R.content!="string")throw le("NOT_EDITABLE_TEXT","open() requires one local text file");let E={id:l,source:x.details.source??R.source,content:R.content,lines:R.lines};return n.record(l,"read",E,x),h=!0,o=E.source,e.rememberRead?.(x),E}if(u==="diff"){let x=await Tn(e.read,a,{cwd:t.cwd,signal:d});return n.record(l,"read",x,Rn(x)),x}let m=u==="read"?Tt:yn;if(!Yr.Check(m,a))throw le("INVALID_ARGUMENTS",`Invalid arguments for ${u}`);if(u==="read"){let x=await e.read.read(a,{cwd:t.cwd,signal:d},"script"),R={...x.script??{kind:"native",source:x.details.source,blocks:x.content},ok:!x.isError&&x.details.failure===void 0};if(n.record(l,p,R,x),h=!0,x.isError||x.details.failure)throw le(ms(x.details.failure),x.details.failure?.message??"Read failed",R);return o=x.details.source??o,e.rememberRead?.(x),R}let y=await e.search.search(a,{cwd:t.cwd,signal:d},"script"),w=y.details.failure,g={...y.script,ok:w===void 0,...w&&{error:w}};if(n.record(l,p,g,{content:y.content,details:{}}),h=!0,w!==void 0)throw le("SEARCH_FAILED","Search failed",w);return g}catch(m){throw h||n.record(l,p,{operation:i,ok:!1,error:Le(m)}),m}},async result(i,a){n.add(i,a)}};return{host:{...s,execute:c((...i)=>r.run(()=>s.execute(...i)),"execute")},results:n,async finish(){await e.editor.enqueueFileOperation(()=>r.finish(i=>{let a=i.after.source,d=n.mutationPresentation(a)?.data,l=i.postEditContributions.map(u=>u.data).findLast(We)?.formatting;!d&&i.before.content===i.after.content&&!l?.formatter||(n.updateFile(a,i.before.content,i.after.content),n.rememberMutation(a,new ee({ok:!0,path:a,...d,afterContent:i.after.content,afterDocument:i.after,diffStatuses:i.postEditContributions.map(u=>u.data).filter(be).flatMap(u=>u.diffStatuses),formatting:l??{status:"not-reported"}})))}))}}}c(Qr,"createApplyExecution");function gs(e){let t=[0];for(let n=0;n<e.length;n+=1)e[n]===`
305
+ `&&t.push(n+1);return t}c(gs,"lineStarts");function Jr(e,t,n){return(e[t-1]??0)+n}c(Jr,"positionOffset");function le(e,t,n){return Object.assign(new Error(t),{code:e,details:n})}c(le,"failure");function ms(e){let t=e?.cause;return t!==null&&typeof t=="object"&&"code"in t&&typeof t.code=="string"?t.code:e?.code??"READ_FAILED"}c(ms,"readFailureCode");import{DEFAULT_MAX_BYTES as Zr,DEFAULT_MAX_LINES as eo,truncateHead as Wt}from"@earendil-works/pi-coding-agent";async function ro(e,t,n,r={cwd:process.cwd()}){let o=e.select(),s=o.explicit.map(y=>({content:xe(y.kind==="operation"?y.presentation??y.value:y.value),read:y.kind==="operation"?y.presentation??no(y.value):void 0})),i=s.flatMap(y=>y.content),a=o.automatic.filter(({kind:y})=>y==="mutation");for(let y of o.automatic)if(y.kind==="read"||hs(y.value)||Te(y.value)||y.value!==null&&typeof y.value=="object"&&"kind"in y.value&&(y.value.kind==="file-operation"||y.value.kind==="index-operation")){let w={content:xe(y.presentation??y.value),read:y.kind==="read"?y.presentation??no(y.value):void 0};s.push(w),i.push(...w.content)}for(let y of a){let w=y.value;if(!Te(w)&&w!==null&&typeof w=="object"&&"metadata"in w){let g={content:xe(w.metadata),read:void 0};s.push(g),i.push(...g.content)}}let d=i.length,l=vn(e);l.length>0&&i.push(new X(l).toTextContent()),n!==void 0&&i.push(te(to(n))),i.length===0&&i.push(te("No operations or explicit results."));let u=qt(i);if(!Wt(u).truncated)return{content:i,level:"full",mutations:l};let p=await t.saveTemporary(u),h=`
306
+
307
+ Full Apply output: ${p}. Read this reference with offset/limit for more.`;if(t.reduceOutput!==void 0&&!r.signal?.aborted){let y=[],w=s.flatMap(oo),g=Math.max(1,w.filter(x=>x.read!==void 0).length);for(let x of w){let R;if(x.read!==void 0)try{R=await t.reduceOutput(x.read,r,{maxBytes:Math.floor((Zr-Buffer.byteLength(h))/g),maxLines:Math.floor((eo-3)/g)})}catch{}y.push(...R?.content??x.content)}if(y.push(...i.slice(d)),y.push(te(h.trimStart())),!Wt(qt(y)).truncated)return{content:y,level:"compact",temporarySource:p,mutations:l}}let f=[`Apply output reduced: ${o.automatic.length} automatic results, ${o.explicit.length} explicit results, ${o.files.length} final files.`,...n===void 0?[]:[to(n)],...o.automatic.filter(({value:y})=>Te(y)).map(({value:y,presentation:w})=>qt(xe(w??y))),...o.files.map(({source:y})=>y)].join(`
308
+ `),m=Wt(f,{maxBytes:Zr-Buffer.byteLength(h),maxLines:eo-3}).content;return{content:[te(m+h),...i.filter(y=>y.type==="image")],level:"summary",temporarySource:p,mutations:l}}c(ro,"renderApplyOutput");function te(e){return{type:"text",text:e}}c(te,"text");function qt(e){return e.filter(t=>t.type==="text").map(t=>t.text).join(`
309
+
310
+ `)}c(qt,"textContent");function oo(e){let t=e.read?.details.resources;return t?.length?t.flatMap(n=>oo({content:n.content,read:n})):[e]}c(oo,"expandReadSection");function hs(e){return e!==null&&typeof e=="object"&&"operations"in e&&Array.isArray(e.operations)&&e.operations.some(t=>t!==null&&typeof t=="object"&&"status"in t&&t.status==="warning")}c(hs,"hasOperationWarnings");function Te(e){return e!==null&&typeof e=="object"&&"ok"in e&&e.ok===!1}c(Te,"isFailure");function to(e){let t=Le(e);return io(t.code,t.message)}c(to,"formatError");function io(e,t){let r={NOT_FOUND:"The requested text or selection was not found. Read the current file and select existing text.",AMBIGUOUS_MATCH:"The selection matched more than once. Use a larger unique fragment or a current candidate anchor.",STALE_EDITOR:"This editor handle was already committed. Open the file again before staging more changes.",STALE_SELECTION:"The search selection no longer matches the file. Search again and use the fresh match.",INVALID_SELECTION:"The selected line or range is invalid. Read the file and select a range inside its current bounds.",STALE_SNAPSHOT:"A touched file changed after it was opened. Open it again and rebuild the transaction.",INVALID_TRANSACTION:"The staged operations conflict or overlap. Build non-overlapping selections from the original snapshots.",TRANSACTION_FAILED:"The commit failed after it started. Check the reported rollback state before retrying.",EEXIST:"The destination already exists. Choose another path or explicitly enable overwrite.",ENOENT:"A source path does not exist. Check the path and retry.",RUN_PARSE_ERROR:"The Apply JavaScript could not be parsed. Fix the reported syntax and run it again.",RUN_RUNTIME_ERROR:"The Apply JavaScript failed. Fix the reported operation or API usage and run it again."}[e];return r===void 0?`${e}: ${t}`:`${e}: ${t}
311
+ ${r}`}c(io,"formatApplyFailure");function xe(e){if(z(e))return e.map(t=>t.type==="custom"?te(JSON.stringify(t)):t);if(e!==null&&typeof e=="object"&&"operation"in e&&typeof e.operation=="string"){let t=[`${e.operation}: ${Te(e)&&"effect"in e&&e.effect==="applied"?"partially applied":"effect"in e?String(e.effect):Te(e)?"failed":"completed"}`];return"path"in e&&typeof e.path=="string"&&t.push(e.path),"target"in e&&typeof e.target=="string"&&t.push(`Target: ${e.target}`),"operations"in e&&Array.isArray(e.operations)?t.push(...e.operations.map(ys)):"errors"in e&&Array.isArray(e.errors)&&t.push(...e.errors.map(ft)),"error"in e&&t.push(ft(e.error)),Te(e)&&"completed"in e&&Array.isArray(e.completed)&&e.completed.length>0&&t.push(`Affected resources: ${e.completed.join(", ")}`),[te(t.join(`
312
+ `)),..."metadata"in e?xe(e.metadata):[]]}return typeof e=="string"?[te(e)]:e!==null&&typeof e=="object"&&"content"in e&&z(e.content)?e.content.map(t=>t.type==="custom"?te(JSON.stringify(t)):t):[te(e===void 0?"undefined":JSON.stringify(e,null,2))]}c(xe,"renderValue");function no(e){if(!(e===null||typeof e!="object"||!("source"in e)||typeof e.source!="string"||!("lines"in e)||!Array.isArray(e.lines)||!("content"in e)||!z(e.content)))return{content:xe(e),details:e}}c(no,"asReadResult");function ys(e){if(e===null||typeof e!="object")return String(e);let t="index"in e?Number(e.index)+1:"?",n="kind"in e?String(e.kind):"operation",r="status"in e?String(e.status):"unknown",o="warning"in e?` \u2014 ${ft(e.warning)}`:"error"in e?` \u2014 ${ft(e.error)}`:"";return`${t}. ${n}: ${r}${o}`}c(ys,"formatOperationOutcome");function ft(e){if(e===null||typeof e!="object")return String(e);let t="source"in e?String(e.source):void 0,n="code"in e?String(e.code):"OPERATION_FAILED",r="message"in e?String(e.message):"The operation failed.";return[t,io(n,r)].filter(Boolean).join(": ")}c(ft,"formatReceiptError");async function ao(e,t){let n,r;await je(e,{id:"apply",protocol:_e,apiVersion:Be,setup(s){n=s}}),await hn(e,{id:"apply",protocol:gn,apiVersion:mn,setup(s){r=s}});let o=Br();e.registerTool({name:"apply",label:"Apply",renderShell:"self",renderCall:c((s,i,a)=>(t.getToolRenderer("apply")?.renderCall??bn)(s,i,a),"renderCall"),renderResult:c((...s)=>(t.getToolRenderer("apply")?.renderResult??Sn)(...s),"renderResult"),promptSnippet:"Compose guarded multi-file editor transactions with JavaScript",description:"Use apply to run read-only IDE operations and snapshot-guarded editor transactions in JavaScript. Output has one 2000-line/50KB budget. No shell, imports or resume."+Dr(),promptGuidelines:[],parameters:so.Object({source:so.String({description:"JavaScript function body. Call IDE functions directly without await; each call finishes before the next statement. Read-only results are recorded automatically. The UI may compact written tool calls or format a display copy; execution uses this source unchanged."})}),async execute(s,{source:i},a,d,l){if(n===void 0||r===void 0)throw new Error("Apply requires the read and search extensions");let u=Qr({editor:t,read:n,search:r,lastResolvedSource:ze(e)?.source,rememberRead:c(g=>Ge(e,g.details),"rememberRead")},l),p=Nr(i),h=!1,f;try{await jr(i,u.host,a,void 0,o)}catch(g){h=!0,f=g}try{await u.finish()}catch(g){h=!0,f??=g}let m=await ro(u.results,n,f,{cwd:l.cwd,signal:a}),y=u.results.mutationValues().flatMap(g=>g!==null&&typeof g=="object"&&"transaction"in g&&typeof g.transaction=="string"&&t.hasApplyUndo(g.transaction)?[g.transaction]:[]);return{content:[...m.content,...y.map(g=>({type:"text",text:`Undo transaction: ${g}`}))],details:{failed:h,displaySource:await p,outputLevel:m.level,display:An(u.results,m,f,l.cwd),temporarySource:m.temporarySource,files:u.results.select().files.map(({source:g})=>g),transactions:y}}}}),e.on("tool_result",s=>{if(s.toolName==="apply"&&s.details&&typeof s.details=="object"&&"failed"in s.details&&s.details.failed)return{isError:!0}})}c(ao,"registerApply");async function Gt(e){let t=new Et,n=c(()=>{bt(e),At(e,t.annotate)},"connectInterceptionRendering");n(),e.on("session_start",n),e.on("session_shutdown",()=>{bt(e),At(e),t.clear()});let r=new Set,o=Ir((d,l)=>{r.add(d.name),e.registerTool(ir(l,d,t,()=>ze(e)?.source))});gr(o,t.resolveArguments),e.on("tool_result",d=>{if(Ge(e,d.details),r.has(d.toolName)&&xs(d.details))return{isError:!0}});let s;await je(e,{protocol:_e,apiVersion:Be,id:"text-anchor-recovery",setup(d){s=d,d.addTargetResolver({resolver:o.textTargetResolver()}),d.addFragmentResolver(Fr(o)),d.describe("path#anchor \u2014 source around a returned line or scope anchor, e.g. notes.txt#12#A4F0. SEARCH# references go directly in path, without a file prefix. offset/limit select context relative to each location; output keeps original line numbers.")}}),Mn(o,(d,l)=>{if(s===void 0)throw new Error("Text anchor recovery requires pi-agent-read");return s.read({...d,views:["anchors"]},l)});let i=e.events.on(nn,d=>{if(!on(d))throw new Error("Invalid pi-agent-text-editor plugin registration request");d.accept(o.registerPlugin(d.plugin))});e.on("session_shutdown",i);let a=e.events.on(ln,d=>{if(!pn(d))throw new Error("Invalid pi-agent-text-editor post-edit handler registration request");d.accept(o.registerPostEditHandler(d.registration))});return e.on("session_shutdown",a),e.events.emit(tn,{protocol:He,apiVersion:Ve}),await o.waitForPendingPlugins(),e.getFlag("pi-agent-ide-no-apply")!==!0&&await ao(e,o),wn(e,o,()=>s),o}c(Gt,"registerTextEditorCore");function xs(e){if(!Re(e))return!1;let t=e.batchRecovery;if(Re(t)&&typeof t.state=="string"&&t.state!=="completed")return!0;let n=Re(e.metadata)?e.metadata.semanticAction:void 0;if(Re(n)&&n.ok===!1)return!0;let r=e.results;return Array.isArray(r)&&r.some(o=>Re(o)?(Re(o.data)?o.data:o).ok===!1:!1)}c(xs,"isFailedTextMutationResult");function Re(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}c(Re,"isRecord");import{Type as ws}from"typebox";import{Type as q}from"typebox";function re(e){return q.Optional(q.String({description:e}))}c(re,"sourcePathProperty");function oe(){return{start:q.Optional(q.String({description:"Anchor or unique exact text. Alone, selects that fragment; a line anchor selects only its line. Omit when path already selects text through a supported resource reference. With end, selects a whole-line range."})),end:q.Optional(q.String({description:"Optional anchor or unique exact text. Range includes start's first line through end's last line, even for SEARCH :match. Mixed types allowed; boundaries must be unique, in one file, and forward-ordered. Omit when start already selects the intended content; do not repeat start. The end line is included, not a stopping point before it."}))}}c(oe,"sourceRangeProperties");function gt(){return{target:q.Optional(q.String({description:"Target resource reference or file path. Required for a whole-file operation; defaults to the source for selected text."})),targetStart:q.Optional(q.String({description:"Registered anchor or unique exact text in the destination. Required unless target already selects one destination range. Without targetEnd, inserts after the last containing line, keeping the selected text. With targetEnd, replacement starts at the first containing line. SEARCH :match also uses these line boundaries."})),targetEnd:q.Optional(q.String({description:"Optional inclusive destination end. Replaces whole lines through the last line containing this anchor, including SEARCH :match. May differ in type from targetStart; both must resolve uniquely in the target file and in forward order. Omit to insert after targetStart instead."})),overwrite:q.Optional(q.Boolean({description:"Allow replacing an existing regular target file. Defaults to false."}))}}c(gt,"targetProperties");function ue(e,t){let n=[...e.values()];if(!n.every(r=>!V.is(r))){if(n.some(r=>!V.is(r)))throw new Error(`Anchor ${t} resolved to incompatible selection types.`);return e}}c(ue,"textSelections");function co(e,t){if(ue(e,t)!==void 0)throw new Error(`Anchor ${t} cannot use a search selection as a line endpoint.`);if(e.size!==1)throw new Error(`Anchor ${t} must resolve in one resource.`);return S(e.values().next().value)}c(co,"lineAnchor");function we(e,t,n,r=!1){if(t.size!==1)throw new Error(`Anchor ${n} must resolve in one resource.`);let[o,s]=S(t.entries().next().value);if(V.is(s)){if(s.ranges.length!==1)throw new Error(`Anchor ${n} must select one match for this operation.`);let a=S(s.ranges[0]),d=e.documentFor(o),l=zt(e,o,a),u=r?Xt(a):Rs(a);if(u!==void 0){let p=d.lineRange(a.start.lineNumber,u);return{source:o,...p,selection:!1,preservesTrailingLineBreak:!0,linewiseStartLine:a.start.lineNumber,linewiseEndLine:u}}return{source:o,...l,selection:!0,preservesTrailingLineBreak:!1}}let i=e.documentFor(o).lineRange(s.lineNumber,s.lineNumber);return{source:o,...i,selection:!1,preservesTrailingLineBreak:!0,linewiseStartLine:s.lineNumber,linewiseEndLine:s.lineNumber}}c(we,"singleAnchorSpan");function Z(e,t,n,r,o){let s=we(e,t,r),i=n===void 0?s:we(e,n,o);if(s.source!==i.source)throw new Error(`Anchors ${r} and ${o} must resolve in one resource.`);if(s.from>i.from)throw new Error(`Anchor ${r} must not come after ${o}.`);if(n===void 0)return s;let a=we(e,t,r,!0),d=we(e,n,o,!0);return{source:a.source,from:a.from,to:d.to,selection:!1,preservesTrailingLineBreak:!0}}c(Z,"anchorSpanRange");function mt(e,t,n){let r=e.documentFor(t).content.includes(`\r
313
+ `)?`\r
314
+ `:`
315
+ `;return n.replace(/\r\n|\r|\n/gu,r)}c(mt,"targetText");function pe(e,t,n){if(n==="")return Ne(e,t);let r=e.documentFor(t.source),o=mt(e,t.source,n),s=r.text(t);if(t.preservesTrailingLineBreak&&!/(?:\r\n|\r|\n)$/u.test(o)){let i=/(?:\r\n|\r|\n)$/u.exec(s)?.[0];i!==void 0&&(o+=i)}return{from:t.from,to:t.to,insert:o}}c(pe,"replaceAnchorSpan");function Ne(e,t){let n=e.documentFor(t.source).content;if(!t.selection&&t.to===n.length&&t.from>0&&!/(?:\r\n|\r|\n)$/u.test(n)){let r=n.slice(0,t.from),o=/(?:\r\n|\r|\n)$/u.exec(r);if(o!==null)return{from:t.from-o[0].length,to:t.to,insert:""}}return{from:t.from,to:t.to,insert:""}}c(Ne,"deleteAnchorSpan");function Ee(e,t,n,r){let o=we(e,t,n,!0),s=mt(e,o.source,r),i=o.linewiseEndLine??co(t,n).lineNumber;return[o.source,e.documentFor(o.source).insertAfterLine(i,s)]}c(Ee,"insertionAfterAnchor");function lo(e,t,n,r){let o=we(e,t,n,!0),s=mt(e,o.source,r),i=o.linewiseStartLine??co(t,n).lineNumber;return[o.source,e.documentFor(o.source).insertBeforeLine(i,s)]}c(lo,"insertionBeforeAnchor");function Ts(e){let t=[];for(let n of e){let r=t.at(-1);r?.linewise===!0&&n.linewise===!0&&r.end.lineNumber===n.start.lineNumber&&r.end.column===n.start.column?t[t.length-1]={...r,end:n.end}:t.push(n)}return t}c(Ts,"coalesceAdjacentLinewiseRanges");function ht(e,t,n){return new Map([...t].map(([r,o])=>[r,(n.length===0?Ts(o.ranges):o.ranges).map(s=>{let i=zt(e,r,s);return pe(e,{source:r,...i,selection:s.linewise!==!0,preservesTrailingLineBreak:s.linewise===!0},n)})]))}c(ht,"selectionChanges");function uo(e,t,n,r=!1){return new Map([...t].map(([o,s])=>[o,[...new Set(s.ranges.map(i=>(zt(e,o,i),r?i.start.lineNumber:Xt(i))))].map(i=>{let a=e.documentFor(o),d=mt(e,o,n);return r?a.insertBeforeLine(i,d):a.insertAfterLine(i,d)})]))}c(uo,"insertionChanges");function zt(e,t,n){return e.documentFor(t).range(n.start.lineNumber,n.start.column,n.end.lineNumber,n.end.column)}c(zt,"selectionRange");function Rs(e){if(e.linewise===!0)return Xt(e)}c(Rs,"linewiseSelectionEndLine");function Xt(e){return e.end.column===0&&e.end.lineNumber>e.start.lineNumber?e.end.lineNumber-1:e.end.lineNumber}c(Xt,"containingEndLine");var Es=ws.Object({path:re("Source file path, or a returned SEARCH# reference selecting the text to copy"),...oe(),...gt()},{additionalProperties:!1}),po={name:"copy",wholeFileOperation:"copy",description:"Use copy to copy one regular file, or to duplicate selected text within or between files.",promptSnippet:"Copy regular files, or copy selected text within or between files",parameters:Es,source:{field:"path",inherited:!0,targets:[{field:"target",fallbackTo:"path"}]},anchors:[{field:"start",sourceField:"path",kinds:[_,B]},{field:"end",sourceField:"path",kinds:[_,B],optional:!0},{field:"targetStart",sourceField:"target",kinds:[_,B]},{field:"targetEnd",sourceField:"target",kinds:[_,B],optional:!0}],pair:["start","end"],mutate:c(async(e,t)=>{let n=await e.resolveAnchors("start"),r=t.end===void 0?void 0:await e.resolveAnchors("end"),o=Z(e,n,r,"start","end"),s=e.documentFor(o.source).text(o),i=await e.resolveAnchors("targetStart");if(t.targetEnd===void 0){let[l,u]=Ee(e,i,"targetStart",s);return{edits:new Map([[l,{changes:[u],action:"edited"}]])}}let a=await e.resolveAnchors("targetEnd"),d=Z(e,i,a,"targetStart","targetEnd");return{edits:new Map([[d.source,{changes:[pe(e,d,s)],action:"edited"}]])}},"mutate")};import{Type as vs}from"typebox";var As=vs.Object({path:re("Source resource reference or file path. A returned SEARCH# reference can select deletion ranges."),...oe()},{additionalProperties:!1}),fo={name:"delete",wholeFileOperation:"delete",description:"Use delete to permanently delete one regular file when path is supplied without text selectors, or to remove selected text. Whole-file deletion rejects directories and symlinks.",promptSnippet:"Delete regular files, or delete selected text using exact matches or anchors",parameters:As,source:{field:"path",inherited:!0},anchors:[{field:"start",sourceField:"path",kinds:[_,B],optional:!0},{field:"end",sourceField:"path",kinds:[_,B],optional:!0}],pair:["start","end"],mutate:c(async(e,t)=>{let n=await e.resolveAnchors("start"),r=ue(n,"start");if(t.end===void 0&&r!==void 0){let i=ht(e,r,"");return{edits:new Map([...i].map(([a,d])=>[a,{changes:d,action:"edited"}]))}}let o=t.end===void 0?void 0:await e.resolveAnchors("end"),s=Z(e,n,o,"start","end");return{edits:new Map([[s.source,{changes:[Ne(e,s)],action:"edited"}]])}},"mutate")};import{Type as ie}from"typebox";var bs=ie.Object({path:ie.Optional(ie.String({description:"Source resource reference or file path. A returned SEARCH# reference can select insertion positions."})),anchor:ie.Optional(ie.String({description:"Registered anchor or unique exact text locating the insertion. Required unless path already supplies a SEARCH selection. Inserts after the last containing line by default, or before the first containing line when before is true. This includes SEARCH :match and multiline exact text; the selected text is kept. Multiple matches on the same insertion line produce one insertion."})),text:ie.String({description:"New text only. The tool supplies the line boundary; do not prefix a newline just to start a new line. For example, 'NEW' inserts one line, while '\\nNEW' intentionally adds a blank line before it. A missing trailing newline is supplied before following text; additional newlines remain intentional blank lines. When appending after an unterminated final line, the tool supplies the separator before the new text and removes one trailing newline from the payload. Payload line endings follow the destination file's LF/CRLF style."}),before:ie.Optional(ie.Boolean({description:"Defaults to false: insert after the last containing line. True: insert before the first containing line. The anchor's text and its lines are kept."}))},{additionalProperties:!1}),go={name:"insert",description:"Use insert to add new text before or after selected lines while keeping existing text. Insertion is line-based, including for exact-text and SEARCH :match anchors.",promptSnippet:"Make precise file edits by inserting text before or after exact matches or anchors",parameters:bs,source:{field:"path",inherited:!0},anchors:[{field:"anchor",sourceField:"path",kinds:[_,B]}],mutate:c(async(e,t)=>{let n=await e.resolveAnchors("anchor"),r=ue(n,"anchor");if(r!==void 0){let a=uo(e,r,t.text,t.before);return{edits:new Map([...a].map(([d,l])=>[d,{changes:l,action:"edited"}]))}}let o=t.before===!0?lo:Ee,[s,i]=o(e,n,"anchor",t.text);return{edits:new Map([[s,{changes:[i],action:"edited"}]])}},"mutate")};import{Type as Ss}from"typebox";var Cs=Ss.Object({path:re("Source file path, or a returned SEARCH# reference selecting the text to move"),...oe(),...gt()},{additionalProperties:!1}),mo={name:"move",wholeFileOperation:"move",description:"Use move to move or rename one regular file, or to relocate selected text within or between files.",promptSnippet:"Move or rename regular files, or move selected text within or between files",parameters:Cs,source:{field:"path",inherited:!0,targets:[{field:"target",fallbackTo:"path"}]},anchors:[{field:"start",sourceField:"path",kinds:[_,B]},{field:"end",sourceField:"path",kinds:[_,B],optional:!0},{field:"targetStart",sourceField:"target",kinds:[_,B]},{field:"targetEnd",sourceField:"target",kinds:[_,B],optional:!0}],pair:["start","end"],mutate:c(async(e,t)=>{let n=await e.resolveAnchors("start"),r=t.end===void 0?void 0:await e.resolveAnchors("end"),o=Z(e,n,r,"start","end"),s=e.documentFor(o.source).text(o),i=Ne(e,o),a=await e.resolveAnchors("targetStart"),d,l;if(t.targetEnd===void 0)[d,l]=Ee(e,a,"targetStart",s);else{let u=await e.resolveAnchors("targetEnd"),p=Z(e,a,u,"targetStart","targetEnd");d=p.source,l=pe(e,p,s)}if(o.source===d&&ks(i,l))throw new Error("Move target must not overlap or touch its source range.");return o.source===d?{edits:new Map([[d,{changes:[i,l],action:"edited"}]])}:{edits:new Map([[o.source,{changes:[i],action:"edited"}],[d,{changes:[l],action:"edited"}]])}},"mutate")};function ks(e,t){return e.from<=t.to&&t.from<=e.to}c(ks,"rangesTouch");import{Type as ho}from"typebox";var Ps=ho.Object({path:re("Source resource reference or file path. A returned SEARCH# reference can select replacement ranges."),...oe(),text:ho.String({description:"Replacement text. Empty text removes the selection; a whole-line selection removes its lines without inserting a blank line. Adjacent unselected lines are kept."})},{additionalProperties:!1}),yo={name:"replace",description:"Use replace to change an existing text fragment, an inclusive line range, or every selected search match.",promptSnippet:"Make precise file edits by replacing text using exact matches or anchors",parameters:Ps,source:{field:"path",inherited:!0},anchors:[{field:"start",sourceField:"path",kinds:[_,B]},{field:"end",sourceField:"path",kinds:[_,B],optional:!0}],pair:["start","end"],mutate:c(async(e,t)=>{let n=await e.resolveAnchors("start"),r=ue(n,"start");if(t.end===void 0&&r!==void 0){let i=ht(e,r,t.text);return{edits:new Map([...i].map(([a,d])=>[a,{changes:d,action:"edited"}]))}}let o=t.end===void 0?void 0:await e.resolveAnchors("end"),s=Z(e,n,o,"start","end");return{edits:new Map([[s.source,{changes:[pe(e,s,t.text)],action:"edited"}]])}},"mutate")};import{Type as Kt}from"typebox";var Ms=Kt.Object({path:Kt.String({description:"Path to the file to create or overwrite"}),content:Kt.String({description:"File content"})},{additionalProperties:!1}),xo={name:"write",description:"Use write to create a new file or deliberately replace a file's entire contents. Supply the complete new text; existing contents are overwritten.",promptSnippet:"Create or overwrite files",parameters:Ms,source:{field:"path"},anchors:[],mutate:c((e,t)=>({edits:new Map([[t.path,{changes:[e.sourceDocument.replaceAll(t.content)],action:"overwritten"}]])}),"mutate")};function To(e,t){t.addMutationTool(xo),t.addMutationTool(yo),t.addMutationTool(go),t.addMutationTool(fo),t.addMutationTool(po),t.addMutationTool(mo)}c(To,"registerTextEditorTools");async function Is(e){en(e,[await xt({id:"apply",description:"Guarded Apply scripting, selections, transactions, and file operations",triggers:[{tool:"apply"}]}),await xt({id:"editing",description:"Precise standalone text and file edits",triggers:["write","replace","insert","delete","copy","move","diff"].map(n=>({tool:n}))})]);let t=await Gt(e);kn(e),To(e,t),mr(e,t)}c(Is,"registerTextEditor");export{Is as default};