blade-code 0.5.19 → 0.6.0
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 +2 -2
- package/dist/{chunk-rpdww3y7.js → chunk-02dgzrzh.js} +1 -1
- package/dist/{chunk-w5bqfcdd.js → chunk-1cb2kqqm.js} +2 -2
- package/dist/{chunk-yk91w5p2.js → chunk-3w1zqywq.js} +3 -3
- package/dist/{chunk-q5yn875m.js → chunk-3z8h9j4f.js} +1 -1
- package/dist/{chunk-pfsft4nd.js → chunk-49pjm1fc.js} +1 -1
- package/dist/{chunk-7gje20de.js → chunk-4h4y84d6.js} +1 -1
- package/dist/chunk-4s0brhtr.js +1 -0
- package/dist/{chunk-yddnm9n2.js → chunk-50qc4e5g.js} +1 -1
- package/dist/{chunk-x9zj0r7s.js → chunk-6c5v0yas.js} +1 -1
- package/dist/{chunk-s9vcpyaq.js → chunk-7qy4kfe7.js} +1 -1
- package/dist/{chunk-bhjw4b73.js → chunk-7rjrzngk.js} +1 -1
- package/dist/chunk-9x5w4as8.js +1 -0
- package/dist/{chunk-k65n39by.js → chunk-bs9fg1qz.js} +1 -1
- package/dist/{chunk-7841654x.js → chunk-cwbszfye.js} +1 -1
- package/dist/chunk-dr1bb8ya.js +28 -0
- package/dist/{chunk-0a5rp0hh.js → chunk-e5ngx3x1.js} +37 -27
- package/dist/{chunk-q6e7ttyy.js → chunk-ekfmr2cb.js} +351 -330
- package/dist/{chunk-4jcdk905.js → chunk-gky78ctd.js} +1 -1
- package/dist/{chunk-g5pasj7t.js → chunk-gn1acna6.js} +1 -1
- package/dist/{chunk-yvs4mhkv.js → chunk-h9q2wpcp.js} +1 -1
- package/dist/{chunk-5mqvwzj8.js → chunk-hhtpxjqn.js} +1 -1
- package/dist/{chunk-zxame725.js → chunk-hy4dsdpp.js} +1 -1
- package/dist/{chunk-set7v1rf.js → chunk-ktag2d1c.js} +1 -1
- package/dist/chunk-mganjb5p.js +1 -0
- package/dist/{chunk-h6vkcgcb.js → chunk-n5xfrmrp.js} +1 -1
- package/dist/chunk-n9mwp62v.js +1 -0
- package/dist/{chunk-gym5t6r6.js → chunk-nhmdze8s.js} +1 -1
- package/dist/chunk-qv3wcc4p.js +2 -0
- package/dist/{chunk-j2ag7hh6.js → chunk-s53zeref.js} +1 -1
- package/dist/chunk-szbfafff.js +1 -0
- package/dist/{chunk-mz6n4w13.js → chunk-t1ex4e6g.js} +1 -1
- package/dist/{chunk-4fkv1hhp.js → chunk-tcqrc6pc.js} +1 -1
- package/dist/{chunk-37rethcy.js → chunk-v0z4bwcv.js} +2 -2
- package/dist/{chunk-68ctb04g.js → chunk-vwcjwzw3.js} +1 -1
- package/dist/{chunk-kt9197hs.js → chunk-w0hbjyzt.js} +1 -1
- package/dist/{chunk-7ycmx7c2.js → chunk-wre40mf1.js} +1 -1
- package/dist/{chunk-8kawkyrj.js → chunk-yjrx2q95.js} +1 -1
- package/dist/{chunk-e2h6cdnx.js → chunk-yz1nbhxn.js} +1 -1
- package/dist/{chunk-qwfywxs2.js → chunk-zfy765hj.js} +1 -1
- package/package.json +1 -1
- package/dist/chunk-bx4d9898.js +0 -1
- package/dist/chunk-c7rvs5ev.js +0 -2
- package/dist/chunk-fe7g701v.js +0 -1
- package/dist/chunk-mxrre2n3.js +0 -24
- package/dist/chunk-th432d0b.js +0 -1
- package/dist/chunk-z4ds84bg.js +0 -1
- package/dist/chunk-zh3ndtvg.js +0 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{N as l,O as c,P as m,S as g,U as d}from"./chunk-
|
|
1
|
+
import{N as l,O as c,P as m,S as g,U as d}from"./chunk-ekfmr2cb.js";import{Eb as u}from"./chunk-wre40mf1.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 +1 @@
|
|
|
1
|
-
import"./chunk-
|
|
1
|
+
import"./chunk-s53zeref.js";var d={command:"install [target]",describe:"Install Blade native build. Use [target] to specify version (stable, latest, or specific version)",builder:(b)=>{return b.positional("target",{describe:"Version to install",type:"string",default:"stable",choices:["stable","latest"]}).option("force",{type:"boolean",describe:"Force reinstall",default:!1}).example([["$0 install","Install stable version"],["$0 install latest","Install latest version"],["$0 install --force","Force reinstall stable version"]])},handler:async(b)=>{console.log(`Installing Blade ${b.target}...`);try{if(b.force)console.log("Force reinstall enabled");console.log("Downloading..."),console.log("Installing..."),console.log("Installation completed successfully")}catch(c){console.error(`Error: Installation failed: ${c instanceof Error?c.message:"未知错误"}`),process.exit(1)}}};export{d as installCommands};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{e as zf,f as Tf}from"./chunk-
|
|
1
|
+
import{e as zf,f as Tf}from"./chunk-3z8h9j4f.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-ekfmr2cb.js";import{Y as T}from"./chunk-yz1nbhxn.js";import{ba as u}from"./chunk-qv3wcc4p.js";import{Ba as xf,Ca as Rf,Ga as z,za as S}from"./chunk-6c5v0yas.js";import{Sa as _f,Ua as t,Za as Ef}from"./chunk-e5ngx3x1.js";import{Eb as R}from"./chunk-wre40mf1.js";import{Ib as x}from"./chunk-ktag2d1c.js";import{Kb as jf}from"./chunk-s53zeref.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{va as z}from"./chunk-
|
|
1
|
+
import{va as z}from"./chunk-6c5v0yas.js";import{Ia as w}from"./chunk-t1ex4e6g.js";import{Ib as u}from"./chunk-ktag2d1c.js";var q=u("General"),F=(b)=>{if(b.yolo){if(b.permissionMode&&b.permissionMode!=="yolo")throw Error("Cannot use both --yolo and --permission-mode with different values");b.permissionMode="yolo"}if(Array.isArray(b.allowedTools))b.allowedTools=b.allowedTools.flatMap((h)=>h.split(",").map((k)=>k.trim()).filter((k)=>k.length>0));if(Array.isArray(b.disallowedTools))b.disallowedTools=b.disallowedTools.flatMap((h)=>h.split(",").map((k)=>k.trim()).filter((k)=>k.length>0));if(Array.isArray(b.allowedTools)&&Array.isArray(b.disallowedTools)){let h=b.allowedTools.filter((k)=>b.disallowedTools.includes(k));if(h.length>0)throw Error(`Tools cannot be both allowed and disallowed: ${h.join(", ")}`)}},G=async(b)=>{try{let k=await w.getInstance().initialize();if(z().config.actions.setConfig(k),b.debug)q.info("[CLI] 配置已加载到 Store")}catch(h){q.error("[CLI] [FAIL] 配置初始化失败",h instanceof Error?h.message:h),console.error(`
|
|
2
2
|
[FAIL] 配置初始化失败
|
|
3
3
|
`),console.error("原因:",h instanceof Error?h.message:"未知错误"),console.error(`
|
|
4
4
|
请检查:`),console.error(" 1. 配置文件格式是否正确 (~/.blade/config.json)"),console.error(" 2. 是否需要运行 blade 进行首次配置"),console.error(` 3. 配置文件权限是否正确
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Aa as g,Ba as h,Ca as i,Da as j,Ea as k,Fa as l,Ga as m,ua as a,va as b,wa as c,xa as d,ya as e,za as f}from"./chunk-
|
|
1
|
+
import{Aa as g,Ba as h,Ca as i,Da as j,Ea as k,Fa as l,Ga as m,ua as a,va as b,wa as c,xa as d,ya as e,za as f}from"./chunk-6c5v0yas.js";import"./chunk-t1ex4e6g.js";import"./chunk-wre40mf1.js";import"./chunk-ktag2d1c.js";import"./chunk-s53zeref.js";export{a as vanillaStore,c as sessionActions,l as getThinkingModeEnabled,b as getState,j as getModelById,e as getMessages,k as getMcpServers,i as getCurrentModel,f as getConfig,h as getAllModels,g as ensureStoreInitialized,m as configActions,d as appActions};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
import{appendFileSync as Z,existsSync as _,mkdirSync as $,readdirSync as E,statSync as Y,unlinkSync as O}from"node:fs";import k from"node:os";import Q from"node:path";var R;((B)=>{B[B.DEBUG=0]="DEBUG";B[B.INFO=1]="INFO";B[B.WARN=2]="WARN";B[B.ERROR=3]="ERROR"})(R||={});var M=null,W=null,X=!1;function m(j){if(M!==j)M=j}async function I(){}function w(){if(X)return W;X=!0;try{let j=Q.join(k.homedir(),".blade","logs");if(!_(j))$(j,{recursive:!0,mode:493});if(Y(j).uid===0&&process.getuid&&process.getuid()!==0)return console.error(""),console.error("[FAIL] 权限错误:~/.blade/logs 目录属于 root 用户"),console.error(""),console.error("这通常是因为您曾经使用 sudo 运行过 blade。"),console.error(""),console.error("解决方法:"),console.error(" sudo chown -R $USER:$USER ~/.blade/"),console.error(""),console.error("然后重新运行 blade(不要使用 sudo)"),console.error(""),null;return z(j,30),W=j,j}catch(j){return console.error("[Logger] 无法创建日志目录:",j),null}}function z(j,q){try{let G=E(j),H=Date.now(),B=q*24*60*60*1000;for(let K of G){if(!K.startsWith("blade-")||!K.endsWith(".log")&&!K.endsWith(".jsonl"))continue;let T=Q.join(j,K);try{let U=Y(T);if(H-U.mtimeMs>B)O(T)}catch(U){}}}catch(G){}}function F(){let j=w();if(!j)return null;let q=M||"default";return Q.join(j,`blade-${q}.jsonl`)}function A(j,q,G){let H=F();if(!H)return;try{let B={timestamp:new Date().toISOString(),level:R[q],category:j,message:G};Z(H,JSON.stringify(B)+`
|
|
2
2
|
`)}catch(B){}}class J{static globalDebugConfig=null;enabled;minLevel;category;constructor(j={}){if(j.enabled!==void 0)this.enabled=j.enabled;else if(J.globalDebugConfig!==null)this.enabled=Boolean(J.globalDebugConfig);else this.enabled=!1;this.minLevel=j.minLevel??0,this.category=j.category??"General"}static setGlobalDebug(j){J.globalDebugConfig=j}static clearGlobalDebug(){J.globalDebugConfig=null}setEnabled(j){this.enabled=j}parseDebugFilter(j){if(!j)return{enabled:!1};if(j===!0||j==="true"||j==="1")return{enabled:!0};let q=String(j).trim();if(!q)return{enabled:!0};if(q.startsWith("!"))return{enabled:!0,filter:{mode:"exclude",categories:q.split(",").map((B)=>B.trim().replace(/^!/,"")).filter(Boolean)}};return{enabled:!0,filter:{mode:"include",categories:q.split(",").map((H)=>H.trim()).filter(Boolean)}}}shouldLogCategory(j){if(!j)return!0;let q=this.category.toLowerCase();if(j.mode==="include")return j.categories.some((G)=>q.includes(G.toLowerCase()));return!j.categories.some((G)=>q.includes(G.toLowerCase()))}shouldLogToConsole(j){if(J.globalDebugConfig!==null){let{enabled:q,filter:G}=this.parseDebugFilter(J.globalDebugConfig);if(!q)return!1;if(j<this.minLevel)return!1;return this.shouldLogCategory(G)}return this.enabled&&j>=this.minLevel}log(j,...q){let G=q.map((H)=>typeof H==="object"?JSON.stringify(H):String(H)).join(" ");if(A(this.category,j,G),this.shouldLogToConsole(j)){let H=R[j],B=`[${this.category}] [${H}]`;console.error(B,...q)}}debug(...j){this.log(0,...j)}info(...j){this.log(1,...j)}warn(...j){this.log(2,...j)}error(...j){this.log(3,...j)}}function V(j,q){return new J({...q,category:j})}var h=new J({category:"General"});
|
|
3
|
-
export{m as
|
|
3
|
+
export{m as Fb,I as Gb,J as Hb,V as Ib,h as Jb};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{ga as a}from"./chunk-vwcjwzw3.js";import"./chunk-6c5v0yas.js";import"./chunk-t1ex4e6g.js";import"./chunk-wre40mf1.js";import"./chunk-ktag2d1c.js";import"./chunk-s53zeref.js";export{a as SpecManager};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{aa as a,ba as b,ca as c,da as d,ea as e,fa as f}from"./chunk-
|
|
1
|
+
import{aa as a,ba as b,ca as c,da as d,ea as e,fa as f}from"./chunk-qv3wcc4p.js";import"./chunk-s53zeref.js";export{b as getVersion,c as getPackageName,a as getPackageInfo,e as getFormattedVersion,d as getDescription,f as getCopyright};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{g as a,h as b,i as c,j as d,k as e}from"./chunk-zfy765hj.js";import"./chunk-s53zeref.js";export{b as setSkipUntilVersion,d as performUpgrade,c as getUpgradeCommand,e as checkVersionOnStartup,a as checkVersion};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{p as _,q as x,r as E,s as N}from"./chunk-
|
|
1
|
+
import{p as _,q as x,r as E,s as N}from"./chunk-gky78ctd.js";import{t as A}from"./chunk-4h4y84d6.js";import{v as B,w as D,x as L}from"./chunk-hhtpxjqn.js";import{G as $,M as b}from"./chunk-ekfmr2cb.js";import"./chunk-yz1nbhxn.js";import"./chunk-dr1bb8ya.js";import"./chunk-qv3wcc4p.js";import"./chunk-vwcjwzw3.js";import"./chunk-6c5v0yas.js";import"./chunk-t1ex4e6g.js";import{Za as Z}from"./chunk-e5ngx3x1.js";import"./chunk-50qc4e5g.js";import"./chunk-3w1zqywq.js";import"./chunk-v0z4bwcv.js";import{Db as X,Eb as Y}from"./chunk-wre40mf1.js";import"./chunk-ktag2d1c.js";import"./chunk-s53zeref.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}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
var e={name:"blade-code",version:"0.6.0",private:!1,description:"🗡️ Blade Code - 智能代码助手命令行工具",type:"module",bin:{blade:"dist/blade.js"},files:["dist","vendor/ripgrep/**","README.md"],scripts:{dev:"node scripts/run-bun.js --watch src/blade.tsx","dev:serve":"node scripts/run-bun.js --watch src/blade.tsx serve --port 4097",build:"rm -rf dist && node scripts/run-bun.js run scripts/build.ts",start:"node scripts/run-bun.js run dist/blade.js",test:"node scripts/test.js","test:all":"vitest run --config vitest.config.ts","test:unit":"node scripts/test.js unit","test:integration":"node scripts/test.js integration","test:cli":"node scripts/test.js cli","test:headless-core":"node scripts/test.js headlessCore","test:e2e":"node scripts/test.js e2e","test:performance":"node scripts/test.js performance","test:snapshot":"node scripts/test.js snapshot","test:security":"node scripts/test.js security","test:coverage":"node scripts/test.js all --coverage","test:watch":"vitest --watch --config vitest.config.ts","benchmark:repo":"node scripts/run-bun.js run scripts/run-real-repo-benchmark.ts","test:update-snapshots":"node scripts/test.js snapshot --update",lint:"biome lint src tests","lint:fix":"biome lint --write src tests","type-check":"tsc --noEmit","format:check":"biome format src tests",ready:"node scripts/run-bun.js run scripts/ready.ts","detect-unused":"node scripts/run-bun.js run scripts/detect-unused.ts",release:"node scripts/release.js","release:dry":"node scripts/release.js --dry-run","release:major":"node scripts/release.js --major","release:minor":"node scripts/release.js --minor","release:patch":"node scripts/release.js --patch"},keywords:["cli","blade","ai","assistant","agent","llm"],author:"echoVic",license:"MIT",engines:{node:">=20.0.0"},optionalDependencies:{"@vscode/ripgrep":"^1.17.0","bun-pty":"^0.4.8","node-pty":"1.0.0"},dependencies:{"@agentclientprotocol/sdk":"^0.12.0","@ai-sdk/anthropic":"^3.0.7","@ai-sdk/azure":"^3.0.5","@ai-sdk/deepseek":"^2.0.4","@ai-sdk/google":"^3.0.4","@ai-sdk/openai":"^3.0.26","@ai-sdk/openai-compatible":"^2.0.4","@inkjs/ui":"^2.0.0","@modelcontextprotocol/sdk":"^1.17.4",ahooks:"^3.9.6",ai:"^6.0.39","ansi-escapes":"^7.2.0","async-mutex":"^0.5.0",axios:"^1.12.2",chalk:"^5.4.1",diff:"^8.0.2","fast-glob":"^3.3.3","fuse.js":"^7.1.0","gray-matter":"^4.0.3",hono:"^4.7.10",ink:"npm:@jrichman/ink@6.4.10","ink-big-text":"^2.0.0","ink-gradient":"^3.0.0","ink-select-input":"^6.2.0","ink-spinner":"^5.0.0","ink-text-input":"^6.0.0","js-tiktoken":"^1.0.21","lodash-es":"^4.17.21",lowlight:"^3.3.0","lru-cache":"^11.2.4",nanoid:"^5.1.6",open:"^10.1.2",openai:"^6.2.0",picomatch:"^4.0.3",react:"^19.1.1","react-dom":"^19.1.1",semver:"^7.7.3","string-width":"^8.1.0",undici:"^7.16.0","write-file-atomic":"^7.0.0",ws:"^8.18.0",yaml:"^2.8.1",yargs:"^18.0.0",zod:"^3.24.2","zod-to-json-schema":"^3.24.6",zustand:"^5.0.9"},devDependencies:{"@biomejs/biome":"^2.2.4","@types/bun":"^1.3.4","@types/json-schema":"^7.0.15","@types/lodash-es":"^4.17.12","@types/node":"^22.15.24","@types/picomatch":"^4.0.2","@types/react":"^19.1.1","@types/react-dom":"^19.1.1","@types/semver":"^7.7.1","@types/write-file-atomic":"^4.0.3","@types/ws":"^8.5.12","@types/yargs":"^17.0.33","@vitest/coverage-v8":"^3.0.0",jsdom:"^26.0.0",typescript:"^5.9.2",vitest:"^3.0.0"}};function r(){return{name:e.name,version:e.version,description:e.description}}function n(){return e.version}function o(){return e.name}function c(){return e.description}function d(){return`v${e.version}`}function a(){return`v${e.version} © 2025 Blade Code`}
|
|
2
|
+
export{r as aa,n as ba,o as ca,c as da,d as ea,a as fa};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import{createRequire as a}from"node:module";var c=a(import.meta.url);
|
|
2
|
-
export{c as
|
|
2
|
+
export{c as Kb};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{v as a,w as b,x as c}from"./chunk-hhtpxjqn.js";import"./chunk-6c5v0yas.js";import"./chunk-t1ex4e6g.js";import"./chunk-wre40mf1.js";import"./chunk-ktag2d1c.js";import"./chunk-s53zeref.js";export{a as validatePermissions,c as validateOutput,b as loadConfiguration};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{Eb as Z}from"./chunk-wre40mf1.js";import{Ib as w}from"./chunk-ktag2d1c.js";var F={currentModelId:"",models:[],temperature:0,maxContextTokens:128000,maxOutputTokens:void 0,stream:!0,topP:0.9,topK:50,timeout:180000,theme:"dracula",uiTheme:"system",language:"zh-CN",fontSize:14,autoSaveSessions:!0,notifyBuild:!0,notifyErrors:!1,notifySounds:!1,privacyTelemetry:!1,privacyCrash:!0,debug:!1,mcpEnabled:!1,mcpServers:{},permissions:{allow:["Bash(pwd)","Bash(which *)","Bash(whoami)","Bash(hostname)","Bash(uname *)","Bash(date)","Bash(echo *)","Bash(ls *)","Bash(tree *)","Bash(git status)","Bash(git status -*)","Bash(git log *)","Bash(git diff *)","Bash(git show *)","Bash(git branch -* *)","Bash(git branch)","Bash(git tag -l *)","Bash(git tag --list *)","Bash(git stash list *)","Bash(git stash show *)","Bash(git rev-parse *)","Bash(git describe *)","Bash(git blame *)","Bash(git ls-files *)","Bash(git config --get *)","Bash(git config --list *)","Bash(git shortlog *)","Bash(git merge-base *)","Bash(git cat-file *)","Bash(git for-each-ref *)","Bash(git grep *)","Bash(git worktree list *)","Bash(git reflog show *)","Bash(git reflog)","Bash(git rev-list *)","Bash(git ls-remote *)","Bash(git remote -v)","Bash(git remote --verbose)","Bash(git remote)","Bash(gh pr view *)","Bash(gh pr list *)","Bash(gh pr diff *)","Bash(gh pr checks *)","Bash(gh pr status *)","Bash(gh issue view *)","Bash(gh issue list *)","Bash(gh issue status *)","Bash(gh run list *)","Bash(gh run view *)","Bash(gh repo view *)","Bash(gh auth status)","Bash(npm list *)","Bash(bun pm ls *)","Bash(npm view *)","Bash(npm outdated *)","Bash(pnpm list *)","Bash(yarn list *)","Bash(pip list *)","Bash(pip show *)"],ask:["Bash(curl *)","Bash(wget *)","Bash(aria2c *)","Bash(axel *)","Bash(rm -rf *)","Bash(rm -r *)","Bash(rm --recursive *)","Bash(nc *)","Bash(netcat *)","Bash(telnet *)","Bash(ncat *)"],deny:["Read(./.env)","Read(./.env.*)","Bash(rm -rf /)","Bash(rm -rf /*)","Bash(sudo *)","Bash(chmod 777 *)","Bash(bash *)","Bash(sh *)","Bash(zsh *)","Bash(fish *)","Bash(dash *)","Bash(eval *)","Bash(source *)","Bash(mkfs *)","Bash(fdisk *)","Bash(dd *)","Bash(format *)","Bash(parted *)","Bash(open http*)","Bash(open https*)","Bash(xdg-open http*)","Bash(xdg-open https*)"]},permissionMode:"default",hooks:{enabled:!1,defaultTimeout:60,timeoutBehavior:"ignore",failureBehavior:"ignore",maxConcurrentHooks:5,PreToolUse:[],PostToolUse:[],PostToolUseFailure:[],PermissionRequest:[],UserPromptSubmit:[],SessionStart:[],SessionEnd:[],Stop:[],SubagentStop:[],Notification:[],Compaction:[]},env:{},disableAllHooks:!1,maxTurns:-1};import{promises as T}from"fs";import{merge as _}from"lodash-es";import I from"os";import G from"path";var M={sonnet:"claude-sonnet-4-20250514",opus:"claude-opus-4-20250514",haiku:"claude-3-5-haiku-20241022",claude:"claude-sonnet-4-20250514",gpt4o:"gpt-4o",gpt4:"gpt-4o",o1:"o1",o3:"o3","o4-mini":"o4-mini",deepseek:"deepseek-chat","deepseek-v3":"deepseek-chat","deepseek-r1":"deepseek-reasoner","deepseek-v4":"deepseek-v4-0324",gemini:"gemini-2.5-pro",flash:"gemini-2.5-flash",qwen:"qwen3-235b-a22b","qwen-max":"qwen-max","qwen-plus":"qwen-plus"};function U(J){let q=J.toLowerCase().trim();return M[q]??J}class B{static instance=null;constructor(){}static getInstance(){if(!B.instance)B.instance=new B;return B.instance}static resetInstance(){B.instance=null}async initialize(){try{let J=await this.loadConfigFiles(),q=await this.loadSettingsFiles(),H={...J,...q},Q=this.normalizeConfig(H),K={...F,...Q};if(this.resolveEnvInterpolation(K),process.env.BLADE_MODEL&&K.models?.length>0){let W=U(process.env.BLADE_MODEL),X=K.models.find((Y)=>Y.id===W||Y.model===W||Y.id===process.env.BLADE_MODEL||Y.model===process.env.BLADE_MODEL);if(X)K.currentModelId=X.id}if(process.env.BLADE_API_KEY&&K.models?.length>0){let W=K.models.find((X)=>X.id===K.currentModelId);if(W)W.apiKey=process.env.BLADE_API_KEY}if(process.env.BLADE_BASE_URL&&K.models?.length>0){let W=K.models.find((X)=>X.id===K.currentModelId);if(W)W.baseUrl=process.env.BLADE_BASE_URL}if(process.env.BLADE_DEBUG)K.debug=process.env.BLADE_DEBUG==="1"||process.env.BLADE_DEBUG==="true"||process.env.BLADE_DEBUG;if(K.debug)console.log("[ConfigManager] Configuration loaded successfully");return K}catch(J){return console.error("[ConfigManager] Failed to initialize:",J),F}}async loadConfigFiles(){let J=G.join(I.homedir(),".blade","config.json"),q=G.join(Z(),".blade","config.json"),H={},Q=await this.loadJsonFile(J);if(Q)H={...H,...Q};let K=await this.loadJsonFile(q);if(K){let W={...H.mcpServers||{},...K.mcpServers||{}};if(H={...H,...K},Object.keys(W).length>0)H.mcpServers=W}return H}async loadSettingsFiles(){let J=G.join(I.homedir(),".blade","settings.json"),q=G.join(Z(),".blade","settings.json"),H=G.join(Z(),".blade","settings.local.json"),Q={},K=await this.loadJsonFile(J);if(K)Q=this.mergeSettings(Q,K);let W=await this.loadJsonFile(q);if(W)Q=this.mergeSettings(Q,W);let X=await this.loadJsonFile(H);if(X)Q=this.mergeSettings(Q,X);return Q}mergeSettings(J,q){let H=JSON.parse(JSON.stringify(J));if(q.permissions){if(!H.permissions)H.permissions={allow:[],ask:[],deny:[]};if(q.permissions.allow){let Q=[...H.permissions.allow||[],...q.permissions.allow];H.permissions.allow=Array.from(new Set(Q))}if(q.permissions.ask){let Q=[...H.permissions.ask||[],...q.permissions.ask];H.permissions.ask=Array.from(new Set(Q))}if(q.permissions.deny){let Q=[...H.permissions.deny||[],...q.permissions.deny];H.permissions.deny=Array.from(new Set(Q))}}if(q.hooks)H.hooks=_({},H.hooks,q.hooks);if(q.env)H.env=_({},H.env,q.env);if(q.mcpServers)H.mcpServers={...H.mcpServers||{},...q.mcpServers};if(q.disableAllHooks!==void 0)H.disableAllHooks=q.disableAllHooks;if(q.permissionMode!==void 0)H.permissionMode=q.permissionMode;if(q.maxTurns!==void 0)H.maxTurns=q.maxTurns;return H}resolveEnvInterpolation(J){let q=/\$\{?([A-Z_][A-Z0-9_]*)(:-([^}]+))?\}?/g,H=(K)=>{if(typeof K==="string")return K.replace(q,(W,X,Y,V)=>{return process.env[X]||V||W});if(Array.isArray(K))return K.map(H);if(typeof K==="object"&&K!==null){let W=K;for(let[X,Y]of Object.entries(W))W[X]=H(Y);return W}return K},Q=J;for(let[K,W]of Object.entries(Q))Q[K]=H(W)}async loadJsonFile(J){try{if(await this.fileExists(J)){let q=await T.readFile(J,"utf-8");return JSON.parse(q)}}catch(q){console.warn(`[ConfigManager] Failed to load ${J}:`,q)}return null}async fileExists(J){try{return await T.access(J),!0}catch{return!1}}normalizeConfig(J){let q=JSON.parse(JSON.stringify(J)),H=(K)=>K.trim().replace(/^`|`$/g,""),Q=(K)=>{for(let[W,X]of Object.entries(K))if(typeof X==="string")K[W]=H(X);else if(Array.isArray(X))X.forEach((Y,V)=>{if(typeof Y==="string")X[V]=H(Y);else if(typeof Y==="object"&&Y!==null)Q(Y)});else if(typeof X==="object"&&X!==null)Q(X)};return Q(q),q}validateConfig(J){let q=[],H=[];if(!J.models||J.models.length===0)q.push("没有可用的模型配置");if(J.models&&J.models.length>0){if(!J.currentModelId)q.push("未设置当前模型 ID");else if(!J.models.find((K)=>K.id===J.currentModelId))q.push(`当前模型 ID "${J.currentModelId}" 在 models 列表中不存在`);for(let Q of J.models){let K=`模型 "${Q.name||Q.id}"`;if(!Q.apiKey)H.push(`${K}: apiKey 为空`);if(!Q.model)q.push(`${K}: model 字段必填`);if(!Q.provider)q.push(`${K}: provider 字段必填`);if(Q.baseUrl&&!Q.baseUrl.startsWith("http"))H.push(`${K}: baseUrl "${Q.baseUrl}" 不是有效的 HTTP URL`)}}if(H.length>0)console.warn(`[ConfigManager] 配置警告:
|
|
2
2
|
${H.map((Q)=>` ⚠ ${Q}`).join(`
|
|
3
3
|
`)}`);if(q.length>0)throw Error(`配置验证失败:
|
|
4
4
|
${q.map((Q)=>` - ${Q}`).join(`
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{$a as
|
|
1
|
+
import{$a as e,Xa as a,Ya as b,Za as c,_a as d,ab as f,bb as g,cb as h,db as i,eb as j,fb as k,gb as l,hb as m,ib as n,jb as o,mb as p,nb as q,ob as r}from"./chunk-e5ngx3x1.js";import"./chunk-50qc4e5g.js";import"./chunk-3w1zqywq.js";import"./chunk-v0z4bwcv.js";import"./chunk-wre40mf1.js";import"./chunk-ktag2d1c.js";import"./chunk-s53zeref.js";export{g as saveUserMessage,i as saveToolUse,j as saveToolResult,k as saveCompaction,h as saveAssistantMessage,a as isRootSystemPrompt,l as handleTaskListUpdate,m as handleSkillActivation,n as extractModelSwitch,r as executeLoopGenerator,c as drainLoop,f as checkStopHook,d as checkOutputRecovery,e as checkIncompleteIntent,q as checkAndCompactInLoop,o as applyToolDomainEffects,p as StreamingToolExecutor,b as ConversationState};
|
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{Ib as S}from"./chunk-ktag2d1c.js";var f=["anthropic","openai","deepseek","google-generative-ai","groq","openrouter"],u={anthropic:"",openai:"","google-generative-ai":"",deepseek:"",groq:"",openrouter:"",azure:"",ollama:"",together:"",fireworks:"",mistral:"",cohere:"",perplexity:"",xai:"",default:""},c={anthropic:"https://api.anthropic.com",openai:"https://api.openai.com/v1",google:"https://generativelanguage.googleapis.com/v1beta",deepseek:"https://api.deepseek.com/v1",groq:"https://api.groq.com/openai/v1",openrouter:"https://openrouter.ai/api/v1",togetherai:"https://api.together.xyz/v1","fireworks-ai":"https://api.fireworks.ai/inference/v1",mistral:"https://api.mistral.ai/v1",cohere:"https://api.cohere.ai/v1",perplexity:"https://api.perplexity.ai",xai:"https://api.x.ai/v1",cerebras:"https://api.cerebras.ai/v1","novita-ai":"https://api.novita.ai/v3/openai",nvidia:"https://integrate.api.nvidia.com/v1"},T={anthropic:{"anthropic-beta":"claude-code-20250219,interleaved-thinking-2025-05-14,fine-grained-tool-streaming-2025-05-14"},openrouter:{"HTTP-Referer":"https://github.com/anthropics/blade","X-Title":"Blade"},cerebras:{"X-Cerebras-3rd-Party-Integration":"blade"},vercel:{"http-referer":"https://github.com/anthropics/blade","x-title":"blade"},zenmux:{"HTTP-Referer":"https://github.com/anthropics/blade","X-Title":"blade"}},H=(Q)=>{return T[Q]||{}};import{createAnthropic as I}from"@ai-sdk/anthropic";import{createAzure as K}from"@ai-sdk/azure";import{createDeepSeek as A}from"@ai-sdk/deepseek";import{createGoogleGenerativeAI as E}from"@ai-sdk/google";import{createOpenAI as y}from"@ai-sdk/openai";import{createOpenAICompatible as V}from"@ai-sdk/openai-compatible";import{generateText as U,jsonSchema as x,streamText as M}from"ai";var j=S("Chat");function O(Q){let q=new Set;for(let X of Q)if(X.role==="assistant"&&X.tool_calls)for(let W of X.tool_calls)q.add(W.id);return Q.filter((X)=>{if(X.role==="tool"){if(!X.tool_call_id)return!1;return q.has(X.tool_call_id)}return!0})}function L(Q){if(typeof Q==="string")return Q;return Q.filter((q)=>q.type==="text").map((q)=>q.text).join(`
|
|
2
2
|
`)}function h(Q){let q=Q;return q.text??q.textDelta??q.delta}function C(Q,q={}){try{return JSON.parse(Q)}catch{return j.warn("[VercelAIChatService] Failed to parse JSON, using fallback",{str:Q}),q}}class R{model;config;constructor(Q){this.config=Q,this.model=this.createModel(Q),j.debug("[VercelAIChatService] Initialized",{provider:Q.provider,model:Q.model})}createModel(Q){let{provider:q,apiKey:X,baseUrl:W,model:Y,customHeaders:Z,apiVersion:J}=Q;switch(q){case"openai":return y({apiKey:X,baseURL:W||void 0,headers:Z})(Y);case"anthropic":return I({apiKey:X,baseURL:W||void 0,headers:Z})(Y);case"gemini":{if(W&&!this.isGeminiOfficialUrl(W))return V({name:"gemini",apiKey:X,baseURL:W,headers:Z})(Y);return E({apiKey:X,baseURL:W||void 0})(Y)}case"google":case"google-generative-ai":case"google-vertex":{if(W&&!this.isGeminiOfficialUrl(W))return V({name:q,apiKey:X,baseURL:W,headers:Z})(Y);return E({apiKey:X,baseURL:W||void 0})(Y)}case"azure-openai":{let $=this.extractAzureResourceName(W);if($)return K({apiKey:X,resourceName:$,apiVersion:J||"2024-08-01-preview"})(Y);let _=this.buildAzureBaseUrl(W,Y);return V({name:"azure-openai",apiKey:X,baseURL:_,headers:{...Z,"api-key":X},queryParams:{"api-version":J||"2024-08-01-preview"}})(Y)}case"azure":{let $=this.extractAzureResourceName(W);if($)return K({apiKey:X,resourceName:$,apiVersion:J||"2024-08-01-preview"})(Y);let _=this.buildAzureBaseUrl(W,Y);return V({name:"azure-openai",apiKey:X,baseURL:_,headers:{...Z,"api-key":X},queryParams:{"api-version":J||"2024-08-01-preview"}})(Y)}case"deepseek":return A({apiKey:X,baseURL:W||void 0,headers:Z})(Y);default:return V({name:q,apiKey:X,baseURL:W,headers:Z})(Y)}}extractAzureResourceName(Q){if(!Q)return;let q=Q.match(/https:\/\/([^.]+)\.openai\.azure(?:\.com|\.us|\.cn|\.de)/);return q?q[1]:void 0}buildAzureBaseUrl(Q,q){if(!Q)return"";let X=Q.replace(/\/$/,"").replace(/\?.*$/,"");if(X.includes("/openai/deployments/"))return X;return`${X}/openai/deployments/${q}`}isGeminiOfficialUrl(Q){return Q.includes("generativelanguage.googleapis.com")||Q.includes("aiplatform.googleapis.com")}needsThinkingReplayMetadata(){return/deepseek/i.test([this.config.provider,this.config.model,this.config.baseUrl].join(" "))}getThinkingReplayProviderOptions(Q){let q=Q?.trim();if(!q||!this.needsThinkingReplayMetadata())return;return{openaiCompatible:{reasoning_content:q}}}shouldFlattenDeepSeekThinkingToolHistory(){return this.needsThinkingReplayMetadata()}flattenDeepSeekThinkingToolHistory(Q){let q=[],X,W=()=>{if(!X)return;q.push({role:"assistant",content:L(X.content).trim()||"I will use the requested tool and continue from its result."}),X=void 0};for(let Y of Q){if(Y.role==="system"){W(),q.push({role:"user",content:`<system>
|
|
3
3
|
${L(Y.content)}
|
|
4
4
|
</system>`});continue}if(Y.role==="assistant"&&Y.tool_calls&&Y.tool_calls.length>0&&Y.reasoningContent?.trim()){W(),X=Y;continue}if(Y.role==="tool"&&X){let Z=X.tool_calls?.find(($)=>$.id===Y.tool_call_id),J=Z?.type==="function"?Z.function:void 0;q.push({role:"user",content:`Tool result for ${Y.name||J?.name||"tool"}${J?.arguments?`(${J.arguments})`:""}:
|
|
5
5
|
${L(Y.content)}
|
|
6
6
|
|
|
7
7
|
Continue from this tool result.`});continue}W(),q.push(Y)}return W(),q}convertMessages(Q){let q=[],X=this.shouldFlattenDeepSeekThinkingToolHistory()?this.flattenDeepSeekThinkingToolHistory(Q):Q;for(let W of X)if(W.role==="system")if(Array.isArray(W.content)){let Y=W.content.find((J)=>J.type==="text"),Z={role:"system",content:L(W.content)};if(Y?.providerOptions)Z.providerOptions=Y.providerOptions;q.push(Z)}else q.push({role:"system",content:W.content});else if(W.role==="user")if(Array.isArray(W.content)){let Y=W.content.map((Z)=>{if(Z.type==="text"){let J={type:"text",text:Z.text};if(Z.providerOptions)J.providerOptions=Z.providerOptions;return J}return{type:"image",image:Z.image_url.url}});q.push({role:"user",content:Y})}else q.push({role:"user",content:W.content});else if(W.role==="assistant")if(W.tool_calls&&W.tool_calls.length>0){let Y=W.tool_calls.map((_)=>{let w=_.function;return{type:"tool-call",toolCallId:_.id,toolName:w?.name||"",input:C(w?.arguments||"{}",{})}}),Z=L(W.content),J=W.reasoningContent?.trim()?[{type:"reasoning",text:W.reasoningContent}]:[],$=this.getThinkingReplayProviderOptions(W.reasoningContent);if(Z){let _={role:"assistant",content:[...J,{type:"text",text:Z},...Y]};if($)_.providerOptions=$;q.push(_)}else if(J.length>0){let _={role:"assistant",content:[...J,...Y]};if($)_.providerOptions=$;q.push(_)}else q.push({role:"assistant",content:Y})}else if(W.reasoningContent?.trim()){let Y=L(W.content),Z=[{type:"reasoning",text:W.reasoningContent}];if(Y)Z.push({type:"text",text:Y});let J={role:"assistant",content:Z},$=this.getThinkingReplayProviderOptions(W.reasoningContent);if($)J.providerOptions=$;q.push(J)}else q.push({role:"assistant",content:L(W.content)});else if(W.role==="tool")q.push({role:"tool",content:[{type:"tool-result",toolCallId:W.tool_call_id,toolName:W.name||"unknown",output:{type:"text",value:L(W.content)}}]});if(this.config.enablePromptCaching&&this.config.provider==="anthropic"){let W=0;for(let Y of q)if(Y.role==="system"&&W<2)Y.providerOptions={anthropic:{cacheControl:{type:"ephemeral"}}},W++;for(let Y=q.length-1;Y>=0;Y--)if(q[Y].role==="user"){q[Y].providerOptions={anthropic:{cacheControl:{type:"ephemeral"}}};break}}return q}convertTools(Q){if(!Q||Q.length===0)return;let q={};for(let X of Q)q[X.name]={description:X.description,inputSchema:x(X.parameters)};return q}convertToolCalls(Q){return Q.map((q)=>({id:q.toolCallId,type:"function",function:{name:q.toolName,arguments:JSON.stringify(q.args??q.input??{})}}))}convertUsage(Q,q){if(!Q)return;let X=Q.promptTokens??Q.inputTokens??0,W=Q.completionTokens??Q.outputTokens??0,Y={promptTokens:X,completionTokens:W,totalTokens:Q.totalTokens??X+W};if(Q.reasoningTokens)Y.reasoningTokens=Q.reasoningTokens;if(q?.anthropic){if(q.anthropic.cacheCreationInputTokens!==void 0)Y.cacheCreationInputTokens=q.anthropic.cacheCreationInputTokens;if(q.anthropic.cacheReadInputTokens!==void 0)Y.cacheReadInputTokens=q.anthropic.cacheReadInputTokens}return Y}isFallbackableError(Q){if(!(Q instanceof Error))return!1;let q=Q.message.toLowerCase();if(q.includes("timeout")||q.includes("econnrefused")||q.includes("enotfound"))return!0;let X=q.match(/status[:\s]*(\d{3})/),W=X?parseInt(X[1],10):Q.status;return W!==void 0&&[429,529,503,502,500].includes(W)}async retryWithBackoff(Q,q,X=2,W=1000){let Y;for(let Z=0;Z<=X;Z++)try{return await Q()}catch(J){if(Y=J,Z>=X)break;if(!this.isFallbackableError(J))throw J;if(q?.aborted)throw J;let $=W*Math.pow(2,Z);j.debug(`[VercelAIChatService] Retry ${Z+1}/${X} after ${$}ms`),await new Promise((_)=>setTimeout(_,$))}throw Y}getFallbackModelIds(){let Q=[];if(this.config.fallbackModels&&this.config.fallbackModels.length>0)Q.push(...this.config.fallbackModels);else if(this.config.fallbackModel)Q.push(this.config.fallbackModel);return Q}getThinkingProviderOptions(){if(!this.config.supportsThinking)return;let Q=this.config.thinkingMode??"budget";if(Q==="off")return;let q=Q==="adaptive",X=this.config.thinkingBudget??1e4;if(this.config.provider==="anthropic")return{anthropic:{thinking:q?{type:"enabled",budgetTokens:0}:{type:"enabled",budgetTokens:X}}};if(this.config.provider==="deepseek"||/deepseek/i.test(this.config.model))return{deepseek:{thinking:q?{type:"enabled",budgetTokens:0}:{type:"enabled",budgetTokens:X}}};return}getStreamTextOptions(Q,q,X,W){let Y=W;if(this.config.timeout&&this.config.timeout>0){let $=AbortSignal.timeout(this.config.timeout);if(W)Y=AbortSignal.any([W,$]);else Y=$}let Z={model:Q,messages:q,tools:X,maxOutputTokens:this.config.maxOutputTokens,temperature:this.config.temperature??0,abortSignal:Y,allowSystemInMessages:!0},J=this.getThinkingProviderOptions();if(J)Z.providerOptions=J;return Z}async chat(Q,q,X){let W=Date.now();j.debug("[VercelAIChatService] Starting chat request");let Y=O(Q),Z=this.convertMessages(Y),J=this.convertTools(q),$=async(_)=>{let w=await U(this.getStreamTextOptions(_,Z,J,X)),N=w.toolCalls&&w.toolCalls.length>0?this.convertToolCalls(w.toolCalls):void 0,z=Array.isArray(w.reasoning)?w.reasoning.map((B)=>B.text).join(""):void 0;return{content:w.text,reasoningContent:z,toolCalls:N,usage:this.convertUsage(w.usage,w.providerMetadata),finishReason:w.finishReason}};try{return await this.retryWithBackoff(()=>$(this.model),X,this.config.maxRetries)}catch(_){let w=Date.now()-W;if(j.error("[VercelAIChatService] Chat failed after",w,"ms"),!this.isFallbackableError(_))throw _;let N=this.getFallbackModelIds();if(N.length===0)throw _;for(let z of N){j.warn(`[VercelAIChatService] Trying fallback model: ${z}`);let B=this.createModel({...this.config,model:z});try{return await $(B)}catch(F){if(j.warn(`[VercelAIChatService] Fallback ${z} failed: ${F instanceof Error?F.message:F}`),!this.isFallbackableError(F))throw F}}throw _}}async*streamChat(Q,q,X){let W=Date.now();j.debug("[VercelAIChatService] Starting stream request");let Y=O(Q),Z=this.convertMessages(Y),J=this.convertTools(q),$=async function*(B,F){let D=M(B.getStreamTextOptions(F,Z,J,X)),P=0;for await(let G of D.fullStream)switch(G.type){case"text-delta":yield{content:h(G)};break;case"reasoning-delta":yield{reasoningContent:h(G)};break;case"tool-call":yield{toolCalls:[{index:P++,id:G.toolCallId,type:"function",function:{name:G.toolName,arguments:JSON.stringify(G.args??G.input??{})}}]};break;case"finish":yield{finishReason:G.finishReason,usage:B.convertUsage(G.totalUsage,G.providerMetadata)};break}},_=this.config.maxRetries??2,w;for(let B=0;B<=_;B++)try{yield*$(this,this.model);let F=Date.now()-W;j.debug("[VercelAIChatService] Stream completed in",F,"ms");return}catch(F){if(w=F,!this.isFallbackableError(F))throw F;if(B<_){let D=1000*Math.pow(2,B);j.debug(`[VercelAIChatService] Stream retry ${B+1}/${_} after ${D}ms`),await new Promise((P)=>setTimeout(P,D));continue}}let N=Date.now()-W;j.error("[VercelAIChatService] Stream failed after",N,"ms");let z=this.getFallbackModelIds();if(z.length===0)throw w;for(let B of z){j.warn(`[VercelAIChatService] Stream fallback: ${B}`),yield{modelFallback:!0};let F=this.createModel({...this.config,model:B});try{yield*$(this,F);return}catch(D){if(j.warn(`[VercelAIChatService] Stream fallback ${B} failed`),!this.isFallbackableError(D))throw D}}throw w}getConfig(){return{...this.config}}updateConfig(Q){j.debug("[VercelAIChatService] Updating configuration"),this.config={...this.config,...Q},this.model=this.createModel(this.config),j.debug("[VercelAIChatService] Configuration updated")}}var v=S("Service");async function qq(Q){let q=Q;if(q.provider){let X=H(q.provider);if(Object.keys(X).length>0)q={...q,customHeaders:{...X,...q.customHeaders}},v.debug(`Injected ${q.provider} specific headers:`,Object.keys(X))}return b(q)}function b(Q){return new R(Q)}
|
|
8
|
-
export{f as
|
|
8
|
+
export{f as vb,u as wb,c as xb,qq as yb};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{Ga as F,ra as $,ta as E,ua as q}from"./chunk-
|
|
1
|
+
import{Ga as F,ra as $,ta as E,ua as q}from"./chunk-6c5v0yas.js";import{Ib as w}from"./chunk-ktag2d1c.js";import{nanoid as O}from"nanoid";var Z=w("Spec");class X{static instance=null;fileManager=null;constructor(){}static getInstance(){if(!X.instance)X.instance=new X;return X.instance}static resetInstance(){X.instance=null}getStoreState(){return q.getState().spec}updateStoreState(z){q.setState((B)=>({spec:{...B.spec,...z}}))}async initialize(z){if(this.fileManager){Z.debug("SpecManager already initialized, skipping...");return}this.fileManager=new E(z),await this.fileManager.initializeDirectories();let B=await this.fileManager.readSteeringContext();this.updateStoreState({steeringContext:B}),Z.debug("SpecManager initialized successfully")}getFileManager(){if(!this.fileManager)throw Error("SpecManager not initialized. Call initialize() first.");return this.fileManager}getState(){return{...this.getStoreState()}}getCurrentSpec(){return this.getStoreState().currentSpec}isActive(){return this.getStoreState().isActive}getSteeringContext(){return this.getStoreState().steeringContext}async getSteeringContextString(){let z=this.getStoreState().steeringContext;if(!z)return null;let B=[];if(z.constitution)B.push(`## Constitution (Project Governance)
|
|
2
2
|
|
|
3
3
|
${z.constitution}`);if(z.product)B.push(`## Product Vision
|
|
4
4
|
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{Y as O}from"./chunk-
|
|
1
|
+
import{Y as O}from"./chunk-yz1nbhxn.js";import"./chunk-qv3wcc4p.js";import{Ea as J,Ga as L}from"./chunk-6c5v0yas.js";import"./chunk-t1ex4e6g.js";import"./chunk-50qc4e5g.js";import{Eb as H}from"./chunk-wre40mf1.js";import"./chunk-ktag2d1c.js";import"./chunk-s53zeref.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 字符串添加服务器
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import{realpathSync as G}from"fs";import{cwd as K}from"process";var D=null;function N(){let q="";if(typeof process<"u"&&typeof process.cwd==="function"&&typeof G==="function"){let F=K();try{q=G(F).normalize("NFC")}catch{q=F.normalize("NFC")}}return{cwd:q,originalCwd:q,projectRoot:q}}function B(){if(!D)D=N();return D}function H(){return B().cwd}function Z(q){B().cwd=q.normalize("NFC")}function J(){return B().originalCwd}function $(){return B().projectRoot}function b(q){B().projectRoot=q.normalize("NFC")}var Q;((x)=>{x.DEFAULT="default";x.AUTO_EDIT="autoEdit";x.YOLO="yolo";x.PLAN="plan";x.SPEC="spec"})(Q||={});import{AsyncLocalStorage as R}from"async_hooks";var U=new R;function V(){return U.getStore()??H()}function W(){try{return V()}catch{return J()}}
|
|
2
|
-
export{Z as
|
|
2
|
+
export{Z as zb,J as Ab,$ as Bb,b as Cb,Q as Db,W as Eb};
|
|
@@ -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-
|
|
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-ekfmr2cb.js";import{Y as M}from"./chunk-yz1nbhxn.js";import"./chunk-dr1bb8ya.js";import"./chunk-qv3wcc4p.js";import"./chunk-vwcjwzw3.js";import{za as y}from"./chunk-6c5v0yas.js";import"./chunk-t1ex4e6g.js";import{Za as O}from"./chunk-e5ngx3x1.js";import"./chunk-50qc4e5g.js";import"./chunk-3w1zqywq.js";import"./chunk-v0z4bwcv.js";import{Eb as D}from"./chunk-wre40mf1.js";import{Ib as W}from"./chunk-ktag2d1c.js";import"./chunk-s53zeref.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{ba as S,ca as h}from"./chunk-
|
|
1
|
+
import{ba as S,ca as h}from"./chunk-qv3wcc4p.js";import{rb as M}from"./chunk-50qc4e5g.js";import{Kb as c}from"./chunk-s53zeref.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,2 +1,2 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{Kb as y}from"./chunk-s53zeref.js";import*as j from"fs/promises";import*as $ from"path";import b from"semver";import{fileURLToPath as N}from"url";import{ProxyAgent as G,fetch as H}from"undici";function T(){return process.env.HTTPS_PROXY||process.env.HTTP_PROXY||process.env.https_proxy||process.env.http_proxy}function R(){let q=T();if(q)try{return new G(q)}catch(z){console.warn(`[proxyFetch] Invalid proxy URL: ${q}`)}return}async function K(q,z={}){let{timeout:W=30000,signal:Q,...B}=z;if(Q?.aborted)throw new DOMException("The operation was aborted.","AbortError");let J=R(),X=new AbortController,Y=!1,F=setTimeout(()=>{Y=!0,X.abort()},W),w=()=>X.abort();Q?.addEventListener("abort",w);try{let Z={method:B.method,headers:B.headers,body:B.body,signal:X.signal,dispatcher:J};return await H(q.toString(),Z)}catch(Z){if(Z instanceof Error&&Z.name==="AbortError"){if(Y)throw Error(`Request timeout after ${W}ms`);throw Z}throw Z}finally{clearTimeout(F),Q?.removeEventListener("abort",w)}}var D="blade-code",f="https://cdn.jsdelivr.net/npm/blade-code@latest/CHANGELOG.md",M=$.join(process.env.HOME||process.env.USERPROFILE||".",".blade"),S=$.join(M,"version-cache.json"),k=3600000,L=`https://registry.npmjs.org/${D}/latest`;async function x(){try{if(process.env.BLADE_VERSION)return process.env.BLADE_VERSION;let q=N(import.meta.url),z=$.dirname(q),W=[$.join(z,"..","..","package.json"),$.join(z,"..","package.json")];for(let Q of W)try{let B=await j.readFile(Q,"utf-8"),J=JSON.parse(B);if(J.name===D&&J.version)return J.version}catch{}return"unknown"}catch{return"unknown"}}async function I(){try{let q=await j.readFile(S,"utf-8"),z=JSON.parse(q);if(Date.now()-z.checkedAt<k)return z;return{...z,checkedAt:0}}catch{return null}}async function O(q){try{await j.mkdir(M,{recursive:!0,mode:493}),await j.writeFile(S,JSON.stringify(q,null,2))}catch{}}async function P(){try{let q=await K(L,{timeout:5000,headers:{Accept:"application/json"}});if(!q.ok)return null;return(await q.json()).version||null}catch{return null}}async function v(q=!1){let z=await x(),W=f;if(z==="unknown")return{currentVersion:z,latestVersion:null,hasUpdate:!1,shouldPrompt:!1,releaseNotesUrl:W,error:"Unable to determine current version"};let Q=await I(),B=Q?.skipUntilVersion,J=null;if(!q&&Q&&Q.checkedAt>0)J=Q.latestVersion;else if(J=await P(),J)await O({latestVersion:J,checkedAt:Date.now(),skipUntilVersion:B});if(!J)return{currentVersion:z,latestVersion:null,hasUpdate:!1,shouldPrompt:!1,releaseNotesUrl:W,error:"Unable to check for updates"};let X=b.gt(J,z),Y=X;if(X&&B)Y=b.gt(J,B);return{currentVersion:z,latestVersion:J,hasUpdate:X,shouldPrompt:Y,releaseNotesUrl:W}}async function u(q){let z=await I();await O({latestVersion:z?.latestVersion||q,checkedAt:z?.checkedAt||Date.now(),skipUntilVersion:q})}function g(){return`npm install -g ${D}@latest --registry https://registry.npmjs.org`}async function C(){let{spawn:q}=await import("child_process");return new Promise((z)=>{let W=g(),Q=q(W,{stdio:"inherit",shell:!0});Q.on("close",(B)=>{if(B===0)z({success:!0,message:"Upgrade successful! Please restart blade."});else z({success:!1,message:`Upgrade failed (exit code: ${B})`})}),Q.on("error",(B)=>{z({success:!1,message:`Upgrade failed: ${B.message}`})})})}async function d(){try{let q=await v();return q.shouldPrompt?q:null}catch{return null}}
|
|
2
2
|
export{v as g,u as h,g as i,C as j,d as k};
|
package/package.json
CHANGED
package/dist/chunk-bx4d9898.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{ga as a}from"./chunk-68ctb04g.js";import"./chunk-x9zj0r7s.js";import"./chunk-mz6n4w13.js";import"./chunk-7ycmx7c2.js";import"./chunk-set7v1rf.js";import"./chunk-j2ag7hh6.js";export{a as SpecManager};
|
package/dist/chunk-c7rvs5ev.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
var e={name:"blade-code",version:"0.5.19",private:!1,description:"🗡️ Blade Code - 智能代码助手命令行工具",type:"module",bin:{blade:"dist/blade.js"},files:["dist","vendor/ripgrep/**","README.md"],scripts:{dev:"node scripts/run-bun.js --watch src/blade.tsx","dev:serve":"node scripts/run-bun.js --watch src/blade.tsx serve --port 4097",build:"rm -rf dist && node scripts/run-bun.js run scripts/build.ts",start:"node scripts/run-bun.js run dist/blade.js",test:"node scripts/test.js","test:all":"vitest run --config vitest.config.ts","test:unit":"node scripts/test.js unit","test:integration":"node scripts/test.js integration","test:cli":"node scripts/test.js cli","test:headless-core":"node scripts/test.js headlessCore","test:e2e":"node scripts/test.js e2e","test:performance":"node scripts/test.js performance","test:snapshot":"node scripts/test.js snapshot","test:security":"node scripts/test.js security","test:coverage":"node scripts/test.js all --coverage","test:watch":"vitest --watch --config vitest.config.ts","benchmark:repo":"node scripts/run-bun.js run scripts/run-real-repo-benchmark.ts","test:update-snapshots":"node scripts/test.js snapshot --update",lint:"biome lint src tests","lint:fix":"biome lint --write src tests","type-check":"tsc --noEmit","format:check":"biome format src tests",ready:"node scripts/run-bun.js run scripts/ready.ts","detect-unused":"node scripts/run-bun.js run scripts/detect-unused.ts",release:"node scripts/release.js","release:dry":"node scripts/release.js --dry-run","release:major":"node scripts/release.js --major","release:minor":"node scripts/release.js --minor","release:patch":"node scripts/release.js --patch"},keywords:["cli","blade","ai","assistant","agent","llm"],author:"echoVic",license:"MIT",engines:{node:">=20.0.0"},optionalDependencies:{"@vscode/ripgrep":"^1.17.0","bun-pty":"^0.4.8","node-pty":"1.0.0"},dependencies:{"@agentclientprotocol/sdk":"^0.12.0","@ai-sdk/anthropic":"^3.0.7","@ai-sdk/azure":"^3.0.5","@ai-sdk/deepseek":"^2.0.4","@ai-sdk/google":"^3.0.4","@ai-sdk/openai":"^3.0.26","@ai-sdk/openai-compatible":"^2.0.4","@inkjs/ui":"^2.0.0","@modelcontextprotocol/sdk":"^1.17.4",ahooks:"^3.9.6",ai:"^6.0.39","ansi-escapes":"^7.2.0","async-mutex":"^0.5.0",axios:"^1.12.2",chalk:"^5.4.1",diff:"^8.0.2","fast-glob":"^3.3.3","fuse.js":"^7.1.0","gray-matter":"^4.0.3",hono:"^4.7.10",ink:"npm:@jrichman/ink@6.4.10","ink-big-text":"^2.0.0","ink-gradient":"^3.0.0","ink-select-input":"^6.2.0","ink-spinner":"^5.0.0","ink-text-input":"^6.0.0","js-tiktoken":"^1.0.21","lodash-es":"^4.17.21",lowlight:"^3.3.0","lru-cache":"^11.2.4",nanoid:"^5.1.6",open:"^10.1.2",openai:"^6.2.0",picomatch:"^4.0.3",react:"^19.1.1","react-dom":"^19.1.1",semver:"^7.7.3","string-width":"^8.1.0",undici:"^7.16.0","write-file-atomic":"^7.0.0",ws:"^8.18.0",yaml:"^2.8.1",yargs:"^18.0.0",zod:"^3.24.2","zod-to-json-schema":"^3.24.6",zustand:"^5.0.9"},devDependencies:{"@biomejs/biome":"^2.2.4","@types/bun":"^1.3.4","@types/json-schema":"^7.0.15","@types/lodash-es":"^4.17.12","@types/node":"^22.15.24","@types/picomatch":"^4.0.2","@types/react":"^19.1.1","@types/react-dom":"^19.1.1","@types/semver":"^7.7.1","@types/write-file-atomic":"^4.0.3","@types/ws":"^8.5.12","@types/yargs":"^17.0.33","@vitest/coverage-v8":"^3.0.0",jsdom:"^26.0.0",typescript:"^5.9.2",vitest:"^3.0.0"}};function r(){return{name:e.name,version:e.version,description:e.description}}function n(){return e.version}function o(){return e.name}function c(){return e.description}function d(){return`v${e.version}`}function a(){return`v${e.version} © 2025 Blade Code`}
|
|
2
|
-
export{r as aa,n as ba,o as ca,c as da,d as ea,a as fa};
|
package/dist/chunk-fe7g701v.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{v as a,w as b,x as c}from"./chunk-5mqvwzj8.js";import"./chunk-x9zj0r7s.js";import"./chunk-mz6n4w13.js";import"./chunk-7ycmx7c2.js";import"./chunk-set7v1rf.js";import"./chunk-j2ag7hh6.js";export{a as validatePermissions,c as validateOutput,b as loadConfiguration};
|
package/dist/chunk-mxrre2n3.js
DELETED
|
@@ -1,24 +0,0 @@
|
|
|
1
|
-
import{sb as $,xb as A}from"./chunk-7ycmx7c2.js";import{execSync as I}from"child_process";import{existsSync as Q,realpathSync as L}from"fs";import{basename as _,isAbsolute as F,resolve as T}from"path";import*as U from"os";import*as H from"path";function J(){let B=A(),q=O(B);return{workingDirectory:B,projectRoot:q,platform:`${U.platform()} (${U.arch()})`,nodeVersion:process.version,currentDate:new Date().toISOString().split("T")[0],homeDirectory:U.homedir()}}function V(B,q){try{return I(q,{cwd:B,encoding:"utf8",stdio:["pipe","pipe","ignore"]}).trim()}catch{return null}}function G(B={}){let{includeGitSnapshot:q=!0,includeDirectoryListing:M=!0}=B,z=J(),W=Q(H.join(z.projectRoot,".git")),E=_(process.env.SHELL||"unknown"),X=["package.json","tsconfig.json","BLADE.md",".env.example"].filter((K)=>Q(H.join(z.projectRoot,K))).map((K)=>`- \`${H.join(z.projectRoot,K)}\``),N=`# Environment
|
|
2
|
-
You have been invoked in the following environment:
|
|
3
|
-
- Primary working directory: ${z.workingDirectory}
|
|
4
|
-
- Is a git repository: ${W?"true":"false"}
|
|
5
|
-
- Platform: ${z.platform}
|
|
6
|
-
- Shell: ${E}
|
|
7
|
-
- Node.js: ${z.nodeVersion}`;if(q&&W){let K=V(z.projectRoot,"git rev-parse --abbrev-ref HEAD"),Y=V(z.projectRoot,"git status --short"),Z=V(z.projectRoot,"git log --oneline -n 3");if(K)N+=`
|
|
8
|
-
- Current branch: ${K}`;if(Y)N+=`
|
|
9
|
-
|
|
10
|
-
Working tree status:
|
|
11
|
-
${Y}`;if(Z)N+=`
|
|
12
|
-
|
|
13
|
-
Recent commits:
|
|
14
|
-
${Z}`}if(N+=`
|
|
15
|
-
|
|
16
|
-
When using file tools (read, write, edit), provide absolute paths based on: \`${z.workingDirectory}/\``,X.length>0)N+=`
|
|
17
|
-
|
|
18
|
-
Key project files at root for quick reference:
|
|
19
|
-
${X.join(`
|
|
20
|
-
`)}`;if(M){let K=V(z.projectRoot,"ls -1 | head -30");if(K)N+=`
|
|
21
|
-
|
|
22
|
-
Project root directory listing:
|
|
23
|
-
${K}`}return N}function O(B){let q=B,M=null;while(q!==H.dirname(q)){if(Q(H.join(q,".git")))return q;if(Q(H.join(q,".blade")))return q;if(Q(H.join(q,".claude")))return q;if(!M&&Q(H.join(q,"package.json")))M=q;q=H.dirname(q)}return M??B}function P(B,q){let M=F(B)?B:T(q||process.cwd(),B),z;try{z=L(M)}catch{z=M}$(z)}
|
|
24
|
-
export{G as Z,O as _,P as $};
|
package/dist/chunk-th432d0b.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{g as a,h as b,i as c,j as d,k as e}from"./chunk-qwfywxs2.js";import"./chunk-j2ag7hh6.js";export{b as setSkipUntilVersion,d as performUpgrade,c as getUpgradeCommand,e as checkVersionOnStartup,a as checkVersion};
|
package/dist/chunk-z4ds84bg.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{t as a,u as b}from"./chunk-7gje20de.js";import"./chunk-c7rvs5ev.js";import"./chunk-j2ag7hh6.js";export{a as globalOptions,b as cliConfig};
|
package/dist/chunk-zh3ndtvg.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{rb as a}from"./chunk-37rethcy.js";import"./chunk-set7v1rf.js";import"./chunk-j2ag7hh6.js";export{a as createChatServiceAsync};
|