pi-agent-ide 1.0.0 → 1.0.1

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 (121) hide show
  1. package/CHANGELOG.md +10 -0
  2. package/dist/{chunk-LG22ELG4.js → chunk-26SMC6OS.js} +1 -1
  3. package/dist/{chunk-QC6VFZSB.js → chunk-3BRGWFEI.js} +1 -1
  4. package/dist/chunk-3JBQYLJ4.js +5 -0
  5. package/dist/{chunk-LRAMFOUP.js → chunk-3KM5DSWL.js} +1 -1
  6. package/dist/{chunk-FVWMI4GP.js → chunk-7OAAM5FL.js} +1 -1
  7. package/dist/{chunk-X4CU7CMR.js → chunk-C327T6YP.js} +1 -1
  8. package/dist/{chunk-WZ7MNISG.js → chunk-KM4NOIOB.js} +1 -1
  9. package/dist/{chunk-NGWQRV25.js → chunk-L2YDUMZC.js} +1 -1
  10. package/dist/chunk-MCHU3BLO.js +53 -0
  11. package/dist/{chunk-AKUBFJAR.js → chunk-NSBRKTZ7.js} +1 -1
  12. package/dist/{chunk-SKHD2QIT.js → chunk-QUK5ZEYX.js} +1 -1
  13. package/dist/{chunk-E6G3UVS7.js → chunk-RYJEEBET.js} +1 -1
  14. package/dist/chunk-UN3XLVPR.js +18 -0
  15. package/dist/{chunk-KJ6HZC6L.js → chunk-VQ2RA43A.js} +1 -1
  16. package/dist/{chunk-HUICUICD.js → chunk-VWYI4WF7.js} +1 -1
  17. package/dist/{chunk-UHGHVYAW.js → chunk-W25HNEMR.js} +1 -1
  18. package/dist/entry-0.js +1 -1
  19. package/dist/entry-20.js +1 -1
  20. package/dist/entry-38.js +1 -1
  21. package/dist/entry-44.js +1 -1
  22. package/dist/entry-57.js +1 -1
  23. package/dist/entry-58.js +1 -1
  24. package/dist/entry-59.js +1 -1
  25. package/dist/entry-60.js +1 -1
  26. package/dist/entry-61.js +1 -1
  27. package/dist/entry-62.js +1 -1
  28. package/dist/entry-94.js +1 -1
  29. package/dist/pi-agent-ide.js +1 -1
  30. package/docs/nightly.md +7 -1
  31. package/docs/releases.md +1 -1
  32. package/node_modules/pi-agent-doctor/package.json +1 -1
  33. package/node_modules/pi-agent-documentation/package.json +1 -1
  34. package/node_modules/pi-agent-filesystem/package.json +7 -7
  35. package/node_modules/pi-agent-filesystem-image/package.json +3 -3
  36. package/node_modules/pi-agent-filesystem-jq/package.json +5 -5
  37. package/node_modules/pi-agent-filesystem-pdf/package.json +3 -3
  38. package/node_modules/pi-agent-filesystem-text/package.json +3 -3
  39. package/node_modules/pi-agent-ide-ast/package.json +13 -13
  40. package/node_modules/pi-agent-ide-changes/package.json +8 -8
  41. package/node_modules/pi-agent-ide-formatter/package.json +3 -3
  42. package/node_modules/pi-agent-ide-languages/package.json +2 -2
  43. package/node_modules/pi-agent-ide-lint/package.json +7 -7
  44. package/node_modules/pi-agent-ide-lsp/package.json +12 -12
  45. package/node_modules/pi-agent-ide-lsp/src/lsp/client.ts +28 -0
  46. package/node_modules/pi-agent-ide-lsp/src/lsp/corrected-names.ts +16 -5
  47. package/node_modules/pi-agent-ide-lsp/src/lsp/declaration-scan.ts +116 -0
  48. package/node_modules/pi-agent-ide-lsp/src/lsp/initialization-options.ts +37 -0
  49. package/node_modules/pi-agent-ide-lsp/src/lsp/manager.ts +138 -128
  50. package/node_modules/pi-agent-ide-lsp/src/lsp/navigation.ts +1 -24
  51. package/node_modules/pi-agent-ide-lsp/src/lsp/project.ts +40 -12
  52. package/node_modules/pi-agent-ide-lsp/src/lsp/symbol-search.ts +98 -40
  53. package/node_modules/pi-agent-ide-lsp/src/lsp/symbol-selectors.ts +48 -0
  54. package/node_modules/pi-agent-ide-lsp/src/lsp/symbols.ts +61 -0
  55. package/node_modules/pi-agent-ide-lsp/src/rename-plan.ts +1 -1
  56. package/node_modules/pi-agent-ide-lsp/src/search-resolver.ts +51 -2
  57. package/node_modules/pi-agent-image/package.json +2 -2
  58. package/node_modules/pi-agent-invariant/package.json +1 -1
  59. package/node_modules/pi-agent-pdf/package.json +2 -2
  60. package/node_modules/pi-agent-read/package.json +7 -7
  61. package/node_modules/pi-agent-resource/package.json +1 -1
  62. package/node_modules/pi-agent-search/package.json +4 -4
  63. package/node_modules/pi-agent-search/src/api/structured-result.ts +28 -4
  64. package/node_modules/pi-agent-search-text/package.json +10 -10
  65. package/node_modules/pi-agent-text/package.json +2 -2
  66. package/node_modules/pi-agent-text-anchor-constant/package.json +3 -3
  67. package/node_modules/pi-agent-text-anchor-exact/package.json +3 -3
  68. package/node_modules/pi-agent-text-anchor-line-hash/package.json +5 -5
  69. package/node_modules/pi-agent-text-editor/package.json +8 -8
  70. package/node_modules/pi-agent-text-editor-renderer/package.json +5 -5
  71. package/node_modules/pi-agent-text-editor-stale-anchor/package.json +4 -4
  72. package/node_modules/pi-agent-tool-call-interception/package.json +2 -2
  73. package/node_modules/pi-agent-tool-ui/package.json +1 -1
  74. package/node_modules/pi-agent-web/package.json +7 -7
  75. package/node_modules/pi-agent-web-html/package.json +2 -2
  76. package/node_modules/pi-agent-web-image/package.json +3 -3
  77. package/node_modules/pi-agent-web-pdf/package.json +3 -3
  78. package/node_modules/pi-agent-web-text/package.json +3 -3
  79. package/package.json +35 -35
  80. package/src/composite/script-values/lsp-search.ts +56 -12
  81. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/package.json +7 -7
  82. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-image/package.json +3 -3
  83. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-jq/package.json +5 -5
  84. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-pdf/package.json +3 -3
  85. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-text/package.json +3 -3
  86. package/src/extensions/pi-agent-read/extensions/pi-agent-web/package.json +7 -7
  87. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-html/package.json +2 -2
  88. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-image/package.json +3 -3
  89. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-pdf/package.json +3 -3
  90. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-text/package.json +3 -3
  91. package/src/extensions/pi-agent-read/package.json +7 -7
  92. package/src/extensions/pi-agent-search/package.json +4 -4
  93. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/package.json +10 -10
  94. package/src/extensions/pi-agent-search/src/api/structured-result.ts +28 -4
  95. package/src/extensions/pi-agent-text-editor/package.json +8 -8
  96. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-constant/package.json +3 -3
  97. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-exact/package.json +3 -3
  98. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-line-hash/package.json +5 -5
  99. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-renderer/package.json +5 -5
  100. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-stale-anchor/package.json +4 -4
  101. package/src/plugins/pi-agent-ide-ast/package.json +13 -13
  102. package/src/plugins/pi-agent-ide-changes/package.json +8 -8
  103. package/src/plugins/pi-agent-ide-formatter/package.json +3 -3
  104. package/src/plugins/pi-agent-ide-languages/package.json +2 -2
  105. package/src/plugins/pi-agent-ide-lint/package.json +7 -7
  106. package/src/plugins/pi-agent-ide-lsp/package.json +12 -12
  107. package/src/plugins/pi-agent-ide-lsp/src/lsp/client.ts +28 -0
  108. package/src/plugins/pi-agent-ide-lsp/src/lsp/corrected-names.ts +16 -5
  109. package/src/plugins/pi-agent-ide-lsp/src/lsp/declaration-scan.ts +116 -0
  110. package/src/plugins/pi-agent-ide-lsp/src/lsp/initialization-options.ts +37 -0
  111. package/src/plugins/pi-agent-ide-lsp/src/lsp/manager.ts +138 -128
  112. package/src/plugins/pi-agent-ide-lsp/src/lsp/navigation.ts +1 -24
  113. package/src/plugins/pi-agent-ide-lsp/src/lsp/project.ts +40 -12
  114. package/src/plugins/pi-agent-ide-lsp/src/lsp/symbol-search.ts +98 -40
  115. package/src/plugins/pi-agent-ide-lsp/src/lsp/symbol-selectors.ts +48 -0
  116. package/src/plugins/pi-agent-ide-lsp/src/lsp/symbols.ts +61 -0
  117. package/src/plugins/pi-agent-ide-lsp/src/rename-plan.ts +1 -1
  118. package/src/plugins/pi-agent-ide-lsp/src/search-resolver.ts +51 -2
  119. package/dist/chunk-4AEYLVSR.js +0 -5
  120. package/dist/chunk-DSB6A5P5.js +0 -53
  121. package/dist/chunk-YSGPCH52.js +0 -18
@@ -1,53 +0,0 @@
1
- import{a as et}from"./chunk-VNG4QPPT.js";import{d as Ze}from"./chunk-BW3XONMZ.js";import{a as Qe}from"./chunk-I3G6K7QU.js";import{a as Ye,b as Ke}from"./chunk-HSAGZWPO.js";import{B as ze,g as We,k as De,m as Ue,ma as ce,na as He,ta as Ge,u as Ie,va as Xe,x as ve}from"./chunk-OEEE5BLN.js";import{a as Re}from"./chunk-2QCE7GOV.js";import{a as i}from"./chunk-EI7MMDWY.js";import{createHash as Qt}from"node:crypto";import Ot from"node:path";import{DEFAULT_MAX_BYTES as Lt,DEFAULT_MAX_LINES as qt,truncateHead as Jt}from"@earendil-works/pi-coding-agent";var G={bytes:Lt,lines:qt,pixels:4e6,images:20,imageBytes:20*1024*1024};async function Q(e,n="",t,o={}){let s=typeof n=="string"?[n]:n,a=[],c=e.flatMap(R=>{if(R.type!=="text")return[];let O=s.find(D=>D.length>0&&R.text.endsWith(D));return O?(a.push(O),[R.text.slice(0,-O.length)]):[R.text]}).join(`
2
- `),d=a.join(""),g=o.limitText===!1?{truncated:!1,content:c,firstLineExceedsLimit:!1}:Jt(c,{maxBytes:G.bytes,maxLines:G.lines}),b=[],V;if(g.truncated&&t!==void 0)try{V=await t(c)}catch{b.push("[Full output could not be saved. Narrow the request to inspect it.]")}g.truncated&&b.push(`[Output truncated: useful content is limited to ${G.bytes} bytes / ${G.lines} lines. Narrow the request or read a smaller source range.]`),V!==void 0&&b.push(`[Full output: ${JSON.stringify(V)}. Read with offset/limit, or read ${JSON.stringify("raw:"+V)} for byte ranges. Available until this runtime is disposed.]`);let P=e.filter(R=>R.type==="image"),L=P.slice(0,G.images),F=[],W=Math.floor(G.pixels/Math.max(1,L.length)),Y=0,v=P.length-L.length,q;for(let[R,O]of L.entries())try{q??=await import("@napi-rs/canvas");let{createCanvas:D,loadImage:pe}=q,se=Buffer.from(O.data,"base64"),z=await pe(se),ee=Math.min(1,Math.sqrt(W/(z.width*z.height))),r=Math.min(W,Math.max(1,Math.floor(z.height*ee))),u=Math.min(Math.floor(W/r),Math.max(1,Math.floor(z.width*ee))),p=se,h=O.mimeType;if(ee<1||Y+p.byteLength>G.imageBytes){let f=D(u,r);f.getContext("2d").drawImage(z,0,0,u,r),p=await f.encode("png"),h="image/png"}if(Y+p.byteLength>G.imageBytes){v++;continue}Y+=p.byteLength,F.push({type:"image",data:p.toString("base64"),mimeType:h}),ee<1&&b.push(`[Image ${R+1} resized from ${z.width}x${z.height} to ${u}x${r} to fit the shared media budget.]`)}catch{v++,b.push(`[Image ${R+1} could not be decoded and was not returned.]`)}return v>0&&b.push(`[${v} images omitted from the result. Read fewer frames or a smaller image region.]`),{text:g.firstLineExceedsLimit?Ft(c):g.content,textTruncated:g.truncated,images:F,notices:b,metadataSuffix:d,fullOutput:V}}i(Q,"limitIdeOutput");function Ft(e){let n=0,t=0;for(let o of e){let s=Buffer.byteLength(o);if(n+s>G.bytes)break;n+=s,t+=o.length}return e.slice(0,t)}i(Ft,"bytePrefix");import je from"node:path";var E={type:"object",properties:{path:{type:"string"},line:{allOf:[{type:"integer"}]},text:{type:"string"},lineText:{type:"string",description:"Complete containing lines without the final line ending; absent when unavailable."},id:{type:"string"}},required:["path","line","text"],additionalProperties:!1};function tt(e,n){if(n===void 0||!je.isAbsolute(e))return e;let t=je.relative(n,e);return t.length>0&&!t.startsWith("..")&&!je.isAbsolute(t)?t:e}i(tt,"scriptMatchPath");var le=/^<system-result\b[^>]*><uuid>([a-f\d-]{36})<\/uuid><\/system-result>\n?/u;function B(e){let n=le.exec(e)?.[1];return n===void 0?void 0:`RESULT#${n}`}i(B,"resultReference");function oe(e=E,n={}){return{anyOf:[{type:"object",properties:{id:{type:"string"},complete:{type:"boolean"},matches:{type:"array",items:e},...n},required:["complete","matches"],additionalProperties:!1},{type:"string",description:"Readable result of a search whose results are not text matches, such as a provider's object list."}]}}i(oe,"matchListSchema");function ge(e,n=!1){let t=S(e.outcome)&&e.outcome.status===(n?"partial":"success")?e.outcome.data:void 0,o=B(e.shown);if(o===void 0||!S(t)||t.kind!=="matches"||!Array.isArray(t.matches)||typeof t.complete!="boolean")return;let s=_e(t.matches,e.cwd);if(s!==void 0)return{...typeof t.target=="string"&&{id:o},complete:t.complete&&t.truncated!==!0,matches:s}}i(ge,"matchList");function _e(e,n){let t=[];for(let o of e){if(!S(o))return;let s=Ce(o,n);if(s===void 0)return;t.push({match:s,data:o})}return t}i(_e,"matchEntries");function Ce(e,n){let{source:t,matchedText:o,target:s,range:a}=e,c=S(a)?a.startLine:void 0;if(!(typeof t!="string"||typeof o!="string"||typeof c!="number"))return{path:tt(t,n),line:c,text:o,...typeof e.lineText=="string"&&{lineText:e.lineText},...typeof s=="string"&&{id:s}}}i(Ce,"scriptMatch");function S(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}i(S,"record");var Te={type:"object",properties:{text:{type:"string"},id:{type:"string"}},required:["text"],additionalProperties:!1},he={schema:oe({...E,properties:{...E.properties,captures:{type:"object",additionalProperties:{type:"array",items:Te}}},required:[...E.required,"captures"]}),project(e){let n=ge(e);if(n===void 0)return e.shown;let t=[];for(let{match:o,data:s}of n.matches){let a={};for(let[c,d]of Object.entries(S(s.captures)?s.captures:{})){if(!Array.isArray(d))return e.shown;let g=[];for(let b of d){let V=S(b)?Ce(b,e.cwd):void 0;if(V===void 0)return e.shown;g.push({text:V.text,...V.id!==void 0&&{id:V.id}})}a[c]=g}t.push({...o,captures:a})}return{...n.id!==void 0&&{id:n.id},complete:n.complete,matches:t}}};var Me={type:"object",description:"Value returned by a resource provider, such as a computer action outcome.",additionalProperties:!0};function ue(e){let n=we(e)?e.metadata:void 0,t=we(n)?n.semanticAction:void 0,o=we(t)?t.script:void 0;return we(o)&&!Array.isArray(o)?o:void 0}i(ue,"providerValue");function we(e){return e!==null&&typeof e=="object"}i(we,"record");var N={schema:{anyOf:[{type:"string",description:"RESULT#<uuid> that selects the text the edit produced; pass it to a source parameter. Null when the edit selects no text or its selection cannot be verified, even if the edit succeeded. Check the failure block; read the file before further edits when no selection is verified."},Me]},project:i(e=>ue(e.details)??Wt(e),"project"),failed:i(({details:e})=>ue(e),"failed")},rt={schema:Me,project:i(({details:e})=>ue(e)??null,"project"),failed:i(({details:e})=>ue(e),"failed")};function Wt({outcome:e,shown:n}){let t=nt(e)&&e.status==="success"?e.data:void 0;return!nt(t)||typeof t.target!="string"?null:B(n)??null}i(Wt,"editSelection");function nt(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}i(nt,"record");var ot=N;var st=rt;var at={schema:{type:"string",description:'Complete unified diff of the two sources; "" when they are equal.'},project({details:e,shown:n}){let t=it(e)?e.comparison:void 0;return!it(t)||typeof t.equal!="boolean"||typeof t.diff!="string"?n:t.equal?"":t.diff}};function it(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}i(it,"record");function xe(e){return{schema:{type:"array",items:{type:"string"}},project:i(({outcome:n})=>{let t=ct(n)?n.data:void 0,o=ct(t)&&(e===void 0||t.kind===e)?t.files:void 0;return Array.isArray(o)&&o.every(s=>typeof s=="string")?o:null},"project")}}i(xe,"pathListValue");function ct(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}i(ct,"record");var lt=xe("files"),ut={...lt,failed:lt.project};var dt=N;var be={schema:oe(E,{fallback:{type:"object",properties:{mode:{type:"string",enum:["regex","words"]},id:{type:"string"},complete:{type:"boolean"},matches:{type:"array",items:E}},required:["mode","complete","matches"],additionalProperties:!1},notices:{type:"array",items:{type:"string"}},editWarning:{type:"string"}}),project(e){return pt(e)??e.shown},failed(e){return pt(e,!0)}};function pt(e,n=!1){let t=ge(e,n);if(t===void 0)return;let o=t.matches.map(({match:g})=>({...g})),s=S(e.outcome)&&S(e.outcome.data)?e.outcome.data:{},a=s.fallback==="regex"||s.fallback==="words"?s.fallback:void 0,c=Array.isArray(s.notices)&&s.notices.every(g=>typeof g=="string")?s.notices:[],d={...t.id!==void 0&&{id:t.id},complete:t.complete,matches:o};return{...a===void 0?d:{complete:!0,matches:[],fallback:{mode:a,...d}},...c.length===0?{}:{notices:c},...typeof s.editWarning=="string"?{editWarning:s.editWarning}:{}}}i(pt,"projectSearch");var Ee={type:"array",items:E},ft={schema:{anyOf:[{type:"object",description:"calls: references in matches, callers in incoming, callees in outgoing.",properties:{id:{type:"string"},complete:{type:"boolean"},matches:Ee,incoming:Ee,outgoing:Ee},required:["id","complete","matches","incoming","outgoing"],additionalProperties:!1},...oe({...E,properties:{...E.properties,captures:{type:"object",properties:{name:{type:"array",items:Te}},additionalProperties:!1}}}).anyOf]},project(e){let n=S(e.outcome)&&e.outcome.status==="success"?e.outcome.data:void 0;return S(n)&&n.kind==="custom"?Dt(n.value,e)??e.shown:S(n)&&Array.isArray(n.matches)&&n.matches.some(t=>S(t)&&S(t.captures))?he.project(e):be.project(e)}};function Dt(e,n){if(!S(e))return;let t=[e.matches,e.incoming,e.outgoing].map(c=>Ut(c,n.cwd)),[o,s,a]=t;if(!(typeof e.target!="string"||typeof e.complete!="boolean"||o===void 0||s===void 0||a===void 0))return{id:e.target,complete:e.complete&&t.every(c=>c?.complete===!0),matches:o.matches,incoming:s.matches,outgoing:a.matches}}i(Dt,"callGraph");function Ut(e,n){if(!S(e)||e.kind!=="matches"||!Array.isArray(e.matches))return;let t=_e(e.matches,n);if(t!==void 0)return{complete:e.truncated!==!0,matches:t.map(({match:o})=>({...o}))}}i(Ut,"places");var mt=N;var yt={type:"object",properties:{type:{const:"image"},data:{type:"string"},mimeType:{type:"string"}},required:["type","data","mimeType"]},xt={type:"object",description:"Text, exactly as requested, without notices. Pass the value or its id to a source parameter.",properties:{text:{type:"string"},id:{type:"string"}},required:["text","id"]},gt=[xt,{type:"object",properties:{bytes:{type:"string"}},required:["bytes"]},{type:"object",properties:{entries:{type:"array",items:{type:"string"}}},required:["entries"]},yt,{type:"object",description:"Several images, such as sequence frames, in source order.",properties:{type:{const:"images"},images:{type:"array",items:yt}},required:["type","images"]}],Oe={schema:{anyOf:[...gt,{type:"array",description:"For an array path: the value of each path in order, null when it failed.",items:{anyOf:[...gt,{type:"null"}]}}]},project(e){let n=wt(e.content);if(e.script!==!0)return kt(n)??e.shown;let t=St(e.outcome);return T(t)&&t.kind==="list"?ht(t,e,n):bt(t,B(e.shown),n)??e.shown},failed(e){let n=T(e.outcome)?e.outcome.data:void 0;if(!(e.script!==!0||!T(n)||n.kind!=="list"))return ht(n,e,wt(e.content))},failureReason({outcome:e}){return!T(e)||!T(e.data)||e.data.kind!=="list"?void 0:(Array.isArray(e.errors)?e.errors:[]).flatMap(t=>T(t)&&typeof t.message=="string"?[t.message]:[]).join(`
3
- `)||void 0}},$e={schema:xt,project:Oe.project};function ht(e,n,t){let o=Array.isArray(e.items)?e.items:[],s=0;return o.map(a=>{let c=St(a);if(!T(c))return null;let d=vt(c),g=t.slice(s,s+d);s+=d;let b=Be(c),V=b===void 0?void 0:n.publish?.(a,b);return bt(c,V,g)??null})}i(ht,"listValue");function bt(e,n,t){if(!T(e))return;let o=kt(t);if(o!==void 0)return o;if(e.kind==="bytes"&&Array.isArray(e.bytes))return{bytes:Buffer.from(e.bytes.filter(zt)).toString("base64")};if(e.kind==="text"&&Array.isArray(e.entries))return{entries:e.entries.filter(a=>typeof a=="string")};let s=Be(e);return s===void 0||n===void 0?void 0:{text:s,id:n}}i(bt,"sourceValue");function Be(e){if(e.kind==="text")return typeof e.text=="string"?e.text:(Array.isArray(e.lines)?e.lines:[]).map(t=>T(t)&&typeof t.content=="string"&&typeof t.lineEnding=="string"?t.content+t.lineEnding:"").join("");if(e.kind==="native"&&Array.isArray(e.blocks))return e.blocks.flatMap(t=>T(t)&&typeof t.text=="string"?[t.text]:[]).join(`
4
- `);if(e.kind==="resources"&&Array.isArray(e.resources))return e.resources.flatMap(t=>{let o=T(t)?Be(t):void 0;return o===void 0?[]:[o]}).join(`
5
- `)}i(Be,"textOf");function vt(e){return!T(e)||e.kind!=="native"||!Array.isArray(e.blocks)?0:e.blocks.filter(t=>T(t)&&t.type==="image").length}i(vt,"imageCount");function wt(e){return e.filter(n=>n.type==="image").map(({data:n,mimeType:t})=>({type:"image",data:n,mimeType:t}))}i(wt,"imageBlocks");function kt(e){let[n]=e;if(n!==void 0)return e.length===1?{...n}:{type:"images",images:e.map(t=>({...t}))}}i(kt,"imageValue");function St(e){return T(e)&&e.status==="success"?e.data:void 0}i(St,"successData");function zt(e){return typeof e=="number"&&Number.isInteger(e)&&e>=0&&e<=255}i(zt,"isByte");function T(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}i(T,"record");var Vt=N;var At=xe();var Ht={type:"object",properties:{output:{type:"string"},truncated:{type:"boolean"},full_output_path:{type:"string"},exit_code:{type:"number"},wall_time_seconds:{type:"number"},session:{type:"string"}},required:["output","truncated","full_output_path","wall_time_seconds","session"],additionalProperties:!1},de={schema:Ht,project:i(({outcome:e})=>Gt(e)??null,"project"),succeeded:i(({outcome:e})=>{let n=Rt(e);return n!==void 0&&!(n.status==="failed"&&n.exit_code===void 0)},"succeeded")};function Gt(e){let n=Rt(e);if(n!==void 0)return{output:Xt(n),truncated:n.truncated,full_output_path:n.full_output_path,...n.exit_code===void 0?{}:{exit_code:n.exit_code},wall_time_seconds:n.wall_time_seconds,session:n.source}}i(Gt,"terminalOutcome");function Xt({output:e,output_ranges:n}){let[t,o]=n;if(n.length!==2||t===void 0||o===void 0)return e;let s=Buffer.from(e,"utf8"),a=t.end-t.start,c=o.start-t.end;return`${s.subarray(0,a).toString("utf8")}
6
-
7
- [... ${c} bytes omitted ...]
8
-
9
- ${s.subarray(a).toString("utf8")}`}i(Xt,"markedOutput");function Rt(e){let n=Ne(e)?e.data:void 0;if(!Ne(n))return;let{output:t,truncated:o,full_output_path:s,output_ranges:a,exit_code:c}=n,{wall_time_seconds:d,source:g,status:b}=n;if(typeof t!="string"||typeof o!="boolean"||typeof s!="string"||!Array.isArray(a)||typeof d!="number"||typeof g!="string"||typeof b!="string"||c!==void 0&&typeof c!="number")return;let V=a.flatMap(P=>Ne(P)&&typeof P.start=="number"&&typeof P.end=="number"?[{start:P.start,end:P.end}]:[]);return{output:t,truncated:o,full_output_path:s,output_ranges:V,...c===void 0?{}:{exit_code:c},wall_time_seconds:d,source:g,status:b}}i(Rt,"shellRecord");function Ne(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}i(Ne,"record");var It={schema:{type:"string"},project:i(({shown:e})=>e,"project")};var jt=N;var _t=N;var Yt={read:Oe,outline:$e,diagnostics:$e,search:be,ast_search:he,lsp_search:ft,file_search:ut,semantic_search:At,replace:Vt,insert:dt,delete:st,write:_t,copy:ot,move:mt,undo:jt,diff:at,bash:de,powershell:de,remote_bash:de,remote_powershell:de};function Pe(e){return Yt[e]??It}i(Pe,"scriptValueOf");function Ct(e){let n=e.schema.anyOf;return{anyOf:[...Array.isArray(n)?n:[e.schema],{type:"null"}]}}i(Ct,"nullableValueSchema");var ke=class{static{i(this,"CodemodeCallLedger")}#e=new Map;record(n,t,o){let s=this.#e.get(n)??{calls:new Map,failures:new Map};s.calls.set(t.id,t),o!==void 0&&s.failures.set(t.id,{...Tt(t),...o}),this.#e.set(n,s)}updateReason(n,t,o){let s=this.#e.get(n)?.failures,a=s?.get(t);a!==void 0&&s?.set(t,{...a,reason:o})}recordBatch(n,t){let o=this.#e.get(n);if(o!==void 0)for(let s of t){let a=o.calls.get(s.id);a===void 0||o.failures.has(s.id)||s.errors.length===0&&s.effect!=="unknown"||o.failures.set(s.id,{...Tt(a),reason:["The edit was accepted, then its editor batch failed when it was saved.",...s.errors.map(c=>c.message)].join(`
10
- `),...s.changed===void 0?{}:{changed:s.changed},...s.unknown===void 0?{}:{unknown:s.unknown}})}}take(n){let t=this.#e.get(n);return this.#e.delete(n),t===void 0||t.failures.size===0?void 0:Kt(t.calls.size,[...t.calls.keys()].flatMap(o=>t.failures.get(o)??[]))}clear(){this.#e.clear()}};function Tt(e){return{tool:e.tool,...e.source===void 0?{}:{source:e.source}}}i(Tt,"identity");function Kt(e,n){let t=[`${n.length} of ${e} IDE call${e===1?"":"s"} failed:`];for(let o of n){t.push(`- ${o.tool}${o.source===void 0?"":` ${o.source}`}`);let s=[...o.changed?.length?[`Changed: ${o.changed.join(", ")}.`]:[],...o.unknown?.length?[`Effect unknown: ${o.unknown.join(", ")}.`]:[]];s.length>0&&t.push(` ${s.join(" ")} Do not repeat this edit blindly; Read the files first.`);for(let a of o.reason.split(`
11
- `))t.push(a===""?"":` ${a}`)}return t.join(`
12
- `)}i(Kt,"formatFailures");function Se(e,n=t=>t){let t=Z(e)?e.data:void 0,o=Z(t)&&Array.isArray(t.files)?t.files:[],s=i(d=>o.flatMap(g=>Z(g)&&g.effect===d&&typeof g.source=="string"?[n(g.source)]:[]),"sources"),a=s("applied"),c=s("unknown");return{...a.length>0&&{changed:a},...c.length>0&&{unknown:c}}}i(Se,"fileEffects");function Mt(e,n=t=>t){let t=Z(e)?e.editorBatchResults:void 0;return Array.isArray(t)?t.flatMap(o=>(Z(o)&&Z(o.data)&&Array.isArray(o.data.operations)?o.data.operations:[]).flatMap(a=>Z(a)&&typeof a.id=="string"&&typeof a.effect=="string"&&Array.isArray(a.errors)?[{id:a.id,effect:a.effect,errors:a.errors.flatMap(c=>Z(c)&&typeof c.message=="string"?[{message:c.message}]:[]),...Se({data:{files:a.files}},n)}]:[])):[]}i(Mt,"batchOperations");function Z(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}i(Z,"record");function Et(e,n,t,o){if(!X(n)||n.status!=="success"||!X(n.data))return[];let s=n.data,a=X(t)&&X(t.metadata)?t.metadata:void 0,c=a&&X(a.semanticAction)?a.semanticAction:void 0;return e==="write"&&c?.kind==="direct-mutation"&&c.ok===!0&&c.effect==="applied"&&Array.isArray(c.files)?c.files.filter(d=>typeof d=="string").map(d=>`write ${o(d)}: saved`):e==="write"&&c===void 0&&X(t)&&t.effect==="not-applied"&&Array.isArray(t.results)?t.results.flatMap(d=>{let g=X(d)&&X(d.data)?d.data:void 0;return g?.ok===!0&&typeof g.path=="string"?[`write ${o(g.path)}: unchanged`]:[]}):s.effect!=="applied"?[]:e==="copy"||e==="move"?c?.kind!=="file-operation"||c.ok!==!0||c.effect!=="applied"||typeof c.path!="string"||typeof c.target!="string"?[]:[`${e} ${o(c.path)} \u2192 ${o(c.target)}: applied`]:e!=="write"||c!==void 0||!Array.isArray(s.files)?[]:s.files.flatMap(d=>X(d)&&d.effect==="applied"&&typeof d.source=="string"&&!/^(?:shell|debug):/u.test(d.source)?[`write ${o(d.source)}: saved`]:[])}i(Et,"fileReceipts");function X(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}i(X,"record");var $t=200,Zt=new Set(["write","replace","insert","delete","copy","move","undo","stage","unstage"]),Ae={read:["path"],outline:["path"],search:["path"],ast_search:["path"],lsp_search:["path"],file_search:["path"],replace:["path"],insert:["path"],delete:["path"],write:["path"],copy:["path","target"],move:["path","target"],undo:["file"],diff:["before","after"]},en={bash:["command"],powershell:["command"],remote_bash:["command"],remote_powershell:["command"],debug:["program"],stage:["file"],unstage:["file"]};function Bt(e,n){let t=i(a=>{if(Array.isArray(a))return a.flatMap(t);let c=ce(a);if(c!==void 0)return t(c);if(a!==null&&typeof a=="object"&&"path"in a)return t(a.path);if(typeof a!="string"||a==="")return[];let d=B(a)??a.replaceAll(/\s+/gu," ");return[d.length>$t?`${d.slice(0,$t)}\u2026`:d]},"labels"),s=(en[e]??Ae[e]??["path"]).map(a=>t(n[a]).join(", ")).filter(a=>a!=="");return s.length===0?void 0:s.join(" \u2192 ")}i(Bt,"sourceLabel");function Ve(e,n){let t=n.endsWith(Ot.sep)?n:n+Ot.sep;return e.startsWith(t)&&e.length>t.length?e.slice(t.length):e}i(Ve,"displayPath");async function tn(e,n){if(typeof e!="object"||e===null||!("editorBatches"in e)||!("editorBatchResults"in e))return;let{editorBatches:t,editorBatchResults:o,...s}=e,a=JSON.stringify({editorBatches:t,editorBatchResults:o});if(Buffer.byteLength(a)<=24*1024)return;let c=await n(a).catch(()=>{});return{...s,editorBatchReceipts:{truncated:!0,...c===void 0?{}:{fullOutput:c}}}}i(tn,"boundEditorBatchReceipts");function Ur(e,n={}){let t=Ge(e),o=Xe(e),s=new Set,a=new Map,c=new ve,d=i(r=>n.resourceOutput?c.save(r):c.saveFile(r),"saveFullOutput"),g=new Map,b=i(r=>Qt("sha256").update(JSON.stringify(r)).digest("hex"),"signature"),V=i(async(r,u)=>{let p=b(u),h=g.get(r);if(h&&(h.source===p||b(await h.content)===p))return h.content;let f=Q(u,"",d).then(l=>[{type:"text",text:l.text+(l.notices.length?`
13
-
14
- ${l.notices.join(`
15
- `)}`:"")},...l.images]);return g.set(r,{source:p,content:f}),f},"limitError");Qe(e,{protocol:Ye,apiVersion:Ke,id:"ide-output-retention",setup(r){r.setOutputSaver(d),n.resourceOutput&&r.addResolver({priority:-1e3,resolver:{id:"ide-output-retention",async tryResolve(u,p){let h=await c.resolver.tryResolve(u,p);return h.kind==="failed"?{kind:"not-handled"}:h}}})}}),e.on("session_shutdown",()=>c.dispose());let P=i((r,u)=>{if(r==="message_end"){let h=u;return e.on("message_end",async(f,l)=>{let y=await h(f,l),m=y?.message??f.message;return m.role!=="toolResult"||!m.isError||!s.has(m.toolName)||m.content.some(x=>x.type==="text"&&x.text.startsWith("<system-result"))?y:{...y,message:{...m,content:await V(m.toolCallId,m.content)}}})}let p=u;return r!=="tool_call"?e.on(r,p):e.on("tool_call",async(h,f)=>{let l=s.has(h.toolName);if(l&&L.has(h.toolCallId))return;let y=await p(h,f);if(!y?.block||!l||y.terminate===!0)return y;let m=await Q([{type:"text",text:y.reason??"Tool execution was blocked"}],"",d);L.set(h.toolCallId,{...L.get(h.toolCallId),reason:m.text+(m.notices.length?`
16
-
17
- ${m.notices.join(`
18
- `)}`:"")})})},"on"),L=new Map,F=new Map,W=new ke,Y=new Set,v=new Map,q=new Map,R=new Map,O=new Map,D=new Map,pe=i(()=>{L.clear(),F.clear(),W.clear(),Y.clear(),v.clear(),R.clear(),O.clear()},"clearCalls"),se=i(()=>{q.clear(),D.clear(),g.clear(),pe()},"clear");e.on("session_start",se),e.on("session_shutdown",se),e.on("agent_end",pe),e.on("before_agent_start",r=>{r.systemPromptOptions.sections[n.promptSection??"ide_results"]="Direct IDE calls return readable text; the system-result reference is not file content. Pass an unchanged result or its UUID to compose tools. Codemode calls return the inline value types. Text Read values hold exactly the requested text without notices; bytes are base64 and directory names end with /. Search match lists hold every found match with whole text and a one-based line; AST captures are keyed by metavariable name without $. An id selects its result, match or capture; pass that value or its RESULT# id to a source or selector parameter. A result selects only its returned ranges, not surrounding preview context. Sources without selections have no id. A false complete means incomplete coverage, so an empty list proves nothing. A broadened Search keeps the original matches empty and places hints in fallback; refine the query before editing them. LSP calls put references in matches and whole caller/callee declarations in incoming/outgoing. Diff is complete, or empty for equal sources. Edits return the id of verified output text or null when no text is selected; filesystem/text delete returns null. A failed IDE call normally resolves to null and the script continues; a multi-source Read keeps its array with null at failed sources, and a provider action keeps its receipt. Terminal exit_code is absent while running; a nonzero exit is a value, not a tool failure. Check the Codemode result's failed calls and effects before retrying. Pi can still reject invalid or blocked calls. Omit optional arguments rather than passing null. Store/load retains values in the session; references cannot be reused across sessions."}),e.on("tool_execution_start",r=>{r.parentToolCallId!==void 0&&q.set(r.toolCallId,q.get(r.parentToolCallId)??r.parentToolCallId)}),e.on("tool_execution_end",r=>{let u=v.get(r.toolCallId);v.delete(r.toolCallId);let p=r.result;if(u&&p!==null&&typeof p=="object"&&"content"in p&&Array.isArray(p.content)){let f=p.content.filter(l=>l!==null&&typeof l=="object"&&"type"in l&&l.type==="text"&&"text"in l&&typeof l.text=="string").map(l=>l.text).join(`
19
- `).replace(le,"");if(f!==u.original){let l=u.original?f.indexOf(u.original):-1,y=l>=0&&l===f.lastIndexOf(u.original),m=u.filtered?y?f.slice(0,l)+u.reason+f.slice(l+u.original.length):u.reason:f;W.updateReason(u.parent,r.toolCallId,m)}}Y.delete(r.toolCallId)&&p!==null&&typeof p=="object"&&Object.assign(p,{structuredContent:null})}),P("tool_call",(r,u)=>{if(!s.has(r.toolName))return;let p=a.get(r.toolName)?.(),h=p?Re(r.input,p,{cwd:u.cwd,sourceFields:[...Ae[r.toolName]??[],"path"],resolveSource:i(l=>t.source(l,u.cwd,!0),"resolveSource")}):r.input;F.set(r.toolCallId,Bt(r.toolName,h));let f={...h};try{for(let l of Ae[r.toolName]??[]){let y=f[l];if(y!==void 0)if(r.toolName==="diff"&&ce(y)===void 0&&y!==null&&typeof y=="object"&&"path"in y)f[l]={...y,path:t.source(y.path,u.cwd,!0)};else if(r.toolName==="read"){let m=i(x=>{let A=t.source(x,u.cwd,!0);if(Array.isArray(A)||typeof A=="string"&&A.startsWith("RESULT#")){let w=ce(x)??x;if(typeof w=="string"&&!w.startsWith("SEARCH#"))return B(w)??(w.startsWith("RESULT#")?w:`RESULT#${w}`)}if(!Array.isArray(A))return A;let I=t.resolve(A,u.cwd);return t.register(I.targets,u.cwd,I.complete)},"readSource");f[l]=Array.isArray(y)?y.map(m):m(y)}else f[l]=t.source(y,u.cwd,["write","insert","delete"].includes(r.toolName)?"live":!1)}for(let l of Ze(r.toolName))f[l]!==void 0&&(f[l]=He(t,f[l],u.cwd));for(let l of["text","content"]){let y=f[l];if(typeof y=="string"&&(y.trimStart().startsWith("<system-result")||/<system-result\b[^>]*><uuid>[a-f\d-]{36}<\/uuid><\/system-result>/iu.test(y)))return{block:!0,reason:"A system result reference is not file content. Do not insert it into a file."}}Object.assign(r.input,f)}catch(l){let y=l instanceof Error?l.message:String(l);return l instanceof ze&&L.set(r.toolCallId,{reason:y,details:{code:l.code,effect:l.effect}}),{block:!0,reason:y}}});let z=i(r=>{s.add(r.name),a.set(r.name,()=>r.parameters);let u={},p=Object.getOwnPropertyDescriptors(r),h=i(m=>{et(e.events,m);let x=Re(m,r.parameters);return r.prepareArguments?r.prepareArguments(x):x},"prepareArguments");p.prepareArguments={value:h,enumerable:!0,configurable:!0,writable:!0},p.outputSchema={value:Ct(Pe(r.name)),enumerable:!0,configurable:!0,writable:!0};let f=i(async(...m)=>{let x=L.get(m[0]);if(x!==void 0)return L.delete(m[0]),{content:[{type:"text",text:x.reason}],details:x.details??{},isError:!0};let A=!(["read","outline"].includes(r.name)&&q.has(m[0])),I=i(async te=>{let C=await r.execute(m[0],m[1],te,m[3],m[4]).catch(async U=>{let ne=await Q([{type:"text",text:U instanceof Error?U.message:String(U)}],"",d);throw ne.notices.length===0?U:new Error(ne.text+`
20
-
21
- ${ne.notices.join(`
22
- `)}`,{cause:U})}),K=C.structuredContent,$=typeof K=="object"&&K!==null&&"data"in K?K.data:void 0;typeof $=="object"&&$!==null&&"effect"in $&&($.effect==="applied"||$.effect==="unknown"||$.effect==="not-applied")&&De($.effect);let M=await Q(C.content,Nt(C.details),d,{limitText:A}),ie={type:"text",text:M.text+M.metadataSuffix+(M.notices.length?`
23
-
24
- ${M.notices.join(`
25
- `)}`:"")};return{...C,content:[M.textTruncated?ie:Ie(C.content,ie),...M.images]}},"run"),w=We(r.name);if(w===void 0)return I(m[2]);let J=F.get(m[0])??Bt(r.name,m[1])??m[4].cwd;return await Ue(r.name,J,w,m[2],Zt.has(r.name)||r.annotations?.readOnlyHint===!1?"unknown":void 0,I)},"execute");p.execute={value:f,enumerable:!0,configurable:!0,writable:!0};let l=r.renderCall;if(l){let m=i((x,A,I)=>l(nn(r.name,x),A,I),"renderCall");p.renderCall={value:m,enumerable:!0,configurable:!0,writable:!0}}let y=r.renderResult;if(y){let m=i((x,A,I,w)=>y({...x,content:x.content.map(J=>J.type==="text"?{...J,text:J.text.replace(le,"")}:J)},A,I,w),"renderer");p.renderResult={value:m,enumerable:!0,configurable:!0,writable:!0}}Object.defineProperties(u,p),e.registerTool(u)},"registerTool"),ee=i(()=>{e.on("context",async r=>({messages:await Promise.all(r.messages.map(async u=>u.role!=="toolResult"||!u.isError||!s.has(u.toolName)||u.content.some(p=>p.type==="text"&&p.text.startsWith("<system-result"))?u:{...u,content:await V(u.toolCallId,u.content)}))})),e.on("tool_result",async(r,u)=>{if(r.toolName==="codemode"){t.refreshAll();let k=new Set(r.content.flatMap(_=>_.type==="image"?[_.data]:[])),j=(D.get(r.toolCallId)??[]).filter(_=>!k.has(_.data));D.delete(r.toolCallId);for(let[_,Pt]of q)Pt===r.toolCallId&&q.delete(_);let H=r.content.filter(_=>_.type==="text"&&_.text.startsWith(`
26
-
27
- ---
28
-
29
- # Guide:`));W.recordBatch(r.toolCallId,Mt(r.details,_=>Ve(_,u.cwd)));let re=W.take(r.toolCallId),qe=await tn(r.details,d),fe=R.get(r.toolCallId)??[];R.delete(r.toolCallId);let Je=O.get(r.toolCallId)??[];O.delete(r.toolCallId);let Fe=r.content.filter(_=>!H.includes(_)),me=Je.length?await Q([{type:"text",text:Je.join(`
30
- `)}],"",d):void 0,ae=await Q([...Fe,...j,...fe.length?[{type:"text",text:`
31
-
32
- ${fe.join(`
33
- `)}`}]:[]],"",d),ye=re===void 0?void 0:await Q([{type:"text",text:re}],"",d);return{...qe===void 0?{}:{details:qe},content:[...ae.textTruncated?[{type:"text",text:ae.text}]:[...Fe.filter(_=>_.type==="text"),...fe.length?[{type:"text",text:`
34
-
35
- ${fe.join(`
36
- `)}`}]:[]],...ae.images,...ae.notices.length?[{type:"text",text:`
37
-
38
- ${ae.notices.join(`
39
- `)}`}]:[],...H,...me===void 0?[]:[{type:"text",text:`
40
-
41
- ${me.text}${me.notices.length?`
42
-
43
- ${me.notices.join(`
44
- `)}`:""}`}],...ye===void 0?[]:[{type:"text",text:`
45
-
46
- ${ye.text}${ye.notices.length?`
47
-
48
- ${ye.notices.join(`
49
- `)}`:""}`}]]}}if(!s.has(r.toolName))return;let p=r.content.filter(k=>k.type==="text").map(k=>k.text).join(`
50
- `),h=r.structuredContent,f=h!==null&&typeof h=="object"&&"data"in h?h:{status:r.isError?"error":"success",data:h},l=f.data,y=l!==null&&typeof l=="object"&&"effect"in l&&l.effect==="applied"&&"targetUnavailable"in l&&typeof l.targetUnavailable=="string"?l.targetUnavailable:void 0,m=y===void 0||p.includes(y)?p:`${p}
51
-
52
- This result has no verified text selection: ${y}
53
- Read/Search the file before the next edit; do not repeat the applied edit.`,x=Le(f),A=r.isError||f.status==="error"||f.status==="partial",I=t.publish(f,m,u.cwd,x);o.keep(I,u.cwd,r.toolName==="read"&&!A?r.content.filter(k=>k.type==="image"):[]);let w=q.get(r.toolCallId);q.delete(r.toolCallId);let J={shown:I,outcome:f,content:r.content,details:r.details,cwd:u.cwd,script:w!==void 0,publish:i((k,j)=>B(t.publish(k,j,u.cwd,Le(k))),"publish")},te=Pe(r.toolName),C,K,$;try{C=A&&te.succeeded?.(J)!==!0,K=C?te.failed?.(J):te.project(J),C&&w!==void 0&&($=te.failureReason?.(J))}catch(k){let j=F.get(r.toolCallId);if(F.delete(r.toolCallId),w===void 0)return;let H=k instanceof Error?k.message:String(k);return W.record(w,{id:r.toolCallId,tool:r.toolName,...j===void 0?{}:{source:j}},{reason:H,...Se(f,re=>Ve(re,u.cwd))}),Y.add(r.toolCallId),{content:[{type:"text",text:H}]}}let M=K===I?void 0:K,ie=F.get(r.toolCallId);F.delete(r.toolCallId);let U=m.replace(le,"");if(w!==void 0){if(!C){let j=Et(r.toolName,f,r.details,H=>Ve(H,u.cwd));j.length&&O.set(w,[...O.get(w)??[],...j])}if(r.toolName==="search"&&!C&&l!==null&&typeof l=="object"){let j="notices"in l&&Array.isArray(l.notices)?l.notices.filter(re=>typeof re=="string"):[],H="editWarning"in l&&typeof l.editWarning=="string"?[l.editWarning]:[];R.set(w,[...new Set([...R.get(w)??[],...j,...H])])}let k=r.content.filter(j=>j.type==="image");k.length&&D.set(w,[...D.get(w)??[],...k]),W.record(w,{id:r.toolCallId,tool:r.toolName,...ie===void 0?{}:{source:ie}},C?{reason:$??U,...Se(f,j=>Ve(j,u.cwd))}:void 0),C&&v.set(r.toolCallId,{parent:w,original:U,reason:$??U,filtered:$!==void 0}),(M===null||C&&M===void 0)&&Y.add(r.toolCallId)}let ne={type:"text",text:A?U:I};return{content:[w===void 0&&!A?Ie(r.content,ne):ne,...r.content.filter(k=>k.type!=="text")],...M!=null&&(w!==void 0||M!==B(I))&&{structuredContent:M}}})},"finalize");return{api:{...e,on:P,registerTool:z},finalize:ee}}i(Ur,"createIdeTextResults");function Nt(e){if(e===null||typeof e!="object")return[];let n="outputNotice"in e&&typeof e.outputNotice=="string"?[e.outputNotice]:[];if("resources"in e&&Array.isArray(e.resources)){let t=e.resources;for(let o of t)o!==null&&typeof o=="object"&&"details"in o&&n.push(...Nt(o.details))}return n}i(Nt,"outputNotices");function nn(e,n){let t=i(s=>{if(Array.isArray(s))return s.map(t);let a=ce(s);return a!==void 0?a:s!==null&&typeof s=="object"&&"path"in s?{...s,path:t(s.path)}:typeof s!="string"?s:B(s)??s},"label"),o={...n};for(let s of Ae[e]??[])n[s]!==void 0&&Object.assign(o,{[s]:t(n[s])});return o}i(nn,"displaySources");function Le(e){if(e===null||typeof e!="object"||!("data"in e))return[];let n=e.data;return n===null||typeof n!="object"?[]:"resources"in n&&Array.isArray(n.resources)?n.resources.flatMap(o=>Le({data:o})):"files"in n&&Array.isArray(n.files)?n.files.flatMap(o=>o!==null&&typeof o=="object"&&"source"in o&&typeof o.source=="string"&&/^(?:shell|debug):/u.test(o.source)?[o.source]:[]):"source"in n&&typeof n.source=="string"?[n.source]:[]}i(Le,"resultResources");export{Ur as a};
@@ -1,18 +0,0 @@
1
- import{a as sr,c as or}from"./chunk-PBMHSK6J.js";import{b as er,c as tr,g as nr,j as rr,p as wt}from"./chunk-OA26FH5G.js";import{a as Zn}from"./chunk-BXGMMZT3.js";import{a as kn,b as An,c as we,e as Mn,f as On,k as Nn,l as $n,o as ht,q as jn,r as Un,s as Wn}from"./chunk-4AEYLVSR.js";import{a as qn}from"./chunk-47SPPIXK.js";import{a as Dn,b as Tn}from"./chunk-VAXLSPPU.js";import{a as Cn,e as Pn}from"./chunk-BW3XONMZ.js";import{f as En,g as In}from"./chunk-JXULBI4S.js";import{a as Gn}from"./chunk-2YO6RVX4.js";import{b as Fn,c as Hn}from"./chunk-MLFJU2US.js";import{a as Vn}from"./chunk-JY63UUC2.js";import{a as _n}from"./chunk-I3G6K7QU.js";import{a as bn,b as Sn}from"./chunk-HSAGZWPO.js";import{a as Xe,e as xn}from"./chunk-PS2B6THP.js";import{d as Ln,e as Rn}from"./chunk-XEPCURYZ.js";import{B as dn,G as un,H as pn,I as gn,e as mt,fa as fn,ia as mn,la as hn,ma as yn,ra as wn,ta as vn}from"./chunk-OEEE5BLN.js";import{d as zn,f as Bn}from"./chunk-YNOR4LIE.js";import{f as Xn}from"./chunk-JKM4E5VB.js";import{a as yt,b as Oe,c as Jn,d as Z}from"./chunk-XQMNVPNS.js";import{m as Me}from"./chunk-IRLWXPL4.js";import{a as F}from"./chunk-ZC65Z3CK.js";import{a as Yn}from"./chunk-ZAWRSA7N.js";import{a as Kn,b as Qn}from"./chunk-OFILFO6D.js";import{a}from"./chunk-EI7MMDWY.js";import Oi from"node:path";var ve=[{id:"vue-typescript-language-server",name:"vue-typescript-language-server",kind:"lsp",languages:["vue"],executables:["typescript-language-server"],dependencies:["typescript-language-server","@vue/typescript-plugin"],configFiles:["tsconfig.json"],documentation:"https://github.com/vuejs/language-tools/tree/master/packages/typescript-plugin",lsp:{command:["typescript-language-server","--stdio"],rootMarkers:["tsconfig.json","package.json"],languageIds:{vue:[".vue"]},initializationOptions:{plugins:[{name:"@vue/typescript-plugin",location:"{project}/node_modules/@vue/typescript-plugin",languages:["vue"]}]}}},N("elixir-ls",["elixir"],["elixir-ls"],["mix.exs"],{elixir:[".ex",".exs"]},["elixir-ls"],"https://github.com/elixir-lsp/elixir-ls",void 0,void 0,{elixirLS:{mcpEnabled:!1}}),N("metals",["scala"],["metals"],["build.sbt","project.scala",".bsp"],{scala:[".scala",".sc"]},["metals"],"https://scalameta.org/metals/"),{id:"angular-language-server",name:"angular-language-server",kind:"lsp",languages:["typescript","html"],executables:["ngserver"],dependencies:["@angular/language-server"],configFiles:["angular.json"],documentation:"https://github.com/angular/vscode-ng-language-service",lsp:{command:["ngserver","--stdio","--tsProbeLocations",".","--ngProbeLocations","."],rootMarkers:["angular.json"],requireRootMarker:!0,languageIds:{typescript:[".ts"],html:[".html"]}}},N("svelte-language-server",["svelte"],["svelteserver"],["svelte.config.js","package.json"],{svelte:[".svelte"]},["svelteserver","--stdio"],"https://github.com/sveltejs/language-tools/tree/master/packages/language-server",["svelte-language-server"]),N("dart-language-server",["dart"],["dart"],["pubspec.yaml","analysis_options.yaml"],{dart:[".dart"]},["dart","language-server","--protocol=lsp"],"https://dart.dev/tools/dart-language-server"),N("r-language-server",["r"],["Rscript"],["DESCRIPTION",".lintr",".Rprofile"],{r:[".r"]},["Rscript","-e","languageserver::run()"],"https://github.com/REditorSupport/languageserver"),N("zls",["zig"],["zls"],["build.zig","build.zig.zon","zls.json"],{zig:[".zig",".zon"]},["zls"],"https://zigtools.org/zls/"),N("clangd",["c","cpp"],["clangd"],[".clangd","compile_commands.json","CMakeLists.txt"],{c:[".c",".h"],cpp:[".cc",".cpp",".cxx",".hh",".hpp",".hxx"]},["clangd"],"https://clangd.llvm.org/"),N("typescript-language-server",["javascript","typescript"],["typescript-language-server"],["tsconfig.json","jsconfig.json","package.json"],{javascript:[".js",".mjs",".cjs"],javascriptreact:[".jsx"],typescript:[".ts",".mts",".cts"],typescriptreact:[".tsx"]},["typescript-language-server","--stdio"],"https://github.com/typescript-language-server/typescript-language-server",["typescript-language-server"]),N("basedpyright",["python"],["basedpyright-langserver"],["pyproject.toml","pyrightconfig.json"],{python:[".py",".pyi"]},["basedpyright-langserver","--stdio"],"https://docs.basedpyright.com/",["basedpyright"]),N("pyright",["python"],["pyright-langserver"],["pyproject.toml","pyrightconfig.json"],{python:[".py",".pyi"]},["pyright-langserver","--stdio"],"https://microsoft.github.io/pyright/",["pyright"]),N("gopls",["go"],["gopls"],["go.mod","go.work"],{go:[".go"]},["gopls"],"https://go.dev/gopls/"),{id:"rust-analyzer",name:"rust-analyzer",kind:"lsp",languages:["rust"],executables:["rust-analyzer"],configFiles:["Cargo.toml","rust-project.json"],documentation:"https://rust-analyzer.github.io/",lsp:{command:["rust-analyzer"],rootMarkers:["Cargo.toml","rust-project.json"],languageIds:{rust:[".rs"]},initializationOptions:{checkOnSave:!1,cargo:{buildScripts:{enable:!1}},procMacro:{enable:!1}}}},N("csharp-ls",["csharp"],["csharp-ls"],[".sln",".csproj"],{csharp:[".cs"]},["csharp-ls"],"https://github.com/razzmatazz/csharp-language-server"),N("jdtls",["java"],["jdtls"],["pom.xml","build.gradle",".project"],{java:[".java"]},["jdtls"],"https://projects.eclipse.org/projects/eclipse.jdt.ls"),N("kotlin-language-server",["kotlin"],["kotlin-language-server"],["build.gradle.kts","pom.xml"],{kotlin:[".kt",".kts"]},["kotlin-language-server"],"https://github.com/fwcd/kotlin-language-server"),N("solargraph",["ruby"],["solargraph"],["Gemfile",".solargraph.yml"],{ruby:[".rb",".rake"]},["solargraph","stdio"],"https://solargraph.org/"),N("intelephense",["php"],["intelephense"],["composer.json"],{php:[".php"]},["intelephense","--stdio"],"https://intelephense.com/"),N("sourcekit-lsp",["swift"],["sourcekit-lsp"],["Package.swift"],{swift:[".swift"]},["sourcekit-lsp"],"https://github.com/swiftlang/sourcekit-lsp"),N("lua-language-server",["lua"],["lua-language-server"],[".luarc.json",".luarc.jsonc"],{lua:[".lua"]},["lua-language-server"],"https://luals.github.io/"),N("bash-language-server",["shell"],["bash-language-server"],[".shellcheckrc"],{shell:[".sh",".bash"]},["bash-language-server","start"],"https://github.com/bash-lsp/bash-language-server"),N("vscode-css-language-server",["css"],["vscode-css-language-server"],["package.json"],{css:[".css",".scss",".less"]},["vscode-css-language-server","--stdio"],"https://github.com/microsoft/vscode-css-languageservice",void 0,void 0,{css:{},scss:{},less:{}}),N("vscode-html-language-server",["html"],["vscode-html-language-server"],["package.json"],{html:[".html",".htm"]},["vscode-html-language-server","--stdio"],"https://github.com/microsoft/vscode-html-languageservice"),N("yaml-language-server",["yaml"],["yaml-language-server"],[".yamllint","package.json"],{yaml:[".yaml",".yml"]},["yaml-language-server","--stdio"],"https://github.com/redhat-developer/yaml-language-server"),N("taplo-lsp",["toml"],["taplo"],["taplo.toml"],{toml:[".toml"]},["taplo","lsp","stdio"],"https://taplo.tamasfe.dev/"),N("marksman",["markdown"],["marksman"],[".marksman.toml"],{markdown:[".md",".mdx"]},["marksman","server"],"https://github.com/artempyanykh/marksman"),N("terraform-ls",["terraform"],["terraform-ls"],[".terraform.lock.hcl"],{terraform:[".tf",".tfvars"]},["terraform-ls","serve"],"https://github.com/hashicorp/terraform-ls"),N("kotlin-lsp",["kotlin"],["intellij-server"],["build.gradle.kts","build.gradle","pom.xml","settings.gradle.kts"],{kotlin:[".kt",".kts"]},["intellij-server","--stdio"],"https://github.com/Kotlin/kotlin-lsp"),N("julia-language-server",["julia"],["julia"],["Project.toml","JuliaProject.toml"],{julia:[".jl"]},["julia","--startup-file=no","--history-file=no","-e","using LanguageServer; runserver()"],"https://github.com/julia-vscode/LanguageServer.jl"),N("powershell-editor-services",["powershell"],["pwsh"],["PSScriptAnalyzerSettings.psd1"],{powershell:[".ps1",".psm1",".psd1"]},["pwsh","-NoProfile","-NonInteractive","-Command",'$ErrorActionPreference="Stop";Import-Module PowerShellEditorServices;$d=Join-Path (Get-Location) ".agents/tmp/powershell-lsp-$PID";[IO.Directory]::CreateDirectory($d)|Out-Null;Start-EditorServices -HostName Pi -HostProfileId Pi -HostVersion 1.0.0 -Stdio -LanguageServiceOnly -LogPath (Join-Path $d "server.log") -SessionDetailsPath (Join-Path $d "session.json")'],"https://github.com/PowerShell/PowerShellEditorServices"),N("neocmakelsp",["cmake"],["neocmakelsp"],["CMakeLists.txt",".neocmake.toml",".neocmakelint.toml"],{cmake:[".cmake"]},["neocmakelsp","stdio"],"https://github.com/neocmakelsp/neocmakelsp",void 0,{cmake:["CMakeLists.txt"]}),N("vscode-json-language-server",["json"],["vscode-json-language-server"],["package.json"],{json:[".json",".jsonc"]},["vscode-json-language-server","--stdio"],"https://github.com/microsoft/vscode-json-languageservice"),N("lemminx",["xml"],["lemminx"],[".lemminx.json"],{xml:[".xml",".xsd",".xsl"]},["lemminx"],"https://github.com/eclipse-lemminx/lemminx"),N("sqls",["sql"],["sqls"],[".sqls.yml"],{sql:[".sql"]},["sqls"],"https://github.com/sqls-server/sqls"),N("docker-langserver",["dockerfile"],["docker-langserver"],["Dockerfile"],{dockerfile:[".dockerfile"]},["docker-langserver","--stdio"],"https://github.com/rcjsuen/dockerfile-language-server-nodejs",void 0,{dockerfile:["Dockerfile","Containerfile"]})];function N(t,e,n,r,s,o,i,c,l,d){return{id:t,name:t,kind:"lsp",languages:e,executables:n,configFiles:r,documentation:i,...c&&{dependencies:c},lsp:{command:o,rootMarkers:r,languageIds:s,...l&&{fileNames:l},...d&&{settings:d}}}}a(N,"recipe");var Ke="lsp.idle-timeout";function vt(t){let e=t.trim(),n=e===""?10:Number(e);if(!Number.isFinite(n)||n<=0)throw new Error(`Invalid ${Ke} setting "${t}": use a positive number of minutes.`);return Math.round(n*6e4)}a(vt,"lspIdleTimeoutMs");import{readFile as ur}from"node:fs/promises";import{URI as pr}from"vscode-uri";var Ne={Error:1,Warning:2,Information:3,Hint:4};var ir={command:"typescript.tsserverRequest",async request(t,e,n){return(await Promise.all(["syntacticDiagnosticsSync","semanticDiagnosticsSync","suggestionDiagnosticsSync"].map(async s=>{let o=await t.sendRequest("workspace/executeCommand",{command:"typescript.tsserverRequest",arguments:[s,{file:t.serverDocumentPath(e),includeLinePosition:!0},{isAsync:!1,expectsResult:!0}]},n);if(!bt(o)||o.success!==!0||!Array.isArray(o.body))throw new Error(`Invalid completed TypeScript diagnostic report: ${s}`);return o.body.map(Ss)}))).flat()}};function Qe(t){return t.supportsCommand(ir.command)?ir:void 0}a(Qe,"completedDiagnosticAdapter");function Ss(t){if(!bt(t)||typeof t.message!="string"||typeof t.code!="number"&&typeof t.code!="string"||!bt(t.startLocation)||!Number.isInteger(t.startLocation.line)||!Number.isInteger(t.startLocation.offset)||Number(t.startLocation.line)<1||Number(t.startLocation.offset)<1||!["error","warning","suggestion","message"].includes(String(t.category)))throw new Error("Invalid TypeScript diagnostic entry");return{code:String(t.code),message:t.message,line:Number(t.startLocation.line),column:Number(t.startLocation.offset),severity:t.category==="error"?"error":t.category==="warning"?"warning":t.category==="suggestion"?"hint":"info"}}a(Ss,"convertTypeScriptDiagnostic");function bt(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}a(bt,"isRecord");function Ye(t){return t!==null&&typeof t=="object"&&"code"in t&&t.code===-32601}a(Ye,"isMethodNotFound");import{watch as ar}from"node:fs";import{readdir as _s,stat as cr}from"node:fs/promises";import G from"node:path";import{URI as St}from"vscode-uri";var Ct=4,lr=-32090,et="pi/sharedDiagnosticsSuperseded",$e=class{static{a(this,"LspFileWatchers")}#e=new Map;#t;#r=!1;#n;#s;#o;constructor(e,n,r){this.#n=G.resolve(e),this.#s=n,this.#o=r}async register(e,n){if(this.#r)throw new Error("Language server file watchers are disposed");let r=[];for(let s of n){let o=s.globPattern,i=typeof o=="string"?this.#n:G.resolve(St.parse(typeof o.baseUri=="string"?o.baseUri:o.baseUri.uri).fsPath);!Ze(i,this.#n)&&!Ze(this.#n,i)||r.push({base:i,expression:typeof o=="string"?o:o.pattern,kind:s.kind??7})}this.#e.set(e,r),r.length>0?await this.#a():this.#i()}unregister(e){this.#e.delete(e),this.#i()}dispose(){this.#r=!0,this.#e.clear(),this.#i()}#a(){if(this.#t)return this.#t.ready;let e=new Rt(this.#n,(n,r)=>this.#c(e,n,r),n=>{this.#t===e&&this.#o(n)});return this.#t=e,e.ready}#i(){[...this.#e.values()].some(e=>e.length>0)||(this.#t?.close(),this.#t=void 0)}#c(e,n,r){let s=a(o=>[...this.#e.values()].some(i=>i.some(c=>(c.kind&1<<o-1)!==0&&Ls(c,r))),"matching");!s(1)&&!s(2)&&!s(3)||cr(r).then(o=>{if(this.#t!==e||o.isDirectory())return;let i=n==="rename"?1:2;s(i)&&this.#s({uri:St.file(r).toString(),type:i})},o=>{this.#t===e&&(o.code!=="ENOENT"?this.#o(o):s(3)&&this.#s({uri:St.file(r).toString(),type:3}))})}};function Ls(t,e){return G.isAbsolute(t.expression)?G.matchesGlob(e,t.expression):Ze(e,t.base)?G.matchesGlob(G.relative(t.base,e),t.expression):!1}a(Ls,"matches");function Ze(t,e){return t===e||t.startsWith(e.endsWith(G.sep)?e:e+G.sep)}a(Ze,"within");var _t=new Set([".git"]),Lt=new Set(["node_modules"]),Rt=class{static{a(this,"TreeWatcher")}#e=new Map;#t;#r=!1;#n;#s;ready=Promise.resolve();constructor(e,n,r){if(this.#n=n,this.#s=r,process.platform==="linux"){this.ready=this.#o(e);return}let s=ar(e,{recursive:!0},(o,i)=>{if(!i)return;let c=G.join(e,i);Rs(G.relative(e,c))&&this.#n(o,c)});s.on("error",o=>this.#s(o)),this.#t=s}close(){this.#r=!0,this.#t?.close();for(let e of this.#e.values())e.close();this.#e.clear()}async#o(e){if(this.#r||this.#e.has(e))return;let n;try{n=ar(e,(s,o)=>{o&&this.#a(s,G.join(e,o))})}catch(s){this.#i(s);return}if(n.on("error",s=>{n.close(),this.#e.get(e)===n&&this.#e.delete(e),this.#i(s)}),this.#e.set(e,n),Lt.has(G.basename(e)))return;let r;try{r=await _s(e,{withFileTypes:!0})}catch(s){this.#i(s);return}for(let s of r)s.isDirectory()&&!_t.has(s.name)&&await this.#o(G.join(e,s.name))}#a(e,n){if(this.#r||(this.#n(e,n),e!=="rename"))return;let r=G.basename(G.dirname(n));_t.has(G.basename(n))||Lt.has(r)||cr(n).then(s=>{s.isDirectory()&&this.#o(n)},()=>{for(let[s,o]of this.#e)Ze(s,n)&&(o.close(),this.#e.delete(s))})}#i(e){let n=e.code;this.#r||n==="ENOENT"||n==="EACCES"||n==="EPERM"||this.#s(e instanceof Error?e:new Error(String(e)))}};function Rs(t){let e=t.split(G.sep);return!e.some((n,r)=>_t.has(n)||Lt.has(n)&&r<e.length-2)}a(Rs,"included");function dr(t,e){return e.map(n=>{let r=t??null;for(let s of n.section?.split(".").filter(Boolean)??[])r=typeof r=="object"&&r!==null?r[s]??null:null;return r})}a(dr,"configurationItems");async function ee(t,e){if(e?.aborted)throw t.catch(()=>{}),e.reason;if(!e)return t;let n;try{return await Promise.race([t,new Promise((r,s)=>{n=a(()=>s(e.reason),"onAbort"),e.addEventListener("abort",n,{once:!0})})])}finally{n&&e.removeEventListener("abort",n)}}a(ee,"waitWithSignal");function je(t,e){let n;return ee(new Promise(r=>{n=setTimeout(r,t)}),e).finally(()=>clearTimeout(n))}a(je,"delayWithSignal");var be=class{static{a(this,"SharedStartup")}controller=new AbortController;promise;settled=!1;waiters=0;constructor(e){this.promise=e(this.controller.signal);let n=a(()=>{this.settled=!0},"settled");this.promise.then(n,n)}async wait(e){this.waiters+=1;let n=await ee(this.promise,e).then(r=>({value:r}),r=>({error:r}));if(this.waiters-=1,!this.settled&&this.waiters===0){this.controller.abort(e?.reason);try{await this.promise}catch(r){if(r!==this.controller.signal.reason)throw new AggregateError([this.controller.signal.reason,r],"Startup cancellation and cleanup failed",{cause:r})}}if("error"in n)throw n.error;return n.value}};var tt="SOURCE_CHANGED",Cs=[0,100,250,500];function O(t,e){return Object.assign(new Error(t,e),{code:tt})}a(O,"sourceChanged");function Pt(t){return t?.code===tt}a(Pt,"isSourceChanged");async function te(t,e,n){for(let r=0;;r+=1)try{return await t()}catch(s){let o=Cs[r];if(o===void 0||e?.aborted||!Pt(s)&&!n?.(s))throw s;o>0&&await je(o,e)}}a(te,"retryWhileSourceChanges");async function pe(t,e,n,r={}){let s=new AbortController,o=AbortSignal.any([s.signal,...r.signal?[r.signal]:[]]),i=setTimeout(()=>s.abort(new Error(`[lsp] ${t.serverId}: diagnostics timed out for ${e}`)),t.timeoutMs);try{return await Ps(t,e,n,r.content,o)}finally{clearTimeout(i)}}a(pe,"requestDiagnostics");async function Ps(t,e,n,r,s){if(s.throwIfAborted(),t.diagnosticMode!=="push"){let l=t.documentVersion(e),d=t.pulledReport(e);try{let u=await t.sendRequest("textDocument/diagnostic",{textDocument:{uri:e},...d!==void 0&&{previousResultId:d.resultId}},s),p=u.kind==="full"&&Array.isArray(u.items)?u.items:u.kind==="unchanged"&&d!==void 0&&u.resultId===d.resultId?[...d.diagnostics]:void 0;if(p===void 0)throw new Error("Invalid full diagnostic report");if(t.documentVersion(e)!==l)throw new Error("Document changed during diagnostic request");return t.setDiagnosticMode("pull"),l!==void 0&&typeof u.resultId=="string"&&t.rememberPulledReport(e,{version:l,resultId:u.resultId,diagnostics:p}),gr(p,!1,!0)}catch(u){if(!Ye(u))throw u;t.setDiagnosticMode("push")}}let o=Qe(t);if(o){t.documentVersion(e)===void 0&&t.syncDocument(e,r??await ur(pr.parse(e).fsPath,"utf8"),n??"plaintext");let l=t.documentVersion(e),d=await o.request(t,e,s);if(s.throwIfAborted(),t.documentVersion(e)!==l)throw new Error("Document changed during diagnostic request");return{diagnostics:d,syntaxErrors:[],otherDiagnostics:d,unversioned:!1,complete:!0}}s.throwIfAborted();let i=t.documentVersion(e)!==void 0,c=i?void 0:r??await ur(pr.parse(e).fsPath,"utf8");s.throwIfAborted(),t.beginDiagnosticRequest(e);try{return await new Promise((l,d)=>{let u=t.documentVersion(e),p=a(b=>{let L=b;L.uri!==e||!Array.isArray(L.diagnostics)||L.version!==void 0&&L.version!==u||t.documentVersion(e)===u&&(w(),l(gr(L.diagnostics,L.version===void 0)))},"receive"),f=t.onNotification("textDocument/publishDiagnostics",p),y=a(()=>{w(),d(O("The language server has newer file text; resync before checking diagnostics."))},"superseded"),S=t.shared?t.onNotification(et,b=>{let L=b;L.uri===e&&L.version===u&&y()}):void 0,h=a(()=>{w(),d(s.reason)},"onAbort");function w(){f(),S?.(),s.removeEventListener("abort",h)}a(w,"cleanup"),s.addEventListener("abort",h,{once:!0});try{i||t.syncDocument(e,c??"",n??"plaintext"),u=t.documentVersion(e);let b=t.diagnosticPublication(e);b?p({uri:e,...b}):t.diagnosticSuperseded(e)&&y()}catch(b){w(),d(b)}})}finally{t.endDiagnosticRequest(e)}}a(Ps,"requestCurrentDiagnostics");function xt(t){return{code:String(t.code??"LSP"),message:t.message,line:t.range.start.line+1,column:t.range.start.character+1,severity:t.severity===Ne.Warning?"warning":t.severity===Ne.Information?"info":t.severity===Ne.Hint?"hint":"error"}}a(xt,"toDiagnostic");function gr(t,e,n=!1){let r=t.map(xt);return{diagnostics:r,syntaxErrors:[],otherDiagnostics:r,unversioned:e,complete:n}}a(gr,"classify");function mr(t,e=(n,r)=>Promise.resolve({cwd:r,external:!1})){return{id:"lsp",async diagnose(n,r){let s=await e(n,r.cwd,r.signal);if(s===void 0)return{status:"unavailable",diagnostics:[],reason:"No local language-server project found for this file"};let o=await t(s.cwd,s.external,r.signal);r.signal.throwIfAborted();let i=await o.getOrStart(n,s.cwd,"diagnostics",r.signal);if(r.signal.throwIfAborted(),!i)return{status:"unavailable",diagnostics:[],reason:"No language server configured for this file"};let c=i.toUri(n),l=o.languageId(n),d=i.retainDocument(c);try{i.syncDocument(c,r.content,l,!0)}catch(g){throw d(),g}let u=i.documentVersion(c),p={active:!0,queued:!1},f=a(()=>!r.signal.aborted&&i.documentVersion(c)===u,"current"),y=a(async()=>(await i.waitUntilLoaded(r.signal),pe(i,c,l,{signal:r.signal,content:r.content})),"request"),S,h,w=a(async()=>{if(S=void 0,h=void 0,!(p.active||!p.queued||!f())){p.active=!0,p.queued=!1;try{let g=await y();f()&&r.publish(fr(g,i.commandName))}catch(g){f()&&r.publish({status:"unavailable",diagnostics:[],reason:g instanceof Error?g.message:String(g),source:i.commandName})}finally{p.active=!1,b()}}},"pullAgain"),b=a(()=>{if(p.active||!p.queued||!f())return;let g=Date.now();h??=g,clearTimeout(S),S=setTimeout(()=>void w(),Math.max(0,Math.min(xs,h+Es-g)))},"schedule"),L=a(()=>{p.queued=!0,b()},"refresh"),T=i.onNotification("workspace/diagnostic/refresh",()=>{f()&&i.diagnosticMode==="pull"&&L()}),k=o.onPushDiagnostics(g=>{!f()||g.uri!==c||g.serverId!==i.serverId||g.cwd!==s.cwd||g.version!==void 0&&g.version!==u||(i.diagnosticMode==="pull"||Qe(i)?L():r.publish({status:"snapshot",diagnostics:g.diagnostics,source:i.commandName,reason:hr(g.version===void 0)}))}),M=a(()=>{clearTimeout(S),k(),T()},"unsubscribe");r.signal.addEventListener("abort",M,{once:!0});try{let g=await y();return u=i.documentVersion(c),fr(g,i.commandName)}catch(g){throw p.queued=!1,M(),r.signal.removeEventListener("abort",M),g}finally{d(),p.active=!1,b()}}}}a(mr,"createLspDiagnosticSource");var xs=750,Es=3e3;function hr(t){return`Latest push snapshot; completion is unknown${t?"; language server omitted the document version":""}`}a(hr,"snapshotReason");function fr(t,e){return t.complete?{status:"ready",diagnostics:t.diagnostics,source:e}:{status:"snapshot",diagnostics:t.diagnostics,reason:hr(t.unversioned),source:e}}a(fr,"toReport");import{URI as Do}from"vscode-uri";import yo from"node:path";import wo from"cross-spawn";import{createMessageConnection as vo,CancellationTokenSource as bo,ResponseError as kr,StreamMessageReader as So}from"vscode-jsonrpc/node";import{URI as Dr}from"vscode-uri";import{spawn as Is}from"node:child_process";import{closeSync as Ds,openSync as Ts,readFileSync as vr,renameSync as ks,statSync as As}from"node:fs";import{createHash as Ms}from"node:crypto";import{lstat as Os,mkdir as br,mkdtemp as Ns,rename as $s,rm as js,stat as Us,symlink as Ws,utimes as qs,writeFile as Fs}from"node:fs/promises";import{createRequire as Hs}from"node:module";import Gs from"node:net";import Sr from"node:os";import J from"node:path";import{PassThrough as yr}from"node:stream";var _r=10*6e4,Vs="PI_AGENT_IDE_LSP_LINGER_MS";function Lr(t){let e=t[Vs];return e!==void 0&&/^\d+$/u.test(e)?Number(e):void 0}a(Lr,"sharedServerLingerOverride");var It=["shared-server-host.mjs","server-request-handlers.mjs"],Rr=It[0],Et=zs();function zs(){try{return It.map(t=>vr(new URL(t,new URL("../src/plugins/pi-agent-ide-lsp/src/lsp/shared-servers.ts",import.meta.url).href),"utf8"))}catch(t){return t instanceof Error?t:new Error(String(t))}}a(zs,"readHostSources");var Cr=1e4,Bs=25,nt=class{static{a(this,"LspSharedServers")}_directory;constructor(e={}){this._directory=e.directory??J.join(Sr.tmpdir(),`pi-agent-ide-lsp-${wr()}`)}async attach(e){let n=Ks(),r=Js(e,n.version),s=await this._socketPath(r),o=await Pr(s,e.signal);if(!o){let i=await Zs(this._directory,n),c=eo(i,s,r,this._directory);o=await oo(s,c,e.signal)}try{let i=await io(o,{protocol:Ct,key:r,command:e.command,cwd:e.cwd,env:e.env,settings:e.settings,initialize:e.initialize,lingerMs:e.lingerMs,timeoutMs:e.timeoutMs},e.timeoutMs+Cr,e.signal);if(typeof i.pid!="number")throw new Error(typeof i.error=="string"?i.error:"Shared language server did not attach");return ao(o,i.pid)}catch(i){throw o.destroy(),i}}async _socketPath(e){if(await br(this._directory,{recursive:!0,mode:448}),process.platform==="win32")return`\\\\.\\pipe\\pi-agent-ide-lsp-${Dt(Xs())}-${e}`;let n=await Os(this._directory);if(!n.isDirectory()||n.uid!==wr()||(n.mode&63)!==0)throw new Error(`Shared language server directory is not private: ${this._directory}`);return J.join(this._directory,`${e}.sock`)}};function Js(t,e){return Dt(JSON.stringify([Ct,e,t.serverId,t.command,t.configuredEnv,t.initialize.rootUri,t.initialize.initializationOptions??null,t.settings??null]))}a(Js,"sharedServerKey");function wr(){return process.getuid?.()??-1}a(wr,"currentUid");function Xs(){try{return Sr.userInfo().username}catch{return process.env.USERNAME||process.env.USER||"unknown"}}a(Xs,"currentUserName");function Dt(t){return Ms("sha256").update(t).digest("hex").slice(0,24)}a(Dt,"hash");function Ks(){if(Et instanceof Error)throw Et;let t=Et,e=Hs(new URL(Rr,new URL("../src/plugins/pi-agent-ide-lsp/src/lsp/shared-servers.ts",import.meta.url).href)),n=new Map([...new Set(t.flatMap(Qs))].toSorted().map(r=>[r,Ys(r,e.resolve(r))]));return{sources:t,packages:n,version:Dt(JSON.stringify([t,[...n]]))}}a(Ks,"loadedHost");function Qs(t){return[...t.matchAll(/\bfrom\s+["']([^"'.][^"']*)["']/gu)].map(([,e=""])=>e).filter(e=>!e.startsWith("node:")).map(e=>{let n=e.split("/");return(e.startsWith("@")?n.slice(0,2):n.slice(0,1)).join("/")})}a(Qs,"packageImports");function Ys(t,e){for(let n=J.dirname(e);;n=J.dirname(n)){try{if(JSON.parse(vr(J.join(n,"package.json"),"utf8")).name===t)return n}catch{}if(J.dirname(n)===n)throw new Error(`Shared language server host package not found: ${t}`)}}a(Ys,"packageRoot");async function Zs(t,e){let n=J.join(t,`host-${e.version}`),r=J.join(n,Rr),s=a(async()=>{try{await Us(r);let i=new Date;return await qs(n,i,i),!0}catch{return!1}},"present");if(await s())return r;let o=await Ns(J.join(t,"staging-"));try{await Promise.all(It.map((i,c)=>Fs(J.join(o,i),e.sources[c]??"")));for(let[i,c]of e.packages){let l=J.join(o,"node_modules",i);await br(J.dirname(l),{recursive:!0}),await Ws(c,l,"junction")}await $s(o,n)}catch(i){if(await js(o,{recursive:!0,force:!0}),!await s())throw i}return r}a(Zs,"writeHost");function eo(t,e,n,r){let s=process.versions.bun||!so()?process.execPath:"node",o=J.join(r,`${n}.log`);to(o);let i=Ts(o,"w",384);try{let c=Is(s,[t,e,n,o],{cwd:r,detached:!0,env:no(),stdio:["ignore","ignore",i],windowsHide:!0});return c.unref(),c}finally{Ds(i)}}a(eo,"startHost");function to(t){try{let{mtimeMs:e,size:n}=As(t);n>0&&ks(t,t.replace(/\.log$/u,`.${String(Math.round(e))}.log`))}catch{}}a(to,"keepFailureLog");function no(){let t={};for(let e of ro){let n=process.env[e];n!==void 0&&(t[e]=n)}return process.versions.bun&&(t.BUN_BE_BUN="1"),t}a(no,"hostEnvironment");var ro=["PATH","Path","HOME","USERPROFILE","TMPDIR","TMP","TEMP","SystemRoot","LANG"];function so(){return process.getBuiltinModule("node:sea")?.isSea?.()??!1}a(so,"singleExecutable");function Pr(t,e){return e?.throwIfAborted(),new Promise((n,r)=>{let s=Gs.connect(t);s.once("connect",()=>{s.removeAllListeners("error"),s.on("error",()=>{}),n(s)}),s.once("error",o=>{s.destroy(),o.code==="ENOENT"||o.code==="ECONNREFUSED"?n(void 0):r(o)})})}a(Pr,"connect");async function oo(t,e,n){let r;e.once("error",o=>r=o),e.once("exit",o=>{o!==0&&(r=new Error(`Shared language server host exited with code ${o}`))});let s=Date.now()+Cr;for(;;){if(r)throw r;let o=await Pr(t,n);if(o)return o;if(Date.now()>s)throw new Error("Shared language server host did not start");await new Promise(i=>setTimeout(i,Bs))}}a(oo,"waitForHost");function io(t,e,n,r){return new Promise((s,o)=>{let i=Buffer.alloc(0),c=a(f=>{i=Buffer.concat([i,f]);let y=i.indexOf(10);if(y!==-1){p(),t.pause(),y+1<i.length&&t.unshift(i.subarray(y+1));try{s(JSON.parse(i.subarray(0,y).toString("utf8")))}catch(S){o(S)}}},"onData"),l=a(()=>{p(),o(new Error("Shared language server host closed the connection"))},"onClose"),d=a(()=>{p(),o(r?.reason)},"onAbort"),u=setTimeout(()=>{p(),o(new Error("Shared language server attach timed out"))},n),p=a(()=>{clearTimeout(u),t.off("data",c),t.off("close",l),r?.removeEventListener("abort",d)},"finish");t.on("data",c),t.once("close",l),r?.addEventListener("abort",d,{once:!0}),t.write(`${JSON.stringify(e)}
2
- `)})}a(io,"exchange");function ao(t,e){let n=!1,r=new Promise(i=>t.once("close",()=>i())),s=new yr;s.end();let o=t.pipe(new yr);return{stdin:t,stdout:o,stderr:s,pid:e,completion:r.then(()=>({exitCode:n?0:1})),async stop(){n=!0,t.end();let i=setTimeout(()=>t.destroy(),1e3);await r,clearTimeout(i)}}}a(ao,"sharedServer");import{StreamMessageWriter as co}from"vscode-jsonrpc/node";var rt=class extends co{constructor(n,r){super(n);this.fail=r}static{a(this,"TransportWriter")}async write(n){try{await super.write(n)}catch(r){this.fail(r)}}};import lo from"node:path";import{URI as uo}from"vscode-uri";function X(t,e){if(e.startsWith("ssh://")){let n=xr(e);if(t.includes("://")){let s=xr(t);if(s.host!==n.host)throw new Error("Document belongs to another language server owner");return s.href}let r=lo.posix.resolve(decodeURIComponent(n.pathname),t);return n.pathname=r.split("/").map(encodeURIComponent).join("/"),n.href}if(t.startsWith("ssh://")||t.includes("://")&&!t.startsWith("file://"))throw new Error("Document belongs to another language server owner");return t.startsWith("file://")?t:uo.file(t).toString()}a(X,"documentUri");function xr(t){let e=new URL(t);if(e.protocol!=="ssh:"||!e.hostname||e.username||e.password||e.port||e.search||e.hash)throw new Error("Invalid language server resource owner");return decodeURIComponent(e.pathname),e}a(xr,"checkedRemote");var po=new Set(["uri","targetUri","target","oldUri","newUri","rootUri","documentUri","scopeUri","baseUri"]),go=new Set(["changes","relatedDocuments"]);function ce(t,e){return Array.isArray(t)?t.map(n=>ce(n,e)):typeof t!="object"||t===null?t:Object.fromEntries(Object.entries(t).map(([n,r])=>po.has(n)&&typeof r=="string"?[n,e(r)]:go.has(n)&&typeof r=="object"&&r!==null&&!Array.isArray(r)?[n,Object.fromEntries(Object.entries(r).map(([s,o])=>[e(s),ce(o,e)]))]:[n,ce(r,e)]))}a(ce,"mapLspUris");import fo from"node:path";var mo=/^clangd(?:-\d+(?:\.\d+)*)?$/u,ho=['u="${XDG_CONFIG_HOME:-$HOME/.config}/clangd/config.yaml"',"write() {",' c="$1/clangd/config.yaml"',' mkdir -p "$1/clangd" && {'," printf '%s\\n' '# Written by pi-agent-ide for the clangd it starts: report every error.' 'CompileFlags:' ' Add: [-ferror-limit=0]'",` if [ -f "$u" ] && [ "$u" != "$c" ]; then printf '%s\\n' '---'; cat "$u"; fi`,' } > "$c.$$" && mv -f "$c.$$" "$c" || { rm -f "$c.$$"; false; }',"}",'d="${XDG_CACHE_HOME:-$HOME/.cache}/pi-agent-ide/clangd-config"','if write "$d" 2>/dev/null || { d=$(mktemp -d "${TMPDIR:-/tmp}/pi-agent-ide-clangd.XXXXXX") && write "$d"; } 2>/dev/null; then',' XDG_CONFIG_HOME="$d"'," export XDG_CONFIG_HOME","fi",'exec "$@"'].join(`
3
- `);function Er(t,e){let n=t[0];return!e||n===void 0||!mo.test(fo.posix.basename(n))?[...t]:["sh","-c",ho,"pi-agent-ide-clangd",...t]}a(Er,"launchCommand");function Ir(t=process.platform){return t!=="win32"&&t!=="darwin"}a(Ir,"localXdgConfig");var ge=class{static{a(this,"LspClient")}_process=null;_ownedProcess=null;_ownedStartup;_ownerTransport;_sharedServers;_sharedServer=null;_connection=null;_initialized=!1;_serverCapabilities=null;_disposed=!1;_shutdownPromise;_crashed=!1;_stderr="";_fileWatchers;_fileWatcherCleanup=Promise.resolve();_handlers=new Map;_documentVersions=new Map;_lastSharedDocumentVersion=0;_documentContents=new Map;_diagnosticPublications=new Map;_supersededDiagnostics=new Set;_pulledReports=new Map;_diagnosticMode="unknown";_pullRegistration;_versionedDiagnostics=!1;_activeDiagnosticRequests=new Set;_serverStatus;_serverStatusListeners=new Set;_pendingSaves=new Set;_documentLeases=new Map;_pendingRequests=0;_idleTimer;_idleTimeoutMs;_onIdle;serverId;rootUri;_command;_launch;_args;_env;_initOptions;_settings;_timeoutMs;constructor(e){this.serverId=e.serverId,this.rootUri=e.rootUri,this._command=e.command,this._launch=Er(e.command,e.ownerTransport!==void 0||Ir()),this._args=this._launch.slice(1),this._env=e.env??{},this._initOptions=e.initOptions,this._settings=e.settings,this._timeoutMs=e.timeoutMs??3e4,this._ownerTransport=e.ownerTransport,this._sharedServers=e.sharedServers,this._idleTimeoutMs=e.idleTimeoutMs,this._onIdle=e.onIdle}get ready(){return this._initialized&&!this._disposed}get crashed(){return this._crashed}get pid(){return this._process?.pid??this._sharedServer?.pid??null}get shared(){return this._sharedServer!==null}get remote(){return this._ownedProcess?.remote}get commandName(){return er(this._command)}get diagnosticMode(){return this._diagnosticMode}setDiagnosticMode(e){this._diagnosticMode=e}get timeoutMs(){return this._timeoutMs}supportsCommand(e){let n=this._serverCapabilities?.executeCommandProvider;return Array.isArray(n?.commands)&&n.commands.includes(e)}get loading(){return this._serverStatus?.quiescent===!1}async waitUntilLoaded(e){if(!this.loading)return;let n,r;try{await ee(new Promise((s,o)=>{n=a(()=>{this.loading||s()},"listener"),this._serverStatusListeners.add(n),r=setTimeout(()=>{let i=this._serverStatus?.message;o(Object.assign(new Error(`[lsp] ${this.serverId} is still loading the project${i?` (${i})`:""}; its results would be incomplete. Try again later.`),{code:"SERVER_LOADING"}))},this._timeoutMs)}),e)}finally{clearTimeout(r),n&&this._serverStatusListeners.delete(n)}}_setServerStatus(e){this._serverStatus=e;for(let n of[...this._serverStatusListeners])n()}get hasWorkspaceSymbolCapability(){let e=this._serverCapabilities?.workspaceSymbolProvider;return e===!0||typeof e=="object"&&e!==null}get hasFoldingRangeCapability(){let e=this._serverCapabilities?.foldingRangeProvider;return e===!0||typeof e=="object"&&e!==null}documentContent(e){return this._documentContents.get(e)}documentVersion(e){return this._documentVersions.get(e)}diagnosticPublication(e){return this._diagnosticPublications.get(e)}diagnosticSuperseded(e){return this._supersededDiagnostics.has(e)}pulledReport(e){let n=this._pulledReports.get(e);return n?.version===this.documentVersion(e)?n:void 0}rememberPulledReport(e,n){n.version===this.documentVersion(e)&&this._pulledReports.set(e,n)}beginDiagnosticRequest(e){this._activeDiagnosticRequests.add(e)}endDiagnosticRequest(e){this._activeDiagnosticRequests.delete(e)}hasActiveDiagnosticRequest(e){return this._activeDiagnosticRequests.has(e)}async start(e){e?.throwIfAborted();try{await this._start(e)}catch(n){try{await this.shutdown()}catch(r){throw new AggregateError([e?.aborted?e.reason:n,r],`[lsp] ${this.serverId}: startup and cleanup failed`,{cause:r})}throw e?.throwIfAborted(),n}}async _start(e){if(this._initialized)return;if(this._disposed)throw new Error(`[lsp] ${this.serverId}: disposed`);if(!this.rootUri.startsWith("file://")&&!this._ownerTransport)throw Object.assign(new Error("No language server process transport for this resource owner"),{code:"UNSUPPORTED_SOURCE"});if(await this._closeFileWatchers(),e?.throwIfAborted(),this._disposed)throw new Error(`[lsp] ${this.serverId}: disposed`);let n=F(this._launch[0]),r=this._ownerTransport?decodeURIComponent(new URL(this.rootUri).pathname):Dr.parse(this.rootUri).fsPath,s=[{uri:this._ownerTransport?.toServerUri(this.rootUri)??this.rootUri,name:yo.basename(r)||r}],o=this._ownerTransport?this._ownerTransport.fileWatchers!==void 0:!0,i={processId:this._ownerTransport?null:process.pid,rootUri:this._ownerTransport?.toServerUri(this.rootUri)??this.rootUri,workspaceFolders:s,capabilities:{workspace:{applyEdit:!1,configuration:!0,workspaceFolders:!0,didChangeWatchedFiles:{dynamicRegistration:o,relativePatternSupport:o},symbol:{dynamicRegistration:!1}},experimental:{serverStatusNotification:!0},textDocument:{synchronization:{didOpen:!0,didChange:!0,didClose:!0},publishDiagnostics:{relatedInformation:!0,versionSupport:!0},diagnostic:{dynamicRegistration:!0,relatedDocumentSupport:!1},documentSymbol:{hierarchicalDocumentSymbolSupport:!0},foldingRange:{lineFoldingOnly:!0}}},initializationOptions:this._initOptions};this._ownedStartup=this._ownerTransport?.start({rootUri:this.rootUri,command:this._launch,env:this._env,signal:e});let c=await this._ownedStartup;if(this._ownedProcess=c??null,e?.throwIfAborted(),this._disposed)throw new Error(`[lsp] ${this.serverId}: disposed`);let l=c?void 0:await this._attachSharedServer(r,i,e);if(this._disposed)throw await l?.stop(),new Error(`[lsp] ${this.serverId}: disposed`);this._sharedServer=l??null,e?.throwIfAborted();let d=c||l?void 0:wo(n,this._args,{stdio:["pipe","pipe","pipe"],...e&&{signal:e},cwd:r,env:wt({command:this._command,env:this._env},r,process.env)});this._process=d??null;let u=d?xo(d):Promise.resolve(),p=c??l,f=F(p?.stdin??d?.stdin),y=F(p?.stdout??d?.stdout),S=F(p?.stderr??d?.stderr);f.on("error",()=>{}),y.on("error",()=>{}),S.on("error",()=>{}),this._stderr="";let h=new Promise(m=>{S.once("end",m),S.once("close",m)}),w,b=a(()=>{},"markExited"),L=new Promise(m=>{b=m});S.setEncoding("utf8"),S.on("data",m=>{this._stderr=(this._stderr+m).slice(-4096)}),d?.on("error",m=>{("code"in m?m.code:void 0)!=="ENOENT"&&console.error(`[lsp] ${this.serverId}: spawn failed:`,m),this._crashed=!0,this._connection?.dispose(),this._connection=null,this._process=null});let T=a(()=>c?this._ownedProcess===c:l?this._sharedServer===l:this._process===d,"current"),k=a(m=>{T()&&(w??=m,b(),this._closeFileWatchers(),!this._disposed&&m!==0&&m!==null&&(this._crashed=!0),this._connection?.dispose(),this._connection=null,this._diagnosticPublications.clear(),this._supersededDiagnostics.clear(),this._pulledReports.clear(),this._activeDiagnosticRequests.clear(),this._diagnosticMode="unknown",this._pullRegistration=void 0,this._versionedDiagnostics=!1,this._setServerStatus(void 0),this._process=null,this._initialized=!1)},"onExit");d?.on("exit",k),p?.completion.then(({exitCode:m})=>k(m),()=>{T()&&(this._crashed=!0,k(null))}),await ee(u,e);let M=vo(new So(y),new rt(f,m=>{this._connection!==M||this._disposed||(this._crashed=!0,this._initialized=!1,this._closeFileWatchers(),M.dispose(),console.error(`[lsp] ${this.serverId}: transport write failed:`,m))}));this._connection=M,this._connection.onError(m=>{console.error(`[lsp] ${this.serverId}: connection error:`,m)});let g=a(m=>{this._sendNotification("workspace/didChangeWatchedFiles",{changes:[m]})},"changed"),C=a(m=>console.error(`[lsp] ${this.serverId}: file watcher failed:`,m),"failed");this._fileWatchers=this._ownerTransport?this._ownerTransport.fileWatchers?.(this.rootUri,g,C):l?void 0:new $e(r,g,C),this._connection.onRequest("client/registerCapability",async m=>{for(let P of m.registrations)if(P.method!=="workspace/didChangeConfiguration"){if(P.method==="textDocument/diagnostic"){this._pullRegistration=P.id,this._initialized&&(this._diagnosticMode="pull");continue}if(P.method!=="workspace/didChangeWatchedFiles")throw new Error(`Unsupported dynamic capability: ${P.method}`);if(!this._fileWatchers)throw new Error("File watching is unavailable for this server owner");await this._fileWatchers.register(P.id,P.registerOptions?.watchers??[])}return null}),this._connection.onRequest("client/unregisterCapability",async m=>{for(let P of m.unregisterations)P.id===this._pullRegistration?(this._pullRegistration=void 0,this._initialized&&(this._diagnosticMode="push")):await this._fileWatchers?.unregister(P.id);return null}),this._connection.onRequest("window/workDoneProgress/create",()=>null),this._connection.onRequest("workspace/diagnostic/refresh",()=>{for(let m of this._handlers.get("workspace/diagnostic/refresh")??[])m(void 0);return null}),this._connection.onRequest("workspace/configuration",m=>dr(this._settings,m.items)),this._connection.listen(),this._connection.onNotification((m,...P)=>{let I=this._ownerTransport,A=I?ce(P[0],x=>I.fromServerUri(x)):P[0];if(m===et){let x=A;if(!this.shared||typeof x?.uri!="string"||typeof x.version!="number"||x.version!==this.documentVersion(x.uri))return;this._supersededDiagnostics.add(x.uri)}if(m==="textDocument/publishDiagnostics"){let x=A;if(typeof x?.version=="number")this._versionedDiagnostics=!0;else if(this._versionedDiagnostics&&typeof x?.uri=="string"&&this._documentVersions.has(x.uri))return;x&&typeof x.uri=="string"&&Array.isArray(x.diagnostics)&&this._documentVersions.has(x.uri)&&(x.version===void 0||x.version===this.documentVersion(x.uri))&&(this._supersededDiagnostics.delete(x.uri),this._diagnosticPublications.set(x.uri,{diagnostics:x.diagnostics,...typeof x.version=="number"&&{version:x.version}}))}if(m==="experimental/serverStatus"){let x=A;this._setServerStatus({quiescent:x?.quiescent!==!1,...typeof x?.message=="string"&&{message:x.message}})}for(let x of this._handlers.get(m)?.slice()??[])x(A)}),this._connection.onRequest("workspace/workspaceFolders",()=>s);let E=await ee(Tr(this._connection.sendRequest("initialize",i),this._timeoutMs,`[lsp] ${this.serverId}: initialize timed out`),e).catch(async m=>{if(e?.aborted)throw m;await Promise.race([Promise.all([h,L]),je(_o,e)]).catch(()=>{});let P=this._stderr.trim(),I=w===void 0?void 0:`exited during startup${w===null?"":` with code ${w}`}`;if(!P&&!I)throw m;let A=`[lsp] ${this.serverId}${I?` ${I}`:""}${P?`: ${P}`:""}`;throw I?new Error(A):new Error(A,{cause:m})});if(await this._connection.sendNotification("initialized",{capabilities:E.capabilities}),this._settings!==void 0&&await this._connection.sendNotification("workspace/didChangeConfiguration",{settings:this._settings}),this._crashed)throw new Error(`[lsp] ${this.serverId}: transport failed during initialization`);e?.throwIfAborted(),this._initialized=!0,this._serverCapabilities=E.capabilities,this._diagnosticMode=E.capabilities.diagnosticProvider||this._pullRegistration!==void 0?"pull":"push"}async _attachSharedServer(e,n,r){if(this._sharedServers)try{return await this._sharedServers.attach({serverId:this.serverId,command:this._launch,cwd:e,configuredEnv:this._env,env:wt({command:this._command,env:this._env},e,process.env),settings:this._settings,initialize:n,lingerMs:Lr(process.env)??this._idleTimeoutMs??_r,timeoutMs:this._timeoutMs,...r&&{signal:r}})}catch{r?.throwIfAborted();return}}touch(){if(clearTimeout(this._idleTimer),this._idleTimer=void 0,this._idleTimeoutMs===void 0||this._disposed||this._busy)return;let e=setTimeout(()=>{this._idleTimer===e&&(this._idleTimer=void 0,this.ready&&!this._busy&&this._onIdle?.())},this._idleTimeoutMs);e.unref(),this._idleTimer=e}get _busy(){return this._pendingRequests>0||this._documentLeases.size>0}retainDocument(e){this._documentLeases.set(e,(this._documentLeases.get(e)??0)+1),this.touch();let n=!1;return()=>{if(n)return;n=!0;let r=(this._documentLeases.get(e)??1)-1;if(r>0){this._documentLeases.set(e,r);return}this._documentLeases.delete(e),this.ready&&this._documentVersions.has(e)&&this.closeDocument(e),this.touch()}}async restart(e){await this.shutdown(),this._closeFileWatchers(),this._connection?.dispose(),this._connection=null,this._process=null,this._initialized=!1,this._crashed=!1,this._disposed=!1,this._shutdownPromise=void 0,this._documentVersions.clear(),this._documentContents.clear(),this._diagnosticPublications.clear(),this._supersededDiagnostics.clear(),this._pulledReports.clear(),this._diagnosticMode="unknown",this._versionedDiagnostics=!1,this._activeDiagnosticRequests.clear(),this._serverCapabilities=null,await this.start(e)}async sendRequest(e,n,r){this._assertReady(),r?.throwIfAborted(),this._pendingRequests++,this.touch();try{let s=!1;for(let o=0;;o++){let i;try{i=await this._sendRequest(e,n,r)}catch(c){if(this.shared&&c instanceof kr&&c.code===lr)throw O(c.message);let l=Lo[o];if(l===void 0||!Po(c))throw c;await je(l,r),this._assertReady();continue}if(s||!this.loading||e==="workspace/executeCommand")return i;s=!0,await this.waitUntilLoaded(r),this._assertReady()}}finally{this._pendingRequests--,this.touch()}}async _sendRequest(e,n,r){let s=this._ownerTransport,o=s?ce(n,d=>s.toServerUri(d)):n,i=a(d=>s?ce(d,u=>s.fromServerUri(u)):d,"mapResult");if(!r)return i(await F(this._connection).sendRequest(e,o));let c=new bo,l;try{let d=F(this._connection).sendRequest(e,o,c.token);return i(await Promise.race([d,new Promise((u,p)=>{l=a(()=>{c.cancel(),p(r.reason)},"onAbort"),r.addEventListener("abort",l,{once:!0})})]))}finally{l&&r.removeEventListener("abort",l),c.dispose()}}sendNotification(e,n){this._assertReady(),this._sendNotification(e,n)}_sendNotification(e,n){let r=this._connection;if(!r)return;let s=this._ownerTransport,o=s?ce(n,i=>s.toServerUri(i)):n;r.sendNotification(e,o).catch(i=>{this._connection!==r||this._disposed||(this._crashed=!0,this._initialized=!1,this._closeFileWatchers(),r.dispose(),console.error(`[lsp] ${this.serverId}: notification ${e} failed:`,i))})}onNotification(e,n){let r=this._handlers.get(e)??[];return r.push(n),this._handlers.set(e,r),()=>{let s=r.indexOf(n);s!==-1&&r.splice(s,1)}}toUri(e){return X(e,this.rootUri)}serverDocumentPath(e){let n=this.toUri(e),r=this._ownerTransport?.toServerUri(n)??n;return this._ownerTransport?decodeURIComponent(new URL(r).pathname):Dr.parse(r).fsPath}openDocument(e,n,r,s=1){let o=this._documentVersions.get(e);if(o!==void 0){this.changeDocument(e,n,Math.max(s,o+1));return}this._diagnosticPublications.delete(e),this._supersededDiagnostics.delete(e),this._pulledReports.delete(e);let i=this._sharedDocumentVersion(s);this.sendNotification("textDocument/didOpen",{textDocument:{uri:e,languageId:r,version:i,text:n}}),this._documentVersions.set(e,i),this._documentContents.set(e,n)}syncDocument(e,n,r,s=!1){if(this._documentContents.get(e)===n&&!this.diagnosticSuperseded(e))return;let o=this._documentVersions.get(e);o===void 0?this.openDocument(e,n,r):this.changeDocument(e,n,o+1),s&&(this.loading?this._deferSave(e):this._sendSave(e))}_sendSave(e){let n=this._serverCapabilities?.textDocumentSync,r=typeof n=="object"&&n!==null?n.save:void 0,s=this._documentContents.get(e);!r||s===void 0||this.sendNotification("textDocument/didSave",{textDocument:{uri:e},...typeof r=="object"&&r.includeText&&{text:s}})}_deferSave(e){let n=this._pendingSaves.size>0;if(this._pendingSaves.add(e),n)return;let r=a(()=>{if(this.loading)return;this._serverStatusListeners.delete(r);let s=[...this._pendingSaves];this._pendingSaves.clear();for(let o of s)this._sendSave(o)},"listener");this._serverStatusListeners.add(r)}changeDocument(e,n,r){let s=this._documentVersions.get(e),o=this._sharedDocumentVersion(Math.max(r,(s??0)+1));this._diagnosticPublications.delete(e),this._supersededDiagnostics.delete(e),this._pulledReports.delete(e),this.sendNotification("textDocument/didChange",{textDocument:{uri:e,version:o},contentChanges:[{text:n}]}),this._documentVersions.set(e,o),this._documentContents.set(e,n)}_sharedDocumentVersion(e){return this.shared?this._lastSharedDocumentVersion=Math.max(e,this._lastSharedDocumentVersion+1):e}closeDocument(e){this.sendNotification("textDocument/didClose",{textDocument:{uri:e}}),this._documentVersions.delete(e),this._documentContents.delete(e),this._diagnosticPublications.delete(e),this._supersededDiagnostics.delete(e),this._pulledReports.delete(e)}shutdown(){return this._shutdownPromise??=this._shutdown()}async _shutdown(){this._disposed=!0,this._setServerStatus(void 0),clearTimeout(this._idleTimer),this._idleTimer=void 0;let e=this._closeFileWatchers();if(this._connection&&this._initialized)try{await Tr(this._connection.sendRequest("shutdown"),Math.min(this._timeoutMs,1e3),`[lsp] ${this.serverId}: shutdown timed out`),await this._connection.sendNotification("exit").catch(()=>{})}catch{}this._connection?.dispose(),this._connection=null;let n=this._ownedProcess??await this._ownedStartup?.catch(()=>{});this._ownedProcess=null,this._ownedStartup=void 0;let r=Promise.resolve().then(()=>n?.stop()),s=this._sharedServer;this._sharedServer=null;let o=Promise.resolve().then(()=>s?.stop()),i=this._process;this._process=null,i&&!i.killed&&(i.kill("SIGTERM"),setTimeout(()=>{i.exitCode===null&&i.signalCode===null&&i.kill("SIGKILL")},2e3).unref()),this._initialized=!1,this._documentVersions.clear(),this._documentContents.clear(),this._diagnosticPublications.clear(),this._supersededDiagnostics.clear(),this._pulledReports.clear(),this._diagnosticMode="unknown",this._versionedDiagnostics=!1,this._activeDiagnosticRequests.clear(),this._serverCapabilities=null;let c=await Promise.allSettled([r,o,e]),l=[];for(let d of c)d.status==="rejected"&&l.push(d.reason);if(l.length>0)throw new AggregateError(l,`[lsp] ${this.serverId}: owned cleanup failed`)}dispose(){return this.shutdown()}_closeFileWatchers(){let e=this._fileWatchers;return this._fileWatchers=void 0,e&&(this._fileWatcherCleanup=this._fileWatcherCleanup.catch(()=>{}).then(()=>e.dispose()),this._fileWatcherCleanup.catch(n=>{console.error(`[lsp] ${this.serverId}: file watcher cleanup failed:`,n)})),this._fileWatcherCleanup}_assertReady(){if(this._disposed)throw new Error(`[lsp] ${this.serverId}: disposed`);if(this._crashed)throw new Error(`[lsp] ${this.serverId}: crashed \u2014 call restart()`);if(!this._initialized)throw new Error(`[lsp] ${this.serverId}: not started \u2014 call start()`);if(!this._connection)throw new Error(`[lsp] ${this.serverId}: connection lost`)}},_o=250,Lo=[50,100,200,400,800],Ro=-32801,Co=-32802;function Po(t){if(!(t instanceof kr))return!1;if(t.code===Ro)return!0;if(t.code!==Co)return!1;let e=t.data;return!(e!==null&&typeof e=="object"&&"retriggerRequest"in e&&e.retriggerRequest===!1)}a(Po,"isRetryableCancellation");function xo(t){return new Promise((e,n)=>{let r=a(()=>{t.off("spawn",s),t.off("error",o)},"cleanup"),s=a(()=>{r(),e()},"onSpawn"),o=a(i=>{r(),n(i)},"onError");t.once("spawn",s),t.once("error",o)})}a(xo,"waitForSpawn");function Tr(t,e,n){return new Promise((r,s)=>{let o=setTimeout(()=>{s(new Error(n))},e);t.then(i=>{clearTimeout(o),r(i)}).catch(i=>{clearTimeout(o),s(i instanceof Error?i:new Error(String(i)))})})}a(Tr,"withTimeout");import H from"node:path";import{existsSync as Eo}from"node:fs";function Ar(t){let e=new Map,n=new Map;for(let[r,s]of Object.entries(t))for(let[o,i]of Object.entries(s.languages))for(let c of i.extensions){let l=c.toLowerCase(),d=e.get(l);if(d!==void 0&&d!==o)throw new Error(`[lsp] extension conflict: "${l}" claimed by "${d}" and "${o}"`);e.set(l,o);let u=n.get(l)??[];u.push(r),n.set(l,u)}return{extToLanguageId:e,extToServerIds:n}}a(Ar,"buildLanguageLookup");var ie=class t{constructor(e,n,r){this._projectRoot=r;this._entries=e;let s=e.filter(o=>o.layer!=="built-in"||n.has(o.id));this._servers=Object.fromEntries(s.map(o=>[o.id,o.config])),this._lookup=Ar(this._servers)}static{a(this,"LspServerRegistry")}_servers;_entries;_lookup;static async fromPackageDir(e,n={}){n.signal?.throwIfAborted();let r=await nr(e,"lsp-servers",l=>Io(l).servers,n);if(n.signal?.throwIfAborted(),e.startsWith("ssh://")&&(!n.executableAvailable&&!n.executableAvailability||n.requireBuiltInEvidence&&!n.recipeEvidence))throw Object.assign(new Error("Remote language server availability needs its workspace owner"),{code:"UNSUPPORTED_SOURCE"});let s=n.environment??process.env,o=r.entries.filter(l=>l.layer==="built-in"),i=[];if(n.executableAvailability){let l=await n.executableAvailability(o.map(d=>d.config));if(l.length!==o.length||l.some(d=>typeof d!="boolean"))throw new TypeError("Invalid owner executable availability report");for(let[d,u]of o.entries())i.push({id:u.id,available:l[d]===!0})}else if(n.executableAvailable)for(let l of o)i.push({id:l.id,available:await n.executableAvailable(l.config)});else i.push(...await Promise.all(o.map(async l=>({id:l.id,available:await rr(l.config,e,s,n.signal)}))));n.signal?.throwIfAborted();let c=n.requireBuiltInEvidence?n.recipeEvidence?await n.recipeEvidence(n.recipes??[]):await Zn(e,n.recipes??[],void 0,n.signal):void 0;return n.signal?.throwIfAborted(),new t(r.entries,new Set(i.filter(l=>l.available&&(c===void 0||(c.get(l.id)?.score??0)>0)).map(l=>l.id)),e.startsWith("ssh://")?e:H.resolve(e))}static fromConfig(e,n=process.cwd()){return new t(Object.entries(e.servers).map(([r,s])=>({id:r,config:s,layer:"project",sourcePath:"<memory>"})),new Set,n.startsWith("ssh://")?n:H.resolve(n))}resolve(e){return this.candidates(e).filter(n=>!n.config.requireRootMarker||this.hasRootMarker(e,n.config.rootMarkers))}candidates(e){let n=H.basename(e),r=H.extname(e)||(e.startsWith(".")?e:`.${e}`),s=a(i=>process.platform==="win32"?i.toLowerCase():i,"normalizeName"),o=[];for(let i of this._entries)if(this._servers[i.id]){for(let[c,l]of Object.entries(i.config.languages))if(l.extensions.some(d=>d.toLowerCase()===r.toLowerCase())||l.fileNames?.some(d=>s(d)===s(n))){o.push({serverId:i.id,config:i.config,languageId:c,layer:i.layer,sourcePath:i.sourcePath});break}}return o}async resolveOwned(e,n){if(!this._projectRoot.startsWith("ssh://"))return this.resolve(e);let r=new URL(this._projectRoot),s=decodeURIComponent(r.pathname),o=e.startsWith(".")&&!e.includes("/"),i=e.includes("://")?new URL(e):new URL(r.href),c=e.includes("://")?decodeURIComponent(i.pathname):H.posix.resolve(s,e),l=H.posix.relative(s,c);if(i.origin!==r.origin||i.host!==r.host||i.protocol!==r.protocol||i.username||i.password||i.port||i.search||i.hash||l===".."||l.startsWith("../"))throw Object.assign(new Error("Language server resource belongs to another owner"),{code:"UNSUPPORTED_SOURCE"});let d=[];for(let u of this.candidates(o?e:c)){if(!u.config.requireRootMarker){d.push(u);continue}let p=o||c===s?s:H.posix.dirname(c);for(;;){let f=!1;for(let y of u.config.rootMarkers){let S=H.posix.resolve(p,y),h=H.posix.relative(s,S);if(h===".."||h.startsWith("../"))continue;let w=new URL(r.href);if(w.pathname=S.split("/").map(encodeURIComponent).join("/"),await n(w.href)){f=!0;break}}if(f){d.push(u);break}if(p===s)break;p=H.posix.dirname(p)}}return d}hasRootMarker(e,n){let r=H.dirname(H.resolve(this._projectRoot,e));for(e.startsWith(".")&&!e.includes(H.sep)&&(r=this._projectRoot);;){let s=H.relative(this._projectRoot,r);if(s===".."||s.startsWith(`..${H.sep}`)||H.isAbsolute(s))return!1;if(n.some(o=>Eo(H.join(r,o))))return!0;if(r===this._projectRoot)return!1;r=H.dirname(r)}}get projectRoot(){return this._projectRoot}get servers(){return this._servers}get entries(){return this._entries}get knownExtensions(){return new Set(this._lookup.extToLanguageId.keys())}languageId(e){let n=e.startsWith("ssh://")?decodeURIComponent(new URL(e).pathname):e;return(this._projectRoot.startsWith("ssh://")?this.candidates(n):this.resolve(n))[0]?.languageId??e.slice(1)}};function Io(t){if(typeof t!="object"||t===null||Array.isArray(t))throw new Error("LSP config must be an object");let e=t;if(e.version!==1)throw new Error("LSP config version must be 1");if(typeof e.servers!="object"||e.servers===null||Array.isArray(e.servers))throw new Error("LSP config servers must be an object");for(let[n,r]of Object.entries(e.servers)){if(typeof r!="object"||r===null||Array.isArray(r))throw new Error(`LSP server ${n} must be an object`);let s=r;if(!Array.isArray(s.command)||s.command.length===0||s.command.some(o=>typeof o!="string"||o.length===0))throw new Error(`LSP server ${n}.command must be a non-empty string array`);if(s.transport!==void 0&&s.transport!=="stdio")throw new Error(`LSP server ${n} only supports stdio transport`);if(!Array.isArray(s.rootMarkers)||s.rootMarkers.some(o=>typeof o!="string"))throw new Error(`LSP server ${n}.rootMarkers must be a string array`);if(s.requireRootMarker!==void 0&&typeof s.requireRootMarker!="boolean")throw new TypeError(`LSP server ${n}.requireRootMarker must be a boolean`);if(s.requireRootMarker&&s.rootMarkers.length===0)throw new Error(`LSP server ${n}.requireRootMarker requires rootMarkers`);if(typeof s.languages!="object"||s.languages===null||Array.isArray(s.languages))throw new Error(`LSP server ${n}.languages must be an object`);for(let[o,i]of Object.entries(s.languages)){let c=typeof i=="object"&&i!==null&&!Array.isArray(i)?i.extensions:void 0;if(!Array.isArray(c)||c.length===0||c.some(d=>typeof d!="string"))throw new Error(`LSP server ${n} language ${o} requires extensions`);let l=i.fileNames;if(l!==void 0&&(!Array.isArray(l)||l.some(d=>typeof d!="string"||d.length===0||/[/\\]/u.test(d))))throw new Error(`LSP server ${n} language ${o}.fileNames must contain basenames`)}if(!Array.isArray(s.capabilities))throw new TypeError(`LSP server ${n}.capabilities must be an array`)}return t}a(Io,"parseLspConfig");var Mr={protocol:Fn,apiVersion:Hn,id:"lsp",setup(t){for(let e of ve)t.addToolRecipe(e);t.addSetupCheck({id:"effective-config",inspect:To}),t.addCheck({id:"config",title:"LSP",async run(e){try{let n=await ie.fromPackageDir(e.cwd,Or(e)),r=ko(n,e.files);return r.length===0?[{status:"skip",message:"No language server matches the inspected project files"}]:await Promise.all(r.map(async s=>{let o=`${s.serverId} [${s.layer}] command ${JSON.stringify(s.config.command)}`,i=e.workspace,c=new ge({serverId:s.serverId,rootUri:i?e.cwd:Do.file(e.cwd).toString(),...i&&{ownerTransport:{start:a(l=>i.start(l.command,l.env,l.signal),"start"),toServerUri:a(l=>i.toNativeUri(l),"toServerUri"),fromServerUri:a(l=>i.fromNativeUri(l),"fromServerUri")}},command:s.config.command,env:Ao(e.env,s.config.env),...s.config.initializationOptions&&{initOptions:s.config.initializationOptions},...s.config.settings&&{settings:s.config.settings},...s.config.timeoutMs&&{timeoutMs:s.config.timeoutMs}});try{return await c.start(e.signal),{status:"pass",message:`${o}: initialized`,detail:s.sourcePath}}catch(l){return{status:"fail",message:`${o}: ${l instanceof Error?l.message:String(l)}`,detail:s.sourcePath}}finally{await c.shutdown()}}))}catch(n){return e.signal?.throwIfAborted(),[{status:"fail",message:n instanceof Error?n.message:String(n)}]}}})}};async function To(t){try{let e=await ie.fromPackageDir(t.cwd,Or(t)),n=[],r=new Map;for(let[s,o]of t.detectedLanguages){let i=o.flatMap(c=>e.resolve(c)).find(c=>c.languageId===s);i!==void 0&&(n.push({kind:"lsp",languageId:s,toolId:i.serverId}),await or(t,i.config)||r.set(i.serverId,{id:`lsp-${i.serverId}-unavailable`,message:`Configured language server ${i.serverId} cannot run ${JSON.stringify(i.config.command)}`}))}return{selections:n,actions:[...r.values()]}}catch(e){return t.signal?.throwIfAborted(),{actions:[{id:"lsp-config-invalid",message:`Language server configuration cannot load: ${e instanceof Error?e.message:String(e)}`}]}}}a(To,"inspectLspSetup");function Or(t){let e=t.workspace;return{...sr(t),recipeEvidence:e?n=>e.evidence(n,t.signal):void 0}}a(Or,"lspOptions");function ko(t,e){let n=new Map;for(let r of e){let s=t.resolve(r)[0];s!==void 0&&!n.has(s.serverId)&&n.set(s.serverId,s)}return[...n.values()]}a(ko,"applicableServers");function Ao(t,e){return Object.fromEntries(Object.entries({...t,...e}).filter(n=>n[1]!==void 0))}a(Ao,"definedEnvironment");var Mo={1:"File",2:"Module",3:"Namespace",4:"Package",5:"Class",6:"Method",7:"Property",8:"Field",9:"Constructor",10:"Enum",11:"Interface",12:"Function",13:"Variable",14:"Constant",15:"String",16:"Number",17:"Boolean",18:"Array",19:"Object",20:"Key",21:"Null",22:"EnumMember",23:"Struct",24:"Event",25:"Operator",26:"TypeParameter"};function Se(t){return Mo[t]??`SymbolKind(${t})`}a(Se,"symbolKindName");async function Ue(t,e,n){let r=t.documentVersion(e),s=await t.sendRequest("textDocument/documentSymbol",{textDocument:{uri:e}},n);if(t.documentVersion(e)!==r)throw O("The document changed while the server listed its symbols.");return s??[]}a(Ue,"requestDocumentSymbols");async function Tt(t,e,n=100,r){return(await t.sendRequest("workspace/symbol",{query:e},r)??[]).slice(0,n)}a(Tt,"requestWorkspaceSymbols");import{ResponseError as Oo}from"vscode-jsonrpc/node";async function kt(t,e,n,r,s){try{return await t.sendRequest("textDocument/rename",{textDocument:{uri:e},position:n,newName:r},s)}catch(o){throw o instanceof Oo&&/^Files? must be saved first: /u.test(o.message)?O("The language server text changed during rename."):o}}a(kt,"requestRename");import ze from"node:path";import{diffLines as Wo}from"diff";var No=/^[\p{L}\p{Nl}_$][\p{L}\p{N}\p{Mn}\p{Mc}\p{Pc}$]*$/u,At=/^fatal_too_many_errors$|too many errors emitted/iu,$o=new Set(["fatal_too_many_errors","module_not_found","module_not_built","module_build_disabled","module_shadowed","module_build_shadowed_submodule","module_cycle","module_prebuilt","module_rebuild_finalized","cannot_open_file","file_modified","sloc_space_too_large","unsupported_bom","module_format_unhandled","pp_file_not_found","pp_through_header_not_found","pp_through_header_not_seen","pp_pragma_hdrstop_not_seen","pp_error_opening_file","fe_error_backend","fe_linking_module","fe_invalid_code_complete_file","fe_remap_missing_to_file","fe_remap_missing_from_file","module_map_not_found","missing_module","modules_embed_file_not_found","module_header_file_not_found","missing_vfs_overlay_file","invalid_vfs_overlay","extract_api_ignores_file_not_found","fe_pch_malformed","fe_pch_malformed_block","fe_ast_file_modified","module_file_conflict","ast_file_not_found","ast_file_out_of_date","ast_file_invalid","module_file_not_module","module_file_missing_top_level_submodule","imported_module_modmap_changed","imported_module_relocated","function_scope_depth_exceeded","bracket_depth_exceeded"]);function jo(t,e){return $o.has(t.replace(/^err_/u,""))||At.test(e)}a(jo,"isFatalClangError");function Nr(t){return`${t.line}:${t.character}`}a(Nr,"positionKey");async function _e(t,e,n,r){let s=[...new Set(n.flatMap(i=>i.match(/[\p{L}\p{N}_$]+/gu)??[]))],o=[];for(let i of t){let{uri:c,start:l,text:d}=e(i);if(!No.test(d)||s.includes(d)){o.push(i);continue}let u=await r(c);u!==void 0&&(u.starts.has(Nr(l))||u.stopped&&s.some(f=>Uo(d,f)))||o.push(i)}return o}a(_e,"withoutCorrectedNames");function Uo(t,e){let n=Math.floor((t.length+2)/3);if(Math.abs(t.length-e.length)>n)return!1;let r=Array.from({length:e.length+1},(s,o)=>o);for(let s=1;s<=t.length;s++){let o=[s];for(let i=1;i<=e.length;i++)o[i]=Math.min((r[i]??0)+1,(o[i-1]??0)+1,(r[i-1]??0)+(t[s-1]===e[i-1]?0:1));r=o}return(r[e.length]??1/0)<=n}a(Uo,"withinTypoDistance");function ne(t,e){let n=[0];for(let i=t.indexOf(`
4
- `);i!==-1;i=t.indexOf(`
5
- `,i+1))n.push(i+1);let r=a(i=>{let c=n[i.line];return c===void 0?void 0:c+i.character},"offset"),s=r(e.start),o=r(e.end);return s===void 0||o===void 0||o<s?"":t.slice(s,o)}a(ne,"textInRange");function Le(t,e){let n=new Map,r=a(async s=>{try{let o=await t(s);if(!o)return;let{diagnostics:i}=await pe(o.client,o.uri,o.languageId,{...e&&{signal:e}}),c=i.filter(l=>l.severity==="error");return{starts:new Set(c.map(l=>Nr({line:l.line-1,character:l.column-1}))),stopped:c.some(l=>At.test(l.code)||At.test(l.message)),fatal:c.filter(l=>jo(l.code,l.message)).map(({line:l,message:d})=>({line:l,message:d}))}}catch(o){if(e?.throwIfAborted(),Pt(o))throw o;if(o instanceof Error)return;throw o}},"read");return s=>{let o=n.get(s);return o===void 0&&(o=r(s),n.set(s,o)),o}}a(Le,"diagnosticErrors");function st(t,e,n,r){let s=t.mapRange(e);return s!==void 0&&ne(n,s)===r?s:void 0}a(st,"followRange");var qo=500,ae=class t{constructor(e){this.runs=e}static{a(this,"LinePositionMap")}static between(e,n){if(e===n)return new t([[0,0,Number.MAX_SAFE_INTEGER]]);let r=Wo(e,n,{timeout:qo});if(r===void 0)return new t(void 0);let s=[],o=0,i=0;for(let c of r){let l=c.count;c.added?i+=l:c.removed?o+=l:(s.push([o,i,l]),o+=l,i+=l)}return new t(s)}mapRange(e){let n=this.runs?.find(([s,,o])=>e.start.line>=s&&e.end.line<s+o);if(n===void 0)return;let r=n[1]-n[0];return{start:{line:e.start.line+r,character:e.start.character},end:{line:e.end.line+r,character:e.end.character}}}};import{URI as ci}from"vscode-uri";import{createHash as Bo}from"node:crypto";import{readdir as Jo,stat as Fr}from"node:fs/promises";import le from"node:path";import{URI as ot}from"vscode-uri";async function Mt(t,e){if(!t.supportsCommand("typescript.tsserverRequest"))return;if((await t.sendRequest("workspace/executeCommand",{command:"typescript.tsserverRequest",arguments:["projectInfo",{file:e,needFileNameList:!0},{isAsync:!1,expectsResult:!0}]}))?.success!==!0)throw new Error("TypeScript could not load the project for a workspace query.")}a(Mt,"prepareProjectQuery");import{AsyncLocalStorage as Fo}from"node:async_hooks";var Ot=new Fo;async function re(t){if(Ot.getStore()!==void 0)return t();let e=new Map;try{return await Ot.run(e,t)}finally{for(let n of e.values())for(let r of n.values())r()}}a(re,"withLspDocuments");function $r(t,e){let n=Ot.getStore();if(n===void 0)return;let r=n.get(t)??new Map;n.set(t,r),r.has(e)||r.set(e,t.retainDocument(e))}a($r,"retainForCurrentOperation");import{execFile as Ho}from"node:child_process";import{existsSync as Go}from"node:fs";import Vo from"node:os";import Nt from"node:path";function jr(t,e){return["--files-with-matches","--fixed-strings","--word-regexp","--no-config","--no-messages","--path-separator=/",...e.flatMap(n=>["--glob",`*${n}`]),"--regexp",t,"--","."]}a(jr,"filesContainingArguments");function Ur(t){return t.split(`
6
- `).map(e=>e.replace(/\r$/u,"").replace(/^\.\//u,"")).filter(e=>e.length>0)}a(Ur,"filesContainingOutput");function zo(){let t=process.env.PI_CODING_AGENT_DIR??Nt.join(Vo.homedir(),".pi","agent"),e=Nt.join(t,"bin",process.platform==="win32"?"rg.exe":"rg");return Go(e)?e:"rg"}a(zo,"ripgrep");function Wr(t,e,n,r){return new Promise((s,o)=>{Ho(zo(),[...jr(e,n)],{cwd:t,maxBuffer:64*1024*1024,...r&&{signal:r}},(i,c,l)=>{if(i&&i.code!==1){o(r?.aborted?r.reason:new Error(`Listing files that contain ${e} failed: ${l||i.message}`));return}s(Ur(c).map(d=>Nt.join(t,d)))})})}a(Wr,"localFilesContaining");function qr(t,e){let n=a(r=>typeof r=="string"?r.replaceAll("{project}",()=>e):Array.isArray(r)?r.map(n):r!==null&&typeof r=="object"?Object.fromEntries(Object.entries(r).map(([s,o])=>[s,n(o)])):r,"expand");return Object.fromEntries(Object.entries(t).map(([r,s])=>[r,n(s)]))}a(qr,"resolveInitializationOptions");var fe=class t{constructor(e,n,r={}){this._registry=e;this._owner=n;this._options=r}static{a(this,"LspManager")}_clients=new Map;_clientStarts=new Map;_pushUnsubscribers=new Map;_pushHandlers=new Set;_pushFingerprints=new Map;_disposed=!1;static _instance=null;static getInstance(){if(!t._instance)throw new Error("[lsp] LspManager not initialized");return t._instance}static getInstanceOrNull(){return t._instance}static init(e,n,r={}){let s=t._instance;return s?._disposed?(s._registry=e,s._owner=n,s._options=r,s._disposed=!1,s):(t._instance=new t(e,n,r),t._instance)}static async resetForTest(){t._instance&&(await t._instance.shutdownAll(),t._instance=null)}requireOwner(){if(!this._owner)throw Object.assign(new Error("No language server workspace owner"),{code:"UNSUPPORTED_SOURCE"});return this._owner}get workspaceRoot(){return this._registry.projectRoot}get clientCount(){return this._clients.size}onPushDiagnostics(e){return this._pushHandlers.add(e),()=>this._pushHandlers.delete(e)}async getOrStart(e,n,r,s){if(s?.throwIfAborted(),this._disposed)return null;let o=n.startsWith("ssh://"),i=o?this.requireOwner():void 0,c=i?await this._registry.resolveOwned(e,w=>i.exists(w,s)):this._registry.resolve(e);if(s?.throwIfAborted(),this._disposed)return null;let l=r==="symbols"?c[0]:c.find(w=>w.config.capabilities.includes(r));if(!l)return null;let d=o?n:ot.file(n).toString(),u=`${l.serverId}:${d}`,p=this._clientStarts.get(u);if(p)return p.controller.signal.aborted?(await ee(p.promise.catch(()=>{}),s),this.getOrStart(e,n,r,s)):p.wait(s);let f=this._clients.get(u);if(f?.ready)return f.touch(),f;let y=new be(w=>this._startClient(u,d,l,f,w));this._clientStarts.set(u,y);let S=a(()=>{this._clientStarts.get(u)===y&&this._clientStarts.delete(u)},"settled");y.promise.then(S,S);let h=await y.wait(s);return h.touch(),h}_stopIdleClient(e,n){if(this._clients.get(e)===n){this._clients.delete(e),this._pushUnsubscribers.get(e)?.(),this._pushUnsubscribers.delete(e);for(let r of this._pushFingerprints.keys())r.startsWith(`${e}:`)&&this._pushFingerprints.delete(r)}n.shutdown().catch(r=>{console.error(`[lsp] ${n.serverId}: idle shutdown failed:`,r)})}async _startClient(e,n,r,s,o){let i=s??new ge({serverId:r.serverId,rootUri:n,command:r.config.command,...n.startsWith("ssh://")&&this._owner&&{ownerTransport:this._owner.transport(n)},...!n.startsWith("ssh://")&&this._options.sharedServers&&{sharedServers:this._options.sharedServers},...r.config.env&&{env:r.config.env},...r.config.initializationOptions&&{initOptions:qr(r.config.initializationOptions,n.startsWith("ssh://")?decodeURIComponent(new URL(n).pathname):ot.parse(n).fsPath)},...r.config.settings&&{settings:r.config.settings},...r.config.timeoutMs&&{timeoutMs:r.config.timeoutMs},...this._options.idleTimeoutMs!==void 0&&{idleTimeoutMs:this._options.idleTimeoutMs,onIdle:a(()=>this._stopIdleClient(e,i),"onIdle")}});try{s?await s.restart(o):await i.start(o),o.throwIfAborted()}catch(c){try{await i.shutdown()}catch(l){if(l!==c)throw new AggregateError([c,l],"Language server startup and cleanup failed",{cause:l})}throw c}if(this._disposed)throw await i.shutdown(),new Error(`[lsp] ${r.serverId}: manager disposed during startup`);return this._clients.set(e,i),this._subscribeToPushDiagnostics(e,i),i}async isSourceFile(e,n,r){if(r?.throwIfAborted(),n.startsWith("ssh://")){if(this._owner===void 0)throw new Error("No language server workspace owner");return this._owner.isFile(X(e,n),r)}let s=await Fr(le.resolve(n,e));return r?.throwIfAborted(),s.isFile()}async filesContaining(e,n,r,s){s?.throwIfAborted();let o=[...this._registry.knownExtensions].filter(i=>r.has(this._registry.languageId(i)));return o.length===0?[]:e.rootUri.startsWith("ssh://")?this.requireOwner().filesContaining?.(e.rootUri,n,o,s):Wr(ot.parse(e.rootUri).fsPath,n,o,s)}async getWorkspaceClients(e,n="symbols",r=e,s=()=>!0,o,i){if(o?.throwIfAborted(),e.startsWith("ssh://")){let f=this._owner;if(!f)throw Object.assign(new Error("No language server workspace owner"),{code:"UNSUPPORTED_SOURCE"});let y=new Set,S=new Set(this._registry.knownExtensions),h=new Set([".git",".cache","node_modules","dist","build"]),w=a(async L=>{if(o?.throwIfAborted(),S.size!==0)for(let T of await f.entries(L,o)){o?.throwIfAborted();let k=X(T.name,`${L}/`);if(T.kind==="directory")h.has(T.name)||await w(k);else if(T.kind==="file"){let M=le.posix.extname(T.name).toLowerCase();if(!S.has(M)||!s(k))continue;let g=await this.openFile(k,e,n,o,i);g&&(y.add(g.client),S.delete(M))}}},"visit"),b=X(r,e);if(await f.isFile(b,o)){if(!s(b))return[];let L=await this.openFile(b,e,n,o,i);return L?[L.client]:[]}return await w(b),[...y]}let c=new Set,l=new Set(this._registry.knownExtensions),d=new Set([".git",".cache","node_modules","dist","build"]),u=a(async f=>{if(o?.throwIfAborted(),l.size===0)return;let y;try{y=await Jo(f,{withFileTypes:!0})}catch{return}for(let S of y){if(o?.throwIfAborted(),l.size===0)return;if(S.isDirectory()){d.has(S.name)||await u(le.join(f,S.name));continue}if(!S.isFile())continue;let h=le.extname(S.name).toLowerCase();if(!l.has(h))continue;let w=le.join(f,S.name);if(!s(w))continue;let b=await this.openFile(w,e,n,o,i);b&&(l.delete(h),b.client.hasWorkspaceSymbolCapability&&(await Mt(b.client,w),c.add(b.client)))}},"visit"),p=le.resolve(e,r);if((await Fr(p)).isFile()){if(!s(p))return[];let f=await this.openFile(p,e,n,o,i);return f===null||!f.client.hasWorkspaceSymbolCapability?[]:(await Mt(f.client,p),[f.client])}return await u(p),o?.throwIfAborted(),[...c]}async prepareWorkspaceSymbols(e,n=e,r,s,o){return this.getWorkspaceClients(e,"symbols",n,r,s,o)}hasServerFor(e){return this._registry.resolve(e).length>0}languageId(e){return this._registry.languageId(e)}syncEditedSource(e,n){for(let r of this._clients.values()){if(!r.ready)continue;let s=r.toUri(e);if(r.documentContent(s)===void 0)continue;let o=this.languageId(le.extname(decodeURIComponent(new URL(s).pathname)));r.syncDocument(s,n,o,!0)}}async readSourceSnapshot(e,n){if(n?.throwIfAborted(),e.startsWith("ssh://"))return this.requireOwner().readSnapshot(e,n);if(e.includes("://"))throw Object.assign(new Error("Unsupported rename source"),{code:"UNSUPPORTED_SOURCE"});let r=await mn(e,()=>this.readSourceText(e,n),(s,o)=>s===o,this._options.fileGeneration);if(r===void 0)throw O("A rename source changed while reading it. No edits applied.");return{content:r.value,version:Bo("sha256").update(r.stamp).update("\0").update(r.value).digest("hex")}}async readSourceBytes(e,n){if(n?.throwIfAborted(),e.startsWith("ssh://"))return this.requireOwner().readBytes(e,n);if(e.includes("://"))throw Object.assign(new Error("Unsupported declaration source"),{code:"UNSUPPORTED_SOURCE"});let{readFile:r}=await import("node:fs/promises");return r(e,{signal:n})}async readSourceText(e,n){if(n?.throwIfAborted(),e.startsWith("ssh://"))return this.requireOwner().readText(e,n);if(e.includes("://"))throw Object.assign(new Error("Unsupported declaration source"),{code:"UNSUPPORTED_SOURCE"});let{readFile:r}=await import("node:fs/promises");return r(e,{encoding:"utf8",signal:n})}async openFile(e,n,r="diagnostics",s,o){if(s?.throwIfAborted(),e.startsWith("ssh://")&&!n.startsWith("ssh://")){if(!this._registry.projectRoot.startsWith("ssh://"))throw Object.assign(new Error("Remote document has no workspace owner"),{code:"UNSUPPORTED_SOURCE"});n=this._registry.projectRoot}let i=n.startsWith("ssh://"),c=i?X(e,n):le.resolve(n,e),l=await this.getOrStart(c,n,r,s);if(!l)return null;let d=l.toUri(c);$r(l,d);let u=i?this.requireOwner():void 0,f=(u?await this._registry.resolveOwned(c,y=>u.exists(y,s)):this._registry.resolve(c))[0]?.languageId??"plaintext";if(u){let y=o?await o(c):await u.readText(d,s);return s?.throwIfAborted(),l.syncDocument(d,y,f),await l.waitUntilLoaded(s),{client:l,uri:d,languageId:f}}try{let{readFile:y}=await import("node:fs/promises"),S=o?await o(c):await y(c,{encoding:"utf8",signal:s});s?.throwIfAborted(),l.syncDocument(d,S,f)}catch(y){if(s?.throwIfAborted(),!(y instanceof Error&&"code"in y&&y.code==="ENOENT"))throw y}return await l.waitUntilLoaded(s),{client:l,uri:d,languageId:f}}_subscribeToPushDiagnostics(e,n){if(this._pushUnsubscribers.has(e))return;let r=n.onNotification("textDocument/publishDiagnostics",s=>{let o=Xo(s);if(!o||n.hasActiveDiagnosticRequest(o.uri))return;let i=n.documentVersion(o.uri);if(o.version!==void 0&&i!==void 0&&o.version<i)return;let c=`${e}:${o.uri}`,l=o.diagnostics.map(xt),d=JSON.stringify([o.version,i,l]);if(this._pushFingerprints.get(c)===d)return;this._pushFingerprints.set(c,d);let u={cwd:n.rootUri.startsWith("ssh://")?n.rootUri:ot.parse(n.rootUri).fsPath,serverId:n.serverId,uri:o.uri,diagnostics:l,...o.version!==void 0&&{version:o.version}};for(let p of this._pushHandlers)p(u)});this._pushUnsubscribers.set(e,r)}async shutdownAll(){this._disposed=!0;let e=[...this._clientStarts.values()];for(let i of e)i.controller.abort(new Error("Language server manager stopped"));let n=await Promise.allSettled(e.map(i=>i.promise)),r=[];for(let[i,c]of n.entries())c.status==="rejected"&&c.reason!==e[i]?.controller.signal.reason&&r.push(c.reason);let s=[...this._clients.values()],o=await Promise.allSettled(s.map(i=>i.shutdown()));for(let i of this._pushUnsubscribers.values())i();this._pushUnsubscribers.clear(),this._clientStarts.clear(),this._pushFingerprints.clear(),this._pushHandlers.clear(),this._clients.clear();for(let i of o)i.status==="rejected"&&r.push(i.reason);if(r.length>0)throw new AggregateError(r,"Language server cleanup failed")}dispose(){return this.shutdownAll()}};function Xo(t){if(t===null||typeof t!="object")return;let e=t;if(!(typeof e.uri!="string"||!Array.isArray(e.diagnostics)))return{uri:e.uri,diagnostics:e.diagnostics,...typeof e.version=="number"&&{version:e.version}}}a(Xo,"parsePushNotification");async function jt(t,e){let n=new AbortController,r=t?AbortSignal.any([t,n.signal]):n.signal,s=setTimeout(()=>{n.abort(Object.assign(new Error(`LSP search timed out after ${mt/1e3} s. Retry or search the text.`),{code:"LSP_NAVIGATION_TIMEOUT"}))},mt);try{r.throwIfAborted();let o=await e(r);return r.throwIfAborted(),o}catch(o){throw r.throwIfAborted(),o}finally{clearTimeout(s)}}a(jt,"withNavigationDeadline");async function $t(t){try{return await t}catch(e){if(Ye(e))return;throw e}}a($t,"unlessUnsupported");async function Ut(t,e,n){if(n?.throwIfAborted(),!t.supportsCommand("typescript.tsserverRequest"))return;let r=await t.sendRequest("workspace/executeCommand",{command:"typescript.tsserverRequest",arguments:["projectInfo",{file:t.serverDocumentPath(e),needFileNameList:!0},{isAsync:!1,expectsResult:!0}]},n);if(n?.throwIfAborted(),r?.success!==!0)throw new Error("TypeScript could not load the project for the workspace query.")}a(Ut,"loadQueryProject");async function We(t,e,n,r){return await Ut(t,e,r),await t.sendRequest("textDocument/references",{textDocument:{uri:e},position:n,context:{includeDeclaration:!0}},r)??[]}a(We,"requestReferences");function it(t,e){if(e.length===0)throw O(`The language server returned no locations for "${t}", including its known declaration. Retry or search the text.`)}a(it,"requireReferenceReply");async function Wt(t,e,n,r){let s=await $t(t.sendRequest("textDocument/prepareCallHierarchy",{textDocument:{uri:e},position:n},r));if(s===void 0)return{items:[],incoming:[],outgoing:[],unsupported:["incoming","outgoing"]};let o=s?.[0];if(!o)return{items:[],incoming:[],outgoing:[],unsupported:[]};let[i,c]=await Promise.all([$t(t.sendRequest("callHierarchy/incomingCalls",{item:o},r)),$t(t.sendRequest("callHierarchy/outgoingCalls",{item:o},r))]);return{items:s,incoming:i??[],outgoing:c??[],unsupported:[...i===void 0?["incoming"]:[],...c===void 0?["outgoing"]:[]]}}a(Wt,"requestCallHierarchy");function Re(t){if(/\r(?!\n)/u.test(t))throw Object.assign(new Error("This file holds a carriage return that is not followed by a line feed. Language servers disagree about the line it ends, so its LSP positions cannot select exact text. Use text search for this file."),{code:"LSP_AMBIGUOUS_LINE_BREAK"})}a(Re,"assertLspLines");function qe(t,e,n){Re(e.content);let{start:r,end:s}=n;for(let l of[r,s]){let d=e.lines[l.line];if(!Number.isInteger(l.line)||!Number.isInteger(l.character)||d===void 0||l.character<0||l.character>d.content.length-(d.content.endsWith("\r")?1:0))throw O("LSP range does not match its source snapshot.")}let o=a(l=>e.lines.slice(0,l).reduce((d,u)=>d+u.content.length+u.lineEnding.length,0),"offset"),i=o(r.line)+r.character,c=o(s.line)+s.character;if(c<i)throw new Error("LSP returned a reversed source range.");return{source:t,lineNumber:r.line+1,endLineNumber:s.line+1,startColumn:r.character,endColumn:s.character,matchedText:e.content.slice(i,c),lineText:F(e.lines[r.line]).content}}a(qe,"lspRangeMatch");var de=new Set(["c","cpp","objective-c","objective-cpp"]),Ko=32;function Qo(t){return t.match(/[\p{L}\p{N}_$]+/gu)?.at(-1)}a(Qo,"searchedWord");function Pe(t){let{manager:e,cwd:n,errorsOf:r,signal:s}=t,o=new Map,i=0,c=a(async(l,d)=>{let u=await e.filesContaining(l,d,de,s);if(u===void 0)return{client:l,opened:[],unopened:[],unlisted:!0};let p=[],f=[];for(let y of[...new Set(u)].sort()){if(s?.throwIfAborted(),t.accepts!==void 0&&!t.accepts(y))continue;let S=l.toUri(y);if(l.documentContent(S)===void 0){if(i>=Ko){f.push(y);continue}if(i+=1,(await e.openFile(y,n,"symbols",s))?.client!==l){f.push(y);continue}}p.push(S)}return await Promise.all(p.map(y=>r(y))),{client:l,opened:p,unopened:f,unlisted:!1}},"reach");return async(l,d,u)=>{if(!de.has(d))return;let p=Qo(u);if(p===void 0)return{client:l,opened:[],unopened:[],unlisted:!1};let f=JSON.stringify([l.serverId,l.rootUri,p]),y=o.get(f);return y===void 0&&(y=c(l,p),o.set(f,y)),y}}a(Pe,"createClangReach");async function xe(t,e,n,r){let s=[...new Set([...e,...t.opened])].filter(i=>t.client.documentContent(i)!==void 0),o=await Promise.all(s.map(i=>n(i)));return{fatal:s.flatMap((i,c)=>(o[c]?.fatal??[]).map(l=>({source:r(i),...l}))),unopened:t.unopened,missingDiagnostics:s.flatMap((i,c)=>o[c]===void 0?[r(i)]:[]),unlisted:t.unlisted}}a(xe,"clangCoverage");function Ee(t){return t===void 0||t.fatal.length===0&&t.unopened.length===0&&t.missingDiagnostics.length===0&&!t.unlisted}a(Ee,"coverageComplete");function Ie(t){let e=t.filter(r=>r!==void 0);if(e.length===0)return;let n=new Map;for(let r of e.flatMap(s=>s.fatal))n.set(JSON.stringify([r.source,r.line,r.message]),r);return{fatal:[...n.values()],unopened:[...new Set(e.flatMap(r=>r.unopened))].sort(),missingDiagnostics:[...new Set(e.flatMap(r=>r.missingDiagnostics))].sort(),unlisted:e.some(r=>r.unlisted)}}a(Ie,"mergeCoverage");function De(t,e){if(t===void 0)return[];let n=[];if(t.fatal.length>0){let r=t.fatal.map(o=>`${e(o.source)}:${o.line} ${o.message}`).join("; "),s=e(F(t.fatal[0]).source);n.push(`Incomplete: clang stopped with a fatal error (${r}), so references after it can be missing. Fix it (diagnostics with path ${s}) and search again, or search the text.`)}return t.unopened.length>0&&n.push(`Incomplete: the name scan found these files, but the server did not check them: ${Ce(t.unopened,e)}. Search those files for references.`),t.missingDiagnostics.length>0&&n.push(`Incomplete: the server did not provide diagnostics for ${Ce(t.missingDiagnostics,e)}. The reference list may be incomplete.`),t.unlisted&&n.push("Incomplete: files that contain the name could not be listed, so references from files the server has not opened can be missing. Search the text."),n}a(De,"coverageNotes");function Ce(t,e){let r=t.slice(0,8).map(e).join(", ");return t.length>8?`${r} (and ${t.length-8} more)`:r}a(Ce,"displayFiles");function Hr(t,e){if(Ee(t)||t===void 0)return;let n=[];if(t.fatal.length>0){let r=t.fatal.map(s=>`${e(s.source)}:${s.line} ${s.message}`).join("; ");n.push(`clang stopped with a fatal error (${r}), so places after it can be missing from the rename. Fix it (diagnostics with path ${e(F(t.fatal[0]).source)}) and rename again.`)}return t.unopened.length>0&&n.push(`The server did not check these files: ${Ce(t.unopened,e)}.`),t.missingDiagnostics.length>0&&n.push(`The server did not provide diagnostics for ${Ce(t.missingDiagnostics,e)}.`),t.unlisted&&n.push("Files that contain the name could not be listed, so the rename can miss files the server has not opened."),`LSP rename refused; no edits applied. ${n.join(" ")} Or replace the text instead.`}a(Hr,"renameRefusal");function Fe(t){let e=t?.code;return e==="ENOENT"||e==="ENOTDIR"}a(Fe,"isMissingSource");function Te(t,e){return t.length===0?[]:[`Skipped places in deleted files that the server still indexes: ${Ce(t,e)}.`]}a(Te,"missingSourcesNotes");var qt="(<[{",Gr=")>]}";function Ge(t,e=[]){let n=t.map(s=>({symbol:s,selectionRange:s.selectionRange??s.range})).filter(s=>s.selectionRange!==void 0),r=new Map;for(let{symbol:s,selectionRange:o}of n){let i=r.get(s.name)??new Set;i.add(Br(s,o)),r.set(s.name,i)}return n.map(({symbol:s,selectionRange:o})=>{let c=(r.get(s.name)?.size??0)>1?ti(s.name,s.detail)??s.name:s.name,l=[...e,c];return{name:s.name,kind:s.kind,...s.detail!==void 0&&s.detail!==""&&{detail:s.detail},range:s.range??o,selectionRange:o,selector:l,children:Ge(s.children??[],l)}}).sort(si)}a(Ge,"normalizeDocumentSymbols");function Gt(t,e,n){if(e.length===0)throw new TypeError("A symbol selector must contain at least one segment.");let r=t,s=[];for(let[o,i]of e.entries()){if(s=e.length===1?Zo(t,i):ei(r,i),s.length===0)throw ai(t,e,n);let c=zt(s);if(c.length>1)throw ii(c,e,o,n);r=s.flatMap(l=>l.children)}return s}a(Gt,"resolveSymbolDeclaration");function Yo(t,e){let[n]=t;if(n!==void 0&&t.length===1)return n;let r=t.filter(s=>ne(e,s.range).trimEnd().endsWith("}"));return r.length===1?r[0]:void 0}a(Yo,"bodyEntry");function Ve(t,e){return(e===void 0?void 0:Yo(t,e))??F(t[0])}a(Ve,"preferredDeclaration");function Vt(t,e){let n=a(r=>r.flatMap(s=>[...s.name===e?[s]:[],...n(s.children)]),"named");return zt(n(t))}a(Vt,"declarationsNamed");function Vr(t,e){let n=a(o=>o.flatMap(i=>[i,...n(i.children)]),"all"),r=n(t),s=r.find(o=>oi(o.selectionRange,e));if(s!==void 0)return zt(r.filter(o=>o.name===s.name)).find(o=>o.includes(s))}a(Vr,"declarationAt");function Zo(t,e){let n=[],r=[],s=[],o=a(i=>{for(let c of i){let l=zr(c,e);l==="named"?n.push(c):l==="exact"?r.push(c):l==="loose"&&s.push(c),o(c.children)}},"visit");return o(t),n.length>0?n:r.length>0?r:s}a(Zo,"matchAtAnyDepth");function ei(t,e){let n=t.map(r=>({symbol:r,grade:zr(r,e)}));for(let r of["named","exact","loose"]){let s=n.filter(o=>o.grade===r).map(o=>o.symbol);if(s.length>0)return s}return[]}a(ei,"matchSegment");function zr(t,e){if(t.name===e)return"named";if(!e.startsWith(t.name))return;let n=e.slice(t.name.length).trimStart();if(!n.startsWith("("))return;let r=Xr(n),s=t.detail===void 0?void 0:Jr(t.detail);if(!(r===void 0||s===void 0)&&r.parameters.length===s.parameters.length){if(r.qualifiers===s.qualifiers&&r.parameters.every((o,i)=>o===s.parameters[i]))return"exact";if(!(r.qualifiers!==""&&r.qualifiers!==s.qualifiers))return r.parameters.every((o,i)=>{let c=s.parameters[i];return o===c||ri(o)===c})?"loose":void 0}}a(zr,"segmentGrade");function zt(t){let e=new Map;for(let n of t){let r=JSON.stringify([n.selector.slice(0,-1),n.name,Br(n,n.selectionRange)]),s=e.get(r)??[];s.push(n),e.set(r,s)}return[...e.values()]}a(zt,"groupDeclarations");function Br(t,e){let n=t.detail?.trim().replace(/\s+/gu," ")??"";return JSON.stringify(n===""?[t.kind,e.start.line,e.start.character]:[t.kind,n])}a(Br,"declarationKey");function ti(t,e){let n=e===void 0?void 0:Jr(e);if(n===void 0)return;let r=n.qualifiers===""?"":` ${n.qualifiers}`;return`${t}(${n.parameters.join(", ")})${r}`}a(ti,"signatureSegment");function Jr(t){let e;for(let n=0;n<t.length;n+=1){if(t[n]!=="("){let s=Ft(t,n);s!==void 0&&(n=s);continue}e=n;let r=Ft(t,n);if(r===void 0)return;n=r}return e===void 0?void 0:Xr(t.slice(e))}a(Jr,"detailSignature");function Xr(t){let e=Ft(t,0);if(e===void 0)return;let n=t.slice(1,e),r=ni(n).map(Ht);return{parameters:r.length===1&&(r[0]===""||r[0]==="void")||r.length===0?[]:r,qualifiers:Ht(t.slice(e+1))}}a(Xr,"parseSignature");function Ft(t,e){if(!qt.includes(t[e]??""))return;let n=0;for(let r=e;r<t.length;r+=1){let s=t[r]??"";if(qt.includes(s))n+=1;else if(Gr.includes(s)&&(n-=1,n===0))return r}}a(Ft,"matchingClose");function ni(t){let e=[],n=0,r=0;for(let s=0;s<t.length;s+=1){let o=t[s]??"";qt.includes(o)?n+=1:Gr.includes(o)?n-=1:o===","&&n===0&&(e.push(t.slice(r,s)),r=s+1)}return e.push(t.slice(r)),e}a(ni,"splitTopLevel");function Ht(t){return t.trim().replace(/\s+/gu," ").replace(/\s*([&*,<>()[\]:])\s*/gu,"$1")}a(Ht,"normalizeType");function ri(t){let e=t.replace(/=.*$/u,"").trim(),n=/^(.*?[\s&*>\]])[\p{L}_][\p{L}\p{N}_]*$/u.exec(e);return n?.[1]===void 0?e:Ht(n[1])}a(ri,"withoutParameterName");function si(t,e){return t.range.start.line-e.range.start.line||t.range.start.character-e.range.start.character||t.name.localeCompare(e.name)}a(si,"compareSymbols");function oi(t,e){return t.start.line===e.start.line&&t.start.character===e.start.character&&t.end.line===e.end.line&&t.end.character===e.end.character}a(oi,"sameRange");function Kr(t,e){let[n]=t;if(n===void 0)return e;let r=t.map(s=>s.selectionRange.start.line+1).join(", ");return`${e}#${Z(n.selector)} (line ${r})`}a(Kr,"describeDeclaration");function ii(t,e,n,r){let s=t.slice(0,10).map(d=>Kr(d,r)),o=t.length>s.length?`, ${t.length-s.length} more`:"",i=new Set(t.map(d=>Z(d[0]?.selector??[]))),c=e.length>1?` at "${e[n]??""}"`:"",l=i.size===t.length?"Use one of these selectors.":"The language server reports no signatures that tell them apart.";return new Error(`Symbol selector "${Z(e)}"${c} matches ${t.length} declarations in ${r}: ${s.join(", ")}${o}. ${l}`)}a(ii,"ambiguousSelector");var He=class extends Error{static{a(this,"SymbolNotFoundError")}};function ai(t,e,n){let r=e.at(-1)??"",s=/^[^(]+/u.exec(r)?.[0].trim()??r,i=(s===r?[]:Vt(t,s)).slice(0,10).map(c=>Kr(c,n));return new He(`Symbol "${Z(e)}" was not found in ${n}.${i.length>0?` Declarations named "${s}": ${i.join(", ")}.`:""}`)}a(ai,"symbolNotFound");function oe(t,e,n){let r=e.startsWith("ssh://"),s=r?ze.posix:ze,o=a(d=>r?decodeURIComponent(new URL(X(d,e)).pathname):d,"native"),i=a(d=>{let u=r?o(d??e):ze.resolve(e,d??"."),p=s.relative(u,o(t));return!(p===".."||p.startsWith(`..${s.sep}`)||s.isAbsolute(p))},"inside");if(!(n.paths??[n.path]).some(i))return!1;let c=s.relative(o(e),o(t)).split(s.sep).join("/"),l=a(d=>Wn(d).some(u=>s.matchesGlob(u.includes("/")?c:s.basename(o(t)),u)),"matches");return(n.include===void 0||l(n.include))&&(n.exclude===void 0||!l(n.exclude))}a(oe,"withinScope");function se(t,e){let n=X(t,e);if(n.startsWith("ssh://"))return n;let r=ci.parse(n);if(r.scheme!=="file")throw new Error("Unsupported LSP source location.");return ze.resolve(r.fsPath)}a(se,"sourceOf");async function Bt(t,e,n,r,s={},o=fe.getInstance()){return te(()=>li(t,e,n,r,s,o),r)}a(Bt,"searchSymbols");async function li(t,e,n,r,s,o){r?.throwIfAborted();let i=s.resultScope;if(i?.targets.length===0)return{hits:[],contents:new Map,complete:i.complete};if(i===void 0&&s.path!==void 0&&!oe(e.startsWith("ssh://")?X(s.path,e):ze.resolve(e,s.path),e,s)&&await o.isSourceFile(s.path,e,r))return{hits:[],contents:new Map,complete:!0};let c=new Map,l=new Map,d=a(v=>{let R=l.get(v);return R===void 0&&(R=o.readSourceSnapshot(v,r).then(({content:_,version:$})=>{let D={document:Me(v,_),version:$};return c.set(v,D),D}),l.set(v,R)),R},"snapshotOf"),u=a(async v=>(await d(se(v,e))).document.content,"readText"),p=i?.targets.map(v=>v.source)??s.paths??[s.path??e],f=new Set((await Promise.all(p.map(v=>o.prepareWorkspaceSymbols(e,v,R=>oe(R,e,s),r,u)))).flat());if(f.size===0)throw new Error("LSP symbol search is unavailable: no provider supports workspace/symbol in this scope.");let y=new Map,S=new Map,h=a((v,R,_,$)=>{let D=S.get(v);return(D===void 0||D.served!==R)&&(D={served:R},S.set(v,D)),D[$]??=$==="toSnapshot"?ae.between(R,_):ae.between(_,R)},"lineDiff"),w=a(async(v,R)=>{r?.throwIfAborted();let _=se(v.uri,e),{document:$}=await d(_);i!==void 0&&!y.has(_)&&y.set(_,wn({targets:i.targets.filter(Je=>Je.source===_),complete:i.complete},new Map([[_,$.content]])));let D=R?.documentContent(v.uri),Q=D===void 0||D===$.content?v.range:h(_,D,$.content,"toSnapshot").mapRange(v.range);if(Q===void 0)throw O("LSP range does not match its source snapshot.");return qe(_,$,Q)},"toMatch"),b=a((v,R,_)=>{let $={line:_.lineNumber-1,character:_.startColumn},D=v.documentContent(R),Q=c.get(_.source)?.document.content;if(D===void 0||Q===void 0||D===Q)return $;let Je={start:$,end:{line:(_.endLineNumber??_.lineNumber)-1,character:_.endColumn}},Ae=st(h(_.source,D,Q,"toServed"),Je,D,_.matchedText);if(Ae===void 0)throw O(`The line of declaration "${_.matchedText}" changed before the server was asked for its references.`);return Ae.start},"servedPosition"),L=a(v=>oe(v.source,e,s)&&(i===void 0||Un(F(y.get(v.source)),v)),"included"),T=[],k=new Set,M=Le(v=>o.openFile(se(v,e),e,"symbols",r,u),r),g=a(v=>s.navigation==="references"?oe(v,e,{}):oe(v,e,s)&&(i===void 0||i.targets.some(R=>R.source===v)),"listable"),C=Pe({manager:o,cwd:e,errorsOf:M,accepts:g,...r&&{signal:r}}),E=new Set,m=a(async v=>{try{return await d(v),!0}catch(R){if(!Fe(R))throw R;return g(v)&&E.add(v),!1}},"exists"),P=[],I=new Set,A=new Map,x=a((v,R)=>{let _=A.get(R);return _===void 0&&(_=Ue(v,R,r).then(Ge),A.set(R,_)),_},"outlineOf");for(let v of f){r?.throwIfAborted();let R=await Tt(v,t,Number.MAX_SAFE_INTEGER,r);for(let _ of R){if(r?.throwIfAborted(),!oe(se(_.location.uri,e),e,{})||!await m(se(_.location.uri,e)))continue;let $=await w(_.location,v).catch(me=>{if(me?.code!=="SOURCE_CHANGED")throw me}),D=await o.openFile(se(_.location.uri,e),e,"symbols",r,u);if(D===null)throw new Error("LSP references are unavailable for a discovered declaration.");let Q=await x(D.client,D.uri),Ae=$?.matchedText===_.name?[Vr(Q,_.location.range)]:Vt(Q,_.name);if(Ae.length===0)throw O(`LSP declaration "${_.name}" is not among the current symbols of its file.`);for(let me of Ae){r?.throwIfAborted();let he=me===void 0?void 0:Ve(me,D.client.documentContent(D.uri)??await o.readSourceText(se(D.uri,e),r)),an=he===void 0?_.location:{uri:D.uri,range:he.selectionRange},cn=JSON.stringify([D.uri,(me?.[0]?.selectionRange??_.location.range).start]);if(I.has(cn))continue;I.add(cn);let z=await w(an,D.client),ye={id:JSON.stringify([v.serverId,z.source,an.range]),name:he?.name??_.name,kind:String(he?.kind??_.kind),...he!==void 0&&{selector:he.selector},source:z.source,range:{startLine:z.lineNumber,startColumn:z.startColumn,endLine:z.endLineNumber??z.lineNumber,endColumn:z.endColumn}},pt=await C(D.client,D.languageId,ye.name),ws=D.client.documentContent(D.uri),vs=b(D.client,D.uri,z),ln=await We(D.client,D.uri,vs,r);if(D.client.documentContent(D.uri)!==ws)throw O("The server's text changed while it answered a references request.");r?.throwIfAborted(),pt!==void 0&&it(ye.name,ln);let gt=[{...z,role:"definition",symbol:ye}],ft=[];for(let q of ln){if(!oe(se(q.uri,e),e,{})||!await m(se(q.uri,e)))continue;let Y=await w(q,D.client);Y.source===z.source&&Y.lineNumber===z.lineNumber&&Y.startColumn===z.startColumn&&Y.endLineNumber===z.endLineNumber&&Y.endColumn===z.endColumn||ft.push({location:q,reference:Y})}let bs=await _e(ft,({location:q,reference:Y})=>({uri:q.uri,start:q.range.start,text:Y.matchedText}),[ye.name,z.matchedText],M);for(let{reference:q}of bs)gt.push({...q,role:"reference",symbol:ye});if(gt.some(L)){pt!==void 0&&P.push(await xe(pt,[D.uri,...ft.map(({location:q})=>q.uri)],M,q=>se(q,e)));for(let q of gt){if(s.navigation!=="references"&&!L(q)||s.navigation==="references"&&!oe(q.source,e,{}))continue;let Y=JSON.stringify([ye.id,q.source,q.lineNumber,q.startColumn,q.endLineNumber,q.endColumn]);k.has(Y)||(k.add(Y),T.push(q))}}}}}r?.throwIfAborted();let j=new Map,W=new Map;for(let v of new Set(T.map(R=>R.source))){let R=F(c.get(v)),_=await o.readSourceSnapshot(v,r).catch($=>{if(!Fe($))throw $});if(_===void 0){g(v)&&E.add(v);continue}W.set(v,_.content),_.version!==R.version&&_.content!==R.document.content&&j.set(v,ae.between(R.document.content,_.content))}let U=T.filter(v=>W.has(v.source));for(let[v,R]of U.entries()){let _=j.get(R.source);if(_===void 0)continue;let $=_.mapRange({start:{line:R.lineNumber-1,character:R.startColumn},end:{line:(R.endLineNumber??R.lineNumber)-1,character:R.endColumn}});if($===void 0)throw O("LSP source changed during search.");U[v]={...R,lineNumber:$.start.line+1,endLineNumber:$.end.line+1}}U.sort((v,R)=>v.source.localeCompare(R.source)||v.lineNumber-R.lineNumber||v.startColumn-R.startColumn||v.endColumn-R.endColumn||v.symbol.id.localeCompare(R.symbol.id));let K=U.slice(0,n),B=Ie(P);return{hits:K,contents:new Map(K.map(v=>[v.source,F(W.get(v.source))])),complete:(i?.complete??!0)&&U.length<=n&&Ee(B),...B!==void 0&&!Ee(B)&&{coverage:B},...E.size>0&&{missing:[...E].sort()}}}a(li,"searchSymbolsOnce");import Jt from"node:path";import{fileURLToPath as Qr}from"node:url";var Xt=10,Kt=5,ke=10,di=new Set([6,9,12,25]);async function Yr(t,e,n,r,s){return te(()=>ui(t,e,n,r,s),s,rs)}a(Yr,"resolveLspDeclaration");async function ui(t,e,n,r,s){ue(s);let o=await dt(t,e,r,s),i=ss(o,n),c=await t.readSourceText(o.filePath,s);ue(s);let l=o.servedText??c,d=Ve(i,l),u=l===c?void 0:ae.between(l,c),p=u===void 0?d.range:u.mapRange(d.range),f=u===void 0?d.selectionRange:u.mapRange(d.selectionRange);if(p===void 0||f===void 0)throw O("The symbol source changed during resolution. Read it again before editing.");return{source:o.filePath,range:p,selectionRange:f,content:c}}a(ui,"resolveLspDeclarationOnce");async function Zr(t,e,n,r,s,o){ue(o);let i=await dt(t,e,r,o,s);if(i.servedText!==s)throw O("The language server changed documents during rename resolution.");return ue(o),{client:i.client,uri:i.uri,entries:Gt(i.symbols,n,i.displayPath),content:s}}a(Zr,"resolveLspRenameTarget");function es(t,e,n,r){let s=Le(o=>t.openFile(Be(o),e,"symbols",r),r);return{errorsOf:s,texts:new Yt(t,r),...n&&{reachOf:Pe({manager:t,cwd:e,errorsOf:s,accepts:a(o=>oe(o,e,{}),"accepts"),...r&&{signal:r}})}}}a(es,"relationContext");function Be(t){return t.startsWith("ssh://")?t:Qr(t)}a(Be,"fileOf");async function en(t,e,n,r,s){return te(async()=>{ue(s);let o=await dt(t,e,r,s),i=ss(o,n),c=Ve(i,o.servedText),l=es(t,r,!0,s),d=await os(o,c,l,s),u=new lt(r),p=await fi(o,c,d,u);return ts(p,[d],l.texts)},s,rs)}a(en,"readLspSymbolGraph");async function ts(t,e,n){let r=new Map,s=a(async i=>{let c=new Map;for(let{uri:l,range:d}of i){let u=Be(l);r.set(u,await n.snapshot(l)),c.set(JSON.stringify([u,d]),{source:u,range:d})}return[...c.values()].sort((l,d)=>l.source.localeCompare(d.source)||l.range.start.line-d.range.start.line||l.range.start.character-d.range.start.character)},"locate"),o=a(i=>i.map(c=>({uri:c.uri,range:c.declaration})),"declarations");return{text:t,references:await s(e.flatMap(i=>i.references)),incoming:await s(e.flatMap(i=>o(i.incoming))),outgoing:await s(e.flatMap(i=>o(i.outgoing))),complete:e.every(i=>Ee(i.coverage)&&i.unsupported.length===0&&!i.callItemMissing&&!i.referenceReplyMissing),contents:r,missing:ns(e)}}a(ts,"graphOf");function ns(t){return[...new Set(t.flatMap(e=>e.missing))].sort()}a(ns,"missingOf");var Yt=class{static{a(this,"ReportedTexts")}#e;#t;#r=new Map;#n=new Map;constructor(e,n){this.#e=e,this.#t=n}snapshot(e){let n=this.#r.get(e);return n===void 0&&(n=this.#e.readSourceText(Be(e),this.#t),this.#r.set(e,n)),n}between(e,n){let r=this.#n.get(e);r===void 0&&(r=new Map,this.#n.set(e,r));let s=r.get(n);return s===void 0&&(s=ae.between(e,n),r.set(n,s)),s}async report(e,n,r){if(n===void 0)return r;let s=await this.snapshot(e);if(n===s)return r;let o=this.between(n,s).mapRange(r);if(o===void 0)throw O("A line the language server reported changed in the file. Read it again.");return o}};async function tn(t,e,n,r){return te(async()=>{ue(r);let s=await dt(t,e,n,r),o=new lt(n),i=[`## file graph: ${s.displayPath}`,`Top-level declarations: ${s.symbols.length}`],c=es(t,n,!1,r),l=[];for(let d of s.symbols){ue(r);let u=await os(s,d,c,r);l.push(u),i.push("",...await wi(s,d,u,o))}return i.splice(2,0,...De(Ie(l.map(d=>d.coverage)),d=>o.display(d)),...Te(ns(l),d=>o.display(d))),ts(i.join(`
7
- `),l,c.texts)},r)}a(tn,"readLspFileGraph");var at=class extends Error{static{a(this,"LspSelectorUnconfirmedError")}code="LSP_SELECTOR_UNCONFIRMED"};function rs(t){return t instanceof at}a(rs,"isUnconfirmedSelector");function ss(t,e){try{return Gt(t.symbols,e,t.displayPath)}catch(n){if(!(n instanceof He)||!de.has(t.languageId))throw n;let r=e.at(-1)??"",s=/^~?([\p{ID_Start}_$][\p{ID_Continue}$]*)(?=\s*\(|$)/u.exec(r)?.[1];throw s===void 0||t.servedText===void 0||!new RegExp(`(?<![\\p{ID_Continue}$])${s.replaceAll("$","\\$")}(?![\\p{ID_Continue}$])`,"u").test(t.servedText)?n:new at(`The language server could not confirm "${Z(e)}" in ${t.displayPath}. Check the current outline before trying again.`,{cause:n})}}a(ss,"resolveNavigationDeclaration");async function dt(t,e,n,r,s){let o=Oe(e,n),i=await t.openFile(o,n,"symbols",r,s===void 0?void 0:()=>Promise.resolve(s));if(!i)throw new Error(`No LSP server with symbol support is configured for ${Zt(o,n)}.`);let c=i.client.documentContent(i.uri),l=await Ue(i.client,i.uri,r),d=Ge(l);return{client:i.client,uri:i.uri,filePath:o,displayPath:Zt(o,n),symbols:d,servedText:c,languageId:i.languageId}}a(dt,"openCodeDocument");async function os(t,e,n,r){let{errorsOf:s,texts:o}=n,i=de.has(t.languageId)?await n.reachOf?.(t.client,t.languageId,e.name)??{client:t.client,opened:[],unopened:[],unlisted:!1}:void 0,c=t.client.documentContent(t.uri),l=gi(t,e,c,o),[d,u]=await Promise.all([We(t.client,t.uri,l,r),Wt(t.client,t.uri,l,r)]);if(ue(r),t.client.documentContent(t.uri)!==c)throw O("The server's text changed while it answered a call graph request.");n.reachOf!==void 0&&de.has(t.languageId)&&it(e.name,d);let p=await pi([...d.map(g=>g.uri),...u.incoming.map(g=>g.from.uri),...u.outgoing.map(g=>g.to.uri)].filter(g=>g!==t.uri),o),f=d.filter(g=>!p.has(g.uri)),y=u.incoming.filter(g=>!p.has(g.from.uri)),S=u.outgoing.filter(g=>!p.has(g.to.uri)),h=new Map([[t.uri,c]]);for(let g of[...f.map(C=>C.uri),...y.map(C=>C.from.uri),...S.map(C=>C.to.uri)])h.has(g)||h.set(g,t.client.documentContent(g));let w=a(async g=>h.get(g)??o.snapshot(g),"contentOf"),b=a(async(g,C)=>o.report(g,h.get(g),C),"report"),L=[e.name,ne(t.servedText??"",e.selectionRange)],T=a(async(g,C)=>g.length===0?[]:(await _e(await Promise.all(g.map(async E=>{let m=C(E);return{item:E,uri:m.uri,start:m.range.start,text:ne(await w(m.uri),m.range)}})),E=>E,L,s)).map(({item:E})=>E),"named"),k=await Promise.all(y.map(async g=>({...g,fromRanges:await T(g.fromRanges,C=>({uri:g.from.uri,range:C}))}))),M=a(async(g,C)=>({name:g.name,kind:g.kind,uri:g.uri,line:(await b(g.uri,C)).start.line,declaration:await b(g.uri,g.range)}),"site");return{definitionLine:(await o.report(t.uri,t.servedText,e.selectionRange)).start.line,references:await Promise.all((await T(f,g=>g)).map(async g=>({uri:g.uri,range:await b(g.uri,g.range)}))),coverage:i&&await xe(i,[t.uri,...f.map(g=>g.uri),...y.map(g=>g.from.uri)],s,Be),incoming:await Promise.all(k.filter((g,C)=>g.fromRanges.length>0||y[C]?.fromRanges.length===0).map(g=>M(g.from,g.fromRanges[0]??g.from.selectionRange))),outgoing:await Promise.all(S.map(g=>M(g.to,g.to.selectionRange))),unsupported:u.unsupported,callItemMissing:u.items.length===0&&u.unsupported.length===0&&di.has(e.kind),referenceReplyMissing:i!==void 0&&d.length===0,missing:[...p].map(Be).sort()}}a(os,"queryRelations");async function pi(t,e){let n=new Set;return await Promise.all([...new Set(t)].map(async r=>{try{await e.snapshot(r)}catch(s){if(!Fe(s))throw s;n.add(r)}})),n}a(pi,"missingFiles");function gi(t,e,n,r){let s=t.servedText,o=e.selectionRange;if(n===void 0||s===void 0||n===s)return o.start;let i=st(r.between(s,n),o,n,ne(s,o));if(i===void 0)throw O(`The line of declaration "${e.name}" changed before the server was asked for its calls.`);return i.start}a(gi,"servedPosition");async function fi(t,e,n,r){let s=Z(e.selector),o=await r.line(t.uri,n.definitionLine+1);return[`## graph: ${s}`,`Definition: ${t.displayPath} ${o} (${Se(e.kind)})`,`Source: calls ${as(t.displayPath,e.selector)}`,...De(n.coverage,c=>r.display(c)),...Te(n.missing,c=>r.display(c)),"",...await mi(n.references,r),"",...ct(t,n,"incoming")??await hi(n.incoming,r),"",...ct(t,n,"outgoing")??await yi(n.outgoing,r)].join(`
8
- `)}a(fi,"formatSymbolGraph");async function mi(t,e){let n=cs(t),r=[`References: ${t.length} in ${n.length} file(s)`];for(let[s,o]of n.slice(0,Xt)){r.push(`- ${e.display(s)} (${o.length})`);for(let i of o.slice(0,Kt))r.push(` - ${await e.line(s,i.range.start.line+1)}`);o.length>Kt&&r.push(` - ... ${o.length-Kt} more`)}return n.length>Xt&&r.push(`- ... ${n.length-Xt} more file(s)`),r}a(mi,"formatReferences");function ct(t,e,n){let r=n==="incoming"?"Incoming calls":"Outgoing calls";if(e.unsupported.includes(n))return[`${r}: not supported by ${t.client.serverId}`];if(e.callItemMissing)return[`${r}: unavailable; the server could not resolve the callable declaration.`]}a(ct,"unavailableCalls");async function hi(t,e){let n=[`Incoming calls: ${t.length}`];t.length===0&&n.push("- none found; the server's index can miss callers added in the last seconds");for(let r of t.slice(0,ke))n.push(await is(r,e));return t.length>ke&&n.push(`- ... ${t.length-ke} more`),n}a(hi,"formatIncomingCalls");async function yi(t,e){let n=[`Outgoing calls: ${t.length}`];for(let r of t.slice(0,ke))n.push(await is(r,e));return t.length>ke&&n.push(`- ... ${t.length-ke} more`),n}a(yi,"formatOutgoingCalls");async function is(t,e){let n=await e.line(t.uri,t.line+1);return`- ${Se(t.kind)} ${t.name} \u2014 ${e.display(t.uri)} ${n}`}a(is,"formatCallSite");async function wi(t,e,n,r){let s=Se(e.kind),o=await r.line(t.uri,n.definitionLine+1),i=cs(n.references).map(([p,f])=>`${r.display(p)} (${f.length})`),c=a(p=>p.map(f=>`${f.name} (${r.display(f.uri)})`),"named"),l=c(n.incoming),d=c(n.outgoing),u=[`### ${s} ${e.name}`,`Selector: ${Z(e.selector)}`,`Definition: ${o}`,n.referenceReplyMissing?"Used by: unavailable; the server returned no locations for this declaration.":`Used by: ${Qt(i)}`,...ct(t,n,"incoming")??[`Incoming calls: ${Qt(l)}`],...ct(t,n,"outgoing")??[`Outgoing calls: ${Qt(d)}`]];if(e.children.length>0){u.push("Members:");for(let p of e.children){let f=as(t.displayPath,p.selector);u.push(`- ${Se(p.kind)} ${p.name} \u2014 calls ${f}`)}}return u}a(wi,"formatFileGraphSymbol");function as(t,e){return Jn("graph",t,e).slice(6)}a(as,"callsReference");function Qt(t,e=5){if(t.length===0)return"none";let n=t.slice(0,e).join(", ");return t.length>e?`${n}, ... ${t.length-e} more`:n}a(Qt,"summarize");function cs(t){let e=new Map;for(let n of t){let r=e.get(n.uri)??[];r.push(n),e.set(n.uri,r)}return[...e].map(([n,r])=>[n,r.sort((s,o)=>s.range.start.line-o.range.start.line||s.range.start.character-o.range.start.character)]).sort(([n],[r])=>n.localeCompare(r))}a(cs,"groupLocationsByUri");var lt=class{static{a(this,"LocationPresenter")}#e;constructor(e){this.#e=e}display(e){return Zt(vi(e),this.#e)}line(e,n){return Promise.resolve(String(n))}};function vi(t){if(!t.startsWith("file://"))return t;try{return Qr(t)}catch{return decodeURIComponent(t.slice(7))}}a(vi,"filePathFromUri");function Zt(t,e){if(t.startsWith("ssh://"))return t;let n=Jt.relative(e,t);return n.length===0||n.startsWith("..")||Jt.isAbsolute(n)?t:n.replaceAll(Jt.sep,"/")}a(Zt,"displayFilePath");function ue(t){if(t?.aborted===!0)throw bi(t)}a(ue,"throwIfAborted");function bi(t,e){if(t.reason instanceof Error)return t.reason;if(e instanceof Error)return e;let n=new Error("The operation was aborted");return n.name="AbortError",n}a(bi,"abortReason");function nn(t){let e=null;return{kind:"compiler",name:"lsp",priority:100,extensions:["*"],detect:a(()=>Promise.resolve(!0),"detect"),async compile({filePath:n},r){r.signal?.throwIfAborted();let s=await t(r.cwd,n,r.signal);r.signal?.throwIfAborted();let o=await re(()=>Si(n,r,s));if(!o)throw new Error("No diagnostic language server for this source");let{client:i,diagnostics:c,syntaxErrors:l,otherDiagnostics:d}=o;return e=i,{ok:!c.some(u=>u.severity==="error"),diagnostics:c,syntaxErrors:l,otherDiagnostics:d}},async restart(){e&&(await e.restart(),e=null)}}}a(nn,"createLspCompiler");async function Si(t,e,n){let r=await n.openFile(t,e.cwd,"diagnostics",e.signal);if(e.signal?.throwIfAborted(),!r)return null;let s=await pe(r.client,r.uri,r.languageId,{signal:e.signal});if(e.signal?.throwIfAborted(),!s.complete)throw new Error("Language server diagnostics are a snapshot, not a completed report");return{client:r.client,...s}}a(Si,"openAndDiagnose");import _i from"node:path";function ls(t){let e=t.options?.lsp;return typeof e=="object"&&e!==null?e:void 0}a(ls,"lspOptions");var Li={resolveLspDeclaration:Yr,readLspFileGraph:tn,readLspSymbolGraph:en,searchSymbols:Bt};function ds(t,e,n=Li,r){return{id:"lsp",supportsResultScope:!0,supportsPathList:!0,readResources:a(s=>ls(s)===void 0?[]:void 0,"readResources"),toScriptData(s){let o=s;return o.mode==="calls"?{kind:"custom",resolverId:"lsp",value:o.data}:o.data},tryResolve(s,o){let i=ls(s),c=i?.calls!==void 0||i?.declaration!==void 0||i?.references===!0;return a(d=>c?jt(o.signal,u=>re(()=>d({...o,signal:u}))):re(()=>d(o)),"withDocuments")(async d=>{let u=a(async C=>{try{return await e(C,d)}catch(E){throw E instanceof Error&&E.name==="SearchSnapshotChangedError"?O(E.message):E}},"register");if(i===void 0)return{kind:"not-handled"};if([i.query,i.declaration,i.calls].filter(C=>C!==void 0).length!==1)return{kind:"failed",error:new Error("Pass exactly one of query, declaration or calls.")};if(i.calls!==void 0){let C=yt(`graph:${i.calls}`,"graph");if(C===void 0)throw new Error("calls requires a file path.");let E=Oe(C.path,d.cwd),m=C.selector,P=a(async j=>{let W=await t(d.cwd,E,j),U=m===void 0?await n.readLspFileGraph(W,E,d.cwd,j):await n.readLspSymbolGraph(W,E,m,d.cwd,j);return{text:U.text,complete:U.complete,...Ri(U)}},"graph"),I=["references","incoming","outgoing"],{text:A,data:x}=await te(async()=>{let j=await P(d.signal),W=[];for(let v of I)W.push(await u({request:s,matches:j[v],complete:j.complete,contents:j.contents,refresh:a(R=>re(async()=>{let _=await P(R);return{matches:_[v],complete:_.complete,contents:_.contents}}),"refresh")}));let[U,K,B]=I.map((v,R)=>{let _=F(W[R]);return we(_.matches,j.complete,_.id,_)});return{text:j.text,data:{target:F(W[0]).target,complete:j.complete,matches:U,incoming:K,outgoing:B}}},d.signal);return{kind:"resolved",payload:{mode:"calls",text:A,data:x}}}if(i.declaration!==void 0){let C=i.declaration.includes("#")?yt(`graph:${i.declaration}`,"graph"):void 0;if(C?.selector===void 0)throw new Error("declaration requires file#selector, such as src/app.ts#App/start.");let E=Oe(C.path,d.cwd),m=C.selector,P=a(async j=>{let W=await t(d.cwd,E,j),U=await n.resolveLspDeclaration(W,E,m,d.cwd,j);return{match:structuredClone(us(U.source,U.content,U.range)),name:qe(U.source,Me(U.source,U.content),U.selectionRange),contents:new Map([[U.source,U.content]])}},"resolve"),{match:I,session:A,captured:x}=await te(async()=>{let{match:j,name:W,contents:U}=await P(d.signal),K=await u({request:s,matches:[W],complete:!0,contents:U,refresh:a(async()=>{throw new Error("Name captures cannot refresh; repeat lsp_search.")},"refresh")});r?.register([K.target,...K.matchTargets??[]],{source:E,selector:m});let B=we(K.matches,!0,void 0,K),v=await u({request:s,matches:[j],complete:!0,contents:U,refresh:a(R=>jt(R,_=>re(async()=>{let $=await P(_);return{matches:[$.match],complete:!0,contents:$.contents}})),"refresh")});return{match:j,session:v,captured:B}},d.signal);return{kind:"resolved",payload:{mode:"declaration",sessionId:A.id,selector:i.declaration,match:I,nameTarget:x.target,data:{...we(A.matches,!0,A.id,A),matches:we(A.matches,!0,A.id,A).matches.map(j=>({...j,captures:{name:x.matches}}))}}}}let f=(i.query??"").trim();if(f.length===0)return{kind:"failed",error:new Error("query must not be empty")};let y=i.references===!0,S=d.scope,h=a(async(C,E)=>{let m=new Map,P=a(async I=>{let A=await t(d.cwd,I,E),x=m.get(A)??{targets:[],paths:[]};return m.set(A,x),x},"group");if(C===void 0){s.paths===void 0&&await P(s.path);for(let I of s.paths??[])(await P(I)).paths.push(I);return m}for(let I of C.targets)(await P(I.source)).targets.push(I);return m},"groupScope"),w=await h(S,d.signal),b=s.limit??100,L=a(async(C,E=!1)=>{let m=E?await jn(d,C):S,P=E?await h(m,C):w,I=[],A=new Map,x=new Set,j=m?.complete??!0,W=[],U=new Set;for(let[B,{targets:v,paths:R}]of P){let _=await n.searchSymbols(f,B.workspaceRoot,b,C,{...s.path===void 0?{}:{path:s.path},...s.paths===void 0?{}:{paths:R},...s.include===void 0?{}:{include:s.include},...s.exclude===void 0?{}:{exclude:s.exclude},...y?{navigation:"references"}:{},...m===void 0?{}:{resultScope:{targets:v,complete:m.complete}}},B);I.push(..._.hits);for(let[$,D]of _.contents){let Q=A.get($);Q===void 0?A.set($,D):Q!==D&&x.add($)}j=j&&_.complete,W.push(_.coverage);for(let $ of _.missing??[])U.add($)}for(let B of x)A.delete(B);let K=Ie(W);return{...structuredClone({hits:I.slice(0,b),complete:j&&I.length<=b,...K&&{coverage:K},...U.size>0&&{missing:[...U].sort()}}),contents:A}},"collect"),T=0,{found:k,session:M}=await te(async()=>{let{contents:C,...E}=await L(d.signal,T++>0),m=await u({request:s,matches:E.hits,complete:E.complete,contents:C,refresh:a(P=>re(async()=>{let I=await L(P,!0);return{matches:I.hits,complete:I.complete,contents:I.contents}}),"refresh")});return{found:E,session:m}},d.signal),g=we(M.matches,k.complete,M.id,M);return{kind:"resolved",payload:{mode:"symbols",sessionId:M.id,hits:k.hits,complete:k.complete,...k.coverage&&{coverage:k.coverage},...k.missing&&{missing:k.missing},references:y,data:{...g,matches:g.matches.map((C,E)=>({...C,role:k.hits[E]?.role,symbol:k.hits[E]?.symbol}))}}}})},renderResult(s,o,i){let c=s.details;return c.mode==="calls"?new Xe({summary:c.text.split(`
9
- `,1)[0]??"Calls",rows:c.text.split(`
10
- `).slice(1).map(l=>({kind:"note",text:l}))},i,o.expanded):c.mode==="declaration"?ht([c.match],!0,i,o.expanded,c.cwd,[],[c.selector]):ht(c.hits,c.complete,i,o.expanded,c.cwd,[...c.references?["LSP reference navigation \xB7 may leave input scope"]:[],...De(c.coverage,l=>rn(l,c.cwd)),...Te(c.missing??[],l=>rn(l,c.cwd))],c.hits.map(l=>`${l.role} ${l.symbol.name}`))},format(s,o){let i=s,c=a(u=>rn(u,o.cwd),"display");if(i.mode==="calls")return{content:[{type:"text",text:i.text}],details:{mode:"calls",text:i.text}};if(i.mode==="declaration"){let{match:u}=i,p=u.endLineNumber??u.lineNumber,f=p>u.lineNumber&&u.endColumn===0?p-1:p;return{content:[{type:"text",text:[`SEARCH#${i.sessionId}:1:match ${c(u.source)}:${u.lineNumber}-${f} declaration ${i.selector}`,u.matchedText.replace(/\r?\n$/u,""),...i.nameTarget?[`capture name: ${i.nameTarget} \xB7 replace this capture to rename through LSP; replacing the declaration edits only its text.`]:[]].join(`
11
- `)}],details:{...i,cwd:o.cwd}}}let l=i.references?"LSP reference navigation (may leave input scope)":"LSP symbols inside scope",d=i.hits.length===0?["No symbols found."]:i.hits.slice(0,100).map((u,p)=>`SEARCH#${i.sessionId}:${p+1}:match ${c(u.source)}:${u.lineNumber}:${u.startColumn+1} ${u.role} ${u.symbol.name} \xB7 ${u.role==="definition"&&u.symbol.selector!==void 0?`selector ${c(u.symbol.source)}#${Z(u.symbol.selector)}`:`declared at ${c(u.symbol.source)}:${u.symbol.range.startLine}:${u.symbol.range.startColumn+1}`}`);return i.complete&&i.hits.length&&d.unshift(`SEARCH#${i.sessionId}:all:match selects all exact symbol matches.`),i.hits.length>100&&d.push("Preview shortened; full source targets retained."),d.push(...De(i.coverage,c)),d.push(...Te(i.missing??[],c)),{content:[{type:"text",text:[l,...d].join(`
12
- `)}],details:{...i,cwd:o.cwd}}}}}a(ds,"createLspSearchResolver");function rn(t,e){return t.startsWith("ssh://")?t:_i.relative(e,t)}a(rn,"displaySource");function Ri(t){let e=a(o=>F(t.contents.get(o)),"textOf"),n=new Map,r=a(o=>{let i=n.get(o)??Me(o,e(o));return n.set(o,i),i},"documentOf"),s=a(o=>o.map(({source:i,range:c})=>structuredClone(us(i,e(i),c))),"declarations");return{references:t.references.map(({source:o,range:i})=>structuredClone(qe(o,r(o),i))),incoming:s(t.incoming),outgoing:s(t.outgoing),contents:t.contents}}a(Ri,"graphMatches");function us(t,e,n){Re(e);let r=e.split(`
13
- `),s=[0];for(let p of r)s.push((s.at(-1)??0)+p.length+1);let o=n.start.line,i=n.end.line+1<r.length,c=i?n.end.line+1:n.end.line,l=i?0:(r[n.end.line]??"").length,d=s[o]??e.length,u=Math.min(e.length,(s[c]??e.length)+l);return{source:t,lineNumber:o+1,startColumn:0,...c===o?{}:{endLineNumber:c+1},endColumn:l,matchedText:e.slice(d,u),lineText:r[o]??""}}a(us,"declarationMatch");import{Type as V}from"typebox";var ps=V.Object({query:V.Optional(V.String({minLength:1,description:"Symbol name to find in the workspace."})),declaration:V.Optional(V.String({minLength:1,description:"file#selector, such as src/app.ts#App/start or main.cpp#clamp(int, float) for one overload: returns the editable declaration with captures.name. Replace its name capture with a new identifier to rename through LSP; replacing the declaration edits only its text."})),calls:V.Optional(V.String({minLength:1,description:"file or file#selector: references and incoming/outgoing calls."})),path:V.Optional(V.Union(hn.anyOf,{description:"For query: file, directory, unchanged Read/Search/edit result or its UUID, or an array of paths or of results."})),references:V.Optional(V.Boolean({description:"For query: also follow symbols found inside path to their references outside it."})),include:V.Optional(V.String({description:"Include glob for query"})),exclude:V.Optional(V.String({description:"Exclude glob for query"})),limit:V.Optional(V.Integer({minimum:1,maximum:1e3,description:"Maximum matches (default 100; in Codemode, all matches)."}))},{additionalProperties:!1});async function gs(t,e){let n;e.then(s=>n=s);let r=gn(t,"lsp_search");t.registerTool(In({name:"lsp_search",label:"lsp_search",exposure:"direct",namespace:{name:"ide_lsp_search",description:"Navigate code through language servers: symbol definitions, references and call graphs."},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1},description:"Use lsp_search to find symbol declarations and references, read one declaration, or list a symbol's calls and references through the project's language servers. Matches and declarations are editable selections.",promptSnippet:"Find symbols, references, declarations and call graphs through language servers",parameters:ps,outputSchema:An,prepareArguments:a(s=>Mn(s,ps),"prepareArguments"),renderCall(s,o,i){return xn(i.lastComponent,{tool:"lsp_search",primary:{text:s.query??s.declaration??s.calls??"",color:"accent",truncate:"end"},qualifiers:[...s.declaration===void 0?[]:[{text:"declaration"}],...s.calls===void 0?[]:[{text:"calls"}],...s.path===void 0?[]:[{text:`in ${Nn(s.path)}`,color:"accent",truncate:"start"}],...s.references===!0?[{text:"references",color:"warning"}]:[]],expanded:i.expanded},o)},renderResult(s,o,i,c){let l=s.details;if(n?.resolver.renderResult!==void 0&&l?.payload!==void 0&&!c.isError&&!o.isPartial)return n.resolver.renderResult({...s,details:l.payload},o,i,c);let d=s.content.flatMap(u=>u.type==="text"?[u.text]:[]).join(`
14
- `);return new Xe({summary:c.isError?"lsp_search failed":"lsp_search",rows:d.split(`
15
- `).map(u=>({kind:"note",text:u}))},i,o.expanded)},async execute(s,o,i,c,l){let d=On(o);if(d!==void 0)return sn(d);let u=o.query??o.declaration??o.calls,p=[o.query,o.declaration,o.calls].filter(b=>b!==void 0);if(u===void 0||p.length!==1)return sn("Pass exactly one of query, declaration or calls.");let f={...o.query===void 0?{}:{query:o.query},...o.declaration===void 0?{}:{declaration:o.declaration},...o.calls===void 0?{}:{calls:o.calls},...o.references===!0?{references:!0}:{}};if(n===void 0)return sn("lsp_search needs the Search module (search.core), which is not loaded.");let{api:y,resolver:S}=n,{limit:h,audience:w}=$n(o.limit,r(s),"matches");return await y.searchWith(S,{query:u,...o.path===void 0?{}:{path:o.path},...o.include===void 0?{}:{include:o.include},...o.exclude===void 0?{}:{exclude:o.exclude},...h===void 0?{}:{limit:h},options:{lsp:f}},{cwd:l.cwd,...i!==void 0&&{signal:i},...c!==void 0&&{onUpdate:c}},w)}},new En))}a(gs,"registerLspSearchTool");function sn(t){return pn({content:[{type:"text",text:t}],details:{failure:{code:"INVALID_REQUEST",message:t}}},kn,{status:"error",errors:[un(new Error(t),"SEARCH_FAILED")]})}a(sn,"failure");var ut=class{static{a(this,"NameCaptures")}#e=new Map;register(e,n){for(let r of e)r!==void 0&&(this.#e.set(r,n),r.startsWith("RESULT#")&&this.#e.set(r.slice(7),n))}get(e){let n=yn(e)??e;return typeof n=="string"?this.#e.get(n):void 0}find(e){if(typeof e!="object"||e===null)return;let n=a(s=>{if(Array.isArray(s)){for(let i of s){let c=n(i);if(c!==void 0)return c}return}let o=this.get(s);return o===void 0?void 0:{capture:o,reference:s}},"find"),r=e;for(let s of["path","at","from","after","through","before"]){let o=n(r[s]);if(o!==void 0)return o}}matches(e){return this.find(e)!==void 0}};async function fs(t,e,n,r){let s=await t.resolveCurrent(e,n,r),o=s.targets[0],i=o?.ranges[0];if(!s.complete||s.targets.length!==1||o?.ranges.length!==1||i===void 0||i.adjusted)throw new Error("The name capture changed. Repeat lsp_search before renaming.");return await t.verify(s,r),{target:o,range:i}}a(fs,"currentNameCapture");import on from"node:path";import{fileURLToPath as Ci}from"node:url";function Pi(t,e){let n=t.split(`
16
- `)[e.line]??"";for(let r of n.matchAll(/[\p{L}\p{N}_$]+/gu))if(r.index<=e.character&&e.character<r.index+r[0].length)return r[0];return""}a(Pi,"identifierAt");function xi(t,e){if(t===null)throw new Error("The language server did not provide rename edits. No text fallback was applied.");let n=new Map(Object.entries(t.changes??{}));for(let r of t.documentChanges??[]){if(!("textDocument"in r)||!("edits"in r))throw new Error("Rename returned an unsupported file operation. No edits applied.");if(r.textDocument.version!=null&&r.textDocument.version!==e.documentVersion(r.textDocument.uri))throw new Error("Rename refers to an unavailable document revision. No edits applied.");if(n.has(r.textDocument.uri))throw new Error("Rename returned duplicate document edits.");n.set(r.textDocument.uri,r.edits)}return n}a(xi,"renameEntries");function hs(t){Re(t);let e=0,n=t.split(`
17
- `).map(r=>{let s={start:e,length:r.replace(/\r$/u,"").length};return e+=r.length+1,s});return({line:r,character:s})=>{let o=n[r];if(!Number.isInteger(r)||r<0||o===void 0||!Number.isInteger(s)||s<0||s>o.length)throw new Error("The language server returned an invalid text position.");return o.start+s}}a(hs,"offsets");function Ei(t,e,n,r,s){let o=a(u=>/^[ \t]*\r?$/u.test(u)||/^[ \t]*\/\/[^\\@#\r]*\r?$/u.test(u)&&!u.includes("*/")&&!u.includes("??/")&&!u.includes(n)&&!u.includes(r),"isTrivia"),i=a(u=>u.split(`
18
- `).flatMap((p,f)=>{if(o(p))return[];let y=p.replace(/^[ \t]*/u,"");return[{index:f,text:y,indent:p.slice(0,p.length-y.length)}]}),"significantLines"),c=i(t),l=i(e);if(c.length!==l.length)return;let d=new Map;for(let[u,p]of c.entries()){let f=l[u];if(f===void 0||f.text!==p.text||!s&&f.indent!==p.indent)return;d.set(p.index,{line:f.index,shift:f.indent.length-p.indent.length})}return d}a(Ei,"matchLayout");function Ii(t,e,n,r,s,o,i){if(!de.has(i))return;let c=/R"|__LINE__|__builtin_LINE|__builtin_COLUMN|source_location|##|%:%:|\?\?=\?\?=|(?:\\|\?\?\/)[ \t]*\r?\n/u;if(c.test(t)||c.test(e))return;let l=/^[\p{L}_$][\p{L}\p{N}_$]*$/u;if(!l.test(s)||!l.test(o))return;let d=/#|%:|\?\?=|\bimport\b/u.test(t),u=Ei(t,e,s,o,!d);if(u===void 0)return;let p=fn(t,e),f=hs(e),y=[];for(let[S,{range:{start:h,end:w},newText:b}]of n.entries()){let L=r[S],T=u.get(h.line);if(L===void 0||b!==o||t.slice(L.from,L.to)!==s||T===void 0||h.line!==w.line)return;let k=p.move({start:{lineNumber:h.line+1,column:h.character},end:{lineNumber:w.line+1,column:w.character}}),M=T.line;if(k===void 0||k.start.lineNumber!==M+1||k.end.lineNumber!==M+1||k.start.column!==h.character+T.shift||k.end.column!==w.character+T.shift)return;let g=f({line:M,character:k.start.column}),C=f({line:M,character:k.end.column});if(e.slice(g,C)!==s)return;y.push({from:g,to:C,insert:b})}return y}a(Ii,"rebaseRename");var Di=12e3,Ti=4e3,ki=[0,50,100,200,400,500,500,500,500],ms=new WeakSet;function Ai(t){return t instanceof dn&&t.code==="RESOURCE_CHANGED"||t?.code===tt}a(Ai,"sourceMoved");function ys(t,e,n,r){let s=performance.now(),o=t.input,i=n.find(o);if(i===void 0)return;let c=n.get(o.path),l,d;function u(f){return ms.add(f),d??=AbortSignal.timeout(Di)}a(u,"startRefresh");function p(){return`The rename could not catch up with newer text after ${((performance.now()-s)/1e3).toFixed(1)} s. Nothing was written. Repeat the same replace call with the same name capture and new name.`}return a(p,"exhaustedMessage"),{...t,...c!==void 0&&{sourceChangeRetry:{delaysMs:ki,start:a(()=>u(c),"start"),exhaustedMessage:p}},input:{...o,path:i.capture.source},planEdit:a(async()=>{if(c===void 0||typeof o.text!="string"||o.text.trim()===""||Pn(o,Cn))throw new Error("Rename needs one declaration name capture and a non-empty new name. Omit text selectors. Use replace with "+JSON.stringify({path:i.reference,text:"newName"}));t.signal?.throwIfAborted();let f=ms.has(c)?u(c):void 0;if(f?.aborted)throw O(p());if(l!==void 0)return l;let y=f===void 0?void 0:AbortSignal.timeout(Ti),S=y===void 0||f===void 0?t.signal:AbortSignal.any([f,y,...t.signal?[t.signal]:[]]);try{let h={...c,newName:o.text},w=await re(()=>Mi(t.cwd,S,h,e,()=>fs(r,o.path,t.cwd,S)));return S?.throwIfAborted(),l={files:w.files.map(b=>({...b,rebase(L){let T=b.rebase?.(L);return T===void 0&&(l=void 0,u(c)),T}}))},l}catch(h){throw t.signal?.throwIfAborted(),f?.aborted?O(p(),{cause:h}):y?.aborted&&h===y.reason?O("The language server did not finish the rename refresh in time."):(Ai(h)&&u(c),h)}},"planEdit"),metadata:{...t.metadata,semanticEdit:{mode:"lsp-rename",referencesUpdated:!0},diffStatuses:[{text:"Renamed through LSP",tone:"success"}]}}}a(ys,"prepareSymbolRename");async function Mi(t,e,{source:n,selector:r,newName:s},o,i){let c=await i(),l=c.target.expectedContent;if(c.target.source!==n)throw new Error("The name capture no longer identifies this declaration. Repeat lsp_search.");let d=await o(t,n,e),u=await Zr(d,n,r,t,l,e),p=u.entries.find(({selectionRange:{start:m,end:P}})=>c.range.start.lineNumber===m.line+1&&c.range.start.column===m.character&&c.range.end.lineNumber===P.line+1&&c.range.end.column===P.character);if(p===void 0)throw new Error("The name capture no longer identifies this declaration. Repeat lsp_search.");let f=p.selectionRange.start,y=a(m=>m.startsWith("ssh://")?m:Ci(m),"fileOf"),{client:S,uri:h}=u,w=new Map([[h,{file:n,content:l,version:S.documentVersion(h)}]]);function b(){e?.throwIfAborted();for(let[m,P]of w)if(S.documentVersion(m)!==P.version||S.documentContent(m)!==P.content)throw O("A rename participant changed on the language server. No edits applied.")}a(b,"checkSnapshots");let L=Le(m=>{let P=w.get(m);return d.openFile(y(m),t,"symbols",e,P===void 0?void 0:()=>Promise.resolve(P.content))},e);await Ut(S,h,e);let T=[p.name,Pi(u.content,f)],k=await Pe({manager:d,cwd:t,errorsOf:L,...e&&{signal:e}})(u.client,d.languageId(on.extname(n)),T[1]||T[0]||"");async function M(){b();let m=await kt(S,h,f,s,e);return b(),xi(m,S)}a(M,"renameOnSnapshots");let g=await M();for(let m of g.keys()){if(m===h)continue;if(e?.throwIfAborted(),X(m,S.rootUri)!==m)throw new Error("Rename returned a non-canonical participant. No edits applied.");let I=y(m),{content:A}=await d.readSourceSnapshot(I,e),x=await d.openFile(I,t,"symbols",e,()=>Promise.resolve(A));if(x?.client!==S||x.uri!==m)throw new Error("A rename participant has a different language server owner. No edits applied.");if(S.documentContent(m)!==A)throw O("A rename participant changed during synchronization. No edits applied.");w.set(m,{file:I,content:A,version:S.documentVersion(m)})}let C=w.size===1?g:await M();if(k!==void 0){let m=Hr(await xe(k,[u.uri,...C.keys()],L,y),P=>P.startsWith("ssh://")?P:on.relative(t,P));if(m!==void 0)throw new Error(m)}let E=[];for(let[m,P]of C){let I=w.get(m);if(!I)throw new Error("Rename discovered a new participant after preflight. No edits applied.");let A=await _e(P,W=>({uri:m,start:W.range.start,text:ne(I.content,W.range)}),T,L);if(A.length===0)continue;let x=hs(I.content),j=A.map(W=>({from:x(W.range.start),to:x(W.range.end),insert:W.newText}));E.push({source:I.file,expectedContent:I.content,changes:j,rebase:a(W=>Ii(I.content,W,A,j,T[1]??"",s,d.languageId(on.extname(I.file))),"rebase")})}return b(),{files:E}}a(Mi,"planRename");async function Ni(t){await $i(t)}a(Ni,"registerLsp");async function $i(t,e){let n=new ut,r=vn(t),s,o=new Promise(h=>s=h),i=new Map,c=new nt,l=!1,d=a(async(h,w=!1,b)=>{if(b?.throwIfAborted(),l)throw new Error("LSP session has ended");let L=JSON.stringify([h,w]),T=i.get(L);if(T?.controller.signal.aborted)return await ee(T.promise.catch(()=>{}),b),i.get(L)===T&&i.delete(L),d(h,w,b);if(!T){T=new be(async M=>{let g=e?await e.loadRegistry(h,w,M):await Ui(h,w,M),C=await ji(t,h);if(M.throwIfAborted(),l)throw new Error("LSP session has ended");return fe.init(g,e?.workspace(h),{idleTimeoutMs:C,sharedServers:c})});let k=T;i.set(L,k),k.promise.catch(()=>{i.get(L)===k&&i.delete(L)})}return T.wait(b)},"managerFor"),u=a(async(h,w,b)=>{if(b?.throwIfAborted(),e)return e.resolveProject(h,w,b);let L=await tr(w,h,"lsp-servers",ve,b);return b?.throwIfAborted(),L===void 0?void 0:{cwd:L,external:L!==Oi.resolve(w)}},"resolveLspProject"),p=a(async(h,w,b)=>{if(b?.throwIfAborted(),!w)return d(h,!1,b);let L=await u(w,h,b);if(b?.throwIfAborted(),!L)throw new Error("No language server project for this source");return d(L.cwd,L.external,b)},"managerForFile"),f={...nn(p),name:"pi-agent-ide-lsp",priority:200},y={protocol:Kn,apiVersion:5,id:"lsp",setup(h){h.addTool(f),h.addDiagnosticSource(mr(d,u))}};t.on("session_shutdown",async()=>{l=!0,await Promise.allSettled([...i.values()].map(async h=>{h.settled||h.controller.abort(new Error("LSP session has ended")),await(await h.promise).shutdownAll()})),i.clear()});let S={protocol:bn,apiVersion:Sn,id:"lsp",setup(h){h.addHandler({stage:"read",when:{resolvedBy:"any",contentKind:"text"},handler:Xn()})}};await Promise.all([Yn(t,y),Vn(t,{protocol:Ln,apiVersion:Rn,id:"lsp-declarations",setup(h){h.onDidEdit(async w=>{await Promise.all([...i.values()].filter(b=>b.settled).map(b=>b.promise.then(L=>L.syncEditedSource(w.source,w.after.content),()=>{})))}),h.tool("replace").addHandler({stage:"text-pre-edit",when:a(w=>n.matches(w),"when"),handler:a(w=>ys(w,p,n,r)??w,"handler")})}}),_n(t,S),Gn(t,Mr),qn(t,{protocol:Dn,apiVersion:Tn,id:"lsp-search",setup(h){s({api:h,resolver:ds(p,h.registerSelection,void 0,n)})}}),gs(t,o)])}a($i,"registerLspWithOwner");async function ji(t,e){try{let{value:n}=await Bn(t.events,Ke,e);if(typeof n!="string")throw new Error(`Invalid ${Ke} setting`);return vt(n)}catch(n){if(n instanceof Error&&"code"in n&&n.code===zn)return vt("");throw n}}a(ji,"readIdleTimeoutMs");async function Ui(t,e,n){let r=e?t:process.env.PI_AGENT_IDE_CONFIG_DIR??t;return ie.fromPackageDir(r,{signal:n,includeGlobal:!e,requireBuiltInEvidence:e,recipes:ve})}a(Ui,"loadRegistry");export{ve as a,ie as b,jr as c,Ur as d,Ni as e,$i as f};