blade-code 0.7.4 → 0.7.5
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-byxazdwv.js → chunk-0rw4tdqy.js} +1 -1
- package/dist/{chunk-3mhbped9.js → chunk-7pcm8vy5.js} +35 -35
- package/dist/{chunk-n5rg9dbv.js → chunk-8ea9h3mb.js} +1 -1
- package/dist/{chunk-6rszb7xd.js → chunk-8w1hd9ct.js} +255 -255
- package/dist/{chunk-7mnefph6.js → chunk-a8znntss.js} +1 -1
- package/dist/{chunk-pa364yr9.js → chunk-apb1p5q4.js} +1 -1
- package/dist/{chunk-erpgkabk.js → chunk-ay3rhhx8.js} +1 -1
- package/dist/{chunk-egavbybx.js → chunk-c3yn8ds8.js} +1 -1
- package/dist/{chunk-jpry8h07.js → chunk-g1eb7f4q.js} +1 -1
- package/dist/{chunk-501my8nh.js → chunk-jfykets9.js} +1 -1
- package/dist/{chunk-4e2fzyf2.js → chunk-jsn8476q.js} +1 -1
- package/dist/chunk-kssr4fbg.js +1 -0
- package/dist/{chunk-b1d49byc.js → chunk-n969rv4v.js} +1 -1
- package/dist/{chunk-ctbhcw8h.js → chunk-vhc1yr3v.js} +1 -1
- package/dist/{chunk-by93yn92.js → chunk-yaj4nmmp.js} +1 -1
- package/dist/{chunk-z7x21493.js → chunk-yz2jztga.js} +1 -1
- package/dist/chunk-zye2s6f0.js +2 -0
- package/package.json +1 -1
- package/dist/chunk-dftaxwg9.js +0 -1
- package/dist/chunk-gzc9n5d6.js +0 -2
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{Ea as S,Fa as h}from"./chunk-
|
|
1
|
+
import{Ea as S,Fa as h}from"./chunk-jsn8476q.js";import{kb as M}from"./chunk-cyxb6fxe.js";import{Nb as c}from"./chunk-kfg3vx5z.js";import{EventEmitter as r}from"events";import{z as L}from"zod";import{isPlainObject as p}from"lodash-es";function J(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`类型错误:期望 ${J(Y)},实际收到 ${J(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(p(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(($)=>J($)).join(", ")}`;return"必须是枚举允许的值之一"}case"invalid_literal":{let Y=Q.expected;return`必须是字面量值:${J(Y)}`}case"unrecognized_keys":{let Y=Q.keys;if(Array.isArray(Y))return`包含未知的参数:${Y.map(($)=>J($)).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 +1 @@
|
|
|
1
|
-
import{Da as a,Ea as b,Fa as c,Ga as d,Ha as e,Ia as f}from"./chunk-
|
|
1
|
+
import{Da as a,Ea as b,Fa as c,Ga as d,Ha as e,Ia as f}from"./chunk-jsn8476q.js";import"./chunk-kfg3vx5z.js";export{b as getVersion,c as getPackageName,a as getPackageInfo,e as getFormattedVersion,d as getDescription,f as getCopyright};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{_ as O}from"./chunk-
|
|
1
|
+
import{_ as O}from"./chunk-a8znntss.js";import{wa as J,ya as L}from"./chunk-5smacbk0.js";import"./chunk-rkhhzc4r.js";import"./chunk-jsn8476q.js";import"./chunk-cyxb6fxe.js";import{tb as H}from"./chunk-63dzf6hr.js";import"./chunk-w1zb8zac.js";import"./chunk-kfg3vx5z.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,4 +1,4 @@
|
|
|
1
|
-
import{p,q as d,r as u,s as m}from"./chunk-
|
|
1
|
+
import{p,q as d,r as u,s as m}from"./chunk-yaj4nmmp.js";import{t as c}from"./chunk-n969rv4v.js";import{v as z,w as g,x as v}from"./chunk-cw125vv3.js";import{y as h}from"./chunk-k4behavv.js";import{H as y,J as C,K as E,M as W,N as S}from"./chunk-8w1hd9ct.js";import"./chunk-e21htmg4.js";import"./chunk-a8znntss.js";import"./chunk-rtn0rb16.js";import"./chunk-5smacbk0.js";import"./chunk-rkhhzc4r.js";import"./chunk-jsn8476q.js";import{Va as F}from"./chunk-7pcm8vy5.js";import"./chunk-cyxb6fxe.js";import"./chunk-jf48kahn.js";import{sb as w,tb as L}from"./chunk-63dzf6hr.js";import"./chunk-98jpdmgc.js";import"./chunk-w1zb8zac.js";import"./chunk-kfg3vx5z.js";import bq from"yargs";import{hideBin as Dq}from"yargs/helpers";import{z as $}from"zod";import{z as Q}from"zod";var k=1,D=Q.object({event_version:Q.literal(k)}),o=D.extend({type:Q.literal("content_delta"),delta:Q.string()}),a=D.extend({type:Q.literal("thinking_delta"),delta:Q.string()}),e=D.extend({type:Q.literal("thinking"),content:Q.string()}),t=D.extend({type:Q.literal("stream_end")}),qq=D.extend({type:Q.literal("content"),content:Q.string()}),Gq=D.extend({type:Q.literal("tool_start"),tool_name:Q.string(),summary:Q.string(),target:Q.string().optional(),tool_kind:Q.enum(["readonly","write","execute"]).optional()}),Qq=D.extend({type:Q.literal("tool_result"),tool_name:Q.string(),summary:Q.string(),target:Q.string().optional(),tool_kind:Q.enum(["readonly","write","execute"]).optional(),success:Q.boolean().optional(),error_type:Q.string().optional(),error_message:Q.string().optional()}),Xq=D.extend({type:Q.literal("phase"),phase:Q.enum(["turn","searching","inspecting","target_hit","executing","completed"]),status:Q.enum(["ongoing","hit","done"]),message:Q.string(),turn:Q.number().optional(),tool_name:Q.string().optional(),target:Q.string().optional()}),Yq=D.extend({type:Q.literal("tool_detail"),tool_name:Q.string(),detail:Q.string()}),Zq=D.extend({type:Q.literal("task_update"),tasks:Q.array(W)}),$q=D.extend({type:Q.literal("token_usage"),input_tokens:Q.number(),output_tokens:Q.number(),total_tokens:Q.number(),max_context_tokens:Q.number()}),Uq=D.extend({type:Q.literal("compacting"),state:Q.enum(["started","completed"])}),Kq=D.extend({type:Q.literal("turn_limit"),turns_count:Q.number(),action:Q.literal("continue")}),Vq=D.extend({type:Q.literal("output"),content:Q.string(),exit_code:Q.number()}),_q=D.extend({type:Q.literal("error"),message:Q.string()}),Tq=Q.discriminatedUnion("type",[o,a,e,t,qq,Gq,Qq,Xq,Yq,Zq,$q,Uq,Kq,Vq,_q]);function H(G,Y){return{event_version:k,type:G,...Y}}function Aq(G){if(G?.signal)return{signal:G.signal,dispose:()=>{return}};let Y=new AbortController,Z=()=>Y.abort("interrupt");return process.once("SIGINT",Z),process.once("SIGTERM",Z),{signal:Y.signal,dispose:()=>{process.removeListener("SIGINT",Z),process.removeListener("SIGTERM",Z)}}}var Mq=$.enum(["text","jsonl"]),Rq=$.object({headless:$.boolean().optional(),message:$.string().optional(),_:$.array($.union([$.string(),$.number()])).optional(),model:$.string().optional(),systemPrompt:$.string().optional(),appendSystemPrompt:$.string().optional(),maxTurns:$.number().int().refine((G)=>G===-1||G>0,{message:"must be -1 or a positive integer"}).optional(),permissionMode:$.nativeEnum(w).optional(),mcpConfig:$.array($.string()).optional(),strictMcpConfig:$.boolean().optional(),sessionId:$.string().optional(),allowedTools:$.array($.string()).optional(),disallowedTools:$.array($.string()).optional(),agents:$.string().optional(),continue:$.boolean().optional(),resume:$.union([$.string(),$.boolean()]).optional(),forkSession:$.boolean().optional(),outputFormat:Mq.optional()});class l{openedThinking=!1;wroteAssistantContent=!1;markAssistantContent(){this.wroteAssistantContent=!0}setThinkingOpened(G){this.openedThinking=G}hasOpenThinking(){return this.openedThinking}completeStream(){let G={openedThinking:this.openedThinking,wroteAssistantContent:this.wroteAssistantContent};return this.openedThinking=!1,this.wroteAssistantContent=!1,G}}function jq(G){return G.issues.map((Y)=>`${Y.path.join(".")||"options"}: ${Y.message}`).join("; ")}function fq(G){let Y=Rq.safeParse(G);if(!Y.success)throw Error(`Invalid headless options: ${jq(Y.error)}`);return Y.data}function Bq(G){return G.command("* [message]","Run full agent loop without Ink UI and print events to the terminal",(Y)=>Y.positional("message",{describe:"Message to process",type:"string"}).option("headless",{type:"boolean",describe:"Run full agent loop without Ink UI and print events to the terminal"}).option("model",{describe:"Model ID for this run",type:"string"}).option("system-prompt",{describe:"Replace the default system prompt",type:"string"}).option("append-system-prompt",{describe:"Append a system prompt to the default system prompt",type:"string"}).option("max-turns",{alias:["maxTurns"],describe:"Maximum conversation turns (-1: unlimited, N>0: limit to N turns)",type:"number"}).option("output-format",{alias:["outputFormat"],choices:["text","jsonl"],describe:"Headless output format",type:"string"}),async(Y)=>{if(!Y.headless)return;let Z=await Nq(Y);process.exit(Z)})}function A(G,Y=""){G.write(`${Y}
|
|
2
2
|
`)}function Iq(G){return`[task] [${G.status}] ${G.subject}`}function Jq(){return{requestConfirmation:async(G)=>({approved:!0,reason:"headless-auto-approved",scope:"session"})}}function xq(G){if(!(G instanceof Error))return"Unknown error";let q=G.lastError??G;if(q.responseBody)try{let V=JSON.parse(q.responseBody)?.error?.message;if(V)return q.statusCode?`${V} (HTTP ${q.statusCode})`:V}catch{}let X=G.message.match(/Last error:\s*(.+)$/);if(X)return X[1];return G.message}function Pq(G){return G==="jsonl"?"jsonl":"text"}function T(G,Y){let Z=(...q)=>{for(let X of q){let _=Y[X];if(typeof _==="string"&&_.trim()!=="")return _}return};switch(G){case"Read":case"Edit":case"Write":case"UndoEdit":return Z("file_path");case"NotebookEdit":return Z("notebook_path");case"Grep":return Z("path","pattern");case"Glob":return Z("pattern");case"WebFetch":return Z("url");case"WebSearch":return Z("query");case"Bash":return Z("command","description");case"Task":return Z("description");case"LSP":return Z("filePath","operation");case"EnterWorktree":return Z("name");case"ExitWorktree":return Z("action");default:return}}function Lq(G,Y,Z,q){let X=new Set(["Glob","Grep","WebSearch","LS"]),_=new Set(["Read","WebFetch"]);if(new Set(["Edit","Write","NotebookEdit","Bash","LSP","UndoEdit","EnterWorktree","ExitWorktree"]).has(G)&&!q.targetLocked)return{phase:"target_hit",status:"hit",message:`Target locked: ${Y}`,shouldLockTarget:!0};if(q.targetLocked)return{phase:"executing",status:"hit",message:Z?`Working within target: ${Y}`:`Executing: ${Y}`,shouldLockTarget:!1};if(X.has(G))return{phase:"searching",status:"ongoing",message:`Still searching: ${Y}`,shouldLockTarget:!1};if(_.has(G))return{phase:"inspecting",status:"ongoing",message:`Inspecting candidate: ${Y}`,shouldLockTarget:!1};return{phase:"executing",status:q.targetLocked?"hit":"ongoing",message:`Executing: ${Y}`,shouldLockTarget:!1}}function O(G,Y){let Z=(q,X)=>{G.stdout.write(`${JSON.stringify(H(q,X))}
|
|
3
3
|
`)};return{contentDelta(q){if(Y==="jsonl"){Z("content_delta",{delta:q});return}G.stdout.write(q)},thinkingDelta(q,X){if(Y==="jsonl")return Z("thinking_delta",{delta:q}),X;if(!X)G.stderr.write("[thinking] ");return G.stderr.write(q),!0},thinking(q){if(Y==="jsonl"){Z("thinking",{content:q});return}A(G.stderr,`[thinking] ${q}`)},streamEnd(q,X){if(Y==="jsonl"){Z("stream_end",{});return}if(X)G.stderr.write(`
|
|
4
4
|
`);if(q)G.stdout.write(`
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{$a as l,Pa as a,Qa as b,Sa as c,Ta as d,Ua as e,Va as f,Wa as g,Xa as h,Ya as i,Za as j,_a as k,ab as m,bb as n,cb as o,fb as p,gb as q,hb as r}from"./chunk-
|
|
1
|
+
import{$a as l,Pa as a,Qa as b,Sa as c,Ta as d,Ua as e,Va as f,Wa as g,Xa as h,Ya as i,Za as j,_a as k,ab as m,bb as n,cb as o,fb as p,gb as q,hb as r}from"./chunk-7pcm8vy5.js";import"./chunk-cyxb6fxe.js";import"./chunk-jf48kahn.js";import"./chunk-63dzf6hr.js";import"./chunk-98jpdmgc.js";import"./chunk-w1zb8zac.js";import"./chunk-kfg3vx5z.js";export{g as saveUserMessage,i as saveToolUse,j as saveToolResult,k as saveCompaction,h as saveAssistantMessage,d as isRootSystemPrompt,l as handleTaskListUpdate,m as handleSkillActivation,n as extractModelSwitch,r as executeLoopGenerator,f as drainLoop,c as checkStopHook,a as checkOutputRecovery,b as checkIncompleteIntent,q as checkAndCompactInLoop,o as applyToolDomainEffects,p as StreamingToolExecutor,e as ConversationState};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{p as A,q as E,r as N,s as f}from"./chunk-
|
|
1
|
+
import{p as A,q as E,r as N,s as f}from"./chunk-yaj4nmmp.js";import{t as D}from"./chunk-n969rv4v.js";import{v as L,w as _,x}from"./chunk-cw125vv3.js";import{y as B}from"./chunk-k4behavv.js";import{H as $,N as b}from"./chunk-8w1hd9ct.js";import"./chunk-e21htmg4.js";import"./chunk-a8znntss.js";import"./chunk-rtn0rb16.js";import"./chunk-5smacbk0.js";import"./chunk-rkhhzc4r.js";import"./chunk-jsn8476q.js";import{Va as Z}from"./chunk-7pcm8vy5.js";import"./chunk-cyxb6fxe.js";import"./chunk-jf48kahn.js";import{sb as Y,tb as T}from"./chunk-63dzf6hr.js";import"./chunk-98jpdmgc.js";import"./chunk-w1zb8zac.js";import"./chunk-kfg3vx5z.js";import h from"yargs";import{hideBin as R}from"yargs/helpers";var w=new Set(Object.values(Y));function X(k){if(k&&w.has(k))return k;return}function M(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 O(F);process.exit(q)})}async function O(k,F=process){let q;try{await A();let J=await E({message:k.message,_:k._,defaultMessage:"Hello"}),G=await N(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:U}=await f({sessionId:k.sessionId,continue:k.continue,resume:k.resume,forkSession:k.forkSession,fallbackSessionPrefix:"print"});q=await $.create({sessionId:K,workspaceRoot:T(),modelId:k.model,mcpConfig:k.mcpConfig,strictMcpConfig:k.strictMcpConfig,agents:k.agents?B(k.agents):void 0});let V=await b.createWithRuntime(q,{sessionId:K,systemPrompt:k.systemPrompt,appendSystemPrompt:k.appendSystemPrompt,maxTurns:k.maxTurns,modelId:k.model,permissionMode:X(k.permissionMode),toolWhitelist:k.allowedTools,toolBlacklist:k.disallowedTools,mcpConfig:k.mcpConfig,strictMcpConfig:k.strictMcpConfig}),H=(await Z(V.chatStream(Q,{messages:[...U],userId:"cli-user",sessionId:K,workspaceRoot:T(),permissionMode:X(k.permissionMode)}))).finalMessage||"";if(k.outputFormat==="json")F.stdout.write(`${JSON.stringify({response:H,input:Q,model:k.model,timestamp:new Date().toISOString()},null,2)}
|
|
3
3
|
`);else if(k.outputFormat==="stream-json")F.stdout.write(`${JSON.stringify({type:"response",content:H})}
|
|
4
4
|
`);else F.stdout.write(`${H}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var s={name:"blade-code",version:"0.7.
|
|
1
|
+
var s={name:"blade-code",version:"0.7.5",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:real-api":"node scripts/test.js realApi","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","qualify:local":"node scripts/run-bun.js run scripts/qualify.ts local","qualify:production":"node scripts/run-bun.js run scripts/qualify.ts production","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/qualify.ts production","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","@anthropic-ai/sandbox-runtime":"0.0.67","@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:s.name,version:s.version,description:s.description}}function n(){return s.version}function o(){return s.name}function c(){return s.description}function a(){return`v${s.version}`}function d(){return`v${s.version} © 2025 Blade Code`}
|
|
2
2
|
export{r as Da,n as Ea,o as Fa,c as Ga,a as Ha,d as Ia};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{t as a,u as b}from"./chunk-n969rv4v.js";import"./chunk-jsn8476q.js";import"./chunk-kfg3vx5z.js";export{a as globalOptions,b as cliConfig};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{Ea as d,Ga as h}from"./chunk-
|
|
1
|
+
import{Ea as d,Ga as h}from"./chunk-jsn8476q.js";var q={debug:{alias:"d",type:"string",describe:'Enable debug mode with optional category filtering (e.g., "agent,ui" or "!chat,!loop")',group:"Debug Options:"},model:{type:"string",describe:"Override the current run model using a model config ID (TUI / print / headless)",group:"AI Options:"},print:{alias:"p",type:"boolean",describe:"Print response and exit (useful for pipes)",group:"Output Options:"},headless:{type:"boolean",describe:"Run full agent loop without Ink UI and print all events to the terminal",group:"Output Options:"},"output-format":{alias:["outputFormat"],type:"string",choices:["text","json","stream-json","jsonl"],default:"text",describe:"Output format: --print supports text|json|stream-json; --headless supports text|jsonl",group:"Output Options:"},"include-partial-messages":{alias:["includePartialMessages"],type:"boolean",describe:"Include partial message chunks as they arrive",group:"Output Options:"},"input-format":{alias:["inputFormat"],type:"string",choices:["text","stream-json"],default:"text",describe:"Input format",group:"Input Options:"},"replay-user-messages":{alias:["replayUserMessages"],type:"boolean",describe:"Re-emit user messages from stdin",group:"Input Options:"},"allowed-tools":{alias:["allowedTools"],type:"array",string:!0,describe:"Comma or space-separated list of tool names to allow",group:"Security Options:"},"disallowed-tools":{alias:["disallowedTools"],type:"array",string:!0,describe:"Comma or space-separated list of tool names to deny",group:"Security Options:"},"mcp-config":{alias:["mcpConfig"],type:"array",string:!0,describe:"Load MCP servers from JSON files or strings",group:"MCP Options:"},"system-prompt":{alias:["systemPrompt"],type:"string",describe:"System prompt to use for the session (replaces default)",group:"AI Options:"},"append-system-prompt":{alias:["appendSystemPrompt"],type:"string",describe:"Append a system prompt to the default system prompt",group:"AI Options:"},"max-turns":{alias:["maxTurns"],type:"number",describe:"Maximum conversation turns (-1: unlimited, 0: disable chat, N>0: limit to N turns)",group:"AI Options:",default:void 0},"permission-mode":{alias:["permissionMode"],type:"string",choices:["default","autoEdit","yolo","plan"],describe:"Permission mode (default: ask for non-read tools, autoEdit: auto-approve edits, yolo: auto-approve all, plan: reserved)",group:"Security Options:"},yolo:{type:"boolean",describe:"Auto-approve all tools (shortcut for --permission-mode=yolo)",group:"Security Options:"},continue:{alias:"c",type:"boolean",describe:"Continue the most recent conversation",group:"Session Options:"},resume:{alias:"r",describe:"Resume a conversation - provide a session ID or interactively select a conversation to resume",group:"Session Options:",coerce:(b)=>{if(b===void 0||b===!0||b==="")return"true";return String(b)}},"fork-session":{alias:["forkSession"],type:"boolean",describe:"Create a new session ID when resuming",group:"Session Options:"},settings:{type:"string",describe:"Path to a settings JSON file or JSON string",group:"Configuration:"},"add-dir":{alias:["addDir"],type:"array",string:!0,describe:"Additional directories to allow tool access to",group:"Security Options:"},ide:{type:"boolean",describe:"Automatically connect to IDE on startup",group:"Integration:"},acp:{type:"boolean",describe:"Run in ACP (Agent Client Protocol) mode for IDE integration",group:"Integration:"},"strict-mcp-config":{alias:["strictMcpConfig"],type:"boolean",describe:"Only use MCP servers from --mcp-config",group:"MCP Options:"},"session-id":{alias:["sessionId"],type:"string",describe:"Use a specific session ID for the conversation",group:"Session Options:"},agents:{type:"string",describe:"JSON object defining custom agents",group:"AI Options:"},"setting-sources":{alias:["settingSources"],type:"string",describe:"Comma-separated list of setting sources to load",group:"Configuration:"},"plugin-dir":{alias:["pluginDir"],type:"array",string:!0,describe:"Load plugins from specified directories",group:"Plugin Options:"}},w={scriptName:"blade",usage:"$0 [command] [options]",description:h(),version:d(),locale:"en",showHelpOnFail:!0,demandCommand:!1,recommendCommands:!0,strict:!1};
|
|
2
2
|
export{q as t,w as u};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{f as y,g as A,h as C,i as D}from"./chunk-
|
|
1
|
+
import{f as y,g as A,h as C,i as D}from"./chunk-zye2s6f0.js";import"./chunk-pvxp2gzr.js";import"./chunk-8w1hd9ct.js";import"./chunk-e21htmg4.js";import"./chunk-a8znntss.js";import"./chunk-rtn0rb16.js";import{sa as q}from"./chunk-5smacbk0.js";import"./chunk-rkhhzc4r.js";import"./chunk-jsn8476q.js";import"./chunk-7pcm8vy5.js";import"./chunk-cyxb6fxe.js";import"./chunk-jf48kahn.js";import"./chunk-63dzf6hr.js";import"./chunk-98jpdmgc.js";import"./chunk-w1zb8zac.js";import"./chunk-kfg3vx5z.js";import H from"chalk";var R={command:"serve",describe:"Start a headless Blade server (no browser)",builder:y,handler:async(E)=>{let f=A(E);if(await q(),!process.env.BLADE_SERVER_PASSWORD)console.log(H.yellow("Warning: BLADE_SERVER_PASSWORD is not set; server is unsecured."));let b=await D.listenAsync(f);if(console.log(`Blade server listening on http://${b.hostname}:${b.port}`),f.hostname==="0.0.0.0"){let F=C();for(let G of F)console.log(` Network: http://${G}:${b.port}`)}await new Promise(()=>{}),await b.stop()}};export{R as serveCommand};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{O as c,P as g,Q as m,T as d,V as r}from"./chunk-
|
|
1
|
+
import{O as c,P as g,Q as m,T as d,V as r}from"./chunk-8w1hd9ct.js";import{tb as n}from"./chunk-63dzf6hr.js";async function h(){if((await c().initialize(n(),[])).plugins.length>0)await g()}async function R(e){let t=e.message||e._?.[0];if(typeof t==="string"&&t.trim())return t;let a=e.stdin??process.stdin;if(!a.isTTY){let u=[];for await(let l of a)u.push(l);return Buffer.concat(u).toString("utf-8").trim()}if(e.defaultMessage!==void 0)return e.defaultMessage;throw Error("No input provided")}async function x(e){if(!d(e))return{mode:"agent",content:e};let t=await r(e,{cwd:n(),workspaceRoot:n()});if(!t.success)return{mode:"output",content:`Error: ${t.error||"未知错误"}`,exitCode:1};let a=t.data;if(a?.action==="invoke_skill"){let{skillName:u,skillArgs:l}=a;return{mode:"agent",content:l?`Please use the "${u}" skill to help me with: ${l}`:`Please use the "${u}" skill.`}}if(a?.action==="invoke_custom_command"||a?.action==="invoke_plugin_command"){let u=a.processedContent;return{mode:"agent",content:`# Custom Command: /${a.commandName}
|
|
2
2
|
|
|
3
3
|
${u}`}}return{mode:"output",content:t.content||t.message||"",exitCode:0}}function i(e){if(!(e instanceof Error))return!1;return e.message.includes("未找到会话")||e.message.includes("ENOENT")||e.message.includes("no such file")}async function f(e){try{return await m.loadSession(e,n())}catch(t){if(i(t))return null;throw t}}async function _(e){if(e.resume===!0||e.resume==="true")throw Error("--resume without a session ID is only supported in interactive UI mode");if(typeof e.resume==="string"&&e.resume.length>0){if(e.forkSession)return m.forkSession(e.resume,{newSessionId:e.sessionId,targetProjectPath:n()});return{sessionId:e.resume,messages:await m.loadSession(e.resume)}}if(e.continue){let t=await m.listSessions();if(t.length>0){let a=t[0].sessionId;if(e.forkSession)return m.forkSession(a,{newSessionId:e.sessionId,targetProjectPath:n()});return{sessionId:a,messages:await m.loadSession(a)}}if(e.forkSession)throw Error("Cannot fork: no sessions are available to continue")}if(e.sessionId)return{sessionId:e.sessionId,messages:await f(e.sessionId)??[]};return{sessionId:`${e.fallbackSessionPrefix}-${Date.now()}`,messages:[]}}
|
|
4
4
|
export{h as p,R as q,x as r,_ as s};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{B as W,H as P,K as T,L as R,N as M,Q as B,T as j,V as A,W as h}from"./chunk-
|
|
1
|
+
import{B as W,H as P,K as T,L as R,N as M,Q as B,T as j,V as A,W as h}from"./chunk-8w1hd9ct.js";import"./chunk-e21htmg4.js";import{_ as x}from"./chunk-a8znntss.js";import"./chunk-rtn0rb16.js";import{ra as y}from"./chunk-5smacbk0.js";import"./chunk-rkhhzc4r.js";import"./chunk-jsn8476q.js";import{Va as L}from"./chunk-7pcm8vy5.js";import"./chunk-cyxb6fxe.js";import"./chunk-jf48kahn.js";import{tb as U}from"./chunk-63dzf6hr.js";import"./chunk-98jpdmgc.js";import{Lb as _}from"./chunk-w1zb8zac.js";import"./chunk-kfg3vx5z.js";import{Readable as c,Writable as p}from"node:stream";import*as w from"@agentclientprotocol/sdk";import{PROTOCOL_VERSION as C}from"@agentclientprotocol/sdk";import{nanoid as v}from"nanoid";import{nanoid as k}from"nanoid";var Z=_("Agent");function f(z){return Object.fromEntries(z.map((G)=>[G.name,G.value]))}function S(z){if("command"in z)return{type:"stdio",command:z.command,args:z.args,env:f(z.env)};return{type:z.type,url:z.url,headers:f(z.headers)}}function u(z){return Object.fromEntries(z.map((G)=>[G.name,S(G)]))}function O(z){if(typeof z==="string")return z?[{type:"text",text:z}]:[];return z.flatMap((G)=>{if(G.type==="text")return G.text?[{type:"text",text:G.text}]:[];let H=G.image_url.url,J=/^data:([^;,]+);base64,(.+)$/s.exec(H);if(!J)return[{type:"text",text:"[Image]"}];return[{type:"image",mimeType:J[1]??"image/png",data:J[2]??""}]})}class D{id;cwd;connection;clientCapabilities;options;agent=null;runtime=null;pendingPrompt=null;pendingResumeRequested=!1;messages;mode="default";sessionApprovals=new Set;constructor(z,G,H,J,Q={}){this.id=z;this.cwd=G;this.connection=H;this.clientCapabilities=J;this.options=Q;this.messages=[...Q.initialMessages??[]]}async initialize(){Z.debug(`[AcpSession ${this.id}] Initializing...`),W.initializeSession(this.connection,this.id,this.clientCapabilities,this.cwd),Z.debug(`[AcpSession ${this.id}] ACP service context initialized`);let z=this.options.mcpServers?u(this.options.mcpServers):void 0;if(this.runtime=await P.create({sessionId:this.id,workspaceRoot:this.cwd,...z?{mcpServers:z}:{}}),this.agent=await M.createWithRuntime(this.runtime,{sessionId:this.id}),Z.debug(`[AcpSession ${this.id}] Agent created successfully`),this.runtime.getPendingSteeringCount()>0)if(this.options.initialMessages===void 0)this.schedulePendingResume();else this.pendingResumeRequested=!0}async replayHistory(){for(let z of this.messages){let G=z.role==="user"?"user_message_chunk":z.role==="assistant"?"agent_message_chunk":void 0;if(!G)continue;for(let H of O(z.content))await this.connection.sessionUpdate({sessionId:this.id,update:{sessionUpdate:G,content:H}})}if(this.pendingResumeRequested)this.schedulePendingResume()}sendAvailableCommandsDelayed(){Z.debug(`[AcpSession ${this.id}] Scheduling available commands update (500ms delay)`),setTimeout(()=>{this.sendAvailableCommands()},500)}async handleSlashCommand(z,G){try{Z.debug(`[AcpSession ${this.id}] Executing slash command: ${z}`);let H={cwd:this.cwd,signal:G,acp:{sendMessage:(X)=>{this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:X}})},sendToolStart:(X,Y,E)=>{let F=`tool_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,$=this.mapToolKind(E);this.sendUpdate({sessionUpdate:"tool_call",toolCallId:F,status:"in_progress",title:`${X}`,content:[{type:"content",content:{type:"text",text:JSON.stringify(Y,null,2)}}],kind:$})},sendToolResult:(X,Y)=>{if(Y.summary)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:Y.summary}})}}},J=await A(z,H),Q=J.content||J.message;if(Q)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:Q}});if(J.error)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[FAIL] ${J.error}`}});return{stopReason:J.success?"end_turn":"cancelled"}}catch(H){return Z.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=h(),G=["model","permissions","theme","config","exit","ide"],J=z.filter((Q)=>!G.includes(Q.name)).map((Q)=>{let X;if(Q.usage){let Y=Q.usage.replace(/^\/\w+\s*/,"").trim();if(Y)X=Y}if(Q.aliases?.length){let Y=`Aliases: ${Q.aliases.join(", ")}`;X=X?`${X} | ${Y}`:Y}return{name:Q.name,description:Q.description,input:X?{hint:X}:void 0}});Z.info(`[AcpSession ${this.id}] Sending available commands: ${JSON.stringify(J.map((Q)=>Q.name))}`),this.sendUpdate({sessionUpdate:"available_commands_update",availableCommands:J}),Z.info(`[AcpSession ${this.id}] Sent ${J.length} available commands`)}catch(z){Z.error(`[AcpSession ${this.id}] Failed to send available commands:`,z)}}async prompt(z,G={}){if(W.setCurrentSession(this.id),!this.agent||!this.runtime)throw Error("Session not initialized");let H=this.resolvePrompt(z.prompt);if(this.pendingPrompt){let Q=await this.runtime.enqueueSteering(H,{allowBeforeTurn:!0});if(!Q.accepted)throw Error(Q.reason==="queue_full"?"Active turn steering queue is full":"Active turn is no longer steerable");if(Z.debug(`[AcpSession ${this.id}] Queued steering for active turn (${Q.queued})`),Q.delivery==="next_turn")this.schedulePendingResume();return{stopReason:"end_turn"}}let J=new AbortController;this.pendingPrompt=J;try{if(Z.debug(`[AcpSession ${this.id}] Received prompt: ${H.slice(0,100)}...`),j(H))return await this.handleSlashCommand(H,J.signal);let Q={sessionId:this.id,userId:"acp-user",workspaceRoot:this.cwd,messages:[...this.messages],signal:J.signal,permissionMode:this.mapModeToPermissionMode(),confirmationHandler:{requestConfirmation:async(X)=>{return this.requestPermission(X)}}};if(await L(this.agent.chatStream(H,Q,{pendingInputOnly:G.pendingInputOnly}),async(X)=>{switch(X.kind){case"content_delta":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:X.delta}});break;case"thinking_delta":this.sendUpdate({sessionUpdate:"agent_thought_chunk",content:{type:"text",text:X.delta}});break;case"tool_start":{let Y=X.toolCall,E="function"in Y?Y.function.name:Y.type,F=this.mapToolKind(X.toolKind);this.sendUpdate({sessionUpdate:"tool_call",toolCallId:Y.id,status:"in_progress",title:`Executing ${E}`,content:[],kind:F});break}case"tool_result":{let{toolCall:Y,result:E}=X,F=[],$=E.metadata;if($?.kind==="edit"&&typeof $.file_path==="string"&&typeof $.oldContent==="string"&&(typeof $.newContent==="string"||$.newContent===void 0))F.push({type:"diff",path:$.file_path,oldText:$.oldContent,newText:$.newContent??null});else{let I="function"in Y?Y.function.name:Y.type,K=R(T(I,E));F.push({type:"content",content:{type:"text",text:K}})}let V=E.success?"completed":"failed";this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:Y.id,status:V,content:F});break}case"task_update":this.sendPlanUpdate(X.tasks);break;case"steering_applied":break;case"follow_up_started":for(let Y of X.messages){if(!Y.recovered||Y.persisted)continue;for(let E of O(Y.content))this.sendUpdate({sessionUpdate:"user_message_chunk",content:E})}if(X.recovered>0)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[Resuming ${X.recovered} queued instruction${X.recovered===1?"":"s"} recovered after restart]
|
|
2
2
|
`}});break;default:break}}),this.messages=[...Q.messages],J.signal.aborted)return{stopReason:"cancelled"};return{stopReason:"end_turn"}}catch(Q){if(J.signal.aborted||Q instanceof Error&&Q.name==="AbortError")return{stopReason:"cancelled"};throw Z.error(`[AcpSession ${this.id}] Prompt error:`,Q),Q}finally{if(this.pendingPrompt===J){if(this.pendingPrompt=null,this.pendingResumeRequested)this.schedulePendingResume()}}}schedulePendingResume(){this.pendingResumeRequested=!0,queueMicrotask(()=>{this.resumePendingIfIdle()})}async resumePendingIfIdle(){if(this.pendingPrompt||!this.runtime||!this.agent)return;if(this.runtime.getPendingSteeringCount()===0){this.pendingResumeRequested=!1;return}this.pendingResumeRequested=!1,await this.prompt({sessionId:this.id,prompt:[]},{pendingInputOnly:!0}).catch((z)=>{Z.error(`[AcpSession ${this.id}] Failed to resume pending input:`,z)})}cancel(){if(Z.info(`[AcpSession ${this.id}] Cancel requested`),this.pendingResumeRequested=!1,this.pendingPrompt)this.pendingPrompt.abort(),this.pendingPrompt=null,Z.info(`[AcpSession ${this.id}] Cancelled successfully`);else Z.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",Z.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(Z.info(`[AcpSession ${this.id}] Model set to: ${z}`),this.pendingPrompt)throw Error("Cannot switch models while a prompt is active");if(!this.agent)throw Error("Session not initialized");await this.agent.switchModel(z)}async destroy(){if(this.cancel(),this.agent)await this.agent.destroy(),this.agent=null;if(this.runtime)await this.runtime.dispose(),this.runtime=null;W.destroySession(this.id),Z.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 J=H.resource;if("text"in J)G.push(`<file path="${J.uri}">
|
|
3
3
|
${J.text}
|
|
4
4
|
</file>`)}else if(H.type==="resource_link")G.push(`[Resource: ${H.uri}]`);return G.join(`
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{j as mf,k as kf}from"./chunk-pvxp2gzr.js";import{A as uf,C as Zf,D as xf,H as Xf,I as v,K as Df,L as wf,N as bf,Q as I,X as pf}from"./chunk-8w1hd9ct.js";import{_ as k}from"./chunk-a8znntss.js";import{ra as r,ta as _f,ua as Cf,ya as m}from"./chunk-5smacbk0.js";import{Ea as o}from"./chunk-jsn8476q.js";import{Ka as hf,Ma as Jf,Va as Nf}from"./chunk-7pcm8vy5.js";import{tb as A}from"./chunk-63dzf6hr.js";import{Lb as q}from"./chunk-w1zb8zac.js";import{Nb as Uf}from"./chunk-kfg3vx5z.js";var o0={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 a0(V){return{port:V.port??0,hostname:V.hostname??"127.0.0.1",cors:V.cors??[]}}import{Hono as k0}from"hono";import{cors as S0}from"hono/cors";import{existsSync as ef,readFileSync as Kf}from"node:fs";import{createServer as h0}from"node:http";import{networkInterfaces as I0}from"node:os";import{dirname as v0,extname as u0,join as g}from"node:path";import{fileURLToPath as p0}from"node:url";import{WebSocketServer as g0}from"ws";import{z as $f}from"zod";class i 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 l extends i{constructor(V,$){super("NOT_FOUND",$?`${V} not found: ${$}`:`${V} not found`,404)}}class w extends i{constructor(V){super("BAD_REQUEST",V,400)}}var i0=$f.object({error:$f.object({code:$f.string(),message:$f.string()})});import{Hono as V0}from"hono";import{z as c}from"zod";var jf=q("Service"),J0=c.object({updates:c.record(c.any()),options:c.object({scope:c.enum(["local","project","global"]).optional(),immediate:c.boolean().optional()}).optional()}),Af=()=>{let V=new V0;return V.get("/",async($)=>{try{let f=r();return $.json(f||{})}catch(f){return jf.error("[ConfigRoutes] Failed to get config:",f),$.json({})}}),V.put("/",async($)=>{try{let f=await $.req.json(),J=J0.safeParse(f);if(!J.success)throw new w("Invalid config update format");let{updates:Q,options:K}=J.data;return await m().updateConfig(Q,K),$.json({success:!0,updates:Q})}catch(f){throw jf.error("[ConfigRoutes] Failed to update config:",f),f}}),V.get("/permissions",async($)=>{try{let f=r();return $.json(f?.permissions||{})}catch(f){return jf.error("[ConfigRoutes] Failed to get permissions:",f),$.json({})}}),V};import{Hono as Q0}from"hono";var Tf=()=>{let V=new Q0;return V.get("/health",($)=>{return $.json({healthy:!0,version:o()})}),V.get("/info",($)=>{return $.json({version:o(),platform:process.platform,arch:process.arch,nodeVersion:process.version,cwd:A()})}),V};import{Hono as Y0}from"hono";var e=q("Service"),Hf=()=>{let V=new Y0;return V.get("/",async($)=>{try{let J=k.getInstance().getAllServers(),Q=Array.from(J.entries()).map(([K,Z])=>({id:K,name:K,status:Z.status==="connected"?"connected":Z.status==="connecting"?"connecting":Z.lastError?"error":"offline",endpoint:Z.config.command?`${Z.config.command} ${(Z.config.args||[]).join(" ")}`.trim():Z.config.url||"Unknown",description:`MCP server: ${K}`,tools:Z.tools.map((X)=>X.name),connectedAt:Z.connectedAt?.toISOString(),error:Z.lastError?.message}));return $.json(Q)}catch(f){return e.error("[McpRoutes] Failed to get MCP servers:",f),$.json([])}}),V.post("/:name/connect",async($)=>{try{let f=$.req.param("name");return await k.getInstance().connectServer(f),$.json({success:!0})}catch(f){return e.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 k.getInstance().disconnectServer(f),$.json({success:!0})}catch(f){return e.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 k.getInstance().unregisterServer(f);let Q=r();if(Q?.mcpServers){let{[f]:K,...Z}=Q.mcpServers;await m().updateConfig({mcpServers:Z})}return $.json({success:!0})}catch(f){return e.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:J,config:Q}=f;if(!J||!Q)return $.json({success:!1,error:"Missing name or config"},400);await k.getInstance().registerServer(J,Q);let Z=r();return await m().updateConfig({mcpServers:{...Z?.mcpServers,[J]:Q}}),$.json({success:!0})}catch(f){return e.error("[McpRoutes] Failed to add MCP server:",f),$.json({success:!1,error:f.message},500)}}),V};import{Hono as Z0}from"hono";var Vf=q("Service"),zf=()=>{let V=new Z0;return V.get("/",async($)=>{try{let f=_f(),J=Cf();return $.json({configured:f,current:J})}catch(f){return Vf.error("[ModelsRoutes] Failed to get models:",f),$.json({configured:[],current:null})}}),V.post("/",async($)=>{try{let f=await $.req.json(),{provider:J,name:Q,model:K,baseUrl:Z,apiKey:X}=f;if(!K)throw new w("model is required");let E=await m().addModel({provider:J||"openai-compatible",name:Q||K,model:K,baseUrl:Z||void 0,apiKey:X||void 0});return $.json({success:!0,model:E})}catch(f){throw Vf.error("[ModelsRoutes] Failed to add model:",f),f}}),V.put("/:modelId",async($)=>{try{let f=$.req.param("modelId"),J=await $.req.json(),{baseUrl:Q,apiKey:K,model:Z}=J;return await m().updateModel(f,{baseUrl:Q||void 0,apiKey:K||void 0,model:Z||void 0}),$.json({success:!0})}catch(f){throw Vf.error("[ModelsRoutes] Failed to update model:",f),f}}),V.delete("/:modelId",async($)=>{try{let f=$.req.param("modelId");return await m().removeModel(f),$.json({success:!0})}catch(f){throw Vf.error("[ModelsRoutes] Failed to delete model:",f),f}}),V};import{Hono as U0}from"hono";import{z as y}from"zod";import{Mutex as K0}from"async-mutex";import{Hono as G0}from"hono";import{streamSSE as O0}from"hono/streaming";import{LRUCache as j0}from"lru-cache";import{nanoid as u}from"nanoid";import{z as H}from"zod";var T=q("Service"),N0=H.object({title:H.string().optional(),projectPath:H.string().optional()}),X0=H.object({content:H.string(),attachments:H.array(H.object({type:H.enum(["file","image","url"]),path:H.string().optional(),url:H.string().optional(),content:H.string().optional(),mimeType:H.string().optional(),name:H.string().optional()})).optional(),permissionMode:H.enum(["default","autoEdit","plan","yolo"]).optional()}),M0=H.object({title:H.string().optional()}),R=new Map,L=new j0({max:100,ttl:1800000,dispose:(V,$)=>{if(V.status==="running"||V.status==="waiting_permission")V.abortController.abort(),T.debug(`[SessionRoutes] Run ${$} disposed due to cache eviction`)}}),E0=(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 Mf(V){if(typeof V==="string")return V;return V.filter(($)=>$.type==="text").map(($)=>$.text).join(`
|
|
2
|
+
`)}function F0(V,$){let f=($??[]).filter((Q)=>Q.type==="image"&&typeof Q.content==="string").map((Q)=>({type:"image_url",image_url:{url:Q.content}}));if(f.length===0)return V;let J=[];if(V.trim())J.push({type:"text",text:V});return J.push(...f),J}var Rf=()=>{let V=new G0,$=new Map,f=new Map,J=new Map,Q=new Map,K=(Y)=>{let G=Q.get(Y);if(!G)G=new K0,Q.set(Y,G);return G},Z=async(Y)=>{let G=$.get(Y.id);if(G)return G;let j=f.get(Y.id);if(!j)j=Xf.create({sessionId:Y.id,workspaceRoot:Y.projectPath}),f.set(Y.id,j);try{let O=await j;return $.set(Y.id,O),O}finally{if(f.get(Y.id)===j)f.delete(Y.id)}},X=async(Y,G)=>{let j=R.get(Y);if(j)return j;let O=J.get(Y);if(!O)O=(async()=>{let F=(await I.listSessions()).find((_)=>_.sessionId===Y),x=F?.projectPath??G,W=F?await I.loadSession(Y,x).catch(()=>[]):[],U={id:Y,projectPath:x,title:`Session ${Y.slice(0,6)}`,createdAt:F?new Date(F.firstMessageTime):new Date,messages:W,relationType:F?.relationType};return R.set(Y,U),U})(),J.set(Y,O);try{return await O}finally{if(J.get(Y)===O)J.delete(Y)}},E=(Y,G,j,O={})=>{let F=u(12),x={id:F,sessionId:Y.id,status:"running",abortController:new AbortController,createdAt:new Date};return L.set(F,x),Y.currentRunId=F,x0(x,Y,G,j,Z,{pendingInputOnly:O.pendingInputOnly,preparedInputTurn:O.preparedInputTurn}).catch((W)=>{T.error(`[SessionRoutes] Run ${F} failed:`,W)}),x},N=async(Y)=>{let G=Y.currentRunId?L.get(Y.currentRunId):void 0;if(G&&(G.status==="running"||G.status==="waiting_permission"))return;if(!await Xf.hasPendingInbox(Y.projectPath,Y.id))return;let j=await Z(Y),O=Y.currentRunId?L.get(Y.currentRunId):void 0;if(O&&(O.status==="running"||O.status==="waiting_permission"))return;if(j.getPendingSteeringCount()===0||j.hasTurnOwner())return;E(Y,"","default",{pendingInputOnly:!0})};return V.get("/",async(Y)=>{try{let G=await I.listSessions(),j=new Set(G.filter((B)=>B.relationType==="subagent").map((B)=>B.sessionId)),O=Array.from(R.values()).filter((B)=>!j.has(B.id)&&B.relationType!=="subagent").map((B)=>({sessionId:B.id,projectPath:B.projectPath,title:B.title,parentId:void 0,relationType:void 0,status:void 0,agentType:void 0,model:void 0,messageCount:B.messages.length,firstMessageTime:B.createdAt.toISOString(),lastMessageTime:new Date().toISOString(),hasErrors:!1,isActive:!0})),F=new Set(O.map((B)=>B.sessionId)),x=G.filter((B)=>!R.has(B.sessionId)&&!F.has(B.sessionId)&&B.relationType!=="subagent"),W=new Set(F),U=x.filter((B)=>{if(W.has(B.sessionId))return!1;return W.add(B.sessionId),!0}),_=[...O,...U];return Y.json(_)}catch(G){return T.error("[SessionRoutes] Failed to list sessions:",G),Y.json([])}}),V.post("/",async(Y)=>{try{let G=await Y.req.json(),j=N0.safeParse(G);if(!j.success)throw new w("Invalid request body");let{title:O,projectPath:F}=j.data,x=u(12),W=F||Y.get("directory")||A(),U={id:x,projectPath:W,title:O||`Session ${x.slice(0,6)}`,createdAt:new Date,messages:[]};return R.set(x,U),Y.json({sessionId:x,projectPath:W,title:U.title,parentId:void 0,relationType:void 0,status:void 0,agentType:void 0,model:void 0,messageCount:0,firstMessageTime:U.createdAt.toISOString(),lastMessageTime:U.createdAt.toISOString(),hasErrors:!1})}catch(G){throw T.error("[SessionRoutes] Failed to create session:",G),G}}),V.get("/:sessionId",async(Y)=>{let G=Y.req.param("sessionId"),j=R.get(G);if(j)return Y.json({sessionId:j.id,projectPath:j.projectPath,title:j.title,messageCount:j.messages.length,firstMessageTime:j.createdAt.toISOString(),lastMessageTime:new Date().toISOString(),hasErrors:!1,isActive:!0});try{let F=(await I.listSessions()).find((x)=>x.sessionId===G);if(!F)throw new l("Session",G);return Y.json(F)}catch(O){if(O instanceof l)throw O;throw T.error("[SessionRoutes] Failed to get session:",O),O}}),V.patch("/:sessionId",async(Y)=>{let G=Y.req.param("sessionId");try{let j=await Y.req.json(),O=M0.safeParse(j);if(!O.success)throw new w("Invalid request body");let{title:F}=O.data,x=R.get(G);if(x&&F)x.title=F;return Y.json({success:!0,title:F})}catch(j){throw T.error("[SessionRoutes] Failed to update session:",j),j}}),V.delete("/:sessionId",async(Y)=>{let G=Y.req.param("sessionId"),j=R.get(G);if(j?.currentRunId){let F=L.get(j.currentRunId);if(F)F.abortController.abort(),v.publish(G,"run.cancelled",{runId:F.id}),L.delete(j.currentRunId)}try{await I.deleteSession(G)}catch(F){T.warn("[SessionRoutes] Failed to delete session file:",F)}R.delete(G),J.delete(G),f.delete(G),Q.delete(G);let O=$.get(G);if(O){if(await O.dispose(),$.delete(G),$.size===0)await k.getInstance().disconnectAll()}return Y.json({success:!0})}),V.get("/:sessionId/message",async(Y)=>{let G=Y.req.param("sessionId");try{let j=await I.loadSession(G);return Y.json(j)}catch(j){return T.error("[SessionRoutes] Failed to get messages:",j),Y.json([])}}),V.get("/:sessionId/events",async(Y)=>{let G=Y.req.param("sessionId"),j=await X(G,Y.get("directory")||A());return O0(Y,async(O)=>{await O.writeSSE({data:JSON.stringify({type:"connected",properties:{sessionId:G,timestamp:Date.now()}})});let x=v.subscribe((U)=>{if(U.sessionId!==G)return;O.writeSSE({data:JSON.stringify({type:U.type,properties:{sessionId:U.sessionId,...U.properties}})}).catch(()=>{})});N(j).catch((U)=>{T.error(`[SessionRoutes] Failed to resume pending input for ${G}:`,U)});let W=setInterval(()=>{if(!O.aborted)O.writeSSE({data:JSON.stringify({type:"heartbeat",properties:{timestamp:Date.now()}})}).catch(()=>{})},15000);O.onAbort(()=>{clearInterval(W),x()});while(!0)if(await new Promise((U)=>setTimeout(U,1000)),O.aborted)break})}),V.post("/:sessionId/message",async(Y)=>{let G=Y.req.param("sessionId"),j=await Y.req.json(),O=X0.safeParse(j);if(!O.success)throw new w("Invalid message format");let{content:F,attachments:x,permissionMode:W}=O.data,U=W||"default",_=Y.get("directory")||A(),B=F0(F,x),z=await X(G,_);return K(G).runExclusive(async()=>{let M=z.currentRunId?L.get(z.currentRunId):void 0;if(M&&(M.status==="running"||M.status==="waiting_permission")){let b=await(await Z(z)).enqueueSteering(B,{allowBeforeTurn:!0});if(!b.accepted)return Y.json({status:"rejected",reason:b.reason??"turn_unavailable"},409);let n=b.messageId??u(12),ff=b.queued;v.publish(G,"message.created",{messageId:n,role:"user",content:Mf(B)});let f0=b.delivery==="next_turn"?"follow_up.queued":"steering.queued";if(v.publish(G,f0,{runId:M.id,messageId:n,queued:ff}),b.delivery==="next_turn"&&M.status!=="running"&&M.status!=="waiting_permission")N(z).catch(($0)=>{T.error(`[SessionRoutes] Failed to wake queued follow-up for ${G}:`,$0)});if(b.delivery==="next_turn")M.pendingFollowUpRequested=!0;return Y.json({runId:M.id,messageId:n,status:b.delivery==="next_turn"?"follow_up_queued":"steering_queued",queued:ff},202)}let d=await(await Z(z)).prepareInputTurn(B);if(!d.accepted)return Y.json({status:"rejected",reason:d.reason},d.reason==="queue_full"?429:409);let Gf=E(z,B,U,{preparedInputTurn:d});return Y.json({runId:Gf.id,messageId:d.messageId,status:"running"},202)})}),V.post("/:sessionId/abort",async(Y)=>{let G=Y.req.param("sessionId"),j=R.get(G);if(j?.currentRunId){let O=L.get(j.currentRunId);if(O)O.abortController.abort(),O.status="cancelled",v.publish(G,"run.cancelled",{runId:O.id})}return Y.json({success:!0})}),V.get("/:sessionId/status",async(Y)=>{let G=Y.req.param("sessionId"),j=R.get(G);if(!j?.currentRunId)return Y.json({sessionId:G,status:"idle"});let O=L.get(j.currentRunId);return Y.json({sessionId:G,runId:j.currentRunId,status:O?.status||"idle"})}),V};async function x0(V,$,f,J,Q,K={}){let{abortController:Z,sessionId:X,id:E}=V,N=K.preparedInputTurn?.messageId??u(12),G=K.pendingInputOnly===!0||K.preparedInputTurn?.mode==="pending"?void 0:u(12),j,O=(F,x)=>{v.publish(X,F,x)};try{if(!K.pendingInputOnly)O("message.created",{messageId:N,role:"user",content:Mf(f)});if(O("session.status",{status:"running"}),G)O("message.created",{messageId:G,role:"assistant",content:""});j=await Q($);let F=j,x=await bf.createWithRuntime(F,{sessionId:X}),W=async(M)=>{let C=u(12),d=300000;V.status="waiting_permission";let Gf=new Promise((b)=>{let n=setTimeout(()=>{T.warn(`[SessionRoutes] Permission ${C} timed out after 300000ms`),O("permission.timeout",{requestId:C}),b({approved:!1,reason:"timeout"})},300000);V.pendingPermission={permissionId:C,resolve:(ff)=>{clearTimeout(n),b(ff)},details:M}});O("permission.asked",{requestId:C,toolName:M.toolName,description:M.message,args:M.args,details:M}),T.info(`[SessionRoutes] Permission request created: ${C}, runId: ${E}`);let Of=await Gf;return T.info(`[SessionRoutes] Permission response received: ${C}, approved: ${Of.approved}`),V.status="running",V.pendingPermission=void 0,Of},U={messages:[...$.messages],userId:"web-user",sessionId:X,workspaceRoot:$.projectPath,signal:Z.signal,permissionMode:J,confirmationHandler:{requestConfirmation:W}},_=()=>{if(!G)G=u(12),O("message.created",{messageId:G,role:"assistant",content:""});return G},B=async(M)=>{switch(M.kind){case"content_delta":O("message.delta",{messageId:_(),delta:M.delta});break;case"thinking_delta":O("thinking.delta",{delta:M.delta});break;case"tool_start":if("function"in M.toolCall)O("tool.start",{messageId:_(),toolName:M.toolCall.function.name,toolCallId:M.toolCall.id,arguments:M.toolCall.function.arguments,toolKind:M.toolKind});break;case"tool_result":if("function"in M.toolCall)O("tool.result",{messageId:_(),toolName:M.toolCall.function.name,toolCallId:M.toolCall.id,success:M.result.success,summary:M.result.metadata?.summary,output:wf(Df(M.toolCall.function.name,M.result)),metadata:E0(M.result.metadata)});break;case"token_usage":O("token.usage",{...M.usage});break;case"turn_start":O("turn.started",{turn:M.turn,maxTurns:M.maxTurns});break;case"steering_applied":O("steering.applied",{runId:E,messageIds:M.messageIds,count:M.count,recovered:M.recovered,delivery:M.delivery,queued:F.getPendingSteeringCount()});break;case"follow_up_started":{if(G)O("message.complete",{messageId:G}),G=void 0;for(let C of M.messages){if(!C.recovered||C.persisted)continue;O("message.created",{messageId:C.id,role:"user",content:Mf(C.content),recovered:!0})}O("follow_up.started",{runId:E,queued:M.queued,recovered:M.recovered}),_();break}case"compaction":O(M.phase==="start"?"compaction.started":"compaction.completed",{});break;case"model_fallback":O("model.fallback",{});break;case"task_update":O("task.updated",{tasks:M.tasks});break;default:break}},z=await Nf(x.chatStream(f,U,{stream:!0,pendingInputOnly:K.pendingInputOnly,preparedInputTurn:K.preparedInputTurn}),B);if(!z.success)throw Error(z.error?.message??"Agent run failed");for(let M=0;M<20;M++){let C=V.pendingFollowUpRequested===!0;if(V.pendingFollowUpRequested=!1,F.getPendingSteeringCount()===0){if(!C)break;continue}if(Z.signal.aborted)break;if(z=await Nf(x.chatStream("",U,{stream:!0,pendingInputOnly:!0}),B),!z.success)throw Error(z.error?.message??"Agent follow-up failed")}if($.messages=[...U.messages],G)O("message.complete",{messageId:G});O("thinking.completed",{}),V.status="completed",O("session.completed",{runId:E,outputTruncated:z.metadata?.outputTruncated??!1}),O("session.status",{status:"idle"})}catch(F){if(j&&K.preparedInputTurn)await j.finishTurn(K.preparedInputTurn.handle).catch(()=>{return});T.error("[SessionRoutes] Agent execution error:",F),V.status="failed",O("session.error",{error:F instanceof Error?F.message:"Unknown error"}),O("session.status",{status:"error"})}}function yf(V,$,f){T.info(`[SessionRoutes] Looking for permission ${$} in session ${V}`),T.info(`[SessionRoutes] Active runs: ${L.size}`);for(let[J,Q]of L.entries())if(T.info(`[SessionRoutes] Checking run ${J}: sessionId=${Q.sessionId}, pendingPermission=${Q.pendingPermission?.permissionId}`),Q.sessionId===V&&Q.pendingPermission?.permissionId===$)return Q.pendingPermission.resolve(f),T.info(`[SessionRoutes] Permission ${$} responded, runId: ${Q.id}`),!0;return T.error(`[SessionRoutes] Permission not found: ${$}`),!1}var Ef=q("Service"),B0=y.object({approved:y.boolean(),remember:y.boolean().optional(),scope:y.enum(["once","session"]).optional(),targetMode:y.enum(["default","autoEdit","plan","yolo"]).optional(),feedback:y.string().optional(),answers:y.record(y.union([y.string(),y.array(y.string())])).optional()}),Lf=()=>{let V=new U0;return V.post("/:permissionId",async($)=>{let f=$.req.param("permissionId"),J=$.req.query("sessionId");Ef.info(`[PermissionRoutes] Received permission response: permissionId=${f}, sessionId=${J}`);try{let Q=await $.req.json(),K=B0.safeParse(Q);if(!K.success)throw new w("Invalid permission response format");let{approved:Z,remember:X,scope:E,targetMode:N,feedback:Y,answers:G}=K.data;if(!J)throw new w("sessionId query parameter is required");if(!yf(J,f,{approved:Z,reason:Y,scope:E,targetMode:N,feedback:Y,answers:G}))throw new l("Permission request",f);return Ef.info(`[PermissionRoutes] Permission ${f} ${Z?"approved":"denied"}`),$.json({success:!0,approved:Z,remember:X})}catch(Q){throw Ef.error("[PermissionRoutes] Failed to respond to permission:",Q),Q}}),V};import{Hono as W0}from"hono";var Pf=q("Service"),Sf=()=>{let V=new W0;return V.get("/",async($)=>{try{let f=await mf();return $.json(f)}catch(f){return Pf.error("[ProviderRoutes] Failed to list providers:",f),$.json([])}}),V.get("/:provider/models",async($)=>{let f=$.req.param("provider");try{let J=await kf(f);return $.json(J)}catch(J){return Pf.error("[ProviderRoutes] Failed to list models:",J),$.json([])}}),V};import{Hono as q0}from"hono";import*as S from"node:fs/promises";import{homedir as A0}from"node:os";import*as Qf from"node:path";var p=q("Service"),Ff=Qf.join(A0(),".blade","skills-config.json");async function If(){try{let V=await S.readFile(Ff,"utf-8");return JSON.parse(V)}catch{return{disabled:[]}}}async function T0(V){await S.mkdir(Qf.dirname(Ff),{recursive:!0}),await S.writeFile(Ff,JSON.stringify(V,null,2))}async function H0(V,$){let f=await If();if($)f.disabled=f.disabled.filter((J)=>J!==V);else if(!f.disabled.includes(V))f.disabled.push(V);await T0(f)}var a=null,_0=300000;async function C0(){if(a&&Date.now()-a.timestamp<_0)return a.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 p.warn(`GitHub API returned ${V.status}`),a?.data||[];let $=await V.json(),f=[];for(let J of $){if(J.type!=="dir")continue;let Q=`Official ${J.name} skill`;try{let K=await fetch(`https://raw.githubusercontent.com/anthropics/skills/main/skills/${J.name}/SKILL.md`,{headers:{"User-Agent":"Blade-Skills-Catalog"}});if(K.ok){let X=(await K.text()).match(/^#[^\n]*\n+([^\n#]+)/);if(X)Q=X[1].trim().slice(0,100)}}catch{}f.push({name:J.name,description:Q,tag:"Official",author:"Anthropic"})}return a={data:f,timestamp:Date.now()},f}catch(V){return p.warn("Failed to fetch skills catalog from GitHub:",V),a?.data||[]}}var vf=()=>{let V=new q0;return V.get("/",async($)=>{try{let f=Jf();await f.initialize();let J=f.getAll(),Q=await If(),K=J.map((Z)=>({id:Z.name,name:Z.name,enabled:!Q.disabled.includes(Z.name),description:Z.description||"",version:Z.version||"1.0.0",provider:"Local",location:Z.source==="builtin"?"Built-in":Z.basePath,capabilities:["prompts"],allowedTools:Z.allowedTools||[]}));return $.json(K)}catch(f){return p.error("[SkillsRoutes] Failed to get skills:",f),$.json([])}}),V.post("/:name/toggle",async($)=>{try{let f=$.req.param("name"),J=await $.req.json();return await H0(f,J.enabled),$.json({success:!0,enabled:J.enabled})}catch(f){return p.error("[SkillsRoutes] Failed to toggle skill:",f),$.json({success:!1,error:f.message},500)}}),V.delete("/:name",async($)=>{try{let f=$.req.param("name"),J=`${process.env.HOME}/.blade/skills/${f}`;return await S.rm(J,{recursive:!0,force:!0}),await Jf().refresh(),$.json({success:!0})}catch(f){return p.error("[SkillsRoutes] Failed to uninstall skill:",f),$.json({success:!1,error:f.message},500)}}),V.post("/install",async($)=>{try{let f=await $.req.json(),J=hf(),Q=Jf(),K=!1;if(f.source==="catalog"&&f.name){if(K=await J.installOfficialSkill(f.name),!K)return $.json({success:!1,error:"Failed to install skill from catalog"},500)}else if(f.source==="repo"&&f.url){if(K=await J.installFromRepo(f.url,f.name),!K)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(K=await J.installFromLocal(f.path,f.name),!K)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 Q.refresh(),$.json({success:!0})}catch(f){return p.error("[SkillsRoutes] Failed to install skill:",f),$.json({success:!1,error:f.message},500)}}),V.get("/catalog",async($)=>{try{let f=await C0();return $.json(f)}catch(f){return p.error("[SkillsRoutes] Failed to get catalog:",f),$.json([])}}),V};import z0 from"fast-glob";import{Hono as D0}from"hono";import{execSync as w0}from"node:child_process";import{readdir as b0}from"node:fs/promises";import Yf from"node:path";var s=q("Service"),R0=(V)=>{try{return w0("git rev-parse --abbrev-ref HEAD",{cwd:V,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||null}catch{return null}},y0=[...Zf.map((V)=>`${V}/**`),...Zf,...xf.map((V)=>`**/${V}`)],L0=new Set(["/theme","/model","/permissions","/mcp","/skills","/exit","/resume","/ide","/login","/logout"]),gf=()=>{let V=new D0;return V.get("/commands",async($)=>{try{let f=$.req.query("q")||"",J=pf(f).filter((Q)=>!L0.has(Q.command));return $.json(J)}catch(f){return s.error("[SuggestionsRoutes] Failed to get command suggestions:",f),$.json([])}}),V.get("/files",async($)=>{try{let f=$.req.query("q")||"",J=$.get("directory")||A(),Q=Math.min(Number($.req.query("limit"))||100,1000),Z=(await z0("**/*",{cwd:J,dot:!1,followSymbolicLinks:!1,onlyFiles:!1,markDirectories:!0,unique:!0,ignore:y0})).map((N)=>N.replace(/\\/g,"/"));if(!f)return $.json(Z.slice(0,Q));let X=f.toLowerCase(),E=Z.filter((N)=>N.toLowerCase().includes(X)).slice(0,Q);return $.json(E)}catch(f){return s.error("[SuggestionsRoutes] Failed to get file suggestions:",f),$.json([])}}),V.get("/files/tree",async($)=>{try{let f=$.get("directory")||A(),J=$.req.query("path")||"",Q=J?Yf.join(f,J):f,Z=(await b0(Q,{withFileTypes:!0})).map((N)=>({name:N.name,path:J?`${J}/${N.name}`:N.name,type:N.isDirectory()?"dir":"file"}));Z.sort((N,Y)=>{if(N.type!==Y.type)return N.type==="dir"?-1:1;return N.name.localeCompare(Y.name)});let X=new Set(Zf),E=Z.filter((N)=>{let Y=N.name;if(Y.startsWith("."))return!1;if(X.has(Y))return!1;for(let G of xf)if(Y.match(new RegExp(G.replace("*",".*"))))return!1;return!0});return $.json(E)}catch(f){return s.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 J=$.get("directory")||A(),Q=Yf.resolve(J,f),K=Yf.relative(J,Q);if(K.startsWith("..")||Yf.isAbsolute(K))return $.json({error:"Invalid file path"},400);let Z=uf(),X=await Z.stat(Q);if(!X?.isFile)return $.json({error:"File not found"},404);let E=200000,N=await Z.readTextFile(Q),Y=N.length>E;return $.json({path:f,content:Y?N.slice(0,E):N,truncated:Y,size:X.size})}catch(f){return s.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")||A(),J=R0(f);return $.json({branch:J})}catch(f){return s.error("[SuggestionsRoutes] Failed to get git info:",f),$.json({branch:null})}}),V};import{Hono as P0}from"hono";var h=q("Service"),t=new Map,df=2097152,lf=65536;function cf(){return typeof globalThis.Bun<"u"}async function m0(V,$,f){if(cf()){let{spawn:K}=await import("bun-pty"),Z=K(V,$,{name:"xterm-256color",cwd:f.cwd,env:f.env});return{pid:Z.pid,write:(X)=>Z.write(X),resize:(X,E)=>Z.resize(X,E),kill:()=>Z.kill(),onData:(X)=>Z.onData(X),onExit:(X)=>Z.onExit(X)}}let Q=(await import("node-pty")).spawn(V,$,{name:"xterm-256color",cwd:f.cwd,env:f.env,cols:80,rows:24});return{pid:Q.pid,write:(K)=>Q.write(K),resize:(K,Z)=>Q.resize(K,Z),kill:()=>Q.kill(),onData:(K)=>{Q.onData(K)},onExit:(K)=>{Q.onExit(K)}}}var Wf=void 0,Bf;if(cf())try{let{createBunWebSocket:V}=await import("hono/bun"),$=V();Bf=$.upgradeWebSocket,Wf=$.websocket}catch(V){h.warn("[Terminal] Failed to initialize Bun WebSocket support:",V)}async function rf(V,$){let f=`term-${Date.now()}`;h.info(`[Terminal] New connection: ${f}, cwd: ${V}`);let J=process.platform==="win32"?"powershell.exe":process.env.SHELL||"/bin/zsh",Q=J.endsWith("sh")?["-l"]:[],K=await m0(J,Q,{cwd:V,env:{...process.env,TERM:"xterm-256color",COLORTERM:"truecolor"}}),Z={id:f,process:K,cwd:V,buffer:"",subscribers:new Set};if(t.set(f,Z),Z.subscribers.add($),K.onData((X)=>{let E=!1;for(let N of Z.subscribers)try{N.send(X),E=!0}catch{Z.subscribers.delete(N)}if(E)return;if(Z.buffer+=X,Z.buffer.length>df)Z.buffer=Z.buffer.slice(-df)}),K.onExit(({exitCode:X})=>{h.info(`[Terminal] Process exited: ${f}, code: ${X}`);for(let E of Z.subscribers)try{E.close()}catch{}t.delete(f)}),Z.buffer){let X=Z.buffer;Z.buffer="";for(let E=0;E<X.length;E+=lf)$.send(X.slice(E,E+lf))}return{session:Z,cleanup:()=>{if(h.info(`[Terminal] Connection closed: ${f}`),Z.subscribers.delete($),Z.subscribers.size===0){try{Z.process.kill()}catch{}t.delete(f)}}}}function of(V,$){V.on("connection",async(f,J)=>{let Q=new URL(J.url||"/",`http://${J.headers.host}`);if(!Q.pathname.endsWith("/terminal/ws")){f.close();return}let K=Q.searchParams.get("cwd")||$()||A();try{let{session:Z,cleanup:X}=await rf(K,{send:(E)=>f.send(E),close:()=>f.close()});f.on("message",(E)=>{try{Z.process.write(String(E))}catch(N){h.error("[Terminal] Failed to write to PTY:",N)}}),f.on("close",X),f.on("error",X)}catch(Z){h.error("[Terminal] Failed to spawn PTY:",Z),f.close()}})}var af=()=>{let V=new P0;if(V.get("/status",($)=>{let f=Array.from(t.values()).map((J)=>({id:J.id,cwd:J.cwd}));return $.json({active:f.length,terminals:f})}),V.post("/kill/:terminalId",($)=>{let f=$.req.param("terminalId"),J=t.get(f);if(J){try{J.process.kill()}catch{}for(let Q of J.subscribers)Q.close();return t.delete(f),$.json({success:!0})}return $.json({success:!1,error:"Terminal not found"},404)}),Bf)V.get("/ws",Bf(($)=>{let f=$.req.query("cwd")||$.get("directory")||A(),J;return{async onOpen(Q,K){try{J=await rf(f,{send:(Z)=>K.send(Z),close:()=>K.close()})}catch(Z){h.error("[Terminal] Failed to spawn PTY:",Z),K.close()}},onMessage(Q){if(!J)return;try{J.session.process.write(String(Q.data))}catch(K){h.error("[Terminal] Failed to write to PTY:",K)}},onClose(){J?.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 D=q("Service"),qf=[];function d0(){let V=v0(p0(import.meta.url)),$=[g(V,"web"),g(A(),"dist/web"),g(A(),"packages/cli/dist/web")];for(let f of $){let J=g(f,"index.html");if(ef(J)){if(Kf(J,"utf-8").includes("/assets/"))return D.debug(`[Server] Found web dist at: ${f}`),f}}return null}function l0(){let V=new k0;V.onError((f,J)=>{if(D.error("[Server] Request error:",f),f instanceof i)return J.json(f.toObject(),f.statusCode);let Q=f instanceof Error?f.message:String(f);return J.json({error:{code:"INTERNAL_ERROR",message:Q}},500)}),V.use(async(f,J)=>{let Q=process.env.BLADE_SERVER_PASSWORD;if(!Q)return J();let K=f.req.path;if(K==="/"||K.startsWith("/assets/")||K.endsWith(".html")||K.endsWith(".js")||K.endsWith(".css"))return J();let Z=f.req.header("Authorization");if(!Z?.startsWith("Basic "))return f.header("WWW-Authenticate",'Basic realm="Blade Server"'),f.json({error:{code:"UNAUTHORIZED",message:"Authentication required"}},401);let X=Buffer.from(Z.slice(6),"base64").toString(),[E,N]=X.split(":"),Y=process.env.BLADE_SERVER_USERNAME??"blade";if(E!==Y||N!==Q)return f.json({error:{code:"UNAUTHORIZED",message:"Invalid credentials"}},401);return J()}),V.use(async(f,J)=>{let Q=f.req.path==="/health"||f.req.path==="/global/health"||f.req.path.startsWith("/assets/");if(!Q)D.debug(`[Server] ${f.req.method} ${f.req.path}`);let K=Date.now();if(await J(),!Q){let Z=Date.now()-K;D.debug(`[Server] ${f.req.method} ${f.req.path} - ${f.res.status} (${Z}ms)`)}}),V.use(S0({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(qf.includes(f))return f;return}})),V.use(async(f,J)=>{let Q=f.req.query("directory")||f.req.header("x-blade-directory")||A();try{Q=decodeURIComponent(Q)}catch{}return f.set("directory",Q),J()}),V.route("/global",Tf()),V.route("/sessions",Rf()),V.route("/configs",Af()),V.route("/permissions",Lf()),V.route("/providers",Sf()),V.route("/models",zf()),V.route("/suggestions",gf()),V.route("/terminal",af()),V.route("/mcp",Hf()),V.route("/skills",vf()),V.get("/health",(f)=>{return f.json({healthy:!0,version:o()})});let $=d0();if($)D.info(`[Server] Serving static files from ${$}`),V.get("/assets/*",(f)=>{let J=g($,f.req.path);if(!ef(J))return f.json({error:{code:"NOT_FOUND",message:`File not found: ${f.req.path}`}},404);let Q=Kf(J),K=u0(J).toLowerCase(),X={".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"}[K]||"application/octet-stream";return new Response(Q,{headers:{"Content-Type":X,"Cache-Control":"public, max-age=31536000, immutable"}})}),V.get("/",(f)=>{let J=g($,"index.html"),Q=Kf(J,"utf-8");return f.html(Q)}),V.get("*",(f)=>{let J=f.req.path;if(J.includes("."))return f.json({error:{code:"NOT_FOUND",message:`File not found: ${J}`}},404);let Q=g($,"index.html"),K=Kf(Q,"utf-8");return f.html(K)});else D.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:o(),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 c0(){let V=I0(),$=[];for(let f of Object.keys(V)){let J=V[f];if(!J)continue;for(let Q of J){if(Q.internal||Q.family!=="IPv4")continue;if(Q.address.startsWith("172."))continue;$.push(Q.address)}}return $}function tf(){return typeof globalThis.Bun<"u"}function nf(V,$){let f=globalThis.Bun,J=(K)=>{try{return f.serve({hostname:$.hostname,port:K,fetch:V.fetch,idleTimeout:0,websocket:Wf})}catch(Z){D.error("Failed to start Bun server:",Z);return}},Q=$.port===0?J(4096)??J(0):J($.port);if(!Q)throw Error(`Failed to start Bun server on port ${$.port}`);return{url:Q.url,port:Q.port,hostname:Q.hostname,stop:async()=>{Q.stop(!0)}}}function r0(V,$){return new Promise((f,J)=>{let Q=h0(async(N,Y)=>{let G=new URL(N.url||"/",`http://${N.headers.host}`),j=new Headers;for(let[x,W]of Object.entries(N.headers))if(W)if(Array.isArray(W))for(let U of W)j.append(x,U);else j.set(x,W);let O;if(N.method!=="GET"&&N.method!=="HEAD")O=(await new Promise((W)=>{let U=[];N.on("data",(_)=>U.push(_)),N.on("end",()=>W(Buffer.concat(U)))})).toString();let F=new Request(G.toString(),{method:N.method,headers:j,body:O});try{let x=await V.fetch(F);if(Y.statusCode=x.status,x.headers.forEach((W,U)=>{Y.setHeader(U,W)}),x.body){let W=x.body.getReader(),U=async()=>{let{done:_,value:B}=await W.read();if(_){Y.end();return}return Y.write(B),U()};await U()}else{let W=await x.text();Y.end(W)}}catch(x){D.error("[Server] Node request error:",x),Y.statusCode=500,Y.end(JSON.stringify({error:{code:"INTERNAL_ERROR",message:"Internal server error"}}))}}),K=new g0({noServer:!0}),Z=A();of(K,()=>Z),Q.on("upgrade",(N,Y,G)=>{if(new URL(N.url||"/",`http://${N.headers.host}`).pathname==="/terminal/ws")K.handleUpgrade(N,Y,G,(O)=>{K.emit("connection",O,N)});else Y.destroy()});let X=(N)=>{return new Promise((Y,G)=>{Q.once("error",(j)=>{if(j.code==="EADDRINUSE")G(j);else G(j)}),Q.listen(N,$.hostname,()=>{let j=Q.address();if(j&&typeof j==="object")Y(j.port);else Y(N)})})};(async()=>{let N;if($.port===0)try{N=await X(4096)}catch{N=await X(0)}else N=await X($.port);let Y=new URL(`http://${$.hostname==="0.0.0.0"?"localhost":$.hostname}:${N}`);f({url:Y,port:N,hostname:$.hostname,stop:async()=>{return new Promise((G)=>{K.close(()=>{Q.close(()=>G())})})}})})().catch(J)})}var sf;((vV)=>{let V,$;function f(){if(!$)$=l0();return $}vV.getApp=f;function J(Z){qf=Z.cors??[];let X=f();if(tf())V=nf(X,Z),D.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 E=V;return{url:E.url,port:E.port,hostname:E.hostname,stop:async()=>{if(V)await V.stop(),V=void 0,$=void 0,D.info("[Server] Blade server stopped")}}}vV.listen=J;async function Q(Z){qf=Z.cors??[];let X=f();if(tf())V=nf(X,Z),D.info(`[Server] Blade server listening on ${V.url} (Bun runtime)`);else V=await r0(X,Z),D.info(`[Server] Blade server listening on ${V.url} (Node.js runtime)`);let E=V;return{url:E.url,port:E.port,hostname:E.hostname,stop:async()=>{if(V)await V.stop(),V=void 0,$=void 0,D.info("[Server] Blade server stopped")}}}vV.listenAsync=Q;function K(){return V!==void 0}vV.isRunning=K})(sf||={});export{o0 as f,a0 as g,c0 as h,sf as i};
|
package/package.json
CHANGED
package/dist/chunk-dftaxwg9.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{t as a,u as b}from"./chunk-b1d49byc.js";import"./chunk-4e2fzyf2.js";import"./chunk-kfg3vx5z.js";export{a as globalOptions,b as cliConfig};
|
package/dist/chunk-gzc9n5d6.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import{j as mf,k as Lf}from"./chunk-pvxp2gzr.js";import{A as hf,C as Jf,D as Mf,H as Gf,I as h,K as _f,L as Cf,N as zf,Q as S,X as If}from"./chunk-6rszb7xd.js";import{_ as y}from"./chunk-7mnefph6.js";import{ra as d,ta as Af,ua as Tf,ya as L}from"./chunk-5smacbk0.js";import{Ea as l}from"./chunk-4e2fzyf2.js";import{Ka as Pf,Ma as ff,Va as Of}from"./chunk-3mhbped9.js";import{tb as W}from"./chunk-63dzf6hr.js";import{Lb as B}from"./chunk-w1zb8zac.js";import{Nb as Ef}from"./chunk-kfg3vx5z.js";var g0={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 d0(V){return{port:V.port??0,hostname:V.hostname??"127.0.0.1",cors:V.cors??[]}}import{Hono as R0}from"hono";import{cors as m0}from"hono/cors";import{existsSync as af,readFileSync as Qf}from"node:fs";import{createServer as L0}from"node:http";import{networkInterfaces as y0}from"node:os";import{dirname as P0,extname as k0,join as u}from"node:path";import{fileURLToPath as S0}from"node:url";import{WebSocketServer as h0}from"ws";import{z as e}from"zod";class t 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 t{constructor(V,$){super("NOT_FOUND",$?`${V} not found: ${$}`:`${V} not found`,404)}}class z extends t{constructor(V){super("BAD_REQUEST",V,400)}}var o0=e.object({error:e.object({code:e.string(),message:e.string()})});import{Hono as ef}from"hono";import{z as g}from"zod";var Kf=B("Service"),sf=g.object({updates:g.record(g.any()),options:g.object({scope:g.enum(["local","project","global"]).optional(),immediate:g.boolean().optional()}).optional()}),Bf=()=>{let V=new ef;return V.get("/",async($)=>{try{let f=d();return $.json(f||{})}catch(f){return Kf.error("[ConfigRoutes] Failed to get config:",f),$.json({})}}),V.put("/",async($)=>{try{let f=await $.req.json(),J=sf.safeParse(f);if(!J.success)throw new z("Invalid config update format");let{updates:Y,options:j}=J.data;return await L().updateConfig(Y,j),$.json({success:!0,updates:Y})}catch(f){throw Kf.error("[ConfigRoutes] Failed to update config:",f),f}}),V.get("/permissions",async($)=>{try{let f=d();return $.json(f?.permissions||{})}catch(f){return Kf.error("[ConfigRoutes] Failed to get permissions:",f),$.json({})}}),V};import{Hono as f0}from"hono";var Wf=()=>{let V=new f0;return V.get("/health",($)=>{return $.json({healthy:!0,version:l()})}),V.get("/info",($)=>{return $.json({version:l(),platform:process.platform,arch:process.arch,nodeVersion:process.version,cwd:W()})}),V};import{Hono as $0}from"hono";var n=B("Service"),qf=()=>{let V=new $0;return V.get("/",async($)=>{try{let J=y.getInstance().getAllServers(),Y=Array.from(J.entries()).map(([j,K])=>({id:j,name:j,status:K.status==="connected"?"connected":K.status==="connecting"?"connecting":K.lastError?"error":"offline",endpoint:K.config.command?`${K.config.command} ${(K.config.args||[]).join(" ")}`.trim():K.config.url||"Unknown",description:`MCP server: ${j}`,tools:K.tools.map((X)=>X.name),connectedAt:K.connectedAt?.toISOString(),error:K.lastError?.message}));return $.json(Y)}catch(f){return n.error("[McpRoutes] Failed to get MCP servers:",f),$.json([])}}),V.post("/:name/connect",async($)=>{try{let f=$.req.param("name");return await y.getInstance().connectServer(f),$.json({success:!0})}catch(f){return n.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 y.getInstance().disconnectServer(f),$.json({success:!0})}catch(f){return n.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 y.getInstance().unregisterServer(f);let Y=d();if(Y?.mcpServers){let{[f]:j,...K}=Y.mcpServers;await L().updateConfig({mcpServers:K})}return $.json({success:!0})}catch(f){return n.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:J,config:Y}=f;if(!J||!Y)return $.json({success:!1,error:"Missing name or config"},400);await y.getInstance().registerServer(J,Y);let K=d();return await L().updateConfig({mcpServers:{...K?.mcpServers,[J]:Y}}),$.json({success:!0})}catch(f){return n.error("[McpRoutes] Failed to add MCP server:",f),$.json({success:!1,error:f.message},500)}}),V};import{Hono as V0}from"hono";var s=B("Service"),Hf=()=>{let V=new V0;return V.get("/",async($)=>{try{let f=Af(),J=Tf();return $.json({configured:f,current:J})}catch(f){return s.error("[ModelsRoutes] Failed to get models:",f),$.json({configured:[],current:null})}}),V.post("/",async($)=>{try{let f=await $.req.json(),{provider:J,name:Y,model:j,baseUrl:K,apiKey:X}=f;if(!j)throw new z("model is required");let Q=await L().addModel({provider:J||"openai-compatible",name:Y||j,model:j,baseUrl:K||void 0,apiKey:X||void 0});return $.json({success:!0,model:Q})}catch(f){throw s.error("[ModelsRoutes] Failed to add model:",f),f}}),V.put("/:modelId",async($)=>{try{let f=$.req.param("modelId"),J=await $.req.json(),{baseUrl:Y,apiKey:j,model:K}=J;return await L().updateModel(f,{baseUrl:Y||void 0,apiKey:j||void 0,model:K||void 0}),$.json({success:!0})}catch(f){throw s.error("[ModelsRoutes] Failed to update model:",f),f}}),V.delete("/:modelId",async($)=>{try{let f=$.req.param("modelId");return await L().removeModel(f),$.json({success:!0})}catch(f){throw s.error("[ModelsRoutes] Failed to delete model:",f),f}}),V};import{Hono as X0}from"hono";import{z as w}from"zod";import{Hono as J0}from"hono";import{streamSSE as Q0}from"hono/streaming";import{LRUCache as Y0}from"lru-cache";import{nanoid as I}from"nanoid";import{z as T}from"zod";var q=B("Service"),Z0=T.object({title:T.string().optional(),projectPath:T.string().optional()}),K0=T.object({content:T.string(),attachments:T.array(T.object({type:T.enum(["file","image","url"]),path:T.string().optional(),url:T.string().optional(),content:T.string().optional(),mimeType:T.string().optional(),name:T.string().optional()})).optional(),permissionMode:T.enum(["default","autoEdit","plan","yolo"]).optional()}),O0=T.object({title:T.string().optional()}),b=new Map,D=new Y0({max:100,ttl:1800000,dispose:(V,$)=>{if(V.status==="running"||V.status==="waiting_permission")V.abortController.abort(),q.debug(`[SessionRoutes] Run ${$} disposed due to cache eviction`)}}),G0=(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 jf(V){if(typeof V==="string")return V;return V.filter(($)=>$.type==="text").map(($)=>$.text).join(`
|
|
2
|
-
`)}function j0(V,$){let f=($??[]).filter((Y)=>Y.type==="image"&&typeof Y.content==="string").map((Y)=>({type:"image_url",image_url:{url:Y.content}}));if(f.length===0)return V;let J=[];if(V.trim())J.push({type:"text",text:V});return J.push(...f),J}var bf=()=>{let V=new J0,$=new Map,f=new Map,J=new Map,Y=async(Q)=>{let Z=$.get(Q.id);if(Z)return Z;let O=f.get(Q.id);if(!O)O=Gf.create({sessionId:Q.id,workspaceRoot:Q.projectPath}),f.set(Q.id,O);try{let G=await O;return $.set(Q.id,G),G}finally{if(f.get(Q.id)===O)f.delete(Q.id)}},j=async(Q,Z)=>{let O=b.get(Q);if(O)return O;let G=J.get(Q);if(!G)G=(async()=>{let N=(await S.listSessions()).find((U)=>U.sessionId===Q),x=N?.projectPath??Z,A=N?await S.loadSession(Q,x).catch(()=>[]):[],F={id:Q,projectPath:x,title:`Session ${Q.slice(0,6)}`,createdAt:N?new Date(N.firstMessageTime):new Date,messages:A,relationType:N?.relationType};return b.set(Q,F),F})(),J.set(Q,G);try{return await G}finally{if(J.get(Q)===G)J.delete(Q)}},K=(Q,Z,O,G=!1)=>{let N=I(12),x={id:N,sessionId:Q.id,status:"running",abortController:new AbortController,createdAt:new Date};return D.set(N,x),Q.currentRunId=N,N0(x,Q,Z,O,Y,{pendingInputOnly:G}).catch((A)=>{q.error(`[SessionRoutes] Run ${N} failed:`,A)}),x},X=async(Q)=>{let Z=Q.currentRunId?D.get(Q.currentRunId):void 0;if(Z&&(Z.status==="running"||Z.status==="waiting_permission"))return;if(!await Gf.hasPendingInbox(Q.projectPath,Q.id))return;let O=await Y(Q),G=Q.currentRunId?D.get(Q.currentRunId):void 0;if(G&&(G.status==="running"||G.status==="waiting_permission"))return;if(O.getPendingSteeringCount()===0||O.hasTurnOwner())return;K(Q,"","default",!0)};return V.get("/",async(Q)=>{try{let Z=await S.listSessions(),O=new Set(Z.filter((E)=>E.relationType==="subagent").map((E)=>E.sessionId)),G=Array.from(b.values()).filter((E)=>!O.has(E.id)&&E.relationType!=="subagent").map((E)=>({sessionId:E.id,projectPath:E.projectPath,title:E.title,parentId:void 0,relationType:void 0,status:void 0,agentType:void 0,model:void 0,messageCount:E.messages.length,firstMessageTime:E.createdAt.toISOString(),lastMessageTime:new Date().toISOString(),hasErrors:!1,isActive:!0})),N=new Set(G.map((E)=>E.sessionId)),x=Z.filter((E)=>!b.has(E.sessionId)&&!N.has(E.sessionId)&&E.relationType!=="subagent"),A=new Set(N),F=x.filter((E)=>{if(A.has(E.sessionId))return!1;return A.add(E.sessionId),!0}),U=[...G,...F];return Q.json(U)}catch(Z){return q.error("[SessionRoutes] Failed to list sessions:",Z),Q.json([])}}),V.post("/",async(Q)=>{try{let Z=await Q.req.json(),O=Z0.safeParse(Z);if(!O.success)throw new z("Invalid request body");let{title:G,projectPath:N}=O.data,x=I(12),A=N||Q.get("directory")||W(),F={id:x,projectPath:A,title:G||`Session ${x.slice(0,6)}`,createdAt:new Date,messages:[]};return b.set(x,F),Q.json({sessionId:x,projectPath:A,title:F.title,parentId:void 0,relationType:void 0,status:void 0,agentType:void 0,model:void 0,messageCount:0,firstMessageTime:F.createdAt.toISOString(),lastMessageTime:F.createdAt.toISOString(),hasErrors:!1})}catch(Z){throw q.error("[SessionRoutes] Failed to create session:",Z),Z}}),V.get("/:sessionId",async(Q)=>{let Z=Q.req.param("sessionId"),O=b.get(Z);if(O)return Q.json({sessionId:O.id,projectPath:O.projectPath,title:O.title,messageCount:O.messages.length,firstMessageTime:O.createdAt.toISOString(),lastMessageTime:new Date().toISOString(),hasErrors:!1,isActive:!0});try{let N=(await S.listSessions()).find((x)=>x.sessionId===Z);if(!N)throw new p("Session",Z);return Q.json(N)}catch(G){if(G instanceof p)throw G;throw q.error("[SessionRoutes] Failed to get session:",G),G}}),V.patch("/:sessionId",async(Q)=>{let Z=Q.req.param("sessionId");try{let O=await Q.req.json(),G=O0.safeParse(O);if(!G.success)throw new z("Invalid request body");let{title:N}=G.data,x=b.get(Z);if(x&&N)x.title=N;return Q.json({success:!0,title:N})}catch(O){throw q.error("[SessionRoutes] Failed to update session:",O),O}}),V.delete("/:sessionId",async(Q)=>{let Z=Q.req.param("sessionId"),O=b.get(Z);if(O?.currentRunId){let N=D.get(O.currentRunId);if(N)N.abortController.abort(),h.publish(Z,"run.cancelled",{runId:N.id}),D.delete(O.currentRunId)}try{await S.deleteSession(Z)}catch(N){q.warn("[SessionRoutes] Failed to delete session file:",N)}b.delete(Z),J.delete(Z),f.delete(Z);let G=$.get(Z);if(G){if(await G.dispose(),$.delete(Z),$.size===0)await y.getInstance().disconnectAll()}return Q.json({success:!0})}),V.get("/:sessionId/message",async(Q)=>{let Z=Q.req.param("sessionId");try{let O=await S.loadSession(Z);return Q.json(O)}catch(O){return q.error("[SessionRoutes] Failed to get messages:",O),Q.json([])}}),V.get("/:sessionId/events",async(Q)=>{let Z=Q.req.param("sessionId"),O=await j(Z,Q.get("directory")||W());return Q0(Q,async(G)=>{await G.writeSSE({data:JSON.stringify({type:"connected",properties:{sessionId:Z,timestamp:Date.now()}})});let x=h.subscribe((F)=>{if(F.sessionId!==Z)return;G.writeSSE({data:JSON.stringify({type:F.type,properties:{sessionId:F.sessionId,...F.properties}})}).catch(()=>{})});X(O).catch((F)=>{q.error(`[SessionRoutes] Failed to resume pending input for ${Z}:`,F)});let A=setInterval(()=>{if(!G.aborted)G.writeSSE({data:JSON.stringify({type:"heartbeat",properties:{timestamp:Date.now()}})}).catch(()=>{})},15000);G.onAbort(()=>{clearInterval(A),x()});while(!0)if(await new Promise((F)=>setTimeout(F,1000)),G.aborted)break})}),V.post("/:sessionId/message",async(Q)=>{let Z=Q.req.param("sessionId"),O=await Q.req.json(),G=K0.safeParse(O);if(!G.success)throw new z("Invalid message format");let{content:N,attachments:x,permissionMode:A}=G.data,F=A||"default",U=Q.get("directory")||W(),E=j0(N,x),C=await j(Z,U),M=C.currentRunId?D.get(C.currentRunId):void 0;if(M&&(M.status==="running"||M.status==="waiting_permission")){let R=await(await Y(C)).enqueueSteering(E,{allowBeforeTurn:!0});if(!R.accepted)return Q.json({status:"rejected",reason:R.reason??"turn_unavailable"},409);let r=I(12),a=R.queued;h.publish(Z,"message.created",{messageId:r,role:"user",content:jf(E)});let Yf=R.delivery==="next_turn"?"follow_up.queued":"steering.queued";if(h.publish(Z,Yf,{runId:M.id,messageId:r,queued:a}),R.delivery==="next_turn"&&M.status!=="running"&&M.status!=="waiting_permission")X(C).catch((Zf)=>{q.error(`[SessionRoutes] Failed to wake queued follow-up for ${Z}:`,Zf)});if(R.delivery==="next_turn")M.pendingFollowUpRequested=!0;return Q.json({runId:M.id,status:R.delivery==="next_turn"?"follow_up_queued":"steering_queued",queued:a},202)}let H=K(C,E,F);return Q.json({runId:H.id,status:"running"},202)}),V.post("/:sessionId/abort",async(Q)=>{let Z=Q.req.param("sessionId"),O=b.get(Z);if(O?.currentRunId){let G=D.get(O.currentRunId);if(G)G.abortController.abort(),G.status="cancelled",h.publish(Z,"run.cancelled",{runId:G.id})}return Q.json({success:!0})}),V.get("/:sessionId/status",async(Q)=>{let Z=Q.req.param("sessionId"),O=b.get(Z);if(!O?.currentRunId)return Q.json({sessionId:Z,status:"idle"});let G=D.get(O.currentRunId);return Q.json({sessionId:Z,runId:O.currentRunId,status:G?.status||"idle"})}),V};async function N0(V,$,f,J,Y,j={}){let{abortController:K,sessionId:X,id:Q}=V,Z=I(12),O=j.pendingInputOnly?void 0:I(12),G=(N,x)=>{h.publish(X,N,x)};try{if(!j.pendingInputOnly)G("message.created",{messageId:Z,role:"user",content:jf(f)});if(G("session.status",{status:"running"}),O)G("message.created",{messageId:O,role:"assistant",content:""});let N=await Y($),x=await zf.createWithRuntime(N,{sessionId:X}),A=async(M)=>{let H=I(12),nf=300000;V.status="waiting_permission";let R=new Promise((a)=>{let Yf=setTimeout(()=>{q.warn(`[SessionRoutes] Permission ${H} timed out after 300000ms`),G("permission.timeout",{requestId:H}),a({approved:!1,reason:"timeout"})},300000);V.pendingPermission={permissionId:H,resolve:(Zf)=>{clearTimeout(Yf),a(Zf)},details:M}});G("permission.asked",{requestId:H,toolName:M.toolName,description:M.message,args:M.args,details:M}),q.info(`[SessionRoutes] Permission request created: ${H}, runId: ${Q}`);let r=await R;return q.info(`[SessionRoutes] Permission response received: ${H}, approved: ${r.approved}`),V.status="running",V.pendingPermission=void 0,r},F={messages:[...$.messages],userId:"web-user",sessionId:X,workspaceRoot:$.projectPath,signal:K.signal,permissionMode:J,confirmationHandler:{requestConfirmation:A}},U=()=>{if(!O)O=I(12),G("message.created",{messageId:O,role:"assistant",content:""});return O},E=async(M)=>{switch(M.kind){case"content_delta":G("message.delta",{messageId:U(),delta:M.delta});break;case"thinking_delta":G("thinking.delta",{delta:M.delta});break;case"tool_start":if("function"in M.toolCall)G("tool.start",{messageId:U(),toolName:M.toolCall.function.name,toolCallId:M.toolCall.id,arguments:M.toolCall.function.arguments,toolKind:M.toolKind});break;case"tool_result":if("function"in M.toolCall)G("tool.result",{messageId:U(),toolName:M.toolCall.function.name,toolCallId:M.toolCall.id,success:M.result.success,summary:M.result.metadata?.summary,output:Cf(_f(M.toolCall.function.name,M.result)),metadata:G0(M.result.metadata)});break;case"token_usage":G("token.usage",{...M.usage});break;case"turn_start":G("turn.started",{turn:M.turn,maxTurns:M.maxTurns});break;case"steering_applied":G("steering.applied",{runId:Q,messageIds:M.messageIds,count:M.count,recovered:M.recovered,delivery:M.delivery,queued:N.getPendingSteeringCount()});break;case"follow_up_started":{if(O)G("message.complete",{messageId:O}),O=void 0;for(let H of M.messages){if(!H.recovered||H.persisted)continue;G("message.created",{messageId:H.id,role:"user",content:jf(H.content),recovered:!0})}G("follow_up.started",{runId:Q,queued:M.queued,recovered:M.recovered}),U();break}case"compaction":G(M.phase==="start"?"compaction.started":"compaction.completed",{});break;case"model_fallback":G("model.fallback",{});break;case"task_update":G("task.updated",{tasks:M.tasks});break;default:break}},C=await Of(x.chatStream(f,F,{stream:!0,pendingInputOnly:j.pendingInputOnly}),E);for(let M=0;M<20;M++){let H=V.pendingFollowUpRequested===!0;if(V.pendingFollowUpRequested=!1,N.getPendingSteeringCount()===0){if(!H)break;continue}if(K.signal.aborted)break;C=await Of(x.chatStream("",F,{stream:!0,pendingInputOnly:!0}),E)}if($.messages=[...F.messages],O)G("message.complete",{messageId:O});G("thinking.completed",{}),V.status="completed",G("session.completed",{runId:Q,outputTruncated:C.metadata?.outputTruncated??!1}),G("session.status",{status:"idle"})}catch(N){q.error("[SessionRoutes] Agent execution error:",N),V.status="failed",G("session.error",{error:N instanceof Error?N.message:"Unknown error"}),G("session.status",{status:"error"})}}function wf(V,$,f){q.info(`[SessionRoutes] Looking for permission ${$} in session ${V}`),q.info(`[SessionRoutes] Active runs: ${D.size}`);for(let[J,Y]of D.entries())if(q.info(`[SessionRoutes] Checking run ${J}: sessionId=${Y.sessionId}, pendingPermission=${Y.pendingPermission?.permissionId}`),Y.sessionId===V&&Y.pendingPermission?.permissionId===$)return Y.pendingPermission.resolve(f),q.info(`[SessionRoutes] Permission ${$} responded, runId: ${Y.id}`),!0;return q.error(`[SessionRoutes] Permission not found: ${$}`),!1}var Nf=B("Service"),M0=w.object({approved:w.boolean(),remember:w.boolean().optional(),scope:w.enum(["once","session"]).optional(),targetMode:w.enum(["default","autoEdit","plan","yolo"]).optional(),feedback:w.string().optional(),answers:w.record(w.union([w.string(),w.array(w.string())])).optional()}),Df=()=>{let V=new X0;return V.post("/:permissionId",async($)=>{let f=$.req.param("permissionId"),J=$.req.query("sessionId");Nf.info(`[PermissionRoutes] Received permission response: permissionId=${f}, sessionId=${J}`);try{let Y=await $.req.json(),j=M0.safeParse(Y);if(!j.success)throw new z("Invalid permission response format");let{approved:K,remember:X,scope:Q,targetMode:Z,feedback:O,answers:G}=j.data;if(!J)throw new z("sessionId query parameter is required");if(!wf(J,f,{approved:K,reason:O,scope:Q,targetMode:Z,feedback:O,answers:G}))throw new p("Permission request",f);return Nf.info(`[PermissionRoutes] Permission ${f} ${K?"approved":"denied"}`),$.json({success:!0,approved:K,remember:X})}catch(Y){throw Nf.error("[PermissionRoutes] Failed to respond to permission:",Y),Y}}),V};import{Hono as E0}from"hono";var Rf=B("Service"),yf=()=>{let V=new E0;return V.get("/",async($)=>{try{let f=await mf();return $.json(f)}catch(f){return Rf.error("[ProviderRoutes] Failed to list providers:",f),$.json([])}}),V.get("/:provider/models",async($)=>{let f=$.req.param("provider");try{let J=await Lf(f);return $.json(J)}catch(J){return Rf.error("[ProviderRoutes] Failed to list models:",J),$.json([])}}),V};import{Hono as F0}from"hono";import*as P from"node:fs/promises";import{homedir as x0}from"node:os";import*as $f from"node:path";var v=B("Service"),Xf=$f.join(x0(),".blade","skills-config.json");async function kf(){try{let V=await P.readFile(Xf,"utf-8");return JSON.parse(V)}catch{return{disabled:[]}}}async function U0(V){await P.mkdir($f.dirname(Xf),{recursive:!0}),await P.writeFile(Xf,JSON.stringify(V,null,2))}async function B0(V,$){let f=await kf();if($)f.disabled=f.disabled.filter((J)=>J!==V);else if(!f.disabled.includes(V))f.disabled.push(V);await U0(f)}var c=null,W0=300000;async function q0(){if(c&&Date.now()-c.timestamp<W0)return c.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 v.warn(`GitHub API returned ${V.status}`),c?.data||[];let $=await V.json(),f=[];for(let J of $){if(J.type!=="dir")continue;let Y=`Official ${J.name} skill`;try{let j=await fetch(`https://raw.githubusercontent.com/anthropics/skills/main/skills/${J.name}/SKILL.md`,{headers:{"User-Agent":"Blade-Skills-Catalog"}});if(j.ok){let X=(await j.text()).match(/^#[^\n]*\n+([^\n#]+)/);if(X)Y=X[1].trim().slice(0,100)}}catch{}f.push({name:J.name,description:Y,tag:"Official",author:"Anthropic"})}return c={data:f,timestamp:Date.now()},f}catch(V){return v.warn("Failed to fetch skills catalog from GitHub:",V),c?.data||[]}}var Sf=()=>{let V=new F0;return V.get("/",async($)=>{try{let f=ff();await f.initialize();let J=f.getAll(),Y=await kf(),j=J.map((K)=>({id:K.name,name:K.name,enabled:!Y.disabled.includes(K.name),description:K.description||"",version:K.version||"1.0.0",provider:"Local",location:K.source==="builtin"?"Built-in":K.basePath,capabilities:["prompts"],allowedTools:K.allowedTools||[]}));return $.json(j)}catch(f){return v.error("[SkillsRoutes] Failed to get skills:",f),$.json([])}}),V.post("/:name/toggle",async($)=>{try{let f=$.req.param("name"),J=await $.req.json();return await B0(f,J.enabled),$.json({success:!0,enabled:J.enabled})}catch(f){return v.error("[SkillsRoutes] Failed to toggle skill:",f),$.json({success:!1,error:f.message},500)}}),V.delete("/:name",async($)=>{try{let f=$.req.param("name"),J=`${process.env.HOME}/.blade/skills/${f}`;return await P.rm(J,{recursive:!0,force:!0}),await ff().refresh(),$.json({success:!0})}catch(f){return v.error("[SkillsRoutes] Failed to uninstall skill:",f),$.json({success:!1,error:f.message},500)}}),V.post("/install",async($)=>{try{let f=await $.req.json(),J=Pf(),Y=ff(),j=!1;if(f.source==="catalog"&&f.name){if(j=await J.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 J.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 J.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 Y.refresh(),$.json({success:!0})}catch(f){return v.error("[SkillsRoutes] Failed to install skill:",f),$.json({success:!1,error:f.message},500)}}),V.get("/catalog",async($)=>{try{let f=await q0();return $.json(f)}catch(f){return v.error("[SkillsRoutes] Failed to get catalog:",f),$.json([])}}),V};import A0 from"fast-glob";import{Hono as T0}from"hono";import{execSync as H0}from"node:child_process";import{readdir as _0}from"node:fs/promises";import Vf from"node:path";var i=B("Service"),C0=(V)=>{try{return H0("git rev-parse --abbrev-ref HEAD",{cwd:V,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||null}catch{return null}},z0=[...Jf.map((V)=>`${V}/**`),...Jf,...Mf.map((V)=>`**/${V}`)],b0=new Set(["/theme","/model","/permissions","/mcp","/skills","/exit","/resume","/ide","/login","/logout"]),vf=()=>{let V=new T0;return V.get("/commands",async($)=>{try{let f=$.req.query("q")||"",J=If(f).filter((Y)=>!b0.has(Y.command));return $.json(J)}catch(f){return i.error("[SuggestionsRoutes] Failed to get command suggestions:",f),$.json([])}}),V.get("/files",async($)=>{try{let f=$.req.query("q")||"",J=$.get("directory")||W(),Y=Math.min(Number($.req.query("limit"))||100,1000),K=(await A0("**/*",{cwd:J,dot:!1,followSymbolicLinks:!1,onlyFiles:!1,markDirectories:!0,unique:!0,ignore:z0})).map((Z)=>Z.replace(/\\/g,"/"));if(!f)return $.json(K.slice(0,Y));let X=f.toLowerCase(),Q=K.filter((Z)=>Z.toLowerCase().includes(X)).slice(0,Y);return $.json(Q)}catch(f){return i.error("[SuggestionsRoutes] Failed to get file suggestions:",f),$.json([])}}),V.get("/files/tree",async($)=>{try{let f=$.get("directory")||W(),J=$.req.query("path")||"",Y=J?Vf.join(f,J):f,K=(await _0(Y,{withFileTypes:!0})).map((Z)=>({name:Z.name,path:J?`${J}/${Z.name}`:Z.name,type:Z.isDirectory()?"dir":"file"}));K.sort((Z,O)=>{if(Z.type!==O.type)return Z.type==="dir"?-1:1;return Z.name.localeCompare(O.name)});let X=new Set(Jf),Q=K.filter((Z)=>{let O=Z.name;if(O.startsWith("."))return!1;if(X.has(O))return!1;for(let G of Mf)if(O.match(new RegExp(G.replace("*",".*"))))return!1;return!0});return $.json(Q)}catch(f){return i.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 J=$.get("directory")||W(),Y=Vf.resolve(J,f),j=Vf.relative(J,Y);if(j.startsWith("..")||Vf.isAbsolute(j))return $.json({error:"Invalid file path"},400);let K=hf(),X=await K.stat(Y);if(!X?.isFile)return $.json({error:"File not found"},404);let Q=200000,Z=await K.readTextFile(Y),O=Z.length>Q;return $.json({path:f,content:O?Z.slice(0,Q):Z,truncated:O,size:X.size})}catch(f){return i.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")||W(),J=C0(f);return $.json({branch:J})}catch(f){return i.error("[SuggestionsRoutes] Failed to get git info:",f),$.json({branch:null})}}),V};import{Hono as w0}from"hono";var k=B("Service"),o=new Map,uf=2097152,pf=65536;function gf(){return typeof globalThis.Bun<"u"}async function D0(V,$,f){if(gf()){let{spawn:j}=await import("bun-pty"),K=j(V,$,{name:"xterm-256color",cwd:f.cwd,env:f.env});return{pid:K.pid,write:(X)=>K.write(X),resize:(X,Q)=>K.resize(X,Q),kill:()=>K.kill(),onData:(X)=>K.onData(X),onExit:(X)=>K.onExit(X)}}let Y=(await import("node-pty")).spawn(V,$,{name:"xterm-256color",cwd:f.cwd,env:f.env,cols:80,rows:24});return{pid:Y.pid,write:(j)=>Y.write(j),resize:(j,K)=>Y.resize(j,K),kill:()=>Y.kill(),onData:(j)=>{Y.onData(j)},onExit:(j)=>{Y.onExit(j)}}}var xf=void 0,Ff;if(gf())try{let{createBunWebSocket:V}=await import("hono/bun"),$=V();Ff=$.upgradeWebSocket,xf=$.websocket}catch(V){k.warn("[Terminal] Failed to initialize Bun WebSocket support:",V)}async function df(V,$){let f=`term-${Date.now()}`;k.info(`[Terminal] New connection: ${f}, cwd: ${V}`);let J=process.platform==="win32"?"powershell.exe":process.env.SHELL||"/bin/zsh",Y=J.endsWith("sh")?["-l"]:[],j=await D0(J,Y,{cwd:V,env:{...process.env,TERM:"xterm-256color",COLORTERM:"truecolor"}}),K={id:f,process:j,cwd:V,buffer:"",subscribers:new Set};if(o.set(f,K),K.subscribers.add($),j.onData((X)=>{let Q=!1;for(let Z of K.subscribers)try{Z.send(X),Q=!0}catch{K.subscribers.delete(Z)}if(Q)return;if(K.buffer+=X,K.buffer.length>uf)K.buffer=K.buffer.slice(-uf)}),j.onExit(({exitCode:X})=>{k.info(`[Terminal] Process exited: ${f}, code: ${X}`);for(let Q of K.subscribers)try{Q.close()}catch{}o.delete(f)}),K.buffer){let X=K.buffer;K.buffer="";for(let Q=0;Q<X.length;Q+=pf)$.send(X.slice(Q,Q+pf))}return{session:K,cleanup:()=>{if(k.info(`[Terminal] Connection closed: ${f}`),K.subscribers.delete($),K.subscribers.size===0){try{K.process.kill()}catch{}o.delete(f)}}}}function lf(V,$){V.on("connection",async(f,J)=>{let Y=new URL(J.url||"/",`http://${J.headers.host}`);if(!Y.pathname.endsWith("/terminal/ws")){f.close();return}let j=Y.searchParams.get("cwd")||$()||W();try{let{session:K,cleanup:X}=await df(j,{send:(Q)=>f.send(Q),close:()=>f.close()});f.on("message",(Q)=>{try{K.process.write(String(Q))}catch(Z){k.error("[Terminal] Failed to write to PTY:",Z)}}),f.on("close",X),f.on("error",X)}catch(K){k.error("[Terminal] Failed to spawn PTY:",K),f.close()}})}var cf=()=>{let V=new w0;if(V.get("/status",($)=>{let f=Array.from(o.values()).map((J)=>({id:J.id,cwd:J.cwd}));return $.json({active:f.length,terminals:f})}),V.post("/kill/:terminalId",($)=>{let f=$.req.param("terminalId"),J=o.get(f);if(J){try{J.process.kill()}catch{}for(let Y of J.subscribers)Y.close();return o.delete(f),$.json({success:!0})}return $.json({success:!1,error:"Terminal not found"},404)}),Ff)V.get("/ws",Ff(($)=>{let f=$.req.query("cwd")||$.get("directory")||W(),J;return{async onOpen(Y,j){try{J=await df(f,{send:(K)=>j.send(K),close:()=>j.close()})}catch(K){k.error("[Terminal] Failed to spawn PTY:",K),j.close()}},onMessage(Y){if(!J)return;try{J.session.process.write(String(Y.data))}catch(j){k.error("[Terminal] Failed to write to PTY:",j)}},onClose(){J?.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 _=B("Service"),Uf=[];function I0(){let V=P0(S0(import.meta.url)),$=[u(V,"web"),u(W(),"dist/web"),u(W(),"packages/cli/dist/web")];for(let f of $){let J=u(f,"index.html");if(af(J)){if(Qf(J,"utf-8").includes("/assets/"))return _.debug(`[Server] Found web dist at: ${f}`),f}}return null}function v0(){let V=new R0;V.onError((f,J)=>{if(_.error("[Server] Request error:",f),f instanceof t)return J.json(f.toObject(),f.statusCode);let Y=f instanceof Error?f.message:String(f);return J.json({error:{code:"INTERNAL_ERROR",message:Y}},500)}),V.use(async(f,J)=>{let Y=process.env.BLADE_SERVER_PASSWORD;if(!Y)return J();let j=f.req.path;if(j==="/"||j.startsWith("/assets/")||j.endsWith(".html")||j.endsWith(".js")||j.endsWith(".css"))return J();let K=f.req.header("Authorization");if(!K?.startsWith("Basic "))return f.header("WWW-Authenticate",'Basic realm="Blade Server"'),f.json({error:{code:"UNAUTHORIZED",message:"Authentication required"}},401);let X=Buffer.from(K.slice(6),"base64").toString(),[Q,Z]=X.split(":"),O=process.env.BLADE_SERVER_USERNAME??"blade";if(Q!==O||Z!==Y)return f.json({error:{code:"UNAUTHORIZED",message:"Invalid credentials"}},401);return J()}),V.use(async(f,J)=>{let Y=f.req.path==="/health"||f.req.path==="/global/health"||f.req.path.startsWith("/assets/");if(!Y)_.debug(`[Server] ${f.req.method} ${f.req.path}`);let j=Date.now();if(await J(),!Y){let K=Date.now()-j;_.debug(`[Server] ${f.req.method} ${f.req.path} - ${f.res.status} (${K}ms)`)}}),V.use(m0({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(Uf.includes(f))return f;return}})),V.use(async(f,J)=>{let Y=f.req.query("directory")||f.req.header("x-blade-directory")||W();try{Y=decodeURIComponent(Y)}catch{}return f.set("directory",Y),J()}),V.route("/global",Wf()),V.route("/sessions",bf()),V.route("/configs",Bf()),V.route("/permissions",Df()),V.route("/providers",yf()),V.route("/models",Hf()),V.route("/suggestions",vf()),V.route("/terminal",cf()),V.route("/mcp",qf()),V.route("/skills",Sf()),V.get("/health",(f)=>{return f.json({healthy:!0,version:l()})});let $=I0();if($)_.info(`[Server] Serving static files from ${$}`),V.get("/assets/*",(f)=>{let J=u($,f.req.path);if(!af(J))return f.json({error:{code:"NOT_FOUND",message:`File not found: ${f.req.path}`}},404);let Y=Qf(J),j=k0(J).toLowerCase(),X={".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(Y,{headers:{"Content-Type":X,"Cache-Control":"public, max-age=31536000, immutable"}})}),V.get("/",(f)=>{let J=u($,"index.html"),Y=Qf(J,"utf-8");return f.html(Y)}),V.get("*",(f)=>{let J=f.req.path;if(J.includes("."))return f.json({error:{code:"NOT_FOUND",message:`File not found: ${J}`}},404);let Y=u($,"index.html"),j=Qf(Y,"utf-8");return f.html(j)});else _.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:l(),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=y0(),$=[];for(let f of Object.keys(V)){let J=V[f];if(!J)continue;for(let Y of J){if(Y.internal||Y.family!=="IPv4")continue;if(Y.address.startsWith("172."))continue;$.push(Y.address)}}return $}function of(){return typeof globalThis.Bun<"u"}function rf(V,$){let f=globalThis.Bun,J=(j)=>{try{return f.serve({hostname:$.hostname,port:j,fetch:V.fetch,idleTimeout:0,websocket:xf})}catch(K){_.error("Failed to start Bun server:",K);return}},Y=$.port===0?J(4096)??J(0):J($.port);if(!Y)throw Error(`Failed to start Bun server on port ${$.port}`);return{url:Y.url,port:Y.port,hostname:Y.hostname,stop:async()=>{Y.stop(!0)}}}function p0(V,$){return new Promise((f,J)=>{let Y=L0(async(Z,O)=>{let G=new URL(Z.url||"/",`http://${Z.headers.host}`),N=new Headers;for(let[F,U]of Object.entries(Z.headers))if(U)if(Array.isArray(U))for(let E of U)N.append(F,E);else N.set(F,U);let x;if(Z.method!=="GET"&&Z.method!=="HEAD")x=(await new Promise((U)=>{let E=[];Z.on("data",(C)=>E.push(C)),Z.on("end",()=>U(Buffer.concat(E)))})).toString();let A=new Request(G.toString(),{method:Z.method,headers:N,body:x});try{let F=await V.fetch(A);if(O.statusCode=F.status,F.headers.forEach((U,E)=>{O.setHeader(E,U)}),F.body){let U=F.body.getReader(),E=async()=>{let{done:C,value:M}=await U.read();if(C){O.end();return}return O.write(M),E()};await E()}else{let U=await F.text();O.end(U)}}catch(F){_.error("[Server] Node request error:",F),O.statusCode=500,O.end(JSON.stringify({error:{code:"INTERNAL_ERROR",message:"Internal server error"}}))}}),j=new h0({noServer:!0}),K=W();lf(j,()=>K),Y.on("upgrade",(Z,O,G)=>{if(new URL(Z.url||"/",`http://${Z.headers.host}`).pathname==="/terminal/ws")j.handleUpgrade(Z,O,G,(x)=>{j.emit("connection",x,Z)});else O.destroy()});let X=(Z)=>{return new Promise((O,G)=>{Y.once("error",(N)=>{if(N.code==="EADDRINUSE")G(N);else G(N)}),Y.listen(Z,$.hostname,()=>{let N=Y.address();if(N&&typeof N==="object")O(N.port);else O(Z)})})};(async()=>{let Z;if($.port===0)try{Z=await X(4096)}catch{Z=await X(0)}else Z=await X($.port);let O=new URL(`http://${$.hostname==="0.0.0.0"?"localhost":$.hostname}:${Z}`);f({url:O,port:Z,hostname:$.hostname,stop:async()=>{return new Promise((G)=>{j.close(()=>{Y.close(()=>G())})})}})})().catch(J)})}var tf;((yV)=>{let V,$;function f(){if(!$)$=v0();return $}yV.getApp=f;function J(K){Uf=K.cors??[];let X=f();if(of())V=rf(X,K),_.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 Q=V;return{url:Q.url,port:Q.port,hostname:Q.hostname,stop:async()=>{if(V)await V.stop(),V=void 0,$=void 0,_.info("[Server] Blade server stopped")}}}yV.listen=J;async function Y(K){Uf=K.cors??[];let X=f();if(of())V=rf(X,K),_.info(`[Server] Blade server listening on ${V.url} (Bun runtime)`);else V=await p0(X,K),_.info(`[Server] Blade server listening on ${V.url} (Node.js runtime)`);let Q=V;return{url:Q.url,port:Q.port,hostname:Q.hostname,stop:async()=>{if(V)await V.stop(),V=void 0,$=void 0,_.info("[Server] Blade server stopped")}}}yV.listenAsync=Y;function j(){return V!==void 0}yV.isRunning=j})(tf||={});export{g0 as f,d0 as g,u0 as h,tf as i};
|