pi-agent-ide 0.7.2 → 0.7.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (157) hide show
  1. package/CHANGELOG.md +29 -0
  2. package/README.md +3 -1
  3. package/dist/{chunk-KOVPDKSJ.js → chunk-2ZMMRINH.js} +1 -1
  4. package/dist/{chunk-EURHXLN3.js → chunk-BYZSBXUK.js} +1 -1
  5. package/dist/{chunk-XDG7EQRN.js → chunk-CEX73RI5.js} +1 -1
  6. package/dist/{chunk-YWQS33DF.js → chunk-DZWTKF2K.js} +1 -1
  7. package/dist/{chunk-F6IWZKOG.js → chunk-EOKEQ3YH.js} +1 -1
  8. package/dist/{chunk-SJ4UZ4GU.js → chunk-HZ5BNF3A.js} +1 -1
  9. package/dist/{chunk-TQGE7RH6.js → chunk-NHKPP2AI.js} +2 -2
  10. package/dist/{chunk-SNF7PDDX.js → chunk-TXOTNK6B.js} +1 -1
  11. package/dist/chunk-WLZIUMJL.js +1 -0
  12. package/dist/entry-11.js +1 -1
  13. package/dist/entry-17.js +1 -1
  14. package/dist/entry-25.js +1 -1
  15. package/dist/entry-31.js +12 -12
  16. package/dist/entry-33.js +3 -2
  17. package/dist/entry-37.js +6 -6
  18. package/dist/entry-51.js +1 -1
  19. package/dist/entry-56.js +1 -1
  20. package/dist/entry-58.js +1 -1
  21. package/dist/entry-60.js +1 -1
  22. package/dist/entry-62.js +1 -1
  23. package/dist/entry-65.js +1 -1
  24. package/dist/entry-68.js +1 -1
  25. package/dist/entry-70.js +1 -1
  26. package/dist/entry-75.js +1 -1
  27. package/dist/entry-77.js +56 -51
  28. package/dist/entry-78.js +8 -7
  29. package/dist/entry-79.js +1 -1
  30. package/dist/pi-agent-ide.js +20 -20
  31. package/docs/agent-guides/editing.md +9 -2
  32. package/docs/configuration.md +21 -0
  33. package/docs/development.md +4 -0
  34. package/docs/directory-operations.md +45 -0
  35. package/docs/releases.md +8 -0
  36. package/docs/research/codemode-write-context.md +56 -0
  37. package/docs/user-hooks.md +26 -0
  38. package/node_modules/pi-agent-doctor/package.json +1 -1
  39. package/node_modules/pi-agent-documentation/package.json +1 -1
  40. package/node_modules/pi-agent-filesystem/package.json +7 -7
  41. package/node_modules/pi-agent-filesystem-image/package.json +3 -3
  42. package/node_modules/pi-agent-filesystem-jq/package.json +5 -5
  43. package/node_modules/pi-agent-filesystem-pdf/package.json +3 -3
  44. package/node_modules/pi-agent-filesystem-text/package.json +3 -3
  45. package/node_modules/pi-agent-ide-ast/package.json +13 -13
  46. package/node_modules/pi-agent-ide-ast/src/extension.ts +3 -1
  47. package/node_modules/pi-agent-ide-ast/src/overflow-handler.ts +7 -2
  48. package/node_modules/pi-agent-ide-changes/package.json +9 -8
  49. package/node_modules/pi-agent-ide-changes/src/tool-index-change.ts +16 -0
  50. package/node_modules/pi-agent-ide-formatter/package.json +3 -3
  51. package/node_modules/pi-agent-ide-languages/package.json +2 -2
  52. package/node_modules/pi-agent-ide-lint/package.json +7 -7
  53. package/node_modules/pi-agent-ide-lsp/index.ts +1 -1
  54. package/node_modules/pi-agent-ide-lsp/package.json +9 -9
  55. package/node_modules/pi-agent-ide-lsp/src/declaration-targets.ts +2 -1
  56. package/node_modules/pi-agent-image/package.json +2 -2
  57. package/node_modules/pi-agent-invariant/package.json +1 -1
  58. package/node_modules/pi-agent-pdf/package.json +2 -2
  59. package/node_modules/pi-agent-read/package.json +7 -7
  60. package/node_modules/pi-agent-resource/package.json +1 -1
  61. package/node_modules/pi-agent-search/package.json +5 -5
  62. package/node_modules/pi-agent-search-text/package.json +7 -7
  63. package/node_modules/pi-agent-text/package.json +2 -2
  64. package/node_modules/pi-agent-text-anchor-constant/package.json +3 -3
  65. package/node_modules/pi-agent-text-anchor-exact/package.json +3 -3
  66. package/node_modules/pi-agent-text-anchor-line-hash/package.json +5 -5
  67. package/node_modules/pi-agent-text-editor/package.json +9 -9
  68. package/node_modules/pi-agent-text-editor/src/api/delete-guard.ts +24 -0
  69. package/node_modules/pi-agent-text-editor/src/api/mutation-guard.ts +1 -0
  70. package/node_modules/pi-agent-text-editor/src/api/plugin-protocol.ts +4 -1
  71. package/node_modules/pi-agent-text-editor/src/core/delete-policy.ts +284 -0
  72. package/node_modules/pi-agent-text-editor/src/core/file-operation-tools.ts +32 -3
  73. package/node_modules/pi-agent-text-editor/src/core/file-operations.ts +30 -40
  74. package/node_modules/pi-agent-text-editor/src/core/file-result-targets.ts +1 -1
  75. package/node_modules/pi-agent-text-editor/src/core/file-transfers.ts +164 -0
  76. package/node_modules/pi-agent-text-editor/src/core/mutation-result/file-mutation-agent-result.ts +1 -6
  77. package/node_modules/pi-agent-text-editor/src/core/mutation-result/file-mutation-result.ts +7 -1
  78. package/node_modules/pi-agent-text-editor/src/core/native-text-edit-batch.ts +55 -12
  79. package/node_modules/pi-agent-text-editor/src/core/result-transfer.ts +39 -9
  80. package/node_modules/pi-agent-text-editor/src/core/structured-result.ts +7 -1
  81. package/node_modules/pi-agent-text-editor/src/core/temporary-directories.ts +96 -0
  82. package/node_modules/pi-agent-text-editor/src/core/text-edit-batch-registrar.ts +3 -0
  83. package/node_modules/pi-agent-text-editor/src/core/text-editor-core.ts +51 -1
  84. package/node_modules/pi-agent-text-editor/src/core/text-mutation.ts +53 -8
  85. package/node_modules/pi-agent-text-editor/src/core/write-agent-result.ts +66 -0
  86. package/node_modules/pi-agent-text-editor/src/tools/text-tool-schema-properties.ts +2 -2
  87. package/node_modules/pi-agent-text-editor/src/tools/tool-text-copy.ts +6 -4
  88. package/node_modules/pi-agent-text-editor/src/tools/tool-text-delete.ts +2 -2
  89. package/node_modules/pi-agent-text-editor/src/tools/tool-text-move.ts +6 -4
  90. package/node_modules/pi-agent-text-editor-renderer/package.json +5 -5
  91. package/node_modules/pi-agent-text-editor-renderer/src/renderer.ts +33 -18
  92. package/node_modules/pi-agent-text-editor-stale-anchor/package.json +4 -4
  93. package/node_modules/pi-agent-tool-call-interception/package.json +2 -2
  94. package/node_modules/pi-agent-tool-ui/package.json +1 -1
  95. package/node_modules/pi-agent-web/package.json +7 -7
  96. package/node_modules/pi-agent-web-html/package.json +2 -2
  97. package/node_modules/pi-agent-web-image/package.json +3 -3
  98. package/node_modules/pi-agent-web-pdf/package.json +3 -3
  99. package/node_modules/pi-agent-web-text/package.json +3 -3
  100. package/package.json +36 -35
  101. package/src/api/hooks.ts +24 -0
  102. package/src/composite/nested-tool-rendering.ts +120 -71
  103. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/package.json +7 -7
  104. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-image/package.json +3 -3
  105. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-jq/package.json +5 -5
  106. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-pdf/package.json +3 -3
  107. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-text/package.json +3 -3
  108. package/src/extensions/pi-agent-read/extensions/pi-agent-web/package.json +7 -7
  109. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-html/package.json +2 -2
  110. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-image/package.json +3 -3
  111. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-pdf/package.json +3 -3
  112. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-text/package.json +3 -3
  113. package/src/extensions/pi-agent-read/package.json +7 -7
  114. package/src/extensions/pi-agent-search/package.json +5 -5
  115. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/package.json +7 -7
  116. package/src/extensions/pi-agent-text-editor/package.json +9 -9
  117. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-constant/package.json +3 -3
  118. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-exact/package.json +3 -3
  119. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-line-hash/package.json +5 -5
  120. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-renderer/package.json +5 -5
  121. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-renderer/src/renderer.ts +33 -18
  122. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-stale-anchor/package.json +4 -4
  123. package/src/extensions/pi-agent-text-editor/src/api/delete-guard.ts +24 -0
  124. package/src/extensions/pi-agent-text-editor/src/api/mutation-guard.ts +1 -0
  125. package/src/extensions/pi-agent-text-editor/src/api/plugin-protocol.ts +4 -1
  126. package/src/extensions/pi-agent-text-editor/src/core/delete-policy.ts +284 -0
  127. package/src/extensions/pi-agent-text-editor/src/core/file-operation-tools.ts +32 -3
  128. package/src/extensions/pi-agent-text-editor/src/core/file-operations.ts +30 -40
  129. package/src/extensions/pi-agent-text-editor/src/core/file-result-targets.ts +1 -1
  130. package/src/extensions/pi-agent-text-editor/src/core/file-transfers.ts +164 -0
  131. package/src/extensions/pi-agent-text-editor/src/core/mutation-result/file-mutation-agent-result.ts +1 -6
  132. package/src/extensions/pi-agent-text-editor/src/core/mutation-result/file-mutation-result.ts +7 -1
  133. package/src/extensions/pi-agent-text-editor/src/core/native-text-edit-batch.ts +55 -12
  134. package/src/extensions/pi-agent-text-editor/src/core/result-transfer.ts +39 -9
  135. package/src/extensions/pi-agent-text-editor/src/core/structured-result.ts +7 -1
  136. package/src/extensions/pi-agent-text-editor/src/core/temporary-directories.ts +96 -0
  137. package/src/extensions/pi-agent-text-editor/src/core/text-edit-batch-registrar.ts +3 -0
  138. package/src/extensions/pi-agent-text-editor/src/core/text-editor-core.ts +51 -1
  139. package/src/extensions/pi-agent-text-editor/src/core/text-mutation.ts +53 -8
  140. package/src/extensions/pi-agent-text-editor/src/core/write-agent-result.ts +66 -0
  141. package/src/extensions/pi-agent-text-editor/src/tools/text-tool-schema-properties.ts +2 -2
  142. package/src/extensions/pi-agent-text-editor/src/tools/tool-text-copy.ts +6 -4
  143. package/src/extensions/pi-agent-text-editor/src/tools/tool-text-delete.ts +2 -2
  144. package/src/extensions/pi-agent-text-editor/src/tools/tool-text-move.ts +6 -4
  145. package/src/plugins/pi-agent-ide-ast/package.json +13 -13
  146. package/src/plugins/pi-agent-ide-ast/src/extension.ts +3 -1
  147. package/src/plugins/pi-agent-ide-ast/src/overflow-handler.ts +7 -2
  148. package/src/plugins/pi-agent-ide-changes/package.json +9 -8
  149. package/src/plugins/pi-agent-ide-changes/src/tool-index-change.ts +16 -0
  150. package/src/plugins/pi-agent-ide-debugger/index.ts +3 -1
  151. package/src/plugins/pi-agent-ide-formatter/package.json +3 -3
  152. package/src/plugins/pi-agent-ide-languages/package.json +2 -2
  153. package/src/plugins/pi-agent-ide-lint/package.json +7 -7
  154. package/src/plugins/pi-agent-ide-lsp/index.ts +1 -1
  155. package/src/plugins/pi-agent-ide-lsp/package.json +9 -9
  156. package/src/plugins/pi-agent-ide-lsp/src/declaration-targets.ts +2 -1
  157. package/dist/chunk-PKSQT6TC.js +0 -1
package/dist/entry-31.js CHANGED
@@ -1,17 +1,17 @@
1
- import{b as Ie}from"./chunk-H445SHSJ.js";import"./chunk-ZIWPKIBZ.js";import{f as Ae,g as ve}from"./chunk-XH5WN5XA.js";import{b as N,c as Le}from"./chunk-QFTBY67N.js";import{e as ne,f as re}from"./chunk-T7I2VX3J.js";import{a as oe}from"./chunk-MGCHOGQD.js";import{a as ee,b as te}from"./chunk-T6LX2RX5.js";import{a as be}from"./chunk-KOVPDKSJ.js";import{a as ge,b as he,c as ye}from"./chunk-SJ4UZ4GU.js";import"./chunk-NNCZYO4Q.js";import{d as ue}from"./chunk-IICJXZBU.js";import{a as ae}from"./chunk-BU7IZLKB.js";import{a as se,b as ie}from"./chunk-S5PL5DFQ.js";import{b as Re}from"./chunk-STBJO3Z3.js";import{e as k}from"./chunk-OB46OPMZ.js";import{a as we}from"./chunk-ZTYWHL2F.js";import{a as Se,b as xe}from"./chunk-7UGNGK7Y.js";import{a as ce,b as le,e as de}from"./chunk-PS2B6THP.js";import{G as D,I as E,J as fe,f as pe,i as me,j as M}from"./chunk-6U5OU77O.js";import{a as X,b as J,c as K,l as Y}from"./chunk-KVHDMIZS.js";import{m as W}from"./chunk-ZPT5D4VP.js";import"./chunk-KINKBPPX.js";import{j as Z}from"./chunk-M5MJP7Z2.js";import"./chunk-WZI4YC2O.js";import{e as Q}from"./chunk-N34ATN52.js";import{a as _}from"./chunk-ZC65Z3CK.js";import{a as p}from"./chunk-EI7MMDWY.js";import{readFile as at}from"node:fs/promises";var ct={cmake:"no compatible Tree-sitter parser is packaged",dockerfile:"no compatible Tree-sitter parser is packaged",julia:"no compatible Tree-sitter parser is packaged",powershell:"no compatible Tree-sitter parser is packaged",r:"no compatible Tree-sitter parser is packaged",svelte:"the container grammar is not available as an ast-grep language package",terraform:"the HCL grammar is not available as an ast-grep language package",vue:"the container grammar is not available as an ast-grep language package",xml:"no compatible Tree-sitter parser is packaged",zig:"no compatible Tree-sitter parser is packaged"},U=new Set(["c","cpp","csharp","css","dart","elixir","go","html","java","kotlin","lua","markdown","php","ruby","scala","shell","sql","swift","javascript","typescript","python","rust","json","yaml","toml"]),Oe={protocol:ee,apiVersion:1,id:"ast",setup(t){t.addSetupCheck({id:"structural-search",async inspect(e){return[...e.detectedLanguageIds].some(o=>U.has(o))?await Z({command:["ast-grep"]},e.cwd,e.env)?{}:{actions:[{id:"ast-grep-unavailable",message:"Structural search is unavailable because ast-grep was not found"}]}:{}}}),t.addCheck({id:"parsers",title:"AST",async run(e){let n=[];for(let o of e.detectedLanguageIds){let r=ct[o];if(r!==void 0){n.push({status:"skip",message:`${o} AST is unavailable: ${r}`});continue}if(!U.has(o))continue;let s=e.files.find(i=>lt(i,o));if(s!==void 0)try{let i=await at(s,"utf8"),c=await N(s,e.cwd,i.replaceAll(`\r
1
+ import{b as Ie}from"./chunk-H445SHSJ.js";import"./chunk-ZIWPKIBZ.js";import{f as Ae,g as ve}from"./chunk-XH5WN5XA.js";import{b as N,c as Le}from"./chunk-QFTBY67N.js";import{e as ne,f as re}from"./chunk-T7I2VX3J.js";import{a as oe}from"./chunk-MGCHOGQD.js";import{a as ee,b as te}from"./chunk-T6LX2RX5.js";import{a as be}from"./chunk-2ZMMRINH.js";import{a as ge,b as he,c as ye}from"./chunk-HZ5BNF3A.js";import"./chunk-NNCZYO4Q.js";import{d as ue}from"./chunk-IICJXZBU.js";import{a as ae}from"./chunk-BU7IZLKB.js";import{a as se,b as ie}from"./chunk-S5PL5DFQ.js";import{b as Re}from"./chunk-STBJO3Z3.js";import{e as k}from"./chunk-OB46OPMZ.js";import{a as we}from"./chunk-ZTYWHL2F.js";import{a as Se,b as xe}from"./chunk-7UGNGK7Y.js";import{a as ce,b as le,e as de}from"./chunk-PS2B6THP.js";import{G as D,I as E,J as fe,f as pe,i as me,j as M}from"./chunk-6U5OU77O.js";import{a as X,b as J,c as K,l as Y}from"./chunk-KVHDMIZS.js";import{m as W}from"./chunk-ZPT5D4VP.js";import"./chunk-KINKBPPX.js";import{j as Z}from"./chunk-M5MJP7Z2.js";import"./chunk-WZI4YC2O.js";import{e as Q}from"./chunk-N34ATN52.js";import{a as _}from"./chunk-ZC65Z3CK.js";import{a as p}from"./chunk-EI7MMDWY.js";import{readFile as at}from"node:fs/promises";var ct={cmake:"no compatible Tree-sitter parser is packaged",dockerfile:"no compatible Tree-sitter parser is packaged",julia:"no compatible Tree-sitter parser is packaged",powershell:"no compatible Tree-sitter parser is packaged",r:"no compatible Tree-sitter parser is packaged",svelte:"the container grammar is not available as an ast-grep language package",terraform:"the HCL grammar is not available as an ast-grep language package",vue:"the container grammar is not available as an ast-grep language package",xml:"no compatible Tree-sitter parser is packaged",zig:"no compatible Tree-sitter parser is packaged"},U=new Set(["c","cpp","csharp","css","dart","elixir","go","html","java","kotlin","lua","markdown","php","ruby","scala","shell","sql","swift","javascript","typescript","python","rust","json","yaml","toml"]),Oe={protocol:ee,apiVersion:1,id:"ast",setup(t){t.addSetupCheck({id:"structural-search",async inspect(e){return[...e.detectedLanguageIds].some(s=>U.has(s))?await Z({command:["ast-grep"]},e.cwd,e.env)?{}:{actions:[{id:"ast-grep-unavailable",message:"Structural search is unavailable because ast-grep was not found"}]}:{}}}),t.addCheck({id:"parsers",title:"AST",async run(e){let n=[];for(let s of e.detectedLanguageIds){let r=ct[s];if(r!==void 0){n.push({status:"skip",message:`${s} AST is unavailable: ${r}`});continue}if(!U.has(s))continue;let o=e.files.find(i=>lt(i,s));if(o!==void 0)try{let i=await at(o,"utf8"),c=await N(o,e.cwd,i.replaceAll(`\r
2
2
  `,`
3
3
  `).split(`
4
- `));n.push(c===void 0?{status:"fail",message:`${o} parser did not return a tree`}:{status:"pass",message:`${o} parser loaded`,detail:s})}catch(i){n.push({status:"fail",message:`${o}: ${i instanceof Error?i.message:String(i)}`})}}return n.length>0?n:[{status:"skip",message:"No supported AST files found"}]}}),t.addCheck({id:"ast-grep",title:"Structural search",async run(e){if(![...e.detectedLanguageIds].some(o=>U.has(o)))return[{status:"skip",message:"No supported structural-search files found"}];let n=await Q("ast-grep",["--version"],e.cwd,e.env);return[n.ok?{status:"pass",message:"ast-grep is available",detail:n.detail}:{status:"fail",message:"ast-grep is not available",detail:n.detail}]}})}};function lt(t,e){let n=t.slice(t.lastIndexOf(".")).toLowerCase();return{c:[".c",".h"],cpp:[".cc",".cpp",".cxx",".hh",".hpp",".hxx"],csharp:[".cs"],css:[".css",".scss",".less"],dart:[".dart"],elixir:[".ex",".exs"],go:[".go"],html:[".html",".htm"],java:[".java"],kotlin:[".kt",".kts"],lua:[".lua"],markdown:[".md",".mdx"],php:[".php"],ruby:[".rb",".rake"],scala:[".scala",".sc"],shell:[".sh",".bash"],sql:[".sql"],swift:[".swift"],javascript:[".js",".jsx",".mjs",".cjs"],typescript:[".ts",".tsx",".mts",".cts"],python:[".py",".pyi"],rust:[".rs"],json:[".json",".jsonc"],yaml:[".yaml",".yml"],toml:[".toml"]}[e]?.includes(n)??!1}p(lt,"matchesLanguage");var dt,ut;function Te(t){return{id:"ast",tryResolve(e,n){return Promise.resolve(pt(e,n,t))}}}p(Te,"createAstOutlineResolver");function pt(t,e,n){let o;try{o=X(t,"ast")}catch(i){return{kind:"failed",error:i}}if(o===void 0)return{kind:"not-handled"};let r;try{r=J(o.path,e.cwd)}catch(i){return{kind:"failed",error:i}}return{kind:"resolved",resource:{source:K("ast",r),async read({signal:i}){i?.throwIfAborted();let c=await(ut??=import("./chunk-7LD2OQH3.js")),u=await(n??(dt??=new c.AstOutlineManager)).readFileOutline(r,e.cwd);return i?.throwIfAborted(),[c.formatAstOutline(u)]}}}}p(pt,"resolveAstOutlineSource");import{DEFAULT_MAX_BYTES as mt,DEFAULT_MAX_LINES as ft,truncateHead as G}from"@earendil-works/pi-coding-agent";var B=p(async(t,e,n)=>{let{source:o,resolvedBy:r,lines:s,totalLines:i,startLine:c}=t.details;if(!(o===void 0||r!=="filesystem"||s===void 0||s.length!==i||c!==void 0&&c!==1))try{let{AstOutlineManager:l,isSupportedOutlinePath:u}=await import("./chunk-7LD2OQH3.js");if(!u(o))return;let d=p(g=>[`Code overview of ${g.path}, source lines 1-${g.totalLines}: the requested text exceeded the output limit.`,`Some source text is omitted. Read ${JSON.stringify(o)} with offset and limit for exact source text.`,...g.renderedLines.map(b=>`${b.sourceLine?.lineNumber??"\u2026"} | ${b.text}`)].join(`
5
- `),"format");e.signal?.throwIfAborted();let h=await new l(12).readDocumentOutline(o,e.cwd,s.map(g=>g.content),g=>(e.signal?.throwIfAborted(),!G(d(g),n).truncated)),y=d(h);return G(y,n).truncated?void 0:{script:t.script,content:[{type:"text",text:y}],details:{source:o,resolvedBy:"ast-overflow"}}}catch{e.signal?.throwIfAborted();return}},"reduceAstReadOutput");function Ee(){return async t=>{let{state:e,result:n}=t,o=n?.content.length===1?n.content[0]:void 0;if(t.audience==="script"||n===void 0||e?.contentKind!=="text"||e.resolvedBy!=="filesystem"||o?.type!=="text"||!G(o.text).truncated)return{kind:"continue",context:t};let r=await B({...n,details:{...n.details,source:e.source,resolvedBy:e.resolvedBy,lines:e.text.lines,startLine:1,totalLines:e.text.lines.length}},t.resolverContext,{maxBytes:mt,maxLines:ft});return r===void 0?{kind:"continue",context:t}:{kind:"return",result:r}}}p(Ee,"createAstOverflowHandler");var ke="pi-agent-ast";function Ne(t){return{id:"ast-scopes",async present(e,n){if(n.resolvedBy!=="filesystem")return e;try{let o=await t.getDocumentScopes(e.source,n.cwd,e.lines.map(s=>s.content)),r=gt(e.lines,o);return r===e.lines?e:{...e,lines:r}}catch{return e}}}}p(Ne,"createAstScopePresenter");function Pe(){return t=>{let e=t.state,n=t.result;if(e?.contentKind!=="text"||n===void 0)return{kind:"continue",context:t};let o=n.details.lines;if(o===void 0)return{kind:"continue",context:t};let r=new Map(e.text.lines.map(d=>[d.lineNumber,d])),s=new Set(o.map(d=>d.lineNumber)),i=new Map;for(let d of o){let h=r.get(d.lineNumber),y=je(h);for(let g of y?.boundaries??[]){if(s.has(g.endLine))continue;let b=r.get(g.endLine);b!==void 0&&i.set(g.endLine,b)}}if(i.size===0)return{kind:"continue",context:t};let c=[...i.values()].sort((d,h)=>d.lineNumber-h.lineNumber),l=[...o,...c],u=o.at(-1);return{kind:"continue",context:t,transform:p(d=>ht(d,l,u),"transform")}}}p(Pe,"createAstScopePostReadHandler");function gt(t,e){if(e.length===0)return t;let n=new Map,o=new Map;for(let r of e){let s=n.get(r.startLine)??[];s.push(r.beginAnchor.value),n.set(r.startLine,s);let i=o.get(r.startLine)??[];i.push({endLine:r.endLine,beginAnchor:r.beginAnchor.value,endAnchor:r.endScopeAnchor.value}),o.set(r.startLine,i);let c=n.get(r.endLine)??[];c.push(r.endScopeAnchor.value),n.set(r.endLine,c)}return t.map(r=>{let s=n.get(r.lineNumber),i=o.get(r.lineNumber);return s===void 0&&i===void 0?r:{...r,...s!==void 0&&{anchors:[...new Set([...r.anchors??[],...s])],presentation:{...r.presentation,suffix:`${r.presentation?.suffix??""}${s.map(c=>` <!-- ${c} -->`).join("")}`}},metadata:{...r.metadata,[ke]:{...je(r),...i!==void 0&&{boundaries:i}}}}})}p(gt,"addScopeMarkers");function je(t){let e=t?.metadata?.[ke];if(!(typeof e!="object"||e===null))return e}p(je,"getAstScopeMetadata");function ht(t,e,n){let o=t.content.length===1?t.content[0]:void 0;if(o?.type!=="text"||t.details.lines===void 0)return t;let r=e.slice(t.details.lines.length);if(r.length===0)return t;let s=n?.lineEnding!==void 0&&n.lineEnding.length>0?n.lineEnding:r[0]?.lineEnding!==void 0&&r[0].lineEnding.length>0?r[0].lineEnding:`
6
- `,i=r.map((u,d)=>{let y=d===r.length-1?u.lineEnding:u.lineEnding||s,g=u.presentation?.prefix??"",b=u.presentation?.suffix??"";return`${g}${u.content}${b}${y}`}).join(""),c=/(?:\r\n|\r|\n)$/.test(o.text)?"":s,l=`${o.text}${c}${i}`;return{...t,content:[{...o,text:l}],details:{...t.details,lines:e}}}p(ht,"appendTextLines");var Ce=/^scope-(begin|end)-[A-Z0-9]{3,4}(?:-[1-9]\d*)?$/;function $e(t){return{id:"ast-scope",description:'`scope-begin-HASH` / `scope-end-HASH` from read views: ["ast"] \u2014 first/last lines of a scope. Any numeric suffix is part of the anchor.',renderFull(e){return e},renderCompact(e){return Ce.exec(e)?.[1]==="begin"?"scope start":"scope end"},async tryResolve(e,n){if(!Ce.test(e))return{kind:"not-handled"};try{let r=(await t.getDocumentScopes(n.source,n.cwd,n.lines)).find(s=>s.beginAnchor.value===e||s.endScopeAnchor.value===e);return r===void 0?{kind:"rejected",rejection:{code:"stale",reason:`AST scope anchor ${e} is stale`}}:{kind:"resolved",anchor:r.beginAnchor.value===e?r.beginAnchor:r.endScopeAnchor}}catch(o){return{kind:"failed",error:o}}}}}p($e,"createAstScopeAnchorResolver");import wt from"cross-spawn";import{readFile as Rt,stat as De}from"node:fs/promises";import P from"node:path";import _e from"node:path";import{pathToFileURL as yt}from"node:url";function Me(t,e,n,o,r){let s=new Map;for(let c of e){let l=s.get(c.file)??[];l.push(c),s.set(c.file,l)}let i=[...s.entries()].map(([c,l])=>bt(c,l,o));return{sessionId:r,query:t,matchCount:e.length,fileCount:i.length,complete:n,files:i}}p(Me,"createAstSearchPresentation");function bt(t,e,n){let o=new Map;e.forEach((i,c)=>{let l=i.lines.replace(/\r/gu,"").split(`
7
- `);l.at(-1)===""&&l.pop();let u=`${t}:${String(c)}`;l.forEach((d,h)=>{let y=i.range.start.line+h+1,g=St(i,d,h,l.length);if(g===void 0)return;let b=o.get(y)??{text:d,ranges:[],logicalMatchIds:[]};b.ranges.push(g),b.logicalMatchIds.push(u),o.set(y,b)})});let r=[...o.entries()].sort(([i],[c])=>i-c).map(([i,c])=>{let l=xt(c.ranges);return{lineNumber:i,text:c.text,matchCount:l.length,ranges:l,logicalMatchIds:[...new Set(c.logicalMatchIds)]}}),s=_e.resolve(n,t);return{path:_e.relative(n,s),link:yt(s).href,matchCount:e.length,lines:r}}p(bt,"createFilePresentation");function St(t,e,n,o){let r=n===0,s=n===o-1,i=r?t.range.start.column:0,c=s?t.range.end.column:e.length;if(!(c<=i))return{from:Math.min(i,e.length),to:Math.min(c,e.length)}}p(St,"highlightedRange");function xt(t){let e=[...t].sort((o,r)=>o.from-r.from||o.to-r.to),n=[];for(let o of e){let r=n.at(-1);r===void 0||o.from>r.to?n.push(o):n[n.length-1]={from:r.from,to:Math.max(r.to,o.to)}}return n}p(xt,"mergeRanges");function Be(t){return{id:"ast",supportsResultScope:!0,readResources:p((e,n)=>e.query.startsWith("ast:")?n.scope?.targets.map(o=>o.source)??[e.path??n.cwd]:[],"readResources"),renderResult:Ie,async tryResolve(e,n){if(!e.query.startsWith("ast:"))return{kind:"not-handled"};let o=e.query.slice(4).trim();if(o.length===0)return{kind:"failed",error:new Error("ast: pattern must not be empty")};let r=p(async d=>{n.scope!==void 0&&await E(n.scope,d);let h=await At(o,e,n.cwd,d,n.scope?.targets.map(m=>m.source));h.sort((m,f)=>P.resolve(n.cwd,m.file).localeCompare(P.resolve(n.cwd,f.file))||m.range.byteOffset.start-f.range.byteOffset.start||m.range.byteOffset.end-f.range.byteOffset.end);let y=await Ue(h,n.cwd,d),g=h.map((m,f)=>{let x=_(y[f]);return{selection:x,raw:{...m,range:{...m.range,start:{line:x.lineNumber-1,column:x.startColumn},end:{line:(x.endLineNumber??x.lineNumber)-1,column:x.endColumn}}}}}).filter(({selection:m})=>n.scope===void 0||Re(n.scope,m)),b=g.slice(0,e.limit??100);return n.scope!==void 0&&await E(n.scope,d),{raw:b.map(m=>m.raw),matches:b.map(m=>m.selection),complete:(n.scope?.complete??!0)&&g.length<=(e.limit??100)}},"collect"),s=await r(n.signal),i=await t({request:e,matches:s.matches,complete:s.complete,refresh:r},n),c=k(s.matches,s.complete,i.id,i),l=[],u=[];for(let d of s.raw.slice(0,c.matches.length)){let h=Object.entries({...Object.fromEntries(Object.entries(d.metaVariables?.single??{}).map(([b,m])=>[b,[m]])),...d.metaVariables?.multi}),y=[],g={};for(let[b,m]of h){for(let w of m)if(w.range.byteOffset.start<d.range.byteOffset.start||w.range.byteOffset.end>d.range.byteOffset.end)throw new Error("AST capture lies outside its parent match.");let f=await Ue(m.map(w=>({...d,...w})),n.cwd,n.signal),x=await t({request:e,matches:f,complete:s.complete,refresh:p(async()=>{throw new Error("Capture snapshots cannot refresh; repeat the AST search.")},"refresh")},n);g[b]={target:_(k(f,s.complete,void 0,x).target),nodes:f.length};let R=[];for(let w=0;w<f.length;w+=100){let T=f.slice(w,w+100),A=await t({request:e,matches:T,complete:s.complete,refresh:p(async()=>{throw new Error("Capture snapshots cannot refresh; repeat the AST search.")},"refresh")},n);R.push(...k(T,s.complete,void 0,A).matches)}y.push([b,R])}l.push(Object.fromEntries(y)),u.push(g)}return n.scope!==void 0&&await E(n.scope,n.signal),{kind:"resolved",payload:{data:{...c,matches:c.matches.map((d,h)=>({...d,captures:l[h]}))},captureGroups:u,pattern:o,matches:s.raw.map((d,h)=>({...d,selection:s.matches[h]})),complete:s.complete,sessionId:i.id,presentation:Me(e.query,s.raw,s.complete,n.cwd,i.id)}}},toScriptData(e){return e.data},format(e){let n=e;if(n.matches.length===0)return{content:[{type:"text",text:"No AST matches found."}],details:n.presentation};let o=n.matches.flatMap((r,s)=>{let i=[`SEARCH#${n.sessionId}:${s+1}:match ${r.file}:${r.range.start.line+1}:${r.range.start.column+1} ${r.language}`,` ${r.lines.trim()}`];for(let[c,l]of Object.entries(n.captureGroups[s]??{}))i.push(` capture ${c}: ${l.target} ${l.nodes} node(s)`);return i});return n.complete&&o.unshift(`SEARCH#${n.sessionId}:all:match selects all exact AST matches.`),{content:[{type:"text",text:o.join(`
8
- `)}],details:n.presentation}}}}p(Be,"createAstSearchResolver");async function Ue(t,e,n){let o=new Map;for(let r of t){let s=P.resolve(e,r.file);if(o.has(s))continue;let i=await De(s),c=await Rt(s,{signal:n}),l=await De(s);if(i.mtimeMs!==l.mtimeMs||i.size!==l.size)throw new Error("AST source changed during search. Run the structural query again.");o.set(s,c)}return t.map(r=>{let s=P.resolve(e,r.file),i=o.get(s);if(i===void 0)throw new Error("Missing AST source snapshot");let{start:c,end:l}=r.range.byteOffset;if(!Number.isInteger(c)||!Number.isInteger(l)||c<0||l<c||l>i.length||i.subarray(c,l).toString("utf8")!==r.text)throw new Error("AST range does not match its source snapshot. Search again.");let u=i.subarray(0,c).toString("utf8"),d=i.subarray(0,l).toString("utf8"),h=u.split(`
9
- `).length;return{source:s,lineNumber:h,endLineNumber:d.split(`
4
+ `));n.push(c===void 0?{status:"fail",message:`${s} parser did not return a tree`}:{status:"pass",message:`${s} parser loaded`,detail:o})}catch(i){n.push({status:"fail",message:`${s}: ${i instanceof Error?i.message:String(i)}`})}}return n.length>0?n:[{status:"skip",message:"No supported AST files found"}]}}),t.addCheck({id:"ast-grep",title:"Structural search",async run(e){if(![...e.detectedLanguageIds].some(s=>U.has(s)))return[{status:"skip",message:"No supported structural-search files found"}];let n=await Q("ast-grep",["--version"],e.cwd,e.env);return[n.ok?{status:"pass",message:"ast-grep is available",detail:n.detail}:{status:"fail",message:"ast-grep is not available",detail:n.detail}]}})}};function lt(t,e){let n=t.slice(t.lastIndexOf(".")).toLowerCase();return{c:[".c",".h"],cpp:[".cc",".cpp",".cxx",".hh",".hpp",".hxx"],csharp:[".cs"],css:[".css",".scss",".less"],dart:[".dart"],elixir:[".ex",".exs"],go:[".go"],html:[".html",".htm"],java:[".java"],kotlin:[".kt",".kts"],lua:[".lua"],markdown:[".md",".mdx"],php:[".php"],ruby:[".rb",".rake"],scala:[".scala",".sc"],shell:[".sh",".bash"],sql:[".sql"],swift:[".swift"],javascript:[".js",".jsx",".mjs",".cjs"],typescript:[".ts",".tsx",".mts",".cts"],python:[".py",".pyi"],rust:[".rs"],json:[".json",".jsonc"],yaml:[".yaml",".yml"],toml:[".toml"]}[e]?.includes(n)??!1}p(lt,"matchesLanguage");var dt,ut;function Te(t){return{id:"ast",tryResolve(e,n){return Promise.resolve(pt(e,n,t))}}}p(Te,"createAstOutlineResolver");function pt(t,e,n){let s;try{s=X(t,"ast")}catch(i){return{kind:"failed",error:i}}if(s===void 0)return{kind:"not-handled"};let r;try{r=J(s.path,e.cwd)}catch(i){return{kind:"failed",error:i}}return{kind:"resolved",resource:{source:K("ast",r),async read({signal:i}){i?.throwIfAborted();let c=await(ut??=import("./chunk-7LD2OQH3.js")),u=await(n??(dt??=new c.AstOutlineManager)).readFileOutline(r,e.cwd);return i?.throwIfAborted(),[c.formatAstOutline(u)]}}}}p(pt,"resolveAstOutlineSource");import{DEFAULT_MAX_BYTES as mt,DEFAULT_MAX_LINES as ft,truncateHead as G}from"@earendil-works/pi-coding-agent";var B=p(async(t,e,n)=>{let{source:s,resolvedBy:r,lines:o,totalLines:i,startLine:c}=t.details;if(!(s===void 0||r!=="filesystem"||o===void 0||o.length!==i||c!==void 0&&c!==1))try{let{AstOutlineManager:l,isSupportedOutlinePath:u}=await import("./chunk-7LD2OQH3.js");if(!u(s))return;let d=p(g=>[`Code overview of ${g.path}, source lines 1-${g.totalLines}: the requested text exceeded the output limit.`,`Some source text is omitted. Read ${JSON.stringify(s)} with offset and limit for exact source text.`,...g.renderedLines.map(b=>`${b.sourceLine?.lineNumber??"\u2026"} | ${b.text}`)].join(`
5
+ `),"format");e.signal?.throwIfAborted();let h=await new l(12).readDocumentOutline(s,e.cwd,o.map(g=>g.content),g=>(e.signal?.throwIfAborted(),!G(d(g),n).truncated)),y=d(h);return G(y,n).truncated?void 0:{script:t.script,content:[{type:"text",text:y}],details:{source:s,resolvedBy:"ast-overflow"}}}catch{e.signal?.throwIfAborted();return}},"reduceAstReadOutput");function Ee(){return async t=>{let{state:e,result:n}=t,s=n?.content.length===1?n.content[0]:void 0;if(t.audience==="script"||n===void 0||e?.contentKind!=="text"||e.resolvedBy!=="filesystem"||s?.type!=="text"||!G(s.text).truncated)return{kind:"continue",context:t};let r=await B({...n,details:{...n.details,source:e.source,resolvedBy:e.resolvedBy,lines:e.text.lines,startLine:1,totalLines:e.text.lines.length}},t.resolverContext,{maxBytes:mt,maxLines:ft});return r===void 0?{kind:"continue",context:t}:{kind:"continue",context:t,transform:p(o=>({...r,script:o.script}),"transform")}}}p(Ee,"createAstOverflowHandler");var ke="pi-agent-ast";function Ne(t){return{id:"ast-scopes",async present(e,n){if(n.resolvedBy!=="filesystem")return e;try{let s=await t.getDocumentScopes(e.source,n.cwd,e.lines.map(o=>o.content)),r=gt(e.lines,s);return r===e.lines?e:{...e,lines:r}}catch{return e}}}}p(Ne,"createAstScopePresenter");function Pe(){return t=>{let e=t.state,n=t.result;if(e?.contentKind!=="text"||n===void 0)return{kind:"continue",context:t};let s=n.details.lines;if(s===void 0)return{kind:"continue",context:t};let r=new Map(e.text.lines.map(d=>[d.lineNumber,d])),o=new Set(s.map(d=>d.lineNumber)),i=new Map;for(let d of s){let h=r.get(d.lineNumber),y=je(h);for(let g of y?.boundaries??[]){if(o.has(g.endLine))continue;let b=r.get(g.endLine);b!==void 0&&i.set(g.endLine,b)}}if(i.size===0)return{kind:"continue",context:t};let c=[...i.values()].sort((d,h)=>d.lineNumber-h.lineNumber),l=[...s,...c],u=s.at(-1);return{kind:"continue",context:t,transform:p(d=>ht(d,l,u),"transform")}}}p(Pe,"createAstScopePostReadHandler");function gt(t,e){if(e.length===0)return t;let n=new Map,s=new Map;for(let r of e){let o=n.get(r.startLine)??[];o.push(r.beginAnchor.value),n.set(r.startLine,o);let i=s.get(r.startLine)??[];i.push({endLine:r.endLine,beginAnchor:r.beginAnchor.value,endAnchor:r.endScopeAnchor.value}),s.set(r.startLine,i);let c=n.get(r.endLine)??[];c.push(r.endScopeAnchor.value),n.set(r.endLine,c)}return t.map(r=>{let o=n.get(r.lineNumber),i=s.get(r.lineNumber);return o===void 0&&i===void 0?r:{...r,...o!==void 0&&{anchors:[...new Set([...r.anchors??[],...o])],presentation:{...r.presentation,suffix:`${r.presentation?.suffix??""}${o.map(c=>` <!-- ${c} -->`).join("")}`}},metadata:{...r.metadata,[ke]:{...je(r),...i!==void 0&&{boundaries:i}}}}})}p(gt,"addScopeMarkers");function je(t){let e=t?.metadata?.[ke];if(!(typeof e!="object"||e===null))return e}p(je,"getAstScopeMetadata");function ht(t,e,n){let s=t.content.length===1?t.content[0]:void 0;if(s?.type!=="text"||t.details.lines===void 0)return t;let r=e.slice(t.details.lines.length);if(r.length===0)return t;let o=n?.lineEnding!==void 0&&n.lineEnding.length>0?n.lineEnding:r[0]?.lineEnding!==void 0&&r[0].lineEnding.length>0?r[0].lineEnding:`
6
+ `,i=r.map((u,d)=>{let y=d===r.length-1?u.lineEnding:u.lineEnding||o,g=u.presentation?.prefix??"",b=u.presentation?.suffix??"";return`${g}${u.content}${b}${y}`}).join(""),c=/(?:\r\n|\r|\n)$/.test(s.text)?"":o,l=`${s.text}${c}${i}`;return{...t,content:[{...s,text:l}],details:{...t.details,lines:e}}}p(ht,"appendTextLines");var Ce=/^scope-(begin|end)-[A-Z0-9]{3,4}(?:-[1-9]\d*)?$/;function $e(t){return{id:"ast-scope",description:'`scope-begin-HASH` / `scope-end-HASH` from read views: ["ast"] \u2014 first/last lines of a scope. Any numeric suffix is part of the anchor.',renderFull(e){return e},renderCompact(e){return Ce.exec(e)?.[1]==="begin"?"scope start":"scope end"},async tryResolve(e,n){if(!Ce.test(e))return{kind:"not-handled"};try{let r=(await t.getDocumentScopes(n.source,n.cwd,n.lines)).find(o=>o.beginAnchor.value===e||o.endScopeAnchor.value===e);return r===void 0?{kind:"rejected",rejection:{code:"stale",reason:`AST scope anchor ${e} is stale`}}:{kind:"resolved",anchor:r.beginAnchor.value===e?r.beginAnchor:r.endScopeAnchor}}catch(s){return{kind:"failed",error:s}}}}}p($e,"createAstScopeAnchorResolver");import wt from"cross-spawn";import{readFile as Rt,stat as De}from"node:fs/promises";import P from"node:path";import _e from"node:path";import{pathToFileURL as yt}from"node:url";function Me(t,e,n,s,r){let o=new Map;for(let c of e){let l=o.get(c.file)??[];l.push(c),o.set(c.file,l)}let i=[...o.entries()].map(([c,l])=>bt(c,l,s));return{sessionId:r,query:t,matchCount:e.length,fileCount:i.length,complete:n,files:i}}p(Me,"createAstSearchPresentation");function bt(t,e,n){let s=new Map;e.forEach((i,c)=>{let l=i.lines.replace(/\r/gu,"").split(`
7
+ `);l.at(-1)===""&&l.pop();let u=`${t}:${String(c)}`;l.forEach((d,h)=>{let y=i.range.start.line+h+1,g=St(i,d,h,l.length);if(g===void 0)return;let b=s.get(y)??{text:d,ranges:[],logicalMatchIds:[]};b.ranges.push(g),b.logicalMatchIds.push(u),s.set(y,b)})});let r=[...s.entries()].sort(([i],[c])=>i-c).map(([i,c])=>{let l=xt(c.ranges);return{lineNumber:i,text:c.text,matchCount:l.length,ranges:l,logicalMatchIds:[...new Set(c.logicalMatchIds)]}}),o=_e.resolve(n,t);return{path:_e.relative(n,o),link:yt(o).href,matchCount:e.length,lines:r}}p(bt,"createFilePresentation");function St(t,e,n,s){let r=n===0,o=n===s-1,i=r?t.range.start.column:0,c=o?t.range.end.column:e.length;if(!(c<=i))return{from:Math.min(i,e.length),to:Math.min(c,e.length)}}p(St,"highlightedRange");function xt(t){let e=[...t].sort((s,r)=>s.from-r.from||s.to-r.to),n=[];for(let s of e){let r=n.at(-1);r===void 0||s.from>r.to?n.push(s):n[n.length-1]={from:r.from,to:Math.max(r.to,s.to)}}return n}p(xt,"mergeRanges");function Be(t){return{id:"ast",supportsResultScope:!0,readResources:p((e,n)=>e.query.startsWith("ast:")?n.scope?.targets.map(s=>s.source)??[e.path??n.cwd]:[],"readResources"),renderResult:Ie,async tryResolve(e,n){if(!e.query.startsWith("ast:"))return{kind:"not-handled"};let s=e.query.slice(4).trim();if(s.length===0)return{kind:"failed",error:new Error("ast: pattern must not be empty")};let r=p(async d=>{n.scope!==void 0&&await E(n.scope,d);let h=await At(s,e,n.cwd,d,n.scope?.targets.map(m=>m.source));h.sort((m,f)=>P.resolve(n.cwd,m.file).localeCompare(P.resolve(n.cwd,f.file))||m.range.byteOffset.start-f.range.byteOffset.start||m.range.byteOffset.end-f.range.byteOffset.end);let y=await Ue(h,n.cwd,d),g=h.map((m,f)=>{let x=_(y[f]);return{selection:x,raw:{...m,range:{...m.range,start:{line:x.lineNumber-1,column:x.startColumn},end:{line:(x.endLineNumber??x.lineNumber)-1,column:x.endColumn}}}}}).filter(({selection:m})=>n.scope===void 0||Re(n.scope,m)),b=g.slice(0,e.limit??100);return n.scope!==void 0&&await E(n.scope,d),{raw:b.map(m=>m.raw),matches:b.map(m=>m.selection),complete:(n.scope?.complete??!0)&&g.length<=(e.limit??100)}},"collect"),o=await r(n.signal),i=await t({request:e,matches:o.matches,complete:o.complete,refresh:r},n),c=k(o.matches,o.complete,i.id,i),l=[],u=[];for(let d of o.raw.slice(0,c.matches.length)){let h=Object.entries({...Object.fromEntries(Object.entries(d.metaVariables?.single??{}).map(([b,m])=>[b,[m]])),...d.metaVariables?.multi}),y=[],g={};for(let[b,m]of h){for(let w of m)if(w.range.byteOffset.start<d.range.byteOffset.start||w.range.byteOffset.end>d.range.byteOffset.end)throw new Error("AST capture lies outside its parent match.");let f=await Ue(m.map(w=>({...d,...w})),n.cwd,n.signal),x=await t({request:e,matches:f,complete:o.complete,refresh:p(async()=>{throw new Error("Capture snapshots cannot refresh; repeat the AST search.")},"refresh")},n);g[b]={target:_(k(f,o.complete,void 0,x).target),nodes:f.length};let R=[];for(let w=0;w<f.length;w+=100){let T=f.slice(w,w+100),A=await t({request:e,matches:T,complete:o.complete,refresh:p(async()=>{throw new Error("Capture snapshots cannot refresh; repeat the AST search.")},"refresh")},n);R.push(...k(T,o.complete,void 0,A).matches)}y.push([b,R])}l.push(Object.fromEntries(y)),u.push(g)}return n.scope!==void 0&&await E(n.scope,n.signal),{kind:"resolved",payload:{data:{...c,matches:c.matches.map((d,h)=>({...d,captures:l[h]}))},captureGroups:u,pattern:s,matches:o.raw.map((d,h)=>({...d,selection:o.matches[h]})),complete:o.complete,sessionId:i.id,presentation:Me(e.query,o.raw,o.complete,n.cwd,i.id)}}},toScriptData(e){return e.data},format(e){let n=e;if(n.matches.length===0)return{content:[{type:"text",text:"No AST matches found."}],details:n.presentation};let s=n.matches.flatMap((r,o)=>{let i=[`SEARCH#${n.sessionId}:${o+1}:match ${r.file}:${r.range.start.line+1}:${r.range.start.column+1} ${r.language}`,` ${r.lines.trim()}`];for(let[c,l]of Object.entries(n.captureGroups[o]??{}))i.push(` capture ${c}: ${l.target} ${l.nodes} node(s)`);return i});return n.complete&&s.unshift(`SEARCH#${n.sessionId}:all:match selects all exact AST matches.`),{content:[{type:"text",text:s.join(`
8
+ `)}],details:n.presentation}}}}p(Be,"createAstSearchResolver");async function Ue(t,e,n){let s=new Map;for(let r of t){let o=P.resolve(e,r.file);if(s.has(o))continue;let i=await De(o),c=await Rt(o,{signal:n}),l=await De(o);if(i.mtimeMs!==l.mtimeMs||i.size!==l.size)throw new Error("AST source changed during search. Run the structural query again.");s.set(o,c)}return t.map(r=>{let o=P.resolve(e,r.file),i=s.get(o);if(i===void 0)throw new Error("Missing AST source snapshot");let{start:c,end:l}=r.range.byteOffset;if(!Number.isInteger(c)||!Number.isInteger(l)||c<0||l<c||l>i.length||i.subarray(c,l).toString("utf8")!==r.text)throw new Error("AST range does not match its source snapshot. Search again.");let u=i.subarray(0,c).toString("utf8"),d=i.subarray(0,l).toString("utf8"),h=u.split(`
9
+ `).length;return{source:o,lineNumber:h,endLineNumber:d.split(`
10
10
  `).length,startColumn:u.length-u.lastIndexOf(`
11
11
  `)-1,endColumn:d.length-d.lastIndexOf(`
12
12
  `)-1,matchedText:r.text,lineText:i.toString("utf8").split(`
13
- `)[h-1]?.replace(/\r$/u,"")??""}})}p(Ue,"selectionMatches");function At(t,e,n,o,r){if(o?.throwIfAborted(),r?.length===0)return Promise.resolve([]);let s=["run","--pattern",t,"--json=compact","--no-ignore","parent"];for(let i of Ge(e.include))s.push("--globs",i);for(let i of Ge(e.exclude))s.push("--globs",`!${i}`);return s.push(...r??[e.path??"."]),new Promise((i,c)=>{let l=wt("ast-grep",s,{cwd:n,stdio:["ignore","pipe","pipe"]}),u="",d="";l.stdout.setEncoding("utf8"),l.stderr.setEncoding("utf8"),l.stdout.on("data",y=>u+=y),l.stderr.on("data",y=>d+=y);let h=p(()=>{l.kill("SIGTERM")},"abort");o?.addEventListener("abort",h,{once:!0}),l.once("error",c),l.once("close",y=>{if(o?.removeEventListener("abort",h),o?.aborted===!0){c(o.reason instanceof Error?o.reason:new Error("AST search aborted"));return}if(y!==0&&y!==1){c(new Error(d.trim()||`ast-grep exited with code ${String(y)}`));return}try{let g=JSON.parse(u.length===0?"[]":u);if(!Array.isArray(g))throw new TypeError("ast-grep returned non-array JSON");i(g)}catch(g){c(g instanceof Error?g:new Error(String(g)))}})})}p(At,"runAstGrep");function Ge(t){return t?.split(",").map(e=>e.trim()).filter(Boolean)??[]}p(Ge,"splitGlobs");import{Text as Ut}from"@earendil-works/pi-tui";import Ve from"node:path";import{pathToFileURL as vt}from"node:url";function Fe(t,e,n,o){let r=new Map;for(let c of t){let l=r.get(c.target.source);l?l.push(c):r.set(c.target.source,[c])}let s=[];t.length||s.push({kind:"note",text:"No selections"}),e||s.push({kind:"note",text:"Incomplete input; not a complete edit scope"}),n&&s.push({kind:"note",text:`${n} input(s) without a selection`});let i=100;for(let[c,l]of r){if(!i)break;let u=l.slice(0,i);i-=u.length;let d=Ve.relative(o,c)||Ve.basename(c),h=[],y=!1,g=l[0]?.target.expectedContent.split(/\r\n|\n|\r/u)??[];for(let m of u){let{start:f,end:x}=m.range,w=f.lineNumber===x.lineNumber&&f.column===x.column?f.lineNumber:x.lineNumber-(x.column===0?1:0),T=Math.min(w,f.lineNumber+19);y||=T<w;for(let A=f.lineNumber;A<=T;A++){let q=g[A-1]??"";h.push({source:c,label:d,link:vt(c).href,lineNumber:A,text:q,ranges:[{from:A===f.lineNumber?f.column:0,to:A===x.lineNumber?x.column:q.length}]})}}let b=le(h);s.push(...b.map(m=>m.kind==="source"?{...m,count:l.length}:m)),y&&s.push({kind:"note",text:"\u2026 selection preview shortened \xB7 full target retained"});for(let m of u){m.range.start.lineNumber===m.range.end.lineNumber&&m.range.start.column===m.range.end.column&&s.push({kind:"note",text:`zero-width \xB7 ${m.range.start.lineNumber}:${m.range.start.column}`});let{start:f,end:x}=m.range;s.push({kind:"note",expandedOnly:!0,text:`${m.syntax?`${m.syntax.object}${m.syntax.part?`/${m.syntax.part}`:""} \xB7 `:""}${f.lineNumber}:${f.column}\u2013${x.lineNumber}:${x.column} \xB7 ${m.origins.length} origin(s)${m.origins.some(R=>R.expanded)?" \xB7 expanded":""}`});for(let R of m.origins.slice(0,20)){let w=R.range;s.push({kind:"note",expandedOnly:!0,text:`from ${w.startLine}:${w.startColumn}\u2013${w.endLine}:${w.endColumn}`})}m.origins.length>20&&s.push({kind:"note",expandedOnly:!0,text:"\u2026 more origins retained in this result reference"})}}return t.length>100&&s.push({kind:"note",text:"\u2026 more selections \xB7 consume the complete result target"}),{summary:`${t.length} ${t.length===1?"selection":"selections"} in ${r.size} ${r.size===1?"file":"files"}${e?"":" \xB7 incomplete"}`,rows:s}}p(Fe,"selectPresentation");import Tt from"node:path";var S=class extends Error{constructor(n,o){super(o);this.code=n}static{p(this,"SelectionError")}};function v(t){return{startLine:t.start.lineNumber,startColumn:t.start.column,endLine:t.end.lineNumber,endColumn:t.end.column}}p(v,"publicRange");function O(t,e){let n=JSON.stringify([e.target.source,e.range]),o=t.get(n);t.set(n,o?{...e,origins:[...o.origins,...e.origins]}:e)}p(O,"retainRegion");var I=class{constructor(e){this.content=e;let n=0,o=W("",e),r=o.lines.map(s=>{let i=n;return n+=s.content.length+s.lineEnding.length,{start:i,length:s.content.length,end:n}});(r.length===0||o.lines.at(-1)?.lineEnding)&&r.push({start:n,length:0,end:n}),this.lines=r}static{p(this,"SourceText")}lines;boundary(e){if(!Number.isSafeInteger(e)||e<0||e>this.content.length)throw new S("INVALID_RANGE","Text bounds are outside the retained snapshot.");let n=this.content.charCodeAt(e-1),o=this.content.charCodeAt(e);if(n>=55296&&n<=56319&&o>=56320&&o<=57343||n===13&&o===10)throw new S("INVALID_BOUNDARY","Text boundary splits a surrogate pair or CRLF separator.")}offset(e){let n=this.lines[e.lineNumber-1];if(!Number.isSafeInteger(e.lineNumber)||!n||!Number.isSafeInteger(e.column)||e.column<0||e.column>n.length)throw new S("INVALID_RANGE","Source bounds are outside the retained snapshot.");let o=n.start+e.column;return this.boundary(o),o}lineIndex(e){let n=0,o=this.lines.length-1;for(;n<o;){let r=Math.ceil((n+o)/2);(this.lines[r]?.start??0)<=e?n=r:o=r-1}return n}position(e){this.boundary(e);let n=this.lineIndex(e);return{lineNumber:n+1,column:e-(this.lines[n]?.start??0)}}range(e,n){if(n<e)throw new S("INVALID_RANGE","Text bounds are reversed.");return{start:this.position(e),end:this.position(n)}}fullLines(e,n){let o=this.lines[this.lineIndex(e)],r=this.lines[this.lineIndex(n>e?n-1:e)];if(!o||!r)throw new S("INVALID_RANGE","Source line bounds are unavailable.");return{from:o.start,to:r.end}}};function He(t,e,n){let o=t;for(;o.parent&&o.parent.node.startIndex===o.node.startIndex&&o.parent.node.endIndex===o.node.endIndex;)o=o.parent;let r=o.parent;if(!r||!(r.node.type==="arguments"&&r.parent?.object==="call"||r.node.type==="formal_parameters"&&r.parent?.object==="function")||o.node.type==="comment")throw new S("EXACT_LIST_ELEMENT_REQUIRED","elementExtent requires an exact direct call argument or parenthesized function parameter. Use a full AST capture; partial expressions and other lists are not supported.");let s=r.node.startIndex,i=r.node.endIndex-1;if(n[s]!=="("||n[i]!==")")throw new S("UNSUPPORTED_LIST","Only parenthesized argument and parameter lists are supported.");if(e==="inside")return{startIndex:o.node.startIndex,endIndex:o.node.endIndex};let c=r.children.filter(m=>m.node.type!=="comment"),l=c.indexOf(o),u=c[l-1],d=c[l+1],h=u?.node.endIndex??s+1,y=d?.node.startIndex??i,g=n.slice(h,o.node.startIndex),b=n.slice(o.node.endIndex,y);if(!(u?/^\s*,\s*$/u:/^\s*$/u).test(g)||!(d?/^\s*,\s*$/u:/^\s*,?\s*$/u).test(b))throw new S("AMBIGUOUS_LIST_TRIVIA","Comments or unsupported trivia in adjacent list gaps have no inferred owner. Use inside for the exact element, or choose explicit text boundaries.");return c.length===1?{startIndex:s+1,endIndex:i}:d||b.includes(",")?{startIndex:o.node.startIndex,endIndex:y}:{startIndex:h,endIndex:o.node.endIndex}}p(He,"listElementExtent");var It={function_declaration:"function",generator_function_declaration:"function",function_expression:"function",generator_function:"function",arrow_function:"function",method_definition:"function",function_signature:"function",method_signature:"function",abstract_method_signature:"function",call_expression:"call",new_expression:"call",class_declaration:"class",class:"class",abstract_class_declaration:"class",if_statement:"if",switch_statement:"switch",for_statement:"loop",for_in_statement:"loop",while_statement:"loop",do_statement:"loop",try_statement:"try",catch_clause:"catch",variable_declarator:"binding",assignment_expression:"assignment",augmented_assignment_expression:"assignment",object:"object",object_pattern:"object",pair:"property",pair_pattern:"property",shorthand_property_identifier:"property",shorthand_property_identifier_pattern:"property",array:"array",array_pattern:"array",return_statement:"return",throw_statement:"throw"};function ze(t,e){let n=[],o=[{node:t,parent:void 0}];for(;o.length;){e?.throwIfAborted();let r=o.pop();if(!r)continue;let s={node:r.node,object:It[r.node.type],parent:r.parent,children:[]};r.parent?.children.push(s),n.push(s);for(let i of r.node.namedChildren.toReversed())o.push({node:i,parent:s})}return n}p(ze,"constructIndex");function L(t){let e=t.parent;for(;e&&!e.object;)e=e.parent;return e}p(L,"constructParent");function V(t,e,n){let o=[],r=[...t.children].reverse();for(;r.length;){n?.throwIfAborted();let s=r.pop();s&&(s.object&&o.push(s),(e||!s.object)&&r.push(...s.children.toReversed()))}return o}p(V,"constructChildren");var Lt={function:[["name",["name"]],["body",["body"]],["parameters",["parameters","parameter"]],["returnType",["return_type"]]],call:[["callee",["function","constructor"]],["arguments",["arguments"]]],class:[["name",["name"]],["body",["body"]]],if:[["condition",["condition"]],["then",["consequence"]],["else",["alternative"]]],switch:[["condition",["value"]],["body",["body"]]],loop:[["condition",["condition"]],["body",["body"]]],try:[["body",["body"]],["handler",["handler"]],["finalizer",["finalizer"]]],catch:[["body",["body"]],["parameter",["parameter"]]],binding:[["name",["name"]],["type",["type"]],["value",["value"]]],assignment:[["left",["left"]],["right",["right"]]],property:[["key",["key"]],["value",["value"]]],return:[["value",[]]],throw:[["value",[]]],object:[],array:[]};function Ot(t){return t.node.type==="for_statement"?[["initializer",["initializer"]],["condition",["condition"]],["update",["increment"]],["body",["body"]]]:t.node.type==="for_in_statement"?[["left",["left"]],["iterable",["right"]],["body",["body"]]]:t.node.type==="finally_clause"?[["body",["body"]]]:t.object?Lt[t.object]:[]}p(Ot,"partFields");function qe(t,e){let n=Ot(t),o=n.find(([r])=>r===e)?.[1];if(!o)throw new S("UNSUPPORTED_PART",`Unsupported part ${e} for ${t.object??"this syntax container"}; supported parts: ${n.map(([r])=>r).join(", ")||"none"}. Use navigate children/descendants for nested constructs.`);if(t.object==="property"&&t.node.type.startsWith("shorthand_property_identifier"))return t.node;if(t.object==="return"||t.object==="throw")return t.node.namedChildren.find(r=>r.type!=="comment");for(let r of o){let s=t.node.childForFieldName(r);if(s)return s}}p(qe,"constructPart");var Et=new Set([".js",".mjs",".cjs",".ts",".mts",".cts"]);function kt(t,e,n){let o=t.filter(s=>s.node.startIndex===e&&s.node.endIndex===n),r=o.find(s=>s.object)??o.at(-1);if(!r)throw new S("EXACT_NODE_REQUIRED","Navigation and parts require an exact syntax node. Use object/enclosing first for a partial match; use a returned part target to navigate its contents.");return r}p(kt,"exactNode");function Nt(t,e,n,o){let r;for(let i of t)i.object!==o.object||i.node.startIndex>e||i.node.endIndex<n||e===n&&i.node.endIndex===n||(!r||i.node.endIndex-i.node.startIndex<r.node.endIndex-r.node.startIndex)&&(r=i);if(!r&&t.filter(i=>i.object===o.object&&i.node.startIndex<n&&i.node.endIndex>e).length>1)throw new S("AMBIGUOUS_SEED","The seed spans separate constructs; select narrower input ranges.");let s=1;for(;r&&s<(o.level??1);){for(r=L(r);r&&r.object!==o.object;)r=L(r);s++}return r}p(Nt,"enclosing");function Pt(t,e,n,o){let r;switch(e.relation){case"parent":{let s=L(t);r=s?[s]:[];break}case"ancestors":{r=[];let s=L(t);for(;s;)o?.throwIfAborted(),r.push(s),s=L(s);break}case"children":case"descendants":{r=V(t,e.relation==="descendants",o);break}case"siblings":{if(!t.object)throw new S("EXACT_CONSTRUCT_REQUIRED","siblings requires an exact supported construct, not a part container. Use enclosing first.");let s=V(L(t)??n,!1,o),i=s.indexOf(t),c=e.direction??"all",l=c==="previous"?s[i-1]:s[i+1];r=c==="all"?s.filter(u=>u!==t):l?[l]:[];break}}return r.filter(s=>!e.object||s.object===e.object).sort((s,i)=>s.node.startIndex-i.node.startIndex||i.node.endIndex-s.node.endIndex)}p(Pt,"navigate");async function Xe(t,e,n,o){let r=new Map,s=0;for(let i of t.targets){if(o?.throwIfAborted(),!Et.has(Tt.extname(i.source).toLowerCase()))throw new S("UNSUPPORTED_LANGUAGE","Select AST supports JavaScript and TypeScript files, without JSX/TSX.");let c=await N(i.source,n,i.expectedContent.split(`
14
- `));if(!c)throw new S("UNSUPPORTED_PROVIDER","No syntax provider is available for this source.");try{if(c.rootNode.hasError)throw new S("INVALID_SYNTAX","The syntax provider reports errors; no structural targets were created.");let l=ze(c.rootNode,o),u=l[0];if(!u)throw Error("Missing syntax root");let d=new I(i.expectedContent);for(let h of i.ranges){o?.throwIfAborted();let y=d.offset(h.start),g=d.offset(h.end),b=e.kind==="object"?Nt(l,y,g,e):kt(l,y,g),m=b&&e.kind==="elementExtent"?He(b,e.extent,i.expectedContent):void 0,f=b?e.kind==="part"?[qe(b,e.part)].filter(x=>x!==void 0).map(x=>({node:x,object:b.object})):e.kind==="navigate"?Pt(b,e,u,o):[b]:[];f.length||s++;for(let x of f){let R=m??x.node,w=x.object&&e.kind!=="elementExtent"?{object:x.object,...e.kind==="part"?{part:e.part}:{}}:void 0;O(r,{target:i,range:{start:d.position(R.startIndex),end:d.position(R.endIndex)},text:i.expectedContent.slice(R.startIndex,R.endIndex),origins:[{source:i.source,range:v({start:h.start,end:d.position(g)}),expanded:R.startIndex<y||R.endIndex>g}],...w?{syntax:w}:{}})}}}finally{c.delete?.()}}return{regions:[...r.values()],missingInputs:s}}p(Xe,"selectStructuralRegions");function Ke(t,e,n){n?.throwIfAborted();let o=e.kind==="range"||e.kind==="lines";if(o&&new Set(t.targets.map(i=>i.source)).size>1)throw new S("MULTIPLE_SOURCES","Absolute text bounds require one source.");let r=new Map,s=0;for(let i of t.targets){n?.throwIfAborted();let c=new I(i.expectedContent),l=o?jt(c,e):void 0,u=!1;for(let d of i.ranges){n?.throwIfAborted();let h=c.offset(d.start),y=c.offset(d.end);c.range(h,y);let g=l?l.from>=h&&l.to<=y?[l]:[]:Ct(c,{from:h,to:y},e,n);g.length?u=!0:s++;for(let b of g){n?.throwIfAborted();let m=c.range(b.from,b.to),f=b.from<h||b.to>y;if(f&&e.kind!=="linesOf"&&!(e.kind==="between"&&e.extent==="lines"))throw new S("OUTSIDE_SCOPE","Text selection exceeds its input scope.");O(r,{target:i,range:m,text:c.content.slice(b.from,b.to),origins:[{source:i.source,range:v(d),expanded:f}]})}}if(l&&!u)throw new S("OUTSIDE_SCOPE","Requested text bounds are outside every input scope.")}return{regions:[...r.values()],missingInputs:s}}p(Ke,"selectTextRegions");function jt(t,e){if(e.kind==="range"){let r=t.offset({lineNumber:e.startLine,column:e.startColumn}),s=t.offset({lineNumber:e.endLine,column:e.endColumn});return t.range(r,s),{from:r,to:s}}let n=t.lines[e.first-1],o=t.lines[e.last-1];if(!Number.isSafeInteger(e.first)||!Number.isSafeInteger(e.last)||!n||!o||e.last<e.first)throw new S("INVALID_RANGE","Line bounds are outside the retained snapshot or reversed.");return{from:n.start,to:o.end}}p(jt,"absoluteInterval");function Ct(t,e,n,o){let r=t.content.slice(e.from,e.to);switch(n.kind){case"between":{F(n.start),F(n.end);let s=[],i=0;for(;i<=r.length;){o?.throwIfAborted();let c=r.indexOf(n.start,i);if(c<0)break;let l=r.indexOf(n.end,c+n.start.length);if(l<0)throw new S("UNMATCHED_MARKER","Opening marker has no following closing marker in its input scope.");let u=e.from+c,d=e.from+l+n.end.length;t.boundary(u),t.boundary(u+n.start.length),t.boundary(e.from+l),t.boundary(d),s.push(n.extent==="lines"?t.fullLines(u,d):{from:n.extent==="inside"?u+n.start.length:u,to:n.extent==="inside"?e.from+l:d}),i=l+n.end.length}return s}case"sliceText":{let s=n.to??r.length;return Je(n.from,s,r.length),[{from:e.from+n.from,to:e.from+s}]}case"trim":{if(!r.trim().length)return[{from:e.to,to:e.to}];let s=n.side==="end"?0:r.length-r.trimStart().length,i=n.side==="start"?r.length:r.trimEnd().length;return[{from:e.from+s,to:e.from+i}]}case"split":{F(n.delimiter);let s=[],i=0;for(;i<=r.length;){o?.throwIfAborted();let c=r.indexOf(n.delimiter,i);if(s.push({from:e.from+i,to:c<0?e.to:e.from+c}),c<0)break;i=c+n.delimiter.length}return s}case"linesOf":return[t.fullLines(e.from,e.to)];case"position":{let s=n.edge==="before"?e.from:e.to;return[{from:s,to:s}]}case"columns":{let s=[],i=t.lineIndex(e.from),c=t.lineIndex(e.to>e.from?e.to-1:e.from);for(let l=i;l<=c;l++){o?.throwIfAborted();let u=t.lines[l];if(!u)throw new S("INVALID_RANGE","Source line bounds are unavailable.");Je(n.from,n.to,u.length);let d={from:u.start+n.from,to:u.start+n.to};if(d.from<e.from||d.to>e.to)throw new S("OUTSIDE_SCOPE","Requested columns exceed their input scope.");s.push(d)}return s}case"range":case"lines":throw new S("INVALID_RANGE","Absolute bounds must resolve against one source.")}}p(Ct,"transform");function F(t){if(!t.length)throw new S("INVALID_MARKER","Use a non-empty literal marker or delimiter.")}p(F,"nonEmpty");function Je(t,e,n){if(!Number.isSafeInteger(t)||!Number.isSafeInteger(e)||t<0||e<t||e>n)throw new S("INVALID_RANGE","Text bounds are outside their region or reversed.")}p(Je,"orderedBounds");function Qe(t,e,n,o){o?.throwIfAborted();let r=new Map;for(let u of[...t.targets,...n.targets]){o?.throwIfAborted();let d=r.get(u.source);if(d&&d.content!==u.expectedContent)throw new S("INCOMPATIBLE_SNAPSHOTS","Geometry inputs use different snapshots of the same source.");d||r.set(u.source,new I(u.expectedContent))}let s=We(t,r,o),i=We(n,r,o),c=new Map,l=0;for(let[u,d]of s){o?.throwIfAborted();let h=r.get(u);if(!h)throw new S("MISSING_SOURCE","Verified source text is unavailable.");let y=i.get(u)??[],g=Ye(y.map(C),!0,o),b=[];if(e.kind==="merge")b.push(...Ye(d.map(C),e.adjacent??!1,o));else for(let m of d){o?.throwIfAborted();let f=$t(m,y,g,e.kind,o);f.length||l++,b.push(...f)}for(let m of b){o?.throwIfAborted();let f=m.seeds[0];if(!f)throw new S("MISSING_ORIGIN","Geometry output has no candidate origin.");O(c,{target:f.target,range:h.range(m.from,m.to),text:h.content.slice(m.from,m.to),origins:m.seeds.map(x=>({source:u,range:v(x.range),expanded:m.from<x.from||m.to>x.to}))})}}return{regions:[...c.values()],missingInputs:l}}p(Qe,"selectGeometryRegions");function We(t,e,n){let o=new Map;for(let r of t.targets){let s=e.get(r.source);if(!s)throw new S("MISSING_SOURCE","Verified source text is unavailable.");let i=o.get(r.source)??[];for(let c of r.ranges){n?.throwIfAborted();let l=s.offset(c.start),u=s.offset(c.end);s.range(l,u),i.push({target:r,range:c,from:l,to:u})}o.set(r.source,i)}return o}p(We,"seedsBySource");function C(t){return{from:t.from,to:t.to,seeds:[t]}}p(C,"asSpan");function j(t,e){return e.from===e.to?t.from===t.to?e.from===t.from:t.from<=e.from&&e.from<t.to:t.from<=e.from&&e.to<=t.to}p(j,"contains");function $t(t,e,n,o,r){if(o==="within")return e.some(c=>j(c,t))?[C(t)]:[];if(t.from===t.to)return n.some(l=>j(l,t))===(o==="intersection")?[C(t)]:[];if(o==="intersection"){let c=[];for(let l of n)if(r?.throwIfAborted(),l.from===l.to)j(t,l)&&c.push({from:l.from,to:l.to,seeds:[t]});else{let u=Math.max(t.from,l.from),d=Math.min(t.to,l.to);u<d&&c.push({from:u,to:d,seeds:[t]})}return c}let s=[],i=t.from;for(let c of n)if(r?.throwIfAborted(),!(c.from===c.to||c.to<=i||c.from>=t.to)&&(c.from>i&&s.push({from:i,to:c.from,seeds:[t]}),i=Math.max(i,c.to),i>=t.to))break;return i<t.to&&s.push({from:i,to:t.to,seeds:[t]}),s}p($t,"transform");function Ye(t,e,n){let o=[...t].sort((i,c)=>i.from-c.from||i.to-c.to),r=[];for(let i of o){if(n?.throwIfAborted(),i.from===i.to)continue;let c=r.at(-1);c&&(i.from<c.to||e&&i.from===c.to)?r[r.length-1]={from:c.from,to:Math.max(c.to,i.to),seeds:[...c.seeds,...i.seeds]}:r.push(i)}let s=new Map;for(let i of o){if(n?.throwIfAborted(),i.from!==i.to)continue;let c=r.findIndex(d=>j(d,i)),l=c>=0?r[c]:s.get(i.from),u=l?{...l,seeds:[...l.seeds,...i.seeds]}:i;c>=0?r[c]=u:s.set(i.from,u)}return[...r,...s.values()].sort((i,c)=>i.from-c.from||i.to-c.to)}p(Ye,"mergeSpans");import{Type as a}from"typebox";var _t=a.Union([a.Object({kind:a.Literal("range"),startLine:a.Integer({minimum:1}),startColumn:a.Integer({minimum:0}),endLine:a.Integer({minimum:1}),endColumn:a.Integer({minimum:0})},{additionalProperties:!1,description:"Use absolute one-based lines and exclusive UTF-16 columns in one source. Require full containment in an input region."}),a.Object({kind:a.Literal("lines"),first:a.Integer({minimum:1}),last:a.Integer({minimum:1})},{additionalProperties:!1,description:"Use inclusive absolute line numbers in one source. Include existing line endings; require full containment in an input region."}),a.Object({kind:a.Literal("between"),start:a.String({minLength:1}),end:a.String({minLength:1}),extent:a.Union([a.Literal("inside"),a.Literal("around"),a.Literal("lines")])},{additionalProperties:!1,description:"Pair non-empty literal opening markers with the next closing marker per region, without nesting. Resume after each pair; unmatched openings are errors. inside excludes markers, around includes them, lines explicitly expands to complete containing lines."}),a.Object({kind:a.Literal("sliceText"),from:a.Integer({minimum:0}),to:a.Optional(a.Integer({minimum:0}))},{additionalProperties:!1,description:"Slice each region by non-negative relative UTF-16 offsets. The exclusive to defaults to its end. Equal offsets select a zero-width point."}),a.Object({kind:a.Literal("trim"),side:a.Union([a.Literal("start"),a.Literal("end"),a.Literal("both")])},{additionalProperties:!1,description:"Trim Unicode whitespace from the requested edges of each region. A whitespace-only region selects a zero-width point at its end."}),a.Object({kind:a.Literal("split"),delimiter:a.String({minLength:1})},{additionalProperties:!1,description:"Split each region by a non-empty literal delimiter, excluding delimiters and retaining empty segments as zero-width points."}),a.Object({kind:a.Literal("linesOf")},{additionalProperties:!1,description:"Expand each region to complete containing lines, preserving line endings and reporting expansion. An exclusive end at next-line column zero does not include that next line."}),a.Object({kind:a.Literal("position"),edge:a.Union([a.Literal("before"),a.Literal("after")])},{additionalProperties:!1,description:"Select the zero-width start or end of each region. Use a whole-file Read for file edges."}),a.Object({kind:a.Literal("columns"),from:a.Integer({minimum:0}),to:a.Integer({minimum:0})},{additionalProperties:!1,description:"Select an exclusive UTF-16 column interval on each touched line, excluding line endings. Every interval must fit its line and original input region; no clipping."})]);function H(t,e){return a.Object({kind:a.Literal(t),scopes:{...D,description:"Comparison scopes: unchanged results, issued UUIDs or item references, arrays of those strings, or a readable source path. Match sets by source, not array position."}},{additionalProperties:!1,description:e})}p(H,"scopedOperation");var Mt=a.Union([H("within","Retain each candidate whole only when one comparison scope contains it. Never clip or join scopes for containment."),H("intersection","Clip each candidate to the union of comparison scopes in its source. Touching text ranges do not create a point."),H("difference","Subtract comparison scopes from each candidate, retaining separate surviving fragments. Point scopes do not cut text."),a.Object({kind:a.Literal("merge"),adjacent:a.Optional(a.Boolean({description:"Also merge touching nonempty ranges. Default false; never fill a gap or extend text for a point."}))},{additionalProperties:!1,description:"Explicitly merge overlapping ranges by source, retaining every contributing origin. Covered points are absorbed; other points remain separate."})]),z=a.Union([a.Literal("function"),a.Literal("call"),a.Literal("class"),a.Literal("if"),a.Literal("switch"),a.Literal("loop"),a.Literal("try"),a.Literal("catch"),a.Literal("binding"),a.Literal("assignment"),a.Literal("object"),a.Literal("property"),a.Literal("array"),a.Literal("return"),a.Literal("throw")]),tt=a.Union([a.Literal("name"),a.Literal("body"),a.Literal("parameters"),a.Literal("returnType"),a.Literal("type"),a.Literal("callee"),a.Literal("arguments"),a.Literal("condition"),a.Literal("then"),a.Literal("else"),a.Literal("initializer"),a.Literal("update"),a.Literal("iterable"),a.Literal("left"),a.Literal("right"),a.Literal("value"),a.Literal("key"),a.Literal("handler"),a.Literal("finalizer"),a.Literal("parameter")]),Ze=a.Optional({...z,description:"Filter results by construct category after navigation. The filter does not change parent/child/sibling relationships."}),Dt=a.Union([a.Object({kind:a.Literal("elementExtent"),extent:a.Union([a.Literal("inside"),a.Literal("around")])},{additionalProperties:!1,description:"Select an exact direct JS/TS call argument or parenthesized function parameter. inside keeps the element; around includes owned comma/whitespace. around includes the following gap; the last element without a trailing comma includes the preceding gap, and an only element includes the whole list interior. Adjacent boundary comments reject around. No destination syntax repair."}),a.Object({kind:a.Literal("object"),object:z,relation:a.Optional(a.Literal("enclosing")),level:a.Optional(a.Integer({minimum:1,description:"Default 1 (nearest). Count only constructs of the requested category."})),extent:a.Optional(a.Literal("around"))},{additionalProperties:!1,description:"Select the requested containing construct. level=1 is nearest and includes an exact seed; higher levels count only that category. Match the entire seed, not its first character."}),a.Object({kind:a.Literal("part"),part:tt},{additionalProperties:!1,description:"Select an exact supported construct's named part, including delimiters belonging to its syntax node. A supported optional part may be absent; unsupported parts are errors with available names. Use an enclosing object first for partial input."}),a.Object({kind:a.Literal("navigate"),relation:a.Union([a.Literal("parent"),a.Literal("ancestors"),a.Literal("children"),a.Literal("descendants")]),object:Ze},{additionalProperties:!1,description:"Navigate from an exact named syntax node, including constructs, part targets and the document root. Skip parser-only wrappers in results. Exclude the starting node; ancestors/descendants return results in source order. parent/children never skip recognized constructs to satisfy a filter. Use enclosing first for ranges that cut through a node."}),a.Object({kind:a.Literal("navigate"),relation:a.Literal("siblings"),object:Ze,direction:a.Optional(a.Union([a.Literal("previous"),a.Literal("next"),a.Literal("all")],{description:"Default all. previous/next select the immediate sibling before category filtering, not the next matching category."}))},{additionalProperties:!1,description:"Select siblings of an exact supported construct under the same normalized parent. Exclude the input; return source order. A missing neighbor is valid absence."})]),nt=a.Object({path:{...D,description:"File path, unchanged Read/Search/Select/edit result, its UUID, or an array of such results. Pass the whole result; do not rebuild it from preview text."},operation:a.Union([Dt,_t,Mt],{description:"Choose a text, syntax or range-set operation. Text operations apply separately to each input region; range/lines require one source. Use UTF-16 bounds that do not split surrogate pairs or CRLF. Range-set operations match sources and snapshots, not array positions."})},{additionalProperties:!1}),et=a.Object({startLine:a.Integer({minimum:1}),startColumn:a.Integer({minimum:0}),endLine:a.Integer({minimum:1}),endColumn:a.Integer({minimum:0})},{additionalProperties:!1}),$=a.Object({kind:a.Literal("selection"),target:a.String({description:"Stored target for every selected range, including items beyond the preview."}),complete:a.Boolean({description:"Execution completeness inherited from all inputs, independent of preview limits."}),totalItems:a.Integer({minimum:0}),missingInputs:a.Integer({minimum:0}),truncated:a.Boolean(),items:a.Array(a.Object({target:a.String(),source:a.String(),range:et,syntax:a.Optional(a.Object({object:z,part:a.Optional(tt)},{additionalProperties:!1,description:"Parser-derived normalized construct category and selected part. This describes the target; it is not edit authority."})),origins:a.Array(a.Object({source:a.String(),range:et,expanded:a.Boolean()},{additionalProperties:!1})),preview:a.String({maxLength:1e3}),textTruncated:a.Boolean()},{additionalProperties:!1}),{maxItems:100})},{additionalProperties:!1}),rt=pe($);function Gt(t){let e=[`${t.totalItems} selection(s)${t.complete?"":" \xB7 incomplete input"}`];t.complete||e.push("Obtain complete source selections before checking absence or editing."),t.missingInputs&&e.push(`${t.missingInputs} input range(s) produced no selection`);for(let n of t.items){let o=n.range;e.push(`${n.target} ${n.source}:${o.startLine}:${o.startColumn}\u2013${o.endLine}:${o.endColumn}${n.syntax?` ${n.syntax.object}${n.syntax.part?`/${n.syntax.part}`:""}`:""}`,n.preview),o.startLine===o.endLine&&o.startColumn===o.endColumn&&e.push("Zero-width position; no text selected."),n.textTruncated&&e.push("\u2026 preview shortened; pass this item reference to consume the full selection")}return t.truncated&&e.push("\u2026 more selections retained; pass the whole result to consume all selections"),e.join(`
15
- `)}p(Gt,"selectionText");function Bt(t){switch(t.kind){case"object":return`enclosing ${t.object} \xB7 level ${t.level??1}`;case"part":return`part ${t.part}`;case"elementExtent":return`list element \xB7 ${t.extent}`;case"navigate":return`${t.relation}${t.relation==="siblings"?` ${t.direction??"all"}`:""}${t.object?` \xB7 ${t.object}`:""}`;case"between":return`between ${JSON.stringify(t.start)} \u2026 ${JSON.stringify(t.end)} \xB7 ${t.extent}`;case"range":return`range ${t.startLine}:${t.startColumn}\u2013${t.endLine}:${t.endColumn}`;case"lines":return`lines ${t.first}\u2013${t.last}`;case"sliceText":return`text slice ${t.from}\u2013${t.to??"end"}`;case"trim":return`trim ${t.side}`;case"split":return`split ${JSON.stringify(t.delimiter)}`;case"linesOf":return"containing lines";case"position":return`position ${t.edge}`;case"columns":return`columns ${t.from}\u2013${t.to}`;case"within":case"intersection":case"difference":return t.kind;case"merge":return t.adjacent?"merge overlaps and adjacent ranges":"merge overlaps"}}p(Bt,"operationLabel");function ot(t){return t.kind==="within"||t.kind==="intersection"||t.kind==="difference"||t.kind==="merge"}p(ot,"isGeometryOperation");async function st(t,e){let n=fe(t);re(t,[await ne({id:"select-code",description:"Derive text and AST boundaries, navigate constructs and combine source-range sets",triggers:[{tool:"select"}]})]),t.registerTool(ve({name:"select",label:"select",exposure:"direct",namespace:{name:"ide_select",description:"Derive exact source boundaries from existing targets."},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1},description:"Use select to derive text ranges or positions, navigate JavaScript/TypeScript constructs and their parts (without JSX/TSX), and combine source-local selections. Pass the returned result or an item reference to Read, Search or an edit tool. Select does not change files.",promptSnippet:"Derive text and AST boundaries, navigate constructs and combine source-range sets",promptGuidelines:["Use Search for predicate matches and existing captures; use Select when a target needs new text or structural boundaries.","Compare the enclosing owner of each inner match with the original function when checking a condition in that function's own body."],parameters:nt,outputSchema:rt,renderCall(o,r,s){return de(s.lastComponent,{tool:"select",primary:{text:Bt(o.operation),color:"accent"},qualifiers:[{text:typeof o.path=="string"&&!o.path.startsWith("RESULT#")?o.path:"in result scope"}],expanded:s.expanded},r)},renderResult(o,r,s){let i=o.details;return i?new ce(i,s,r.expanded):new Ut(o.content.flatMap(c=>c.type==="text"?[c.text]:[]).join(`
16
- `),0,0)},async execute(o,r,s,i,c){try{s?.throwIfAborted();let l=p(async f=>{if(typeof f=="string"&&!f.startsWith("RESULT#")){let x=await e.read({path:f},{cwd:c.cwd,...s!==void 0&&{signal:s}},"script");if(x.isError)throw new Error("Select could not read this source.");f=x.script}return n.resolve(f,c.cwd)},"resolve"),u=await l(r.path),d=r.operation,h=ot(d)&&"scopes"in d?await l(d.scopes):{targets:[],complete:!0},y={targets:[...u.targets,...h.targets],complete:u.complete&&h.complete};await n.verify(y,s);let g=ot(d)?Qe(u,d,h,s):d.kind==="object"||d.kind==="part"||d.kind==="navigate"||d.kind==="elementExtent"?await Xe(u,d,c.cwd,s):Ke(u,d,s);await n.verify(y,s),s?.throwIfAborted();let b=g.regions.map(f=>({...f.target,ranges:[f.range]})),m={kind:"selection",target:n.register(b,c.cwd,y.complete),complete:y.complete,totalItems:g.regions.length,missingInputs:g.missingInputs,truncated:g.regions.length>100,items:g.regions.slice(0,100).map(f=>{let x=f.text.slice(0,1e3).replace(/[\uD800-\uDBFF]$/u,"");return{target:n.register([{...f.target,ranges:[f.range]}],c.cwd,y.complete),source:f.target.source,range:v(f.range),origins:f.origins,...f.syntax?{syntax:f.syntax}:{},preview:x,textTruncated:x.length<f.text.length}})};return M({content:[{type:"text",text:Gt(m)}],details:Fe(g.regions,y.complete,g.missingInputs,c.cwd)},$,{status:"success",data:m,errors:[]})}catch(l){if(s?.aborted)throw l;return M({content:[{type:"text",text:`${l instanceof Error?l.message:String(l)}
17
- Resolve the reported error before retrying. Do not treat a failed selection as an empty result.`}],details:void 0},$,{status:"error",errors:[me(l,"SELECT_FAILED")]})}}},new Ae))}p(st,"registerSelect");var Vt=ue({kind:"code-view",label:"AST"});async function it(t){let e=new Le,n=Ne(e),o={protocol:se,apiVersion:ie,id:"ast",async setup(s){s.addResolver({resolver:Te(),renderResult:Vt}),s.addHandler({stage:"read",when:{resolvedBy:"ast",contentKind:"text"},handler:Y()}),s.addView({view:"ast",presenter:n});let i=Ee();s.addOutputReducer(B);let c=Pe();s.addHandler({stage:"post-read",async handler(l){let u=await i(l);return u.kind==="return"?u:c(u.context)}}),s.describe({path:"ast:<path> \u2014 compact declaration outline for a code file.",views:"ast \u2014 scope boundaries alongside source text."}),await st(t,s)}},r={protocol:ge,apiVersion:he,id:"ast",setup(s){s.addAnchorResolver({resolver:$e(e),kind:ye,type:"auxiliary"}),s.addTextPresenter({presenter:n})}};await Promise.all([ae(t,o),oe(t,Oe),be(t,r),we(t,{protocol:Se,apiVersion:xe,id:"ast-search",setup(s){s.addResolver({resolver:Be(s.registerSelection)}),s.describe("Search code structure with ast:<pattern>, using source-code syntax and placeholders such as $NAME for one node and $$$BODY for several nodes. path, include and exclude narrow the search. Use returned SEARCH# references to read, replace, copy, move or delete exact AST matches, including multiline nodes. A single :match reference becomes stale after its file changes; :all:match reruns the original structural query. Incomplete results do not provide all selections. Use the displayed capture NAME reference as a Search/Select/edit source. Single captures contain one node; multi captures retain provider nodes, including punctuation. Strict result scopes return only wholly contained matches. These edits do not update imports or references.")}})])}p(it,"registerAst");export{it as default};
13
+ `)[h-1]?.replace(/\r$/u,"")??""}})}p(Ue,"selectionMatches");function At(t,e,n,s,r){if(s?.throwIfAborted(),r?.length===0)return Promise.resolve([]);let o=["run","--pattern",t,"--json=compact","--no-ignore","parent"];for(let i of Ge(e.include))o.push("--globs",i);for(let i of Ge(e.exclude))o.push("--globs",`!${i}`);return o.push(...r??[e.path??"."]),new Promise((i,c)=>{let l=wt("ast-grep",o,{cwd:n,stdio:["ignore","pipe","pipe"]}),u="",d="";l.stdout.setEncoding("utf8"),l.stderr.setEncoding("utf8"),l.stdout.on("data",y=>u+=y),l.stderr.on("data",y=>d+=y);let h=p(()=>{l.kill("SIGTERM")},"abort");s?.addEventListener("abort",h,{once:!0}),l.once("error",c),l.once("close",y=>{if(s?.removeEventListener("abort",h),s?.aborted===!0){c(s.reason instanceof Error?s.reason:new Error("AST search aborted"));return}if(y!==0&&y!==1){c(new Error(d.trim()||`ast-grep exited with code ${String(y)}`));return}try{let g=JSON.parse(u.length===0?"[]":u);if(!Array.isArray(g))throw new TypeError("ast-grep returned non-array JSON");i(g)}catch(g){c(g instanceof Error?g:new Error(String(g)))}})})}p(At,"runAstGrep");function Ge(t){return t?.split(",").map(e=>e.trim()).filter(Boolean)??[]}p(Ge,"splitGlobs");import{Text as Ut}from"@earendil-works/pi-tui";import Ve from"node:path";import{pathToFileURL as vt}from"node:url";function Fe(t,e,n,s){let r=new Map;for(let c of t){let l=r.get(c.target.source);l?l.push(c):r.set(c.target.source,[c])}let o=[];t.length||o.push({kind:"note",text:"No selections"}),e||o.push({kind:"note",text:"Incomplete input; not a complete edit scope"}),n&&o.push({kind:"note",text:`${n} input(s) without a selection`});let i=100;for(let[c,l]of r){if(!i)break;let u=l.slice(0,i);i-=u.length;let d=Ve.relative(s,c)||Ve.basename(c),h=[],y=!1,g=l[0]?.target.expectedContent.split(/\r\n|\n|\r/u)??[];for(let m of u){let{start:f,end:x}=m.range,w=f.lineNumber===x.lineNumber&&f.column===x.column?f.lineNumber:x.lineNumber-(x.column===0?1:0),T=Math.min(w,f.lineNumber+19);y||=T<w;for(let A=f.lineNumber;A<=T;A++){let q=g[A-1]??"";h.push({source:c,label:d,link:vt(c).href,lineNumber:A,text:q,ranges:[{from:A===f.lineNumber?f.column:0,to:A===x.lineNumber?x.column:q.length}]})}}let b=le(h);o.push(...b.map(m=>m.kind==="source"?{...m,count:l.length}:m)),y&&o.push({kind:"note",text:"\u2026 selection preview shortened \xB7 full target retained"});for(let m of u){m.range.start.lineNumber===m.range.end.lineNumber&&m.range.start.column===m.range.end.column&&o.push({kind:"note",text:`zero-width \xB7 ${m.range.start.lineNumber}:${m.range.start.column}`});let{start:f,end:x}=m.range;o.push({kind:"note",expandedOnly:!0,text:`${m.syntax?`${m.syntax.object}${m.syntax.part?`/${m.syntax.part}`:""} \xB7 `:""}${f.lineNumber}:${f.column}\u2013${x.lineNumber}:${x.column} \xB7 ${m.origins.length} origin(s)${m.origins.some(R=>R.expanded)?" \xB7 expanded":""}`});for(let R of m.origins.slice(0,20)){let w=R.range;o.push({kind:"note",expandedOnly:!0,text:`from ${w.startLine}:${w.startColumn}\u2013${w.endLine}:${w.endColumn}`})}m.origins.length>20&&o.push({kind:"note",expandedOnly:!0,text:"\u2026 more origins retained in this result reference"})}}return t.length>100&&o.push({kind:"note",text:"\u2026 more selections \xB7 consume the complete result target"}),{summary:`${t.length} ${t.length===1?"selection":"selections"} in ${r.size} ${r.size===1?"file":"files"}${e?"":" \xB7 incomplete"}`,rows:o}}p(Fe,"selectPresentation");import Tt from"node:path";var S=class extends Error{constructor(n,s){super(s);this.code=n}static{p(this,"SelectionError")}};function v(t){return{startLine:t.start.lineNumber,startColumn:t.start.column,endLine:t.end.lineNumber,endColumn:t.end.column}}p(v,"publicRange");function O(t,e){let n=JSON.stringify([e.target.source,e.range]),s=t.get(n);t.set(n,s?{...e,origins:[...s.origins,...e.origins]}:e)}p(O,"retainRegion");var I=class{constructor(e){this.content=e;let n=0,s=W("",e),r=s.lines.map(o=>{let i=n;return n+=o.content.length+o.lineEnding.length,{start:i,length:o.content.length,end:n}});(r.length===0||s.lines.at(-1)?.lineEnding)&&r.push({start:n,length:0,end:n}),this.lines=r}static{p(this,"SourceText")}lines;boundary(e){if(!Number.isSafeInteger(e)||e<0||e>this.content.length)throw new S("INVALID_RANGE","Text bounds are outside the retained snapshot.");let n=this.content.charCodeAt(e-1),s=this.content.charCodeAt(e);if(n>=55296&&n<=56319&&s>=56320&&s<=57343||n===13&&s===10)throw new S("INVALID_BOUNDARY","Text boundary splits a surrogate pair or CRLF separator.")}offset(e){let n=this.lines[e.lineNumber-1];if(!Number.isSafeInteger(e.lineNumber)||!n||!Number.isSafeInteger(e.column)||e.column<0||e.column>n.length)throw new S("INVALID_RANGE","Source bounds are outside the retained snapshot.");let s=n.start+e.column;return this.boundary(s),s}lineIndex(e){let n=0,s=this.lines.length-1;for(;n<s;){let r=Math.ceil((n+s)/2);(this.lines[r]?.start??0)<=e?n=r:s=r-1}return n}position(e){this.boundary(e);let n=this.lineIndex(e);return{lineNumber:n+1,column:e-(this.lines[n]?.start??0)}}range(e,n){if(n<e)throw new S("INVALID_RANGE","Text bounds are reversed.");return{start:this.position(e),end:this.position(n)}}fullLines(e,n){let s=this.lines[this.lineIndex(e)],r=this.lines[this.lineIndex(n>e?n-1:e)];if(!s||!r)throw new S("INVALID_RANGE","Source line bounds are unavailable.");return{from:s.start,to:r.end}}};function He(t,e,n){let s=t;for(;s.parent&&s.parent.node.startIndex===s.node.startIndex&&s.parent.node.endIndex===s.node.endIndex;)s=s.parent;let r=s.parent;if(!r||!(r.node.type==="arguments"&&r.parent?.object==="call"||r.node.type==="formal_parameters"&&r.parent?.object==="function")||s.node.type==="comment")throw new S("EXACT_LIST_ELEMENT_REQUIRED","elementExtent requires an exact direct call argument or parenthesized function parameter. Use a full AST capture; partial expressions and other lists are not supported.");let o=r.node.startIndex,i=r.node.endIndex-1;if(n[o]!=="("||n[i]!==")")throw new S("UNSUPPORTED_LIST","Only parenthesized argument and parameter lists are supported.");if(e==="inside")return{startIndex:s.node.startIndex,endIndex:s.node.endIndex};let c=r.children.filter(m=>m.node.type!=="comment"),l=c.indexOf(s),u=c[l-1],d=c[l+1],h=u?.node.endIndex??o+1,y=d?.node.startIndex??i,g=n.slice(h,s.node.startIndex),b=n.slice(s.node.endIndex,y);if(!(u?/^\s*,\s*$/u:/^\s*$/u).test(g)||!(d?/^\s*,\s*$/u:/^\s*,?\s*$/u).test(b))throw new S("AMBIGUOUS_LIST_TRIVIA","Comments or unsupported trivia in adjacent list gaps have no inferred owner. Use inside for the exact element, or choose explicit text boundaries.");return c.length===1?{startIndex:o+1,endIndex:i}:d||b.includes(",")?{startIndex:s.node.startIndex,endIndex:y}:{startIndex:h,endIndex:s.node.endIndex}}p(He,"listElementExtent");var It={function_declaration:"function",generator_function_declaration:"function",function_expression:"function",generator_function:"function",arrow_function:"function",method_definition:"function",function_signature:"function",method_signature:"function",abstract_method_signature:"function",call_expression:"call",new_expression:"call",class_declaration:"class",class:"class",abstract_class_declaration:"class",if_statement:"if",switch_statement:"switch",for_statement:"loop",for_in_statement:"loop",while_statement:"loop",do_statement:"loop",try_statement:"try",catch_clause:"catch",variable_declarator:"binding",assignment_expression:"assignment",augmented_assignment_expression:"assignment",object:"object",object_pattern:"object",pair:"property",pair_pattern:"property",shorthand_property_identifier:"property",shorthand_property_identifier_pattern:"property",array:"array",array_pattern:"array",return_statement:"return",throw_statement:"throw"};function ze(t,e){let n=[],s=[{node:t,parent:void 0}];for(;s.length;){e?.throwIfAborted();let r=s.pop();if(!r)continue;let o={node:r.node,object:It[r.node.type],parent:r.parent,children:[]};r.parent?.children.push(o),n.push(o);for(let i of r.node.namedChildren.toReversed())s.push({node:i,parent:o})}return n}p(ze,"constructIndex");function L(t){let e=t.parent;for(;e&&!e.object;)e=e.parent;return e}p(L,"constructParent");function V(t,e,n){let s=[],r=[...t.children].reverse();for(;r.length;){n?.throwIfAborted();let o=r.pop();o&&(o.object&&s.push(o),(e||!o.object)&&r.push(...o.children.toReversed()))}return s}p(V,"constructChildren");var Lt={function:[["name",["name"]],["body",["body"]],["parameters",["parameters","parameter"]],["returnType",["return_type"]]],call:[["callee",["function","constructor"]],["arguments",["arguments"]]],class:[["name",["name"]],["body",["body"]]],if:[["condition",["condition"]],["then",["consequence"]],["else",["alternative"]]],switch:[["condition",["value"]],["body",["body"]]],loop:[["condition",["condition"]],["body",["body"]]],try:[["body",["body"]],["handler",["handler"]],["finalizer",["finalizer"]]],catch:[["body",["body"]],["parameter",["parameter"]]],binding:[["name",["name"]],["type",["type"]],["value",["value"]]],assignment:[["left",["left"]],["right",["right"]]],property:[["key",["key"]],["value",["value"]]],return:[["value",[]]],throw:[["value",[]]],object:[],array:[]};function Ot(t){return t.node.type==="for_statement"?[["initializer",["initializer"]],["condition",["condition"]],["update",["increment"]],["body",["body"]]]:t.node.type==="for_in_statement"?[["left",["left"]],["iterable",["right"]],["body",["body"]]]:t.node.type==="finally_clause"?[["body",["body"]]]:t.object?Lt[t.object]:[]}p(Ot,"partFields");function qe(t,e){let n=Ot(t),s=n.find(([r])=>r===e)?.[1];if(!s)throw new S("UNSUPPORTED_PART",`Unsupported part ${e} for ${t.object??"this syntax container"}; supported parts: ${n.map(([r])=>r).join(", ")||"none"}. Use navigate children/descendants for nested constructs.`);if(t.object==="property"&&t.node.type.startsWith("shorthand_property_identifier"))return t.node;if(t.object==="return"||t.object==="throw")return t.node.namedChildren.find(r=>r.type!=="comment");for(let r of s){let o=t.node.childForFieldName(r);if(o)return o}}p(qe,"constructPart");var Et=new Set([".js",".mjs",".cjs",".ts",".mts",".cts"]);function kt(t,e,n){let s=t.filter(o=>o.node.startIndex===e&&o.node.endIndex===n),r=s.find(o=>o.object)??s.at(-1);if(!r)throw new S("EXACT_NODE_REQUIRED","Navigation and parts require an exact syntax node. Use object/enclosing first for a partial match; use a returned part target to navigate its contents.");return r}p(kt,"exactNode");function Nt(t,e,n,s){let r;for(let i of t)i.object!==s.object||i.node.startIndex>e||i.node.endIndex<n||e===n&&i.node.endIndex===n||(!r||i.node.endIndex-i.node.startIndex<r.node.endIndex-r.node.startIndex)&&(r=i);if(!r&&t.filter(i=>i.object===s.object&&i.node.startIndex<n&&i.node.endIndex>e).length>1)throw new S("AMBIGUOUS_SEED","The seed spans separate constructs; select narrower input ranges.");let o=1;for(;r&&o<(s.level??1);){for(r=L(r);r&&r.object!==s.object;)r=L(r);o++}return r}p(Nt,"enclosing");function Pt(t,e,n,s){let r;switch(e.relation){case"parent":{let o=L(t);r=o?[o]:[];break}case"ancestors":{r=[];let o=L(t);for(;o;)s?.throwIfAborted(),r.push(o),o=L(o);break}case"children":case"descendants":{r=V(t,e.relation==="descendants",s);break}case"siblings":{if(!t.object)throw new S("EXACT_CONSTRUCT_REQUIRED","siblings requires an exact supported construct, not a part container. Use enclosing first.");let o=V(L(t)??n,!1,s),i=o.indexOf(t),c=e.direction??"all",l=c==="previous"?o[i-1]:o[i+1];r=c==="all"?o.filter(u=>u!==t):l?[l]:[];break}}return r.filter(o=>!e.object||o.object===e.object).sort((o,i)=>o.node.startIndex-i.node.startIndex||i.node.endIndex-o.node.endIndex)}p(Pt,"navigate");async function Xe(t,e,n,s){let r=new Map,o=0;for(let i of t.targets){if(s?.throwIfAborted(),!Et.has(Tt.extname(i.source).toLowerCase()))throw new S("UNSUPPORTED_LANGUAGE","Select AST supports JavaScript and TypeScript files, without JSX/TSX.");let c=await N(i.source,n,i.expectedContent.split(`
14
+ `));if(!c)throw new S("UNSUPPORTED_PROVIDER","No syntax provider is available for this source.");try{if(c.rootNode.hasError)throw new S("INVALID_SYNTAX","The syntax provider reports errors; no structural targets were created.");let l=ze(c.rootNode,s),u=l[0];if(!u)throw Error("Missing syntax root");let d=new I(i.expectedContent);for(let h of i.ranges){s?.throwIfAborted();let y=d.offset(h.start),g=d.offset(h.end),b=e.kind==="object"?Nt(l,y,g,e):kt(l,y,g),m=b&&e.kind==="elementExtent"?He(b,e.extent,i.expectedContent):void 0,f=b?e.kind==="part"?[qe(b,e.part)].filter(x=>x!==void 0).map(x=>({node:x,object:b.object})):e.kind==="navigate"?Pt(b,e,u,s):[b]:[];f.length||o++;for(let x of f){let R=m??x.node,w=x.object&&e.kind!=="elementExtent"?{object:x.object,...e.kind==="part"?{part:e.part}:{}}:void 0;O(r,{target:i,range:{start:d.position(R.startIndex),end:d.position(R.endIndex)},text:i.expectedContent.slice(R.startIndex,R.endIndex),origins:[{source:i.source,range:v({start:h.start,end:d.position(g)}),expanded:R.startIndex<y||R.endIndex>g}],...w?{syntax:w}:{}})}}}finally{c.delete?.()}}return{regions:[...r.values()],missingInputs:o}}p(Xe,"selectStructuralRegions");function Ke(t,e,n){n?.throwIfAborted();let s=e.kind==="range"||e.kind==="lines";if(s&&new Set(t.targets.map(i=>i.source)).size>1)throw new S("MULTIPLE_SOURCES","Absolute text bounds require one source.");let r=new Map,o=0;for(let i of t.targets){n?.throwIfAborted();let c=new I(i.expectedContent),l=s?jt(c,e):void 0,u=!1;for(let d of i.ranges){n?.throwIfAborted();let h=c.offset(d.start),y=c.offset(d.end);c.range(h,y);let g=l?l.from>=h&&l.to<=y?[l]:[]:Ct(c,{from:h,to:y},e,n);g.length?u=!0:o++;for(let b of g){n?.throwIfAborted();let m=c.range(b.from,b.to),f=b.from<h||b.to>y;if(f&&e.kind!=="linesOf"&&!(e.kind==="between"&&e.extent==="lines"))throw new S("OUTSIDE_SCOPE","Text selection exceeds its input scope.");O(r,{target:i,range:m,text:c.content.slice(b.from,b.to),origins:[{source:i.source,range:v(d),expanded:f}]})}}if(l&&!u)throw new S("OUTSIDE_SCOPE","Requested text bounds are outside every input scope.")}return{regions:[...r.values()],missingInputs:o}}p(Ke,"selectTextRegions");function jt(t,e){if(e.kind==="range"){let r=t.offset({lineNumber:e.startLine,column:e.startColumn}),o=t.offset({lineNumber:e.endLine,column:e.endColumn});return t.range(r,o),{from:r,to:o}}let n=t.lines[e.first-1],s=t.lines[e.last-1];if(!Number.isSafeInteger(e.first)||!Number.isSafeInteger(e.last)||!n||!s||e.last<e.first)throw new S("INVALID_RANGE","Line bounds are outside the retained snapshot or reversed.");return{from:n.start,to:s.end}}p(jt,"absoluteInterval");function Ct(t,e,n,s){let r=t.content.slice(e.from,e.to);switch(n.kind){case"between":{F(n.start),F(n.end);let o=[],i=0;for(;i<=r.length;){s?.throwIfAborted();let c=r.indexOf(n.start,i);if(c<0)break;let l=r.indexOf(n.end,c+n.start.length);if(l<0)throw new S("UNMATCHED_MARKER","Opening marker has no following closing marker in its input scope.");let u=e.from+c,d=e.from+l+n.end.length;t.boundary(u),t.boundary(u+n.start.length),t.boundary(e.from+l),t.boundary(d),o.push(n.extent==="lines"?t.fullLines(u,d):{from:n.extent==="inside"?u+n.start.length:u,to:n.extent==="inside"?e.from+l:d}),i=l+n.end.length}return o}case"sliceText":{let o=n.to??r.length;return Je(n.from,o,r.length),[{from:e.from+n.from,to:e.from+o}]}case"trim":{if(!r.trim().length)return[{from:e.to,to:e.to}];let o=n.side==="end"?0:r.length-r.trimStart().length,i=n.side==="start"?r.length:r.trimEnd().length;return[{from:e.from+o,to:e.from+i}]}case"split":{F(n.delimiter);let o=[],i=0;for(;i<=r.length;){s?.throwIfAborted();let c=r.indexOf(n.delimiter,i);if(o.push({from:e.from+i,to:c<0?e.to:e.from+c}),c<0)break;i=c+n.delimiter.length}return o}case"linesOf":return[t.fullLines(e.from,e.to)];case"position":{let o=n.edge==="before"?e.from:e.to;return[{from:o,to:o}]}case"columns":{let o=[],i=t.lineIndex(e.from),c=t.lineIndex(e.to>e.from?e.to-1:e.from);for(let l=i;l<=c;l++){s?.throwIfAborted();let u=t.lines[l];if(!u)throw new S("INVALID_RANGE","Source line bounds are unavailable.");Je(n.from,n.to,u.length);let d={from:u.start+n.from,to:u.start+n.to};if(d.from<e.from||d.to>e.to)throw new S("OUTSIDE_SCOPE","Requested columns exceed their input scope.");o.push(d)}return o}case"range":case"lines":throw new S("INVALID_RANGE","Absolute bounds must resolve against one source.")}}p(Ct,"transform");function F(t){if(!t.length)throw new S("INVALID_MARKER","Use a non-empty literal marker or delimiter.")}p(F,"nonEmpty");function Je(t,e,n){if(!Number.isSafeInteger(t)||!Number.isSafeInteger(e)||t<0||e<t||e>n)throw new S("INVALID_RANGE","Text bounds are outside their region or reversed.")}p(Je,"orderedBounds");function Qe(t,e,n,s){s?.throwIfAborted();let r=new Map;for(let u of[...t.targets,...n.targets]){s?.throwIfAborted();let d=r.get(u.source);if(d&&d.content!==u.expectedContent)throw new S("INCOMPATIBLE_SNAPSHOTS","Geometry inputs use different snapshots of the same source.");d||r.set(u.source,new I(u.expectedContent))}let o=We(t,r,s),i=We(n,r,s),c=new Map,l=0;for(let[u,d]of o){s?.throwIfAborted();let h=r.get(u);if(!h)throw new S("MISSING_SOURCE","Verified source text is unavailable.");let y=i.get(u)??[],g=Ye(y.map(C),!0,s),b=[];if(e.kind==="merge")b.push(...Ye(d.map(C),e.adjacent??!1,s));else for(let m of d){s?.throwIfAborted();let f=$t(m,y,g,e.kind,s);f.length||l++,b.push(...f)}for(let m of b){s?.throwIfAborted();let f=m.seeds[0];if(!f)throw new S("MISSING_ORIGIN","Geometry output has no candidate origin.");O(c,{target:f.target,range:h.range(m.from,m.to),text:h.content.slice(m.from,m.to),origins:m.seeds.map(x=>({source:u,range:v(x.range),expanded:m.from<x.from||m.to>x.to}))})}}return{regions:[...c.values()],missingInputs:l}}p(Qe,"selectGeometryRegions");function We(t,e,n){let s=new Map;for(let r of t.targets){let o=e.get(r.source);if(!o)throw new S("MISSING_SOURCE","Verified source text is unavailable.");let i=s.get(r.source)??[];for(let c of r.ranges){n?.throwIfAborted();let l=o.offset(c.start),u=o.offset(c.end);o.range(l,u),i.push({target:r,range:c,from:l,to:u})}s.set(r.source,i)}return s}p(We,"seedsBySource");function C(t){return{from:t.from,to:t.to,seeds:[t]}}p(C,"asSpan");function j(t,e){return e.from===e.to?t.from===t.to?e.from===t.from:t.from<=e.from&&e.from<t.to:t.from<=e.from&&e.to<=t.to}p(j,"contains");function $t(t,e,n,s,r){if(s==="within")return e.some(c=>j(c,t))?[C(t)]:[];if(t.from===t.to)return n.some(l=>j(l,t))===(s==="intersection")?[C(t)]:[];if(s==="intersection"){let c=[];for(let l of n)if(r?.throwIfAborted(),l.from===l.to)j(t,l)&&c.push({from:l.from,to:l.to,seeds:[t]});else{let u=Math.max(t.from,l.from),d=Math.min(t.to,l.to);u<d&&c.push({from:u,to:d,seeds:[t]})}return c}let o=[],i=t.from;for(let c of n)if(r?.throwIfAborted(),!(c.from===c.to||c.to<=i||c.from>=t.to)&&(c.from>i&&o.push({from:i,to:c.from,seeds:[t]}),i=Math.max(i,c.to),i>=t.to))break;return i<t.to&&o.push({from:i,to:t.to,seeds:[t]}),o}p($t,"transform");function Ye(t,e,n){let s=[...t].sort((i,c)=>i.from-c.from||i.to-c.to),r=[];for(let i of s){if(n?.throwIfAborted(),i.from===i.to)continue;let c=r.at(-1);c&&(i.from<c.to||e&&i.from===c.to)?r[r.length-1]={from:c.from,to:Math.max(c.to,i.to),seeds:[...c.seeds,...i.seeds]}:r.push(i)}let o=new Map;for(let i of s){if(n?.throwIfAborted(),i.from!==i.to)continue;let c=r.findIndex(d=>j(d,i)),l=c>=0?r[c]:o.get(i.from),u=l?{...l,seeds:[...l.seeds,...i.seeds]}:i;c>=0?r[c]=u:o.set(i.from,u)}return[...r,...o.values()].sort((i,c)=>i.from-c.from||i.to-c.to)}p(Ye,"mergeSpans");import{Type as a}from"typebox";var _t=a.Union([a.Object({kind:a.Literal("range"),startLine:a.Integer({minimum:1}),startColumn:a.Integer({minimum:0}),endLine:a.Integer({minimum:1}),endColumn:a.Integer({minimum:0})},{additionalProperties:!1,description:"Use absolute one-based lines and exclusive UTF-16 columns in one source. Require full containment in an input region."}),a.Object({kind:a.Literal("lines"),first:a.Integer({minimum:1}),last:a.Integer({minimum:1})},{additionalProperties:!1,description:"Use inclusive absolute line numbers in one source. Include existing line endings; require full containment in an input region."}),a.Object({kind:a.Literal("between"),start:a.String({minLength:1}),end:a.String({minLength:1}),extent:a.Union([a.Literal("inside"),a.Literal("around"),a.Literal("lines")])},{additionalProperties:!1,description:"Pair non-empty literal opening markers with the next closing marker per region, without nesting. Resume after each pair; unmatched openings are errors. inside excludes markers, around includes them, lines explicitly expands to complete containing lines."}),a.Object({kind:a.Literal("sliceText"),from:a.Integer({minimum:0}),to:a.Optional(a.Integer({minimum:0}))},{additionalProperties:!1,description:"Slice each region by non-negative relative UTF-16 offsets. The exclusive to defaults to its end. Equal offsets select a zero-width point."}),a.Object({kind:a.Literal("trim"),side:a.Union([a.Literal("start"),a.Literal("end"),a.Literal("both")])},{additionalProperties:!1,description:"Trim Unicode whitespace from the requested edges of each region. A whitespace-only region selects a zero-width point at its end."}),a.Object({kind:a.Literal("split"),delimiter:a.String({minLength:1})},{additionalProperties:!1,description:"Split each region by a non-empty literal delimiter, excluding delimiters and retaining empty segments as zero-width points."}),a.Object({kind:a.Literal("linesOf")},{additionalProperties:!1,description:"Expand each region to complete containing lines, preserving line endings and reporting expansion. An exclusive end at next-line column zero does not include that next line."}),a.Object({kind:a.Literal("position"),edge:a.Union([a.Literal("before"),a.Literal("after")])},{additionalProperties:!1,description:"Select the zero-width start or end of each region. Use a whole-file Read for file edges."}),a.Object({kind:a.Literal("columns"),from:a.Integer({minimum:0}),to:a.Integer({minimum:0})},{additionalProperties:!1,description:"Select an exclusive UTF-16 column interval on each touched line, excluding line endings. Every interval must fit its line and original input region; no clipping."})]);function H(t,e){return a.Object({kind:a.Literal(t),scopes:{...D,description:"Comparison scopes: unchanged results, issued UUIDs or item references, arrays of those strings, or a readable source path. Match sets by source, not array position."}},{additionalProperties:!1,description:e})}p(H,"scopedOperation");var Mt=a.Union([H("within","Retain each candidate whole only when one comparison scope contains it. Never clip or join scopes for containment."),H("intersection","Clip each candidate to the union of comparison scopes in its source. Touching text ranges do not create a point."),H("difference","Subtract comparison scopes from each candidate, retaining separate surviving fragments. Point scopes do not cut text."),a.Object({kind:a.Literal("merge"),adjacent:a.Optional(a.Boolean({description:"Also merge touching nonempty ranges. Default false; never fill a gap or extend text for a point."}))},{additionalProperties:!1,description:"Explicitly merge overlapping ranges by source, retaining every contributing origin. Covered points are absorbed; other points remain separate."})]),z=a.Union([a.Literal("function"),a.Literal("call"),a.Literal("class"),a.Literal("if"),a.Literal("switch"),a.Literal("loop"),a.Literal("try"),a.Literal("catch"),a.Literal("binding"),a.Literal("assignment"),a.Literal("object"),a.Literal("property"),a.Literal("array"),a.Literal("return"),a.Literal("throw")]),tt=a.Union([a.Literal("name"),a.Literal("body"),a.Literal("parameters"),a.Literal("returnType"),a.Literal("type"),a.Literal("callee"),a.Literal("arguments"),a.Literal("condition"),a.Literal("then"),a.Literal("else"),a.Literal("initializer"),a.Literal("update"),a.Literal("iterable"),a.Literal("left"),a.Literal("right"),a.Literal("value"),a.Literal("key"),a.Literal("handler"),a.Literal("finalizer"),a.Literal("parameter")]),Ze=a.Optional({...z,description:"Filter results by construct category after navigation. The filter does not change parent/child/sibling relationships."}),Dt=a.Union([a.Object({kind:a.Literal("elementExtent"),extent:a.Union([a.Literal("inside"),a.Literal("around")])},{additionalProperties:!1,description:"Select an exact direct JS/TS call argument or parenthesized function parameter. inside keeps the element; around includes owned comma/whitespace. around includes the following gap; the last element without a trailing comma includes the preceding gap, and an only element includes the whole list interior. Adjacent boundary comments reject around. No destination syntax repair."}),a.Object({kind:a.Literal("object"),object:z,relation:a.Optional(a.Literal("enclosing")),level:a.Optional(a.Integer({minimum:1,description:"Default 1 (nearest). Count only constructs of the requested category."})),extent:a.Optional(a.Literal("around"))},{additionalProperties:!1,description:"Select the requested containing construct. level=1 is nearest and includes an exact seed; higher levels count only that category. Match the entire seed, not its first character."}),a.Object({kind:a.Literal("part"),part:tt},{additionalProperties:!1,description:"Select an exact supported construct's named part, including delimiters belonging to its syntax node. A supported optional part may be absent; unsupported parts are errors with available names. Use an enclosing object first for partial input."}),a.Object({kind:a.Literal("navigate"),relation:a.Union([a.Literal("parent"),a.Literal("ancestors"),a.Literal("children"),a.Literal("descendants")]),object:Ze},{additionalProperties:!1,description:"Navigate from an exact named syntax node, including constructs, part targets and the document root. Skip parser-only wrappers in results. Exclude the starting node; ancestors/descendants return results in source order. parent/children never skip recognized constructs to satisfy a filter. Use enclosing first for ranges that cut through a node."}),a.Object({kind:a.Literal("navigate"),relation:a.Literal("siblings"),object:Ze,direction:a.Optional(a.Union([a.Literal("previous"),a.Literal("next"),a.Literal("all")],{description:"Default all. previous/next select the immediate sibling before category filtering, not the next matching category."}))},{additionalProperties:!1,description:"Select siblings of an exact supported construct under the same normalized parent. Exclude the input; return source order. A missing neighbor is valid absence."})]),nt=a.Object({path:{...D,description:"File path, unchanged Read/Search/Select/edit result, its UUID, or an array of such results. Pass the whole result; do not rebuild it from preview text."},operation:a.Union([Dt,_t,Mt],{description:"Choose a text, syntax or range-set operation. Text operations apply separately to each input region; range/lines require one source. Use UTF-16 bounds that do not split surrogate pairs or CRLF. Range-set operations match sources and snapshots, not array positions."})},{additionalProperties:!1}),et=a.Object({startLine:a.Integer({minimum:1}),startColumn:a.Integer({minimum:0}),endLine:a.Integer({minimum:1}),endColumn:a.Integer({minimum:0})},{additionalProperties:!1}),$=a.Object({kind:a.Literal("selection"),target:a.String({description:"Stored target for every selected range, including items beyond the preview."}),complete:a.Boolean({description:"Execution completeness inherited from all inputs, independent of preview limits."}),totalItems:a.Integer({minimum:0}),missingInputs:a.Integer({minimum:0}),truncated:a.Boolean(),items:a.Array(a.Object({target:a.String(),source:a.String(),range:et,syntax:a.Optional(a.Object({object:z,part:a.Optional(tt)},{additionalProperties:!1,description:"Parser-derived normalized construct category and selected part. This describes the target; it is not edit authority."})),origins:a.Array(a.Object({source:a.String(),range:et,expanded:a.Boolean()},{additionalProperties:!1})),preview:a.String({maxLength:1e3}),textTruncated:a.Boolean()},{additionalProperties:!1}),{maxItems:100})},{additionalProperties:!1}),rt=pe($);function Gt(t){let e=[`${t.totalItems} selection(s)${t.complete?"":" \xB7 incomplete input"}`];t.complete||e.push("Obtain complete source selections before checking absence or editing."),t.missingInputs&&e.push(`${t.missingInputs} input range(s) produced no selection`);for(let n of t.items){let s=n.range;e.push(`${n.target} ${n.source}:${s.startLine}:${s.startColumn}\u2013${s.endLine}:${s.endColumn}${n.syntax?` ${n.syntax.object}${n.syntax.part?`/${n.syntax.part}`:""}`:""}`,n.preview),s.startLine===s.endLine&&s.startColumn===s.endColumn&&e.push("Zero-width position; no text selected."),n.textTruncated&&e.push("\u2026 preview shortened; pass this item reference to consume the full selection")}return t.truncated&&e.push("\u2026 more selections retained; pass the whole result to consume all selections"),e.join(`
15
+ `)}p(Gt,"selectionText");function Bt(t){switch(t.kind){case"object":return`enclosing ${t.object} \xB7 level ${t.level??1}`;case"part":return`part ${t.part}`;case"elementExtent":return`list element \xB7 ${t.extent}`;case"navigate":return`${t.relation}${t.relation==="siblings"?` ${t.direction??"all"}`:""}${t.object?` \xB7 ${t.object}`:""}`;case"between":return`between ${JSON.stringify(t.start)} \u2026 ${JSON.stringify(t.end)} \xB7 ${t.extent}`;case"range":return`range ${t.startLine}:${t.startColumn}\u2013${t.endLine}:${t.endColumn}`;case"lines":return`lines ${t.first}\u2013${t.last}`;case"sliceText":return`text slice ${t.from}\u2013${t.to??"end"}`;case"trim":return`trim ${t.side}`;case"split":return`split ${JSON.stringify(t.delimiter)}`;case"linesOf":return"containing lines";case"position":return`position ${t.edge}`;case"columns":return`columns ${t.from}\u2013${t.to}`;case"within":case"intersection":case"difference":return t.kind;case"merge":return t.adjacent?"merge overlaps and adjacent ranges":"merge overlaps"}}p(Bt,"operationLabel");function ot(t){return t.kind==="within"||t.kind==="intersection"||t.kind==="difference"||t.kind==="merge"}p(ot,"isGeometryOperation");async function st(t,e){let n=fe(t);re(t,[await ne({id:"select-code",description:"Derive text and AST boundaries, navigate constructs and combine source-range sets",triggers:[{tool:"select"}]})]),t.registerTool(ve({name:"select",label:"select",exposure:"direct",namespace:{name:"ide_select",description:"Derive exact source boundaries from existing targets."},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1},description:"Use select to derive text ranges or positions, navigate JavaScript/TypeScript constructs and their parts (without JSX/TSX), and combine source-local selections. Pass the returned result or an item reference to Read, Search or an edit tool. Select does not change files.",promptSnippet:"Derive text and AST boundaries, navigate constructs and combine source-range sets",promptGuidelines:["Use Search for predicate matches and existing captures; use Select when a target needs new text or structural boundaries.","Compare the enclosing owner of each inner match with the original function when checking a condition in that function's own body."],parameters:nt,outputSchema:rt,renderCall(s,r,o){return de(o.lastComponent,{tool:"select",primary:{text:Bt(s.operation),color:"accent"},qualifiers:[{text:typeof s.path=="string"&&!s.path.startsWith("RESULT#")?s.path:"in result scope"}],expanded:o.expanded},r)},renderResult(s,r,o){let i=s.details;return i?new ce(i,o,r.expanded):new Ut(s.content.flatMap(c=>c.type==="text"?[c.text]:[]).join(`
16
+ `),0,0)},async execute(s,r,o,i,c){try{o?.throwIfAborted();let l=p(async f=>{if(typeof f=="string"&&!f.startsWith("RESULT#")){let x=await e.read({path:f},{cwd:c.cwd,...o!==void 0&&{signal:o}},"script");if(x.isError)throw new Error("Select could not read this source.");f=x.script}return n.resolve(f,c.cwd)},"resolve"),u=await l(r.path),d=r.operation,h=ot(d)&&"scopes"in d?await l(d.scopes):{targets:[],complete:!0},y={targets:[...u.targets,...h.targets],complete:u.complete&&h.complete};await n.verify(y,o);let g=ot(d)?Qe(u,d,h,o):d.kind==="object"||d.kind==="part"||d.kind==="navigate"||d.kind==="elementExtent"?await Xe(u,d,c.cwd,o):Ke(u,d,o);await n.verify(y,o),o?.throwIfAborted();let b=g.regions.map(f=>({...f.target,ranges:[f.range]})),m={kind:"selection",target:n.register(b,c.cwd,y.complete),complete:y.complete,totalItems:g.regions.length,missingInputs:g.missingInputs,truncated:g.regions.length>100,items:g.regions.slice(0,100).map(f=>{let x=f.text.slice(0,1e3).replace(/[\uD800-\uDBFF]$/u,"");return{target:n.register([{...f.target,ranges:[f.range]}],c.cwd,y.complete),source:f.target.source,range:v(f.range),origins:f.origins,...f.syntax?{syntax:f.syntax}:{},preview:x,textTruncated:x.length<f.text.length}})};return M({content:[{type:"text",text:Gt(m)}],details:Fe(g.regions,y.complete,g.missingInputs,c.cwd)},$,{status:"success",data:m,errors:[]})}catch(l){if(o?.aborted)throw l;return M({content:[{type:"text",text:`${l instanceof Error?l.message:String(l)}
17
+ Resolve the reported error before retrying. Do not treat a failed selection as an empty result.`}],details:void 0},$,{status:"error",errors:[me(l,"SELECT_FAILED")]})}}},new Ae))}p(st,"registerSelect");var Vt=ue({kind:"code-view",label:"AST"});async function it(t){let e=new Le,n=Ne(e),s={protocol:se,apiVersion:ie,id:"ast",async setup(o){o.addResolver({resolver:Te(),renderResult:Vt}),o.addHandler({stage:"read",when:{resolvedBy:"ast",contentKind:"text"},handler:Y()}),o.addView({view:"ast",presenter:n});let i=Ee();o.addOutputReducer(B);let c=Pe();o.addHandler({stage:"post-read",async handler(l){let u=await i(l);return u.kind==="return"||u.transform!==void 0?u:c(u.context)}}),o.describe({path:"ast:<path> \u2014 compact declaration outline for a code file.",views:"ast \u2014 scope boundaries alongside source text."}),await st(t,o)}},r={protocol:ge,apiVersion:he,id:"ast",setup(o){o.addAnchorResolver({resolver:$e(e),kind:ye,type:"auxiliary"}),o.addTextPresenter({presenter:n})}};await Promise.all([ae(t,s),oe(t,Oe),be(t,r),we(t,{protocol:Se,apiVersion:xe,id:"ast-search",setup(o){o.addResolver({resolver:Be(o.registerSelection)}),o.describe("Search code structure with ast:<pattern>, using source-code syntax and placeholders such as $NAME for one node and $$$BODY for several nodes. path, include and exclude narrow the search. Use returned SEARCH# references to read, replace, copy, move or delete exact AST matches, including multiline nodes. A single :match reference becomes stale after its file changes; :all:match reruns the original structural query. Incomplete results do not provide all selections. Use the displayed capture NAME reference as a Search/Select/edit source. Single captures contain one node; multi captures retain provider nodes, including punctuation. Strict result scopes return only wholly contained matches. These edits do not update imports or references.")}})])}p(it,"registerAst");export{it as default};
package/dist/entry-33.js CHANGED
@@ -1,2 +1,3 @@
1
- import{a as Z,b as Y,c as J}from"./chunk-DEP55R35.js";import{e as F,f as j}from"./chunk-T7I2VX3J.js";import{a as M}from"./chunk-MGCHOGQD.js";import{a as O,b as U}from"./chunk-T6LX2RX5.js";import{a as q}from"./chunk-KOVPDKSJ.js";import{a as K,b as X}from"./chunk-SJ4UZ4GU.js";import{a as V}from"./chunk-BU7IZLKB.js";import{a as _,b as B}from"./chunk-S5PL5DFQ.js";import{G as W,f as z,i as Q,j as E}from"./chunk-6U5OU77O.js";import{a as D}from"./chunk-ZPT5D4VP.js";import{d as L,e as N}from"./chunk-N34ATN52.js";import{a as x}from"./chunk-ZC65Z3CK.js";import{a as s}from"./chunk-EI7MMDWY.js";import{access as ue}from"node:fs/promises";import le from"node:path";var ee={protocol:O,apiVersion:1,id:"changes",setup(n){n.addSetupCheck({id:"git",async inspect(e){return await ge(e.cwd)?await L("git",e.cwd,e.env)?{}:{actions:[{id:"git-unavailable",message:"Git integration is unavailable because Git was not found"}]}:{}}}),n.addCheck({id:"git",title:"Git changes",async run(e){let t=await N("git",["--version"],e.cwd,e.env);return[t.ok?{status:"pass",message:"Git is available",detail:t.detail}:{status:"warn",message:"Git is not available; change anchors and index tools are disabled",detail:t.detail}]}})}};async function ge(n){try{return await ue(le.join(n,".git")),!0}catch{return!1}}s(ge,"isGitProject");import{mkdtemp as fe,rm as pe,writeFile as he}from"node:fs/promises";import me from"node:os";import m from"node:path";var b=class n{constructor(e,t){this.executor=e;this.repositoryRoot=t}static{s(this,"GitChangesBackend")}static async create(e,t,r){let i=await e.exec("git",["rev-parse","--show-toplevel"],{cwd:t,...r!==void 0&&{signal:r}});return i.code!==0?{status:"unavailable",reason:"no-worktree",message:i.stderr.trim()||"not inside a Git worktree"}:{status:"ready",backend:new n(e,m.resolve(i.stdout.trim()))}}async readTrackedFile(e,t,r){let i=m.resolve(t,e),a=m.relative(this.repositoryRoot,i);return a===".."||a.startsWith(`..${m.sep}`)||m.isAbsolute(a)?{status:"unavailable",reason:"outside-worktree",message:`${i} is outside ${this.repositoryRoot}`}:this.readTrackedRepositoryFile(a.split(m.sep).join("/"),r)}async readTrackedRepositoryFile(e,t){let r=await this.git(["rev-parse","--verify","HEAD"],t);if(r.code!==0)return{status:"unavailable",reason:"missing-head",message:r.stderr.trim()||"Git HEAD does not exist"};let i=await this.git(["--literal-pathspecs","ls-tree","-z","HEAD","--",e],t);if(i.code!==0)return{status:"unavailable",reason:"head-file-lookup-failed",message:i.stderr.trim()||`could not inspect HEAD:${e}`};let a=xe(i.stdout);if(a===void 0)return{status:"untracked"};let c=await this.readBlob(a.blob,"HEAD",e,t);if(c.status!=="found")return c;let d=await this.git(["--literal-pathspecs","ls-files","--stage","-z","--",e],t);if(d.code!==0)return{status:"unavailable",reason:"index-file-lookup-failed",message:d.stderr.trim()||`could not inspect the index entry for ${e}`};let o=ye(d.stdout);if(o.some(({stage:u})=>u!==0))return{status:"unavailable",reason:"conflicted",message:`${e} has unresolved Git index entries`};let l=o.find(({stage:u})=>u===0),f="";if(l!==void 0){let u=await this.readBlob(l.blob,"index",e,t);if(u.status!=="found")return u;f=u.text}return{status:"found",head:r.stdout.trim(),repositoryPath:e,repositoryRoot:this.repositoryRoot,headText:c.text,indexText:f,indexMode:l?.mode??a.mode}}async writeIndexFile(e,t,r,i){let a=await fe(m.join(me.tmpdir(),"pi-agent-index-")),c=m.join(a,"content");try{await he(c,r,"utf8");let d=await this.git(["hash-object","-w",`--path=${e}`,c],i);if(d.code!==0||d.stdout.trim().length===0)throw new Error(d.stderr.trim()||`could not write a Git blob for ${e}`);let o=await this.git(["update-index","--add","--cacheinfo",t,d.stdout.trim(),e],i);if(o.code!==0)throw new Error(o.stderr.trim()||`could not update the Git index entry for ${e}`)}finally{await pe(a,{recursive:!0,force:!0})}}async readBlob(e,t,r,i){let a=await this.git(["cat-file","blob",e],i);return a.code!==0?{status:"unavailable",reason:t==="HEAD"?"head-file-lookup-failed":"index-file-lookup-failed",message:a.stderr.trim()||`could not read ${t}:${r}`}:{status:"found",text:a.stdout}}git(e,t){return this.executor.exec("git",e,{cwd:this.repositoryRoot,...t!==void 0&&{signal:t}})}};function xe(n){let e=n.split("\0",1)[0];if(e===void 0||e.length===0)return;let t=e.indexOf(" ");if(t===-1)return;let[r,i,a]=e.slice(0,t).split(" ",3);return r===void 0||i!=="blob"||a===void 0?void 0:{mode:r,blob:a,path:e.slice(t+1)}}s(xe,"parseTreeEntry");function ye(n){return n.split("\0").filter(Boolean).flatMap(e=>{let t=e.indexOf(" ");if(t===-1)return[];let[r,i,a]=e.slice(0,t).split(" ",3),c=Number(a);return r===void 0||i===void 0||!Number.isInteger(c)?[]:[{mode:r,blob:i,stage:c,path:e.slice(t+1)}]})}s(ye,"parseIndexEntries");function te(n){return{exec:s((e,t,r)=>n.exec(e,t,r),"exec")}}s(te,"extensionGitExecutor");var h=class n{constructor(e){this.git=e}static{s(this,"ChangeService")}static async create(e,t,r){let i=await b.create(e,t,r);return i.status==="unavailable"?i:{status:"ready",service:new n(i.backend)}}async inspect(e){if(e.worktreeText.includes("\0"))return{status:"unavailable",reason:"binary",message:"worktree file contains binary content"};let t=await this.git.readTrackedFile(e.source,e.cwd,e.signal);if(t.status!=="found")return t.status==="untracked"?{status:"not-applicable",reason:"untracked"}:t;if(t.headText.includes("\0")||t.indexText.includes("\0"))return{status:"unavailable",reason:"binary",message:"Git file state contains binary content"};let r=Z(t.repositoryPath,t.headText,t.indexText,e.worktreeText);return r.length===0?{status:"not-applicable",reason:"clean"}:{status:"applicable",head:t.head,repositoryRoot:t.repositoryRoot,repositoryPath:t.repositoryPath,groups:r}}async changeIndex(e,t,r){let i=await this.inspect(e);if(i.status!=="applicable")return i;let a=i.groups.find(l=>l.selector===t);if(a===void 0)return A(t,i.groups.map(({selector:l})=>l));let c=r==="stage"?"staged":"unstaged";if(a.state===c)return{status:"unchanged",state:c,group:a};let d=x(a.segments[0]),o={head:i.head,repositoryPath:i.repositoryPath,headStart:d.headStart,headEnd:d.headEnd,replacementText:r==="stage"?d.worktreeText:d.headText};try{await this.applyIndexUpdate(o,e.signal)}catch(l){return{status:"unavailable",reason:"index-write-failed",message:we(l)}}return{status:"applied",state:c,group:a}}async prepareUndo(e,t){let r=await this.inspect(e);if(r.status!=="applicable")return r;let i=r.groups.find(o=>o.selector===t);if(i===void 0)return A(t,r.groups.map(({selector:o})=>o));let a=Y(e.worktreeText,i);if(a===void 0)return A(t,r.groups.map(({selector:o})=>o));let c=x(i.segments[0]),d=i.state==="unstaged"?void 0:{head:r.head,repositoryPath:r.repositoryPath,headStart:c.headStart,headEnd:c.headEnd,replacementText:c.headText};return{status:"applied",worktreeText:a,group:i,...d!==void 0&&{indexUpdate:d}}}async applyIndexUpdate(e,t){let r=await this.git.readTrackedRepositoryFile(e.repositoryPath,t);if(r.status!=="found")throw new Error(r.status==="untracked"?`${e.repositoryPath} is no longer tracked by HEAD`:r.message);if(r.head!==e.head)throw new Error(`Git HEAD changed while updating ${e.repositoryPath}`);let i=J(r.headText,r.indexText,e.headStart,e.headEnd,e.replacementText);i!==r.indexText&&await this.git.writeIndexFile(e.repositoryPath,r.indexMode,i,t)}};function A(n,e){return{status:"unavailable",reason:"stale-selector",message:`${n} is not available in the current file state`,availableSelectors:e}}s(A,"staleSelector");function we(n){return n instanceof Error?n.message:String(n)}s(we,"errorMessage");var T="pi-agent-ide-changes/change",be=/^CHANGE#[0-9A-F]{4,64}$/,Te=/^[A-Za-z][A-Za-z\d+.-]*:\/\//,P=class extends D{static{s(this,"ChangeTextAnchor")}constructor(e){super(e.selector,e.currentStartLine)}};function ne(n){return{resolver:Ce(s(async t=>{if(Te.test(t.source))return;let r=await h.create(n,t.cwd,t.signal);if(r.status!=="ready")throw new Error(r.message);return r.service.inspect({source:t.source,worktreeText:t.content,cwd:t.cwd,...t.signal!==void 0&&{signal:t.signal}})},"inspect"))}}s(ne,"createChangeAnchorRegistration");function Ce(n){return{id:"git-change",description:"Use the complete `CHANGE#HASH` shown beside a current Git change.",renderFull(e){return e},renderCompact(e){return e},async tryResolve(e,t){if(!be.test(e))return{kind:"not-handled"};try{let r=await n(t);if(r===void 0)return{kind:"not-handled"};if(r.status==="unavailable")return{kind:"failed",error:new Error(r.message)};let i=r.status==="applicable"?r.groups.find(a=>a.selector===e):void 0;return i===void 0?{kind:"rejected",rejection:{code:"stale",reason:`Change anchor ${e} is stale or unknown`}}:{kind:"resolved",anchor:new P(i)}}catch(r){return{kind:"failed",error:r}}}}}s(Ce,"createChangeAnchorResolver");import{diffLines as ve}from"diff";var ke="filesystem";function re(n){return{id:"current-git-changes",async present(e,t){if(t.purpose!=="read"||t.resolvedBy!==ke)return e;let r=await h.create(n,t.cwd,t.signal);if(r.status!=="ready")return e;let i=await r.service.inspect({source:t.source,worktreeText:e.content,cwd:t.cwd,...t.signal!==void 0&&{signal:t.signal}});return i.status!=="applicable"?e:Ee(e,i.groups)}}}s(re,"createCurrentChangePresenter");function Ee(n,e){let t=new Map;for(let r of e)Ae(n,r,t);return{...n,references:e.map(r=>({value:r.selector,kind:"change",state:r.state})),lines:n.lines.map(r=>Ge(r,t.get(r.lineNumber)))}}s(Ee,"presentChangeGroups");function Ae(n,e,t){let r=x(e.segments[0]),i=ve(r.headText,r.worktreeText),a=e.currentStartLine,c,d;for(let o of i){let l=Re(o.value);if(o.removed){let f=Ie(n,a),u=I(t,f.lineNumber),p=f.after?u.after:u.before;for(let $ of l){let w={kind:"synthetic",rows:p,index:p.length};p.push({marker:"-",prefix:"|",content:$}),c??=w,d=w}continue}if(o.added){for(let f of l){let u=I(t,a),p={kind:"current",lineNumber:a};u.added=!0,c??=p,d=p,a++}continue}a+=l.length}if(c!==void 0&&d!==void 0){let o=`${e.selector} \xB7 ${e.state}`;Pe(c,d)?G(t,c,`<!-- change: ${o} -->`):(G(t,c,`<!-- change-begin: ${o} -->`),G(t,d,`<!-- change-end: ${o} -->`))}}s(Ae,"presentChangeGroup");function Pe(n,e){return n.kind==="current"&&e.kind==="current"?n.lineNumber===e.lineNumber:n.kind==="synthetic"&&e.kind==="synthetic"?n.rows===e.rows&&n.index===e.index:!1}s(Pe,"sameTarget");function G(n,e,t){if(e.kind==="current"){I(n,e.lineNumber).annotations.push(t);return}let r=x(e.rows[e.index]);e.rows[e.index]={...r,suffix:`${r.suffix??""} ${t}`}}s(G,"annotateTarget");function Ge(n,e){if(e===void 0)return n;let t=e.annotations.length===0?"":` ${e.annotations.join(" ")}`;return{...n,presentation:{...n.presentation,...e.added&&{marker:"+"},before:[...n.presentation?.before??[],...e.before],after:[...e.after,...n.presentation?.after??[]],suffix:`${n.presentation?.suffix??""}${t}`}}}s(Ge,"presentLine");function I(n,e){let t=n.get(e);if(t!==void 0)return t;let r={before:[],after:[],annotations:[],added:!1};return n.set(e,r),r}s(I,"presentationsFor");function Ie(n,e){return e<=n.lines.length?{lineNumber:Math.max(1,e),after:!1}:{lineNumber:n.lines.length,after:!0}}s(Ie,"placementFor");function Re(n){if(n.length===0)return[];let e=n.split(/\r\n|\r|\n/u);return e.at(-1)===""&&e.pop(),e}s(Re,"splitLines");var C=class{static{s(this,"IndexMutationQueue")}tail=Promise.resolve();run(e){let t=this.tail.then(e,e);return this.tail=t.then(()=>{},()=>{}),t}};import{createHash as Se}from"node:crypto";import{realpathSync as He}from"node:fs";import oe from"node:path";import{fileURLToPath as $e}from"node:url";var k=class{static{s(this,"LastTextTransactionStore")}#e=new Map;observe(e){let t=ie(e.resourceSource,e.cwd);if(e.postProcessing==="final"){let r=this.#e.get(t);r&&r.afterDigest===v(e.before.content)?this.#e.set(t,{...r,afterDigest:v(e.after.content)}):this.#e.delete(t);return}if(e.intent!=="edit"||!e.existed||e.before.content===e.after.content){this.#e.delete(t);return}this.#e.set(t,{before:e.before.content,afterDigest:v(e.after.content)})}restore(e,t,r){let i=ie(e,t),a=this.#e.get(i);if(a===void 0)throw new Error(`No last text transaction is available for ${e}.`);if(a.afterDigest!==v(r))throw this.#e.delete(i),new Error(`${e} changed after its last text transaction; refusing to overwrite newer text.`);return a.before}};function ie(n,e){return n.startsWith("file://")?ae($e(new URL(n))):/^[a-z][a-z\d+.-]*:/iu.test(n)?n:ae(oe.resolve(e,n))}s(ie,"sourceKey");function ae(n){try{return He.native(n)}catch{return oe.normalize(n)}}s(ae,"canonicalFile");function v(n){return Se("sha256").update(n).digest("hex")}s(v,"textDigest");import{readFile as De}from"node:fs/promises";import Le from"node:path";import{defineTool as Ne,withFileMutationQueue as Oe}from"@earendil-works/pi-coding-agent";import{Type as g}from"typebox";var R=g.Object({action:g.Union([g.Literal("stage"),g.Literal("unstage")]),change:g.String(),file:g.String(),state:g.Optional(g.Union([g.Literal("staged"),g.Literal("unstaged")])),effect:g.Union([g.Literal("applied"),g.Literal("not-applied"),g.Literal("unknown")]),unchanged:g.Optional(g.Boolean())},{additionalProperties:!1}),Ue=z(R),y=g.Object({file:g.String({description:"Path to the tracked text file"}),change:g.String({description:"Complete CHANGE#HASH anchor shown by read",pattern:"^CHANGE#[0-9A-F]{4,64}$"})},{additionalProperties:!1}),Fe=g.Object({file:{...y.properties.file,description:"Path to a tracked text file in the current Git worktree. Relative paths resolve from the workspace."},change:{...y.properties.change,description:'Select one complete current CHANGE#HASH anchor returned by read with views: ["changes"].'}},{additionalProperties:!1});function de(n,e,t){n.registerTool(se("stage",e,t)),n.registerTool(se("unstage",e,t))}s(de,"registerIndexChangeTools");function se(n,e,t){let r=je(n,e,t),i=n==="stage"?"Staged":"Unstaged",a=n==="stage"?{...y,properties:{file:{...y.properties.file,description:"Path to the tracked text file, absolute or relative to the current working directory."},change:{...y.properties.change,description:'Use the complete current CHANGE#HASH anchor shown by read with views: ["changes"].'}}}:Fe;return Ne({name:n,exposure:"deferred",namespace:{name:"ide_git",description:"Stage or unstage selected Git changes without changing worktree files."},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},label:n,promptSnippet:`${i.slice(0,-1)} a selected Git change`,description:n==="stage"?"Use stage to add one selected Git change to the index without changing the worktree file.":"Use unstage to remove one selected Git change from the index. Worktree content is kept.",parameters:a,outputSchema:Ue,async execute(c,d,o,l,f){try{let u=await r(d,o,f);return E(u,R,{status:"success",data:{...u.details,effect:u.details.unchanged?"not-applied":"applied"},errors:[]})}catch(u){if(o?.aborted)throw u;let p=Q(u,"INDEX_CHANGE_FAILED",d.file);return E({content:[{type:"text",text:p.message}],details:{action:n,change:d.change,file:S(d.file,f.cwd)}},R,{status:"error",data:{action:n,change:d.change,file:S(d.file,f.cwd),effect:"unknown"},errors:[p]})}}})}s(se,"createIndexChangeTool");function je(n,e,t){let r=n==="stage"?"staged":"unstaged",i=n==="stage"?"Staged":"Unstaged";return async(a,c,d)=>{let o=S(a.file,d.cwd);return Oe(o,()=>t.run(async()=>{let l=await De(o,"utf8"),f=await h.create(e,d.cwd,c);if(f.status!=="ready")throw new Error(n==="stage"?`Cannot stage ${a.file}: ${f.message}`:f.message);let u=await f.service.changeIndex({source:o,worktreeText:l,cwd:d.cwd,...c!==void 0&&{signal:c}},a.change,n);if(u.status==="unavailable")throw n==="stage"&&u.reason==="stale-selector"?new Error(`${u.message}. Read ${a.file} with views: ["changes"] and use a current CHANGE# anchor.`):n==="stage"&&u.reason==="index-write-failed"&&!c?.aborted?new Error(`${u.message}
2
- The index may have changed. Read ${a.file} with views: ["changes"] before retrying.`):new Error(n==="stage"&&u.reason!=="index-write-failed"?`Cannot stage ${a.file}: ${u.message}`:u.message);if(u.status==="not-applicable"){if(n==="stage"){let w=u.reason==="clean"?"the worktree text matches HEAD":"the file is not present in HEAD";throw new Error(`Cannot stage ${a.file}: ${w}.`)}throw new Error(`${n} is not applicable to ${o}: ${u.reason}`)}let p=u.status==="unchanged";return{content:[{type:"text",text:p?`${a.change} is already ${r} in ${a.file}.`:`${i} ${a.change} in ${a.file}.`}],details:{action:n,change:a.change,file:o,state:r,unchanged:p}}}))}}s(je,"createIndexChangeExecutor");function S(n,e){let t=n.startsWith("@")?n.slice(1):n;return Le.resolve(e,t)}s(S,"resolveFile");import{diffChars as Me}from"diff";import{Type as H}from"typebox";var _e=H.Object({file:H.Optional({...W,description:"File path or one whole-file source result. Partial and multi-file selections are rejected. Omit file to use the supplied CHANGE anchor's file or the last resolved source."}),change:H.String({description:`Use a complete current CHANGE#HASH anchor from read with views: ["changes"] to restore that change to HEAD in both worktree and index. Use last to restore the file's latest saved text-editor transaction.`,pattern:"^(?:CHANGE#[0-9A-F]{4,64}|last)$"})},{additionalProperties:!1});function ce(n,e,t){return{name:"undo",description:"Use undo to restore one selected uncommitted Git change or a file's latest text-editor transaction.",promptSnippet:"Restore a Git change or latest text edit",parameters:_e,intent:"restore",source:{field:"file",inherited:!0},anchors:[{field:"change",sourceField:"file",kinds:[T],nonAnchorValues:["last"]}],async mutate(r,i){let a=r.sourceFor("file"),c,d;if(i.change==="last")c=e.restore(a,r.cwd,r.sourceDocument.content);else{await r.resolveAnchor("change");let o=await h.create(n,r.cwd,r.signal);if(o.status!=="ready")throw new Error(o.message);let l=await o.service.prepareUndo({source:a,worktreeText:r.sourceDocument.content,cwd:r.cwd,...r.signal!==void 0&&{signal:r.signal}},i.change);if(l.status!=="applied")throw l.status==="unavailable"?new Error(l.message):new Error(`Undo is not applicable to ${a}: ${l.reason}`);if(c=l.worktreeText,l.indexUpdate!==void 0){let f=l.indexUpdate;d=s(()=>t.run(()=>o.service.applyIndexUpdate(f,r.signal)),"afterWrite")}}return{edits:new Map([[a,{changes:Be(r.sourceDocument.content,c),action:"edited"}]]),...d!==void 0&&{afterWrite:d}}}}}s(ce,"createUndoMutationTool");function Be(n,e){let t=[],r=0,i,a=0,c="",d=s(()=>{i!==void 0&&(t.push({from:i,to:i+a,insert:c}),i=void 0,a=0,c="")},"flush");for(let o of Me(n,e)){if(!o.added&&!o.removed){d(),r+=o.value.length;continue}i??=r,o.removed?(r+=o.value.length,a+=o.value.length):c+=o.value}return d(),t}s(Be,"createTextChanges");async function Ve(n){j(n,[await F({id:"git-changes",description:"Git change anchors, staging, and safe undo",triggers:["stage","unstage","undo"].map(o=>({tool:o}))})]);let e=te(n),t=new k,r=new C,i=re(e),a=ne(e),c={protocol:_,apiVersion:B,id:"current-git-changes",setup(o){o.addView({view:"changes",presenter:i}),o.describe({views:"changes \u2014 uncommitted edits in tracked files, staged/unstaged state, and CHANGE# anchors for stage, unstage and undo."})}},d={protocol:K,apiVersion:X,id:"current-git-changes",setup(o){o.addAnchorResolver({...a,kind:T,type:"auxiliary"}),o.onDidEdit(l=>{t.observe(l)}),o.addMutationTool(ce(e,t,r)),o.addTextPresenter({presenter:i})}};await Promise.all([M(n,ee),V(n,c),q(n,d)]),de(n,e,r)}s(Ve,"registerGitChanges");export{Ve as default};
1
+ import{a as Z,b as Y,c as J}from"./chunk-DEP55R35.js";import{e as F,f as j}from"./chunk-T7I2VX3J.js";import{a as M}from"./chunk-MGCHOGQD.js";import{a as O,b as U}from"./chunk-T6LX2RX5.js";import{a as q}from"./chunk-2ZMMRINH.js";import{a as K,b as X}from"./chunk-HZ5BNF3A.js";import{a as V}from"./chunk-BU7IZLKB.js";import{a as _,b as B}from"./chunk-S5PL5DFQ.js";import{G as W,f as z,i as Q,j as E}from"./chunk-6U5OU77O.js";import{a as D}from"./chunk-ZPT5D4VP.js";import{d as L,e as N}from"./chunk-N34ATN52.js";import{a as x}from"./chunk-ZC65Z3CK.js";import{a as s}from"./chunk-EI7MMDWY.js";import{access as ue}from"node:fs/promises";import le from"node:path";var ee={protocol:O,apiVersion:1,id:"changes",setup(n){n.addSetupCheck({id:"git",async inspect(e){return await ge(e.cwd)?await L("git",e.cwd,e.env)?{}:{actions:[{id:"git-unavailable",message:"Git integration is unavailable because Git was not found"}]}:{}}}),n.addCheck({id:"git",title:"Git changes",async run(e){let t=await N("git",["--version"],e.cwd,e.env);return[t.ok?{status:"pass",message:"Git is available",detail:t.detail}:{status:"warn",message:"Git is not available; change anchors and index tools are disabled",detail:t.detail}]}})}};async function ge(n){try{return await ue(le.join(n,".git")),!0}catch{return!1}}s(ge,"isGitProject");import{mkdtemp as fe,rm as pe,writeFile as he}from"node:fs/promises";import me from"node:os";import m from"node:path";var b=class n{constructor(e,t){this.executor=e;this.repositoryRoot=t}static{s(this,"GitChangesBackend")}static async create(e,t,r){let i=await e.exec("git",["rev-parse","--show-toplevel"],{cwd:t,...r!==void 0&&{signal:r}});return i.code!==0?{status:"unavailable",reason:"no-worktree",message:i.stderr.trim()||"not inside a Git worktree"}:{status:"ready",backend:new n(e,m.resolve(i.stdout.trim()))}}async readTrackedFile(e,t,r){let i=m.resolve(t,e),o=m.relative(this.repositoryRoot,i);return o===".."||o.startsWith(`..${m.sep}`)||m.isAbsolute(o)?{status:"unavailable",reason:"outside-worktree",message:`${i} is outside ${this.repositoryRoot}`}:this.readTrackedRepositoryFile(o.split(m.sep).join("/"),r)}async readTrackedRepositoryFile(e,t){let r=await this.git(["rev-parse","--verify","HEAD"],t);if(r.code!==0)return{status:"unavailable",reason:"missing-head",message:r.stderr.trim()||"Git HEAD does not exist"};let i=await this.git(["--literal-pathspecs","ls-tree","-z","HEAD","--",e],t);if(i.code!==0)return{status:"unavailable",reason:"head-file-lookup-failed",message:i.stderr.trim()||`could not inspect HEAD:${e}`};let o=xe(i.stdout);if(o===void 0)return{status:"untracked"};let c=await this.readBlob(o.blob,"HEAD",e,t);if(c.status!=="found")return c;let d=await this.git(["--literal-pathspecs","ls-files","--stage","-z","--",e],t);if(d.code!==0)return{status:"unavailable",reason:"index-file-lookup-failed",message:d.stderr.trim()||`could not inspect the index entry for ${e}`};let a=ye(d.stdout);if(a.some(({stage:u})=>u!==0))return{status:"unavailable",reason:"conflicted",message:`${e} has unresolved Git index entries`};let l=a.find(({stage:u})=>u===0),f="";if(l!==void 0){let u=await this.readBlob(l.blob,"index",e,t);if(u.status!=="found")return u;f=u.text}return{status:"found",head:r.stdout.trim(),repositoryPath:e,repositoryRoot:this.repositoryRoot,headText:c.text,indexText:f,indexMode:l?.mode??o.mode}}async writeIndexFile(e,t,r,i){let o=await fe(m.join(me.tmpdir(),"pi-agent-index-")),c=m.join(o,"content");try{await he(c,r,"utf8");let d=await this.git(["hash-object","-w",`--path=${e}`,c],i);if(d.code!==0||d.stdout.trim().length===0)throw new Error(d.stderr.trim()||`could not write a Git blob for ${e}`);let a=await this.git(["update-index","--add","--cacheinfo",t,d.stdout.trim(),e],i);if(a.code!==0)throw new Error(a.stderr.trim()||`could not update the Git index entry for ${e}`)}finally{await pe(o,{recursive:!0,force:!0})}}async readBlob(e,t,r,i){let o=await this.git(["cat-file","blob",e],i);return o.code!==0?{status:"unavailable",reason:t==="HEAD"?"head-file-lookup-failed":"index-file-lookup-failed",message:o.stderr.trim()||`could not read ${t}:${r}`}:{status:"found",text:o.stdout}}git(e,t){return this.executor.exec("git",e,{cwd:this.repositoryRoot,...t!==void 0&&{signal:t}})}};function xe(n){let e=n.split("\0",1)[0];if(e===void 0||e.length===0)return;let t=e.indexOf(" ");if(t===-1)return;let[r,i,o]=e.slice(0,t).split(" ",3);return r===void 0||i!=="blob"||o===void 0?void 0:{mode:r,blob:o,path:e.slice(t+1)}}s(xe,"parseTreeEntry");function ye(n){return n.split("\0").filter(Boolean).flatMap(e=>{let t=e.indexOf(" ");if(t===-1)return[];let[r,i,o]=e.slice(0,t).split(" ",3),c=Number(o);return r===void 0||i===void 0||!Number.isInteger(c)?[]:[{mode:r,blob:i,stage:c,path:e.slice(t+1)}]})}s(ye,"parseIndexEntries");function te(n){return{exec:s((e,t,r)=>n.exec(e,t,r),"exec")}}s(te,"extensionGitExecutor");var h=class n{constructor(e){this.git=e}static{s(this,"ChangeService")}static async create(e,t,r){let i=await b.create(e,t,r);return i.status==="unavailable"?i:{status:"ready",service:new n(i.backend)}}async inspect(e){if(e.worktreeText.includes("\0"))return{status:"unavailable",reason:"binary",message:"worktree file contains binary content"};let t=await this.git.readTrackedFile(e.source,e.cwd,e.signal);if(t.status!=="found")return t.status==="untracked"?{status:"not-applicable",reason:"untracked"}:t;if(t.headText.includes("\0")||t.indexText.includes("\0"))return{status:"unavailable",reason:"binary",message:"Git file state contains binary content"};let r=Z(t.repositoryPath,t.headText,t.indexText,e.worktreeText);return r.length===0?{status:"not-applicable",reason:"clean"}:{status:"applicable",head:t.head,repositoryRoot:t.repositoryRoot,repositoryPath:t.repositoryPath,groups:r}}async changeIndex(e,t,r){let i=await this.inspect(e);if(i.status!=="applicable")return i;let o=i.groups.find(l=>l.selector===t);if(o===void 0)return A(t,i.groups.map(({selector:l})=>l));let c=r==="stage"?"staged":"unstaged";if(o.state===c)return{status:"unchanged",state:c,group:o};let d=x(o.segments[0]),a={head:i.head,repositoryPath:i.repositoryPath,headStart:d.headStart,headEnd:d.headEnd,replacementText:r==="stage"?d.worktreeText:d.headText};try{await this.applyIndexUpdate(a,e.signal)}catch(l){return{status:"unavailable",reason:"index-write-failed",message:we(l)}}return{status:"applied",state:c,group:o}}async prepareUndo(e,t){let r=await this.inspect(e);if(r.status!=="applicable")return r;let i=r.groups.find(a=>a.selector===t);if(i===void 0)return A(t,r.groups.map(({selector:a})=>a));let o=Y(e.worktreeText,i);if(o===void 0)return A(t,r.groups.map(({selector:a})=>a));let c=x(i.segments[0]),d=i.state==="unstaged"?void 0:{head:r.head,repositoryPath:r.repositoryPath,headStart:c.headStart,headEnd:c.headEnd,replacementText:c.headText};return{status:"applied",worktreeText:o,group:i,...d!==void 0&&{indexUpdate:d}}}async applyIndexUpdate(e,t){let r=await this.git.readTrackedRepositoryFile(e.repositoryPath,t);if(r.status!=="found")throw new Error(r.status==="untracked"?`${e.repositoryPath} is no longer tracked by HEAD`:r.message);if(r.head!==e.head)throw new Error(`Git HEAD changed while updating ${e.repositoryPath}`);let i=J(r.headText,r.indexText,e.headStart,e.headEnd,e.replacementText);i!==r.indexText&&await this.git.writeIndexFile(e.repositoryPath,r.indexMode,i,t)}};function A(n,e){return{status:"unavailable",reason:"stale-selector",message:`${n} is not available in the current file state`,availableSelectors:e}}s(A,"staleSelector");function we(n){return n instanceof Error?n.message:String(n)}s(we,"errorMessage");var T="pi-agent-ide-changes/change",be=/^CHANGE#[0-9A-F]{4,64}$/,Te=/^[A-Za-z][A-Za-z\d+.-]*:\/\//,P=class extends D{static{s(this,"ChangeTextAnchor")}constructor(e){super(e.selector,e.currentStartLine)}};function ne(n){return{resolver:Ce(s(async t=>{if(Te.test(t.source))return;let r=await h.create(n,t.cwd,t.signal);if(r.status!=="ready")throw new Error(r.message);return r.service.inspect({source:t.source,worktreeText:t.content,cwd:t.cwd,...t.signal!==void 0&&{signal:t.signal}})},"inspect"))}}s(ne,"createChangeAnchorRegistration");function Ce(n){return{id:"git-change",description:"Use the complete `CHANGE#HASH` shown beside a current Git change.",renderFull(e){return e},renderCompact(e){return e},async tryResolve(e,t){if(!be.test(e))return{kind:"not-handled"};try{let r=await n(t);if(r===void 0)return{kind:"not-handled"};if(r.status==="unavailable")return{kind:"failed",error:new Error(r.message)};let i=r.status==="applicable"?r.groups.find(o=>o.selector===e):void 0;return i===void 0?{kind:"rejected",rejection:{code:"stale",reason:`Change anchor ${e} is stale or unknown`}}:{kind:"resolved",anchor:new P(i)}}catch(r){return{kind:"failed",error:r}}}}}s(Ce,"createChangeAnchorResolver");import{diffLines as ve}from"diff";var ke="filesystem";function re(n){return{id:"current-git-changes",async present(e,t){if(t.purpose!=="read"||t.resolvedBy!==ke)return e;let r=await h.create(n,t.cwd,t.signal);if(r.status!=="ready")return e;let i=await r.service.inspect({source:t.source,worktreeText:e.content,cwd:t.cwd,...t.signal!==void 0&&{signal:t.signal}});return i.status!=="applicable"?e:Ee(e,i.groups)}}}s(re,"createCurrentChangePresenter");function Ee(n,e){let t=new Map;for(let r of e)Ae(n,r,t);return{...n,references:e.map(r=>({value:r.selector,kind:"change",state:r.state})),lines:n.lines.map(r=>Ge(r,t.get(r.lineNumber)))}}s(Ee,"presentChangeGroups");function Ae(n,e,t){let r=x(e.segments[0]),i=ve(r.headText,r.worktreeText),o=e.currentStartLine,c,d;for(let a of i){let l=Re(a.value);if(a.removed){let f=Ie(n,o),u=I(t,f.lineNumber),p=f.after?u.after:u.before;for(let $ of l){let w={kind:"synthetic",rows:p,index:p.length};p.push({marker:"-",prefix:"|",content:$}),c??=w,d=w}continue}if(a.added){for(let f of l){let u=I(t,o),p={kind:"current",lineNumber:o};u.added=!0,c??=p,d=p,o++}continue}o+=l.length}if(c!==void 0&&d!==void 0){let a=`${e.selector} \xB7 ${e.state}`;Pe(c,d)?G(t,c,`<!-- change: ${a} -->`):(G(t,c,`<!-- change-begin: ${a} -->`),G(t,d,`<!-- change-end: ${a} -->`))}}s(Ae,"presentChangeGroup");function Pe(n,e){return n.kind==="current"&&e.kind==="current"?n.lineNumber===e.lineNumber:n.kind==="synthetic"&&e.kind==="synthetic"?n.rows===e.rows&&n.index===e.index:!1}s(Pe,"sameTarget");function G(n,e,t){if(e.kind==="current"){I(n,e.lineNumber).annotations.push(t);return}let r=x(e.rows[e.index]);e.rows[e.index]={...r,suffix:`${r.suffix??""} ${t}`}}s(G,"annotateTarget");function Ge(n,e){if(e===void 0)return n;let t=e.annotations.length===0?"":` ${e.annotations.join(" ")}`;return{...n,presentation:{...n.presentation,...e.added&&{marker:"+"},before:[...n.presentation?.before??[],...e.before],after:[...e.after,...n.presentation?.after??[]],suffix:`${n.presentation?.suffix??""}${t}`}}}s(Ge,"presentLine");function I(n,e){let t=n.get(e);if(t!==void 0)return t;let r={before:[],after:[],annotations:[],added:!1};return n.set(e,r),r}s(I,"presentationsFor");function Ie(n,e){return e<=n.lines.length?{lineNumber:Math.max(1,e),after:!1}:{lineNumber:n.lines.length,after:!0}}s(Ie,"placementFor");function Re(n){if(n.length===0)return[];let e=n.split(/\r\n|\r|\n/u);return e.at(-1)===""&&e.pop(),e}s(Re,"splitLines");var C=class{static{s(this,"IndexMutationQueue")}tail=Promise.resolve();run(e){let t=this.tail.then(e,e);return this.tail=t.then(()=>{},()=>{}),t}};import{createHash as Se}from"node:crypto";import{realpathSync as He}from"node:fs";import ae from"node:path";import{fileURLToPath as $e}from"node:url";var k=class{static{s(this,"LastTextTransactionStore")}#e=new Map;observe(e){let t=ie(e.resourceSource,e.cwd);if(e.postProcessing==="final"){let r=this.#e.get(t);r&&r.afterDigest===v(e.before.content)?this.#e.set(t,{...r,afterDigest:v(e.after.content)}):this.#e.delete(t);return}if(e.intent!=="edit"||!e.existed||e.before.content===e.after.content){this.#e.delete(t);return}this.#e.set(t,{before:e.before.content,afterDigest:v(e.after.content)})}restore(e,t,r){let i=ie(e,t),o=this.#e.get(i);if(o===void 0)throw new Error(`No last text transaction is available for ${e}.`);if(o.afterDigest!==v(r))throw this.#e.delete(i),new Error(`${e} changed after its last text transaction; refusing to overwrite newer text.`);return o.before}};function ie(n,e){return n.startsWith("file://")?oe($e(new URL(n))):/^[a-z][a-z\d+.-]*:/iu.test(n)?n:oe(ae.resolve(e,n))}s(ie,"sourceKey");function oe(n){try{return He.native(n)}catch{return ae.normalize(n)}}s(oe,"canonicalFile");function v(n){return Se("sha256").update(n).digest("hex")}s(v,"textDigest");import{readFile as De}from"node:fs/promises";import Le from"node:path";import{defineTool as Ne,withFileMutationQueue as Oe}from"@earendil-works/pi-coding-agent";import{Text as Ue}from"@earendil-works/pi-tui";import{Type as g}from"typebox";var R=g.Object({action:g.Union([g.Literal("stage"),g.Literal("unstage")]),change:g.String(),file:g.String(),state:g.Optional(g.Union([g.Literal("staged"),g.Literal("unstaged")])),effect:g.Union([g.Literal("applied"),g.Literal("not-applied"),g.Literal("unknown")]),unchanged:g.Optional(g.Boolean())},{additionalProperties:!1}),Fe=z(R),y=g.Object({file:g.String({description:"Path to the tracked text file"}),change:g.String({description:"Complete CHANGE#HASH anchor shown by read",pattern:"^CHANGE#[0-9A-F]{4,64}$"})},{additionalProperties:!1}),je=g.Object({file:{...y.properties.file,description:"Path to a tracked text file in the current Git worktree. Relative paths resolve from the workspace."},change:{...y.properties.change,description:'Select one complete current CHANGE#HASH anchor returned by read with views: ["changes"].'}},{additionalProperties:!1});function de(n,e,t){n.registerTool(se("stage",e,t)),n.registerTool(se("unstage",e,t))}s(de,"registerIndexChangeTools");function se(n,e,t){let r=Me(n,e,t),i=n==="stage"?"Staged":"Unstaged",o=n==="stage"?{...y,properties:{file:{...y.properties.file,description:"Path to the tracked text file, absolute or relative to the current working directory."},change:{...y.properties.change,description:'Use the complete current CHANGE#HASH anchor shown by read with views: ["changes"].'}}}:je;return Ne({name:n,exposure:"deferred",namespace:{name:"ide_git",description:"Stage or unstage selected Git changes without changing worktree files."},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},label:n,promptSnippet:`${i.slice(0,-1)} a selected Git change`,description:n==="stage"?"Use stage to add one selected Git change to the index without changing the worktree file.":"Use unstage to remove one selected Git change from the index. Worktree content is kept.",parameters:o,outputSchema:Fe,...n==="stage"&&{renderResult(c,d,a){return new Ue(a.fg("toolOutput",c.content.flatMap(l=>l.type==="text"?[l.text]:[]).join(`
2
+ `)),0,0)}},async execute(c,d,a,l,f){try{let u=await r(d,a,f);return E(u,R,{status:"success",data:{...u.details,effect:u.details.unchanged?"not-applied":"applied"},errors:[]})}catch(u){if(a?.aborted)throw u;let p=Q(u,"INDEX_CHANGE_FAILED",d.file);return E({content:[{type:"text",text:p.message}],details:{action:n,change:d.change,file:S(d.file,f.cwd)}},R,{status:"error",data:{action:n,change:d.change,file:S(d.file,f.cwd),effect:"unknown"},errors:[p]})}}})}s(se,"createIndexChangeTool");function Me(n,e,t){let r=n==="stage"?"staged":"unstaged",i=n==="stage"?"Staged":"Unstaged";return async(o,c,d)=>{let a=S(o.file,d.cwd);return Oe(a,()=>t.run(async()=>{let l=await De(a,"utf8"),f=await h.create(e,d.cwd,c);if(f.status!=="ready")throw new Error(n==="stage"?`Cannot stage ${o.file}: ${f.message}`:f.message);let u=await f.service.changeIndex({source:a,worktreeText:l,cwd:d.cwd,...c!==void 0&&{signal:c}},o.change,n);if(u.status==="unavailable")throw n==="stage"&&u.reason==="stale-selector"?new Error(`${u.message}. Read ${o.file} with views: ["changes"] and use a current CHANGE# anchor.`):n==="stage"&&u.reason==="index-write-failed"&&!c?.aborted?new Error(`${u.message}
3
+ The index may have changed. Read ${o.file} with views: ["changes"] before retrying.`):new Error(n==="stage"&&u.reason!=="index-write-failed"?`Cannot stage ${o.file}: ${u.message}`:u.message);if(u.status==="not-applicable"){if(n==="stage"){let w=u.reason==="clean"?"the worktree text matches HEAD":"the file is not present in HEAD";throw new Error(`Cannot stage ${o.file}: ${w}.`)}throw new Error(`${n} is not applicable to ${a}: ${u.reason}`)}let p=u.status==="unchanged";return{content:[{type:"text",text:p?`${o.change} is already ${r} in ${o.file}.`:`${i} ${o.change} in ${o.file}.`}],details:{action:n,change:o.change,file:a,state:r,unchanged:p}}}))}}s(Me,"createIndexChangeExecutor");function S(n,e){let t=n.startsWith("@")?n.slice(1):n;return Le.resolve(e,t)}s(S,"resolveFile");import{diffChars as _e}from"diff";import{Type as H}from"typebox";var Be=H.Object({file:H.Optional({...W,description:"File path or one whole-file source result. Partial and multi-file selections are rejected. Omit file to use the supplied CHANGE anchor's file or the last resolved source."}),change:H.String({description:`Use a complete current CHANGE#HASH anchor from read with views: ["changes"] to restore that change to HEAD in both worktree and index. Use last to restore the file's latest saved text-editor transaction.`,pattern:"^(?:CHANGE#[0-9A-F]{4,64}|last)$"})},{additionalProperties:!1});function ce(n,e,t){return{name:"undo",description:"Use undo to restore one selected uncommitted Git change or a file's latest text-editor transaction.",promptSnippet:"Restore a Git change or latest text edit",parameters:Be,intent:"restore",source:{field:"file",inherited:!0},anchors:[{field:"change",sourceField:"file",kinds:[T],nonAnchorValues:["last"]}],async mutate(r,i){let o=r.sourceFor("file"),c,d;if(i.change==="last")c=e.restore(o,r.cwd,r.sourceDocument.content);else{await r.resolveAnchor("change");let a=await h.create(n,r.cwd,r.signal);if(a.status!=="ready")throw new Error(a.message);let l=await a.service.prepareUndo({source:o,worktreeText:r.sourceDocument.content,cwd:r.cwd,...r.signal!==void 0&&{signal:r.signal}},i.change);if(l.status!=="applied")throw l.status==="unavailable"?new Error(l.message):new Error(`Undo is not applicable to ${o}: ${l.reason}`);if(c=l.worktreeText,l.indexUpdate!==void 0){let f=l.indexUpdate;d=s(()=>t.run(()=>a.service.applyIndexUpdate(f,r.signal)),"afterWrite")}}return{edits:new Map([[o,{changes:Ve(r.sourceDocument.content,c),action:"edited"}]]),...d!==void 0&&{afterWrite:d}}}}}s(ce,"createUndoMutationTool");function Ve(n,e){let t=[],r=0,i,o=0,c="",d=s(()=>{i!==void 0&&(t.push({from:i,to:i+o,insert:c}),i=void 0,o=0,c="")},"flush");for(let a of _e(n,e)){if(!a.added&&!a.removed){d(),r+=a.value.length;continue}i??=r,a.removed?(r+=a.value.length,o+=a.value.length):c+=a.value}return d(),t}s(Ve,"createTextChanges");async function ze(n){j(n,[await F({id:"git-changes",description:"Git change anchors, staging, and safe undo",triggers:["stage","unstage","undo"].map(a=>({tool:a}))})]);let e=te(n),t=new k,r=new C,i=re(e),o=ne(e),c={protocol:_,apiVersion:B,id:"current-git-changes",setup(a){a.addView({view:"changes",presenter:i}),a.describe({views:"changes \u2014 uncommitted edits in tracked files, staged/unstaged state, and CHANGE# anchors for stage, unstage and undo."})}},d={protocol:K,apiVersion:X,id:"current-git-changes",setup(a){a.addAnchorResolver({...o,kind:T,type:"auxiliary"}),a.onDidEdit(l=>{t.observe(l)}),a.addMutationTool(ce(e,t,r)),a.addTextPresenter({presenter:i})}};await Promise.all([M(n,ee),V(n,c),q(n,d)]),de(n,e,r)}s(ze,"registerGitChanges");export{ze as default};