blade-code 0.5.7 → 0.5.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/blade.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import{n as B}from"./chunk-mb7hm0ga.js";import{$ as F,_ as D}from"./chunk-esnkk33h.js";import"./chunk-j73schtj.js";import"./chunk-n2dcjqbe.js";import"./chunk-1e2phnbj.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-wf0y3mtz.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-5d6jtejt.js");if(await K())return}if(z(X,"--print","-p")){let{handlePrintMode:K}=await import("./chunk-7syqwtm1.js");if(await K())return}if(X.includes("--acp")){let{runAcpIntegration:K}=await import("./chunk-ap7bms54.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-phyx8td6.js"),import("./chunk-gbcwjg7v.js"),import("./chunk-y2m6x22z.js"),import("./chunk-g5pasj7t.js"),import("./chunk-d5rw1sw3.js"),import("./chunk-efa9w1ry.js"),import("./chunk-bhjw4b73.js"),import("./chunk-qa0vgwq7.js")]),x=W(T(process.argv)).scriptName(N.scriptName).usage(N.usage).version(N.version).locale(N.locale).showHelpOnFail(N.showHelpOnFail).demandCommand(0,"").recommendCommands().strict(N.strict).parserConfiguration({"populate--":!0}).options(G).middleware([M,I,L]).command(R).command(_).command(k).command(y).command(O).command(S).completion("completion",!1).help("help","Show help").alias("help","h").alias("version","V").fail((K,U,Z)=>{if(U){if(console.error("An error occurred:"),console.error(U.message),w&&U.stack)console.error(`
2
+ import{n as B}from"./chunk-mb7hm0ga.js";import{$ as F,_ as D}from"./chunk-esnkk33h.js";import"./chunk-j73schtj.js";import"./chunk-n2dcjqbe.js";import"./chunk-1e2phnbj.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-artre29e.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-9rd4s3s8.js");if(await K())return}if(z(X,"--print","-p")){let{handlePrintMode:K}=await import("./chunk-fw6vvf5q.js");if(await K())return}if(X.includes("--acp")){let{runAcpIntegration:K}=await import("./chunk-szrw09wy.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-nsn09rda.js"),import("./chunk-gbcwjg7v.js"),import("./chunk-y2m6x22z.js"),import("./chunk-g5pasj7t.js"),import("./chunk-vxjtxwr9.js"),import("./chunk-b9ttaacg.js"),import("./chunk-bhjw4b73.js"),import("./chunk-47nkcxv7.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-mzb8bn02.js")]),Y={...K,initialMessage:Z,debug:K.debug,print:Boolean(K.print),versionCheckPromise:V};delete Y._,delete Y.$0,delete Y.message,b(P(h,Y),{patchConsole:!0,exitOnCtrlC:!1,alternateBuffer:!1})});try{await x.parse()}catch(K){console.error("Error: Parse error:",K),process.exit(1)}}if(J.main==J.module)f().catch(console.error);export{f as main};
5
+ Hint: Did you mean:`),Z.showHelp(),process.exit(1)}).command("$0",!1,()=>{},async(K)=>{let U=K._.slice(1),Z=U.length>0?U.join(" "):void 0,V=import("./chunk-th432d0b.js").then(({checkVersionOnStartup:A})=>A()),[{render:b},{createElement:P},{AppWrapper:h}]=await Promise.all([import("ink"),import("react"),import("./chunk-hc26w438.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{ba as S,ca as h}from"./chunk-vppcvxzd.js";import{kb as M}from"./chunk-yddnm9n2.js";import{Db as c}from"./chunk-j2ag7hh6.js";import{EventEmitter as r}from"events";import{z as L}from"zod";import{isPlainObject as v}from"lodash-es";function b(B){if(B===void 0)return"undefined";if(typeof B==="string")return B;try{let G=JSON.stringify(B);return G===void 0?String(B):G}catch{return String(B)}}class R extends Error{issues;type;constructor(B,G,Q="validation_error"){super(B);this.issues=G;this.type=Q;this.name="ToolValidationError"}}function g(B){let{code:G}=B,Q=B,X=Q.received;switch(G){case"invalid_type":{let Y=Q.expected;return`类型错误:期望 ${b(Y)},实际收到 ${b(X)}`}case"too_small":{let{minimum:Y,inclusive:$}=Q,W=typeof Q.type==="string"?Q.type:void 0;if(W==="string"&&typeof Y==="number")return`长度不能少于 ${Y} 个字符`;if(W==="number"&&typeof Y==="number")return`不能小于${$?"等于":""} ${Y}`;if(W==="array"&&typeof Y==="number")return`数组长度不能少于 ${Y}`;return"值太小"}case"too_big":{let{maximum:Y,inclusive:$}=Q,W=typeof Q.type==="string"?Q.type:void 0;if(W==="string"&&typeof Y==="number")return`长度不能超过 ${Y} 个字符`;if(W==="number"&&typeof Y==="number")return`不能大于${$?"等于":""} ${Y}`;if(W==="array"&&typeof Y==="number")return`数组长度不能超过 ${Y}`;return"值太大"}case"invalid_string":{let Y=Q.validation;if(Y==="email")return"必须是有效的电子邮件地址";if(Y==="url")return"必须是有效的 URL";if(Y==="uuid")return"必须是有效的 UUID";if(v(Y)){let $=Y;if(typeof $.includes==="string")return`必须包含 "${$.includes}"`;if(typeof $.startsWith==="string")return`必须以 "${$.startsWith}" 开头`;if(typeof $.endsWith==="string")return`必须以 "${$.endsWith}" 结尾`}return"字符串格式不正确"}case"invalid_enum_value":{let Y=Q.options;if(Array.isArray(Y))return`必须是以下值之一:${Y.map(($)=>b($)).join(", ")}`;return"必须是枚举允许的值之一"}case"invalid_literal":{let Y=Q.expected;return`必须是字面量值:${b(Y)}`}case"unrecognized_keys":{let Y=Q.keys;if(Array.isArray(Y))return`包含未知的参数:${Y.map(($)=>b($)).join(", ")}`;return"包含未知的参数"}case"invalid_union":return"不符合任何有效的类型定义";case"invalid_date":return"必须是有效的日期";case"custom":return B.message||"自定义验证失败";default:return B.message||"验证失败"}}function u(B){let G=B.issues.map((X)=>{let Y=X.path.join("."),$=g(X),W=X.received;return{field:Y||"root",message:$,value:W}}),Q=G.length===1?`参数验证失败 [${G[0].field}]: ${G[0].message}`:`参数验证失败 (${G.length} 个错误):
1
+ import{ba as S,ca as h}from"./chunk-5gxn6wrh.js";import{kb as M}from"./chunk-yddnm9n2.js";import{Db as c}from"./chunk-j2ag7hh6.js";import{EventEmitter as r}from"events";import{z as L}from"zod";import{isPlainObject as v}from"lodash-es";function b(B){if(B===void 0)return"undefined";if(typeof B==="string")return B;try{let G=JSON.stringify(B);return G===void 0?String(B):G}catch{return String(B)}}class R extends Error{issues;type;constructor(B,G,Q="validation_error"){super(B);this.issues=G;this.type=Q;this.name="ToolValidationError"}}function g(B){let{code:G}=B,Q=B,X=Q.received;switch(G){case"invalid_type":{let Y=Q.expected;return`类型错误:期望 ${b(Y)},实际收到 ${b(X)}`}case"too_small":{let{minimum:Y,inclusive:$}=Q,W=typeof Q.type==="string"?Q.type:void 0;if(W==="string"&&typeof Y==="number")return`长度不能少于 ${Y} 个字符`;if(W==="number"&&typeof Y==="number")return`不能小于${$?"等于":""} ${Y}`;if(W==="array"&&typeof Y==="number")return`数组长度不能少于 ${Y}`;return"值太小"}case"too_big":{let{maximum:Y,inclusive:$}=Q,W=typeof Q.type==="string"?Q.type:void 0;if(W==="string"&&typeof Y==="number")return`长度不能超过 ${Y} 个字符`;if(W==="number"&&typeof Y==="number")return`不能大于${$?"等于":""} ${Y}`;if(W==="array"&&typeof Y==="number")return`数组长度不能超过 ${Y}`;return"值太大"}case"invalid_string":{let Y=Q.validation;if(Y==="email")return"必须是有效的电子邮件地址";if(Y==="url")return"必须是有效的 URL";if(Y==="uuid")return"必须是有效的 UUID";if(v(Y)){let $=Y;if(typeof $.includes==="string")return`必须包含 "${$.includes}"`;if(typeof $.startsWith==="string")return`必须以 "${$.startsWith}" 开头`;if(typeof $.endsWith==="string")return`必须以 "${$.endsWith}" 结尾`}return"字符串格式不正确"}case"invalid_enum_value":{let Y=Q.options;if(Array.isArray(Y))return`必须是以下值之一:${Y.map(($)=>b($)).join(", ")}`;return"必须是枚举允许的值之一"}case"invalid_literal":{let Y=Q.expected;return`必须是字面量值:${b(Y)}`}case"unrecognized_keys":{let Y=Q.keys;if(Array.isArray(Y))return`包含未知的参数:${Y.map(($)=>b($)).join(", ")}`;return"包含未知的参数"}case"invalid_union":return"不符合任何有效的类型定义";case"invalid_date":return"必须是有效的日期";case"custom":return B.message||"自定义验证失败";default:return B.message||"验证失败"}}function u(B){let G=B.issues.map((X)=>{let Y=X.path.join("."),$=g(X),W=X.received;return{field:Y||"root",message:$,value:W}}),Q=G.length===1?`参数验证失败 [${G[0].field}]: ${G[0].message}`:`参数验证失败 (${G.length} 个错误):
2
2
  ${G.map((X)=>` - ${X.field}: ${X.message}`).join(`
3
3
  `)}`;return new R(Q,G)}function y(B,G){let Q=B.safeParse(G);if(!Q.success)throw u(Q.error);return Q.data}import{zodToJsonSchema as l}from"zod-to-json-schema";function H(B){let G=l(B,{target:"jsonSchema7",$refStrategy:"none"});if(G.type==="object"&&G.properties&&!Array.isArray(G.required))G.required=[];return G}class w{toolName;params;executeFn;descriptionFn;affectedPathsFn;constructor(B,G,Q,X,Y){this.toolName=B;this.params=G;this.executeFn=Q;this.descriptionFn=X;this.affectedPathsFn=Y}getDescription(){if(this.descriptionFn)return this.descriptionFn(this.params);return`执行工具: ${this.toolName}`}getAffectedPaths(){if(this.affectedPathsFn)return this.affectedPathsFn(this.params);return[]}async execute(B,G,Q){let X={signal:B,updateOutput:G,...Q};return this.executeFn(this.params,X)}}function k(B){return{name:B.name,displayName:B.displayName,kind:B.kind,isReadOnly:B.isReadOnly??M(B.kind),isConcurrencySafe:B.isConcurrencySafe??!1,strict:B.strict??!1,description:B.description,version:B.version||"1.0.0",category:B.category,tags:B.tags||[],getFunctionDeclaration(){let G=H(B.schema),Q=B.description.short;if(B.description.long)Q+=`
4
4
 
@@ -1,4 +1,4 @@
1
- import{a as Q,b as R,c as T,d as W}from"./chunk-m0gqzy3r.js";import"./chunk-q5yn875m.js";import"./chunk-tjzyqsnc.js";import"./chunk-sdfra3bn.js";import"./chunk-esnkk33h.js";import{ba as M}from"./chunk-vppcvxzd.js";import"./chunk-cj5w17y3.js";import{Aa as J}from"./chunk-j73schtj.js";import"./chunk-n2dcjqbe.js";import"./chunk-10js1kwp.js";import"./chunk-yddnm9n2.js";import"./chunk-1e2phnbj.js";import"./chunk-37rethcy.js";import"./chunk-7ycmx7c2.js";import"./chunk-set7v1rf.js";import"./chunk-j2ag7hh6.js";import b from"chalk";import H from"open";var $=`
1
+ import{a as Q,b as R,c as T,d as W}from"./chunk-zbcbh3gs.js";import"./chunk-q5yn875m.js";import"./chunk-x4ta13s0.js";import"./chunk-365tx34d.js";import"./chunk-esnkk33h.js";import{ba as M}from"./chunk-5gxn6wrh.js";import"./chunk-cj5w17y3.js";import{Aa as J}from"./chunk-j73schtj.js";import"./chunk-n2dcjqbe.js";import"./chunk-5yffdaq2.js";import"./chunk-yddnm9n2.js";import"./chunk-1e2phnbj.js";import"./chunk-37rethcy.js";import"./chunk-7ycmx7c2.js";import"./chunk-set7v1rf.js";import"./chunk-j2ag7hh6.js";import b from"chalk";import H from"open";var $=`
2
2
  ____ _ _
3
3
  | __ )| | __ _ __| | ___
4
4
  | _ \\| |/ _\` |/ _\` |/ _ \\
@@ -1,2 +1,2 @@
1
- var e={name:"blade-code",version:"0.5.7",private:!1,description:"🗡️ Blade Code - 智能代码助手命令行工具",type:"module",bin:{blade:"dist/blade.js"},files:["dist","vendor/ripgrep/**","README.md"],scripts:{dev:"node scripts/run-bun.js --watch src/blade.tsx","dev:serve":"node scripts/run-bun.js --watch src/blade.tsx serve --port 4097",build:"rm -rf dist && node scripts/run-bun.js run scripts/build.ts",start:"node scripts/run-bun.js run dist/blade.js",test:"node scripts/test.js","test:all":"vitest run --config vitest.config.ts","test:unit":"node scripts/test.js unit","test:integration":"node scripts/test.js integration","test:cli":"node scripts/test.js cli","test:headless-core":"node scripts/test.js headlessCore","test:e2e":"node scripts/test.js e2e","test:performance":"node scripts/test.js performance","test:snapshot":"node scripts/test.js snapshot","test:security":"node scripts/test.js security","test:coverage":"node scripts/test.js all --coverage","test:watch":"vitest --watch --config vitest.config.ts","benchmark:repo":"node scripts/run-bun.js run scripts/run-real-repo-benchmark.ts","test:update-snapshots":"node scripts/test.js snapshot --update",lint:"biome lint src tests","lint:fix":"biome lint --write src tests","type-check":"tsc --noEmit","format:check":"biome format src tests",ready:"node scripts/run-bun.js run scripts/ready.ts","detect-unused":"node scripts/run-bun.js run scripts/detect-unused.ts",release:"node scripts/release.js","release:dry":"node scripts/release.js --dry-run","release:major":"node scripts/release.js --major","release:minor":"node scripts/release.js --minor","release:patch":"node scripts/release.js --patch"},keywords:["cli","blade","ai","assistant","agent","llm"],author:"echoVic",license:"MIT",engines:{node:">=20.0.0"},optionalDependencies:{"@vscode/ripgrep":"^1.17.0","bun-pty":"^0.4.8","node-pty":"1.0.0"},dependencies:{"@agentclientprotocol/sdk":"^0.12.0","@ai-sdk/anthropic":"^3.0.7","@ai-sdk/azure":"^3.0.5","@ai-sdk/deepseek":"^2.0.4","@ai-sdk/google":"^3.0.4","@ai-sdk/openai":"^3.0.26","@ai-sdk/openai-compatible":"^2.0.4","@inkjs/ui":"^2.0.0","@modelcontextprotocol/sdk":"^1.17.4",ahooks:"^3.9.6",ai:"^6.0.39","ansi-escapes":"^7.2.0","async-mutex":"^0.5.0",axios:"^1.12.2",chalk:"^5.4.1",diff:"^8.0.2","fast-glob":"^3.3.3","fuse.js":"^7.1.0","gray-matter":"^4.0.3",hono:"^4.7.10",ink:"npm:@jrichman/ink@6.4.10","ink-big-text":"^2.0.0","ink-gradient":"^3.0.0","ink-select-input":"^6.2.0","ink-spinner":"^5.0.0","ink-text-input":"^6.0.0","js-tiktoken":"^1.0.21","lodash-es":"^4.17.21",lowlight:"^3.3.0","lru-cache":"^11.2.4",nanoid:"^5.1.6",open:"^10.1.2",openai:"^6.2.0",picomatch:"^4.0.3",react:"^19.1.1","react-dom":"^19.1.1",semver:"^7.7.3","string-width":"^8.1.0",undici:"^7.16.0","write-file-atomic":"^7.0.0",ws:"^8.18.0",yaml:"^2.8.1",yargs:"^18.0.0",zod:"^3.24.2","zod-to-json-schema":"^3.24.6",zustand:"^5.0.9"},devDependencies:{"@biomejs/biome":"^2.2.4","@types/bun":"^1.3.4","@types/json-schema":"^7.0.15","@types/lodash-es":"^4.17.12","@types/node":"^22.15.24","@types/picomatch":"^4.0.2","@types/react":"^19.1.1","@types/react-dom":"^19.1.1","@types/semver":"^7.7.1","@types/write-file-atomic":"^4.0.3","@types/ws":"^8.5.12","@types/yargs":"^17.0.33","@vitest/coverage-v8":"^3.0.0",jsdom:"^26.0.0",typescript:"^5.9.2",vitest:"^3.0.0"}};function r(){return{name:e.name,version:e.version,description:e.description}}function n(){return e.version}function o(){return e.name}function c(){return e.description}function d(){return`v${e.version}`}function a(){return`v${e.version} © 2025 Blade Code`}
1
+ var e={name:"blade-code",version:"0.5.8",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,12 +1,12 @@
1
- import{nb as W0}from"./chunk-1e2phnbj.js";import{rb as e0}from"./chunk-37rethcy.js";import{xb as k}from"./chunk-7ycmx7c2.js";import{Bb as M}from"./chunk-set7v1rf.js";import{Db as RQ}from"./chunk-j2ag7hh6.js";function G0(Q){return Q.role==="system"&&Array.isArray(Q.content)}class V0{systemMessages;_history;_pending=[];context;constructor(Q,Z){this.context=Q;let $=Q.messages.find(G0);if($)this.systemMessages=[$];else if(Z)this.systemMessages=[{role:"system",content:[{type:"text",text:Z,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,Z){if(Q==="system")throw Error("Cannot append system control message via appendControl. Use constructor for root system prompt.");this._pending.push(Z)}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((Z)=>!G0(Z))}writeback(){this.commitPending(),this.context.messages=this._history}get hasSystemPrompt(){return this.systemMessages.length>0}}async function fQ(Q,Z){let $;while(!($=await Q.next()).done)if(Z)await Z($.value);return $.value}function g0(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 c0(Q){return{budget:Q.budget,usage:0,consecutiveContinuations:0,lastOutputDelta:0,isSubagent:Q.isSubagent??!1}}function u0(Q,Z,$){return{...Q,usage:Q.usage+Z,lastOutputDelta:Z,consecutiveContinuations:$?Q.consecutiveContinuations+1:0}}var r=M("Agent"),TQ=3;function N0(Q,Z,$){if(Q!=="length")return{action:"none"};if(Z>=TQ)return{action:"truncated"};if(g0($)==="stop")return r.info("[Loop] Token budget: diminishing returns detected, skipping recovery"),{action:"budget_stop"};return{action:"recover"}}var xQ=[/:\s*$/,/:\s*$/,/\.\.\.\s*$/,/让我(先|来|开始|查看|检查|修复)/,/Let me (first|start|check|look|fix)/i,/I('ll| will) (now |)(create|write|edit|update|modify|fix|add|implement)/i,/我(现在就|来|要)(创建|写入|编辑|修改|修复|添加|实现)/,/\d+\.\s+(First|Next|Then|Finally)/i],hQ=/```[\s\S]{50,}```/,i0="请执行你提到的操作,不要只是描述。使用 Edit/Write/Bash 工具来实际修改文件。",kQ=2;function A0(Q,Z,$=!0){if(!Q||Z>=kQ)return{action:"none"};if(!$&&hQ.test(Q))return{action:"retry",prompt:i0};let J=Q.slice(-200),q=J.match(/```/g);if(q&&q.length%2!==0)return{action:"none"};if(xQ.some((G)=>G.test(J)))return{action:"retry",prompt:i0};return{action:"none"}}var n0=30000;async function y0(Q){try{let $=W0.getInstance().executeStopHooks({projectDir:k(),sessionId:Q.sessionId,permissionMode:Q.permissionMode,reason:Q.reason,abortSignal:Q.abortSignal}),J,q=new Promise((z)=>{J=setTimeout(()=>z("timeout"),n0)});try{let z=await Promise.race([$,q]);if(z==="timeout")return r.warn(`[Loop] Stop hook 超时 (${n0}ms),按 shouldStop: true 处理`),{action:"stop"};let G=z;if(!G.shouldStop)return{action:"continue",reason:G.continueReason};return{action:"stop"}}finally{clearTimeout(J)}}catch(Z){return r.warn("[Loop] Stop hook execution failed:",Z),{action:"stop"}}}var CQ=0.9;async function l0(Q){try{let{SpecManager:Z}=await import("./chunk-jmsm3eam.js"),$=Z.getInstance();if(!$.isActive())return{action:"none"};let J=$.getCurrentSpec();if(!J||J.phase!=="implementation")return{action:"none"};if(Q.maxTurns>0&&Q.turnsCount>=Q.maxTurns*CQ)return r.info(`[RalphLoop] 轮次接近上限 (${Q.turnsCount}/${Q.maxTurns}),停止自动继续`),{action:"none"};let q=J.tasks??[],z=q.filter((H)=>H.status==="completed"||H.status==="skipped").length,G=q.length;if(z>=G)return{action:"none"};let V=q.find((H)=>H.status==="pending"||H.status==="in_progress"),W=`[Ralph Loop] Spec "${J.name}" 仍有未完成任务。
1
+ import{nb as K0}from"./chunk-1e2phnbj.js";import{rb as QQ}from"./chunk-37rethcy.js";import{xb as k}from"./chunk-7ycmx7c2.js";import{Bb as M}from"./chunk-set7v1rf.js";import{Db as xQ}from"./chunk-j2ag7hh6.js";function W0(Q){return Q.role==="system"&&Array.isArray(Q.content)}class Y0{systemMessages;_history;_pending=[];context;constructor(Q,Z){this.context=Q;let $=Q.messages.find(W0);if($)this.systemMessages=[$];else if(Z)this.systemMessages=[{role:"system",content:[{type:"text",text:Z,providerOptions:{anthropic:{cacheControl:{type:"ephemeral"}}}}]}];else this.systemMessages=[];this._history=Q.messages.filter((J)=>!W0(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,Z){if(Q==="system")throw Error("Cannot append system control message via appendControl. Use constructor for root system prompt.");this._pending.push(Z)}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((Z)=>!W0(Z))}writeback(){this.commitPending(),this.context.messages=this._history}get hasSystemPrompt(){return this.systemMessages.length>0}}async function TQ(Q,Z){let $;while(!($=await Q.next()).done)if(Z)await Z($.value);return $.value}function c0(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 u0(Q){return{budget:Q.budget,usage:0,consecutiveContinuations:0,lastOutputDelta:0,isSubagent:Q.isSubagent??!1}}function i0(Q,Z,$){return{...Q,usage:Q.usage+Z,lastOutputDelta:Z,consecutiveContinuations:$?Q.consecutiveContinuations+1:0}}var r=M("Agent"),hQ=3;function y0(Q,Z,$){if(Q!=="length")return{action:"none"};if(Z>=hQ)return{action:"truncated"};if(c0($)==="stop")return r.info("[Loop] Token budget: diminishing returns detected, skipping recovery"),{action:"budget_stop"};return{action:"recover"}}var kQ=[/:\s*$/,/:\s*$/,/\.\.\.\s*$/,/让我(先|来|开始|查看|检查|修复)/,/Let me (first|start|check|look|fix)/i,/I('ll| will) (now |)(create|write|edit|update|modify|fix|add|implement)/i,/我(现在就|来|要)(创建|写入|编辑|修改|修复|添加|实现)/,/\d+\.\s+(First|Next|Then|Finally)/i],CQ=/```[\s\S]{50,}```/,n0="请执行你提到的操作,不要只是描述。使用 Edit/Write/Bash 工具来实际修改文件。",pQ=2;function A0(Q,Z,$=!0){if(!Q||Z>=pQ)return{action:"none"};if(!$&&CQ.test(Q))return{action:"retry",prompt:n0};let J=Q.slice(-200),q=J.match(/```/g);if(q&&q.length%2!==0)return{action:"none"};if(kQ.some((G)=>G.test(J)))return{action:"retry",prompt:n0};return{action:"none"}}var l0=30000;async function S0(Q){try{let $=K0.getInstance().executeStopHooks({projectDir:k(),sessionId:Q.sessionId,permissionMode:Q.permissionMode,reason:Q.reason,abortSignal:Q.abortSignal}),J,q=new Promise((z)=>{J=setTimeout(()=>z("timeout"),l0)});try{let z=await Promise.race([$,q]);if(z==="timeout")return r.warn(`[Loop] Stop hook 超时 (${l0}ms),按 shouldStop: true 处理`),{action:"stop"};let G=z;if(!G.shouldStop)return{action:"continue",reason:G.continueReason};return{action:"stop"}}finally{clearTimeout(J)}}catch(Z){return r.warn("[Loop] Stop hook execution failed:",Z),{action:"stop"}}}var dQ=0.9;async function a0(Q){try{let{SpecManager:Z}=await import("./chunk-jmsm3eam.js"),$=Z.getInstance();if(!$.isActive())return{action:"none"};let J=$.getCurrentSpec();if(!J||J.phase!=="implementation")return{action:"none"};if(Q.maxTurns>0&&Q.turnsCount>=Q.maxTurns*dQ)return r.info(`[RalphLoop] 轮次接近上限 (${Q.turnsCount}/${Q.maxTurns}),停止自动继续`),{action:"none"};let q=J.tasks??[],z=q.filter((B)=>B.status==="completed"||B.status==="skipped").length,G=q.length;if(z>=G)return{action:"none"};let V=q.find((B)=>B.status==="pending"||B.status==="in_progress"),W=`[Ralph Loop] Spec "${J.name}" 仍有未完成任务。
2
2
  `+`进度: ${z}/${G} 任务已完成。
3
3
  `+(V?`下一个任务: ${V.title}${V.description?` — ${V.description}`:""}
4
- `:"")+"请继续执行下一个未完成的任务,不要停止。";return r.info(`[RalphLoop] Spec "${J.name}" 进度 ${z}/${G},自动继续`),{action:"continue",reason:W}}catch{return{action:"none"}}}var s=M("Agent");function t(Q){return Q.executionEngine?.getContextManager()}async function g(Q,Z,$,J=null){try{let q=t(Q),z=typeof $==="string"?$.trim()!=="":$.some((G)=>G.type==="text"?G.text.trim()!=="":!0);if(q&&Z.sessionId&&z)return await q.saveMessage(Z.sessionId,"user",$,J,void 0,Z.subagentInfo)}catch(q){s.warn("[Loop] 保存用户消息失败:",q)}return null}async function C(Q,Z,$,J){try{let q=t(Q);if(q&&Z.sessionId&&$.trim())return await q.saveMessage(Z.sessionId,"assistant",$,J,void 0,Z.subagentInfo)}catch(q){s.warn("[Loop] 保存助手消息失败:",q)}return null}async function S0(Q,Z,$,J,q){try{let z=t(Q);if(z&&Z.sessionId)return await z.saveToolUse(Z.sessionId,$,J,q,Z.subagentInfo)}catch(z){s.warn("[Loop] 保存工具调用失败:",z)}return null}async function P0(Q,Z,$,J,q,z,G,V){try{let W=t(Q);if(W&&Z.sessionId)return await W.saveToolResult(Z.sessionId,$,J,q,z,G,Z.subagentInfo,V)}catch(W){s.warn("[Loop] 保存工具结果失败:",W)}return null}async function Y0(Q,Z,$,J){try{let q=t(Q);if(q&&Z.sessionId)return await q.saveCompaction(Z.sessionId,$,J,null)}catch(q){s.warn("[Loop] 保存压缩数据失败:",q)}return null}function a0(Q,Z){if(!["TaskCreate","TaskUpdate","TaskList"].includes(Q.function.name)||!Z.success||!Z.llmContent&&!Z.metadata)return null;let $=typeof Z.llmContent==="object"?Z.llmContent:{};return{kind:"task_update",tasks:Z.metadata?.tasks||$.tasks||[]}}function r0(Q,Z,$){if(Q.function.name!=="Skill"||!Z.success||!Z.metadata)return;let J=Z.metadata;if(J.skillName)$.onSkillActivated?.({skillName:J.skillName,allowedTools:J.allowedTools,basePath:J.basePath||""})}function o0(Q){let Z=Q.metadata;if(!Z)return;return Z.modelId?.toString().trim()||Z.model?.toString().trim()||void 0||void 0}function pQ(Q,Z){if(Q.function.name!=="Task")return null;let $=Z.metadata;if(!$?.subagentSessionId)return null;let J=$.subagentSessionId,q=$.subagentType||"Task",z=$.subagentStatus;if(z==="completed"||z==="failed"||z==="cancelled")return{kind:"subagent_completed",sessionId:J,success:z==="completed",summary:$.subagentSummary};if(z==="running"){let G="";try{G=JSON.parse(Q.function.arguments).prompt||""}catch{}return{kind:"subagent_spawned",sessionId:J,type:q,prompt:G}}return null}async function M0(Q,Z,$){let J=a0(Q,Z),q=pQ(Q,Z);r0(Q,Z,$);let z=o0(Z);if(z)await $.onModelSwitch?.(z);return q||J}import{nanoid as HZ}from"nanoid";import{promises as gQ}from"node:fs";import{nanoid as u}from"nanoid";import{promises as K0}from"node:fs";var e=M("Tool");class p{static instance=null;accessedFiles=new Map;constructor(){}static getInstance(){if(!p.instance)p.instance=new p;return p.instance}async recordFileRead(Q,Z){try{let $=await K0.stat(Q),J={filePath:Q,accessTime:Date.now(),mtime:$.mtimeMs,sessionId:Z,lastOperation:"read"};this.accessedFiles.set(Q,J),e.debug(`记录文件读取: ${Q}`)}catch($){e.warn(`记录文件读取失败: ${Q}`,$)}}async recordFileEdit(Q,Z,$="edit"){try{let J=await K0.stat(Q),q={filePath:Q,accessTime:Date.now(),mtime:J.mtimeMs,sessionId:Z,lastOperation:$};this.accessedFiles.set(Q,q),e.debug(`记录文件${$==="edit"?"编辑":"写入"}: ${Q}`)}catch(J){e.warn(`记录文件${$==="edit"?"编辑":"写入"}失败: ${Q}`,J)}}hasFileBeenRead(Q,Z){let $=this.accessedFiles.get(Q);if(!$)return!1;if(Z&&$.sessionId!==Z)return!1;return!0}async checkFileModification(Q){let Z=this.accessedFiles.get(Q);if(!Z)return{modified:!1,message:"文件未被跟踪"};try{let $=await K0.stat(Q);if(Math.abs($.mtimeMs-Z.mtime)>1)return{modified:!0,message:`文件在访问后被修改(访问时间: ${new Date(Z.accessTime).toISOString()}, 当前修改时间: ${$.mtime.toISOString()})`};return{modified:!1}}catch($){let J=$;if(J.code==="ENOENT")return{modified:!0,message:"文件已被删除"};return{modified:!1,message:`无法检查文件状态: ${J.message}`}}}async checkExternalModification(Q){let Z=this.accessedFiles.get(Q);if(!Z)return{isExternal:!1,message:"文件未被跟踪"};try{let $=await K0.stat(Q);if($.mtimeMs-Z.mtime>2000)return{isExternal:!0,message:`文件在 ${new Date(Z.accessTime).toISOString()} (${Z.lastOperation}) 之后被外部程序修改(当前修改时间: ${$.mtime.toISOString()})`};return{isExternal:!1}}catch($){let J=$;if(J.code==="ENOENT")return{isExternal:!0,message:"文件已被删除"};return e.warn(`检查文件外部修改失败: ${Q}`,$),{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($.sessionId===Q)this.accessedFiles.delete(Z)}getTrackedFiles(){return Array.from(this.accessedFiles.keys())}getTrackedFileCount(){return this.accessedFiles.size}static resetInstance(){p.instance=null}}import{readFile as dQ}from"node:fs/promises";import{basename as mQ}from"node:path";class X0{static MAX_FILES=5;static MAX_LINES_PER_FILE=1000;static analyzeFiles(Q){let Z=new Map;return Q.forEach((J,q)=>{let z=typeof J.content==="string"?J.content:(J.content||[]).filter((V)=>V.type==="text").map((V)=>V.text).join(`
5
- `);if(this.extractFilePathsFromContent(z).forEach((V)=>{this.updateFileReference(Z,V,q,!1)}),J.tool_calls&&Array.isArray(J.tool_calls))J.tool_calls.forEach((V)=>{let W=this.extractFilePathsFromToolCall(V),H=V.type==="function"&&"function"in V?V.function?.name:"",F=["Write","Edit"].includes(H||"");W.forEach((L)=>{this.updateFileReference(Z,L,q,F)})})}),Array.from(Z.values()).sort((J,q)=>{if(J.wasModified!==q.wasModified)return J.wasModified?-1:1;if(J.mentions!==q.mentions)return q.mentions-J.mentions;return q.lastMentioned-J.lastMentioned}).slice(0,this.MAX_FILES)}static async readFilesContent(Q){let Z=[];for(let $ of Q)try{let J=await dQ($,"utf-8"),q=J.split(`
4
+ `:"")+"请继续执行下一个未完成的任务,不要停止。";return r.info(`[RalphLoop] Spec "${J.name}" 进度 ${z}/${G},自动继续`),{action:"continue",reason:W}}catch{return{action:"none"}}}var s=M("Agent");function t(Q){return Q.executionEngine?.getContextManager()}async function m(Q,Z,$,J=null){try{let q=t(Q),z=typeof $==="string"?$.trim()!=="":$.some((G)=>G.type==="text"?G.text.trim()!=="":!0);if(q&&Z.sessionId&&z)return await q.saveMessage(Z.sessionId,"user",$,J,void 0,Z.subagentInfo)}catch(q){s.warn("[Loop] 保存用户消息失败:",q)}return null}async function C(Q,Z,$,J){try{let q=t(Q);if(q&&Z.sessionId&&$.trim())return await q.saveMessage(Z.sessionId,"assistant",$,J,void 0,Z.subagentInfo)}catch(q){s.warn("[Loop] 保存助手消息失败:",q)}return null}async function P0(Q,Z,$,J,q){try{let z=t(Q);if(z&&Z.sessionId)return await z.saveToolUse(Z.sessionId,$,J,q,Z.subagentInfo)}catch(z){s.warn("[Loop] 保存工具调用失败:",z)}return null}async function M0(Q,Z,$,J,q,z,G,V){try{let W=t(Q);if(W&&Z.sessionId)return await W.saveToolResult(Z.sessionId,$,J,q,z,G,Z.subagentInfo,V)}catch(W){s.warn("[Loop] 保存工具结果失败:",W)}return null}async function X0(Q,Z,$,J){try{let q=t(Q);if(q&&Z.sessionId)return await q.saveCompaction(Z.sessionId,$,J,null)}catch(q){s.warn("[Loop] 保存压缩数据失败:",q)}return null}function r0(Q,Z){if(!["TaskCreate","TaskUpdate","TaskList"].includes(Q.function.name)||!Z.success||!Z.llmContent&&!Z.metadata)return null;let $=typeof Z.llmContent==="object"?Z.llmContent:{};return{kind:"task_update",tasks:Z.metadata?.tasks||$.tasks||[]}}function o0(Q,Z,$){if(Q.function.name!=="Skill"||!Z.success||!Z.metadata)return;let J=Z.metadata;if(J.skillName)$.onSkillActivated?.({skillName:J.skillName,allowedTools:J.allowedTools,basePath:J.basePath||""})}function s0(Q){let Z=Q.metadata;if(!Z)return;return Z.modelId?.toString().trim()||Z.model?.toString().trim()||void 0||void 0}function mQ(Q,Z){if(Q.function.name!=="Task")return null;let $=Z.metadata;if(!$?.subagentSessionId)return null;let J=$.subagentSessionId,q=$.subagentType||"Task",z=$.subagentStatus;if(z==="completed"||z==="failed"||z==="cancelled")return{kind:"subagent_completed",sessionId:J,success:z==="completed",summary:$.subagentSummary};if(z==="running"){let G="";try{G=JSON.parse(Q.function.arguments).prompt||""}catch{}return{kind:"subagent_spawned",sessionId:J,type:q,prompt:G}}return null}async function f0(Q,Z,$){let J=r0(Q,Z),q=mQ(Q,Z);o0(Q,Z,$);let z=s0(Z);if(z)await $.onModelSwitch?.(z);return q||J}import{nanoid as wZ}from"nanoid";import{promises as uQ}from"node:fs";import{nanoid as c}from"nanoid";import{promises as H0}from"node:fs";var e=M("Tool");class p{static instance=null;accessedFiles=new Map;constructor(){}static getInstance(){if(!p.instance)p.instance=new p;return p.instance}async recordFileRead(Q,Z){try{let $=await H0.stat(Q),J={filePath:Q,accessTime:Date.now(),mtime:$.mtimeMs,sessionId:Z,lastOperation:"read"};this.accessedFiles.set(Q,J),e.debug(`记录文件读取: ${Q}`)}catch($){e.warn(`记录文件读取失败: ${Q}`,$)}}async recordFileEdit(Q,Z,$="edit"){try{let J=await H0.stat(Q),q={filePath:Q,accessTime:Date.now(),mtime:J.mtimeMs,sessionId:Z,lastOperation:$};this.accessedFiles.set(Q,q),e.debug(`记录文件${$==="edit"?"编辑":"写入"}: ${Q}`)}catch(J){e.warn(`记录文件${$==="edit"?"编辑":"写入"}失败: ${Q}`,J)}}hasFileBeenRead(Q,Z){let $=this.accessedFiles.get(Q);if(!$)return!1;if(Z&&$.sessionId!==Z)return!1;return!0}async checkFileModification(Q){let Z=this.accessedFiles.get(Q);if(!Z)return{modified:!1,message:"文件未被跟踪"};try{let $=await H0.stat(Q);if(Math.abs($.mtimeMs-Z.mtime)>1)return{modified:!0,message:`文件在访问后被修改(访问时间: ${new Date(Z.accessTime).toISOString()}, 当前修改时间: ${$.mtime.toISOString()})`};return{modified:!1}}catch($){let J=$;if(J.code==="ENOENT")return{modified:!0,message:"文件已被删除"};return{modified:!1,message:`无法检查文件状态: ${J.message}`}}}async checkExternalModification(Q){let Z=this.accessedFiles.get(Q);if(!Z)return{isExternal:!1,message:"文件未被跟踪"};try{let $=await H0.stat(Q);if($.mtimeMs-Z.mtime>2000)return{isExternal:!0,message:`文件在 ${new Date(Z.accessTime).toISOString()} (${Z.lastOperation}) 之后被外部程序修改(当前修改时间: ${$.mtime.toISOString()})`};return{isExternal:!1}}catch($){let J=$;if(J.code==="ENOENT")return{isExternal:!0,message:"文件已被删除"};return e.warn(`检查文件外部修改失败: ${Q}`,$),{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($.sessionId===Q)this.accessedFiles.delete(Z)}getTrackedFiles(){return Array.from(this.accessedFiles.keys())}getTrackedFileCount(){return this.accessedFiles.size}static resetInstance(){p.instance=null}}import{readFile as gQ}from"node:fs/promises";import{basename as cQ}from"node:path";class B0{static MAX_FILES=5;static MAX_LINES_PER_FILE=1000;static analyzeFiles(Q){let Z=new Map;return Q.forEach((J,q)=>{let z=typeof J.content==="string"?J.content:(J.content||[]).filter((V)=>V.type==="text").map((V)=>V.text).join(`
5
+ `);if(this.extractFilePathsFromContent(z).forEach((V)=>{this.updateFileReference(Z,V,q,!1)}),J.tool_calls&&Array.isArray(J.tool_calls))J.tool_calls.forEach((V)=>{let W=this.extractFilePathsFromToolCall(V),B=V.type==="function"&&"function"in V?V.function?.name:"",F=["Write","Edit"].includes(B||"");W.forEach((O)=>{this.updateFileReference(Z,O,q,F)})})}),Array.from(Z.values()).sort((J,q)=>{if(J.wasModified!==q.wasModified)return J.wasModified?-1:1;if(J.mentions!==q.mentions)return q.mentions-J.mentions;return q.lastMentioned-J.lastMentioned}).slice(0,this.MAX_FILES)}static async readFilesContent(Q){let Z=[];for(let $ of Q)try{let J=await gQ($,"utf-8"),q=J.split(`
6
6
  `),z=q.length,G=J,V=!1,W=z;if(z>this.MAX_LINES_PER_FILE)G=q.slice(0,this.MAX_LINES_PER_FILE).join(`
7
7
  `),G+=`
8
8
 
9
- ... (truncated ${z-this.MAX_LINES_PER_FILE} lines)`,V=!0,W=this.MAX_LINES_PER_FILE;Z.push({path:$,content:G,truncated:V,lines:z,includedLines:W})}catch(J){console.warn(`[FileAnalyzer] 无法读取文件: ${$}`,J)}return Z}static extractFilePathsFromContent(Q){let Z=new Set,$=/```(?:\w+)?\s*\n?([\s\S]*?)```/g,J=Array.from(Q.matchAll($));for(let z of J){let G=z[1];this.extractPathsFromText(G).forEach((W)=>Z.add(W))}return this.extractPathsFromText(Q).forEach((z)=>Z.add(z)),Array.from(Z)}static extractPathsFromText(Q){let Z=[],$=[/(?:src|tests?|docs?|lib|config|scripts?|bin|utils?|components?|services?|hooks?)\/[\w\-/.]+\.[\w]+/g,/(?:package|tsconfig|vite\.config|webpack\.config|next\.config|babel\.config)\.[\w]+/g,/(?:\.\.?\/|\/)[a-zA-Z0-9\-_/.]+\.[\w]+/g];for(let J of $){let q=Array.from(Q.matchAll(J));for(let z of q){let G=z[0];if(G=G.replace(/[,。;:!?""''()【】《》]$/g,""),G=G.replace(/[,.;:!?"'()[\]<>]$/g,""),this.isValidFilePath(G))Z.push(G)}}return Z}static extractFilePathsFromToolCall(Q){let Z=[];if(Q.type!=="function"||!Q.function)return Z;try{let $=Q.function.name,J=JSON.parse(Q.function.arguments||"{}");if(["Read","Write","Edit","Glob","Grep","NotebookEdit","mcp__github__get_file_contents","mcp__github__create_or_update_file"].includes($)){let z=["file_path","path","notebook_path","filePath"];for(let G of z)if(J[G]&&typeof J[G]==="string")Z.push(J[G])}}catch{}return Z}static updateFileReference(Q,Z,$,J){let q=Q.get(Z);if(q)q.mentions++,q.lastMentioned=$,q.wasModified=q.wasModified||J;else Q.set(Z,{path:Z,mentions:1,lastMentioned:$,wasModified:J})}static isValidFilePath(Q){if(!Q.includes("/"))return!1;let Z=mQ(Q);if(!Z.includes("."))return!1;let $=["ts","tsx","js","jsx","json","md","py","java","go","rs","c","cpp","h","css","scss","html","xml","yaml","yml","toml","sh","bash","sql","graphql","vue","svelte"],J=Z.split(".").pop()?.toLowerCase();if(!J||!$.includes(J))return!1;return!0}}import{encodingForModel as s0}from"js-tiktoken";class Q0{static encodingCache=new Map;static countTokens(Q,Z){let $=this.getEncoding(Z),J=0;for(let q of Q){if(J+=4,q.role)J+=$.encode(q.role).length;if(q.content)if(typeof q.content==="string")J+=$.encode(q.content).length;else J+=$.encode(JSON.stringify(q.content)).length;if(q.tool_calls&&Array.isArray(q.tool_calls))J+=this.countToolCallTokens(q.tool_calls,$);if(q.name)J+=$.encode(q.name).length}return J}static getTokenLimit(Q){return Q}static shouldCompact(Q,Z,$,J=0.8){let q=this.countTokens(Q,Z),z=Math.floor($*J);return q>=z}static getEncoding(Q){if(!this.encodingCache.has(Q))try{let Z=s0(Q);this.encodingCache.set(Q,Z)}catch{try{let Z=s0("gpt-4");this.encodingCache.set(Q,Z)}catch{console.warn(`[TokenCounter] 无法为模型 ${Q} 获取 encoding,使用粗略估算`),this.encodingCache.set(Q,{encode:(Z)=>{return Array(Math.ceil(Z.length/4))}})}}return this.encodingCache.get(Q)}static countToolCallTokens(Q,Z){let $=0;for(let J of Q){if($+=4,J.type==="function"&&J.function?.name)$+=Z.encode(J.function.name).length;if(J.type==="function"&&J.function?.arguments)$+=Z.encode(J.function.arguments).length;if(J.id)$+=Z.encode(J.id).length}return $}static clearCache(){this.encodingCache.clear()}static estimateTokens(Q){let Z=(Q.match(/[\u4e00-\u9fa5]/g)||[]).length,$=Q.length-Z;return Math.ceil(Z/1.5+$/4)}}function c(Q){if(!(Q instanceof Error))return!1;if(Q.name==="AbortError")return!0;if(Q instanceof DOMException&&Q.name==="AbortError")return!0;if(Q.message.includes("aborted"))return!0;return!1}function t0(...Q){let Z=Q.filter(Boolean);if(Z.length===0)return new AbortController().signal;if(Z.length===1)return Z[0];let $=AbortSignal;if(typeof $.any==="function")return $.any(Z);for(let z of Z)if(z.aborted)return z;let J=new AbortController,q=new Map;for(let z of Z){let G=()=>{J.abort(z.reason);for(let[V,W]of q)V.removeEventListener("abort",W)};q.set(z,G)}for(let[z,G]of q)z.addEventListener("abort",G,{once:!0});return J.signal}var H0=new Map,cQ=3;class n{static THRESHOLD_PERCENT=0.8;static RETAIN_PERCENT=0.2;static FALLBACK_RETAIN_PERCENT=0.3;static async compact(Q,Z){if(Z.signal?.aborted)throw new DOMException("Aborted","AbortError");let $=Z.actualPreTokens??Q0.countTokens(Q,Z.modelName),J=Z.actualPreTokens?"actual (from LLM usage)":"estimated";console.log(`[CompactionService] preTokens source: ${J}`);try{let V=await W0.getInstance().executeCompactionHooks(Z.trigger,{projectDir:k(),sessionId:Z.sessionId||"unknown",permissionMode:Z.permissionMode||"default",messagesBefore:Q.length,tokensBefore:$});if(V.blockCompaction)return console.log(`[CompactionService] Compaction hook 阻止压缩: ${V.blockReason||"(无原因)"}`),{success:!1,summary:"",preTokens:$,postTokens:$,filesIncluded:[],compactedMessages:Q,boundaryMessage:{role:"system",content:""},summaryMessage:{role:"user",content:""},error:V.blockReason||"Compaction blocked by hook"};if(V.warning)console.warn(`[CompactionService] Compaction hook warning: ${V.warning}`)}catch(G){console.warn("[CompactionService] Compaction hook execution failed:",G)}let q=Z.sessionId??"_default",z=H0.get(q)??0;if(z>=cQ)return console.warn(`[CompactionService] Circuit breaker open (${z} consecutive failures for session ${q}), using fallback`),this.fallbackCompact(Q,Z,$,Error("Circuit breaker open"));try{console.log("[CompactionService] 开始压缩,消息数:",Q.length),console.log("[CompactionService] 压缩前 tokens:",$);let V=X0.analyzeFiles(Q).map((S)=>S.path);console.log("[CompactionService] 提取重点文件:",V);let W=await X0.readFilesContent(V);console.log("[CompactionService] 成功读取文件:",W.length);let H=await this.generateSummary(Q,W,Z);console.log("[CompactionService] 生成总结,长度:",H.length);let F=Math.ceil(Q.length*this.RETAIN_PERCENT),L=Q.slice(-F),Y=new Set;for(let S of L)if(S.role==="assistant"&&S.tool_calls)for(let m of S.tool_calls)Y.add(m.id);let O=L.filter((S)=>{if(S.role==="tool"&&S.tool_call_id)return Y.has(S.tool_call_id);return!0});console.log("[CompactionService] 保留消息数:",F),console.log("[CompactionService] 过滤后保留消息数:",O.length);let _=u(),B=this.createBoundaryMessage(_,Z.trigger,$),j=u(),P=this.createSummaryMessage(j,H),R=[P,...O],h=await this.buildFileRestorationMessage();if(h)R.push(h);let f=Q0.countTokens(R,Z.modelName);return console.log("[CompactionService] 压缩完成!"),console.log("[CompactionService] Token 变化:",$,"->",f,`(-${((1-f/$)*100).toFixed(1)}%)`),H0.delete(q),{success:!0,summary:H,preTokens:$,postTokens:f,filesIncluded:V,compactedMessages:R,boundaryMessage:B,summaryMessage:P}}catch(G){if(c(G))throw G;return H0.set(q,(H0.get(q)??0)+1),console.error("[CompactionService] 压缩失败,使用降级策略",G),this.fallbackCompact(Q,Z,$,G)}}static async generateSummary(Q,Z,$){let J=this.buildCompactionPrompt(Q,Z);if(console.log("[CompactionService] 使用压缩模型:",$.modelName),$.signal?.aborted)throw new DOMException("Aborted","AbortError");let G=(await(await e0({apiKey:$.apiKey||process.env.BLADE_API_KEY||"",baseUrl:$.baseURL||process.env.BLADE_BASE_URL||"https://api.openai.com/v1",model:$.modelName,temperature:0.3,maxOutputTokens:8000,timeout:60000,provider:"openai-compatible"})).chat([{role:"user",content:J}],[],$.signal)).content||"",V=G.match(/<summary>([\s\S]*?)<\/summary>/);if(!V)return console.warn("[CompactionService] 总结格式不正确,使用完整响应"),G;return V[1].trim()}static buildCompactionPrompt(Q,Z){let $=Q.map((z,G)=>{let V=z.role||"unknown",W=typeof z.content==="string"?z.content:JSON.stringify(z.content),H=5000,F=W.length>5000?W.substring(0,5000)+"...":W;return`[${G+1}] ${V}: ${F}`}).join(`
9
+ ... (truncated ${z-this.MAX_LINES_PER_FILE} lines)`,V=!0,W=this.MAX_LINES_PER_FILE;Z.push({path:$,content:G,truncated:V,lines:z,includedLines:W})}catch(J){console.warn(`[FileAnalyzer] 无法读取文件: ${$}`,J)}return Z}static extractFilePathsFromContent(Q){let Z=new Set,$=/```(?:\w+)?\s*\n?([\s\S]*?)```/g,J=Array.from(Q.matchAll($));for(let z of J){let G=z[1];this.extractPathsFromText(G).forEach((W)=>Z.add(W))}return this.extractPathsFromText(Q).forEach((z)=>Z.add(z)),Array.from(Z)}static extractPathsFromText(Q){let Z=[],$=[/(?:src|tests?|docs?|lib|config|scripts?|bin|utils?|components?|services?|hooks?)\/[\w\-/.]+\.[\w]+/g,/(?:package|tsconfig|vite\.config|webpack\.config|next\.config|babel\.config)\.[\w]+/g,/(?:\.\.?\/|\/)[a-zA-Z0-9\-_/.]+\.[\w]+/g];for(let J of $){let q=Array.from(Q.matchAll(J));for(let z of q){let G=z[0];if(G=G.replace(/[,。;:!?""''()【】《》]$/g,""),G=G.replace(/[,.;:!?"'()[\]<>]$/g,""),this.isValidFilePath(G))Z.push(G)}}return Z}static extractFilePathsFromToolCall(Q){let Z=[];if(Q.type!=="function"||!Q.function)return Z;try{let $=Q.function.name,J=JSON.parse(Q.function.arguments||"{}");if(["Read","Write","Edit","Glob","Grep","NotebookEdit","mcp__github__get_file_contents","mcp__github__create_or_update_file"].includes($)){let z=["file_path","path","notebook_path","filePath"];for(let G of z)if(J[G]&&typeof J[G]==="string")Z.push(J[G])}}catch{}return Z}static updateFileReference(Q,Z,$,J){let q=Q.get(Z);if(q)q.mentions++,q.lastMentioned=$,q.wasModified=q.wasModified||J;else Q.set(Z,{path:Z,mentions:1,lastMentioned:$,wasModified:J})}static isValidFilePath(Q){if(!Q.includes("/"))return!1;let Z=cQ(Q);if(!Z.includes("."))return!1;let $=["ts","tsx","js","jsx","json","md","py","java","go","rs","c","cpp","h","css","scss","html","xml","yaml","yml","toml","sh","bash","sql","graphql","vue","svelte"],J=Z.split(".").pop()?.toLowerCase();if(!J||!$.includes(J))return!1;return!0}}import{encodingForModel as t0}from"js-tiktoken";class Q0{static encodingCache=new Map;static countTokens(Q,Z){let $=this.getEncoding(Z),J=0;for(let q of Q){if(J+=4,q.role)J+=$.encode(q.role).length;if(q.content)if(typeof q.content==="string")J+=$.encode(q.content).length;else J+=$.encode(JSON.stringify(q.content)).length;if(q.tool_calls&&Array.isArray(q.tool_calls))J+=this.countToolCallTokens(q.tool_calls,$);if(q.name)J+=$.encode(q.name).length}return J}static getTokenLimit(Q){return Q}static shouldCompact(Q,Z,$,J=0.8){let q=this.countTokens(Q,Z),z=Math.floor($*J);return q>=z}static getEncoding(Q){if(!this.encodingCache.has(Q))try{let Z=t0(Q);this.encodingCache.set(Q,Z)}catch{try{let Z=t0("gpt-4");this.encodingCache.set(Q,Z)}catch{console.warn(`[TokenCounter] 无法为模型 ${Q} 获取 encoding,使用粗略估算`),this.encodingCache.set(Q,{encode:(Z)=>{return Array(Math.ceil(Z.length/4))}})}}return this.encodingCache.get(Q)}static countToolCallTokens(Q,Z){let $=0;for(let J of Q){if($+=4,J.type==="function"&&J.function?.name)$+=Z.encode(J.function.name).length;if(J.type==="function"&&J.function?.arguments)$+=Z.encode(J.function.arguments).length;if(J.id)$+=Z.encode(J.id).length}return $}static clearCache(){this.encodingCache.clear()}static estimateTokens(Q){let Z=(Q.match(/[\u4e00-\u9fa5]/g)||[]).length,$=Q.length-Z;return Math.ceil(Z/1.5+$/4)}}function g(Q){if(!(Q instanceof Error))return!1;if(Q.name==="AbortError")return!0;if(Q instanceof DOMException&&Q.name==="AbortError")return!0;if(Q.message.includes("aborted"))return!0;return!1}function e0(...Q){let Z=Q.filter(Boolean);if(Z.length===0)return new AbortController().signal;if(Z.length===1)return Z[0];let $=AbortSignal;if(typeof $.any==="function")return $.any(Z);for(let z of Z)if(z.aborted)return z;let J=new AbortController,q=new Map;for(let z of Z){let G=()=>{J.abort(z.reason);for(let[V,W]of q)V.removeEventListener("abort",W)};q.set(z,G)}for(let[z,G]of q)z.addEventListener("abort",G,{once:!0});return J.signal}var j0=new Map,iQ=3;class i{static THRESHOLD_PERCENT=0.8;static RETAIN_PERCENT=0.2;static FALLBACK_RETAIN_PERCENT=0.3;static async compact(Q,Z){if(Z.signal?.aborted)throw new DOMException("Aborted","AbortError");let $=Z.actualPreTokens??Q0.countTokens(Q,Z.modelName),J=Z.actualPreTokens?"actual (from LLM usage)":"estimated";console.log(`[CompactionService] preTokens source: ${J}`);try{let V=await K0.getInstance().executeCompactionHooks(Z.trigger,{projectDir:k(),sessionId:Z.sessionId||"unknown",permissionMode:Z.permissionMode||"default",messagesBefore:Q.length,tokensBefore:$});if(V.blockCompaction)return console.log(`[CompactionService] Compaction hook 阻止压缩: ${V.blockReason||"(无原因)"}`),{success:!1,summary:"",preTokens:$,postTokens:$,filesIncluded:[],compactedMessages:Q,boundaryMessage:{role:"system",content:""},summaryMessage:{role:"user",content:""},error:V.blockReason||"Compaction blocked by hook"};if(V.warning)console.warn(`[CompactionService] Compaction hook warning: ${V.warning}`)}catch(G){console.warn("[CompactionService] Compaction hook execution failed:",G)}let q=Z.sessionId??"_default",z=j0.get(q)??0;if(z>=iQ)return console.warn(`[CompactionService] Circuit breaker open (${z} consecutive failures for session ${q}), using fallback`),this.fallbackCompact(Q,Z,$,Error("Circuit breaker open"));try{console.log("[CompactionService] 开始压缩,消息数:",Q.length),console.log("[CompactionService] 压缩前 tokens:",$);let V=B0.analyzeFiles(Q).map((S)=>S.path);console.log("[CompactionService] 提取重点文件:",V);let W=await B0.readFilesContent(V);console.log("[CompactionService] 成功读取文件:",W.length);let B=await this.generateSummary(Q,W,Z);console.log("[CompactionService] 生成总结,长度:",B.length);let F=Math.ceil(Q.length*this.RETAIN_PERCENT),O=Q.slice(-F),Y=new Set;for(let S of O)if(S.role==="assistant"&&S.tool_calls)for(let q0 of S.tool_calls)Y.add(q0.id);let L=O.filter((S)=>{if(S.role==="tool"&&S.tool_call_id)return Y.has(S.tool_call_id);return!0});console.log("[CompactionService] 保留消息数:",F),console.log("[CompactionService] 过滤后保留消息数:",L.length);let E=c(),j=this.createBoundaryMessage(E,Z.trigger,$),K=c(),P=this.createSummaryMessage(K,B),R=[P,...L],h=await this.buildFileRestorationMessage();if(h)R.push(h);let f=Q0.countTokens(R,Z.modelName);return console.log("[CompactionService] 压缩完成!"),console.log("[CompactionService] Token 变化:",$,"->",f,`(-${((1-f/$)*100).toFixed(1)}%)`),j0.delete(q),{success:!0,summary:B,preTokens:$,postTokens:f,filesIncluded:V,compactedMessages:R,boundaryMessage:j,summaryMessage:P}}catch(G){if(g(G))throw G;return j0.set(q,(j0.get(q)??0)+1),console.error("[CompactionService] 压缩失败,使用降级策略",G),this.fallbackCompact(Q,Z,$,G)}}static async generateSummary(Q,Z,$){let J=this.buildCompactionPrompt(Q,Z);if(console.log("[CompactionService] 使用压缩模型:",$.modelName),$.signal?.aborted)throw new DOMException("Aborted","AbortError");let G=(await(await QQ({apiKey:$.apiKey||process.env.BLADE_API_KEY||"",baseUrl:$.baseURL||process.env.BLADE_BASE_URL||"https://api.openai.com/v1",model:$.modelName,temperature:0.3,maxOutputTokens:8000,timeout:60000,provider:"openai-compatible"})).chat([{role:"user",content:J}],[],$.signal)).content||"",V=G.match(/<summary>([\s\S]*?)<\/summary>/);if(!V)return console.warn("[CompactionService] 总结格式不正确,使用完整响应"),G;return V[1].trim()}static buildCompactionPrompt(Q,Z){let $=Q.map((z,G)=>{let V=z.role||"unknown",W=typeof z.content==="string"?z.content:JSON.stringify(z.content),B=5000,F=W.length>5000?W.substring(0,5000)+"...":W;return`[${G+1}] ${V}: ${F}`}).join(`
10
10
 
11
11
  `),J=Z.map((z)=>{return`### ${z.path}
12
12
  \`\`\`
@@ -79,32 +79,32 @@ ${Z.length>0?`## Important Files
79
79
 
80
80
  ${J}`:""}
81
81
 
82
- Please provide your summary following the structure specified above, with both <analysis> and <summary> sections.`}static createBoundaryMessage(Q,Z,$){return{id:u(),role:"system",content:"Conversation compacted",metadata:{type:"system",subtype:"compact_boundary",parentId:Q,compactMetadata:{trigger:Z,preTokens:$}}}}static createSummaryMessage(Q,Z){return{id:u(),role:"user",content:Z,metadata:{parentId:Q,isCompactSummary:!0}}}static getRecentlyAccessedFiles(Q){let Z=p.getInstance();return Z.getTrackedFiles().map((q)=>({filePath:q,record:Z.getFileRecord(q)})).filter((q)=>q.record!==void 0).sort((q,z)=>z.record.accessTime-q.record.accessTime).slice(0,Q).map((q)=>q.filePath)}static async buildFileRestorationMessage(){let Q=this.getRecentlyAccessedFiles(5);if(Q.length===0)return null;let Z=[];for(let J of Q)try{let z=(await gQ.readFile(J,"utf-8")).split(`
82
+ Please provide your summary following the structure specified above, with both <analysis> and <summary> sections.`}static createBoundaryMessage(Q,Z,$){return{id:c(),role:"system",content:"Conversation compacted",metadata:{type:"system",subtype:"compact_boundary",parentId:Q,compactMetadata:{trigger:Z,preTokens:$}}}}static createSummaryMessage(Q,Z){return{id:c(),role:"user",content:Z,metadata:{parentId:Q,isCompactSummary:!0}}}static getRecentlyAccessedFiles(Q){let Z=p.getInstance();return Z.getTrackedFiles().map((q)=>({filePath:q,record:Z.getFileRecord(q)})).filter((q)=>q.record!==void 0).sort((q,z)=>z.record.accessTime-q.record.accessTime).slice(0,Q).map((q)=>q.filePath)}static async buildFileRestorationMessage(){let Q=this.getRecentlyAccessedFiles(5);if(Q.length===0)return null;let Z=[];for(let J of Q)try{let z=(await uQ.readFile(J,"utf-8")).split(`
83
83
  `),G=z.slice(0,200).join(`
84
84
  `),V=z.length>200?`
85
85
  ... (${z.length-200} more lines)`:"";Z.push(`<file path="${J}" lines="${z.length}">
86
86
  ${G}${V}
87
87
  </file>`)}catch{}if(Z.length===0)return null;let $=["<system-reminder>","Post-compaction file restoration. These files were recently accessed in the conversation:",...Z,"</system-reminder>"].join(`
88
- `);return console.log("[CompactionService] Post-compact 恢复文件:",Q.length),{id:u(),role:"user",content:$,metadata:{isPostCompactRestoration:!0}}}static fallbackCompact(Q,Z,$,J){let q=Math.ceil(Q.length*this.FALLBACK_RETAIN_PERCENT),z=Q.slice(-q),G=new Set;for(let B of z)if(B.role==="assistant"&&B.tool_calls)for(let j of B.tool_calls)G.add(j.id);let V=z.filter((B)=>{if(B.role==="tool"&&B.tool_call_id)return G.has(B.tool_call_id);return!0}),W=u(),H=this.createBoundaryMessage(W,Z.trigger,$),F=J instanceof Error?J.message:String(J),L=u(),Y=this.createSummaryMessage(L,`[Automatic compaction failed; using fallback]
88
+ `);return console.log("[CompactionService] Post-compact 恢复文件:",Q.length),{id:c(),role:"user",content:$,metadata:{isPostCompactRestoration:!0}}}static fallbackCompact(Q,Z,$,J){let q=Math.ceil(Q.length*this.FALLBACK_RETAIN_PERCENT),z=Q.slice(-q),G=new Set;for(let j of z)if(j.role==="assistant"&&j.tool_calls)for(let K of j.tool_calls)G.add(K.id);let V=z.filter((j)=>{if(j.role==="tool"&&j.tool_call_id)return G.has(j.tool_call_id);return!0}),W=c(),B=this.createBoundaryMessage(W,Z.trigger,$),F=J instanceof Error?J.message:String(J),O=c(),Y=this.createSummaryMessage(O,`[Automatic compaction failed; using fallback]
89
89
 
90
90
  An error occurred during compaction. Retained the latest ${q} messages (~30%).
91
91
 
92
92
  Error: ${F}
93
93
 
94
- The conversation can continue, but consider retrying compaction later with /compact.`),O=[Y,...V],_=Q0.countTokens(O,Z.modelName);return{success:!1,summary:typeof Y.content==="string"?Y.content:Y.content.filter((B)=>B.type==="text").map((B)=>B.text).join(`
95
- `),preTokens:$,postTokens:_,filesIncluded:[],compactedMessages:O,boundaryMessage:H,summaryMessage:Y,error:F}}}var uQ=new Set(["Read","Grep","Glob","Search","WebSearch","WebFetch","ToolSearch"]);function iQ(Q,Z){let q=(Q[Z.assistantIdx].tool_calls??[]).filter((G)=>G.type==="function").map((G)=>G.function.name).some((G)=>!uQ.has(G));if(Z.toolResultIdxs.some((G)=>{let V=Q[G]?.content;if(typeof V!=="string")return!1;return V.startsWith("Error:")||V.includes("failed")||V.includes("ENOENT")}))return 3;if(q)return 2;return 1}function B0(Q,Z){let $=Z?.keepRecentTurns??10,J=Z?.minMessagesForSnip??30;if(Q.length<J)return{messages:Q,snippedCount:0,estimatedTokensFreed:0};let q=[];for(let Y=0;Y<Q.length;Y++){let O=Q[Y];if(O.role==="assistant"&&O.tool_calls&&O.tool_calls.length>0){let _=new Set(O.tool_calls.map((j)=>j.id)),B=[];for(let j=Y+1;j<Q.length;j++){let P=Q[j];if(P.role==="tool"&&P.tool_call_id&&_.has(P.tool_call_id))B.push(j);if(P.role==="assistant"||P.role==="user")break}q.push({assistantIdx:Y,toolResultIdxs:B,priority:0})}}for(let Y of q)Y.priority=iQ(Q,Y);let V=[...q.slice(0,Math.max(0,q.length-$))].sort((Y,O)=>Y.priority-O.priority);if(V.length===0)return{messages:Q,snippedCount:0,estimatedTokensFreed:0};let W=new Set,H=0;for(let Y of V){W.add(Y.assistantIdx);for(let O of Y.toolResultIdxs)W.add(O)}for(let Y of W){let O=Q[Y],_=typeof O.content==="string"?O.content:JSON.stringify(O.content);if(H+=_.length,O.tool_calls)H+=JSON.stringify(O.tool_calls).length}let F=[],L=!1;for(let Y=0;Y<Q.length;Y++){if(W.has(Y)){if(!L)F.push({role:"system",content:`[${V.length} earlier tool interaction${V.length===1?"":"s"} snipped for brevity]`}),L=!0;continue}F.push(Q[Y])}return{messages:F,snippedCount:V.length,estimatedTokensFreed:Math.floor(H/4)}}class f0{hasAttempted=!1;async tryReactiveCompact(Q,Z){if(this.hasAttempted)return{success:!1,messages:Q};this.hasAttempted=!0;let $=B0(Q,{keepRecentTurns:3,minMessagesForSnip:10}),J=$.messages;try{let q=await n.compact(J,{trigger:"auto",modelName:Z.modelName,maxContextTokens:Z.maxContextTokens,apiKey:Z.apiKey,baseURL:Z.baseURL,signal:Z.signal});if(q.success)return{success:!0,messages:q.compactedMessages};if($.snippedCount>0)return{success:!0,messages:J};return{success:!1,messages:Q}}catch(q){if(c(q))throw q;if($.snippedCount>0)return{success:!0,messages:J};return{success:!1,messages:Q}}}reset(){this.hasAttempted=!1}}import*as l from"fs";import*as R0 from"os";import*as Z0 from"path";import{nanoid as $Q}from"nanoid";var nQ=1e5,lQ=2000,QQ=200000;class T0{currentChars=0;track(Q){this.currentChars+=Q}remaining(){return Math.max(0,QQ-this.currentChars)}isExhausted(){return this.currentChars>=QQ}reset(){this.currentChars=0}}function JQ(Q,Z,$){let J=$?.maxCharsPerResult??nQ,q=$?.previewChars??lQ,z=$?.messageBudget,G=typeof Q==="string"?Q:JSON.stringify(Q,null,2);if(G.length<=J)return aQ(Q,G,Z,q,z,$);let V=$?.outputDir??Z0.join(R0.homedir(),".blade","tool-results"),W=`${Z}-${$Q(8)}.txt`,H=Z0.join(V,W);try{l.mkdirSync(V,{recursive:!0}),l.writeFileSync(H,G,"utf-8")}catch{let Y=G.slice(0,J)+`
94
+ The conversation can continue, but consider retrying compaction later with /compact.`),L=[Y,...V],E=Q0.countTokens(L,Z.modelName);return{success:!1,summary:typeof Y.content==="string"?Y.content:Y.content.filter((j)=>j.type==="text").map((j)=>j.text).join(`
95
+ `),preTokens:$,postTokens:E,filesIncluded:[],compactedMessages:L,boundaryMessage:B,summaryMessage:Y,error:F}}}var nQ=new Set(["Read","Grep","Glob","Search","WebSearch","WebFetch","ToolSearch"]);function lQ(Q,Z){let q=(Q[Z.assistantIdx].tool_calls??[]).filter((G)=>G.type==="function").map((G)=>G.function.name).some((G)=>!nQ.has(G));if(Z.toolResultIdxs.some((G)=>{let V=Q[G]?.content;if(typeof V!=="string")return!1;return V.startsWith("Error:")||V.includes("failed")||V.includes("ENOENT")}))return 3;if(q)return 2;return 1}function Z0(Q,Z){let $=Z?.keepRecentTurns??10,J=Z?.minMessagesForSnip??30;if(Q.length<J)return{messages:Q,snippedCount:0,estimatedTokensFreed:0};let q=[];for(let Y=0;Y<Q.length;Y++){let L=Q[Y];if(L.role==="assistant"&&L.tool_calls&&L.tool_calls.length>0){let E=new Set(L.tool_calls.map((K)=>K.id)),j=[];for(let K=Y+1;K<Q.length;K++){let P=Q[K];if(P.role==="tool"&&P.tool_call_id&&E.has(P.tool_call_id))j.push(K);if(P.role==="assistant"||P.role==="user")break}q.push({assistantIdx:Y,toolResultIdxs:j,priority:0})}}for(let Y of q)Y.priority=lQ(Q,Y);let V=[...q.slice(0,Math.max(0,q.length-$))].sort((Y,L)=>Y.priority-L.priority);if(V.length===0)return{messages:Q,snippedCount:0,estimatedTokensFreed:0};let W=new Set,B=0;for(let Y of V){W.add(Y.assistantIdx);for(let L of Y.toolResultIdxs)W.add(L)}for(let Y of W){let L=Q[Y],E=typeof L.content==="string"?L.content:JSON.stringify(L.content);if(B+=E.length,L.tool_calls)B+=JSON.stringify(L.tool_calls).length}let F=[],O=!1;for(let Y=0;Y<Q.length;Y++){if(W.has(Y)){if(!O)F.push({role:"system",content:`[${V.length} earlier tool interaction${V.length===1?"":"s"} snipped for brevity]`}),O=!0;continue}F.push(Q[Y])}return{messages:F,snippedCount:V.length,estimatedTokensFreed:Math.floor(B/4)}}var aQ=60000,rQ=3;function ZQ(Q,Z){if(!Z)return null;if(Date.now()-Z<aQ)return null;let J=Z0(Q,{keepRecentTurns:rQ,minMessagesForSnip:15});if(J.snippedCount===0)return null;return J}class R0{hasAttempted=!1;async tryReactiveCompact(Q,Z){if(this.hasAttempted)return{success:!1,messages:Q};this.hasAttempted=!0;let $=Z0(Q,{keepRecentTurns:3,minMessagesForSnip:10}),J=$.messages;try{let q=await i.compact(J,{trigger:"auto",modelName:Z.modelName,maxContextTokens:Z.maxContextTokens,apiKey:Z.apiKey,baseURL:Z.baseURL,signal:Z.signal});if(q.success)return{success:!0,messages:q.compactedMessages};if($.snippedCount>0)return{success:!0,messages:J};return{success:!1,messages:Q}}catch(q){if(g(q))throw q;if($.snippedCount>0)return{success:!0,messages:J};return{success:!1,messages:Q}}}reset(){this.hasAttempted=!1}}import*as n from"fs";import*as T0 from"os";import*as $0 from"path";import{nanoid as qQ}from"nanoid";var oQ=1e5,sQ=2000,$Q=200000;class x0{currentChars=0;track(Q){this.currentChars+=Q}remaining(){return Math.max(0,$Q-this.currentChars)}isExhausted(){return this.currentChars>=$Q}reset(){this.currentChars=0}}function zQ(Q,Z,$){let J=$?.maxCharsPerResult??oQ,q=$?.previewChars??sQ,z=$?.messageBudget,G=typeof Q==="string"?Q:JSON.stringify(Q,null,2);if(G.length<=J)return tQ(Q,G,Z,q,z,$);let V=$?.outputDir??$0.join(T0.homedir(),".blade","tool-results"),W=`${Z}-${qQ(8)}.txt`,B=$0.join(V,W);try{n.mkdirSync(V,{recursive:!0}),n.writeFileSync(B,G,"utf-8")}catch{let Y=G.slice(0,J)+`
96
96
 
97
- ... (truncated, ${G.length} total chars)`;if(z)z.track(Y.length);return Y}let F=G.slice(0,q),L=`Result too large (${G.length} chars). Full output saved to: ${H}
97
+ ... (truncated, ${G.length} total chars)`;if(z)z.track(Y.length);return Y}let F=G.slice(0,q),O=`Result too large (${G.length} chars). Full output saved to: ${B}
98
98
 
99
99
  Preview:
100
100
  ${F}
101
101
 
102
- ... (${G.length-q} more chars in file)`;if(z)z.track(L.length);return L}function aQ(Q,Z,$,J,q,z){if(!q)return Q;let G=q.remaining();if(G<=0){let V=Z.slice(0,J),W=ZQ(Z,V,$,z,"[Message budget exhausted. Full output saved to disk.]");return q.track(typeof W==="string"?W.length:J),W}if(Z.length>G){let V=Math.max(J,G),W=Z.slice(0,V),H=ZQ(Z,W,$,z,`... (truncated by message budget, ${Z.length} total chars)`);return q.track(typeof H==="string"?H.length:V),H}return q.track(Z.length),Q}function ZQ(Q,Z,$,J,q){let z=J?.outputDir??Z0.join(R0.homedir(),".blade","tool-results"),G=`${$}-${$Q(8)}.txt`,V=Z0.join(z,G);try{return l.mkdirSync(z,{recursive:!0}),l.writeFileSync(V,Q,"utf-8"),`${Z}
102
+ ... (${G.length-q} more chars in file)`;if(z)z.track(O.length);return O}function tQ(Q,Z,$,J,q,z){if(!q)return Q;let G=q.remaining();if(G<=0){let V=Z.slice(0,J),W=JQ(Z,V,$,z,"[Message budget exhausted. Full output saved to disk.]");return q.track(typeof W==="string"?W.length:J),W}if(Z.length>G){let V=Math.max(J,G),W=Z.slice(0,V),B=JQ(Z,W,$,z,`... (truncated by message budget, ${Z.length} total chars)`);return q.track(typeof B==="string"?B.length:V),B}return q.track(Z.length),Q}function JQ(Q,Z,$,J,q){let z=J?.outputDir??$0.join(T0.homedir(),".blade","tool-results"),G=`${$}-${qQ(8)}.txt`,V=$0.join(z,G);try{return n.mkdirSync(z,{recursive:!0}),n.writeFileSync(V,Q,"utf-8"),`${Z}
103
103
 
104
104
  ${q}
105
105
  Full output saved to: ${V}`}catch{return`${Z}
106
106
 
107
- ${q}`}}import*as L0 from"node:fs/promises";import{homedir as jQ}from"node:os";import*as x from"node:path";var j0={name:"skill-creator",description:"Create new Skills interactively. Use when the user wants to create a new Skill, define a custom workflow, or add a specialized capability to Blade.",allowedTools:["Read","Write","Glob","Bash","AskUserQuestion"],version:"1.0.0",argumentHint:void 0,userInvocable:!0,disableModelInvocation:!1,model:void 0,whenToUse:"User wants to create a new skill, define a custom workflow, or add a specialized capability.",path:"builtin://skill-creator",basePath:"",source:"builtin"};function qQ(){return{metadata:j0,instructions:`# Skill Creator
107
+ ${q}`}}import*as b0 from"node:fs/promises";import{homedir as wQ}from"node:os";import*as x from"node:path";var D0={name:"skill-creator",description:"Create new Skills interactively. Use when the user wants to create a new Skill, define a custom workflow, or add a specialized capability to Blade.",allowedTools:["Read","Write","Glob","Bash","AskUserQuestion"],version:"1.0.0",argumentHint:void 0,userInvocable:!0,disableModelInvocation:!1,model:void 0,whenToUse:"User wants to create a new skill, define a custom workflow, or add a specialized capability.",path:"builtin://skill-creator",basePath:"",source:"builtin"};function GQ(){return{metadata:D0,instructions:`# Skill Creator
108
108
 
109
109
  帮助用户创建新的 Blade Skills。
110
110
 
@@ -287,7 +287,7 @@ user-invocable: true
287
287
  <footer>
288
288
  \`\`\`
289
289
  \`\`\`
290
- `}}var D0={name:"update-config",description:"配置 Blade harness(settings/hooks/permissions)。"+"用户请求自动化行为时使用此 Skill。",allowedTools:["ConfigTool","Read","Bash","AskUserQuestion"],version:"1.0.0",userInvocable:!0,disableModelInvocation:!1,whenToUse:'用户说"从现在起..."、"每次..."、"当...时..."、'+"需要改配置、安装 hooks、修改权限",path:"builtin://update-config",basePath:"",source:"builtin"};function zQ(){return{metadata:D0,instructions:`# Update Config Skill
290
+ `}}var w0={name:"update-config",description:"配置 Blade harness(settings/hooks/permissions)。"+"用户请求自动化行为时使用此 Skill。",allowedTools:["ConfigTool","Read","Bash","AskUserQuestion"],version:"1.0.0",userInvocable:!0,disableModelInvocation:!1,whenToUse:'用户说"从现在起..."、"每次..."、"当...时..."、'+"需要改配置、安装 hooks、修改权限",path:"builtin://update-config",basePath:"",source:"builtin"};function VQ(){return{metadata:w0,instructions:`# Update Config Skill
291
291
 
292
292
  配置 Blade 运行环境。管理 settings、hooks、permissions、环境变量等。
293
293
 
@@ -560,11 +560,11 @@ ConfigTool({
560
560
  2. **permissions 字段使用 replace 策略**:设置 permissions 会完全替换现有值。如果只想添加规则,先 GET 当前值,合并后再 SET
561
561
  3. **env 字段使用 deep-merge 策略**:可以逐个添加环境变量
562
562
  4. **scope 默认值**:不指定 scope 时,根据字段路由表决定(hooks/permissions/env 默认 local,temperature/theme 等默认 global)
563
- `}}import{exec as rQ}from"node:child_process";import*as D from"node:fs/promises";import{homedir as oQ}from"node:os";import*as v from"node:path";import{promisify as sQ}from"node:util";var w0=sQ(rQ),U=M("General"),x0={url:"https://github.com/anthropics/skills.git",branch:"main",defaultSkills:["skill-creator"]};class GQ{skillsDir;constructor(Q){this.skillsDir=Q||v.join(oQ(),".blade","skills")}async isInstalled(Q){let Z=v.join(this.skillsDir,Q,"SKILL.md");try{return await D.access(Z),!0}catch{return!1}}async isGitAvailable(){try{return await w0("git --version"),!0}catch{return!1}}async installOfficialSkill(Q){let{url:Z,branch:$}=x0,J=v.join(this.skillsDir,Q),q=v.join(this.skillsDir,`.tmp-${Q}-${Date.now()}`);try{if(!await this.isGitAvailable())return U.warn("Git not available, skipping skill installation"),!1;U.info(`Installing official skill: ${Q}...`),await D.mkdir(this.skillsDir,{recursive:!0,mode:493}),await w0(`git clone --depth 1 --branch ${$} --single-branch ${Z} "${q}"`,{timeout:30000});let z=v.join(q,"skills",Q);try{await D.access(z)}catch{return U.warn(`Skill ${Q} not found in official repository`),await D.rm(q,{recursive:!0,force:!0}),!1}try{await D.rm(J,{recursive:!0,force:!0})}catch{}return await D.cp(z,J,{recursive:!0}),await D.rm(q,{recursive:!0,force:!0}),U.info(`Successfully installed: ${Q}`),!0}catch(z){try{await D.rm(q,{recursive:!0,force:!0})}catch{}return U.warn(`Failed to install ${Q}: ${z instanceof Error?z.message:"Unknown error"}`),!1}}async ensureDefaultSkillsInstalled(){await D.mkdir(this.skillsDir,{recursive:!0,mode:493});for(let Q of x0.defaultSkills)if(!await this.isInstalled(Q))await this.installOfficialSkill(Q)}async installFromRepo(Q,Z){let $=Z||this.extractRepoName(Q),J=v.join(this.skillsDir,$),q=v.join(this.skillsDir,`.tmp-repo-${$}-${Date.now()}`);try{if(!await this.isGitAvailable())return U.warn("Git not available, cannot install from repo"),!1;U.info(`Installing skill from repo: ${Q}...`),await D.mkdir(this.skillsDir,{recursive:!0,mode:493}),await w0(`git clone --depth 1 "${Q}" "${q}"`,{timeout:60000});let z=v.join(q,"SKILL.md");try{await D.access(z)}catch{return U.warn(`No SKILL.md found in repository ${Q}`),await D.rm(q,{recursive:!0,force:!0}),!1}await D.rm(J,{recursive:!0,force:!0}),await D.rename(q,J);try{await D.rm(v.join(J,".git"),{recursive:!0,force:!0})}catch{}return U.info(`Successfully installed skill from repo: ${$}`),!0}catch(z){try{await D.rm(q,{recursive:!0,force:!0})}catch{}return U.warn(`Failed to install from repo ${Q}: ${z instanceof Error?z.message:"Unknown error"}`),!1}}async installFromLocal(Q,Z,$=!0){let J=Z||v.basename(Q),q=v.join(this.skillsDir,J);try{let z=v.resolve(Q);try{await D.access(z)}catch{return U.warn(`Local path does not exist: ${z}`),!1}let G=v.join(z,"SKILL.md");try{await D.access(G)}catch{return U.warn(`No SKILL.md found in local path: ${z}`),!1}if(U.info(`Installing skill from local path: ${z}...`),await D.mkdir(this.skillsDir,{recursive:!0,mode:493}),await D.rm(q,{recursive:!0,force:!0}),$)await D.symlink(z,q,"dir"),U.info(`Created symlink for skill: ${J}`);else await D.cp(z,q,{recursive:!0}),U.info(`Copied skill to: ${J}`);return!0}catch(z){return U.warn(`Failed to install from local path ${Q}: ${z instanceof Error?z.message:"Unknown error"}`),!1}}extractRepoName(Q){return Q.match(/\/([^/]+?)(\.git)?$/)?.[1]||"unknown-skill"}async installAllOfficialSkills(){let{url:Q,branch:Z}=x0,$=v.join(this.skillsDir,`.tmp-all-${Date.now()}`),J=[],q=[];try{if(!await this.isGitAvailable())return U.warn("Git not available, skipping skill installation"),{installed:J,failed:q};await D.mkdir(this.skillsDir,{recursive:!0,mode:493}),U.info("Cloning official skills repository..."),await w0(`git clone --depth 1 --branch ${Z} --single-branch ${Q} "${$}"`,{timeout:60000});let z=v.join($,"skills"),G=await D.readdir(z,{withFileTypes:!0});for(let V of G){if(!V.isDirectory())continue;let W=V.name,H=v.join(z,W),F=v.join(this.skillsDir,W);try{await D.access(v.join(H,"SKILL.md")),await D.rm(F,{recursive:!0,force:!0}),await D.cp(H,F,{recursive:!0}),U.info(`Installed: ${W}`),J.push(W)}catch(L){U.warn(`Failed to install ${W}`),q.push(W)}}await D.rm($,{recursive:!0,force:!0})}catch(z){try{await D.rm($,{recursive:!0,force:!0})}catch{}U.warn(`Failed to install skills: ${z instanceof Error?z.message:"Unknown error"}`)}return{installed:J,failed:q}}}var h0=null;function VQ(Q){if(!h0)h0=new GQ(Q);return h0}import*as $0 from"node:fs/promises";import*as F0 from"node:path";import{parse as tQ}from"yaml";var eQ=/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/,QZ=/^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]?$/,WQ=1024;function ZZ(Q){if(!Q)return;if(typeof Q==="string")return Q.split(",").map((Z)=>Z.trim()).filter(Boolean);if(Array.isArray(Q))return Q.map((Z)=>String(Z).trim()).filter(Boolean);return}function YQ(Q){if(Q===void 0)return;if(typeof Q==="boolean")return Q;if(typeof Q==="string"){let Z=Q.toLowerCase().trim();if(Z==="true"||Z==="yes"||Z==="1")return!0;if(Z==="false"||Z==="no"||Z==="0")return!1}return}function $Z(Q,Z){if(!Q.name)return{valid:!1,error:"Missing required field: name"};if(!QZ.test(Q.name))return{valid:!1,error:`Invalid name "${Q.name}": must be lowercase letters, numbers, and hyphens only, 1-64 characters`};if(!Q.description)return{valid:!1,error:"Missing required field: description"};if(Q.description.length>WQ)return{valid:!1,error:`Description too long: ${Q.description.length} characters (max ${WQ})`};let $;if(Q.model)$=Q.model==="inherit"?"inherit":Q.model;return{valid:!0,metadata:{name:Q.name,description:Q.description.trim(),allowedTools:ZZ(Q["allowed-tools"]),version:Q.version,argumentHint:Q["argument-hint"]?.trim(),userInvocable:YQ(Q["user-invocable"]),disableModelInvocation:YQ(Q["disable-model-invocation"]),model:$,whenToUse:Q.when_to_use?.trim()}}}function KQ(Q,Z,$){let J=Q.match(eQ);if(!J)return{success:!1,error:"Invalid SKILL.md format: missing YAML frontmatter (must start with ---)"};let[,q,z]=J,G;try{G=tQ(q)}catch(H){return{success:!1,error:`Failed to parse YAML frontmatter: ${H instanceof Error?H.message:String(H)}`}}let V=$Z(G,Z);if(!V.valid)return{success:!1,error:V.error};let W=F0.dirname(Z);return{success:!0,content:{metadata:{...V.metadata,path:Z,basePath:W,source:$},instructions:z.trim()}}}async function XQ(Q,Z){try{let $=await $0.readFile(Q,"utf-8");return KQ($,Q,Z)}catch($){if($.code==="ENOENT")return{success:!1,error:`File not found: ${Q}`};return{success:!1,error:`Failed to read file: ${$ instanceof Error?$.message:String($)}`}}}async function HQ(Q){try{let Z=await $0.readFile(Q.path,"utf-8"),$=KQ(Z,Q.path,Q.source);return $.success?$.content:null}catch{return null}}async function BQ(Q){try{return await $0.access(F0.join(Q,"SKILL.md")),!0}catch{return!1}}var JZ={userSkillsDir:x.join(jQ(),".blade","skills"),projectSkillsDir:".blade/skills",claudeUserSkillsDir:x.join(jQ(),".claude","skills"),claudeProjectSkillsDir:".claude/skills"},O0=null;class k0{skills=new Map;pluginSkills=new Map;config;initialized=!1;constructor(Q){this.config={...JZ,cwd:k(),...Q}}static getInstance(Q){if(!O0)O0=new k0(Q);return O0}static resetInstance(){O0=null}async initialize(){if(this.initialized)return{skills:Array.from(this.skills.values()),errors:[]};let Q=[],Z=[];try{await VQ(this.config.userSkillsDir).ensureDefaultSkillsInstalled()}catch(W){Q.push({path:"SkillInstaller",error:`Failed to install default skills: ${W instanceof Error?W.message:"Unknown error"}`})}this.loadBuiltinSkills();let $=await this.scanDirectory(this.config.claudeUserSkillsDir,"user");Z.push(...$.skills),Q.push(...$.errors);let J=await this.scanDirectory(this.config.userSkillsDir,"user");Z.push(...J.skills),Q.push(...J.errors);let q=x.isAbsolute(this.config.claudeProjectSkillsDir)?this.config.claudeProjectSkillsDir:x.join(this.config.cwd,this.config.claudeProjectSkillsDir),z=await this.scanDirectory(q,"project");Z.push(...z.skills),Q.push(...z.errors);let G=x.isAbsolute(this.config.projectSkillsDir)?this.config.projectSkillsDir:x.join(this.config.cwd,this.config.projectSkillsDir),V=await this.scanDirectory(G,"project");Z.push(...V.skills),Q.push(...V.errors);for(let W of Z)this.skills.set(W.name,W);return this.initialized=!0,{skills:Array.from(this.skills.values()),errors:Q}}loadBuiltinSkills(){this.skills.set(j0.name,j0),this.skills.set(D0.name,D0)}async scanDirectory(Q,Z){let $=[],J=[];try{await L0.access(Q)}catch{return{skills:$,errors:J}}try{let q=await L0.readdir(Q,{withFileTypes:!0});for(let z of q){if(!z.isDirectory())continue;let G=x.join(Q,z.name),V=x.join(G,"SKILL.md");if(!await BQ(G))continue;let W=await XQ(V,Z);if(W.success&&W.content)$.push(W.content.metadata);else J.push({path:V,error:W.error||"Unknown error"})}}catch(q){J.push({path:Q,error:`Failed to scan directory: ${q instanceof Error?q.message:String(q)}`})}return{skills:$,errors:J}}getAll(){return Array.from(this.skills.values())}get(Q){return this.skills.get(Q)}has(Q){return this.skills.has(Q)}async loadContent(Q){let Z=this.skills.get(Q);if(!Z)return null;if(Z.source==="builtin")return this.loadBuiltinContent(Q);return HQ(Z)}loadBuiltinContent(Q){switch(Q){case"skill-creator":return qQ();case"update-config":return zQ();default:return null}}getModelInvocableSkills(){return Array.from(this.skills.values()).filter((Q)=>!Q.disableModelInvocation)}getUserInvocableSkills(){return Array.from(this.skills.values()).filter((Q)=>Q.userInvocable===!0)}generateAvailableSkillsList(){let Q=this.getModelInvocableSkills();if(Q.length===0)return"";let Z=[];for(let $ of Q){let J=$.description.length>100?`${$.description.substring(0,97)}...`:$.description,q=$.argumentHint?`${$.name} ${$.argumentHint}`:$.name;Z.push(`- ${q}: ${J}`)}return Z.join(`
564
- `)}get size(){return this.skills.size}async refresh(){return this.skills.clear(),this.pluginSkills.clear(),this.initialized=!1,this.initialize()}registerPluginSkill(Q){this.pluginSkills.set(Q.namespacedName,Q),this.skills.set(Q.namespacedName,Q.metadata)}findPluginSkill(Q){let Z=this.pluginSkills.get(Q);if(Z)return Z;let $=[];for(let J of this.pluginSkills.values())if(J.originalName===Q)$.push(J);if($.length===1)return $[0];return}getAllPluginSkills(){return Array.from(this.pluginSkills.values())}clearPluginSkills(){for(let Q of this.pluginSkills.values())this.skills.delete(Q.namespacedName);this.pluginSkills.clear()}getPluginSkillCount(){return this.pluginSkills.size}}function b0(Q){return k0.getInstance(Q)}async function qZ(Q){return b0(Q).initialize()}var zZ="Skill",GZ=/<available_skills>\s*<\/available_skills>/;function C0(Q){let $=b0().generateAvailableSkillsList();if(!$)return Q;return Q.map((J)=>{if(J.name!==zZ)return J;let q=J.description.replace(GZ,`<available_skills>
563
+ `}}import{exec as eQ}from"node:child_process";import*as D from"node:fs/promises";import{homedir as QZ}from"node:os";import*as v from"node:path";import{promisify as ZZ}from"node:util";var F0=ZZ(eQ),I=M("General"),h0={url:"https://github.com/anthropics/skills.git",branch:"main",defaultSkills:["skill-creator"]};class WQ{skillsDir;constructor(Q){this.skillsDir=Q||v.join(QZ(),".blade","skills")}async isInstalled(Q){let Z=v.join(this.skillsDir,Q,"SKILL.md");try{return await D.access(Z),!0}catch{return!1}}async isGitAvailable(){try{return await F0("git --version"),!0}catch{return!1}}async installOfficialSkill(Q){let{url:Z,branch:$}=h0,J=v.join(this.skillsDir,Q),q=v.join(this.skillsDir,`.tmp-${Q}-${Date.now()}`);try{if(!await this.isGitAvailable())return I.warn("Git not available, skipping skill installation"),!1;I.info(`Installing official skill: ${Q}...`),await D.mkdir(this.skillsDir,{recursive:!0,mode:493}),await F0(`git clone --depth 1 --branch ${$} --single-branch ${Z} "${q}"`,{timeout:30000});let z=v.join(q,"skills",Q);try{await D.access(z)}catch{return I.warn(`Skill ${Q} not found in official repository`),await D.rm(q,{recursive:!0,force:!0}),!1}try{await D.rm(J,{recursive:!0,force:!0})}catch{}return await D.cp(z,J,{recursive:!0}),await D.rm(q,{recursive:!0,force:!0}),I.info(`Successfully installed: ${Q}`),!0}catch(z){try{await D.rm(q,{recursive:!0,force:!0})}catch{}return I.warn(`Failed to install ${Q}: ${z instanceof Error?z.message:"Unknown error"}`),!1}}async ensureDefaultSkillsInstalled(){await D.mkdir(this.skillsDir,{recursive:!0,mode:493});for(let Q of h0.defaultSkills)if(!await this.isInstalled(Q))await this.installOfficialSkill(Q)}async installFromRepo(Q,Z){let $=Z||this.extractRepoName(Q),J=v.join(this.skillsDir,$),q=v.join(this.skillsDir,`.tmp-repo-${$}-${Date.now()}`);try{if(!await this.isGitAvailable())return I.warn("Git not available, cannot install from repo"),!1;I.info(`Installing skill from repo: ${Q}...`),await D.mkdir(this.skillsDir,{recursive:!0,mode:493}),await F0(`git clone --depth 1 "${Q}" "${q}"`,{timeout:60000});let z=v.join(q,"SKILL.md");try{await D.access(z)}catch{return I.warn(`No SKILL.md found in repository ${Q}`),await D.rm(q,{recursive:!0,force:!0}),!1}await D.rm(J,{recursive:!0,force:!0}),await D.rename(q,J);try{await D.rm(v.join(J,".git"),{recursive:!0,force:!0})}catch{}return I.info(`Successfully installed skill from repo: ${$}`),!0}catch(z){try{await D.rm(q,{recursive:!0,force:!0})}catch{}return I.warn(`Failed to install from repo ${Q}: ${z instanceof Error?z.message:"Unknown error"}`),!1}}async installFromLocal(Q,Z,$=!0){let J=Z||v.basename(Q),q=v.join(this.skillsDir,J);try{let z=v.resolve(Q);try{await D.access(z)}catch{return I.warn(`Local path does not exist: ${z}`),!1}let G=v.join(z,"SKILL.md");try{await D.access(G)}catch{return I.warn(`No SKILL.md found in local path: ${z}`),!1}if(I.info(`Installing skill from local path: ${z}...`),await D.mkdir(this.skillsDir,{recursive:!0,mode:493}),await D.rm(q,{recursive:!0,force:!0}),$)await D.symlink(z,q,"dir"),I.info(`Created symlink for skill: ${J}`);else await D.cp(z,q,{recursive:!0}),I.info(`Copied skill to: ${J}`);return!0}catch(z){return I.warn(`Failed to install from local path ${Q}: ${z instanceof Error?z.message:"Unknown error"}`),!1}}extractRepoName(Q){return Q.match(/\/([^/]+?)(\.git)?$/)?.[1]||"unknown-skill"}async installAllOfficialSkills(){let{url:Q,branch:Z}=h0,$=v.join(this.skillsDir,`.tmp-all-${Date.now()}`),J=[],q=[];try{if(!await this.isGitAvailable())return I.warn("Git not available, skipping skill installation"),{installed:J,failed:q};await D.mkdir(this.skillsDir,{recursive:!0,mode:493}),I.info("Cloning official skills repository..."),await F0(`git clone --depth 1 --branch ${Z} --single-branch ${Q} "${$}"`,{timeout:60000});let z=v.join($,"skills"),G=await D.readdir(z,{withFileTypes:!0});for(let V of G){if(!V.isDirectory())continue;let W=V.name,B=v.join(z,W),F=v.join(this.skillsDir,W);try{await D.access(v.join(B,"SKILL.md")),await D.rm(F,{recursive:!0,force:!0}),await D.cp(B,F,{recursive:!0}),I.info(`Installed: ${W}`),J.push(W)}catch(O){I.warn(`Failed to install ${W}`),q.push(W)}}await D.rm($,{recursive:!0,force:!0})}catch(z){try{await D.rm($,{recursive:!0,force:!0})}catch{}I.warn(`Failed to install skills: ${z instanceof Error?z.message:"Unknown error"}`)}return{installed:J,failed:q}}}var k0=null;function YQ(Q){if(!k0)k0=new WQ(Q);return k0}import*as J0 from"node:fs/promises";import*as O0 from"node:path";import{parse as $Z}from"yaml";var JZ=/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/,qZ=/^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]?$/,KQ=1024;function zZ(Q){if(!Q)return;if(typeof Q==="string")return Q.split(",").map((Z)=>Z.trim()).filter(Boolean);if(Array.isArray(Q))return Q.map((Z)=>String(Z).trim()).filter(Boolean);return}function XQ(Q){if(Q===void 0)return;if(typeof Q==="boolean")return Q;if(typeof Q==="string"){let Z=Q.toLowerCase().trim();if(Z==="true"||Z==="yes"||Z==="1")return!0;if(Z==="false"||Z==="no"||Z==="0")return!1}return}function GZ(Q,Z){if(!Q.name)return{valid:!1,error:"Missing required field: name"};if(!qZ.test(Q.name))return{valid:!1,error:`Invalid name "${Q.name}": must be lowercase letters, numbers, and hyphens only, 1-64 characters`};if(!Q.description)return{valid:!1,error:"Missing required field: description"};if(Q.description.length>KQ)return{valid:!1,error:`Description too long: ${Q.description.length} characters (max ${KQ})`};let $;if(Q.model)$=Q.model==="inherit"?"inherit":Q.model;return{valid:!0,metadata:{name:Q.name,description:Q.description.trim(),allowedTools:zZ(Q["allowed-tools"]),version:Q.version,argumentHint:Q["argument-hint"]?.trim(),userInvocable:XQ(Q["user-invocable"]),disableModelInvocation:XQ(Q["disable-model-invocation"]),model:$,whenToUse:Q.when_to_use?.trim()}}}function HQ(Q,Z,$){let J=Q.match(JZ);if(!J)return{success:!1,error:"Invalid SKILL.md format: missing YAML frontmatter (must start with ---)"};let[,q,z]=J,G;try{G=$Z(q)}catch(B){return{success:!1,error:`Failed to parse YAML frontmatter: ${B instanceof Error?B.message:String(B)}`}}let V=GZ(G,Z);if(!V.valid)return{success:!1,error:V.error};let W=O0.dirname(Z);return{success:!0,content:{metadata:{...V.metadata,path:Z,basePath:W,source:$},instructions:z.trim()}}}async function BQ(Q,Z){try{let $=await J0.readFile(Q,"utf-8");return HQ($,Q,Z)}catch($){if($.code==="ENOENT")return{success:!1,error:`File not found: ${Q}`};return{success:!1,error:`Failed to read file: ${$ instanceof Error?$.message:String($)}`}}}async function jQ(Q){try{let Z=await J0.readFile(Q.path,"utf-8"),$=HQ(Z,Q.path,Q.source);return $.success?$.content:null}catch{return null}}async function DQ(Q){try{return await J0.access(O0.join(Q,"SKILL.md")),!0}catch{return!1}}var VZ={userSkillsDir:x.join(wQ(),".blade","skills"),projectSkillsDir:".blade/skills",claudeUserSkillsDir:x.join(wQ(),".claude","skills"),claudeProjectSkillsDir:".claude/skills"},L0=null;class C0{skills=new Map;pluginSkills=new Map;config;initialized=!1;constructor(Q){this.config={...VZ,cwd:k(),...Q}}static getInstance(Q){if(!L0)L0=new C0(Q);return L0}static resetInstance(){L0=null}async initialize(){if(this.initialized)return{skills:Array.from(this.skills.values()),errors:[]};let Q=[],Z=[];try{await YQ(this.config.userSkillsDir).ensureDefaultSkillsInstalled()}catch(W){Q.push({path:"SkillInstaller",error:`Failed to install default skills: ${W instanceof Error?W.message:"Unknown error"}`})}this.loadBuiltinSkills();let $=await this.scanDirectory(this.config.claudeUserSkillsDir,"user");Z.push(...$.skills),Q.push(...$.errors);let J=await this.scanDirectory(this.config.userSkillsDir,"user");Z.push(...J.skills),Q.push(...J.errors);let q=x.isAbsolute(this.config.claudeProjectSkillsDir)?this.config.claudeProjectSkillsDir:x.join(this.config.cwd,this.config.claudeProjectSkillsDir),z=await this.scanDirectory(q,"project");Z.push(...z.skills),Q.push(...z.errors);let G=x.isAbsolute(this.config.projectSkillsDir)?this.config.projectSkillsDir:x.join(this.config.cwd,this.config.projectSkillsDir),V=await this.scanDirectory(G,"project");Z.push(...V.skills),Q.push(...V.errors);for(let W of Z)this.skills.set(W.name,W);return this.initialized=!0,{skills:Array.from(this.skills.values()),errors:Q}}loadBuiltinSkills(){this.skills.set(D0.name,D0),this.skills.set(w0.name,w0)}async scanDirectory(Q,Z){let $=[],J=[];try{await b0.access(Q)}catch{return{skills:$,errors:J}}try{let q=await b0.readdir(Q,{withFileTypes:!0});for(let z of q){if(!z.isDirectory())continue;let G=x.join(Q,z.name),V=x.join(G,"SKILL.md");if(!await DQ(G))continue;let W=await BQ(V,Z);if(W.success&&W.content)$.push(W.content.metadata);else J.push({path:V,error:W.error||"Unknown error"})}}catch(q){J.push({path:Q,error:`Failed to scan directory: ${q instanceof Error?q.message:String(q)}`})}return{skills:$,errors:J}}getAll(){return Array.from(this.skills.values())}get(Q){return this.skills.get(Q)}has(Q){return this.skills.has(Q)}async loadContent(Q){let Z=this.skills.get(Q);if(!Z)return null;if(Z.source==="builtin")return this.loadBuiltinContent(Q);return jQ(Z)}loadBuiltinContent(Q){switch(Q){case"skill-creator":return GQ();case"update-config":return VQ();default:return null}}getModelInvocableSkills(){return Array.from(this.skills.values()).filter((Q)=>!Q.disableModelInvocation)}getUserInvocableSkills(){return Array.from(this.skills.values()).filter((Q)=>Q.userInvocable===!0)}generateAvailableSkillsList(){let Q=this.getModelInvocableSkills();if(Q.length===0)return"";let Z=[];for(let $ of Q){let J=$.description.length>100?`${$.description.substring(0,97)}...`:$.description,q=$.argumentHint?`${$.name} ${$.argumentHint}`:$.name;Z.push(`- ${q}: ${J}`)}return Z.join(`
564
+ `)}get size(){return this.skills.size}async refresh(){return this.skills.clear(),this.pluginSkills.clear(),this.initialized=!1,this.initialize()}registerPluginSkill(Q){this.pluginSkills.set(Q.namespacedName,Q),this.skills.set(Q.namespacedName,Q.metadata)}findPluginSkill(Q){let Z=this.pluginSkills.get(Q);if(Z)return Z;let $=[];for(let J of this.pluginSkills.values())if(J.originalName===Q)$.push(J);if($.length===1)return $[0];return}getAllPluginSkills(){return Array.from(this.pluginSkills.values())}clearPluginSkills(){for(let Q of this.pluginSkills.values())this.skills.delete(Q.namespacedName);this.pluginSkills.clear()}getPluginSkillCount(){return this.pluginSkills.size}}function _0(Q){return C0.getInstance(Q)}async function WZ(Q){return _0(Q).initialize()}var YZ="Skill",KZ=/<available_skills>\s*<\/available_skills>/;function p0(Q){let $=_0().generateAvailableSkillsList();if(!$)return Q;return Q.map((J)=>{if(J.name!==YZ)return J;let q=J.description.replace(KZ,`<available_skills>
565
565
  ${$}
566
- </available_skills>`);if(q===J.description)return J;return{...J,description:q}})}var VZ=new Set(["user-cancel","interrupt","sibling-error","timeout"]);function DQ(Q){if(!Q.aborted)return;if(typeof Q.reason==="string"&&VZ.has(Q.reason))return Q.reason;return"user-cancel"}function wQ(){return{consecutiveFailures:new Map,totalFailures:0,lastFailedTool:null}}function FQ(Q,Z){Q.consecutiveFailures.set(Z,0),Q.lastFailedTool=null}function OQ(Q,Z){let $=(Q.consecutiveFailures.get(Z)??0)+1;Q.consecutiveFailures.set(Z,$),Q.totalFailures++,Q.lastFailedTool=Z}function WZ(Q,Z){return(Q.consecutiveFailures.get(Z)??0)>=3}function LQ(Q,Z){if(!WZ(Q,Z))return;let $=Q.consecutiveFailures.get(Z)??0;return`WARNING: ${Z} has failed ${$} consecutive times. Consider a different approach: use a different tool, verify your parameters, or break the task into smaller steps.`}function bQ(Q){return Q>0&&Q%5===0}function _Q(Q,Z){let $=[`[Self-check at turn ${Q}]`,"Before continuing, briefly assess:","1. Are you making progress toward the goal?","2. Have any approaches failed repeatedly that you should abandon?","3. Is there a simpler path you haven't tried?"];if(Z>3)$.push(`Note: ${Z} tool failures so far. Consider whether your current strategy needs adjustment.`);return $.join(`
567
- `)}function IQ(){return{recentOutputHashes:[]}}function YZ(Q){let Z=Q.trim().slice(0,500),$=0;for(let J=0;J<Z.length;J++)$=($<<5)-$+Z.charCodeAt(J)|0;return $.toString(36)}function UQ(Q,Z){let $=YZ(Z);if(Q.recentOutputHashes.push($),Q.recentOutputHashes.length>4)Q.recentOutputHashes.shift();if(Q.recentOutputHashes.length<3)return!1;let J=Q.recentOutputHashes.slice(-3);return J.every((q)=>q===J[0])}function vQ(){return"WARNING: You appear to be repeating the same output. Stop and try a fundamentally different approach. If the task cannot be completed, explain why and stop."}var d=M("Agent"),XZ=new Set(["Read","Glob","Grep","WebFetch","WebSearch","MemoryRead","GetSpecContext","ValidateSpec","TaskOutput"]);class _0{pipeline;execContext;registry;contextMgr;sessionId;lastMessageUuid;subagentInfo;pending=new Map;completed=new Map;queued=[];order=[];dispatched=new Set;abortController=new AbortController;epoch=0;activeAborts=new Map;constructor(Q,Z,$,J,q,z,G){this.pipeline=Q;this.execContext=Z;this.registry=$;this.contextMgr=J;this.sessionId=q;this.lastMessageUuid=z;this.subagentInfo=G}addTool(Q,Z){if(this.dispatched.has(Q.id)){d.debug(`[StreamingToolExecutor] 跳过已分发工具: ${Q.function.name} (${Q.id})`);return}if(this.dispatched.add(Q.id),this.order.push(Q.id),XZ.has(Q.function.name)){d.debug(`[StreamingToolExecutor] 立即执行预启动工具: ${Q.function.name}`);let J=this.executeOne(Q,Z);this.pending.set(Q.id,J)}else d.debug(`[StreamingToolExecutor] 排队非预启动工具: ${Q.function.name}`),this.queued.push({toolCall:Q,params:Z})}async*getRemainingResults(){for(let Q of this.order){if(this.completed.has(Q)){yield this.completed.get(Q),this.completed.delete(Q);continue}if(this.pending.has(Q)){let $=await this.pending.get(Q);this.pending.delete(Q),yield $;continue}let Z=this.queued.findIndex(($)=>$.toolCall.id===Q);if(Z!==-1){let{toolCall:$,params:J}=this.queued[Z];if(this.queued.splice(Z,1),this.execContext.signal?.aborted){d.debug(`[StreamingToolExecutor] Signal aborted, 跳过排队工具: ${$.function.name} (${$.id})`),yield this.makeAbortResult($,"Tool execution skipped: task aborted before launch");continue}yield await this.executeOne($,J)}}}getCompletedResults(){let Q=Array.from(this.completed.values());return this.completed.clear(),Q}discard(){this.epoch++,this.abortController.abort(),this.abortController=new AbortController;for(let[,Q]of this.activeAborts)Q.abort();this.activeAborts.clear(),this.queued=[],this.order=[],this.dispatched.clear(),this.completed.clear(),this.pending.clear(),d.debug(`[StreamingToolExecutor] 已丢弃所有挂起工作并重置状态 (epoch=${this.epoch})`)}hasTools(){return this.order.length>0}getEpoch(){return this.epoch}makeAbortResult(Q,Z){return{toolCall:Q,result:{success:!1,llmContent:"",error:{type:"execution_error",message:Z},metadata:{abortedBeforeLaunch:!0}},toolUseUuid:null}}async executeOne(Q,Z){let $=this.epoch,J=new AbortController;this.activeAborts.set(Q.id,J);let q=this.abortController.signal;try{if(q.aborted||J.signal.aborted)return this.makeAbortResult(Q,"Tool execution aborted due to discard");let z=null;try{if(this.contextMgr&&this.sessionId)z=await this.contextMgr.saveToolUse(this.sessionId,Q.function.name,Z,this.lastMessageUuid??null,this.subagentInfo)}catch(Y){d.warn("[StreamingToolExecutor] 保存工具调用失败:",Y)}let G=[q,J.signal],V=this.execContext.signal;if(V)G.push(V);let W=t0(...G),H={...this.execContext,signal:W},F=await this.pipeline.execute(Q.function.name,Z,H);if($!==this.epoch)return d.debug(`[StreamingToolExecutor] 丢弃旧世代工具结果: ${Q.function.name} (startEpoch=${$}, currentEpoch=${this.epoch})`),this.makeAbortResult(Q,"Tool execution aborted due to epoch mismatch (discard)");let L={toolCall:Q,result:F,toolUseUuid:z};if(this.pending.has(Q.id))this.pending.delete(Q.id),this.completed.set(Q.id,L);return L}catch(z){if($!==this.epoch)return this.makeAbortResult(Q,"Tool execution aborted due to epoch mismatch (discard)");d.error(`[StreamingToolExecutor] 工具执行失败: ${Q.function.name}`,z);let G={success:!1,llmContent:"",error:{type:"execution_error",message:z instanceof Error?z.message:"Unknown error"},metadata:void 0},V={toolCall:Q,result:G,toolUseUuid:null,error:z instanceof Error?z:Error("Unknown error")};if(this.pending.has(Q.id))this.pending.delete(Q.id),this.completed.set(Q.id,V);return V}finally{this.activeAborts.delete(Q.id)}}}var N=M("Agent"),BZ=0.1,jZ=8192,DZ=32768,EQ=100,wZ=`
566
+ </available_skills>`);if(q===J.description)return J;return{...J,description:q}})}var XZ=new Set(["user-cancel","interrupt","sibling-error","timeout"]);function FQ(Q){if(!Q.aborted)return;if(typeof Q.reason==="string"&&XZ.has(Q.reason))return Q.reason;return"user-cancel"}function OQ(){return{consecutiveFailures:new Map,totalFailures:0,lastFailedTool:null}}function LQ(Q,Z){Q.consecutiveFailures.set(Z,0),Q.lastFailedTool=null}function bQ(Q,Z){let $=(Q.consecutiveFailures.get(Z)??0)+1;Q.consecutiveFailures.set(Z,$),Q.totalFailures++,Q.lastFailedTool=Z}function HZ(Q,Z){return(Q.consecutiveFailures.get(Z)??0)>=3}function _Q(Q,Z){if(!HZ(Q,Z))return;let $=Q.consecutiveFailures.get(Z)??0;return`WARNING: ${Z} has failed ${$} consecutive times. Consider a different approach: use a different tool, verify your parameters, or break the task into smaller steps.`}function IQ(Q){return Q>0&&Q%5===0}function vQ(Q,Z){let $=[`[Self-check at turn ${Q}]`,"Before continuing, briefly assess:","1. Are you making progress toward the goal?","2. Have any approaches failed repeatedly that you should abandon?","3. Is there a simpler path you haven't tried?"];if(Z>3)$.push(`Note: ${Z} tool failures so far. Consider whether your current strategy needs adjustment.`);return $.join(`
567
+ `)}function UQ(){return{recentOutputHashes:[]}}function BZ(Q){let Z=Q.trim().slice(0,500),$=0;for(let J=0;J<Z.length;J++)$=($<<5)-$+Z.charCodeAt(J)|0;return $.toString(36)}function EQ(Q,Z){let $=BZ(Z);if(Q.recentOutputHashes.push($),Q.recentOutputHashes.length>4)Q.recentOutputHashes.shift();if(Q.recentOutputHashes.length<3)return!1;let J=Q.recentOutputHashes.slice(-3);return J.every((q)=>q===J[0])}function NQ(){return"WARNING: You appear to be repeating the same output. Stop and try a fundamentally different approach. If the task cannot be completed, explain why and stop."}var d=M("Agent"),DZ=new Set(["Read","Glob","Grep","WebFetch","WebSearch","MemoryRead","GetSpecContext","ValidateSpec","TaskOutput"]);class I0{pipeline;execContext;registry;contextMgr;sessionId;lastMessageUuid;subagentInfo;pending=new Map;completed=new Map;queued=[];order=[];dispatched=new Set;abortController=new AbortController;epoch=0;activeAborts=new Map;constructor(Q,Z,$,J,q,z,G){this.pipeline=Q;this.execContext=Z;this.registry=$;this.contextMgr=J;this.sessionId=q;this.lastMessageUuid=z;this.subagentInfo=G}addTool(Q,Z){if(this.dispatched.has(Q.id)){d.debug(`[StreamingToolExecutor] 跳过已分发工具: ${Q.function.name} (${Q.id})`);return}if(this.dispatched.add(Q.id),this.order.push(Q.id),DZ.has(Q.function.name)){d.debug(`[StreamingToolExecutor] 立即执行预启动工具: ${Q.function.name}`);let J=this.executeOne(Q,Z);this.pending.set(Q.id,J)}else d.debug(`[StreamingToolExecutor] 排队非预启动工具: ${Q.function.name}`),this.queued.push({toolCall:Q,params:Z})}async*getRemainingResults(){for(let Q of this.order){if(this.completed.has(Q)){yield this.completed.get(Q),this.completed.delete(Q);continue}if(this.pending.has(Q)){let $=await this.pending.get(Q);this.pending.delete(Q),yield $;continue}let Z=this.queued.findIndex(($)=>$.toolCall.id===Q);if(Z!==-1){let{toolCall:$,params:J}=this.queued[Z];if(this.queued.splice(Z,1),this.execContext.signal?.aborted){d.debug(`[StreamingToolExecutor] Signal aborted, 跳过排队工具: ${$.function.name} (${$.id})`),yield this.makeAbortResult($,"Tool execution skipped: task aborted before launch");continue}yield await this.executeOne($,J)}}}getCompletedResults(){let Q=Array.from(this.completed.values());return this.completed.clear(),Q}discard(){this.epoch++,this.abortController.abort(),this.abortController=new AbortController;for(let[,Q]of this.activeAborts)Q.abort();this.activeAborts.clear(),this.queued=[],this.order=[],this.dispatched.clear(),this.completed.clear(),this.pending.clear(),d.debug(`[StreamingToolExecutor] 已丢弃所有挂起工作并重置状态 (epoch=${this.epoch})`)}hasTools(){return this.order.length>0}getEpoch(){return this.epoch}makeAbortResult(Q,Z){return{toolCall:Q,result:{success:!1,llmContent:"",error:{type:"execution_error",message:Z},metadata:{abortedBeforeLaunch:!0}},toolUseUuid:null}}async executeOne(Q,Z){let $=this.epoch,J=new AbortController;this.activeAborts.set(Q.id,J);let q=this.abortController.signal;try{if(q.aborted||J.signal.aborted)return this.makeAbortResult(Q,"Tool execution aborted due to discard");let z=null;try{if(this.contextMgr&&this.sessionId)z=await this.contextMgr.saveToolUse(this.sessionId,Q.function.name,Z,this.lastMessageUuid??null,this.subagentInfo)}catch(Y){d.warn("[StreamingToolExecutor] 保存工具调用失败:",Y)}let G=[q,J.signal],V=this.execContext.signal;if(V)G.push(V);let W=e0(...G),B={...this.execContext,signal:W},F=await this.pipeline.execute(Q.function.name,Z,B);if($!==this.epoch)return d.debug(`[StreamingToolExecutor] 丢弃旧世代工具结果: ${Q.function.name} (startEpoch=${$}, currentEpoch=${this.epoch})`),this.makeAbortResult(Q,"Tool execution aborted due to epoch mismatch (discard)");let O={toolCall:Q,result:F,toolUseUuid:z};if(this.pending.has(Q.id))this.pending.delete(Q.id),this.completed.set(Q.id,O);return O}catch(z){if($!==this.epoch)return this.makeAbortResult(Q,"Tool execution aborted due to epoch mismatch (discard)");d.error(`[StreamingToolExecutor] 工具执行失败: ${Q.function.name}`,z);let G={success:!1,llmContent:"",error:{type:"execution_error",message:z instanceof Error?z.message:"Unknown error"},metadata:void 0},V={toolCall:Q,result:G,toolUseUuid:null,error:z instanceof Error?z:Error("Unknown error")};if(this.pending.has(Q.id))this.pending.delete(Q.id),this.completed.set(Q.id,V);return V}finally{this.activeAborts.delete(Q.id)}}}var N=M("Agent"),FZ=0.1,OZ=8192,LZ=32768,yQ=100,bZ=`
568
568
 
569
569
  # Task Execution Strategy
570
570
  When facing complex multi-step tasks:
@@ -572,22 +572,22 @@ When facing complex multi-step tasks:
572
572
  2. Execute one step at a time — verify each step succeeded before moving to the next.
573
573
  3. If a step fails, diagnose the root cause rather than repeating the same approach.
574
574
  4. When uncertain about file paths or project structure, use Grep/Glob/Read to gather facts first.
575
- 5. Prefer the smallest change that achieves the goal — avoid unnecessary refactoring.`;function FZ(Q){if(typeof Q==="string")return Q;try{return JSON.parse(JSON.stringify(Q))}catch{return String(Q)}}function OZ(Q){if(!(Q instanceof Error))return"未知错误";let J=Q.lastError??Q;if(J.responseBody)try{let V=JSON.parse(J.responseBody)?.error?.message;if(V){let W=J.statusCode?` (HTTP ${J.statusCode})`:"";return`${V}${W}`}}catch{}let q=Q.message,z=q.match(/Last error:\s*(.+)$/);if(z)return z[1];return q}function LZ(Q){if(!(Q instanceof Error))return!1;return["stream not supported","streaming is not available","sse not supported","does not support streaming"].some(($)=>Q.message.toLowerCase().includes($.toLowerCase()))}function bZ(Q,Z){if(!Z)return"Tool execution failed (no details).";let $=[`Error: ${Z.message||"Unknown error"}`];if(Z.type==="validation_error")$.push("Hint: Check the tool parameters — a required field may be missing or have the wrong type.");else if(Z.type==="permission_denied")$.push("Hint: This operation requires user approval. Try a different approach or ask the user.");else if(Z.type==="timeout_error")$.push("Hint: The operation timed out. Consider breaking it into smaller steps or increasing timeout.");else if(Z.type==="execution_error"){let J=Z.message??"";if(J.includes("ENOENT")||J.includes("no such file"))$.push("Hint: File or directory not found. Use Glob or Grep to find the correct path first.");else if(J.includes("EACCES")||J.includes("permission"))$.push("Hint: Permission denied. The file may be read-only or owned by another user.");else if(J.includes("not found in file")||J.includes("old_string"))$.push(`Hint: The target text was not found. Use Read to view the current file content, then retry ${Q} with the exact text.`);else if(J.includes("ENOTDIR"))$.push("Hint: A path component is not a directory. Verify the full path with Glob.")}return $.join(`
576
- `)}function _Z(Q){if(!(Q instanceof Error))return!1;let Z=Q.message.toLowerCase();return Z.includes("prompt_too_long")||Z.includes("prompt is too long")||Z.includes("maximum context length")||Z.includes("request too large")||Q.status===413}function IZ(Q,Z){let $=Z,J=$.index??0;if(!Q.has(J))Q.set(J,{id:$.id||"",name:$.function?.name||"",arguments:""});let q=Q.get(J);if($.id&&!q.id)q.id=$.id;if($.function?.name&&!q.name)q.name=$.function.name;if($.function?.arguments)q.arguments+=$.function.arguments}function UZ(Q){if(Q.size===0)return;return Array.from(Q.values()).filter((Z)=>Z.id&&Z.name).map((Z)=>({id:Z.id,type:"function",function:{name:Z.name,arguments:Z.arguments}}))}async function*vZ(Q,Z,$,J,q){let z="",G="",V,W,H=new Map;try{let F=Q.chatService.streamChat(Z,$,J),L=0;for await(let Y of F){if(L++,J?.aborted)break;if(Y.modelFallback){q?.discard(),z="",G="",V=void 0,W=void 0,H.clear(),L=0,yield{kind:"model_fallback"};continue}if(Y.content)z+=Y.content,yield{kind:"content_delta",delta:Y.content};if(Y.reasoningContent)G+=Y.reasoningContent,yield{kind:"thinking_delta",delta:Y.reasoningContent};if(Y.usage)V=Y.usage;if(Y.toolCalls){for(let O of Y.toolCalls)if(IZ(H,O),q){let B=O.index??0,j=H.get(B);if(j&&j.id&&j.name)try{let P=JSON.parse(j.arguments),R={id:j.id,type:"function",function:{name:j.name,arguments:j.arguments}},f=Q.executionPipeline.getRegistry().get(j.name)?.kind;q.addTool(R,P),yield{kind:"tool_start",toolCall:R,toolKind:f}}catch{}}}if(Y.finishReason){W=Y.finishReason;break}}if(L===0&&!J?.aborted&&z.length===0&&H.size===0)return N.warn("[Loop] 流式响应返回0个chunk,回退到非流式模式"),q?.discard(),{...await Q.chatService.chat(Z,$,J),_nonStreamingFallback:!0};return{content:z,reasoningContent:G||void 0,toolCalls:UZ(H),usage:V,finishReason:W}}catch(F){if(LZ(F))return N.warn("[Loop] 流式请求失败,降级到非流式模式"),q?.discard(),{...await Q.chatService.chat(Z,$,J),_nonStreamingFallback:!0};throw F}}async function NQ(Q,Z,$,J,q){if(J===void 0)return N.debug(`[Loop] [轮次 ${$}] 压缩检查: 跳过(无历史 usage 数据)`),"none";let z=B0(Z.messages),G=!1;if(z.snippedCount>0)G=!0,N.debug(`[Loop] [轮次 ${$}] Snip 压缩: 移除 ${z.snippedCount} 轮旧工具调用,释放约 ${z.estimatedTokensFreed} tokens`);let V=Q.chatService.getConfig(),W=V.model,H=V.maxContextTokens??Q.config.maxContextTokens,F=V.maxOutputTokens??Q.config.maxOutputTokens??Math.min(Math.max(Math.floor(H*BZ),jZ),DZ),L=H-F,Y=Math.floor(L*0.8);if(N.debug(`[Loop] [轮次 ${$}] 压缩检查:`,{promptTokens:J,maxContextTokens:H,maxOutputTokens:F,availableForInput:L,threshold:Y,shouldCompact:J>=Y}),J<Y){if(G)Z.messages=z.messages;return G?"snipped":"none"}N.debug($===0?"[Loop] 触发自动压缩":`[Loop] [轮次 ${$}] 触发循环内自动压缩`);try{let O=G?z.messages:Z.messages,_=await n.compact(O,{trigger:"auto",modelName:W,maxContextTokens:H,apiKey:V.apiKey,baseURL:V.baseUrl,actualPreTokens:J,signal:q});if(Z.messages=_.compactedMessages,_.success)N.debug(`[Loop] [轮次 ${$}] 压缩完成: ${_.preTokens} -> ${_.postTokens} tokens`);else N.warn(`[Loop] [轮次 ${$}] 压缩使用降级策略: ${_.preTokens} -> ${_.postTokens} tokens`);return await Y0(Q,Z,_.summary,{trigger:"auto",preTokens:_.preTokens,postTokens:_.postTokens,filesIncluded:_.filesIncluded}),"compacted"}catch(O){if(c(O))return N.debug(`[Loop] [轮次 ${$}] 压缩被中止`),"none";if(G)Z.messages=z.messages;return N.error(`[Loop] [轮次 ${$}] 压缩失败,继续执行`,O),G?"snipped":"none"}}function i(Q,Z,$,J){let q=J?DQ(J):"user-cancel";return{success:!1,error:{type:"aborted",message:(q==="interrupt"?void 0:"任务已被用户中止")??"任务已中断"},metadata:{turnsCount:Q,toolCallsCount:Z,duration:Date.now()-$,abortReason:q}}}async function*EZ(Q,Z,$,J,q){let z=Date.now(),G=0,V=[];try{let W=Q.executionPipeline.getRegistry(),H=$.permissionMode,F=W.getFunctionDeclarationsByMode(H);F=C0(F);let L=Q.applySkillToolRestrictions(F),Y=wQ(),O=IQ(),_=q;if(typeof W.getDeferredToolsListing==="function"){let a=W.getDeferredToolsListing();if(a&&_)_=`${_}
575
+ 5. Prefer the smallest change that achieves the goal — avoid unnecessary refactoring.`;function _Z(Q){if(typeof Q==="string")return Q;try{return JSON.parse(JSON.stringify(Q))}catch{return String(Q)}}function IZ(Q){if(!(Q instanceof Error))return"未知错误";let J=Q.lastError??Q;if(J.responseBody)try{let V=JSON.parse(J.responseBody)?.error?.message;if(V){let W=J.statusCode?` (HTTP ${J.statusCode})`:"";return`${V}${W}`}}catch{}let q=Q.message,z=q.match(/Last error:\s*(.+)$/);if(z)return z[1];return q}function vZ(Q){if(!(Q instanceof Error))return!1;return["stream not supported","streaming is not available","sse not supported","does not support streaming"].some(($)=>Q.message.toLowerCase().includes($.toLowerCase()))}function UZ(Q,Z){if(!Z)return"Tool execution failed (no details).";let $=[`Error: ${Z.message||"Unknown error"}`];if(Z.type==="validation_error")$.push("Hint: Check the tool parameters — a required field may be missing or have the wrong type.");else if(Z.type==="permission_denied")$.push("Hint: This operation requires user approval. Try a different approach or ask the user.");else if(Z.type==="timeout_error")$.push("Hint: The operation timed out. Consider breaking it into smaller steps or increasing timeout.");else if(Z.type==="execution_error"){let J=Z.message??"";if(J.includes("ENOENT")||J.includes("no such file"))$.push("Hint: File or directory not found. Use Glob or Grep to find the correct path first.");else if(J.includes("EACCES")||J.includes("permission"))$.push("Hint: Permission denied. The file may be read-only or owned by another user.");else if(J.includes("not found in file")||J.includes("old_string"))$.push(`Hint: The target text was not found. Use Read to view the current file content, then retry ${Q} with the exact text.`);else if(J.includes("ENOTDIR"))$.push("Hint: A path component is not a directory. Verify the full path with Glob.")}return $.join(`
576
+ `)}function EZ(Q){if(!(Q instanceof Error))return!1;let Z=Q.message.toLowerCase();return Z.includes("prompt_too_long")||Z.includes("prompt is too long")||Z.includes("maximum context length")||Z.includes("request too large")||Q.status===413}function NZ(Q,Z){let $=Z,J=$.index??0;if(!Q.has(J))Q.set(J,{id:$.id||"",name:$.function?.name||"",arguments:""});let q=Q.get(J);if($.id&&!q.id)q.id=$.id;if($.function?.name&&!q.name)q.name=$.function.name;if($.function?.arguments)q.arguments+=$.function.arguments}function yZ(Q){if(Q.size===0)return;return Array.from(Q.values()).filter((Z)=>Z.id&&Z.name).map((Z)=>({id:Z.id,type:"function",function:{name:Z.name,arguments:Z.arguments}}))}async function*AZ(Q,Z,$,J,q){let z="",G="",V,W,B=new Map;try{let F=Q.chatService.streamChat(Z,$,J),O=0;for await(let Y of F){if(O++,J?.aborted)break;if(Y.modelFallback){q?.discard(),z="",G="",V=void 0,W=void 0,B.clear(),O=0,yield{kind:"model_fallback"};continue}if(Y.content)z+=Y.content,yield{kind:"content_delta",delta:Y.content};if(Y.reasoningContent)G+=Y.reasoningContent,yield{kind:"thinking_delta",delta:Y.reasoningContent};if(Y.usage)V=Y.usage;if(Y.toolCalls){for(let L of Y.toolCalls)if(NZ(B,L),q){let j=L.index??0,K=B.get(j);if(K&&K.id&&K.name)try{let P=JSON.parse(K.arguments),R={id:K.id,type:"function",function:{name:K.name,arguments:K.arguments}},f=Q.executionPipeline.getRegistry().get(K.name)?.kind;q.addTool(R,P),yield{kind:"tool_start",toolCall:R,toolKind:f}}catch{}}}if(Y.finishReason){W=Y.finishReason;break}}if(O===0&&!J?.aborted&&z.length===0&&B.size===0)return N.warn("[Loop] 流式响应返回0个chunk,回退到非流式模式"),q?.discard(),{...await Q.chatService.chat(Z,$,J),_nonStreamingFallback:!0};return{content:z,reasoningContent:G||void 0,toolCalls:yZ(B),usage:V,finishReason:W}}catch(F){if(vZ(F))return N.warn("[Loop] 流式请求失败,降级到非流式模式"),q?.discard(),{...await Q.chatService.chat(Z,$,J),_nonStreamingFallback:!0};throw F}}async function AQ(Q,Z,$,J,q,z){if(J===void 0)return N.debug(`[Loop] [轮次 ${$}] 压缩检查: 跳过(无历史 usage 数据)`),"none";let G=ZQ(Z.messages,z);if(G)Z.messages=G.messages,N.debug(`[Loop] [轮次 ${$}] MicroCompact: 清理 ${G.snippedCount} 轮旧工具结果(缓存已过期)`);let V=Z0(Z.messages),W=!1;if(V.snippedCount>0)W=!0,N.debug(`[Loop] [轮次 ${$}] Snip 压缩: 移除 ${V.snippedCount} 轮旧工具调用,释放约 ${V.estimatedTokensFreed} tokens`);let B=Q.chatService.getConfig(),F=B.model,O=B.maxContextTokens??Q.config.maxContextTokens,Y=B.maxOutputTokens??Q.config.maxOutputTokens??Math.min(Math.max(Math.floor(O*FZ),OZ),LZ),L=O-Y,E=Math.floor(L*0.8);if(N.debug(`[Loop] [轮次 ${$}] 压缩检查:`,{promptTokens:J,maxContextTokens:O,maxOutputTokens:Y,availableForInput:L,threshold:E,shouldCompact:J>=E}),J<E){if(W)Z.messages=V.messages;return W?"snipped":"none"}N.debug($===0?"[Loop] 触发自动压缩":`[Loop] [轮次 ${$}] 触发循环内自动压缩`);try{let j=W?V.messages:Z.messages,K=await i.compact(j,{trigger:"auto",modelName:F,maxContextTokens:O,apiKey:B.apiKey,baseURL:B.baseUrl,actualPreTokens:J,signal:q});if(Z.messages=K.compactedMessages,K.success)N.debug(`[Loop] [轮次 ${$}] 压缩完成: ${K.preTokens} -> ${K.postTokens} tokens`);else N.warn(`[Loop] [轮次 ${$}] 压缩使用降级策略: ${K.preTokens} -> ${K.postTokens} tokens`);return await X0(Q,Z,K.summary,{trigger:"auto",preTokens:K.preTokens,postTokens:K.postTokens,filesIncluded:K.filesIncluded}),"compacted"}catch(j){if(g(j))return N.debug(`[Loop] [轮次 ${$}] 压缩被中止`),"none";if(W)Z.messages=V.messages;return N.error(`[Loop] [轮次 ${$}] 压缩失败,继续执行`,j),W?"snipped":"none"}}function u(Q,Z,$,J){let q=J?FQ(J):"user-cancel";return{success:!1,error:{type:"aborted",message:(q==="interrupt"?void 0:"任务已被用户中止")??"任务已中断"},metadata:{turnsCount:Q,toolCallsCount:Z,duration:Date.now()-$,abortReason:q}}}async function*SZ(Q,Z,$,J,q){let z=Date.now(),G=0,V=[];try{let W=Q.executionPipeline.getRegistry(),B=$.permissionMode,F=W.getFunctionDeclarationsByMode(B);F=p0(F);let O=Q.applySkillToolRestrictions(F),Y=OQ(),L=UQ(),E=q;if(typeof W.getDeferredToolsListing==="function"){let a=W.getDeferredToolsListing();if(a&&E)E=`${E}
577
577
 
578
- ${a}`}if(_)_+=wZ;let B=new V0($,_);B.appendUser({role:"user",content:Z});let j=await g(Q,$,Z),P=$.permissionMode==="yolo",R=Q.runtimeOptions.maxTurns??J?.maxTurns??Q.config.maxTurns??-1;if(R===0)return{success:!1,error:{type:"chat_disabled",message:"对话功能已被禁用 (maxTurns=0)"},metadata:{turnsCount:0,toolCallsCount:0,duration:0}};let h=R===-1?EQ:Math.min(R,EQ),f=0,S,m=0,I0=0,AQ=!!$.subagentInfo,U0=c0({budget:Q.currentModelMaxContextTokens,isSubagent:AQ}),p0=new f0;try{while(!0){if(J?.signal?.aborted)return i(G,V.length,z,J.signal);B.writeback();let a=await NQ(Q,$,G,S,J?.signal);if(a!=="none"){if(a==="compacted")yield{kind:"compaction",phase:"start"},yield{kind:"compaction",phase:"end"};B.replaceHistory($.messages)}if(G++,p0.reset(),yield{kind:"turn_start",turn:G,maxTurns:h},J?.signal?.aborted)return i(G-1,V.length,z,J.signal);if(bQ(G)&&G>1){let I=_Q(G,Y.totalFailures);B.appendControl("user",{role:"user",content:`
578
+ ${a}`}if(E)E+=bZ;let j=new Y0($,E);j.appendUser({role:"user",content:Z});let K=await m(Q,$,Z),P=$.permissionMode==="yolo",R=Q.runtimeOptions.maxTurns??J?.maxTurns??Q.config.maxTurns??-1;if(R===0)return{success:!1,error:{type:"chat_disabled",message:"对话功能已被禁用 (maxTurns=0)"},metadata:{turnsCount:0,toolCallsCount:0,duration:0}};let h=R===-1?yQ:Math.min(R,yQ),f=0,S,q0,l=0,v0=0,SQ=!!$.subagentInfo,U0=u0({budget:Q.currentModelMaxContextTokens,isSubagent:SQ}),d0=new R0;try{while(!0){if(J?.signal?.aborted)return u(G,V.length,z,J.signal);j.writeback();let a=await AQ(Q,$,G,S,J?.signal,q0);if(a!=="none"){if(a==="compacted")yield{kind:"compaction",phase:"start"},yield{kind:"compaction",phase:"end"};j.replaceHistory($.messages)}if(G++,d0.reset(),yield{kind:"turn_start",turn:G,maxTurns:h},J?.signal?.aborted)return u(G-1,V.length,z,J.signal);if(IQ(G)&&G>1){let _=vQ(G,Y.totalFailures);j.appendControl("user",{role:"user",content:`
579
579
 
580
580
  <system-reminder>
581
- ${I}
582
- </system-reminder>`})}let d0=J?.stream!==!1,K,J0;try{if(d0)J0=new _0(Q.executionPipeline,{sessionId:$.sessionId,userId:$.userId||"default",workspaceRoot:$.workspaceRoot||k(),signal:J?.signal,confirmationHandler:$.confirmationHandler,permissionMode:$.permissionMode,toolRegistry:W,deferredToolManager:W.deferredToolManager},Q.executionPipeline.getRegistry(),Q.executionEngine?.getContextManager(),$.sessionId,j,$.subagentInfo),K=yield*vZ(Q,B.toLLMMessages(),L,J?.signal,J0);else K=await Q.chatService.chat(B.toLLMMessages(),L,J?.signal)}catch(I){if(_Z(I)){N.warn("[Loop] 检测到 prompt_too_long 错误,尝试反应式压缩");let X=Q.chatService.getConfig(),w=await p0.tryReactiveCompact($.messages,{modelName:X.model,maxContextTokens:X.maxContextTokens??Q.config.maxContextTokens,apiKey:X.apiKey,baseURL:X.baseUrl,signal:J?.signal});if(w.success){$.messages=w.messages,B.replaceHistory($.messages),N.info("[Loop] 反应式压缩成功,重试 LLM 调用"),G--;continue}}throw I}if(K.usage){if(K.usage.totalTokens)f+=K.usage.totalTokens;S=K.usage.promptTokens,yield{kind:"token_usage",usage:{inputTokens:K.usage.promptTokens??0,outputTokens:K.usage.completionTokens??0,totalTokens:K.usage.totalTokens??0,maxContextTokens:Q.currentModelMaxContextTokens}}}let yQ=K.usage?.completionTokens??0;if(U0=u0(U0,yQ,m>0),J?.signal?.aborted)return i(G-1,V.length,z,J.signal);if(!d0||!!K._nonStreamingFallback){if(K.reasoningContent&&K.reasoningContent.trim())yield{kind:"thinking_delta",delta:K.reasoningContent};if(K.content&&K.content.trim())yield{kind:"content_delta",delta:K.content}}yield{kind:"stream_end"};let v0=N0(K.finishReason,m,U0);if(v0.action==="recover"){m++,N.warn(`[Loop] Max output tokens hit (recovery ${m}/3)`);let I={role:"assistant",content:K.content||"",reasoningContent:K.reasoningContent,tool_calls:K.toolCalls};B.appendToHistory(I);let X=await C(Q,$,K.content||"",j);if(X)j=X;let w={role:"user",content:"Output token limit hit. Resume directly — no apology, no recap. "+"Pick up mid-thought if that is where the cut happened. Break remaining work into smaller pieces."};B.appendToHistory(w);let b=await g(Q,$,w.content,j);if(b)j=b;continue}if(v0.action==="truncated"||v0.action==="budget_stop"){B.appendAssistant({role:"assistant",content:K.content||"",reasoningContent:K.reasoningContent,tool_calls:K.toolCalls});let I=await C(Q,$,K.content||"",j);if(I)j=I;return{success:!0,finalMessage:K.content,metadata:{turnsCount:G,toolCallsCount:V.length,duration:Date.now()-z,tokensUsed:f,outputTruncated:!0}}}if(K.finishReason!=="length")m=0;if(!K.toolCalls||K.toolCalls.length===0){if(K.content&&UQ(O,K.content)){B.appendAssistant({role:"assistant",content:K.content||"",reasoningContent:K.reasoningContent}),B.appendControl("user",{role:"user",content:`
581
+ ${_}
582
+ </system-reminder>`})}let m0=J?.stream!==!1,X,z0;try{if(m0)z0=new I0(Q.executionPipeline,{sessionId:$.sessionId,userId:$.userId||"default",workspaceRoot:$.workspaceRoot||k(),signal:J?.signal,confirmationHandler:$.confirmationHandler,permissionMode:$.permissionMode,toolRegistry:W,deferredToolManager:W.deferredToolManager},Q.executionPipeline.getRegistry(),Q.executionEngine?.getContextManager(),$.sessionId,K,$.subagentInfo),X=yield*AZ(Q,j.toLLMMessages(),O,J?.signal,z0);else X=await Q.chatService.chat(j.toLLMMessages(),O,J?.signal)}catch(_){if(EZ(_)){N.warn("[Loop] 检测到 prompt_too_long 错误,尝试反应式压缩");let H=Q.chatService.getConfig(),w=await d0.tryReactiveCompact($.messages,{modelName:H.model,maxContextTokens:H.maxContextTokens??Q.config.maxContextTokens,apiKey:H.apiKey,baseURL:H.baseUrl,signal:J?.signal});if(w.success){$.messages=w.messages,j.replaceHistory($.messages),N.info("[Loop] 反应式压缩成功,重试 LLM 调用"),G--;continue}}throw _}if(q0=Date.now(),X.usage){if(X.usage.totalTokens)f+=X.usage.totalTokens;S=X.usage.promptTokens,yield{kind:"token_usage",usage:{inputTokens:X.usage.promptTokens??0,outputTokens:X.usage.completionTokens??0,totalTokens:X.usage.totalTokens??0,maxContextTokens:Q.currentModelMaxContextTokens}}}let PQ=X.usage?.completionTokens??0;if(U0=i0(U0,PQ,l>0),J?.signal?.aborted)return u(G-1,V.length,z,J.signal);if(!m0||!!X._nonStreamingFallback){if(X.reasoningContent&&X.reasoningContent.trim())yield{kind:"thinking_delta",delta:X.reasoningContent};if(X.content&&X.content.trim())yield{kind:"content_delta",delta:X.content}}yield{kind:"stream_end"};let E0=y0(X.finishReason,l,U0);if(E0.action==="recover"){l++,N.warn(`[Loop] Max output tokens hit (recovery ${l}/3)`);let _={role:"assistant",content:X.content||"",reasoningContent:X.reasoningContent,tool_calls:X.toolCalls};j.appendToHistory(_);let H=await C(Q,$,X.content||"",K);if(H)K=H;let w={role:"user",content:"Output token limit hit. Resume directly — no apology, no recap. "+"Pick up mid-thought if that is where the cut happened. Break remaining work into smaller pieces."};j.appendToHistory(w);let b=await m(Q,$,w.content,K);if(b)K=b;continue}if(E0.action==="truncated"||E0.action==="budget_stop"){j.appendAssistant({role:"assistant",content:X.content||"",reasoningContent:X.reasoningContent,tool_calls:X.toolCalls});let _=await C(Q,$,X.content||"",K);if(_)K=_;return{success:!0,finalMessage:X.content,metadata:{turnsCount:G,toolCallsCount:V.length,duration:Date.now()-z,tokensUsed:f,outputTruncated:!0}}}if(X.finishReason!=="length")l=0;if(!X.toolCalls||X.toolCalls.length===0){if(X.content&&EQ(L,X.content)){j.appendAssistant({role:"assistant",content:X.content||"",reasoningContent:X.reasoningContent}),j.appendControl("user",{role:"user",content:`
583
583
 
584
584
  <system-reminder>
585
- ${vQ()}
586
- </system-reminder>`});continue}let I=A0(K.content,I0);if(I.action==="retry"){I0++,B.appendAssistant({role:"assistant",content:K.content||"",reasoningContent:K.reasoningContent});let y=await C(Q,$,K.content||"",j);if(y)j=y;let E={role:"user",content:I.prompt};B.appendControl("user",E);let T=await g(Q,$,E.content,j);if(T)j=T;continue}I0=0;let X=await l0({turnsCount:G,maxTurns:h});if(X.action==="continue"){B.appendAssistant({role:"assistant",content:K.content||"",reasoningContent:K.reasoningContent});let y=await C(Q,$,K.content||"",j);if(y)j=y;let E={role:"user",content:`
585
+ ${NQ()}
586
+ </system-reminder>`});continue}let _=A0(X.content,v0);if(_.action==="retry"){v0++,j.appendAssistant({role:"assistant",content:X.content||"",reasoningContent:X.reasoningContent});let A=await C(Q,$,X.content||"",K);if(A)K=A;let U={role:"user",content:_.prompt};j.appendControl("user",U);let T=await m(Q,$,U.content,K);if(T)K=T;continue}v0=0;let H=await a0({turnsCount:G,maxTurns:h});if(H.action==="continue"){j.appendAssistant({role:"assistant",content:X.content||"",reasoningContent:X.reasoningContent});let A=await C(Q,$,X.content||"",K);if(A)K=A;let U={role:"user",content:`
587
587
 
588
588
  <system-reminder>
589
- ${X.reason}
590
- </system-reminder>`};B.appendControl("user",E);let T=await g(Q,$,E.content,j);if(T)j=T;continue}let w=await y0({sessionId:$.sessionId,permissionMode:$.permissionMode,reason:K.content,abortSignal:J?.signal});if(w.action==="continue"){B.appendAssistant({role:"assistant",content:K.content||"",reasoningContent:K.reasoningContent});let y=await C(Q,$,K.content||"",j);if(y)j=y;let T={role:"user",content:w.reason?`
589
+ ${H.reason}
590
+ </system-reminder>`};j.appendControl("user",U);let T=await m(Q,$,U.content,K);if(T)K=T;continue}let w=await S0({sessionId:$.sessionId,permissionMode:$.permissionMode,reason:X.content,abortSignal:J?.signal});if(w.action==="continue"){j.appendAssistant({role:"assistant",content:X.content||"",reasoningContent:X.reasoningContent});let A=await C(Q,$,X.content||"",K);if(A)K=A;let T={role:"user",content:w.reason?`
591
591
 
592
592
  <system-reminder>
593
593
  ${w.reason}
@@ -595,8 +595,8 @@ ${w.reason}
595
595
 
596
596
  <system-reminder>
597
597
  Please continue the conversation from where we left it off without asking the user any further questions. Continue with the last task that you were asked to work on.
598
- </system-reminder>`};B.appendControl("user",T);let A=await g(Q,$,T.content,j);if(A)j=A;continue}B.appendAssistant({role:"assistant",content:K.content||"",reasoningContent:K.reasoningContent});let b=await C(Q,$,K.content||"",j);if(b)j=b;return{success:!0,finalMessage:K.content,metadata:{turnsCount:G,toolCallsCount:V.length,duration:Date.now()-z,tokensUsed:f,toolSuccessRate:V.length>0?V.filter((y)=>y.success).length/V.length:void 0,totalToolFailures:Y.totalFailures||void 0}}}B.appendAssistant({role:"assistant",content:K.content||"",reasoningContent:K.reasoningContent,tool_calls:K.toolCalls});{let I=await C(Q,$,K.content||"",j);if(I)j=I}if(J?.signal?.aborted)return i(G,V.length,z,J.signal);let E0=K.toolCalls.filter((I)=>I.type==="function"),q0;if(J0?.hasTools()){N.debug(`[Loop] 使用 StreamingToolExecutor 收集 ${E0.length} 个工具结果`),q0=[];for await(let I of J0.getRemainingResults())q0.push(I)}else{for(let X of E0){let b=W.get(X.function.name)?.kind;yield{kind:"tool_start",toolCall:X,toolKind:b}}let I=async(X)=>{try{let w=JSON.parse(X.function.arguments);if(X.function.name==="Task"&&(typeof w.subagent_session_id!=="string"||w.subagent_session_id.length===0))w.subagent_session_id=typeof w.resume==="string"&&w.resume.length>0?w.resume:HZ();let b=null;b=await S0(Q,$,X.function.name,w,j);let y=await Q.executionPipeline.execute(X.function.name,w,{sessionId:$.sessionId,userId:$.userId||"default",workspaceRoot:$.workspaceRoot||k(),signal:J?.signal,confirmationHandler:$.confirmationHandler,permissionMode:$.permissionMode,toolRegistry:W,deferredToolManager:W.deferredToolManager});return{toolCall:X,result:y,toolUseUuid:b}}catch(w){return N.error(`Tool execution failed for ${X.function.name}:`,w),{toolCall:X,result:{success:!1,llmContent:"",error:{type:"execution_error",message:w instanceof Error?w.message:"Unknown error"},metadata:void 0},toolUseUuid:null,error:w instanceof Error?w:Error("Unknown error")}}};q0=await Promise.all(E0.map(I))}let SQ=new T0;for(let{toolCall:I,result:X,toolUseUuid:w}of q0){let b=I;if(V.push(X),X.metadata?.abortedBeforeLaunch)return i(G,V.length,z,J?.signal);yield{kind:"tool_result",toolCall:b,result:X};{let A=X.metadata&&typeof X.metadata==="object"?X.metadata:void 0,PQ=((z0)=>z0==="running"||z0==="completed"||z0==="failed"||z0==="cancelled")(A?.subagentStatus)?A.subagentStatus:"completed",MQ=A&&typeof A.subagentSessionId==="string"?{subagentSessionId:A.subagentSessionId,subagentType:typeof A.subagentType==="string"?A.subagentType:b.function.name,subagentStatus:PQ,subagentSummary:typeof A.subagentSummary==="string"?A.subagentSummary:void 0}:void 0,m0=await P0(Q,$,b.id,b.function.name,X.success?FZ(X.llmContent):null,w,X.success?void 0:X.error?.message,MQ);if(m0)j=m0}let y=await M0(b,X,Q);if(y)yield y;if(X.success)FQ(Y,b.function.name);else OQ(Y,b.function.name);let E=X.success?X.llmContent||"":bZ(b.function.name,X.error);if(!X.success){let A=LQ(Y,b.function.name);if(A&&typeof E==="string")E=`${E}
598
+ </system-reminder>`};j.appendControl("user",T);let y=await m(Q,$,T.content,K);if(y)K=y;continue}j.appendAssistant({role:"assistant",content:X.content||"",reasoningContent:X.reasoningContent});let b=await C(Q,$,X.content||"",K);if(b)K=b;return{success:!0,finalMessage:X.content,metadata:{turnsCount:G,toolCallsCount:V.length,duration:Date.now()-z,tokensUsed:f,toolSuccessRate:V.length>0?V.filter((A)=>A.success).length/V.length:void 0,totalToolFailures:Y.totalFailures||void 0}}}j.appendAssistant({role:"assistant",content:X.content||"",reasoningContent:X.reasoningContent,tool_calls:X.toolCalls});{let _=await C(Q,$,X.content||"",K);if(_)K=_}if(J?.signal?.aborted)return u(G,V.length,z,J.signal);let N0=X.toolCalls.filter((_)=>_.type==="function"),G0;if(z0?.hasTools()){N.debug(`[Loop] 使用 StreamingToolExecutor 收集 ${N0.length} 个工具结果`),G0=[];for await(let _ of z0.getRemainingResults())G0.push(_)}else{for(let H of N0){let b=W.get(H.function.name)?.kind;yield{kind:"tool_start",toolCall:H,toolKind:b}}let _=async(H)=>{try{let w=JSON.parse(H.function.arguments);if(H.function.name==="Task"&&(typeof w.subagent_session_id!=="string"||w.subagent_session_id.length===0))w.subagent_session_id=typeof w.resume==="string"&&w.resume.length>0?w.resume:wZ();let b=null;b=await P0(Q,$,H.function.name,w,K);let A=await Q.executionPipeline.execute(H.function.name,w,{sessionId:$.sessionId,userId:$.userId||"default",workspaceRoot:$.workspaceRoot||k(),signal:J?.signal,confirmationHandler:$.confirmationHandler,permissionMode:$.permissionMode,toolRegistry:W,deferredToolManager:W.deferredToolManager});return{toolCall:H,result:A,toolUseUuid:b}}catch(w){return N.error(`Tool execution failed for ${H.function.name}:`,w),{toolCall:H,result:{success:!1,llmContent:"",error:{type:"execution_error",message:w instanceof Error?w.message:"Unknown error"},metadata:void 0},toolUseUuid:null,error:w instanceof Error?w:Error("Unknown error")}}};G0=await Promise.all(N0.map(_))}let MQ=new x0;for(let{toolCall:_,result:H,toolUseUuid:w}of G0){let b=_;if(V.push(H),H.metadata?.abortedBeforeLaunch)return u(G,V.length,z,J?.signal);yield{kind:"tool_result",toolCall:b,result:H};{let y=H.metadata&&typeof H.metadata==="object"?H.metadata:void 0,fQ=((V0)=>V0==="running"||V0==="completed"||V0==="failed"||V0==="cancelled")(y?.subagentStatus)?y.subagentStatus:"completed",RQ=y&&typeof y.subagentSessionId==="string"?{subagentSessionId:y.subagentSessionId,subagentType:typeof y.subagentType==="string"?y.subagentType:b.function.name,subagentStatus:fQ,subagentSummary:typeof y.subagentSummary==="string"?y.subagentSummary:void 0}:void 0,g0=await M0(Q,$,b.id,b.function.name,H.success?_Z(H.llmContent):null,w,H.success?void 0:H.error?.message,RQ);if(g0)K=g0}let A=await f0(b,H,Q);if(A)yield A;if(H.success)LQ(Y,b.function.name);else bQ(Y,b.function.name);let U=H.success?H.llmContent||"":UZ(b.function.name,H.error);if(!H.success){let y=_Q(Y,b.function.name);if(y&&typeof U==="string")U=`${U}
599
599
 
600
- ${A}`}if(typeof E==="object"&&E!==null)E=JSON.stringify(E,null,2);if(typeof E==="string")E=JQ(E,b.function.name,{messageBudget:SQ});let T=typeof E==="string"?E:JSON.stringify(E);if(B.appendToolResult({role:"tool",tool_call_id:b.id,name:b.function.name,content:T}),X.metadata?.shouldExitLoop){let A=typeof X.llmContent==="string"?X.llmContent:"循环已退出";return{success:X.success,finalMessage:A,metadata:{turnsCount:G,toolCallsCount:V.length,duration:Date.now()-z,shouldExitLoop:!0,targetMode:X.metadata?.targetMode,planContent:typeof X.metadata?.planContent==="string"?X.metadata.planContent:void 0}}}}if(J?.signal?.aborted)return i(G,V.length,z,J.signal);if(G>=h&&!P){if(N.info(`Warning: 达到轮次上限 ${h} 轮`),J?.onTurnLimitReached){let I=await J.onTurnLimitReached({turnsCount:G});if(I?.continue){B.writeback();try{let X=Q.chatService.getConfig(),w=await n.compact($.messages,{trigger:"auto",modelName:X.model,maxContextTokens:X.maxContextTokens??Q.config.maxContextTokens,apiKey:X.apiKey,baseURL:X.baseUrl,actualPreTokens:S,signal:J?.signal});$.messages=w.compactedMessages,B.replaceHistory($.messages);let b={role:"user",content:`This session is being continued from a previous conversation. The conversation is summarized above.
600
+ ${y}`}if(typeof U==="object"&&U!==null)U=JSON.stringify(U,null,2);if(typeof U==="string")U=zQ(U,b.function.name,{messageBudget:MQ});let T=typeof U==="string"?U:JSON.stringify(U);if(j.appendToolResult({role:"tool",tool_call_id:b.id,name:b.function.name,content:T}),H.metadata?.shouldExitLoop){let y=typeof H.llmContent==="string"?H.llmContent:"循环已退出";return{success:H.success,finalMessage:y,metadata:{turnsCount:G,toolCallsCount:V.length,duration:Date.now()-z,shouldExitLoop:!0,targetMode:H.metadata?.targetMode,planContent:typeof H.metadata?.planContent==="string"?H.metadata.planContent:void 0}}}}if(J?.signal?.aborted)return u(G,V.length,z,J.signal);if(G>=h&&!P){if(N.info(`Warning: 达到轮次上限 ${h} 轮`),J?.onTurnLimitReached){let _=await J.onTurnLimitReached({turnsCount:G});if(_?.continue){j.writeback();try{let H=Q.chatService.getConfig(),w=await i.compact($.messages,{trigger:"auto",modelName:H.model,maxContextTokens:H.maxContextTokens??Q.config.maxContextTokens,apiKey:H.apiKey,baseURL:H.baseUrl,actualPreTokens:S,signal:J?.signal});$.messages=w.compactedMessages,j.replaceHistory($.messages);let b={role:"user",content:`This session is being continued from a previous conversation. The conversation is summarized above.
601
601
 
602
- Please continue the conversation from where we left it off without asking the user any further questions. Continue with the last task that you were asked to work on.`};B.appendToHistory(b),await Y0(Q,$,w.summary,{trigger:"auto",preTokens:w.preTokens,postTokens:w.postTokens,filesIncluded:w.filesIncluded})}catch(X){N.error("[Loop] 压缩失败,使用降级策略:",X);let b=B.getHistory().slice(-80);B.replaceHistory(b)}G=0;continue}return{success:!0,finalMessage:I?.reason||"已达到对话轮次上限,用户选择停止",metadata:{turnsCount:G,toolCallsCount:V.length,duration:Date.now()-z,tokensUsed:f}}}return{success:!1,error:{type:"max_turns_exceeded",message:`已达到轮次上限 (${h} 轮)。使用 --permission-mode yolo 跳过此限制。`},metadata:{turnsCount:G,toolCallsCount:V.length,duration:Date.now()-z,tokensUsed:f}}}}}finally{B.writeback()}}catch(W){if(c(W))return i(G,V.length,z,J?.signal);let H=OZ(W);return N.error(`API 调用失败: ${H}`),{success:!1,error:{type:"api_error",message:H,details:W},metadata:{turnsCount:G,toolCallsCount:V.length,duration:Date.now()-z}}}}export{VQ as La,XQ as Ma,b0 as Na,qZ as Oa,p as Pa,G0 as Qa,V0 as Ra,fQ as Sa,N0 as Ta,A0 as Ua,y0 as Va,g as Wa,C as Xa,S0 as Ya,P0 as Za,Y0 as _a,a0 as $a,r0 as ab,o0 as bb,M0 as cb,Q0 as db,n as eb,_0 as fb,NQ as gb,EZ as hb};
602
+ Please continue the conversation from where we left it off without asking the user any further questions. Continue with the last task that you were asked to work on.`};j.appendToHistory(b),await X0(Q,$,w.summary,{trigger:"auto",preTokens:w.preTokens,postTokens:w.postTokens,filesIncluded:w.filesIncluded})}catch(H){N.error("[Loop] 压缩失败,使用降级策略:",H);let b=j.getHistory().slice(-80);j.replaceHistory(b)}G=0;continue}return{success:!0,finalMessage:_?.reason||"已达到对话轮次上限,用户选择停止",metadata:{turnsCount:G,toolCallsCount:V.length,duration:Date.now()-z,tokensUsed:f}}}return{success:!1,error:{type:"max_turns_exceeded",message:`已达到轮次上限 (${h} 轮)。使用 --permission-mode yolo 跳过此限制。`},metadata:{turnsCount:G,toolCallsCount:V.length,duration:Date.now()-z,tokensUsed:f}}}}}finally{j.writeback()}}catch(W){if(g(W))return u(G,V.length,z,J?.signal);let B=IZ(W);return N.error(`API 调用失败: ${B}`),{success:!1,error:{type:"api_error",message:B,details:W},metadata:{turnsCount:G,toolCallsCount:V.length,duration:Date.now()-z}}}}export{YQ as La,BQ as Ma,_0 as Na,WZ as Oa,p as Pa,W0 as Qa,Y0 as Ra,TQ as Sa,y0 as Ta,A0 as Ua,S0 as Va,m as Wa,C as Xa,P0 as Ya,M0 as Za,X0 as _a,r0 as $a,o0 as ab,s0 as bb,f0 as cb,Q0 as db,i as eb,I0 as fb,AQ as gb,SZ as hb};
@@ -1,4 +1,4 @@
1
- import{p as z,q as g,r as v,s as p}from"./chunk-wc4agkf7.js";import{t as E}from"./chunk-pcky0ctg.js";import{v as S,w as h,x as c}from"./chunk-2be9zcm4.js";import{G as w,I as F,J as y,L as x,M as C}from"./chunk-tjzyqsnc.js";import"./chunk-sdfra3bn.js";import"./chunk-esnkk33h.js";import"./chunk-vppcvxzd.js";import"./chunk-cj5w17y3.js";import"./chunk-j73schtj.js";import"./chunk-n2dcjqbe.js";import{Sa as O}from"./chunk-10js1kwp.js";import"./chunk-yddnm9n2.js";import"./chunk-1e2phnbj.js";import"./chunk-37rethcy.js";import{wb as H,xb as T}from"./chunk-7ycmx7c2.js";import"./chunk-set7v1rf.js";import"./chunk-j2ag7hh6.js";import bq from"yargs";import{hideBin as Uq}from"yargs/helpers";import{z as b}from"zod";import{z as Q}from"zod";var L=1,V=Q.object({event_version:Q.literal(L)}),i=V.extend({type:Q.literal("content_delta"),delta:Q.string()}),n=V.extend({type:Q.literal("thinking_delta"),delta:Q.string()}),r=V.extend({type:Q.literal("thinking"),content:Q.string()}),s=V.extend({type:Q.literal("stream_end")}),o=V.extend({type:Q.literal("content"),content:Q.string()}),a=V.extend({type:Q.literal("tool_start"),tool_name:Q.string(),summary:Q.string(),target:Q.string().optional(),tool_kind:Q.enum(["readonly","write","execute"]).optional()}),t=V.extend({type:Q.literal("tool_result"),tool_name:Q.string(),summary:Q.string(),target:Q.string().optional(),tool_kind:Q.enum(["readonly","write","execute"]).optional()}),e=V.extend({type:Q.literal("phase"),phase:Q.enum(["turn","searching","inspecting","target_hit","executing","completed"]),status:Q.enum(["ongoing","hit","done"]),message:Q.string(),turn:Q.number().optional(),tool_name:Q.string().optional(),target:Q.string().optional()}),qq=V.extend({type:Q.literal("tool_detail"),tool_name:Q.string(),detail:Q.string()}),Gq=V.extend({type:Q.literal("task_update"),tasks:Q.array(x)}),Qq=V.extend({type:Q.literal("token_usage"),input_tokens:Q.number(),output_tokens:Q.number(),total_tokens:Q.number(),max_context_tokens:Q.number()}),Xq=V.extend({type:Q.literal("compacting"),state:Q.enum(["started","completed"])}),Yq=V.extend({type:Q.literal("turn_limit"),turns_count:Q.number(),action:Q.literal("continue")}),Zq=V.extend({type:Q.literal("output"),content:Q.string(),exit_code:Q.number()}),$q=V.extend({type:Q.literal("error"),message:Q.string()}),Nq=Q.discriminatedUnion("type",[i,n,r,s,o,a,t,e,qq,Gq,Qq,Xq,Yq,Zq,$q]);function N(G,X){return{event_version:L,type:G,...X}}var Kq=b.enum(["text","jsonl"]),Aq=b.object({headless:b.boolean().optional(),message:b.string().optional(),_:b.array(b.union([b.string(),b.number()])).optional(),model:b.string().optional(),systemPrompt:b.string().optional(),appendSystemPrompt:b.string().optional(),maxTurns:b.number().int().refine((G)=>G===-1||G>0,{message:"must be -1 or a positive integer"}).optional(),permissionMode:b.nativeEnum(H).optional(),mcpConfig:b.array(b.string()).optional(),strictMcpConfig:b.boolean().optional(),sessionId:b.string().optional(),allowedTools:b.array(b.string()).optional(),disallowedTools:b.array(b.string()).optional(),continue:b.boolean().optional(),resume:b.union([b.string(),b.boolean()]).optional(),outputFormat:Kq.optional()});class d{openedThinking=!1;wroteAssistantContent=!1;markAssistantContent(){this.wroteAssistantContent=!0}setThinkingOpened(G){this.openedThinking=G}hasOpenThinking(){return this.openedThinking}completeStream(){let G={openedThinking:this.openedThinking,wroteAssistantContent:this.wroteAssistantContent};return this.openedThinking=!1,this.wroteAssistantContent=!1,G}}function Rq(G){return G.issues.map((X)=>`${X.path.join(".")||"options"}: ${X.message}`).join("; ")}function Vq(G){let X=Aq.safeParse(G);if(!X.success)throw Error(`Invalid headless options: ${Rq(X.error)}`);return X.data}function _q(G){return G.command("* [message]","Run full agent loop without Ink UI and print events to the terminal",(X)=>X.positional("message",{describe:"Message to process",type:"string"}).option("headless",{type:"boolean",describe:"Run full agent loop without Ink UI and print events to the terminal"}).option("model",{describe:"Model ID for this run",type:"string"}).option("system-prompt",{describe:"Replace the default system prompt",type:"string"}).option("append-system-prompt",{describe:"Append a system prompt to the default system prompt",type:"string"}).option("max-turns",{alias:["maxTurns"],describe:"Maximum conversation turns (-1: unlimited, N>0: limit to N turns)",type:"number"}).option("output-format",{alias:["outputFormat"],choices:["text","jsonl"],describe:"Headless output format",type:"string"}),async(X)=>{if(!X.headless)return;let Y=await Bq(X);process.exit(Y)})}function _(G,X=""){G.write(`${X}
1
+ import{p as z,q as g,r as v,s as p}from"./chunk-tjmdp193.js";import{t as E}from"./chunk-hqyfpgdr.js";import{v as S,w as h,x as c}from"./chunk-2be9zcm4.js";import{G as w,I as F,J as y,L as x,M as C}from"./chunk-x4ta13s0.js";import"./chunk-365tx34d.js";import"./chunk-esnkk33h.js";import"./chunk-5gxn6wrh.js";import"./chunk-cj5w17y3.js";import"./chunk-j73schtj.js";import"./chunk-n2dcjqbe.js";import{Sa as O}from"./chunk-5yffdaq2.js";import"./chunk-yddnm9n2.js";import"./chunk-1e2phnbj.js";import"./chunk-37rethcy.js";import{wb as H,xb as T}from"./chunk-7ycmx7c2.js";import"./chunk-set7v1rf.js";import"./chunk-j2ag7hh6.js";import bq from"yargs";import{hideBin as Uq}from"yargs/helpers";import{z as b}from"zod";import{z as Q}from"zod";var L=1,V=Q.object({event_version:Q.literal(L)}),i=V.extend({type:Q.literal("content_delta"),delta:Q.string()}),n=V.extend({type:Q.literal("thinking_delta"),delta:Q.string()}),r=V.extend({type:Q.literal("thinking"),content:Q.string()}),s=V.extend({type:Q.literal("stream_end")}),o=V.extend({type:Q.literal("content"),content:Q.string()}),a=V.extend({type:Q.literal("tool_start"),tool_name:Q.string(),summary:Q.string(),target:Q.string().optional(),tool_kind:Q.enum(["readonly","write","execute"]).optional()}),t=V.extend({type:Q.literal("tool_result"),tool_name:Q.string(),summary:Q.string(),target:Q.string().optional(),tool_kind:Q.enum(["readonly","write","execute"]).optional()}),e=V.extend({type:Q.literal("phase"),phase:Q.enum(["turn","searching","inspecting","target_hit","executing","completed"]),status:Q.enum(["ongoing","hit","done"]),message:Q.string(),turn:Q.number().optional(),tool_name:Q.string().optional(),target:Q.string().optional()}),qq=V.extend({type:Q.literal("tool_detail"),tool_name:Q.string(),detail:Q.string()}),Gq=V.extend({type:Q.literal("task_update"),tasks:Q.array(x)}),Qq=V.extend({type:Q.literal("token_usage"),input_tokens:Q.number(),output_tokens:Q.number(),total_tokens:Q.number(),max_context_tokens:Q.number()}),Xq=V.extend({type:Q.literal("compacting"),state:Q.enum(["started","completed"])}),Yq=V.extend({type:Q.literal("turn_limit"),turns_count:Q.number(),action:Q.literal("continue")}),Zq=V.extend({type:Q.literal("output"),content:Q.string(),exit_code:Q.number()}),$q=V.extend({type:Q.literal("error"),message:Q.string()}),Nq=Q.discriminatedUnion("type",[i,n,r,s,o,a,t,e,qq,Gq,Qq,Xq,Yq,Zq,$q]);function N(G,X){return{event_version:L,type:G,...X}}var Kq=b.enum(["text","jsonl"]),Aq=b.object({headless:b.boolean().optional(),message:b.string().optional(),_:b.array(b.union([b.string(),b.number()])).optional(),model:b.string().optional(),systemPrompt:b.string().optional(),appendSystemPrompt:b.string().optional(),maxTurns:b.number().int().refine((G)=>G===-1||G>0,{message:"must be -1 or a positive integer"}).optional(),permissionMode:b.nativeEnum(H).optional(),mcpConfig:b.array(b.string()).optional(),strictMcpConfig:b.boolean().optional(),sessionId:b.string().optional(),allowedTools:b.array(b.string()).optional(),disallowedTools:b.array(b.string()).optional(),continue:b.boolean().optional(),resume:b.union([b.string(),b.boolean()]).optional(),outputFormat:Kq.optional()});class d{openedThinking=!1;wroteAssistantContent=!1;markAssistantContent(){this.wroteAssistantContent=!0}setThinkingOpened(G){this.openedThinking=G}hasOpenThinking(){return this.openedThinking}completeStream(){let G={openedThinking:this.openedThinking,wroteAssistantContent:this.wroteAssistantContent};return this.openedThinking=!1,this.wroteAssistantContent=!1,G}}function Rq(G){return G.issues.map((X)=>`${X.path.join(".")||"options"}: ${X.message}`).join("; ")}function Vq(G){let X=Aq.safeParse(G);if(!X.success)throw Error(`Invalid headless options: ${Rq(X.error)}`);return X.data}function _q(G){return G.command("* [message]","Run full agent loop without Ink UI and print events to the terminal",(X)=>X.positional("message",{describe:"Message to process",type:"string"}).option("headless",{type:"boolean",describe:"Run full agent loop without Ink UI and print events to the terminal"}).option("model",{describe:"Model ID for this run",type:"string"}).option("system-prompt",{describe:"Replace the default system prompt",type:"string"}).option("append-system-prompt",{describe:"Append a system prompt to the default system prompt",type:"string"}).option("max-turns",{alias:["maxTurns"],describe:"Maximum conversation turns (-1: unlimited, N>0: limit to N turns)",type:"number"}).option("output-format",{alias:["outputFormat"],choices:["text","jsonl"],describe:"Headless output format",type:"string"}),async(X)=>{if(!X.headless)return;let Y=await Bq(X);process.exit(Y)})}function _(G,X=""){G.write(`${X}
2
2
  `)}function Dq(G){return`[task] [${G.status}] ${G.subject}`}function Mq(){return{requestConfirmation:async(G)=>({approved:!0,reason:"headless-auto-approved",scope:"session"})}}function jq(G){if(!(G instanceof Error))return"Unknown error";let q=G.lastError??G;if(q.responseBody)try{let A=JSON.parse(q.responseBody)?.error?.message;if(A)return q.statusCode?`${A} (HTTP ${q.statusCode})`:A}catch{}let Z=G.message.match(/Last error:\s*(.+)$/);if(Z)return Z[1];return G.message}function fq(G){return G==="jsonl"?"jsonl":"text"}function W(G,X){let Y=(...q)=>{for(let Z of q){let U=X[Z];if(typeof U==="string"&&U.trim()!=="")return U}return};switch(G){case"Read":case"Edit":case"Write":case"UndoEdit":return Y("file_path");case"NotebookEdit":return Y("notebook_path");case"Grep":return Y("path","pattern");case"Glob":return Y("pattern");case"WebFetch":return Y("url");case"WebSearch":return Y("query");case"Bash":return Y("description","command");case"Task":return Y("description");case"LSP":return Y("filePath","operation");default:return}}function Pq(G,X,Y,q){let Z=new Set(["Glob","Grep","WebSearch","LS"]),U=new Set(["Read","WebFetch"]);if(new Set(["Edit","Write","NotebookEdit","Bash","LSP","UndoEdit"]).has(G)&&!q.targetLocked)return{phase:"target_hit",status:"hit",message:`Target locked: ${X}`,shouldLockTarget:!0};if(q.targetLocked)return{phase:"executing",status:"hit",message:Y?`Working within target: ${X}`:`Executing: ${X}`,shouldLockTarget:!1};if(Z.has(G))return{phase:"searching",status:"ongoing",message:`Still searching: ${X}`,shouldLockTarget:!1};if(U.has(G))return{phase:"inspecting",status:"ongoing",message:`Inspecting candidate: ${X}`,shouldLockTarget:!1};return{phase:"executing",status:q.targetLocked?"hit":"ongoing",message:`Executing: ${X}`,shouldLockTarget:!1}}function k(G,X){let Y=(q,Z)=>{G.stdout.write(`${JSON.stringify(N(q,Z))}
3
3
  `)};return{contentDelta(q){if(X==="jsonl"){Y("content_delta",{delta:q});return}G.stdout.write(q)},thinkingDelta(q,Z){if(X==="jsonl")return Y("thinking_delta",{delta:q}),Z;if(!Z)G.stderr.write("[thinking] ");return G.stderr.write(q),!0},thinking(q){if(X==="jsonl"){Y("thinking",{content:q});return}_(G.stderr,`[thinking] ${q}`)},streamEnd(q,Z){if(X==="jsonl"){Y("stream_end",{});return}if(Z)G.stderr.write(`
4
4
  `);if(q)G.stdout.write(`
@@ -1 +1 @@
1
- import{aa as a,ba as b,ca as c,da as d,ea as e,fa as f}from"./chunk-vppcvxzd.js";import"./chunk-j2ag7hh6.js";export{b as getVersion,c as getPackageName,a as getPackageInfo,e as getFormattedVersion,d as getDescription,f as getCopyright};
1
+ import{aa as a,ba as b,ca as c,da as d,ea as e,fa as f}from"./chunk-5gxn6wrh.js";import"./chunk-j2ag7hh6.js";export{b as getVersion,c as getPackageName,a as getPackageInfo,e as getFormattedVersion,d as getDescription,f as getCopyright};
@@ -1 +1 @@
1
- import{a as y,b as A,c as C,d as D}from"./chunk-m0gqzy3r.js";import"./chunk-q5yn875m.js";import"./chunk-tjzyqsnc.js";import"./chunk-sdfra3bn.js";import"./chunk-esnkk33h.js";import"./chunk-vppcvxzd.js";import"./chunk-cj5w17y3.js";import{Aa as q}from"./chunk-j73schtj.js";import"./chunk-n2dcjqbe.js";import"./chunk-10js1kwp.js";import"./chunk-yddnm9n2.js";import"./chunk-1e2phnbj.js";import"./chunk-37rethcy.js";import"./chunk-7ycmx7c2.js";import"./chunk-set7v1rf.js";import"./chunk-j2ag7hh6.js";import H from"chalk";var R={command:"serve",describe:"Start a headless Blade server (no browser)",builder:y,handler:async(E)=>{let f=A(E);if(await q(),!process.env.BLADE_SERVER_PASSWORD)console.log(H.yellow("Warning: BLADE_SERVER_PASSWORD is not set; server is unsecured."));let b=await D.listenAsync(f);if(console.log(`Blade server listening on http://${b.hostname}:${b.port}`),f.hostname==="0.0.0.0"){let F=C();for(let G of F)console.log(` Network: http://${G}:${b.port}`)}await new Promise(()=>{}),await b.stop()}};export{R as serveCommand};
1
+ import{a as y,b as A,c as C,d as D}from"./chunk-zbcbh3gs.js";import"./chunk-q5yn875m.js";import"./chunk-x4ta13s0.js";import"./chunk-365tx34d.js";import"./chunk-esnkk33h.js";import"./chunk-5gxn6wrh.js";import"./chunk-cj5w17y3.js";import{Aa as q}from"./chunk-j73schtj.js";import"./chunk-n2dcjqbe.js";import"./chunk-5yffdaq2.js";import"./chunk-yddnm9n2.js";import"./chunk-1e2phnbj.js";import"./chunk-37rethcy.js";import"./chunk-7ycmx7c2.js";import"./chunk-set7v1rf.js";import"./chunk-j2ag7hh6.js";import H from"chalk";var R={command:"serve",describe:"Start a headless Blade server (no browser)",builder:y,handler:async(E)=>{let f=A(E);if(await q(),!process.env.BLADE_SERVER_PASSWORD)console.log(H.yellow("Warning: BLADE_SERVER_PASSWORD is not set; server is unsecured."));let b=await D.listenAsync(f);if(console.log(`Blade server listening on http://${b.hostname}:${b.port}`),f.hostname==="0.0.0.0"){let F=C();for(let G of F)console.log(` Network: http://${G}:${b.port}`)}await new Promise(()=>{}),await b.stop()}};export{R as serveCommand};
@@ -1,4 +1,4 @@
1
- import{p as _,q as x,r as E,s as N}from"./chunk-wc4agkf7.js";import{t as A}from"./chunk-pcky0ctg.js";import{v as B,w as D,x as L}from"./chunk-2be9zcm4.js";import{G as $,M as b}from"./chunk-tjzyqsnc.js";import"./chunk-sdfra3bn.js";import"./chunk-esnkk33h.js";import"./chunk-vppcvxzd.js";import"./chunk-cj5w17y3.js";import"./chunk-j73schtj.js";import"./chunk-n2dcjqbe.js";import{Sa as Z}from"./chunk-10js1kwp.js";import"./chunk-yddnm9n2.js";import"./chunk-1e2phnbj.js";import"./chunk-37rethcy.js";import{wb as X,xb as Y}from"./chunk-7ycmx7c2.js";import"./chunk-set7v1rf.js";import"./chunk-j2ag7hh6.js";import f from"yargs";import{hideBin as h}from"yargs/helpers";var R=new Set(Object.values(X));function W(k){if(k&&R.has(k))return k;return}function w(k){return k.command("* [message]","Print response and exit (useful for pipes)",(F)=>F.positional("message",{describe:"Message to process",type:"string"}).option("p",{alias:"print",describe:"Print response and exit (useful for pipes)",type:"boolean"}).option("output-format",{describe:'Output format: "text", "json", "stream-json"',type:"string",default:"text"}).option("include-partial-messages",{describe:"Include partial message chunks as they arrive",type:"boolean"}).option("input-format",{describe:'Input format: "text", "stream-json"',type:"string",default:"text"}).option("model",{describe:"Model for the current session",type:"string"}).option("append-system-prompt",{describe:"Append a system prompt to the default system prompt",type:"string"}).option("system-prompt",{describe:"Replace the default system prompt",type:"string"}).option("max-turns",{alias:["maxTurns"],describe:"Maximum conversation turns (-1: unlimited, N>0: limit to N turns)",type:"number"}),async(F)=>{if(!F.p)return;let q=await M(F);process.exit(q)})}async function M(k,F=process){let q;try{await _();let J=await x({message:k.message,_:k._,defaultMessage:"Hello"}),G=await E(J);if(G.mode==="output"){if(G.content)F.stdout.write(`${G.content}
1
+ import{p as _,q as x,r as E,s as N}from"./chunk-tjmdp193.js";import{t as A}from"./chunk-hqyfpgdr.js";import{v as B,w as D,x as L}from"./chunk-2be9zcm4.js";import{G as $,M as b}from"./chunk-x4ta13s0.js";import"./chunk-365tx34d.js";import"./chunk-esnkk33h.js";import"./chunk-5gxn6wrh.js";import"./chunk-cj5w17y3.js";import"./chunk-j73schtj.js";import"./chunk-n2dcjqbe.js";import{Sa as Z}from"./chunk-5yffdaq2.js";import"./chunk-yddnm9n2.js";import"./chunk-1e2phnbj.js";import"./chunk-37rethcy.js";import{wb as X,xb as Y}from"./chunk-7ycmx7c2.js";import"./chunk-set7v1rf.js";import"./chunk-j2ag7hh6.js";import f from"yargs";import{hideBin as h}from"yargs/helpers";var R=new Set(Object.values(X));function W(k){if(k&&R.has(k))return k;return}function w(k){return k.command("* [message]","Print response and exit (useful for pipes)",(F)=>F.positional("message",{describe:"Message to process",type:"string"}).option("p",{alias:"print",describe:"Print response and exit (useful for pipes)",type:"boolean"}).option("output-format",{describe:'Output format: "text", "json", "stream-json"',type:"string",default:"text"}).option("include-partial-messages",{describe:"Include partial message chunks as they arrive",type:"boolean"}).option("input-format",{describe:'Input format: "text", "stream-json"',type:"string",default:"text"}).option("model",{describe:"Model for the current session",type:"string"}).option("append-system-prompt",{describe:"Append a system prompt to the default system prompt",type:"string"}).option("system-prompt",{describe:"Replace the default system prompt",type:"string"}).option("max-turns",{alias:["maxTurns"],describe:"Maximum conversation turns (-1: unlimited, N>0: limit to N turns)",type:"number"}),async(F)=>{if(!F.p)return;let q=await M(F);process.exit(q)})}async function M(k,F=process){let q;try{await _();let J=await x({message:k.message,_:k._,defaultMessage:"Hello"}),G=await E(J);if(G.mode==="output"){if(G.content)F.stdout.write(`${G.content}
2
2
  `);return G.exitCode??0}let Q=G.content,{sessionId:K,messages:T}=await N({sessionId:k.sessionId,continue:k.continue,resume:k.resume,fallbackSessionPrefix:"print"});q=await $.create({sessionId:K,modelId:k.model,mcpConfig:k.mcpConfig,strictMcpConfig:k.strictMcpConfig});let U=await b.createWithRuntime(q,{sessionId:K,systemPrompt:k.systemPrompt,appendSystemPrompt:k.appendSystemPrompt,maxTurns:k.maxTurns,modelId:k.model,permissionMode:W(k.permissionMode),toolWhitelist:k.allowedTools,toolBlacklist:k.disallowedTools,mcpConfig:k.mcpConfig,strictMcpConfig:k.strictMcpConfig}),H=(await Z(U.chatStream(Q,{messages:[...T],userId:"cli-user",sessionId:K,workspaceRoot:Y(),permissionMode:W(k.permissionMode)}))).finalMessage||"";if(k.outputFormat==="json")F.stdout.write(`${JSON.stringify({response:H,input:Q,model:k.model,timestamp:new Date().toISOString()},null,2)}
3
3
  `);else if(k.outputFormat==="stream-json")F.stdout.write(`${JSON.stringify({type:"response",content:H})}
4
4
  `);else F.stdout.write(`${H}
@@ -1,4 +1,4 @@
1
- import{e as E2,f as h2}from"./chunk-q5yn875m.js";import{h as A4,i as v4,j as R4}from"./chunk-qwfywxs2.js";import{l as D$,m as k4,o as o1}from"./chunk-mb7hm0ga.js";import{B as r8,C as e6,D as f4,E as X8,F as e1,G as h6,I as f6,J as D6,M as f$,N as M8,O as D4,P as _1,Q as wJ,R as bJ,S as M6,T as V4,U as C6,W as KJ,y as UJ}from"./chunk-tjzyqsnc.js";import{Y as S4}from"./chunk-sdfra3bn.js";import"./chunk-esnkk33h.js";import{fa as I2}from"./chunk-vppcvxzd.js";import{ga as S8}from"./chunk-cj5w17y3.js";import{Aa as x6,Ga as p0,ha as O$,ia as m0,ja as E1,ka as vQ,la as i1,ma as T$,na as iJ,oa as mQ,pa as D2,qa as nJ,sa as K4,ua as iQ,va as H1,wa as C4,xa as w1,ya as b4}from"./chunk-j73schtj.js";import{Ha as I4,Ja as M4}from"./chunk-n2dcjqbe.js";import{Na as G4,Oa as T4,Sa as d6}from"./chunk-10js1kwp.js";import"./chunk-yddnm9n2.js";import{mb as yQ,nb as L1}from"./chunk-1e2phnbj.js";import{qb as o2}from"./chunk-37rethcy.js";import{ub as AJ,xb as A0}from"./chunk-7ycmx7c2.js";import{Bb as j1,yb as P4}from"./chunk-set7v1rf.js";import{Db as s$}from"./chunk-j2ag7hh6.js";import{useMemoizedFn as dQ}from"ahooks";import{useEffect as c5,useState as lQ}from"react";import{useMemoizedFn as r0}from"ahooks";import{Box as l1}from"ink";import{useEffect as r1,useRef as T8}from"react";import{useShallow as nQ}from"zustand/react/shallow";import{useStore as c4}from"zustand";function Q0($){return c4(iQ,$)}var u4=[],tQ=()=>Q0(($)=>$.session.sessionId),sQ=()=>Q0(($)=>$.session.messages),eQ=()=>Q0(($)=>$.session.clearCount),$6=()=>Q0(($)=>$.session.isCompacting),Q6=()=>Q0(($)=>$.session.tokenUsage.estimatedCostUsd),f1=()=>Q0(($)=>$.session.actions),J6=()=>Q0(($)=>{let{inputTokens:Q,maxContextTokens:J}=$.session.tokenUsage;if(J<=0)return 100;let Y=Math.max(0,100-Q/J*100);return Math.round(Y)}),Y6=()=>Q0(($)=>$.app.initializationStatus),Z6=()=>Q0(($)=>$.app.initializationError),a$=()=>Q0(($)=>$.app.activeModal),X6=()=>Q0(($)=>$.app.tasks),q6=()=>Q0(($)=>$.app.modelEditorTarget),G6=()=>Q0(($)=>$.app.sessionSelectorData),U6=()=>Q0(($)=>$.app.awaitingSecondCtrlC),D1=()=>Q0(($)=>$.app.actions),o$=()=>Q0(($)=>$.app.initializationStatus==="ready"),K6=()=>Q0(($)=>$.app.tasks.length>0),_$=()=>Q0(($)=>$.config.config?.permissionMode||"default"),O6=()=>Q0(($)=>$.config.config?.models??u4),i$=()=>Q0(($)=>{let Q=$.config.config;if(!Q)return;let J=Q.currentModelId;return Q.models.find((Z)=>Z.id===J)??Q.models[0]}),z6=()=>Q0(($)=>$.config.config?.currentModelId),_0=()=>Q0(($)=>{return m0.getTheme()}),_6=()=>Q0(($)=>$.config.config?.theme??"default"),i0=()=>Q0(($)=>$.focus.currentFocus),N6=()=>Q0(($)=>$.focus.actions),V1=()=>Q0(($)=>$.command.isProcessing),F6=()=>Q0(($)=>$.command.actions),W6=()=>Q0(($)=>$.command.pendingCommands),n$=()=>Q0(($)=>$.app.thinkingModeEnabled),H6=()=>Q0(($)=>$.session.currentThinkingContent),L6=()=>Q0(($)=>$.session.thinkingExpanded),w6=()=>Q0(($)=>$.session.currentStreamingMessageId),b6=()=>Q0(nQ(($)=>({lines:$.session.currentStreamingLines,tail:$.session.currentStreamingTail,lineCount:$.session.currentStreamingLineCount,version:$.session.currentStreamingVersion}))),B6=()=>Q0(($)=>$.session.finalizingStreamingMessageId),A6=()=>Q0(($)=>$.session.historyExpanded),v6=()=>Q0(($)=>$.session.expandedMessageCount),R6=()=>Q0(nQ(($)=>{let Q=$.spec.currentSpec;if(!Q)return{phase:null,completed:0,total:0};let J=Q.tasks??[],Y=J.filter((Z)=>Z.status==="completed").length;return{phase:Q.phase,completed:Y,total:J.length}}));import{useMemoizedFn as u8}from"ahooks";import{useEffect as c6,useRef as Y9}from"react";function x4($){if(!($ instanceof Error))return"未知错误";let Y=$.lastError??$;if(Y.responseBody)try{let X=JSON.parse(Y.responseBody)?.error?.message;if(X){let G=Y.statusCode?` (HTTP ${Y.statusCode})`:"";return`${X}${G}`}}catch{}let Z=$.message.match(/Last error:\s*(.+)$/);if(Z)return Z[1];return $.message}function d4($){if(!($ instanceof Error))return!1;return $.name==="AbortError"||$.message.includes("aborted")}function l4($){if(!($ instanceof Error))return!1;let Q=$.message;return Q.includes("can only concatenate str")||Q.includes("image_url")||Q.includes("multimodal")||Q.includes("vision")||Q.includes("does not support images")}function m8($){let Q=d4($),J=l4($),Y;if(J)Y="当前模型不支持图片理解功能。请切换到支持视觉能力的模型(如 Claude 4.5、GPT-5.2、Gemini 3 Pro、Qwen3-VL-Plus 等)后重试。";else Y=x4($);return{displayMessage:Y,isAbort:Q,isVisionNotSupported:J}}function y6($){let{text:Q,images:J,parts:Y}=$;if(J.length===0)return Q;let Z=[];for(let q of Y)if(q.type==="text")Z.push({type:"text",text:q.text});else Z.push({type:"image_url",image_url:{url:`data:${q.mimeType};base64,${q.base64}`}});return Z}function P6($){return{role:$.role,content:$.content}}function I6($){if(!$.restoredContextMessages||$.restoredVisibleMessageCount<=0)return $.messages.map(P6);let Q=$.messages.slice($.restoredVisibleMessageCount).map(P6);return[...$.restoredContextMessages,...Q]}function r4($){return typeof $==="object"&&$!==null&&$.action==="invoke_skill"&&typeof $.skillName==="string"}function a4($){return typeof $==="object"&&$!==null&&$.action==="invoke_custom_command"&&typeof $.commandName==="string"&&typeof $.processedContent==="string"}function o4($){return typeof $==="object"&&$!==null&&$.action==="invoke_plugin_command"&&typeof $.commandName==="string"&&typeof $.processedContent==="string"}function i4($){return typeof $==="object"&&$!==null&&$.action==="invoke_once_model"&&typeof $.modelId==="string"&&typeof $.prompt==="string"}function n4($,Q,J,Y){switch($){case"show_theme_selector":return J.setActiveModal("themeSelector"),!0;case"show_model_selector":return J.setActiveModal("modelSelector"),!0;case"show_model_add_wizard":return J.setActiveModal("modelAddWizard"),!0;case"show_permissions_manager":return J.setActiveModal("permissionsManager"),!0;case"show_agents_manager":return J.setActiveModal("agentsManager"),!0;case"show_skills_manager":return J.setActiveModal("skillsManager"),!0;case"show_hooks_manager":return J.setActiveModal("hooksManager"),!0;case"show_plugins_manager":return J.setActiveModal("pluginsManager"),!0;case"show_agent_creation_wizard":return J.setActiveModal("agentCreationWizard"),!0;case"show_session_selector":{let Z=Q?.sessions;return J.showSessionSelector(Z),!0}case"clear_screen":return Y.clearMessages(),Y.setError(null),Y.resetTokenUsage(),J.setTasks([]),!0;case"compact_completed":case"compact_fallback":return Y.resetTokenUsage(),!0;case"exit_application":return o1(0),!0;default:return!1}}async function k6($,Q,J,Y){let{text:Z}=$;if(!M6(Z))return{type:"not_slash"};let q={cwd:A0(),signal:Y},X=await C6(Z,q);if(X.message){if(n4(X.message,X.data,Q,J))return{type:"handled",commandResult:{success:!0}}}if(r4(X.data)){let{skillName:K,skillArgs:U}=X.data,F=U?`Please use the "${K}" skill to help me with: ${U}`:`Please use the "${K}" skill.`;return J.addUserMessage(F),{type:"continue_as_agent",result:{userDisplayMessage:F,agentInput:{displayText:F,text:F,images:[],parts:[{type:"text",text:F}]},userMessageAlreadyAdded:!0}}}if(a4(X.data)){let{commandName:K,processedContent:U}=X.data;J.addUserMessage(Z);let F=`# Custom Command: /${K}
1
+ import{e as E2,f as h2}from"./chunk-q5yn875m.js";import{h as A4,i as v4,j as R4}from"./chunk-qwfywxs2.js";import{l as D$,m as k4,o as o1}from"./chunk-mb7hm0ga.js";import{B as r8,C as e6,D as f4,E as X8,F as e1,G as h6,I as f6,J as D6,M as f$,N as M8,O as D4,P as _1,Q as wJ,R as bJ,S as M6,T as V4,U as C6,W as KJ,y as UJ}from"./chunk-x4ta13s0.js";import{Y as S4}from"./chunk-365tx34d.js";import"./chunk-esnkk33h.js";import{fa as I2}from"./chunk-5gxn6wrh.js";import{ga as S8}from"./chunk-cj5w17y3.js";import{Aa as x6,Ga as p0,ha as O$,ia as m0,ja as E1,ka as vQ,la as i1,ma as T$,na as iJ,oa as mQ,pa as D2,qa as nJ,sa as K4,ua as iQ,va as H1,wa as C4,xa as w1,ya as b4}from"./chunk-j73schtj.js";import{Ha as I4,Ja as M4}from"./chunk-n2dcjqbe.js";import{Na as G4,Oa as T4,Sa as d6}from"./chunk-5yffdaq2.js";import"./chunk-yddnm9n2.js";import{mb as yQ,nb as L1}from"./chunk-1e2phnbj.js";import{qb as o2}from"./chunk-37rethcy.js";import{ub as AJ,xb as A0}from"./chunk-7ycmx7c2.js";import{Bb as j1,yb as P4}from"./chunk-set7v1rf.js";import{Db as s$}from"./chunk-j2ag7hh6.js";import{useMemoizedFn as dQ}from"ahooks";import{useEffect as c5,useState as lQ}from"react";import{useMemoizedFn as r0}from"ahooks";import{Box as l1}from"ink";import{useEffect as r1,useRef as T8}from"react";import{useShallow as nQ}from"zustand/react/shallow";import{useStore as c4}from"zustand";function Q0($){return c4(iQ,$)}var u4=[],tQ=()=>Q0(($)=>$.session.sessionId),sQ=()=>Q0(($)=>$.session.messages),eQ=()=>Q0(($)=>$.session.clearCount),$6=()=>Q0(($)=>$.session.isCompacting),Q6=()=>Q0(($)=>$.session.tokenUsage.estimatedCostUsd),f1=()=>Q0(($)=>$.session.actions),J6=()=>Q0(($)=>{let{inputTokens:Q,maxContextTokens:J}=$.session.tokenUsage;if(J<=0)return 100;let Y=Math.max(0,100-Q/J*100);return Math.round(Y)}),Y6=()=>Q0(($)=>$.app.initializationStatus),Z6=()=>Q0(($)=>$.app.initializationError),a$=()=>Q0(($)=>$.app.activeModal),X6=()=>Q0(($)=>$.app.tasks),q6=()=>Q0(($)=>$.app.modelEditorTarget),G6=()=>Q0(($)=>$.app.sessionSelectorData),U6=()=>Q0(($)=>$.app.awaitingSecondCtrlC),D1=()=>Q0(($)=>$.app.actions),o$=()=>Q0(($)=>$.app.initializationStatus==="ready"),K6=()=>Q0(($)=>$.app.tasks.length>0),_$=()=>Q0(($)=>$.config.config?.permissionMode||"default"),O6=()=>Q0(($)=>$.config.config?.models??u4),i$=()=>Q0(($)=>{let Q=$.config.config;if(!Q)return;let J=Q.currentModelId;return Q.models.find((Z)=>Z.id===J)??Q.models[0]}),z6=()=>Q0(($)=>$.config.config?.currentModelId),_0=()=>Q0(($)=>{return m0.getTheme()}),_6=()=>Q0(($)=>$.config.config?.theme??"default"),i0=()=>Q0(($)=>$.focus.currentFocus),N6=()=>Q0(($)=>$.focus.actions),V1=()=>Q0(($)=>$.command.isProcessing),F6=()=>Q0(($)=>$.command.actions),W6=()=>Q0(($)=>$.command.pendingCommands),n$=()=>Q0(($)=>$.app.thinkingModeEnabled),H6=()=>Q0(($)=>$.session.currentThinkingContent),L6=()=>Q0(($)=>$.session.thinkingExpanded),w6=()=>Q0(($)=>$.session.currentStreamingMessageId),b6=()=>Q0(nQ(($)=>({lines:$.session.currentStreamingLines,tail:$.session.currentStreamingTail,lineCount:$.session.currentStreamingLineCount,version:$.session.currentStreamingVersion}))),B6=()=>Q0(($)=>$.session.finalizingStreamingMessageId),A6=()=>Q0(($)=>$.session.historyExpanded),v6=()=>Q0(($)=>$.session.expandedMessageCount),R6=()=>Q0(nQ(($)=>{let Q=$.spec.currentSpec;if(!Q)return{phase:null,completed:0,total:0};let J=Q.tasks??[],Y=J.filter((Z)=>Z.status==="completed").length;return{phase:Q.phase,completed:Y,total:J.length}}));import{useMemoizedFn as u8}from"ahooks";import{useEffect as c6,useRef as Y9}from"react";function x4($){if(!($ instanceof Error))return"未知错误";let Y=$.lastError??$;if(Y.responseBody)try{let X=JSON.parse(Y.responseBody)?.error?.message;if(X){let G=Y.statusCode?` (HTTP ${Y.statusCode})`:"";return`${X}${G}`}}catch{}let Z=$.message.match(/Last error:\s*(.+)$/);if(Z)return Z[1];return $.message}function d4($){if(!($ instanceof Error))return!1;return $.name==="AbortError"||$.message.includes("aborted")}function l4($){if(!($ instanceof Error))return!1;let Q=$.message;return Q.includes("can only concatenate str")||Q.includes("image_url")||Q.includes("multimodal")||Q.includes("vision")||Q.includes("does not support images")}function m8($){let Q=d4($),J=l4($),Y;if(J)Y="当前模型不支持图片理解功能。请切换到支持视觉能力的模型(如 Claude 4.5、GPT-5.2、Gemini 3 Pro、Qwen3-VL-Plus 等)后重试。";else Y=x4($);return{displayMessage:Y,isAbort:Q,isVisionNotSupported:J}}function y6($){let{text:Q,images:J,parts:Y}=$;if(J.length===0)return Q;let Z=[];for(let q of Y)if(q.type==="text")Z.push({type:"text",text:q.text});else Z.push({type:"image_url",image_url:{url:`data:${q.mimeType};base64,${q.base64}`}});return Z}function P6($){return{role:$.role,content:$.content}}function I6($){if(!$.restoredContextMessages||$.restoredVisibleMessageCount<=0)return $.messages.map(P6);let Q=$.messages.slice($.restoredVisibleMessageCount).map(P6);return[...$.restoredContextMessages,...Q]}function r4($){return typeof $==="object"&&$!==null&&$.action==="invoke_skill"&&typeof $.skillName==="string"}function a4($){return typeof $==="object"&&$!==null&&$.action==="invoke_custom_command"&&typeof $.commandName==="string"&&typeof $.processedContent==="string"}function o4($){return typeof $==="object"&&$!==null&&$.action==="invoke_plugin_command"&&typeof $.commandName==="string"&&typeof $.processedContent==="string"}function i4($){return typeof $==="object"&&$!==null&&$.action==="invoke_once_model"&&typeof $.modelId==="string"&&typeof $.prompt==="string"}function n4($,Q,J,Y){switch($){case"show_theme_selector":return J.setActiveModal("themeSelector"),!0;case"show_model_selector":return J.setActiveModal("modelSelector"),!0;case"show_model_add_wizard":return J.setActiveModal("modelAddWizard"),!0;case"show_permissions_manager":return J.setActiveModal("permissionsManager"),!0;case"show_agents_manager":return J.setActiveModal("agentsManager"),!0;case"show_skills_manager":return J.setActiveModal("skillsManager"),!0;case"show_hooks_manager":return J.setActiveModal("hooksManager"),!0;case"show_plugins_manager":return J.setActiveModal("pluginsManager"),!0;case"show_agent_creation_wizard":return J.setActiveModal("agentCreationWizard"),!0;case"show_session_selector":{let Z=Q?.sessions;return J.showSessionSelector(Z),!0}case"clear_screen":return Y.clearMessages(),Y.setError(null),Y.resetTokenUsage(),J.setTasks([]),!0;case"compact_completed":case"compact_fallback":return Y.resetTokenUsage(),!0;case"exit_application":return o1(0),!0;default:return!1}}async function k6($,Q,J,Y){let{text:Z}=$;if(!M6(Z))return{type:"not_slash"};let q={cwd:A0(),signal:Y},X=await C6(Z,q);if(X.message){if(n4(X.message,X.data,Q,J))return{type:"handled",commandResult:{success:!0}}}if(r4(X.data)){let{skillName:K,skillArgs:U}=X.data,F=U?`Please use the "${K}" skill to help me with: ${U}`:`Please use the "${K}" skill.`;return J.addUserMessage(F),{type:"continue_as_agent",result:{userDisplayMessage:F,agentInput:{displayText:F,text:F,images:[],parts:[{type:"text",text:F}]},userMessageAlreadyAdded:!0}}}if(a4(X.data)){let{commandName:K,processedContent:U}=X.data;J.addUserMessage(Z);let F=`# Custom Command: /${K}
2
2
 
3
3
  The user has invoked the custom command "/${K}". Follow the instructions below to complete the task.
4
4
 
@@ -1,2 +1,2 @@
1
- import{ba as d,da as h}from"./chunk-vppcvxzd.js";var q={debug:{alias:"d",type:"string",describe:'Enable debug mode with optional category filtering (e.g., "agent,ui" or "!chat,!loop")',group:"Debug Options:"},model:{type:"string",describe:"Override the current run model using a model config ID (TUI / print / headless)",group:"AI Options:"},print:{alias:"p",type:"boolean",describe:"Print response and exit (useful for pipes)",group:"Output Options:"},headless:{type:"boolean",describe:"Run full agent loop without Ink UI and print all events to the terminal",group:"Output Options:"},"output-format":{alias:["outputFormat"],type:"string",choices:["text","json","stream-json","jsonl"],default:"text",describe:"Output format: --print supports text|json|stream-json; --headless supports text|jsonl",group:"Output Options:"},"include-partial-messages":{alias:["includePartialMessages"],type:"boolean",describe:"Include partial message chunks as they arrive",group:"Output Options:"},"input-format":{alias:["inputFormat"],type:"string",choices:["text","stream-json"],default:"text",describe:"Input format",group:"Input Options:"},"replay-user-messages":{alias:["replayUserMessages"],type:"boolean",describe:"Re-emit user messages from stdin",group:"Input Options:"},"allowed-tools":{alias:["allowedTools"],type:"array",string:!0,describe:"Comma or space-separated list of tool names to allow",group:"Security Options:"},"disallowed-tools":{alias:["disallowedTools"],type:"array",string:!0,describe:"Comma or space-separated list of tool names to deny",group:"Security Options:"},"mcp-config":{alias:["mcpConfig"],type:"array",string:!0,describe:"Load MCP servers from JSON files or strings",group:"MCP Options:"},"system-prompt":{alias:["systemPrompt"],type:"string",describe:"System prompt to use for the session (replaces default)",group:"AI Options:"},"append-system-prompt":{alias:["appendSystemPrompt"],type:"string",describe:"Append a system prompt to the default system prompt",group:"AI Options:"},"max-turns":{alias:["maxTurns"],type:"number",describe:"Maximum conversation turns (-1: unlimited, 0: disable chat, N>0: limit to N turns)",group:"AI Options:",default:void 0},"permission-mode":{alias:["permissionMode"],type:"string",choices:["default","autoEdit","yolo","plan"],describe:"Permission mode (default: ask for non-read tools, autoEdit: auto-approve edits, yolo: auto-approve all, plan: reserved)",group:"Security Options:"},yolo:{type:"boolean",describe:"Auto-approve all tools (shortcut for --permission-mode=yolo)",group:"Security Options:"},continue:{alias:"c",type:"boolean",describe:"Continue the most recent conversation",group:"Session Options:"},resume:{alias:"r",describe:"Resume a conversation - provide a session ID or interactively select a conversation to resume",group:"Session Options:",coerce:(b)=>{if(b===void 0||b===!0||b==="")return"true";return String(b)}},"fork-session":{alias:["forkSession"],type:"boolean",describe:"Create a new session ID when resuming",group:"Session Options:"},settings:{type:"string",describe:"Path to a settings JSON file or JSON string",group:"Configuration:"},"add-dir":{alias:["addDir"],type:"array",string:!0,describe:"Additional directories to allow tool access to",group:"Security Options:"},ide:{type:"boolean",describe:"Automatically connect to IDE on startup",group:"Integration:"},acp:{type:"boolean",describe:"Run in ACP (Agent Client Protocol) mode for IDE integration",group:"Integration:"},"strict-mcp-config":{alias:["strictMcpConfig"],type:"boolean",describe:"Only use MCP servers from --mcp-config",group:"MCP Options:"},"session-id":{alias:["sessionId"],type:"string",describe:"Use a specific session ID for the conversation",group:"Session Options:"},agents:{type:"string",describe:"JSON object defining custom agents",group:"AI Options:"},"setting-sources":{alias:["settingSources"],type:"string",describe:"Comma-separated list of setting sources to load",group:"Configuration:"},"plugin-dir":{alias:["pluginDir"],type:"array",string:!0,describe:"Load plugins from specified directories",group:"Plugin Options:"}},w={scriptName:"blade",usage:"$0 [command] [options]",description:h(),version:d(),locale:"en",showHelpOnFail:!0,demandCommand:!1,recommendCommands:!0,strict:!1};
1
+ import{ba as d,da as h}from"./chunk-5gxn6wrh.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};
@@ -0,0 +1 @@
1
+ import{t as a,u as b}from"./chunk-hqyfpgdr.js";import"./chunk-5gxn6wrh.js";import"./chunk-j2ag7hh6.js";export{a as globalOptions,b as cliConfig};
@@ -1 +1 @@
1
- import{$a as l,Qa as a,Ra 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-10js1kwp.js";import"./chunk-yddnm9n2.js";import"./chunk-1e2phnbj.js";import"./chunk-37rethcy.js";import"./chunk-7ycmx7c2.js";import"./chunk-set7v1rf.js";import"./chunk-j2ag7hh6.js";export{g as saveUserMessage,i as saveToolUse,j as saveToolResult,k as saveCompaction,h as saveAssistantMessage,a as isRootSystemPrompt,l as handleTaskListUpdate,m as handleSkillActivation,n as extractModelSwitch,r as executeLoopGenerator,c as drainLoop,f as checkStopHook,d as checkOutputRecovery,e as checkIncompleteIntent,q as checkAndCompactInLoop,o as applyToolDomainEffects,p as StreamingToolExecutor,b as ConversationState};
1
+ import{$a as l,Qa as a,Ra 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-5yffdaq2.js";import"./chunk-yddnm9n2.js";import"./chunk-1e2phnbj.js";import"./chunk-37rethcy.js";import"./chunk-7ycmx7c2.js";import"./chunk-set7v1rf.js";import"./chunk-j2ag7hh6.js";export{g as saveUserMessage,i as saveToolUse,j as saveToolResult,k as saveCompaction,h as saveAssistantMessage,a as isRootSystemPrompt,l as handleTaskListUpdate,m as handleSkillActivation,n as extractModelSwitch,r as executeLoopGenerator,c as drainLoop,f as checkStopHook,d as checkOutputRecovery,e as checkIncompleteIntent,q as checkAndCompactInLoop,o as applyToolDomainEffects,p as StreamingToolExecutor,b as ConversationState};
@@ -1,4 +1,4 @@
1
- import{A as V,G as f,J as N,K as L,M as T,S as h,U as P,V as R}from"./chunk-tjzyqsnc.js";import{Y as M}from"./chunk-sdfra3bn.js";import"./chunk-esnkk33h.js";import"./chunk-vppcvxzd.js";import"./chunk-cj5w17y3.js";import{za as y}from"./chunk-j73schtj.js";import"./chunk-n2dcjqbe.js";import{Sa as O}from"./chunk-10js1kwp.js";import"./chunk-yddnm9n2.js";import"./chunk-1e2phnbj.js";import"./chunk-37rethcy.js";import{xb as D}from"./chunk-7ycmx7c2.js";import{Bb as W}from"./chunk-set7v1rf.js";import"./chunk-j2ag7hh6.js";import{Readable as K,Writable as k}from"node:stream";import*as _ from"@agentclientprotocol/sdk";import{PROTOCOL_VERSION as I}from"@agentclientprotocol/sdk";import{nanoid as S}from"nanoid";import{nanoid as x}from"nanoid";var X=W("Agent");class B{id;cwd;connection;clientCapabilities;agent=null;runtime=null;pendingPrompt=null;messages=[];mode="default";sessionApprovals=new Set;constructor(z,G,H,Q){this.id=z;this.cwd=G;this.connection=H;this.clientCapabilities=Q}async initialize(){X.debug(`[AcpSession ${this.id}] Initializing...`),V.initializeSession(this.connection,this.id,this.clientCapabilities,this.cwd),X.debug(`[AcpSession ${this.id}] ACP service context initialized`),this.runtime=await f.create({sessionId:this.id}),this.agent=await T.createWithRuntime(this.runtime,{sessionId:this.id}),X.debug(`[AcpSession ${this.id}] Agent created successfully`)}sendAvailableCommandsDelayed(){X.debug(`[AcpSession ${this.id}] Scheduling available commands update (500ms delay)`),setTimeout(()=>{this.sendAvailableCommands()},500)}async handleSlashCommand(z,G){try{X.debug(`[AcpSession ${this.id}] Executing slash command: ${z}`);let H={cwd:this.cwd,signal:G,acp:{sendMessage:(U)=>{this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:U}})},sendToolStart:(U,Y,q)=>{let Z=`tool_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,E=this.mapToolKind(q);this.sendUpdate({sessionUpdate:"tool_call",toolCallId:Z,status:"in_progress",title:`${U}`,content:[{type:"content",content:{type:"text",text:JSON.stringify(Y,null,2)}}],kind:E})},sendToolResult:(U,Y)=>{if(Y.summary)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:Y.summary}})}}},Q=await P(z,H),J=Q.content||Q.message;if(J)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:J}});if(Q.error)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[FAIL] ${Q.error}`}});return{stopReason:Q.success?"end_turn":"cancelled"}}catch(H){return X.error(`[AcpSession ${this.id}] Slash command error:`,H),this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[FAIL] 命令执行失败: ${H instanceof Error?H.message:"未知错误"}`}}),{stopReason:"cancelled"}}}async sendAvailableCommands(){try{let z=R(),G=["model","permissions","theme","config","exit","ide"],Q=z.filter((J)=>!G.includes(J.name)).map((J)=>{let U;if(J.usage){let Y=J.usage.replace(/^\/\w+\s*/,"").trim();if(Y)U=Y}if(J.aliases?.length){let Y=`Aliases: ${J.aliases.join(", ")}`;U=U?`${U} | ${Y}`:Y}return{name:J.name,description:J.description,input:U?{hint:U}:void 0}});X.info(`[AcpSession ${this.id}] Sending available commands: ${JSON.stringify(Q.map((J)=>J.name))}`),this.sendUpdate({sessionUpdate:"available_commands_update",availableCommands:Q}),X.info(`[AcpSession ${this.id}] Sent ${Q.length} available commands`)}catch(z){X.error(`[AcpSession ${this.id}] Failed to send available commands:`,z)}}async prompt(z){V.setCurrentSession(this.id),this.pendingPrompt?.abort();let G=new AbortController;if(this.pendingPrompt=G,!this.agent)throw Error("Session not initialized");try{let H=this.resolvePrompt(z.prompt);if(X.debug(`[AcpSession ${this.id}] Received prompt: ${H.slice(0,100)}...`),h(H))return await this.handleSlashCommand(H,G.signal);let Q={sessionId:this.id,userId:"acp-user",workspaceRoot:this.cwd,messages:[...this.messages],signal:G.signal,permissionMode:this.mapModeToPermissionMode(),confirmationHandler:{requestConfirmation:async(J)=>{return this.requestPermission(J)}}};if(await O(this.agent.chatStream(H,Q),async(J)=>{switch(J.kind){case"content_delta":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:J.delta}});break;case"thinking_delta":this.sendUpdate({sessionUpdate:"agent_thought_chunk",content:{type:"text",text:J.delta}});break;case"tool_start":{let U=J.toolCall,Y="function"in U?U.function.name:U.type,q=this.mapToolKind(J.toolKind);this.sendUpdate({sessionUpdate:"tool_call",toolCallId:U.id,status:"in_progress",title:`Executing ${Y}`,content:[],kind:q});break}case"tool_result":{let{toolCall:U,result:Y}=J,q=[],Z=Y.metadata;if(Z?.kind==="edit"&&typeof Z.file_path==="string"&&typeof Z.oldContent==="string"&&(typeof Z.newContent==="string"||Z.newContent===void 0))q.push({type:"diff",path:Z.file_path,oldText:Z.oldContent,newText:Z.newContent??null});else{let F="function"in U?U.function.name:U.type,j=L(N(F,Y));q.push({type:"content",content:{type:"text",text:j}})}let E=Y.success?"completed":"failed";this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:U.id,status:E,content:q});break}case"task_update":this.sendPlanUpdate(J.tasks);break;default:break}}),this.messages=[...Q.messages],G.signal.aborted)return{stopReason:"cancelled"};return{stopReason:"end_turn"}}catch(H){if(G.signal.aborted||H instanceof Error&&H.name==="AbortError")return{stopReason:"cancelled"};throw X.error(`[AcpSession ${this.id}] Prompt error:`,H),H}finally{if(this.pendingPrompt===G)this.pendingPrompt=null}}cancel(){if(X.info(`[AcpSession ${this.id}] Cancel requested`),this.pendingPrompt)this.pendingPrompt.abort(),this.pendingPrompt=null,X.info(`[AcpSession ${this.id}] Cancelled successfully`);else X.warn(`[AcpSession ${this.id}] No pending prompt to cancel`)}async setMode(z){let G=["default","auto-edit","yolo","plan"];this.mode=G.includes(z)?z:"default",X.info(`[AcpSession ${this.id}] Mode set to: ${this.mode}`),this.sendUpdate({sessionUpdate:"current_mode_update",currentModeId:this.mode})}mapModeToPermissionMode(){switch(this.mode){case"yolo":return"yolo";case"auto-edit":return"autoEdit";case"plan":return"plan";case"default":default:return"default"}}shouldAutoApprove(z){switch(this.mode){case"yolo":return!0;case"auto-edit":return z==="readonly"||z==="write";case"plan":return z==="readonly";case"default":default:return!1}}async setModel(z){if(X.info(`[AcpSession ${this.id}] Model set to: ${z}`),this.agent)X.warn(`[AcpSession ${this.id}] Runtime model switching not yet implemented`)}async destroy(){if(this.cancel(),this.agent)await this.agent.destroy(),this.agent=null;if(this.runtime)await this.runtime.dispose(),this.runtime=null;V.destroySession(this.id),X.debug(`[AcpSession ${this.id}] Destroyed`)}resolvePrompt(z){let G=[];for(let H of z)if(H.type==="text")G.push(H.text);else if(H.type==="image")G.push(`[Image: ${H.mimeType}]`);else if(H.type==="resource"){let Q=H.resource;if("text"in Q)G.push(`<file path="${Q.uri}">
1
+ import{A as V,G as f,J as N,K as L,M as T,S as h,U as P,V as R}from"./chunk-x4ta13s0.js";import{Y as M}from"./chunk-365tx34d.js";import"./chunk-esnkk33h.js";import"./chunk-5gxn6wrh.js";import"./chunk-cj5w17y3.js";import{za as y}from"./chunk-j73schtj.js";import"./chunk-n2dcjqbe.js";import{Sa as O}from"./chunk-5yffdaq2.js";import"./chunk-yddnm9n2.js";import"./chunk-1e2phnbj.js";import"./chunk-37rethcy.js";import{xb as D}from"./chunk-7ycmx7c2.js";import{Bb as W}from"./chunk-set7v1rf.js";import"./chunk-j2ag7hh6.js";import{Readable as K,Writable as k}from"node:stream";import*as _ from"@agentclientprotocol/sdk";import{PROTOCOL_VERSION as I}from"@agentclientprotocol/sdk";import{nanoid as S}from"nanoid";import{nanoid as x}from"nanoid";var X=W("Agent");class B{id;cwd;connection;clientCapabilities;agent=null;runtime=null;pendingPrompt=null;messages=[];mode="default";sessionApprovals=new Set;constructor(z,G,H,Q){this.id=z;this.cwd=G;this.connection=H;this.clientCapabilities=Q}async initialize(){X.debug(`[AcpSession ${this.id}] Initializing...`),V.initializeSession(this.connection,this.id,this.clientCapabilities,this.cwd),X.debug(`[AcpSession ${this.id}] ACP service context initialized`),this.runtime=await f.create({sessionId:this.id}),this.agent=await T.createWithRuntime(this.runtime,{sessionId:this.id}),X.debug(`[AcpSession ${this.id}] Agent created successfully`)}sendAvailableCommandsDelayed(){X.debug(`[AcpSession ${this.id}] Scheduling available commands update (500ms delay)`),setTimeout(()=>{this.sendAvailableCommands()},500)}async handleSlashCommand(z,G){try{X.debug(`[AcpSession ${this.id}] Executing slash command: ${z}`);let H={cwd:this.cwd,signal:G,acp:{sendMessage:(U)=>{this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:U}})},sendToolStart:(U,Y,q)=>{let Z=`tool_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,E=this.mapToolKind(q);this.sendUpdate({sessionUpdate:"tool_call",toolCallId:Z,status:"in_progress",title:`${U}`,content:[{type:"content",content:{type:"text",text:JSON.stringify(Y,null,2)}}],kind:E})},sendToolResult:(U,Y)=>{if(Y.summary)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:Y.summary}})}}},Q=await P(z,H),J=Q.content||Q.message;if(J)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:J}});if(Q.error)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[FAIL] ${Q.error}`}});return{stopReason:Q.success?"end_turn":"cancelled"}}catch(H){return X.error(`[AcpSession ${this.id}] Slash command error:`,H),this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[FAIL] 命令执行失败: ${H instanceof Error?H.message:"未知错误"}`}}),{stopReason:"cancelled"}}}async sendAvailableCommands(){try{let z=R(),G=["model","permissions","theme","config","exit","ide"],Q=z.filter((J)=>!G.includes(J.name)).map((J)=>{let U;if(J.usage){let Y=J.usage.replace(/^\/\w+\s*/,"").trim();if(Y)U=Y}if(J.aliases?.length){let Y=`Aliases: ${J.aliases.join(", ")}`;U=U?`${U} | ${Y}`:Y}return{name:J.name,description:J.description,input:U?{hint:U}:void 0}});X.info(`[AcpSession ${this.id}] Sending available commands: ${JSON.stringify(Q.map((J)=>J.name))}`),this.sendUpdate({sessionUpdate:"available_commands_update",availableCommands:Q}),X.info(`[AcpSession ${this.id}] Sent ${Q.length} available commands`)}catch(z){X.error(`[AcpSession ${this.id}] Failed to send available commands:`,z)}}async prompt(z){V.setCurrentSession(this.id),this.pendingPrompt?.abort();let G=new AbortController;if(this.pendingPrompt=G,!this.agent)throw Error("Session not initialized");try{let H=this.resolvePrompt(z.prompt);if(X.debug(`[AcpSession ${this.id}] Received prompt: ${H.slice(0,100)}...`),h(H))return await this.handleSlashCommand(H,G.signal);let Q={sessionId:this.id,userId:"acp-user",workspaceRoot:this.cwd,messages:[...this.messages],signal:G.signal,permissionMode:this.mapModeToPermissionMode(),confirmationHandler:{requestConfirmation:async(J)=>{return this.requestPermission(J)}}};if(await O(this.agent.chatStream(H,Q),async(J)=>{switch(J.kind){case"content_delta":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:J.delta}});break;case"thinking_delta":this.sendUpdate({sessionUpdate:"agent_thought_chunk",content:{type:"text",text:J.delta}});break;case"tool_start":{let U=J.toolCall,Y="function"in U?U.function.name:U.type,q=this.mapToolKind(J.toolKind);this.sendUpdate({sessionUpdate:"tool_call",toolCallId:U.id,status:"in_progress",title:`Executing ${Y}`,content:[],kind:q});break}case"tool_result":{let{toolCall:U,result:Y}=J,q=[],Z=Y.metadata;if(Z?.kind==="edit"&&typeof Z.file_path==="string"&&typeof Z.oldContent==="string"&&(typeof Z.newContent==="string"||Z.newContent===void 0))q.push({type:"diff",path:Z.file_path,oldText:Z.oldContent,newText:Z.newContent??null});else{let F="function"in U?U.function.name:U.type,j=L(N(F,Y));q.push({type:"content",content:{type:"text",text:j}})}let E=Y.success?"completed":"failed";this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:U.id,status:E,content:q});break}case"task_update":this.sendPlanUpdate(J.tasks);break;default:break}}),this.messages=[...Q.messages],G.signal.aborted)return{stopReason:"cancelled"};return{stopReason:"end_turn"}}catch(H){if(G.signal.aborted||H instanceof Error&&H.name==="AbortError")return{stopReason:"cancelled"};throw X.error(`[AcpSession ${this.id}] Prompt error:`,H),H}finally{if(this.pendingPrompt===G)this.pendingPrompt=null}}cancel(){if(X.info(`[AcpSession ${this.id}] Cancel requested`),this.pendingPrompt)this.pendingPrompt.abort(),this.pendingPrompt=null,X.info(`[AcpSession ${this.id}] Cancelled successfully`);else X.warn(`[AcpSession ${this.id}] No pending prompt to cancel`)}async setMode(z){let G=["default","auto-edit","yolo","plan"];this.mode=G.includes(z)?z:"default",X.info(`[AcpSession ${this.id}] Mode set to: ${this.mode}`),this.sendUpdate({sessionUpdate:"current_mode_update",currentModeId:this.mode})}mapModeToPermissionMode(){switch(this.mode){case"yolo":return"yolo";case"auto-edit":return"autoEdit";case"plan":return"plan";case"default":default:return"default"}}shouldAutoApprove(z){switch(this.mode){case"yolo":return!0;case"auto-edit":return z==="readonly"||z==="write";case"plan":return z==="readonly";case"default":default:return!1}}async setModel(z){if(X.info(`[AcpSession ${this.id}] Model set to: ${z}`),this.agent)X.warn(`[AcpSession ${this.id}] Runtime model switching not yet implemented`)}async destroy(){if(this.cancel(),this.agent)await this.agent.destroy(),this.agent=null;if(this.runtime)await this.runtime.dispose(),this.runtime=null;V.destroySession(this.id),X.debug(`[AcpSession ${this.id}] Destroyed`)}resolvePrompt(z){let G=[];for(let H of z)if(H.type==="text")G.push(H.text);else if(H.type==="image")G.push(`[Image: ${H.mimeType}]`);else if(H.type==="resource"){let Q=H.resource;if("text"in Q)G.push(`<file path="${Q.uri}">
2
2
  ${Q.text}
3
3
  </file>`)}else if(H.type==="resource_link")G.push(`[Resource: ${H.uri}]`);return G.join(`
4
4
  `)}sendUpdate(z){let G={sessionId:this.id,update:z};this.connection.sessionUpdate(G).catch((H)=>{X.warn(`[AcpSession ${this.id}] Failed to send update:`,H)})}sendPlanUpdate(z){let G=z.map((H)=>({content:H.subject,priority:H.priority,status:H.status}));X.debug(`[AcpSession ${this.id}] Sending plan update with ${G.length} entries`),this.sendUpdate({sessionUpdate:"plan",entries:G})}async requestPermission(z){let G=z.kind?.toLowerCase()||"execute";if(this.shouldAutoApprove(G))return X.debug(`[AcpSession ${this.id}] Auto-approving ${G} in mode: ${this.mode}`),{approved:!0};if(this.mode==="plan"&&(G==="write"||G==="execute"))return X.debug(`[AcpSession ${this.id}] Rejecting ${G} in plan mode`),{approved:!1,reason:"Write and execute operations are not allowed in Plan mode"};let H=`${G}:${z.title||"unknown"}`;if(this.sessionApprovals.has(H))return X.debug(`[AcpSession ${this.id}] Using cached approval for: ${H}`),{approved:!0};try{let Q=x(),J=[];if(z.message)J.push({type:"content",content:{type:"text",text:z.message}});if(z.risks&&z.risks.length>0)J.push({type:"content",content:{type:"text",text:`Risks:
@@ -1,4 +1,4 @@
1
- import{N as l,O as c,P as m,S as g,U as d}from"./chunk-tjzyqsnc.js";import{xb as u}from"./chunk-7ycmx7c2.js";async function C(){if((await l().initialize(u(),[])).plugins.length>0)await c()}async function h(t){let e=t.message||t._?.[0];if(typeof e==="string"&&e.trim())return e;let n=t.stdin??process.stdin;if(!n.isTTY){let a=[];for await(let i of n)a.push(i);return Buffer.concat(a).toString("utf-8").trim()}if(t.defaultMessage!==void 0)return t.defaultMessage;throw Error("No input provided")}async function R(t){if(!g(t))return{mode:"agent",content:t};let e=await d(t,{cwd:u(),workspaceRoot:u()});if(!e.success)return{mode:"output",content:`Error: ${e.error||"未知错误"}`,exitCode:1};let n=e.data;if(n?.action==="invoke_skill"){let{skillName:a,skillArgs:i}=n;return{mode:"agent",content:i?`Please use the "${a}" skill to help me with: ${i}`:`Please use the "${a}" skill.`}}if(n?.action==="invoke_custom_command"||n?.action==="invoke_plugin_command"){let a=n.processedContent;return{mode:"agent",content:`# Custom Command: /${n.commandName}
1
+ import{N as l,O as c,P as m,S as g,U as d}from"./chunk-x4ta13s0.js";import{xb as u}from"./chunk-7ycmx7c2.js";async function C(){if((await l().initialize(u(),[])).plugins.length>0)await c()}async function h(t){let e=t.message||t._?.[0];if(typeof e==="string"&&e.trim())return e;let n=t.stdin??process.stdin;if(!n.isTTY){let a=[];for await(let i of n)a.push(i);return Buffer.concat(a).toString("utf-8").trim()}if(t.defaultMessage!==void 0)return t.defaultMessage;throw Error("No input provided")}async function R(t){if(!g(t))return{mode:"agent",content:t};let e=await d(t,{cwd:u(),workspaceRoot:u()});if(!e.success)return{mode:"output",content:`Error: ${e.error||"未知错误"}`,exitCode:1};let n=e.data;if(n?.action==="invoke_skill"){let{skillName:a,skillArgs:i}=n;return{mode:"agent",content:i?`Please use the "${a}" skill to help me with: ${i}`:`Please use the "${a}" skill.`}}if(n?.action==="invoke_custom_command"||n?.action==="invoke_plugin_command"){let a=n.processedContent;return{mode:"agent",content:`# Custom Command: /${n.commandName}
2
2
 
3
3
  ${a}`}}return{mode:"output",content:e.content||e.message||"",exitCode:0}}function r(t){if(!(t instanceof Error))return!1;return t.message.includes("未找到会话")||t.message.includes("ENOENT")||t.message.includes("no such file")}async function s(t){try{return await m.loadSession(t,u())}catch(e){if(r(e))return null;throw e}}async function N(t){if(t.resume===!0||t.resume==="true")throw Error("--resume without a session ID is only supported in interactive UI mode");if(typeof t.resume==="string"&&t.resume.length>0)return{sessionId:t.resume,messages:await m.loadSession(t.resume)};if(t.continue){let e=await m.listSessions();if(e.length>0){let n=e[0].sessionId;return{sessionId:n,messages:await m.loadSession(n)}}}if(t.sessionId)return{sessionId:t.sessionId,messages:await s(t.sessionId)??[]};return{sessionId:`${t.fallbackSessionPrefix}-${Date.now()}`,messages:[]}}
4
4
  export{C as p,h as q,R as r,N as s};
@@ -1,4 +1,4 @@
1
- import{Y as O}from"./chunk-sdfra3bn.js";import"./chunk-vppcvxzd.js";import{Ea as J,Ga as L}from"./chunk-j73schtj.js";import"./chunk-n2dcjqbe.js";import"./chunk-yddnm9n2.js";import{xb as H}from"./chunk-7ycmx7c2.js";import"./chunk-set7v1rf.js";import"./chunk-j2ag7hh6.js";import P from"os";import E from"path";function _(q){return typeof q==="string"?q:void 0}function T(q){if(!Array.isArray(q))return;let z=[];for(let F of q)if(typeof F==="string")z.push(F);else if(F!=null)z.push(String(F));return z}function G(){console.log(`
1
+ import{Y as O}from"./chunk-365tx34d.js";import"./chunk-5gxn6wrh.js";import{Ea as J,Ga as L}from"./chunk-j73schtj.js";import"./chunk-n2dcjqbe.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{X as D,Y as F$}from"./chunk-sdfra3bn.js";import{Z as Q4}from"./chunk-esnkk33h.js";import{ba as M1}from"./chunk-vppcvxzd.js";import{ga as m}from"./chunk-cj5w17y3.js";import{Aa as C1,Ba as l$,Ca as j$,Da as c0,Ea as L$,Fa as I1,Ga as x$,ra as i4,sa as s,ua as l0,va as i,wa as A,za as t}from"./chunk-j73schtj.js";import{Ia as v1}from"./chunk-n2dcjqbe.js";import{Ma as r2,Na as Q$,Oa as D0,Pa as y$,Sa as N$,db as n1,eb as $9,hb as Q2}from"./chunk-10js1kwp.js";import{ib as G2,jb as F2,kb as Q5,lb as Y2}from"./chunk-yddnm9n2.js";import{mb as y5,nb as X$}from"./chunk-1e2phnbj.js";import{rb as S1}from"./chunk-37rethcy.js";import{tb as i5,xb as N}from"./chunk-7ycmx7c2.js";import{Bb as M,Cb as S}from"./chunk-set7v1rf.js";import{Db as s$}from"./chunk-j2ag7hh6.js";import{spawn as m9}from"child_process";import{randomUUID as c9}from"crypto";class n{static instance=null;processes=new Map;static getInstance(){if(!n.instance)n.instance=new n;return n.instance}startBackgroundProcess($){let Z=`bash_${c9()}`,J={};for(let[Y,V]of Object.entries({...process.env,...$.env,BLADE_CLI:"1"}))if(V!==void 0)J[Y]=V;let W=m9("bash",["-c",$.command],{cwd:$.cwd||N(),env:J,stdio:["ignore","pipe","pipe"]}),X={id:Z,command:$.command,sessionId:$.sessionId,cwd:$.cwd,env:$.env,process:W,pid:W.pid,status:"running",startTime:Date.now(),pendingStdout:"",pendingStderr:""};return W.stdout?.setEncoding("utf8"),W.stderr?.setEncoding("utf8"),W.stdout?.on("data",(Y)=>{X.pendingStdout+=Y.toString()}),W.stderr?.on("data",(Y)=>{X.pendingStderr+=Y.toString()}),W.on("close",(Y,V)=>{X.status=X.status==="killed"?"killed":"exited",X.exitCode=Y,X.signal=V,X.endTime=Date.now(),X.process=void 0}),W.on("error",(Y)=>{X.status="error",X.errorMessage=Y.message,X.endTime=Date.now(),X.process=void 0,X.pendingStderr+=`
1
+ import{X as D,Y as F$}from"./chunk-365tx34d.js";import{Z as Q4}from"./chunk-esnkk33h.js";import{ba as M1}from"./chunk-5gxn6wrh.js";import{ga as m}from"./chunk-cj5w17y3.js";import{Aa as C1,Ba as l$,Ca as j$,Da as c0,Ea as L$,Fa as I1,Ga as x$,ra as i4,sa as s,ua as l0,va as i,wa as A,za as t}from"./chunk-j73schtj.js";import{Ia as v1}from"./chunk-n2dcjqbe.js";import{Ma as r2,Na as Q$,Oa as D0,Pa as y$,Sa as N$,db as n1,eb as $9,hb as Q2}from"./chunk-5yffdaq2.js";import{ib as G2,jb as F2,kb as Q5,lb as Y2}from"./chunk-yddnm9n2.js";import{mb as y5,nb as X$}from"./chunk-1e2phnbj.js";import{rb as S1}from"./chunk-37rethcy.js";import{tb as i5,xb as N}from"./chunk-7ycmx7c2.js";import{Bb as M,Cb as S}from"./chunk-set7v1rf.js";import{Db as s$}from"./chunk-j2ag7hh6.js";import{spawn as m9}from"child_process";import{randomUUID as c9}from"crypto";class n{static instance=null;processes=new Map;static getInstance(){if(!n.instance)n.instance=new n;return n.instance}startBackgroundProcess($){let Z=`bash_${c9()}`,J={};for(let[Y,V]of Object.entries({...process.env,...$.env,BLADE_CLI:"1"}))if(V!==void 0)J[Y]=V;let W=m9("bash",["-c",$.command],{cwd:$.cwd||N(),env:J,stdio:["ignore","pipe","pipe"]}),X={id:Z,command:$.command,sessionId:$.sessionId,cwd:$.cwd,env:$.env,process:W,pid:W.pid,status:"running",startTime:Date.now(),pendingStdout:"",pendingStderr:""};return W.stdout?.setEncoding("utf8"),W.stderr?.setEncoding("utf8"),W.stdout?.on("data",(Y)=>{X.pendingStdout+=Y.toString()}),W.stderr?.on("data",(Y)=>{X.pendingStderr+=Y.toString()}),W.on("close",(Y,V)=>{X.status=X.status==="killed"?"killed":"exited",X.exitCode=Y,X.signal=V,X.endTime=Date.now(),X.process=void 0}),W.on("error",(Y)=>{X.status="error",X.errorMessage=Y.message,X.endTime=Date.now(),X.process=void 0,X.pendingStderr+=`
2
2
  [error] ${Y.message}`}),this.processes.set(Z,X),X}consumeOutput($){let Z=this.processes.get($);if(!Z)return;let J={id:Z.id,command:Z.command,status:Z.status,stdout:Z.pendingStdout,stderr:Z.pendingStderr,exitCode:Z.exitCode,signal:Z.signal,pid:Z.pid,startedAt:Z.startTime,endedAt:Z.endTime,errorMessage:Z.errorMessage};return Z.pendingStdout="",Z.pendingStderr="",J}getProcess($){return this.processes.get($)}kill($){let Z=this.processes.get($);if(!Z)return;if(Z.status!=="running"||!Z.process)return{success:!1,alreadyExited:!0,status:Z.status,pid:Z.pid,exitCode:Z.exitCode,signal:Z.signal};if(!Z.process.kill("SIGTERM"))return{success:!1,alreadyExited:!1,status:Z.status,pid:Z.pid,exitCode:Z.exitCode,signal:Z.signal};return Z.status="killed",Z.endTime=Date.now(),Z.process=void 0,{success:!0,alreadyExited:!1,status:Z.status,pid:Z.pid,exitCode:Z.exitCode,signal:Z.signal}}killAll(){for(let[$,Z]of this.processes)if(Z.status==="running"&&Z.process)try{Z.process.kill("SIGTERM"),Z.status="killed",Z.endTime=Date.now(),Z.process=void 0}catch{}this.processes.clear()}}import Y8 from"node:fs";import X1 from"node:os";import k$ from"node:path";import l9 from"yaml";var g5={name:"verification",description:"Independent verification agent that validates implementation by running builds, tests, linters, and adversarial"+" probes. Strictly read-only — cannot modify code. Use"+" after completing implementation to get an independent quality assessment.",tools:["Read","Glob","Grep","Bash"],systemPrompt:`# Verification Agent
3
3
 
4
4
  You are an **independent verification engineer**. Your sole purpose is to find problems — not to praise or reassure. You are the last line of defense before code ships.
@@ -1343,7 +1343,7 @@ ${U}
1343
1343
  </approved-plan>
1344
1344
 
1345
1345
  IMPORTANT: Execute according to the approved plan above. Follow the steps exactly as specified.`;if(typeof W==="string")H=W+G;else H=[...W,{type:"text",text:G}]}K=yield*this.runLoop(H,q,B)}return K}let X=typeof W==="string"?W:W.filter((B)=>B.type==="text").map((B)=>B.text).join(`
1346
- `),Y={id:this.generateTaskId(),type:"simple",prompt:X};return{success:!0,finalMessage:(await this.executeTask(Y)).content,metadata:{turnsCount:1,toolCallsCount:0,duration:0}}}async chat($,Z,J){let{drainLoop:W}=await import("./chunk-zy2ke0vv.js");return W(this.chatStream($,Z,J))}async*runPlanLoop($,Z,J){k.debug("Processing Plan mode message...");let{prompt:W}=await $0({projectPath:N(),mode:"plan",includeEnvironment:!0,language:this.config.language}),X;if(typeof $==="string")X=C0($);else{let Y=$.filter((V)=>V.type==="text");if(Y.length>0){let V=Y[0];X=$.map((B)=>B===V?{type:"text",text:C0(V.text)}:B)}else X=[{type:"text",text:C0("")},...$]}return yield*this.executeLoop(X,Z,J,W)}async*runSpecLoop($,Z,J){k.debug("Processing Spec mode message...");let W=m.getInstance(),X=Z.workspaceRoot||N();try{await W.initialize(X)}catch(U){k.warn("SpecManager initialization warning:",U)}let Y=W.getCurrentSpec(),V=await W.getSteeringContextString(),B=V1(Y,V),K,Q=Y?.phase||"init";if(typeof $==="string")K=`${B1(Q)}
1346
+ `),Y={id:this.generateTaskId(),type:"simple",prompt:X};return{success:!0,finalMessage:(await this.executeTask(Y)).content,metadata:{turnsCount:1,toolCallsCount:0,duration:0}}}async chat($,Z,J){let{drainLoop:W}=await import("./chunk-rwdg0e8r.js");return W(this.chatStream($,Z,J))}async*runPlanLoop($,Z,J){k.debug("Processing Plan mode message...");let{prompt:W}=await $0({projectPath:N(),mode:"plan",includeEnvironment:!0,language:this.config.language}),X;if(typeof $==="string")X=C0($);else{let Y=$.filter((V)=>V.type==="text");if(Y.length>0){let V=Y[0];X=$.map((B)=>B===V?{type:"text",text:C0(V.text)}:B)}else X=[{type:"text",text:C0("")},...$]}return yield*this.executeLoop(X,Z,J,W)}async*runSpecLoop($,Z,J){k.debug("Processing Spec mode message...");let W=m.getInstance(),X=Z.workspaceRoot||N();try{await W.initialize(X)}catch(U){k.warn("SpecManager initialization warning:",U)}let Y=W.getCurrentSpec(),V=await W.getSteeringContextString(),B=V1(Y,V),K,Q=Y?.phase||"init";if(typeof $==="string")K=`${B1(Q)}
1347
1347
 
1348
1348
  ${$}`;else{let U=$.filter((q)=>q.type==="text");if(U.length>0){let q=U[0];K=$.map((H)=>H===q?{type:"text",text:`${B1(Q)}
1349
1349
 
@@ -1,2 +1,2 @@
1
- import{e as zf,f as Tf}from"./chunk-q5yn875m.js";import{B as s,C as Mf,G as Ff,H as g,J as Uf,K as qf,M as Bf,P as h,W as Lf,z as wf}from"./chunk-tjzyqsnc.js";import{Y as T}from"./chunk-sdfra3bn.js";import{ba as u}from"./chunk-vppcvxzd.js";import{Ba as xf,Ca as Rf,Ga as z,za as S}from"./chunk-j73schtj.js";import{La as _f,Na as t,Sa as Ef}from"./chunk-10js1kwp.js";import{xb as R}from"./chunk-7ycmx7c2.js";import{Bb as x}from"./chunk-set7v1rf.js";import{Db as jf}from"./chunk-j2ag7hh6.js";var I0={port:{type:"number",describe:"Port to listen on (0 for auto)",default:0},hostname:{type:"string",describe:"Hostname to listen on",default:"127.0.0.1"},cors:{type:"array",describe:"Additional domains to allow for CORS",default:[]}};function v0(V){return{port:V.port??0,hostname:V.hostname??"127.0.0.1",cors:V.cors??[]}}import{Hono as T0}from"hono";import{cors as y0}from"hono/cors";import{existsSync as gf,readFileSync as e}from"node:fs";import{createServer as _0}from"node:http";import{networkInterfaces as D0}from"node:os";import{dirname as b0,extname as w0,join as w}from"node:path";import{fileURLToPath as L0}from"node:url";import{WebSocketServer as P0}from"ws";import{z as c}from"zod";class p extends Error{code;statusCode;constructor(V,$,f=500){super($);this.code=V;this.statusCode=f;this.name="BladeServerError"}toObject(){return{error:{code:this.code,message:this.message}}}}class P extends p{constructor(V,$){super("NOT_FOUND",$?`${V} not found: ${$}`:`${V} not found`,404)}}class A extends p{constructor(V){super("BAD_REQUEST",V,400)}}var g0=c.object({error:c.object({code:c.string(),message:c.string()})});import{Hono as cf}from"hono";import{z as k}from"zod";var $f=x("Service"),af=k.object({updates:k.record(k.any()),options:k.object({scope:k.enum(["local","project","global"]).optional(),immediate:k.boolean().optional()}).optional()}),Gf=()=>{let V=new cf;return V.get("/",async($)=>{try{let f=S();return $.json(f||{})}catch(f){return $f.error("[ConfigRoutes] Failed to get config:",f),$.json({})}}),V.put("/",async($)=>{try{let f=await $.req.json(),O=af.safeParse(f);if(!O.success)throw new A("Invalid config update format");let{updates:M,options:J}=O.data;return await z().updateConfig(M,J),$.json({success:!0,updates:M})}catch(f){throw $f.error("[ConfigRoutes] Failed to update config:",f),f}}),V.get("/permissions",async($)=>{try{let f=S();return $.json(f?.permissions||{})}catch(f){return $f.error("[ConfigRoutes] Failed to get permissions:",f),$.json({})}}),V};import{Hono as tf}from"hono";var Nf=()=>{let V=new tf;return V.get("/health",($)=>{return $.json({healthy:!0,version:u()})}),V.get("/info",($)=>{return $.json({version:u(),platform:process.platform,arch:process.arch,nodeVersion:process.version,cwd:R()})}),V};import{Hono as nf}from"hono";var o=x("Service"),mf=()=>{let V=new nf;return V.get("/",async($)=>{try{let O=T.getInstance().getAllServers(),M=Array.from(O.entries()).map(([J,j])=>({id:J,name:J,status:j.status==="connected"?"connected":j.status==="connecting"?"connecting":j.lastError?"error":"offline",endpoint:j.config.command?`${j.config.command} ${(j.config.args||[]).join(" ")}`.trim():j.config.url||"Unknown",description:`MCP server: ${J}`,tools:j.tools.map((Y)=>Y.name),connectedAt:j.connectedAt?.toISOString(),error:j.lastError?.message}));return $.json(M)}catch(f){return o.error("[McpRoutes] Failed to get MCP servers:",f),$.json([])}}),V.post("/:name/connect",async($)=>{try{let f=$.req.param("name");return await T.getInstance().connectServer(f),$.json({success:!0})}catch(f){return o.error("[McpRoutes] Failed to connect MCP server:",f),$.json({success:!1,error:f.message},500)}}),V.post("/:name/disconnect",async($)=>{try{let f=$.req.param("name");return await T.getInstance().disconnectServer(f),$.json({success:!0})}catch(f){return o.error("[McpRoutes] Failed to disconnect MCP server:",f),$.json({success:!1,error:f.message},500)}}),V.delete("/:name",async($)=>{try{let f=$.req.param("name");await T.getInstance().unregisterServer(f);let M=S();if(M?.mcpServers){let{[f]:J,...j}=M.mcpServers;await z().updateConfig({mcpServers:j})}return $.json({success:!0})}catch(f){return o.error("[McpRoutes] Failed to delete MCP server:",f),$.json({success:!1,error:f.message},500)}}),V.post("/",async($)=>{try{let f=await $.req.json(),{name:O,config:M}=f;if(!O||!M)return $.json({success:!1,error:"Missing name or config"},400);await T.getInstance().registerServer(O,M);let j=S();return await z().updateConfig({mcpServers:{...j?.mcpServers,[O]:M}}),$.json({success:!0})}catch(f){return o.error("[McpRoutes] Failed to add MCP server:",f),$.json({success:!1,error:f.message},500)}}),V};import{Hono as sf}from"hono";var a=x("Service"),Xf=()=>{let V=new sf;return V.get("/",async($)=>{try{let f=xf(),O=Rf();return $.json({configured:f,current:O})}catch(f){return a.error("[ModelsRoutes] Failed to get models:",f),$.json({configured:[],current:null})}}),V.post("/",async($)=>{try{let f=await $.req.json(),{provider:O,name:M,model:J,baseUrl:j,apiKey:Y}=f;if(!J)throw new A("model is required");let K=await z().addModel({provider:O||"openai-compatible",name:M||J,model:J,baseUrl:j||void 0,apiKey:Y||void 0});return $.json({success:!0,model:K})}catch(f){throw a.error("[ModelsRoutes] Failed to add model:",f),f}}),V.put("/:modelId",async($)=>{try{let f=$.req.param("modelId"),O=await $.req.json(),{baseUrl:M,apiKey:J,model:j}=O;return await z().updateModel(f,{baseUrl:M||void 0,apiKey:J||void 0,model:j||void 0}),$.json({success:!0})}catch(f){throw a.error("[ModelsRoutes] Failed to update model:",f),f}}),V.delete("/:modelId",async($)=>{try{let f=$.req.param("modelId");return await z().removeModel(f),$.json({success:!0})}catch(f){throw a.error("[ModelsRoutes] Failed to delete model:",f),f}}),V};import{Hono as Z0}from"hono";import{z as C}from"zod";import{Hono as ef}from"hono";import{streamSSE as f0}from"hono/streaming";import{LRUCache as $0}from"lru-cache";import{nanoid as d}from"nanoid";import{z as U}from"zod";var X=x("Service"),V0=U.object({title:U.string().optional(),projectPath:U.string().optional()}),O0=U.object({content:U.string(),attachments:U.array(U.object({type:U.enum(["file","image","url"]),path:U.string().optional(),url:U.string().optional(),content:U.string().optional(),mimeType:U.string().optional(),name:U.string().optional()})).optional(),permissionMode:U.enum(["default","autoEdit","plan","spec","yolo"]).optional()}),M0=U.object({title:U.string().optional()}),B=new Map,D=new $0({max:100,ttl:1800000,dispose:(V,$)=>{if(V.status==="running"||V.status==="waiting_permission")V.abortController.abort(),X.debug(`[SessionRoutes] Run ${$} disposed due to cache eviction`)}}),j0=(V)=>{if(!V||typeof V!=="object")return V;let $={...V},f=200000;if(typeof $.oldContent==="string"&&$.oldContent.length>f)delete $.oldContent;if(typeof $.newContent==="string"&&$.newContent.length>f)delete $.newContent;return $};function J0(V){if(typeof V==="string")return V;return V.filter(($)=>$.type==="text").map(($)=>$.text).join(`
1
+ import{e as zf,f as Tf}from"./chunk-q5yn875m.js";import{B as s,C as Mf,G as Ff,H as g,J as Uf,K as qf,M as Bf,P as h,W as Lf,z as wf}from"./chunk-x4ta13s0.js";import{Y as T}from"./chunk-365tx34d.js";import{ba as u}from"./chunk-5gxn6wrh.js";import{Ba as xf,Ca as Rf,Ga as z,za as S}from"./chunk-j73schtj.js";import{La as _f,Na as t,Sa as Ef}from"./chunk-5yffdaq2.js";import{xb as R}from"./chunk-7ycmx7c2.js";import{Bb as x}from"./chunk-set7v1rf.js";import{Db as jf}from"./chunk-j2ag7hh6.js";var I0={port:{type:"number",describe:"Port to listen on (0 for auto)",default:0},hostname:{type:"string",describe:"Hostname to listen on",default:"127.0.0.1"},cors:{type:"array",describe:"Additional domains to allow for CORS",default:[]}};function v0(V){return{port:V.port??0,hostname:V.hostname??"127.0.0.1",cors:V.cors??[]}}import{Hono as T0}from"hono";import{cors as y0}from"hono/cors";import{existsSync as gf,readFileSync as e}from"node:fs";import{createServer as _0}from"node:http";import{networkInterfaces as D0}from"node:os";import{dirname as b0,extname as w0,join as w}from"node:path";import{fileURLToPath as L0}from"node:url";import{WebSocketServer as P0}from"ws";import{z as c}from"zod";class p extends Error{code;statusCode;constructor(V,$,f=500){super($);this.code=V;this.statusCode=f;this.name="BladeServerError"}toObject(){return{error:{code:this.code,message:this.message}}}}class P extends p{constructor(V,$){super("NOT_FOUND",$?`${V} not found: ${$}`:`${V} not found`,404)}}class A extends p{constructor(V){super("BAD_REQUEST",V,400)}}var g0=c.object({error:c.object({code:c.string(),message:c.string()})});import{Hono as cf}from"hono";import{z as k}from"zod";var $f=x("Service"),af=k.object({updates:k.record(k.any()),options:k.object({scope:k.enum(["local","project","global"]).optional(),immediate:k.boolean().optional()}).optional()}),Gf=()=>{let V=new cf;return V.get("/",async($)=>{try{let f=S();return $.json(f||{})}catch(f){return $f.error("[ConfigRoutes] Failed to get config:",f),$.json({})}}),V.put("/",async($)=>{try{let f=await $.req.json(),O=af.safeParse(f);if(!O.success)throw new A("Invalid config update format");let{updates:M,options:J}=O.data;return await z().updateConfig(M,J),$.json({success:!0,updates:M})}catch(f){throw $f.error("[ConfigRoutes] Failed to update config:",f),f}}),V.get("/permissions",async($)=>{try{let f=S();return $.json(f?.permissions||{})}catch(f){return $f.error("[ConfigRoutes] Failed to get permissions:",f),$.json({})}}),V};import{Hono as tf}from"hono";var Nf=()=>{let V=new tf;return V.get("/health",($)=>{return $.json({healthy:!0,version:u()})}),V.get("/info",($)=>{return $.json({version:u(),platform:process.platform,arch:process.arch,nodeVersion:process.version,cwd:R()})}),V};import{Hono as nf}from"hono";var o=x("Service"),mf=()=>{let V=new nf;return V.get("/",async($)=>{try{let O=T.getInstance().getAllServers(),M=Array.from(O.entries()).map(([J,j])=>({id:J,name:J,status:j.status==="connected"?"connected":j.status==="connecting"?"connecting":j.lastError?"error":"offline",endpoint:j.config.command?`${j.config.command} ${(j.config.args||[]).join(" ")}`.trim():j.config.url||"Unknown",description:`MCP server: ${J}`,tools:j.tools.map((Y)=>Y.name),connectedAt:j.connectedAt?.toISOString(),error:j.lastError?.message}));return $.json(M)}catch(f){return o.error("[McpRoutes] Failed to get MCP servers:",f),$.json([])}}),V.post("/:name/connect",async($)=>{try{let f=$.req.param("name");return await T.getInstance().connectServer(f),$.json({success:!0})}catch(f){return o.error("[McpRoutes] Failed to connect MCP server:",f),$.json({success:!1,error:f.message},500)}}),V.post("/:name/disconnect",async($)=>{try{let f=$.req.param("name");return await T.getInstance().disconnectServer(f),$.json({success:!0})}catch(f){return o.error("[McpRoutes] Failed to disconnect MCP server:",f),$.json({success:!1,error:f.message},500)}}),V.delete("/:name",async($)=>{try{let f=$.req.param("name");await T.getInstance().unregisterServer(f);let M=S();if(M?.mcpServers){let{[f]:J,...j}=M.mcpServers;await z().updateConfig({mcpServers:j})}return $.json({success:!0})}catch(f){return o.error("[McpRoutes] Failed to delete MCP server:",f),$.json({success:!1,error:f.message},500)}}),V.post("/",async($)=>{try{let f=await $.req.json(),{name:O,config:M}=f;if(!O||!M)return $.json({success:!1,error:"Missing name or config"},400);await T.getInstance().registerServer(O,M);let j=S();return await z().updateConfig({mcpServers:{...j?.mcpServers,[O]:M}}),$.json({success:!0})}catch(f){return o.error("[McpRoutes] Failed to add MCP server:",f),$.json({success:!1,error:f.message},500)}}),V};import{Hono as sf}from"hono";var a=x("Service"),Xf=()=>{let V=new sf;return V.get("/",async($)=>{try{let f=xf(),O=Rf();return $.json({configured:f,current:O})}catch(f){return a.error("[ModelsRoutes] Failed to get models:",f),$.json({configured:[],current:null})}}),V.post("/",async($)=>{try{let f=await $.req.json(),{provider:O,name:M,model:J,baseUrl:j,apiKey:Y}=f;if(!J)throw new A("model is required");let K=await z().addModel({provider:O||"openai-compatible",name:M||J,model:J,baseUrl:j||void 0,apiKey:Y||void 0});return $.json({success:!0,model:K})}catch(f){throw a.error("[ModelsRoutes] Failed to add model:",f),f}}),V.put("/:modelId",async($)=>{try{let f=$.req.param("modelId"),O=await $.req.json(),{baseUrl:M,apiKey:J,model:j}=O;return await z().updateModel(f,{baseUrl:M||void 0,apiKey:J||void 0,model:j||void 0}),$.json({success:!0})}catch(f){throw a.error("[ModelsRoutes] Failed to update model:",f),f}}),V.delete("/:modelId",async($)=>{try{let f=$.req.param("modelId");return await z().removeModel(f),$.json({success:!0})}catch(f){throw a.error("[ModelsRoutes] Failed to delete model:",f),f}}),V};import{Hono as Z0}from"hono";import{z as C}from"zod";import{Hono as ef}from"hono";import{streamSSE as f0}from"hono/streaming";import{LRUCache as $0}from"lru-cache";import{nanoid as d}from"nanoid";import{z as U}from"zod";var X=x("Service"),V0=U.object({title:U.string().optional(),projectPath:U.string().optional()}),O0=U.object({content:U.string(),attachments:U.array(U.object({type:U.enum(["file","image","url"]),path:U.string().optional(),url:U.string().optional(),content:U.string().optional(),mimeType:U.string().optional(),name:U.string().optional()})).optional(),permissionMode:U.enum(["default","autoEdit","plan","spec","yolo"]).optional()}),M0=U.object({title:U.string().optional()}),B=new Map,D=new $0({max:100,ttl:1800000,dispose:(V,$)=>{if(V.status==="running"||V.status==="waiting_permission")V.abortController.abort(),X.debug(`[SessionRoutes] Run ${$} disposed due to cache eviction`)}}),j0=(V)=>{if(!V||typeof V!=="object")return V;let $={...V},f=200000;if(typeof $.oldContent==="string"&&$.oldContent.length>f)delete $.oldContent;if(typeof $.newContent==="string"&&$.newContent.length>f)delete $.newContent;return $};function J0(V){if(typeof V==="string")return V;return V.filter(($)=>$.type==="text").map(($)=>$.text).join(`
2
2
  `)}function Q0(V,$){let f=($??[]).filter((M)=>M.type==="image"&&typeof M.content==="string").map((M)=>({type:"image_url",image_url:{url:M.content}}));if(f.length===0)return V;let O=[];if(V.trim())O.push({type:"text",text:V});return O.push(...f),O}var Wf=()=>{let V=new ef,$=new Map;return V.get("/",async(f)=>{try{let O=await h.listSessions(),M=new Set(O.filter((G)=>G.relationType==="subagent").map((G)=>G.sessionId)),J=Array.from(B.values()).filter((G)=>!M.has(G.id)&&G.relationType!=="subagent").map((G)=>({sessionId:G.id,projectPath:G.projectPath,title:G.title,parentId:void 0,relationType:void 0,status:void 0,agentType:void 0,model:void 0,messageCount:G.messages.length,firstMessageTime:G.createdAt.toISOString(),lastMessageTime:new Date().toISOString(),hasErrors:!1,isActive:!0})),j=new Set(J.map((G)=>G.sessionId)),Y=O.filter((G)=>!B.has(G.sessionId)&&!j.has(G.sessionId)&&G.relationType!=="subagent"),K=new Set(j),Q=Y.filter((G)=>{if(K.has(G.sessionId))return!1;return K.add(G.sessionId),!0}),Z=[...J,...Q];return f.json(Z)}catch(O){return X.error("[SessionRoutes] Failed to list sessions:",O),f.json([])}}),V.post("/",async(f)=>{try{let O=await f.req.json(),M=V0.safeParse(O);if(!M.success)throw new A("Invalid request body");let{title:J,projectPath:j}=M.data,Y=d(12),K=j||f.get("directory")||R(),Q={id:Y,projectPath:K,title:J||`Session ${Y.slice(0,6)}`,createdAt:new Date,messages:[]};return B.set(Y,Q),f.json({sessionId:Y,projectPath:K,title:Q.title,parentId:void 0,relationType:void 0,status:void 0,agentType:void 0,model:void 0,messageCount:0,firstMessageTime:Q.createdAt.toISOString(),lastMessageTime:Q.createdAt.toISOString(),hasErrors:!1})}catch(O){throw X.error("[SessionRoutes] Failed to create session:",O),O}}),V.get("/:sessionId",async(f)=>{let O=f.req.param("sessionId"),M=B.get(O);if(M)return f.json({sessionId:M.id,projectPath:M.projectPath,title:M.title,messageCount:M.messages.length,firstMessageTime:M.createdAt.toISOString(),lastMessageTime:new Date().toISOString(),hasErrors:!1,isActive:!0});try{let j=(await h.listSessions()).find((Y)=>Y.sessionId===O);if(!j)throw new P("Session",O);return f.json(j)}catch(J){if(J instanceof P)throw J;throw X.error("[SessionRoutes] Failed to get session:",J),J}}),V.patch("/:sessionId",async(f)=>{let O=f.req.param("sessionId");try{let M=await f.req.json(),J=M0.safeParse(M);if(!J.success)throw new A("Invalid request body");let{title:j}=J.data,Y=B.get(O);if(Y&&j)Y.title=j;return f.json({success:!0,title:j})}catch(M){throw X.error("[SessionRoutes] Failed to update session:",M),M}}),V.delete("/:sessionId",async(f)=>{let O=f.req.param("sessionId"),M=B.get(O);if(M?.currentRunId){let j=D.get(M.currentRunId);if(j)j.abortController.abort(),g.publish(O,"run.cancelled",{runId:j.id}),D.delete(M.currentRunId)}try{await h.deleteSession(O)}catch(j){X.warn("[SessionRoutes] Failed to delete session file:",j)}B.delete(O);let J=$.get(O);if(J){if(await J.dispose(),$.delete(O),$.size===0)await T.getInstance().disconnectAll()}return f.json({success:!0})}),V.get("/:sessionId/message",async(f)=>{let O=f.req.param("sessionId");try{let M=await h.loadSession(O);return f.json(M)}catch(M){return X.error("[SessionRoutes] Failed to get messages:",M),f.json([])}}),V.get("/:sessionId/events",async(f)=>{let O=f.req.param("sessionId"),M=B.get(O);if(!M){let J=f.get("directory")||R();M={id:O,projectPath:J,title:`Session ${O.slice(0,6)}`,createdAt:new Date,messages:[]},B.set(O,M)}return f0(f,async(J)=>{await J.writeSSE({data:JSON.stringify({type:"connected",properties:{sessionId:O,timestamp:Date.now()}})});let Y=g.subscribe((Q)=>{if(Q.sessionId!==O)return;J.writeSSE({data:JSON.stringify({type:Q.type,properties:{sessionId:Q.sessionId,...Q.properties}})}).catch(()=>{})}),K=setInterval(()=>{if(!J.aborted)J.writeSSE({data:JSON.stringify({type:"heartbeat",properties:{timestamp:Date.now()}})}).catch(()=>{})},15000);J.onAbort(()=>{clearInterval(K),Y()});while(!0)if(await new Promise((Q)=>setTimeout(Q,1000)),J.aborted)break})}),V.post("/:sessionId/message",async(f)=>{let O=f.req.param("sessionId"),M=await f.req.json(),J=O0.safeParse(M);if(!J.success)throw new A("Invalid message format");let{content:j,attachments:Y,permissionMode:K}=J.data,Q=K||"default",Z=f.get("directory")||R(),G=Q0(j,Y),m=B.get(O);if(!m){let N=await h.loadSession(O).catch(()=>[]);m={id:O,projectPath:Z,title:`Session ${O.slice(0,6)}`,createdAt:new Date,messages:N},B.set(O,m)}let q=d(12),L=new AbortController,E={id:q,sessionId:O,status:"running",abortController:L,createdAt:new Date};return D.set(q,E),m.currentRunId=q,Y0(E,m,G,Q,$).catch((N)=>{X.error(`[SessionRoutes] Run ${q} failed:`,N)}),f.json({runId:q,status:"running"},202)}),V.post("/:sessionId/abort",async(f)=>{let O=f.req.param("sessionId"),M=B.get(O);if(M?.currentRunId){let J=D.get(M.currentRunId);if(J)J.abortController.abort(),J.status="cancelled",g.publish(O,"run.cancelled",{runId:J.id})}return f.json({success:!0})}),V.get("/:sessionId/status",async(f)=>{let O=f.req.param("sessionId"),M=B.get(O);if(!M?.currentRunId)return f.json({sessionId:O,status:"idle"});let J=D.get(M.currentRunId);return f.json({sessionId:O,runId:M.currentRunId,status:J?.status||"idle"})}),V};async function Y0(V,$,f,O,M){let{abortController:J,sessionId:j,id:Y}=V,K=d(12),Q=d(12),Z=(G,m)=>{g.publish(j,G,m)};try{Z("message.created",{messageId:K,role:"user",content:J0(f)}),Z("session.status",{status:"running"}),Z("message.created",{messageId:Q,role:"assistant",content:""});let G=M.get(j);if(!G)G=await Ff.create({sessionId:j}),M.set(j,G);let m=await Bf.createWithRuntime(G,{sessionId:j}),q=async(N)=>{let F=d(12),l=300000;V.status="waiting_permission";let ff=new Promise((Kf)=>{let rf=setTimeout(()=>{X.warn(`[SessionRoutes] Permission ${F} timed out after 300000ms`),Z("permission.timeout",{requestId:F}),Kf({approved:!1,reason:"timeout"})},300000);V.pendingPermission={permissionId:F,resolve:(lf)=>{clearTimeout(rf),Kf(lf)},details:N}});Z("permission.asked",{requestId:F,toolName:N.toolName,description:N.message,args:N.args,details:N}),X.info(`[SessionRoutes] Permission request created: ${F}, runId: ${Y}`);let Zf=await ff;return X.info(`[SessionRoutes] Permission response received: ${F}, approved: ${Zf.approved}`),V.status="running",V.pendingPermission=void 0,Zf},L={messages:[...$.messages],userId:"web-user",sessionId:j,workspaceRoot:$.projectPath,signal:J.signal,permissionMode:O,confirmationHandler:{requestConfirmation:q}},E=await Ef(m.chatStream(f,L,{stream:!0}),async(N)=>{switch(N.kind){case"content_delta":Z("message.delta",{messageId:Q,delta:N.delta});break;case"thinking_delta":Z("thinking.delta",{delta:N.delta});break;case"tool_start":if("function"in N.toolCall)Z("tool.start",{messageId:Q,toolName:N.toolCall.function.name,toolCallId:N.toolCall.id,arguments:N.toolCall.function.arguments,toolKind:N.toolKind});break;case"tool_result":if("function"in N.toolCall)Z("tool.result",{messageId:Q,toolName:N.toolCall.function.name,toolCallId:N.toolCall.id,success:!N.result.error,summary:N.result.metadata?.summary,output:qf(Uf(N.toolCall.function.name,N.result)),metadata:j0(N.result.metadata)});break;case"token_usage":Z("token.usage",{...N.usage});break;case"task_update":Z("task.updated",{tasks:N.tasks});break;default:break}});$.messages=[...L.messages],Z("message.complete",{messageId:Q}),Z("thinking.completed",{}),V.status="completed",Z("session.completed",{runId:Y,outputTruncated:E.metadata?.outputTruncated??!1}),Z("session.status",{status:"idle"})}catch(G){X.error("[SessionRoutes] Agent execution error:",G),V.status="failed",Z("session.error",{error:G instanceof Error?G.message:"Unknown error"}),Z("session.status",{status:"error"})}}function Af(V,$,f){X.info(`[SessionRoutes] Looking for permission ${$} in session ${V}`),X.info(`[SessionRoutes] Active runs: ${D.size}`);for(let[O,M]of D.entries())if(X.info(`[SessionRoutes] Checking run ${O}: sessionId=${M.sessionId}, pendingPermission=${M.pendingPermission?.permissionId}`),M.sessionId===V&&M.pendingPermission?.permissionId===$)return M.pendingPermission.resolve(f),X.info(`[SessionRoutes] Permission ${$} responded, runId: ${M.id}`),!0;return X.error(`[SessionRoutes] Permission not found: ${$}`),!1}var Vf=x("Service"),K0=C.object({approved:C.boolean(),remember:C.boolean().optional(),scope:C.enum(["once","session"]).optional(),targetMode:C.enum(["default","autoEdit","plan","spec","yolo"]).optional(),feedback:C.string().optional(),answers:C.record(C.union([C.string(),C.array(C.string())])).optional()}),Cf=()=>{let V=new Z0;return V.post("/:permissionId",async($)=>{let f=$.req.param("permissionId"),O=$.req.query("sessionId");Vf.info(`[PermissionRoutes] Received permission response: permissionId=${f}, sessionId=${O}`);try{let M=await $.req.json(),J=K0.safeParse(M);if(!J.success)throw new A("Invalid permission response format");let{approved:j,remember:Y,scope:K,targetMode:Q,feedback:Z,answers:G}=J.data;if(!O)throw new A("sessionId query parameter is required");if(!Af(O,f,{approved:j,reason:Z,scope:K,targetMode:Q,feedback:Z,answers:G}))throw new P("Permission request",f);return Vf.info(`[PermissionRoutes] Permission ${f} ${j?"approved":"denied"}`),$.json({success:!0,approved:j,remember:Y})}catch(M){throw Vf.error("[PermissionRoutes] Failed to respond to permission:",M),M}}),V};import{Hono as G0}from"hono";var Hf=x("Service"),yf=()=>{let V=new G0;return V.get("/",async($)=>{try{let f=await zf();return $.json(f)}catch(f){return Hf.error("[ProviderRoutes] Failed to list providers:",f),$.json([])}}),V.get("/:provider/models",async($)=>{let f=$.req.param("provider");try{let O=await Tf(f);return $.json(O)}catch(O){return Hf.error("[ProviderRoutes] Failed to list models:",O),$.json([])}}),V};import{Hono as N0}from"hono";import*as y from"node:fs/promises";import{homedir as m0}from"node:os";import*as n from"node:path";var b=x("Service"),Of=n.join(m0(),".blade","skills-config.json");async function Df(){try{let V=await y.readFile(Of,"utf-8");return JSON.parse(V)}catch{return{disabled:[]}}}async function x0(V){await y.mkdir(n.dirname(Of),{recursive:!0}),await y.writeFile(Of,JSON.stringify(V,null,2))}async function R0(V,$){let f=await Df();if($)f.disabled=f.disabled.filter((O)=>O!==V);else if(!f.disabled.includes(V))f.disabled.push(V);await x0(f)}var I=null,X0=300000;async function E0(){if(I&&Date.now()-I.timestamp<X0)return I.data;try{let V=await fetch("https://api.github.com/repos/anthropics/skills/contents/skills",{headers:{Accept:"application/vnd.github.v3+json","User-Agent":"Blade-Skills-Catalog"}});if(!V.ok)return b.warn(`GitHub API returned ${V.status}`),I?.data||[];let $=await V.json(),f=[];for(let O of $){if(O.type!=="dir")continue;let M=`Official ${O.name} skill`;try{let J=await fetch(`https://raw.githubusercontent.com/anthropics/skills/main/skills/${O.name}/SKILL.md`,{headers:{"User-Agent":"Blade-Skills-Catalog"}});if(J.ok){let Y=(await J.text()).match(/^#[^\n]*\n+([^\n#]+)/);if(Y)M=Y[1].trim().slice(0,100)}}catch{}f.push({name:O.name,description:M,tag:"Official",author:"Anthropic"})}return I={data:f,timestamp:Date.now()},f}catch(V){return b.warn("Failed to fetch skills catalog from GitHub:",V),I?.data||[]}}var bf=()=>{let V=new N0;return V.get("/",async($)=>{try{let f=t();await f.initialize();let O=f.getAll(),M=await Df(),J=O.map((j)=>({id:j.name,name:j.name,enabled:!M.disabled.includes(j.name),description:j.description||"",version:j.version||"1.0.0",provider:"Local",location:j.source==="builtin"?"Built-in":j.basePath,capabilities:["prompts"],allowedTools:j.allowedTools||[]}));return $.json(J)}catch(f){return b.error("[SkillsRoutes] Failed to get skills:",f),$.json([])}}),V.post("/:name/toggle",async($)=>{try{let f=$.req.param("name"),O=await $.req.json();return await R0(f,O.enabled),$.json({success:!0,enabled:O.enabled})}catch(f){return b.error("[SkillsRoutes] Failed to toggle skill:",f),$.json({success:!1,error:f.message},500)}}),V.delete("/:name",async($)=>{try{let f=$.req.param("name"),O=`${process.env.HOME}/.blade/skills/${f}`;return await y.rm(O,{recursive:!0,force:!0}),await t().refresh(),$.json({success:!0})}catch(f){return b.error("[SkillsRoutes] Failed to uninstall skill:",f),$.json({success:!1,error:f.message},500)}}),V.post("/install",async($)=>{try{let f=await $.req.json(),O=_f(),M=t(),J=!1;if(f.source==="catalog"&&f.name){if(J=await O.installOfficialSkill(f.name),!J)return $.json({success:!1,error:"Failed to install skill from catalog"},500)}else if(f.source==="repo"&&f.url){if(J=await O.installFromRepo(f.url,f.name),!J)return $.json({success:!1,error:"Failed to install skill from repository. Make sure the repo contains a SKILL.md file."},500)}else if(f.source==="local"&&f.path){if(J=await O.installFromLocal(f.path,f.name),!J)return $.json({success:!1,error:"Failed to install skill from local path. Make sure the path exists and contains a SKILL.md file."},500)}else return $.json({success:!1,error:"Invalid install parameters. Required: source with corresponding url/path/name"},400);return await M.refresh(),$.json({success:!0})}catch(f){return b.error("[SkillsRoutes] Failed to install skill:",f),$.json({success:!1,error:f.message},500)}}),V.get("/catalog",async($)=>{try{let f=await E0();return $.json(f)}catch(f){return b.error("[SkillsRoutes] Failed to get catalog:",f),$.json([])}}),V};import F0 from"fast-glob";import{Hono as U0}from"hono";import{execSync as q0}from"node:child_process";import{readdir as B0}from"node:fs/promises";import i from"node:path";var r=x("Service"),W0=(V)=>{try{return q0("git rev-parse --abbrev-ref HEAD",{cwd:V,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||null}catch{return null}},A0=[...s.map((V)=>`${V}/**`),...s,...Mf.map((V)=>`**/${V}`)],C0=new Set(["/theme","/model","/permissions","/mcp","/skills","/exit","/resume","/ide","/login","/logout"]),Pf=()=>{let V=new U0;return V.get("/commands",async($)=>{try{let f=$.req.query("q")||"",O=Lf(f).filter((M)=>!C0.has(M.command));return $.json(O)}catch(f){return r.error("[SuggestionsRoutes] Failed to get command suggestions:",f),$.json([])}}),V.get("/files",async($)=>{try{let f=$.req.query("q")||"",O=$.get("directory")||R(),M=Math.min(Number($.req.query("limit"))||100,1000),j=(await F0("**/*",{cwd:O,dot:!1,followSymbolicLinks:!1,onlyFiles:!1,markDirectories:!0,unique:!0,ignore:A0})).map((Q)=>Q.replace(/\\/g,"/"));if(!f)return $.json(j.slice(0,M));let Y=f.toLowerCase(),K=j.filter((Q)=>Q.toLowerCase().includes(Y)).slice(0,M);return $.json(K)}catch(f){return r.error("[SuggestionsRoutes] Failed to get file suggestions:",f),$.json([])}}),V.get("/files/tree",async($)=>{try{let f=$.get("directory")||R(),O=$.req.query("path")||"",M=O?i.join(f,O):f,j=(await B0(M,{withFileTypes:!0})).map((Q)=>({name:Q.name,path:O?`${O}/${Q.name}`:Q.name,type:Q.isDirectory()?"dir":"file"}));j.sort((Q,Z)=>{if(Q.type!==Z.type)return Q.type==="dir"?-1:1;return Q.name.localeCompare(Z.name)});let Y=new Set(s),K=j.filter((Q)=>{let Z=Q.name;if(Z.startsWith("."))return!1;if(Y.has(Z))return!1;for(let G of Mf)if(Z.match(new RegExp(G.replace("*",".*"))))return!1;return!0});return $.json(K)}catch(f){return r.error("[SuggestionsRoutes] Failed to get file tree:",f),$.json([])}}),V.get("/files/content",async($)=>{try{let f=$.req.query("path");if(!f)return $.json({error:"Missing file path"},400);let O=$.get("directory")||R(),M=i.resolve(O,f),J=i.relative(O,M);if(J.startsWith("..")||i.isAbsolute(J))return $.json({error:"Invalid file path"},400);let j=wf(),Y=await j.stat(M);if(!Y?.isFile)return $.json({error:"File not found"},404);let K=200000,Q=await j.readTextFile(M),Z=Q.length>K;return $.json({path:f,content:Z?Q.slice(0,K):Q,truncated:Z,size:Y.size})}catch(f){return r.error("[SuggestionsRoutes] Failed to get file content:",f),$.json({error:"Failed to read file"},500)}}),V.get("/git-info",async($)=>{try{let f=$.get("directory")||R(),O=W0(f);return $.json({branch:O})}catch(f){return r.error("[SuggestionsRoutes] Failed to get git info:",f),$.json({branch:null})}}),V};import{Hono as H0}from"hono";var _=x("Service"),v=new Map,kf=2097152,Sf=65536;function uf(){return typeof globalThis.Bun<"u"}async function z0(V,$,f){if(uf()){let{spawn:J}=await import("bun-pty"),j=J(V,$,{name:"xterm-256color",cwd:f.cwd,env:f.env});return{pid:j.pid,write:(Y)=>j.write(Y),resize:(Y,K)=>j.resize(Y,K),kill:()=>j.kill(),onData:(Y)=>j.onData(Y),onExit:(Y)=>j.onExit(Y)}}let M=(await import("node-pty")).spawn(V,$,{name:"xterm-256color",cwd:f.cwd,env:f.env,cols:80,rows:24});return{pid:M.pid,write:(J)=>M.write(J),resize:(J,j)=>M.resize(J,j),kill:()=>M.kill(),onData:(J)=>{M.onData(J)},onExit:(J)=>{M.onExit(J)}}}var Qf=void 0,Jf;if(uf())try{let{createBunWebSocket:V}=await import("hono/bun"),$=V();Jf=$.upgradeWebSocket,Qf=$.websocket}catch(V){_.warn("[Terminal] Failed to initialize Bun WebSocket support:",V)}async function hf(V,$){let f=`term-${Date.now()}`;_.info(`[Terminal] New connection: ${f}, cwd: ${V}`);let O=process.platform==="win32"?"powershell.exe":process.env.SHELL||"/bin/zsh",M=O.endsWith("sh")?["-l"]:[],J=await z0(O,M,{cwd:V,env:{...process.env,TERM:"xterm-256color",COLORTERM:"truecolor"}}),j={id:f,process:J,cwd:V,buffer:"",subscribers:new Set};if(v.set(f,j),j.subscribers.add($),J.onData((Y)=>{let K=!1;for(let Q of j.subscribers)try{Q.send(Y),K=!0}catch{j.subscribers.delete(Q)}if(K)return;if(j.buffer+=Y,j.buffer.length>kf)j.buffer=j.buffer.slice(-kf)}),J.onExit(({exitCode:Y})=>{_.info(`[Terminal] Process exited: ${f}, code: ${Y}`);for(let K of j.subscribers)try{K.close()}catch{}v.delete(f)}),j.buffer){let Y=j.buffer;j.buffer="";for(let K=0;K<Y.length;K+=Sf)$.send(Y.slice(K,K+Sf))}return{session:j,cleanup:()=>{if(_.info(`[Terminal] Connection closed: ${f}`),j.subscribers.delete($),j.subscribers.size===0){try{j.process.kill()}catch{}v.delete(f)}}}}function If(V,$){V.on("connection",async(f,O)=>{let M=new URL(O.url||"/",`http://${O.headers.host}`);if(!M.pathname.endsWith("/terminal/ws")){f.close();return}let J=M.searchParams.get("cwd")||$()||R();try{let{session:j,cleanup:Y}=await hf(J,{send:(K)=>f.send(K),close:()=>f.close()});f.on("message",(K)=>{try{j.process.write(String(K))}catch(Q){_.error("[Terminal] Failed to write to PTY:",Q)}}),f.on("close",Y),f.on("error",Y)}catch(j){_.error("[Terminal] Failed to spawn PTY:",j),f.close()}})}var vf=()=>{let V=new H0;if(V.get("/status",($)=>{let f=Array.from(v.values()).map((O)=>({id:O.id,cwd:O.cwd}));return $.json({active:f.length,terminals:f})}),V.post("/kill/:terminalId",($)=>{let f=$.req.param("terminalId"),O=v.get(f);if(O){try{O.process.kill()}catch{}for(let M of O.subscribers)M.close();return v.delete(f),$.json({success:!0})}return $.json({success:!1,error:"Terminal not found"},404)}),Jf)V.get("/ws",Jf(($)=>{let f=$.req.query("cwd")||$.get("directory")||R(),O;return{async onOpen(M,J){try{O=await hf(f,{send:(j)=>J.send(j),close:()=>J.close()})}catch(j){_.error("[Terminal] Failed to spawn PTY:",j),J.close()}},onMessage(M){if(!O)return;try{O.session.process.write(String(M.data))}catch(J){_.error("[Terminal] Failed to write to PTY:",J)}},onClose(){O?.cleanup()}}}));else V.get("/ws",($)=>{return $.json({message:"WebSocket endpoint - connect via ws:// protocol",hint:"Use WebSocket client to connect to this endpoint"})});return V};var W=x("Service"),Yf=[];function k0(){let V=b0(L0(import.meta.url)),$=[w(V,"web"),w(R(),"dist/web"),w(R(),"packages/cli/dist/web")];for(let f of $){let O=w(f,"index.html");if(gf(O)){if(e(O,"utf-8").includes("/assets/"))return W.debug(`[Server] Found web dist at: ${f}`),f}}return null}function S0(){let V=new T0;V.onError((f,O)=>{if(W.error("[Server] Request error:",f),f instanceof p)return O.json(f.toObject(),f.statusCode);let M=f instanceof Error?f.message:String(f);return O.json({error:{code:"INTERNAL_ERROR",message:M}},500)}),V.use(async(f,O)=>{let M=process.env.BLADE_SERVER_PASSWORD;if(!M)return O();let J=f.req.path;if(J==="/"||J.startsWith("/assets/")||J.endsWith(".html")||J.endsWith(".js")||J.endsWith(".css"))return O();let j=f.req.header("Authorization");if(!j?.startsWith("Basic "))return f.header("WWW-Authenticate",'Basic realm="Blade Server"'),f.json({error:{code:"UNAUTHORIZED",message:"Authentication required"}},401);let Y=Buffer.from(j.slice(6),"base64").toString(),[K,Q]=Y.split(":"),Z=process.env.BLADE_SERVER_USERNAME??"blade";if(K!==Z||Q!==M)return f.json({error:{code:"UNAUTHORIZED",message:"Invalid credentials"}},401);return O()}),V.use(async(f,O)=>{let M=f.req.path==="/health"||f.req.path==="/global/health"||f.req.path.startsWith("/assets/");if(!M)W.debug(`[Server] ${f.req.method} ${f.req.path}`);let J=Date.now();if(await O(),!M){let j=Date.now()-J;W.debug(`[Server] ${f.req.method} ${f.req.path} - ${f.res.status} (${j}ms)`)}}),V.use(y0({origin(f){if(!f)return;if(f.startsWith("http://localhost:"))return f;if(f.startsWith("http://127.0.0.1:"))return f;if(f==="tauri://localhost"||f==="http://tauri.localhost")return f;if(Yf.includes(f))return f;return}})),V.use(async(f,O)=>{let M=f.req.query("directory")||f.req.header("x-blade-directory")||R();try{M=decodeURIComponent(M)}catch{}return f.set("directory",M),O()}),V.route("/global",Nf()),V.route("/sessions",Wf()),V.route("/configs",Gf()),V.route("/permissions",Cf()),V.route("/providers",yf()),V.route("/models",Xf()),V.route("/suggestions",Pf()),V.route("/terminal",vf()),V.route("/mcp",mf()),V.route("/skills",bf()),V.get("/health",(f)=>{return f.json({healthy:!0,version:u()})});let $=k0();if($)W.info(`[Server] Serving static files from ${$}`),V.get("/assets/*",(f)=>{let O=w($,f.req.path);if(!gf(O))return f.json({error:{code:"NOT_FOUND",message:`File not found: ${f.req.path}`}},404);let M=e(O),J=w0(O).toLowerCase(),Y={".js":"application/javascript",".css":"text/css",".html":"text/html",".json":"application/json",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".svg":"image/svg+xml",".ico":"image/x-icon",".woff":"font/woff",".woff2":"font/woff2",".ttf":"font/ttf",".eot":"application/vnd.ms-fontobject"}[J]||"application/octet-stream";return new Response(M,{headers:{"Content-Type":Y,"Cache-Control":"public, max-age=31536000, immutable"}})}),V.get("/",(f)=>{let O=w($,"index.html"),M=e(O,"utf-8");return f.html(M)}),V.get("*",(f)=>{let O=f.req.path;if(O.includes("."))return f.json({error:{code:"NOT_FOUND",message:`File not found: ${O}`}},404);let M=w($,"index.html"),J=e(M,"utf-8");return f.html(J)});else W.warn('[Server] Web UI not found. Run "cd packages/cli/web && bun run build" to enable web interface.'),V.get("/",(f)=>{return f.json({message:"Blade API Server",version:u(),webUI:!1,hint:'Web UI not built. Run "cd packages/cli/web && bun run build" to enable.',endpoints:{health:"/health",sessions:"/sessions",configs:"/configs",permissions:"/permissions",providers:"/providers"}})}),V.all("*",(f)=>{return f.json({error:{code:"NOT_FOUND",message:`Route not found: ${f.req.path}`}},404)});return V}function u0(){let V=D0(),$=[];for(let f of Object.keys(V)){let O=V[f];if(!O)continue;for(let M of O){if(M.internal||M.family!=="IPv4")continue;if(M.address.startsWith("172."))continue;$.push(M.address)}}return $}function pf(){return typeof globalThis.Bun<"u"}function of(V,$){let f=globalThis.Bun,O=(J)=>{try{return f.serve({hostname:$.hostname,port:J,fetch:V.fetch,idleTimeout:0,websocket:Qf})}catch(j){W.error("Failed to start Bun server:",j);return}},M=$.port===0?O(4096)??O(0):O($.port);if(!M)throw Error(`Failed to start Bun server on port ${$.port}`);return{url:M.url,port:M.port,hostname:M.hostname,stop:async()=>{M.stop(!0)}}}function h0(V,$){return new Promise((f,O)=>{let M=_0(async(Q,Z)=>{let G=new URL(Q.url||"/",`http://${Q.headers.host}`),m=new Headers;for(let[E,N]of Object.entries(Q.headers))if(N)if(Array.isArray(N))for(let F of N)m.append(E,F);else m.set(E,N);let q;if(Q.method!=="GET"&&Q.method!=="HEAD")q=(await new Promise((N)=>{let F=[];Q.on("data",(l)=>F.push(l)),Q.on("end",()=>N(Buffer.concat(F)))})).toString();let L=new Request(G.toString(),{method:Q.method,headers:m,body:q});try{let E=await V.fetch(L);if(Z.statusCode=E.status,E.headers.forEach((N,F)=>{Z.setHeader(F,N)}),E.body){let N=E.body.getReader(),F=async()=>{let{done:l,value:ff}=await N.read();if(l){Z.end();return}return Z.write(ff),F()};await F()}else{let N=await E.text();Z.end(N)}}catch(E){W.error("[Server] Node request error:",E),Z.statusCode=500,Z.end(JSON.stringify({error:{code:"INTERNAL_ERROR",message:"Internal server error"}}))}}),J=new P0({noServer:!0}),j=R();If(J,()=>j),M.on("upgrade",(Q,Z,G)=>{if(new URL(Q.url||"/",`http://${Q.headers.host}`).pathname==="/terminal/ws")J.handleUpgrade(Q,Z,G,(q)=>{J.emit("connection",q,Q)});else Z.destroy()});let Y=(Q)=>{return new Promise((Z,G)=>{M.once("error",(m)=>{if(m.code==="EADDRINUSE")G(m);else G(m)}),M.listen(Q,$.hostname,()=>{let m=M.address();if(m&&typeof m==="object")Z(m.port);else Z(Q)})})};(async()=>{let Q;if($.port===0)try{Q=await Y(4096)}catch{Q=await Y(0)}else Q=await Y($.port);let Z=new URL(`http://${$.hostname==="0.0.0.0"?"localhost":$.hostname}:${Q}`);f({url:Z,port:Q,hostname:$.hostname,stop:async()=>{return new Promise((G)=>{J.close(()=>{M.close(()=>G())})})}})})().catch(O)})}var df;((DV)=>{let V,$;function f(){if(!$)$=S0();return $}DV.getApp=f;function O(j){Yf=j.cors??[];let Y=f();if(pf())V=of(Y,j),W.info(`[Server] Blade server listening on ${V.url} (Bun runtime)`);else throw Error("Blade web server requires Bun runtime. Please run with Bun: `bun run blade web` or install Bun from https://bun.sh");let K=V;return{url:K.url,port:K.port,hostname:K.hostname,stop:async()=>{if(V)await V.stop(),V=void 0,$=void 0,W.info("[Server] Blade server stopped")}}}DV.listen=O;async function M(j){Yf=j.cors??[];let Y=f();if(pf())V=of(Y,j),W.info(`[Server] Blade server listening on ${V.url} (Bun runtime)`);else V=await h0(Y,j),W.info(`[Server] Blade server listening on ${V.url} (Node.js runtime)`);let K=V;return{url:K.url,port:K.port,hostname:K.hostname,stop:async()=>{if(V)await V.stop(),V=void 0,$=void 0,W.info("[Server] Blade server stopped")}}}DV.listenAsync=M;function J(){return V!==void 0}DV.isRunning=J})(df||={});export{I0 as a,v0 as b,u0 as c,df as d};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "blade-code",
3
- "version": "0.5.7",
3
+ "version": "0.5.8",
4
4
  "private": false,
5
5
  "description": "🗡️ Blade Code - 智能代码助手命令行工具",
6
6
  "type": "module",
@@ -1 +0,0 @@
1
- import{t as a,u as b}from"./chunk-pcky0ctg.js";import"./chunk-vppcvxzd.js";import"./chunk-j2ag7hh6.js";export{a as globalOptions,b as cliConfig};