blade-code 0.4.4 → 0.4.6

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 (38) hide show
  1. package/dist/blade.js +2 -2
  2. package/dist/{chunk-tf0m57f5.js → chunk-2e3pajfb.js} +1 -1
  3. package/dist/{chunk-kd1t45br.js → chunk-6yvqtcx0.js} +1 -1
  4. package/dist/{chunk-ehcjnwnr.js → chunk-9syksrkj.js} +1 -1
  5. package/dist/chunk-c6ts8bd9.js +26 -0
  6. package/dist/{chunk-420vamtq.js → chunk-cfbp6h36.js} +1 -1
  7. package/dist/{chunk-8pn5m426.js → chunk-ctacwg1h.js} +1 -1
  8. package/dist/{chunk-5xc0kzdt.js → chunk-cwafz1g3.js} +1 -1
  9. package/dist/{chunk-5zkcs06z.js → chunk-d1hwbcne.js} +1 -1
  10. package/dist/{chunk-9mrna4y3.js → chunk-e38t8r4f.js} +1 -1
  11. package/dist/{chunk-mvyxksrz.js → chunk-f35tdzfy.js} +1 -1
  12. package/dist/{chunk-jvbx3h56.js → chunk-gkd5eew1.js} +140 -114
  13. package/dist/chunk-hhgbhadg.js +76 -0
  14. package/dist/{chunk-7637p6w5.js → chunk-hpafbk1w.js} +1 -1
  15. package/dist/{chunk-q4hrt6r4.js → chunk-ksd0cxtf.js} +1 -1
  16. package/dist/{chunk-52k9k0w8.js → chunk-mjgch1nt.js} +1 -1
  17. package/dist/{chunk-zs7xeymy.js → chunk-n466beq9.js} +1 -1
  18. package/dist/{chunk-094ekgv6.js → chunk-nhp35rk0.js} +2 -2
  19. package/dist/chunk-pe6dnssd.js +1 -0
  20. package/dist/chunk-pkmw32r0.js +8 -0
  21. package/dist/chunk-pmtfesmc.js +1 -0
  22. package/dist/{chunk-jz59sjzb.js → chunk-r8wmg3fc.js} +1 -1
  23. package/dist/{chunk-7snnj126.js → chunk-tf74ehds.js} +1 -1
  24. package/dist/{chunk-8jwqy5d0.js → chunk-v1c9xwen.js} +1 -1
  25. package/dist/chunk-vs5a1443.js +157 -0
  26. package/dist/{chunk-tph4ngbj.js → chunk-x2jkbn5c.js} +1 -1
  27. package/dist/{chunk-vwn39c84.js → chunk-xcpjsrem.js} +1 -1
  28. package/dist/{chunk-n8na8c5h.js → chunk-xpbgzgfz.js} +1 -1
  29. package/dist/{chunk-vs2x9sxb.js → chunk-yf7cz40m.js} +1 -1
  30. package/dist/{chunk-4jh0h16z.js → chunk-yhwrv3qf.js} +1 -1
  31. package/dist/{chunk-z1qz8p1j.js → chunk-ze1tddc3.js} +1 -1
  32. package/package.json +2 -2
  33. package/dist/chunk-5mtjqqav.js +0 -8
  34. package/dist/chunk-76emdpxa.js +0 -76
  35. package/dist/chunk-92kjp66d.js +0 -1
  36. package/dist/chunk-a5b9fkp3.js +0 -157
  37. package/dist/chunk-h3ccyfqj.js +0 -1
  38. package/dist/chunk-y5g06jmk.js +0 -24
@@ -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-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(`
1
+ import{e as zf,f as Tf}from"./chunk-xcpjsrem.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-gkd5eew1.js";import{Y as T}from"./chunk-yhwrv3qf.js";import{ba as u}from"./chunk-6yvqtcx0.js";import{Ba as xf,Ca as Rf,Ga as z,za as S}from"./chunk-hhgbhadg.js";import{La as _f,Na as t,Sa as Ef}from"./chunk-9syksrkj.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,2 +1,2 @@
1
- import{ob as Q,pb as W,qb as Y}from"./chunk-5mtjqqav.js";import{Bb as X}from"./chunk-set7v1rf.js";var J=X("Service"),$="https://models.dev/api.json",j=3600000,G=null,Z=async()=>{if(G&&Date.now()-G.timestamp<j)return G.data;try{J.info("Fetching models.dev data...");let q=await fetch($,{headers:{"User-Agent":"Blade-CLI/1.0"}});if(!q.ok)throw Error(`HTTP ${q.status}: ${q.statusText}`);let x=await q.json();return G={data:x,timestamp:Date.now()},J.info(`Loaded ${Object.keys(x).length} providers from models.dev`),x}catch(q){throw J.error("Failed to fetch models.dev data:",q),q}},y=async()=>{let q=await Z(),x=[];for(let[w,k]of Object.entries(q)){let z=Object.keys(k.models||{}).length;if(z===0)continue;x.push({id:w,name:k.name||w,icon:W[w]||W.default,description:`${z} 个模型`,envVars:k.env||[],docUrl:k.doc,defaultBaseUrl:Y[w]})}return x.sort((w,k)=>{let z=Q.indexOf(w.id),K=Q.indexOf(k.id);if(z!==-1&&K!==-1)return z-K;if(z!==-1)return-1;if(K!==-1)return 1;return w.name.localeCompare(k.name)})},f=async(q)=>{let w=(await Z())[q];if(!w?.models)return J.warn(`No models found for provider: ${q}`),[];return Object.values(w.models).map((k)=>({id:k.id,name:k.name||k.id,contextWindow:k.limit?.context,maxOutput:k.limit?.output,inputCost:k.cost?.input,outputCost:k.cost?.output}))};
1
+ import{ob as Q,pb as W,qb as Y}from"./chunk-pkmw32r0.js";import{Bb as X}from"./chunk-set7v1rf.js";var J=X("Service"),$="https://models.dev/api.json",j=3600000,G=null,Z=async()=>{if(G&&Date.now()-G.timestamp<j)return G.data;try{J.info("Fetching models.dev data...");let q=await fetch($,{headers:{"User-Agent":"Blade-CLI/1.0"}});if(!q.ok)throw Error(`HTTP ${q.status}: ${q.statusText}`);let x=await q.json();return G={data:x,timestamp:Date.now()},J.info(`Loaded ${Object.keys(x).length} providers from models.dev`),x}catch(q){throw J.error("Failed to fetch models.dev data:",q),q}},y=async()=>{let q=await Z(),x=[];for(let[w,k]of Object.entries(q)){let z=Object.keys(k.models||{}).length;if(z===0)continue;x.push({id:w,name:k.name||w,icon:W[w]||W.default,description:`${z} 个模型`,envVars:k.env||[],docUrl:k.doc,defaultBaseUrl:Y[w]})}return x.sort((w,k)=>{let z=Q.indexOf(w.id),K=Q.indexOf(k.id);if(z!==-1&&K!==-1)return z-K;if(z!==-1)return-1;if(K!==-1)return 1;return w.name.localeCompare(k.name)})},f=async(q)=>{let w=(await Z())[q];if(!w?.models)return J.warn(`No models found for provider: ${q}`),[];return Object.values(w.models).map((k)=>({id:k.id,name:k.name||k.id,contextWindow:k.limit?.context,maxOutput:k.limit?.output,inputCost:k.cost?.input,outputCost:k.cost?.output}))};
2
2
  export{y as e,f};
@@ -1 +1 @@
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
+ import{aa as a,ba as b,ca as c,da as d,ea as e,fa as f}from"./chunk-6yvqtcx0.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,4 +1,4 @@
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}
1
+ import{p as z,q as g,r as v,s as p}from"./chunk-cwafz1g3.js";import{t as E}from"./chunk-e38t8r4f.js";import{v as S,w as h,x as c}from"./chunk-r8wmg3fc.js";import{G as w,I as F,J as y,L as x,M as C}from"./chunk-gkd5eew1.js";import"./chunk-yhwrv3qf.js";import"./chunk-esnkk33h.js";import"./chunk-6yvqtcx0.js";import"./chunk-v1c9xwen.js";import"./chunk-hhgbhadg.js";import"./chunk-c6ts8bd9.js";import{Sa as O}from"./chunk-9syksrkj.js";import"./chunk-yddnm9n2.js";import"./chunk-nhp35rk0.js";import"./chunk-pkmw32r0.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(`
@@ -1,4 +1,4 @@
1
- import{ba as S,ca as h}from"./chunk-kd1t45br.js";import{kb as M}from"./chunk-yddnm9n2.js";import{Db as c}from"./chunk-j2ag7hh6.js";import{EventEmitter as r}from"events";import{z as L}from"zod";import{isPlainObject as v}from"lodash-es";function b(B){if(B===void 0)return"undefined";if(typeof B==="string")return B;try{let G=JSON.stringify(B);return G===void 0?String(B):G}catch{return String(B)}}class R extends Error{issues;type;constructor(B,G,Q="validation_error"){super(B);this.issues=G;this.type=Q;this.name="ToolValidationError"}}function g(B){let{code:G}=B,Q=B,X=Q.received;switch(G){case"invalid_type":{let Y=Q.expected;return`类型错误:期望 ${b(Y)},实际收到 ${b(X)}`}case"too_small":{let{minimum:Y,inclusive:$}=Q,W=typeof Q.type==="string"?Q.type:void 0;if(W==="string"&&typeof Y==="number")return`长度不能少于 ${Y} 个字符`;if(W==="number"&&typeof Y==="number")return`不能小于${$?"等于":""} ${Y}`;if(W==="array"&&typeof Y==="number")return`数组长度不能少于 ${Y}`;return"值太小"}case"too_big":{let{maximum:Y,inclusive:$}=Q,W=typeof Q.type==="string"?Q.type:void 0;if(W==="string"&&typeof Y==="number")return`长度不能超过 ${Y} 个字符`;if(W==="number"&&typeof Y==="number")return`不能大于${$?"等于":""} ${Y}`;if(W==="array"&&typeof Y==="number")return`数组长度不能超过 ${Y}`;return"值太大"}case"invalid_string":{let Y=Q.validation;if(Y==="email")return"必须是有效的电子邮件地址";if(Y==="url")return"必须是有效的 URL";if(Y==="uuid")return"必须是有效的 UUID";if(v(Y)){let $=Y;if(typeof $.includes==="string")return`必须包含 "${$.includes}"`;if(typeof $.startsWith==="string")return`必须以 "${$.startsWith}" 开头`;if(typeof $.endsWith==="string")return`必须以 "${$.endsWith}" 结尾`}return"字符串格式不正确"}case"invalid_enum_value":{let Y=Q.options;if(Array.isArray(Y))return`必须是以下值之一:${Y.map(($)=>b($)).join(", ")}`;return"必须是枚举允许的值之一"}case"invalid_literal":{let Y=Q.expected;return`必须是字面量值:${b(Y)}`}case"unrecognized_keys":{let Y=Q.keys;if(Array.isArray(Y))return`包含未知的参数:${Y.map(($)=>b($)).join(", ")}`;return"包含未知的参数"}case"invalid_union":return"不符合任何有效的类型定义";case"invalid_date":return"必须是有效的日期";case"custom":return B.message||"自定义验证失败";default:return B.message||"验证失败"}}function u(B){let G=B.issues.map((X)=>{let Y=X.path.join("."),$=g(X),W=X.received;return{field:Y||"root",message:$,value:W}}),Q=G.length===1?`参数验证失败 [${G[0].field}]: ${G[0].message}`:`参数验证失败 (${G.length} 个错误):
1
+ import{ba as S,ca as h}from"./chunk-6yvqtcx0.js";import{kb as M}from"./chunk-yddnm9n2.js";import{Db as c}from"./chunk-j2ag7hh6.js";import{EventEmitter as r}from"events";import{z as L}from"zod";import{isPlainObject as v}from"lodash-es";function b(B){if(B===void 0)return"undefined";if(typeof B==="string")return B;try{let G=JSON.stringify(B);return G===void 0?String(B):G}catch{return String(B)}}class R extends Error{issues;type;constructor(B,G,Q="validation_error"){super(B);this.issues=G;this.type=Q;this.name="ToolValidationError"}}function g(B){let{code:G}=B,Q=B,X=Q.received;switch(G){case"invalid_type":{let Y=Q.expected;return`类型错误:期望 ${b(Y)},实际收到 ${b(X)}`}case"too_small":{let{minimum:Y,inclusive:$}=Q,W=typeof Q.type==="string"?Q.type:void 0;if(W==="string"&&typeof Y==="number")return`长度不能少于 ${Y} 个字符`;if(W==="number"&&typeof Y==="number")return`不能小于${$?"等于":""} ${Y}`;if(W==="array"&&typeof Y==="number")return`数组长度不能少于 ${Y}`;return"值太小"}case"too_big":{let{maximum:Y,inclusive:$}=Q,W=typeof Q.type==="string"?Q.type:void 0;if(W==="string"&&typeof Y==="number")return`长度不能超过 ${Y} 个字符`;if(W==="number"&&typeof Y==="number")return`不能大于${$?"等于":""} ${Y}`;if(W==="array"&&typeof Y==="number")return`数组长度不能超过 ${Y}`;return"值太大"}case"invalid_string":{let Y=Q.validation;if(Y==="email")return"必须是有效的电子邮件地址";if(Y==="url")return"必须是有效的 URL";if(Y==="uuid")return"必须是有效的 UUID";if(v(Y)){let $=Y;if(typeof $.includes==="string")return`必须包含 "${$.includes}"`;if(typeof $.startsWith==="string")return`必须以 "${$.startsWith}" 开头`;if(typeof $.endsWith==="string")return`必须以 "${$.endsWith}" 结尾`}return"字符串格式不正确"}case"invalid_enum_value":{let Y=Q.options;if(Array.isArray(Y))return`必须是以下值之一:${Y.map(($)=>b($)).join(", ")}`;return"必须是枚举允许的值之一"}case"invalid_literal":{let Y=Q.expected;return`必须是字面量值:${b(Y)}`}case"unrecognized_keys":{let Y=Q.keys;if(Array.isArray(Y))return`包含未知的参数:${Y.map(($)=>b($)).join(", ")}`;return"包含未知的参数"}case"invalid_union":return"不符合任何有效的类型定义";case"invalid_date":return"必须是有效的日期";case"custom":return B.message||"自定义验证失败";default:return B.message||"验证失败"}}function u(B){let G=B.issues.map((X)=>{let Y=X.path.join("."),$=g(X),W=X.received;return{field:Y||"root",message:$,value:W}}),Q=G.length===1?`参数验证失败 [${G[0].field}]: ${G[0].message}`:`参数验证失败 (${G.length} 个错误):
2
2
  ${G.map((X)=>` - ${X.field}: ${X.message}`).join(`
3
3
  `)}`;return new R(Q,G)}function y(B,G){let Q=B.safeParse(G);if(!Q.success)throw u(Q.error);return Q.data}import{zodToJsonSchema as l}from"zod-to-json-schema";function H(B){let G=l(B,{target:"jsonSchema7",$refStrategy:"none"});if(G.type==="object"&&G.properties&&!Array.isArray(G.required))G.required=[];return G}class w{toolName;params;executeFn;descriptionFn;affectedPathsFn;constructor(B,G,Q,X,Y){this.toolName=B;this.params=G;this.executeFn=Q;this.descriptionFn=X;this.affectedPathsFn=Y}getDescription(){if(this.descriptionFn)return this.descriptionFn(this.params);return`执行工具: ${this.toolName}`}getAffectedPaths(){if(this.affectedPathsFn)return this.affectedPathsFn(this.params);return[]}async execute(B,G,Q){let X={signal:B,updateOutput:G,...Q};return this.executeFn(this.params,X)}}function k(B){return{name:B.name,displayName:B.displayName,kind:B.kind,isReadOnly:B.isReadOnly??M(B.kind),isConcurrencySafe:B.isConcurrencySafe??!1,strict:B.strict??!1,description:B.description,version:B.version||"1.0.0",category:B.category,tags:B.tags||[],getFunctionDeclaration(){let G=H(B.schema),Q=B.description.short;if(B.description.long)Q+=`
4
4
 
@@ -1,4 +1,4 @@
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 $=`
1
+ import{a as Q,b as R,c as T,d as W}from"./chunk-x2jkbn5c.js";import"./chunk-xcpjsrem.js";import"./chunk-gkd5eew1.js";import"./chunk-yhwrv3qf.js";import"./chunk-esnkk33h.js";import{ba as M}from"./chunk-6yvqtcx0.js";import"./chunk-v1c9xwen.js";import{Aa as J}from"./chunk-hhgbhadg.js";import"./chunk-c6ts8bd9.js";import"./chunk-9syksrkj.js";import"./chunk-yddnm9n2.js";import"./chunk-nhp35rk0.js";import"./chunk-pkmw32r0.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
  | _ \\| |/ _\` |/ _\` |/ _ \\
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "blade-code",
3
- "version": "0.4.4",
3
+ "version": "0.4.6",
4
4
  "private": false,
5
5
  "description": "🗡️ Blade Code - 智能代码助手命令行工具",
6
6
  "type": "module",
@@ -127,4 +127,4 @@
127
127
  "typescript": "^5.9.2",
128
128
  "vitest": "^3.0.0"
129
129
  }
130
- }
130
+ }
@@ -1,8 +0,0 @@
1
- import{Bb as R}from"./chunk-set7v1rf.js";var C=["anthropic","openai","deepseek","google-generative-ai","groq","openrouter"],b={anthropic:"",openai:"","google-generative-ai":"",deepseek:"",groq:"",openrouter:"",azure:"",ollama:"",together:"",fireworks:"",mistral:"",cohere:"",perplexity:"",xai:"",default:""},f={anthropic:"https://api.anthropic.com",openai:"https://api.openai.com/v1",google:"https://generativelanguage.googleapis.com/v1beta",deepseek:"https://api.deepseek.com/v1",groq:"https://api.groq.com/openai/v1",openrouter:"https://openrouter.ai/api/v1",togetherai:"https://api.together.xyz/v1","fireworks-ai":"https://api.fireworks.ai/inference/v1",mistral:"https://api.mistral.ai/v1",cohere:"https://api.cohere.ai/v1",perplexity:"https://api.perplexity.ai",xai:"https://api.x.ai/v1",cerebras:"https://api.cerebras.ai/v1","novita-ai":"https://api.novita.ai/v3/openai",nvidia:"https://integrate.api.nvidia.com/v1"},h={anthropic:{"anthropic-beta":"claude-code-20250219,interleaved-thinking-2025-05-14,fine-grained-tool-streaming-2025-05-14"},openrouter:{"HTTP-Referer":"https://github.com/anthropics/blade","X-Title":"Blade"},cerebras:{"X-Cerebras-3rd-Party-Integration":"blade"},vercel:{"http-referer":"https://github.com/anthropics/blade","x-title":"blade"},zenmux:{"HTTP-Referer":"https://github.com/anthropics/blade","X-Title":"blade"}},V=(F)=>{return h[F]||{}};import{createAnthropic as A}from"@ai-sdk/anthropic";import{createAzure as E}from"@ai-sdk/azure";import{createDeepSeek as k}from"@ai-sdk/deepseek";import{createGoogleGenerativeAI as P}from"@ai-sdk/google";import{createOpenAI as x}from"@ai-sdk/openai";import{createOpenAICompatible as z}from"@ai-sdk/openai-compatible";import{generateText as H,jsonSchema as T,streamText as K}from"ai";var B=R("Chat");function O(F){let q=new Set;for(let W of F)if(W.role==="assistant"&&W.tool_calls)for(let Q of W.tool_calls)q.add(Q.id);return F.filter((W)=>{if(W.role==="tool"){if(!W.tool_call_id)return!1;return q.has(W.tool_call_id)}return!0})}function N(F){if(typeof F==="string")return F;return F.filter((q)=>q.type==="text").map((q)=>q.text).join(`
2
- `)}function L(F){let q=F;return q.text??q.textDelta??q.delta}function U(F,q={}){try{return JSON.parse(F)}catch{return B.warn("[VercelAIChatService] Failed to parse JSON, using fallback",{str:F}),q}}class D{model;config;constructor(F){this.config=F,this.model=this.createModel(F),B.debug("[VercelAIChatService] Initialized",{provider:F.provider,model:F.model})}createModel(F){let{provider:q,apiKey:W,baseUrl:Q,model:X,customHeaders:Z,apiVersion:$}=F;switch(q){case"openai":return x({apiKey:W,baseURL:Q||void 0,headers:Z})(X);case"anthropic":return A({apiKey:W,baseURL:Q||void 0,headers:Z})(X);case"gemini":{if(Q&&!this.isGeminiOfficialUrl(Q))return z({name:"gemini",apiKey:W,baseURL:Q,headers:Z})(X);return P({apiKey:W,baseURL:Q||void 0})(X)}case"google":case"google-generative-ai":case"google-vertex":{if(Q&&!this.isGeminiOfficialUrl(Q))return z({name:q,apiKey:W,baseURL:Q,headers:Z})(X);return P({apiKey:W,baseURL:Q||void 0})(X)}case"azure-openai":{let Y=this.extractAzureResourceName(Q);if(Y)return E({apiKey:W,resourceName:Y,apiVersion:$||"2024-08-01-preview"})(X);let J=this.buildAzureBaseUrl(Q,X);return z({name:"azure-openai",apiKey:W,baseURL:J,headers:{...Z,"api-key":W},queryParams:{"api-version":$||"2024-08-01-preview"}})(X)}case"azure":{let Y=this.extractAzureResourceName(Q);if(Y)return E({apiKey:W,resourceName:Y,apiVersion:$||"2024-08-01-preview"})(X);let J=this.buildAzureBaseUrl(Q,X);return z({name:"azure-openai",apiKey:W,baseURL:J,headers:{...Z,"api-key":W},queryParams:{"api-version":$||"2024-08-01-preview"}})(X)}case"deepseek":return k({apiKey:W,baseURL:Q||void 0,headers:Z})(X);default:return z({name:q,apiKey:W,baseURL:Q,headers:Z})(X)}}extractAzureResourceName(F){if(!F)return;let q=F.match(/https:\/\/([^.]+)\.openai\.azure(?:\.com|\.us|\.cn|\.de)/);return q?q[1]:void 0}buildAzureBaseUrl(F,q){if(!F)return"";let W=F.replace(/\/$/,"").replace(/\?.*$/,"");if(W.includes("/openai/deployments/"))return W;return`${W}/openai/deployments/${q}`}isGeminiOfficialUrl(F){return F.includes("generativelanguage.googleapis.com")||F.includes("aiplatform.googleapis.com")}needsThinkingReplayMetadata(){return/deepseek/i.test([this.config.provider,this.config.model,this.config.baseUrl].join(" "))}getThinkingReplayProviderOptions(F){let q=F?.trim();if(!q||!this.needsThinkingReplayMetadata())return;return{openaiCompatible:{reasoning_content:q}}}shouldFlattenDeepSeekThinkingToolHistory(){return this.needsThinkingReplayMetadata()}flattenDeepSeekThinkingToolHistory(F){let q=[],W,Q=()=>{if(!W)return;q.push({role:"assistant",content:N(W.content).trim()||"I will use the requested tool and continue from its result."}),W=void 0};for(let X of F){if(X.role==="system"){Q(),q.push({role:"user",content:`<system>
3
- ${N(X.content)}
4
- </system>`});continue}if(X.role==="assistant"&&X.tool_calls&&X.tool_calls.length>0&&X.reasoningContent?.trim()){Q(),W=X;continue}if(X.role==="tool"&&W){let Z=W.tool_calls?.find((Y)=>Y.id===X.tool_call_id),$=Z?.type==="function"?Z.function:void 0;q.push({role:"user",content:`Tool result for ${X.name||$?.name||"tool"}${$?.arguments?`(${$.arguments})`:""}:
5
- ${N(X.content)}
6
-
7
- Continue from this tool result.`});continue}Q(),q.push(X)}return Q(),q}convertMessages(F){let q=[],W=this.shouldFlattenDeepSeekThinkingToolHistory()?this.flattenDeepSeekThinkingToolHistory(F):F;for(let Q of W)if(Q.role==="system")if(Array.isArray(Q.content)){let X=Q.content.find(($)=>$.type==="text"),Z={role:"system",content:N(Q.content)};if(X?.providerOptions)Z.providerOptions=X.providerOptions;q.push(Z)}else q.push({role:"system",content:Q.content});else if(Q.role==="user")if(Array.isArray(Q.content)){let X=Q.content.map((Z)=>{if(Z.type==="text"){let $={type:"text",text:Z.text};if(Z.providerOptions)$.providerOptions=Z.providerOptions;return $}return{type:"image",image:Z.image_url.url}});q.push({role:"user",content:X})}else q.push({role:"user",content:Q.content});else if(Q.role==="assistant")if(Q.tool_calls&&Q.tool_calls.length>0){let X=Q.tool_calls.map((J)=>{let j=J.function;return{type:"tool-call",toolCallId:J.id,toolName:j?.name||"",input:U(j?.arguments||"{}",{})}}),Z=N(Q.content),$=Q.reasoningContent?.trim()?[{type:"reasoning",text:Q.reasoningContent}]:[],Y=this.getThinkingReplayProviderOptions(Q.reasoningContent);if(Z){let J={role:"assistant",content:[...$,{type:"text",text:Z},...X]};if(Y)J.providerOptions=Y;q.push(J)}else if($.length>0){let J={role:"assistant",content:[...$,...X]};if(Y)J.providerOptions=Y;q.push(J)}else q.push({role:"assistant",content:X})}else if(Q.reasoningContent?.trim()){let X=N(Q.content),Z=[{type:"reasoning",text:Q.reasoningContent}];if(X)Z.push({type:"text",text:X});let $={role:"assistant",content:Z},Y=this.getThinkingReplayProviderOptions(Q.reasoningContent);if(Y)$.providerOptions=Y;q.push($)}else q.push({role:"assistant",content:N(Q.content)});else if(Q.role==="tool")q.push({role:"tool",content:[{type:"tool-result",toolCallId:Q.tool_call_id,toolName:Q.name||"unknown",output:{type:"text",value:N(Q.content)}}]});return q}convertTools(F){if(!F||F.length===0)return;let q={};for(let W of F)q[W.name]={description:W.description,inputSchema:T(W.parameters)};return q}convertToolCalls(F){return F.map((q)=>({id:q.toolCallId,type:"function",function:{name:q.toolName,arguments:JSON.stringify(q.args??q.input??{})}}))}convertUsage(F,q){if(!F)return;let W=F.promptTokens??F.inputTokens??0,Q=F.completionTokens??F.outputTokens??0,X={promptTokens:W,completionTokens:Q,totalTokens:F.totalTokens??W+Q};if(q?.anthropic){if(q.anthropic.cacheCreationInputTokens!==void 0)X.cacheCreationInputTokens=q.anthropic.cacheCreationInputTokens;if(q.anthropic.cacheReadInputTokens!==void 0)X.cacheReadInputTokens=q.anthropic.cacheReadInputTokens}return X}isFallbackableError(F){if(!(F instanceof Error))return!1;let W=F.message.toLowerCase().match(/status[:\s]*(\d{3})/),Q=W?parseInt(W[1],10):F.status;return Q!==void 0&&[429,529,503].includes(Q)}async chat(F,q,W){let Q=Date.now();B.debug("[VercelAIChatService] Starting chat request");let X=O(F),Z=this.convertMessages(X),$=this.convertTools(q);try{let Y=await H({model:this.model,messages:Z,tools:$,maxOutputTokens:this.config.maxOutputTokens,temperature:this.config.temperature??0,abortSignal:W,...{allowSystemInMessages:!0}}),J=Date.now()-Q;B.debug("[VercelAIChatService] Response received in",J,"ms");let j=Y.toolCalls&&Y.toolCalls.length>0?this.convertToolCalls(Y.toolCalls):void 0,w=Array.isArray(Y.reasoning)?Y.reasoning.map((_)=>_.text).join(""):void 0;return{content:Y.text,reasoningContent:w,toolCalls:j,usage:this.convertUsage(Y.usage,Y.providerMetadata),finishReason:Y.finishReason}}catch(Y){let J=Date.now()-Q;if(B.error("[VercelAIChatService] Chat failed after",J,"ms"),this.isFallbackableError(Y)&&this.config.fallbackModel){B.warn(`[VercelAIChatService] Switching to fallback model (non-stream): ${this.config.fallbackModel}`);let j={...this.config,model:this.config.fallbackModel},w=this.createModel(j);try{let _=await H({model:w,messages:Z,tools:$,maxOutputTokens:this.config.maxOutputTokens,temperature:this.config.temperature??0,abortSignal:W,...{allowSystemInMessages:!0}}),S=_.toolCalls&&_.toolCalls.length>0?this.convertToolCalls(_.toolCalls):void 0,G=Array.isArray(_.reasoning)?_.reasoning.map((I)=>I.text).join(""):void 0;return{content:_.text||"",reasoningContent:G,toolCalls:S,usage:this.convertUsage(_.usage,_.providerMetadata),finishReason:_.finishReason}}catch(_){throw Error(`Fallback model (${this.config.fallbackModel}) also failed: ${_ instanceof Error?_.message:_}`,{cause:Y})}}throw Y}}async*streamChat(F,q,W){let Q=Date.now();B.debug("[VercelAIChatService] Starting stream request");let X=O(F),Z=this.convertMessages(X),$=this.convertTools(q);try{let Y=K({model:this.model,messages:Z,tools:$,maxOutputTokens:this.config.maxOutputTokens,temperature:this.config.temperature??0,abortSignal:W,...{allowSystemInMessages:!0}});B.debug("[VercelAIChatService] Stream started");let J=0;for await(let w of Y.fullStream)switch(w.type){case"text-delta":yield{content:L(w)};break;case"reasoning-delta":yield{reasoningContent:L(w)};break;case"tool-call":yield{toolCalls:[{index:J++,id:w.toolCallId,type:"function",function:{name:w.toolName,arguments:JSON.stringify(w.args??w.input??{})}}]};break;case"finish":yield{finishReason:w.finishReason,usage:this.convertUsage(w.totalUsage,w.providerMetadata)};break}let j=Date.now()-Q;B.debug("[VercelAIChatService] Stream completed in",j,"ms")}catch(Y){let J=Date.now()-Q;if(B.error("[VercelAIChatService] Stream failed after",J,"ms"),this.isFallbackableError(Y)&&this.config.fallbackModel){B.warn(`[VercelAIChatService] Switching to fallback model: ${this.config.fallbackModel}`),yield{modelFallback:!0};let j={...this.config,model:this.config.fallbackModel},w=this.createModel(j);try{let _=K({model:w,messages:Z,tools:$,maxOutputTokens:this.config.maxOutputTokens,temperature:this.config.temperature??0,abortSignal:W,...{allowSystemInMessages:!0}}),S=0;for await(let G of _.fullStream)switch(G.type){case"text-delta":yield{content:L(G)};break;case"reasoning-delta":yield{reasoningContent:L(G)};break;case"tool-call":yield{toolCalls:[{index:S++,id:G.toolCallId,type:"function",function:{name:G.toolName,arguments:JSON.stringify(G.args??G.input??{})}}]};break;case"finish":yield{finishReason:G.finishReason,usage:this.convertUsage(G.totalUsage,G.providerMetadata)};break}return}catch(_){throw Error(`Fallback model (${this.config.fallbackModel}) also failed: ${_ instanceof Error?_.message:_}`,{cause:Y})}}throw Y}}getConfig(){return{...this.config}}updateConfig(F){B.debug("[VercelAIChatService] Updating configuration"),this.config={...this.config,...F},this.model=this.createModel(this.config),B.debug("[VercelAIChatService] Configuration updated")}}var M=R("Service");async function s(F){let q=F;if(q.provider){let W=V(q.provider);if(Object.keys(W).length>0)q={...q,customHeaders:{...W,...q.customHeaders}},M.debug(`Injected ${q.provider} specific headers:`,Object.keys(W))}return v(q)}function v(F){return new D(F)}
8
- export{C as ob,b as pb,f as qb,s as rb};
@@ -1,76 +0,0 @@
1
- import{Ia as KQ,Ka as A}from"./chunk-y5g06jmk.js";import{Bb as FQ}from"./chunk-set7v1rf.js";import{nanoid as rQ}from"nanoid";import{devtools as lQ,subscribeWithSelector as cQ}from"zustand/middleware";import{createStore as iQ}from"zustand/vanilla";var OQ={name:"ayu-dark",colors:{primary:"#ffcc66",secondary:"#bae67e",accent:"#73d0ff",success:"#bae67e",warning:"#ffcc66",error:"#ff3333",info:"#73d0ff",light:"#f0f0f0",dark:"#000000",muted:"#5c6773",highlight:"#2d323b",text:{primary:"#e6e1cf",secondary:"#bae67e",muted:"#5c6773",light:"#ffffff"},background:{primary:"#0f1419",secondary:"#14191f",dark:"#000000"},border:{light:"#2d323b",dark:"#000000"},syntax:{comment:"#5c6773",string:"#bae67e",number:"#ffcc66",keyword:"#ff8f40",function:"#73d0ff",variable:"#e6e1cf",operator:"#f29e74",type:"#73d0ff",tag:"#ff8f40",attr:"#ffd580",default:"#e6e1cf"}},spacing:{xs:0.25,sm:0.5,md:1,lg:1.5,xl:2},typography:{fontSize:{xs:0.75,sm:0.875,base:1,lg:1.125,xl:1.25,"2xl":1.5,"3xl":1.875},fontWeight:{light:300,normal:400,medium:500,semibold:600,bold:700}},borderRadius:{sm:0.125,base:0.25,lg:0.5,xl:0.75},boxShadow:{sm:"0 1px 2px 0 rgba(0, 0, 0, 0.2)",base:"0 1px 3px 0 rgba(0, 0, 0, 0.3), 0 1px 2px 0 rgba(0, 0, 0, 0.2)",lg:"0 10px 15px -3px rgba(0, 0, 0, 0.3), 0 4px 6px -2px rgba(0, 0, 0, 0.2)"}},xQ={name:"dracula",colors:{primary:"#bd93f9",secondary:"#ffb86c",accent:"#ff79c6",success:"#50fa7b",warning:"#f1fa8c",error:"#ff5555",info:"#8be9fd",light:"#f8f8f2",dark:"#282a36",muted:"#6272a4",highlight:"#44475a",text:{primary:"#f8f8f2",secondary:"#f1fa8c",muted:"#6272a4",light:"#ffffff"},background:{primary:"#282a36",secondary:"#44475a",dark:"#21222c"},border:{light:"#44475a",dark:"#000000"},syntax:{comment:"#6272a4",string:"#f1fa8c",number:"#bd93f9",keyword:"#ff79c6",function:"#50fa7b",variable:"#f8f8f2",operator:"#ff79c6",type:"#8be9fd",tag:"#ff79c6",attr:"#50fa7b",default:"#f8f8f2"}},spacing:{xs:0.25,sm:0.5,md:1,lg:1.5,xl:2},typography:{fontSize:{xs:0.75,sm:0.875,base:1,lg:1.125,xl:1.25,"2xl":1.5,"3xl":1.875},fontWeight:{light:300,normal:400,medium:500,semibold:600,bold:700}},borderRadius:{sm:0.125,base:0.25,lg:0.5,xl:0.75},boxShadow:{sm:"0 1px 2px 0 rgba(40, 42, 54, 0.2)",base:"0 1px 3px 0 rgba(40, 42, 54, 0.3), 0 1px 2px 0 rgba(40, 42, 54, 0.2)",lg:"0 10px 15px -3px rgba(40, 42, 54, 0.3), 0 4px 6px -2px rgba(40, 42, 54, 0.2)"}},BQ={name:"monokai",colors:{primary:"#66d9ef",secondary:"#a6e22e",accent:"#f92672",success:"#a6e22e",warning:"#e6db74",error:"#f92672",info:"#66d9ef",light:"#f8f8f2",dark:"#272822",muted:"#75715e",highlight:"#3e3d32",text:{primary:"#f8f8f2",secondary:"#e6db74",muted:"#75715e",light:"#ffffff"},background:{primary:"#272822",secondary:"#3e3d32",dark:"#1e1f1c"},border:{light:"#3e3d32",dark:"#000000"},syntax:{comment:"#75715e",string:"#e6db74",number:"#ae81ff",keyword:"#f92672",function:"#a6e22e",variable:"#f8f8f2",operator:"#f92672",type:"#66d9ef",tag:"#f92672",attr:"#a6e22e",default:"#f8f8f2"}},spacing:{xs:0.25,sm:0.5,md:1,lg:1.5,xl:2},typography:{fontSize:{xs:0.75,sm:0.875,base:1,lg:1.125,xl:1.25,"2xl":1.5,"3xl":1.875},fontWeight:{light:300,normal:400,medium:500,semibold:600,bold:700}},borderRadius:{sm:0.125,base:0.25,lg:0.5,xl:0.75},boxShadow:{sm:"0 1px 2px 0 rgba(39, 40, 34, 0.2)",base:"0 1px 3px 0 rgba(39, 40, 34, 0.3), 0 1px 2px 0 rgba(39, 40, 34, 0.2)",lg:"0 10px 15px -3px rgba(39, 40, 34, 0.3), 0 4px 6px -2px rgba(39, 40, 34, 0.2)"}},wQ={name:"nord",colors:{primary:"#88c0d0",secondary:"#81a1c1",accent:"#b48ead",success:"#a3be8c",warning:"#ebcb8b",error:"#bf616a",info:"#88c0d0",light:"#eceff4",dark:"#2e3440",muted:"#4c566a",highlight:"#434c5e",text:{primary:"#eceff4",secondary:"#d8dee9",muted:"#4c566a",light:"#ffffff"},background:{primary:"#2e3440",secondary:"#3b4252",dark:"#242933"},border:{light:"#434c5e",dark:"#000000"},syntax:{comment:"#616e88",string:"#a3be8c",number:"#b48ead",keyword:"#81a1c1",function:"#88c0d0",variable:"#d8dee9",operator:"#81a1c1",type:"#8fbcbb",tag:"#81a1c1",attr:"#8fbcbb",default:"#eceff4"}},spacing:{xs:0.25,sm:0.5,md:1,lg:1.5,xl:2},typography:{fontSize:{xs:0.75,sm:0.875,base:1,lg:1.125,xl:1.25,"2xl":1.5,"3xl":1.875},fontWeight:{light:300,normal:400,medium:500,semibold:600,bold:700}},borderRadius:{sm:0.125,base:0.25,lg:0.5,xl:0.75},boxShadow:{sm:"0 1px 2px 0 rgba(46, 52, 64, 0.2)",base:"0 1px 3px 0 rgba(46, 52, 64, 0.3), 0 1px 2px 0 rgba(46, 52, 64, 0.2)",lg:"0 10px 15px -3px rgba(46, 52, 64, 0.3), 0 4px 6px -2px rgba(46, 52, 64, 0.2)"}},_Q={name:"solarized-light",colors:{primary:"#268bd2",secondary:"#2aa198",accent:"#d33682",success:"#859900",warning:"#cb4b16",error:"#dc322f",info:"#268bd2",light:"#fdf6e3",dark:"#073642",muted:"#93a1a1",highlight:"#eee8d5",text:{primary:"#586e75",secondary:"#657b83",muted:"#93a1a1",light:"#002b36"},background:{primary:"#fdf6e3",secondary:"#eee8d5",dark:"#073642"},border:{light:"#eee8d5",dark:"#073642"},syntax:{comment:"#93a1a1",string:"#2aa198",number:"#d33682",keyword:"#859900",function:"#268bd2",variable:"#657b83",operator:"#859900",type:"#b58900",tag:"#268bd2",attr:"#93a1a1",default:"#657b83"}},spacing:{xs:0.25,sm:0.5,md:1,lg:1.5,xl:2},typography:{fontSize:{xs:0.75,sm:0.875,base:1,lg:1.125,xl:1.25,"2xl":1.5,"3xl":1.875},fontWeight:{light:300,normal:400,medium:500,semibold:600,bold:700}},borderRadius:{sm:0.125,base:0.25,lg:0.5,xl:0.75},boxShadow:{sm:"0 1px 2px 0 rgba(253, 246, 227, 0.2)",base:"0 1px 3px 0 rgba(253, 246, 227, 0.3), 0 1px 2px 0 rgba(253, 246, 227, 0.2)",lg:"0 10px 15px -3px rgba(253, 246, 227, 0.3), 0 4px 6px -2px rgba(253, 246, 227, 0.2)"}},AQ={name:"solarized-dark",colors:{primary:"#268bd2",secondary:"#2aa198",accent:"#d33682",success:"#859900",warning:"#b58900",error:"#dc322f",info:"#268bd2",light:"#fdf6e3",dark:"#073642",muted:"#586e75",highlight:"#073642",text:{primary:"#839496",secondary:"#93a1a1",muted:"#586e75",light:"#fdf6e3"},background:{primary:"#002b36",secondary:"#073642",dark:"#001f29"},border:{light:"#073642",dark:"#000000"},syntax:{comment:"#586e75",string:"#2aa198",number:"#d33682",keyword:"#859900",function:"#268bd2",variable:"#839496",operator:"#859900",type:"#b58900",tag:"#268bd2",attr:"#93a1a1",default:"#839496"}},spacing:{xs:0.25,sm:0.5,md:1,lg:1.5,xl:2},typography:{fontSize:{xs:0.75,sm:0.875,base:1,lg:1.125,xl:1.25,"2xl":1.5,"3xl":1.875},fontWeight:{light:300,normal:400,medium:500,semibold:600,bold:700}},borderRadius:{sm:0.125,base:0.25,lg:0.5,xl:0.75},boxShadow:{sm:"0 1px 2px 0 rgba(0, 43, 54, 0.2)",base:"0 1px 3px 0 rgba(0, 43, 54, 0.3), 0 1px 2px 0 rgba(0, 43, 54, 0.2)",lg:"0 10px 15px -3px rgba(0, 43, 54, 0.3), 0 4px 6px -2px rgba(0, 43, 54, 0.2)"}},DQ={name:"tokyo-night",colors:{primary:"#7aa2f7",secondary:"#7dcfff",accent:"#bb9af7",success:"#9ece6a",warning:"#e0af68",error:"#f7768e",info:"#7aa2f7",light:"#c0caf5",dark:"#1a1b26",muted:"#565f89",highlight:"#292e42",text:{primary:"#a9b1d6",secondary:"#c0caf5",muted:"#565f89",light:"#ffffff"},background:{primary:"#1a1b26",secondary:"#292e42",dark:"#16161e"},border:{light:"#292e42",dark:"#000000"},syntax:{comment:"#565f89",string:"#9ece6a",number:"#ff9e64",keyword:"#bb9af7",function:"#7aa2f7",variable:"#c0caf5",operator:"#89ddff",type:"#7dcfff",tag:"#f7768e",attr:"#7aa2f7",default:"#a9b1d6"}},spacing:{xs:0.25,sm:0.5,md:1,lg:1.5,xl:2},typography:{fontSize:{xs:0.75,sm:0.875,base:1,lg:1.125,xl:1.25,"2xl":1.5,"3xl":1.875},fontWeight:{light:300,normal:400,medium:500,semibold:600,bold:700}},borderRadius:{sm:0.125,base:0.25,lg:0.5,xl:0.75},boxShadow:{sm:"0 1px 2px 0 rgba(26, 27, 38, 0.2)",base:"0 1px 3px 0 rgba(26, 27, 38, 0.3), 0 1px 2px 0 rgba(26, 27, 38, 0.2)",lg:"0 10px 15px -3px rgba(26, 27, 38, 0.3), 0 4px 6px -2px rgba(26, 27, 38, 0.2)"}},LQ={name:"github",colors:{primary:"#0969da",secondary:"#8250df",accent:"#bc4c00",success:"#1a7f37",warning:"#bc4c00",error:"#d1242f",info:"#0969da",light:"#f6f8fa",dark:"#24292f",muted:"#6e7781",highlight:"#ddf4ff",text:{primary:"#24292f",secondary:"#57606a",muted:"#6e7781",light:"#ffffff"},background:{primary:"#ffffff",secondary:"#f6f8fa",dark:"#24292f"},border:{light:"#d0d7de",dark:"#24292f"},syntax:{comment:"#6e7781",string:"#0a3069",number:"#0550ae",keyword:"#cf222e",function:"#8250df",variable:"#24292f",operator:"#cf222e",type:"#0550ae",tag:"#116329",attr:"#0550ae",default:"#24292f"}},spacing:{xs:0.25,sm:0.5,md:1,lg:1.5,xl:2},typography:{fontSize:{xs:0.75,sm:0.875,base:1,lg:1.125,xl:1.25,"2xl":1.5,"3xl":1.875},fontWeight:{light:300,normal:400,medium:500,semibold:600,bold:700}},borderRadius:{sm:0.125,base:0.25,lg:0.5,xl:0.75},boxShadow:{sm:"0 1px 2px 0 rgba(255, 255, 255, 0.2)",base:"0 1px 3px 0 rgba(255, 255, 255, 0.3), 0 1px 2px 0 rgba(255, 255, 255, 0.2)",lg:"0 10px 15px -3px rgba(255, 255, 255, 0.3), 0 4px 6px -2px rgba(255, 255, 255, 0.2)"}},vQ={name:"gruvbox",colors:{primary:"#83a598",secondary:"#8ec07c",accent:"#d3869b",success:"#b8bb26",warning:"#fabd2f",error:"#fb4934",info:"#83a598",light:"#fbf1c7",dark:"#282828",muted:"#928374",highlight:"#3c3836",text:{primary:"#ebdbb2",secondary:"#d5c4a1",muted:"#928374",light:"#ffffff"},background:{primary:"#282828",secondary:"#3c3836",dark:"#1d2021"},border:{light:"#3c3836",dark:"#000000"},syntax:{comment:"#928374",string:"#b8bb26",number:"#d3869b",keyword:"#fb4934",function:"#8ec07c",variable:"#ebdbb2",operator:"#fe8019",type:"#fabd2f",tag:"#fb4934",attr:"#b8bb26",default:"#ebdbb2"}},spacing:{xs:0.25,sm:0.5,md:1,lg:1.5,xl:2},typography:{fontSize:{xs:0.75,sm:0.875,base:1,lg:1.125,xl:1.25,"2xl":1.5,"3xl":1.875},fontWeight:{light:300,normal:400,medium:500,semibold:600,bold:700}},borderRadius:{sm:0.125,base:0.25,lg:0.5,xl:0.75},boxShadow:{sm:"0 1px 2px 0 rgba(40, 40, 40, 0.2)",base:"0 1px 3px 0 rgba(40, 40, 40, 0.3), 0 1px 2px 0 rgba(40, 40, 40, 0.2)",lg:"0 10px 15px -3px rgba(40, 40, 40, 0.3), 0 4px 6px -2px rgba(40, 40, 40, 0.2)"}},EQ={name:"one-dark",colors:{primary:"#61afef",secondary:"#c678dd",accent:"#e5c07b",success:"#98c379",warning:"#e5c07b",error:"#e06c75",info:"#56b6c2",light:"#abb2bf",dark:"#282c34",muted:"#5c6370",highlight:"#3e4451",text:{primary:"#abb2bf",secondary:"#c6c8d0",muted:"#5c6370",light:"#ffffff"},background:{primary:"#282c34",secondary:"#3e4451",dark:"#21252b"},border:{light:"#3e4451",dark:"#000000"},syntax:{comment:"#5c6370",string:"#98c379",number:"#d19a66",keyword:"#c678dd",function:"#61afef",variable:"#e06c75",operator:"#56b6c2",type:"#e5c07b",tag:"#e06c75",attr:"#d19a66",default:"#abb2bf"}},spacing:{xs:0.25,sm:0.5,md:1,lg:1.5,xl:2},typography:{fontSize:{xs:0.75,sm:0.875,base:1,lg:1.125,xl:1.25,"2xl":1.5,"3xl":1.875},fontWeight:{light:300,normal:400,medium:500,semibold:600,bold:700}},borderRadius:{sm:0.125,base:0.25,lg:0.5,xl:0.75},boxShadow:{sm:"0 1px 2px 0 rgba(40, 44, 52, 0.2)",base:"0 1px 3px 0 rgba(40, 44, 52, 0.3), 0 1px 2px 0 rgba(40, 44, 52, 0.2)",lg:"0 10px 15px -3px rgba(40, 44, 52, 0.3), 0 4px 6px -2px rgba(40, 44, 52, 0.2)"}},yQ={name:"catppuccin",colors:{primary:"#89b4fa",secondary:"#cba6f7",accent:"#f5c2e7",success:"#a6e3a1",warning:"#f9e2af",error:"#f38ba8",info:"#89dceb",light:"#cdd6f4",dark:"#11111b",muted:"#6c7086",highlight:"#181825",text:{primary:"#cdd6f4",secondary:"#bac2de",muted:"#6c7086",light:"#ffffff"},background:{primary:"#1e1e2e",secondary:"#181825",dark:"#11111b"},border:{light:"#181825",dark:"#000000"},syntax:{comment:"#6c7086",string:"#a6e3a1",number:"#fab387",keyword:"#cba6f7",function:"#89b4fa",variable:"#cdd6f4",operator:"#89dceb",type:"#f5c2e7",tag:"#f38ba8",attr:"#89b4fa",default:"#cdd6f4"}},spacing:{xs:0.25,sm:0.5,md:1,lg:1.5,xl:2},typography:{fontSize:{xs:0.75,sm:0.875,base:1,lg:1.125,xl:1.25,"2xl":1.5,"3xl":1.875},fontWeight:{light:300,normal:400,medium:500,semibold:600,bold:700}},borderRadius:{sm:0.125,base:0.25,lg:0.5,xl:0.75},boxShadow:{sm:"0 1px 2px 0 rgba(30, 30, 46, 0.2)",base:"0 1px 3px 0 rgba(30, 30, 46, 0.3), 0 1px 2px 0 rgba(30, 30, 46, 0.2)",lg:"0 10px 15px -3px rgba(30, 30, 46, 0.3), 0 4px 6px -2px rgba(30, 30, 46, 0.2)"}},CQ={name:"rose-pine",colors:{primary:"#9ccfd8",secondary:"#c4a7e7",accent:"#f6c177",success:"#31748f",warning:"#f6c177",error:"#eb6f92",info:"#9ccfd8",light:"#e0def4",dark:"#191724",muted:"#6e6a86",highlight:"#1f1d2e",text:{primary:"#e0def4",secondary:"#cecacd",muted:"#6e6a86",light:"#ffffff"},background:{primary:"#191724",secondary:"#1f1d2e",dark:"#12101a"},border:{light:"#1f1d2e",dark:"#000000"},syntax:{comment:"#6e6a86",string:"#9ccfd8",number:"#ea9a97",keyword:"#c4a7e7",function:"#31748f",variable:"#e0def4",operator:"#f6c177",type:"#9ccfd8",tag:"#eb6f92",attr:"#f6c177",default:"#e0def4"}},spacing:{xs:0.25,sm:0.5,md:1,lg:1.5,xl:2},typography:{fontSize:{xs:0.75,sm:0.875,base:1,lg:1.125,xl:1.25,"2xl":1.5,"3xl":1.875},fontWeight:{light:300,normal:400,medium:500,semibold:600,bold:700}},borderRadius:{sm:0.125,base:0.25,lg:0.5,xl:0.75},boxShadow:{sm:"0 1px 2px 0 rgba(25, 23, 36, 0.2)",base:"0 1px 3px 0 rgba(25, 23, 36, 0.3), 0 1px 2px 0 rgba(25, 23, 36, 0.2)",lg:"0 10px 15px -3px rgba(25, 23, 36, 0.3), 0 4px 6px -2px rgba(25, 23, 36, 0.2)"}},PQ={name:"kanagawa",colors:{primary:"#8ba4b0",secondary:"#a292a3",accent:"#c47fd5",success:"#76946a",warning:"#c0a36e",error:"#c34043",info:"#7e9cd8",light:"#dcd7ba",dark:"#1f1f28",muted:"#727169",highlight:"#2a2a37",text:{primary:"#dcd7ba",secondary:"#c8c093",muted:"#727169",light:"#ffffff"},background:{primary:"#1f1f28",secondary:"#2a2a37",dark:"#16161d"},border:{light:"#2a2a37",dark:"#000000"},syntax:{comment:"#727169",string:"#98bb6c",number:"#d27e99",keyword:"#957fb8",function:"#7e9cd8",variable:"#dcd7ba",operator:"#c0a36e",type:"#7aa89f",tag:"#c34043",attr:"#7fb4ca",default:"#dcd7ba"}},spacing:{xs:0.25,sm:0.5,md:1,lg:1.5,xl:2},typography:{fontSize:{xs:0.75,sm:0.875,base:1,lg:1.125,xl:1.25,"2xl":1.5,"3xl":1.875},fontWeight:{light:300,normal:400,medium:500,semibold:600,bold:700}},borderRadius:{sm:0.125,base:0.25,lg:0.5,xl:0.75},boxShadow:{sm:"0 1px 2px 0 rgba(31, 31, 40, 0.2)",base:"0 1px 3px 0 rgba(31, 31, 40, 0.3), 0 1px 2px 0 rgba(31, 31, 40, 0.2)",lg:"0 10px 15px -3px rgba(31, 31, 40, 0.3), 0 4px 6px -2px rgba(31, 31, 40, 0.2)"}},a=[{id:"ayu-dark",label:"Ayu Dark",theme:OQ,tags:["dark","popular"]},{id:"dracula",label:"Dracula",theme:xQ,tags:["dark","popular"]},{id:"monokai",label:"Monokai",theme:BQ,tags:["dark","classic"]},{id:"nord",label:"Nord",theme:wQ,tags:["dark","minimal"]},{id:"solarized-light",label:"Solarized Light",theme:_Q,tags:["light"]},{id:"solarized-dark",label:"Solarized Dark",theme:AQ,tags:["dark"]},{id:"tokyo-night",label:"Tokyo Night",theme:DQ,tags:["dark","popular"]},{id:"github",label:"GitHub",theme:LQ,tags:["light","minimal"]},{id:"gruvbox",label:"Gruvbox",theme:vQ,tags:["dark","warm"]},{id:"one-dark",label:"One Dark",theme:EQ,tags:["dark","popular"]},{id:"catppuccin",label:"Catppuccin",theme:yQ,tags:["dark","pastel"]},{id:"rose-pine",label:"Rose Pine",theme:CQ,tags:["dark","elegant"]},{id:"kanagawa",label:"Kanagawa",theme:PQ,tags:["dark","japanese"]}];var t={primary:"#0066cc",secondary:"#6c757d",accent:"#e83e8c",success:"#28a745",warning:"#ffc107",error:"#dc3545",info:"#17a2b8",light:"#f8f9fa",dark:"#343a40",muted:"#6c757d",highlight:"#fff3cd",text:{primary:"#212529",secondary:"#6c757d",muted:"#6c757d",light:"#ffffff"},background:{primary:"#ffffff",secondary:"#f8f9fa",dark:"#343a40"},border:{light:"#dee2e6",dark:"#495057"},syntax:{comment:"#6c757d",string:"#28a745",number:"#e83e8c",keyword:"#007bff",function:"#17a2b8",variable:"#495057",operator:"#ffc107",type:"#007bff",tag:"#dc3545",attr:"#ffc107",default:"#212529"}},p={name:"default",colors:t,spacing:{xs:0.25,sm:0.5,md:1,lg:1.5,xl:2},typography:{fontSize:{xs:0.75,sm:0.875,base:1,lg:1.125,xl:1.25,"2xl":1.5,"3xl":1.875},fontWeight:{light:300,normal:400,medium:500,semibold:600,bold:700}},borderRadius:{sm:0.125,base:0.25,lg:0.5,xl:0.75},boxShadow:{sm:"0 1px 2px 0 rgba(0, 0, 0, 0.05)",base:"0 1px 3px 0 rgba(0, 0, 0, 0.1), 0 1px 2px 0 rgba(0, 0, 0, 0.06)",lg:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05)"}},RQ={...p,name:"dark",colors:{...t,text:{primary:"#ffffff",secondary:"#e2e8f0",muted:"#94a3b8",light:"#000000"},background:{primary:"#1e293b",secondary:"#334155",dark:"#0f172a"},border:{light:"#475569",dark:"#64748b"},syntax:{comment:"#94a3b8",string:"#34d399",number:"#f472b6",keyword:"#60a5fa",function:"#06b6d4",variable:"#e2e8f0",operator:"#fbbf24",type:"#60a5fa",tag:"#fb7185",attr:"#fbbf24",default:"#ffffff"}}};class e{currentTheme=p;themes=new Map;constructor(){this.themes.set("default",p),this.themes.set("dark",RQ);for(let Q of a)this.themes.set(Q.id,Q.theme)}setTheme(Q){let Z=this.themes.get(Q);if(Z)this.currentTheme=Z;else throw Error(`Theme '${Q}' not found`)}getTheme(){return this.currentTheme}getAvailableThemes(){return Array.from(this.themes.keys())}getCurrentThemeName(){return this.currentTheme.name}getThemeByName(Q){return this.themes.get(Q)}hasTheme(Q){return this.themes.has(Q)}}var QQ=new e;var IQ={initializationStatus:"idle",initializationError:null,activeModal:"none",sessionSelectorData:void 0,modelEditorTarget:null,tasks:[],awaitingSecondCtrlC:!1,thinkingModeEnabled:!1,subagentProgress:null},g=(Q)=>({...IQ,actions:{setInitializationStatus:(Z)=>{Q((X)=>({app:{...X.app,initializationStatus:Z}}))},setInitializationError:(Z)=>{Q((X)=>({app:{...X.app,initializationError:Z}}))},setActiveModal:(Z)=>{Q((X)=>({app:{...X.app,activeModal:Z}}))},showSessionSelector:(Z)=>{Q((X)=>({app:{...X.app,activeModal:"sessionSelector",sessionSelectorData:Z}}))},showModelEditWizard:(Z)=>{Q((X)=>({app:{...X.app,activeModal:"modelEditWizard",modelEditorTarget:Z}}))},closeModal:()=>{Q((Z)=>({app:{...Z.app,activeModal:"none",sessionSelectorData:void 0,modelEditorTarget:null}}))},setTasks:(Z)=>{Q((X)=>({app:{...X.app,tasks:Z}}))},updateTask:(Z)=>{Q((X)=>({app:{...X.app,tasks:X.app.tasks.map(($)=>$.id===Z.id?Z:$)}}))},setAwaitingSecondCtrlC:(Z)=>{Q((X)=>({app:{...X.app,awaitingSecondCtrlC:Z}}))},setThinkingModeEnabled:(Z)=>{Q((X)=>({app:{...X.app,thinkingModeEnabled:Z}}))},toggleThinkingMode:()=>{Q((Z)=>({app:{...Z.app,thinkingModeEnabled:!Z.app.thinkingModeEnabled}}))},startSubagentProgress:(Z,X,$)=>{Q((Y)=>({app:{...Y.app,subagentProgress:{id:Z,type:X,description:$,status:"running",startTime:Date.now()}}}))},updateSubagentTool:(Z)=>{Q((X)=>{if(!X.app.subagentProgress)return X;return{app:{...X.app,subagentProgress:{...X.app.subagentProgress,currentTool:Z}}}})},completeSubagentProgress:(Z)=>{Q((X)=>{if(!X.app.subagentProgress)return X;return{app:{...X.app,subagentProgress:{...X.app.subagentProgress,status:Z?"completed":"failed",currentTool:void 0}}}}),setTimeout(()=>{Q((X)=>({app:{...X.app,subagentProgress:null}}))},1500)}}});var TQ={isProcessing:!1,abortController:null,pendingCommands:[]},d=(Q,Z)=>({...TQ,actions:{setProcessing:(X)=>{Q(($)=>({command:{...$.command,isProcessing:X}}))},createAbortController:()=>{let X=Z().command.abortController;if(X&&!X.signal.aborted)X.abort("interrupted-by-new-command");let $=new AbortController;return Q((Y)=>({command:{...Y.command,abortController:$}})),$},getAbortController:()=>{return Z().command.abortController},clearAbortController:(X)=>{let $=Z().command.abortController;if(X!==void 0&&$!==X)return;Q((Y)=>({command:{...Y.command,abortController:null}}))},abort:(X)=>{let{abortController:$}=Z().command;if($&&!$.signal.aborted)$.abort(X??"user-cancel");Q((Y)=>({command:{...Y.command,isProcessing:!1,pendingCommands:[]}}))},enqueueCommand:(X)=>{Q(($)=>({command:{...$.command,pendingCommands:[...$.command.pendingCommands,X]}}))},dequeueCommand:()=>{let{pendingCommands:X}=Z().command;if(X.length===0)return;let[$,...Y]=X;return Q((V)=>({command:{...V.command,pendingCommands:Y}})),$},clearQueue:()=>{Q((X)=>({command:{...X.command,pendingCommands:[]}}))}}});var MQ={config:null},m=(Q)=>({...MQ,actions:{setConfig:(Z)=>{Q((X)=>({config:{...X.config,config:Z}}))},updateConfig:(Z)=>{Q((X)=>{if(!X.config.config)throw Error(`[ConfigSlice] Config not initialized. Cannot update: ${JSON.stringify(Z)}`);return{config:{...X.config,config:{...X.config.config,...Z}}}})}}});var bQ={currentFocus:"main-input",previousFocus:null},r=(Q)=>({...bQ,actions:{setFocus:(Z)=>{Q((X)=>({focus:{...X.focus,currentFocus:Z,previousFocus:X.focus.currentFocus}}))},restorePreviousFocus:()=>{Q((Z)=>({focus:{...Z.focus,currentFocus:Z.focus.previousFocus||"main-input",previousFocus:null}}))}}});import{nanoid as fQ}from"nanoid";var W={codeBlock:/^```(\w+)?\s*$/,heading:/^ *(#{1,4}) +(.+)/,blockquote:/^(>+)\s?(.*)/,ulItem:/^([ \t]*)([-*+]) +(.+)/,olItem:/^([ \t]*)(\d+)\. +(.+)/,hr:/^ *([-*_] *){3,} *$/,table:/^\|(.+)\|$/,tableSeparator:/^\|[\s]*:?-+:?[\s]*(\|[\s]*:?-+:?[\s]*)+\|?$/,diffStart:/^<<<DIFF>>>$/,diffEnd:/^<<<\/DIFF>>>$/,commandMessage:/<command-message>(.*?)<\/command-message>/};function $X(Q){let Z=[],X=Q.split(/\r?\n/),$=!1,Y=[],V=null,J=0,U=!1,G=[],z=[],K=!1,E=[],y=!1,B=[],H=0,j=!0;for(let D=0;D<X.length;D++){let O=X[D];if(K){if(O.match(W.diffEnd)){try{let w=JSON.parse(E.join(`
2
- `));Z.push({type:"diff",content:"",diffData:{patch:w.patch,startLine:w.startLine,matchLine:w.matchLine}})}catch(w){Z.push({type:"text",content:E.join(`
3
- `)})}K=!1,E=[],j=!1;continue}E.push(O);continue}if(O.match(W.diffStart)){K=!0,E=[],j=!1;continue}if($){let w=O.match(W.codeBlock),L=O.trim()==="```";if(w&&w[1])J++,Y.push(O);else if(L)if(J>0)J--,Y.push(O);else{let qQ=Y.join(`
4
- `);Z.push({type:"code",content:qQ,language:V||void 0}),$=!1,Y=[],V=null,J=0,j=!1}else Y.push(O);continue}let n=O.match(W.codeBlock);if(n){$=!0,V=n[1]||null,J=0,j=!1;continue}let T=O.match(W.table),WQ=O.match(W.tableSeparator);if(T&&!U){if(D+1<X.length){if(X[D+1].match(W.tableSeparator)){U=!0,G=T[1].split("|").map((L)=>L.trim()).filter((L)=>L.length>0),z=[],j=!1;continue}}}if(U&&WQ)continue;if(U&&T){let w=T[1].split("|").map((L)=>L.trim()).filter((L)=>L.length>0);while(w.length<G.length)w.push("");if(w.length>G.length)w.length=G.length;z.push(w);continue}if(U&&!T){if(G.length>0&&z.length>0)Z.push({type:"table",content:"",tableData:{headers:G,rows:z}});U=!1,G=[],z=[]}let S=O.match(W.blockquote);if(S){let w=S[1].length,L=S[2]||"";if(y&&w===H)B.push(L);else{if(y)Z.push({type:"blockquote",content:B.join(`
5
- `),blockquoteLevel:H,blockquoteLines:[...B]});y=!0,H=w,B=[L]}j=!1;continue}if(y)Z.push({type:"blockquote",content:B.join(`
6
- `),blockquoteLevel:H,blockquoteLines:[...B]}),y=!1,B=[],H=0;let u=O.match(W.heading);if(u){Z.push({type:"heading",content:u[2],level:u[1].length}),j=!1;continue}let h=O.match(W.ulItem);if(h){Z.push({type:"list",content:h[3],listType:"ul",marker:h[2],indentation:h[1].length}),j=!1;continue}let k=O.match(W.olItem);if(k){Z.push({type:"list",content:k[3],listType:"ol",marker:k[2],indentation:k[1].length}),j=!1;continue}if(O.match(W.hr)){Z.push({type:"hr",content:""}),j=!1;continue}if(O.trim().length===0){if(!j)Z.push({type:"empty",content:""}),j=!0;continue}let s=O.match(W.commandMessage);if(s){Z.push({type:"command-message",content:s[1]}),j=!1;continue}Z.push({type:"text",content:O}),j=!1}if($){let D=Y.join(`
7
- `);Z.push({type:"code",content:D,language:V||void 0})}if(U&&G.length>0&&z.length>0)Z.push({type:"table",content:"",tableData:{headers:G,rows:z}});if(y&&B.length>0)Z.push({type:"blockquote",content:B.join(`
8
- `),blockquoteLevel:H,blockquoteLines:[...B]});while(Z.length>0&&Z[Z.length-1].type==="empty")Z.pop();return Z}var C=new Map;function NQ(){return{inCodeBlock:!1,codeBlockContent:[],codeBlockLang:null,codeBlockDepth:0,inTable:!1,tableHeaders:[],tableRows:[],inDiff:!1,diffContent:[],inBlockquote:!1,blockquoteLines:[],blockquoteLevel:0,lastLineEmpty:!0,pendingTableHeader:null}}function hQ(Q){let Z=C.get(Q);if(Z)return Z;let X={state:NQ(),blocks:[],pendingLine:"",finalized:!1};return C.set(Q,X),X}function XQ(Q){return Q.endsWith("\r")?Q.slice(0,-1):Q}function ZQ(Q,Z){if(Q.tableHeaders.length>0&&Q.tableRows.length>0)Z.push({type:"table",content:"",tableData:{headers:Q.tableHeaders,rows:Q.tableRows}});Q.inTable=!1,Q.tableHeaders=[],Q.tableRows=[]}function l(Q,Z){if(Q.blockquoteLines.length>0)Z.push({type:"blockquote",content:Q.blockquoteLines.join(`
9
- `),blockquoteLevel:Q.blockquoteLevel,blockquoteLines:[...Q.blockquoteLines]});Q.inBlockquote=!1,Q.blockquoteLines=[],Q.blockquoteLevel=0}function $Q(Q,Z){let X=Q.codeBlockContent.join(`
10
- `);Z.push({type:"code",content:X,language:Q.codeBlockLang||void 0}),Q.inCodeBlock=!1,Q.codeBlockContent=[],Q.codeBlockLang=null,Q.codeBlockDepth=0,Q.lastLineEmpty=!1}function c(Q,Z,X=!0){let{state:$,blocks:Y}=Z;if($.pendingTableHeader!==null){if(Q.match(W.tableSeparator)){$.inTable=!0,$.tableHeaders=$.pendingTableHeader.slice(1,-1).split("|").map((H)=>H.trim()).filter((H)=>H.length>0),$.tableRows=[],$.pendingTableHeader=null,$.lastLineEmpty=!1;return}Y.push({type:"text",content:$.pendingTableHeader}),$.pendingTableHeader=null,$.lastLineEmpty=!1}if($.inDiff){if(Q.match(W.diffEnd)){try{let H=JSON.parse($.diffContent.join(`
11
- `));Y.push({type:"diff",content:"",diffData:{patch:H.patch,startLine:H.startLine,matchLine:H.matchLine}})}catch(H){Y.push({type:"text",content:$.diffContent.join(`
12
- `)})}$.inDiff=!1,$.diffContent=[],$.lastLineEmpty=!1;return}$.diffContent.push(Q);return}if(Q.match(W.diffStart)){$.inDiff=!0,$.diffContent=[],$.lastLineEmpty=!1;return}if($.inCodeBlock){let H=Q.match(W.codeBlock),j=Q.trim()==="```";if(H&&H[1])$.codeBlockDepth++,$.codeBlockContent.push(Q);else if(j)if($.codeBlockDepth>0)$.codeBlockDepth--,$.codeBlockContent.push(Q);else $Q($,Y);else $.codeBlockContent.push(Q);return}let V=Q.match(W.codeBlock);if(V){$.inCodeBlock=!0,$.codeBlockLang=V[1]||null,$.codeBlockDepth=0,$.lastLineEmpty=!1;return}let J=Q.match(W.table),U=Q.match(W.tableSeparator);if(J&&!$.inTable){$.pendingTableHeader=Q;return}if($.inTable&&U)return;if($.inTable&&J){let H=J[1].split("|").map((j)=>j.trim()).filter((j)=>j.length>0);while(H.length<$.tableHeaders.length)H.push("");if(H.length>$.tableHeaders.length)H.length=$.tableHeaders.length;$.tableRows.push(H);return}if($.inTable&&!J){if(ZQ($,Y),X){c(Q,Z,!1);return}}let G=Q.match(W.blockquote);if(G){let H=G[1].length,j=G[2]||"";if($.inBlockquote&&H===$.blockquoteLevel)$.blockquoteLines.push(j);else{if($.inBlockquote)l($,Y);$.inBlockquote=!0,$.blockquoteLevel=H,$.blockquoteLines=[j]}$.lastLineEmpty=!1;return}if($.inBlockquote)l($,Y);let z=Q.match(W.heading);if(z){Y.push({type:"heading",content:z[2],level:z[1].length}),$.lastLineEmpty=!1;return}let K=Q.match(W.ulItem);if(K){Y.push({type:"list",content:K[3],listType:"ul",marker:K[2],indentation:K[1].length}),$.lastLineEmpty=!1;return}let E=Q.match(W.olItem);if(E){Y.push({type:"list",content:E[3],listType:"ol",marker:E[2],indentation:E[1].length}),$.lastLineEmpty=!1;return}if(Q.match(W.hr)){Y.push({type:"hr",content:""}),$.lastLineEmpty=!1;return}if(Q.trim().length===0){if(!$.lastLineEmpty)Y.push({type:"empty",content:""}),$.lastLineEmpty=!0;return}let B=Q.match(W.commandMessage);if(B){Y.push({type:"command-message",content:B[1]}),$.lastLineEmpty=!1;return}Y.push({type:"text",content:Q}),$.lastLineEmpty=!1}function JX(Q,Z){if(!Q||!Z)return;let X=hQ(Q);if(X.finalized)return;let $=X.pendingLine+Z,Y=$.split(`
13
- `),V=$.endsWith(`
14
- `),J=V?Y:Y.slice(0,-1);X.pendingLine=V?"":Y[Y.length-1]??"";for(let U of J)c(XQ(U),X)}function UX(Q){let Z=C.get(Q);if(!Z||Z.finalized)return;if(Z.pendingLine)c(XQ(Z.pendingLine),Z),Z.pendingLine="";if(Z.state.pendingTableHeader!==null)Z.blocks.push({type:"text",content:Z.state.pendingTableHeader}),Z.state.pendingTableHeader=null;if(Z.state.inCodeBlock)$Q(Z.state,Z.blocks);if(Z.state.inTable)ZQ(Z.state,Z.blocks);if(Z.state.inBlockquote)l(Z.state,Z.blocks);if(Z.state.inDiff)Z.blocks.push({type:"text",content:Z.state.diffContent.join(`
15
- `)}),Z.state.inDiff=!1,Z.state.diffContent=[];while(Z.blocks.length>0&&Z.blocks[Z.blocks.length-1].type==="empty")Z.blocks.pop();Z.finalized=!0}function GX(Q){let Z=C.get(Q);if(!Z||!Z.finalized)return null;return Z.blocks}function jX(Q){let Z=C.get(Q);if(!Z)return null;return Z.blocks}function kQ(Q){let Z=C.get(Q);if(!Z)return null;let X=[],$=Z.state;if($.inDiff)X.push("<<<DIFF>>>"),X.push(...$.diffContent);else if($.inCodeBlock){let Y=$.codeBlockLang?`\`\`\`${$.codeBlockLang}`:"```";X.push(Y),X.push(...$.codeBlockContent)}else if($.inTable){if($.tableHeaders.length>0){X.push(`| ${$.tableHeaders.join(" | ")} |`),X.push(`| ${$.tableHeaders.map(()=>"---").join(" | ")} |`);for(let Y of $.tableRows)X.push(`| ${Y.join(" | ")} |`)}}else if($.inBlockquote){let Y=">".repeat($.blockquoteLevel)+" ";for(let V of $.blockquoteLines)X.push(Y+V)}else if($.pendingTableHeader)X.push($.pendingTableHeader);if(Z.pendingLine)X.push(Z.pendingLine);return X.length>0?X:null}function HX(Q){let Z=C.get(Q);if(!Z)return null;let X="text";if(Z.state.inDiff)X="diff";else if(Z.state.inCodeBlock)X="code";else if(Z.state.inTable||Z.state.pendingTableHeader)X="table";let $=kQ(Q);if(!$||$.length===0)return null;return{lines:$,mode:X}}function zX(Q){C.delete(Q)}function f(){C.clear()}var YQ=2000,M=[];function SQ(){let Q=M;return M=[],Q}var JQ={inputTokens:0,outputTokens:0,totalTokens:0,maxContextTokens:200000},VQ={sessionId:fQ(),messages:[],restoredContextMessages:null,restoredVisibleMessageCount:0,isCompacting:!1,currentCommand:null,error:null,isActive:!0,tokenUsage:{...JQ},currentThinkingContent:null,thinkingExpanded:!1,clearCount:0,historyExpanded:!1,expandedMessageCount:100,currentStreamingMessageId:null,currentStreamingChunks:[],currentStreamingLines:[],currentStreamingTail:"",currentStreamingLineCount:0,currentStreamingVersion:0,finalizingStreamingMessageId:null},i=(Q,Z)=>({...VQ,actions:{addMessage:(X)=>{Q(($)=>({session:{...$.session,messages:[...$.session.messages,X],error:null}}))},addUserMessage:(X)=>{let $={id:`user-${Date.now()}-${Math.random()}`,role:"user",content:X,timestamp:Date.now()};Z().session.actions.addMessage($)},addAssistantMessage:(X,$)=>{let Y={id:`assistant-${Date.now()}-${Math.random()}`,role:"assistant",content:X,timestamp:Date.now(),thinkingContent:$};Z().session.actions.addMessage(Y)},addAssistantMessageAndClearThinking:(X)=>{let $=Z().session.currentThinkingContent,Y={id:`assistant-${Date.now()}-${Math.random()}`,role:"assistant",content:X,timestamp:Date.now(),thinkingContent:$||void 0};Q((V)=>({session:{...V.session,messages:[...V.session.messages,Y],currentThinkingContent:null,error:null}}))},addToolMessage:(X,$)=>{let Y={id:`tool-${Date.now()}-${Math.random()}`,role:"tool",content:X,timestamp:Date.now(),metadata:$};Z().session.actions.addMessage(Y)},setCompacting:(X)=>{Q(($)=>({session:{...$.session,isCompacting:X}}))},setCommand:(X)=>{Q(($)=>({session:{...$.session,currentCommand:X}}))},setError:(X)=>{Q(($)=>({session:{...$.session,error:X}}))},clearMessages:()=>{f(),Q((X)=>({session:{...X.session,messages:[],restoredContextMessages:null,restoredVisibleMessageCount:0,error:null,clearCount:X.session.clearCount+1}}))},resetSession:()=>{f(),Q((X)=>({session:{...X.session,...VQ,sessionId:X.session.sessionId,isActive:!0}}))},restoreSession:(X,$,Y)=>{f(),Q((V)=>({session:{...V.session,sessionId:X,messages:$,restoredContextMessages:Y??null,restoredVisibleMessageCount:Y?$.length:0,error:null,isActive:!0}}))},updateTokenUsage:(X)=>{Q(($)=>({session:{...$.session,tokenUsage:{...$.session.tokenUsage,...X}}}))},resetTokenUsage:()=>{Q((X)=>({session:{...X.session,tokenUsage:{...JQ}}}))},setCurrentThinkingContent:(X)=>{if(Z().session.currentThinkingContent===X)return;Q(($)=>({session:{...$.session,currentThinkingContent:X}}))},appendThinkingContent:(X)=>{Q(($)=>({session:{...$.session,currentThinkingContent:($.session.currentThinkingContent||"")+X}}))},setThinkingExpanded:(X)=>{Q(($)=>({session:{...$.session,thinkingExpanded:X}}))},toggleThinkingExpanded:()=>{Q((X)=>({session:{...X.session,thinkingExpanded:!X.session.thinkingExpanded}}))},setHistoryExpanded:(X)=>{Q(($)=>({session:{...$.session,historyExpanded:X}}))},toggleHistoryExpanded:()=>{Q((X)=>({session:{...X.session,historyExpanded:!X.session.historyExpanded}}))},setExpandedMessageCount:(X)=>{Q(($)=>({session:{...$.session,expandedMessageCount:X}}))},incrementClearCount:()=>{Q((X)=>({session:{...X.session,clearCount:X.session.clearCount+1}}))},startStreamingAssistantMessage:()=>{let X=`assistant-${Date.now()}-${Math.random()}`,$={id:X,role:"assistant",content:"",timestamp:Date.now()};return M=[],Q((Y)=>({session:{...Y.session,messages:[...Y.session.messages,$],currentStreamingMessageId:X,currentStreamingChunks:[],currentStreamingLines:[],currentStreamingTail:"",currentStreamingLineCount:0,currentStreamingVersion:0,error:null}})),X},appendAssistantContent:(X)=>{let $=Z().session.currentStreamingMessageId,Y=$??`assistant-${Date.now()}-${Math.random()}`;return M.push(X),Q((V)=>{let J=(D)=>D.endsWith("\r")?D.slice(0,-1):D,U=$?V.session.currentStreamingLines:[],G=$?V.session.currentStreamingTail:"",z=$?V.session.currentStreamingLineCount:0,K=$?V.session.currentStreamingVersion:0,y=(G+X).split(`
16
- `),B=y.slice(0,-1).map(J),H=J(y[y.length-1]??""),j=U;if(B.length>0){if(j=[...U,...B],j.length>YQ){let D=j.length-YQ;j=j.slice(D)}}return{session:{...V.session,currentStreamingMessageId:Y,currentStreamingLines:j,currentStreamingTail:H,currentStreamingLineCount:z+B.length,currentStreamingVersion:K+1,error:null}}}),Y},finalizeStreamingMessage:(X,$)=>{let Y=SQ();Q((V)=>{let J=V.session.currentStreamingMessageId,G=Y.join("")+(X||""),z=(V.session.currentThinkingContent||"")+($||"");if(G.length>0){let K={id:J||`assistant-${Date.now()}-${Math.random()}`,role:"assistant",content:G,timestamp:Date.now(),thinkingContent:z||void 0};return{session:{...V.session,messages:[...V.session.messages,K],currentStreamingMessageId:null,currentStreamingChunks:[],currentStreamingLines:[],currentStreamingTail:"",currentStreamingLineCount:0,currentStreamingVersion:0,currentThinkingContent:null,finalizingStreamingMessageId:K.id}}}return{session:{...V.session,currentStreamingMessageId:null,currentStreamingChunks:[],currentStreamingLines:[],currentStreamingTail:"",currentStreamingLineCount:0,currentStreamingVersion:0,currentThinkingContent:null,finalizingStreamingMessageId:null}}})},clearFinalizingStreamingMessageId:()=>{Q((X)=>({session:{...X.session,finalizingStreamingMessageId:null}}))},discardStreamingMessage:()=>{M=[],Q((X)=>({session:{...X.session,currentStreamingMessageId:null,currentStreamingChunks:[],currentStreamingLines:[],currentStreamingTail:"",currentStreamingLineCount:0,currentStreamingVersion:0,finalizingStreamingMessageId:null}}))}}});import{nanoid as mQ}from"nanoid";import{promises as _}from"node:fs";import*as F from"node:path";import{fileURLToPath as uQ}from"node:url";import{nanoid as pQ}from"nanoid";var UQ={proposal:"proposal.md",spec:"spec.md",requirements:"requirements.md",design:"design.md",tasks:"tasks.md",meta:".meta.json"},P={SPECS:"specs",CHANGES:"changes",ARCHIVE:"archive",STEERING:"steering",SPEC_DELTA:"specs"},R={CONSTITUTION:"constitution.md",PRODUCT:"product.md",TECH:"tech.md",STRUCTURE:"structure.md"};var b={init:["requirements"],requirements:["design","tasks"],design:["tasks"],tasks:["implementation"],implementation:["done","tasks"],done:[]},OX={init:"初始化",requirements:"需求定义",design:"架构设计",tasks:"任务分解",implementation:"实现中",done:"已完成"},GQ={init:"proposal",requirements:"requirements",design:"design",tasks:"tasks",implementation:"tasks",done:null};var gQ=uQ(import.meta.url),dQ=F.dirname(gQ),jQ=F.join(dQ,"templates");class N{workspaceRoot;bladeDir;constructor(Q){this.workspaceRoot=Q,this.bladeDir=F.join(Q,".blade")}getSpecsDir(){return F.join(this.bladeDir,P.SPECS)}getChangesDir(){return F.join(this.bladeDir,P.CHANGES)}getArchiveDir(){return F.join(this.bladeDir,P.ARCHIVE)}getSteeringDir(){return F.join(this.bladeDir,P.STEERING)}getChangePath(Q){return F.join(this.getChangesDir(),Q)}getChangeFilePath(Q,Z){return F.join(this.getChangePath(Q),UQ[Z])}async initializeDirectories(){await _.mkdir(this.getChangesDir(),{recursive:!0,mode:493})}async createChangeDir(Q){let Z=this.getChangePath(Q);return await _.mkdir(Z,{recursive:!0,mode:493}),await _.mkdir(F.join(Z,P.SPEC_DELTA),{recursive:!0,mode:493}),Z}async readFile(Q){try{return await _.readFile(Q,"utf-8")}catch(Z){if(Z.code==="ENOENT")return null;throw Z}}async writeFile(Q,Z){let X=F.dirname(Q);await _.mkdir(X,{recursive:!0,mode:493}),await _.writeFile(Q,Z,"utf-8")}async fileExists(Q){try{return await _.access(Q),!0}catch{return!1}}async dirExists(Q){try{return(await _.stat(Q)).isDirectory()}catch{return!1}}createMetadata(Q,Z){let X=new Date().toISOString();return{id:pQ(),name:Q,description:Z,phase:"init",createdAt:X,updatedAt:X,tasks:[]}}async readMetadata(Q){let Z=this.getChangeFilePath(Q,"meta"),X=await this.readFile(Z);if(!X)return null;try{return JSON.parse(X)}catch{return null}}async writeMetadata(Q,Z){let X=this.getChangeFilePath(Q,"meta");Z.updatedAt=new Date().toISOString(),await this.writeFile(X,JSON.stringify(Z,null,2))}async updatePhase(Q,Z){let X=await this.readMetadata(Q);if(!X)return null;return X.phase=Z,await this.writeMetadata(Q,X),X}async readSpecFile(Q,Z){let X=this.getChangeFilePath(Q,Z);return this.readFile(X)}async writeSpecFile(Q,Z,X){let $=this.getChangeFilePath(Q,Z);await this.writeFile($,X);let Y=await this.readMetadata(Q);if(Y)await this.writeMetadata(Q,Y)}async getPhaseContent(Q,Z){let X=GQ[Z];if(!X)return null;return this.readSpecFile(Q,X)}async readSteeringContext(){let Q=this.getSteeringDir(),[Z,X,$,Y]=await Promise.all([this.readFile(F.join(Q,R.CONSTITUTION)),this.readFile(F.join(Q,R.PRODUCT)),this.readFile(F.join(Q,R.TECH)),this.readFile(F.join(Q,R.STRUCTURE))]);return{constitution:Z||void 0,product:X||void 0,tech:$||void 0,structure:Y||void 0}}async writeSteeringFile(Q,Z){let X=F.join(this.getSteeringDir(),R[Q]);await this.writeFile(X,Z)}async hasSteeringDocs(){let Q=this.getSteeringDir();if(!await this.dirExists(Q))return!1;return(await _.readdir(Q)).length>0}async listActiveChanges(){let Q=this.getChangesDir();if(!await this.dirExists(Q))return[];return(await _.readdir(Q,{withFileTypes:!0})).filter((X)=>X.isDirectory()).map((X)=>X.name)}async listArchivedChanges(){let Q=this.getArchiveDir();if(!await this.dirExists(Q))return[];return(await _.readdir(Q,{withFileTypes:!0})).filter((X)=>X.isDirectory()).map((X)=>X.name)}async changeExists(Q){return this.dirExists(this.getChangePath(Q))}async archiveChange(Q){let Z=this.getChangePath(Q),X=F.join(this.getArchiveDir(),Q);await _.mkdir(F.dirname(X),{recursive:!0,mode:493}),await _.rename(Z,X)}async restoreChange(Q){let Z=F.join(this.getArchiveDir(),Q),X=this.getChangePath(Q);await _.rename(Z,X)}async listSpecDomains(){let Q=this.getSpecsDir();if(!await this.dirExists(Q))return[];return(await _.readdir(Q,{withFileTypes:!0})).filter((X)=>X.isDirectory()).map((X)=>X.name)}async readAuthorativeSpec(Q){let Z=F.join(this.getSpecsDir(),Q,"spec.md");return this.readFile(Z)}async writeAuthorativeSpec(Q,Z){let X=F.join(this.getSpecsDir(),Q,"spec.md");await this.writeFile(X,Z)}async mergeSpecDeltas(Q){let Z=F.join(this.getChangePath(Q),P.SPEC_DELTA);if(!await this.dirExists(Z))return[];let X=[],$=await _.readdir(Z,{withFileTypes:!0});for(let Y of $){if(!Y.isDirectory())continue;let V=F.join(Z,Y.name,"spec.md"),J=await this.readFile(V);if(J){let U=await this.readAuthorativeSpec(Y.name),G=U?`${U}
17
-
18
- ---
19
-
20
- <!-- Merged from ${Q} -->
21
-
22
- ${J}`:J;await this.writeAuthorativeSpec(Y.name,G),X.push(Y.name)}}return X}static TEMPLATE_NAMES={proposal:"proposal.md.template",spec:"spec.md.template",requirements:"requirements.md.template",design:"design.md.template",tasks:"tasks.md.template",meta:""};static STEERING_TEMPLATE_NAMES={CONSTITUTION:"steering/constitution.md.template",PRODUCT:"steering/product.md.template",TECH:"steering/tech.md.template",STRUCTURE:"steering/structure.md.template"};async readTemplate(Q){let Z=N.TEMPLATE_NAMES[Q];if(!Z)return null;let X=F.join(jQ,Z);return this.readFile(X)}async readSteeringTemplate(Q){let Z=N.STEERING_TEMPLATE_NAMES[Q],X=F.join(jQ,Z);return this.readFile(X)}fillTemplate(Q,Z){let X=Q;for(let[$,Y]of Object.entries(Z))X=X.replace(new RegExp(`\\{\\{${$}\\}\\}`,"g"),Y);return X}async createFromTemplate(Q,Z,X){let $=await this.readTemplate(Z);if(!$)return null;let Y=this.fillTemplate($,{name:Q,createdAt:new Date().toISOString(),updatedAt:new Date().toISOString(),...X});return await this.writeSpecFile(Q,Z,Y),Y}async createSteeringFromTemplate(Q,Z={}){let X=await this.readSteeringTemplate(Q);if(!X)return null;let $=this.fillTemplate(X,{createdAt:new Date().toISOString(),...Z});return await this.writeSteeringFile(Q,$),$}async initializeSteeringDocs(){let Q=[],Z=this.getSteeringDir();for(let[X,$]of Object.entries(R)){let Y=F.join(Z,$);if(!await this.fileExists(Y))await this.createSteeringFromTemplate(X),Q.push($)}return Q}}class x{static instance=null;fileManager=null;workspaceRoot=null;constructor(){}static getInstance(){if(!x.instance)x.instance=new x;return x.instance}static resetInstance(){x.instance=null}async initialize(Q){if(this.workspaceRoot===Q&&this.fileManager)return;this.workspaceRoot=Q,this.fileManager=new N(Q),await this.fileManager.initializeDirectories()}getFileManager(){if(!this.fileManager)throw Error("SpecService not initialized. Call initialize() first.");return this.fileManager}async readSteeringContext(){return this.getFileManager().readSteeringContext()}async readSpecMetadata(Q){return this.getFileManager().readMetadata(Q)}async specExists(Q){return this.getFileManager().changeExists(Q)}getSpecPath(Q){return this.getFileManager().getChangePath(Q)}async createSpec(Q,Z){let X=this.getFileManager();if(await X.changeExists(Q))return{success:!1,message:`Spec "${Q}" already exists`,error:"SPEC_EXISTS"};let $=await X.createChangeDir(Q),Y=X.createMetadata(Q,Z);await X.writeMetadata(Q,Y);let V=this.generateProposalTemplate(Q,Z);return await X.writeSpecFile(Q,"proposal",V),{success:!0,message:`Spec "${Q}" created successfully`,data:{spec:Y,path:$}}}async loadSpec(Q){let Z=this.getFileManager(),X=await Z.readMetadata(Q);if(!X)return{success:!1,message:`Spec "${Q}" not found`,error:"SPEC_NOT_FOUND"};let $=Z.getChangePath(Q);return{success:!0,message:`Spec "${Q}" loaded successfully`,data:{spec:X,path:$}}}canTransitionPhase(Q,Z){return b[Q].includes(Z)}getAllowedTransitions(Q){return b[Q]}async updatePhase(Q,Z){return this.getFileManager().updatePhase(Q,Z)}createTask(Q,Z,X){return{id:mQ(8),title:Q,description:Z,status:"pending",dependencies:X?.dependencies||[],affectedFiles:X?.affectedFiles||[],complexity:X?.complexity||"medium"}}async saveMetadata(Q,Z){await this.getFileManager().writeMetadata(Q,Z)}getNextTask(Q){return Q.find((Z)=>{if(Z.status!=="pending")return!1;return Z.dependencies.every((X)=>{return Q.find((Y)=>Y.id===X)?.status==="completed"})})||null}getTaskProgress(Q){if(Q.length===0)return{total:0,completed:0,percentage:0};let Z=Q.length,X=Q.filter((Y)=>Y.status==="completed").length,$=Math.round(X/Z*100);return{total:Z,completed:X,percentage:$}}async listActiveSpecs(){return this.getFileManager().listActiveChanges()}async listArchivedSpecs(){return this.getFileManager().listArchivedChanges()}async archiveSpec(Q){let Z=this.getFileManager();return await Z.mergeSpecDeltas(Q),await Z.updatePhase(Q,"done"),await Z.archiveChange(Q),{success:!0,message:`Spec "${Q}" archived successfully`}}async validateSpec(Q){let Z=this.getFileManager(),X=[],$=[],[Y,V,J,U,G]=await Promise.all([Z.readSpecFile(Q.name,"proposal"),Z.readSpecFile(Q.name,"spec"),Z.readSpecFile(Q.name,"requirements"),Z.readSpecFile(Q.name,"design"),Z.readSpecFile(Q.name,"tasks")]),z={proposal:!!Y,spec:!!V,requirements:!!J,design:!!U,tasks:!!G};if(Q.phase==="requirements"&&!z.requirements)X.push({severity:"warning",file:"requirements",message:"Requirements document is missing"}),$.push("Generate requirements using EARS format");if(Q.phase==="design"&&!z.design)X.push({severity:"warning",file:"design",message:"Design document is missing"}),$.push("Create architecture diagrams and API contracts");if(Q.phase==="tasks"&&Q.tasks.length===0)X.push({severity:"warning",file:"tasks",message:"No tasks defined"}),$.push("Break down the spec into atomic tasks");if(Q.phase==="implementation"){let K=this.getTaskProgress(Q.tasks);if(K.completed<K.total)X.push({severity:"info",file:"tasks",message:`${K.total-K.completed} tasks remaining`})}return{valid:X.filter((K)=>K.severity==="error").length===0,phase:Q.phase,completeness:z,issues:X,suggestions:$}}generateProposalTemplate(Q,Z){return`# ${Q}
23
-
24
- ## Summary
25
-
26
- ${Z}
27
-
28
- ## Background
29
-
30
- <!-- Why is this change needed? What problem does it solve? -->
31
-
32
- ## Goals
33
-
34
- <!-- What are the specific objectives of this change? -->
35
-
36
- - [ ] Goal 1
37
- - [ ] Goal 2
38
-
39
- ## Non-Goals
40
-
41
- <!-- What is explicitly out of scope? -->
42
-
43
- ## Risks and Mitigations
44
-
45
- <!-- What could go wrong? How will you address it? -->
46
-
47
- | Risk | Mitigation |
48
- |------|------------|
49
- | | |
50
-
51
- ## Open Questions
52
-
53
- <!-- What needs to be clarified before proceeding? -->
54
-
55
- 1.
56
- `}}var HQ=FQ("Spec"),zQ={currentSpec:null,specPath:null,isActive:!1,steeringContext:null,recentSpecs:[],isLoading:!1,error:null,workspaceRoot:null},o=(Q,Z)=>({...zQ,actions:{initialize:async(X)=>{let $=x.getInstance();await $.initialize(X);let Y=await $.readSteeringContext();Q((V)=>({spec:{...V.spec,workspaceRoot:X,steeringContext:Y}}))},createSpec:async(X,$)=>{let V=await x.getInstance().createSpec(X,$);if(V.success&&V.data){let{spec:J,path:U}=V.data,G=Z().spec.recentSpecs.filter((z)=>z!==X);G.unshift(X),Q((z)=>({spec:{...z.spec,currentSpec:J,specPath:U,isActive:!0,recentSpecs:G.slice(0,10)}}))}return V},loadSpec:async(X)=>{let Y=await x.getInstance().loadSpec(X);if(Y.success&&Y.data){let{spec:V,path:J}=Y.data,U=Z().spec.recentSpecs.filter((G)=>G!==X);U.unshift(X),Q((G)=>({spec:{...G.spec,currentSpec:V,specPath:J,isActive:!0,recentSpecs:U.slice(0,10)}}))}return Y},closeSpec:()=>{Q((X)=>({spec:{...X.spec,currentSpec:null,specPath:null,isActive:!1}}))},exitSpecMode:()=>{Z().spec.actions.closeSpec()},transitionPhase:async(X)=>{let $=Z().spec.currentSpec;if(!$)return{success:!1,message:"No active spec",error:"NO_ACTIVE_SPEC"};let Y=x.getInstance();if(!Y.canTransitionPhase($.phase,X))return{success:!1,message:`Cannot transition from "${$.phase}" to "${X}"`,error:"INVALID_TRANSITION"};let V=await Y.updatePhase($.name,X);if(!V)return{success:!1,message:"Failed to update phase",error:"UPDATE_FAILED"};if(Q((J)=>({spec:{...J.spec,currentSpec:V}})),X==="done")try{let{config:J}=Z();if(J.actions)J.actions.updateConfig({permissionMode:"default"});HQ.info("Spec 已完成,已自动退出 Spec 模式")}catch(J){HQ.error("自动退出 Spec 模式失败:",J)}return{success:!0,message:`Transitioned to "${X}" phase`,data:{spec:V,phase:X}}},getAllowedTransitions:()=>{let X=Z().spec.currentSpec;if(!X)return[];return b[X.phase]},addTask:async(X,$,Y)=>{let V=Z().spec.currentSpec;if(!V)return{success:!1,message:"No active spec",error:"NO_ACTIVE_SPEC"};let J=x.getInstance(),U=J.createTask(X,$,Y),G={...V,tasks:[...V.tasks,U],updatedAt:new Date().toISOString()};return await J.saveMetadata(V.name,G),Q((z)=>({spec:{...z.spec,currentSpec:G}})),{success:!0,message:`Task "${X}" added`,data:{task:U}}},updateTaskStatus:async(X,$)=>{let Y=Z().spec.currentSpec;if(!Y)return{success:!1,message:"No active spec",error:"NO_ACTIVE_SPEC"};let V=Y.tasks.find((K)=>K.id===X);if(!V)return{success:!1,message:`Task "${X}" not found`,error:"TASK_NOT_FOUND"};let J={...V,status:$,completedAt:$==="completed"?new Date().toISOString():V.completedAt},U=Y.tasks.map((K)=>K.id===X?J:K),G={...Y,tasks:U,currentTaskId:$==="in_progress"?X:Y.currentTaskId===X?void 0:Y.currentTaskId,updatedAt:new Date().toISOString()};return await x.getInstance().saveMetadata(Y.name,G),Q((K)=>({spec:{...K.spec,currentSpec:G}})),{success:!0,message:`Task status updated to "${$}"`,data:{task:J}}},getNextTask:()=>{let X=Z().spec.currentSpec;if(!X)return null;return x.getInstance().getNextTask(X.tasks)},getTaskProgress:()=>{let X=Z().spec.currentSpec;if(!X)return{total:0,completed:0,percentage:0};return x.getInstance().getTaskProgress(X.tasks)},listSpecs:async(X)=>{let $=x.getInstance(),Y=[],V=await $.listActiveSpecs();for(let J of V){let U=await $.readSpecMetadata(J);if(!U)continue;if(X?.phase&&U.phase!==X.phase)continue;if(X?.tags&&!X.tags.some((z)=>U.tags?.includes(z)))continue;if(X?.query&&!U.name.toLowerCase().includes(X.query.toLowerCase())&&!U.description.toLowerCase().includes(X.query.toLowerCase()))continue;let G=$.getTaskProgress(U.tasks);Y.push({name:U.name,description:U.description,phase:U.phase,updatedAt:U.updatedAt,path:$.getSpecPath(J),isArchived:!1,taskProgress:{total:G.total,completed:G.completed}})}if(X?.includeArchived){let J=await $.listArchivedSpecs();for(let U of J)Y.push({name:U,description:"(archived)",phase:"done",updatedAt:"",path:`archive/${U}`,isArchived:!0,taskProgress:{total:0,completed:0}})}return Y.sort((J,U)=>{if(J.isArchived!==U.isArchived)return J.isArchived?1:-1;return new Date(U.updatedAt).getTime()-new Date(J.updatedAt).getTime()}),Y},archiveCurrentSpec:async()=>{let X=Z().spec.currentSpec;if(!X)return{success:!1,message:"No active spec",error:"NO_ACTIVE_SPEC"};let Y=await x.getInstance().archiveSpec(X.name);if(Y.success)Z().spec.actions.closeSpec();return Y},validateCurrentSpec:async()=>{let X=Z().spec.currentSpec;if(!X)return{valid:!1,phase:"init",completeness:{proposal:!1,spec:!1,requirements:!1,design:!1,tasks:!1},issues:[{severity:"error",file:"meta",message:"No active spec"}],suggestions:["Create a new spec with /spec proposal <name>"]};return x.getInstance().validateSpec(X)},getSteeringContextString:async()=>{let X=Z().spec.steeringContext;if(!X)return null;let $=[];if(X.constitution)$.push(`## Constitution (Project Governance)
57
-
58
- ${X.constitution}`);if(X.product)$.push(`## Product Vision
59
-
60
- ${X.product}`);if(X.tech)$.push(`## Technology Stack
61
-
62
- ${X.tech}`);if(X.structure)$.push(`## Code Structure
63
-
64
- ${X.structure}`);return $.length>0?$.join(`
65
-
66
- ---
67
-
68
- `):null},setError:(X)=>{Q(($)=>({spec:{...$.spec,error:X}}))},setLoading:(X)=>{Q(($)=>({spec:{...$.spec,isLoading:X}}))},reset:()=>{Q((X)=>({spec:{...zQ,actions:X.spec.actions}}))}}});var oQ=iQ()(lQ(cQ((...Q)=>({session:i(...Q),app:g(...Q),config:m(...Q),focus:r(...Q),command:d(...Q),spec:o(...Q)})),{name:"BladeStore",enabled:!0})),q=()=>oQ.getState(),iX=()=>q().session.actions,oX=()=>q().app.actions,nX=()=>q().session.messages,v=()=>q().config.config,I=null;async function sX(){if(v()!==null)return;if(I)return I;return I=(async()=>{try{let X=await KQ.getInstance().initialize();q().config.actions.setConfig(X)}catch(Z){throw I=null,Error(`[FAIL] Store 未初始化且无法自动初始化
69
-
70
- `+`原因: ${Z instanceof Error?Z.message:"未知错误"}
71
-
72
- `+`请确保:
73
- `+`1. 配置文件格式正确 (~/.blade/config.json)
74
- `+`2. 运行 blade 进行首次配置
75
- `+"3. 配置文件权限正确")}finally{I=null}})(),I}var aX=()=>q().config.config?.models??[],tX=()=>{let Q=v();if(!Q)return;let Z=Q.currentModelId;return Q.models.find(($)=>$.id===Z)??Q.models[0]},eX=(Q)=>{let Z=v();if(!Z)return;return Z.models.find((X)=>X.id===Q)},QZ=()=>q().config.config?.mcpServers??{},XZ=()=>q().app.thinkingModeEnabled,ZZ=()=>({setPermissionMode:async(Q)=>{q().config.actions.updateConfig({permissionMode:Q})},setTheme:async(Q,Z={})=>{try{QQ.setTheme(Q)}catch{return}q().config.actions.updateConfig({theme:Q}),await A().save({theme:Q},{scope:"global",...Z})},setLanguage:async(Q,Z={})=>{q().config.actions.updateConfig({language:Q}),await A().save({language:Q},{scope:"global",...Z})},setDebug:async(Q,Z={})=>{q().config.actions.updateConfig({debug:Q}),await A().save({debug:Q},{scope:"global",...Z})},setTemperature:async(Q,Z={})=>{q().config.actions.updateConfig({temperature:Q}),await A().save({temperature:Q},{scope:"global",...Z})},updateConfig:async(Q,Z={})=>{let X=v();if(!X)throw Error("Config not initialized");let $={...X};q().config.actions.updateConfig(Q);try{await A().save(Q,Z)}catch(Y){throw q().config.actions.setConfig($),Y}},flush:async()=>{await A().flush()},appendPermissionAllowRule:async(Q,Z={})=>{let X=v();if(!X)throw Error("Config not initialized");let $=X.permissions?.allow||[];if(!$.includes(Q)){let Y=[...$,Q];q().config.actions.updateConfig({permissions:{...X.permissions,allow:Y}})}await A().appendPermissionRule(Q,Z)},appendLocalPermissionAllowRule:async(Q,Z={})=>{let X=v();if(!X)throw Error("Config not initialized");let $=X.permissions?.allow||[];if(!$.includes(Q)){let Y=[...$,Q];q().config.actions.updateConfig({permissions:{...X.permissions,allow:Y}})}await A().appendLocalPermissionRule(Q,Z)},setCurrentModel:async(Q,Z={})=>{let X=v();if(!X)throw Error("Config not initialized");if(!X.models.find((Y)=>Y.id===Q))throw Error(`Model not found: ${Q}`);q().config.actions.updateConfig({currentModelId:Q}),await A().save({currentModelId:Q},{scope:"global",...Z})},addModel:async(Q,Z={})=>{let X=v();if(!X)throw Error("Config not initialized");let $="id"in Q?Q:{id:rQ(),...Q},V={models:[...X.models,$]};if(X.models.length===0)V.currentModelId=$.id;return q().config.actions.updateConfig(V),await A().save(V,{scope:"global",...Z}),$},updateModel:async(Q,Z,X={})=>{let $=v();if(!$)throw Error("Config not initialized");let Y=$.models.findIndex((J)=>J.id===Q);if(Y===-1)throw Error(`Model not found: ${Q}`);let V=[...$.models];V[Y]={...V[Y],...Z},q().config.actions.updateConfig({models:V}),await A().save({models:V},{scope:"global",...X})},removeModel:async(Q,Z={})=>{let X=v();if(!X)throw Error("Config not initialized");if(X.models.length===1)throw Error("Cannot remove the only model");let $=X.models.filter((V)=>V.id!==Q),Y={models:$};if(X.currentModelId===Q)Y.currentModelId=$[0].id;q().config.actions.updateConfig(Y),await A().save(Y,{scope:"global",...Z})},addMcpServer:async(Q,Z,X={})=>{let $=v();if(!$)throw Error("Config not initialized");let V={...$.mcpServers??{},[Q]:Z};q().config.actions.updateConfig({mcpServers:V}),await A().save({mcpServers:V},{scope:"project",...X})},removeMcpServer:async(Q,Z={})=>{let X=v();if(!X)throw Error("Config not initialized");let Y={...X.mcpServers??{}};delete Y[Q],q().config.actions.updateConfig({mcpServers:Y}),await A().save({mcpServers:Y},{scope:"project",...Z})}});
76
- export{a as ha,QQ as ia,W as ja,$X as ka,JX as la,UX as ma,GX as na,jX as oa,HX as pa,zX as qa,b as ra,OX as sa,N as ta,oQ as ua,q as va,iX as wa,oX as xa,nX as ya,v as za,sX as Aa,aX as Ba,tX as Ca,eX as Da,QZ as Ea,XZ as Fa,ZZ as Ga};
@@ -1 +0,0 @@
1
- import{t as a,u as b}from"./chunk-9mrna4y3.js";import"./chunk-kd1t45br.js";import"./chunk-j2ag7hh6.js";export{a as globalOptions,b as cliConfig};