blade-code 0.4.2 → 0.4.4

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 (48) hide show
  1. package/dist/blade.js +2 -2
  2. package/dist/{chunk-ena4sxgr.js → chunk-094ekgv6.js} +1 -1
  3. package/dist/{chunk-vd38synx.js → chunk-420vamtq.js} +1 -1
  4. package/dist/{chunk-zxf08z5f.js → chunk-4jh0h16z.js} +1 -1
  5. package/dist/{chunk-4nsh53k6.js → chunk-5xc0kzdt.js} +1 -1
  6. package/dist/{chunk-vfdhz37s.js → chunk-5zkcs06z.js} +1 -1
  7. package/dist/{chunk-zyc1whnr.js → chunk-7637p6w5.js} +1 -1
  8. package/dist/{chunk-m99qhdkf.js → chunk-76emdpxa.js} +1 -1
  9. package/dist/{chunk-3wnjpk9b.js → chunk-7snnj126.js} +1 -1
  10. package/dist/{chunk-2tpgtpcp.js → chunk-8jwqy5d0.js} +1 -1
  11. package/dist/{chunk-z6tkw0b6.js → chunk-8pn5m426.js} +1 -1
  12. package/dist/chunk-92kjp66d.js +1 -0
  13. package/dist/chunk-9mrna4y3.js +2 -0
  14. package/dist/chunk-a5b9fkp3.js +157 -0
  15. package/dist/{chunk-j25kww7j.js → chunk-ehcjnwnr.js} +1 -1
  16. package/dist/chunk-h3ccyfqj.js +1 -0
  17. package/dist/{chunk-j79jvd54.js → chunk-jvbx3h56.js} +2 -2
  18. package/dist/{chunk-1en8fh5f.js → chunk-jz59sjzb.js} +1 -1
  19. package/dist/chunk-kd1t45br.js +2 -0
  20. package/dist/{chunk-n6e89s1v.js → chunk-mvyxksrz.js} +1 -1
  21. package/dist/{chunk-d7zcd9xp.js → chunk-n8na8c5h.js} +1 -1
  22. package/dist/{chunk-wxp0yadf.js → chunk-q4hrt6r4.js} +1 -1
  23. package/dist/{chunk-t3zaj1t7.js → chunk-tf0m57f5.js} +1 -1
  24. package/dist/{chunk-akr185xe.js → chunk-tph4ngbj.js} +1 -1
  25. package/dist/{chunk-nx2zqct5.js → chunk-vs2x9sxb.js} +1 -1
  26. package/dist/chunk-y5g06jmk.js +24 -0
  27. package/dist/{chunk-w7h3v075.js → chunk-z1qz8p1j.js} +1 -1
  28. package/dist/{chunk-tmjmp9gq.js → chunk-zs7xeymy.js} +1 -1
  29. package/dist/web/assets/{FilePreview-BLcxez_T.js → FilePreview-R1mRzyRz.js} +1 -1
  30. package/dist/web/assets/{MarkdownRenderer-BkQt-J8a.js → MarkdownRenderer-B46lJYAn.js} +1 -1
  31. package/dist/web/assets/{McpModal-B4ReoSE5.js → McpModal-QRv5Ij61.js} +1 -1
  32. package/dist/web/assets/{SettingsModal-QzwdsQwR.js → SettingsModal-D-mi6mUR.js} +1 -1
  33. package/dist/web/assets/{SettingsStore-E-aIqvyl.js → SettingsStore-Dmo3sZ_R.js} +1 -1
  34. package/dist/web/assets/{SkillsModal-CzE0m00G.js → SkillsModal-DNXjbjEs.js} +1 -1
  35. package/dist/web/assets/{TerminalPanel-DXA1C6Cg.js → TerminalPanel-DG_Q4UKr.js} +1 -1
  36. package/dist/web/assets/{dialog-CSpPttY0.js → dialog-CsiChiYt.js} +1 -1
  37. package/dist/web/assets/{index-DehGtSvJ.js → index-BeYCsOvo.js} +3 -3
  38. package/dist/web/assets/{useRequest-P_-JRihD.js → useRequest-BJp539HQ.js} +1 -1
  39. package/dist/web/assets/vendor-radix-CfxBc_4-.js +45 -0
  40. package/dist/web/index.html +1 -1
  41. package/package.json +4 -1
  42. package/dist/chunk-3xqfqpa7.js +0 -2
  43. package/dist/chunk-93b0x9b4.js +0 -157
  44. package/dist/chunk-dq65yfh6.js +0 -1
  45. package/dist/chunk-e2vtbvda.js +0 -24
  46. package/dist/chunk-q52j8tp4.js +0 -1
  47. package/dist/chunk-wr7w4af5.js +0 -2
  48. package/dist/web/assets/vendor-radix-CKNFO4jS.js +0 -45
@@ -1,4 +1,4 @@
1
- import{nb as W0}from"./chunk-ena4sxgr.js";import{rb as s0}from"./chunk-5mtjqqav.js";import{xb as h}from"./chunk-7ycmx7c2.js";import{Bb as M}from"./chunk-set7v1rf.js";import{Db as bQ}from"./chunk-j2ag7hh6.js";function G0(Q){return Q.role==="system"&&Array.isArray(Q.content)}class q0{systemMessages;_history;_pending=[];context;constructor(Q,$){this.context=Q;let Z=Q.messages.find(G0);if(Z)this.systemMessages=[Z];else if($)this.systemMessages=[{role:"system",content:[{type:"text",text:$,providerOptions:{anthropic:{cacheControl:{type:"ephemeral"}}}}]}];else this.systemMessages=[];this._history=Q.messages.filter((J)=>!G0(J))}get historyLength(){return this._history.length}get history(){return this._history}get pending(){return this._pending}toLLMMessages(){return[...this.systemMessages,...this._history,...this._pending]}getMessagesForLLM(){return this.toLLMMessages()}getHistory(){return this._history}appendPending(Q){this._pending.push(Q)}appendUser(Q){this._pending.push(Q)}appendAssistant(Q){this._pending.push(Q)}appendToolResult(Q){this._pending.push(Q)}appendControl(Q,$){if(Q==="system")throw Error("Cannot append system control message via appendControl. Use constructor for root system prompt.");this._pending.push($)}appendToHistory(Q){this._history.push(Q)}commitPending(){if(this._pending.length>0)this._history.push(...this._pending),this._pending=[]}replaceHistory(Q){this._history=Q.filter(($)=>!G0($))}writeback(){this.commitPending(),this.context.messages=this._history}get hasSystemPrompt(){return this.systemMessages.length>0}}async function _Q(Q,$){let Z;while(!(Z=await Q.next()).done)if($)await $(Z.value);return Z.value}function m0(Q){if(Q.isSubagent)return"continue";if(!Q.budget||Q.budget<=0)return"continue";if(Q.consecutiveContinuations>=3&&Q.lastOutputDelta<500)return"stop";if(Q.usage/Q.budget>=0.9)return"stop";return"continue"}function g0(Q){return{budget:Q.budget,usage:0,consecutiveContinuations:0,lastOutputDelta:0,isSubagent:Q.isSubagent??!1}}function c0(Q,$,Z){return{...Q,usage:Q.usage+$,lastOutputDelta:$,consecutiveContinuations:Z?Q.consecutiveContinuations+1:0}}var a=M("Agent"),NQ=3;function U0(Q,$,Z){if(Q!=="length")return{action:"none"};if($>=NQ)return{action:"truncated"};if(m0(Z)==="stop")return a.info("[Loop] Token budget: diminishing returns detected, skipping recovery"),{action:"budget_stop"};return{action:"recover"}}var EQ=[/:\s*$/,/:\s*$/,/\.\.\.\s*$/,/让我(先|来|开始|查看|检查|修复)/,/Let me (first|start|check|look|fix)/i],IQ="请执行你提到的操作,不要只是描述。",UQ=2;function v0(Q,$){if(!Q||$>=UQ)return{action:"none"};let Z=Q.slice(-200),J=Z.match(/```/g);if(J&&J.length%2!==0)return{action:"none"};if(EQ.some((G)=>G.test(Z)))return{action:"retry",prompt:IQ};return{action:"none"}}var u0=30000;async function A0(Q){try{let Z=W0.getInstance().executeStopHooks({projectDir:h(),sessionId:Q.sessionId,permissionMode:Q.permissionMode,reason:Q.reason,abortSignal:Q.abortSignal}),J,z=new Promise((G)=>{J=setTimeout(()=>G("timeout"),u0)});try{let G=await Promise.race([Z,z]);if(G==="timeout")return a.warn(`[Loop] Stop hook 超时 (${u0}ms),按 shouldStop: true 处理`),{action:"stop"};let q=G;if(!q.shouldStop)return{action:"continue",reason:q.continueReason};return{action:"stop"}}finally{clearTimeout(J)}}catch($){return a.warn("[Loop] Stop hook execution failed:",$),{action:"stop"}}}var vQ=0.9;async function i0(Q){try{let{SpecManager:$}=await import("./chunk-dq65yfh6.js"),Z=$.getInstance();if(!Z.isActive())return{action:"none"};let J=Z.getCurrentSpec();if(!J||J.phase!=="implementation")return{action:"none"};if(Q.maxTurns>0&&Q.turnsCount>=Q.maxTurns*vQ)return a.info(`[RalphLoop] 轮次接近上限 (${Q.turnsCount}/${Q.maxTurns}),停止自动继续`),{action:"none"};let z=J.tasks??[],G=z.filter((K)=>K.status==="completed"||K.status==="skipped").length,q=z.length;if(G>=q)return{action:"none"};let W=z.find((K)=>K.status==="pending"||K.status==="in_progress"),V=`[Ralph Loop] Spec "${J.name}" 仍有未完成任务。
1
+ import{nb as W0}from"./chunk-094ekgv6.js";import{rb as s0}from"./chunk-5mtjqqav.js";import{xb as h}from"./chunk-7ycmx7c2.js";import{Bb as M}from"./chunk-set7v1rf.js";import{Db as bQ}from"./chunk-j2ag7hh6.js";function G0(Q){return Q.role==="system"&&Array.isArray(Q.content)}class q0{systemMessages;_history;_pending=[];context;constructor(Q,$){this.context=Q;let Z=Q.messages.find(G0);if(Z)this.systemMessages=[Z];else if($)this.systemMessages=[{role:"system",content:[{type:"text",text:$,providerOptions:{anthropic:{cacheControl:{type:"ephemeral"}}}}]}];else this.systemMessages=[];this._history=Q.messages.filter((J)=>!G0(J))}get historyLength(){return this._history.length}get history(){return this._history}get pending(){return this._pending}toLLMMessages(){return[...this.systemMessages,...this._history,...this._pending]}getMessagesForLLM(){return this.toLLMMessages()}getHistory(){return this._history}appendPending(Q){this._pending.push(Q)}appendUser(Q){this._pending.push(Q)}appendAssistant(Q){this._pending.push(Q)}appendToolResult(Q){this._pending.push(Q)}appendControl(Q,$){if(Q==="system")throw Error("Cannot append system control message via appendControl. Use constructor for root system prompt.");this._pending.push($)}appendToHistory(Q){this._history.push(Q)}commitPending(){if(this._pending.length>0)this._history.push(...this._pending),this._pending=[]}replaceHistory(Q){this._history=Q.filter(($)=>!G0($))}writeback(){this.commitPending(),this.context.messages=this._history}get hasSystemPrompt(){return this.systemMessages.length>0}}async function _Q(Q,$){let Z;while(!(Z=await Q.next()).done)if($)await $(Z.value);return Z.value}function m0(Q){if(Q.isSubagent)return"continue";if(!Q.budget||Q.budget<=0)return"continue";if(Q.consecutiveContinuations>=3&&Q.lastOutputDelta<500)return"stop";if(Q.usage/Q.budget>=0.9)return"stop";return"continue"}function g0(Q){return{budget:Q.budget,usage:0,consecutiveContinuations:0,lastOutputDelta:0,isSubagent:Q.isSubagent??!1}}function c0(Q,$,Z){return{...Q,usage:Q.usage+$,lastOutputDelta:$,consecutiveContinuations:Z?Q.consecutiveContinuations+1:0}}var a=M("Agent"),NQ=3;function U0(Q,$,Z){if(Q!=="length")return{action:"none"};if($>=NQ)return{action:"truncated"};if(m0(Z)==="stop")return a.info("[Loop] Token budget: diminishing returns detected, skipping recovery"),{action:"budget_stop"};return{action:"recover"}}var EQ=[/:\s*$/,/:\s*$/,/\.\.\.\s*$/,/让我(先|来|开始|查看|检查|修复)/,/Let me (first|start|check|look|fix)/i],IQ="请执行你提到的操作,不要只是描述。",UQ=2;function v0(Q,$){if(!Q||$>=UQ)return{action:"none"};let Z=Q.slice(-200),J=Z.match(/```/g);if(J&&J.length%2!==0)return{action:"none"};if(EQ.some((G)=>G.test(Z)))return{action:"retry",prompt:IQ};return{action:"none"}}var u0=30000;async function A0(Q){try{let Z=W0.getInstance().executeStopHooks({projectDir:h(),sessionId:Q.sessionId,permissionMode:Q.permissionMode,reason:Q.reason,abortSignal:Q.abortSignal}),J,z=new Promise((G)=>{J=setTimeout(()=>G("timeout"),u0)});try{let G=await Promise.race([Z,z]);if(G==="timeout")return a.warn(`[Loop] Stop hook 超时 (${u0}ms),按 shouldStop: true 处理`),{action:"stop"};let q=G;if(!q.shouldStop)return{action:"continue",reason:q.continueReason};return{action:"stop"}}finally{clearTimeout(J)}}catch($){return a.warn("[Loop] Stop hook execution failed:",$),{action:"stop"}}}var vQ=0.9;async function i0(Q){try{let{SpecManager:$}=await import("./chunk-h3ccyfqj.js"),Z=$.getInstance();if(!Z.isActive())return{action:"none"};let J=Z.getCurrentSpec();if(!J||J.phase!=="implementation")return{action:"none"};if(Q.maxTurns>0&&Q.turnsCount>=Q.maxTurns*vQ)return a.info(`[RalphLoop] 轮次接近上限 (${Q.turnsCount}/${Q.maxTurns}),停止自动继续`),{action:"none"};let z=J.tasks??[],G=z.filter((K)=>K.status==="completed"||K.status==="skipped").length,q=z.length;if(G>=q)return{action:"none"};let W=z.find((K)=>K.status==="pending"||K.status==="in_progress"),V=`[Ralph Loop] Spec "${J.name}" 仍有未完成任务。
2
2
  `+`进度: ${G}/${q} 任务已完成。
3
3
  `+(W?`下一个任务: ${W.title}${W.description?` — ${W.description}`:""}
4
4
  `:"")+"请继续执行下一个未完成的任务,不要停止。";return a.info(`[RalphLoop] Spec "${J.name}" 进度 ${G}/${q},自动继续`),{action:"continue",reason:V}}catch{return{action:"none"}}}var o=M("Agent");function s(Q){return Q.executionEngine?.getContextManager()}async function m(Q,$,Z,J=null){try{let z=s(Q),G=typeof Z==="string"?Z.trim()!=="":Z.some((q)=>q.type==="text"?q.text.trim()!=="":!0);if(z&&$.sessionId&&G)return await z.saveMessage($.sessionId,"user",Z,J,void 0,$.subagentInfo)}catch(z){o.warn("[Loop] 保存用户消息失败:",z)}return null}async function k(Q,$,Z,J){try{let z=s(Q);if(z&&$.sessionId&&Z.trim())return await z.saveMessage($.sessionId,"assistant",Z,J,void 0,$.subagentInfo)}catch(z){o.warn("[Loop] 保存助手消息失败:",z)}return null}async function y0(Q,$,Z,J,z){try{let G=s(Q);if(G&&$.sessionId)return await G.saveToolUse($.sessionId,Z,J,z,$.subagentInfo)}catch(G){o.warn("[Loop] 保存工具调用失败:",G)}return null}async function S0(Q,$,Z,J,z,G,q,W){try{let V=s(Q);if(V&&$.sessionId)return await V.saveToolResult($.sessionId,Z,J,z,G,q,$.subagentInfo,W)}catch(V){o.warn("[Loop] 保存工具结果失败:",V)}return null}async function V0(Q,$,Z,J){try{let z=s(Q);if(z&&$.sessionId)return await z.saveCompaction($.sessionId,Z,J,null)}catch(z){o.warn("[Loop] 保存压缩数据失败:",z)}return null}function n0(Q,$){if(!["TaskCreate","TaskUpdate","TaskList"].includes(Q.function.name)||!$.success||!$.llmContent&&!$.metadata)return null;let Z=typeof $.llmContent==="object"?$.llmContent:{};return{kind:"task_update",tasks:$.metadata?.tasks||Z.tasks||[]}}function l0(Q,$,Z){if(Q.function.name!=="Skill"||!$.success||!$.metadata)return;let J=$.metadata;if(J.skillName)Z.onSkillActivated?.({skillName:J.skillName,allowedTools:J.allowedTools,basePath:J.basePath||""})}function a0(Q){let $=Q.metadata;if(!$)return;return $.modelId?.toString().trim()||$.model?.toString().trim()||void 0||void 0}async function P0(Q,$,Z){let J=n0(Q,$);l0(Q,$,Z);let z=a0($);if(z)await Z.onModelSwitch?.(z);return J}import{nanoid as rQ}from"nanoid";import{promises as SQ}from"node:fs";import{nanoid as c}from"nanoid";import{promises as Y0}from"node:fs";var t=M("Tool");class C{static instance=null;accessedFiles=new Map;constructor(){}static getInstance(){if(!C.instance)C.instance=new C;return C.instance}async recordFileRead(Q,$){try{let Z=await Y0.stat(Q),J={filePath:Q,accessTime:Date.now(),mtime:Z.mtimeMs,sessionId:$,lastOperation:"read"};this.accessedFiles.set(Q,J),t.debug(`记录文件读取: ${Q}`)}catch(Z){t.warn(`记录文件读取失败: ${Q}`,Z)}}async recordFileEdit(Q,$,Z="edit"){try{let J=await Y0.stat(Q),z={filePath:Q,accessTime:Date.now(),mtime:J.mtimeMs,sessionId:$,lastOperation:Z};this.accessedFiles.set(Q,z),t.debug(`记录文件${Z==="edit"?"编辑":"写入"}: ${Q}`)}catch(J){t.warn(`记录文件${Z==="edit"?"编辑":"写入"}失败: ${Q}`,J)}}hasFileBeenRead(Q,$){let Z=this.accessedFiles.get(Q);if(!Z)return!1;if($&&Z.sessionId!==$)return!1;return!0}async checkFileModification(Q){let $=this.accessedFiles.get(Q);if(!$)return{modified:!1,message:"文件未被跟踪"};try{let Z=await Y0.stat(Q);if(Math.abs(Z.mtimeMs-$.mtime)>1)return{modified:!0,message:`文件在访问后被修改(访问时间: ${new Date($.accessTime).toISOString()}, 当前修改时间: ${Z.mtime.toISOString()})`};return{modified:!1}}catch(Z){let J=Z;if(J.code==="ENOENT")return{modified:!0,message:"文件已被删除"};return{modified:!1,message:`无法检查文件状态: ${J.message}`}}}async checkExternalModification(Q){let $=this.accessedFiles.get(Q);if(!$)return{isExternal:!1,message:"文件未被跟踪"};try{let Z=await Y0.stat(Q);if(Z.mtimeMs-$.mtime>2000)return{isExternal:!0,message:`文件在 ${new Date($.accessTime).toISOString()} (${$.lastOperation}) 之后被外部程序修改(当前修改时间: ${Z.mtime.toISOString()})`};return{isExternal:!1}}catch(Z){let J=Z;if(J.code==="ENOENT")return{isExternal:!0,message:"文件已被删除"};return t.warn(`检查文件外部修改失败: ${Q}`,Z),{isExternal:!1,message:`无法检查文件状态: ${J.message}`}}}getFileRecord(Q){return this.accessedFiles.get(Q)}clearFileRecord(Q){this.accessedFiles.delete(Q)}clearAll(){this.accessedFiles.clear()}clearSession(Q){for(let[$,Z]of this.accessedFiles.entries())if(Z.sessionId===Q)this.accessedFiles.delete($)}getTrackedFiles(){return Array.from(this.accessedFiles.keys())}getTrackedFileCount(){return this.accessedFiles.size}static resetInstance(){C.instance=null}}import{readFile as AQ}from"node:fs/promises";import{basename as yQ}from"node:path";class X0{static MAX_FILES=5;static MAX_LINES_PER_FILE=1000;static analyzeFiles(Q){let $=new Map;return Q.forEach((J,z)=>{let G=typeof J.content==="string"?J.content:(J.content||[]).filter((W)=>W.type==="text").map((W)=>W.text).join(`
@@ -0,0 +1 @@
1
+ import{ga as a}from"./chunk-8jwqy5d0.js";import"./chunk-76emdpxa.js";import"./chunk-y5g06jmk.js";import"./chunk-7ycmx7c2.js";import"./chunk-set7v1rf.js";import"./chunk-j2ag7hh6.js";export{a as SpecManager};
@@ -1,4 +1,4 @@
1
- import{X as D,Y as F$}from"./chunk-zxf08z5f.js";import{Z as K4}from"./chunk-esnkk33h.js";import{ba as T1}from"./chunk-3xqfqpa7.js";import{ga as m}from"./chunk-2tpgtpcp.js";import{Aa as v1,Ba as m$,Ca as v$,Da as m0,Ea as D$,Fa as C1,Ga as y$,ra as l4,sa as r,ua as c0,va as G$,wa as A,za as K$}from"./chunk-m99qhdkf.js";import{Ia as M1}from"./chunk-e2vtbvda.js";import{Ma as n9,Na as V$,Oa as N0,Pa as P$,Sa as j$,db as a1,eb as e9,hb as K9}from"./chunk-j25kww7j.js";import{ib as H9,jb as G9,kb as K8,lb as X9}from"./chunk-yddnm9n2.js";import{mb as P8,nb as J$}from"./chunk-ena4sxgr.js";import{rb as I1}from"./chunk-5mtjqqav.js";import{tb as l8,xb as N}from"./chunk-7ycmx7c2.js";import{Bb as M,Cb as I}from"./chunk-set7v1rf.js";import{Db as F0}from"./chunk-j2ag7hh6.js";import{spawn as d2}from"child_process";import{randomUUID as g2}from"crypto";class a{static instance=null;processes=new Map;static getInstance(){if(!a.instance)a.instance=new a;return a.instance}startBackgroundProcess($){let Z=`bash_${g2()}`,J={};for(let[Y,V]of Object.entries({...process.env,...$.env,BLADE_CLI:"1"}))if(V!==void 0)J[Y]=V;let W=d2("bash",["-c",$.command],{cwd:$.cwd||N(),env:J,stdio:["ignore","pipe","pipe"]}),X={id:Z,command:$.command,sessionId:$.sessionId,cwd:$.cwd,env:$.env,process:W,pid:W.pid,status:"running",startTime:Date.now(),pendingStdout:"",pendingStderr:""};return W.stdout?.setEncoding("utf8"),W.stderr?.setEncoding("utf8"),W.stdout?.on("data",(Y)=>{X.pendingStdout+=Y.toString()}),W.stderr?.on("data",(Y)=>{X.pendingStderr+=Y.toString()}),W.on("close",(Y,V)=>{X.status=X.status==="killed"?"killed":"exited",X.exitCode=Y,X.signal=V,X.endTime=Date.now(),X.process=void 0}),W.on("error",(Y)=>{X.status="error",X.errorMessage=Y.message,X.endTime=Date.now(),X.process=void 0,X.pendingStderr+=`
1
+ import{X as D,Y as F$}from"./chunk-4jh0h16z.js";import{Z as K4}from"./chunk-esnkk33h.js";import{ba as T1}from"./chunk-kd1t45br.js";import{ga as m}from"./chunk-8jwqy5d0.js";import{Aa as v1,Ba as m$,Ca as v$,Da as m0,Ea as D$,Fa as C1,Ga as y$,ra as l4,sa as r,ua as c0,va as G$,wa as A,za as K$}from"./chunk-76emdpxa.js";import{Ia as M1}from"./chunk-y5g06jmk.js";import{Ma as n9,Na as V$,Oa as N0,Pa as P$,Sa as j$,db as a1,eb as e9,hb as K9}from"./chunk-ehcjnwnr.js";import{ib as H9,jb as G9,kb as K8,lb as X9}from"./chunk-yddnm9n2.js";import{mb as P8,nb as J$}from"./chunk-094ekgv6.js";import{rb as I1}from"./chunk-5mtjqqav.js";import{tb as l8,xb as N}from"./chunk-7ycmx7c2.js";import{Bb as M,Cb as I}from"./chunk-set7v1rf.js";import{Db as F0}from"./chunk-j2ag7hh6.js";import{spawn as d2}from"child_process";import{randomUUID as g2}from"crypto";class a{static instance=null;processes=new Map;static getInstance(){if(!a.instance)a.instance=new a;return a.instance}startBackgroundProcess($){let Z=`bash_${g2()}`,J={};for(let[Y,V]of Object.entries({...process.env,...$.env,BLADE_CLI:"1"}))if(V!==void 0)J[Y]=V;let W=d2("bash",["-c",$.command],{cwd:$.cwd||N(),env:J,stdio:["ignore","pipe","pipe"]}),X={id:Z,command:$.command,sessionId:$.sessionId,cwd:$.cwd,env:$.env,process:W,pid:W.pid,status:"running",startTime:Date.now(),pendingStdout:"",pendingStderr:""};return W.stdout?.setEncoding("utf8"),W.stderr?.setEncoding("utf8"),W.stdout?.on("data",(Y)=>{X.pendingStdout+=Y.toString()}),W.stderr?.on("data",(Y)=>{X.pendingStderr+=Y.toString()}),W.on("close",(Y,V)=>{X.status=X.status==="killed"?"killed":"exited",X.exitCode=Y,X.signal=V,X.endTime=Date.now(),X.process=void 0}),W.on("error",(Y)=>{X.status="error",X.errorMessage=Y.message,X.endTime=Date.now(),X.process=void 0,X.pendingStderr+=`
2
2
  [error] ${Y.message}`}),this.processes.set(Z,X),X}consumeOutput($){let Z=this.processes.get($);if(!Z)return;let J={id:Z.id,command:Z.command,status:Z.status,stdout:Z.pendingStdout,stderr:Z.pendingStderr,exitCode:Z.exitCode,signal:Z.signal,pid:Z.pid,startedAt:Z.startTime,endedAt:Z.endTime,errorMessage:Z.errorMessage};return Z.pendingStdout="",Z.pendingStderr="",J}getProcess($){return this.processes.get($)}kill($){let Z=this.processes.get($);if(!Z)return;if(Z.status!=="running"||!Z.process)return{success:!1,alreadyExited:!0,status:Z.status,pid:Z.pid,exitCode:Z.exitCode,signal:Z.signal};if(!Z.process.kill("SIGTERM"))return{success:!1,alreadyExited:!1,status:Z.status,pid:Z.pid,exitCode:Z.exitCode,signal:Z.signal};return Z.status="killed",Z.endTime=Date.now(),Z.process=void 0,{success:!0,alreadyExited:!1,status:Z.status,pid:Z.pid,exitCode:Z.exitCode,signal:Z.signal}}killAll(){for(let[$,Z]of this.processes)if(Z.status==="running"&&Z.process)try{Z.process.kill("SIGTERM"),Z.status="killed",Z.endTime=Date.now(),Z.process=void 0}catch{}this.processes.clear()}}import W5 from"node:fs";import W1 from"node:os";import R$ from"node:path";import u2 from"yaml";var g8={name:"verification",description:"Independent verification agent that validates implementation by running builds, tests, linters, and adversarial"+" probes. Strictly read-only — cannot modify code. Use"+" after completing implementation to get an independent quality assessment.",tools:["Read","Glob","Grep","Bash"],systemPrompt:`# Verification Agent
3
3
 
4
4
  You are an **independent verification engineer**. Your sole purpose is to find problems — not to praise or reassure. You are the last line of defense before code ships.
@@ -1343,7 +1343,7 @@ ${U}
1343
1343
  </approved-plan>
1344
1344
 
1345
1345
  IMPORTANT: Execute according to the approved plan above. Follow the steps exactly as specified.`;if(typeof W==="string")H=W+G;else H=[...W,{type:"text",text:G}]}K=yield*this.runLoop(H,q,B)}return K}let X=typeof W==="string"?W:W.filter((B)=>B.type==="text").map((B)=>B.text).join(`
1346
- `),Y={id:this.generateTaskId(),type:"simple",prompt:X};return{success:!0,finalMessage:(await this.executeTask(Y)).content,metadata:{turnsCount:1,toolCallsCount:0,duration:0}}}async chat($,Z,J){let{drainLoop:W}=await import("./chunk-wxp0yadf.js");return W(this.chatStream($,Z,J))}async*runPlanLoop($,Z,J){k.debug("Processing Plan mode message...");let{prompt:W}=await t$({projectPath:N(),mode:"plan",includeEnvironment:!0,language:this.config.language}),X;if(typeof $==="string")X=v0($);else{let Y=$.filter((V)=>V.type==="text");if(Y.length>0){let V=Y[0];X=$.map((B)=>B===V?{type:"text",text:v0(V.text)}:B)}else X=[{type:"text",text:v0("")},...$]}return yield*this.executeLoop(X,Z,J,W)}async*runSpecLoop($,Z,J){k.debug("Processing Spec mode message...");let W=m.getInstance(),X=Z.workspaceRoot||N();try{await W.initialize(X)}catch(U){k.warn("SpecManager initialization warning:",U)}let Y=W.getCurrentSpec(),V=await W.getSteeringContextString(),B=Y1(Y,V),K,Q=Y?.phase||"init";if(typeof $==="string")K=`${V1(Q)}
1346
+ `),Y={id:this.generateTaskId(),type:"simple",prompt:X};return{success:!0,finalMessage:(await this.executeTask(Y)).content,metadata:{turnsCount:1,toolCallsCount:0,duration:0}}}async chat($,Z,J){let{drainLoop:W}=await import("./chunk-q4hrt6r4.js");return W(this.chatStream($,Z,J))}async*runPlanLoop($,Z,J){k.debug("Processing Plan mode message...");let{prompt:W}=await t$({projectPath:N(),mode:"plan",includeEnvironment:!0,language:this.config.language}),X;if(typeof $==="string")X=v0($);else{let Y=$.filter((V)=>V.type==="text");if(Y.length>0){let V=Y[0];X=$.map((B)=>B===V?{type:"text",text:v0(V.text)}:B)}else X=[{type:"text",text:v0("")},...$]}return yield*this.executeLoop(X,Z,J,W)}async*runSpecLoop($,Z,J){k.debug("Processing Spec mode message...");let W=m.getInstance(),X=Z.workspaceRoot||N();try{await W.initialize(X)}catch(U){k.warn("SpecManager initialization warning:",U)}let Y=W.getCurrentSpec(),V=await W.getSteeringContextString(),B=Y1(Y,V),K,Q=Y?.phase||"init";if(typeof $==="string")K=`${V1(Q)}
1347
1347
 
1348
1348
  ${$}`;else{let U=$.filter((q)=>q.type==="text");if(U.length>0){let q=U[0];K=$.map((H)=>H===q?{type:"text",text:`${V1(Q)}
1349
1349
 
@@ -1,4 +1,4 @@
1
- import{va as z}from"./chunk-m99qhdkf.js";import{Ia as w}from"./chunk-e2vtbvda.js";import{Bb as u}from"./chunk-set7v1rf.js";var q=u("General"),F=(b)=>{if(b.yolo){if(b.permissionMode&&b.permissionMode!=="yolo")throw Error("Cannot use both --yolo and --permission-mode with different values");b.permissionMode="yolo"}if(Array.isArray(b.allowedTools))b.allowedTools=b.allowedTools.flatMap((h)=>h.split(",").map((k)=>k.trim()).filter((k)=>k.length>0));if(Array.isArray(b.disallowedTools))b.disallowedTools=b.disallowedTools.flatMap((h)=>h.split(",").map((k)=>k.trim()).filter((k)=>k.length>0));if(Array.isArray(b.allowedTools)&&Array.isArray(b.disallowedTools)){let h=b.allowedTools.filter((k)=>b.disallowedTools.includes(k));if(h.length>0)throw Error(`Tools cannot be both allowed and disallowed: ${h.join(", ")}`)}},G=async(b)=>{try{let k=await w.getInstance().initialize();if(z().config.actions.setConfig(k),b.debug)q.info("[CLI] 配置已加载到 Store")}catch(h){q.error("[CLI] [FAIL] 配置初始化失败",h instanceof Error?h.message:h),console.error(`
1
+ import{va as z}from"./chunk-76emdpxa.js";import{Ia as w}from"./chunk-y5g06jmk.js";import{Bb as u}from"./chunk-set7v1rf.js";var q=u("General"),F=(b)=>{if(b.yolo){if(b.permissionMode&&b.permissionMode!=="yolo")throw Error("Cannot use both --yolo and --permission-mode with different values");b.permissionMode="yolo"}if(Array.isArray(b.allowedTools))b.allowedTools=b.allowedTools.flatMap((h)=>h.split(",").map((k)=>k.trim()).filter((k)=>k.length>0));if(Array.isArray(b.disallowedTools))b.disallowedTools=b.disallowedTools.flatMap((h)=>h.split(",").map((k)=>k.trim()).filter((k)=>k.length>0));if(Array.isArray(b.allowedTools)&&Array.isArray(b.disallowedTools)){let h=b.allowedTools.filter((k)=>b.disallowedTools.includes(k));if(h.length>0)throw Error(`Tools cannot be both allowed and disallowed: ${h.join(", ")}`)}},G=async(b)=>{try{let k=await w.getInstance().initialize();if(z().config.actions.setConfig(k),b.debug)q.info("[CLI] 配置已加载到 Store")}catch(h){q.error("[CLI] [FAIL] 配置初始化失败",h instanceof Error?h.message:h),console.error(`
2
2
  [FAIL] 配置初始化失败
3
3
  `),console.error("原因:",h instanceof Error?h.message:"未知错误"),console.error(`
4
4
  请检查:`),console.error(" 1. 配置文件格式是否正确 (~/.blade/config.json)"),console.error(" 2. 是否需要运行 blade 进行首次配置"),console.error(` 3. 配置文件权限是否正确
@@ -0,0 +1,2 @@
1
+ var e={name:"blade-code",version:"0.4.4",private:!1,description:"🗡️ Blade Code - 智能代码助手命令行工具",type:"module",bin:{blade:"dist/blade.js"},files:["dist","vendor/ripgrep/**","README.md"],scripts:{dev:"node scripts/run-bun.js --watch src/blade.tsx","dev:serve":"node scripts/run-bun.js --watch src/blade.tsx serve --port 4097",build:"rm -rf dist && node scripts/run-bun.js run scripts/build.ts",start:"node scripts/run-bun.js run dist/blade.js",test:"node scripts/test.js","test:all":"vitest run --config vitest.config.ts","test:unit":"node scripts/test.js unit","test:integration":"node scripts/test.js integration","test:cli":"node scripts/test.js cli","test:headless-core":"node scripts/test.js headlessCore","test:e2e":"node scripts/test.js e2e","test:performance":"node scripts/test.js performance","test:snapshot":"node scripts/test.js snapshot","test:security":"node scripts/test.js security","test:coverage":"node scripts/test.js all --coverage","test:watch":"vitest --watch --config vitest.config.ts","benchmark:repo":"node scripts/run-bun.js run scripts/run-real-repo-benchmark.ts","test:update-snapshots":"node scripts/test.js snapshot --update",lint:"biome lint src tests","lint:fix":"biome lint --write src tests","type-check":"tsc --noEmit","format:check":"biome format src tests",ready:"node scripts/run-bun.js run scripts/ready.ts","detect-unused":"node scripts/run-bun.js run scripts/detect-unused.ts",release:"node scripts/release.js","release:dry":"node scripts/release.js --dry-run","release:major":"node scripts/release.js --major","release:minor":"node scripts/release.js --minor","release:patch":"node scripts/release.js --patch"},keywords:["cli","blade","ai","assistant","agent","llm"],author:"echoVic",license:"MIT",engines:{node:">=20.0.0"},optionalDependencies:{"@vscode/ripgrep":"^1.17.0","bun-pty":"^0.4.8","node-pty":"1.0.0"},dependencies:{"@agentclientprotocol/sdk":"^0.12.0","@ai-sdk/anthropic":"^3.0.7","@ai-sdk/azure":"^3.0.5","@ai-sdk/deepseek":"^2.0.4","@ai-sdk/google":"^3.0.4","@ai-sdk/openai":"^3.0.26","@ai-sdk/openai-compatible":"^2.0.4","@inkjs/ui":"^2.0.0","@modelcontextprotocol/sdk":"^1.17.4",ahooks:"^3.9.6",ai:"^6.0.39","ansi-escapes":"^7.2.0","async-mutex":"^0.5.0",axios:"^1.12.2",chalk:"^5.4.1",diff:"^8.0.2","fast-glob":"^3.3.3","fuse.js":"^7.1.0","gray-matter":"^4.0.3",hono:"^4.7.10",ink:"npm:@jrichman/ink@6.4.10","ink-big-text":"^2.0.0","ink-gradient":"^3.0.0","ink-select-input":"^6.2.0","ink-spinner":"^5.0.0","ink-text-input":"^6.0.0","js-tiktoken":"^1.0.21","lodash-es":"^4.17.21",lowlight:"^3.3.0","lru-cache":"^11.2.4",nanoid:"^5.1.6",open:"^10.1.2",openai:"^6.2.0",picomatch:"^4.0.3",react:"^19.1.1","react-dom":"^19.1.1",semver:"^7.7.3","string-width":"^8.1.0",undici:"^7.16.0","write-file-atomic":"^7.0.0",ws:"^8.18.0",yaml:"^2.8.1",yargs:"^18.0.0",zod:"^3.24.2","zod-to-json-schema":"^3.24.6",zustand:"^5.0.9"},devDependencies:{"@biomejs/biome":"^2.2.4","@types/bun":"^1.3.4","@types/json-schema":"^7.0.15","@types/lodash-es":"^4.17.12","@types/node":"^22.15.24","@types/picomatch":"^4.0.2","@types/react":"^19.1.1","@types/react-dom":"^19.1.1","@types/semver":"^7.7.1","@types/write-file-atomic":"^4.0.3","@types/ws":"^8.5.12","@types/yargs":"^17.0.33","@vitest/coverage-v8":"^3.0.0",jsdom:"^26.0.0",typescript:"^5.9.2",vitest:"^3.0.0"}};function r(){return{name:e.name,version:e.version,description:e.description}}function n(){return e.version}function o(){return e.name}function c(){return e.description}function d(){return`v${e.version}`}function a(){return`v${e.version} © 2025 Blade Code`}
2
+ export{r as aa,n as ba,o as ca,c as da,d as ea,a as fa};
@@ -1,4 +1,4 @@
1
- import{p as _,q as x,r as E,s as N}from"./chunk-4nsh53k6.js";import{t as A}from"./chunk-wr7w4af5.js";import{v as B,w as D,x as L}from"./chunk-1en8fh5f.js";import{G as $,M as b}from"./chunk-j79jvd54.js";import"./chunk-zxf08z5f.js";import"./chunk-esnkk33h.js";import"./chunk-3xqfqpa7.js";import"./chunk-2tpgtpcp.js";import"./chunk-m99qhdkf.js";import"./chunk-e2vtbvda.js";import{Sa as Z}from"./chunk-j25kww7j.js";import"./chunk-yddnm9n2.js";import"./chunk-ena4sxgr.js";import"./chunk-5mtjqqav.js";import{wb as X,xb as Y}from"./chunk-7ycmx7c2.js";import"./chunk-set7v1rf.js";import"./chunk-j2ag7hh6.js";import f from"yargs";import{hideBin as h}from"yargs/helpers";var R=new Set(Object.values(X));function W(k){if(k&&R.has(k))return k;return}function w(k){return k.command("* [message]","Print response and exit (useful for pipes)",(F)=>F.positional("message",{describe:"Message to process",type:"string"}).option("p",{alias:"print",describe:"Print response and exit (useful for pipes)",type:"boolean"}).option("output-format",{describe:'Output format: "text", "json", "stream-json"',type:"string",default:"text"}).option("include-partial-messages",{describe:"Include partial message chunks as they arrive",type:"boolean"}).option("input-format",{describe:'Input format: "text", "stream-json"',type:"string",default:"text"}).option("model",{describe:"Model for the current session",type:"string"}).option("append-system-prompt",{describe:"Append a system prompt to the default system prompt",type:"string"}).option("system-prompt",{describe:"Replace the default system prompt",type:"string"}).option("max-turns",{alias:["maxTurns"],describe:"Maximum conversation turns (-1: unlimited, N>0: limit to N turns)",type:"number"}),async(F)=>{if(!F.p)return;let q=await M(F);process.exit(q)})}async function M(k,F=process){let q;try{await _();let J=await x({message:k.message,_:k._,defaultMessage:"Hello"}),G=await E(J);if(G.mode==="output"){if(G.content)F.stdout.write(`${G.content}
1
+ import{p as _,q as x,r as E,s as N}from"./chunk-5xc0kzdt.js";import{t as A}from"./chunk-9mrna4y3.js";import{v as B,w as D,x as L}from"./chunk-jz59sjzb.js";import{G as $,M as b}from"./chunk-jvbx3h56.js";import"./chunk-4jh0h16z.js";import"./chunk-esnkk33h.js";import"./chunk-kd1t45br.js";import"./chunk-8jwqy5d0.js";import"./chunk-76emdpxa.js";import"./chunk-y5g06jmk.js";import{Sa as Z}from"./chunk-ehcjnwnr.js";import"./chunk-yddnm9n2.js";import"./chunk-094ekgv6.js";import"./chunk-5mtjqqav.js";import{wb as X,xb as Y}from"./chunk-7ycmx7c2.js";import"./chunk-set7v1rf.js";import"./chunk-j2ag7hh6.js";import f from"yargs";import{hideBin as h}from"yargs/helpers";var R=new Set(Object.values(X));function W(k){if(k&&R.has(k))return k;return}function w(k){return k.command("* [message]","Print response and exit (useful for pipes)",(F)=>F.positional("message",{describe:"Message to process",type:"string"}).option("p",{alias:"print",describe:"Print response and exit (useful for pipes)",type:"boolean"}).option("output-format",{describe:'Output format: "text", "json", "stream-json"',type:"string",default:"text"}).option("include-partial-messages",{describe:"Include partial message chunks as they arrive",type:"boolean"}).option("input-format",{describe:'Input format: "text", "stream-json"',type:"string",default:"text"}).option("model",{describe:"Model for the current session",type:"string"}).option("append-system-prompt",{describe:"Append a system prompt to the default system prompt",type:"string"}).option("system-prompt",{describe:"Replace the default system prompt",type:"string"}).option("max-turns",{alias:["maxTurns"],describe:"Maximum conversation turns (-1: unlimited, N>0: limit to N turns)",type:"number"}),async(F)=>{if(!F.p)return;let q=await M(F);process.exit(q)})}async function M(k,F=process){let q;try{await _();let J=await x({message:k.message,_:k._,defaultMessage:"Hello"}),G=await E(J);if(G.mode==="output"){if(G.content)F.stdout.write(`${G.content}
2
2
  `);return G.exitCode??0}let Q=G.content,{sessionId:K,messages:T}=await N({sessionId:k.sessionId,continue:k.continue,resume:k.resume,fallbackSessionPrefix:"print"});q=await $.create({sessionId:K,modelId:k.model,mcpConfig:k.mcpConfig,strictMcpConfig:k.strictMcpConfig});let U=await b.createWithRuntime(q,{sessionId:K,systemPrompt:k.systemPrompt,appendSystemPrompt:k.appendSystemPrompt,maxTurns:k.maxTurns,modelId:k.model,permissionMode:W(k.permissionMode),toolWhitelist:k.allowedTools,toolBlacklist:k.disallowedTools,mcpConfig:k.mcpConfig,strictMcpConfig:k.strictMcpConfig}),H=(await Z(U.chatStream(Q,{messages:[...T],userId:"cli-user",sessionId:K,workspaceRoot:Y(),permissionMode:W(k.permissionMode)}))).finalMessage||"";if(k.outputFormat==="json")F.stdout.write(`${JSON.stringify({response:H,input:Q,model:k.model,timestamp:new Date().toISOString()},null,2)}
3
3
  `);else if(k.outputFormat==="stream-json")F.stdout.write(`${JSON.stringify({type:"response",content:H})}
4
4
  `);else F.stdout.write(`${H}
@@ -1 +1 @@
1
- import{aa as a,ba as b,ca as c,da as d,ea as e,fa as f}from"./chunk-3xqfqpa7.js";import"./chunk-j2ag7hh6.js";export{b as getVersion,c as getPackageName,a as getPackageInfo,e as getFormattedVersion,d as getDescription,f as getCopyright};
1
+ import{aa as a,ba as b,ca as c,da as d,ea as e,fa as f}from"./chunk-kd1t45br.js";import"./chunk-j2ag7hh6.js";export{b as getVersion,c as getPackageName,a as getPackageInfo,e as getFormattedVersion,d as getDescription,f as getCopyright};
@@ -1 +1 @@
1
- import{$a as l,Qa as a,Ra as b,Sa as c,Ta as d,Ua as e,Va as f,Wa as g,Xa as h,Ya as i,Za as j,_a as k,ab as m,bb as n,cb as o,fb as p,gb as q,hb as r}from"./chunk-j25kww7j.js";import"./chunk-yddnm9n2.js";import"./chunk-ena4sxgr.js";import"./chunk-5mtjqqav.js";import"./chunk-7ycmx7c2.js";import"./chunk-set7v1rf.js";import"./chunk-j2ag7hh6.js";export{g as saveUserMessage,i as saveToolUse,j as saveToolResult,k as saveCompaction,h as saveAssistantMessage,a as isRootSystemPrompt,l as handleTaskListUpdate,m as handleSkillActivation,n as extractModelSwitch,r as executeLoopGenerator,c as drainLoop,f as checkStopHook,d as checkOutputRecovery,e as checkIncompleteIntent,q as checkAndCompactInLoop,o as applyToolDomainEffects,p as StreamingToolExecutor,b as ConversationState};
1
+ import{$a as l,Qa as a,Ra as b,Sa as c,Ta as d,Ua as e,Va as f,Wa as g,Xa as h,Ya as i,Za as j,_a as k,ab as m,bb as n,cb as o,fb as p,gb as q,hb as r}from"./chunk-ehcjnwnr.js";import"./chunk-yddnm9n2.js";import"./chunk-094ekgv6.js";import"./chunk-5mtjqqav.js";import"./chunk-7ycmx7c2.js";import"./chunk-set7v1rf.js";import"./chunk-j2ag7hh6.js";export{g as saveUserMessage,i as saveToolUse,j as saveToolResult,k as saveCompaction,h as saveAssistantMessage,a as isRootSystemPrompt,l as handleTaskListUpdate,m as handleSkillActivation,n as extractModelSwitch,r as executeLoopGenerator,c as drainLoop,f as checkStopHook,d as checkOutputRecovery,e as checkIncompleteIntent,q as checkAndCompactInLoop,o as applyToolDomainEffects,p as StreamingToolExecutor,b as ConversationState};
@@ -1,4 +1,4 @@
1
- import{va as Q}from"./chunk-m99qhdkf.js";import{nb as U}from"./chunk-ena4sxgr.js";import{xb as O}from"./chunk-7ycmx7c2.js";import{Bb as N,zb as K}from"./chunk-set7v1rf.js";function Y(){if(process.stdin.isTTY&&typeof process.stdin.setRawMode==="function")try{process.stdin.setRawMode(!1)}catch{}process.stdout.write("\x1B[<u"),process.stdout.write("\x1B[>4;0m"),process.stdout.write("\x1B[?2004l"),process.stdout.write("\x1B[?1l\x1B>"),process.stdout.write("\x1B[?25h"),process.stdout.write("\x1B[0m")}var A=N("Service");function Z(b){switch(b){case"SIGINT":return"ctrl_c";case"esc":return"esc";case"uncaughtException":case"unhandledRejection":return"error";case"SIGTERM":case"normal":default:return"user_exit"}}class D{static instance=null;cleanupHandlers=[];isShuttingDown=!1;initialized=!1;lastSigintTime=0;SIGINT_DOUBLE_CLICK_WINDOW=3000;constructor(){}static getInstance(){if(!D.instance)D.instance=new D;return D.instance}initialize(){if(this.initialized){A.debug("[GracefulShutdown] 已初始化,跳过重复初始化");return}process.on("uncaughtException",(b)=>{this.handleFatalError("uncaughtException",b)}),process.on("unhandledRejection",(b)=>{let q=b instanceof Error?b:Error(String(b));this.handleFatalError("unhandledRejection",q)}),process.on("SIGTERM",()=>{A.info("[GracefulShutdown] 收到 SIGTERM 信号"),this.shutdown("SIGTERM",0)}),process.on("SIGINT",()=>{let b=Date.now();if(b-this.lastSigintTime<this.SIGINT_DOUBLE_CLICK_WINDOW)A.info("[GracefulShutdown] 收到第二次 SIGINT 信号,执行退出"),this.shutdown("SIGINT",0);else A.info("[GracefulShutdown] 收到第一次 SIGINT 信号,再按一次退出"),this.lastSigintTime=b,console.log(`
1
+ import{va as Q}from"./chunk-76emdpxa.js";import{nb as U}from"./chunk-094ekgv6.js";import{xb as O}from"./chunk-7ycmx7c2.js";import{Bb as N,zb as K}from"./chunk-set7v1rf.js";function Y(){if(process.stdin.isTTY&&typeof process.stdin.setRawMode==="function")try{process.stdin.setRawMode(!1)}catch{}process.stdout.write("\x1B[<u"),process.stdout.write("\x1B[>4;0m"),process.stdout.write("\x1B[?2004l"),process.stdout.write("\x1B[?1l\x1B>"),process.stdout.write("\x1B[?25h"),process.stdout.write("\x1B[0m")}var A=N("Service");function Z(b){switch(b){case"SIGINT":return"ctrl_c";case"esc":return"esc";case"uncaughtException":case"unhandledRejection":return"error";case"SIGTERM":case"normal":default:return"user_exit"}}class D{static instance=null;cleanupHandlers=[];isShuttingDown=!1;initialized=!1;lastSigintTime=0;SIGINT_DOUBLE_CLICK_WINDOW=3000;constructor(){}static getInstance(){if(!D.instance)D.instance=new D;return D.instance}initialize(){if(this.initialized){A.debug("[GracefulShutdown] 已初始化,跳过重复初始化");return}process.on("uncaughtException",(b)=>{this.handleFatalError("uncaughtException",b)}),process.on("unhandledRejection",(b)=>{let q=b instanceof Error?b:Error(String(b));this.handleFatalError("unhandledRejection",q)}),process.on("SIGTERM",()=>{A.info("[GracefulShutdown] 收到 SIGTERM 信号"),this.shutdown("SIGTERM",0)}),process.on("SIGINT",()=>{let b=Date.now();if(b-this.lastSigintTime<this.SIGINT_DOUBLE_CLICK_WINDOW)A.info("[GracefulShutdown] 收到第二次 SIGINT 信号,执行退出"),this.shutdown("SIGINT",0);else A.info("[GracefulShutdown] 收到第一次 SIGINT 信号,再按一次退出"),this.lastSigintTime=b,console.log(`
2
2
  再按一次 Ctrl+C 退出
3
3
  `)}),this.initialized=!0,A.debug("[GracefulShutdown] 全局错误处理器已初始化")}registerCleanup(b){return this.cleanupHandlers.push(b),A.debug(`[GracefulShutdown] 注册清理函数,当前共 ${this.cleanupHandlers.length} 个`),()=>{let q=this.cleanupHandlers.indexOf(b);if(q!==-1)this.cleanupHandlers.splice(q,1),A.debug(`[GracefulShutdown] 取消注册清理函数,剩余 ${this.cleanupHandlers.length} 个`)}}handleFatalError(b,q){if(this.isShuttingDown){console.error(`[GracefulShutdown] 退出过程中发生额外错误 (${b}):`,q);return}if(console.error(""),console.error("═".repeat(60)),console.error(`Uncaught error (${b})`),console.error("═".repeat(60)),console.error(""),console.error("错误信息:",q.message),console.error(""),q.stack)console.error("堆栈跟踪:"),console.error(q.stack);console.error(""),console.error("═".repeat(60)),console.error(""),this.shutdown(b,1)}async shutdown(b,q=0){if(this.isShuttingDown){A.debug("[GracefulShutdown] 已在退出过程中,跳过重复退出");return}this.isShuttingDown=!0,A.info(`[GracefulShutdown] 开始优雅退出 (原因: ${b})`);try{await K()}catch(z){}try{let z=U.getInstance();if(z.isEnabled()){let F=Q(),W=F.session?.sessionId||"unknown",X=F.config?.config?.permissionMode||"default";await z.executeSessionEndHooks(Z(b),{projectDir:O(),sessionId:W,permissionMode:X})}}catch(z){console.error("[GracefulShutdown] SessionEnd hooks 执行失败:",z)}let B=5000,V=new Promise((z,F)=>{setTimeout(()=>{F(Error(`清理超时 (${B}ms)`))},B)});try{let z=this.runCleanupHandlers();await Promise.race([z,V])}catch(z){console.error("[GracefulShutdown] 清理过程中发生错误:",z)}finally{Y(),setTimeout(()=>{process.exit(q)},100)}}async runCleanupHandlers(){let b=[...this.cleanupHandlers].reverse();for(let q of b)try{let B=q();if(B instanceof Promise)await B}catch(B){console.error("[GracefulShutdown] 清理函数执行失败:",B)}}isExiting(){return this.isShuttingDown}reset(){this.isShuttingDown=!1,this.cleanupHandlers=[],this.initialized=!1}}var J=()=>{return D.getInstance()},H=(b)=>{return J().registerCleanup(b)},P=()=>{J().initialize()},L=(b=0)=>{J().shutdown("normal",b)};
4
4
  export{J as l,H as m,P as n,L as o};
@@ -1,2 +1,2 @@
1
- import{e as zf,f as Tf}from"./chunk-vwn39c84.js";import{B as s,C as Mf,G as Ff,H as g,J as Uf,K as qf,M as Bf,P as h,W as Lf,z as wf}from"./chunk-j79jvd54.js";import{Y as T}from"./chunk-zxf08z5f.js";import{ba as u}from"./chunk-3xqfqpa7.js";import{Ba as xf,Ca as Rf,Ga as z,za as S}from"./chunk-m99qhdkf.js";import{La as _f,Na as t,Sa as Ef}from"./chunk-j25kww7j.js";import{xb as R}from"./chunk-7ycmx7c2.js";import{Bb as x}from"./chunk-set7v1rf.js";import{Db as jf}from"./chunk-j2ag7hh6.js";var I0={port:{type:"number",describe:"Port to listen on (0 for auto)",default:0},hostname:{type:"string",describe:"Hostname to listen on",default:"127.0.0.1"},cors:{type:"array",describe:"Additional domains to allow for CORS",default:[]}};function v0(V){return{port:V.port??0,hostname:V.hostname??"127.0.0.1",cors:V.cors??[]}}import{Hono as T0}from"hono";import{cors as y0}from"hono/cors";import{existsSync as gf,readFileSync as e}from"node:fs";import{createServer as _0}from"node:http";import{networkInterfaces as D0}from"node:os";import{dirname as b0,extname as w0,join as w}from"node:path";import{fileURLToPath as L0}from"node:url";import{WebSocketServer as P0}from"ws";import{z as c}from"zod";class p extends Error{code;statusCode;constructor(V,$,f=500){super($);this.code=V;this.statusCode=f;this.name="BladeServerError"}toObject(){return{error:{code:this.code,message:this.message}}}}class P extends p{constructor(V,$){super("NOT_FOUND",$?`${V} not found: ${$}`:`${V} not found`,404)}}class A extends p{constructor(V){super("BAD_REQUEST",V,400)}}var g0=c.object({error:c.object({code:c.string(),message:c.string()})});import{Hono as cf}from"hono";import{z as k}from"zod";var $f=x("Service"),af=k.object({updates:k.record(k.any()),options:k.object({scope:k.enum(["local","project","global"]).optional(),immediate:k.boolean().optional()}).optional()}),Gf=()=>{let V=new cf;return V.get("/",async($)=>{try{let f=S();return $.json(f||{})}catch(f){return $f.error("[ConfigRoutes] Failed to get config:",f),$.json({})}}),V.put("/",async($)=>{try{let f=await $.req.json(),O=af.safeParse(f);if(!O.success)throw new A("Invalid config update format");let{updates:M,options:J}=O.data;return await z().updateConfig(M,J),$.json({success:!0,updates:M})}catch(f){throw $f.error("[ConfigRoutes] Failed to update config:",f),f}}),V.get("/permissions",async($)=>{try{let f=S();return $.json(f?.permissions||{})}catch(f){return $f.error("[ConfigRoutes] Failed to get permissions:",f),$.json({})}}),V};import{Hono as tf}from"hono";var Nf=()=>{let V=new tf;return V.get("/health",($)=>{return $.json({healthy:!0,version:u()})}),V.get("/info",($)=>{return $.json({version:u(),platform:process.platform,arch:process.arch,nodeVersion:process.version,cwd:R()})}),V};import{Hono as nf}from"hono";var o=x("Service"),mf=()=>{let V=new nf;return V.get("/",async($)=>{try{let O=T.getInstance().getAllServers(),M=Array.from(O.entries()).map(([J,j])=>({id:J,name:J,status:j.status==="connected"?"connected":j.status==="connecting"?"connecting":j.lastError?"error":"offline",endpoint:j.config.command?`${j.config.command} ${(j.config.args||[]).join(" ")}`.trim():j.config.url||"Unknown",description:`MCP server: ${J}`,tools:j.tools.map((Y)=>Y.name),connectedAt:j.connectedAt?.toISOString(),error:j.lastError?.message}));return $.json(M)}catch(f){return o.error("[McpRoutes] Failed to get MCP servers:",f),$.json([])}}),V.post("/:name/connect",async($)=>{try{let f=$.req.param("name");return await T.getInstance().connectServer(f),$.json({success:!0})}catch(f){return o.error("[McpRoutes] Failed to connect MCP server:",f),$.json({success:!1,error:f.message},500)}}),V.post("/:name/disconnect",async($)=>{try{let f=$.req.param("name");return await T.getInstance().disconnectServer(f),$.json({success:!0})}catch(f){return o.error("[McpRoutes] Failed to disconnect MCP server:",f),$.json({success:!1,error:f.message},500)}}),V.delete("/:name",async($)=>{try{let f=$.req.param("name");await T.getInstance().unregisterServer(f);let M=S();if(M?.mcpServers){let{[f]:J,...j}=M.mcpServers;await z().updateConfig({mcpServers:j})}return $.json({success:!0})}catch(f){return o.error("[McpRoutes] Failed to delete MCP server:",f),$.json({success:!1,error:f.message},500)}}),V.post("/",async($)=>{try{let f=await $.req.json(),{name:O,config:M}=f;if(!O||!M)return $.json({success:!1,error:"Missing name or config"},400);await T.getInstance().registerServer(O,M);let j=S();return await z().updateConfig({mcpServers:{...j?.mcpServers,[O]:M}}),$.json({success:!0})}catch(f){return o.error("[McpRoutes] Failed to add MCP server:",f),$.json({success:!1,error:f.message},500)}}),V};import{Hono as sf}from"hono";var a=x("Service"),Xf=()=>{let V=new sf;return V.get("/",async($)=>{try{let f=xf(),O=Rf();return $.json({configured:f,current:O})}catch(f){return a.error("[ModelsRoutes] Failed to get models:",f),$.json({configured:[],current:null})}}),V.post("/",async($)=>{try{let f=await $.req.json(),{provider:O,name:M,model:J,baseUrl:j,apiKey:Y}=f;if(!J)throw new A("model is required");let K=await z().addModel({provider:O||"openai-compatible",name:M||J,model:J,baseUrl:j||void 0,apiKey:Y||void 0});return $.json({success:!0,model:K})}catch(f){throw a.error("[ModelsRoutes] Failed to add model:",f),f}}),V.put("/:modelId",async($)=>{try{let f=$.req.param("modelId"),O=await $.req.json(),{baseUrl:M,apiKey:J,model:j}=O;return await z().updateModel(f,{baseUrl:M||void 0,apiKey:J||void 0,model:j||void 0}),$.json({success:!0})}catch(f){throw a.error("[ModelsRoutes] Failed to update model:",f),f}}),V.delete("/:modelId",async($)=>{try{let f=$.req.param("modelId");return await z().removeModel(f),$.json({success:!0})}catch(f){throw a.error("[ModelsRoutes] Failed to delete model:",f),f}}),V};import{Hono as Z0}from"hono";import{z as C}from"zod";import{Hono as ef}from"hono";import{streamSSE as f0}from"hono/streaming";import{LRUCache as $0}from"lru-cache";import{nanoid as d}from"nanoid";import{z as U}from"zod";var X=x("Service"),V0=U.object({title:U.string().optional(),projectPath:U.string().optional()}),O0=U.object({content:U.string(),attachments:U.array(U.object({type:U.enum(["file","image","url"]),path:U.string().optional(),url:U.string().optional(),content:U.string().optional(),mimeType:U.string().optional(),name:U.string().optional()})).optional(),permissionMode:U.enum(["default","autoEdit","plan","spec","yolo"]).optional()}),M0=U.object({title:U.string().optional()}),B=new Map,D=new $0({max:100,ttl:1800000,dispose:(V,$)=>{if(V.status==="running"||V.status==="waiting_permission")V.abortController.abort(),X.debug(`[SessionRoutes] Run ${$} disposed due to cache eviction`)}}),j0=(V)=>{if(!V||typeof V!=="object")return V;let $={...V},f=200000;if(typeof $.oldContent==="string"&&$.oldContent.length>f)delete $.oldContent;if(typeof $.newContent==="string"&&$.newContent.length>f)delete $.newContent;return $};function J0(V){if(typeof V==="string")return V;return V.filter(($)=>$.type==="text").map(($)=>$.text).join(`
1
+ import{e as zf,f as Tf}from"./chunk-vwn39c84.js";import{B as s,C as Mf,G as Ff,H as g,J as Uf,K as qf,M as Bf,P as h,W as Lf,z as wf}from"./chunk-jvbx3h56.js";import{Y as T}from"./chunk-4jh0h16z.js";import{ba as u}from"./chunk-kd1t45br.js";import{Ba as xf,Ca as Rf,Ga as z,za as S}from"./chunk-76emdpxa.js";import{La as _f,Na as t,Sa as Ef}from"./chunk-ehcjnwnr.js";import{xb as R}from"./chunk-7ycmx7c2.js";import{Bb as x}from"./chunk-set7v1rf.js";import{Db as jf}from"./chunk-j2ag7hh6.js";var I0={port:{type:"number",describe:"Port to listen on (0 for auto)",default:0},hostname:{type:"string",describe:"Hostname to listen on",default:"127.0.0.1"},cors:{type:"array",describe:"Additional domains to allow for CORS",default:[]}};function v0(V){return{port:V.port??0,hostname:V.hostname??"127.0.0.1",cors:V.cors??[]}}import{Hono as T0}from"hono";import{cors as y0}from"hono/cors";import{existsSync as gf,readFileSync as e}from"node:fs";import{createServer as _0}from"node:http";import{networkInterfaces as D0}from"node:os";import{dirname as b0,extname as w0,join as w}from"node:path";import{fileURLToPath as L0}from"node:url";import{WebSocketServer as P0}from"ws";import{z as c}from"zod";class p extends Error{code;statusCode;constructor(V,$,f=500){super($);this.code=V;this.statusCode=f;this.name="BladeServerError"}toObject(){return{error:{code:this.code,message:this.message}}}}class P extends p{constructor(V,$){super("NOT_FOUND",$?`${V} not found: ${$}`:`${V} not found`,404)}}class A extends p{constructor(V){super("BAD_REQUEST",V,400)}}var g0=c.object({error:c.object({code:c.string(),message:c.string()})});import{Hono as cf}from"hono";import{z as k}from"zod";var $f=x("Service"),af=k.object({updates:k.record(k.any()),options:k.object({scope:k.enum(["local","project","global"]).optional(),immediate:k.boolean().optional()}).optional()}),Gf=()=>{let V=new cf;return V.get("/",async($)=>{try{let f=S();return $.json(f||{})}catch(f){return $f.error("[ConfigRoutes] Failed to get config:",f),$.json({})}}),V.put("/",async($)=>{try{let f=await $.req.json(),O=af.safeParse(f);if(!O.success)throw new A("Invalid config update format");let{updates:M,options:J}=O.data;return await z().updateConfig(M,J),$.json({success:!0,updates:M})}catch(f){throw $f.error("[ConfigRoutes] Failed to update config:",f),f}}),V.get("/permissions",async($)=>{try{let f=S();return $.json(f?.permissions||{})}catch(f){return $f.error("[ConfigRoutes] Failed to get permissions:",f),$.json({})}}),V};import{Hono as tf}from"hono";var Nf=()=>{let V=new tf;return V.get("/health",($)=>{return $.json({healthy:!0,version:u()})}),V.get("/info",($)=>{return $.json({version:u(),platform:process.platform,arch:process.arch,nodeVersion:process.version,cwd:R()})}),V};import{Hono as nf}from"hono";var o=x("Service"),mf=()=>{let V=new nf;return V.get("/",async($)=>{try{let O=T.getInstance().getAllServers(),M=Array.from(O.entries()).map(([J,j])=>({id:J,name:J,status:j.status==="connected"?"connected":j.status==="connecting"?"connecting":j.lastError?"error":"offline",endpoint:j.config.command?`${j.config.command} ${(j.config.args||[]).join(" ")}`.trim():j.config.url||"Unknown",description:`MCP server: ${J}`,tools:j.tools.map((Y)=>Y.name),connectedAt:j.connectedAt?.toISOString(),error:j.lastError?.message}));return $.json(M)}catch(f){return o.error("[McpRoutes] Failed to get MCP servers:",f),$.json([])}}),V.post("/:name/connect",async($)=>{try{let f=$.req.param("name");return await T.getInstance().connectServer(f),$.json({success:!0})}catch(f){return o.error("[McpRoutes] Failed to connect MCP server:",f),$.json({success:!1,error:f.message},500)}}),V.post("/:name/disconnect",async($)=>{try{let f=$.req.param("name");return await T.getInstance().disconnectServer(f),$.json({success:!0})}catch(f){return o.error("[McpRoutes] Failed to disconnect MCP server:",f),$.json({success:!1,error:f.message},500)}}),V.delete("/:name",async($)=>{try{let f=$.req.param("name");await T.getInstance().unregisterServer(f);let M=S();if(M?.mcpServers){let{[f]:J,...j}=M.mcpServers;await z().updateConfig({mcpServers:j})}return $.json({success:!0})}catch(f){return o.error("[McpRoutes] Failed to delete MCP server:",f),$.json({success:!1,error:f.message},500)}}),V.post("/",async($)=>{try{let f=await $.req.json(),{name:O,config:M}=f;if(!O||!M)return $.json({success:!1,error:"Missing name or config"},400);await T.getInstance().registerServer(O,M);let j=S();return await z().updateConfig({mcpServers:{...j?.mcpServers,[O]:M}}),$.json({success:!0})}catch(f){return o.error("[McpRoutes] Failed to add MCP server:",f),$.json({success:!1,error:f.message},500)}}),V};import{Hono as sf}from"hono";var a=x("Service"),Xf=()=>{let V=new sf;return V.get("/",async($)=>{try{let f=xf(),O=Rf();return $.json({configured:f,current:O})}catch(f){return a.error("[ModelsRoutes] Failed to get models:",f),$.json({configured:[],current:null})}}),V.post("/",async($)=>{try{let f=await $.req.json(),{provider:O,name:M,model:J,baseUrl:j,apiKey:Y}=f;if(!J)throw new A("model is required");let K=await z().addModel({provider:O||"openai-compatible",name:M||J,model:J,baseUrl:j||void 0,apiKey:Y||void 0});return $.json({success:!0,model:K})}catch(f){throw a.error("[ModelsRoutes] Failed to add model:",f),f}}),V.put("/:modelId",async($)=>{try{let f=$.req.param("modelId"),O=await $.req.json(),{baseUrl:M,apiKey:J,model:j}=O;return await z().updateModel(f,{baseUrl:M||void 0,apiKey:J||void 0,model:j||void 0}),$.json({success:!0})}catch(f){throw a.error("[ModelsRoutes] Failed to update model:",f),f}}),V.delete("/:modelId",async($)=>{try{let f=$.req.param("modelId");return await z().removeModel(f),$.json({success:!0})}catch(f){throw a.error("[ModelsRoutes] Failed to delete model:",f),f}}),V};import{Hono as Z0}from"hono";import{z as C}from"zod";import{Hono as ef}from"hono";import{streamSSE as f0}from"hono/streaming";import{LRUCache as $0}from"lru-cache";import{nanoid as d}from"nanoid";import{z as U}from"zod";var X=x("Service"),V0=U.object({title:U.string().optional(),projectPath:U.string().optional()}),O0=U.object({content:U.string(),attachments:U.array(U.object({type:U.enum(["file","image","url"]),path:U.string().optional(),url:U.string().optional(),content:U.string().optional(),mimeType:U.string().optional(),name:U.string().optional()})).optional(),permissionMode:U.enum(["default","autoEdit","plan","spec","yolo"]).optional()}),M0=U.object({title:U.string().optional()}),B=new Map,D=new $0({max:100,ttl:1800000,dispose:(V,$)=>{if(V.status==="running"||V.status==="waiting_permission")V.abortController.abort(),X.debug(`[SessionRoutes] Run ${$} disposed due to cache eviction`)}}),j0=(V)=>{if(!V||typeof V!=="object")return V;let $={...V},f=200000;if(typeof $.oldContent==="string"&&$.oldContent.length>f)delete $.oldContent;if(typeof $.newContent==="string"&&$.newContent.length>f)delete $.newContent;return $};function J0(V){if(typeof V==="string")return V;return V.filter(($)=>$.type==="text").map(($)=>$.text).join(`
2
2
  `)}function Q0(V,$){let f=($??[]).filter((M)=>M.type==="image"&&typeof M.content==="string").map((M)=>({type:"image_url",image_url:{url:M.content}}));if(f.length===0)return V;let O=[];if(V.trim())O.push({type:"text",text:V});return O.push(...f),O}var Wf=()=>{let V=new ef,$=new Map;return V.get("/",async(f)=>{try{let O=await h.listSessions(),M=new Set(O.filter((G)=>G.relationType==="subagent").map((G)=>G.sessionId)),J=Array.from(B.values()).filter((G)=>!M.has(G.id)&&G.relationType!=="subagent").map((G)=>({sessionId:G.id,projectPath:G.projectPath,title:G.title,parentId:void 0,relationType:void 0,status:void 0,agentType:void 0,model:void 0,messageCount:G.messages.length,firstMessageTime:G.createdAt.toISOString(),lastMessageTime:new Date().toISOString(),hasErrors:!1,isActive:!0})),j=new Set(J.map((G)=>G.sessionId)),Y=O.filter((G)=>!B.has(G.sessionId)&&!j.has(G.sessionId)&&G.relationType!=="subagent"),K=new Set(j),Q=Y.filter((G)=>{if(K.has(G.sessionId))return!1;return K.add(G.sessionId),!0}),Z=[...J,...Q];return f.json(Z)}catch(O){return X.error("[SessionRoutes] Failed to list sessions:",O),f.json([])}}),V.post("/",async(f)=>{try{let O=await f.req.json(),M=V0.safeParse(O);if(!M.success)throw new A("Invalid request body");let{title:J,projectPath:j}=M.data,Y=d(12),K=j||f.get("directory")||R(),Q={id:Y,projectPath:K,title:J||`Session ${Y.slice(0,6)}`,createdAt:new Date,messages:[]};return B.set(Y,Q),f.json({sessionId:Y,projectPath:K,title:Q.title,parentId:void 0,relationType:void 0,status:void 0,agentType:void 0,model:void 0,messageCount:0,firstMessageTime:Q.createdAt.toISOString(),lastMessageTime:Q.createdAt.toISOString(),hasErrors:!1})}catch(O){throw X.error("[SessionRoutes] Failed to create session:",O),O}}),V.get("/:sessionId",async(f)=>{let O=f.req.param("sessionId"),M=B.get(O);if(M)return f.json({sessionId:M.id,projectPath:M.projectPath,title:M.title,messageCount:M.messages.length,firstMessageTime:M.createdAt.toISOString(),lastMessageTime:new Date().toISOString(),hasErrors:!1,isActive:!0});try{let j=(await h.listSessions()).find((Y)=>Y.sessionId===O);if(!j)throw new P("Session",O);return f.json(j)}catch(J){if(J instanceof P)throw J;throw X.error("[SessionRoutes] Failed to get session:",J),J}}),V.patch("/:sessionId",async(f)=>{let O=f.req.param("sessionId");try{let M=await f.req.json(),J=M0.safeParse(M);if(!J.success)throw new A("Invalid request body");let{title:j}=J.data,Y=B.get(O);if(Y&&j)Y.title=j;return f.json({success:!0,title:j})}catch(M){throw X.error("[SessionRoutes] Failed to update session:",M),M}}),V.delete("/:sessionId",async(f)=>{let O=f.req.param("sessionId"),M=B.get(O);if(M?.currentRunId){let j=D.get(M.currentRunId);if(j)j.abortController.abort(),g.publish(O,"run.cancelled",{runId:j.id}),D.delete(M.currentRunId)}try{await h.deleteSession(O)}catch(j){X.warn("[SessionRoutes] Failed to delete session file:",j)}B.delete(O);let J=$.get(O);if(J){if(await J.dispose(),$.delete(O),$.size===0)await T.getInstance().disconnectAll()}return f.json({success:!0})}),V.get("/:sessionId/message",async(f)=>{let O=f.req.param("sessionId");try{let M=await h.loadSession(O);return f.json(M)}catch(M){return X.error("[SessionRoutes] Failed to get messages:",M),f.json([])}}),V.get("/:sessionId/events",async(f)=>{let O=f.req.param("sessionId"),M=B.get(O);if(!M){let J=f.get("directory")||R();M={id:O,projectPath:J,title:`Session ${O.slice(0,6)}`,createdAt:new Date,messages:[]},B.set(O,M)}return f0(f,async(J)=>{await J.writeSSE({data:JSON.stringify({type:"connected",properties:{sessionId:O,timestamp:Date.now()}})});let Y=g.subscribe((Q)=>{if(Q.sessionId!==O)return;J.writeSSE({data:JSON.stringify({type:Q.type,properties:{sessionId:Q.sessionId,...Q.properties}})}).catch(()=>{})}),K=setInterval(()=>{if(!J.aborted)J.writeSSE({data:JSON.stringify({type:"heartbeat",properties:{timestamp:Date.now()}})}).catch(()=>{})},15000);J.onAbort(()=>{clearInterval(K),Y()});while(!0)if(await new Promise((Q)=>setTimeout(Q,1000)),J.aborted)break})}),V.post("/:sessionId/message",async(f)=>{let O=f.req.param("sessionId"),M=await f.req.json(),J=O0.safeParse(M);if(!J.success)throw new A("Invalid message format");let{content:j,attachments:Y,permissionMode:K}=J.data,Q=K||"default",Z=f.get("directory")||R(),G=Q0(j,Y),m=B.get(O);if(!m){let N=await h.loadSession(O).catch(()=>[]);m={id:O,projectPath:Z,title:`Session ${O.slice(0,6)}`,createdAt:new Date,messages:N},B.set(O,m)}let q=d(12),L=new AbortController,E={id:q,sessionId:O,status:"running",abortController:L,createdAt:new Date};return D.set(q,E),m.currentRunId=q,Y0(E,m,G,Q,$).catch((N)=>{X.error(`[SessionRoutes] Run ${q} failed:`,N)}),f.json({runId:q,status:"running"},202)}),V.post("/:sessionId/abort",async(f)=>{let O=f.req.param("sessionId"),M=B.get(O);if(M?.currentRunId){let J=D.get(M.currentRunId);if(J)J.abortController.abort(),J.status="cancelled",g.publish(O,"run.cancelled",{runId:J.id})}return f.json({success:!0})}),V.get("/:sessionId/status",async(f)=>{let O=f.req.param("sessionId"),M=B.get(O);if(!M?.currentRunId)return f.json({sessionId:O,status:"idle"});let J=D.get(M.currentRunId);return f.json({sessionId:O,runId:M.currentRunId,status:J?.status||"idle"})}),V};async function Y0(V,$,f,O,M){let{abortController:J,sessionId:j,id:Y}=V,K=d(12),Q=d(12),Z=(G,m)=>{g.publish(j,G,m)};try{Z("message.created",{messageId:K,role:"user",content:J0(f)}),Z("session.status",{status:"running"}),Z("message.created",{messageId:Q,role:"assistant",content:""});let G=M.get(j);if(!G)G=await Ff.create({sessionId:j}),M.set(j,G);let m=await Bf.createWithRuntime(G,{sessionId:j}),q=async(N)=>{let F=d(12),l=300000;V.status="waiting_permission";let ff=new Promise((Kf)=>{let rf=setTimeout(()=>{X.warn(`[SessionRoutes] Permission ${F} timed out after 300000ms`),Z("permission.timeout",{requestId:F}),Kf({approved:!1,reason:"timeout"})},300000);V.pendingPermission={permissionId:F,resolve:(lf)=>{clearTimeout(rf),Kf(lf)},details:N}});Z("permission.asked",{requestId:F,toolName:N.toolName,description:N.message,args:N.args,details:N}),X.info(`[SessionRoutes] Permission request created: ${F}, runId: ${Y}`);let Zf=await ff;return X.info(`[SessionRoutes] Permission response received: ${F}, approved: ${Zf.approved}`),V.status="running",V.pendingPermission=void 0,Zf},L={messages:[...$.messages],userId:"web-user",sessionId:j,workspaceRoot:$.projectPath,signal:J.signal,permissionMode:O,confirmationHandler:{requestConfirmation:q}},E=await Ef(m.chatStream(f,L,{stream:!0}),async(N)=>{switch(N.kind){case"content_delta":Z("message.delta",{messageId:Q,delta:N.delta});break;case"thinking_delta":Z("thinking.delta",{delta:N.delta});break;case"tool_start":if("function"in N.toolCall)Z("tool.start",{messageId:Q,toolName:N.toolCall.function.name,toolCallId:N.toolCall.id,arguments:N.toolCall.function.arguments,toolKind:N.toolKind});break;case"tool_result":if("function"in N.toolCall)Z("tool.result",{messageId:Q,toolName:N.toolCall.function.name,toolCallId:N.toolCall.id,success:!N.result.error,summary:N.result.metadata?.summary,output:qf(Uf(N.toolCall.function.name,N.result)),metadata:j0(N.result.metadata)});break;case"token_usage":Z("token.usage",{...N.usage});break;case"task_update":Z("task.updated",{tasks:N.tasks});break;default:break}});$.messages=[...L.messages],Z("message.complete",{messageId:Q}),Z("thinking.completed",{}),V.status="completed",Z("session.completed",{runId:Y,outputTruncated:E.metadata?.outputTruncated??!1}),Z("session.status",{status:"idle"})}catch(G){X.error("[SessionRoutes] Agent execution error:",G),V.status="failed",Z("session.error",{error:G instanceof Error?G.message:"Unknown error"}),Z("session.status",{status:"error"})}}function Af(V,$,f){X.info(`[SessionRoutes] Looking for permission ${$} in session ${V}`),X.info(`[SessionRoutes] Active runs: ${D.size}`);for(let[O,M]of D.entries())if(X.info(`[SessionRoutes] Checking run ${O}: sessionId=${M.sessionId}, pendingPermission=${M.pendingPermission?.permissionId}`),M.sessionId===V&&M.pendingPermission?.permissionId===$)return M.pendingPermission.resolve(f),X.info(`[SessionRoutes] Permission ${$} responded, runId: ${M.id}`),!0;return X.error(`[SessionRoutes] Permission not found: ${$}`),!1}var Vf=x("Service"),K0=C.object({approved:C.boolean(),remember:C.boolean().optional(),scope:C.enum(["once","session"]).optional(),targetMode:C.enum(["default","autoEdit","plan","spec","yolo"]).optional(),feedback:C.string().optional(),answers:C.record(C.union([C.string(),C.array(C.string())])).optional()}),Cf=()=>{let V=new Z0;return V.post("/:permissionId",async($)=>{let f=$.req.param("permissionId"),O=$.req.query("sessionId");Vf.info(`[PermissionRoutes] Received permission response: permissionId=${f}, sessionId=${O}`);try{let M=await $.req.json(),J=K0.safeParse(M);if(!J.success)throw new A("Invalid permission response format");let{approved:j,remember:Y,scope:K,targetMode:Q,feedback:Z,answers:G}=J.data;if(!O)throw new A("sessionId query parameter is required");if(!Af(O,f,{approved:j,reason:Z,scope:K,targetMode:Q,feedback:Z,answers:G}))throw new P("Permission request",f);return Vf.info(`[PermissionRoutes] Permission ${f} ${j?"approved":"denied"}`),$.json({success:!0,approved:j,remember:Y})}catch(M){throw Vf.error("[PermissionRoutes] Failed to respond to permission:",M),M}}),V};import{Hono as G0}from"hono";var Hf=x("Service"),yf=()=>{let V=new G0;return V.get("/",async($)=>{try{let f=await zf();return $.json(f)}catch(f){return Hf.error("[ProviderRoutes] Failed to list providers:",f),$.json([])}}),V.get("/:provider/models",async($)=>{let f=$.req.param("provider");try{let O=await Tf(f);return $.json(O)}catch(O){return Hf.error("[ProviderRoutes] Failed to list models:",O),$.json([])}}),V};import{Hono as N0}from"hono";import*as y from"node:fs/promises";import{homedir as m0}from"node:os";import*as n from"node:path";var b=x("Service"),Of=n.join(m0(),".blade","skills-config.json");async function Df(){try{let V=await y.readFile(Of,"utf-8");return JSON.parse(V)}catch{return{disabled:[]}}}async function x0(V){await y.mkdir(n.dirname(Of),{recursive:!0}),await y.writeFile(Of,JSON.stringify(V,null,2))}async function R0(V,$){let f=await Df();if($)f.disabled=f.disabled.filter((O)=>O!==V);else if(!f.disabled.includes(V))f.disabled.push(V);await x0(f)}var I=null,X0=300000;async function E0(){if(I&&Date.now()-I.timestamp<X0)return I.data;try{let V=await fetch("https://api.github.com/repos/anthropics/skills/contents/skills",{headers:{Accept:"application/vnd.github.v3+json","User-Agent":"Blade-Skills-Catalog"}});if(!V.ok)return b.warn(`GitHub API returned ${V.status}`),I?.data||[];let $=await V.json(),f=[];for(let O of $){if(O.type!=="dir")continue;let M=`Official ${O.name} skill`;try{let J=await fetch(`https://raw.githubusercontent.com/anthropics/skills/main/skills/${O.name}/SKILL.md`,{headers:{"User-Agent":"Blade-Skills-Catalog"}});if(J.ok){let Y=(await J.text()).match(/^#[^\n]*\n+([^\n#]+)/);if(Y)M=Y[1].trim().slice(0,100)}}catch{}f.push({name:O.name,description:M,tag:"Official",author:"Anthropic"})}return I={data:f,timestamp:Date.now()},f}catch(V){return b.warn("Failed to fetch skills catalog from GitHub:",V),I?.data||[]}}var bf=()=>{let V=new N0;return V.get("/",async($)=>{try{let f=t();await f.initialize();let O=f.getAll(),M=await Df(),J=O.map((j)=>({id:j.name,name:j.name,enabled:!M.disabled.includes(j.name),description:j.description||"",version:j.version||"1.0.0",provider:"Local",location:j.source==="builtin"?"Built-in":j.basePath,capabilities:["prompts"],allowedTools:j.allowedTools||[]}));return $.json(J)}catch(f){return b.error("[SkillsRoutes] Failed to get skills:",f),$.json([])}}),V.post("/:name/toggle",async($)=>{try{let f=$.req.param("name"),O=await $.req.json();return await R0(f,O.enabled),$.json({success:!0,enabled:O.enabled})}catch(f){return b.error("[SkillsRoutes] Failed to toggle skill:",f),$.json({success:!1,error:f.message},500)}}),V.delete("/:name",async($)=>{try{let f=$.req.param("name"),O=`${process.env.HOME}/.blade/skills/${f}`;return await y.rm(O,{recursive:!0,force:!0}),await t().refresh(),$.json({success:!0})}catch(f){return b.error("[SkillsRoutes] Failed to uninstall skill:",f),$.json({success:!1,error:f.message},500)}}),V.post("/install",async($)=>{try{let f=await $.req.json(),O=_f(),M=t(),J=!1;if(f.source==="catalog"&&f.name){if(J=await O.installOfficialSkill(f.name),!J)return $.json({success:!1,error:"Failed to install skill from catalog"},500)}else if(f.source==="repo"&&f.url){if(J=await O.installFromRepo(f.url,f.name),!J)return $.json({success:!1,error:"Failed to install skill from repository. Make sure the repo contains a SKILL.md file."},500)}else if(f.source==="local"&&f.path){if(J=await O.installFromLocal(f.path,f.name),!J)return $.json({success:!1,error:"Failed to install skill from local path. Make sure the path exists and contains a SKILL.md file."},500)}else return $.json({success:!1,error:"Invalid install parameters. Required: source with corresponding url/path/name"},400);return await M.refresh(),$.json({success:!0})}catch(f){return b.error("[SkillsRoutes] Failed to install skill:",f),$.json({success:!1,error:f.message},500)}}),V.get("/catalog",async($)=>{try{let f=await E0();return $.json(f)}catch(f){return b.error("[SkillsRoutes] Failed to get catalog:",f),$.json([])}}),V};import F0 from"fast-glob";import{Hono as U0}from"hono";import{execSync as q0}from"node:child_process";import{readdir as B0}from"node:fs/promises";import i from"node:path";var r=x("Service"),W0=(V)=>{try{return q0("git rev-parse --abbrev-ref HEAD",{cwd:V,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||null}catch{return null}},A0=[...s.map((V)=>`${V}/**`),...s,...Mf.map((V)=>`**/${V}`)],C0=new Set(["/theme","/model","/permissions","/mcp","/skills","/exit","/resume","/ide","/login","/logout"]),Pf=()=>{let V=new U0;return V.get("/commands",async($)=>{try{let f=$.req.query("q")||"",O=Lf(f).filter((M)=>!C0.has(M.command));return $.json(O)}catch(f){return r.error("[SuggestionsRoutes] Failed to get command suggestions:",f),$.json([])}}),V.get("/files",async($)=>{try{let f=$.req.query("q")||"",O=$.get("directory")||R(),M=Math.min(Number($.req.query("limit"))||100,1000),j=(await F0("**/*",{cwd:O,dot:!1,followSymbolicLinks:!1,onlyFiles:!1,markDirectories:!0,unique:!0,ignore:A0})).map((Q)=>Q.replace(/\\/g,"/"));if(!f)return $.json(j.slice(0,M));let Y=f.toLowerCase(),K=j.filter((Q)=>Q.toLowerCase().includes(Y)).slice(0,M);return $.json(K)}catch(f){return r.error("[SuggestionsRoutes] Failed to get file suggestions:",f),$.json([])}}),V.get("/files/tree",async($)=>{try{let f=$.get("directory")||R(),O=$.req.query("path")||"",M=O?i.join(f,O):f,j=(await B0(M,{withFileTypes:!0})).map((Q)=>({name:Q.name,path:O?`${O}/${Q.name}`:Q.name,type:Q.isDirectory()?"dir":"file"}));j.sort((Q,Z)=>{if(Q.type!==Z.type)return Q.type==="dir"?-1:1;return Q.name.localeCompare(Z.name)});let Y=new Set(s),K=j.filter((Q)=>{let Z=Q.name;if(Z.startsWith("."))return!1;if(Y.has(Z))return!1;for(let G of Mf)if(Z.match(new RegExp(G.replace("*",".*"))))return!1;return!0});return $.json(K)}catch(f){return r.error("[SuggestionsRoutes] Failed to get file tree:",f),$.json([])}}),V.get("/files/content",async($)=>{try{let f=$.req.query("path");if(!f)return $.json({error:"Missing file path"},400);let O=$.get("directory")||R(),M=i.resolve(O,f),J=i.relative(O,M);if(J.startsWith("..")||i.isAbsolute(J))return $.json({error:"Invalid file path"},400);let j=wf(),Y=await j.stat(M);if(!Y?.isFile)return $.json({error:"File not found"},404);let K=200000,Q=await j.readTextFile(M),Z=Q.length>K;return $.json({path:f,content:Z?Q.slice(0,K):Q,truncated:Z,size:Y.size})}catch(f){return r.error("[SuggestionsRoutes] Failed to get file content:",f),$.json({error:"Failed to read file"},500)}}),V.get("/git-info",async($)=>{try{let f=$.get("directory")||R(),O=W0(f);return $.json({branch:O})}catch(f){return r.error("[SuggestionsRoutes] Failed to get git info:",f),$.json({branch:null})}}),V};import{Hono as H0}from"hono";var _=x("Service"),v=new Map,kf=2097152,Sf=65536;function uf(){return typeof globalThis.Bun<"u"}async function z0(V,$,f){if(uf()){let{spawn:J}=await import("bun-pty"),j=J(V,$,{name:"xterm-256color",cwd:f.cwd,env:f.env});return{pid:j.pid,write:(Y)=>j.write(Y),resize:(Y,K)=>j.resize(Y,K),kill:()=>j.kill(),onData:(Y)=>j.onData(Y),onExit:(Y)=>j.onExit(Y)}}let M=(await import("node-pty")).spawn(V,$,{name:"xterm-256color",cwd:f.cwd,env:f.env,cols:80,rows:24});return{pid:M.pid,write:(J)=>M.write(J),resize:(J,j)=>M.resize(J,j),kill:()=>M.kill(),onData:(J)=>{M.onData(J)},onExit:(J)=>{M.onExit(J)}}}var Qf=void 0,Jf;if(uf())try{let{createBunWebSocket:V}=await import("hono/bun"),$=V();Jf=$.upgradeWebSocket,Qf=$.websocket}catch(V){_.warn("[Terminal] Failed to initialize Bun WebSocket support:",V)}async function hf(V,$){let f=`term-${Date.now()}`;_.info(`[Terminal] New connection: ${f}, cwd: ${V}`);let O=process.platform==="win32"?"powershell.exe":process.env.SHELL||"/bin/zsh",M=O.endsWith("sh")?["-l"]:[],J=await z0(O,M,{cwd:V,env:{...process.env,TERM:"xterm-256color",COLORTERM:"truecolor"}}),j={id:f,process:J,cwd:V,buffer:"",subscribers:new Set};if(v.set(f,j),j.subscribers.add($),J.onData((Y)=>{let K=!1;for(let Q of j.subscribers)try{Q.send(Y),K=!0}catch{j.subscribers.delete(Q)}if(K)return;if(j.buffer+=Y,j.buffer.length>kf)j.buffer=j.buffer.slice(-kf)}),J.onExit(({exitCode:Y})=>{_.info(`[Terminal] Process exited: ${f}, code: ${Y}`);for(let K of j.subscribers)try{K.close()}catch{}v.delete(f)}),j.buffer){let Y=j.buffer;j.buffer="";for(let K=0;K<Y.length;K+=Sf)$.send(Y.slice(K,K+Sf))}return{session:j,cleanup:()=>{if(_.info(`[Terminal] Connection closed: ${f}`),j.subscribers.delete($),j.subscribers.size===0){try{j.process.kill()}catch{}v.delete(f)}}}}function If(V,$){V.on("connection",async(f,O)=>{let M=new URL(O.url||"/",`http://${O.headers.host}`);if(!M.pathname.endsWith("/terminal/ws")){f.close();return}let J=M.searchParams.get("cwd")||$()||R();try{let{session:j,cleanup:Y}=await hf(J,{send:(K)=>f.send(K),close:()=>f.close()});f.on("message",(K)=>{try{j.process.write(String(K))}catch(Q){_.error("[Terminal] Failed to write to PTY:",Q)}}),f.on("close",Y),f.on("error",Y)}catch(j){_.error("[Terminal] Failed to spawn PTY:",j),f.close()}})}var vf=()=>{let V=new H0;if(V.get("/status",($)=>{let f=Array.from(v.values()).map((O)=>({id:O.id,cwd:O.cwd}));return $.json({active:f.length,terminals:f})}),V.post("/kill/:terminalId",($)=>{let f=$.req.param("terminalId"),O=v.get(f);if(O){try{O.process.kill()}catch{}for(let M of O.subscribers)M.close();return v.delete(f),$.json({success:!0})}return $.json({success:!1,error:"Terminal not found"},404)}),Jf)V.get("/ws",Jf(($)=>{let f=$.req.query("cwd")||$.get("directory")||R(),O;return{async onOpen(M,J){try{O=await hf(f,{send:(j)=>J.send(j),close:()=>J.close()})}catch(j){_.error("[Terminal] Failed to spawn PTY:",j),J.close()}},onMessage(M){if(!O)return;try{O.session.process.write(String(M.data))}catch(J){_.error("[Terminal] Failed to write to PTY:",J)}},onClose(){O?.cleanup()}}}));else V.get("/ws",($)=>{return $.json({message:"WebSocket endpoint - connect via ws:// protocol",hint:"Use WebSocket client to connect to this endpoint"})});return V};var W=x("Service"),Yf=[];function k0(){let V=b0(L0(import.meta.url)),$=[w(V,"web"),w(R(),"dist/web"),w(R(),"packages/cli/dist/web")];for(let f of $){let O=w(f,"index.html");if(gf(O)){if(e(O,"utf-8").includes("/assets/"))return W.debug(`[Server] Found web dist at: ${f}`),f}}return null}function S0(){let V=new T0;V.onError((f,O)=>{if(W.error("[Server] Request error:",f),f instanceof p)return O.json(f.toObject(),f.statusCode);let M=f instanceof Error?f.message:String(f);return O.json({error:{code:"INTERNAL_ERROR",message:M}},500)}),V.use(async(f,O)=>{let M=process.env.BLADE_SERVER_PASSWORD;if(!M)return O();let J=f.req.path;if(J==="/"||J.startsWith("/assets/")||J.endsWith(".html")||J.endsWith(".js")||J.endsWith(".css"))return O();let j=f.req.header("Authorization");if(!j?.startsWith("Basic "))return f.header("WWW-Authenticate",'Basic realm="Blade Server"'),f.json({error:{code:"UNAUTHORIZED",message:"Authentication required"}},401);let Y=Buffer.from(j.slice(6),"base64").toString(),[K,Q]=Y.split(":"),Z=process.env.BLADE_SERVER_USERNAME??"blade";if(K!==Z||Q!==M)return f.json({error:{code:"UNAUTHORIZED",message:"Invalid credentials"}},401);return O()}),V.use(async(f,O)=>{let M=f.req.path==="/health"||f.req.path==="/global/health"||f.req.path.startsWith("/assets/");if(!M)W.debug(`[Server] ${f.req.method} ${f.req.path}`);let J=Date.now();if(await O(),!M){let j=Date.now()-J;W.debug(`[Server] ${f.req.method} ${f.req.path} - ${f.res.status} (${j}ms)`)}}),V.use(y0({origin(f){if(!f)return;if(f.startsWith("http://localhost:"))return f;if(f.startsWith("http://127.0.0.1:"))return f;if(f==="tauri://localhost"||f==="http://tauri.localhost")return f;if(Yf.includes(f))return f;return}})),V.use(async(f,O)=>{let M=f.req.query("directory")||f.req.header("x-blade-directory")||R();try{M=decodeURIComponent(M)}catch{}return f.set("directory",M),O()}),V.route("/global",Nf()),V.route("/sessions",Wf()),V.route("/configs",Gf()),V.route("/permissions",Cf()),V.route("/providers",yf()),V.route("/models",Xf()),V.route("/suggestions",Pf()),V.route("/terminal",vf()),V.route("/mcp",mf()),V.route("/skills",bf()),V.get("/health",(f)=>{return f.json({healthy:!0,version:u()})});let $=k0();if($)W.info(`[Server] Serving static files from ${$}`),V.get("/assets/*",(f)=>{let O=w($,f.req.path);if(!gf(O))return f.json({error:{code:"NOT_FOUND",message:`File not found: ${f.req.path}`}},404);let M=e(O),J=w0(O).toLowerCase(),Y={".js":"application/javascript",".css":"text/css",".html":"text/html",".json":"application/json",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".svg":"image/svg+xml",".ico":"image/x-icon",".woff":"font/woff",".woff2":"font/woff2",".ttf":"font/ttf",".eot":"application/vnd.ms-fontobject"}[J]||"application/octet-stream";return new Response(M,{headers:{"Content-Type":Y,"Cache-Control":"public, max-age=31536000, immutable"}})}),V.get("/",(f)=>{let O=w($,"index.html"),M=e(O,"utf-8");return f.html(M)}),V.get("*",(f)=>{let O=f.req.path;if(O.includes("."))return f.json({error:{code:"NOT_FOUND",message:`File not found: ${O}`}},404);let M=w($,"index.html"),J=e(M,"utf-8");return f.html(J)});else W.warn('[Server] Web UI not found. Run "cd packages/cli/web && bun run build" to enable web interface.'),V.get("/",(f)=>{return f.json({message:"Blade API Server",version:u(),webUI:!1,hint:'Web UI not built. Run "cd packages/cli/web && bun run build" to enable.',endpoints:{health:"/health",sessions:"/sessions",configs:"/configs",permissions:"/permissions",providers:"/providers"}})}),V.all("*",(f)=>{return f.json({error:{code:"NOT_FOUND",message:`Route not found: ${f.req.path}`}},404)});return V}function u0(){let V=D0(),$=[];for(let f of Object.keys(V)){let O=V[f];if(!O)continue;for(let M of O){if(M.internal||M.family!=="IPv4")continue;if(M.address.startsWith("172."))continue;$.push(M.address)}}return $}function pf(){return typeof globalThis.Bun<"u"}function of(V,$){let f=globalThis.Bun,O=(J)=>{try{return f.serve({hostname:$.hostname,port:J,fetch:V.fetch,idleTimeout:0,websocket:Qf})}catch(j){W.error("Failed to start Bun server:",j);return}},M=$.port===0?O(4096)??O(0):O($.port);if(!M)throw Error(`Failed to start Bun server on port ${$.port}`);return{url:M.url,port:M.port,hostname:M.hostname,stop:async()=>{M.stop(!0)}}}function h0(V,$){return new Promise((f,O)=>{let M=_0(async(Q,Z)=>{let G=new URL(Q.url||"/",`http://${Q.headers.host}`),m=new Headers;for(let[E,N]of Object.entries(Q.headers))if(N)if(Array.isArray(N))for(let F of N)m.append(E,F);else m.set(E,N);let q;if(Q.method!=="GET"&&Q.method!=="HEAD")q=(await new Promise((N)=>{let F=[];Q.on("data",(l)=>F.push(l)),Q.on("end",()=>N(Buffer.concat(F)))})).toString();let L=new Request(G.toString(),{method:Q.method,headers:m,body:q});try{let E=await V.fetch(L);if(Z.statusCode=E.status,E.headers.forEach((N,F)=>{Z.setHeader(F,N)}),E.body){let N=E.body.getReader(),F=async()=>{let{done:l,value:ff}=await N.read();if(l){Z.end();return}return Z.write(ff),F()};await F()}else{let N=await E.text();Z.end(N)}}catch(E){W.error("[Server] Node request error:",E),Z.statusCode=500,Z.end(JSON.stringify({error:{code:"INTERNAL_ERROR",message:"Internal server error"}}))}}),J=new P0({noServer:!0}),j=R();If(J,()=>j),M.on("upgrade",(Q,Z,G)=>{if(new URL(Q.url||"/",`http://${Q.headers.host}`).pathname==="/terminal/ws")J.handleUpgrade(Q,Z,G,(q)=>{J.emit("connection",q,Q)});else Z.destroy()});let Y=(Q)=>{return new Promise((Z,G)=>{M.once("error",(m)=>{if(m.code==="EADDRINUSE")G(m);else G(m)}),M.listen(Q,$.hostname,()=>{let m=M.address();if(m&&typeof m==="object")Z(m.port);else Z(Q)})})};(async()=>{let Q;if($.port===0)try{Q=await Y(4096)}catch{Q=await Y(0)}else Q=await Y($.port);let Z=new URL(`http://${$.hostname==="0.0.0.0"?"localhost":$.hostname}:${Q}`);f({url:Z,port:Q,hostname:$.hostname,stop:async()=>{return new Promise((G)=>{J.close(()=>{M.close(()=>G())})})}})})().catch(O)})}var df;((DV)=>{let V,$;function f(){if(!$)$=S0();return $}DV.getApp=f;function O(j){Yf=j.cors??[];let Y=f();if(pf())V=of(Y,j),W.info(`[Server] Blade server listening on ${V.url} (Bun runtime)`);else throw Error("Blade web server requires Bun runtime. Please run with Bun: `bun run blade web` or install Bun from https://bun.sh");let K=V;return{url:K.url,port:K.port,hostname:K.hostname,stop:async()=>{if(V)await V.stop(),V=void 0,$=void 0,W.info("[Server] Blade server stopped")}}}DV.listen=O;async function M(j){Yf=j.cors??[];let Y=f();if(pf())V=of(Y,j),W.info(`[Server] Blade server listening on ${V.url} (Bun runtime)`);else V=await h0(Y,j),W.info(`[Server] Blade server listening on ${V.url} (Node.js runtime)`);let K=V;return{url:K.url,port:K.port,hostname:K.hostname,stop:async()=>{if(V)await V.stop(),V=void 0,$=void 0,W.info("[Server] Blade server stopped")}}}DV.listenAsync=M;function J(){return V!==void 0}DV.isRunning=J})(df||={});export{I0 as a,v0 as b,u0 as c,df as d};
@@ -1,4 +1,4 @@
1
- import{p as z,q as g,r as v,s as p}from"./chunk-4nsh53k6.js";import{t as E}from"./chunk-wr7w4af5.js";import{v as S,w as h,x as c}from"./chunk-1en8fh5f.js";import{G as w,I as F,J as y,L as x,M as C}from"./chunk-j79jvd54.js";import"./chunk-zxf08z5f.js";import"./chunk-esnkk33h.js";import"./chunk-3xqfqpa7.js";import"./chunk-2tpgtpcp.js";import"./chunk-m99qhdkf.js";import"./chunk-e2vtbvda.js";import{Sa as O}from"./chunk-j25kww7j.js";import"./chunk-yddnm9n2.js";import"./chunk-ena4sxgr.js";import"./chunk-5mtjqqav.js";import{wb as H,xb as T}from"./chunk-7ycmx7c2.js";import"./chunk-set7v1rf.js";import"./chunk-j2ag7hh6.js";import bq from"yargs";import{hideBin as Uq}from"yargs/helpers";import{z as b}from"zod";import{z as Q}from"zod";var L=1,V=Q.object({event_version:Q.literal(L)}),i=V.extend({type:Q.literal("content_delta"),delta:Q.string()}),n=V.extend({type:Q.literal("thinking_delta"),delta:Q.string()}),r=V.extend({type:Q.literal("thinking"),content:Q.string()}),s=V.extend({type:Q.literal("stream_end")}),o=V.extend({type:Q.literal("content"),content:Q.string()}),a=V.extend({type:Q.literal("tool_start"),tool_name:Q.string(),summary:Q.string(),target:Q.string().optional(),tool_kind:Q.enum(["readonly","write","execute"]).optional()}),t=V.extend({type:Q.literal("tool_result"),tool_name:Q.string(),summary:Q.string(),target:Q.string().optional(),tool_kind:Q.enum(["readonly","write","execute"]).optional()}),e=V.extend({type:Q.literal("phase"),phase:Q.enum(["turn","searching","inspecting","target_hit","executing","completed"]),status:Q.enum(["ongoing","hit","done"]),message:Q.string(),turn:Q.number().optional(),tool_name:Q.string().optional(),target:Q.string().optional()}),qq=V.extend({type:Q.literal("tool_detail"),tool_name:Q.string(),detail:Q.string()}),Gq=V.extend({type:Q.literal("task_update"),tasks:Q.array(x)}),Qq=V.extend({type:Q.literal("token_usage"),input_tokens:Q.number(),output_tokens:Q.number(),total_tokens:Q.number(),max_context_tokens:Q.number()}),Xq=V.extend({type:Q.literal("compacting"),state:Q.enum(["started","completed"])}),Yq=V.extend({type:Q.literal("turn_limit"),turns_count:Q.number(),action:Q.literal("continue")}),Zq=V.extend({type:Q.literal("output"),content:Q.string(),exit_code:Q.number()}),$q=V.extend({type:Q.literal("error"),message:Q.string()}),Nq=Q.discriminatedUnion("type",[i,n,r,s,o,a,t,e,qq,Gq,Qq,Xq,Yq,Zq,$q]);function N(G,X){return{event_version:L,type:G,...X}}var Kq=b.enum(["text","jsonl"]),Aq=b.object({headless:b.boolean().optional(),message:b.string().optional(),_:b.array(b.union([b.string(),b.number()])).optional(),model:b.string().optional(),systemPrompt:b.string().optional(),appendSystemPrompt:b.string().optional(),maxTurns:b.number().int().refine((G)=>G===-1||G>0,{message:"must be -1 or a positive integer"}).optional(),permissionMode:b.nativeEnum(H).optional(),mcpConfig:b.array(b.string()).optional(),strictMcpConfig:b.boolean().optional(),sessionId:b.string().optional(),allowedTools:b.array(b.string()).optional(),disallowedTools:b.array(b.string()).optional(),continue:b.boolean().optional(),resume:b.union([b.string(),b.boolean()]).optional(),outputFormat:Kq.optional()});class d{openedThinking=!1;wroteAssistantContent=!1;markAssistantContent(){this.wroteAssistantContent=!0}setThinkingOpened(G){this.openedThinking=G}hasOpenThinking(){return this.openedThinking}completeStream(){let G={openedThinking:this.openedThinking,wroteAssistantContent:this.wroteAssistantContent};return this.openedThinking=!1,this.wroteAssistantContent=!1,G}}function Rq(G){return G.issues.map((X)=>`${X.path.join(".")||"options"}: ${X.message}`).join("; ")}function Vq(G){let X=Aq.safeParse(G);if(!X.success)throw Error(`Invalid headless options: ${Rq(X.error)}`);return X.data}function _q(G){return G.command("* [message]","Run full agent loop without Ink UI and print events to the terminal",(X)=>X.positional("message",{describe:"Message to process",type:"string"}).option("headless",{type:"boolean",describe:"Run full agent loop without Ink UI and print events to the terminal"}).option("model",{describe:"Model ID for this run",type:"string"}).option("system-prompt",{describe:"Replace the default system prompt",type:"string"}).option("append-system-prompt",{describe:"Append a system prompt to the default system prompt",type:"string"}).option("max-turns",{alias:["maxTurns"],describe:"Maximum conversation turns (-1: unlimited, N>0: limit to N turns)",type:"number"}).option("output-format",{alias:["outputFormat"],choices:["text","jsonl"],describe:"Headless output format",type:"string"}),async(X)=>{if(!X.headless)return;let Y=await Bq(X);process.exit(Y)})}function _(G,X=""){G.write(`${X}
1
+ import{p as z,q as g,r as v,s as p}from"./chunk-5xc0kzdt.js";import{t as E}from"./chunk-9mrna4y3.js";import{v as S,w as h,x as c}from"./chunk-jz59sjzb.js";import{G as w,I as F,J as y,L as x,M as C}from"./chunk-jvbx3h56.js";import"./chunk-4jh0h16z.js";import"./chunk-esnkk33h.js";import"./chunk-kd1t45br.js";import"./chunk-8jwqy5d0.js";import"./chunk-76emdpxa.js";import"./chunk-y5g06jmk.js";import{Sa as O}from"./chunk-ehcjnwnr.js";import"./chunk-yddnm9n2.js";import"./chunk-094ekgv6.js";import"./chunk-5mtjqqav.js";import{wb as H,xb as T}from"./chunk-7ycmx7c2.js";import"./chunk-set7v1rf.js";import"./chunk-j2ag7hh6.js";import bq from"yargs";import{hideBin as Uq}from"yargs/helpers";import{z as b}from"zod";import{z as Q}from"zod";var L=1,V=Q.object({event_version:Q.literal(L)}),i=V.extend({type:Q.literal("content_delta"),delta:Q.string()}),n=V.extend({type:Q.literal("thinking_delta"),delta:Q.string()}),r=V.extend({type:Q.literal("thinking"),content:Q.string()}),s=V.extend({type:Q.literal("stream_end")}),o=V.extend({type:Q.literal("content"),content:Q.string()}),a=V.extend({type:Q.literal("tool_start"),tool_name:Q.string(),summary:Q.string(),target:Q.string().optional(),tool_kind:Q.enum(["readonly","write","execute"]).optional()}),t=V.extend({type:Q.literal("tool_result"),tool_name:Q.string(),summary:Q.string(),target:Q.string().optional(),tool_kind:Q.enum(["readonly","write","execute"]).optional()}),e=V.extend({type:Q.literal("phase"),phase:Q.enum(["turn","searching","inspecting","target_hit","executing","completed"]),status:Q.enum(["ongoing","hit","done"]),message:Q.string(),turn:Q.number().optional(),tool_name:Q.string().optional(),target:Q.string().optional()}),qq=V.extend({type:Q.literal("tool_detail"),tool_name:Q.string(),detail:Q.string()}),Gq=V.extend({type:Q.literal("task_update"),tasks:Q.array(x)}),Qq=V.extend({type:Q.literal("token_usage"),input_tokens:Q.number(),output_tokens:Q.number(),total_tokens:Q.number(),max_context_tokens:Q.number()}),Xq=V.extend({type:Q.literal("compacting"),state:Q.enum(["started","completed"])}),Yq=V.extend({type:Q.literal("turn_limit"),turns_count:Q.number(),action:Q.literal("continue")}),Zq=V.extend({type:Q.literal("output"),content:Q.string(),exit_code:Q.number()}),$q=V.extend({type:Q.literal("error"),message:Q.string()}),Nq=Q.discriminatedUnion("type",[i,n,r,s,o,a,t,e,qq,Gq,Qq,Xq,Yq,Zq,$q]);function N(G,X){return{event_version:L,type:G,...X}}var Kq=b.enum(["text","jsonl"]),Aq=b.object({headless:b.boolean().optional(),message:b.string().optional(),_:b.array(b.union([b.string(),b.number()])).optional(),model:b.string().optional(),systemPrompt:b.string().optional(),appendSystemPrompt:b.string().optional(),maxTurns:b.number().int().refine((G)=>G===-1||G>0,{message:"must be -1 or a positive integer"}).optional(),permissionMode:b.nativeEnum(H).optional(),mcpConfig:b.array(b.string()).optional(),strictMcpConfig:b.boolean().optional(),sessionId:b.string().optional(),allowedTools:b.array(b.string()).optional(),disallowedTools:b.array(b.string()).optional(),continue:b.boolean().optional(),resume:b.union([b.string(),b.boolean()]).optional(),outputFormat:Kq.optional()});class d{openedThinking=!1;wroteAssistantContent=!1;markAssistantContent(){this.wroteAssistantContent=!0}setThinkingOpened(G){this.openedThinking=G}hasOpenThinking(){return this.openedThinking}completeStream(){let G={openedThinking:this.openedThinking,wroteAssistantContent:this.wroteAssistantContent};return this.openedThinking=!1,this.wroteAssistantContent=!1,G}}function Rq(G){return G.issues.map((X)=>`${X.path.join(".")||"options"}: ${X.message}`).join("; ")}function Vq(G){let X=Aq.safeParse(G);if(!X.success)throw Error(`Invalid headless options: ${Rq(X.error)}`);return X.data}function _q(G){return G.command("* [message]","Run full agent loop without Ink UI and print events to the terminal",(X)=>X.positional("message",{describe:"Message to process",type:"string"}).option("headless",{type:"boolean",describe:"Run full agent loop without Ink UI and print events to the terminal"}).option("model",{describe:"Model ID for this run",type:"string"}).option("system-prompt",{describe:"Replace the default system prompt",type:"string"}).option("append-system-prompt",{describe:"Append a system prompt to the default system prompt",type:"string"}).option("max-turns",{alias:["maxTurns"],describe:"Maximum conversation turns (-1: unlimited, N>0: limit to N turns)",type:"number"}).option("output-format",{alias:["outputFormat"],choices:["text","jsonl"],describe:"Headless output format",type:"string"}),async(X)=>{if(!X.headless)return;let Y=await Bq(X);process.exit(Y)})}function _(G,X=""){G.write(`${X}
2
2
  `)}function Dq(G){return`[task] [${G.status}] ${G.subject}`}function Mq(){return{requestConfirmation:async(G)=>({approved:!0,reason:"headless-auto-approved",scope:"session"})}}function jq(G){if(!(G instanceof Error))return"Unknown error";let q=G.lastError??G;if(q.responseBody)try{let A=JSON.parse(q.responseBody)?.error?.message;if(A)return q.statusCode?`${A} (HTTP ${q.statusCode})`:A}catch{}let Z=G.message.match(/Last error:\s*(.+)$/);if(Z)return Z[1];return G.message}function fq(G){return G==="jsonl"?"jsonl":"text"}function W(G,X){let Y=(...q)=>{for(let Z of q){let U=X[Z];if(typeof U==="string"&&U.trim()!=="")return U}return};switch(G){case"Read":case"Edit":case"Write":case"UndoEdit":return Y("file_path");case"NotebookEdit":return Y("notebook_path");case"Grep":return Y("path","pattern");case"Glob":return Y("pattern");case"WebFetch":return Y("url");case"WebSearch":return Y("query");case"Bash":return Y("description","command");case"Task":return Y("description");case"LSP":return Y("filePath","operation");default:return}}function Pq(G,X,Y,q){let Z=new Set(["Glob","Grep","WebSearch","LS"]),U=new Set(["Read","WebFetch"]);if(new Set(["Edit","Write","NotebookEdit","Bash","LSP","UndoEdit"]).has(G)&&!q.targetLocked)return{phase:"target_hit",status:"hit",message:`Target locked: ${X}`,shouldLockTarget:!0};if(q.targetLocked)return{phase:"executing",status:"hit",message:Y?`Working within target: ${X}`:`Executing: ${X}`,shouldLockTarget:!1};if(Z.has(G))return{phase:"searching",status:"ongoing",message:`Still searching: ${X}`,shouldLockTarget:!1};if(U.has(G))return{phase:"inspecting",status:"ongoing",message:`Inspecting candidate: ${X}`,shouldLockTarget:!1};return{phase:"executing",status:q.targetLocked?"hit":"ongoing",message:`Executing: ${X}`,shouldLockTarget:!1}}function k(G,X){let Y=(q,Z)=>{G.stdout.write(`${JSON.stringify(N(q,Z))}
3
3
  `)};return{contentDelta(q){if(X==="jsonl"){Y("content_delta",{delta:q});return}G.stdout.write(q)},thinkingDelta(q,Z){if(X==="jsonl")return Y("thinking_delta",{delta:q}),Z;if(!Z)G.stderr.write("[thinking] ");return G.stderr.write(q),!0},thinking(q){if(X==="jsonl"){Y("thinking",{content:q});return}_(G.stderr,`[thinking] ${q}`)},streamEnd(q,Z){if(X==="jsonl"){Y("stream_end",{});return}if(Z)G.stderr.write(`
4
4
  `);if(q)G.stdout.write(`
@@ -0,0 +1,24 @@
1
+ import{xb as Y}from"./chunk-7ycmx7c2.js";import{Bb as M}from"./chunk-set7v1rf.js";var D={currentModelId:"",models:[],temperature:0,maxContextTokens:128000,maxOutputTokens:void 0,stream:!0,topP:0.9,topK:50,timeout:180000,theme:"dracula",uiTheme:"system",language:"zh-CN",fontSize:14,autoSaveSessions:!0,notifyBuild:!0,notifyErrors:!1,notifySounds:!1,privacyTelemetry:!1,privacyCrash:!0,debug:!1,mcpEnabled:!1,mcpServers:{},permissions:{allow:["Bash(pwd)","Bash(which *)","Bash(whoami)","Bash(hostname)","Bash(uname *)","Bash(date)","Bash(echo *)","Bash(ls *)","Bash(tree *)","Bash(git status)","Bash(git status -*)","Bash(git log *)","Bash(git diff *)","Bash(git show *)","Bash(git branch -* *)","Bash(git branch)","Bash(git tag -l *)","Bash(git tag --list *)","Bash(git stash list *)","Bash(git stash show *)","Bash(git rev-parse *)","Bash(git describe *)","Bash(git blame *)","Bash(git ls-files *)","Bash(git config --get *)","Bash(git config --list *)","Bash(git shortlog *)","Bash(git merge-base *)","Bash(git cat-file *)","Bash(git for-each-ref *)","Bash(git grep *)","Bash(git worktree list *)","Bash(git reflog show *)","Bash(git reflog)","Bash(git rev-list *)","Bash(git ls-remote *)","Bash(git remote -v)","Bash(git remote --verbose)","Bash(git remote)","Bash(gh pr view *)","Bash(gh pr list *)","Bash(gh pr diff *)","Bash(gh pr checks *)","Bash(gh pr status *)","Bash(gh issue view *)","Bash(gh issue list *)","Bash(gh issue status *)","Bash(gh run list *)","Bash(gh run view *)","Bash(gh repo view *)","Bash(gh auth status)","Bash(npm list *)","Bash(bun pm ls *)","Bash(npm view *)","Bash(npm outdated *)","Bash(pnpm list *)","Bash(yarn list *)","Bash(pip list *)","Bash(pip show *)"],ask:["Bash(curl *)","Bash(wget *)","Bash(aria2c *)","Bash(axel *)","Bash(rm -rf *)","Bash(rm -r *)","Bash(rm --recursive *)","Bash(nc *)","Bash(netcat *)","Bash(telnet *)","Bash(ncat *)"],deny:["Read(./.env)","Read(./.env.*)","Bash(rm -rf /)","Bash(rm -rf /*)","Bash(sudo *)","Bash(chmod 777 *)","Bash(bash *)","Bash(sh *)","Bash(zsh *)","Bash(fish *)","Bash(dash *)","Bash(eval *)","Bash(source *)","Bash(mkfs *)","Bash(fdisk *)","Bash(dd *)","Bash(format *)","Bash(parted *)","Bash(open http*)","Bash(open https*)","Bash(xdg-open http*)","Bash(xdg-open https*)"]},permissionMode:"default",hooks:{enabled:!1,defaultTimeout:60,timeoutBehavior:"ignore",failureBehavior:"ignore",maxConcurrentHooks:5,PreToolUse:[],PostToolUse:[],PostToolUseFailure:[],PermissionRequest:[],UserPromptSubmit:[],SessionStart:[],SessionEnd:[],Stop:[],SubagentStop:[],Notification:[],Compaction:[]},env:{},disableAllHooks:!1,maxTurns:-1};import{promises as N}from"fs";import{merge as b}from"lodash-es";import j from"os";import R from"path";class V{static instance=null;constructor(){}static getInstance(){if(!V.instance)V.instance=new V;return V.instance}static resetInstance(){V.instance=null}async initialize(){try{let H=await this.loadConfigFiles(),q=await this.loadSettingsFiles(),z={...D,...H,...q};if(this.resolveEnvInterpolation(z),z.debug)console.log("[ConfigManager] Configuration loaded successfully");return z}catch(H){return console.error("[ConfigManager] Failed to initialize:",H),D}}async loadConfigFiles(){let H=R.join(j.homedir(),".blade","config.json"),q=R.join(Y(),".blade","config.json"),z={},J=await this.loadJsonFile(H);if(J)z={...z,...J};let K=await this.loadJsonFile(q);if(K){let Q={...z.mcpServers||{},...K.mcpServers||{}};if(z={...z,...K},Object.keys(Q).length>0)z.mcpServers=Q}return z}async loadSettingsFiles(){let H=R.join(j.homedir(),".blade","settings.json"),q=R.join(Y(),".blade","settings.json"),z=R.join(Y(),".blade","settings.local.json"),J={},K=await this.loadJsonFile(H);if(K)J=this.mergeSettings(J,K);let Q=await this.loadJsonFile(q);if(Q)J=this.mergeSettings(J,Q);let W=await this.loadJsonFile(z);if(W)J=this.mergeSettings(J,W);return J}mergeSettings(H,q){let z=JSON.parse(JSON.stringify(H));if(q.permissions){if(!z.permissions)z.permissions={allow:[],ask:[],deny:[]};if(q.permissions.allow){let J=[...z.permissions.allow||[],...q.permissions.allow];z.permissions.allow=Array.from(new Set(J))}if(q.permissions.ask){let J=[...z.permissions.ask||[],...q.permissions.ask];z.permissions.ask=Array.from(new Set(J))}if(q.permissions.deny){let J=[...z.permissions.deny||[],...q.permissions.deny];z.permissions.deny=Array.from(new Set(J))}}if(q.hooks)z.hooks=b({},z.hooks,q.hooks);if(q.env)z.env=b({},z.env,q.env);if(q.mcpServers)z.mcpServers={...z.mcpServers||{},...q.mcpServers};if(q.disableAllHooks!==void 0)z.disableAllHooks=q.disableAllHooks;if(q.permissionMode!==void 0)z.permissionMode=q.permissionMode;if(q.maxTurns!==void 0)z.maxTurns=q.maxTurns;return z}resolveEnvInterpolation(H){let q=/\$\{?([A-Z_][A-Z0-9_]*)(:-([^}]+))?\}?/g,z=(J)=>{if(typeof J==="string")return J.replace(q,(K,Q,W,X)=>{return process.env[Q]||X||K});return J};for(let[J,K]of Object.entries(H))if(typeof K==="string")H[J]=z(K)}async loadJsonFile(H){try{if(await this.fileExists(H)){let q=await N.readFile(H,"utf-8");return JSON.parse(q)}}catch(q){console.warn(`[ConfigManager] Failed to load ${H}:`,q)}return null}async fileExists(H){try{return await N.access(H),!0}catch{return!1}}validateConfig(H){let q=[];if(!H.models||H.models.length===0)q.push("没有可用的模型配置");if(H.models&&H.models.length>0){if(!H.currentModelId)q.push("未设置当前模型 ID");else if(!H.models.find((J)=>J.id===H.currentModelId))q.push("当前模型 ID 无效")}if(q.length>0)throw Error(`配置验证失败:
2
+ ${q.map((z)=>` - ${z}`).join(`
3
+ `)}
4
+
5
+ `+`请通过以下方式之一提供配置:
6
+ `+` 1. 首次启动: 运行 blade,系统会自动引导配置
7
+ `+` 2. 添加模型: blade 后输入 /model add
8
+ `+` 3. 初始化向导: 输入 /init
9
+
10
+ `+`配置文件示例 (~/.blade/config.json):
11
+ `+`{
12
+ "currentModelId": "model-id-123",
13
+ "models": [
14
+ {
15
+ "id": "model-id-123",
16
+ `+` "name": "默认模型",
17
+ `+` "provider": "openai-compatible",
18
+ "apiKey": "your-api-key",
19
+ "baseUrl": "https://api.example.com/v1",
20
+ "model": "model-name"
21
+ }
22
+ ]
23
+ }
24
+ `)}}function w(H,q={}){let z={...H};if(q.debug!==void 0)z.debug=q.debug===""?!0:q.debug;if(q.model){if(!H.models.some((K)=>K.id===q.model))throw Error(`模型配置未找到: ${q.model}`);z.currentModelId=q.model}if(q.yolo===!0)z.permissionMode="yolo";else if(q.permissionMode!==void 0)z.permissionMode=q.permissionMode;if(q.maxTurns!==void 0)z.maxTurns=q.maxTurns;return z.systemPrompt=q.systemPrompt,z.appendSystemPrompt=q.appendSystemPrompt,z.model=q.model,z.resumeSessionId=q.sessionId,z.forkSession=q.forkSession,z.allowedTools=q.allowedTools,z.disallowedTools=q.disallowedTools,z.mcpConfigPaths=q.mcpConfig,z.strictMcpConfig=q.strictMcpConfig,z.addDirs=q.addDir,z.outputFormat=q.outputFormat,z.inputFormat=q.inputFormat,z.print=q.print,z.includePartialMessages=q.includePartialMessages,z.replayUserMessages=q.replayUserMessages,z.agentsConfig=q.agents,z.settingSources=q.settingSources,z}import{Mutex as U}from"async-mutex";import{merge as T}from"lodash-es";import{promises as G}from"node:fs";import _ from"node:os";import $ from"node:path";import E from"write-file-atomic";var I=M("Service"),B={models:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},currentModelId:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},temperature:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},maxContextTokens:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},maxOutputTokens:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},timeout:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},theme:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},uiTheme:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},language:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},debug:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},fontSize:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},autoSaveSessions:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},notifyBuild:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},notifyErrors:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},notifySounds:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},privacyTelemetry:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},privacyCrash:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},permissionMode:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},permissions:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!0},hooks:{target:"settings",defaultScope:"local",mergeStrategy:"deep-merge",persistable:!0},env:{target:"settings",defaultScope:"local",mergeStrategy:"deep-merge",persistable:!0},disableAllHooks:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!0},maxTurns:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!0},mcpServers:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},stream:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!1},topP:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!1},topK:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!1},mcpEnabled:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!1},systemPrompt:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},appendSystemPrompt:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},initialMessage:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},resumeSessionId:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},forkSession:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},allowedTools:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},disallowedTools:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},mcpConfigPaths:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},strictMcpConfig:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},addDirs:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},outputFormat:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},inputFormat:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},print:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},includePartialMessages:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},replayUserMessages:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},agentsConfig:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},settingSources:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1}},t=new Set(Object.entries(B).filter(([H,q])=>q.persistable).map(([H])=>H)),i=new Set(Object.entries(B).filter(([H,q])=>!q.persistable).map(([H])=>H));class Z{static instance=null;pendingUpdates=new Map;timers=new Map;fileLocks=new Map;lastSaveError=null;debounceDelay=300;constructor(){}static getInstance(){if(!Z.instance)Z.instance=new Z;return Z.instance}static resetInstance(){if(Z.instance)for(let H of Z.instance.timers.values())clearTimeout(H);Z.instance=null}async save(H,q={}){this.validatePersistableFields(H);let z=this.groupUpdatesByTarget(H,q.scope);if(q.immediate)await Promise.all(Array.from(z.entries()).map(([J,K])=>this.flushTarget(J,K)));else for(let[J,K]of z)this.scheduleSave(J,K)}async flush(){for(let q of this.timers.values())clearTimeout(q);this.timers.clear();let H=Array.from(this.pendingUpdates.entries()).map(([q,z])=>this.flushTarget(q,z));this.pendingUpdates.clear(),await Promise.all(H)}getLastSaveError(){return this.lastSaveError}clearLastSaveError(){this.lastSaveError=null}async appendPermissionRule(H,q={}){let z=q.scope??"local",J=this.resolveFilePath("settings",z);await this.flushTargetWithModifier(J,(K)=>{let Q=K.permissions??{allow:[],ask:[],deny:[]},W={allow:this.dedupeArray([...Q.allow||[],H]),ask:Q.ask||[],deny:Q.deny||[]};return{...K,permissions:W}})}async appendLocalPermissionRule(H,q={}){await this.appendPermissionRule(H,{...q,scope:"local"})}validatePersistableFields(H){for(let q of Object.keys(H)){let z=B[q];if(!z)throw Error(`Unknown config field: ${q}`);if(!z.persistable)throw Error(`Field "${q}" is non-persistable and cannot be saved to config files. Non-persistable fields are runtime-only and only valid for the current session.`)}}groupUpdatesByTarget(H,q){let z=new Map;for(let[J,K]of Object.entries(H)){let Q=B[J];if(!Q)continue;let W=q??Q.defaultScope,X=this.resolveFilePath(Q.target,W);if(!z.has(X))z.set(X,{});z.get(X)[J]=K}return z}resolveFilePath(H,q){if(H==="config")return q==="global"?$.join(_.homedir(),".blade","config.json"):$.join(Y(),".blade","config.json");switch(q){case"local":return $.join(Y(),".blade","settings.local.json");case"project":return $.join(Y(),".blade","settings.json");case"global":return $.join(_.homedir(),".blade","settings.json");default:return $.join(Y(),".blade","settings.local.json")}}scheduleSave(H,q){let z=this.pendingUpdates.get(H)??{},J=this.mergePendingUpdates(z,q);this.pendingUpdates.set(H,J);let K=this.timers.get(H);if(K)clearTimeout(K);let Q=setTimeout(async()=>{let W=this.pendingUpdates.get(H);if(W){this.pendingUpdates.delete(H),this.timers.delete(H);try{await this.flushTarget(H,W),this.lastSaveError=null}catch(X){let A=X instanceof Error?X:Error(String(X));this.lastSaveError=A,I.error(`Failed to save config to ${H}:`,A.message),I.error("Stack trace:",A.stack)}}},this.debounceDelay);this.timers.set(H,Q)}mergePendingUpdates(H,q){let z={...H};for(let[J,K]of Object.entries(q)){let Q=B[J];if(!Q){z[J]=K;continue}switch(Q.mergeStrategy){case"replace":z[J]=K;break;case"append-dedupe":this.applyAppendDedupe(z,J,K);break;case"deep-merge":this.applyDeepMerge(z,J,K);break}}return z}async flushTarget(H,q){let z=this.fileLocks.get(H);if(!z)z=new U,this.fileLocks.set(H,z);await z.runExclusive(async()=>{await this.performWrite(H,q)})}async flushTargetWithModifier(H,q){let z=this.fileLocks.get(H);if(!z)z=new U,this.fileLocks.set(H,z);await z.runExclusive(async()=>{await G.mkdir($.dirname(H),{recursive:!0,mode:493});let J={};try{let Q=await G.readFile(H,"utf-8");J=JSON.parse(Q)}catch{J={}}let K=q(J);await this.atomicWrite(H,K)})}async performWrite(H,q){await G.mkdir($.dirname(H),{recursive:!0,mode:493});let z={};try{let K=await G.readFile(H,"utf-8");z=JSON.parse(K)}catch{z={}}let J={...z};for(let[K,Q]of Object.entries(q)){let W=B[K];if(!W){J[K]=Q;continue}switch(W.mergeStrategy){case"replace":J[K]=Q;break;case"append-dedupe":this.applyAppendDedupe(J,K,Q);break;case"deep-merge":this.applyDeepMerge(J,K,Q);break}}await this.atomicWrite(H,J)}applyAppendDedupe(H,q,z){if(q==="permissions"&&typeof z==="object"&&z!==null){let J=H[q]??{allow:[],ask:[],deny:[]},K=z;H[q]={allow:this.dedupeArray([...J.allow||[],...K.allow||[]]),ask:this.dedupeArray([...J.ask||[],...K.ask||[]]),deny:this.dedupeArray([...J.deny||[],...K.deny||[]])}}else if(Array.isArray(z)){let J=Array.isArray(H[q])?H[q]:[];H[q]=this.dedupeArray([...J,...z])}else H[q]=z}applyDeepMerge(H,q,z){if(typeof z==="object"&&z!==null&&!Array.isArray(z)){let J=typeof H[q]==="object"&&H[q]!==null?H[q]:{};H[q]=T({},J,z)}else H[q]=z}dedupeArray(H){return Array.from(new Set(H))}async atomicWrite(H,q){await E(H,JSON.stringify(q,null,2),{mode:384,encoding:"utf-8"})}}function L(){return Z.getInstance()}export{D as Ha,V as Ia,w as Ja,L as Ka};
@@ -1,4 +1,4 @@
1
- import{a as Q,b as R,c as T,d as W}from"./chunk-akr185xe.js";import"./chunk-vwn39c84.js";import"./chunk-j79jvd54.js";import"./chunk-zxf08z5f.js";import"./chunk-esnkk33h.js";import{ba as M}from"./chunk-3xqfqpa7.js";import"./chunk-2tpgtpcp.js";import{Aa as J}from"./chunk-m99qhdkf.js";import"./chunk-e2vtbvda.js";import"./chunk-j25kww7j.js";import"./chunk-yddnm9n2.js";import"./chunk-ena4sxgr.js";import"./chunk-5mtjqqav.js";import"./chunk-7ycmx7c2.js";import"./chunk-set7v1rf.js";import"./chunk-j2ag7hh6.js";import b from"chalk";import H from"open";var $=`
1
+ import{a as Q,b as R,c as T,d as W}from"./chunk-tph4ngbj.js";import"./chunk-vwn39c84.js";import"./chunk-jvbx3h56.js";import"./chunk-4jh0h16z.js";import"./chunk-esnkk33h.js";import{ba as M}from"./chunk-kd1t45br.js";import"./chunk-8jwqy5d0.js";import{Aa as J}from"./chunk-76emdpxa.js";import"./chunk-y5g06jmk.js";import"./chunk-ehcjnwnr.js";import"./chunk-yddnm9n2.js";import"./chunk-094ekgv6.js";import"./chunk-5mtjqqav.js";import"./chunk-7ycmx7c2.js";import"./chunk-set7v1rf.js";import"./chunk-j2ag7hh6.js";import b from"chalk";import H from"open";var $=`
2
2
  ____ _ _
3
3
  | __ )| | __ _ __| | ___
4
4
  | _ \\| |/ _\` |/ _\` |/ _ \\
@@ -1 +1 @@
1
- import{v as a,w as b,x as c}from"./chunk-1en8fh5f.js";import"./chunk-m99qhdkf.js";import"./chunk-e2vtbvda.js";import"./chunk-7ycmx7c2.js";import"./chunk-set7v1rf.js";import"./chunk-j2ag7hh6.js";export{a as validatePermissions,c as validateOutput,b as loadConfiguration};
1
+ import{v as a,w as b,x as c}from"./chunk-jz59sjzb.js";import"./chunk-76emdpxa.js";import"./chunk-y5g06jmk.js";import"./chunk-7ycmx7c2.js";import"./chunk-set7v1rf.js";import"./chunk-j2ag7hh6.js";export{a as validatePermissions,c as validateOutput,b as loadConfiguration};
@@ -1,4 +1,4 @@
1
- import{_ as Q}from"./vendor-markdown-DIcugY1e.js";import{r as l,j as e}from"./vendor-react-Dm1xU4bP.js";import{c as j,u as le,b as fe,B as ue}from"./index-DehGtSvJ.js";import{i as xe,L as Y,j as Z,k as M}from"./vendor-radix-CKNFO4jS.js";import{u as me}from"./SettingsStore-E-aIqvyl.js";import{X as pe,i as J,l as H,g as ee,n as be,o as ge}from"./vendor-icons-DlzC8I7m.js";import"./vendor-monaco-w6PwaWGP.js";const he=xe,te=l.forwardRef(({className:t,...a},r)=>e.jsx(Y,{ref:r,className:j("inline-flex h-10 items-center justify-center rounded-md bg-muted p-1 text-muted-foreground",t),...a}));te.displayName=Y.displayName;const S=l.forwardRef(({className:t,...a},r)=>e.jsx(Z,{ref:r,className:j("inline-flex items-center justify-center whitespace-nowrap rounded-sm px-3 py-1.5 text-sm font-medium ring-offset-background transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-background data-[state=active]:text-foreground data-[state=active]:shadow-sm",t),...a}));S.displayName=Z.displayName;const L=l.forwardRef(({className:t,...a},r)=>e.jsx(M,{ref:r,className:j("mt-2 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",t),...a}));L.displayName=M.displayName;const ye={"ayu-dark":{background:{primary:"#0f1419",secondary:"#14191f"},text:{primary:"#e6e1cf",secondary:"#bae67e",muted:"#5c6773"},border:{light:"#2d323b"},syntax:{comment:"#5c6773",string:"#bae67e",number:"#ffcc66",keyword:"#ff8f40",function:"#73d0ff",variable:"#e6e1cf",operator:"#f29e74",type:"#73d0ff",tag:"#ff8f40",attr:"#ffd580",default:"#e6e1cf"}},dracula:{background:{primary:"#282a36",secondary:"#44475a"},text:{primary:"#f8f8f2",secondary:"#f1fa8c",muted:"#6272a4"},border:{light:"#44475a"},syntax:{comment:"#6272a4",string:"#f1fa8c",number:"#bd93f9",keyword:"#ff79c6",function:"#50fa7b",variable:"#f8f8f2",operator:"#ff79c6",type:"#8be9fd",tag:"#ff79c6",attr:"#50fa7b",default:"#f8f8f2"}},monokai:{background:{primary:"#272822",secondary:"#3e3d32"},text:{primary:"#f8f8f2",secondary:"#e6db74",muted:"#75715e"},border:{light:"#3e3d32"},syntax:{comment:"#75715e",string:"#e6db74",number:"#ae81ff",keyword:"#f92672",function:"#a6e22e",variable:"#f8f8f2",operator:"#f92672",type:"#66d9ef",tag:"#f92672",attr:"#a6e22e",default:"#f8f8f2"}},nord:{background:{primary:"#2e3440",secondary:"#3b4252"},text:{primary:"#eceff4",secondary:"#d8dee9",muted:"#4c566a"},border:{light:"#434c5e"},syntax:{comment:"#616e88",string:"#a3be8c",number:"#b48ead",keyword:"#81a1c1",function:"#88c0d0",variable:"#d8dee9",operator:"#81a1c1",type:"#8fbcbb",tag:"#81a1c1",attr:"#8fbcbb",default:"#eceff4"}},"solarized-light":{background:{primary:"#fdf6e3",secondary:"#eee8d5"},text:{primary:"#586e75",secondary:"#657b83",muted:"#93a1a1"},border:{light:"#eee8d5"},syntax:{comment:"#93a1a1",string:"#2aa198",number:"#d33682",keyword:"#859900",function:"#268bd2",variable:"#657b83",operator:"#859900",type:"#b58900",tag:"#268bd2",attr:"#93a1a1",default:"#657b83"}},"solarized-dark":{background:{primary:"#002b36",secondary:"#073642"},text:{primary:"#839496",secondary:"#93a1a1",muted:"#586e75"},border:{light:"#073642"},syntax:{comment:"#586e75",string:"#2aa198",number:"#d33682",keyword:"#859900",function:"#268bd2",variable:"#839496",operator:"#859900",type:"#b58900",tag:"#268bd2",attr:"#93a1a1",default:"#839496"}},"tokyo-night":{background:{primary:"#1a1b26",secondary:"#292e42"},text:{primary:"#a9b1d6",secondary:"#c0caf5",muted:"#565f89"},border:{light:"#292e42"},syntax:{comment:"#565f89",string:"#9ece6a",number:"#ff9e64",keyword:"#bb9af7",function:"#7aa2f7",variable:"#c0caf5",operator:"#89ddff",type:"#7dcfff",tag:"#f7768e",attr:"#7aa2f7",default:"#a9b1d6"}},github:{background:{primary:"#ffffff",secondary:"#f6f8fa"},text:{primary:"#24292f",secondary:"#57606a",muted:"#6e7781"},border:{light:"#d0d7de"},syntax:{comment:"#6e7781",string:"#0a3069",number:"#0550ae",keyword:"#cf222e",function:"#8250df",variable:"#24292f",operator:"#cf222e",type:"#0550ae",tag:"#116329",attr:"#0550ae",default:"#24292f"}},gruvbox:{background:{primary:"#282828",secondary:"#3c3836"},text:{primary:"#ebdbb2",secondary:"#d5c4a1",muted:"#928374"},border:{light:"#3c3836"},syntax:{comment:"#928374",string:"#b8bb26",number:"#d3869b",keyword:"#fb4934",function:"#b8bb26",variable:"#ebdbb2",operator:"#fe8019",type:"#fabd2f",tag:"#fb4934",attr:"#fabd2f",default:"#ebdbb2"}},"one-dark":{background:{primary:"#282c34",secondary:"#21252b"},text:{primary:"#abb2bf",secondary:"#e5c07b",muted:"#5c6370"},border:{light:"#3e4451"},syntax:{comment:"#5c6370",string:"#98c379",number:"#d19a66",keyword:"#c678dd",function:"#61afef",variable:"#e06c75",operator:"#56b6c2",type:"#e5c07b",tag:"#e06c75",attr:"#d19a66",default:"#abb2bf"}},catppuccin:{background:{primary:"#1e1e2e",secondary:"#313244"},text:{primary:"#cdd6f4",secondary:"#f5e0dc",muted:"#6c7086"},border:{light:"#313244"},syntax:{comment:"#6c7086",string:"#a6e3a1",number:"#fab387",keyword:"#cba6f7",function:"#89b4fa",variable:"#f5e0dc",operator:"#89dceb",type:"#f9e2af",tag:"#f38ba8",attr:"#f9e2af",default:"#cdd6f4"}},"rose-pine":{background:{primary:"#191724",secondary:"#1f1d2e"},text:{primary:"#e0def4",secondary:"#908caa",muted:"#6e6a86"},border:{light:"#26233a"},syntax:{comment:"#6e6a86",string:"#f6c177",number:"#ebbcba",keyword:"#c4a7e7",function:"#9ccfd8",variable:"#e0def4",operator:"#31748f",type:"#eb6f92",tag:"#eb6f92",attr:"#c4a7e7",default:"#e0def4"}},kanagawa:{background:{primary:"#1f1f28",secondary:"#2a2a37"},text:{primary:"#dcd7ba",secondary:"#c8c093",muted:"#727169"},border:{light:"#2a2a37"},syntax:{comment:"#727169",string:"#98bb6c",number:"#d27e99",keyword:"#957fb8",function:"#7e9cd8",variable:"#dcd7ba",operator:"#c0a36e",type:"#7aa89f",tag:"#e46876",attr:"#ffa066",default:"#dcd7ba"}}};function ke(t){const a=t.replace("#",""),r=parseInt(a.substring(0,2),16),s=parseInt(a.substring(2,4),16),o=parseInt(a.substring(4,6),16);return(.299*r+.587*s+.114*o)/255<.5}function ve(t){return{base:ke(t.background.primary)?"vs-dark":"vs",inherit:!0,rules:[{token:"",foreground:t.text.primary.replace("#",""),background:t.background.primary.replace("#","")},{token:"comment",foreground:t.syntax.comment.replace("#",""),fontStyle:"italic"},{token:"string",foreground:t.syntax.string.replace("#","")},{token:"number",foreground:t.syntax.number.replace("#","")},{token:"keyword",foreground:t.syntax.keyword.replace("#","")},{token:"type",foreground:t.syntax.type.replace("#","")},{token:"identifier",foreground:t.syntax.variable.replace("#","")},{token:"function",foreground:t.syntax.function.replace("#","")},{token:"variable",foreground:t.syntax.variable.replace("#","")},{token:"operator",foreground:t.syntax.operator.replace("#","")},{token:"delimiter",foreground:t.syntax.operator.replace("#","")},{token:"tag",foreground:t.syntax.tag.replace("#","")},{token:"attribute.name",foreground:t.syntax.attr.replace("#","")},{token:"attribute.value",foreground:t.syntax.string.replace("#","")}],colors:{"editor.background":t.background.primary,"editor.foreground":t.text.primary,"editor.lineHighlightBackground":t.background.secondary,"editor.selectionBackground":`${t.syntax.function}40`,"editorLineNumber.foreground":t.text.muted,"editorLineNumber.activeForeground":t.text.secondary,"editorCursor.foreground":t.text.primary,"editorIndentGuide.background":t.border.light,"editorWidget.background":t.background.secondary,"editorWidget.border":t.border.light,"scrollbarSlider.background":`${t.text.muted}40`,"scrollbarSlider.hoverBackground":`${t.text.muted}60`}}}const K=new Set;function U(t,a){const r=a.toLowerCase().replace(/\s+/g,"-"),s=ye[r];if(!s)return"vs-dark";if(!K.has(r)){const o=ve(s);t.editor.defineTheme(r,o),K.add(r)}return r}l.lazy(async()=>({default:(await Q(()=>import("./vendor-react-Dm1xU4bP.js").then(a=>a.k),[])).DiffEditor}));const Ee=l.lazy(async()=>({default:(await Q(()=>import("./vendor-react-Dm1xU4bP.js").then(a=>a.k),[])).Editor}));function Re(){const{toggleFilePreview:t}=le(),{messages:a,currentSessionId:r}=fe(),[s,o]=l.useState("diff"),[c,i]=l.useState([]),[d,u]=l.useState({}),[x,p]=l.useState(!1),[g,b]=l.useState(null),[F,k]=l.useState({}),[w,T]=l.useState({}),[h,P]=l.useState(null),[re,A]=l.useState(""),[D,z]=l.useState(!1),[_,$]=l.useState(null),[W,R]=l.useState(!1),I=async(n="")=>{try{const f=n?`/suggestions/files/tree?path=${encodeURIComponent(n)}`:"/suggestions/files/tree",m=await fetch(f);if(!m.ok)throw new Error("Failed to load tree");return(await m.json()).map(B=>({...B,children:B.type==="dir"?[]:void 0}))}catch{return[]}};l.useEffect(()=>{let n=!0;return(async()=>{p(!0),b(null);try{const m=await I();n&&i(m)}catch(m){n&&b(m.message)}finally{n&&p(!1)}})(),()=>{n=!1}},[r]),l.useEffect(()=>{P(null),A(""),$(null),R(!1),k({}),u({})},[r]);const C=l.useMemo(()=>Ne(a),[a]),O=l.useMemo(()=>we(a),[a]),[ne,se]=l.useState({}),oe=n=>{se(f=>({...f,[n]:!f[n]}))},de=async n=>{P(n),A(""),z(!0),$(null),R(!1);try{const f=await fetch(`/suggestions/files/content?path=${encodeURIComponent(n)}`);if(!f.ok)throw new Error("Failed to load file");const m=await f.json();A(m.content||""),R(!!m.truncated)}catch(f){$(f.message)}finally{z(!1)}},ie=async n=>{const f=!F[n];if(k(m=>({...m,[n]:f})),f&&!d[n]){const m=await I(n);u(y=>({...y,[n]:m}))}},ce=n=>{T(f=>({...f,[n]:!f[n]}))};return e.jsxs("div",{className:"w-[55%] min-w-[420px] max-w-[860px] border-l border-[#E5E7EB] dark:border-zinc-800 bg-white dark:bg-[#09090b] flex flex-col h-full shadow-xl shrink-0",children:[e.jsxs("div",{className:"flex items-center justify-between px-4 h-12 border-b border-[#E5E7EB] dark:border-zinc-800 shrink-0",children:[e.jsx("span",{className:"font-normal text-[13px] text-[#6B7280] dark:text-zinc-400 font-mono",children:"Preview"}),e.jsx(ue,{variant:"ghost",size:"icon",onClick:t,className:"h-8 w-8 text-[#9CA3AF] hover:text-[#111827] hover:bg-[#E5E7EB]/60 dark:text-zinc-500 dark:hover:text-zinc-300 dark:hover:bg-zinc-800/50",children:e.jsx(pe,{className:"w-4 h-4"})})]}),e.jsxs(he,{value:s,onValueChange:n=>o(n),className:"flex flex-col flex-1 min-h-0",children:[e.jsx("div",{className:"px-4 py-3 border-b border-[#E5E7EB] dark:border-zinc-800",children:e.jsxs(te,{className:"bg-white dark:bg-[#111113] border border-[#E5E7EB] dark:border-[#27272a] h-9 p-1 rounded-md w-full justify-start",children:[e.jsx(S,{value:"diff",className:"text-[12px] font-mono px-3 text-[#6B7280] dark:text-[#a1a1aa] data-[state=active]:bg-[#E5E7EB] data-[state=active]:text-[#111827] dark:data-[state=active]:bg-[#27272a] dark:data-[state=active]:text-white",children:"Diff"}),e.jsx(S,{value:"files",className:"text-[12px] font-mono px-3 text-[#6B7280] dark:text-[#a1a1aa] data-[state=active]:bg-[#E5E7EB] data-[state=active]:text-[#111827] dark:data-[state=active]:bg-[#27272a] dark:data-[state=active]:text-white",children:"Files"}),e.jsx(S,{value:"logs",className:"text-[12px] font-mono px-3 text-[#6B7280] dark:text-[#a1a1aa] data-[state=active]:bg-[#E5E7EB] data-[state=active]:text-[#111827] dark:data-[state=active]:bg-[#27272a] dark:data-[state=active]:text-white",children:"Logs"})]})}),e.jsx(L,{value:"diff",className:"overflow-hidden flex-1 mt-0",children:e.jsx("div",{className:"overflow-y-auto px-4 py-4 space-y-3 h-full",children:C.length===0?e.jsx(N,{title:"No patch yet",subtitle:"Run a tool that changes files to see diffs here."}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"text-[12px] text-[#6B7280] dark:text-[#71717a] font-mono mb-2",children:[C.length," changed file",C.length>1?"s":""]}),C.map(n=>{var y;const f=((y=n.filePath)==null?void 0:y.split("/").pop())||"unknown",m=ne[n.filePath||""]!==!1;return e.jsxs("div",{className:"border border-[#E5E7EB] dark:border-[#27272a] rounded-lg overflow-hidden",children:[e.jsxs("button",{onClick:()=>oe(n.filePath||""),className:"w-full flex items-center gap-2 px-3 py-2 bg-[#F9FAFB] dark:bg-[#111113] hover:bg-[#F3F4F6] dark:hover:bg-[#18181b] transition-colors",children:[m?e.jsx(J,{className:"w-4 h-4 text-[#6B7280] dark:text-[#71717a]"}):e.jsx(H,{className:"w-4 h-4 text-[#6B7280] dark:text-[#71717a]"}),e.jsx(ee,{className:"w-4 h-4 text-[#6B7280] dark:text-[#71717a]"}),e.jsx("span",{className:"text-[13px] text-[#111827] dark:text-[#E5E5E5] font-mono flex-1 text-left truncate",children:f}),n.summary&&e.jsx("span",{className:"text-[11px] text-[#6B7280] dark:text-[#a1a1aa] font-mono",children:n.summary})]}),m&&e.jsxs("div",{className:"border-t border-[#E5E7EB] dark:border-[#27272a]",children:[e.jsx("div",{className:"px-3 py-1 text-[11px] text-[#9CA3AF] dark:text-[#52525b] font-mono truncate",children:n.filePath}),e.jsx(Be,{diff:n.diff})]})]},n.filePath)})]})})}),e.jsx(L,{value:"files",className:"overflow-hidden flex-1 mt-0",children:e.jsxs("div",{className:"px-4 py-4 h-full",children:[x&&e.jsx(N,{title:"Loading files…",subtitle:"Fetching workspace tree."}),!x&&g&&e.jsx(N,{title:"Failed to load files",subtitle:g}),!x&&!g&&c.length===0&&e.jsx(N,{title:"No files yet",subtitle:"Start a session to load the workspace tree."}),!x&&!g&&c.length>0&&e.jsxs("div",{className:"h-full grid grid-cols-[220px_1fr] gap-4 min-h-0",children:[e.jsx("div",{className:"border border-[#E5E7EB] dark:border-[#27272a] rounded-lg p-2 overflow-y-auto min-h-0",children:c.map(n=>e.jsx(ae,{node:n,depth:0,expandedDirs:F,childrenCache:d,toggleDir:ie,selectedPath:h,onSelectFile:de},n.path))}),e.jsxs("div",{className:"border border-[#E5E7EB] dark:border-[#27272a] rounded-lg overflow-hidden flex flex-col min-h-0",children:[e.jsxs("div",{className:"px-3 py-2 bg-[#F9FAFB] dark:bg-[#111113] border-b border-[#E5E7EB] dark:border-[#27272a] text-[12px] text-[#6B7280] dark:text-[#71717a] font-mono flex items-center justify-between",children:[e.jsx("span",{children:h||"Select a file to preview"}),h&&e.jsx("span",{className:"text-[11px] text-[#9CA3AF] dark:text-[#a1a1aa] font-mono",children:D?"Loading…":W?"Truncated":"Ready"})]}),W&&!D&&e.jsx("div",{className:"px-3 py-2 bg-[#FEF3C7] dark:bg-[#111113] border-b border-[#E5E7EB] dark:border-[#27272a] text-[11px] text-[#b45309] dark:text-[#facc15] font-mono",children:"Preview truncated to 200k characters."}),e.jsxs("div",{className:"flex-1 min-h-0",children:[!h&&e.jsx("div",{className:"h-full flex items-center justify-center text-[12px] text-[#6B7280] dark:text-[#71717a] font-mono",children:"Pick a file from the tree to preview."}),h&&_&&e.jsx("div",{className:"h-full flex items-center justify-center text-[12px] text-[#DC2626] dark:text-[#fca5a5] font-mono",children:_}),h&&!_&&e.jsx("div",{className:"h-full",children:D?e.jsx(q,{}):e.jsx(l.Suspense,{fallback:e.jsx(q,{}),children:e.jsx(Fe,{content:re,filename:h})})})]})]})]})]})}),e.jsx(L,{value:"logs",className:"overflow-hidden flex-1 mt-0",children:e.jsx("div",{className:"overflow-y-auto px-4 py-4 space-y-3 h-full",children:O.length===0?e.jsx(N,{title:"No logs yet",subtitle:"Tool runs will appear here."}):O.map(n=>{var V;const f=w[n.id],m=(n.content||"").split(`
1
+ import{_ as Q}from"./vendor-markdown-DIcugY1e.js";import{r as l,j as e}from"./vendor-react-Dm1xU4bP.js";import{c as j,u as le,b as fe,B as ue}from"./index-BeYCsOvo.js";import{i as xe,L as Y,j as Z,k as M}from"./vendor-radix-CfxBc_4-.js";import{u as me}from"./SettingsStore-Dmo3sZ_R.js";import{X as pe,i as J,l as H,g as ee,n as be,o as ge}from"./vendor-icons-DlzC8I7m.js";import"./vendor-monaco-w6PwaWGP.js";const he=xe,te=l.forwardRef(({className:t,...a},r)=>e.jsx(Y,{ref:r,className:j("inline-flex h-10 items-center justify-center rounded-md bg-muted p-1 text-muted-foreground",t),...a}));te.displayName=Y.displayName;const S=l.forwardRef(({className:t,...a},r)=>e.jsx(Z,{ref:r,className:j("inline-flex items-center justify-center whitespace-nowrap rounded-sm px-3 py-1.5 text-sm font-medium ring-offset-background transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-background data-[state=active]:text-foreground data-[state=active]:shadow-sm",t),...a}));S.displayName=Z.displayName;const L=l.forwardRef(({className:t,...a},r)=>e.jsx(M,{ref:r,className:j("mt-2 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",t),...a}));L.displayName=M.displayName;const ye={"ayu-dark":{background:{primary:"#0f1419",secondary:"#14191f"},text:{primary:"#e6e1cf",secondary:"#bae67e",muted:"#5c6773"},border:{light:"#2d323b"},syntax:{comment:"#5c6773",string:"#bae67e",number:"#ffcc66",keyword:"#ff8f40",function:"#73d0ff",variable:"#e6e1cf",operator:"#f29e74",type:"#73d0ff",tag:"#ff8f40",attr:"#ffd580",default:"#e6e1cf"}},dracula:{background:{primary:"#282a36",secondary:"#44475a"},text:{primary:"#f8f8f2",secondary:"#f1fa8c",muted:"#6272a4"},border:{light:"#44475a"},syntax:{comment:"#6272a4",string:"#f1fa8c",number:"#bd93f9",keyword:"#ff79c6",function:"#50fa7b",variable:"#f8f8f2",operator:"#ff79c6",type:"#8be9fd",tag:"#ff79c6",attr:"#50fa7b",default:"#f8f8f2"}},monokai:{background:{primary:"#272822",secondary:"#3e3d32"},text:{primary:"#f8f8f2",secondary:"#e6db74",muted:"#75715e"},border:{light:"#3e3d32"},syntax:{comment:"#75715e",string:"#e6db74",number:"#ae81ff",keyword:"#f92672",function:"#a6e22e",variable:"#f8f8f2",operator:"#f92672",type:"#66d9ef",tag:"#f92672",attr:"#a6e22e",default:"#f8f8f2"}},nord:{background:{primary:"#2e3440",secondary:"#3b4252"},text:{primary:"#eceff4",secondary:"#d8dee9",muted:"#4c566a"},border:{light:"#434c5e"},syntax:{comment:"#616e88",string:"#a3be8c",number:"#b48ead",keyword:"#81a1c1",function:"#88c0d0",variable:"#d8dee9",operator:"#81a1c1",type:"#8fbcbb",tag:"#81a1c1",attr:"#8fbcbb",default:"#eceff4"}},"solarized-light":{background:{primary:"#fdf6e3",secondary:"#eee8d5"},text:{primary:"#586e75",secondary:"#657b83",muted:"#93a1a1"},border:{light:"#eee8d5"},syntax:{comment:"#93a1a1",string:"#2aa198",number:"#d33682",keyword:"#859900",function:"#268bd2",variable:"#657b83",operator:"#859900",type:"#b58900",tag:"#268bd2",attr:"#93a1a1",default:"#657b83"}},"solarized-dark":{background:{primary:"#002b36",secondary:"#073642"},text:{primary:"#839496",secondary:"#93a1a1",muted:"#586e75"},border:{light:"#073642"},syntax:{comment:"#586e75",string:"#2aa198",number:"#d33682",keyword:"#859900",function:"#268bd2",variable:"#839496",operator:"#859900",type:"#b58900",tag:"#268bd2",attr:"#93a1a1",default:"#839496"}},"tokyo-night":{background:{primary:"#1a1b26",secondary:"#292e42"},text:{primary:"#a9b1d6",secondary:"#c0caf5",muted:"#565f89"},border:{light:"#292e42"},syntax:{comment:"#565f89",string:"#9ece6a",number:"#ff9e64",keyword:"#bb9af7",function:"#7aa2f7",variable:"#c0caf5",operator:"#89ddff",type:"#7dcfff",tag:"#f7768e",attr:"#7aa2f7",default:"#a9b1d6"}},github:{background:{primary:"#ffffff",secondary:"#f6f8fa"},text:{primary:"#24292f",secondary:"#57606a",muted:"#6e7781"},border:{light:"#d0d7de"},syntax:{comment:"#6e7781",string:"#0a3069",number:"#0550ae",keyword:"#cf222e",function:"#8250df",variable:"#24292f",operator:"#cf222e",type:"#0550ae",tag:"#116329",attr:"#0550ae",default:"#24292f"}},gruvbox:{background:{primary:"#282828",secondary:"#3c3836"},text:{primary:"#ebdbb2",secondary:"#d5c4a1",muted:"#928374"},border:{light:"#3c3836"},syntax:{comment:"#928374",string:"#b8bb26",number:"#d3869b",keyword:"#fb4934",function:"#b8bb26",variable:"#ebdbb2",operator:"#fe8019",type:"#fabd2f",tag:"#fb4934",attr:"#fabd2f",default:"#ebdbb2"}},"one-dark":{background:{primary:"#282c34",secondary:"#21252b"},text:{primary:"#abb2bf",secondary:"#e5c07b",muted:"#5c6370"},border:{light:"#3e4451"},syntax:{comment:"#5c6370",string:"#98c379",number:"#d19a66",keyword:"#c678dd",function:"#61afef",variable:"#e06c75",operator:"#56b6c2",type:"#e5c07b",tag:"#e06c75",attr:"#d19a66",default:"#abb2bf"}},catppuccin:{background:{primary:"#1e1e2e",secondary:"#313244"},text:{primary:"#cdd6f4",secondary:"#f5e0dc",muted:"#6c7086"},border:{light:"#313244"},syntax:{comment:"#6c7086",string:"#a6e3a1",number:"#fab387",keyword:"#cba6f7",function:"#89b4fa",variable:"#f5e0dc",operator:"#89dceb",type:"#f9e2af",tag:"#f38ba8",attr:"#f9e2af",default:"#cdd6f4"}},"rose-pine":{background:{primary:"#191724",secondary:"#1f1d2e"},text:{primary:"#e0def4",secondary:"#908caa",muted:"#6e6a86"},border:{light:"#26233a"},syntax:{comment:"#6e6a86",string:"#f6c177",number:"#ebbcba",keyword:"#c4a7e7",function:"#9ccfd8",variable:"#e0def4",operator:"#31748f",type:"#eb6f92",tag:"#eb6f92",attr:"#c4a7e7",default:"#e0def4"}},kanagawa:{background:{primary:"#1f1f28",secondary:"#2a2a37"},text:{primary:"#dcd7ba",secondary:"#c8c093",muted:"#727169"},border:{light:"#2a2a37"},syntax:{comment:"#727169",string:"#98bb6c",number:"#d27e99",keyword:"#957fb8",function:"#7e9cd8",variable:"#dcd7ba",operator:"#c0a36e",type:"#7aa89f",tag:"#e46876",attr:"#ffa066",default:"#dcd7ba"}}};function ke(t){const a=t.replace("#",""),r=parseInt(a.substring(0,2),16),s=parseInt(a.substring(2,4),16),o=parseInt(a.substring(4,6),16);return(.299*r+.587*s+.114*o)/255<.5}function ve(t){return{base:ke(t.background.primary)?"vs-dark":"vs",inherit:!0,rules:[{token:"",foreground:t.text.primary.replace("#",""),background:t.background.primary.replace("#","")},{token:"comment",foreground:t.syntax.comment.replace("#",""),fontStyle:"italic"},{token:"string",foreground:t.syntax.string.replace("#","")},{token:"number",foreground:t.syntax.number.replace("#","")},{token:"keyword",foreground:t.syntax.keyword.replace("#","")},{token:"type",foreground:t.syntax.type.replace("#","")},{token:"identifier",foreground:t.syntax.variable.replace("#","")},{token:"function",foreground:t.syntax.function.replace("#","")},{token:"variable",foreground:t.syntax.variable.replace("#","")},{token:"operator",foreground:t.syntax.operator.replace("#","")},{token:"delimiter",foreground:t.syntax.operator.replace("#","")},{token:"tag",foreground:t.syntax.tag.replace("#","")},{token:"attribute.name",foreground:t.syntax.attr.replace("#","")},{token:"attribute.value",foreground:t.syntax.string.replace("#","")}],colors:{"editor.background":t.background.primary,"editor.foreground":t.text.primary,"editor.lineHighlightBackground":t.background.secondary,"editor.selectionBackground":`${t.syntax.function}40`,"editorLineNumber.foreground":t.text.muted,"editorLineNumber.activeForeground":t.text.secondary,"editorCursor.foreground":t.text.primary,"editorIndentGuide.background":t.border.light,"editorWidget.background":t.background.secondary,"editorWidget.border":t.border.light,"scrollbarSlider.background":`${t.text.muted}40`,"scrollbarSlider.hoverBackground":`${t.text.muted}60`}}}const K=new Set;function U(t,a){const r=a.toLowerCase().replace(/\s+/g,"-"),s=ye[r];if(!s)return"vs-dark";if(!K.has(r)){const o=ve(s);t.editor.defineTheme(r,o),K.add(r)}return r}l.lazy(async()=>({default:(await Q(()=>import("./vendor-react-Dm1xU4bP.js").then(a=>a.k),[])).DiffEditor}));const Ee=l.lazy(async()=>({default:(await Q(()=>import("./vendor-react-Dm1xU4bP.js").then(a=>a.k),[])).Editor}));function Re(){const{toggleFilePreview:t}=le(),{messages:a,currentSessionId:r}=fe(),[s,o]=l.useState("diff"),[c,i]=l.useState([]),[d,u]=l.useState({}),[x,p]=l.useState(!1),[g,b]=l.useState(null),[F,k]=l.useState({}),[w,T]=l.useState({}),[h,P]=l.useState(null),[re,A]=l.useState(""),[D,z]=l.useState(!1),[_,$]=l.useState(null),[W,R]=l.useState(!1),I=async(n="")=>{try{const f=n?`/suggestions/files/tree?path=${encodeURIComponent(n)}`:"/suggestions/files/tree",m=await fetch(f);if(!m.ok)throw new Error("Failed to load tree");return(await m.json()).map(B=>({...B,children:B.type==="dir"?[]:void 0}))}catch{return[]}};l.useEffect(()=>{let n=!0;return(async()=>{p(!0),b(null);try{const m=await I();n&&i(m)}catch(m){n&&b(m.message)}finally{n&&p(!1)}})(),()=>{n=!1}},[r]),l.useEffect(()=>{P(null),A(""),$(null),R(!1),k({}),u({})},[r]);const C=l.useMemo(()=>Ne(a),[a]),O=l.useMemo(()=>we(a),[a]),[ne,se]=l.useState({}),oe=n=>{se(f=>({...f,[n]:!f[n]}))},de=async n=>{P(n),A(""),z(!0),$(null),R(!1);try{const f=await fetch(`/suggestions/files/content?path=${encodeURIComponent(n)}`);if(!f.ok)throw new Error("Failed to load file");const m=await f.json();A(m.content||""),R(!!m.truncated)}catch(f){$(f.message)}finally{z(!1)}},ie=async n=>{const f=!F[n];if(k(m=>({...m,[n]:f})),f&&!d[n]){const m=await I(n);u(y=>({...y,[n]:m}))}},ce=n=>{T(f=>({...f,[n]:!f[n]}))};return e.jsxs("div",{className:"w-[55%] min-w-[420px] max-w-[860px] border-l border-[#E5E7EB] dark:border-zinc-800 bg-white dark:bg-[#09090b] flex flex-col h-full shadow-xl shrink-0",children:[e.jsxs("div",{className:"flex items-center justify-between px-4 h-12 border-b border-[#E5E7EB] dark:border-zinc-800 shrink-0",children:[e.jsx("span",{className:"font-normal text-[13px] text-[#6B7280] dark:text-zinc-400 font-mono",children:"Preview"}),e.jsx(ue,{variant:"ghost",size:"icon",onClick:t,className:"h-8 w-8 text-[#9CA3AF] hover:text-[#111827] hover:bg-[#E5E7EB]/60 dark:text-zinc-500 dark:hover:text-zinc-300 dark:hover:bg-zinc-800/50",children:e.jsx(pe,{className:"w-4 h-4"})})]}),e.jsxs(he,{value:s,onValueChange:n=>o(n),className:"flex flex-col flex-1 min-h-0",children:[e.jsx("div",{className:"px-4 py-3 border-b border-[#E5E7EB] dark:border-zinc-800",children:e.jsxs(te,{className:"bg-white dark:bg-[#111113] border border-[#E5E7EB] dark:border-[#27272a] h-9 p-1 rounded-md w-full justify-start",children:[e.jsx(S,{value:"diff",className:"text-[12px] font-mono px-3 text-[#6B7280] dark:text-[#a1a1aa] data-[state=active]:bg-[#E5E7EB] data-[state=active]:text-[#111827] dark:data-[state=active]:bg-[#27272a] dark:data-[state=active]:text-white",children:"Diff"}),e.jsx(S,{value:"files",className:"text-[12px] font-mono px-3 text-[#6B7280] dark:text-[#a1a1aa] data-[state=active]:bg-[#E5E7EB] data-[state=active]:text-[#111827] dark:data-[state=active]:bg-[#27272a] dark:data-[state=active]:text-white",children:"Files"}),e.jsx(S,{value:"logs",className:"text-[12px] font-mono px-3 text-[#6B7280] dark:text-[#a1a1aa] data-[state=active]:bg-[#E5E7EB] data-[state=active]:text-[#111827] dark:data-[state=active]:bg-[#27272a] dark:data-[state=active]:text-white",children:"Logs"})]})}),e.jsx(L,{value:"diff",className:"overflow-hidden flex-1 mt-0",children:e.jsx("div",{className:"overflow-y-auto px-4 py-4 space-y-3 h-full",children:C.length===0?e.jsx(N,{title:"No patch yet",subtitle:"Run a tool that changes files to see diffs here."}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"text-[12px] text-[#6B7280] dark:text-[#71717a] font-mono mb-2",children:[C.length," changed file",C.length>1?"s":""]}),C.map(n=>{var y;const f=((y=n.filePath)==null?void 0:y.split("/").pop())||"unknown",m=ne[n.filePath||""]!==!1;return e.jsxs("div",{className:"border border-[#E5E7EB] dark:border-[#27272a] rounded-lg overflow-hidden",children:[e.jsxs("button",{onClick:()=>oe(n.filePath||""),className:"w-full flex items-center gap-2 px-3 py-2 bg-[#F9FAFB] dark:bg-[#111113] hover:bg-[#F3F4F6] dark:hover:bg-[#18181b] transition-colors",children:[m?e.jsx(J,{className:"w-4 h-4 text-[#6B7280] dark:text-[#71717a]"}):e.jsx(H,{className:"w-4 h-4 text-[#6B7280] dark:text-[#71717a]"}),e.jsx(ee,{className:"w-4 h-4 text-[#6B7280] dark:text-[#71717a]"}),e.jsx("span",{className:"text-[13px] text-[#111827] dark:text-[#E5E5E5] font-mono flex-1 text-left truncate",children:f}),n.summary&&e.jsx("span",{className:"text-[11px] text-[#6B7280] dark:text-[#a1a1aa] font-mono",children:n.summary})]}),m&&e.jsxs("div",{className:"border-t border-[#E5E7EB] dark:border-[#27272a]",children:[e.jsx("div",{className:"px-3 py-1 text-[11px] text-[#9CA3AF] dark:text-[#52525b] font-mono truncate",children:n.filePath}),e.jsx(Be,{diff:n.diff})]})]},n.filePath)})]})})}),e.jsx(L,{value:"files",className:"overflow-hidden flex-1 mt-0",children:e.jsxs("div",{className:"px-4 py-4 h-full",children:[x&&e.jsx(N,{title:"Loading files…",subtitle:"Fetching workspace tree."}),!x&&g&&e.jsx(N,{title:"Failed to load files",subtitle:g}),!x&&!g&&c.length===0&&e.jsx(N,{title:"No files yet",subtitle:"Start a session to load the workspace tree."}),!x&&!g&&c.length>0&&e.jsxs("div",{className:"h-full grid grid-cols-[220px_1fr] gap-4 min-h-0",children:[e.jsx("div",{className:"border border-[#E5E7EB] dark:border-[#27272a] rounded-lg p-2 overflow-y-auto min-h-0",children:c.map(n=>e.jsx(ae,{node:n,depth:0,expandedDirs:F,childrenCache:d,toggleDir:ie,selectedPath:h,onSelectFile:de},n.path))}),e.jsxs("div",{className:"border border-[#E5E7EB] dark:border-[#27272a] rounded-lg overflow-hidden flex flex-col min-h-0",children:[e.jsxs("div",{className:"px-3 py-2 bg-[#F9FAFB] dark:bg-[#111113] border-b border-[#E5E7EB] dark:border-[#27272a] text-[12px] text-[#6B7280] dark:text-[#71717a] font-mono flex items-center justify-between",children:[e.jsx("span",{children:h||"Select a file to preview"}),h&&e.jsx("span",{className:"text-[11px] text-[#9CA3AF] dark:text-[#a1a1aa] font-mono",children:D?"Loading…":W?"Truncated":"Ready"})]}),W&&!D&&e.jsx("div",{className:"px-3 py-2 bg-[#FEF3C7] dark:bg-[#111113] border-b border-[#E5E7EB] dark:border-[#27272a] text-[11px] text-[#b45309] dark:text-[#facc15] font-mono",children:"Preview truncated to 200k characters."}),e.jsxs("div",{className:"flex-1 min-h-0",children:[!h&&e.jsx("div",{className:"h-full flex items-center justify-center text-[12px] text-[#6B7280] dark:text-[#71717a] font-mono",children:"Pick a file from the tree to preview."}),h&&_&&e.jsx("div",{className:"h-full flex items-center justify-center text-[12px] text-[#DC2626] dark:text-[#fca5a5] font-mono",children:_}),h&&!_&&e.jsx("div",{className:"h-full",children:D?e.jsx(q,{}):e.jsx(l.Suspense,{fallback:e.jsx(q,{}),children:e.jsx(Fe,{content:re,filename:h})})})]})]})]})]})}),e.jsx(L,{value:"logs",className:"overflow-hidden flex-1 mt-0",children:e.jsx("div",{className:"overflow-y-auto px-4 py-4 space-y-3 h-full",children:O.length===0?e.jsx(N,{title:"No logs yet",subtitle:"Tool runs will appear here."}):O.map(n=>{var V;const f=w[n.id],m=(n.content||"").split(`
2
2
  `),y=m.length>10||(((V=n.content)==null?void 0:V.length)||0)>800,B=f||!y?m:m.slice(0,8);return e.jsxs("div",{className:"border border-[#E5E7EB] dark:border-[#27272a] rounded-lg overflow-hidden",children:[e.jsxs("div",{className:"flex items-center justify-between px-3 py-2 bg-[#F9FAFB] dark:bg-[#111113] border-b border-[#E5E7EB] dark:border-[#27272a]",children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsx("div",{className:"text-[12px] text-[#111827] dark:text-[#E5E5E5] font-mono",children:n.title}),n.subtitle&&e.jsx("div",{className:"text-[11px] text-[#6B7280] dark:text-[#71717a] font-mono",children:n.subtitle})]}),e.jsx(je,{status:n.status})]}),n.content&&e.jsxs("div",{className:"px-3 py-3 space-y-2",children:[e.jsxs("pre",{className:"text-[12px] text-[#374151] dark:text-[#d4d4d8] bg-[#F3F4F6] dark:bg-[#09090b] border border-[#E5E7EB] dark:border-[#27272a] rounded-md p-3 overflow-x-auto whitespace-pre-wrap font-mono",children:[B.join(`
3
3
  `),!f&&y&&`
4
4
  …`]}),y&&e.jsxs("button",{onClick:()=>ce(n.id),className:"flex items-center gap-1 text-[12px] text-[#6B7280] dark:text-[#a1a1aa] font-mono hover:text-[#111827] dark:hover:text-[#E5E5E5] transition-colors",children:[f?e.jsx(J,{className:"w-3 h-3"}):e.jsx(H,{className:"w-3 h-3"}),f?"Collapse":"Expand"]})]})]},n.id)})})})]})]})}function N({title:t,subtitle:a}){return e.jsxs("div",{className:"border border-dashed border-[#E5E7EB] dark:border-[#27272a] rounded-lg p-6 text-center",children:[e.jsx("div",{className:"text-[13px] text-[#111827] dark:text-[#E5E5E5] font-mono",children:t}),e.jsx("div",{className:"text-[12px] text-[#6B7280] dark:text-[#71717a] font-mono mt-1",children:a})]})}function je({status:t}){const a=t==="success"?"Success":t==="error"?"Failed":"Running",r=t==="success"?"bg-[#22C55E] text-white":t==="error"?"bg-[#FEE2E2] text-[#b91c1c] dark:bg-[#EF4444]/20 dark:text-[#fca5a5]":"bg-[#E5E7EB] text-[#6B7280] dark:bg-[#27272a] dark:text-[#a1a1aa]";return e.jsx("span",{className:j("text-[11px] px-2 py-0.5 rounded-full font-mono",r),children:a})}function ae({node:t,depth:a,expandedDirs:r,childrenCache:s,toggleDir:o,onSelectFile:c,selectedPath:i}){const d=t.type==="dir",u=r[t.path],x=!d&&i===t.path,p=s[t.path]||[];return e.jsxs("div",{children:[e.jsx("button",{onClick:()=>{d?o(t.path):c(t.path)},className:j("flex items-center gap-2 w-full text-left text-[12px] font-mono px-2 py-1 rounded-md transition-colors",x?"bg-[#16A34A]/10 text-[#111827] dark:bg-[#22C55E]/10 dark:text-[#E5E5E5]":"hover:bg-[#F3F4F6] text-[#6B7280] dark:hover:bg-[#111113] dark:text-[#a1a1aa]",d&&"cursor-pointer",x&&"border border-[#16A34A]/30 dark:border-[#22C55E]/30"),style:{paddingLeft:a*14+8},children:d?e.jsxs(e.Fragment,{children:[u?e.jsx(be,{className:"h-3.5 w-3.5 shrink-0 text-[#111827] dark:text-[#E5E5E5]"}):e.jsx(ge,{className:"h-3.5 w-3.5 shrink-0 text-[#6B7280] dark:text-[#a1a1aa]"}),e.jsx("span",{className:"text-[#111827] dark:text-[#E5E5E5] truncate",children:t.name})]}):e.jsxs(e.Fragment,{children:[e.jsx(ee,{className:"h-3.5 w-3.5 shrink-0 text-[#9CA3AF] dark:text-[#71717a]"}),e.jsx("span",{className:"text-[#111827] dark:text-[#E5E5E5] truncate",children:t.name})]})}),d&&u&&e.jsx("div",{children:p.map(g=>e.jsx(ae,{node:g,depth:a+1,expandedDirs:r,childrenCache:s,toggleDir:o,onSelectFile:c,selectedPath:i},g.path))})]})}function we(t){return t.flatMap(a=>{var o,c,i;const r=[];if((o=a.agentContent)!=null&&o.toolCalls)for(const d of a.agentContent.toolCalls){const u=X(d.arguments),x=d.output,p=x?(c=E(x))!=null&&c.diff?G(x):x:void 0;r.push({id:`${a.id}-${d.toolCallId}`,title:d.toolName||"Tool",subtitle:d.summary,status:d.status==="success"?"success":d.status==="error"?"error":"running",content:p||(u?`Arguments:
@@ -1 +1 @@
1
- import{M as k,r as h,_ as j}from"./vendor-markdown-DIcugY1e.js";import{r as o,j as r}from"./vendor-react-Dm1xU4bP.js";import{c as b}from"./index-DehGtSvJ.js";import{a as f}from"./SettingsStore-E-aIqvyl.js";import{c as g,r as N}from"./vendor-icons-DlzC8I7m.js";import"./vendor-monaco-w6PwaWGP.js";import"./vendor-radix-CKNFO4jS.js";const v=[h],y=o.lazy(()=>j(()=>import("./CodeBlockHighlighter-C86flFwh.js"),[]).then(t=>({default:t.CodeBlockHighlighter}))),R=o.memo(function({content:s,className:a,syntaxHighlight:d=!0}){const i=f(),E=o.useMemo(()=>({code({className:e,children:n,...c}){const x=/language-(\w+)/.exec(e||""),p=!x,m=x?x[1]:"",l=String(n).replace(/\n$/,"");return p?r.jsx("code",{className:b("bg-[#F3F4F6] dark:bg-[#27272a] px-1.5 py-0.5 rounded text-[#111827] dark:text-[#E5E5E5] font-mono text-[13px]",e),...c,children:n}):d?r.jsxs("div",{className:"relative my-4 rounded-lg overflow-hidden border border-[#E5E7EB] dark:border-[#27272a] bg-[#F9FAFB] dark:bg-[#1e1e1e]",children:[r.jsxs("div",{className:"flex items-center justify-between px-4 py-2 bg-[#F3F4F6] dark:bg-[#27272a] border-b border-[#E5E7EB] dark:border-[#27272a]",children:[r.jsx("span",{className:"text-xs text-[#6B7280] dark:text-[#a1a1aa] font-mono",children:m||"text"}),r.jsx(F,{content:l})]}),r.jsx(o.Suspense,{fallback:r.jsx(u,{className:e,code:l,props:c}),children:r.jsx(y,{code:l,language:m,isDark:i})})]}):r.jsx(u,{className:e,code:l,props:c})},p({children:e}){return r.jsx("p",{className:"mb-4 leading-relaxed last:mb-0",children:e})},ul({children:e}){return r.jsx("ul",{className:"pl-4 mb-4 space-y-1 list-disc last:mb-0",children:e})},ol({children:e}){return r.jsx("ol",{className:"pl-4 mb-4 space-y-1 list-decimal last:mb-0",children:e})},li({children:e}){return r.jsx("li",{className:"leading-relaxed",children:e})},h1({children:e}){return r.jsx("h1",{className:"text-2xl font-bold mb-4 mt-6 text-[#111827] dark:text-[#E5E5E5]",children:e})},h2({children:e}){return r.jsx("h2",{className:"text-xl font-bold mb-3 mt-5 text-[#111827] dark:text-[#E5E5E5]",children:e})},h3({children:e}){return r.jsx("h3",{className:"text-lg font-bold mb-2 mt-4 text-[#111827] dark:text-[#E5E5E5]",children:e})},blockquote({children:e}){return r.jsx("blockquote",{className:"border-l-2 border-[#22C55E] pl-4 italic text-[#6B7280] dark:text-[#a1a1aa] mb-4",children:e})},a({href:e,children:n}){return r.jsx("a",{href:e,target:"_blank",rel:"noopener noreferrer",className:"text-[#22C55E] hover:underline transition-colors",children:n})},table({children:e}){return r.jsx("div",{className:"overflow-x-auto mb-4 border border-[#E5E7EB] dark:border-[#27272a] rounded-lg",children:r.jsx("table",{className:"w-full text-sm text-left",children:e})})},thead({children:e}){return r.jsx("thead",{className:"bg-[#F3F4F6] text-[#111827] dark:bg-[#27272a] dark:text-[#E5E5E5]",children:e})},tbody({children:e}){return r.jsx("tbody",{className:"divide-y divide-[#E5E7EB] dark:divide-[#27272a]",children:e})},tr({children:e}){return r.jsx("tr",{className:"hover:bg-[#F3F4F6] dark:hover:bg-[#27272a]/50 transition-colors",children:e})},th({children:e}){return r.jsx("th",{className:"px-4 py-3 font-medium whitespace-nowrap",children:e})},td({children:e}){return r.jsx("td",{className:"px-4 py-3 text-[#374151] dark:text-[#d4d4d8]",children:e})},hr(){return r.jsx("hr",{className:"my-6 border-[#E5E7EB] dark:border-[#27272a]"})}}),[i,d]);return r.jsx("div",{className:b("text-[14px] text-[#111827] dark:text-[#E5E5E5] font-mono break-words min-w-0 w-full",a),children:r.jsx(k,{remarkPlugins:v,components:E,children:s})})});function u({className:t,code:s,props:a}){return r.jsx("pre",{className:"my-4 overflow-x-auto rounded-lg border border-[#E5E7EB] dark:border-[#27272a] bg-[#F9FAFB] dark:bg-[#1e1e1e] p-4 text-[13px] leading-normal",children:r.jsx("code",{className:t,...a,children:s})})}function F({content:t}){const[s,a]=o.useState(!1),d=async()=>{await navigator.clipboard.writeText(t),a(!0),setTimeout(()=>a(!1),2e3)};return r.jsx("button",{onClick:d,className:"p-1 hover:bg-[#E5E7EB] dark:hover:bg-[#3f3f46] rounded-md transition-colors text-[#9CA3AF] dark:text-[#a1a1aa] hover:text-[#111827] dark:hover:text-[#E5E5E5]",title:"Copy code",children:s?r.jsx(g,{className:"h-3.5 w-3.5 text-[#22C55E]"}):r.jsx(N,{className:"h-3.5 w-3.5"})})}export{R as MarkdownRenderer};
1
+ import{M as k,r as h,_ as j}from"./vendor-markdown-DIcugY1e.js";import{r as o,j as r}from"./vendor-react-Dm1xU4bP.js";import{c as b}from"./index-BeYCsOvo.js";import{a as f}from"./SettingsStore-Dmo3sZ_R.js";import{c as g,r as N}from"./vendor-icons-DlzC8I7m.js";import"./vendor-monaco-w6PwaWGP.js";import"./vendor-radix-CfxBc_4-.js";const v=[h],y=o.lazy(()=>j(()=>import("./CodeBlockHighlighter-C86flFwh.js"),[]).then(t=>({default:t.CodeBlockHighlighter}))),R=o.memo(function({content:s,className:a,syntaxHighlight:d=!0}){const i=f(),E=o.useMemo(()=>({code({className:e,children:n,...c}){const x=/language-(\w+)/.exec(e||""),p=!x,m=x?x[1]:"",l=String(n).replace(/\n$/,"");return p?r.jsx("code",{className:b("bg-[#F3F4F6] dark:bg-[#27272a] px-1.5 py-0.5 rounded text-[#111827] dark:text-[#E5E5E5] font-mono text-[13px]",e),...c,children:n}):d?r.jsxs("div",{className:"relative my-4 rounded-lg overflow-hidden border border-[#E5E7EB] dark:border-[#27272a] bg-[#F9FAFB] dark:bg-[#1e1e1e]",children:[r.jsxs("div",{className:"flex items-center justify-between px-4 py-2 bg-[#F3F4F6] dark:bg-[#27272a] border-b border-[#E5E7EB] dark:border-[#27272a]",children:[r.jsx("span",{className:"text-xs text-[#6B7280] dark:text-[#a1a1aa] font-mono",children:m||"text"}),r.jsx(F,{content:l})]}),r.jsx(o.Suspense,{fallback:r.jsx(u,{className:e,code:l,props:c}),children:r.jsx(y,{code:l,language:m,isDark:i})})]}):r.jsx(u,{className:e,code:l,props:c})},p({children:e}){return r.jsx("p",{className:"mb-4 leading-relaxed last:mb-0",children:e})},ul({children:e}){return r.jsx("ul",{className:"pl-4 mb-4 space-y-1 list-disc last:mb-0",children:e})},ol({children:e}){return r.jsx("ol",{className:"pl-4 mb-4 space-y-1 list-decimal last:mb-0",children:e})},li({children:e}){return r.jsx("li",{className:"leading-relaxed",children:e})},h1({children:e}){return r.jsx("h1",{className:"text-2xl font-bold mb-4 mt-6 text-[#111827] dark:text-[#E5E5E5]",children:e})},h2({children:e}){return r.jsx("h2",{className:"text-xl font-bold mb-3 mt-5 text-[#111827] dark:text-[#E5E5E5]",children:e})},h3({children:e}){return r.jsx("h3",{className:"text-lg font-bold mb-2 mt-4 text-[#111827] dark:text-[#E5E5E5]",children:e})},blockquote({children:e}){return r.jsx("blockquote",{className:"border-l-2 border-[#22C55E] pl-4 italic text-[#6B7280] dark:text-[#a1a1aa] mb-4",children:e})},a({href:e,children:n}){return r.jsx("a",{href:e,target:"_blank",rel:"noopener noreferrer",className:"text-[#22C55E] hover:underline transition-colors",children:n})},table({children:e}){return r.jsx("div",{className:"overflow-x-auto mb-4 border border-[#E5E7EB] dark:border-[#27272a] rounded-lg",children:r.jsx("table",{className:"w-full text-sm text-left",children:e})})},thead({children:e}){return r.jsx("thead",{className:"bg-[#F3F4F6] text-[#111827] dark:bg-[#27272a] dark:text-[#E5E5E5]",children:e})},tbody({children:e}){return r.jsx("tbody",{className:"divide-y divide-[#E5E7EB] dark:divide-[#27272a]",children:e})},tr({children:e}){return r.jsx("tr",{className:"hover:bg-[#F3F4F6] dark:hover:bg-[#27272a]/50 transition-colors",children:e})},th({children:e}){return r.jsx("th",{className:"px-4 py-3 font-medium whitespace-nowrap",children:e})},td({children:e}){return r.jsx("td",{className:"px-4 py-3 text-[#374151] dark:text-[#d4d4d8]",children:e})},hr(){return r.jsx("hr",{className:"my-6 border-[#E5E7EB] dark:border-[#27272a]"})}}),[i,d]);return r.jsx("div",{className:b("text-[14px] text-[#111827] dark:text-[#E5E5E5] font-mono break-words min-w-0 w-full",a),children:r.jsx(k,{remarkPlugins:v,components:E,children:s})})});function u({className:t,code:s,props:a}){return r.jsx("pre",{className:"my-4 overflow-x-auto rounded-lg border border-[#E5E7EB] dark:border-[#27272a] bg-[#F9FAFB] dark:bg-[#1e1e1e] p-4 text-[13px] leading-normal",children:r.jsx("code",{className:t,...a,children:s})})}function F({content:t}){const[s,a]=o.useState(!1),d=async()=>{await navigator.clipboard.writeText(t),a(!0),setTimeout(()=>a(!1),2e3)};return r.jsx("button",{onClick:d,className:"p-1 hover:bg-[#E5E7EB] dark:hover:bg-[#3f3f46] rounded-md transition-colors text-[#9CA3AF] dark:text-[#a1a1aa] hover:text-[#111827] dark:hover:text-[#E5E5E5]",title:"Copy code",children:s?r.jsx(g,{className:"h-3.5 w-3.5 text-[#22C55E]"}):r.jsx(N,{className:"h-3.5 w-3.5"})})}export{R as MarkdownRenderer};