blade-code 0.4.4 → 0.4.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/blade.js +2 -2
- package/dist/{chunk-tf0m57f5.js → chunk-2e3pajfb.js} +1 -1
- package/dist/{chunk-kd1t45br.js → chunk-6yvqtcx0.js} +1 -1
- package/dist/{chunk-ehcjnwnr.js → chunk-9syksrkj.js} +1 -1
- package/dist/chunk-c6ts8bd9.js +26 -0
- package/dist/{chunk-420vamtq.js → chunk-cfbp6h36.js} +1 -1
- package/dist/{chunk-8pn5m426.js → chunk-ctacwg1h.js} +1 -1
- package/dist/{chunk-5xc0kzdt.js → chunk-cwafz1g3.js} +1 -1
- package/dist/{chunk-5zkcs06z.js → chunk-d1hwbcne.js} +1 -1
- package/dist/{chunk-9mrna4y3.js → chunk-e38t8r4f.js} +1 -1
- package/dist/{chunk-mvyxksrz.js → chunk-f35tdzfy.js} +1 -1
- package/dist/{chunk-jvbx3h56.js → chunk-gkd5eew1.js} +140 -114
- package/dist/chunk-hhgbhadg.js +76 -0
- package/dist/{chunk-7637p6w5.js → chunk-hpafbk1w.js} +1 -1
- package/dist/{chunk-q4hrt6r4.js → chunk-ksd0cxtf.js} +1 -1
- package/dist/{chunk-52k9k0w8.js → chunk-mjgch1nt.js} +1 -1
- package/dist/{chunk-zs7xeymy.js → chunk-n466beq9.js} +1 -1
- package/dist/{chunk-094ekgv6.js → chunk-nhp35rk0.js} +2 -2
- package/dist/chunk-pe6dnssd.js +1 -0
- package/dist/chunk-pkmw32r0.js +8 -0
- package/dist/chunk-pmtfesmc.js +1 -0
- package/dist/{chunk-jz59sjzb.js → chunk-r8wmg3fc.js} +1 -1
- package/dist/{chunk-7snnj126.js → chunk-tf74ehds.js} +1 -1
- package/dist/{chunk-8jwqy5d0.js → chunk-v1c9xwen.js} +1 -1
- package/dist/chunk-vs5a1443.js +157 -0
- package/dist/{chunk-tph4ngbj.js → chunk-x2jkbn5c.js} +1 -1
- package/dist/{chunk-vwn39c84.js → chunk-xcpjsrem.js} +1 -1
- package/dist/{chunk-n8na8c5h.js → chunk-xpbgzgfz.js} +1 -1
- package/dist/{chunk-vs2x9sxb.js → chunk-yf7cz40m.js} +1 -1
- package/dist/{chunk-4jh0h16z.js → chunk-yhwrv3qf.js} +1 -1
- package/dist/{chunk-z1qz8p1j.js → chunk-ze1tddc3.js} +1 -1
- package/package.json +2 -2
- package/dist/chunk-5mtjqqav.js +0 -8
- package/dist/chunk-76emdpxa.js +0 -76
- package/dist/chunk-92kjp66d.js +0 -1
- package/dist/chunk-a5b9fkp3.js +0 -157
- package/dist/chunk-h3ccyfqj.js +0 -1
- package/dist/chunk-y5g06jmk.js +0 -24
package/dist/blade.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{n as B}from"./chunk-
|
|
2
|
+
import{n as B}from"./chunk-2e3pajfb.js";import{$ as F,_ as D}from"./chunk-esnkk33h.js";import"./chunk-hhgbhadg.js";import"./chunk-c6ts8bd9.js";import"./chunk-nhp35rk0.js";import{vb as E,xb as q}from"./chunk-7ycmx7c2.js";import{Ab as H}from"./chunk-set7v1rf.js";import{Db as J}from"./chunk-j2ag7hh6.js";var X=process.argv.slice(2),$=v(X),w=$!==null;if($!==null)H.setGlobalDebug($);function v(Q){for(let W=0;W<Q.length;W+=1){let T=Q[W];if(T==="--debug"||T==="-d"){let N=Q[W+1];return N&&!N.startsWith("-")?N:!0}if(T.startsWith("--debug="))return T.slice(8)||!0}return null}function C(Q){return Q.length===1&&(Q[0]==="--version"||Q[0]==="-V")}function z(Q,...W){return Q.some((T)=>W.some((N)=>T===N||T.startsWith(`${N}=`)))}async function f(){if(C(X)){let{getVersion:K}=await import("./chunk-xpbgzgfz.js");console.log(K());return}let Q=D(process.cwd());if(F(Q),E(q()),process.getuid&&process.getuid()===0){let K=!!process.env.SUDO_USER,U=!!process.env.BLADE_ALLOW_ROOT;if(K&&!U)console.error(""),console.error("Error: 请不要使用 sudo 运行 blade"),console.error(""),console.error("原因:"),console.error(" 使用 sudo 会创建属于 root 的配置文件,"),console.error(" 导致普通用户无法访问。"),console.error(""),console.error("正确用法:"),console.error(" blade # 直接运行,不要加 sudo"),console.error(""),console.error("如果遇到权限错误,请运行:"),console.error(" sudo chown -R $USER:$USER ~/.blade/"),console.error(""),console.error("如果你确实需要以 root 运行(容器/CI),设置环境变量:"),console.error(" BLADE_ALLOW_ROOT=1 blade"),console.error(""),process.exit(1)}if(B(),z(X,"--headless")){let{handleHeadlessMode:K}=await import("./chunk-yf7cz40m.js");if(await K())return}if(z(X,"--print","-p")){let{handlePrintMode:K}=await import("./chunk-f35tdzfy.js");if(await K())return}if(X.includes("--acp")){let{runAcpIntegration:K}=await import("./chunk-hpafbk1w.js");await K();return}let[{default:W},{hideBin:T},{cliConfig:N,globalOptions:G},{loadConfiguration:I,validateOutput:L,validatePermissions:M},{doctorCommands:_},{installCommands:y},{mcpCommands:R},{serveCommand:S},{updateCommands:k},{webCommand:O}]=await Promise.all([import("yargs"),import("yargs/helpers"),import("./chunk-pe6dnssd.js"),import("./chunk-n466beq9.js"),import("./chunk-d1hwbcne.js"),import("./chunk-g5pasj7t.js"),import("./chunk-ctacwg1h.js"),import("./chunk-tf74ehds.js"),import("./chunk-bhjw4b73.js"),import("./chunk-ze1tddc3.js")]),x=W(T(process.argv)).scriptName(N.scriptName).usage(N.usage).version(N.version).locale(N.locale).showHelpOnFail(N.showHelpOnFail).demandCommand(0,"").recommendCommands().strict(N.strict).parserConfiguration({"populate--":!0}).options(G).middleware([M,I,L]).command(R).command(_).command(k).command(y).command(O).command(S).completion("completion",!1).help("help","Show help").alias("help","h").alias("version","V").fail((K,U,Z)=>{if(U){if(console.error("An error occurred:"),console.error(U.message),w&&U.stack)console.error(`
|
|
3
3
|
Stack trace:`),console.error(U.stack);else console.error(`
|
|
4
4
|
Run with --debug to show the stack trace.`);process.exit(1)}if(K)console.error("Error: Invalid arguments:"),console.error(K),console.error(`
|
|
5
|
-
Hint: Did you mean:`),Z.showHelp(),process.exit(1)}).command("$0",!1,()=>{},async(K)=>{let U=K._.slice(1),Z=U.length>0?U.join(" "):void 0,V=import("./chunk-th432d0b.js").then(({checkVersionOnStartup:A})=>A()),[{render:b},{createElement:P},{AppWrapper:h}]=await Promise.all([import("ink"),import("react"),import("./chunk-
|
|
5
|
+
Hint: Did you mean:`),Z.showHelp(),process.exit(1)}).command("$0",!1,()=>{},async(K)=>{let U=K._.slice(1),Z=U.length>0?U.join(" "):void 0,V=import("./chunk-th432d0b.js").then(({checkVersionOnStartup:A})=>A()),[{render:b},{createElement:P},{AppWrapper:h}]=await Promise.all([import("ink"),import("react"),import("./chunk-vs5a1443.js")]),Y={...K,initialMessage:Z,debug:K.debug,print:Boolean(K.print),versionCheckPromise:V};delete Y._,delete Y.$0,delete Y.message,b(P(h,Y),{patchConsole:!0,exitOnCtrlC:!1,alternateBuffer:!1})});try{await x.parse()}catch(K){console.error("Error: Parse error:",K),process.exit(1)}}if(J.main==J.module)f().catch(console.error);export{f as main};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{va as Q}from"./chunk-
|
|
1
|
+
import{va as Q}from"./chunk-hhgbhadg.js";import{nb as U}from"./chunk-nhp35rk0.js";import{xb as O}from"./chunk-7ycmx7c2.js";import{Bb as N,zb as K}from"./chunk-set7v1rf.js";function Y(){if(process.stdin.isTTY&&typeof process.stdin.setRawMode==="function")try{process.stdin.setRawMode(!1)}catch{}process.stdout.write("\x1B[<u"),process.stdout.write("\x1B[>4;0m"),process.stdout.write("\x1B[?2004l"),process.stdout.write("\x1B[?1l\x1B>"),process.stdout.write("\x1B[?25h"),process.stdout.write("\x1B[0m")}var A=N("Service");function Z(b){switch(b){case"SIGINT":return"ctrl_c";case"esc":return"esc";case"uncaughtException":case"unhandledRejection":return"error";case"SIGTERM":case"normal":default:return"user_exit"}}class D{static instance=null;cleanupHandlers=[];isShuttingDown=!1;initialized=!1;lastSigintTime=0;SIGINT_DOUBLE_CLICK_WINDOW=3000;constructor(){}static getInstance(){if(!D.instance)D.instance=new D;return D.instance}initialize(){if(this.initialized){A.debug("[GracefulShutdown] 已初始化,跳过重复初始化");return}process.on("uncaughtException",(b)=>{this.handleFatalError("uncaughtException",b)}),process.on("unhandledRejection",(b)=>{let q=b instanceof Error?b:Error(String(b));this.handleFatalError("unhandledRejection",q)}),process.on("SIGTERM",()=>{A.info("[GracefulShutdown] 收到 SIGTERM 信号"),this.shutdown("SIGTERM",0)}),process.on("SIGINT",()=>{let b=Date.now();if(b-this.lastSigintTime<this.SIGINT_DOUBLE_CLICK_WINDOW)A.info("[GracefulShutdown] 收到第二次 SIGINT 信号,执行退出"),this.shutdown("SIGINT",0);else A.info("[GracefulShutdown] 收到第一次 SIGINT 信号,再按一次退出"),this.lastSigintTime=b,console.log(`
|
|
2
2
|
再按一次 Ctrl+C 退出
|
|
3
3
|
`)}),this.initialized=!0,A.debug("[GracefulShutdown] 全局错误处理器已初始化")}registerCleanup(b){return this.cleanupHandlers.push(b),A.debug(`[GracefulShutdown] 注册清理函数,当前共 ${this.cleanupHandlers.length} 个`),()=>{let q=this.cleanupHandlers.indexOf(b);if(q!==-1)this.cleanupHandlers.splice(q,1),A.debug(`[GracefulShutdown] 取消注册清理函数,剩余 ${this.cleanupHandlers.length} 个`)}}handleFatalError(b,q){if(this.isShuttingDown){console.error(`[GracefulShutdown] 退出过程中发生额外错误 (${b}):`,q);return}if(console.error(""),console.error("═".repeat(60)),console.error(`Uncaught error (${b})`),console.error("═".repeat(60)),console.error(""),console.error("错误信息:",q.message),console.error(""),q.stack)console.error("堆栈跟踪:"),console.error(q.stack);console.error(""),console.error("═".repeat(60)),console.error(""),this.shutdown(b,1)}async shutdown(b,q=0){if(this.isShuttingDown){A.debug("[GracefulShutdown] 已在退出过程中,跳过重复退出");return}this.isShuttingDown=!0,A.info(`[GracefulShutdown] 开始优雅退出 (原因: ${b})`);try{await K()}catch(z){}try{let z=U.getInstance();if(z.isEnabled()){let F=Q(),W=F.session?.sessionId||"unknown",X=F.config?.config?.permissionMode||"default";await z.executeSessionEndHooks(Z(b),{projectDir:O(),sessionId:W,permissionMode:X})}}catch(z){console.error("[GracefulShutdown] SessionEnd hooks 执行失败:",z)}let B=5000,V=new Promise((z,F)=>{setTimeout(()=>{F(Error(`清理超时 (${B}ms)`))},B)});try{let z=this.runCleanupHandlers();await Promise.race([z,V])}catch(z){console.error("[GracefulShutdown] 清理过程中发生错误:",z)}finally{Y(),setTimeout(()=>{process.exit(q)},100)}}async runCleanupHandlers(){let b=[...this.cleanupHandlers].reverse();for(let q of b)try{let B=q();if(B instanceof Promise)await B}catch(B){console.error("[GracefulShutdown] 清理函数执行失败:",B)}}isExiting(){return this.isShuttingDown}reset(){this.isShuttingDown=!1,this.cleanupHandlers=[],this.initialized=!1}}var J=()=>{return D.getInstance()},H=(b)=>{return J().registerCleanup(b)},P=()=>{J().initialize()},L=(b=0)=>{J().shutdown("normal",b)};
|
|
4
4
|
export{J as l,H as m,P as n,L as o};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var e={name:"blade-code",version:"0.4.
|
|
1
|
+
var e={name:"blade-code",version:"0.4.6",private:!1,description:"🗡️ Blade Code - 智能代码助手命令行工具",type:"module",bin:{blade:"dist/blade.js"},files:["dist","vendor/ripgrep/**","README.md"],scripts:{dev:"node scripts/run-bun.js --watch src/blade.tsx","dev:serve":"node scripts/run-bun.js --watch src/blade.tsx serve --port 4097",build:"rm -rf dist && node scripts/run-bun.js run scripts/build.ts",start:"node scripts/run-bun.js run dist/blade.js",test:"node scripts/test.js","test:all":"vitest run --config vitest.config.ts","test:unit":"node scripts/test.js unit","test:integration":"node scripts/test.js integration","test:cli":"node scripts/test.js cli","test:headless-core":"node scripts/test.js headlessCore","test:e2e":"node scripts/test.js e2e","test:performance":"node scripts/test.js performance","test:snapshot":"node scripts/test.js snapshot","test:security":"node scripts/test.js security","test:coverage":"node scripts/test.js all --coverage","test:watch":"vitest --watch --config vitest.config.ts","benchmark:repo":"node scripts/run-bun.js run scripts/run-real-repo-benchmark.ts","test:update-snapshots":"node scripts/test.js snapshot --update",lint:"biome lint src tests","lint:fix":"biome lint --write src tests","type-check":"tsc --noEmit","format:check":"biome format src tests",ready:"node scripts/run-bun.js run scripts/ready.ts","detect-unused":"node scripts/run-bun.js run scripts/detect-unused.ts",release:"node scripts/release.js","release:dry":"node scripts/release.js --dry-run","release:major":"node scripts/release.js --major","release:minor":"node scripts/release.js --minor","release:patch":"node scripts/release.js --patch"},keywords:["cli","blade","ai","assistant","agent","llm"],author:"echoVic",license:"MIT",engines:{node:">=20.0.0"},optionalDependencies:{"@vscode/ripgrep":"^1.17.0","bun-pty":"^0.4.8","node-pty":"1.0.0"},dependencies:{"@agentclientprotocol/sdk":"^0.12.0","@ai-sdk/anthropic":"^3.0.7","@ai-sdk/azure":"^3.0.5","@ai-sdk/deepseek":"^2.0.4","@ai-sdk/google":"^3.0.4","@ai-sdk/openai":"^3.0.26","@ai-sdk/openai-compatible":"^2.0.4","@inkjs/ui":"^2.0.0","@modelcontextprotocol/sdk":"^1.17.4",ahooks:"^3.9.6",ai:"^6.0.39","ansi-escapes":"^7.2.0","async-mutex":"^0.5.0",axios:"^1.12.2",chalk:"^5.4.1",diff:"^8.0.2","fast-glob":"^3.3.3","fuse.js":"^7.1.0","gray-matter":"^4.0.3",hono:"^4.7.10",ink:"npm:@jrichman/ink@6.4.10","ink-big-text":"^2.0.0","ink-gradient":"^3.0.0","ink-select-input":"^6.2.0","ink-spinner":"^5.0.0","ink-text-input":"^6.0.0","js-tiktoken":"^1.0.21","lodash-es":"^4.17.21",lowlight:"^3.3.0","lru-cache":"^11.2.4",nanoid:"^5.1.6",open:"^10.1.2",openai:"^6.2.0",picomatch:"^4.0.3",react:"^19.1.1","react-dom":"^19.1.1",semver:"^7.7.3","string-width":"^8.1.0",undici:"^7.16.0","write-file-atomic":"^7.0.0",ws:"^8.18.0",yaml:"^2.8.1",yargs:"^18.0.0",zod:"^3.24.2","zod-to-json-schema":"^3.24.6",zustand:"^5.0.9"},devDependencies:{"@biomejs/biome":"^2.2.4","@types/bun":"^1.3.4","@types/json-schema":"^7.0.15","@types/lodash-es":"^4.17.12","@types/node":"^22.15.24","@types/picomatch":"^4.0.2","@types/react":"^19.1.1","@types/react-dom":"^19.1.1","@types/semver":"^7.7.1","@types/write-file-atomic":"^4.0.3","@types/ws":"^8.5.12","@types/yargs":"^17.0.33","@vitest/coverage-v8":"^3.0.0",jsdom:"^26.0.0",typescript:"^5.9.2",vitest:"^3.0.0"}};function r(){return{name:e.name,version:e.version,description:e.description}}function n(){return e.version}function o(){return e.name}function c(){return e.description}function d(){return`v${e.version}`}function a(){return`v${e.version} © 2025 Blade Code`}
|
|
2
2
|
export{r as aa,n as ba,o as ca,c as da,d as ea,a as fa};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{nb as W0}from"./chunk-
|
|
1
|
+
import{nb as W0}from"./chunk-nhp35rk0.js";import{rb as s0}from"./chunk-pkmw32r0.js";import{xb as h}from"./chunk-7ycmx7c2.js";import{Bb as M}from"./chunk-set7v1rf.js";import{Db as bQ}from"./chunk-j2ag7hh6.js";function G0(Q){return Q.role==="system"&&Array.isArray(Q.content)}class q0{systemMessages;_history;_pending=[];context;constructor(Q,$){this.context=Q;let Z=Q.messages.find(G0);if(Z)this.systemMessages=[Z];else if($)this.systemMessages=[{role:"system",content:[{type:"text",text:$,providerOptions:{anthropic:{cacheControl:{type:"ephemeral"}}}}]}];else this.systemMessages=[];this._history=Q.messages.filter((J)=>!G0(J))}get historyLength(){return this._history.length}get history(){return this._history}get pending(){return this._pending}toLLMMessages(){return[...this.systemMessages,...this._history,...this._pending]}getMessagesForLLM(){return this.toLLMMessages()}getHistory(){return this._history}appendPending(Q){this._pending.push(Q)}appendUser(Q){this._pending.push(Q)}appendAssistant(Q){this._pending.push(Q)}appendToolResult(Q){this._pending.push(Q)}appendControl(Q,$){if(Q==="system")throw Error("Cannot append system control message via appendControl. Use constructor for root system prompt.");this._pending.push($)}appendToHistory(Q){this._history.push(Q)}commitPending(){if(this._pending.length>0)this._history.push(...this._pending),this._pending=[]}replaceHistory(Q){this._history=Q.filter(($)=>!G0($))}writeback(){this.commitPending(),this.context.messages=this._history}get hasSystemPrompt(){return this.systemMessages.length>0}}async function _Q(Q,$){let Z;while(!(Z=await Q.next()).done)if($)await $(Z.value);return Z.value}function m0(Q){if(Q.isSubagent)return"continue";if(!Q.budget||Q.budget<=0)return"continue";if(Q.consecutiveContinuations>=3&&Q.lastOutputDelta<500)return"stop";if(Q.usage/Q.budget>=0.9)return"stop";return"continue"}function g0(Q){return{budget:Q.budget,usage:0,consecutiveContinuations:0,lastOutputDelta:0,isSubagent:Q.isSubagent??!1}}function c0(Q,$,Z){return{...Q,usage:Q.usage+$,lastOutputDelta:$,consecutiveContinuations:Z?Q.consecutiveContinuations+1:0}}var a=M("Agent"),NQ=3;function U0(Q,$,Z){if(Q!=="length")return{action:"none"};if($>=NQ)return{action:"truncated"};if(m0(Z)==="stop")return a.info("[Loop] Token budget: diminishing returns detected, skipping recovery"),{action:"budget_stop"};return{action:"recover"}}var EQ=[/:\s*$/,/:\s*$/,/\.\.\.\s*$/,/让我(先|来|开始|查看|检查|修复)/,/Let me (first|start|check|look|fix)/i],IQ="请执行你提到的操作,不要只是描述。",UQ=2;function v0(Q,$){if(!Q||$>=UQ)return{action:"none"};let Z=Q.slice(-200),J=Z.match(/```/g);if(J&&J.length%2!==0)return{action:"none"};if(EQ.some((G)=>G.test(Z)))return{action:"retry",prompt:IQ};return{action:"none"}}var u0=30000;async function A0(Q){try{let Z=W0.getInstance().executeStopHooks({projectDir:h(),sessionId:Q.sessionId,permissionMode:Q.permissionMode,reason:Q.reason,abortSignal:Q.abortSignal}),J,z=new Promise((G)=>{J=setTimeout(()=>G("timeout"),u0)});try{let G=await Promise.race([Z,z]);if(G==="timeout")return a.warn(`[Loop] Stop hook 超时 (${u0}ms),按 shouldStop: true 处理`),{action:"stop"};let q=G;if(!q.shouldStop)return{action:"continue",reason:q.continueReason};return{action:"stop"}}finally{clearTimeout(J)}}catch($){return a.warn("[Loop] Stop hook execution failed:",$),{action:"stop"}}}var vQ=0.9;async function i0(Q){try{let{SpecManager:$}=await import("./chunk-pmtfesmc.js"),Z=$.getInstance();if(!Z.isActive())return{action:"none"};let J=Z.getCurrentSpec();if(!J||J.phase!=="implementation")return{action:"none"};if(Q.maxTurns>0&&Q.turnsCount>=Q.maxTurns*vQ)return a.info(`[RalphLoop] 轮次接近上限 (${Q.turnsCount}/${Q.maxTurns}),停止自动继续`),{action:"none"};let z=J.tasks??[],G=z.filter((K)=>K.status==="completed"||K.status==="skipped").length,q=z.length;if(G>=q)return{action:"none"};let W=z.find((K)=>K.status==="pending"||K.status==="in_progress"),V=`[Ralph Loop] Spec "${J.name}" 仍有未完成任务。
|
|
2
2
|
`+`进度: ${G}/${q} 任务已完成。
|
|
3
3
|
`+(W?`下一个任务: ${W.title}${W.description?` — ${W.description}`:""}
|
|
4
4
|
`:"")+"请继续执行下一个未完成的任务,不要停止。";return a.info(`[RalphLoop] Spec "${J.name}" 进度 ${G}/${q},自动继续`),{action:"continue",reason:V}}catch{return{action:"none"}}}var o=M("Agent");function s(Q){return Q.executionEngine?.getContextManager()}async function m(Q,$,Z,J=null){try{let z=s(Q),G=typeof Z==="string"?Z.trim()!=="":Z.some((q)=>q.type==="text"?q.text.trim()!=="":!0);if(z&&$.sessionId&&G)return await z.saveMessage($.sessionId,"user",Z,J,void 0,$.subagentInfo)}catch(z){o.warn("[Loop] 保存用户消息失败:",z)}return null}async function k(Q,$,Z,J){try{let z=s(Q);if(z&&$.sessionId&&Z.trim())return await z.saveMessage($.sessionId,"assistant",Z,J,void 0,$.subagentInfo)}catch(z){o.warn("[Loop] 保存助手消息失败:",z)}return null}async function y0(Q,$,Z,J,z){try{let G=s(Q);if(G&&$.sessionId)return await G.saveToolUse($.sessionId,Z,J,z,$.subagentInfo)}catch(G){o.warn("[Loop] 保存工具调用失败:",G)}return null}async function S0(Q,$,Z,J,z,G,q,W){try{let V=s(Q);if(V&&$.sessionId)return await V.saveToolResult($.sessionId,Z,J,z,G,q,$.subagentInfo,W)}catch(V){o.warn("[Loop] 保存工具结果失败:",V)}return null}async function V0(Q,$,Z,J){try{let z=s(Q);if(z&&$.sessionId)return await z.saveCompaction($.sessionId,Z,J,null)}catch(z){o.warn("[Loop] 保存压缩数据失败:",z)}return null}function n0(Q,$){if(!["TaskCreate","TaskUpdate","TaskList"].includes(Q.function.name)||!$.success||!$.llmContent&&!$.metadata)return null;let Z=typeof $.llmContent==="object"?$.llmContent:{};return{kind:"task_update",tasks:$.metadata?.tasks||Z.tasks||[]}}function l0(Q,$,Z){if(Q.function.name!=="Skill"||!$.success||!$.metadata)return;let J=$.metadata;if(J.skillName)Z.onSkillActivated?.({skillName:J.skillName,allowedTools:J.allowedTools,basePath:J.basePath||""})}function a0(Q){let $=Q.metadata;if(!$)return;return $.modelId?.toString().trim()||$.model?.toString().trim()||void 0||void 0}async function P0(Q,$,Z){let J=n0(Q,$);l0(Q,$,Z);let z=a0($);if(z)await Z.onModelSwitch?.(z);return J}import{nanoid as rQ}from"nanoid";import{promises as SQ}from"node:fs";import{nanoid as c}from"nanoid";import{promises as Y0}from"node:fs";var t=M("Tool");class C{static instance=null;accessedFiles=new Map;constructor(){}static getInstance(){if(!C.instance)C.instance=new C;return C.instance}async recordFileRead(Q,$){try{let Z=await Y0.stat(Q),J={filePath:Q,accessTime:Date.now(),mtime:Z.mtimeMs,sessionId:$,lastOperation:"read"};this.accessedFiles.set(Q,J),t.debug(`记录文件读取: ${Q}`)}catch(Z){t.warn(`记录文件读取失败: ${Q}`,Z)}}async recordFileEdit(Q,$,Z="edit"){try{let J=await Y0.stat(Q),z={filePath:Q,accessTime:Date.now(),mtime:J.mtimeMs,sessionId:$,lastOperation:Z};this.accessedFiles.set(Q,z),t.debug(`记录文件${Z==="edit"?"编辑":"写入"}: ${Q}`)}catch(J){t.warn(`记录文件${Z==="edit"?"编辑":"写入"}失败: ${Q}`,J)}}hasFileBeenRead(Q,$){let Z=this.accessedFiles.get(Q);if(!Z)return!1;if($&&Z.sessionId!==$)return!1;return!0}async checkFileModification(Q){let $=this.accessedFiles.get(Q);if(!$)return{modified:!1,message:"文件未被跟踪"};try{let Z=await Y0.stat(Q);if(Math.abs(Z.mtimeMs-$.mtime)>1)return{modified:!0,message:`文件在访问后被修改(访问时间: ${new Date($.accessTime).toISOString()}, 当前修改时间: ${Z.mtime.toISOString()})`};return{modified:!1}}catch(Z){let J=Z;if(J.code==="ENOENT")return{modified:!0,message:"文件已被删除"};return{modified:!1,message:`无法检查文件状态: ${J.message}`}}}async checkExternalModification(Q){let $=this.accessedFiles.get(Q);if(!$)return{isExternal:!1,message:"文件未被跟踪"};try{let Z=await Y0.stat(Q);if(Z.mtimeMs-$.mtime>2000)return{isExternal:!0,message:`文件在 ${new Date($.accessTime).toISOString()} (${$.lastOperation}) 之后被外部程序修改(当前修改时间: ${Z.mtime.toISOString()})`};return{isExternal:!1}}catch(Z){let J=Z;if(J.code==="ENOENT")return{isExternal:!0,message:"文件已被删除"};return t.warn(`检查文件外部修改失败: ${Q}`,Z),{isExternal:!1,message:`无法检查文件状态: ${J.message}`}}}getFileRecord(Q){return this.accessedFiles.get(Q)}clearFileRecord(Q){this.accessedFiles.delete(Q)}clearAll(){this.accessedFiles.clear()}clearSession(Q){for(let[$,Z]of this.accessedFiles.entries())if(Z.sessionId===Q)this.accessedFiles.delete($)}getTrackedFiles(){return Array.from(this.accessedFiles.keys())}getTrackedFileCount(){return this.accessedFiles.size}static resetInstance(){C.instance=null}}import{readFile as AQ}from"node:fs/promises";import{basename as yQ}from"node:path";class X0{static MAX_FILES=5;static MAX_LINES_PER_FILE=1000;static analyzeFiles(Q){let $=new Map;return Q.forEach((J,z)=>{let G=typeof J.content==="string"?J.content:(J.content||[]).filter((W)=>W.type==="text").map((W)=>W.text).join(`
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import{xb as Z}from"./chunk-7ycmx7c2.js";import{Bb as E}from"./chunk-set7v1rf.js";var G={currentModelId:"",models:[],temperature:0,maxContextTokens:128000,maxOutputTokens:void 0,stream:!0,topP:0.9,topK:50,timeout:180000,theme:"dracula",uiTheme:"system",language:"zh-CN",fontSize:14,autoSaveSessions:!0,notifyBuild:!0,notifyErrors:!1,notifySounds:!1,privacyTelemetry:!1,privacyCrash:!0,debug:!1,mcpEnabled:!1,mcpServers:{},permissions:{allow:["Bash(pwd)","Bash(which *)","Bash(whoami)","Bash(hostname)","Bash(uname *)","Bash(date)","Bash(echo *)","Bash(ls *)","Bash(tree *)","Bash(git status)","Bash(git status -*)","Bash(git log *)","Bash(git diff *)","Bash(git show *)","Bash(git branch -* *)","Bash(git branch)","Bash(git tag -l *)","Bash(git tag --list *)","Bash(git stash list *)","Bash(git stash show *)","Bash(git rev-parse *)","Bash(git describe *)","Bash(git blame *)","Bash(git ls-files *)","Bash(git config --get *)","Bash(git config --list *)","Bash(git shortlog *)","Bash(git merge-base *)","Bash(git cat-file *)","Bash(git for-each-ref *)","Bash(git grep *)","Bash(git worktree list *)","Bash(git reflog show *)","Bash(git reflog)","Bash(git rev-list *)","Bash(git ls-remote *)","Bash(git remote -v)","Bash(git remote --verbose)","Bash(git remote)","Bash(gh pr view *)","Bash(gh pr list *)","Bash(gh pr diff *)","Bash(gh pr checks *)","Bash(gh pr status *)","Bash(gh issue view *)","Bash(gh issue list *)","Bash(gh issue status *)","Bash(gh run list *)","Bash(gh run view *)","Bash(gh repo view *)","Bash(gh auth status)","Bash(npm list *)","Bash(bun pm ls *)","Bash(npm view *)","Bash(npm outdated *)","Bash(pnpm list *)","Bash(yarn list *)","Bash(pip list *)","Bash(pip show *)"],ask:["Bash(curl *)","Bash(wget *)","Bash(aria2c *)","Bash(axel *)","Bash(rm -rf *)","Bash(rm -r *)","Bash(rm --recursive *)","Bash(nc *)","Bash(netcat *)","Bash(telnet *)","Bash(ncat *)"],deny:["Read(./.env)","Read(./.env.*)","Bash(rm -rf /)","Bash(rm -rf /*)","Bash(sudo *)","Bash(chmod 777 *)","Bash(bash *)","Bash(sh *)","Bash(zsh *)","Bash(fish *)","Bash(dash *)","Bash(eval *)","Bash(source *)","Bash(mkfs *)","Bash(fdisk *)","Bash(dd *)","Bash(format *)","Bash(parted *)","Bash(open http*)","Bash(open https*)","Bash(xdg-open http*)","Bash(xdg-open https*)"]},permissionMode:"default",hooks:{enabled:!1,defaultTimeout:60,timeoutBehavior:"ignore",failureBehavior:"ignore",maxConcurrentHooks:5,PreToolUse:[],PostToolUse:[],PostToolUseFailure:[],PermissionRequest:[],UserPromptSubmit:[],SessionStart:[],SessionEnd:[],Stop:[],SubagentStop:[],Notification:[],Compaction:[]},env:{},disableAllHooks:!1,maxTurns:-1};import{promises as N}from"fs";import{merge as U}from"lodash-es";import _ from"os";import D from"path";class B{static instance=null;constructor(){}static getInstance(){if(!B.instance)B.instance=new B;return B.instance}static resetInstance(){B.instance=null}async initialize(){try{let J=await this.loadConfigFiles(),q=await this.loadSettingsFiles(),H={...J,...q},K=this.normalizeConfig(H),Q={...G,...K};if(this.resolveEnvInterpolation(Q),Q.debug)console.log("[ConfigManager] Configuration loaded successfully");return Q}catch(J){return console.error("[ConfigManager] Failed to initialize:",J),G}}async loadConfigFiles(){let J=D.join(_.homedir(),".blade","config.json"),q=D.join(Z(),".blade","config.json"),H={},K=await this.loadJsonFile(J);if(K)H={...H,...K};let Q=await this.loadJsonFile(q);if(Q){let W={...H.mcpServers||{},...Q.mcpServers||{}};if(H={...H,...Q},Object.keys(W).length>0)H.mcpServers=W}return H}async loadSettingsFiles(){let J=D.join(_.homedir(),".blade","settings.json"),q=D.join(Z(),".blade","settings.json"),H=D.join(Z(),".blade","settings.local.json"),K={},Q=await this.loadJsonFile(J);if(Q)K=this.mergeSettings(K,Q);let W=await this.loadJsonFile(q);if(W)K=this.mergeSettings(K,W);let X=await this.loadJsonFile(H);if(X)K=this.mergeSettings(K,X);return K}mergeSettings(J,q){let H=JSON.parse(JSON.stringify(J));if(q.permissions){if(!H.permissions)H.permissions={allow:[],ask:[],deny:[]};if(q.permissions.allow){let K=[...H.permissions.allow||[],...q.permissions.allow];H.permissions.allow=Array.from(new Set(K))}if(q.permissions.ask){let K=[...H.permissions.ask||[],...q.permissions.ask];H.permissions.ask=Array.from(new Set(K))}if(q.permissions.deny){let K=[...H.permissions.deny||[],...q.permissions.deny];H.permissions.deny=Array.from(new Set(K))}}if(q.hooks)H.hooks=U({},H.hooks,q.hooks);if(q.env)H.env=U({},H.env,q.env);if(q.mcpServers)H.mcpServers={...H.mcpServers||{},...q.mcpServers};if(q.disableAllHooks!==void 0)H.disableAllHooks=q.disableAllHooks;if(q.permissionMode!==void 0)H.permissionMode=q.permissionMode;if(q.maxTurns!==void 0)H.maxTurns=q.maxTurns;return H}resolveEnvInterpolation(J){let q=/\$\{?([A-Z_][A-Z0-9_]*)(:-([^}]+))?\}?/g,H=(Q)=>{if(typeof Q==="string")return Q.replace(q,(W,X,Y,V)=>{return process.env[X]||V||W});if(Array.isArray(Q))return Q.map(H);if(typeof Q==="object"&&Q!==null){let W=Q;for(let[X,Y]of Object.entries(W))W[X]=H(Y);return W}return Q},K=J;for(let[Q,W]of Object.entries(K))K[Q]=H(W)}async loadJsonFile(J){try{if(await this.fileExists(J)){let q=await N.readFile(J,"utf-8");return JSON.parse(q)}}catch(q){console.warn(`[ConfigManager] Failed to load ${J}:`,q)}return null}async fileExists(J){try{return await N.access(J),!0}catch{return!1}}normalizeConfig(J){let q=JSON.parse(JSON.stringify(J)),H=(Q)=>Q.trim().replace(/^`|`$/g,""),K=(Q)=>{for(let[W,X]of Object.entries(Q))if(typeof X==="string")Q[W]=H(X);else if(Array.isArray(X))X.forEach((Y,V)=>{if(typeof Y==="string")X[V]=H(Y);else if(typeof Y==="object"&&Y!==null)K(Y)});else if(typeof X==="object"&&X!==null)K(X)};return K(q),q}validateConfig(J){let q=[],H=[];if(!J.models||J.models.length===0)q.push("没有可用的模型配置");if(J.models&&J.models.length>0){if(!J.currentModelId)q.push("未设置当前模型 ID");else if(!J.models.find((Q)=>Q.id===J.currentModelId))q.push(`当前模型 ID "${J.currentModelId}" 在 models 列表中不存在`);for(let K of J.models){let Q=`模型 "${K.name||K.id}"`;if(!K.apiKey)H.push(`${Q}: apiKey 为空`);if(!K.model)q.push(`${Q}: model 字段必填`);if(!K.provider)q.push(`${Q}: provider 字段必填`);if(K.baseUrl&&!K.baseUrl.startsWith("http"))H.push(`${Q}: baseUrl "${K.baseUrl}" 不是有效的 HTTP URL`)}}if(H.length>0)console.warn(`[ConfigManager] 配置警告:
|
|
2
|
+
${H.map((K)=>` ⚠ ${K}`).join(`
|
|
3
|
+
`)}`);if(q.length>0)throw Error(`配置验证失败:
|
|
4
|
+
${q.map((K)=>` - ${K}`).join(`
|
|
5
|
+
`)}
|
|
6
|
+
|
|
7
|
+
`+`请通过以下方式之一提供配置:
|
|
8
|
+
`+` 1. 首次启动: 运行 blade,系统会自动引导配置
|
|
9
|
+
`+` 2. 添加模型: blade 后输入 /model add
|
|
10
|
+
`+` 3. 初始化向导: 输入 /init
|
|
11
|
+
|
|
12
|
+
`+`配置文件示例 (~/.blade/config.json):
|
|
13
|
+
`+`{
|
|
14
|
+
"currentModelId": "model-id-123",
|
|
15
|
+
"models": [
|
|
16
|
+
{
|
|
17
|
+
"id": "model-id-123",
|
|
18
|
+
`+` "name": "默认模型",
|
|
19
|
+
`+` "provider": "openai-compatible",
|
|
20
|
+
"apiKey": "your-api-key",
|
|
21
|
+
"baseUrl": "https://api.example.com/v1",
|
|
22
|
+
"model": "model-name"
|
|
23
|
+
}
|
|
24
|
+
]
|
|
25
|
+
}
|
|
26
|
+
`)}}function L(J,q={}){let H={...J};if(q.debug!==void 0)H.debug=q.debug===""?!0:q.debug;if(q.model){if(!J.models.some((Q)=>Q.id===q.model))throw Error(`模型配置未找到: ${q.model}`);H.currentModelId=q.model}if(q.yolo===!0)H.permissionMode="yolo";else if(q.permissionMode!==void 0)H.permissionMode=q.permissionMode;if(q.maxTurns!==void 0)H.maxTurns=q.maxTurns;return H.systemPrompt=q.systemPrompt,H.appendSystemPrompt=q.appendSystemPrompt,H.model=q.model,H.resumeSessionId=q.sessionId,H.forkSession=q.forkSession,H.allowedTools=q.allowedTools,H.disallowedTools=q.disallowedTools,H.mcpConfigPaths=q.mcpConfig,H.strictMcpConfig=q.strictMcpConfig,H.addDirs=q.addDir,H.outputFormat=q.outputFormat,H.inputFormat=q.inputFormat,H.print=q.print,H.includePartialMessages=q.includePartialMessages,H.replayUserMessages=q.replayUserMessages,H.agentsConfig=q.agents,H.settingSources=q.settingSources,H}import{Mutex as I}from"async-mutex";import{merge as w}from"lodash-es";import{promises as A}from"node:fs";import M from"node:os";import z from"node:path";import S from"write-file-atomic";var T=E("Service"),R={models:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},currentModelId:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},temperature:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},maxContextTokens:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},maxOutputTokens:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},timeout:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},theme:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},uiTheme:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},language:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},debug:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},fontSize:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},autoSaveSessions:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},notifyBuild:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},notifyErrors:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},notifySounds:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},privacyTelemetry:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},privacyCrash:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},permissionMode:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},permissions:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!0},hooks:{target:"settings",defaultScope:"local",mergeStrategy:"deep-merge",persistable:!0},env:{target:"settings",defaultScope:"local",mergeStrategy:"deep-merge",persistable:!0},disableAllHooks:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!0},maxTurns:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!0},mcpServers:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},stream:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!1},topP:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!1},topK:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!1},mcpEnabled:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!1},systemPrompt:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},appendSystemPrompt:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},initialMessage:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},resumeSessionId:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},forkSession:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},allowedTools:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},disallowedTools:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},mcpConfigPaths:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},strictMcpConfig:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},addDirs:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},outputFormat:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},inputFormat:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},print:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},includePartialMessages:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},replayUserMessages:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},agentsConfig:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},settingSources:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1}},t=new Set(Object.entries(R).filter(([J,q])=>q.persistable).map(([J])=>J)),i=new Set(Object.entries(R).filter(([J,q])=>!q.persistable).map(([J])=>J));class ${static instance=null;pendingUpdates=new Map;timers=new Map;fileLocks=new Map;lastSaveError=null;debounceDelay=300;constructor(){}static getInstance(){if(!$.instance)$.instance=new $;return $.instance}static resetInstance(){if($.instance)for(let J of $.instance.timers.values())clearTimeout(J);$.instance=null}async save(J,q={}){this.validatePersistableFields(J);let H=this.groupUpdatesByTarget(J,q.scope);if(q.immediate)await Promise.all(Array.from(H.entries()).map(([K,Q])=>this.flushTarget(K,Q)));else for(let[K,Q]of H)this.scheduleSave(K,Q)}async flush(){for(let q of this.timers.values())clearTimeout(q);this.timers.clear();let J=Array.from(this.pendingUpdates.entries()).map(([q,H])=>this.flushTarget(q,H));this.pendingUpdates.clear(),await Promise.all(J)}getLastSaveError(){return this.lastSaveError}clearLastSaveError(){this.lastSaveError=null}async appendPermissionRule(J,q={}){let H=q.scope??"local",K=this.resolveFilePath("settings",H);await this.flushTargetWithModifier(K,(Q)=>{let W=Q.permissions??{allow:[],ask:[],deny:[]},X={allow:this.dedupeArray([...W.allow||[],J]),ask:W.ask||[],deny:W.deny||[]};return{...Q,permissions:X}})}async appendLocalPermissionRule(J,q={}){await this.appendPermissionRule(J,{...q,scope:"local"})}validatePersistableFields(J){for(let q of Object.keys(J)){let H=R[q];if(!H)throw Error(`Unknown config field: ${q}`);if(!H.persistable)throw Error(`Field "${q}" is non-persistable and cannot be saved to config files. Non-persistable fields are runtime-only and only valid for the current session.`)}}groupUpdatesByTarget(J,q){let H=new Map;for(let[K,Q]of Object.entries(J)){let W=R[K];if(!W)continue;let X=q??W.defaultScope,Y=this.resolveFilePath(W.target,X);if(!H.has(Y))H.set(Y,{});H.get(Y)[K]=Q}return H}resolveFilePath(J,q){if(J==="config")return q==="global"?z.join(M.homedir(),".blade","config.json"):z.join(Z(),".blade","config.json");switch(q){case"local":return z.join(Z(),".blade","settings.local.json");case"project":return z.join(Z(),".blade","settings.json");case"global":return z.join(M.homedir(),".blade","settings.json");default:return z.join(Z(),".blade","settings.local.json")}}scheduleSave(J,q){let H=this.pendingUpdates.get(J)??{},K=this.mergePendingUpdates(H,q);this.pendingUpdates.set(J,K);let Q=this.timers.get(J);if(Q)clearTimeout(Q);let W=setTimeout(async()=>{let X=this.pendingUpdates.get(J);if(X){this.pendingUpdates.delete(J),this.timers.delete(J);try{await this.flushTarget(J,X),this.lastSaveError=null}catch(Y){let V=Y instanceof Error?Y:Error(String(Y));this.lastSaveError=V,T.error(`Failed to save config to ${J}:`,V.message),T.error("Stack trace:",V.stack)}}},this.debounceDelay);this.timers.set(J,W)}mergePendingUpdates(J,q){let H={...J};for(let[K,Q]of Object.entries(q)){let W=R[K];if(!W){H[K]=Q;continue}switch(W.mergeStrategy){case"replace":H[K]=Q;break;case"append-dedupe":this.applyAppendDedupe(H,K,Q);break;case"deep-merge":this.applyDeepMerge(H,K,Q);break}}return H}async flushTarget(J,q){let H=this.fileLocks.get(J);if(!H)H=new I,this.fileLocks.set(J,H);await H.runExclusive(async()=>{await this.performWrite(J,q)})}async flushTargetWithModifier(J,q){let H=this.fileLocks.get(J);if(!H)H=new I,this.fileLocks.set(J,H);await H.runExclusive(async()=>{await A.mkdir(z.dirname(J),{recursive:!0,mode:493});let K={};try{let W=await A.readFile(J,"utf-8");K=JSON.parse(W)}catch{K={}}let Q=q(K);await this.atomicWrite(J,Q)})}async performWrite(J,q){await A.mkdir(z.dirname(J),{recursive:!0,mode:493});let H={};try{let Q=await A.readFile(J,"utf-8");H=JSON.parse(Q)}catch{H={}}let K={...H};for(let[Q,W]of Object.entries(q)){let X=R[Q];if(!X){K[Q]=W;continue}switch(X.mergeStrategy){case"replace":K[Q]=W;break;case"append-dedupe":this.applyAppendDedupe(K,Q,W);break;case"deep-merge":this.applyDeepMerge(K,Q,W);break}}await this.atomicWrite(J,K)}applyAppendDedupe(J,q,H){if(q==="permissions"&&typeof H==="object"&&H!==null){let K=J[q]??{allow:[],ask:[],deny:[]},Q=H;J[q]={allow:this.dedupeArray([...K.allow||[],...Q.allow||[]]),ask:this.dedupeArray([...K.ask||[],...Q.ask||[]]),deny:this.dedupeArray([...K.deny||[],...Q.deny||[]])}}else if(Array.isArray(H)){let K=Array.isArray(J[q])?J[q]:[];J[q]=this.dedupeArray([...K,...H])}else J[q]=H}applyDeepMerge(J,q,H){if(typeof H==="object"&&H!==null&&!Array.isArray(H)){let K=typeof J[q]==="object"&&J[q]!==null?J[q]:{};J[q]=w({},K,H)}else J[q]=H}dedupeArray(J){return Array.from(new Set(J))}async atomicWrite(J,q){await S(J,JSON.stringify(q,null,2),{mode:384,encoding:"utf-8"})}}function b(){return $.getInstance()}export{G as Ha,B as Ia,L as Ja,b as Ka};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Aa as g,Ba as h,Ca as i,Da as j,Ea as k,Fa as l,Ga as m,ua as a,va as b,wa as c,xa as d,ya as e,za as f}from"./chunk-
|
|
1
|
+
import{Aa as g,Ba as h,Ca as i,Da as j,Ea as k,Fa as l,Ga as m,ua as a,va as b,wa as c,xa as d,ya as e,za as f}from"./chunk-hhgbhadg.js";import"./chunk-c6ts8bd9.js";import"./chunk-7ycmx7c2.js";import"./chunk-set7v1rf.js";import"./chunk-j2ag7hh6.js";export{a as vanillaStore,c as sessionActions,l as getThinkingModeEnabled,b as getState,j as getModelById,e as getMessages,k as getMcpServers,i as getCurrentModel,f as getConfig,h as getAllModels,g as ensureStoreInitialized,m as configActions,d as appActions};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{Y as O}from"./chunk-
|
|
1
|
+
import{Y as O}from"./chunk-yhwrv3qf.js";import"./chunk-6yvqtcx0.js";import{Ea as J,Ga as L}from"./chunk-hhgbhadg.js";import"./chunk-c6ts8bd9.js";import"./chunk-yddnm9n2.js";import{xb as H}from"./chunk-7ycmx7c2.js";import"./chunk-set7v1rf.js";import"./chunk-j2ag7hh6.js";import P from"os";import E from"path";function _(q){return typeof q==="string"?q:void 0}function T(q){if(!Array.isArray(q))return;let z=[];for(let F of q)if(typeof F==="string")z.push(F);else if(F!=null)z.push(String(F));return z}function G(){console.log(`
|
|
2
2
|
blade mcp
|
|
3
3
|
`),console.log(`管理 MCP 服务器
|
|
4
4
|
`),console.log("Commands:"),console.log(" blade mcp add <name> <commandOrUrl> [args...] 添加 MCP 服务器"),console.log(" blade mcp remove <name> 删除 MCP 服务器 [aliases: rm]"),console.log(" blade mcp list 列出所有 MCP 服务器并检查健康状态 [aliases: ls]"),console.log(" blade mcp get <name> 获取服务器详情"),console.log(` blade mcp add-json <name> <json> 从 JSON 字符串添加服务器
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{N as l,O as c,P as m,S as g,U as d}from"./chunk-
|
|
1
|
+
import{N as l,O as c,P as m,S as g,U as d}from"./chunk-gkd5eew1.js";import{xb as u}from"./chunk-7ycmx7c2.js";async function C(){if((await l().initialize(u(),[])).plugins.length>0)await c()}async function h(t){let e=t.message||t._?.[0];if(typeof e==="string"&&e.trim())return e;let n=t.stdin??process.stdin;if(!n.isTTY){let a=[];for await(let i of n)a.push(i);return Buffer.concat(a).toString("utf-8").trim()}if(t.defaultMessage!==void 0)return t.defaultMessage;throw Error("No input provided")}async function R(t){if(!g(t))return{mode:"agent",content:t};let e=await d(t,{cwd:u(),workspaceRoot:u()});if(!e.success)return{mode:"output",content:`Error: ${e.error||"未知错误"}`,exitCode:1};let n=e.data;if(n?.action==="invoke_skill"){let{skillName:a,skillArgs:i}=n;return{mode:"agent",content:i?`Please use the "${a}" skill to help me with: ${i}`:`Please use the "${a}" skill.`}}if(n?.action==="invoke_custom_command"||n?.action==="invoke_plugin_command"){let a=n.processedContent;return{mode:"agent",content:`# Custom Command: /${n.commandName}
|
|
2
2
|
|
|
3
3
|
${a}`}}return{mode:"output",content:e.content||e.message||"",exitCode:0}}function r(t){if(!(t instanceof Error))return!1;return t.message.includes("未找到会话")||t.message.includes("ENOENT")||t.message.includes("no such file")}async function s(t){try{return await m.loadSession(t,u())}catch(e){if(r(e))return null;throw e}}async function N(t){if(t.resume===!0||t.resume==="true")throw Error("--resume without a session ID is only supported in interactive UI mode");if(typeof t.resume==="string"&&t.resume.length>0)return{sessionId:t.resume,messages:await m.loadSession(t.resume)};if(t.continue){let e=await m.listSessions();if(e.length>0){let n=e[0].sessionId;return{sessionId:n,messages:await m.loadSession(n)}}}if(t.sessionId)return{sessionId:t.sessionId,messages:await s(t.sessionId)??[]};return{sessionId:`${t.fallbackSessionPrefix}-${Date.now()}`,messages:[]}}
|
|
4
4
|
export{C as p,h as q,R as r,N as s};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{Ia as t}from"./chunk-
|
|
1
|
+
import{Ia as t}from"./chunk-c6ts8bd9.js";import{xb as r}from"./chunk-7ycmx7c2.js";import"./chunk-set7v1rf.js";import{Db as s}from"./chunk-j2ag7hh6.js";var m={command:"doctor",describe:"Check the health of your Blade installation",handler:async()=>{console.log(`Running Blade health check...
|
|
2
2
|
`);let e=0;try{await t.getInstance().initialize(),console.log("[OK] Configuration: OK")}catch(o){console.log("[FAIL] Configuration: FAILED"),console.log(` Error: ${o instanceof Error?o.message:"未知错误"}`),e++}let n=process.version;if(parseInt(n.slice(1).split(".")[0])>=18)console.log(`[OK] Node.js version: ${n}`);else console.log(`[WARN] Node.js version: ${n} (recommended: v18+)`),e++;try{let o=await import("fs/promises"),i=r();await o.access(i,(await import("fs")).constants.R_OK|(await import("fs")).constants.W_OK),console.log("[OK] File system permissions: OK")}catch(o){console.log("[FAIL] File system permissions: FAILED"),console.log(" Error: Cannot read/write in current directory"),e++}try{await import("ink"),console.log("[OK] Dependencies: OK")}catch(o){console.log("[FAIL] Dependencies: FAILED"),console.log(" Error: Missing required dependencies"),e++}if(console.log(`
|
|
3
3
|
Health Check Summary:`),e===0)console.log("All checks passed! Blade is ready to use.");else console.log(`Warning: Found ${e} issue(s). Please resolve them for optimal performance.`),process.exit(1)}};export{m as doctorCommands};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{ba as d,da as h}from"./chunk-
|
|
1
|
+
import{ba as d,da as h}from"./chunk-6yvqtcx0.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,4 +1,4 @@
|
|
|
1
|
-
import{p as _,q as x,r as E,s as N}from"./chunk-
|
|
1
|
+
import{p as _,q as x,r as E,s as N}from"./chunk-cwafz1g3.js";import{t as A}from"./chunk-e38t8r4f.js";import{v as B,w as D,x as L}from"./chunk-r8wmg3fc.js";import{G as $,M as b}from"./chunk-gkd5eew1.js";import"./chunk-yhwrv3qf.js";import"./chunk-esnkk33h.js";import"./chunk-6yvqtcx0.js";import"./chunk-v1c9xwen.js";import"./chunk-hhgbhadg.js";import"./chunk-c6ts8bd9.js";import{Sa as Z}from"./chunk-9syksrkj.js";import"./chunk-yddnm9n2.js";import"./chunk-nhp35rk0.js";import"./chunk-pkmw32r0.js";import{wb as X,xb as Y}from"./chunk-7ycmx7c2.js";import"./chunk-set7v1rf.js";import"./chunk-j2ag7hh6.js";import f from"yargs";import{hideBin as h}from"yargs/helpers";var R=new Set(Object.values(X));function W(k){if(k&&R.has(k))return k;return}function w(k){return k.command("* [message]","Print response and exit (useful for pipes)",(F)=>F.positional("message",{describe:"Message to process",type:"string"}).option("p",{alias:"print",describe:"Print response and exit (useful for pipes)",type:"boolean"}).option("output-format",{describe:'Output format: "text", "json", "stream-json"',type:"string",default:"text"}).option("include-partial-messages",{describe:"Include partial message chunks as they arrive",type:"boolean"}).option("input-format",{describe:'Input format: "text", "stream-json"',type:"string",default:"text"}).option("model",{describe:"Model for the current session",type:"string"}).option("append-system-prompt",{describe:"Append a system prompt to the default system prompt",type:"string"}).option("system-prompt",{describe:"Replace the default system prompt",type:"string"}).option("max-turns",{alias:["maxTurns"],describe:"Maximum conversation turns (-1: unlimited, N>0: limit to N turns)",type:"number"}),async(F)=>{if(!F.p)return;let q=await M(F);process.exit(q)})}async function M(k,F=process){let q;try{await _();let J=await x({message:k.message,_:k._,defaultMessage:"Hello"}),G=await E(J);if(G.mode==="output"){if(G.content)F.stdout.write(`${G.content}
|
|
2
2
|
`);return G.exitCode??0}let Q=G.content,{sessionId:K,messages:T}=await N({sessionId:k.sessionId,continue:k.continue,resume:k.resume,fallbackSessionPrefix:"print"});q=await $.create({sessionId:K,modelId:k.model,mcpConfig:k.mcpConfig,strictMcpConfig:k.strictMcpConfig});let U=await b.createWithRuntime(q,{sessionId:K,systemPrompt:k.systemPrompt,appendSystemPrompt:k.appendSystemPrompt,maxTurns:k.maxTurns,modelId:k.model,permissionMode:W(k.permissionMode),toolWhitelist:k.allowedTools,toolBlacklist:k.disallowedTools,mcpConfig:k.mcpConfig,strictMcpConfig:k.strictMcpConfig}),H=(await Z(U.chatStream(Q,{messages:[...T],userId:"cli-user",sessionId:K,workspaceRoot:Y(),permissionMode:W(k.permissionMode)}))).finalMessage||"";if(k.outputFormat==="json")F.stdout.write(`${JSON.stringify({response:H,input:Q,model:k.model,timestamp:new Date().toISOString()},null,2)}
|
|
3
3
|
`);else if(k.outputFormat==="stream-json")F.stdout.write(`${JSON.stringify({type:"response",content:H})}
|
|
4
4
|
`);else F.stdout.write(`${H}
|