pi-agent-ide 0.7.0 → 0.7.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 (218) hide show
  1. package/CHANGELOG.md +7 -0
  2. package/dist/chunk-2TRHFMCZ.js +11 -0
  3. package/dist/{chunk-FXNKMNSJ.js → chunk-4GCWGE2C.js} +1 -1
  4. package/dist/chunk-4XMY4H4V.js +1 -0
  5. package/dist/{chunk-3HYXQ4YA.js → chunk-76ZK5ODR.js} +2 -2
  6. package/dist/{chunk-6CZO43OH.js → chunk-BU7IZLKB.js} +1 -1
  7. package/dist/chunk-CWD4O5PM.js +3 -0
  8. package/dist/chunk-D3WTDA6V.js +2 -0
  9. package/dist/chunk-GXEGY7GV.js +1 -0
  10. package/dist/{chunk-GBLKIB6O.js → chunk-HZEY4GT4.js} +1 -1
  11. package/dist/{chunk-S5LXX32D.js → chunk-LEEQIQ7D.js} +6 -6
  12. package/dist/chunk-NRZO5KJT.js +9 -0
  13. package/dist/chunk-OMVRLWMX.js +5 -0
  14. package/dist/{chunk-KR36BT5E.js → chunk-PGIVHICI.js} +1 -1
  15. package/dist/{chunk-YRF7OATP.js → chunk-PKKDDIWW.js} +1 -1
  16. package/dist/{chunk-EDURPQAV.js → chunk-QRJLIV6P.js} +6 -6
  17. package/dist/{chunk-OBNING2A.js → chunk-S5PL5DFQ.js} +1 -1
  18. package/dist/chunk-VMTR74FF.js +2 -0
  19. package/dist/{chunk-PYPPV2F5.js → chunk-WMO6RNE2.js} +1 -1
  20. package/dist/{chunk-3JO7QFIL.js → chunk-WU6ZK6YD.js} +1 -1
  21. package/dist/{chunk-F5YZG77W.js → chunk-XH5WN5XA.js} +1 -1
  22. package/dist/{chunk-AJRIASPQ.js → chunk-YP46DVVP.js} +1 -1
  23. package/dist/entry-11.js +1 -1
  24. package/dist/entry-13.js +1 -1
  25. package/dist/entry-14.js +1 -1
  26. package/dist/entry-15.js +1 -1
  27. package/dist/entry-17.js +1 -1
  28. package/dist/entry-25.js +2 -2
  29. package/dist/entry-26.js +1 -1
  30. package/dist/entry-27.js +2 -2
  31. package/dist/entry-28.js +1 -1
  32. package/dist/entry-29.js +1 -1
  33. package/dist/entry-31.js +13 -12
  34. package/dist/entry-33.js +1 -1
  35. package/dist/entry-37.js +6 -6
  36. package/dist/entry-41.js +1 -1
  37. package/dist/entry-43.js +1 -1
  38. package/dist/entry-44.js +1 -1
  39. package/dist/entry-45.js +13 -14
  40. package/dist/entry-46.js +1 -1
  41. package/dist/entry-49.js +1 -1
  42. package/dist/entry-50.js +1 -1
  43. package/dist/entry-51.js +2 -2
  44. package/dist/entry-53.js +1 -1
  45. package/dist/entry-54.js +1 -1
  46. package/dist/entry-56.js +1 -1
  47. package/dist/entry-57.js +1 -1
  48. package/dist/entry-58.js +1 -1
  49. package/dist/entry-60.js +1 -1
  50. package/dist/entry-62.js +1 -1
  51. package/dist/entry-65.js +1 -1
  52. package/dist/entry-68.js +1 -1
  53. package/dist/entry-70.js +1 -1
  54. package/dist/entry-75.js +1 -1
  55. package/dist/entry-77.js +33 -34
  56. package/dist/entry-78.js +1 -1
  57. package/dist/entry-79.js +1 -1
  58. package/dist/entry-80.js +1 -1
  59. package/dist/entry-82.js +2 -2
  60. package/dist/entry-83.js +1 -1
  61. package/dist/entry-84.js +1 -1
  62. package/dist/entry-85.js +1 -1
  63. package/dist/entry-86.js +1 -1
  64. package/dist/pi-agent-ide.js +14 -9
  65. package/docs/agent-guides/editing.md +35 -46
  66. package/docs/agent-guides/read-resources.md +5 -9
  67. package/docs/agent-guides/search-code.md +12 -17
  68. package/docs/agent-guides/select-code.md +61 -140
  69. package/docs/structured-results.md +27 -62
  70. package/docs/tools.md +6 -10
  71. package/node_modules/pi-agent-doctor/package.json +1 -1
  72. package/node_modules/pi-agent-documentation/package.json +1 -1
  73. package/node_modules/pi-agent-filesystem/index.ts +7 -6
  74. package/node_modules/pi-agent-filesystem/package.json +7 -7
  75. package/node_modules/pi-agent-filesystem-image/package.json +3 -3
  76. package/node_modules/pi-agent-filesystem-jq/index.ts +4 -3
  77. package/node_modules/pi-agent-filesystem-jq/package.json +5 -5
  78. package/node_modules/pi-agent-filesystem-pdf/package.json +3 -3
  79. package/node_modules/pi-agent-filesystem-text/package.json +3 -3
  80. package/node_modules/pi-agent-ide-ast/package.json +13 -13
  81. package/node_modules/pi-agent-ide-ast/src/extension.ts +7 -4
  82. package/node_modules/pi-agent-ide-ast/src/search-resolver.ts +35 -6
  83. package/node_modules/pi-agent-ide-ast/src/select-presentation.ts +1 -1
  84. package/node_modules/pi-agent-ide-ast/src/select-schema.ts +2 -2
  85. package/node_modules/pi-agent-ide-ast/src/tool-select.ts +18 -1
  86. package/node_modules/pi-agent-ide-changes/index.ts +4 -3
  87. package/node_modules/pi-agent-ide-changes/package.json +8 -8
  88. package/node_modules/pi-agent-ide-formatter/package.json +3 -3
  89. package/node_modules/pi-agent-ide-languages/package.json +2 -2
  90. package/node_modules/pi-agent-ide-lint/package.json +7 -7
  91. package/node_modules/pi-agent-ide-lsp/index.ts +3 -3
  92. package/node_modules/pi-agent-ide-lsp/package.json +9 -9
  93. package/node_modules/pi-agent-ide-lsp/src/search-resolver.ts +5 -1
  94. package/node_modules/pi-agent-image/package.json +2 -2
  95. package/node_modules/pi-agent-invariant/package.json +1 -1
  96. package/node_modules/pi-agent-pdf/package.json +2 -2
  97. package/node_modules/pi-agent-read/package.json +7 -7
  98. package/node_modules/pi-agent-read/src/api/plugin-protocol.ts +1 -1
  99. package/node_modules/pi-agent-read/src/api/read-parameters.ts +38 -1
  100. package/node_modules/pi-agent-read/src/api/tools/read.ts +7 -1
  101. package/node_modules/pi-agent-read/src/core/extension.ts +7 -1
  102. package/node_modules/pi-agent-read/src/core/read-core.ts +50 -35
  103. package/node_modules/pi-agent-read/src/core/tools/read/structured-result.ts +3 -3
  104. package/node_modules/pi-agent-read/src/core/tools/tool-read.ts +9 -2
  105. package/node_modules/pi-agent-resource/package.json +1 -1
  106. package/node_modules/pi-agent-resource/src/result-targets.ts +183 -9
  107. package/node_modules/pi-agent-resource/src/tool-result.ts +13 -1
  108. package/node_modules/pi-agent-search/package.json +5 -5
  109. package/node_modules/pi-agent-search/src/api/search-parameters.ts +1 -1
  110. package/node_modules/pi-agent-search-text/index.ts +1 -1
  111. package/node_modules/pi-agent-search-text/package.json +7 -7
  112. package/node_modules/pi-agent-text/package.json +2 -2
  113. package/node_modules/pi-agent-text-anchor-constant/package.json +3 -3
  114. package/node_modules/pi-agent-text-anchor-exact/index.ts +65 -4
  115. package/node_modules/pi-agent-text-anchor-exact/package.json +3 -3
  116. package/node_modules/pi-agent-text-anchor-exact/src/anchor.ts +12 -2
  117. package/node_modules/pi-agent-text-anchor-line-hash/index.ts +4 -3
  118. package/node_modules/pi-agent-text-anchor-line-hash/package.json +5 -5
  119. package/node_modules/pi-agent-text-editor/package.json +9 -9
  120. package/node_modules/pi-agent-text-editor/src/api/mutation-result.ts +3 -1
  121. package/node_modules/pi-agent-text-editor/src/core/extension.ts +10 -3
  122. package/node_modules/pi-agent-text-editor/src/core/file-operations.ts +3 -13
  123. package/node_modules/pi-agent-text-editor/src/core/native-text-edit-batch.ts +18 -11
  124. package/node_modules/pi-agent-text-editor/src/core/structured-result.ts +43 -209
  125. package/node_modules/pi-agent-text-editor/src/core/text-mutation.ts +37 -31
  126. package/node_modules/pi-agent-text-editor/src/core/tool-call-interceptor/coordinator.ts +1 -1
  127. package/node_modules/pi-agent-text-editor/src/tools/text-tool-schema-properties.ts +2 -7
  128. package/node_modules/pi-agent-text-editor/src/tools/tool-text-copy.ts +1 -1
  129. package/node_modules/pi-agent-text-editor/src/tools/tool-text-delete.ts +2 -2
  130. package/node_modules/pi-agent-text-editor/src/tools/tool-text-move.ts +1 -1
  131. package/node_modules/pi-agent-text-editor/src/tools/tool-text-replace.ts +1 -1
  132. package/node_modules/pi-agent-text-editor-renderer/package.json +5 -5
  133. package/node_modules/pi-agent-text-editor-stale-anchor/package.json +4 -4
  134. package/node_modules/pi-agent-tool-call-interception/package.json +2 -2
  135. package/node_modules/pi-agent-tool-call-interception/src/index.ts +3 -0
  136. package/node_modules/pi-agent-tool-ui/package.json +1 -1
  137. package/node_modules/pi-agent-web/index.ts +4 -3
  138. package/node_modules/pi-agent-web/package.json +7 -7
  139. package/node_modules/pi-agent-web-html/package.json +2 -2
  140. package/node_modules/pi-agent-web-image/package.json +3 -3
  141. package/node_modules/pi-agent-web-pdf/package.json +3 -3
  142. package/node_modules/pi-agent-web-text/package.json +3 -3
  143. package/package.json +35 -35
  144. package/src/composite/text-results.ts +221 -0
  145. package/src/documentation/extension.ts +11 -9
  146. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/index.ts +7 -6
  147. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/package.json +7 -7
  148. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-image/package.json +3 -3
  149. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-jq/index.ts +4 -3
  150. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-jq/package.json +5 -5
  151. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-pdf/package.json +3 -3
  152. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-text/package.json +3 -3
  153. package/src/extensions/pi-agent-read/extensions/pi-agent-web/index.ts +4 -3
  154. package/src/extensions/pi-agent-read/extensions/pi-agent-web/package.json +7 -7
  155. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-html/package.json +2 -2
  156. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-image/package.json +3 -3
  157. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-pdf/package.json +3 -3
  158. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-text/package.json +3 -3
  159. package/src/extensions/pi-agent-read/package.json +7 -7
  160. package/src/extensions/pi-agent-read/src/api/plugin-protocol.ts +1 -1
  161. package/src/extensions/pi-agent-read/src/api/read-parameters.ts +38 -1
  162. package/src/extensions/pi-agent-read/src/api/tools/read.ts +7 -1
  163. package/src/extensions/pi-agent-read/src/core/extension.ts +7 -1
  164. package/src/extensions/pi-agent-read/src/core/read-core.ts +50 -35
  165. package/src/extensions/pi-agent-read/src/core/tools/read/structured-result.ts +3 -3
  166. package/src/extensions/pi-agent-read/src/core/tools/tool-read.ts +9 -2
  167. package/src/extensions/pi-agent-search/package.json +5 -5
  168. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/index.ts +1 -1
  169. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/package.json +7 -7
  170. package/src/extensions/pi-agent-search/src/api/search-parameters.ts +1 -1
  171. package/src/extensions/pi-agent-text-editor/package.json +9 -9
  172. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-constant/package.json +3 -3
  173. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-exact/index.ts +65 -4
  174. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-exact/package.json +3 -3
  175. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-exact/src/anchor.ts +12 -2
  176. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-line-hash/index.ts +4 -3
  177. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-line-hash/package.json +5 -5
  178. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-renderer/package.json +5 -5
  179. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-stale-anchor/package.json +4 -4
  180. package/src/extensions/pi-agent-text-editor/src/api/mutation-result.ts +3 -1
  181. package/src/extensions/pi-agent-text-editor/src/core/extension.ts +10 -3
  182. package/src/extensions/pi-agent-text-editor/src/core/file-operations.ts +3 -13
  183. package/src/extensions/pi-agent-text-editor/src/core/native-text-edit-batch.ts +18 -11
  184. package/src/extensions/pi-agent-text-editor/src/core/structured-result.ts +43 -209
  185. package/src/extensions/pi-agent-text-editor/src/core/text-mutation.ts +37 -31
  186. package/src/extensions/pi-agent-text-editor/src/core/tool-call-interceptor/coordinator.ts +1 -1
  187. package/src/extensions/pi-agent-text-editor/src/tools/text-tool-schema-properties.ts +2 -7
  188. package/src/extensions/pi-agent-text-editor/src/tools/tool-text-copy.ts +1 -1
  189. package/src/extensions/pi-agent-text-editor/src/tools/tool-text-delete.ts +2 -2
  190. package/src/extensions/pi-agent-text-editor/src/tools/tool-text-move.ts +1 -1
  191. package/src/extensions/pi-agent-text-editor/src/tools/tool-text-replace.ts +1 -1
  192. package/src/pi-agent-ide.ts +4 -1
  193. package/src/plugins/pi-agent-ide-ast/package.json +13 -13
  194. package/src/plugins/pi-agent-ide-ast/src/extension.ts +7 -4
  195. package/src/plugins/pi-agent-ide-ast/src/search-resolver.ts +35 -6
  196. package/src/plugins/pi-agent-ide-ast/src/select-presentation.ts +1 -1
  197. package/src/plugins/pi-agent-ide-ast/src/select-schema.ts +2 -2
  198. package/src/plugins/pi-agent-ide-ast/src/tool-select.ts +18 -1
  199. package/src/plugins/pi-agent-ide-changes/index.ts +4 -3
  200. package/src/plugins/pi-agent-ide-changes/package.json +8 -8
  201. package/src/plugins/pi-agent-ide-debugger/index.ts +5 -3
  202. package/src/plugins/pi-agent-ide-diagnostics/src/extension.ts +5 -3
  203. package/src/plugins/pi-agent-ide-formatter/package.json +3 -3
  204. package/src/plugins/pi-agent-ide-languages/package.json +2 -2
  205. package/src/plugins/pi-agent-ide-lint/package.json +7 -7
  206. package/src/plugins/pi-agent-ide-lsp/index.ts +3 -3
  207. package/src/plugins/pi-agent-ide-lsp/package.json +9 -9
  208. package/src/plugins/pi-agent-ide-lsp/src/search-resolver.ts +5 -1
  209. package/src/plugins/pi-agent-ide-terminal/src/resources.ts +8 -6
  210. package/src/plugins/pi-agent-ide-vision/index.ts +12 -4
  211. package/dist/chunk-4NIFBFFR.js +0 -11
  212. package/dist/chunk-7LZKOHH2.js +0 -1
  213. package/dist/chunk-FK42RSF4.js +0 -1
  214. package/dist/chunk-KBP3QUDT.js +0 -2
  215. package/dist/chunk-OE7QVAI2.js +0 -5
  216. package/dist/chunk-SILJ3OL4.js +0 -9
  217. package/dist/chunk-SQKAXYIR.js +0 -2
  218. package/dist/chunk-VCGNVTXQ.js +0 -1
package/CHANGELOG.md CHANGED
@@ -1,5 +1,12 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.7.1 — 2026-10-05
4
+
5
+ - Reduced prompt size by keeping internal result structures out of agent-facing tool schemas.
6
+ - Restored readable string results for agents. Structured records stay internal because exposing their layout made tool use more complicated.
7
+ - Preserved tool composition, including Read, Search, Select, editing and Codemode store/load. Results carry registered references instead of exposing internal fields.
8
+ - Made Copy and Move replace existing destination files without a separate overwrite flag.
9
+
3
10
  ## 0.7.0 — 2026-10-05
4
11
 
5
12
  ### Native tool composition
@@ -0,0 +1,11 @@
1
+ import{d as B,h as M}from"./chunk-XH5WN5XA.js";import{a as N}from"./chunk-4XMY4H4V.js";import{h as w,i as P}from"./chunk-CWD4O5PM.js";import{a as y}from"./chunk-EI7MMDWY.js";import{Allow as $}from"partial-json";import{Guard as f}from"typebox-guard/guard";import{Allow as F,parse as H}from"partial-json";function _(o,e=F.ALL){if(!(!o||o.trim().length===0))try{let t=H(o,e);return t==null||typeof t!="object"||Array.isArray(t)?void 0:t}catch{return}}y(_,"resolvePartial");var R=class{static{y(this,"PartialToolRecoveryRegistry")}registrations=new Map;states=new Map;register(e){this.registrations.set(e.recoveryKey??e.toolName,e)}unregister(e){for(let[t,n]of this.registrations)(n.toolName===e||t===e)&&this.registrations.delete(t)}recoveryKeyFor(e){for(let[t,n]of this.registrations)if(n.toolName===e||n.toolNames?.includes(e)||t===e)return t}async recover(e){let t=this.states.get(e.contentIndex);if(t?.status==="done")return t.result;if(t?.status==="running")return t.promise;let n=this.registrations.get(e.recoveryKey??e.toolName);if(!n)return;let r=this.run(n,e);this.states.set(e.contentIndex,{status:"running",promise:r});let a=await r;return this.states.set(e.contentIndex,{status:"done",result:a}),a}cancel(e){this.states.delete(e)}cleanup(e){this.states.delete(e)}cleanupAll(){this.states.clear()}async run(e,t){let n=[],r=new Set(t.completedEntryIndexes),a=new Set(t.blockedEntryIndexes),i=e.extractEntries(t).filter(c=>{if(r.has(c.index))return n.push({index:c.index,reason:"entry already completed before recovery"}),!1;if(a.has(c.index))return n.push({index:c.index,reason:"entry was blocked by a guard"}),!1;let g=e.isCompleteEntry?.(c,t)??c.complete;return g||n.push({index:c.index,reason:t.recoverCompleteBatch?"entry was incomplete in the recovered batch":"entry was incomplete before the stale entry"}),!t.recoverCompleteBatch&&t.staleEntryIndex!==void 0&&c.index>=t.staleEntryIndex?!1:g}),s=e.filterEntries?.(i,t)??i,d=new Set(s.map(c=>c.index));for(let c of i)d.has(c.index)||n.push({index:c.index,reason:"entry was excluded by recovery filtering"});let u=[];for(let c of s)try{e.validateEntry?.(c,t),u.push(c)}catch(g){n.push({index:c.index,reason:g instanceof Error?g.message:String(g)})}let m={toolName:t.toolName,contentIndex:t.contentIndex,...t.staleEntryIndex!==void 0&&{staleEntryIndex:t.staleEntryIndex},staleDetails:t.staleDetails};if(u.length===0)return{...m,status:"skipped",appliedEntries:[],skippedEntries:n};try{let c=e.buildParams(u,t),g=await e.execute(c,{contentIndex:t.contentIndex,toolCallId:t.toolCallId,toolName:t.toolName,cwd:t.cwd,ctx:t.ctx,signal:new AbortController().signal});return{...m,status:"recovered",appliedEntries:e.getAppliedEntries?.(g,u,t)??u.map(b=>b.index),skippedEntries:n,normalResult:g}}catch(c){return{...m,status:"failed",appliedEntries:[],skippedEntries:n,error:c instanceof Error?c.message:String(c)}}}};import{createAssistantMessageEventStream as W}from"@earendil-works/pi-ai";var O=Symbol.for("pi-agent-text-editor.tool-call-interceptor.streaming-provider.state");function K(o,e,t,n){let r=new Map,a={context:void 0,processStreamEvent:e,markStreamEventProcessed:t,finalizeStreamInterception:n},l=y((i,s)=>{if(!i)return;let d=s.modelRegistry.getProvider(i.provider);if(!d)return;let u=r.get(i.provider);if(u){if(u.subscribers.add(a),u.api===i.api&&d.streamSimple===u.wrapper)return;u.api=i.api;let p=s.modelRegistry.getRegisteredProviderConfig(i.provider);o.registerProvider(i.provider,{...p,api:i.api,streamSimple:u.wrapper});return}let m=d.streamSimple[O];if(m){if(m.subscribers.add(a),r.set(i.provider,m),m.api===i.api)return;m.api=i.api;let p=s.modelRegistry.getRegisteredProviderConfig(i.provider);o.registerProvider(i.provider,{...p,api:i.api,streamSimple:m.wrapper});return}let c=d.streamSimple.bind(d),g=new Set([a]),b=y((p,v,C)=>U(c,p,v,C,g),"wrapper"),E={api:i.api,delegate:c,wrapper:b,subscribers:g};b[O]=E;let h=s.modelRegistry.getRegisteredProviderConfig(i.provider);o.registerProvider(i.provider,{...h,api:i.api,streamSimple:b}),r.set(i.provider,E)},"install");o.on("before_provider_request",(i,s)=>{a.context=s,l(s.model,s)}),o.on("turn_start",(i,s)=>{a.context=s,l(s.model,s)}),o.on("agent_start",(i,s)=>{a.context=s,l(s.model,s)}),o.on("session_start",(i,s)=>{a.context=s,l(s.model,s)}),o.on("model_select",(i,s)=>{a.context=s,l(i.model,s)}),o.on("session_shutdown",()=>{for(let[i,s]of r)s.subscribers.delete(a),s.subscribers.size===0&&o.unregisterProvider(i);r.clear(),a.context=void 0})}y(K,"registerStreamingInterceptorProvider");function U(o,e,t,n,r){let a=W(),l=new AbortController,i=n?.signal,s=!1,d=Y(e),u=new Set,m=new Set,c=new Set,g=new Set,b=y(h=>{for(let p of r)p.markStreamEventProcessed(h)},"markStreamEventProcessed"),E=y(()=>{l.abort()},"abortFromParent");return i&&(i.aborted?l.abort():i.addEventListener("abort",E,{once:!0})),(async()=>{try{let h=o(e,t,{...n,signal:l.signal});for await(let p of h){if(s)continue;p.type==="done"?d=structuredClone(p.message):p.type==="error"?d=structuredClone(p.error):d=structuredClone(p.partial),Q(p,u);let v;for(let C of r){let I=C.context;if(I){let T=await C.processStreamEvent(p,I);v??=T}}if(b(p),q(p,m,c,g),a.push(structuredClone(p)),v){if(p.type==="toolcall_delta"||p.type==="toolcall_end")for(let x of r)x.finalizeStreamInterception(p.contentIndex);s=!0,l.abort();let C=p.type==="toolcall_delta"||p.type==="toolcall_end"?p.contentIndex:void 0,I={...d,content:d.content.filter((x,A)=>u.has(A)&&(C===void 0||A<=C||g.has(A))).map(x=>x.type==="toolCall"&&x.id===v.toolCallId?{...x,arguments:structuredClone(v.arguments)}:x)};V(a,b,I,u,m,c,g);let{errorMessage:T,...L}=I;a.push({type:"done",reason:"toolUse",message:{...L,stopReason:"toolUse"}}),a.end();continue}if(p.type==="done"||p.type==="error"){a.end();return}}}catch(h){if(s)return;let p=d,v=i?.aborted===!0?"aborted":"error",C={...p,stopReason:v,errorMessage:h instanceof Error?h.message:String(h)};a.push({type:"error",reason:v,error:C}),a.end()}finally{i?.removeEventListener("abort",E)}})(),a}y(U,"wrapStream");function Q(o,e){(o.type==="text_start"||o.type==="thinking_start"||o.type==="toolcall_start")&&e.add(o.contentIndex)}y(Q,"rememberStartEvent");function q(o,e,t,n){switch(o.type){case"text_end":{e.add(o.contentIndex);break}case"thinking_end":{t.add(o.contentIndex);break}case"toolcall_end":{n.add(o.contentIndex);break}}}y(q,"rememberEndEvent");function V(o,e,t,n,r,a,l){for(let[i,s]of t.content.entries())if(n.has(i)){if(s.type==="text"&&!r.has(i)){let d={type:"text_end",contentIndex:i,content:s.text,partial:t};e(d),o.push(d)}else if(s.type==="thinking"&&!a.has(i)){let d={type:"thinking_end",contentIndex:i,content:s.thinking,partial:t};e(d),o.push(d)}else if(s.type==="toolCall"&&!l.has(i)){let d={type:"toolcall_end",contentIndex:i,toolCall:s,partial:t};e(d),o.push(d)}}}y(V,"emitMissingEndEvents");function Y(o){return{role:"assistant",content:[],api:o.api,provider:o.provider,model:o.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"toolUse",timestamp:Date.now()}}y(Y,"emptyAssistantMessage");var Z="agentic-ide-partial-tool-recovery",G="pi-agent-text-editor/tool-call-annotation",S=new WeakMap,k=class{constructor(e){this.pi=e;e.on("tool_call",t=>{let n=this.toolCallRecords.get(t.toolCallId),r=n?.blockExecution?n.guardResult:void 0;return r?{block:!0,reason:r.content.filter(l=>l.type==="text").map(l=>l.text).join(`
2
+ `)||`Tool call ${t.toolName} was blocked by a streaming interceptor.`}:void 0}),e.on("tool_result",t=>{let n=this.toolCallBatchEntryIndexes.get(t.toolCallId);n!==void 0&&this.completedBatchEntryIndexes.add(n);let r=this.toolCallRecords.get(t.toolCallId)?.guardResult;if(this.toolCallRecords.delete(t.toolCallId),r){let a=r.details,l=typeof a=="object"&&a!==null&&"effect"in a&&(a.effect==="not-applied"||a.effect==="applied")?a.effect:"unknown",i=r.content.flatMap(s=>s.type==="text"?[s.text]:[]).join(`
3
+ `);return P({content:r.content,details:a},N(t.toolName),{status:"error",errors:[w(i,"INTERCEPTED")],data:{operation:t.toolName,operationId:t.toolCallId,effect:l,files:[]}})}}),e.on("message_update",async(t,n)=>{let r=t.assistantMessageEvent;this.consumeProcessedStreamEvent(r)||await this.processStreamEvent(r,n)}),e.on("message_end",async t=>{if(await this.finalizeRecovery(),this.annotateIncompleteCalls(),t.message.role!=="assistant")return;let n=this.pendingAbortReason;if(this.pendingAbortReason=void 0,!(n===void 0||t.message.stopReason!=="aborted"))return{message:{...t.message,errorMessage:n}}}),e.on("agent_end",async()=>{await this.finalizeRecovery(),this.annotateIncompleteCalls(),this.cleanupAll()})}static{y(this,"InterceptorImpl")}handlers=new Map;recoveryRegistry=new R;pendingRecoveryBlocks=[];pendingAbortReason;recoveryAppliedBatchIndexes=new Set;partialBuffers=new Map;completeArgumentContentIndices=new Set;streamedBatchEntries=new Map;batchEntryIndexes=new Map;toolCallBatchEntryIndexes=new Map;completedBatchEntryIndexes=new Set;nextBatchEntryIndex=0;contentNames=new Map;contentToolCallIds=new Map;pendingToolCallAnnotations=new Map;emittedToolCallAnnotationKinds=new Map;abortedContentIndices=new Set;dispatchQueues=new Map;abortCleanups=new Map;processedStreamEvents=new WeakSet;processedStreamEventKeys=new Map;toolCallRecords=new Map;blockedCallSink;processStreamEvent(e,t){if(e.type==="toolcall_start"){let n=e.partial.content[e.contentIndex];if(n?.type==="toolCall"){let r=this.getOrCreateBatchEntryIndex(e.contentIndex);this.contentNames.set(e.contentIndex,n.name),typeof n.id=="string"&&this.bindToolCallId(e.contentIndex,n.id),this.partialBuffers.set(e.contentIndex,""),this.streamedBatchEntries.set(e.contentIndex,{index:r,toolName:n.name,args:{},complete:!1}),this.installAbortCleanup(e.contentIndex,t.signal)}return Promise.resolve(void 0)}return e.type==="toolcall_delta"?this.enqueue(e.contentIndex,async()=>{let n=this.contentNames.get(e.contentIndex),r=this.contentToolCallIds.get(e.contentIndex);if(!n)return;let a=(this.partialBuffers.get(e.contentIndex)??"")+e.delta;this.partialBuffers.set(e.contentIndex,a),this.installAbortCleanup(e.contentIndex,t.signal);let l=_(a,$.OBJ|$.ARR)??{},i=ee(a),s=this.getOrCreateBatchEntryIndex(e.contentIndex);this.streamedBatchEntries.set(e.contentIndex,{index:s,toolName:n,args:l,complete:i!==void 0});let d=this.handlers.get(n);if(!r||!d||d.length===0||!i&&Object.keys(l).length===0)return;let u=i!==void 0;if(u&&this.completeArgumentContentIndices.has(e.contentIndex))return;u&&this.completeArgumentContentIndices.add(e.contentIndex);let m=i??l,c=await this.dispatchHandlers(d,{toolCall:{id:r,name:n,arguments:m},args:m,...!u&&{partialArgs:l},batchEntryIndex:s,batchEntries:this.getBatchEntries(s),contentIndex:e.contentIndex,cwd:t.cwd,signal:t.signal,ctx:t});return c&&this.rememberOriginalArguments(c.toolCallId,c.arguments),c}):e.type==="toolcall_end"?this.enqueue(e.contentIndex,async()=>{let n=e.toolCall.name,r=this.handlers.get(n),a=this.getOrCreateBatchEntryIndex(e.contentIndex);this.bindToolCallId(e.contentIndex,e.toolCall.id);let l=this.toolCallRecords.get(e.toolCall.id);this.toolCallRecords.set(e.toolCall.id,{originalArguments:structuredClone(e.toolCall.arguments),...l?.guardResult&&{guardResult:l.guardResult},...l?.blockExecution&&{blockExecution:!0}}),this.streamedBatchEntries.set(e.contentIndex,{index:a,toolName:n,args:e.toolCall.arguments,complete:!1});let i=!this.completeArgumentContentIndices.has(e.contentIndex),s;i&&(this.completeArgumentContentIndices.add(e.contentIndex),s=r&&r.length>0?await this.dispatchHandlers(r,{toolCall:e.toolCall,args:e.toolCall.arguments,batchEntryIndex:a,batchEntries:this.getBatchEntries(a),contentIndex:e.contentIndex,cwd:t.cwd,signal:t.signal,ctx:t}):void 0);let d=this.streamedBatchEntries.get(e.contentIndex);return d&&this.streamedBatchEntries.set(e.contentIndex,{...d,complete:!0}),this.cleanupContent(e.contentIndex,n),s}):Promise.resolve(void 0)}markStreamEventProcessed(e){this.processedStreamEvents.add(e);let t=j(e);t!==void 0&&this.processedStreamEventKeys.set(t,(this.processedStreamEventKeys.get(t)??0)+1)}consumeProcessedStreamEvent(e){let t=this.processedStreamEvents.delete(e),n=j(e);if(n===void 0)return t;let r=this.processedStreamEventKeys.get(n)??0;return r===0?t:(r===1?this.processedStreamEventKeys.delete(n):this.processedStreamEventKeys.set(n,r-1),!0)}finalizeStreamInterception(e){this.cleanupTransientContent(e,void 0,!0)}getToolCallRecord(e){return this.toolCallRecords.get(e)}rememberOriginalArguments(e,t){let n=this.toolCallRecords.get(e);n&&this.toolCallRecords.set(e,{originalArguments:structuredClone(t),...n.guardResult&&{guardResult:n.guardResult},...n.blockExecution&&{blockExecution:!0}})}async dispatchHandlers(e,t){for(let n of e){let r=await n.intercept(t);if(r!==void 0){this.pendingRecoveryBlocks.push({blocked:r,ctx:t});let a={content:[{type:"text",text:r.message.content}],details:r.message.details??null};return this.blockedCallSink?.({callId:t.toolCall.id,toolName:t.toolCall.name,arguments:structuredClone(t.args),...t.contentIndex!==void 0&&{contentIndex:t.contentIndex},...t.batchEntryIndex!==void 0&&{batchEntryIndex:t.batchEntryIndex},...r.message.details!==void 0&&{details:r.message.details},result:a,nativeExecutionBlocked:n.blockExecution===!0}),{toolCallId:t.toolCall.id,arguments:structuredClone(t.args),result:this.abortToolCall(r,t,n.name,n.blockExecution===!0)}}}}annotateIncompleteCalls(){for(let[e,t]of this.streamedBatchEntries)!t.complete&&this.contentNames.has(e)&&!this.recoveryAppliedBatchIndexes.has(t.index)&&!this.emittedToolCallAnnotationKinds.get(e)?.has("stale-anchor")&&this.annotateContent(e,{kind:"aborted"})}bindToolCallId(e,t){this.contentToolCallIds.set(e,t);let n=this.batchEntryIndexes.get(e);n!==void 0&&this.toolCallBatchEntryIndexes.set(t,n);let r=this.pendingToolCallAnnotations.get(e);if(r){for(let a of r)this.emitToolCallAnnotation(t,a);this.pendingToolCallAnnotations.delete(e)}}annotateContent(e,t){let n=this.emittedToolCallAnnotationKinds.get(e)??new Set;if(n.has(t.kind))return;n.add(t.kind),this.emittedToolCallAnnotationKinds.set(e,n);let r=this.contentToolCallIds.get(e);if(r){this.emitToolCallAnnotation(r,t);return}let a=this.pendingToolCallAnnotations.get(e)??[];a.push(t),this.pendingToolCallAnnotations.set(e,a)}emitToolCallAnnotation(e,t){let n={toolCallId:e,annotation:t};this.pi.events.emit(G,n)}getOrCreateBatchEntryIndex(e){let t=this.batchEntryIndexes.get(e);if(t!==void 0)return t;let n=this.nextBatchEntryIndex;return this.nextBatchEntryIndex+=1,this.batchEntryIndexes.set(e,n),n}getBatchEntries(e){return[...this.streamedBatchEntries.values()].filter(t=>t.index<=e).sort((t,n)=>t.index-n.index)}getAllBatchEntries(){return[...this.streamedBatchEntries.values()].sort((e,t)=>e.index-t.index)}abortToolCall(e,t,n,r){let a=X(e,n),l=e.annotation?e.annotation.kind==="aborted"&&e.annotation.label===void 0?{...e.annotation,label:a}:e.annotation:e.message.customType==="text-editor-stale-anchor-block"?{kind:"stale-anchor",label:a}:{kind:"aborted",label:a,color:"error"};t.contentIndex!==void 0&&(this.abortedContentIndices.add(t.contentIndex),this.annotateContent(t.contentIndex,l));let i={content:[{type:"text",text:e.message.content}],details:B(e.message.details,l,a)};return this.toolCallRecords.set(t.toolCall.id,{originalArguments:structuredClone(t.args),guardResult:i,...r&&{blockExecution:!0}}),i}async finalizeRecovery(){let e=this.pendingRecoveryBlocks.splice(0);if(e.length===0)return;let t=new Map;for(let n of e){let r=this.recoveryRegistry.recoveryKeyFor(n.ctx.toolCall.name);if(r===void 0)continue;let a=t.get(r)??[];a.push(n),t.set(r,a)}for(let n of t.values()){let r=n[0];if(!r)continue;let a=await this.recoverIfNeeded(r.blocked,r.ctx,this.getAllBatchEntries(),n);if(a===r.blocked)continue;let l=a.message.details,s=(f.IsObjectNotArray(l)&&f.IsObjectNotArray(l.recovery)?l.recovery:void 0)?.appliedEntries;if(Array.isArray(s))for(let d of s)typeof d=="number"&&this.recoveryAppliedBatchIndexes.add(d)}}async recoverIfNeeded(e,t,n,r){if(t.contentIndex===void 0)return e;let a=e.message.details,l=f.IsObjectNotArray(a)&&typeof a.entryIndex=="number"?a.entryIndex:void 0,i=[...new Set(r.map(g=>g.ctx.batchEntryIndex).filter(g=>g!==void 0))],s=[...new Set(r.map(g=>g.ctx.toolCall.id))],d=r.map(g=>g.blocked.message.details),u=r[0],m=u?this.recoveryRegistry.recoveryKeyFor(u.ctx.toolCall.name):void 0;if(!m)return e;let c=await this.recoveryRegistry.recover({contentIndex:t.contentIndex,toolCallId:t.toolCall.id,toolName:t.toolCall.name,...l!==void 0&&{staleEntryIndex:l},staleDetails:a,...t.partialArgs&&{partialArgs:t.partialArgs},args:t.args,batchEntries:n,...t.batchEntryIndex!==void 0&&{batchEntryIndex:t.batchEntryIndex},recoverCompleteBatch:!0,completedEntryIndexes:[...this.completedBatchEntryIndexes],blockedEntryIndexes:i,blockedToolCallIds:s,blockedDetails:d,recoveryKey:m,cwd:t.cwd,ctx:t.ctx});return c&&(c.appliedEntries.length>0||c.skippedEntries.length>0)?re(e,c):e}async enqueue(e,t){let r=(this.dispatchQueues.get(e)??Promise.resolve()).catch(()=>{}).then(t);this.dispatchQueues.set(e,r);try{return await r}finally{this.dispatchQueues.get(e)===r&&this.dispatchQueues.delete(e)}}installAbortCleanup(e,t){if(!t||this.abortCleanups.has(e))return;let n=y(()=>{let r=this.contentNames.get(e),a=r?this.handlers.get(r):void 0;for(let l of a??[])l.onAbort?.(e)},"listener");t.addEventListener("abort",n,{once:!0}),this.abortCleanups.set(e,()=>{t.removeEventListener("abort",n)})}cleanupContent(e,t){this.cleanupTransientContent(e,t),this.recoveryRegistry.cleanup(e)}cleanupTransientContent(e,t,n=!1){let r=t??this.contentNames.get(e),a=r?this.handlers.get(r):void 0;for(let l of a??[])n&&l.onAbort?.(e),l.onContentEnd?.(e);this.abortCleanups.get(e)?.(),this.abortCleanups.delete(e),this.contentNames.delete(e),this.contentToolCallIds.delete(e),this.pendingToolCallAnnotations.delete(e),this.emittedToolCallAnnotationKinds.delete(e),this.completeArgumentContentIndices.delete(e),this.partialBuffers.delete(e),this.abortedContentIndices.delete(e)}cleanupAll(){for(let e of this.handlers.values())for(let t of e)t.onAgentEnd?.();for(let e of this.abortCleanups.values())e();this.abortCleanups.clear(),this.contentNames.clear(),this.contentToolCallIds.clear(),this.pendingToolCallAnnotations.clear(),this.completeArgumentContentIndices.clear(),this.emittedToolCallAnnotationKinds.clear(),this.partialBuffers.clear(),this.streamedBatchEntries.clear(),this.batchEntryIndexes.clear(),this.toolCallBatchEntryIndexes.clear(),this.toolCallRecords.clear(),this.completedBatchEntryIndexes.clear(),this.nextBatchEntryIndex=0,this.abortedContentIndices.clear(),this.pendingAbortReason=void 0,this.dispatchQueues.clear(),this.processedStreamEventKeys.clear(),this.recoveryRegistry.cleanupAll(),this.pendingRecoveryBlocks.length=0,this.recoveryAppliedBatchIndexes.clear()}registerRecovery(e){this.recoveryRegistry.register(e)}unregisterRecovery(e){this.recoveryRegistry.unregister(e)}registerBlockedCallSink(e){this.blockedCallSink=e}register(e){let t=new Set(e.toolNames);for(let[n,r]of this.handlers){let a=r.findIndex(l=>l.name===e.name);a!==-1&&(t.has(n)?(r[a]=e,t.delete(n)):r.splice(a,1))}for(let n of t){let r=this.handlers.get(n)??[];r.push(e),this.handlers.set(n,r)}}unregister(e){for(let[t,n]of this.handlers)this.handlers.set(t,n.filter(r=>r.name!==e))}};function j(o){if(o.type==="toolcall_end")return`${o.type}\0${o.contentIndex}\0${o.toolCall.id}`;if(o.type!=="toolcall_start"&&o.type!=="toolcall_delta")return;let e=o.partial.content[o.contentIndex],t=e?.type==="toolCall"?e.id:"",n=o.type==="toolcall_delta"?o.delta:"";return`${o.type}\0${o.contentIndex}\0${t}\0${n}`}y(j,"toolStreamEventKey");function X(o,e){return o.annotation?.reason?o.annotation.reason:o.annotation?.label?o.annotation.label:o.message.customType==="text-editor-stale-anchor-block"?"Stale Anchor":e.replace(/[-_]+/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").replace(/\s+/g," ").trim().replace(/\b\w/g,t=>t.toUpperCase())||"Blocked"}y(X,"abortReason");function ee(o){try{let e=JSON.parse(o);return f.IsObjectNotArray(e)?e:void 0}catch{return}}y(ee,"parseCompleteArguments");function te(o){let e=o.normalResult;if(!f.IsObjectNotArray(e)||!f.IsObjectNotArray(e.details))return[];let t=e.details.results;if(!Array.isArray(t))return[];let n=f.IsObjectNotArray(o.staleDetails)&&typeof o.staleDetails.path=="string"?o.staleDetails.path:void 0,r=t.filter(f.IsObjectNotArray).map(s=>f.IsObjectNotArray(s.data)?s.data:s),a=n===void 0?r:r.filter(s=>s.path===n),i=(a.length>0?a:r).flatMap(s=>{let d=s.freshAnchors;return Array.isArray(d)?d.filter(u=>typeof u=="string"):[]});return[...new Set(i)]}y(te,"freshAnchorsAfterRecovery");function ne(o,e){let n=o.indexOf(`
4
+
5
+ Current nearby anchors:`);return`${n===-1?o:o.slice(0,n)}
6
+
7
+ Current nearby anchors:
8
+ ${e.map(a=>` ${a}`).join(`
9
+ `)}`}y(ne,"replaceCurrentAnchors");function re(o,e){let t=e.appliedEntries.length,n=t>0?`${t} (indices: ${e.appliedEntries.join(", ")})`:"0",r=e.skippedEntries.length>0?e.skippedEntries.map(u=>`${u.index} (${u.reason})`).join(", "):"none",a=e.error?`Recovery execution failed: ${e.error}.`:"Recovery execution completed.",l=te(e),i=l.length>0&&f.IsObjectNotArray(o.message.details)?{...o.message.details,freshAnchors:l}:o.message.details,s=l.length>0?ne(o.message.content,l):o.message.content,d=l.length>0&&f.IsObjectNotArray(e.staleDetails)?{...e,staleDetails:{...e.staleDetails,freshAnchors:l}}:e;return{message:{customType:Z,content:`${s}
10
+
11
+ [RECOVERY] Status: ${e.status}. Applied entries: ${n}. Skipped entries: ${r}. ${a}`,display:!1,details:{blocked:i,recovery:d}}}}y(re,"makeRecoveryResult");var D=new WeakMap;function z(o){let e=D.get(o);if(e)return e;let t=new k(o);return D.set(o,t),K(o,(n,r)=>t.processStreamEvent(n,r),n=>{t.markStreamEventProcessed(n)},n=>{t.finalizeStreamInterception(n)}),t}y(z,"coordinatorFor");function oe(o,e){z(o).register(e)}y(oe,"registerToolCallInterceptor");function ae(o,e){if(S.get(o)?.(),S.delete(o),e===void 0)return;let t=o.events.on(G,n=>{!f.IsObjectNotArray(n)||typeof n.toolCallId!="string"||!M(n.annotation)||e(n.toolCallId,n.annotation)});S.set(o,t)}y(ae,"registerToolCallAnnotationSink");function Ee(o,e){z(o).registerBlockedCallSink(e)}y(Ee,"registerBlockedToolCallSink");export{oe as a,ae as b,Ee as c};
@@ -1 +1 @@
1
- import{m as c}from"./chunk-SQKAXYIR.js";import{e as a}from"./chunk-ZPT5D4VP.js";import{a as r}from"./chunk-EI7MMDWY.js";import{Type as e}from"typebox";import{Value as i}from"typebox/value";var n="pi-agent-text-editor",p=23,P="pi-agent-text-editor/position",I="pi-agent-text-editor/search",b=`${n}/core/ready`,S=`${n}/plugin/register`,s=e.Function([],e.Unknown()),d=e.Object({tryResolve:s},{additionalProperties:!0}),l=e.Object({lineNumber:e.Integer({minimum:1}),column:e.Integer({minimum:0})}),T=e.Object({start:l,end:l,linewise:e.Optional(e.Boolean())}),R=e.Object({source:e.String({minLength:1}),ranges:e.Optional(e.Array(T))}),x=e.Union([e.Object({kind:e.Literal("not-handled")},{additionalProperties:!0}),e.Object({kind:e.Literal("resolved"),targets:e.Array(R,{minItems:1})},{additionalProperties:!0}),e.Object({kind:e.Literal("rejected"),rejection:e.Object({code:e.Union([e.Literal("invalid"),e.Literal("stale"),e.Literal("missing"),e.Literal("ambiguous")]),reason:e.String(),contextRange:e.Optional(e.Object({offset:e.Number(),limit:e.Number()}))})},{additionalProperties:!0}),e.Object({kind:e.Literal("failed"),error:e.Unknown()},{additionalProperties:!0})]),g=e.String({pattern:"\\S"}),m=e.Object({resolver:e.Unknown(),priority:e.Optional(e.Number())}),y=e.Object({resolver:e.Unknown(),resources:e.Optional(e.Unknown()),kind:e.String({pattern:"\\S"}),type:e.Union([e.Literal("major"),e.Literal("auxiliary"),e.Literal("constant")]),priority:e.Optional(e.Number())}),v=e.Object({protocol:e.Literal(n),apiVersion:e.Literal(p)}),u=e.Object({protocol:e.Literal(n),apiVersion:e.Literal(p),id:e.String(),setup:s}),E=e.Object({plugin:u,accept:s});function k(t){return i.Check(g,t)}r(k,"isTextEditorToolId");function _(t){if(!i.Check(m,t))return!1;let o=t;return c(o.resolver)&&(!("priority"in o)||typeof o.priority=="number")}r(_,"isResourceResolverRegistration");function j(t){if(!i.Check(y,t))return!1;let o=t;return a(o.resolver)&&(!("resources"in o)||i.Check(d,o.resources))&&(!("priority"in o)||typeof o.priority=="number")}r(j,"isTextAnchorResolverRegistration");function C(t){return i.Check(x,t)}r(C,"isTextAnchorResourceResolutionAttempt");function L(t){return i.Check(v,t)}r(L,"isTextEditorCoreReady");function w(t){return i.Check(u,t)}r(w,"isTextEditorPlugin");function N(t){return i.Check(E,t)}r(N,"isTextEditorPluginRegistrationRequest");export{n as a,p as b,P as c,I as d,b as e,S as f,k as g,_ as h,j as i,C as j,L as k,w as l,N as m};
1
+ import{m as c}from"./chunk-CWD4O5PM.js";import{e as a}from"./chunk-ZPT5D4VP.js";import{a as r}from"./chunk-EI7MMDWY.js";import{Type as e}from"typebox";import{Value as i}from"typebox/value";var n="pi-agent-text-editor",p=23,P="pi-agent-text-editor/position",I="pi-agent-text-editor/search",b=`${n}/core/ready`,S=`${n}/plugin/register`,s=e.Function([],e.Unknown()),d=e.Object({tryResolve:s},{additionalProperties:!0}),l=e.Object({lineNumber:e.Integer({minimum:1}),column:e.Integer({minimum:0})}),T=e.Object({start:l,end:l,linewise:e.Optional(e.Boolean())}),R=e.Object({source:e.String({minLength:1}),ranges:e.Optional(e.Array(T))}),x=e.Union([e.Object({kind:e.Literal("not-handled")},{additionalProperties:!0}),e.Object({kind:e.Literal("resolved"),targets:e.Array(R,{minItems:1})},{additionalProperties:!0}),e.Object({kind:e.Literal("rejected"),rejection:e.Object({code:e.Union([e.Literal("invalid"),e.Literal("stale"),e.Literal("missing"),e.Literal("ambiguous")]),reason:e.String(),contextRange:e.Optional(e.Object({offset:e.Number(),limit:e.Number()}))})},{additionalProperties:!0}),e.Object({kind:e.Literal("failed"),error:e.Unknown()},{additionalProperties:!0})]),g=e.String({pattern:"\\S"}),m=e.Object({resolver:e.Unknown(),priority:e.Optional(e.Number())}),y=e.Object({resolver:e.Unknown(),resources:e.Optional(e.Unknown()),kind:e.String({pattern:"\\S"}),type:e.Union([e.Literal("major"),e.Literal("auxiliary"),e.Literal("constant")]),priority:e.Optional(e.Number())}),v=e.Object({protocol:e.Literal(n),apiVersion:e.Literal(p)}),u=e.Object({protocol:e.Literal(n),apiVersion:e.Literal(p),id:e.String(),setup:s}),E=e.Object({plugin:u,accept:s});function k(t){return i.Check(g,t)}r(k,"isTextEditorToolId");function _(t){if(!i.Check(m,t))return!1;let o=t;return c(o.resolver)&&(!("priority"in o)||typeof o.priority=="number")}r(_,"isResourceResolverRegistration");function j(t){if(!i.Check(y,t))return!1;let o=t;return a(o.resolver)&&(!("resources"in o)||i.Check(d,o.resources))&&(!("priority"in o)||typeof o.priority=="number")}r(j,"isTextAnchorResolverRegistration");function C(t){return i.Check(x,t)}r(C,"isTextAnchorResourceResolutionAttempt");function L(t){return i.Check(v,t)}r(L,"isTextEditorCoreReady");function w(t){return i.Check(u,t)}r(w,"isTextEditorPlugin");function N(t){return i.Check(E,t)}r(N,"isTextEditorPluginRegistrationRequest");export{n as a,p as b,P as c,I as d,b as e,S as f,k as g,_ as h,j as i,C as j,L as k,w as l,N as m};
@@ -0,0 +1 @@
1
+ import{d as k,e as S,h as m,i as M}from"./chunk-CWD4O5PM.js";import{a as p}from"./chunk-EI7MMDWY.js";import{Type as t}from"typebox";var T=t.Union([t.Literal("pending"),t.Literal("applied"),t.Literal("not-applied"),t.Literal("unknown")]),b=t.Object({source:t.String(),effect:T,state:t.Optional(t.Union([t.Literal("present"),t.Literal("absent"),t.Literal("unknown")]))},{additionalProperties:!1}),O={effect:T,files:t.Array(b)};function R(s){return t.Object({operation:t.Literal(s),...O,operationId:t.Optional(t.String()),...s==="delete"||s==="flush"?{}:{target:t.Optional(t.String()),targetUnavailable:t.Optional(t.String())}},{additionalProperties:!1})}p(R,"mutationDataSchema");function N(s){return S(R(s))}p(N,"mutationResultSchema");var U=t.Object({id:t.String(),operation:t.String(),effect:T,errors:t.Array(k)},{additionalProperties:!1}),D=t.Object({operation:t.Literal("flush"),...O,operations:t.Array(U)},{additionalProperties:!1}),_=S(D);function u(s){return typeof s=="object"&&s!==null}p(u,"record");function F(s,i,h=[]){let r=s.details,l=u(r)?r:{};if((u(r)&&u(r.nativeEditBatch)?r.nativeEditBatch:void 0)?.state==="accepted")return{status:"success",errors:[],data:{operation:i,effect:"pending",...i!=="delete"&&typeof r.metadata?.resultTarget=="string"?{target:r.metadata.resultTarget}:{},files:typeof l.source=="string"?[{source:l.source,effect:"pending"}]:[]}};let g=new Set(h.map(e=>e.resourceSource)),n=[],f=[],E=r.results;for(let e of E??[]){let o=e.data,y=[...new Set([...(o.files??[]).map(c=>c.path),...o.path?[o.path]:[]])];for(let c of y)f.push({source:c,...g.has(c)?{state:"present"}:{},effect:g.has(c)||o.ok===!0&&o.files?.some(L=>L.path===c)?"applied":r.effect??"unknown"});for(let c of o.errors??[])n.push({code:c.code??"MUTATION_FAILED",message:c.reason??"Mutation failed",source:c.path});o.ok===!1&&(o.errors?.length??0)===0&&n.push({code:"MUTATION_FAILED",message:"Mutation failed",...o.path?{source:o.path}:{}})}for(let e of g)f.some(o=>o.source===e)||f.push({source:e,effect:"applied",state:"present"});let a=u(r.metadata)&&u(r.metadata.semanticAction)?r.metadata.semanticAction:void 0;if(a){let e=a.effect==="not-applied"||a.effect==="unknown"?a.effect:a.ok===!1?"unknown":"applied",o=typeof a.source=="string"?a.source:void 0;o&&f.push({source:o,...a.kind==="file-operation"&&a.ok===!0?{state:i==="delete"||i==="move"?"absent":"present"}:{},effect:i==="copy"&&typeof a.target=="string"&&a.target!==o?"not-applied":e}),typeof a.target=="string"&&f.push({source:a.target,effect:e,...a.kind==="file-operation"&&a.ok===!0?{state:"present"}:{}}),u(a.error)&&n.push(m(a.error.message,typeof a.error.code=="string"?a.error.code:"MUTATION_FAILED",o)),typeof a.postProcessingError=="string"&&n.push(m(a.postProcessingError,"POST_EDIT_FAILED",o)),a.ok===!1&&n.length===0&&n.push(m("Resource operation failed","MUTATION_FAILED",o))}let d=[...new Map(f.map(e=>[e.source,e])).values()];if(Array.isArray(r.metadata?.resultFileStates))for(let e of r.metadata.resultFileStates){if(!u(e))continue;let o=d.find(y=>y.source===e.source);o&&(e.state==="present"||e.state==="absent")&&(o.state=e.state)}let A=d.some(e=>e.effect==="applied");s.isError&&n.length===0&&n.push({code:"MUTATION_FAILED",message:"Mutation failed"}),(E?.length??0)===0&&!a&&g.size===0&&n.length===0&&r.effect!=="not-applied"&&n.push({code:"UNKNOWN_RESULT",message:"Mutation effects were not reported"});let w=d.some(e=>e.effect==="unknown")||n.some(e=>e.code==="UNKNOWN_RESULT")?"unknown":A?"applied":"not-applied";return{status:n.length===0?"success":!a&&A&&d.some(e=>e.effect!=="applied")?"partial":"error",data:{operation:i,effect:w,files:d,...i!=="delete"&&typeof r.metadata?.resultTarget=="string"?{target:r.metadata.resultTarget}:{},...i!=="delete"&&typeof r.metadata?.targetUnavailable=="string"?{targetUnavailable:r.metadata.targetUnavailable}:{}},errors:n}}p(F,"mutationOutcome");function j(s,i,h=[],r){let l=F(s,i,h);return l.data&&r!==void 0&&(l.data.operationId=r),M(s,R(i),l)}p(j,"structuredMutation");export{R as a,N as b,D as c,_ as d,F as e,j as f};
@@ -1,4 +1,4 @@
1
- import{a as De,b as Pe,c as Se}from"./chunk-ESPNEJHK.js";import{a as ye}from"./chunk-M5IVSCR2.js";import{e as de,f as ue}from"./chunk-T7I2VX3J.js";import{a as le}from"./chunk-MGCHOGQD.js";import{a as ie,b as se}from"./chunk-T6LX2RX5.js";import{a as we}from"./chunk-YRF7OATP.js";import{a as he,b as ve}from"./chunk-FXNKMNSJ.js";import{a as C}from"./chunk-K5G4FDXD.js";import{a as ge}from"./chunk-6CZO43OH.js";import{a as ce,b as pe}from"./chunk-OBNING2A.js";import{e as be}from"./chunk-PS2B6THP.js";import{e as fe,h as me,i as Y}from"./chunk-SQKAXYIR.js";import"./chunk-ZPT5D4VP.js";import{d as S,e as w}from"./chunk-N34ATN52.js";import{a as s}from"./chunk-EI7MMDWY.js";import A from"node:path";import{access as Lt}from"node:fs/promises";import{StringEnum as Bt}from"@earendil-works/pi-ai";import{defineTool as Ht}from"@earendil-works/pi-coding-agent";import{Type as h}from"typebox";import{access as B}from"node:fs/promises";async function j(r,e=process.env,t=process.platform){if(e.PI_PYTHON_PATH!==void 0)return{command:e.PI_PYTHON_PATH,args:[]};let n=t==="win32"?[{command:"python",args:[]},{command:"python3",args:[]},{command:"py",args:["-3"]}]:[{command:"python3",args:[]},{command:"python",args:[]}];for(let o of n)if(await S(o.command,r,e))return o;return n[0]}s(j,"resolvePythonDebuggerCommand");import Qe from"cross-spawn";import{cp as et,mkdtemp as tt,readdir as rt,rm as nt,stat as O}from"node:fs/promises";import{tmpdir as at}from"node:os";import ot from"node:net";import P from"node:path";import{pathToFileURL as it}from"node:url";import{createMessageConnection as st,StreamMessageReader as dt,StreamMessageWriter as ut}from"vscode-jsonrpc/node";import Ke from"cross-spawn";import Xe from"node:net";var Ye=new Set(["initialized","stopped","continued","terminated","exited","loadedSource","breakpoint","custom"]),Ze=128,k=class r{static{s(this,"DapClient")}#t;#o;#u;#r=new Map;#n=[];#i=new Set;#c=new Set;#a=Buffer.alloc(0);#g=1;#l;#f;#p;constructor(e,t,n){this.#t=e,this.#o=t,this.#u=n,e.on("data",o=>this.#b(o)),e.once("error",o=>this.#e(o)),e.once("close",()=>this.#e(new Error("Debug adapter connection closed"))),n!==void 0&&(n.stderr.on("data",o=>{process.env.PI_DEBUG_DAP_TRACE==="1"&&process.stderr.write(o)}),n.once("error",o=>this.#e(o)),n.once("exit",(o,a)=>{this.#e(new Error(`Debug adapter exited${o===null?"":` with code ${o}`}${a===null?"":` (${a})`}`))}))}static start(e,t,n){let a=Ke(e,[...t],{cwd:n,env:process.env,stdio:["pipe","pipe","pipe"]});return new r(a.stdout,a.stdin,a)}static fromSocket(e,t=1){let n=new r(e,e);return n.#g=t,n}static connect(e,t="127.0.0.1"){return new Promise((n,o)=>{let a=Xe.createConnection({port:e,host:t}),i=s(d=>o(d),"fail");a.once("error",i),a.once("connect",()=>{a.off("error",i),n(new r(a,a))})})}onReverseRequest(e){this.#f=e}onEvent(e){return this.#c.add(e),()=>this.#c.delete(e)}request(e,t,n={}){if(this.#l!==void 0)return Promise.reject(this.#l);if(n.signal?.aborted===!0)return Promise.reject(n.signal.reason instanceof Error?n.signal.reason:new Error("Debug operation aborted"));["continue","next","stepIn","stepOut"].includes(e)&&(this.#p=void 0);let o=this.#g++,a={seq:o,type:"request",command:e,...t===void 0?{}:{arguments:t}},i=new Promise((d,u)=>{let b,l=s(()=>{b!==void 0&&clearTimeout(b),n.signal?.removeEventListener("abort",p)},"cleanup"),p=s(()=>{this.#r.delete(o),l(),u(n.signal?.reason instanceof Error?n.signal.reason:new Error("Debug operation aborted"))},"abort");n.timeoutMs!==void 0&&(b=setTimeout(()=>{this.#r.delete(o),l(),u(new Error(`Timed out waiting for debug response ${e}`))},n.timeoutMs)),this.#r.set(o,{resolve:s(m=>d(m),"resolve"),reject:u,cleanup:l}),n.signal?.addEventListener("abort",p,{once:!0})});return this.#d(a),i}waitForEvent(e,t=3e4){return this.waitForAnyEvent([e],t)}waitForAnyEvent(e,t=3e4,n){let o=new Set(e),a=this.#n.findIndex(i=>o.has(i.event));return a>=0?Promise.resolve(this.#n.splice(a,1)[0]):this.#l!==void 0?Promise.reject(this.#l):new Promise((i,d)=>{let u={events:o,resolve:s(l=>{clearTimeout(u.timer),this.#i.delete(u),i(l)},"resolve"),reject:s(l=>{clearTimeout(u.timer),this.#i.delete(u),d(l)},"reject"),timer:setTimeout(()=>{this.#i.delete(u),d(new Error(`Timed out waiting for debug event ${e.join(" or ")}`))},t)};this.#i.add(u);let b=s(()=>u.reject(n?.reason instanceof Error?n.reason:new Error("Debug operation aborted")),"abort");n?.aborted===!0?b():n?.addEventListener("abort",b,{once:!0})})}close(){this.#t.destroy(),this.#o.destroy(),this.#u!==void 0&&!this.#u.killed&&this.#u.kill(),this.#e(new Error("Debug adapter closed"))}#d(e){let t=Buffer.from(JSON.stringify(e),"utf8");this.#o.write(Buffer.concat([Buffer.from(`Content-Length: ${t.length}\r
1
+ import{a as De,b as Pe,c as Se}from"./chunk-ESPNEJHK.js";import{a as ye}from"./chunk-M5IVSCR2.js";import{e as de,f as ue}from"./chunk-T7I2VX3J.js";import{a as le}from"./chunk-MGCHOGQD.js";import{a as ie,b as se}from"./chunk-T6LX2RX5.js";import{a as we}from"./chunk-PKKDDIWW.js";import{a as he,b as ve}from"./chunk-4GCWGE2C.js";import{a as C}from"./chunk-K5G4FDXD.js";import{a as ge}from"./chunk-BU7IZLKB.js";import{a as ce,b as pe}from"./chunk-S5PL5DFQ.js";import{e as be}from"./chunk-PS2B6THP.js";import{e as fe,h as me,i as Y}from"./chunk-CWD4O5PM.js";import"./chunk-ZPT5D4VP.js";import{d as S,e as w}from"./chunk-N34ATN52.js";import{a as s}from"./chunk-EI7MMDWY.js";import A from"node:path";import{access as Lt}from"node:fs/promises";import{StringEnum as Bt}from"@earendil-works/pi-ai";import{defineTool as Ht}from"@earendil-works/pi-coding-agent";import{Type as h}from"typebox";import{access as B}from"node:fs/promises";async function j(r,e=process.env,t=process.platform){if(e.PI_PYTHON_PATH!==void 0)return{command:e.PI_PYTHON_PATH,args:[]};let n=t==="win32"?[{command:"python",args:[]},{command:"python3",args:[]},{command:"py",args:["-3"]}]:[{command:"python3",args:[]},{command:"python",args:[]}];for(let o of n)if(await S(o.command,r,e))return o;return n[0]}s(j,"resolvePythonDebuggerCommand");import Qe from"cross-spawn";import{cp as et,mkdtemp as tt,readdir as rt,rm as nt,stat as O}from"node:fs/promises";import{tmpdir as at}from"node:os";import ot from"node:net";import P from"node:path";import{pathToFileURL as it}from"node:url";import{createMessageConnection as st,StreamMessageReader as dt,StreamMessageWriter as ut}from"vscode-jsonrpc/node";import Ke from"cross-spawn";import Xe from"node:net";var Ye=new Set(["initialized","stopped","continued","terminated","exited","loadedSource","breakpoint","custom"]),Ze=128,k=class r{static{s(this,"DapClient")}#t;#o;#u;#r=new Map;#n=[];#i=new Set;#c=new Set;#a=Buffer.alloc(0);#g=1;#l;#f;#p;constructor(e,t,n){this.#t=e,this.#o=t,this.#u=n,e.on("data",o=>this.#b(o)),e.once("error",o=>this.#e(o)),e.once("close",()=>this.#e(new Error("Debug adapter connection closed"))),n!==void 0&&(n.stderr.on("data",o=>{process.env.PI_DEBUG_DAP_TRACE==="1"&&process.stderr.write(o)}),n.once("error",o=>this.#e(o)),n.once("exit",(o,a)=>{this.#e(new Error(`Debug adapter exited${o===null?"":` with code ${o}`}${a===null?"":` (${a})`}`))}))}static start(e,t,n){let a=Ke(e,[...t],{cwd:n,env:process.env,stdio:["pipe","pipe","pipe"]});return new r(a.stdout,a.stdin,a)}static fromSocket(e,t=1){let n=new r(e,e);return n.#g=t,n}static connect(e,t="127.0.0.1"){return new Promise((n,o)=>{let a=Xe.createConnection({port:e,host:t}),i=s(d=>o(d),"fail");a.once("error",i),a.once("connect",()=>{a.off("error",i),n(new r(a,a))})})}onReverseRequest(e){this.#f=e}onEvent(e){return this.#c.add(e),()=>this.#c.delete(e)}request(e,t,n={}){if(this.#l!==void 0)return Promise.reject(this.#l);if(n.signal?.aborted===!0)return Promise.reject(n.signal.reason instanceof Error?n.signal.reason:new Error("Debug operation aborted"));["continue","next","stepIn","stepOut"].includes(e)&&(this.#p=void 0);let o=this.#g++,a={seq:o,type:"request",command:e,...t===void 0?{}:{arguments:t}},i=new Promise((d,u)=>{let b,l=s(()=>{b!==void 0&&clearTimeout(b),n.signal?.removeEventListener("abort",p)},"cleanup"),p=s(()=>{this.#r.delete(o),l(),u(n.signal?.reason instanceof Error?n.signal.reason:new Error("Debug operation aborted"))},"abort");n.timeoutMs!==void 0&&(b=setTimeout(()=>{this.#r.delete(o),l(),u(new Error(`Timed out waiting for debug response ${e}`))},n.timeoutMs)),this.#r.set(o,{resolve:s(m=>d(m),"resolve"),reject:u,cleanup:l}),n.signal?.addEventListener("abort",p,{once:!0})});return this.#d(a),i}waitForEvent(e,t=3e4){return this.waitForAnyEvent([e],t)}waitForAnyEvent(e,t=3e4,n){let o=new Set(e),a=this.#n.findIndex(i=>o.has(i.event));return a>=0?Promise.resolve(this.#n.splice(a,1)[0]):this.#l!==void 0?Promise.reject(this.#l):new Promise((i,d)=>{let u={events:o,resolve:s(l=>{clearTimeout(u.timer),this.#i.delete(u),i(l)},"resolve"),reject:s(l=>{clearTimeout(u.timer),this.#i.delete(u),d(l)},"reject"),timer:setTimeout(()=>{this.#i.delete(u),d(new Error(`Timed out waiting for debug event ${e.join(" or ")}`))},t)};this.#i.add(u);let b=s(()=>u.reject(n?.reason instanceof Error?n.reason:new Error("Debug operation aborted")),"abort");n?.aborted===!0?b():n?.addEventListener("abort",b,{once:!0})})}close(){this.#t.destroy(),this.#o.destroy(),this.#u!==void 0&&!this.#u.killed&&this.#u.kill(),this.#e(new Error("Debug adapter closed"))}#d(e){let t=Buffer.from(JSON.stringify(e),"utf8");this.#o.write(Buffer.concat([Buffer.from(`Content-Length: ${t.length}\r
2
2
  \r
3
3
  `),t]))}#b(e){for(this.#a=Buffer.concat([this.#a,e]);;){let t=this.#a.indexOf(`\r
4
4
  \r
@@ -17,7 +17,7 @@ ${t.fg("accent",Et(e))}`,0,0)}s($e,"renderDebugActionCall");function N(r,e,t,n){
17
17
  \r
18
18
  ${e}`}s(It,"dapFrame");function re(r,e,t){return r.request("initialize",{clientID:"pi-agent-ide",adapterID:e,pathFormat:"path",linesStartAt1:!0,columnsStartAt1:!0,supportsVariableType:!0,supportsVariablePaging:!0,supportsRunInTerminalRequest:!1,supportsStartDebuggingRequest:!0},{signal:t})}s(re,"initializeClient");function V(){return new Promise((r,e)=>{let t=Ve.createServer();t.once("error",e),t.listen(0,"127.0.0.1",()=>{let n=t.address();if(n===null||typeof n=="string"){t.close(),e(new Error("Could not allocate a debug adapter port"));return}t.close(o=>o===void 0?r(n.port):e(o))})})}s(V,"availablePort");function ne(r,e){if(process.env.PI_DEBUG_DAP_TRACE==="1"){process.stderr.write(`[${e}] pid=${String(r.pid)}
19
19
  `),r.once("exit",(t,n)=>process.stderr.write(`[${e}] exit code=${String(t)} signal=${String(n)}
20
- `));for(let t of[r.stdout,r.stderr])t?.on("data",n=>process.stderr.write(`[${e}] ${n.toString("utf8")}`))}}s(ne,"traceAdapterProcess");function $t(r,e,t){return new Promise((n,o)=>{let a=setTimeout(()=>d(new Error("Timed out starting vscDebugger")),5e3),i=s(()=>{clearTimeout(a),e.off("error",d),e.off("exit",u)},"cleanup"),d=s(b=>{i(),t.close(),e.killed||e.kill(),o(b)},"fail"),u=s(b=>d(new Error(`vscDebugger exited with code ${String(b)} before connecting`)),"onExit");e.once("error",d),e.once("exit",u),r.then(b=>{i(),n(b)},d)})}s($t,"waitForRAdapterConnection");function Je(r,e,t){return new Promise((n,o)=>{let a=[r.stdout,r.stderr].filter(b=>b!==null),i=setTimeout(()=>o(new Error(`Timed out starting ${t} server`)),process.platform==="win32"?15e3:5e3),d=s(()=>{clearTimeout(i);for(let b of a)b.off("data",u)},"cleanup"),u=s(b=>{b.toString("utf8").includes(e)&&(d(),n())},"onData");for(let b of a)b.on("data",u);r.once("error",b=>{d(),o(b)}),r.once("exit",b=>{d(),o(new Error(`${t} server exited with code ${String(b)}`))})})}s(Je,"waitForAdapterReady");function Ct(r){return new Promise((e,t)=>{let n=r.stdout;if(n===null){t(new Error("js-debug server stdout is unavailable"));return}let o=setTimeout(()=>t(new Error("Timed out starting js-debug server")),5e3),a=s(i=>{i.toString("utf8").includes("Debug server listening")&&(clearTimeout(o),n.off("data",a),e())},"onData");n.on("data",a),r.once("error",t),r.once("exit",i=>t(new Error(`js-debug server exited with code ${i}`)))})}s(Ct,"waitForJsDebugReady");async function Ue(r,e="js-debug"){let t;for(let n=0;n<100;n++)try{return await k.connect(r)}catch(o){t=o,await new Promise(a=>setTimeout(a,25))}throw t instanceof Error?t:new Error(`Could not connect to ${e}`)}s(Ue,"connectWithRetry");async function ae(r){r.adapterTemporaryDirectory!==void 0&&(await xt(r.adapterTemporaryDirectory,{recursive:!0,force:!0,maxRetries:process.platform==="win32"?10:0,retryDelay:100}),r.adapterTemporaryDirectory=void 0)}s(ae,"removeAdapterTemporaryDirectory");async function Me(r){if(!(r===void 0||r.exitCode!==null||r.signalCode!==null)){if(process.platform!=="win32"||r.pid===void 0){r.kill();return}await new Promise(e=>{let t=H("taskkill.exe",["/pid",String(r.pid),"/t","/f"],{stdio:"ignore",windowsHide:!0});t.once("error",()=>{r.kill(),e()}),t.once("exit",()=>e())})}}s(Me,"terminateOwnedAdapterProcess");async function jt(r,e){let t={name:"Pi Agent IDE debug session",request:"launch",program:r.program,cwd:r.cwd,args:[...r.args]};if(r.adapter==="dart")return{command:process.env.PI_DART_PATH??"dart",args:["debug_adapter"],adapterID:"dart",request:"launch",launch:{...t,type:"dart",debugSdkLibraries:!1,debugExternalPackageLibraries:!1,stopOnEntry:!0,vmAdditionalArgs:["--pause-isolates-on-start"]}};if(r.adapter==="debugpy"){let n=await j(r.cwd);return{command:n.command,args:[...n.args,"-m","debugpy.adapter"],adapterID:"debugpy",request:"launch",launch:{...t,type:"python",console:"internalConsole",justMyCode:!1}}}if(r.adapter==="kotlin"){if(r.mainClass===void 0)throw new Error("Java and Kotlin debug sessions require mainClass");return{command:process.env.PI_KOTLIN_DEBUG_ADAPTER_PATH??"kotlin-debug-adapter",args:[],adapterID:r.adapter,request:"launch",launch:{...t,type:"kotlin",mainClass:r.mainClass,projectRoot:r.cwd,stopOnEntry:!0}}}if(r.adapter==="netcoredbg")return{command:process.env.PI_NETCOREDBG_PATH??"netcoredbg",args:["--interpreter=vscode"],adapterID:"coreclr",request:"launch",launch:{...t,type:"coreclr",console:"internalConsole"}};if(r.adapter==="elixir")return{command:process.env.PI_ELIXIR_LS_DEBUG_PATH??(process.platform==="win32"?"debug_adapter.bat":"/opt/pi-debug-adapters/elixir-ls/debug_adapter.sh"),args:[],adapterID:"mix_task",request:"launch",launch:{name:t.name,request:"launch",type:"mix_task",task:"run",taskArgs:[r.program,...r.args],projectDir:r.cwd,startApps:!0,exitAfterTaskReturns:!0}};if(r.adapter==="julia")return{command:process.env.PI_JULIA_PATH??"julia",args:[],adapterID:"julia",request:"launch",launch:{...t,type:"julia",stopOnEntry:!1}};if(r.adapter==="lldb-dap")return{command:y.extname(r.sourceFile).toLowerCase()===".swift"?process.env.PI_SWIFT_LLDB_DAP_PATH??process.env.PI_LLDB_DAP_PATH??"lldb-dap":process.env.PI_LLDB_DAP_PATH??(process.platform==="win32"?"lldb-dap":"lldb-dap-18"),args:[],adapterID:"lldb-dap",request:"launch",launch:{...t,type:"lldb-dap"}};if(r.adapter==="delve")return{command:process.env.PI_DELVE_PATH??"dlv",args:[],adapterID:"go",request:"launch",launch:{...t,type:"go",mode:"debug"}};if(r.adapter==="r")return{command:process.env.PI_R_PATH??"R",args:[],adapterID:"R-Debugger",request:"launch",launch:{name:t.name,request:"launch",type:"R-Debugger",debugMode:"file",file:r.program,workingDirectory:r.cwd,commandLineArgs:[...r.args],allowGlobalDebugging:!1,loadPackages:[],supportsStdoutReading:!0,supportsWriteToStdinEvent:!0,overwriteHelp:!1}};if(r.adapter==="ruby")return{command:process.env.PI_RUBY_DEBUG_PATH??"rdbg",args:[],adapterID:"rdbg",request:"launch",launch:{...t,type:"rdbg"}};if(r.adapter==="php")return{command:process.execPath,args:[process.env.PI_PHP_DEBUG_PATH??"/opt/pi-debug-adapters/php-debug/extension/out/phpDebug.js"],adapterID:"php",request:"launch",launch:{...t,type:"php",runtimeExecutable:process.env.PI_PHP_PATH??"php",runtimeArgs:["-dxdebug.start_with_request=yes"],console:"internalConsole",port:0,env:{XDEBUG_MODE:"debug,develop",XDEBUG_CONFIG:"client_port=${port}"}}};if(r.adapter==="lua")return{command:process.execPath,args:[process.env.PI_LUA_DEBUG_PATH??"/opt/pi-debug-adapters/lua-debug/extension/extension/debugAdapter.js"],adapterID:"lua-local",request:"launch",launch:{...t,type:"lua-local",program:{lua:process.env.PI_LUA_PATH??"lua",file:r.program},extensionPath:y.dirname(y.dirname(process.env.PI_LUA_DEBUG_PATH??"/opt/pi-debug-adapters/lua-debug/extension/extension/debugAdapter.js")),workspacePath:r.cwd}};if(r.adapter==="shell"){let n=process.env.PI_BASH_DEBUG_ROOT??"/opt/pi-debug-adapters/bash-debug/extension";return{command:process.execPath,args:[process.env.PI_BASH_DEBUG_PATH??y.join(n,"out/bashDebug.js")],adapterID:"bashdb",request:"launch",launch:{...t,type:"bashdb",pathBash:process.env.PI_BASH_PATH??"/usr/bin/bash",pathBashdb:y.join(n,"bashdb_dir/bashdb"),pathBashdbLib:y.join(n,"bashdb_dir"),pathCat:"/usr/bin/cat",pathMkfifo:"/usr/bin/mkfifo",pathPkill:"/usr/bin/pkill",terminalKind:"debugConsole",argsString:"",env:{},showDebugOutput:!1,trace:!1}}}if(r.adapter==="powershell"){let n=process.env.PI_POWERSHELL_EDITOR_SERVICES_PATH??"/opt/pi-debug-adapters/powershell-editor-services";if(e===void 0)throw new Error("PowerShell debugger temporary directory was not created");return{command:process.env.PI_PWSH_PATH??"pwsh",args:["-NoLogo","-NoProfile","-Command",`& '${y.join(n,"PowerShellEditorServices/Start-EditorServices.ps1").replaceAll("'","''")}' -LogPath '${y.join(e,"logs").replaceAll("'","''")}' -LogLevel Warning -SessionDetailsPath '${y.join(e,"session.json").replaceAll("'","''")}' -FeatureFlags @() -AdditionalModules @() -HostName 'Pi Agent IDE' -HostProfileId 'pi-agent-ide' -HostVersion '1.0.0' -BundledModulesPath '${n.replaceAll("'","''")}' -Stdio -DebugServiceOnly`],adapterID:"PowerShell",request:"launch",launch:{...t,script:r.program,createTemporaryIntegratedConsole:!1,executeMode:"Call"}}}return{command:process.execPath,args:[],adapterID:"pwa-node",request:"launch",launch:{...t,type:"pwa-node",console:"internalConsole",autoAttachChildProcesses:!1,stopOnEntry:!0,sourceMaps:!0,pauseForSourceMap:!0,outFiles:[y.join(y.dirname(r.program),"**","*.js")]}}}s(jt,"adapterRecipe");var oe=h.Object({source:h.String(),sourceResource:h.String(),breakpointsResource:h.String(),adapter:h.String(),program:h.String(),cwd:h.String(),status:h.String(),breakpoints:h.Array(h.Object({source:h.String(),file:h.String(),line:h.Integer(),verified:h.Boolean()},{additionalProperties:!1}))},{additionalProperties:!1}),qt=fe(oe),Nt=h.Object({adapter:Bt(["dart","debugpy","delve","java","elixir","julia","kotlin","lldb-dap","lua","netcoredbg","node","php","powershell","r","ruby","shell"],{description:"Select an installed DAP adapter for Dart, Python, Go, Java, Elixir, Julia, Kotlin, C, C++, Rust, Swift, Zig, Lua, C#, JavaScript, TypeScript, PHP, PowerShell, R, Ruby, or shell scripts."}),program:h.String({minLength:1,description:"Source file or executable to launch. Relative paths resolve from cwd."}),source:h.Optional(h.String({description:"Source file used for anchored breakpoints. Defaults to program."})),args:h.Optional(h.Array(h.String(),{description:"Arguments passed to the debugged program."})),mainClass:h.Optional(h.String({minLength:1,description:"Fully qualified JVM main class. Required by Java and Kotlin adapters."})),cwd:h.Optional(h.String({description:"Working directory. Relative paths resolve from the workspace."}))},{additionalProperties:!1});async function Ot(r){ue(r,[await de({id:"debugger",description:"Debugger sessions, breakpoints, stepping, and cleanup",triggers:[{tool:"debug"},...["read","insert","delete"].map(l=>({tool:l,resourcePrefixes:["debug:"]}))]})]);let e=Pe("debugger"),t=e!==void 0&&typeof e.evaluate=="function"?e:new W,n=new Map,o=We(t,"debugger-source"),a=We(t,"debugger-input"),i=ye(r).add(Oe(t)),d=Ie(t),u={protocol:ce,apiVersion:pe,id:"debugger",setup(l){l.addResolver({resolver:o,matchesCall:s(p=>t.sourceFile(p)!==void 0,"matchesCall"),renderCall(p,m,c){let g=$(p)?p:{},f=typeof g.path=="string"?g.path:"",D=t.get(f),v=t.sourceFile(f);if(D===void 0||v===void 0)throw new Error("Debugger source header lost its session");let E=A.relative(D.options.cwd,v),_=Array.isArray(g.views)?g.views.filter(X=>typeof X=="string"):[],R=typeof g.offset=="number"?g.offset:1,I=typeof g.limit=="number"?g.limit:void 0,K=I===void 0?String(R):`${R}-${R+I-1}`;return be(c.lastComponent,{tool:"debug file",primary:{text:`${E}:${K}`,color:"accent",underline:!0},qualifiers:_.length===0?[]:[{text:`views ${_.join(",")}`}],details:[{label:"source",value:f},{label:"file",value:v},..._.length===0?[]:[{label:"views",value:_.join(",")}]],expanded:c.expanded},m)}}),l.addView({view:"breakpoints",presenter:d}),l.describe('views: ["breakpoints"] \u2014 current debugger breakpoints beside source lines. Normal files include every current session; debug sources are session-scoped. debug:<session> \u2014 debugger state.')}},b={protocol:he,apiVersion:ve,id:"debugger",setup(l){l.addResolver({resolver:a}),l.tool("insert").addSemanticHandler({matches:s(p=>Ft(p,t),"matches"),execute:s(async(p,m)=>{let c=m,g=ze(t,c.path);if(t.sourceFile(c.path)!==void 0){if(c.text!=="breakpoint"||c.anchor===void 0)throw new Error('A debug source accepts text "breakpoint" with one anchor');let D=await p.resolveAnchor("anchor"),v=await t.addBreakpoint(c.path,D.lineNumber,p.signal);return{source:v.source,summary:`Breakpoint ${v.source} created at ${A.relative(g.options.cwd,v.file)}:${v.line}.`,data:{kind:"debug-breakpoint",session:g.source,file:v.file,line:v.line,verified:v.verified,snapshot:t.snapshot(g)}}}if(c.path!==g.source||c.anchor!==void 0)throw new Error("Debug commands target the session resource without an anchor");let f=await Ut(t,g,c.text,p.signal);return{source:g.source,summary:f===void 0?z(g):`${f.expression} = ${f.result}${f.type===void 0?"":` (${f.type})`}`,data:Gt(t,g,c.text,f)}},"execute")}),l.tool("delete").addSemanticHandler({matches:s(p=>Jt(p,t),"matches"),execute:s(async(p,m)=>{let c=m.path,g=ze(t,c),f=t.snapshot(g);n.set(c,f);let D=c.includes("/breakpoint/");await t.delete(c,p.signal);let v=D?t.snapshot(g):{...f,status:"terminated"};return{source:c,summary:`Deleted ${c}.`,data:{kind:D?"debug-breakpoint":"debug-session",deleted:!0,snapshot:v}}},"execute")}),l.describe('For debug:<session> resources, insert performs debugger actions without changing source text. On a debug source, insert "breakpoint" at an anchor. On the session, insert start, continue, step over, step into, step out, or evaluate <expression>. Delete removes a breakpoint or terminates the session.');for(let p of["insert","delete"])l.addToolRenderer({tool:p,matches(m,c){return c==="call"?$(m)&&typeof m.path=="string"&&(t.get(m.path)!==void 0||n.has(m.path)):te($(m)&&"details"in m?m.details:m)!==void 0},renderCall(m,c,g){let f=m,D=f.path===void 0?void 0:t.get(f.path),v=f.path===void 0?void 0:n.get(f.path),E=g.state;D!==void 0?E.snapshot=t.snapshot(D):v!==void 0&&(E.snapshot=v);let _=E.snapshot;if(_===void 0)throw new Error("Debugger renderer lost its session");let R=f.path===void 0?void 0:t.breakpoint(f.path)??_.breakpoints.find(X=>X.source===f.path),I=f.path===void 0?void 0:t.sourceFile(f.path),K=p==="delete"?R===void 0?"delete-session":`delete-breakpoint ${A.basename(R.file)}:${R.line}`:f.text==="breakpoint"&&I!==void 0?`breakpoint ${A.basename(I)}:${Wt(f)}`:f.text??"debug action";return $e(_,K,c)},renderResult(m,c,g){let f=te(m.details);if(f===void 0)throw new Error("Debugger result is missing its session");let D=qe(m.details);return N(f,c.expanded,g,D)}})}};await Promise.all([le(r,Ae),ge(r,u)]),await we(r,b),r.registerTool(Ht({name:"debug",exposure:"deferred",namespace:{name:"ide_debug",description:"Create local debugger sessions and inspect debug resources."},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1},label:"Debug session",promptSnippet:"Create a local DAP debug session before setting anchored breakpoints",description:"Use debug to create a configured local debugger session. This does not launch the program yet. The returned debug: resource survives extension reloads.",parameters:Nt,outputSchema:qt,async execute(l,p,m,c,g){let f=A.resolve(g.cwd,p.cwd??"."),D=A.resolve(f,p.program);try{await Lt(D);let v=t.create({adapter:p.adapter,program:D,sourceFile:A.resolve(f,p.source??p.program),args:p.args??[],cwd:f,...p.mainClass===void 0?{}:{mainClass:p.mainClass}}),E=Mt(t,v),{snapshot:_,stop:R,...I}=E;return Y({content:[{type:"text",text:`${z(v)}
20
+ `));for(let t of[r.stdout,r.stderr])t?.on("data",n=>process.stderr.write(`[${e}] ${n.toString("utf8")}`))}}s(ne,"traceAdapterProcess");function $t(r,e,t){return new Promise((n,o)=>{let a=setTimeout(()=>d(new Error("Timed out starting vscDebugger")),5e3),i=s(()=>{clearTimeout(a),e.off("error",d),e.off("exit",u)},"cleanup"),d=s(b=>{i(),t.close(),e.killed||e.kill(),o(b)},"fail"),u=s(b=>d(new Error(`vscDebugger exited with code ${String(b)} before connecting`)),"onExit");e.once("error",d),e.once("exit",u),r.then(b=>{i(),n(b)},d)})}s($t,"waitForRAdapterConnection");function Je(r,e,t){return new Promise((n,o)=>{let a=[r.stdout,r.stderr].filter(b=>b!==null),i=setTimeout(()=>o(new Error(`Timed out starting ${t} server`)),process.platform==="win32"?15e3:5e3),d=s(()=>{clearTimeout(i);for(let b of a)b.off("data",u)},"cleanup"),u=s(b=>{b.toString("utf8").includes(e)&&(d(),n())},"onData");for(let b of a)b.on("data",u);r.once("error",b=>{d(),o(b)}),r.once("exit",b=>{d(),o(new Error(`${t} server exited with code ${String(b)}`))})})}s(Je,"waitForAdapterReady");function Ct(r){return new Promise((e,t)=>{let n=r.stdout;if(n===null){t(new Error("js-debug server stdout is unavailable"));return}let o=setTimeout(()=>t(new Error("Timed out starting js-debug server")),5e3),a=s(i=>{i.toString("utf8").includes("Debug server listening")&&(clearTimeout(o),n.off("data",a),e())},"onData");n.on("data",a),r.once("error",t),r.once("exit",i=>t(new Error(`js-debug server exited with code ${i}`)))})}s(Ct,"waitForJsDebugReady");async function Ue(r,e="js-debug"){let t;for(let n=0;n<100;n++)try{return await k.connect(r)}catch(o){t=o,await new Promise(a=>setTimeout(a,25))}throw t instanceof Error?t:new Error(`Could not connect to ${e}`)}s(Ue,"connectWithRetry");async function ae(r){r.adapterTemporaryDirectory!==void 0&&(await xt(r.adapterTemporaryDirectory,{recursive:!0,force:!0,maxRetries:process.platform==="win32"?10:0,retryDelay:100}),r.adapterTemporaryDirectory=void 0)}s(ae,"removeAdapterTemporaryDirectory");async function Me(r){if(!(r===void 0||r.exitCode!==null||r.signalCode!==null)){if(process.platform!=="win32"||r.pid===void 0){r.kill();return}await new Promise(e=>{let t=H("taskkill.exe",["/pid",String(r.pid),"/t","/f"],{stdio:"ignore",windowsHide:!0});t.once("error",()=>{r.kill(),e()}),t.once("exit",()=>e())})}}s(Me,"terminateOwnedAdapterProcess");async function jt(r,e){let t={name:"Pi Agent IDE debug session",request:"launch",program:r.program,cwd:r.cwd,args:[...r.args]};if(r.adapter==="dart")return{command:process.env.PI_DART_PATH??"dart",args:["debug_adapter"],adapterID:"dart",request:"launch",launch:{...t,type:"dart",debugSdkLibraries:!1,debugExternalPackageLibraries:!1,stopOnEntry:!0,vmAdditionalArgs:["--pause-isolates-on-start"]}};if(r.adapter==="debugpy"){let n=await j(r.cwd);return{command:n.command,args:[...n.args,"-m","debugpy.adapter"],adapterID:"debugpy",request:"launch",launch:{...t,type:"python",console:"internalConsole",justMyCode:!1}}}if(r.adapter==="kotlin"){if(r.mainClass===void 0)throw new Error("Java and Kotlin debug sessions require mainClass");return{command:process.env.PI_KOTLIN_DEBUG_ADAPTER_PATH??"kotlin-debug-adapter",args:[],adapterID:r.adapter,request:"launch",launch:{...t,type:"kotlin",mainClass:r.mainClass,projectRoot:r.cwd,stopOnEntry:!0}}}if(r.adapter==="netcoredbg")return{command:process.env.PI_NETCOREDBG_PATH??"netcoredbg",args:["--interpreter=vscode"],adapterID:"coreclr",request:"launch",launch:{...t,type:"coreclr",console:"internalConsole"}};if(r.adapter==="elixir")return{command:process.env.PI_ELIXIR_LS_DEBUG_PATH??(process.platform==="win32"?"debug_adapter.bat":"/opt/pi-debug-adapters/elixir-ls/debug_adapter.sh"),args:[],adapterID:"mix_task",request:"launch",launch:{name:t.name,request:"launch",type:"mix_task",task:"run",taskArgs:[r.program,...r.args],projectDir:r.cwd,startApps:!0,exitAfterTaskReturns:!0}};if(r.adapter==="julia")return{command:process.env.PI_JULIA_PATH??"julia",args:[],adapterID:"julia",request:"launch",launch:{...t,type:"julia",stopOnEntry:!1}};if(r.adapter==="lldb-dap")return{command:y.extname(r.sourceFile).toLowerCase()===".swift"?process.env.PI_SWIFT_LLDB_DAP_PATH??process.env.PI_LLDB_DAP_PATH??"lldb-dap":process.env.PI_LLDB_DAP_PATH??(process.platform==="win32"?"lldb-dap":"lldb-dap-18"),args:[],adapterID:"lldb-dap",request:"launch",launch:{...t,type:"lldb-dap"}};if(r.adapter==="delve")return{command:process.env.PI_DELVE_PATH??"dlv",args:[],adapterID:"go",request:"launch",launch:{...t,type:"go",mode:"debug"}};if(r.adapter==="r")return{command:process.env.PI_R_PATH??"R",args:[],adapterID:"R-Debugger",request:"launch",launch:{name:t.name,request:"launch",type:"R-Debugger",debugMode:"file",file:r.program,workingDirectory:r.cwd,commandLineArgs:[...r.args],allowGlobalDebugging:!1,loadPackages:[],supportsStdoutReading:!0,supportsWriteToStdinEvent:!0,overwriteHelp:!1}};if(r.adapter==="ruby")return{command:process.env.PI_RUBY_DEBUG_PATH??"rdbg",args:[],adapterID:"rdbg",request:"launch",launch:{...t,type:"rdbg"}};if(r.adapter==="php")return{command:process.execPath,args:[process.env.PI_PHP_DEBUG_PATH??"/opt/pi-debug-adapters/php-debug/extension/out/phpDebug.js"],adapterID:"php",request:"launch",launch:{...t,type:"php",runtimeExecutable:process.env.PI_PHP_PATH??"php",runtimeArgs:["-dxdebug.start_with_request=yes"],console:"internalConsole",port:0,env:{XDEBUG_MODE:"debug,develop",XDEBUG_CONFIG:"client_port=${port}"}}};if(r.adapter==="lua")return{command:process.execPath,args:[process.env.PI_LUA_DEBUG_PATH??"/opt/pi-debug-adapters/lua-debug/extension/extension/debugAdapter.js"],adapterID:"lua-local",request:"launch",launch:{...t,type:"lua-local",program:{lua:process.env.PI_LUA_PATH??"lua",file:r.program},extensionPath:y.dirname(y.dirname(process.env.PI_LUA_DEBUG_PATH??"/opt/pi-debug-adapters/lua-debug/extension/extension/debugAdapter.js")),workspacePath:r.cwd}};if(r.adapter==="shell"){let n=process.env.PI_BASH_DEBUG_ROOT??"/opt/pi-debug-adapters/bash-debug/extension";return{command:process.execPath,args:[process.env.PI_BASH_DEBUG_PATH??y.join(n,"out/bashDebug.js")],adapterID:"bashdb",request:"launch",launch:{...t,type:"bashdb",pathBash:process.env.PI_BASH_PATH??"/usr/bin/bash",pathBashdb:y.join(n,"bashdb_dir/bashdb"),pathBashdbLib:y.join(n,"bashdb_dir"),pathCat:"/usr/bin/cat",pathMkfifo:"/usr/bin/mkfifo",pathPkill:"/usr/bin/pkill",terminalKind:"debugConsole",argsString:"",env:{},showDebugOutput:!1,trace:!1}}}if(r.adapter==="powershell"){let n=process.env.PI_POWERSHELL_EDITOR_SERVICES_PATH??"/opt/pi-debug-adapters/powershell-editor-services";if(e===void 0)throw new Error("PowerShell debugger temporary directory was not created");return{command:process.env.PI_PWSH_PATH??"pwsh",args:["-NoLogo","-NoProfile","-Command",`& '${y.join(n,"PowerShellEditorServices/Start-EditorServices.ps1").replaceAll("'","''")}' -LogPath '${y.join(e,"logs").replaceAll("'","''")}' -LogLevel Warning -SessionDetailsPath '${y.join(e,"session.json").replaceAll("'","''")}' -FeatureFlags @() -AdditionalModules @() -HostName 'Pi Agent IDE' -HostProfileId 'pi-agent-ide' -HostVersion '1.0.0' -BundledModulesPath '${n.replaceAll("'","''")}' -Stdio -DebugServiceOnly`],adapterID:"PowerShell",request:"launch",launch:{...t,script:r.program,createTemporaryIntegratedConsole:!1,executeMode:"Call"}}}return{command:process.execPath,args:[],adapterID:"pwa-node",request:"launch",launch:{...t,type:"pwa-node",console:"internalConsole",autoAttachChildProcesses:!1,stopOnEntry:!0,sourceMaps:!0,pauseForSourceMap:!0,outFiles:[y.join(y.dirname(r.program),"**","*.js")]}}}s(jt,"adapterRecipe");var oe=h.Object({source:h.String(),sourceResource:h.String(),breakpointsResource:h.String(),adapter:h.String(),program:h.String(),cwd:h.String(),status:h.String(),breakpoints:h.Array(h.Object({source:h.String(),file:h.String(),line:h.Integer(),verified:h.Boolean()},{additionalProperties:!1}))},{additionalProperties:!1}),qt=fe(oe),Nt=h.Object({adapter:Bt(["dart","debugpy","delve","java","elixir","julia","kotlin","lldb-dap","lua","netcoredbg","node","php","powershell","r","ruby","shell"],{description:"Select an installed DAP adapter for Dart, Python, Go, Java, Elixir, Julia, Kotlin, C, C++, Rust, Swift, Zig, Lua, C#, JavaScript, TypeScript, PHP, PowerShell, R, Ruby, or shell scripts."}),program:h.String({minLength:1,description:"Source file or executable to launch. Relative paths resolve from cwd."}),source:h.Optional(h.String({description:"Source file used for anchored breakpoints. Defaults to program."})),args:h.Optional(h.Array(h.String(),{description:"Arguments passed to the debugged program."})),mainClass:h.Optional(h.String({minLength:1,description:"Fully qualified JVM main class. Required by Java and Kotlin adapters."})),cwd:h.Optional(h.String({description:"Working directory. Relative paths resolve from the workspace."}))},{additionalProperties:!1});async function Ot(r){ue(r,[await de({id:"debugger",description:"Debugger sessions, breakpoints, stepping, and cleanup",triggers:[{tool:"debug"},...["read","insert","delete"].map(l=>({tool:l,resourcePrefixes:["debug:"]}))]})]);let e=Pe("debugger"),t=e!==void 0&&typeof e.evaluate=="function"?e:new W,n=new Map,o=We(t,"debugger-source"),a=We(t,"debugger-input"),i=ye(r).add(Oe(t)),d=Ie(t),u={protocol:ce,apiVersion:pe,id:"debugger",setup(l){l.addResolver({resolver:o,matchesCall:s(p=>t.sourceFile(p)!==void 0,"matchesCall"),renderCall(p,m,c){let g=$(p)?p:{},f=typeof g.path=="string"?g.path:"",D=t.get(f),v=t.sourceFile(f);if(D===void 0||v===void 0)throw new Error("Debugger source header lost its session");let E=A.relative(D.options.cwd,v),_=Array.isArray(g.views)?g.views.filter(X=>typeof X=="string"):[],R=typeof g.offset=="number"?g.offset:1,I=typeof g.limit=="number"?g.limit:void 0,K=I===void 0?String(R):`${R}-${R+I-1}`;return be(c.lastComponent,{tool:"debug file",primary:{text:`${E}:${K}`,color:"accent",underline:!0},qualifiers:_.length===0?[]:[{text:`views ${_.join(",")}`}],details:[{label:"source",value:f},{label:"file",value:v},..._.length===0?[]:[{label:"views",value:_.join(",")}]],expanded:c.expanded},m)}}),l.addView({view:"breakpoints",presenter:d}),l.describe({path:"debug:<session> \u2014 debugger state.",views:"breakpoints \u2014 current debugger breakpoints beside source lines. Normal files include every current session; debug sources are session-scoped."})}},b={protocol:he,apiVersion:ve,id:"debugger",setup(l){l.addResolver({resolver:a}),l.tool("insert").addSemanticHandler({matches:s(p=>Ft(p,t),"matches"),execute:s(async(p,m)=>{let c=m,g=ze(t,c.path);if(t.sourceFile(c.path)!==void 0){if(c.text!=="breakpoint"||c.anchor===void 0)throw new Error('A debug source accepts text "breakpoint" with one anchor');let D=await p.resolveAnchor("anchor"),v=await t.addBreakpoint(c.path,D.lineNumber,p.signal);return{source:v.source,summary:`Breakpoint ${v.source} created at ${A.relative(g.options.cwd,v.file)}:${v.line}.`,data:{kind:"debug-breakpoint",session:g.source,file:v.file,line:v.line,verified:v.verified,snapshot:t.snapshot(g)}}}if(c.path!==g.source||c.anchor!==void 0)throw new Error("Debug commands target the session resource without an anchor");let f=await Ut(t,g,c.text,p.signal);return{source:g.source,summary:f===void 0?z(g):`${f.expression} = ${f.result}${f.type===void 0?"":` (${f.type})`}`,data:Gt(t,g,c.text,f)}},"execute")}),l.tool("delete").addSemanticHandler({matches:s(p=>Jt(p,t),"matches"),execute:s(async(p,m)=>{let c=m.path,g=ze(t,c),f=t.snapshot(g);n.set(c,f);let D=c.includes("/breakpoint/");await t.delete(c,p.signal);let v=D?t.snapshot(g):{...f,status:"terminated"};return{source:c,summary:`Deleted ${c}.`,data:{kind:D?"debug-breakpoint":"debug-session",deleted:!0,snapshot:v}}},"execute")}),l.describe('For debug:<session> resources, insert performs debugger actions without changing source text. On a debug source, insert "breakpoint" at an anchor. On the session, insert start, continue, step over, step into, step out, or evaluate <expression>. Delete removes a breakpoint or terminates the session.');for(let p of["insert","delete"])l.addToolRenderer({tool:p,matches(m,c){return c==="call"?$(m)&&typeof m.path=="string"&&(t.get(m.path)!==void 0||n.has(m.path)):te($(m)&&"details"in m?m.details:m)!==void 0},renderCall(m,c,g){let f=m,D=f.path===void 0?void 0:t.get(f.path),v=f.path===void 0?void 0:n.get(f.path),E=g.state;D!==void 0?E.snapshot=t.snapshot(D):v!==void 0&&(E.snapshot=v);let _=E.snapshot;if(_===void 0)throw new Error("Debugger renderer lost its session");let R=f.path===void 0?void 0:t.breakpoint(f.path)??_.breakpoints.find(X=>X.source===f.path),I=f.path===void 0?void 0:t.sourceFile(f.path),K=p==="delete"?R===void 0?"delete-session":`delete-breakpoint ${A.basename(R.file)}:${R.line}`:f.text==="breakpoint"&&I!==void 0?`breakpoint ${A.basename(I)}:${Wt(f)}`:f.text??"debug action";return $e(_,K,c)},renderResult(m,c,g){let f=te(m.details);if(f===void 0)throw new Error("Debugger result is missing its session");let D=qe(m.details);return N(f,c.expanded,g,D)}})}};await Promise.all([le(r,Ae),ge(r,u)]),await we(r,b),r.registerTool(Ht({name:"debug",exposure:"deferred",namespace:{name:"ide_debug",description:"Create local debugger sessions and inspect debug resources."},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1},label:"Debug session",promptSnippet:"Create a local DAP debug session before setting anchored breakpoints",description:"Use debug to create a configured local debugger session. This does not launch the program yet. The returned debug: resource survives extension reloads.",parameters:Nt,outputSchema:qt,async execute(l,p,m,c,g){let f=A.resolve(g.cwd,p.cwd??"."),D=A.resolve(f,p.program);try{await Lt(D);let v=t.create({adapter:p.adapter,program:D,sourceFile:A.resolve(f,p.source??p.program),args:p.args??[],cwd:f,...p.mainClass===void 0?{}:{mainClass:p.mainClass}}),E=Mt(t,v),{snapshot:_,stop:R,...I}=E;return Y({content:[{type:"text",text:`${z(v)}
21
21
  Source: ${E.sourceResource}
22
22
  Breakpoints: ${E.breakpointsResource}
23
23
 
@@ -1 +1 @@
1
- import{c as a,d as u,e as c}from"./chunk-OBNING2A.js";import{a as t}from"./chunk-EI7MMDWY.js";function E(o,r){let s=t(()=>{let e,i={plugin:r,accept(R){if(e!==void 0)throw new Error(`Plugin ${r.id} registration was accepted more than once`);e=R}};return o.events.emit(u,i),e},"announce"),n=t(()=>{},"unsubscribe");n=o.events.on(a,e=>{if(!c(e))throw new Error("Invalid pi-agent-read core readiness event");let i=s();if(i===void 0)throw new Error("pi-agent-read core announced readiness without accepting the plugin");n(),i.catch(()=>{})}),o.on("session_shutdown",n);let d=s();if(d!==void 0)return n(),d}t(E,"connectReadPlugin");export{E as a};
1
+ import{c as a,d as u,e as c}from"./chunk-S5PL5DFQ.js";import{a as t}from"./chunk-EI7MMDWY.js";function E(o,r){let s=t(()=>{let e,i={plugin:r,accept(R){if(e!==void 0)throw new Error(`Plugin ${r.id} registration was accepted more than once`);e=R}};return o.events.emit(u,i),e},"announce"),n=t(()=>{},"unsubscribe");n=o.events.on(a,e=>{if(!c(e))throw new Error("Invalid pi-agent-read core readiness event");let i=s();if(i===void 0)throw new Error("pi-agent-read core announced readiness without accepting the plugin");n(),i.catch(()=>{})}),o.on("session_shutdown",n);let d=s();if(d!==void 0)return n(),d}t(E,"connectReadPlugin");export{E as a};
@@ -0,0 +1,3 @@
1
+ import{a as i}from"./chunk-EI7MMDWY.js";import{AsyncLocalStorage as Ce}from"node:async_hooks";function oe(){return{pending:new Set,active:new Ce}}i(oe,"createSchedulerState");function ve(r,e){return r===void 0||e===void 0?!0:r.some(t=>e.some(n=>(t.mode==="write"||n.mode==="write")&&(t.resource==="*"||n.resource==="*"||t.resource===n.resource||t.recursive===!0&&n.resource.startsWith(t.resource.endsWith("/")?t.resource:`${t.resource}/`)||n.recursive===!0&&t.resource.startsWith(n.resource.endsWith("/")?n.resource:`${n.resource}/`))))}i(ve,"conflicts");function Re(r,e,t){if(e===void 0||!t&&e.some(o=>o.mode!=="read"))return!1;if(r===void 0)return!0;let n=new Map;for(let o of e){let s=o.group??o.resource;n.set(s,[...n.get(s)??[],o])}return[...n.values()].every(o=>o.some(s=>r.some(a=>(s.mode==="read"||a.mode==="write")&&(a.resource==="*"||s.resource===a.resource&&(s.recursive!==!0||a.recursive===!0)||a.recursive===!0&&s.resource.startsWith(a.resource.endsWith("/")?a.resource:`${a.resource}/`)))))}i(Re,"coveredAccess");async function we(r,e){if(e===void 0)return await r;e.throwIfAborted();let t,n=new Promise((o,s)=>{t=i(()=>s(e.reason),"abort"),e.addEventListener("abort",t,{once:!0})});try{return await Promise.race([r,n])}finally{e.removeEventListener("abort",t)}}i(we,"waitForDependencies");var U=class r{constructor(e=oe()){this.state=e}static{i(this,"ResourceScheduler")}run(e,t,n,o={}){let s=Promise.resolve(e),a=this.state.active.getStore();if(a?.open){let m=s.then(b=>{if(n?.throwIfAborted(),!Re(a.accesses,b,a.allowNestedWrites))throw Object.assign(new Error("Nested resource access must be covered by its parent reservation and permitted by its owner."),{code:"UNDECLARED_RESOURCE_ACCESS"});return b});a.nested??=new r;let y=a.nested.run(m,t,n,{allowNestedWrites:a.allowNestedWrites});return a.children.add(y),y.then(()=>a.children.delete(y),()=>a.children.delete(y)),y}let d=[...this.state.pending],u=s.catch(()=>{}),p,f=new Promise(m=>{p=m}),h={accesses:u,done:f};return this.state.pending.add(h),(async()=>{try{n?.throwIfAborted();let m=await we(s.then(async b=>(await Promise.all(d.map(q=>Promise.race([q.done,q.accesses.then(ye=>ve(b,ye)?q.done:void 0)]))),b)),n);n?.throwIfAborted();let y={accesses:m,children:new Set,open:!0,allowNestedWrites:o.allowNestedWrites===!0};try{return await this.state.active.run(y,t)}finally{for(;y.children.size>0;)await Promise.allSettled([...y.children]);y.open=!1}}finally{this.state.pending.delete(h),p()}})()}},Te=Symbol.for("pi-agent-resource.resource-scheduler-state"),be=globalThis,Ee=be[Te]??=oe(),Se=new U(Ee);import{realpath as xe,stat as Ae}from"node:fs/promises";import j from"node:path";import{fileURLToPath as Oe}from"node:url";async function se(r,e,t){if(/^[a-z][a-z\d+.-]*:/iu.test(r)&&!/^[a-z]:[\\/]/iu.test(r)&&!r.startsWith("file:"))return[{resource:r,mode:t}];let n=j.resolve(e,r.startsWith("file:")?Oe(r):r),[o,s]=await Promise.allSettled([xe(n),Ae(n,{bigint:!0})]),a;if(o.status==="fulfilled")a=o.value;else{let f=o.reason;if(!(f instanceof Error)||!("code"in f)||f.code!=="ENOENT")throw f;let h=j.dirname(n);if(h===n)a=n;else{let y=(await se(h,e,t)).find(b=>b.resource.startsWith("file:"));a=j.join(y?.resource.slice(5)??h,j.basename(n))}}let d=a.split(j.sep).join("/"),u=`file:${process.platform==="win32"?d.toLowerCase():d}`,p=[{resource:u,group:u,mode:t}];if(s.status==="fulfilled"){let f=s.value;f.isDirectory()&&(p[0]={resource:u,group:u,mode:t,recursive:!0}),f.ino!==0n&&p.push({resource:`inode:${f.dev}:${f.ino}`,group:u,mode:t,recursive:f.isDirectory()})}else{let f=s.reason;if(!(f instanceof Error)||!("code"in f)||f.code!=="ENOENT")throw f}return p}i(se,"resourceAccesses");import{Type as g}from"typebox";import{Value as ke}from"typebox/value";var D=g.Object({code:g.String(),message:g.String(),source:g.Optional(g.String())},{additionalProperties:!1});function ie(r){return{...g.Union([g.Object({status:g.Literal("success"),data:r,errors:g.Array(D,{maxItems:0})},{additionalProperties:!1}),g.Object({status:g.Union([g.Literal("error"),g.Literal("partial")]),data:g.Optional(r),errors:g.Array(D,{minItems:1})},{additionalProperties:!1})]),type:"object",properties:{status:g.Union([g.Literal("success"),g.Literal("error"),g.Literal("partial")]),data:g.Optional(r),errors:g.Array(D)},required:["status","errors"],additionalProperties:!1}}i(ie,"structuredResultSchema");var ae=1024*1024;function z(r){let e=new Set,t=i(n=>{if(!(n===null||typeof n=="string"||typeof n=="boolean")&&!(typeof n=="number"&&Number.isFinite(n))){if(typeof n!="object"||e.has(n))throw new TypeError("Structured data must be finite, acyclic JSON");if(!Array.isArray(n)&&Object.getPrototypeOf(n)!==Object.prototype&&Object.getPrototypeOf(n)!==null)throw new TypeError("Structured data must not contain classes or raw byte buffers");e.add(n);for(let o of Array.isArray(n)?n:Object.values(n))t(o);e.delete(n)}},"visit");if(t(r),Buffer.byteLength(JSON.stringify(r))>ae)throw new RangeError("Structured data exceeds 1 MiB; return a smaller window or a full-result reference")}i(z,"assertJsonData");function ce(r,e="EXECUTION_FAILED",t){return{code:typeof r=="object"&&r!==null&&"code"in r&&typeof r.code=="string"?r.code:e,message:r instanceof Error?r.message:String(r),...t===void 0?{}:{source:t}}}i(ce,"resultError");function Ne(r,e,t){try{if(z(t),!ke.Check(ie(e),t))throw new TypeError("Result adapter returned data outside its public schema");return{...r,structuredContent:t,isError:t.status!=="success"}}catch(n){let o=ce(n,"INVALID_STRUCTURED_RESULT"),s={status:"error",errors:[o]};return z(s),{...r,content:[...r.content,{type:"text",text:o.message}],structuredContent:s,isError:!0}}}i(Ne,"withStructuredResult");function je(r,e){if(e.length===0)return;let t=r.trim();if(t.length===0||/[\r\n]/u.test(t))throw new TypeError("Content provider summary must be one non-empty line");return[t,...e.map(({description:n})=>n)].join(`
2
+ `)}i(je,"renderContentDescription");import{Type as l}from"typebox";import{Value as He}from"typebox/value";import{Type as c}from"typebox";import{Value as Pe}from"typebox/value";var C={additionalProperties:!0},P=c.Function([],c.Unknown()),v=c.String({minLength:1}),Ie=c.Object({type:c.Literal("text"),text:c.String(),textSignature:c.Optional(c.String())},C),_e=c.Object({type:c.Literal("image"),data:c.String(),mimeType:c.String()},C),Ue=c.Object({type:c.Literal("custom"),kind:v,data:c.Unknown()},C),De=c.Array(c.Union([Ie,_e,Ue]),{minItems:1}),ue=c.Union([c.Object({source:v,link:c.Optional(v),read:P,write:c.Optional(c.Never())},C),c.Object({source:v,link:c.Optional(v),read:c.Optional(c.Never()),write:P},C),c.Object({source:v,link:c.Optional(v),read:P,write:P},C)]),Le=c.Object({id:v,tryResolve:P},C),$e=c.Union([c.Object({kind:c.Literal("not-handled")},C),c.Object({kind:c.Literal("resolved"),resource:ue},C),c.Object({kind:c.Literal("failed"),error:c.Unknown()},C)]);function J(r){return L(De,r)?$(()=>r.every(e=>e.type!=="text"||!("textSignature"in e)||typeof e.textSignature=="string")):!1}i(J,"isAgentContent");function le(r){return L(ue,r)?$(()=>{let e=r,t=!("read"in e)||typeof e.read=="function",n=!("write"in e)||typeof e.write=="function";return t&&n}):!1}i(le,"isResource");function We(r){return L(Le,r)}i(We,"isResourceResolver");function Ve(r){return L($e,r)?$(()=>{let e=r;return e.kind!=="resolved"||le(e.resource)}):!1}i(Ve,"isResourceResolutionAttempt");function L(r,e){return $(()=>Pe.Check(r,e))}i(L,"safeCheck");function $(r){try{return r()}catch{return!1}}i($,"safeEvaluate");var R={additionalProperties:!0},Me=l.Function([],l.Unknown()),W=l.String({minLength:1}),Fe=l.Object({provider:W,capability:l.Union([l.Literal("read"),l.Literal("write")])},R),Ke=l.Object({source:W,bytes:l.Unknown(),mediaType:l.Optional(l.String())},R),qe=l.Object({signal:l.Optional(l.Unknown())},R),ze=l.Object({id:W,description:W,tryConvert:Me},R),Je=l.Union([l.Object({kind:l.Literal("not-handled")},R),l.Object({kind:l.Literal("converted"),content:l.Unknown()},R),l.Object({kind:l.Literal("failed"),error:l.Unknown()},R)]),Be=l.Object({target:l.Unknown(),converter:l.Unknown(),priority:l.Optional(l.Number())},R);function A(r){return O(Fe,r)&&S(()=>r.provider.trim().length>0)}i(A,"isContentTarget");function B(r){return O(Ke,r)?S(()=>{let e=r;return e.bytes instanceof Uint8Array&&(!("mediaType"in e)||typeof e.mediaType=="string")}):!1}i(B,"isContentInput");function Y(r){return O(qe,r)?S(()=>{let e=r;return!("signal"in e)||e.signal instanceof AbortSignal}):!1}i(Y,"isContentConversionContext");function de(r){return O(ze,r)?S(()=>{let e=r;return e.id.trim().length>0&&e.description.trim().length>0&&!/[\r\n]/u.test(e.description)}):!1}i(de,"isContentConverter");function G(r){return O(Je,r)?S(()=>{let e=r;return e.kind!=="converted"||J(e.content)}):!1}i(G,"isContentConversionAttempt");function E(r){return O(Be,r)?S(()=>{let e=r;return A(e.target)&&de(e.converter)&&(!("priority"in e)||typeof e.priority=="number"&&Number.isFinite(e.priority))}):!1}i(E,"isContentConverterRegistration");function O(r,e){return S(()=>He.Check(r,e))}i(O,"safeCheck");function S(r){try{return r()}catch{return!1}}i(S,"safeEvaluate");var V=class extends Error{static{i(this,"UnsupportedContentError")}source;target;constructor(e,t){super(`No content converter for ${e} in ${t.provider}/${t.capability}`),this.name="UnsupportedContentError",this.source=e,this.target=t}};function Q(r){if(!A(r))throw new TypeError("Invalid content target");let e={...r},t=[],n=i(()=>[...t].sort((o,s)=>o.priority-s.priority||o.order-s.order),"snapshotConverters");return{target:e,register(o){if(!E(o))throw new TypeError("Invalid content converter registration");if(!k(e,o.target))throw new Error(`Content converter ${o.converter.id} targets ${o.target.provider}/${o.target.capability}, not ${e.provider}/${e.capability}`);if(t.some(({converter:s})=>s.id===o.converter.id))throw new Error(`Content converter ${o.converter.id} is already registered for ${e.provider}/${e.capability}`);t.push({converter:o.converter,priority:o.priority??0,order:t.length})},listDescriptions(){return n().map(({converter:o})=>({id:o.id,description:o.description}))},async convert(o,s){if(!B(o))throw new TypeError("Invalid content input");if(!Y(s))throw new TypeError("Invalid content conversion context");X(s.signal);let a=n();for(let{converter:d}of a){X(s.signal);let u=await d.tryConvert(o,s);if(X(s.signal),!G(u))throw new TypeError(`Content converter ${d.id} returned an invalid outcome`);if(u.kind!=="not-handled"){if(u.kind==="failed")throw u.error;return u.content}}throw new V(o.source,e)}}}i(Q,"createContentRunner");function k(r,e){return r.provider===e.provider&&r.capability===e.capability}i(k,"targetsEqual");function X(r){r?.throwIfAborted()}i(X,"throwIfAborted");import{Type as w}from"typebox";import{Value as Ye}from"typebox/value";var N="pi-agent-resource/content-conversion",H=2,I=`${N}/host/ready`,_=`${N}/converter/register`,fe={additionalProperties:!0},Ge=w.Function([],w.Unknown()),Xe=w.Object({protocol:w.Literal(N),apiVersion:w.Literal(H),target:w.Unknown()},fe),Qe=w.Object({registration:w.Unknown(),accept:Ge},fe);function Z(r){return pe(Xe,r)&&te(()=>A(r.target))}i(Z,"isContentHostReady");function ee(r){return pe(Qe,r)&&te(()=>E(r.registration))}i(ee,"isContentConverterRegistrationRequest");function pe(r,e){return te(()=>Ye.Check(r,e))}i(pe,"safeCheck");function te(r){try{return r()}catch{return!1}}i(te,"safeEvaluate");function Ze(r,e){let t=Q(e),n=r.events.on(_,o=>{if(!ee(o))throw new Error("Invalid content converter registration request");if(!k(t.target,o.registration.target))return;let s;try{t.register(o.registration),s=Promise.resolve()}catch(a){s=Promise.reject(a instanceof Error?a:new Error("Content converter registration failed",{cause:a}))}o.accept(s)});return r.on("session_shutdown",n),r.events.emit(I,{protocol:N,apiVersion:H,target:t.target}),{target:t.target,listDescriptions(){return t.listDescriptions()},convert(o,s){return t.convert(o,s)}}}i(Ze,"createContentHost");function et(r,e){if(!E(e))throw new TypeError("Invalid content converter registration");let t=i(()=>{let s,a={registration:e,accept(d){if(s!==void 0)throw new Error(`Content converter ${e.converter.id} registration was accepted more than once`);s=d}};return r.events.emit(_,a),s},"announce"),n=i(()=>{},"unsubscribe");n=r.events.on(I,s=>{if(!Z(s))throw new Error("Invalid content conversion host readiness event");if(!k(e.target,s.target))return;let a=t();if(a===void 0)throw new Error(`${s.target.provider}/${s.target.capability} announced readiness without accepting content converter ${e.converter.id}`);n(),a.catch(()=>{})}),r.on("session_shutdown",n);let o=t();if(o!==void 0)return n(),o}i(et,"connectContentConverter");import{createHash as ge,randomUUID as re}from"node:crypto";import{statSync as tt}from"node:fs";import{readFile as rt}from"node:fs/promises";import T from"node:path";import{fileURLToPath as nt}from"node:url";import{Type as M}from"typebox";var ot=M.Union([M.String(),M.Array(M.String())]),x="RESULT#",he="pi-agent-resource:result-targets",K=class{static{i(this,"ResultTargetStore")}#e=new Map;#o=new Map;#n=new Map;#t=new Map;clear(){this.#e.clear(),this.#o.clear(),this.#n.clear(),this.#t.clear()}register(e,t,n=!0){for(let s of e)this.refresh(s.source,t);let o=`${x}${re()}`;return this.#e.set(o,{state:"ready",targets:ne(e),complete:n,cwd:T.resolve(t)}),o}reserve(e){let t=`${x}${re()}`;return this.#e.set(t,{state:"pending",cwd:T.resolve(e)}),t}confirm(e,t,n){let o=this.#e.get(e);if(o?.state!=="pending"||o.cwd!==T.resolve(n))throw new Error("Only a pending result in this worktree can be confirmed.");for(let s of t)this.refresh(s.source,n);this.#e.set(e,{state:"ready",cwd:o.cwd,targets:ne(t),complete:!0})}reject(e,t){let n=this.#e.get(e);n?.state==="pending"&&this.#e.set(e,{state:"rejected",cwd:n.cwd,reason:t})}resolve(e,t){e=this.source(e,t);let n=this.#r(e),o=[],s=!0;for(let a of n){let d=this.#e.get(a);if(d===void 0)throw new Error("Result target expired or unknown; repeat Read/Search.");if(d.cwd!==T.resolve(t))throw new Error("Result target belongs to another worktree.");if(d.state==="pending")throw new Error("Result target is pending; its write has not been confirmed.");if(d.state==="rejected")throw new Error(d.reason);for(let u of d.targets)this.refresh(u.source,t);if(!this.#e.has(a))throw new Error("Result target expired after its snapshot changed; repeat Read/Search.");s&&=d.complete,o.push(...d.targets)}return{targets:ne(o),complete:s}}resolveOrdered(e,t){let n=this.resolve(e,t),o=[],s=new Set;for(let a of new Set(this.#r(this.source(e,t))))for(let d of this.resolve(a,t).targets)for(let u of d.ranges){let p=JSON.stringify([d.source,u]);s.has(p)||(s.add(p),o.push({...d,ranges:[u]}))}return{targets:o,complete:n.complete}}async verify(e,t){try{await me(e,t)}catch(n){if(!t?.aborted)for(let o of e.targets)this.invalidate(o.source);throw n}}publish(e,t,n,o=[]){let s=re();for(let p of o)this.refresh(p,n);let a=[];try{a=this.#r(e)}catch{}let d=`<system-result note="Internal reference; not part of the file. Do not edit."><uuid>${s}</uuid></system-result>
3
+ ${t}`,u=e!==null&&typeof e=="object"&&"status"in e&&e.status==="success";if(u&&"data"in e){let p=e.data;if(p!==null&&typeof p=="object"&&"matches"in p&&Array.isArray(p.matches)){let f=p.matches;for(let h of f){if(h===null||typeof h!="object"||!("target"in h)||typeof h.target!="string"||!this.#e.has(h.target)||!("references"in h))continue;let m=h.references;m!==null&&typeof m=="object"&&"match"in m&&typeof m.match=="string"&&/^SEARCH#[A-F\d]+:\d+:match$/u.test(m.match)&&this.#o.set(m.match,h.target)}}}return this.#t.set(s,{cwd:T.resolve(n),digest:ge("sha256").update(d).digest("hex"),consumable:u,references:a,resources:o}),d}source(e,t,n=!1){if(Array.isArray(e))return e.map(f=>this.source(f,t,n));if(typeof e!="string")return e;let o=this.#o.get(e);if(o)return this.source(o,t,n);let s=/^<system-result\b[^>]*><uuid>([a-f\d-]{36})<\/uuid><\/system-result>(?:\n|$)/u.exec(e),a=s?.[1]??(e.startsWith(x)?e.slice(x.length):e),d=/^[a-f\d]{8}-[a-f\d]{4}-[a-f\d]{4}-[a-f\d]{4}-[a-f\d]{12}$/u.test(a);if(!s&&!d){if(e.startsWith("<system-result"))throw new Error("Invalid system result reference.");return e}let u=this.#t.get(a);if(!u&&!s&&e.startsWith(x)&&this.#e.has(e))return e;if(!u)throw new Error("Result reference expired or unknown; repeat the source tool.");if(u.cwd!==T.resolve(t))throw new Error("Result belongs to another worktree.");if(s&&ge("sha256").update(e).digest("hex")!==u.digest)throw new Error("Result text changed; pass the original result or its UUID.");for(let f of u.resources)this.refresh(f,t);if(!this.#t.has(a))throw new Error("Result reference expired; repeat the source tool.");if(!u.consumable)throw new Error("Only successful source results can be consumed.");for(let f of u.references)if(!this.#e.has(f))throw this.#t.delete(a),new Error("Result reference expired; repeat the source tool.");if(u.references.length===1)return u.references[0];if(u.references.length>1)return u.references;let p=u.resources.length===1?u.resources[0]:void 0;if(p&&(n===!0||n==="live"&&/^(?:shell|debug):/u.test(p)))return p;throw new Error("This result has no reusable text selection.")}invalidate(e){let t=new Set;for(let[n,o]of this.#e)o.state==="ready"&&o.targets.some(s=>F(s.source,o.cwd)===e)&&(this.#e.delete(n),t.add(n));for(let[n,o]of this.#t)(o.resources.some(s=>F(s,o.cwd)===e)||o.references.some(s=>t.has(s)))&&this.#t.delete(n)}refresh(e,t){let n=F(e,t),o=JSON.stringify([T.resolve(t),n]),s=st(e,t),a=this.#n.get(o);a&&a.stamp!==s&&this.invalidate(n),this.#n.set(o,{source:e,cwd:t,stamp:s})}refreshAll(){for(let e of[...this.#n.values()])this.refresh(e.source,e.cwd)}#r(e){if(typeof e=="string"&&e.startsWith(x))return[e];if(Array.isArray(e))return e.flatMap(n=>this.#r(n));if(e===null||typeof e!="object")throw new Error("Unsupported result input.");let t=e;if("status"in t){if(t.status!=="success")throw new Error("Only successful source results can be consumed.");return this.#r(t.data)}if(typeof t.target=="string"&&t.target.startsWith(x))return[t.target];if(t.kind==="resources"&&Array.isArray(t.resources))return this.#r(t.resources);throw new Error("This result has no supported source target; do not use preview text as a source.")}};function F(r,e){let t=r.startsWith("raw:")?r.slice(4):r;if(t.startsWith("file:"))try{return nt(t)}catch{}return T.resolve(e,t)}i(F,"sourcePath");function st(r,e){try{let t=tt(F(r,e),{bigint:!0});return`${t.dev}:${t.ino}:${t.size}:${t.mtimeNs}:${t.ctimeNs}`}catch{return}}i(st,"fileStamp");async function me(r,e){let t=new Map;for(let n of r.targets){e?.throwIfAborted();let o=t.get(n.source);if(o===void 0&&(o=await rt(n.source,{encoding:"utf8",signal:e}),t.set(n.source,o)),o!==n.expectedContent)throw new Error("Result target is stale; repeat Read/Search.")}}i(me,"verifyResultTargets");function ne(r){let e=new Map;for(let t of r){let n=e.get(t.source);if(n!==void 0&&n.expectedContent!==t.expectedContent)throw new Error("Result targets refer to different snapshots of the same source.");let o=n??{source:t.source,expectedContent:t.expectedContent,ranges:[],seen:new Set};for(let s of t.ranges){let a=JSON.stringify(s);o.seen.has(a)||(o.seen.add(a),o.ranges.push(structuredClone(s)))}e.set(t.source,o)}return[...e.values()].filter(t=>t.ranges.length>0).map(({seen:t,...n})=>({...n,ranges:n.ranges.sort((o,s)=>o.start.lineNumber-s.start.lineNumber||o.start.column-s.start.column||o.end.lineNumber-s.end.lineNumber||o.end.column-s.end.column)}))}i(ne,"combineTargets");function it(r){let e;if(r.events.emit(he,{accept:i(o=>{e=o},"accept")}),e!==void 0)return e;let t=new K,n=r.events.on(he,o=>{o!==null&&typeof o=="object"&&"accept"in o&&typeof o.accept=="function"&&o.accept(t)});return r.on("session_start",()=>{t.clear()}),r.on("session_shutdown",()=>{t.clear(),n()}),t}i(it,"connectResultTargets");export{U as a,Se as b,se as c,D as d,ie as e,ae as f,z as g,ce as h,Ne as i,je as j,J as k,le as l,We as m,Ve as n,A as o,B as p,Y as q,de as r,G as s,E as t,V as u,Q as v,k as w,N as x,H as y,I as z,_ as A,Z as B,ee as C,Ze as D,et as E,ot as F,K as G,me as H,it as I};
@@ -0,0 +1,2 @@
1
+ import{e as m,i as g,m as x}from"./chunk-CWD4O5PM.js";import{a as i}from"./chunk-EI7MMDWY.js";import{Type as n}from"typebox";import{Value as y}from"typebox/value";import{Type as d}from"typebox";var c=d.Object({path:d.Optional(d.String({description:"What to read: a supported resource such as a file or directory path, URL, returned temp: reference, SEARCH# or RESULT# reference, or registered protocol source. Supply a path; an empty call cannot select a source."})),offset:d.Optional(d.Number({description:"For raw: sources, use a zero-based byte offset; negative offsets count from the file end. For other sources: first line to return, numbered from 1. Omit or use 0 to start at line 1; -1 starts at the last line, -10 at the tenth line from the end. For path#anchor, SEARCH or RESULT# selections, count from its containing line instead: 0 or 1 starts there, 2 starts one line later, -1 one line earlier. For image and sequence views, offset is a zero-based row-major grid cell index and requires limit."})),limit:d.Optional(d.Number({description:"For raw: sources, use a non-negative byte count (0 reads no bytes). Otherwise, maximum lines from the selected starting position. Output is bounded; omit for the default read. For image and sequence views, limit is the square grid cell size in pixels; omit offset to select cell 0, or omit both for the bounded full image."})),views:d.Optional(d.Array(d.String(),{description:`Optional source-specific presentations. Combine views when both presentations are needed, for example ["anchors", "ast"]. Omit for the source's default presentation.`}))}),O={path:"What to read: a resource path, unchanged source result or its UUID. Pass the whole result to compose tools. Supply a source; an empty call cannot select one. temp:<id> reads saved complete output until this runtime is disposed. raw:<local-file> reads original bytes from a regular file (relative, absolute or file:// path); raw: does not accept views.",offset:"For raw: sources, a zero-based integer byte offset; negative offsets count from the file end. For text sources, the first line to return, numbered from 1. Omit or use 0 to start at line 1; -1 starts at the last line, -10 at the tenth line from the end.",limit:"For raw: sources, a non-negative integer byte count (0 reads no bytes). For text sources, the maximum lines from the selected starting position. Omit for the bounded default read. Explicit ranges on other content require a source-specific handler; otherwise they fail.",views:"Optional source-specific presentations. Omit for the source's default presentation. Values may include settings after a colon; use the syntax below. Combine views only when their contracts allow it. Unknown views can be ignored and reported in ignoredViews; they do not add capabilities. raw: sources reject views."};function H(e){let r=i((o,u)=>({...o,description:[O[u],e[u]].filter(R=>R!==void 0).join(`
2
+ `)}),"describe");return{...c,properties:{path:r(c.properties.path,"path"),offset:r(c.properties.offset,"offset"),limit:r(c.properties.limit,"limit"),views:r(c.properties.views,"views")}}}i(H,"describeReadParameters");import{Type as t}from"typebox";var w=t.Object({value:t.String(),kind:t.String(),state:t.Optional(t.String())},{additionalProperties:!1}),k=t.Object({lineNumber:t.Integer(),content:t.String(),lineEnding:t.String(),anchors:t.Optional(t.Array(t.String()))},{additionalProperties:!1}),L=t.Object({path:t.String(),offset:t.Integer()},{additionalProperties:!1}),f={source:t.String(),truncated:t.Boolean(),continuation:t.Optional(L),fullResult:t.Optional(t.String())},h=t.Object({...f,kind:t.Literal("text"),target:t.Optional(t.String()),lines:t.Array(k),startLine:t.Integer(),endLine:t.Integer(),totalLines:t.Integer(),references:t.Optional(t.Array(w))},{additionalProperties:!1}),b=t.Object({...f,kind:t.Literal("bytes"),bytes:t.Array(t.Integer({minimum:0,maximum:255})),byteOffset:t.Integer(),byteLength:t.Integer(),totalBytes:t.Integer()},{additionalProperties:!1}),P=t.Union([t.Object({type:t.Literal("text"),text:t.String()},{additionalProperties:!1}),t.Object({type:t.Literal("image"),mimeType:t.String()},{additionalProperties:!1})]),S=t.Object({...f,kind:t.Literal("native"),blocks:t.Array(P)},{additionalProperties:!1}),p=t.Union([t.Object({kind:t.Literal("recovery"),source:t.String(),candidates:t.Array(t.Object({path:t.String()},{additionalProperties:!1}))},{additionalProperties:!1}),h,b,S,t.Object({kind:t.Literal("resources"),source:t.Optional(t.String()),resources:t.Array(t.Union([h,b,S])),truncated:t.Boolean(),fullResult:t.Optional(t.String())},{additionalProperties:!1})]),v=m(p);function C(e){return{lineNumber:e.lineNumber,content:e.content,lineEnding:e.lineEnding,...e.anchors===void 0?{}:{anchors:[...e.anchors]}}}i(C,"publicLine");function T(e){if(e.kind==="resources"){let a=e.resources.map(s=>T(s));return{kind:e.kind,...e.source===void 0?{}:{source:e.source},resources:a,truncated:a.some(s=>typeof s=="object"&&s!==null&&"truncated"in s&&s.truncated===!0)}}if(e.kind==="bytes"){let a=e.bytes.slice(0,32768),s=e.truncated===!0||a.length<e.bytes.length;return{kind:e.kind,source:e.source,bytes:a,byteOffset:e.byteOffset,byteLength:a.length,totalBytes:e.totalBytes,truncated:s,...e.byteOffset+a.length<e.totalBytes?{continuation:{path:e.source,offset:e.byteOffset+a.length}}:{}}}if(e.kind==="native")return{kind:e.kind,source:e.source,truncated:!1,blocks:e.blocks.map(a=>{if(a.type==="text")return{type:a.type,text:a.text};if(a.type==="image")return{type:a.type,mimeType:a.mimeType};throw new TypeError("Custom content requires a structured adapter")})};let r=[],o=0;for(let a of e.lines){let s=C(a);if(o+=Buffer.byteLength(JSON.stringify(s)),r.length>=2e3||o>512*1024)break;r.push(s)}if(r.length===0&&e.lines.length>0)throw new RangeError("Selected line exceeds the structured window; use a raw byte range or a source-specific view");let u=r.length<e.lines.length,R=r.at(-1)?.lineNumber??e.startLine-1;return{kind:e.kind,source:e.source,lines:r,startLine:r[0]?.lineNumber??0,endLine:r.at(-1)?.lineNumber??0,totalLines:e.totalLines,truncated:u,...e.target===void 0?{}:{target:e.target},...e.references===void 0?{}:{references:e.references},...u||R<e.totalLines?{continuation:{path:e.source,offset:R+1}}:{}}}i(T,"publicData");function E(e){let r=e.details.failure;if(e.isError||r!==void 0)return g(e,p,{status:"error",...r?.candidates?.length&&r.source!==void 0?{data:{kind:"recovery",source:r.source,candidates:r.candidates}}:{},errors:[{code:r?.code??"READ_FAILED",message:r?.message??"Read failed",...r?.source===void 0?{}:{source:r.source}}]});try{if(e.script===void 0)throw new TypeError("Read handler must return structured script data");let o=T(e.script);return g(e,p,{status:"success",data:e.details.temporarySource!==void 0&&typeof o=="object"&&o!==null?{...o,fullResult:e.details.temporarySource}:o,errors:[]})}catch(o){return g(e,p,{status:"error",errors:[{code:o instanceof RangeError?"STRUCTURED_RESULT_TOO_LARGE":"STRUCTURED_ADAPTER_REQUIRED",message:o instanceof Error?o.message:String(o)}]})}}i(E,"structuredRead");var l=n.Function([],n.Unknown()),D=n.Object({resolver:n.Unknown(),matchesCall:n.Optional(l),renderCall:n.Optional(l),priority:n.Optional(n.Number()),renderResult:n.Optional(l),preserveTruncatedOutput:n.Optional(n.Boolean())}),A=n.Object({resolver:n.Unknown(),priority:n.Optional(n.Number())}),F=n.Object({id:n.String({pattern:"\\S"}),priority:n.Optional(n.Number()),resolve:l}),N=n.Object({view:n.String({pattern:"\\S"}),includes:n.Optional(n.Array(n.String({pattern:"\\S"}))),presenter:n.Object({id:n.String(),present:l}),priority:n.Optional(n.Number())}),U=n.Object({resolvedBy:n.String({pattern:"\\S"}),contentKind:n.Union([n.Literal("text"),n.Literal("any")])}),j=n.Union([n.Object({stage:n.Literal("pre-read"),handler:l}),n.Object({stage:n.Literal("read"),when:U,handler:l}),n.Object({stage:n.Literal("post-read"),handler:l})]);function J(e){if(!y.Check(A,e))return!1;let r=e,o=r.resolver;return typeof o.id=="string"&&o.id.length>0&&typeof o.tryResolve=="function"&&(!("priority"in r)||typeof r.priority=="number")}i(J,"isTextTargetResolverRegistration");function Y(e){if(!y.Check(D,e))return!1;let r=e;return x(r.resolver)?r.resolver.id!=="any"&&(!("priority"in r)||typeof r.priority=="number")&&(!("matchesCall"in r)||typeof r.matchesCall=="function")&&(!("renderCall"in r)||typeof r.renderCall=="function")&&"matchesCall"in r=="renderCall"in r&&(!("renderResult"in r)||typeof r.renderResult=="function"):!1}i(Y,"isResourceResolverRegistration");function X(e){return y.Check(j,e)}i(X,"isReadHandlerRegistration");function Z(e){return y.Check(N,e)}i(Z,"isReadViewRegistration");function $(e){return y.Check(F,e)}i($,"isFragmentResolverRegistration");function ee(e){return I(e)?e.kind==="not-handled"?!0:e.kind==="failed"?typeof e.message=="string"&&e.message.length>0:e.kind==="resolved"&&typeof e.originLine=="number":!1}i(ee,"isReadFragmentResolution");function I(e){return typeof e=="object"&&e!==null}i(I,"isRecord");export{c as a,H as b,p as c,v as d,E as e,J as f,Y as g,X as h,Z as i,$ as j,ee as k};
@@ -0,0 +1 @@
1
+ import{F as d,e as c}from"./chunk-CWD4O5PM.js";import{a as s}from"./chunk-EI7MMDWY.js";import{Type as t}from"typebox";var y=t.Object({query:t.String({minLength:1,description:"Text to find, a Boolean expression, or a prefixed query described below, such as files:*.ts. Quote text to keep it literal, or use regex:<pattern> for regular-expression matching."}),path:t.Optional({...d,description:"File, directory, URL, unchanged Read/Search/Select/edit result, its UUID, or an array of such results. Results select only their registered ranges unless symbols: navigation follows external references."}),navigation:t.Optional(t.Literal("references",{description:"Only for symbols: queries. Explicitly follow symbols represented inside path to their references outside that scope. Without navigation, all returned ranges stay inside path."})),include:t.Optional(t.String({description:"Optional include glob for local search"})),exclude:t.Optional(t.String({description:"Optional exclude glob for local search"})),caseSensitive:t.Optional(t.Boolean({description:"Match letter case"})),wholeWord:t.Optional(t.Boolean({description:"Match complete words"})),limit:t.Optional(t.Integer({minimum:1,maximum:1e3,description:"Maximum detailed results returned to the agent (default 50)"}))},{additionalProperties:!1});import{Type as e}from"typebox";var u=e.Object({startLine:e.Integer(),startColumn:e.Integer(),endLine:e.Integer(),endColumn:e.Integer()},{additionalProperties:!1}),m=e.Object({line:e.Optional(e.String()),match:e.Optional(e.String())},{additionalProperties:!1}),p={source:e.String(),target:e.Optional(e.String()),range:u,matchedText:e.Optional(e.String()),textTruncated:e.Optional(e.Boolean()),references:e.Optional(m)},f=e.Object({...p,captures:e.Optional(e.Record(e.String(),e.Array(e.Object(p,{additionalProperties:!1})))),role:e.Optional(e.Union([e.Literal("definition"),e.Literal("reference")])),symbol:e.Optional(e.Object({id:e.String(),name:e.String(),kind:e.String(),source:e.String(),range:u},{additionalProperties:!1}))},{additionalProperties:!1}),g={target:e.Optional(e.String()),kind:e.Literal("matches"),truncated:e.Optional(e.Boolean()),fullResult:e.Optional(e.String()),complete:e.Boolean(),matches:e.Array(f),all:e.Optional(m),notices:e.Optional(e.Array(e.String()))},h=e.Object({status:e.Union([e.Literal("ready"),e.Literal("skipped")]),message:e.Optional(e.String()),candidates:e.Array(e.Object({identifier:e.String(),kind:e.Union([e.Literal("normalized"),e.Literal("component"),e.Literal("typo")]),reason:e.String(),matchCount:e.Integer(),fileCount:e.Integer(),selection:e.Object(g,{additionalProperties:!1})},{additionalProperties:!1}))},{additionalProperties:!1}),O=e.Union([e.Object({...g,fuzzy:e.Optional(h)},{additionalProperties:!1}),e.Object({kind:e.Literal("files"),complete:e.Boolean(),files:e.Array(e.String())},{additionalProperties:!1}),e.Object({kind:e.Literal("custom"),resolverId:e.String(),value:e.Unknown()},{additionalProperties:!1})]),P=c(O);function T(o,l,r,i){return{kind:"matches",...i?.target===void 0?{}:{target:i.target},truncated:o.length>100,complete:l,matches:o.slice(0,100).map((n,a)=>({source:n.source,...i?.matchTargets?.[a]===void 0?{}:{target:i.matchTargets[a]},range:{startLine:n.lineNumber,startColumn:n.startColumn,endLine:n.endLineNumber??n.lineNumber,endColumn:n.endColumn},...Buffer.byteLength(n.matchedText)<=4096?{matchedText:n.matchedText}:{textTruncated:!0},...r===void 0?{}:{references:{line:`SEARCH#${r}:${a+1}:line`,match:`SEARCH#${r}:${a+1}:match`}}})),...l&&r!==void 0?{all:{line:`SEARCH#${r}:all:line`,match:`SEARCH#${r}:all:match`}}:{}}}s(T,"selectionData");export{y as a,h as b,O as c,P as d,T as e};
@@ -1,2 +1,2 @@
1
- import{d as R}from"./chunk-3JO7QFIL.js";import{a as S}from"./chunk-PS2B6THP.js";import{t as p,u as y}from"./chunk-ZPT5D4VP.js";import{a as c}from"./chunk-EI7MMDWY.js";import{keyText as C}from"@earendil-works/pi-coding-agent";import{Text as D}from"@earendil-works/pi-tui";function x(e){return e.replaceAll("\u27E6","").replaceAll("\u27E7","")}c(x,"sourceText");function w(e,r){let{files:o,...t}=e,s=x(r);return{...t,storedFiles:o.map(({lines:l,...a})=>({...a,lines:l.map(n=>{let i=[n.lineNumber,p(n.text,s),n.ranges];return n.logicalMatchIds===void 0?i:[...i,n.logicalMatchIds]})}))}}c(w,"compactSearchDetails");function g(e,r){if("files"in e)return e;let{storedFiles:o,...t}=e,s=x(r);return{...t,files:o.map(({lines:l,...a})=>({...a,lines:l.map(([n,i,h,u])=>({lineNumber:n,text:y(i,s),ranges:h,matchCount:h.length,...u===void 0?{}:{logicalMatchIds:u}}))}))}}c(g,"restoreSearchDetails");var k=new WeakMap,z=12;function v(e,r,o,t){if(typeof e.details=="object"){let a=k.get(e.details);a===void 0&&(a=g(e.details,e.content.flatMap(n=>n.type==="text"?[n.text]:[]).join(`
1
+ import{d as R}from"./chunk-WU6ZK6YD.js";import{a as S}from"./chunk-PS2B6THP.js";import{t as p,u as y}from"./chunk-ZPT5D4VP.js";import{a as c}from"./chunk-EI7MMDWY.js";import{keyText as C}from"@earendil-works/pi-coding-agent";import{Text as D}from"@earendil-works/pi-tui";function x(e){return e.replaceAll("\u27E6","").replaceAll("\u27E7","")}c(x,"sourceText");function w(e,r){let{files:o,...t}=e,s=x(r);return{...t,storedFiles:o.map(({lines:l,...a})=>({...a,lines:l.map(n=>{let i=[n.lineNumber,p(n.text,s),n.ranges];return n.logicalMatchIds===void 0?i:[...i,n.logicalMatchIds]})}))}}c(w,"compactSearchDetails");function g(e,r){if("files"in e)return e;let{storedFiles:o,...t}=e,s=x(r);return{...t,files:o.map(({lines:l,...a})=>({...a,lines:l.map(([n,i,h,u])=>({lineNumber:n,text:y(i,s),ranges:h,matchCount:h.length,...u===void 0?{}:{logicalMatchIds:u}}))}))}}c(g,"restoreSearchDetails");var k=new WeakMap,z=12;function v(e,r,o,t){if(typeof e.details=="object"){let a=k.get(e.details);a===void 0&&(a=g(e.details,e.content.flatMap(n=>n.type==="text"?[n.text]:[]).join(`
2
2
  `)),k.set(e.details,a)),e={...e,details:a}}if(r.isPartial||t.isError||!R(e.details)){let a=e.content[0],n=a?.type==="text"?a.text:"",i=t.isError?"error":r.isPartial?"dim":"toolOutput";return new D(o.fg(i,n),0,0)}let l=(t.lastComponent instanceof f?t.lastComponent:void 0)??new f(e.details,o,r.expanded);return l.updateSearch(e.details,o,r.expanded),l}c(v,"renderSearchResult");var f=class extends S{static{c(this,"SearchResultPanel")}constructor(r,o,t){super(T(r,t),o,t)}updateSearch(r,o,t){super.update(T(r,t),o,t)}};function T(e,r){let o=$(e,r).map(t=>t.kind==="file"?{kind:"source",label:t.file.path,link:t.file.link,count:t.file.matchCount}:t.kind==="line"?{kind:"line",...t.line}:t.kind==="candidate"?{kind:"note",text:t.identifier}:t.kind==="summary"?{kind:"note",text:t.text}:t.kind==="omitted"?{kind:"note",text:`\u2026 ${t.matches} more ${d(t.matches,"match","matches")} \xB7 ${C("app.tools.expand")} to expand`}:{kind:"note",text:"No matches found"});return{summary:P(e),rows:o}}c(T,"searchModel");function $(e,r){let o=e.fuzzy?.status==="ready"&&e.fuzzy.candidates.length>0,t=e.files.length===0?o?[]:[{kind:"empty"}]:e.files.flatMap(n=>[{kind:"file",file:n},...n.uniqueLineCount===void 0?n.lines.map(i=>({kind:"line",file:n,line:i})):[{kind:"summary",text:`${String(n.uniqueLineCount)} unique line texts \xB7 search this path with a narrower query`},...(n.groups??[]).map(i=>({kind:"summary",text:`\xD7${String(i.matchCount)} ${i.text}`}))]]);if(e.fuzzy!==void 0&&(e.fuzzy.status==="skipped"?t.push({kind:"summary",text:"Fuzzy search unavailable"}):e.fuzzy.candidates.length>0&&t.push(...e.fuzzy.candidates.flatMap(n=>{let i=e.fuzzyPresentation?.groups.find(u=>u.identifier===n.identifier)?.files??[],h=i.reduce((u,m)=>u+m.matchCount,0);return[{kind:"candidate",identifier:n.identifier},...i.length===0?[]:[{kind:"summary",text:`Shown ${String(h)} of ${String(n.matchCount)}${n.selection.complete?"":"+"}`},...i.flatMap(u=>[{kind:"file",file:u},...u.lines.map(m=>({kind:"line",file:u,line:m}))])]]}))),e.fuzzy!==void 0||r||t.length<=z)return t;let s=t.slice(0,z-1);for(;s.at(-1)?.kind==="file";)s.pop();let l=new Set(s.flatMap(n=>n.kind==="line"?n.line.logicalMatchIds??[]:[])),a=l.size>0?l.size:s.reduce((n,i)=>n+(i.kind==="line"?i.line.matchCount:0),0);return[...s,{kind:"omitted",matches:Math.max(0,e.matchCount-a)}]}c($,"searchViewport");function P(e){if(e.matchCount===0&&e.fuzzy?.status==="ready"&&e.fuzzy.candidates.length>0&&e.fuzzyPresentation!==void 0){let o=e.fuzzy.candidates.reduce((l,a)=>l+a.matchCount,0),t=e.fuzzy.candidates.every(l=>l.selection.complete)?"":"+",s=e.fuzzyPresentation.fileCount;return`0 exact \xB7 ${String(o)}${t} fuzzy ${d(o,"match","matches")} \xB7 ${String(s)}${t} ${d(s,"file","files")}`}return e.matchCount===0?e.complete?"No matches":"No matches \xB7 incomplete":`${`${String(e.matchCount)}${e.complete?"":"+"}`} ${d(e.matchCount,"match","matches")} in ${String(e.fileCount)} ${d(e.fileCount,"file","files")}`}c(P,"searchSummary");function d(e,r,o){return e===1?r:o}c(d,"plural");export{w as a,v as b,f as c};
@@ -1,7 +1,7 @@
1
- import{a as de,b as me,c as pe}from"./chunk-ESPNEJHK.js";import{a as ce}from"./chunk-M5IVSCR2.js";import"./chunk-EAZGN5ND.js";import{a as I}from"./chunk-VCGNVTXQ.js";import{e as Z,f as J}from"./chunk-T7I2VX3J.js";import{a as ie}from"./chunk-YRF7OATP.js";import{a as ne,b as re}from"./chunk-FXNKMNSJ.js";import{b as E}from"./chunk-64M3SQPG.js";import{a as te}from"./chunk-6CZO43OH.js";import{a as Q,b as ee}from"./chunk-OBNING2A.js";import{a as le}from"./chunk-AJRIASPQ.js";import{e as ue}from"./chunk-FK42RSF4.js";import{a as ae}from"./chunk-ZTYWHL2F.js";import{a as oe,b as se}from"./chunk-7UGNGK7Y.js";import"./chunk-PS2B6THP.js";import{h as j,i as L}from"./chunk-SQKAXYIR.js";import"./chunk-ZPT5D4VP.js";import"./chunk-ZC65Z3CK.js";import{a as s}from"./chunk-EI7MMDWY.js";import et from"node:path";import{stripVTControlCharacters as tt}from"node:util";import{truncateLine as nt}from"@earendil-works/pi-coding-agent";import{Text as R}from"@earendil-works/pi-tui";import{DEFAULT_MAX_BYTES as fe,DEFAULT_MAX_LINES as ge,formatSize as Je,truncateTail as Qe}from"@earendil-works/pi-coding-agent";function $(t){return Qe(t,{maxBytes:fe-4096,maxLines:ge-32})}s($,"terminalOutputTail");function M(t){let e=$(t.output),n=[`session: ${t.source}`,`status: ${t.status}`,`shell: ${t.shell}`,`cwd: ${t.cwd}`,`elapsedMs: ${t.elapsedMs}`,t.exitCode===void 0?void 0:`exitCode: ${t.exitCode}`,t.signal===void 0?void 0:`signal: ${t.signal}`,t.error===void 0?void 0:`error: ${t.error}`,t.waitReason===void 0?void 0:`reason: ${t.waitReason}`,t.completionReason===void 0?void 0:`completionReason: ${t.completionReason}`,t.waitReason===void 0||t.status!=="running"?void 0:`next: Read ${t.source} to inspect it, then use write or insert to send input.`,`outputRange: ${t.outputStart}-${t.outputEnd}`,t.truncated?"retainedOutput: earlier data omitted from memory":void 0,e.truncated?`fullOutput: ${t.fullOutputPath}`:void 0].filter(o=>o!==void 0),r=e.content.trimEnd();if(!e.truncated)return`${n.join(`
1
+ import{a as de,b as me,c as fe}from"./chunk-ESPNEJHK.js";import{a as ce}from"./chunk-M5IVSCR2.js";import"./chunk-EAZGN5ND.js";import{a as I}from"./chunk-4XMY4H4V.js";import{e as Z,f as J}from"./chunk-T7I2VX3J.js";import{a as ie}from"./chunk-PKKDDIWW.js";import{a as ne,b as re}from"./chunk-4GCWGE2C.js";import{b as E}from"./chunk-64M3SQPG.js";import{a as te}from"./chunk-BU7IZLKB.js";import{a as Q,b as ee}from"./chunk-S5PL5DFQ.js";import{a as le}from"./chunk-YP46DVVP.js";import{e as ue}from"./chunk-GXEGY7GV.js";import{a as ae}from"./chunk-ZTYWHL2F.js";import{a as oe,b as se}from"./chunk-7UGNGK7Y.js";import"./chunk-PS2B6THP.js";import{h as j,i as L}from"./chunk-CWD4O5PM.js";import"./chunk-ZPT5D4VP.js";import"./chunk-ZC65Z3CK.js";import{a as s}from"./chunk-EI7MMDWY.js";import et from"node:path";import{stripVTControlCharacters as tt}from"node:util";import{truncateLine as nt}from"@earendil-works/pi-coding-agent";import{Text as R}from"@earendil-works/pi-tui";import{DEFAULT_MAX_BYTES as pe,DEFAULT_MAX_LINES as ge,formatSize as Je,truncateTail as Qe}from"@earendil-works/pi-coding-agent";function $(t){return Qe(t,{maxBytes:pe-4096,maxLines:ge-32})}s($,"terminalOutputTail");function M(t){let e=$(t.output),n=[`session: ${t.source}`,`status: ${t.status}`,`shell: ${t.shell}`,`cwd: ${t.cwd}`,`elapsedMs: ${t.elapsedMs}`,t.exitCode===void 0?void 0:`exitCode: ${t.exitCode}`,t.signal===void 0?void 0:`signal: ${t.signal}`,t.error===void 0?void 0:`error: ${t.error}`,t.waitReason===void 0?void 0:`reason: ${t.waitReason}`,t.completionReason===void 0?void 0:`completionReason: ${t.completionReason}`,t.waitReason===void 0||t.status!=="running"?void 0:`next: Read ${t.source} to inspect it, then use write or insert to send input.`,`outputRange: ${t.outputStart}-${t.outputEnd}`,t.truncated?"retainedOutput: earlier data omitted from memory":void 0,e.truncated?`fullOutput: ${t.fullOutputPath}`:void 0].filter(o=>o!==void 0),r=e.content.trimEnd();if(!e.truncated)return`${n.join(`
2
2
  `)}
3
3
  output:${r.length===0?" (empty)":`
4
- ${r}`}`;let i=e.truncatedBy==="lines"?`${ge} line output budget`:`${Je(fe)} output budget`,a=`[Earlier output omitted: showing the last ${e.outputLines} of ${e.totalLines} lines (${i}). Full output: ${t.fullOutputPath}]`;return`${n.join(`
4
+ ${r}`}`;let i=e.truncatedBy==="lines"?`${ge} line output budget`:`${Je(pe)} output budget`,a=`[Earlier output omitted: showing the last ${e.outputLines} of ${e.totalLines} lines (${i}). Full output: ${t.fullOutputPath}]`;return`${n.join(`
5
5
  `)}
6
6
  output:
7
7
  ${a}${r.length===0?"":`
@@ -15,14 +15,14 @@ ${i.fg("accent",H(r.family))} ${t}`,0,0)}s(he,"renderRunCall");function ye(t,e,n
15
15
  `),0,0)}s(Se,"renderRunResult");function Te(t,e){let n=s((o,c)=>e?.fg(o,c)??c,"color"),i=[`${n("accent",t.shell.toLocaleLowerCase())} ${n("muted",`\xB7 ${D(t.cwd)} \xB7 ${t.background?"background":"wait"}`)}`,`${n("accent",H(t.shellFamily))} ${B(t.command,84)}`],a=it(t.output,2);return a.length>0&&i.push(...a.map(o=>` ${n("dim",B(o,90))}`)),i.push(k(t,n)),i.join(`
16
16
  `)}s(Te,"renderActiveTerminal");function be(t,e,n){let r=(t.shell??"terminal").toLocaleLowerCase(),i=t.background===!0?"background":"wait",a=t.cwd===void 0?"workspace":D(t.cwd),o=t.shellFamily??"posix",c=[`${n.fg("accent",r)} ${n.fg("muted",`\xB7 ${a} \xB7 ${i}`)}`,`${n.fg("accent",H(o))} ${t.command??""}`],l=_(t.output??"",e);return l.omission!==void 0&&c.push(` ${n.fg("muted",l.omission)}`),l.lines.length>0&&c.push(...l.lines.map(u=>` ${n.fg("dim",u)}`)),c.push(k(t,(u,d)=>n.fg(u,d))),c}s(be,"terminalCardLines");function it(t,e){return _(t,e).lines}s(it,"outputTail");function _(t,e){let n=$(tt(t).replaceAll("\r","")),r=n.content.split(`
17
17
  `).map(l=>nt(l.trimEnd(),rt).text);r.at(-1)===""&&r.pop();let i=Number.isFinite(e)?Math.max(0,e):r.length,a=Math.max(0,r.length-i),o=Math.max(0,n.totalLines-n.outputLines),c=a+o;return{lines:r.slice(a),...n.truncated||c>0?{omission:c>0?`\u2026 ${c} earlier lines`:"\u2026 earlier output omitted"}:{}}}s(_,"outputWindow");function k(t,e){let n=t.status??"running",r=ot(n),i=n==="completed"?"success":n==="running"?"accent":"error",a=[`${r} ${n}`,at(t.elapsedMs??0)];return t.waitReason!==void 0&&a.push(`background \xB7 ${t.waitReason}`),t.completionReason!==void 0&&a.push(`reason ${t.completionReason}`),t.exitCode!==void 0?a.push(`exit ${t.exitCode}`):t.signal!==void 0&&a.push(`signal ${t.signal}`),e(i,a.join(" \xB7 "))}s(k,"statusLine");function ot(t){return t==="completed"?"\u2713":t==="running"?"\u25CF":t==="stopping"?"\u25CC":"\u2717"}s(ot,"statusIcon");function H(t){return t==="powershell"?"PS>":t==="cmd"?">":"$"}s(H,"promptMarker");function st(t,e){let n=(t.shell??"terminal").toLocaleLowerCase(),r=t.cwd===void 0?"workspace":D(t.cwd),i=t.background===!0?"background":"wait",a=B(t.command??"process",48);return`${e.fg("toolTitle",n)} ${e.fg("muted",`\xB7 ${r} \xB7 ${i} \xB7 ${a}`)}`}s(st,"terminalIdentity");function D(t){let e=process.env.HOME;return e!==void 0&&(t===e||t.startsWith(`${e}${et.sep}`))?`~${t.slice(e.length)}`:t}s(D,"shortCwd");function B(t,e){let n=t.replaceAll(/\s+/gu," ").trim();return n.length<=e?n:`${n.slice(0,e-1)}\u2026`}s(B,"oneLine");function at(t){return t<1e3?`${t}ms`:`${(t/1e3).toFixed(t<1e4?1:0)}s`}s(at,"formatElapsed");function Re(t){return{id:"terminal",onDidChange:s(e=>t.onDidChange(e),"onDidChange"),list:s(()=>t.list().filter(e=>e.status==="running"||e.status==="stopping").map(e=>({source:e.source,kind:"terminal",title:e.shell.toLocaleLowerCase(),description:e.command,status:e.status==="stopping"?"stopping":"running",...e.pid===void 0?{}:{pid:e.pid,owned:!0},renderSummary:s(n=>Te(e,n).split(`
18
- `),"renderSummary"),renderDetail:s(n=>x(e,!0,n),"renderDetail"),sendInput:s(n=>t.write(e.source,n),"sendInput"),stop:s(()=>t.delete(e.source),"stop")})),"list")}}s(Re,"terminalProcessProvider");import{setTimeout as mt}from"node:timers/promises";var lt="#d8dee9",G="#111418",ut=["#000000","#cd0000","#00cd00","#cdcd00","#0000ee","#cd00cd","#00cdcd","#e5e5e5","#7f7f7f","#ff0000","#00ff00","#ffff00","#5c5cff","#ff00ff","#00ffff","#ffffff"];async function q(t,e,n,r=1){let i=t.get(e);if(i===void 0)throw new Error(`Unknown terminal session ${e}`);await i.screenReady;let{createCanvas:a}=await import("@napi-rs/canvas"),o=Math.max(0,Math.min(i.rows-1,n?.start??0)),c=Math.max(1,Math.min(i.rows-o,n?.count??i.rows)),l=i.cols*9+24,u=c*18+24,d=a(Math.max(1,Math.round(l*r)),Math.max(1,Math.round(u*r))),m=d.getContext("2d");m.scale(r,r),m.fillStyle=G,m.fillRect(0,0,d.width,d.height),m.textBaseline="top";let p=i.screen.buffer.active,f=Math.max(0,p.baseY);for(let h=0;h<c;h+=1){let w=p.getLine(f+o+h);if(w!==void 0)for(let y=0;y<i.cols;y+=1){let P=w.getCell(y);P===void 0||P.getWidth()===0||ct(m,P,y,h)}}return i.status==="running"&&p.cursorY>=o&&p.cursorY<o+c&&(m.fillStyle="rgba(216, 222, 233, 0.75)",m.fillRect(12+p.cursorX*9,12+(p.cursorY-o)*18+18-2,9,2)),d.toBuffer("image/png").toString("base64")}s(q,"renderTerminalScreen");function ct(t,e,n,r){let i=xe(e,"foreground"),a=xe(e,"background");e.isInverse()&&([i,a]=[a,i]);let o=12+n*9,c=12+r*18;a!==G&&(t.fillStyle=a,t.fillRect(o,c,9*Math.max(1,e.getWidth()),18));let l=e.getChars();l.length!==0&&(t.font=`${e.isBold()?"bold ":""}14px monospace`,t.fillStyle=i,t.fillText(l,o,c),e.isUnderline()&&t.fillRect(o,c+18-2,9*Math.max(1,e.getWidth()),1))}s(ct,"drawCell");function xe(t,e){let n=e==="foreground";if(n?t.isFgDefault():t.isBgDefault())return n?lt:G;let i=n?t.isFgRGB():t.isBgRGB(),a=n?t.getFgColor():t.getBgColor();return i?`#${a.toString(16).padStart(6,"0")}`:dt(a)}s(xe,"cellColor");function dt(t){let e=ut[t];if(e!==void 0)return e;if(t>=232){let c=8+(t-232)*10;return ve(c,c,c)}let n=Math.max(0,t-16),r=Math.floor(n/36),i=Math.floor(n%36/6),a=n%6,o=s(c=>c===0?0:55+c*40,"channel");return ve(o(r),o(i),o(a))}s(dt,"ansiColor");function ve(t,e,n){return`#${[t,e,n].map(r=>r.toString(16).padStart(2,"0")).join("")}`}s(ve,"rgb");var Y="\0pi-terminal-write\0",X="\0pi-terminal-keys\0";function pt(t){let e=t?.find(l=>l==="image"||l==="sequence"||l.startsWith("image:")||l.startsWith("sequence:"));if(e===void 0)return;let n=e.indexOf(":"),r=n<0?e:e.slice(0,n),i=new Map;if(n>=0)for(let l of e.slice(n+1).split(",")){let[u,d,m]=l.split("=");if(u===void 0||d===void 0||m!==void 0||d.length===0)throw new Error(`Invalid terminal ${r} view parameter: ${l}`);if(u!=="duration"&&u!=="interval"&&u!=="scale")throw new Error(`Unsupported terminal ${r} view parameter: ${u}`);let p=Number(d);if(!Number.isFinite(p))throw new Error(`Terminal ${u} must be a number`);i.set(u,p)}let a=i.get("duration")??2,o=i.get("interval")??.5,c=i.get("scale")??1;if(!(c>0&&c<=1))throw new Error("Terminal image scale must be greater than 0 and at most 1");if(r==="sequence"){if(!(a>0&&a<=10))throw new Error("Terminal sequence duration must be greater than 0 and at most 10 seconds");if(!(o>0))throw new Error("Terminal sequence interval must be greater than 0 seconds");if(Math.floor(a/o)+1>20)throw new Error("Terminal sequence capture is limited to 20 frames")}return{mode:r,duration:a,interval:o,scale:c}}s(pt,"parseTerminalVisualView");async function $e(t,e){let n=new Map,r=new Map,i={protocol:Q,apiVersion:ee,id:"terminal",setup(o){o.addResolver({resolver:ft(e),preserveTruncatedOutput:!0,renderResult(c,l,u){let d=c.details,m=d.source===void 0?void 0:e.get(d.source),p=m===void 0?{}:e.snapshot(m);return x(m===void 0?p:{...p,output:e.screenTail(m).join(`
19
- `)},l.expanded,u,"read terminal")}}),o.addHandler({stage:"pre-read",async handler(c){let l=c.request.path;if(l===void 0||!T(l))return{kind:"continue",context:c};let u;try{u=pt(c.request.views)}catch(m){return{kind:"return",result:V(l,m instanceof Error?m.message:String(m))}}if(u===void 0)return{kind:"continue",context:c};let d=e.get(l);if(d===void 0)return{kind:"return",result:V(l,`Unknown terminal session ${l}`)};try{e.markInspected(l);let m=u.mode==="image"?1:Math.floor(u.duration/u.interval)+1,p=[];for(let f=0;f<m;f+=1){c.resolverContext.signal?.throwIfAborted(),f>0&&await mt(u.interval*1e3,void 0,{signal:c.resolverContext.signal});let h=await q(e,l,void 0,u.scale);p.push({type:"image",data:h,mimeType:"image/png"})}return{kind:"return",result:{content:p,script:{kind:"native",source:d.source,blocks:p},details:{source:d.source,resolvedBy:"terminal",frames:m,mode:u.mode}}}}catch(m){return{kind:"return",result:V(l,m instanceof Error?m.message:String(m))}}}}),o.describe("shell:<session> \u2014 terminal status and a bounded output tail with a full-log path when truncated. image and parameterized sequence views return the virtual terminal screen as ordered PNG frames.")}},a={protocol:ne,apiVersion:re,id:"terminal",setup(o){o.addResolver({resolver:gt(e)}),o.tool("write").addHandler({stage:"text-pre-edit",handler:s(async c=>(Ee(c.input,e,n),await Pe(c.input,e,r),ht(c,Y)),"handler")}),o.tool("insert").addHandler({stage:"text-pre-edit",handler:s(async c=>(await Pe(c.input,e,r),Ee(c.input,e,n),yt(c)),"handler")});for(let c of["write","insert","delete"])o.addToolRenderer({tool:c,matches:s((l,u)=>bt(l,u),"matches"),renderCall(l,u,d){let m=l,p=typeof m.path=="string"?e.get(m.path):void 0,f=d.state;return p!==void 0&&(f.snapshot=e.snapshot(p)),we(f.snapshot??{},c,Ae(c,m),[],u)},renderResult(l,u,d){let m=Tt(l.details);return ye(m.action,m.changedLines,d)}});o.describe("For shell:<session> resources, write sends exact terminal input, insert sends named keys at end, and delete terminates and removes the session. replace is unsupported."),o.tool("write").describe("When path is shell:<session>, send content exactly as terminal input without adding Enter."),o.tool("insert").describe("When path is shell:<session>, omit anchor or use end, keep before false, and put whitespace- or comma-separated named keys and chords such as Enter, Ctrl+C, Ctrl+Left, Ctrl+Shift+Left, Up, or Backspace in text. Use Unix caret forms such as ^C and ^U for control characters.")}};await Promise.all([te(t,i),ie(t,a)]),t.on("tool_result",async(o,c)=>{if(!b(o.input))return;let l=o.input.path;if(o.toolName==="replace"&&typeof l=="string"&&T(l)){let A=`replace is unsupported for ${l}; use write for text, insert for keys, or delete to terminate and remove the session.`;return L({content:[{type:"text",text:A}],details:o.details},I,{status:"error",errors:[j(A,"UNSUPPORTED_OPERATION",l)],data:{operation:"replace",effect:"not-applied",files:[{source:l,effect:"not-applied"}]}})}if(o.toolName==="delete"&&typeof l=="string"&&T(l)){let A=e.get(l);if(A===void 0)return;let Ze=e.snapshot(A);return e.delete(l).then(()=>L({content:[{type:"text",text:`Deleted terminal session ${l}.`}],details:{source:l,deleted:!0,snapshot:Ze,action:"delete",input:"session",changedLines:[]}},I,{status:"success",errors:[],data:{operation:"delete",effect:"applied",files:[{source:l,effect:"applied"}]}}),C=>L({content:[{type:"text",text:C instanceof Error?C.message:String(C)}],details:{source:l,deleted:!1}},I,{status:"error",errors:[j(C,"TERMINAL_DELETE_FAILED",l)],data:{operation:"delete",effect:"unknown",files:[{source:l,effect:"unknown"}]}}))}if(o.toolName!=="write"&&o.toolName!=="insert"||o.isError)return;let u=o.input.path;if(typeof u!="string"||!T(u))return;let d=e.get(u);if(d===void 0)return;let m=r.get(u)??e.screenRows(d);r.delete(u);let p=n.get(u)??d.outputStart+d.output.length;n.delete(u),await e.waitForOutputAfter(d,p);let f=e.snapshot(d),h=o.toolName,w=Ae(h,o.input),y=e.screenChangeRegion(d,m,6),P=[{type:"text",text:`Sent ${w} to ${d.source}.`}];return c.model?.input.includes("image")===!0&&P.push({type:"image",data:await q(e,u,{start:y.startRow,count:y.lines.length}),mimeType:"image/png"}),{content:P,details:{source:d.source,action:h,status:d.status,snapshot:f,input:w,changedLines:y.lines},isError:o.isError,...o.structuredContent===void 0?{}:{structuredContent:o.structuredContent}}})}s($e,"registerTerminalResources");function ft(t){return{id:"terminal",async tryResolve(e){if(!T(e))return{kind:"not-handled"};let n=t.get(e);return n===void 0?{kind:"failed",error:new Error(`Unknown terminal session ${e}`)}:{kind:"resolved",resource:{source:n.source,async read(){t.markInspected(n.source);let r=t.snapshot(n);return[{type:"text",text:wt(r)}]}}}}}}s(ft,"createReadResolver");function gt(t){return{id:"terminal-input",async tryResolve(e){if(!T(e))return{kind:"not-handled"};let n=t.get(e);return n===void 0?{kind:"failed",error:new Error(`Unknown terminal session ${e}`)}:{kind:"resolved",resource:{source:n.source,skipPostEdit:!0,async read(){return[{type:"text",text:"terminal input"}]},async write(r){let i=St(r),a=i.indexOf(Y),o=i.indexOf(X);if(a>=0){t.write(n.source,i.slice(a+Y.length));return}if(o>=0){t.sendKeys(n.source,i.slice(o+X.length).trim());return}throw new Error(`Unsupported text operation for ${n.source}`)}}}}}}s(gt,"createInputResolver");function ht(t,e){return!b(t.input)||!ke(t.input.path)?t:{...t,input:{...t.input,content:`${e}${typeof t.input.content=="string"?t.input.content:""}`}}}s(ht,"transformWriteInput");function yt(t){if(!b(t.input)||!ke(t.input.path))return t;if(t.input.before===!0)throw new Error("Shell keys can only be inserted after the active input position");return{...t,input:{...t.input,anchor:"end",before:!1,text:`${X}${typeof t.input.text=="string"?t.input.text:""}`}}}s(yt,"transformInsertInput");function wt(t){return M(t)}s(wt,"formatSnapshot");function St(t){if(t.length!==1||t[0].type!=="text")throw new Error("Terminal input must contain one text block");return t[0].text}s(St,"singleText");function V(t,e){return{content:[{type:"text",text:e}],details:{source:t,failure:{code:"READ_FAILED",source:t,resolverId:"terminal",message:e}},isError:!0}}s(V,"failure");function T(t){return/^shell:[a-f\d]{12}$/u.test(t)}s(T,"isShellSource");function ke(t){return typeof t=="string"&&T(t)}s(ke,"isShellSourceValue");function Tt(t){if(!b(t)||!b(t.snapshot))throw new TypeError("Invalid terminal action result");let e=t.snapshot,n=t.action;if(n!=="write"&&n!=="insert"&&n!=="delete")throw new TypeError("Invalid terminal action");return{source:typeof t.source=="string"?t.source:"shell:unknown",action:n,input:typeof t.input=="string"?t.input:"",changedLines:Array.isArray(t.changedLines)?t.changedLines.filter(r=>typeof r=="string"):[],snapshot:{...typeof e.shell=="string"?{shell:e.shell}:{},...typeof e.cwd=="string"?{cwd:e.cwd}:{},...typeof e.command=="string"?{command:e.command}:{},...typeof e.background=="boolean"?{background:e.background}:{},...typeof e.status=="string"?{status:e.status}:{}}}}s(Tt,"terminalActionDetails");async function Pe(t,e,n){if(!b(t)||typeof t.path!="string"||!T(t.path))return;let r=e.get(t.path);r!==void 0&&await r.screenReady,r!==void 0&&n.set(t.path,e.screenRows(r))}s(Pe,"rememberScreen");function Ee(t,e,n){if(!b(t)||typeof t.path!="string"||!T(t.path))return;let r=e.get(t.path);r!==void 0&&n.set(t.path,r.outputStart+r.output.length)}s(Ee,"rememberOutputEnd");function Ae(t,e){if(t==="delete")return"session";let n=t==="write"?e.content:e.text,r=typeof n=="string"?n:"";return t==="write"?`text ${JSON.stringify(r)}`:`keys ${r}`}s(Ae,"terminalInputLabel");function bt(t,e){if(!b(t))return!1;if(e==="call")return typeof t.path=="string"&&T(t.path);let n=t.details;return b(n)&&typeof n.source=="string"&&T(n.source)}s(bt,"isTerminalRenderValue");function b(t){return typeof t=="object"&&t!==null}s(b,"isRecord");async function Ce(t,e){await ae(t,{protocol:oe,apiVersion:se,id:"terminal",setup(r){r.addResolver({resolver:Rt(e),priority:100}),r.describe("path shell:<session> searches the retained text output of that terminal, including rows outside its current screen.")}})}s(Ce,"registerTerminalSearch");function Rt(t){return{readResources:s(e=>e.path?.startsWith("shell:")?[e.path]:[],"readResources"),id:"terminal",toScriptData(e){let n=O(e);return ue(n.matches,!1)},async tryResolve(e){if(e.path===void 0||!e.path.startsWith("shell:"))return{kind:"not-handled"};let n=t.get(e.path);if(n===void 0)return{kind:"failed",error:new Error(`Unknown terminal session ${e.path}`)};let r=t.snapshot(n),i=xt(r,e);return{kind:"resolved",payload:{snapshot:r,query:e.query,matches:i}}},format(e){let n=O(e),r=n.matches.map(i=>`${n.snapshot.source}:${i.lineNumber}: ${i.lineText}`);return{content:[{type:"text",text:r.length===0?`No matches in ${n.snapshot.source}`:`${r.join(`
18
+ `),"renderSummary"),renderDetail:s(n=>x(e,!0,n),"renderDetail"),sendInput:s(n=>t.write(e.source,n),"sendInput"),stop:s(()=>t.delete(e.source),"stop")})),"list")}}s(Re,"terminalProcessProvider");import{setTimeout as mt}from"node:timers/promises";var lt="#d8dee9",G="#111418",ut=["#000000","#cd0000","#00cd00","#cdcd00","#0000ee","#cd00cd","#00cdcd","#e5e5e5","#7f7f7f","#ff0000","#00ff00","#ffff00","#5c5cff","#ff00ff","#00ffff","#ffffff"];async function q(t,e,n,r=1){let i=t.get(e);if(i===void 0)throw new Error(`Unknown terminal session ${e}`);await i.screenReady;let{createCanvas:a}=await import("@napi-rs/canvas"),o=Math.max(0,Math.min(i.rows-1,n?.start??0)),c=Math.max(1,Math.min(i.rows-o,n?.count??i.rows)),l=i.cols*9+24,u=c*18+24,d=a(Math.max(1,Math.round(l*r)),Math.max(1,Math.round(u*r))),m=d.getContext("2d");m.scale(r,r),m.fillStyle=G,m.fillRect(0,0,d.width,d.height),m.textBaseline="top";let f=i.screen.buffer.active,p=Math.max(0,f.baseY);for(let h=0;h<c;h+=1){let w=f.getLine(p+o+h);if(w!==void 0)for(let y=0;y<i.cols;y+=1){let P=w.getCell(y);P===void 0||P.getWidth()===0||ct(m,P,y,h)}}return i.status==="running"&&f.cursorY>=o&&f.cursorY<o+c&&(m.fillStyle="rgba(216, 222, 233, 0.75)",m.fillRect(12+f.cursorX*9,12+(f.cursorY-o)*18+18-2,9,2)),d.toBuffer("image/png").toString("base64")}s(q,"renderTerminalScreen");function ct(t,e,n,r){let i=xe(e,"foreground"),a=xe(e,"background");e.isInverse()&&([i,a]=[a,i]);let o=12+n*9,c=12+r*18;a!==G&&(t.fillStyle=a,t.fillRect(o,c,9*Math.max(1,e.getWidth()),18));let l=e.getChars();l.length!==0&&(t.font=`${e.isBold()?"bold ":""}14px monospace`,t.fillStyle=i,t.fillText(l,o,c),e.isUnderline()&&t.fillRect(o,c+18-2,9*Math.max(1,e.getWidth()),1))}s(ct,"drawCell");function xe(t,e){let n=e==="foreground";if(n?t.isFgDefault():t.isBgDefault())return n?lt:G;let i=n?t.isFgRGB():t.isBgRGB(),a=n?t.getFgColor():t.getBgColor();return i?`#${a.toString(16).padStart(6,"0")}`:dt(a)}s(xe,"cellColor");function dt(t){let e=ut[t];if(e!==void 0)return e;if(t>=232){let c=8+(t-232)*10;return ve(c,c,c)}let n=Math.max(0,t-16),r=Math.floor(n/36),i=Math.floor(n%36/6),a=n%6,o=s(c=>c===0?0:55+c*40,"channel");return ve(o(r),o(i),o(a))}s(dt,"ansiColor");function ve(t,e,n){return`#${[t,e,n].map(r=>r.toString(16).padStart(2,"0")).join("")}`}s(ve,"rgb");var Y="\0pi-terminal-write\0",X="\0pi-terminal-keys\0";function ft(t){let e=t?.find(l=>l==="image"||l==="sequence"||l.startsWith("image:")||l.startsWith("sequence:"));if(e===void 0)return;let n=e.indexOf(":"),r=n<0?e:e.slice(0,n),i=new Map;if(n>=0)for(let l of e.slice(n+1).split(",")){let[u,d,m]=l.split("=");if(u===void 0||d===void 0||m!==void 0||d.length===0)throw new Error(`Invalid terminal ${r} view parameter: ${l}`);if(u!=="duration"&&u!=="interval"&&u!=="scale")throw new Error(`Unsupported terminal ${r} view parameter: ${u}`);let f=Number(d);if(!Number.isFinite(f))throw new Error(`Terminal ${u} must be a number`);i.set(u,f)}let a=i.get("duration")??2,o=i.get("interval")??.5,c=i.get("scale")??1;if(!(c>0&&c<=1))throw new Error("Terminal image scale must be greater than 0 and at most 1");if(r==="sequence"){if(!(a>0&&a<=10))throw new Error("Terminal sequence duration must be greater than 0 and at most 10 seconds");if(!(o>0))throw new Error("Terminal sequence interval must be greater than 0 seconds");if(Math.floor(a/o)+1>20)throw new Error("Terminal sequence capture is limited to 20 frames")}return{mode:r,duration:a,interval:o,scale:c}}s(ft,"parseTerminalVisualView");async function $e(t,e){let n=new Map,r=new Map,i={protocol:Q,apiVersion:ee,id:"terminal",setup(o){o.addResolver({resolver:pt(e),preserveTruncatedOutput:!0,renderResult(c,l,u){let d=c.details,m=d.source===void 0?void 0:e.get(d.source),f=m===void 0?{}:e.snapshot(m);return x(m===void 0?f:{...f,output:e.screenTail(m).join(`
19
+ `)},l.expanded,u,"read terminal")}}),o.addHandler({stage:"pre-read",async handler(c){let l=c.request.path;if(l===void 0||!T(l))return{kind:"continue",context:c};let u;try{u=ft(c.request.views)}catch(m){return{kind:"return",result:V(l,m instanceof Error?m.message:String(m))}}if(u===void 0)return{kind:"continue",context:c};let d=e.get(l);if(d===void 0)return{kind:"return",result:V(l,`Unknown terminal session ${l}`)};try{e.markInspected(l);let m=u.mode==="image"?1:Math.floor(u.duration/u.interval)+1,f=[];for(let p=0;p<m;p+=1){c.resolverContext.signal?.throwIfAborted(),p>0&&await mt(u.interval*1e3,void 0,{signal:c.resolverContext.signal});let h=await q(e,l,void 0,u.scale);f.push({type:"image",data:h,mimeType:"image/png"})}return{kind:"return",result:{content:f,script:{kind:"native",source:d.source,blocks:f},details:{source:d.source,resolvedBy:"terminal",frames:m,mode:u.mode}}}}catch(m){return{kind:"return",result:V(l,m instanceof Error?m.message:String(m))}}}}),o.describe({path:"shell:<session> \u2014 terminal status and a bounded output tail with a full-log path when truncated.",views:"On shell:<session>, image[:scale=S] returns the virtual terminal screen; sequence[:duration=D,interval=I,scale=S] returns ordered PNG frames. Defaults: D=2 seconds, I=0.5 seconds, S=1. Scale satisfies 0 < S <= 1; sequences require 0 < D <= 10, I > 0, and at most 20 frames (floor(D/I)+1). Terminal captures do not support region or image grid selection; offset/limit do not crop their frames."})}},a={protocol:ne,apiVersion:re,id:"terminal",setup(o){o.addResolver({resolver:gt(e)}),o.tool("write").addHandler({stage:"text-pre-edit",handler:s(async c=>(Ee(c.input,e,n),await Pe(c.input,e,r),ht(c,Y)),"handler")}),o.tool("insert").addHandler({stage:"text-pre-edit",handler:s(async c=>(await Pe(c.input,e,r),Ee(c.input,e,n),yt(c)),"handler")});for(let c of["write","insert","delete"])o.addToolRenderer({tool:c,matches:s((l,u)=>bt(l,u),"matches"),renderCall(l,u,d){let m=l,f=typeof m.path=="string"?e.get(m.path):void 0,p=d.state;return f!==void 0&&(p.snapshot=e.snapshot(f)),we(p.snapshot??{},c,Ae(c,m),[],u)},renderResult(l,u,d){let m=Tt(l.details);return ye(m.action,m.changedLines,d)}});o.describe("For shell:<session> resources, write sends exact terminal input, insert sends named keys at end, and delete terminates and removes the session. replace is unsupported."),o.tool("write").describe("When path is shell:<session>, send content exactly as terminal input without adding Enter."),o.tool("insert").describe("When path is shell:<session>, omit anchor or use end, keep before false, and put whitespace- or comma-separated named keys and chords such as Enter, Ctrl+C, Ctrl+Left, Ctrl+Shift+Left, Up, or Backspace in text. Use Unix caret forms such as ^C and ^U for control characters.")}};await Promise.all([te(t,i),ie(t,a)]),t.on("tool_result",async(o,c)=>{if(!b(o.input))return;let l=o.input.path;if(o.toolName==="replace"&&typeof l=="string"&&T(l)){let A=`replace is unsupported for ${l}; use write for text, insert for keys, or delete to terminate and remove the session.`;return L({content:[{type:"text",text:A}],details:o.details},I(o.toolName),{status:"error",errors:[j(A,"UNSUPPORTED_OPERATION",l)],data:{operation:"replace",effect:"not-applied",files:[{source:l,effect:"not-applied"}]}})}if(o.toolName==="delete"&&typeof l=="string"&&T(l)){let A=e.get(l);if(A===void 0)return;let Ze=e.snapshot(A);return e.delete(l).then(()=>L({content:[{type:"text",text:`Deleted terminal session ${l}.`}],details:{source:l,deleted:!0,snapshot:Ze,action:"delete",input:"session",changedLines:[]}},I(o.toolName),{status:"success",errors:[],data:{operation:"delete",effect:"applied",files:[{source:l,effect:"applied"}]}}),C=>L({content:[{type:"text",text:C instanceof Error?C.message:String(C)}],details:{source:l,deleted:!1}},I(o.toolName),{status:"error",errors:[j(C,"TERMINAL_DELETE_FAILED",l)],data:{operation:"delete",effect:"unknown",files:[{source:l,effect:"unknown"}]}}))}if(o.toolName!=="write"&&o.toolName!=="insert"||o.isError)return;let u=o.input.path;if(typeof u!="string"||!T(u))return;let d=e.get(u);if(d===void 0)return;let m=r.get(u)??e.screenRows(d);r.delete(u);let f=n.get(u)??d.outputStart+d.output.length;n.delete(u),await e.waitForOutputAfter(d,f);let p=e.snapshot(d),h=o.toolName,w=Ae(h,o.input),y=e.screenChangeRegion(d,m,6),P=[{type:"text",text:`Sent ${w} to ${d.source}.`}];return c.model?.input.includes("image")===!0&&P.push({type:"image",data:await q(e,u,{start:y.startRow,count:y.lines.length}),mimeType:"image/png"}),{content:P,details:{source:d.source,action:h,status:d.status,snapshot:p,input:w,changedLines:y.lines},isError:o.isError,...o.structuredContent===void 0?{}:{structuredContent:o.structuredContent}}})}s($e,"registerTerminalResources");function pt(t){return{id:"terminal",async tryResolve(e){if(!T(e))return{kind:"not-handled"};let n=t.get(e);return n===void 0?{kind:"failed",error:new Error(`Unknown terminal session ${e}`)}:{kind:"resolved",resource:{source:n.source,async read(){t.markInspected(n.source);let r=t.snapshot(n);return[{type:"text",text:wt(r)}]}}}}}}s(pt,"createReadResolver");function gt(t){return{id:"terminal-input",async tryResolve(e){if(!T(e))return{kind:"not-handled"};let n=t.get(e);return n===void 0?{kind:"failed",error:new Error(`Unknown terminal session ${e}`)}:{kind:"resolved",resource:{source:n.source,skipPostEdit:!0,async read(){return[{type:"text",text:"terminal input"}]},async write(r){let i=St(r),a=i.indexOf(Y),o=i.indexOf(X);if(a>=0){t.write(n.source,i.slice(a+Y.length));return}if(o>=0){t.sendKeys(n.source,i.slice(o+X.length).trim());return}throw new Error(`Unsupported text operation for ${n.source}`)}}}}}}s(gt,"createInputResolver");function ht(t,e){return!b(t.input)||!ke(t.input.path)?t:{...t,input:{...t.input,content:`${e}${typeof t.input.content=="string"?t.input.content:""}`}}}s(ht,"transformWriteInput");function yt(t){if(!b(t.input)||!ke(t.input.path))return t;if(t.input.before===!0)throw new Error("Shell keys can only be inserted after the active input position");return{...t,input:{...t.input,anchor:"end",before:!1,text:`${X}${typeof t.input.text=="string"?t.input.text:""}`}}}s(yt,"transformInsertInput");function wt(t){return M(t)}s(wt,"formatSnapshot");function St(t){if(t.length!==1||t[0].type!=="text")throw new Error("Terminal input must contain one text block");return t[0].text}s(St,"singleText");function V(t,e){return{content:[{type:"text",text:e}],details:{source:t,failure:{code:"READ_FAILED",source:t,resolverId:"terminal",message:e}},isError:!0}}s(V,"failure");function T(t){return/^shell:[a-f\d]{12}$/u.test(t)}s(T,"isShellSource");function ke(t){return typeof t=="string"&&T(t)}s(ke,"isShellSourceValue");function Tt(t){if(!b(t)||!b(t.snapshot))throw new TypeError("Invalid terminal action result");let e=t.snapshot,n=t.action;if(n!=="write"&&n!=="insert"&&n!=="delete")throw new TypeError("Invalid terminal action");return{source:typeof t.source=="string"?t.source:"shell:unknown",action:n,input:typeof t.input=="string"?t.input:"",changedLines:Array.isArray(t.changedLines)?t.changedLines.filter(r=>typeof r=="string"):[],snapshot:{...typeof e.shell=="string"?{shell:e.shell}:{},...typeof e.cwd=="string"?{cwd:e.cwd}:{},...typeof e.command=="string"?{command:e.command}:{},...typeof e.background=="boolean"?{background:e.background}:{},...typeof e.status=="string"?{status:e.status}:{}}}}s(Tt,"terminalActionDetails");async function Pe(t,e,n){if(!b(t)||typeof t.path!="string"||!T(t.path))return;let r=e.get(t.path);r!==void 0&&await r.screenReady,r!==void 0&&n.set(t.path,e.screenRows(r))}s(Pe,"rememberScreen");function Ee(t,e,n){if(!b(t)||typeof t.path!="string"||!T(t.path))return;let r=e.get(t.path);r!==void 0&&n.set(t.path,r.outputStart+r.output.length)}s(Ee,"rememberOutputEnd");function Ae(t,e){if(t==="delete")return"session";let n=t==="write"?e.content:e.text,r=typeof n=="string"?n:"";return t==="write"?`text ${JSON.stringify(r)}`:`keys ${r}`}s(Ae,"terminalInputLabel");function bt(t,e){if(!b(t))return!1;if(e==="call")return typeof t.path=="string"&&T(t.path);let n=t.details;return b(n)&&typeof n.source=="string"&&T(n.source)}s(bt,"isTerminalRenderValue");function b(t){return typeof t=="object"&&t!==null}s(b,"isRecord");async function Ce(t,e){await ae(t,{protocol:oe,apiVersion:se,id:"terminal",setup(r){r.addResolver({resolver:Rt(e),priority:100}),r.describe("path shell:<session> searches the retained text output of that terminal, including rows outside its current screen.")}})}s(Ce,"registerTerminalSearch");function Rt(t){return{readResources:s(e=>e.path?.startsWith("shell:")?[e.path]:[],"readResources"),id:"terminal",toScriptData(e){let n=O(e);return ue(n.matches,!1)},async tryResolve(e){if(e.path===void 0||!e.path.startsWith("shell:"))return{kind:"not-handled"};let n=t.get(e.path);if(n===void 0)return{kind:"failed",error:new Error(`Unknown terminal session ${e.path}`)};let r=t.snapshot(n),i=xt(r,e);return{kind:"resolved",payload:{snapshot:r,query:e.query,matches:i}}},format(e){let n=O(e),r=n.matches.map(i=>`${n.snapshot.source}:${i.lineNumber}: ${i.lineText}`);return{content:[{type:"text",text:r.length===0?`No matches in ${n.snapshot.source}`:`${r.join(`
20
20
  `)}
21
21
 
22
22
  ${r.length} match${r.length===1?"":"es"} in ${n.snapshot.source}`}],details:{source:n.snapshot.source,payload:n}}},renderResult(e,n,r){let i=e.details,a=K(i)?O(i.payload):O(void 0);return le(a.matches,!1,r,n.expanded===!0,void 0,[`Retained terminal output \xB7 ${a.snapshot.status} \xB7 read-only`])}}}s(Rt,"terminalSearchResolver");function xt(t,e){let n=e.caseSensitive===!0?e.query:e.query.toLocaleLowerCase();if(n.length===0)return[];let r=[],i=e.limit??100;for(let[a,o]of t.output.replaceAll("\r","").split(`
23
- `).entries()){let c=e.caseSensitive===!0?o:o.toLocaleLowerCase(),l=0;for(;r.length<i;){let u=c.indexOf(n,l);if(u<0)break;let d=u+n.length;(e.wholeWord!==!0||vt(c,u,d))&&r.push({source:t.source,lineNumber:a+1,startColumn:u,endColumn:d,matchedText:o.slice(u,d),lineText:o}),l=Math.max(d,u+1)}if(r.length>=i)break}return r}s(xt,"findTerminalMatches");function vt(t,e,n){return!/[\p{L}\p{N}_]/u.test(t[e-1]??"")&&!/[\p{L}\p{N}_]/u.test(t[n]??"")}s(vt,"isWordBoundary");function O(t){if(!Pt(t))throw new TypeError("Invalid terminal search result");return t}s(O,"parsePayload");function Pt(t){return K(t)&&typeof t.query=="string"&&Array.isArray(t.matches)&&K(t.snapshot)&&typeof t.snapshot.source=="string"}s(Pt,"isTerminalSearchPayload");function K(t){return typeof t=="object"&&t!==null}s(K,"isRecord");import{spawn as Et}from"node:child_process";import{closeSync as At,mkdirSync as $t,openSync as kt,rmSync as Ct,writeSync as Lt}from"node:fs";import It from"node:os";import Le from"node:path";import{createRequire as Mt}from"node:module";import{randomUUID as _t}from"node:crypto";import{stripVTControlCharacters as Dt}from"node:util";var _e=Mt(new URL("../src/plugins/pi-agent-ide-terminal/src/session-manager.ts",import.meta.url).href),Ie=1e6,Ot=100,Nt=30,Ut=2e3,N=class{static{s(this,"TerminalSessionManager")}#a;#e=new Map;#t=new Set;#r=new Set;#i=new Map;#o=!1;constructor(e=jt){this.#a=e}onDidChange(e){return this.#t.add(e),()=>this.#t.delete(e)}onDidComplete(e){return this.#r.add(e),()=>this.#r.delete(e)}list(){return[...this.#e.values()].sort((e,n)=>n.startedAt-e.startedAt).map(e=>this.snapshot(e))}get(e){return this.#e.get(Bt(e))}snapshot(e,n=Date.now()){return{id:e.id,source:e.source,command:e.command,cwd:e.cwd,shell:e.shell.displayName,shellFamily:e.shell.family,...e.process===void 0?{}:{pid:e.process.pid},background:e.background,status:e.status,...e.waitReason===void 0?{}:{waitReason:e.waitReason},...e.completionReason===void 0?{}:{completionReason:e.completionReason},lastActivityAt:e.lastActivityAt,idleMs:Math.max(0,n-e.lastActivityAt),startedAt:e.startedAt,...e.endedAt===void 0?{}:{endedAt:e.endedAt},elapsedMs:(e.endedAt??n)-e.startedAt,...e.exitCode===void 0?{}:{exitCode:e.exitCode},...e.signal===void 0?{}:{signal:e.signal},...e.error===void 0?{}:{error:e.error},output:e.output,outputStart:e.outputStart,outputEnd:e.outputStart+e.output.length,truncated:e.outputStart>0,fullOutputPath:e.fullOutputPath,cols:e.cols,rows:e.rows}}start(e){if(this.#o)throw new Error("Terminal session manager is closed");let n=this.#a();if(!/^[a-f\d]{12}$/u.test(n)||this.#e.has(n))throw new Error("Terminal session IDs must be unique 12-character hexadecimal values");let r=Xt(n);this.#i.set(n,kt(r,"a",384));let i=e.cols??Ot,a=e.rows??Nt,o=Ft(i,a),c=s(p=>{},"resolveCompletion"),l=new Promise(p=>{c=p}),u={id:n,source:`shell:${n}`,command:e.command,background:e.background,cwd:e.cwd,shell:e.shell,startedAt:Date.now(),lastActivityAt:Date.now(),cols:i,rows:a,fullOutputPath:r,screen:o,status:"running",output:"",outputStart:0,screenReady:Promise.resolve(),completion:l,resolveCompletion:c,completionDelivered:!1,staleReminderDelivered:!1},d;try{let p=_e("node-pty"),f={name:"xterm-256color",cols:i,rows:a,cwd:e.cwd,env:Gt(Ht())};d=p.spawn(e.shell.executable,[...e.shell.commandArgs(e.command)],f)}catch(p){let f={...u,status:"failed",endedAt:Date.now(),error:Yt(p)};return this.#e.set(n,f),this.#s(n),c(f),queueMicrotask(()=>this.#l(f)),f}let m={...u,process:d};return this.#e.set(n,m),d.onData(p=>this.#u(m,p)),d.onExit(({exitCode:p,signal:f})=>{v(m.status)||(m.endedAt=Date.now(),m.exitCode=p,f!==0&&(m.signal=f),m.status=m.status==="stopping"?"stopped":p===0?"completed":"failed",(p===124||p===137)&&(m.completionReason="timeout"),this.#s(m.id),m.resolveCompletion(m),this.#n(m),this.#l(m))}),this.#n(m),m}async wait(e,n){let r=this.required(e);return v(r.status)?r:n?.aborted===!0?(await this.stop(r.source,"cancelled"),r):await new Promise((i,a)=>{let o=s(()=>{this.stop(r.source,"cancelled").then(i,a)},"onAbort");n?.addEventListener("abort",o,{once:!0}),r.completion.then(c=>{n?.removeEventListener("abort",o),i(c)},a)})}async waitForForeground(e,n){let r=this.required(e);if(v(r.status))return{session:r};let i=n.interactiveDelayMs??3e3;return await new Promise(a=>{let o=!1,c,l=s(p=>{o||(p!==void 0&&v(r.status)&&(p=void 0),o=!0,clearTimeout(d),clearInterval(m),n.signal?.removeEventListener("abort",u),p!==void 0&&(r.background=!0,p!=="aborted"&&(r.waitReason=p),this.#n(r)),a({session:r,...p===void 0?{}:{reason:p}}))},"finish"),u=s(()=>l("aborted"),"onAbort"),d=setTimeout(()=>l("timeout"),n.timeoutMs),m=setInterval(()=>{if(!Wt(r)){c=void 0;return}c??=Date.now(),Date.now()-c>=i&&l("interactive")},Math.min(100,Math.max(10,i/2)));n.signal?.addEventListener("abort",u,{once:!0}),n.signal?.aborted===!0&&u(),r.completion.then(()=>l())})}async waitForOutputAfter(e,n){let r=Date.now()+300,i=n,a;for(;Date.now()<r;){let o=e.outputStart+e.output.length;if(o!==i)i=o,a=Date.now(),await e.screenReady;else if(a!==void 0&&Date.now()-a>=40)return;await z(10)}await e.screenReady}screenRows(e){let n=e.screen.buffer.active;return Array.from({length:e.rows},(r,i)=>(n.getLine(n.baseY+i)?.translateToString(!0)??"").trimEnd())}screenChangeRegion(e,n,r=6){let i=this.screenRows(e),a=Math.max(1,Math.min(e.rows,r)),o=Math.max(0,e.screen.buffer.active.cursorY-Math.floor(a/2)),c=-1;for(let d=0;d<=e.rows-a;d+=1){let m=0;for(let p=d;p<d+a;p+=1){let f=n[p]??"",h=i[p]??"",w=h.length>0&&!n.includes(h),y=f.length>0&&h.length===0;f!==h&&(w||y)&&(m+=1)}m>c&&(c=m,o=d)}let l=e.screen.buffer.active;return{lines:i.slice(o,o+a).map((d,m)=>{if(o+m!==l.cursorY)return d;let f=d.padEnd(l.cursorX," ");return`${f.slice(0,l.cursorX)}\u258C${f.slice(l.cursorX)}`}),startRow:o}}screenChangeWindow(e,n,r=6){return this.screenChangeRegion(e,n,r).lines}screenTail(e,n=e.rows){let r=e.screen.buffer.active,i=Math.max(0,r.baseY),a=[];for(let o=0;o<e.rows;o+=1){let c=r.getLine(i+o)?.translateToString(!0).trimEnd();c!==void 0&&c.length>0&&a.push(c)}return a.slice(-Math.max(0,n))}markInspected(e){let n=this.required(e);n.status==="running"&&(n.lastActivityAt=Date.now(),this.#n(n))}write(e,n){this.requiredRunning(e).process?.write(n)}sendKeys(e,n){this.requiredRunning(e).process?.write(qt(n))}async stop(e,n="stopped"){let r=this.required(e);return v(r.status)||(r.status="stopping",this.#n(r),await Me(r,!1),await Promise.race([r.completion.then(()=>!0),z(Ut).then(()=>!1)])||(await Me(r,!0),await Promise.race([r.completion,z(1e3)])),v(r.status)||(r.status=n,r.endedAt=Date.now(),this.#s(r.id),r.resolveCompletion(r),this.#l(r)),n==="cancelled"&&(r.status="cancelled"),this.#n(r)),r}async delete(e){let n=this.required(e);n.completionDelivered=!0,await this.stop(n.source),n.screen.dispose(),this.#s(n.id),Ct(n.fullOutputPath,{force:!0}),this.#e.delete(n.id),this.#n(n)}async screenLines(e){let n=this.required(e);await n.screenReady;let r=n.screen.buffer.active,i=[],a=Math.max(0,r.baseY);for(let o=a;o<a+n.rows;o+=1)i.push(r.getLine(o)?.translateToString(!0)??"");return i}cursor(e){let n=this.required(e);return{x:n.screen.buffer.active.cursorX,y:n.screen.buffer.active.cursorY}}async dispose(){if(!this.#o){this.#o=!0,await Promise.all([...this.#e.values()].filter(e=>!v(e.status)).map(e=>this.stop(e.source)));for(let e of this.#e.values())e.screen.dispose(),this.#s(e.id);this.#t.clear(),this.#r.clear()}}required(e){let n=this.get(e);if(n===void 0)throw new Error(`Unknown terminal session ${e}`);return n}requiredRunning(e){let n=this.required(e);if(n.status!=="running")throw new Error(`Terminal session ${n.source} is ${n.status}; input is unavailable`);return n}#u(e,n){e.lastActivityAt=Date.now();let r=Dt(n),i=this.#i.get(e.id);if(i!==void 0&&Lt(i,r),e.output+=r,e.output.length>Ie){let a=e.output.length-Ie;e.output=e.output.slice(a),e.outputStart+=a}e.screenReady=e.screenReady.then(()=>new Promise(a=>{e.screen.write(n,a)})),this.#n(e)}#s(e){let n=this.#i.get(e);n!==void 0&&(At(n),this.#i.delete(e))}#n(e){for(let n of this.#t)n(e)}#l(e){for(let n of this.#r)n(e)}};function Wt(t){if(t.status!=="running")return!1;let e=t.screen.buffer.active,n=e.getLine(e.baseY+e.cursorY)?.translateToString(!0).trimEnd()??"";return/\[[^\]\n]{1,20}(?:\/[^\]\n]{1,20})+\]\s*[:?>]?\s*$/iu.test(n)||/(?:choose|select|enter|password|confirm|continue|proceed)[^\n]{0,60}[:?]\s*$/iu.test(n)||/^(?:❯|›)\s+\S/u.test(n)}s(Wt,"looksInteractive");function Ft(t,e){let{Terminal:n}=_e("@xterm/headless");return new n({cols:t,rows:e,scrollback:2e3,allowProposedApi:!0})}s(Ft,"createScreen");function jt(){return _t().replaceAll("-","").slice(0,12)}s(jt,"defaultSessionId");function Bt(t){return t.startsWith("shell:")?t.slice(6):t}s(Bt,"normalizeSessionId");function v(t){return t!=="running"&&t!=="stopping"}s(v,"isTerminalStatus");function Ht(){return process.env}s(Ht,"processEnvironment");function Gt(t){return{...Object.fromEntries(Object.entries(t).filter(e=>e[1]!==void 0)),PAGER:"cat",GIT_PAGER:"cat",SYSTEMD_PAGER:"cat",GH_PAGER:"cat"}}s(Gt,"cleanEnvironment");function qt(t){return t.split(/[\s,]+/u).filter(Boolean).map(Vt).join("")}s(qt,"encodeTerminalKeys");function Vt(t){if(/^\^[?@A-Z[\\\]^_]$/iu.test(t)){let d=t.slice(1).toUpperCase();return d==="?"?"\x7F":String.fromCharCode(d.charCodeAt(0)&31)}let e=t.toLowerCase().split("+"),n=e.pop()??"",r=new Set(e);if([...r].some(d=>!["ctrl","control","alt","meta","shift"].includes(d)))throw new Error(`Unsupported terminal key ${t}`);let i=r.has("ctrl")||r.has("control"),a=r.has("alt")||r.has("meta"),o=r.has("shift");if(i&&n.length===1&&/[a-z@[\\\]^_?]/u.test(n)){let d=n.toUpperCase(),m=d==="?"?"\x7F":String.fromCharCode(d.charCodeAt(0)&31);return a?`\x1B${m}`:m}let c={enter:"\r",tab:" ",escape:"\x1B",esc:"\x1B",backspace:"\x7F",home:"\x1B[H",end:"\x1B[F",delete:"\x1B[3~"};if(!i&&!a&&!o&&c[n]!==void 0)return c[n];if(a&&!i&&!o&&c[n]!==void 0)return`\x1B${c[n]}`;let u={up:"A",down:"B",right:"C",left:"D",home:"H",end:"F"}[n];if(u!==void 0)return!i&&!a&&!o?`\x1B[${u}`:`\x1B[1;${1+(o?1:0)+(a?2:0)+(i?4:0)}${u}`;if(a&&!i&&n.length===1)return`\x1B${o?n.toUpperCase():n}`;throw new Error(`Unsupported terminal key ${t}`)}s(Vt,"encodeTerminalKey");async function Me(t,e){let n=t.process;if(n!==void 0){if(globalThis.process.platform!=="win32")try{globalThis.process.kill(-n.pid,e?"SIGKILL":"SIGTERM");return}catch{try{n.kill(e?"SIGKILL":"SIGTERM")}catch{}return}await new Promise(r=>{let i=Et("taskkill.exe",["/PID",String(n.pid),"/T",...e?["/F"]:[]],{windowsHide:!0,stdio:"ignore"});i.once("error",()=>r()),i.once("exit",()=>r())})}}s(Me,"terminateProcessTree");function z(t){return new Promise(e=>setTimeout(e,t))}s(z,"delay");function Yt(t){return t instanceof Error?t.message:String(t)}s(Yt,"errorMessage");function Xt(t){let e=Le.join(It.tmpdir(),`pi-agent-ide-terminal-${process.pid}`);return $t(e,{recursive:!0,mode:448}),Le.join(e,`${t}.log`)}s(Xt,"createOutputLog");import{AgentSession as Kt}from"@earendil-works/pi-coding-agent";var U=Symbol.for("pi-agent-ide.terminal-steering-observers");function De(t){let e=Kt.prototype,n=e[U]??zt(e);return n.listeners.add(t),()=>{n.listeners.delete(t),n.listeners.size===0&&n.restore()}}s(De,"observeQueuedSteering");function zt(t){let e=t.prompt,n=t.steer,r=new Set,i=s(l=>{for(let u of[...r])u(l)},"notify"),a=s(function(l,u){return u?.streamingBehavior!=="steer"?e.call(this,l,u):e.call(this,l,{...u,preflightResult:s(d=>{u.preflightResult?.(d),d==="queued"&&i(this)},"preflightResult")})},"prompt"),o=s(async function(...l){let u=await n.apply(this,l);return u==="queued"&&i(this),u},"steer");t.prompt=a,t.steer=o;let c={listeners:r,restore:s(()=>{t[U]===c&&(t.prompt===a&&(t.prompt=e),t.steer===o&&(t.steer=n),delete t[U])},"restore")};return t[U]=c,c}s(zt,"installObservers");import Zt from"node:os";import Oe from"node:path";function Ne(t=process.platform,e=process.env){if(t==="win32"){let i=e.SHELL?.trim()||"powershell.exe",a=Oe.win32.basename(i).toLowerCase();return a==="cmd"||a==="cmd.exe"?{executable:i,displayName:"Command Prompt",family:"cmd",commandArgs:s(o=>["/d","/s","/c",o],"commandArgs")}:{executable:i,displayName:a.startsWith("pwsh")?"PowerShell":"Windows PowerShell",family:"powershell",commandArgs:s(o=>["-NoLogo","-NoProfile","-Command",o],"commandArgs")}}let n=e.SHELL?.trim()||Zt.userInfo().shell||(t==="darwin"?"/bin/zsh":"/bin/bash"),r=Oe.basename(n);return{executable:n,displayName:r==="zsh"?"zsh":r==="bash"?"Bash":r,family:"posix",commandArgs:s(i=>["-c",i],"commandArgs")}}s(Ne,"resolveShellProfile");function Ue(t){switch(t.family){case"powershell":return"Write PowerShell syntax. Use PowerShell cmdlets, `$env:NAME` for environment variables, and `;` or pipelines to compose commands.";case"cmd":return"Write Command Prompt syntax. Use `%NAME%` for environment variables and `&&` to chain successful commands.";case"posix":return`Write ${t.displayName} syntax. Use POSIX-style paths, \`$NAME\` for environment variables, and \`&&\` or pipelines to compose commands.`}}s(Ue,"shellSyntaxGuidance");import Be from"node:path";import{stripVTControlCharacters as Qt}from"node:util";import{defineTool as en}from"@earendil-works/pi-coding-agent";import{Type as S}from"typebox";import{Text as tn}from"@earendil-works/pi-tui";import{open as Jt}from"node:fs/promises";import{Type as g}from"typebox";var We=1024*1024,Fe=g.Object({output:g.String({description:"ANSI-free PTY output, up to 1 MiB. Longer output joins the first and last 512 KiB without adding labels or an omission marker. See output_ranges for the gap."}),truncated:g.Boolean({description:"Whether output omits bytes from the retained log. This is independent of whether the process has finished."}),full_output_path:g.String({description:"UTF-8 log of all output received so far. Available until the shell session is deleted."}),output_ranges:g.Array(g.Object({start:g.Integer(),end:g.Integer()}),{description:"Zero-based, end-exclusive UTF-8 byte ranges in the log, concatenated into output."}),exit_code:g.Optional(g.Number({description:"Process exit code, only when known."})),wall_time_seconds:g.Number(),session:g.String({description:"Session ID."}),source:g.String({description:"Persistent shell: source for Read, input and termination."}),status:g.Union(["running","completed","failed","stopping","stopped","cancelled","lost"].map(t=>g.Literal(t))),background:g.Boolean(),wait_reason:g.Optional(g.Union([g.Literal("timeout"),g.Literal("interactive"),g.Literal("steering")])),completion_reason:g.Optional(g.Literal("timeout")),signal:g.Optional(g.Number()),error:g.Optional(g.String())});async function je(t){let e=await Jt(t.fullOutputPath,"r");try{let n=(await e.stat()).size,r=s(async(c,l)=>{let u=Buffer.alloc(l),d=0;for(;d<l;){let m=await e.read(u,d,l-d,c+d);if(m.bytesRead===0)throw new Error("Shell output log ended before its snapshot size");d+=m.bytesRead}return u},"readRange"),i,a,o=n>We;if(!o)i=(await r(0,n)).toString("utf8"),a=[{start:0,end:n}];else{let c=We/2,l=await r(0,c),u=await r(n-c,c),d=new TextDecoder().decode(l,{stream:!0}),m=0;for(;m<u.length&&(u.readUInt8(m)&192)===128;)m++;let p=u.subarray(m).toString("utf8");i=d+p,a=[{start:0,end:Buffer.byteLength(d)},{start:n-c+m,end:n}]}return{output:i,truncated:o,full_output_path:t.fullOutputPath,output_ranges:a,...t.exitCode===void 0?{}:{exit_code:t.exitCode},wall_time_seconds:t.elapsedMs/1e3,session:t.id,source:t.source,status:t.status,background:t.background,...t.waitReason===void 0?{}:{wait_reason:t.waitReason},...t.completionReason===void 0?{}:{completion_reason:t.completionReason},...t.signal===void 0?{}:{signal:t.signal},...t.error===void 0?{}:{error:t.error}}}finally{await e.close()}}s(je,"structuredShellResult");var nn=s(t=>S.Object({command:S.String({minLength:1,description:`Command for ${t.displayName} (${t.executable}). ${Ue(t)}`}),background:S.Optional(S.Boolean({description:"Return immediately while the terminal session continues. Defaults to false."})),timeoutSeconds:S.Optional(S.Number({minimum:.1,maximum:86400,description:"Maximum foreground wait in seconds before returning the live session as background. Defaults to 60."})),cwd:S.Optional(S.String({description:"Working directory. Relative paths resolve from the current workspace."})),cols:S.Optional(S.Integer({minimum:20,maximum:300,description:"Virtual terminal width in cells"})),rows:S.Optional(S.Integer({minimum:5,maximum:120,description:"Virtual terminal height in cells"}))},{additionalProperties:!1}),"createRunParameters");function He(t,e,n,r,i="compact"){let a=new Set,o=process.platform==="win32"?"powershell":"bash",c=nn(n);return t.registerTool(en({name:o,exposure:"direct",namespace:{name:"ide_terminal",description:"Run shell commands in persistent terminal sessions."},annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!0},label:n.displayName,promptSnippet:`Execute ${n.displayName} commands in synchronous or background terminal sessions`,promptGuidelines:[`Do not use ${o} commands or scripts to edit files. Use the standalone editing tools instead. Commands that inherently generate files, such as formatters and code generators, are allowed.`],description:`Use ${o} to execute a command in the user's configured ${n.displayName} shell (${n.executable}). Every call creates an addressable terminal session. Set background to true to continue without waiting. A foreground wait automatically returns the live session as background on timeout, a stable interactive prompt, or turn abort. Background completion is delivered automatically and wakes the agent. Silent background sessions wake an idle agent once for inspection after two minutes, with no further stale reminders for that session. Sessions survive extension reloads and keep the same shell: source. Output uses the shared Read limits, keeps the tail, and links a complete log file when truncated.`,parameters:c,outputSchema:Fe,async execute(l,u,d,m,p){r.bind(p);let f=u.cwd===void 0?p.cwd:Be.resolve(p.cwd,u.cwd),h=e.start({command:u.command,background:u.background??!1,cwd:f,shell:n,...u.cols===void 0?{}:{cols:u.cols},...u.rows===void 0?{}:{rows:u.rows}});if(u.background===!0&&h.status!=="failed")return await rn(e,h,m),h.status!=="running"&&(h.completionDelivered=!0),W(e.snapshot(h));if(h.status==="failed")return W(e.snapshot(h));let w=new AbortController;a.add(w);let y;try{y=await e.waitForForeground(h.source,{signal:d===void 0?w.signal:AbortSignal.any([d,w.signal]),timeoutMs:(u.timeoutSeconds??60)*1e3})}finally{a.delete(w)}return y.reason==="aborted"&&w.signal.aborted&&d?.aborted!==!0?(y.session.waitReason="steering",W(e.snapshot(y.session))):(y.reason==="aborted"&&r.notifyWaitTransition(y.session),W(e.snapshot(y.session)))},renderCall(l,u,d){if((d.expanded?"full":i)==="disabled")return new tn(u.fg("toolTitle",o),0,0);let p=typeof l.command=="string"?l.command:"",f=typeof l.cwd=="string"?Be.resolve(process.cwd(),l.cwd):process.cwd();return he(p,l.background===!0,f,n,u)},renderResult(l,u,d){return Se(l.details,u.expanded?"full":i,d)}})),()=>{for(let l of a)l.abort()}}s(He,"registerTerminalTools");function Ge(t){let e=$(t.output).content;return{content:[{type:"text",text:M(t)}],details:{...t,output:e,outputStart:t.outputEnd-e.length,truncated:t.truncated||e.length<t.output.length},isError:t.status==="failed"||t.status==="lost"}}s(Ge,"terminalPreview");async function W(t){return{...Ge(t),structuredContent:await je(t)}}s(W,"terminalResult");async function rn(t,e,n){await new Promise(r=>{let i=!1,a,o=s(()=>{},"unsubscribe"),c=s(()=>{i||(i=!0,clearTimeout(a),o(),r())},"finish"),l=s(()=>{let u=t.snapshot(e);n?.(Ge(u)),(Qt(u.output).replaceAll("\r","").split(`
23
+ `).entries()){let c=e.caseSensitive===!0?o:o.toLocaleLowerCase(),l=0;for(;r.length<i;){let u=c.indexOf(n,l);if(u<0)break;let d=u+n.length;(e.wholeWord!==!0||vt(c,u,d))&&r.push({source:t.source,lineNumber:a+1,startColumn:u,endColumn:d,matchedText:o.slice(u,d),lineText:o}),l=Math.max(d,u+1)}if(r.length>=i)break}return r}s(xt,"findTerminalMatches");function vt(t,e,n){return!/[\p{L}\p{N}_]/u.test(t[e-1]??"")&&!/[\p{L}\p{N}_]/u.test(t[n]??"")}s(vt,"isWordBoundary");function O(t){if(!Pt(t))throw new TypeError("Invalid terminal search result");return t}s(O,"parsePayload");function Pt(t){return K(t)&&typeof t.query=="string"&&Array.isArray(t.matches)&&K(t.snapshot)&&typeof t.snapshot.source=="string"}s(Pt,"isTerminalSearchPayload");function K(t){return typeof t=="object"&&t!==null}s(K,"isRecord");import{spawn as Et}from"node:child_process";import{closeSync as At,mkdirSync as $t,openSync as kt,rmSync as Ct,writeSync as Lt}from"node:fs";import It from"node:os";import Le from"node:path";import{createRequire as Mt}from"node:module";import{randomUUID as _t}from"node:crypto";import{stripVTControlCharacters as Dt}from"node:util";var _e=Mt(new URL("../src/plugins/pi-agent-ide-terminal/src/session-manager.ts",import.meta.url).href),Ie=1e6,Ot=100,Nt=30,Ut=2e3,N=class{static{s(this,"TerminalSessionManager")}#a;#e=new Map;#t=new Set;#r=new Set;#i=new Map;#o=!1;constructor(e=jt){this.#a=e}onDidChange(e){return this.#t.add(e),()=>this.#t.delete(e)}onDidComplete(e){return this.#r.add(e),()=>this.#r.delete(e)}list(){return[...this.#e.values()].sort((e,n)=>n.startedAt-e.startedAt).map(e=>this.snapshot(e))}get(e){return this.#e.get(Bt(e))}snapshot(e,n=Date.now()){return{id:e.id,source:e.source,command:e.command,cwd:e.cwd,shell:e.shell.displayName,shellFamily:e.shell.family,...e.process===void 0?{}:{pid:e.process.pid},background:e.background,status:e.status,...e.waitReason===void 0?{}:{waitReason:e.waitReason},...e.completionReason===void 0?{}:{completionReason:e.completionReason},lastActivityAt:e.lastActivityAt,idleMs:Math.max(0,n-e.lastActivityAt),startedAt:e.startedAt,...e.endedAt===void 0?{}:{endedAt:e.endedAt},elapsedMs:(e.endedAt??n)-e.startedAt,...e.exitCode===void 0?{}:{exitCode:e.exitCode},...e.signal===void 0?{}:{signal:e.signal},...e.error===void 0?{}:{error:e.error},output:e.output,outputStart:e.outputStart,outputEnd:e.outputStart+e.output.length,truncated:e.outputStart>0,fullOutputPath:e.fullOutputPath,cols:e.cols,rows:e.rows}}start(e){if(this.#o)throw new Error("Terminal session manager is closed");let n=this.#a();if(!/^[a-f\d]{12}$/u.test(n)||this.#e.has(n))throw new Error("Terminal session IDs must be unique 12-character hexadecimal values");let r=Xt(n);this.#i.set(n,kt(r,"a",384));let i=e.cols??Ot,a=e.rows??Nt,o=Ft(i,a),c=s(f=>{},"resolveCompletion"),l=new Promise(f=>{c=f}),u={id:n,source:`shell:${n}`,command:e.command,background:e.background,cwd:e.cwd,shell:e.shell,startedAt:Date.now(),lastActivityAt:Date.now(),cols:i,rows:a,fullOutputPath:r,screen:o,status:"running",output:"",outputStart:0,screenReady:Promise.resolve(),completion:l,resolveCompletion:c,completionDelivered:!1,staleReminderDelivered:!1},d;try{let f=_e("node-pty"),p={name:"xterm-256color",cols:i,rows:a,cwd:e.cwd,env:Gt(Ht())};d=f.spawn(e.shell.executable,[...e.shell.commandArgs(e.command)],p)}catch(f){let p={...u,status:"failed",endedAt:Date.now(),error:Yt(f)};return this.#e.set(n,p),this.#s(n),c(p),queueMicrotask(()=>this.#l(p)),p}let m={...u,process:d};return this.#e.set(n,m),d.onData(f=>this.#u(m,f)),d.onExit(({exitCode:f,signal:p})=>{v(m.status)||(m.endedAt=Date.now(),m.exitCode=f,p!==0&&(m.signal=p),m.status=m.status==="stopping"?"stopped":f===0?"completed":"failed",(f===124||f===137)&&(m.completionReason="timeout"),this.#s(m.id),m.resolveCompletion(m),this.#n(m),this.#l(m))}),this.#n(m),m}async wait(e,n){let r=this.required(e);return v(r.status)?r:n?.aborted===!0?(await this.stop(r.source,"cancelled"),r):await new Promise((i,a)=>{let o=s(()=>{this.stop(r.source,"cancelled").then(i,a)},"onAbort");n?.addEventListener("abort",o,{once:!0}),r.completion.then(c=>{n?.removeEventListener("abort",o),i(c)},a)})}async waitForForeground(e,n){let r=this.required(e);if(v(r.status))return{session:r};let i=n.interactiveDelayMs??3e3;return await new Promise(a=>{let o=!1,c,l=s(f=>{o||(f!==void 0&&v(r.status)&&(f=void 0),o=!0,clearTimeout(d),clearInterval(m),n.signal?.removeEventListener("abort",u),f!==void 0&&(r.background=!0,f!=="aborted"&&(r.waitReason=f),this.#n(r)),a({session:r,...f===void 0?{}:{reason:f}}))},"finish"),u=s(()=>l("aborted"),"onAbort"),d=setTimeout(()=>l("timeout"),n.timeoutMs),m=setInterval(()=>{if(!Wt(r)){c=void 0;return}c??=Date.now(),Date.now()-c>=i&&l("interactive")},Math.min(100,Math.max(10,i/2)));n.signal?.addEventListener("abort",u,{once:!0}),n.signal?.aborted===!0&&u(),r.completion.then(()=>l())})}async waitForOutputAfter(e,n){let r=Date.now()+300,i=n,a;for(;Date.now()<r;){let o=e.outputStart+e.output.length;if(o!==i)i=o,a=Date.now(),await e.screenReady;else if(a!==void 0&&Date.now()-a>=40)return;await z(10)}await e.screenReady}screenRows(e){let n=e.screen.buffer.active;return Array.from({length:e.rows},(r,i)=>(n.getLine(n.baseY+i)?.translateToString(!0)??"").trimEnd())}screenChangeRegion(e,n,r=6){let i=this.screenRows(e),a=Math.max(1,Math.min(e.rows,r)),o=Math.max(0,e.screen.buffer.active.cursorY-Math.floor(a/2)),c=-1;for(let d=0;d<=e.rows-a;d+=1){let m=0;for(let f=d;f<d+a;f+=1){let p=n[f]??"",h=i[f]??"",w=h.length>0&&!n.includes(h),y=p.length>0&&h.length===0;p!==h&&(w||y)&&(m+=1)}m>c&&(c=m,o=d)}let l=e.screen.buffer.active;return{lines:i.slice(o,o+a).map((d,m)=>{if(o+m!==l.cursorY)return d;let p=d.padEnd(l.cursorX," ");return`${p.slice(0,l.cursorX)}\u258C${p.slice(l.cursorX)}`}),startRow:o}}screenChangeWindow(e,n,r=6){return this.screenChangeRegion(e,n,r).lines}screenTail(e,n=e.rows){let r=e.screen.buffer.active,i=Math.max(0,r.baseY),a=[];for(let o=0;o<e.rows;o+=1){let c=r.getLine(i+o)?.translateToString(!0).trimEnd();c!==void 0&&c.length>0&&a.push(c)}return a.slice(-Math.max(0,n))}markInspected(e){let n=this.required(e);n.status==="running"&&(n.lastActivityAt=Date.now(),this.#n(n))}write(e,n){this.requiredRunning(e).process?.write(n)}sendKeys(e,n){this.requiredRunning(e).process?.write(qt(n))}async stop(e,n="stopped"){let r=this.required(e);return v(r.status)||(r.status="stopping",this.#n(r),await Me(r,!1),await Promise.race([r.completion.then(()=>!0),z(Ut).then(()=>!1)])||(await Me(r,!0),await Promise.race([r.completion,z(1e3)])),v(r.status)||(r.status=n,r.endedAt=Date.now(),this.#s(r.id),r.resolveCompletion(r),this.#l(r)),n==="cancelled"&&(r.status="cancelled"),this.#n(r)),r}async delete(e){let n=this.required(e);n.completionDelivered=!0,await this.stop(n.source),n.screen.dispose(),this.#s(n.id),Ct(n.fullOutputPath,{force:!0}),this.#e.delete(n.id),this.#n(n)}async screenLines(e){let n=this.required(e);await n.screenReady;let r=n.screen.buffer.active,i=[],a=Math.max(0,r.baseY);for(let o=a;o<a+n.rows;o+=1)i.push(r.getLine(o)?.translateToString(!0)??"");return i}cursor(e){let n=this.required(e);return{x:n.screen.buffer.active.cursorX,y:n.screen.buffer.active.cursorY}}async dispose(){if(!this.#o){this.#o=!0,await Promise.all([...this.#e.values()].filter(e=>!v(e.status)).map(e=>this.stop(e.source)));for(let e of this.#e.values())e.screen.dispose(),this.#s(e.id);this.#t.clear(),this.#r.clear()}}required(e){let n=this.get(e);if(n===void 0)throw new Error(`Unknown terminal session ${e}`);return n}requiredRunning(e){let n=this.required(e);if(n.status!=="running")throw new Error(`Terminal session ${n.source} is ${n.status}; input is unavailable`);return n}#u(e,n){e.lastActivityAt=Date.now();let r=Dt(n),i=this.#i.get(e.id);if(i!==void 0&&Lt(i,r),e.output+=r,e.output.length>Ie){let a=e.output.length-Ie;e.output=e.output.slice(a),e.outputStart+=a}e.screenReady=e.screenReady.then(()=>new Promise(a=>{e.screen.write(n,a)})),this.#n(e)}#s(e){let n=this.#i.get(e);n!==void 0&&(At(n),this.#i.delete(e))}#n(e){for(let n of this.#t)n(e)}#l(e){for(let n of this.#r)n(e)}};function Wt(t){if(t.status!=="running")return!1;let e=t.screen.buffer.active,n=e.getLine(e.baseY+e.cursorY)?.translateToString(!0).trimEnd()??"";return/\[[^\]\n]{1,20}(?:\/[^\]\n]{1,20})+\]\s*[:?>]?\s*$/iu.test(n)||/(?:choose|select|enter|password|confirm|continue|proceed)[^\n]{0,60}[:?]\s*$/iu.test(n)||/^(?:❯|›)\s+\S/u.test(n)}s(Wt,"looksInteractive");function Ft(t,e){let{Terminal:n}=_e("@xterm/headless");return new n({cols:t,rows:e,scrollback:2e3,allowProposedApi:!0})}s(Ft,"createScreen");function jt(){return _t().replaceAll("-","").slice(0,12)}s(jt,"defaultSessionId");function Bt(t){return t.startsWith("shell:")?t.slice(6):t}s(Bt,"normalizeSessionId");function v(t){return t!=="running"&&t!=="stopping"}s(v,"isTerminalStatus");function Ht(){return process.env}s(Ht,"processEnvironment");function Gt(t){return{...Object.fromEntries(Object.entries(t).filter(e=>e[1]!==void 0)),PAGER:"cat",GIT_PAGER:"cat",SYSTEMD_PAGER:"cat",GH_PAGER:"cat"}}s(Gt,"cleanEnvironment");function qt(t){return t.split(/[\s,]+/u).filter(Boolean).map(Vt).join("")}s(qt,"encodeTerminalKeys");function Vt(t){if(/^\^[?@A-Z[\\\]^_]$/iu.test(t)){let d=t.slice(1).toUpperCase();return d==="?"?"\x7F":String.fromCharCode(d.charCodeAt(0)&31)}let e=t.toLowerCase().split("+"),n=e.pop()??"",r=new Set(e);if([...r].some(d=>!["ctrl","control","alt","meta","shift"].includes(d)))throw new Error(`Unsupported terminal key ${t}`);let i=r.has("ctrl")||r.has("control"),a=r.has("alt")||r.has("meta"),o=r.has("shift");if(i&&n.length===1&&/[a-z@[\\\]^_?]/u.test(n)){let d=n.toUpperCase(),m=d==="?"?"\x7F":String.fromCharCode(d.charCodeAt(0)&31);return a?`\x1B${m}`:m}let c={enter:"\r",tab:" ",escape:"\x1B",esc:"\x1B",backspace:"\x7F",home:"\x1B[H",end:"\x1B[F",delete:"\x1B[3~"};if(!i&&!a&&!o&&c[n]!==void 0)return c[n];if(a&&!i&&!o&&c[n]!==void 0)return`\x1B${c[n]}`;let u={up:"A",down:"B",right:"C",left:"D",home:"H",end:"F"}[n];if(u!==void 0)return!i&&!a&&!o?`\x1B[${u}`:`\x1B[1;${1+(o?1:0)+(a?2:0)+(i?4:0)}${u}`;if(a&&!i&&n.length===1)return`\x1B${o?n.toUpperCase():n}`;throw new Error(`Unsupported terminal key ${t}`)}s(Vt,"encodeTerminalKey");async function Me(t,e){let n=t.process;if(n!==void 0){if(globalThis.process.platform!=="win32")try{globalThis.process.kill(-n.pid,e?"SIGKILL":"SIGTERM");return}catch{try{n.kill(e?"SIGKILL":"SIGTERM")}catch{}return}await new Promise(r=>{let i=Et("taskkill.exe",["/PID",String(n.pid),"/T",...e?["/F"]:[]],{windowsHide:!0,stdio:"ignore"});i.once("error",()=>r()),i.once("exit",()=>r())})}}s(Me,"terminateProcessTree");function z(t){return new Promise(e=>setTimeout(e,t))}s(z,"delay");function Yt(t){return t instanceof Error?t.message:String(t)}s(Yt,"errorMessage");function Xt(t){let e=Le.join(It.tmpdir(),`pi-agent-ide-terminal-${process.pid}`);return $t(e,{recursive:!0,mode:448}),Le.join(e,`${t}.log`)}s(Xt,"createOutputLog");import{AgentSession as Kt}from"@earendil-works/pi-coding-agent";var U=Symbol.for("pi-agent-ide.terminal-steering-observers");function De(t){let e=Kt.prototype,n=e[U]??zt(e);return n.listeners.add(t),()=>{n.listeners.delete(t),n.listeners.size===0&&n.restore()}}s(De,"observeQueuedSteering");function zt(t){let e=t.prompt,n=t.steer,r=new Set,i=s(l=>{for(let u of[...r])u(l)},"notify"),a=s(function(l,u){return u?.streamingBehavior!=="steer"?e.call(this,l,u):e.call(this,l,{...u,preflightResult:s(d=>{u.preflightResult?.(d),d==="queued"&&i(this)},"preflightResult")})},"prompt"),o=s(async function(...l){let u=await n.apply(this,l);return u==="queued"&&i(this),u},"steer");t.prompt=a,t.steer=o;let c={listeners:r,restore:s(()=>{t[U]===c&&(t.prompt===a&&(t.prompt=e),t.steer===o&&(t.steer=n),delete t[U])},"restore")};return t[U]=c,c}s(zt,"installObservers");import Zt from"node:os";import Oe from"node:path";function Ne(t=process.platform,e=process.env){if(t==="win32"){let i=e.SHELL?.trim()||"powershell.exe",a=Oe.win32.basename(i).toLowerCase();return a==="cmd"||a==="cmd.exe"?{executable:i,displayName:"Command Prompt",family:"cmd",commandArgs:s(o=>["/d","/s","/c",o],"commandArgs")}:{executable:i,displayName:a.startsWith("pwsh")?"PowerShell":"Windows PowerShell",family:"powershell",commandArgs:s(o=>["-NoLogo","-NoProfile","-Command",o],"commandArgs")}}let n=e.SHELL?.trim()||Zt.userInfo().shell||(t==="darwin"?"/bin/zsh":"/bin/bash"),r=Oe.basename(n);return{executable:n,displayName:r==="zsh"?"zsh":r==="bash"?"Bash":r,family:"posix",commandArgs:s(i=>["-c",i],"commandArgs")}}s(Ne,"resolveShellProfile");function Ue(t){switch(t.family){case"powershell":return"Write PowerShell syntax. Use PowerShell cmdlets, `$env:NAME` for environment variables, and `;` or pipelines to compose commands.";case"cmd":return"Write Command Prompt syntax. Use `%NAME%` for environment variables and `&&` to chain successful commands.";case"posix":return`Write ${t.displayName} syntax. Use POSIX-style paths, \`$NAME\` for environment variables, and \`&&\` or pipelines to compose commands.`}}s(Ue,"shellSyntaxGuidance");import Be from"node:path";import{stripVTControlCharacters as Qt}from"node:util";import{defineTool as en}from"@earendil-works/pi-coding-agent";import{Type as S}from"typebox";import{Text as tn}from"@earendil-works/pi-tui";import{open as Jt}from"node:fs/promises";import{Type as g}from"typebox";var We=1024*1024,Fe=g.Object({output:g.String({description:"ANSI-free PTY output, up to 1 MiB. Longer output joins the first and last 512 KiB without adding labels or an omission marker. See output_ranges for the gap."}),truncated:g.Boolean({description:"Whether output omits bytes from the retained log. This is independent of whether the process has finished."}),full_output_path:g.String({description:"UTF-8 log of all output received so far. Available until the shell session is deleted."}),output_ranges:g.Array(g.Object({start:g.Integer(),end:g.Integer()}),{description:"Zero-based, end-exclusive UTF-8 byte ranges in the log, concatenated into output."}),exit_code:g.Optional(g.Number({description:"Process exit code, only when known."})),wall_time_seconds:g.Number(),session:g.String({description:"Session ID."}),source:g.String({description:"Persistent shell: source for Read, input and termination."}),status:g.Union(["running","completed","failed","stopping","stopped","cancelled","lost"].map(t=>g.Literal(t))),background:g.Boolean(),wait_reason:g.Optional(g.Union([g.Literal("timeout"),g.Literal("interactive"),g.Literal("steering")])),completion_reason:g.Optional(g.Literal("timeout")),signal:g.Optional(g.Number()),error:g.Optional(g.String())});async function je(t){let e=await Jt(t.fullOutputPath,"r");try{let n=(await e.stat()).size,r=s(async(c,l)=>{let u=Buffer.alloc(l),d=0;for(;d<l;){let m=await e.read(u,d,l-d,c+d);if(m.bytesRead===0)throw new Error("Shell output log ended before its snapshot size");d+=m.bytesRead}return u},"readRange"),i,a,o=n>We;if(!o)i=(await r(0,n)).toString("utf8"),a=[{start:0,end:n}];else{let c=We/2,l=await r(0,c),u=await r(n-c,c),d=new TextDecoder().decode(l,{stream:!0}),m=0;for(;m<u.length&&(u.readUInt8(m)&192)===128;)m++;let f=u.subarray(m).toString("utf8");i=d+f,a=[{start:0,end:Buffer.byteLength(d)},{start:n-c+m,end:n}]}return{output:i,truncated:o,full_output_path:t.fullOutputPath,output_ranges:a,...t.exitCode===void 0?{}:{exit_code:t.exitCode},wall_time_seconds:t.elapsedMs/1e3,session:t.id,source:t.source,status:t.status,background:t.background,...t.waitReason===void 0?{}:{wait_reason:t.waitReason},...t.completionReason===void 0?{}:{completion_reason:t.completionReason},...t.signal===void 0?{}:{signal:t.signal},...t.error===void 0?{}:{error:t.error}}}finally{await e.close()}}s(je,"structuredShellResult");var nn=s(t=>S.Object({command:S.String({minLength:1,description:`Command for ${t.displayName} (${t.executable}). ${Ue(t)}`}),background:S.Optional(S.Boolean({description:"Return immediately while the terminal session continues. Defaults to false."})),timeoutSeconds:S.Optional(S.Number({minimum:.1,maximum:86400,description:"Maximum foreground wait in seconds before returning the live session as background. Defaults to 60."})),cwd:S.Optional(S.String({description:"Working directory. Relative paths resolve from the current workspace."})),cols:S.Optional(S.Integer({minimum:20,maximum:300,description:"Virtual terminal width in cells"})),rows:S.Optional(S.Integer({minimum:5,maximum:120,description:"Virtual terminal height in cells"}))},{additionalProperties:!1}),"createRunParameters");function He(t,e,n,r,i="compact"){let a=new Set,o=process.platform==="win32"?"powershell":"bash",c=nn(n);return t.registerTool(en({name:o,exposure:"direct",namespace:{name:"ide_terminal",description:"Run shell commands in persistent terminal sessions."},annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!0},label:n.displayName,promptSnippet:`Execute ${n.displayName} commands in synchronous or background terminal sessions`,promptGuidelines:[`Do not use ${o} commands or scripts to edit files. Use the standalone editing tools instead. Commands that inherently generate files, such as formatters and code generators, are allowed.`],description:`Use ${o} to execute a command in the user's configured ${n.displayName} shell (${n.executable}). Every call creates an addressable terminal session. Set background to true to continue without waiting. A foreground wait automatically returns the live session as background on timeout, a stable interactive prompt, or turn abort. Background completion is delivered automatically and wakes the agent. Silent background sessions wake an idle agent once for inspection after two minutes, with no further stale reminders for that session. Sessions survive extension reloads and keep the same shell: source. Output uses the shared Read limits, keeps the tail, and links a complete log file when truncated.`,parameters:c,outputSchema:Fe,async execute(l,u,d,m,f){r.bind(f);let p=u.cwd===void 0?f.cwd:Be.resolve(f.cwd,u.cwd),h=e.start({command:u.command,background:u.background??!1,cwd:p,shell:n,...u.cols===void 0?{}:{cols:u.cols},...u.rows===void 0?{}:{rows:u.rows}});if(u.background===!0&&h.status!=="failed")return await rn(e,h,m),h.status!=="running"&&(h.completionDelivered=!0),W(e.snapshot(h));if(h.status==="failed")return W(e.snapshot(h));let w=new AbortController;a.add(w);let y;try{y=await e.waitForForeground(h.source,{signal:d===void 0?w.signal:AbortSignal.any([d,w.signal]),timeoutMs:(u.timeoutSeconds??60)*1e3})}finally{a.delete(w)}return y.reason==="aborted"&&w.signal.aborted&&d?.aborted!==!0?(y.session.waitReason="steering",W(e.snapshot(y.session))):(y.reason==="aborted"&&r.notifyWaitTransition(y.session),W(e.snapshot(y.session)))},renderCall(l,u,d){if((d.expanded?"full":i)==="disabled")return new tn(u.fg("toolTitle",o),0,0);let f=typeof l.command=="string"?l.command:"",p=typeof l.cwd=="string"?Be.resolve(process.cwd(),l.cwd):process.cwd();return he(f,l.background===!0,p,n,u)},renderResult(l,u,d){return Se(l.details,u.expanded?"full":i,d)}})),()=>{for(let l of a)l.abort()}}s(He,"registerTerminalTools");function Ge(t){let e=$(t.output).content;return{content:[{type:"text",text:M(t)}],details:{...t,output:e,outputStart:t.outputEnd-e.length,truncated:t.truncated||e.length<t.output.length},isError:t.status==="failed"||t.status==="lost"}}s(Ge,"terminalPreview");async function W(t){return{...Ge(t),structuredContent:await je(t)}}s(W,"terminalResult");async function rn(t,e,n){await new Promise(r=>{let i=!1,a,o=s(()=>{},"unsubscribe"),c=s(()=>{i||(i=!0,clearTimeout(a),o(),r())},"finish"),l=s(()=>{let u=t.snapshot(e);n?.(Ge(u)),(Qt(u.output).replaceAll("\r","").split(`
24
24
  `).filter(m=>m.length>0).length>=E||u.status!=="running")&&c()},"publish");o=t.onDidChange(u=>{u.id===e.id&&l()}),a=setTimeout(c,2e3),l()})}s(rn,"captureInitialBackgroundPreview");import{Box as qe,Container as Ve}from"@earendil-works/pi-tui";var on=120,sn=12e4,F=class{constructor(e,n,r=sn){this.pi=e;this.manager=n;this.staleIntervalMs=r;e.registerMessageRenderer("terminal-stale",(i,{expanded:a},o)=>{let c=Ye(i.details)?i.details:void 0,l=new Ve;c!==void 0&&l.addChild(x(c,a,o,"stale \xB7 inspect session"));let u=new qe(1,1,d=>o.bg("toolPendingBg",d));return u.addChild(l),u}),e.registerMessageRenderer("terminal-completion",(i,{expanded:a},o)=>{let c=new Ve;for(let u of an(i.details))c.addChild(x(u,a,o));let l=new qe(1,1,u=>o.bg("toolSuccessBg",u));return l.addChild(c),l}),this.#u=[n.onDidChange(i=>this.#s(i)),n.onDidComplete(i=>{this.#l(i.id),i.background&&this.#c(i)})]}static{s(this,"TerminalUi")}#a=new Map;#e;#t=new Map;#r=new Set;#i;#o=!1;#u;bind(e){this.#i=e}onAgentSettled(e){this.#i=e;for(let n of[...this.#r]){this.#r.delete(n);let r=this.manager.get(n);r!==void 0&&this.#s(r,!0)}}notifyWaitTransition(e){let n=this.manager.snapshot(e);this.pi.sendMessage({customType:"terminal-wait-transition",display:!1,content:`Terminal wait ended; ${n.source} is still running in background. Read it to inspect output, then use write or insert to send input.`,details:n},{triggerTurn:!0,deliverAs:"steer"})}dispose(){this.#o=!0,this.#e!==void 0&&clearTimeout(this.#e),this.#e=void 0,this.#a.clear();for(let e of this.#t.values())clearTimeout(e);this.#t.clear(),this.#r.clear(),this.#i=void 0;for(let e of this.#u)e()}#s(e,n=!1){if(this.#l(e.id),this.#o||e.staleReminderDelivered||!e.background||e.status!=="running")return;let r=this.manager.snapshot(e),i=Math.max(0,this.staleIntervalMs-r.idleMs);if(n&&i===0){this.#n(e);return}this.#t.set(e.id,setTimeout(()=>this.#n(e),i))}#n(e){if(this.#t.delete(e.id),this.#o||e.staleReminderDelivered||e.status!=="running"||!e.background)return;if(this.#i?.isIdle()!==!0){this.#r.add(e.id);return}e.staleReminderDelivered=!0;let n=this.manager.snapshot(e);this.pi.sendMessage({customType:"terminal-stale",display:!0,content:un(n),details:n},{triggerTurn:!0,deliverAs:"followUp"})}#l(e){let n=this.#t.get(e);n!==void 0&&clearTimeout(n),this.#t.delete(e),this.#r.delete(e)}#c(e){this.#o||e.completionDelivered||(this.#a.set(e.id,e),this.#e===void 0&&(this.#e=setTimeout(()=>{this.#e=void 0;let n=[...this.#a.values()].filter(i=>!i.completionDelivered);if(this.#a.clear(),this.#o||n.length===0)return;for(let i of n)i.completionDelivered=!0;let r=n.map(i=>this.manager.snapshot(i));this.pi.sendMessage({customType:"terminal-completion",display:!0,content:ln(r),details:{sessions:r}},{triggerTurn:!0,deliverAs:"steer"})},on)))}};function an(t){return!Ke(t)||!Array.isArray(t.sessions)?[]:t.sessions.filter(Ye)}s(an,"completionSnapshots");function Ye(t){return Ke(t)&&typeof t.id=="string"&&typeof t.source=="string"&&typeof t.command=="string"&&typeof t.cwd=="string"&&typeof t.shell=="string"&&typeof t.background=="boolean"&&typeof t.status=="string"&&typeof t.startedAt=="number"&&typeof t.elapsedMs=="number"&&typeof t.output=="string"}s(Ye,"isTerminalSessionSnapshot");function ln(t){return`${t.length===1?"Background terminal completed:":"Background terminals completed:"}
25
25
  ${t.map(n=>{let r=n.exitCode===void 0?"":`, exit ${n.exitCode}`,i=n.completionReason===void 0?"":`, reason ${n.completionReason}`,a=n.output.trimEnd().slice(-2e3);return`- ${n.source}: ${n.status}${r}${i}, ${Xe(n.elapsedMs)}
26
26
  ${a||"(no output)"}`}).join(`
27
27
  `)}`}s(ln,"formatCompletionMessage");function un(t){let e=t.output.trimEnd().slice(-2e3);return`Background terminal ${t.source} has produced no output for ${Xe(t.idleMs)}. Inspect it with read. If it is healthy, keep waiting; otherwise send input or stop it.
28
- ${e||"(no output)"}`}s(un,"formatStaleMessage");function Xe(t){return t<1e3?`${t}ms`:`${(t/1e3).toFixed(t<1e4?1:0)}s`}s(Xe,"formatElapsed");function Ke(t){return typeof t=="object"&&t!==null}s(Ke,"isRecord");function ze(t){return t==="full"||t==="disabled"?t:"compact"}s(ze,"toolPresentation");async function cn(t,e){J(t,[await Z({id:"terminal",description:"Foreground and background commands, shell resources, and processes",triggers:[{tool:"bash"},{tool:"powershell"},...["read","write","insert","delete"].map(l=>({tool:l,resourcePrefixes:["shell:","process:"]}))]})]);let n=me("terminal")??new N,r=Ne(),i=new F(t,n),a=ce(t).add(Re(n));await Promise.all([$e(t,n),Ce(t,n)]);let o=He(t,n,r,i,ze(e?.preferences["ui.terminal"])),c=s(()=>{},"removeSteeringObserver");t.on("session_start",(l,u)=>{i.bind(u),c(),c=De(d=>{d.sessionManager===u.sessionManager&&o()})}),t.on("agent_settled",(l,u)=>i.onAgentSettled(u)),t.on("session_shutdown",async l=>{if(c(),i.dispose(),a(),l.reason!=="quit"){de("terminal",n);return}pe("terminal",n),await n.dispose()})}s(cn,"registerTerminal");export{cn as default};
28
+ ${e||"(no output)"}`}s(un,"formatStaleMessage");function Xe(t){return t<1e3?`${t}ms`:`${(t/1e3).toFixed(t<1e4?1:0)}s`}s(Xe,"formatElapsed");function Ke(t){return typeof t=="object"&&t!==null}s(Ke,"isRecord");function ze(t){return t==="full"||t==="disabled"?t:"compact"}s(ze,"toolPresentation");async function cn(t,e){J(t,[await Z({id:"terminal",description:"Foreground and background commands, shell resources, and processes",triggers:[{tool:"bash"},{tool:"powershell"},...["read","write","insert","delete"].map(l=>({tool:l,resourcePrefixes:["shell:","process:"]}))]})]);let n=me("terminal")??new N,r=Ne(),i=new F(t,n),a=ce(t).add(Re(n));await Promise.all([$e(t,n),Ce(t,n)]);let o=He(t,n,r,i,ze(e?.preferences["ui.terminal"])),c=s(()=>{},"removeSteeringObserver");t.on("session_start",(l,u)=>{i.bind(u),c(),c=De(d=>{d.sessionManager===u.sessionManager&&o()})}),t.on("agent_settled",(l,u)=>i.onAgentSettled(u)),t.on("session_shutdown",async l=>{if(c(),i.dispose(),a(),l.reason!=="quit"){de("terminal",n);return}fe("terminal",n),await n.dispose()})}s(cn,"registerTerminal");export{cn as default};