blade-code 0.10.72 → 0.10.74

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 (120) hide show
  1. package/README.md +1 -1
  2. package/dist/blade.js +2 -2
  3. package/dist/{chunk-jyds9m8p.js → chunk-03947xkg.js} +1 -1
  4. package/dist/{chunk-2sdnmxts.js → chunk-0cbpjhq7.js} +1 -1
  5. package/dist/{chunk-cqeqjtxn.js → chunk-0m2bs3s2.js} +1 -1
  6. package/dist/chunk-16k0tc6h.js +160 -0
  7. package/dist/chunk-1qde0g23.js +1 -0
  8. package/dist/{chunk-mhyat4mq.js → chunk-1ykz47d9.js} +2 -2
  9. package/dist/{chunk-28wsyv32.js → chunk-1zkwxaa0.js} +1 -1
  10. package/dist/chunk-21bb1xda.js +1657 -0
  11. package/dist/{chunk-0kat01bw.js → chunk-22aaybx2.js} +1 -1
  12. package/dist/chunk-22s3r2xy.js +2 -0
  13. package/dist/chunk-2e6pcscc.js +1 -0
  14. package/dist/chunk-2faga011.js +2 -0
  15. package/dist/{chunk-yhnr8vdb.js → chunk-2m4mgw58.js} +2 -2
  16. package/dist/{chunk-gv3ed5gw.js → chunk-2qqmmxqf.js} +2 -2
  17. package/dist/{chunk-zac26wwd.js → chunk-2v10cw32.js} +1 -1
  18. package/dist/{chunk-e0hf1317.js → chunk-44zkyzrj.js} +1 -1
  19. package/dist/{chunk-y858e8pb.js → chunk-453tf6d0.js} +2 -2
  20. package/dist/chunk-465tgzab.js +44 -0
  21. package/dist/chunk-4mgjj8zg.js +1 -0
  22. package/dist/{chunk-6j9t1xbh.js → chunk-4ppgfhqd.js} +2 -2
  23. package/dist/chunk-54va5hc4.js +8 -0
  24. package/dist/chunk-63c25yhj.js +1 -0
  25. package/dist/{chunk-11gdqmbm.js → chunk-6ra5d8ng.js} +1 -1
  26. package/dist/{chunk-hhk5ecpv.js → chunk-74wb5e1h.js} +2 -2
  27. package/dist/{chunk-2fd5trh8.js → chunk-7hc84akg.js} +2 -2
  28. package/dist/{chunk-z7vj2xrg.js → chunk-7kf3hwp3.js} +3 -3
  29. package/dist/{chunk-yjj7q7hy.js → chunk-8asewt01.js} +1 -1
  30. package/dist/chunk-8w1gtvy0.js +22 -0
  31. package/dist/{chunk-6v7f2cv9.js → chunk-8zpsw401.js} +4 -4
  32. package/dist/{chunk-zf96d5we.js → chunk-99nevk7k.js} +1 -1
  33. package/dist/chunk-a6kbpq05.js +1 -0
  34. package/dist/chunk-aqzbsxjh.js +1 -0
  35. package/dist/chunk-bawbgvm3.js +6 -0
  36. package/dist/{chunk-wvg81sd9.js → chunk-bj5msq36.js} +1 -1
  37. package/dist/chunk-bxtw5f52.js +6 -0
  38. package/dist/{chunk-m6qgme8k.js → chunk-c03xn5s3.js} +1 -1
  39. package/dist/{chunk-ss1znmv0.js → chunk-cpky2bgy.js} +1 -1
  40. package/dist/chunk-cvbacjwr.js +10 -0
  41. package/dist/{chunk-xahapj98.js → chunk-d51pge1m.js} +1 -1
  42. package/dist/{chunk-0qj8jfj1.js → chunk-fbgzeb3m.js} +1 -1
  43. package/dist/chunk-ffkdx471.js +1 -0
  44. package/dist/{chunk-5va3hhfp.js → chunk-fhxy024n.js} +1 -1
  45. package/dist/{chunk-7am1z065.js → chunk-fj297dmj.js} +1 -1
  46. package/dist/{chunk-mp4bfn57.js → chunk-fx19tpcm.js} +2 -2
  47. package/dist/{chunk-hwjmm2br.js → chunk-gbrwzpyg.js} +2 -2
  48. package/dist/{chunk-2d2bcyn1.js → chunk-h4d37zt2.js} +1 -1
  49. package/dist/{chunk-xszsveq1.js → chunk-k3ddw7q3.js} +1 -1
  50. package/dist/{chunk-4wvsg8cc.js → chunk-kaf6m50a.js} +1 -1
  51. package/dist/chunk-kheaqr7j.js +1 -0
  52. package/dist/{chunk-tms0pr01.js → chunk-map4165w.js} +2 -2
  53. package/dist/chunk-ntvm6t83.js +1 -0
  54. package/dist/{chunk-bs77d8hn.js → chunk-p7ww2tcn.js} +1 -1
  55. package/dist/{chunk-g8425xh4.js → chunk-qp8mejbn.js} +1 -1
  56. package/dist/chunk-qtt17d5s.js +2 -0
  57. package/dist/{chunk-j0yvwrd7.js → chunk-qw5j84ny.js} +2 -2
  58. package/dist/chunk-qxjsfp2c.js +1 -0
  59. package/dist/{chunk-s9brgcgs.js → chunk-qyxbee3w.js} +1 -1
  60. package/dist/{chunk-c4j2anbm.js → chunk-r297pq3s.js} +2 -2
  61. package/dist/{chunk-18atvz38.js → chunk-rc7jnds2.js} +1 -1
  62. package/dist/chunk-rjgfy07e.js +5 -0
  63. package/dist/{chunk-awj9aqjy.js → chunk-shx5e10e.js} +2 -2
  64. package/dist/chunk-vm5bzhrm.js +1 -0
  65. package/dist/chunk-wgztvasm.js +1 -0
  66. package/dist/chunk-x5579r4w.js +1 -0
  67. package/dist/{chunk-6j3k4v08.js → chunk-xbj18hxh.js} +1 -1
  68. package/dist/{chunk-hhvkzn6m.js → chunk-xgmn301g.js} +1 -1
  69. package/dist/{chunk-q6daf441.js → chunk-xkz9ecdx.js} +1 -1
  70. package/dist/{chunk-06y3rada.js → chunk-y67yrm3k.js} +2 -2
  71. package/dist/chunk-yjbq4jeg.js +2 -0
  72. package/dist/chunk-yrbbx1pr.js +1 -0
  73. package/dist/{chunk-a38chc6z.js → chunk-ytce7gnt.js} +2 -2
  74. package/dist/{chunk-eh4h7fmr.js → chunk-yz80dp1a.js} +2 -2
  75. package/dist/web/assets/ChatView-Bjl8VJFM.js +18 -0
  76. package/dist/web/assets/{CodeBlockHighlighter-B5DRAEhB.js → CodeBlockHighlighter-i8Yc4Qe4.js} +1 -1
  77. package/dist/web/assets/{FilePreview-DSpvLsjW.js → FilePreview-DbU1IMtz.js} +1 -1
  78. package/dist/web/assets/{KanbanBoard-6K7IeCXi.js → KanbanBoard-Fe4qkgpi.js} +1 -1
  79. package/dist/web/assets/{MarkdownRenderer-D6LiW9kF.js → MarkdownRenderer-CdeC66uL.js} +3 -3
  80. package/dist/web/assets/{SettingsModal-CFHxLfuL.js → SettingsModal-mbG701yW.js} +2 -2
  81. package/dist/web/assets/{TaskSwitcher-Bng9nDed.js → TaskSwitcher-DF-q_rMi.js} +1 -1
  82. package/dist/web/assets/{TerminalPanel-BnyQZwkN.js → TerminalPanel-BxAmwOXK.js} +1 -1
  83. package/dist/web/assets/index-8G4ejlcH.css +1 -0
  84. package/dist/web/assets/index-BTj86SSJ.js +11 -0
  85. package/dist/web/assets/{session-events-BvtUOaNG.js → session-events-Bgir_Gl_.js} +6 -6
  86. package/dist/web/assets/team-QZ9byb3E.js +1 -0
  87. package/dist/web/assets/teamService-Cnno2N5h.js +1 -0
  88. package/dist/web/assets/{vendor-icons-C927DZlr.js → vendor-icons-DovdPN7M.js} +25 -20
  89. package/dist/web/index.html +4 -4
  90. package/package.json +1 -1
  91. package/dist/chunk-139s7p91.js +0 -1
  92. package/dist/chunk-2vkzwqv0.js +0 -1
  93. package/dist/chunk-41smvqs8.js +0 -1
  94. package/dist/chunk-4xpj0d6y.js +0 -2
  95. package/dist/chunk-61arrvhp.js +0 -1
  96. package/dist/chunk-7hf1k2c9.js +0 -6
  97. package/dist/chunk-8geywf8q.js +0 -1
  98. package/dist/chunk-91qsjpm6.js +0 -2
  99. package/dist/chunk-bqz8wera.js +0 -1
  100. package/dist/chunk-brm24s69.js +0 -2
  101. package/dist/chunk-ccgq8nrm.js +0 -44
  102. package/dist/chunk-cyjnza5n.js +0 -8
  103. package/dist/chunk-d9a0g85f.js +0 -1
  104. package/dist/chunk-e4ynb9qf.js +0 -1
  105. package/dist/chunk-e6ezndyf.js +0 -22
  106. package/dist/chunk-eh9gdzk5.js +0 -160
  107. package/dist/chunk-emqbb5xh.js +0 -1
  108. package/dist/chunk-gzysna9c.js +0 -1
  109. package/dist/chunk-hryhnmwv.js +0 -1635
  110. package/dist/chunk-mrh3vs01.js +0 -2
  111. package/dist/chunk-ph5rn44j.js +0 -1
  112. package/dist/chunk-pqhjrdnq.js +0 -10
  113. package/dist/chunk-v7phc78b.js +0 -1
  114. package/dist/chunk-x4hh8yqg.js +0 -6
  115. package/dist/chunk-ypwjzw5x.js +0 -5
  116. package/dist/chunk-zqxj65xc.js +0 -1
  117. package/dist/chunk-zssys78z.js +0 -1
  118. package/dist/web/assets/ChatView-CgUC5rxo.js +0 -18
  119. package/dist/web/assets/index-CDdYV8kB.css +0 -1
  120. package/dist/web/assets/index-DId2GJVO.js +0 -11
@@ -1,2 +0,0 @@
1
- var _=20,T=5242880,A=32000;
2
- export{_ as vg,T as wg,A as xg};
@@ -1 +0,0 @@
1
- import{je as a}from"./chunk-ypwjzw5x.js";import"./chunk-4xpj0d6y.js";import"./chunk-gv3ed5gw.js";import"./chunk-hwjmm2br.js";import"./chunk-wvg81sd9.js";import"./chunk-j0yvwrd7.js";import"./chunk-zf96d5we.js";export{a as createChatServiceAsync};
@@ -1,10 +0,0 @@
1
- import{f as T,g as W,h as X,i as Y}from"./chunk-cyjnza5n.js";import"./chunk-28wsyv32.js";import"./chunk-2d2bcyn1.js";import"./chunk-xszsveq1.js";import"./chunk-11gdqmbm.js";import"./chunk-5va3hhfp.js";import"./chunk-hryhnmwv.js";import"./chunk-mp4bfn57.js";import"./chunk-brm24s69.js";import"./chunk-6v7f2cv9.js";import"./chunk-0qj8jfj1.js";import"./chunk-mhyat4mq.js";import"./chunk-s9brgcgs.js";import"./chunk-c4j2anbm.js";import{vd as R}from"./chunk-awj9aqjy.js";import"./chunk-yhnr8vdb.js";import{Rd as Q}from"./chunk-a38chc6z.js";import"./chunk-v508x7cg.js";import"./chunk-q6daf441.js";import"./chunk-ypwjzw5x.js";import"./chunk-91qsjpm6.js";import"./chunk-6j3k4v08.js";import"./chunk-06y3rada.js";import"./chunk-hhk5ecpv.js";import"./chunk-4wvsg8cc.js";import"./chunk-2sdnmxts.js";import"./chunk-18atvz38.js";import"./chunk-z7vj2xrg.js";import"./chunk-jyds9m8p.js";import"./chunk-ccgq8nrm.js";import"./chunk-g8425xh4.js";import"./chunk-m6qgme8k.js";import"./chunk-mrh3vs01.js";import"./chunk-0kat01bw.js";import"./chunk-4xpj0d6y.js";import"./chunk-gv3ed5gw.js";import"./chunk-hwjmm2br.js";import"./chunk-wvg81sd9.js";import{oh as M}from"./chunk-y858e8pb.js";import"./chunk-eh4h7fmr.js";import"./chunk-bs77d8hn.js";import"./chunk-j0yvwrd7.js";import"./chunk-zf96d5we.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 +0,0 @@
1
- import{Je as a,Ke as b,Le as c,Me as d,Ne as e,Oe as f,Pe as g,Qe as h,Re as i,Se as j}from"./chunk-hhk5ecpv.js";import"./chunk-4wvsg8cc.js";import"./chunk-2sdnmxts.js";import"./chunk-18atvz38.js";import"./chunk-z7vj2xrg.js";import"./chunk-jyds9m8p.js";import"./chunk-ccgq8nrm.js";import"./chunk-g8425xh4.js";import"./chunk-m6qgme8k.js";import"./chunk-mrh3vs01.js";import"./chunk-0kat01bw.js";import"./chunk-4xpj0d6y.js";import"./chunk-gv3ed5gw.js";import"./chunk-hwjmm2br.js";import"./chunk-wvg81sd9.js";import"./chunk-y858e8pb.js";import"./chunk-eh4h7fmr.js";import"./chunk-bs77d8hn.js";import"./chunk-j0yvwrd7.js";import"./chunk-zf96d5we.js";export{g as withWorkspaceAgentResources,i as snapshotWorkspaceAgentResources,f as resolveWorkspaceAgentResources,j as resetWorkspaceAgentResources,d as refreshWorkspaceCommunicationStyles,h as getWorkspaceAgentResourceCacheStats,e as configureInvocationPluginDirs,c as WorkspaceAgentResourceCapacityError,a as MAX_RESIDENT_WORKSPACE_AGENT_RESOURCES,b as MAX_ACTIVE_WORKSPACE_AGENT_RESOURCES};
@@ -1,6 +0,0 @@
1
- import{m as MH,n as fH,o as yH,p as SH,q as TH,r as bH}from"./chunk-hhvkzn6m.js";import{A as JH,v as AH,w as t,x as e,y as HH,z as d}from"./chunk-5va3hhfp.js";import{O as jH,Q as xH,R as UH,T as VH,V as _H}from"./chunk-hryhnmwv.js";import"./chunk-mp4bfn57.js";import"./chunk-brm24s69.js";import{Bb as WH,gb as s,sb as LH}from"./chunk-6v7f2cv9.js";import"./chunk-0qj8jfj1.js";import{Hc as O,Sc as a,sc as QH,wc as DH}from"./chunk-mhyat4mq.js";import"./chunk-s9brgcgs.js";import"./chunk-c4j2anbm.js";import{od as PH}from"./chunk-tms0pr01.js";import{qd as FH,rd as EH,sd as zH}from"./chunk-7hf1k2c9.js";import{td as GH}from"./chunk-6j9t1xbh.js";import"./chunk-yhnr8vdb.js";import{Td as NH}from"./chunk-a38chc6z.js";import"./chunk-v508x7cg.js";import"./chunk-q6daf441.js";import"./chunk-ypwjzw5x.js";import"./chunk-91qsjpm6.js";import"./chunk-6j3k4v08.js";import"./chunk-06y3rada.js";import"./chunk-hhk5ecpv.js";import"./chunk-4wvsg8cc.js";import"./chunk-2sdnmxts.js";import"./chunk-18atvz38.js";import"./chunk-z7vj2xrg.js";import"./chunk-jyds9m8p.js";import"./chunk-ccgq8nrm.js";import{ng as YH}from"./chunk-g8425xh4.js";import{pg as BH,rg as H,sg as KH,ug as N}from"./chunk-m6qgme8k.js";import"./chunk-mrh3vs01.js";import{Bg as g}from"./chunk-0kat01bw.js";import"./chunk-4xpj0d6y.js";import"./chunk-gv3ed5gw.js";import"./chunk-hwjmm2br.js";import"./chunk-wvg81sd9.js";import"./chunk-y858e8pb.js";import"./chunk-eh4h7fmr.js";import"./chunk-bs77d8hn.js";import"./chunk-j0yvwrd7.js";import"./chunk-zf96d5we.js";import MJ from"yargs";import{hideBin as fJ}from"yargs/helpers";function p(K,V,Q){if(K.off){K.off(V,Q);return}K.removeListener?.(V,Q)}function wH(K,V){if(!K.once&&!K.on||!K.off&&!K.removeListener)throw Error("Writable returned false without an observable drain contract");return new Promise((Q,q)=>{let J=!1,Z=()=>{p(K,"drain",x),p(K,"error",j),V.removeEventListener("abort",G)},W=(F)=>{if(J)return;J=!0,Z(),F()},x=()=>W(Q),j=(F)=>W(()=>q(F??Error("Writable emitted an error"))),G=()=>W(()=>q(V.reason??Error("Writable drain aborted")));if(V.aborted){G();return}let f=K.once?.bind(K)??K.on?.bind(K);f?.("drain",x),f?.("error",j),V.addEventListener("abort",G,{once:!0})})}async function mH(K,V,Q){if(K.destroyed||K.writableEnded)throw Error("Writable is already closed");if(K.write(V)===!1)await wH(K,Q)}class v{options;queues;sinkErrorListeners=[];failed=!1;closing=!1;handleAbort=()=>{this.fail(new d("aborted","Headless output was aborted",{cause:this.options.signal?.reason}))};constructor(K,V={}){this.options=V;let Q=(q)=>new JH({maxPendingItems:V.maxPendingItems??t,maxPendingBytes:V.maxPendingBytes??e,writeTimeoutMs:V.writeTimeoutMs??HH,sizeOf:(J)=>Buffer.byteLength(J),write:(J,Z)=>mH(K[q],J,Z),onFailure:(J)=>this.fail(J)});if(this.queues={stdout:Q("stdout"),stderr:Q("stderr")},this.observeSinkErrors(K.stdout),K.stderr!==K.stdout)this.observeSinkErrors(K.stderr);if(V.signal?.addEventListener("abort",this.handleAbort,{once:!0}),V.signal?.aborted)this.handleAbort()}write(K,V){return this.queues[K].offer(V).accepted}async flush(){await Promise.all([this.queues.stdout.flush(),this.queues.stderr.flush()])}close(K){if(this.closing||this.failed)return;this.closing=!0,this.options.signal?.removeEventListener("abort",this.handleAbort),this.removeSinkErrorListeners(),this.queues.stdout.close(K),this.queues.stderr.close(K)}stats(){return{stdout:this.queues.stdout.stats(),stderr:this.queues.stderr.stats()}}observeSinkErrors(K){if(!K.on||!K.off&&!K.removeListener)return;let V=(Q)=>{this.fail(new d("write_failed","Headless writable failed",{cause:Q??Error("Writable emitted an error")}))};K.on("error",V),this.sinkErrorListeners.push({writer:K,listener:V})}fail(K){if(this.closing||this.failed)return;this.failed=!0,this.options.signal?.removeEventListener("abort",this.handleAbort),this.removeSinkErrorListeners(),this.queues.stdout.close(K),this.queues.stderr.close(K),this.options.onFailure?.(K)}removeSinkErrorListeners(){for(let{writer:K,listener:V}of this.sinkErrorListeners.splice(0))p(K,"error",V)}}var ZH=1;function D(K){return H.Object({event_version:H.Literal(ZH),...K})}var cH=D({type:H.Literal("content_delta"),delta:H.String()}),uH=D({type:H.Literal("thinking_delta"),delta:H.String()}),dH=D({type:H.Literal("thinking"),content:H.String()}),pH=D({type:H.Literal("stream_end")}),vH=D({type:H.Literal("content"),content:H.String()}),lH=D({type:H.Literal("structured_output"),output:H.Record(H.String(),H.Unknown()),schema_digest:H.String({pattern:"^[a-f0-9]{64}$"})}),l=N(["readonly","write","execute"]),aH=H.Object({kind:l,scope:N(["global","session"]),queue_position:H.Integer({minimum:1}),in_flight:H.Integer({minimum:0}),limit:H.Integer({minimum:1})}),sH=D({type:H.Literal("tool_start"),tool_name:H.String(),summary:H.String(),target:H.Optional(H.String()),tool_kind:H.Optional(l)}),iH=D({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(aH)}),oH=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:N(["local","acp"])}),rH=D({type:H.Literal("tool_result"),tool_name:H.String(),summary:H.String(),target:H.Optional(H.String()),tool_kind:H.Optional(l),success:H.Optional(H.Boolean()),error_type:H.Optional(H.String()),error_message:H.Optional(H.String()),background:H.Optional(oH)}),nH=D({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())}),tH=D({type:H.Literal("mcp_content_changed"),revision:H.Integer({minimum:1}),server_name:H.String(),content_kind:N(["resources","resource_templates","prompts"]),added:H.Array(H.String()),removed:H.Array(H.String()),updated:H.Array(H.String())}),eH=D({type:H.Literal("mcp_resource_updated"),revision:H.Integer({minimum:1}),server_name:H.String(),uri:H.String()}),HJ=D({type:H.Literal("mcp_connection_changed"),revision:H.Integer({minimum:1}),server_name:H.String(),phase:N(["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())}),JJ=D({type:H.Literal("mcp_log"),revision:H.Integer({minimum:1}),server_name:H.String(),level:N(["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())}),KJ=D({type:H.Literal("mcp_instructions_changed"),revision:H.Integer({minimum:0}),server_name:H.String(),action:N(["added","removed"]),reason:N(["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())}),VJ=D({type:H.Literal("mcp_task_changed"),revision:H.Integer({minimum:0}),task_id:H.String(),server_name:H.String(),tool_name:H.String(),status:N(["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())}),ZJ=D({type:H.Literal("project_rules_loaded"),files:H.Array(H.Object({id:H.String(),relative_path:H.String(),source:N(["project","local"]),conditional:H.Boolean(),content_sha256:H.String({pattern:"^[a-f0-9]{64}$"})})),trigger_paths:H.Array(H.String()),blocked_write:H.Boolean()}),$J=D({type:H.Literal("user_shell_started"),execution_id:H.String(),command:H.String(),auxiliary:H.Boolean()}),qJ=D({type:H.Literal("user_shell_output"),execution_id:H.String(),stream:N(["stdout","stderr"]),chunk:H.String(),stream_truncated:H.Boolean()}),XJ=D({type:H.Literal("user_shell_completed"),execution_id:H.String(),message_id:H.String(),status:N(["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()}),YJ=D({type:H.Literal("phase"),phase:N(["turn","searching","inspecting","target_hit","executing","completed"]),status:N(["ongoing","hit","done"]),message:H.String(),turn:H.Optional(H.Number()),tool_name:H.Optional(H.String()),target:H.Optional(H.String())}),BJ=D({type:H.Literal("tool_detail"),tool_name:H.String(),detail:H.String()}),NJ=D({type:H.Literal("task_update"),tasks:H.Array(VH)}),QJ=D({type:H.Literal("goal"),state:N(["updated","cleared"]),goal_id:H.Optional(H.String()),status:H.Optional(N(["active","verifying","paused","blocked","usage_limited","budget_limited","complete"])),verification_attempt:H.Optional(H.Integer({minimum:1})),verification_status:H.Optional(N(["pending","pass","fail","partial"])),verifier_session_id:H.Optional(H.String()),verification_evidence_sha256:H.Optional(H.String({pattern:"^[a-f0-9]{64}$"}))}),DJ=D({type:H.Literal("subagent"),state:N(["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(N(["pass","fail","partial"])),resumed_from:H.Optional(H.String()),root_agent_id:H.Optional(H.String()),resume_depth:H.Optional(H.Integer({minimum:0}))}),LJ=D({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:N(["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())}),WJ=D({type:H.Literal("compacting"),state:N(["started","completed"]),reason:H.Optional(N(["threshold","context_limit","turn_limit","manual"])),strategy:H.Optional(N(["llm","fallback","snip"])),outcome:H.Optional(N(["completed","fallback","failed"])),pre_tokens:H.Optional(H.Number({minimum:0})),post_tokens:H.Optional(H.Number({minimum:0}))}),jJ=D({type:H.Literal("provider_retry"),phase:N(["scheduled","waiting","attempt","recovered","exhausted"]),attempt:H.Integer({minimum:0}),max_retries:H.Integer({minimum:0}),reason:N(["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(N(["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(N(["attempt_limit","recovery_budget"]))}),xJ=D({type:H.Literal("provider_admission"),phase:N(["queued","admitted","rejected"]),request_class:N(["foreground","background","internal"]),resource:N(["stream","pending_count","pending_bytes"]),scope:N(["global","domain","owner","class"]),reason:H.Optional(N(["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}))}),UJ=D({type:H.Literal("provider_circuit"),phase:N(["opened","waiting","probe","closed","reopened","rejected"]),reason:N(["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}))}),_J=D({type:H.Literal("provider_stall"),phase:N(["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()}),GJ=D({type:H.Literal("action_stationarity"),phase:N(["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()}),PJ=D({type:H.Literal("turn_limit"),turns_count:H.Number(),action:H.Literal("continue")}),FJ=D({type:H.Literal("task_session"),session_id:H.String(),project_path:H.String(),source_project_path:H.String(),isolation:N(["local","worktree"]),worktree_branch:H.Optional(H.String()),base_commit:H.Optional(H.String())}),EJ=D({type:H.Literal("task_admission"),state:N(["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})}),zJ=D({type:H.Literal("output"),content:H.String(),exit_code:H.Number()}),AJ=D({type:H.Literal("error"),message:H.String()}),aJ=KH(H.Union([cH,uH,dH,pH,vH,lH,sH,iH,rH,nH,tH,eH,HJ,JJ,KJ,VJ,ZJ,$J,qJ,XJ,YJ,BJ,NJ,QJ,DJ,LJ,WJ,xJ,UJ,jJ,_J,GJ,PJ,FJ,EJ,zJ,AJ]));function $H(K,V){return{event_version:ZH,type:K,...V}}function yJ(K){if(!K||typeof K!=="object"||Array.isArray(K))return;let V=K;if(V.auto_backgrounded!==!0||V.background_reason!=="foreground_budget"||!Number.isSafeInteger(V.foreground_budget_ms)||V.foreground_budget_ms<=0||typeof V.shell_id!=="string"||!/^bash_[A-Za-z0-9-]+$/.test(V.shell_id)||V.shell_id.length>128||V.terminal_transport!=="local"&&V.terminal_transport!=="acp"||V.pid!==void 0&&(!Number.isSafeInteger(V.pid)||V.pid<=0))return;return{auto_backgrounded:!0,background_reason:"foreground_budget",foreground_budget_ms:V.foreground_budget_ms,shell_id:V.shell_id,...V.pid===void 0?{}:{pid:V.pid},terminal_transport:V.terminal_transport}}function SJ(K){let V=new AbortController,Q=(Z)=>{if(!V.signal.aborted)V.abort(Z)},q=()=>Q("interrupt"),J=()=>Q(K?.signal?.reason);if(K?.signal){if(K.signal.addEventListener("abort",J,{once:!0}),K.signal.aborted)J()}else process.once("SIGINT",q),process.once("SIGTERM",q);return{signal:V.signal,abort:Q,dispose:()=>{K?.signal?.removeEventListener("abort",J),process.removeListener("SIGINT",q),process.removeListener("SIGTERM",q)}}}var TJ=N(["text","jsonl"]),bJ=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(),(K)=>K===-1||K>0,()=>"must be -1 (unlimited) or a positive integer")),permissionMode:H.Optional(H.Enum(YH)),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(N(["local","worktree"])),outputFormat:H.Optional(TJ),jsonSchema:H.Optional(H.String()),outputSchema:H.Optional(H.String())});class RH{openedThinking=!1;wroteAssistantContent=!1;markAssistantContent(){this.wroteAssistantContent=!0}setThinkingOpened(K){this.openedThinking=K}hasOpenThinking(){return this.openedThinking}completeStream(){let K={openedThinking:this.openedThinking,wroteAssistantContent:this.wroteAssistantContent};return this.openedThinking=!1,this.wroteAssistantContent=!1,K}}function RJ(K){return K.issues.map((V)=>`${V.path.join(".")||"options"}: ${V.message}`).join("; ")}function IJ(K){let V=BH(bJ,K);if(!V.success)throw Error(`Invalid headless options: ${RJ(V.error)}`);return V.data}function gJ(K){return K.command("* [message]","Run full agent loop without Ink UI and print events to the terminal",(V)=>V.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(V)=>{if(!V.headless)return;let Q=await mJ(V);process.exit(Q)})}function L(K,V=""){K.write(`${V}
2
- `)}function CJ(K){return`[task] [${K.status}] ${K.subject}`}function kJ(){return{requestConfirmation:async(K)=>K.type==="mcpElicitation"?{approved:!1,reason:"headless-mcp-elicitation-unavailable",elicitation:{action:"cancel"}}:K.type==="mcpSampling"?{approved:!1,reason:"headless-mcp-sampling-unavailable"}:{approved:!0,reason:"headless-auto-approved",scope:"session"}}}function hJ(K){if(!(K instanceof Error))return"Unknown error";let q=K.lastError??K;if(q.responseBody)try{let W=JSON.parse(q.responseBody)?.error?.message;if(W)return q.statusCode?`${W} (HTTP ${q.statusCode})`:W}catch{}let J=K.message.match(/Last error:\s*(.+)$/);if(J)return J[1];return K.message}function OJ(K){return K==="jsonl"?"jsonl":"text"}function qH(K,V){let Q=(...q)=>{for(let J of q){let Z=V[J];if(typeof Z==="string"&&Z.trim()!=="")return Z}return};switch(K){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 wJ(K,V,Q,q){let J=new Set(["Glob","Grep","WebSearch","LS"]),Z=new Set(["Read","WebFetch"]);if(new Set(["Edit","Write","ApplyPatch","NotebookEdit","Bash","LSP","UndoEdit","EnterWorktree","ExitWorktree"]).has(K)&&!q.targetLocked)return{phase:"target_hit",status:"hit",message:`Target locked: ${V}`,shouldLockTarget:!0};if(q.targetLocked)return{phase:"executing",status:"hit",message:Q?`Working within target: ${V}`:`Executing: ${V}`,shouldLockTarget:!1};if(J.has(K))return{phase:"searching",status:"ongoing",message:`Still searching: ${V}`,shouldLockTarget:!1};if(Z.has(K))return{phase:"inspecting",status:"ongoing",message:`Inspecting candidate: ${V}`,shouldLockTarget:!1};return{phase:"executing",status:q.targetLocked?"hit":"ongoing",message:`Executing: ${V}`,shouldLockTarget:!1}}function XH(K,V,Q=!1){let q=(J,Z)=>{K.stdout.write(`${JSON.stringify($H(J,Z))}
3
- `)};return{contentDelta(J){if(V==="jsonl"){q("content_delta",{delta:J});return}if(Q)return;K.stdout.write(J)},thinkingDelta(J,Z){if(V==="jsonl")return q("thinking_delta",{delta:J}),Z;if(!Z)K.stderr.write("[thinking] ");return K.stderr.write(J),!0},thinking(J){if(V==="jsonl"){q("thinking",{content:J});return}L(K.stderr,`[thinking] ${J}`)},streamEnd(J,Z){if(V==="jsonl"){q("stream_end",{});return}if(Z)K.stderr.write(`
4
- `);if(J)K.stdout.write(`
5
- `)},content(J){if(V==="jsonl"){q("content",{content:J});return}L(K.stdout,J)},structuredOutput(J){if(V==="jsonl"){q("structured_output",{output:J.output,schema_digest:J.schemaDigest});return}L(K.stdout,JSON.stringify(J.output))},toolStart(J,Z,W,x){if(V==="jsonl"){q("tool_start",{tool_name:J,summary:Z,target:W,tool_kind:x});return}L(K.stderr,`[tool:start] ${Z}`)},toolProgress(J,Z,W,x,j){if(V==="jsonl"){q("tool_progress",{tool_name:J,message:Z,progress:W,total:x,admission:j?{kind:j.kind,scope:j.scope,queue_position:j.queuePosition,in_flight:j.inFlight,limit:j.limit}:void 0});return}L(K.stderr,`[tool:progress] ${J}: ${Z}`)},toolResult(J,Z,W,x,j){if(V==="jsonl"){q("tool_result",{tool_name:J,summary:Z,target:W,tool_kind:x,success:j?.success,error_type:j?.errorType,error_message:j?.errorMessage,background:j?.background});return}L(K.stderr,`[tool:result] ${Z}`)},mcpCatalogChanged(J){if(V==="jsonl"){q("mcp_catalog_changed",{revision:J.revision,server_name:J.serverName,added:J.added,removed:J.removed,updated:J.updated});return}L(K.stderr,`[mcp:catalog] r${J.revision} ${J.serverName} +${J.added.length} -${J.removed.length} ~${J.updated.length}`)},mcpContentChanged(J){if(V==="jsonl"){q("mcp_content_changed",{revision:J.revision,server_name:J.serverName,content_kind:J.contentKind==="resourceTemplates"?"resource_templates":J.contentKind,added:J.added,removed:J.removed,updated:J.updated});return}L(K.stderr,`[mcp:${J.contentKind}] r${J.revision} ${J.serverName} +${J.added.length} -${J.removed.length} ~${J.updated.length}`)},mcpResourceUpdated(J){if(V==="jsonl"){q("mcp_resource_updated",{revision:J.revision,server_name:J.serverName,uri:J.uri});return}L(K.stderr,`[mcp:resource] r${J.revision} ${J.serverName} updated ${J.uri}`)},mcpConnectionChanged(J){if(V==="jsonl"){q("mcp_connection_changed",{revision:J.revision,server_name:J.serverName,phase:J.phase,reason:J.reason,attempt:J.attempt,max_attempts:J.maxAttempts,...J.nextRetryAt!==void 0?{next_retry_at:J.nextRetryAt}:{},...J.error?{error:J.error}:{}});return}L(K.stderr,`[mcp:connection] r${J.revision} ${J.serverName} ${J.phase} ${J.attempt}/${J.maxAttempts}`)},mcpLog(J){if(V==="jsonl"){q("mcp_log",{revision:J.revision,server_name:J.serverName,level:J.level,logger:J.logger,message:J.message,projected_bytes:J.projectedBytes,data_sha256:J.dataSha256,truncated:J.truncated,details_omitted:J.detailsOmitted,timestamp:J.timestamp,synthetic:J.synthetic});return}L(K.stderr,`[mcp:log] ${J.level} ${J.serverName}${J.logger?` logger=${J.logger}`:""}: ${J.message}`)},mcpInstructionsChanged(J){if(V==="jsonl"){q("mcp_instructions_changed",{revision:J.revision,server_name:J.serverName,action:J.action,reason:J.reason,text:J.text,source_bytes:J.sourceBytes,projected_bytes:J.projectedBytes,sha256:J.sha256,truncated:J.truncated,details_omitted:J.detailsOmitted});return}L(K.stderr,`[mcp:instructions] ${J.action} ${J.serverName}${J.truncated?" (truncated)":""}`)},mcpTaskChanged(J){if(V==="jsonl"){q("mcp_task_changed",{revision:J.revision,task_id:J.taskId,server_name:J.serverName,tool_name:J.toolName,status:J.status,status_message:J.statusMessage,created_at:J.createdAt,updated_at:J.updatedAt,completed_at:J.completedAt,has_result:J.hasResult,error:J.error});return}L(K.stderr,`[mcp:task] ${J.taskId} ${J.serverName}/${J.toolName} `+J.status)},projectRulesLoaded(J){if(V==="jsonl"){q("project_rules_loaded",{files:J.files.map((Z)=>({id:Z.id,relative_path:Z.relativePath,source:Z.source,conditional:Z.conditional,content_sha256:Z.contentSha256})),trigger_paths:J.triggerPaths,blocked_write:J.blockedWrite});return}L(K.stderr,`[project-rules] loaded ${J.files.length} file(s)${J.blockedWrite?" before write":""}`)},userShellStarted(J,Z,W){if(V==="jsonl"){q("user_shell_started",{execution_id:J,command:Z,auxiliary:W});return}L(K.stderr,`[user-shell:start] ${Z}`)},userShellOutput(J,Z,W,x){if(V==="jsonl"){q("user_shell_output",{execution_id:J,stream:Z,chunk:W,stream_truncated:x});return}(Z==="stderr"?K.stderr:K.stdout).write(W)},userShellCompleted(J){if(V==="jsonl"){q("user_shell_completed",{execution_id:J.executionId,message_id:J.messageId,status:J.record.status,exit_code:J.record.exitCode,duration_ms:J.record.durationMs,stdout:J.record.stdout,stderr:J.record.stderr,truncated:J.record.truncated,auxiliary:J.auxiliary});return}L(K.stderr,`[user-shell:${J.record.status}] exit=${J.record.exitCode??"null"} ${J.record.durationMs}ms`)},phase(J,Z,W,x={}){if(V==="jsonl"){q("phase",{phase:J,status:Z,message:W,turn:x.turn,tool_name:x.toolName,target:x.target});return}L(K.stderr,`[phase:${J}] ${W}`)},toolDetail(J,Z){if(V==="jsonl"){q("tool_detail",{tool_name:J,detail:Z});return}L(K.stderr,Z)},taskUpdate(J){if(V==="jsonl"){q("task_update",{tasks:J});return}for(let Z of J)L(K.stderr,CJ(Z))},goal(J){if(V==="jsonl"){q("goal",{state:J.goal?"updated":"cleared",goal_id:J.goal?.goalId,status:J.goal?.status,verification_attempt:J.goal?.completionVerification?.attempt,verification_status:J.goal?.completionVerification?.status,verifier_session_id:J.goal?.completionVerification?.verifierSessionId,verification_evidence_sha256:J.goal?.completionVerification?.evidenceSha256});return}if(J.goal)L(K.stderr,`[goal:${J.goal.status}] ${J.goal.objective}`);else L(K.stderr,"[goal:cleared]")},subagent(J){let Z=J.kind==="subagent_spawned";if(V==="jsonl"){q("subagent",{state:Z?"spawned":"completed",session_id:J.sessionId,subagent_type:J.type,success:Z?void 0:J.success,summary:Z?void 0:J.summary,verification_verdict:Z?void 0:J.verificationVerdict,resumed_from:J.resumedFrom,root_agent_id:J.rootAgentId,resume_depth:J.resumeDepth});return}L(K.stderr,`[subagent:${Z?"spawned":"completed"}] ${J.sessionId}${J.resumedFrom?` resumed from ${J.resumedFrom}`:""}`)},tokenUsage(J){if(V==="jsonl"){q("token_usage",{input_tokens:J.inputTokens,output_tokens:J.outputTokens,total_tokens:J.totalTokens,max_context_tokens:J.maxContextTokens,cache_read_tokens:J.cacheReadTokens,cache_write_tokens:J.cacheWriteTokens,prompt_cache_break:J.cacheBreak?{reason:J.cacheBreak.reason,previous_cache_read_tokens:J.cacheBreak.previousCacheReadTokens,cache_read_tokens:J.cacheBreak.cacheReadTokens,cache_write_tokens:J.cacheBreak.cacheWriteTokens,token_drop:J.cacheBreak.tokenDrop,elapsed_ms:J.cacheBreak.elapsedMs,call_number:J.cacheBreak.callNumber,system_prompt_changed:J.cacheBreak.systemPromptChanged,system_char_delta:J.cacheBreak.systemCharDelta,tools_changed:J.cacheBreak.toolsChanged,added_tool_count:J.cacheBreak.addedToolCount,removed_tool_count:J.cacheBreak.removedToolCount,changed_tool_count:J.cacheBreak.changedToolCount,model_changed:J.cacheBreak.modelChanged,request_policy_changed:J.cacheBreak.requestPolicyChanged}:void 0,cost_usd:J.costUsd});return}L(K.stderr,`[tokens] in=${J.inputTokens} out=${J.outputTokens} total=${J.totalTokens} / ${J.maxContextTokens}`)},compacting(J){let Z=J.phase==="start";if(V==="jsonl"){q("compacting",{state:Z?"started":"completed",reason:J.reason,strategy:J.strategy,outcome:J.outcome,pre_tokens:J.preTokens,post_tokens:J.postTokens});return}L(K.stderr,Z?`[context] compacting started${J.reason?` (${J.reason})`:""}`:`[context] compacting ${J.outcome??"completed"}`)},providerAdmission(J){if(V==="jsonl"){q("provider_admission",{phase:J.phase,request_class:J.requestClass,resource:J.resource,scope:J.scope,reason:J.reason,queue_position:J.queuePosition,queue_depth:J.queueDepth,in_flight:J.inFlight,limit:J.limit,wait_ms:J.waitMs,max_wait_ms:J.maxWaitMs,recovery_remaining_ms:J.recoveryRemainingMs});return}L(K.stderr,`[provider-admission:${J.phase}] ${J.resource}/${J.scope} ${J.inFlight}/${J.limit} queue=${J.queuePosition}/${J.queueDepth}`)},providerRetry(J){if(V==="jsonl"){q("provider_retry",{phase:J.phase,attempt:J.attempt,max_retries:J.maxRetries,reason:J.reason,status_code:J.statusCode,delay_ms:J.delayMs,next_retry_at:J.nextRetryAt,mode:J.mode,recovery_budget_ms:J.recoveryBudgetMs,recovery_elapsed_ms:J.recoveryElapsedMs,recovery_remaining_ms:J.recoveryRemainingMs,exhausted_by:J.exhaustedBy});return}let Z=J.delayMs!==void 0?` in ${Math.max(0,Math.ceil(J.delayMs/1000))}s`:"";L(K.stderr,`[provider-retry:${J.phase}] ${J.attempt}/${J.maxRetries} ${J.reason}${Z}`)},providerCircuit(J){if(V==="jsonl"){q("provider_circuit",{phase:J.phase,reason:J.reason,status_code:J.statusCode,retry_after_ms:J.retryAfterMs,next_probe_at:J.nextProbeAt,open_duration_ms:J.openDurationMs,sample_count:J.sampleCount,failure_count:J.failureCount,recovery_remaining_ms:J.recoveryRemainingMs});return}let Z=J.retryAfterMs!==void 0?` retry in ${Math.max(0,Math.ceil(J.retryAfterMs/1000))}s`:"";L(K.stderr,`[provider-circuit:${J.phase}] ${J.reason}${Z}`)},providerStall(J){if(V==="jsonl"){q("provider_stall",{phase:J.phase,stall_count:J.stallCount,duration_ms:J.durationMs,warning_after_ms:J.warningAfterMs,timeout_ms:J.timeoutMs,output_started:J.outputStarted});return}L(K.stderr,`[provider-stall:${J.phase}] ${J.durationMs}ms / ${J.timeoutMs}ms`)},actionStationarity(J){if(V==="jsonl"){q("action_stationarity",{phase:J.phase,tool_name:J.toolName,run_length:J.runLength,nudge_threshold:J.nudgeThreshold,halt_threshold:J.haltThreshold,progress_aware:J.progressAware});return}L(K.stderr,`[action-stationarity:${J.phase}] ${J.toolName} ${J.runLength}/${J.haltThreshold}`)},turnLimit(J){if(V==="jsonl"){q("turn_limit",{turns_count:J,action:"continue"});return}L(K.stderr,`[turn-limit] continuing after ${J} turns`)},taskSession(J){if(V==="jsonl"){q("task_session",{session_id:J.sessionId,project_path:J.projectPath,source_project_path:J.sourceProjectPath,isolation:J.isolation,worktree_branch:J.worktreeBranch,base_commit:J.baseCommit});return}L(K.stderr,`[task:${J.isolation}] ${J.sessionId} ${J.sourceProjectPath} -> ${J.projectPath}${J.worktreeBranch?` (${J.worktreeBranch})`:""}`)},taskAdmission(J){if(V==="jsonl"){q("task_admission",{state:J.state,queue_position:J.queuePosition,queue_depth:J.queueDepth,in_flight:J.inFlight,max_concurrent_tasks:J.maxConcurrentTasks});return}L(K.stderr,J.state==="queued"?`[task:queued] position ${J.queuePosition??1}/${J.queueDepth} (running ${J.inFlight}/${J.maxConcurrentTasks})`:`[task:running] admitted (running ${J.inFlight}/${J.maxConcurrentTasks})`)},output(J,Z=0){if(V==="jsonl"){q("output",{content:J,exit_code:Z});return}L(Z===0?K.stdout:K.stderr,J)},error(J){if(V==="jsonl"){q("error",{message:J});return}L(K.stderr,J)}}}async function mJ(K,V={stdout:process.stdout,stderr:process.stderr},Q){let q="text",J=new RH,Z={targetLocked:!1},W,x,j,G=SJ(Q),f=!1,F=new v(V,{signal:G.signal,onFailure:(Y)=>{f=!0,G.abort(Y)}}),w={stdout:{write:(Y)=>F.write("stdout",Y)},stderr:{write:(Y)=>F.write("stderr",Y)}},B=XH(w,q),m=async()=>{try{return await F.flush(),!f}catch{return!1}},y=async(Y)=>{return x?.(),x=void 0,j?.(),j=void 0,await m()?Y:1};try{let Y=IJ(K);q=OJ(Y.outputFormat);let S=await TH(Y);B=XH(w,q,Boolean(S)),await MH();let i=Y.forkSession!==!0&&(Y.continue===!0||typeof Y.resume==="string"&&Y.resume.length>0)?await yH({message:Y.message,_:Y._,stdin:Q?.stdin}):await fH({...Y,stdin:Q?.stdin}),R=i===void 0,P=R?{mode:"agent",content:""}:await SH(i);if(P.mode==="output"){if(P.content)B.output(P.content,P.exitCode??0);return await y(P.exitCode??0)}let C=P.content.trimStart().startsWith("!")?P.content.trimStart().slice(1).trim():void 0;if(C!==void 0&&Y.taskIsolation)throw Error("User shell commands cannot be combined with --task-isolation");if(C!==void 0&&S)throw Error("Output schemas cannot be combined with user shell commands");if(Y.taskIsolation&&(Y.continue||Y.resume||Y.forkSession))throw Error("--task-isolation cannot be combined with --continue, --resume, or --fork-session");let{sessionId:_,messages:o,metadata:r}=await bH({sessionId:Y.sessionId,continue:Y.continue,resume:Y.resume,forkSession:Y.forkSession,fallbackSessionPrefix:"headless"}),I=Y.permissionMode??r?.permissionMode??"yolo",n=Y.model&&Y.model!=="inherit"?Y.model:NH()?.id,U=Y.taskIsolation?await AH.createSessionTask({sessionId:_,prompt:P.content,sourceProjectPath:g(),isolation:Y.taskIsolation,dispatch:{version:1,prompt:P.content,sourceProjectPath:g(),isolation:Y.taskIsolation,permissionMode:I,...n?{modelId:n}:{},...S?{outputSchema:S}:{}}}):void 0,E=U?.metadata.projectPath??r?.projectPath??g();if(j=s.subscribe((X)=>{if(X.type!=="subagent.provider.admission"||X.sessionId!==_||X.projectPath!==E)return;let $=X.properties,z=["queued","admitted","rejected"],A=["foreground","background","internal"],M=["stream","pending_count","pending_bytes"],b=["global","domain","owner","class"],OH=["capacity","queue_full","wait_timeout","closed"];if(!z.includes($.phase)||!A.includes($.requestClass)||!M.includes($.resource)||!b.includes($.scope)||$.reason!==void 0&&!OH.includes($.reason)||typeof $.queuePosition!=="number"||typeof $.queueDepth!=="number"||typeof $.inFlight!=="number"||typeof $.limit!=="number"||typeof $.waitMs!=="number"||typeof $.maxWaitMs!=="number"||$.recoveryRemainingMs!==void 0&&typeof $.recoveryRemainingMs!=="number")return;B.providerAdmission({kind:"provider_admission",phase:$.phase,requestClass:$.requestClass,resource:$.resource,scope:$.scope,...$.reason!==void 0?{reason:$.reason}:{},queuePosition:$.queuePosition,queueDepth:$.queueDepth,inFlight:$.inFlight,limit:$.limit,waitMs:$.waitMs,maxWaitMs:$.maxWaitMs,...$.recoveryRemainingMs!==void 0?{recoveryRemainingMs:$.recoveryRemainingMs}:{}})}),!U)await a.setSessionPermissionMode(_,E,I);let IH=U?!1:await WH.cancelPendingNonInteractive(E,_);if(U)B.taskSession({sessionId:_,projectPath:E,sourceProjectPath:U.metadata.taskSourceProjectPath??g(),isolation:Y.taskIsolation,worktreeBranch:U.metadata.taskWorktreeBranch,baseCommit:U.metadata.taskBaseCommit}),x=s.subscribe((X)=>{if(X.type!=="task.status"||X.sessionId!==_||X.projectPath!==E||!["queued","running"].includes(String(X.properties.taskStatus))||typeof X.properties.taskQueueDepth!=="number"||typeof X.properties.taskInFlight!=="number"||typeof X.properties.taskConcurrencyLimit!=="number")return;B.taskAdmission({state:X.properties.taskStatus,queuePosition:typeof X.properties.taskQueuePosition==="number"?X.properties.taskQueuePosition:void 0,queueDepth:X.properties.taskQueueDepth,inFlight:X.properties.taskInFlight,maxConcurrentTasks:X.properties.taskConcurrencyLimit})});let gH={messages:IH?await a.loadSessionModelContext(_,E):[...o],userId:"cli-user",sessionId:_,workspaceRoot:E,permissionMode:I,signal:G.signal,...U?.taskWorktree?{worktreeActive:!0}:{},confirmationHandler:kJ()};W=await jH.create({sessionId:_,workspaceRoot:E,modelId:Y.model,permissionMode:I,mcpConfig:Y.mcpConfig,strictMcpConfig:Y.strictMcpConfig,agents:Y.agents?GH(Y.agents):void 0,...U?.taskWorktree?{taskWorktree:U.taskWorktree}:{},...U?.metadata.taskIsolation?{taskIsolation:U.metadata.taskIsolation}:{},...o.length>0?{sessionStart:{isResume:!0,resumeSessionId:_}}:{}});let k=R&&W.getPendingSteeringCount()>0,h=R&&!k?await W.getGoal():null,c=h?.status==="active"||h?.status==="verifying",T=R&&!k&&!c?await W.getRecoveredFinalResponse():void 0;if(R&&!k&&!c){if(!T)throw Error("No unfinished turn or active goal to resume");if(h)B.goal({kind:"goal_updated",goal:h});if(T.structuredOutput&&T.structuredOutputSchemaDigest)B.structuredOutput({kind:"structured_output",output:T.structuredOutput,schemaDigest:T.structuredOutputSchemaDigest});else B.content(T.content);return B.phase("completed","done","Recovered headless run completed"),await y(0)}if(C!==void 0){let X=await W.executeUserShellCommand(C,{signal:G.signal,onEvent:async($)=>{if($.type==="started")B.userShellStarted($.executionId,$.command,$.auxiliary);else if($.type==="output")B.userShellOutput($.executionId,$.stream,$.chunk,$.streamTruncated);await m()}});return B.userShellCompleted(X),await y(X.record.status==="completed"?0:X.record.status==="aborted"?130:X.record.exitCode??1)}let CH=Y.maxTurns??W.getConfig().maxTurns,kH=U?.taskWorktree?[...new Set([...Y.disallowedTools??[],"EnterWorktree","ExitWorktree"])]:Y.disallowedTools,hH=await _H.createWithRuntime(W,{sessionId:_,systemPrompt:Y.systemPrompt,appendSystemPrompt:Y.appendSystemPrompt,maxTurns:Y.maxTurns,modelId:Y.model,permissionMode:I,toolWhitelist:Y.allowedTools,toolBlacklist:kH,mcpConfig:Y.mcpConfig,strictMcpConfig:Y.strictMcpConfig}),u=await LH(hH.chatStream(P.content,gH,{stream:!0,signal:G.signal,maxTurns:Y.maxTurns,builtinVerification:Y.verificationAgent!==!1,outputSchema:S,pendingInputOnly:k,goalContinuationOnly:c,...CH===-1?{onTurnLimitReached:async(X)=>{return B.turnLimit(X.turnsCount),{continue:!0,reason:"headless-auto-continue"}}}:{}}),async(X)=>{switch(X.kind){case"content_delta":if(!S||q==="jsonl")J.markAssistantContent();B.contentDelta(X.delta);break;case"thinking_delta":J.setThinkingOpened(B.thinkingDelta(X.delta,J.hasOpenThinking()));break;case"stream_end":{let $=J.completeStream();B.streamEnd($.wroteAssistantContent,$.openedThinking);break}case"tool_start":{let $=X.toolCall;if(!("function"in $))break;if($.function.name===O)break;if(["TaskCreate","TaskUpdate","TaskList"].includes($.function.name))break;try{let z=JSON.parse($.function.arguments),A=xH($.function.name,z),M=qH($.function.name,z),b=wJ($.function.name,A,M,Z);if(b.shouldLockTarget)Z.targetLocked=!0;B.phase(b.phase,b.status,b.message,{toolName:$.function.name,target:M}),B.toolStart($.function.name,A,M,X.toolKind)}catch{B.phase(Z.targetLocked?"executing":"searching",Z.targetLocked?"hit":"ongoing",Z.targetLocked?`Working within target: ${$.function.name}`:`Still searching: ${$.function.name}`,{toolName:$.function.name}),B.toolStart($.function.name,$.function.name,void 0,X.toolKind)}break}case"tool_progress":{let $=X.toolCall;if(!("function"in $))break;if($.function.name===O)break;B.toolProgress($.function.name,X.update.message,X.update.progress,X.update.total,X.update.admission);break}case"tool_result":{let $=X.toolCall;if(!("function"in $))break;if($.function.name===O)break;let z;try{let M=JSON.parse($.function.arguments);z=qH($.function.name,M)}catch{z=void 0}let A=DH(UH($.function.name,X.result),QH);if(B.toolResult($.function.name,A.summary,z,void 0,{success:X.result.success,errorType:X.result.error?.type,errorMessage:X.result.error?.message,background:yJ(X.result.metadata)}),A.detail)B.toolDetail($.function.name,A.detail);break}case"token_usage":B.tokenUsage(X.usage);break;case"compaction":B.compacting(X);break;case"task_update":B.taskUpdate(X.tasks);break;case"structured_output":B.structuredOutput(X);break;case"mcp_catalog_changed":B.mcpCatalogChanged(X);break;case"mcp_content_changed":B.mcpContentChanged(X);break;case"mcp_resource_updated":B.mcpResourceUpdated(X);break;case"mcp_connection_changed":B.mcpConnectionChanged(X);break;case"mcp_log":B.mcpLog(X);break;case"mcp_instructions_changed":B.mcpInstructionsChanged(X);break;case"mcp_task_changed":B.mcpTaskChanged(X);break;case"project_rules_loaded":B.projectRulesLoaded(X);break;case"steering_applied":case"follow_up_started":case"goal_continuation_started":break;case"goal_updated":B.goal(X);break;case"subagent_spawned":case"subagent_completed":B.subagent(X);break;case"model_fallback":break;case"provider_admission":B.providerAdmission(X);break;case"provider_retry":B.providerRetry(X);break;case"provider_circuit":B.providerCircuit(X);break;case"provider_stall":B.providerStall(X);break;case"action_stationarity":B.actionStationarity(X);break;case"turn_start":if(X.turn===1)Z.targetLocked=!1;B.phase("turn",Z.targetLocked?"hit":"ongoing",`Turn ${X.turn} started`,{turn:X.turn});break;default:{let $=X}}await m()});if(u.metadata?.outputTruncated)B.error("[warning] 输出因达到 token 上限被截断,部分内容可能不完整。");if(!u.success)return B.error(`Error: ${u.error?.message??"Agent execution failed"}`),await y(1);return B.phase("completed","done","Headless run completed"),await y(0)}catch(Y){if(!f){if(J.hasOpenThinking()&&q==="text")w.stderr.write(`
6
- `);B.error(`Error: ${hJ(Y)}`)}return await y(1)}finally{x?.(),j?.();try{await W?.dispose()}finally{F.close(),G.dispose()}}}async function _K(){if(!process.argv.slice(2).includes("--headless"))return!1;let{headless:Q,"output-format":q,"system-prompt":J,"append-system-prompt":Z,"max-turns":W,...x}=PH,j=MJ(fJ(process.argv)).scriptName("blade").strict(!1).options(x).middleware([EH,FH,zH]);return gJ(j),await j.parse(),!0}export{mJ as runHeadless,_K as handleHeadlessMode,bJ as HeadlessOptionsSchema};
@@ -1,5 +0,0 @@
1
- import{Fg as TE,Gg as gf,Hg as lf,Ig as xE,Jg as Wf,Lg as $f,Ng as Kf,Og as If,Pg as uf,Qg as Cf,Sg as Df,Tg as Ff,Vg as s}from"./chunk-4xpj0d6y.js";import{ah as g}from"./chunk-gv3ed5gw.js";import{eh as P_,gh as Xf}from"./chunk-hwjmm2br.js";import{jh as e_}from"./chunk-wvg81sd9.js";var YE={openrouter:{"HTTP-Referer":"https://github.com/echoVic/blade-code","X-Title":"Blade"},cerebras:{"X-Cerebras-3rd-Party-Integration":"blade"}},T_=(f)=>YE[f]||{};var cE=new Set(["user-cancel","interrupt","sibling-error","timeout"]);function Vf(f){return typeof f==="string"&&cE.has(f)}function Xh(f){if(!f.aborted)return;if(Vf(f.reason))return f.reason;return"user-cancel"}function Wh(f){if(Vf(f))return!0;if(!(f instanceof Error))return!1;if(f.name==="AbortError")return!0;if(f instanceof DOMException&&f.name==="AbortError")return!0;if(f.message.includes("aborted"))return!0;return!1}function x_(...f){let _=f.filter(Boolean);if(_.length===0)return new AbortController().signal;if(_.length===1)return _[0];let E=AbortSignal;if(typeof E.any==="function")return E.any(_);for(let x of _)if(x.aborted)return x;let h=new AbortController,T=new Map;for(let x of _){let S=()=>{h.abort(x.reason);for(let[P,t]of T)P.removeEventListener("abort",t)};T.set(x,S)}for(let[x,S]of T)x.addEventListener("abort",S,{once:!0});return h.signal}function i(f,_,E){let h=E?.throwOnAbort??!1;if(_?.aborted){if(h)return Promise.reject(new DOMException("Aborted","AbortError"));return Promise.resolve()}return new Promise((T,x)=>{let S,P=setTimeout(()=>{if(_&&S)_.removeEventListener("abort",S);T()},f);if(_)S=()=>{if(clearTimeout(P),h)x(new DOMException("Aborted","AbortError"));else T()},_.addEventListener("abort",S,{once:!0})})}var bE=g("Chat"),OE={input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}};function jf(f){if(typeof f==="string")return f;return f.filter((_)=>_.type==="text").map((_)=>_.text).join(`
2
- `)}function BE(f){if(!f)return{};try{let _=JSON.parse(f);return _&&typeof _==="object"&&!Array.isArray(_)?_:{}}catch{return bE.warn("[PiAIChatService] Invalid historical tool arguments",{value:f}),{}}}function VE(f){let _=f.match(/^data:([^;,]+);base64,(.+)$/s);return _?{mimeType:_[1],data:_[2]}:void 0}async function jE(f,_){let E=VE(f);if(E)return{type:"image",...E};if(!/^https?:\/\//i.test(f))return{type:"text",text:`[Unsupported image source: ${f}]`};let h=await fetch(f,{signal:_});if(!h.ok)throw Error(`Failed to load image ${f}: HTTP ${h.status}`);return{type:"image",mimeType:h.headers.get("content-type")?.split(";")[0]??"image/png",data:Buffer.from(await h.arrayBuffer()).toString("base64")}}async function M_(f,_,E,h,T){let x=f.filter((t)=>t.role==="system").map((t)=>jf(t.content)).filter(Boolean).join(`
3
-
4
- `),S=[];for(let t of f){if(t.role==="system")continue;if(t.role==="user"){let N=_.input.includes("image"),M=typeof t.content==="string"?t.content:await Promise.all(t.content.map((R)=>R.type==="text"?Promise.resolve({type:"text",text:R.text}):N?jE(R.image_url.url,h):Promise.resolve({type:"text",text:"[Image omitted: current model does not support image input]"})));S.push({role:"user",content:M,timestamp:Date.now()});continue}if(t.role==="assistant"){let N=[];if(t.reasoningContent?.trim())N.push({type:"thinking",thinking:t.reasoningContent});let M=jf(t.content);if(M)N.push({type:"text",text:M});for(let R of t.tool_calls??[]){if(!("function"in R))continue;N.push({type:"toolCall",id:R.id,name:R.function.name,arguments:BE(R.function.arguments)})}S.push({role:"assistant",content:N,api:_.api,provider:_.provider,model:_.id,usage:OE,stopReason:t.tool_calls?.length?"toolUse":"stop",timestamp:Date.now()});continue}S.push({role:"toolResult",toolCallId:t.tool_call_id??"",toolName:t.name??"unknown",content:[{type:"text",text:jf(t.content)}],isError:!1,timestamp:Date.now()})}let P=E?.filter((t)=>!T||t.name===T).map((t)=>({name:t.name,description:t.description,parameters:t.parameters,constrainedSampling:t.constrainedSampling})).sort((t,N)=>t.name<N.name?-1:t.name>N.name?1:0);return{...x?{systemPrompt:x}:{},messages:S,...P?.length?{tools:P}:{}}}function R_(f){let _=[];for(let E=0;E<f.length;E++){let h=f[E];if(h.role==="tool")continue;let T=h.role==="assistant"&&h.tool_calls?.length?h.tool_calls:void 0;if(!T){_.push(h);continue}let x=[],S=E+1;while(S<f.length&&f[S].role==="tool")x.push(f[S++]);let P=new Set(T.map((M)=>M.id)),t=x.filter((M)=>M.tool_call_id&&P.has(M.tool_call_id)),N=new Set(t.map((M)=>M.tool_call_id));if(P.size===T.length&&t.length===P.size&&N.size===P.size)_.push(h,...t);E=S-1}return _}function A_(f){return f.some((_)=>_.role==="assistant"&&Boolean(_.tool_calls?.length)&&!_.reasoningContent?.trim())}function S_(f,_){return{...f,..._.baseUrl?{baseUrl:P_(f.api,_.baseUrl)}:{},..._.maxOutputTokens?{maxTokens:_.maxOutputTokens}:{}}}function zf(f){let _=f.modelCatalog??Xf();return{models:_.models,model:S_(_.getModel(f.provider,f.model),f)}}function N_(f,_){let E=f.modelCatalog??Xf();return S_(E.getModel(_.provider,_.model),f)}import{createHash as XE}from"node:crypto";var zE=32,JE=1000,WE=512,$E=2000,kE=0.1,LE=0.05,GE=0.9,ZE=300000,QE=3600000;class Jf{sessions=new Map;observe(f){if(f.retention==="none"){this.sessions.delete(f.sessionId);return}let _=f.now??Date.now(),E=KE(f,_),h=this.sessions.get(f.sessionId);if(E.callCount=(h?.callCount??0)+1,this.touch(f.sessionId,E),h&&E.contextEpoch!==h.contextEpoch)return;if(!h||h.cacheReadTokens<JE)return;let T=h.cacheReadTokens-E.cacheReadTokens,x=Math.min($E,Math.max(WE,h.cacheReadTokens*kE));if(T<x||E.cacheReadTokens>=h.cacheReadTokens*(1-LE))return;let S=E.modelIdentity!==h.modelIdentity,P=E.systemHash!==h.systemHash,t=E.toolsHash!==h.toolsHash,N=E.policyHash!==h.policyHash;if(!(S||P||t||N)&&E.promptTokens<h.promptTokens*GE)return;let R=Math.max(0,_-h.recordedAt),u=h.retention==="long"?QE:ZE,Y=S?"model_changed":P?"system_prompt_changed":t?"tools_changed":N?"request_policy_changed":R>=u?"ttl_expired":"server_side",$=CE(h,E);return{reason:Y,previousCacheReadTokens:h.cacheReadTokens,cacheReadTokens:E.cacheReadTokens,cacheWriteTokens:Math.max(0,f.usage.cacheCreationInputTokens??0),tokenDrop:T,elapsedMs:R,callNumber:E.callCount,systemPromptChanged:P,systemCharDelta:E.systemChars-h.systemChars,toolsChanged:t,addedToolCount:$.added,removedToolCount:$.removed,changedToolCount:$.changed,modelChanged:S,requestPolicyChanged:N}}clear(f){if(f)this.sessions.delete(f);else this.sessions.clear()}statsForTests(){return{sessions:this.sessions.size}}touch(f,_){this.sessions.delete(f),this.sessions.set(f,_);while(this.sessions.size>zE){let E=this.sessions.keys().next().value;if(E===void 0)break;this.sessions.delete(E)}}}function KE(f,_){let E=[...f.tools??f.context.tools??[]].map((h)=>({identityHash:ff(h.name),contractHash:ff(_f(h))})).sort((h,T)=>h.identityHash<T.identityHash?-1:h.identityHash>T.identityHash?1:0);return{modelIdentity:f.modelIdentity,systemHash:ff(f.context.systemPrompt??""),systemChars:f.context.systemPrompt?.length??0,toolsHash:ff(_f(E)),toolFingerprints:E,policyHash:ff(_f(f.policy)),contextEpoch:f.contextEpoch??"",retention:f.retention,promptTokens:Number.isFinite(f.usage.promptTokens)?Math.max(0,f.usage.promptTokens):0,cacheReadTokens:Math.max(0,f.usage.cacheReadInputTokens??0),recordedAt:_,callCount:1}}function CE(f,_){let E=new Map(f.toolFingerprints.map((T)=>[T.identityHash,T.contractHash])),h=new Map(_.toolFingerprints.map((T)=>[T.identityHash,T.contractHash]));return{added:[...h.keys()].filter((T)=>!E.has(T)).length,removed:[...E.keys()].filter((T)=>!h.has(T)).length,changed:[...h].filter(([T,x])=>E.has(T)&&E.get(T)!==x).length}}function _f(f){if(f===null||typeof f!=="object")return JSON.stringify(f)??"undefined";if(Array.isArray(f))return`[${f.map(_f).join(",")}]`;let _=f;return`{${Object.keys(_).sort().map((E)=>`${JSON.stringify(E)}:${_f(_[E])}`).join(",")}}`}function ff(f){return XE("sha256").update(f).digest("hex")}import{randomBytes as vE}from"node:crypto";import{createHmac as FE}from"node:crypto";function oE(f){try{let _=new URL(f);if(_.hash="",_.hostname=_.hostname.toLowerCase(),_.searchParams.sort(),_.pathname!=="/")_.pathname=_.pathname.replace(/\/+$/,"");return _.toString()}catch{return f.trim().replace(/\/+$/,"")}}function sE(f){if(!f)return[];return Object.entries(f).map(([_,E])=>[_.trim().toLowerCase(),E.trim()]).sort(([_],[E])=>_.localeCompare(E))}function Pf(f,_,E){let h=JSON.stringify([f.provider.trim(),String(f.api).trim(),oE(f.baseUrl),f.model.trim(),f.serviceTier?.trim()??"",f.apiVersion?.trim()??"",f.apiKey??"",sE(f.customHeaders),E]);return FE("sha256",Buffer.from(_)).update(h).digest("hex")}var wE=60000,pE=4,mE=0.8;var Nf=300000,kf=600000;var I_=128,u_=256,qE=1800000,Sf=50;class hf extends Error{circuit;code="PROVIDER_CIRCUIT_OPEN";constructor(f){super(`Provider circuit open; retry after ${f.retryAfterMs??0}ms`);this.circuit=f;this.name="ProviderCircuitOpenError"}}function Lf(f){return f instanceof hf||f!==null&&typeof f==="object"&&"code"in f&&f.code==="PROVIDER_CIRCUIT_OPEN"}function l(f,_){return f!==void 0&&Number.isSafeInteger(f)&&f>0?f:_}function gE(f,_){return f!==void 0&&Number.isFinite(f)&&f>0&&f<=1?f:_}function lE(f,_){return Pf(f,_,{providerCircuitOpenDurationMs:f.openDurationMs})}function Ef(f){let _=0;for(let E of f)if(E.failure)_++;return _}function D_(f){return f!==void 0&&Number.isInteger(f)&&f>=100&&f<=599?f:void 0}function H_(f){if(f===void 0||!Number.isFinite(f)||f<0)return;return Math.min(Math.ceil(f),$f)}class Y_{#x=new Map;#t=new WeakMap;#f;#E;#T;#h;constructor(f={}){this.#f=f.processSecret?new Uint8Array(f.processSecret):vE(32),this.#E=f.now??(()=>performance.now()),this.#T=f.wallNow??f.now??Date.now,this.#h={maxEntries:Math.min(l(f.maxEntries,I_),I_),maxWindowEntries:Math.min(l(f.maxWindowEntries,u_),u_),windowMs:l(f.windowMs,wE),minSamples:l(f.minSamples,pE),errorRateThreshold:gE(f.errorRateThreshold,mE),idleTtlMs:l(f.idleTtlMs,qE)}}get size(){return this.#x.size}get(f){if(f.openDurationMs===0)return this.#R();let _=this.#E();this.#c(_);let E=lE(f,this.#f),h=this.#x.get(E);if(h)return h.lastTouchedAt=_,this.#_(h,f.probeLeaseMs);if(this.#x.size>=this.#h.maxEntries)this.#D();if(this.#x.size>=this.#h.maxEntries)return this.#R();let T={key:E,state:"closed",samples:[],generation:0,nextAttemptId:1,nextProbeLeaseId:1,configuredOpenDurationMs:f.openDurationMs,effectiveOpenDurationMs:f.openDurationMs,lastTouchedAt:_,detached:!1};return this.#x.set(E,T),this.#_(T,f.probeLeaseMs)}#_(f,_){let E=this,h=Math.max(Nf,Math.min(l(_,Nf),kf));return{preflight:()=>E.#A(f),check:()=>E.#b(f,h),recordSuccess:(T)=>E.#M(T,"success"),recordFailure:(T,x)=>E.#M(T,"failure",x),recordNeutral:(T)=>E.#M(T,"neutral"),abandon:(T)=>E.#N(T),snapshot:()=>E.#j(f)}}#R(){let f=this;return{preflight:()=>({eligible:!0}),check:()=>{let _=Object.freeze({kind:"noop"});return f.#t.set(_,{generation:0,attemptId:0,kind:"noop",settled:!1}),{allowed:!0,probe:!1,token:_}},recordSuccess:(_)=>f.#S(_),recordFailure:(_)=>f.#S(_),recordNeutral:(_)=>f.#S(_),abandon:(_)=>f.#N(_),snapshot:()=>({state:"closed",sampleCount:0,failureCount:0,noop:!0,detached:!1})}}#S(f){let _=this.#t.get(f);if(_?.kind==="noop")_.settled=!0;return}#A(f){let _=this.#E();if(f.detached)return{eligible:!0};if(f.lastTouchedAt=_,this.#I(f,_),f.state==="closed")return{eligible:!0};if(f.state==="open"){let h=f.nextProbeAt??_;return _<h?this.#U(f,h-_):{eligible:!0}}if(f.probeLeaseId===void 0||f.probeLeaseExpiresAt!==void 0&&_>=f.probeLeaseExpiresAt)return{eligible:!0};let E=Math.max(1,(f.probeLeaseExpiresAt??_+Sf)-_);return this.#U(f,Math.min(Sf,E))}#U(f,_){let{allowed:E,...h}=this.#P(f,_);return{eligible:!1,...h}}#b(f,_){let E=this.#E();if(f.detached)return this.#R().check();if(f.lastTouchedAt=E,this.#I(f,E),f.state==="closed")return this.#Y(f,"regular");if(f.state==="open"){let T=f.nextProbeAt??E;if(E<T)return this.#P(f,T-E);f.state="half_open",f.generation++,f.probeLeaseId=void 0,f.probeLeaseExpiresAt=void 0}if(f.probeLeaseId===void 0||f.probeLeaseExpiresAt!==void 0&&E>=f.probeLeaseExpiresAt)return this.#O(f,E,_);let h=Math.max(1,(f.probeLeaseExpiresAt??E+Sf)-E);return this.#P(f,Math.min(Sf,h))}#Y(f,_,E){let h=Object.freeze({kind:_});return this.#t.set(h,{entry:f,generation:f.generation,attemptId:f.nextAttemptId++,kind:_,...E!==void 0?{probeLeaseId:E}:{},settled:!1}),{allowed:!0,probe:_==="probe",token:h}}#O(f,_,E){let h=f.nextProbeLeaseId++;f.probeLeaseId=h,f.probeLeaseExpiresAt=_+E,f.lastTouchedAt=_;let T=this.#Y(f,"probe",h),x=f.lastFailure??{reason:"server_error"};return{...T,reason:x.reason,...x.statusCode!==void 0?{statusCode:x.statusCode}:{},openDurationMs:f.effectiveOpenDurationMs,sampleCount:f.samples.length,failureCount:Ef(f.samples)}}#P(f,_){let E=f.lastFailure??{reason:"server_error"};return{allowed:!1,state:f.state==="open"?"open":"half_open",reason:E.reason,...E.statusCode!==void 0?{statusCode:E.statusCode}:{},retryAfterMs:Math.max(0,Math.ceil(_)),nextProbeAt:this.#T()+Math.max(0,Math.ceil(_)),openDurationMs:f.effectiveOpenDurationMs,sampleCount:f.samples.length,failureCount:Ef(f.samples)}}#M(f,_,E){let h=this.#t.get(f);if(!h||h.settled)return;if(h.settled=!0,h.kind==="noop"||!h.entry)return;let T=h.entry;if(T.detached||h.generation!==T.generation||h.kind==="regular"&&T.state!=="closed"||h.kind==="probe"&&(T.state!=="half_open"||h.probeLeaseId!==T.probeLeaseId))return;let x=this.#E();if(T.lastTouchedAt=x,h.kind==="probe"){if(_==="failure"&&E)return this.#u(T,E,x,"reopened");return this.#B(T)}if(_==="neutral")return;if(this.#V(T,_==="failure",x),_!=="failure"||!E)return;let S=Ef(T.samples),P=T.samples.length===0?0:S/T.samples.length;if(T.samples.length>=this.#h.minSamples&&P>=this.#h.errorRateThreshold)return this.#u(T,E,x,"opened");return}#u(f,_,E,h){let T={reason:_.reason,...D_(_.statusCode)!==void 0?{statusCode:D_(_.statusCode)}:{},...H_(_.retryAfterMs)!==void 0?{retryAfterMs:H_(_.retryAfterMs)}:{}},x=T.retryAfterMs??0,S=Math.max(f.configuredOpenDurationMs,x);return f.state="open",f.generation++,f.probeLeaseId=void 0,f.probeLeaseExpiresAt=void 0,f.effectiveOpenDurationMs=S,f.nextProbeAt=E+S,f.lastFailure=T,{phase:h,reason:T.reason,...T.statusCode!==void 0?{statusCode:T.statusCode}:{},retryAfterMs:S,nextProbeAt:this.#T()+S,openDurationMs:S,sampleCount:f.samples.length,failureCount:Ef(f.samples)}}#B(f){let _=f.lastFailure??{reason:"server_error"};return f.state="closed",f.generation++,f.samples=[],f.probeLeaseId=void 0,f.probeLeaseExpiresAt=void 0,f.nextProbeAt=void 0,f.effectiveOpenDurationMs=f.configuredOpenDurationMs,{phase:"closed",reason:_.reason,..._.statusCode!==void 0?{statusCode:_.statusCode}:{},openDurationMs:f.effectiveOpenDurationMs,sampleCount:0,failureCount:0}}#N(f){let _=this.#t.get(f);if(!_||_.settled)return!1;if(_.settled=!0,_.kind==="noop")return!0;let E=_.entry;if(!E||E.detached||_.kind!=="probe"||_.generation!==E.generation||_.probeLeaseId!==E.probeLeaseId)return!1;return E.probeLeaseId=void 0,E.probeLeaseExpiresAt=void 0,E.lastTouchedAt=this.#E(),!0}#V(f,_,E){if(this.#I(f,E),f.samples.length>=this.#h.maxWindowEntries)f.samples.shift();f.samples.push({at:E,failure:_})}#I(f,_){let E=_-this.#h.windowMs,h=0;while(h<f.samples.length&&f.samples[h].at<E)h++;if(h>0)f.samples.splice(0,h)}#j(f){if(!f.detached)this.#I(f,this.#E());return{state:f.state,sampleCount:f.samples.length,failureCount:Ef(f.samples),...f.nextProbeAt!==void 0?{nextProbeAt:f.nextProbeAt}:{},noop:!1,detached:f.detached}}#c(f){for(let[_,E]of this.#x)if(E.state==="closed"&&f-E.lastTouchedAt>this.#h.idleTtlMs)this.#H(_,E)}#D(){let f;for(let _ of this.#x.values())if(_.state==="closed"&&(!f||_.lastTouchedAt<f.lastTouchedAt))f=_;if(f)this.#H(f.key,f)}#H(f,_){_.detached=!0,this.#x.delete(f)}}var U_;function c_(){return U_??=new Y_,U_}import{randomBytes as aE}from"node:crypto";var b_=16,O_=128,B_=32,V_=3,j_=16,X_=96,z_=24,J_=12,W_=16,$_=4,k_=4,L_=67108864,G_=33554432,Z_=12,Q_=2,K_=2,C_=1,w_=15000,F_=30000;function Gf(){return{foreground:0,background:0,internal:0}}function Zf(){return{inFlight:Gf(),queued:Gf(),pendingBytes:Gf()}}function U(f){return f.foreground+f.background+f.internal}function W(f){return f.background+f.internal}function o_(f){return f.inFlight.foreground===0&&f.inFlight.background===0&&f.inFlight.internal===0&&f.queued.foreground===0&&f.queued.background===0&&f.queued.internal===0&&f.pendingBytes.foreground===0&&f.pendingBytes.background===0&&f.pendingBytes.internal===0}class Tf extends Error{reason;scope;requestClass;resource;inFlight;limit;queued;maxWaitMs;code="PROVIDER_ADMISSION_BUSY";retryable;constructor(f,_,E,h,T,x,S,P){super(f==="queue_full"?`Provider request admission ${_} ${h} queue is full`:f==="wait_timeout"?`Provider request admission timed out waiting for ${_} capacity`:"Provider request admission scheduler is closed");this.reason=f;this.scope=_;this.requestClass=E;this.resource=h;this.inFlight=T;this.limit=x;this.queued=S;this.maxWaitMs=P;this.name="ProviderAdmissionError",this.retryable=f!=="closed"}}function xf(f){return f instanceof Tf||f!==null&&typeof f==="object"&&"code"in f&&f.code==="PROVIDER_ADMISSION_BUSY"}function z(f,_,E){if(f===void 0||!Number.isSafeInteger(f)||f<=0)return _;return Math.min(f,E)}function yE(f){let _=z(f.globalMaxInFlight,b_,b_),E=z(f.globalMaxPending,O_,O_),h=z(f.domainMaxPending,B_,B_),T=Math.min(z(f.ownerMaxInFlight,V_,V_),_),x=Math.min(z(f.ownerMaxPending,j_,j_),E),S=Math.min(z(f.nonForegroundGlobalMaxPending,Math.min(X_,Math.max(1,Math.floor(E*3/4))),X_),E),P=Math.min(z(f.nonForegroundDomainMaxPending,Math.min(z_,Math.max(1,Math.floor(h*3/4))),z_),h),t=Math.min(z(f.nonForegroundOwnerMaxPending,Math.min(J_,Math.max(1,Math.floor(x*3/4))),J_),x),N=Math.min(z(f.internalGlobalMaxPending,Math.min(W_,Math.max(1,Math.floor(E/8))),W_),S),M=Math.min(z(f.internalDomainMaxPending,Math.min($_,Math.max(1,Math.floor(h/8))),$_),P),R=Math.min(z(f.internalOwnerMaxPending,Math.min(k_,Math.max(1,Math.floor(x/4))),k_),t),u=z(f.globalMaxPendingBytes,s,s),Y=Math.min(z(f.domainMaxPendingBytes,L_,L_),u),$=Math.min(z(f.ownerMaxPendingBytes,G_,G_),u),Q=Math.min(z(f.nonForegroundGlobalMaxInFlight,Math.min(Z_,_),Z_),_),K=Math.min(z(f.nonForegroundOwnerMaxInFlight,Math.min(Q_,T),Q_),T),o=Math.min(z(f.internalGlobalMaxInFlight,Math.min(K_,_),K_),_),Uf=z(f.internalDomainMaxInFlight,C_,C_),tf=z(f.agingMs,F_,F_);return{globalMaxInFlight:_,globalMaxPending:E,domainMaxPending:h,ownerMaxInFlight:T,ownerMaxPending:x,nonForegroundGlobalMaxPending:S,nonForegroundDomainMaxPending:P,nonForegroundOwnerMaxPending:t,internalGlobalMaxPending:N,internalDomainMaxPending:M,internalOwnerMaxPending:R,globalMaxPendingBytes:u,domainMaxPendingBytes:Y,ownerMaxPendingBytes:$,nonForegroundGlobalMaxInFlight:Q,nonForegroundOwnerMaxInFlight:K,internalGlobalMaxInFlight:o,internalDomainMaxInFlight:Uf,agingMs:tf}}function s_(f,_){if(!f.trim())throw Error(`${_} must not be blank`)}function dE(f){if(s_(f.sessionId,"sessionId"),s_(f.ownerId,"ownerId"),!Number.isSafeInteger(f.scope.maxConcurrent)||f.scope.maxConcurrent<If||f.scope.maxConcurrent>uf)throw Error(`maxConcurrent must be between ${If} and ${uf}`);if(!Number.isSafeInteger(f.scope.maxPendingBytes)||f.scope.maxPendingBytes<=0||f.scope.maxPendingBytes>s)throw Error(`maxPendingBytes must be between 1 and ${s}`);if(!Number.isSafeInteger(f.pendingBytes)||f.pendingBytes<=0||f.pendingBytes>s+1)throw Error(`pendingBytes must be between 1 and ${s+1}`);if(!Number.isSafeInteger(f.maxWaitMs)||f.maxWaitMs<0||f.maxWaitMs>Df)throw Error(`maxWaitMs must be 0-${Df}`)}function Qf(f,_){if(_!==void 0)return _;if(f?.reason!==void 0)return f.reason;return new DOMException("Provider request admission cancelled","AbortError")}function eE(f,_){return Pf(f,_,{providerRequestConcurrency:f.maxConcurrent,providerRequestPendingBytes:f.maxPendingBytes})}class p_{#x;#t;#f;#E=[];#T=new Map;#h=new Map;#_=Zf();#R=1;#S=0;#A=!1;constructor(f={}){this.#x=f.processSecret?new Uint8Array(f.processSecret):aE(32),this.#t=f.now??(()=>performance.now()),this.#f=yE(f)}admit(f){if(dE(f),this.#A)throw this.#X("closed",f,{scope:"global",resource:"stream",inFlight:U(this.#_.inFlight),limit:this.#f.globalMaxInFlight},this.#E.length);if(f.signal?.aborted)throw Qf(f.signal);let _=eE(f.scope,this.#x),E=this.#T.get(_),h=this.#h.get(f.ownerId),T=E??this.#Y(f.scope.maxConcurrent),x=h??this.#O();if(this.#E.length===0&&this.#P(T,x,f.requestClass)){if(!E)this.#T.set(_,T);if(!h)this.#h.set(f.ownerId,x),this.#R++;let u=this.#u(_,f.ownerId,f.requestClass),Y=this.#k(f,0);return{ready:Promise.resolve(u),getSnapshot:()=>({...Y}),cancel:()=>{Y={...Y}}}}let S=this.#U(f,T,x);if(S)throw this.#X("queue_full",f,S,this.#E.length);let P=this.#M(T,x,f.requestClass);if(f.maxWaitMs===0)throw this.#X("wait_timeout",f,P,this.#E.length);if(!E)this.#T.set(_,T);if(!h)this.#h.set(f.ownerId,x),this.#R++;let t,N,M=new Promise((u,Y)=>{t=u,N=Y});M.catch(()=>{return});let R={domainKey:_,sessionId:f.sessionId,ownerId:f.ownerId,requestClass:f.requestClass,maxWaitMs:f.maxWaitMs,pendingBytes:f.pendingBytes,enqueuedAt:this.#t(),signal:f.signal,resolve:t,reject:N,settled:!1,admitted:!1};if(f.signal)R.abortListener=()=>this.#c(R,Qf(f.signal)),f.signal.addEventListener("abort",R.abortListener,{once:!0});return R.timer=setTimeout(()=>this.#j(R),f.maxWaitMs),R.timer.unref?.(),this.#E.push(R),this.#b(T,x,R),this.#N(),{ready:M,getSnapshot:()=>this.#$(R),cancel:(u)=>this.#c(R,Qf(f.signal,u))}}close(){if(this.#A)return;this.#A=!0;for(let f of[...this.#E]){let _=this.#T.get(f.domainKey),E=this.#h.get(f.ownerId),h=_&&E?this.#M(_,E,f.requestClass):{scope:"global",resource:"stream",inFlight:U(this.#_.inFlight),limit:this.#f.globalMaxInFlight};this.#D(f,new Tf("closed",h.scope,f.requestClass,h.resource,h.inFlight,h.limit,this.#E.length,f.maxWaitMs))}}getStats(){return{inFlight:U(this.#_.inFlight),queued:this.#E.length,pendingBytes:U(this.#_.pendingBytes),nonForegroundInFlight:W(this.#_.inFlight),internalInFlight:this.#_.inFlight.internal,nonForegroundQueued:W(this.#_.queued),internalQueued:this.#_.queued.internal,nonForegroundPendingBytes:W(this.#_.pendingBytes),internalPendingBytes:this.#_.pendingBytes.internal,domainCount:this.#T.size,ownerCount:this.#h.size,closed:this.#A}}#U(f,_,E){let h=(M,R,u)=>R>=u?{scope:M,resource:"pending_count",inFlight:R,limit:u}:void 0;if(f.requestClass==="internal"){let M=h("class",this.#_.queued.internal,this.#f.internalGlobalMaxPending)??h("class",E.counters.queued.internal,this.#f.internalOwnerMaxPending)??h("class",_.counters.queued.internal,this.#f.internalDomainMaxPending);if(M)return M}if(f.requestClass!=="foreground"){let M=h("class",W(this.#_.queued),this.#f.nonForegroundGlobalMaxPending)??h("class",W(E.counters.queued),this.#f.nonForegroundOwnerMaxPending)??h("class",W(_.counters.queued),this.#f.nonForegroundDomainMaxPending);if(M)return M}let T=h("global",this.#E.length,this.#f.globalMaxPending)??h("owner",U(E.counters.queued),this.#f.ownerMaxPending)??h("domain",U(_.counters.queued),this.#f.domainMaxPending);if(T)return T;let x=Math.min(f.scope.maxPendingBytes,this.#f.globalMaxPendingBytes),S=Math.min(x,this.#f.domainMaxPendingBytes),P=Math.min(x,this.#f.ownerMaxPendingBytes),t=(M,R)=>f.pendingBytes>R-M,N=(M)=>{if(M==="owner")return{scope:M,resource:"pending_bytes",inFlight:U(E.counters.inFlight),limit:this.#f.ownerMaxInFlight};if(M==="domain")return{scope:M,resource:"pending_bytes",inFlight:U(_.counters.inFlight),limit:_.maxConcurrent};return{scope:M,resource:"pending_bytes",inFlight:U(this.#_.inFlight),limit:this.#f.globalMaxInFlight}};if(f.requestClass==="internal"){let M=Math.max(1,Math.floor(x/8)),R=Math.max(1,Math.floor(S/4)),u=Math.max(1,Math.floor(P/4));if(t(this.#_.pendingBytes.internal,M)||t(E.counters.pendingBytes.internal,u)||t(_.counters.pendingBytes.internal,R))return N("class")}if(f.requestClass!=="foreground"){let M=Math.max(1,Math.floor(x*3/4)),R=Math.max(1,Math.floor(S*3/4)),u=Math.max(1,Math.floor(P/2));if(t(W(this.#_.pendingBytes),M)||t(W(E.counters.pendingBytes),u)||t(W(_.counters.pendingBytes),R))return N("class")}if(t(U(this.#_.pendingBytes),x))return N("global");if(t(U(E.counters.pendingBytes),P))return N("owner");if(t(U(_.counters.pendingBytes),S))return N("domain");return}#b(f,_,E){let{requestClass:h,pendingBytes:T}=E;this.#_.queued[h]++,f.counters.queued[h]++,_.counters.queued[h]++,this.#_.pendingBytes[h]+=T,f.counters.pendingBytes[h]+=T,_.counters.pendingBytes[h]+=T}#Y(f){return{maxConcurrent:f,counters:Zf()}}#O(){return{order:this.#R,counters:Zf()}}#P(f,_,E){if(U(this.#_.inFlight)>=this.#f.globalMaxInFlight)return!1;if(U(f.counters.inFlight)>=f.maxConcurrent)return!1;if(U(_.counters.inFlight)>=this.#f.ownerMaxInFlight)return!1;if(E==="foreground")return!0;if(W(this.#_.inFlight)>=this.#f.nonForegroundGlobalMaxInFlight)return!1;if(W(_.counters.inFlight)>=this.#f.nonForegroundOwnerMaxInFlight)return!1;let h=Math.max(1,f.maxConcurrent-1);if(W(f.counters.inFlight)>=h)return!1;if(E!=="internal")return!0;return this.#_.inFlight.internal<this.#f.internalGlobalMaxInFlight&&f.counters.inFlight.internal<this.#f.internalDomainMaxInFlight}#M(f,_,E){if(U(_.counters.inFlight)>=this.#f.ownerMaxInFlight)return{scope:"owner",resource:"stream",inFlight:U(_.counters.inFlight),limit:this.#f.ownerMaxInFlight};if(E!=="foreground"&&W(_.counters.inFlight)>=this.#f.nonForegroundOwnerMaxInFlight)return{scope:"class",resource:"stream",inFlight:W(_.counters.inFlight),limit:this.#f.nonForegroundOwnerMaxInFlight};if(U(f.counters.inFlight)>=f.maxConcurrent)return{scope:"domain",resource:"stream",inFlight:U(f.counters.inFlight),limit:f.maxConcurrent};if(E!=="foreground"){let h=Math.max(1,f.maxConcurrent-1);if(W(f.counters.inFlight)>=h)return{scope:"class",resource:"stream",inFlight:W(f.counters.inFlight),limit:h}}if(E==="internal"&&f.counters.inFlight.internal>=this.#f.internalDomainMaxInFlight)return{scope:"class",resource:"stream",inFlight:f.counters.inFlight.internal,limit:this.#f.internalDomainMaxInFlight};if(U(this.#_.inFlight)>=this.#f.globalMaxInFlight)return{scope:"global",resource:"stream",inFlight:U(this.#_.inFlight),limit:this.#f.globalMaxInFlight};if(E!=="foreground"&&W(this.#_.inFlight)>=this.#f.nonForegroundGlobalMaxInFlight)return{scope:"class",resource:"stream",inFlight:W(this.#_.inFlight),limit:this.#f.nonForegroundGlobalMaxInFlight};if(E==="internal"&&this.#_.inFlight.internal>=this.#f.internalGlobalMaxInFlight)return{scope:"class",resource:"stream",inFlight:this.#_.inFlight.internal,limit:this.#f.internalGlobalMaxInFlight};return{scope:"domain",resource:"stream",inFlight:U(f.counters.inFlight),limit:f.maxConcurrent}}#u(f,_,E){let h=this.#T.get(f),T=this.#h.get(_);if(!h||!T)throw Error("Provider admission accounting state is unavailable");this.#_.inFlight[E]++,h.counters.inFlight[E]++,T.counters.inFlight[E]++;let x=!1;return{release:()=>{if(x)return;x=!0,this.#B(f,_,E)}}}#B(f,_,E){let h=this.#T.get(f),T=this.#h.get(_);if(this.#_.inFlight[E]--,h)h.counters.inFlight[E]--;if(T)T.counters.inFlight[E]--;this.#z(f,_),this.#N()}#N(){if(this.#A)return;while(this.#E.length>0){let f=this.#t(),_=new Map;for(let[P,t]of this.#E.entries()){let N=this.#T.get(t.domainKey),M=this.#h.get(t.ownerId);if(N===void 0||M===void 0||!this.#P(N,M,t.requestClass))continue;let R=this.#V(t,f),u=_.get(t.ownerId);if(!u||R<u.rank||R===u.rank&&P<u.index)_.set(t.ownerId,{pending:t,rank:R,index:P})}let E=[..._.values()].filter(({pending:P})=>{let t=this.#T.get(P.domainKey),N=this.#h.get(P.ownerId);return t!==void 0&&N!==void 0&&this.#P(t,N,P.requestClass)}).map(({pending:P,rank:t})=>({pending:P,rank:t,order:this.#h.get(P.ownerId).order}));if(E.length===0)return;let h=Math.min(...E.map((P)=>P.rank)),T=E.filter((P)=>P.rank===h),S=T.filter((P)=>P.order>this.#S).sort((P,t)=>P.order-t.order)[0]??T.sort((P,t)=>P.order-t.order)[0];this.#I(S.pending,S.order)}}#V(f,_){let E=f.requestClass==="foreground"?0:f.requestClass==="background"?1:2,h=Math.floor(Math.max(0,_-f.enqueuedAt)/this.#f.agingMs);return Math.max(0,E-h)}#I(f,_){if(!this.#H(f,!1))return;f.settled=!0,f.admitted=!0,this.#S=_;let E=this.#u(f.domainKey,f.ownerId,f.requestClass);f.permit=E,f.resolve(E)}#j(f){let _=this.#T.get(f.domainKey),E=this.#h.get(f.ownerId),h=_&&E?this.#M(_,E,f.requestClass):{scope:"global",resource:"stream",inFlight:U(this.#_.inFlight),limit:this.#f.globalMaxInFlight};this.#D(f,new Tf("wait_timeout",h.scope,f.requestClass,h.resource,h.inFlight,h.limit,this.#E.length,f.maxWaitMs))}#c(f,_){this.#D(f,_)}#D(f,_){if(!this.#H(f))return;f.settled=!0,f.reject(_),this.#N()}#H(f,_=!0){if(f.settled||f.admitted)return!1;let E=this.#E.indexOf(f);if(E<0)return!1;this.#E.splice(E,1);let h=this.#T.get(f.domainKey),T=this.#h.get(f.ownerId);if(h&&T)this.#J(h,T,f);if(this.#W(f),_)this.#z(f.domainKey,f.ownerId);return!0}#J(f,_,E){let{requestClass:h,pendingBytes:T}=E;this.#_.queued[h]--,f.counters.queued[h]--,_.counters.queued[h]--,this.#_.pendingBytes[h]-=T,f.counters.pendingBytes[h]-=T,_.counters.pendingBytes[h]-=T}#W(f){if(f.timer)clearTimeout(f.timer);if(f.timer=void 0,f.signal&&f.abortListener)f.signal.removeEventListener("abort",f.abortListener);f.abortListener=void 0,f.signal=void 0}#z(f,_){let E=this.#T.get(f);if(E&&o_(E.counters))this.#T.delete(f);let h=this.#h.get(_);if(h&&o_(h.counters))this.#h.delete(_)}#$(f){let _=Math.max(0,Math.floor(this.#t()-f.enqueuedAt));if(f.admitted)return{state:"admitted",requestClass:f.requestClass,resource:"stream",scope:"domain",queuePosition:0,queueDepth:this.#E.length,inFlight:U(this.#_.inFlight),limit:this.#f.globalMaxInFlight,waitMs:_,maxWaitMs:f.maxWaitMs};let E=this.#T.get(f.domainKey),h=this.#h.get(f.ownerId),T=E&&h?this.#M(E,h,f.requestClass):{scope:"global",resource:"stream",inFlight:U(this.#_.inFlight),limit:this.#f.globalMaxInFlight};return{state:"queued",requestClass:f.requestClass,resource:T.resource,scope:T.scope,reason:"capacity",queuePosition:this.#L(f,T.scope),queueDepth:this.#E.length,inFlight:T.inFlight,limit:T.limit,waitMs:_,maxWaitMs:f.maxWaitMs}}#k(f,_){return{state:"admitted",requestClass:f.requestClass,resource:"stream",scope:"domain",queuePosition:0,queueDepth:this.#E.length,inFlight:U(this.#_.inFlight),limit:this.#f.globalMaxInFlight,waitMs:_,maxWaitMs:f.maxWaitMs}}#L(f,_){let E=this.#E.filter((h)=>{switch(_){case"owner":return h.ownerId===f.ownerId;case"domain":return h.domainKey===f.domainKey;case"class":return h.requestClass===f.requestClass;case"global":return!0}});return Math.max(1,E.indexOf(f)+1)}#X(f,_,E,h){return new Tf(f,E.scope,_.requestClass,E.resource,E.inFlight,E.limit,h,_.maxWaitMs)}}var v_;function m_(){return v_??=new p_,v_}function q_(f,_={}){let E=_.maxBytes??134217728,h=_.maxNodes??1e5;if(!Number.isSafeInteger(E)||E<=0||E>=Number.MAX_SAFE_INTEGER)throw Error("maxBytes must be a positive safe integer");if(!Number.isSafeInteger(h)||h<=0)throw Error("maxNodes must be a positive safe integer");let T=new WeakSet,x=0,S=0,P=!1,t=(M)=>{if(P||M<=0)return;if(!Number.isSafeInteger(M)||M>E-x){x=E+1,P=!0;return}x+=M},N=(M)=>{if(P)return;if(S+=1,S>h){t(E+1);return}if(M===null){t(4);return}switch(typeof M){case"string":t(Buffer.byteLength(M,"utf8"));return;case"number":case"bigint":t(8);return;case"boolean":t(4);return;case"undefined":case"function":case"symbol":return;case"object":break}if(T.has(M))return;if(T.add(M),ArrayBuffer.isView(M)){t(32+M.byteLength);return}if(M instanceof ArrayBuffer){t(32+M.byteLength);return}if(M instanceof Date){t(40);return}if(M instanceof RegExp){t(32+Buffer.byteLength(M.source,"utf8"));return}if(M instanceof Map){t(32);for(let[R,u]of M)if(N(R),N(u),P)return;return}if(M instanceof Set){t(32);for(let R of M)if(N(R),P)return;return}if(M instanceof WeakMap||M instanceof WeakSet){t(32);return}if(Array.isArray(M)){t(16);for(let R of M)if(N(R),P)return;return}t(32);for(let R of Reflect.ownKeys(M)){if(typeof R!=="string")continue;let u=Object.getOwnPropertyDescriptor(M,R);if(!u?.enumerable||!("value"in u))continue;if(t(8+Buffer.byteLength(R,"utf8")),N(u.value),P)return}};return N(f),x}function g_(f){return q_([f.messages,f.context,f.tools,f.requestOptions],{maxBytes:s})}var l_=new WeakSet;class a extends Error{budgetMs;elapsedMs;code="PROVIDER_RECOVERY_BUDGET_EXCEEDED";constructor(f,_){super(`Provider recovery budget exhausted after ${f}ms`);this.budgetMs=f;this.elapsedMs=_;this.name="ProviderRecoveryBudgetExceededError"}}class of extends Error{timeoutMs;code="PROVIDER_REQUEST_DEADLINE_EXCEEDED";constructor(f){super(`Provider request deadline exceeded after ${f}ms`);this.timeoutMs=f;this.name="ProviderRequestDeadlineExceededError"}}var nE=["gousagelimiterror","freeusagelimiterror","monthly usage limit reached","available balance","insufficient_quota","out of budget","quota exceeded","billing"],rE=["prompt_too_long","prompt is too long","maximum context length","context length exceeded","context_length_exceeded","request too large"],iE=["econnreset","econnrefused","enotfound","eai_again","etimedout","fetch failed","network error","connection error","connection refused","connection lost","other side closed","socket hang up","socket connection was closed","upstream connect","reset before headers","websocket closed","websocket error","http2 request did not get a response"];function a_(f){return(f instanceof Error?f.message:String(f)).toLowerCase()}function fh(f){let _=a_(f);return rE.some((E)=>_.includes(E))}function sf(f){if(f!==null&&typeof f==="object")l_.add(f)}function RT(f){return f!==null&&typeof f==="object"&&l_.has(f)}function _h(f){return f!==null&&typeof f==="object"&&"code"in f?f.code:void 0}function Eh(f){if(f===null||typeof f!=="object")return;let _=f;for(let E of["status","statusCode"]){let h=_[E];if(typeof h==="number"&&Number.isInteger(h))return h}return}function hh(f){let _=f.match(/^(?:error:\s*)?(\d{3})\b/),E=f.match(/\b(?:status(?:\s+code)?|http)[:\s]+(\d{3})\b/),h=Number(_?.[1]??E?.[1]);return Number.isInteger(h)?h:void 0}function y(f,_){let E=a_(f),h=_h(f);if(h==="STREAM_IDLE_TIMEOUT"||h==="PROVIDER_RECOVERY_BUDGET_EXCEEDED"||f instanceof Error&&f.name==="AbortError"||E.includes("request aborted")||E==="aborted")return{retryable:!1};if(nE.some((x)=>E.includes(x))||fh(f))return{retryable:!1};if(_?.shouldRetry==="false")return{retryable:!1,statusCode:_.statusCode};if(h==="PROVIDER_REQUEST_DEADLINE_EXCEEDED")return{retryable:!0,reason:"timeout"};let T=_?.statusCode??Eh(f)??hh(E);if(_?.shouldRetry==="true")return{retryable:!0,reason:T===429?"rate_limit":T===408||T===409?"timeout":"server_error",statusCode:T};if(T===429)return{retryable:!0,reason:"rate_limit",statusCode:T};if(T===408||T===409)return{retryable:!0,reason:"timeout",statusCode:T};if(T!==void 0&&T>=500&&T<=599)return{retryable:!0,reason:"server_error",statusCode:T};if(h==="PROVIDER_STREAM_CLOSED"||E.includes("stream closed before completion")||E.includes("ended without")||E.includes("stream ended before"))return{retryable:!0,reason:"stream_closed",statusCode:T};if(iE.some((x)=>E.includes(x)))return{retryable:!0,reason:"transport",statusCode:T};if(E.includes("timeout")||E.includes("timed out")||E.includes("temporarily unavailable")||E.includes("upstream_error")||E.includes("overloaded")||E.includes("rate limit")||E.includes("too many requests")||E.includes("service unavailable")||E.includes("server error")||E.includes("internal error")||E.includes("please retry")||E.includes("try your request again"))return{retryable:!0,reason:E.includes("rate")||E.includes("too many")?"rate_limit":E.includes("timeout")||E.includes("timed out")?"timeout":"server_error",statusCode:T};return{retryable:!1,statusCode:T}}function vf(f,_){if(!f)return;if(f.retryAfterMs!==void 0){let T=Number.parseFloat(f.retryAfterMs);if(Number.isFinite(T))return Math.max(0,T)}if(f.retryAfter===void 0)return;let E=Number.parseFloat(f.retryAfter);if(Number.isFinite(E))return Math.max(0,E*1000);let h=Date.parse(f.retryAfter);return Number.isFinite(h)?Math.max(0,h-_):void 0}function y_(f,_,E={}){let h=E.now??Date.now(),T=E.maxDelayMs??60000,x=vf(_,h);if(x!==void 0)return Math.min(Math.ceil(x),T);let S=Math.max(0,f-1),P=E.maxExponentialDelayMs??8000,t=Math.min(500*2**S,P),N=Math.max(0,Math.min(1,E.random??Math.random())),M=t*(0.75+N*0.25);return Math.min(Math.round(M),T)}function n_(f,_){let E=f.onPayload;f.onPayload=async(h,T)=>{let x=E?await E(h,T):h;return _(x===void 0?h:x,T)}}function Th(f){if(!f.reasoningEnabled)return;return f.reasoningEffort??f.reasoningLevel??"high"}function wf(f,_,E){if(!f.enablePromptCaching)return"none";if(E&&_.api==="openai-completions"&&!_.baseUrl.includes("api.openai.com"))return"long";return"short"}function xh(f){switch(f){case"minimal":return"MINIMAL";case"low":return"LOW";case"medium":return"MEDIUM";default:return"HIGH"}}function th(f,_,E,h){let T=h?void 0:Th(E);if(!T){if(_.api==="anthropic-messages")f.thinkingEnabled=!1;if(_.api==="google-generative-ai"||_.api==="google-vertex")f.thinking={enabled:!1};return}switch(_.api){case"anthropic-messages":f.thinkingEnabled=!0,f.effort=T;break;case"google-generative-ai":case"google-vertex":f.thinking={enabled:!0,level:xh(T)};break;case"mistral-conversations":f.reasoningEffort="high";break;case"bedrock-converse-stream":case"pi-messages":f.reasoning=T;break;default:f.reasoningEffort=T}}function Mh(f,_,E){if(!E)return;switch(_){case"anthropic-messages":case"bedrock-converse-stream":f.toolChoice={type:"tool",name:E};break;case"openai-completions":case"mistral-conversations":case"pi-messages":f.toolChoice={type:"function",function:{name:E}};break;case"openai-responses":case"openai-codex-responses":case"azure-openai-responses":f.toolChoice={type:"function",name:E};break;case"google-generative-ai":case"google-vertex":f.toolChoice="any";break}}function Rh(f,_,E){let h=E.serviceTier;if(!h)return;if(_.api==="openai-responses"||_.api==="openai-codex-responses"||_.api==="azure-openai-responses"){f.serviceTier=h;return}if(_.api!=="openai-completions"&&!(_.api==="anthropic-messages"&&h==="fast"))return;n_(f,(T)=>{if(!T||typeof T!=="object"||Array.isArray(T))return T;return _.api==="anthropic-messages"?{...T,speed:"fast"}:{...T,service_tier:h}})}function Ah(f,_,E){let h=E.responseVerbosity;if(!h)return;if(e_(_,h),_.api==="openai-codex-responses"){f.textVerbosity=h;return}n_(f,(T)=>{if(!T||typeof T!=="object"||Array.isArray(T))return T;if(_.api==="openai-completions")return{...T,verbosity:h};let x="text"in T&&T.text&&typeof T.text==="object"&&!Array.isArray(T.text)?T.text:{};return{...T,text:{...x,verbosity:h}}})}function r_(f,_,E,h,T=!1){let x={apiKey:f.apiKey,headers:f.customHeaders,signal:E,temperature:h?.temperature??f.temperature??0,maxTokens:h?.maxOutputTokens??f.maxOutputTokens,timeoutMs:f.timeout,maxRetries:0,cacheRetention:wf(f,_,h?.providerSessionId),sessionId:h?.providerSessionId};if(th(x,_,f,T),Mh(x,_.api,h?.toolChoice?.toolName),Rh(x,_,f),Ah(x,_,f),_.api==="azure-openai-responses")x.azureBaseUrl=f.baseUrl,x.azureApiVersion=f.apiVersion,x.azureDeploymentName=_.id;return x}function d_(f,_){let E=_.get("x-should-retry");return{statusCode:f,..._.get("retry-after")!==null?{retryAfter:_.get("retry-after")??void 0}:{},..._.get("retry-after-ms")!==null?{retryAfterMs:_.get("retry-after-ms")??void 0}:{},...E==="true"||E==="false"?{shouldRetry:E}:{}}}var Ph=new Set(["anthropic-messages","openai-completions","openai-responses","openai-codex-responses","azure-openai-responses","pi-messages"]);function i_(f,_,E){let h=f.onResponse;if(f.onResponse=async(x,S)=>{let P=new Headers(x.headers);E(d_(x.status,P)),await h?.(x,S)},!Ph.has(_.api)||typeof globalThis.fetch!=="function")return;let T=typeof f.fetch==="function"?f.fetch:globalThis.fetch.bind(globalThis);f.fetch=async(x,S)=>{let P=await T(x,S);return E(d_(P.status,P.headers)),P}}function fE(f){return{promptTokens:f.input+f.cacheRead+f.cacheWrite,completionTokens:f.output,totalTokens:f.totalTokens,costUsd:f.cost.total,...f.reasoning!==void 0?{reasoningTokens:f.reasoning}:{},...f.cacheWrite>0?{cacheCreationInputTokens:f.cacheWrite}:{},...f.cacheRead>0?{cacheReadInputTokens:f.cacheRead}:{}}}var Hf=300000,Sh=30000;class _E extends Error{timeoutMs;code="STREAM_IDLE_TIMEOUT";constructor(f){super(`Provider stream idle timeout after ${f}ms without an event`);this.timeoutMs=f;this.name="StreamIdleTimeoutError"}}class EE extends Error{code="PROVIDER_STREAM_CLOSED";constructor(){super("Provider stream closed before completion");this.name="ProviderStreamClosedError"}}function pf(f){return f.reason instanceof Error?f.reason:new DOMException("Aborted","AbortError")}function Nh(f){return f.idleTimeoutMs&&f.idleTimeoutMs>0?f.idleTimeoutMs:Hf}function Ih(f,_){if(_===0)return;let E=_!==void 0&&_>0?_:Sh;return Math.max(1,Math.min(E,Math.floor(f/2)))}function uh(f,_,E){if(E?.aborted)return Promise.reject(pf(E));return new Promise((h,T)=>{let x=!1,S=()=>{clearTimeout(M),E?.removeEventListener("abort",N)},P=(R)=>{if(x)return;x=!0,S(),h(R)},t=(R)=>{if(x)return;x=!0,S(),T(R instanceof Error?R:Error(String(R)))},N=()=>{if(E)t(pf(E))},M=setTimeout(()=>P({kind:"timer"}),Math.max(0,_));if(E?.addEventListener("abort",N,{once:!0}),E?.aborted){N();return}f.then((R)=>P({kind:"next",result:R}),t)})}async function*Dh(f,_,E){let h=Nh(_),T=Ih(h,_.stallWarningMs);if(_.signal?.aborted)throw pf(_.signal);let x=Date.now(),S=Promise.resolve().then(()=>f.next()),P;for(;;){let N=await uh(S,(P?h:T??h)-(Date.now()-x),_.signal);if(N.kind==="next"){if(P)yield{...P,phase:"recovered",durationMs:Math.max(P.durationMs,Date.now()-x)};return N.result}if(!P&&T!==void 0){E.stallCount++,P={phase:"detected",stallCount:E.stallCount,durationMs:T,warningAfterMs:T,timeoutMs:h,outputStarted:E.outputStarted},yield P;continue}let M=new _E(h);throw _.abort?.(M),M}}async function*hE(f,_,E,h,T={}){let S=f.stream(_,E,h)[Symbol.asyncIterator](),P=0,t=!1,N={stallCount:0,outputStarted:!1};try{while(!0){let M=Dh(S,T,N),R=await M.next();while(!R.done)yield{providerStall:R.value},R=await M.next();let u=R.value;if(u.done)throw new EE;let Y=u.value;switch(Y.type){case"text_delta":N.outputStarted=!0,yield{content:Y.delta};break;case"thinking_delta":N.outputStarted=!0,yield{reasoningContent:Y.delta};break;case"toolcall_end":N.outputStarted=!0,yield{toolCalls:[{index:P++,id:Y.toolCall.id,type:"function",function:{name:Y.toolCall.name,arguments:JSON.stringify(Y.toolCall.arguments)}}]};break;case"done":t=!0,yield{finishReason:Y.reason,usage:fE(Y.message.usage)};return;case"error":throw Error(Y.error.errorMessage??`Request ${Y.reason==="aborted"?"aborted":"failed"}`)}}}finally{if(!t)Promise.resolve(S.return?.()).catch(()=>{return})}}var mf=g("Chat"),Hh=1;function Uh(f,_){let E=_.provider===f.provider,h=E&&_.channel===void 0,T=_.channel;return{...f,provider:_.provider,model:_.model,apiKey:T?.apiKey??(h?f.apiKey:void 0),baseUrl:T?.baseUrl??(h?f.baseUrl:void 0),temperature:T?.temperature??f.temperature,maxOutputTokens:T?.maxOutputTokens??(h?f.maxOutputTokens:void 0),timeout:T?.timeout??f.timeout,streamIdleTimeout:T?.streamIdleTimeout??f.streamIdleTimeout,apiVersion:T?.apiVersion??(h?f.apiVersion:void 0),customHeaders:T?.customHeaders??(h?f.customHeaders:void 0),enablePromptCaching:T?.enablePromptCaching??(h?f.enablePromptCaching:void 0),serviceTier:E?f.serviceTier:void 0,responseVerbosity:E?f.responseVerbosity:void 0,fallbackModels:void 0}}function Yh(f){return Boolean(f&&f.role==="user"&&Array.isArray(f.content)&&f.content.some((_)=>_.type==="image_url"))}function ch(f){let E=f.findLast((h)=>{let T=h.metadata;return T!==null&&typeof T==="object"&&!Array.isArray(T)&&T.isCompactSummary===!0})?.metadata;return E!==null&&typeof E==="object"&&!Array.isArray(E)&&typeof E.parentId==="string"?E.parentId:""}function bh(f,_){let E=y(f,_);if(!E.retryable||!E.reason)return;let h=E.statusCode;switch(E.reason){case"rate_limit":if(h!==429)return;break;case"server_error":if(h===void 0||h<500||h>599)return;break;case"transport":case"stream_closed":break;case"timeout":return}let T=vf(_,Date.now());return{reason:E.reason,...h!==void 0?{statusCode:h}:{},...T!==void 0?{retryAfterMs:T}:{}}}function qf(f){return f!==null&&typeof f==="object"&&"code"in f&&f.code==="STREAM_IDLE_TIMEOUT"}class af{config;models;model;promptCacheBreakMonitor=new Jf;admissionFallbackOwnerId=`pi-service-${process.pid}-${Hh++}`;constructor(f){let _=zf(f);this.config={...f,maxContextTokens:_.model.contextWindow,maxOutputTokens:f.maxOutputTokens??_.model.maxTokens},this.models=_.models,this.model=_.model,mf.debug("[PiAIChatService] Initialized",{provider:this.model.provider,model:this.model.id,api:this.model.api})}async chat(f,_,E,h){let T="",x="",S=[],P,t;for await(let N of this.streamChat(f,_,E,h)){T+=N.content??"",x+=N.reasoningContent??"";for(let M of N.toolCalls??[])if(M.id&&M.type==="function"&&M.function?.name)S.push(M);P=N.usage??P,t=N.finishReason??t}return{content:T,...x?{reasoningContent:x}:{},...S.length>0?{toolCalls:S}:{},usage:P,finishReason:t}}async*streamChat(f,_,E,h){let T=h?.toolChoice?.toolName;if(T&&!_?.some((A)=>A.name===T))throw Error(`Required tool is unavailable: ${T}`);let x=R_(f);if(x.some((A)=>Yh(A))&&!this.model.input.includes("image"))throw Error(`${this.model.name} does not support image input`);let S=Boolean(T)||A_(x),P=await M_(x,this.model,_,E,T),t=(A,I)=>{let B=h?.providerSessionId;if(!B||!A.usage)return A;if(!this.config.enablePromptCaching)return this.promptCacheBreakMonitor.clear(B),A;let c=wf(this.config,I,B),H=this.promptCacheBreakMonitor.observe({sessionId:B,modelIdentity:`${I.provider}\x00${I.api}\x00${I.id}`,context:P,retention:c,contextEpoch:ch(x),policy:{baseUrl:I.baseUrl??this.config.baseUrl??"",retention:c,requiredTool:T??"",reasoningEnabled:this.config.reasoningEnabled??!1,reasoningEffort:this.config.reasoningEffort??this.config.reasoningLevel??"",serviceTier:this.config.serviceTier??"",responseVerbosity:this.config.responseVerbosity??"",temperature:h?.temperature??this.config.temperature??0,maxOutputTokens:h?.maxOutputTokens??this.config.maxOutputTokens??0,customHeaders:this.config.customHeaders??{}},usage:A.usage});if(!H)return A;return mf.warn("[PiAIChatService] Prompt cache break detected",{reason:H.reason,previousCacheReadTokens:H.previousCacheReadTokens,cacheReadTokens:H.cacheReadTokens,tokenDrop:H.tokenDrop,callNumber:H.callNumber}),{...A,usage:{...A.usage,promptCacheBreak:H}}},N=g_({messages:x,context:P,tools:_,requestOptions:h}),M=h?.providerRecovery;if(M&&!xE(M.budgetMs))throw Error("Invalid bounded foreground Provider recovery budget");let R=M?.mode==="bounded_foreground"&&M.budgetMs>0?{budgetMs:M.budgetMs,startedAt:void 0}:void 0,u=R?"bounded_foreground":"standard",Y=this.config.maxRetries??2,$=this.config.maxRetries??(R?TE:2),Q=R!==void 0&&this.config.maxRetries===void 0,K=0,o,Uf=this.config.providerCircuitRegistry??c_(),tf=this.config.providerCircuitBreakerOpenMs??Wf,tE=Math.max(Nf,Math.min(this.config.streamIdleTimeout??Hf,kf)),ME=this.config.providerRequestAdmissionScheduler??m_(),RE=this.config.providerRequestConcurrency??Kf,yf=this.config.providerRequestAdmissionMs??Cf,AE=this.config.providerRequestPendingBytes??Ff,Yf=h?.providerAdmission??{sessionId:this.admissionFallbackOwnerId,ownerId:this.admissionFallbackOwnerId,requestClass:"internal"},PE=(A,I)=>Uf.get({provider:A.provider,api:A.api,baseUrl:A.baseUrl??I.baseUrl??"",model:A.id,serviceTier:I.serviceTier,apiVersion:I.apiVersion,apiKey:I.apiKey,customHeaders:I.customHeaders,openDurationMs:tf,probeLeaseMs:tE}),SE=(A,I)=>({provider:A.provider,api:A.api,baseUrl:A.baseUrl??I.baseUrl??"",model:A.id,serviceTier:I.serviceTier,apiVersion:I.apiVersion,apiKey:I.apiKey,customHeaders:I.customHeaders,maxConcurrent:RE,maxPendingBytes:AE}),j=(A=Date.now())=>{if(!R)return;let I=R.startedAt===void 0?0:Math.min(R.budgetMs,Math.max(0,A-R.startedAt));return{recoveryBudgetMs:R.budgetMs,recoveryElapsedMs:I,recoveryRemainingMs:Math.max(0,R.budgetMs-I)}},v=()=>({mode:u,...j()??{}}),df=()=>{if(R&&R.startedAt===void 0)R.startedAt=Date.now()},w=()=>{let A=j();return new a(R?.budgetMs??0,A?.recoveryElapsedMs??0)},d=()=>!Q||K<$+1,cf=(A,I)=>{let{state:B,...c}=I;return{phase:A,...c,...j()?{recoveryRemainingMs:j()?.recoveryRemainingMs}:{}}},ef=(A)=>({phase:"rejected",requestClass:A.requestClass,resource:A.resource,scope:A.scope,reason:A.reason,queuePosition:0,queueDepth:Math.max(0,A.queued),inFlight:Math.max(0,A.inFlight),limit:Math.max(0,A.limit),waitMs:A.reason==="wait_timeout"?A.maxWaitMs:0,maxWaitMs:A.maxWaitMs,...j()?{recoveryRemainingMs:j()?.recoveryRemainingMs}:{}}),NE=async function*(A,I){let B=j()?.recoveryRemainingMs,c=B!==void 0&&R?.startedAt!==void 0?Math.min(yf,B):yf,H;try{H=ME.admit({scope:SE(A,I),sessionId:Yf.sessionId,ownerId:Yf.ownerId,requestClass:Yf.requestClass,maxWaitMs:c,pendingBytes:N,signal:E})}catch(b){if(xf(b)){if(b.reason==="wait_timeout"&&R?.startedAt!==void 0&&(j()?.recoveryRemainingMs??0)<=0)throw w();yield{providerAdmission:ef(b)}}throw b}let L=H.getSnapshot();if(L.state==="admitted")return await H.ready;yield{providerAdmission:cf("queued",L)};let F=H.ready.then((b)=>({kind:"ready",permit:b}),(b)=>({kind:"error",error:b}));while(!0){let b=H.getSnapshot(),O=Math.max(1,Math.min(w_,Math.max(1,c-b.waitMs))),J,X=new Promise((p)=>{J=setTimeout(()=>p({kind:"heartbeat"}),O),J.unref?.()}),G=await Promise.race([F,X]);if(J)clearTimeout(J);if(G.kind==="heartbeat"){yield{providerAdmission:cf("queued",H.getSnapshot())};continue}if(G.kind==="error"){if(xf(G.error)){if(G.error.reason==="wait_timeout"&&R?.startedAt!==void 0&&(j()?.recoveryRemainingMs??0)<=0)throw w();yield{providerAdmission:ef(G.error)}}throw G.error}return yield{providerAdmission:cf("admitted",H.getSnapshot())},G.permit}},IE=(A,I)=>{if(!d())throw w();if(Q)K++;o=void 0;let B=new AbortController,c=E?x_(E,B.signal):B.signal,H=typeof I.timeout==="number"&&Number.isFinite(I.timeout)&&I.timeout>0?Math.max(1,Math.floor(I.timeout)):void 0,L;if(R?.startedAt!==void 0){let O=j()?.recoveryRemainingMs??0;if(O<=0)throw w();L={remainingMs:O,error:new a(R.budgetMs,R.budgetMs)}}let F=r_(I,A,c,h,S);i_(F,A,(O)=>{o=O});let b=hE(this.models,A,P,F,{idleTimeoutMs:I.streamIdleTimeout??Hf,signal:c,abort:(O)=>B.abort(O)});return async function*(){let O,J;try{if(H!==void 0&&(L===void 0||H<L.remainingMs)){let X=new of(H);O=setTimeout(()=>B.abort(X),H),O.unref?.()}if(L){let X=L;J=setTimeout(()=>B.abort(X.error),X.remainingMs),J.unref?.()}yield*b}finally{if(O)clearTimeout(O);if(J)clearTimeout(J)}}()},nf=this,q=(A)=>({phase:A.phase,reason:A.reason,...A.statusCode!==void 0?{statusCode:A.statusCode}:{},...A.retryAfterMs!==void 0?{retryAfterMs:A.retryAfterMs}:{},...A.nextProbeAt!==void 0?{nextProbeAt:A.nextProbeAt}:{},openDurationMs:A.openDurationMs,sampleCount:A.sampleCount,failureCount:A.failureCount,...j()?{recoveryRemainingMs:j()?.recoveryRemainingMs}:{}}),rf=(A,I)=>({phase:A,reason:I.reason,...I.statusCode!==void 0?{statusCode:I.statusCode}:{},retryAfterMs:I.retryAfterMs,...I.nextProbeAt!==void 0?{nextProbeAt:I.nextProbeAt}:{},openDurationMs:I.openDurationMs,sampleCount:I.sampleCount,failureCount:I.failureCount,...j()?{recoveryRemainingMs:j()?.recoveryRemainingMs}:{}}),uE=(A)=>({phase:"probe",reason:A.reason??"server_error",...A.statusCode!==void 0?{statusCode:A.statusCode}:{},openDurationMs:A.openDurationMs??tf,...A.sampleCount!==void 0?{sampleCount:A.sampleCount}:{},...A.failureCount!==void 0?{failureCount:A.failureCount}:{},...j()?{recoveryRemainingMs:j()?.recoveryRemainingMs}:{}}),bf=(A,I,B)=>({providerRetry:{phase:"exhausted",attempt:A,maxRetries:$,reason:I,...B!==void 0?{statusCode:B}:{},...v(),exhaustedBy:"recovery_budget"}}),f_=async function*(A,I,B,c,H){let L,F=!1,b,O,J=PE(A,I);for(let X=0;X<=c;X++){if(!d())break;let G,p;while(!G){let D=J.preflight();while(!D.eligible){if(b=D.reason,O=D.statusCode,!R||!H){let C=rf("rejected",D);throw yield{providerCircuit:C},new hf(C)}df();let V=j()?.recoveryRemainingMs??0;if(V<=0){let C=w();throw yield bf(Q?Math.max(0,K-1):X,D.reason,D.statusCode),C}yield{providerCircuit:rf("waiting",D)};let m=Math.min(Math.max(1,D.retryAfterMs),gf,V);if(await i(m,E,{throwOnAbort:!0}),(j()?.recoveryRemainingMs??0)<=0){let C=w();throw yield bf(Q?Math.max(0,K-1):X,D.reason,D.statusCode),C}D=J.preflight()}try{p=yield*NE(A,I)}catch(Z){if(Z instanceof a)yield bf(Q?Math.max(0,K-1):X,b??"timeout",O);throw Z}let k=J.check();if(k.allowed)G=k;else p.release(),p=void 0}let e=G.token;if(G.probe)yield{providerCircuit:uE(G)};try{let D=!1,k=!1;for await(let Z of IE(A,I)){if(Z.providerStall){yield Z;continue}let V=Q?K-1:X;if(V>0&&b&&!D)D=!0,yield{providerRetry:{phase:"recovered",attempt:V,maxRetries:$,reason:b,...O!==void 0?{statusCode:O}:{},...v()}};if(!k){k=!0;let m=J.recordSuccess(e);if(m)yield{providerCircuit:q(m)}}F=!0,B(),yield t(Z,A)}if(!k){let Z=J.recordSuccess(e);if(Z)yield{providerCircuit:q(Z)}}return}catch(D){if(p?.release(),L=D,nf.logIdleTimeout(D,F,A),await nf.handleAbort(E),D instanceof a){if(F)throw sf(D),D;throw yield{providerRetry:{phase:"exhausted",attempt:Q?Math.max(0,K-1):X,maxRetries:$,reason:b??"timeout",...O!==void 0?{statusCode:O}:{},...v(),exhaustedBy:"recovery_budget"}},D}let k=y(D,o);if(F)throw sf(D),D;let Z=bh(D,o),V=Z?J.recordFailure(e,Z):o&&!qf(D)?J.recordNeutral(e):void 0;if(V)yield{providerCircuit:q(V)};if(!k.retryable||!k.reason){if(X>0&&b)yield{providerRetry:{phase:"exhausted",attempt:Q?Math.max(0,K-1):X,maxRetries:$,reason:b,...O!==void 0?{statusCode:O}:{},...v()}};throw D}b=k.reason,O=k.statusCode;let m=X<c&&d();if(V&&V.phase!=="closed"&&m&&(!R||!H)){let C={...q(V),phase:"rejected"};throw yield{providerCircuit:C},new hf(C)}if(m){df();let C=Q?K:X+1,HE=y_(C,o,R?{maxDelayMs:lf,maxExponentialDelayMs:lf}:void 0),E_=V&&V.phase!=="closed"?V.retryAfterMs??0:0;if(R&&E_>0&&V)yield{providerCircuit:{...q(V),phase:"waiting"}};let UE=j(),Bf=Math.max(HE,E_),n=R?Math.min(Bf,UE?.recoveryRemainingMs??Bf):Bf,Rf={attempt:C,maxRetries:$,reason:k.reason,...k.statusCode!==void 0?{statusCode:k.statusCode}:{}};if(yield{providerRetry:{phase:"scheduled",...Rf,delayMs:n,nextRetryAt:Date.now()+n,...v()}},R){let r=n;while(r>0){let h_=Math.min(r,gf);if(await i(h_,E,{throwOnAbort:!0}),r-=h_,(j()?.recoveryRemainingMs??0)<=0){let Af=w();throw yield{providerRetry:{phase:"exhausted",...Rf,...v(),exhaustedBy:"recovery_budget"}},Af}if(r>0){if(V&&V.phase!=="closed"&&V.nextProbeAt!==void 0){let Af=Math.max(0,V.nextProbeAt-Date.now());if(Af>0)yield{providerCircuit:{...q(V),phase:"waiting",retryAfterMs:Af}}}yield{providerRetry:{phase:"waiting",...Rf,delayMs:n,nextRetryAt:Date.now()+r,...v()}}}}}else await i(n,E,{throwOnAbort:!0});yield{providerRetry:{phase:"attempt",...Rf,...v()}}}else yield{providerRetry:{phase:"exhausted",attempt:Q?Math.max(0,K-1):X,maxRetries:$,reason:k.reason,...k.statusCode!==void 0?{statusCode:k.statusCode}:{},...v(),...R&&(H||!d())?{exhaustedBy:"attempt_limit"}:{}}}}finally{J.abandon(e),p?.release()}}throw L},Of,__=!1,Mf=this.config.fallbackModels??[],DE=R&&Mf.length>0?Math.min(Y,$):$;try{for await(let A of f_(this.model,this.config,()=>{__=!0},DE,Mf.length===0))yield A;return}catch(A){if(Of=A,__||!xf(A)&&!Lf(A)&&!qf(A)&&!y(A,o).retryable)throw A}for(let[A,I]of Mf.entries()){if(!d())break;yield{modelFallback:!0};let B=!1;try{let c=Uh(this.config,I),H=N_(c,I),L=A===Mf.length-1,F=R&&!L?Math.min(Y,$):$;for await(let b of f_(H,c,()=>{B=!0},F,L))yield b;return}catch(c){if(Of=c,B||!xf(c)&&!Lf(c)&&!qf(c)&&!y(c,o).retryable)throw c}}throw Of}async handleAbort(f){if(f?.aborted)await i(0,f,{throwOnAbort:!0})}logIdleTimeout(f,_,E){if(f===null||typeof f!=="object"||!("code"in f)||f.code!=="STREAM_IDLE_TIMEOUT"||!("timeoutMs"in f)||typeof f.timeoutMs!=="number")return;mf.warn("[PiAIChatService] Provider stream idle timeout",{provider:E.provider,model:E.id,timeoutMs:f.timeoutMs,replayBoundaryCrossed:_})}getConfig(){return{...this.config}}updateConfig(f){let _={...this.config,...f},E=zf(_);this.config={..._,maxContextTokens:E.model.contextWindow,maxOutputTokens:_.maxOutputTokens??E.model.maxTokens},this.models=E.models,this.model=E.model}}var Oh=g("Service");async function GT(f){let _=f;if(_.provider){let E=T_(_.provider);if(Object.keys(E).length>0)_={..._,customHeaders:{...E,..._.customHeaders}},Oh.debug(`Injected ${_.provider} specific headers:`,Object.keys(E))}return Bh(_)}function Bh(f){return new af(f)}
5
- export{Xh as be,Wh as ce,x_ as de,xf as ee,q_ as fe,fh as ge,RT as he,af as ie,GT as je};
@@ -1 +0,0 @@
1
- import{pe as a,qe as b,re as c}from"./chunk-06y3rada.js";import"./chunk-ccgq8nrm.js";import"./chunk-g8425xh4.js";import"./chunk-m6qgme8k.js";import"./chunk-mrh3vs01.js";import"./chunk-0kat01bw.js";import"./chunk-4xpj0d6y.js";import"./chunk-gv3ed5gw.js";import"./chunk-hwjmm2br.js";import"./chunk-wvg81sd9.js";import"./chunk-y858e8pb.js";import"./chunk-eh4h7fmr.js";import"./chunk-bs77d8hn.js";import"./chunk-j0yvwrd7.js";import"./chunk-zf96d5we.js";export{c as snapshotWorkspaceModelResources,b as resolveWorkspaceModelResources,a as cloneWorkspaceModelConfig};
@@ -1 +0,0 @@
1
- import{th as a,uh as b,vh as c}from"./chunk-eh4h7fmr.js";import"./chunk-bs77d8hn.js";import"./chunk-j0yvwrd7.js";import"./chunk-zf96d5we.js";export{b as isWorkspaceTrusted,c as WorkspaceTrustService,a as MAX_RESIDENT_WORKSPACE_TRUST_STATUSES};
@@ -1,18 +0,0 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/MarkdownRenderer-D6LiW9kF.js","assets/index-DId2GJVO.js","assets/vendor-react-DG5dkZ_t.js","assets/vendor-radix-DXRuAJHH.js","assets/vendor-icons-C927DZlr.js","assets/session-events-BvtUOaNG.js","assets/index-CDdYV8kB.css"])))=>i.map(i=>d[i]);
2
- import{r as b,j as e}from"./vendor-react-DG5dkZ_t.js";import{u as F,a as y,b as ve,s as $e,c as Ge,d as J,D as De,e as Be,f as We,g as Ie,h as _e,i as Pe,j as T,k as U,B as xe,_ as Ve,S as Qe,l as Je,m as Ye,C as Xe,n as Ze}from"./index-DId2GJVO.js";import{U as Ne,Q as et,G as tt,Z as st,L as A,E as at,T as se,C as ne,_ as rt,w as nt,$ as it,B as ot,a0 as Le,z as ie,n as ge,R as ke,t as lt,H as ct,a1 as Oe,V as dt,a2 as ut,a3 as mt,a4 as ht,P as Ue,a5 as xt,X as He,a6 as pt,a7 as ft,f as je,a8 as bt,a9 as vt,aa as gt,W as kt,a as jt}from"./vendor-icons-C927DZlr.js";import{k as yt,g as wt,l as Nt,e as St,t as Ct,j as Et}from"./session-events-BvtUOaNG.js";import{j as Tt,k as Mt,l as At,m as Ke}from"./vendor-radix-DXRuAJHH.js";function Se(t){return t.split("/").filter(Boolean).at(-1)||t}function Rt(){const t=F(),s=y(S=>S.sessions),a=y(S=>S.currentSessionRef),r=y(S=>S.taskDeliveryActions),i=y(S=>S.deliverTask),n=ve(S=>S.openFilePreview),[d,f]=b.useState(!1),c=s.find(S=>$e({sessionId:S.sessionId,projectPath:S.projectPath},a));if(!(c!=null&&c.taskIsolation))return null;const l=c.taskDiffStat,k=c.taskIsolation==="worktree",o=Ge(c),h=r[J(o)],u=c.taskDelivery,j=(u==null?void 0:u.status)==="conflicted",N=!!(l&&(l.changedFiles>0||l.commits>0)),m=!["queued","running"].includes(c.taskStatus),w=(u==null?void 0:u.status)==="applied"||(u==null?void 0:u.status)==="discarded",g=k&&N&&m&&!w,p=l?l.additions+l.deletions:0,x=p>0&&l?l.additions/p*100:0,E=S=>{i(o,S).catch(()=>{})};return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex min-h-10 flex-wrap items-center gap-x-3 gap-y-1.5 border-b border-[hsl(var(--deck-hairline))] bg-[hsl(var(--deck-canvas-veil))]/60 px-3 py-1.5 font-mono text-[10.5px] text-[hsl(var(--deck-ink-muted))] backdrop-blur-sm sm:px-5",children:[e.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-3",children:[e.jsxs("span",{className:"inline-flex min-w-0 items-center gap-1.5",children:[e.jsx(Ne,{className:"h-3 w-3 shrink-0 text-[hsl(var(--deck-ink-faint))]"}),e.jsx("span",{className:"truncate text-[hsl(var(--deck-ink))]",children:Se(c.taskSourceProjectPath||c.projectPath)})]}),e.jsx("span",{className:"text-[hsl(var(--deck-ink-faint))]/60",children:"/"}),e.jsxs("span",{className:"inline-flex min-w-0 items-center gap-1.5",children:[k?e.jsx(et,{className:"h-3 w-3 shrink-0 text-[hsl(var(--deck-accent))]"}):e.jsx(Ne,{className:"h-3 w-3 shrink-0"}),e.jsx("span",{className:k?"text-[hsl(var(--deck-accent))]":void 0,children:t(k?"artifact.env.isolated":"artifact.env.local")})]}),c.taskWorktreeBranch&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-[hsl(var(--deck-ink-faint))]/60",children:"/"}),e.jsxs("span",{className:"inline-flex min-w-0 items-center gap-1.5 truncate",title:c.taskWorktreeBranch,children:[e.jsx(tt,{className:"h-3 w-3 shrink-0 text-[hsl(var(--deck-ink-faint))]"}),e.jsx("span",{className:"truncate",children:c.taskWorktreeBranch})]})]})]}),l&&e.jsxs("div",{className:"ml-auto flex max-w-full items-center gap-2",children:[e.jsxs("span",{className:"inline-flex items-center gap-1 text-[hsl(var(--deck-ink-muted))]",children:[e.jsx(st,{className:"h-3 w-3 text-[hsl(var(--deck-ink-faint))]"}),e.jsx("span",{className:"tabular-nums",children:l.changedFiles})]}),p>0&&e.jsxs("span",{className:"relative hidden h-1.5 w-14 overflow-hidden rounded-sm border border-[hsl(var(--deck-border))] bg-[hsl(var(--deck-surface))] sm:inline-flex","aria-hidden":"true",children:[e.jsx("span",{className:"h-full bg-[hsl(var(--deck-accent))]",style:{width:`${x}%`}}),e.jsx("span",{className:"h-full bg-red-500/80",style:{width:`${100-x}%`}})]}),e.jsxs("span",{className:"tabular-nums text-[hsl(var(--deck-accent))]",children:["+",l.additions]}),e.jsxs("span",{className:"tabular-nums text-red-600 dark:text-red-400",children:["-",l.deletions]}),l.commits>0&&e.jsx("span",{className:"hidden tabular-nums text-[hsl(var(--deck-ink-faint))] sm:inline",children:t("artifact.commits",{count:l.commits})}),N&&(u==null?void 0:u.status)!=="discarded"&&e.jsx("button",{type:"button",onClick:()=>n({tab:"diff"}),className:"inline-flex items-center gap-1 rounded-md border border-[hsl(var(--deck-border))] bg-[hsl(var(--deck-surface))] px-2 py-1 text-[hsl(var(--deck-ink))] transition hover:border-[hsl(var(--deck-accent)/0.55)] hover:text-[hsl(var(--deck-accent))]",children:t("artifact.review")}),g&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{type:"button",disabled:!!h,onClick:()=>E("apply"),className:"inline-flex items-center gap-1 rounded-md bg-[hsl(var(--deck-accent))] px-2 py-1 font-semibold text-white transition hover:brightness-95 disabled:cursor-wait disabled:opacity-65",children:[h==="apply"?e.jsx(A,{className:"h-3 w-3 animate-spin"}):e.jsx(at,{className:"h-3 w-3"}),t(h==="apply"?"artifact.applying":j?"artifact.retryApply":"artifact.apply")]}),e.jsx("button",{type:"button",disabled:!!h,onClick:()=>f(!0),className:"inline-flex items-center gap-1 rounded-md px-1.5 py-1 text-[hsl(var(--deck-ink-faint))] transition hover:bg-red-500/10 hover:text-red-600 disabled:cursor-wait disabled:opacity-50 dark:hover:text-red-400","aria-label":t("artifact.discard"),title:t("artifact.discard"),children:h==="discard"?e.jsx(A,{className:"h-3 w-3 animate-spin"}):e.jsx(se,{className:"h-3 w-3"})})]}),(u==null?void 0:u.status)==="applied"&&e.jsxs("span",{className:"inline-flex items-center gap-1 rounded-md bg-emerald-500/10 px-2 py-1 font-semibold text-emerald-700 dark:text-emerald-300",children:[e.jsx(ne,{className:"h-3 w-3"}),t("artifact.applied")]}),(u==null?void 0:u.status)==="discarded"&&e.jsxs("span",{className:"inline-flex items-center gap-1 rounded-md bg-[hsl(var(--deck-surface-2))] px-2 py-1 text-[hsl(var(--deck-ink-faint))]",children:[e.jsx(se,{className:"h-3 w-3"}),t("artifact.discarded")]})]}),(u==null?void 0:u.status)==="conflicted"&&e.jsxs("div",{className:"flex w-full items-start gap-1.5 border-t border-amber-500/20 pt-1.5 text-amber-700 dark:text-amber-300",role:"alert",children:[e.jsx(rt,{className:"mt-0.5 h-3 w-3 shrink-0"}),e.jsxs("span",{className:"min-w-0 flex-1 space-y-0.5",children:[e.jsx("span",{className:"block",children:u.message||t("artifact.conflict")}),e.jsx("span",{className:"block text-[hsl(var(--deck-ink-faint))]",children:t("artifact.conflictHint")})]})]})]}),e.jsx(De,{open:d,onOpenChange:f,children:e.jsxs(Be,{className:"w-[calc(100%_-_2rem)] max-w-md border-[hsl(var(--deck-border))] bg-[hsl(var(--deck-surface))] text-[hsl(var(--deck-ink))]",children:[e.jsxs(We,{children:[e.jsx(Ie,{children:t("artifact.discardDialog.title")}),e.jsx(_e,{className:"text-[hsl(var(--deck-ink-muted))]",children:t("artifact.discardDialog.description",{project:Se(c.taskSourceProjectPath||c.projectPath),count:(l==null?void 0:l.changedFiles)??0})})]}),e.jsx("div",{className:"rounded-lg border border-red-500/20 bg-red-500/5 px-3 py-2 text-xs leading-relaxed text-red-700 dark:text-red-300",children:t("artifact.discardDialog.warning")}),e.jsxs(Pe,{className:"gap-2 sm:space-x-0",children:[e.jsx("button",{type:"button",onClick:()=>f(!1),className:"rounded-md border border-[hsl(var(--deck-border))] px-3 py-2 text-sm hover:bg-[hsl(var(--deck-surface-2))]",children:t("artifact.discardDialog.cancel")}),e.jsxs("button",{type:"button",onClick:()=>{f(!1),E("discard")},className:"inline-flex items-center justify-center gap-1.5 rounded-md bg-red-600 px-3 py-2 text-sm font-semibold text-white hover:bg-red-700",children:[e.jsx(se,{className:"h-3.5 w-3.5"}),t("artifact.discardDialog.confirm")]})]})]})})]})}const Ft=new Set(["completed","stale","failed","aborted","interrupted"]),$t={completed:"chat.review.status.completed",stale:"chat.review.status.stale",failed:"chat.review.status.failed",aborted:"chat.review.status.aborted",interrupted:"chat.review.status.interrupted"},Dt={completed:"bg-emerald-500/10 text-emerald-700 dark:text-emerald-300 border-emerald-500/20",stale:"bg-amber-500/10 text-amber-700 dark:text-amber-300 border-amber-500/20",failed:"bg-red-500/10 text-red-700 dark:text-red-300 border-red-500/20",aborted:"bg-zinc-500/10 text-zinc-700 dark:text-zinc-300 border-zinc-500/20",interrupted:"bg-amber-500/10 text-amber-700 dark:text-amber-300 border-amber-500/20"};function ae(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:void 0}function Bt(t){const s=ae(t),a=ae(s==null?void 0:s.codeLocation),r=s==null?void 0:s.priority,i=s==null?void 0:s.confidenceScore,n=a==null?void 0:a.lineStart,d=a==null?void 0:a.lineEnd;if(!(typeof(s==null?void 0:s.title)!="string"||typeof s.body!="string"||r!==0&&r!==1&&r!==2&&r!==3||typeof i!="number"||!Number.isFinite(i)||typeof(a==null?void 0:a.path)!="string"||!Number.isInteger(n)||!Number.isInteger(d)))return{title:s.title,body:s.body,priority:r,confidenceScore:i,codeLocation:{path:a.path,lineStart:n,lineEnd:d}}}function It(t){const s=ae(t),a=ae(s==null?void 0:s.target);if((s==null?void 0:s.phase)!=="completed"||typeof s.status!="string"||!Ft.has(s.status)||typeof(a==null?void 0:a.label)!="string"||a.kind!=="uncommitted"&&a.kind!=="base"&&a.kind!=="commit"||typeof s.overallExplanation!="string"||!Array.isArray(s.findings))return;const r=s.findings.map(Bt);if(!r.some(i=>i===void 0))return{status:s.status,target:{kind:a.kind,label:a.label,...typeof a.reference=="string"?{reference:a.reference}:{}},overallExplanation:s.overallExplanation,findings:r,...typeof s.error=="string"?{error:s.error}:{}}}function _t(t){const{path:s,lineStart:a,lineEnd:r}=t.codeLocation;return a===r?`${s}:L${a}`:`${s}:L${a}-${r}`}function Pt({report:t}){const s=F(),a=t.target.kind==="uncommitted"?s("chat.review.target.uncommitted"):t.target.kind==="base"?s("chat.review.target.base",{ref:t.target.reference??t.target.label}):s("chat.review.target.commit",{ref:t.target.reference??t.target.label});return e.jsxs("section",{"data-code-review-report":!0,className:"overflow-hidden rounded-xl border border-[hsl(var(--deck-border))] bg-[hsl(var(--deck-surface))]",children:[e.jsxs("header",{className:"flex flex-wrap items-center justify-between gap-3 border-b border-[hsl(var(--deck-hairline))] bg-[hsl(var(--deck-surface-2))]/60 px-4 py-3",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-[13px] font-semibold text-[hsl(var(--deck-ink))]",children:s("chat.review.title")}),e.jsxs("p",{className:"mt-0.5 font-mono text-[10.5px] text-[hsl(var(--deck-ink-faint))]",children:[s("chat.review.target"),": ",a]})]}),e.jsxs("span",{className:T("rounded-full border px-2.5 py-1 font-mono text-[10.5px] font-medium",Dt[t.status]),children:[s("chat.review.status"),": ",s($t[t.status])]})]}),e.jsxs("div",{className:"space-y-4 px-4 py-3.5",children:[e.jsx("p",{className:"whitespace-pre-wrap text-[13px] leading-6 text-[hsl(var(--deck-ink-muted))]",children:t.overallExplanation}),e.jsxs("div",{children:[e.jsxs("div",{className:"mb-2 flex items-center justify-between",children:[e.jsx("h4",{className:"deck-eyebrow text-[hsl(var(--deck-ink-faint))]",children:s("chat.review.findings")}),e.jsx("span",{className:"font-mono text-[10px] text-[hsl(var(--deck-ink-faint))]",children:t.findings.length})]}),t.findings.length===0?e.jsx("div",{className:"rounded-lg bg-[hsl(var(--deck-surface-2))] px-3 py-2.5 text-[12px] text-[hsl(var(--deck-ink-muted))]",children:s("chat.review.noFindings")}):e.jsx("ol",{className:"space-y-2",children:t.findings.map((r,i)=>e.jsxs("li",{className:"rounded-lg border border-[hsl(var(--deck-hairline))] bg-[hsl(var(--deck-canvas-veil))] px-3 py-2.5",children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-2",children:[e.jsx("h5",{className:"text-[12.5px] font-medium leading-5 text-[hsl(var(--deck-ink))]",children:r.title}),e.jsx("span",{className:"shrink-0 font-mono text-[10px] text-[hsl(var(--deck-ink-faint))]",children:s("chat.review.confidence",{value:r.confidenceScore.toFixed(2)})})]}),e.jsx("code",{className:"mt-1 block text-[10.5px] text-[hsl(var(--deck-accent))]",children:_t(r)}),e.jsx("p",{className:"mt-1.5 whitespace-pre-wrap text-[12px] leading-5 text-[hsl(var(--deck-ink-muted))]",children:r.body})]},`${r.codeLocation.path}:${r.codeLocation.lineStart}:${i}`))})]}),t.error&&e.jsxs("div",{className:"rounded-lg border border-red-500/20 bg-red-500/5 px-3 py-2 text-[11px] text-red-700 dark:text-red-300",children:[e.jsxs("span",{className:"font-medium",children:[s("chat.review.error"),":"]})," ",t.error]})]})]})}function Vt({elicitation:t,messageId:s}){const a=F(),r=y(g=>g.currentSessionRef),i=y(g=>g.setElicitation),[n,d]=b.useState(()=>Ot(t.details.fields??[])),[f,c]=b.useState(()=>Ut(t.details.fields??[])),[l,k]=b.useState(!1),[o,h]=b.useState(),u=t.details.fields??[],j=b.useMemo(()=>u.every(g=>{var x;if(!g.required)return!0;if(oe(g))return!!((x=f[g.name])!=null&&x.trim()||g.defaultValue!==void 0);const p=n[g.name]??g.defaultValue;return Array.isArray(p)?p.length>0:p!==void 0}),[u,f,n]);if(t.status!=="pending")return e.jsx("div",{className:"rounded-lg border border-[hsl(var(--deck-border))] bg-[hsl(var(--deck-surface-2))] px-3 py-2 font-mono text-[12px] text-[hsl(var(--deck-ink-muted))]",children:a(t.status==="cancelled"?"interaction.elicitation.cancelled":"interaction.elicitation.responded")});const N=async(g,p)=>{if(!(!r||l)){k(!0),h(void 0);try{await U.respondToElicitation(r,t.toolCallId,{action:g,...p?{content:p}:{}}),i(s,{...t,status:"responded"})}catch(x){h(x instanceof Error?x.message:a("interaction.elicitation.failed"))}finally{k(!1)}}},m=async()=>{try{await N("accept",Ht(u,n,f))}catch(g){h(g instanceof Error?g.message:String(g))}},w=()=>{const g=t.details.url;if(!g){h("MCP URL is unavailable");return}if(!window.open(g,"_blank","noopener,noreferrer")){h("The browser blocked the external window");return}N("accept")};return e.jsxs("div",{"data-pending-interaction":"elicitation",tabIndex:-1,role:"alert",className:"space-y-4 rounded-lg border border-amber-300/70 bg-amber-50/70 p-4 outline-none focus-visible:ring-2 focus-visible:ring-amber-500 dark:border-amber-800/70 dark:bg-amber-950/25",children:[e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(nt,{className:"mt-0.5 h-4 w-4 shrink-0 text-amber-600 dark:text-amber-400"}),e.jsxs("div",{className:"min-w-0 space-y-1",children:[e.jsxs("div",{className:"font-mono text-[12px] font-semibold text-[hsl(var(--deck-ink))]",children:[a("interaction.elicitation.title")," · ",t.details.serverName]}),e.jsx("div",{className:"font-mono text-[12px] text-[hsl(var(--deck-ink-muted))]",children:t.details.message}),e.jsx("div",{className:"font-mono text-[11px] text-amber-700 dark:text-amber-300",children:a("interaction.elicitation.warning")})]})]}),t.details.mode==="url"?e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"rounded-md border border-[hsl(var(--deck-border))] bg-[hsl(var(--deck-surface-2))] p-3 font-mono text-[11px]",children:[e.jsx("div",{className:"text-[hsl(var(--deck-ink-muted))]",children:t.details.domain}),e.jsx("div",{className:"mt-1 break-all text-[hsl(var(--deck-ink))]",children:t.details.url})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(q,{onClick:w,disabled:l,primary:!0,label:a("interaction.elicitation.open"),icon:e.jsx(it,{className:"h-3.5 w-3.5"})}),e.jsx(q,{onClick:()=>void N("decline"),disabled:l,label:a("interaction.elicitation.decline")}),e.jsx(q,{onClick:()=>void N("cancel"),disabled:l,label:a("interaction.elicitation.cancel")})]})]}):e.jsxs("div",{className:"space-y-4",children:[u.map(g=>e.jsx(Lt,{field:g,value:n[g.name],rawValue:f[g.name]??"",onValueChange:p=>d(x=>({...x,[g.name]:p})),onRawChange:p=>c(x=>({...x,[g.name]:p}))},g.name)),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(q,{onClick:()=>void m(),disabled:l||!j,primary:!0,label:a("interaction.elicitation.submit"),icon:l?e.jsx(A,{className:"h-3.5 w-3.5 animate-spin"}):null}),e.jsx(q,{onClick:()=>void N("decline"),disabled:l,label:a("interaction.elicitation.decline")}),e.jsx(q,{onClick:()=>void N("cancel"),disabled:l,label:a("interaction.elicitation.cancel")})]})]}),o&&e.jsx("div",{className:"rounded-md border border-red-300/70 bg-red-50 px-2.5 py-2 font-mono text-[11px] text-red-700 dark:border-red-900/70 dark:bg-red-950/35 dark:text-red-300",children:o})]})}function Lt({field:t,value:s,rawValue:a,onValueChange:r,onRawChange:i}){return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{htmlFor:`mcp-elicitation-${t.name}`,className:"block font-mono text-[12px] font-medium text-[hsl(var(--deck-ink))]",children:[t.title,t.required?" *":""]}),t.description&&e.jsx("div",{className:"font-mono text-[11px] text-[hsl(var(--deck-ink-faint))]",children:t.description}),t.type==="select"||t.type==="multi-select"||t.type==="boolean"?e.jsx("div",{id:`mcp-elicitation-${t.name}`,className:"flex flex-wrap gap-2",children:Kt(t).map(n=>{const d=Array.isArray(s)?s.includes(n.value):s===n.typedValue;return e.jsx("button",{type:"button","aria-pressed":d,onClick:()=>{if(t.type==="multi-select"){const f=Array.isArray(s)?s:[];r(f.includes(n.value)?f.filter(c=>c!==n.value):[...f,n.value])}else r(n.typedValue)},className:T("rounded-md border px-3 py-2 font-mono text-[12px] transition-colors",d?"border-emerald-500 bg-emerald-50 text-emerald-800 dark:bg-emerald-950/40 dark:text-emerald-200":"border-[hsl(var(--deck-border))] bg-[hsl(var(--deck-surface-2))] text-[hsl(var(--deck-ink-muted))] hover:text-[hsl(var(--deck-ink))]"),children:n.label},n.value)})}):e.jsx("input",{id:`mcp-elicitation-${t.name}`,type:qt(t),value:a,onChange:n=>i(n.target.value),min:t.minimum,max:t.maximum,minLength:t.minLength,maxLength:t.maxLength,required:t.required,placeholder:t.defaultValue===void 0?t.required?"Required":"Optional":String(t.defaultValue),className:"w-full rounded-md border border-[hsl(var(--deck-border))] bg-[hsl(var(--deck-surface-2))] px-3 py-2 font-mono text-[12px] text-[hsl(var(--deck-ink))] outline-none transition-colors focus:border-amber-500 focus:ring-1 focus:ring-amber-500"})]})}function q({onClick:t,disabled:s,primary:a=!1,label:r,icon:i}){return e.jsxs("button",{type:"button",onClick:t,disabled:s,className:T("inline-flex min-h-8 items-center gap-1.5 rounded-md px-3 py-1.5 font-mono text-[12px] transition-colors disabled:cursor-wait disabled:opacity-50",a?"bg-amber-600 text-white hover:bg-amber-700":"border border-[hsl(var(--deck-border))] bg-[hsl(var(--deck-surface-2))] text-[hsl(var(--deck-ink-muted))] hover:text-[hsl(var(--deck-ink))]"),children:[i,r]})}function Ot(t){return Object.fromEntries(t.filter(s=>!oe(s)&&s.defaultValue!==void 0).map(s=>[s.name,Array.isArray(s.defaultValue)?[...s.defaultValue]:s.defaultValue]))}function Ut(t){return Object.fromEntries(t.filter(s=>oe(s)&&s.defaultValue!==void 0).map(s=>[s.name,String(s.defaultValue)]))}function Ht(t,s,a){var i;const r={};for(const n of t){if(oe(n)){const f=((i=a[n.name])==null?void 0:i.trim())??"";if(!f){if(n.defaultValue!==void 0)r[n.name]=n.defaultValue;else if(n.required)throw new Error(`${n.title} is required`);continue}if(n.type==="number"||n.type==="integer"){const c=Number(f);if(!Number.isFinite(c))throw new Error(`${n.title} must be a finite number`);if(n.type==="integer"&&!Number.isSafeInteger(c))throw new Error(`${n.title} must be a safe integer`);r[n.name]=c}else r[n.name]=f;continue}const d=s[n.name]??n.defaultValue;if(d===void 0){if(n.required)throw new Error(`${n.title} is required`);continue}if(Array.isArray(d)){if(n.minItems!==void 0&&d.length<n.minItems)throw new Error(`${n.title} requires at least ${n.minItems} choices`);if(n.maxItems!==void 0&&d.length>n.maxItems)throw new Error(`${n.title} allows at most ${n.maxItems} choices`)}r[n.name]=d}return r}function Kt(t){return t.type==="boolean"?[{value:"true",label:"Yes",typedValue:!0},{value:"false",label:"No",typedValue:!1}]:(t.options??[]).map(s=>({...s,typedValue:s.value}))}function oe(t){return t.type==="string"||t.type==="number"||t.type==="integer"}function qt(t){return t.type==="number"||t.type==="integer"?"number":t.format==="email"?"email":t.format==="uri"?"url":t.format==="date"?"date":t.format==="date-time"?"datetime-local":"text"}function zt(t){if(!t||typeof t!="object"||Array.isArray(t))return;const s=t;if(!(!s.output||typeof s.output!="object"||Array.isArray(s.output)))return{output:s.output,...typeof s.schemaDigest=="string"?{schemaDigest:s.schemaDigest}:{}}}function Gt({report:t}){const s=F(),[a,r]=b.useState(!1),i=JSON.stringify(t.output,null,2),n=async()=>{try{await navigator.clipboard.writeText(i),r(!0),window.setTimeout(()=>r(!1),1400)}catch{}};return e.jsxs("section",{"data-structured-output":!0,className:"overflow-hidden rounded-lg border border-[hsl(var(--deck-border))] bg-[hsl(var(--deck-surface))]",children:[e.jsxs("header",{className:"flex min-h-9 items-center justify-between gap-3 border-b border-[hsl(var(--deck-border))] bg-[hsl(var(--deck-surface-2))] px-3",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[e.jsx(ot,{className:"h-3.5 w-3.5 shrink-0 text-[hsl(var(--deck-accent))]"}),e.jsx("span",{className:"font-mono text-[11px] font-semibold text-[hsl(var(--deck-ink))]",children:s("chat.structuredOutput.title")}),t.schemaDigest&&e.jsxs("span",{title:t.schemaDigest,className:"truncate font-mono text-[9px] text-[hsl(var(--deck-ink-faint))]",children:["sha256:",t.schemaDigest.slice(0,10)]})]}),e.jsx("button",{type:"button",onClick:n,"aria-label":s("chat.structuredOutput.copy"),title:s("chat.structuredOutput.copy"),className:"flex h-6 w-6 shrink-0 items-center justify-center rounded text-[hsl(var(--deck-ink-faint))] hover:bg-[hsl(var(--deck-surface))] hover:text-[hsl(var(--deck-ink))] focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-[hsl(var(--deck-accent))]",children:a?e.jsx(ne,{className:"h-3.5 w-3.5 text-[hsl(var(--deck-accent))]"}):e.jsx(Le,{className:"h-3.5 w-3.5"})})]}),e.jsx("pre",{className:"max-h-[440px] overflow-auto whitespace-pre p-3 font-mono text-[11px] leading-5 text-[hsl(var(--deck-ink))]",children:i})]})}const Wt=b.lazy(()=>Ve(()=>import("./MarkdownRenderer-D6LiW9kF.js").then(t=>t.M),__vite__mapDeps([0,1,2,3,4,5,6])).then(t=>({default:t.MarkdownRenderer})));function Ce({text:t,label:s}){const[a,r]=b.useState(!1);if(!t.trim())return null;const i=async()=>{try{await navigator.clipboard.writeText(t),r(!0),window.setTimeout(()=>r(!1),1400)}catch{}};return e.jsx("button",{type:"button","aria-label":s,title:s,onClick:i,className:"flex h-6 w-6 items-center justify-center rounded-md text-[hsl(var(--deck-ink-faint))] transition-colors hover:bg-[hsl(var(--deck-surface))] hover:text-[hsl(var(--deck-ink))] focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-[hsl(var(--deck-accent))]",children:a?e.jsx(ne,{className:"h-3.5 w-3.5 text-[hsl(var(--deck-accent))]"}):e.jsx(Le,{className:"h-3.5 w-3.5"})})}function Qt(){return e.jsx("div",{className:"flex h-8 w-8 shrink-0 select-none items-center justify-center rounded-lg border border-[hsl(var(--deck-border))] bg-[hsl(var(--deck-surface))] shadow-[0_1px_0_hsl(var(--deck-hairline))]",children:e.jsx(xe,{size:20,pulse:!1})})}function Jt(){return e.jsx("div",{className:"flex h-8 w-8 shrink-0 select-none items-center justify-center rounded-full border border-[hsl(var(--deck-border))] bg-[hsl(var(--deck-canvas-veil))]",children:e.jsx("span",{className:"font-mono text-[11px] font-medium text-[hsl(var(--deck-ink))]",children:"U"})})}function Ee(t){let s=t;return s=s.replace(/<system-reminder>[\s\S]*?<\/system-reminder>/g,""),s=s.replace(/<file path="[^"]*">[\s\S]*?<\/file>/g,""),s=s.replace(/<attached_files>[\s\S]*?<\/attached_files>/g,""),s=s.trim(),s}function Yt(t){if(typeof t=="string")return{text:Ee(t),images:[]};const s=t.filter(r=>r.type==="text").map(r=>r.text).join(`
3
- `),a=t.filter(r=>r.type==="image_url").map(r=>r.image_url.url);return{text:Ee(s),images:a}}function ye(t){return typeof t=="string"?t:t.filter(s=>s.type==="text").map(s=>s.text).join(`
4
- `)}function Xt(t){const s=t.agentContent;return s?yt(s):ye(t.content)}function Te({content:t,syntaxHighlight:s=!0}){return e.jsx(b.Suspense,{fallback:e.jsx("pre",{className:"text-[14px] text-[hsl(var(--deck-ink))] font-mono whitespace-pre-wrap",children:t}),children:e.jsx(Wt,{content:t,syntaxHighlight:s})})}function we({status:t}){if(!t)return null;const s={running:"bg-[#FEF3C7] text-[#92400E] dark:bg-[#F59E0B]/20 dark:text-[#FBBF24]",success:"bg-[#DCFCE7] text-[#15803D] dark:bg-[#22C55E]/20 dark:text-[#22C55E]",error:"bg-[#FEE2E2] text-[#b91c1c] dark:bg-[#EF4444]/20 dark:text-[#fca5a5]",pending:"bg-[#E5E7EB] text-[#6B7280] dark:bg-[#27272a] dark:text-[#a1a1aa]",info:"bg-[#DBEAFE] text-[#1D4ED8] dark:bg-[#3B82F6]/20 dark:text-[#60A5FA]"},a={running:"Running",success:"Success",error:"Error",pending:"Pending",info:"Info"};return e.jsx("span",{className:T("text-[11px] px-2 py-0.5 rounded-full font-mono",s[t]),children:a[t]})}function Zt(t){if(!t)return"";if(typeof t=="string")try{return JSON.stringify(JSON.parse(t),null,2)}catch{return t}return JSON.stringify(t,null,2)}const Me=500;function qe(t,s){if(t.length<=s)return t;let a=Math.max(0,s);return a>0&&/[\uD800-\uDBFF]/.test(t.charAt(a-1))&&(a-=1),t.slice(0,a)}function Ae(t,s){if(t.length<=s)return t;let a=Math.max(0,t.length-s);return/[\uDC00-\uDFFF]/.test(t.charAt(a))&&(a+=1),t.slice(a)}function de(t,s){if(t.length<=s)return t;if(s<=0)return"";const a=`
5
- ... (display clipped) ...
6
- `,r=s-a.length;if(r<=0)return Ae(t,s);const i=Math.floor(r/3);return`${qe(t,i)}${a}${Ae(t,r-i)}`}function es(t){const s=t.split(`
7
- `),a=s.at(-1),r=a!=null&&a.startsWith("Output truncated")?a:void 0,i=r?s.slice(0,-1).join(`
8
- `):t,n=r?`
9
- ${r}`:"",d=Math.max(0,Me-n.length),c=i.indexOf(`
10
- stderr:
11
- `);let l;if(c>=0&&i.includes(`
12
- stdout:
13
- `)){const k=i.slice(0,c),o=i.slice(c+1),h=Math.max(0,d-1),u=Math.floor(h/2);l=`${de(k,u)}
14
- ${de(o,h-u)}`}else l=de(i,d);return{body:qe(l,d),...r?{notice:r}:{},truncated:!!r||t.length>Me}}function ts({tool:t}){const[s,a]=b.useState(!1),r=Zt(t.arguments),i=t.output?es(t.output):void 0;return e.jsxs("div",{"data-tool-name":t.toolName,"data-tool-status":t.status,"data-tool-truncated":i!=null&&i.truncated?"true":"false",className:"bg-white dark:bg-[#18181b] border border-[hsl(var(--deck-border))] rounded-lg overflow-hidden",children:[e.jsxs("button",{type:"button","aria-expanded":s,"data-tool-call-id":t.toolCallId,onClick:()=>a(n=>!n),className:"w-full flex items-center justify-between px-3 py-2 bg-[hsl(var(--deck-surface-2))] hover:bg-[hsl(var(--deck-surface))] transition-colors",children:[e.jsxs("div",{className:"flex gap-2 items-center min-w-0",children:[s?e.jsx(ie,{className:"h-4 w-4 text-[hsl(var(--deck-ink-faint))] shrink-0"}):e.jsx(ge,{className:"h-4 w-4 text-[hsl(var(--deck-ink-faint))] shrink-0"}),e.jsx("span",{className:"text-[12px] text-[hsl(var(--deck-ink))] font-mono shrink-0",children:t.toolName}),t.summary&&e.jsx("span",{className:"text-[11px] text-[hsl(var(--deck-ink-muted))] font-mono truncate",children:t.summary})]}),e.jsx(we,{status:t.status})]}),t.status==="running"&&t.progressMessage&&e.jsxs("div",{className:"border-t border-[hsl(var(--deck-border))] px-3 py-2 space-y-1.5",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3 font-mono text-[10px] text-[hsl(var(--deck-ink-muted))]",children:[e.jsx("span",{className:"truncate",children:t.progressMessage}),t.progressTotal!==void 0&&t.progress!==void 0&&e.jsxs("span",{className:"shrink-0",children:[Math.max(0,Math.min(100,Math.round(t.progress/t.progressTotal*100))),"%"]})]}),t.progressTotal!==void 0&&t.progress!==void 0&&e.jsx("div",{role:"progressbar","aria-label":`${t.toolName} progress`,"aria-valuemin":0,"aria-valuemax":t.progressTotal,"aria-valuenow":Math.min(t.progress,t.progressTotal),className:"h-1 overflow-hidden rounded-full bg-[hsl(var(--deck-border))]",children:e.jsx("div",{className:"h-full rounded-full bg-amber-500 transition-[width] duration-150",style:{width:`${Math.max(0,Math.min(100,t.progress/t.progressTotal*100))}%`}})})]}),s&&e.jsxs("div",{className:"px-3 py-2 space-y-2 border-t border-[hsl(var(--deck-border))]",children:[r&&e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"text-[11px] text-[hsl(var(--deck-ink-muted))] font-mono",children:"Arguments"}),e.jsx("pre",{className:"text-[11px] text-[hsl(var(--deck-ink))] bg-[hsl(var(--deck-surface-2))] border border-[hsl(var(--deck-border))] rounded-md p-2 overflow-x-auto whitespace-pre-wrap font-mono max-h-[120px] overflow-y-auto",children:r})]}),i&&e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"text-[11px] text-[hsl(var(--deck-ink-muted))] font-mono",children:"Output"}),e.jsxs("pre",{"data-tool-output":!0,className:"text-[11px] text-[hsl(var(--deck-ink))] bg-[hsl(var(--deck-surface-2))] border border-[hsl(var(--deck-border))] rounded-md p-2 overflow-x-auto whitespace-pre-wrap font-mono max-h-[120px] overflow-y-auto",children:[i.body,i.notice&&e.jsxs(e.Fragment,{children:[`
15
- `,e.jsx("span",{"data-tool-truncation-notice":!0,children:i.notice})]})]})]})]})]})}function ze({toolCalls:t}){return t.length===0?null:e.jsx("div",{className:"space-y-2",children:t.map(s=>e.jsx(ts,{tool:s},s.toolCallId))})}function ss({toolCalls:t,toolCallIds:s}){const a=F(),[r,i]=b.useState(!1),n=b.useMemo(()=>new Map(t.map(o=>[o.toolCallId,o])),[t]),d=s.flatMap(o=>{const h=n.get(o);return h?[h]:[]});if(d.length===0)return null;const f=d.filter(o=>o.status==="running").length,c=d.filter(o=>o.status==="error").length,l=[...d].reverse().find(o=>o.status==="running"&&!!o.progressMessage),k=f>0?a(d.length===1?"chat.timeline.tools.runningOne":"chat.timeline.tools.running",{count:d.length}):c>0?a(d.length===1?"chat.timeline.tools.completedOneWithError":"chat.timeline.tools.completedWithErrors",{count:d.length,errors:c}):a(d.length===1?"chat.timeline.tools.completedOne":"chat.timeline.tools.completed",{count:d.length});return e.jsxs("div",{"data-agent-tool-group":!0,className:"py-0.5",children:[e.jsxs("button",{type:"button","aria-expanded":r,onClick:()=>i(o=>!o),className:"group flex min-h-7 w-full items-center gap-1.5 rounded-md px-1.5 text-left font-mono text-[11.5px] text-[hsl(var(--deck-ink-faint))] transition-colors hover:bg-[hsl(var(--deck-surface))]/65 hover:text-[hsl(var(--deck-ink-muted))] focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-[hsl(var(--deck-accent))]",children:[r?e.jsx(ie,{className:"h-3.5 w-3.5 shrink-0"}):e.jsx(ge,{className:"h-3.5 w-3.5 shrink-0"}),f>0&&e.jsx(A,{className:"h-3 w-3 shrink-0 animate-spin text-[hsl(var(--deck-accent))]"}),e.jsx("span",{children:k}),(l==null?void 0:l.progressMessage)&&e.jsxs("span",{className:"min-w-0 truncate text-[10.5px] text-[hsl(var(--deck-ink-muted))]",children:[l.progressMessage,l.progress!==void 0&&l.progressTotal!==void 0&&` · ${Math.max(0,Math.min(100,Math.round(l.progress/l.progressTotal*100)))}%`]})]}),(l==null?void 0:l.progress)!==void 0&&l.progressTotal!==void 0&&e.jsx("div",{role:"progressbar","aria-label":`${l.toolName} progress`,"aria-valuemin":0,"aria-valuemax":l.progressTotal,"aria-valuenow":Math.min(l.progress,l.progressTotal),className:"mx-1.5 h-0.5 overflow-hidden rounded-full bg-[hsl(var(--deck-border))]",children:e.jsx("div",{className:"h-full rounded-full bg-amber-500 transition-[width] duration-150",style:{width:`${Math.max(0,Math.min(100,l.progress/l.progressTotal*100))}%`}})}),r&&e.jsx("div",{"data-agent-tool-group-details":!0,className:"mt-2 space-y-2 pl-1",children:e.jsx(ze,{toolCalls:d})})]})}function as({content:t}){const s=F(),[a,r]=b.useState(!1);return t?e.jsxs("div",{"data-agent-thinking":!0,className:"py-0.5",children:[e.jsxs("button",{type:"button","aria-expanded":a,onClick:()=>r(i=>!i),className:"flex min-h-7 w-full items-center gap-1.5 rounded-md px-1.5 text-left font-mono text-[11.5px] text-[hsl(var(--deck-ink-faint))] transition-colors hover:bg-[hsl(var(--deck-surface))]/65 hover:text-[hsl(var(--deck-ink-muted))] focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-[hsl(var(--deck-accent))]",children:[a?e.jsx(ie,{className:"h-4 w-4 text-[hsl(var(--deck-ink-faint))]"}):e.jsx(ge,{className:"h-4 w-4 text-[hsl(var(--deck-ink-faint))]"}),e.jsx("span",{children:s("chat.timeline.thinking")})]}),a&&e.jsx("div",{className:"ml-1 mt-1 border-l border-[hsl(var(--deck-border))] py-1 pl-3",children:e.jsx("pre",{className:"whitespace-pre-wrap font-mono text-[11px] leading-5 text-[hsl(var(--deck-ink-muted))]",children:t})})]}):null}function rs({tasks:t}){if(t.length===0)return null;const s=t.filter(r=>r.status==="completed").length,a=s===t.length;return e.jsx("div",{className:"bg-[hsl(var(--deck-surface-2))] border border-[hsl(var(--deck-border))] rounded-lg px-3 py-2",children:e.jsx("div",{className:"flex gap-2 items-center",children:e.jsx("span",{className:"text-[12px] text-[hsl(var(--deck-ink-muted))] font-mono",children:a?"✓ All tasks done":`Tasks: ${s}/${t.length}`})})})}function ns({toolCalls:t}){const s=ve(r=>r.openFilePreview),a=b.useMemo(()=>{const r=new Map,i=["Write","SearchReplace","Edit","ApplyPatch"];for(const n of t){if(n.status!=="success")continue;const d=n.metadata;if(n.toolName==="ApplyPatch"&&Array.isArray(d==null?void 0:d.changes)){for(const c of d.changes)c&&typeof c=="object"&&"path"in c&&typeof c.path=="string"&&r.set(c.path,{path:c.path,toolName:n.toolName});continue}const f=d==null?void 0:d.file_path;f&&i.includes(n.toolName)&&r.set(f,{path:f,toolName:n.toolName})}return Array.from(r.values())},[t]);return a.length===0?null:e.jsxs("div",{className:"bg-[hsl(var(--deck-surface-2))] border border-[hsl(var(--deck-border))] rounded-lg px-3 py-2",children:[e.jsxs("div",{className:"text-[11px] text-[hsl(var(--deck-ink-muted))] font-mono mb-1.5",children:["Changed files (",a.length,")"]}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:a.map(({path:r})=>{const i=r.split("/").pop()||r;return e.jsxs("button",{onClick:()=>s({tab:"diff",targetPath:r}),className:"flex items-center gap-1 px-2 py-1 text-[11px] font-mono bg-[#E5E7EB] dark:bg-[#27272a] text-[hsl(var(--deck-ink))] rounded hover:bg-[#D1D5DB] dark:hover:bg-[#3f3f46] transition-colors",title:r,children:[e.jsx(lt,{className:"w-3 h-3"}),i]},r)})})]})}function is({subagent:t}){var G,K,Y,X;const s=F(),[a,r]=b.useState(null),[i,n]=b.useState(!1),[d,f]=b.useState(null),[c,l]=b.useState(!1),[k,o]=b.useState(""),[h,u]=b.useState(!1),[j,N]=b.useState(null),[m,w]=b.useState(null),[g,p]=b.useState(null),x=y(M=>M.currentSessionRef),E=y(M=>M.isStreaming),S=y(M=>M.isTemporarySession);if(!t)return null;const D=t.status==="running",R=a!==null?a:D,L=t.toolCalls||d||[],_=t.output||t.thinking||L.length>0||t.sessionId,C=m&&m.status!=="running"?m:g,B=(C==null?void 0:C.id)??t.sessionId,H=((G=C==null?void 0:C.restartRecovery)==null?void 0:G.outcome)==="failed",le=!D&&!E&&!S&&!H&&(m==null?void 0:m.status)!=="running"&&!!(B&&x);b.useEffect(()=>{if(!R||D||!t.sessionId||!(x!=null&&x.projectPath)||d!==null||t.toolCalls&&t.toolCalls.length>0)return;let M=!0;return n(!0),U.getMessages({sessionId:t.sessionId,projectPath:x.projectPath}).then(P=>{var I,$;if(!M)return;const V=St(P),v=new Map;for(const W of V)if(($=(I=W.agentContent)==null?void 0:I.toolCalls)!=null&&$.length)for(const ce of W.agentContent.toolCalls)v.has(ce.toolCallId)||v.set(ce.toolCallId,ce);f(Array.from(v.values()))}).finally(()=>{M&&n(!1)}),()=>{M=!1}},[R,D,t.sessionId,t.toolCalls,d,x==null?void 0:x.projectPath]),b.useEffect(()=>{if(!t.sessionId||!x)return;let M=!0;const P=t.rootAgentId??t.sessionId,V=t.resumeDepth??0;return U.listSubagents(x).then(v=>{if(!M)return;p(v.find($=>$.id===t.sessionId)??null);const I=v.filter($=>$.id!==t.sessionId&&$.rootAgentId===P&&$.resumeDepth>V).sort(($,W)=>W.resumeDepth-$.resumeDepth||W.lastActiveAt-$.lastActiveAt)[0];I&&w(I)}).catch(()=>{}),()=>{M=!1}},[x==null?void 0:x.sessionId,x==null?void 0:x.projectPath,t.sessionId,t.rootAgentId,t.resumeDepth]),b.useEffect(()=>{if(!m||m.status!=="running"||!x)return;let M=!0;const P=async()=>{try{const I=(await U.listSubagents(x)).find($=>$.id===m.id);M&&I&&w(I)}catch{}},V=window.setInterval(()=>{P()},1e3);return()=>{M=!1,window.clearInterval(V)}},[x,m==null?void 0:m.id,m==null?void 0:m.status]);const z=async()=>{if(!(!x||!B||!k.trim()||h)){u(!0),N(null);try{const M=await U.resumeSubagent(x,B,k.trim());w(M.session),o(""),l(!1),r(!0)}catch(M){N(M instanceof Error?M.message:s("chat.subagent.resumeFailed"))}finally{u(!1)}}};return e.jsxs("div",{"data-subagent-id":t.id,"data-subagent-session-id":t.sessionId,className:"bg-[hsl(var(--deck-surface-2))] border border-[hsl(var(--deck-border))] rounded-lg px-3 py-2",children:[e.jsxs("button",{type:"button",onClick:()=>r(!R),className:"flex gap-2 justify-between items-center w-full transition-opacity cursor-pointer hover:opacity-80",children:[e.jsxs("div",{className:"flex gap-2 items-center",children:[D&&e.jsx(A,{className:"h-3 w-3 animate-spin text-[hsl(var(--deck-ink-muted))]"}),e.jsxs("span",{className:"text-[12px] text-[hsl(var(--deck-ink-muted))] font-mono",children:[t.type,": ",t.description]}),e.jsx(we,{status:t.status==="completed"?"success":t.status==="failed"?"error":"running"}),t.type==="verification"&&t.verificationVerdict&&e.jsx("span",{"data-verification-verdict":t.verificationVerdict,className:T("rounded px-1.5 py-0.5 text-[10px] font-semibold uppercase tracking-wide",t.verificationVerdict==="pass"?"bg-emerald-500/10 text-emerald-600 dark:text-emerald-400":t.verificationVerdict==="fail"?"bg-red-500/10 text-red-600 dark:text-red-400":"bg-amber-500/10 text-amber-600 dark:text-amber-400"),children:t.verificationVerdict}),t.resumedFrom&&e.jsx("span",{className:"rounded bg-[#EDE9FE] px-1.5 py-0.5 text-[10px] font-mono text-[#6D28D9] dark:bg-[#2E1065] dark:text-[#C4B5FD]",title:s("chat.subagent.resumedFromTitle",{id:t.resumedFrom}),children:s("chat.subagent.resumedDepth",{depth:t.resumeDepth??1})})]}),_&&e.jsx(ie,{className:T("h-3.5 w-3.5 text-[hsl(var(--deck-ink-muted))] transition-transform",R&&"rotate-180")})]}),!R&&!D&&t.output&&e.jsx("div",{"data-subagent-output-summary":!0,className:"mt-2 max-h-10 overflow-hidden whitespace-pre-wrap break-words font-mono text-[11px] text-[hsl(var(--deck-ink))]",children:t.output}),R&&e.jsxs("div",{className:"mt-2 space-y-2",children:[(t.output||t.thinking)&&e.jsxs(e.Fragment,{children:[t.output&&e.jsx("pre",{className:"text-[11px] text-[hsl(var(--deck-ink))] bg-[hsl(var(--deck-surface-2))] border border-[hsl(var(--deck-border))] rounded-md p-2 overflow-x-auto whitespace-pre-wrap font-mono max-h-[160px] overflow-y-auto",children:t.output}),t.thinking&&e.jsx("pre",{className:"text-[11px] text-[hsl(var(--deck-ink-muted))] bg-[hsl(var(--deck-surface-2))] border border-[hsl(var(--deck-border))] rounded-md p-2 overflow-x-auto whitespace-pre-wrap font-mono max-h-[120px] overflow-y-auto",children:t.thinking})]}),i&&e.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-[hsl(var(--deck-ink-muted))] font-mono",children:[e.jsx(A,{className:"w-3 h-3 animate-spin"}),s("chat.subagent.loadingLogs")]}),!i&&L.length>0&&e.jsx(ze,{toolCalls:L}),m&&e.jsxs("div",{className:"rounded-md border border-[#DDD6FE] bg-[#F5F3FF] p-2 text-[11px] font-mono text-[#5B21B6] dark:border-[#4C1D95] dark:bg-[#1E1B4B] dark:text-[#C4B5FD]",children:[e.jsx("div",{children:s("chat.subagent.resumedAs",{id:m.id,status:m.status,depth:m.resumeDepth??1})}),(((K=m.result)==null?void 0:K.message)||((Y=m.result)==null?void 0:Y.error))&&e.jsx("div",{className:"mt-1 whitespace-pre-wrap text-[hsl(var(--deck-ink))]",children:m.result.message||m.result.error})]}),H&&((X=C==null?void 0:C.result)==null?void 0:X.error)&&e.jsx("div",{role:"alert",className:"text-[11px] text-red-600",children:C.result.error}),le&&e.jsxs("div",{className:"space-y-2",children:[c?e.jsxs("div",{className:"space-y-2 rounded-md border border-[#E5E7EB] bg-white p-2 dark:border-[#27272a] dark:bg-[#111113]",children:[e.jsx("textarea",{"aria-label":s("chat.subagent.followUpAria"),value:k,onChange:M=>o(M.target.value),placeholder:s("chat.subagent.followUpPlaceholder"),rows:3,className:"w-full resize-y rounded border border-[#D1D5DB] bg-white p-2 text-[11px] text-[#111827] outline-none focus:border-[#8B5CF6] dark:border-[#3f3f46] dark:bg-[#18181b] dark:text-[#f4f4f5]"}),e.jsxs("div",{className:"flex gap-2 justify-end",children:[e.jsx("button",{type:"button",onClick:()=>{l(!1),N(null)},className:"rounded px-2 py-1 text-[11px] text-[#6B7280] hover:bg-[#F3F4F6] dark:hover:bg-[#27272a]",children:s("chat.subagent.cancel")}),e.jsxs("button",{type:"button",onClick:()=>void z(),disabled:!k.trim()||h,className:"flex items-center gap-1 rounded bg-[#7C3AED] px-2 py-1 text-[11px] font-medium text-white disabled:opacity-50",children:[h&&e.jsx(A,{className:"w-3 h-3 animate-spin"}),s("chat.subagent.resumeAgent")]})]})]}):e.jsxs("button",{type:"button","aria-label":s("chat.subagent.resumeAria"),onClick:()=>l(!0),className:"flex items-center gap-1.5 rounded-md border border-[#D1D5DB] px-2 py-1 text-[11px] font-medium text-[#374151] transition-colors hover:bg-[#F3F4F6] dark:border-[#3f3f46] dark:text-[#d4d4d8] dark:hover:bg-[#27272a]",children:[e.jsx(ke,{className:"w-3 h-3"}),s("chat.subagent.resume")]}),j&&e.jsx("div",{role:"alert",className:"text-[11px] text-red-600",children:j})]})]})]})}function os({confirmation:t,messageId:s}){const a=F(),[r,i]=b.useState(!1),[n,d]=b.useState(null),f=y(k=>k.currentSessionRef),c=y(k=>k.setConfirmation);if(!t)return null;const l=async(k,o)=>{if(!(!f||r)){i(!0),d(null);try{await U.respondPermission(f,t.toolCallId,{approved:k,scope:o}),c(s,{...t,status:k?"approved":"denied"})}catch(h){d(h instanceof Error?h.message:a("interaction.permission.failed"))}finally{i(!1)}}};return t.status!=="pending"?null:e.jsxs("div",{"data-pending-interaction":"permission",tabIndex:-1,role:"alert",className:"space-y-3 rounded-lg border border-amber-300/70 bg-amber-50/70 p-4 outline-none focus-visible:ring-2 focus-visible:ring-amber-500 dark:border-amber-800/70 dark:bg-amber-950/25",children:[e.jsx("div",{className:"text-[13px] text-[hsl(var(--deck-ink))] font-mono",children:a("interaction.permission.title",{tool:t.toolName})}),e.jsx("div",{className:"text-[12px] text-[hsl(var(--deck-ink-muted))] font-mono",children:t.description}),t.diff&&e.jsx("pre",{className:"text-[11px] text-[hsl(var(--deck-ink))] bg-[hsl(var(--deck-surface-2))] border border-[hsl(var(--deck-border))] rounded-md p-2 overflow-x-auto whitespace-pre-wrap font-mono max-h-[200px] overflow-y-auto",children:t.diff}),n&&e.jsx("div",{role:"alert",className:"rounded-md border border-red-300/70 bg-red-50 px-2.5 py-2 font-mono text-[11px] text-red-700 dark:border-red-900/70 dark:bg-red-950/35 dark:text-red-300",children:n}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx("button",{type:"button",onClick:()=>void l(!0,"once"),disabled:r,className:"min-h-8 px-3 py-1.5 text-[12px] font-mono bg-[#22C55E] text-white rounded-md hover:bg-[#16A34A] disabled:cursor-wait disabled:opacity-50",children:r?e.jsx(A,{className:"h-3.5 w-3.5 animate-spin"}):a("interaction.permission.once")}),t.allowRemember!==!1&&e.jsxs(e.Fragment,{children:[e.jsx("button",{type:"button",onClick:()=>void l(!0,"session"),disabled:r,className:"min-h-8 px-3 py-1.5 text-[12px] font-mono bg-[#3B82F6] text-white rounded-md hover:bg-[#2563EB] disabled:cursor-wait disabled:opacity-50",children:a("interaction.permission.session")}),e.jsx("button",{type:"button",onClick:()=>void l(!0,"project"),disabled:r,className:"min-h-8 px-3 py-1.5 text-[12px] font-mono bg-[#6366F1] text-white rounded-md hover:bg-[#4F46E5] disabled:cursor-wait disabled:opacity-50",children:a("interaction.permission.project")})]}),e.jsx("button",{type:"button",onClick:()=>void l(!1),disabled:r,className:"min-h-8 px-3 py-1.5 text-[12px] font-mono bg-[#EF4444] text-white rounded-md hover:bg-[#DC2626] disabled:cursor-wait disabled:opacity-50",children:a("interaction.permission.deny")})]})]})}function ls({question:t,messageId:s}){const a=F(),[r,i]=b.useState({}),[n,d]=b.useState({}),[f,c]=b.useState(!1),[l,k]=b.useState(null),o=y(m=>m.currentSessionRef),h=y(m=>m.setQuestion),u=b.useMemo(()=>t?t.questions.reduce((m,w)=>{var E;const g=(E=n[w.header])==null?void 0:E.trim(),p=r[w.header];if(w.multiSelect){const S=Array.isArray(p)?[...p]:[];return g&&S.push(g),S.length>0&&(m[w.header]=S),m}const x=g||(typeof p=="string"?p:"");return x&&(m[w.header]=x),m},{}):{},[r,n,t]),j=(t==null?void 0:t.questions.every(m=>m.header in u))??!1;if(!t)return null;const N=async()=>{if(!(!o||f||!j)){c(!0),k(null);try{await U.respondToQuestion(o,t.toolCallId,u),h(s,{...t,status:"answered",answers:u})}catch(m){k(m instanceof Error?m.message:a("interaction.question.failed"))}finally{c(!1)}}};return t.status!=="pending"?e.jsx("div",{className:"bg-[hsl(var(--deck-surface-2))] border border-[hsl(var(--deck-border))] rounded-lg px-3 py-2",children:e.jsx("div",{className:"text-[12px] text-[hsl(var(--deck-ink-muted))] font-mono",children:a("interaction.question.answered")})}):e.jsxs("div",{"data-pending-interaction":"question",tabIndex:-1,role:"alert",className:"space-y-4 rounded-lg border border-amber-300/70 bg-amber-50/70 p-4 outline-none focus-visible:ring-2 focus-visible:ring-amber-500 dark:border-amber-800/70 dark:bg-amber-950/25",children:[t.questions.map((m,w)=>e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"text-[13px] text-[hsl(var(--deck-ink))] font-mono",children:m.question}),e.jsxs("div",{className:"space-y-1",children:[m.options.map((g,p)=>e.jsxs("button",{type:"button",onClick:()=>{if(m.multiSelect){const x=r[m.header]||[],E=x.includes(g.label)?x.filter(S=>S!==g.label):[...x,g.label];i({...r,[m.header]:E})}else i({...r,[m.header]:g.label}),d({...n,[m.header]:""})},className:T("w-full text-left px-3 py-2 rounded-md border text-[12px] font-mono transition-colors","border-[hsl(var(--deck-border))]",(m.multiSelect?(r[m.header]||[]).includes(g.label):r[m.header]===g.label)?"bg-[#DCFCE7] text-[#166534] dark:bg-[#22C55E]/20 dark:text-[#E5E5E5]":"bg-[hsl(var(--deck-surface-2))] text-[hsl(var(--deck-ink-muted))]"),children:[e.jsx("div",{children:g.label}),e.jsx("div",{className:"text-[11px] text-[hsl(var(--deck-ink-faint))] mt-1",children:g.description})]},p)),e.jsx("input",{"aria-label":`${m.header} other response`,value:n[m.header]??"",onChange:g=>d({...n,[m.header]:g.target.value}),placeholder:a("interaction.question.other"),className:"w-full rounded-md border border-[#E5E7EB] bg-white px-3 py-2 text-[12px] text-[#111827] outline-none focus:border-[#22C55E] dark:border-[#27272a] dark:bg-[#111113] dark:text-[#E5E5E5]"})]})]},w)),l&&e.jsx("div",{role:"alert",className:"rounded-md border border-red-300/70 bg-red-50 px-2.5 py-2 font-mono text-[11px] text-red-700 dark:border-red-900/70 dark:bg-red-950/35 dark:text-red-300",children:l}),e.jsxs("button",{type:"button",onClick:()=>void N(),disabled:f||!j,className:"inline-flex min-h-8 items-center gap-1.5 px-3 py-1.5 text-[12px] font-mono bg-[#22C55E] text-white rounded-md hover:bg-[#16A34A] disabled:cursor-wait disabled:opacity-50",children:[f&&e.jsx(A,{className:"h-3.5 w-3.5 animate-spin"}),a("interaction.question.submit")]})]})}function cs({message:t}){const s=t.agentContent,a=y(j=>j.isStreaming&&j.currentAssistantMessageId===t.id);if(!s){const j=ye(t.content);return j?e.jsx(Te,{content:j}):null}const{toolCalls:r,tasks:i,confirmation:n,question:d,elicitation:f}=s,c=wt(s),l=Nt(s);if(!(l.length>0||i.length>0||c.length>0||n||d||f)&&a)return e.jsxs("div",{className:"flex items-center gap-2 text-[hsl(var(--deck-ink-muted))]",children:[e.jsx(A,{className:"w-4 h-4 animate-spin"}),e.jsx("span",{className:"text-[12px] font-mono",children:"Thinking..."})]});const h=r.length>0&&r.every(j=>j.status==="success"||j.status==="error")&&!a,u=!a;return e.jsxs("div",{className:"space-y-3",children:[l.map(j=>j.type==="thinking"?e.jsx("div",{"data-agent-timeline-block":"thinking",children:e.jsx(as,{content:j.content})},j.id):j.type==="text"?e.jsx("div",{"data-agent-timeline-block":"text",children:e.jsx(Te,{content:j.content,syntaxHighlight:u})},j.id):e.jsx("div",{"data-agent-timeline-block":"tool_group",children:e.jsx(ss,{toolCalls:r,toolCallIds:j.toolCallIds})},j.id)),i.length>0&&e.jsx(rs,{tasks:i}),c.map(j=>e.jsx(is,{subagent:j},j.id)),n&&e.jsx(os,{confirmation:n,messageId:t.id}),d&&e.jsx(ls,{question:d,messageId:t.id}),f&&e.jsx(Vt,{elicitation:f,messageId:t.id}),h&&e.jsx(ns,{toolCalls:r})]})}function ds({message:t,showAvatar:s=!0}){var f,c,l,k;const a=t.role==="user";if(t.role==="system"){const o=ye(t.content);return e.jsx("div",{"data-chat-message-id":t.id,"data-chat-role":"system",className:"flex justify-center p-2 w-full",children:e.jsx("div",{className:"text-xs text-[hsl(var(--deck-ink-muted))] bg-[#F3F4F6] dark:bg-[#18181b] px-3 py-1 rounded-full font-mono",children:o})})}if(a){const o=(f=t.metadata)!=null&&f.userShellCommand&&typeof t.metadata.userShellCommand=="object"?t.metadata.userShellCommand:(c=t.metadata)!=null&&c.userShellExecution&&typeof t.metadata.userShellExecution=="object"?t.metadata.userShellExecution:void 0;if(o){const j=typeof o.command=="string"?o.command:"",N=o.status==="running"?"running":o.status==="completed"?"success":"error",m=typeof o.output=="string"?o.output:[typeof o.stdout=="string"?o.stdout:"",typeof o.stderr=="string"&&o.stderr?`stderr:
16
- ${o.stderr}`:""].filter(Boolean).join(`
17
- `);return e.jsx("div",{"data-chat-message-id":t.id,"data-chat-role":"user","data-user-shell-command":!0,className:"flex w-full justify-end p-4",children:e.jsxs("div",{className:"w-full max-w-[85%] overflow-hidden rounded-lg border border-[hsl(var(--deck-border))] bg-[hsl(var(--deck-surface))]",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3 border-b border-[hsl(var(--deck-border))] bg-[hsl(var(--deck-surface-2))] px-3 py-2",children:[e.jsxs("div",{className:"min-w-0 truncate font-mono text-[12px] text-[hsl(var(--deck-ink))]",children:[e.jsx("span",{className:"mr-2 text-amber-600 dark:text-amber-400",children:"$"}),j]}),e.jsx(we,{status:N})]}),e.jsx("pre",{className:"max-h-64 overflow-auto whitespace-pre-wrap px-3 py-2 font-mono text-[11px] text-[hsl(var(--deck-ink-muted))]",children:m||"(no output)"}),typeof o.exitCode=="number"&&e.jsxs("div",{className:"border-t border-[hsl(var(--deck-border))] px-3 py-1.5 font-mono text-[10px] text-[hsl(var(--deck-ink-faint))]",children:["exit ",o.exitCode,typeof o.durationMs=="number"?` · ${(o.durationMs/1e3).toFixed(3)}s`:"",o.truncated===!0?" · truncated":""]})]})})}const{text:h,images:u}=Yt(t.content);return e.jsxs("div",{"data-chat-message-id":t.id,"data-chat-role":"user",className:"group flex gap-2 justify-end p-4 w-full items-start",children:[e.jsx("div",{className:"mt-1 flex shrink-0 opacity-0 transition-opacity group-hover:opacity-100 group-focus-within:opacity-100",children:e.jsx(Ce,{text:h,label:"Copy message"})}),e.jsxs("div",{className:"bg-[hsl(var(--deck-surface-2))] rounded-lg px-4 py-3 max-w-[85%]",children:[h&&e.jsx("p",{className:"text-[14px] text-[hsl(var(--deck-ink))] font-mono leading-relaxed whitespace-pre-wrap",children:h}),u.length>0&&e.jsx("div",{className:T("grid gap-2",u.length===1?"grid-cols-1 mt-0":"grid-cols-2 mt-3"),children:u.map((j,N)=>e.jsx("img",{src:j,alt:`attachment-${N+1}`,className:"object-cover w-full max-h-64 rounded-md"},`${j}-${N}`))})]}),e.jsx(Jt,{})]})}const i=Xt(t),n=It((l=t.metadata)==null?void 0:l.codeReview),d=zt((k=t.metadata)==null?void 0:k.structuredOutput);return e.jsxs("div",{"data-chat-message-id":t.id,"data-chat-role":"assistant",className:T("group flex gap-4 justify-start w-full",s?"p-4":"px-4 pt-0 pb-3"),children:[s?e.jsx(Qt,{}):e.jsx("div",{className:"w-8 shrink-0"}),e.jsxs("div",{className:"overflow-hidden flex-1 min-w-0",children:[n?e.jsx(Pt,{report:n}):d?e.jsx(Gt,{report:d}):e.jsx(cs,{message:t}),!d&&i.trim()&&e.jsx("div",{className:"mt-1.5 flex opacity-0 transition-opacity group-hover:opacity-100 group-focus-within:opacity-100",children:e.jsx(Ce,{text:i,label:"Copy response"})})]})]})}const us=b.memo(ds);function ms(t,s,a){return Math.max(0,t+(a-s))}function hs(t,s,a){return Math.min(s,Math.max(0,t)+Math.max(0,a))}function Re(t,s){return t?t.querySelector(`[data-chat-message-id="${CSS.escape(s)}"]`):null}function xs({turns:t,viewportRef:s,containerRef:a,onRevealTurn:r}){const i=F(),[n,d]=b.useState(null),[f,c]=b.useState(!1),l=b.useRef(null),k=b.useCallback(()=>{var m;const h=s.current,u=a.current;if(!h||!u||t.length===0)return;const j=h.getBoundingClientRect().top;let N=((m=t[0])==null?void 0:m.id)??null;for(const w of t){const g=Re(u,w.id);if(g)if(g.getBoundingClientRect().top-j<=24)N=w.id;else break}d(N)},[t,s,a]);b.useEffect(()=>{const h=s.current;if(!h)return;const u=()=>{l.current===null&&(l.current=window.requestAnimationFrame(()=>{l.current=null,k()}))};return k(),h.addEventListener("scroll",u,{passive:!0}),()=>{h.removeEventListener("scroll",u),l.current!==null&&(window.cancelAnimationFrame(l.current),l.current=null)}},[k,s]);const o=b.useCallback(h=>{const u=()=>{const N=Re(a.current,h.id);N&&(N.scrollIntoView({behavior:"smooth",block:"start"}),d(h.id))};r(h.index)?u():window.requestAnimationFrame(()=>window.requestAnimationFrame(u))},[a,r]);return t.length<2?null:e.jsx("nav",{"aria-label":i("chat.turns.aria"),className:"absolute right-1 top-1/2 z-20 hidden -translate-y-1/2 sm:block",onMouseEnter:()=>c(!0),onMouseLeave:()=>c(!1),onFocusCapture:()=>c(!0),onBlurCapture:h=>{h.currentTarget.contains(h.relatedTarget)||c(!1)},children:e.jsxs("div",{className:"relative flex items-center justify-end",children:[e.jsx("ul",{className:T("flex flex-col items-center gap-2 py-2 transition-opacity",f?"opacity-0":"opacity-100"),"aria-hidden":f,children:t.map(h=>e.jsx("li",{children:e.jsx("span",{className:T("block rounded-full transition-all",h.id===n?"h-2 w-2 bg-[hsl(var(--deck-accent))]":"h-1.5 w-1.5 bg-[hsl(var(--deck-ink-faint))]/40")})},h.id))}),e.jsx("div",{className:T("absolute right-0 max-h-[min(70vh,520px)] w-[280px] overflow-y-auto rounded-lg border border-[hsl(var(--deck-border))] bg-[hsl(var(--deck-surface))]/95 p-1 shadow-xl backdrop-blur transition-all",f?"pointer-events-auto translate-x-0 opacity-100":"pointer-events-none translate-x-2 opacity-0"),children:t.map((h,u)=>e.jsxs("button",{type:"button",onClick:()=>o(h),className:T("flex w-full items-start gap-2 rounded-md px-2 py-1.5 text-left transition-colors",h.id===n?"bg-[hsl(var(--deck-hairline))]/70 text-[hsl(var(--deck-ink))]":"text-[hsl(var(--deck-ink-muted))] hover:bg-[hsl(var(--deck-hairline))]/50 hover:text-[hsl(var(--deck-ink))]"),children:[e.jsx("span",{className:T("mt-1 h-1.5 w-1.5 shrink-0 rounded-full",h.id===n?"bg-[hsl(var(--deck-accent))]":"bg-[hsl(var(--deck-ink-faint))]/40")}),e.jsxs("span",{className:"min-w-0 flex-1",children:[e.jsx("span",{className:"block font-mono text-[9.5px] uppercase tracking-[0.12em] text-[hsl(var(--deck-ink-faint))]",children:i("chat.turns.label",{n:u+1})}),e.jsx("span",{className:"line-clamp-2 text-[12px] leading-4",children:h.preview})]})]},h.id))})]})})}const Fe=80;function ps(t){return typeof t=="string"?t:Array.isArray(t)?t.filter(s=>s.type==="text").map(s=>s.text).join(" "):""}function fs(t){const s=ps(t).replace(/\s+/g," ").trim();return s?s.length>Fe?`${s.slice(0,Fe-1)}…`:s:""}function bs(t){const s=[];for(let a=0;a<t.length;a+=1){const r=t[a];if(r.role!=="user"||!r.id)continue;const i=fs(r.content);i&&s.push({id:r.id,index:a,preview:i})}return s}const ue=120,me=80,vs=96;function Q(t){return(t==null?void 0:t.querySelector("[data-radix-scroll-area-viewport]"))??null}function gs({messages:t,isLoading:s}){const a=F(),r=b.useRef(null),i=b.useRef(null),n=b.useRef(!0),d=b.useRef(t.length),f=b.useRef(null),[c,l]=b.useState(ue),[k,o]=b.useState(!1);b.useEffect(()=>{const p=Q(r.current);if(!p||!n.current)return;const x=window.requestAnimationFrame(()=>{p.scrollTop=p.scrollHeight});return()=>window.cancelAnimationFrame(x)},[t]),b.useEffect(()=>{const p=Q(r.current);if(!p)return;i.current=p;const x=()=>{const S=p.scrollHeight-p.scrollTop-p.clientHeight<=vs;n.current=S,o(!S)};return x(),p.addEventListener("scroll",x,{passive:!0}),()=>p.removeEventListener("scroll",x)},[]),b.useEffect(()=>{const p=d.current;d.current=t.length,l(x=>x>=p&&t.length>p?t.length:Math.min(Math.max(x,ue),t.length||ue))},[t.length]);const h=Math.max(t.length-c,0),u=h,j=b.useMemo(()=>t.slice(u),[t,u]),N=b.useMemo(()=>bs(t),[t]);if(b.useLayoutEffect(()=>{var E;const p=f.current;if(!p)return;const x=Q(r.current);if(f.current=null,!!x){if((E=p.element)!=null&&E.isConnected){const S=p.element.getBoundingClientRect().top-p.viewportTop;x.scrollTop+=S;return}x.scrollTop=ms(p.scrollTop,p.scrollHeight,x.scrollHeight)}},[c]),s)return e.jsx("div",{role:"status","aria-live":"polite","aria-busy":"true",className:"flex overflow-hidden flex-1 justify-center items-center px-5 py-8 min-h-0",children:e.jsxs("div",{className:"w-full max-w-[560px]",children:[e.jsxs("div",{className:"flex flex-col items-center text-center",children:[e.jsxs("div",{className:"relative",children:[e.jsx("div",{className:"absolute inset-0 animate-pulse rounded-full bg-[hsl(var(--deck-accent-soft))] blur-xl"}),e.jsx(xe,{size:42,className:"relative"})]}),e.jsxs("div",{className:"mt-4 inline-flex items-center gap-1.5 font-mono text-[10px] uppercase tracking-[0.16em] text-[hsl(var(--deck-accent))]",children:[e.jsx(ct,{className:"w-3 h-3"}),a("chat.list.loading.eyebrow")]}),e.jsx("h2",{className:"mt-2 text-[15px] font-medium text-[hsl(var(--deck-ink))]",children:a("chat.list.loading.title")}),e.jsx("p",{className:"mt-1 max-w-sm text-[11.5px] leading-5 text-[hsl(var(--deck-ink-faint))]",children:a("chat.list.loading.hint")})]}),e.jsx("div",{"aria-hidden":"true",className:"mt-7 space-y-4 rounded-xl border border-[hsl(var(--deck-hairline))] bg-[hsl(var(--deck-surface))]/45 px-4 py-5",children:[72,88,64].map((p,x)=>e.jsxs("div",{className:T("flex gap-3",x%2===1&&"flex-row-reverse"),children:[e.jsx("span",{className:"h-7 w-7 shrink-0 animate-pulse rounded-md bg-[hsl(var(--deck-surface-2))]"}),e.jsx("span",{className:"h-10 animate-pulse rounded-lg bg-[hsl(var(--deck-surface-2))]",style:{width:`${p}%`,animationDelay:`${x*120}ms`}})]},p))})]})});if(t.length===0&&!s)return e.jsx("div",{className:"flex flex-1 justify-center items-center",children:e.jsxs("div",{className:"flex flex-col gap-4 items-center text-center",children:[e.jsx(xe,{size:44}),e.jsxs("div",{children:[e.jsx("div",{className:"deck-eyebrow text-[hsl(var(--deck-accent))]",children:a("chat.list.empty.eyebrow")}),e.jsx("div",{className:"mt-2 text-[15px] font-medium text-[hsl(var(--deck-ink))]",children:a("chat.list.empty.title")}),e.jsx("div",{className:"mt-1 max-w-xs text-[12px] text-[hsl(var(--deck-ink-muted))]",children:a("chat.list.empty.hint")})]})]})});const m=()=>{const p=Q(r.current);p&&(n.current=!0,o(!1),p.scrollTo({top:p.scrollHeight,behavior:"smooth"}))},w=()=>{var x;const p=Q(r.current);if(p){const E=((x=r.current)==null?void 0:x.querySelector("[data-chat-message-id]"))??null;f.current={element:E,viewportTop:(E==null?void 0:E.getBoundingClientRect().top)??0,scrollHeight:p.scrollHeight,scrollTop:p.scrollTop}}l(E=>hs(E,t.length,me))},g=p=>p>=u?!0:(l(t.length),!1);return e.jsxs("div",{ref:r,className:"relative flex-1 min-h-0",children:[e.jsx(Qe,{className:"h-full",children:e.jsxs("div",{className:"flex flex-col px-4 pb-4 w-full md:px-6",children:[h>0&&e.jsx("div",{className:"flex justify-center py-3",children:e.jsx("button",{type:"button",onClick:w,"aria-label":a("chat.list.showEarlierWithRemaining",{count:Math.min(h,me),remaining:h}),className:"rounded-md border border-[hsl(var(--deck-border))] bg-[hsl(var(--deck-surface))] px-3 py-1.5 font-mono text-[12px] text-[hsl(var(--deck-ink-muted))] transition-colors hover:border-[hsl(var(--deck-border-strong))] hover:text-[hsl(var(--deck-ink))]",children:a("chat.list.showEarlier",{count:Math.min(h,me)})})}),j.map((p,x)=>{const E=u+x,S=E>0?t[E-1]:null,D=!S||S.role!==p.role||S.role==="user";return e.jsx(us,{message:p,showAvatar:D},p.id||`msg-${E}`)})]})}),e.jsx(xs,{turns:N,viewportRef:i,containerRef:r,onRevealTurn:g}),k&&e.jsxs("button",{type:"button",onClick:m,className:"absolute bottom-4 left-1/2 z-10 inline-flex -translate-x-1/2 items-center gap-1.5 rounded-full border border-[hsl(var(--deck-border-strong))] bg-[hsl(var(--deck-surface))]/95 px-3 py-1.5 font-mono text-[11px] text-[hsl(var(--deck-ink-muted))] shadow-lg backdrop-blur transition-colors hover:text-[hsl(var(--deck-ink))] focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-[hsl(var(--deck-accent))]",children:[e.jsx(Oe,{className:"h-3.5 w-3.5 text-[hsl(var(--deck-accent))]"}),a("chat.list.jumpLatest")]})]})}const ks=b.memo(gs),pe=Tt,fe=Mt,be=At,re=b.forwardRef(({className:t,sideOffset:s=4,...a},r)=>e.jsx(Ke,{ref:r,sideOffset:s,className:T("z-50 overflow-hidden rounded-md border bg-popover px-3 py-1.5 text-sm text-popover-foreground shadow-md animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 origin-[--radix-tooltip-content-transform-origin]",t),...a}));re.displayName=Ke.displayName;const js={active:{labelKey:"goal.status.active",dot:"bg-[hsl(var(--deck-accent))] shadow-[0_0_6px_hsl(var(--deck-accent-glow)/0.5)]",accent:"text-[hsl(var(--deck-accent))]"},verifying:{labelKey:"goal.status.active",dot:"animate-pulse bg-sky-400",accent:"text-sky-600 dark:text-sky-300"},paused:{labelKey:"goal.status.paused",dot:"bg-amber-400",accent:"text-amber-600 dark:text-amber-300"},blocked:{labelKey:"goal.status.blocked",dot:"bg-rose-500",accent:"text-rose-600 dark:text-rose-300"},usage_limited:{labelKey:"goal.status.usageLimited",dot:"bg-orange-500",accent:"text-orange-600 dark:text-orange-300"},budget_limited:{labelKey:"goal.status.budgetLimited",dot:"bg-orange-500",accent:"text-orange-600 dark:text-orange-300"},complete:{labelKey:"goal.status.complete",dot:"bg-emerald-500",accent:"text-emerald-600 dark:text-emerald-300"}};function Z(t){return t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${(t/1e3).toFixed(1)}K`:String(t)}function ys(t){if(t<60)return`${t}s`;const s=Math.floor(t/60),a=t%60;return a===0?`${s}m`:`${s}m ${a}s`}function ws(){var _;const t=F(),{locale:s}=Je(),a=y(C=>C.goal),r=y(C=>C.pauseGoal),i=y(C=>C.resumeGoal),n=y(C=>C.editGoal),d=y(C=>C.clearGoal),[f,c]=b.useState(!1),[l,k]=b.useState(!1),[o,h]=b.useState(""),[u,j]=b.useState(null),[N,m]=b.useState(!1);if(b.useEffect(()=>{c(!1),k(!1),h((a==null?void 0:a.objective)??""),m(!1)},[a==null?void 0:a.goalId]),!a)return null;const w=js[a.status],g=["active","verifying","paused","blocked"].includes(a.status),p=a.status==="active"||a.status==="verifying",x=a.status==="paused"||a.status==="blocked",E=u!==null,S=async(C,B)=>{j(C);try{await B()}finally{j(null)}},D=()=>{h(a.objective),k(!0),c(!0)},R=async C=>{C.preventDefault();const B=o.trim();if(!B||B===a.objective){k(!1);return}await S("edit",()=>n(B)),k(!1)},L=async()=>{await S("delete",d),m(!1)};return e.jsxs(e.Fragment,{children:[e.jsx(pe,{delayDuration:250,children:e.jsxs("section",{"aria-label":t("goal.aria.section"),className:"mx-3 mb-1 shrink-0","data-blade-goal-status":a.status,children:[e.jsxs("div",{className:T("flex h-9 items-center gap-2 rounded-lg border px-3 transition-colors","border-[hsl(var(--deck-border))]/60 bg-[hsl(var(--deck-surface))]/80 backdrop-blur-sm",f&&"rounded-b-none border-b-0"),children:[a.status==="complete"?e.jsx(dt,{className:"h-3.5 w-3.5 shrink-0 text-emerald-500"}):e.jsx(ut,{className:T("h-3.5 w-3.5 shrink-0",w.accent)}),e.jsx("span",{className:T("h-1.5 w-1.5 shrink-0 rounded-full",w.dot)}),e.jsx("span",{className:T("shrink-0 text-[10px] font-medium leading-none",w.accent),children:a.status==="verifying"?s==="zh"?"验证中":"Verifying":t(w.labelKey)}),e.jsx("span",{className:"h-3 w-px shrink-0 bg-[hsl(var(--deck-hairline))]"}),e.jsx("button",{type:"button","aria-label":t(f?"goal.action.collapse":"goal.action.expand"),className:"min-w-0 flex-1 truncate text-left text-[12px] leading-5 text-[hsl(var(--deck-ink))]/85 outline-none transition-colors hover:text-[hsl(var(--deck-ink))]",onClick:()=>c(C=>!C),"aria-expanded":f,title:a.objective,children:a.objective}),a.tokensUsed>0&&e.jsxs("span",{className:"hidden shrink-0 text-[10px] tabular-nums text-[hsl(var(--deck-ink-muted))] sm:inline",children:[Z(a.tokensUsed),a.tokenBudget!==void 0&&`/${Z(a.tokenBudget)}`]}),e.jsxs("div",{className:"flex shrink-0 items-center",children:[p&&e.jsx(ee,{label:t("goal.action.pause"),disabled:E,onClick:()=>void S("pause",r),children:u==="pause"?e.jsx(A,{className:"animate-spin"}):e.jsx(mt,{})}),x&&e.jsx(ee,{label:t("goal.action.resume"),disabled:E,onClick:()=>void S("resume",i),children:u==="resume"?e.jsx(A,{className:"animate-spin"}):e.jsx(ht,{})}),e.jsx(ee,{label:t(g?"goal.action.edit":"goal.action.expand"),disabled:!g&&!f,onClick:g?D:()=>c(C=>!C),children:g?e.jsx(Ue,{}):e.jsx(xt,{})}),e.jsx(ee,{label:t("goal.action.delete"),disabled:E,destructive:!0,onClick:()=>m(!0),children:e.jsx(se,{})})]})]}),f&&e.jsx("div",{className:"rounded-b-lg border border-t-0 border-[hsl(var(--deck-border))]/60 bg-[hsl(var(--deck-surface))]/80 px-4 py-3 backdrop-blur-sm",children:l?e.jsxs("form",{onSubmit:R,children:[e.jsx("textarea",{id:"goal-objective",value:o,onChange:C=>h(C.target.value),onKeyDown:C=>{C.key==="Escape"&&k(!1)},rows:3,autoFocus:!0,className:"w-full resize-none rounded-md border border-[hsl(var(--deck-border))] bg-[hsl(var(--deck-canvas))] px-3 py-2 text-[12px] leading-5 text-[hsl(var(--deck-ink))] outline-none transition-shadow focus:border-[hsl(var(--deck-accent))] focus:ring-1 focus:ring-[hsl(var(--deck-accent-glow))]"}),e.jsxs("div",{className:"mt-2 flex items-center justify-end gap-2",children:[e.jsxs("button",{type:"button",onClick:()=>k(!1),className:"inline-flex h-7 items-center gap-1 rounded-md px-2.5 text-[11px] text-[hsl(var(--deck-ink-muted))] transition-colors hover:bg-[hsl(var(--deck-hairline))]/60",children:[e.jsx(He,{className:"h-3 w-3"}),t("goal.action.cancel")]}),e.jsxs("button",{type:"submit",disabled:!o.trim()||u==="edit",className:"inline-flex h-7 items-center gap-1 rounded-md bg-[hsl(var(--deck-accent))] px-2.5 text-[11px] font-medium text-white transition-colors hover:bg-[hsl(var(--deck-accent))]/90 disabled:cursor-not-allowed disabled:opacity-50",children:[u==="edit"?e.jsx(A,{className:"h-3 w-3 animate-spin"}):e.jsx(ne,{className:"h-3 w-3"}),t("goal.action.save")]})]})]}):e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"whitespace-pre-wrap text-[12px] leading-5 text-[hsl(var(--deck-ink))]/90",children:a.objective}),e.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-x-4 gap-y-1.5 text-[10px] text-[hsl(var(--deck-ink-muted))]",children:[e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx(pt,{className:"h-3 w-3"}),Z(a.tokensUsed),a.tokenBudget!==void 0&&` / ${Z(a.tokenBudget)}`," ",t("goal.metrics.tokens")]}),e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx(ft,{className:"h-3 w-3"}),ys(a.timeUsedSeconds)]}),e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx(ke,{className:"h-3 w-3"}),a.continuationCount===1?t("goal.metrics.continuationOne",{n:a.continuationCount}):t("goal.metrics.continuationMany",{n:a.continuationCount})]})]}),a.completionVerification&&e.jsxs("div",{"data-goal-verification":a.completionVerification.status,className:"mt-2 rounded-md border border-sky-200/50 bg-sky-50/60 px-2.5 py-2 text-[11px] text-sky-900 dark:border-sky-400/15 dark:bg-sky-400/[0.05] dark:text-sky-100",children:[e.jsxs("p",{className:"font-mono font-medium",children:["#",a.completionVerification.attempt," ·"," ",a.completionVerification.status.toUpperCase()," ·"," ",((_=a.completionVerification.verifierSessionId)==null?void 0:_.slice(0,12))??"-"]}),a.completionVerification.summary&&e.jsx("p",{className:"mt-1 line-clamp-3 whitespace-pre-wrap opacity-80",children:a.completionVerification.summary}),a.completionVerification.evidenceSha256&&e.jsxs("p",{className:"mt-1 font-mono text-[10px] opacity-60",children:["sha256:",a.completionVerification.evidenceSha256.slice(0,12)]})]}),a.statusReason&&e.jsx("div",{className:"mt-2 rounded-md border border-amber-200/50 bg-amber-50/60 px-2.5 py-1.5 text-[11px] text-amber-800 dark:border-amber-400/15 dark:bg-amber-400/[0.05] dark:text-amber-200",children:a.statusReason})]})})]})}),e.jsx(De,{open:N,onOpenChange:m,children:e.jsxs(Be,{className:"max-w-[400px] border-[hsl(var(--deck-border))] bg-[hsl(var(--deck-surface))]",children:[e.jsx(Ie,{children:t("goal.dialog.title")}),e.jsx(_e,{children:t("goal.dialog.description")}),e.jsxs(Pe,{className:"mt-2",children:[e.jsx("button",{type:"button",onClick:()=>m(!1),className:"inline-flex h-8 items-center justify-center rounded-md border border-[hsl(var(--deck-border))] px-3 text-[12px] text-[hsl(var(--deck-ink))] hover:bg-[hsl(var(--deck-hairline))]/60",children:t("goal.action.cancel")}),e.jsxs("button",{type:"button",disabled:u==="delete",onClick:()=>void L(),className:"inline-flex gap-1.5 justify-center items-center px-3 h-8 text-[12px] font-medium text-white bg-rose-600 rounded-md hover:bg-rose-500 disabled:opacity-50",children:[u==="delete"&&e.jsx(A,{className:"w-3.5 h-3.5 animate-spin"}),t("goal.action.delete")]})]})]})})]})}function ee({label:t,children:s,disabled:a,destructive:r,onClick:i}){return e.jsxs(fe,{children:[e.jsx(be,{asChild:!0,children:e.jsx("button",{type:"button","aria-label":t,disabled:a,onClick:i,className:T("flex h-6 w-6 items-center justify-center rounded-md text-[hsl(var(--deck-ink-muted))] outline-none transition-colors focus-visible:ring-1 focus-visible:ring-[hsl(var(--deck-accent-glow))]/50 disabled:cursor-not-allowed disabled:opacity-35 [&_svg]:h-3.5 [&_svg]:w-3.5",r?"hover:bg-rose-500/10 hover:text-rose-500":"hover:bg-[hsl(var(--deck-hairline))]/60 hover:text-[hsl(var(--deck-ink))]"),children:s})}),e.jsx(re,{side:"top",className:"text-[10px]",children:t})]})}function Ns(){const t=F(),s=y(c=>c.currentSessionRef),a=y(c=>c.sessions),r=y(c=>c.messages),i=b.useMemo(()=>{var l,k,o,h,u;const c=s?(l=Ye(a,s))==null?void 0:l.pendingInteraction:void 0;if(c)return c.type;for(let j=r.length-1;j>=0;j-=1){const N=(k=r[j])==null?void 0:k.agentContent;if(((o=N==null?void 0:N.confirmation)==null?void 0:o.status)==="pending")return"permission";if(((h=N==null?void 0:N.question)==null?void 0:h.status)==="pending")return"question";if(((u=N==null?void 0:N.elicitation)==null?void 0:u.status)==="pending")return"elicitation"}return null},[s,r,a]);if(!i)return null;const n=()=>{const c=document.querySelector(`[data-pending-interaction="${i}"]`);c==null||c.scrollIntoView({block:"center",behavior:"smooth"}),window.setTimeout(()=>c==null?void 0:c.focus(),250)},d=i==="question",f=i==="elicitation";return e.jsxs("div",{role:"alert",className:"mx-3 mb-2 flex flex-wrap items-center gap-2 rounded-lg border border-amber-300/80 bg-amber-50/95 px-3 py-2 font-mono text-amber-950 shadow-sm backdrop-blur dark:border-amber-800/80 dark:bg-amber-950/90 dark:text-amber-100 sm:mx-5",children:[e.jsx(je,{className:"h-4 w-4 shrink-0 text-amber-600 dark:text-amber-400"}),e.jsxs("div",{className:"min-w-[180px] flex-1",children:[e.jsx("div",{className:"text-[11.5px] font-semibold",children:t(d?"interaction.bar.questionTitle":f?"interaction.bar.elicitationTitle":"interaction.bar.permissionTitle")}),e.jsx("div",{className:"mt-0.5 text-[10px] leading-4 text-amber-800 dark:text-amber-300",children:t(d?"interaction.bar.questionHint":f?"interaction.bar.elicitationHint":"interaction.bar.permissionHint")})]}),e.jsxs("button",{type:"button",onClick:n,className:"inline-flex min-h-8 shrink-0 items-center gap-1.5 rounded-md border border-amber-400/80 bg-white/80 px-2.5 text-[10.5px] font-medium transition-colors hover:bg-white focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-amber-500 dark:border-amber-700 dark:bg-amber-950/70 dark:hover:bg-amber-900",children:[e.jsx(Oe,{className:"h-3 w-3"}),t("interaction.bar.review")]})]})}const Ss=b.lazy(()=>Ve(()=>import("./MarkdownRenderer-D6LiW9kF.js").then(t=>t.M),__vite__mapDeps([0,1,2,3,4,5,6])).then(t=>({default:t.MarkdownRenderer})));function Cs(t){return t<1e3?`${t}ms`:`${(t/1e3).toFixed(1)}s`}function Es(){const t=F(),s=y(r=>r.sideConversation),a=y(r=>r.dismissSideConversation);return s?e.jsx("section",{"aria-label":t("chat.side.title"),"data-blade-side-conversation":!0,"data-status":s.status,className:"shrink-0 border-y border-[hsl(var(--deck-accent)/0.28)] bg-[hsl(var(--deck-accent-soft)/0.42)]",children:e.jsxs("div",{className:"px-4 py-3 md:px-6",children:[e.jsxs("header",{className:"flex min-h-7 items-start gap-2",children:[e.jsx(bt,{"aria-hidden":!0,className:"mt-0.5 h-4 w-4 shrink-0 text-[hsl(var(--deck-accent))]"}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex flex-wrap items-baseline gap-x-2 gap-y-1",children:[e.jsx("h2",{className:"font-mono text-[11px] font-semibold uppercase text-[hsl(var(--deck-accent))]",children:t("chat.side.title")}),s.durationMs!==void 0&&e.jsxs("span",{className:"inline-flex items-center gap-1 font-mono text-[9.5px] text-[hsl(var(--deck-ink-faint))]",children:[e.jsx(vt,{"aria-hidden":!0,className:"h-3 w-3"}),Cs(s.durationMs)]})]}),e.jsx("p",{className:"mt-0.5 break-words font-mono text-[11px] leading-4 text-[hsl(var(--deck-ink-muted))]",children:s.question})]}),e.jsx("button",{type:"button",onClick:a,"aria-label":t("chat.side.dismiss"),title:t("chat.side.dismiss"),className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-md text-[hsl(var(--deck-ink-faint))] transition-colors hover:bg-[hsl(var(--deck-surface))] hover:text-[hsl(var(--deck-ink))] focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-[hsl(var(--deck-accent))]",children:e.jsx(He,{"aria-hidden":!0,className:"h-3.5 w-3.5"})})]}),e.jsxs("div",{"aria-live":"polite","aria-busy":s.status==="loading",className:"mt-2 max-h-[min(36vh,320px)] overflow-y-auto border-l-2 border-[hsl(var(--deck-accent)/0.42)] pl-3 pr-1",children:[s.status==="loading"&&e.jsxs("div",{role:"status",className:"flex min-h-9 items-center gap-2 font-mono text-[11px] text-[hsl(var(--deck-ink-muted))]",children:[e.jsx(A,{"aria-hidden":!0,className:"h-3.5 w-3.5 animate-spin text-[hsl(var(--deck-accent))]"}),t("chat.side.loading")]}),s.status==="error"&&e.jsxs("div",{role:"alert",className:"flex min-h-9 items-start gap-2 font-mono text-[11px] leading-5 text-red-700 dark:text-red-300",children:[e.jsx(je,{"aria-hidden":!0,className:"mt-0.5 h-3.5 w-3.5 shrink-0"}),e.jsx("span",{className:"break-words",children:s.error??t("chat.side.failed")})]}),s.status==="completed"&&s.response&&e.jsx(b.Suspense,{fallback:e.jsx("div",{className:"whitespace-pre-wrap break-words font-mono text-[12px] leading-5 text-[hsl(var(--deck-ink))]",children:s.response}),children:e.jsx(Ss,{content:s.response,className:"text-[12px] leading-5 [&_h1]:text-[14px] [&_h2]:text-[13px] [&_h3]:text-[12px]"})})]})]})}):null}function he(t){return Number.isFinite(t)?Math.max(0,t):0}function Ts(t){const s=he(t.totalInputTokens),a=he(t.cacheReadTokens),r=he(t.cacheWriteTokens),i=Math.min(a,s),n=Math.min(r,Math.max(0,s-i)),d=Math.max(0,s-i-n),f=s>0&&(a>0||r>0);return{totalInputTokens:s,cacheReadTokens:i,cacheWriteTokens:n,uncachedInputTokens:d,...f?{hitRate:i/s}:{}}}function Ms(t){return t===void 0||!Number.isFinite(t)?"—":`${Math.round(Math.max(0,Math.min(1,t))*100)}%`}const As={running:"status.phase.running",compacting:"status.phase.compacting",recovering_context:"status.phase.recoveringContext",switching_model:"status.phase.switchingModel",waiting_permission:"status.phase.waitingPermission",error:"status.phase.error",idle:""},Rs={model_changed:"status.cacheBreak.model",system_prompt_changed:"status.cacheBreak.system",tools_changed:"status.cacheBreak.tools",request_policy_changed:"status.cacheBreak.policy",ttl_expired:"status.cacheBreak.ttl",server_side:"status.cacheBreak.server"},O=t=>t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${(t/1e3).toFixed(1)}K`:t.toString(),te=t=>{const s=Math.max(0,Math.ceil(t/1e3)),a=Math.floor(s/60),r=s%60;return a>0?`${a}m ${r}s`:`${r}s`};function Fs(){const t=F(),s=y(w=>w.tokenUsage),a=y(w=>w.isStreaming),r=y(w=>w.agentPhase),i=y(w=>w.providerAdmission),n=y(w=>w.providerCircuit),d=y(w=>w.providerRetry),f=y(w=>w.providerStall),c=y(w=>w.actionStationarity),l=As[r]??"",k=(d==null?void 0:d.delayMs)!==void 0?` · ${Math.max(0,Math.ceil(d.delayMs/1e3))}s`:"",o=c?`${t(c.phase==="halted"?"status.phase.actionStationarityStopped":"status.phase.actionStationarityRecovering")} · ${c.toolName} · ${c.runLength}/${c.haltThreshold}`:n?n.phase==="probe"?"Provider · Recovery probe":`Provider · Circuit open${n.retryAfterMs!==void 0?` · probe in ${te(n.retryAfterMs)}`:""}${n.recoveryRemainingMs!==void 0?` · ${te(n.recoveryRemainingMs)}`:""}`:i?`Provider · Capacity queue ${i.queuePosition}/${Math.max(i.queueDepth,i.queuePosition)} · ${i.scope} · ${te(i.waitMs)}`:d?d.mode==="bounded_foreground"?`Provider · Bounded recovery · ${d.attempt}/${d.maxRetries} · ${te(d.recoveryRemainingMs??0)}`:`Provider · ${t("chat.error.action.retryingTask")} · ${d.attempt}/${d.maxRetries}${k}`:f?`${t("status.phase.providerStall")} · ${Math.ceil(f.durationMs/1e3)}s / ${Math.ceil(f.timeoutMs/1e3)}s`:l?t(l):"",h=s.maxContextTokens>0?Math.round(s.totalTokens/s.maxContextTokens*100):0,u=Ts(s),j=Ms(u.hitRate),N=Math.min(h,100),m=h>95?"danger":h>80?"warn":"safe";return e.jsxs("div",{className:"flex items-center gap-2 border-t border-[hsl(var(--deck-hairline))] bg-[hsl(var(--deck-canvas-veil))]/70 px-3 py-2 font-mono text-[11px] text-[hsl(var(--deck-ink-muted))] backdrop-blur-sm sm:gap-4 sm:px-5",children:[e.jsxs("div",{className:"flex items-center gap-2 sm:gap-3",children:[e.jsx("span",{className:"deck-eyebrow text-[hsl(var(--deck-ink-faint))]",children:t("status.context")}),e.jsxs("span",{className:"flex gap-1 items-baseline tabular-nums",children:[e.jsx("span",{className:T("text-[12px] font-medium",m==="safe"&&"text-[hsl(var(--deck-ink))]",m==="warn"&&"text-amber-600 dark:text-amber-400",m==="danger"&&"text-red-600 dark:text-red-400"),children:O(s.totalTokens)}),e.jsxs("span",{className:"text-[hsl(var(--deck-ink-faint))]",children:["/ ",O(s.maxContextTokens)]})]}),s.isDefaultMaxTokens&&e.jsx(pe,{children:e.jsxs(fe,{children:[e.jsx(be,{asChild:!0,children:e.jsx(gt,{className:"h-3 w-3 cursor-help text-[hsl(var(--deck-ink-faint))]"})}),e.jsx(re,{side:"top",className:"max-w-[220px]",children:e.jsx("p",{className:"text-xs",children:t("status.tokenLimitTooltip")})})]})}),e.jsxs("div",{className:"relative hidden h-2 w-32 overflow-hidden rounded-sm border border-[hsl(var(--deck-border))] bg-[hsl(var(--deck-surface))] sm:block","aria-hidden":"true",children:[e.jsx("div",{className:T("absolute inset-y-0 left-0 transition-[width] duration-300",m==="safe"&&"bg-[hsl(var(--deck-accent))]",m==="warn"&&"bg-amber-500",m==="danger"&&"bg-red-500"),style:{width:`${N}%`}}),e.jsx("div",{className:"flex absolute inset-0 pointer-events-none",children:[25,50,75].map(w=>e.jsx("span",{className:"absolute inset-y-0 w-px bg-[hsl(var(--deck-canvas-veil))]/60",style:{left:`${w}%`}},w))})]}),e.jsxs("span",{className:T("w-10 text-right tabular-nums text-[hsl(var(--deck-ink-faint))]",m==="warn"&&"text-amber-600 dark:text-amber-400",m==="danger"&&"text-red-600 dark:text-red-400"),children:[h,"%"]})]}),e.jsx(pe,{children:e.jsxs(fe,{children:[e.jsx(be,{asChild:!0,children:e.jsxs("div",{className:"flex shrink-0 cursor-help items-baseline gap-2 border-l border-[hsl(var(--deck-hairline))] pl-2 sm:pl-4","data-testid":"prompt-cache-hit-rate","aria-label":`${t("status.cache")} ${j}`,children:[e.jsx("span",{className:"deck-eyebrow text-[hsl(var(--deck-ink-faint))]",children:t("status.cache")}),e.jsx("span",{className:T("tabular-nums",u.hitRate===void 0?"text-[hsl(var(--deck-ink-faint))]":"font-medium text-[hsl(var(--deck-accent))]"),children:j})]})}),e.jsx(re,{side:"top",className:"max-w-[280px]",children:u.hitRate===void 0?e.jsx("p",{className:"text-xs",children:t("status.cacheUnavailable")}):e.jsxs("div",{className:"space-y-1 text-xs",children:[e.jsx("p",{children:t("status.cacheTooltip")}),e.jsx("p",{className:"font-mono tabular-nums",children:t("status.cacheDetails",{read:O(u.cacheReadTokens),write:O(u.cacheWriteTokens),uncached:O(u.uncachedInputTokens)})}),s.cacheBreak&&e.jsx("p",{className:"text-[hsl(var(--deck-accent))]",children:t("status.cacheBreak",{reason:t(Rs[s.cacheBreak.reason]??"status.cacheBreak.server"),previous:O(s.cacheBreak.previousCacheReadTokens),current:O(s.cacheBreak.cacheReadTokens)})})]})})]})}),e.jsx("div",{className:"flex-1"}),a&&o&&e.jsxs("div",{className:"flex gap-2 items-center",children:[e.jsx("span",{className:"deck-pulse-dot"}),e.jsx("span",{className:"text-[hsl(var(--deck-accent))]",children:o})]})]})}function $s(t){const s=[...t].reverse().find(i=>i.role==="user");if(!s)return null;if(typeof s.content=="string")return{content:s.content,attachments:[]};const a=s.content.filter(i=>i.type==="text").map(i=>i.text).join(`
18
- `),r=s.content.filter(i=>i.type==="image_url").map((i,n)=>{var f;const d=((f=i.image_url.url.match(/^data:([^;,]+)[;,]/))==null?void 0:f[1])??"application/octet-stream";return{id:`recovery-${s.id}-${n}`,name:`attachment-${n+1}`,mimeType:d,dataUrl:i.image_url.url}});return{content:a,attachments:r}}function Vs(){var V;const t=F(),s=y(v=>v.messages),a=y(v=>v.currentSessionRef),r=y(v=>v.isStreaming),i=y(v=>v.isStopping),n=y(v=>v.sessionEventConnectionState),d=y(v=>v.pendingSteeringCount),f=y(v=>v.pendingInputDelivery),c=y(v=>v.recoveredSteeringCount),l=y(v=>v.isLoading),k=y(v=>v.error),o=y(v=>v.errorContext),h=y(v=>v.sessions),u=y(v=>v.sendMessage),j=y(v=>v.abortSession),N=y(v=>v.retryTask),m=y(v=>v.retryingTaskKeys),w=ve(v=>v.openSettings),g=y(v=>v.reconnectSessionEvents),p=y(v=>v.clearError),[x,E]=b.useState(null),S=a?h.find(v=>v.sessionId===a.sessionId&&v.projectPath===a.projectPath):void 0,D=!!k&&((o==null?void 0:o.kind)==="navigation"||!(o!=null&&o.sessionRef)||$e(o.sessionRef,a)),R=(o==null?void 0:o.failureCode)??((V=S==null?void 0:S.taskFailure)==null?void 0:V.code),L=(o==null?void 0:o.kind)==="execution"&&R?t(Ct(R)):k==="queue_full"?t("chat.error.queueFull"):k==="turn_unavailable"||k==="turn_active"?t("chat.error.turnChanged"):k,_=n==="connecting"||n==="reconnecting",C=r&&n!=="connected",B=a?`session:${J(a)}`:"session:temporary",H=b.useMemo(()=>$s(s),[s]),le=a?J(a):"temporary-session",z=!!(a&&(S!=null&&S.taskRetryAvailable)&&(!R||Et(R)))&&((o==null?void 0:o.kind)==="execution"||(o==null?void 0:o.kind)==="task_action"),G=(o==null?void 0:o.kind)==="execution"&&(R==="authentication"||R==="permission"||R==="model_unavailable"),K=a?m.includes(J(a)):!1;b.useEffect(()=>{E(null)},[le]);const Y=async v=>u({content:v.content,modelId:v.modelId,reasoningEffort:v.reasoningEffort,serviceTier:v.serviceTier,responseVerbosity:v.responseVerbosity,communicationStyle:v.communicationStyle,...v.outputSchema?{outputSchema:v.outputSchema}:{},attachments:v.attachments.map(I=>({type:"image",content:I.dataUrl,mimeType:I.mimeType,name:I.name}))}),X=()=>j(),M=async()=>{if(G){p(),w("models");return}if(z&&a){p(),await N(a).catch(()=>{});return}if((o==null?void 0:o.kind)==="execution"&&H){E({...H,revision:Date.now()}),p();return}p(),requestAnimationFrame(()=>Ze())},P=z?t(K?"chat.error.action.retryingTask":"chat.error.action.retryTask"):G?t("chat.error.action.checkModels"):(o==null?void 0:o.kind)==="execution"&&H?t("chat.error.action.editResend"):(o==null?void 0:o.kind)==="submission"?t("chat.error.action.returnDraft"):null;return e.jsxs("div",{className:"flex h-full flex-col bg-[hsl(var(--deck-canvas))]",children:[D&&e.jsxs("div",{role:"alert","data-blade-session-error":!0,className:"flex min-h-11 flex-wrap items-center gap-2 border-b border-red-200/60 bg-red-50/80 px-4 py-2 font-mono text-[11px] text-red-700 dark:border-red-900/50 dark:bg-red-950/30 dark:text-red-300 sm:px-5",children:[e.jsx(je,{className:"h-3.5 w-3.5 shrink-0"}),e.jsxs("span",{className:"min-w-0 flex-1 break-words",children:[e.jsx("span",{className:"font-semibold",children:t((o==null?void 0:o.kind)==="submission"?"chat.error.title.submission":(o==null?void 0:o.kind)==="execution"?"chat.error.title.execution":(o==null?void 0:o.kind)==="navigation"?"chat.error.title.navigation":"chat.error.title.generic")})," ",L]}),P&&e.jsxs("button",{type:"button",onClick:()=>void M(),disabled:K,className:"inline-flex min-h-7 shrink-0 items-center gap-1.5 rounded-md border border-red-300/70 bg-white/65 px-2.5 font-medium transition-colors hover:bg-white focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-red-500 disabled:cursor-wait disabled:opacity-60 dark:border-red-800 dark:bg-red-950/45 dark:hover:bg-red-900/60",children:[z?K?e.jsx(A,{className:"h-3 w-3 animate-spin"}):e.jsx(ke,{className:"h-3 w-3"}):e.jsx(Ue,{className:"h-3 w-3"}),P]}),e.jsx("button",{type:"button",onClick:p,"aria-label":t("chat.error.dismiss"),className:"p-1 text-red-500 rounded transition-colors hover:bg-red-100/60 hover:text-red-700 dark:hover:bg-red-950/60 dark:hover:text-red-100",children:"✕"})]}),(_||n==="offline")&&e.jsxs("div",{role:n==="offline"?"alert":"status","aria-live":"polite",className:"flex min-h-10 flex-wrap items-center gap-2 border-b border-amber-300/60 bg-amber-50/80 px-4 py-2 font-mono text-[11px] text-amber-900 dark:border-amber-800/60 dark:bg-amber-950/35 dark:text-amber-200 sm:px-5",children:[_?e.jsx(A,{className:"h-3.5 w-3.5 shrink-0 animate-spin"}):e.jsx(kt,{className:"h-3.5 w-3.5 shrink-0"}),e.jsx("span",{className:"min-w-0 flex-1",children:t(_?"chat.connection.reconnecting":"chat.connection.offline")}),n==="offline"&&e.jsxs("button",{type:"button",onClick:()=>void g().catch(()=>{}),className:"inline-flex min-h-7 items-center gap-1.5 rounded-md border border-amber-400/70 bg-white/60 px-2.5 font-medium transition-colors hover:bg-white focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-amber-500 dark:border-amber-700 dark:bg-amber-950/50 dark:hover:bg-amber-900/50",children:[e.jsx(jt,{className:"h-3 w-3"}),t("chat.connection.retry")]})]}),e.jsx(Rt,{}),e.jsx(ks,{messages:s,isLoading:l},a?J(a):"temporary-session"),e.jsx(Es,{}),e.jsx(Ns,{}),e.jsx(ws,{}),e.jsx(Xe,{draftKey:B,draft:x==null?void 0:x.content,draftAttachments:x==null?void 0:x.attachments,draftRevision:x==null?void 0:x.revision,onSend:Y,onAbort:X,disabled:l||C,isStreaming:r,isStopping:i,pendingSteeringCount:d,pendingInputDelivery:f,recoveredSteeringCount:c,workspacePath:a==null?void 0:a.projectPath},B),e.jsx(Fs,{})]})}export{Vs as ChatView};