blade-code 0.10.160 → 0.10.162

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (134) hide show
  1. package/dist/blade.js +2 -2
  2. package/dist/{chunk-erhaedch.js → chunk-06hkf59s.js} +1 -1
  3. package/dist/chunk-0aya8d61.js +14 -0
  4. package/dist/{chunk-k3ne93k8.js → chunk-0mr8nexh.js} +2 -2
  5. package/dist/{chunk-tya95jej.js → chunk-0tzecdv3.js} +1 -1
  6. package/dist/chunk-1yq72zb7.js +8 -0
  7. package/dist/{chunk-jsv3e4k6.js → chunk-2f8d0km4.js} +1 -1
  8. package/dist/{chunk-5q4z0sfr.js → chunk-2mk914vk.js} +2 -2
  9. package/dist/{chunk-ht8epjz2.js → chunk-30x3mcsb.js} +2 -2
  10. package/dist/{chunk-6112ra8v.js → chunk-3aavhxe8.js} +1 -1
  11. package/dist/{chunk-ewwrss2w.js → chunk-3kszepm6.js} +1 -1
  12. package/dist/chunk-3xffezpc.js +1 -0
  13. package/dist/{chunk-28tzj187.js → chunk-3y2x6fb6.js} +1 -1
  14. package/dist/{chunk-7rjft1z9.js → chunk-46t79ek8.js} +2 -2
  15. package/dist/{chunk-9kj19a8t.js → chunk-4cdk4mds.js} +1 -1
  16. package/dist/chunk-4k7gvnth.js +1 -0
  17. package/dist/{chunk-7xtxvrh8.js → chunk-4wx5sya5.js} +1 -1
  18. package/dist/{chunk-7wcxjbyg.js → chunk-50vwafn5.js} +1 -1
  19. package/dist/{chunk-9xbwtjac.js → chunk-53fc0yrq.js} +1 -1
  20. package/dist/chunk-56ma2n3p.js +1 -0
  21. package/dist/chunk-5v0jcyea.js +2 -0
  22. package/dist/chunk-66wk3exc.js +1 -0
  23. package/dist/chunk-6c5z2b5s.js +1 -0
  24. package/dist/{chunk-5f40659e.js → chunk-6sedqj8r.js} +1 -1
  25. package/dist/{chunk-hs56jgkm.js → chunk-92ck72sg.js} +1 -1
  26. package/dist/{chunk-4c13mnh8.js → chunk-9cb1hv2z.js} +1 -1
  27. package/dist/chunk-9f6nyfcs.js +1 -0
  28. package/dist/{chunk-mt26v0vg.js → chunk-a6wkam4s.js} +1 -1
  29. package/dist/chunk-abc5bzqn.js +1 -0
  30. package/dist/{chunk-kr5w8q8v.js → chunk-ajtwwg2b.js} +1 -1
  31. package/dist/chunk-azn3qphf.js +1 -0
  32. package/dist/{chunk-gmmhpp0k.js → chunk-cvwcrr4h.js} +5 -5
  33. package/dist/{chunk-42y6ks44.js → chunk-d420fs8m.js} +1 -1
  34. package/dist/{chunk-n34qsnks.js → chunk-ddvdc2p0.js} +1 -1
  35. package/dist/chunk-e6tz8qrg.js +1 -0
  36. package/dist/{chunk-sdapqhj0.js → chunk-eg3ms291.js} +1 -1
  37. package/dist/{chunk-5xnht5vw.js → chunk-f194ct93.js} +2 -2
  38. package/dist/{chunk-zrgfvc4k.js → chunk-g01mth5d.js} +2 -2
  39. package/dist/{chunk-2ffyr4zh.js → chunk-hjrc4jdm.js} +1 -1
  40. package/dist/{chunk-y0vdq8h3.js → chunk-hs0fatm3.js} +1 -1
  41. package/dist/{chunk-0b67y4j1.js → chunk-j8hbddjp.js} +2 -2
  42. package/dist/chunk-j9fdpvq0.js +1 -0
  43. package/dist/{chunk-v1mamd1x.js → chunk-jj4ggb04.js} +2 -2
  44. package/dist/{chunk-f2y0gxyq.js → chunk-kqvzmnja.js} +2 -2
  45. package/dist/{chunk-sd9bze9x.js → chunk-kv458q06.js} +1 -1
  46. package/dist/{chunk-9tk6wq70.js → chunk-kvp523gt.js} +1 -1
  47. package/dist/{chunk-yh34b6z0.js → chunk-mg03ydep.js} +2 -2
  48. package/dist/{chunk-7bexc9c3.js → chunk-msx7ecb2.js} +2 -2
  49. package/dist/chunk-n6mv8p83.js +1 -0
  50. package/dist/chunk-n7kwrvvw.js +10 -0
  51. package/dist/{chunk-v67st2xb.js → chunk-nheny8xp.js} +2 -2
  52. package/dist/{chunk-4n0efk4n.js → chunk-nj2bggcj.js} +2 -2
  53. package/dist/{chunk-9q26ss92.js → chunk-psm2d7pr.js} +1 -1
  54. package/dist/chunk-pzqy0x7r.js +1 -0
  55. package/dist/{chunk-70hjk2jn.js → chunk-qjbn97e2.js} +2 -2
  56. package/dist/{chunk-sn2bqttf.js → chunk-qq8h5eag.js} +1 -1
  57. package/dist/{chunk-fhsvz4b1.js → chunk-rjbneaq0.js} +2 -2
  58. package/dist/{chunk-gm2yfq3r.js → chunk-rvs364rz.js} +2 -2
  59. package/dist/{chunk-g7pwwxvz.js → chunk-sspk1ah8.js} +3 -3
  60. package/dist/{chunk-xgyx1hwx.js → chunk-syq7j5b0.js} +2 -2
  61. package/dist/{chunk-qzxj1gvs.js → chunk-sz1jw89z.js} +1 -1
  62. package/dist/{chunk-7xhw74hk.js → chunk-t0gm0pn1.js} +1 -1
  63. package/dist/{chunk-erext256.js → chunk-t89f4way.js} +2 -2
  64. package/dist/{chunk-hv8nt7wj.js → chunk-vbjgcn49.js} +1 -1
  65. package/dist/{chunk-kenxyanc.js → chunk-vh5hxd2w.js} +1 -1
  66. package/dist/{chunk-n9819k4p.js → chunk-vw9paban.js} +1 -1
  67. package/dist/{chunk-fx9vm1n5.js → chunk-w33zjw8m.js} +2 -2
  68. package/dist/{chunk-e07acz8d.js → chunk-wbr9fc4k.js} +1 -1
  69. package/dist/{chunk-53vh6vpt.js → chunk-wcps5gjm.js} +1 -1
  70. package/dist/{chunk-jbpasjg9.js → chunk-xmymx75h.js} +1 -1
  71. package/dist/{chunk-a5r7c1n4.js → chunk-y54mge74.js} +3 -3
  72. package/dist/{chunk-vz13c7fr.js → chunk-y5wngtz0.js} +2 -2
  73. package/dist/{chunk-9zvxdc7t.js → chunk-yk62xvqm.js} +2 -2
  74. package/dist/{chunk-hj1c3k0m.js → chunk-za0frk62.js} +2 -2
  75. package/dist/chunk-zb6mn0dz.js +1 -0
  76. package/dist/{chunk-pv6cgfv1.js → chunk-zj1g4nbq.js} +1 -1
  77. package/dist/{chunk-wm896gnx.js → chunk-zzvs471p.js} +1 -1
  78. package/dist/web/assets/ChatView-er_sxPPR.js +70 -0
  79. package/dist/web/assets/{CodeBlockHighlighter-BpPOUcO7.js → CodeBlockHighlighter-y0h2qpHE.js} +1 -1
  80. package/dist/web/assets/{FilePreview-DXGkgNrQ.js → FilePreview-D3mhQ088.js} +14 -19
  81. package/dist/web/assets/{KanbanBoard-MYvqGgQH.js → KanbanBoard-CVg8k1mE.js} +2 -2
  82. package/dist/web/assets/{MarkdownRenderer-CXDrI3kX.js → MarkdownRenderer-CNBuegIp.js} +3 -3
  83. package/dist/web/assets/{ScrollArea-DocDa_rN.js → ScrollArea-nKClMHtv.js} +1 -1
  84. package/dist/web/assets/{SessionHistorySurface-D4Hxlpnr.js → SessionHistorySurface-DxS7TPaS.js} +1 -1
  85. package/dist/web/assets/{SettingsModal-ROSA92Eo.js → SettingsModal-CUn7pWF9.js} +1 -1
  86. package/dist/web/assets/{Sidebar-ByhqdRdj.js → Sidebar-CfxwNI2v.js} +1 -1
  87. package/dist/web/assets/TaskSwitcher-CSoJ4y5B.js +26 -0
  88. package/dist/web/assets/{TerminalPanel-czvVuMgl.js → TerminalPanel-BQuhnBca.js} +2 -2
  89. package/dist/web/assets/{archive-BwNnCDDQ.js → archive-BboAmbOv.js} +1 -1
  90. package/dist/web/assets/{arrow-left-Dc9lvaeD.js → arrow-left-DAUtSPbk.js} +1 -1
  91. package/dist/web/assets/{calendar-clock-o0GyQ0Np.js → calendar-clock-Vl0t-Nd3.js} +1 -1
  92. package/dist/web/assets/{chevron-right-CgHjrrmB.js → chevron-right-CF4tZJv_.js} +1 -1
  93. package/dist/web/assets/{clock-3-BB58ITKo.js → clock-3-UujBmwyg.js} +1 -1
  94. package/dist/web/assets/{copy-o_KiXkAh.js → copy-DqhAOOxU.js} +1 -1
  95. package/dist/web/assets/{download-BBtK3WHk.js → download-9K17cUAi.js} +1 -1
  96. package/dist/web/assets/{external-link-smSBd9oE.js → external-link-ZWYy4pMB.js} +1 -1
  97. package/dist/web/assets/{folder-BJP6kIlC.js → folder-CWkv_E0L.js} +1 -1
  98. package/dist/web/assets/index-C6zClU0B.js +211 -0
  99. package/dist/web/assets/index-CaCifsSK.css +1 -0
  100. package/dist/web/assets/message-square-plus-DOcUaurY.js +21 -0
  101. package/dist/web/assets/{pause-yqaK1hvk.js → pause-CvRQWY37.js} +1 -1
  102. package/dist/web/assets/{pencil-BZbDnyg2.js → pencil-CrKIc9az.js} +1 -1
  103. package/dist/web/assets/{play-WQ7288Ky.js → play-DN4KhXKM.js} +1 -1
  104. package/dist/web/assets/{plus-veQ2IAZx.js → plus-jGKGKGzn.js} +1 -1
  105. package/dist/web/assets/{session-events-Dwyp0AVI.js → session-events-aq2qdB3u.js} +25 -25
  106. package/dist/web/assets/{settings-B8xvrdSb.js → settings-DkVTw2qw.js} +1 -1
  107. package/dist/web/assets/{team-BrF46S7E.js → team-BBLJq3rO.js} +1 -1
  108. package/dist/web/assets/teamService-B6W5r_Z_.js +1 -0
  109. package/dist/web/assets/{terminal-BrqsCKf2.js → terminal-C30CbzhP.js} +1 -1
  110. package/dist/web/index.html +2 -2
  111. package/package.json +1 -1
  112. package/dist/chunk-514va7ce.js +0 -2
  113. package/dist/chunk-6c7v7ny5.js +0 -1
  114. package/dist/chunk-6s037nx9.js +0 -14
  115. package/dist/chunk-7ss9htq0.js +0 -1
  116. package/dist/chunk-bz9e9hj8.js +0 -1
  117. package/dist/chunk-dav8ngkr.js +0 -1
  118. package/dist/chunk-enf0egke.js +0 -1
  119. package/dist/chunk-er7r2abv.js +0 -1
  120. package/dist/chunk-j7784bxm.js +0 -1
  121. package/dist/chunk-k1tfry97.js +0 -5
  122. package/dist/chunk-p2r4svss.js +0 -10
  123. package/dist/chunk-r95wa6vn.js +0 -1
  124. package/dist/chunk-wsa7g7vd.js +0 -1
  125. package/dist/chunk-yx6kf3s7.js +0 -1
  126. package/dist/chunk-zn9tdkrq.js +0 -1
  127. package/dist/chunk-zqjm9yd8.js +0 -1
  128. package/dist/chunk-zv01qe34.js +0 -1
  129. package/dist/web/assets/ChatView-DYpMrwtA.js +0 -63
  130. package/dist/web/assets/TaskSwitcher-Dbo20Tim.js +0 -26
  131. package/dist/web/assets/chevrons-up-down-zQ_UZWV9.js +0 -16
  132. package/dist/web/assets/index-RGoMvYl5.css +0 -1
  133. package/dist/web/assets/index-pqMcowCZ.js +0 -203
  134. package/dist/web/assets/teamService-fDnXqw4L.js +0 -1
@@ -1,5 +0,0 @@
1
- import{qg as of}from"./chunk-f2y0gxyq.js";import{ej as t_,fj as yf,gj as af,hj as R_,ij as Lf,kj as Gf,mj as Hf,oj as g,pj as Cf,rj as Uf,sj as Ff,uj as s}from"./chunk-n34qsnks.js";import{Cj as a}from"./chunk-5q4z0sfr.js";import{Mj as IE,Oj as Jf}from"./chunk-0b67y4j1.js";import{Rj as eE}from"./chunk-9kj19a8t.js";var B_={openrouter:{"HTTP-Referer":"https://github.com/echoVic/blade-code","X-Title":"Blade"},cerebras:{"X-Cerebras-3rd-Party-Integration":"blade"}},RE=(f)=>B_[f]||{};var b_=new Set(["user-cancel","interrupt","sibling-error","timeout"]);function cf(f){return typeof f==="string"&&b_.has(f)}function LT(f){if(!f.aborted)return;if(cf(f.reason))return f.reason;return"user-cancel"}function ZT(f){if(cf(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 PE(...f){let E=f.filter(Boolean);if(E.length===0)return new AbortController().signal;if(E.length===1)return E[0];let _=AbortSignal;if(typeof _.any==="function")return _.any(E);for(let x of E)if(x.aborted)return x;let T=new AbortController,h=new Map;for(let x of E){let N=()=>{T.abort(x.reason);for(let[P,M]of h)P.removeEventListener("abort",M)};h.set(x,N)}for(let[x,N]of h)x.addEventListener("abort",N,{once:!0});return T.signal}function _f(f,E,_){let T=_?.throwOnAbort??!1;if(E?.aborted){if(T)return Promise.reject(new DOMException("Aborted","AbortError"));return Promise.resolve()}return new Promise((h,x)=>{let N,P=setTimeout(()=>{if(E&&N)E.removeEventListener("abort",N);h()},f);if(E)N=()=>{if(clearTimeout(P),T)x(new DOMException("Aborted","AbortError"));else h()},E.addEventListener("abort",N,{once:!0})})}var O_=a("Chat"),V_={input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}};function AE(f){if(typeof f==="string")return f;return f.filter((E)=>E.type==="text").map((E)=>E.text).join(`
2
- `)}function j_(f){if(!f)return{};try{let E=JSON.parse(f);return E&&typeof E==="object"&&!Array.isArray(E)?E:{}}catch{return O_.warn("[PiAIChatService] Invalid historical tool arguments",{value:f}),{}}}function X_(f){let E=f.match(/^data:([^;,]+);base64,(.+)$/s);return E?{mimeType:E[1],data:E[2]}:void 0}async function c_(f,E){let _=X_(f);if(_)return{type:"image",..._};if(!/^https?:\/\//i.test(f))return{type:"text",text:`[Unsupported image source: ${f}]`};let T=await fetch(f,{signal:E});if(!T.ok)throw Error(`Failed to load image ${f}: HTTP ${T.status}`);return{type:"image",mimeType:T.headers.get("content-type")?.split(";")[0]??"image/png",data:Buffer.from(await T.arrayBuffer()).toString("base64")}}async function SE(f,E,_){return Promise.all(f.map((T)=>T.type==="text"?Promise.resolve({type:"text",text:T.text}):E?c_(T.image_url.url,_):Promise.resolve({type:"text",text:"[Image omitted: current model does not support image input]"})))}async function NE(f,E,_,T,h){let x=f.filter((S)=>S.role==="system").map((S)=>AE(S.content)).filter(Boolean).join(`
3
-
4
- `),N=[],P=E.input.includes("image");for(let S of f){if(S.role==="system")continue;if(S.role==="user"){let t=typeof S.content==="string"?S.content:await SE(S.content,P,T);N.push({role:"user",content:t,timestamp:Date.now()});continue}if(S.role==="assistant"){let t=[];if(S.reasoningContent?.trim())t.push({type:"thinking",thinking:S.reasoningContent});let A=AE(S.content);if(A)t.push({type:"text",text:A});for(let D of S.tool_calls??[]){if(!("function"in D))continue;t.push({type:"toolCall",id:D.id,name:D.function.name,arguments:j_(D.function.arguments)})}N.push({role:"assistant",content:t,api:E.api,provider:E.provider,model:E.id,usage:V_,stopReason:S.tool_calls?.length?"toolUse":"stop",timestamp:Date.now()});continue}N.push({role:"toolResult",toolCallId:S.tool_call_id??"",toolName:S.name??"unknown",content:typeof S.content==="string"?[{type:"text",text:S.content}]:await SE(S.content,P,T),isError:!1,timestamp:Date.now()})}let M=_?.filter((S)=>!h||S.name===h).map((S)=>({name:S.name,description:S.description,parameters:S.parameters,constrainedSampling:S.constrainedSampling})).sort((S,t)=>S.name<t.name?-1:S.name>t.name?1:0);return{...x?{systemPrompt:x}:{},messages:N,...M?.length?{tools:M}:{}}}function uE(f){let E=[];for(let _=0;_<f.length;_++){let T=f[_];if(T.role==="tool")continue;let h=T.role==="assistant"&&T.tool_calls?.length?T.tool_calls:void 0;if(!h){E.push(T);continue}let x=[],N=_+1;while(N<f.length&&f[N].role==="tool")x.push(f[N++]);let P=new Set(h.map((t)=>t.id)),M=x.filter((t)=>t.tool_call_id&&P.has(t.tool_call_id)),S=new Set(M.map((t)=>t.tool_call_id));if(P.size===h.length&&M.length===P.size&&S.size===P.size)E.push(T,...M);_=N-1}return E}function DE(f){return f.some((E)=>E.role==="assistant"&&Boolean(E.tool_calls?.length)&&!E.reasoningContent?.trim())}function HE(f,E){return{...f,...E.baseUrl?{baseUrl:IE(f.api,E.baseUrl)}:{},...E.maxOutputTokens?{maxTokens:E.maxOutputTokens}:{}}}function Wf(f){let E=f.modelCatalog??Jf();return{models:E.models,model:HE(E.getModel(f.provider,f.model),f)}}function UE(f,E){let _=f.modelCatalog??Jf();return HE(_.getModel(E.provider,E.model),f)}import{createHash as J_}from"node:crypto";var W_=32,$_=1000,z_=512,L_=2000,G_=0.1,k_=0.05,Z_=0.9,Q_=300000,K_=3600000;class $f{sessions=new Map;observe(f){if(f.retention==="none"){this.sessions.delete(f.sessionId);return}let E=f.now??Date.now(),_=C_(f,E),T=this.sessions.get(f.sessionId);if(_.callCount=(T?.callCount??0)+1,this.touch(f.sessionId,_),T&&_.contextEpoch!==T.contextEpoch)return;if(!T||T.cacheReadTokens<$_)return;let h=T.cacheReadTokens-_.cacheReadTokens,x=Math.min(L_,Math.max(z_,T.cacheReadTokens*G_));if(h<x||_.cacheReadTokens>=T.cacheReadTokens*(1-k_))return;let N=_.modelIdentity!==T.modelIdentity,P=_.systemHash!==T.systemHash,M=_.toolsHash!==T.toolsHash,S=_.policyHash!==T.policyHash;if(!(N||P||M||S)&&_.promptTokens<T.promptTokens*Z_)return;let A=Math.max(0,E-T.recordedAt),D=T.retention==="long"?K_:Q_,Y=N?"model_changed":P?"system_prompt_changed":M?"tools_changed":S?"request_policy_changed":A>=D?"ttl_expired":"server_side",z=F_(T,_);return{reason:Y,previousCacheReadTokens:T.cacheReadTokens,cacheReadTokens:_.cacheReadTokens,cacheWriteTokens:Math.max(0,f.usage.cacheCreationInputTokens??0),tokenDrop:h,elapsedMs:A,callNumber:_.callCount,systemPromptChanged:P,systemCharDelta:_.systemChars-T.systemChars,toolsChanged:M,addedToolCount:z.added,removedToolCount:z.removed,changedToolCount:z.changed,modelChanged:N,requestPolicyChanged:S}}clear(f){if(f)this.sessions.delete(f);else this.sessions.clear()}statsForTests(){return{sessions:this.sessions.size}}touch(f,E){this.sessions.delete(f),this.sessions.set(f,E);while(this.sessions.size>W_){let _=this.sessions.keys().next().value;if(_===void 0)break;this.sessions.delete(_)}}}function C_(f,E){let _=[...f.tools??f.context.tools??[]].map((T)=>({identityHash:Tf(T.name),contractHash:Tf(hf(T))})).sort((T,h)=>T.identityHash<h.identityHash?-1:T.identityHash>h.identityHash?1:0);return{modelIdentity:f.modelIdentity,systemHash:Tf(f.context.systemPrompt??""),systemChars:f.context.systemPrompt?.length??0,toolsHash:Tf(hf(_)),toolFingerprints:_,policyHash:Tf(hf(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:E,callCount:1}}function F_(f,E){let _=new Map(f.toolFingerprints.map((h)=>[h.identityHash,h.contractHash])),T=new Map(E.toolFingerprints.map((h)=>[h.identityHash,h.contractHash]));return{added:[...T.keys()].filter((h)=>!_.has(h)).length,removed:[..._.keys()].filter((h)=>!T.has(h)).length,changed:[...T].filter(([h,x])=>_.has(h)&&_.get(h)!==x).length}}function hf(f){if(f===null||typeof f!=="object")return JSON.stringify(f)??"undefined";if(Array.isArray(f))return`[${f.map(hf).join(",")}]`;let E=f;return`{${Object.keys(E).sort().map((_)=>`${JSON.stringify(_)}:${hf(E[_])}`).join(",")}}`}function Tf(f){return J_("sha256").update(f).digest("hex")}import{randomBytes as o_}from"node:crypto";import{createHmac as v_}from"node:crypto";function s_(f){try{let E=new URL(f);if(E.hash="",E.hostname=E.hostname.toLowerCase(),E.searchParams.sort(),E.pathname!=="/")E.pathname=E.pathname.replace(/\/+$/,"");return E.toString()}catch{return f.trim().replace(/\/+$/,"")}}function w_(f){if(!f)return[];return Object.entries(f).map(([E,_])=>[E.trim().toLowerCase(),_.trim()]).sort(([E],[_])=>E.localeCompare(_))}function uf(f,E,_){let T=JSON.stringify([f.provider.trim(),String(f.api).trim(),s_(f.baseUrl),f.model.trim(),f.serviceTier?.trim()??"",f.apiVersion?.trim()??"",f.apiKey??"",w_(f.customHeaders),_]);return v_("sha256",Buffer.from(E)).update(T).digest("hex")}var p_=60000,m_=4,q_=0.8;var If=300000,kf=600000;var YE=128,BE=256,g_=1800000,Df=50;class tf 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 Rf(f){return f instanceof tf||f!==null&&typeof f==="object"&&"code"in f&&f.code==="PROVIDER_CIRCUIT_OPEN"}function d(f,E){return f!==void 0&&Number.isSafeInteger(f)&&f>0?f:E}function l_(f,E){return f!==void 0&&Number.isFinite(f)&&f>0&&f<=1?f:E}function y_(f,E){return uf(f,E,{providerCircuitOpenDurationMs:f.openDurationMs})}function xf(f){let E=0;for(let _ of f)if(_.failure)E++;return E}function bE(f){return f!==void 0&&Number.isInteger(f)&&f>=100&&f<=599?f:void 0}function zf(f){if(f===void 0||!Number.isFinite(f)||f<0)return;return Math.min(Math.ceil(f),Gf)}class VE{#x=new Map;#t=new WeakMap;#f;#_;#h;#T;constructor(f={}){this.#f=f.processSecret?new Uint8Array(f.processSecret):o_(32),this.#_=f.now??(()=>performance.now()),this.#h=f.wallNow??f.now??Date.now,this.#T={maxEntries:Math.min(d(f.maxEntries,YE),YE),maxWindowEntries:Math.min(d(f.maxWindowEntries,BE),BE),windowMs:d(f.windowMs,p_),minSamples:d(f.minSamples,m_),errorRateThreshold:l_(f.errorRateThreshold,q_),idleTtlMs:d(f.idleTtlMs,g_)}}get size(){return this.#x.size}get(f){if(f.openDurationMs===0)return this.#P();let E=this.#_();this.#B(E);let _=y_(f,this.#f),T=this.#x.get(_);if(T)return T.lastTouchedAt=E,this.#E(T,f.probeLeaseMs);if(this.#x.size>=this.#T.maxEntries)this.#I();if(this.#x.size>=this.#T.maxEntries)return this.#P();let h={key:_,state:"closed",samples:[],generation:0,nextAttemptId:1,nextProbeLeaseId:1,configuredOpenDurationMs:f.openDurationMs,effectiveOpenDurationMs:f.openDurationMs,lastTouchedAt:E,detached:!1};return this.#x.set(_,h),this.#E(h,f.probeLeaseMs)}#E(f,E){let _=this,T=Math.max(If,Math.min(d(E,If),kf));return{preflight:()=>_.#A(f),check:()=>_.#b(f,T),recordSuccess:(h)=>_.#R(h,"success"),recordFailure:(h,x)=>_.#R(h,"failure",x),recordNeutral:(h)=>_.#R(h,"neutral"),abandon:(h)=>_.#u(h),snapshot:()=>_.#X(f)}}#P(){let f=this;return{preflight:()=>({eligible:!0}),check:()=>{let E=Object.freeze({kind:"noop"});return f.#t.set(E,{generation:0,attemptId:0,kind:"noop",settled:!1}),{allowed:!0,probe:!1,token:E}},recordSuccess:(E)=>f.#M(E),recordFailure:(E)=>f.#M(E),recordNeutral:(E)=>f.#M(E),abandon:(E)=>f.#u(E),snapshot:()=>({state:"closed",sampleCount:0,failureCount:0,noop:!0,detached:!1})}}#M(f){let E=this.#t.get(f);if(E?.kind==="noop")E.settled=!0;return}#A(f){let E=this.#_();if(f.detached)return{eligible:!0};if(f.lastTouchedAt=E,this.#D(f,E),f.state==="closed")return{eligible:!0};if(f.state==="open"){let T=f.nextProbeAt??E;return E<T?this.#U(f,T-E):{eligible:!0}}if(f.probeLeaseId===void 0||f.probeLeaseExpiresAt!==void 0&&E>=f.probeLeaseExpiresAt)return{eligible:!0};let _=Math.max(1,(f.probeLeaseExpiresAt??E+Df)-E);return this.#U(f,Math.min(Df,_))}#U(f,E){let{allowed:_,...T}=this.#S(f,E);return{eligible:!1,...T}}#b(f,E){let _=this.#_();if(f.detached)return this.#P().check();if(f.lastTouchedAt=_,this.#D(f,_),f.state==="closed")return this.#Y(f,"regular");if(f.state==="open"){let h=f.nextProbeAt??_;if(_<h)return this.#S(f,h-_);f.state="half_open",f.generation++,f.probeLeaseId=void 0,f.probeLeaseExpiresAt=void 0}if(f.probeLeaseId===void 0||f.probeLeaseExpiresAt!==void 0&&_>=f.probeLeaseExpiresAt)return this.#O(f,_,E);let T=Math.max(1,(f.probeLeaseExpiresAt??_+Df)-_);return this.#S(f,Math.min(Df,T))}#Y(f,E,_){let T=Object.freeze({kind:E});return this.#t.set(T,{entry:f,generation:f.generation,attemptId:f.nextAttemptId++,kind:E,..._!==void 0?{probeLeaseId:_}:{},settled:!1}),{allowed:!0,probe:E==="probe",token:T}}#O(f,E,_){let T=f.nextProbeLeaseId++;f.probeLeaseId=T,f.probeLeaseExpiresAt=E+_,f.lastTouchedAt=E;let h=this.#Y(f,"probe",T),x=f.lastFailure??{reason:"server_error"};return{...h,reason:x.reason,...x.statusCode!==void 0?{statusCode:x.statusCode}:{},openDurationMs:f.effectiveOpenDurationMs,sampleCount:f.samples.length,failureCount:xf(f.samples)}}#S(f,E){let _=f.lastFailure??{reason:"server_error"};return{allowed:!1,state:f.state==="open"?"open":"half_open",reason:_.reason,..._.statusCode!==void 0?{statusCode:_.statusCode}:{},retryAfterMs:Math.max(0,Math.ceil(E)),nextProbeAt:this.#h()+Math.max(0,Math.ceil(E)),openDurationMs:f.effectiveOpenDurationMs,sampleCount:f.samples.length,failureCount:xf(f.samples)}}#R(f,E,_){let T=this.#t.get(f);if(!T||T.settled)return;if(T.settled=!0,T.kind==="noop"||!T.entry)return;let h=T.entry;if(h.detached||T.generation!==h.generation||T.kind==="regular"&&h.state!=="closed"||T.kind==="probe"&&(h.state!=="half_open"||T.probeLeaseId!==h.probeLeaseId))return;let x=this.#_();if(h.lastTouchedAt=x,T.kind==="probe"){if(E==="failure"&&_)return this.#N(h,_,x,"reopened");return this.#V(h)}if(E==="neutral")return;if(this.#j(h,E==="failure",x),E!=="failure"||!_)return;let N=zf(_.retryAfterMs);if(_.reason==="rate_limit"&&_.statusCode===429&&N!==void 0&&N>0)return this.#N(h,{..._,retryAfterMs:N},x,"opened");let P=xf(h.samples),M=h.samples.length===0?0:P/h.samples.length;if(h.samples.length>=this.#T.minSamples&&M>=this.#T.errorRateThreshold)return this.#N(h,_,x,"opened");return}#N(f,E,_,T){let h={reason:E.reason,...bE(E.statusCode)!==void 0?{statusCode:bE(E.statusCode)}:{},...zf(E.retryAfterMs)!==void 0?{retryAfterMs:zf(E.retryAfterMs)}:{}},x=h.retryAfterMs??0,N=Math.max(f.configuredOpenDurationMs,x);return f.state="open",f.generation++,f.probeLeaseId=void 0,f.probeLeaseExpiresAt=void 0,f.effectiveOpenDurationMs=N,f.nextProbeAt=_+N,f.lastFailure=h,{phase:T,reason:h.reason,...h.statusCode!==void 0?{statusCode:h.statusCode}:{},retryAfterMs:N,nextProbeAt:this.#h()+N,openDurationMs:N,sampleCount:f.samples.length,failureCount:xf(f.samples)}}#V(f){let E=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:E.reason,...E.statusCode!==void 0?{statusCode:E.statusCode}:{},openDurationMs:f.effectiveOpenDurationMs,sampleCount:0,failureCount:0}}#u(f){let E=this.#t.get(f);if(!E||E.settled)return!1;if(E.settled=!0,E.kind==="noop")return!0;let _=E.entry;if(!_||_.detached||E.kind!=="probe"||E.generation!==_.generation||E.probeLeaseId!==_.probeLeaseId)return!1;return _.probeLeaseId=void 0,_.probeLeaseExpiresAt=void 0,_.lastTouchedAt=this.#_(),!0}#j(f,E,_){if(this.#D(f,_),f.samples.length>=this.#T.maxWindowEntries)f.samples.shift();f.samples.push({at:_,failure:E})}#D(f,E){let _=E-this.#T.windowMs,T=0;while(T<f.samples.length&&f.samples[T].at<_)T++;if(T>0)f.samples.splice(0,T)}#X(f){if(!f.detached)this.#D(f,this.#_());return{state:f.state,sampleCount:f.samples.length,failureCount:xf(f.samples),...f.nextProbeAt!==void 0?{nextProbeAt:f.nextProbeAt}:{},noop:!1,detached:f.detached}}#B(f){for(let[E,_]of this.#x)if(_.state==="closed"&&f-_.lastTouchedAt>this.#T.idleTtlMs)this.#H(E,_)}#I(){let f;for(let E of this.#x.values())if(E.state==="closed"&&(!f||E.lastTouchedAt<f.lastTouchedAt))f=E;if(f)this.#H(f.key,f)}#H(f,E){E.detached=!0,this.#x.delete(f)}}var OE;function jE(){return OE??=new VE,OE}import{randomBytes as a_}from"node:crypto";var d_=16,XE=128,cE=32,n_=3,JE=16,WE=96,$E=24,zE=12,LE=16,GE=4,kE=4,ZE=67108864,QE=33554432,e_=12,r_=2,KE=2,CE=1,oE=15000,FE=30000;function Zf(){return{foreground:0,background:0,internal:0}}function Qf(){return{inFlight:Zf(),queued:Zf(),pendingBytes:Zf()}}function U(f){return f.foreground+f.background+f.internal}function $(f){return f.background+f.internal}function vE(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 Pf extends Error{reason;scope;requestClass;resource;inFlight;limit;queued;maxWaitMs;code="PROVIDER_ADMISSION_BUSY";retryable;constructor(f,E,_,T,h,x,N,P){super(f==="queue_full"?`Provider request admission ${E} ${T} queue is full`:f==="wait_timeout"?`Provider request admission timed out waiting for ${E} capacity`:"Provider request admission scheduler is closed");this.reason=f;this.scope=E;this.requestClass=_;this.resource=T;this.inFlight=h;this.limit=x;this.queued=N;this.maxWaitMs=P;this.name="ProviderAdmissionError",this.retryable=f!=="closed"}}function l(f){return f instanceof Pf||f!==null&&typeof f==="object"&&"code"in f&&f.code==="PROVIDER_ADMISSION_BUSY"}function J(f,E,_){if(f===void 0||!Number.isSafeInteger(f)||f<=0)return E;return Math.min(f,_)}function i_(f){let E=J(f.globalMaxInFlight,d_,Number.MAX_SAFE_INTEGER),_=J(f.globalMaxPending,XE,XE),T=J(f.domainMaxPending,cE,cE),h=Math.min(J(f.ownerMaxInFlight,n_,Number.MAX_SAFE_INTEGER),E),x=Math.min(J(f.ownerMaxPending,JE,JE),_),N=Math.min(J(f.nonForegroundGlobalMaxPending,Math.min(WE,Math.max(1,Math.floor(_*3/4))),WE),_),P=Math.min(J(f.nonForegroundDomainMaxPending,Math.min($E,Math.max(1,Math.floor(T*3/4))),$E),T),M=Math.min(J(f.nonForegroundOwnerMaxPending,Math.min(zE,Math.max(1,Math.floor(x*3/4))),zE),x),S=Math.min(J(f.internalGlobalMaxPending,Math.min(LE,Math.max(1,Math.floor(_/8))),LE),N),t=Math.min(J(f.internalDomainMaxPending,Math.min(GE,Math.max(1,Math.floor(T/8))),GE),P),A=Math.min(J(f.internalOwnerMaxPending,Math.min(kE,Math.max(1,Math.floor(x/4))),kE),M),D=J(f.globalMaxPendingBytes,s,s),Y=Math.min(J(f.domainMaxPendingBytes,ZE,ZE),D),z=Math.min(J(f.ownerMaxPendingBytes,QE,QE),D),Q=Math.min(J(f.nonForegroundGlobalMaxInFlight,Math.min(e_,E),E),E),K=Math.min(J(f.nonForegroundOwnerMaxInFlight,Math.min(r_,h),h),h),F=Math.min(J(f.internalGlobalMaxInFlight,Math.min(KE,E),KE),E),Bf=J(f.internalDomainMaxInFlight,CE,CE),Af=J(f.agingMs,FE,FE);return{globalMaxInFlight:E,globalMaxPending:_,domainMaxPending:T,ownerMaxInFlight:h,ownerMaxPending:x,nonForegroundGlobalMaxPending:N,nonForegroundDomainMaxPending:P,nonForegroundOwnerMaxPending:M,internalGlobalMaxPending:S,internalDomainMaxPending:t,internalOwnerMaxPending:A,globalMaxPendingBytes:D,domainMaxPendingBytes:Y,ownerMaxPendingBytes:z,nonForegroundGlobalMaxInFlight:Q,nonForegroundOwnerMaxInFlight:K,internalGlobalMaxInFlight:F,internalDomainMaxInFlight:Bf,agingMs:Af,classLimitsEnabled:f.classLimitsEnabled!==!1}}function sE(f,E){if(!f.trim())throw Error(`${E} must not be blank`)}function fT(f){if(sE(f.sessionId,"sessionId"),sE(f.ownerId,"ownerId"),!Number.isSafeInteger(f.scope.maxConcurrent)||f.scope.maxConcurrent<Hf||f.scope.maxConcurrent>g)throw Error(`maxConcurrent must be between ${Hf} and ${g}`);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>Uf)throw Error(`maxWaitMs must be 0-${Uf}`)}function Kf(f,E){if(E!==void 0)return E;if(f?.reason!==void 0)return f.reason;return new DOMException("Provider request admission cancelled","AbortError")}function ET(f,E){return uf(f,E,{providerRequestConcurrency:f.maxConcurrent,providerRequestPendingBytes:f.maxPendingBytes})}class pE{#x;#t;#f;#_=[];#h=new Map;#T=new Map;#E=Qf();#P=1;#M=0;#A=!1;constructor(f={}){this.#x=f.processSecret?new Uint8Array(f.processSecret):a_(32),this.#t=f.now??(()=>performance.now()),this.#f=i_(f)}admit(f){if(fT(f),this.#A)throw this.#c("closed",f,{scope:"global",resource:"stream",inFlight:U(this.#E.inFlight),limit:this.#f.globalMaxInFlight},this.#_.length);if(f.signal?.aborted)throw Kf(f.signal);let E=ET(f.scope,this.#x),_=this.#h.get(E),T=this.#T.get(f.ownerId),h=_??this.#Y(f.scope.maxConcurrent),x=T??this.#O();if(this.#_.length===0&&this.#S(h,x,f.requestClass)){if(!_)this.#h.set(E,h);if(!T)this.#T.set(f.ownerId,x),this.#P++;let D=this.#N(E,f.ownerId,f.requestClass),Y=this.#L(f,0);return{ready:Promise.resolve(D),getSnapshot:()=>({...Y}),cancel:()=>{Y={...Y}}}}let N=this.#U(f,h,x);if(N)throw this.#c("queue_full",f,N,this.#_.length);let P=this.#R(h,x,f.requestClass);if(f.maxWaitMs===0)throw this.#c("wait_timeout",f,P,this.#_.length);if(!_)this.#h.set(E,h);if(!T)this.#T.set(f.ownerId,x),this.#P++;let M,S,t=new Promise((D,Y)=>{M=D,S=Y});t.catch(()=>{return});let A={domainKey:E,sessionId:f.sessionId,ownerId:f.ownerId,requestClass:f.requestClass,maxWaitMs:f.maxWaitMs,pendingBytes:f.pendingBytes,enqueuedAt:this.#t(),signal:f.signal,resolve:M,reject:S,settled:!1,admitted:!1};if(f.signal)A.abortListener=()=>this.#B(A,Kf(f.signal)),f.signal.addEventListener("abort",A.abortListener,{once:!0});return A.timer=setTimeout(()=>this.#X(A),f.maxWaitMs),A.timer.unref?.(),this.#_.push(A),this.#b(h,x,A),this.#u(),{ready:t,getSnapshot:()=>this.#z(A),cancel:(D)=>this.#B(A,Kf(f.signal,D))}}close(){if(this.#A)return;this.#A=!0;for(let f of[...this.#_]){let E=this.#h.get(f.domainKey),_=this.#T.get(f.ownerId),T=E&&_?this.#R(E,_,f.requestClass):{scope:"global",resource:"stream",inFlight:U(this.#E.inFlight),limit:this.#f.globalMaxInFlight};this.#I(f,new Pf("closed",T.scope,f.requestClass,T.resource,T.inFlight,T.limit,this.#_.length,f.maxWaitMs))}}getStats(){return{inFlight:U(this.#E.inFlight),queued:this.#_.length,pendingBytes:U(this.#E.pendingBytes),nonForegroundInFlight:$(this.#E.inFlight),internalInFlight:this.#E.inFlight.internal,nonForegroundQueued:$(this.#E.queued),internalQueued:this.#E.queued.internal,nonForegroundPendingBytes:$(this.#E.pendingBytes),internalPendingBytes:this.#E.pendingBytes.internal,domainCount:this.#h.size,ownerCount:this.#T.size,closed:this.#A}}#U(f,E,_){let T=(t,A,D)=>A>=D?{scope:t,resource:"pending_count",inFlight:A,limit:D}:void 0;if(this.#f.classLimitsEnabled&&f.requestClass==="internal"){let t=T("class",this.#E.queued.internal,this.#f.internalGlobalMaxPending)??T("class",_.counters.queued.internal,this.#f.internalOwnerMaxPending)??T("class",E.counters.queued.internal,this.#f.internalDomainMaxPending);if(t)return t}if(this.#f.classLimitsEnabled&&f.requestClass!=="foreground"){let t=T("class",$(this.#E.queued),this.#f.nonForegroundGlobalMaxPending)??T("class",$(_.counters.queued),this.#f.nonForegroundOwnerMaxPending)??T("class",$(E.counters.queued),this.#f.nonForegroundDomainMaxPending);if(t)return t}let h=T("global",this.#_.length,this.#f.globalMaxPending)??T("owner",U(_.counters.queued),this.#f.ownerMaxPending)??T("domain",U(E.counters.queued),this.#f.domainMaxPending);if(h)return h;let x=Math.min(f.scope.maxPendingBytes,this.#f.globalMaxPendingBytes),N=Math.min(x,this.#f.domainMaxPendingBytes),P=Math.min(x,this.#f.ownerMaxPendingBytes),M=(t,A)=>f.pendingBytes>A-t,S=(t)=>{if(t==="owner")return{scope:t,resource:"pending_bytes",inFlight:U(_.counters.inFlight),limit:this.#f.ownerMaxInFlight};if(t==="domain")return{scope:t,resource:"pending_bytes",inFlight:U(E.counters.inFlight),limit:E.maxConcurrent};return{scope:t,resource:"pending_bytes",inFlight:U(this.#E.inFlight),limit:this.#f.globalMaxInFlight}};if(f.requestClass==="internal"){let t=Math.max(1,Math.floor(x/8)),A=Math.max(1,Math.floor(N/4)),D=Math.max(1,Math.floor(P/4));if(M(this.#E.pendingBytes.internal,t)||M(_.counters.pendingBytes.internal,D)||M(E.counters.pendingBytes.internal,A))return S("class")}if(f.requestClass!=="foreground"){let t=Math.max(1,Math.floor(x*3/4)),A=Math.max(1,Math.floor(N*3/4)),D=Math.max(1,Math.floor(P/2));if(M($(this.#E.pendingBytes),t)||M($(_.counters.pendingBytes),D)||M($(E.counters.pendingBytes),A))return S("class")}if(M(U(this.#E.pendingBytes),x))return S("global");if(M(U(_.counters.pendingBytes),P))return S("owner");if(M(U(E.counters.pendingBytes),N))return S("domain");return}#b(f,E,_){let{requestClass:T,pendingBytes:h}=_;this.#E.queued[T]++,f.counters.queued[T]++,E.counters.queued[T]++,this.#E.pendingBytes[T]+=h,f.counters.pendingBytes[T]+=h,E.counters.pendingBytes[T]+=h}#Y(f){return{maxConcurrent:f,counters:Qf()}}#O(){return{order:this.#P,counters:Qf()}}#S(f,E,_){if(U(this.#E.inFlight)>=this.#f.globalMaxInFlight)return!1;if(U(f.counters.inFlight)>=f.maxConcurrent)return!1;if(U(E.counters.inFlight)>=this.#f.ownerMaxInFlight)return!1;if(_==="foreground"||!this.#f.classLimitsEnabled)return!0;if($(this.#E.inFlight)>=this.#f.nonForegroundGlobalMaxInFlight)return!1;if($(E.counters.inFlight)>=this.#f.nonForegroundOwnerMaxInFlight)return!1;let T=Math.max(1,f.maxConcurrent-1);if($(f.counters.inFlight)>=T)return!1;if(_!=="internal")return!0;return this.#E.inFlight.internal<this.#f.internalGlobalMaxInFlight&&f.counters.inFlight.internal<this.#f.internalDomainMaxInFlight}#R(f,E,_){if(U(E.counters.inFlight)>=this.#f.ownerMaxInFlight)return{scope:"owner",resource:"stream",inFlight:U(E.counters.inFlight),limit:this.#f.ownerMaxInFlight};if(this.#f.classLimitsEnabled&&_!=="foreground"&&$(E.counters.inFlight)>=this.#f.nonForegroundOwnerMaxInFlight)return{scope:"class",resource:"stream",inFlight:$(E.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(this.#f.classLimitsEnabled&&_!=="foreground"){let T=Math.max(1,f.maxConcurrent-1);if($(f.counters.inFlight)>=T)return{scope:"class",resource:"stream",inFlight:$(f.counters.inFlight),limit:T}}if(this.#f.classLimitsEnabled&&_==="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.#E.inFlight)>=this.#f.globalMaxInFlight)return{scope:"global",resource:"stream",inFlight:U(this.#E.inFlight),limit:this.#f.globalMaxInFlight};if(this.#f.classLimitsEnabled&&_!=="foreground"&&$(this.#E.inFlight)>=this.#f.nonForegroundGlobalMaxInFlight)return{scope:"class",resource:"stream",inFlight:$(this.#E.inFlight),limit:this.#f.nonForegroundGlobalMaxInFlight};if(this.#f.classLimitsEnabled&&_==="internal"&&this.#E.inFlight.internal>=this.#f.internalGlobalMaxInFlight)return{scope:"class",resource:"stream",inFlight:this.#E.inFlight.internal,limit:this.#f.internalGlobalMaxInFlight};return{scope:"domain",resource:"stream",inFlight:U(f.counters.inFlight),limit:f.maxConcurrent}}#N(f,E,_){let T=this.#h.get(f),h=this.#T.get(E);if(!T||!h)throw Error("Provider admission accounting state is unavailable");this.#E.inFlight[_]++,T.counters.inFlight[_]++,h.counters.inFlight[_]++;let x=!1;return{release:()=>{if(x)return;x=!0,this.#V(f,E,_)}}}#V(f,E,_){let T=this.#h.get(f),h=this.#T.get(E);if(this.#E.inFlight[_]--,T)T.counters.inFlight[_]--;if(h)h.counters.inFlight[_]--;this.#J(f,E),this.#u()}#u(){if(this.#A)return;while(this.#_.length>0){let f=this.#t(),E=new Map;for(let[P,M]of this.#_.entries()){let S=this.#h.get(M.domainKey),t=this.#T.get(M.ownerId);if(S===void 0||t===void 0||!this.#S(S,t,M.requestClass))continue;let A=this.#j(M,f),D=E.get(M.ownerId);if(!D||A<D.rank||A===D.rank&&P<D.index)E.set(M.ownerId,{pending:M,rank:A,index:P})}let _=[...E.values()].filter(({pending:P})=>{let M=this.#h.get(P.domainKey),S=this.#T.get(P.ownerId);return M!==void 0&&S!==void 0&&this.#S(M,S,P.requestClass)}).map(({pending:P,rank:M})=>({pending:P,rank:M,order:this.#T.get(P.ownerId).order}));if(_.length===0)return;let T=Math.min(..._.map((P)=>P.rank)),h=_.filter((P)=>P.rank===T),N=h.filter((P)=>P.order>this.#M).sort((P,M)=>P.order-M.order)[0]??h.sort((P,M)=>P.order-M.order)[0];this.#D(N.pending,N.order)}}#j(f,E){let _=f.requestClass==="foreground"?0:f.requestClass==="background"?1:2,T=Math.floor(Math.max(0,E-f.enqueuedAt)/this.#f.agingMs);return Math.max(0,_-T)}#D(f,E){if(!this.#H(f,!1))return;f.settled=!0,f.admitted=!0,this.#M=E;let _=this.#N(f.domainKey,f.ownerId,f.requestClass);f.permit=_,f.resolve(_)}#X(f){let E=this.#h.get(f.domainKey),_=this.#T.get(f.ownerId),T=E&&_?this.#R(E,_,f.requestClass):{scope:"global",resource:"stream",inFlight:U(this.#E.inFlight),limit:this.#f.globalMaxInFlight};this.#I(f,new Pf("wait_timeout",T.scope,f.requestClass,T.resource,T.inFlight,T.limit,this.#_.length,f.maxWaitMs))}#B(f,E){this.#I(f,E)}#I(f,E){if(!this.#H(f))return;f.settled=!0,f.reject(E),this.#u()}#H(f,E=!0){if(f.settled||f.admitted)return!1;let _=this.#_.indexOf(f);if(_<0)return!1;this.#_.splice(_,1);let T=this.#h.get(f.domainKey),h=this.#T.get(f.ownerId);if(T&&h)this.#W(T,h,f);if(this.#$(f),E)this.#J(f.domainKey,f.ownerId);return!0}#W(f,E,_){let{requestClass:T,pendingBytes:h}=_;this.#E.queued[T]--,f.counters.queued[T]--,E.counters.queued[T]--,this.#E.pendingBytes[T]-=h,f.counters.pendingBytes[T]-=h,E.counters.pendingBytes[T]-=h}#$(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}#J(f,E){let _=this.#h.get(f);if(_&&vE(_.counters))this.#h.delete(f);let T=this.#T.get(E);if(T&&vE(T.counters))this.#T.delete(E)}#z(f){let E=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.#_.length,inFlight:U(this.#E.inFlight),limit:this.#f.globalMaxInFlight,waitMs:E,maxWaitMs:f.maxWaitMs};let _=this.#h.get(f.domainKey),T=this.#T.get(f.ownerId),h=_&&T?this.#R(_,T,f.requestClass):{scope:"global",resource:"stream",inFlight:U(this.#E.inFlight),limit:this.#f.globalMaxInFlight};return{state:"queued",requestClass:f.requestClass,resource:h.resource,scope:h.scope,reason:"capacity",queuePosition:this.#G(f,h.scope),queueDepth:this.#_.length,inFlight:h.inFlight,limit:h.limit,waitMs:E,maxWaitMs:f.maxWaitMs}}#L(f,E){return{state:"admitted",requestClass:f.requestClass,resource:"stream",scope:"domain",queuePosition:0,queueDepth:this.#_.length,inFlight:U(this.#E.inFlight),limit:this.#f.globalMaxInFlight,waitMs:E,maxWaitMs:f.maxWaitMs}}#G(f,E){let _=this.#_.filter((T)=>{switch(E){case"owner":return T.ownerId===f.ownerId;case"domain":return T.domainKey===f.domainKey;case"class":return T.requestClass===f.requestClass;case"global":return!0}});return Math.max(1,_.indexOf(f)+1)}#c(f,E,_,T){return new Pf(f,_.scope,E.requestClass,_.resource,_.inFlight,_.limit,T,E.maxWaitMs)}}var wE;function mE(f={}){return wE??=new pE(f),wE}var qE=new WeakSet;class n extends Error{budgetMs;elapsedMs;code="PROVIDER_RECOVERY_BUDGET_EXCEEDED";constructor(f,E){super(`Provider recovery budget exhausted after ${f}ms`);this.budgetMs=f;this.elapsedMs=E;this.name="ProviderRecoveryBudgetExceededError"}}class vf 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 _T=["gousagelimiterror","freeusagelimiterror","monthly usage limit reached","available balance","insufficient_quota","out of budget","quota exceeded","billing"],TT=["prompt_too_long","prompt is too long","maximum context length","context length exceeded","context_length_exceeded","request too large"],hT=["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 gE(f){return(f instanceof Error?f.message:String(f)).toLowerCase()}function xT(f){let E=gE(f);return TT.some((_)=>E.includes(_))}function sf(f){if(f!==null&&typeof f==="object")qE.add(f)}function Rh(f){return f!==null&&typeof f==="object"&&qE.has(f)}function tT(f){return f!==null&&typeof f==="object"&&"code"in f?f.code:void 0}function RT(f){if(f===null||typeof f!=="object")return;let E=f;for(let _ of["status","statusCode"]){let T=E[_];if(typeof T==="number"&&Number.isInteger(T))return T}return}function PT(f){let E=f.match(/^(?:error:\s*)?(\d{3})\b/),_=f.match(/\b(?:status(?:\s+code)?|http)[:\s]+(\d{3})\b/),T=Number(E?.[1]??_?.[1]);return Number.isInteger(T)?T:void 0}function o(f,E){let _=gE(f),T=tT(f);if(T==="STREAM_IDLE_TIMEOUT"||T==="PROVIDER_RECOVERY_BUDGET_EXCEEDED"||f instanceof Error&&f.name==="AbortError"||_.includes("request aborted")||_==="aborted")return{retryable:!1};if(_T.some((x)=>_.includes(x))||xT(f))return{retryable:!1};if(E?.shouldRetry==="false")return{retryable:!1,statusCode:E.statusCode};if(T==="PROVIDER_REQUEST_DEADLINE_EXCEEDED")return{retryable:!0,reason:"timeout"};let h=E?.statusCode??RT(f)??PT(_);if(E?.shouldRetry==="true")return{retryable:!0,reason:h===429?"rate_limit":h===408||h===409?"timeout":"server_error",statusCode:h};if(h===429)return{retryable:!0,reason:"rate_limit",statusCode:h};if(h===408||h===409)return{retryable:!0,reason:"timeout",statusCode:h};if(h!==void 0&&h>=500&&h<=599)return{retryable:!0,reason:"server_error",statusCode:h};if(T==="PROVIDER_STREAM_CLOSED"||_.includes("stream closed before completion")||_.includes("ended without")||_.includes("stream ended before"))return{retryable:!0,reason:"stream_closed",statusCode:h};if(hT.some((x)=>_.includes(x)))return{retryable:!0,reason:"transport",statusCode:h};if(_.includes("timeout")||_.includes("timed out")||_.includes("temporarily unavailable")||_.includes("upstream_error")||_.includes("overloaded")||_.includes("rate limit")||_.includes("too many requests")||_.includes("service unavailable")||_.includes("server error")||_.includes("internal error")||_.includes("please retry")||_.includes("try your request again"))return{retryable:!0,reason:_.includes("rate")||_.includes("too many")?"rate_limit":_.includes("timeout")||_.includes("timed out")?"timeout":"server_error",statusCode:h};return{retryable:!1,statusCode:h}}function wf(f,E){if(!f)return;if(f.retryAfterMs!==void 0){let h=Number.parseFloat(f.retryAfterMs);if(Number.isFinite(h))return Math.max(0,h)}if(f.retryAfter===void 0)return;let _=Number.parseFloat(f.retryAfter);if(Number.isFinite(_))return Math.max(0,_*1000);let T=Date.parse(f.retryAfter);return Number.isFinite(T)?Math.max(0,T-E):void 0}function lE(f,E,_={}){let T=_.now??Date.now(),h=_.maxDelayMs??60000,x=wf(E,T);if(x!==void 0)return Math.min(Math.ceil(x),h);let N=Math.max(0,f-1),P=_.maxExponentialDelayMs??8000,M=Math.min(500*2**N,P),S=Math.max(0,Math.min(1,_.random??Math.random())),t=M*(0.75+S*0.25);return Math.min(Math.round(t),h)}function pf(f,E){return{provider:of(f),model:of(E)}}function yE(f,E){if(l(f))return{source:"admission",reason:f.reason};if(Rf(f))return{source:"circuit",reason:f.circuit.reason,...f.circuit.statusCode!==void 0?{statusCode:f.circuit.statusCode}:{}};if(f!==null&&typeof f==="object"&&"code"in f&&f.code==="STREAM_IDLE_TIMEOUT")return{source:"stall",reason:"timeout"};let _=o(f,E);if(_.retryable&&_.reason)return{source:"retry",reason:_.reason,..._.statusCode!==void 0?{statusCode:_.statusCode}:{}};throw Error("Provider fallback trigger is not classified")}function aE(f,E={}){let _=E.maxBytes??134217728,T=E.maxNodes??1e5;if(!Number.isSafeInteger(_)||_<=0||_>=Number.MAX_SAFE_INTEGER)throw Error("maxBytes must be a positive safe integer");if(!Number.isSafeInteger(T)||T<=0)throw Error("maxNodes must be a positive safe integer");let h=new WeakSet,x=0,N=0,P=!1,M=(t)=>{if(P||t<=0)return;if(!Number.isSafeInteger(t)||t>_-x){x=_+1,P=!0;return}x+=t},S=(t)=>{if(P)return;if(N+=1,N>T){M(_+1);return}if(t===null){M(4);return}switch(typeof t){case"string":M(Buffer.byteLength(t,"utf8"));return;case"number":case"bigint":M(8);return;case"boolean":M(4);return;case"undefined":case"function":case"symbol":return;case"object":break}if(h.has(t))return;if(h.add(t),ArrayBuffer.isView(t)){M(32+t.byteLength);return}if(t instanceof ArrayBuffer){M(32+t.byteLength);return}if(t instanceof Date){M(40);return}if(t instanceof RegExp){M(32+Buffer.byteLength(t.source,"utf8"));return}if(t instanceof Map){M(32);for(let[A,D]of t)if(S(A),S(D),P)return;return}if(t instanceof Set){M(32);for(let A of t)if(S(A),P)return;return}if(t instanceof WeakMap||t instanceof WeakSet){M(32);return}if(Array.isArray(t)){M(16);for(let A of t)if(S(A),P)return;return}M(32);for(let A of Reflect.ownKeys(t)){if(typeof A!=="string")continue;let D=Object.getOwnPropertyDescriptor(t,A);if(!D?.enumerable||!("value"in D))continue;if(M(8+Buffer.byteLength(A,"utf8")),S(D.value),P)return}};return S(f),x}function dE(f){return aE([f.messages,f.context,f.tools,f.requestOptions],{maxBytes:s})}function rE(f,E){let _=f.onPayload;f.onPayload=async(T,h)=>{let x=_?await _(T,h):T;return E(x===void 0?T:x,h)}}function AT(f){if(!f.reasoningEnabled)return;return f.reasoningEffort??f.reasoningLevel??"high"}function mf(f,E,_){if(!f.enablePromptCaching)return"none";if(_&&E.api==="openai-completions"&&!E.baseUrl.includes("api.openai.com"))return"long";return"short"}function ST(f){switch(f){case"minimal":return"MINIMAL";case"low":return"LOW";case"medium":return"MEDIUM";default:return"HIGH"}}function MT(f,E,_,T){let h=T?void 0:AT(_);if(!h){if(E.api==="anthropic-messages")f.thinkingEnabled=!1;if(E.api==="google-generative-ai"||E.api==="google-vertex")f.thinking={enabled:!1};return}switch(E.api){case"anthropic-messages":f.thinkingEnabled=!0,f.effort=h;break;case"google-generative-ai":case"google-vertex":f.thinking={enabled:!0,level:ST(h)};break;case"mistral-conversations":f.reasoningEffort="high";break;case"bedrock-converse-stream":case"pi-messages":f.reasoning=h;break;default:f.reasoningEffort=h}}function NT(f,E,_){if(!_)return;switch(E){case"anthropic-messages":case"bedrock-converse-stream":f.toolChoice={type:"tool",name:_};break;case"openai-completions":case"mistral-conversations":case"pi-messages":f.toolChoice={type:"function",function:{name:_}};break;case"openai-responses":case"openai-codex-responses":case"azure-openai-responses":f.toolChoice={type:"function",name:_};break;case"google-generative-ai":case"google-vertex":f.toolChoice="any";break}}function uT(f,E,_){let T=_.serviceTier;if(!T)return;if(E.api==="openai-responses"||E.api==="openai-codex-responses"||E.api==="azure-openai-responses"){f.serviceTier=T;return}if(E.api!=="openai-completions"&&!(E.api==="anthropic-messages"&&T==="fast"))return;rE(f,(h)=>{if(!h||typeof h!=="object"||Array.isArray(h))return h;return E.api==="anthropic-messages"?{...h,speed:"fast"}:{...h,service_tier:T}})}function DT(f,E,_){let T=_.responseVerbosity;if(!T)return;if(eE(E,T),E.api==="openai-codex-responses"){f.textVerbosity=T;return}rE(f,(h)=>{if(!h||typeof h!=="object"||Array.isArray(h))return h;if(E.api==="openai-completions")return{...h,verbosity:T};let x="text"in h&&h.text&&typeof h.text==="object"&&!Array.isArray(h.text)?h.text:{};return{...h,text:{...x,verbosity:T}}})}function iE(f,E,_,T,h=!1){let x={apiKey:f.apiKey,headers:f.customHeaders,signal:_,temperature:T?.temperature??f.temperature??0,maxTokens:T?.maxOutputTokens??f.maxOutputTokens,timeoutMs:f.timeout,maxRetries:0,cacheRetention:mf(f,E,T?.providerSessionId),sessionId:T?.providerSessionId};if(MT(x,E,f,h),NT(x,E.api,T?.toolChoice?.toolName),uT(x,E,f),DT(x,E,f),E.api==="azure-openai-responses")x.azureBaseUrl=f.baseUrl,x.azureApiVersion=f.apiVersion,x.azureDeploymentName=E.id;return x}function nE(f,E){let _=E.get("x-should-retry");return{statusCode:f,...E.get("retry-after")!==null?{retryAfter:E.get("retry-after")??void 0}:{},...E.get("retry-after-ms")!==null?{retryAfterMs:E.get("retry-after-ms")??void 0}:{},..._==="true"||_==="false"?{shouldRetry:_}:{}}}var IT=new Set(["anthropic-messages","openai-completions","openai-responses","openai-codex-responses","azure-openai-responses","pi-messages"]);function f_(f,E,_){let T=f.onResponse;if(f.onResponse=async(x,N)=>{let P=new Headers(x.headers);_(nE(x.status,P)),await T?.(x,N)},!IT.has(E.api)||typeof globalThis.fetch!=="function")return;let h=typeof f.fetch==="function"?f.fetch:globalThis.fetch.bind(globalThis);f.fetch=async(x,N)=>{let P=await h(x,N);return _(nE(P.status,P.headers)),P}}function E_(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 Yf=300000,HT=30000;class __ 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 T_ extends Error{code="PROVIDER_STREAM_CLOSED";constructor(){super("Provider stream closed before completion");this.name="ProviderStreamClosedError"}}function qf(f){return f.reason instanceof Error?f.reason:new DOMException("Aborted","AbortError")}function UT(f){return f.idleTimeoutMs&&f.idleTimeoutMs>0?f.idleTimeoutMs:Yf}function YT(f,E){if(E===0)return;let _=E!==void 0&&E>0?E:HT;return Math.max(1,Math.min(_,Math.floor(f/2)))}function BT(f,E,_){if(_?.aborted)return Promise.reject(qf(_));return new Promise((T,h)=>{let x=!1,N=()=>{clearTimeout(t),_?.removeEventListener("abort",S)},P=(A)=>{if(x)return;x=!0,N(),T(A)},M=(A)=>{if(x)return;x=!0,N(),h(A instanceof Error?A:Error(String(A)))},S=()=>{if(_)M(qf(_))},t=setTimeout(()=>P({kind:"timer"}),Math.max(0,E));if(_?.addEventListener("abort",S,{once:!0}),_?.aborted){S();return}f.then((A)=>P({kind:"next",result:A}),M)})}async function*bT(f,E,_){let T=UT(E),h=YT(T,E.stallWarningMs);if(E.signal?.aborted)throw qf(E.signal);let x=Date.now(),N=Promise.resolve().then(()=>f.next()),P;for(;;){let S=await BT(N,(P?T:h??T)-(Date.now()-x),E.signal);if(S.kind==="next"){if(P)yield{...P,phase:"recovered",durationMs:Math.max(P.durationMs,Date.now()-x)};return S.result}if(!P&&h!==void 0){_.stallCount++,P={phase:"detected",stallCount:_.stallCount,durationMs:h,warningAfterMs:h,timeoutMs:T,outputStarted:_.outputStarted},yield P;continue}let t=new __(T);throw E.abort?.(t),t}}async function*h_(f,E,_,T,h={}){let N=f.stream(E,_,T)[Symbol.asyncIterator](),P=0,M=!1,S={stallCount:0,outputStarted:!1};try{while(!0){let t=bT(N,h,S),A=await t.next();while(!A.done)yield{providerStall:A.value},A=await t.next();let D=A.value;if(D.done)throw new T_;let Y=D.value;switch(Y.type){case"text_delta":S.outputStarted=!0,yield{content:Y.delta};break;case"thinking_delta":S.outputStarted=!0,yield{reasoningContent:Y.delta};break;case"toolcall_end":S.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":M=!0,yield{finishReason:Y.reason,usage:E_(Y.message.usage)};return;case"error":throw Error(Y.error.errorMessage??`Request ${Y.reason==="aborted"?"aborted":"failed"}`)}}}finally{if(!M)Promise.resolve(N.return?.()).catch(()=>{return})}}var gf=a("Chat"),OT=1;function VT(f,E){let _=E.provider===f.provider,T=_&&E.channel===void 0,h=E.channel;return{...f,provider:E.provider,model:E.model,apiKey:h?.apiKey??(T?f.apiKey:void 0),baseUrl:h?.baseUrl??(T?f.baseUrl:void 0),temperature:h?.temperature??f.temperature,maxOutputTokens:h?.maxOutputTokens??(T?f.maxOutputTokens:void 0),timeout:h?.timeout??f.timeout,streamIdleTimeout:h?.streamIdleTimeout??f.streamIdleTimeout,apiVersion:h?.apiVersion??(T?f.apiVersion:void 0),customHeaders:h?.customHeaders??(T?f.customHeaders:void 0),enablePromptCaching:h?.enablePromptCaching??(T?f.enablePromptCaching:void 0),serviceTier:_?f.serviceTier:void 0,responseVerbosity:_?f.responseVerbosity:void 0,fallbackModels:void 0}}function jT(f){return Boolean(f&&f.role==="user"&&Array.isArray(f.content)&&f.content.some((E)=>E.type==="image_url"))}function XT(f){let _=f.findLast((T)=>{let h=T.metadata;return h!==null&&typeof h==="object"&&!Array.isArray(h)&&h.isCompactSummary===!0})?.metadata;return _!==null&&typeof _==="object"&&!Array.isArray(_)&&typeof _.parentId==="string"?_.parentId:""}function cT(f,E){let _=o(f,E);if(!_.retryable||!_.reason)return;let T=_.statusCode;switch(_.reason){case"rate_limit":if(T!==429)return;break;case"server_error":if(T===void 0||T<500||T>599)return;break;case"transport":case"stream_closed":break;case"timeout":return}let h=wf(E,Date.now());return{reason:_.reason,...T!==void 0?{statusCode:T}:{},...h!==void 0?{retryAfterMs:h}:{}}}function lf(f){return f!==null&&typeof f==="object"&&"code"in f&&f.code==="STREAM_IDLE_TIMEOUT"}class df{config;models;model;promptCacheBreakMonitor=new $f;providerAdmissionScheduler;admissionFallbackOwnerId=`pi-service-${process.pid}-${OT++}`;constructor(f){let E=Wf(f);this.config={...f,maxContextTokens:E.model.contextWindow,maxOutputTokens:f.maxOutputTokens??E.model.maxTokens},this.models=E.models,this.model=E.model,this.providerAdmissionScheduler=x_(this.config),gf.debug("[PiAIChatService] Initialized",{provider:this.model.provider,model:this.model.id,api:this.model.api})}async chat(f,E,_,T){let h="",x="",N=[],P,M;for await(let S of this.streamChat(f,E,_,T)){h+=S.content??"",x+=S.reasoningContent??"";for(let t of S.toolCalls??[])if(t.id&&t.type==="function"&&t.function?.name)N.push(t);P=S.usage??P,M=S.finishReason??M}return{content:h,...x?{reasoningContent:x}:{},...N.length>0?{toolCalls:N}:{},usage:P,finishReason:M}}async*streamChat(f,E,_,T){let h=T?.toolChoice?.toolName;if(h&&!E?.some((R)=>R.name===h))throw Error(`Required tool is unavailable: ${h}`);let x=uE(f);if(x.some((R)=>jT(R))&&!this.model.input.includes("image"))throw Error(`${this.model.name} does not support image input`);let N=Boolean(h)||DE(x),P=await NE(x,this.model,E,_,h),M=(R,u)=>{let V=T?.providerSessionId;if(!V||!R.usage)return R;if(!this.config.enablePromptCaching)return this.promptCacheBreakMonitor.clear(V),R;let B=mf(this.config,u,V),I=this.promptCacheBreakMonitor.observe({sessionId:V,modelIdentity:`${u.provider}\x00${u.api}\x00${u.id}`,context:P,retention:B,contextEpoch:XT(x),policy:{baseUrl:u.baseUrl??this.config.baseUrl??"",retention:B,requiredTool:h??"",reasoningEnabled:this.config.reasoningEnabled??!1,reasoningEffort:this.config.reasoningEffort??this.config.reasoningLevel??"",serviceTier:this.config.serviceTier??"",responseVerbosity:this.config.responseVerbosity??"",temperature:T?.temperature??this.config.temperature??0,maxOutputTokens:T?.maxOutputTokens??this.config.maxOutputTokens??0,customHeaders:this.config.customHeaders??{}},usage:R.usage});if(!I)return R;return gf.warn("[PiAIChatService] Prompt cache break detected",{reason:I.reason,previousCacheReadTokens:I.previousCacheReadTokens,cacheReadTokens:I.cacheReadTokens,tokenDrop:I.tokenDrop,callNumber:I.callNumber}),{...R,usage:{...R.usage,promptCacheBreak:I}}},S=dE({messages:x,context:P,tools:E,requestOptions:T}),t=T?.providerRecovery;if(t&&!R_(t.budgetMs))throw Error("Invalid bounded foreground Provider recovery budget");let A=t?.mode==="bounded_foreground"&&t.budgetMs>0?{budgetMs:t.budgetMs,startedAt:void 0}:void 0,D=A?"bounded_foreground":"standard",Y=this.config.maxRetries??2,z=this.config.maxRetries??(A?t_:2),Q=A!==void 0&&this.config.maxRetries===void 0,K=0,F,Bf=this.config.providerCircuitRegistry??jE(),Af=this.config.providerCircuitBreakerOpenMs??Lf,P_=Math.max(If,Math.min(this.config.streamIdleTimeout??Yf,kf)),nf=this.providerAdmissionScheduler,A_=this.config.providerRequestConcurrency??g,ef=this.config.providerRequestAdmissionMs??Cf,S_=this.config.providerRequestPendingBytes??Ff,bf=T?.providerAdmission??{sessionId:this.admissionFallbackOwnerId,ownerId:this.admissionFallbackOwnerId,requestClass:"internal"},M_=(R,u)=>Bf.get({provider:R.provider,api:R.api,baseUrl:R.baseUrl??u.baseUrl??"",model:R.id,serviceTier:u.serviceTier,apiVersion:u.apiVersion,apiKey:u.apiKey,customHeaders:u.customHeaders,openDurationMs:Af,probeLeaseMs:P_}),N_=(R,u)=>({provider:R.provider,api:R.api,baseUrl:R.baseUrl??u.baseUrl??"",model:R.id,serviceTier:u.serviceTier,apiVersion:u.apiVersion,apiKey:u.apiKey,customHeaders:u.customHeaders,maxConcurrent:A_,maxPendingBytes:S_}),X=(R=Date.now())=>{if(!A)return;let u=A.startedAt===void 0?0:Math.min(A.budgetMs,Math.max(0,R-A.startedAt));return{recoveryBudgetMs:A.budgetMs,recoveryElapsedMs:u,recoveryRemainingMs:Math.max(0,A.budgetMs-u)}},w=()=>({mode:D,...X()??{}}),rf=()=>{if(A&&A.startedAt===void 0)A.startedAt=Date.now()},p=()=>{let R=X();return new n(A?.budgetMs??0,R?.recoveryElapsedMs??0)},e=()=>!Q||K<z+1,Of=(R,u)=>{let{state:V,...B}=u;return{phase:R,...B,...X()?{recoveryRemainingMs:X()?.recoveryRemainingMs}:{}}},fE=(R)=>({phase:"rejected",requestClass:R.requestClass,resource:R.resource,scope:R.scope,reason:R.reason,queuePosition:0,queueDepth:Math.max(0,R.queued),inFlight:Math.max(0,R.inFlight),limit:Math.max(0,R.limit),waitMs:R.reason==="wait_timeout"?R.maxWaitMs:0,maxWaitMs:R.maxWaitMs,...X()?{recoveryRemainingMs:X()?.recoveryRemainingMs}:{}}),u_=async function*(R,u){if(!nf)return{release:()=>{return}};let V=X()?.recoveryRemainingMs,B=V!==void 0&&A?.startedAt!==void 0?Math.min(ef,V):ef,I;try{I=nf.admit({scope:N_(R,u),sessionId:bf.sessionId,ownerId:bf.ownerId,requestClass:bf.requestClass,maxWaitMs:B,pendingBytes:S,signal:_})}catch(b){if(l(b)){if(b.reason==="wait_timeout"&&A?.startedAt!==void 0&&(X()?.recoveryRemainingMs??0)<=0)throw p();yield{providerAdmission:fE(b)}}throw b}let G=I.getSnapshot();if(G.state==="admitted")return await I.ready;yield{providerAdmission:Of("queued",G)};let v=I.ready.then((b)=>({kind:"ready",permit:b}),(b)=>({kind:"error",error:b}));while(!0){let b=I.getSnapshot(),O=Math.max(1,Math.min(oE,Math.max(1,B-b.waitMs))),W,c=new Promise((m)=>{W=setTimeout(()=>m({kind:"heartbeat"}),O),W.unref?.()}),k=await Promise.race([v,c]);if(W)clearTimeout(W);if(k.kind==="heartbeat"){yield{providerAdmission:Of("queued",I.getSnapshot())};continue}if(k.kind==="error"){if(l(k.error)){if(k.error.reason==="wait_timeout"&&A?.startedAt!==void 0&&(X()?.recoveryRemainingMs??0)<=0)throw p();yield{providerAdmission:fE(k.error)}}throw k.error}return yield{providerAdmission:Of("admitted",I.getSnapshot())},k.permit}},D_=(R,u)=>{if(!e())throw p();if(Q)K++;F=void 0;let V=new AbortController,B=_?PE(_,V.signal):V.signal,I=typeof u.timeout==="number"&&Number.isFinite(u.timeout)&&u.timeout>0?Math.max(1,Math.floor(u.timeout)):void 0,G;if(A?.startedAt!==void 0){let O=X()?.recoveryRemainingMs??0;if(O<=0)throw p();G={remainingMs:O,error:new n(A.budgetMs,A.budgetMs)}}let v=iE(u,R,B,T,N);f_(v,R,(O)=>{F=O});let b=h_(this.models,R,P,v,{idleTimeoutMs:u.streamIdleTimeout??Yf,signal:B,abort:(O)=>V.abort(O)});return async function*(){let O,W;try{if(I!==void 0&&(G===void 0||I<G.remainingMs)){let c=new vf(I);O=setTimeout(()=>V.abort(c),I),O.unref?.()}if(G){let c=G;W=setTimeout(()=>V.abort(c.error),c.remainingMs),W.unref?.()}yield*b}finally{if(O)clearTimeout(O);if(W)clearTimeout(W)}}()},EE=this,y=(R)=>({phase:R.phase,reason:R.reason,...R.statusCode!==void 0?{statusCode:R.statusCode}:{},...R.retryAfterMs!==void 0?{retryAfterMs:R.retryAfterMs}:{},...R.nextProbeAt!==void 0?{nextProbeAt:R.nextProbeAt}:{},openDurationMs:R.openDurationMs,sampleCount:R.sampleCount,failureCount:R.failureCount,...X()?{recoveryRemainingMs:X()?.recoveryRemainingMs}:{}}),_E=(R,u)=>({phase:R,reason:u.reason,...u.statusCode!==void 0?{statusCode:u.statusCode}:{},retryAfterMs:u.retryAfterMs,...u.nextProbeAt!==void 0?{nextProbeAt:u.nextProbeAt}:{},openDurationMs:u.openDurationMs,sampleCount:u.sampleCount,failureCount:u.failureCount,...X()?{recoveryRemainingMs:X()?.recoveryRemainingMs}:{}}),I_=(R)=>({phase:"probe",reason:R.reason??"server_error",...R.statusCode!==void 0?{statusCode:R.statusCode}:{},openDurationMs:R.openDurationMs??Af,...R.sampleCount!==void 0?{sampleCount:R.sampleCount}:{},...R.failureCount!==void 0?{failureCount:R.failureCount}:{},...X()?{recoveryRemainingMs:X()?.recoveryRemainingMs}:{}}),Vf=(R,u,V)=>({providerRetry:{phase:"exhausted",attempt:R,maxRetries:z,reason:u,...V!==void 0?{statusCode:V}:{},...w(),exhaustedBy:"recovery_budget"}}),TE=async function*(R,u,V,B,I){let G,v=!1,b,O,W=M_(R,u);for(let c=0;c<=B;c++){if(!e())break;let k,m;while(!k){let H=W.preflight();while(!H.eligible){if(b=H.reason,O=H.statusCode,!A||!I){let C=_E("rejected",H);throw yield{providerCircuit:C},new tf(C)}rf();let j=X()?.recoveryRemainingMs??0;if(j<=0){let C=p();throw yield Vf(Q?Math.max(0,K-1):c,H.reason,H.statusCode),C}yield{providerCircuit:_E("waiting",H)};let q=Math.min(Math.max(1,H.retryAfterMs),yf,j);if(await _f(q,_,{throwOnAbort:!0}),(X()?.recoveryRemainingMs??0)<=0){let C=p();throw yield Vf(Q?Math.max(0,K-1):c,H.reason,H.statusCode),C}H=W.preflight()}try{m=yield*u_(R,u)}catch(Z){if(Z instanceof n)yield Vf(Q?Math.max(0,K-1):c,b??"timeout",O);throw Z}let L=W.check();if(L.allowed)k=L;else m.release(),m=void 0}let i=k.token;if(k.probe)yield{providerCircuit:I_(k)};try{let H=!1,L=!1;for await(let Z of D_(R,u)){if(Z.providerStall){yield Z;continue}let j=Q?K-1:c;if(j>0&&b&&!H)H=!0,yield{providerRetry:{phase:"recovered",attempt:j,maxRetries:z,reason:b,...O!==void 0?{statusCode:O}:{},...w()}};if(!L){L=!0;let q=W.recordSuccess(i);if(q)yield{providerCircuit:y(q)}}v=!0,V(),yield M(Z,R)}if(!L){let Z=W.recordSuccess(i);if(Z)yield{providerCircuit:y(Z)}}return}catch(H){if(m?.release(),G=H,EE.logIdleTimeout(H,v,R),await EE.handleAbort(_),H instanceof n){if(v)throw sf(H),H;throw yield{providerRetry:{phase:"exhausted",attempt:Q?Math.max(0,K-1):c,maxRetries:z,reason:b??"timeout",...O!==void 0?{statusCode:O}:{},...w(),exhaustedBy:"recovery_budget"}},H}let L=o(H,F);if(v)throw sf(H),H;let Z=cT(H,F),j=Z?W.recordFailure(i,Z):F&&!lf(H)?W.recordNeutral(i):void 0;if(j)yield{providerCircuit:y(j)};if(!L.retryable||!L.reason){if(c>0&&b)yield{providerRetry:{phase:"exhausted",attempt:Q?Math.max(0,K-1):c,maxRetries:z,reason:b,...O!==void 0?{statusCode:O}:{},...w()}};throw H}b=L.reason,O=L.statusCode;let q=c<B&&e();if(j&&j.phase!=="closed"&&q&&(!A||!I)){let C={...y(j),phase:"rejected"};throw yield{providerCircuit:C},new tf(C)}if(q){rf();let C=Q?K:c+1,U_=lE(C,F,A?{maxDelayMs:af,maxExponentialDelayMs:af}:void 0),xE=j&&j.phase!=="closed"?j.retryAfterMs??0:0;if(A&&xE>0&&j)yield{providerCircuit:{...y(j),phase:"waiting"}};let Y_=X(),Xf=Math.max(U_,xE),ff=A?Math.min(Xf,Y_?.recoveryRemainingMs??Xf):Xf,Mf={attempt:C,maxRetries:z,reason:L.reason,...L.statusCode!==void 0?{statusCode:L.statusCode}:{}};if(yield{providerRetry:{phase:"scheduled",...Mf,delayMs:ff,nextRetryAt:Date.now()+ff,...w()}},A){let Ef=ff;while(Ef>0){let tE=Math.min(Ef,yf);if(await _f(tE,_,{throwOnAbort:!0}),Ef-=tE,(X()?.recoveryRemainingMs??0)<=0){let Nf=p();throw yield{providerRetry:{phase:"exhausted",...Mf,...w(),exhaustedBy:"recovery_budget"}},Nf}if(Ef>0){if(j&&j.phase!=="closed"&&j.nextProbeAt!==void 0){let Nf=Math.max(0,j.nextProbeAt-Date.now());if(Nf>0)yield{providerCircuit:{...y(j),phase:"waiting",retryAfterMs:Nf}}}yield{providerRetry:{phase:"waiting",...Mf,delayMs:ff,nextRetryAt:Date.now()+Ef,...w()}}}}}else await _f(ff,_,{throwOnAbort:!0});yield{providerRetry:{phase:"attempt",...Mf,...w()}}}else yield{providerRetry:{phase:"exhausted",attempt:Q?Math.max(0,K-1):c,maxRetries:z,reason:L.reason,...L.statusCode!==void 0?{statusCode:L.statusCode}:{},...w(),...A&&(I||!e())?{exhaustedBy:"attempt_limit"}:{}}}}finally{W.abandon(i),m?.release()}}throw G},Sf,hE=!1,jf=this.model,r=this.config.fallbackModels??[],H_=A&&r.length>0?Math.min(Y,z):z;try{for await(let R of TE(this.model,this.config,()=>{hE=!0},H_,r.length===0))yield R;return}catch(R){if(Sf=R,hE||!l(R)&&!Rf(R)&&!lf(R)&&!o(R,F).retryable)throw R}for(let[R,u]of r.entries()){if(!e())break;let V=!1;try{let B=VT(this.config,u),I=UE(B,u);yield{modelFallback:{from:pf(jf.provider,jf.id),to:pf(I.provider,I.id),candidate:R+1,candidateCount:r.length,trigger:yE(Sf,F)}},jf=I;let G=R===r.length-1,v=A&&!G?Math.min(Y,z):z;for await(let b of TE(I,B,()=>{V=!0},v,G))yield b;return}catch(B){if(Sf=B,V||!l(B)&&!Rf(B)&&!lf(B)&&!o(B,F).retryable)throw B}}throw Sf}async handleAbort(f){if(f?.aborted)await _f(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;gf.warn("[PiAIChatService] Provider stream idle timeout",{provider:_.provider,model:_.id,timeoutMs:f.timeoutMs,replayBoundaryCrossed:E})}getConfig(){return{...this.config}}updateConfig(f){let E={...this.config,...f},_=Wf(E);this.config={...E,maxContextTokens:_.model.contextWindow,maxOutputTokens:E.maxOutputTokens??_.model.maxTokens},this.models=_.models,this.model=_.model,this.providerAdmissionScheduler=x_(this.config)}}function x_(f){if(f.providerRequestAdmissionScheduler)return f.providerRequestAdmissionScheduler;if(f.providerRequestConcurrency===void 0&&f.providerGlobalConcurrency===void 0&&f.providerOwnerConcurrency===void 0)return;let E=f.providerGlobalConcurrency??Number.MAX_SAFE_INTEGER,_=f.providerOwnerConcurrency??Number.MAX_SAFE_INTEGER;return mE({globalMaxInFlight:E,ownerMaxInFlight:_,nonForegroundGlobalMaxInFlight:E,nonForegroundOwnerMaxInFlight:_,internalGlobalMaxInFlight:E,internalDomainMaxInFlight:f.providerRequestConcurrency??g,classLimitsEnabled:!1})}var JT=a("Service");async function mh(f){let E=f;if(E.provider){let _=RE(E.provider);if(Object.keys(_).length>0)E={...E,customHeaders:{..._,...E.customHeaders}},JT.debug(`Injected ${E.provider} specific headers:`,Object.keys(_))}return WT(E)}function WT(f){return new df(f)}
5
- export{LT as dg,ZT as eg,PE as fg,_f as gg,l as hg,xT as ig,Rh as jg,o as kg,lE as lg,aE as mg,df as ng,mh as og};
@@ -1,10 +0,0 @@
1
- import{a as T,b as W,c as X,d as Y}from"./chunk-6s037nx9.js";import"./chunk-e07acz8d.js";import"./chunk-pv6cgfv1.js";import"./chunk-2ffyr4zh.js";import"./chunk-4c13mnh8.js";import"./chunk-kr5w8q8v.js";import"./chunk-gmmhpp0k.js";import"./chunk-zrgfvc4k.js";import"./chunk-4n0efk4n.js";import"./chunk-ht8epjz2.js";import"./chunk-a5r7c1n4.js";import"./chunk-wm896gnx.js";import"./chunk-hj1c3k0m.js";import"./chunk-9xbwtjac.js";import"./chunk-vz13c7fr.js";import"./chunk-fx9vm1n5.js";import{xf as R}from"./chunk-70hjk2jn.js";import"./chunk-v1mamd1x.js";import{Tf as Q}from"./chunk-xgyx1hwx.js";import"./chunk-v508x7cg.js";import"./chunk-7xhw74hk.js";import"./chunk-k1tfry97.js";import"./chunk-f2y0gxyq.js";import"./chunk-k3ne93k8.js";import"./chunk-7wcxjbyg.js";import"./chunk-erext256.js";import"./chunk-yh34b6z0.js";import"./chunk-ewwrss2w.js";import"./chunk-53vh6vpt.js";import"./chunk-hv8nt7wj.js";import"./chunk-erhaedch.js";import"./chunk-g7pwwxvz.js";import"./chunk-28tzj187.js";import"./chunk-5xnht5vw.js";import"./chunk-sd9bze9x.js";import"./chunk-514va7ce.js";import"./chunk-jsv3e4k6.js";import"./chunk-n34qsnks.js";import"./chunk-5q4z0sfr.js";import"./chunk-0b67y4j1.js";import"./chunk-9kj19a8t.js";import{Wj as M}from"./chunk-fhsvz4b1.js";import"./chunk-gm2yfq3r.js";import"./chunk-n9819k4p.js";import"./chunk-7xtxvrh8.js";import"./chunk-sdapqhj0.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{Vj as a,Wj as b,Xj as c,Yj as d,Zj as e,_j as f}from"./chunk-fhsvz4b1.js";import"./chunk-sdapqhj0.js";export{b as getVersion,c as getPackageName,a as getPackageInfo,e as getFormattedVersion,d as getDescription,f as getCopyright};
@@ -1 +0,0 @@
1
- import{ae as a,be as b,ce as c,de as d,ee as e,fe as f,ge as g}from"./chunk-hj1c3k0m.js";import"./chunk-9xbwtjac.js";import"./chunk-vz13c7fr.js";import"./chunk-fx9vm1n5.js";import"./chunk-7wcxjbyg.js";import"./chunk-hv8nt7wj.js";import"./chunk-28tzj187.js";import"./chunk-514va7ce.js";import"./chunk-jsv3e4k6.js";import"./chunk-5q4z0sfr.js";import"./chunk-9kj19a8t.js";import"./chunk-fhsvz4b1.js";import"./chunk-7xtxvrh8.js";import"./chunk-sdapqhj0.js";export{b as __setSessionSnapshotIOForTesting,c as __resetSessionSnapshotIOForTesting,g as SessionService,d as SessionMissingCreationError,e as SessionArchivedError,f as SessionArchiveConflictError,a as STALE_EMPTY_SESSION_AGE_MS};
@@ -1 +0,0 @@
1
- import{$g as k,Rg as a,Sg as b,Tg as c,Ug as d,Vg as e,Wg as f,Xg as g,Yg as h,Zg as i,_g as j}from"./chunk-yh34b6z0.js";import"./chunk-ewwrss2w.js";import"./chunk-53vh6vpt.js";import"./chunk-hv8nt7wj.js";import"./chunk-erhaedch.js";import"./chunk-g7pwwxvz.js";import"./chunk-28tzj187.js";import"./chunk-5xnht5vw.js";import"./chunk-sd9bze9x.js";import"./chunk-514va7ce.js";import"./chunk-jsv3e4k6.js";import"./chunk-n34qsnks.js";import"./chunk-5q4z0sfr.js";import"./chunk-0b67y4j1.js";import"./chunk-9kj19a8t.js";import"./chunk-fhsvz4b1.js";import"./chunk-gm2yfq3r.js";import"./chunk-n9819k4p.js";import"./chunk-7xtxvrh8.js";import"./chunk-sdapqhj0.js";export{g as withWorkspaceAgentResources,i as snapshotWorkspaceAgentResources,f as resolveWorkspaceAgentResources,k as resetWorkspaceAgentResources,d as refreshWorkspaceCommunicationStyles,h as getWorkspaceAgentResourceCacheStats,j as createEmptySessionAgentResources,e as configureInvocationPluginDirs,c as WorkspaceAgentResourceCapacityError,a as MAX_RESIDENT_WORKSPACE_AGENT_RESOURCES,b as MAX_ACTIVE_WORKSPACE_AGENT_RESOURCES};
@@ -1 +0,0 @@
1
- import{$b as i,Pb as a,Qb as b,Sb as c,Wb as d,Xb as e,Yb as f,Zb as g,_b as h,ac as j,bc as k,jc as l,kc as m,lc as n,mc as o,oc as p,pc as q,qc as r}from"./chunk-a5r7c1n4.js";import"./chunk-wm896gnx.js";import"./chunk-hj1c3k0m.js";import"./chunk-9xbwtjac.js";import"./chunk-vz13c7fr.js";import"./chunk-fx9vm1n5.js";import"./chunk-7xhw74hk.js";import"./chunk-k1tfry97.js";import"./chunk-f2y0gxyq.js";import"./chunk-7wcxjbyg.js";import"./chunk-ewwrss2w.js";import"./chunk-53vh6vpt.js";import"./chunk-hv8nt7wj.js";import"./chunk-g7pwwxvz.js";import"./chunk-28tzj187.js";import"./chunk-sd9bze9x.js";import"./chunk-514va7ce.js";import"./chunk-jsv3e4k6.js";import"./chunk-n34qsnks.js";import"./chunk-5q4z0sfr.js";import"./chunk-0b67y4j1.js";import"./chunk-9kj19a8t.js";import"./chunk-fhsvz4b1.js";import"./chunk-n9819k4p.js";import"./chunk-7xtxvrh8.js";import"./chunk-sdapqhj0.js";export{g as saveUserMessage,i as saveToolUse,j as saveToolResult,k as saveCompaction,h as saveAssistantMessage,d as isRootSystemPrompt,m as handleTaskListUpdate,n as handleSkillActivation,o as extractModelSwitch,r as executeLoopGenerator,f as drainLoop,c as checkStopHook,a as checkOutputRecovery,b as checkIncompleteIntent,q as checkAndCompactInLoop,p as applyToolDomainEffects,l as StreamingToolExecutor,e as ConversationState};
@@ -1 +0,0 @@
1
- import{rg as a,sg as b,tg as c}from"./chunk-k3ne93k8.js";import"./chunk-7wcxjbyg.js";import"./chunk-0b67y4j1.js";import"./chunk-9kj19a8t.js";import"./chunk-7xtxvrh8.js";import"./chunk-sdapqhj0.js";export{b as resolveModelConfig,c as getModelDisplayName,a as getModelApiKeyEnvironmentVariable};
@@ -1 +0,0 @@
1
- import{a,b as i,c as l,d as m}from"./chunk-6s037nx9.js";import"./chunk-e07acz8d.js";import"./chunk-pv6cgfv1.js";import"./chunk-2ffyr4zh.js";import"./chunk-4c13mnh8.js";import"./chunk-kr5w8q8v.js";import"./chunk-gmmhpp0k.js";import"./chunk-zrgfvc4k.js";import"./chunk-4n0efk4n.js";import"./chunk-ht8epjz2.js";import"./chunk-a5r7c1n4.js";import"./chunk-wm896gnx.js";import"./chunk-hj1c3k0m.js";import"./chunk-9xbwtjac.js";import"./chunk-vz13c7fr.js";import"./chunk-fx9vm1n5.js";import{xf as n}from"./chunk-70hjk2jn.js";import"./chunk-v1mamd1x.js";import{Tf as s}from"./chunk-xgyx1hwx.js";import"./chunk-v508x7cg.js";import"./chunk-7xhw74hk.js";import"./chunk-k1tfry97.js";import"./chunk-f2y0gxyq.js";import"./chunk-k3ne93k8.js";import"./chunk-7wcxjbyg.js";import"./chunk-erext256.js";import"./chunk-yh34b6z0.js";import"./chunk-ewwrss2w.js";import"./chunk-53vh6vpt.js";import"./chunk-hv8nt7wj.js";import"./chunk-erhaedch.js";import"./chunk-g7pwwxvz.js";import"./chunk-28tzj187.js";import"./chunk-5xnht5vw.js";import"./chunk-sd9bze9x.js";import"./chunk-514va7ce.js";import"./chunk-jsv3e4k6.js";import"./chunk-n34qsnks.js";import"./chunk-5q4z0sfr.js";import"./chunk-0b67y4j1.js";import"./chunk-9kj19a8t.js";import"./chunk-fhsvz4b1.js";import"./chunk-gm2yfq3r.js";import"./chunk-n9819k4p.js";import"./chunk-7xtxvrh8.js";import"./chunk-sdapqhj0.js";import v from"chalk";var C={command:"serve",describe:"Start a headless Blade server (no browser)",builder:a,handler:async(p)=>{let r=i(p);if(await s(),!process.env.BLADE_SERVER_PASSWORD)console.log(v.yellow("Warning: BLADE_SERVER_PASSWORD is not set; server is unsecured."));let e=await m.listenAsync(r);if(console.log(`Blade server listening on http://${e.hostname}:${e.port}`),r.hostname==="0.0.0.0"){let o=l();for(let g of o)console.log(` Network: http://${g}:${e.port}`)}let t,c=new Promise((o)=>{t=o}),d=n(async()=>{await e.stop(),t()});try{await c}finally{d(),await e.stop()}}};export{C as serveCommand};
@@ -1,63 +0,0 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/MarkdownRenderer-CXDrI3kX.js","assets/index-pqMcowCZ.js","assets/vendor-react-DofNRwfy.js","assets/vendor-radix-D6QrtXqd.js","assets/session-events-Dwyp0AVI.js","assets/index-RGoMvYl5.css","assets/copy-o_KiXkAh.js"])))=>i.map(i=>d[i]);
2
- import{r as h,j as e}from"./vendor-react-DofNRwfy.js";import{c as X,u as B,a as f,s as ze,b as mt,d as de,H as $e,P as ht,G as qe,L as _,S as Ge,T as ne,C as ge,D as We,e as Je,f as xt,g as Ye,h as Xe,i as Ze,j as D,k as pt,l as ae,B as ft,m as Ce,n as me,R as fe,F as bt,_ as et,o as vt,p as tt,q as gt,r as st,t as kt,X as at,v as yt,A as Ae,w as jt,x as wt,W as Nt,y as St,z as Ct}from"./index-pqMcowCZ.js";import{_ as Re,M as ie,Z as K,a2 as Tt,A as Et,a3 as Mt,a4 as At,Q as Rt,X as Ft,Y as Dt}from"./session-events-Dwyp0AVI.js";import{A as It,E as $t}from"./external-link-smSBd9oE.js";import{S as _t}from"./ScrollArea-DocDa_rN.js";import{C as rt}from"./copy-o_KiXkAh.js";import{C as oe}from"./chevron-right-CgHjrrmB.js";import{A as Fe,a as Bt,C as Pt}from"./chevrons-up-down-zQ_UZWV9.js";import{f as Lt,g as Ut,h as Ot,i as nt}from"./vendor-radix-D6QrtXqd.js";import{P as Kt}from"./pause-yqaK1hvk.js";import{P as Vt}from"./play-WQ7288Ky.js";import{P as it}from"./pencil-BZbDnyg2.js";import{C as Ht}from"./clock-3-BB58ITKo.js";import{t as U,A as _e}from"./team-BrF46S7E.js";import{teamService as Be}from"./teamService-fDnXqw4L.js";/**
3
- * @license lucide-react v0.300.0 - ISC
4
- *
5
- * This source code is licensed under the ISC license.
6
- * See the LICENSE file in the root directory of this source tree.
7
- */const Qt=X("Files",[["path",{d:"M15.5 2H8.6c-.4 0-.8.2-1.1.5-.3.3-.5.7-.5 1.1v12.8c0 .4.2.8.5 1.1.3.3.7.5 1.1.5h9.8c.4 0 .8-.2 1.1-.5.3-.3.5-.7.5-1.1V6.5L15.5 2z",key:"cennsq"}],["path",{d:"M3 7.6v12.8c0 .4.2.8.5 1.1.3.3.7.5 1.1.5h9.8",key:"ms809a"}],["path",{d:"M15 2v5h5",key:"qq6kwv"}]]);/**
8
- * @license lucide-react v0.300.0 - ISC
9
- *
10
- * This source code is licensed under the ISC license.
11
- * See the LICENSE file in the root directory of this source tree.
12
- */const zt=X("Gauge",[["path",{d:"m12 14 4-4",key:"9kzdfg"}],["path",{d:"M3.34 19a10 10 0 1 1 17.32 0",key:"19p75a"}]]);/**
13
- * @license lucide-react v0.300.0 - ISC
14
- *
15
- * This source code is licensed under the ISC license.
16
- * See the LICENSE file in the root directory of this source tree.
17
- */const qt=X("HelpCircle",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3",key:"1u773s"}],["path",{d:"M12 17h.01",key:"p32p05"}]]);/**
18
- * @license lucide-react v0.300.0 - ISC
19
- *
20
- * This source code is licensed under the ISC license.
21
- * See the LICENSE file in the root directory of this source tree.
22
- */const Gt=X("ListOrdered",[["line",{x1:"10",x2:"21",y1:"6",y2:"6",key:"76qw6h"}],["line",{x1:"10",x2:"21",y1:"12",y2:"12",key:"16nom4"}],["line",{x1:"10",x2:"21",y1:"18",y2:"18",key:"u3jurt"}],["path",{d:"M4 6h1v4",key:"cnovpq"}],["path",{d:"M4 10h2",key:"16xx2s"}],["path",{d:"M6 18H4c0-1 2-2 2-3s-1-1.5-2-1",key:"m9a95d"}]]);/**
23
- * @license lucide-react v0.300.0 - ISC
24
- *
25
- * This source code is licensed under the ISC license.
26
- * See the LICENSE file in the root directory of this source tree.
27
- */const Wt=X("LockKeyhole",[["circle",{cx:"12",cy:"16",r:"1",key:"1au0dj"}],["rect",{x:"3",y:"10",width:"18",height:"12",rx:"2",key:"6s8ecr"}],["path",{d:"M7 10V7a5 5 0 0 1 10 0v3",key:"1pqi11"}]]);/**
28
- * @license lucide-react v0.300.0 - ISC
29
- *
30
- * This source code is licensed under the ISC license.
31
- * See the LICENSE file in the root directory of this source tree.
32
- */const Jt=X("MessageCircleQuestion",[["path",{d:"M7.9 20A9 9 0 1 0 4 16.1L2 22Z",key:"vv11sd"}],["path",{d:"M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3",key:"1u773s"}],["path",{d:"M12 17h.01",key:"p32p05"}]]);/**
33
- * @license lucide-react v0.300.0 - ISC
34
- *
35
- * This source code is licensed under the ISC license.
36
- * See the LICENSE file in the root directory of this source tree.
37
- */const Yt=X("Target",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["circle",{cx:"12",cy:"12",r:"6",key:"1vlfrh"}],["circle",{cx:"12",cy:"12",r:"2",key:"1c9p78"}]]);/**
38
- * @license lucide-react v0.300.0 - ISC
39
- *
40
- * This source code is licensed under the ISC license.
41
- * See the LICENSE file in the root directory of this source tree.
42
- */const Xt=X("Timer",[["line",{x1:"10",x2:"14",y1:"2",y2:"2",key:"14vaq8"}],["line",{x1:"12",x2:"15",y1:"14",y2:"11",key:"17fdiu"}],["circle",{cx:"12",cy:"14",r:"8",key:"1e1u0o"}]]);/**
43
- * @license lucide-react v0.300.0 - ISC
44
- *
45
- * This source code is licensed under the ISC license.
46
- * See the LICENSE file in the root directory of this source tree.
47
- */const Zt=X("Users",[["path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2",key:"1yyitq"}],["circle",{cx:"9",cy:"7",r:"4",key:"nufk8"}],["path",{d:"M22 21v-2a4 4 0 0 0-3-3.87",key:"kshegd"}],["path",{d:"M16 3.13a4 4 0 0 1 0 7.75",key:"1da9ce"}]]);function Pe(t){return t.split("/").filter(Boolean).at(-1)||t}function es(){const t=B(),a=f(j=>j.sessions),s=f(j=>j.currentSessionRef),r=f(j=>j.historySurfaceSelection),o=f(j=>j.taskDeliveryActions),i=f(j=>j.deliverTask),l=Re(j=>j.openFilePreview),[u,x]=h.useState(!1),c=a.find(j=>ze({sessionId:j.sessionId,projectPath:j.projectPath},s));if(ie(r)||!(c!=null&&c.taskIsolation))return null;const v=c.taskDiffStat,b=c.taskIsolation==="worktree",d=mt(c),y=o[de(d)],p=c.taskDelivery,N=(p==null?void 0:p.status)==="conflicted",m=!!(v&&(v.changedFiles>0||v.commits>0)),S=!["queued","running"].includes(c.taskStatus),k=(p==null?void 0:p.status)==="applied"||(p==null?void 0:p.status)==="discarded",w=b&&m&&S&&!k,n=v?v.additions+v.deletions:0,E=n>0&&v?v.additions/n*100:0,F=j=>{K(f.getState())||i(d,j).catch(()=>{})},R=()=>{K(f.getState())||l({tab:"diff"})};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($e,{className:"h-3 w-3 shrink-0 text-[hsl(var(--deck-ink-faint))]"}),e.jsx("span",{className:"truncate text-[hsl(var(--deck-ink))]",children:Pe(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:[b?e.jsx(ht,{className:"h-3 w-3 shrink-0 text-[hsl(var(--deck-accent))]"}):e.jsx($e,{className:"h-3 w-3 shrink-0"}),e.jsx("span",{className:b?"text-[hsl(var(--deck-accent))]":void 0,children:t(b?"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(qe,{className:"h-3 w-3 shrink-0 text-[hsl(var(--deck-ink-faint))]"}),e.jsx("span",{className:"truncate",children:c.taskWorktreeBranch})]})]})]}),v&&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(Qt,{className:"h-3 w-3 text-[hsl(var(--deck-ink-faint))]"}),e.jsx("span",{className:"tabular-nums",children:v.changedFiles})]}),n>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:`${E}%`}}),e.jsx("span",{className:"h-full bg-red-500/80",style:{width:`${100-E}%`}})]}),e.jsxs("span",{className:"tabular-nums text-[hsl(var(--deck-accent))]",children:["+",v.additions]}),e.jsxs("span",{className:"tabular-nums text-red-600 dark:text-red-400",children:["-",v.deletions]}),v.commits>0&&e.jsx("span",{className:"hidden tabular-nums text-[hsl(var(--deck-ink-faint))] sm:inline",children:t("artifact.commits",{count:v.commits})}),m&&(p==null?void 0:p.status)!=="discarded"&&e.jsx("button",{type:"button",onClick:R,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")}),w&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{type:"button",disabled:!!y,onClick:()=>F("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:[y==="apply"?e.jsx(_,{className:"h-3 w-3 animate-spin"}):e.jsx(Ge,{className:"h-3 w-3"}),t(y==="apply"?"artifact.applying":N?"artifact.retryApply":"artifact.apply")]}),e.jsx("button",{type:"button",disabled:!!y,onClick:()=>x(!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:y==="discard"?e.jsx(_,{className:"h-3 w-3 animate-spin"}):e.jsx(ne,{className:"h-3 w-3"})})]}),(p==null?void 0:p.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(ge,{className:"h-3 w-3"}),t("artifact.applied")]}),(p==null?void 0:p.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(ne,{className:"h-3 w-3"}),t("artifact.discarded")]})]}),(p==null?void 0:p.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(It,{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:p.message||t("artifact.conflict")}),e.jsx("span",{className:"block text-[hsl(var(--deck-ink-faint))]",children:t("artifact.conflictHint")})]})]})]}),e.jsx(We,{open:u,onOpenChange:x,children:e.jsxs(Je,{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(xt,{children:[e.jsx(Ye,{children:t("artifact.discardDialog.title")}),e.jsx(Xe,{className:"text-[hsl(var(--deck-ink-muted))]",children:t("artifact.discardDialog.description",{project:Pe(c.taskSourceProjectPath||c.projectPath),count:(v==null?void 0:v.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(Ze,{className:"gap-2 sm:space-x-0",children:[e.jsx("button",{type:"button",onClick:()=>x(!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:()=>{x(!1),F("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(ne,{className:"h-3.5 w-3.5"}),t("artifact.discardDialog.confirm")]})]})]})})]})}const ts=new Set(["completed","stale","failed","aborted","interrupted"]),ss={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"},as={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 be(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:void 0}function rs(t){const a=be(t),s=be(a==null?void 0:a.codeLocation),r=a==null?void 0:a.priority,o=a==null?void 0:a.confidenceScore,i=s==null?void 0:s.lineStart,l=s==null?void 0:s.lineEnd;if(!(typeof(a==null?void 0:a.title)!="string"||typeof a.body!="string"||r!==0&&r!==1&&r!==2&&r!==3||typeof o!="number"||!Number.isFinite(o)||typeof(s==null?void 0:s.path)!="string"||!Number.isInteger(i)||!Number.isInteger(l)))return{title:a.title,body:a.body,priority:r,confidenceScore:o,codeLocation:{path:s.path,lineStart:i,lineEnd:l}}}function ns(t){const a=be(t),s=be(a==null?void 0:a.target);if((a==null?void 0:a.phase)!=="completed"||typeof a.status!="string"||!ts.has(a.status)||typeof(s==null?void 0:s.label)!="string"||s.kind!=="uncommitted"&&s.kind!=="base"&&s.kind!=="commit"||typeof a.overallExplanation!="string"||!Array.isArray(a.findings))return;const r=a.findings.map(rs);if(!r.some(o=>o===void 0))return{status:a.status,target:{kind:s.kind,label:s.label,...typeof s.reference=="string"?{reference:s.reference}:{}},overallExplanation:a.overallExplanation,findings:r,...typeof a.error=="string"?{error:a.error}:{}}}function is(t){const{path:a,lineStart:s,lineEnd:r}=t.codeLocation;return s===r?`${a}:L${s}`:`${a}:L${s}-${r}`}function os({report:t}){const a=B(),s=t.target.kind==="uncommitted"?a("chat.review.target.uncommitted"):t.target.kind==="base"?a("chat.review.target.base",{ref:t.target.reference??t.target.label}):a("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:a("chat.review.title")}),e.jsxs("p",{className:"mt-0.5 font-mono text-[10.5px] text-[hsl(var(--deck-ink-faint))]",children:[a("chat.review.target"),": ",s]})]}),e.jsxs("span",{className:D("rounded-full border px-2.5 py-1 font-mono text-[10.5px] font-medium",as[t.status]),children:[a("chat.review.status"),": ",a(ss[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:a("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:a("chat.review.noFindings")}):e.jsx("ol",{className:"space-y-2",children:t.findings.map((r,o)=>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:a("chat.review.confidence",{value:r.confidenceScore.toFixed(2)})})]}),e.jsx("code",{className:"mt-1 block text-[10.5px] text-[hsl(var(--deck-accent))]",children:is(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}:${o}`))})]}),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:[a("chat.review.error"),":"]})," ",t.error]})]})]})}function cs({elicitation:t,messageId:a}){const s=B(),r=f(k=>k.currentSessionRef),o=f(k=>k.setElicitation),[i,l]=h.useState(()=>ds(t.details.fields??[])),[u,x]=h.useState(()=>us(t.details.fields??[])),[c,v]=h.useState(!1),[b,d]=h.useState(),y=t.details.fields??[],p=h.useMemo(()=>y.every(k=>{var n;if(!k.required)return!0;if(ke(k))return!!((n=u[k.name])!=null&&n.trim()||k.defaultValue!==void 0);const w=i[k.name]??k.defaultValue;return Array.isArray(w)?w.length>0:w!==void 0}),[y,u,i]);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:s(t.status==="cancelled"?"interaction.elicitation.cancelled":"interaction.elicitation.responded")});const N=async(k,w)=>{if(!K(f.getState())&&!(!r||c)){v(!0),d(void 0);try{await ae.respondToElicitation(r,t.toolCallId,{action:k,...w?{content:w}:{}}),o(a,{...t,status:"responded"})}catch(n){d(n instanceof Error?n.message:s("interaction.elicitation.failed"))}finally{v(!1)}}},m=async()=>{try{await N("accept",ms(y,i,u))}catch(k){d(k instanceof Error?k.message:String(k))}},S=()=>{if(K(f.getState()))return;const k=t.details.url;if(!k){d("MCP URL is unavailable");return}if(!window.open(k,"_blank","noopener,noreferrer")){d("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(pt,{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:[s("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:s("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(re,{onClick:S,disabled:c,primary:!0,label:s("interaction.elicitation.open"),icon:e.jsx($t,{className:"h-3.5 w-3.5"})}),e.jsx(re,{onClick:()=>void N("decline"),disabled:c,label:s("interaction.elicitation.decline")}),e.jsx(re,{onClick:()=>void N("cancel"),disabled:c,label:s("interaction.elicitation.cancel")})]})]}):e.jsxs("div",{className:"space-y-4",children:[y.map(k=>e.jsx(ls,{field:k,value:i[k.name],rawValue:u[k.name]??"",onValueChange:w=>l(n=>({...n,[k.name]:w})),onRawChange:w=>x(n=>({...n,[k.name]:w}))},k.name)),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(re,{onClick:()=>void m(),disabled:c||!p,primary:!0,label:s("interaction.elicitation.submit"),icon:c?e.jsx(_,{className:"h-3.5 w-3.5 animate-spin"}):null}),e.jsx(re,{onClick:()=>void N("decline"),disabled:c,label:s("interaction.elicitation.decline")}),e.jsx(re,{onClick:()=>void N("cancel"),disabled:c,label:s("interaction.elicitation.cancel")})]})]}),b&&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:b})]})}function ls({field:t,value:a,rawValue:s,onValueChange:r,onRawChange:o}){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:hs(t).map(i=>{const l=Array.isArray(a)?a.includes(i.value):a===i.typedValue;return e.jsx("button",{type:"button","aria-pressed":l,onClick:()=>{if(t.type==="multi-select"){const u=Array.isArray(a)?a:[];r(u.includes(i.value)?u.filter(x=>x!==i.value):[...u,i.value])}else r(i.typedValue)},className:D("rounded-md border px-3 py-2 font-mono text-[12px] transition-colors",l?"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:i.label},i.value)})}):e.jsx("input",{id:`mcp-elicitation-${t.name}`,type:xs(t),value:s,onChange:i=>o(i.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 re({onClick:t,disabled:a,primary:s=!1,label:r,icon:o}){return e.jsxs("button",{type:"button",onClick:t,disabled:a,className:D("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",s?"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:[o,r]})}function ds(t){return Object.fromEntries(t.filter(a=>!ke(a)&&a.defaultValue!==void 0).map(a=>[a.name,Array.isArray(a.defaultValue)?[...a.defaultValue]:a.defaultValue]))}function us(t){return Object.fromEntries(t.filter(a=>ke(a)&&a.defaultValue!==void 0).map(a=>[a.name,String(a.defaultValue)]))}function ms(t,a,s){var o;const r={};for(const i of t){if(ke(i)){const u=((o=s[i.name])==null?void 0:o.trim())??"";if(!u){if(i.defaultValue!==void 0)r[i.name]=i.defaultValue;else if(i.required)throw new Error(`${i.title} is required`);continue}if(i.type==="number"||i.type==="integer"){const x=Number(u);if(!Number.isFinite(x))throw new Error(`${i.title} must be a finite number`);if(i.type==="integer"&&!Number.isSafeInteger(x))throw new Error(`${i.title} must be a safe integer`);r[i.name]=x}else r[i.name]=u;continue}const l=a[i.name]??i.defaultValue;if(l===void 0){if(i.required)throw new Error(`${i.title} is required`);continue}if(Array.isArray(l)){if(i.minItems!==void 0&&l.length<i.minItems)throw new Error(`${i.title} requires at least ${i.minItems} choices`);if(i.maxItems!==void 0&&l.length>i.maxItems)throw new Error(`${i.title} allows at most ${i.maxItems} choices`)}r[i.name]=l}return r}function hs(t){return t.type==="boolean"?[{value:"true",label:"Yes",typedValue:!0},{value:"false",label:"No",typedValue:!1}]:(t.options??[]).map(a=>({...a,typedValue:a.value}))}function ke(t){return t.type==="string"||t.type==="number"||t.type==="integer"}function xs(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 ps(t){if(!t||typeof t!="object"||Array.isArray(t))return;const a=t;if(!(!a.output||typeof a.output!="object"||Array.isArray(a.output)))return{output:a.output,...typeof a.schemaDigest=="string"?{schemaDigest:a.schemaDigest}:{}}}function fs({report:t}){const a=B(),[s,r]=h.useState(!1),o=JSON.stringify(t.output,null,2),i=async()=>{try{await navigator.clipboard.writeText(o),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(ft,{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:a("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:i,"aria-label":a("chat.structuredOutput.copy"),title:a("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:s?e.jsx(ge,{className:"h-3.5 w-3.5 text-[hsl(var(--deck-accent))]"}):e.jsx(rt,{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:o})]})}const bs=h.lazy(()=>et(()=>import("./MarkdownRenderer-CXDrI3kX.js").then(t=>t.M),__vite__mapDeps([0,1,2,3,4,5,6])).then(t=>({default:t.MarkdownRenderer})));function Le({text:t,label:a}){const[s,r]=h.useState(!1);if(!t.trim())return null;const o=async()=>{try{await navigator.clipboard.writeText(t),r(!0),window.setTimeout(()=>r(!1),1400)}catch{}};return e.jsx("button",{type:"button","aria-label":a,title:a,onClick:o,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:s?e.jsx(ge,{className:"h-3.5 w-3.5 text-[hsl(var(--deck-accent))]"}):e.jsx(rt,{className:"h-3.5 w-3.5"})})}function vs(){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(Ce,{size:20,pulse:!1})})}function gs(){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 Ue(t){let a=t;return a=a.replace(/<system-reminder>[\s\S]*?<\/system-reminder>/g,""),a=a.replace(/<file path="[^"]*">[\s\S]*?<\/file>/g,""),a=a.replace(/<attached_files>[\s\S]*?<\/attached_files>/g,""),a=a.trim(),a}function ks(t){if(typeof t=="string")return{text:Ue(t),images:[]};const a=t.filter(r=>r.type==="text").map(r=>r.text).join(`
48
- `),s=t.filter(r=>r.type==="image_url").map(r=>r.image_url.url);return{text:Ue(a),images:s}}function De(t){return typeof t=="string"?t:t.filter(a=>a.type==="text").map(a=>a.text).join(`
49
- `)}function ys(t){const a=t.agentContent;return a?Tt(a):De(t.content)}function Oe({content:t,syntaxHighlight:a=!0}){return e.jsx(h.Suspense,{fallback:e.jsx("pre",{className:"text-[14px] text-[hsl(var(--deck-ink))] font-mono whitespace-pre-wrap",children:t}),children:e.jsx(bs,{content:t,syntaxHighlight:a})})}function Ie({status:t}){if(!t)return null;const a={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]"},s={running:"Running",success:"Success",error:"Error",pending:"Pending",info:"Info"};return e.jsx("span",{className:D("text-[11px] px-2 py-0.5 rounded-full font-mono",a[t]),children:s[t]})}function js(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 Ke=500;function ot(t,a){if(t.length<=a)return t;let s=Math.max(0,a);return s>0&&/[\uD800-\uDBFF]/.test(t.charAt(s-1))&&(s-=1),t.slice(0,s)}function Ve(t,a){if(t.length<=a)return t;let s=Math.max(0,t.length-a);return/[\uDC00-\uDFFF]/.test(t.charAt(s))&&(s+=1),t.slice(s)}function je(t,a){if(t.length<=a)return t;if(a<=0)return"";const s=`
50
- ... (display clipped) ...
51
- `,r=a-s.length;if(r<=0)return Ve(t,a);const o=Math.floor(r/3);return`${ot(t,o)}${s}${Ve(t,r-o)}`}function ws(t){const a=t.split(`
52
- `),s=a.at(-1),r=s!=null&&s.startsWith("Output truncated")?s:void 0,o=r?a.slice(0,-1).join(`
53
- `):t,i=r?`
54
- ${r}`:"",l=Math.max(0,Ke-i.length),x=o.indexOf(`
55
- stderr:
56
- `);let c;if(x>=0&&o.includes(`
57
- stdout:
58
- `)){const v=o.slice(0,x),b=o.slice(x+1),d=Math.max(0,l-1),y=Math.floor(d/2);c=`${je(v,y)}
59
- ${je(b,d-y)}`}else c=je(o,l);return{body:ot(c,l),...r?{notice:r}:{},truncated:!!r||t.length>Ke}}function Ns({tool:t}){const[a,s]=h.useState(!1),r=js(t.arguments),o=t.output?ws(t.output):void 0;return e.jsxs("div",{"data-tool-name":t.toolName,"data-tool-status":t.status,"data-tool-truncated":o!=null&&o.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":a,"data-tool-call-id":t.toolCallId,onClick:()=>s(i=>!i),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:[a?e.jsx(me,{className:"h-4 w-4 text-[hsl(var(--deck-ink-faint))] shrink-0"}):e.jsx(oe,{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(Ie,{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))}%`}})})]}),a&&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})]}),o&&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:[o.body,o.notice&&e.jsxs(e.Fragment,{children:[`
60
- `,e.jsx("span",{"data-tool-truncation-notice":!0,children:o.notice})]})]})]})]})]})}function ct({toolCalls:t}){return t.length===0?null:e.jsx("div",{className:"space-y-2",children:t.map(a=>e.jsx(Ns,{tool:a},a.toolCallId))})}function Ss({toolCalls:t,toolCallIds:a}){const s=B(),[r,o]=h.useState(!1),i=h.useMemo(()=>new Map(t.map(b=>[b.toolCallId,b])),[t]),l=a.flatMap(b=>{const d=i.get(b);return d?[d]:[]});if(l.length===0)return null;const u=l.filter(b=>b.status==="running").length,x=l.filter(b=>b.status==="error").length,c=[...l].reverse().find(b=>b.status==="running"&&!!b.progressMessage),v=u>0?s(l.length===1?"chat.timeline.tools.runningOne":"chat.timeline.tools.running",{count:l.length}):x>0?s(l.length===1?"chat.timeline.tools.completedOneWithError":"chat.timeline.tools.completedWithErrors",{count:l.length,errors:x}):s(l.length===1?"chat.timeline.tools.completedOne":"chat.timeline.tools.completed",{count:l.length});return e.jsxs("div",{"data-agent-tool-group":!0,className:"py-0.5",children:[e.jsxs("button",{type:"button","aria-expanded":r,onClick:()=>o(b=>!b),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(me,{className:"h-3.5 w-3.5 shrink-0"}):e.jsx(oe,{className:"h-3.5 w-3.5 shrink-0"}),u>0&&e.jsx(_,{className:"h-3 w-3 shrink-0 animate-spin text-[hsl(var(--deck-accent))]"}),e.jsx("span",{children:v}),(c==null?void 0:c.progressMessage)&&e.jsxs("span",{className:"min-w-0 truncate text-[10.5px] text-[hsl(var(--deck-ink-muted))]",children:[c.progressMessage,c.progress!==void 0&&c.progressTotal!==void 0&&` · ${Math.max(0,Math.min(100,Math.round(c.progress/c.progressTotal*100)))}%`]})]}),(c==null?void 0:c.progress)!==void 0&&c.progressTotal!==void 0&&e.jsx("div",{role:"progressbar","aria-label":`${c.toolName} progress`,"aria-valuemin":0,"aria-valuemax":c.progressTotal,"aria-valuenow":Math.min(c.progress,c.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,c.progress/c.progressTotal*100))}%`}})}),r&&e.jsx("div",{"data-agent-tool-group-details":!0,className:"pl-1 mt-2 space-y-2",children:e.jsx(ct,{toolCalls:l})})]})}function Cs({content:t}){const a=B(),[s,r]=h.useState(!1);return t?e.jsxs("div",{"data-agent-thinking":!0,className:"py-0.5",children:[e.jsxs("button",{type:"button","aria-expanded":s,onClick:()=>r(o=>!o),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:[s?e.jsx(me,{className:"h-4 w-4 text-[hsl(var(--deck-ink-faint))]"}):e.jsx(oe,{className:"h-4 w-4 text-[hsl(var(--deck-ink-faint))]"}),e.jsx("span",{children:a("chat.timeline.thinking")})]}),s&&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 Ts({tasks:t}){if(t.length===0)return null;const a=t.filter(r=>r.status==="completed").length,s=a===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:s?"✓ All tasks done":`Tasks: ${a}/${t.length}`})})})}function Es({toolCalls:t}){const a=Re(i=>i.openFilePreview),s=f(i=>ie(i.historySurfaceSelection)),r=h.useMemo(()=>{const i=new Map,l=["Write","SearchReplace","Edit","ApplyPatch"];for(const u of t){if(u.status!=="success")continue;const x=u.metadata;if(u.toolName==="ApplyPatch"&&Array.isArray(x==null?void 0:x.changes)){for(const v of x.changes)v&&typeof v=="object"&&"path"in v&&typeof v.path=="string"&&i.set(v.path,{path:v.path,toolName:u.toolName});continue}const c=x==null?void 0:x.file_path;c&&l.includes(u.toolName)&&i.set(c,{path:c,toolName:u.toolName})}return Array.from(i.values())},[t]);if(s||r.length===0)return null;const o=i=>{K(f.getState())||a({tab:"diff",targetPath:i})};return 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 (",r.length,")"]}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:r.map(({path:i})=>{const l=i.split("/").pop()||i;return e.jsxs("button",{onClick:()=>o(i),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:i,children:[e.jsx(bt,{className:"w-3 h-3"}),l]},i)})})]})}function Ms({subagent:t}){var Q,Z,J,te;const a=B(),[s,r]=h.useState(null),[o,i]=h.useState(!1),[l,u]=h.useState(null),[x,c]=h.useState(!1),[v,b]=h.useState(""),[d,y]=h.useState(!1),[p,N]=h.useState(null),[m,S]=h.useState(null),[k,w]=h.useState(null),n=f(A=>A.currentSessionRef),E=f(A=>A.isStreaming),F=f(A=>A.isTemporarySession),R=f(A=>ie(A.historySurfaceSelection));if(!t)return null;const j=t.status==="running",O=s!==null?s:j,G=t.toolCalls||l||[],C=t.output||t.thinking||G.length>0||t.sessionId,T=m&&m.status!=="running"?m:k,M=(T==null?void 0:T.id)??t.sessionId,P=((Q=T==null?void 0:T.restartRecovery)==null?void 0:Q.outcome)==="failed",L=!j&&!E&&!F&&!R&&!P&&(m==null?void 0:m.status)!=="running"&&!!(M&&n);h.useEffect(()=>{if(R||!O||j||!t.sessionId||!(n!=null&&n.projectPath)||l!==null||t.toolCalls&&t.toolCalls.length>0)return;let A=!0;return i(!0),ae.getMessages({sessionId:t.sessionId,projectPath:n.projectPath}).then(z=>{var H,$;if(!A)return;const q=Rt(z),V=new Map;for(const W of q)if(($=(H=W.agentContent)==null?void 0:H.toolCalls)!=null&&$.length)for(const Y of W.agentContent.toolCalls)V.has(Y.toolCallId)||V.set(Y.toolCallId,Y);u(Array.from(V.values()))}).finally(()=>{A&&i(!1)}),()=>{A=!1}},[O,R,j,t.sessionId,t.toolCalls,l,n==null?void 0:n.projectPath]),h.useEffect(()=>{if(R||!t.sessionId||!n)return;let A=!0;const z=t.rootAgentId??t.sessionId,q=t.resumeDepth??0;return ae.listSubagents(n).then(V=>{if(!A)return;w(V.find($=>$.id===t.sessionId)??null);const H=V.filter($=>$.id!==t.sessionId&&$.rootAgentId===z&&$.resumeDepth>q).sort(($,W)=>W.resumeDepth-$.resumeDepth||W.lastActiveAt-$.lastActiveAt)[0];H&&S(H)}).catch(()=>{}),()=>{A=!1}},[n==null?void 0:n.sessionId,n==null?void 0:n.projectPath,R,t.sessionId,t.rootAgentId,t.resumeDepth]),h.useEffect(()=>{if(R||!m||m.status!=="running"||!n)return;let A=!0;const z=async()=>{try{const H=(await ae.listSubagents(n)).find($=>$.id===m.id);A&&H&&S(H)}catch{}},q=window.setInterval(()=>{z()},1e3);return()=>{A=!1,window.clearInterval(q)}},[n,R,m==null?void 0:m.id,m==null?void 0:m.status]);const ee=async()=>{if(!K(f.getState())&&!(!n||!M||!v.trim()||d)){y(!0),N(null);try{const A=await ae.resumeSubagent(n,M,v.trim());S(A.session),b(""),c(!1),r(!0)}catch(A){N(A instanceof Error?A.message:a("chat.subagent.resumeFailed"))}finally{y(!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(!O),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:[j&&e.jsx(_,{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(Ie,{status:t.status==="completed"?"success":t.status==="failed"?"error":"running"}),t.type==="verification"&&t.verificationVerdict&&e.jsx("span",{"data-verification-verdict":t.verificationVerdict,className:D("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:a("chat.subagent.resumedFromTitle",{id:t.resumedFrom}),children:a("chat.subagent.resumedDepth",{depth:t.resumeDepth??1})})]}),C&&e.jsx(me,{className:D("h-3.5 w-3.5 text-[hsl(var(--deck-ink-muted))] transition-transform",O&&"rotate-180")})]}),!O&&!j&&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}),O&&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})]}),o&&e.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-[hsl(var(--deck-ink-muted))] font-mono",children:[e.jsx(_,{className:"w-3 h-3 animate-spin"}),a("chat.subagent.loadingLogs")]}),!o&&G.length>0&&e.jsx(ct,{toolCalls:G}),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:a("chat.subagent.resumedAs",{id:m.id,status:m.status,depth:m.resumeDepth??1})}),(((Z=m.result)==null?void 0:Z.message)||((J=m.result)==null?void 0:J.error))&&e.jsx("div",{className:"mt-1 whitespace-pre-wrap text-[hsl(var(--deck-ink))]",children:m.result.message||m.result.error})]}),P&&((te=T==null?void 0:T.result)==null?void 0:te.error)&&e.jsx("div",{role:"alert",className:"text-[11px] text-red-600",children:T.result.error}),L&&e.jsxs("div",{className:"space-y-2",children:[x?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":a("chat.subagent.followUpAria"),value:v,onChange:A=>b(A.target.value),placeholder:a("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:()=>{c(!1),N(null)},className:"rounded px-2 py-1 text-[11px] text-[#6B7280] hover:bg-[#F3F4F6] dark:hover:bg-[#27272a]",children:a("chat.subagent.cancel")}),e.jsxs("button",{type:"button",onClick:()=>void ee(),disabled:!v.trim()||d,className:"flex items-center gap-1 rounded bg-[#7C3AED] px-2 py-1 text-[11px] font-medium text-white disabled:opacity-50",children:[d&&e.jsx(_,{className:"w-3 h-3 animate-spin"}),a("chat.subagent.resumeAgent")]})]})]}):e.jsxs("button",{type:"button","aria-label":a("chat.subagent.resumeAria"),onClick:()=>c(!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(fe,{className:"w-3 h-3"}),a("chat.subagent.resume")]}),p&&e.jsx("div",{role:"alert",className:"text-[11px] text-red-600",children:p})]})]})]})}function As({confirmation:t,messageId:a}){const s=B(),[r,o]=h.useState(!1),[i,l]=h.useState(null),u=f(v=>v.currentSessionRef),x=f(v=>v.setConfirmation);if(!t)return null;const c=async(v,b)=>{if(!K(f.getState())&&!(!u||r)){o(!0),l(null);try{await ae.respondPermission(u,t.toolCallId,{approved:v,scope:b}),x(a,{...t,status:v?"approved":"denied"})}catch(d){l(d instanceof Error?d.message:s("interaction.permission.failed"))}finally{o(!1)}}};return t.status!=="pending"?null:e.jsxs("div",{"data-pending-interaction":"permission",tabIndex:-1,role:"alert",className:"p-4 space-y-3 rounded-lg border outline-none border-amber-300/70 bg-amber-50/70 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:s("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}),i&&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:i}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx("button",{type:"button",onClick:()=>void c(!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(_,{className:"h-3.5 w-3.5 animate-spin"}):s("interaction.permission.once")}),t.allowRemember!==!1&&e.jsxs(e.Fragment,{children:[e.jsx("button",{type:"button",onClick:()=>void c(!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:s("interaction.permission.session")}),e.jsx("button",{type:"button",onClick:()=>void c(!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:s("interaction.permission.project")})]}),e.jsx("button",{type:"button",onClick:()=>void c(!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:s("interaction.permission.deny")})]})]})}function Rs({question:t,messageId:a}){const s=B(),[r,o]=h.useState({}),[i,l]=h.useState({}),[u,x]=h.useState(!1),[c,v]=h.useState(null),b=f(m=>m.currentSessionRef),d=f(m=>m.setQuestion),y=h.useMemo(()=>t?t.questions.reduce((m,S)=>{var E;const k=(E=i[S.header])==null?void 0:E.trim(),w=r[S.header];if(S.multiSelect){const F=Array.isArray(w)?[...w]:[];return k&&F.push(k),F.length>0&&(m[S.header]=F),m}const n=k||(typeof w=="string"?w:"");return n&&(m[S.header]=n),m},{}):{},[r,i,t]),p=(t==null?void 0:t.questions.every(m=>m.header in y))??!1;if(!t)return null;const N=async()=>{if(!K(f.getState())&&!(!b||u||!p)){x(!0),v(null);try{await ae.respondToQuestion(b,t.toolCallId,y),d(a,{...t,status:"answered",answers:y})}catch(m){v(m instanceof Error?m.message:s("interaction.question.failed"))}finally{x(!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:s("interaction.question.answered")})}):e.jsxs("div",{"data-pending-interaction":"question",tabIndex:-1,role:"alert",className:"p-4 space-y-4 rounded-lg border outline-none border-amber-300/70 bg-amber-50/70 focus-visible:ring-2 focus-visible:ring-amber-500 dark:border-amber-800/70 dark:bg-amber-950/25",children:[t.questions.map((m,S)=>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((k,w)=>e.jsxs("button",{type:"button",onClick:()=>{if(m.multiSelect){const n=r[m.header]||[],E=n.includes(k.label)?n.filter(F=>F!==k.label):[...n,k.label];o({...r,[m.header]:E})}else o({...r,[m.header]:k.label}),l({...i,[m.header]:""})},className:D("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(k.label):r[m.header]===k.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:k.label}),e.jsx("div",{className:"text-[11px] text-[hsl(var(--deck-ink-faint))] mt-1",children:k.description})]},w)),e.jsx("input",{"aria-label":`${m.header} other response`,value:i[m.header]??"",onChange:k=>l({...i,[m.header]:k.target.value}),placeholder:s("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]"})]})]},S)),c&&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:c}),e.jsxs("button",{type:"button",onClick:()=>void N(),disabled:u||!p,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:[u&&e.jsx(_,{className:"h-3.5 w-3.5 animate-spin"}),s("interaction.question.submit")]})]})}function Fs({message:t}){const a=t.agentContent,s=f(p=>p.isStreaming&&p.currentAssistantMessageId===t.id);if(!a){const p=De(t.content);return p?e.jsx(Oe,{content:p}):null}const{toolCalls:r,tasks:o,confirmation:i,question:l,elicitation:u}=a,x=Et(a),c=Mt(At(a));if(!(c.length>0||o.length>0||x.length>0||i||l||u)&&s)return e.jsxs("div",{className:"flex items-center gap-2 text-[hsl(var(--deck-ink-muted))]",children:[e.jsx(_,{className:"w-4 h-4 animate-spin"}),e.jsx("span",{className:"text-[12px] font-mono",children:"Thinking..."})]});const d=r.length>0&&r.every(p=>p.status==="success"||p.status==="error")&&!s,y=!s;return e.jsxs("div",{className:"space-y-3",children:[c.map(p=>p.type==="thinking"?e.jsx("div",{"data-agent-timeline-block":"thinking",children:e.jsx(Cs,{content:p.content})},p.id):p.type==="text"?e.jsx("div",{"data-agent-timeline-block":"text",children:e.jsx(Oe,{content:p.content,syntaxHighlight:y})},p.id):e.jsx("div",{"data-agent-timeline-block":"tool_group",children:e.jsx(Ss,{toolCalls:r,toolCallIds:p.toolCallIds})},p.id)),o.length>0&&e.jsx(Ts,{tasks:o}),x.map(p=>e.jsx(Ms,{subagent:p},p.id)),i&&e.jsx(As,{confirmation:i,messageId:t.id}),l&&e.jsx(Rs,{question:l,messageId:t.id}),u&&e.jsx(cs,{elicitation:u,messageId:t.id}),d&&e.jsx(Es,{toolCalls:r})]})}function Ds({message:t,showAvatar:a=!0}){var u,x,c,v;const s=t.role==="user";if(t.role==="system"){const b=De(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:b})})}if(s){const b=(u=t.metadata)!=null&&u.userShellCommand&&typeof t.metadata.userShellCommand=="object"?t.metadata.userShellCommand:(x=t.metadata)!=null&&x.userShellExecution&&typeof t.metadata.userShellExecution=="object"?t.metadata.userShellExecution:void 0;if(b){const p=typeof b.command=="string"?b.command:"",N=b.status==="running"?"running":b.status==="completed"?"success":"error",m=typeof b.output=="string"?b.output:[typeof b.stdout=="string"?b.stdout:"",typeof b.stderr=="string"&&b.stderr?`stderr:
61
- ${b.stderr}`:""].filter(Boolean).join(`
62
- `);return e.jsx("div",{"data-chat-message-id":t.id,"data-chat-role":"user","data-user-shell-command":!0,className:"flex justify-end p-4 w-full",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:"$"}),p]}),e.jsx(Ie,{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 b.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 ",b.exitCode,typeof b.durationMs=="number"?` · ${(b.durationMs/1e3).toFixed(3)}s`:"",b.truncated===!0?" · truncated":""]})]})})}const{text:d,images:y}=ks(t.content);return e.jsxs("div",{"data-chat-message-id":t.id,"data-chat-role":"user",className:"flex gap-2 justify-end items-start p-4 w-full group",children:[e.jsx("div",{className:"flex mt-1 opacity-0 transition-opacity shrink-0 group-hover:opacity-100 group-focus-within:opacity-100",children:e.jsx(Le,{text:d,label:"Copy message"})}),e.jsxs("div",{className:"bg-[hsl(var(--deck-surface-2))] rounded-lg px-4 py-3 max-w-[85%]",children:[d&&e.jsx("p",{className:"text-[14px] text-[hsl(var(--deck-ink))] font-mono leading-relaxed whitespace-pre-wrap",children:d}),y.length>0&&e.jsx("div",{className:D("grid gap-2",y.length===1?"grid-cols-1 mt-0":"grid-cols-2 mt-3"),children:y.map((p,N)=>e.jsx("img",{src:p,alt:`attachment-${N+1}`,className:"object-cover w-full max-h-64 rounded-md"},`${p}-${N}`))})]}),e.jsx(gs,{})]})}const o=ys(t),i=ns((c=t.metadata)==null?void 0:c.codeReview),l=ps((v=t.metadata)==null?void 0:v.structuredOutput);return e.jsxs("div",{"data-chat-message-id":t.id,"data-chat-role":"assistant",className:D("flex gap-4 justify-start w-full group",a?"p-4":"px-4 pt-0 pb-3"),children:[a?e.jsx(vs,{}):e.jsx("div",{className:"w-8 shrink-0"}),e.jsxs("div",{className:"overflow-hidden flex-1 min-w-0",children:[i?e.jsx(os,{report:i}):l?e.jsx(fs,{report:l}):e.jsx(Fs,{message:t}),!l&&o.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(Le,{text:o,label:"Copy response"})})]})]})}const Is=h.memo(Ds);function $s(t,a,s){return Math.max(0,t+(s-a))}function _s(t,a,s){return Math.min(a,Math.max(0,t)+Math.max(0,s))}function Bs(t,a,s,r){const o=new Map(t.filter(l=>!!l.id).map(l=>[l.id,l])),i=new Set(s);for(const l of a){if(!l.id)continue;const u=o.get(l.id);u!==l&&(!u||!r||r(u)!==r(l))&&i.add(l.id)}return i}function He(t,a){return t?t.querySelector(`[data-chat-message-id="${CSS.escape(a)}"]`):null}function Ps({turns:t,viewportRef:a,containerRef:s,onRevealTurn:r}){const o=B(),[i,l]=h.useState(null),[u,x]=h.useState(!1),c=h.useRef(null),v=h.useCallback(()=>{var m;const d=a.current,y=s.current;if(!d||!y||t.length===0)return;const p=d.getBoundingClientRect().top;let N=((m=t[0])==null?void 0:m.id)??null;for(const S of t){const k=He(y,S.id);if(k)if(k.getBoundingClientRect().top-p<=24)N=S.id;else break}l(N)},[t,a,s]);h.useEffect(()=>{const d=a.current;if(!d)return;const y=()=>{c.current===null&&(c.current=window.requestAnimationFrame(()=>{c.current=null,v()}))};return v(),d.addEventListener("scroll",y,{passive:!0}),()=>{d.removeEventListener("scroll",y),c.current!==null&&(window.cancelAnimationFrame(c.current),c.current=null)}},[v,a]);const b=h.useCallback(d=>{const y=()=>{const N=He(s.current,d.id);N&&(N.scrollIntoView({behavior:"smooth",block:"start"}),l(d.id))};r(d.index)?y():window.requestAnimationFrame(()=>window.requestAnimationFrame(y))},[s,r]);return t.length<2?null:e.jsx("nav",{"aria-label":o("chat.turns.aria"),className:"absolute right-1 top-1/2 z-20 hidden -translate-y-1/2 sm:block",onMouseEnter:()=>x(!0),onMouseLeave:()=>x(!1),onFocusCapture:()=>x(!0),onBlurCapture:d=>{d.currentTarget.contains(d.relatedTarget)||x(!1)},children:e.jsxs("div",{className:"relative flex items-center justify-end",children:[e.jsx("ul",{className:D("flex flex-col items-center gap-2 py-2 transition-opacity",u?"opacity-0":"opacity-100"),"aria-hidden":u,children:t.map(d=>e.jsx("li",{children:e.jsx("span",{className:D("block rounded-full transition-all",d.id===i?"h-2 w-2 bg-[hsl(var(--deck-accent))]":"h-1.5 w-1.5 bg-[hsl(var(--deck-ink-faint))]/40")})},d.id))}),e.jsx("div",{className:D("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",u?"pointer-events-auto translate-x-0 opacity-100":"pointer-events-none translate-x-2 opacity-0"),children:t.map((d,y)=>e.jsxs("button",{type:"button",onClick:()=>b(d),className:D("flex w-full items-start gap-2 rounded-md px-2 py-1.5 text-left transition-colors",d.id===i?"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:D("mt-1 h-1.5 w-1.5 shrink-0 rounded-full",d.id===i?"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:o("chat.turns.label",{n:y+1})}),e.jsx("span",{className:"line-clamp-2 text-[12px] leading-4",children:d.preview})]})]},d.id))})]})})}const Qe=80;function Ls(t){return typeof t=="string"?t:Array.isArray(t)?t.filter(a=>a.type==="text").map(a=>a.text).join(" "):""}function Us(t){const a=Ls(t).replace(/\s+/g," ").trim();return a?a.length>Qe?`${a.slice(0,Qe-1)}…`:a:""}function Os(t){const a=[];for(let s=0;s<t.length;s+=1){const r=t[s];if(r.role!=="user"||!r.id)continue;const o=Us(r.content);o&&a.push({id:r.id,index:s,preview:o})}return a}const we=120,Ne=80,Ks=96;function le(t){return(t==null?void 0:t.querySelector("[data-radix-scroll-area-viewport]"))??null}function Vs(t){return JSON.stringify([t.role,t.content,t.metadata,t.agentContent])}function Hs({messages:t,isLoading:a}){const s=B(),r=h.useRef(null),o=h.useRef(null),i=h.useRef(!0),l=h.useRef(!1),u=h.useRef(t),x=h.useRef(t),c=h.useRef(new Set),v=h.useRef(t.length),b=h.useRef(null),[d,y]=h.useState(we),[p,N]=h.useState(!1),[m,S]=h.useState(0),k=t.length>0;u.current=t,h.useEffect(()=>{const C=le(r.current);if(!C||l.current&&!i.current)return;const T=window.requestAnimationFrame(()=>{C.scrollTop=C.scrollHeight,l.current=!0,i.current=!0,c.current=new Set,S(0),N(!1)});return()=>window.cancelAnimationFrame(T)},[t]),h.useEffect(()=>{const C=le(r.current);if(!C)return;o.current=C;const T=()=>{if(!l.current)return;const P=C.scrollHeight-C.scrollTop-C.clientHeight<=Ks,L=i.current;i.current=P,N(!P),P?(c.current=new Set,S(0)):L&&(x.current=u.current,c.current=new Set,S(0))};return T(),C.addEventListener("scroll",T,{passive:!0}),()=>C.removeEventListener("scroll",T)},[k,a]),h.useEffect(()=>{const C=x.current;if(x.current=t,i.current){c.current.size>0&&(c.current=new Set,S(0));return}const T=Bs(C,t,c.current,Vs);c.current=T,S(T.size)},[t]),h.useEffect(()=>{const C=v.current;v.current=t.length,y(T=>T>=C&&t.length>C?t.length:Math.min(Math.max(T,we),t.length||we))},[t.length]);const w=Math.max(t.length-d,0),n=w,E=h.useMemo(()=>t.slice(n),[t,n]),F=h.useMemo(()=>Os(t),[t]);if(h.useLayoutEffect(()=>{var M;const C=b.current;if(!C)return;const T=le(r.current);if(b.current=null,!!T){if((M=C.element)!=null&&M.isConnected){const P=C.element.getBoundingClientRect().top-C.viewportTop;T.scrollTop+=P;return}T.scrollTop=$s(C.scrollTop,C.scrollHeight,T.scrollHeight)}},[d]),a)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(Ce,{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(vt,{className:"w-3 h-3"}),s("chat.list.loading.eyebrow")]}),e.jsx("h2",{className:"mt-2 text-[15px] font-medium text-[hsl(var(--deck-ink))]",children:s("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:s("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((C,T)=>e.jsxs("div",{className:D("flex gap-3",T%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:`${C}%`,animationDelay:`${T*120}ms`}})]},C))})]})});if(t.length===0&&!a)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(Ce,{size:44}),e.jsxs("div",{children:[e.jsx("div",{className:"deck-eyebrow text-[hsl(var(--deck-accent))]",children:s("chat.list.empty.eyebrow")}),e.jsx("div",{className:"mt-2 text-[15px] font-medium text-[hsl(var(--deck-ink))]",children:s("chat.list.empty.title")}),e.jsx("div",{className:"mt-1 max-w-xs text-[12px] text-[hsl(var(--deck-ink-muted))]",children:s("chat.list.empty.hint")})]})]})});const R=()=>{const C=le(r.current);C&&(C.scrollTop=C.scrollHeight,i.current=!0,l.current=!0,c.current=new Set,S(0),N(!1))},j=()=>{var T;const C=le(r.current);if(C){const M=((T=r.current)==null?void 0:T.querySelector("[data-chat-message-id]"))??null;b.current={element:M,viewportTop:(M==null?void 0:M.getBoundingClientRect().top)??0,scrollHeight:C.scrollHeight,scrollTop:C.scrollTop}}y(M=>_s(M,t.length,Ne))},O=C=>C>=n?!0:(y(t.length),!1),G=m===1?s("chat.list.unreadMessage"):s("chat.list.unreadMessages",{count:m});return e.jsxs("div",{ref:r,className:"relative flex-1 min-h-0",children:[e.jsx(_t,{className:"h-full",children:e.jsxs("div",{className:"flex flex-col px-4 pb-4 w-full md:px-6",children:[w>0&&e.jsx("div",{className:"flex justify-center py-3",children:e.jsx("button",{type:"button",onClick:j,"aria-label":s("chat.list.showEarlierWithRemaining",{count:Math.min(w,Ne),remaining:w}),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:s("chat.list.showEarlier",{count:Math.min(w,Ne)})})}),E.map((C,T)=>{const M=n+T,P=M>0?t[M-1]:null,L=!P||P.role!==C.role||P.role==="user";return e.jsx(Is,{message:C,showAvatar:L},C.id||`msg-${M}`)})]})}),e.jsx(Ps,{turns:F,viewportRef:o,containerRef:r,onRevealTurn:O}),p&&e.jsxs("button",{type:"button",onClick:R,"aria-live":"polite","aria-label":m>0?G:s("chat.list.jumpLatest"),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(Fe,{className:"h-3.5 w-3.5 text-[hsl(var(--deck-accent))]"}),m>0?G:s("chat.list.jumpLatest")]})]})}const lt=h.memo(Hs);function Qs({queue:t,mutation:a,onMutate:s,onRefresh:r}){const o=B(),[i,l]=h.useState(!1),u=h.useRef(null),x=h.useRef(null),c=h.useRef(null);h.useLayoutEffect(()=>{var p,N,m;if(a.pending||!u.current)return;const d=u.current;u.current=null,(m=Array.from(((p=x.current)==null?void 0:p.querySelectorAll("[data-follow-up-focus-id]"))??[]).find(S=>S.dataset.followUpFocusId===d)??((N=x.current)==null?void 0:N.querySelector("button")))==null||m.focus()},[a.pending,t==null?void 0:t.version]);const v=h.useCallback(async d=>{u.current=d.messageId,await s(d)},[s]),b=h.useCallback((d,y)=>{v({type:"move",messageId:d,toPosition:y})},[v]);return!t||t.pending===0&&!a.errorMessage?null:e.jsxs("section",{ref:x,"data-blade-follow-up-queue":!0,className:"mx-4 mb-2 overflow-hidden rounded-lg border border-amber-300/70 bg-amber-50/70 shadow-sm dark:border-amber-900/60 dark:bg-amber-950/25 md:mx-6","aria-label":o("chat.followUpQueue.title"),children:[e.jsxs("button",{type:"button","aria-label":o(i?"chat.followUpQueue.hide":"chat.followUpQueue.show"),"aria-expanded":i,onClick:()=>l(d=>!d),className:"flex min-h-10 w-full items-center gap-2 px-3 text-left font-mono text-[11px] text-amber-950 transition-colors hover:bg-amber-100/70 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-amber-500 dark:text-amber-100 dark:hover:bg-amber-900/35",children:[e.jsx(Gt,{className:"h-3.5 w-3.5 shrink-0","aria-hidden":!0}),e.jsx("span",{className:"font-semibold",children:o("chat.followUpQueue.count",{count:t.pending})}),t.locked>0&&e.jsx("span",{className:"text-amber-700/80 dark:text-amber-300/75",children:o("chat.followUpQueue.lockedCount",{count:t.locked})}),e.jsx(oe,{className:`ml-auto h-3.5 w-3.5 transition-transform ${i?"rotate-90":""}`,"aria-hidden":!0})]}),i&&e.jsxs("div",{className:"border-t border-amber-300/60 px-2 py-2 dark:border-amber-900/50",children:[a.errorMessage&&e.jsxs("div",{role:"alert",className:"mb-2 flex items-center gap-2 rounded-md border border-red-200 bg-red-50 px-2.5 py-2 text-[11px] text-red-700 dark:border-red-900/60 dark:bg-red-950/35 dark:text-red-300",children:[e.jsx("span",{className:"min-w-0 flex-1",children:a.errorCode==="revision_conflict"?o("chat.followUpQueue.stale"):a.errorMessage}),r&&e.jsx("button",{type:"button","aria-label":o("chat.followUpQueue.refresh"),onClick:()=>void r(),className:"rounded p-1 hover:bg-red-100 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-red-500 dark:hover:bg-red-900/60",children:e.jsx(tt,{className:"h-3.5 w-3.5","aria-hidden":!0})})]}),e.jsx("ol",{className:"space-y-1.5",children:t.items.map((d,y)=>{const p=t.items[y-1],N=t.items[y+1],m=d.mutable&&(p==null?void 0:p.mutable)===!0,S=d.mutable&&(N==null?void 0:N.mutable)===!0,k=a.pending;return e.jsxs("li",{"data-follow-up-id":d.id,"data-follow-up-state":d.state,"data-follow-up-focus-id":d.id,tabIndex:-1,draggable:d.mutable&&!a.pending,onDragStart:()=>{c.current=d.mutable?d.id:null},onDragOver:w=>{const n=c.current,E=t.items.find(F=>F.id===n);E!=null&&E.mutable&&d.mutable&&w.preventDefault()},onDrop:w=>{w.preventDefault();const n=c.current;c.current=null;const E=t.items.find(j=>j.id===n);if(!(E!=null&&E.mutable)||!d.mutable||E.id===d.id)return;const F=Math.min(E.position,d.position),R=Math.max(E.position,d.position);t.items.slice(F,R+1).some(j=>!j.mutable)||b(E.id,d.position)},onDragEnd:()=>{c.current=null},className:"flex min-w-0 items-center gap-2 rounded-md border border-amber-200/70 bg-white/75 px-2.5 py-2 dark:border-amber-900/50 dark:bg-zinc-950/45",children:[e.jsx("span",{className:"w-5 shrink-0 text-center font-mono text-[10px] text-amber-700 dark:text-amber-400",children:y+1}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"truncate text-xs text-[hsl(var(--deck-ink))]",children:d.kind==="internal"?o("chat.followUpQueue.internal"):d.preview||o("chat.followUpQueue.attachmentOnly")}),e.jsxs("div",{className:"mt-0.5 flex items-center gap-2 font-mono text-[9px] uppercase tracking-[0.08em] text-[hsl(var(--deck-ink-faint))]",children:[e.jsx("span",{children:o(`chat.followUpQueue.delivery.${d.delivery}`)}),!d.mutable&&e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx(Wt,{className:"h-2.5 w-2.5","aria-hidden":!0}),o("chat.followUpQueue.locked")]}),d.attachmentCount>0&&e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx(gt,{className:"h-2.5 w-2.5","aria-hidden":!0}),d.attachmentCount]})]})]}),k&&a.messageId===d.id?e.jsx(_,{className:"h-3.5 w-3.5 shrink-0 animate-spin text-amber-600"}):e.jsxs("div",{className:"flex shrink-0 items-center gap-0.5",children:[e.jsx("button",{type:"button","aria-label":o("chat.followUpQueue.moveUp",{id:d.id}),disabled:k||!m,onClick:()=>b(d.id,y-1),className:"rounded p-1 text-amber-800 transition-colors hover:bg-amber-100 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-amber-500 disabled:opacity-30 dark:text-amber-300 dark:hover:bg-amber-900/50",children:e.jsx(Bt,{className:"h-3.5 w-3.5","aria-hidden":!0})}),e.jsx("button",{type:"button","aria-label":o("chat.followUpQueue.moveDown",{id:d.id}),disabled:k||!S,onClick:()=>b(d.id,y+1),className:"rounded p-1 text-amber-800 transition-colors hover:bg-amber-100 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-amber-500 disabled:opacity-30 dark:text-amber-300 dark:hover:bg-amber-900/50",children:e.jsx(Fe,{className:"h-3.5 w-3.5","aria-hidden":!0})}),e.jsx("button",{type:"button","aria-label":o("chat.followUpQueue.remove",{id:d.id}),disabled:k||!d.mutable,onClick:()=>void v({type:"remove",messageId:d.id}),className:"rounded p-1 text-red-600 transition-colors hover:bg-red-100 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-red-500 disabled:opacity-30 dark:text-red-400 dark:hover:bg-red-950/60",children:e.jsx(ne,{className:"h-3.5 w-3.5","aria-hidden":!0})})]})]},d.id)})})]})]})}const Te=Lt,Ee=Ut,Me=Ot,ve=h.forwardRef(({className:t,sideOffset:a=4,...s},r)=>e.jsx(nt,{ref:r,sideOffset:a,className:D("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),...s}));ve.displayName=nt.displayName;const zs={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 xe(t){return t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${(t/1e3).toFixed(1)}K`:String(t)}function qs(t){if(t<60)return`${t}s`;const a=Math.floor(t/60),s=t%60;return s===0?`${a}m`:`${a}m ${s}s`}function Gs(){var C,T,M,P,L,ee,Q,Z,J,te,A,z,q,V,H,$,W,Y,he,ce;const t=B(),{locale:a}=st(),s=f(I=>I.goal),r=f(I=>I.pauseGoal),o=f(I=>I.resumeGoal),i=f(I=>I.editGoal),l=f(I=>I.clearGoal),u=f(I=>ie(I.historySurfaceSelection)),[x,c]=h.useState(!1),[v,b]=h.useState(!1),[d,y]=h.useState(""),[p,N]=h.useState(null),[m,S]=h.useState(!1);if(h.useEffect(()=>{c(!1),b(!1),y((s==null?void 0:s.objective)??""),S(!1)},[s==null?void 0:s.goalId]),u||!s)return null;const k=zs[s.status],w=["active","verifying","paused","blocked"].includes(s.status),n=s.status==="active"||s.status==="verifying",E=s.status==="paused"||s.status==="blocked",F=p!==null,R=async(I,g)=>{if(!K(f.getState())){N(I);try{await g()}finally{N(null)}}},j=()=>{y(s.objective),b(!0),c(!0)},O=async I=>{I.preventDefault();const g=d.trim();if(!g||g===s.objective){b(!1);return}await R("edit",()=>i(g)),b(!1)},G=async()=>{await R("delete",l),S(!1)};return e.jsxs(e.Fragment,{children:[e.jsx(Te,{delayDuration:250,children:e.jsxs("section",{"aria-label":t("goal.aria.section"),className:"mx-3 mb-1 shrink-0","data-blade-goal-status":s.status,"data-blade-goal-recovery":(C=s.prematureStop)==null?void 0:C.consecutiveCount,"data-blade-goal-recovery-pattern":(T=s.prematureStop)==null?void 0:T.pattern,"data-blade-goal-verification-stall":(M=s.verificationStall)==null?void 0:M.consecutiveCount,"data-blade-goal-frontier-task-list":(P=s.executionFrontier)==null?void 0:P.taskListId,"data-blade-goal-frontier-total":(L=s.executionFrontier)==null?void 0:L.total,"data-blade-goal-frontier-completed":(ee=s.executionFrontier)==null?void 0:ee.completed,"data-blade-goal-frontier-in-progress":(Q=s.executionFrontier)==null?void 0:Q.inProgress,"data-blade-goal-frontier-pending":(Z=s.executionFrontier)==null?void 0:Z.pending,"data-blade-goal-frontier-blocked":(J=s.executionFrontier)==null?void 0:J.blocked,"data-blade-goal-frontier-next-task":(A=(te=s.executionFrontier)==null?void 0:te.nextTask)==null?void 0:A.id,"data-blade-goal-frontier-digest":(z=s.executionFrontier)==null?void 0:z.digestSha256.slice(0,16),"data-blade-goal-frontier-stall":(q=s.frontierStall)==null?void 0:q.category,"data-blade-goal-frontier-stall-count":(V=s.frontierStall)==null?void 0:V.consecutiveCount,"data-blade-goal-execution-host-failure":(H=s.executionHostFailure)==null?void 0:H.category,"data-blade-goal-execution-host-failure-count":($=s.executionHostFailure)==null?void 0:$.consecutiveCount,"data-blade-goal-root-turn":(W=s.turnLineage)==null?void 0:W.rootTurnId,"data-blade-goal-current-turn":(Y=s.turnLineage)==null?void 0:Y.currentTurnId,"data-blade-goal-parent-turn":(he=s.turnLineage)==null?void 0:he.parentTurnId,children:[e.jsxs("div",{className:D("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",x&&"rounded-b-none border-b-0"),children:[s.status==="complete"?e.jsx(kt,{className:"h-3.5 w-3.5 shrink-0 text-emerald-500"}):e.jsx(Yt,{className:D("h-3.5 w-3.5 shrink-0",k.accent)}),e.jsx("span",{className:D("h-1.5 w-1.5 shrink-0 rounded-full",k.dot)}),e.jsx("span",{className:D("shrink-0 text-[10px] font-medium leading-none",k.accent),children:s.status==="verifying"?a==="zh"?"验证中":"Verifying":t(k.labelKey)}),e.jsx("span",{className:"h-3 w-px shrink-0 bg-[hsl(var(--deck-hairline))]"}),e.jsx("button",{type:"button","aria-label":t(x?"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(I=>!I),"aria-expanded":x,title:s.objective,children:s.objective}),s.tokensUsed>0&&e.jsxs("span",{className:"hidden shrink-0 text-[10px] tabular-nums text-[hsl(var(--deck-ink-muted))] sm:inline",children:[xe(s.tokensUsed),s.tokenBudget!==void 0&&`/${xe(s.tokenBudget)}`]}),e.jsxs("div",{className:"flex shrink-0 items-center",children:[n&&e.jsx(pe,{label:t("goal.action.pause"),disabled:F,onClick:()=>void R("pause",r),children:p==="pause"?e.jsx(_,{className:"animate-spin"}):e.jsx(Kt,{})}),E&&e.jsx(pe,{label:t("goal.action.resume"),disabled:F,onClick:()=>void R("resume",o),children:p==="resume"?e.jsx(_,{className:"animate-spin"}):e.jsx(Vt,{})}),e.jsx(pe,{label:t(w?"goal.action.edit":"goal.action.expand"),disabled:!w&&!x,onClick:w?j:()=>c(I=>!I),children:w?e.jsx(it,{}):e.jsx(Pt,{})}),e.jsx(pe,{label:t("goal.action.delete"),disabled:F,destructive:!0,onClick:()=>S(!0),children:e.jsx(ne,{})})]})]}),x&&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:v?e.jsxs("form",{onSubmit:O,children:[e.jsx("textarea",{id:"goal-objective",value:d,onChange:I=>y(I.target.value),onKeyDown:I=>{I.key==="Escape"&&b(!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:()=>b(!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(at,{className:"h-3 w-3"}),t("goal.action.cancel")]}),e.jsxs("button",{type:"submit",disabled:!d.trim()||p==="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:[p==="edit"?e.jsx(_,{className:"h-3 w-3 animate-spin"}):e.jsx(ge,{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:s.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(zt,{className:"h-3 w-3"}),xe(s.tokensUsed),s.tokenBudget!==void 0&&` / ${xe(s.tokenBudget)}`," ",t("goal.metrics.tokens")]}),e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx(Xt,{className:"h-3 w-3"}),qs(s.timeUsedSeconds)]}),e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx(fe,{className:"h-3 w-3"}),s.continuationCount===1?t("goal.metrics.continuationOne",{n:s.continuationCount}):t("goal.metrics.continuationMany",{n:s.continuationCount})]})]}),s.turnLineage&&e.jsxs("div",{className:"mt-2 grid grid-cols-[auto_1fr] gap-x-3 gap-y-1 rounded-md border border-[hsl(var(--deck-border))]/50 bg-[hsl(var(--deck-canvas))]/45 px-2.5 py-2 font-mono text-[10px] text-[hsl(var(--deck-ink-muted))]",children:[e.jsx("span",{children:t("goal.lineage.origin")}),e.jsx("span",{className:"truncate",children:s.turnLineage.rootTurnId??"?"}),e.jsx("span",{children:t("goal.lineage.current")}),e.jsx("span",{className:"truncate",children:s.turnLineage.currentTurnId}),e.jsx("span",{children:t("goal.lineage.parent")}),e.jsx("span",{className:"truncate",children:s.turnLineage.parentTurnId??"?"})]}),s.prematureStop&&e.jsxs("div",{className:"mt-2 inline-flex items-center gap-1.5 font-mono text-[10px] text-amber-700 dark:text-amber-300",children:[e.jsx(fe,{className:"h-3 w-3"}),a==="zh"?"恢复提示":"Recovery nudge"," ",s.prematureStop.consecutiveCount," ·"," ",s.prematureStop.pattern.replaceAll("_"," ")]}),s.executionHostFailure&&e.jsxs("div",{className:"mt-2 rounded-md border border-amber-200/50 bg-amber-50/60 px-2.5 py-2 text-[11px] text-amber-900 dark:border-amber-400/15 dark:bg-amber-400/[0.05] dark:text-amber-100",children:[e.jsx("p",{className:"font-medium",children:t("goal.executionHostFailure.title")}),e.jsxs("p",{className:"mt-1 font-mono opacity-80",children:[t(`goal.executionHostFailure.category.${s.executionHostFailure.category}`)," ","· ",s.executionHostFailure.consecutiveCount,"/3"]})]}),s.completionVerification&&e.jsxs("div",{"data-goal-verification":s.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:["#",s.completionVerification.attempt," ·"," ",s.completionVerification.status.toUpperCase()," ·"," ",((ce=s.completionVerification.verifierSessionId)==null?void 0:ce.slice(0,12))??"-",s.verificationStall?a==="zh"?` · 重复 ${s.verificationStall.consecutiveCount}/3`:` · repeat ${s.verificationStall.consecutiveCount}/3`:""]}),s.completionVerification.summary&&e.jsx("p",{className:"mt-1 line-clamp-3 whitespace-pre-wrap opacity-80",children:s.completionVerification.summary}),s.completionVerification.evidenceSha256&&e.jsxs("p",{className:"mt-1 font-mono text-[10px] opacity-60",children:["sha256:",s.completionVerification.evidenceSha256.slice(0,12)]})]}),s.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:s.statusReason})]})})]})}),e.jsx(We,{open:m,onOpenChange:S,children:e.jsxs(Je,{className:"max-w-[400px] border-[hsl(var(--deck-border))] bg-[hsl(var(--deck-surface))]",children:[e.jsx(Ye,{children:t("goal.dialog.title")}),e.jsx(Xe,{children:t("goal.dialog.description")}),e.jsxs(Ze,{className:"mt-2",children:[e.jsx("button",{type:"button",onClick:()=>S(!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:p==="delete",onClick:()=>void G(),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:[p==="delete"&&e.jsx(_,{className:"w-3.5 h-3.5 animate-spin"}),t("goal.action.delete")]})]})]})})]})}function pe({label:t,children:a,disabled:s,destructive:r,onClick:o}){return e.jsxs(Ee,{children:[e.jsx(Me,{asChild:!0,children:e.jsx("button",{type:"button","aria-label":t,disabled:s,onClick:o,className:D("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:a})}),e.jsx(ve,{side:"top",className:"text-[10px]",children:t})]})}function Ws(){const t=B(),a=f(c=>c.currentSessionRef),s=f(c=>c.sessions),r=f(c=>c.messages),o=f(c=>ie(c.historySurfaceSelection)),i=h.useMemo(()=>{var v,b,d,y,p;const c=a?(v=yt(s,a))==null?void 0:v.pendingInteraction:void 0;if(c)return c.type;for(let N=r.length-1;N>=0;N-=1){const m=(b=r[N])==null?void 0:b.agentContent;if(((d=m==null?void 0:m.confirmation)==null?void 0:d.status)==="pending")return"permission";if(((y=m==null?void 0:m.question)==null?void 0:y.status)==="pending")return"question";if(((p=m==null?void 0:m.elicitation)==null?void 0:p.status)==="pending")return"elicitation"}return null},[a,r,s]);if(o||!i)return null;const l=()=>{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)},u=i==="question",x=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(Ae,{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(u?"interaction.bar.questionTitle":x?"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(u?"interaction.bar.questionHint":x?"interaction.bar.elicitationHint":"interaction.bar.permissionHint")})]}),e.jsxs("button",{type:"button",onClick:l,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(Fe,{className:"h-3 w-3"}),t("interaction.bar.review")]})]})}function ue(t){return Math.max(0,Math.ceil((t??0)/1e3))}function Js(t,a=Date.now()){var r;const s=(r=t.snapshot)==null?void 0:r.nextActionAt;return s===void 0?void 0:ue(s-a)}function dt(t,a=Date.now()){const s=t==null?void 0:t.snapshot;if(!s)return null;const r=Js(t,a)??0,o=s.retry,i=s.admission,l=s.stall,u=s.fallback,x={seconds:r,attempt:(o==null?void 0:o.attempt)??0,maxRetries:(o==null?void 0:o.maxRetries)??0,budgetSeconds:ue(o==null?void 0:o.recoveryRemainingMs),position:(i==null?void 0:i.queuePosition)??0,depth:i?Math.max(i.queueDepth,i.queuePosition):0,scope:(i==null?void 0:i.scope)??"",waitSeconds:ue(i==null?void 0:i.waitMs),stallSeconds:ue(l==null?void 0:l.durationMs),timeoutSeconds:ue(l==null?void 0:l.timeoutMs),from:(u==null?void 0:u.from.model)??"",to:(u==null?void 0:u.to.model)??"",candidate:(u==null?void 0:u.candidate)??0,candidateCount:(u==null?void 0:u.candidateCount)??0};switch(s.activity){case"admission_wait":return{titleKey:"chat.providerRecovery.admission",detailKey:"chat.providerRecovery.admissionDetail",compactKey:"chat.providerRecovery.admissionCompact",params:x};case"retry_wait":return{titleKey:s.reason==="rate_limit"?"chat.providerRecovery.rateLimit":"chat.providerRecovery.retryWait",detailKey:"chat.providerRecovery.retryDetail",compactKey:"chat.providerRecovery.retryCompact",params:x};case"retry_attempt":return{titleKey:"chat.providerRecovery.retryAttempt",detailKey:"chat.providerRecovery.retryDetail",compactKey:"chat.providerRecovery.retryCompact",params:x};case"circuit_open":return{titleKey:s.reason==="rate_limit"?"chat.providerRecovery.rateLimitCircuit":"chat.providerRecovery.circuit",detailKey:"chat.providerRecovery.circuitDetail",compactKey:s.reason==="rate_limit"?"chat.providerRecovery.rateLimitCircuitCompact":"chat.providerRecovery.circuitCompact",params:x};case"circuit_probe":return{titleKey:"chat.providerRecovery.probe",detailKey:"chat.providerRecovery.probeDetail",compactKey:"chat.providerRecovery.probeCompact",params:x};case"stream_stall":return{titleKey:l!=null&&l.outputStarted?"chat.providerRecovery.stallAfterOutput":"chat.providerRecovery.stall",detailKey:"chat.providerRecovery.stallDetail",compactKey:"chat.providerRecovery.stallCompact",params:x};case"fallback":return{titleKey:"chat.providerRecovery.fallback",detailKey:"chat.providerRecovery.fallbackDetail",compactKey:"chat.providerRecovery.fallbackCompact",params:x}}}function Ys({recovery:t,stopping:a,onStop:s}){var x;const r=B(),[o,i]=h.useState(Date.now()),l=(x=t==null?void 0:t.snapshot)==null?void 0:x.nextActionAt;h.useEffect(()=>{if(l===void 0)return;i(Date.now());const c=window.setInterval(()=>i(Date.now()),1e3);return()=>window.clearInterval(c)},[l]);const u=dt(t,o);return u?e.jsxs("section",{role:"status","aria-live":"polite","data-provider-recovery-banner":!0,className:"mx-4 mb-2 flex min-h-12 items-center gap-3 rounded-lg border border-amber-300/70 bg-amber-50/80 px-3 py-2 text-amber-950 shadow-sm dark:border-amber-800/60 dark:bg-amber-950/35 dark:text-amber-100 md:mx-6",children:[e.jsx(_,{className:"h-4 w-4 shrink-0 animate-spin","aria-hidden":!0}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"text-xs font-semibold",children:r(u.titleKey,u.params)}),e.jsx("div",{className:"mt-0.5 truncate font-mono text-[10px] opacity-80",children:r(u.detailKey,u.params)})]}),e.jsxs("button",{type:"button","data-provider-recovery-stop":!0,onClick:s,disabled:a,className:"inline-flex min-h-8 shrink-0 items-center gap-1.5 rounded-md border border-amber-400/70 bg-white/70 px-2.5 text-xs font-medium transition-colors hover:bg-white focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-amber-500 disabled:cursor-wait disabled:opacity-60 dark:border-amber-700 dark:bg-amber-950/50 dark:hover:bg-amber-900/50",children:[a?e.jsx(_,{className:"h-3.5 w-3.5 animate-spin","aria-hidden":!0}):e.jsx(jt,{className:"h-3 w-3 fill-current","aria-hidden":!0}),r(a?"chat.input.action.stopping":"chat.providerRecovery.stop")]})]}):null}const Xs=h.lazy(()=>et(()=>import("./MarkdownRenderer-CXDrI3kX.js").then(t=>t.M),__vite__mapDeps([0,1,2,3,4,5,6])).then(t=>({default:t.MarkdownRenderer})));function Zs(t){return t<1e3?`${t}ms`:`${(t/1e3).toFixed(1)}s`}function ea(){const t=B(),a=f(r=>r.sideConversation),s=f(r=>r.dismissSideConversation);return a?e.jsx("section",{"aria-label":t("chat.side.title"),"data-blade-side-conversation":!0,"data-status":a.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(Jt,{"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")}),a.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(Ht,{"aria-hidden":!0,className:"h-3 w-3"}),Zs(a.durationMs)]})]}),e.jsx("p",{className:"mt-0.5 break-words font-mono text-[11px] leading-4 text-[hsl(var(--deck-ink-muted))]",children:a.question})]}),e.jsx("button",{type:"button",onClick:s,"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(at,{"aria-hidden":!0,className:"h-3.5 w-3.5"})})]}),e.jsxs("div",{"aria-live":"polite","aria-busy":a.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:[a.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(_,{"aria-hidden":!0,className:"h-3.5 w-3.5 animate-spin text-[hsl(var(--deck-accent))]"}),t("chat.side.loading")]}),a.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(Ae,{"aria-hidden":!0,className:"mt-0.5 h-3.5 w-3.5 shrink-0"}),e.jsx("span",{className:"break-words",children:a.error??t("chat.side.failed")})]}),a.status==="completed"&&a.response&&e.jsx(h.Suspense,{fallback:e.jsx("div",{className:"whitespace-pre-wrap break-words font-mono text-[12px] leading-5 text-[hsl(var(--deck-ink))]",children:a.response}),children:e.jsx(Xs,{content:a.response,className:"text-[12px] leading-5 [&_h1]:text-[14px] [&_h2]:text-[13px] [&_h3]:text-[12px]"})})]})]})}):null}function Se(t){return Number.isFinite(t)?Math.max(0,t):0}function ta(t){const a=Se(t.totalInputTokens),s=Se(t.cacheReadTokens),r=Se(t.cacheWriteTokens),o=Math.min(s,a),i=Math.min(r,Math.max(0,a-o)),l=Math.max(0,a-o-i),u=a>0&&(s>0||r>0);return{totalInputTokens:a,cacheReadTokens:o,cacheWriteTokens:i,uncachedInputTokens:l,...u?{hitRate:o/a}:{}}}function sa(t){return t===void 0||!Number.isFinite(t)?"—":`${Math.round(Math.max(0,Math.min(1,t))*100)}%`}const aa={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:""},ra={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"},se=t=>t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${(t/1e3).toFixed(1)}K`:t.toString(),na=t=>{const a=Math.max(0,Math.ceil(t/1e3)),s=Math.floor(a/60),r=a%60;return s>0?`${s}m ${r}s`:`${r}s`};function ut(){const t=B(),a=f(n=>n.tokenUsage),s=f(n=>n.isStreaming),r=f(n=>n.agentPhase),o=f(n=>n.providerRecovery),i=f(n=>n.turnActivity),l=f(n=>n.pendingResume),u=f(n=>n.actionStationarity),x=f(n=>n.turnRecovery),c=aa[r]??"",v=dt(o),b=(l==null?void 0:l.delayMs)!==void 0?` · retry in ${na(l.delayMs)}`:"",d=(x==null?void 0:x.state)==="requires_attention"?t("status.recovery.review"):"",y=(x==null?void 0:x.state)==="requires_attention"?t(x.reason==="interrupted_tool_call"?"status.recovery.interruptedTool":"status.recovery.successfulTool"):"",p=d||(u?`${t(u.phase==="halted"?"status.phase.actionStationarityStopped":"status.phase.actionStationarityRecovering")} · ${u.toolName} · ${u.runLength}/${u.haltThreshold}`:v?t(v.compactKey,v.params):l?`Recovery attempt ${l.attempt}/${l.maxAttempts}${b}`:c?t(c):""),N=a.maxContextTokens>0?Math.round(a.totalTokens/a.maxContextTokens*100):0,m=ta(a),S=sa(m.hitRate),k=Math.min(N,100),w=N>95?"danger":N>80?"warn":"safe";return e.jsxs("div",{"data-chat-status-bar":!0,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:D("text-[12px] font-medium",w==="safe"&&"text-[hsl(var(--deck-ink))]",w==="warn"&&"text-amber-600 dark:text-amber-400",w==="danger"&&"text-red-600 dark:text-red-400"),children:se(a.totalTokens)}),e.jsxs("span",{className:"text-[hsl(var(--deck-ink-faint))]",children:["/ ",se(a.maxContextTokens)]})]}),a.isDefaultMaxTokens&&e.jsx(Te,{children:e.jsxs(Ee,{children:[e.jsx(Me,{asChild:!0,children:e.jsx(qt,{className:"h-3 w-3 cursor-help text-[hsl(var(--deck-ink-faint))]"})}),e.jsx(ve,{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:D("absolute inset-y-0 left-0 transition-[width] duration-300",w==="safe"&&"bg-[hsl(var(--deck-accent))]",w==="warn"&&"bg-amber-500",w==="danger"&&"bg-red-500"),style:{width:`${k}%`}}),e.jsx("div",{className:"flex absolute inset-0 pointer-events-none",children:[25,50,75].map(n=>e.jsx("span",{className:"absolute inset-y-0 w-px bg-[hsl(var(--deck-canvas-veil))]/60",style:{left:`${n}%`}},n))})]}),e.jsxs("span",{className:D("w-10 text-right tabular-nums text-[hsl(var(--deck-ink-faint))]",w==="warn"&&"text-amber-600 dark:text-amber-400",w==="danger"&&"text-red-600 dark:text-red-400"),children:[N,"%"]})]}),e.jsx(Te,{children:e.jsxs(Ee,{children:[e.jsx(Me,{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")} ${S}`,children:[e.jsx("span",{className:"deck-eyebrow text-[hsl(var(--deck-ink-faint))]",children:t("status.cache")}),e.jsx("span",{className:D("tabular-nums",m.hitRate===void 0?"text-[hsl(var(--deck-ink-faint))]":"font-medium text-[hsl(var(--deck-accent))]"),children:S})]})}),e.jsx(ve,{side:"top",className:"max-w-[280px]",children:m.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:se(m.cacheReadTokens),write:se(m.cacheWriteTokens),uncached:se(m.uncachedInputTokens)})}),a.cacheBreak&&e.jsx("p",{className:"text-[hsl(var(--deck-accent))]",children:t("status.cacheBreak",{reason:t(ra[a.cacheBreak.reason]??"status.cacheBreak.server"),previous:se(a.cacheBreak.previousCacheReadTokens),current:se(a.cacheBreak.cacheReadTokens)})})]})})]})}),e.jsx("div",{className:"flex-1"}),(d||s&&p&&(!(i!=null&&i.snapshot)||u))&&e.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[e.jsx("span",{className:D("shrink-0",d?"h-2 w-2 rounded-sm bg-amber-500":"deck-pulse-dot")}),e.jsxs("span",{className:D("truncate",d?"text-amber-600 dark:text-amber-400":"text-[hsl(var(--deck-accent))]"),children:[p,y?e.jsxs("span",{className:"hidden sm:inline",children:[" · ",y]}):null]})]})]})}function ia(){const{locale:t}=st(),a=wt(n=>n.agentTeamsEnabled),s=f(n=>n.teams),r=f(n=>n.currentSessionRef),o=f(n=>ie(n.historySurfaceSelection)),i=f(n=>n.loadTeams),[l,u]=h.useState({}),[x,c]=h.useState({}),[v,b]=h.useState({}),[d,y]=h.useState(null),[p,N]=h.useState(null),[m,S]=h.useState(null);if(h.useEffect(()=>{o||i(r??void 0)},[a,r,o,i]),o||!a||!r||s.length===0)return null;const k=async n=>{var F;if(K(f.getState()))return;const E=(F=v[n])==null?void 0:F.trim();if(!(!E||d)){y(n),S(null);try{await Be.sendMessage(r,n,x[n]??"*",E),b(R=>({...R,[n]:""})),await i(r)}catch(R){S(R instanceof Error?R.message:U(t,"actionFailed"))}finally{y(null)}}},w=async n=>{if(!K(f.getState())&&!p){N(n),S(null);try{await Be.delete(r,n),await i(r)}catch(E){S(E instanceof Error?E.message:U(t,"actionFailed"))}finally{N(null)}}};return e.jsxs("section",{"aria-label":U(t,"title"),"data-blade-team-panel":!0,className:"shrink-0 border-y border-emerald-300/50 bg-emerald-50/55 dark:border-emerald-800/55 dark:bg-emerald-950/20",children:[m&&e.jsx("div",{role:"alert",className:"border-b border-red-200 bg-red-50 px-4 py-2 font-mono text-[10px] text-red-700 dark:border-red-900 dark:bg-red-950/30 dark:text-red-300 md:px-6",children:m}),s.filter(n=>n.status!=="deleted").map(n=>{var R;const E=l[n.name]??n.status==="running",F=n.tasks.filter(j=>j.status==="completed").length;return e.jsxs("div",{className:"border-b border-emerald-200/40 last:border-0 dark:border-emerald-900/40",children:[e.jsxs("div",{className:"flex min-h-11 items-center gap-2 px-4 py-2 md:px-6",children:[e.jsx("button",{type:"button",onClick:()=>u(j=>({...j,[n.name]:!E})),"aria-label":E?U(t,"collapse"):U(t,"expand"),className:"flex h-7 w-7 items-center justify-center rounded-md text-emerald-700 hover:bg-emerald-100 dark:text-emerald-300 dark:hover:bg-emerald-900/50",children:E?e.jsx(me,{className:"h-4 w-4"}):e.jsx(oe,{className:"h-4 w-4"})}),e.jsx(Zt,{className:"h-4 w-4 shrink-0 text-emerald-700 dark:text-emerald-300"}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex flex-wrap items-baseline gap-2",children:[e.jsx("h2",{className:"truncate font-mono text-[11px] font-semibold uppercase text-emerald-800 dark:text-emerald-200",children:n.name}),e.jsxs("span",{className:"font-mono text-[9.5px] text-[hsl(var(--deck-ink-faint))]",children:[n.status," · ",n.members.length-1," ",U(t,"members")," · ",F,"/",n.tasks.length," ",U(t,"tasks")]})]}),n.description&&e.jsx("p",{className:"truncate font-mono text-[10px] text-[hsl(var(--deck-ink-muted))]",children:n.description})]}),e.jsx("button",{type:"button",onClick:()=>void w(n.name),disabled:p===n.name,"aria-label":U(t,"delete"),title:U(t,"delete"),className:"flex h-7 w-7 items-center justify-center rounded-md text-[hsl(var(--deck-ink-faint))] hover:bg-red-50 hover:text-red-600 disabled:opacity-40 dark:hover:bg-red-950/40",children:e.jsx(ne,{className:"h-3.5 w-3.5"})})]}),E&&e.jsxs("div",{className:"max-h-[min(40vh,360px)] overflow-y-auto border-t border-emerald-200/40 px-4 py-3 md:px-6 dark:border-emerald-900/40",children:[e.jsxs("div",{className:"grid gap-x-6 gap-y-2 lg:grid-cols-2",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"mb-1 font-mono text-[9.5px] font-semibold uppercase text-[hsl(var(--deck-ink-faint))]",children:U(t,"members")}),n.members.map(j=>e.jsxs("div",{className:"flex min-h-7 items-center gap-2 border-b border-[hsl(var(--deck-hairline)/0.55)] py-1 last:border-0",children:[e.jsx("span",{"aria-label":j.status,className:`h-1.5 w-1.5 shrink-0 rounded-full ${j.status==="running"?"bg-emerald-500":j.status==="completed"||j.status==="leader"?"bg-sky-500":j.status==="failed"?"bg-red-500":"bg-zinc-400"}`}),e.jsx("span",{className:"min-w-0 flex-1 truncate font-mono text-[10.5px] text-[hsl(var(--deck-ink))]",children:j.name}),e.jsx("span",{className:"font-mono text-[9px] text-[hsl(var(--deck-ink-faint))]",children:j.subagentType}),j.worktreePath&&e.jsx(qe,{className:"h-3 w-3 text-[hsl(var(--deck-ink-faint))]","aria-label":U(t,"worktree")})]},j.id))]}),e.jsxs("div",{children:[e.jsx("h3",{className:"mb-1 font-mono text-[9.5px] font-semibold uppercase text-[hsl(var(--deck-ink-faint))]",children:U(t,"tasks")}),n.tasks.length===0?e.jsx("p",{className:"font-mono text-[10px] text-[hsl(var(--deck-ink-faint))]",children:U(t,"noTasks")}):n.tasks.map(j=>e.jsxs("div",{className:"flex min-h-7 items-center gap-2 border-b border-[hsl(var(--deck-hairline)/0.55)] py-1 last:border-0",children:[e.jsxs("span",{className:"w-5 shrink-0 font-mono text-[9px] text-[hsl(var(--deck-ink-faint))]",children:["#",j.id]}),e.jsx("span",{className:"min-w-0 flex-1 truncate font-mono text-[10.5px] text-[hsl(var(--deck-ink))]",children:j.subject}),e.jsx("span",{className:"font-mono text-[9px] text-[hsl(var(--deck-ink-faint))]",children:j.status})]},j.id))]})]}),n.peerMessagingEnabled&&e.jsxs("div",{className:"mt-3 flex items-center gap-2 border-t border-emerald-200/40 pt-3 dark:border-emerald-900/40",children:[e.jsxs("select",{"aria-label":U(t,"recipient"),value:x[n.name]??"*",onChange:j=>c(O=>({...O,[n.name]:j.target.value})),className:"h-8 max-w-32 rounded-md border border-[hsl(var(--deck-hairline))] bg-[hsl(var(--deck-surface))] px-2 font-mono text-[10px]",children:[e.jsx("option",{value:"*",children:U(t,"broadcast")}),n.members.filter(j=>j.status!=="leader").map(j=>e.jsx("option",{value:j.name,children:j.name},j.id))]}),e.jsx("input",{value:v[n.name]??"",onChange:j=>b(O=>({...O,[n.name]:j.target.value})),onKeyDown:j=>{j.key==="Enter"&&k(n.name)},placeholder:U(t,"messagePlaceholder"),className:"h-8 min-w-0 flex-1 rounded-md border border-[hsl(var(--deck-hairline))] bg-[hsl(var(--deck-surface))] px-2 font-mono text-[10.5px] outline-none focus:border-emerald-500"}),e.jsx("button",{type:"button",onClick:()=>void k(n.name),disabled:!((R=v[n.name])!=null&&R.trim())||d===n.name,"aria-label":U(t,"send"),title:U(t,"send"),className:"flex h-8 w-8 shrink-0 items-center justify-center rounded-md bg-emerald-700 text-white hover:bg-emerald-800 disabled:opacity-40 dark:bg-emerald-600",children:e.jsx(Ge,{className:"h-3.5 w-3.5"})})]})]})]},n.name)})]})}const oa={starting:"chat.turnActivity.starting",thinking:"chat.turnActivity.thinking",responding:"chat.turnActivity.responding",executing_tools:"chat.turnActivity.executingTools",compacting:"chat.turnActivity.compacting",continuing:"chat.turnActivity.continuing"};function ca(t){const a=Math.max(0,Math.floor(t/1e3));if(a<60)return`${a}s`;const s=Math.floor(a/60),r=a%60;return s<60?`${s}m ${r}s`:`${Math.floor(s/60)}h ${s%60}m ${r}s`}function la(t,a=Date.now()){const s=t==null?void 0:t.snapshot;if(!s)return null;const r=s.activeTools.length+s.activeToolOverflow,o=s.activeTools.slice(0,2).map(l=>l.progress!==void 0&&l.total!==void 0?`${l.name} ${l.progress}/${l.total}`:l.name),i=Math.max(0,s.activeTools.length-o.length+s.activeToolOverflow);return{phaseKey:oa[s.phase],phaseParams:{count:r},tools:o,hiddenTools:i,completedTools:s.toolCallsCompleted,startedTools:s.toolCallsStarted,turn:s.turn,maxTurns:s.maxTurns,elapsed:ca(a-s.startedAt)}}function da({activity:t,memory:a=null}){var x;const s=B(),[r,o]=h.useState(Date.now()),i=(x=t==null?void 0:t.snapshot)==null?void 0:x.startedAt;h.useEffect(()=>{if(i===void 0)return;o(Date.now());const c=window.setInterval(()=>o(Date.now()),1e3);return()=>window.clearInterval(c)},[i]);const l=la(t,r);if(!l)return(a==null?void 0:a.outcome)!=="written"?null:e.jsxs("section",{role:"status","aria-live":"polite","data-memory-consolidation-notice":!0,className:"mx-4 mb-2 flex min-h-10 items-center gap-3 rounded-lg border border-[hsl(var(--deck-border))] bg-[hsl(var(--deck-surface))]/80 px-3 py-2 text-[hsl(var(--deck-ink))] shadow-sm md:mx-6",children:[e.jsx(_e,{className:"h-4 w-4 shrink-0 text-[hsl(var(--deck-accent))]","aria-hidden":!0}),e.jsx("span",{className:"text-xs font-semibold",children:s("chat.memoryConsolidation.saved",{count:a.entries})})]});const u=[(a==null?void 0:a.outcome)==="written"?s("chat.memoryConsolidation.saved",{count:a.entries}):void 0,...l.tools,l.hiddenTools>0?`+${l.hiddenTools}`:void 0,l.startedTools>0?s("chat.turnActivity.toolCount",{completed:l.completedTools,started:l.startedTools}):void 0,l.turn>0?l.maxTurns===null?s("chat.turnActivity.turn",{turn:l.turn}):s("chat.turnActivity.turnBounded",{turn:l.turn,maxTurns:l.maxTurns}):void 0].filter(c=>c!==void 0);return e.jsxs("section",{role:"status","aria-live":"polite","data-turn-activity-strip":!0,className:"mx-4 mb-2 flex min-h-10 items-center gap-3 rounded-lg border border-[hsl(var(--deck-border))] bg-[hsl(var(--deck-surface))]/80 px-3 py-2 text-[hsl(var(--deck-ink))] shadow-sm md:mx-6",children:[e.jsx(_e,{className:"h-4 w-4 shrink-0 text-[hsl(var(--deck-accent))] motion-safe:animate-pulse","aria-hidden":!0}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"text-xs font-semibold",children:s(l.phaseKey,l.phaseParams)}),u.length>0&&e.jsx("div",{className:"mt-0.5 truncate font-mono text-[10px] text-[hsl(var(--deck-ink-muted))]",children:u.join(" · ")})]}),e.jsx("span",{className:"shrink-0 font-mono text-[10px] tabular-nums text-[hsl(var(--deck-ink-muted))]",children:l.elapsed})]})}function ua(t){const a=[...t].reverse().find(o=>o.role==="user");if(!a)return null;if(typeof a.content=="string")return{content:a.content,attachments:[]};const s=a.content.filter(o=>o.type==="text").map(o=>o.text).join(`
63
- `),r=a.content.filter(o=>o.type==="image_url").map((o,i)=>{var u;const l=((u=o.image_url.url.match(/^data:([^;,]+)[;,]/))==null?void 0:u[1])??"application/octet-stream";return{id:`recovery-${a.id}-${i}`,name:`attachment-${i+1}`,mimeType:l,dataUrl:o.image_url.url}});return{content:s,attachments:r}}function ma({messages:t,isLoading:a,isStreaming:s,isStopping:r,errorMessage:o}){const i=B(),[l,u]=h.useState(!1),x=i(o?"status.phase.error":r?"chat.input.action.stopping":s?"status.phase.running":"preview.files.status.ready");return e.jsxs("details",{"data-preview-status-disclosure":!0,open:l,onToggle:c=>u(c.currentTarget.open),className:"group hidden",children:[e.jsxs("summary",{className:"flex h-9 cursor-pointer list-none items-center gap-2 px-3 font-mono text-[11px] text-[hsl(var(--deck-ink-muted))] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-[hsl(var(--deck-accent))]",children:[s&&e.jsx("span",{className:"deck-pulse-dot"}),e.jsx("span",{className:"min-w-0 flex-1 truncate",children:x}),e.jsx(oe,{className:"h-3.5 w-3.5 shrink-0 transition-transform group-open:rotate-90"})]}),l&&e.jsxs("div",{"data-preview-activity-details":!0,className:"flex h-[min(44vh,420px)] min-h-0 flex-col border-t border-[hsl(var(--deck-hairline))]",children:[o&&e.jsx("div",{role:"alert",className:"border-b border-red-200/60 bg-red-50/80 px-3 py-2 font-mono text-[11px] text-red-700 dark:border-red-900/50 dark:bg-red-950/30 dark:text-red-300",children:o}),e.jsx(lt,{messages:t,isLoading:a}),e.jsx(ut,{})]})]})}function Ea(){var I;const t=B(),a=f(g=>g.messages),s=f(g=>g.currentSessionRef),r=f(g=>g.isStreaming),o=f(g=>g.isStopping),i=f(g=>g.providerRecovery),l=f(g=>g.turnActivity),u=f(g=>g.memoryConsolidation),x=f(g=>g.actionStationarity),c=f(g=>g.sessionEventConnectionState),v=f(g=>g.pendingSteeringCount),b=f(g=>g.pendingInputDelivery),d=f(g=>g.recoveredSteeringCount),y=f(g=>g.followUpQueue),p=f(g=>g.followUpQueueMutation),N=f(g=>g.mutateFollowUpQueue),m=f(g=>g.refreshFollowUpQueue),S=f(g=>!!g.historySurfaceSelection),k=f(g=>g.isLoading),w=f(g=>g.error),n=f(g=>g.errorContext),E=f(g=>g.sessions),F=f(g=>g.sendMessage),R=f(g=>g.abortSession),j=f(g=>g.retryTask),O=f(g=>g.retryingTaskKeys),G=Re(g=>g.openSettings),C=f(g=>g.reconnectSessionEvents),T=f(g=>g.clearError),[M,P]=h.useState(null),L=s?E.find(g=>g.sessionId===s.sessionId&&g.projectPath===s.projectPath):void 0,ee=!!w&&((n==null?void 0:n.kind)==="navigation"||!(n!=null&&n.sessionRef)||ze(n.sessionRef,s)),Q=(n==null?void 0:n.failureCode)??((I=L==null?void 0:L.taskFailure)==null?void 0:I.code),Z=((n==null?void 0:n.kind)==="execution"||n!=null&&n.failureCode)&&Q?t(Ft(Q)):w==="queue_full"?t("chat.error.queueFull"):w==="turn_unavailable"||w==="turn_active"?t("chat.error.turnChanged"):w,J=c==="connecting"||c==="reconnecting",te=r&&c!=="connected",A=s?`session:${de(s)}`:"session:temporary",z=h.useMemo(()=>ua(a),[a]),q=s?de(s):"temporary-session",V=!!(s&&(L!=null&&L.taskRetryAvailable)&&(!Q||Dt(Q)))&&((n==null?void 0:n.kind)==="execution"||(n==null?void 0:n.kind)==="task_action"),H=(n==null?void 0:n.kind)==="execution"&&(Q==="authentication"||Q==="permission"||Q==="model_unavailable"),$=s?O.includes(de(s)):!1;h.useEffect(()=>{P(null)},[q]);const W=async g=>K(f.getState())?!1:F({content:g.content,modelId:g.modelId,reasoningEffort:g.reasoningEffort,serviceTier:g.serviceTier,responseVerbosity:g.responseVerbosity,communicationStyle:g.communicationStyle,...g.outputSchema?{outputSchema:g.outputSchema}:{},attachments:g.attachments.map(ye=>({type:"image",content:ye.dataUrl,mimeType:ye.mimeType,name:ye.name}))}),Y=()=>{if(!K(f.getState()))return R()},he=async()=>{if(!K(f.getState())){if(H){T(),G("models");return}if(V&&s){T(),await j(s).catch(()=>{});return}if((n==null?void 0:n.kind)==="execution"&&z){P({...z,revision:Date.now()}),T();return}T(),requestAnimationFrame(()=>Ct())}},ce=V?t($?"chat.error.action.retryingTask":"chat.error.action.retryTask"):H?t("chat.error.action.checkModels"):(n==null?void 0:n.kind)==="execution"&&z?t("chat.error.action.editResend"):(n==null?void 0:n.kind)==="submission"?t("chat.error.action.returnDraft"):null;return e.jsxs("div",{"data-chat-view":!0,className:"flex h-full flex-col bg-[hsl(var(--deck-canvas))]",children:[e.jsxs("div",{"data-chat-history":!0,className:"contents",children:[ee&&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(Ae,{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((n==null?void 0:n.kind)==="submission"?"chat.error.title.submission":(n==null?void 0:n.kind)==="execution"?"chat.error.title.execution":(n==null?void 0:n.kind)==="navigation"?"chat.error.title.navigation":"chat.error.title.generic")})," ",Z]}),ce&&e.jsxs("button",{type:"button",onClick:()=>void he(),disabled:$,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:[V?$?e.jsx(_,{className:"h-3 w-3 animate-spin"}):e.jsx(fe,{className:"h-3 w-3"}):e.jsx(it,{className:"h-3 w-3"}),ce]}),e.jsx("button",{type:"button",onClick:T,"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:"✕"})]}),(J||c==="offline")&&e.jsxs("div",{role:c==="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:[J?e.jsx(_,{className:"h-3.5 w-3.5 shrink-0 animate-spin"}):e.jsx(Nt,{className:"h-3.5 w-3.5 shrink-0"}),e.jsx("span",{className:"min-w-0 flex-1",children:t(J?"chat.connection.reconnecting":"chat.connection.offline")}),c==="offline"&&e.jsxs("button",{type:"button",onClick:()=>{K(f.getState())||C().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(tt,{className:"h-3 w-3"}),t("chat.connection.retry")]})]}),e.jsx(es,{}),e.jsx(lt,{messages:a,isLoading:k},s?de(s):"temporary-session"),e.jsx(ia,{}),e.jsx(ea,{})]}),e.jsxs("div",{"data-chat-composer-dock":!0,className:"contents",children:[e.jsx(ma,{messages:a,isLoading:k,isStreaming:r,isStopping:o,errorMessage:ee?Z:null},q),e.jsx(Ws,{}),e.jsx(Gs,{}),e.jsx(Qs,{queue:S?null:y,mutation:p,onMutate:N,onRefresh:m}),e.jsx(Ys,{recovery:S?null:i,stopping:o,onStop:Y}),e.jsx(da,{activity:S||i!=null&&i.snapshot||x||L!=null&&L.pendingInteraction?null:l,memory:S?null:u}),e.jsx(St,{draftKey:A,draft:M==null?void 0:M.content,draftAttachments:M==null?void 0:M.attachments,draftRevision:M==null?void 0:M.revision,onSend:W,onAbort:Y,disabled:k||te,isStreaming:r,isStopping:o,pendingSteeringCount:v,pendingInputDelivery:b,recoveredSteeringCount:d,workspacePath:s==null?void 0:s.projectPath},A),e.jsx("div",{"data-chat-primary-status":!0,className:"contents",children:e.jsx(ut,{})})]})]})}export{Ea as ChatView};