blade-code 0.10.160 → 0.10.162

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 (134) hide show
  1. package/dist/blade.js +2 -2
  2. package/dist/{chunk-erhaedch.js → chunk-06hkf59s.js} +1 -1
  3. package/dist/chunk-0aya8d61.js +14 -0
  4. package/dist/{chunk-k3ne93k8.js → chunk-0mr8nexh.js} +2 -2
  5. package/dist/{chunk-tya95jej.js → chunk-0tzecdv3.js} +1 -1
  6. package/dist/chunk-1yq72zb7.js +8 -0
  7. package/dist/{chunk-jsv3e4k6.js → chunk-2f8d0km4.js} +1 -1
  8. package/dist/{chunk-5q4z0sfr.js → chunk-2mk914vk.js} +2 -2
  9. package/dist/{chunk-ht8epjz2.js → chunk-30x3mcsb.js} +2 -2
  10. package/dist/{chunk-6112ra8v.js → chunk-3aavhxe8.js} +1 -1
  11. package/dist/{chunk-ewwrss2w.js → chunk-3kszepm6.js} +1 -1
  12. package/dist/chunk-3xffezpc.js +1 -0
  13. package/dist/{chunk-28tzj187.js → chunk-3y2x6fb6.js} +1 -1
  14. package/dist/{chunk-7rjft1z9.js → chunk-46t79ek8.js} +2 -2
  15. package/dist/{chunk-9kj19a8t.js → chunk-4cdk4mds.js} +1 -1
  16. package/dist/chunk-4k7gvnth.js +1 -0
  17. package/dist/{chunk-7xtxvrh8.js → chunk-4wx5sya5.js} +1 -1
  18. package/dist/{chunk-7wcxjbyg.js → chunk-50vwafn5.js} +1 -1
  19. package/dist/{chunk-9xbwtjac.js → chunk-53fc0yrq.js} +1 -1
  20. package/dist/chunk-56ma2n3p.js +1 -0
  21. package/dist/chunk-5v0jcyea.js +2 -0
  22. package/dist/chunk-66wk3exc.js +1 -0
  23. package/dist/chunk-6c5z2b5s.js +1 -0
  24. package/dist/{chunk-5f40659e.js → chunk-6sedqj8r.js} +1 -1
  25. package/dist/{chunk-hs56jgkm.js → chunk-92ck72sg.js} +1 -1
  26. package/dist/{chunk-4c13mnh8.js → chunk-9cb1hv2z.js} +1 -1
  27. package/dist/chunk-9f6nyfcs.js +1 -0
  28. package/dist/{chunk-mt26v0vg.js → chunk-a6wkam4s.js} +1 -1
  29. package/dist/chunk-abc5bzqn.js +1 -0
  30. package/dist/{chunk-kr5w8q8v.js → chunk-ajtwwg2b.js} +1 -1
  31. package/dist/chunk-azn3qphf.js +1 -0
  32. package/dist/{chunk-gmmhpp0k.js → chunk-cvwcrr4h.js} +5 -5
  33. package/dist/{chunk-42y6ks44.js → chunk-d420fs8m.js} +1 -1
  34. package/dist/{chunk-n34qsnks.js → chunk-ddvdc2p0.js} +1 -1
  35. package/dist/chunk-e6tz8qrg.js +1 -0
  36. package/dist/{chunk-sdapqhj0.js → chunk-eg3ms291.js} +1 -1
  37. package/dist/{chunk-5xnht5vw.js → chunk-f194ct93.js} +2 -2
  38. package/dist/{chunk-zrgfvc4k.js → chunk-g01mth5d.js} +2 -2
  39. package/dist/{chunk-2ffyr4zh.js → chunk-hjrc4jdm.js} +1 -1
  40. package/dist/{chunk-y0vdq8h3.js → chunk-hs0fatm3.js} +1 -1
  41. package/dist/{chunk-0b67y4j1.js → chunk-j8hbddjp.js} +2 -2
  42. package/dist/chunk-j9fdpvq0.js +1 -0
  43. package/dist/{chunk-v1mamd1x.js → chunk-jj4ggb04.js} +2 -2
  44. package/dist/{chunk-f2y0gxyq.js → chunk-kqvzmnja.js} +2 -2
  45. package/dist/{chunk-sd9bze9x.js → chunk-kv458q06.js} +1 -1
  46. package/dist/{chunk-9tk6wq70.js → chunk-kvp523gt.js} +1 -1
  47. package/dist/{chunk-yh34b6z0.js → chunk-mg03ydep.js} +2 -2
  48. package/dist/{chunk-7bexc9c3.js → chunk-msx7ecb2.js} +2 -2
  49. package/dist/chunk-n6mv8p83.js +1 -0
  50. package/dist/chunk-n7kwrvvw.js +10 -0
  51. package/dist/{chunk-v67st2xb.js → chunk-nheny8xp.js} +2 -2
  52. package/dist/{chunk-4n0efk4n.js → chunk-nj2bggcj.js} +2 -2
  53. package/dist/{chunk-9q26ss92.js → chunk-psm2d7pr.js} +1 -1
  54. package/dist/chunk-pzqy0x7r.js +1 -0
  55. package/dist/{chunk-70hjk2jn.js → chunk-qjbn97e2.js} +2 -2
  56. package/dist/{chunk-sn2bqttf.js → chunk-qq8h5eag.js} +1 -1
  57. package/dist/{chunk-fhsvz4b1.js → chunk-rjbneaq0.js} +2 -2
  58. package/dist/{chunk-gm2yfq3r.js → chunk-rvs364rz.js} +2 -2
  59. package/dist/{chunk-g7pwwxvz.js → chunk-sspk1ah8.js} +3 -3
  60. package/dist/{chunk-xgyx1hwx.js → chunk-syq7j5b0.js} +2 -2
  61. package/dist/{chunk-qzxj1gvs.js → chunk-sz1jw89z.js} +1 -1
  62. package/dist/{chunk-7xhw74hk.js → chunk-t0gm0pn1.js} +1 -1
  63. package/dist/{chunk-erext256.js → chunk-t89f4way.js} +2 -2
  64. package/dist/{chunk-hv8nt7wj.js → chunk-vbjgcn49.js} +1 -1
  65. package/dist/{chunk-kenxyanc.js → chunk-vh5hxd2w.js} +1 -1
  66. package/dist/{chunk-n9819k4p.js → chunk-vw9paban.js} +1 -1
  67. package/dist/{chunk-fx9vm1n5.js → chunk-w33zjw8m.js} +2 -2
  68. package/dist/{chunk-e07acz8d.js → chunk-wbr9fc4k.js} +1 -1
  69. package/dist/{chunk-53vh6vpt.js → chunk-wcps5gjm.js} +1 -1
  70. package/dist/{chunk-jbpasjg9.js → chunk-xmymx75h.js} +1 -1
  71. package/dist/{chunk-a5r7c1n4.js → chunk-y54mge74.js} +3 -3
  72. package/dist/{chunk-vz13c7fr.js → chunk-y5wngtz0.js} +2 -2
  73. package/dist/{chunk-9zvxdc7t.js → chunk-yk62xvqm.js} +2 -2
  74. package/dist/{chunk-hj1c3k0m.js → chunk-za0frk62.js} +2 -2
  75. package/dist/chunk-zb6mn0dz.js +1 -0
  76. package/dist/{chunk-pv6cgfv1.js → chunk-zj1g4nbq.js} +1 -1
  77. package/dist/{chunk-wm896gnx.js → chunk-zzvs471p.js} +1 -1
  78. package/dist/web/assets/ChatView-er_sxPPR.js +70 -0
  79. package/dist/web/assets/{CodeBlockHighlighter-BpPOUcO7.js → CodeBlockHighlighter-y0h2qpHE.js} +1 -1
  80. package/dist/web/assets/{FilePreview-DXGkgNrQ.js → FilePreview-D3mhQ088.js} +14 -19
  81. package/dist/web/assets/{KanbanBoard-MYvqGgQH.js → KanbanBoard-CVg8k1mE.js} +2 -2
  82. package/dist/web/assets/{MarkdownRenderer-CXDrI3kX.js → MarkdownRenderer-CNBuegIp.js} +3 -3
  83. package/dist/web/assets/{ScrollArea-DocDa_rN.js → ScrollArea-nKClMHtv.js} +1 -1
  84. package/dist/web/assets/{SessionHistorySurface-D4Hxlpnr.js → SessionHistorySurface-DxS7TPaS.js} +1 -1
  85. package/dist/web/assets/{SettingsModal-ROSA92Eo.js → SettingsModal-CUn7pWF9.js} +1 -1
  86. package/dist/web/assets/{Sidebar-ByhqdRdj.js → Sidebar-CfxwNI2v.js} +1 -1
  87. package/dist/web/assets/TaskSwitcher-CSoJ4y5B.js +26 -0
  88. package/dist/web/assets/{TerminalPanel-czvVuMgl.js → TerminalPanel-BQuhnBca.js} +2 -2
  89. package/dist/web/assets/{archive-BwNnCDDQ.js → archive-BboAmbOv.js} +1 -1
  90. package/dist/web/assets/{arrow-left-Dc9lvaeD.js → arrow-left-DAUtSPbk.js} +1 -1
  91. package/dist/web/assets/{calendar-clock-o0GyQ0Np.js → calendar-clock-Vl0t-Nd3.js} +1 -1
  92. package/dist/web/assets/{chevron-right-CgHjrrmB.js → chevron-right-CF4tZJv_.js} +1 -1
  93. package/dist/web/assets/{clock-3-BB58ITKo.js → clock-3-UujBmwyg.js} +1 -1
  94. package/dist/web/assets/{copy-o_KiXkAh.js → copy-DqhAOOxU.js} +1 -1
  95. package/dist/web/assets/{download-BBtK3WHk.js → download-9K17cUAi.js} +1 -1
  96. package/dist/web/assets/{external-link-smSBd9oE.js → external-link-ZWYy4pMB.js} +1 -1
  97. package/dist/web/assets/{folder-BJP6kIlC.js → folder-CWkv_E0L.js} +1 -1
  98. package/dist/web/assets/index-C6zClU0B.js +211 -0
  99. package/dist/web/assets/index-CaCifsSK.css +1 -0
  100. package/dist/web/assets/message-square-plus-DOcUaurY.js +21 -0
  101. package/dist/web/assets/{pause-yqaK1hvk.js → pause-CvRQWY37.js} +1 -1
  102. package/dist/web/assets/{pencil-BZbDnyg2.js → pencil-CrKIc9az.js} +1 -1
  103. package/dist/web/assets/{play-WQ7288Ky.js → play-DN4KhXKM.js} +1 -1
  104. package/dist/web/assets/{plus-veQ2IAZx.js → plus-jGKGKGzn.js} +1 -1
  105. package/dist/web/assets/{session-events-Dwyp0AVI.js → session-events-aq2qdB3u.js} +25 -25
  106. package/dist/web/assets/{settings-B8xvrdSb.js → settings-DkVTw2qw.js} +1 -1
  107. package/dist/web/assets/{team-BrF46S7E.js → team-BBLJq3rO.js} +1 -1
  108. package/dist/web/assets/teamService-B6W5r_Z_.js +1 -0
  109. package/dist/web/assets/{terminal-BrqsCKf2.js → terminal-C30CbzhP.js} +1 -1
  110. package/dist/web/index.html +2 -2
  111. package/package.json +1 -1
  112. package/dist/chunk-514va7ce.js +0 -2
  113. package/dist/chunk-6c7v7ny5.js +0 -1
  114. package/dist/chunk-6s037nx9.js +0 -14
  115. package/dist/chunk-7ss9htq0.js +0 -1
  116. package/dist/chunk-bz9e9hj8.js +0 -1
  117. package/dist/chunk-dav8ngkr.js +0 -1
  118. package/dist/chunk-enf0egke.js +0 -1
  119. package/dist/chunk-er7r2abv.js +0 -1
  120. package/dist/chunk-j7784bxm.js +0 -1
  121. package/dist/chunk-k1tfry97.js +0 -5
  122. package/dist/chunk-p2r4svss.js +0 -10
  123. package/dist/chunk-r95wa6vn.js +0 -1
  124. package/dist/chunk-wsa7g7vd.js +0 -1
  125. package/dist/chunk-yx6kf3s7.js +0 -1
  126. package/dist/chunk-zn9tdkrq.js +0 -1
  127. package/dist/chunk-zqjm9yd8.js +0 -1
  128. package/dist/chunk-zv01qe34.js +0 -1
  129. package/dist/web/assets/ChatView-DYpMrwtA.js +0 -63
  130. package/dist/web/assets/TaskSwitcher-Dbo20Tim.js +0 -26
  131. package/dist/web/assets/chevrons-up-down-zQ_UZWV9.js +0 -16
  132. package/dist/web/assets/index-RGoMvYl5.css +0 -1
  133. package/dist/web/assets/index-pqMcowCZ.js +0 -203
  134. package/dist/web/assets/teamService-fDnXqw4L.js +0 -1
@@ -1,4 +1,4 @@
1
- import{p as gH,q as kH,r as CH,s as hH,t as OH,u as wH}from"./chunk-6112ra8v.js";import{B as RH,C as ZH,D as $H,E as qH,F as a,G as XH}from"./chunk-kr5w8q8v.js";import{H as NH,ca as MH,ea as zH,fa as fH,ja as AH}from"./chunk-gmmhpp0k.js";import"./chunk-zrgfvc4k.js";import"./chunk-4n0efk4n.js";import{$a as QH}from"./chunk-ht8epjz2.js";import{Mb as e,Yb as FH,gc as EH}from"./chunk-a5r7c1n4.js";import"./chunk-wm896gnx.js";import{Rd as GH,Vd as PH,Xd as d,ge as t}from"./chunk-hj1c3k0m.js";import"./chunk-9xbwtjac.js";import"./chunk-vz13c7fr.js";import"./chunk-fx9vm1n5.js";import{qf as TH}from"./chunk-9zvxdc7t.js";import{sf as yH,tf as bH,uf as IH}from"./chunk-7rjft1z9.js";import{vf as SH}from"./chunk-v67st2xb.js";import"./chunk-v1mamd1x.js";import{Vf as _H}from"./chunk-xgyx1hwx.js";import"./chunk-v508x7cg.js";import"./chunk-7xhw74hk.js";import"./chunk-k1tfry97.js";import"./chunk-f2y0gxyq.js";import"./chunk-k3ne93k8.js";import"./chunk-7wcxjbyg.js";import"./chunk-erext256.js";import"./chunk-yh34b6z0.js";import"./chunk-ewwrss2w.js";import{gh as c,kh as BH}from"./chunk-53vh6vpt.js";import"./chunk-hv8nt7wj.js";import"./chunk-erhaedch.js";import"./chunk-g7pwwxvz.js";import"./chunk-28tzj187.js";import"./chunk-5xnht5vw.js";import{Si as xH}from"./chunk-sd9bze9x.js";import{Xi as r,Yi as n}from"./chunk-514va7ce.js";import{aj as C}from"./chunk-jsv3e4k6.js";import"./chunk-n34qsnks.js";import{Ej as UH,Gj as H,Hj as YH,Jj as Y}from"./chunk-5q4z0sfr.js";import"./chunk-0b67y4j1.js";import"./chunk-9kj19a8t.js";import"./chunk-fhsvz4b1.js";import"./chunk-gm2yfq3r.js";import"./chunk-n9819k4p.js";import"./chunk-7xtxvrh8.js";import"./chunk-sdapqhj0.js";import uJ from"yargs";import{hideBin as dJ}from"yargs/helpers";function i(V,Z,Q){if(V.off){V.off(Z,Q);return}V.removeListener?.(Z,Q)}function aH(V,Z){if(!V.once&&!V.on||!V.off&&!V.removeListener)throw Error("Writable returned false without an observable drain contract");return new Promise((Q,q)=>{let J=!1,K=()=>{i(V,"drain",x),i(V,"error",j),Z.removeEventListener("abort",P)},D=(F)=>{if(J)return;J=!0,K(),F()},x=()=>D(Q),j=(F)=>D(()=>q(F??Error("Writable emitted an error"))),P=()=>D(()=>q(Z.reason??Error("Writable drain aborted")));if(Z.aborted){P();return}let T=V.once?.bind(V)??V.on?.bind(V);T?.("drain",x),T?.("error",j),Z.addEventListener("abort",P,{once:!0})})}async function iH(V,Z,Q){if(V.destroyed||V.writableEnded)throw Error("Writable is already closed");if(V.write(Z)===!1)await aH(V,Q)}class o{options;queues;sinkErrorListeners=[];failed=!1;closing=!1;handleAbort=()=>{this.fail(new a("aborted","Headless output was aborted",{cause:this.options.signal?.reason}))};constructor(V,Z={}){this.options=Z;let Q=(q)=>new XH({maxPendingItems:Z.maxPendingItems??ZH,maxPendingBytes:Z.maxPendingBytes??$H,writeTimeoutMs:Z.writeTimeoutMs??qH,sizeOf:(J)=>Buffer.byteLength(J),write:(J,K)=>iH(V[q],J,K),onFailure:(J)=>this.fail(J)});if(this.queues={stdout:Q("stdout"),stderr:Q("stderr")},this.observeSinkErrors(V.stdout),V.stderr!==V.stdout)this.observeSinkErrors(V.stderr);if(Z.signal?.addEventListener("abort",this.handleAbort,{once:!0}),Z.signal?.aborted)this.handleAbort()}write(V,Z){return this.queues[V].offer(Z).accepted}async flush(){await Promise.all([this.queues.stdout.flush(),this.queues.stderr.flush()])}close(V){if(this.closing||this.failed)return;this.closing=!0,this.options.signal?.removeEventListener("abort",this.handleAbort),this.removeSinkErrorListeners(),this.queues.stdout.close(V),this.queues.stderr.close(V)}stats(){return{stdout:this.queues.stdout.stats(),stderr:this.queues.stderr.stats()}}observeSinkErrors(V){if(!V.on||!V.off&&!V.removeListener)return;let Z=(Q)=>{this.fail(new a("write_failed","Headless writable failed",{cause:Q??Error("Writable emitted an error")}))};V.on("error",Z),this.sinkErrorListeners.push({writer:V,listener:Z})}fail(V){if(this.closing||this.failed)return;this.failed=!0,this.options.signal?.removeEventListener("abort",this.handleAbort),this.removeSinkErrorListeners(),this.queues.stdout.close(V),this.queues.stderr.close(V),this.options.onFailure?.(V)}removeSinkErrorListeners(){for(let{writer:V,listener:Z}of this.sinkErrorListeners.splice(0))i(V,"error",Z)}}var k=1;function L(V){return H.Object({event_version:H.Literal(k),...V})}var oH=L({type:H.Literal("content_delta"),delta:H.String()}),sH=L({type:H.Literal("thinking_delta"),delta:H.String()}),rH=L({type:H.Literal("thinking"),content:H.String()}),nH=L({type:H.Literal("stream_end")}),tH=L({type:H.Literal("content"),content:H.String()}),eH=L({type:H.Literal("structured_output"),output:H.Record(H.String(),H.Unknown()),schema_digest:H.String({pattern:"^[a-f0-9]{64}$"})}),s=Y(["readonly","write","execute"]),HJ=H.Object({kind:s,scope:Y(["global","session"]),queue_position:H.Integer({minimum:1}),in_flight:H.Integer({minimum:0}),limit:H.Integer({minimum:1})}),JJ=L({type:H.Literal("tool_start"),tool_name:H.String(),summary:H.String(),target:H.Optional(H.String()),tool_kind:H.Optional(s)}),KJ=L({type:H.Literal("tool_progress"),tool_name:H.String(),message:H.String(),progress:H.Optional(H.Number()),total:H.Optional(H.Number()),admission:H.Optional(HJ)}),VJ=H.Object({auto_backgrounded:H.Literal(!0),background_reason:H.Literal("foreground_budget"),foreground_budget_ms:H.Integer({minimum:1}),shell_id:H.String({minLength:1,maxLength:128,pattern:"^bash_[A-Za-z0-9-]+$"}),pid:H.Optional(H.Integer({minimum:1})),terminal_transport:Y(["local","acp"])}),ZJ=L({type:H.Literal("tool_result"),tool_name:H.String(),summary:H.String(),target:H.Optional(H.String()),tool_kind:H.Optional(s),success:H.Optional(H.Boolean()),error_type:H.Optional(H.String()),error_message:H.Optional(H.String()),background:H.Optional(VJ)}),$J=L({type:H.Literal("mcp_catalog_changed"),revision:H.Integer({minimum:1}),server_name:H.String(),added:H.Array(H.String()),removed:H.Array(H.String()),updated:H.Array(H.String())}),qJ=L({type:H.Literal("mcp_content_changed"),revision:H.Integer({minimum:1}),server_name:H.String(),content_kind:Y(["resources","resource_templates","prompts"]),added:H.Array(H.String()),removed:H.Array(H.String()),updated:H.Array(H.String())}),XJ=L({type:H.Literal("mcp_resource_updated"),revision:H.Integer({minimum:1}),server_name:H.String(),uri:H.String()}),YJ=L({type:H.Literal("mcp_connection_changed"),revision:H.Integer({minimum:1}),server_name:H.String(),phase:Y(["reconnecting","recovered","failed"]),reason:H.String(),attempt:H.Integer({minimum:0}),max_attempts:H.Integer({minimum:0}),next_retry_at:H.Optional(H.Integer({minimum:0})),error:H.Optional(H.String())}),BJ=L({type:H.Literal("mcp_log"),revision:H.Integer({minimum:1}),server_name:H.String(),level:Y(["debug","info","notice","warning","error","critical","alert","emergency"]),logger:H.Optional(H.String()),message:H.String(),projected_bytes:H.Integer({minimum:0}),data_sha256:H.String(),truncated:H.Boolean(),details_omitted:H.Boolean(),timestamp:H.Integer({minimum:0}),synthetic:H.Optional(H.Boolean())}),NJ=L({type:H.Literal("mcp_instructions_changed"),revision:H.Integer({minimum:0}),server_name:H.String(),action:Y(["added","removed"]),reason:Y(["snapshot","connection","disconnection"]),text:H.Optional(H.String()),source_bytes:H.Optional(H.Integer({minimum:0})),projected_bytes:H.Optional(H.Integer({minimum:0})),sha256:H.Optional(H.String()),truncated:H.Optional(H.Boolean()),details_omitted:H.Optional(H.Boolean())}),QJ=L({type:H.Literal("mcp_task_changed"),revision:H.Integer({minimum:0}),task_id:H.String(),server_name:H.String(),tool_name:H.String(),status:Y(["working","input_required","interrupted","completed","failed","cancelled"]),status_message:H.Optional(H.String()),created_at:H.Integer({minimum:0}),updated_at:H.Integer({minimum:0}),completed_at:H.Optional(H.Integer({minimum:0})),has_result:H.Boolean(),error:H.Optional(H.String())}),DJ=L({type:H.Literal("project_rules_loaded"),files:H.Array(H.Object({id:H.String(),relative_path:H.String(),source:Y(["project","local"]),conditional:H.Boolean(),content_sha256:H.String({pattern:"^[a-f0-9]{64}$"})})),trigger_paths:H.Array(H.String()),blocked_write:H.Boolean()}),LJ=L({type:H.Literal("user_shell_started"),execution_id:H.String(),command:H.String(),auxiliary:H.Boolean()}),WJ=L({type:H.Literal("user_shell_output"),execution_id:H.String(),stream:Y(["stdout","stderr"]),chunk:H.String(),stream_truncated:H.Boolean()}),jJ=L({type:H.Literal("user_shell_completed"),execution_id:H.String(),message_id:H.String(),status:Y(["completed","failed","aborted","timed_out","spawn_error"]),exit_code:H.Union([H.Integer(),H.Null()]),duration_ms:H.Number({minimum:0}),stdout:H.String(),stderr:H.String(),truncated:H.Boolean(),auxiliary:H.Boolean()}),xJ=L({type:H.Literal("phase"),phase:Y(["turn","searching","inspecting","target_hit","executing","completed"]),status:Y(["ongoing","hit","done"]),message:H.String(),turn:H.Optional(H.Number()),tool_name:H.Optional(H.String()),target:H.Optional(H.String())}),UJ=L({type:H.Literal("tool_detail"),tool_name:H.String(),detail:H.String()}),_J=L({type:H.Literal("task_update"),tasks:H.Array(NH)}),GJ=L({type:H.Literal("goal_frontier"),goal_id:H.String({minLength:1}),status:Y(["active","verifying","paused","blocked","usage_limited","budget_limited","complete"]),task_list_id:H.String({minLength:1,maxLength:256}),total:H.Integer({minimum:0}),completed:H.Integer({minimum:0}),in_progress:H.Integer({minimum:0}),pending:H.Integer({minimum:0}),blocked:H.Integer({minimum:0}),next_task:H.Optional(H.Object({id:H.String({minLength:1}),subject:H.String({minLength:1,maxLength:512}),priority:Y(["high","medium","low"])})),digest_sha256:H.String({pattern:"^[a-f0-9]{64}$"}),observed_at:H.String(),stall_category:H.Optional(Y(["waiting_dependency","same_task_no_effect","repeated_deferral"])),stall_count:H.Optional(H.Integer({minimum:1,maximum:3}))}),PJ=L({type:H.Literal("goal"),state:Y(["updated","cleared"]),goal_id:H.Optional(H.String()),status:H.Optional(Y(["active","verifying","paused","blocked","usage_limited","budget_limited","complete"])),verification_attempt:H.Optional(H.Integer({minimum:1})),verification_status:H.Optional(Y(["pending","pass","fail","partial"])),verifier_session_id:H.Optional(H.String()),verification_evidence_sha256:H.Optional(H.String({pattern:"^[a-f0-9]{64}$"})),verification_summary:H.Optional(H.String()),verification_stall_count:H.Optional(H.Integer({minimum:1})),premature_stop_pattern:H.Optional(Y(BH)),premature_stop_count:H.Optional(H.Integer({minimum:1})),execution_host_failure_category:H.Optional(Y(["timeout","admission","spawn","finalization","sandbox_start","terminal"])),execution_host_failure_count:H.Optional(H.Integer({minimum:1,maximum:3})),frontier_stall_category:H.Optional(Y(["waiting_dependency","same_task_no_effect","repeated_deferral"])),frontier_stall_count:H.Optional(H.Integer({minimum:1,maximum:3})),root_turn_id:H.Optional(H.String({minLength:1,maxLength:c})),current_turn_id:H.Optional(H.String({minLength:1,maxLength:c})),parent_turn_id:H.Optional(H.String({minLength:1,maxLength:c}))}),FJ=L({type:H.Literal("subagent"),state:Y(["spawned","completed"]),session_id:H.String(),subagent_type:H.Optional(H.String()),success:H.Optional(H.Boolean()),summary:H.Optional(H.String()),verification_verdict:H.Optional(Y(["pass","fail","partial"])),resumed_from:H.Optional(H.String()),root_agent_id:H.Optional(H.String()),resume_depth:H.Optional(H.Integer({minimum:0}))}),EJ=L({type:H.Literal("token_usage"),input_tokens:H.Number(),output_tokens:H.Number(),total_tokens:H.Number(),max_context_tokens:H.Number(),cache_read_tokens:H.Optional(H.Number()),cache_write_tokens:H.Optional(H.Number()),prompt_cache_break:H.Optional(H.Object({reason:Y(["model_changed","system_prompt_changed","tools_changed","request_policy_changed","ttl_expired","server_side"]),previous_cache_read_tokens:H.Number(),cache_read_tokens:H.Number(),cache_write_tokens:H.Number(),token_drop:H.Number(),elapsed_ms:H.Number(),call_number:H.Number(),system_prompt_changed:H.Boolean(),system_char_delta:H.Number(),tools_changed:H.Boolean(),added_tool_count:H.Number(),removed_tool_count:H.Number(),changed_tool_count:H.Number(),model_changed:H.Boolean(),request_policy_changed:H.Boolean()})),cost_usd:H.Optional(H.Number())}),MJ=L({type:H.Literal("compacting"),state:Y(["started","completed"]),reason:H.Optional(Y(["threshold","context_limit","turn_limit","manual"])),strategy:H.Optional(Y(["llm","fallback","snip"])),outcome:H.Optional(Y(["completed","fallback","failed"])),pre_tokens:H.Optional(H.Number({minimum:0})),pre_token_source:H.Optional(Y(["provider","provider_plus_estimate","local_estimate"])),estimated_pending_tokens:H.Optional(H.Number({minimum:0})),post_tokens:H.Optional(H.Number({minimum:0})),sample_attempts:H.Optional(H.Integer({minimum:0})),input_reductions:H.Optional(H.Integer({minimum:0})),messages_omitted:H.Optional(H.Integer({minimum:0})),files_omitted:H.Optional(H.Integer({minimum:0})),images_omitted:H.Optional(H.Integer({minimum:0})),fallback_target_tokens:H.Optional(H.Integer({minimum:0})),fallback_messages_omitted:H.Optional(H.Integer({minimum:0})),fallback_messages_truncated:H.Optional(H.Integer({minimum:0})),failure_reason:H.Optional(Y(["circuit_open","context_exhausted","deterministic","empty_exhausted","insufficient_reduction","transient_exhausted"])),memory:H.Optional(QH)}),zJ=L({type:H.Literal("provider_retry"),phase:Y(["scheduled","waiting","attempt","recovered","exhausted"]),attempt:H.Integer({minimum:0}),max_retries:H.Integer({minimum:0}),reason:Y(["rate_limit","server_error","timeout","transport","stream_closed"]),status_code:H.Optional(H.Integer({minimum:100,maximum:599})),delay_ms:H.Optional(H.Integer({minimum:0})),next_retry_at:H.Optional(H.Integer({minimum:0})),mode:H.Optional(Y(["standard","bounded_foreground"])),recovery_budget_ms:H.Optional(H.Integer({minimum:0})),recovery_elapsed_ms:H.Optional(H.Integer({minimum:0})),recovery_remaining_ms:H.Optional(H.Integer({minimum:0})),exhausted_by:H.Optional(Y(["attempt_limit","recovery_budget"]))}),fJ=L({type:H.Literal("provider_admission"),phase:Y(["queued","admitted","rejected"]),request_class:Y(["foreground","background","internal"]),resource:Y(["stream","pending_count","pending_bytes"]),scope:Y(["global","domain","owner","class"]),reason:H.Optional(Y(["capacity","queue_full","wait_timeout","closed"])),queue_position:H.Integer({minimum:0}),queue_depth:H.Integer({minimum:0}),in_flight:H.Integer({minimum:0}),limit:H.Integer({minimum:0}),wait_ms:H.Integer({minimum:0}),max_wait_ms:H.Integer({minimum:0}),recovery_remaining_ms:H.Optional(H.Integer({minimum:0}))}),AJ=L({type:H.Literal("provider_circuit"),phase:Y(["opened","waiting","probe","closed","reopened","rejected"]),reason:Y(["rate_limit","server_error","transport","stream_closed"]),status_code:H.Optional(H.Integer({minimum:100,maximum:599})),retry_after_ms:H.Optional(H.Integer({minimum:0})),next_probe_at:H.Optional(H.Integer({minimum:0})),open_duration_ms:H.Integer({minimum:0}),sample_count:H.Optional(H.Integer({minimum:0})),failure_count:H.Optional(H.Integer({minimum:0})),recovery_remaining_ms:H.Optional(H.Integer({minimum:0}))}),SJ=L({type:H.Literal("provider_stall"),phase:Y(["detected","recovered"]),stall_count:H.Integer({minimum:1}),duration_ms:H.Integer({minimum:0}),warning_after_ms:H.Integer({minimum:1}),timeout_ms:H.Integer({minimum:1}),output_started:H.Boolean()}),u=H.Object({provider:H.String({minLength:1,maxLength:256}),model:H.String({minLength:1,maxLength:256})},{additionalProperties:!1}),DH=H.Union([H.Object({source:Y(["retry","circuit"]),reason:Y(["rate_limit","server_error","timeout","transport","stream_closed"]),status_code:H.Optional(H.Integer({minimum:100,maximum:999}))},{additionalProperties:!1}),H.Object({source:H.Literal("admission"),reason:Y(["queue_full","wait_timeout","closed"])},{additionalProperties:!1}),H.Object({source:H.Literal("stall"),reason:H.Literal("timeout")},{additionalProperties:!1})]),TJ=H.Object({activity:Y(["admission_wait","retry_wait","retry_attempt","circuit_open","circuit_probe","stream_stall","fallback"]),reason:Y(["capacity","queue_full","wait_timeout","admission_closed","rate_limit","server_error","timeout","transport","stream_closed","circuit_open","stream_stall"]),updated_at:H.Integer({minimum:0}),next_action_at:H.Optional(H.Integer({minimum:0})),retry:H.Optional(H.Object({attempt:H.Integer({minimum:0}),max_retries:H.Integer({minimum:0}),status_code:H.Optional(H.Integer({minimum:100,maximum:999})),delay_ms:H.Optional(H.Integer({minimum:0})),recovery_budget_ms:H.Optional(H.Integer({minimum:0})),recovery_elapsed_ms:H.Optional(H.Integer({minimum:0})),recovery_remaining_ms:H.Optional(H.Integer({minimum:0}))},{additionalProperties:!1})),admission:H.Optional(H.Object({request_class:Y(["foreground","background","internal"]),scope:Y(["global","domain","owner","class"]),resource:Y(["stream","pending_count","pending_bytes"]),queue_position:H.Integer({minimum:0}),queue_depth:H.Integer({minimum:0}),in_flight:H.Integer({minimum:0}),limit:H.Integer({minimum:0}),wait_ms:H.Integer({minimum:0}),max_wait_ms:H.Integer({minimum:0}),recovery_remaining_ms:H.Optional(H.Integer({minimum:0}))},{additionalProperties:!1})),circuit:H.Optional(H.Object({phase:Y(["opened","reopened","waiting","probe","rejected"]),status_code:H.Optional(H.Integer({minimum:100,maximum:999})),retry_after_ms:H.Optional(H.Integer({minimum:0})),next_probe_at:H.Optional(H.Integer({minimum:0})),open_duration_ms:H.Integer({minimum:0}),sample_count:H.Optional(H.Integer({minimum:0})),failure_count:H.Optional(H.Integer({minimum:0})),recovery_remaining_ms:H.Optional(H.Integer({minimum:0}))},{additionalProperties:!1})),stall:H.Optional(H.Object({stall_count:H.Integer({minimum:0}),duration_ms:H.Integer({minimum:0}),warning_after_ms:H.Integer({minimum:0}),timeout_ms:H.Integer({minimum:0}),output_started:H.Boolean()},{additionalProperties:!1})),fallback:H.Optional(H.Object({from:u,to:u,candidate:H.Integer({minimum:1}),candidate_count:H.Integer({minimum:1}),trigger:DH},{additionalProperties:!1}))},{additionalProperties:!1}),yJ=H.Object({event_version:H.Literal(k),type:H.Literal("provider_recovery"),generation:H.String({minLength:1,maxLength:128}),revision:H.Integer({minimum:0}),snapshot:H.Union([TJ,H.Null()])},{additionalProperties:!1}),bJ=H.Object({name:H.String({minLength:1,maxLength:128}),kind:H.Optional(Y(["readonly","write","execute"])),started_at:H.Integer({minimum:0}),progress:H.Optional(H.Integer({minimum:0})),total:H.Optional(H.Integer({minimum:0}))},{additionalProperties:!1}),IJ=H.Object({phase:Y(["starting","thinking","responding","executing_tools","compacting","continuing"]),started_at:H.Integer({minimum:0}),updated_at:H.Integer({minimum:0}),turn:H.Integer({minimum:0}),max_turns:H.Union([H.Integer({minimum:0}),H.Null()]),output_started:H.Boolean(),tool_calls_started:H.Integer({minimum:0}),tool_calls_completed:H.Integer({minimum:0}),active_tools:H.Array(bJ,{maxItems:8}),active_tool_overflow:H.Integer({minimum:0})},{additionalProperties:!1}),RJ=H.Object({event_version:H.Literal(k),type:H.Literal("turn_activity"),generation:H.String({minLength:1,maxLength:128}),revision:H.Integer({minimum:0}),snapshot:H.Union([IJ,H.Null()])},{additionalProperties:!1}),gJ=H.Object({event_version:H.Literal(k),type:H.Literal("model_fallback"),from:u,to:u,candidate:H.Integer({minimum:1}),candidate_count:H.Integer({minimum:1}),trigger:DH},{additionalProperties:!1}),kJ=L({type:H.Literal("action_stationarity"),phase:Y(["detected","recovered","halted"]),tool_name:H.String(),run_length:H.Integer({minimum:1}),nudge_threshold:H.Integer({minimum:1}),halt_threshold:H.Integer({minimum:1}),progress_aware:H.Boolean()}),CJ=L({type:H.Literal("turn_recovery"),state:Y(["completed","resumable","requires_attention"]),turn_id:H.String({minLength:1}),input_message_count:H.Integer({minimum:0}),reason:H.Optional(Y(["successful_tool_result","interrupted_tool_call"]))}),hJ=L({type:H.Literal("turn_limit"),turns_count:H.Number(),action:H.Literal("continue")}),OJ=L({type:H.Literal("task_session"),session_id:H.String(),project_path:H.String(),source_project_path:H.String(),isolation:Y(["local","worktree"]),worktree_branch:H.Optional(H.String()),base_commit:H.Optional(H.String())}),wJ=L({type:H.Literal("task_admission"),state:Y(["queued","running"]),queue_position:H.Optional(H.Integer({minimum:1})),queue_depth:H.Integer({minimum:0}),in_flight:H.Integer({minimum:0}),max_concurrent_tasks:H.Integer({minimum:1})}),mJ=L({type:H.Literal("output"),content:H.String(),exit_code:H.Number()}),cJ=L({type:H.Literal("error"),message:H.String()}),NK=YH(H.Union([oH,sH,rH,nH,tH,eH,JJ,KJ,ZJ,$J,qJ,XJ,YJ,BJ,NJ,QJ,DJ,LJ,WJ,jJ,xJ,UJ,_J,GJ,PJ,FJ,EJ,MJ,fJ,AJ,zJ,SJ,yJ,RJ,gJ,kJ,CJ,hJ,OJ,wJ,mJ,cJ]));function LH(V,Z){return{event_version:k,type:V,...Z}}function pJ(V){if(!V||typeof V!=="object"||Array.isArray(V))return;let Z=V;if(Z.auto_backgrounded!==!0||Z.background_reason!=="foreground_budget"||!Number.isSafeInteger(Z.foreground_budget_ms)||Z.foreground_budget_ms<=0||typeof Z.shell_id!=="string"||!/^bash_[A-Za-z0-9-]+$/.test(Z.shell_id)||Z.shell_id.length>128||Z.terminal_transport!=="local"&&Z.terminal_transport!=="acp"||Z.pid!==void 0&&(!Number.isSafeInteger(Z.pid)||Z.pid<=0))return;return{auto_backgrounded:!0,background_reason:"foreground_budget",foreground_budget_ms:Z.foreground_budget_ms,shell_id:Z.shell_id,...Z.pid===void 0?{}:{pid:Z.pid},terminal_transport:Z.terminal_transport}}function vJ(V){let Z=new AbortController,Q=(K)=>{if(!Z.signal.aborted)Z.abort(K)},q=()=>Q("interrupt"),J=()=>Q(V?.signal?.reason);if(V?.signal){if(V.signal.addEventListener("abort",J,{once:!0}),V.signal.aborted)J()}else process.once("SIGINT",q),process.once("SIGTERM",q);return{signal:Z.signal,abort:Q,dispose:()=>{V?.signal?.removeEventListener("abort",J),process.removeListener("SIGINT",q),process.removeListener("SIGTERM",q)}}}var lJ=Y(["text","jsonl"]),aJ=H.Object({headless:H.Optional(H.Boolean()),message:H.Optional(H.String()),_:H.Optional(H.Array(H.Union([H.String(),H.Number()]))),model:H.Optional(H.String()),systemPrompt:H.Optional(H.String()),appendSystemPrompt:H.Optional(H.String()),verificationAgent:H.Optional(H.Boolean()),maxTurns:H.Optional(H.Refine(H.Integer(),(V)=>V===-1||V>0,()=>"must be -1 (unlimited) or a positive integer")),permissionMode:H.Optional(H.Enum(xH)),mcpConfig:H.Optional(H.Array(H.String())),strictMcpConfig:H.Optional(H.Boolean()),sessionId:H.Optional(H.String()),allowedTools:H.Optional(H.Array(H.String())),disallowedTools:H.Optional(H.Array(H.String())),agents:H.Optional(H.String()),continue:H.Optional(H.Boolean()),resume:H.Optional(H.Union([H.String(),H.Boolean()])),forkSession:H.Optional(H.Boolean()),taskIsolation:H.Optional(Y(["local","worktree"])),outputFormat:H.Optional(lJ),jsonSchema:H.Optional(H.String()),outputSchema:H.Optional(H.String())});class mH{openedThinking=!1;wroteAssistantContent=!1;markAssistantContent(){this.wroteAssistantContent=!0}setThinkingOpened(V){this.openedThinking=V}hasOpenThinking(){return this.openedThinking}completeStream(){let V={openedThinking:this.openedThinking,wroteAssistantContent:this.wroteAssistantContent};return this.openedThinking=!1,this.wroteAssistantContent=!1,V}}function iJ(V){return V.issues.map((Z)=>`${Z.path.join(".")||"options"}: ${Z.message}`).join("; ")}function oJ(V){let Z=UH(aJ,V);if(!Z.success)throw Error(`Invalid headless options: ${iJ(Z.error)}`);return Z.data}function sJ(V){return V.command("* [message]","Run full agent loop without Ink UI and print events to the terminal",(Z)=>Z.positional("message",{describe:"Message to process",type:"string"}).option("headless",{type:"boolean",describe:"Run full agent loop without Ink UI and print events to the terminal"}).option("model",{describe:"Model ID for this run",type:"string"}).option("system-prompt",{describe:"Replace the default system prompt",type:"string"}).option("append-system-prompt",{describe:"Append a system prompt to the default system prompt",type:"string"}).option("verification-agent",{describe:"Run the built-in independent verification agent after non-trivial changes",type:"boolean",default:!0}).option("max-turns",{alias:["maxTurns"],describe:"Maximum conversation turns (-1: unlimited, N>0: limit to N turns)",type:"number"}).option("output-format",{alias:["outputFormat"],choices:["text","jsonl"],describe:"Headless output format",type:"string"}).option("json-schema",{alias:["jsonSchema"],describe:"Inline JSON Schema for the structured final response",type:"string"}).option("output-schema",{alias:["outputSchema"],describe:"Path to a JSON Schema file for the structured final response",type:"string"}).option("task-isolation",{alias:["taskIsolation"],choices:["local","worktree"],describe:"Dispatch a new durable task in the selected workspace mode",type:"string"}),async(Z)=>{if(!Z.headless)return;let Q=await JK(Z);process.exit(Q)})}function W(V,Z=""){V.write(`${Z}
1
+ import{p as gH,q as kH,r as CH,s as hH,t as OH,u as wH}from"./chunk-3aavhxe8.js";import{B as RH,C as ZH,D as $H,E as qH,F as a,G as XH}from"./chunk-ajtwwg2b.js";import{H as NH,da as MH,fa as zH,ga as fH,ka as AH}from"./chunk-cvwcrr4h.js";import"./chunk-g01mth5d.js";import"./chunk-nj2bggcj.js";import{ab as QH}from"./chunk-30x3mcsb.js";import{Nb as e,Zb as FH,hc as EH}from"./chunk-y54mge74.js";import"./chunk-zzvs471p.js";import{Sd as GH,Wd as PH,Yd as d,he as t}from"./chunk-za0frk62.js";import"./chunk-53fc0yrq.js";import"./chunk-y5wngtz0.js";import"./chunk-w33zjw8m.js";import{rf as TH}from"./chunk-yk62xvqm.js";import{tf as yH,uf as bH,vf as IH}from"./chunk-46t79ek8.js";import{wf as SH}from"./chunk-nheny8xp.js";import"./chunk-jj4ggb04.js";import{Wf as _H}from"./chunk-syq7j5b0.js";import"./chunk-v508x7cg.js";import"./chunk-t0gm0pn1.js";import"./chunk-1yq72zb7.js";import"./chunk-kqvzmnja.js";import"./chunk-0mr8nexh.js";import"./chunk-50vwafn5.js";import"./chunk-t89f4way.js";import"./chunk-mg03ydep.js";import"./chunk-3kszepm6.js";import{hh as c,lh as BH}from"./chunk-wcps5gjm.js";import"./chunk-vbjgcn49.js";import"./chunk-06hkf59s.js";import"./chunk-sspk1ah8.js";import"./chunk-3y2x6fb6.js";import"./chunk-f194ct93.js";import{Ti as xH}from"./chunk-kv458q06.js";import{Yi as r,Zi as n}from"./chunk-5v0jcyea.js";import{bj as C}from"./chunk-2f8d0km4.js";import"./chunk-ddvdc2p0.js";import{Fj as UH,Hj as H,Ij as YH,Kj as Y}from"./chunk-2mk914vk.js";import"./chunk-j8hbddjp.js";import"./chunk-4cdk4mds.js";import"./chunk-rjbneaq0.js";import"./chunk-rvs364rz.js";import"./chunk-vw9paban.js";import"./chunk-4wx5sya5.js";import"./chunk-eg3ms291.js";import uJ from"yargs";import{hideBin as dJ}from"yargs/helpers";function i(V,Z,Q){if(V.off){V.off(Z,Q);return}V.removeListener?.(Z,Q)}function aH(V,Z){if(!V.once&&!V.on||!V.off&&!V.removeListener)throw Error("Writable returned false without an observable drain contract");return new Promise((Q,q)=>{let J=!1,K=()=>{i(V,"drain",x),i(V,"error",j),Z.removeEventListener("abort",P)},D=(F)=>{if(J)return;J=!0,K(),F()},x=()=>D(Q),j=(F)=>D(()=>q(F??Error("Writable emitted an error"))),P=()=>D(()=>q(Z.reason??Error("Writable drain aborted")));if(Z.aborted){P();return}let T=V.once?.bind(V)??V.on?.bind(V);T?.("drain",x),T?.("error",j),Z.addEventListener("abort",P,{once:!0})})}async function iH(V,Z,Q){if(V.destroyed||V.writableEnded)throw Error("Writable is already closed");if(V.write(Z)===!1)await aH(V,Q)}class o{options;queues;sinkErrorListeners=[];failed=!1;closing=!1;handleAbort=()=>{this.fail(new a("aborted","Headless output was aborted",{cause:this.options.signal?.reason}))};constructor(V,Z={}){this.options=Z;let Q=(q)=>new XH({maxPendingItems:Z.maxPendingItems??ZH,maxPendingBytes:Z.maxPendingBytes??$H,writeTimeoutMs:Z.writeTimeoutMs??qH,sizeOf:(J)=>Buffer.byteLength(J),write:(J,K)=>iH(V[q],J,K),onFailure:(J)=>this.fail(J)});if(this.queues={stdout:Q("stdout"),stderr:Q("stderr")},this.observeSinkErrors(V.stdout),V.stderr!==V.stdout)this.observeSinkErrors(V.stderr);if(Z.signal?.addEventListener("abort",this.handleAbort,{once:!0}),Z.signal?.aborted)this.handleAbort()}write(V,Z){return this.queues[V].offer(Z).accepted}async flush(){await Promise.all([this.queues.stdout.flush(),this.queues.stderr.flush()])}close(V){if(this.closing||this.failed)return;this.closing=!0,this.options.signal?.removeEventListener("abort",this.handleAbort),this.removeSinkErrorListeners(),this.queues.stdout.close(V),this.queues.stderr.close(V)}stats(){return{stdout:this.queues.stdout.stats(),stderr:this.queues.stderr.stats()}}observeSinkErrors(V){if(!V.on||!V.off&&!V.removeListener)return;let Z=(Q)=>{this.fail(new a("write_failed","Headless writable failed",{cause:Q??Error("Writable emitted an error")}))};V.on("error",Z),this.sinkErrorListeners.push({writer:V,listener:Z})}fail(V){if(this.closing||this.failed)return;this.failed=!0,this.options.signal?.removeEventListener("abort",this.handleAbort),this.removeSinkErrorListeners(),this.queues.stdout.close(V),this.queues.stderr.close(V),this.options.onFailure?.(V)}removeSinkErrorListeners(){for(let{writer:V,listener:Z}of this.sinkErrorListeners.splice(0))i(V,"error",Z)}}var k=1;function L(V){return H.Object({event_version:H.Literal(k),...V})}var oH=L({type:H.Literal("content_delta"),delta:H.String()}),sH=L({type:H.Literal("thinking_delta"),delta:H.String()}),rH=L({type:H.Literal("thinking"),content:H.String()}),nH=L({type:H.Literal("stream_end")}),tH=L({type:H.Literal("content"),content:H.String()}),eH=L({type:H.Literal("structured_output"),output:H.Record(H.String(),H.Unknown()),schema_digest:H.String({pattern:"^[a-f0-9]{64}$"})}),s=Y(["readonly","write","execute"]),HJ=H.Object({kind:s,scope:Y(["global","session"]),queue_position:H.Integer({minimum:1}),in_flight:H.Integer({minimum:0}),limit:H.Integer({minimum:1})}),JJ=L({type:H.Literal("tool_start"),tool_name:H.String(),summary:H.String(),target:H.Optional(H.String()),tool_kind:H.Optional(s)}),KJ=L({type:H.Literal("tool_progress"),tool_name:H.String(),message:H.String(),progress:H.Optional(H.Number()),total:H.Optional(H.Number()),admission:H.Optional(HJ)}),VJ=H.Object({auto_backgrounded:H.Literal(!0),background_reason:H.Literal("foreground_budget"),foreground_budget_ms:H.Integer({minimum:1}),shell_id:H.String({minLength:1,maxLength:128,pattern:"^bash_[A-Za-z0-9-]+$"}),pid:H.Optional(H.Integer({minimum:1})),terminal_transport:Y(["local","acp"])}),ZJ=L({type:H.Literal("tool_result"),tool_name:H.String(),summary:H.String(),target:H.Optional(H.String()),tool_kind:H.Optional(s),success:H.Optional(H.Boolean()),error_type:H.Optional(H.String()),error_message:H.Optional(H.String()),background:H.Optional(VJ)}),$J=L({type:H.Literal("mcp_catalog_changed"),revision:H.Integer({minimum:1}),server_name:H.String(),added:H.Array(H.String()),removed:H.Array(H.String()),updated:H.Array(H.String())}),qJ=L({type:H.Literal("mcp_content_changed"),revision:H.Integer({minimum:1}),server_name:H.String(),content_kind:Y(["resources","resource_templates","prompts"]),added:H.Array(H.String()),removed:H.Array(H.String()),updated:H.Array(H.String())}),XJ=L({type:H.Literal("mcp_resource_updated"),revision:H.Integer({minimum:1}),server_name:H.String(),uri:H.String()}),YJ=L({type:H.Literal("mcp_connection_changed"),revision:H.Integer({minimum:1}),server_name:H.String(),phase:Y(["reconnecting","recovered","failed"]),reason:H.String(),attempt:H.Integer({minimum:0}),max_attempts:H.Integer({minimum:0}),next_retry_at:H.Optional(H.Integer({minimum:0})),error:H.Optional(H.String())}),BJ=L({type:H.Literal("mcp_log"),revision:H.Integer({minimum:1}),server_name:H.String(),level:Y(["debug","info","notice","warning","error","critical","alert","emergency"]),logger:H.Optional(H.String()),message:H.String(),projected_bytes:H.Integer({minimum:0}),data_sha256:H.String(),truncated:H.Boolean(),details_omitted:H.Boolean(),timestamp:H.Integer({minimum:0}),synthetic:H.Optional(H.Boolean())}),NJ=L({type:H.Literal("mcp_instructions_changed"),revision:H.Integer({minimum:0}),server_name:H.String(),action:Y(["added","removed"]),reason:Y(["snapshot","connection","disconnection"]),text:H.Optional(H.String()),source_bytes:H.Optional(H.Integer({minimum:0})),projected_bytes:H.Optional(H.Integer({minimum:0})),sha256:H.Optional(H.String()),truncated:H.Optional(H.Boolean()),details_omitted:H.Optional(H.Boolean())}),QJ=L({type:H.Literal("mcp_task_changed"),revision:H.Integer({minimum:0}),task_id:H.String(),server_name:H.String(),tool_name:H.String(),status:Y(["working","input_required","interrupted","completed","failed","cancelled"]),status_message:H.Optional(H.String()),created_at:H.Integer({minimum:0}),updated_at:H.Integer({minimum:0}),completed_at:H.Optional(H.Integer({minimum:0})),has_result:H.Boolean(),error:H.Optional(H.String())}),DJ=L({type:H.Literal("project_rules_loaded"),files:H.Array(H.Object({id:H.String(),relative_path:H.String(),source:Y(["project","local"]),conditional:H.Boolean(),content_sha256:H.String({pattern:"^[a-f0-9]{64}$"})})),trigger_paths:H.Array(H.String()),blocked_write:H.Boolean()}),LJ=L({type:H.Literal("user_shell_started"),execution_id:H.String(),command:H.String(),auxiliary:H.Boolean()}),WJ=L({type:H.Literal("user_shell_output"),execution_id:H.String(),stream:Y(["stdout","stderr"]),chunk:H.String(),stream_truncated:H.Boolean()}),jJ=L({type:H.Literal("user_shell_completed"),execution_id:H.String(),message_id:H.String(),status:Y(["completed","failed","aborted","timed_out","spawn_error"]),exit_code:H.Union([H.Integer(),H.Null()]),duration_ms:H.Number({minimum:0}),stdout:H.String(),stderr:H.String(),truncated:H.Boolean(),auxiliary:H.Boolean()}),xJ=L({type:H.Literal("phase"),phase:Y(["turn","searching","inspecting","target_hit","executing","completed"]),status:Y(["ongoing","hit","done"]),message:H.String(),turn:H.Optional(H.Number()),tool_name:H.Optional(H.String()),target:H.Optional(H.String())}),UJ=L({type:H.Literal("tool_detail"),tool_name:H.String(),detail:H.String()}),_J=L({type:H.Literal("task_update"),tasks:H.Array(NH)}),GJ=L({type:H.Literal("goal_frontier"),goal_id:H.String({minLength:1}),status:Y(["active","verifying","paused","blocked","usage_limited","budget_limited","complete"]),task_list_id:H.String({minLength:1,maxLength:256}),total:H.Integer({minimum:0}),completed:H.Integer({minimum:0}),in_progress:H.Integer({minimum:0}),pending:H.Integer({minimum:0}),blocked:H.Integer({minimum:0}),next_task:H.Optional(H.Object({id:H.String({minLength:1}),subject:H.String({minLength:1,maxLength:512}),priority:Y(["high","medium","low"])})),digest_sha256:H.String({pattern:"^[a-f0-9]{64}$"}),observed_at:H.String(),stall_category:H.Optional(Y(["waiting_dependency","same_task_no_effect","repeated_deferral"])),stall_count:H.Optional(H.Integer({minimum:1,maximum:3}))}),PJ=L({type:H.Literal("goal"),state:Y(["updated","cleared"]),goal_id:H.Optional(H.String()),status:H.Optional(Y(["active","verifying","paused","blocked","usage_limited","budget_limited","complete"])),verification_attempt:H.Optional(H.Integer({minimum:1})),verification_status:H.Optional(Y(["pending","pass","fail","partial"])),verifier_session_id:H.Optional(H.String()),verification_evidence_sha256:H.Optional(H.String({pattern:"^[a-f0-9]{64}$"})),verification_summary:H.Optional(H.String()),verification_stall_count:H.Optional(H.Integer({minimum:1})),premature_stop_pattern:H.Optional(Y(BH)),premature_stop_count:H.Optional(H.Integer({minimum:1})),execution_host_failure_category:H.Optional(Y(["timeout","admission","spawn","finalization","sandbox_start","terminal"])),execution_host_failure_count:H.Optional(H.Integer({minimum:1,maximum:3})),frontier_stall_category:H.Optional(Y(["waiting_dependency","same_task_no_effect","repeated_deferral"])),frontier_stall_count:H.Optional(H.Integer({minimum:1,maximum:3})),root_turn_id:H.Optional(H.String({minLength:1,maxLength:c})),current_turn_id:H.Optional(H.String({minLength:1,maxLength:c})),parent_turn_id:H.Optional(H.String({minLength:1,maxLength:c}))}),FJ=L({type:H.Literal("subagent"),state:Y(["spawned","completed"]),session_id:H.String(),subagent_type:H.Optional(H.String()),success:H.Optional(H.Boolean()),summary:H.Optional(H.String()),verification_verdict:H.Optional(Y(["pass","fail","partial"])),resumed_from:H.Optional(H.String()),root_agent_id:H.Optional(H.String()),resume_depth:H.Optional(H.Integer({minimum:0}))}),EJ=L({type:H.Literal("token_usage"),input_tokens:H.Number(),output_tokens:H.Number(),total_tokens:H.Number(),max_context_tokens:H.Number(),cache_read_tokens:H.Optional(H.Number()),cache_write_tokens:H.Optional(H.Number()),prompt_cache_break:H.Optional(H.Object({reason:Y(["model_changed","system_prompt_changed","tools_changed","request_policy_changed","ttl_expired","server_side"]),previous_cache_read_tokens:H.Number(),cache_read_tokens:H.Number(),cache_write_tokens:H.Number(),token_drop:H.Number(),elapsed_ms:H.Number(),call_number:H.Number(),system_prompt_changed:H.Boolean(),system_char_delta:H.Number(),tools_changed:H.Boolean(),added_tool_count:H.Number(),removed_tool_count:H.Number(),changed_tool_count:H.Number(),model_changed:H.Boolean(),request_policy_changed:H.Boolean()})),cost_usd:H.Optional(H.Number())}),MJ=L({type:H.Literal("compacting"),state:Y(["started","completed"]),reason:H.Optional(Y(["threshold","context_limit","turn_limit","manual"])),strategy:H.Optional(Y(["llm","fallback","snip"])),outcome:H.Optional(Y(["completed","fallback","failed"])),pre_tokens:H.Optional(H.Number({minimum:0})),pre_token_source:H.Optional(Y(["provider","provider_plus_estimate","local_estimate"])),estimated_pending_tokens:H.Optional(H.Number({minimum:0})),post_tokens:H.Optional(H.Number({minimum:0})),sample_attempts:H.Optional(H.Integer({minimum:0})),input_reductions:H.Optional(H.Integer({minimum:0})),messages_omitted:H.Optional(H.Integer({minimum:0})),files_omitted:H.Optional(H.Integer({minimum:0})),images_omitted:H.Optional(H.Integer({minimum:0})),fallback_target_tokens:H.Optional(H.Integer({minimum:0})),fallback_messages_omitted:H.Optional(H.Integer({minimum:0})),fallback_messages_truncated:H.Optional(H.Integer({minimum:0})),failure_reason:H.Optional(Y(["circuit_open","context_exhausted","deterministic","empty_exhausted","insufficient_reduction","transient_exhausted"])),memory:H.Optional(QH)}),zJ=L({type:H.Literal("provider_retry"),phase:Y(["scheduled","waiting","attempt","recovered","exhausted"]),attempt:H.Integer({minimum:0}),max_retries:H.Integer({minimum:0}),reason:Y(["rate_limit","server_error","timeout","transport","stream_closed"]),status_code:H.Optional(H.Integer({minimum:100,maximum:599})),delay_ms:H.Optional(H.Integer({minimum:0})),next_retry_at:H.Optional(H.Integer({minimum:0})),mode:H.Optional(Y(["standard","bounded_foreground"])),recovery_budget_ms:H.Optional(H.Integer({minimum:0})),recovery_elapsed_ms:H.Optional(H.Integer({minimum:0})),recovery_remaining_ms:H.Optional(H.Integer({minimum:0})),exhausted_by:H.Optional(Y(["attempt_limit","recovery_budget"]))}),fJ=L({type:H.Literal("provider_admission"),phase:Y(["queued","admitted","rejected"]),request_class:Y(["foreground","background","internal"]),resource:Y(["stream","pending_count","pending_bytes"]),scope:Y(["global","domain","owner","class"]),reason:H.Optional(Y(["capacity","queue_full","wait_timeout","closed"])),queue_position:H.Integer({minimum:0}),queue_depth:H.Integer({minimum:0}),in_flight:H.Integer({minimum:0}),limit:H.Integer({minimum:0}),wait_ms:H.Integer({minimum:0}),max_wait_ms:H.Integer({minimum:0}),recovery_remaining_ms:H.Optional(H.Integer({minimum:0}))}),AJ=L({type:H.Literal("provider_circuit"),phase:Y(["opened","waiting","probe","closed","reopened","rejected"]),reason:Y(["rate_limit","server_error","transport","stream_closed"]),status_code:H.Optional(H.Integer({minimum:100,maximum:599})),retry_after_ms:H.Optional(H.Integer({minimum:0})),next_probe_at:H.Optional(H.Integer({minimum:0})),open_duration_ms:H.Integer({minimum:0}),sample_count:H.Optional(H.Integer({minimum:0})),failure_count:H.Optional(H.Integer({minimum:0})),recovery_remaining_ms:H.Optional(H.Integer({minimum:0}))}),SJ=L({type:H.Literal("provider_stall"),phase:Y(["detected","recovered"]),stall_count:H.Integer({minimum:1}),duration_ms:H.Integer({minimum:0}),warning_after_ms:H.Integer({minimum:1}),timeout_ms:H.Integer({minimum:1}),output_started:H.Boolean()}),u=H.Object({provider:H.String({minLength:1,maxLength:256}),model:H.String({minLength:1,maxLength:256})},{additionalProperties:!1}),DH=H.Union([H.Object({source:Y(["retry","circuit"]),reason:Y(["rate_limit","server_error","timeout","transport","stream_closed"]),status_code:H.Optional(H.Integer({minimum:100,maximum:999}))},{additionalProperties:!1}),H.Object({source:H.Literal("admission"),reason:Y(["queue_full","wait_timeout","closed"])},{additionalProperties:!1}),H.Object({source:H.Literal("stall"),reason:H.Literal("timeout")},{additionalProperties:!1})]),TJ=H.Object({activity:Y(["admission_wait","retry_wait","retry_attempt","circuit_open","circuit_probe","stream_stall","fallback"]),reason:Y(["capacity","queue_full","wait_timeout","admission_closed","rate_limit","server_error","timeout","transport","stream_closed","circuit_open","stream_stall"]),updated_at:H.Integer({minimum:0}),next_action_at:H.Optional(H.Integer({minimum:0})),retry:H.Optional(H.Object({attempt:H.Integer({minimum:0}),max_retries:H.Integer({minimum:0}),status_code:H.Optional(H.Integer({minimum:100,maximum:999})),delay_ms:H.Optional(H.Integer({minimum:0})),recovery_budget_ms:H.Optional(H.Integer({minimum:0})),recovery_elapsed_ms:H.Optional(H.Integer({minimum:0})),recovery_remaining_ms:H.Optional(H.Integer({minimum:0}))},{additionalProperties:!1})),admission:H.Optional(H.Object({request_class:Y(["foreground","background","internal"]),scope:Y(["global","domain","owner","class"]),resource:Y(["stream","pending_count","pending_bytes"]),queue_position:H.Integer({minimum:0}),queue_depth:H.Integer({minimum:0}),in_flight:H.Integer({minimum:0}),limit:H.Integer({minimum:0}),wait_ms:H.Integer({minimum:0}),max_wait_ms:H.Integer({minimum:0}),recovery_remaining_ms:H.Optional(H.Integer({minimum:0}))},{additionalProperties:!1})),circuit:H.Optional(H.Object({phase:Y(["opened","reopened","waiting","probe","rejected"]),status_code:H.Optional(H.Integer({minimum:100,maximum:999})),retry_after_ms:H.Optional(H.Integer({minimum:0})),next_probe_at:H.Optional(H.Integer({minimum:0})),open_duration_ms:H.Integer({minimum:0}),sample_count:H.Optional(H.Integer({minimum:0})),failure_count:H.Optional(H.Integer({minimum:0})),recovery_remaining_ms:H.Optional(H.Integer({minimum:0}))},{additionalProperties:!1})),stall:H.Optional(H.Object({stall_count:H.Integer({minimum:0}),duration_ms:H.Integer({minimum:0}),warning_after_ms:H.Integer({minimum:0}),timeout_ms:H.Integer({minimum:0}),output_started:H.Boolean()},{additionalProperties:!1})),fallback:H.Optional(H.Object({from:u,to:u,candidate:H.Integer({minimum:1}),candidate_count:H.Integer({minimum:1}),trigger:DH},{additionalProperties:!1}))},{additionalProperties:!1}),yJ=H.Object({event_version:H.Literal(k),type:H.Literal("provider_recovery"),generation:H.String({minLength:1,maxLength:128}),revision:H.Integer({minimum:0}),snapshot:H.Union([TJ,H.Null()])},{additionalProperties:!1}),bJ=H.Object({name:H.String({minLength:1,maxLength:128}),kind:H.Optional(Y(["readonly","write","execute"])),started_at:H.Integer({minimum:0}),progress:H.Optional(H.Integer({minimum:0})),total:H.Optional(H.Integer({minimum:0}))},{additionalProperties:!1}),IJ=H.Object({phase:Y(["starting","thinking","responding","executing_tools","compacting","continuing"]),started_at:H.Integer({minimum:0}),updated_at:H.Integer({minimum:0}),turn:H.Integer({minimum:0}),max_turns:H.Union([H.Integer({minimum:0}),H.Null()]),output_started:H.Boolean(),tool_calls_started:H.Integer({minimum:0}),tool_calls_completed:H.Integer({minimum:0}),active_tools:H.Array(bJ,{maxItems:8}),active_tool_overflow:H.Integer({minimum:0})},{additionalProperties:!1}),RJ=H.Object({event_version:H.Literal(k),type:H.Literal("turn_activity"),generation:H.String({minLength:1,maxLength:128}),revision:H.Integer({minimum:0}),snapshot:H.Union([IJ,H.Null()])},{additionalProperties:!1}),gJ=H.Object({event_version:H.Literal(k),type:H.Literal("model_fallback"),from:u,to:u,candidate:H.Integer({minimum:1}),candidate_count:H.Integer({minimum:1}),trigger:DH},{additionalProperties:!1}),kJ=L({type:H.Literal("action_stationarity"),phase:Y(["detected","recovered","halted"]),tool_name:H.String(),run_length:H.Integer({minimum:1}),nudge_threshold:H.Integer({minimum:1}),halt_threshold:H.Integer({minimum:1}),progress_aware:H.Boolean()}),CJ=L({type:H.Literal("turn_recovery"),state:Y(["completed","resumable","requires_attention"]),turn_id:H.String({minLength:1}),input_message_count:H.Integer({minimum:0}),reason:H.Optional(Y(["successful_tool_result","interrupted_tool_call"]))}),hJ=L({type:H.Literal("turn_limit"),turns_count:H.Number(),action:H.Literal("continue")}),OJ=L({type:H.Literal("task_session"),session_id:H.String(),project_path:H.String(),source_project_path:H.String(),isolation:Y(["local","worktree"]),worktree_branch:H.Optional(H.String()),base_commit:H.Optional(H.String())}),wJ=L({type:H.Literal("task_admission"),state:Y(["queued","running"]),queue_position:H.Optional(H.Integer({minimum:1})),queue_depth:H.Integer({minimum:0}),in_flight:H.Integer({minimum:0}),max_concurrent_tasks:H.Integer({minimum:1})}),mJ=L({type:H.Literal("output"),content:H.String(),exit_code:H.Number()}),cJ=L({type:H.Literal("error"),message:H.String()}),NK=YH(H.Union([oH,sH,rH,nH,tH,eH,JJ,KJ,ZJ,$J,qJ,XJ,YJ,BJ,NJ,QJ,DJ,LJ,WJ,jJ,xJ,UJ,_J,GJ,PJ,FJ,EJ,MJ,fJ,AJ,zJ,SJ,yJ,RJ,gJ,kJ,CJ,hJ,OJ,wJ,mJ,cJ]));function LH(V,Z){return{event_version:k,type:V,...Z}}function pJ(V){if(!V||typeof V!=="object"||Array.isArray(V))return;let Z=V;if(Z.auto_backgrounded!==!0||Z.background_reason!=="foreground_budget"||!Number.isSafeInteger(Z.foreground_budget_ms)||Z.foreground_budget_ms<=0||typeof Z.shell_id!=="string"||!/^bash_[A-Za-z0-9-]+$/.test(Z.shell_id)||Z.shell_id.length>128||Z.terminal_transport!=="local"&&Z.terminal_transport!=="acp"||Z.pid!==void 0&&(!Number.isSafeInteger(Z.pid)||Z.pid<=0))return;return{auto_backgrounded:!0,background_reason:"foreground_budget",foreground_budget_ms:Z.foreground_budget_ms,shell_id:Z.shell_id,...Z.pid===void 0?{}:{pid:Z.pid},terminal_transport:Z.terminal_transport}}function vJ(V){let Z=new AbortController,Q=(K)=>{if(!Z.signal.aborted)Z.abort(K)},q=()=>Q("interrupt"),J=()=>Q(V?.signal?.reason);if(V?.signal){if(V.signal.addEventListener("abort",J,{once:!0}),V.signal.aborted)J()}else process.once("SIGINT",q),process.once("SIGTERM",q);return{signal:Z.signal,abort:Q,dispose:()=>{V?.signal?.removeEventListener("abort",J),process.removeListener("SIGINT",q),process.removeListener("SIGTERM",q)}}}var lJ=Y(["text","jsonl"]),aJ=H.Object({headless:H.Optional(H.Boolean()),message:H.Optional(H.String()),_:H.Optional(H.Array(H.Union([H.String(),H.Number()]))),model:H.Optional(H.String()),systemPrompt:H.Optional(H.String()),appendSystemPrompt:H.Optional(H.String()),verificationAgent:H.Optional(H.Boolean()),maxTurns:H.Optional(H.Refine(H.Integer(),(V)=>V===-1||V>0,()=>"must be -1 (unlimited) or a positive integer")),permissionMode:H.Optional(H.Enum(xH)),mcpConfig:H.Optional(H.Array(H.String())),strictMcpConfig:H.Optional(H.Boolean()),sessionId:H.Optional(H.String()),allowedTools:H.Optional(H.Array(H.String())),disallowedTools:H.Optional(H.Array(H.String())),agents:H.Optional(H.String()),continue:H.Optional(H.Boolean()),resume:H.Optional(H.Union([H.String(),H.Boolean()])),forkSession:H.Optional(H.Boolean()),taskIsolation:H.Optional(Y(["local","worktree"])),outputFormat:H.Optional(lJ),jsonSchema:H.Optional(H.String()),outputSchema:H.Optional(H.String())});class mH{openedThinking=!1;wroteAssistantContent=!1;markAssistantContent(){this.wroteAssistantContent=!0}setThinkingOpened(V){this.openedThinking=V}hasOpenThinking(){return this.openedThinking}completeStream(){let V={openedThinking:this.openedThinking,wroteAssistantContent:this.wroteAssistantContent};return this.openedThinking=!1,this.wroteAssistantContent=!1,V}}function iJ(V){return V.issues.map((Z)=>`${Z.path.join(".")||"options"}: ${Z.message}`).join("; ")}function oJ(V){let Z=UH(aJ,V);if(!Z.success)throw Error(`Invalid headless options: ${iJ(Z.error)}`);return Z.data}function sJ(V){return V.command("* [message]","Run full agent loop without Ink UI and print events to the terminal",(Z)=>Z.positional("message",{describe:"Message to process",type:"string"}).option("headless",{type:"boolean",describe:"Run full agent loop without Ink UI and print events to the terminal"}).option("model",{describe:"Model ID for this run",type:"string"}).option("system-prompt",{describe:"Replace the default system prompt",type:"string"}).option("append-system-prompt",{describe:"Append a system prompt to the default system prompt",type:"string"}).option("verification-agent",{describe:"Run the built-in independent verification agent after non-trivial changes",type:"boolean",default:!0}).option("max-turns",{alias:["maxTurns"],describe:"Maximum conversation turns (-1: unlimited, N>0: limit to N turns)",type:"number"}).option("output-format",{alias:["outputFormat"],choices:["text","jsonl"],describe:"Headless output format",type:"string"}).option("json-schema",{alias:["jsonSchema"],describe:"Inline JSON Schema for the structured final response",type:"string"}).option("output-schema",{alias:["outputSchema"],describe:"Path to a JSON Schema file for the structured final response",type:"string"}).option("task-isolation",{alias:["taskIsolation"],choices:["local","worktree"],describe:"Dispatch a new durable task in the selected workspace mode",type:"string"}),async(Z)=>{if(!Z.headless)return;let Q=await JK(Z);process.exit(Q)})}function W(V,Z=""){V.write(`${Z}
2
2
  `)}function rJ(V){return`[task] [${V.status}] ${V.subject}`}function nJ(){return{requestConfirmation:async(V)=>V.type==="mcpElicitation"?{approved:!1,reason:"headless-mcp-elicitation-unavailable",elicitation:{action:"cancel"}}:V.type==="mcpSampling"?{approved:!1,reason:"headless-mcp-sampling-unavailable"}:{approved:!0,reason:"headless-auto-approved",scope:"session"}}}function tJ(V){if(!(V instanceof Error))return"Unknown error";let q=V.lastError??V;if(q.responseBody)try{let D=JSON.parse(q.responseBody)?.error?.message;if(D)return q.statusCode?`${D} (HTTP ${q.statusCode})`:D}catch{}let J=V.message.match(/Last error:\s*(.+)$/);if(J)return J[1];return V.message}function eJ(V){return V==="jsonl"?"jsonl":"text"}function WH(V,Z){let Q=(...q)=>{for(let J of q){let K=Z[J];if(typeof K==="string"&&K.trim()!=="")return K}return};switch(V){case"Read":case"Edit":case"Write":case"UndoEdit":return Q("file_path");case"ApplyPatch":return"multi-file patch";case"NotebookEdit":return Q("notebook_path");case"Grep":return Q("path","pattern");case"Glob":return Q("pattern");case"WebFetch":return Q("url");case"WebSearch":return Q("query");case"Bash":return Q("command","description");case"Task":return Q("description");case"LSP":return Q("filePath","operation");case"EnterWorktree":return Q("name");case"ExitWorktree":return Q("action");default:return}}function HK(V,Z,Q,q){let J=new Set(["Glob","Grep","WebSearch","LS"]),K=new Set(["Read","WebFetch"]);if(new Set(["Edit","Write","ApplyPatch","NotebookEdit","Bash","LSP","UndoEdit","EnterWorktree","ExitWorktree"]).has(V)&&!q.targetLocked)return{phase:"target_hit",status:"hit",message:`Target locked: ${Z}`,shouldLockTarget:!0};if(q.targetLocked)return{phase:"executing",status:"hit",message:Q?`Working within target: ${Z}`:`Executing: ${Z}`,shouldLockTarget:!1};if(J.has(V))return{phase:"searching",status:"ongoing",message:`Still searching: ${Z}`,shouldLockTarget:!1};if(K.has(V))return{phase:"inspecting",status:"ongoing",message:`Inspecting candidate: ${Z}`,shouldLockTarget:!1};return{phase:"executing",status:q.targetLocked?"hit":"ongoing",message:`Executing: ${Z}`,shouldLockTarget:!1}}function jH(V,Z,Q=!1){let q=(J,K)=>{V.stdout.write(`${JSON.stringify(LH(J,K))}
3
3
  `)};return{contentDelta(J){if(Z==="jsonl"){q("content_delta",{delta:J});return}if(Q)return;V.stdout.write(J)},thinkingDelta(J,K){if(Z==="jsonl")return q("thinking_delta",{delta:J}),K;if(!K)V.stderr.write("[thinking] ");return V.stderr.write(J),!0},thinking(J){if(Z==="jsonl"){q("thinking",{content:J});return}W(V.stderr,`[thinking] ${J}`)},streamEnd(J,K){if(Z==="jsonl"){q("stream_end",{});return}if(K)V.stderr.write(`
4
4
  `);if(J)V.stdout.write(`
@@ -1,3 +1,3 @@
1
- import{Qj as N,Tj as M}from"./chunk-9kj19a8t.js";import{ek as H}from"./chunk-7xtxvrh8.js";import{createModels as _,createProvider as Y,envApiKeyAuth as x,getSupportedThinkingLevels as E}from"@earendil-works/pi-ai";import{anthropicMessagesApi as F}from"@earendil-works/pi-ai/api/anthropic-messages.lazy";import{openAICompletionsApi as U}from"@earendil-works/pi-ai/api/openai-completions.lazy";import{builtinProviders as P}from"@earendil-works/pi-ai/providers/all";var K=/^[a-z][a-z0-9._-]{0,63}$/,z=/^[A-Z_][A-Z0-9_]*$/,s=new Set(["openai-completions","anthropic-messages"]);function B(u){return typeof u==="string"&&s.has(u)}function X(u,$){let h=`modelProviders.${u}`,b=[];if(!K.test(u))b.push(`${h}: id must match ${K.source}`);if(!$.name?.trim())b.push(`${h}: name must not be empty`);if(!B($.wireApi))b.push(`${h}: wireApi must be openai-completions or anthropic-messages`);try{let w=new URL($.baseUrl);if(!["http:","https:"].includes(w.protocol))b.push(`${h}: baseUrl must be an absolute HTTP(S) URL`)}catch{b.push(`${h}: baseUrl must be an absolute HTTP(S) URL`)}if($.apiKeyEnv!==void 0&&!z.test($.apiKeyEnv))b.push(`${h}: apiKeyEnv must be a valid environment variable name`);if("apiKey"in $)b.push(`${h}: API keys must be stored separately in auth.json`);return b}function J(u,$){let h=$.trim().replace(/\/+$/,"");if(u==="anthropic-messages"&&/\/v1$/i.test(h))return h.slice(0,-3);return h}import{promises as Z}from"node:fs";import j from"node:path";import{Mutex as R}from"async-mutex";import T from"write-file-atomic";class Q{filePath;mutex=new R;constructor(u=j.join(H(),"auth.json")){this.filePath=u}async read(u){return(await this.readAll())[u]}async list(){let u=await this.readAll();return Object.entries(u).map(([$,h])=>({providerId:$,type:h.type}))}async modify(u,$){return this.mutex.runExclusive(async()=>{let h=await this.readAll(),b=h[u],w=await $(b);if(w===void 0)return b;return h[u]=w,await this.writeAll(h),w})}async delete(u){await this.mutex.runExclusive(async()=>{let $=await this.readAll();if(!(u in $))return;delete $[u],await this.writeAll($)})}async readAll(){try{let u=await Z.readFile(this.filePath,"utf8"),$=JSON.parse(u);return $&&typeof $==="object"&&!Array.isArray($)?$:{}}catch(u){if(u.code==="ENOENT")return{};throw u}}async writeAll(u){let $=j.dirname(this.filePath);await Z.mkdir($,{recursive:!0,mode:448}),await Z.chmod($,448),await T(this.filePath,`${JSON.stringify(u,null,2)}
1
+ import{Rj as N,Uj as M}from"./chunk-4cdk4mds.js";import{fk as H}from"./chunk-4wx5sya5.js";import{createModels as _,createProvider as Y,envApiKeyAuth as x,getSupportedThinkingLevels as E}from"@earendil-works/pi-ai";import{anthropicMessagesApi as F}from"@earendil-works/pi-ai/api/anthropic-messages.lazy";import{openAICompletionsApi as U}from"@earendil-works/pi-ai/api/openai-completions.lazy";import{builtinProviders as P}from"@earendil-works/pi-ai/providers/all";var K=/^[a-z][a-z0-9._-]{0,63}$/,z=/^[A-Z_][A-Z0-9_]*$/,s=new Set(["openai-completions","anthropic-messages"]);function B(u){return typeof u==="string"&&s.has(u)}function X(u,$){let h=`modelProviders.${u}`,b=[];if(!K.test(u))b.push(`${h}: id must match ${K.source}`);if(!$.name?.trim())b.push(`${h}: name must not be empty`);if(!B($.wireApi))b.push(`${h}: wireApi must be openai-completions or anthropic-messages`);try{let w=new URL($.baseUrl);if(!["http:","https:"].includes(w.protocol))b.push(`${h}: baseUrl must be an absolute HTTP(S) URL`)}catch{b.push(`${h}: baseUrl must be an absolute HTTP(S) URL`)}if($.apiKeyEnv!==void 0&&!z.test($.apiKeyEnv))b.push(`${h}: apiKeyEnv must be a valid environment variable name`);if("apiKey"in $)b.push(`${h}: API keys must be stored separately in auth.json`);return b}function J(u,$){let h=$.trim().replace(/\/+$/,"");if(u==="anthropic-messages"&&/\/v1$/i.test(h))return h.slice(0,-3);return h}import{promises as Z}from"node:fs";import j from"node:path";import{Mutex as R}from"async-mutex";import T from"write-file-atomic";class Q{filePath;mutex=new R;constructor(u=j.join(H(),"auth.json")){this.filePath=u}async read(u){return(await this.readAll())[u]}async list(){let u=await this.readAll();return Object.entries(u).map(([$,h])=>({providerId:$,type:h.type}))}async modify(u,$){return this.mutex.runExclusive(async()=>{let h=await this.readAll(),b=h[u],w=await $(b);if(w===void 0)return b;return h[u]=w,await this.writeAll(h),w})}async delete(u){await this.mutex.runExclusive(async()=>{let $=await this.readAll();if(!(u in $))return;delete $[u],await this.writeAll($)})}async readAll(){try{let u=await Z.readFile(this.filePath,"utf8"),$=JSON.parse(u);return $&&typeof $==="object"&&!Array.isArray($)?$:{}}catch(u){if(u.code==="ENOENT")return{};throw u}}async writeAll(u){let $=j.dirname(this.filePath);await Z.mkdir($,{recursive:!0,mode:448}),await Z.chmod($,448),await T(this.filePath,`${JSON.stringify(u,null,2)}
2
2
  `,{mode:384}),await Z.chmod(this.filePath,384)}}var q="openai-compatible",G="anthropic-compatible",D="https://api.openai.com/v1",V="https://api.anthropic.com",A=128000,C=32768,t={input:0,output:0,cacheRead:0,cacheWrite:0},f=["openai","anthropic","deepseek","google","moonshotai","moonshotai-cn","zai","zai-coding-cn"];class L{credentials;models;compatibleModels=new Map;anthropicCompatibleModels=new Map;customProviderConfigs=new Map;customProviderModels=new Map;reservedProviderIds=new Set;constructor(u=new Q){this.credentials=u,this.models=_({credentials:u});for(let $ of P())this.models.setProvider($);this.installOpenAICompatibleProvider(),this.installAnthropicCompatibleProvider();for(let $ of this.models.getProviders())this.reservedProviderIds.add($.id)}async listProviders(){return Promise.all(this.models.getProviders().map(async(u)=>{let $=u.getModels(),h=this.customProviderConfigs.get(u.id),b=this.getFactoryWireApi(u.id);return{id:u.id,name:u.name,modelCount:$.length,defaultBaseUrl:u.baseUrl??$[0]?.baseUrl,supportsApiKey:Boolean(u.auth.apiKey),supportsOAuth:Boolean(u.auth.oauth),configured:b?!1:Boolean(await this.models.checkAuth(u.id)),custom:Boolean(h),factoryWireApi:b,wireApi:h?.wireApi,apiKeyEnv:h?.apiKeyEnv}}))}listModels(u){return this.models.getModels(u).map(($)=>this.toCatalogEntry($))}getModel(u,$){let h=this.models.getModel(u,$);if(!h&&u===q)this.registerOpenAICompatibleModel($),h=this.models.getModel(u,$);if(!h&&u===G)this.registerAnthropicCompatibleModel($),h=this.models.getModel(u,$);if(!h&&this.customProviderConfigs.has(u))this.registerCustomProviderModel(u,$),h=this.models.getModel(u,$);if(!h)throw Error(`Unknown pi-ai model: ${u}/${$}`);return h}resolveConfig(u){let $=this.getModel(u.provider,u.model),h=u.overrides;return{...$,...h?.baseUrl?{baseUrl:J($.api,h.baseUrl)}:{},...h?.maxOutputTokens?{maxTokens:h.maxOutputTokens}:{}}}async setApiKey(u,$){this.requireProvider(u),await this.credentials.modify(u,async()=>({type:"api_key",key:$}))}async clearCredential(u){this.requireProvider(u),await this.credentials.delete(u)}async isConfigured(u){return this.requireProvider(u),Boolean(await this.models.checkAuth(u))}isReservedProviderId(u){return this.reservedProviderIds.has(u)}configureModelProviders(u,$){for(let h of this.customProviderConfigs.keys())this.models.deleteProvider(h);this.customProviderConfigs.clear(),this.customProviderModels.clear();for(let[h,b]of Object.entries(u)){let w=$.filter((k)=>k.provider===h).map((k)=>k.model);this.registerModelProvider(h,b,w)}}registerModelProvider(u,$,h=[]){if(this.isReservedProviderId(u))throw Error(`modelProviders.${u}: built-in provider ids cannot be overridden`);let b=X(u,$);if(b.length>0)throw Error(b.join("; "));let w={...$,name:$.name.trim(),baseUrl:J($.wireApi,$.baseUrl),...$.apiKeyEnv?{apiKeyEnv:$.apiKeyEnv.trim()}:{}};this.customProviderConfigs.set(u,w);let k=new Map;for(let y of new Set(h)){let W=y.trim();if(!W)continue;k.set(W,this.createCompatibleModel(u,W,w.wireApi,w.baseUrl))}this.customProviderModels.set(u,k),this.installCustomProvider(u)}unregisterModelProvider(u){if(!this.customProviderConfigs.has(u))return;this.customProviderConfigs.delete(u),this.customProviderModels.delete(u),this.models.deleteProvider(u)}requireProvider(u){if(!this.models.getProvider(u))throw Error(`Unknown pi-ai provider: ${u}`)}registerOpenAICompatibleModel(u){let $=u.trim();if(!$)throw Error("OpenAI-compatible model ID must not be empty");if(this.compatibleModels.has($))return;let h=this.createCompatibleModel(q,$,"openai-completions",D);this.compatibleModels.set($,h),this.installOpenAICompatibleProvider()}registerAnthropicCompatibleModel(u){let $=u.trim();if(!$)throw Error("Anthropic-compatible model ID must not be empty");if(this.anthropicCompatibleModels.has($))return;let h=this.createCompatibleModel(G,$,"anthropic-messages",V);this.anthropicCompatibleModels.set($,h),this.installAnthropicCompatibleProvider()}registerCustomProviderModel(u,$){let h=$.trim();if(!h)throw Error("Custom provider model ID must not be empty");let b=this.customProviderConfigs.get(u),w=this.customProviderModels.get(u);if(!b||!w||w.has(h))return;w.set(h,this.createCompatibleModel(u,h,b.wireApi,b.baseUrl)),this.installCustomProvider(u)}createCompatibleModel(u,$,h,b){let w=this.models.getModels().filter((y)=>y.provider!==u&&!this.customProviderConfigs.has(y.provider)&&y.id===$),k=f.flatMap((y)=>w.filter((W)=>W.provider===y))[0]??w[0];return{id:$,name:k?.name??$,api:h,provider:u,baseUrl:b,reasoning:k?.reasoning??!1,input:k?[...k.input]:["text"],cost:{...t},contextWindow:k?.contextWindow??A,maxTokens:k?.maxTokens??C,...k?.thinkingLevelMap?{thinkingLevelMap:{...k.thinkingLevelMap}}:{}}}installOpenAICompatibleProvider(){this.models.setProvider(Y({id:q,name:"Custom OpenAI Endpoint",baseUrl:D,auth:{apiKey:x("OpenAI-compatible API key",["OPENAI_COMPATIBLE_API_KEY","BLADE_API_KEY"])},models:[...this.compatibleModels.values()],api:U()}))}installAnthropicCompatibleProvider(){this.models.setProvider(Y({id:G,name:"Custom Anthropic Endpoint",baseUrl:V,auth:{apiKey:x("Anthropic-compatible API key",["ANTHROPIC_API_KEY","BLADE_API_KEY"])},models:[...this.anthropicCompatibleModels.values()],api:F()}))}installCustomProvider(u){let $=this.customProviderConfigs.get(u),h=this.customProviderModels.get(u);if(!$||!h)return;let b=$.apiKeyEnv?[$.apiKeyEnv]:[];this.models.setProvider(Y({id:u,name:$.name,baseUrl:$.baseUrl,auth:{apiKey:x(`${$.name} API key`,b)},models:[...h.values()],api:$.wireApi==="anthropic-messages"?F():U()}))}getFactoryWireApi(u){if(u===q)return"openai-completions";if(u===G)return"anthropic-messages";return}toCatalogEntry(u){return{id:u.id,name:u.name,provider:u.provider,api:u.api,baseUrl:u.baseUrl,reasoning:u.reasoning,supportedReasoningEfforts:E(u),supportedServiceTiers:M(u),supportedResponseVerbosities:N(u),input:[...u.input],contextWindow:u.contextWindow,maxTokens:u.maxTokens,cost:{...u.cost}}}}var S;function hu(){return S??=new L,S}
3
- export{K as Kj,X as Lj,J as Mj,L as Nj,hu as Oj};
3
+ export{K as Lj,X as Mj,J as Nj,L as Oj,hu as Pj};
@@ -0,0 +1 @@
1
+ import{$b as h,Qb as a,Rb as b,Tb as c,Xb as d,Yb as e,Zb as f,_b as g,ac as i,bc as j,cc as k,kc as l,lc as m,mc as n,nc as o,pc as p,qc as q,rc as r}from"./chunk-y54mge74.js";import"./chunk-zzvs471p.js";import"./chunk-za0frk62.js";import"./chunk-53fc0yrq.js";import"./chunk-y5wngtz0.js";import"./chunk-w33zjw8m.js";import"./chunk-t0gm0pn1.js";import"./chunk-1yq72zb7.js";import"./chunk-kqvzmnja.js";import"./chunk-50vwafn5.js";import"./chunk-3kszepm6.js";import"./chunk-wcps5gjm.js";import"./chunk-vbjgcn49.js";import"./chunk-sspk1ah8.js";import"./chunk-3y2x6fb6.js";import"./chunk-kv458q06.js";import"./chunk-5v0jcyea.js";import"./chunk-2f8d0km4.js";import"./chunk-ddvdc2p0.js";import"./chunk-2mk914vk.js";import"./chunk-j8hbddjp.js";import"./chunk-4cdk4mds.js";import"./chunk-rjbneaq0.js";import"./chunk-vw9paban.js";import"./chunk-4wx5sya5.js";import"./chunk-eg3ms291.js";export{g as saveUserMessage,i as saveToolUse,j as saveToolResult,k as saveCompaction,h as saveAssistantMessage,d as isRootSystemPrompt,m as handleTaskListUpdate,n as handleSkillActivation,o as extractModelSwitch,r as executeLoopGenerator,f as drainLoop,c as checkStopHook,a as checkOutputRecovery,b as checkIncompleteIntent,q as checkAndCompactInLoop,p as applyToolDomainEffects,l as StreamingToolExecutor,e as ConversationState};
@@ -1,4 +1,4 @@
1
- import{Zi as L,aj as _}from"./chunk-jsv3e4k6.js";import{execSync as F}from"child_process";import{existsSync as Q,readFileSync as O,realpathSync as b}from"fs";import*as V from"os";import*as H from"path";import{basename as J,isAbsolute as j,resolve as R}from"path";function G(z=_()){let q=z,M=f(q);return{workingDirectory:q,projectRoot:M,platform:`${V.platform()} (${V.arch()})`,nodeVersion:process.version,currentDate:new Date().toISOString().split("T")[0],homeDirectory:V.homedir()}}function Y(z,q){try{return F(q,{cwd:z,encoding:"utf8",stdio:["pipe","pipe","ignore"]}).trim()}catch{return null}}function v(z={}){let{includeGitSnapshot:q=!0,includeDirectoryListing:M=!0,workingDirectory:W}=z,B=G(W),$=Q(H.join(B.projectRoot,".git")),T=J(process.env.SHELL||"unknown"),A=["package.json","tsconfig.json","BLADE.md",".env.example"].filter((K)=>Q(H.join(B.projectRoot,K))).map((K)=>`- \`${H.join(B.projectRoot,K)}\``),N=`# Environment
1
+ import{_i as L,bj as _}from"./chunk-2f8d0km4.js";import{execSync as F}from"child_process";import{existsSync as Q,readFileSync as O,realpathSync as b}from"fs";import*as V from"os";import*as H from"path";import{basename as J,isAbsolute as j,resolve as R}from"path";function G(z=_()){let q=z,M=f(q);return{workingDirectory:q,projectRoot:M,platform:`${V.platform()} (${V.arch()})`,nodeVersion:process.version,currentDate:new Date().toISOString().split("T")[0],homeDirectory:V.homedir()}}function Y(z,q){try{return F(q,{cwd:z,encoding:"utf8",stdio:["pipe","pipe","ignore"]}).trim()}catch{return null}}function v(z={}){let{includeGitSnapshot:q=!0,includeDirectoryListing:M=!0,workingDirectory:W}=z,B=G(W),$=Q(H.join(B.projectRoot,".git")),T=J(process.env.SHELL||"unknown"),A=["package.json","tsconfig.json","BLADE.md",".env.example"].filter((K)=>Q(H.join(B.projectRoot,K))).map((K)=>`- \`${H.join(B.projectRoot,K)}\``),N=`# Environment
2
2
  You have been invoked in the following environment:
3
3
  - Primary working directory: ${B.workingDirectory}
4
4
  - Is a git repository: ${$?"true":"false"}
@@ -25,4 +25,4 @@ ${I.join(`
25
25
 
26
26
  Project root directory listing:
27
27
  ${K}`}return N}function f(z){let q=z,M=null;while(q!==H.dirname(q)){if(Q(H.join(q,".git")))return q;if(Q(H.join(q,".blade")))return q;if(Q(H.join(q,".claude")))return q;if(!M&&Q(H.join(q,"package.json")))M=q;q=H.dirname(q)}return M??z}function x(z,q){let M=j(z)?z:R(q||process.cwd(),z),W;try{W=b(M)}catch{W=M}L(W)}
28
- export{v as Af,f as Bf,x as Cf};
28
+ export{v as Bf,f as Cf,x as Df};
@@ -1,2 +1,2 @@
1
- import{Gj as b,Hj as K,Jj as j}from"./chunk-5q4z0sfr.js";var L=256,Z=128,p=1e6,$=86400000,G=8640000000000000,g=b.Integer({minimum:0,maximum:p}),f=b.Integer({minimum:0,maximum:$}),q=b.Integer({minimum:0,maximum:G}),x=b.String({minLength:1,maxLength:L,pattern:"^(?!.*://)[^\x00-\x1F]+$"}),H=j(["capacity","queue_full","wait_timeout","admission_closed","rate_limit","server_error","timeout","transport","stream_closed","circuit_open","stream_stall"]),U=j(["admission_wait","retry_wait","retry_attempt","circuit_open","circuit_probe","stream_stall","fallback"]),F=b.Object({provider:x,model:x},{additionalProperties:!1}),J=j(["rate_limit","server_error","timeout","transport","stream_closed"]),s=b.Union([b.Object({source:b.Literal("retry"),reason:J,statusCode:b.Optional(b.Integer({minimum:100,maximum:999}))},{additionalProperties:!1}),b.Object({source:b.Literal("circuit"),reason:J,statusCode:b.Optional(b.Integer({minimum:100,maximum:999}))},{additionalProperties:!1}),b.Object({source:b.Literal("admission"),reason:j(["queue_full","wait_timeout","closed"])},{additionalProperties:!1}),b.Object({source:b.Literal("stall"),reason:b.Literal("timeout")},{additionalProperties:!1})]),T=b.Object({from:F,to:F,candidate:b.Integer({minimum:1,maximum:p}),candidateCount:b.Integer({minimum:1,maximum:p}),trigger:s},{additionalProperties:!1}),X=b.Object({attempt:g,maxRetries:g,statusCode:b.Optional(b.Integer({minimum:100,maximum:999})),delayMs:b.Optional(f),recoveryBudgetMs:b.Optional(f),recoveryElapsedMs:b.Optional(f),recoveryRemainingMs:b.Optional(f)},{additionalProperties:!1}),Y=b.Object({requestClass:j(["foreground","background","internal"]),scope:j(["global","domain","owner","class"]),resource:j(["stream","pending_count","pending_bytes"]),queuePosition:g,queueDepth:g,inFlight:g,limit:g,waitMs:f,maxWaitMs:f,recoveryRemainingMs:b.Optional(f)},{additionalProperties:!1}),z=b.Object({phase:j(["opened","reopened","waiting","probe","rejected"]),statusCode:b.Optional(b.Integer({minimum:100,maximum:999})),retryAfterMs:b.Optional(f),nextProbeAt:b.Optional(q),openDurationMs:f,sampleCount:b.Optional(g),failureCount:b.Optional(g),recoveryRemainingMs:b.Optional(f)},{additionalProperties:!1}),C=b.Object({stallCount:g,durationMs:f,warningAfterMs:f,timeoutMs:f,outputStarted:b.Boolean()},{additionalProperties:!1}),I=b.Object({activity:U,reason:H,updatedAt:q,nextActionAt:b.Optional(q),retry:b.Optional(X),admission:b.Optional(Y),circuit:b.Optional(z),stall:b.Optional(C),fallback:b.Optional(T)},{additionalProperties:!1}),N=K(b.Object({version:b.Literal(1),generation:b.String({minLength:1,maxLength:Z,pattern:"^[^\x00-\x1F]+$"}),revision:g,snapshot:b.Union([I,b.Null()])},{additionalProperties:!1}));function V(Q){let k=[...Q].filter((W)=>{let w=W.codePointAt(0)??0;return w>31&&w!==127}).join("").trim().slice(0,L);if(!k)throw Error("Provider recovery identity is empty");if(k.includes("://"))throw Error("Provider recovery identity cannot be a URL");return k}
2
- export{N as pg,V as qg};
1
+ import{Hj as b,Ij as K,Kj as j}from"./chunk-2mk914vk.js";var L=256,Z=128,p=1e6,$=86400000,G=8640000000000000,g=b.Integer({minimum:0,maximum:p}),f=b.Integer({minimum:0,maximum:$}),q=b.Integer({minimum:0,maximum:G}),x=b.String({minLength:1,maxLength:L,pattern:"^(?!.*://)[^\x00-\x1F]+$"}),H=j(["capacity","queue_full","wait_timeout","admission_closed","rate_limit","server_error","timeout","transport","stream_closed","circuit_open","stream_stall"]),U=j(["admission_wait","retry_wait","retry_attempt","circuit_open","circuit_probe","stream_stall","fallback"]),F=b.Object({provider:x,model:x},{additionalProperties:!1}),J=j(["rate_limit","server_error","timeout","transport","stream_closed"]),s=b.Union([b.Object({source:b.Literal("retry"),reason:J,statusCode:b.Optional(b.Integer({minimum:100,maximum:999}))},{additionalProperties:!1}),b.Object({source:b.Literal("circuit"),reason:J,statusCode:b.Optional(b.Integer({minimum:100,maximum:999}))},{additionalProperties:!1}),b.Object({source:b.Literal("admission"),reason:j(["queue_full","wait_timeout","closed"])},{additionalProperties:!1}),b.Object({source:b.Literal("stall"),reason:b.Literal("timeout")},{additionalProperties:!1})]),T=b.Object({from:F,to:F,candidate:b.Integer({minimum:1,maximum:p}),candidateCount:b.Integer({minimum:1,maximum:p}),trigger:s},{additionalProperties:!1}),X=b.Object({attempt:g,maxRetries:g,statusCode:b.Optional(b.Integer({minimum:100,maximum:999})),delayMs:b.Optional(f),recoveryBudgetMs:b.Optional(f),recoveryElapsedMs:b.Optional(f),recoveryRemainingMs:b.Optional(f)},{additionalProperties:!1}),Y=b.Object({requestClass:j(["foreground","background","internal"]),scope:j(["global","domain","owner","class"]),resource:j(["stream","pending_count","pending_bytes"]),queuePosition:g,queueDepth:g,inFlight:g,limit:g,waitMs:f,maxWaitMs:f,recoveryRemainingMs:b.Optional(f)},{additionalProperties:!1}),z=b.Object({phase:j(["opened","reopened","waiting","probe","rejected"]),statusCode:b.Optional(b.Integer({minimum:100,maximum:999})),retryAfterMs:b.Optional(f),nextProbeAt:b.Optional(q),openDurationMs:f,sampleCount:b.Optional(g),failureCount:b.Optional(g),recoveryRemainingMs:b.Optional(f)},{additionalProperties:!1}),C=b.Object({stallCount:g,durationMs:f,warningAfterMs:f,timeoutMs:f,outputStarted:b.Boolean()},{additionalProperties:!1}),I=b.Object({activity:U,reason:H,updatedAt:q,nextActionAt:b.Optional(q),retry:b.Optional(X),admission:b.Optional(Y),circuit:b.Optional(z),stall:b.Optional(C),fallback:b.Optional(T)},{additionalProperties:!1}),N=K(b.Object({version:b.Literal(1),generation:b.String({minLength:1,maxLength:Z,pattern:"^[^\x00-\x1F]+$"}),revision:g,snapshot:b.Union([I,b.Null()])},{additionalProperties:!1}));function V(Q){let k=[...Q].filter((W)=>{let w=W.codePointAt(0)??0;return w>31&&w!==127}).join("").trim().slice(0,L);if(!k)throw Error("Provider recovery identity is empty");if(k.includes("://"))throw Error("Provider recovery identity cannot be a URL");return k}
2
+ export{N as qg,V as rg};
@@ -1,2 +1,2 @@
1
1
  var F;((D)=>{D.DEFAULT="default";D.AUTO_EDIT="autoEdit";D.YOLO="yolo";D.PLAN="plan"})(F||={});import{Mutex as G}from"async-mutex";class H{entries=new Map;async runExclusive(C,E){let B=this.entries.get(C);if(!B)B={mutex:new G,operations:0},this.entries.set(C,B);B.operations++;try{return await B.mutex.runExclusive(E)}finally{if(B.operations--,B.operations===0&&this.entries.get(C)===B)this.entries.delete(C)}}getStats(){let C=0;for(let E of this.entries.values())C+=E.operations;return{keys:this.entries.size,operations:C}}}
2
- export{F as Si,H as Ti};
2
+ export{F as Ti,H as Ui};
@@ -1 +1 @@
1
- import{Ea as h,Ga as f,Ha as k}from"./chunk-zrgfvc4k.js";import"./chunk-sdapqhj0.js";var p={command:"status",describe:"Check the pinned Playwright Chromium installation",handler:async()=>{let c=await f();if(console.log(`Playwright: ${c.playwrightVersion}`),console.log(`Chromium executable: ${c.executablePath}`),!c.installed){console.error(`Chromium: unavailable (${c.error??"unknown error"})`),console.error(`Install with: ${h}`),process.exitCode=1;return}console.log(`Chromium: ${c.browserVersion}`),console.log("Status: ready")}},q={command:"install",describe:"Install Chromium for the pinned Playwright runtime",handler:async()=>{try{await k();let c=await f();if(!c.installed)throw Error(c.error??"Chromium is not runnable after installation");console.log(`Chromium installed: Playwright ${c.playwrightVersion}, ${c.browserVersion}`)}catch(c){console.error(`Browser installation failed: ${c instanceof Error?c.message:String(c)}`),process.exitCode=1}}},x={command:"browser",describe:"Manage the native Browser Tool runtime",builder:(c)=>c.command(p).command(q).demandCommand(1).strict(),handler:()=>{return}};export{p as browserStatusCommand,q as browserInstallCommand,x as browserCommands};
1
+ import{Fa as h,Ha as f,Ia as k}from"./chunk-g01mth5d.js";import"./chunk-eg3ms291.js";var p={command:"status",describe:"Check the pinned Playwright Chromium installation",handler:async()=>{let c=await f();if(console.log(`Playwright: ${c.playwrightVersion}`),console.log(`Chromium executable: ${c.executablePath}`),!c.installed){console.error(`Chromium: unavailable (${c.error??"unknown error"})`),console.error(`Install with: ${h}`),process.exitCode=1;return}console.log(`Chromium: ${c.browserVersion}`),console.log("Status: ready")}},q={command:"install",describe:"Install Chromium for the pinned Playwright runtime",handler:async()=>{try{await k();let c=await f();if(!c.installed)throw Error(c.error??"Chromium is not runnable after installation");console.log(`Chromium installed: Playwright ${c.playwrightVersion}, ${c.browserVersion}`)}catch(c){console.error(`Browser installation failed: ${c instanceof Error?c.message:String(c)}`),process.exitCode=1}}},x={command:"browser",describe:"Manage the native Browser Tool runtime",builder:(c)=>c.command(p).command(q).demandCommand(1).strict(),handler:()=>{return}};export{p as browserStatusCommand,q as browserInstallCommand,x as browserCommands};
@@ -1,4 +1,4 @@
1
- import{ah as j1,bh as K0,ch as F1}from"./chunk-ewwrss2w.js";import{ih as w0}from"./chunk-53vh6vpt.js";import{rh as YO,sh as L1}from"./chunk-hv8nt7wj.js";import{vh as I1}from"./chunk-erhaedch.js";import{wh as B0,yh as $0}from"./chunk-g7pwwxvz.js";import{Li as S0,Mi as $O,Qi as I0}from"./chunk-5xnht5vw.js";import{aj as B}from"./chunk-jsv3e4k6.js";import{Cj as P,Dj as j,Ej as p,Gj as q,Jj as k1}from"./chunk-5q4z0sfr.js";import{Wj as k0}from"./chunk-fhsvz4b1.js";import{bk as D}from"./chunk-gm2yfq3r.js";import{yk as t1}from"./chunk-7xtxvrh8.js";import T0 from"node:path";import QO from"node:path";import C0 from"node:fs";import L0 from"node:os";import w from"node:path";import RO from"yaml";var G1=2000,W1=50,Y1=1000,O4={type:"object",properties:{verdict:{type:"string",enum:["pass","fail","partial"]},summary:{type:"string",minLength:1,maxLength:G1},findings:{type:"array",maxItems:W1,items:{type:"string",minLength:1,maxLength:Y1}}},required:["verdict","summary","findings"],additionalProperties:!1};function q1(O,$){let Q=O.trim().replaceAll(/\s+/g," ");if($)Q=Q.replaceAll($,".");return Q.replace(/\bBearer\s+[^\s"'`]+/gi,"Bearer [redacted]").replace(/\bsk-[A-Za-z0-9_-]{8,}\b/g,"[redacted-key]").replace(/\b(api(?:[_-]?|\s+)key|access(?:[_-]?|\s+)token|authorization|cookie|password|passwd|refresh(?:[_-]?|\s+)token|secret|session(?:[_-]?|\s+)token)\b(\s*[:=]\s*)([^\s,;]+)/gi,"$1$2[redacted]")}function NO(O){if(O.length<=w0)return O;let $=" [verification feedback truncated]",Q=O.slice(0,w0-$.length);if(/[\uD800-\uDBFF]$/.test(Q))Q=Q.slice(0,-1);return Q.trimEnd()+$}function X1(O){if(!O||typeof O!=="object"||Array.isArray(O))return;let $=O;if($.verdict!=="pass"&&$.verdict!=="fail"&&$.verdict!=="partial"||typeof $.summary!=="string"||!$.summary.trim()||$.summary.length>G1||!Array.isArray($.findings)||$.findings.length>W1||!$.findings.every((Q)=>typeof Q==="string"&&Q.trim().length>0&&Q.length<=Y1))return;return{verdict:$.verdict,summary:$.summary.trim(),findings:$.findings.map((Q)=>Q.trim())}}function $4(O,$){let Q=X1(O);if(!Q)return;let Z=q1(Q.summary,$),J=Q.findings.map((L)=>q1(L,$));return NO([Z,J.length>0?`Findings:
1
+ import{bh as j1,ch as K0,dh as F1}from"./chunk-3kszepm6.js";import{jh as w0}from"./chunk-wcps5gjm.js";import{sh as YO,th as L1}from"./chunk-vbjgcn49.js";import{wh as I1}from"./chunk-06hkf59s.js";import{xh as B0,zh as $0}from"./chunk-sspk1ah8.js";import{Mi as S0,Ni as $O,Ri as I0}from"./chunk-f194ct93.js";import{bj as B}from"./chunk-2f8d0km4.js";import{Dj as P,Ej as j,Fj as p,Hj as q,Kj as k1}from"./chunk-2mk914vk.js";import{Xj as k0}from"./chunk-rjbneaq0.js";import{ck as D}from"./chunk-rvs364rz.js";import{zk as t1}from"./chunk-4wx5sya5.js";import T0 from"node:path";import QO from"node:path";import C0 from"node:fs";import L0 from"node:os";import w from"node:path";import RO from"yaml";var G1=2000,W1=50,Y1=1000,O4={type:"object",properties:{verdict:{type:"string",enum:["pass","fail","partial"]},summary:{type:"string",minLength:1,maxLength:G1},findings:{type:"array",maxItems:W1,items:{type:"string",minLength:1,maxLength:Y1}}},required:["verdict","summary","findings"],additionalProperties:!1};function q1(O,$){let Q=O.trim().replaceAll(/\s+/g," ");if($)Q=Q.replaceAll($,".");return Q.replace(/\bBearer\s+[^\s"'`]+/gi,"Bearer [redacted]").replace(/\bsk-[A-Za-z0-9_-]{8,}\b/g,"[redacted-key]").replace(/\b(api(?:[_-]?|\s+)key|access(?:[_-]?|\s+)token|authorization|cookie|password|passwd|refresh(?:[_-]?|\s+)token|secret|session(?:[_-]?|\s+)token)\b(\s*[:=]\s*)([^\s,;]+)/gi,"$1$2[redacted]")}function NO(O){if(O.length<=w0)return O;let $=" [verification feedback truncated]",Q=O.slice(0,w0-$.length);if(/[\uD800-\uDBFF]$/.test(Q))Q=Q.slice(0,-1);return Q.trimEnd()+$}function X1(O){if(!O||typeof O!=="object"||Array.isArray(O))return;let $=O;if($.verdict!=="pass"&&$.verdict!=="fail"&&$.verdict!=="partial"||typeof $.summary!=="string"||!$.summary.trim()||$.summary.length>G1||!Array.isArray($.findings)||$.findings.length>W1||!$.findings.every((Q)=>typeof Q==="string"&&Q.trim().length>0&&Q.length<=Y1))return;return{verdict:$.verdict,summary:$.summary.trim(),findings:$.findings.map((Q)=>Q.trim())}}function $4(O,$){let Q=X1(O);if(!Q)return;let Z=q1(Q.summary,$),J=Q.findings.map((L)=>q1(L,$));return NO([Z,J.length>0?`Findings:
2
2
  ${J.map((L)=>`- ${L}`).join(`
3
3
  `)}`:""].filter(Boolean).join(`
4
4
 
@@ -730,4 +730,4 @@ ${Z.join(`
730
730
  </${Q}>`:"";return{content:L,files:[...O],references:O.map(c$),triggerPaths:[...$],contentBytes:Buffer.byteLength(L,"utf8"),provenanceSha256:x0(O.map((K)=>`${K.id}:${K.contentSha256}`).join(`
731
731
  `))}}function jO(O,$){let Q=$,Z=[];for(let J=O.length-1;J>=0;J-=1){let L=O[J];if(!L)continue;let K=Buffer.byteLength(L.content,"utf8");if(K>Q)continue;Z.push(L),Q-=K}return Z.reverse()}class h{projectRoot;catalogSha256;definitions;byId;constructor(O,$=[]){this.projectRoot=O;this.projectRoot=O1(O),this.definitions=Object.freeze([...$].sort(Q1).map((Q)=>Object.freeze({...Q}))),this.byId=new Map(this.definitions.map((Q)=>[Q.id,Q])),this.catalogSha256=x0(this.definitions.map((Q)=>`${Q.id}:${Q.contentSha256}`).join(`
732
732
  `))}static empty(O){return new h(O)}list(){return this.definitions.map((O)=>({id:O.id,relativePath:O.relativePath,source:O.source,kind:O.kind,conditional:O.conditional,contentSha256:O.contentSha256}))}snapshot(){return new h(this.projectRoot,this.definitions.map((O)=>({...O,patterns:O.patterns?[...O.patterns]:void 0})))}staticRules(O,$=y$){if(this.definitions.length===0)return Q0([],[],"project-instructions");let Q=this.relativeSourcePath(O),Z=this.definitions.filter((J)=>!J.conditional&&$1(J.scopeDirectory,Q));return Q0(jO(Z,$),[],"project-instructions")}contextualRules(O,$,Q,Z=h$){if(this.definitions.length===0)return Q0([],[],"contextual-project-instructions");let J=this.relativeSourcePath(O),L=[...new Set($.map((G)=>Z1(I.relative(this.projectRoot,O1(G)))).filter(J1))].sort(),K=new Map;for(let G of L)for(let Y of this.definitions){if(Q.has(Y.id))continue;if(!$1(Y.scopeDirectory,G))continue;if(Y.conditional){let X=I.posix.relative(Y.scopeDirectory||".",G);if(!Y.patterns?.some((H)=>IO(H,{dot:!0})(X)))continue}else if($1(Y.scopeDirectory,J))continue;K.set(Y.id,Y)}let W=jO([...K.values()].sort(Q1),Z);return Q0(W,L,"contextual-project-instructions")}hydrate(O){let $=O.map((Q)=>{let Z=this.byId.get(Q.id);if(!Z||Z.contentSha256!==Q.contentSha256||Z.relativePath!==Q.relativePath||Z.source!==Q.source)throw Error(`Project rule provenance mismatch: ${Q.relativePath}`);return Z});return Q0([...new Map($.map((Q)=>[Q.id,Q])).values()].sort(Q1),[],"contextual-project-instructions")}relativeSourcePath(O){let $=Z1(I.relative(this.projectRoot,O1(O)));if($&&!J1($))throw Error("Project instruction source is outside the catalog root");return $}}async function l$(O,$){let Q=await f.lstat($);if(!Q.isFile()||Q.isSymbolicLink())throw Error("Project rule must be a regular file");if(Q.size>FO)throw Error(`Project rule exceeds ${FO} bytes`);let Z=await f.realpath($),J=Z1(I.relative(O,Z));if(!J1(J))throw Error("Project rule escapes its repository root");let L=await f.readFile(Z,"utf8");if(BO(L))throw Error("Project rule contains hidden control characters");let K=R$(L),W=K.content.trim();if(!W)throw Error("Project rule content must not be empty");let G=g$(K.data.paths),Y=u$(J),X=x0(JSON.stringify({relativePath:J,patterns:G??[],content:W}));return{id:`${Y.source}:${x0(J).slice(0,20)}`,relativePath:J,source:Y.source,kind:Y.kind,scopeDirectory:Y.scopeDirectory,priority:Y.priority,conditional:Boolean(G),...G?{patterns:G}:{},content:W,contentSha256:X}}async function MO(O,$){let Q=d$(O);if(!$.projectTrusted)return h.empty(Q);let Z=await f.realpath(Q),J=v$.stream([...m$],{cwd:Z,absolute:!0,dot:!0,deep:f$,onlyFiles:!0,followSymbolicLinks:!1,unique:!0,ignore:[...p$]}),L=[];for await(let Y of J)if(L.push(Y.toString()),L.length>UO)throw Error(`Project rule catalog exceeds ${UO} files`);L.sort();let K=new Set(L.filter((Y)=>I.basename(Y)==="AGENTS.override.md").map((Y)=>I.dirname(Y))),W=[],G=0;for(let Y of L){if(I.basename(Y)==="AGENTS.md"&&K.has(I.dirname(Y)))continue;try{let X=await l$(Z,Y);if(G+=Buffer.byteLength(X.content,"utf8"),G>HO)throw Error(`Project rule catalog exceeds ${HO} bytes`);W.push(X)}catch(X){P$.warn(`[ProjectRules] Ignoring rule: ${X instanceof Error?X.message:String(X)}`)}}return new h(Z,W)}var zO=32,_0=64;class bO extends Error{capacity=_0;constructor(){super(`Workspace agent resource capacity is full (${_0})`);this.name="WorkspaceAgentResourceCapacityError"}}var b=new Map,K1=0,AO=[];async function s$(O){let $=await D.getInstance().getStatus(O.workspaceRoot);O.communicationStyles=await e0(O.workspaceRoot,{projectTrusted:$.state==="trusted",plugins:O.plugins.getActive()})}function n$(O){let $={...O};for(let Q of Object.values(B0))$[Q]=(O[Q]??[]).map((Z)=>({...Z,matcher:Z.matcher?{...Z.matcher}:void 0,hooks:Z.hooks.map((J)=>({...J}))}));return $}function u2(O){AO=[...new Set(O.map(($)=>T0.resolve($)))]}function xO(O,$){JO(O,$.plugins),x.releaseInstance(O,$.subagents),R.releaseInstance({cwd:O},$.skills),z.releaseInstance(O,$.commands),T.releaseInstance(O,$.plugins)}function _O(O){xO(O.workspaceRoot,O)}function Z0(){while(b.size>zO){let O=!1;for(let[$,Q]of b){if(!Q.resources||Q.users>0)continue;if(b.get($)!==Q)continue;b.delete($),_O(Q.resources),O=!0;break}if(!O)return}}function i$(O){setImmediate(()=>{O.users=Math.max(0,O.users-1),Z0()}).unref?.()}async function o$(O,$){let Q=await D.getInstance().getStatus(O),Z=s(O),J=m({cwd:O}),L=z.getInstance(O),K=e(O);try{if(Z.getAllNames().length===0)Z.loadFromStandardLocations(Q.state==="trusted");await Promise.all([J.initialize(),L.isInitialized()?void 0:L.initialize(O),K.isInitialized()?void 0:K.initialize(O,[...$.cliPluginDirs??AO])]),M0(O),await t0(O);let W=await e0(O,{projectTrusted:Q.state==="trusted",plugins:K.getActive()}),G=await MO(O,{projectTrusted:Q.state==="trusted"});return{workspaceRoot:O,subagents:Z,skills:J,commands:L,plugins:K,communicationStyles:W,projectRules:G}}catch(W){throw xO(O,{subagents:Z,skills:J,commands:L,plugins:K}),W}}function a$(O,$){let Q={generation:K1,users:0};return Q.promise=o$(O,$).then((Z)=>{if(Q.generation!==K1||b.get(O)!==Q)return _O(Z),Z;return Q.resources=Z,Z0(),Z},(Z)=>{if(b.get(O)===Q)b.delete(O);throw Z}),b.set(O,Q),Q}async function TO(O,$){let Q=T0.resolve(O),Z=b.get(Q);if(!Z){if(Z0(),b.size>=_0)throw new bO;Z=a$(Q,$)}else b.delete(Q),b.set(Q,Z);Z.users++;let J;try{J=await Z.promise}catch(L){throw Z.users=Math.max(0,Z.users-1),Z0(),L}return{entry:Z,resources:J}}async function DO(O,$){if(!$)return;M0(O.workspaceRoot),await t0(O.workspaceRoot),await s$(O)}async function c2(O,$={}){let Q=await TO(O,$);try{return await DO(Q.resources,$.reconcilePlugins),Q.resources}finally{i$(Q.entry)}}async function l2(O,$,Q={}){let Z=await TO(O,Q);try{return await DO(Z.resources,Q.reconcilePlugins),await $(Z.resources)}finally{Z.entry.users=Math.max(0,Z.entry.users-1),Z0()}}function s2(){let O=0,$=0;for(let Q of b.values()){if(Q.resources)O++;$+=Q.users}return{capacity:zO,activeCapacity:_0,entries:b.size,initialized:O,inFlight:b.size-O,activeUsers:$}}function n2(O){let $="projectRoot"in O?O.projectRoot:O.workspaceRoot;return{projectRoot:T0.resolve($),subagents:O.subagents.snapshot(),skills:O.skills.snapshot(),commands:O.commands.snapshot(),communicationStyles:O.communicationStyles?.snapshot()??L1.snapshot(),projectRules:O.projectRules?.snapshot()??h.empty($),hooks:n$("hooks"in O&&O.hooks?O.hooks:$0.getInstance().getConfig($))}}function i2(O){let $=T0.resolve(O);return{projectRoot:$,subagents:new x,skills:new R,commands:z.empty($),hooks:{enabled:!1},communicationStyles:L1.snapshot(),projectRules:h.empty($)}}function o2(){K1++;for(let[O,$]of b)if($.resources)M0(O);b.clear(),x.resetInstances(),R.resetInstance(),z.resetInstance(),T.resetInstance()}
733
- export{O4 as Ag,$4 as Bg,Q4 as Cg,H1 as Dg,q4 as Eg,G4 as Fg,s as Gg,x4 as Hg,m as Ig,z as Jg,s0 as Kg,j0 as Lg,T as Mg,e as Ng,t0 as Og,M0 as Pg,h as Qg,zO as Rg,_0 as Sg,bO as Tg,s$ as Ug,u2 as Vg,c2 as Wg,l2 as Xg,s2 as Yg,n2 as Zg,i2 as _g,o2 as $g};
733
+ export{O4 as Bg,$4 as Cg,Q4 as Dg,H1 as Eg,q4 as Fg,G4 as Gg,s as Hg,x4 as Ig,m as Jg,z as Kg,s0 as Lg,j0 as Mg,T as Ng,e as Og,t0 as Pg,M0 as Qg,h as Rg,zO as Sg,_0 as Tg,bO as Ug,s$ as Vg,u2 as Wg,c2 as Xg,l2 as Yg,s2 as Zg,n2 as _g,i2 as $g,o2 as ah};
@@ -1,4 +1,4 @@
1
- import"./chunk-v508x7cg.js";import{Qi as Q}from"./chunk-5xnht5vw.js";import"./chunk-sd9bze9x.js";import"./chunk-514va7ce.js";import{aj as L}from"./chunk-jsv3e4k6.js";import"./chunk-n34qsnks.js";import"./chunk-5q4z0sfr.js";import"./chunk-0b67y4j1.js";import"./chunk-9kj19a8t.js";import"./chunk-fhsvz4b1.js";import"./chunk-gm2yfq3r.js";import"./chunk-n9819k4p.js";import"./chunk-7xtxvrh8.js";import{Lk as F}from"./chunk-sdapqhj0.js";var K=[22,19,0];function T(G){let A=/^v?(\d+)\.(\d+)\.(\d+)/.exec(G);if(!A)return!1;let H=A.slice(1).map(Number);for(let z=0;z<K.length;z++){let B=H[z]??0,J=K[z];if(B!==J)return B>J}return!0}var X={command:"doctor",describe:"Check the health of your Blade installation",builder:(G)=>G.option("rebuild-index",{type:"boolean",default:!1,describe:"Rebuild the SQLite session index from JSONL transcripts"}),handler:async(G)=>{if(G.rebuildIndex){console.log(`Rebuilding session index from JSONL transcripts...
2
- `);try{let{rebuildProjectionIndex:z}=await import("./chunk-42y6ks44.js"),{SessionService:B}=await import("./chunk-wsa7g7vd.js"),J=await z(B.projectionDeriverForSearch());if(J===null)console.log("[WARN] Session index unavailable (SQLite driver missing); reads fall back to JSONL scan.");else console.log(`[OK] Session index rebuilt: ${J} session(s) indexed.`)}catch(z){console.log("[FAIL] Session index rebuild failed"),console.log(` Error: ${z instanceof Error?z.message:"未知错误"}`),process.exit(1)}return}console.log(`Running Blade health check...
1
+ import"./chunk-v508x7cg.js";import{Ri as Q}from"./chunk-f194ct93.js";import"./chunk-kv458q06.js";import"./chunk-5v0jcyea.js";import{bj as L}from"./chunk-2f8d0km4.js";import"./chunk-ddvdc2p0.js";import"./chunk-2mk914vk.js";import"./chunk-j8hbddjp.js";import"./chunk-4cdk4mds.js";import"./chunk-rjbneaq0.js";import"./chunk-rvs364rz.js";import"./chunk-vw9paban.js";import"./chunk-4wx5sya5.js";import{Mk as F}from"./chunk-eg3ms291.js";var K=[22,19,0];function T(G){let A=/^v?(\d+)\.(\d+)\.(\d+)/.exec(G);if(!A)return!1;let H=A.slice(1).map(Number);for(let z=0;z<K.length;z++){let B=H[z]??0,J=K[z];if(B!==J)return B>J}return!0}var X={command:"doctor",describe:"Check the health of your Blade installation",builder:(G)=>G.option("rebuild-index",{type:"boolean",default:!1,describe:"Rebuild the SQLite session index from JSONL transcripts"}),handler:async(G)=>{if(G.rebuildIndex){console.log(`Rebuilding session index from JSONL transcripts...
2
+ `);try{let{rebuildProjectionIndex:z}=await import("./chunk-d420fs8m.js"),{SessionService:B}=await import("./chunk-4k7gvnth.js"),J=await z(B.projectionDeriverForSearch());if(J===null)console.log("[WARN] Session index unavailable (SQLite driver missing); reads fall back to JSONL scan.");else console.log(`[OK] Session index rebuilt: ${J} session(s) indexed.`)}catch(z){console.log("[FAIL] Session index rebuild failed"),console.log(` Error: ${z instanceof Error?z.message:"未知错误"}`),process.exit(1)}return}console.log(`Running Blade health check...
3
3
  `);let A=0;try{await Q.getInstance().initialize(),console.log("[OK] Configuration: OK")}catch(z){console.log("[FAIL] Configuration: FAILED"),console.log(` Error: ${z instanceof Error?z.message:"未知错误"}`),A++}let H=process.version;if(T(H))console.log(`[OK] Node.js version: ${H}`);else console.log(`[WARN] Node.js version: ${H} (required: >=22.19.0)`),A++;try{let z=await import("fs/promises"),B=L();await z.access(B,(await import("fs")).constants.R_OK|(await import("fs")).constants.W_OK),console.log("[OK] File system permissions: OK")}catch(z){console.log("[FAIL] File system permissions: FAILED"),console.log(" Error: Cannot read/write in current directory"),A++}try{await import("ink"),console.log("[OK] Dependencies: OK")}catch(z){console.log("[FAIL] Dependencies: FAILED"),console.log(" Error: Missing required dependencies"),A++}if(console.log(`
4
4
  Health Check Summary:`),A===0)console.log("All checks passed! Blade is ready to use.");else console.log(`Warning: Found ${A} issue(s). Please resolve them for optimal performance.`),process.exit(1)}};export{T as isSupportedNodeVersion,X as doctorCommands};
@@ -0,0 +1 @@
1
+ import{pg as a}from"./chunk-1yq72zb7.js";import"./chunk-kqvzmnja.js";import"./chunk-ddvdc2p0.js";import"./chunk-2mk914vk.js";import"./chunk-j8hbddjp.js";import"./chunk-4cdk4mds.js";import"./chunk-4wx5sya5.js";import"./chunk-eg3ms291.js";export{a as createChatServiceAsync};
@@ -0,0 +1,10 @@
1
+ import{a as T,b as W,c as X,d as Y}from"./chunk-0aya8d61.js";import"./chunk-wbr9fc4k.js";import"./chunk-zj1g4nbq.js";import"./chunk-hjrc4jdm.js";import"./chunk-9cb1hv2z.js";import"./chunk-ajtwwg2b.js";import"./chunk-cvwcrr4h.js";import"./chunk-g01mth5d.js";import"./chunk-nj2bggcj.js";import"./chunk-30x3mcsb.js";import"./chunk-y54mge74.js";import"./chunk-zzvs471p.js";import"./chunk-za0frk62.js";import"./chunk-53fc0yrq.js";import"./chunk-y5wngtz0.js";import"./chunk-w33zjw8m.js";import{yf as R}from"./chunk-qjbn97e2.js";import"./chunk-jj4ggb04.js";import{Uf as Q}from"./chunk-syq7j5b0.js";import"./chunk-v508x7cg.js";import"./chunk-t0gm0pn1.js";import"./chunk-1yq72zb7.js";import"./chunk-kqvzmnja.js";import"./chunk-0mr8nexh.js";import"./chunk-50vwafn5.js";import"./chunk-t89f4way.js";import"./chunk-mg03ydep.js";import"./chunk-3kszepm6.js";import"./chunk-wcps5gjm.js";import"./chunk-vbjgcn49.js";import"./chunk-06hkf59s.js";import"./chunk-sspk1ah8.js";import"./chunk-3y2x6fb6.js";import"./chunk-f194ct93.js";import"./chunk-kv458q06.js";import"./chunk-5v0jcyea.js";import"./chunk-2f8d0km4.js";import"./chunk-ddvdc2p0.js";import"./chunk-2mk914vk.js";import"./chunk-j8hbddjp.js";import"./chunk-4cdk4mds.js";import{Xj as M}from"./chunk-rjbneaq0.js";import"./chunk-rvs364rz.js";import"./chunk-vw9paban.js";import"./chunk-4wx5sya5.js";import"./chunk-eg3ms291.js";import m from"chalk";import K from"open";var A=`
2
+ ____ _ _
3
+ | __ )| | __ _ __| | ___
4
+ | _ \\| |/ _\` |/ _\` |/ _ \\
5
+ | |_) | | (_| | (_| | __/
6
+ |____/|_|\\__,_|\\__,_|\\___|
7
+ `,C={command:"web",describe:"Start Blade server and open web interface",builder:T,handler:async(Z)=>{let H=W(Z);if(await Q(),!process.env.BLADE_SERVER_PASSWORD)console.log(m.yellow("[WARN] BLADE_SERVER_PASSWORD is not set; server is unsecured.")),console.log(m.gray(` Set this environment variable to enable Basic Auth.
8
+ `));let F=await Y.listenAsync(H);if(console.log(m.cyan(A)),console.log(m.gray(` v${M()}
9
+ `)),H.hostname==="0.0.0.0"){let q=`http://localhost:${F.port}`;console.log(m.blue.bold(" Local access: "),m.white(q));let x=X();for(let z of x)console.log(m.blue.bold(" Network access: "),m.white(`http://${z}:${F.port}`));K(q).catch(()=>{})}else{let q=F.url.toString();console.log(m.blue.bold(" Web interface: "),m.white(q)),K(q).catch(()=>{})}console.log(""),console.log(m.gray(` Press Ctrl+C to stop the server.
10
+ `));let J,$=new Promise((q)=>{J=q}),b=R(async()=>{await F.stop(),J()});try{await $}finally{b(),await F.stop()}}};export{C as webCommand};
@@ -1,2 +1,2 @@
1
- import{vh as Q}from"./chunk-erhaedch.js";import{Ej as F,Gj as k,Jj as G}from"./chunk-5q4z0sfr.js";var V=k.String({minLength:1,maxLength:128,pattern:"^[A-Za-z0-9][A-Za-z0-9_-]*$"}),K=k.Array(k.String({minLength:1,maxLength:200,pattern:".*\\S.*"}),{maxItems:128}),W=k.Object({description:k.String({minLength:1,maxLength:4096,pattern:".*\\S.*"}),prompt:k.String({minLength:1,maxLength:1e5,pattern:".*\\S.*"}),tools:k.Optional(K),disallowedTools:k.Optional(K),model:k.Optional(k.String({minLength:1,maxLength:200,pattern:".*\\S.*"})),permissionMode:k.Optional(G(["default","acceptEdits","dontAsk","bypassPermissions","plan","ignore"])),maxTurns:k.Optional(k.Integer({minimum:1})),isolation:k.Optional(G(["none","worktree"]))},{additionalProperties:!1});function Z(R){let w;try{w=JSON.parse(R)}catch{throw Error("Invalid JSON provided to --agents")}if(w===null||Array.isArray(w)||typeof w!=="object")throw Error("--agents must be a JSON object");let H=Object.entries(w);if(H.length>64)throw Error("--agents supports at most 64 definitions");return H.map(([z,U])=>{if(!F(V,z).success)throw Error(`Invalid --agents name "${z}": use letters, numbers, hyphens, or underscores`);let I=F(W,U);if(!I.success)throw Error(`Invalid --agents definition for "${z}"`);let q=I.data;return{name:z,description:q.description.trim(),systemPrompt:q.prompt.trim(),tools:q.tools?[...new Set(q.tools.map((B)=>B.trim()))]:void 0,disallowedTools:q.disallowedTools?[...new Set(q.disallowedTools.map((B)=>B.trim()))]:void 0,model:q.model?.trim(),permissionMode:q.permissionMode===void 0?void 0:Q(q.permissionMode),maxTurns:q.maxTurns,isolation:q.isolation,source:"flag"}})}
2
- export{Z as vf};
1
+ import{wh as Q}from"./chunk-06hkf59s.js";import{Fj as F,Hj as k,Kj as G}from"./chunk-2mk914vk.js";var V=k.String({minLength:1,maxLength:128,pattern:"^[A-Za-z0-9][A-Za-z0-9_-]*$"}),K=k.Array(k.String({minLength:1,maxLength:200,pattern:".*\\S.*"}),{maxItems:128}),W=k.Object({description:k.String({minLength:1,maxLength:4096,pattern:".*\\S.*"}),prompt:k.String({minLength:1,maxLength:1e5,pattern:".*\\S.*"}),tools:k.Optional(K),disallowedTools:k.Optional(K),model:k.Optional(k.String({minLength:1,maxLength:200,pattern:".*\\S.*"})),permissionMode:k.Optional(G(["default","acceptEdits","dontAsk","bypassPermissions","plan","ignore"])),maxTurns:k.Optional(k.Integer({minimum:1})),isolation:k.Optional(G(["none","worktree"]))},{additionalProperties:!1});function Z(R){let w;try{w=JSON.parse(R)}catch{throw Error("Invalid JSON provided to --agents")}if(w===null||Array.isArray(w)||typeof w!=="object")throw Error("--agents must be a JSON object");let H=Object.entries(w);if(H.length>64)throw Error("--agents supports at most 64 definitions");return H.map(([z,U])=>{if(!F(V,z).success)throw Error(`Invalid --agents name "${z}": use letters, numbers, hyphens, or underscores`);let I=F(W,U);if(!I.success)throw Error(`Invalid --agents definition for "${z}"`);let q=I.data;return{name:z,description:q.description.trim(),systemPrompt:q.prompt.trim(),tools:q.tools?[...new Set(q.tools.map((B)=>B.trim()))]:void 0,disallowedTools:q.disallowedTools?[...new Set(q.disallowedTools.map((B)=>B.trim()))]:void 0,model:q.model?.trim(),permissionMode:q.permissionMode===void 0?void 0:Q(q.permissionMode),maxTurns:q.maxTurns,isolation:q.isolation,source:"flag"}})}
2
+ export{Z as wf};
@@ -1,4 +1,4 @@
1
- import{rc as Xt,sc as En,tc as yn,uc as bn}from"./chunk-wm896gnx.js";import{yh as Bt}from"./chunk-g7pwwxvz.js";import{$h as Gt,Dh as xt,Eh as vi,Fh as sn,Gh as zt,Hh as U,Ih as en,Jh as gt,Kh as mt,Mh as rn,Nh as Tn,Oh as B,Ph as dn,Qh as on,Rh as pn,Sh as lt,Th as un,Uh as cn,Vh as Mn,Xh as S,_h as wn,ai as Ut,bi as h,ci as Ht}from"./chunk-5xnht5vw.js";import{aj as It}from"./chunk-jsv3e4k6.js";import{Ej as X,Gj as x}from"./chunk-5q4z0sfr.js";import{Wj as tn,Xj as nn}from"./chunk-fhsvz4b1.js";import{Lk as ns}from"./chunk-sdapqhj0.js";import{EventEmitter as fs}from"events";import Un from"node:path";function hn(t){if(t===void 0)return"undefined";if(typeof t==="string")return t;try{let i=JSON.stringify(t);return i===void 0?String(t):i}catch{return String(t)}}function An(t){let i=t;switch(t.code){case"type":return`类型错误:${t.message}`;case"required":return"缺少必需参数";case"minLength":return`字符串过短:${t.message}`;case"maxLength":return`字符串过长:${t.message}`;case"minimum":case"exclusiveMinimum":return`数值太小:${t.message}`;case"maximum":case"exclusiveMaximum":return`数值太大:${t.message}`;case"minItems":return`数组元素过少:${t.message}`;case"maxItems":return`数组元素过多:${t.message}`;case"format":return`格式错误:${t.message}`;case"enum":return`必须是枚举允许的值之一:${t.message}`;case"const":return`必须是指定的字面量值:${t.message}`;case"additionalProperties":case"unevaluatedProperties":return`包含未知参数:${t.message}`;case"anyOf":case"oneOf":return"不符合任何有效的类型定义";case"~refine":return t.message||"自定义验证失败";default:return t.message||`验证失败:${hn(i)}`}}class Jt extends Error{issues;type;constructor(t,i,n="validation_error"){super(t);this.issues=i;this.type=n;this.name="ToolValidationError"}}function Vt(t,i){let n=X(t,i);if(n.success)return n.data;let s=n.error.issues.map((r)=>({field:r.path.length>0?r.path.join("."):"root",message:An(r),value:r.value})),e=s.length===1?`参数验证失败 [${s[0].field}]: ${s[0].message}`:`参数验证失败 (${s.length} 个错误):
1
+ import{sc as Xt,tc as En,uc as yn,vc as bn}from"./chunk-zzvs471p.js";import{zh as Bt}from"./chunk-sspk1ah8.js";import{$h as wn,Eh as xt,Fh as vi,Gh as sn,Hh as zt,Ih as U,Jh as en,Kh as gt,Lh as mt,Nh as rn,Oh as Tn,Ph as B,Qh as dn,Rh as on,Sh as pn,Th as lt,Uh as un,Vh as cn,Wh as Mn,Yh as S,ai as Gt,bi as Ut,ci as h,di as Ht}from"./chunk-f194ct93.js";import{bj as It}from"./chunk-2f8d0km4.js";import{Fj as X,Hj as x}from"./chunk-2mk914vk.js";import{Xj as tn,Yj as nn}from"./chunk-rjbneaq0.js";import{Mk as ns}from"./chunk-eg3ms291.js";import{EventEmitter as fs}from"events";import Un from"node:path";function hn(t){if(t===void 0)return"undefined";if(typeof t==="string")return t;try{let i=JSON.stringify(t);return i===void 0?String(t):i}catch{return String(t)}}function An(t){let i=t;switch(t.code){case"type":return`类型错误:${t.message}`;case"required":return"缺少必需参数";case"minLength":return`字符串过短:${t.message}`;case"maxLength":return`字符串过长:${t.message}`;case"minimum":case"exclusiveMinimum":return`数值太小:${t.message}`;case"maximum":case"exclusiveMaximum":return`数值太大:${t.message}`;case"minItems":return`数组元素过少:${t.message}`;case"maxItems":return`数组元素过多:${t.message}`;case"format":return`格式错误:${t.message}`;case"enum":return`必须是枚举允许的值之一:${t.message}`;case"const":return`必须是指定的字面量值:${t.message}`;case"additionalProperties":case"unevaluatedProperties":return`包含未知参数:${t.message}`;case"anyOf":case"oneOf":return"不符合任何有效的类型定义";case"~refine":return t.message||"自定义验证失败";default:return t.message||`验证失败:${hn(i)}`}}class Jt extends Error{issues;type;constructor(t,i,n="validation_error"){super(t);this.issues=i;this.type=n;this.name="ToolValidationError"}}function Vt(t,i){let n=X(t,i);if(n.success)return n.data;let s=n.error.issues.map((r)=>({field:r.path.length>0?r.path.join("."):"root",message:An(r),value:r.value})),e=s.length===1?`参数验证失败 [${s[0].field}]: ${s[0].message}`:`参数验证失败 (${s.length} 个错误):
2
2
  ${s.map((r)=>` - ${r.field}: ${r.message}`).join(`
3
3
  `)}`;throw new Jt(e,s)}function st(t){if(!t||typeof t!=="object")return;let i=t;if(i.type==="object"&&i.properties)i.required??=[],i.additionalProperties??=!1;for(let n of Object.values(i))if(Array.isArray(n))for(let s of n)st(s);else st(n)}function et(t){let i=JSON.parse(JSON.stringify(t,(n,s)=>n.startsWith("~")?void 0:s));return st(i),i}class rt{toolName;params;executeFn;descriptionFn;affectedPathsFn;isRetrySafe;constructor(t,i,n,s,e,r=!1){this.toolName=t;this.params=i;this.executeFn=n;this.descriptionFn=s;this.affectedPathsFn=e;this.isRetrySafe=r}getDescription(){if(this.descriptionFn)return this.descriptionFn(this.params);return`执行工具: ${this.toolName}`}getAffectedPaths(){if(this.affectedPathsFn)return this.affectedPathsFn(this.params);return[]}async execute(t,i,n){let s={signal:t,updateOutput:i,...n};return this.executeFn(this.params,s)}}function jt(t){return{name:t.name,displayName:t.displayName,kind:t.kind,isConcurrencySafe:t.isConcurrencySafe??!1,isRetrySafe:t.isRetrySafe??!1,parallelism:t.parallelism??(t.isConcurrencySafe?"shared":"exclusive"),strict:t.strict??!1,description:t.description,version:t.version||"1.0.0",category:t.category,tags:t.tags||[],getFunctionDeclaration(){let i=et(t.schema),n=t.description.short;if(t.description.long)n+=`
4
4
 
@@ -22,4 +22,4 @@ ${c}
22
22
 
23
23
  Preview (tail):
24
24
  ${M}`,u=!0}return{isError:t.isError===!0,llmContent:o,metadata:{contentCount:t.content.length,textBytes:n.textBytes,structuredBytes:r?.bytes??0,artifactCount:e.length,truncated:u,binaryOmitted:n.binaryBytes>0,artifacts:e}}}function yt(t){let i=t instanceof Error?t.message:String(t),n=gn(i.replace(/\bhttps?:\/\/[^\s"'`]+/gi,"[redacted-url]").replace(/\bBearer\s+\S+/gi,"Bearer [redacted]").replace(/\bsk-[A-Za-z0-9_-]{8,}\b/g,"[redacted]")).trim();return wt(n||"MCP tool execution failed",Cn)}function Tt(t,i,n,s,e){let r=n.inputSchema&&typeof n.inputSchema==="object"?x.Unsafe(n.inputSchema):x.Any(),o=s||n.name;return jt({name:o,displayName:`${i}: ${n.name}`,kind:"execute",schema:r,description:{short:n.description||`MCP Tool: ${n.name}`,important:[`From MCP server: ${i}`,"Executes external tools; user confirmation required",...n.taskSupport==="required"?["This tool requires MCP task execution and returns an opaque task ID.","Use TaskOutput to retrieve the eventual result."]:[]]},category:"MCP tool",tags:["mcp","external",i],async execute(u,d){try{let p={...d.confirmationHandler?{confirmationHandler:d.confirmationHandler}:{},...d.mcpSamplingHandler?{samplingHandler:d.mcpSamplingHandler}:{},...d.onProgressUpdate?{progressHandler:d.onProgressUpdate}:{},...d.sessionId?{sessionId:d.sessionId}:{},...d.workspaceRoot?{workspaceRoot:d.workspaceRoot}:{},...d.permissionMode?{permissionMode:d.permissionMode}:{}};if(n.taskSupport==="required"){if(!d.sessionId)throw Error("MCP tasks require an active Session");let y=await T.getInstance().start({client:t,serverName:i,toolName:n.name,arguments:u,owner:{sessionId:d.sessionId,projectPath:Un.resolve(d.workspaceRoot||It())},interactionContext:p,signal:d.signal});return{success:!0,llmContent:{task_id:y.taskId,type:"mcp",status:y.status,message:`MCP task started. Use TaskOutput(task_id: "${y.taskId}") to retrieve its result.`},metadata:{summary:`Started MCP task ${y.taskId}`,serverName:i,toolName:n.name,task_id:y.taskId,taskType:"mcp",taskStatus:y.status,background:!0}}}let c=await t.callTool(n.name,u,{...d.signal?{signal:d.signal}:{},...p}),M=await j(c,e),w={summary:`MCP ${n.name} 执行${M.isError?"失败":"成功"}`,serverName:i,toolName:n.name,mcpResult:{isError:M.isError,...M.metadata}};if(M.isError){let y=yt(M.llmContent);return{success:!1,llmContent:y,error:{type:"execution_error",message:y},metadata:w}}return{success:!0,llmContent:M.llmContent,metadata:w}}catch(p){let c=yt(p);return{success:!1,llmContent:`MCP tool execution failed: ${c}`,error:{type:"execution_error",message:c},metadata:{summary:`MCP ${n.name} 执行失败`,serverName:i,toolName:n.name}}}}})}import{realpathSync as ss}from"node:fs";import Ni from"node:path";import{pathToFileURL as es}from"node:url";import{Client as rs}from"@modelcontextprotocol/sdk/client/index.js";import{SSEClientTransport as ds}from"@modelcontextprotocol/sdk/client/sse.js";import{StdioClientTransport as os}from"@modelcontextprotocol/sdk/client/stdio.js";import{CallToolResultSchema as St,CreateMessageRequestSchema as ps,ElicitationCompleteNotificationSchema as us,ElicitRequestSchema as cs,ErrorCode as R,ListRootsRequestSchema as Ms,LoggingMessageNotificationSchema as ws,McpError as P,ResourceUpdatedNotificationSchema as ys,TaskStatusNotificationSchema as Ts}from"@modelcontextprotocol/sdk/types.js";import{EventEmitter as Es}from"events";import bs from"open";import{EventEmitter as Bn}from"events";function Et(t,i,n,s,e){if(t===void 0)return i;if(typeof t!=="number"||!Number.isFinite(t)||!Number.isInteger(t)||t<s||t>e)throw Error(`${n} must be an integer between ${s} and ${e}`);return t}class bt extends Bn{client;config;checkTimer=null;isChecking=!1;running=!1;consecutiveFailures=0;lastCheckTime=0;currentStatus="healthy";constructor(t,i={}){super();if(this.client=t,i.enabled!==void 0&&typeof i.enabled!=="boolean")throw Error("MCP health check enabled must be a boolean");this.config={interval:Et(i.interval,30000,"MCP health check interval",10,300000),timeout:Et(i.timeout,1e4,"MCP health check timeout",10,60000),enabled:i.enabled??!1,failureThreshold:Et(i.failureThreshold,3,"MCP health check failureThreshold",1,10)}}start(){if(this.running||!this.config.enabled)return;this.running=!0,this.scheduleNextCheck()}stop(){if(this.running=!1,this.checkTimer)clearTimeout(this.checkTimer),this.checkTimer=null}scheduleNextCheck(){if(!this.running)return;this.checkTimer=setTimeout(async()=>{this.checkTimer=null,await this.performHealthCheck().catch(()=>{return}),this.scheduleNextCheck()},this.config.interval),this.checkTimer.unref()}async performHealthCheck(){if(this.isChecking)return this.getLastResult();this.isChecking=!0,this.lastCheckTime=Date.now(),this.setStatus("checking");try{let t=this.client.connectionStatus;if(t==="connected"){await this.client.ping(this.config.timeout),this.consecutiveFailures=0,this.setStatus("healthy");let i={status:"healthy",timestamp:Date.now(),consecutiveFailures:0};return this.emit("healthCheck",i),i}else throw Error(`连接状态异常: ${t}`)}catch(t){this.consecutiveFailures++;let i=t,n;if(this.consecutiveFailures>=this.config.failureThreshold)n="unhealthy",this.emit("unhealthy",this.consecutiveFailures,i),this.client.requestRecovery(i,"health_check");else n="degraded";this.setStatus(n);let s={status:n,timestamp:Date.now(),consecutiveFailures:this.consecutiveFailures,lastError:i};return this.emit("healthCheck",s),s}finally{this.isChecking=!1}}setStatus(t){if(this.currentStatus!==t){let i=this.currentStatus;this.currentStatus=t,this.emit("statusChanged",t,i)}}getStatus(){return this.currentStatus}getLastResult(){return{status:this.currentStatus,timestamp:this.lastCheckTime,consecutiveFailures:this.consecutiveFailures}}getStatistics(){return{status:this.currentStatus,consecutiveFailures:this.consecutiveFailures,lastCheckTime:this.lastCheckTime,isChecking:this.isChecking,config:this.config}}async checkNow(){return this.performHealthCheck()}resetFailureCount(){if(this.consecutiveFailures=0,this.currentStatus!=="checking")this.setStatus("healthy")}}import{createHash as Xn}from"node:crypto";import{UriTemplate as zn}from"@modelcontextprotocol/sdk/shared/uriTemplate.js";var ti=100,Yn=4096,Dn=65536,ft=1048576,ii=32,ni=65536,oi=4,ht=15000,si=256,ei=16384,Fn=256,Jn=8192,Vn=/[\p{Cf}\p{Co}\p{Cn}]/u;function jn(t){return[...new Set(new zn(t).variableNames)]}function pi(t,i){let n=G(t.argument.name,"completion argument name",si),s=ri(t.argument.value,"completion argument value",ei),e,r;if(t.reference.type==="prompt"){let p=G(t.reference.name,"completion prompt name",Fn),c=i.prompts.find((M)=>M.name===p);if(!c)throw Error(`MCP prompt "${p}" is not present in the current catalog`);e=new Set(c.arguments.map((M)=>M.name)),r={type:"ref/prompt",name:p}}else{let p=G(t.reference.uri,"completion resource template URI",Jn);if(!i.resourceTemplates.find((w)=>w.uriTemplate===p))throw Error(`MCP resource template "${p}" is not present in the current catalog`);let M;try{M=jn(p)}catch{throw Error(`MCP resource template "${p}" is invalid`)}e=new Set(M),r={type:"ref/resource",uri:p}}if(!e.has(n))throw Error(`MCP ${t.reference.type} completion argument "${n}" is not declared`);let o=Object.entries(t.context??{});if(o.length>ii)throw Error(`MCP completion context exceeds ${ii} arguments`);let u=Object.create(null),d=0;for(let[p,c]of o){let M=G(p,"completion context argument name",si);if(wi(M))throw Error(`Unsafe MCP completion context argument "${M}"`);if(!e.has(M))throw Error(`Unknown MCP completion context argument "${M}"`);let w=ri(c,`completion context argument "${M}"`,ei);if(d+=Buffer.byteLength(M)+Buffer.byteLength(w),d>ni)throw Error(`MCP completion context exceeds ${ni} bytes`);u[M]=w}return{ref:r,argument:{name:n,value:s},...o.length>0?{context:{arguments:u}}:{}}}function ui(t){let i=t.completion,n=JSON.stringify(i),s=Buffer.byteLength(n),e=Xn("sha256").update(n).digest("hex"),r=i.values.length,o=[],u=new Set,d=0,p=0,c=r>ti||s>ft;for(let w of i.values.slice(0,ti)){let y=Buffer.byteLength(w),E=Math.max(0,ft-p);if(E===0){c=!0;break}let a=di(w,Math.min(ft,E));if(p+=Buffer.byteLength(a),y>Buffer.byteLength(a))c=!0;let Dt=ci(a),L=di(Dt,Yn);if(Buffer.byteLength(L)<Buffer.byteLength(Dt))c=!0;if(u.has(L))continue;let Ft=Buffer.byteLength(L);if(d+Ft>Dn){c=!0;break}u.add(L),o.push(L),d+=Ft}if(o.length<r)c=!0;let M=i.total!==void 0&&Number.isSafeInteger(i.total)&&i.total>=0?i.total:void 0;return{values:o,...M!==void 0?{total:M}:{},hasMore:i.hasMore===!0||c||M!==void 0&&M>o.length,sourceValueCount:r,sourceBytes:s,projectedBytes:d,sha256:e,truncated:c}}function ci(t){return[...t.normalize("NFKC")].filter((i)=>{let n=i.codePointAt(0)??0;if(n<32||n===127)return!1;return!Vn.test(i)}).join("")}function G(t,i,n){if(typeof t!=="string"||!t||Buffer.byteLength(t)>n)throw Error(`MCP ${i} is invalid`);if(ci(t)!==t||Mi(t))throw Error(`MCP ${i} contains unsafe characters`);if(wi(t))throw Error(`MCP ${i} is unsafe`);return t}function ri(t,i,n){if(typeof t!=="string"||Buffer.byteLength(t)>n)throw Error(`MCP ${i} exceeds ${n} bytes`);if(Mi(t))throw Error(`MCP ${i} contains control characters`);return t}function Mi(t){return[...t].some((i)=>{let n=i.codePointAt(0)??0;return n<32||n===127})}function wi(t){return["__proto__","constructor","prototype"].includes(t)}function di(t,i){let n=Buffer.from(t);if(n.length<=i)return t;let s=n.subarray(0,Math.max(0,i)).toString("utf8");while(Buffer.byteLength(s)>i)s=s.slice(0,-1);return s}var At=20,_t=300000;function yi(t,i,n,s,e){if(t===void 0)return i;if(typeof t!=="number"||!Number.isFinite(t))throw Error(`${n} must be a finite number`);if(t<s||t>e)throw Error(`${n} must be between ${s} and ${e}`);return t}function H(t,i,n,s,e){let r=yi(t,i,n,s,e);if(!Number.isInteger(r))throw Error(`${n} must be an integer`);return r}function Ti(t){let i=t.recovery;if(i!==void 0&&(i===null||typeof i!=="object"||Array.isArray(i)))throw Error("MCP recovery configuration must be an object");let n=i?.enabled??!0;if(typeof n!=="boolean")throw Error("MCP recovery enabled must be a boolean");let s=H(i?.maxAttempts,5,"MCP recovery maxAttempts",0,20),e=H(i?.initialDelayMs,1000,"MCP recovery initialDelayMs",10,300000),r=H(i?.maxDelayMs,30000,"MCP recovery maxDelayMs",e,300000),o=yi(i?.jitterRatio,0.2,"MCP recovery jitterRatio",0,1),u=H(i?.terminalErrorThreshold,3,"MCP recovery terminalErrorThreshold",1,10);return{enabled:n,maxAttempts:s,initialDelayMs:e,maxDelayMs:r,jitterRatio:o,terminalErrorThreshold:u}}function Ei(t,i,n=Math.random){let s=Math.max(0,i-1),e=Math.min(t.initialDelayMs*2**s,t.maxDelayMs);if(t.jitterRatio===0)return e;let r=Math.min(1,Math.max(0,n())),o=1-t.jitterRatio+2*t.jitterRatio*r;return Math.max(0,Math.round(e*o))}function k(t){let n=(t instanceof Error?t.message:String(t)).replace(/\bhttps?:\/\/[^\s"'`]+/gi,"[redacted-url]").replace(/\bBearer\s+\S+/gi,"Bearer [redacted]").replace(/\bsk-[A-Za-z0-9_-]{8,}\b/g,"[redacted]").replace(/[\r\n\t]+/g," ").trim();if(Buffer.byteLength(n)<=512)return n;let s=Buffer.from(n).subarray(0,512).toString("utf8");while(Buffer.byteLength(s)>512)s=s.slice(0,-1);return s}function bi(t){let n=(t instanceof Error?t.message:String(t)).toLowerCase();return(n.includes("404")||n.includes("-32001"))&&(n.includes("session")||n.includes("not found"))}function fi(t){let n=(t instanceof Error?t.message:String(t)).toLowerCase();return["econnreset","etimedout","epipe","ehostunreach","econnrefused","body timeout error","socket hang up","connection closed","connection terminated","sse stream disconnected","failed to reconnect sse stream","maximum reconnection attempts"].some((s)=>n.includes(s))}function C(t){return new DOMException(String(t||"MCP connection recovery cancelled"),"AbortError")}async function Rt(t,i,n=!0){if(i.aborted)throw C(i.reason);await new Promise((s,e)=>{let o=setTimeout(()=>{i.removeEventListener("abort",u),s()},t);if(n)o.unref();let u=()=>{clearTimeout(o),i.removeEventListener("abort",u),e(C(i.reason))};i.addEventListener("abort",u,{once:!0})})}import{createHash as ai}from"node:crypto";var Pt=100,q=1000,K=1000,W=1000,at=100,hi=64,Z=1048576,_=4194304,A=256,N=8192,g=256,m=16384,Ai=64,Gn=4096,_i=4194304,Ri=128;function $i(t){return[...t].some((i)=>{let n=i.charCodeAt(0);return n<=31||n===127})}function Hn(t){return[...t].some((i)=>{let n=i.charCodeAt(0);return n===0||n>=1&&n<=8||n===11||n===12||n>=14&&n<=31||n===127})}function b(t,i,n){if(t===void 0)return;if(i==="description"?Hn(t):$i(t))throw Error(`MCP ${i} contains control characters`);if(Buffer.byteLength(t)>n)throw Error(`MCP ${i} exceeds ${n} bytes`);return t}function f(t,i,n){let s=t.trim();if(!s||s.length>n||$i(s))throw Error(`MCP ${i} is invalid`);return s}function $t(t){return Buffer.byteLength(JSON.stringify(t))}function Ct(t,i){if($t(t)>_i)throw Error(`MCP ${i} catalog exceeds ${_i} bytes`)}function Q(t,i){let n=new Set;for(let s of t){if(n.has(s))throw Error(`MCP ${i} catalog contains duplicate "${s}"`);n.add(s)}}function Ci(t){if(t.length>q)throw Error(`MCP resource catalog exceeds ${q} entries`);let i=t.map((n)=>({uri:f(n.uri,"resource URI",N),name:f(n.name,"resource name",A),...b(n.title,"resource title",A)?{title:n.title}:{},...b(n.description,"description",m)?{description:n.description}:{},...b(n.mimeType,"resource MIME type",g)?{mimeType:n.mimeType}:{},...n.size!==void 0&&Number.isSafeInteger(n.size)&&n.size>=0?{size:n.size}:{}}));return Q(i.map((n)=>n.uri),"resource"),Ct(i,"resource"),i}function ki(t){if(t.length>K)throw Error(`MCP resource template catalog exceeds ${K} entries`);let i=t.map((n)=>({uriTemplate:f(n.uriTemplate,"resource template URI",N),name:f(n.name,"resource template name",A),...b(n.title,"resource template title",A)?{title:n.title}:{},...b(n.description,"description",m)?{description:n.description}:{},...b(n.mimeType,"resource template MIME type",g)?{mimeType:n.mimeType}:{}}));return Q(i.map((n)=>n.uriTemplate),"resource template"),Ct(i,"resource template"),i}function Oi(t){if(t.length>W)throw Error(`MCP prompt catalog exceeds ${W} entries`);let i=t.map((n)=>{if((n.arguments?.length??0)>Ai)throw Error(`MCP prompt "${n.name}" exceeds ${Ai} arguments`);let s=(n.arguments??[]).map((e)=>{let r=f(e.name,"prompt argument name",A);if(["__proto__","constructor","prototype"].includes(r))throw Error(`MCP prompt argument name "${r}" is unsafe`);return{name:r,...b(e.description,"description",Gn)?{description:e.description}:{},required:e.required===!0}});return Q(s.map((e)=>e.name),`prompt "${n.name}" argument`),{name:f(n.name,"prompt name",A),...b(n.title,"prompt title",A)?{title:n.title}:{},...b(n.description,"description",m)?{description:n.description}:{},arguments:s}});return Q(i.map((n)=>n.name),"prompt"),Ct(i,"prompt"),i}function Pi(t){return ai("sha256").update(JSON.stringify(t)).digest("hex")}function I(t,i,n){let s=new Map(t.map((r)=>[n(r),Pi(r)])),e=new Map(i.map((r)=>[n(r),Pi(r)]));return{added:[...e.keys()].filter((r)=>!s.has(r)).sort(),removed:[...s.keys()].filter((r)=>!e.has(r)).sort(),updated:[...e.keys()].filter((r)=>s.has(r)&&s.get(r)!==e.get(r)).sort()}}function Li(t){return t.added.length>0||t.removed.length>0||t.updated.length>0}function kt(t,i,n){if(t.bytes+=i,t.bytes>_)throw Error(`MCP ${n} exceeds ${_} total bytes`)}function Si(t,i,n){if(t.length%4!==0||!/^[A-Za-z0-9+/]*={0,2}$/.test(t))throw Error(`MCP ${i} contains invalid base64`);let s=Buffer.from(t,"base64");if(s.length>_)throw Error(`MCP ${i} exceeds ${_} decoded bytes`);return kt(n,s.length,i),{size:s.length,sha256:ai("sha256").update(s).digest("hex"),omitted:!0}}function xi(t,i){let n=f(typeof t.uri==="string"?t.uri:"","resource content URI",N),s=typeof t.mimeType==="string"?b(t.mimeType,"resource MIME type",g):void 0;if(typeof t.text==="string"){let e=Buffer.byteLength(t.text);if(e>Z)throw Error(`MCP resource text exceeds ${Z} bytes`);return kt(i,e,"resource result"),{uri:n,...s?{mimeType:s}:{},text:t.text}}if(typeof t.blob==="string")return{uri:n,...s?{mimeType:s}:{},binary:Si(t.blob,"resource blob",i)};throw Error("MCP resource content has neither text nor blob data")}function gi(t){let i=t&&typeof t==="object"&&Array.isArray(t.contents)?t.contents:[];if(i.length>hi)throw Error(`MCP resource result exceeds ${hi} contents`);let n={bytes:0},s=i.map((e)=>{if(!e||typeof e!=="object"||Array.isArray(e))throw Error("MCP resource content is malformed");return xi(e,n)});if($t(s)>_)throw Error(`MCP resource result exceeds ${_} bytes`);return{contents:s}}function mi(t){if(!t||typeof t!=="object"||Array.isArray(t))throw Error("MCP prompt result is malformed");let i=t,n=Array.isArray(i.messages)?i.messages:[];if(n.length>Ri)throw Error(`MCP prompt exceeds ${Ri} messages`);let s={bytes:0},e=n.map((r)=>{if(!r||typeof r!=="object"||Array.isArray(r))throw Error("MCP prompt message is malformed");let o=r,u=o.role;if(u!=="user"&&u!=="assistant")throw Error("MCP prompt message has an invalid role");let d=o.content;if(!d||typeof d!=="object"||Array.isArray(d))throw Error("MCP prompt message content is malformed");let p=d;if(p.type==="text"&&typeof p.text==="string"){let c=Buffer.byteLength(p.text);if(c>Z)throw Error(`MCP prompt text exceeds ${Z} bytes`);return kt(s,c,"prompt result"),{role:u,content:{type:"text",text:p.text}}}if((p.type==="image"||p.type==="audio")&&typeof p.data==="string"&&typeof p.mimeType==="string")return{role:u,content:{type:p.type,mimeType:f(p.mimeType,"prompt content MIME type",g),binary:Si(p.data,`prompt ${p.type}`,s)}};if(p.type==="resource"&&p.resource&&typeof p.resource==="object"&&!Array.isArray(p.resource))return{role:u,content:{type:"resource",resource:xi(p.resource,s)}};if(p.type==="resource_link"&&typeof p.uri==="string"&&typeof p.name==="string")return{role:u,content:{type:"resource_link",uri:f(p.uri,"prompt resource link URI",N),name:f(p.name,"prompt resource link name",A),...typeof p.mimeType==="string"?{mimeType:f(p.mimeType,"prompt resource link MIME type",g)}:{},...typeof p.description==="string"?{description:b(p.description,"description",m)}:{}}};throw Error(`Unsupported MCP prompt content type: ${String(p.type)}`)});if($t(e)>_)throw Error(`MCP prompt result exceeds ${_} bytes`);return{...typeof i.description==="string"?{description:b(i.description,"description",m)}:{},messages:e}}var li=4000,Ui=4096,Bi=32,qn=128,Xi=1000,zi=100,Yi=65536,Kn=new Set(["__proto__","constructor","prototype"]);function Di(t,i){if(!t.trim())throw Error("MCP elicitation server name is empty");if(!i.message.trim())throw Error("MCP elicitation message is empty");if(i.message.length>li)throw Error(`MCP elicitation message exceeds ${li} characters`);if(i.mode==="url"){let e=Nn(i.url);if(!i.elicitationId.trim())throw Error("MCP URL elicitation ID is empty");return{serverName:t,mode:"url",message:i.message,url:e.toString(),domain:e.hostname,elicitationId:i.elicitationId}}let n=Object.entries(i.requestedSchema.properties);if(n.length>Bi)throw Error(`MCP elicitation exceeds the ${Bi} field limit`);let s=new Set(i.requestedSchema.required??[]);for(let e of s)if(!Object.hasOwn(i.requestedSchema.properties,e))throw Error(`MCP elicitation requires an unknown field: ${e}`);return{serverName:t,mode:"form",message:i.message,fields:n.map(([e,r])=>Wn(e,r,s.has(e))),requestedSchema:structuredClone(i.requestedSchema)}}function vs(t){let i=Object.create(null);for(let n of t.fields??[])if(n.defaultValue!==void 0)i[n.name]=Array.isArray(n.defaultValue)?[...n.defaultValue]:n.defaultValue;return i}function te(t,i){let n=i.trim();if(!n){if(t.defaultValue!==void 0)return t.defaultValue;if(!t.required)return;throw Error(`${t.title} is required`)}if(t.type==="number"||t.type==="integer"){let s=Number(n);if(!Number.isFinite(s))throw Error(`${t.title} must be a finite number`);if(t.type==="integer"&&!Number.isSafeInteger(s))throw Error(`${t.title} must be a safe integer`);return s}if(t.type==="boolean"){if(["true","yes","y","1"].includes(n.toLowerCase()))return!0;if(["false","no","n","0"].includes(n.toLowerCase()))return!1;throw Error(`${t.title} must be true or false`)}return n}function Fi(t,i){if(i.action!=="accept")return{action:i.action};if(t.mode==="url")return{action:"accept"};if(!t.requestedSchema)throw Error("MCP form elicitation schema is unavailable");let n=i.content??{};if(Buffer.byteLength(JSON.stringify(n),"utf8")>Yi)throw Error(`MCP elicitation response exceeds ${Yi} bytes`);for(let r of Object.keys(n))Ji(r);for(let r of Object.values(n))if(typeof r==="number"&&(!Number.isFinite(r)||Number.isInteger(r)&&!Number.isSafeInteger(r)))throw Error("MCP elicitation response contains an unsafe number");let s=x.Unsafe({...t.requestedSchema,additionalProperties:!1}),e=X(s,n);if(!e.success)throw Error(`Invalid MCP elicitation response: ${e.error.message}`);return{action:"accept",content:e.data}}function Wn(t,i,n){Ji(t);let s=tt(i.title?.trim()||t,"field title"),e=i.description?tt(i.description,"field description"):void 0,r={name:t,title:s,description:e,required:n};if(i.type==="boolean")return{...r,type:"boolean",...typeof i.default==="boolean"?{defaultValue:i.default}:{}};if(i.type==="number"||i.type==="integer")return{...r,type:i.type,...typeof i.default==="number"?{defaultValue:i.default}:{},...i.minimum!==void 0?{minimum:i.minimum}:{},...i.maximum!==void 0?{maximum:i.maximum}:{}};if(i.type==="array"){let u=Qn(i);return{...r,type:"multi-select",options:u,...Array.isArray(i.default)&&i.default.every((d)=>typeof d==="string")?{defaultValue:[...i.default]}:{},...i.minItems!==void 0?{minItems:i.minItems}:{},...i.maxItems!==void 0?{maxItems:i.maxItems}:{}}}let o=Zn(i);if(o)return{...r,type:"select",options:o,...typeof i.default==="string"?{defaultValue:i.default}:{}};return{...r,type:"string",...typeof i.default==="string"?{defaultValue:i.default}:{},...i.format?{format:i.format}:{},...i.minLength!==void 0?{minLength:i.minLength}:{},...i.maxLength!==void 0?{maxLength:i.maxLength}:{}}}function Zn(t){if(t.oneOf)return v(t.oneOf.map((i)=>({value:i.const,label:i.title})));if(!t.enum)return;return v(t.enum.map((i,n)=>({value:i,label:t.enumNames?.[n]??i})))}function Qn(t){if(t.items?.anyOf)return v(t.items.anyOf.map((i)=>({value:i.const,label:i.title})));if(t.items?.enum)return v(t.items.enum.map((i)=>({value:i,label:i})));throw Error("MCP multi-select elicitation is missing enum options")}function v(t){if(t.length===0||t.length>zi)throw Error(`MCP elicitation options must contain 1-${zi} items`);let i=new Set;return t.map((n)=>{if(i.has(n.value))throw Error(`MCP elicitation contains duplicate option: ${n.value}`);return i.add(n.value),{value:tt(n.value,"option value"),label:tt(n.label,"option label")}})}function Ji(t){if(!t||t.length>qn||Kn.has(t))throw Error(`Unsafe MCP elicitation field name: ${t||"(empty)"}`)}function tt(t,i){if(t.length>Xi)throw Error(`MCP elicitation ${i} exceeds ${Xi} characters`);return t}function Nn(t){if(t.length>Ui)throw Error(`MCP elicitation URL exceeds ${Ui} characters`);let i;try{i=new URL(t)}catch{throw Error("MCP elicitation URL is invalid")}if(!["http:","https:"].includes(i.protocol))throw Error(`MCP elicitation URL protocol is not allowed: ${i.protocol}`);if(i.username||i.password)throw Error("MCP elicitation URL must not contain credentials");return i}import{createHash as Ki}from"node:crypto";var l=1000,it=100,In=256,Vi=16384,ji=262144,Gi=4194304,Hi=24;function vn(t,i=10){return Ki("sha256").update(t).digest("hex").slice(0,i)}function Ot(t){if(Array.isArray(t))return t.map(Ot);if(!t||typeof t!=="object")return t;let i=t;return Object.fromEntries(Object.keys(i).sort().map((n)=>[n,Ot(i[n])]))}function Wi(t){let i=t.normalize("NFKC"),n=i.replace(/[^A-Za-z0-9_-]/g,"_");if(n&&n===i&&n.length<=Hi)return n;return`${(n||"unnamed").slice(0,Hi-11)}_${vn(i)}`}function Lt(t,i){return`${ts(t)}${Wi(i)}`}function ts(t){return`mcp__${Wi(t)}__`}function qi(t){return Ki("sha256").update(JSON.stringify(Ot({name:t.name,description:t.description,inputSchema:t.inputSchema,taskSupport:t.taskSupport}))).digest("hex")}function is(t){return[...t].some((i)=>{let n=i.charCodeAt(0);return n<=31||n===127})}function Zi(t){if(t.length>l)throw Error(`MCP tool catalog exceeds ${l} tools`);let i=new Set,n=[],s=0;for(let e of t){let r=e.name.trim();if(!r||r.length>In||is(r))throw Error("MCP tool catalog contains an invalid tool name");if(i.has(r))throw Error(`MCP tool catalog contains duplicate tool "${r}"`);i.add(r);let o=e.description??"";if(Buffer.byteLength(o)>Vi)throw Error(`MCP tool "${r}" description exceeds ${Vi} bytes`);let u=JSON.stringify(e.inputSchema),d=Buffer.byteLength(u);if(d>ji)throw Error(`MCP tool "${r}" schema exceeds ${ji} bytes`);if(s+=Buffer.byteLength(r)+Buffer.byteLength(o)+d,s>Gi)throw Error(`MCP tool catalog exceeds ${Gi} bytes`);n.push({name:r,description:o,inputSchema:JSON.parse(u),...e.execution?.taskSupport?{taskSupport:e.execution.taskSupport}:{}})}return n}function Qi(t,i){let n=new Map(t.map((e)=>[e.name,qi(e)])),s=new Map(i.map((e)=>[e.name,qi(e)]));return{added:[...s.keys()].filter((e)=>!n.has(e)).sort(),removed:[...n.keys()].filter((e)=>!s.has(e)).sort(),updated:[...s.keys()].filter((e)=>n.has(e)&&n.get(e)!==s.get(e)).sort()}}function nt(t){return t.added.length>0||t.removed.length>0||t.updated.length>0}function Ii(t){if(t instanceof zt||t instanceof U)return{type:"auth_error",isRetryable:!1,originalError:t};if(!(t instanceof Error))return{type:"unknown",isRetryable:!1,originalError:Error(String(t))};let i=t.message.toLowerCase();if(["command not found","no such file","permission denied","invalid configuration","malformed","syntax error"].some((e)=>i.includes(e)))return{type:"config_error",isRetryable:!1,originalError:t};if(i.includes("unauthorized")||i.includes("401")||i.includes("authentication failed"))return{type:"auth_error",isRetryable:!1,originalError:t};if(["timeout","connection refused","network error","temporary","try again","rate limit","too many requests","service unavailable","socket hang up","econnreset","enotfound","econnrefused","etimedout","503","429"].some((e)=>i.includes(e)))return{type:"network_temporary",isRetryable:!0,originalError:t};return{type:"unknown",isRetryable:!0,originalError:t}}class Yt extends Es{config;runtimeOptions;status="disconnected";sdkClient=null;tools=new Map;toolCatalogRevision=0;toolRefreshPromise;toolRefreshRequested=!1;resources=[];resourceTemplates=[];prompts=[];contentCatalogRevision=0;contentRefreshPromise;requestedContentCatalogs=new Set;contentRefreshReason="manual";catalogGeneration=0;desiredResourceSubscriptions=new Set;activeResourceSubscriptions=new Set;serverInfo=null;serverInstructions;completionCallsInFlight=0;loggingPolicy;logWindowStartedAt=0;logEventsInWindow=0;logRateWarningEmitted=!1;recoveryPolicy;desiredConnected=!1;connectionGeneration=0;connectPromise;connectAbortController;recoveryPromise;recoveryAbortController;recoveryState;consecutiveTerminalErrors=0;oauthProvider=null;serverName;healthMonitor=null;activeInteraction;taskInteractions=new Map;taskPolicy;roots;constructor(t,i,n,s={}){super();this.config=t;this.runtimeOptions=s;this.serverName=i||"default",this.recoveryPolicy=Ti(t),this.loggingPolicy=dn(t),this.taskPolicy=wn(t.tasks),this.roots=(s.roots??[]).map((r)=>{let o=ss.native(Ni.resolve(r));return{uri:es(o).href,name:Ni.basename(o)||o}});let e=vi(t);if(this.config={...t,...e?{oauth:e}:{}},e?.enabled&&t.url&&s.oauthCredentialAccess!==!1)this.oauthProvider=new en(this.serverName,t.url,e,s.oauthStorageRoot?{tokenStorage:new sn(s.oauthStorageRoot)}:{});if(n?.enabled)this.healthMonitor=new bt(this,n),this.healthMonitor.on("unhealthy",(r,o)=>{this.emit("unhealthy",r,o)})}get connectionStatus(){return this.status}get availableTools(){return Array.from(this.tools.values())}get contentCatalog(){return{resources:structuredClone(this.resources),resourceTemplates:structuredClone(this.resourceTemplates),prompts:structuredClone(this.prompts)}}get completionSupported(){return Boolean(this.sdkClient?.getServerCapabilities()?.completions)}get tasks(){return{...this.taskPolicy}}get server(){return this.serverInfo}get instructions(){return this.serverInstructions?structuredClone(this.serverInstructions):void 0}get healthCheck(){return this.healthMonitor}get recovery(){return this.recoveryState?structuredClone(this.recoveryState):void 0}get logging(){return{...this.loggingPolicy}}get oauthEnabled(){return this.config.oauth?.enabled===!0}async getOAuthStatus(){if(!this.oauthEnabled)return"disabled";if(this.runtimeOptions.oauthCredentialAccess===!1)return"unavailable";return this.oauthProvider?.getStatus()??"error"}async beginOAuthLogin(t={}){if(!this.oauthEnabled)throw Error(`MCP server "${this.serverName}" does not enable OAuth`);if(this.runtimeOptions.oauthCredentialAccess===!1||!this.oauthProvider)throw new U(this.serverName);return t.openBrowser?this.oauthProvider.openAuthorization():this.oauthProvider.beginAuthorization()}async logoutOAuth(){if(!this.oauthEnabled)throw Error(`MCP server "${this.serverName}" does not enable OAuth`);if(this.runtimeOptions.oauthCredentialAccess===!1||!this.oauthProvider)throw new U(this.serverName);if(this.status!=="disconnected")await this.disconnect();await this.oauthProvider.logout()}async connect(){return this.connectWithRetry(3,1000)}async connectWithRetry(t=3,i=1000){if(!Number.isInteger(t)||t<1||t>At)throw Error(`MCP connection maxRetries must be an integer between 1 and ${At}`);if(!Number.isFinite(i)||i<0||i>_t)throw Error(`MCP connection initialDelay must be between 0 and ${_t}`);if(this.status==="connected")return;if(this.recoveryPromise)return this.recoveryPromise;if(this.connectPromise)return this.connectPromise;this.desiredConnected=!0;let n=++this.connectionGeneration,s=new AbortController;this.connectAbortController=s;let e=this.runInitialConnection(Math.max(1,t),Math.max(0,i),n,s.signal).finally(()=>{if(this.connectPromise===e)this.connectPromise=void 0;if(this.connectAbortController===s)this.connectAbortController=void 0});return this.connectPromise=e,e}async runInitialConnection(t,i,n,s){let e;for(let o=1;o<=t;o++){this.assertConnectionGeneration(n,s);try{await this.doConnect(n,!1);return}catch(u){if(!this.isConnectionGenerationCurrent(n)||s.aborted)throw C(s.reason);if(e=u instanceof Error?u:Error(String(u)),!Ii(e).isRetryable||o===t)break;await Rt(i*2**Math.max(0,o-1),s,!1)}}let r=e??Error("MCP connection failed");if(this.isConnectionGenerationCurrent(n))this.invalidateLiveConnection(!1),this.setStatus("error"),this.emitClientError(r);throw r}async doConnect(t,i){let n;try{this.assertConnectionGeneration(t),this.setStatus(i?"reconnecting":"connecting");let s=cn(this.config.sampling),e={...s,enabled:s.enabled&&this.runtimeOptions.samplingAvailable===!0};n=new rs({name:nn(),version:tn()},{capabilities:{roots:{listChanged:!1},elicitation:{form:{applyDefaults:!1},url:{}},...e.enabled?{sampling:{}}:{}},listChanged:{tools:{autoRefresh:!1,debounceMs:0,onChanged:()=>{this.refreshTools("notification")}},resources:{autoRefresh:!1,debounceMs:0,onChanged:()=>{this.refreshContentCatalogs("notification",["resources"])}},prompts:{autoRefresh:!1,debounceMs:0,onChanged:()=>{this.refreshContentCatalogs("notification",["prompts"])}}}});let r=n;if(this.sdkClient=r,this.resetCatalogRefreshState(),this.registerElicitationHandlers(r),this.registerRootHandler(r),e.enabled)this.registerSamplingHandler(r,e);if(this.registerResourceNotificationHandler(r),this.registerLoggingHandler(r),this.taskPolicy.enabled)this.registerTaskStatusHandler(r);r.onclose=()=>{this.handleUnexpectedClose(r,t)},r.onerror=(d)=>{this.handleTransportError(r,t,d)};let o=await this.createTransport();this.assertConnectionGeneration(t),await r.connect(o),this.assertConnectionGeneration(t);let u=r.getServerVersion();this.serverInfo={name:u?.name||"Unknown",version:u?.version||"0.0.0"},this.serverInstructions=yn(r.getInstructions(),{exposeDetails:this.runtimeOptions.exposeInstructions}),await this.configureLogging(r),await this.refreshTools("initial"),await this.refreshContentCatalogs("initial").catch(()=>{return}),await this.reconcileResourceSubscriptions(r),this.assertConnectionGeneration(t),this.consecutiveTerminalErrors=0,this.setStatus("connected"),this.emit("connected",this.serverInfo),this.healthMonitor?.resetFailureCount(),this.healthMonitor?.start()}catch(s){if(n&&this.sdkClient===n)this.sdkClient=null;if(n)n.onclose=void 0,n.onerror=void 0,await n.close().catch(()=>{return});throw s}}handleUnexpectedClose(t,i){if(this.sdkClient!==t||!this.isConnectionGenerationCurrent(i)||this.status!=="connected")return;this.startRecovery(Error(`MCP server "${this.serverName}" connection closed`),"transport_closed",!1)}handleTransportError(t,i,n){if(this.sdkClient!==t||!this.isConnectionGenerationCurrent(i)||this.status!=="connected")return;if(this.emit("transportError",{serverName:this.serverName,error:k(n)}),bi(n)){this.startRecovery(n,"session_expired",!0);return}if(!fi(n)){this.consecutiveTerminalErrors=0;return}if(this.consecutiveTerminalErrors++,n.message.toLowerCase().includes("maximum reconnection attempts")||this.consecutiveTerminalErrors>=this.recoveryPolicy.terminalErrorThreshold)this.startRecovery(n,"transport_error",!0)}requestRecovery(t,i){if(!this.desiredConnected||this.status!=="connected"||this.recoveryPromise)return;this.startRecovery(t,i,!0)}startRecovery(t,i,n){if(!this.desiredConnected||this.recoveryPromise)return;let s=this.sdkClient;if(this.sdkClient=null,s)s.onclose=void 0,s.onerror=void 0;this.healthMonitor?.stop(),this.invalidateLiveConnection(!0);let e=++this.connectionGeneration,r=new AbortController;if(this.recoveryAbortController=r,this.setStatus("reconnecting"),n&&s)s.close().catch(()=>{return});let o=Promise.resolve().then(()=>this.runRecoveryLoop(t,i,e,r.signal)).finally(()=>{if(this.recoveryPromise===o)this.recoveryPromise=void 0;if(this.recoveryAbortController===r)this.recoveryAbortController=void 0});this.recoveryPromise=o,o.catch(()=>{return})}async runRecoveryLoop(t,i,n,s){let e=t;if(!this.recoveryPolicy.enabled||this.recoveryPolicy.maxAttempts===0){this.failRecovery(e,i,0,n);return}for(let r=1;r<=this.recoveryPolicy.maxAttempts;r++){this.assertConnectionGeneration(n,s);let o=Ei(this.recoveryPolicy,r,this.runtimeOptions.recoveryRandom),u=Date.now()+o;this.publishConnectionLifecycle({phase:"reconnecting",reason:i,attempt:r,maxAttempts:this.recoveryPolicy.maxAttempts,nextRetryAt:u,error:k(e)}),await Rt(o,s),this.assertConnectionGeneration(n,s);try{await this.doConnect(n,!0),this.healthMonitor?.resetFailureCount(),this.publishConnectionLifecycle({phase:"recovered",reason:i,attempt:r,maxAttempts:this.recoveryPolicy.maxAttempts}),this.emit("reconnected");return}catch(d){if(!this.isConnectionGenerationCurrent(n)||s.aborted)throw C(s.reason);if(e=d instanceof Error?d:Error(String(d)),!Ii(e).isRetryable){this.failRecovery(e,i,r,n);return}}}this.failRecovery(e,i,this.recoveryPolicy.maxAttempts,n)}failRecovery(t,i,n,s){if(!this.isConnectionGenerationCurrent(s))return;this.setStatus("error"),this.publishConnectionLifecycle({phase:"failed",reason:i,attempt:n,maxAttempts:this.recoveryPolicy.maxAttempts,error:k(t)}),this.emit("reconnectFailed",t)}publishConnectionLifecycle(t){this.recoveryState=structuredClone(t),this.emit("connectionLifecycleChanged",structuredClone(t))}isConnectionGenerationCurrent(t){return this.desiredConnected&&this.connectionGeneration===t}assertConnectionGeneration(t,i){if(i?.aborted||!this.desiredConnected||this.connectionGeneration!==t)throw C(i?.reason)}invalidateLiveConnection(t){if(this.resetCatalogRefreshState(),this.tools.clear(),this.resources=[],this.resourceTemplates=[],this.prompts=[],this.activeResourceSubscriptions.clear(),!t)this.desiredResourceSubscriptions.clear();if(!t)this.taskInteractions.clear();this.serverInfo=null,this.serverInstructions=void 0,this.consecutiveTerminalErrors=0}resetCatalogRefreshState(){this.catalogGeneration++,this.toolRefreshPromise=void 0,this.toolRefreshRequested=!1,this.contentRefreshPromise=void 0,this.requestedContentCatalogs.clear(),this.contentRefreshReason="manual"}emitClientError(t){if(this.listenerCount("error")>0)this.emit("error",t)}async ping(t=1e4){let i=this.sdkClient;if(!i||this.status!=="connected")throw Error(`MCP server "${this.serverName}" is not connected`);let n=new AbortController,s=setTimeout(()=>n.abort("MCP health check timeout"),t);s.unref();try{await i.ping({signal:n.signal,timeout:t,maxTotalTimeout:t})}catch(e){if(n.signal.aborted)throw Error(`MCP server "${this.serverName}" health check timed out after ${t}ms`);throw e}finally{clearTimeout(s)}}async disconnect(){this.desiredConnected=!1,this.connectionGeneration++,this.connectAbortController?.abort("MCP client disconnected"),this.recoveryAbortController?.abort("MCP client disconnected"),this.healthMonitor?.stop();let t=this.sdkClient;if(this.sdkClient=null,t)t.onclose=void 0,t.onerror=void 0,await t.close().catch(()=>{return});await Promise.allSettled([this.connectPromise,this.recoveryPromise].filter((i)=>i!==void 0)),this.invalidateLiveConnection(!1),this.recoveryState=void 0,await this.oauthProvider?.dispose(),this.setStatus("disconnected"),this.emit("disconnected")}async callTool(t,i={},n={}){let s=this.sdkClient;if(!s||this.status!=="connected")throw Error("客户端未连接到服务器");if(!this.tools.has(t))throw Error(`工具 "${t}" 不存在`);if(this.activeInteraction)throw Error(`MCP server "${this.serverName}" does not allow overlapping interactive tool calls`);let e=gt(this.config),r=Symbol(t);this.activeInteraction={token:r,context:n,samplingRequests:0,samplingInFlight:!1};let o=new AbortController,u=setTimeout(()=>o.abort("mcp-tool-timeout"),e.totalTimeoutMs);u.unref();let d=n.signal?AbortSignal.any([n.signal,o.signal]):o.signal,p={count:0};try{return await s.callTool({name:t,arguments:i},St,{signal:d,timeout:e.idleTimeoutMs,resetTimeoutOnProgress:!0,maxTotalTimeout:e.totalTimeoutMs,onprogress:(M)=>{let w=mt(M,p,e);if(w&&!d.aborted&&this.activeInteraction?.token===r)n.progressHandler?.(w),this.emit("toolProgress",{serverName:this.serverName,toolName:t,...w})}})}catch(c){if(n.signal?.aborted)throw new DOMException(String(n.signal.reason||"MCP tool call cancelled"),"AbortError");if(o.signal.aborted&&!n.signal?.aborted)throw new P(R.RequestTimeout,`MCP server "${this.serverName}" tool "${t}" timed out after ${e.totalTimeoutMs}ms`);throw console.error(`[McpClient] 调用工具 "${t}" 失败:`,c),c}finally{if(clearTimeout(u),this.activeInteraction?.token===r)this.activeInteraction=void 0}}getToolTaskSupport(t){return this.tools.get(t)?.taskSupport}async createToolTask(t,i,n,s,e){let r=this.sdkClient;if(!r||this.status!=="connected")throw Error("MCP client is not connected");if(!this.taskPolicy.enabled)throw Error(`MCP tasks are disabled for server "${this.serverName}"`);if(!r.getServerCapabilities()?.tasks?.requests?.tools?.call)throw Error(`MCP server "${this.serverName}" does not support task-augmented tools/call`);let o=this.getToolTaskSupport(t);if(o!=="required"&&o!=="optional")throw Error(`MCP tool "${t}" does not support task execution`);if(this.activeInteraction)throw Error(`MCP server "${this.serverName}" does not allow overlapping interactive task creation`);let u=gt(this.config),d=Symbol(t),p={token:d,context:{...n,signal:s},samplingRequests:0,samplingInFlight:!1};this.activeInteraction=p;let c={count:0},M=r.experimental.tasks.callToolStream({name:t,arguments:i},St,{signal:s,task:{ttl:e??this.taskPolicy.defaultTtlMs,pollInterval:this.taskPolicy.pollIntervalMs},timeout:u.idleTimeoutMs,maxTotalTimeout:u.totalTimeoutMs,resetTimeoutOnProgress:!0,onprogress:(y)=>{let E=mt(y,c,u);if(E&&!s.aborted&&this.hasInteractionToken(d))n.progressHandler?.(E),this.emit("toolProgress",{serverName:this.serverName,toolName:t,...E})}}),w=!1;try{let y=await M.next();if(await M.return(void 0),y.done||y.value.type!=="taskCreated"){if(!y.done&&y.value.type==="error")throw y.value.error;throw Error(`MCP tool "${t}" did not create a task`)}if(this.sdkClient!==r)throw Error("MCP client changed while creating a task");let E=Ut(y.value.task,this.taskPolicy);return this.taskInteractions.set(E.taskId,p),w=!0,this.emit("taskCreated",{serverName:this.serverName,toolName:t,task:E}),E}finally{if(this.activeInteraction?.token===d)this.activeInteraction=void 0;if(!w){for(let[y,E]of this.taskInteractions)if(E.token===d)this.taskInteractions.delete(y)}}}async getToolTask(t,i,n){let s=this.requireTaskClient(),e=await s.experimental.tasks.getTask(t,{signal:n,timeout:this.taskPolicy.pollIntervalMs+1e4,maxTotalTimeout:this.taskPolicy.pollIntervalMs+1e4});if(this.sdkClient!==s)throw Error("MCP client changed while reading a task");return Ut(e,this.taskPolicy,{taskId:t,createdAt:i})}async getToolTaskResult(t,i,n=this.taskPolicy.maxLifetimeMs){let s=this.requireTaskClient(),e=Math.max(1,Math.min(n,this.taskPolicy.maxLifetimeMs)),r=await s.experimental.tasks.getTaskResult(t,St,{signal:i,timeout:e,maxTotalTimeout:e});if(this.sdkClient!==s)throw Error("MCP client changed while reading a task result");return r}async cancelToolTask(t,i){let n=this.requireTaskClient();if(!n.getServerCapabilities()?.tasks?.cancel)throw Error(`MCP server "${this.serverName}" does not support task cancellation`);if(await n.experimental.tasks.cancelTask(t,{signal:i,timeout:15000,maxTotalTimeout:15000}),this.sdkClient!==n)throw Error("MCP client changed while cancelling a task")}async normalizeToolTaskResult(t){return j(t,this.runtimeOptions.artifactWriter)}releaseTaskInteraction(t){this.taskInteractions.delete(t)}async waitUntilConnected(t,i){if(this.status==="connected"&&this.sdkClient)return;if(!this.desiredConnected)throw Error(`MCP server "${this.serverName}" is disconnected`);await new Promise((n,s)=>{let e=setTimeout(()=>{d(),s(Error(`MCP server "${this.serverName}" recovery timed out`))},i);e.unref();let r=()=>{d(),n()},o=()=>{if(this.desiredConnected)return;d(),s(Error(`MCP server "${this.serverName}" was disconnected`))},u=()=>{d(),s(new DOMException(String(t.reason||"MCP task recovery cancelled"),"AbortError"))},d=()=>{clearTimeout(e),this.off("connected",r),this.off("disconnected",o),t.removeEventListener("abort",u)};if(this.on("connected",r),this.on("disconnected",o),t.addEventListener("abort",u,{once:!0}),t.aborted)u()})}requireTaskClient(){let t=this.sdkClient;if(!t||this.status!=="connected"||!this.taskPolicy.enabled)throw Error(`MCP server "${this.serverName}" task client is unavailable`);if(!t.getServerCapabilities()?.tasks?.requests?.tools?.call)throw Error(`MCP server "${this.serverName}" does not support task-augmented tools/call`);return t}hasInteractionToken(t){if(this.activeInteraction?.token===t)return!0;return[...this.taskInteractions.values()].some((i)=>i.token===t)}registerRootHandler(t){t.setRequestHandler(Ms,async()=>({roots:this.roots.map((i)=>({...i}))}))}resolveInteraction(t){let i=t._meta?.["io.modelcontextprotocol/related-task"]?.taskId;return i?this.taskInteractions.get(i):this.activeInteraction}registerTaskStatusHandler(t){t.setNotificationHandler(Ts,(i)=>{this.emit("taskStatus",i.params)})}registerSamplingHandler(t,i){t.setRequestHandler(ps,async(n,s)=>{let e=this.resolveInteraction(n.params);if(!e?.context.confirmationHandler||!e.context.samplingHandler)throw new P(R.InvalidRequest,"MCP sampling requires an active interactive Session");if(e.samplingInFlight)throw new P(R.InvalidRequest,"MCP server does not allow overlapping sampling requests");e.samplingInFlight=!0;try{if(e.samplingRequests++,e.samplingRequests>i.maxRequestsPerToolCall)throw new P(R.InvalidRequest,`MCP sampling exceeded ${i.maxRequestsPerToolCall} requests for one tool call`);let r=e.context.signal?AbortSignal.any([e.context.signal,s.signal]):s.signal;if(r.aborted)throw new P(R.InvalidRequest,"MCP sampling was cancelled");let o;try{o=Mn(n.params,i)}catch(p){throw new P(R.InvalidRequest,p instanceof Error?p.message:String(p))}let u=await e.context.confirmationHandler.requestConfirmation({type:"mcpSampling",kind:"execute",toolName:`MCP sampling: ${this.serverName}`,title:"MCP model sampling request",message:`MCP server "${this.serverName}" wants to call the current Session model with up to ${o.maxTokens} output tokens.`,details:o.preview,risks:[`May consume up to ${o.maxTokens} output tokens`,"The model response will be returned to the MCP server"]},r);if(r.aborted||u.reason===Xt||u.reason==="timeout")throw new P(R.InvalidRequest,"MCP sampling was cancelled");if(!u.approved)throw new P(R.InvalidRequest,"MCP sampling was denied");let d=await e.context.samplingHandler(o,r);return this.emit("samplingCompleted",{serverName:this.serverName,model:d.model,maxTokens:o.maxTokens}),d}finally{e.samplingInFlight=!1}})}registerElicitationHandlers(t){t.setRequestHandler(cs,async(i,n)=>{let s=this.resolveInteraction(i.params)?.context;if(!s?.confirmationHandler)return this.emit("elicitationCancelled",{serverName:this.serverName,reason:"no-interaction-handler"}),{action:"cancel"};let e=s.signal?AbortSignal.any([s.signal,n.signal]):n.signal;if(e.aborted)return{action:"cancel"};let r;try{r=Di(this.serverName,i.params)}catch(o){return this.emit("elicitationRejected",{serverName:this.serverName,reason:o instanceof Error?o.message:String(o)}),{action:"decline"}}try{let o=s.sessionId&&s.workspaceRoot&&s.permissionMode?{projectDir:s.workspaceRoot,sessionId:s.sessionId,permissionMode:s.permissionMode,abortSignal:e}:void 0,u=o?await Bt.getInstance().executeElicitationHooks(r,o):{},d;if(u.blockedReason)d={action:"decline"};else if(u.response)d=u.response;else{let M=await s.confirmationHandler.requestConfirmation({type:"mcpElicitation",message:r.message,title:`MCP input requested by ${this.serverName}`,mcpElicitation:r},e),w=this.resolveElicitationAction(M,e);if(d=M.elicitation??{action:w},w==="accept"&&r.mode==="url"&&M.openExternalUrl&&r.url)await bs(r.url,{wait:!1})}let p=o?await Bt.getInstance().executeElicitationResultHooks(r,d,o):{};if(p.blockedReason)d={action:"cancel"};else if(p.response)d=p.response;let c=Fi(r,d);return this.emit("elicitationResolved",{serverName:this.serverName,mode:r.mode,action:c.action,elicitationId:r.elicitationId}),c}catch(o){return this.emit("elicitationCancelled",{serverName:this.serverName,reason:o instanceof Error?o.message:String(o)}),{action:"cancel"}}}),t.setNotificationHandler(us,(i)=>{this.emit("elicitationCompleted",{serverName:this.serverName,elicitationId:i.params.elicitationId})})}resolveElicitationAction(t,i){if(i.aborted||t.reason===Xt||t.reason==="timeout")return"cancel";if(t.elicitation)return t.elicitation.action;return t.approved?"accept":"decline"}async createTransport(){let{type:t,command:i,args:n,env:s,cwd:e,url:r,headers:o,oauth:u}=this.config,d;if(u?.enabled){if(this.runtimeOptions.oauthCredentialAccess===!1||!this.oauthProvider)throw new U(this.serverName);if(!await this.oauthProvider.hasUsableCredentials())throw new zt(this.serverName);d=this.oauthProvider}if(t==="stdio"){if(!i)throw Error("stdio 传输需要 command 参数");let p={};for(let[c,M]of Object.entries(process.env))if(M!==void 0)p[c]=M;return new os({command:i,args:n||[],env:{...p,...s},cwd:e,stderr:"ignore"})}else if(t==="sse"){if(!r)throw Error("sse 传输需要 url 参数");return new ds(new URL(r),{requestInit:{headers:o},...u?.enabled?{fetch:xt}:{},...d?{authProvider:d}:{}})}else if(t==="http"){if(!r)throw Error("http 传输需要 url 参数");let{StreamableHTTPClientTransport:p}=await import("@modelcontextprotocol/sdk/client/streamableHttp.js");return new p(new URL(r),{requestInit:{headers:o},...u?.enabled?{fetch:xt}:{},...d?{authProvider:d}:{}})}throw Error(`不支持的传输类型: ${t}`)}async refreshTools(t="manual"){if(this.toolRefreshRequested=!0,this.toolRefreshPromise)return this.toolRefreshPromise;let i=this.catalogGeneration,n=(t==="notification"?new Promise((s)=>{setTimeout(s,25).unref()}):Promise.resolve()).then(()=>this.runToolRefresh(t)).finally(()=>{if(i!==this.catalogGeneration||this.toolRefreshPromise!==n)return;let s=this.toolRefreshRequested;if(this.toolRefreshPromise=void 0,this.toolRefreshRequested=!1,s&&this.sdkClient)this.refreshTools("notification")});return this.toolRefreshPromise=n,n}async waitForToolRefresh(){while(this.toolRefreshPromise)await this.toolRefreshPromise}async runToolRefresh(t){let i=t;for(let n=0;n<3&&this.toolRefreshRequested;n++){this.toolRefreshRequested=!1;try{await this.fetchAndPublishTools(i)}catch(s){if(this.emit("toolsRefreshFailed",{serverName:this.serverName,reason:i,error:s instanceof Error?s:Error(String(s))}),i!=="notification")throw s;return}i="notification"}}async fetchAndPublishTools(t){let i=this.sdkClient;if(!i)throw Error("MCP client is not connected");let n=[],s=new Set,e;for(let p=0;p<it;p++){let c=await i.listTools(e?{cursor:e}:void 0);if(n.push(...c.tools),n.length>l)throw Error(`MCP tool catalog exceeds ${l} tools`);if(e=c.nextCursor,!e)break;if(s.has(e))throw Error("MCP tool catalog returned a repeated cursor");if(s.add(e),p===it-1)throw Error(`MCP tool catalog exceeds ${it} pages`)}let r=Zi(n);if(this.sdkClient!==i)throw Error("MCP client changed while refreshing tools");let o=this.availableTools,u=Qi(o,r);if(this.tools=new Map(r.map((p)=>[p.name,p])),!nt(u))return;this.toolCatalogRevision++;let d={revision:this.toolCatalogRevision,reason:t,...u};this.emit("toolsUpdated",this.availableTools,d)}async refreshContentCatalogs(t="manual",i=["resources","prompts"]){let n=this.sdkClient?.getServerCapabilities();for(let r of i){if(r==="resources"&&n?.resources)this.requestedContentCatalogs.add(r);if(r==="prompts"&&n?.prompts)this.requestedContentCatalogs.add(r)}if(this.requestedContentCatalogs.size===0)return;if(this.contentRefreshPromise){if(t!=="notification")this.contentRefreshReason=t;return this.contentRefreshPromise}this.contentRefreshReason=t;let s=this.catalogGeneration,e=(t==="notification"?new Promise((r)=>{setTimeout(r,25).unref()}):Promise.resolve()).then(()=>this.runContentCatalogRefresh()).finally(()=>{if(s!==this.catalogGeneration||this.contentRefreshPromise!==e)return;let r=this.requestedContentCatalogs.size>0;if(this.contentRefreshPromise=void 0,this.contentRefreshReason="manual",r&&this.sdkClient)this.refreshContentCatalogs("notification")});return this.contentRefreshPromise=e,e}async waitForCatalogRefresh(){while(this.toolRefreshPromise||this.contentRefreshPromise)await Promise.all([this.toolRefreshPromise??Promise.resolve(),this.contentRefreshPromise??Promise.resolve()])}async runContentCatalogRefresh(){for(let t=0;t<3&&this.requestedContentCatalogs.size>0;t++){let i=[...this.requestedContentCatalogs];this.requestedContentCatalogs.clear();let n=this.contentRefreshReason;this.contentRefreshReason="notification";let s=[];for(let e of i)try{if(e==="resources")await this.fetchAndPublishResourceCatalog(n);else await this.fetchAndPublishPromptCatalog(n)}catch(r){let o=r instanceof Error?r:Error(String(r));s.push(o),this.emit("contentCatalogRefreshFailed",{serverName:this.serverName,catalog:e,reason:n,error:o})}if(s.length>0&&n!=="notification")throw AggregateError(s,`Failed to refresh MCP content catalogs for "${this.serverName}"`)}}async fetchAndPublishResourceCatalog(t){let i=this.sdkClient;if(!i)throw Error("MCP client is not connected");let n=await this.fetchContentPages("resource",q,(d)=>i.listResources(d?{cursor:d}:void 0),(d)=>d.resources),s=await this.fetchContentPages("resource template",K,(d)=>i.listResourceTemplates(d?{cursor:d}:void 0),(d)=>d.resourceTemplates),e=Ci(n),r=ki(s);if(this.sdkClient!==i)throw Error("MCP client changed while refreshing resource catalogs");let o=I(this.resources,e,(d)=>d.uri),u=I(this.resourceTemplates,r,(d)=>d.uriTemplate);this.resources=e,this.resourceTemplates=r,await this.reconcileResourceSubscriptions(i),this.publishContentCatalogDelta("resources",t,o),this.publishContentCatalogDelta("resourceTemplates",t,u)}async fetchAndPublishPromptCatalog(t){let i=this.sdkClient;if(!i)throw Error("MCP client is not connected");let n=await this.fetchContentPages("prompt",W,(r)=>i.listPrompts(r?{cursor:r}:void 0),(r)=>r.prompts),s=Oi(n);if(this.sdkClient!==i)throw Error("MCP client changed while refreshing prompts");let e=I(this.prompts,s,(r)=>r.name);this.prompts=s,this.publishContentCatalogDelta("prompts",t,e)}async fetchContentPages(t,i,n,s){let e=[],r=new Set,o;for(let u=0;u<Pt;u++){let d=await n(o);if(e.push(...s(d)),e.length>i)throw Error(`MCP ${t} catalog exceeds ${i} entries`);if(o=d.nextCursor,!o)return e;if(r.has(o))throw Error(`MCP ${t} catalog returned a repeated cursor`);r.add(o)}throw Error(`MCP ${t} catalog exceeds ${Pt} pages`)}publishContentCatalogDelta(t,i,n){if(!Li(n))return;this.contentCatalogRevision++;let s={revision:this.contentCatalogRevision,kind:t,reason:i,...n};this.emit("contentCatalogUpdated",this.contentCatalog,s)}registerResourceNotificationHandler(t){t.setNotificationHandler(ys,(i)=>{let n=i.params.uri;if(this.sdkClient!==t||!this.activeResourceSubscriptions.has(n))return;this.contentCatalogRevision++,this.emit("resourceUpdated",{revision:this.contentCatalogRevision,serverName:this.serverName,uri:n})})}registerLoggingHandler(t){t.setNotificationHandler(ws,(i)=>{if(this.sdkClient!==t||!this.loggingPolicy.enabled||!pn(i.params.level,this.loggingPolicy.level))return;let n=Date.now();if(n-this.logWindowStartedAt>=1000)this.logWindowStartedAt=n,this.logEventsInWindow=0,this.logRateWarningEmitted=!1;if(this.logEventsInWindow>=rn){if(!this.logRateWarningEmitted)this.logRateWarningEmitted=!0,this.emit("log",un(1,{now:n}));return}this.logEventsInWindow++;let s=lt({level:i.params.level,logger:i.params.logger,data:i.params.data},{exposeDetails:this.runtimeOptions.exposeLogDetails,now:n});this.emit("log",s)})}async configureLogging(t){if(this.logWindowStartedAt=Date.now(),this.logEventsInWindow=0,this.logRateWarningEmitted=!1,!this.loggingPolicy.enabled||!t.getServerCapabilities()?.logging)return;try{await t.setLoggingLevel(this.loggingPolicy.level)}catch(i){if(this.sdkClient!==t)return;let n={serverName:this.serverName,level:this.loggingPolicy.level,error:k(i)};this.emit("loggingSetupFailed",n),this.emit("log",{...lt({level:"warning",logger:"blade.mcp.logging",data:`Failed to set MCP logging level: ${n.error}`},{exposeDetails:this.runtimeOptions.exposeLogDetails}),synthetic:!0})}}async setLoggingLevel(t){if(!on(t))throw Error("Invalid MCP logging level");let i=this.sdkClient;if(!i)throw Error("MCP client is not connected");if(!i.getServerCapabilities()?.logging)throw Error(`MCP server "${this.serverName}" does not support logging`);if(await i.setLoggingLevel(t),this.sdkClient!==i)throw Error("MCP client changed while setting logging level");this.loggingPolicy={enabled:!0,level:t},this.emit("loggingLevelChanged",{serverName:this.serverName,level:t})}async complete(t,i){let n=this.sdkClient;if(!n||this.status!=="connected")throw Error("MCP client is not connected");if(!n.getServerCapabilities()?.completions)throw Error(`MCP server "${this.serverName}" does not support completions`);if(this.completionCallsInFlight>=oi)throw Error(`MCP server "${this.serverName}" has too many completion requests`);let s=pi(t,this.contentCatalog);this.completionCallsInFlight++;try{let e=await n.complete(s,{signal:i,timeout:ht,maxTotalTimeout:ht});if(this.sdkClient!==n)throw Error("MCP client changed while completing an argument");return ui(e)}catch(e){if(i?.aborted)throw new DOMException(String(i.reason||"MCP completion cancelled"),"AbortError");throw e}finally{this.completionCallsInFlight--}}async readResource(t){let i=this.sdkClient;if(!i)throw Error("MCP client is not connected");if(!this.resources.some((n)=>n.uri===t))throw Error(`MCP resource "${t}" is not present in server "${this.serverName}" catalog`);return gi(await i.readResource({uri:t}))}async getPrompt(t,i={}){let n=this.sdkClient;if(!n)throw Error("MCP client is not connected");let s=this.prompts.find((r)=>r.name===t);if(!s)throw Error(`MCP prompt "${t}" is not present in server "${this.serverName}" catalog`);let e=new Set(s.arguments.map((r)=>r.name));for(let[r,o]of Object.entries(i)){if(["__proto__","constructor","prototype"].includes(r))throw Error(`Unsafe argument "${r}" for MCP prompt "${t}"`);if(!e.has(r))throw Error(`Unknown argument "${r}" for MCP prompt "${t}"`);if(Buffer.byteLength(o)>16384)throw Error(`Argument "${r}" for MCP prompt "${t}" is too large`)}for(let r of s.arguments)if(r.required&&i[r.name]===void 0)throw Error(`Required argument "${r.name}" is missing for MCP prompt "${t}"`);return mi(await n.getPrompt({name:t,arguments:i}))}async setResourceSubscription(t,i){let n=this.sdkClient;if(!n)throw Error("MCP client is not connected");if(i){if(!this.resources.some((s)=>s.uri===t))throw Error(`MCP resource "${t}" is not present in server "${this.serverName}" catalog`);if(this.desiredResourceSubscriptions.has(t)&&this.activeResourceSubscriptions.has(t))return;if(!this.desiredResourceSubscriptions.has(t)&&this.desiredResourceSubscriptions.size>=at)throw Error(`MCP resource subscriptions exceed ${at}`);if(!n.getServerCapabilities()?.resources?.subscribe)throw Error(`MCP server "${this.serverName}" does not support resource subscriptions`);if(await n.subscribeResource({uri:t}),this.sdkClient!==n)throw Error("MCP client changed while subscribing to resource");this.desiredResourceSubscriptions.add(t),this.activeResourceSubscriptions.add(t);return}if(!this.desiredResourceSubscriptions.has(t))return;if(this.activeResourceSubscriptions.has(t)){if(await n.unsubscribeResource({uri:t}),this.sdkClient!==n)throw Error("MCP client changed while unsubscribing from resource")}this.activeResourceSubscriptions.delete(t),this.desiredResourceSubscriptions.delete(t)}async reconcileResourceSubscriptions(t){if(this.sdkClient!==t)return;let i=new Set(this.resources.map((n)=>n.uri));for(let n of this.activeResourceSubscriptions)if(!i.has(n))this.activeResourceSubscriptions.delete(n);if(!t.getServerCapabilities()?.resources?.subscribe){this.activeResourceSubscriptions.clear();return}for(let n of this.desiredResourceSubscriptions){if(!i.has(n)||this.activeResourceSubscriptions.has(n))continue;try{if(await t.subscribeResource({uri:n}),this.sdkClient!==t)return;this.activeResourceSubscriptions.add(n)}catch(s){this.emit("resourceSubscriptionRestoreFailed",{serverName:this.serverName,uri:n,error:k(s)})}}}setStatus(t){let i=this.status;if(i===t)return;this.status=t,this.emit("statusChanged",t,i)}async initialize(){return this.connect()}async destroy(){return this.disconnect()}async connectToServer(t){return this.connect()}async disconnectFromServer(t){return this.disconnect()}async listResources(t){return structuredClone(this.resources)}async listResourceTemplates(){return structuredClone(this.resourceTemplates)}async listPrompts(){return structuredClone(this.prompts)}async listTools(t){return this.availableTools}}class O extends fs{runtimeOptions;static instance=null;servers=new Map;isDiscovering=!1;catalogRevision=0;contentCatalogRevision=0;connectionRevision=0;logRevision=0;instructionsRevision=0;logEntries=[];projectedTools=new Map;constructor(t={}){super();this.runtimeOptions=t}static getInstance(){if(!O.instance)O.instance=new O;return O.instance}static createIsolated(t={}){return new O(t)}async registerServer(t,i,n={}){if(this.servers.has(t))throw Error(`MCP服务器 "${t}" 已经注册`);let s=new Yt(i,t,i.healthCheck,this.runtimeOptions),e={config:i,client:s,status:"disconnected",tools:[],contentCatalog:{resources:[],resourceTemplates:[],prompts:[]},logging:s.logging};if(this.setupClientEventHandlers(s,e,t),this.servers.set(t,e),this.emit("serverRegistered",t,e),n.connect===!1)return;try{await this.connectServer(t)}catch(r){console.warn(`MCP服务器 "${t}" 连接失败:`,r)}}async unregisterServer(t){let i=this.servers.get(t);if(!i)return;try{await T.getInstance().cancelClient(i.client),await i.client.disconnect()}catch(n){console.warn(`断开MCP服务器 "${t}" 时出错:`,n)}this.servers.delete(t),this.logEntries=this.logEntries.filter((n)=>n.serverName!==t),this.emit("serverUnregistered",t)}async connectServer(t){let i=this.servers.get(t);if(!i)throw Error(`MCP服务器 "${t}" 未注册`);if(i.status==="connected")return;try{i.status="connecting",await i.client.connect(),i.connectedAt=new Date,i.lastError=void 0,i.tools=i.client.availableTools}catch(n){throw i.lastError=n,i.status="error",n}}async disconnectServer(t){let i=this.servers.get(t);if(!i)return;await T.getInstance().cancelClient(i.client),await i.client.disconnect(),i.connectedAt=void 0}async reconnectServer(t){let i=this.servers.get(t);if(!i)throw Error(`MCP服务器 "${t}" 未注册`);await T.getInstance().cancelClient(i.client),await i.client.disconnect();try{i.status="connecting",await i.client.connect(),i.connectedAt=new Date,i.lastError=void 0,i.tools=i.client.availableTools}catch(n){throw i.lastError=n,i.status="error",n}}async getAvailableTools(){return[...this.projectedTools.values()]}getCatalogSnapshot(){return{revision:this.catalogRevision,tools:[...this.projectedTools.values()]}}async waitForCatalogIdle(){await Promise.all([...this.servers.values()].map((t)=>t.client.waitForCatalogRefresh()))}getContentCatalogSnapshot(){let t=[],i=[],n=[];for(let[s,e]of this.servers){if(e.status!=="connected")continue;t.push(...e.contentCatalog.resources.map((r)=>({server:s,...structuredClone(r)}))),i.push(...e.contentCatalog.resourceTemplates.map((r)=>({server:s,...structuredClone(r)}))),n.push(...e.contentCatalog.prompts.map((r)=>({server:s,...structuredClone(r)})))}return{revision:this.contentCatalogRevision,resources:t,resourceTemplates:i,prompts:n}}getLogSnapshot(t,i={}){let n=Number.isSafeInteger(i.afterRevision)&&(i.afterRevision??0)>=0?i.afterRevision??0:0,s=Number.isSafeInteger(i.limit)&&(i.limit??0)>=1&&(i.limit??0)<=B?i.limit??B:B,e=this.logEntries.filter((r)=>r.revision>n&&(!t||r.serverName===t)).slice(-s).map((r)=>structuredClone(r));return{revision:this.logRevision,entries:e}}getInstructionsSnapshot(){let t=[];for(let[i,n]of this.servers){if(n.status!=="connected"||!n.instructions)continue;t.push({serverName:i,...structuredClone(n.instructions)})}return t.sort((i,n)=>i.serverName.localeCompare(n.serverName)),{revision:this.instructionsRevision,instructions:t}}async refreshContentCatalogs(t){if(t){await this.requireConnectedServer(t).client.refreshContentCatalogs("manual");return}await Promise.all([...this.servers.values()].filter((i)=>i.status==="connected").map((i)=>i.client.refreshContentCatalogs("manual")))}async readResource(t,i){return this.requireConnectedServer(t).client.readResource(i)}async getPrompt(t,i,n={}){return this.requireConnectedServer(t).client.getPrompt(i,n)}async complete(t,i,n){return this.requireConnectedServer(t).client.complete(i,n)}async startTask(t,i,n,s,e,r,o){let u=this.requireConnectedServer(t);if(!u.tools.some((d)=>d.name===i))throw Error(`MCP tool "${i}" is not present in server "${t}" catalog`);return T.getInstance().start({client:u.client,serverName:t,toolName:i,arguments:n,owner:s,interactionContext:e,signal:r,ttlMs:o})}listTasks(t,i){return T.getInstance().list(t,i)}getTask(t,i){return T.getInstance().get(t,i)}waitForTask(t,i,n,s){return T.getInstance().wait(t,i,n,s)}cancelTask(t,i,n){return T.getInstance().cancel(t,i,n)}async setResourceSubscription(t,i,n){await this.requireConnectedServer(t).client.setResourceSubscription(i,n)}async setServerLoggingLevel(t,i){let n=this.requireConnectedServer(t);await n.client.setLoggingLevel(i),n.logging=n.client.logging}async findTool(t){return this.projectedTools.get(t)??null}getToolsByServer(t){let i=this.servers.get(t);if(!i||i.status!=="connected")return[];return i.tools.map((n)=>Tt(i.client,t,n,Lt(t,n.name),this.runtimeOptions.artifactWriter))}getServerStatus(t){return this.servers.get(t)||null}getAllServers(){return new Map(this.servers)}async getServerOAuthStatus(t){let i=this.servers.get(t);if(!i)throw Error(`MCP服务器 "${t}" 未注册`);return i.client.getOAuthStatus()}async beginOAuthLogin(t,i={}){let n=this.servers.get(t);if(!n)throw Error(`MCP服务器 "${t}" 未注册`);let s=await n.client.beginOAuthLogin(i);this.emit("serverOAuthStatusChanged",t,"authorizing");let e=s.completion.then(async()=>{this.emit("serverOAuthCompleted",t),this.emit("serverOAuthStatusChanged",t,"authenticated");try{await this.reconnectServer(t)}catch(r){n.lastError=r instanceof Error?r:Error(String(r)),n.status="error",this.emit("serverError",t,n.lastError)}},(r)=>{throw n.lastError=r instanceof Error?r:Error(String(r)),this.emit("serverOAuthError",t,n.lastError),this.emit("serverOAuthStatusChanged",t,"error"),n.lastError});return e.catch(()=>{return}),{...s,completion:e}}async logoutOAuth(t){let i=this.servers.get(t);if(!i)throw Error(`MCP服务器 "${t}" 未注册`);await i.client.logoutOAuth(),i.status="disconnected",i.connectedAt=void 0,i.lastError=void 0,i.tools=[],this.emit("serverOAuthStatusChanged",t,"unauthenticated")}async refreshAllTools(){let t=[];for(let[i,n]of this.servers)if(n.status==="connected")t.push(this.refreshServerTools(i));await Promise.allSettled(t)}async refreshServerTools(t){let i=this.servers.get(t);if(!i||i.status!=="connected")return;try{await i.client.refreshTools("manual")}catch(n){throw console.warn(`刷新服务器 "${t}" 工具列表失败:`,n),n}}setupClientEventHandlers(t,i,n){t.on("connected",(s)=>{if(i.status="connected",i.connectedAt=new Date,i.lastError=void 0,i.tools=t.availableTools,i.contentCatalog=t.contentCatalog,i.logging=t.logging,i.instructions=this.fitInstructionBudget(n,t.instructions),this.publishCatalog(n,"connection"),this.publishInitialContentCatalog(n,i.contentCatalog),i.instructions)this.publishInstructions(n,"added","connection",i.instructions);this.emit("serverConnected",n,s)}),t.on("disconnected",()=>{i.status="disconnected",i.connectedAt=void 0,i.lastError=void 0,i.recovery=void 0,this.invalidateServerProjection(n,i),this.emit("serverDisconnected",n)}),t.on("error",(s)=>{i.status="error",i.lastError=s,this.invalidateServerProjection(n,i),this.emit("serverError",n,s)}),t.on("connectionLifecycleChanged",(s)=>{if(i.recovery=structuredClone(s),s.phase==="reconnecting")i.status="reconnecting",i.connectedAt=void 0,i.lastError=s.error?Error(s.error):i.lastError,this.invalidateServerProjection(n,i);else if(s.phase==="recovered")i.status="connected",i.lastError=void 0;else i.status="error",i.connectedAt=void 0,i.lastError=s.error?Error(s.error):i.lastError;this.publishConnectionLifecycle(n,s)}),t.on("toolsUpdated",(s,e)=>{let r=i.tools.length;if(i.tools=s,i.status==="connected"&&e)this.publishCatalog(n,e.reason);this.emit("toolsUpdated",n,s,r)}),t.on("toolsRefreshFailed",(s)=>{this.emit("catalogRefreshFailed",{serverName:n,...s})}),t.on("contentCatalogUpdated",(s,e)=>{if(i.contentCatalog=s,i.status!=="connected")return;this.publishContentCatalogChange(n,e.kind,e.reason,{added:e.added,removed:e.removed,updated:e.updated})}),t.on("contentCatalogRefreshFailed",(s)=>{this.emit("contentCatalogRefreshFailed",{serverName:n,...s})}),t.on("resourceUpdated",(s)=>{if(i.status!=="connected")return;this.contentCatalogRevision++;let e={revision:this.contentCatalogRevision,serverName:n,uri:s.uri};this.emit("resourceUpdated",e)}),t.on("statusChanged",(s,e)=>{if(i.status=s,s==="reconnecting"&&e==="connected")i.connectedAt=void 0,this.invalidateServerProjection(n,i);this.emit("serverStatusChanged",n,s,e)}),t.on("loggingLevelChanged",()=>{i.logging=t.logging,this.emit("serverLoggingLevelChanged",n,i.logging.level)}),t.on("log",(s)=>{this.publishLog(n,s)})}publishLog(t,i){this.logRevision++;let n={revision:this.logRevision,serverName:t,...structuredClone(i)};this.logEntries.push(n);let s=0;for(let e=this.logEntries.length-1;e>=0;e--){if(this.logEntries[e]?.serverName!==t)continue;if(s++,s>Tn)this.logEntries.splice(e,1)}while(this.logEntries.length>B)this.logEntries.shift();this.emit("log",structuredClone(n))}invalidateServerProjection(t,i){let n=i.contentCatalog,s=i.instructions!==void 0;if(i.tools=[],i.contentCatalog={resources:[],resourceTemplates:[],prompts:[]},i.instructions=void 0,this.publishCatalog(t,"disconnection"),this.publishRemovedContentCatalog(t,n),s)this.publishInstructions(t,"removed","disconnection")}fitInstructionBudget(t,i){if(!i)return;let n=0;for(let[s,e]of this.servers){if(s===t)continue;n+=e.instructions?.projectedBytes??0}return bn(i,Math.max(0,En-n))}publishInstructions(t,i,n,s){this.instructionsRevision++;let e={revision:this.instructionsRevision,serverName:t,action:i,reason:n,...s?{instruction:structuredClone(s)}:{}};this.emit("instructionsChanged",e)}publishConnectionLifecycle(t,i){this.connectionRevision++;let n={revision:this.connectionRevision,serverName:t,...structuredClone(i)};this.emit("connectionLifecycleChanged",n)}publishCatalog(t,i){let n=new Map;for(let[u,d]of this.servers){if(d.status!=="connected")continue;for(let p of d.tools){let c=Lt(u,p.name);if(n.has(c))throw Error(`Duplicate projected MCP tool "${c}"`);n.set(c,Tt(d.client,u,p,c,this.runtimeOptions.artifactWriter))}}let s=new Map([...this.projectedTools].map(([u,d])=>[u,JSON.stringify(d.getFunctionDeclaration())])),e=new Map([...n].map(([u,d])=>[u,JSON.stringify(d.getFunctionDeclaration())])),r={added:[...n.keys()].filter((u)=>!this.projectedTools.has(u)).sort(),removed:[...this.projectedTools.keys()].filter((u)=>!n.has(u)).sort(),updated:[...n.keys()].filter((u)=>this.projectedTools.has(u)&&s.get(u)!==e.get(u)).sort()};if(this.projectedTools=n,!nt(r))return;this.catalogRevision++;let o={revision:this.catalogRevision,serverName:t,reason:i,tools:[...n.values()],...r};this.emit("catalogChanged",o)}publishInitialContentCatalog(t,i){this.publishContentCatalogChange(t,"resources","connection",{added:i.resources.map((n)=>n.uri).sort(),removed:[],updated:[]}),this.publishContentCatalogChange(t,"resourceTemplates","connection",{added:i.resourceTemplates.map((n)=>n.uriTemplate).sort(),removed:[],updated:[]}),this.publishContentCatalogChange(t,"prompts","connection",{added:i.prompts.map((n)=>n.name).sort(),removed:[],updated:[]})}publishRemovedContentCatalog(t,i){this.publishContentCatalogChange(t,"resources","disconnection",{added:[],removed:i.resources.map((n)=>n.uri).sort(),updated:[]}),this.publishContentCatalogChange(t,"resourceTemplates","disconnection",{added:[],removed:i.resourceTemplates.map((n)=>n.uriTemplate).sort(),updated:[]}),this.publishContentCatalogChange(t,"prompts","disconnection",{added:[],removed:i.prompts.map((n)=>n.name).sort(),updated:[]})}publishContentCatalogChange(t,i,n,s){if(s.added.length===0&&s.removed.length===0&&s.updated.length===0)return;this.contentCatalogRevision++;let e={revision:this.contentCatalogRevision,serverName:t,kind:i,reason:n,...s};this.emit("contentCatalogChanged",e)}requireConnectedServer(t){let i=this.servers.get(t);if(!i)throw Error(`MCP服务器 "${t}" 未注册`);if(i.status!=="connected")throw Error(`MCP服务器 "${t}" 未连接`);return i}async discoverServers(){if(this.isDiscovering)return Array.from(this.servers.values());this.isDiscovering=!0,this.emit("discoveryStarted");try{return Array.from(this.servers.values())}finally{this.isDiscovering=!1,this.emit("discoveryCompleted")}}async registerServers(t){let i=Object.entries(t).map(([n,s])=>this.registerServer(n,s).catch((e)=>{return console.warn(`注册MCP服务器 "${n}" 失败:`,e),e}));await Promise.allSettled(i)}getStatistics(){let t=0,i=0,n=0;for(let s of this.servers.values())if(s.status==="connected")t++,i+=s.tools.length;else if(s.status==="error")n++;return{totalServers:this.servers.size,connectedServers:t,errorServers:n,totalTools:i,isDiscovering:this.isDiscovering}}async disconnectAll(){let t=[];for(let[i,n]of this.servers)t.push(T.getInstance().cancelClient(n.client).then(()=>n.client.disconnect()).catch((s)=>{console.warn(`断开 MCP 服务器 "${i}" 时出错:`,s)}));await Promise.allSettled(t),this.servers.clear(),this.projectedTools.clear(),this.logEntries=[]}}
25
- export{jt as Ia,T as Ja,jn as Ka,vs as La,te as Ma,Fi as Na,Lt as Oa,ts as Pa,O as Qa};
25
+ export{jt as Ja,T as Ka,jn as La,vs as Ma,te as Na,Fi as Oa,Lt as Pa,ts as Qa,O as Ra};
@@ -1,4 +1,4 @@
1
- import{p as c,q as v,r as d,s as m,t as l,u as a}from"./chunk-6112ra8v.js";import{ca as O,ja as S}from"./chunk-gmmhpp0k.js";import"./chunk-zrgfvc4k.js";import"./chunk-4n0efk4n.js";import"./chunk-ht8epjz2.js";import{Yb as M,gc as E}from"./chunk-a5r7c1n4.js";import"./chunk-wm896gnx.js";import{ge as f}from"./chunk-hj1c3k0m.js";import"./chunk-9xbwtjac.js";import{Le as h}from"./chunk-vz13c7fr.js";import"./chunk-fx9vm1n5.js";import{qf as I}from"./chunk-9zvxdc7t.js";import{sf as y,tf as R,uf as g}from"./chunk-7rjft1z9.js";import{vf as C}from"./chunk-v67st2xb.js";import"./chunk-v1mamd1x.js";import{Sf as w}from"./chunk-xgyx1hwx.js";import"./chunk-v508x7cg.js";import"./chunk-7xhw74hk.js";import"./chunk-k1tfry97.js";import"./chunk-f2y0gxyq.js";import"./chunk-k3ne93k8.js";import"./chunk-7wcxjbyg.js";import"./chunk-erext256.js";import"./chunk-yh34b6z0.js";import"./chunk-ewwrss2w.js";import"./chunk-53vh6vpt.js";import"./chunk-hv8nt7wj.js";import"./chunk-erhaedch.js";import"./chunk-g7pwwxvz.js";import"./chunk-28tzj187.js";import"./chunk-5xnht5vw.js";import{Si as A}from"./chunk-sd9bze9x.js";import"./chunk-514va7ce.js";import{aj as P}from"./chunk-jsv3e4k6.js";import"./chunk-n34qsnks.js";import"./chunk-5q4z0sfr.js";import"./chunk-0b67y4j1.js";import"./chunk-9kj19a8t.js";import"./chunk-fhsvz4b1.js";import"./chunk-gm2yfq3r.js";import"./chunk-n9819k4p.js";import"./chunk-7xtxvrh8.js";import"./chunk-sdapqhj0.js";import s from"yargs";import{hideBin as e}from"yargs/helpers";var i=new Set(Object.values(A));function t(j){if(j&&i.has(j))return j;return}function z(j){if(j.options.outputFormat==="json")j.io.stdout.write(`${JSON.stringify({response:j.response,...j.structuredOutput?{structured_output:j.structuredOutput,output_schema_digest:j.structuredOutputSchemaDigest}:{},input:j.requestInput,model:j.options.model,timestamp:new Date().toISOString()},null,2)}
1
+ import{p as c,q as v,r as d,s as m,t as l,u as a}from"./chunk-3aavhxe8.js";import{da as O,ka as S}from"./chunk-cvwcrr4h.js";import"./chunk-g01mth5d.js";import"./chunk-nj2bggcj.js";import"./chunk-30x3mcsb.js";import{Zb as M,hc as E}from"./chunk-y54mge74.js";import"./chunk-zzvs471p.js";import{he as f}from"./chunk-za0frk62.js";import"./chunk-53fc0yrq.js";import{Me as h}from"./chunk-y5wngtz0.js";import"./chunk-w33zjw8m.js";import{rf as I}from"./chunk-yk62xvqm.js";import{tf as y,uf as R,vf as g}from"./chunk-46t79ek8.js";import{wf as C}from"./chunk-nheny8xp.js";import"./chunk-jj4ggb04.js";import{Tf as w}from"./chunk-syq7j5b0.js";import"./chunk-v508x7cg.js";import"./chunk-t0gm0pn1.js";import"./chunk-1yq72zb7.js";import"./chunk-kqvzmnja.js";import"./chunk-0mr8nexh.js";import"./chunk-50vwafn5.js";import"./chunk-t89f4way.js";import"./chunk-mg03ydep.js";import"./chunk-3kszepm6.js";import"./chunk-wcps5gjm.js";import"./chunk-vbjgcn49.js";import"./chunk-06hkf59s.js";import"./chunk-sspk1ah8.js";import"./chunk-3y2x6fb6.js";import"./chunk-f194ct93.js";import{Ti as A}from"./chunk-kv458q06.js";import"./chunk-5v0jcyea.js";import{bj as P}from"./chunk-2f8d0km4.js";import"./chunk-ddvdc2p0.js";import"./chunk-2mk914vk.js";import"./chunk-j8hbddjp.js";import"./chunk-4cdk4mds.js";import"./chunk-rjbneaq0.js";import"./chunk-rvs364rz.js";import"./chunk-vw9paban.js";import"./chunk-4wx5sya5.js";import"./chunk-eg3ms291.js";import s from"yargs";import{hideBin as e}from"yargs/helpers";var i=new Set(Object.values(A));function t(j){if(j&&i.has(j))return j;return}function z(j){if(j.options.outputFormat==="json")j.io.stdout.write(`${JSON.stringify({response:j.response,...j.structuredOutput?{structured_output:j.structuredOutput,output_schema_digest:j.structuredOutputSchemaDigest}:{},input:j.requestInput,model:j.options.model,timestamp:new Date().toISOString()},null,2)}
2
2
  `);else if(j.options.outputFormat==="stream-json")j.io.stdout.write(`${JSON.stringify(j.structuredOutput?{type:"structured_output",output:j.structuredOutput,schema_digest:j.structuredOutputSchemaDigest}:{type:"response",content:j.response})}
3
3
  `);else j.io.stdout.write(`${j.response}
4
4
  `)}function n(j){return j.command("* [message]","Print response and exit (useful for pipes)",(B)=>B.positional("message",{describe:"Message to process",type:"string"}).option("p",{alias:"print",describe:"Print response and exit (useful for pipes)",type:"boolean"}).option("output-format",{describe:'Output format: "text", "json", "stream-json"',type:"string",default:"text"}).option("include-partial-messages",{describe:"Include partial message chunks as they arrive",type:"boolean"}).option("input-format",{describe:'Input format: "text", "stream-json"',type:"string",default:"text"}).option("json-schema",{alias:["jsonSchema"],describe:"Inline JSON Schema for the structured final response",type:"string"}).option("output-schema",{alias:["outputSchema"],describe:"Path to a JSON Schema file for the structured final response",type:"string"}).option("model",{describe:"Model for the current session",type:"string"}).option("append-system-prompt",{describe:"Append a system prompt to the default system prompt",type:"string"}).option("system-prompt",{describe:"Replace the default system prompt",type:"string"}).option("max-turns",{alias:["maxTurns"],describe:"Maximum conversation turns (-1: unlimited, N>0: limit to N turns)",type:"number"}),async(B)=>{if(!B.p)return;let q=await o(B);process.exit(q)})}async function o(j,B=process){let q;try{await c();let D=j.forkSession!==!0&&(j.continue===!0||typeof j.resume==="string"&&j.resume.length>0)?await d({message:j.message,_:j._}):await v({message:j.message,_:j._,defaultMessage:"Hello"}),K=D===void 0,T=K?{mode:"agent",content:""}:await m(D);if(T.mode==="output"){if(T.content)B.stdout.write(`${T.content}
@@ -0,0 +1 @@
1
+ import{sg as a,tg as b,ug as c}from"./chunk-0mr8nexh.js";import"./chunk-50vwafn5.js";import"./chunk-j8hbddjp.js";import"./chunk-4cdk4mds.js";import"./chunk-4wx5sya5.js";import"./chunk-eg3ms291.js";export{b as resolveModelConfig,c as getModelDisplayName,a as getModelApiKeyEnvironmentVariable};