blade-code 0.5.15 → 0.5.17

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.
package/dist/blade.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import{n as B}from"./chunk-pfsft4nd.js";import{$ as F,_ as D}from"./chunk-mxrre2n3.js";import"./chunk-x9zj0r7s.js";import"./chunk-mz6n4w13.js";import"./chunk-yk91w5p2.js";import{vb as E,xb as q}from"./chunk-7ycmx7c2.js";import{Ab as H}from"./chunk-set7v1rf.js";import{Db as J}from"./chunk-j2ag7hh6.js";var X=process.argv.slice(2),$=v(X),w=$!==null;if($!==null)H.setGlobalDebug($);function v(Q){for(let W=0;W<Q.length;W+=1){let T=Q[W];if(T==="--debug"||T==="-d"){let N=Q[W+1];return N&&!N.startsWith("-")?N:!0}if(T.startsWith("--debug="))return T.slice(8)||!0}return null}function C(Q){return Q.length===1&&(Q[0]==="--version"||Q[0]==="-V")}function z(Q,...W){return Q.some((T)=>W.some((N)=>T===N||T.startsWith(`${N}=`)))}async function f(){if(C(X)){let{getVersion:K}=await import("./chunk-wgkqtd9q.js");console.log(K());return}let Q=D(process.cwd());if(F(Q),E(q()),process.getuid&&process.getuid()===0){let K=!!process.env.SUDO_USER,U=!!process.env.BLADE_ALLOW_ROOT;if(K&&!U)console.error(""),console.error("Error: 请不要使用 sudo 运行 blade"),console.error(""),console.error("原因:"),console.error(" 使用 sudo 会创建属于 root 的配置文件,"),console.error(" 导致普通用户无法访问。"),console.error(""),console.error("正确用法:"),console.error(" blade # 直接运行,不要加 sudo"),console.error(""),console.error("如果遇到权限错误,请运行:"),console.error(" sudo chown -R $USER:$USER ~/.blade/"),console.error(""),console.error("如果你确实需要以 root 运行(容器/CI),设置环境变量:"),console.error(" BLADE_ALLOW_ROOT=1 blade"),console.error(""),process.exit(1)}if(B(),z(X,"--headless")){let{handleHeadlessMode:K}=await import("./chunk-9h3ezzr5.js");if(await K())return}if(z(X,"--print","-p")){let{handlePrintMode:K}=await import("./chunk-wcnfx70a.js");if(await K())return}if(X.includes("--acp")){let{runAcpIntegration:K}=await import("./chunk-1jg3a3y0.js");await K();return}let[{default:W},{hideBin:T},{cliConfig:N,globalOptions:G},{loadConfiguration:I,validateOutput:L,validatePermissions:M},{doctorCommands:_},{installCommands:y},{mcpCommands:R},{serveCommand:S},{updateCommands:k},{webCommand:O}]=await Promise.all([import("yargs"),import("yargs/helpers"),import("./chunk-26354ct8.js"),import("./chunk-fe7g701v.js"),import("./chunk-k65n39by.js"),import("./chunk-g5pasj7t.js"),import("./chunk-rwwze12b.js"),import("./chunk-vwtssawg.js"),import("./chunk-bhjw4b73.js"),import("./chunk-9b9tcp8m.js")]),x=W(T(process.argv)).scriptName(N.scriptName).usage(N.usage).version(N.version).locale(N.locale).showHelpOnFail(N.showHelpOnFail).demandCommand(0,"").recommendCommands().strict(N.strict).parserConfiguration({"populate--":!0}).options(G).middleware([M,I,L]).command(R).command(_).command(k).command(y).command(O).command(S).completion("completion",!1).help("help","Show help").alias("help","h").alias("version","V").fail((K,U,Z)=>{if(U){if(console.error("An error occurred:"),console.error(U.message),w&&U.stack)console.error(`
2
+ import{n as B}from"./chunk-pfsft4nd.js";import{$ as F,_ as D}from"./chunk-mxrre2n3.js";import"./chunk-x9zj0r7s.js";import"./chunk-mz6n4w13.js";import"./chunk-yk91w5p2.js";import{vb as E,xb as q}from"./chunk-7ycmx7c2.js";import{Ab as H}from"./chunk-set7v1rf.js";import{Db as J}from"./chunk-j2ag7hh6.js";var X=process.argv.slice(2),$=v(X),w=$!==null;if($!==null)H.setGlobalDebug($);function v(Q){for(let W=0;W<Q.length;W+=1){let T=Q[W];if(T==="--debug"||T==="-d"){let N=Q[W+1];return N&&!N.startsWith("-")?N:!0}if(T.startsWith("--debug="))return T.slice(8)||!0}return null}function C(Q){return Q.length===1&&(Q[0]==="--version"||Q[0]==="-V")}function z(Q,...W){return Q.some((T)=>W.some((N)=>T===N||T.startsWith(`${N}=`)))}async function f(){if(C(X)){let{getVersion:K}=await import("./chunk-c22wfv5n.js");console.log(K());return}let Q=D(process.cwd());if(F(Q),E(q()),process.getuid&&process.getuid()===0){let K=!!process.env.SUDO_USER,U=!!process.env.BLADE_ALLOW_ROOT;if(K&&!U)console.error(""),console.error("Error: 请不要使用 sudo 运行 blade"),console.error(""),console.error("原因:"),console.error(" 使用 sudo 会创建属于 root 的配置文件,"),console.error(" 导致普通用户无法访问。"),console.error(""),console.error("正确用法:"),console.error(" blade # 直接运行,不要加 sudo"),console.error(""),console.error("如果遇到权限错误,请运行:"),console.error(" sudo chown -R $USER:$USER ~/.blade/"),console.error(""),console.error("如果你确实需要以 root 运行(容器/CI),设置环境变量:"),console.error(" BLADE_ALLOW_ROOT=1 blade"),console.error(""),process.exit(1)}if(B(),z(X,"--headless")){let{handleHeadlessMode:K}=await import("./chunk-9qvvemc7.js");if(await K())return}if(z(X,"--print","-p")){let{handlePrintMode:K}=await import("./chunk-5yg2dzqm.js");if(await K())return}if(X.includes("--acp")){let{runAcpIntegration:K}=await import("./chunk-8p71rmjt.js");await K();return}let[{default:W},{hideBin:T},{cliConfig:N,globalOptions:G},{loadConfiguration:I,validateOutput:L,validatePermissions:M},{doctorCommands:_},{installCommands:y},{mcpCommands:R},{serveCommand:S},{updateCommands:k},{webCommand:O}]=await Promise.all([import("yargs"),import("yargs/helpers"),import("./chunk-bvakgayc.js"),import("./chunk-fe7g701v.js"),import("./chunk-k65n39by.js"),import("./chunk-g5pasj7t.js"),import("./chunk-b2z8h75p.js"),import("./chunk-nfvmapfz.js"),import("./chunk-bhjw4b73.js"),import("./chunk-rwecb1ar.js")]),x=W(T(process.argv)).scriptName(N.scriptName).usage(N.usage).version(N.version).locale(N.locale).showHelpOnFail(N.showHelpOnFail).demandCommand(0,"").recommendCommands().strict(N.strict).parserConfiguration({"populate--":!0}).options(G).middleware([M,I,L]).command(R).command(_).command(k).command(y).command(O).command(S).completion("completion",!1).help("help","Show help").alias("help","h").alias("version","V").fail((K,U,Z)=>{if(U){if(console.error("An error occurred:"),console.error(U.message),w&&U.stack)console.error(`
3
3
  Stack trace:`),console.error(U.stack);else console.error(`
4
4
  Run with --debug to show the stack trace.`);process.exit(1)}if(K)console.error("Error: Invalid arguments:"),console.error(K),console.error(`
5
- Hint: Did you mean:`),Z.showHelp(),process.exit(1)}).command("$0",!1,()=>{},async(K)=>{let U=K._.slice(1),Z=U.length>0?U.join(" "):void 0,V=import("./chunk-th432d0b.js").then(({checkVersionOnStartup:A})=>A()),[{render:b},{createElement:P},{AppWrapper:h}]=await Promise.all([import("ink"),import("react"),import("./chunk-4tz7ntym.js")]),Y={...K,initialMessage:Z,debug:K.debug,print:Boolean(K.print),versionCheckPromise:V};delete Y._,delete Y.$0,delete Y.message,b(P(h,Y),{patchConsole:!0,exitOnCtrlC:!1,alternateBuffer:!1})});try{await x.parse()}catch(K){console.error("Error: Parse error:",K),process.exit(1)}}if(J.main==J.module)f().catch(console.error);export{f as main};
5
+ Hint: Did you mean:`),Z.showHelp(),process.exit(1)}).command("$0",!1,()=>{},async(K)=>{let U=K._.slice(1),Z=U.length>0?U.join(" "):void 0,V=import("./chunk-th432d0b.js").then(({checkVersionOnStartup:A})=>A()),[{render:b},{createElement:P},{AppWrapper:h}]=await Promise.all([import("ink"),import("react"),import("./chunk-ab8zssbp.js")]),Y={...K,initialMessage:Z,debug:K.debug,print:Boolean(K.print),versionCheckPromise:V};delete Y._,delete Y.$0,delete Y.message,b(P(h,Y),{patchConsole:!0,exitOnCtrlC:!1,alternateBuffer:!1})});try{await x.parse()}catch(K){console.error("Error: Parse error:",K),process.exit(1)}}if(J.main==J.module)f().catch(console.error);export{f as main};
@@ -1,2 +1,2 @@
1
- import{e as zf,f as Tf}from"./chunk-q5yn875m.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-ds6m379k.js";import{Y as T}from"./chunk-v1nfdykq.js";import{ba as u}from"./chunk-cbcws8wy.js";import{Ba as xf,Ca as Rf,Ga as z,za as S}from"./chunk-x9zj0r7s.js";import{La as _f,Na as t,Sa as Ef}from"./chunk-c3nh2cc1.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-q5yn875m.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-tkjbcmc1.js";import{Y as T}from"./chunk-p988nqta.js";import{ba as u}from"./chunk-7qw2xttt.js";import{Ba as xf,Ca as Rf,Ga as z,za as S}from"./chunk-x9zj0r7s.js";import{La as _f,Na as t,Sa as Ef}from"./chunk-c3nh2cc1.js";import{xb as R}from"./chunk-7ycmx7c2.js";import{Bb as x}from"./chunk-set7v1rf.js";import{Db as jf}from"./chunk-j2ag7hh6.js";var I0={port:{type:"number",describe:"Port to listen on (0 for auto)",default:0},hostname:{type:"string",describe:"Hostname to listen on",default:"127.0.0.1"},cors:{type:"array",describe:"Additional domains to allow for CORS",default:[]}};function v0(V){return{port:V.port??0,hostname:V.hostname??"127.0.0.1",cors:V.cors??[]}}import{Hono as T0}from"hono";import{cors as y0}from"hono/cors";import{existsSync as gf,readFileSync as e}from"node:fs";import{createServer as _0}from"node:http";import{networkInterfaces as D0}from"node:os";import{dirname as b0,extname as w0,join as w}from"node:path";import{fileURLToPath as L0}from"node:url";import{WebSocketServer as P0}from"ws";import{z as c}from"zod";class p extends Error{code;statusCode;constructor(V,$,f=500){super($);this.code=V;this.statusCode=f;this.name="BladeServerError"}toObject(){return{error:{code:this.code,message:this.message}}}}class P extends p{constructor(V,$){super("NOT_FOUND",$?`${V} not found: ${$}`:`${V} not found`,404)}}class A extends p{constructor(V){super("BAD_REQUEST",V,400)}}var g0=c.object({error:c.object({code:c.string(),message:c.string()})});import{Hono as cf}from"hono";import{z as k}from"zod";var $f=x("Service"),af=k.object({updates:k.record(k.any()),options:k.object({scope:k.enum(["local","project","global"]).optional(),immediate:k.boolean().optional()}).optional()}),Gf=()=>{let V=new cf;return V.get("/",async($)=>{try{let f=S();return $.json(f||{})}catch(f){return $f.error("[ConfigRoutes] Failed to get config:",f),$.json({})}}),V.put("/",async($)=>{try{let f=await $.req.json(),O=af.safeParse(f);if(!O.success)throw new A("Invalid config update format");let{updates:M,options:J}=O.data;return await z().updateConfig(M,J),$.json({success:!0,updates:M})}catch(f){throw $f.error("[ConfigRoutes] Failed to update config:",f),f}}),V.get("/permissions",async($)=>{try{let f=S();return $.json(f?.permissions||{})}catch(f){return $f.error("[ConfigRoutes] Failed to get permissions:",f),$.json({})}}),V};import{Hono as tf}from"hono";var Nf=()=>{let V=new tf;return V.get("/health",($)=>{return $.json({healthy:!0,version:u()})}),V.get("/info",($)=>{return $.json({version:u(),platform:process.platform,arch:process.arch,nodeVersion:process.version,cwd:R()})}),V};import{Hono as nf}from"hono";var o=x("Service"),mf=()=>{let V=new nf;return V.get("/",async($)=>{try{let O=T.getInstance().getAllServers(),M=Array.from(O.entries()).map(([J,j])=>({id:J,name:J,status:j.status==="connected"?"connected":j.status==="connecting"?"connecting":j.lastError?"error":"offline",endpoint:j.config.command?`${j.config.command} ${(j.config.args||[]).join(" ")}`.trim():j.config.url||"Unknown",description:`MCP server: ${J}`,tools:j.tools.map((Y)=>Y.name),connectedAt:j.connectedAt?.toISOString(),error:j.lastError?.message}));return $.json(M)}catch(f){return o.error("[McpRoutes] Failed to get MCP servers:",f),$.json([])}}),V.post("/:name/connect",async($)=>{try{let f=$.req.param("name");return await T.getInstance().connectServer(f),$.json({success:!0})}catch(f){return o.error("[McpRoutes] Failed to connect MCP server:",f),$.json({success:!1,error:f.message},500)}}),V.post("/:name/disconnect",async($)=>{try{let f=$.req.param("name");return await T.getInstance().disconnectServer(f),$.json({success:!0})}catch(f){return o.error("[McpRoutes] Failed to disconnect MCP server:",f),$.json({success:!1,error:f.message},500)}}),V.delete("/:name",async($)=>{try{let f=$.req.param("name");await T.getInstance().unregisterServer(f);let M=S();if(M?.mcpServers){let{[f]:J,...j}=M.mcpServers;await z().updateConfig({mcpServers:j})}return $.json({success:!0})}catch(f){return o.error("[McpRoutes] Failed to delete MCP server:",f),$.json({success:!1,error:f.message},500)}}),V.post("/",async($)=>{try{let f=await $.req.json(),{name:O,config:M}=f;if(!O||!M)return $.json({success:!1,error:"Missing name or config"},400);await T.getInstance().registerServer(O,M);let j=S();return await z().updateConfig({mcpServers:{...j?.mcpServers,[O]:M}}),$.json({success:!0})}catch(f){return o.error("[McpRoutes] Failed to add MCP server:",f),$.json({success:!1,error:f.message},500)}}),V};import{Hono as sf}from"hono";var a=x("Service"),Xf=()=>{let V=new sf;return V.get("/",async($)=>{try{let f=xf(),O=Rf();return $.json({configured:f,current:O})}catch(f){return a.error("[ModelsRoutes] Failed to get models:",f),$.json({configured:[],current:null})}}),V.post("/",async($)=>{try{let f=await $.req.json(),{provider:O,name:M,model:J,baseUrl:j,apiKey:Y}=f;if(!J)throw new A("model is required");let K=await z().addModel({provider:O||"openai-compatible",name:M||J,model:J,baseUrl:j||void 0,apiKey:Y||void 0});return $.json({success:!0,model:K})}catch(f){throw a.error("[ModelsRoutes] Failed to add model:",f),f}}),V.put("/:modelId",async($)=>{try{let f=$.req.param("modelId"),O=await $.req.json(),{baseUrl:M,apiKey:J,model:j}=O;return await z().updateModel(f,{baseUrl:M||void 0,apiKey:J||void 0,model:j||void 0}),$.json({success:!0})}catch(f){throw a.error("[ModelsRoutes] Failed to update model:",f),f}}),V.delete("/:modelId",async($)=>{try{let f=$.req.param("modelId");return await z().removeModel(f),$.json({success:!0})}catch(f){throw a.error("[ModelsRoutes] Failed to delete model:",f),f}}),V};import{Hono as Z0}from"hono";import{z as C}from"zod";import{Hono as ef}from"hono";import{streamSSE as f0}from"hono/streaming";import{LRUCache as $0}from"lru-cache";import{nanoid as d}from"nanoid";import{z as U}from"zod";var X=x("Service"),V0=U.object({title:U.string().optional(),projectPath:U.string().optional()}),O0=U.object({content:U.string(),attachments:U.array(U.object({type:U.enum(["file","image","url"]),path:U.string().optional(),url:U.string().optional(),content:U.string().optional(),mimeType:U.string().optional(),name:U.string().optional()})).optional(),permissionMode:U.enum(["default","autoEdit","plan","spec","yolo"]).optional()}),M0=U.object({title:U.string().optional()}),B=new Map,D=new $0({max:100,ttl:1800000,dispose:(V,$)=>{if(V.status==="running"||V.status==="waiting_permission")V.abortController.abort(),X.debug(`[SessionRoutes] Run ${$} disposed due to cache eviction`)}}),j0=(V)=>{if(!V||typeof V!=="object")return V;let $={...V},f=200000;if(typeof $.oldContent==="string"&&$.oldContent.length>f)delete $.oldContent;if(typeof $.newContent==="string"&&$.newContent.length>f)delete $.newContent;return $};function J0(V){if(typeof V==="string")return V;return V.filter(($)=>$.type==="text").map(($)=>$.text).join(`
2
2
  `)}function Q0(V,$){let f=($??[]).filter((M)=>M.type==="image"&&typeof M.content==="string").map((M)=>({type:"image_url",image_url:{url:M.content}}));if(f.length===0)return V;let O=[];if(V.trim())O.push({type:"text",text:V});return O.push(...f),O}var Wf=()=>{let V=new ef,$=new Map;return V.get("/",async(f)=>{try{let O=await h.listSessions(),M=new Set(O.filter((G)=>G.relationType==="subagent").map((G)=>G.sessionId)),J=Array.from(B.values()).filter((G)=>!M.has(G.id)&&G.relationType!=="subagent").map((G)=>({sessionId:G.id,projectPath:G.projectPath,title:G.title,parentId:void 0,relationType:void 0,status:void 0,agentType:void 0,model:void 0,messageCount:G.messages.length,firstMessageTime:G.createdAt.toISOString(),lastMessageTime:new Date().toISOString(),hasErrors:!1,isActive:!0})),j=new Set(J.map((G)=>G.sessionId)),Y=O.filter((G)=>!B.has(G.sessionId)&&!j.has(G.sessionId)&&G.relationType!=="subagent"),K=new Set(j),Q=Y.filter((G)=>{if(K.has(G.sessionId))return!1;return K.add(G.sessionId),!0}),Z=[...J,...Q];return f.json(Z)}catch(O){return X.error("[SessionRoutes] Failed to list sessions:",O),f.json([])}}),V.post("/",async(f)=>{try{let O=await f.req.json(),M=V0.safeParse(O);if(!M.success)throw new A("Invalid request body");let{title:J,projectPath:j}=M.data,Y=d(12),K=j||f.get("directory")||R(),Q={id:Y,projectPath:K,title:J||`Session ${Y.slice(0,6)}`,createdAt:new Date,messages:[]};return B.set(Y,Q),f.json({sessionId:Y,projectPath:K,title:Q.title,parentId:void 0,relationType:void 0,status:void 0,agentType:void 0,model:void 0,messageCount:0,firstMessageTime:Q.createdAt.toISOString(),lastMessageTime:Q.createdAt.toISOString(),hasErrors:!1})}catch(O){throw X.error("[SessionRoutes] Failed to create session:",O),O}}),V.get("/:sessionId",async(f)=>{let O=f.req.param("sessionId"),M=B.get(O);if(M)return f.json({sessionId:M.id,projectPath:M.projectPath,title:M.title,messageCount:M.messages.length,firstMessageTime:M.createdAt.toISOString(),lastMessageTime:new Date().toISOString(),hasErrors:!1,isActive:!0});try{let j=(await h.listSessions()).find((Y)=>Y.sessionId===O);if(!j)throw new P("Session",O);return f.json(j)}catch(J){if(J instanceof P)throw J;throw X.error("[SessionRoutes] Failed to get session:",J),J}}),V.patch("/:sessionId",async(f)=>{let O=f.req.param("sessionId");try{let M=await f.req.json(),J=M0.safeParse(M);if(!J.success)throw new A("Invalid request body");let{title:j}=J.data,Y=B.get(O);if(Y&&j)Y.title=j;return f.json({success:!0,title:j})}catch(M){throw X.error("[SessionRoutes] Failed to update session:",M),M}}),V.delete("/:sessionId",async(f)=>{let O=f.req.param("sessionId"),M=B.get(O);if(M?.currentRunId){let j=D.get(M.currentRunId);if(j)j.abortController.abort(),g.publish(O,"run.cancelled",{runId:j.id}),D.delete(M.currentRunId)}try{await h.deleteSession(O)}catch(j){X.warn("[SessionRoutes] Failed to delete session file:",j)}B.delete(O);let J=$.get(O);if(J){if(await J.dispose(),$.delete(O),$.size===0)await T.getInstance().disconnectAll()}return f.json({success:!0})}),V.get("/:sessionId/message",async(f)=>{let O=f.req.param("sessionId");try{let M=await h.loadSession(O);return f.json(M)}catch(M){return X.error("[SessionRoutes] Failed to get messages:",M),f.json([])}}),V.get("/:sessionId/events",async(f)=>{let O=f.req.param("sessionId"),M=B.get(O);if(!M){let J=f.get("directory")||R();M={id:O,projectPath:J,title:`Session ${O.slice(0,6)}`,createdAt:new Date,messages:[]},B.set(O,M)}return f0(f,async(J)=>{await J.writeSSE({data:JSON.stringify({type:"connected",properties:{sessionId:O,timestamp:Date.now()}})});let Y=g.subscribe((Q)=>{if(Q.sessionId!==O)return;J.writeSSE({data:JSON.stringify({type:Q.type,properties:{sessionId:Q.sessionId,...Q.properties}})}).catch(()=>{})}),K=setInterval(()=>{if(!J.aborted)J.writeSSE({data:JSON.stringify({type:"heartbeat",properties:{timestamp:Date.now()}})}).catch(()=>{})},15000);J.onAbort(()=>{clearInterval(K),Y()});while(!0)if(await new Promise((Q)=>setTimeout(Q,1000)),J.aborted)break})}),V.post("/:sessionId/message",async(f)=>{let O=f.req.param("sessionId"),M=await f.req.json(),J=O0.safeParse(M);if(!J.success)throw new A("Invalid message format");let{content:j,attachments:Y,permissionMode:K}=J.data,Q=K||"default",Z=f.get("directory")||R(),G=Q0(j,Y),m=B.get(O);if(!m){let N=await h.loadSession(O).catch(()=>[]);m={id:O,projectPath:Z,title:`Session ${O.slice(0,6)}`,createdAt:new Date,messages:N},B.set(O,m)}let q=d(12),L=new AbortController,E={id:q,sessionId:O,status:"running",abortController:L,createdAt:new Date};return D.set(q,E),m.currentRunId=q,Y0(E,m,G,Q,$).catch((N)=>{X.error(`[SessionRoutes] Run ${q} failed:`,N)}),f.json({runId:q,status:"running"},202)}),V.post("/:sessionId/abort",async(f)=>{let O=f.req.param("sessionId"),M=B.get(O);if(M?.currentRunId){let J=D.get(M.currentRunId);if(J)J.abortController.abort(),J.status="cancelled",g.publish(O,"run.cancelled",{runId:J.id})}return f.json({success:!0})}),V.get("/:sessionId/status",async(f)=>{let O=f.req.param("sessionId"),M=B.get(O);if(!M?.currentRunId)return f.json({sessionId:O,status:"idle"});let J=D.get(M.currentRunId);return f.json({sessionId:O,runId:M.currentRunId,status:J?.status||"idle"})}),V};async function Y0(V,$,f,O,M){let{abortController:J,sessionId:j,id:Y}=V,K=d(12),Q=d(12),Z=(G,m)=>{g.publish(j,G,m)};try{Z("message.created",{messageId:K,role:"user",content:J0(f)}),Z("session.status",{status:"running"}),Z("message.created",{messageId:Q,role:"assistant",content:""});let G=M.get(j);if(!G)G=await Ff.create({sessionId:j}),M.set(j,G);let m=await Bf.createWithRuntime(G,{sessionId:j}),q=async(N)=>{let F=d(12),l=300000;V.status="waiting_permission";let ff=new Promise((Kf)=>{let rf=setTimeout(()=>{X.warn(`[SessionRoutes] Permission ${F} timed out after 300000ms`),Z("permission.timeout",{requestId:F}),Kf({approved:!1,reason:"timeout"})},300000);V.pendingPermission={permissionId:F,resolve:(lf)=>{clearTimeout(rf),Kf(lf)},details:N}});Z("permission.asked",{requestId:F,toolName:N.toolName,description:N.message,args:N.args,details:N}),X.info(`[SessionRoutes] Permission request created: ${F}, runId: ${Y}`);let Zf=await ff;return X.info(`[SessionRoutes] Permission response received: ${F}, approved: ${Zf.approved}`),V.status="running",V.pendingPermission=void 0,Zf},L={messages:[...$.messages],userId:"web-user",sessionId:j,workspaceRoot:$.projectPath,signal:J.signal,permissionMode:O,confirmationHandler:{requestConfirmation:q}},E=await Ef(m.chatStream(f,L,{stream:!0}),async(N)=>{switch(N.kind){case"content_delta":Z("message.delta",{messageId:Q,delta:N.delta});break;case"thinking_delta":Z("thinking.delta",{delta:N.delta});break;case"tool_start":if("function"in N.toolCall)Z("tool.start",{messageId:Q,toolName:N.toolCall.function.name,toolCallId:N.toolCall.id,arguments:N.toolCall.function.arguments,toolKind:N.toolKind});break;case"tool_result":if("function"in N.toolCall)Z("tool.result",{messageId:Q,toolName:N.toolCall.function.name,toolCallId:N.toolCall.id,success:!N.result.error,summary:N.result.metadata?.summary,output:qf(Uf(N.toolCall.function.name,N.result)),metadata:j0(N.result.metadata)});break;case"token_usage":Z("token.usage",{...N.usage});break;case"task_update":Z("task.updated",{tasks:N.tasks});break;default:break}});$.messages=[...L.messages],Z("message.complete",{messageId:Q}),Z("thinking.completed",{}),V.status="completed",Z("session.completed",{runId:Y,outputTruncated:E.metadata?.outputTruncated??!1}),Z("session.status",{status:"idle"})}catch(G){X.error("[SessionRoutes] Agent execution error:",G),V.status="failed",Z("session.error",{error:G instanceof Error?G.message:"Unknown error"}),Z("session.status",{status:"error"})}}function Af(V,$,f){X.info(`[SessionRoutes] Looking for permission ${$} in session ${V}`),X.info(`[SessionRoutes] Active runs: ${D.size}`);for(let[O,M]of D.entries())if(X.info(`[SessionRoutes] Checking run ${O}: sessionId=${M.sessionId}, pendingPermission=${M.pendingPermission?.permissionId}`),M.sessionId===V&&M.pendingPermission?.permissionId===$)return M.pendingPermission.resolve(f),X.info(`[SessionRoutes] Permission ${$} responded, runId: ${M.id}`),!0;return X.error(`[SessionRoutes] Permission not found: ${$}`),!1}var Vf=x("Service"),K0=C.object({approved:C.boolean(),remember:C.boolean().optional(),scope:C.enum(["once","session"]).optional(),targetMode:C.enum(["default","autoEdit","plan","spec","yolo"]).optional(),feedback:C.string().optional(),answers:C.record(C.union([C.string(),C.array(C.string())])).optional()}),Cf=()=>{let V=new Z0;return V.post("/:permissionId",async($)=>{let f=$.req.param("permissionId"),O=$.req.query("sessionId");Vf.info(`[PermissionRoutes] Received permission response: permissionId=${f}, sessionId=${O}`);try{let M=await $.req.json(),J=K0.safeParse(M);if(!J.success)throw new A("Invalid permission response format");let{approved:j,remember:Y,scope:K,targetMode:Q,feedback:Z,answers:G}=J.data;if(!O)throw new A("sessionId query parameter is required");if(!Af(O,f,{approved:j,reason:Z,scope:K,targetMode:Q,feedback:Z,answers:G}))throw new P("Permission request",f);return Vf.info(`[PermissionRoutes] Permission ${f} ${j?"approved":"denied"}`),$.json({success:!0,approved:j,remember:Y})}catch(M){throw Vf.error("[PermissionRoutes] Failed to respond to permission:",M),M}}),V};import{Hono as G0}from"hono";var Hf=x("Service"),yf=()=>{let V=new G0;return V.get("/",async($)=>{try{let f=await zf();return $.json(f)}catch(f){return Hf.error("[ProviderRoutes] Failed to list providers:",f),$.json([])}}),V.get("/:provider/models",async($)=>{let f=$.req.param("provider");try{let O=await Tf(f);return $.json(O)}catch(O){return Hf.error("[ProviderRoutes] Failed to list models:",O),$.json([])}}),V};import{Hono as N0}from"hono";import*as y from"node:fs/promises";import{homedir as m0}from"node:os";import*as n from"node:path";var b=x("Service"),Of=n.join(m0(),".blade","skills-config.json");async function Df(){try{let V=await y.readFile(Of,"utf-8");return JSON.parse(V)}catch{return{disabled:[]}}}async function x0(V){await y.mkdir(n.dirname(Of),{recursive:!0}),await y.writeFile(Of,JSON.stringify(V,null,2))}async function R0(V,$){let f=await Df();if($)f.disabled=f.disabled.filter((O)=>O!==V);else if(!f.disabled.includes(V))f.disabled.push(V);await x0(f)}var I=null,X0=300000;async function E0(){if(I&&Date.now()-I.timestamp<X0)return I.data;try{let V=await fetch("https://api.github.com/repos/anthropics/skills/contents/skills",{headers:{Accept:"application/vnd.github.v3+json","User-Agent":"Blade-Skills-Catalog"}});if(!V.ok)return b.warn(`GitHub API returned ${V.status}`),I?.data||[];let $=await V.json(),f=[];for(let O of $){if(O.type!=="dir")continue;let M=`Official ${O.name} skill`;try{let J=await fetch(`https://raw.githubusercontent.com/anthropics/skills/main/skills/${O.name}/SKILL.md`,{headers:{"User-Agent":"Blade-Skills-Catalog"}});if(J.ok){let Y=(await J.text()).match(/^#[^\n]*\n+([^\n#]+)/);if(Y)M=Y[1].trim().slice(0,100)}}catch{}f.push({name:O.name,description:M,tag:"Official",author:"Anthropic"})}return I={data:f,timestamp:Date.now()},f}catch(V){return b.warn("Failed to fetch skills catalog from GitHub:",V),I?.data||[]}}var bf=()=>{let V=new N0;return V.get("/",async($)=>{try{let f=t();await f.initialize();let O=f.getAll(),M=await Df(),J=O.map((j)=>({id:j.name,name:j.name,enabled:!M.disabled.includes(j.name),description:j.description||"",version:j.version||"1.0.0",provider:"Local",location:j.source==="builtin"?"Built-in":j.basePath,capabilities:["prompts"],allowedTools:j.allowedTools||[]}));return $.json(J)}catch(f){return b.error("[SkillsRoutes] Failed to get skills:",f),$.json([])}}),V.post("/:name/toggle",async($)=>{try{let f=$.req.param("name"),O=await $.req.json();return await R0(f,O.enabled),$.json({success:!0,enabled:O.enabled})}catch(f){return b.error("[SkillsRoutes] Failed to toggle skill:",f),$.json({success:!1,error:f.message},500)}}),V.delete("/:name",async($)=>{try{let f=$.req.param("name"),O=`${process.env.HOME}/.blade/skills/${f}`;return await y.rm(O,{recursive:!0,force:!0}),await t().refresh(),$.json({success:!0})}catch(f){return b.error("[SkillsRoutes] Failed to uninstall skill:",f),$.json({success:!1,error:f.message},500)}}),V.post("/install",async($)=>{try{let f=await $.req.json(),O=_f(),M=t(),J=!1;if(f.source==="catalog"&&f.name){if(J=await O.installOfficialSkill(f.name),!J)return $.json({success:!1,error:"Failed to install skill from catalog"},500)}else if(f.source==="repo"&&f.url){if(J=await O.installFromRepo(f.url,f.name),!J)return $.json({success:!1,error:"Failed to install skill from repository. Make sure the repo contains a SKILL.md file."},500)}else if(f.source==="local"&&f.path){if(J=await O.installFromLocal(f.path,f.name),!J)return $.json({success:!1,error:"Failed to install skill from local path. Make sure the path exists and contains a SKILL.md file."},500)}else return $.json({success:!1,error:"Invalid install parameters. Required: source with corresponding url/path/name"},400);return await M.refresh(),$.json({success:!0})}catch(f){return b.error("[SkillsRoutes] Failed to install skill:",f),$.json({success:!1,error:f.message},500)}}),V.get("/catalog",async($)=>{try{let f=await E0();return $.json(f)}catch(f){return b.error("[SkillsRoutes] Failed to get catalog:",f),$.json([])}}),V};import F0 from"fast-glob";import{Hono as U0}from"hono";import{execSync as q0}from"node:child_process";import{readdir as B0}from"node:fs/promises";import i from"node:path";var r=x("Service"),W0=(V)=>{try{return q0("git rev-parse --abbrev-ref HEAD",{cwd:V,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||null}catch{return null}},A0=[...s.map((V)=>`${V}/**`),...s,...Mf.map((V)=>`**/${V}`)],C0=new Set(["/theme","/model","/permissions","/mcp","/skills","/exit","/resume","/ide","/login","/logout"]),Pf=()=>{let V=new U0;return V.get("/commands",async($)=>{try{let f=$.req.query("q")||"",O=Lf(f).filter((M)=>!C0.has(M.command));return $.json(O)}catch(f){return r.error("[SuggestionsRoutes] Failed to get command suggestions:",f),$.json([])}}),V.get("/files",async($)=>{try{let f=$.req.query("q")||"",O=$.get("directory")||R(),M=Math.min(Number($.req.query("limit"))||100,1000),j=(await F0("**/*",{cwd:O,dot:!1,followSymbolicLinks:!1,onlyFiles:!1,markDirectories:!0,unique:!0,ignore:A0})).map((Q)=>Q.replace(/\\/g,"/"));if(!f)return $.json(j.slice(0,M));let Y=f.toLowerCase(),K=j.filter((Q)=>Q.toLowerCase().includes(Y)).slice(0,M);return $.json(K)}catch(f){return r.error("[SuggestionsRoutes] Failed to get file suggestions:",f),$.json([])}}),V.get("/files/tree",async($)=>{try{let f=$.get("directory")||R(),O=$.req.query("path")||"",M=O?i.join(f,O):f,j=(await B0(M,{withFileTypes:!0})).map((Q)=>({name:Q.name,path:O?`${O}/${Q.name}`:Q.name,type:Q.isDirectory()?"dir":"file"}));j.sort((Q,Z)=>{if(Q.type!==Z.type)return Q.type==="dir"?-1:1;return Q.name.localeCompare(Z.name)});let Y=new Set(s),K=j.filter((Q)=>{let Z=Q.name;if(Z.startsWith("."))return!1;if(Y.has(Z))return!1;for(let G of Mf)if(Z.match(new RegExp(G.replace("*",".*"))))return!1;return!0});return $.json(K)}catch(f){return r.error("[SuggestionsRoutes] Failed to get file tree:",f),$.json([])}}),V.get("/files/content",async($)=>{try{let f=$.req.query("path");if(!f)return $.json({error:"Missing file path"},400);let O=$.get("directory")||R(),M=i.resolve(O,f),J=i.relative(O,M);if(J.startsWith("..")||i.isAbsolute(J))return $.json({error:"Invalid file path"},400);let j=wf(),Y=await j.stat(M);if(!Y?.isFile)return $.json({error:"File not found"},404);let K=200000,Q=await j.readTextFile(M),Z=Q.length>K;return $.json({path:f,content:Z?Q.slice(0,K):Q,truncated:Z,size:Y.size})}catch(f){return r.error("[SuggestionsRoutes] Failed to get file content:",f),$.json({error:"Failed to read file"},500)}}),V.get("/git-info",async($)=>{try{let f=$.get("directory")||R(),O=W0(f);return $.json({branch:O})}catch(f){return r.error("[SuggestionsRoutes] Failed to get git info:",f),$.json({branch:null})}}),V};import{Hono as H0}from"hono";var _=x("Service"),v=new Map,kf=2097152,Sf=65536;function uf(){return typeof globalThis.Bun<"u"}async function z0(V,$,f){if(uf()){let{spawn:J}=await import("bun-pty"),j=J(V,$,{name:"xterm-256color",cwd:f.cwd,env:f.env});return{pid:j.pid,write:(Y)=>j.write(Y),resize:(Y,K)=>j.resize(Y,K),kill:()=>j.kill(),onData:(Y)=>j.onData(Y),onExit:(Y)=>j.onExit(Y)}}let M=(await import("node-pty")).spawn(V,$,{name:"xterm-256color",cwd:f.cwd,env:f.env,cols:80,rows:24});return{pid:M.pid,write:(J)=>M.write(J),resize:(J,j)=>M.resize(J,j),kill:()=>M.kill(),onData:(J)=>{M.onData(J)},onExit:(J)=>{M.onExit(J)}}}var Qf=void 0,Jf;if(uf())try{let{createBunWebSocket:V}=await import("hono/bun"),$=V();Jf=$.upgradeWebSocket,Qf=$.websocket}catch(V){_.warn("[Terminal] Failed to initialize Bun WebSocket support:",V)}async function hf(V,$){let f=`term-${Date.now()}`;_.info(`[Terminal] New connection: ${f}, cwd: ${V}`);let O=process.platform==="win32"?"powershell.exe":process.env.SHELL||"/bin/zsh",M=O.endsWith("sh")?["-l"]:[],J=await z0(O,M,{cwd:V,env:{...process.env,TERM:"xterm-256color",COLORTERM:"truecolor"}}),j={id:f,process:J,cwd:V,buffer:"",subscribers:new Set};if(v.set(f,j),j.subscribers.add($),J.onData((Y)=>{let K=!1;for(let Q of j.subscribers)try{Q.send(Y),K=!0}catch{j.subscribers.delete(Q)}if(K)return;if(j.buffer+=Y,j.buffer.length>kf)j.buffer=j.buffer.slice(-kf)}),J.onExit(({exitCode:Y})=>{_.info(`[Terminal] Process exited: ${f}, code: ${Y}`);for(let K of j.subscribers)try{K.close()}catch{}v.delete(f)}),j.buffer){let Y=j.buffer;j.buffer="";for(let K=0;K<Y.length;K+=Sf)$.send(Y.slice(K,K+Sf))}return{session:j,cleanup:()=>{if(_.info(`[Terminal] Connection closed: ${f}`),j.subscribers.delete($),j.subscribers.size===0){try{j.process.kill()}catch{}v.delete(f)}}}}function If(V,$){V.on("connection",async(f,O)=>{let M=new URL(O.url||"/",`http://${O.headers.host}`);if(!M.pathname.endsWith("/terminal/ws")){f.close();return}let J=M.searchParams.get("cwd")||$()||R();try{let{session:j,cleanup:Y}=await hf(J,{send:(K)=>f.send(K),close:()=>f.close()});f.on("message",(K)=>{try{j.process.write(String(K))}catch(Q){_.error("[Terminal] Failed to write to PTY:",Q)}}),f.on("close",Y),f.on("error",Y)}catch(j){_.error("[Terminal] Failed to spawn PTY:",j),f.close()}})}var vf=()=>{let V=new H0;if(V.get("/status",($)=>{let f=Array.from(v.values()).map((O)=>({id:O.id,cwd:O.cwd}));return $.json({active:f.length,terminals:f})}),V.post("/kill/:terminalId",($)=>{let f=$.req.param("terminalId"),O=v.get(f);if(O){try{O.process.kill()}catch{}for(let M of O.subscribers)M.close();return v.delete(f),$.json({success:!0})}return $.json({success:!1,error:"Terminal not found"},404)}),Jf)V.get("/ws",Jf(($)=>{let f=$.req.query("cwd")||$.get("directory")||R(),O;return{async onOpen(M,J){try{O=await hf(f,{send:(j)=>J.send(j),close:()=>J.close()})}catch(j){_.error("[Terminal] Failed to spawn PTY:",j),J.close()}},onMessage(M){if(!O)return;try{O.session.process.write(String(M.data))}catch(J){_.error("[Terminal] Failed to write to PTY:",J)}},onClose(){O?.cleanup()}}}));else V.get("/ws",($)=>{return $.json({message:"WebSocket endpoint - connect via ws:// protocol",hint:"Use WebSocket client to connect to this endpoint"})});return V};var W=x("Service"),Yf=[];function k0(){let V=b0(L0(import.meta.url)),$=[w(V,"web"),w(R(),"dist/web"),w(R(),"packages/cli/dist/web")];for(let f of $){let O=w(f,"index.html");if(gf(O)){if(e(O,"utf-8").includes("/assets/"))return W.debug(`[Server] Found web dist at: ${f}`),f}}return null}function S0(){let V=new T0;V.onError((f,O)=>{if(W.error("[Server] Request error:",f),f instanceof p)return O.json(f.toObject(),f.statusCode);let M=f instanceof Error?f.message:String(f);return O.json({error:{code:"INTERNAL_ERROR",message:M}},500)}),V.use(async(f,O)=>{let M=process.env.BLADE_SERVER_PASSWORD;if(!M)return O();let J=f.req.path;if(J==="/"||J.startsWith("/assets/")||J.endsWith(".html")||J.endsWith(".js")||J.endsWith(".css"))return O();let j=f.req.header("Authorization");if(!j?.startsWith("Basic "))return f.header("WWW-Authenticate",'Basic realm="Blade Server"'),f.json({error:{code:"UNAUTHORIZED",message:"Authentication required"}},401);let Y=Buffer.from(j.slice(6),"base64").toString(),[K,Q]=Y.split(":"),Z=process.env.BLADE_SERVER_USERNAME??"blade";if(K!==Z||Q!==M)return f.json({error:{code:"UNAUTHORIZED",message:"Invalid credentials"}},401);return O()}),V.use(async(f,O)=>{let M=f.req.path==="/health"||f.req.path==="/global/health"||f.req.path.startsWith("/assets/");if(!M)W.debug(`[Server] ${f.req.method} ${f.req.path}`);let J=Date.now();if(await O(),!M){let j=Date.now()-J;W.debug(`[Server] ${f.req.method} ${f.req.path} - ${f.res.status} (${j}ms)`)}}),V.use(y0({origin(f){if(!f)return;if(f.startsWith("http://localhost:"))return f;if(f.startsWith("http://127.0.0.1:"))return f;if(f==="tauri://localhost"||f==="http://tauri.localhost")return f;if(Yf.includes(f))return f;return}})),V.use(async(f,O)=>{let M=f.req.query("directory")||f.req.header("x-blade-directory")||R();try{M=decodeURIComponent(M)}catch{}return f.set("directory",M),O()}),V.route("/global",Nf()),V.route("/sessions",Wf()),V.route("/configs",Gf()),V.route("/permissions",Cf()),V.route("/providers",yf()),V.route("/models",Xf()),V.route("/suggestions",Pf()),V.route("/terminal",vf()),V.route("/mcp",mf()),V.route("/skills",bf()),V.get("/health",(f)=>{return f.json({healthy:!0,version:u()})});let $=k0();if($)W.info(`[Server] Serving static files from ${$}`),V.get("/assets/*",(f)=>{let O=w($,f.req.path);if(!gf(O))return f.json({error:{code:"NOT_FOUND",message:`File not found: ${f.req.path}`}},404);let M=e(O),J=w0(O).toLowerCase(),Y={".js":"application/javascript",".css":"text/css",".html":"text/html",".json":"application/json",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".svg":"image/svg+xml",".ico":"image/x-icon",".woff":"font/woff",".woff2":"font/woff2",".ttf":"font/ttf",".eot":"application/vnd.ms-fontobject"}[J]||"application/octet-stream";return new Response(M,{headers:{"Content-Type":Y,"Cache-Control":"public, max-age=31536000, immutable"}})}),V.get("/",(f)=>{let O=w($,"index.html"),M=e(O,"utf-8");return f.html(M)}),V.get("*",(f)=>{let O=f.req.path;if(O.includes("."))return f.json({error:{code:"NOT_FOUND",message:`File not found: ${O}`}},404);let M=w($,"index.html"),J=e(M,"utf-8");return f.html(J)});else W.warn('[Server] Web UI not found. Run "cd packages/cli/web && bun run build" to enable web interface.'),V.get("/",(f)=>{return f.json({message:"Blade API Server",version:u(),webUI:!1,hint:'Web UI not built. Run "cd packages/cli/web && bun run build" to enable.',endpoints:{health:"/health",sessions:"/sessions",configs:"/configs",permissions:"/permissions",providers:"/providers"}})}),V.all("*",(f)=>{return f.json({error:{code:"NOT_FOUND",message:`Route not found: ${f.req.path}`}},404)});return V}function u0(){let V=D0(),$=[];for(let f of Object.keys(V)){let O=V[f];if(!O)continue;for(let M of O){if(M.internal||M.family!=="IPv4")continue;if(M.address.startsWith("172."))continue;$.push(M.address)}}return $}function pf(){return typeof globalThis.Bun<"u"}function of(V,$){let f=globalThis.Bun,O=(J)=>{try{return f.serve({hostname:$.hostname,port:J,fetch:V.fetch,idleTimeout:0,websocket:Qf})}catch(j){W.error("Failed to start Bun server:",j);return}},M=$.port===0?O(4096)??O(0):O($.port);if(!M)throw Error(`Failed to start Bun server on port ${$.port}`);return{url:M.url,port:M.port,hostname:M.hostname,stop:async()=>{M.stop(!0)}}}function h0(V,$){return new Promise((f,O)=>{let M=_0(async(Q,Z)=>{let G=new URL(Q.url||"/",`http://${Q.headers.host}`),m=new Headers;for(let[E,N]of Object.entries(Q.headers))if(N)if(Array.isArray(N))for(let F of N)m.append(E,F);else m.set(E,N);let q;if(Q.method!=="GET"&&Q.method!=="HEAD")q=(await new Promise((N)=>{let F=[];Q.on("data",(l)=>F.push(l)),Q.on("end",()=>N(Buffer.concat(F)))})).toString();let L=new Request(G.toString(),{method:Q.method,headers:m,body:q});try{let E=await V.fetch(L);if(Z.statusCode=E.status,E.headers.forEach((N,F)=>{Z.setHeader(F,N)}),E.body){let N=E.body.getReader(),F=async()=>{let{done:l,value:ff}=await N.read();if(l){Z.end();return}return Z.write(ff),F()};await F()}else{let N=await E.text();Z.end(N)}}catch(E){W.error("[Server] Node request error:",E),Z.statusCode=500,Z.end(JSON.stringify({error:{code:"INTERNAL_ERROR",message:"Internal server error"}}))}}),J=new P0({noServer:!0}),j=R();If(J,()=>j),M.on("upgrade",(Q,Z,G)=>{if(new URL(Q.url||"/",`http://${Q.headers.host}`).pathname==="/terminal/ws")J.handleUpgrade(Q,Z,G,(q)=>{J.emit("connection",q,Q)});else Z.destroy()});let Y=(Q)=>{return new Promise((Z,G)=>{M.once("error",(m)=>{if(m.code==="EADDRINUSE")G(m);else G(m)}),M.listen(Q,$.hostname,()=>{let m=M.address();if(m&&typeof m==="object")Z(m.port);else Z(Q)})})};(async()=>{let Q;if($.port===0)try{Q=await Y(4096)}catch{Q=await Y(0)}else Q=await Y($.port);let Z=new URL(`http://${$.hostname==="0.0.0.0"?"localhost":$.hostname}:${Q}`);f({url:Z,port:Q,hostname:$.hostname,stop:async()=>{return new Promise((G)=>{J.close(()=>{M.close(()=>G())})})}})})().catch(O)})}var df;((DV)=>{let V,$;function f(){if(!$)$=S0();return $}DV.getApp=f;function O(j){Yf=j.cors??[];let Y=f();if(pf())V=of(Y,j),W.info(`[Server] Blade server listening on ${V.url} (Bun runtime)`);else throw Error("Blade web server requires Bun runtime. Please run with Bun: `bun run blade web` or install Bun from https://bun.sh");let K=V;return{url:K.url,port:K.port,hostname:K.hostname,stop:async()=>{if(V)await V.stop(),V=void 0,$=void 0,W.info("[Server] Blade server stopped")}}}DV.listen=O;async function M(j){Yf=j.cors??[];let Y=f();if(pf())V=of(Y,j),W.info(`[Server] Blade server listening on ${V.url} (Bun runtime)`);else V=await h0(Y,j),W.info(`[Server] Blade server listening on ${V.url} (Node.js runtime)`);let K=V;return{url:K.url,port:K.port,hostname:K.hostname,stop:async()=>{if(V)await V.stop(),V=void 0,$=void 0,W.info("[Server] Blade server stopped")}}}DV.listenAsync=M;function J(){return V!==void 0}DV.isRunning=J})(df||={});export{I0 as a,v0 as b,u0 as c,df as d};
@@ -1,4 +1,4 @@
1
- import{p as _,q as x,r as E,s as N}from"./chunk-jpe7hkkr.js";import{t as A}from"./chunk-fq64rt80.js";import{v as B,w as D,x as L}from"./chunk-5mqvwzj8.js";import{G as $,M as b}from"./chunk-ds6m379k.js";import"./chunk-v1nfdykq.js";import"./chunk-mxrre2n3.js";import"./chunk-cbcws8wy.js";import"./chunk-68ctb04g.js";import"./chunk-x9zj0r7s.js";import"./chunk-mz6n4w13.js";import{Sa as Z}from"./chunk-c3nh2cc1.js";import"./chunk-yddnm9n2.js";import"./chunk-yk91w5p2.js";import"./chunk-37rethcy.js";import{wb as X,xb as Y}from"./chunk-7ycmx7c2.js";import"./chunk-set7v1rf.js";import"./chunk-j2ag7hh6.js";import f from"yargs";import{hideBin as h}from"yargs/helpers";var R=new Set(Object.values(X));function W(k){if(k&&R.has(k))return k;return}function w(k){return k.command("* [message]","Print response and exit (useful for pipes)",(F)=>F.positional("message",{describe:"Message to process",type:"string"}).option("p",{alias:"print",describe:"Print response and exit (useful for pipes)",type:"boolean"}).option("output-format",{describe:'Output format: "text", "json", "stream-json"',type:"string",default:"text"}).option("include-partial-messages",{describe:"Include partial message chunks as they arrive",type:"boolean"}).option("input-format",{describe:'Input format: "text", "stream-json"',type:"string",default:"text"}).option("model",{describe:"Model for the current session",type:"string"}).option("append-system-prompt",{describe:"Append a system prompt to the default system prompt",type:"string"}).option("system-prompt",{describe:"Replace the default system prompt",type:"string"}).option("max-turns",{alias:["maxTurns"],describe:"Maximum conversation turns (-1: unlimited, N>0: limit to N turns)",type:"number"}),async(F)=>{if(!F.p)return;let q=await M(F);process.exit(q)})}async function M(k,F=process){let q;try{await _();let J=await x({message:k.message,_:k._,defaultMessage:"Hello"}),G=await E(J);if(G.mode==="output"){if(G.content)F.stdout.write(`${G.content}
1
+ import{p as _,q as x,r as E,s as N}from"./chunk-7wsn6pe7.js";import{t as A}from"./chunk-gr86637a.js";import{v as B,w as D,x as L}from"./chunk-5mqvwzj8.js";import{G as $,M as b}from"./chunk-tkjbcmc1.js";import"./chunk-p988nqta.js";import"./chunk-mxrre2n3.js";import"./chunk-7qw2xttt.js";import"./chunk-68ctb04g.js";import"./chunk-x9zj0r7s.js";import"./chunk-mz6n4w13.js";import{Sa as Z}from"./chunk-c3nh2cc1.js";import"./chunk-yddnm9n2.js";import"./chunk-yk91w5p2.js";import"./chunk-37rethcy.js";import{wb as X,xb as Y}from"./chunk-7ycmx7c2.js";import"./chunk-set7v1rf.js";import"./chunk-j2ag7hh6.js";import f from"yargs";import{hideBin as h}from"yargs/helpers";var R=new Set(Object.values(X));function W(k){if(k&&R.has(k))return k;return}function w(k){return k.command("* [message]","Print response and exit (useful for pipes)",(F)=>F.positional("message",{describe:"Message to process",type:"string"}).option("p",{alias:"print",describe:"Print response and exit (useful for pipes)",type:"boolean"}).option("output-format",{describe:'Output format: "text", "json", "stream-json"',type:"string",default:"text"}).option("include-partial-messages",{describe:"Include partial message chunks as they arrive",type:"boolean"}).option("input-format",{describe:'Input format: "text", "stream-json"',type:"string",default:"text"}).option("model",{describe:"Model for the current session",type:"string"}).option("append-system-prompt",{describe:"Append a system prompt to the default system prompt",type:"string"}).option("system-prompt",{describe:"Replace the default system prompt",type:"string"}).option("max-turns",{alias:["maxTurns"],describe:"Maximum conversation turns (-1: unlimited, N>0: limit to N turns)",type:"number"}),async(F)=>{if(!F.p)return;let q=await M(F);process.exit(q)})}async function M(k,F=process){let q;try{await _();let J=await x({message:k.message,_:k._,defaultMessage:"Hello"}),G=await E(J);if(G.mode==="output"){if(G.content)F.stdout.write(`${G.content}
2
2
  `);return G.exitCode??0}let Q=G.content,{sessionId:K,messages:T}=await N({sessionId:k.sessionId,continue:k.continue,resume:k.resume,fallbackSessionPrefix:"print"});q=await $.create({sessionId:K,modelId:k.model,mcpConfig:k.mcpConfig,strictMcpConfig:k.strictMcpConfig});let U=await b.createWithRuntime(q,{sessionId:K,systemPrompt:k.systemPrompt,appendSystemPrompt:k.appendSystemPrompt,maxTurns:k.maxTurns,modelId:k.model,permissionMode:W(k.permissionMode),toolWhitelist:k.allowedTools,toolBlacklist:k.disallowedTools,mcpConfig:k.mcpConfig,strictMcpConfig:k.strictMcpConfig}),H=(await Z(U.chatStream(Q,{messages:[...T],userId:"cli-user",sessionId:K,workspaceRoot:Y(),permissionMode:W(k.permissionMode)}))).finalMessage||"";if(k.outputFormat==="json")F.stdout.write(`${JSON.stringify({response:H,input:Q,model:k.model,timestamp:new Date().toISOString()},null,2)}
3
3
  `);else if(k.outputFormat==="stream-json")F.stdout.write(`${JSON.stringify({type:"response",content:H})}
4
4
  `);else F.stdout.write(`${H}
@@ -1,2 +1,2 @@
1
- var e={name:"blade-code",version:"0.5.15",private:!1,description:"🗡️ Blade Code - 智能代码助手命令行工具",type:"module",bin:{blade:"dist/blade.js"},files:["dist","vendor/ripgrep/**","README.md"],scripts:{dev:"node scripts/run-bun.js --watch src/blade.tsx","dev:serve":"node scripts/run-bun.js --watch src/blade.tsx serve --port 4097",build:"rm -rf dist && node scripts/run-bun.js run scripts/build.ts",start:"node scripts/run-bun.js run dist/blade.js",test:"node scripts/test.js","test:all":"vitest run --config vitest.config.ts","test:unit":"node scripts/test.js unit","test:integration":"node scripts/test.js integration","test:cli":"node scripts/test.js cli","test:headless-core":"node scripts/test.js headlessCore","test:e2e":"node scripts/test.js e2e","test:performance":"node scripts/test.js performance","test:snapshot":"node scripts/test.js snapshot","test:security":"node scripts/test.js security","test:coverage":"node scripts/test.js all --coverage","test:watch":"vitest --watch --config vitest.config.ts","benchmark:repo":"node scripts/run-bun.js run scripts/run-real-repo-benchmark.ts","test:update-snapshots":"node scripts/test.js snapshot --update",lint:"biome lint src tests","lint:fix":"biome lint --write src tests","type-check":"tsc --noEmit","format:check":"biome format src tests",ready:"node scripts/run-bun.js run scripts/ready.ts","detect-unused":"node scripts/run-bun.js run scripts/detect-unused.ts",release:"node scripts/release.js","release:dry":"node scripts/release.js --dry-run","release:major":"node scripts/release.js --major","release:minor":"node scripts/release.js --minor","release:patch":"node scripts/release.js --patch"},keywords:["cli","blade","ai","assistant","agent","llm"],author:"echoVic",license:"MIT",engines:{node:">=20.0.0"},optionalDependencies:{"@vscode/ripgrep":"^1.17.0","bun-pty":"^0.4.8","node-pty":"1.0.0"},dependencies:{"@agentclientprotocol/sdk":"^0.12.0","@ai-sdk/anthropic":"^3.0.7","@ai-sdk/azure":"^3.0.5","@ai-sdk/deepseek":"^2.0.4","@ai-sdk/google":"^3.0.4","@ai-sdk/openai":"^3.0.26","@ai-sdk/openai-compatible":"^2.0.4","@inkjs/ui":"^2.0.0","@modelcontextprotocol/sdk":"^1.17.4",ahooks:"^3.9.6",ai:"^6.0.39","ansi-escapes":"^7.2.0","async-mutex":"^0.5.0",axios:"^1.12.2",chalk:"^5.4.1",diff:"^8.0.2","fast-glob":"^3.3.3","fuse.js":"^7.1.0","gray-matter":"^4.0.3",hono:"^4.7.10",ink:"npm:@jrichman/ink@6.4.10","ink-big-text":"^2.0.0","ink-gradient":"^3.0.0","ink-select-input":"^6.2.0","ink-spinner":"^5.0.0","ink-text-input":"^6.0.0","js-tiktoken":"^1.0.21","lodash-es":"^4.17.21",lowlight:"^3.3.0","lru-cache":"^11.2.4",nanoid:"^5.1.6",open:"^10.1.2",openai:"^6.2.0",picomatch:"^4.0.3",react:"^19.1.1","react-dom":"^19.1.1",semver:"^7.7.3","string-width":"^8.1.0",undici:"^7.16.0","write-file-atomic":"^7.0.0",ws:"^8.18.0",yaml:"^2.8.1",yargs:"^18.0.0",zod:"^3.24.2","zod-to-json-schema":"^3.24.6",zustand:"^5.0.9"},devDependencies:{"@biomejs/biome":"^2.2.4","@types/bun":"^1.3.4","@types/json-schema":"^7.0.15","@types/lodash-es":"^4.17.12","@types/node":"^22.15.24","@types/picomatch":"^4.0.2","@types/react":"^19.1.1","@types/react-dom":"^19.1.1","@types/semver":"^7.7.1","@types/write-file-atomic":"^4.0.3","@types/ws":"^8.5.12","@types/yargs":"^17.0.33","@vitest/coverage-v8":"^3.0.0",jsdom:"^26.0.0",typescript:"^5.9.2",vitest:"^3.0.0"}};function r(){return{name:e.name,version:e.version,description:e.description}}function n(){return e.version}function o(){return e.name}function c(){return e.description}function d(){return`v${e.version}`}function a(){return`v${e.version} © 2025 Blade Code`}
1
+ var e={name:"blade-code",version:"0.5.17",private:!1,description:"🗡️ Blade Code - 智能代码助手命令行工具",type:"module",bin:{blade:"dist/blade.js"},files:["dist","vendor/ripgrep/**","README.md"],scripts:{dev:"node scripts/run-bun.js --watch src/blade.tsx","dev:serve":"node scripts/run-bun.js --watch src/blade.tsx serve --port 4097",build:"rm -rf dist && node scripts/run-bun.js run scripts/build.ts",start:"node scripts/run-bun.js run dist/blade.js",test:"node scripts/test.js","test:all":"vitest run --config vitest.config.ts","test:unit":"node scripts/test.js unit","test:integration":"node scripts/test.js integration","test:cli":"node scripts/test.js cli","test:headless-core":"node scripts/test.js headlessCore","test:e2e":"node scripts/test.js e2e","test:performance":"node scripts/test.js performance","test:snapshot":"node scripts/test.js snapshot","test:security":"node scripts/test.js security","test:coverage":"node scripts/test.js all --coverage","test:watch":"vitest --watch --config vitest.config.ts","benchmark:repo":"node scripts/run-bun.js run scripts/run-real-repo-benchmark.ts","test:update-snapshots":"node scripts/test.js snapshot --update",lint:"biome lint src tests","lint:fix":"biome lint --write src tests","type-check":"tsc --noEmit","format:check":"biome format src tests",ready:"node scripts/run-bun.js run scripts/ready.ts","detect-unused":"node scripts/run-bun.js run scripts/detect-unused.ts",release:"node scripts/release.js","release:dry":"node scripts/release.js --dry-run","release:major":"node scripts/release.js --major","release:minor":"node scripts/release.js --minor","release:patch":"node scripts/release.js --patch"},keywords:["cli","blade","ai","assistant","agent","llm"],author:"echoVic",license:"MIT",engines:{node:">=20.0.0"},optionalDependencies:{"@vscode/ripgrep":"^1.17.0","bun-pty":"^0.4.8","node-pty":"1.0.0"},dependencies:{"@agentclientprotocol/sdk":"^0.12.0","@ai-sdk/anthropic":"^3.0.7","@ai-sdk/azure":"^3.0.5","@ai-sdk/deepseek":"^2.0.4","@ai-sdk/google":"^3.0.4","@ai-sdk/openai":"^3.0.26","@ai-sdk/openai-compatible":"^2.0.4","@inkjs/ui":"^2.0.0","@modelcontextprotocol/sdk":"^1.17.4",ahooks:"^3.9.6",ai:"^6.0.39","ansi-escapes":"^7.2.0","async-mutex":"^0.5.0",axios:"^1.12.2",chalk:"^5.4.1",diff:"^8.0.2","fast-glob":"^3.3.3","fuse.js":"^7.1.0","gray-matter":"^4.0.3",hono:"^4.7.10",ink:"npm:@jrichman/ink@6.4.10","ink-big-text":"^2.0.0","ink-gradient":"^3.0.0","ink-select-input":"^6.2.0","ink-spinner":"^5.0.0","ink-text-input":"^6.0.0","js-tiktoken":"^1.0.21","lodash-es":"^4.17.21",lowlight:"^3.3.0","lru-cache":"^11.2.4",nanoid:"^5.1.6",open:"^10.1.2",openai:"^6.2.0",picomatch:"^4.0.3",react:"^19.1.1","react-dom":"^19.1.1",semver:"^7.7.3","string-width":"^8.1.0",undici:"^7.16.0","write-file-atomic":"^7.0.0",ws:"^8.18.0",yaml:"^2.8.1",yargs:"^18.0.0",zod:"^3.24.2","zod-to-json-schema":"^3.24.6",zustand:"^5.0.9"},devDependencies:{"@biomejs/biome":"^2.2.4","@types/bun":"^1.3.4","@types/json-schema":"^7.0.15","@types/lodash-es":"^4.17.12","@types/node":"^22.15.24","@types/picomatch":"^4.0.2","@types/react":"^19.1.1","@types/react-dom":"^19.1.1","@types/semver":"^7.7.1","@types/write-file-atomic":"^4.0.3","@types/ws":"^8.5.12","@types/yargs":"^17.0.33","@vitest/coverage-v8":"^3.0.0",jsdom:"^26.0.0",typescript:"^5.9.2",vitest:"^3.0.0"}};function r(){return{name:e.name,version:e.version,description:e.description}}function n(){return e.version}function o(){return e.name}function c(){return e.description}function d(){return`v${e.version}`}function a(){return`v${e.version} © 2025 Blade Code`}
2
2
  export{r as aa,n as ba,o as ca,c as da,d as ea,a as fa};
@@ -1,4 +1,4 @@
1
- import{N as l,O as c,P as m,S as g,U as d}from"./chunk-ds6m379k.js";import{xb as u}from"./chunk-7ycmx7c2.js";async function C(){if((await l().initialize(u(),[])).plugins.length>0)await c()}async function h(t){let e=t.message||t._?.[0];if(typeof e==="string"&&e.trim())return e;let n=t.stdin??process.stdin;if(!n.isTTY){let a=[];for await(let i of n)a.push(i);return Buffer.concat(a).toString("utf-8").trim()}if(t.defaultMessage!==void 0)return t.defaultMessage;throw Error("No input provided")}async function R(t){if(!g(t))return{mode:"agent",content:t};let e=await d(t,{cwd:u(),workspaceRoot:u()});if(!e.success)return{mode:"output",content:`Error: ${e.error||"未知错误"}`,exitCode:1};let n=e.data;if(n?.action==="invoke_skill"){let{skillName:a,skillArgs:i}=n;return{mode:"agent",content:i?`Please use the "${a}" skill to help me with: ${i}`:`Please use the "${a}" skill.`}}if(n?.action==="invoke_custom_command"||n?.action==="invoke_plugin_command"){let a=n.processedContent;return{mode:"agent",content:`# Custom Command: /${n.commandName}
1
+ import{N as l,O as c,P as m,S as g,U as d}from"./chunk-tkjbcmc1.js";import{xb as u}from"./chunk-7ycmx7c2.js";async function C(){if((await l().initialize(u(),[])).plugins.length>0)await c()}async function h(t){let e=t.message||t._?.[0];if(typeof e==="string"&&e.trim())return e;let n=t.stdin??process.stdin;if(!n.isTTY){let a=[];for await(let i of n)a.push(i);return Buffer.concat(a).toString("utf-8").trim()}if(t.defaultMessage!==void 0)return t.defaultMessage;throw Error("No input provided")}async function R(t){if(!g(t))return{mode:"agent",content:t};let e=await d(t,{cwd:u(),workspaceRoot:u()});if(!e.success)return{mode:"output",content:`Error: ${e.error||"未知错误"}`,exitCode:1};let n=e.data;if(n?.action==="invoke_skill"){let{skillName:a,skillArgs:i}=n;return{mode:"agent",content:i?`Please use the "${a}" skill to help me with: ${i}`:`Please use the "${a}" skill.`}}if(n?.action==="invoke_custom_command"||n?.action==="invoke_plugin_command"){let a=n.processedContent;return{mode:"agent",content:`# Custom Command: /${n.commandName}
2
2
 
3
3
  ${a}`}}return{mode:"output",content:e.content||e.message||"",exitCode:0}}function r(t){if(!(t instanceof Error))return!1;return t.message.includes("未找到会话")||t.message.includes("ENOENT")||t.message.includes("no such file")}async function s(t){try{return await m.loadSession(t,u())}catch(e){if(r(e))return null;throw e}}async function N(t){if(t.resume===!0||t.resume==="true")throw Error("--resume without a session ID is only supported in interactive UI mode");if(typeof t.resume==="string"&&t.resume.length>0)return{sessionId:t.resume,messages:await m.loadSession(t.resume)};if(t.continue){let e=await m.listSessions();if(e.length>0){let n=e[0].sessionId;return{sessionId:n,messages:await m.loadSession(n)}}}if(t.sessionId)return{sessionId:t.sessionId,messages:await s(t.sessionId)??[]};return{sessionId:`${t.fallbackSessionPrefix}-${Date.now()}`,messages:[]}}
4
4
  export{C as p,h as q,R as r,N as s};
@@ -1,4 +1,4 @@
1
- import{A as V,G as f,J as N,K as L,M as T,S as h,U as P,V as R}from"./chunk-ds6m379k.js";import{Y as M}from"./chunk-v1nfdykq.js";import"./chunk-mxrre2n3.js";import"./chunk-cbcws8wy.js";import"./chunk-68ctb04g.js";import{za as y}from"./chunk-x9zj0r7s.js";import"./chunk-mz6n4w13.js";import{Sa as O}from"./chunk-c3nh2cc1.js";import"./chunk-yddnm9n2.js";import"./chunk-yk91w5p2.js";import"./chunk-37rethcy.js";import{xb as D}from"./chunk-7ycmx7c2.js";import{Bb as W}from"./chunk-set7v1rf.js";import"./chunk-j2ag7hh6.js";import{Readable as K,Writable as k}from"node:stream";import*as _ from"@agentclientprotocol/sdk";import{PROTOCOL_VERSION as I}from"@agentclientprotocol/sdk";import{nanoid as S}from"nanoid";import{nanoid as x}from"nanoid";var X=W("Agent");class B{id;cwd;connection;clientCapabilities;agent=null;runtime=null;pendingPrompt=null;messages=[];mode="default";sessionApprovals=new Set;constructor(z,G,H,Q){this.id=z;this.cwd=G;this.connection=H;this.clientCapabilities=Q}async initialize(){X.debug(`[AcpSession ${this.id}] Initializing...`),V.initializeSession(this.connection,this.id,this.clientCapabilities,this.cwd),X.debug(`[AcpSession ${this.id}] ACP service context initialized`),this.runtime=await f.create({sessionId:this.id}),this.agent=await T.createWithRuntime(this.runtime,{sessionId:this.id}),X.debug(`[AcpSession ${this.id}] Agent created successfully`)}sendAvailableCommandsDelayed(){X.debug(`[AcpSession ${this.id}] Scheduling available commands update (500ms delay)`),setTimeout(()=>{this.sendAvailableCommands()},500)}async handleSlashCommand(z,G){try{X.debug(`[AcpSession ${this.id}] Executing slash command: ${z}`);let H={cwd:this.cwd,signal:G,acp:{sendMessage:(U)=>{this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:U}})},sendToolStart:(U,Y,q)=>{let Z=`tool_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,E=this.mapToolKind(q);this.sendUpdate({sessionUpdate:"tool_call",toolCallId:Z,status:"in_progress",title:`${U}`,content:[{type:"content",content:{type:"text",text:JSON.stringify(Y,null,2)}}],kind:E})},sendToolResult:(U,Y)=>{if(Y.summary)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:Y.summary}})}}},Q=await P(z,H),J=Q.content||Q.message;if(J)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:J}});if(Q.error)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[FAIL] ${Q.error}`}});return{stopReason:Q.success?"end_turn":"cancelled"}}catch(H){return X.error(`[AcpSession ${this.id}] Slash command error:`,H),this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[FAIL] 命令执行失败: ${H instanceof Error?H.message:"未知错误"}`}}),{stopReason:"cancelled"}}}async sendAvailableCommands(){try{let z=R(),G=["model","permissions","theme","config","exit","ide"],Q=z.filter((J)=>!G.includes(J.name)).map((J)=>{let U;if(J.usage){let Y=J.usage.replace(/^\/\w+\s*/,"").trim();if(Y)U=Y}if(J.aliases?.length){let Y=`Aliases: ${J.aliases.join(", ")}`;U=U?`${U} | ${Y}`:Y}return{name:J.name,description:J.description,input:U?{hint:U}:void 0}});X.info(`[AcpSession ${this.id}] Sending available commands: ${JSON.stringify(Q.map((J)=>J.name))}`),this.sendUpdate({sessionUpdate:"available_commands_update",availableCommands:Q}),X.info(`[AcpSession ${this.id}] Sent ${Q.length} available commands`)}catch(z){X.error(`[AcpSession ${this.id}] Failed to send available commands:`,z)}}async prompt(z){V.setCurrentSession(this.id),this.pendingPrompt?.abort();let G=new AbortController;if(this.pendingPrompt=G,!this.agent)throw Error("Session not initialized");try{let H=this.resolvePrompt(z.prompt);if(X.debug(`[AcpSession ${this.id}] Received prompt: ${H.slice(0,100)}...`),h(H))return await this.handleSlashCommand(H,G.signal);let Q={sessionId:this.id,userId:"acp-user",workspaceRoot:this.cwd,messages:[...this.messages],signal:G.signal,permissionMode:this.mapModeToPermissionMode(),confirmationHandler:{requestConfirmation:async(J)=>{return this.requestPermission(J)}}};if(await O(this.agent.chatStream(H,Q),async(J)=>{switch(J.kind){case"content_delta":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:J.delta}});break;case"thinking_delta":this.sendUpdate({sessionUpdate:"agent_thought_chunk",content:{type:"text",text:J.delta}});break;case"tool_start":{let U=J.toolCall,Y="function"in U?U.function.name:U.type,q=this.mapToolKind(J.toolKind);this.sendUpdate({sessionUpdate:"tool_call",toolCallId:U.id,status:"in_progress",title:`Executing ${Y}`,content:[],kind:q});break}case"tool_result":{let{toolCall:U,result:Y}=J,q=[],Z=Y.metadata;if(Z?.kind==="edit"&&typeof Z.file_path==="string"&&typeof Z.oldContent==="string"&&(typeof Z.newContent==="string"||Z.newContent===void 0))q.push({type:"diff",path:Z.file_path,oldText:Z.oldContent,newText:Z.newContent??null});else{let F="function"in U?U.function.name:U.type,j=L(N(F,Y));q.push({type:"content",content:{type:"text",text:j}})}let E=Y.success?"completed":"failed";this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:U.id,status:E,content:q});break}case"task_update":this.sendPlanUpdate(J.tasks);break;default:break}}),this.messages=[...Q.messages],G.signal.aborted)return{stopReason:"cancelled"};return{stopReason:"end_turn"}}catch(H){if(G.signal.aborted||H instanceof Error&&H.name==="AbortError")return{stopReason:"cancelled"};throw X.error(`[AcpSession ${this.id}] Prompt error:`,H),H}finally{if(this.pendingPrompt===G)this.pendingPrompt=null}}cancel(){if(X.info(`[AcpSession ${this.id}] Cancel requested`),this.pendingPrompt)this.pendingPrompt.abort(),this.pendingPrompt=null,X.info(`[AcpSession ${this.id}] Cancelled successfully`);else X.warn(`[AcpSession ${this.id}] No pending prompt to cancel`)}async setMode(z){let G=["default","auto-edit","yolo","plan"];this.mode=G.includes(z)?z:"default",X.info(`[AcpSession ${this.id}] Mode set to: ${this.mode}`),this.sendUpdate({sessionUpdate:"current_mode_update",currentModeId:this.mode})}mapModeToPermissionMode(){switch(this.mode){case"yolo":return"yolo";case"auto-edit":return"autoEdit";case"plan":return"plan";case"default":default:return"default"}}shouldAutoApprove(z){switch(this.mode){case"yolo":return!0;case"auto-edit":return z==="readonly"||z==="write";case"plan":return z==="readonly";case"default":default:return!1}}async setModel(z){if(X.info(`[AcpSession ${this.id}] Model set to: ${z}`),this.agent)X.warn(`[AcpSession ${this.id}] Runtime model switching not yet implemented`)}async destroy(){if(this.cancel(),this.agent)await this.agent.destroy(),this.agent=null;if(this.runtime)await this.runtime.dispose(),this.runtime=null;V.destroySession(this.id),X.debug(`[AcpSession ${this.id}] Destroyed`)}resolvePrompt(z){let G=[];for(let H of z)if(H.type==="text")G.push(H.text);else if(H.type==="image")G.push(`[Image: ${H.mimeType}]`);else if(H.type==="resource"){let Q=H.resource;if("text"in Q)G.push(`<file path="${Q.uri}">
1
+ import{A as V,G as f,J as N,K as L,M as T,S as h,U as P,V as R}from"./chunk-tkjbcmc1.js";import{Y as M}from"./chunk-p988nqta.js";import"./chunk-mxrre2n3.js";import"./chunk-7qw2xttt.js";import"./chunk-68ctb04g.js";import{za as y}from"./chunk-x9zj0r7s.js";import"./chunk-mz6n4w13.js";import{Sa as O}from"./chunk-c3nh2cc1.js";import"./chunk-yddnm9n2.js";import"./chunk-yk91w5p2.js";import"./chunk-37rethcy.js";import{xb as D}from"./chunk-7ycmx7c2.js";import{Bb as W}from"./chunk-set7v1rf.js";import"./chunk-j2ag7hh6.js";import{Readable as K,Writable as k}from"node:stream";import*as _ from"@agentclientprotocol/sdk";import{PROTOCOL_VERSION as I}from"@agentclientprotocol/sdk";import{nanoid as S}from"nanoid";import{nanoid as x}from"nanoid";var X=W("Agent");class B{id;cwd;connection;clientCapabilities;agent=null;runtime=null;pendingPrompt=null;messages=[];mode="default";sessionApprovals=new Set;constructor(z,G,H,Q){this.id=z;this.cwd=G;this.connection=H;this.clientCapabilities=Q}async initialize(){X.debug(`[AcpSession ${this.id}] Initializing...`),V.initializeSession(this.connection,this.id,this.clientCapabilities,this.cwd),X.debug(`[AcpSession ${this.id}] ACP service context initialized`),this.runtime=await f.create({sessionId:this.id}),this.agent=await T.createWithRuntime(this.runtime,{sessionId:this.id}),X.debug(`[AcpSession ${this.id}] Agent created successfully`)}sendAvailableCommandsDelayed(){X.debug(`[AcpSession ${this.id}] Scheduling available commands update (500ms delay)`),setTimeout(()=>{this.sendAvailableCommands()},500)}async handleSlashCommand(z,G){try{X.debug(`[AcpSession ${this.id}] Executing slash command: ${z}`);let H={cwd:this.cwd,signal:G,acp:{sendMessage:(U)=>{this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:U}})},sendToolStart:(U,Y,q)=>{let Z=`tool_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,E=this.mapToolKind(q);this.sendUpdate({sessionUpdate:"tool_call",toolCallId:Z,status:"in_progress",title:`${U}`,content:[{type:"content",content:{type:"text",text:JSON.stringify(Y,null,2)}}],kind:E})},sendToolResult:(U,Y)=>{if(Y.summary)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:Y.summary}})}}},Q=await P(z,H),J=Q.content||Q.message;if(J)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:J}});if(Q.error)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[FAIL] ${Q.error}`}});return{stopReason:Q.success?"end_turn":"cancelled"}}catch(H){return X.error(`[AcpSession ${this.id}] Slash command error:`,H),this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[FAIL] 命令执行失败: ${H instanceof Error?H.message:"未知错误"}`}}),{stopReason:"cancelled"}}}async sendAvailableCommands(){try{let z=R(),G=["model","permissions","theme","config","exit","ide"],Q=z.filter((J)=>!G.includes(J.name)).map((J)=>{let U;if(J.usage){let Y=J.usage.replace(/^\/\w+\s*/,"").trim();if(Y)U=Y}if(J.aliases?.length){let Y=`Aliases: ${J.aliases.join(", ")}`;U=U?`${U} | ${Y}`:Y}return{name:J.name,description:J.description,input:U?{hint:U}:void 0}});X.info(`[AcpSession ${this.id}] Sending available commands: ${JSON.stringify(Q.map((J)=>J.name))}`),this.sendUpdate({sessionUpdate:"available_commands_update",availableCommands:Q}),X.info(`[AcpSession ${this.id}] Sent ${Q.length} available commands`)}catch(z){X.error(`[AcpSession ${this.id}] Failed to send available commands:`,z)}}async prompt(z){V.setCurrentSession(this.id),this.pendingPrompt?.abort();let G=new AbortController;if(this.pendingPrompt=G,!this.agent)throw Error("Session not initialized");try{let H=this.resolvePrompt(z.prompt);if(X.debug(`[AcpSession ${this.id}] Received prompt: ${H.slice(0,100)}...`),h(H))return await this.handleSlashCommand(H,G.signal);let Q={sessionId:this.id,userId:"acp-user",workspaceRoot:this.cwd,messages:[...this.messages],signal:G.signal,permissionMode:this.mapModeToPermissionMode(),confirmationHandler:{requestConfirmation:async(J)=>{return this.requestPermission(J)}}};if(await O(this.agent.chatStream(H,Q),async(J)=>{switch(J.kind){case"content_delta":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:J.delta}});break;case"thinking_delta":this.sendUpdate({sessionUpdate:"agent_thought_chunk",content:{type:"text",text:J.delta}});break;case"tool_start":{let U=J.toolCall,Y="function"in U?U.function.name:U.type,q=this.mapToolKind(J.toolKind);this.sendUpdate({sessionUpdate:"tool_call",toolCallId:U.id,status:"in_progress",title:`Executing ${Y}`,content:[],kind:q});break}case"tool_result":{let{toolCall:U,result:Y}=J,q=[],Z=Y.metadata;if(Z?.kind==="edit"&&typeof Z.file_path==="string"&&typeof Z.oldContent==="string"&&(typeof Z.newContent==="string"||Z.newContent===void 0))q.push({type:"diff",path:Z.file_path,oldText:Z.oldContent,newText:Z.newContent??null});else{let F="function"in U?U.function.name:U.type,j=L(N(F,Y));q.push({type:"content",content:{type:"text",text:j}})}let E=Y.success?"completed":"failed";this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:U.id,status:E,content:q});break}case"task_update":this.sendPlanUpdate(J.tasks);break;default:break}}),this.messages=[...Q.messages],G.signal.aborted)return{stopReason:"cancelled"};return{stopReason:"end_turn"}}catch(H){if(G.signal.aborted||H instanceof Error&&H.name==="AbortError")return{stopReason:"cancelled"};throw X.error(`[AcpSession ${this.id}] Prompt error:`,H),H}finally{if(this.pendingPrompt===G)this.pendingPrompt=null}}cancel(){if(X.info(`[AcpSession ${this.id}] Cancel requested`),this.pendingPrompt)this.pendingPrompt.abort(),this.pendingPrompt=null,X.info(`[AcpSession ${this.id}] Cancelled successfully`);else X.warn(`[AcpSession ${this.id}] No pending prompt to cancel`)}async setMode(z){let G=["default","auto-edit","yolo","plan"];this.mode=G.includes(z)?z:"default",X.info(`[AcpSession ${this.id}] Mode set to: ${this.mode}`),this.sendUpdate({sessionUpdate:"current_mode_update",currentModeId:this.mode})}mapModeToPermissionMode(){switch(this.mode){case"yolo":return"yolo";case"auto-edit":return"autoEdit";case"plan":return"plan";case"default":default:return"default"}}shouldAutoApprove(z){switch(this.mode){case"yolo":return!0;case"auto-edit":return z==="readonly"||z==="write";case"plan":return z==="readonly";case"default":default:return!1}}async setModel(z){if(X.info(`[AcpSession ${this.id}] Model set to: ${z}`),this.agent)X.warn(`[AcpSession ${this.id}] Runtime model switching not yet implemented`)}async destroy(){if(this.cancel(),this.agent)await this.agent.destroy(),this.agent=null;if(this.runtime)await this.runtime.dispose(),this.runtime=null;V.destroySession(this.id),X.debug(`[AcpSession ${this.id}] Destroyed`)}resolvePrompt(z){let G=[];for(let H of z)if(H.type==="text")G.push(H.text);else if(H.type==="image")G.push(`[Image: ${H.mimeType}]`);else if(H.type==="resource"){let Q=H.resource;if("text"in Q)G.push(`<file path="${Q.uri}">
2
2
  ${Q.text}
3
3
  </file>`)}else if(H.type==="resource_link")G.push(`[Resource: ${H.uri}]`);return G.join(`
4
4
  `)}sendUpdate(z){let G={sessionId:this.id,update:z};this.connection.sessionUpdate(G).catch((H)=>{X.warn(`[AcpSession ${this.id}] Failed to send update:`,H)})}sendPlanUpdate(z){let G=z.map((H)=>({content:H.subject,priority:H.priority,status:H.status}));X.debug(`[AcpSession ${this.id}] Sending plan update with ${G.length} entries`),this.sendUpdate({sessionUpdate:"plan",entries:G})}async requestPermission(z){let G=z.kind?.toLowerCase()||"execute";if(this.shouldAutoApprove(G))return X.debug(`[AcpSession ${this.id}] Auto-approving ${G} in mode: ${this.mode}`),{approved:!0};if(this.mode==="plan"&&(G==="write"||G==="execute"))return X.debug(`[AcpSession ${this.id}] Rejecting ${G} in plan mode`),{approved:!1,reason:"Write and execute operations are not allowed in Plan mode"};let H=`${G}:${z.title||"unknown"}`;if(this.sessionApprovals.has(H))return X.debug(`[AcpSession ${this.id}] Using cached approval for: ${H}`),{approved:!0};try{let Q=x(),J=[];if(z.message)J.push({type:"content",content:{type:"text",text:z.message}});if(z.risks&&z.risks.length>0)J.push({type:"content",content:{type:"text",text:`Risks:
@@ -1,4 +1,4 @@
1
- import{p as z,q as g,r as v,s as p}from"./chunk-jpe7hkkr.js";import{t as E}from"./chunk-fq64rt80.js";import{v as S,w as h,x as c}from"./chunk-5mqvwzj8.js";import{G as w,I as F,J as y,L as x,M as C}from"./chunk-ds6m379k.js";import"./chunk-v1nfdykq.js";import"./chunk-mxrre2n3.js";import"./chunk-cbcws8wy.js";import"./chunk-68ctb04g.js";import"./chunk-x9zj0r7s.js";import"./chunk-mz6n4w13.js";import{Sa as O}from"./chunk-c3nh2cc1.js";import"./chunk-yddnm9n2.js";import"./chunk-yk91w5p2.js";import"./chunk-37rethcy.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-7wsn6pe7.js";import{t as E}from"./chunk-gr86637a.js";import{v as S,w as h,x as c}from"./chunk-5mqvwzj8.js";import{G as w,I as F,J as y,L as x,M as C}from"./chunk-tkjbcmc1.js";import"./chunk-p988nqta.js";import"./chunk-mxrre2n3.js";import"./chunk-7qw2xttt.js";import"./chunk-68ctb04g.js";import"./chunk-x9zj0r7s.js";import"./chunk-mz6n4w13.js";import{Sa as O}from"./chunk-c3nh2cc1.js";import"./chunk-yddnm9n2.js";import"./chunk-yk91w5p2.js";import"./chunk-37rethcy.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{e as E2,f as h2}from"./chunk-q5yn875m.js";import{h as A4,i as v4,j as R4}from"./chunk-qwfywxs2.js";import{l as D$,m as k4,o as o1}from"./chunk-pfsft4nd.js";import{B as r8,C as e6,D as f4,E as X8,F as e1,G as h6,I as f6,J as D6,M as f$,N as M8,O as D4,P as _1,Q as wJ,R as bJ,S as M6,T as V4,U as C6,W as KJ,y as UJ}from"./chunk-ds6m379k.js";import{Y as S4}from"./chunk-v1nfdykq.js";import"./chunk-mxrre2n3.js";import{fa as I2}from"./chunk-cbcws8wy.js";import{ga as S8}from"./chunk-68ctb04g.js";import{Aa as x6,Ga as p0,ha as O$,ia as m0,ja as E1,ka as vQ,la as i1,ma as T$,na as iJ,oa as mQ,pa as D2,qa as nJ,sa as K4,ua as iQ,va as H1,wa as C4,xa as w1,ya as b4}from"./chunk-x9zj0r7s.js";import{Ha as I4,Ja as M4}from"./chunk-mz6n4w13.js";import{Na as G4,Oa as T4,Sa as d6}from"./chunk-c3nh2cc1.js";import"./chunk-yddnm9n2.js";import{mb as yQ,nb as L1}from"./chunk-yk91w5p2.js";import{qb as o2}from"./chunk-37rethcy.js";import{ub as AJ,xb as A0}from"./chunk-7ycmx7c2.js";import{Bb as j1,yb as P4}from"./chunk-set7v1rf.js";import{Db as s$}from"./chunk-j2ag7hh6.js";import{useMemoizedFn as dQ}from"ahooks";import{useEffect as c5,useState as lQ}from"react";import{useMemoizedFn as r0}from"ahooks";import{Box as l1}from"ink";import{useEffect as r1,useRef as T8}from"react";import{useShallow as nQ}from"zustand/react/shallow";import{useStore as c4}from"zustand";function Q0($){return c4(iQ,$)}var u4=[],tQ=()=>Q0(($)=>$.session.sessionId),sQ=()=>Q0(($)=>$.session.messages),eQ=()=>Q0(($)=>$.session.clearCount),$6=()=>Q0(($)=>$.session.isCompacting),Q6=()=>Q0(($)=>$.session.tokenUsage.estimatedCostUsd),f1=()=>Q0(($)=>$.session.actions),J6=()=>Q0(($)=>{let{inputTokens:Q,maxContextTokens:J}=$.session.tokenUsage;if(J<=0)return 100;let Y=Math.max(0,100-Q/J*100);return Math.round(Y)}),Y6=()=>Q0(($)=>$.app.initializationStatus),Z6=()=>Q0(($)=>$.app.initializationError),a$=()=>Q0(($)=>$.app.activeModal),X6=()=>Q0(($)=>$.app.tasks),q6=()=>Q0(($)=>$.app.modelEditorTarget),G6=()=>Q0(($)=>$.app.sessionSelectorData),U6=()=>Q0(($)=>$.app.awaitingSecondCtrlC),D1=()=>Q0(($)=>$.app.actions),o$=()=>Q0(($)=>$.app.initializationStatus==="ready"),K6=()=>Q0(($)=>$.app.tasks.length>0),_$=()=>Q0(($)=>$.config.config?.permissionMode||"default"),O6=()=>Q0(($)=>$.config.config?.models??u4),i$=()=>Q0(($)=>{let Q=$.config.config;if(!Q)return;let J=Q.currentModelId;return Q.models.find((Z)=>Z.id===J)??Q.models[0]}),z6=()=>Q0(($)=>$.config.config?.currentModelId),_0=()=>Q0(($)=>{return m0.getTheme()}),_6=()=>Q0(($)=>$.config.config?.theme??"default"),i0=()=>Q0(($)=>$.focus.currentFocus),N6=()=>Q0(($)=>$.focus.actions),V1=()=>Q0(($)=>$.command.isProcessing),F6=()=>Q0(($)=>$.command.actions),W6=()=>Q0(($)=>$.command.pendingCommands),n$=()=>Q0(($)=>$.app.thinkingModeEnabled),H6=()=>Q0(($)=>$.session.currentThinkingContent),L6=()=>Q0(($)=>$.session.thinkingExpanded),w6=()=>Q0(($)=>$.session.currentStreamingMessageId),b6=()=>Q0(nQ(($)=>({lines:$.session.currentStreamingLines,tail:$.session.currentStreamingTail,lineCount:$.session.currentStreamingLineCount,version:$.session.currentStreamingVersion}))),B6=()=>Q0(($)=>$.session.finalizingStreamingMessageId),A6=()=>Q0(($)=>$.session.historyExpanded),v6=()=>Q0(($)=>$.session.expandedMessageCount),R6=()=>Q0(nQ(($)=>{let Q=$.spec.currentSpec;if(!Q)return{phase:null,completed:0,total:0};let J=Q.tasks??[],Y=J.filter((Z)=>Z.status==="completed").length;return{phase:Q.phase,completed:Y,total:J.length}}));import{useMemoizedFn as u8}from"ahooks";import{useEffect as c6,useRef as Y9}from"react";function x4($){if(!($ instanceof Error))return"未知错误";let Y=$.lastError??$;if(Y.responseBody)try{let X=JSON.parse(Y.responseBody)?.error?.message;if(X){let G=Y.statusCode?` (HTTP ${Y.statusCode})`:"";return`${X}${G}`}}catch{}let Z=$.message.match(/Last error:\s*(.+)$/);if(Z)return Z[1];return $.message}function d4($){if(!($ instanceof Error))return!1;return $.name==="AbortError"||$.message.includes("aborted")}function l4($){if(!($ instanceof Error))return!1;let Q=$.message;return Q.includes("can only concatenate str")||Q.includes("image_url")||Q.includes("multimodal")||Q.includes("vision")||Q.includes("does not support images")}function m8($){let Q=d4($),J=l4($),Y;if(J)Y="当前模型不支持图片理解功能。请切换到支持视觉能力的模型(如 Claude 4.5、GPT-5.2、Gemini 3 Pro、Qwen3-VL-Plus 等)后重试。";else Y=x4($);return{displayMessage:Y,isAbort:Q,isVisionNotSupported:J}}function y6($){let{text:Q,images:J,parts:Y}=$;if(J.length===0)return Q;let Z=[];for(let q of Y)if(q.type==="text")Z.push({type:"text",text:q.text});else Z.push({type:"image_url",image_url:{url:`data:${q.mimeType};base64,${q.base64}`}});return Z}function P6($){return{role:$.role,content:$.content}}function I6($){if(!$.restoredContextMessages||$.restoredVisibleMessageCount<=0)return $.messages.map(P6);let Q=$.messages.slice($.restoredVisibleMessageCount).map(P6);return[...$.restoredContextMessages,...Q]}function r4($){return typeof $==="object"&&$!==null&&$.action==="invoke_skill"&&typeof $.skillName==="string"}function a4($){return typeof $==="object"&&$!==null&&$.action==="invoke_custom_command"&&typeof $.commandName==="string"&&typeof $.processedContent==="string"}function o4($){return typeof $==="object"&&$!==null&&$.action==="invoke_plugin_command"&&typeof $.commandName==="string"&&typeof $.processedContent==="string"}function i4($){return typeof $==="object"&&$!==null&&$.action==="invoke_once_model"&&typeof $.modelId==="string"&&typeof $.prompt==="string"}function n4($,Q,J,Y){switch($){case"show_theme_selector":return J.setActiveModal("themeSelector"),!0;case"show_model_selector":return J.setActiveModal("modelSelector"),!0;case"show_model_add_wizard":return J.setActiveModal("modelAddWizard"),!0;case"show_permissions_manager":return J.setActiveModal("permissionsManager"),!0;case"show_agents_manager":return J.setActiveModal("agentsManager"),!0;case"show_skills_manager":return J.setActiveModal("skillsManager"),!0;case"show_hooks_manager":return J.setActiveModal("hooksManager"),!0;case"show_plugins_manager":return J.setActiveModal("pluginsManager"),!0;case"show_agent_creation_wizard":return J.setActiveModal("agentCreationWizard"),!0;case"show_session_selector":{let Z=Q?.sessions;return J.showSessionSelector(Z),!0}case"clear_screen":return Y.clearMessages(),Y.setError(null),Y.resetTokenUsage(),J.setTasks([]),!0;case"compact_completed":case"compact_fallback":return Y.resetTokenUsage(),!0;case"exit_application":return o1(0),!0;default:return!1}}async function k6($,Q,J,Y){let{text:Z}=$;if(!M6(Z))return{type:"not_slash"};let q={cwd:A0(),signal:Y},X=await C6(Z,q);if(X.message){if(n4(X.message,X.data,Q,J))return{type:"handled",commandResult:{success:!0}}}if(r4(X.data)){let{skillName:K,skillArgs:U}=X.data,F=U?`Please use the "${K}" skill to help me with: ${U}`:`Please use the "${K}" skill.`;return J.addUserMessage(F),{type:"continue_as_agent",result:{userDisplayMessage:F,agentInput:{displayText:F,text:F,images:[],parts:[{type:"text",text:F}]},userMessageAlreadyAdded:!0}}}if(a4(X.data)){let{commandName:K,processedContent:U}=X.data;J.addUserMessage(Z);let F=`# Custom Command: /${K}
1
+ import{e as E2,f as h2}from"./chunk-q5yn875m.js";import{h as A4,i as v4,j as R4}from"./chunk-qwfywxs2.js";import{l as D$,m as k4,o as o1}from"./chunk-pfsft4nd.js";import{B as r8,C as e6,D as f4,E as X8,F as e1,G as h6,I as f6,J as D6,M as f$,N as M8,O as D4,P as _1,Q as wJ,R as bJ,S as M6,T as V4,U as C6,W as KJ,y as UJ}from"./chunk-tkjbcmc1.js";import{Y as S4}from"./chunk-p988nqta.js";import"./chunk-mxrre2n3.js";import{fa as I2}from"./chunk-7qw2xttt.js";import{ga as S8}from"./chunk-68ctb04g.js";import{Aa as x6,Ga as p0,ha as O$,ia as m0,ja as E1,ka as vQ,la as i1,ma as T$,na as iJ,oa as mQ,pa as D2,qa as nJ,sa as K4,ua as iQ,va as H1,wa as C4,xa as w1,ya as b4}from"./chunk-x9zj0r7s.js";import{Ha as I4,Ja as M4}from"./chunk-mz6n4w13.js";import{Na as G4,Oa as T4,Sa as d6}from"./chunk-c3nh2cc1.js";import"./chunk-yddnm9n2.js";import{mb as yQ,nb as L1}from"./chunk-yk91w5p2.js";import{qb as o2}from"./chunk-37rethcy.js";import{ub as AJ,xb as A0}from"./chunk-7ycmx7c2.js";import{Bb as j1,yb as P4}from"./chunk-set7v1rf.js";import{Db as s$}from"./chunk-j2ag7hh6.js";import{useMemoizedFn as dQ}from"ahooks";import{useEffect as c5,useState as lQ}from"react";import{useMemoizedFn as r0}from"ahooks";import{Box as l1}from"ink";import{useEffect as r1,useRef as T8}from"react";import{useShallow as nQ}from"zustand/react/shallow";import{useStore as c4}from"zustand";function Q0($){return c4(iQ,$)}var u4=[],tQ=()=>Q0(($)=>$.session.sessionId),sQ=()=>Q0(($)=>$.session.messages),eQ=()=>Q0(($)=>$.session.clearCount),$6=()=>Q0(($)=>$.session.isCompacting),Q6=()=>Q0(($)=>$.session.tokenUsage.estimatedCostUsd),f1=()=>Q0(($)=>$.session.actions),J6=()=>Q0(($)=>{let{inputTokens:Q,maxContextTokens:J}=$.session.tokenUsage;if(J<=0)return 100;let Y=Math.max(0,100-Q/J*100);return Math.round(Y)}),Y6=()=>Q0(($)=>$.app.initializationStatus),Z6=()=>Q0(($)=>$.app.initializationError),a$=()=>Q0(($)=>$.app.activeModal),X6=()=>Q0(($)=>$.app.tasks),q6=()=>Q0(($)=>$.app.modelEditorTarget),G6=()=>Q0(($)=>$.app.sessionSelectorData),U6=()=>Q0(($)=>$.app.awaitingSecondCtrlC),D1=()=>Q0(($)=>$.app.actions),o$=()=>Q0(($)=>$.app.initializationStatus==="ready"),K6=()=>Q0(($)=>$.app.tasks.length>0),_$=()=>Q0(($)=>$.config.config?.permissionMode||"default"),O6=()=>Q0(($)=>$.config.config?.models??u4),i$=()=>Q0(($)=>{let Q=$.config.config;if(!Q)return;let J=Q.currentModelId;return Q.models.find((Z)=>Z.id===J)??Q.models[0]}),z6=()=>Q0(($)=>$.config.config?.currentModelId),_0=()=>Q0(($)=>{return m0.getTheme()}),_6=()=>Q0(($)=>$.config.config?.theme??"default"),i0=()=>Q0(($)=>$.focus.currentFocus),N6=()=>Q0(($)=>$.focus.actions),V1=()=>Q0(($)=>$.command.isProcessing),F6=()=>Q0(($)=>$.command.actions),W6=()=>Q0(($)=>$.command.pendingCommands),n$=()=>Q0(($)=>$.app.thinkingModeEnabled),H6=()=>Q0(($)=>$.session.currentThinkingContent),L6=()=>Q0(($)=>$.session.thinkingExpanded),w6=()=>Q0(($)=>$.session.currentStreamingMessageId),b6=()=>Q0(nQ(($)=>({lines:$.session.currentStreamingLines,tail:$.session.currentStreamingTail,lineCount:$.session.currentStreamingLineCount,version:$.session.currentStreamingVersion}))),B6=()=>Q0(($)=>$.session.finalizingStreamingMessageId),A6=()=>Q0(($)=>$.session.historyExpanded),v6=()=>Q0(($)=>$.session.expandedMessageCount),R6=()=>Q0(nQ(($)=>{let Q=$.spec.currentSpec;if(!Q)return{phase:null,completed:0,total:0};let J=Q.tasks??[],Y=J.filter((Z)=>Z.status==="completed").length;return{phase:Q.phase,completed:Y,total:J.length}}));import{useMemoizedFn as u8}from"ahooks";import{useEffect as c6,useRef as Y9}from"react";function x4($){if(!($ instanceof Error))return"未知错误";let Y=$.lastError??$;if(Y.responseBody)try{let X=JSON.parse(Y.responseBody)?.error?.message;if(X){let G=Y.statusCode?` (HTTP ${Y.statusCode})`:"";return`${X}${G}`}}catch{}let Z=$.message.match(/Last error:\s*(.+)$/);if(Z)return Z[1];return $.message}function d4($){if(!($ instanceof Error))return!1;return $.name==="AbortError"||$.message.includes("aborted")}function l4($){if(!($ instanceof Error))return!1;let Q=$.message;return Q.includes("can only concatenate str")||Q.includes("image_url")||Q.includes("multimodal")||Q.includes("vision")||Q.includes("does not support images")}function m8($){let Q=d4($),J=l4($),Y;if(J)Y="当前模型不支持图片理解功能。请切换到支持视觉能力的模型(如 Claude 4.5、GPT-5.2、Gemini 3 Pro、Qwen3-VL-Plus 等)后重试。";else Y=x4($);return{displayMessage:Y,isAbort:Q,isVisionNotSupported:J}}function y6($){let{text:Q,images:J,parts:Y}=$;if(J.length===0)return Q;let Z=[];for(let q of Y)if(q.type==="text")Z.push({type:"text",text:q.text});else Z.push({type:"image_url",image_url:{url:`data:${q.mimeType};base64,${q.base64}`}});return Z}function P6($){return{role:$.role,content:$.content}}function I6($){if(!$.restoredContextMessages||$.restoredVisibleMessageCount<=0)return $.messages.map(P6);let Q=$.messages.slice($.restoredVisibleMessageCount).map(P6);return[...$.restoredContextMessages,...Q]}function r4($){return typeof $==="object"&&$!==null&&$.action==="invoke_skill"&&typeof $.skillName==="string"}function a4($){return typeof $==="object"&&$!==null&&$.action==="invoke_custom_command"&&typeof $.commandName==="string"&&typeof $.processedContent==="string"}function o4($){return typeof $==="object"&&$!==null&&$.action==="invoke_plugin_command"&&typeof $.commandName==="string"&&typeof $.processedContent==="string"}function i4($){return typeof $==="object"&&$!==null&&$.action==="invoke_once_model"&&typeof $.modelId==="string"&&typeof $.prompt==="string"}function n4($,Q,J,Y){switch($){case"show_theme_selector":return J.setActiveModal("themeSelector"),!0;case"show_model_selector":return J.setActiveModal("modelSelector"),!0;case"show_model_add_wizard":return J.setActiveModal("modelAddWizard"),!0;case"show_permissions_manager":return J.setActiveModal("permissionsManager"),!0;case"show_agents_manager":return J.setActiveModal("agentsManager"),!0;case"show_skills_manager":return J.setActiveModal("skillsManager"),!0;case"show_hooks_manager":return J.setActiveModal("hooksManager"),!0;case"show_plugins_manager":return J.setActiveModal("pluginsManager"),!0;case"show_agent_creation_wizard":return J.setActiveModal("agentCreationWizard"),!0;case"show_session_selector":{let Z=Q?.sessions;return J.showSessionSelector(Z),!0}case"clear_screen":return Y.clearMessages(),Y.setError(null),Y.resetTokenUsage(),J.setTasks([]),!0;case"compact_completed":case"compact_fallback":return Y.resetTokenUsage(),!0;case"exit_application":return o1(0),!0;default:return!1}}async function k6($,Q,J,Y){let{text:Z}=$;if(!M6(Z))return{type:"not_slash"};let q={cwd:A0(),signal:Y},X=await C6(Z,q);if(X.message){if(n4(X.message,X.data,Q,J))return{type:"handled",commandResult:{success:!0}}}if(r4(X.data)){let{skillName:K,skillArgs:U}=X.data,F=U?`Please use the "${K}" skill to help me with: ${U}`:`Please use the "${K}" skill.`;return J.addUserMessage(F),{type:"continue_as_agent",result:{userDisplayMessage:F,agentInput:{displayText:F,text:F,images:[],parts:[{type:"text",text:F}]},userMessageAlreadyAdded:!0}}}if(a4(X.data)){let{commandName:K,processedContent:U}=X.data;J.addUserMessage(Z);let F=`# Custom Command: /${K}
2
2
 
3
3
  The user has invoked the custom command "/${K}". Follow the instructions below to complete the task.
4
4
 
@@ -1,4 +1,4 @@
1
- import{Y as O}from"./chunk-v1nfdykq.js";import"./chunk-cbcws8wy.js";import{Ea as J,Ga as L}from"./chunk-x9zj0r7s.js";import"./chunk-mz6n4w13.js";import"./chunk-yddnm9n2.js";import{xb as H}from"./chunk-7ycmx7c2.js";import"./chunk-set7v1rf.js";import"./chunk-j2ag7hh6.js";import P from"os";import E from"path";function _(q){return typeof q==="string"?q:void 0}function T(q){if(!Array.isArray(q))return;let z=[];for(let F of q)if(typeof F==="string")z.push(F);else if(F!=null)z.push(String(F));return z}function G(){console.log(`
1
+ import{Y as O}from"./chunk-p988nqta.js";import"./chunk-7qw2xttt.js";import{Ea as J,Ga as L}from"./chunk-x9zj0r7s.js";import"./chunk-mz6n4w13.js";import"./chunk-yddnm9n2.js";import{xb as H}from"./chunk-7ycmx7c2.js";import"./chunk-set7v1rf.js";import"./chunk-j2ag7hh6.js";import P from"os";import E from"path";function _(q){return typeof q==="string"?q:void 0}function T(q){if(!Array.isArray(q))return;let z=[];for(let F of q)if(typeof F==="string")z.push(F);else if(F!=null)z.push(String(F));return z}function G(){console.log(`
2
2
  blade mcp
3
3
  `),console.log(`管理 MCP 服务器
4
4
  `),console.log("Commands:"),console.log(" blade mcp add <name> <commandOrUrl> [args...] 添加 MCP 服务器"),console.log(" blade mcp remove <name> 删除 MCP 服务器 [aliases: rm]"),console.log(" blade mcp list 列出所有 MCP 服务器并检查健康状态 [aliases: ls]"),console.log(" blade mcp get <name> 获取服务器详情"),console.log(` blade mcp add-json <name> <json> 从 JSON 字符串添加服务器
@@ -0,0 +1 @@
1
+ import{t as a,u as b}from"./chunk-gr86637a.js";import"./chunk-7qw2xttt.js";import"./chunk-j2ag7hh6.js";export{a as globalOptions,b as cliConfig};
@@ -1 +1 @@
1
- import{aa as a,ba as b,ca as c,da as d,ea as e,fa as f}from"./chunk-cbcws8wy.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-7qw2xttt.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,2 +1,2 @@
1
- import{ba as d,da as h}from"./chunk-cbcws8wy.js";var q={debug:{alias:"d",type:"string",describe:'Enable debug mode with optional category filtering (e.g., "agent,ui" or "!chat,!loop")',group:"Debug Options:"},model:{type:"string",describe:"Override the current run model using a model config ID (TUI / print / headless)",group:"AI Options:"},print:{alias:"p",type:"boolean",describe:"Print response and exit (useful for pipes)",group:"Output Options:"},headless:{type:"boolean",describe:"Run full agent loop without Ink UI and print all events to the terminal",group:"Output Options:"},"output-format":{alias:["outputFormat"],type:"string",choices:["text","json","stream-json","jsonl"],default:"text",describe:"Output format: --print supports text|json|stream-json; --headless supports text|jsonl",group:"Output Options:"},"include-partial-messages":{alias:["includePartialMessages"],type:"boolean",describe:"Include partial message chunks as they arrive",group:"Output Options:"},"input-format":{alias:["inputFormat"],type:"string",choices:["text","stream-json"],default:"text",describe:"Input format",group:"Input Options:"},"replay-user-messages":{alias:["replayUserMessages"],type:"boolean",describe:"Re-emit user messages from stdin",group:"Input Options:"},"allowed-tools":{alias:["allowedTools"],type:"array",string:!0,describe:"Comma or space-separated list of tool names to allow",group:"Security Options:"},"disallowed-tools":{alias:["disallowedTools"],type:"array",string:!0,describe:"Comma or space-separated list of tool names to deny",group:"Security Options:"},"mcp-config":{alias:["mcpConfig"],type:"array",string:!0,describe:"Load MCP servers from JSON files or strings",group:"MCP Options:"},"system-prompt":{alias:["systemPrompt"],type:"string",describe:"System prompt to use for the session (replaces default)",group:"AI Options:"},"append-system-prompt":{alias:["appendSystemPrompt"],type:"string",describe:"Append a system prompt to the default system prompt",group:"AI Options:"},"max-turns":{alias:["maxTurns"],type:"number",describe:"Maximum conversation turns (-1: unlimited, 0: disable chat, N>0: limit to N turns)",group:"AI Options:",default:void 0},"permission-mode":{alias:["permissionMode"],type:"string",choices:["default","autoEdit","yolo","plan"],describe:"Permission mode (default: ask for non-read tools, autoEdit: auto-approve edits, yolo: auto-approve all, plan: reserved)",group:"Security Options:"},yolo:{type:"boolean",describe:"Auto-approve all tools (shortcut for --permission-mode=yolo)",group:"Security Options:"},continue:{alias:"c",type:"boolean",describe:"Continue the most recent conversation",group:"Session Options:"},resume:{alias:"r",describe:"Resume a conversation - provide a session ID or interactively select a conversation to resume",group:"Session Options:",coerce:(b)=>{if(b===void 0||b===!0||b==="")return"true";return String(b)}},"fork-session":{alias:["forkSession"],type:"boolean",describe:"Create a new session ID when resuming",group:"Session Options:"},settings:{type:"string",describe:"Path to a settings JSON file or JSON string",group:"Configuration:"},"add-dir":{alias:["addDir"],type:"array",string:!0,describe:"Additional directories to allow tool access to",group:"Security Options:"},ide:{type:"boolean",describe:"Automatically connect to IDE on startup",group:"Integration:"},acp:{type:"boolean",describe:"Run in ACP (Agent Client Protocol) mode for IDE integration",group:"Integration:"},"strict-mcp-config":{alias:["strictMcpConfig"],type:"boolean",describe:"Only use MCP servers from --mcp-config",group:"MCP Options:"},"session-id":{alias:["sessionId"],type:"string",describe:"Use a specific session ID for the conversation",group:"Session Options:"},agents:{type:"string",describe:"JSON object defining custom agents",group:"AI Options:"},"setting-sources":{alias:["settingSources"],type:"string",describe:"Comma-separated list of setting sources to load",group:"Configuration:"},"plugin-dir":{alias:["pluginDir"],type:"array",string:!0,describe:"Load plugins from specified directories",group:"Plugin Options:"}},w={scriptName:"blade",usage:"$0 [command] [options]",description:h(),version:d(),locale:"en",showHelpOnFail:!0,demandCommand:!1,recommendCommands:!0,strict:!1};
1
+ import{ba as d,da as h}from"./chunk-7qw2xttt.js";var q={debug:{alias:"d",type:"string",describe:'Enable debug mode with optional category filtering (e.g., "agent,ui" or "!chat,!loop")',group:"Debug Options:"},model:{type:"string",describe:"Override the current run model using a model config ID (TUI / print / headless)",group:"AI Options:"},print:{alias:"p",type:"boolean",describe:"Print response and exit (useful for pipes)",group:"Output Options:"},headless:{type:"boolean",describe:"Run full agent loop without Ink UI and print all events to the terminal",group:"Output Options:"},"output-format":{alias:["outputFormat"],type:"string",choices:["text","json","stream-json","jsonl"],default:"text",describe:"Output format: --print supports text|json|stream-json; --headless supports text|jsonl",group:"Output Options:"},"include-partial-messages":{alias:["includePartialMessages"],type:"boolean",describe:"Include partial message chunks as they arrive",group:"Output Options:"},"input-format":{alias:["inputFormat"],type:"string",choices:["text","stream-json"],default:"text",describe:"Input format",group:"Input Options:"},"replay-user-messages":{alias:["replayUserMessages"],type:"boolean",describe:"Re-emit user messages from stdin",group:"Input Options:"},"allowed-tools":{alias:["allowedTools"],type:"array",string:!0,describe:"Comma or space-separated list of tool names to allow",group:"Security Options:"},"disallowed-tools":{alias:["disallowedTools"],type:"array",string:!0,describe:"Comma or space-separated list of tool names to deny",group:"Security Options:"},"mcp-config":{alias:["mcpConfig"],type:"array",string:!0,describe:"Load MCP servers from JSON files or strings",group:"MCP Options:"},"system-prompt":{alias:["systemPrompt"],type:"string",describe:"System prompt to use for the session (replaces default)",group:"AI Options:"},"append-system-prompt":{alias:["appendSystemPrompt"],type:"string",describe:"Append a system prompt to the default system prompt",group:"AI Options:"},"max-turns":{alias:["maxTurns"],type:"number",describe:"Maximum conversation turns (-1: unlimited, 0: disable chat, N>0: limit to N turns)",group:"AI Options:",default:void 0},"permission-mode":{alias:["permissionMode"],type:"string",choices:["default","autoEdit","yolo","plan"],describe:"Permission mode (default: ask for non-read tools, autoEdit: auto-approve edits, yolo: auto-approve all, plan: reserved)",group:"Security Options:"},yolo:{type:"boolean",describe:"Auto-approve all tools (shortcut for --permission-mode=yolo)",group:"Security Options:"},continue:{alias:"c",type:"boolean",describe:"Continue the most recent conversation",group:"Session Options:"},resume:{alias:"r",describe:"Resume a conversation - provide a session ID or interactively select a conversation to resume",group:"Session Options:",coerce:(b)=>{if(b===void 0||b===!0||b==="")return"true";return String(b)}},"fork-session":{alias:["forkSession"],type:"boolean",describe:"Create a new session ID when resuming",group:"Session Options:"},settings:{type:"string",describe:"Path to a settings JSON file or JSON string",group:"Configuration:"},"add-dir":{alias:["addDir"],type:"array",string:!0,describe:"Additional directories to allow tool access to",group:"Security Options:"},ide:{type:"boolean",describe:"Automatically connect to IDE on startup",group:"Integration:"},acp:{type:"boolean",describe:"Run in ACP (Agent Client Protocol) mode for IDE integration",group:"Integration:"},"strict-mcp-config":{alias:["strictMcpConfig"],type:"boolean",describe:"Only use MCP servers from --mcp-config",group:"MCP Options:"},"session-id":{alias:["sessionId"],type:"string",describe:"Use a specific session ID for the conversation",group:"Session Options:"},agents:{type:"string",describe:"JSON object defining custom agents",group:"AI Options:"},"setting-sources":{alias:["settingSources"],type:"string",describe:"Comma-separated list of setting sources to load",group:"Configuration:"},"plugin-dir":{alias:["pluginDir"],type:"array",string:!0,describe:"Load plugins from specified directories",group:"Plugin Options:"}},w={scriptName:"blade",usage:"$0 [command] [options]",description:h(),version:d(),locale:"en",showHelpOnFail:!0,demandCommand:!1,recommendCommands:!0,strict:!1};
2
2
  export{q as t,w as u};
@@ -1 +1 @@
1
- import{a as y,b as A,c as C,d as D}from"./chunk-1fg4r093.js";import"./chunk-q5yn875m.js";import"./chunk-ds6m379k.js";import"./chunk-v1nfdykq.js";import"./chunk-mxrre2n3.js";import"./chunk-cbcws8wy.js";import"./chunk-68ctb04g.js";import{Aa as q}from"./chunk-x9zj0r7s.js";import"./chunk-mz6n4w13.js";import"./chunk-c3nh2cc1.js";import"./chunk-yddnm9n2.js";import"./chunk-yk91w5p2.js";import"./chunk-37rethcy.js";import"./chunk-7ycmx7c2.js";import"./chunk-set7v1rf.js";import"./chunk-j2ag7hh6.js";import H from"chalk";var R={command:"serve",describe:"Start a headless Blade server (no browser)",builder:y,handler:async(E)=>{let f=A(E);if(await q(),!process.env.BLADE_SERVER_PASSWORD)console.log(H.yellow("Warning: BLADE_SERVER_PASSWORD is not set; server is unsecured."));let b=await D.listenAsync(f);if(console.log(`Blade server listening on http://${b.hostname}:${b.port}`),f.hostname==="0.0.0.0"){let F=C();for(let G of F)console.log(` Network: http://${G}:${b.port}`)}await new Promise(()=>{}),await b.stop()}};export{R as serveCommand};
1
+ import{a as y,b as A,c as C,d as D}from"./chunk-0jczmnqq.js";import"./chunk-q5yn875m.js";import"./chunk-tkjbcmc1.js";import"./chunk-p988nqta.js";import"./chunk-mxrre2n3.js";import"./chunk-7qw2xttt.js";import"./chunk-68ctb04g.js";import{Aa as q}from"./chunk-x9zj0r7s.js";import"./chunk-mz6n4w13.js";import"./chunk-c3nh2cc1.js";import"./chunk-yddnm9n2.js";import"./chunk-yk91w5p2.js";import"./chunk-37rethcy.js";import"./chunk-7ycmx7c2.js";import"./chunk-set7v1rf.js";import"./chunk-j2ag7hh6.js";import H from"chalk";var R={command:"serve",describe:"Start a headless Blade server (no browser)",builder:y,handler:async(E)=>{let f=A(E);if(await q(),!process.env.BLADE_SERVER_PASSWORD)console.log(H.yellow("Warning: BLADE_SERVER_PASSWORD is not set; server is unsecured."));let b=await D.listenAsync(f);if(console.log(`Blade server listening on http://${b.hostname}:${b.port}`),f.hostname==="0.0.0.0"){let F=C();for(let G of F)console.log(` Network: http://${G}:${b.port}`)}await new Promise(()=>{}),await b.stop()}};export{R as serveCommand};
@@ -1,4 +1,4 @@
1
- import{ba as S,ca as h}from"./chunk-cbcws8wy.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-7qw2xttt.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-1fg4r093.js";import"./chunk-q5yn875m.js";import"./chunk-ds6m379k.js";import"./chunk-v1nfdykq.js";import"./chunk-mxrre2n3.js";import{ba as M}from"./chunk-cbcws8wy.js";import"./chunk-68ctb04g.js";import{Aa as J}from"./chunk-x9zj0r7s.js";import"./chunk-mz6n4w13.js";import"./chunk-c3nh2cc1.js";import"./chunk-yddnm9n2.js";import"./chunk-yk91w5p2.js";import"./chunk-37rethcy.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-0jczmnqq.js";import"./chunk-q5yn875m.js";import"./chunk-tkjbcmc1.js";import"./chunk-p988nqta.js";import"./chunk-mxrre2n3.js";import{ba as M}from"./chunk-7qw2xttt.js";import"./chunk-68ctb04g.js";import{Aa as J}from"./chunk-x9zj0r7s.js";import"./chunk-mz6n4w13.js";import"./chunk-c3nh2cc1.js";import"./chunk-yddnm9n2.js";import"./chunk-yk91w5p2.js";import"./chunk-37rethcy.js";import"./chunk-7ycmx7c2.js";import"./chunk-set7v1rf.js";import"./chunk-j2ag7hh6.js";import b from"chalk";import H from"open";var $=`
2
2
  ____ _ _
3
3
  | __ )| | __ _ __| | ___
4
4
  | _ \\| |/ _\` |/ _\` |/ _ \\
@@ -1,4 +1,4 @@
1
- import{X as D,Y as F$}from"./chunk-v1nfdykq.js";import{Z as K4}from"./chunk-mxrre2n3.js";import{ba as M1}from"./chunk-cbcws8wy.js";import{ga as m}from"./chunk-68ctb04g.js";import{Aa as C1,Ba as l$,Ca as j$,Da as c0,Ea as L$,Fa as I1,Ga as x$,ra as l4,sa as s,ua as l0,va as i,wa as A,za as t}from"./chunk-x9zj0r7s.js";import{Ia as v1}from"./chunk-mz6n4w13.js";import{Ma as r9,Na as Q$,Oa as D0,Pa as y$,Sa as N$,db as n1,eb as $2,hb as Q9}from"./chunk-c3nh2cc1.js";import{ib as G9,jb as F9,kb as K8,lb as Y9}from"./chunk-yddnm9n2.js";import{mb as P8,nb as X$}from"./chunk-yk91w5p2.js";import{rb as S1}from"./chunk-37rethcy.js";import{tb as l8,xb as N}from"./chunk-7ycmx7c2.js";import{Bb as M,Cb as S}from"./chunk-set7v1rf.js";import{Db as s$}from"./chunk-j2ag7hh6.js";import{spawn as m2}from"child_process";import{randomUUID as c2}from"crypto";class n{static instance=null;processes=new Map;static getInstance(){if(!n.instance)n.instance=new n;return n.instance}startBackgroundProcess($){let Z=`bash_${c2()}`,J={};for(let[Y,V]of Object.entries({...process.env,...$.env,BLADE_CLI:"1"}))if(V!==void 0)J[Y]=V;let W=m2("bash",["-c",$.command],{cwd:$.cwd||N(),env:J,stdio:["ignore","pipe","pipe"]}),X={id:Z,command:$.command,sessionId:$.sessionId,cwd:$.cwd,env:$.env,process:W,pid:W.pid,status:"running",startTime:Date.now(),pendingStdout:"",pendingStderr:""};return W.stdout?.setEncoding("utf8"),W.stderr?.setEncoding("utf8"),W.stdout?.on("data",(Y)=>{X.pendingStdout+=Y.toString()}),W.stderr?.on("data",(Y)=>{X.pendingStderr+=Y.toString()}),W.on("close",(Y,V)=>{X.status=X.status==="killed"?"killed":"exited",X.exitCode=Y,X.signal=V,X.endTime=Date.now(),X.process=void 0}),W.on("error",(Y)=>{X.status="error",X.errorMessage=Y.message,X.endTime=Date.now(),X.process=void 0,X.pendingStderr+=`
1
+ import{X as D,Y as F$}from"./chunk-p988nqta.js";import{Z as K4}from"./chunk-mxrre2n3.js";import{ba as M1}from"./chunk-7qw2xttt.js";import{ga as m}from"./chunk-68ctb04g.js";import{Aa as C1,Ba as l$,Ca as j$,Da as c0,Ea as L$,Fa as I1,Ga as x$,ra as l4,sa as s,ua as l0,va as i,wa as A,za as t}from"./chunk-x9zj0r7s.js";import{Ia as v1}from"./chunk-mz6n4w13.js";import{Ma as r9,Na as Q$,Oa as D0,Pa as y$,Sa as N$,db as n1,eb as $2,hb as Q9}from"./chunk-c3nh2cc1.js";import{ib as G9,jb as F9,kb as K8,lb as Y9}from"./chunk-yddnm9n2.js";import{mb as P8,nb as X$}from"./chunk-yk91w5p2.js";import{rb as S1}from"./chunk-37rethcy.js";import{tb as l8,xb as N}from"./chunk-7ycmx7c2.js";import{Bb as M,Cb as S}from"./chunk-set7v1rf.js";import{Db as s$}from"./chunk-j2ag7hh6.js";import{spawn as m2}from"child_process";import{randomUUID as c2}from"crypto";class n{static instance=null;processes=new Map;static getInstance(){if(!n.instance)n.instance=new n;return n.instance}startBackgroundProcess($){let Z=`bash_${c2()}`,J={};for(let[Y,V]of Object.entries({...process.env,...$.env,BLADE_CLI:"1"}))if(V!==void 0)J[Y]=V;let W=m2("bash",["-c",$.command],{cwd:$.cwd||N(),env:J,stdio:["ignore","pipe","pipe"]}),X={id:Z,command:$.command,sessionId:$.sessionId,cwd:$.cwd,env:$.env,process:W,pid:W.pid,status:"running",startTime:Date.now(),pendingStdout:"",pendingStderr:""};return W.stdout?.setEncoding("utf8"),W.stderr?.setEncoding("utf8"),W.stdout?.on("data",(Y)=>{X.pendingStdout+=Y.toString()}),W.stderr?.on("data",(Y)=>{X.pendingStderr+=Y.toString()}),W.on("close",(Y,V)=>{X.status=X.status==="killed"?"killed":"exited",X.exitCode=Y,X.signal=V,X.endTime=Date.now(),X.process=void 0}),W.on("error",(Y)=>{X.status="error",X.errorMessage=Y.message,X.endTime=Date.now(),X.process=void 0,X.pendingStderr+=`
2
2
  [error] ${Y.message}`}),this.processes.set(Z,X),X}consumeOutput($){let Z=this.processes.get($);if(!Z)return;let J={id:Z.id,command:Z.command,status:Z.status,stdout:Z.pendingStdout,stderr:Z.pendingStderr,exitCode:Z.exitCode,signal:Z.signal,pid:Z.pid,startedAt:Z.startTime,endedAt:Z.endTime,errorMessage:Z.errorMessage};return Z.pendingStdout="",Z.pendingStderr="",J}getProcess($){return this.processes.get($)}kill($){let Z=this.processes.get($);if(!Z)return;if(Z.status!=="running"||!Z.process)return{success:!1,alreadyExited:!0,status:Z.status,pid:Z.pid,exitCode:Z.exitCode,signal:Z.signal};if(!Z.process.kill("SIGTERM"))return{success:!1,alreadyExited:!1,status:Z.status,pid:Z.pid,exitCode:Z.exitCode,signal:Z.signal};return Z.status="killed",Z.endTime=Date.now(),Z.process=void 0,{success:!0,alreadyExited:!1,status:Z.status,pid:Z.pid,exitCode:Z.exitCode,signal:Z.signal}}killAll(){for(let[$,Z]of this.processes)if(Z.status==="running"&&Z.process)try{Z.process.kill("SIGTERM"),Z.status="killed",Z.endTime=Date.now(),Z.process=void 0}catch{}this.processes.clear()}}import Y5 from"node:fs";import X1 from"node:os";import k$ from"node:path";import l2 from"yaml";var u8={name:"verification",description:"Independent verification agent that validates implementation by running builds, tests, linters, and adversarial"+" probes. Strictly read-only — cannot modify code. Use"+" after completing implementation to get an independent quality assessment.",tools:["Read","Glob","Grep","Bash"],systemPrompt:`# Verification Agent
3
3
 
4
4
  You are an **independent verification engineer**. Your sole purpose is to find problems — not to praise or reassure. You are the last line of defense before code ships.
@@ -542,7 +542,8 @@ ${JSON.stringify({patch:w,startLine:H+1,matchLine:B+1})}
542
542
 
543
543
  Details: ${J$.message}`,error:{type:"validation_error",message:"File modified externally",details:{externalModification:J$.message}}}}if(B&&K)try{let v=new P0({sessionId:B});await v.initialize(),await v.createSnapshot(J,K)}catch(v){console.warn("[EditTool] 创建快照失败:",v)}if(W===X)return{success:!1,llmContent:"New string is identical; no replacement needed",error:{type:"validation_error",message:"新旧字符串相同"}};let G=H7(H,W);if(!G.matched){let v=F7(H,W,J);return{success:!1,llmContent:v.llmContent,error:{type:"execution_error",message:"未找到匹配内容",details:v.metadata}}}let O=G.matched;if(G.strategy!=="exact")console.log(`[SmartEdit] 使用策略: ${G.strategy}`);let F=G7(H,O);if(F.length>1&&!Y){let v=H.split(`
544
544
  `),J$=0,v0=[];for(let K$=0;K$<v.length;K$++){let J5=v[K$],p8=J$,d8=J$+J5.length;for(let W5 of F)if(W5>=p8&&W5<d8){let p2=Math.max(0,K$-1),d2=Math.min(v.length-1,K$+1),u2=v.slice(p2,d2+1).map((g2)=>g2.trim()).join(" ").slice(0,80);v0.push({line:K$+1,column:W5-p8+1,context:u2})}J$=d8+1}return{success:!1,llmContent:[`[WARN] EDIT PAUSED: old_string matches ${F.length} locations (must be unique).`,"","**Matches found at:**",...v0.map((K$,J5)=>` ${J5+1}. Line ${K$.line}`),"","**Action Required:** Add 3-5 lines of surrounding context to make old_string unique.","","**Tips for quick success:**","• Include the function/class name that wraps the target code","• Add 2-3 lines before and after the target","• Include unique comments or variable names nearby",`• Or use replace_all=true to change all ${F.length} occurrences`,"","**Auto-retry expected** - This usually resolves in 1-2 attempts."].join(`
545
- `),error:{type:"validation_error",message:"old_string is not unique",details:{matches:v0.map((K$)=>({line:K$.line,column:K$.column})),count:F.length}}}}else V?.(`找到 ${F.length} 个匹配项,开始替换...`);let z,w;if(Y)z=H.split(O).join(X),w=F.length;else{let v=H.indexOf(O);z=H.substring(0,v)+X+H.substring(v+O.length),w=1}if(typeof Q.throwIfAborted==="function")Q.throwIfAborted();if(q)V?.("通过 IDE 写入文件...");if(await U.writeTextFile(J,z),B)await y$.getInstance().recordFileEdit(J,B,"edit");let L=await U.stat(J),E=w4(H,z,O,X,4),j=U7(J),b=w===1?`替换 1 处匹配到 ${j}`:`替换 ${w} 处匹配到 ${j}`,a={file_path:J,matches_found:F.length,replacements_made:w,replace_all:Y,old_string_length:W.length,new_string_length:X.length,original_size:H.length,new_size:z.length,size_diff:z.length-H.length,last_modified:L?.mtime instanceof Date?L.mtime.toISOString():void 0,snapshot_created:!!(B&&K),session_id:B,message_id:K,diff_snippet:E,summary:b,kind:"edit",oldContent:H,newContent:z};return{success:!0,llmContent:{file_path:J,replacements:w,total_matches:F.length},metadata:a}}catch(U){let q=U;if(q.name==="AbortError")return{success:!1,llmContent:"File edit aborted",error:{type:"execution_error",message:"操作被中止"}};return{success:!1,llmContent:`File edit failed: ${q.message}`,error:{type:"execution_error",message:q.message,details:q}}}},version:"2.0.0",category:"文件操作",tags:["file","edit","replace","modify"],extractSignatureContent:($)=>$.file_path,abstractPermissionRule:($)=>{let Z=q7($.file_path);return Z?`**/*${Z}`:"**/*"}});function L4($){return $.replaceAll("‘","'").replaceAll("’","'").replaceAll("“",'"').replaceAll("”",'"')}function H7($,Z){if($.includes(Z))return{matched:Z,strategy:"exact"};let J=L4(Z),X=L4($).indexOf(J);if(X!==-1)return{matched:$.substring(X,X+Z.length),strategy:"normalize_quotes"};let Y=j4(Z);if(Y!==Z&&$.includes(Y))return{matched:Y,strategy:"unescape"};let V=N4($,Z);if(V)return{matched:V,strategy:"flexible"};return{matched:null,strategy:"failed"}}function G7($,Z){if(Z.length===0)return[];let J=[],W=$.indexOf(Z);while(W!==-1)J.push(W),W=$.indexOf(Z,W+Z.length);return J}function F7($,Z,J){let W=$.split(`
545
+ `),error:{type:"validation_error",message:"old_string is not unique",details:{matches:v0.map((K$)=>({line:K$.line,column:K$.column})),count:F.length}}}}else V?.(`找到 ${F.length} 个匹配项,开始替换...`);let z,w;if(Y)z=H.split(O).join(X),w=F.length;else{let v=H.indexOf(O);z=H.substring(0,v)+X+H.substring(v+O.length),w=1}if(typeof Q.throwIfAborted==="function")Q.throwIfAborted();if(q)V?.("通过 IDE 写入文件...");if(await U.writeTextFile(J,z),B)await y$.getInstance().recordFileEdit(J,B,"edit");let L=await U.stat(J),E=w4(H,z,O,X,4),j=U7(J),b=w===1?`替换 1 处匹配到 ${j}`:`替换 ${w} 处匹配到 ${j}`,a={file_path:J,matches_found:F.length,replacements_made:w,replace_all:Y,old_string_length:W.length,new_string_length:X.length,original_size:H.length,new_size:z.length,size_diff:z.length-H.length,last_modified:L?.mtime instanceof Date?L.mtime.toISOString():void 0,snapshot_created:!!(B&&K),session_id:B,message_id:K,diff_snippet:E,summary:b,kind:"edit",oldContent:H,newContent:z};return{success:!0,llmContent:E?`Edited ${J} (${w} replacement${w>1?"s":""}):
546
+ ${E}`:`Edited ${J} (${w} replacement${w>1?"s":""})`,metadata:a}}catch(U){let q=U;if(q.name==="AbortError")return{success:!1,llmContent:"File edit aborted",error:{type:"execution_error",message:"操作被中止"}};return{success:!1,llmContent:`File edit failed: ${q.message}`,error:{type:"execution_error",message:q.message,details:q}}}},version:"2.0.0",category:"文件操作",tags:["file","edit","replace","modify"],extractSignatureContent:($)=>$.file_path,abstractPermissionRule:($)=>{let Z=q7($.file_path);return Z?`**/*${Z}`:"**/*"}});function L4($){return $.replaceAll("‘","'").replaceAll("’","'").replaceAll("“",'"').replaceAll("”",'"')}function H7($,Z){if($.includes(Z))return{matched:Z,strategy:"exact"};let J=L4(Z),X=L4($).indexOf(J);if(X!==-1)return{matched:$.substring(X,X+Z.length),strategy:"normalize_quotes"};let Y=j4(Z);if(Y!==Z&&$.includes(Y))return{matched:Y,strategy:"unescape"};let V=N4($,Z);if(V)return{matched:V,strategy:"flexible"};return{matched:null,strategy:"failed"}}function G7($,Z){if(Z.length===0)return[];let J=[],W=$.indexOf(Z);while(W!==-1)J.push(W),W=$.indexOf(Z,W+Z.length);return J}function F7($,Z,J){let W=$.split(`
546
547
  `),X=W.length,Y=O7($,Z,3),V=0,B=Math.min(20,X);if(Y.length>0){let H=Y[0];V=Math.max(0,H.lineNumber-10),B=Math.min(X,H.lineNumber+10)}let Q=W.slice(V,B).map((H,G)=>{return` ${(V+G+1).toString().padStart(4)}: ${H}`}).join(`
547
548
  `),U=`String not found in file.
548
549
 
@@ -581,7 +582,7 @@ Common issues:
581
582
  `),z.lines_read=v.length,z.total_lines=j.length,z.start_line=b+1,z.end_line=Math.min(a,j.length)}let w=w7(J),L=z.lines_read||z.total_lines,E=L?`读取 ${L} 行从 ${w}`:`读取 ${w}`;return z.summary=E,{success:!0,llmContent:F,metadata:z}}catch(Q){let U=Q;if(U.name==="AbortError")return{success:!1,llmContent:"File read aborted",error:{type:"execution_error",message:"Operation aborted"}};return{success:!1,llmContent:`File read failed: ${U.message}`,error:{type:"execution_error",message:U.message,details:U}}}},version:"2.0.0",category:"文件操作",tags:["file","io","read"],extractSignatureContent:($)=>$.file_path,abstractPermissionRule:($)=>{let Z=_4($.file_path);return Z?`**/*${Z}`:"**/*"}});function N7($){return[".txt",".md",".js",".ts",".jsx",".tsx",".json",".xml",".html",".htm",".css",".scss",".sass",".less",".yml",".yaml",".toml",".ini",".cfg",".py",".rb",".php",".java",".cpp",".c",".h",".hpp",".rs",".go",".sh",".bash",".zsh",".fish",".ps1",".bat",".cmd",".sql",".graphql",".vue",".svelte",".astro",".dockerfile",".gitignore",".env"].includes($)||$===""}function D7($){return[".jpg",".jpeg",".png",".gif",".bmp",".svg",".ico",".webp",".mp3",".wav",".mp4",".avi",".mov",".wmv",".flv",".webm",".pdf",".doc",".docx",".xls",".xlsx",".ppt",".pptx",".zip",".tar",".gz",".rar",".7z",".exe",".dll",".so",".ttf",".otf",".woff",".woff2",".eot"].includes($)}import{promises as L7}from"fs";import{basename as E7,dirname as _7,extname as A7}from"path";import{z as F5}from"zod";var O5=D({name:"Write",displayName:"File Write",kind:"write",strict:!0,isConcurrencySafe:!1,schema:F5.object({file_path:y.filePath({description:"Absolute file path to write"}),content:F5.string().describe("Content to write"),encoding:y.encoding(),create_directories:F5.boolean().default(!0).describe("Automatically create missing parent directories")}),description:{short:"Writes a file to the local filesystem",long:"Writes a file to the local filesystem.",usageNotes:["This tool will overwrite the existing file if there is one at the provided path.","If this is an existing file, you MUST use the Read tool first to read the file's contents. This tool will fail if you did not read the file first.","ALWAYS prefer editing existing files in the codebase. NEVER write new files unless explicitly required.","NEVER proactively create documentation files (*.md) or README files. Only create documentation files if explicitly requested by the User.","Only use emojis if the user explicitly requests it. Avoid writing emojis to files unless asked."]},async execute($,Z){let{file_path:J,content:W,encoding:X,create_directories:Y}=$,{updateOutput:V,sessionId:B,messageId:K}=Z,Q=Z.signal??new AbortController().signal;try{V?.("开始写入文件...");let U=w0(),q=P$();if(Y){let j=_7(J);try{await U.mkdir(j,{recursive:!0,mode:493})}catch(b){if(b.code!=="EEXIST")throw b}}if(typeof Q.throwIfAborted==="function")Q.throwIfAborted();let H=!1,G=null;try{if(H=await U.exists(J),H&&X==="utf8")try{G=await U.readTextFile(J)}catch(j){console.warn("[WriteTool] 读取旧文件内容失败:",j)}}catch{}if(H&&B){let j=y$.getInstance();if(!j.hasFileBeenRead(J,B))return{success:!1,llmContent:"If this is an existing file, you MUST use the Read tool first to read the file's contents. This tool will fail if you did not read the file first.",error:{type:"validation_error",message:"File not read before write"},metadata:{requiresRead:!0}};let b=await j.checkExternalModification(J);if(b.isExternal)return{success:!1,llmContent:`The file has been modified by an external program since you last read it. You must use the Read tool again to see the current content before writing.
582
583
 
583
584
  Details: ${b.message}`,error:{type:"validation_error",message:"File modified externally",details:{externalModification:b.message}}}}let O=!1;if(H&&B&&K)try{let j=new P0({sessionId:B});await j.initialize(),await j.createSnapshot(J,K),O=!0}catch(j){console.warn("[WriteTool] 创建快照失败:",j)}if(typeof Q.throwIfAborted==="function")Q.throwIfAborted();if(X==="utf8"){if(q)V?.("通过 IDE 写入文件...");await U.writeTextFile(J,W)}else{if(q)return{success:!1,llmContent:"Binary file writes are not supported in ACP mode. The IDE only supports text file operations. Please use encoding='utf8' for text files, or ask the user to write the file manually.",error:{type:"validation_error",message:"Binary writes not supported in ACP mode"}};let j;if(X==="base64")j=Buffer.from(W,"base64");else if(X==="binary")j=Buffer.from(W,"binary");else j=Buffer.from(W,"utf8");await L7.writeFile(J,j)}if(B)await y$.getInstance().recordFileEdit(J,B,"write");if(typeof Q.throwIfAborted==="function")Q.throwIfAborted();let F=await U.stat(J),z=X==="utf8"?W.split(`
584
- `).length:0,w=E7(J),L=null;if(G&&X==="utf8"&&G!==W){if(G.length<1048576&&W.length<1048576)L=z4(G,W,4)}let E={file_path:J,content_size:W.length,file_size:F?.size,encoding:X,created_directories:Y,snapshot_created:O,session_id:B,message_id:K,last_modified:F?.mtime instanceof Date?F.mtime.toISOString():void 0,has_diff:!!L,summary:X==="utf8"?`写入 ${z} 行到 ${w}`:`写入 ${F?.size?R7(F.size):"unknown"} 到 ${w}`,kind:"edit",oldContent:G||"",newContent:X==="utf8"?W:void 0};return{success:!0,llmContent:{file_path:J,size:F?.size,modified:F?.mtime instanceof Date?F.mtime.toISOString():void 0},metadata:E}}catch(U){let q=U;if(q.name==="AbortError")return{success:!1,llmContent:"File write aborted",error:{type:"execution_error",message:"操作被中止"}};return{success:!1,llmContent:`File write failed: ${q.message}`,error:{type:"execution_error",message:q.message,details:q}}}},version:"2.0.0",category:"文件操作",tags:["file","io","write","create"],extractSignatureContent:($)=>$.file_path,abstractPermissionRule:($)=>{let Z=A7($.file_path);return Z?`**/*${Z}`:"**/*"}});function R7($){let Z=["B","KB","MB","GB"],J=$,W=0;while(J>=1024&&W<Z.length-1)J/=1024,W++;return`${J.toFixed(1)}${Z[W]}`}import{z as y0}from"zod";var k4=new Set(["temperature","maxContextTokens","maxOutputTokens","timeout","theme","uiTheme","language","fontSize","debug","autoSaveSessions","maxTurns","disableAllHooks","permissions","hooks","env","mcpServers"]),k7=new Set(["systemPrompt","appendSystemPrompt","initialMessage","resumeSessionId","forkSession","allowedTools","disallowedTools","mcpConfigPaths","strictMcpConfig","addDirs","outputFormat","inputFormat","print","includePartialMessages","replayUserMessages","agentsConfig","settingSources"]),b7=y0.object({operation:y0.enum(["get","set","list"]).describe("操作类型: get(读取)/ set(设置)/ list(列举可配置项)"),key:y0.string().optional().describe("配置键名,支持点号嵌套(如 hooks.PreToolUse)。"+' get 时用 "*" 获取全部配置'),value:y0.unknown().optional().describe("要设置的值(仅 set 操作需要)"),scope:y0.enum(["local","project","global"]).optional().describe("持久化范围: local(.blade/settings.local.json)"+"/ project(.blade/settings.json)"+"/ global(~/.blade/)")});function A4($){let Z={...$};if(Array.isArray(Z.models))Z.models=Z.models.map((J)=>{let W={...J};if(typeof W.apiKey==="string"&&W.apiKey){let X=W.apiKey;W.apiKey=X.length>8?`${X.slice(0,4)}...${X.slice(-4)}`:"****"}return W});return Z}function R4($,Z){let J=Z.split("."),W=$;for(let X of J){if(W===null||W===void 0||typeof W!=="object")return;W=W[X]}return W}function T7($){let Z=["可配置项列表(白名单):",""];for(let J of k4){let W=$[J],X=W===void 0?"(未设置)":JSON.stringify(W,null,2),Y=X.length>200?`${X.slice(0,197)}...`:X;Z.push(`- ${J}: ${Y}`)}return Z.join(`
585
+ `).length:0,w=E7(J),L=null;if(G&&X==="utf8"&&G!==W){if(G.length<1048576&&W.length<1048576)L=z4(G,W,4)}let E={file_path:J,content_size:W.length,file_size:F?.size,encoding:X,created_directories:Y,snapshot_created:O,session_id:B,message_id:K,last_modified:F?.mtime instanceof Date?F.mtime.toISOString():void 0,has_diff:!!L,summary:X==="utf8"?`写入 ${z} 行到 ${w}`:`写入 ${F?.size?R7(F.size):"unknown"} 到 ${w}`,kind:"edit",oldContent:G||"",newContent:X==="utf8"?W:void 0};return{success:!0,llmContent:G?`Wrote ${J} (${W.length} chars, updated existing file)`:`Created ${J} (${W.length} chars, new file)`,metadata:E}}catch(U){let q=U;if(q.name==="AbortError")return{success:!1,llmContent:"File write aborted",error:{type:"execution_error",message:"操作被中止"}};return{success:!1,llmContent:`File write failed: ${q.message}`,error:{type:"execution_error",message:q.message,details:q}}}},version:"2.0.0",category:"文件操作",tags:["file","io","write","create"],extractSignatureContent:($)=>$.file_path,abstractPermissionRule:($)=>{let Z=A7($.file_path);return Z?`**/*${Z}`:"**/*"}});function R7($){let Z=["B","KB","MB","GB"],J=$,W=0;while(J>=1024&&W<Z.length-1)J/=1024,W++;return`${J.toFixed(1)}${Z[W]}`}import{z as y0}from"zod";var k4=new Set(["temperature","maxContextTokens","maxOutputTokens","timeout","theme","uiTheme","language","fontSize","debug","autoSaveSessions","maxTurns","disableAllHooks","permissions","hooks","env","mcpServers"]),k7=new Set(["systemPrompt","appendSystemPrompt","initialMessage","resumeSessionId","forkSession","allowedTools","disallowedTools","mcpConfigPaths","strictMcpConfig","addDirs","outputFormat","inputFormat","print","includePartialMessages","replayUserMessages","agentsConfig","settingSources"]),b7=y0.object({operation:y0.enum(["get","set","list"]).describe("操作类型: get(读取)/ set(设置)/ list(列举可配置项)"),key:y0.string().optional().describe("配置键名,支持点号嵌套(如 hooks.PreToolUse)。"+' get 时用 "*" 获取全部配置'),value:y0.unknown().optional().describe("要设置的值(仅 set 操作需要)"),scope:y0.enum(["local","project","global"]).optional().describe("持久化范围: local(.blade/settings.local.json)"+"/ project(.blade/settings.json)"+"/ global(~/.blade/)")});function A4($){let Z={...$};if(Array.isArray(Z.models))Z.models=Z.models.map((J)=>{let W={...J};if(typeof W.apiKey==="string"&&W.apiKey){let X=W.apiKey;W.apiKey=X.length>8?`${X.slice(0,4)}...${X.slice(-4)}`:"****"}return W});return Z}function R4($,Z){let J=Z.split("."),W=$;for(let X of J){if(W===null||W===void 0||typeof W!=="object")return;W=W[X]}return W}function T7($){let Z=["可配置项列表(白名单):",""];for(let J of k4){let W=$[J],X=W===void 0?"(未设置)":JSON.stringify(W,null,2),Y=X.length>200?`${X.slice(0,197)}...`:X;Z.push(`- ${J}: ${Y}`)}return Z.join(`
585
586
  `)}var z5=D({name:"ConfigTool",displayName:"Config",kind:"execute",isConcurrencySafe:!1,schema:b7,description:{short:"Read, update, or list Blade configuration",long:"Manage Blade configuration: get reads a config value, set updates a whitelisted config field (with persistence), list enumerates all settable keys and their current values.",usageNotes:['Use operation="get" with key="*" to dump all config','Use operation="get" with a dotted key like "hooks.PreToolUse"','Use operation="set" with key and value to update config','Use operation="list" to see all settable keys',"The scope option controls persistence: local/project/global","models and apiKey fields cannot be modified for security"],examples:[{description:"Get all configuration",params:{operation:"get",key:"*"}},{description:"Get a specific config value",params:{operation:"get",key:"hooks"}},{description:"Set temperature",params:{operation:"set",key:"temperature",value:0.7,scope:"global"}},{description:"List all settable keys",params:{operation:"list"}}]},async execute($,Z){let{operation:J,key:W,value:X,scope:Y}=$,V=t();if(!V)return{success:!1,llmContent:"Config not initialized. Please wait for Blade to finish starting.",error:{message:"Config not initialized",type:"execution_error"},metadata:{summary:"配置未初始化"}};switch(J){case"get":{if(!W)return{success:!1,llmContent:'Missing "key" parameter for get operation. Use key="*" to get all config.',error:{message:"Missing key",type:"validation_error"},metadata:{summary:"缺少 key 参数"}};if(W==="*"){let U=A4(V);return{success:!0,llmContent:JSON.stringify(U,null,2),metadata:{summary:"获取全部配置"}}}let B=V;if(W.split(".")[0]==="models"){let U=A4(B),q=R4(U,W);return{success:!0,llmContent:JSON.stringify(q,null,2),metadata:{summary:`获取配置: ${W}`}}}let Q=R4(B,W);if(Q===void 0)return{success:!0,llmContent:`Config key "${W}" is not set or does not exist.`,metadata:{summary:`配置项 ${W} 不存在`}};return{success:!0,llmContent:JSON.stringify(Q,null,2),metadata:{summary:`获取配置: ${W}`}}}case"set":{if(!W)return{success:!1,llmContent:'Missing "key" parameter for set operation.',error:{message:"Missing key",type:"validation_error"},metadata:{summary:"缺少 key 参数"}};if(X===void 0)return{success:!1,llmContent:'Missing "value" parameter for set operation.',error:{message:"Missing value",type:"validation_error"},metadata:{summary:"缺少 value 参数"}};let B=W.split(".")[0];if(B==="models"||B==="currentModelId")return{success:!1,llmContent:'Refused: "models" and "currentModelId" cannot be modified via ConfigTool to protect API keys. Use the /model slash command instead.',error:{message:"Forbidden key: models",type:"permission_denied"},metadata:{summary:"拒绝修改 models"}};if(k7.has(B))return{success:!1,llmContent:`Refused: "${B}" is a runtime-only field and cannot be persisted via ConfigTool.`,error:{message:`Forbidden runtime key: ${B}`,type:"permission_denied"},metadata:{summary:`拒绝修改运行时字段: ${B}`}};if(!k4.has(B))return{success:!1,llmContent:`Key "${B}" is not in the settable whitelist. Use operation="list" to see all allowed keys.`,error:{message:`Key not settable: ${B}`,type:"validation_error"},metadata:{summary:`不可设置的 key: ${B}`}};let K;if(W.includes(".")){let Q=W.split(".");if(K={[Q[0]]:X},Q.length===2){let U=V[Q[0]];if(typeof U==="object"&&U!==null)K={[Q[0]]:{...U,[Q[1]]:X}};else K={[Q[0]]:{[Q[1]]:X}}}}else K={[W]:X};try{await x$().updateConfig(K,Y?{scope:Y}:{});let Q=JSON.stringify(X).length>200?`${JSON.stringify(X).slice(0,197)}...`:JSON.stringify(X);return{success:!0,llmContent:`Config updated: ${W} = ${Q}`+(Y?` (scope: ${Y})`:""),metadata:{summary:`配置已更新: ${W}`}}}catch(Q){let U=Q instanceof Error?Q.message:String(Q);return{success:!1,llmContent:`Failed to update config: ${U}`,error:{message:U,type:"execution_error"},metadata:{summary:`配置更新失败: ${W}`}}}}case"list":return{success:!0,llmContent:T7(V),metadata:{summary:"列举可配置项"}};default:return{success:!1,llmContent:`Unknown operation: ${J}`,error:{message:`Unknown operation: ${J}`,type:"validation_error"},metadata:{summary:`未知操作: ${J}`}}}}});import{z as b4}from"zod";var w5=D({name:"MemoryRead",displayName:"Memory Read",kind:"readonly",isConcurrencySafe:!0,schema:b4.object({topic:b4.string().describe('Topic name to read (e.g., "debugging", "patterns", "MEMORY" for the index, "_list" to list all topics). Without .md extension.')}),description:{short:"Read a topic file from project auto memory",long:"Reads a topic file from the project's persistent auto memory directory. Use this to retrieve detailed notes that were saved in previous sessions. The MEMORY.md index is automatically loaded at session start, but topic files need to be read on demand.",usageNotes:['Use topic="MEMORY" to read the full MEMORY.md index','Use topic="_list" to list all available memory files',"Topic files are stored at ~/.blade/projects/{project}/memory/{topic}.md"],examples:[{description:"Read debugging notes",params:{topic:"debugging"}},{description:"Read the full MEMORY.md index",params:{topic:"MEMORY"}},{description:"List all memory topics",params:{topic:"_list"}}]},async execute($,Z){let{topic:J}=$,W=Z.workspaceRoot||N(),X=new T$(W);if(J==="_list"){let V=await X.listTopics();if(V.length===0)return{success:!0,llmContent:"No memory files found. Use MemoryWrite to save project knowledge.",metadata:{summary:"无记忆文件"}};return{success:!0,llmContent:`Memory files:
586
587
  ${V.map((Q)=>`- ${Q.name}.md (${Q.size} bytes, updated ${Q.lastModified.toISOString()})`).join(`
587
588
  `)}`,metadata:{summary:`列出 ${V.length} 个记忆文件`}}}let Y=await X.readTopic(J);if(Y===null)return{success:!0,llmContent:`Memory topic "${J}" not found. Use topic="_list" to see available topics.`,metadata:{summary:`记忆主题未找到: ${J}`}};return{success:!0,llmContent:Y,metadata:{summary:`读取记忆: ${J}`}}}});import{z as F1}from"zod";var M7=[/password\s*[:=]/i,/token\s*[:=]/i,/secret\s*[:=]/i,/api[_-]?key\s*[:=]/i,/private[_-]?key/i],j5=D({name:"MemoryWrite",displayName:"Memory Write",kind:"write",isConcurrencySafe:!1,schema:F1.object({topic:F1.string().describe('Topic name to write to (e.g., "debugging", "patterns", "MEMORY" for the index). Without .md extension.'),content:F1.string().describe("Content to write to the memory file"),mode:F1.enum(["overwrite","append"]).default("append").describe('Write mode: "append" adds to existing content, "overwrite" replaces it')}),description:{short:"Save project knowledge to persistent auto memory",long:"Saves notes and learnings to the project's persistent auto memory. Use this to record useful project knowledge that should survive across sessions — build commands, code patterns, debugging insights, architecture notes, and user preferences.",usageNotes:['Use topic="MEMORY" to update the index file (keep it concise, under 200 lines)','Use descriptive topic names for detailed notes (e.g., "debugging", "api-conventions")','Default mode is "append" — adds to existing content','Use "overwrite" mode to replace the entire topic file',"Do NOT save sensitive data (passwords, tokens, API keys)"],examples:[{description:"Save a debugging insight",params:{topic:"debugging",content:"## Redis connection timeout\nThe test suite requires a local Redis instance. Start with `docker compose up redis`."}},{description:"Update the memory index",params:{topic:"MEMORY",content:"# Project Memory\n\n- Build: `bun run build`\n- Test: `bun run test`\n- See debugging.md for common issues",mode:"overwrite"}}]},async execute($,Z){let{topic:J,content:W,mode:X}=$,Y=Z.workspaceRoot||N();for(let Q of M7)if(Q.test(W)){let U=`Refused: content appears to contain sensitive data (matched ${Q}). Do not save passwords, tokens, or API keys to memory.`;return{success:!1,llmContent:U,error:{message:U,type:"validation_error"},metadata:{summary:"拒绝写入敏感信息"}}}let V=new T$(Y);if(J==="MEMORY")await V.updateIndex(W,X);else await V.writeTopic(J,W,X);return{success:!0,llmContent:`${X==="overwrite"?"Written":"Appended"} to memory/${J}.md (${W.length} chars)`,metadata:{summary:`写入记忆: ${J}`}}}});import*as O1 from"fs/promises";import{z as j0}from"zod";var N5=D({name:"NotebookEdit",displayName:"Notebook Edit",kind:"write",isConcurrencySafe:!1,schema:j0.object({notebook_path:j0.string().describe("The absolute path to the Jupyter notebook file to edit (must be absolute, not relative)"),cell_id:j0.string().optional().describe("The ID of the cell to edit. When inserting a new cell, the new cell will be inserted after the cell with this ID, or at the beginning if not specified."),new_source:j0.string().describe("The new source for the cell"),cell_type:j0.enum(["code","markdown"]).optional().describe("The type of the cell (code or markdown). If not specified, it defaults to the current cell type. If using edit_mode=insert, this is required."),edit_mode:j0.enum(["replace","insert","delete"]).optional().default("replace").describe("The type of edit to make (replace, insert, delete). Defaults to replace.")}),description:{short:"Completely replaces the contents of a specific cell in a Jupyter notebook",long:"Completely replaces the contents of a specific cell in a Jupyter notebook (.ipynb file) with new source. Jupyter notebooks are interactive documents that combine code, text, and visualizations, commonly used for data analysis and scientific computing. The notebook_path parameter must be an absolute path, not a relative path. The cell_number is 0-indexed. Use edit_mode=insert to add a new cell at the index specified by cell_number. Use edit_mode=delete to delete the cell at the index specified by cell_number."},async execute($,Z){let{notebook_path:J,cell_id:W,new_source:X,cell_type:Y,edit_mode:V="replace"}=$;try{let B=await O1.readFile(J,"utf-8"),K=JSON.parse(B);if(!K.cells||!Array.isArray(K.cells))return{success:!1,llmContent:"Invalid notebook format: no cells array found",error:{type:"validation_error",message:"Invalid notebook format"},metadata:{summary:"无效的 Notebook 格式"}};let Q=-1;if(W){if(Q=K.cells.findIndex((q)=>q.id===W),Q===-1&&V!=="insert")return{success:!1,llmContent:`Cell with ID "${W}" not found`,error:{type:"validation_error",message:`Cell ID "${W}" not found`},metadata:{summary:`Cell 未找到: ${W}`}}}switch(V){case"replace":{if(Q===-1)return{success:!1,llmContent:"Cell ID required for replace operation",error:{type:"validation_error",message:"Cell ID required for replace"},metadata:{summary:"替换操作需要 Cell ID"}};let q=K.cells[Q];if(q.source=X.split(`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "blade-code",
3
- "version": "0.5.15",
3
+ "version": "0.5.17",
4
4
  "private": false,
5
5
  "description": "🗡️ Blade Code - 智能代码助手命令行工具",
6
6
  "type": "module",
@@ -1 +0,0 @@
1
- import{t as a,u as b}from"./chunk-fq64rt80.js";import"./chunk-cbcws8wy.js";import"./chunk-j2ag7hh6.js";export{a as globalOptions,b as cliConfig};