blade-code 0.10.85 → 0.10.86

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 (58) hide show
  1. package/dist/blade.js +2 -2
  2. package/dist/{chunk-7wjqw574.js → chunk-00xsfm2j.js} +1 -1
  3. package/dist/{chunk-1jyr0t4q.js → chunk-0nb8999e.js} +1 -1
  4. package/dist/{chunk-72th07qj.js → chunk-2dq84j8s.js} +1 -1
  5. package/dist/{chunk-syg4pnbr.js → chunk-2ps02f7j.js} +1 -1
  6. package/dist/{chunk-a0nb3aad.js → chunk-4y34e9ty.js} +1 -1
  7. package/dist/{chunk-y8fswz6h.js → chunk-6n63ev2e.js} +1 -1
  8. package/dist/{chunk-bvzzq0jb.js → chunk-90b512gm.js} +1 -1
  9. package/dist/{chunk-q4c1nv7m.js → chunk-9erhm3gg.js} +1 -1
  10. package/dist/{chunk-1gv7095w.js → chunk-9vmxd900.js} +1 -1
  11. package/dist/{chunk-1khv7fp2.js → chunk-9zm7v41x.js} +1 -1
  12. package/dist/{chunk-0nsrw84g.js → chunk-b1mh28yd.js} +1 -1
  13. package/dist/{chunk-mhq9p8mm.js → chunk-b8p2mwq9.js} +1 -1
  14. package/dist/{chunk-9ye1s8tj.js → chunk-bthb5c55.js} +1 -1
  15. package/dist/{chunk-99h419nm.js → chunk-bwt1djsp.js} +1 -1
  16. package/dist/{chunk-rg3bvddy.js → chunk-cdx9tebt.js} +1 -1
  17. package/dist/{chunk-ax95qw8w.js → chunk-deeh2eq1.js} +1 -1
  18. package/dist/{chunk-xkb0zrjj.js → chunk-gk79etn6.js} +1 -1
  19. package/dist/{chunk-7md9r31q.js → chunk-gzjt969t.js} +1 -1
  20. package/dist/{chunk-1q3z3ryy.js → chunk-hazs43pe.js} +1 -1
  21. package/dist/chunk-hm92k82b.js +1 -0
  22. package/dist/{chunk-kzzzzymt.js → chunk-hxgzj76t.js} +1 -1
  23. package/dist/{chunk-fevtj34k.js → chunk-j2s2g9ep.js} +1 -1
  24. package/dist/{chunk-tbbc90bs.js → chunk-k6m9wmsq.js} +1 -1
  25. package/dist/{chunk-ff5y1ba2.js → chunk-mp90dsxs.js} +1 -1
  26. package/dist/{chunk-c7sx7pa4.js → chunk-p3jvzk1f.js} +1 -1
  27. package/dist/{chunk-h1gapq0a.js → chunk-t5d4p0gc.js} +1 -1
  28. package/dist/{chunk-7qa8rfmy.js → chunk-tap68662.js} +1 -1
  29. package/dist/{chunk-7ne59gra.js → chunk-vt654hsf.js} +1 -1
  30. package/dist/{chunk-d7v34g3f.js → chunk-wktx761x.js} +2 -2
  31. package/dist/chunk-x564avfw.js +1 -0
  32. package/dist/{chunk-knwa4gmn.js → chunk-x89n28mq.js} +1 -1
  33. package/dist/{chunk-cxe0ghk2.js → chunk-xwtx2vng.js} +1 -1
  34. package/dist/{chunk-jw8zwqyg.js → chunk-yq5vm0hf.js} +1 -1
  35. package/dist/{chunk-hm782j80.js → chunk-z21es9vg.js} +1 -1
  36. package/dist/{chunk-htt5c847.js → chunk-zg8g2jcr.js} +1 -1
  37. package/dist/{chunk-ppyqrdqc.js → chunk-zpbbcdme.js} +3 -3
  38. package/dist/{chunk-21rjwgc2.js → chunk-zpryec89.js} +1 -1
  39. package/dist/web/assets/ChatView-juDcmnHV.js +18 -0
  40. package/dist/web/assets/{CodeBlockHighlighter-DeJNC14V.js → CodeBlockHighlighter-BR4c98oZ.js} +1 -1
  41. package/dist/web/assets/FilePreview-DKgh-Chb.js +8 -0
  42. package/dist/web/assets/{KanbanBoard-DvHAwhcw.js → KanbanBoard-CQU0UQP8.js} +1 -1
  43. package/dist/web/assets/{MarkdownRenderer-BY51R1Fj.js → MarkdownRenderer-BVPIxk31.js} +3 -3
  44. package/dist/web/assets/{SettingsModal-CZGKcV1S.js → SettingsModal-CuUrUdWR.js} +1 -1
  45. package/dist/web/assets/{TaskSwitcher-DgeqVRAB.js → TaskSwitcher-DB7by2ch.js} +1 -1
  46. package/dist/web/assets/{TerminalPanel-KOLgH_tg.js → TerminalPanel-BN9ftZUH.js} +1 -1
  47. package/dist/web/assets/index-BdnOTMNi.css +1 -0
  48. package/dist/web/assets/index-ebnhtfFC.js +11 -0
  49. package/dist/web/assets/{teamService-Bxs4R7Al.js → teamService-CFKFv0qS.js} +1 -1
  50. package/dist/web/assets/{vendor-icons-DovdPN7M.js → vendor-icons-CX5BfgqQ.js} +1 -1
  51. package/dist/web/index.html +3 -3
  52. package/package.json +1 -1
  53. package/dist/chunk-kvk1bbqj.js +0 -1
  54. package/dist/chunk-znv9g3mt.js +0 -1
  55. package/dist/web/assets/ChatView-DMPNX1fC.js +0 -18
  56. package/dist/web/assets/FilePreview-qWMpc2P_.js +0 -8
  57. package/dist/web/assets/index-BNeDPN7E.css +0 -1
  58. package/dist/web/assets/index-DHX-G3RT.js +0 -11
@@ -1,2 +1,2 @@
1
- import{Hh as S}from"./chunk-c7sx7pa4.js";import{$h as f}from"./chunk-6jsmac0q.js";import*as $ from"fs/promises";import*as K from"path";import j from"semver";import{ProxyAgent as H,fetch as I}from"undici";function R(){return process.env.HTTPS_PROXY||process.env.HTTP_PROXY||process.env.https_proxy||process.env.http_proxy}function N(){let q=R();if(q)try{return new H(q)}catch(z){console.warn(`[proxyFetch] Invalid proxy URL: ${q}`)}return}async function M(q,z={}){let{timeout:W=30000,signal:Q,...B}=z;if(Q?.aborted)throw new DOMException("The operation was aborted.","AbortError");let J=N(),X=new AbortController,Y=!1,F=setTimeout(()=>{Y=!0,X.abort()},W),b=()=>X.abort();Q?.addEventListener("abort",b);try{let Z={method:B.method,headers:B.headers,body:B.body,signal:X.signal,dispatcher:J};return await I(q.toString(),Z)}catch(Z){if(Z instanceof Error&&Z.name==="AbortError"){if(Y)throw Error(`Request timeout after ${W}ms`);throw Z}throw Z}finally{clearTimeout(F),Q?.removeEventListener("abort",b)}}var w="blade-code",y="https://cdn.jsdelivr.net/npm/blade-code@latest/CHANGELOG.md",G=K.join(process.env.HOME||process.env.USERPROFILE||".",".blade"),O=K.join(G,"version-cache.json"),P=3600000,k=`https://registry.npmjs.org/${w}/latest`;async function L(){try{if(process.env.BLADE_VERSION)return process.env.BLADE_VERSION;return S()}catch{return"unknown"}}async function T(){try{let q=await $.readFile(O,"utf-8"),z=JSON.parse(q);if(Date.now()-z.checkedAt<P)return z;return{...z,checkedAt:0}}catch{return null}}async function D(q){try{await $.mkdir(G,{recursive:!0,mode:493}),await $.writeFile(O,JSON.stringify(q,null,2))}catch{}}async function x(){try{let q=await M(k,{timeout:5000,headers:{Accept:"application/json"}});if(!q.ok)return null;return(await q.json()).version||null}catch{return null}}async function _(q=!1){let z=await L(),W=y;if(z==="unknown")return{currentVersion:z,latestVersion:null,hasUpdate:!1,shouldPrompt:!1,releaseNotesUrl:W,error:"Unable to determine current version"};let Q=await T(),B=Q?.skipUntilVersion,J=null;if(!q&&Q?.latestVersion&&Q.checkedAt>0)J=Q.latestVersion;else if(J=await x(),J)await D({latestVersion:J,checkedAt:Date.now(),skipUntilVersion:B});else if(Q?.latestVersion)await D({checkedAt:0,skipUntilVersion:B});if(!J||!j.valid(J))return{currentVersion:z,latestVersion:null,hasUpdate:!1,shouldPrompt:!1,releaseNotesUrl:W,error:"Unable to check for updates"};if(j.lt(J,z))J=z,await D({latestVersion:J,checkedAt:Date.now(),skipUntilVersion:B});let X=j.gt(J,z),Y=X;if(X&&B)Y=j.gt(J,B);return{currentVersion:z,latestVersion:J,hasUpdate:X,shouldPrompt:Y,releaseNotesUrl:W}}async function u(q){let z=await T();await D({latestVersion:z?.latestVersion??q,checkedAt:z?.checkedAt||Date.now(),skipUntilVersion:q})}function g(){return`npm install -g ${w}@latest --registry https://registry.npmjs.org`}async function C(){let{spawn:q}=await import("child_process");return new Promise((z)=>{let W=g(),Q=q(W,{stdio:"inherit",shell:!0});Q.on("close",(B)=>{if(B===0)z({success:!0,message:"Upgrade successful! Please restart blade."});else z({success:!1,message:`Upgrade failed (exit code: ${B})`})}),Q.on("error",(B)=>{z({success:!1,message:`Upgrade failed: ${B.message}`})})})}async function V(){try{let q=await _();return q.shouldPrompt?q:null}catch{return null}}
1
+ import{Hh as S}from"./chunk-p3jvzk1f.js";import{$h as f}from"./chunk-6jsmac0q.js";import*as $ from"fs/promises";import*as K from"path";import j from"semver";import{ProxyAgent as H,fetch as I}from"undici";function R(){return process.env.HTTPS_PROXY||process.env.HTTP_PROXY||process.env.https_proxy||process.env.http_proxy}function N(){let q=R();if(q)try{return new H(q)}catch(z){console.warn(`[proxyFetch] Invalid proxy URL: ${q}`)}return}async function M(q,z={}){let{timeout:W=30000,signal:Q,...B}=z;if(Q?.aborted)throw new DOMException("The operation was aborted.","AbortError");let J=N(),X=new AbortController,Y=!1,F=setTimeout(()=>{Y=!0,X.abort()},W),b=()=>X.abort();Q?.addEventListener("abort",b);try{let Z={method:B.method,headers:B.headers,body:B.body,signal:X.signal,dispatcher:J};return await I(q.toString(),Z)}catch(Z){if(Z instanceof Error&&Z.name==="AbortError"){if(Y)throw Error(`Request timeout after ${W}ms`);throw Z}throw Z}finally{clearTimeout(F),Q?.removeEventListener("abort",b)}}var w="blade-code",y="https://cdn.jsdelivr.net/npm/blade-code@latest/CHANGELOG.md",G=K.join(process.env.HOME||process.env.USERPROFILE||".",".blade"),O=K.join(G,"version-cache.json"),P=3600000,k=`https://registry.npmjs.org/${w}/latest`;async function L(){try{if(process.env.BLADE_VERSION)return process.env.BLADE_VERSION;return S()}catch{return"unknown"}}async function T(){try{let q=await $.readFile(O,"utf-8"),z=JSON.parse(q);if(Date.now()-z.checkedAt<P)return z;return{...z,checkedAt:0}}catch{return null}}async function D(q){try{await $.mkdir(G,{recursive:!0,mode:493}),await $.writeFile(O,JSON.stringify(q,null,2))}catch{}}async function x(){try{let q=await M(k,{timeout:5000,headers:{Accept:"application/json"}});if(!q.ok)return null;return(await q.json()).version||null}catch{return null}}async function _(q=!1){let z=await L(),W=y;if(z==="unknown")return{currentVersion:z,latestVersion:null,hasUpdate:!1,shouldPrompt:!1,releaseNotesUrl:W,error:"Unable to determine current version"};let Q=await T(),B=Q?.skipUntilVersion,J=null;if(!q&&Q?.latestVersion&&Q.checkedAt>0)J=Q.latestVersion;else if(J=await x(),J)await D({latestVersion:J,checkedAt:Date.now(),skipUntilVersion:B});else if(Q?.latestVersion)await D({checkedAt:0,skipUntilVersion:B});if(!J||!j.valid(J))return{currentVersion:z,latestVersion:null,hasUpdate:!1,shouldPrompt:!1,releaseNotesUrl:W,error:"Unable to check for updates"};if(j.lt(J,z))J=z,await D({latestVersion:J,checkedAt:Date.now(),skipUntilVersion:B});let X=j.gt(J,z),Y=X;if(X&&B)Y=j.gt(J,B);return{currentVersion:z,latestVersion:J,hasUpdate:X,shouldPrompt:Y,releaseNotesUrl:W}}async function u(q){let z=await T();await D({latestVersion:z?.latestVersion??q,checkedAt:z?.checkedAt||Date.now(),skipUntilVersion:q})}function g(){return`npm install -g ${w}@latest --registry https://registry.npmjs.org`}async function C(){let{spawn:q}=await import("child_process");return new Promise((z)=>{let W=g(),Q=q(W,{stdio:"inherit",shell:!0});Q.on("close",(B)=>{if(B===0)z({success:!0,message:"Upgrade successful! Please restart blade."});else z({success:!1,message:`Upgrade failed (exit code: ${B})`})}),Q.on("error",(B)=>{z({success:!1,message:`Upgrade failed: ${B.message}`})})})}async function V(){try{let q=await _();return q.shouldPrompt?q:null}catch{return null}}
2
2
  export{_ as a,u as b,g as c,C as d,V as e};
@@ -25,7 +25,7 @@ import{yf as YO}from"./chunk-272swnyr.js";import{Fg as qO,Hg as S,Kg as y}from".
25
25
  `):void 0}}async executeNotificationHooks(O,q,Q){let Z="message"in q?q.message:"";if(O.length===0)return{suppress:!1,message:Z};let Y=[],$=!1,X=Z;for(let W of O)try{let J=await this.executeHook(W,q,Q);if(!J.success){if(J.warning)Y.push(J.warning);continue}if(J.output?.suppressOutput){$=!0;break}if(J.stdout&&J.stdout.trim())X=J.stdout.trim()}catch(J){let G=J instanceof Error?J.message:String(J);Y.push(`Hook failed: ${G}`)}return{suppress:$,message:X,warning:Y.length>0?Y.join(`
26
26
  `):void 0}}async executeCompactionHooks(O,q,Q){if(O.length===0)return{blockCompaction:!1};let Z=[];for(let Y of O)try{let $=await this.executeHook(Y,q,Q);if(!$.success){if($.warning)Z.push($.warning);continue}let X=$.output?.hookSpecificOutput;if(X&&"blockCompaction"in X&&X.blockCompaction)return{blockCompaction:!0,blockReason:X.blockReason,warning:Z.length>0?Z.join(`
27
27
  `):void 0}}catch($){let X=$ instanceof Error?$.message:String($);Z.push(`Hook failed: ${X}`)}return{blockCompaction:!1,warning:Z.length>0?Z.join(`
28
- `):void 0}}async executeHook(O,q,Q){if(O.type!=="function"){let Y=await A.getInstance().getStatus(Q.projectDir,Q.config);if(Y.state!=="trusted"){let $=`${Y.trustRoot}:${Y.currentDigest}:${Y.state}`;if(!this.trustWarnings.has($)){if(this.trustWarnings.size>=512)this.trustWarnings.clear();this.trustWarnings.add($),$O.warn(`[HookTrust] Skipping configured hooks for ${Y.trustRoot}: ${Y.state}`)}return{success:!0,hook:O,warning:`Hook skipped: project hook trust is ${Y.state}`}}}let Z=this.withHookEnvironment(Q,O);if(O.type==="command")return this.executeCommandHook(O,q,Z);if(O.type==="prompt")return this.executePromptHook(O,q,Z);if(O.type==="function")return this.executeFunctionHook(O,q,Z);if(O.type==="http")return this.executeHttpHook(O,q,Z);throw Error(`Hook type ${O.type} not supported`)}async executeCommandHook(O,q,Q){let Z=(O.timeout??Q.config.defaultTimeout??60)*1000;try{let Y=await this.processExecutor.execute(O.command,q,Q,Z);return this.outputParser.parse(Y,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}catch(Y){return{success:!1,blocking:!1,error:Y instanceof Error?Y.message:String(Y),hook:O}}}async executePromptHook(O,q,Q){let Z=(O.timeout??Q.config.defaultTimeout??60)*1000;try{let Y=await this.getOrCreateChatService(O.model,Q),$="hook_event_name"in q?String(q.hook_event_name):"Unknown",X=this.buildPromptHookSystemMessage(O,$),W=JSON.stringify(q,null,2),J=new AbortController,G=setTimeout(()=>J.abort(),Z),L;try{L=(await Y.chat([{role:"system",content:X},{role:"user",content:W}],void 0,J.signal,{providerAdmission:{sessionId:Q.sessionId,ownerId:Q.sessionId,requestClass:"background"}})).content}catch(z){if(J.signal.aborted||z instanceof Error&&z.name==="AbortError")return this.outputParser.parse({stdout:"",stderr:"",exitCode:0,timedOut:!0},O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior});throw z}finally{clearTimeout(G)}let F=this.extractJsonFromLLMResponse(L);return this.outputParser.parse({stdout:F,stderr:"",exitCode:0,timedOut:!1},O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}catch(Y){return $O.warn(`[PromptHook] 执行失败: ${Y instanceof Error?Y.message:String(Y)}`),{success:!1,blocking:!1,error:Y instanceof Error?Y.message:String(Y),hook:O}}}async executeFunctionHook(O,q,Q){let Z=(O.timeout??10)*1000;try{let Y=await this.runFunctionWithTimeout(O.handler,q,Q,Z);if(Y===void 0||Y===null)return{success:!0,hook:O};let $={stdout:JSON.stringify(Y),stderr:"",exitCode:0,timedOut:!1};return this.outputParser.parse($,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}catch(Y){if(Y.isTimeout){let $={stdout:"",stderr:`Function hook timeout after ${Z}ms`,exitCode:124,timedOut:!0};return this.outputParser.parse($,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}return{success:!1,blocking:!1,error:Y instanceof Error?Y.message:String(Y),hook:O}}}runFunctionWithTimeout(O,q,Q,Z){return new Promise((Y,$)=>{let X=!1,W=setTimeout(()=>{if(X)return;X=!0;let G=Object.assign(Error(`Function hook timed out after ${Z}ms`),{isTimeout:!0});$(G)},Z),J=()=>{if(X)return;X=!0,clearTimeout(W),$(Error("Function hook aborted"))};Q.abortSignal?.addEventListener("abort",J,{once:!0}),Promise.resolve().then(()=>O(q,Q)).then((G)=>{if(X)return;X=!0,clearTimeout(W),Q.abortSignal?.removeEventListener("abort",J),Y(G)},(G)=>{if(X)return;X=!0,clearTimeout(W),Q.abortSignal?.removeEventListener("abort",J),$(G)})})}async executeHttpHook(O,q,Q){let Z=(O.timeout??10)*1000,Y=O.maxResponseBytes??262144,$=Math.max(1,(O.retries??0)+1);try{e(O.url,Q.config.httpPolicy)}catch(G){return{success:!1,blocking:!0,error:G instanceof Error?G.message:String(G),hook:O}}let X={"Content-Type":"application/json",...OO(O.headers)},W=JSON.stringify(q),J;for(let G=0;G<$;G++){if(G>0){let V=Math.min(2**G*200,5000);await new Promise((B)=>setTimeout(B,V))}let L=new AbortController,F=setTimeout(()=>L.abort(),Z),z=()=>L.abort();Q.abortSignal?.addEventListener("abort",z,{once:!0});try{let V=await fetch(O.url,{method:"POST",headers:X,body:W,redirect:"manual",signal:L.signal});if(V.status>=300&&V.status<400){J=Error(`HTTP hook received redirect (${V.status}); redirects are disabled`);continue}if(!V.ok){if(J=Error(`HTTP hook returned ${V.status} ${V.statusText}`),V.status>=400&&V.status<500)break;continue}let U={stdout:await HO(V,Y),stderr:"",exitCode:0,timedOut:!1};return this.outputParser.parse(U,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}catch(V){let B=V.name==="AbortError"||V.code==="ABORT_ERR";if(B&&Q.abortSignal?.aborted){J=Error("HTTP hook aborted by caller");break}if(B){let U={stdout:"",stderr:`HTTP hook timeout after ${Z}ms`,exitCode:124,timedOut:!0};if(G===$-1)return this.outputParser.parse(U,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior});J=Error(`HTTP hook timeout attempt ${G+1}`);continue}J=V}finally{clearTimeout(F),Q.abortSignal?.removeEventListener("abort",z)}}return{success:!1,blocking:!1,error:J?.message??"HTTP hook failed",hook:O}}async getOrCreateChatService(O,q){let Q=this.sessionResourceKey(q.sessionId,q.projectDir),Z=`${Q}\x00${O||"__default__"}`,Y=this.chatServiceCache.get(Z);if(Y)return Y;let{ensureStoreInitialized:$,getConfig:X}=await import("./chunk-cxe0ghk2.js"),{createChatServiceAsync:W}=await import("./chunk-xj65p2sn.js"),{resolveModelConfig:J}=await import("./chunk-x2rraka3.js"),{resolveWorkspaceModelResources:G}=await import("./chunk-syg4pnbr.js");await $();let L=X();if(!L)throw Error("PromptHook: 配置未初始化");let F=this.sessionModelResources.get(Q)??await G(q.projectDir,L),z=O?F.config.models.find((B)=>B.id===O):F.config.models.find((B)=>B.id===F.config.currentModelId)??F.config.models[0];if(!z)throw Error("PromptHook: 无法获取模型配置。请确保至少配置了一个模型。");let V=await W(J(z,F.config,"off",F.catalog).chat);return this.chatServiceCache.set(Z,V),V}sessionResourceKey(O,q){return`${O}\x00${DO.resolve(q)}`}withSessionEnvironment(O){let q=this.sessionEnvironments.get(this.sessionResourceKey(O.sessionId,O.projectDir));return q?{...O,environment:q}:O}withHookEnvironment(O,q){let Q=this.withSessionEnvironment(O);if(!q.source)return Q;return{...Q,environment:{...Q.environment,BLADE_PLUGIN_ROOT:q.source.pluginRoot,CLAUDE_PLUGIN_ROOT:q.source.pluginRoot,BLADE_PLUGIN_NAME:q.source.pluginName}}}buildPromptHookSystemMessage(O,q){let Q=yO[q]||"{ ... 根据事件类型返回相应字段 }";return`你是一个代码质量评估器,作为 Hook 在 ${q} 事件中被触发。
28
+ `):void 0}}async executeHook(O,q,Q){if(O.type!=="function"){let Y=await A.getInstance().getStatus(Q.projectDir,Q.config);if(Y.state!=="trusted"){let $=`${Y.trustRoot}:${Y.currentDigest}:${Y.state}`;if(!this.trustWarnings.has($)){if(this.trustWarnings.size>=512)this.trustWarnings.clear();this.trustWarnings.add($),$O.warn(`[HookTrust] Skipping configured hooks for ${Y.trustRoot}: ${Y.state}`)}return{success:!0,hook:O,warning:`Hook skipped: project hook trust is ${Y.state}`}}}let Z=this.withHookEnvironment(Q,O);if(O.type==="command")return this.executeCommandHook(O,q,Z);if(O.type==="prompt")return this.executePromptHook(O,q,Z);if(O.type==="function")return this.executeFunctionHook(O,q,Z);if(O.type==="http")return this.executeHttpHook(O,q,Z);throw Error(`Hook type ${O.type} not supported`)}async executeCommandHook(O,q,Q){let Z=(O.timeout??Q.config.defaultTimeout??60)*1000;try{let Y=await this.processExecutor.execute(O.command,q,Q,Z);return this.outputParser.parse(Y,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}catch(Y){return{success:!1,blocking:!1,error:Y instanceof Error?Y.message:String(Y),hook:O}}}async executePromptHook(O,q,Q){let Z=(O.timeout??Q.config.defaultTimeout??60)*1000;try{let Y=await this.getOrCreateChatService(O.model,Q),$="hook_event_name"in q?String(q.hook_event_name):"Unknown",X=this.buildPromptHookSystemMessage(O,$),W=JSON.stringify(q,null,2),J=new AbortController,G=setTimeout(()=>J.abort(),Z),L;try{L=(await Y.chat([{role:"system",content:X},{role:"user",content:W}],void 0,J.signal,{providerAdmission:{sessionId:Q.sessionId,ownerId:Q.sessionId,requestClass:"background"}})).content}catch(z){if(J.signal.aborted||z instanceof Error&&z.name==="AbortError")return this.outputParser.parse({stdout:"",stderr:"",exitCode:0,timedOut:!0},O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior});throw z}finally{clearTimeout(G)}let F=this.extractJsonFromLLMResponse(L);return this.outputParser.parse({stdout:F,stderr:"",exitCode:0,timedOut:!1},O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}catch(Y){return $O.warn(`[PromptHook] 执行失败: ${Y instanceof Error?Y.message:String(Y)}`),{success:!1,blocking:!1,error:Y instanceof Error?Y.message:String(Y),hook:O}}}async executeFunctionHook(O,q,Q){let Z=(O.timeout??10)*1000;try{let Y=await this.runFunctionWithTimeout(O.handler,q,Q,Z);if(Y===void 0||Y===null)return{success:!0,hook:O};let $={stdout:JSON.stringify(Y),stderr:"",exitCode:0,timedOut:!1};return this.outputParser.parse($,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}catch(Y){if(Y.isTimeout){let $={stdout:"",stderr:`Function hook timeout after ${Z}ms`,exitCode:124,timedOut:!0};return this.outputParser.parse($,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}return{success:!1,blocking:!1,error:Y instanceof Error?Y.message:String(Y),hook:O}}}runFunctionWithTimeout(O,q,Q,Z){return new Promise((Y,$)=>{let X=!1,W=setTimeout(()=>{if(X)return;X=!0;let G=Object.assign(Error(`Function hook timed out after ${Z}ms`),{isTimeout:!0});$(G)},Z),J=()=>{if(X)return;X=!0,clearTimeout(W),$(Error("Function hook aborted"))};Q.abortSignal?.addEventListener("abort",J,{once:!0}),Promise.resolve().then(()=>O(q,Q)).then((G)=>{if(X)return;X=!0,clearTimeout(W),Q.abortSignal?.removeEventListener("abort",J),Y(G)},(G)=>{if(X)return;X=!0,clearTimeout(W),Q.abortSignal?.removeEventListener("abort",J),$(G)})})}async executeHttpHook(O,q,Q){let Z=(O.timeout??10)*1000,Y=O.maxResponseBytes??262144,$=Math.max(1,(O.retries??0)+1);try{e(O.url,Q.config.httpPolicy)}catch(G){return{success:!1,blocking:!0,error:G instanceof Error?G.message:String(G),hook:O}}let X={"Content-Type":"application/json",...OO(O.headers)},W=JSON.stringify(q),J;for(let G=0;G<$;G++){if(G>0){let V=Math.min(2**G*200,5000);await new Promise((B)=>setTimeout(B,V))}let L=new AbortController,F=setTimeout(()=>L.abort(),Z),z=()=>L.abort();Q.abortSignal?.addEventListener("abort",z,{once:!0});try{let V=await fetch(O.url,{method:"POST",headers:X,body:W,redirect:"manual",signal:L.signal});if(V.status>=300&&V.status<400){J=Error(`HTTP hook received redirect (${V.status}); redirects are disabled`);continue}if(!V.ok){if(J=Error(`HTTP hook returned ${V.status} ${V.statusText}`),V.status>=400&&V.status<500)break;continue}let U={stdout:await HO(V,Y),stderr:"",exitCode:0,timedOut:!1};return this.outputParser.parse(U,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}catch(V){let B=V.name==="AbortError"||V.code==="ABORT_ERR";if(B&&Q.abortSignal?.aborted){J=Error("HTTP hook aborted by caller");break}if(B){let U={stdout:"",stderr:`HTTP hook timeout after ${Z}ms`,exitCode:124,timedOut:!0};if(G===$-1)return this.outputParser.parse(U,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior});J=Error(`HTTP hook timeout attempt ${G+1}`);continue}J=V}finally{clearTimeout(F),Q.abortSignal?.removeEventListener("abort",z)}}return{success:!1,blocking:!1,error:J?.message??"HTTP hook failed",hook:O}}async getOrCreateChatService(O,q){let Q=this.sessionResourceKey(q.sessionId,q.projectDir),Z=`${Q}\x00${O||"__default__"}`,Y=this.chatServiceCache.get(Z);if(Y)return Y;let{ensureStoreInitialized:$,getConfig:X}=await import("./chunk-xwtx2vng.js"),{createChatServiceAsync:W}=await import("./chunk-xj65p2sn.js"),{resolveModelConfig:J}=await import("./chunk-x2rraka3.js"),{resolveWorkspaceModelResources:G}=await import("./chunk-2ps02f7j.js");await $();let L=X();if(!L)throw Error("PromptHook: 配置未初始化");let F=this.sessionModelResources.get(Q)??await G(q.projectDir,L),z=O?F.config.models.find((B)=>B.id===O):F.config.models.find((B)=>B.id===F.config.currentModelId)??F.config.models[0];if(!z)throw Error("PromptHook: 无法获取模型配置。请确保至少配置了一个模型。");let V=await W(J(z,F.config,"off",F.catalog).chat);return this.chatServiceCache.set(Z,V),V}sessionResourceKey(O,q){return`${O}\x00${DO.resolve(q)}`}withSessionEnvironment(O){let q=this.sessionEnvironments.get(this.sessionResourceKey(O.sessionId,O.projectDir));return q?{...O,environment:q}:O}withHookEnvironment(O,q){let Q=this.withSessionEnvironment(O);if(!q.source)return Q;return{...Q,environment:{...Q.environment,BLADE_PLUGIN_ROOT:q.source.pluginRoot,CLAUDE_PLUGIN_ROOT:q.source.pluginRoot,BLADE_PLUGIN_NAME:q.source.pluginName}}}buildPromptHookSystemMessage(O,q){let Q=yO[q]||"{ ... 根据事件类型返回相应字段 }";return`你是一个代码质量评估器,作为 Hook 在 ${q} 事件中被触发。
29
29
 
30
30
  `+`## 评估指令
31
31
  ${O.prompt}
@@ -1,2 +1,2 @@
1
- import{Hh as d,Jh as h}from"./chunk-c7sx7pa4.js";var q={debug:{alias:"d",type:"string",describe:'Enable debug mode with optional category filtering (e.g., "agent,ui" or "!chat,!loop")',group:"Debug Options:"},model:{type:"string",describe:"Override the current run model using a model config ID (TUI / print / headless)",group:"AI Options:"},print:{alias:"p",type:"boolean",describe:"Print response and exit (useful for pipes)",group:"Output Options:"},headless:{type:"boolean",describe:"Run full agent loop without Ink UI and print all events to the terminal",group:"Output Options:"},"output-format":{alias:["outputFormat"],type:"string",choices:["text","json","stream-json","jsonl"],default:"text",describe:"Output format: --print supports text|json|stream-json; --headless supports text|jsonl",group:"Output Options:"},"json-schema":{alias:["jsonSchema"],type:"string",describe:"Inline JSON Schema for the turn-scoped structured final response",group:"Output Options:"},"output-schema":{alias:["outputSchema"],type:"string",describe:"Path to a JSON Schema file for the structured final response",group:"Output Options:"},"include-partial-messages":{alias:["includePartialMessages"],type:"boolean",describe:"Include partial message chunks as they arrive",group:"Output Options:"},"input-format":{alias:["inputFormat"],type:"string",choices:["text","stream-json"],default:"text",describe:"Input format",group:"Input Options:"},"replay-user-messages":{alias:["replayUserMessages"],type:"boolean",describe:"Re-emit user messages from stdin",group:"Input Options:"},"allowed-tools":{alias:["allowedTools"],type:"array",string:!0,describe:"Comma or space-separated list of tool names to allow",group:"Security Options:"},"disallowed-tools":{alias:["disallowedTools"],type:"array",string:!0,describe:"Comma or space-separated list of tool names to deny",group:"Security Options:"},"mcp-config":{alias:["mcpConfig"],type:"array",string:!0,describe:"Load MCP servers from JSON files or strings",group:"MCP Options:"},"system-prompt":{alias:["systemPrompt"],type:"string",describe:"System prompt to use for the session (replaces default)",group:"AI Options:"},"append-system-prompt":{alias:["appendSystemPrompt"],type:"string",describe:"Append a system prompt to the default system prompt",group:"AI Options:"},"max-turns":{alias:["maxTurns"],type:"number",describe:"Maximum conversation turns (-1: unlimited, 0: disable chat, N>0: limit to N turns)",group:"AI Options:",default:void 0},"max-concurrent-tasks":{alias:["maxConcurrentTasks"],type:"number",describe:"Maximum top-level tasks running concurrently in this process",group:"AI Options:",default:void 0},"max-queued-tasks":{alias:["maxQueuedTasks"],type:"number",describe:"Maximum top-level tasks waiting for an admission slot",group:"AI Options:",default:void 0},"max-queued-task-bytes":{alias:["maxQueuedTaskBytes"],type:"number",describe:"Maximum retained bytes across queued top-level tasks",group:"AI Options:",default:void 0},"max-resident-session-runtimes":{alias:["maxResidentSessionRuntimes"],type:"number",describe:"Maximum initialized Session runtimes resident in this process",group:"AI Options:",default:void 0},"session-runtime-idle-ms":{alias:["sessionRuntimeIdleMs"],type:"number",describe:"Idle time before an evictable Web Session runtime is disposed",group:"AI Options:",default:void 0},"permission-mode":{alias:["permissionMode"],type:"string",choices:["default","autoEdit","yolo","plan"],describe:"Permission mode (default: ask for non-read tools, autoEdit: auto-approve edits, yolo: auto-approve all, plan: reserved)",group:"Security Options:"},yolo:{type:"boolean",describe:"Auto-approve all tools (shortcut for --permission-mode=yolo)",group:"Security Options:"},"trust-workspace":{alias:["trustWorkspace"],type:"boolean",describe:"Trust the current workspace before loading project models, MCP, LSP, permissions, or plugins",group:"Security Options:"},continue:{alias:"c",type:"boolean",describe:"Continue the most recent conversation",group:"Session Options:"},resume:{alias:"r",describe:"Resume a conversation - provide a session ID or interactively select a conversation to resume",group:"Session Options:",coerce:(b)=>{if(b===void 0||b===!0||b==="")return"true";return String(b)}},"fork-session":{alias:["forkSession"],type:"boolean",describe:"Create a new session ID when resuming",group:"Session Options:"},settings:{type:"string",describe:"Path to a settings JSON file or JSON string",group:"Configuration:"},"add-dir":{alias:["addDir"],type:"array",string:!0,describe:"Additional directories to allow tool access to",group:"Security Options:"},ide:{type:"boolean",describe:"Automatically connect to IDE on startup",group:"Integration:"},acp:{type:"boolean",describe:"Run in ACP (Agent Client Protocol) mode for IDE integration",group:"Integration:"},"strict-mcp-config":{alias:["strictMcpConfig"],type:"boolean",describe:"Only use MCP servers from --mcp-config",group:"MCP Options:"},"session-id":{alias:["sessionId"],type:"string",describe:"Use a specific session ID for the conversation",group:"Session Options:"},agents:{type:"string",describe:"JSON object defining custom agents",group:"AI Options:"},"setting-sources":{alias:["settingSources"],type:"string",describe:"Comma-separated list of setting sources to load",group:"Configuration:"},"plugin-dir":{alias:["pluginDir"],type:"array",string:!0,describe:"Load plugins from specified directories",group:"Plugin Options:"}},w={scriptName:"blade",usage:"$0 [command] [options]",description:h(),version:d(),locale:"en",showHelpOnFail:!0,demandCommand:!1,recommendCommands:!0,strict:!1};
1
+ import{Hh as d,Jh as h}from"./chunk-p3jvzk1f.js";var q={debug:{alias:"d",type:"string",describe:'Enable debug mode with optional category filtering (e.g., "agent,ui" or "!chat,!loop")',group:"Debug Options:"},model:{type:"string",describe:"Override the current run model using a model config ID (TUI / print / headless)",group:"AI Options:"},print:{alias:"p",type:"boolean",describe:"Print response and exit (useful for pipes)",group:"Output Options:"},headless:{type:"boolean",describe:"Run full agent loop without Ink UI and print all events to the terminal",group:"Output Options:"},"output-format":{alias:["outputFormat"],type:"string",choices:["text","json","stream-json","jsonl"],default:"text",describe:"Output format: --print supports text|json|stream-json; --headless supports text|jsonl",group:"Output Options:"},"json-schema":{alias:["jsonSchema"],type:"string",describe:"Inline JSON Schema for the turn-scoped structured final response",group:"Output Options:"},"output-schema":{alias:["outputSchema"],type:"string",describe:"Path to a JSON Schema file for the structured final response",group:"Output Options:"},"include-partial-messages":{alias:["includePartialMessages"],type:"boolean",describe:"Include partial message chunks as they arrive",group:"Output Options:"},"input-format":{alias:["inputFormat"],type:"string",choices:["text","stream-json"],default:"text",describe:"Input format",group:"Input Options:"},"replay-user-messages":{alias:["replayUserMessages"],type:"boolean",describe:"Re-emit user messages from stdin",group:"Input Options:"},"allowed-tools":{alias:["allowedTools"],type:"array",string:!0,describe:"Comma or space-separated list of tool names to allow",group:"Security Options:"},"disallowed-tools":{alias:["disallowedTools"],type:"array",string:!0,describe:"Comma or space-separated list of tool names to deny",group:"Security Options:"},"mcp-config":{alias:["mcpConfig"],type:"array",string:!0,describe:"Load MCP servers from JSON files or strings",group:"MCP Options:"},"system-prompt":{alias:["systemPrompt"],type:"string",describe:"System prompt to use for the session (replaces default)",group:"AI Options:"},"append-system-prompt":{alias:["appendSystemPrompt"],type:"string",describe:"Append a system prompt to the default system prompt",group:"AI Options:"},"max-turns":{alias:["maxTurns"],type:"number",describe:"Maximum conversation turns (-1: unlimited, 0: disable chat, N>0: limit to N turns)",group:"AI Options:",default:void 0},"max-concurrent-tasks":{alias:["maxConcurrentTasks"],type:"number",describe:"Maximum top-level tasks running concurrently in this process",group:"AI Options:",default:void 0},"max-queued-tasks":{alias:["maxQueuedTasks"],type:"number",describe:"Maximum top-level tasks waiting for an admission slot",group:"AI Options:",default:void 0},"max-queued-task-bytes":{alias:["maxQueuedTaskBytes"],type:"number",describe:"Maximum retained bytes across queued top-level tasks",group:"AI Options:",default:void 0},"max-resident-session-runtimes":{alias:["maxResidentSessionRuntimes"],type:"number",describe:"Maximum initialized Session runtimes resident in this process",group:"AI Options:",default:void 0},"session-runtime-idle-ms":{alias:["sessionRuntimeIdleMs"],type:"number",describe:"Idle time before an evictable Web Session runtime is disposed",group:"AI Options:",default:void 0},"permission-mode":{alias:["permissionMode"],type:"string",choices:["default","autoEdit","yolo","plan"],describe:"Permission mode (default: ask for non-read tools, autoEdit: auto-approve edits, yolo: auto-approve all, plan: reserved)",group:"Security Options:"},yolo:{type:"boolean",describe:"Auto-approve all tools (shortcut for --permission-mode=yolo)",group:"Security Options:"},"trust-workspace":{alias:["trustWorkspace"],type:"boolean",describe:"Trust the current workspace before loading project models, MCP, LSP, permissions, or plugins",group:"Security Options:"},continue:{alias:"c",type:"boolean",describe:"Continue the most recent conversation",group:"Session Options:"},resume:{alias:"r",describe:"Resume a conversation - provide a session ID or interactively select a conversation to resume",group:"Session Options:",coerce:(b)=>{if(b===void 0||b===!0||b==="")return"true";return String(b)}},"fork-session":{alias:["forkSession"],type:"boolean",describe:"Create a new session ID when resuming",group:"Session Options:"},settings:{type:"string",describe:"Path to a settings JSON file or JSON string",group:"Configuration:"},"add-dir":{alias:["addDir"],type:"array",string:!0,describe:"Additional directories to allow tool access to",group:"Security Options:"},ide:{type:"boolean",describe:"Automatically connect to IDE on startup",group:"Integration:"},acp:{type:"boolean",describe:"Run in ACP (Agent Client Protocol) mode for IDE integration",group:"Integration:"},"strict-mcp-config":{alias:["strictMcpConfig"],type:"boolean",describe:"Only use MCP servers from --mcp-config",group:"MCP Options:"},"session-id":{alias:["sessionId"],type:"string",describe:"Use a specific session ID for the conversation",group:"Session Options:"},agents:{type:"string",describe:"JSON object defining custom agents",group:"AI Options:"},"setting-sources":{alias:["settingSources"],type:"string",describe:"Comma-separated list of setting sources to load",group:"Configuration:"},"plugin-dir":{alias:["pluginDir"],type:"array",string:!0,describe:"Load plugins from specified directories",group:"Plugin Options:"}},w={scriptName:"blade",usage:"$0 [command] [options]",description:h(),version:d(),locale:"en",showHelpOnFail:!0,demandCommand:!1,recommendCommands:!0,strict:!1};
2
2
  export{q as ud,w as vd};
@@ -1,4 +1,4 @@
1
- import{ra as C,sa as m0,xa as z3,ya as m9,za as u0}from"./chunk-mhq9p8mm.js";import{Aa as W6,Ca as n3,Ea as a3,Fa as UZ,Xa as o3}from"./chunk-tpxs85cg.js";import{$a as a$,Bb as v5,Cb as eJ,Db as _J,Fb as Z2,Gb as IJ,Lb as W7,Ob as X7,Ya as A$,Za as F1,_a as M9,ab as K9,bb as T9,cb as D9,db as R9,eb as P9,fb as L7,jb as X0,lb as $5,ob as O5,qb as G4,rb as F5,sb as D5,ub as U8,vb as U$}from"./chunk-y8fswz6h.js";import{$b as _9,Fc as OZ,Gc as p0,Hc as D1,Ic as fJ,Jc as kJ,Mc as X3,Qc as Y7,Ub as F0,Vb as f1,Vc as yJ,Wb as m$,Wc as vJ,Xb as N2,Yb as GZ,Yc as o,Zb as K5,_b as G5,ac as q9,bc as SJ,uc as P5,vc as L0,wc as Z$}from"./chunk-xkb0zrjj.js";import{$c as A7,Zc as u,_c as b7,ad as s$}from"./chunk-d2pwwdab.js";import{bd as t3,ed as e3,nd as $Y,td as ZY}from"./chunk-r77pcb0f.js";import{Ed as Y8,Fd as Z8}from"./chunk-skg520wq.js";import{$d as i$,Rd as B5,Sd as K0,Td as y,Wd as B0,Xd as Z5,Yd as B1,Zd as S$,_d as w4,ae as Z7,fe as G1}from"./chunk-9ye1s8tj.js";import{ge as $1}from"./chunk-g9xjcfrf.js";import{le as J7,me as e9,re as iJ,se as J5}from"./chunk-b2p9qm6j.js";import{ue as P0,ve as u$}from"./chunk-0q5bz3nm.js";import{we as Z3}from"./chunk-44dzrn0p.js";import{Ae as TJ,ye as MJ,ze as CJ}from"./chunk-ax95qw8w.js";import{$e as Y5,Be as Q5,Ce as U5,De as V5,Fe as H5,Ge as z5,He as x$,Ie as R7,Ke as G$,Le as J$,Me as o0,Ne as Z6,Oe as z1,Pe as k5,Qe as W1,Re as X1,Se as PJ,We as u4,Ye as S0,Ze as V$,af as xJ}from"./chunk-h1gapq0a.js";import{cf as k$,ef as Q$,ff as c2,gf as bZ,hf as AZ,if as g1,jf as jZ,kf as MZ,lf as M2}from"./chunk-sr4zv59p.js";import{mf as E3,of as RJ,pf as R5,qf as W8}from"./chunk-ww51801m.js";import{sf as ZZ,uf as j0}from"./chunk-hm782j80.js";import{vf as F2,wf as KZ,xf as D2,yf as U1}from"./chunk-272swnyr.js";import{$f as t$,Af as dZ,Ag as jJ,Bg as Q0,Ff as pZ,Hf as o4,Mf as H3,Qf as cZ,Sf as NJ,Uf as A9,Vf as j9,cg as F9,mg as p9,ng as c9,og as l9,pg as i9,qg as L4,rg as r9,sg as P$,tg as n9,ug as a9,vg as o9,xg as SZ,zg as gJ}from"./chunk-21rjwgc2.js";import{Eg as b$}from"./chunk-7m5q8vxf.js";import{Fg as j2,Gg as s5,Hg as O,Ig as y7,Jg as S,Kg as l}from"./chunk-sk8h4m9m.js";import{Mg as DJ,Og as BJ}from"./chunk-hg8d4vhj.js";import{Rg as f2,Tg as M}from"./chunk-sb84vdcf.js";import{th as a}from"./chunk-ffa6hhee.js";import{yh as bJ,zh as AJ}from"./chunk-t1633e8m.js";import{Ah as N3,Dh as q3}from"./chunk-m5f934fh.js";import{Hh as M3}from"./chunk-c7sx7pa4.js";import{Nh as hJ,Oh as v0}from"./chunk-rwvaapta.js";import{Sh as w2,Uh as T$,Wh as wJ,Xh as NZ,Zh as t}from"./chunk-shr5cg46.js";import{$h as t0}from"./chunk-6jsmac0q.js";import{randomUUID as a5}from"crypto";import{randomUUID as EY}from"node:crypto";var DY=String.raw`
1
+ import{ra as C,sa as m0,xa as z3,ya as m9,za as u0}from"./chunk-b8p2mwq9.js";import{Aa as W6,Ca as n3,Ea as a3,Fa as UZ,Xa as o3}from"./chunk-tpxs85cg.js";import{$a as a$,Bb as v5,Cb as eJ,Db as _J,Fb as Z2,Gb as IJ,Lb as W7,Ob as X7,Ya as A$,Za as F1,_a as M9,ab as K9,bb as T9,cb as D9,db as R9,eb as P9,fb as L7,jb as X0,lb as $5,ob as O5,qb as G4,rb as F5,sb as D5,ub as U8,vb as U$}from"./chunk-6n63ev2e.js";import{$b as _9,Fc as OZ,Gc as p0,Hc as D1,Ic as fJ,Jc as kJ,Mc as X3,Qc as Y7,Ub as F0,Vb as f1,Vc as yJ,Wb as m$,Wc as vJ,Xb as N2,Yb as GZ,Yc as o,Zb as K5,_b as G5,ac as q9,bc as SJ,uc as P5,vc as L0,wc as Z$}from"./chunk-gk79etn6.js";import{$c as A7,Zc as u,_c as b7,ad as s$}from"./chunk-d2pwwdab.js";import{bd as t3,ed as e3,nd as $Y,td as ZY}from"./chunk-r77pcb0f.js";import{Ed as Y8,Fd as Z8}from"./chunk-skg520wq.js";import{$d as i$,Rd as B5,Sd as K0,Td as y,Wd as B0,Xd as Z5,Yd as B1,Zd as S$,_d as w4,ae as Z7,fe as G1}from"./chunk-bthb5c55.js";import{ge as $1}from"./chunk-g9xjcfrf.js";import{le as J7,me as e9,re as iJ,se as J5}from"./chunk-b2p9qm6j.js";import{ue as P0,ve as u$}from"./chunk-0q5bz3nm.js";import{we as Z3}from"./chunk-44dzrn0p.js";import{Ae as TJ,ye as MJ,ze as CJ}from"./chunk-deeh2eq1.js";import{$e as Y5,Be as Q5,Ce as U5,De as V5,Fe as H5,Ge as z5,He as x$,Ie as R7,Ke as G$,Le as J$,Me as o0,Ne as Z6,Oe as z1,Pe as k5,Qe as W1,Re as X1,Se as PJ,We as u4,Ye as S0,Ze as V$,af as xJ}from"./chunk-t5d4p0gc.js";import{cf as k$,ef as Q$,ff as c2,gf as bZ,hf as AZ,if as g1,jf as jZ,kf as MZ,lf as M2}from"./chunk-sr4zv59p.js";import{mf as E3,of as RJ,pf as R5,qf as W8}from"./chunk-ww51801m.js";import{sf as ZZ,uf as j0}from"./chunk-z21es9vg.js";import{vf as F2,wf as KZ,xf as D2,yf as U1}from"./chunk-272swnyr.js";import{$f as t$,Af as dZ,Ag as jJ,Bg as Q0,Ff as pZ,Hf as o4,Mf as H3,Qf as cZ,Sf as NJ,Uf as A9,Vf as j9,cg as F9,mg as p9,ng as c9,og as l9,pg as i9,qg as L4,rg as r9,sg as P$,tg as n9,ug as a9,vg as o9,xg as SZ,zg as gJ}from"./chunk-zpryec89.js";import{Eg as b$}from"./chunk-7m5q8vxf.js";import{Fg as j2,Gg as s5,Hg as O,Ig as y7,Jg as S,Kg as l}from"./chunk-sk8h4m9m.js";import{Mg as DJ,Og as BJ}from"./chunk-hg8d4vhj.js";import{Rg as f2,Tg as M}from"./chunk-sb84vdcf.js";import{th as a}from"./chunk-ffa6hhee.js";import{yh as bJ,zh as AJ}from"./chunk-t1633e8m.js";import{Ah as N3,Dh as q3}from"./chunk-m5f934fh.js";import{Hh as M3}from"./chunk-p3jvzk1f.js";import{Nh as hJ,Oh as v0}from"./chunk-rwvaapta.js";import{Sh as w2,Uh as T$,Wh as wJ,Xh as NZ,Zh as t}from"./chunk-shr5cg46.js";import{$h as t0}from"./chunk-6jsmac0q.js";import{randomUUID as a5}from"crypto";import{randomUUID as EY}from"node:crypto";var DY=String.raw`
2
2
  const { spawn } = require('node:child_process');
3
3
  const [ownerPidValue, command, ...args] = process.argv.slice(1);
4
4
  const ownerPid = Number(ownerPidValue);
@@ -821,7 +821,7 @@ ${n}
821
821
  </approved-plan>
822
822
 
823
823
  IMPORTANT: Execute according to the approved plan above. Follow the steps exactly as specified.`;if(typeof _==="string")d0=_+V0;else d0=[..._,{type:"text",text:V0}]}k=yield*this.runLoop(d0,L,{...v,inputMessageId:void 0})}if(!this.sessionRuntime||!P)return k;let f=await this.sessionRuntime.recordGoalProgress({tokens:k.metadata?.tokensUsed??0,elapsedMs:k.metadata?.duration??0,prematureStopPattern:k.success?b9(k.finalMessage):void 0});if(f)yield{kind:"goal_updated",goal:f};if(!k.success||L.signal?.aborted){if(f=await this.sessionRuntime.pauseActiveGoal(L.signal?.aborted?"goal paused after user cancellation":k.error?.message??"goal paused after turn failure"),f)yield{kind:"goal_updated",goal:f}}if(k.success&&!L.signal?.aborted&&R<20)await this.sessionRuntime.waitForBackgroundSubagentFollowUp(P,L.signal);let g=k.success&&!L.signal?.aborted&&R<20,Z0=cQ(k);if(A=await this.sessionRuntime.finishTurn(P,{continuePending:g,...Z0?{acknowledgeInput:!0}:{},outcome:k.success&&!L.signal?.aborted?{status:"completed",turnsCount:k.metadata?.turnsCount??0,toolCallsCount:k.metadata?.toolCallsCount??0,durationMs:k.metadata?.duration??0}:{status:"aborted",cause:L.signal?.aborted?"cancelled":"failed",turnsCount:k.metadata?.turnsCount??0,toolCallsCount:k.metadata?.toolCallsCount??0,durationMs:k.metadata?.duration??0}}),A){R++,q=!0,N=!1,b=null,_="",T=void 0,j="",E=void 0,w=x(),yield{kind:"follow_up_started",queued:this.sessionRuntime.getPendingSteeringCount(),recovered:this.sessionRuntime.getRecoveredSteeringCount(),messages:m()};continue}if(!k.success||L.signal?.aborted)return k;if(f=await this.sessionRuntime.getGoal(),!f||f.status!=="active"&&f.status!=="verifying")return k;if(b=await this.sessionRuntime.beginGoalContinuation(),!b)return k;A=await this.sessionRuntime.beginTurn("goal"),q=!1,N=!0,_=C6(b),T=void 0,w=void 0,yield{kind:"goal_continuation_started",goal:b,continuation:b.continuationCount,...b.prematureStop?{prematureStopPattern:b.prematureStop.pattern,prematureStopCount:b.prematureStop.consecutiveCount}:{}},yield{kind:"goal_updated",goal:b}}}finally{if(this.sessionRuntime&&A)await this.sessionRuntime.finishTurn(A)}}let F=typeof H==="string"?H:H.filter((_)=>_.type==="text").map((_)=>_.text).join(`
824
- `),B={id:this.generateTaskId(),type:"simple",prompt:F};return{success:!0,finalMessage:(await this.executeTask(B)).content,metadata:{turnsCount:1,toolCallsCount:0,duration:0}}}async chat($,Z,J){let{drainLoop:Y}=await import("./chunk-7qa8rfmy.js");return Y(this.chatStream($,Z,J))}async*runPlanLoop($,Z,J){r.debug("Processing Plan mode message...");let{prompt:Y}=await j$({projectPath:Z.workspaceRoot||M(),mode:"plan",includeEnvironment:!0,environmentOptions:Z2,language:this.config.language,availableSkills:this.agentResources?.skills.generateAvailableSkillsList(),communicationStyle:this.sessionRuntime?.getCommunicationStyleConfiguration().selection,communicationStyleCatalog:this.sessionRuntime?.getCommunicationStyleCatalog(),projectRuleCatalog:this.sessionRuntime?.getProjectRuleCatalog(),projectInstructionSourcePath:this.sessionRuntime?.projectRoot}),W;if(typeof $==="string")W=d1($);else{let X=$.filter((Q)=>Q.type==="text");if(X.length>0){let Q=X[0];W=$.map((U)=>U===Q?{type:"text",text:d1(Q.text)}:U)}else W=[{type:"text",text:d1("")},...$]}return yield*this.executeLoop(W,Z,J,Y)}async*runLoop($,Z,J){r.debug("Processing enhanced chat message...");let Y=Z.systemPrompt??await this.buildSystemPromptOnDemand(Z.workspaceRoot||M());return yield*this.executeLoop($,Z,J,Y)}async buildSystemPromptOnDemand($){let Z=this.runtimeOptions.systemPrompt,J=this.runtimeOptions.appendSystemPrompt;return(await j$({projectPath:$,replaceDefault:Z,append:J,includeEnvironment:!0,environmentOptions:Z2,language:this.config.language,availableSkills:this.agentResources?.skills.generateAvailableSkillsList(),communicationStyle:this.sessionRuntime?.getCommunicationStyleConfiguration().selection,communicationStyleCatalog:this.sessionRuntime?.getCommunicationStyleCatalog(),projectRuleCatalog:this.sessionRuntime?.getProjectRuleCatalog(),projectInstructionSourcePath:this.sessionRuntime?.projectRoot})).prompt}executeLoop($,Z,J,Y){if(!this.isInitialized)throw Error("Agent未初始化");let W=this.buildLoopDependencies();return X7(W,$,Z,J,Y)}takeStartupAdoptedToolResultEvents(){return(this.sessionRuntime?.takeStartupAdoptedToolResults()??[]).flatMap(({call:Z,result:J})=>{let Y={id:Z.toolCallId,type:"function",function:{name:Z.toolName,arguments:JSON.stringify(Z.input)}},W=J.metadata&&typeof J.metadata==="object"&&!Array.isArray(J.metadata)?J.metadata:void 0,X=J.error===void 0,Q=J.output,U={success:X,llmContent:typeof Q==="string"||Q!==null&&typeof Q==="object"?Q:Q===null?J.error?`Subagent execution failed: ${J.error}.`:"":String(Q),...J.error?{error:{type:"execution_error",message:J.error}}:{},...W?{metadata:W}:{}},V=[{kind:"tool_result",toolCall:Y,result:U}],H=W7(Y,U);if(H)V.push(H);return V})}buildLoopDependencies(){return{chatService:this.chatService,toolExecutor:this.toolExecutor,executionEngine:this.executionEngine,config:this.config,runtimeOptions:this.runtimeOptions,currentModelMaxContextTokens:this.currentModelMaxContextTokens,activeSkillContext:this.activeSkillContext,onSkillActivated:($)=>{this.activeSkillContext=$,r.debug(`Skill "${$.skillName}" activated`+($.allowedTools?` with allowed tools: ${$.allowedTools.join(", ")}`:""))},onModelSwitch:($)=>this.switchModelIfNeeded($),applySkillToolRestrictions:($)=>this.applySkillToolRestrictions($),staticProjectRules:this.sessionRuntime?.getStaticProjectRules(),hydrateProjectRules:this.sessionRuntime?($)=>this.sessionRuntime.hydrateProjectRules($):void 0,resolveContextualProjectRules:this.sessionRuntime?($,Z,J,Y)=>this.sessionRuntime.resolveContextualProjectRules($,Z,J,Y):void 0}}async chatWithSystem($,Z){if(!this.isInitialized)throw Error("Agent未初始化");let J=[{role:"system",content:$},{role:"user",content:Z}];return(await this.chatService.chat(J)).content}getActiveTask(){return this.activeTask}getChatService(){return this.chatService}getContextManager(){return this.executionEngine?.getContextManager()}getStats(){return{initialized:this.isInitialized,activeTask:this.activeTask?.id,components:{chatService:this.chatService?"ready":"not_loaded",executionEngine:this.executionEngine?"ready":"not_loaded"}}}getAvailableTools(){return this.toolExecutor?this.toolExecutor.getRegistry().getAll():[]}getToolRegistry(){return this.toolExecutor.getRegistry()}applyToolWhitelist($){let Z=this.toolExecutor.getRegistry(),Y=Z.getAll().filter((W)=>!$.includes(W.name));for(let W of Y)Z.unregister(W.name);r.debug(`Applied tool whitelist: ${$.join(", ")} (removed ${Y.length} tools)`)}applyToolBlacklist($){let Z=this.toolExecutor.getRegistry(),J=new Set($);for(let Y of Z.getAll())if(J.has(Y.name))Z.unregister(Y.name);r.debug(`Applied tool blacklist: ${$.join(", ")}`)}getToolStats(){let $=this.getAvailableTools(),Z=new Map;return $.forEach((J)=>{let Y=Z.get(J.kind)||0;Z.set(J.kind,Y+1)}),{totalTools:$.length,toolsByKind:Object.fromEntries(Z),toolNames:$.map((J)=>J.name)}}async destroy(){if(this.destroyPromise)return this.destroyPromise;return this.destroyPromise=(async()=>{this.log("销毁Agent..."),await this.activeOperations.shutdown("agent-destroy");try{await this.legacyMcpRegistry?.disconnectAll(),this.legacyMcpRegistry=void 0,this.log("Agent已销毁")}catch($){throw this.error("Agent销毁失败",$),$}finally{this.toolExecutor.dispose(),this.isInitialized=!1}})(),this.destroyPromise}syncRuntimeState(){if(!this.sessionRuntime)return;this.chatService=this.sessionRuntime.getChatService(),this.executionEngine=this.sessionRuntime.getExecutionEngine(),this.attachmentCollector=this.sessionRuntime.getAttachmentCollector(),this.currentModelId=this.sessionRuntime.getCurrentModelId(),this.currentModelMaxContextTokens=this.sessionRuntime.getCurrentModelMaxContextTokens()}generateTaskId(){return`task_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}log($,Z){r.debug(`[MainAgent] ${$}`,Z||"")}error($,Z){r.error(`[MainAgent] ${$}`,Z||"")}async initializeSystemPrompt(){try{let $=this.runtimeOptions.systemPrompt,Z=this.runtimeOptions.appendSystemPrompt,J=await j$({projectPath:this.sessionRuntime?.workspaceRoot??M(),replaceDefault:$,append:Z,includeEnvironment:!1,language:this.config.language,availableSkills:this.agentResources?.skills.generateAvailableSkillsList(),communicationStyle:this.sessionRuntime?.getCommunicationStyleConfiguration().selection,communicationStyleCatalog:this.sessionRuntime?.getCommunicationStyleCatalog(),projectRuleCatalog:this.sessionRuntime?.getProjectRuleCatalog(),projectInstructionSourcePath:this.sessionRuntime?.projectRoot});if(J.prompt)this.log("系统提示配置验证成功"),r.debug(`[SystemPrompt] 可用来源: ${J.sources.filter((Y)=>Y.loaded).map((Y)=>Y.name).join(", ")}`)}catch($){this.error("系统提示配置验证失败",$)}}async registerBuiltinTools(){try{let $=await W5({sessionId:"default",configDir:t(),workspaceRoot:M(),resourceRoot:M(),agentResources:this.agentResources});r.debug(`Registering ${$.length} builtin tools...`),this.toolExecutor.getRegistry().registerAll($);let Z=this.toolExecutor.getRegistry().getAll().length;r.debug(`Builtin tools registered: ${Z} tools`),r.debug(`[Tools] ${this.toolExecutor.getRegistry().getAll().map((J)=>J.name).join(", ")}`),await this.registerMcpTools()}catch($){throw r.error("Failed to register builtin tools:",$),$}}async registerMcpTools(){try{let $=await k2({workspaceRoot:M(),storeServers:this.config.mcpServers??{},cliConfigs:this.runtimeOptions.mcpConfig,strictCliConfig:this.runtimeOptions.strictMcpConfig});if(Object.keys($).length===0){r.debug("No MCP servers configured");return}let Z=u0.createIsolated({artifactWriter:new m1(`legacy-${pQ()}`)});this.legacyMcpRegistry=Z;for(let[X,Q]of Object.entries($))try{r.debug(`Connecting to MCP server: ${X}`),await Z.registerServer(X,Q),r.debug(`MCP server "${X}" connected`)}catch(U){r.warn(`Warning: MCP server "${X}" connection failed:`,U)}let J=this.toolExecutor.getRegistry();J.setMcpCatalogBarrier(()=>Z.waitForCatalogIdle());let Y=Z.getCatalogSnapshot();J.replaceMcpTools(Y.tools),J.registerAll(r1(Z));let W=Z.getInstructionsSnapshot();if(J.queueMcpInstructionsChange({revision:W.revision,reason:"snapshot",replace:!0,instructions:W.instructions,removed:[]}),Z.on("catalogChanged",(X)=>{J.replaceMcpTools(X.tools,X)}),Z.on("contentCatalogChanged",(X)=>{J.queueMcpContentChange(X)}),Z.on("resourceUpdated",(X)=>{J.queueMcpResourceUpdated(X)}),Z.on("connectionLifecycleChanged",(X)=>{J.queueMcpConnectionChange(X)}),Z.on("log",(X)=>{J.queueMcpLog(X)}),Z.on("instructionsChanged",(X)=>{J.queueMcpInstructionsChange({revision:X.revision,reason:X.reason,replace:!1,instructions:X.action==="added"&&X.instruction?[{serverName:X.serverName,...X.instruction}]:[],removed:X.action==="removed"?[X.serverName]:[]})}),Y.tools.length>0)r.debug(`Registered ${Y.tools.length} MCP tools`),r.debug(`[MCP Tools] ${Y.tools.map((X)=>X.name).join(", ")}`)}catch($){r.warn("Failed to register MCP tools:",$)}}async loadSubagents(){let $=await S0(M());if(this.agentResources=Y5($),this.subagentRegistry=this.agentResources.subagents,this.runtimeOptions.agents?.length)this.subagentRegistry.applyOverrides(this.runtimeOptions.agents);let Z=this.subagentRegistry.getAllNames().length;if(Z>0)r.debug(`Loaded ${Z} subagents: ${this.subagentRegistry.getAllNames().join(", ")}`);else r.debug("No subagents configured")}applySkillToolRestrictions($){if(!this.activeSkillContext?.allowedTools)return $;let Z=this.activeSkillContext.allowedTools;r.debug(`Applying Skill tool restrictions: ${Z.join(", ")}`);let J=$.filter((Y)=>{if(Y.name==="ReadPromptArtifact")return!0;return Z.some((W)=>{if(W===Y.name)return!0;let X=W.match(/^(\w+)\(.*\)$/);if(X&&X[1]===Y.name)return!0;return!1})});return r.debug(`Filtered tools: ${J.map((Y)=>Y.name).join(", ")} (${J.length}/${$.length})`),J}clearSkillContext(){if(this.activeSkillContext)r.debug(`Skill "${this.activeSkillContext.skillName}" deactivated`),this.activeSkillContext=void 0}async processAtMentionsForContent($){if(!this.attachmentCollector)return $;if(typeof $==="string")return this.processAtMentions($);let Z=[];for(let Y of $)if(Y.type==="text")Z.push(Y.text);if(Z.length===0)return $;let J=Z.join(`
824
+ `),B={id:this.generateTaskId(),type:"simple",prompt:F};return{success:!0,finalMessage:(await this.executeTask(B)).content,metadata:{turnsCount:1,toolCallsCount:0,duration:0}}}async chat($,Z,J){let{drainLoop:Y}=await import("./chunk-tap68662.js");return Y(this.chatStream($,Z,J))}async*runPlanLoop($,Z,J){r.debug("Processing Plan mode message...");let{prompt:Y}=await j$({projectPath:Z.workspaceRoot||M(),mode:"plan",includeEnvironment:!0,environmentOptions:Z2,language:this.config.language,availableSkills:this.agentResources?.skills.generateAvailableSkillsList(),communicationStyle:this.sessionRuntime?.getCommunicationStyleConfiguration().selection,communicationStyleCatalog:this.sessionRuntime?.getCommunicationStyleCatalog(),projectRuleCatalog:this.sessionRuntime?.getProjectRuleCatalog(),projectInstructionSourcePath:this.sessionRuntime?.projectRoot}),W;if(typeof $==="string")W=d1($);else{let X=$.filter((Q)=>Q.type==="text");if(X.length>0){let Q=X[0];W=$.map((U)=>U===Q?{type:"text",text:d1(Q.text)}:U)}else W=[{type:"text",text:d1("")},...$]}return yield*this.executeLoop(W,Z,J,Y)}async*runLoop($,Z,J){r.debug("Processing enhanced chat message...");let Y=Z.systemPrompt??await this.buildSystemPromptOnDemand(Z.workspaceRoot||M());return yield*this.executeLoop($,Z,J,Y)}async buildSystemPromptOnDemand($){let Z=this.runtimeOptions.systemPrompt,J=this.runtimeOptions.appendSystemPrompt;return(await j$({projectPath:$,replaceDefault:Z,append:J,includeEnvironment:!0,environmentOptions:Z2,language:this.config.language,availableSkills:this.agentResources?.skills.generateAvailableSkillsList(),communicationStyle:this.sessionRuntime?.getCommunicationStyleConfiguration().selection,communicationStyleCatalog:this.sessionRuntime?.getCommunicationStyleCatalog(),projectRuleCatalog:this.sessionRuntime?.getProjectRuleCatalog(),projectInstructionSourcePath:this.sessionRuntime?.projectRoot})).prompt}executeLoop($,Z,J,Y){if(!this.isInitialized)throw Error("Agent未初始化");let W=this.buildLoopDependencies();return X7(W,$,Z,J,Y)}takeStartupAdoptedToolResultEvents(){return(this.sessionRuntime?.takeStartupAdoptedToolResults()??[]).flatMap(({call:Z,result:J})=>{let Y={id:Z.toolCallId,type:"function",function:{name:Z.toolName,arguments:JSON.stringify(Z.input)}},W=J.metadata&&typeof J.metadata==="object"&&!Array.isArray(J.metadata)?J.metadata:void 0,X=J.error===void 0,Q=J.output,U={success:X,llmContent:typeof Q==="string"||Q!==null&&typeof Q==="object"?Q:Q===null?J.error?`Subagent execution failed: ${J.error}.`:"":String(Q),...J.error?{error:{type:"execution_error",message:J.error}}:{},...W?{metadata:W}:{}},V=[{kind:"tool_result",toolCall:Y,result:U}],H=W7(Y,U);if(H)V.push(H);return V})}buildLoopDependencies(){return{chatService:this.chatService,toolExecutor:this.toolExecutor,executionEngine:this.executionEngine,config:this.config,runtimeOptions:this.runtimeOptions,currentModelMaxContextTokens:this.currentModelMaxContextTokens,activeSkillContext:this.activeSkillContext,onSkillActivated:($)=>{this.activeSkillContext=$,r.debug(`Skill "${$.skillName}" activated`+($.allowedTools?` with allowed tools: ${$.allowedTools.join(", ")}`:""))},onModelSwitch:($)=>this.switchModelIfNeeded($),applySkillToolRestrictions:($)=>this.applySkillToolRestrictions($),staticProjectRules:this.sessionRuntime?.getStaticProjectRules(),hydrateProjectRules:this.sessionRuntime?($)=>this.sessionRuntime.hydrateProjectRules($):void 0,resolveContextualProjectRules:this.sessionRuntime?($,Z,J,Y)=>this.sessionRuntime.resolveContextualProjectRules($,Z,J,Y):void 0}}async chatWithSystem($,Z){if(!this.isInitialized)throw Error("Agent未初始化");let J=[{role:"system",content:$},{role:"user",content:Z}];return(await this.chatService.chat(J)).content}getActiveTask(){return this.activeTask}getChatService(){return this.chatService}getContextManager(){return this.executionEngine?.getContextManager()}getStats(){return{initialized:this.isInitialized,activeTask:this.activeTask?.id,components:{chatService:this.chatService?"ready":"not_loaded",executionEngine:this.executionEngine?"ready":"not_loaded"}}}getAvailableTools(){return this.toolExecutor?this.toolExecutor.getRegistry().getAll():[]}getToolRegistry(){return this.toolExecutor.getRegistry()}applyToolWhitelist($){let Z=this.toolExecutor.getRegistry(),Y=Z.getAll().filter((W)=>!$.includes(W.name));for(let W of Y)Z.unregister(W.name);r.debug(`Applied tool whitelist: ${$.join(", ")} (removed ${Y.length} tools)`)}applyToolBlacklist($){let Z=this.toolExecutor.getRegistry(),J=new Set($);for(let Y of Z.getAll())if(J.has(Y.name))Z.unregister(Y.name);r.debug(`Applied tool blacklist: ${$.join(", ")}`)}getToolStats(){let $=this.getAvailableTools(),Z=new Map;return $.forEach((J)=>{let Y=Z.get(J.kind)||0;Z.set(J.kind,Y+1)}),{totalTools:$.length,toolsByKind:Object.fromEntries(Z),toolNames:$.map((J)=>J.name)}}async destroy(){if(this.destroyPromise)return this.destroyPromise;return this.destroyPromise=(async()=>{this.log("销毁Agent..."),await this.activeOperations.shutdown("agent-destroy");try{await this.legacyMcpRegistry?.disconnectAll(),this.legacyMcpRegistry=void 0,this.log("Agent已销毁")}catch($){throw this.error("Agent销毁失败",$),$}finally{this.toolExecutor.dispose(),this.isInitialized=!1}})(),this.destroyPromise}syncRuntimeState(){if(!this.sessionRuntime)return;this.chatService=this.sessionRuntime.getChatService(),this.executionEngine=this.sessionRuntime.getExecutionEngine(),this.attachmentCollector=this.sessionRuntime.getAttachmentCollector(),this.currentModelId=this.sessionRuntime.getCurrentModelId(),this.currentModelMaxContextTokens=this.sessionRuntime.getCurrentModelMaxContextTokens()}generateTaskId(){return`task_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}log($,Z){r.debug(`[MainAgent] ${$}`,Z||"")}error($,Z){r.error(`[MainAgent] ${$}`,Z||"")}async initializeSystemPrompt(){try{let $=this.runtimeOptions.systemPrompt,Z=this.runtimeOptions.appendSystemPrompt,J=await j$({projectPath:this.sessionRuntime?.workspaceRoot??M(),replaceDefault:$,append:Z,includeEnvironment:!1,language:this.config.language,availableSkills:this.agentResources?.skills.generateAvailableSkillsList(),communicationStyle:this.sessionRuntime?.getCommunicationStyleConfiguration().selection,communicationStyleCatalog:this.sessionRuntime?.getCommunicationStyleCatalog(),projectRuleCatalog:this.sessionRuntime?.getProjectRuleCatalog(),projectInstructionSourcePath:this.sessionRuntime?.projectRoot});if(J.prompt)this.log("系统提示配置验证成功"),r.debug(`[SystemPrompt] 可用来源: ${J.sources.filter((Y)=>Y.loaded).map((Y)=>Y.name).join(", ")}`)}catch($){this.error("系统提示配置验证失败",$)}}async registerBuiltinTools(){try{let $=await W5({sessionId:"default",configDir:t(),workspaceRoot:M(),resourceRoot:M(),agentResources:this.agentResources});r.debug(`Registering ${$.length} builtin tools...`),this.toolExecutor.getRegistry().registerAll($);let Z=this.toolExecutor.getRegistry().getAll().length;r.debug(`Builtin tools registered: ${Z} tools`),r.debug(`[Tools] ${this.toolExecutor.getRegistry().getAll().map((J)=>J.name).join(", ")}`),await this.registerMcpTools()}catch($){throw r.error("Failed to register builtin tools:",$),$}}async registerMcpTools(){try{let $=await k2({workspaceRoot:M(),storeServers:this.config.mcpServers??{},cliConfigs:this.runtimeOptions.mcpConfig,strictCliConfig:this.runtimeOptions.strictMcpConfig});if(Object.keys($).length===0){r.debug("No MCP servers configured");return}let Z=u0.createIsolated({artifactWriter:new m1(`legacy-${pQ()}`)});this.legacyMcpRegistry=Z;for(let[X,Q]of Object.entries($))try{r.debug(`Connecting to MCP server: ${X}`),await Z.registerServer(X,Q),r.debug(`MCP server "${X}" connected`)}catch(U){r.warn(`Warning: MCP server "${X}" connection failed:`,U)}let J=this.toolExecutor.getRegistry();J.setMcpCatalogBarrier(()=>Z.waitForCatalogIdle());let Y=Z.getCatalogSnapshot();J.replaceMcpTools(Y.tools),J.registerAll(r1(Z));let W=Z.getInstructionsSnapshot();if(J.queueMcpInstructionsChange({revision:W.revision,reason:"snapshot",replace:!0,instructions:W.instructions,removed:[]}),Z.on("catalogChanged",(X)=>{J.replaceMcpTools(X.tools,X)}),Z.on("contentCatalogChanged",(X)=>{J.queueMcpContentChange(X)}),Z.on("resourceUpdated",(X)=>{J.queueMcpResourceUpdated(X)}),Z.on("connectionLifecycleChanged",(X)=>{J.queueMcpConnectionChange(X)}),Z.on("log",(X)=>{J.queueMcpLog(X)}),Z.on("instructionsChanged",(X)=>{J.queueMcpInstructionsChange({revision:X.revision,reason:X.reason,replace:!1,instructions:X.action==="added"&&X.instruction?[{serverName:X.serverName,...X.instruction}]:[],removed:X.action==="removed"?[X.serverName]:[]})}),Y.tools.length>0)r.debug(`Registered ${Y.tools.length} MCP tools`),r.debug(`[MCP Tools] ${Y.tools.map((X)=>X.name).join(", ")}`)}catch($){r.warn("Failed to register MCP tools:",$)}}async loadSubagents(){let $=await S0(M());if(this.agentResources=Y5($),this.subagentRegistry=this.agentResources.subagents,this.runtimeOptions.agents?.length)this.subagentRegistry.applyOverrides(this.runtimeOptions.agents);let Z=this.subagentRegistry.getAllNames().length;if(Z>0)r.debug(`Loaded ${Z} subagents: ${this.subagentRegistry.getAllNames().join(", ")}`);else r.debug("No subagents configured")}applySkillToolRestrictions($){if(!this.activeSkillContext?.allowedTools)return $;let Z=this.activeSkillContext.allowedTools;r.debug(`Applying Skill tool restrictions: ${Z.join(", ")}`);let J=$.filter((Y)=>{if(Y.name==="ReadPromptArtifact")return!0;return Z.some((W)=>{if(W===Y.name)return!0;let X=W.match(/^(\w+)\(.*\)$/);if(X&&X[1]===Y.name)return!0;return!1})});return r.debug(`Filtered tools: ${J.map((Y)=>Y.name).join(", ")} (${J.length}/${$.length})`),J}clearSkillContext(){if(this.activeSkillContext)r.debug(`Skill "${this.activeSkillContext.skillName}" deactivated`),this.activeSkillContext=void 0}async processAtMentionsForContent($){if(!this.attachmentCollector)return $;if(typeof $==="string")return this.processAtMentions($);let Z=[];for(let Y of $)if(Y.type==="text")Z.push(Y.text);if(Z.length===0)return $;let J=Z.join(`
825
825
  `);try{let Y=await this.attachmentCollector.collect(J);if(Y.length===0)return $;r.debug(`Processed ${Y.length} @ file mentions in multimodal message`);let W=this.buildAttachmentText(Y);if(!W)return $;return[...$,{type:"text",text:W}]}catch(Y){return r.error("Failed to process @ mentions in multimodal message:",Y),$}}buildAttachmentText($){let Z=[],J=[];for(let W of $)if(W.type==="file"){let X=W.metadata?.lineRange?` (lines ${W.metadata.lineRange.start}${W.metadata.lineRange.end?`-${W.metadata.lineRange.end}`:""})`:"";Z.push(`<file path="${W.path}"${X?` range="${X}"`:""}>`,W.content,"</file>")}else if(W.type==="directory")Z.push(`<directory path="${W.path}">`,W.content,"</directory>");else if(W.type==="error")J.push(`- @${W.path}: ${W.error}`);let Y="";if(Z.length>0)Y+=`
826
826
 
827
827
  <system-reminder>
@@ -1631,7 +1631,7 @@ ${J}
1631
1631
  `)),{success:!0,message:"Schedules listed",content:V.join(`
1632
1632
  `)}}case"create":{let U=NK(X);if("error"in U)return Y.sendMessage(`创建失败:${U.error}`),{success:!1,error:U.error};let V={prompt:U.prompt,projectPath:Q,trigger:U.trigger,isolation:"worktree",permissionMode:"default",enabled:!0};try{let H=await $.create(V),z=H.nextRunAt?new Date(H.nextRunAt).toLocaleString():"(无)";return Y.sendMessage(`[OK] 已创建定时任务 \`${H.id}\`
1633
1633
  ${UZ(H.trigger)} · 下次运行: ${z}`),{success:!0,message:`Schedule ${H.id} created`}}catch(H){let z=H instanceof Error?H.message:String(H);return Y.sendMessage(`创建失败:${z}`),{success:!1,error:z}}}case"remove":case"rm":{let U=X[0];if(!U)return Y.sendMessage("用法:/schedule remove <id>"),{success:!1,error:"Missing schedule id"};let V=await $.remove(U);return Y.sendMessage(V?`[OK] 已删除 \`${U}\``:`未找到 \`${U}\``),{success:V,message:V?"Removed":"Not found"}}case"enable":case"disable":{let U=X[0];if(!U)return Y.sendMessage(`用法:/schedule ${W} <id>`),{success:!1,error:"Missing schedule id"};let V=await $.setEnabled(U,W==="enable");return Y.sendMessage(V?`[OK] 已${W==="enable"?"启用":"停用"} \`${U}\``:`未找到 \`${U}\``),{success:Boolean(V),message:V?"Updated":"Not found"}}case"run":{let U=X[0];if(!U)return Y.sendMessage("用法:/schedule run <id>"),{success:!1,error:"Missing schedule id"};try{return await bK(U),Y.sendMessage(`[OK] 已触发 \`${U}\``),{success:!0,message:"Schedule triggered"}}catch(V){let H=V instanceof Error?V.message:String(V);return Y.sendMessage(`运行失败:${H}`),{success:!1,error:H}}}default:return Y.sendMessage(`未知子命令: ${W}
1634
- 使用 /schedule 查看帮助`),{success:!1,error:`Unknown subcommand: ${W}`}}}}}var s3=AK();import*as R1 from"node:fs/promises";import*as P1 from"node:path";async function JY($,Z={}){let{maxResults:J=20,caseSensitive:Y=!1,projectPath:W,storagePath:X}=Z,Q=X??w2(W??M());if(!X){let G=await jK($,W??M(),J,Y);if(G)return G}let U;try{U=(await R1.readdir(Q)).filter((F)=>F.endsWith(".jsonl")&&!F.startsWith("agent_")).map((F)=>P1.join(Q,F))}catch{return[]}let H=(await Promise.all(U.map(async(G)=>{try{let F=await R1.stat(G);return{path:G,mtime:F.mtimeMs}}catch{return null}}))).filter((G)=>G!==null).sort((G,F)=>F.mtime-G.mtime).map((G)=>G.path),z=[],K=Y?$:$.toLowerCase();for(let G of H){if(z.length>=J)break;let F=P1.basename(G,".jsonl"),B=await MK(G,K,Y,F);if(z.push(...B),z.length>=J){z.length=J;break}}return z}async function jK($,Z,J,Y){try{let{syncAll:W}=await import("./chunk-w2sb1hy9.js"),X=await $Y();if(!X)return null;let{SessionService:Q}=await import("./chunk-kzzzzymt.js");await W(X,Q.projectionDeriverForSearch());let U=P1.resolve(Z),V=ZY(X,$,U,J*4),H=Y?$:$.toLowerCase(),z=[];for(let K of V){if(K.role!=="user"&&K.role!=="assistant")continue;let G=VZ(K.text,H,Y,K.session_id,K.role,K.timestamp??void 0,0);if(G)z.push(G);if(z.length>=J)break}return z}catch{return null}}async function MK($,Z,J,Y){try{let W=await R1.readFile($,"utf8"),Q=W.split(`
1634
+ 使用 /schedule 查看帮助`),{success:!1,error:`Unknown subcommand: ${W}`}}}}}var s3=AK();import*as R1 from"node:fs/promises";import*as P1 from"node:path";async function JY($,Z={}){let{maxResults:J=20,caseSensitive:Y=!1,projectPath:W,storagePath:X}=Z,Q=X??w2(W??M());if(!X){let G=await jK($,W??M(),J,Y);if(G)return G}let U;try{U=(await R1.readdir(Q)).filter((F)=>F.endsWith(".jsonl")&&!F.startsWith("agent_")).map((F)=>P1.join(Q,F))}catch{return[]}let H=(await Promise.all(U.map(async(G)=>{try{let F=await R1.stat(G);return{path:G,mtime:F.mtimeMs}}catch{return null}}))).filter((G)=>G!==null).sort((G,F)=>F.mtime-G.mtime).map((G)=>G.path),z=[],K=Y?$:$.toLowerCase();for(let G of H){if(z.length>=J)break;let F=P1.basename(G,".jsonl"),B=await MK(G,K,Y,F);if(z.push(...B),z.length>=J){z.length=J;break}}return z}async function jK($,Z,J,Y){try{let{syncAll:W}=await import("./chunk-w2sb1hy9.js"),X=await $Y();if(!X)return null;let{SessionService:Q}=await import("./chunk-hxgzj76t.js");await W(X,Q.projectionDeriverForSearch());let U=P1.resolve(Z),V=ZY(X,$,U,J*4),H=Y?$:$.toLowerCase(),z=[];for(let K of V){if(K.role!=="user"&&K.role!=="assistant")continue;let G=VZ(K.text,H,Y,K.session_id,K.role,K.timestamp??void 0,0);if(G)z.push(G);if(z.length>=J)break}return z}catch{return null}}async function MK($,Z,J,Y){try{let W=await R1.readFile($,"utf8"),Q=W.split(`
1635
1635
  `).flatMap((K,G)=>{if(!K.trim())return[];try{return[{event:JSON.parse(K),index:G}]}catch{return[]}});if(!Q.some(({event:K})=>K.type==="session_created"))return CK(Q,Z,J,Y);let V=new Map(Q.flatMap(({event:K,index:G})=>typeof K.id==="string"?[[K.id,G+1]]:[])),H=t3(e3(W,$)),z=new Map;for(let K of H){if(K.type==="message_created"&&(K.data.role==="user"||K.data.role==="assistant"))z.set(K.data.messageId,{role:K.data.role,content:[],timestamp:K.timestamp,lineNumber:V.get(K.id)??0});if(K.type==="part_created"&&K.data.partType==="text"){let G=z.get(K.data.messageId),F=K.data.payload.text;if(G&&typeof F==="string")G.content.push(F)}}return[...z.values()].flatMap((K)=>{let G=VZ(K.content.join(" "),Z,J,Y,K.role,K.timestamp,K.lineNumber);return G?[G]:[]})}catch{return[]}}function CK($,Z,J,Y){return $.flatMap(({event:W,index:X})=>{if(W.type!=="message")return[];let Q=W.message;if(Q?.role!=="user"&&Q?.role!=="assistant"||!Q.content)return[];let U=typeof Q.content==="string"?Q.content:Array.isArray(Q.content)?Q.content.filter((H)=>typeof H==="object"&&H!==null&&H.type==="text"&&typeof H.text==="string").map((H)=>H.text).join(" "):"",V=VZ(U,Z,J,Y,Q.role,typeof W.timestamp==="string"?W.timestamp:void 0,X+1);return V?[V]:[]})}function VZ($,Z,J,Y,W,X,Q){if(!$)return;let U=J?$:$.toLowerCase();if(!U.includes(Z))return;let V=U.indexOf(Z),H=Math.max(0,V-80),z=Math.min($.length,V+Z.length+80);return{sessionId:Y,role:W,content:(H>0?"...":"")+$.slice(H,z).replace(/\n/g," ")+(z<$.length?"...":""),timestamp:X,lineNumber:Q}}function YY($){if($.length===0)return"没有找到匹配的历史记录";let Z=[`**找到 ${$.length} 条匹配:**
1636
1636
  `];for(let J of $){let Y=J.timestamp?new Date(J.timestamp).toLocaleString("zh-CN",{timeZone:"Asia/Shanghai"}):"?",W=J.role==="user"?"\uD83D\uDC64":"\uD83E\uDD16";Z.push(`${W} \`${J.sessionId.slice(0,8)}\` (${Y})`),Z.push(` ${J.content}`),Z.push("")}return Z.join(`
1637
1637
  `)}var TK={name:"search",description:"Search past session transcripts",fullDescription:"搜索历史会话记录,查找过去的对话内容",usage:"/search <keyword>",aliases:["find","history"],category:"Session",examples:['/search 断路器 - 搜索包含"断路器"的历史对话',"/search edit tool - 搜索 edit tool 相关讨论"],async handler($,Z){let J=h(Z);if($.length===0)return J.sendMessage("**用法:** `/search <关键词>`\n\n在历史会话中搜索包含指定关键词的对话"),{success:!0,message:"显示帮助"};let Y=$.join(" ");J.sendMessage(`正在搜索: "${Y}" ...`);try{let W=await JY(Y,{maxResults:15,projectPath:Z.cwd}),X=YY(W);return J.sendMessage(X),{success:!0,message:`found ${W.length} results`,data:{matches:W.length}}}catch(W){let X=W instanceof Error?W.message:"未知错误";return J.sendMessage(`搜索失败: ${X}`),{success:!1,error:X}}}},WY=TK;var RK={name:"skills",description:"查看所有可用的 Skills",fullDescription:"显示所有已发现的 Skills 及其详细信息,包括名称、描述、来源和允许的工具。",usage:"/skills",category:"system",examples:["/skills"],handler:async($,Z)=>{try{let J=Z.workspaceRoot??Z.cwd;return await V$(J,async(Y)=>{await Y.skills.refresh(),X1(J),await W1(J)}),{success:!0,message:"show_skills_manager",data:{action:"show_skills_manager"}}}catch(J){let Y=`获取 Skills 失败: ${J instanceof Error?J.message:"未知错误"}`;return y().addAssistantMessage(Y),{success:!1,error:Y}}}},XY=RK;import PK from"node:path";function p5($){if($<1000)return`${$}ms`;let Z=Math.floor($/1000);if(Z<60)return`${Z}s`;let J=Math.floor(Z/60);if(J<60)return`${J}m ${Z%60}s`;return`${Math.floor(J/60)}h ${J%60}m`}function QY($){switch($){case"running":return"[RUNNING]";case"completed":case"exited":return"[OK]";case"failed":case"error":return"[FAIL]";case"killed":case"cancelled":return"[STOPPED]";default:return"[?]"}}function UY($,Z){if($.length<=Z)return $;return $.slice(0,Z-3)+"..."}async function SK($,Z){let J=h(Z),Y=$[0],W=e.getInstance(),X=U0.getInstance(),Q=Z.sessionId??"",U=Z.sessionId?{sessionId:Z.sessionId,projectPath:PK.resolve(Z.workspaceRoot??Z.cwd)}:void 0;if(Y==="resume"){let F=$[1],B=$.slice(2).join(" ").trim();if(!F||!B)return{success:!1,error:"Usage: /tasks resume <agentId> <prompt>"};if(!Z.subagents)return{success:!1,error:"This surface does not own a subagent runtime"};let D=await Z.subagents.resume(F,B),_=`Resumed \`${F}\` as \`${D.session.id}\` (depth ${D.session.resumeDepth}).`;return J.sendMessage(_),{success:!0,message:_,data:{action:"subagent_resumed",sourceAgentId:F,subagent:D.session}}}if(Y==="clean"){let F=X.cleanupExpiredSessionsForParent(U??Q,0);return J.sendMessage(`已清理 ${F} 个已完成的 Agent 会话`),{success:!0,message:`Cleaned ${F} agent sessions`}}let V=[`**后台任务列表**
@@ -1,4 +1,4 @@
1
- import{Eg as Y}from"./chunk-7m5q8vxf.js";import{Fg as on,Gg as F,Hg as o}from"./chunk-sk8h4m9m.js";import{Lg as ct,Mg as bt}from"./chunk-hg8d4vhj.js";import{Tg as x}from"./chunk-sb84vdcf.js";import{$g as kn,Ug as Jn,Vg as Xt,Wg as pt,_g as gt,ah as it,bh as Rt,ch as Ct,dh as un,eh as zt,fh as Bt,gh as On,hh as Kt,ih as Ut,jh as jn,kh as Ht,lh as Yt,mh as qt,nh as Vt,oh as Qt,ph as Gt}from"./chunk-hjr9r44k.js";import{th as fn}from"./chunk-ffa6hhee.js";import{wh as $t,zh as J}from"./chunk-t1633e8m.js";import{Hh as Pn,Ih as Ln}from"./chunk-c7sx7pa4.js";import{Oh as h}from"./chunk-rwvaapta.js";import{Zh as Tn}from"./chunk-shr5cg46.js";var Wt=/^[\x21\x23-\x5b\x5d-\x7e]+$/;function Zt(n){return n==="127.0.0.1"||n==="[::1]"||n.toLowerCase()==="localhost"}function R(n,t="MCP OAuth URL"){let M=new URL(n);if(M.username||M.password)throw Error(`${t} must not contain credentials`);if(M.protocol!=="https:"&&!(M.protocol==="http:"&&Zt(M.hostname)))throw Error(`${t} requires HTTPS; HTTP is allowed only for loopback servers`);return M}var U=async(n,t)=>{R(n,"MCP OAuth request URL");let M=await fetch(n,{...t,redirect:"manual"});if(M.status>=300&&M.status<400)throw await M.body?.cancel(),Error("MCP OAuth network requests must not follow redirects");return M};function k(n){let t=n.oauth;if(!t)return;let M=t;for(let u of["clientSecret","authorizationUrl","tokenUrl","redirectUri"])if(M[u]!==void 0)throw Error(`MCP OAuth "${u}" is not supported; use standards-based discovery`);if(t.enabled!==!0)return{enabled:!1};if(n.type!=="http"&&n.type!=="sse")throw Error("MCP OAuth is supported only for HTTP and SSE transports");if(!n.url)throw Error("MCP OAuth requires an MCP server URL");if(R(n.url,"MCP OAuth server URL"),Object.keys(n.headers??{}).find((u)=>u.toLowerCase()==="authorization"))throw Error("MCP OAuth cannot be combined with a configured Authorization header");let _=t.clientId?.trim();if(_&&_.length>4096)throw Error("MCP OAuth clientId exceeds 4096 characters");let S=t.scopes?.map((u)=>u.trim());if(S){if(S.length>32)throw Error("MCP OAuth supports at most 32 scopes");if(S.some((u)=>!u||u.length>128||!Wt.test(u)))throw Error("MCP OAuth scopes contain an invalid value");if(new Set(S).size!==S.length)throw Error("MCP OAuth scopes must not contain duplicates")}let r=t.callbackPort;if(r!==void 0&&(!Number.isInteger(r)||r<1024||r>65535))throw Error("MCP OAuth callbackPort must be between 1024 and 65535");return{enabled:!0,..._?{clientId:_}:{},...S?.length?{scopes:S}:{},...r!==void 0?{callbackPort:r}:{}}}import{randomUUID as v}from"node:crypto";import MM from"node:http";import{auth as cn}from"@modelcontextprotocol/sdk/client/auth.js";import _M from"open";import{createHash as Dt,randomUUID as Jt}from"node:crypto";import{constants as O,promises as L}from"node:fs";import j from"node:path";import kt from"write-file-atomic";var An=1,Ot=1048576,jt=5000,yt=50,Ft=/^[a-f0-9]{64}$/,lt=o.Object({client_id:o.String({minLength:1,maxLength:4096})},{additionalProperties:!0}),vt=o.Object({access_token:o.String({minLength:1,maxLength:65536}),token_type:o.String({minLength:1,maxLength:64}),expires_in:o.Optional(o.Number({minimum:0})),refresh_token:o.Optional(o.String({minLength:1,maxLength:65536})),scope:o.Optional(o.String({maxLength:16384})),id_token:o.Optional(o.String({minLength:1,maxLength:262144}))},{additionalProperties:!1}),nM=o.Unsafe({type:"object",properties:{authorizationServerUrl:o.String({format:"uri"}),resourceMetadataUrl:o.Optional(o.String({format:"uri"})),resourceMetadata:o.Optional(o.Unknown()),authorizationServerMetadata:o.Optional(o.Unknown())},required:["authorizationServerUrl"],additionalProperties:!1}),sn=o.Object({serverUrl:o.String({format:"uri"}),clientId:o.Optional(o.String({minLength:1,maxLength:4096})),clientInformation:o.Optional(lt),tokens:o.Optional(vt),tokenExpiresAt:o.Optional(o.Number({minimum:0})),discoveryState:o.Optional(nM),updatedAt:o.String({format:"date-time"})},{additionalProperties:!1}),En=o.Object({version:o.Literal(An),credentials:o.Record(o.String(),sn)},{additionalProperties:!1});function H(n,t){return n instanceof Error&&"code"in n&&n.code===t}function tM(n){if(!Number.isInteger(n)||n<=0)return!1;try{return process.kill(n,0),!0}catch(t){return H(t,"EPERM")}}function y(n){return structuredClone(n)}function mn(n){if(Object.keys(n.credentials).some((t)=>!Ft.test(t)))throw Error("MCP OAuth credential store contains an invalid identity")}function q(n){let t=new URL(n);return t.hash="",t.toString()}function l(n,t,M=[]){return Dt("sha256").update(JSON.stringify({serverUrl:q(n),clientId:t?.trim()||null,scopes:[...M].sort()})).digest("hex")}class I{static locks=new Y;stateRoot;tokenFilePath;constructor(n=Tn()){this.stateRoot=j.join(n,"mcp"),this.tokenFilePath=j.join(this.stateRoot,"oauth-credentials.json")}static coordinationStatsForTests(){return this.locks.getStats()}async getCredential(n){return I.locks.runExclusive(this.tokenFilePath,async()=>{let M=(await this.readStore()).credentials[n];return M?y(M):null})}async updateCredential(n,t){return this.runMutation(async(M)=>{let e=M.credentials[n],_=await t(e?y(e):null);if(_)M.credentials[n]=F(sn,_);else delete M.credentials[n];return _?y(M.credentials[n]):null})}async deleteCredential(n){await this.updateCredential(n,()=>null)}async listCredentialIds(){return I.locks.runExclusive(this.tokenFilePath,async()=>Object.keys((await this.readStore()).credentials).sort())}async runMutation(n){return I.locks.runExclusive(this.tokenFilePath,async()=>{let t=await this.acquireStoreLock();try{let M=await this.readStore(),e=await n(M);return await this.writeStore(M),e}finally{await t()}})}async ensureStateRoot(){await L.mkdir(this.stateRoot,{recursive:!0,mode:448});let n=await L.lstat(this.stateRoot);if(!n.isDirectory()||n.isSymbolicLink())throw Error("MCP OAuth credential root must be a regular directory");if(process.getuid&&n.uid!==process.getuid())throw Error("MCP OAuth credential root must be owned by the current user");if((n.mode&63)!==0)throw Error("MCP OAuth credential root permissions must not allow group access")}async readStore(){try{let n=await L.lstat(this.tokenFilePath);if(!n.isFile()||n.isSymbolicLink())throw Error("MCP OAuth credential store must be a regular file");if(process.getuid&&n.uid!==process.getuid())throw Error("MCP OAuth credential store must be owned by the current user");if((n.mode&511)!==384)throw Error("MCP OAuth credential store permissions must be 0600");if(n.size>Ot)throw Error("MCP OAuth credential store exceeds the 1 MiB limit");let t=JSON.parse(await L.readFile(this.tokenFilePath,"utf8")),M=on(En,t);if(!M.success)throw Error("MCP OAuth credential store has an invalid schema");return mn(M.data),M.data}catch(n){if(H(n,"ENOENT"))return{version:An,credentials:{}};throw n}}async writeStore(n){await this.ensureStateRoot();let t=F(En,n);mn(t),await kt(this.tokenFilePath,`${JSON.stringify(t,null,2)}
1
+ import{Eg as Y}from"./chunk-7m5q8vxf.js";import{Fg as on,Gg as F,Hg as o}from"./chunk-sk8h4m9m.js";import{Lg as ct,Mg as bt}from"./chunk-hg8d4vhj.js";import{Tg as x}from"./chunk-sb84vdcf.js";import{$g as kn,Ug as Jn,Vg as Xt,Wg as pt,_g as gt,ah as it,bh as Rt,ch as Ct,dh as un,eh as zt,fh as Bt,gh as On,hh as Kt,ih as Ut,jh as jn,kh as Ht,lh as Yt,mh as qt,nh as Vt,oh as Qt,ph as Gt}from"./chunk-hjr9r44k.js";import{th as fn}from"./chunk-ffa6hhee.js";import{wh as $t,zh as J}from"./chunk-t1633e8m.js";import{Hh as Pn,Ih as Ln}from"./chunk-p3jvzk1f.js";import{Oh as h}from"./chunk-rwvaapta.js";import{Zh as Tn}from"./chunk-shr5cg46.js";var Wt=/^[\x21\x23-\x5b\x5d-\x7e]+$/;function Zt(n){return n==="127.0.0.1"||n==="[::1]"||n.toLowerCase()==="localhost"}function R(n,t="MCP OAuth URL"){let M=new URL(n);if(M.username||M.password)throw Error(`${t} must not contain credentials`);if(M.protocol!=="https:"&&!(M.protocol==="http:"&&Zt(M.hostname)))throw Error(`${t} requires HTTPS; HTTP is allowed only for loopback servers`);return M}var U=async(n,t)=>{R(n,"MCP OAuth request URL");let M=await fetch(n,{...t,redirect:"manual"});if(M.status>=300&&M.status<400)throw await M.body?.cancel(),Error("MCP OAuth network requests must not follow redirects");return M};function k(n){let t=n.oauth;if(!t)return;let M=t;for(let u of["clientSecret","authorizationUrl","tokenUrl","redirectUri"])if(M[u]!==void 0)throw Error(`MCP OAuth "${u}" is not supported; use standards-based discovery`);if(t.enabled!==!0)return{enabled:!1};if(n.type!=="http"&&n.type!=="sse")throw Error("MCP OAuth is supported only for HTTP and SSE transports");if(!n.url)throw Error("MCP OAuth requires an MCP server URL");if(R(n.url,"MCP OAuth server URL"),Object.keys(n.headers??{}).find((u)=>u.toLowerCase()==="authorization"))throw Error("MCP OAuth cannot be combined with a configured Authorization header");let _=t.clientId?.trim();if(_&&_.length>4096)throw Error("MCP OAuth clientId exceeds 4096 characters");let S=t.scopes?.map((u)=>u.trim());if(S){if(S.length>32)throw Error("MCP OAuth supports at most 32 scopes");if(S.some((u)=>!u||u.length>128||!Wt.test(u)))throw Error("MCP OAuth scopes contain an invalid value");if(new Set(S).size!==S.length)throw Error("MCP OAuth scopes must not contain duplicates")}let r=t.callbackPort;if(r!==void 0&&(!Number.isInteger(r)||r<1024||r>65535))throw Error("MCP OAuth callbackPort must be between 1024 and 65535");return{enabled:!0,..._?{clientId:_}:{},...S?.length?{scopes:S}:{},...r!==void 0?{callbackPort:r}:{}}}import{randomUUID as v}from"node:crypto";import MM from"node:http";import{auth as cn}from"@modelcontextprotocol/sdk/client/auth.js";import _M from"open";import{createHash as Dt,randomUUID as Jt}from"node:crypto";import{constants as O,promises as L}from"node:fs";import j from"node:path";import kt from"write-file-atomic";var An=1,Ot=1048576,jt=5000,yt=50,Ft=/^[a-f0-9]{64}$/,lt=o.Object({client_id:o.String({minLength:1,maxLength:4096})},{additionalProperties:!0}),vt=o.Object({access_token:o.String({minLength:1,maxLength:65536}),token_type:o.String({minLength:1,maxLength:64}),expires_in:o.Optional(o.Number({minimum:0})),refresh_token:o.Optional(o.String({minLength:1,maxLength:65536})),scope:o.Optional(o.String({maxLength:16384})),id_token:o.Optional(o.String({minLength:1,maxLength:262144}))},{additionalProperties:!1}),nM=o.Unsafe({type:"object",properties:{authorizationServerUrl:o.String({format:"uri"}),resourceMetadataUrl:o.Optional(o.String({format:"uri"})),resourceMetadata:o.Optional(o.Unknown()),authorizationServerMetadata:o.Optional(o.Unknown())},required:["authorizationServerUrl"],additionalProperties:!1}),sn=o.Object({serverUrl:o.String({format:"uri"}),clientId:o.Optional(o.String({minLength:1,maxLength:4096})),clientInformation:o.Optional(lt),tokens:o.Optional(vt),tokenExpiresAt:o.Optional(o.Number({minimum:0})),discoveryState:o.Optional(nM),updatedAt:o.String({format:"date-time"})},{additionalProperties:!1}),En=o.Object({version:o.Literal(An),credentials:o.Record(o.String(),sn)},{additionalProperties:!1});function H(n,t){return n instanceof Error&&"code"in n&&n.code===t}function tM(n){if(!Number.isInteger(n)||n<=0)return!1;try{return process.kill(n,0),!0}catch(t){return H(t,"EPERM")}}function y(n){return structuredClone(n)}function mn(n){if(Object.keys(n.credentials).some((t)=>!Ft.test(t)))throw Error("MCP OAuth credential store contains an invalid identity")}function q(n){let t=new URL(n);return t.hash="",t.toString()}function l(n,t,M=[]){return Dt("sha256").update(JSON.stringify({serverUrl:q(n),clientId:t?.trim()||null,scopes:[...M].sort()})).digest("hex")}class I{static locks=new Y;stateRoot;tokenFilePath;constructor(n=Tn()){this.stateRoot=j.join(n,"mcp"),this.tokenFilePath=j.join(this.stateRoot,"oauth-credentials.json")}static coordinationStatsForTests(){return this.locks.getStats()}async getCredential(n){return I.locks.runExclusive(this.tokenFilePath,async()=>{let M=(await this.readStore()).credentials[n];return M?y(M):null})}async updateCredential(n,t){return this.runMutation(async(M)=>{let e=M.credentials[n],_=await t(e?y(e):null);if(_)M.credentials[n]=F(sn,_);else delete M.credentials[n];return _?y(M.credentials[n]):null})}async deleteCredential(n){await this.updateCredential(n,()=>null)}async listCredentialIds(){return I.locks.runExclusive(this.tokenFilePath,async()=>Object.keys((await this.readStore()).credentials).sort())}async runMutation(n){return I.locks.runExclusive(this.tokenFilePath,async()=>{let t=await this.acquireStoreLock();try{let M=await this.readStore(),e=await n(M);return await this.writeStore(M),e}finally{await t()}})}async ensureStateRoot(){await L.mkdir(this.stateRoot,{recursive:!0,mode:448});let n=await L.lstat(this.stateRoot);if(!n.isDirectory()||n.isSymbolicLink())throw Error("MCP OAuth credential root must be a regular directory");if(process.getuid&&n.uid!==process.getuid())throw Error("MCP OAuth credential root must be owned by the current user");if((n.mode&63)!==0)throw Error("MCP OAuth credential root permissions must not allow group access")}async readStore(){try{let n=await L.lstat(this.tokenFilePath);if(!n.isFile()||n.isSymbolicLink())throw Error("MCP OAuth credential store must be a regular file");if(process.getuid&&n.uid!==process.getuid())throw Error("MCP OAuth credential store must be owned by the current user");if((n.mode&511)!==384)throw Error("MCP OAuth credential store permissions must be 0600");if(n.size>Ot)throw Error("MCP OAuth credential store exceeds the 1 MiB limit");let t=JSON.parse(await L.readFile(this.tokenFilePath,"utf8")),M=on(En,t);if(!M.success)throw Error("MCP OAuth credential store has an invalid schema");return mn(M.data),M.data}catch(n){if(H(n,"ENOENT"))return{version:An,credentials:{}};throw n}}async writeStore(n){await this.ensureStateRoot();let t=F(En,n);mn(t),await kt(this.tokenFilePath,`${JSON.stringify(t,null,2)}
2
2
  `,{mode:384,encoding:"utf8"}),await L.chmod(this.tokenFilePath,384)}async acquireStoreLock(){await this.ensureStateRoot();let n=j.join(this.stateRoot,".oauth-credentials.lock"),t=Jt(),M=Date.now()+jt;while(Date.now()<M)try{let e=await L.open(n,O.O_CREAT|O.O_EXCL|O.O_WRONLY,384);return await e.writeFile(`${JSON.stringify({version:1,pid:process.pid,token:t,createdAt:new Date().toISOString()})}
3
3
  `,"utf8"),await e.close(),async()=>{try{if(JSON.parse(await L.readFile(n,"utf8")).token===t)await L.unlink(n)}catch(_){if(!H(_,"ENOENT"))throw _}}}catch(e){if(!H(e,"EEXIST"))throw e;await this.removeDeadLock(n),await new Promise((_)=>setTimeout(_,yt))}throw Error("MCP OAuth credential store is busy; retry the operation")}async removeDeadLock(n){let t=await L.lstat(n);if(!t.isFile()||t.isSymbolicLink())throw Error("MCP OAuth credential lock must be a regular file");if(process.getuid&&t.uid!==process.getuid()||(t.mode&511)!==384)throw Error("MCP OAuth credential lock ownership or permissions are invalid");let M=JSON.parse(await L.readFile(n,"utf8"));if(typeof M.pid!=="number"||!Number.isInteger(M.pid)||M.pid<=0)throw Error("MCP OAuth credential lock owner is invalid");if(!tM(M.pid))await L.unlink(n)}}var bn="127.0.0.1",wn=7777,xn="/oauth/callback",eM=300000;class nn extends Error{constructor(n){super(`MCP server "${n}" requires OAuth authorization; run "blade mcp login ${n}" or use the Web MCP panel`);this.name="McpOAuthAuthorizationRequiredError"}}class an extends Error{constructor(n){super(`MCP OAuth credentials are unavailable in this runtime for server "${n}"`);this.name="McpOAuthUnavailableError"}}function rM(n){let t=n?"Authentication complete":"Authentication failed";return`<!doctype html>
4
4
  <html lang="en">
@@ -0,0 +1,18 @@
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/MarkdownRenderer-BVPIxk31.js","assets/index-ebnhtfFC.js","assets/vendor-react-DG5dkZ_t.js","assets/vendor-radix-DXRuAJHH.js","assets/vendor-icons-CX5BfgqQ.js","assets/session-events-Bgir_Gl_.js","assets/index-BdnOTMNi.css"])))=>i.map(i=>d[i]);
2
+ import{r as f,j as e}from"./vendor-react-DG5dkZ_t.js";import{u as D,a as y,b as je,s as Be,c as et,d as X,D as Ie,e as _e,f as tt,g as Pe,h as Le,i as Ve,j as M,k as z,B as be,_ as Oe,S as st,l as Ue,m as at,n as rt,C as nt,o as it}from"./index-ebnhtfFC.js";import{Q as Se,O as ot,G as He,Y as lt,L as $,z as Ke,T as Z,C as de,Z as ct,v as dt,_ as ut,B as mt,$ as qe,y as ee,n as te,R as oe,s as ht,H as xt,a0 as ze,U as pt,a1 as ft,a2 as bt,a3 as vt,P as Ge,a4 as gt,X as We,a5 as kt,a6 as jt,f as ye,a7 as yt,a8 as wt,a9 as Nt,aa as St,W as Ct,a as Et}from"./vendor-icons-CX5BfgqQ.js";import{k as Tt,g as Mt,l as At,e as Rt,t as Ft,j as $t}from"./session-events-Bgir_Gl_.js";import{j as Dt,k as Bt,l as It,m as Qe}from"./vendor-radix-DXRuAJHH.js";import{t as F}from"./team-QZ9byb3E.js";import{teamService as Ce}from"./teamService-CFKFv0qS.js";function Ee(t){return t.split("/").filter(Boolean).at(-1)||t}function _t(){const t=D(),s=y(w=>w.sessions),a=y(w=>w.currentSessionRef),r=y(w=>w.taskDeliveryActions),i=y(w=>w.deliverTask),n=je(w=>w.openFilePreview),[d,b]=f.useState(!1),u=s.find(w=>Be({sessionId:w.sessionId,projectPath:w.projectPath},a));if(!(u!=null&&u.taskIsolation))return null;const c=u.taskDiffStat,k=u.taskIsolation==="worktree",l=et(u),p=r[X(l)],x=u.taskDelivery,j=(x==null?void 0:x.status)==="conflicted",S=!!(c&&(c.changedFiles>0||c.commits>0)),h=!["queued","running"].includes(u.taskStatus),N=(x==null?void 0:x.status)==="applied"||(x==null?void 0:x.status)==="discarded",v=k&&S&&h&&!N,o=c?c.additions+c.deletions:0,m=o>0&&c?c.additions/o*100:0,E=w=>{i(l,w).catch(()=>{})};return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex min-h-10 flex-wrap items-center gap-x-3 gap-y-1.5 border-b border-[hsl(var(--deck-hairline))] bg-[hsl(var(--deck-canvas-veil))]/60 px-3 py-1.5 font-mono text-[10.5px] text-[hsl(var(--deck-ink-muted))] backdrop-blur-sm sm:px-5",children:[e.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-3",children:[e.jsxs("span",{className:"inline-flex min-w-0 items-center gap-1.5",children:[e.jsx(Se,{className:"h-3 w-3 shrink-0 text-[hsl(var(--deck-ink-faint))]"}),e.jsx("span",{className:"truncate text-[hsl(var(--deck-ink))]",children:Ee(u.taskSourceProjectPath||u.projectPath)})]}),e.jsx("span",{className:"text-[hsl(var(--deck-ink-faint))]/60",children:"/"}),e.jsxs("span",{className:"inline-flex min-w-0 items-center gap-1.5",children:[k?e.jsx(ot,{className:"h-3 w-3 shrink-0 text-[hsl(var(--deck-accent))]"}):e.jsx(Se,{className:"h-3 w-3 shrink-0"}),e.jsx("span",{className:k?"text-[hsl(var(--deck-accent))]":void 0,children:t(k?"artifact.env.isolated":"artifact.env.local")})]}),u.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:u.taskWorktreeBranch,children:[e.jsx(He,{className:"h-3 w-3 shrink-0 text-[hsl(var(--deck-ink-faint))]"}),e.jsx("span",{className:"truncate",children:u.taskWorktreeBranch})]})]})]}),c&&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(lt,{className:"h-3 w-3 text-[hsl(var(--deck-ink-faint))]"}),e.jsx("span",{className:"tabular-nums",children:c.changedFiles})]}),o>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:`${m}%`}}),e.jsx("span",{className:"h-full bg-red-500/80",style:{width:`${100-m}%`}})]}),e.jsxs("span",{className:"tabular-nums text-[hsl(var(--deck-accent))]",children:["+",c.additions]}),e.jsxs("span",{className:"tabular-nums text-red-600 dark:text-red-400",children:["-",c.deletions]}),c.commits>0&&e.jsx("span",{className:"hidden tabular-nums text-[hsl(var(--deck-ink-faint))] sm:inline",children:t("artifact.commits",{count:c.commits})}),S&&(x==null?void 0:x.status)!=="discarded"&&e.jsx("button",{type:"button",onClick:()=>n({tab:"diff"}),className:"inline-flex items-center gap-1 rounded-md border border-[hsl(var(--deck-border))] bg-[hsl(var(--deck-surface))] px-2 py-1 text-[hsl(var(--deck-ink))] transition hover:border-[hsl(var(--deck-accent)/0.55)] hover:text-[hsl(var(--deck-accent))]",children:t("artifact.review")}),v&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{type:"button",disabled:!!p,onClick:()=>E("apply"),className:"inline-flex items-center gap-1 rounded-md bg-[hsl(var(--deck-accent))] px-2 py-1 font-semibold text-white transition hover:brightness-95 disabled:cursor-wait disabled:opacity-65",children:[p==="apply"?e.jsx($,{className:"h-3 w-3 animate-spin"}):e.jsx(Ke,{className:"h-3 w-3"}),t(p==="apply"?"artifact.applying":j?"artifact.retryApply":"artifact.apply")]}),e.jsx("button",{type:"button",disabled:!!p,onClick:()=>b(!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:p==="discard"?e.jsx($,{className:"h-3 w-3 animate-spin"}):e.jsx(Z,{className:"h-3 w-3"})})]}),(x==null?void 0:x.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(de,{className:"h-3 w-3"}),t("artifact.applied")]}),(x==null?void 0:x.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(Z,{className:"h-3 w-3"}),t("artifact.discarded")]})]}),(x==null?void 0:x.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(ct,{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:x.message||t("artifact.conflict")}),e.jsx("span",{className:"block text-[hsl(var(--deck-ink-faint))]",children:t("artifact.conflictHint")})]})]})]}),e.jsx(Ie,{open:d,onOpenChange:b,children:e.jsxs(_e,{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(tt,{children:[e.jsx(Pe,{children:t("artifact.discardDialog.title")}),e.jsx(Le,{className:"text-[hsl(var(--deck-ink-muted))]",children:t("artifact.discardDialog.description",{project:Ee(u.taskSourceProjectPath||u.projectPath),count:(c==null?void 0:c.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(Ve,{className:"gap-2 sm:space-x-0",children:[e.jsx("button",{type:"button",onClick:()=>b(!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:()=>{b(!1),E("discard")},className:"inline-flex items-center justify-center gap-1.5 rounded-md bg-red-600 px-3 py-2 text-sm font-semibold text-white hover:bg-red-700",children:[e.jsx(Z,{className:"h-3.5 w-3.5"}),t("artifact.discardDialog.confirm")]})]})]})})]})}const Pt=new Set(["completed","stale","failed","aborted","interrupted"]),Lt={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"},Vt={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 le(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:void 0}function Ot(t){const s=le(t),a=le(s==null?void 0:s.codeLocation),r=s==null?void 0:s.priority,i=s==null?void 0:s.confidenceScore,n=a==null?void 0:a.lineStart,d=a==null?void 0:a.lineEnd;if(!(typeof(s==null?void 0:s.title)!="string"||typeof s.body!="string"||r!==0&&r!==1&&r!==2&&r!==3||typeof i!="number"||!Number.isFinite(i)||typeof(a==null?void 0:a.path)!="string"||!Number.isInteger(n)||!Number.isInteger(d)))return{title:s.title,body:s.body,priority:r,confidenceScore:i,codeLocation:{path:a.path,lineStart:n,lineEnd:d}}}function Ut(t){const s=le(t),a=le(s==null?void 0:s.target);if((s==null?void 0:s.phase)!=="completed"||typeof s.status!="string"||!Pt.has(s.status)||typeof(a==null?void 0:a.label)!="string"||a.kind!=="uncommitted"&&a.kind!=="base"&&a.kind!=="commit"||typeof s.overallExplanation!="string"||!Array.isArray(s.findings))return;const r=s.findings.map(Ot);if(!r.some(i=>i===void 0))return{status:s.status,target:{kind:a.kind,label:a.label,...typeof a.reference=="string"?{reference:a.reference}:{}},overallExplanation:s.overallExplanation,findings:r,...typeof s.error=="string"?{error:s.error}:{}}}function Ht(t){const{path:s,lineStart:a,lineEnd:r}=t.codeLocation;return a===r?`${s}:L${a}`:`${s}:L${a}-${r}`}function Kt({report:t}){const s=D(),a=t.target.kind==="uncommitted"?s("chat.review.target.uncommitted"):t.target.kind==="base"?s("chat.review.target.base",{ref:t.target.reference??t.target.label}):s("chat.review.target.commit",{ref:t.target.reference??t.target.label});return e.jsxs("section",{"data-code-review-report":!0,className:"overflow-hidden rounded-xl border border-[hsl(var(--deck-border))] bg-[hsl(var(--deck-surface))]",children:[e.jsxs("header",{className:"flex flex-wrap items-center justify-between gap-3 border-b border-[hsl(var(--deck-hairline))] bg-[hsl(var(--deck-surface-2))]/60 px-4 py-3",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-[13px] font-semibold text-[hsl(var(--deck-ink))]",children:s("chat.review.title")}),e.jsxs("p",{className:"mt-0.5 font-mono text-[10.5px] text-[hsl(var(--deck-ink-faint))]",children:[s("chat.review.target"),": ",a]})]}),e.jsxs("span",{className:M("rounded-full border px-2.5 py-1 font-mono text-[10.5px] font-medium",Vt[t.status]),children:[s("chat.review.status"),": ",s(Lt[t.status])]})]}),e.jsxs("div",{className:"space-y-4 px-4 py-3.5",children:[e.jsx("p",{className:"whitespace-pre-wrap text-[13px] leading-6 text-[hsl(var(--deck-ink-muted))]",children:t.overallExplanation}),e.jsxs("div",{children:[e.jsxs("div",{className:"mb-2 flex items-center justify-between",children:[e.jsx("h4",{className:"deck-eyebrow text-[hsl(var(--deck-ink-faint))]",children:s("chat.review.findings")}),e.jsx("span",{className:"font-mono text-[10px] text-[hsl(var(--deck-ink-faint))]",children:t.findings.length})]}),t.findings.length===0?e.jsx("div",{className:"rounded-lg bg-[hsl(var(--deck-surface-2))] px-3 py-2.5 text-[12px] text-[hsl(var(--deck-ink-muted))]",children:s("chat.review.noFindings")}):e.jsx("ol",{className:"space-y-2",children:t.findings.map((r,i)=>e.jsxs("li",{className:"rounded-lg border border-[hsl(var(--deck-hairline))] bg-[hsl(var(--deck-canvas-veil))] px-3 py-2.5",children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-2",children:[e.jsx("h5",{className:"text-[12.5px] font-medium leading-5 text-[hsl(var(--deck-ink))]",children:r.title}),e.jsx("span",{className:"shrink-0 font-mono text-[10px] text-[hsl(var(--deck-ink-faint))]",children:s("chat.review.confidence",{value:r.confidenceScore.toFixed(2)})})]}),e.jsx("code",{className:"mt-1 block text-[10.5px] text-[hsl(var(--deck-accent))]",children:Ht(r)}),e.jsx("p",{className:"mt-1.5 whitespace-pre-wrap text-[12px] leading-5 text-[hsl(var(--deck-ink-muted))]",children:r.body})]},`${r.codeLocation.path}:${r.codeLocation.lineStart}:${i}`))})]}),t.error&&e.jsxs("div",{className:"rounded-lg border border-red-500/20 bg-red-500/5 px-3 py-2 text-[11px] text-red-700 dark:text-red-300",children:[e.jsxs("span",{className:"font-medium",children:[s("chat.review.error"),":"]})," ",t.error]})]})]})}function qt({elicitation:t,messageId:s}){const a=D(),r=y(v=>v.currentSessionRef),i=y(v=>v.setElicitation),[n,d]=f.useState(()=>Gt(t.details.fields??[])),[b,u]=f.useState(()=>Wt(t.details.fields??[])),[c,k]=f.useState(!1),[l,p]=f.useState(),x=t.details.fields??[],j=f.useMemo(()=>x.every(v=>{var m;if(!v.required)return!0;if(ue(v))return!!((m=b[v.name])!=null&&m.trim()||v.defaultValue!==void 0);const o=n[v.name]??v.defaultValue;return Array.isArray(o)?o.length>0:o!==void 0}),[x,b,n]);if(t.status!=="pending")return e.jsx("div",{className:"rounded-lg border border-[hsl(var(--deck-border))] bg-[hsl(var(--deck-surface-2))] px-3 py-2 font-mono text-[12px] text-[hsl(var(--deck-ink-muted))]",children:a(t.status==="cancelled"?"interaction.elicitation.cancelled":"interaction.elicitation.responded")});const S=async(v,o)=>{if(!(!r||c)){k(!0),p(void 0);try{await z.respondToElicitation(r,t.toolCallId,{action:v,...o?{content:o}:{}}),i(s,{...t,status:"responded"})}catch(m){p(m instanceof Error?m.message:a("interaction.elicitation.failed"))}finally{k(!1)}}},h=async()=>{try{await S("accept",Qt(x,n,b))}catch(v){p(v instanceof Error?v.message:String(v))}},N=()=>{const v=t.details.url;if(!v){p("MCP URL is unavailable");return}if(!window.open(v,"_blank","noopener,noreferrer")){p("The browser blocked the external window");return}S("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(dt,{className:"mt-0.5 h-4 w-4 shrink-0 text-amber-600 dark:text-amber-400"}),e.jsxs("div",{className:"min-w-0 space-y-1",children:[e.jsxs("div",{className:"font-mono text-[12px] font-semibold text-[hsl(var(--deck-ink))]",children:[a("interaction.elicitation.title")," · ",t.details.serverName]}),e.jsx("div",{className:"font-mono text-[12px] text-[hsl(var(--deck-ink-muted))]",children:t.details.message}),e.jsx("div",{className:"font-mono text-[11px] text-amber-700 dark:text-amber-300",children:a("interaction.elicitation.warning")})]})]}),t.details.mode==="url"?e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"rounded-md border border-[hsl(var(--deck-border))] bg-[hsl(var(--deck-surface-2))] p-3 font-mono text-[11px]",children:[e.jsx("div",{className:"text-[hsl(var(--deck-ink-muted))]",children:t.details.domain}),e.jsx("div",{className:"mt-1 break-all text-[hsl(var(--deck-ink))]",children:t.details.url})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(W,{onClick:N,disabled:c,primary:!0,label:a("interaction.elicitation.open"),icon:e.jsx(ut,{className:"h-3.5 w-3.5"})}),e.jsx(W,{onClick:()=>void S("decline"),disabled:c,label:a("interaction.elicitation.decline")}),e.jsx(W,{onClick:()=>void S("cancel"),disabled:c,label:a("interaction.elicitation.cancel")})]})]}):e.jsxs("div",{className:"space-y-4",children:[x.map(v=>e.jsx(zt,{field:v,value:n[v.name],rawValue:b[v.name]??"",onValueChange:o=>d(m=>({...m,[v.name]:o})),onRawChange:o=>u(m=>({...m,[v.name]:o}))},v.name)),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(W,{onClick:()=>void h(),disabled:c||!j,primary:!0,label:a("interaction.elicitation.submit"),icon:c?e.jsx($,{className:"h-3.5 w-3.5 animate-spin"}):null}),e.jsx(W,{onClick:()=>void S("decline"),disabled:c,label:a("interaction.elicitation.decline")}),e.jsx(W,{onClick:()=>void S("cancel"),disabled:c,label:a("interaction.elicitation.cancel")})]})]}),l&&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:l})]})}function zt({field:t,value:s,rawValue:a,onValueChange:r,onRawChange:i}){return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{htmlFor:`mcp-elicitation-${t.name}`,className:"block font-mono text-[12px] font-medium text-[hsl(var(--deck-ink))]",children:[t.title,t.required?" *":""]}),t.description&&e.jsx("div",{className:"font-mono text-[11px] text-[hsl(var(--deck-ink-faint))]",children:t.description}),t.type==="select"||t.type==="multi-select"||t.type==="boolean"?e.jsx("div",{id:`mcp-elicitation-${t.name}`,className:"flex flex-wrap gap-2",children:Jt(t).map(n=>{const d=Array.isArray(s)?s.includes(n.value):s===n.typedValue;return e.jsx("button",{type:"button","aria-pressed":d,onClick:()=>{if(t.type==="multi-select"){const b=Array.isArray(s)?s:[];r(b.includes(n.value)?b.filter(u=>u!==n.value):[...b,n.value])}else r(n.typedValue)},className:M("rounded-md border px-3 py-2 font-mono text-[12px] transition-colors",d?"border-emerald-500 bg-emerald-50 text-emerald-800 dark:bg-emerald-950/40 dark:text-emerald-200":"border-[hsl(var(--deck-border))] bg-[hsl(var(--deck-surface-2))] text-[hsl(var(--deck-ink-muted))] hover:text-[hsl(var(--deck-ink))]"),children:n.label},n.value)})}):e.jsx("input",{id:`mcp-elicitation-${t.name}`,type:Yt(t),value:a,onChange:n=>i(n.target.value),min:t.minimum,max:t.maximum,minLength:t.minLength,maxLength:t.maxLength,required:t.required,placeholder:t.defaultValue===void 0?t.required?"Required":"Optional":String(t.defaultValue),className:"w-full rounded-md border border-[hsl(var(--deck-border))] bg-[hsl(var(--deck-surface-2))] px-3 py-2 font-mono text-[12px] text-[hsl(var(--deck-ink))] outline-none transition-colors focus:border-amber-500 focus:ring-1 focus:ring-amber-500"})]})}function W({onClick:t,disabled:s,primary:a=!1,label:r,icon:i}){return e.jsxs("button",{type:"button",onClick:t,disabled:s,className:M("inline-flex min-h-8 items-center gap-1.5 rounded-md px-3 py-1.5 font-mono text-[12px] transition-colors disabled:cursor-wait disabled:opacity-50",a?"bg-amber-600 text-white hover:bg-amber-700":"border border-[hsl(var(--deck-border))] bg-[hsl(var(--deck-surface-2))] text-[hsl(var(--deck-ink-muted))] hover:text-[hsl(var(--deck-ink))]"),children:[i,r]})}function Gt(t){return Object.fromEntries(t.filter(s=>!ue(s)&&s.defaultValue!==void 0).map(s=>[s.name,Array.isArray(s.defaultValue)?[...s.defaultValue]:s.defaultValue]))}function Wt(t){return Object.fromEntries(t.filter(s=>ue(s)&&s.defaultValue!==void 0).map(s=>[s.name,String(s.defaultValue)]))}function Qt(t,s,a){var i;const r={};for(const n of t){if(ue(n)){const b=((i=a[n.name])==null?void 0:i.trim())??"";if(!b){if(n.defaultValue!==void 0)r[n.name]=n.defaultValue;else if(n.required)throw new Error(`${n.title} is required`);continue}if(n.type==="number"||n.type==="integer"){const u=Number(b);if(!Number.isFinite(u))throw new Error(`${n.title} must be a finite number`);if(n.type==="integer"&&!Number.isSafeInteger(u))throw new Error(`${n.title} must be a safe integer`);r[n.name]=u}else r[n.name]=b;continue}const d=s[n.name]??n.defaultValue;if(d===void 0){if(n.required)throw new Error(`${n.title} is required`);continue}if(Array.isArray(d)){if(n.minItems!==void 0&&d.length<n.minItems)throw new Error(`${n.title} requires at least ${n.minItems} choices`);if(n.maxItems!==void 0&&d.length>n.maxItems)throw new Error(`${n.title} allows at most ${n.maxItems} choices`)}r[n.name]=d}return r}function Jt(t){return t.type==="boolean"?[{value:"true",label:"Yes",typedValue:!0},{value:"false",label:"No",typedValue:!1}]:(t.options??[]).map(s=>({...s,typedValue:s.value}))}function ue(t){return t.type==="string"||t.type==="number"||t.type==="integer"}function Yt(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 Xt(t){if(!t||typeof t!="object"||Array.isArray(t))return;const s=t;if(!(!s.output||typeof s.output!="object"||Array.isArray(s.output)))return{output:s.output,...typeof s.schemaDigest=="string"?{schemaDigest:s.schemaDigest}:{}}}function Zt({report:t}){const s=D(),[a,r]=f.useState(!1),i=JSON.stringify(t.output,null,2),n=async()=>{try{await navigator.clipboard.writeText(i),r(!0),window.setTimeout(()=>r(!1),1400)}catch{}};return e.jsxs("section",{"data-structured-output":!0,className:"overflow-hidden rounded-lg border border-[hsl(var(--deck-border))] bg-[hsl(var(--deck-surface))]",children:[e.jsxs("header",{className:"flex min-h-9 items-center justify-between gap-3 border-b border-[hsl(var(--deck-border))] bg-[hsl(var(--deck-surface-2))] px-3",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[e.jsx(mt,{className:"h-3.5 w-3.5 shrink-0 text-[hsl(var(--deck-accent))]"}),e.jsx("span",{className:"font-mono text-[11px] font-semibold text-[hsl(var(--deck-ink))]",children:s("chat.structuredOutput.title")}),t.schemaDigest&&e.jsxs("span",{title:t.schemaDigest,className:"truncate font-mono text-[9px] text-[hsl(var(--deck-ink-faint))]",children:["sha256:",t.schemaDigest.slice(0,10)]})]}),e.jsx("button",{type:"button",onClick:n,"aria-label":s("chat.structuredOutput.copy"),title:s("chat.structuredOutput.copy"),className:"flex h-6 w-6 shrink-0 items-center justify-center rounded text-[hsl(var(--deck-ink-faint))] hover:bg-[hsl(var(--deck-surface))] hover:text-[hsl(var(--deck-ink))] focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-[hsl(var(--deck-accent))]",children:a?e.jsx(de,{className:"h-3.5 w-3.5 text-[hsl(var(--deck-accent))]"}):e.jsx(qe,{className:"h-3.5 w-3.5"})})]}),e.jsx("pre",{className:"max-h-[440px] overflow-auto whitespace-pre p-3 font-mono text-[11px] leading-5 text-[hsl(var(--deck-ink))]",children:i})]})}const es=f.lazy(()=>Oe(()=>import("./MarkdownRenderer-BVPIxk31.js").then(t=>t.M),__vite__mapDeps([0,1,2,3,4,5,6])).then(t=>({default:t.MarkdownRenderer})));function Te({text:t,label:s}){const[a,r]=f.useState(!1);if(!t.trim())return null;const i=async()=>{try{await navigator.clipboard.writeText(t),r(!0),window.setTimeout(()=>r(!1),1400)}catch{}};return e.jsx("button",{type:"button","aria-label":s,title:s,onClick:i,className:"flex h-6 w-6 items-center justify-center rounded-md text-[hsl(var(--deck-ink-faint))] transition-colors hover:bg-[hsl(var(--deck-surface))] hover:text-[hsl(var(--deck-ink))] focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-[hsl(var(--deck-accent))]",children:a?e.jsx(de,{className:"h-3.5 w-3.5 text-[hsl(var(--deck-accent))]"}):e.jsx(qe,{className:"h-3.5 w-3.5"})})}function ts(){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(be,{size:20,pulse:!1})})}function ss(){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 Me(t){let s=t;return s=s.replace(/<system-reminder>[\s\S]*?<\/system-reminder>/g,""),s=s.replace(/<file path="[^"]*">[\s\S]*?<\/file>/g,""),s=s.replace(/<attached_files>[\s\S]*?<\/attached_files>/g,""),s=s.trim(),s}function as(t){if(typeof t=="string")return{text:Me(t),images:[]};const s=t.filter(r=>r.type==="text").map(r=>r.text).join(`
3
+ `),a=t.filter(r=>r.type==="image_url").map(r=>r.image_url.url);return{text:Me(s),images:a}}function we(t){return typeof t=="string"?t:t.filter(s=>s.type==="text").map(s=>s.text).join(`
4
+ `)}function rs(t){const s=t.agentContent;return s?Tt(s):we(t.content)}function Ae({content:t,syntaxHighlight:s=!0}){return e.jsx(f.Suspense,{fallback:e.jsx("pre",{className:"text-[14px] text-[hsl(var(--deck-ink))] font-mono whitespace-pre-wrap",children:t}),children:e.jsx(es,{content:t,syntaxHighlight:s})})}function Ne({status:t}){if(!t)return null;const s={running:"bg-[#FEF3C7] text-[#92400E] dark:bg-[#F59E0B]/20 dark:text-[#FBBF24]",success:"bg-[#DCFCE7] text-[#15803D] dark:bg-[#22C55E]/20 dark:text-[#22C55E]",error:"bg-[#FEE2E2] text-[#b91c1c] dark:bg-[#EF4444]/20 dark:text-[#fca5a5]",pending:"bg-[#E5E7EB] text-[#6B7280] dark:bg-[#27272a] dark:text-[#a1a1aa]",info:"bg-[#DBEAFE] text-[#1D4ED8] dark:bg-[#3B82F6]/20 dark:text-[#60A5FA]"},a={running:"Running",success:"Success",error:"Error",pending:"Pending",info:"Info"};return e.jsx("span",{className:M("text-[11px] px-2 py-0.5 rounded-full font-mono",s[t]),children:a[t]})}function ns(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 Re=500;function Je(t,s){if(t.length<=s)return t;let a=Math.max(0,s);return a>0&&/[\uD800-\uDBFF]/.test(t.charAt(a-1))&&(a-=1),t.slice(0,a)}function Fe(t,s){if(t.length<=s)return t;let a=Math.max(0,t.length-s);return/[\uDC00-\uDFFF]/.test(t.charAt(a))&&(a+=1),t.slice(a)}function he(t,s){if(t.length<=s)return t;if(s<=0)return"";const a=`
5
+ ... (display clipped) ...
6
+ `,r=s-a.length;if(r<=0)return Fe(t,s);const i=Math.floor(r/3);return`${Je(t,i)}${a}${Fe(t,r-i)}`}function is(t){const s=t.split(`
7
+ `),a=s.at(-1),r=a!=null&&a.startsWith("Output truncated")?a:void 0,i=r?s.slice(0,-1).join(`
8
+ `):t,n=r?`
9
+ ${r}`:"",d=Math.max(0,Re-n.length),u=i.indexOf(`
10
+ stderr:
11
+ `);let c;if(u>=0&&i.includes(`
12
+ stdout:
13
+ `)){const k=i.slice(0,u),l=i.slice(u+1),p=Math.max(0,d-1),x=Math.floor(p/2);c=`${he(k,x)}
14
+ ${he(l,p-x)}`}else c=he(i,d);return{body:Je(c,d),...r?{notice:r}:{},truncated:!!r||t.length>Re}}function os({tool:t}){const[s,a]=f.useState(!1),r=ns(t.arguments),i=t.output?is(t.output):void 0;return e.jsxs("div",{"data-tool-name":t.toolName,"data-tool-status":t.status,"data-tool-truncated":i!=null&&i.truncated?"true":"false",className:"bg-white dark:bg-[#18181b] border border-[hsl(var(--deck-border))] rounded-lg overflow-hidden",children:[e.jsxs("button",{type:"button","aria-expanded":s,"data-tool-call-id":t.toolCallId,onClick:()=>a(n=>!n),className:"w-full flex items-center justify-between px-3 py-2 bg-[hsl(var(--deck-surface-2))] hover:bg-[hsl(var(--deck-surface))] transition-colors",children:[e.jsxs("div",{className:"flex gap-2 items-center min-w-0",children:[s?e.jsx(ee,{className:"h-4 w-4 text-[hsl(var(--deck-ink-faint))] shrink-0"}):e.jsx(te,{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(Ne,{status:t.status})]}),t.status==="running"&&t.progressMessage&&e.jsxs("div",{className:"border-t border-[hsl(var(--deck-border))] px-3 py-2 space-y-1.5",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3 font-mono text-[10px] text-[hsl(var(--deck-ink-muted))]",children:[e.jsx("span",{className:"truncate",children:t.progressMessage}),t.progressTotal!==void 0&&t.progress!==void 0&&e.jsxs("span",{className:"shrink-0",children:[Math.max(0,Math.min(100,Math.round(t.progress/t.progressTotal*100))),"%"]})]}),t.progressTotal!==void 0&&t.progress!==void 0&&e.jsx("div",{role:"progressbar","aria-label":`${t.toolName} progress`,"aria-valuemin":0,"aria-valuemax":t.progressTotal,"aria-valuenow":Math.min(t.progress,t.progressTotal),className:"h-1 overflow-hidden rounded-full bg-[hsl(var(--deck-border))]",children:e.jsx("div",{className:"h-full rounded-full bg-amber-500 transition-[width] duration-150",style:{width:`${Math.max(0,Math.min(100,t.progress/t.progressTotal*100))}%`}})})]}),s&&e.jsxs("div",{className:"px-3 py-2 space-y-2 border-t border-[hsl(var(--deck-border))]",children:[r&&e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"text-[11px] text-[hsl(var(--deck-ink-muted))] font-mono",children:"Arguments"}),e.jsx("pre",{className:"text-[11px] text-[hsl(var(--deck-ink))] bg-[hsl(var(--deck-surface-2))] border border-[hsl(var(--deck-border))] rounded-md p-2 overflow-x-auto whitespace-pre-wrap font-mono max-h-[120px] overflow-y-auto",children:r})]}),i&&e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"text-[11px] text-[hsl(var(--deck-ink-muted))] font-mono",children:"Output"}),e.jsxs("pre",{"data-tool-output":!0,className:"text-[11px] text-[hsl(var(--deck-ink))] bg-[hsl(var(--deck-surface-2))] border border-[hsl(var(--deck-border))] rounded-md p-2 overflow-x-auto whitespace-pre-wrap font-mono max-h-[120px] overflow-y-auto",children:[i.body,i.notice&&e.jsxs(e.Fragment,{children:[`
15
+ `,e.jsx("span",{"data-tool-truncation-notice":!0,children:i.notice})]})]})]})]})]})}function Ye({toolCalls:t}){return t.length===0?null:e.jsx("div",{className:"space-y-2",children:t.map(s=>e.jsx(os,{tool:s},s.toolCallId))})}function ls({toolCalls:t,toolCallIds:s}){const a=D(),[r,i]=f.useState(!1),n=f.useMemo(()=>new Map(t.map(l=>[l.toolCallId,l])),[t]),d=s.flatMap(l=>{const p=n.get(l);return p?[p]:[]});if(d.length===0)return null;const b=d.filter(l=>l.status==="running").length,u=d.filter(l=>l.status==="error").length,c=[...d].reverse().find(l=>l.status==="running"&&!!l.progressMessage),k=b>0?a(d.length===1?"chat.timeline.tools.runningOne":"chat.timeline.tools.running",{count:d.length}):u>0?a(d.length===1?"chat.timeline.tools.completedOneWithError":"chat.timeline.tools.completedWithErrors",{count:d.length,errors:u}):a(d.length===1?"chat.timeline.tools.completedOne":"chat.timeline.tools.completed",{count:d.length});return e.jsxs("div",{"data-agent-tool-group":!0,className:"py-0.5",children:[e.jsxs("button",{type:"button","aria-expanded":r,onClick:()=>i(l=>!l),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(ee,{className:"h-3.5 w-3.5 shrink-0"}):e.jsx(te,{className:"h-3.5 w-3.5 shrink-0"}),b>0&&e.jsx($,{className:"h-3 w-3 shrink-0 animate-spin text-[hsl(var(--deck-accent))]"}),e.jsx("span",{children:k}),(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:"mt-2 space-y-2 pl-1",children:e.jsx(Ye,{toolCalls:d})})]})}function cs({content:t}){const s=D(),[a,r]=f.useState(!1);return t?e.jsxs("div",{"data-agent-thinking":!0,className:"py-0.5",children:[e.jsxs("button",{type:"button","aria-expanded":a,onClick:()=>r(i=>!i),className:"flex min-h-7 w-full items-center gap-1.5 rounded-md px-1.5 text-left font-mono text-[11.5px] text-[hsl(var(--deck-ink-faint))] transition-colors hover:bg-[hsl(var(--deck-surface))]/65 hover:text-[hsl(var(--deck-ink-muted))] focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-[hsl(var(--deck-accent))]",children:[a?e.jsx(ee,{className:"h-4 w-4 text-[hsl(var(--deck-ink-faint))]"}):e.jsx(te,{className:"h-4 w-4 text-[hsl(var(--deck-ink-faint))]"}),e.jsx("span",{children:s("chat.timeline.thinking")})]}),a&&e.jsx("div",{className:"ml-1 mt-1 border-l border-[hsl(var(--deck-border))] py-1 pl-3",children:e.jsx("pre",{className:"whitespace-pre-wrap font-mono text-[11px] leading-5 text-[hsl(var(--deck-ink-muted))]",children:t})})]}):null}function ds({tasks:t}){if(t.length===0)return null;const s=t.filter(r=>r.status==="completed").length,a=s===t.length;return e.jsx("div",{className:"bg-[hsl(var(--deck-surface-2))] border border-[hsl(var(--deck-border))] rounded-lg px-3 py-2",children:e.jsx("div",{className:"flex gap-2 items-center",children:e.jsx("span",{className:"text-[12px] text-[hsl(var(--deck-ink-muted))] font-mono",children:a?"✓ All tasks done":`Tasks: ${s}/${t.length}`})})})}function us({toolCalls:t}){const s=je(r=>r.openFilePreview),a=f.useMemo(()=>{const r=new Map,i=["Write","SearchReplace","Edit","ApplyPatch"];for(const n of t){if(n.status!=="success")continue;const d=n.metadata;if(n.toolName==="ApplyPatch"&&Array.isArray(d==null?void 0:d.changes)){for(const u of d.changes)u&&typeof u=="object"&&"path"in u&&typeof u.path=="string"&&r.set(u.path,{path:u.path,toolName:n.toolName});continue}const b=d==null?void 0:d.file_path;b&&i.includes(n.toolName)&&r.set(b,{path:b,toolName:n.toolName})}return Array.from(r.values())},[t]);return a.length===0?null:e.jsxs("div",{className:"bg-[hsl(var(--deck-surface-2))] border border-[hsl(var(--deck-border))] rounded-lg px-3 py-2",children:[e.jsxs("div",{className:"text-[11px] text-[hsl(var(--deck-ink-muted))] font-mono mb-1.5",children:["Changed files (",a.length,")"]}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:a.map(({path:r})=>{const i=r.split("/").pop()||r;return e.jsxs("button",{onClick:()=>s({tab:"diff",targetPath:r}),className:"flex items-center gap-1 px-2 py-1 text-[11px] font-mono bg-[#E5E7EB] dark:bg-[#27272a] text-[hsl(var(--deck-ink))] rounded hover:bg-[#D1D5DB] dark:hover:bg-[#3f3f46] transition-colors",title:r,children:[e.jsx(ht,{className:"w-3 h-3"}),i]},r)})})]})}function ms({subagent:t}){var Q,G,se,ae;const s=D(),[a,r]=f.useState(null),[i,n]=f.useState(!1),[d,b]=f.useState(null),[u,c]=f.useState(!1),[k,l]=f.useState(""),[p,x]=f.useState(!1),[j,S]=f.useState(null),[h,N]=f.useState(null),[v,o]=f.useState(null),m=y(A=>A.currentSessionRef),E=y(A=>A.isStreaming),w=y(A=>A.isTemporarySession);if(!t)return null;const C=t.status==="running",R=a!==null?a:C,O=t.toolCalls||d||[],U=t.output||t.thinking||O.length>0||t.sessionId,B=h&&h.status!=="running"?h:v,L=(B==null?void 0:B.id)??t.sessionId,V=((Q=B==null?void 0:B.restartRecovery)==null?void 0:Q.outcome)==="failed",T=!C&&!E&&!w&&!V&&(h==null?void 0:h.status)!=="running"&&!!(L&&m);f.useEffect(()=>{if(!R||C||!t.sessionId||!(m!=null&&m.projectPath)||d!==null||t.toolCalls&&t.toolCalls.length>0)return;let A=!0;return n(!0),z.getMessages({sessionId:t.sessionId,projectPath:m.projectPath}).then(H=>{var _,I;if(!A)return;const K=Rt(H),g=new Map;for(const J of K)if((I=(_=J.agentContent)==null?void 0:_.toolCalls)!=null&&I.length)for(const me of J.agentContent.toolCalls)g.has(me.toolCallId)||g.set(me.toolCallId,me);b(Array.from(g.values()))}).finally(()=>{A&&n(!1)}),()=>{A=!1}},[R,C,t.sessionId,t.toolCalls,d,m==null?void 0:m.projectPath]),f.useEffect(()=>{if(!t.sessionId||!m)return;let A=!0;const H=t.rootAgentId??t.sessionId,K=t.resumeDepth??0;return z.listSubagents(m).then(g=>{if(!A)return;o(g.find(I=>I.id===t.sessionId)??null);const _=g.filter(I=>I.id!==t.sessionId&&I.rootAgentId===H&&I.resumeDepth>K).sort((I,J)=>J.resumeDepth-I.resumeDepth||J.lastActiveAt-I.lastActiveAt)[0];_&&N(_)}).catch(()=>{}),()=>{A=!1}},[m==null?void 0:m.sessionId,m==null?void 0:m.projectPath,t.sessionId,t.rootAgentId,t.resumeDepth]),f.useEffect(()=>{if(!h||h.status!=="running"||!m)return;let A=!0;const H=async()=>{try{const _=(await z.listSubagents(m)).find(I=>I.id===h.id);A&&_&&N(_)}catch{}},K=window.setInterval(()=>{H()},1e3);return()=>{A=!1,window.clearInterval(K)}},[m,h==null?void 0:h.id,h==null?void 0:h.status]);const P=async()=>{if(!(!m||!L||!k.trim()||p)){x(!0),S(null);try{const A=await z.resumeSubagent(m,L,k.trim());N(A.session),l(""),c(!1),r(!0)}catch(A){S(A instanceof Error?A.message:s("chat.subagent.resumeFailed"))}finally{x(!1)}}};return e.jsxs("div",{"data-subagent-id":t.id,"data-subagent-session-id":t.sessionId,className:"bg-[hsl(var(--deck-surface-2))] border border-[hsl(var(--deck-border))] rounded-lg px-3 py-2",children:[e.jsxs("button",{type:"button",onClick:()=>r(!R),className:"flex gap-2 justify-between items-center w-full transition-opacity cursor-pointer hover:opacity-80",children:[e.jsxs("div",{className:"flex gap-2 items-center",children:[C&&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(Ne,{status:t.status==="completed"?"success":t.status==="failed"?"error":"running"}),t.type==="verification"&&t.verificationVerdict&&e.jsx("span",{"data-verification-verdict":t.verificationVerdict,className:M("rounded px-1.5 py-0.5 text-[10px] font-semibold uppercase tracking-wide",t.verificationVerdict==="pass"?"bg-emerald-500/10 text-emerald-600 dark:text-emerald-400":t.verificationVerdict==="fail"?"bg-red-500/10 text-red-600 dark:text-red-400":"bg-amber-500/10 text-amber-600 dark:text-amber-400"),children:t.verificationVerdict}),t.resumedFrom&&e.jsx("span",{className:"rounded bg-[#EDE9FE] px-1.5 py-0.5 text-[10px] font-mono text-[#6D28D9] dark:bg-[#2E1065] dark:text-[#C4B5FD]",title:s("chat.subagent.resumedFromTitle",{id:t.resumedFrom}),children:s("chat.subagent.resumedDepth",{depth:t.resumeDepth??1})})]}),U&&e.jsx(ee,{className:M("h-3.5 w-3.5 text-[hsl(var(--deck-ink-muted))] transition-transform",R&&"rotate-180")})]}),!R&&!C&&t.output&&e.jsx("div",{"data-subagent-output-summary":!0,className:"mt-2 max-h-10 overflow-hidden whitespace-pre-wrap break-words font-mono text-[11px] text-[hsl(var(--deck-ink))]",children:t.output}),R&&e.jsxs("div",{className:"mt-2 space-y-2",children:[(t.output||t.thinking)&&e.jsxs(e.Fragment,{children:[t.output&&e.jsx("pre",{className:"text-[11px] text-[hsl(var(--deck-ink))] bg-[hsl(var(--deck-surface-2))] border border-[hsl(var(--deck-border))] rounded-md p-2 overflow-x-auto whitespace-pre-wrap font-mono max-h-[160px] overflow-y-auto",children:t.output}),t.thinking&&e.jsx("pre",{className:"text-[11px] text-[hsl(var(--deck-ink-muted))] bg-[hsl(var(--deck-surface-2))] border border-[hsl(var(--deck-border))] rounded-md p-2 overflow-x-auto whitespace-pre-wrap font-mono max-h-[120px] overflow-y-auto",children:t.thinking})]}),i&&e.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-[hsl(var(--deck-ink-muted))] font-mono",children:[e.jsx($,{className:"w-3 h-3 animate-spin"}),s("chat.subagent.loadingLogs")]}),!i&&O.length>0&&e.jsx(Ye,{toolCalls:O}),h&&e.jsxs("div",{className:"rounded-md border border-[#DDD6FE] bg-[#F5F3FF] p-2 text-[11px] font-mono text-[#5B21B6] dark:border-[#4C1D95] dark:bg-[#1E1B4B] dark:text-[#C4B5FD]",children:[e.jsx("div",{children:s("chat.subagent.resumedAs",{id:h.id,status:h.status,depth:h.resumeDepth??1})}),(((G=h.result)==null?void 0:G.message)||((se=h.result)==null?void 0:se.error))&&e.jsx("div",{className:"mt-1 whitespace-pre-wrap text-[hsl(var(--deck-ink))]",children:h.result.message||h.result.error})]}),V&&((ae=B==null?void 0:B.result)==null?void 0:ae.error)&&e.jsx("div",{role:"alert",className:"text-[11px] text-red-600",children:B.result.error}),T&&e.jsxs("div",{className:"space-y-2",children:[u?e.jsxs("div",{className:"space-y-2 rounded-md border border-[#E5E7EB] bg-white p-2 dark:border-[#27272a] dark:bg-[#111113]",children:[e.jsx("textarea",{"aria-label":s("chat.subagent.followUpAria"),value:k,onChange:A=>l(A.target.value),placeholder:s("chat.subagent.followUpPlaceholder"),rows:3,className:"w-full resize-y rounded border border-[#D1D5DB] bg-white p-2 text-[11px] text-[#111827] outline-none focus:border-[#8B5CF6] dark:border-[#3f3f46] dark:bg-[#18181b] dark:text-[#f4f4f5]"}),e.jsxs("div",{className:"flex gap-2 justify-end",children:[e.jsx("button",{type:"button",onClick:()=>{c(!1),S(null)},className:"rounded px-2 py-1 text-[11px] text-[#6B7280] hover:bg-[#F3F4F6] dark:hover:bg-[#27272a]",children:s("chat.subagent.cancel")}),e.jsxs("button",{type:"button",onClick:()=>void P(),disabled:!k.trim()||p,className:"flex items-center gap-1 rounded bg-[#7C3AED] px-2 py-1 text-[11px] font-medium text-white disabled:opacity-50",children:[p&&e.jsx($,{className:"w-3 h-3 animate-spin"}),s("chat.subagent.resumeAgent")]})]})]}):e.jsxs("button",{type:"button","aria-label":s("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(oe,{className:"w-3 h-3"}),s("chat.subagent.resume")]}),j&&e.jsx("div",{role:"alert",className:"text-[11px] text-red-600",children:j})]})]})]})}function hs({confirmation:t,messageId:s}){const a=D(),[r,i]=f.useState(!1),[n,d]=f.useState(null),b=y(k=>k.currentSessionRef),u=y(k=>k.setConfirmation);if(!t)return null;const c=async(k,l)=>{if(!(!b||r)){i(!0),d(null);try{await z.respondPermission(b,t.toolCallId,{approved:k,scope:l}),u(s,{...t,status:k?"approved":"denied"})}catch(p){d(p instanceof Error?p.message:a("interaction.permission.failed"))}finally{i(!1)}}};return t.status!=="pending"?null:e.jsxs("div",{"data-pending-interaction":"permission",tabIndex:-1,role:"alert",className:"space-y-3 rounded-lg border border-amber-300/70 bg-amber-50/70 p-4 outline-none focus-visible:ring-2 focus-visible:ring-amber-500 dark:border-amber-800/70 dark:bg-amber-950/25",children:[e.jsx("div",{className:"text-[13px] text-[hsl(var(--deck-ink))] font-mono",children:a("interaction.permission.title",{tool:t.toolName})}),e.jsx("div",{className:"text-[12px] text-[hsl(var(--deck-ink-muted))] font-mono",children:t.description}),t.diff&&e.jsx("pre",{className:"text-[11px] text-[hsl(var(--deck-ink))] bg-[hsl(var(--deck-surface-2))] border border-[hsl(var(--deck-border))] rounded-md p-2 overflow-x-auto whitespace-pre-wrap font-mono max-h-[200px] overflow-y-auto",children:t.diff}),n&&e.jsx("div",{role:"alert",className:"rounded-md border border-red-300/70 bg-red-50 px-2.5 py-2 font-mono text-[11px] text-red-700 dark:border-red-900/70 dark:bg-red-950/35 dark:text-red-300",children:n}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx("button",{type:"button",onClick:()=>void 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"}):a("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:a("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:a("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:a("interaction.permission.deny")})]})]})}function xs({question:t,messageId:s}){const a=D(),[r,i]=f.useState({}),[n,d]=f.useState({}),[b,u]=f.useState(!1),[c,k]=f.useState(null),l=y(h=>h.currentSessionRef),p=y(h=>h.setQuestion),x=f.useMemo(()=>t?t.questions.reduce((h,N)=>{var E;const v=(E=n[N.header])==null?void 0:E.trim(),o=r[N.header];if(N.multiSelect){const w=Array.isArray(o)?[...o]:[];return v&&w.push(v),w.length>0&&(h[N.header]=w),h}const m=v||(typeof o=="string"?o:"");return m&&(h[N.header]=m),h},{}):{},[r,n,t]),j=(t==null?void 0:t.questions.every(h=>h.header in x))??!1;if(!t)return null;const S=async()=>{if(!(!l||b||!j)){u(!0),k(null);try{await z.respondToQuestion(l,t.toolCallId,x),p(s,{...t,status:"answered",answers:x})}catch(h){k(h instanceof Error?h.message:a("interaction.question.failed"))}finally{u(!1)}}};return t.status!=="pending"?e.jsx("div",{className:"bg-[hsl(var(--deck-surface-2))] border border-[hsl(var(--deck-border))] rounded-lg px-3 py-2",children:e.jsx("div",{className:"text-[12px] text-[hsl(var(--deck-ink-muted))] font-mono",children:a("interaction.question.answered")})}):e.jsxs("div",{"data-pending-interaction":"question",tabIndex:-1,role:"alert",className:"space-y-4 rounded-lg border border-amber-300/70 bg-amber-50/70 p-4 outline-none focus-visible:ring-2 focus-visible:ring-amber-500 dark:border-amber-800/70 dark:bg-amber-950/25",children:[t.questions.map((h,N)=>e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"text-[13px] text-[hsl(var(--deck-ink))] font-mono",children:h.question}),e.jsxs("div",{className:"space-y-1",children:[h.options.map((v,o)=>e.jsxs("button",{type:"button",onClick:()=>{if(h.multiSelect){const m=r[h.header]||[],E=m.includes(v.label)?m.filter(w=>w!==v.label):[...m,v.label];i({...r,[h.header]:E})}else i({...r,[h.header]:v.label}),d({...n,[h.header]:""})},className:M("w-full text-left px-3 py-2 rounded-md border text-[12px] font-mono transition-colors","border-[hsl(var(--deck-border))]",(h.multiSelect?(r[h.header]||[]).includes(v.label):r[h.header]===v.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:v.label}),e.jsx("div",{className:"text-[11px] text-[hsl(var(--deck-ink-faint))] mt-1",children:v.description})]},o)),e.jsx("input",{"aria-label":`${h.header} other response`,value:n[h.header]??"",onChange:v=>d({...n,[h.header]:v.target.value}),placeholder:a("interaction.question.other"),className:"w-full rounded-md border border-[#E5E7EB] bg-white px-3 py-2 text-[12px] text-[#111827] outline-none focus:border-[#22C55E] dark:border-[#27272a] dark:bg-[#111113] dark:text-[#E5E5E5]"})]})]},N)),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 S(),disabled:b||!j,className:"inline-flex min-h-8 items-center gap-1.5 px-3 py-1.5 text-[12px] font-mono bg-[#22C55E] text-white rounded-md hover:bg-[#16A34A] disabled:cursor-wait disabled:opacity-50",children:[b&&e.jsx($,{className:"h-3.5 w-3.5 animate-spin"}),a("interaction.question.submit")]})]})}function ps({message:t}){const s=t.agentContent,a=y(j=>j.isStreaming&&j.currentAssistantMessageId===t.id);if(!s){const j=we(t.content);return j?e.jsx(Ae,{content:j}):null}const{toolCalls:r,tasks:i,confirmation:n,question:d,elicitation:b}=s,u=Mt(s),c=At(s);if(!(c.length>0||i.length>0||u.length>0||n||d||b)&&a)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 p=r.length>0&&r.every(j=>j.status==="success"||j.status==="error")&&!a,x=!a;return e.jsxs("div",{className:"space-y-3",children:[c.map(j=>j.type==="thinking"?e.jsx("div",{"data-agent-timeline-block":"thinking",children:e.jsx(cs,{content:j.content})},j.id):j.type==="text"?e.jsx("div",{"data-agent-timeline-block":"text",children:e.jsx(Ae,{content:j.content,syntaxHighlight:x})},j.id):e.jsx("div",{"data-agent-timeline-block":"tool_group",children:e.jsx(ls,{toolCalls:r,toolCallIds:j.toolCallIds})},j.id)),i.length>0&&e.jsx(ds,{tasks:i}),u.map(j=>e.jsx(ms,{subagent:j},j.id)),n&&e.jsx(hs,{confirmation:n,messageId:t.id}),d&&e.jsx(xs,{question:d,messageId:t.id}),b&&e.jsx(qt,{elicitation:b,messageId:t.id}),p&&e.jsx(us,{toolCalls:r})]})}function fs({message:t,showAvatar:s=!0}){var b,u,c,k;const a=t.role==="user";if(t.role==="system"){const l=we(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:l})})}if(a){const l=(b=t.metadata)!=null&&b.userShellCommand&&typeof t.metadata.userShellCommand=="object"?t.metadata.userShellCommand:(u=t.metadata)!=null&&u.userShellExecution&&typeof t.metadata.userShellExecution=="object"?t.metadata.userShellExecution:void 0;if(l){const j=typeof l.command=="string"?l.command:"",S=l.status==="running"?"running":l.status==="completed"?"success":"error",h=typeof l.output=="string"?l.output:[typeof l.stdout=="string"?l.stdout:"",typeof l.stderr=="string"&&l.stderr?`stderr:
16
+ ${l.stderr}`:""].filter(Boolean).join(`
17
+ `);return e.jsx("div",{"data-chat-message-id":t.id,"data-chat-role":"user","data-user-shell-command":!0,className:"flex w-full justify-end p-4",children:e.jsxs("div",{className:"w-full max-w-[85%] overflow-hidden rounded-lg border border-[hsl(var(--deck-border))] bg-[hsl(var(--deck-surface))]",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3 border-b border-[hsl(var(--deck-border))] bg-[hsl(var(--deck-surface-2))] px-3 py-2",children:[e.jsxs("div",{className:"min-w-0 truncate font-mono text-[12px] text-[hsl(var(--deck-ink))]",children:[e.jsx("span",{className:"mr-2 text-amber-600 dark:text-amber-400",children:"$"}),j]}),e.jsx(Ne,{status:S})]}),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:h||"(no output)"}),typeof l.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 ",l.exitCode,typeof l.durationMs=="number"?` · ${(l.durationMs/1e3).toFixed(3)}s`:"",l.truncated===!0?" · truncated":""]})]})})}const{text:p,images:x}=as(t.content);return e.jsxs("div",{"data-chat-message-id":t.id,"data-chat-role":"user",className:"group flex gap-2 justify-end p-4 w-full items-start",children:[e.jsx("div",{className:"mt-1 flex shrink-0 opacity-0 transition-opacity group-hover:opacity-100 group-focus-within:opacity-100",children:e.jsx(Te,{text:p,label:"Copy message"})}),e.jsxs("div",{className:"bg-[hsl(var(--deck-surface-2))] rounded-lg px-4 py-3 max-w-[85%]",children:[p&&e.jsx("p",{className:"text-[14px] text-[hsl(var(--deck-ink))] font-mono leading-relaxed whitespace-pre-wrap",children:p}),x.length>0&&e.jsx("div",{className:M("grid gap-2",x.length===1?"grid-cols-1 mt-0":"grid-cols-2 mt-3"),children:x.map((j,S)=>e.jsx("img",{src:j,alt:`attachment-${S+1}`,className:"object-cover w-full max-h-64 rounded-md"},`${j}-${S}`))})]}),e.jsx(ss,{})]})}const i=rs(t),n=Ut((c=t.metadata)==null?void 0:c.codeReview),d=Xt((k=t.metadata)==null?void 0:k.structuredOutput);return e.jsxs("div",{"data-chat-message-id":t.id,"data-chat-role":"assistant",className:M("group flex gap-4 justify-start w-full",s?"p-4":"px-4 pt-0 pb-3"),children:[s?e.jsx(ts,{}):e.jsx("div",{className:"w-8 shrink-0"}),e.jsxs("div",{className:"overflow-hidden flex-1 min-w-0",children:[n?e.jsx(Kt,{report:n}):d?e.jsx(Zt,{report:d}):e.jsx(ps,{message:t}),!d&&i.trim()&&e.jsx("div",{className:"mt-1.5 flex opacity-0 transition-opacity group-hover:opacity-100 group-focus-within:opacity-100",children:e.jsx(Te,{text:i,label:"Copy response"})})]})]})}const bs=f.memo(fs);function vs(t,s,a){return Math.max(0,t+(a-s))}function gs(t,s,a){return Math.min(s,Math.max(0,t)+Math.max(0,a))}function $e(t,s){return t?t.querySelector(`[data-chat-message-id="${CSS.escape(s)}"]`):null}function ks({turns:t,viewportRef:s,containerRef:a,onRevealTurn:r}){const i=D(),[n,d]=f.useState(null),[b,u]=f.useState(!1),c=f.useRef(null),k=f.useCallback(()=>{var h;const p=s.current,x=a.current;if(!p||!x||t.length===0)return;const j=p.getBoundingClientRect().top;let S=((h=t[0])==null?void 0:h.id)??null;for(const N of t){const v=$e(x,N.id);if(v)if(v.getBoundingClientRect().top-j<=24)S=N.id;else break}d(S)},[t,s,a]);f.useEffect(()=>{const p=s.current;if(!p)return;const x=()=>{c.current===null&&(c.current=window.requestAnimationFrame(()=>{c.current=null,k()}))};return k(),p.addEventListener("scroll",x,{passive:!0}),()=>{p.removeEventListener("scroll",x),c.current!==null&&(window.cancelAnimationFrame(c.current),c.current=null)}},[k,s]);const l=f.useCallback(p=>{const x=()=>{const S=$e(a.current,p.id);S&&(S.scrollIntoView({behavior:"smooth",block:"start"}),d(p.id))};r(p.index)?x():window.requestAnimationFrame(()=>window.requestAnimationFrame(x))},[a,r]);return t.length<2?null:e.jsx("nav",{"aria-label":i("chat.turns.aria"),className:"absolute right-1 top-1/2 z-20 hidden -translate-y-1/2 sm:block",onMouseEnter:()=>u(!0),onMouseLeave:()=>u(!1),onFocusCapture:()=>u(!0),onBlurCapture:p=>{p.currentTarget.contains(p.relatedTarget)||u(!1)},children:e.jsxs("div",{className:"relative flex items-center justify-end",children:[e.jsx("ul",{className:M("flex flex-col items-center gap-2 py-2 transition-opacity",b?"opacity-0":"opacity-100"),"aria-hidden":b,children:t.map(p=>e.jsx("li",{children:e.jsx("span",{className:M("block rounded-full transition-all",p.id===n?"h-2 w-2 bg-[hsl(var(--deck-accent))]":"h-1.5 w-1.5 bg-[hsl(var(--deck-ink-faint))]/40")})},p.id))}),e.jsx("div",{className:M("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",b?"pointer-events-auto translate-x-0 opacity-100":"pointer-events-none translate-x-2 opacity-0"),children:t.map((p,x)=>e.jsxs("button",{type:"button",onClick:()=>l(p),className:M("flex w-full items-start gap-2 rounded-md px-2 py-1.5 text-left transition-colors",p.id===n?"bg-[hsl(var(--deck-hairline))]/70 text-[hsl(var(--deck-ink))]":"text-[hsl(var(--deck-ink-muted))] hover:bg-[hsl(var(--deck-hairline))]/50 hover:text-[hsl(var(--deck-ink))]"),children:[e.jsx("span",{className:M("mt-1 h-1.5 w-1.5 shrink-0 rounded-full",p.id===n?"bg-[hsl(var(--deck-accent))]":"bg-[hsl(var(--deck-ink-faint))]/40")}),e.jsxs("span",{className:"min-w-0 flex-1",children:[e.jsx("span",{className:"block font-mono text-[9.5px] uppercase tracking-[0.12em] text-[hsl(var(--deck-ink-faint))]",children:i("chat.turns.label",{n:x+1})}),e.jsx("span",{className:"line-clamp-2 text-[12px] leading-4",children:p.preview})]})]},p.id))})]})})}const De=80;function js(t){return typeof t=="string"?t:Array.isArray(t)?t.filter(s=>s.type==="text").map(s=>s.text).join(" "):""}function ys(t){const s=js(t).replace(/\s+/g," ").trim();return s?s.length>De?`${s.slice(0,De-1)}…`:s:""}function ws(t){const s=[];for(let a=0;a<t.length;a+=1){const r=t[a];if(r.role!=="user"||!r.id)continue;const i=ys(r.content);i&&s.push({id:r.id,index:a,preview:i})}return s}const xe=120,pe=80,Ns=96;function Y(t){return(t==null?void 0:t.querySelector("[data-radix-scroll-area-viewport]"))??null}function Ss({messages:t,isLoading:s}){const a=D(),r=f.useRef(null),i=f.useRef(null),n=f.useRef(!0),d=f.useRef(t.length),b=f.useRef(null),[u,c]=f.useState(xe),[k,l]=f.useState(!1);f.useEffect(()=>{const o=Y(r.current);if(!o||!n.current)return;const m=window.requestAnimationFrame(()=>{o.scrollTop=o.scrollHeight});return()=>window.cancelAnimationFrame(m)},[t]),f.useEffect(()=>{const o=Y(r.current);if(!o)return;i.current=o;const m=()=>{const w=o.scrollHeight-o.scrollTop-o.clientHeight<=Ns;n.current=w,l(!w)};return m(),o.addEventListener("scroll",m,{passive:!0}),()=>o.removeEventListener("scroll",m)},[]),f.useEffect(()=>{const o=d.current;d.current=t.length,c(m=>m>=o&&t.length>o?t.length:Math.min(Math.max(m,xe),t.length||xe))},[t.length]);const p=Math.max(t.length-u,0),x=p,j=f.useMemo(()=>t.slice(x),[t,x]),S=f.useMemo(()=>ws(t),[t]);if(f.useLayoutEffect(()=>{var E;const o=b.current;if(!o)return;const m=Y(r.current);if(b.current=null,!!m){if((E=o.element)!=null&&E.isConnected){const w=o.element.getBoundingClientRect().top-o.viewportTop;m.scrollTop+=w;return}m.scrollTop=vs(o.scrollTop,o.scrollHeight,m.scrollHeight)}},[u]),s)return e.jsx("div",{role:"status","aria-live":"polite","aria-busy":"true",className:"flex overflow-hidden flex-1 justify-center items-center px-5 py-8 min-h-0",children:e.jsxs("div",{className:"w-full max-w-[560px]",children:[e.jsxs("div",{className:"flex flex-col items-center text-center",children:[e.jsxs("div",{className:"relative",children:[e.jsx("div",{className:"absolute inset-0 animate-pulse rounded-full bg-[hsl(var(--deck-accent-soft))] blur-xl"}),e.jsx(be,{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(xt,{className:"w-3 h-3"}),a("chat.list.loading.eyebrow")]}),e.jsx("h2",{className:"mt-2 text-[15px] font-medium text-[hsl(var(--deck-ink))]",children:a("chat.list.loading.title")}),e.jsx("p",{className:"mt-1 max-w-sm text-[11.5px] leading-5 text-[hsl(var(--deck-ink-faint))]",children:a("chat.list.loading.hint")})]}),e.jsx("div",{"aria-hidden":"true",className:"mt-7 space-y-4 rounded-xl border border-[hsl(var(--deck-hairline))] bg-[hsl(var(--deck-surface))]/45 px-4 py-5",children:[72,88,64].map((o,m)=>e.jsxs("div",{className:M("flex gap-3",m%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:`${o}%`,animationDelay:`${m*120}ms`}})]},o))})]})});if(t.length===0&&!s)return e.jsx("div",{className:"flex flex-1 justify-center items-center",children:e.jsxs("div",{className:"flex flex-col gap-4 items-center text-center",children:[e.jsx(be,{size:44}),e.jsxs("div",{children:[e.jsx("div",{className:"deck-eyebrow text-[hsl(var(--deck-accent))]",children:a("chat.list.empty.eyebrow")}),e.jsx("div",{className:"mt-2 text-[15px] font-medium text-[hsl(var(--deck-ink))]",children:a("chat.list.empty.title")}),e.jsx("div",{className:"mt-1 max-w-xs text-[12px] text-[hsl(var(--deck-ink-muted))]",children:a("chat.list.empty.hint")})]})]})});const h=()=>{const o=Y(r.current);o&&(n.current=!0,l(!1),o.scrollTo({top:o.scrollHeight,behavior:"smooth"}))},N=()=>{var m;const o=Y(r.current);if(o){const E=((m=r.current)==null?void 0:m.querySelector("[data-chat-message-id]"))??null;b.current={element:E,viewportTop:(E==null?void 0:E.getBoundingClientRect().top)??0,scrollHeight:o.scrollHeight,scrollTop:o.scrollTop}}c(E=>gs(E,t.length,pe))},v=o=>o>=x?!0:(c(t.length),!1);return e.jsxs("div",{ref:r,className:"relative flex-1 min-h-0",children:[e.jsx(st,{className:"h-full",children:e.jsxs("div",{className:"flex flex-col px-4 pb-4 w-full md:px-6",children:[p>0&&e.jsx("div",{className:"flex justify-center py-3",children:e.jsx("button",{type:"button",onClick:N,"aria-label":a("chat.list.showEarlierWithRemaining",{count:Math.min(p,pe),remaining:p}),className:"rounded-md border border-[hsl(var(--deck-border))] bg-[hsl(var(--deck-surface))] px-3 py-1.5 font-mono text-[12px] text-[hsl(var(--deck-ink-muted))] transition-colors hover:border-[hsl(var(--deck-border-strong))] hover:text-[hsl(var(--deck-ink))]",children:a("chat.list.showEarlier",{count:Math.min(p,pe)})})}),j.map((o,m)=>{const E=x+m,w=E>0?t[E-1]:null,C=!w||w.role!==o.role||w.role==="user";return e.jsx(bs,{message:o,showAvatar:C},o.id||`msg-${E}`)})]})}),e.jsx(ks,{turns:S,viewportRef:i,containerRef:r,onRevealTurn:v}),k&&e.jsxs("button",{type:"button",onClick:h,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(ze,{className:"h-3.5 w-3.5 text-[hsl(var(--deck-accent))]"}),a("chat.list.jumpLatest")]})]})}const Xe=f.memo(Ss),ve=Dt,ge=Bt,ke=It,ce=f.forwardRef(({className:t,sideOffset:s=4,...a},r)=>e.jsx(Qe,{ref:r,sideOffset:s,className:M("z-50 overflow-hidden rounded-md border bg-popover px-3 py-1.5 text-sm text-popover-foreground shadow-md animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 origin-[--radix-tooltip-content-transform-origin]",t),...a}));ce.displayName=Qe.displayName;const Cs={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 re(t){return t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${(t/1e3).toFixed(1)}K`:String(t)}function Es(t){if(t<60)return`${t}s`;const s=Math.floor(t/60),a=t%60;return a===0?`${s}m`:`${s}m ${a}s`}function Ts(){var U,B,L,V;const t=D(),{locale:s}=Ue(),a=y(T=>T.goal),r=y(T=>T.pauseGoal),i=y(T=>T.resumeGoal),n=y(T=>T.editGoal),d=y(T=>T.clearGoal),[b,u]=f.useState(!1),[c,k]=f.useState(!1),[l,p]=f.useState(""),[x,j]=f.useState(null),[S,h]=f.useState(!1);if(f.useEffect(()=>{u(!1),k(!1),p((a==null?void 0:a.objective)??""),h(!1)},[a==null?void 0:a.goalId]),!a)return null;const N=Cs[a.status],v=["active","verifying","paused","blocked"].includes(a.status),o=a.status==="active"||a.status==="verifying",m=a.status==="paused"||a.status==="blocked",E=x!==null,w=async(T,P)=>{j(T);try{await P()}finally{j(null)}},C=()=>{p(a.objective),k(!0),u(!0)},R=async T=>{T.preventDefault();const P=l.trim();if(!P||P===a.objective){k(!1);return}await w("edit",()=>n(P)),k(!1)},O=async()=>{await w("delete",d),h(!1)};return e.jsxs(e.Fragment,{children:[e.jsx(ve,{delayDuration:250,children:e.jsxs("section",{"aria-label":t("goal.aria.section"),className:"mx-3 mb-1 shrink-0","data-blade-goal-status":a.status,"data-blade-goal-recovery":(U=a.prematureStop)==null?void 0:U.consecutiveCount,"data-blade-goal-recovery-pattern":(B=a.prematureStop)==null?void 0:B.pattern,"data-blade-goal-verification-stall":(L=a.verificationStall)==null?void 0:L.consecutiveCount,children:[e.jsxs("div",{className:M("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",b&&"rounded-b-none border-b-0"),children:[a.status==="complete"?e.jsx(pt,{className:"h-3.5 w-3.5 shrink-0 text-emerald-500"}):e.jsx(ft,{className:M("h-3.5 w-3.5 shrink-0",N.accent)}),e.jsx("span",{className:M("h-1.5 w-1.5 shrink-0 rounded-full",N.dot)}),e.jsx("span",{className:M("shrink-0 text-[10px] font-medium leading-none",N.accent),children:a.status==="verifying"?s==="zh"?"验证中":"Verifying":t(N.labelKey)}),e.jsx("span",{className:"h-3 w-px shrink-0 bg-[hsl(var(--deck-hairline))]"}),e.jsx("button",{type:"button","aria-label":t(b?"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:()=>u(T=>!T),"aria-expanded":b,title:a.objective,children:a.objective}),a.tokensUsed>0&&e.jsxs("span",{className:"hidden shrink-0 text-[10px] tabular-nums text-[hsl(var(--deck-ink-muted))] sm:inline",children:[re(a.tokensUsed),a.tokenBudget!==void 0&&`/${re(a.tokenBudget)}`]}),e.jsxs("div",{className:"flex shrink-0 items-center",children:[o&&e.jsx(ne,{label:t("goal.action.pause"),disabled:E,onClick:()=>void w("pause",r),children:x==="pause"?e.jsx($,{className:"animate-spin"}):e.jsx(bt,{})}),m&&e.jsx(ne,{label:t("goal.action.resume"),disabled:E,onClick:()=>void w("resume",i),children:x==="resume"?e.jsx($,{className:"animate-spin"}):e.jsx(vt,{})}),e.jsx(ne,{label:t(v?"goal.action.edit":"goal.action.expand"),disabled:!v&&!b,onClick:v?C:()=>u(T=>!T),children:v?e.jsx(Ge,{}):e.jsx(gt,{})}),e.jsx(ne,{label:t("goal.action.delete"),disabled:E,destructive:!0,onClick:()=>h(!0),children:e.jsx(Z,{})})]})]}),b&&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:c?e.jsxs("form",{onSubmit:R,children:[e.jsx("textarea",{id:"goal-objective",value:l,onChange:T=>p(T.target.value),onKeyDown:T=>{T.key==="Escape"&&k(!1)},rows:3,autoFocus:!0,className:"w-full resize-none rounded-md border border-[hsl(var(--deck-border))] bg-[hsl(var(--deck-canvas))] px-3 py-2 text-[12px] leading-5 text-[hsl(var(--deck-ink))] outline-none transition-shadow focus:border-[hsl(var(--deck-accent))] focus:ring-1 focus:ring-[hsl(var(--deck-accent-glow))]"}),e.jsxs("div",{className:"mt-2 flex items-center justify-end gap-2",children:[e.jsxs("button",{type:"button",onClick:()=>k(!1),className:"inline-flex h-7 items-center gap-1 rounded-md px-2.5 text-[11px] text-[hsl(var(--deck-ink-muted))] transition-colors hover:bg-[hsl(var(--deck-hairline))]/60",children:[e.jsx(We,{className:"h-3 w-3"}),t("goal.action.cancel")]}),e.jsxs("button",{type:"submit",disabled:!l.trim()||x==="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:[x==="edit"?e.jsx($,{className:"h-3 w-3 animate-spin"}):e.jsx(de,{className:"h-3 w-3"}),t("goal.action.save")]})]})]}):e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"whitespace-pre-wrap text-[12px] leading-5 text-[hsl(var(--deck-ink))]/90",children:a.objective}),e.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-x-4 gap-y-1.5 text-[10px] text-[hsl(var(--deck-ink-muted))]",children:[e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx(kt,{className:"h-3 w-3"}),re(a.tokensUsed),a.tokenBudget!==void 0&&` / ${re(a.tokenBudget)}`," ",t("goal.metrics.tokens")]}),e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx(jt,{className:"h-3 w-3"}),Es(a.timeUsedSeconds)]}),e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx(oe,{className:"h-3 w-3"}),a.continuationCount===1?t("goal.metrics.continuationOne",{n:a.continuationCount}):t("goal.metrics.continuationMany",{n:a.continuationCount})]})]}),a.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(oe,{className:"h-3 w-3"}),s==="zh"?"恢复提示":"Recovery nudge"," ",a.prematureStop.consecutiveCount," ·"," ",a.prematureStop.pattern.replaceAll("_"," ")]}),a.completionVerification&&e.jsxs("div",{"data-goal-verification":a.completionVerification.status,className:"mt-2 rounded-md border border-sky-200/50 bg-sky-50/60 px-2.5 py-2 text-[11px] text-sky-900 dark:border-sky-400/15 dark:bg-sky-400/[0.05] dark:text-sky-100",children:[e.jsxs("p",{className:"font-mono font-medium",children:["#",a.completionVerification.attempt," ·"," ",a.completionVerification.status.toUpperCase()," ·"," ",((V=a.completionVerification.verifierSessionId)==null?void 0:V.slice(0,12))??"-",a.verificationStall?s==="zh"?` · 重复 ${a.verificationStall.consecutiveCount}/3`:` · repeat ${a.verificationStall.consecutiveCount}/3`:""]}),a.completionVerification.summary&&e.jsx("p",{className:"mt-1 line-clamp-3 whitespace-pre-wrap opacity-80",children:a.completionVerification.summary}),a.completionVerification.evidenceSha256&&e.jsxs("p",{className:"mt-1 font-mono text-[10px] opacity-60",children:["sha256:",a.completionVerification.evidenceSha256.slice(0,12)]})]}),a.statusReason&&e.jsx("div",{className:"mt-2 rounded-md border border-amber-200/50 bg-amber-50/60 px-2.5 py-1.5 text-[11px] text-amber-800 dark:border-amber-400/15 dark:bg-amber-400/[0.05] dark:text-amber-200",children:a.statusReason})]})})]})}),e.jsx(Ie,{open:S,onOpenChange:h,children:e.jsxs(_e,{className:"max-w-[400px] border-[hsl(var(--deck-border))] bg-[hsl(var(--deck-surface))]",children:[e.jsx(Pe,{children:t("goal.dialog.title")}),e.jsx(Le,{children:t("goal.dialog.description")}),e.jsxs(Ve,{className:"mt-2",children:[e.jsx("button",{type:"button",onClick:()=>h(!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:x==="delete",onClick:()=>void O(),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:[x==="delete"&&e.jsx($,{className:"w-3.5 h-3.5 animate-spin"}),t("goal.action.delete")]})]})]})})]})}function ne({label:t,children:s,disabled:a,destructive:r,onClick:i}){return e.jsxs(ge,{children:[e.jsx(ke,{asChild:!0,children:e.jsx("button",{type:"button","aria-label":t,disabled:a,onClick:i,className:M("flex h-6 w-6 items-center justify-center rounded-md text-[hsl(var(--deck-ink-muted))] outline-none transition-colors focus-visible:ring-1 focus-visible:ring-[hsl(var(--deck-accent-glow))]/50 disabled:cursor-not-allowed disabled:opacity-35 [&_svg]:h-3.5 [&_svg]:w-3.5",r?"hover:bg-rose-500/10 hover:text-rose-500":"hover:bg-[hsl(var(--deck-hairline))]/60 hover:text-[hsl(var(--deck-ink))]"),children:s})}),e.jsx(ce,{side:"top",className:"text-[10px]",children:t})]})}function Ms(){const t=D(),s=y(u=>u.currentSessionRef),a=y(u=>u.sessions),r=y(u=>u.messages),i=f.useMemo(()=>{var c,k,l,p,x;const u=s?(c=at(a,s))==null?void 0:c.pendingInteraction:void 0;if(u)return u.type;for(let j=r.length-1;j>=0;j-=1){const S=(k=r[j])==null?void 0:k.agentContent;if(((l=S==null?void 0:S.confirmation)==null?void 0:l.status)==="pending")return"permission";if(((p=S==null?void 0:S.question)==null?void 0:p.status)==="pending")return"question";if(((x=S==null?void 0:S.elicitation)==null?void 0:x.status)==="pending")return"elicitation"}return null},[s,r,a]);if(!i)return null;const n=()=>{const u=document.querySelector(`[data-pending-interaction="${i}"]`);u==null||u.scrollIntoView({block:"center",behavior:"smooth"}),window.setTimeout(()=>u==null?void 0:u.focus(),250)},d=i==="question",b=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(ye,{className:"h-4 w-4 shrink-0 text-amber-600 dark:text-amber-400"}),e.jsxs("div",{className:"min-w-[180px] flex-1",children:[e.jsx("div",{className:"text-[11.5px] font-semibold",children:t(d?"interaction.bar.questionTitle":b?"interaction.bar.elicitationTitle":"interaction.bar.permissionTitle")}),e.jsx("div",{className:"mt-0.5 text-[10px] leading-4 text-amber-800 dark:text-amber-300",children:t(d?"interaction.bar.questionHint":b?"interaction.bar.elicitationHint":"interaction.bar.permissionHint")})]}),e.jsxs("button",{type:"button",onClick:n,className:"inline-flex min-h-8 shrink-0 items-center gap-1.5 rounded-md border border-amber-400/80 bg-white/80 px-2.5 text-[10.5px] font-medium transition-colors hover:bg-white focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-amber-500 dark:border-amber-700 dark:bg-amber-950/70 dark:hover:bg-amber-900",children:[e.jsx(ze,{className:"h-3 w-3"}),t("interaction.bar.review")]})]})}const As=f.lazy(()=>Oe(()=>import("./MarkdownRenderer-BVPIxk31.js").then(t=>t.M),__vite__mapDeps([0,1,2,3,4,5,6])).then(t=>({default:t.MarkdownRenderer})));function Rs(t){return t<1e3?`${t}ms`:`${(t/1e3).toFixed(1)}s`}function Fs(){const t=D(),s=y(r=>r.sideConversation),a=y(r=>r.dismissSideConversation);return s?e.jsx("section",{"aria-label":t("chat.side.title"),"data-blade-side-conversation":!0,"data-status":s.status,className:"shrink-0 border-y border-[hsl(var(--deck-accent)/0.28)] bg-[hsl(var(--deck-accent-soft)/0.42)]",children:e.jsxs("div",{className:"px-4 py-3 md:px-6",children:[e.jsxs("header",{className:"flex min-h-7 items-start gap-2",children:[e.jsx(yt,{"aria-hidden":!0,className:"mt-0.5 h-4 w-4 shrink-0 text-[hsl(var(--deck-accent))]"}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex flex-wrap items-baseline gap-x-2 gap-y-1",children:[e.jsx("h2",{className:"font-mono text-[11px] font-semibold uppercase text-[hsl(var(--deck-accent))]",children:t("chat.side.title")}),s.durationMs!==void 0&&e.jsxs("span",{className:"inline-flex items-center gap-1 font-mono text-[9.5px] text-[hsl(var(--deck-ink-faint))]",children:[e.jsx(wt,{"aria-hidden":!0,className:"h-3 w-3"}),Rs(s.durationMs)]})]}),e.jsx("p",{className:"mt-0.5 break-words font-mono text-[11px] leading-4 text-[hsl(var(--deck-ink-muted))]",children:s.question})]}),e.jsx("button",{type:"button",onClick:a,"aria-label":t("chat.side.dismiss"),title:t("chat.side.dismiss"),className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-md text-[hsl(var(--deck-ink-faint))] transition-colors hover:bg-[hsl(var(--deck-surface))] hover:text-[hsl(var(--deck-ink))] focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-[hsl(var(--deck-accent))]",children:e.jsx(We,{"aria-hidden":!0,className:"h-3.5 w-3.5"})})]}),e.jsxs("div",{"aria-live":"polite","aria-busy":s.status==="loading",className:"mt-2 max-h-[min(36vh,320px)] overflow-y-auto border-l-2 border-[hsl(var(--deck-accent)/0.42)] pl-3 pr-1",children:[s.status==="loading"&&e.jsxs("div",{role:"status",className:"flex min-h-9 items-center gap-2 font-mono text-[11px] text-[hsl(var(--deck-ink-muted))]",children:[e.jsx($,{"aria-hidden":!0,className:"h-3.5 w-3.5 animate-spin text-[hsl(var(--deck-accent))]"}),t("chat.side.loading")]}),s.status==="error"&&e.jsxs("div",{role:"alert",className:"flex min-h-9 items-start gap-2 font-mono text-[11px] leading-5 text-red-700 dark:text-red-300",children:[e.jsx(ye,{"aria-hidden":!0,className:"mt-0.5 h-3.5 w-3.5 shrink-0"}),e.jsx("span",{className:"break-words",children:s.error??t("chat.side.failed")})]}),s.status==="completed"&&s.response&&e.jsx(f.Suspense,{fallback:e.jsx("div",{className:"whitespace-pre-wrap break-words font-mono text-[12px] leading-5 text-[hsl(var(--deck-ink))]",children:s.response}),children:e.jsx(As,{content:s.response,className:"text-[12px] leading-5 [&_h1]:text-[14px] [&_h2]:text-[13px] [&_h3]:text-[12px]"})})]})]})}):null}function fe(t){return Number.isFinite(t)?Math.max(0,t):0}function $s(t){const s=fe(t.totalInputTokens),a=fe(t.cacheReadTokens),r=fe(t.cacheWriteTokens),i=Math.min(a,s),n=Math.min(r,Math.max(0,s-i)),d=Math.max(0,s-i-n),b=s>0&&(a>0||r>0);return{totalInputTokens:s,cacheReadTokens:i,cacheWriteTokens:n,uncachedInputTokens:d,...b?{hitRate:i/s}:{}}}function Ds(t){return t===void 0||!Number.isFinite(t)?"—":`${Math.round(Math.max(0,Math.min(1,t))*100)}%`}const Bs={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:""},Is={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"},q=t=>t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${(t/1e3).toFixed(1)}K`:t.toString(),ie=t=>{const s=Math.max(0,Math.ceil(t/1e3)),a=Math.floor(s/60),r=s%60;return a>0?`${a}m ${r}s`:`${r}s`};function Ze(){const t=D(),s=y(N=>N.tokenUsage),a=y(N=>N.isStreaming),r=y(N=>N.agentPhase),i=y(N=>N.providerAdmission),n=y(N=>N.providerCircuit),d=y(N=>N.providerRetry),b=y(N=>N.providerStall),u=y(N=>N.actionStationarity),c=Bs[r]??"",k=(d==null?void 0:d.delayMs)!==void 0?` · ${Math.max(0,Math.ceil(d.delayMs/1e3))}s`:"",l=u?`${t(u.phase==="halted"?"status.phase.actionStationarityStopped":"status.phase.actionStationarityRecovering")} · ${u.toolName} · ${u.runLength}/${u.haltThreshold}`:n?n.phase==="probe"?"Provider · Recovery probe":`Provider · Circuit open${n.retryAfterMs!==void 0?` · probe in ${ie(n.retryAfterMs)}`:""}${n.recoveryRemainingMs!==void 0?` · ${ie(n.recoveryRemainingMs)}`:""}`:i?`Provider · Capacity queue ${i.queuePosition}/${Math.max(i.queueDepth,i.queuePosition)} · ${i.scope} · ${ie(i.waitMs)}`:d?d.mode==="bounded_foreground"?`Provider · Bounded recovery · ${d.attempt}/${d.maxRetries} · ${ie(d.recoveryRemainingMs??0)}`:`Provider · ${t("chat.error.action.retryingTask")} · ${d.attempt}/${d.maxRetries}${k}`:b?`${t("status.phase.providerStall")} · ${Math.ceil(b.durationMs/1e3)}s / ${Math.ceil(b.timeoutMs/1e3)}s`:c?t(c):"",p=s.maxContextTokens>0?Math.round(s.totalTokens/s.maxContextTokens*100):0,x=$s(s),j=Ds(x.hitRate),S=Math.min(p,100),h=p>95?"danger":p>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:M("text-[12px] font-medium",h==="safe"&&"text-[hsl(var(--deck-ink))]",h==="warn"&&"text-amber-600 dark:text-amber-400",h==="danger"&&"text-red-600 dark:text-red-400"),children:q(s.totalTokens)}),e.jsxs("span",{className:"text-[hsl(var(--deck-ink-faint))]",children:["/ ",q(s.maxContextTokens)]})]}),s.isDefaultMaxTokens&&e.jsx(ve,{children:e.jsxs(ge,{children:[e.jsx(ke,{asChild:!0,children:e.jsx(Nt,{className:"h-3 w-3 cursor-help text-[hsl(var(--deck-ink-faint))]"})}),e.jsx(ce,{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:M("absolute inset-y-0 left-0 transition-[width] duration-300",h==="safe"&&"bg-[hsl(var(--deck-accent))]",h==="warn"&&"bg-amber-500",h==="danger"&&"bg-red-500"),style:{width:`${S}%`}}),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:M("w-10 text-right tabular-nums text-[hsl(var(--deck-ink-faint))]",h==="warn"&&"text-amber-600 dark:text-amber-400",h==="danger"&&"text-red-600 dark:text-red-400"),children:[p,"%"]})]}),e.jsx(ve,{children:e.jsxs(ge,{children:[e.jsx(ke,{asChild:!0,children:e.jsxs("div",{className:"flex shrink-0 cursor-help items-baseline gap-2 border-l border-[hsl(var(--deck-hairline))] pl-2 sm:pl-4","data-testid":"prompt-cache-hit-rate","aria-label":`${t("status.cache")} ${j}`,children:[e.jsx("span",{className:"deck-eyebrow text-[hsl(var(--deck-ink-faint))]",children:t("status.cache")}),e.jsx("span",{className:M("tabular-nums",x.hitRate===void 0?"text-[hsl(var(--deck-ink-faint))]":"font-medium text-[hsl(var(--deck-accent))]"),children:j})]})}),e.jsx(ce,{side:"top",className:"max-w-[280px]",children:x.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:q(x.cacheReadTokens),write:q(x.cacheWriteTokens),uncached:q(x.uncachedInputTokens)})}),s.cacheBreak&&e.jsx("p",{className:"text-[hsl(var(--deck-accent))]",children:t("status.cacheBreak",{reason:t(Is[s.cacheBreak.reason]??"status.cacheBreak.server"),previous:q(s.cacheBreak.previousCacheReadTokens),current:q(s.cacheBreak.cacheReadTokens)})})]})})]})}),e.jsx("div",{className:"flex-1"}),a&&l&&e.jsxs("div",{className:"flex gap-2 items-center",children:[e.jsx("span",{className:"deck-pulse-dot"}),e.jsx("span",{className:"text-[hsl(var(--deck-accent))]",children:l})]})]})}function _s(){const{locale:t}=Ue(),s=rt(o=>o.agentTeamsEnabled),a=y(o=>o.teams),r=y(o=>o.currentSessionRef),i=y(o=>o.loadTeams),[n,d]=f.useState({}),[b,u]=f.useState({}),[c,k]=f.useState({}),[l,p]=f.useState(null),[x,j]=f.useState(null),[S,h]=f.useState(null);if(f.useEffect(()=>{i(r??void 0)},[s,r,i]),!s||!r||a.length===0)return null;const N=async o=>{var E;const m=(E=c[o])==null?void 0:E.trim();if(!(!m||l)){p(o),h(null);try{await Ce.sendMessage(r,o,b[o]??"*",m),k(w=>({...w,[o]:""})),await i(r)}catch(w){h(w instanceof Error?w.message:F(t,"actionFailed"))}finally{p(null)}}},v=async o=>{if(!x){j(o),h(null);try{await Ce.delete(r,o),await i(r)}catch(m){h(m instanceof Error?m.message:F(t,"actionFailed"))}finally{j(null)}}};return e.jsxs("section",{"aria-label":F(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:[S&&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:S}),a.filter(o=>o.status!=="deleted").map(o=>{var w;const m=n[o.name]??o.status==="running",E=o.tasks.filter(C=>C.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:()=>d(C=>({...C,[o.name]:!m})),"aria-label":m?F(t,"collapse"):F(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:m?e.jsx(ee,{className:"h-4 w-4"}):e.jsx(te,{className:"h-4 w-4"})}),e.jsx(St,{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:o.name}),e.jsxs("span",{className:"font-mono text-[9.5px] text-[hsl(var(--deck-ink-faint))]",children:[o.status," · ",o.members.length-1," ",F(t,"members")," · ",E,"/",o.tasks.length," ",F(t,"tasks")]})]}),o.description&&e.jsx("p",{className:"truncate font-mono text-[10px] text-[hsl(var(--deck-ink-muted))]",children:o.description})]}),e.jsx("button",{type:"button",onClick:()=>void v(o.name),disabled:x===o.name,"aria-label":F(t,"delete"),title:F(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(Z,{className:"h-3.5 w-3.5"})})]}),m&&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:F(t,"members")}),o.members.map(C=>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":C.status,className:`h-1.5 w-1.5 shrink-0 rounded-full ${C.status==="running"?"bg-emerald-500":C.status==="completed"||C.status==="leader"?"bg-sky-500":C.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:C.name}),e.jsx("span",{className:"font-mono text-[9px] text-[hsl(var(--deck-ink-faint))]",children:C.subagentType}),C.worktreePath&&e.jsx(He,{className:"h-3 w-3 text-[hsl(var(--deck-ink-faint))]","aria-label":F(t,"worktree")})]},C.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:F(t,"tasks")}),o.tasks.length===0?e.jsx("p",{className:"font-mono text-[10px] text-[hsl(var(--deck-ink-faint))]",children:F(t,"noTasks")}):o.tasks.map(C=>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:["#",C.id]}),e.jsx("span",{className:"min-w-0 flex-1 truncate font-mono text-[10.5px] text-[hsl(var(--deck-ink))]",children:C.subject}),e.jsx("span",{className:"font-mono text-[9px] text-[hsl(var(--deck-ink-faint))]",children:C.status})]},C.id))]})]}),o.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":F(t,"recipient"),value:b[o.name]??"*",onChange:C=>u(R=>({...R,[o.name]:C.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:F(t,"broadcast")}),o.members.filter(C=>C.status!=="leader").map(C=>e.jsx("option",{value:C.name,children:C.name},C.id))]}),e.jsx("input",{value:c[o.name]??"",onChange:C=>k(R=>({...R,[o.name]:C.target.value})),onKeyDown:C=>{C.key==="Enter"&&N(o.name)},placeholder:F(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 N(o.name),disabled:!((w=c[o.name])!=null&&w.trim())||l===o.name,"aria-label":F(t,"send"),title:F(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(Ke,{className:"h-3.5 w-3.5"})})]})]})]},o.name)})]})}function Ps(t){const s=[...t].reverse().find(i=>i.role==="user");if(!s)return null;if(typeof s.content=="string")return{content:s.content,attachments:[]};const a=s.content.filter(i=>i.type==="text").map(i=>i.text).join(`
18
+ `),r=s.content.filter(i=>i.type==="image_url").map((i,n)=>{var b;const d=((b=i.image_url.url.match(/^data:([^;,]+)[;,]/))==null?void 0:b[1])??"application/octet-stream";return{id:`recovery-${s.id}-${n}`,name:`attachment-${n+1}`,mimeType:d,dataUrl:i.image_url.url}});return{content:a,attachments:r}}function Ls({messages:t,isLoading:s,isStreaming:a,isStopping:r,errorMessage:i}){const n=D(),[d,b]=f.useState(!1),u=n(i?"status.phase.error":r?"chat.input.action.stopping":a?"status.phase.running":"preview.files.status.ready");return e.jsxs("details",{"data-preview-status-disclosure":!0,open:d,onToggle:c=>b(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:[a&&e.jsx("span",{className:"deck-pulse-dot"}),e.jsx("span",{className:"min-w-0 flex-1 truncate",children:u}),e.jsx(te,{className:"h-3.5 w-3.5 shrink-0 transition-transform group-open:rotate-90"})]}),d&&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:[i&&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:i}),e.jsx(Xe,{messages:t,isLoading:s}),e.jsx(Ze,{})]})]})}function Gs(){var K;const t=D(),s=y(g=>g.messages),a=y(g=>g.currentSessionRef),r=y(g=>g.isStreaming),i=y(g=>g.isStopping),n=y(g=>g.sessionEventConnectionState),d=y(g=>g.pendingSteeringCount),b=y(g=>g.pendingInputDelivery),u=y(g=>g.recoveredSteeringCount),c=y(g=>g.isLoading),k=y(g=>g.error),l=y(g=>g.errorContext),p=y(g=>g.sessions),x=y(g=>g.sendMessage),j=y(g=>g.abortSession),S=y(g=>g.retryTask),h=y(g=>g.retryingTaskKeys),N=je(g=>g.openSettings),v=y(g=>g.reconnectSessionEvents),o=y(g=>g.clearError),[m,E]=f.useState(null),w=a?p.find(g=>g.sessionId===a.sessionId&&g.projectPath===a.projectPath):void 0,C=!!k&&((l==null?void 0:l.kind)==="navigation"||!(l!=null&&l.sessionRef)||Be(l.sessionRef,a)),R=(l==null?void 0:l.failureCode)??((K=w==null?void 0:w.taskFailure)==null?void 0:K.code),O=(l==null?void 0:l.kind)==="execution"&&R?t(Ft(R)):k==="queue_full"?t("chat.error.queueFull"):k==="turn_unavailable"||k==="turn_active"?t("chat.error.turnChanged"):k,U=n==="connecting"||n==="reconnecting",B=r&&n!=="connected",L=a?`session:${X(a)}`:"session:temporary",V=f.useMemo(()=>Ps(s),[s]),T=a?X(a):"temporary-session",P=!!(a&&(w!=null&&w.taskRetryAvailable)&&(!R||$t(R)))&&((l==null?void 0:l.kind)==="execution"||(l==null?void 0:l.kind)==="task_action"),Q=(l==null?void 0:l.kind)==="execution"&&(R==="authentication"||R==="permission"||R==="model_unavailable"),G=a?h.includes(X(a)):!1;f.useEffect(()=>{E(null)},[T]);const se=async g=>x({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(_=>({type:"image",content:_.dataUrl,mimeType:_.mimeType,name:_.name}))}),ae=()=>j(),A=async()=>{if(Q){o(),N("models");return}if(P&&a){o(),await S(a).catch(()=>{});return}if((l==null?void 0:l.kind)==="execution"&&V){E({...V,revision:Date.now()}),o();return}o(),requestAnimationFrame(()=>it())},H=P?t(G?"chat.error.action.retryingTask":"chat.error.action.retryTask"):Q?t("chat.error.action.checkModels"):(l==null?void 0:l.kind)==="execution"&&V?t("chat.error.action.editResend"):(l==null?void 0:l.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:[C&&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(ye,{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((l==null?void 0:l.kind)==="submission"?"chat.error.title.submission":(l==null?void 0:l.kind)==="execution"?"chat.error.title.execution":(l==null?void 0:l.kind)==="navigation"?"chat.error.title.navigation":"chat.error.title.generic")})," ",O]}),H&&e.jsxs("button",{type:"button",onClick:()=>void A(),disabled:G,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:[P?G?e.jsx($,{className:"h-3 w-3 animate-spin"}):e.jsx(oe,{className:"h-3 w-3"}):e.jsx(Ge,{className:"h-3 w-3"}),H]}),e.jsx("button",{type:"button",onClick:o,"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:"✕"})]}),(U||n==="offline")&&e.jsxs("div",{role:n==="offline"?"alert":"status","aria-live":"polite",className:"flex min-h-10 flex-wrap items-center gap-2 border-b border-amber-300/60 bg-amber-50/80 px-4 py-2 font-mono text-[11px] text-amber-900 dark:border-amber-800/60 dark:bg-amber-950/35 dark:text-amber-200 sm:px-5",children:[U?e.jsx($,{className:"h-3.5 w-3.5 shrink-0 animate-spin"}):e.jsx(Ct,{className:"h-3.5 w-3.5 shrink-0"}),e.jsx("span",{className:"min-w-0 flex-1",children:t(U?"chat.connection.reconnecting":"chat.connection.offline")}),n==="offline"&&e.jsxs("button",{type:"button",onClick:()=>void v().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(Et,{className:"h-3 w-3"}),t("chat.connection.retry")]})]}),e.jsx(_t,{}),e.jsx(Xe,{messages:s,isLoading:c},a?X(a):"temporary-session"),e.jsx(_s,{}),e.jsx(Fs,{})]}),e.jsxs("div",{"data-chat-composer-dock":!0,className:"contents",children:[e.jsx(Ls,{messages:s,isLoading:c,isStreaming:r,isStopping:i,errorMessage:C?O:null},T),e.jsx(Ms,{}),e.jsx(Ts,{}),e.jsx(nt,{draftKey:L,draft:m==null?void 0:m.content,draftAttachments:m==null?void 0:m.attachments,draftRevision:m==null?void 0:m.revision,onSend:se,onAbort:ae,disabled:c||B,isStreaming:r,isStopping:i,pendingSteeringCount:d,pendingInputDelivery:b,recoveredSteeringCount:u,workspacePath:a==null?void 0:a.projectPath},L),e.jsx("div",{"data-chat-primary-status":!0,className:"contents",children:e.jsx(Ze,{})})]})]})}export{Gs as ChatView};
@@ -1,4 +1,4 @@
1
- import{c as I,j as Ke}from"./vendor-react-DG5dkZ_t.js";import{f as Ve,p as Se,a as xe,n as Ae,h as Je,s as Qe,d as Ne}from"./MarkdownRenderer-BY51R1Fj.js";import"./index-DHX-G3RT.js";import"./vendor-radix-DXRuAJHH.js";import"./vendor-icons-DovdPN7M.js";import"./session-events-Bgir_Gl_.js";function Pe(e,t){if(e==null)return{};var n={};for(var a in e)if({}.hasOwnProperty.call(e,a)){if(t.indexOf(a)!==-1)continue;n[a]=e[a]}return n}function et(e,t){if(e==null)return{};var n,a,o=Pe(e,t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);for(a=0;a<r.length;a++)n=r[a],t.indexOf(n)===-1&&{}.propertyIsEnumerable.call(e,n)&&(o[n]=e[n])}return o}function se(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,a=Array(t);n<t;n++)a[n]=e[n];return a}function tt(e){if(Array.isArray(e))return se(e)}function nt(e){if(typeof Symbol<"u"&&e[Symbol.iterator]!=null||e["@@iterator"]!=null)return Array.from(e)}function at(e,t){if(e){if(typeof e=="string")return se(e,t);var n={}.toString.call(e).slice(8,-1);return n==="Object"&&e.constructor&&(n=e.constructor.name),n==="Map"||n==="Set"?Array.from(e):n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?se(e,t):void 0}}function ot(){throw new TypeError(`Invalid attempt to spread non-iterable instance.
1
+ import{c as I,j as Ke}from"./vendor-react-DG5dkZ_t.js";import{f as Ve,p as Se,a as xe,n as Ae,h as Je,s as Qe,d as Ne}from"./MarkdownRenderer-BVPIxk31.js";import"./index-ebnhtfFC.js";import"./vendor-radix-DXRuAJHH.js";import"./vendor-icons-CX5BfgqQ.js";import"./session-events-Bgir_Gl_.js";function Pe(e,t){if(e==null)return{};var n={};for(var a in e)if({}.hasOwnProperty.call(e,a)){if(t.indexOf(a)!==-1)continue;n[a]=e[a]}return n}function et(e,t){if(e==null)return{};var n,a,o=Pe(e,t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);for(a=0;a<r.length;a++)n=r[a],t.indexOf(n)===-1&&{}.propertyIsEnumerable.call(e,n)&&(o[n]=e[n])}return o}function se(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,a=Array(t);n<t;n++)a[n]=e[n];return a}function tt(e){if(Array.isArray(e))return se(e)}function nt(e){if(typeof Symbol<"u"&&e[Symbol.iterator]!=null||e["@@iterator"]!=null)return Array.from(e)}function at(e,t){if(e){if(typeof e=="string")return se(e,t);var n={}.toString.call(e).slice(8,-1);return n==="Object"&&e.constructor&&(n=e.constructor.name),n==="Map"||n==="Set"?Array.from(e):n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?se(e,t):void 0}}function ot(){throw new TypeError(`Invalid attempt to spread non-iterable instance.
2
2
  In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function le(e){return tt(e)||nt(e)||at(e)||ot()}function Z(e){"@babel/helpers - typeof";return Z=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Z(e)}function rt(e,t){if(Z(e)!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var a=n.call(e,t);if(Z(a)!="object")return a;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function it(e){var t=rt(e,"string");return Z(t)=="symbol"?t:t+""}function Te(e,t,n){return(t=it(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function ce(){return ce=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var a in n)({}).hasOwnProperty.call(n,a)&&(e[a]=n[a])}return e},ce.apply(null,arguments)}function Ee(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);t&&(a=a.filter(function(o){return Object.getOwnPropertyDescriptor(e,o).enumerable})),n.push.apply(n,a)}return n}function H(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?Ee(Object(n),!0).forEach(function(a){Te(e,a,n[a])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):Ee(Object(n)).forEach(function(a){Object.defineProperty(e,a,Object.getOwnPropertyDescriptor(n,a))})}return e}function st(e){var t=e.length;if(t===0||t===1)return e;if(t===2)return[e[0],e[1],"".concat(e[0],".").concat(e[1]),"".concat(e[1],".").concat(e[0])];if(t===3)return[e[0],e[1],e[2],"".concat(e[0],".").concat(e[1]),"".concat(e[0],".").concat(e[2]),"".concat(e[1],".").concat(e[0]),"".concat(e[1],".").concat(e[2]),"".concat(e[2],".").concat(e[0]),"".concat(e[2],".").concat(e[1]),"".concat(e[0],".").concat(e[1],".").concat(e[2]),"".concat(e[0],".").concat(e[2],".").concat(e[1]),"".concat(e[1],".").concat(e[0],".").concat(e[2]),"".concat(e[1],".").concat(e[2],".").concat(e[0]),"".concat(e[2],".").concat(e[0],".").concat(e[1]),"".concat(e[2],".").concat(e[1],".").concat(e[0])];if(t>=4)return[e[0],e[1],e[2],e[3],"".concat(e[0],".").concat(e[1]),"".concat(e[0],".").concat(e[2]),"".concat(e[0],".").concat(e[3]),"".concat(e[1],".").concat(e[0]),"".concat(e[1],".").concat(e[2]),"".concat(e[1],".").concat(e[3]),"".concat(e[2],".").concat(e[0]),"".concat(e[2],".").concat(e[1]),"".concat(e[2],".").concat(e[3]),"".concat(e[3],".").concat(e[0]),"".concat(e[3],".").concat(e[1]),"".concat(e[3],".").concat(e[2]),"".concat(e[0],".").concat(e[1],".").concat(e[2]),"".concat(e[0],".").concat(e[1],".").concat(e[3]),"".concat(e[0],".").concat(e[2],".").concat(e[1]),"".concat(e[0],".").concat(e[2],".").concat(e[3]),"".concat(e[0],".").concat(e[3],".").concat(e[1]),"".concat(e[0],".").concat(e[3],".").concat(e[2]),"".concat(e[1],".").concat(e[0],".").concat(e[2]),"".concat(e[1],".").concat(e[0],".").concat(e[3]),"".concat(e[1],".").concat(e[2],".").concat(e[0]),"".concat(e[1],".").concat(e[2],".").concat(e[3]),"".concat(e[1],".").concat(e[3],".").concat(e[0]),"".concat(e[1],".").concat(e[3],".").concat(e[2]),"".concat(e[2],".").concat(e[0],".").concat(e[1]),"".concat(e[2],".").concat(e[0],".").concat(e[3]),"".concat(e[2],".").concat(e[1],".").concat(e[0]),"".concat(e[2],".").concat(e[1],".").concat(e[3]),"".concat(e[2],".").concat(e[3],".").concat(e[0]),"".concat(e[2],".").concat(e[3],".").concat(e[1]),"".concat(e[3],".").concat(e[0],".").concat(e[1]),"".concat(e[3],".").concat(e[0],".").concat(e[2]),"".concat(e[3],".").concat(e[1],".").concat(e[0]),"".concat(e[3],".").concat(e[1],".").concat(e[2]),"".concat(e[3],".").concat(e[2],".").concat(e[0]),"".concat(e[3],".").concat(e[2],".").concat(e[1]),"".concat(e[0],".").concat(e[1],".").concat(e[2],".").concat(e[3]),"".concat(e[0],".").concat(e[1],".").concat(e[3],".").concat(e[2]),"".concat(e[0],".").concat(e[2],".").concat(e[1],".").concat(e[3]),"".concat(e[0],".").concat(e[2],".").concat(e[3],".").concat(e[1]),"".concat(e[0],".").concat(e[3],".").concat(e[1],".").concat(e[2]),"".concat(e[0],".").concat(e[3],".").concat(e[2],".").concat(e[1]),"".concat(e[1],".").concat(e[0],".").concat(e[2],".").concat(e[3]),"".concat(e[1],".").concat(e[0],".").concat(e[3],".").concat(e[2]),"".concat(e[1],".").concat(e[2],".").concat(e[0],".").concat(e[3]),"".concat(e[1],".").concat(e[2],".").concat(e[3],".").concat(e[0]),"".concat(e[1],".").concat(e[3],".").concat(e[0],".").concat(e[2]),"".concat(e[1],".").concat(e[3],".").concat(e[2],".").concat(e[0]),"".concat(e[2],".").concat(e[0],".").concat(e[1],".").concat(e[3]),"".concat(e[2],".").concat(e[0],".").concat(e[3],".").concat(e[1]),"".concat(e[2],".").concat(e[1],".").concat(e[0],".").concat(e[3]),"".concat(e[2],".").concat(e[1],".").concat(e[3],".").concat(e[0]),"".concat(e[2],".").concat(e[3],".").concat(e[0],".").concat(e[1]),"".concat(e[2],".").concat(e[3],".").concat(e[1],".").concat(e[0]),"".concat(e[3],".").concat(e[0],".").concat(e[1],".").concat(e[2]),"".concat(e[3],".").concat(e[0],".").concat(e[2],".").concat(e[1]),"".concat(e[3],".").concat(e[1],".").concat(e[0],".").concat(e[2]),"".concat(e[3],".").concat(e[1],".").concat(e[2],".").concat(e[0]),"".concat(e[3],".").concat(e[2],".").concat(e[0],".").concat(e[1]),"".concat(e[3],".").concat(e[2],".").concat(e[1],".").concat(e[0])]}var ie={};function lt(e){if(e.length===0||e.length===1)return e;var t=e.join(".");return ie[t]||(ie[t]=st(e)),ie[t]}function ct(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},n=arguments.length>2?arguments[2]:void 0,a=e.filter(function(r){return r!=="token"}),o=lt(a);return o.reduce(function(r,s){return H(H({},r),n[s])},t)}function Fe(e){return e.join(" ")}function ut(e,t){var n=0;return function(a){return n+=1,a.map(function(o,r){return Ie({node:o,stylesheet:e,useInlineStyles:t,key:"code-segment-".concat(n,"-").concat(r)})})}}function Ie(e){var t=e.node,n=e.stylesheet,a=e.style,o=a===void 0?{}:a,r=e.useInlineStyles,s=e.key,i=t.properties,c=t.type,l=t.tagName,u=t.value;if(c==="text")return u;if(l){var g=ut(n,r),d;if(!r)d=H(H({},i),{},{className:Fe(i.className)});else{var p=Object.keys(n).reduce(function(b,w){return w.split(".").forEach(function(N){b.includes(N)||b.push(N)}),b},[]),f=i.className&&i.className.includes("token")?["token"]:[],v=i.className&&f.concat(i.className.filter(function(b){return!p.includes(b)}));d=H(H({},i),{},{className:Fe(v)||void 0,style:ct(i.className,Object.assign({},i.style,o),n)})}var y=g(t.children);return I.createElement(l,ce({key:s},d),y)}}const dt=function(e,t){var n=e.listLanguages();return n.indexOf(t)!==-1};var gt=["language","children","style","customStyle","codeTagProps","useInlineStyles","showLineNumbers","showInlineLineNumbers","startingLineNumber","lineNumberContainerStyle","lineNumberStyle","wrapLines","wrapLongLines","lineProps","renderer","PreTag","CodeTag","code","astGenerator"];function $e(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);t&&(a=a.filter(function(o){return Object.getOwnPropertyDescriptor(e,o).enumerable})),n.push.apply(n,a)}return n}function R(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?$e(Object(n),!0).forEach(function(a){Te(e,a,n[a])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):$e(Object(n)).forEach(function(a){Object.defineProperty(e,a,Object.getOwnPropertyDescriptor(n,a))})}return e}var pt=/\n/g;function ft(e){return e.match(pt)}function ht(e){var t=e.lines,n=e.startingLineNumber,a=e.style;return t.map(function(o,r){var s=r+n;return I.createElement("span",{key:"line-".concat(r),className:"react-syntax-highlighter-line-number",style:typeof a=="function"?a(s):a},"".concat(s,`
3
3
  `))})}function bt(e){var t=e.codeString,n=e.codeStyle,a=e.containerStyle,o=a===void 0?{float:"left",paddingRight:"10px"}:a,r=e.numberStyle,s=r===void 0?{}:r,i=e.startingLineNumber;return I.createElement("code",{style:Object.assign({},n,o)},ht({lines:t.replace(/\n$/,"").split(`
4
4
  `),style:s,startingLineNumber:i}))}function mt(e){return"".concat(e.toString().length,".25em")}function Re(e,t){return{type:"element",tagName:"span",properties:{key:"line-number--".concat(e),className:["comment","linenumber","react-syntax-highlighter-line-number"],style:t},children:[{type:"text",value:e}]}}function De(e,t,n){var a={display:"inline-block",minWidth:mt(n),paddingRight:"1em",textAlign:"right",userSelect:"none"},o=typeof e=="function"?e(t):e,r=R(R({},a),o);return r}function J(e){var t=e.children,n=e.lineNumber,a=e.lineNumberStyle,o=e.largestLineNumber,r=e.showInlineLineNumbers,s=e.lineProps,i=s===void 0?{}:s,c=e.className,l=c===void 0?[]:c,u=e.showLineNumbers,g=e.wrapLongLines,d=e.wrapLines,p=d===void 0?!1:d,f=p?R({},typeof i=="function"?i(n):i):{};if(f.className=f.className?[].concat(le(f.className.trim().split(/\s+/)),le(l)):l,n&&r){var v=De(a,n,o);t.unshift(Re(n,v))}return g&u&&(f.style=R({display:"flex"},f.style)),{type:"element",tagName:"span",properties:f,children:t}}function ze(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:[],n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:[];e.length===void 0&&(e=[e]);for(var a=0;a<e.length;a++){var o=e[a];if(o.type==="text")n.push(J({children:[o],className:le(new Set(t))}));else if(o.children){var r,s=t.concat(((r=o.properties)===null||r===void 0?void 0:r.className)||[]);ze(o.children,s).forEach(function(i){return n.push(i)})}}return n}function yt(e,t,n,a,o,r,s,i,c){var l,u=ze(e.value),g=[],d=-1,p=0;function f(S,k){var x=arguments.length>2&&arguments[2]!==void 0?arguments[2]:[];return J({children:S,lineNumber:k,lineNumberStyle:i,largestLineNumber:s,showInlineLineNumbers:o,lineProps:n,className:x,showLineNumbers:a,wrapLongLines:c,wrapLines:t})}function v(S,k){if(a&&k&&o){var x=De(i,k,s);S.unshift(Re(k,x))}return S}function y(S,k){var x=arguments.length>2&&arguments[2]!==void 0?arguments[2]:[];return t||x.length>0?f(S,k,x):v(S,k)}for(var b=function(){var k=u[p],x=k.children[0].value,E=ft(x);if(E){var j=x.split(`