blade-code 0.0.48 → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/blade.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{createRequire as xU}from"node:module";var SU=Object.create;var{getPrototypeOf:CU,defineProperty:w9,getOwnPropertyNames:kU}=Object;var fU=Object.prototype.hasOwnProperty;var m$=($,Z,X)=>{X=$!=null?SU(CU($)):{};let Y=Z||!$||!$.__esModule?w9(X,"default",{value:$,enumerable:!0}):X;for(let Q of kU($))if(!fU.call(Y,Q))w9(Y,Q,{get:()=>$[Q],enumerable:!0});return Y};var hU=($,Z)=>{for(var X in Z)w9($,X,{get:Z[X],enumerable:!0,configurable:!0,set:(Y)=>Z[X]=()=>Y})};var A=($,Z)=>()=>($&&(Z=$($=0)),Z);var V$=xU(import.meta.url);var M8;var ZX=A(()=>{M8={name:"blade-code",version:"0.0
|
|
2
|
+
import{createRequire as xU}from"node:module";var SU=Object.create;var{getPrototypeOf:CU,defineProperty:w9,getOwnPropertyNames:kU}=Object;var fU=Object.prototype.hasOwnProperty;var m$=($,Z,X)=>{X=$!=null?SU(CU($)):{};let Y=Z||!$||!$.__esModule?w9(X,"default",{value:$,enumerable:!0}):X;for(let Q of kU($))if(!fU.call(Y,Q))w9(Y,Q,{get:()=>$[Q],enumerable:!0});return Y};var hU=($,Z)=>{for(var X in Z)w9($,X,{get:Z[X],enumerable:!0,configurable:!0,set:(Y)=>Z[X]=()=>Y})};var A=($,Z)=>()=>($&&(Z=$($=0)),Z);var V$=xU(import.meta.url);var M8;var ZX=A(()=>{M8={name:"blade-code",version:"0.1.0",private:!1,description:"🗡️ Blade Code - 智能代码助手命令行工具",type:"module",bin:{blade:"dist/blade.js"},files:["dist","vendor/ripgrep/**","README.md","CHANGELOG.md"],scripts:{dev:"bun --watch src/blade.tsx",build:"rm -rf dist && bun run scripts/build.ts",start:"bun 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:coverage":"node scripts/test.js all --coverage","test:unit:coverage":"node scripts/test.js unit --coverage","test:integration:coverage":"node scripts/test.js integration --coverage","test:cli:coverage":"node scripts/test.js cli --coverage","test:watch":"vitest --watch --config vitest.config.ts","test:unit:watch":"vitest --watch --config vitest.config.ts --project unit","test:integration:watch":"vitest --watch --config vitest.config.ts --project integration","test:cli:watch":"vitest --watch --config vitest.config.ts --project cli","test:debug":"node scripts/test.js all --debug","test:verbose":"node scripts/test.js all --verbose","test:ci":"vitest run --config vitest.config.ts --coverage --reporter=verbose","test:performance":'vitest --testNamePattern="performance" --verbose',lint:"biome lint src tests","lint:fix":"biome lint --write src tests",format:"biome format --write src tests","format:check":"biome format src tests",check:"biome check src tests","check:fix":"biome check --write src tests","type-check":"tsc --noEmit","check:full":"npm run type-check && npm run lint && npm run format:check && npm run test:ci","security:audit":"pnpm audit","security:test":"bash scripts/run-security-tests.sh","vendor:ripgrep":"node scripts/download-ripgrep.js","vendor:ripgrep:clean":"rm -rf vendor/ripgrep/darwin-* vendor/ripgrep/linux-* vendor/ripgrep/win32-*",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",clean:"rm -rf dist node_modules/.cache coverage",prepare:'test -n "$CI" || bun run build',preflight:"npm run clean && pnpm install && npm run format && npm run lint && npm run build && npm run type-check && npm run test:ci"},keywords:["cli","blade","ai","assistant","agent","llm","tool","qwen","volcengine","smart-tools","code-review","documentation","git-tools"],author:"echoVic",license:"MIT",repository:{type:"git",url:"git+https://github.com/echoVic/blade-code.git"},homepage:"https://github.com/echoVic/blade-code",bugs:{url:"https://github.com/echoVic/blade-code/issues"},engines:{node:">=16.0.0"},devDependencies:{"@biomejs/biome":"^2.2.4","@testing-library/react":"^16.2.0","@testing-library/user-event":"^14.5.0","@types/bun":"^1.3.4","@types/diff":"^8.0.0","@types/inquirer":"^9.0.8","@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.12","@types/react-dom":"^19.1.9","@types/semver":"^7.7.1","@types/uuid":"^10.0.0","@types/write-file-atomic":"^4.0.3","@types/ws":"^8.5.12","@types/yargs":"^17.0.33","@vitest/coverage-v8":"^3.0.0",execa:"^9.6.0",jsdom:"^26.0.0",knip:"^5.80.0","ts-node":"^10.9.2",typescript:"^5.9.2",vitest:"^3.0.0"},optionalDependencies:{"@vscode/ripgrep":"^1.17.0"},dependencies:{"@agentclientprotocol/sdk":"^0.12.0","@anthropic-ai/sdk":"^0.71.2","@azure/identity":"^4.13.0","@google/genai":"^1.34.0","@inkjs/ui":"^2.0.0","@modelcontextprotocol/sdk":"^1.17.4",ahooks:"^3.9.5","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","fullscreen-ink":"^0.1.0","fuse.js":"^7.1.0",glob:"^11.0.3","gray-matter":"^4.0.3",ink:"npm:@jrichman/ink@6.4.6","ink-big-text":"^2.0.0","ink-gradient":"^3.0.0","ink-progress-bar":"^3.0.0","ink-select-input":"^6.2.0","ink-spinner":"^5.0.0","ink-text-input":"^6.0.0",inquirer:"^12.6.3","js-tiktoken":"^1.0.21","lodash-es":"^4.17.21",lowlight:"^3.3.0","lru-cache":"^11.2.4",nanoid:"^5.1.6",openai:"^6.2.0",picomatch:"^4.0.3",pino:"^10.1.0","pino-pretty":"^13.1.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"}}});function M4(){return M8.version}function XX(){return M8.name}function YX(){return M8.description}function QX(){return`v${M8.version} © 2025 Blade Code`}var j8=A(()=>{ZX()});var U$=()=>{};var j4;var N9=A(()=>{U$();j4={currentModelId:"",models:[],temperature:0,maxContextTokens:128000,maxOutputTokens:32768,stream:!0,topP:0.9,topK:50,timeout:180000,theme:"GitHub",language:"zh-CN",fontSize:14,debug:!1,mcpEnabled:!1,mcpServers:{},permissions:{allow:["Bash(pwd)","Bash(which *)","Bash(whoami)","Bash(hostname)","Bash(uname *)","Bash(date)","Bash(echo *)","Bash(ls *)","Bash(tree *)","Bash(git status)","Bash(git log *)","Bash(git diff *)","Bash(git branch *)","Bash(git show *)","Bash(git remote *)","Bash(npm list *)","Bash(npm view *)","Bash(npm outdated *)","Bash(pnpm list *)","Bash(yarn list *)","Bash(pip list *)","Bash(pip show *)"],ask:["Bash(curl *)","Bash(wget *)","Bash(aria2c *)","Bash(axel *)","Bash(rm -rf *)","Bash(rm -r *)","Bash(rm --recursive *)","Bash(nc *)","Bash(netcat *)","Bash(telnet *)","Bash(ncat *)"],deny:["Read(./.env)","Read(./.env.*)","Bash(rm -rf /)","Bash(rm -rf /*)","Bash(sudo *)","Bash(chmod 777 *)","Bash(bash *)","Bash(sh *)","Bash(zsh *)","Bash(fish *)","Bash(dash *)","Bash(eval *)","Bash(source *)","Bash(mkfs *)","Bash(fdisk *)","Bash(dd *)","Bash(format *)","Bash(parted *)","Bash(open http*)","Bash(open https*)","Bash(xdg-open http*)","Bash(xdg-open https*)"]},permissionMode:"default",hooks:{enabled:!1,defaultTimeout:60,timeoutBehavior:"ignore",failureBehavior:"ignore",maxConcurrentHooks:5,PreToolUse:[],PostToolUse:[],PostToolUseFailure:[],PermissionRequest:[],UserPromptSubmit:[],SessionStart:[],SessionEnd:[],Stop:[],SubagentStop:[],Notification:[],Compaction:[]},env:{},disableAllHooks:!1,maxTurns:-1}});import{promises as GX}from"fs";import{merge as qX}from"lodash-es";import KX from"os";import I8 from"path";class u${static instance=null;constructor(){}static getInstance(){if(!u$.instance)u$.instance=new u$;return u$.instance}static resetInstance(){u$.instance=null}async initialize(){try{let $=await this.loadConfigFiles(),Z=await this.loadSettingsFiles(),X={...j4,...$,...Z};if(this.resolveEnvInterpolation(X),X.debug)console.log("[ConfigManager] Configuration loaded successfully");return X}catch($){return console.error("[ConfigManager] Failed to initialize:",$),j4}}async loadConfigFiles(){let $=I8.join(KX.homedir(),".blade","config.json"),Z=I8.join(process.cwd(),".blade","config.json"),X={},Y=await this.loadJsonFile($);if(Y)X={...X,...Y};let Q=await this.loadJsonFile(Z);if(Q){let J={...X.mcpServers||{},...Q.mcpServers||{}};if(X={...X,...Q},Object.keys(J).length>0)X.mcpServers=J}return X}async loadSettingsFiles(){let $=I8.join(KX.homedir(),".blade","settings.json"),Z=I8.join(process.cwd(),".blade","settings.json"),X=I8.join(process.cwd(),".blade","settings.local.json"),Y={},Q=await this.loadJsonFile($);if(Q)Y=this.mergeSettings(Y,Q);let J=await this.loadJsonFile(Z);if(J)Y=this.mergeSettings(Y,J);let G=await this.loadJsonFile(X);if(G)Y=this.mergeSettings(Y,G);return Y}mergeSettings($,Z){let X=JSON.parse(JSON.stringify($));if(Z.permissions){if(!X.permissions)X.permissions={allow:[],ask:[],deny:[]};if(Z.permissions.allow){let Y=[...X.permissions.allow||[],...Z.permissions.allow];X.permissions.allow=Array.from(new Set(Y))}if(Z.permissions.ask){let Y=[...X.permissions.ask||[],...Z.permissions.ask];X.permissions.ask=Array.from(new Set(Y))}if(Z.permissions.deny){let Y=[...X.permissions.deny||[],...Z.permissions.deny];X.permissions.deny=Array.from(new Set(Y))}}if(Z.hooks)X.hooks=qX({},X.hooks,Z.hooks);if(Z.env)X.env=qX({},X.env,Z.env);if(Z.mcpServers)X.mcpServers={...X.mcpServers||{},...Z.mcpServers};if(Z.disableAllHooks!==void 0)X.disableAllHooks=Z.disableAllHooks;if(Z.permissionMode!==void 0)X.permissionMode=Z.permissionMode;if(Z.maxTurns!==void 0)X.maxTurns=Z.maxTurns;return X}resolveEnvInterpolation($){let Z=/\$\{?([A-Z_][A-Z0-9_]*)(:-([^}]+))?\}?/g,X=(Y)=>{if(typeof Y==="string")return Y.replace(Z,(Q,J,G,q)=>{return process.env[J]||q||Q});return Y};for(let[Y,Q]of Object.entries($))if(typeof Q==="string")$[Y]=X(Q)}async loadJsonFile($){try{if(await this.fileExists($)){let Z=await GX.readFile($,"utf-8");return JSON.parse(Z)}}catch(Z){console.warn(`[ConfigManager] Failed to load ${$}:`,Z)}return null}async fileExists($){try{return await GX.access($),!0}catch{return!1}}validateConfig($){let Z=[];if(!$.models||$.models.length===0)Z.push("没有可用的模型配置");if($.models&&$.models.length>0){if(!$.currentModelId)Z.push("未设置当前模型 ID");else if(!$.models.find((Y)=>Y.id===$.currentModelId))Z.push("当前模型 ID 无效")}if(Z.length>0)throw Error(`配置验证失败:
|
|
3
3
|
${Z.map((X)=>` - ${X}`).join(`
|
|
4
4
|
`)}
|
|
5
5
|
|
|
@@ -22,24 +22,24 @@ ${Z.map((X)=>` - ${X}`).join(`
|
|
|
22
22
|
}
|
|
23
23
|
]
|
|
24
24
|
}
|
|
25
|
-
`)}}function b9($,Z={}){let X={...$};if(Z.debug!==void 0)X.debug=Z.debug===""?!0:Z.debug;if(Z.yolo===!0)X.permissionMode="yolo";else if(Z.permissionMode!==void 0)X.permissionMode=Z.permissionMode;if(Z.maxTurns!==void 0)X.maxTurns=Z.maxTurns;return X.systemPrompt=Z.systemPrompt,X.appendSystemPrompt=Z.appendSystemPrompt,X.resumeSessionId=Z.sessionId,X.forkSession=Z.forkSession,X.allowedTools=Z.allowedTools,X.disallowedTools=Z.disallowedTools,X.mcpConfigPaths=Z.mcpConfig,X.strictMcpConfig=Z.strictMcpConfig,X.addDirs=Z.addDir,X.outputFormat=Z.outputFormat,X.inputFormat=Z.inputFormat,X.print=Z.print,X.includePartialMessages=Z.includePartialMessages,X.replayUserMessages=Z.replayUserMessages,X.agentsConfig=Z.agents,X.settingSources=Z.settingSources,X}var WX=A(()=>{N9();U$()});import{promises as dU}from"node:fs";import mU from"node:os";import UX from"node:path";import uU from"pino";async function cU(){let $=UX.join(mU.homedir(),".blade","logs");return await dU.mkdir($,{recursive:!0}),UX.join($,"blade.log")}async function lU(){if(y8)return y8;if(v8)return v8;return v8=(async()=>{let $=await cU();return y8=uU({level:"debug",transport:{target:"pino/file",options:{destination:$}}}),y8})(),v8}function HX(){y8=null,v8=null}class N1{static globalDebugConfig=null;enabled;minLevel;category;pinoLogger=null;constructor($={}){if($.enabled!==void 0)this.enabled=$.enabled;else if(N1.globalDebugConfig!==null)this.enabled=Boolean(N1.globalDebugConfig);else this.enabled=!1;this.minLevel=$.minLevel??0,this.category=$.category??"General",this.initPino()}async initPino(){try{let $=await lU();this.pinoLogger=$.child({category:this.category})}catch($){console.error("[Logger] Failed to initialize pino:",$)}}static setGlobalDebug($){N1.globalDebugConfig=$,HX()}static clearGlobalDebug(){N1.globalDebugConfig=null,HX()}setEnabled($){this.enabled=$}parseDebugFilter($){if(!$)return{enabled:!1};if($===!0||$==="true"||$==="1")return{enabled:!0};let Z=String($).trim();if(!Z)return{enabled:!0};if(Z.startsWith("!"))return{enabled:!0,filter:{mode:"exclude",categories:Z.split(",").map((Q)=>Q.trim().replace(/^!/,"")).filter(Boolean)}};return{enabled:!0,filter:{mode:"include",categories:Z.split(",").map((Y)=>Y.trim()).filter(Boolean)}}}shouldLogCategory($){if(!$)return!0;let Z=this.category.toLowerCase();if($.mode==="include")return $.categories.some((X)=>Z.includes(X.toLowerCase()));return!$.categories.some((X)=>Z.includes(X.toLowerCase()))}shouldLogToConsole($){if(N1.globalDebugConfig!==null){let{enabled:Z,filter:X}=this.parseDebugFilter(N1.globalDebugConfig);if(!Z)return!1;if($<this.minLevel)return!1;return this.shouldLogCategory(X)}return this.enabled&&$>=this.minLevel}log($,...Z){let X=Z.map((Y)=>typeof Y==="object"?JSON.stringify(Y):String(Y)).join(" ");if(this.pinoLogger){let Y=gU[$];this.pinoLogger[Y](X)}if(this.shouldLogToConsole($)){let Y=FX[$],Q=`[${this.category}] [${Y}]`;console.error(Q,...Z)}}debug(...$){this.log(0,...$)}info(...$){this.log(1,...$)}warn(...$){this.log(2,...$)}error(...$){this.log(3,...$)}}function i($,Z){return new N1({...Z,category:$})}var FX,gU,y8=null,v8=null,u0;var B0=A(()=>{((Q)=>{Q[Q.DEBUG=0]="DEBUG";Q[Q.INFO=1]="INFO";Q[Q.WARN=2]="WARN";Q[Q.ERROR=3]="ERROR"})(FX||={});gU={[0]:"debug",[1]:"info",[2]:"warn",[3]:"error"};u0=new N1({category:"General"})});import{Mutex as OX}from"async-mutex";import{merge as iU}from"lodash-es";import{promises as j3}from"node:fs";import zX from"node:os";import L4 from"node:path";import aU from"write-file-atomic";class s1{static instance=null;pendingUpdates=new Map;timers=new Map;fileLocks=new Map;lastSaveError=null;debounceDelay=300;constructor(){}static getInstance(){if(!s1.instance)s1.instance=new s1;return s1.instance}static resetInstance(){if(s1.instance)for(let $ of s1.instance.timers.values())clearTimeout($);s1.instance=null}async save($,Z={}){this.validatePersistableFields($);let X=this.groupUpdatesByTarget($,Z.scope);if(Z.immediate)await Promise.all(Array.from(X.entries()).map(([Y,Q])=>this.flushTarget(Y,Q)));else for(let[Y,Q]of X)this.scheduleSave(Y,Q)}async flush(){for(let Z of this.timers.values())clearTimeout(Z);this.timers.clear();let $=Array.from(this.pendingUpdates.entries()).map(([Z,X])=>this.flushTarget(Z,X));this.pendingUpdates.clear(),await Promise.all($)}getLastSaveError(){return this.lastSaveError}clearLastSaveError(){this.lastSaveError=null}async appendPermissionRule($,Z={}){let X=Z.scope??"local",Y=this.resolveFilePath("settings",X);await this.flushTargetWithModifier(Y,(Q)=>{let J=Q.permissions??{allow:[],ask:[],deny:[]},G={allow:this.dedupeArray([...J.allow||[],$]),ask:J.ask||[],deny:J.deny||[]};return{...Q,permissions:G}})}async appendLocalPermissionRule($,Z={}){await this.appendPermissionRule($,{...Z,scope:"local"})}validatePersistableFields($){for(let Z of Object.keys($)){let X=I2[Z];if(!X)throw Error(`Unknown config field: ${Z}`);if(!X.persistable)throw Error(`Field "${Z}" is non-persistable and cannot be saved to config files. Non-persistable fields are runtime-only and only valid for the current session.`)}}groupUpdatesByTarget($,Z){let X=new Map;for(let[Y,Q]of Object.entries($)){let J=I2[Y];if(!J)continue;let G=Z??J.defaultScope,q=this.resolveFilePath(J.target,G);if(!X.has(q))X.set(q,{});X.get(q)[Y]=Q}return X}resolveFilePath($,Z){if($==="config")return Z==="global"?L4.join(zX.homedir(),".blade","config.json"):L4.join(process.cwd(),".blade","config.json");switch(Z){case"local":return L4.join(process.cwd(),".blade","settings.local.json");case"project":return L4.join(process.cwd(),".blade","settings.json");case"global":return L4.join(zX.homedir(),".blade","settings.json");default:return L4.join(process.cwd(),".blade","settings.local.json")}}scheduleSave($,Z){let X=this.pendingUpdates.get($)??{},Y=this.mergePendingUpdates(X,Z);this.pendingUpdates.set($,Y);let Q=this.timers.get($);if(Q)clearTimeout(Q);let J=setTimeout(async()=>{let G=this.pendingUpdates.get($);if(G){this.pendingUpdates.delete($),this.timers.delete($);try{await this.flushTarget($,G),this.lastSaveError=null}catch(q){let K=q instanceof Error?q:Error(String(q));this.lastSaveError=K,_X.error(`Failed to save config to ${$}:`,K.message),_X.error("Stack trace:",K.stack)}}},this.debounceDelay);this.timers.set($,J)}mergePendingUpdates($,Z){let X={...$};for(let[Y,Q]of Object.entries(Z)){let J=I2[Y];if(!J){X[Y]=Q;continue}switch(J.mergeStrategy){case"replace":X[Y]=Q;break;case"append-dedupe":this.applyAppendDedupe(X,Y,Q);break;case"deep-merge":this.applyDeepMerge(X,Y,Q);break}}return X}async flushTarget($,Z){let X=this.fileLocks.get($);if(!X)X=new OX,this.fileLocks.set($,X);await X.runExclusive(async()=>{await this.performWrite($,Z)})}async flushTargetWithModifier($,Z){let X=this.fileLocks.get($);if(!X)X=new OX,this.fileLocks.set($,X);await X.runExclusive(async()=>{await j3.mkdir(L4.dirname($),{recursive:!0});let Y={};try{let J=await j3.readFile($,"utf-8");Y=JSON.parse(J)}catch{Y={}}let Q=Z(Y);await this.atomicWrite($,Q)})}async performWrite($,Z){await j3.mkdir(L4.dirname($),{recursive:!0});let X={};try{let Q=await j3.readFile($,"utf-8");X=JSON.parse(Q)}catch{X={}}let Y={...X};for(let[Q,J]of Object.entries(Z)){let G=I2[Q];if(!G){Y[Q]=J;continue}switch(G.mergeStrategy){case"replace":Y[Q]=J;break;case"append-dedupe":this.applyAppendDedupe(Y,Q,J);break;case"deep-merge":this.applyDeepMerge(Y,Q,J);break}}await this.atomicWrite($,Y)}applyAppendDedupe($,Z,X){if(Z==="permissions"&&typeof X==="object"&&X!==null){let Y=$[Z]??{allow:[],ask:[],deny:[]},Q=X;$[Z]={allow:this.dedupeArray([...Y.allow||[],...Q.allow||[]]),ask:this.dedupeArray([...Y.ask||[],...Q.ask||[]]),deny:this.dedupeArray([...Y.deny||[],...Q.deny||[]])}}else if(Array.isArray(X)){let Y=Array.isArray($[Z])?$[Z]:[];$[Z]=this.dedupeArray([...Y,...X])}else $[Z]=X}applyDeepMerge($,Z,X){if(typeof X==="object"&&X!==null&&!Array.isArray(X)){let Y=typeof $[Z]==="object"&&$[Z]!==null?$[Z]:{};$[Z]=iU({},Y,X)}else $[Z]=X}dedupeArray($){return Array.from(new Set($))}async atomicWrite($,Z){await aU($,JSON.stringify(Z,null,2),{mode:384,encoding:"utf-8"})}}function S$(){return s1.getInstance()}var _X,I2,JA,GA;var BX=A(()=>{B0();_X=i("Service"),I2={models:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},currentModelId:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},temperature:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},maxContextTokens:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},maxOutputTokens:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},timeout:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},theme:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},language:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},debug:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},permissionMode:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},permissions:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!0},hooks:{target:"settings",defaultScope:"local",mergeStrategy:"deep-merge",persistable:!0},env:{target:"settings",defaultScope:"local",mergeStrategy:"deep-merge",persistable:!0},disableAllHooks:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!0},maxTurns:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!0},mcpServers:{target:"config",defaultScope:"project",mergeStrategy:"replace",persistable:!0},stream:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!1},topP:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!1},topK:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!1},fontSize:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!1},mcpEnabled:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!1},systemPrompt:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},appendSystemPrompt:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},initialMessage:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},resumeSessionId:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},forkSession:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},allowedTools:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},disallowedTools:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},mcpConfigPaths:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},strictMcpConfig:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},addDirs:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},outputFormat:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},inputFormat:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},print:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},includePartialMessages:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},replayUserMessages:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},agentsConfig:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},settingSources:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1}},JA=new Set(Object.entries(I2).filter(([$,Z])=>Z.persistable).map(([$])=>$)),GA=new Set(Object.entries(I2).filter(([$,Z])=>!Z.persistable).map(([$])=>$))});import E8 from"picomatch";class l4{config;constructor($){this.config=$}check($){let Z=l4.buildSignature($),X=this.matchRules(Z,this.config.deny);if(X)return{result:"deny",matchedRule:X.rule,matchType:X.type,reason:`工具调用被拒绝规则阻止: ${X.rule}`};let Y=this.matchRules(Z,this.config.allow);if(Y)return{result:"allow",matchedRule:Y.rule,matchType:Y.type,reason:`工具调用符合允许规则: ${Y.rule}`};let Q=this.matchRules(Z,this.config.ask);if(Q)return{result:"ask",matchedRule:Q.rule,matchType:Q.type,reason:`工具调用需要用户确认: ${Q.rule}`};return{result:"ask",reason:"工具调用未匹配任何规则,默认需要确认"}}static buildSignature($){let{toolName:Z,params:X,tool:Y}=$;try{if(Y?.extractSignatureContent){let Q=Y.extractSignatureContent(X);return Q?`${Z}(${Q})`:Z}return Z}catch(Q){return console.warn(`Failed to build signature for ${Z}:`,Q instanceof Error?Q.message:Q),Z}}static abstractPattern($){let{toolName:Z,params:X,tool:Y}=$;try{if(Y?.abstractPermissionRule){let Q=Y.abstractPermissionRule(X);if(Q==="")return"";return Q?`${Z}(${Q})`:Z}return Z}catch(Q){return console.warn(`Failed to abstract pattern for ${Z}:`,Q instanceof Error?Q.message:Q),Z}}matchRules($,Z){for(let X of Z){let Y=this.matchRule($,X);if(Y)return{rule:X,type:Y}}return null}matchRule($,Z){if($===Z)return"exact";if(Z==="*"||Z==="**")return"wildcard";let X=this.extractToolName($),Y=this.extractToolName(Z);if(!X||!Y)return null;if(Y.includes("*")){if(!E8.isMatch(X,Y,{dot:!0,bash:!0}))return null}else if(X!==Y)return null;if(Z===Y)return"prefix";if(Z.includes("*")){let Q=this.extractParams($),J=this.extractParams(Z);if(J==="*"||J==="**")return"wildcard";if(this.matchParams(Q,J))return J.includes("**")?"glob":"wildcard";if(E8.isMatch($,Z,{dot:!0,bash:!0}))return Z.includes("**")?"glob":"wildcard"}return null}extractParams($){let Z=$.match(/\(([\s\S]*)\)$/);return Z?Z[1]:""}matchParams($,Z){if(!$||!Z)return!1;let X=this.parseParamPairs($),Y=this.parseParamPairs(Z),Q=Object.keys(Y).length>0,J=Object.keys(X).length>0;if(Q!==J)return!1;if(!Q&&!J){if(Z==="*"||Z==="**")return!0;if(Z.includes("*")||Z.includes("{")||Z.includes("?"))return E8.isMatch($,Z,{dot:!0,bash:!0});return $===Z}for(let[G,q]of Object.entries(Y)){let K=X[G];if(K===void 0)return!1;if(q.includes("*")||q.includes("{")||q.includes("?")){if(q==="*"||q==="**")continue;if(!E8.isMatch(K,q,{dot:!0,bash:!0}))return!1}else if(K!==q)return!1}return!0}parseParamPairs($){let Z={},X=this.smartSplit($,",");for(let Y of X){let Q=this.findTopLevelDelimiter(Y,":");if(Q>0){let J=Y.slice(0,Q).trim(),G=Y.slice(Q+1).trim();Z[J]=G}}return Z}smartSplit($,Z){let X=[],Y="",Q=0,J=0,G=0,q=!1,K="",W=!1;for(let U=0;U<$.length;U++){let H=$[U];if(W){Y+=H,W=!1;continue}if(H==="\\"){Y+=H,W=!0;continue}if(!q&&H==="{")Q++;else if(!q&&H==="}")Q--;else if(!q&&H==="(")J++;else if(!q&&H===")")J--;else if(!q&&H==="[")G++;else if(!q&&H==="]")G--;if((H==='"'||H==="'")&&!q){q=!0,K=H,Y+=H;continue}else if(q&&H===K){q=!1,K="",Y+=H;continue}if(H===Z&&Q===0&&J===0&&G===0&&!q)X.push(Y.trim()),Y="";else Y+=H}if(Y)X.push(Y.trim());return X}findTopLevelDelimiter($,Z){let X=0,Y=0,Q=0,J=!1,G="",q=!1;for(let K=0;K<$.length;K++){let W=$[K];if(q){q=!1;continue}if(W==="\\"){q=!0;continue}if(!J&&W==="{")X++;else if(!J&&W==="}")X--;else if(!J&&W==="(")Y++;else if(!J&&W===")")Y--;else if(!J&&W==="[")Q++;else if(!J&&W==="]")Q--;if((W==='"'||W==="'")&&!J){J=!0,G=W;continue}else if(J&&W===G){J=!1,G="";continue}if(W===Z&&X===0&&Y===0&&Q===0&&!J)return K}return-1}extractToolName($){let Z=$.match(/^([A-Za-z0-9_]+)(\(|$)/);return Z?Z[1]:null}isAllowed($){return this.check($).result==="allow"}isDenied($){return this.check($).result==="deny"}needsConfirmation($){return this.check($).result==="ask"}updateConfig($){if($.allow)this.config.allow=[...this.config.allow,...$.allow];if($.ask)this.config.ask=[...this.config.ask,...$.ask];if($.deny)this.config.deny=[...this.config.deny,...$.deny]}replaceConfig($){this.config={...$}}getConfig(){return{...this.config}}}var A9=()=>{};var y2=A(()=>{WX();BX();N9();A9();U$()});var nU,oU,sU,tU,eU,$H,ZH,XH,YH,QH,JH,GH,qH,t1;var R9=A(()=>{nU={name:"ayu-dark",colors:{primary:"#ffcc66",secondary:"#bae67e",accent:"#73d0ff",success:"#bae67e",warning:"#ffcc66",error:"#ff3333",info:"#73d0ff",light:"#f0f0f0",dark:"#000000",muted:"#5c6773",highlight:"#2d323b",text:{primary:"#e6e1cf",secondary:"#bae67e",muted:"#5c6773",light:"#ffffff"},background:{primary:"#0f1419",secondary:"#14191f",dark:"#000000"},border:{light:"#2d323b",dark:"#000000"},syntax:{comment:"#5c6773",string:"#bae67e",number:"#ffcc66",keyword:"#ff8f40",function:"#73d0ff",variable:"#e6e1cf",operator:"#f29e74",type:"#73d0ff",tag:"#ff8f40",attr:"#ffd580",default:"#e6e1cf"}},spacing:{xs:0.25,sm:0.5,md:1,lg:1.5,xl:2},typography:{fontSize:{xs:0.75,sm:0.875,base:1,lg:1.125,xl:1.25,"2xl":1.5,"3xl":1.875},fontWeight:{light:300,normal:400,medium:500,semibold:600,bold:700}},borderRadius:{sm:0.125,base:0.25,lg:0.5,xl:0.75},boxShadow:{sm:"0 1px 2px 0 rgba(0, 0, 0, 0.2)",base:"0 1px 3px 0 rgba(0, 0, 0, 0.3), 0 1px 2px 0 rgba(0, 0, 0, 0.2)",lg:"0 10px 15px -3px rgba(0, 0, 0, 0.3), 0 4px 6px -2px rgba(0, 0, 0, 0.2)"}},oU={name:"dracula",colors:{primary:"#bd93f9",secondary:"#ffb86c",accent:"#ff79c6",success:"#50fa7b",warning:"#f1fa8c",error:"#ff5555",info:"#8be9fd",light:"#f8f8f2",dark:"#282a36",muted:"#6272a4",highlight:"#44475a",text:{primary:"#f8f8f2",secondary:"#f1fa8c",muted:"#6272a4",light:"#ffffff"},background:{primary:"#282a36",secondary:"#44475a",dark:"#21222c"},border:{light:"#44475a",dark:"#000000"},syntax:{comment:"#6272a4",string:"#f1fa8c",number:"#bd93f9",keyword:"#ff79c6",function:"#50fa7b",variable:"#f8f8f2",operator:"#ff79c6",type:"#8be9fd",tag:"#ff79c6",attr:"#50fa7b",default:"#f8f8f2"}},spacing:{xs:0.25,sm:0.5,md:1,lg:1.5,xl:2},typography:{fontSize:{xs:0.75,sm:0.875,base:1,lg:1.125,xl:1.25,"2xl":1.5,"3xl":1.875},fontWeight:{light:300,normal:400,medium:500,semibold:600,bold:700}},borderRadius:{sm:0.125,base:0.25,lg:0.5,xl:0.75},boxShadow:{sm:"0 1px 2px 0 rgba(40, 42, 54, 0.2)",base:"0 1px 3px 0 rgba(40, 42, 54, 0.3), 0 1px 2px 0 rgba(40, 42, 54, 0.2)",lg:"0 10px 15px -3px rgba(40, 42, 54, 0.3), 0 4px 6px -2px rgba(40, 42, 54, 0.2)"}},sU={name:"monokai",colors:{primary:"#66d9ef",secondary:"#a6e22e",accent:"#f92672",success:"#a6e22e",warning:"#e6db74",error:"#f92672",info:"#66d9ef",light:"#f8f8f2",dark:"#272822",muted:"#75715e",highlight:"#3e3d32",text:{primary:"#f8f8f2",secondary:"#e6db74",muted:"#75715e",light:"#ffffff"},background:{primary:"#272822",secondary:"#3e3d32",dark:"#1e1f1c"},border:{light:"#3e3d32",dark:"#000000"},syntax:{comment:"#75715e",string:"#e6db74",number:"#ae81ff",keyword:"#f92672",function:"#a6e22e",variable:"#f8f8f2",operator:"#f92672",type:"#66d9ef",tag:"#f92672",attr:"#a6e22e",default:"#f8f8f2"}},spacing:{xs:0.25,sm:0.5,md:1,lg:1.5,xl:2},typography:{fontSize:{xs:0.75,sm:0.875,base:1,lg:1.125,xl:1.25,"2xl":1.5,"3xl":1.875},fontWeight:{light:300,normal:400,medium:500,semibold:600,bold:700}},borderRadius:{sm:0.125,base:0.25,lg:0.5,xl:0.75},boxShadow:{sm:"0 1px 2px 0 rgba(39, 40, 34, 0.2)",base:"0 1px 3px 0 rgba(39, 40, 34, 0.3), 0 1px 2px 0 rgba(39, 40, 34, 0.2)",lg:"0 10px 15px -3px rgba(39, 40, 34, 0.3), 0 4px 6px -2px rgba(39, 40, 34, 0.2)"}},tU={name:"nord",colors:{primary:"#88c0d0",secondary:"#81a1c1",accent:"#b48ead",success:"#a3be8c",warning:"#ebcb8b",error:"#bf616a",info:"#88c0d0",light:"#eceff4",dark:"#2e3440",muted:"#4c566a",highlight:"#434c5e",text:{primary:"#eceff4",secondary:"#d8dee9",muted:"#4c566a",light:"#ffffff"},background:{primary:"#2e3440",secondary:"#3b4252",dark:"#242933"},border:{light:"#434c5e",dark:"#000000"},syntax:{comment:"#616e88",string:"#a3be8c",number:"#b48ead",keyword:"#81a1c1",function:"#88c0d0",variable:"#d8dee9",operator:"#81a1c1",type:"#8fbcbb",tag:"#81a1c1",attr:"#8fbcbb",default:"#eceff4"}},spacing:{xs:0.25,sm:0.5,md:1,lg:1.5,xl:2},typography:{fontSize:{xs:0.75,sm:0.875,base:1,lg:1.125,xl:1.25,"2xl":1.5,"3xl":1.875},fontWeight:{light:300,normal:400,medium:500,semibold:600,bold:700}},borderRadius:{sm:0.125,base:0.25,lg:0.5,xl:0.75},boxShadow:{sm:"0 1px 2px 0 rgba(46, 52, 64, 0.2)",base:"0 1px 3px 0 rgba(46, 52, 64, 0.3), 0 1px 2px 0 rgba(46, 52, 64, 0.2)",lg:"0 10px 15px -3px rgba(46, 52, 64, 0.3), 0 4px 6px -2px rgba(46, 52, 64, 0.2)"}},eU={name:"solarized-light",colors:{primary:"#268bd2",secondary:"#2aa198",accent:"#d33682",success:"#859900",warning:"#b58900",error:"#dc322f",info:"#268bd2",light:"#fdf6e3",dark:"#073642",muted:"#93a1a1",highlight:"#eee8d5",text:{primary:"#586e75",secondary:"#657b83",muted:"#93a1a1",light:"#002b36"},background:{primary:"#fdf6e3",secondary:"#eee8d5",dark:"#073642"},border:{light:"#eee8d5",dark:"#073642"},syntax:{comment:"#93a1a1",string:"#2aa198",number:"#d33682",keyword:"#859900",function:"#268bd2",variable:"#657b83",operator:"#859900",type:"#b58900",tag:"#268bd2",attr:"#93a1a1",default:"#657b83"}},spacing:{xs:0.25,sm:0.5,md:1,lg:1.5,xl:2},typography:{fontSize:{xs:0.75,sm:0.875,base:1,lg:1.125,xl:1.25,"2xl":1.5,"3xl":1.875},fontWeight:{light:300,normal:400,medium:500,semibold:600,bold:700}},borderRadius:{sm:0.125,base:0.25,lg:0.5,xl:0.75},boxShadow:{sm:"0 1px 2px 0 rgba(253, 246, 227, 0.2)",base:"0 1px 3px 0 rgba(253, 246, 227, 0.3), 0 1px 2px 0 rgba(253, 246, 227, 0.2)",lg:"0 10px 15px -3px rgba(253, 246, 227, 0.3), 0 4px 6px -2px rgba(253, 246, 227, 0.2)"}},$H={name:"solarized-dark",colors:{primary:"#268bd2",secondary:"#2aa198",accent:"#d33682",success:"#859900",warning:"#b58900",error:"#dc322f",info:"#268bd2",light:"#fdf6e3",dark:"#073642",muted:"#586e75",highlight:"#073642",text:{primary:"#839496",secondary:"#93a1a1",muted:"#586e75",light:"#fdf6e3"},background:{primary:"#002b36",secondary:"#073642",dark:"#001f29"},border:{light:"#073642",dark:"#000000"},syntax:{comment:"#586e75",string:"#2aa198",number:"#d33682",keyword:"#859900",function:"#268bd2",variable:"#839496",operator:"#859900",type:"#b58900",tag:"#268bd2",attr:"#93a1a1",default:"#839496"}},spacing:{xs:0.25,sm:0.5,md:1,lg:1.5,xl:2},typography:{fontSize:{xs:0.75,sm:0.875,base:1,lg:1.125,xl:1.25,"2xl":1.5,"3xl":1.875},fontWeight:{light:300,normal:400,medium:500,semibold:600,bold:700}},borderRadius:{sm:0.125,base:0.25,lg:0.5,xl:0.75},boxShadow:{sm:"0 1px 2px 0 rgba(0, 43, 54, 0.2)",base:"0 1px 3px 0 rgba(0, 43, 54, 0.3), 0 1px 2px 0 rgba(0, 43, 54, 0.2)",lg:"0 10px 15px -3px rgba(0, 43, 54, 0.3), 0 4px 6px -2px rgba(0, 43, 54, 0.2)"}},ZH={name:"tokyo-night",colors:{primary:"#7aa2f7",secondary:"#7dcfff",accent:"#bb9af7",success:"#9ece6a",warning:"#e0af68",error:"#f7768e",info:"#7aa2f7",light:"#c0caf5",dark:"#1a1b26",muted:"#565f89",highlight:"#292e42",text:{primary:"#a9b1d6",secondary:"#c0caf5",muted:"#565f89",light:"#ffffff"},background:{primary:"#1a1b26",secondary:"#292e42",dark:"#16161e"},border:{light:"#292e42",dark:"#000000"},syntax:{comment:"#565f89",string:"#9ece6a",number:"#ff9e64",keyword:"#bb9af7",function:"#7aa2f7",variable:"#c0caf5",operator:"#89ddff",type:"#7dcfff",tag:"#f7768e",attr:"#7aa2f7",default:"#a9b1d6"}},spacing:{xs:0.25,sm:0.5,md:1,lg:1.5,xl:2},typography:{fontSize:{xs:0.75,sm:0.875,base:1,lg:1.125,xl:1.25,"2xl":1.5,"3xl":1.875},fontWeight:{light:300,normal:400,medium:500,semibold:600,bold:700}},borderRadius:{sm:0.125,base:0.25,lg:0.5,xl:0.75},boxShadow:{sm:"0 1px 2px 0 rgba(26, 27, 38, 0.2)",base:"0 1px 3px 0 rgba(26, 27, 38, 0.3), 0 1px 2px 0 rgba(26, 27, 38, 0.2)",lg:"0 10px 15px -3px rgba(26, 27, 38, 0.3), 0 4px 6px -2px rgba(26, 27, 38, 0.2)"}},XH={name:"github",colors:{primary:"#0969da",secondary:"#8250df",accent:"#bc4c00",success:"#1a7f37",warning:"#9a6700",error:"#d1242f",info:"#0969da",light:"#f6f8fa",dark:"#24292f",muted:"#6e7781",highlight:"#ddf4ff",text:{primary:"#24292f",secondary:"#57606a",muted:"#6e7781",light:"#ffffff"},background:{primary:"#ffffff",secondary:"#f6f8fa",dark:"#24292f"},border:{light:"#d0d7de",dark:"#24292f"},syntax:{comment:"#6e7781",string:"#0a3069",number:"#0550ae",keyword:"#cf222e",function:"#8250df",variable:"#24292f",operator:"#cf222e",type:"#0550ae",tag:"#116329",attr:"#0550ae",default:"#24292f"}},spacing:{xs:0.25,sm:0.5,md:1,lg:1.5,xl:2},typography:{fontSize:{xs:0.75,sm:0.875,base:1,lg:1.125,xl:1.25,"2xl":1.5,"3xl":1.875},fontWeight:{light:300,normal:400,medium:500,semibold:600,bold:700}},borderRadius:{sm:0.125,base:0.25,lg:0.5,xl:0.75},boxShadow:{sm:"0 1px 2px 0 rgba(255, 255, 255, 0.2)",base:"0 1px 3px 0 rgba(255, 255, 255, 0.3), 0 1px 2px 0 rgba(255, 255, 255, 0.2)",lg:"0 10px 15px -3px rgba(255, 255, 255, 0.3), 0 4px 6px -2px rgba(255, 255, 255, 0.2)"}},YH={name:"gruvbox",colors:{primary:"#83a598",secondary:"#8ec07c",accent:"#d3869b",success:"#b8bb26",warning:"#fabd2f",error:"#fb4934",info:"#83a598",light:"#fbf1c7",dark:"#282828",muted:"#928374",highlight:"#3c3836",text:{primary:"#ebdbb2",secondary:"#d5c4a1",muted:"#928374",light:"#ffffff"},background:{primary:"#282828",secondary:"#3c3836",dark:"#1d2021"},border:{light:"#3c3836",dark:"#000000"},syntax:{comment:"#928374",string:"#b8bb26",number:"#d3869b",keyword:"#fb4934",function:"#8ec07c",variable:"#ebdbb2",operator:"#fe8019",type:"#fabd2f",tag:"#fb4934",attr:"#b8bb26",default:"#ebdbb2"}},spacing:{xs:0.25,sm:0.5,md:1,lg:1.5,xl:2},typography:{fontSize:{xs:0.75,sm:0.875,base:1,lg:1.125,xl:1.25,"2xl":1.5,"3xl":1.875},fontWeight:{light:300,normal:400,medium:500,semibold:600,bold:700}},borderRadius:{sm:0.125,base:0.25,lg:0.5,xl:0.75},boxShadow:{sm:"0 1px 2px 0 rgba(40, 40, 40, 0.2)",base:"0 1px 3px 0 rgba(40, 40, 40, 0.3), 0 1px 2px 0 rgba(40, 40, 40, 0.2)",lg:"0 10px 15px -3px rgba(40, 40, 40, 0.3), 0 4px 6px -2px rgba(40, 40, 40, 0.2)"}},QH={name:"one-dark",colors:{primary:"#61afef",secondary:"#c678dd",accent:"#e5c07b",success:"#98c379",warning:"#e5c07b",error:"#e06c75",info:"#56b6c2",light:"#abb2bf",dark:"#282c34",muted:"#5c6370",highlight:"#3e4451",text:{primary:"#abb2bf",secondary:"#c6c8d0",muted:"#5c6370",light:"#ffffff"},background:{primary:"#282c34",secondary:"#3e4451",dark:"#21252b"},border:{light:"#3e4451",dark:"#000000"},syntax:{comment:"#5c6370",string:"#98c379",number:"#d19a66",keyword:"#c678dd",function:"#61afef",variable:"#e06c75",operator:"#56b6c2",type:"#e5c07b",tag:"#e06c75",attr:"#d19a66",default:"#abb2bf"}},spacing:{xs:0.25,sm:0.5,md:1,lg:1.5,xl:2},typography:{fontSize:{xs:0.75,sm:0.875,base:1,lg:1.125,xl:1.25,"2xl":1.5,"3xl":1.875},fontWeight:{light:300,normal:400,medium:500,semibold:600,bold:700}},borderRadius:{sm:0.125,base:0.25,lg:0.5,xl:0.75},boxShadow:{sm:"0 1px 2px 0 rgba(40, 44, 52, 0.2)",base:"0 1px 3px 0 rgba(40, 44, 52, 0.3), 0 1px 2px 0 rgba(40, 44, 52, 0.2)",lg:"0 10px 15px -3px rgba(40, 44, 52, 0.3), 0 4px 6px -2px rgba(40, 44, 52, 0.2)"}},JH={name:"catppuccin",colors:{primary:"#89b4fa",secondary:"#cba6f7",accent:"#f5c2e7",success:"#a6e3a1",warning:"#f9e2af",error:"#f38ba8",info:"#89dceb",light:"#cdd6f4",dark:"#11111b",muted:"#6c7086",highlight:"#181825",text:{primary:"#cdd6f4",secondary:"#bac2de",muted:"#6c7086",light:"#ffffff"},background:{primary:"#1e1e2e",secondary:"#181825",dark:"#11111b"},border:{light:"#181825",dark:"#000000"},syntax:{comment:"#6c7086",string:"#a6e3a1",number:"#fab387",keyword:"#cba6f7",function:"#89b4fa",variable:"#cdd6f4",operator:"#89dceb",type:"#f5c2e7",tag:"#f38ba8",attr:"#89b4fa",default:"#cdd6f4"}},spacing:{xs:0.25,sm:0.5,md:1,lg:1.5,xl:2},typography:{fontSize:{xs:0.75,sm:0.875,base:1,lg:1.125,xl:1.25,"2xl":1.5,"3xl":1.875},fontWeight:{light:300,normal:400,medium:500,semibold:600,bold:700}},borderRadius:{sm:0.125,base:0.25,lg:0.5,xl:0.75},boxShadow:{sm:"0 1px 2px 0 rgba(30, 30, 46, 0.2)",base:"0 1px 3px 0 rgba(30, 30, 46, 0.3), 0 1px 2px 0 rgba(30, 30, 46, 0.2)",lg:"0 10px 15px -3px rgba(30, 30, 46, 0.3), 0 4px 6px -2px rgba(30, 30, 46, 0.2)"}},GH={name:"rose-pine",colors:{primary:"#9ccfd8",secondary:"#c4a7e7",accent:"#f6c177",success:"#31748f",warning:"#f6c177",error:"#eb6f92",info:"#9ccfd8",light:"#e0def4",dark:"#191724",muted:"#6e6a86",highlight:"#1f1d2e",text:{primary:"#e0def4",secondary:"#cecacd",muted:"#6e6a86",light:"#ffffff"},background:{primary:"#191724",secondary:"#1f1d2e",dark:"#12101a"},border:{light:"#1f1d2e",dark:"#000000"},syntax:{comment:"#6e6a86",string:"#9ccfd8",number:"#ea9a97",keyword:"#c4a7e7",function:"#31748f",variable:"#e0def4",operator:"#f6c177",type:"#9ccfd8",tag:"#eb6f92",attr:"#f6c177",default:"#e0def4"}},spacing:{xs:0.25,sm:0.5,md:1,lg:1.5,xl:2},typography:{fontSize:{xs:0.75,sm:0.875,base:1,lg:1.125,xl:1.25,"2xl":1.5,"3xl":1.875},fontWeight:{light:300,normal:400,medium:500,semibold:600,bold:700}},borderRadius:{sm:0.125,base:0.25,lg:0.5,xl:0.75},boxShadow:{sm:"0 1px 2px 0 rgba(25, 23, 36, 0.2)",base:"0 1px 3px 0 rgba(25, 23, 36, 0.3), 0 1px 2px 0 rgba(25, 23, 36, 0.2)",lg:"0 10px 15px -3px rgba(25, 23, 36, 0.3), 0 4px 6px -2px rgba(25, 23, 36, 0.2)"}},qH={name:"kanagawa",colors:{primary:"#8ba4b0",secondary:"#a292a3",accent:"#c47fd5",success:"#76946a",warning:"#c0a36e",error:"#c34043",info:"#7e9cd8",light:"#dcd7ba",dark:"#1f1f28",muted:"#727169",highlight:"#2a2a37",text:{primary:"#dcd7ba",secondary:"#c8c093",muted:"#727169",light:"#ffffff"},background:{primary:"#1f1f28",secondary:"#2a2a37",dark:"#16161d"},border:{light:"#2a2a37",dark:"#000000"},syntax:{comment:"#727169",string:"#98bb6c",number:"#d27e99",keyword:"#957fb8",function:"#7e9cd8",variable:"#dcd7ba",operator:"#c0a36e",type:"#7aa89f",tag:"#c34043",attr:"#7fb4ca",default:"#dcd7ba"}},spacing:{xs:0.25,sm:0.5,md:1,lg:1.5,xl:2},typography:{fontSize:{xs:0.75,sm:0.875,base:1,lg:1.125,xl:1.25,"2xl":1.5,"3xl":1.875},fontWeight:{light:300,normal:400,medium:500,semibold:600,bold:700}},borderRadius:{sm:0.125,base:0.25,lg:0.5,xl:0.75},boxShadow:{sm:"0 1px 2px 0 rgba(31, 31, 40, 0.2)",base:"0 1px 3px 0 rgba(31, 31, 40, 0.3), 0 1px 2px 0 rgba(31, 31, 40, 0.2)",lg:"0 10px 15px -3px rgba(31, 31, 40, 0.3), 0 4px 6px -2px rgba(31, 31, 40, 0.2)"}},t1=[{id:"ayu-dark",label:"Ayu Dark",theme:nU,tags:["dark","popular"]},{id:"dracula",label:"Dracula",theme:oU,tags:["dark","popular"]},{id:"monokai",label:"Monokai",theme:sU,tags:["dark","classic"]},{id:"nord",label:"Nord",theme:tU,tags:["dark","minimal"]},{id:"solarized-light",label:"Solarized Light",theme:eU,tags:["light"]},{id:"solarized-dark",label:"Solarized Dark",theme:$H,tags:["dark"]},{id:"tokyo-night",label:"Tokyo Night",theme:ZH,tags:["dark","popular"]},{id:"github",label:"GitHub",theme:XH,tags:["light","minimal"]},{id:"gruvbox",label:"Gruvbox",theme:YH,tags:["dark","warm"]},{id:"one-dark",label:"One Dark",theme:QH,tags:["dark","popular"]},{id:"catppuccin",label:"Catppuccin",theme:JH,tags:["dark","pastel"]},{id:"rose-pine",label:"Rose Pine",theme:GH,tags:["dark","elegant"]},{id:"kanagawa",label:"Kanagawa",theme:qH,tags:["dark","japanese"]}]});class wX{currentTheme=V9;themes=new Map;constructor(){this.themes.set("default",V9),this.themes.set("dark",KH);for(let $ of t1)this.themes.set($.id,$.theme)}setTheme($){let Z=this.themes.get($);if(Z)this.currentTheme=Z;else throw Error(`Theme '${$}' not found`)}getTheme(){return this.currentTheme}getAvailableThemes(){return Array.from(this.themes.keys())}getCurrentThemeName(){return this.currentTheme.name}getThemeByName($){return this.themes.get($)}hasTheme($){return this.themes.has($)}}var LX,V9,KH,g$;var i4=A(()=>{R9();LX={primary:"#0066cc",secondary:"#6c757d",accent:"#e83e8c",success:"#28a745",warning:"#ffc107",error:"#dc3545",info:"#17a2b8",light:"#f8f9fa",dark:"#343a40",muted:"#6c757d",highlight:"#fff3cd",text:{primary:"#212529",secondary:"#6c757d",muted:"#6c757d",light:"#ffffff"},background:{primary:"#ffffff",secondary:"#f8f9fa",dark:"#343a40"},border:{light:"#dee2e6",dark:"#495057"},syntax:{comment:"#6c757d",string:"#28a745",number:"#e83e8c",keyword:"#007bff",function:"#17a2b8",variable:"#495057",operator:"#ffc107",type:"#007bff",tag:"#dc3545",attr:"#ffc107",default:"#212529"}},V9={name:"default",colors:LX,spacing:{xs:0.25,sm:0.5,md:1,lg:1.5,xl:2},typography:{fontSize:{xs:0.75,sm:0.875,base:1,lg:1.125,xl:1.25,"2xl":1.5,"3xl":1.875},fontWeight:{light:300,normal:400,medium:500,semibold:600,bold:700}},borderRadius:{sm:0.125,base:0.25,lg:0.5,xl:0.75},boxShadow:{sm:"0 1px 2px 0 rgba(0, 0, 0, 0.05)",base:"0 1px 3px 0 rgba(0, 0, 0, 0.1), 0 1px 2px 0 rgba(0, 0, 0, 0.06)",lg:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05)"}},KH={...V9,name:"dark",colors:{...LX,text:{primary:"#ffffff",secondary:"#e2e8f0",muted:"#94a3b8",light:"#000000"},background:{primary:"#1e293b",secondary:"#334155",dark:"#0f172a"},border:{light:"#475569",dark:"#64748b"},syntax:{comment:"#94a3b8",string:"#34d399",number:"#f472b6",keyword:"#60a5fa",function:"#06b6d4",variable:"#e2e8f0",operator:"#fbbf24",type:"#60a5fa",tag:"#fb7185",attr:"#fbbf24",default:"#ffffff"}}};g$=new wX});var WH,D9=($)=>({...WH,actions:{setInitializationStatus:(Z)=>{$((X)=>({app:{...X.app,initializationStatus:Z}}))},setInitializationError:(Z)=>{$((X)=>({app:{...X.app,initializationError:Z}}))},setActiveModal:(Z)=>{$((X)=>({app:{...X.app,activeModal:Z}}))},showSessionSelector:(Z)=>{$((X)=>({app:{...X.app,activeModal:"sessionSelector",sessionSelectorData:Z}}))},showModelEditWizard:(Z)=>{$((X)=>({app:{...X.app,activeModal:"modelEditWizard",modelEditorTarget:Z}}))},closeModal:()=>{$((Z)=>({app:{...Z.app,activeModal:"none",sessionSelectorData:void 0,modelEditorTarget:null}}))},setTodos:(Z)=>{$((X)=>({app:{...X.app,todos:Z}}))},updateTodo:(Z)=>{$((X)=>({app:{...X.app,todos:X.app.todos.map((Y)=>Y.id===Z.id?Z:Y)}}))},setAwaitingSecondCtrlC:(Z)=>{$((X)=>({app:{...X.app,awaitingSecondCtrlC:Z}}))},setThinkingModeEnabled:(Z)=>{$((X)=>({app:{...X.app,thinkingModeEnabled:Z}}))},toggleThinkingMode:()=>{$((Z)=>({app:{...Z.app,thinkingModeEnabled:!Z.app.thinkingModeEnabled}}))}}});var NX=A(()=>{WH={initializationStatus:"idle",initializationError:null,activeModal:"none",sessionSelectorData:void 0,modelEditorTarget:null,todos:[],awaitingSecondCtrlC:!1,thinkingModeEnabled:!1}});var UH,M9=($,Z)=>({...UH,actions:{setProcessing:(X)=>{$((Y)=>({command:{...Y.command,isProcessing:X}}))},createAbortController:()=>{let X=Z().command.abortController;if(X&&!X.signal.aborted)return X;let Y=new AbortController;return $((Q)=>({command:{...Q.command,abortController:Y}})),Y},getAbortController:()=>{return Z().command.abortController},clearAbortController:(X)=>{let Y=Z().command.abortController;if(X!==void 0&&Y!==X)return;$((Q)=>({command:{...Q.command,abortController:null}}))},abort:()=>{let{abortController:X}=Z().command;if(X&&!X.signal.aborted)X.abort();$((Y)=>({command:{...Y.command,isProcessing:!1,pendingCommands:[]}}))},enqueueCommand:(X)=>{$((Y)=>({command:{...Y.command,pendingCommands:[...Y.command.pendingCommands,X]}}))},dequeueCommand:()=>{let{pendingCommands:X}=Z().command;if(X.length===0)return;let[Y,...Q]=X;return $((J)=>({command:{...J.command,pendingCommands:Q}})),Y},clearQueue:()=>{$((X)=>({command:{...X.command,pendingCommands:[]}}))}}});var bX=A(()=>{UH={isProcessing:!1,abortController:null,pendingCommands:[]}});var HH,j9=($)=>({...HH,actions:{setConfig:(Z)=>{$((X)=>({config:{...X.config,config:Z}}))},updateConfig:(Z)=>{$((X)=>{if(!X.config.config)throw Error(`[ConfigSlice] Config not initialized. Cannot update: ${JSON.stringify(Z)}`);return{config:{...X.config,config:{...X.config.config,...Z}}}})}}});var AX=A(()=>{HH={config:null}});var FH,I9=($)=>({...FH,actions:{setFocus:(Z)=>{$((X)=>({focus:{...X.focus,currentFocus:Z,previousFocus:X.focus.currentFocus}}))},restorePreviousFocus:()=>{$((Z)=>({focus:{...Z.focus,currentFocus:Z.focus.previousFocus||"main-input",previousFocus:null}}))}}});var RX=A(()=>{FH={currentFocus:"main-input",previousFocus:null}});function a4($){let Z=[],X=$.split(/\r?\n/),Y=!1,Q=[],J=null,G=0,q=!1,K=[],W=[],U=!1,H=[],F=!0;for(let O=0;O<X.length;O++){let z=X[O];if(U){if(z.match(I0.diffEnd)){try{let v=JSON.parse(H.join(`
|
|
25
|
+
`)}}function b9($,Z={}){let X={...$};if(Z.debug!==void 0)X.debug=Z.debug===""?!0:Z.debug;if(Z.yolo===!0)X.permissionMode="yolo";else if(Z.permissionMode!==void 0)X.permissionMode=Z.permissionMode;if(Z.maxTurns!==void 0)X.maxTurns=Z.maxTurns;return X.systemPrompt=Z.systemPrompt,X.appendSystemPrompt=Z.appendSystemPrompt,X.resumeSessionId=Z.sessionId,X.forkSession=Z.forkSession,X.allowedTools=Z.allowedTools,X.disallowedTools=Z.disallowedTools,X.mcpConfigPaths=Z.mcpConfig,X.strictMcpConfig=Z.strictMcpConfig,X.addDirs=Z.addDir,X.outputFormat=Z.outputFormat,X.inputFormat=Z.inputFormat,X.print=Z.print,X.includePartialMessages=Z.includePartialMessages,X.replayUserMessages=Z.replayUserMessages,X.agentsConfig=Z.agents,X.settingSources=Z.settingSources,X}var WX=A(()=>{N9();U$()});import{promises as dU}from"node:fs";import mU from"node:os";import UX from"node:path";import uU from"pino";async function cU(){let $=UX.join(mU.homedir(),".blade","logs");return await dU.mkdir($,{recursive:!0}),UX.join($,"blade.log")}async function lU(){if(y8)return y8;if(v8)return v8;return v8=(async()=>{let $=await cU();return y8=uU({level:"debug",transport:{target:"pino/file",options:{destination:$}}}),y8})(),v8}function HX(){y8=null,v8=null}class N1{static globalDebugConfig=null;enabled;minLevel;category;pinoLogger=null;constructor($={}){if($.enabled!==void 0)this.enabled=$.enabled;else if(N1.globalDebugConfig!==null)this.enabled=Boolean(N1.globalDebugConfig);else this.enabled=!1;this.minLevel=$.minLevel??0,this.category=$.category??"General",this.initPino()}async initPino(){try{let $=await lU();this.pinoLogger=$.child({category:this.category})}catch($){console.error("[Logger] Failed to initialize pino:",$)}}static setGlobalDebug($){N1.globalDebugConfig=$,HX()}static clearGlobalDebug(){N1.globalDebugConfig=null,HX()}setEnabled($){this.enabled=$}parseDebugFilter($){if(!$)return{enabled:!1};if($===!0||$==="true"||$==="1")return{enabled:!0};let Z=String($).trim();if(!Z)return{enabled:!0};if(Z.startsWith("!"))return{enabled:!0,filter:{mode:"exclude",categories:Z.split(",").map((Q)=>Q.trim().replace(/^!/,"")).filter(Boolean)}};return{enabled:!0,filter:{mode:"include",categories:Z.split(",").map((Y)=>Y.trim()).filter(Boolean)}}}shouldLogCategory($){if(!$)return!0;let Z=this.category.toLowerCase();if($.mode==="include")return $.categories.some((X)=>Z.includes(X.toLowerCase()));return!$.categories.some((X)=>Z.includes(X.toLowerCase()))}shouldLogToConsole($){if(N1.globalDebugConfig!==null){let{enabled:Z,filter:X}=this.parseDebugFilter(N1.globalDebugConfig);if(!Z)return!1;if($<this.minLevel)return!1;return this.shouldLogCategory(X)}return this.enabled&&$>=this.minLevel}log($,...Z){let X=Z.map((Y)=>typeof Y==="object"?JSON.stringify(Y):String(Y)).join(" ");if(this.pinoLogger){let Y=gU[$];this.pinoLogger[Y](X)}if(this.shouldLogToConsole($)){let Y=FX[$],Q=`[${this.category}] [${Y}]`;console.error(Q,...Z)}}debug(...$){this.log(0,...$)}info(...$){this.log(1,...$)}warn(...$){this.log(2,...$)}error(...$){this.log(3,...$)}}function i($,Z){return new N1({...Z,category:$})}var FX,gU,y8=null,v8=null,u0;var B0=A(()=>{((Q)=>{Q[Q.DEBUG=0]="DEBUG";Q[Q.INFO=1]="INFO";Q[Q.WARN=2]="WARN";Q[Q.ERROR=3]="ERROR"})(FX||={});gU={[0]:"debug",[1]:"info",[2]:"warn",[3]:"error"};u0=new N1({category:"General"})});import{Mutex as OX}from"async-mutex";import{merge as iU}from"lodash-es";import{promises as j3}from"node:fs";import zX from"node:os";import L2 from"node:path";import aU from"write-file-atomic";class s1{static instance=null;pendingUpdates=new Map;timers=new Map;fileLocks=new Map;lastSaveError=null;debounceDelay=300;constructor(){}static getInstance(){if(!s1.instance)s1.instance=new s1;return s1.instance}static resetInstance(){if(s1.instance)for(let $ of s1.instance.timers.values())clearTimeout($);s1.instance=null}async save($,Z={}){this.validatePersistableFields($);let X=this.groupUpdatesByTarget($,Z.scope);if(Z.immediate)await Promise.all(Array.from(X.entries()).map(([Y,Q])=>this.flushTarget(Y,Q)));else for(let[Y,Q]of X)this.scheduleSave(Y,Q)}async flush(){for(let Z of this.timers.values())clearTimeout(Z);this.timers.clear();let $=Array.from(this.pendingUpdates.entries()).map(([Z,X])=>this.flushTarget(Z,X));this.pendingUpdates.clear(),await Promise.all($)}getLastSaveError(){return this.lastSaveError}clearLastSaveError(){this.lastSaveError=null}async appendPermissionRule($,Z={}){let X=Z.scope??"local",Y=this.resolveFilePath("settings",X);await this.flushTargetWithModifier(Y,(Q)=>{let J=Q.permissions??{allow:[],ask:[],deny:[]},G={allow:this.dedupeArray([...J.allow||[],$]),ask:J.ask||[],deny:J.deny||[]};return{...Q,permissions:G}})}async appendLocalPermissionRule($,Z={}){await this.appendPermissionRule($,{...Z,scope:"local"})}validatePersistableFields($){for(let Z of Object.keys($)){let X=I4[Z];if(!X)throw Error(`Unknown config field: ${Z}`);if(!X.persistable)throw Error(`Field "${Z}" is non-persistable and cannot be saved to config files. Non-persistable fields are runtime-only and only valid for the current session.`)}}groupUpdatesByTarget($,Z){let X=new Map;for(let[Y,Q]of Object.entries($)){let J=I4[Y];if(!J)continue;let G=Z??J.defaultScope,q=this.resolveFilePath(J.target,G);if(!X.has(q))X.set(q,{});X.get(q)[Y]=Q}return X}resolveFilePath($,Z){if($==="config")return Z==="global"?L2.join(zX.homedir(),".blade","config.json"):L2.join(process.cwd(),".blade","config.json");switch(Z){case"local":return L2.join(process.cwd(),".blade","settings.local.json");case"project":return L2.join(process.cwd(),".blade","settings.json");case"global":return L2.join(zX.homedir(),".blade","settings.json");default:return L2.join(process.cwd(),".blade","settings.local.json")}}scheduleSave($,Z){let X=this.pendingUpdates.get($)??{},Y=this.mergePendingUpdates(X,Z);this.pendingUpdates.set($,Y);let Q=this.timers.get($);if(Q)clearTimeout(Q);let J=setTimeout(async()=>{let G=this.pendingUpdates.get($);if(G){this.pendingUpdates.delete($),this.timers.delete($);try{await this.flushTarget($,G),this.lastSaveError=null}catch(q){let K=q instanceof Error?q:Error(String(q));this.lastSaveError=K,_X.error(`Failed to save config to ${$}:`,K.message),_X.error("Stack trace:",K.stack)}}},this.debounceDelay);this.timers.set($,J)}mergePendingUpdates($,Z){let X={...$};for(let[Y,Q]of Object.entries(Z)){let J=I4[Y];if(!J){X[Y]=Q;continue}switch(J.mergeStrategy){case"replace":X[Y]=Q;break;case"append-dedupe":this.applyAppendDedupe(X,Y,Q);break;case"deep-merge":this.applyDeepMerge(X,Y,Q);break}}return X}async flushTarget($,Z){let X=this.fileLocks.get($);if(!X)X=new OX,this.fileLocks.set($,X);await X.runExclusive(async()=>{await this.performWrite($,Z)})}async flushTargetWithModifier($,Z){let X=this.fileLocks.get($);if(!X)X=new OX,this.fileLocks.set($,X);await X.runExclusive(async()=>{await j3.mkdir(L2.dirname($),{recursive:!0});let Y={};try{let J=await j3.readFile($,"utf-8");Y=JSON.parse(J)}catch{Y={}}let Q=Z(Y);await this.atomicWrite($,Q)})}async performWrite($,Z){await j3.mkdir(L2.dirname($),{recursive:!0});let X={};try{let Q=await j3.readFile($,"utf-8");X=JSON.parse(Q)}catch{X={}}let Y={...X};for(let[Q,J]of Object.entries(Z)){let G=I4[Q];if(!G){Y[Q]=J;continue}switch(G.mergeStrategy){case"replace":Y[Q]=J;break;case"append-dedupe":this.applyAppendDedupe(Y,Q,J);break;case"deep-merge":this.applyDeepMerge(Y,Q,J);break}}await this.atomicWrite($,Y)}applyAppendDedupe($,Z,X){if(Z==="permissions"&&typeof X==="object"&&X!==null){let Y=$[Z]??{allow:[],ask:[],deny:[]},Q=X;$[Z]={allow:this.dedupeArray([...Y.allow||[],...Q.allow||[]]),ask:this.dedupeArray([...Y.ask||[],...Q.ask||[]]),deny:this.dedupeArray([...Y.deny||[],...Q.deny||[]])}}else if(Array.isArray(X)){let Y=Array.isArray($[Z])?$[Z]:[];$[Z]=this.dedupeArray([...Y,...X])}else $[Z]=X}applyDeepMerge($,Z,X){if(typeof X==="object"&&X!==null&&!Array.isArray(X)){let Y=typeof $[Z]==="object"&&$[Z]!==null?$[Z]:{};$[Z]=iU({},Y,X)}else $[Z]=X}dedupeArray($){return Array.from(new Set($))}async atomicWrite($,Z){await aU($,JSON.stringify(Z,null,2),{mode:384,encoding:"utf-8"})}}function S$(){return s1.getInstance()}var _X,I4,JA,GA;var BX=A(()=>{B0();_X=i("Service"),I4={models:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},currentModelId:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},temperature:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},maxContextTokens:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},maxOutputTokens:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},timeout:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},theme:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},language:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},debug:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},permissionMode:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},permissions:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!0},hooks:{target:"settings",defaultScope:"local",mergeStrategy:"deep-merge",persistable:!0},env:{target:"settings",defaultScope:"local",mergeStrategy:"deep-merge",persistable:!0},disableAllHooks:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!0},maxTurns:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!0},mcpServers:{target:"config",defaultScope:"project",mergeStrategy:"replace",persistable:!0},stream:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!1},topP:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!1},topK:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!1},fontSize:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!1},mcpEnabled:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!1},systemPrompt:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},appendSystemPrompt:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},initialMessage:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},resumeSessionId:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},forkSession:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},allowedTools:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},disallowedTools:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},mcpConfigPaths:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},strictMcpConfig:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},addDirs:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},outputFormat:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},inputFormat:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},print:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},includePartialMessages:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},replayUserMessages:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},agentsConfig:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},settingSources:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1}},JA=new Set(Object.entries(I4).filter(([$,Z])=>Z.persistable).map(([$])=>$)),GA=new Set(Object.entries(I4).filter(([$,Z])=>!Z.persistable).map(([$])=>$))});import E8 from"picomatch";class l2{config;constructor($){this.config=$}check($){let Z=l2.buildSignature($),X=this.matchRules(Z,this.config.deny);if(X)return{result:"deny",matchedRule:X.rule,matchType:X.type,reason:`工具调用被拒绝规则阻止: ${X.rule}`};let Y=this.matchRules(Z,this.config.allow);if(Y)return{result:"allow",matchedRule:Y.rule,matchType:Y.type,reason:`工具调用符合允许规则: ${Y.rule}`};let Q=this.matchRules(Z,this.config.ask);if(Q)return{result:"ask",matchedRule:Q.rule,matchType:Q.type,reason:`工具调用需要用户确认: ${Q.rule}`};return{result:"ask",reason:"工具调用未匹配任何规则,默认需要确认"}}static buildSignature($){let{toolName:Z,params:X,tool:Y}=$;try{if(Y?.extractSignatureContent){let Q=Y.extractSignatureContent(X);return Q?`${Z}(${Q})`:Z}return Z}catch(Q){return console.warn(`Failed to build signature for ${Z}:`,Q instanceof Error?Q.message:Q),Z}}static abstractPattern($){let{toolName:Z,params:X,tool:Y}=$;try{if(Y?.abstractPermissionRule){let Q=Y.abstractPermissionRule(X);if(Q==="")return"";return Q?`${Z}(${Q})`:Z}return Z}catch(Q){return console.warn(`Failed to abstract pattern for ${Z}:`,Q instanceof Error?Q.message:Q),Z}}matchRules($,Z){for(let X of Z){let Y=this.matchRule($,X);if(Y)return{rule:X,type:Y}}return null}matchRule($,Z){if($===Z)return"exact";if(Z==="*"||Z==="**")return"wildcard";let X=this.extractToolName($),Y=this.extractToolName(Z);if(!X||!Y)return null;if(Y.includes("*")){if(!E8.isMatch(X,Y,{dot:!0,bash:!0}))return null}else if(X!==Y)return null;if(Z===Y)return"prefix";if(Z.includes("*")){let Q=this.extractParams($),J=this.extractParams(Z);if(J==="*"||J==="**")return"wildcard";if(this.matchParams(Q,J))return J.includes("**")?"glob":"wildcard";if(E8.isMatch($,Z,{dot:!0,bash:!0}))return Z.includes("**")?"glob":"wildcard"}return null}extractParams($){let Z=$.match(/\(([\s\S]*)\)$/);return Z?Z[1]:""}matchParams($,Z){if(!$||!Z)return!1;let X=this.parseParamPairs($),Y=this.parseParamPairs(Z),Q=Object.keys(Y).length>0,J=Object.keys(X).length>0;if(Q!==J)return!1;if(!Q&&!J){if(Z==="*"||Z==="**")return!0;if(Z.includes("*")||Z.includes("{")||Z.includes("?"))return E8.isMatch($,Z,{dot:!0,bash:!0});return $===Z}for(let[G,q]of Object.entries(Y)){let K=X[G];if(K===void 0)return!1;if(q.includes("*")||q.includes("{")||q.includes("?")){if(q==="*"||q==="**")continue;if(!E8.isMatch(K,q,{dot:!0,bash:!0}))return!1}else if(K!==q)return!1}return!0}parseParamPairs($){let Z={},X=this.smartSplit($,",");for(let Y of X){let Q=this.findTopLevelDelimiter(Y,":");if(Q>0){let J=Y.slice(0,Q).trim(),G=Y.slice(Q+1).trim();Z[J]=G}}return Z}smartSplit($,Z){let X=[],Y="",Q=0,J=0,G=0,q=!1,K="",W=!1;for(let U=0;U<$.length;U++){let H=$[U];if(W){Y+=H,W=!1;continue}if(H==="\\"){Y+=H,W=!0;continue}if(!q&&H==="{")Q++;else if(!q&&H==="}")Q--;else if(!q&&H==="(")J++;else if(!q&&H===")")J--;else if(!q&&H==="[")G++;else if(!q&&H==="]")G--;if((H==='"'||H==="'")&&!q){q=!0,K=H,Y+=H;continue}else if(q&&H===K){q=!1,K="",Y+=H;continue}if(H===Z&&Q===0&&J===0&&G===0&&!q)X.push(Y.trim()),Y="";else Y+=H}if(Y)X.push(Y.trim());return X}findTopLevelDelimiter($,Z){let X=0,Y=0,Q=0,J=!1,G="",q=!1;for(let K=0;K<$.length;K++){let W=$[K];if(q){q=!1;continue}if(W==="\\"){q=!0;continue}if(!J&&W==="{")X++;else if(!J&&W==="}")X--;else if(!J&&W==="(")Y++;else if(!J&&W===")")Y--;else if(!J&&W==="[")Q++;else if(!J&&W==="]")Q--;if((W==='"'||W==="'")&&!J){J=!0,G=W;continue}else if(J&&W===G){J=!1,G="";continue}if(W===Z&&X===0&&Y===0&&Q===0&&!J)return K}return-1}extractToolName($){let Z=$.match(/^([A-Za-z0-9_]+)(\(|$)/);return Z?Z[1]:null}isAllowed($){return this.check($).result==="allow"}isDenied($){return this.check($).result==="deny"}needsConfirmation($){return this.check($).result==="ask"}updateConfig($){if($.allow)this.config.allow=[...this.config.allow,...$.allow];if($.ask)this.config.ask=[...this.config.ask,...$.ask];if($.deny)this.config.deny=[...this.config.deny,...$.deny]}replaceConfig($){this.config={...$}}getConfig(){return{...this.config}}}var A9=()=>{};var y4=A(()=>{WX();BX();N9();A9();U$()});var nU,oU,sU,tU,eU,$H,ZH,XH,YH,QH,JH,GH,qH,t1;var R9=A(()=>{nU={name:"ayu-dark",colors:{primary:"#ffcc66",secondary:"#bae67e",accent:"#73d0ff",success:"#bae67e",warning:"#ffcc66",error:"#ff3333",info:"#73d0ff",light:"#f0f0f0",dark:"#000000",muted:"#5c6773",highlight:"#2d323b",text:{primary:"#e6e1cf",secondary:"#bae67e",muted:"#5c6773",light:"#ffffff"},background:{primary:"#0f1419",secondary:"#14191f",dark:"#000000"},border:{light:"#2d323b",dark:"#000000"},syntax:{comment:"#5c6773",string:"#bae67e",number:"#ffcc66",keyword:"#ff8f40",function:"#73d0ff",variable:"#e6e1cf",operator:"#f29e74",type:"#73d0ff",tag:"#ff8f40",attr:"#ffd580",default:"#e6e1cf"}},spacing:{xs:0.25,sm:0.5,md:1,lg:1.5,xl:2},typography:{fontSize:{xs:0.75,sm:0.875,base:1,lg:1.125,xl:1.25,"2xl":1.5,"3xl":1.875},fontWeight:{light:300,normal:400,medium:500,semibold:600,bold:700}},borderRadius:{sm:0.125,base:0.25,lg:0.5,xl:0.75},boxShadow:{sm:"0 1px 2px 0 rgba(0, 0, 0, 0.2)",base:"0 1px 3px 0 rgba(0, 0, 0, 0.3), 0 1px 2px 0 rgba(0, 0, 0, 0.2)",lg:"0 10px 15px -3px rgba(0, 0, 0, 0.3), 0 4px 6px -2px rgba(0, 0, 0, 0.2)"}},oU={name:"dracula",colors:{primary:"#bd93f9",secondary:"#ffb86c",accent:"#ff79c6",success:"#50fa7b",warning:"#f1fa8c",error:"#ff5555",info:"#8be9fd",light:"#f8f8f2",dark:"#282a36",muted:"#6272a4",highlight:"#44475a",text:{primary:"#f8f8f2",secondary:"#f1fa8c",muted:"#6272a4",light:"#ffffff"},background:{primary:"#282a36",secondary:"#44475a",dark:"#21222c"},border:{light:"#44475a",dark:"#000000"},syntax:{comment:"#6272a4",string:"#f1fa8c",number:"#bd93f9",keyword:"#ff79c6",function:"#50fa7b",variable:"#f8f8f2",operator:"#ff79c6",type:"#8be9fd",tag:"#ff79c6",attr:"#50fa7b",default:"#f8f8f2"}},spacing:{xs:0.25,sm:0.5,md:1,lg:1.5,xl:2},typography:{fontSize:{xs:0.75,sm:0.875,base:1,lg:1.125,xl:1.25,"2xl":1.5,"3xl":1.875},fontWeight:{light:300,normal:400,medium:500,semibold:600,bold:700}},borderRadius:{sm:0.125,base:0.25,lg:0.5,xl:0.75},boxShadow:{sm:"0 1px 2px 0 rgba(40, 42, 54, 0.2)",base:"0 1px 3px 0 rgba(40, 42, 54, 0.3), 0 1px 2px 0 rgba(40, 42, 54, 0.2)",lg:"0 10px 15px -3px rgba(40, 42, 54, 0.3), 0 4px 6px -2px rgba(40, 42, 54, 0.2)"}},sU={name:"monokai",colors:{primary:"#66d9ef",secondary:"#a6e22e",accent:"#f92672",success:"#a6e22e",warning:"#e6db74",error:"#f92672",info:"#66d9ef",light:"#f8f8f2",dark:"#272822",muted:"#75715e",highlight:"#3e3d32",text:{primary:"#f8f8f2",secondary:"#e6db74",muted:"#75715e",light:"#ffffff"},background:{primary:"#272822",secondary:"#3e3d32",dark:"#1e1f1c"},border:{light:"#3e3d32",dark:"#000000"},syntax:{comment:"#75715e",string:"#e6db74",number:"#ae81ff",keyword:"#f92672",function:"#a6e22e",variable:"#f8f8f2",operator:"#f92672",type:"#66d9ef",tag:"#f92672",attr:"#a6e22e",default:"#f8f8f2"}},spacing:{xs:0.25,sm:0.5,md:1,lg:1.5,xl:2},typography:{fontSize:{xs:0.75,sm:0.875,base:1,lg:1.125,xl:1.25,"2xl":1.5,"3xl":1.875},fontWeight:{light:300,normal:400,medium:500,semibold:600,bold:700}},borderRadius:{sm:0.125,base:0.25,lg:0.5,xl:0.75},boxShadow:{sm:"0 1px 2px 0 rgba(39, 40, 34, 0.2)",base:"0 1px 3px 0 rgba(39, 40, 34, 0.3), 0 1px 2px 0 rgba(39, 40, 34, 0.2)",lg:"0 10px 15px -3px rgba(39, 40, 34, 0.3), 0 4px 6px -2px rgba(39, 40, 34, 0.2)"}},tU={name:"nord",colors:{primary:"#88c0d0",secondary:"#81a1c1",accent:"#b48ead",success:"#a3be8c",warning:"#ebcb8b",error:"#bf616a",info:"#88c0d0",light:"#eceff4",dark:"#2e3440",muted:"#4c566a",highlight:"#434c5e",text:{primary:"#eceff4",secondary:"#d8dee9",muted:"#4c566a",light:"#ffffff"},background:{primary:"#2e3440",secondary:"#3b4252",dark:"#242933"},border:{light:"#434c5e",dark:"#000000"},syntax:{comment:"#616e88",string:"#a3be8c",number:"#b48ead",keyword:"#81a1c1",function:"#88c0d0",variable:"#d8dee9",operator:"#81a1c1",type:"#8fbcbb",tag:"#81a1c1",attr:"#8fbcbb",default:"#eceff4"}},spacing:{xs:0.25,sm:0.5,md:1,lg:1.5,xl:2},typography:{fontSize:{xs:0.75,sm:0.875,base:1,lg:1.125,xl:1.25,"2xl":1.5,"3xl":1.875},fontWeight:{light:300,normal:400,medium:500,semibold:600,bold:700}},borderRadius:{sm:0.125,base:0.25,lg:0.5,xl:0.75},boxShadow:{sm:"0 1px 2px 0 rgba(46, 52, 64, 0.2)",base:"0 1px 3px 0 rgba(46, 52, 64, 0.3), 0 1px 2px 0 rgba(46, 52, 64, 0.2)",lg:"0 10px 15px -3px rgba(46, 52, 64, 0.3), 0 4px 6px -2px rgba(46, 52, 64, 0.2)"}},eU={name:"solarized-light",colors:{primary:"#268bd2",secondary:"#2aa198",accent:"#d33682",success:"#859900",warning:"#b58900",error:"#dc322f",info:"#268bd2",light:"#fdf6e3",dark:"#073642",muted:"#93a1a1",highlight:"#eee8d5",text:{primary:"#586e75",secondary:"#657b83",muted:"#93a1a1",light:"#002b36"},background:{primary:"#fdf6e3",secondary:"#eee8d5",dark:"#073642"},border:{light:"#eee8d5",dark:"#073642"},syntax:{comment:"#93a1a1",string:"#2aa198",number:"#d33682",keyword:"#859900",function:"#268bd2",variable:"#657b83",operator:"#859900",type:"#b58900",tag:"#268bd2",attr:"#93a1a1",default:"#657b83"}},spacing:{xs:0.25,sm:0.5,md:1,lg:1.5,xl:2},typography:{fontSize:{xs:0.75,sm:0.875,base:1,lg:1.125,xl:1.25,"2xl":1.5,"3xl":1.875},fontWeight:{light:300,normal:400,medium:500,semibold:600,bold:700}},borderRadius:{sm:0.125,base:0.25,lg:0.5,xl:0.75},boxShadow:{sm:"0 1px 2px 0 rgba(253, 246, 227, 0.2)",base:"0 1px 3px 0 rgba(253, 246, 227, 0.3), 0 1px 2px 0 rgba(253, 246, 227, 0.2)",lg:"0 10px 15px -3px rgba(253, 246, 227, 0.3), 0 4px 6px -2px rgba(253, 246, 227, 0.2)"}},$H={name:"solarized-dark",colors:{primary:"#268bd2",secondary:"#2aa198",accent:"#d33682",success:"#859900",warning:"#b58900",error:"#dc322f",info:"#268bd2",light:"#fdf6e3",dark:"#073642",muted:"#586e75",highlight:"#073642",text:{primary:"#839496",secondary:"#93a1a1",muted:"#586e75",light:"#fdf6e3"},background:{primary:"#002b36",secondary:"#073642",dark:"#001f29"},border:{light:"#073642",dark:"#000000"},syntax:{comment:"#586e75",string:"#2aa198",number:"#d33682",keyword:"#859900",function:"#268bd2",variable:"#839496",operator:"#859900",type:"#b58900",tag:"#268bd2",attr:"#93a1a1",default:"#839496"}},spacing:{xs:0.25,sm:0.5,md:1,lg:1.5,xl:2},typography:{fontSize:{xs:0.75,sm:0.875,base:1,lg:1.125,xl:1.25,"2xl":1.5,"3xl":1.875},fontWeight:{light:300,normal:400,medium:500,semibold:600,bold:700}},borderRadius:{sm:0.125,base:0.25,lg:0.5,xl:0.75},boxShadow:{sm:"0 1px 2px 0 rgba(0, 43, 54, 0.2)",base:"0 1px 3px 0 rgba(0, 43, 54, 0.3), 0 1px 2px 0 rgba(0, 43, 54, 0.2)",lg:"0 10px 15px -3px rgba(0, 43, 54, 0.3), 0 4px 6px -2px rgba(0, 43, 54, 0.2)"}},ZH={name:"tokyo-night",colors:{primary:"#7aa2f7",secondary:"#7dcfff",accent:"#bb9af7",success:"#9ece6a",warning:"#e0af68",error:"#f7768e",info:"#7aa2f7",light:"#c0caf5",dark:"#1a1b26",muted:"#565f89",highlight:"#292e42",text:{primary:"#a9b1d6",secondary:"#c0caf5",muted:"#565f89",light:"#ffffff"},background:{primary:"#1a1b26",secondary:"#292e42",dark:"#16161e"},border:{light:"#292e42",dark:"#000000"},syntax:{comment:"#565f89",string:"#9ece6a",number:"#ff9e64",keyword:"#bb9af7",function:"#7aa2f7",variable:"#c0caf5",operator:"#89ddff",type:"#7dcfff",tag:"#f7768e",attr:"#7aa2f7",default:"#a9b1d6"}},spacing:{xs:0.25,sm:0.5,md:1,lg:1.5,xl:2},typography:{fontSize:{xs:0.75,sm:0.875,base:1,lg:1.125,xl:1.25,"2xl":1.5,"3xl":1.875},fontWeight:{light:300,normal:400,medium:500,semibold:600,bold:700}},borderRadius:{sm:0.125,base:0.25,lg:0.5,xl:0.75},boxShadow:{sm:"0 1px 2px 0 rgba(26, 27, 38, 0.2)",base:"0 1px 3px 0 rgba(26, 27, 38, 0.3), 0 1px 2px 0 rgba(26, 27, 38, 0.2)",lg:"0 10px 15px -3px rgba(26, 27, 38, 0.3), 0 4px 6px -2px rgba(26, 27, 38, 0.2)"}},XH={name:"github",colors:{primary:"#0969da",secondary:"#8250df",accent:"#bc4c00",success:"#1a7f37",warning:"#9a6700",error:"#d1242f",info:"#0969da",light:"#f6f8fa",dark:"#24292f",muted:"#6e7781",highlight:"#ddf4ff",text:{primary:"#24292f",secondary:"#57606a",muted:"#6e7781",light:"#ffffff"},background:{primary:"#ffffff",secondary:"#f6f8fa",dark:"#24292f"},border:{light:"#d0d7de",dark:"#24292f"},syntax:{comment:"#6e7781",string:"#0a3069",number:"#0550ae",keyword:"#cf222e",function:"#8250df",variable:"#24292f",operator:"#cf222e",type:"#0550ae",tag:"#116329",attr:"#0550ae",default:"#24292f"}},spacing:{xs:0.25,sm:0.5,md:1,lg:1.5,xl:2},typography:{fontSize:{xs:0.75,sm:0.875,base:1,lg:1.125,xl:1.25,"2xl":1.5,"3xl":1.875},fontWeight:{light:300,normal:400,medium:500,semibold:600,bold:700}},borderRadius:{sm:0.125,base:0.25,lg:0.5,xl:0.75},boxShadow:{sm:"0 1px 2px 0 rgba(255, 255, 255, 0.2)",base:"0 1px 3px 0 rgba(255, 255, 255, 0.3), 0 1px 2px 0 rgba(255, 255, 255, 0.2)",lg:"0 10px 15px -3px rgba(255, 255, 255, 0.3), 0 4px 6px -2px rgba(255, 255, 255, 0.2)"}},YH={name:"gruvbox",colors:{primary:"#83a598",secondary:"#8ec07c",accent:"#d3869b",success:"#b8bb26",warning:"#fabd2f",error:"#fb4934",info:"#83a598",light:"#fbf1c7",dark:"#282828",muted:"#928374",highlight:"#3c3836",text:{primary:"#ebdbb2",secondary:"#d5c4a1",muted:"#928374",light:"#ffffff"},background:{primary:"#282828",secondary:"#3c3836",dark:"#1d2021"},border:{light:"#3c3836",dark:"#000000"},syntax:{comment:"#928374",string:"#b8bb26",number:"#d3869b",keyword:"#fb4934",function:"#8ec07c",variable:"#ebdbb2",operator:"#fe8019",type:"#fabd2f",tag:"#fb4934",attr:"#b8bb26",default:"#ebdbb2"}},spacing:{xs:0.25,sm:0.5,md:1,lg:1.5,xl:2},typography:{fontSize:{xs:0.75,sm:0.875,base:1,lg:1.125,xl:1.25,"2xl":1.5,"3xl":1.875},fontWeight:{light:300,normal:400,medium:500,semibold:600,bold:700}},borderRadius:{sm:0.125,base:0.25,lg:0.5,xl:0.75},boxShadow:{sm:"0 1px 2px 0 rgba(40, 40, 40, 0.2)",base:"0 1px 3px 0 rgba(40, 40, 40, 0.3), 0 1px 2px 0 rgba(40, 40, 40, 0.2)",lg:"0 10px 15px -3px rgba(40, 40, 40, 0.3), 0 4px 6px -2px rgba(40, 40, 40, 0.2)"}},QH={name:"one-dark",colors:{primary:"#61afef",secondary:"#c678dd",accent:"#e5c07b",success:"#98c379",warning:"#e5c07b",error:"#e06c75",info:"#56b6c2",light:"#abb2bf",dark:"#282c34",muted:"#5c6370",highlight:"#3e4451",text:{primary:"#abb2bf",secondary:"#c6c8d0",muted:"#5c6370",light:"#ffffff"},background:{primary:"#282c34",secondary:"#3e4451",dark:"#21252b"},border:{light:"#3e4451",dark:"#000000"},syntax:{comment:"#5c6370",string:"#98c379",number:"#d19a66",keyword:"#c678dd",function:"#61afef",variable:"#e06c75",operator:"#56b6c2",type:"#e5c07b",tag:"#e06c75",attr:"#d19a66",default:"#abb2bf"}},spacing:{xs:0.25,sm:0.5,md:1,lg:1.5,xl:2},typography:{fontSize:{xs:0.75,sm:0.875,base:1,lg:1.125,xl:1.25,"2xl":1.5,"3xl":1.875},fontWeight:{light:300,normal:400,medium:500,semibold:600,bold:700}},borderRadius:{sm:0.125,base:0.25,lg:0.5,xl:0.75},boxShadow:{sm:"0 1px 2px 0 rgba(40, 44, 52, 0.2)",base:"0 1px 3px 0 rgba(40, 44, 52, 0.3), 0 1px 2px 0 rgba(40, 44, 52, 0.2)",lg:"0 10px 15px -3px rgba(40, 44, 52, 0.3), 0 4px 6px -2px rgba(40, 44, 52, 0.2)"}},JH={name:"catppuccin",colors:{primary:"#89b4fa",secondary:"#cba6f7",accent:"#f5c2e7",success:"#a6e3a1",warning:"#f9e2af",error:"#f38ba8",info:"#89dceb",light:"#cdd6f4",dark:"#11111b",muted:"#6c7086",highlight:"#181825",text:{primary:"#cdd6f4",secondary:"#bac2de",muted:"#6c7086",light:"#ffffff"},background:{primary:"#1e1e2e",secondary:"#181825",dark:"#11111b"},border:{light:"#181825",dark:"#000000"},syntax:{comment:"#6c7086",string:"#a6e3a1",number:"#fab387",keyword:"#cba6f7",function:"#89b4fa",variable:"#cdd6f4",operator:"#89dceb",type:"#f5c2e7",tag:"#f38ba8",attr:"#89b4fa",default:"#cdd6f4"}},spacing:{xs:0.25,sm:0.5,md:1,lg:1.5,xl:2},typography:{fontSize:{xs:0.75,sm:0.875,base:1,lg:1.125,xl:1.25,"2xl":1.5,"3xl":1.875},fontWeight:{light:300,normal:400,medium:500,semibold:600,bold:700}},borderRadius:{sm:0.125,base:0.25,lg:0.5,xl:0.75},boxShadow:{sm:"0 1px 2px 0 rgba(30, 30, 46, 0.2)",base:"0 1px 3px 0 rgba(30, 30, 46, 0.3), 0 1px 2px 0 rgba(30, 30, 46, 0.2)",lg:"0 10px 15px -3px rgba(30, 30, 46, 0.3), 0 4px 6px -2px rgba(30, 30, 46, 0.2)"}},GH={name:"rose-pine",colors:{primary:"#9ccfd8",secondary:"#c4a7e7",accent:"#f6c177",success:"#31748f",warning:"#f6c177",error:"#eb6f92",info:"#9ccfd8",light:"#e0def4",dark:"#191724",muted:"#6e6a86",highlight:"#1f1d2e",text:{primary:"#e0def4",secondary:"#cecacd",muted:"#6e6a86",light:"#ffffff"},background:{primary:"#191724",secondary:"#1f1d2e",dark:"#12101a"},border:{light:"#1f1d2e",dark:"#000000"},syntax:{comment:"#6e6a86",string:"#9ccfd8",number:"#ea9a97",keyword:"#c4a7e7",function:"#31748f",variable:"#e0def4",operator:"#f6c177",type:"#9ccfd8",tag:"#eb6f92",attr:"#f6c177",default:"#e0def4"}},spacing:{xs:0.25,sm:0.5,md:1,lg:1.5,xl:2},typography:{fontSize:{xs:0.75,sm:0.875,base:1,lg:1.125,xl:1.25,"2xl":1.5,"3xl":1.875},fontWeight:{light:300,normal:400,medium:500,semibold:600,bold:700}},borderRadius:{sm:0.125,base:0.25,lg:0.5,xl:0.75},boxShadow:{sm:"0 1px 2px 0 rgba(25, 23, 36, 0.2)",base:"0 1px 3px 0 rgba(25, 23, 36, 0.3), 0 1px 2px 0 rgba(25, 23, 36, 0.2)",lg:"0 10px 15px -3px rgba(25, 23, 36, 0.3), 0 4px 6px -2px rgba(25, 23, 36, 0.2)"}},qH={name:"kanagawa",colors:{primary:"#8ba4b0",secondary:"#a292a3",accent:"#c47fd5",success:"#76946a",warning:"#c0a36e",error:"#c34043",info:"#7e9cd8",light:"#dcd7ba",dark:"#1f1f28",muted:"#727169",highlight:"#2a2a37",text:{primary:"#dcd7ba",secondary:"#c8c093",muted:"#727169",light:"#ffffff"},background:{primary:"#1f1f28",secondary:"#2a2a37",dark:"#16161d"},border:{light:"#2a2a37",dark:"#000000"},syntax:{comment:"#727169",string:"#98bb6c",number:"#d27e99",keyword:"#957fb8",function:"#7e9cd8",variable:"#dcd7ba",operator:"#c0a36e",type:"#7aa89f",tag:"#c34043",attr:"#7fb4ca",default:"#dcd7ba"}},spacing:{xs:0.25,sm:0.5,md:1,lg:1.5,xl:2},typography:{fontSize:{xs:0.75,sm:0.875,base:1,lg:1.125,xl:1.25,"2xl":1.5,"3xl":1.875},fontWeight:{light:300,normal:400,medium:500,semibold:600,bold:700}},borderRadius:{sm:0.125,base:0.25,lg:0.5,xl:0.75},boxShadow:{sm:"0 1px 2px 0 rgba(31, 31, 40, 0.2)",base:"0 1px 3px 0 rgba(31, 31, 40, 0.3), 0 1px 2px 0 rgba(31, 31, 40, 0.2)",lg:"0 10px 15px -3px rgba(31, 31, 40, 0.3), 0 4px 6px -2px rgba(31, 31, 40, 0.2)"}},t1=[{id:"ayu-dark",label:"Ayu Dark",theme:nU,tags:["dark","popular"]},{id:"dracula",label:"Dracula",theme:oU,tags:["dark","popular"]},{id:"monokai",label:"Monokai",theme:sU,tags:["dark","classic"]},{id:"nord",label:"Nord",theme:tU,tags:["dark","minimal"]},{id:"solarized-light",label:"Solarized Light",theme:eU,tags:["light"]},{id:"solarized-dark",label:"Solarized Dark",theme:$H,tags:["dark"]},{id:"tokyo-night",label:"Tokyo Night",theme:ZH,tags:["dark","popular"]},{id:"github",label:"GitHub",theme:XH,tags:["light","minimal"]},{id:"gruvbox",label:"Gruvbox",theme:YH,tags:["dark","warm"]},{id:"one-dark",label:"One Dark",theme:QH,tags:["dark","popular"]},{id:"catppuccin",label:"Catppuccin",theme:JH,tags:["dark","pastel"]},{id:"rose-pine",label:"Rose Pine",theme:GH,tags:["dark","elegant"]},{id:"kanagawa",label:"Kanagawa",theme:qH,tags:["dark","japanese"]}]});class wX{currentTheme=V9;themes=new Map;constructor(){this.themes.set("default",V9),this.themes.set("dark",KH);for(let $ of t1)this.themes.set($.id,$.theme)}setTheme($){let Z=this.themes.get($);if(Z)this.currentTheme=Z;else throw Error(`Theme '${$}' not found`)}getTheme(){return this.currentTheme}getAvailableThemes(){return Array.from(this.themes.keys())}getCurrentThemeName(){return this.currentTheme.name}getThemeByName($){return this.themes.get($)}hasTheme($){return this.themes.has($)}}var LX,V9,KH,g$;var i2=A(()=>{R9();LX={primary:"#0066cc",secondary:"#6c757d",accent:"#e83e8c",success:"#28a745",warning:"#ffc107",error:"#dc3545",info:"#17a2b8",light:"#f8f9fa",dark:"#343a40",muted:"#6c757d",highlight:"#fff3cd",text:{primary:"#212529",secondary:"#6c757d",muted:"#6c757d",light:"#ffffff"},background:{primary:"#ffffff",secondary:"#f8f9fa",dark:"#343a40"},border:{light:"#dee2e6",dark:"#495057"},syntax:{comment:"#6c757d",string:"#28a745",number:"#e83e8c",keyword:"#007bff",function:"#17a2b8",variable:"#495057",operator:"#ffc107",type:"#007bff",tag:"#dc3545",attr:"#ffc107",default:"#212529"}},V9={name:"default",colors:LX,spacing:{xs:0.25,sm:0.5,md:1,lg:1.5,xl:2},typography:{fontSize:{xs:0.75,sm:0.875,base:1,lg:1.125,xl:1.25,"2xl":1.5,"3xl":1.875},fontWeight:{light:300,normal:400,medium:500,semibold:600,bold:700}},borderRadius:{sm:0.125,base:0.25,lg:0.5,xl:0.75},boxShadow:{sm:"0 1px 2px 0 rgba(0, 0, 0, 0.05)",base:"0 1px 3px 0 rgba(0, 0, 0, 0.1), 0 1px 2px 0 rgba(0, 0, 0, 0.06)",lg:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05)"}},KH={...V9,name:"dark",colors:{...LX,text:{primary:"#ffffff",secondary:"#e2e8f0",muted:"#94a3b8",light:"#000000"},background:{primary:"#1e293b",secondary:"#334155",dark:"#0f172a"},border:{light:"#475569",dark:"#64748b"},syntax:{comment:"#94a3b8",string:"#34d399",number:"#f472b6",keyword:"#60a5fa",function:"#06b6d4",variable:"#e2e8f0",operator:"#fbbf24",type:"#60a5fa",tag:"#fb7185",attr:"#fbbf24",default:"#ffffff"}}};g$=new wX});var WH,D9=($)=>({...WH,actions:{setInitializationStatus:(Z)=>{$((X)=>({app:{...X.app,initializationStatus:Z}}))},setInitializationError:(Z)=>{$((X)=>({app:{...X.app,initializationError:Z}}))},setActiveModal:(Z)=>{$((X)=>({app:{...X.app,activeModal:Z}}))},showSessionSelector:(Z)=>{$((X)=>({app:{...X.app,activeModal:"sessionSelector",sessionSelectorData:Z}}))},showModelEditWizard:(Z)=>{$((X)=>({app:{...X.app,activeModal:"modelEditWizard",modelEditorTarget:Z}}))},closeModal:()=>{$((Z)=>({app:{...Z.app,activeModal:"none",sessionSelectorData:void 0,modelEditorTarget:null}}))},setTodos:(Z)=>{$((X)=>({app:{...X.app,todos:Z}}))},updateTodo:(Z)=>{$((X)=>({app:{...X.app,todos:X.app.todos.map((Y)=>Y.id===Z.id?Z:Y)}}))},setAwaitingSecondCtrlC:(Z)=>{$((X)=>({app:{...X.app,awaitingSecondCtrlC:Z}}))},setThinkingModeEnabled:(Z)=>{$((X)=>({app:{...X.app,thinkingModeEnabled:Z}}))},toggleThinkingMode:()=>{$((Z)=>({app:{...Z.app,thinkingModeEnabled:!Z.app.thinkingModeEnabled}}))}}});var NX=A(()=>{WH={initializationStatus:"idle",initializationError:null,activeModal:"none",sessionSelectorData:void 0,modelEditorTarget:null,todos:[],awaitingSecondCtrlC:!1,thinkingModeEnabled:!1}});var UH,M9=($,Z)=>({...UH,actions:{setProcessing:(X)=>{$((Y)=>({command:{...Y.command,isProcessing:X}}))},createAbortController:()=>{let X=Z().command.abortController;if(X&&!X.signal.aborted)return X;let Y=new AbortController;return $((Q)=>({command:{...Q.command,abortController:Y}})),Y},getAbortController:()=>{return Z().command.abortController},clearAbortController:(X)=>{let Y=Z().command.abortController;if(X!==void 0&&Y!==X)return;$((Q)=>({command:{...Q.command,abortController:null}}))},abort:()=>{let{abortController:X}=Z().command;if(X&&!X.signal.aborted)X.abort();$((Y)=>({command:{...Y.command,isProcessing:!1,pendingCommands:[]}}))},enqueueCommand:(X)=>{$((Y)=>({command:{...Y.command,pendingCommands:[...Y.command.pendingCommands,X]}}))},dequeueCommand:()=>{let{pendingCommands:X}=Z().command;if(X.length===0)return;let[Y,...Q]=X;return $((J)=>({command:{...J.command,pendingCommands:Q}})),Y},clearQueue:()=>{$((X)=>({command:{...X.command,pendingCommands:[]}}))}}});var bX=A(()=>{UH={isProcessing:!1,abortController:null,pendingCommands:[]}});var HH,j9=($)=>({...HH,actions:{setConfig:(Z)=>{$((X)=>({config:{...X.config,config:Z}}))},updateConfig:(Z)=>{$((X)=>{if(!X.config.config)throw Error(`[ConfigSlice] Config not initialized. Cannot update: ${JSON.stringify(Z)}`);return{config:{...X.config,config:{...X.config.config,...Z}}}})}}});var AX=A(()=>{HH={config:null}});var FH,I9=($)=>({...FH,actions:{setFocus:(Z)=>{$((X)=>({focus:{...X.focus,currentFocus:Z,previousFocus:X.focus.currentFocus}}))},restorePreviousFocus:()=>{$((Z)=>({focus:{...Z.focus,currentFocus:Z.focus.previousFocus||"main-input",previousFocus:null}}))}}});var RX=A(()=>{FH={currentFocus:"main-input",previousFocus:null}});function a2($){let Z=[],X=$.split(/\r?\n/),Y=!1,Q=[],J=null,G=0,q=!1,K=[],W=[],U=!1,H=[],F=!0;for(let O=0;O<X.length;O++){let z=X[O];if(U){if(z.match(I0.diffEnd)){try{let v=JSON.parse(H.join(`
|
|
26
26
|
`));Z.push({type:"diff",content:"",diffData:{patch:v.patch,startLine:v.startLine,matchLine:v.matchLine}})}catch(v){Z.push({type:"text",content:H.join(`
|
|
27
27
|
`)})}U=!1,H=[],F=!1;continue}H.push(z);continue}if(z.match(I0.diffStart)){U=!0,H=[],F=!1;continue}if(Y){let v=z.match(I0.codeBlock),N=z.trim()==="```";if(v&&v[1])G++,Q.push(z);else if(N)if(G>0)G--,Q.push(z);else{let k=Q.join(`
|
|
28
|
-
`);if(J?.toLowerCase()==="markdown"||J?.toLowerCase()==="md"){let m=
|
|
29
|
-
`);if(J?.toLowerCase()==="markdown"||J?.toLowerCase()==="md"){let z=
|
|
30
|
-
`);if($.codeBlockLang?.toLowerCase()==="markdown"||$.codeBlockLang?.toLowerCase()==="md")Z.push(...
|
|
28
|
+
`);if(J?.toLowerCase()==="markdown"||J?.toLowerCase()==="md"){let m=a2(k);Z.push(...m)}else Z.push({type:"code",content:k,language:J||void 0});Y=!1,Q=[],J=null,G=0,F=!1}else Q.push(z);continue}let _=z.match(I0.codeBlock);if(_){Y=!0,J=_[1]||null,G=0,F=!1;continue}let B=z.match(I0.table),L=z.match(I0.tableSeparator);if(B&&!q){if(O+1<X.length){if(X[O+1].match(I0.tableSeparator)){q=!0,K=B[1].split("|").map((N)=>N.trim()).filter((N)=>N.length>0),W=[],F=!1;continue}}}if(q&&L)continue;if(q&&B){let v=B[1].split("|").map((N)=>N.trim()).filter((N)=>N.length>0);while(v.length<K.length)v.push("");if(v.length>K.length)v.length=K.length;W.push(v);continue}if(q&&!B){if(K.length>0&&W.length>0)Z.push({type:"table",content:"",tableData:{headers:K,rows:W}});q=!1,K=[],W=[]}let w=z.match(I0.heading);if(w){Z.push({type:"heading",content:w[2],level:w[1].length}),F=!1;continue}let R=z.match(I0.ulItem);if(R){Z.push({type:"list",content:R[3],listType:"ul",marker:R[2],indentation:R[1].length}),F=!1;continue}let D=z.match(I0.olItem);if(D){Z.push({type:"list",content:D[3],listType:"ol",marker:D[2],indentation:D[1].length}),F=!1;continue}if(z.match(I0.hr)){Z.push({type:"hr",content:""}),F=!1;continue}if(z.trim().length===0){if(!F)Z.push({type:"empty",content:""}),F=!0;continue}let I=z.match(I0.commandMessage);if(I){Z.push({type:"command-message",content:I[1]}),F=!1;continue}Z.push({type:"text",content:z}),F=!1}if(Y){let O=Q.join(`
|
|
29
|
+
`);if(J?.toLowerCase()==="markdown"||J?.toLowerCase()==="md"){let z=a2(O);Z.push(...z)}else Z.push({type:"code",content:O,language:J||void 0})}if(q&&K.length>0&&W.length>0)Z.push({type:"table",content:"",tableData:{headers:K,rows:W}});while(Z.length>0&&Z[Z.length-1].type==="empty")Z.pop();return Z}var I0;var y9=A(()=>{I0={codeBlock:/^```(\w+)?\s*$/,heading:/^ *(#{1,4}) +(.+)/,ulItem:/^([ \t]*)([-*+]) +(.+)/,olItem:/^([ \t]*)(\d+)\. +(.+)/,hr:/^ *([-*_] *){3,} *$/,table:/^\|(.+)\|$/,tableSeparator:/^\|[\s]*:?-+:?[\s]*(\|[\s]*:?-+:?[\s]*)+\|?$/,diffStart:/^<<<DIFF>>>$/,diffEnd:/^<<<\/DIFF>>>$/,commandMessage:/<command-message>(.*?)<\/command-message>/}});function OH(){return{inCodeBlock:!1,codeBlockContent:[],codeBlockLang:null,codeBlockDepth:0,inTable:!1,tableHeaders:[],tableRows:[],inDiff:!1,diffContent:[],lastLineEmpty:!0,pendingTableHeader:null}}function zH($){let Z=e1.get($);if(Z)return Z;let X={state:OH(),blocks:[],pendingLine:"",finalized:!1};return e1.set($,X),X}function VX($){return $.endsWith("\r")?$.slice(0,-1):$}function DX($,Z){if($.tableHeaders.length>0&&$.tableRows.length>0)Z.push({type:"table",content:"",tableData:{headers:$.tableHeaders,rows:$.tableRows}});$.inTable=!1,$.tableHeaders=[],$.tableRows=[]}function MX($,Z){let X=$.codeBlockContent.join(`
|
|
30
|
+
`);if($.codeBlockLang?.toLowerCase()==="markdown"||$.codeBlockLang?.toLowerCase()==="md")Z.push(...a2(X));else Z.push({type:"code",content:X,language:$.codeBlockLang||void 0});$.inCodeBlock=!1,$.codeBlockContent=[],$.codeBlockLang=null,$.codeBlockDepth=0,$.lastLineEmpty=!1}function v9($,Z,X=!0){let{state:Y,blocks:Q}=Z;if(Y.pendingTableHeader!==null){if($.match(I0.tableSeparator)){Y.inTable=!0,Y.tableHeaders=Y.pendingTableHeader.slice(1,-1).split("|").map((O)=>O.trim()).filter((O)=>O.length>0),Y.tableRows=[],Y.pendingTableHeader=null,Y.lastLineEmpty=!1;return}Q.push({type:"text",content:Y.pendingTableHeader}),Y.pendingTableHeader=null,Y.lastLineEmpty=!1}if(Y.inDiff){if($.match(I0.diffEnd)){try{let O=JSON.parse(Y.diffContent.join(`
|
|
31
31
|
`));Q.push({type:"diff",content:"",diffData:{patch:O.patch,startLine:O.startLine,matchLine:O.matchLine}})}catch(O){Q.push({type:"text",content:Y.diffContent.join(`
|
|
32
32
|
`)})}Y.inDiff=!1,Y.diffContent=[],Y.lastLineEmpty=!1;return}Y.diffContent.push($);return}if($.match(I0.diffStart)){Y.inDiff=!0,Y.diffContent=[],Y.lastLineEmpty=!1;return}if(Y.inCodeBlock){let O=$.match(I0.codeBlock),z=$.trim()==="```";if(O&&O[1])Y.codeBlockDepth++,Y.codeBlockContent.push($);else if(z)if(Y.codeBlockDepth>0)Y.codeBlockDepth--,Y.codeBlockContent.push($);else MX(Y,Q);else Y.codeBlockContent.push($);return}let J=$.match(I0.codeBlock);if(J){Y.inCodeBlock=!0,Y.codeBlockLang=J[1]||null,Y.codeBlockDepth=0,Y.lastLineEmpty=!1;return}let G=$.match(I0.table),q=$.match(I0.tableSeparator);if(G&&!Y.inTable){Y.pendingTableHeader=$;return}if(Y.inTable&&q)return;if(Y.inTable&&G){let O=G[1].split("|").map((z)=>z.trim()).filter((z)=>z.length>0);while(O.length<Y.tableHeaders.length)O.push("");if(O.length>Y.tableHeaders.length)O.length=Y.tableHeaders.length;Y.tableRows.push(O);return}if(Y.inTable&&!G){if(DX(Y,Q),X){v9($,Z,!1);return}}let K=$.match(I0.heading);if(K){Q.push({type:"heading",content:K[2],level:K[1].length}),Y.lastLineEmpty=!1;return}let W=$.match(I0.ulItem);if(W){Q.push({type:"list",content:W[3],listType:"ul",marker:W[2],indentation:W[1].length}),Y.lastLineEmpty=!1;return}let U=$.match(I0.olItem);if(U){Q.push({type:"list",content:U[3],listType:"ol",marker:U[2],indentation:U[1].length}),Y.lastLineEmpty=!1;return}if($.match(I0.hr)){Q.push({type:"hr",content:""}),Y.lastLineEmpty=!1;return}if($.trim().length===0){if(!Y.lastLineEmpty)Q.push({type:"empty",content:""}),Y.lastLineEmpty=!0;return}let F=$.match(I0.commandMessage);if(F){Q.push({type:"command-message",content:F[1]}),Y.lastLineEmpty=!1;return}Q.push({type:"text",content:$}),Y.lastLineEmpty=!1}function E9($,Z){if(!$||!Z)return;let X=zH($);if(X.finalized)return;let Y=X.pendingLine+Z,Q=Y.split(`
|
|
33
33
|
`),J=Y.endsWith(`
|
|
34
34
|
`),G=J?Q:Q.slice(0,-1);X.pendingLine=J?"":Q[Q.length-1]??"";for(let q of G)v9(VX(q),X)}function P9($){let Z=e1.get($);if(!Z||Z.finalized)return;if(Z.pendingLine)v9(VX(Z.pendingLine),Z),Z.pendingLine="";if(Z.state.pendingTableHeader!==null)Z.blocks.push({type:"text",content:Z.state.pendingTableHeader}),Z.state.pendingTableHeader=null;if(Z.state.inCodeBlock)MX(Z.state,Z.blocks);if(Z.state.inTable)DX(Z.state,Z.blocks);if(Z.state.inDiff)Z.blocks.push({type:"text",content:Z.state.diffContent.join(`
|
|
35
35
|
`)}),Z.state.inDiff=!1,Z.state.diffContent=[];while(Z.blocks.length>0&&Z.blocks[Z.blocks.length-1].type==="empty")Z.blocks.pop();Z.finalized=!0}function jX($){let Z=e1.get($);if(!Z||!Z.finalized)return null;return Z.blocks}function T9($){let Z=e1.get($);if(!Z)return null;return Z.blocks}function _H($){let Z=e1.get($);if(!Z)return null;let X=[],Y=Z.state;if(Y.inDiff)X.push("<<<DIFF>>>"),X.push(...Y.diffContent);else if(Y.inCodeBlock){let Q=Y.codeBlockLang?`\`\`\`${Y.codeBlockLang}`:"```";X.push(Q),X.push(...Y.codeBlockContent)}else if(Y.inTable){if(Y.tableHeaders.length>0){X.push(`| ${Y.tableHeaders.join(" | ")} |`),X.push(`| ${Y.tableHeaders.map(()=>"---").join(" | ")} |`);for(let Q of Y.tableRows)X.push(`| ${Q.join(" | ")} |`)}}else if(Y.pendingTableHeader)X.push(Y.pendingTableHeader);if(Z.pendingLine)X.push(Z.pendingLine);return X.length>0?X:null}function IX($){let Z=e1.get($);if(!Z)return null;let X="text";if(Z.state.inDiff)X="diff";else if(Z.state.inCodeBlock)X="code";else if(Z.state.inTable||Z.state.pendingTableHeader)X="table";let Y=_H($);if(!Y||Y.length===0)return null;return{lines:Y,mode:X}}function yX($){e1.delete($)}function I3(){e1.clear()}var e1;var P8=A(()=>{y9();e1=new Map});import{nanoid as BH}from"nanoid";var vX=2000,PX,EX,S9=($,Z)=>({...EX,actions:{addMessage:(X)=>{$((Y)=>({session:{...Y.session,messages:[...Y.session.messages,X],error:null}}))},addUserMessage:(X)=>{let Y={id:`user-${Date.now()}-${Math.random()}`,role:"user",content:X,timestamp:Date.now()};Z().session.actions.addMessage(Y)},addAssistantMessage:(X,Y)=>{let Q={id:`assistant-${Date.now()}-${Math.random()}`,role:"assistant",content:X,timestamp:Date.now(),thinkingContent:Y};Z().session.actions.addMessage(Q)},addAssistantMessageAndClearThinking:(X)=>{let Y=Z().session.currentThinkingContent,Q={id:`assistant-${Date.now()}-${Math.random()}`,role:"assistant",content:X,timestamp:Date.now(),thinkingContent:Y||void 0};$((J)=>({session:{...J.session,messages:[...J.session.messages,Q],currentThinkingContent:null,error:null}}))},addToolMessage:(X,Y)=>{let Q={id:`tool-${Date.now()}-${Math.random()}`,role:"tool",content:X,timestamp:Date.now(),metadata:Y};Z().session.actions.addMessage(Q)},setCompacting:(X)=>{$((Y)=>({session:{...Y.session,isCompacting:X}}))},setCommand:(X)=>{$((Y)=>({session:{...Y.session,currentCommand:X}}))},setError:(X)=>{$((Y)=>({session:{...Y.session,error:X}}))},clearMessages:()=>{I3(),$((X)=>({session:{...X.session,messages:[],error:null,clearCount:X.session.clearCount+1}}))},resetSession:()=>{I3(),$((X)=>({session:{...X.session,...EX,sessionId:X.session.sessionId,isActive:!0}}))},restoreSession:(X,Y)=>{I3(),$((Q)=>({session:{...Q.session,sessionId:X,messages:Y,error:null,isActive:!0}}))},updateTokenUsage:(X)=>{$((Y)=>({session:{...Y.session,tokenUsage:{...Y.session.tokenUsage,...X}}}))},resetTokenUsage:()=>{$((X)=>({session:{...X.session,tokenUsage:{...PX}}}))},setCurrentThinkingContent:(X)=>{if(Z().session.currentThinkingContent===X)return;$((Y)=>({session:{...Y.session,currentThinkingContent:X}}))},appendThinkingContent:(X)=>{$((Y)=>({session:{...Y.session,currentThinkingContent:(Y.session.currentThinkingContent||"")+X}}))},setThinkingExpanded:(X)=>{$((Y)=>({session:{...Y.session,thinkingExpanded:X}}))},toggleThinkingExpanded:()=>{$((X)=>({session:{...X.session,thinkingExpanded:!X.session.thinkingExpanded}}))},setHistoryExpanded:(X)=>{$((Y)=>({session:{...Y.session,historyExpanded:X}}))},toggleHistoryExpanded:()=>{$((X)=>({session:{...X.session,historyExpanded:!X.session.historyExpanded}}))},setExpandedMessageCount:(X)=>{$((Y)=>({session:{...Y.session,expandedMessageCount:X}}))},incrementClearCount:()=>{$((X)=>({session:{...X.session,clearCount:X.session.clearCount+1}}))},startStreamingAssistantMessage:()=>{let X=`assistant-${Date.now()}-${Math.random()}`,Y={id:X,role:"assistant",content:"",timestamp:Date.now()};return $((Q)=>({session:{...Q.session,messages:[...Q.session.messages,Y],currentStreamingMessageId:X,currentStreamingChunks:[],currentStreamingLines:[],currentStreamingTail:"",currentStreamingLineCount:0,currentStreamingVersion:0,error:null}})),X},appendAssistantContent:(X)=>{let Y=Z().session.currentStreamingMessageId,Q=Y??`assistant-${Date.now()}-${Math.random()}`;return $((J)=>{let G=(w)=>w.endsWith("\r")?w.slice(0,-1):w,q=Y?J.session.currentStreamingChunks:[],K=Y?J.session.currentStreamingLines:[],W=Y?J.session.currentStreamingTail:"",U=Y?J.session.currentStreamingLineCount:0,H=Y?J.session.currentStreamingVersion:0,O=(W+X).split(`
|
|
36
|
-
`),z=O.slice(0,-1).map(G),_=G(O[O.length-1]??""),B=[...q,X],L=K;if(z.length>0){if(L=[...K,...z],L.length>vX){let w=L.length-vX;L=L.slice(w)}}return{session:{...J.session,currentStreamingMessageId:Q,currentStreamingChunks:B,currentStreamingLines:L,currentStreamingTail:_,currentStreamingLineCount:U+z.length,currentStreamingVersion:H+1,error:null}}}),Q},finalizeStreamingMessage:(X,Y)=>{$((Q)=>{let J=Q.session.currentStreamingMessageId,q=Q.session.currentStreamingChunks.join("")+(X||""),K=(Q.session.currentThinkingContent||"")+(Y||"");if(q.length>0){let W={id:J||`assistant-${Date.now()}-${Math.random()}`,role:"assistant",content:q,timestamp:Date.now(),thinkingContent:K||void 0};return{session:{...Q.session,messages:[...Q.session.messages,W],currentStreamingMessageId:null,currentStreamingChunks:[],currentStreamingLines:[],currentStreamingTail:"",currentStreamingLineCount:0,currentStreamingVersion:0,currentThinkingContent:null,finalizingStreamingMessageId:W.id}}}return{session:{...Q.session,currentStreamingMessageId:null,currentStreamingChunks:[],currentStreamingLines:[],currentStreamingTail:"",currentStreamingLineCount:0,currentStreamingVersion:0,currentThinkingContent:null,finalizingStreamingMessageId:null}}})},clearFinalizingStreamingMessageId:()=>{$((X)=>({session:{...X.session,finalizingStreamingMessageId:null}}))}}});var TX=A(()=>{P8();PX={inputTokens:0,outputTokens:0,totalTokens:0,maxContextTokens:200000},EX={sessionId:BH(),messages:[],isCompacting:!1,currentCommand:null,error:null,isActive:!0,tokenUsage:{...PX},currentThinkingContent:null,thinkingExpanded:!1,clearCount:0,historyExpanded:!1,expandedMessageCount:100,currentStreamingMessageId:null,currentStreamingChunks:[],currentStreamingLines:[],currentStreamingTail:"",currentStreamingLineCount:0,currentStreamingVersion:0,finalizingStreamingMessageId:null}});var SX,
|
|
36
|
+
`),z=O.slice(0,-1).map(G),_=G(O[O.length-1]??""),B=[...q,X],L=K;if(z.length>0){if(L=[...K,...z],L.length>vX){let w=L.length-vX;L=L.slice(w)}}return{session:{...J.session,currentStreamingMessageId:Q,currentStreamingChunks:B,currentStreamingLines:L,currentStreamingTail:_,currentStreamingLineCount:U+z.length,currentStreamingVersion:H+1,error:null}}}),Q},finalizeStreamingMessage:(X,Y)=>{$((Q)=>{let J=Q.session.currentStreamingMessageId,q=Q.session.currentStreamingChunks.join("")+(X||""),K=(Q.session.currentThinkingContent||"")+(Y||"");if(q.length>0){let W={id:J||`assistant-${Date.now()}-${Math.random()}`,role:"assistant",content:q,timestamp:Date.now(),thinkingContent:K||void 0};return{session:{...Q.session,messages:[...Q.session.messages,W],currentStreamingMessageId:null,currentStreamingChunks:[],currentStreamingLines:[],currentStreamingTail:"",currentStreamingLineCount:0,currentStreamingVersion:0,currentThinkingContent:null,finalizingStreamingMessageId:W.id}}}return{session:{...Q.session,currentStreamingMessageId:null,currentStreamingChunks:[],currentStreamingLines:[],currentStreamingTail:"",currentStreamingLineCount:0,currentStreamingVersion:0,currentThinkingContent:null,finalizingStreamingMessageId:null}}})},clearFinalizingStreamingMessageId:()=>{$((X)=>({session:{...X.session,finalizingStreamingMessageId:null}}))}}});var TX=A(()=>{P8();PX={inputTokens:0,outputTokens:0,totalTokens:0,maxContextTokens:200000},EX={sessionId:BH(),messages:[],isCompacting:!1,currentCommand:null,error:null,isActive:!0,tokenUsage:{...PX},currentThinkingContent:null,thinkingExpanded:!1,clearCount:0,historyExpanded:!1,expandedMessageCount:100,currentStreamingMessageId:null,currentStreamingChunks:[],currentStreamingLines:[],currentStreamingTail:"",currentStreamingLineCount:0,currentStreamingVersion:0,finalizingStreamingMessageId:null}});var SX,r2,n2,S1,y$,CX;var b1=A(()=>{SX={proposal:"proposal.md",spec:"spec.md",requirements:"requirements.md",design:"design.md",tasks:"tasks.md",meta:".meta.json"},r2={SPECS:"specs",CHANGES:"changes",ARCHIVE:"archive",STEERING:"steering",SPEC_DELTA:"specs"},n2={CONSTITUTION:"constitution.md",PRODUCT:"product.md",TECH:"tech.md",STRUCTURE:"structure.md"},S1={init:["requirements"],requirements:["design","tasks"],design:["tasks"],tasks:["implementation"],implementation:["done","tasks"],done:[]},y$={init:"初始化",requirements:"需求定义",design:"架构设计",tasks:"任务分解",implementation:"实现中",done:"已完成"},CX={init:"proposal",requirements:"requirements",design:"design",tasks:"tasks",implementation:"tasks",done:null}});import{promises as v$}from"node:fs";import*as h0 from"node:path";import{fileURLToPath as LH}from"node:url";import{nanoid as wH}from"nanoid";var NH,bH,kX,o2;var C9=A(()=>{b1();NH=LH(import.meta.url),bH=h0.dirname(NH),kX=h0.join(bH,"templates");o2=class o2{workspaceRoot;bladeDir;constructor($){this.workspaceRoot=$,this.bladeDir=h0.join($,".blade")}getSpecsDir(){return h0.join(this.bladeDir,r2.SPECS)}getChangesDir(){return h0.join(this.bladeDir,r2.CHANGES)}getArchiveDir(){return h0.join(this.bladeDir,r2.ARCHIVE)}getSteeringDir(){return h0.join(this.bladeDir,r2.STEERING)}getChangePath($){return h0.join(this.getChangesDir(),$)}getChangeFilePath($,Z){return h0.join(this.getChangePath($),SX[Z])}async initializeDirectories(){await v$.mkdir(this.getChangesDir(),{recursive:!0})}async createChangeDir($){let Z=this.getChangePath($);return await v$.mkdir(Z,{recursive:!0}),await v$.mkdir(h0.join(Z,r2.SPEC_DELTA),{recursive:!0}),Z}async readFile($){try{return await v$.readFile($,"utf-8")}catch(Z){if(Z.code==="ENOENT")return null;throw Z}}async writeFile($,Z){let X=h0.dirname($);await v$.mkdir(X,{recursive:!0}),await v$.writeFile($,Z,"utf-8")}async fileExists($){try{return await v$.access($),!0}catch{return!1}}async dirExists($){try{return(await v$.stat($)).isDirectory()}catch{return!1}}createMetadata($,Z){let X=new Date().toISOString();return{id:wH(),name:$,description:Z,phase:"init",createdAt:X,updatedAt:X,tasks:[]}}async readMetadata($){let Z=this.getChangeFilePath($,"meta"),X=await this.readFile(Z);if(!X)return null;try{return JSON.parse(X)}catch{return null}}async writeMetadata($,Z){let X=this.getChangeFilePath($,"meta");Z.updatedAt=new Date().toISOString(),await this.writeFile(X,JSON.stringify(Z,null,2))}async updatePhase($,Z){let X=await this.readMetadata($);if(!X)return null;return X.phase=Z,await this.writeMetadata($,X),X}async readSpecFile($,Z){let X=this.getChangeFilePath($,Z);return this.readFile(X)}async writeSpecFile($,Z,X){let Y=this.getChangeFilePath($,Z);await this.writeFile(Y,X);let Q=await this.readMetadata($);if(Q)await this.writeMetadata($,Q)}async getPhaseContent($,Z){let X=CX[Z];if(!X)return null;return this.readSpecFile($,X)}async readSteeringContext(){let $=this.getSteeringDir(),[Z,X,Y,Q]=await Promise.all([this.readFile(h0.join($,n2.CONSTITUTION)),this.readFile(h0.join($,n2.PRODUCT)),this.readFile(h0.join($,n2.TECH)),this.readFile(h0.join($,n2.STRUCTURE))]);return{constitution:Z||void 0,product:X||void 0,tech:Y||void 0,structure:Q||void 0}}async writeSteeringFile($,Z){let X=h0.join(this.getSteeringDir(),n2[$]);await this.writeFile(X,Z)}async hasSteeringDocs(){let $=this.getSteeringDir();if(!await this.dirExists($))return!1;return(await v$.readdir($)).length>0}async listActiveChanges(){let $=this.getChangesDir();if(!await this.dirExists($))return[];return(await v$.readdir($,{withFileTypes:!0})).filter((X)=>X.isDirectory()).map((X)=>X.name)}async listArchivedChanges(){let $=this.getArchiveDir();if(!await this.dirExists($))return[];return(await v$.readdir($,{withFileTypes:!0})).filter((X)=>X.isDirectory()).map((X)=>X.name)}async changeExists($){return this.dirExists(this.getChangePath($))}async archiveChange($){let Z=this.getChangePath($),X=h0.join(this.getArchiveDir(),$);await v$.mkdir(h0.dirname(X),{recursive:!0}),await v$.rename(Z,X)}async restoreChange($){let Z=h0.join(this.getArchiveDir(),$),X=this.getChangePath($);await v$.rename(Z,X)}async listSpecDomains(){let $=this.getSpecsDir();if(!await this.dirExists($))return[];return(await v$.readdir($,{withFileTypes:!0})).filter((X)=>X.isDirectory()).map((X)=>X.name)}async readAuthorativeSpec($){let Z=h0.join(this.getSpecsDir(),$,"spec.md");return this.readFile(Z)}async writeAuthorativeSpec($,Z){let X=h0.join(this.getSpecsDir(),$,"spec.md");await this.writeFile(X,Z)}async mergeSpecDeltas($){let Z=h0.join(this.getChangePath($),r2.SPEC_DELTA);if(!await this.dirExists(Z))return[];let X=[],Y=await v$.readdir(Z,{withFileTypes:!0});for(let Q of Y){if(!Q.isDirectory())continue;let J=h0.join(Z,Q.name,"spec.md"),G=await this.readFile(J);if(G){let q=await this.readAuthorativeSpec(Q.name),K=q?`${q}
|
|
37
37
|
|
|
38
38
|
---
|
|
39
39
|
|
|
40
40
|
<!-- Merged from ${$} -->
|
|
41
41
|
|
|
42
|
-
${G}`:G;await this.writeAuthorativeSpec(Q.name,K),X.push(Q.name)}}return X}static TEMPLATE_NAMES={proposal:"proposal.md.template",spec:"spec.md.template",requirements:"requirements.md.template",design:"design.md.template",tasks:"tasks.md.template",meta:""};static STEERING_TEMPLATE_NAMES={CONSTITUTION:"steering/constitution.md.template",PRODUCT:"steering/product.md.template",TECH:"steering/tech.md.template",STRUCTURE:"steering/structure.md.template"};async readTemplate($){let Z=
|
|
42
|
+
${G}`:G;await this.writeAuthorativeSpec(Q.name,K),X.push(Q.name)}}return X}static TEMPLATE_NAMES={proposal:"proposal.md.template",spec:"spec.md.template",requirements:"requirements.md.template",design:"design.md.template",tasks:"tasks.md.template",meta:""};static STEERING_TEMPLATE_NAMES={CONSTITUTION:"steering/constitution.md.template",PRODUCT:"steering/product.md.template",TECH:"steering/tech.md.template",STRUCTURE:"steering/structure.md.template"};async readTemplate($){let Z=o2.TEMPLATE_NAMES[$];if(!Z)return null;let X=h0.join(kX,Z);return this.readFile(X)}async readSteeringTemplate($){let Z=o2.STEERING_TEMPLATE_NAMES[$],X=h0.join(kX,Z);return this.readFile(X)}fillTemplate($,Z){let X=$;for(let[Y,Q]of Object.entries(Z))X=X.replace(new RegExp(`\\{\\{${Y}\\}\\}`,"g"),Q);return X}async createFromTemplate($,Z,X){let Y=await this.readTemplate(Z);if(!Y)return null;let Q=this.fillTemplate(Y,{name:$,createdAt:new Date().toISOString(),updatedAt:new Date().toISOString(),...X});return await this.writeSpecFile($,Z,Q),Q}async createSteeringFromTemplate($,Z={}){let X=await this.readSteeringTemplate($);if(!X)return null;let Y=this.fillTemplate(X,{createdAt:new Date().toISOString(),...Z});return await this.writeSteeringFile($,Y),Y}async initializeSteeringDocs(){let $=[],Z=this.getSteeringDir();for(let[X,Y]of Object.entries(n2)){let Q=h0.join(Z,Y);if(!await this.fileExists(Q))await this.createSteeringFromTemplate(X),$.push(Y)}return $}}});import{nanoid as AH}from"nanoid";class D${static instance=null;fileManager=null;workspaceRoot=null;constructor(){}static getInstance(){if(!D$.instance)D$.instance=new D$;return D$.instance}static resetInstance(){D$.instance=null}async initialize($){if(this.workspaceRoot===$&&this.fileManager)return;this.workspaceRoot=$,this.fileManager=new o2($),await this.fileManager.initializeDirectories()}getFileManager(){if(!this.fileManager)throw Error("SpecService not initialized. Call initialize() first.");return this.fileManager}async readSteeringContext(){return this.getFileManager().readSteeringContext()}async readSpecMetadata($){return this.getFileManager().readMetadata($)}async specExists($){return this.getFileManager().changeExists($)}getSpecPath($){return this.getFileManager().getChangePath($)}async createSpec($,Z){let X=this.getFileManager();if(await X.changeExists($))return{success:!1,message:`Spec "${$}" already exists`,error:"SPEC_EXISTS"};let Y=await X.createChangeDir($),Q=X.createMetadata($,Z);await X.writeMetadata($,Q);let J=this.generateProposalTemplate($,Z);return await X.writeSpecFile($,"proposal",J),{success:!0,message:`Spec "${$}" created successfully`,data:{spec:Q,path:Y}}}async loadSpec($){let Z=this.getFileManager(),X=await Z.readMetadata($);if(!X)return{success:!1,message:`Spec "${$}" not found`,error:"SPEC_NOT_FOUND"};let Y=Z.getChangePath($);return{success:!0,message:`Spec "${$}" loaded successfully`,data:{spec:X,path:Y}}}canTransitionPhase($,Z){return S1[$].includes(Z)}getAllowedTransitions($){return S1[$]}async updatePhase($,Z){return this.getFileManager().updatePhase($,Z)}createTask($,Z,X){return{id:AH(8),title:$,description:Z,status:"pending",dependencies:X?.dependencies||[],affectedFiles:X?.affectedFiles||[],complexity:X?.complexity||"medium"}}async saveMetadata($,Z){await this.getFileManager().writeMetadata($,Z)}getNextTask($){return $.find((Z)=>{if(Z.status!=="pending")return!1;return Z.dependencies.every((X)=>{return $.find((Q)=>Q.id===X)?.status==="completed"})})||null}getTaskProgress($){if($.length===0)return{total:0,completed:0,percentage:0};let Z=$.length,X=$.filter((Q)=>Q.status==="completed").length,Y=Math.round(X/Z*100);return{total:Z,completed:X,percentage:Y}}async listActiveSpecs(){return this.getFileManager().listActiveChanges()}async listArchivedSpecs(){return this.getFileManager().listArchivedChanges()}async archiveSpec($){let Z=this.getFileManager();return await Z.mergeSpecDeltas($),await Z.updatePhase($,"done"),await Z.archiveChange($),{success:!0,message:`Spec "${$}" archived successfully`}}async validateSpec($){let Z=this.getFileManager(),X=[],Y=[],[Q,J,G,q,K]=await Promise.all([Z.readSpecFile($.name,"proposal"),Z.readSpecFile($.name,"spec"),Z.readSpecFile($.name,"requirements"),Z.readSpecFile($.name,"design"),Z.readSpecFile($.name,"tasks")]),W={proposal:!!Q,spec:!!J,requirements:!!G,design:!!q,tasks:!!K};if($.phase==="requirements"&&!W.requirements)X.push({severity:"warning",file:"requirements",message:"Requirements document is missing"}),Y.push("Generate requirements using EARS format");if($.phase==="design"&&!W.design)X.push({severity:"warning",file:"design",message:"Design document is missing"}),Y.push("Create architecture diagrams and API contracts");if($.phase==="tasks"&&$.tasks.length===0)X.push({severity:"warning",file:"tasks",message:"No tasks defined"}),Y.push("Break down the spec into atomic tasks");if($.phase==="implementation"){let U=this.getTaskProgress($.tasks);if(U.completed<U.total)X.push({severity:"info",file:"tasks",message:`${U.total-U.completed} tasks remaining`})}return{valid:X.filter((U)=>U.severity==="error").length===0,phase:$.phase,completeness:W,issues:X,suggestions:Y}}generateProposalTemplate($,Z){return`# ${$}
|
|
43
43
|
|
|
44
44
|
## Summary
|
|
45
45
|
|
|
@@ -85,14 +85,14 @@ ${X.structure}`);return Y.length>0?Y.join(`
|
|
|
85
85
|
|
|
86
86
|
---
|
|
87
87
|
|
|
88
|
-
`):null},setError:(X)=>{$((Y)=>({spec:{...Y.spec,error:X}}))},setLoading:(X)=>{$((Y)=>({spec:{...Y.spec,isLoading:X}}))},reset:()=>{$((X)=>({spec:{...xX,actions:X.spec.actions}}))}}});var pX=A(()=>{U$();B0();fX();b1();hX=i("Spec"),xX={currentSpec:null,specPath:null,isActive:!1,steeringContext:null,recentSpecs:[],isLoading:!1,error:null,workspaceRoot:null}});var dX=A(()=>{NX();bX();AX();RX();TX();pX()});import{nanoid as RH}from"nanoid";import{devtools as VH,subscribeWithSelector as DH}from"zustand/middleware";import{createStore as MH}from"zustand/vanilla";async function y3(){if(H$()!==null)return;if(
|
|
88
|
+
`):null},setError:(X)=>{$((Y)=>({spec:{...Y.spec,error:X}}))},setLoading:(X)=>{$((Y)=>({spec:{...Y.spec,isLoading:X}}))},reset:()=>{$((X)=>({spec:{...xX,actions:X.spec.actions}}))}}});var pX=A(()=>{U$();B0();fX();b1();hX=i("Spec"),xX={currentSpec:null,specPath:null,isActive:!1,steeringContext:null,recentSpecs:[],isLoading:!1,error:null,workspaceRoot:null}});var dX=A(()=>{NX();bX();AX();RX();TX();pX()});import{nanoid as RH}from"nanoid";import{devtools as VH,subscribeWithSelector as DH}from"zustand/middleware";import{createStore as MH}from"zustand/vanilla";async function y3(){if(H$()!==null)return;if(v4)return v4;return v4=(async()=>{try{let X=await u$.getInstance().initialize();K0().config.actions.setConfig(X)}catch(Z){throw v4=null,Error(`❌ Store 未初始化且无法自动初始化
|
|
89
89
|
|
|
90
90
|
`+`原因: ${Z instanceof Error?Z.message:"未知错误"}
|
|
91
91
|
|
|
92
92
|
`+`请确保:
|
|
93
93
|
`+`1. 配置文件格式正确 (~/.blade/config.json)
|
|
94
94
|
`+`2. 运行 blade 进行首次配置
|
|
95
|
-
`+"3. 配置文件权限正确")}finally{
|
|
95
|
+
`+"3. 配置文件权限正确")}finally{v4=null}})(),v4}var E4,K0=()=>E4.getState(),z0=()=>K0().session.actions,$2=()=>K0().app.actions,mX=()=>K0().session.messages,H$=()=>K0().config.config,v4=null,T8=()=>K0().config.config?.models??[],P4=()=>{let $=H$();if(!$)return;let Z=$.currentModelId;return $.models.find((Y)=>Y.id===Z)??$.models[0]},G1=()=>K0().config.config?.mcpServers??{},uX=()=>K0().app.thinkingModeEnabled,x0=()=>({setPermissionMode:async($)=>{K0().config.actions.updateConfig({permissionMode:$})},setTheme:async($,Z={})=>{try{g$.setTheme($)}catch{return}K0().config.actions.updateConfig({theme:$}),await S$().save({theme:$},{scope:"global",...Z})},setLanguage:async($,Z={})=>{K0().config.actions.updateConfig({language:$}),await S$().save({language:$},{scope:"global",...Z})},setDebug:async($,Z={})=>{K0().config.actions.updateConfig({debug:$}),await S$().save({debug:$},{scope:"global",...Z})},setTemperature:async($,Z={})=>{K0().config.actions.updateConfig({temperature:$}),await S$().save({temperature:$},{scope:"global",...Z})},updateConfig:async($,Z={})=>{let X=H$();if(!X)throw Error("Config not initialized");let Y={...X};K0().config.actions.updateConfig($);try{await S$().save($,Z)}catch(Q){throw K0().config.actions.setConfig(Y),Q}},flush:async()=>{await S$().flush()},appendPermissionAllowRule:async($,Z={})=>{let X=H$();if(!X)throw Error("Config not initialized");let Y=X.permissions?.allow||[];if(!Y.includes($)){let Q=[...Y,$];K0().config.actions.updateConfig({permissions:{...X.permissions,allow:Q}})}await S$().appendPermissionRule($,Z)},appendLocalPermissionAllowRule:async($,Z={})=>{let X=H$();if(!X)throw Error("Config not initialized");let Y=X.permissions?.allow||[];if(!Y.includes($)){let Q=[...Y,$];K0().config.actions.updateConfig({permissions:{...X.permissions,allow:Q}})}await S$().appendLocalPermissionRule($,Z)},setCurrentModel:async($,Z={})=>{let X=H$();if(!X)throw Error("Config not initialized");if(!X.models.find((Q)=>Q.id===$))throw Error(`Model not found: ${$}`);K0().config.actions.updateConfig({currentModelId:$}),await S$().save({currentModelId:$},{scope:"global",...Z})},addModel:async($,Z={})=>{let X=H$();if(!X)throw Error("Config not initialized");let Y="id"in $?$:{id:RH(),...$},J={models:[...X.models,Y]};if(X.models.length===0)J.currentModelId=Y.id;return K0().config.actions.updateConfig(J),await S$().save(J,{scope:"global",...Z}),Y},updateModel:async($,Z,X={})=>{let Y=H$();if(!Y)throw Error("Config not initialized");let Q=Y.models.findIndex((G)=>G.id===$);if(Q===-1)throw Error(`Model not found: ${$}`);let J=[...Y.models];J[Q]={...J[Q],...Z},K0().config.actions.updateConfig({models:J}),await S$().save({models:J},{scope:"global",...X})},removeModel:async($,Z={})=>{let X=H$();if(!X)throw Error("Config not initialized");if(X.models.length===1)throw Error("Cannot remove the only model");let Y=X.models.filter((J)=>J.id!==$),Q={models:Y};if(X.currentModelId===$)Q.currentModelId=Y[0].id;K0().config.actions.updateConfig(Q),await S$().save(Q,{scope:"global",...Z})},addMcpServer:async($,Z,X={})=>{let Y=H$();if(!Y)throw Error("Config not initialized");let J={...Y.mcpServers??{},[$]:Z};K0().config.actions.updateConfig({mcpServers:J}),await S$().save({mcpServers:J},{scope:"project",...X})},removeMcpServer:async($,Z={})=>{let X=H$();if(!X)throw Error("Config not initialized");let Q={...X.mcpServers??{}};delete Q[$],K0().config.actions.updateConfig({mcpServers:Q}),await S$().save({mcpServers:Q},{scope:"project",...Z})}});var C0=A(()=>{y4();i2();dX();E4=MH()(VH(DH((...$)=>({session:S9(...$),app:D9(...$),config:j9(...$),focus:I9(...$),command:M9(...$),spec:k9(...$)})),{name:"BladeStore",enabled:!0}))});function S8($){return $==="readonly"}var w$=()=>{};class h9{toolName;params;context;aborted=!1;result;_internal={};constructor($,Z,X){this.toolName=$;this.params=Z;this.context=X}shouldAbort(){return this.aborted||(this.context.signal?.aborted??!1)}abort($,Z){this.aborted=!0,this.result={success:!1,llmContent:`Tool execution aborted: ${$||"Unknown reason"}`,displayContent:`执行已中止: ${$||"未知原因"}`,error:{type:"execution_error",message:$||"Execution aborted"},metadata:Z?.shouldExitLoop?{shouldExitLoop:!0}:void 0}}setResult($){this.result=$}getResult(){if(!this.result)throw Error("Tool execution result not set");return this.result}}var x9=A(()=>{w$()});var E$=A(()=>{x9();w$()});import{isPlainObject as jH}from"lodash-es";function C8($){if($===void 0)return"undefined";if(typeof $==="string")return $;try{let Z=JSON.stringify($);return Z===void 0?String($):Z}catch{return String($)}}function IH($){let{code:Z}=$,X=$,Y=X.received;switch(Z){case"invalid_type":{let Q=X.expected;return`类型错误:期望 ${C8(Q)},实际收到 ${C8(Y)}`}case"too_small":{let{minimum:Q,inclusive:J}=X,G=typeof X.type==="string"?X.type:void 0;if(G==="string"&&typeof Q==="number")return`长度不能少于 ${Q} 个字符`;if(G==="number"&&typeof Q==="number")return`不能小于${J?"等于":""} ${Q}`;if(G==="array"&&typeof Q==="number")return`数组长度不能少于 ${Q}`;return"值太小"}case"too_big":{let{maximum:Q,inclusive:J}=X,G=typeof X.type==="string"?X.type:void 0;if(G==="string"&&typeof Q==="number")return`长度不能超过 ${Q} 个字符`;if(G==="number"&&typeof Q==="number")return`不能大于${J?"等于":""} ${Q}`;if(G==="array"&&typeof Q==="number")return`数组长度不能超过 ${Q}`;return"值太大"}case"invalid_string":{let Q=X.validation;if(Q==="email")return"必须是有效的电子邮件地址";if(Q==="url")return"必须是有效的 URL";if(Q==="uuid")return"必须是有效的 UUID";if(jH(Q)){let J=Q;if(typeof J.includes==="string")return`必须包含 "${J.includes}"`;if(typeof J.startsWith==="string")return`必须以 "${J.startsWith}" 开头`;if(typeof J.endsWith==="string")return`必须以 "${J.endsWith}" 结尾`}return"字符串格式不正确"}case"invalid_enum_value":{let Q=X.options;if(Array.isArray(Q))return`必须是以下值之一:${Q.map((J)=>C8(J)).join(", ")}`;return"必须是枚举允许的值之一"}case"invalid_literal":{let Q=X.expected;return`必须是字面量值:${C8(Q)}`}case"unrecognized_keys":{let Q=X.keys;if(Array.isArray(Q))return`包含未知的参数:${Q.map((J)=>C8(J)).join(", ")}`;return"包含未知的参数"}case"invalid_union":return"不符合任何有效的类型定义";case"invalid_date":return"必须是有效的日期";case"custom":return $.message||"自定义验证失败";default:return $.message||"验证失败"}}function yH($){let Z=$.issues.map((Y)=>{let Q=Y.path.join("."),J=IH(Y),G=Y.received;return{field:Q||"root",message:J,value:G}}),X=Z.length===1?`参数验证失败 [${Z[0].field}]: ${Z[0].message}`:`参数验证失败 (${Z.length} 个错误):
|
|
96
96
|
${Z.map((Y)=>` - ${Y.field}: ${Y.message}`).join(`
|
|
97
97
|
`)}`;return new rX(X,Z)}function nX($,Z){let X=$.safeParse(Z);if(!X.success)throw yH(X.error);return X.data}var rX;var oX=A(()=>{E$();rX=class rX extends Error{issues;type;constructor($,Z,X="validation_error"){super($);this.issues=Z;this.type=X;this.name="ToolValidationError"}}});import{zodToJsonSchema as vH}from"zod-to-json-schema";function p9($){return vH($,{target:"jsonSchema7",$refStrategy:"none"})}var sX=()=>{};class d9{toolName;params;executeFn;descriptionFn;affectedPathsFn;constructor($,Z,X,Y,Q){this.toolName=$;this.params=Z;this.executeFn=X;this.descriptionFn=Y;this.affectedPathsFn=Q}getDescription(){if(this.descriptionFn)return this.descriptionFn(this.params);return`执行工具: ${this.toolName}`}getAffectedPaths(){if(this.affectedPathsFn)return this.affectedPathsFn(this.params);return[]}async execute($,Z,X){let Y={signal:$,updateOutput:Z,...X};return this.executeFn(this.params,Y)}}function e($){return{name:$.name,displayName:$.displayName,kind:$.kind,isReadOnly:$.isReadOnly??S8($.kind),isConcurrencySafe:$.isConcurrencySafe??!0,strict:$.strict??!1,description:$.description,version:$.version||"1.0.0",category:$.category,tags:$.tags||[],getFunctionDeclaration(){let Z=p9($.schema),X=$.description.short;if($.description.long)X+=`
|
|
98
98
|
|
|
@@ -127,7 +127,7 @@ ${U}`,metadata:{serverName:Z,toolName:X.name,mcpResult:K}}}catch(K){return{succe
|
|
|
127
127
|
</html>
|
|
128
128
|
`),Y.close(),Z(q)}catch(G){Y.close(),X(G)}});Y.on("error",X),Y.listen(f8,()=>{console.log(`[OAuth] Callback server listening on port ${f8}`)}),setTimeout(()=>{Y.close(),X(Error("OAuth callback timeout"))},300000)})}async exchangeCodeForToken($,Z,X){let Y=$.redirectUri||`http://localhost:${f8}${c9}`,Q=new URLSearchParams({grant_type:"authorization_code",code:Z,redirect_uri:Y,code_verifier:X,client_id:$.clientId});if($.clientSecret)Q.append("client_secret",$.clientSecret);let J=await fetch($.tokenUrl,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:Q.toString()});if(!J.ok){let G=await J.text();throw Error(`Token exchange failed: ${J.status} - ${G}`)}return await J.json()}async refreshAccessToken($,Z){let X=new URLSearchParams({grant_type:"refresh_token",refresh_token:Z,client_id:$.clientId});if($.clientSecret)X.append("client_secret",$.clientSecret);if($.scopes&&$.scopes.length>0)X.append("scope",$.scopes.join(" "));let Y=await fetch($.tokenUrl,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:X.toString()});if(!Y.ok){let Q=await Y.text();throw Error(`Token refresh failed: ${Y.status} - ${Q}`)}return await Y.json()}async authenticate($,Z){if(!Z.clientId||!Z.authorizationUrl||!Z.tokenUrl)throw Error("Missing required OAuth configuration");let X=this.generatePKCEParams(),Y=this.buildAuthorizationUrl(Z,X);console.log(`
|
|
129
129
|
[OAuth] Opening browser for authentication...`),console.log(`
|
|
130
|
-
If the browser does not open automatically, copy and paste this URL:`),console.log(Y),console.log("");let Q=this.startCallbackServer(X.state);try{await this.openAuthorizationUrl(Y)}catch(K){console.warn("[OAuth] Failed to open browser automatically:",K)}let J=await Q;console.log("[OAuth] Authorization code received, exchanging for tokens...");let G=await this.exchangeCodeForToken(Z,J,X.codeVerifier),q={accessToken:G.access_token,tokenType:G.token_type||"Bearer",refreshToken:G.refresh_token,scope:G.scope};if(G.expires_in)q.expiresAt=Date.now()+G.expires_in*1000;return await this.tokenStorage.saveToken($,q,Z.clientId,Z.tokenUrl),console.log("[OAuth] Authentication successful! Token saved."),q}async openAuthorizationUrl($){let{command:Z,args:X}=this.getBrowserCommand($);await new Promise((Y,Q)=>{let J=PH(Z,X,{stdio:"ignore"});J.once("error",Q),J.once("close",(G)=>{if(G===0||G===null)Y();else Q(Error(`Failed to open browser (exit code ${G})`))})})}getBrowserCommand($){if(process.platform==="darwin")return{command:"open",args:[$]};if(process.platform==="win32")return{command:"cmd",args:["/c","start","",$]};return{command:"xdg-open",args:[$]}}async getValidToken($,Z){let X=await this.tokenStorage.getCredentials($);if(!X)return null;let{token:Y}=X;if(!this.tokenStorage.isTokenExpired(Y))return Y.accessToken;if(Y.refreshToken&&Z.clientId&&X.tokenUrl)try{console.log(`[OAuth] Refreshing expired token for server: ${$}`);let Q=await this.refreshAccessToken(Z,Y.refreshToken),J={accessToken:Q.access_token,tokenType:Q.token_type,refreshToken:Q.refresh_token||Y.refreshToken,scope:Q.scope||Y.scope};if(Q.expires_in)J.expiresAt=Date.now()+Q.expires_in*1000;return await this.tokenStorage.saveToken($,J,Z.clientId,X.tokenUrl),J.accessToken}catch(Q){console.error("[OAuth] Failed to refresh token:",Q),await this.tokenStorage.deleteCredentials($)}return null}}var f8=7777,c9="/oauth/callback",$Y=200;var XY=A(()=>{g9()});var YY=A(()=>{XY();g9()});var T2=()=>{};import{EventEmitter as TH}from"events";var l9;var QY=A(()=>{T2();l9=class l9 extends TH{client;config;checkTimer=null;isChecking=!1;consecutiveFailures=0;lastCheckTime=0;currentStatus="healthy";constructor($,Z={}){super();this.client=$,this.config={interval:Z.interval??30000,timeout:Z.timeout??1e4,enabled:Z.enabled??!1,failureThreshold:Z.failureThreshold??3}}start(){if(this.checkTimer){console.warn("[HealthMonitor] 健康监控已在运行");return}if(!this.config.enabled){console.log("[HealthMonitor] 健康监控未启用");return}console.log(`[HealthMonitor] 启动健康监控(间隔: ${this.config.interval}ms)`),this.scheduleNextCheck()}stop(){if(this.checkTimer)clearTimeout(this.checkTimer),this.checkTimer=null,console.log("[HealthMonitor] 停止健康监控")}scheduleNextCheck(){this.checkTimer=setTimeout(async()=>{await this.performHealthCheck(),this.scheduleNextCheck()},this.config.interval)}async performHealthCheck(){if(this.isChecking)return console.warn("[HealthMonitor] 上一次检查仍在进行中"),this.getLastResult();this.isChecking=!0,this.lastCheckTime=Date.now(),this.setStatus("checking");try{let $=this.client.connectionStatus;if($==="connected"){await this.pingServer(),this.consecutiveFailures=0,this.setStatus("healthy");let Z={status:"healthy",timestamp:Date.now(),consecutiveFailures:0};return this.emit("healthCheck",Z),Z}else throw Error(`连接状态异常: ${$}`)}catch($){this.consecutiveFailures++;let Z=$;console.warn(`[HealthMonitor] 健康检查失败(${this.consecutiveFailures}/${this.config.failureThreshold}):`,Z.message);let X;if(this.consecutiveFailures>=this.config.failureThreshold)X="unhealthy",this.emit("unhealthy",this.consecutiveFailures,Z),console.log("[HealthMonitor] 达到失败阈值,触发重连..."),this.triggerReconnection().catch((Q)=>{console.error("[HealthMonitor] 重连失败:",Q)});else X="degraded";this.setStatus(X);let Y={status:X,timestamp:Date.now(),consecutiveFailures:this.consecutiveFailures,lastError:Z};return this.emit("healthCheck",Y),Y}finally{this.isChecking=!1}}async pingServer(){let $=new Promise((X,Y)=>{setTimeout(()=>Y(Error("Health check timeout")),this.config.timeout)}),Z=(async()=>{if(this.client.availableTools.length===0){if(!this.client.server)throw Error("Server info not available")}})();await Promise.race([Z,$])}async triggerReconnection(){try{await this.client.disconnect(),await new Promise(($)=>setTimeout($,1000)),await this.client.connect(),console.log("[HealthMonitor] 重连成功"),this.consecutiveFailures=0,this.setStatus("healthy"),this.emit("reconnected")}catch($){throw console.error("[HealthMonitor] 重连失败:",$),$}}setStatus($){if(this.currentStatus!==$){let Z=this.currentStatus;this.currentStatus=$,this.emit("statusChanged",$,Z)}}getStatus(){return this.currentStatus}getLastResult(){return{status:this.currentStatus,timestamp:this.lastCheckTime,consecutiveFailures:this.consecutiveFailures}}getStatistics(){return{status:this.currentStatus,consecutiveFailures:this.consecutiveFailures,lastCheckTime:this.lastCheckTime,isChecking:this.isChecking,config:this.config}}async checkNow(){return this.performHealthCheck()}resetFailureCount(){if(this.consecutiveFailures=0,this.currentStatus!=="checking")this.setStatus("healthy")}}});import{Client as SH}from"@modelcontextprotocol/sdk/client/index.js";import{SSEClientTransport as CH}from"@modelcontextprotocol/sdk/client/sse.js";import{StdioClientTransport as kH}from"@modelcontextprotocol/sdk/client/stdio.js";import{EventEmitter as fH}from"events";function JY($){if(!($ instanceof Error))return{type:"unknown",isRetryable:!1,originalError:Error(String($))};let Z=$.message.toLowerCase();if(["command not found","no such file","permission denied","invalid configuration","malformed","syntax error"].some((Q)=>Z.includes(Q)))return{type:"config_error",isRetryable:!1,originalError:$};if(Z.includes("unauthorized")||Z.includes("401")||Z.includes("authentication failed"))return{type:"auth_error",isRetryable:!1,originalError:$};if(["timeout","connection refused","network error","temporary","try again","rate limit","too many requests","service unavailable","socket hang up","econnreset","enotfound","econnrefused","etimedout","503","429"].some((Q)=>Z.includes(Q)))return{type:"network_temporary",isRetryable:!0,originalError:$};return{type:"unknown",isRetryable:!0,originalError:$}}var i9;var GY=A(()=>{j8();YY();QY();T2();i9=class i9 extends fH{config;status="disconnected";sdkClient=null;tools=new Map;serverInfo=null;reconnectAttempts=0;MAX_RECONNECT_ATTEMPTS=5;reconnectTimer=null;isManualDisconnect=!1;oauthProvider=null;serverName;healthMonitor=null;constructor($,Z,X){super();this.config=$;if(this.serverName=Z||"default",$.oauth?.enabled)this.oauthProvider=new P3;if(X?.enabled)this.healthMonitor=new l9(this,X),this.healthMonitor.on("unhealthy",(Y,Q)=>{this.emit("unhealthy",Y,Q)}),this.healthMonitor.on("reconnected",()=>{this.emit("healthMonitorReconnected")})}get connectionStatus(){return this.status}get availableTools(){return Array.from(this.tools.values())}get server(){return this.serverInfo}get healthCheck(){return this.healthMonitor}async connect(){return this.connectWithRetry(3,1000)}async connectWithRetry($=3,Z=1000){if(this.status!=="disconnected"&&this.status!=="error")throw Error("客户端已连接或正在连接中");if(this.status==="error"){if(this.sdkClient){try{await this.sdkClient.close()}catch{}this.sdkClient=null}this.setStatus("disconnected")}let X=null;for(let Y=1;Y<=$;Y++)try{await this.doConnect(),this.reconnectAttempts=0;return}catch(Q){X=Q;let J=JY(Q);if(!J.isRetryable)throw console.error("[McpClient] 检测到永久性错误,放弃重试:",J.type),Q;if(Y<$){let G=Z*Math.pow(2,Y-1);console.warn(`[McpClient] 连接失败(${Y}/${$}),${G}ms 后重试...`),await new Promise((q)=>setTimeout(q,G))}}throw X||Error("连接失败")}async doConnect(){try{this.setStatus("connecting"),this.sdkClient=new SH({name:XX(),version:M2()},{capabilities:{roots:{listChanged:!0},sampling:{}}}),this.sdkClient.onclose=()=>{this.handleUnexpectedClose()};let $=await this.createTransport();await this.sdkClient.connect($);let Z=this.sdkClient.getServerVersion();if(this.serverInfo={name:Z?.name||"Unknown",version:Z?.version||"0.0.0"},await this.loadTools(),this.setStatus("connected"),this.emit("connected",this.serverInfo),this.healthMonitor)this.healthMonitor.start()}catch($){throw this.setStatus("error"),this.emit("error",$),$}}handleUnexpectedClose(){if(this.isManualDisconnect)return;if(this.status==="connected")console.warn("[McpClient] 检测到意外断连,准备重连..."),this.setStatus("error"),this.emit("error",Error("MCP服务器连接意外关闭")),this.scheduleReconnect()}scheduleReconnect(){if(this.reconnectTimer)clearTimeout(this.reconnectTimer),this.reconnectTimer=null;if(this.reconnectAttempts>=this.MAX_RECONNECT_ATTEMPTS){console.error("[McpClient] 达到最大重连次数,放弃重连"),this.emit("reconnectFailed");return}let $=Math.min(1000*Math.pow(2,this.reconnectAttempts),30000);this.reconnectAttempts++,console.log(`[McpClient] 将在 ${$}ms 后进行第 ${this.reconnectAttempts} 次重连...`),this.reconnectTimer=setTimeout(async()=>{try{if(this.sdkClient){try{await this.sdkClient.close()}catch{}this.sdkClient=null}this.setStatus("disconnected"),await this.doConnect(),console.log("[McpClient] 重连成功"),this.reconnectAttempts=0,this.emit("reconnected")}catch(Z){if(console.error("[McpClient] 重连失败:",Z),JY(Z).isRetryable)this.scheduleReconnect();else console.error("[McpClient] 检测到永久性错误,停止重连"),this.emit("reconnectFailed")}},$)}async disconnect(){if(this.isManualDisconnect=!0,this.healthMonitor)this.healthMonitor.stop();if(this.reconnectTimer)clearTimeout(this.reconnectTimer),this.reconnectTimer=null;if(this.sdkClient){try{await this.sdkClient.close()}catch($){console.warn("[McpClient] 断开连接时出错:",$)}this.sdkClient=null}this.tools.clear(),this.serverInfo=null,this.reconnectAttempts=0,this.setStatus("disconnected"),this.emit("disconnected"),this.isManualDisconnect=!1}async callTool($,Z={}){if(!this.sdkClient)throw Error("客户端未连接到服务器");if(!this.tools.has($))throw Error(`工具 "${$}" 不存在`);try{return await this.sdkClient.callTool({name:$,arguments:Z})}catch(X){throw console.error(`[McpClient] 调用工具 "${$}" 失败:`,X),X}}async createTransport(){let{type:$,command:Z,args:X,env:Y,url:Q,headers:J,oauth:G}=this.config,q={...J};if(G?.enabled&&this.oauthProvider&&($==="sse"||$==="http"))try{let K=await this.oauthProvider.getValidToken(this.serverName,G);if(!K){console.log(`[McpClient] 服务器 "${this.serverName}" 需要 OAuth 认证`);let W=await this.oauthProvider.authenticate(this.serverName,G);q.Authorization=`Bearer ${W.accessToken}`}else q.Authorization=`Bearer ${K}`}catch(K){throw console.error("[McpClient] OAuth 认证失败:",K),Error(`OAuth 认证失败: ${K instanceof Error?K.message:String(K)}`)}if($==="stdio"){if(!Z)throw Error("stdio 传输需要 command 参数");let K={};for(let[W,U]of Object.entries(process.env))if(U!==void 0)K[W]=U;return new kH({command:Z,args:X||[],env:{...K,...Y},stderr:"ignore"})}else if($==="sse"){if(!Q)throw Error("sse 传输需要 url 参数");return new CH(new URL(Q),{requestInit:{headers:q}})}else if($==="http"){if(!Q)throw Error("http 传输需要 url 参数");let{StreamableHTTPClientTransport:K}=await import("@modelcontextprotocol/sdk/client/streamableHttp.js");return new K(new URL(Q),{requestInit:{headers:q}})}throw Error(`不支持的传输类型: ${$}`)}async loadTools(){if(!this.sdkClient)return;try{let $=await this.sdkClient.listTools();if(this.tools.clear(),$.tools)for(let Z of $.tools)this.tools.set(Z.name,Z);this.emit("toolsUpdated",this.availableTools)}catch($){throw console.error("[McpClient] 加载工具失败:",$),$}}setStatus($){let Z=this.status;this.status=$,this.emit("statusChanged",$,Z)}async initialize(){return this.connect()}async destroy(){return this.disconnect()}async connectToServer($){return this.connect()}async disconnectFromServer($){return this.disconnect()}async listResources($){if(!this.sdkClient)return[];try{return(await this.sdkClient.listResources()).resources||[]}catch{return[]}}async listTools($){return this.availableTools}async readResource($,Z){if(!this.sdkClient)throw Error("客户端未连接");return(await this.sdkClient.readResource({uri:$})).contents?.[0]||{uri:$,text:""}}}});import{EventEmitter as hH}from"events";var N$;var s4=A(()=>{tX();GY();T2();N$=class N$ extends hH{static instance=null;servers=new Map;isDiscovering=!1;constructor(){super()}static getInstance(){if(!N$.instance)N$.instance=new N$;return N$.instance}async registerServer($,Z){if(this.servers.has($))throw Error(`MCP服务器 "${$}" 已经注册`);let X=new i9(Z,$,Z.healthCheck),Y={config:Z,client:X,status:"disconnected",tools:[]};this.setupClientEventHandlers(X,Y,$),this.servers.set($,Y),this.emit("serverRegistered",$,Y);try{await this.connectServer($)}catch(Q){console.warn(`MCP服务器 "${$}" 连接失败:`,Q)}}async unregisterServer($){let Z=this.servers.get($);if(!Z)return;try{await Z.client.disconnect()}catch(X){console.warn(`断开MCP服务器 "${$}" 时出错:`,X)}this.servers.delete($),this.emit("serverUnregistered",$)}async connectServer($){let Z=this.servers.get($);if(!Z)throw Error(`MCP服务器 "${$}" 未注册`);if(Z.status==="connected")return;try{Z.status="connecting",await Z.client.connect(),Z.connectedAt=new Date,Z.lastError=void 0,Z.tools=Z.client.availableTools}catch(X){throw Z.lastError=X,Z.status="error",X}}async disconnectServer($){let Z=this.servers.get($);if(!Z)return;await Z.client.disconnect(),Z.connectedAt=void 0}async reconnectServer($){let Z=this.servers.get($);if(!Z)throw Error(`MCP服务器 "${$}" 未注册`);if(Z.status==="connected")await Z.client.disconnect();try{Z.status="connecting",await Z.client.connect(),Z.connectedAt=new Date,Z.lastError=void 0,Z.tools=Z.client.availableTools}catch(X){throw Z.lastError=X,Z.status="error",X}}async getAvailableTools(){let $=[],Z=new Map;for(let[X,Y]of this.servers)if(Y.status==="connected")for(let Q of Y.tools){let J=Z.get(Q.name)||0;Z.set(Q.name,J+1)}for(let[X,Y]of this.servers)if(Y.status==="connected")for(let Q of Y.tools){let G=(Z.get(Q.name)||0)>1?`${X}__${Q.name}`:Q.name,q=v3(Y.client,X,Q,G);$.push(q)}return $}async findTool($){for(let[Z,X]of this.servers)if(X.status==="connected"){let Y=X.tools.find((Q)=>Q.name===$);if(Y)return v3(X.client,Z,Y)}return null}getToolsByServer($){let Z=this.servers.get($);if(!Z||Z.status!=="connected")return[];return Z.tools.map((X)=>v3(Z.client,$,X))}getServerStatus($){return this.servers.get($)||null}getAllServers(){return new Map(this.servers)}async refreshAllTools(){let $=[];for(let[Z,X]of this.servers)if(X.status==="connected")$.push(this.refreshServerTools(Z));await Promise.allSettled($)}async refreshServerTools($){let Z=this.servers.get($);if(!Z||Z.status!=="connected")return;try{let X=Z.client.availableTools,Y=Z.tools.length;Z.tools=X,this.emit("toolsUpdated",$,X,Y)}catch(X){console.warn(`刷新服务器 "${$}" 工具列表失败:`,X)}}setupClientEventHandlers($,Z,X){$.on("connected",(Y)=>{Z.status="connected",Z.connectedAt=new Date,Z.tools=$.availableTools,this.emit("serverConnected",X,Y)}),$.on("disconnected",()=>{Z.status="disconnected",Z.connectedAt=void 0,Z.tools=[],this.emit("serverDisconnected",X)}),$.on("error",(Y)=>{Z.status="error",Z.lastError=Y,this.emit("serverError",X,Y)}),$.on("toolsUpdated",(Y)=>{let Q=Z.tools.length;Z.tools=Y,this.emit("toolsUpdated",X,Y,Q)}),$.on("statusChanged",(Y,Q)=>{Z.status=Y,this.emit("serverStatusChanged",X,Y,Q)})}async discoverServers(){if(this.isDiscovering)return Array.from(this.servers.values());this.isDiscovering=!0,this.emit("discoveryStarted");try{return Array.from(this.servers.values())}finally{this.isDiscovering=!1,this.emit("discoveryCompleted")}}async registerServers($){let Z=Object.entries($).map(([X,Y])=>this.registerServer(X,Y).catch((Q)=>{return console.warn(`注册MCP服务器 "${X}" 失败:`,Q),Q}));await Promise.allSettled(Z)}getStatistics(){let $=0,Z=0,X=0;for(let Y of this.servers.values())if(Y.status==="connected")$++,Z+=Y.tools.length;else if(Y.status==="error")X++;return{totalServers:this.servers.size,connectedServers:$,errorServers:X,totalTools:Z,isDiscovering:this.isDiscovering}}async disconnectAll(){let $=[];for(let[Z,X]of this.servers)if(X.status==="connected")$.push(X.client.disconnect().catch((Y)=>{console.warn(`断开 MCP 服务器 "${Z}" 时出错:`,Y)}));await Promise.allSettled($),this.servers.clear()}}});function n9($,Z){return{...$,...Z,PreToolUse:Z.PreToolUse??$.PreToolUse,PostToolUse:Z.PostToolUse??$.PostToolUse,PostToolUseFailure:Z.PostToolUseFailure??$.PostToolUseFailure,PermissionRequest:Z.PermissionRequest??$.PermissionRequest,UserPromptSubmit:Z.UserPromptSubmit??$.UserPromptSubmit,SessionStart:Z.SessionStart??$.SessionStart,SessionEnd:Z.SessionEnd??$.SessionEnd,Stop:Z.Stop??$.Stop,SubagentStop:Z.SubagentStop??$.SubagentStop,Notification:Z.Notification??$.Notification,Compaction:Z.Compaction??$.Compaction}}function WY(){let $={};if(process.env.BLADE_DISABLE_HOOKS==="true")$.enabled=!1;if(process.env.BLADE_HOOK_TIMEOUT){let Z=parseInt(process.env.BLADE_HOOK_TIMEOUT,10);if(!isNaN(Z)&&Z>0)$.defaultTimeout=Z}return $}var r9;var UY=A(()=>{r9={enabled:!1,defaultTimeout:60,timeoutBehavior:"ignore",failureBehavior:"ignore",maxConcurrentHooks:5,PreToolUse:[],PostToolUse:[],PostToolUseFailure:[],PermissionRequest:[],UserPromptSubmit:[],SessionStart:[],SessionEnd:[],Stop:[],SubagentStop:[],Notification:[],Compaction:[]}});class o9{executedHooks=new Map;canExecute($,Z){if(!this.executedHooks.has($))this.executedHooks.set($,new Set);if(this.executedHooks.get($).has(Z))return console.warn(`[HookGuard] Hook ${Z} for tool ${$} already executed, skipping`),!1;return!0}markExecuted($,Z){let X=this.executedHooks.get($);if(X)X.add(Z)}cleanup($){this.executedHooks.delete($)}cleanupAll(){this.executedHooks.clear()}}var C1,s9,t9;var C2=A(()=>{((H)=>{H.PreToolUse="PreToolUse";H.PostToolUse="PostToolUse";H.PostToolUseFailure="PostToolUseFailure";H.PermissionRequest="PermissionRequest";H.UserPromptSubmit="UserPromptSubmit";H.SessionStart="SessionStart";H.SessionEnd="SessionEnd";H.Stop="Stop";H.SubagentStop="SubagentStop";H.Notification="Notification";H.Compaction="Compaction"})(C1||={});((Y)=>{Y.Approve="approve";Y.Block="block";Y.Async="async"})(s9||={});((Y)=>{Y.Allow="allow";Y.Deny="deny";Y.Ask="ask"})(t9||={})});import{z as P}from"zod";function HY($){let Z=FF.safeParse($);if(Z.success)return{success:!0,data:Z.data};return{success:!1,error:Z.error}}var R1,aH,rH,nH,oH,sH,tH,eH,$F,ZF,XF,YF,NV,QF,JF,GF,qF,KF,WF,UF,HF,FF,OF,zF,_F,e9,BF,A1,bV;var FY=A(()=>{C2();R1=P.object({hook_event_name:P.nativeEnum(C1),hook_execution_id:P.string(),timestamp:P.string(),project_dir:P.string(),session_id:P.string(),permission_mode:P.enum(["default","autoEdit","yolo","plan"]),_metadata:P.object({blade_version:P.string(),hook_timeout_ms:P.number()}).optional()}),aH=R1.extend({hook_event_name:P.literal("PreToolUse"),tool_name:P.string(),tool_use_id:P.string(),tool_input:P.record(P.unknown())}),rH=R1.extend({hook_event_name:P.literal("PostToolUse"),tool_name:P.string(),tool_use_id:P.string(),tool_input:P.record(P.unknown()),tool_response:P.unknown()}),nH=R1.extend({hook_event_name:P.literal("Stop"),reason:P.string().optional()}),oH=R1.extend({hook_event_name:P.literal("PostToolUseFailure"),tool_name:P.string(),tool_use_id:P.string(),tool_input:P.record(P.unknown()),error:P.string(),error_type:P.string().optional(),is_interrupt:P.boolean(),is_timeout:P.boolean()}),sH=R1.extend({hook_event_name:P.literal("PermissionRequest"),tool_name:P.string(),tool_use_id:P.string(),tool_input:P.record(P.unknown())}),tH=R1.extend({hook_event_name:P.literal("UserPromptSubmit"),user_prompt:P.string(),has_images:P.boolean(),image_count:P.number()}),eH=R1.extend({hook_event_name:P.literal("SessionStart"),is_resume:P.boolean(),resume_session_id:P.string().optional()}),$F=R1.extend({hook_event_name:P.literal("SessionEnd"),reason:P.enum(["user_exit","error","max_turns","idle_timeout","ctrl_c","clear","logout","other"])}),ZF=R1.extend({hook_event_name:P.literal("SubagentStop"),agent_type:P.string(),task_description:P.string().optional(),success:P.boolean(),result_summary:P.string().optional(),error:P.string().optional()}),XF=R1.extend({hook_event_name:P.literal("Notification"),notification_type:P.enum(["permission_prompt","idle_prompt","auth_success","elicitation_dialog","info","warning","error"]),title:P.string().optional(),message:P.string()}),YF=R1.extend({hook_event_name:P.literal("Compaction"),trigger:P.enum(["manual","auto"]),messages_before:P.number(),tokens_before:P.number()}),NV=P.discriminatedUnion("hook_event_name",[aH,rH,nH,oH,sH,tH,eH,$F,ZF,XF,YF]),QF=P.object({hookEventName:P.literal("PreToolUse"),permissionDecision:P.nativeEnum(t9).optional(),permissionDecisionReason:P.string().optional(),updatedInput:P.record(P.unknown()).optional()}),JF=P.object({hookEventName:P.literal("PostToolUse"),additionalContext:P.string().optional(),updatedOutput:P.unknown().optional()}),GF=P.object({hookEventName:P.literal("Stop"),continue:P.boolean().optional(),continueReason:P.string().optional()}),qF=P.object({hookEventName:P.literal("SubagentStop"),continue:P.boolean().optional(),continueReason:P.string().optional(),additionalContext:P.string().optional()}),KF=P.object({hookEventName:P.literal("PermissionRequest"),permissionDecision:P.enum(["approve","deny","ask"]).optional(),permissionDecisionReason:P.string().optional()}),WF=P.object({hookEventName:P.literal("UserPromptSubmit"),updatedPrompt:P.string().optional(),contextInjection:P.string().optional()}),UF=P.object({hookEventName:P.literal("SessionStart"),env:P.record(P.string()).optional()}),HF=P.object({hookEventName:P.literal("Compaction"),blockCompaction:P.boolean().optional(),blockReason:P.string().optional()}),FF=P.object({decision:P.object({behavior:P.nativeEnum(s9)}).optional(),systemMessage:P.string().optional(),hookSpecificOutput:P.discriminatedUnion("hookEventName",[QF,JF,GF,qF,KF,WF,UF,HF]).optional(),suppressOutput:P.boolean().optional()}),OF=P.object({type:P.literal("command"),command:P.string(),timeout:P.number().positive().optional(),statusMessage:P.string().optional()}),zF=P.object({type:P.literal("prompt"),prompt:P.string(),timeout:P.number().positive().optional()}),_F=P.discriminatedUnion("type",[OF,zF]),e9=P.union([P.string(),P.array(P.string())]),BF=P.object({tools:e9.optional(),paths:e9.optional(),commands:e9.optional()}),A1=P.object({name:P.string().optional(),matcher:BF.optional(),hooks:P.array(_F)}),bV=P.object({enabled:P.boolean().optional(),defaultTimeout:P.number().positive().optional(),timeoutBehavior:P.enum(["ignore","deny","ask"]).optional(),failureBehavior:P.enum(["ignore","deny","ask"]).optional(),maxConcurrentHooks:P.number().positive().optional(),PreToolUse:P.array(A1).optional(),PostToolUse:P.array(A1).optional(),PostToolUseFailure:P.array(A1).optional(),PermissionRequest:P.array(A1).optional(),UserPromptSubmit:P.array(A1).optional(),SessionStart:P.array(A1).optional(),SessionEnd:P.array(A1).optional(),Stop:P.array(A1).optional(),SubagentStop:P.array(A1).optional(),Notification:P.array(A1).optional(),Compaction:P.array(A1).optional()})});class $7{parse($,Z,X){if($.timedOut){let Q=X?.timeoutBehavior||"ignore",J="Hook timeout";if(Q==="deny")return{success:!1,blocking:!0,error:"Hook timeout",stdout:$.stdout,stderr:$.stderr,exitCode:$.exitCode,hook:Z};else if(Q==="ask")return{success:!1,blocking:!1,needsConfirmation:!0,warning:"Hook timeout. Continue?",stdout:$.stdout,stderr:$.stderr,exitCode:$.exitCode,hook:Z};else return{success:!1,blocking:!1,warning:"Hook timeout",stdout:$.stdout,stderr:$.stderr,exitCode:$.exitCode,hook:Z}}let Y=this.tryParseJSON($.stdout);if(Y){let Q=HY(Y);if(!Q.success){let G="error"in Q?Q.error.message:"Unknown validation error",q=X?.failureBehavior||"ignore",K=`Invalid hook output JSON: ${G}`;if(q==="deny")return{success:!1,blocking:!0,error:K,stdout:$.stdout,stderr:$.stderr,exitCode:$.exitCode,hook:Z};else if(q==="ask")return{success:!1,blocking:!1,needsConfirmation:!0,warning:`${K}. Continue?`,stdout:$.stdout,stderr:$.stderr,exitCode:$.exitCode,hook:Z};else return{success:!1,blocking:!1,warning:K,stdout:$.stdout,stderr:$.stderr,exitCode:$.exitCode,hook:Z}}let J=Q.data;if(J.decision?.behavior==="block")return{success:!1,blocking:!0,error:J.systemMessage||"Hook blocked execution",output:J,stdout:$.stdout,stderr:$.stderr,exitCode:$.exitCode,hook:Z};if(J.decision?.behavior==="async")return{success:!0,output:J,stdout:$.stdout,stderr:$.stderr,exitCode:$.exitCode,hook:Z};return{success:!0,output:J,stdout:$.stdout,stderr:$.stderr,exitCode:$.exitCode,hook:Z}}return this.parseByExitCode($,Z,X)}parseByExitCode($,Z,X){let Y=$.exitCode;switch(Y){case 0:return{success:!0,stdout:$.stdout,stderr:$.stderr,exitCode:Y,hook:Z};case 2:return{success:!1,blocking:!0,error:$.stderr||$.stdout||"Hook returned exit code 2",stdout:$.stdout,stderr:$.stderr,exitCode:Y,hook:Z};case 124:{let Q=X?.timeoutBehavior||"ignore",J="Hook timeout";if(Q==="deny")return{success:!1,blocking:!0,error:"Hook timeout",stdout:$.stdout,stderr:$.stderr,exitCode:Y,hook:Z};else if(Q==="ask")return{success:!1,blocking:!1,needsConfirmation:!0,warning:"Hook timeout. Continue?",stdout:$.stdout,stderr:$.stderr,exitCode:Y,hook:Z};else return{success:!1,blocking:!1,warning:"Hook timeout",stdout:$.stdout,stderr:$.stderr,exitCode:Y,hook:Z}}default:{let Q=X?.failureBehavior||"ignore",J=$.stderr||$.stdout||`Hook failed with exit code ${Y}`;if(Q==="deny")return{success:!1,blocking:!0,error:J,stdout:$.stdout,stderr:$.stderr,exitCode:Y,hook:Z};else if(Q==="ask")return{success:!1,blocking:!1,needsConfirmation:!0,warning:`${J}. Continue?`,stdout:$.stdout,stderr:$.stderr,exitCode:Y,hook:Z};else return{success:!1,blocking:!1,warning:J,stdout:$.stdout,stderr:$.stderr,exitCode:Y,hook:Z}}}}tryParseJSON($){try{let Z=$.trim();if(!Z)return null;let X=Z.match(/^\s*(\{[\s\S]*\})\s*$/);if(!X)return null;return JSON.parse(X[1])}catch{return null}}}var OY=A(()=>{FY()});import{spawn as LF}from"child_process";class Z7{content="";maxSize;constructor($){this.maxSize=$}append($){if(this.content.length<this.maxSize){let Z=this.maxSize-this.content.length;this.content+=$.substring(0,Z)}}getContent(){return this.content}isFull(){return this.content.length>=this.maxSize}}class X7{MAX_STDOUT_SIZE=1048576;MAX_STDERR_SIZE=1048576;MAX_INPUT_SIZE=102400;async execute($,Z,X,Y){let Q=JSON.stringify(Z);if(Q.length>this.MAX_INPUT_SIZE)throw Error(`Hook input too large: ${Q.length} bytes (max ${this.MAX_INPUT_SIZE})`);let J=this.createSafeEnv(Z),G=LF($,[],{shell:!0,env:J,cwd:X.projectDir,timeout:Y}),q=new Z7(this.MAX_STDOUT_SIZE),K=new Z7(this.MAX_STDERR_SIZE);G.stdout.setEncoding("utf8"),G.stderr.setEncoding("utf8"),G.stdout.on("data",(W)=>{q.append(W)}),G.stderr.on("data",(W)=>{K.append(W)});try{G.stdin.write(Q),G.stdin.end()}catch(W){throw G.kill("SIGTERM"),Error(`Failed to write hook input: ${W}`)}return new Promise((W,U)=>{let H=!1,F=!1,O=null,z=()=>{if(O&&X.abortSignal)X.abortSignal.removeEventListener("abort",O),O=null},_=setTimeout(()=>{H=!0,G.kill("SIGKILL")},Y);if(G.on("close",(B)=>{if(F)return;F=!0,clearTimeout(_),z(),W({stdout:q.getContent(),stderr:K.getContent(),exitCode:H?124:B??1,timedOut:H})}),G.on("error",(B)=>{if(F)return;F=!0,clearTimeout(_),z(),U(B)}),X.abortSignal)O=()=>{if(F)return;F=!0,clearTimeout(_),z(),G.kill("SIGTERM"),W({stdout:q.getContent(),stderr:"Hook cancelled by abort signal",exitCode:1,timedOut:!1})},X.abortSignal.addEventListener("abort",O)})}createSafeEnv($){return{BLADE_PROJECT_DIR:$.project_dir,BLADE_SESSION_ID:$.session_id,BLADE_HOOK_EVENT:$.hook_event_name,BLADE_TOOL_NAME:"tool_name"in $?$.tool_name:"",BLADE_TOOL_USE_ID:"tool_use_id"in $?$.tool_use_id:"",PATH:process.env.PATH||"",HOME:process.env.HOME||"",USER:process.env.USER||"",SHELL:process.env.SHELL||"/bin/sh"}}}var zY=()=>{};class Y7{processExecutor=new X7;outputParser=new $7;async executePreToolHooks($,Z,X){if($.length===0)return{decision:"allow"};let Y="tool_input"in Z?Z.tool_input:{},Q=[];for(let J of $)try{let G={...Z,...Y&&{tool_input:Y}},q=await this.executeHook(J,G,X);if(!q.success){if(q.blocking)return{decision:"deny",reason:q.error};if(q.needsConfirmation)return{decision:"ask",reason:q.warning||q.error};if(q.warning)Q.push(q.warning);continue}let K=q.output?.hookSpecificOutput;if(K&&"permissionDecision"in K){switch(K.permissionDecision){case"deny":return{decision:"deny",reason:K.permissionDecisionReason};case"ask":return{decision:"ask",reason:K.permissionDecisionReason};case"allow":break}if("updatedInput"in K&&K.updatedInput)Y={...Y,...K.updatedInput}}}catch(G){let q=G instanceof Error?G.message:String(G);if(Q.push(`Hook failed: ${q}`),X.config.failureBehavior==="deny")return{decision:"deny",reason:q};else if(X.config.failureBehavior==="ask")return{decision:"ask",reason:`Hook failed: ${q}. Continue?`}}return{decision:"allow",modifiedInput:Y,warning:Q.length>0?Q.join(`
|
|
130
|
+
If the browser does not open automatically, copy and paste this URL:`),console.log(Y),console.log("");let Q=this.startCallbackServer(X.state);try{await this.openAuthorizationUrl(Y)}catch(K){console.warn("[OAuth] Failed to open browser automatically:",K)}let J=await Q;console.log("[OAuth] Authorization code received, exchanging for tokens...");let G=await this.exchangeCodeForToken(Z,J,X.codeVerifier),q={accessToken:G.access_token,tokenType:G.token_type||"Bearer",refreshToken:G.refresh_token,scope:G.scope};if(G.expires_in)q.expiresAt=Date.now()+G.expires_in*1000;return await this.tokenStorage.saveToken($,q,Z.clientId,Z.tokenUrl),console.log("[OAuth] Authentication successful! Token saved."),q}async openAuthorizationUrl($){let{command:Z,args:X}=this.getBrowserCommand($);await new Promise((Y,Q)=>{let J=PH(Z,X,{stdio:"ignore"});J.once("error",Q),J.once("close",(G)=>{if(G===0||G===null)Y();else Q(Error(`Failed to open browser (exit code ${G})`))})})}getBrowserCommand($){if(process.platform==="darwin")return{command:"open",args:[$]};if(process.platform==="win32")return{command:"cmd",args:["/c","start","",$]};return{command:"xdg-open",args:[$]}}async getValidToken($,Z){let X=await this.tokenStorage.getCredentials($);if(!X)return null;let{token:Y}=X;if(!this.tokenStorage.isTokenExpired(Y))return Y.accessToken;if(Y.refreshToken&&Z.clientId&&X.tokenUrl)try{console.log(`[OAuth] Refreshing expired token for server: ${$}`);let Q=await this.refreshAccessToken(Z,Y.refreshToken),J={accessToken:Q.access_token,tokenType:Q.token_type,refreshToken:Q.refresh_token||Y.refreshToken,scope:Q.scope||Y.scope};if(Q.expires_in)J.expiresAt=Date.now()+Q.expires_in*1000;return await this.tokenStorage.saveToken($,J,Z.clientId,X.tokenUrl),J.accessToken}catch(Q){console.error("[OAuth] Failed to refresh token:",Q),await this.tokenStorage.deleteCredentials($)}return null}}var f8=7777,c9="/oauth/callback",$Y=200;var XY=A(()=>{g9()});var YY=A(()=>{XY();g9()});var T4=()=>{};import{EventEmitter as TH}from"events";var l9;var QY=A(()=>{T4();l9=class l9 extends TH{client;config;checkTimer=null;isChecking=!1;consecutiveFailures=0;lastCheckTime=0;currentStatus="healthy";constructor($,Z={}){super();this.client=$,this.config={interval:Z.interval??30000,timeout:Z.timeout??1e4,enabled:Z.enabled??!1,failureThreshold:Z.failureThreshold??3}}start(){if(this.checkTimer){console.warn("[HealthMonitor] 健康监控已在运行");return}if(!this.config.enabled){console.log("[HealthMonitor] 健康监控未启用");return}console.log(`[HealthMonitor] 启动健康监控(间隔: ${this.config.interval}ms)`),this.scheduleNextCheck()}stop(){if(this.checkTimer)clearTimeout(this.checkTimer),this.checkTimer=null,console.log("[HealthMonitor] 停止健康监控")}scheduleNextCheck(){this.checkTimer=setTimeout(async()=>{await this.performHealthCheck(),this.scheduleNextCheck()},this.config.interval)}async performHealthCheck(){if(this.isChecking)return console.warn("[HealthMonitor] 上一次检查仍在进行中"),this.getLastResult();this.isChecking=!0,this.lastCheckTime=Date.now(),this.setStatus("checking");try{let $=this.client.connectionStatus;if($==="connected"){await this.pingServer(),this.consecutiveFailures=0,this.setStatus("healthy");let Z={status:"healthy",timestamp:Date.now(),consecutiveFailures:0};return this.emit("healthCheck",Z),Z}else throw Error(`连接状态异常: ${$}`)}catch($){this.consecutiveFailures++;let Z=$;console.warn(`[HealthMonitor] 健康检查失败(${this.consecutiveFailures}/${this.config.failureThreshold}):`,Z.message);let X;if(this.consecutiveFailures>=this.config.failureThreshold)X="unhealthy",this.emit("unhealthy",this.consecutiveFailures,Z),console.log("[HealthMonitor] 达到失败阈值,触发重连..."),this.triggerReconnection().catch((Q)=>{console.error("[HealthMonitor] 重连失败:",Q)});else X="degraded";this.setStatus(X);let Y={status:X,timestamp:Date.now(),consecutiveFailures:this.consecutiveFailures,lastError:Z};return this.emit("healthCheck",Y),Y}finally{this.isChecking=!1}}async pingServer(){let $=new Promise((X,Y)=>{setTimeout(()=>Y(Error("Health check timeout")),this.config.timeout)}),Z=(async()=>{if(this.client.availableTools.length===0){if(!this.client.server)throw Error("Server info not available")}})();await Promise.race([Z,$])}async triggerReconnection(){try{await this.client.disconnect(),await new Promise(($)=>setTimeout($,1000)),await this.client.connect(),console.log("[HealthMonitor] 重连成功"),this.consecutiveFailures=0,this.setStatus("healthy"),this.emit("reconnected")}catch($){throw console.error("[HealthMonitor] 重连失败:",$),$}}setStatus($){if(this.currentStatus!==$){let Z=this.currentStatus;this.currentStatus=$,this.emit("statusChanged",$,Z)}}getStatus(){return this.currentStatus}getLastResult(){return{status:this.currentStatus,timestamp:this.lastCheckTime,consecutiveFailures:this.consecutiveFailures}}getStatistics(){return{status:this.currentStatus,consecutiveFailures:this.consecutiveFailures,lastCheckTime:this.lastCheckTime,isChecking:this.isChecking,config:this.config}}async checkNow(){return this.performHealthCheck()}resetFailureCount(){if(this.consecutiveFailures=0,this.currentStatus!=="checking")this.setStatus("healthy")}}});import{Client as SH}from"@modelcontextprotocol/sdk/client/index.js";import{SSEClientTransport as CH}from"@modelcontextprotocol/sdk/client/sse.js";import{StdioClientTransport as kH}from"@modelcontextprotocol/sdk/client/stdio.js";import{EventEmitter as fH}from"events";function JY($){if(!($ instanceof Error))return{type:"unknown",isRetryable:!1,originalError:Error(String($))};let Z=$.message.toLowerCase();if(["command not found","no such file","permission denied","invalid configuration","malformed","syntax error"].some((Q)=>Z.includes(Q)))return{type:"config_error",isRetryable:!1,originalError:$};if(Z.includes("unauthorized")||Z.includes("401")||Z.includes("authentication failed"))return{type:"auth_error",isRetryable:!1,originalError:$};if(["timeout","connection refused","network error","temporary","try again","rate limit","too many requests","service unavailable","socket hang up","econnreset","enotfound","econnrefused","etimedout","503","429"].some((Q)=>Z.includes(Q)))return{type:"network_temporary",isRetryable:!0,originalError:$};return{type:"unknown",isRetryable:!0,originalError:$}}var i9;var GY=A(()=>{j8();YY();QY();T4();i9=class i9 extends fH{config;status="disconnected";sdkClient=null;tools=new Map;serverInfo=null;reconnectAttempts=0;MAX_RECONNECT_ATTEMPTS=5;reconnectTimer=null;isManualDisconnect=!1;oauthProvider=null;serverName;healthMonitor=null;constructor($,Z,X){super();this.config=$;if(this.serverName=Z||"default",$.oauth?.enabled)this.oauthProvider=new P3;if(X?.enabled)this.healthMonitor=new l9(this,X),this.healthMonitor.on("unhealthy",(Y,Q)=>{this.emit("unhealthy",Y,Q)}),this.healthMonitor.on("reconnected",()=>{this.emit("healthMonitorReconnected")})}get connectionStatus(){return this.status}get availableTools(){return Array.from(this.tools.values())}get server(){return this.serverInfo}get healthCheck(){return this.healthMonitor}async connect(){return this.connectWithRetry(3,1000)}async connectWithRetry($=3,Z=1000){if(this.status!=="disconnected"&&this.status!=="error")throw Error("客户端已连接或正在连接中");if(this.status==="error"){if(this.sdkClient){try{await this.sdkClient.close()}catch{}this.sdkClient=null}this.setStatus("disconnected")}let X=null;for(let Y=1;Y<=$;Y++)try{await this.doConnect(),this.reconnectAttempts=0;return}catch(Q){X=Q;let J=JY(Q);if(!J.isRetryable)throw console.error("[McpClient] 检测到永久性错误,放弃重试:",J.type),Q;if(Y<$){let G=Z*Math.pow(2,Y-1);console.warn(`[McpClient] 连接失败(${Y}/${$}),${G}ms 后重试...`),await new Promise((q)=>setTimeout(q,G))}}throw X||Error("连接失败")}async doConnect(){try{this.setStatus("connecting"),this.sdkClient=new SH({name:XX(),version:M4()},{capabilities:{roots:{listChanged:!0},sampling:{}}}),this.sdkClient.onclose=()=>{this.handleUnexpectedClose()};let $=await this.createTransport();await this.sdkClient.connect($);let Z=this.sdkClient.getServerVersion();if(this.serverInfo={name:Z?.name||"Unknown",version:Z?.version||"0.0.0"},await this.loadTools(),this.setStatus("connected"),this.emit("connected",this.serverInfo),this.healthMonitor)this.healthMonitor.start()}catch($){throw this.setStatus("error"),this.emit("error",$),$}}handleUnexpectedClose(){if(this.isManualDisconnect)return;if(this.status==="connected")console.warn("[McpClient] 检测到意外断连,准备重连..."),this.setStatus("error"),this.emit("error",Error("MCP服务器连接意外关闭")),this.scheduleReconnect()}scheduleReconnect(){if(this.reconnectTimer)clearTimeout(this.reconnectTimer),this.reconnectTimer=null;if(this.reconnectAttempts>=this.MAX_RECONNECT_ATTEMPTS){console.error("[McpClient] 达到最大重连次数,放弃重连"),this.emit("reconnectFailed");return}let $=Math.min(1000*Math.pow(2,this.reconnectAttempts),30000);this.reconnectAttempts++,console.log(`[McpClient] 将在 ${$}ms 后进行第 ${this.reconnectAttempts} 次重连...`),this.reconnectTimer=setTimeout(async()=>{try{if(this.sdkClient){try{await this.sdkClient.close()}catch{}this.sdkClient=null}this.setStatus("disconnected"),await this.doConnect(),console.log("[McpClient] 重连成功"),this.reconnectAttempts=0,this.emit("reconnected")}catch(Z){if(console.error("[McpClient] 重连失败:",Z),JY(Z).isRetryable)this.scheduleReconnect();else console.error("[McpClient] 检测到永久性错误,停止重连"),this.emit("reconnectFailed")}},$)}async disconnect(){if(this.isManualDisconnect=!0,this.healthMonitor)this.healthMonitor.stop();if(this.reconnectTimer)clearTimeout(this.reconnectTimer),this.reconnectTimer=null;if(this.sdkClient){try{await this.sdkClient.close()}catch($){console.warn("[McpClient] 断开连接时出错:",$)}this.sdkClient=null}this.tools.clear(),this.serverInfo=null,this.reconnectAttempts=0,this.setStatus("disconnected"),this.emit("disconnected"),this.isManualDisconnect=!1}async callTool($,Z={}){if(!this.sdkClient)throw Error("客户端未连接到服务器");if(!this.tools.has($))throw Error(`工具 "${$}" 不存在`);try{return await this.sdkClient.callTool({name:$,arguments:Z})}catch(X){throw console.error(`[McpClient] 调用工具 "${$}" 失败:`,X),X}}async createTransport(){let{type:$,command:Z,args:X,env:Y,url:Q,headers:J,oauth:G}=this.config,q={...J};if(G?.enabled&&this.oauthProvider&&($==="sse"||$==="http"))try{let K=await this.oauthProvider.getValidToken(this.serverName,G);if(!K){console.log(`[McpClient] 服务器 "${this.serverName}" 需要 OAuth 认证`);let W=await this.oauthProvider.authenticate(this.serverName,G);q.Authorization=`Bearer ${W.accessToken}`}else q.Authorization=`Bearer ${K}`}catch(K){throw console.error("[McpClient] OAuth 认证失败:",K),Error(`OAuth 认证失败: ${K instanceof Error?K.message:String(K)}`)}if($==="stdio"){if(!Z)throw Error("stdio 传输需要 command 参数");let K={};for(let[W,U]of Object.entries(process.env))if(U!==void 0)K[W]=U;return new kH({command:Z,args:X||[],env:{...K,...Y},stderr:"ignore"})}else if($==="sse"){if(!Q)throw Error("sse 传输需要 url 参数");return new CH(new URL(Q),{requestInit:{headers:q}})}else if($==="http"){if(!Q)throw Error("http 传输需要 url 参数");let{StreamableHTTPClientTransport:K}=await import("@modelcontextprotocol/sdk/client/streamableHttp.js");return new K(new URL(Q),{requestInit:{headers:q}})}throw Error(`不支持的传输类型: ${$}`)}async loadTools(){if(!this.sdkClient)return;try{let $=await this.sdkClient.listTools();if(this.tools.clear(),$.tools)for(let Z of $.tools)this.tools.set(Z.name,Z);this.emit("toolsUpdated",this.availableTools)}catch($){throw console.error("[McpClient] 加载工具失败:",$),$}}setStatus($){let Z=this.status;this.status=$,this.emit("statusChanged",$,Z)}async initialize(){return this.connect()}async destroy(){return this.disconnect()}async connectToServer($){return this.connect()}async disconnectFromServer($){return this.disconnect()}async listResources($){if(!this.sdkClient)return[];try{return(await this.sdkClient.listResources()).resources||[]}catch{return[]}}async listTools($){return this.availableTools}async readResource($,Z){if(!this.sdkClient)throw Error("客户端未连接");return(await this.sdkClient.readResource({uri:$})).contents?.[0]||{uri:$,text:""}}}});import{EventEmitter as hH}from"events";var N$;var s2=A(()=>{tX();GY();T4();N$=class N$ extends hH{static instance=null;servers=new Map;isDiscovering=!1;constructor(){super()}static getInstance(){if(!N$.instance)N$.instance=new N$;return N$.instance}async registerServer($,Z){if(this.servers.has($))throw Error(`MCP服务器 "${$}" 已经注册`);let X=new i9(Z,$,Z.healthCheck),Y={config:Z,client:X,status:"disconnected",tools:[]};this.setupClientEventHandlers(X,Y,$),this.servers.set($,Y),this.emit("serverRegistered",$,Y);try{await this.connectServer($)}catch(Q){console.warn(`MCP服务器 "${$}" 连接失败:`,Q)}}async unregisterServer($){let Z=this.servers.get($);if(!Z)return;try{await Z.client.disconnect()}catch(X){console.warn(`断开MCP服务器 "${$}" 时出错:`,X)}this.servers.delete($),this.emit("serverUnregistered",$)}async connectServer($){let Z=this.servers.get($);if(!Z)throw Error(`MCP服务器 "${$}" 未注册`);if(Z.status==="connected")return;try{Z.status="connecting",await Z.client.connect(),Z.connectedAt=new Date,Z.lastError=void 0,Z.tools=Z.client.availableTools}catch(X){throw Z.lastError=X,Z.status="error",X}}async disconnectServer($){let Z=this.servers.get($);if(!Z)return;await Z.client.disconnect(),Z.connectedAt=void 0}async reconnectServer($){let Z=this.servers.get($);if(!Z)throw Error(`MCP服务器 "${$}" 未注册`);if(Z.status==="connected")await Z.client.disconnect();try{Z.status="connecting",await Z.client.connect(),Z.connectedAt=new Date,Z.lastError=void 0,Z.tools=Z.client.availableTools}catch(X){throw Z.lastError=X,Z.status="error",X}}async getAvailableTools(){let $=[],Z=new Map;for(let[X,Y]of this.servers)if(Y.status==="connected")for(let Q of Y.tools){let J=Z.get(Q.name)||0;Z.set(Q.name,J+1)}for(let[X,Y]of this.servers)if(Y.status==="connected")for(let Q of Y.tools){let G=(Z.get(Q.name)||0)>1?`${X}__${Q.name}`:Q.name,q=v3(Y.client,X,Q,G);$.push(q)}return $}async findTool($){for(let[Z,X]of this.servers)if(X.status==="connected"){let Y=X.tools.find((Q)=>Q.name===$);if(Y)return v3(X.client,Z,Y)}return null}getToolsByServer($){let Z=this.servers.get($);if(!Z||Z.status!=="connected")return[];return Z.tools.map((X)=>v3(Z.client,$,X))}getServerStatus($){return this.servers.get($)||null}getAllServers(){return new Map(this.servers)}async refreshAllTools(){let $=[];for(let[Z,X]of this.servers)if(X.status==="connected")$.push(this.refreshServerTools(Z));await Promise.allSettled($)}async refreshServerTools($){let Z=this.servers.get($);if(!Z||Z.status!=="connected")return;try{let X=Z.client.availableTools,Y=Z.tools.length;Z.tools=X,this.emit("toolsUpdated",$,X,Y)}catch(X){console.warn(`刷新服务器 "${$}" 工具列表失败:`,X)}}setupClientEventHandlers($,Z,X){$.on("connected",(Y)=>{Z.status="connected",Z.connectedAt=new Date,Z.tools=$.availableTools,this.emit("serverConnected",X,Y)}),$.on("disconnected",()=>{Z.status="disconnected",Z.connectedAt=void 0,Z.tools=[],this.emit("serverDisconnected",X)}),$.on("error",(Y)=>{Z.status="error",Z.lastError=Y,this.emit("serverError",X,Y)}),$.on("toolsUpdated",(Y)=>{let Q=Z.tools.length;Z.tools=Y,this.emit("toolsUpdated",X,Y,Q)}),$.on("statusChanged",(Y,Q)=>{Z.status=Y,this.emit("serverStatusChanged",X,Y,Q)})}async discoverServers(){if(this.isDiscovering)return Array.from(this.servers.values());this.isDiscovering=!0,this.emit("discoveryStarted");try{return Array.from(this.servers.values())}finally{this.isDiscovering=!1,this.emit("discoveryCompleted")}}async registerServers($){let Z=Object.entries($).map(([X,Y])=>this.registerServer(X,Y).catch((Q)=>{return console.warn(`注册MCP服务器 "${X}" 失败:`,Q),Q}));await Promise.allSettled(Z)}getStatistics(){let $=0,Z=0,X=0;for(let Y of this.servers.values())if(Y.status==="connected")$++,Z+=Y.tools.length;else if(Y.status==="error")X++;return{totalServers:this.servers.size,connectedServers:$,errorServers:X,totalTools:Z,isDiscovering:this.isDiscovering}}async disconnectAll(){let $=[];for(let[Z,X]of this.servers)if(X.status==="connected")$.push(X.client.disconnect().catch((Y)=>{console.warn(`断开 MCP 服务器 "${Z}" 时出错:`,Y)}));await Promise.allSettled($),this.servers.clear()}}});function n9($,Z){return{...$,...Z,PreToolUse:Z.PreToolUse??$.PreToolUse,PostToolUse:Z.PostToolUse??$.PostToolUse,PostToolUseFailure:Z.PostToolUseFailure??$.PostToolUseFailure,PermissionRequest:Z.PermissionRequest??$.PermissionRequest,UserPromptSubmit:Z.UserPromptSubmit??$.UserPromptSubmit,SessionStart:Z.SessionStart??$.SessionStart,SessionEnd:Z.SessionEnd??$.SessionEnd,Stop:Z.Stop??$.Stop,SubagentStop:Z.SubagentStop??$.SubagentStop,Notification:Z.Notification??$.Notification,Compaction:Z.Compaction??$.Compaction}}function WY(){let $={};if(process.env.BLADE_DISABLE_HOOKS==="true")$.enabled=!1;if(process.env.BLADE_HOOK_TIMEOUT){let Z=parseInt(process.env.BLADE_HOOK_TIMEOUT,10);if(!isNaN(Z)&&Z>0)$.defaultTimeout=Z}return $}var r9;var UY=A(()=>{r9={enabled:!1,defaultTimeout:60,timeoutBehavior:"ignore",failureBehavior:"ignore",maxConcurrentHooks:5,PreToolUse:[],PostToolUse:[],PostToolUseFailure:[],PermissionRequest:[],UserPromptSubmit:[],SessionStart:[],SessionEnd:[],Stop:[],SubagentStop:[],Notification:[],Compaction:[]}});class o9{executedHooks=new Map;canExecute($,Z){if(!this.executedHooks.has($))this.executedHooks.set($,new Set);if(this.executedHooks.get($).has(Z))return console.warn(`[HookGuard] Hook ${Z} for tool ${$} already executed, skipping`),!1;return!0}markExecuted($,Z){let X=this.executedHooks.get($);if(X)X.add(Z)}cleanup($){this.executedHooks.delete($)}cleanupAll(){this.executedHooks.clear()}}var C1,s9,t9;var C4=A(()=>{((H)=>{H.PreToolUse="PreToolUse";H.PostToolUse="PostToolUse";H.PostToolUseFailure="PostToolUseFailure";H.PermissionRequest="PermissionRequest";H.UserPromptSubmit="UserPromptSubmit";H.SessionStart="SessionStart";H.SessionEnd="SessionEnd";H.Stop="Stop";H.SubagentStop="SubagentStop";H.Notification="Notification";H.Compaction="Compaction"})(C1||={});((Y)=>{Y.Approve="approve";Y.Block="block";Y.Async="async"})(s9||={});((Y)=>{Y.Allow="allow";Y.Deny="deny";Y.Ask="ask"})(t9||={})});import{z as P}from"zod";function HY($){let Z=FF.safeParse($);if(Z.success)return{success:!0,data:Z.data};return{success:!1,error:Z.error}}var R1,aH,rH,nH,oH,sH,tH,eH,$F,ZF,XF,YF,NV,QF,JF,GF,qF,KF,WF,UF,HF,FF,OF,zF,_F,e9,BF,A1,bV;var FY=A(()=>{C4();R1=P.object({hook_event_name:P.nativeEnum(C1),hook_execution_id:P.string(),timestamp:P.string(),project_dir:P.string(),session_id:P.string(),permission_mode:P.enum(["default","autoEdit","yolo","plan"]),_metadata:P.object({blade_version:P.string(),hook_timeout_ms:P.number()}).optional()}),aH=R1.extend({hook_event_name:P.literal("PreToolUse"),tool_name:P.string(),tool_use_id:P.string(),tool_input:P.record(P.unknown())}),rH=R1.extend({hook_event_name:P.literal("PostToolUse"),tool_name:P.string(),tool_use_id:P.string(),tool_input:P.record(P.unknown()),tool_response:P.unknown()}),nH=R1.extend({hook_event_name:P.literal("Stop"),reason:P.string().optional()}),oH=R1.extend({hook_event_name:P.literal("PostToolUseFailure"),tool_name:P.string(),tool_use_id:P.string(),tool_input:P.record(P.unknown()),error:P.string(),error_type:P.string().optional(),is_interrupt:P.boolean(),is_timeout:P.boolean()}),sH=R1.extend({hook_event_name:P.literal("PermissionRequest"),tool_name:P.string(),tool_use_id:P.string(),tool_input:P.record(P.unknown())}),tH=R1.extend({hook_event_name:P.literal("UserPromptSubmit"),user_prompt:P.string(),has_images:P.boolean(),image_count:P.number()}),eH=R1.extend({hook_event_name:P.literal("SessionStart"),is_resume:P.boolean(),resume_session_id:P.string().optional()}),$F=R1.extend({hook_event_name:P.literal("SessionEnd"),reason:P.enum(["user_exit","error","max_turns","idle_timeout","ctrl_c","clear","logout","other"])}),ZF=R1.extend({hook_event_name:P.literal("SubagentStop"),agent_type:P.string(),task_description:P.string().optional(),success:P.boolean(),result_summary:P.string().optional(),error:P.string().optional()}),XF=R1.extend({hook_event_name:P.literal("Notification"),notification_type:P.enum(["permission_prompt","idle_prompt","auth_success","elicitation_dialog","info","warning","error"]),title:P.string().optional(),message:P.string()}),YF=R1.extend({hook_event_name:P.literal("Compaction"),trigger:P.enum(["manual","auto"]),messages_before:P.number(),tokens_before:P.number()}),NV=P.discriminatedUnion("hook_event_name",[aH,rH,nH,oH,sH,tH,eH,$F,ZF,XF,YF]),QF=P.object({hookEventName:P.literal("PreToolUse"),permissionDecision:P.nativeEnum(t9).optional(),permissionDecisionReason:P.string().optional(),updatedInput:P.record(P.unknown()).optional()}),JF=P.object({hookEventName:P.literal("PostToolUse"),additionalContext:P.string().optional(),updatedOutput:P.unknown().optional()}),GF=P.object({hookEventName:P.literal("Stop"),continue:P.boolean().optional(),continueReason:P.string().optional()}),qF=P.object({hookEventName:P.literal("SubagentStop"),continue:P.boolean().optional(),continueReason:P.string().optional(),additionalContext:P.string().optional()}),KF=P.object({hookEventName:P.literal("PermissionRequest"),permissionDecision:P.enum(["approve","deny","ask"]).optional(),permissionDecisionReason:P.string().optional()}),WF=P.object({hookEventName:P.literal("UserPromptSubmit"),updatedPrompt:P.string().optional(),contextInjection:P.string().optional()}),UF=P.object({hookEventName:P.literal("SessionStart"),env:P.record(P.string()).optional()}),HF=P.object({hookEventName:P.literal("Compaction"),blockCompaction:P.boolean().optional(),blockReason:P.string().optional()}),FF=P.object({decision:P.object({behavior:P.nativeEnum(s9)}).optional(),systemMessage:P.string().optional(),hookSpecificOutput:P.discriminatedUnion("hookEventName",[QF,JF,GF,qF,KF,WF,UF,HF]).optional(),suppressOutput:P.boolean().optional()}),OF=P.object({type:P.literal("command"),command:P.string(),timeout:P.number().positive().optional(),statusMessage:P.string().optional()}),zF=P.object({type:P.literal("prompt"),prompt:P.string(),timeout:P.number().positive().optional()}),_F=P.discriminatedUnion("type",[OF,zF]),e9=P.union([P.string(),P.array(P.string())]),BF=P.object({tools:e9.optional(),paths:e9.optional(),commands:e9.optional()}),A1=P.object({name:P.string().optional(),matcher:BF.optional(),hooks:P.array(_F)}),bV=P.object({enabled:P.boolean().optional(),defaultTimeout:P.number().positive().optional(),timeoutBehavior:P.enum(["ignore","deny","ask"]).optional(),failureBehavior:P.enum(["ignore","deny","ask"]).optional(),maxConcurrentHooks:P.number().positive().optional(),PreToolUse:P.array(A1).optional(),PostToolUse:P.array(A1).optional(),PostToolUseFailure:P.array(A1).optional(),PermissionRequest:P.array(A1).optional(),UserPromptSubmit:P.array(A1).optional(),SessionStart:P.array(A1).optional(),SessionEnd:P.array(A1).optional(),Stop:P.array(A1).optional(),SubagentStop:P.array(A1).optional(),Notification:P.array(A1).optional(),Compaction:P.array(A1).optional()})});class $7{parse($,Z,X){if($.timedOut){let Q=X?.timeoutBehavior||"ignore",J="Hook timeout";if(Q==="deny")return{success:!1,blocking:!0,error:"Hook timeout",stdout:$.stdout,stderr:$.stderr,exitCode:$.exitCode,hook:Z};else if(Q==="ask")return{success:!1,blocking:!1,needsConfirmation:!0,warning:"Hook timeout. Continue?",stdout:$.stdout,stderr:$.stderr,exitCode:$.exitCode,hook:Z};else return{success:!1,blocking:!1,warning:"Hook timeout",stdout:$.stdout,stderr:$.stderr,exitCode:$.exitCode,hook:Z}}let Y=this.tryParseJSON($.stdout);if(Y){let Q=HY(Y);if(!Q.success){let G="error"in Q?Q.error.message:"Unknown validation error",q=X?.failureBehavior||"ignore",K=`Invalid hook output JSON: ${G}`;if(q==="deny")return{success:!1,blocking:!0,error:K,stdout:$.stdout,stderr:$.stderr,exitCode:$.exitCode,hook:Z};else if(q==="ask")return{success:!1,blocking:!1,needsConfirmation:!0,warning:`${K}. Continue?`,stdout:$.stdout,stderr:$.stderr,exitCode:$.exitCode,hook:Z};else return{success:!1,blocking:!1,warning:K,stdout:$.stdout,stderr:$.stderr,exitCode:$.exitCode,hook:Z}}let J=Q.data;if(J.decision?.behavior==="block")return{success:!1,blocking:!0,error:J.systemMessage||"Hook blocked execution",output:J,stdout:$.stdout,stderr:$.stderr,exitCode:$.exitCode,hook:Z};if(J.decision?.behavior==="async")return{success:!0,output:J,stdout:$.stdout,stderr:$.stderr,exitCode:$.exitCode,hook:Z};return{success:!0,output:J,stdout:$.stdout,stderr:$.stderr,exitCode:$.exitCode,hook:Z}}return this.parseByExitCode($,Z,X)}parseByExitCode($,Z,X){let Y=$.exitCode;switch(Y){case 0:return{success:!0,stdout:$.stdout,stderr:$.stderr,exitCode:Y,hook:Z};case 2:return{success:!1,blocking:!0,error:$.stderr||$.stdout||"Hook returned exit code 2",stdout:$.stdout,stderr:$.stderr,exitCode:Y,hook:Z};case 124:{let Q=X?.timeoutBehavior||"ignore",J="Hook timeout";if(Q==="deny")return{success:!1,blocking:!0,error:"Hook timeout",stdout:$.stdout,stderr:$.stderr,exitCode:Y,hook:Z};else if(Q==="ask")return{success:!1,blocking:!1,needsConfirmation:!0,warning:"Hook timeout. Continue?",stdout:$.stdout,stderr:$.stderr,exitCode:Y,hook:Z};else return{success:!1,blocking:!1,warning:"Hook timeout",stdout:$.stdout,stderr:$.stderr,exitCode:Y,hook:Z}}default:{let Q=X?.failureBehavior||"ignore",J=$.stderr||$.stdout||`Hook failed with exit code ${Y}`;if(Q==="deny")return{success:!1,blocking:!0,error:J,stdout:$.stdout,stderr:$.stderr,exitCode:Y,hook:Z};else if(Q==="ask")return{success:!1,blocking:!1,needsConfirmation:!0,warning:`${J}. Continue?`,stdout:$.stdout,stderr:$.stderr,exitCode:Y,hook:Z};else return{success:!1,blocking:!1,warning:J,stdout:$.stdout,stderr:$.stderr,exitCode:Y,hook:Z}}}}tryParseJSON($){try{let Z=$.trim();if(!Z)return null;let X=Z.match(/^\s*(\{[\s\S]*\})\s*$/);if(!X)return null;return JSON.parse(X[1])}catch{return null}}}var OY=A(()=>{FY()});import{spawn as LF}from"child_process";class Z7{content="";maxSize;constructor($){this.maxSize=$}append($){if(this.content.length<this.maxSize){let Z=this.maxSize-this.content.length;this.content+=$.substring(0,Z)}}getContent(){return this.content}isFull(){return this.content.length>=this.maxSize}}class X7{MAX_STDOUT_SIZE=1048576;MAX_STDERR_SIZE=1048576;MAX_INPUT_SIZE=102400;async execute($,Z,X,Y){let Q=JSON.stringify(Z);if(Q.length>this.MAX_INPUT_SIZE)throw Error(`Hook input too large: ${Q.length} bytes (max ${this.MAX_INPUT_SIZE})`);let J=this.createSafeEnv(Z),G=LF($,[],{shell:!0,env:J,cwd:X.projectDir,timeout:Y}),q=new Z7(this.MAX_STDOUT_SIZE),K=new Z7(this.MAX_STDERR_SIZE);G.stdout.setEncoding("utf8"),G.stderr.setEncoding("utf8"),G.stdout.on("data",(W)=>{q.append(W)}),G.stderr.on("data",(W)=>{K.append(W)});try{G.stdin.write(Q),G.stdin.end()}catch(W){throw G.kill("SIGTERM"),Error(`Failed to write hook input: ${W}`)}return new Promise((W,U)=>{let H=!1,F=!1,O=null,z=()=>{if(O&&X.abortSignal)X.abortSignal.removeEventListener("abort",O),O=null},_=setTimeout(()=>{H=!0,G.kill("SIGKILL")},Y);if(G.on("close",(B)=>{if(F)return;F=!0,clearTimeout(_),z(),W({stdout:q.getContent(),stderr:K.getContent(),exitCode:H?124:B??1,timedOut:H})}),G.on("error",(B)=>{if(F)return;F=!0,clearTimeout(_),z(),U(B)}),X.abortSignal)O=()=>{if(F)return;F=!0,clearTimeout(_),z(),G.kill("SIGTERM"),W({stdout:q.getContent(),stderr:"Hook cancelled by abort signal",exitCode:1,timedOut:!1})},X.abortSignal.addEventListener("abort",O)})}createSafeEnv($){return{BLADE_PROJECT_DIR:$.project_dir,BLADE_SESSION_ID:$.session_id,BLADE_HOOK_EVENT:$.hook_event_name,BLADE_TOOL_NAME:"tool_name"in $?$.tool_name:"",BLADE_TOOL_USE_ID:"tool_use_id"in $?$.tool_use_id:"",PATH:process.env.PATH||"",HOME:process.env.HOME||"",USER:process.env.USER||"",SHELL:process.env.SHELL||"/bin/sh"}}}var zY=()=>{};class Y7{processExecutor=new X7;outputParser=new $7;async executePreToolHooks($,Z,X){if($.length===0)return{decision:"allow"};let Y="tool_input"in Z?Z.tool_input:{},Q=[];for(let J of $)try{let G={...Z,...Y&&{tool_input:Y}},q=await this.executeHook(J,G,X);if(!q.success){if(q.blocking)return{decision:"deny",reason:q.error};if(q.needsConfirmation)return{decision:"ask",reason:q.warning||q.error};if(q.warning)Q.push(q.warning);continue}let K=q.output?.hookSpecificOutput;if(K&&"permissionDecision"in K){switch(K.permissionDecision){case"deny":return{decision:"deny",reason:K.permissionDecisionReason};case"ask":return{decision:"ask",reason:K.permissionDecisionReason};case"allow":break}if("updatedInput"in K&&K.updatedInput)Y={...Y,...K.updatedInput}}}catch(G){let q=G instanceof Error?G.message:String(G);if(Q.push(`Hook failed: ${q}`),X.config.failureBehavior==="deny")return{decision:"deny",reason:q};else if(X.config.failureBehavior==="ask")return{decision:"ask",reason:`Hook failed: ${q}. Continue?`}}return{decision:"allow",modifiedInput:Y,warning:Q.length>0?Q.join(`
|
|
131
131
|
`):void 0}}async executePostToolHooks($,Z,X){if($.length===0)return{};let Y=X.config.maxConcurrentHooks||5,Q=await this.executeHooksConcurrently($,Z,X,Y),J=[],G=void 0,q=[];for(let K of Q){if(!K.success&&K.warning){q.push(K.warning);continue}let W=K.output?.hookSpecificOutput;if(W&&"additionalContext"in W){if(W.additionalContext)J.push(W.additionalContext);if("updatedOutput"in W&&W.updatedOutput!==void 0)G=W.updatedOutput}}return{additionalContext:J.length>0?J.join(`
|
|
132
132
|
|
|
133
133
|
`):void 0,modifiedOutput:G,warning:q.length>0?q.join(`
|
|
@@ -150,12 +150,12 @@ If the browser does not open automatically, copy and paste this URL:`),console.l
|
|
|
150
150
|
`):void 0}}async executeNotificationHooks($,Z,X){let Y="message"in Z?Z.message:"";if($.length===0)return{suppress:!1,message:Y};let Q=[],J=!1,G=Y;for(let q of $)try{let K=await this.executeHook(q,Z,X);if(!K.success){if(K.warning)Q.push(K.warning);continue}if(K.output?.suppressOutput){J=!0;break}if(K.stdout&&K.stdout.trim())G=K.stdout.trim()}catch(K){let W=K instanceof Error?K.message:String(K);Q.push(`Hook failed: ${W}`)}return{suppress:J,message:G,warning:Q.length>0?Q.join(`
|
|
151
151
|
`):void 0}}async executeCompactionHooks($,Z,X){if($.length===0)return{blockCompaction:!1};let Y=[];for(let Q of $)try{let J=await this.executeHook(Q,Z,X);if(!J.success){if(J.warning)Y.push(J.warning);continue}let G=J.output?.hookSpecificOutput;if(G&&"blockCompaction"in G&&G.blockCompaction)return{blockCompaction:!0,blockReason:G.blockReason,warning:Y.length>0?Y.join(`
|
|
152
152
|
`):void 0}}catch(J){let G=J instanceof Error?J.message:String(J);Y.push(`Hook failed: ${G}`)}return{blockCompaction:!1,warning:Y.length>0?Y.join(`
|
|
153
|
-
`):void 0}}async executeHook($,Z,X){if($.type==="command")return this.executeCommandHook($,Z,X);throw Error(`Hook type ${$.type} not yet implemented`)}async executeCommandHook($,Z,X){let Y=($.timeout??X.config.defaultTimeout??60)*1000;try{let Q=await this.processExecutor.execute($.command,Z,X,Y);return this.outputParser.parse(Q,$,{timeoutBehavior:X.config.timeoutBehavior,failureBehavior:X.config.failureBehavior})}catch(Q){return{success:!1,blocking:!1,error:Q instanceof Error?Q.message:String(Q),hook:$}}}async executeHooksConcurrently($,Z,X,Y){let Q=[],J=new Set;for(let G of $){if(J.size>=Y)await Promise.race(J);let q=this.executeHook(G,Z,X).catch((W)=>({success:!1,blocking:!1,error:W instanceof Error?W.message:String(W),hook:G})),K=q.then(()=>{J.delete(K)}).catch(()=>{J.delete(K)});J.add(K),Q.push(q)}return Promise.all(Q)}}var _Y=A(()=>{OY();zY();C2()});import Q7 from"picomatch";class J7{matches($,Z){if(!$)return!0;if($.tools&&Z.toolName){if(!this.matchTools($.tools,Z))return!1}if($.paths&&Z.filePath){if(!this.matchPaths($.paths,Z.filePath))return!1}if($.commands&&Z.command){if(!this.matchCommands($.commands,Z.command))return!1}return!0}matchTools($,Z){if(Array.isArray($))return $.some((X)=>this.matchToolWithParams(X,Z));return this.matchToolWithParams($,Z)}matchPaths($,Z){if(Array.isArray($))return $.some((Y)=>{return Q7(Y)(Z)});return Q7($)(Z)}matchCommands($,Z){if(Array.isArray($))return $.some((X)=>this.matchPattern(Z,X));return this.matchPattern(Z,$)}matchToolWithParams($,Z){let{toolName:X,command:Y,filePath:Q}=Z,J=wF.exec($);if(!J)return this.matchPattern(X,$);let[,G,q]=J;if(!this.matchPattern(X,G))return!1;let K=this.getArgValue(X,Y,Q);if(!K)return!1;return this.matchGlobOrPattern(K,q)}getArgValue($,Z,X){if($==="Bash"||$==="BashTool")return Z;if(["Read","Edit","Write","Glob","Grep"].includes($))return X;return Z||X}matchGlobOrPattern($,Z){if(/[*?[\]{}!]/.test(Z))try{return Q7(Z,{bash:!0,dot:!0})($)}catch{}if(Z.endsWith("*")){let X=Z.slice(0,-1);return $.startsWith(X)}return $===Z}matchPattern($,Z){if(Z==="*")return!0;if(!Z.includes("|")&&!/[.*+?^${}()|[\]\\]/.test(Z))return $===Z;if(Z.includes("|"))return Z.split("|").map((Y)=>Y.trim()).includes($);try{return new RegExp(Z).test($)}catch{return $===Z}}}var wF;var BY=A(()=>{wF=/^([A-Za-z0-9_|]+)\((.+)\)$/});import{nanoid as V1}from"nanoid";class M0{static instance=null;config=r9;executor=new Y7;guard=new o9;matcher=new J7;sessionDisabled=!1;constructor(){}static getInstance(){if(!M0.instance)M0.instance=new M0;return M0.instance}loadConfig($){let Z=n9(r9,$),X=WY();Z=n9(Z,X),this.config=Z}isEnabled(){if(!this.config.enabled)return!1;if(this.sessionDisabled)return!1;return!0}disable(){this.sessionDisabled=!0,console.log("[HookManager] Hooks disabled for this session")}enable(){this.sessionDisabled=!1,console.log("[HookManager] Hooks enabled for this session")}getConfig(){return this.config}async reloadConfig(){let $=await import("node:fs/promises"),Z=await import("node:path");try{let X=Z.join(process.cwd(),".blade","settings.local.json"),Y=await $.readFile(X,"utf-8"),Q=JSON.parse(Y);if(Q.hooks)this.loadConfig(Q.hooks)}catch{}}async executePreToolHooks($,Z,X,Y){if(!this.isEnabled())return{decision:"allow"};if(Y.permissionMode==="plan")return{decision:"allow"};if(!this.guard.canExecute(Z,"PreToolUse"))return{decision:"allow"};let Q={hook_event_name:"PreToolUse",hook_execution_id:V1(),timestamp:new Date().toISOString(),tool_name:$,tool_use_id:Z,tool_input:X,project_dir:Y.projectDir,session_id:Y.sessionId,permission_mode:Y.permissionMode},J=this.getMatchingHooks("PreToolUse",{toolName:$,filePath:this.extractFilePath(X),command:this.extractCommand($,X)});if(J.length===0)return{decision:"allow"};let G={projectDir:Y.projectDir,sessionId:Y.sessionId,permissionMode:Y.permissionMode,config:this.config,abortSignal:Y.abortSignal};try{let q=await this.executor.executePreToolHooks(J,Q,G);if(this.guard.markExecuted(Z,"PreToolUse"),Y.permissionMode==="yolo"){if(q.decision==="deny")return q;return{decision:"allow",modifiedInput:q.modifiedInput,warning:q.warning,reason:q.reason}}return q}catch(q){return console.error("[HookManager] Error executing PreToolUse hooks:",q),{decision:"allow",warning:`Hook execution failed: ${q instanceof Error?q.message:String(q)}`}}}async executePostToolHooks($,Z,X,Y,Q){if(!this.isEnabled())return{};if(Q.permissionMode==="plan")return{};if(!this.guard.canExecute(Z,"PostToolUse"))return{};let J={hook_event_name:"PostToolUse",hook_execution_id:V1(),timestamp:new Date().toISOString(),tool_name:$,tool_use_id:Z,tool_input:X,tool_response:Y,project_dir:Q.projectDir,session_id:Q.sessionId,permission_mode:Q.permissionMode},G=this.getMatchingHooks("PostToolUse",{toolName:$,filePath:this.extractFilePath(X),command:this.extractCommand($,X)});if(G.length===0)return{};let q={projectDir:Q.projectDir,sessionId:Q.sessionId,permissionMode:Q.permissionMode,config:this.config,abortSignal:Q.abortSignal};try{let K=await this.executor.executePostToolHooks(G,J,q);return this.guard.markExecuted(Z,"PostToolUse"),K}catch(K){return console.error("[HookManager] Error executing PostToolUse hooks:",K),{warning:`Hook execution failed: ${K instanceof Error?K.message:String(K)}`}}finally{this.guard.cleanup(Z)}}async executeStopHooks($){if(!this.isEnabled())return{shouldStop:!0};let Z={hook_event_name:"Stop",hook_execution_id:V1(),timestamp:new Date().toISOString(),project_dir:$.projectDir,session_id:$.sessionId,permission_mode:$.permissionMode,reason:$.reason},X=this.getMatchingHooks("Stop",{});if(X.length===0)return{shouldStop:!0};let Y={projectDir:$.projectDir,sessionId:$.sessionId,permissionMode:$.permissionMode,config:this.config,abortSignal:$.abortSignal};try{return await this.executor.executeStopHooks(X,Z,Y)}catch(Q){return console.error("[HookManager] Error executing Stop hooks:",Q),{shouldStop:!0,warning:`Hook execution failed: ${Q instanceof Error?Q.message:String(Q)}`}}}async executeSubagentStopHooks($,Z){if(!this.isEnabled())return{shouldStop:!0};let X={hook_event_name:"SubagentStop",hook_execution_id:V1(),timestamp:new Date().toISOString(),project_dir:Z.projectDir,session_id:Z.sessionId,permission_mode:Z.permissionMode,agent_type:$,task_description:Z.taskDescription,success:Z.success,result_summary:Z.resultSummary,error:Z.error},Y=this.getMatchingHooks("SubagentStop",{});if(Y.length===0)return{shouldStop:!0};let Q={projectDir:Z.projectDir,sessionId:Z.sessionId,permissionMode:Z.permissionMode,config:this.config,abortSignal:Z.abortSignal};try{return await this.executor.executeSubagentStopHooks(Y,X,Q)}catch(J){return console.error("[HookManager] Error executing SubagentStop hooks:",J),{shouldStop:!0,warning:`Hook execution failed: ${J instanceof Error?J.message:String(J)}`}}}async executePermissionRequestHooks($,Z,X,Y){if(!this.isEnabled())return{decision:"ask"};let Q={hook_event_name:"PermissionRequest",hook_execution_id:V1(),timestamp:new Date().toISOString(),tool_name:$,tool_use_id:Z,tool_input:X,project_dir:Y.projectDir,session_id:Y.sessionId,permission_mode:Y.permissionMode},J=this.getMatchingHooks("PermissionRequest",{toolName:$,filePath:this.extractFilePath(X),command:this.extractCommand($,X)});if(J.length===0)return{decision:"ask"};let G={projectDir:Y.projectDir,sessionId:Y.sessionId,permissionMode:Y.permissionMode,config:this.config,abortSignal:Y.abortSignal};try{return await this.executor.executePermissionRequestHooks(J,Q,G)}catch(q){return console.error("[HookManager] Error executing PermissionRequest hooks:",q),{decision:"ask",warning:`Hook execution failed: ${q instanceof Error?q.message:String(q)}`}}}async executeUserPromptSubmitHooks($,Z){if(!this.isEnabled())return{proceed:!0};let X={hook_event_name:"UserPromptSubmit",hook_execution_id:V1(),timestamp:new Date().toISOString(),user_prompt:$,has_images:Z.hasImages,image_count:Z.imageCount,project_dir:Z.projectDir,session_id:Z.sessionId,permission_mode:Z.permissionMode},Y=this.getMatchingHooks("UserPromptSubmit",{});if(Y.length===0)return{proceed:!0};let Q={projectDir:Z.projectDir,sessionId:Z.sessionId,permissionMode:Z.permissionMode,config:this.config,abortSignal:Z.abortSignal};try{return await this.executor.executeUserPromptSubmitHooks(Y,X,Q)}catch(J){return console.error("[HookManager] Error executing UserPromptSubmit hooks:",J),{proceed:!0,warning:`Hook execution failed: ${J instanceof Error?J.message:String(J)}`}}}async executeSessionStartHooks($){if(!this.isEnabled())return{proceed:!0};let Z={hook_event_name:"SessionStart",hook_execution_id:V1(),timestamp:new Date().toISOString(),project_dir:$.projectDir,session_id:$.sessionId,permission_mode:$.permissionMode,is_resume:$.isResume,resume_session_id:$.resumeSessionId},X=this.getMatchingHooks("SessionStart",{});if(X.length===0)return{proceed:!0};let Y={projectDir:$.projectDir,sessionId:$.sessionId,permissionMode:$.permissionMode,config:this.config,abortSignal:$.abortSignal};try{return await this.executor.executeSessionStartHooks(X,Z,Y)}catch(Q){return console.error("[HookManager] Error executing SessionStart hooks:",Q),{proceed:!0,warning:`Hook execution failed: ${Q instanceof Error?Q.message:String(Q)}`}}}async executeSessionEndHooks($,Z){if(!this.isEnabled())return{};let X={hook_event_name:"SessionEnd",hook_execution_id:V1(),timestamp:new Date().toISOString(),project_dir:Z.projectDir,session_id:Z.sessionId,permission_mode:Z.permissionMode,reason:$},Y=this.getMatchingHooks("SessionEnd",{});if(Y.length===0)return{};let Q={projectDir:Z.projectDir,sessionId:Z.sessionId,permissionMode:Z.permissionMode,config:this.config,abortSignal:Z.abortSignal};try{return await this.executor.executeSessionEndHooks(Y,X,Q),{}}catch(J){return console.error("[HookManager] Error executing SessionEnd hooks:",J),{warning:`Hook execution failed: ${J instanceof Error?J.message:String(J)}`}}}async executePostToolUseFailureHooks($,Z,X,Y,Q){if(!this.isEnabled())return{};let J={hook_event_name:"PostToolUseFailure",hook_execution_id:V1(),timestamp:new Date().toISOString(),tool_name:$,tool_use_id:Z,tool_input:X,error:Y,error_type:Q.errorType,is_interrupt:Q.isInterrupt,is_timeout:Q.isTimeout,project_dir:Q.projectDir,session_id:Q.sessionId,permission_mode:Q.permissionMode},G=this.getMatchingHooks("PostToolUseFailure",{toolName:$,filePath:this.extractFilePath(X),command:this.extractCommand($,X)});if(G.length===0)return{};let q={projectDir:Q.projectDir,sessionId:Q.sessionId,permissionMode:Q.permissionMode,config:this.config,abortSignal:Q.abortSignal};try{return await this.executor.executePostToolUseFailureHooks(G,J,q)}catch(K){return console.error("[HookManager] Error executing PostToolUseFailure hooks:",K),{warning:`Hook execution failed: ${K instanceof Error?K.message:String(K)}`}}}async executeNotificationHooks($,Z,X){if(!this.isEnabled())return{suppress:!1,message:Z};let Y={hook_event_name:"Notification",hook_execution_id:V1(),timestamp:new Date().toISOString(),project_dir:X.projectDir,session_id:X.sessionId,permission_mode:X.permissionMode,notification_type:$,title:X.title,message:Z},Q=this.getMatchingHooks("Notification",{});if(Q.length===0)return{suppress:!1,message:Z};let J={projectDir:X.projectDir,sessionId:X.sessionId,permissionMode:X.permissionMode,config:this.config,abortSignal:X.abortSignal};try{return await this.executor.executeNotificationHooks(Q,Y,J)}catch(G){return console.error("[HookManager] Error executing Notification hooks:",G),{suppress:!1,message:Z,warning:`Hook execution failed: ${G instanceof Error?G.message:String(G)}`}}}async executeCompactionHooks($,Z){if(!this.isEnabled())return{blockCompaction:!1};let X={hook_event_name:"Compaction",hook_execution_id:V1(),timestamp:new Date().toISOString(),project_dir:Z.projectDir,session_id:Z.sessionId,permission_mode:Z.permissionMode,trigger:$,messages_before:Z.messagesBefore,tokens_before:Z.tokensBefore},Y=this.getMatchingHooks("Compaction",{});if(Y.length===0)return{blockCompaction:!1};let Q={projectDir:Z.projectDir,sessionId:Z.sessionId,permissionMode:Z.permissionMode,config:this.config,abortSignal:Z.abortSignal};try{return await this.executor.executeCompactionHooks(Y,X,Q)}catch(J){return console.error("[HookManager] Error executing Compaction hooks:",J),{blockCompaction:!1,warning:`Hook execution failed: ${J instanceof Error?J.message:String(J)}`}}}getMatchingHooks($,Z){let X=this.config[$]||[],Y=[];for(let Q of X)if(this.matcher.matches(Q.matcher,Z))Y.push(...Q.hooks);return Y}extractFilePath($){let Z=["file_path","path","filePath","source","target"];for(let X of Z){let Y=$[X];if(typeof Y==="string")return Y}return}extractCommand($,Z){if($==="Bash"||$==="BashTool"){let X=Z.command;if(typeof X==="string")return X}return}cleanup(){this.guard.cleanupAll()}}var r$=A(()=>{UY();_Y();BY();C2()});function LY(){return"blade-builtin-glm47"}function G7($){return $==="blade-free-tier"}function q7($){return G7($.apiKey)}function bF($){return{id:"blade-builtin-glm47",name:$.name,provider:$.provider,baseUrl:$.baseUrl,model:$.model,apiKey:$.apiKey,maxContextTokens:$.maxContextTokens,maxOutputTokens:$.maxOutputTokens,supportsThinking:$.supportsThinking}}function wY(){return bF(NF[0])}var NF;var C3=A(()=>{NF=[{name:"✨ GLM-4.7 (内置免费)",provider:"openai-compatible",baseUrl:"https://blade-api-proxy.137844255.workers.dev/v1",model:"glm-4.7",apiKey:"blade-free-tier",description:"智谱 GLM-4.7 Thinking - 由 Blade 提供免费额度",maxContextTokens:204800,maxOutputTokens:16384,supportsThinking:!0}]});import NY from"@anthropic-ai/sdk";function AF($){if($.startsWith("data:")){let Z=$.match(/^data:([^;,]+)/);if(Z){let X=Z[1];if(X==="image/jpeg"||X==="image/png"||X==="image/gif"||X==="image/webp")return X}}return"image/png"}function RF($){if($.startsWith("data:")){let Z=$.indexOf(",");if(Z!==-1)return $.slice(Z+1)}return $}function bY($){let Z=new Set;for(let X of $)if(X.role==="assistant"&&X.tool_calls)for(let Y of X.tool_calls)Z.add(Y.id);return $.filter((X)=>{if(X.role==="tool"){if(!X.tool_call_id)return!1;return Z.has(X.tool_call_id)}return!0})}function K7($){if(typeof $==="string")return $;return $.filter((Z)=>Z.type==="text").map((Z)=>Z.text).join(`
|
|
153
|
+
`):void 0}}async executeHook($,Z,X){if($.type==="command")return this.executeCommandHook($,Z,X);throw Error(`Hook type ${$.type} not yet implemented`)}async executeCommandHook($,Z,X){let Y=($.timeout??X.config.defaultTimeout??60)*1000;try{let Q=await this.processExecutor.execute($.command,Z,X,Y);return this.outputParser.parse(Q,$,{timeoutBehavior:X.config.timeoutBehavior,failureBehavior:X.config.failureBehavior})}catch(Q){return{success:!1,blocking:!1,error:Q instanceof Error?Q.message:String(Q),hook:$}}}async executeHooksConcurrently($,Z,X,Y){let Q=[],J=new Set;for(let G of $){if(J.size>=Y)await Promise.race(J);let q=this.executeHook(G,Z,X).catch((W)=>({success:!1,blocking:!1,error:W instanceof Error?W.message:String(W),hook:G})),K=q.then(()=>{J.delete(K)}).catch(()=>{J.delete(K)});J.add(K),Q.push(q)}return Promise.all(Q)}}var _Y=A(()=>{OY();zY();C4()});import Q7 from"picomatch";class J7{matches($,Z){if(!$)return!0;if($.tools&&Z.toolName){if(!this.matchTools($.tools,Z))return!1}if($.paths&&Z.filePath){if(!this.matchPaths($.paths,Z.filePath))return!1}if($.commands&&Z.command){if(!this.matchCommands($.commands,Z.command))return!1}return!0}matchTools($,Z){if(Array.isArray($))return $.some((X)=>this.matchToolWithParams(X,Z));return this.matchToolWithParams($,Z)}matchPaths($,Z){if(Array.isArray($))return $.some((Y)=>{return Q7(Y)(Z)});return Q7($)(Z)}matchCommands($,Z){if(Array.isArray($))return $.some((X)=>this.matchPattern(Z,X));return this.matchPattern(Z,$)}matchToolWithParams($,Z){let{toolName:X,command:Y,filePath:Q}=Z,J=wF.exec($);if(!J)return this.matchPattern(X,$);let[,G,q]=J;if(!this.matchPattern(X,G))return!1;let K=this.getArgValue(X,Y,Q);if(!K)return!1;return this.matchGlobOrPattern(K,q)}getArgValue($,Z,X){if($==="Bash"||$==="BashTool")return Z;if(["Read","Edit","Write","Glob","Grep"].includes($))return X;return Z||X}matchGlobOrPattern($,Z){if(/[*?[\]{}!]/.test(Z))try{return Q7(Z,{bash:!0,dot:!0})($)}catch{}if(Z.endsWith("*")){let X=Z.slice(0,-1);return $.startsWith(X)}return $===Z}matchPattern($,Z){if(Z==="*")return!0;if(!Z.includes("|")&&!/[.*+?^${}()|[\]\\]/.test(Z))return $===Z;if(Z.includes("|"))return Z.split("|").map((Y)=>Y.trim()).includes($);try{return new RegExp(Z).test($)}catch{return $===Z}}}var wF;var BY=A(()=>{wF=/^([A-Za-z0-9_|]+)\((.+)\)$/});import{nanoid as V1}from"nanoid";class M0{static instance=null;config=r9;executor=new Y7;guard=new o9;matcher=new J7;sessionDisabled=!1;constructor(){}static getInstance(){if(!M0.instance)M0.instance=new M0;return M0.instance}loadConfig($){let Z=n9(r9,$),X=WY();Z=n9(Z,X),this.config=Z}isEnabled(){if(!this.config.enabled)return!1;if(this.sessionDisabled)return!1;return!0}disable(){this.sessionDisabled=!0,console.log("[HookManager] Hooks disabled for this session")}enable(){this.sessionDisabled=!1,console.log("[HookManager] Hooks enabled for this session")}getConfig(){return this.config}async reloadConfig(){let $=await import("node:fs/promises"),Z=await import("node:path");try{let X=Z.join(process.cwd(),".blade","settings.local.json"),Y=await $.readFile(X,"utf-8"),Q=JSON.parse(Y);if(Q.hooks)this.loadConfig(Q.hooks)}catch{}}async executePreToolHooks($,Z,X,Y){if(!this.isEnabled())return{decision:"allow"};if(Y.permissionMode==="plan")return{decision:"allow"};if(!this.guard.canExecute(Z,"PreToolUse"))return{decision:"allow"};let Q={hook_event_name:"PreToolUse",hook_execution_id:V1(),timestamp:new Date().toISOString(),tool_name:$,tool_use_id:Z,tool_input:X,project_dir:Y.projectDir,session_id:Y.sessionId,permission_mode:Y.permissionMode},J=this.getMatchingHooks("PreToolUse",{toolName:$,filePath:this.extractFilePath(X),command:this.extractCommand($,X)});if(J.length===0)return{decision:"allow"};let G={projectDir:Y.projectDir,sessionId:Y.sessionId,permissionMode:Y.permissionMode,config:this.config,abortSignal:Y.abortSignal};try{let q=await this.executor.executePreToolHooks(J,Q,G);if(this.guard.markExecuted(Z,"PreToolUse"),Y.permissionMode==="yolo"){if(q.decision==="deny")return q;return{decision:"allow",modifiedInput:q.modifiedInput,warning:q.warning,reason:q.reason}}return q}catch(q){return console.error("[HookManager] Error executing PreToolUse hooks:",q),{decision:"allow",warning:`Hook execution failed: ${q instanceof Error?q.message:String(q)}`}}}async executePostToolHooks($,Z,X,Y,Q){if(!this.isEnabled())return{};if(Q.permissionMode==="plan")return{};if(!this.guard.canExecute(Z,"PostToolUse"))return{};let J={hook_event_name:"PostToolUse",hook_execution_id:V1(),timestamp:new Date().toISOString(),tool_name:$,tool_use_id:Z,tool_input:X,tool_response:Y,project_dir:Q.projectDir,session_id:Q.sessionId,permission_mode:Q.permissionMode},G=this.getMatchingHooks("PostToolUse",{toolName:$,filePath:this.extractFilePath(X),command:this.extractCommand($,X)});if(G.length===0)return{};let q={projectDir:Q.projectDir,sessionId:Q.sessionId,permissionMode:Q.permissionMode,config:this.config,abortSignal:Q.abortSignal};try{let K=await this.executor.executePostToolHooks(G,J,q);return this.guard.markExecuted(Z,"PostToolUse"),K}catch(K){return console.error("[HookManager] Error executing PostToolUse hooks:",K),{warning:`Hook execution failed: ${K instanceof Error?K.message:String(K)}`}}finally{this.guard.cleanup(Z)}}async executeStopHooks($){if(!this.isEnabled())return{shouldStop:!0};let Z={hook_event_name:"Stop",hook_execution_id:V1(),timestamp:new Date().toISOString(),project_dir:$.projectDir,session_id:$.sessionId,permission_mode:$.permissionMode,reason:$.reason},X=this.getMatchingHooks("Stop",{});if(X.length===0)return{shouldStop:!0};let Y={projectDir:$.projectDir,sessionId:$.sessionId,permissionMode:$.permissionMode,config:this.config,abortSignal:$.abortSignal};try{return await this.executor.executeStopHooks(X,Z,Y)}catch(Q){return console.error("[HookManager] Error executing Stop hooks:",Q),{shouldStop:!0,warning:`Hook execution failed: ${Q instanceof Error?Q.message:String(Q)}`}}}async executeSubagentStopHooks($,Z){if(!this.isEnabled())return{shouldStop:!0};let X={hook_event_name:"SubagentStop",hook_execution_id:V1(),timestamp:new Date().toISOString(),project_dir:Z.projectDir,session_id:Z.sessionId,permission_mode:Z.permissionMode,agent_type:$,task_description:Z.taskDescription,success:Z.success,result_summary:Z.resultSummary,error:Z.error},Y=this.getMatchingHooks("SubagentStop",{});if(Y.length===0)return{shouldStop:!0};let Q={projectDir:Z.projectDir,sessionId:Z.sessionId,permissionMode:Z.permissionMode,config:this.config,abortSignal:Z.abortSignal};try{return await this.executor.executeSubagentStopHooks(Y,X,Q)}catch(J){return console.error("[HookManager] Error executing SubagentStop hooks:",J),{shouldStop:!0,warning:`Hook execution failed: ${J instanceof Error?J.message:String(J)}`}}}async executePermissionRequestHooks($,Z,X,Y){if(!this.isEnabled())return{decision:"ask"};let Q={hook_event_name:"PermissionRequest",hook_execution_id:V1(),timestamp:new Date().toISOString(),tool_name:$,tool_use_id:Z,tool_input:X,project_dir:Y.projectDir,session_id:Y.sessionId,permission_mode:Y.permissionMode},J=this.getMatchingHooks("PermissionRequest",{toolName:$,filePath:this.extractFilePath(X),command:this.extractCommand($,X)});if(J.length===0)return{decision:"ask"};let G={projectDir:Y.projectDir,sessionId:Y.sessionId,permissionMode:Y.permissionMode,config:this.config,abortSignal:Y.abortSignal};try{return await this.executor.executePermissionRequestHooks(J,Q,G)}catch(q){return console.error("[HookManager] Error executing PermissionRequest hooks:",q),{decision:"ask",warning:`Hook execution failed: ${q instanceof Error?q.message:String(q)}`}}}async executeUserPromptSubmitHooks($,Z){if(!this.isEnabled())return{proceed:!0};let X={hook_event_name:"UserPromptSubmit",hook_execution_id:V1(),timestamp:new Date().toISOString(),user_prompt:$,has_images:Z.hasImages,image_count:Z.imageCount,project_dir:Z.projectDir,session_id:Z.sessionId,permission_mode:Z.permissionMode},Y=this.getMatchingHooks("UserPromptSubmit",{});if(Y.length===0)return{proceed:!0};let Q={projectDir:Z.projectDir,sessionId:Z.sessionId,permissionMode:Z.permissionMode,config:this.config,abortSignal:Z.abortSignal};try{return await this.executor.executeUserPromptSubmitHooks(Y,X,Q)}catch(J){return console.error("[HookManager] Error executing UserPromptSubmit hooks:",J),{proceed:!0,warning:`Hook execution failed: ${J instanceof Error?J.message:String(J)}`}}}async executeSessionStartHooks($){if(!this.isEnabled())return{proceed:!0};let Z={hook_event_name:"SessionStart",hook_execution_id:V1(),timestamp:new Date().toISOString(),project_dir:$.projectDir,session_id:$.sessionId,permission_mode:$.permissionMode,is_resume:$.isResume,resume_session_id:$.resumeSessionId},X=this.getMatchingHooks("SessionStart",{});if(X.length===0)return{proceed:!0};let Y={projectDir:$.projectDir,sessionId:$.sessionId,permissionMode:$.permissionMode,config:this.config,abortSignal:$.abortSignal};try{return await this.executor.executeSessionStartHooks(X,Z,Y)}catch(Q){return console.error("[HookManager] Error executing SessionStart hooks:",Q),{proceed:!0,warning:`Hook execution failed: ${Q instanceof Error?Q.message:String(Q)}`}}}async executeSessionEndHooks($,Z){if(!this.isEnabled())return{};let X={hook_event_name:"SessionEnd",hook_execution_id:V1(),timestamp:new Date().toISOString(),project_dir:Z.projectDir,session_id:Z.sessionId,permission_mode:Z.permissionMode,reason:$},Y=this.getMatchingHooks("SessionEnd",{});if(Y.length===0)return{};let Q={projectDir:Z.projectDir,sessionId:Z.sessionId,permissionMode:Z.permissionMode,config:this.config,abortSignal:Z.abortSignal};try{return await this.executor.executeSessionEndHooks(Y,X,Q),{}}catch(J){return console.error("[HookManager] Error executing SessionEnd hooks:",J),{warning:`Hook execution failed: ${J instanceof Error?J.message:String(J)}`}}}async executePostToolUseFailureHooks($,Z,X,Y,Q){if(!this.isEnabled())return{};let J={hook_event_name:"PostToolUseFailure",hook_execution_id:V1(),timestamp:new Date().toISOString(),tool_name:$,tool_use_id:Z,tool_input:X,error:Y,error_type:Q.errorType,is_interrupt:Q.isInterrupt,is_timeout:Q.isTimeout,project_dir:Q.projectDir,session_id:Q.sessionId,permission_mode:Q.permissionMode},G=this.getMatchingHooks("PostToolUseFailure",{toolName:$,filePath:this.extractFilePath(X),command:this.extractCommand($,X)});if(G.length===0)return{};let q={projectDir:Q.projectDir,sessionId:Q.sessionId,permissionMode:Q.permissionMode,config:this.config,abortSignal:Q.abortSignal};try{return await this.executor.executePostToolUseFailureHooks(G,J,q)}catch(K){return console.error("[HookManager] Error executing PostToolUseFailure hooks:",K),{warning:`Hook execution failed: ${K instanceof Error?K.message:String(K)}`}}}async executeNotificationHooks($,Z,X){if(!this.isEnabled())return{suppress:!1,message:Z};let Y={hook_event_name:"Notification",hook_execution_id:V1(),timestamp:new Date().toISOString(),project_dir:X.projectDir,session_id:X.sessionId,permission_mode:X.permissionMode,notification_type:$,title:X.title,message:Z},Q=this.getMatchingHooks("Notification",{});if(Q.length===0)return{suppress:!1,message:Z};let J={projectDir:X.projectDir,sessionId:X.sessionId,permissionMode:X.permissionMode,config:this.config,abortSignal:X.abortSignal};try{return await this.executor.executeNotificationHooks(Q,Y,J)}catch(G){return console.error("[HookManager] Error executing Notification hooks:",G),{suppress:!1,message:Z,warning:`Hook execution failed: ${G instanceof Error?G.message:String(G)}`}}}async executeCompactionHooks($,Z){if(!this.isEnabled())return{blockCompaction:!1};let X={hook_event_name:"Compaction",hook_execution_id:V1(),timestamp:new Date().toISOString(),project_dir:Z.projectDir,session_id:Z.sessionId,permission_mode:Z.permissionMode,trigger:$,messages_before:Z.messagesBefore,tokens_before:Z.tokensBefore},Y=this.getMatchingHooks("Compaction",{});if(Y.length===0)return{blockCompaction:!1};let Q={projectDir:Z.projectDir,sessionId:Z.sessionId,permissionMode:Z.permissionMode,config:this.config,abortSignal:Z.abortSignal};try{return await this.executor.executeCompactionHooks(Y,X,Q)}catch(J){return console.error("[HookManager] Error executing Compaction hooks:",J),{blockCompaction:!1,warning:`Hook execution failed: ${J instanceof Error?J.message:String(J)}`}}}getMatchingHooks($,Z){let X=this.config[$]||[],Y=[];for(let Q of X)if(this.matcher.matches(Q.matcher,Z))Y.push(...Q.hooks);return Y}extractFilePath($){let Z=["file_path","path","filePath","source","target"];for(let X of Z){let Y=$[X];if(typeof Y==="string")return Y}return}extractCommand($,Z){if($==="Bash"||$==="BashTool"){let X=Z.command;if(typeof X==="string")return X}return}cleanup(){this.guard.cleanupAll()}}var r$=A(()=>{UY();_Y();BY();C4()});function LY(){return"blade-builtin-glm47"}function G7($){return $==="blade-free-tier"}function q7($){return G7($.apiKey)}function bF($){return{id:"blade-builtin-glm47",name:$.name,provider:$.provider,baseUrl:$.baseUrl,model:$.model,apiKey:$.apiKey,maxContextTokens:$.maxContextTokens,maxOutputTokens:$.maxOutputTokens,supportsThinking:$.supportsThinking}}function wY(){return bF(NF[0])}var NF;var C3=A(()=>{NF=[{name:"✨ GLM-4.7 (内置免费)",provider:"openai-compatible",baseUrl:"https://blade-api-proxy.137844255.workers.dev/v1",model:"glm-4.7",apiKey:"blade-free-tier",description:"智谱 GLM-4.7 Thinking - 由 Blade 提供免费额度",maxContextTokens:204800,maxOutputTokens:16384,supportsThinking:!0}]});import NY from"@anthropic-ai/sdk";function AF($){if($.startsWith("data:")){let Z=$.match(/^data:([^;,]+)/);if(Z){let X=Z[1];if(X==="image/jpeg"||X==="image/png"||X==="image/gif"||X==="image/webp")return X}}return"image/png"}function RF($){if($.startsWith("data:")){let Z=$.indexOf(",");if(Z!==-1)return $.slice(Z+1)}return $}function bY($){let Z=new Set;for(let X of $)if(X.role==="assistant"&&X.tool_calls)for(let Y of X.tool_calls)Z.add(Y.id);return $.filter((X)=>{if(X.role==="tool"){if(!X.tool_call_id)return!1;return Z.has(X.tool_call_id)}return!0})}function K7($){if(typeof $==="string")return $;return $.filter((Z)=>Z.type==="text").map((Z)=>Z.text).join(`
|
|
154
154
|
`)}class W7{client;config;constructor($){if(this.config=$,E0.debug("\uD83D\uDE80 [AnthropicChatService] Initializing"),E0.debug("⚙️ [AnthropicChatService] Config:",{model:$.model,baseUrl:$.baseUrl,temperature:$.temperature,maxContextTokens:$.maxContextTokens,timeout:$.timeout,hasApiKey:!!$.apiKey}),!$.apiKey)throw E0.error("❌ [AnthropicChatService] apiKey is required"),Error("apiKey is required in ChatConfig");if(!$.model)throw E0.error("❌ [AnthropicChatService] model is required"),Error("model is required in ChatConfig");this.client=new NY({apiKey:$.apiKey,baseURL:$.baseUrl||void 0,timeout:$.timeout??180000,maxRetries:3}),E0.debug("✅ [AnthropicChatService] Initialized successfully")}convertToAnthropicMessages($){let Z=$.find((G)=>G.role==="system"),X=Z?K7(Z.content):void 0,Y=[],Q=$.filter((G)=>G.role!=="system");for(let G=0;G<Q.length;G++){let q=Q[G];if(q.role==="assistant"){let K=[],W=K7(q.content);if(W)K.push({type:"text",text:W});if(q.tool_calls)for(let U of q.tool_calls){if(U.type!=="function")continue;let H={};try{H=JSON.parse(U.function.arguments||"{}")}catch{E0.warn(`⚠️ [AnthropicChatService] Failed to parse tool arguments: ${U.function.arguments}`)}K.push({type:"tool_use",id:U.id,name:U.function.name,input:H})}if(K.length>0)Y.push({role:"assistant",content:K})}else if(q.role==="tool"){let K={type:"tool_result",tool_use_id:q.tool_call_id,content:K7(q.content)},W=Y[Y.length-1];if(W?.role==="user"&&Array.isArray(W.content))W.content.push(K);else Y.push({role:"user",content:[K]})}else if(q.role==="user")if(Array.isArray(q.content)){let K=[];for(let W of q.content)if(W.type==="text")K.push({type:"text",text:W.text});else if(W.type==="image_url"){let U=W.image_url.url;K.push({type:"image",source:{type:"base64",media_type:AF(U),data:RF(U)}})}Y.push({role:"user",content:K})}else Y.push({role:"user",content:q.content})}if(Y.length>0&&Y[0].role!=="user")Y.unshift({role:"user",content:"[System initialized]"});let J=[];for(let G of Y){let q=J[J.length-1];if(q?.role===G.role){if(typeof q.content==="string"&&typeof G.content==="string")q.content=`${q.content}
|
|
155
155
|
|
|
156
|
-
${G.content}`;else if(Array.isArray(q.content)&&Array.isArray(G.content))q.content=[...q.content,...G.content];else if(typeof q.content==="string"&&Array.isArray(G.content))q.content=[{type:"text",text:q.content},...G.content];else if(Array.isArray(q.content)&&typeof G.content==="string")q.content.push({type:"text",text:G.content})}else J.push(G)}return{system:X,messages:J}}convertToAnthropicTools($){if(!$||$.length===0)return;return $.map((Z)=>({name:Z.name,description:Z.description,input_schema:Z.parameters}))}parseAnthropicResponse($,Z){let X="",Y=[];for(let Q of $)if(Q.type==="text")X+=Q.text;else if(Q.type==="tool_use")Y.push({id:Q.id,type:"function",function:{name:Q.name,arguments:JSON.stringify(Q.input)}});return{content:X,toolCalls:Y.length>0?Y:void 0,usage:{promptTokens:Z.input_tokens,completionTokens:Z.output_tokens,totalTokens:Z.input_tokens+Z.output_tokens}}}async chat($,Z,X){let Y=Date.now();E0.debug("\uD83D\uDE80 [AnthropicChatService] Starting chat request"),E0.debug("\uD83D\uDCDD [AnthropicChatService] Messages count:",$.length);let Q=bY($);if(Q.length<$.length)E0.debug(`\uD83D\uDD27 [AnthropicChatService] 过滤掉 ${$.length-Q.length} 条孤儿 tool 消息`);let{system:J,messages:G}=this.convertToAnthropicMessages(Q),q=this.convertToAnthropicTools(Z);E0.debug("\uD83D\uDD27 [AnthropicChatService] Tools count:",q?.length||0),E0.debug("\uD83D\uDCE4 [AnthropicChatService] Request params:",{model:this.config.model,messagesCount:G.length,hasSystem:!!J,toolsCount:q?.length||0,max_tokens:this.config.maxOutputTokens??4096,temperature:this.config.temperature??0});try{let K=await this.client.messages.create({model:this.config.model,max_tokens:this.config.maxOutputTokens??4096,system:J,messages:G,tools:q,temperature:this.config.temperature??0},{signal:X}),W=Date.now()-Y;E0.debug("\uD83D\uDCE5 [AnthropicChatService] Response received in",W,"ms"),E0.debug("\uD83D\uDCCA [AnthropicChatService] Response:",{stopReason:K.stop_reason,contentBlocksCount:K.content.length,usage:K.usage});let U=this.parseAnthropicResponse(K.content,K.usage);return E0.debug("✅ [AnthropicChatService] Chat completed successfully"),E0.debug("\uD83D\uDCCA [AnthropicChatService] Final response:",{contentLength:U.content.length,toolCallsCount:U.toolCalls?.length||0,usage:U.usage}),U}catch(K){let W=Date.now()-Y;throw E0.error("❌ [AnthropicChatService] Chat request failed after",W,"ms"),E0.error("❌ [AnthropicChatService] Error details:",K),K}}async*streamChat($,Z,X){let Y=Date.now();E0.debug("\uD83D\uDE80 [AnthropicChatService] Starting stream request"),E0.debug("\uD83D\uDCDD [AnthropicChatService] Messages count:",$.length);let Q=bY($);if(Q.length<$.length)E0.debug(`\uD83D\uDD27 [AnthropicChatService] 过滤掉 ${$.length-Q.length} 条孤儿 tool 消息`);let{system:J,messages:G}=this.convertToAnthropicMessages(Q),q=this.convertToAnthropicTools(Z);E0.debug("\uD83D\uDD27 [AnthropicChatService] Stream tools count:",q?.length||0),E0.debug("\uD83D\uDCE4 [AnthropicChatService] Stream request params:",{model:this.config.model,messagesCount:G.length,hasSystem:!!J,toolsCount:q?.length||0,max_tokens:this.config.maxOutputTokens??4096,temperature:this.config.temperature??0});try{let K=await this.client.messages.create({model:this.config.model,max_tokens:this.config.maxOutputTokens??4096,system:J,messages:G,tools:q,temperature:this.config.temperature??0,stream:!0},{signal:X}),W=Date.now()-Y;E0.debug("\uD83D\uDCE5 [AnthropicChatService] Stream started in",W,"ms");let U=new Map,H=0,F="",O=!1,z=0,_=0;for await(let B of K){if(H++,B.type==="message_start"){let L=B.message?.usage;if(L)z=L.input_tokens||0,_=L.output_tokens||0}if(B.type==="content_block_start"){if(B.content_block.type==="tool_use")U.set(B.index,{id:B.content_block.id,name:B.content_block.name,arguments:""}),O=!0,E0.debug(`\uD83D\uDD27 [AnthropicChatService] Tool use started: ${B.content_block.name}`)}else if(B.type==="content_block_delta"){if(B.delta.type==="text_delta")F+=B.delta.text,yield{content:B.delta.text};else if(B.delta.type==="input_json_delta"){let L=U.get(B.index);if(L)L.arguments+=B.delta.partial_json}}else if(B.type==="content_block_stop"){let L=U.get(B.index);if(L&&L.id)E0.debug(`\uD83D\uDD27 [AnthropicChatService] Tool use completed: ${L.name}`),yield{toolCalls:[{id:L.id,type:"function",function:{name:L.name,arguments:L.arguments}}]}}else if(B.type==="message_delta"){let L=B.usage;if(L)_+=L.output_tokens||0;let w=B.delta.stop_reason;if(w){E0.debug("\uD83C\uDFC1 [AnthropicChatService] Stream finished:",w),E0.debug("\uD83D\uDCCA [AnthropicChatService] Stream summary:",{totalEvents:H,totalContentLength:F.length,hadToolCalls:O,duration:Date.now()-Y+"ms"});let R;if(w==="end_turn")R="stop";else if(w==="tool_use")R="tool_calls";else if(w==="max_tokens")R="length";else R=w;yield{finishReason:R,usage:{promptTokens:z,completionTokens:_,totalTokens:z+_}}}}}E0.debug("✅ [AnthropicChatService] Stream completed successfully")}catch(K){let W=Date.now()-Y;throw E0.error("❌ [AnthropicChatService] Stream request failed after",W,"ms"),E0.error("❌ [AnthropicChatService] Stream error details:",K),K}}getConfig(){return{...this.config}}updateConfig($){E0.debug("\uD83D\uDD04 [AnthropicChatService] Updating configuration"),this.config={...this.config,...$},this.client=new NY({apiKey:this.config.apiKey,baseURL:this.config.baseUrl||void 0,timeout:this.config.timeout??180000,maxRetries:3}),E0.debug("✅ [AnthropicChatService] Configuration updated successfully")}}var E0;var AY=A(()=>{B0();E0=i("Chat")});import{ProxyAgent as VF,fetch as DF}from"undici";function MF(){return process.env.HTTPS_PROXY||process.env.HTTP_PROXY||process.env.https_proxy||process.env.http_proxy}function jF(){let $=MF();if($)try{return new VF($)}catch(Z){console.warn(`[proxyFetch] Invalid proxy URL: ${$}`)}return}async function P$($,Z={}){let{timeout:X=30000,signal:Y,...Q}=Z;if(Y?.aborted)throw new DOMException("The operation was aborted.","AbortError");let J=jF(),G=new AbortController,q=!1,K=setTimeout(()=>{q=!0,G.abort()},X),W=()=>G.abort();Y?.addEventListener("abort",W);try{let U={method:Q.method,headers:Q.headers,body:Q.body,signal:G.signal,dispatcher:J};return await DF($.toString(),U)}catch(U){if(U instanceof Error&&U.name==="AbortError"){if(q)throw Error(`Request timeout after ${X}ms`);throw U}throw U}finally{clearTimeout(K),Y?.removeEventListener("abort",W)}}var k2=()=>{};var RY,VY,x8,p8,d8,k3;var m8=A(()=>{RY={authorizationUrl:"https://accounts.google.com/o/oauth2/v2/auth",tokenUrl:"https://oauth2.googleapis.com/token",scopes:["https://www.googleapis.com/auth/cloud-platform","https://www.googleapis.com/auth/userinfo.email","https://www.googleapis.com/auth/userinfo.profile","https://www.googleapis.com/auth/cclog","https://www.googleapis.com/auth/experimentsandconfigs"],clientId:"1071006060591-tmhssin2h21lcre235vtolojh4g403ep.apps.googleusercontent.com",clientSecret:"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",redirectPort:51121,redirectPath:"/oauth-callback"},VY={authorizationUrl:"https://accounts.google.com/o/oauth2/v2/auth",tokenUrl:"https://oauth2.googleapis.com/token",scopes:["https://www.googleapis.com/auth/cloud-platform","https://www.googleapis.com/auth/userinfo.email","https://www.googleapis.com/auth/userinfo.profile"],clientId:"681255809395-oo8ft2oprdrnp9e3aqf6av3hmdib135j.apps.googleusercontent.com",clientSecret:"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",redirectPort:45289,redirectPath:"/"},x8={production:"https://cloudcode-pa.googleapis.com",sandbox:"https://daily-cloudcode-pa.sandbox.googleapis.com"},p8={generateContent:"/v1internal:generateContent",streamGenerateContent:"/v1internal:streamGenerateContent",loadCodeAssist:"/v1internal:loadCodeAssist",onboardUser:"/v1internal:onboardUser"},d8={"claude-sonnet-4-5":{id:"claude-sonnet-4-5",name:"Claude Sonnet 4.5",provider:"anthropic",supportsThinking:!1,description:"平衡速度与质量的 Claude 模型"},"claude-sonnet-4-5-thinking":{id:"claude-sonnet-4-5-thinking",name:"Claude Sonnet 4.5 (Thinking)",provider:"anthropic",supportsThinking:!0,description:"支持思维链的 Claude Sonnet"},"claude-opus-4-5-thinking":{id:"claude-opus-4-5-thinking",name:"Claude Opus 4.5 (Thinking)",provider:"anthropic",supportsThinking:!0,description:"最强 Claude 模型,支持思维链"},"gemini-3-pro-high":{id:"gemini-3-pro-high",name:"Gemini 3 Pro (High)",provider:"google",supportsThinking:!1,description:"高质量 Gemini 模型 (Pro)"},"gemini-3-pro-low":{id:"gemini-3-pro-low",name:"Gemini 3 Pro (Low)",provider:"google",supportsThinking:!1,description:"快速 Gemini 模型 (Pro)"},"gemini-3-flash":{id:"gemini-3-flash",name:"Gemini 3 Flash",provider:"google",supportsThinking:!1,description:"超快速 Gemini 模型 (Pro)"},"gpt-oss-120b-medium":{id:"gpt-oss-120b-medium",name:"GPT-OSS 120B Medium",provider:"openai-oss",supportsThinking:!1,description:"OpenAI 开源模型"}},k3={"gemini-2.5-pro":{id:"gemini-2.5-pro",name:"Gemini 2.5 Pro",provider:"google",supportsThinking:!1,description:"最强 Gemini 2.5 模型,1M 上下文"},"gemini-2.5-flash":{id:"gemini-2.5-flash",name:"Gemini 2.5 Flash",provider:"google",supportsThinking:!1,description:"快速 Gemini 2.5 模型"},"gemini-2.5-flash-lite":{id:"gemini-2.5-flash-lite",name:"Gemini 2.5 Flash Lite",provider:"google",supportsThinking:!1,description:"轻量级 Gemini 2.5 模型"}}});import{spawn as IF}from"child_process";import*as g8 from"crypto";import*as N4 from"fs/promises";import*as MY from"http";import*as u8 from"path";import{URL as yF}from"url";function DY($){return $==="gemini-cli"?VY:RY}function H7(){let $=process.env.HOME||process.env.USERPROFILE||"";return u8.join($,".blade")}class M${static instance=null;cachedToken=null;constructor(){}static getInstance(){if(!M$.instance)M$.instance=new M$;return M$.instance}async isLoggedIn(){let $=await this.loadToken();if(!$)return!1;let Z=300000;if($.expiresAt&&Date.now()>$.expiresAt-Z){if($.refreshToken)try{return await this.refreshToken(),!0}catch{return!1}return!1}return!0}async login($="antigravity"){let Z=$==="gemini-cli"?"Gemini CLI":"Antigravity";w4.info(`\uD83D\uDD10 Starting ${Z} OAuth login...`);let X=DY($),Y=this.generatePKCEParams(),Q=this.buildAuthorizationUrl(Y,X);console.log(`
|
|
156
|
+
${G.content}`;else if(Array.isArray(q.content)&&Array.isArray(G.content))q.content=[...q.content,...G.content];else if(typeof q.content==="string"&&Array.isArray(G.content))q.content=[{type:"text",text:q.content},...G.content];else if(Array.isArray(q.content)&&typeof G.content==="string")q.content.push({type:"text",text:G.content})}else J.push(G)}return{system:X,messages:J}}convertToAnthropicTools($){if(!$||$.length===0)return;return $.map((Z)=>({name:Z.name,description:Z.description,input_schema:Z.parameters}))}parseAnthropicResponse($,Z){let X="",Y=[];for(let Q of $)if(Q.type==="text")X+=Q.text;else if(Q.type==="tool_use")Y.push({id:Q.id,type:"function",function:{name:Q.name,arguments:JSON.stringify(Q.input)}});return{content:X,toolCalls:Y.length>0?Y:void 0,usage:{promptTokens:Z.input_tokens,completionTokens:Z.output_tokens,totalTokens:Z.input_tokens+Z.output_tokens}}}async chat($,Z,X){let Y=Date.now();E0.debug("\uD83D\uDE80 [AnthropicChatService] Starting chat request"),E0.debug("\uD83D\uDCDD [AnthropicChatService] Messages count:",$.length);let Q=bY($);if(Q.length<$.length)E0.debug(`\uD83D\uDD27 [AnthropicChatService] 过滤掉 ${$.length-Q.length} 条孤儿 tool 消息`);let{system:J,messages:G}=this.convertToAnthropicMessages(Q),q=this.convertToAnthropicTools(Z);E0.debug("\uD83D\uDD27 [AnthropicChatService] Tools count:",q?.length||0),E0.debug("\uD83D\uDCE4 [AnthropicChatService] Request params:",{model:this.config.model,messagesCount:G.length,hasSystem:!!J,toolsCount:q?.length||0,max_tokens:this.config.maxOutputTokens??4096,temperature:this.config.temperature??0});try{let K=await this.client.messages.create({model:this.config.model,max_tokens:this.config.maxOutputTokens??4096,system:J,messages:G,tools:q,temperature:this.config.temperature??0},{signal:X}),W=Date.now()-Y;E0.debug("\uD83D\uDCE5 [AnthropicChatService] Response received in",W,"ms"),E0.debug("\uD83D\uDCCA [AnthropicChatService] Response:",{stopReason:K.stop_reason,contentBlocksCount:K.content.length,usage:K.usage});let U=this.parseAnthropicResponse(K.content,K.usage);return E0.debug("✅ [AnthropicChatService] Chat completed successfully"),E0.debug("\uD83D\uDCCA [AnthropicChatService] Final response:",{contentLength:U.content.length,toolCallsCount:U.toolCalls?.length||0,usage:U.usage}),U}catch(K){let W=Date.now()-Y;throw E0.error("❌ [AnthropicChatService] Chat request failed after",W,"ms"),E0.error("❌ [AnthropicChatService] Error details:",K),K}}async*streamChat($,Z,X){let Y=Date.now();E0.debug("\uD83D\uDE80 [AnthropicChatService] Starting stream request"),E0.debug("\uD83D\uDCDD [AnthropicChatService] Messages count:",$.length);let Q=bY($);if(Q.length<$.length)E0.debug(`\uD83D\uDD27 [AnthropicChatService] 过滤掉 ${$.length-Q.length} 条孤儿 tool 消息`);let{system:J,messages:G}=this.convertToAnthropicMessages(Q),q=this.convertToAnthropicTools(Z);E0.debug("\uD83D\uDD27 [AnthropicChatService] Stream tools count:",q?.length||0),E0.debug("\uD83D\uDCE4 [AnthropicChatService] Stream request params:",{model:this.config.model,messagesCount:G.length,hasSystem:!!J,toolsCount:q?.length||0,max_tokens:this.config.maxOutputTokens??4096,temperature:this.config.temperature??0});try{let K=await this.client.messages.create({model:this.config.model,max_tokens:this.config.maxOutputTokens??4096,system:J,messages:G,tools:q,temperature:this.config.temperature??0,stream:!0},{signal:X}),W=Date.now()-Y;E0.debug("\uD83D\uDCE5 [AnthropicChatService] Stream started in",W,"ms");let U=new Map,H=0,F="",O=!1,z=0,_=0;for await(let B of K){if(H++,B.type==="message_start"){let L=B.message?.usage;if(L)z=L.input_tokens||0,_=L.output_tokens||0}if(B.type==="content_block_start"){if(B.content_block.type==="tool_use")U.set(B.index,{id:B.content_block.id,name:B.content_block.name,arguments:""}),O=!0,E0.debug(`\uD83D\uDD27 [AnthropicChatService] Tool use started: ${B.content_block.name}`)}else if(B.type==="content_block_delta"){if(B.delta.type==="text_delta")F+=B.delta.text,yield{content:B.delta.text};else if(B.delta.type==="input_json_delta"){let L=U.get(B.index);if(L)L.arguments+=B.delta.partial_json}}else if(B.type==="content_block_stop"){let L=U.get(B.index);if(L&&L.id)E0.debug(`\uD83D\uDD27 [AnthropicChatService] Tool use completed: ${L.name}`),yield{toolCalls:[{id:L.id,type:"function",function:{name:L.name,arguments:L.arguments}}]}}else if(B.type==="message_delta"){let L=B.usage;if(L)_+=L.output_tokens||0;let w=B.delta.stop_reason;if(w){E0.debug("\uD83C\uDFC1 [AnthropicChatService] Stream finished:",w),E0.debug("\uD83D\uDCCA [AnthropicChatService] Stream summary:",{totalEvents:H,totalContentLength:F.length,hadToolCalls:O,duration:Date.now()-Y+"ms"});let R;if(w==="end_turn")R="stop";else if(w==="tool_use")R="tool_calls";else if(w==="max_tokens")R="length";else R=w;yield{finishReason:R,usage:{promptTokens:z,completionTokens:_,totalTokens:z+_}}}}}E0.debug("✅ [AnthropicChatService] Stream completed successfully")}catch(K){let W=Date.now()-Y;throw E0.error("❌ [AnthropicChatService] Stream request failed after",W,"ms"),E0.error("❌ [AnthropicChatService] Stream error details:",K),K}}getConfig(){return{...this.config}}updateConfig($){E0.debug("\uD83D\uDD04 [AnthropicChatService] Updating configuration"),this.config={...this.config,...$},this.client=new NY({apiKey:this.config.apiKey,baseURL:this.config.baseUrl||void 0,timeout:this.config.timeout??180000,maxRetries:3}),E0.debug("✅ [AnthropicChatService] Configuration updated successfully")}}var E0;var AY=A(()=>{B0();E0=i("Chat")});import{ProxyAgent as VF,fetch as DF}from"undici";function MF(){return process.env.HTTPS_PROXY||process.env.HTTP_PROXY||process.env.https_proxy||process.env.http_proxy}function jF(){let $=MF();if($)try{return new VF($)}catch(Z){console.warn(`[proxyFetch] Invalid proxy URL: ${$}`)}return}async function P$($,Z={}){let{timeout:X=30000,signal:Y,...Q}=Z;if(Y?.aborted)throw new DOMException("The operation was aborted.","AbortError");let J=jF(),G=new AbortController,q=!1,K=setTimeout(()=>{q=!0,G.abort()},X),W=()=>G.abort();Y?.addEventListener("abort",W);try{let U={method:Q.method,headers:Q.headers,body:Q.body,signal:G.signal,dispatcher:J};return await DF($.toString(),U)}catch(U){if(U instanceof Error&&U.name==="AbortError"){if(q)throw Error(`Request timeout after ${X}ms`);throw U}throw U}finally{clearTimeout(K),Y?.removeEventListener("abort",W)}}var k4=()=>{};var RY,VY,x8,p8,d8,k3;var m8=A(()=>{RY={authorizationUrl:"https://accounts.google.com/o/oauth2/v2/auth",tokenUrl:"https://oauth2.googleapis.com/token",scopes:["https://www.googleapis.com/auth/cloud-platform","https://www.googleapis.com/auth/userinfo.email","https://www.googleapis.com/auth/userinfo.profile","https://www.googleapis.com/auth/cclog","https://www.googleapis.com/auth/experimentsandconfigs"],clientId:"1071006060591-tmhssin2h21lcre235vtolojh4g403ep.apps.googleusercontent.com",clientSecret:"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",redirectPort:51121,redirectPath:"/oauth-callback"},VY={authorizationUrl:"https://accounts.google.com/o/oauth2/v2/auth",tokenUrl:"https://oauth2.googleapis.com/token",scopes:["https://www.googleapis.com/auth/cloud-platform","https://www.googleapis.com/auth/userinfo.email","https://www.googleapis.com/auth/userinfo.profile"],clientId:"681255809395-oo8ft2oprdrnp9e3aqf6av3hmdib135j.apps.googleusercontent.com",clientSecret:"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",redirectPort:45289,redirectPath:"/"},x8={production:"https://cloudcode-pa.googleapis.com",sandbox:"https://daily-cloudcode-pa.sandbox.googleapis.com"},p8={generateContent:"/v1internal:generateContent",streamGenerateContent:"/v1internal:streamGenerateContent",loadCodeAssist:"/v1internal:loadCodeAssist",onboardUser:"/v1internal:onboardUser"},d8={"claude-sonnet-4-5":{id:"claude-sonnet-4-5",name:"Claude Sonnet 4.5",provider:"anthropic",supportsThinking:!1,description:"平衡速度与质量的 Claude 模型"},"claude-sonnet-4-5-thinking":{id:"claude-sonnet-4-5-thinking",name:"Claude Sonnet 4.5 (Thinking)",provider:"anthropic",supportsThinking:!0,description:"支持思维链的 Claude Sonnet"},"claude-opus-4-5-thinking":{id:"claude-opus-4-5-thinking",name:"Claude Opus 4.5 (Thinking)",provider:"anthropic",supportsThinking:!0,description:"最强 Claude 模型,支持思维链"},"gemini-3-pro-high":{id:"gemini-3-pro-high",name:"Gemini 3 Pro (High)",provider:"google",supportsThinking:!1,description:"高质量 Gemini 模型 (Pro)"},"gemini-3-pro-low":{id:"gemini-3-pro-low",name:"Gemini 3 Pro (Low)",provider:"google",supportsThinking:!1,description:"快速 Gemini 模型 (Pro)"},"gemini-3-flash":{id:"gemini-3-flash",name:"Gemini 3 Flash",provider:"google",supportsThinking:!1,description:"超快速 Gemini 模型 (Pro)"},"gpt-oss-120b-medium":{id:"gpt-oss-120b-medium",name:"GPT-OSS 120B Medium",provider:"openai-oss",supportsThinking:!1,description:"OpenAI 开源模型"}},k3={"gemini-2.5-pro":{id:"gemini-2.5-pro",name:"Gemini 2.5 Pro",provider:"google",supportsThinking:!1,description:"最强 Gemini 2.5 模型,1M 上下文"},"gemini-2.5-flash":{id:"gemini-2.5-flash",name:"Gemini 2.5 Flash",provider:"google",supportsThinking:!1,description:"快速 Gemini 2.5 模型"},"gemini-2.5-flash-lite":{id:"gemini-2.5-flash-lite",name:"Gemini 2.5 Flash Lite",provider:"google",supportsThinking:!1,description:"轻量级 Gemini 2.5 模型"}}});import{spawn as IF}from"child_process";import*as g8 from"crypto";import*as N2 from"fs/promises";import*as MY from"http";import*as u8 from"path";import{URL as yF}from"url";function DY($){return $==="gemini-cli"?VY:RY}function H7(){let $=process.env.HOME||process.env.USERPROFILE||"";return u8.join($,".blade")}class M${static instance=null;cachedToken=null;constructor(){}static getInstance(){if(!M$.instance)M$.instance=new M$;return M$.instance}async isLoggedIn(){let $=await this.loadToken();if(!$)return!1;let Z=300000;if($.expiresAt&&Date.now()>$.expiresAt-Z){if($.refreshToken)try{return await this.refreshToken(),!0}catch{return!1}return!1}return!0}async login($="antigravity"){let Z=$==="gemini-cli"?"Gemini CLI":"Antigravity";w2.info(`\uD83D\uDD10 Starting ${Z} OAuth login...`);let X=DY($),Y=this.generatePKCEParams(),Q=this.buildAuthorizationUrl(Y,X);console.log(`
|
|
157
157
|
\uD83C\uDF10 Opening browser for Google authentication...`),console.log(`
|
|
158
|
-
If the browser does not open automatically, copy and paste this URL:`),console.log(Q),console.log("");let J=this.startCallbackServer(Y.state,X);try{await this.openBrowser(Q)}catch(W){
|
|
158
|
+
If the browser does not open automatically, copy and paste this URL:`),console.log(Q),console.log("");let J=this.startCallbackServer(Y.state,X);try{await this.openBrowser(Q)}catch(W){w2.warn("Failed to open browser automatically:",W)}let G=await J;console.log("✅ Authorization code received, exchanging for tokens...");let q=await this.exchangeCodeForToken(G,Y.codeVerifier,X),K={accessToken:q.access_token,refreshToken:q.refresh_token||"",expiresAt:Date.now()+q.expires_in*1000,tokenType:q.token_type||"Bearer",scope:q.scope,configType:$};await this.saveToken(K),this.cachedToken=K,console.log(`✅ ${Z} login successful!`),w2.info(`${Z} OAuth login completed`)}async logout(){let $=u8.join(H7(),U7);try{await N2.unlink($),this.cachedToken=null,console.log("✅ Logged out from Antigravity"),w2.info("Antigravity logout completed")}catch(Z){if(Z.code!=="ENOENT")throw Z;this.cachedToken=null}}async getAccessToken(){if(this.cachedToken){if(this.cachedToken.expiresAt>Date.now()+300000)return this.cachedToken.accessToken}let $=await this.loadToken();if(!$)throw Error("Not logged in. Please run /login first.");let Z=300000;if($.expiresAt<=Date.now()+Z){if(!$.refreshToken)throw Error("Token expired and no refresh token available. Please run /login again.");return await this.refreshToken(),this.cachedToken.accessToken}return this.cachedToken=$,$.accessToken}async refreshToken(){let $=await this.loadToken();if(!$||!$.refreshToken)throw Error("No refresh token available");let Z=$.configType||"antigravity",X=DY(Z),Y=Z==="gemini-cli"?"Gemini CLI":"Antigravity";w2.info(`\uD83D\uDD04 Refreshing ${Y} access token...`);let Q=new URLSearchParams({grant_type:"refresh_token",refresh_token:$.refreshToken,client_id:X.clientId,client_secret:X.clientSecret}),J=await P$(X.tokenUrl,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:Q.toString()});if(!J.ok){let K=await J.text();throw w2.error("Token refresh failed:",K),Error(`Token refresh failed: ${J.status}`)}let G=await J.json(),q={accessToken:G.access_token,refreshToken:G.refresh_token||$.refreshToken,expiresAt:Date.now()+G.expires_in*1000,tokenType:G.token_type||"Bearer",scope:G.scope||$.scope,configType:Z};await this.saveToken(q),this.cachedToken=q,w2.info("✅ Token refreshed successfully")}generatePKCEParams(){let $=g8.randomBytes(32).toString("base64url"),Z=g8.createHash("sha256").update($).digest("base64url"),X=g8.randomBytes(16).toString("base64url");return{codeVerifier:$,codeChallenge:Z,state:X}}buildAuthorizationUrl($,Z){let X=`http://localhost:${Z.redirectPort}${Z.redirectPath}`,Y=new URLSearchParams({client_id:Z.clientId,response_type:"code",redirect_uri:X,state:$.state,code_challenge:$.codeChallenge,code_challenge_method:"S256",scope:Z.scopes.join(" "),access_type:"offline",prompt:"consent"});return`${Z.authorizationUrl}?${Y.toString()}`}async startCallbackServer($,Z){let{redirectPort:X,redirectPath:Y}=Z;return new Promise((Q,J)=>{let G=null,q=!1,K=()=>{if(G)clearTimeout(G),G=null},W=MY.createServer((U,H)=>{try{let F=new yF(U.url,`http://localhost:${X}`);if(F.pathname!==Y){H.writeHead(404),H.end("Not found");return}let O=F.searchParams.get("code"),z=F.searchParams.get("state"),_=F.searchParams.get("error");if(_){if(H.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),H.end(`
|
|
159
159
|
<html>
|
|
160
160
|
<head><title>Authentication Failed</title></head>
|
|
161
161
|
<body style="font-family: system-ui; padding: 40px; text-align: center;">
|
|
@@ -173,17 +173,17 @@ If the browser does not open automatically, copy and paste this URL:`),console.l
|
|
|
173
173
|
<script>setTimeout(() => window.close(), 2000);</script>
|
|
174
174
|
</body>
|
|
175
175
|
</html>
|
|
176
|
-
`),K(),W.close(),!q)q=!0,Q(O)}catch(F){if(K(),W.close(),!q)q=!0,J(F)}});W.on("error",(U)=>{if(K(),!q)if(q=!0,U.code==="EADDRINUSE")J(Error(`Port ${X} is already in use. Please close other applications using this port.`));else J(U)}),W.listen(X,()=>{
|
|
176
|
+
`),K(),W.close(),!q)q=!0,Q(O)}catch(F){if(K(),W.close(),!q)q=!0,J(F)}});W.on("error",(U)=>{if(K(),!q)if(q=!0,U.code==="EADDRINUSE")J(Error(`Port ${X} is already in use. Please close other applications using this port.`));else J(U)}),W.listen(X,()=>{w2.debug(`OAuth callback server listening on port ${X}`)}),G=setTimeout(()=>{if(W.close(),!q)q=!0,J(Error("OAuth callback timeout (5 minutes)"))},300000)})}async exchangeCodeForToken($,Z,X){let Y=`http://localhost:${X.redirectPort}${X.redirectPath}`,Q=new URLSearchParams({grant_type:"authorization_code",code:$,redirect_uri:Y,code_verifier:Z,client_id:X.clientId,client_secret:X.clientSecret}),J=await P$(X.tokenUrl,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:Q.toString()});if(!J.ok){let G=await J.text();throw Error(`Token exchange failed: ${J.status} - ${G}`)}return await J.json()}async openBrowser($){let Z,X;if(process.platform==="darwin")Z="open",X=[$];else if(process.platform==="win32")Z="cmd",X=["/c","start","",$];else Z="xdg-open",X=[$];await new Promise((Y,Q)=>{let J=IF(Z,X,{stdio:"ignore"});J.once("error",Q),J.once("close",(G)=>{if(G===0||G===null)Y();else Q(Error(`Failed to open browser (exit code ${G})`))})})}async saveToken($){let Z=H7();await N2.mkdir(Z,{recursive:!0});let X=u8.join(Z,U7);await N2.writeFile(X,JSON.stringify($,null,2),{mode:384})}async loadToken(){let $=u8.join(H7(),U7);try{let Z=await N2.readFile($,"utf-8");return JSON.parse(Z)}catch(Z){if(Z.code==="ENOENT")return null;throw Z}}async getStatus(){let $=await this.loadToken();if(!$)return{loggedIn:!1};return{loggedIn:!0,expiresAt:$.expiresAt?new Date($.expiresAt):void 0,configType:$.configType||"antigravity"}}async getConfigType(){let $=await this.loadToken();if(!$)return null;return $.configType||"antigravity"}}var w2,U7="antigravity-token.json";var c8=A(()=>{B0();k4();m8();w2=i("Service")});function jY($){if($==="antigravity")return{ideType:"ANTIGRAVITY"};return{ideType:"IDE_UNSPECIFIED",platform:"PLATFORM_UNSPECIFIED",pluginType:"GEMINI"}}function f3($){if($==="antigravity")return"antigravity/1.11.3 Darwin/arm64";return"gemini-cli/1.0.0"}function IY($){let Z=new Set;for(let X of $)if(X.role==="assistant"&&X.tool_calls)for(let Y of X.tool_calls)Z.add(Y.id);return $.filter((X)=>{if(X.role==="tool"){if(!X.tool_call_id)return!1;return Z.has(X.tool_call_id)}return!0})}function h3($){if(typeof $==="string")return $;return $.filter((Z)=>Z.type==="text").map((Z)=>Z.text).join(`
|
|
177
177
|
`)}function F7($){let Z=["const","$ref","$defs","$schema","$id","default","examples"],X={};for(let[Y,Q]of Object.entries($)){if(Z.includes(Y)){if(Y==="const")X.enum=[Q];continue}if(Q&&typeof Q==="object"&&!Array.isArray(Q))X[Y]=F7(Q);else if(Array.isArray(Q))X[Y]=Q.map((J)=>J&&typeof J==="object"&&!Array.isArray(J)?F7(J):J);else X[Y]=Q}return X}class O7{config;auth;projectId;userTier;sessionId;configType="antigravity";projectIdInitialized=!1;constructor($){this.config=$,this.auth=M$.getInstance(),this.projectId=void 0,this.sessionId=`session_${Date.now()}_${Math.random().toString(36).slice(2,11)}`,P0.debug("\uD83D\uDE80 [AntigravityChatService] Initializing"),P0.debug("⚙️ [AntigravityChatService] Config:",{model:$.model,temperature:$.temperature,maxOutputTokens:$.maxOutputTokens,sessionId:this.sessionId})}async ensureProjectId(){if(this.projectIdInitialized)return;try{let $=await this.auth.getConfigType();this.configType=$||"antigravity",P0.debug(`\uD83D\uDD04 [AntigravityChatService] Using OAuth config: ${this.configType}`),P0.debug("\uD83D\uDD04 [AntigravityChatService] Setting up user via loadCodeAssist...");let Z=await this.auth.getAccessToken(),X=await this.callLoadCodeAssist(Z);if(P0.debug("[AntigravityChatService] loadCodeAssist response:",JSON.stringify(X)),X.currentTier){if(this.userTier=X.currentTier.id,X.cloudaicompanionProject){this.projectId=X.cloudaicompanionProject,P0.debug(`✅ [AntigravityChatService] User already setup: tier=${this.userTier}, project=${this.projectId}`),this.projectIdInitialized=!0;return}let J=process.env.GOOGLE_CLOUD_PROJECT||process.env.GOOGLE_CLOUD_PROJECT_ID;if(J){this.projectId=J,P0.debug(`✅ [AntigravityChatService] Using env project: ${this.projectId}`),this.projectIdInitialized=!0;return}P0.debug("⚠️ [AntigravityChatService] Has tier but no project, need onboarding...")}let Y=this.getDefaultTier(X);P0.debug(`\uD83D\uDD04 [AntigravityChatService] Onboarding user with tier: ${Y.id}`);let Q=await this.callOnboardUser(Z,Y.id);this.projectId=Q.projectId,this.userTier=Y.id,P0.debug(`✅ [AntigravityChatService] User setup complete: tier=${this.userTier}, project=${this.projectId||"(managed)"}`)}catch($){P0.warn("Failed to setup user:",$)}this.projectIdInitialized=!0}async callLoadCodeAssist($){let Z=`${x8.production}${p8.loadCodeAssist}`,X=jY(this.configType),Y=f3(this.configType),Q=await P$(Z,{method:"POST",headers:{Authorization:`Bearer ${$}`,"Content-Type":"application/json","User-Agent":Y},body:JSON.stringify({metadata:X})});if(!Q.ok){let J=await Q.text();throw Error(`loadCodeAssist failed: ${Q.status} - ${J}`)}return await Q.json()}getDefaultTier($){for(let Z of $.allowedTiers||[])if(Z.isDefault)return{id:Z.id};return{id:"free-tier"}}async callOnboardUser($,Z){let X=`${x8.production}${p8.onboardUser}`,Y=jY(this.configType),Q=f3(this.configType),J={tierId:Z,metadata:Y};if(Z!=="free-tier"){let K=process.env.GOOGLE_CLOUD_PROJECT||process.env.GOOGLE_CLOUD_PROJECT_ID;if(K)J.cloudaicompanionProject=K,J.metadata={...Y,duetProject:K}}let G=0,q=30;while(G<q){let K=await P$(X,{method:"POST",headers:{Authorization:`Bearer ${$}`,"Content-Type":"application/json","User-Agent":Q},body:JSON.stringify(J)});if(!K.ok){let U=await K.text();throw Error(`onboardUser failed: ${K.status} - ${U}`)}let W=await K.json();if(P0.debug(`[AntigravityChatService] onboardUser attempt ${G+1}:`,JSON.stringify(W)),W.error)throw Error(`onboardUser error: ${W.error.message||W.error.code}`);if(W.done)return{projectId:W.response?.cloudaicompanionProject?.id};P0.debug("[AntigravityChatService] onboardUser not done, waiting 5s..."),await new Promise((U)=>setTimeout(U,5000)),G++}throw Error("onboardUser timeout: LRO did not complete in time")}convertToAntigravityMessages($){let Z=$.find((q)=>q.role==="system"),X=Z?{parts:[{text:h3(Z.content)}]}:void 0,Y=[],Q=$.filter((q)=>q.role!=="system"),J=new Map;for(let q of Q)if(q.role==="assistant"&&q.tool_calls){for(let K of q.tool_calls)if(K.type==="function")J.set(K.id,K.function.name)}for(let q of Q)if(q.role==="user"){let K=[];if(Array.isArray(q.content)){for(let W of q.content)if(W.type==="text")K.push({text:W.text})}else K.push({text:q.content});Y.push({role:"user",parts:K})}else if(q.role==="assistant"){let K=[],W=h3(q.content);if(W)K.push({text:W});if(q.tool_calls)for(let U of q.tool_calls){if(U.type!=="function")continue;let H={};try{H=JSON.parse(U.function.arguments||"{}")}catch{P0.warn(`Failed to parse tool arguments: ${U.function.arguments}`)}K.push({functionCall:{name:U.function.name,args:H,id:U.id}})}if(K.length>0)Y.push({role:"model",parts:K})}else if(q.role==="tool"){let K=J.get(q.tool_call_id||"");if(K){let W;try{W=JSON.parse(h3(q.content))}catch{W={result:h3(q.content)}}Y.push({role:"user",parts:[{functionResponse:{name:K,id:q.tool_call_id,response:W}}]})}}let G=[];for(let q of Y){let K=G[G.length-1];if(K?.role===q.role)K.parts=[...K.parts,...q.parts];else G.push(q)}if(G.length>0&&G[0].role!=="user")G.unshift({role:"user",parts:[{text:"[Conversation start]"}]});return{systemInstruction:X,contents:G}}convertToAntigravityTools($){if(!$||$.length===0)return;return[{functionDeclarations:$.map((X)=>({name:X.name,description:X.description,parameters:F7(X.parameters||{type:"object",properties:{}})}))}]}async makeRequest($,Z,X){let Y=await this.auth.getAccessToken(),Q=`${x8.production}${$}`,J=f3(this.configType),G=await P$(Q,{method:"POST",headers:{Authorization:`Bearer ${Y}`,"Content-Type":"application/json","User-Agent":J},body:JSON.stringify(Z),signal:X});if(!G.ok){let q=await G.text();if(P0.error(`Antigravity API error: ${G.status} - ${q}`),G.status===401)throw Error("Authentication expired. Please run /login again.");if(G.status===403)throw Error("Permission denied. Please check your Google account permissions.");if(G.status===429)throw Error("Rate limit exceeded. Please wait a moment and try again.");throw Error(`Antigravity API error: ${G.status} - ${q}`)}return G}async chat($,Z,X){let Y=Date.now();P0.debug("\uD83D\uDE80 [AntigravityChatService] Starting chat request"),P0.debug("\uD83D\uDCDD [AntigravityChatService] Messages count:",$.length),await this.ensureProjectId();let Q=IY($);if(Q.length<$.length)P0.debug(`Filtered ${$.length-Q.length} orphan tool messages`);let{systemInstruction:J,contents:G}=this.convertToAntigravityMessages(Q),q=this.convertToAntigravityTools(Z),K=`prompt_${Date.now()}_${Math.random().toString(36).slice(2,9)}`,W={model:this.config.model,project:this.projectId,user_prompt_id:K,request:{contents:G,systemInstruction:J,generationConfig:{maxOutputTokens:this.config.maxOutputTokens??8192,temperature:this.config.temperature??0.7},tools:q,session_id:this.sessionId}};P0.debug("\uD83D\uDCE4 [AntigravityChatService] Request:",{model:this.config.model,contentsCount:G.length,hasSystemInstruction:!!J,toolsCount:q?.[0]?.functionDeclarations?.length||0});try{let H=await(await this.makeRequest(p8.generateContent,W,X)).json(),F=Date.now()-Y;P0.debug("\uD83D\uDCE5 [AntigravityChatService] Response received in",F,"ms");let O="",z=[],B=H.response?.candidates?.[0]?.content?.parts||[];for(let R of B)if(R.text)O+=R.text;else if(R.functionCall){let D=R.functionCall;z.push({id:D.id||`call_${Date.now()}_${Math.random().toString(36).slice(2,9)}`,type:"function",function:{name:D.name,arguments:JSON.stringify(D.args||{})}})}let L=H.response?.usageMetadata,w={content:O,toolCalls:z.length>0?z:void 0,usage:{promptTokens:L?.promptTokenCount||0,completionTokens:L?.candidatesTokenCount||0,totalTokens:L?.totalTokenCount||0}};return P0.debug("✅ [AntigravityChatService] Chat completed:",{contentLength:w.content.length,toolCallsCount:w.toolCalls?.length||0,usage:w.usage}),w}catch(U){let H=Date.now()-Y;throw P0.error("❌ [AntigravityChatService] Chat failed after",H,"ms"),P0.error("❌ [AntigravityChatService] Error:",U),U}}async*streamChat($,Z,X){let Y=Date.now();P0.debug("\uD83D\uDE80 [AntigravityChatService] Starting stream request"),await this.ensureProjectId();let Q=IY($),{systemInstruction:J,contents:G}=this.convertToAntigravityMessages(Q),q=this.convertToAntigravityTools(Z),K=`prompt_${Date.now()}_${Math.random().toString(36).slice(2,9)}`,W={model:this.config.model,project:this.projectId,user_prompt_id:K,request:{contents:G,systemInstruction:J,generationConfig:{maxOutputTokens:this.config.maxOutputTokens??8192,temperature:this.config.temperature??0.7},tools:q,session_id:this.sessionId}};try{let U=await this.auth.getAccessToken(),H=`${x8.production}${p8.streamGenerateContent}?alt=sse`,F=f3(this.configType),O=await P$(H,{method:"POST",headers:{Authorization:`Bearer ${U}`,"Content-Type":"application/json",Accept:"text/event-stream","User-Agent":F},body:JSON.stringify(W),signal:X});if(!O.ok){let R=await O.text();throw Error(`Antigravity API error: ${O.status} - ${R}`)}let z=O.body?.getReader();if(!z)throw Error("No response body");let _=new TextDecoder,B="",L=0,w=Date.now()-Y;P0.debug("\uD83D\uDCE5 [AntigravityChatService] Stream started in",w,"ms");while(!0){let{done:R,value:D}=await z.read();if(R)break;B+=_.decode(D,{stream:!0});let V=B.split(`
|
|
178
|
-
`);B=V.pop()||"";for(let I of V)if(I.startsWith("data: ")){let v=I.slice(6);if(v==="[DONE]"){yield{finishReason:"stop"};continue}try{let N=JSON.parse(v);if(L++,N.usageMetadata)yield{usage:{promptTokens:N.usageMetadata.promptTokenCount||0,completionTokens:N.usageMetadata.candidatesTokenCount||0,totalTokens:N.usageMetadata.totalTokenCount||0}};let k=N.candidates?.[0],m=k?.content?.parts||[];for(let S of m)if(S.text)yield{content:S.text};else if(S.functionCall){let T=S.functionCall;yield{toolCalls:[{id:T.id||`call_${Date.now()}_${Math.random().toString(36).slice(2,9)}`,type:"function",function:{name:T.name,arguments:JSON.stringify(T.args||{})}}]}}let s=k?.finishReason;if(s)yield{finishReason:s==="STOP"?"stop":s==="MAX_TOKENS"?"length":s.toLowerCase()}}catch(N){P0.debug("Failed to parse SSE data:",v)}}}P0.debug("✅ [AntigravityChatService] Stream completed:",{eventCount:L,duration:Date.now()-Y+"ms"})}catch(U){let H=Date.now()-Y;throw P0.error("❌ [AntigravityChatService] Stream failed after",H,"ms"),P0.error("❌ [AntigravityChatService] Error:",U),U}}getConfig(){return{...this.config}}updateConfig($){P0.debug("\uD83D\uDD04 [AntigravityChatService] Updating configuration"),this.config={...this.config,...$},P0.debug("✅ [AntigravityChatService] Configuration updated")}}var P0;var yY=A(()=>{B0();
|
|
178
|
+
`);B=V.pop()||"";for(let I of V)if(I.startsWith("data: ")){let v=I.slice(6);if(v==="[DONE]"){yield{finishReason:"stop"};continue}try{let N=JSON.parse(v);if(L++,N.usageMetadata)yield{usage:{promptTokens:N.usageMetadata.promptTokenCount||0,completionTokens:N.usageMetadata.candidatesTokenCount||0,totalTokens:N.usageMetadata.totalTokenCount||0}};let k=N.candidates?.[0],m=k?.content?.parts||[];for(let S of m)if(S.text)yield{content:S.text};else if(S.functionCall){let T=S.functionCall;yield{toolCalls:[{id:T.id||`call_${Date.now()}_${Math.random().toString(36).slice(2,9)}`,type:"function",function:{name:T.name,arguments:JSON.stringify(T.args||{})}}]}}let s=k?.finishReason;if(s)yield{finishReason:s==="STOP"?"stop":s==="MAX_TOKENS"?"length":s.toLowerCase()}}catch(N){P0.debug("Failed to parse SSE data:",v)}}}P0.debug("✅ [AntigravityChatService] Stream completed:",{eventCount:L,duration:Date.now()-Y+"ms"})}catch(U){let H=Date.now()-Y;throw P0.error("❌ [AntigravityChatService] Stream failed after",H,"ms"),P0.error("❌ [AntigravityChatService] Error:",U),U}}getConfig(){return{...this.config}}updateConfig($){P0.debug("\uD83D\uDD04 [AntigravityChatService] Updating configuration"),this.config={...this.config,...$},P0.debug("✅ [AntigravityChatService] Configuration updated")}}var P0;var yY=A(()=>{B0();k4();c8();m8();P0=i("Chat")});function x3($){if(!($ instanceof Error))return!1;let Z=$.message.toLowerCase();return Z.includes("stream_options")||Z.includes("include_usage")||Z.includes("unknown parameter")||Z.includes("unrecognized request argument")}import{AzureOpenAI as vY}from"openai";function EY($){let Z=new Set;for(let X of $)if(X.role==="assistant"&&X.tool_calls)for(let Y of X.tool_calls)Z.add(Y.id);return $.filter((X)=>{if(X.role==="tool"){if(!X.tool_call_id)return!1;return Z.has(X.tool_call_id)}return!0})}class z7{client;config;constructor($){if(this.config=$,y0.debug("\uD83D\uDE80 [AzureOpenAIChatService] Initializing"),y0.debug("⚙️ [AzureOpenAIChatService] Config:",{model:$.model,baseUrl:$.baseUrl,temperature:$.temperature,maxContextTokens:$.maxContextTokens,timeout:$.timeout,apiVersion:$.apiVersion,hasApiKey:!!$.apiKey}),!$.apiKey)throw y0.error("❌ [AzureOpenAIChatService] apiKey is required"),Error("apiKey is required in ChatConfig");if(!$.baseUrl)throw y0.error("❌ [AzureOpenAIChatService] baseUrl is required"),Error("baseUrl is required in ChatConfig");if(!$.model)throw y0.error("❌ [AzureOpenAIChatService] model (deployment) is required"),Error("model (deployment) is required in ChatConfig");this.client=new vY({apiKey:$.apiKey,endpoint:$.baseUrl,apiVersion:$.apiVersion||"2024-08-01-preview",timeout:$.timeout??180000,maxRetries:3}),y0.debug("✅ [AzureOpenAIChatService] Initialized successfully")}convertToOpenAIMessages($){return $.map((Z)=>{if(Z.role==="tool")return{role:"tool",content:typeof Z.content==="string"?Z.content:Z.content.filter((Y)=>Y.type==="text").map((Y)=>Y.text).join(`
|
|
179
179
|
`),tool_call_id:Z.tool_call_id};if(Z.role==="assistant"&&Z.tool_calls)return{role:"assistant",content:(typeof Z.content==="string"?Z.content:Z.content.filter((Y)=>Y.type==="text").map((Y)=>Y.text).join(`
|
|
180
180
|
`))||null,tool_calls:Z.tool_calls};if(Z.role==="user"&&Array.isArray(Z.content))return{role:"user",content:Z.content.map((X)=>{if(X.type==="text")return{type:"text",text:X.text};return{type:"image_url",image_url:{url:X.image_url.url}}})};return{role:Z.role,content:typeof Z.content==="string"?Z.content:Z.content.filter((X)=>X.type==="text").map((X)=>X.text).join(`
|
|
181
|
-
`)}})}convertToOpenAITools($){return $?.map((Z)=>({type:"function",function:{name:Z.name,description:Z.description,parameters:Z.parameters}}))}async chat($,Z,X){let Y=Date.now();y0.debug("\uD83D\uDE80 [AzureOpenAIChatService] Starting chat request"),y0.debug("\uD83D\uDCDD [AzureOpenAIChatService] Messages count:",$.length);let Q=EY($);if(Q.length<$.length)y0.debug(`\uD83D\uDD27 [AzureOpenAIChatService] 过滤掉 ${$.length-Q.length} 条孤儿 tool 消息`);let J=this.convertToOpenAIMessages(Q),G=this.convertToOpenAITools(Z);y0.debug("\uD83D\uDD27 [AzureOpenAIChatService] Tools count:",G?.length||0);let q={model:this.config.model,messages:J,tools:G,tool_choice:G&&G.length>0?"auto":void 0,max_tokens:this.config.maxOutputTokens??32768,temperature:this.config.temperature??0};y0.debug("\uD83D\uDCE4 [AzureOpenAIChatService] Request params:",{model:q.model,messagesCount:q.messages.length,toolsCount:q.tools?.length||0,max_tokens:q.max_tokens,temperature:q.temperature});try{let K=await this.client.chat.completions.create(q,{signal:X}),W=Date.now()-Y;if(y0.debug("\uD83D\uDCE5 [AzureOpenAIChatService] Response received in",W,"ms"),!K||!K.choices||K.choices.length===0)throw Error("Invalid API response: missing choices");let U=K.choices[0];if(!U)throw Error("No completion choice returned");let H=U.message.tool_calls?.filter((O)=>O.type==="function"),F={content:U.message.content||"",toolCalls:H,usage:{promptTokens:K.usage?.prompt_tokens||0,completionTokens:K.usage?.completion_tokens||0,totalTokens:K.usage?.total_tokens||0}};return y0.debug("✅ [AzureOpenAIChatService] Chat completed successfully"),y0.debug("\uD83D\uDCCA [AzureOpenAIChatService] Final response:",{contentLength:F.content.length,toolCallsCount:F.toolCalls?.length||0,usage:F.usage}),F}catch(K){let W=Date.now()-Y;throw y0.error("❌ [AzureOpenAIChatService] Chat request failed after",W,"ms"),y0.error("❌ [AzureOpenAIChatService] Error details:",K),K}}async*streamChat($,Z,X){let Y=Date.now();y0.debug("\uD83D\uDE80 [AzureOpenAIChatService] Starting stream request"),y0.debug("\uD83D\uDCDD [AzureOpenAIChatService] Messages count:",$.length);let Q=EY($);if(Q.length<$.length)y0.debug(`\uD83D\uDD27 [AzureOpenAIChatService] 过滤掉 ${$.length-Q.length} 条孤儿 tool 消息`);let J=this.convertToOpenAIMessages(Q),G=this.convertToOpenAITools(Z);y0.debug("\uD83D\uDD27 [AzureOpenAIChatService] Stream tools count:",G?.length||0);let q={model:this.config.model,messages:J,tools:G,tool_choice:G&&G.length>0?"auto":void 0,max_tokens:this.config.maxOutputTokens??32768,temperature:this.config.temperature??0,stream:!0,stream_options:{include_usage:!0}};y0.debug("\uD83D\uDCE4 [AzureOpenAIChatService] Stream request params:",{model:q.model,messagesCount:q.messages.length,toolsCount:q.tools?.length||0,max_tokens:q.max_tokens,temperature:q.temperature});try{let K;try{K=await this.client.chat.completions.create(q,{signal:X})}catch(O){if(!x3(O))throw O;y0.warn("⚠️ [AzureOpenAIChatService] stream_options 不被支持,已降级为无 usage 流式请求");let{stream_options:z,..._}=q;K=await this.client.chat.completions.create(_,{signal:X})}let W=Date.now()-Y;y0.debug("\uD83D\uDCE5 [AzureOpenAIChatService] Stream started in",W,"ms");let U=0,H="",F=!1;for await(let O of K){U++;let z=O.usage;if(!O||!O.choices||!Array.isArray(O.choices)){if(z){yield{usage:{promptTokens:z.prompt_tokens||0,completionTokens:z.completion_tokens||0,totalTokens:z.total_tokens||0}};continue}y0.warn("⚠️ [AzureOpenAIChatService] Invalid chunk format in stream",U);continue}let _=O.choices[0]?.delta;if(!_){if(z){yield{usage:{promptTokens:z.prompt_tokens||0,completionTokens:z.completion_tokens||0,totalTokens:z.total_tokens||0}};continue}y0.warn("⚠️ [AzureOpenAIChatService] Empty delta in chunk",U);continue}if(_.content)H+=_.content;if(_.tool_calls&&!F)F=!0,y0.debug("\uD83D\uDD27 [AzureOpenAIChatService] Tool calls detected in stream");let B=O.choices[0]?.finish_reason;if(B)y0.debug("\uD83C\uDFC1 [AzureOpenAIChatService] Stream finished with reason:",B),y0.debug("\uD83D\uDCCA [AzureOpenAIChatService] Stream summary:",{totalChunks:U,totalContentLength:H.length,hadToolCalls:F,duration:Date.now()-Y+"ms"});let L={content:_.content||void 0,toolCalls:_.tool_calls,finishReason:B||void 0};if(z)L.usage={promptTokens:z.prompt_tokens||0,completionTokens:z.completion_tokens||0,totalTokens:z.total_tokens||0};yield L}y0.debug("✅ [AzureOpenAIChatService] Stream completed successfully")}catch(K){let W=Date.now()-Y;throw y0.error("❌ [AzureOpenAIChatService] Stream request failed after",W,"ms"),y0.error("❌ [AzureOpenAIChatService] Stream error details:",K),K}}getConfig(){return{...this.config}}updateConfig($){y0.debug("\uD83D\uDD04 [AzureOpenAIChatService] Updating configuration"),this.config={...this.config,...$},this.client=new vY({apiKey:this.config.apiKey,endpoint:this.config.baseUrl,apiVersion:this.config.apiVersion||"2024-08-01-preview",timeout:this.config.timeout??180000,maxRetries:3}),y0.debug("✅ [AzureOpenAIChatService] Configuration updated successfully")}}var y0;var PY=A(()=>{B0();y0=i("Chat")});async function TY($){return $}var
|
|
181
|
+
`)}})}convertToOpenAITools($){return $?.map((Z)=>({type:"function",function:{name:Z.name,description:Z.description,parameters:Z.parameters}}))}async chat($,Z,X){let Y=Date.now();y0.debug("\uD83D\uDE80 [AzureOpenAIChatService] Starting chat request"),y0.debug("\uD83D\uDCDD [AzureOpenAIChatService] Messages count:",$.length);let Q=EY($);if(Q.length<$.length)y0.debug(`\uD83D\uDD27 [AzureOpenAIChatService] 过滤掉 ${$.length-Q.length} 条孤儿 tool 消息`);let J=this.convertToOpenAIMessages(Q),G=this.convertToOpenAITools(Z);y0.debug("\uD83D\uDD27 [AzureOpenAIChatService] Tools count:",G?.length||0);let q={model:this.config.model,messages:J,tools:G,tool_choice:G&&G.length>0?"auto":void 0,max_tokens:this.config.maxOutputTokens??32768,temperature:this.config.temperature??0};y0.debug("\uD83D\uDCE4 [AzureOpenAIChatService] Request params:",{model:q.model,messagesCount:q.messages.length,toolsCount:q.tools?.length||0,max_tokens:q.max_tokens,temperature:q.temperature});try{let K=await this.client.chat.completions.create(q,{signal:X}),W=Date.now()-Y;if(y0.debug("\uD83D\uDCE5 [AzureOpenAIChatService] Response received in",W,"ms"),!K||!K.choices||K.choices.length===0)throw Error("Invalid API response: missing choices");let U=K.choices[0];if(!U)throw Error("No completion choice returned");let H=U.message.tool_calls?.filter((O)=>O.type==="function"),F={content:U.message.content||"",toolCalls:H,usage:{promptTokens:K.usage?.prompt_tokens||0,completionTokens:K.usage?.completion_tokens||0,totalTokens:K.usage?.total_tokens||0}};return y0.debug("✅ [AzureOpenAIChatService] Chat completed successfully"),y0.debug("\uD83D\uDCCA [AzureOpenAIChatService] Final response:",{contentLength:F.content.length,toolCallsCount:F.toolCalls?.length||0,usage:F.usage}),F}catch(K){let W=Date.now()-Y;throw y0.error("❌ [AzureOpenAIChatService] Chat request failed after",W,"ms"),y0.error("❌ [AzureOpenAIChatService] Error details:",K),K}}async*streamChat($,Z,X){let Y=Date.now();y0.debug("\uD83D\uDE80 [AzureOpenAIChatService] Starting stream request"),y0.debug("\uD83D\uDCDD [AzureOpenAIChatService] Messages count:",$.length);let Q=EY($);if(Q.length<$.length)y0.debug(`\uD83D\uDD27 [AzureOpenAIChatService] 过滤掉 ${$.length-Q.length} 条孤儿 tool 消息`);let J=this.convertToOpenAIMessages(Q),G=this.convertToOpenAITools(Z);y0.debug("\uD83D\uDD27 [AzureOpenAIChatService] Stream tools count:",G?.length||0);let q={model:this.config.model,messages:J,tools:G,tool_choice:G&&G.length>0?"auto":void 0,max_tokens:this.config.maxOutputTokens??32768,temperature:this.config.temperature??0,stream:!0,stream_options:{include_usage:!0}};y0.debug("\uD83D\uDCE4 [AzureOpenAIChatService] Stream request params:",{model:q.model,messagesCount:q.messages.length,toolsCount:q.tools?.length||0,max_tokens:q.max_tokens,temperature:q.temperature});try{let K;try{K=await this.client.chat.completions.create(q,{signal:X})}catch(O){if(!x3(O))throw O;y0.warn("⚠️ [AzureOpenAIChatService] stream_options 不被支持,已降级为无 usage 流式请求");let{stream_options:z,..._}=q;K=await this.client.chat.completions.create(_,{signal:X})}let W=Date.now()-Y;y0.debug("\uD83D\uDCE5 [AzureOpenAIChatService] Stream started in",W,"ms");let U=0,H="",F=!1;for await(let O of K){U++;let z=O.usage;if(!O||!O.choices||!Array.isArray(O.choices)){if(z){yield{usage:{promptTokens:z.prompt_tokens||0,completionTokens:z.completion_tokens||0,totalTokens:z.total_tokens||0}};continue}y0.warn("⚠️ [AzureOpenAIChatService] Invalid chunk format in stream",U);continue}let _=O.choices[0]?.delta;if(!_){if(z){yield{usage:{promptTokens:z.prompt_tokens||0,completionTokens:z.completion_tokens||0,totalTokens:z.total_tokens||0}};continue}y0.warn("⚠️ [AzureOpenAIChatService] Empty delta in chunk",U);continue}if(_.content)H+=_.content;if(_.tool_calls&&!F)F=!0,y0.debug("\uD83D\uDD27 [AzureOpenAIChatService] Tool calls detected in stream");let B=O.choices[0]?.finish_reason;if(B)y0.debug("\uD83C\uDFC1 [AzureOpenAIChatService] Stream finished with reason:",B),y0.debug("\uD83D\uDCCA [AzureOpenAIChatService] Stream summary:",{totalChunks:U,totalContentLength:H.length,hadToolCalls:F,duration:Date.now()-Y+"ms"});let L={content:_.content||void 0,toolCalls:_.tool_calls,finishReason:B||void 0};if(z)L.usage={promptTokens:z.prompt_tokens||0,completionTokens:z.completion_tokens||0,totalTokens:z.total_tokens||0};yield L}y0.debug("✅ [AzureOpenAIChatService] Stream completed successfully")}catch(K){let W=Date.now()-Y;throw y0.error("❌ [AzureOpenAIChatService] Stream request failed after",W,"ms"),y0.error("❌ [AzureOpenAIChatService] Stream error details:",K),K}}getConfig(){return{...this.config}}updateConfig($){y0.debug("\uD83D\uDD04 [AzureOpenAIChatService] Updating configuration"),this.config={...this.config,...$},this.client=new vY({apiKey:this.config.apiKey,endpoint:this.config.baseUrl,apiVersion:this.config.apiVersion||"2024-08-01-preview",timeout:this.config.timeout??180000,maxRetries:3}),y0.debug("✅ [AzureOpenAIChatService] Configuration updated successfully")}}var y0;var PY=A(()=>{B0();y0=i("Chat")});async function TY($){return $}var t2,l8,p3;var i8=A(()=>{t2={deviceCodeUrl:"https://github.com/login/device/code",tokenUrl:"https://github.com/login/oauth/access_token",clientId:"01ab8ac9400c4e429b23",scope:"user:email",grantType:"urn:ietf:params:oauth:grant-type:device_code"},l8={tokenExchange:"https://api.github.com/copilot_internal/v2/token",chatCompletions:"https://api.githubcopilot.com/chat/completions",models:"https://api.githubcopilot.com/models"},p3={"gpt-5-mini":{id:"gpt-5-mini",name:"GPT-5 Mini",provider:"openai",supportsStreaming:!0,description:"快速高效,适合简单任务"},"grok-code-fast-1":{id:"grok-code-fast-1",name:"Grok Code Fast 1",provider:"xai",supportsStreaming:!0,description:"xAI 快速代码模型"},"claude-haiku-4.5":{id:"claude-haiku-4.5",name:"Claude Haiku 4.5",provider:"anthropic",supportsStreaming:!0,description:"快速智能的 Claude"},"gpt-4.1":{id:"gpt-4.1",name:"GPT-4.1",provider:"openai",supportsStreaming:!0,description:"默认模型,平衡速度与质量"},"gpt-4o":{id:"gpt-4o",name:"GPT-4o",provider:"openai",supportsStreaming:!0,description:"多模态模型,适合日常编码"},"gpt-5":{id:"gpt-5",name:"GPT-5",provider:"openai",supportsStreaming:!0,description:"最新 GPT-5 模型"},"claude-sonnet-4":{id:"claude-sonnet-4",name:"Claude Sonnet 4",provider:"anthropic",supportsStreaming:!0,description:"平衡速度与智能的 Claude"},"claude-sonnet-4.5":{id:"claude-sonnet-4.5",name:"Claude Sonnet 4.5",provider:"anthropic",supportsStreaming:!0,description:"最新 Claude Sonnet"},"claude-opus-4.1":{id:"claude-opus-4.1",name:"Claude Opus 4.1",provider:"anthropic",supportsStreaming:!0,description:"最强 Claude,适合复杂任务"},"gemini-2.5-pro":{id:"gemini-2.5-pro",name:"Gemini 2.5 Pro",provider:"google",supportsStreaming:!0,description:"高级推理和长上下文"},"gemini-3-pro":{id:"gemini-3-pro",name:"Gemini 3 Pro",provider:"google",supportsStreaming:!0,description:"数据分析和多模态"},"gemini-3-flash":{id:"gemini-3-flash",name:"Gemini 3 Flash",provider:"google",supportsStreaming:!0,description:"快速响应模型"}}});import{spawn as vF}from"child_process";import*as b2 from"fs/promises";import*as r8 from"path";function B7(){let $=process.env.HOME||process.env.USERPROFILE||"";return r8.join($,".blade")}class C${static instance=null;cachedToken=null;constructor(){}static getInstance(){if(!C$.instance)C$.instance=new C$;return C$.instance}async isLoggedIn(){let $=await this.loadToken();if(!$)return!1;let Z=300000;if($.copilotExpiresAt&&Date.now()>$.copilotExpiresAt-Z)try{return await this.refreshCopilotToken(),!0}catch{return!1}return!0}async login(){a8.info("\uD83D\uDD10 Starting GitHub Copilot OAuth login..."),console.log(`
|
|
182
182
|
\uD83D\uDD10 开始 GitHub Copilot 认证...`);let $=await this.requestDeviceCode();console.log(`
|
|
183
183
|
\uD83D\uDCCB 请在浏览器中完成授权:`),console.log(` 1. 打开 ${$.verification_uri}`),console.log(` 2. 输入代码: ${$.user_code}`),console.log("");try{await this.openBrowser($.verification_uri),console.log("\uD83C\uDF10 已自动打开浏览器,请输入上面的代码完成授权")}catch{console.log("⚠️ 无法自动打开浏览器,请手动打开上述链接")}console.log(`
|
|
184
|
-
⏳ 等待授权中...`);let Z=await this.pollForAccessToken($.device_code,$.interval,$.expires_in);console.log("✅ GitHub 授权成功!"),console.log("\uD83D\uDD04 正在获取 Copilot token...");let X=await this.exchangeForCopilotToken(Z),Y={githubToken:Z,copilotToken:X.token,copilotExpiresAt:X.expires_at*1000};await this.saveToken(Y),this.cachedToken=Y,console.log("✅ GitHub Copilot 登录成功!"),a8.info("GitHub Copilot OAuth login completed")}async logout(){let $=r8.join(B7(),_7);try{await
|
|
184
|
+
⏳ 等待授权中...`);let Z=await this.pollForAccessToken($.device_code,$.interval,$.expires_in);console.log("✅ GitHub 授权成功!"),console.log("\uD83D\uDD04 正在获取 Copilot token...");let X=await this.exchangeForCopilotToken(Z),Y={githubToken:Z,copilotToken:X.token,copilotExpiresAt:X.expires_at*1000};await this.saveToken(Y),this.cachedToken=Y,console.log("✅ GitHub Copilot 登录成功!"),a8.info("GitHub Copilot OAuth login completed")}async logout(){let $=r8.join(B7(),_7);try{await b2.unlink($),this.cachedToken=null,console.log("✅ 已登出 GitHub Copilot"),a8.info("GitHub Copilot logout completed")}catch(Z){if(Z.code!=="ENOENT")throw Z;this.cachedToken=null}}async getCopilotToken(){if(this.cachedToken){if(this.cachedToken.copilotExpiresAt>Date.now()+300000)return this.cachedToken.copilotToken}let $=await this.loadToken();if(!$)throw Error("Not logged in to GitHub Copilot. Please run /login copilot first.");let Z=300000;if($.copilotExpiresAt<=Date.now()+Z)return await this.refreshCopilotToken(),this.cachedToken.copilotToken;return this.cachedToken=$,$.copilotToken}async refreshCopilotToken(){let $=await this.loadToken();if(!$||!$.githubToken)throw Error("No GitHub token available");a8.info("\uD83D\uDD04 Refreshing Copilot token...");let Z=await this.exchangeForCopilotToken($.githubToken),X={githubToken:$.githubToken,copilotToken:Z.token,copilotExpiresAt:Z.expires_at*1000};await this.saveToken(X),this.cachedToken=X,a8.info("✅ Copilot token refreshed successfully")}async requestDeviceCode(){let $=new URLSearchParams({client_id:t2.clientId,scope:t2.scope}),Z=await P$(t2.deviceCodeUrl,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:$.toString()});if(!Z.ok){let X=await Z.text();throw Error(`Failed to request device code: ${Z.status} - ${X}`)}return await Z.json()}async pollForAccessToken($,Z,X){let Y=Date.now(),Q=X*1000;while(Date.now()-Y<Q){await this.sleep(Z*1000);let J=new URLSearchParams({client_id:t2.clientId,device_code:$,grant_type:t2.grantType}),q=await(await P$(t2.tokenUrl,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:J.toString()})).json();if(q.access_token)return q.access_token;if(q.error==="authorization_pending")continue;if(q.error==="slow_down"){Z+=5;continue}if(q.error==="expired_token")throw Error("Device code expired. Please try again.");if(q.error==="access_denied")throw Error("Authorization denied by user.");if(q.error)throw Error(`OAuth error: ${q.error} - ${q.error_description||""}`)}throw Error("Device code expired. Please try again.")}async exchangeForCopilotToken($){let Z=await P$(l8.tokenExchange,{method:"GET",headers:{Authorization:`token ${$}`,Accept:"application/json","User-Agent":"GitHubCopilotChat/0.22.2024","Editor-Version":"vscode/1.95.0","Editor-Plugin-Version":"copilot-chat/0.22.2024"}});if(!Z.ok){let X=await Z.text();if(Z.status===401)throw Error("GitHub token is invalid or expired. Please run /login copilot again.");if(Z.status===403)throw Error("No Copilot subscription found. Please ensure you have an active GitHub Copilot subscription.");throw Error(`Failed to exchange for Copilot token: ${Z.status} - ${X}`)}return await Z.json()}async openBrowser($){let Z,X;if(process.platform==="darwin")Z="open",X=[$];else if(process.platform==="win32")Z="cmd",X=["/c","start","",$];else Z="xdg-open",X=[$];await new Promise((Y,Q)=>{let J=vF(Z,X,{stdio:"ignore"});J.once("error",Q),J.once("close",(G)=>{if(G===0||G===null)Y();else Q(Error(`Failed to open browser (exit code ${G})`))})})}async saveToken($){let Z=B7();await b2.mkdir(Z,{recursive:!0});let X=r8.join(Z,_7);await b2.writeFile(X,JSON.stringify($,null,2),{mode:384})}async loadToken(){let $=r8.join(B7(),_7);try{let Z=await b2.readFile($,"utf-8");return JSON.parse(Z)}catch(Z){if(Z.code==="ENOENT")return null;throw Z}}async getStatus(){let $=await this.loadToken();if(!$)return{loggedIn:!1};return{loggedIn:!0,expiresAt:$.copilotExpiresAt?new Date($.copilotExpiresAt):void 0}}sleep($){return new Promise((Z)=>setTimeout(Z,$))}}var a8,_7="copilot-token.json";var n8=A(()=>{B0();k4();i8();a8=i("Service")});import{isPlainObject as d3}from"lodash-es";class L7{config;auth;constructor($){this.config=$,this.auth=C$.getInstance()}getConfig(){return this.config}updateConfig($){this.config={...this.config,...$}}async chat($,Z,X){let Y=Date.now();K1.debug("\uD83D\uDE80 [CopilotChatService] Starting chat request"),K1.debug(`\uD83D\uDCDD [CopilotChatService] Messages count: ${$.length}`);try{let Q=await this.auth.getCopilotToken(),J=this.buildRequest($,Z,!1),G=await this.makeRequest(Q,J,X),q=Date.now()-Y;return K1.debug(`✅ [CopilotChatService] Chat completed in ${q} ms`),this.parseResponse(G)}catch(Q){let J=Date.now()-Y;throw K1.error(`❌ [CopilotChatService] Chat failed after ${J} ms`),K1.error(`❌ [CopilotChatService] Error: ${Q}`),Q}}async*streamChat($,Z,X){let Y=Date.now();K1.debug("\uD83D\uDE80 [CopilotChatService] Starting stream chat request"),K1.debug(`\uD83D\uDCDD [CopilotChatService] Messages count: ${$.length}`);try{let Q=await this.auth.getCopilotToken(),J=this.buildRequest($,Z,!0),G=await P$(l8.chatCompletions,{method:"POST",headers:{Authorization:`Bearer ${Q}`,"Content-Type":"application/json",Accept:"text/event-stream","Copilot-Integration-Id":"vscode-chat","Editor-Version":"vscode/1.95.0","Editor-Plugin-Version":"copilot-chat/0.22.2024","User-Agent":"GitHubCopilotChat/0.22.2024"},body:JSON.stringify(J),signal:X});if(!G.ok){let F=await G.text();throw Error(`Copilot API error: ${G.status} - ${F}`)}if(!G.body)throw Error("No response body");let q=G.body.getReader(),K=new TextDecoder,W="",U=new Map;while(!0){let{done:F,value:O}=await q.read();if(F)break;W+=K.decode(O,{stream:!0});let z=W.split(`
|
|
185
185
|
`);W=z.pop()||"";for(let _ of z){if(!_.startsWith("data: "))continue;let B=_.slice(6).trim();if(B==="[DONE]"){if(U.size>0)yield{toolCalls:Array.from(U.values()),finishReason:"tool_calls"};continue}try{let w=JSON.parse(B).choices[0];if(w){let R={};if(w.delta.content)R.content=w.delta.content;if(w.delta.tool_calls)for(let D of w.delta.tool_calls){let V=U.get(D.index);if(V){if(D.function?.arguments)V.function.arguments+=D.function.arguments}else U.set(D.index,{id:D.id||"",type:"function",function:{name:D.function?.name||"",arguments:D.function?.arguments||""}})}if(w.finish_reason)R.finishReason=w.finish_reason;if(R.content||R.finishReason==="stop")yield R}}catch{}}}let H=Date.now()-Y;K1.debug(`✅ [CopilotChatService] Stream completed in ${H} ms`)}catch(Q){let J=Date.now()-Y;throw K1.error(`❌ [CopilotChatService] Stream failed after ${J} ms`),K1.error(`❌ [CopilotChatService] Error: ${Q}`),Q}}sanitizeMessages($){let Z=[],X=new Set;for(let Y=0;Y<$.length;Y++){let Q=$[Y];if(Q.role==="assistant"&&Q.tool_calls&&Q.tool_calls.length>0){let J=[];for(let G of Q.tool_calls){let q=!1;for(let K=Y+1;K<$.length;K++){if($[K].role==="tool"&&$[K].tool_call_id===G.id){q=!0;break}if($[K].role==="assistant"||$[K].role==="user")break}if(q)J.push(G.id),X.add(G.id)}if(J.length>0)Z.push({...Q,tool_calls:Q.tool_calls.filter((G)=>J.includes(G.id))});else Z.push({role:Q.role,content:Q.content||"",reasoningContent:Q.reasoningContent})}else if(Q.role==="tool"){if(Q.tool_call_id&&X.has(Q.tool_call_id))Z.push(Q)}else Z.push(Q)}if(Z.length!==$.length)K1.debug(`[CopilotChatService] Sanitized messages: ${$.length} -> ${Z.length}`);return Z}buildRequest($,Z,X=!1){let Q=this.sanitizeMessages($).map((G)=>{let q;if(typeof G.content==="string")q=G.content;else if(Array.isArray(G.content))q=G.content.filter((W)=>W.type==="text").map((W)=>W.text).join(`
|
|
186
|
-
`);else q=null;let K={role:G.role,content:q};if(G.tool_call_id)K.tool_call_id=G.tool_call_id;if(G.name)K.name=G.name;if(G.tool_calls&&G.tool_calls.length>0)K.tool_calls=G.tool_calls.filter((W)=>W.type==="function"&&("function"in W)).map((W)=>({id:W.id,type:"function",function:{name:W.function.name,arguments:W.function.arguments}}));return K}),J={model:this.config.model,messages:Q,stream:X};if(this.config.temperature!==void 0)J.temperature=this.config.temperature;if(this.config.maxOutputTokens)J.max_tokens=this.config.maxOutputTokens;if(Z&&Z.length>0)J.tools=Z.map((G)=>({type:"function",function:{name:G.name,description:G.description,parameters:this.cleanParameters(G.parameters)}})),J.tool_choice="auto";return J}cleanParameters($){if(!d3($))return{};let Z={};for(let[X,Y]of Object.entries($)){if(["$ref","const","default"].includes(X))continue;if(X==="properties"&&d3(Y)){let Q={};for(let[J,G]of Object.entries(Y))Q[J]=d3(G)?this.cleanParameters(G):G;Z[X]=Q}else if(X==="items"&&d3(Y))Z[X]=this.cleanParameters(Y);else Z[X]=Y}return Z}async makeRequest($,Z,X){let Y=await P$(l8.chatCompletions,{method:"POST",headers:{Authorization:`Bearer ${$}`,"Content-Type":"application/json",Accept:"application/json","Copilot-Integration-Id":"vscode-chat","Editor-Version":"vscode/1.95.0","Editor-Plugin-Version":"copilot-chat/0.22.2024","User-Agent":"GitHubCopilotChat/0.22.2024"},body:JSON.stringify(Z),signal:X});if(!Y.ok){let Q=await Y.text();if(K1.error(`Copilot API error: ${Y.status} - ${Q}`),Y.status===401)throw Error("Copilot token expired or invalid. Please run /login copilot again.");if(Y.status===403)throw Error("Permission denied. Please ensure you have an active GitHub Copilot subscription.");if(Y.status===429)throw Error("Rate limit exceeded. Please wait and try again.");throw Error(`Copilot API error: ${Y.status} - ${Q}`)}return await Y.json()}parseResponse($){let Z=$.choices[0];if(!Z)throw Error("No response from Copilot API");let X={content:Z.message.content||""};if(Z.message.tool_calls&&Z.message.tool_calls.length>0)X.toolCalls=Z.message.tool_calls.map((Y)=>({id:Y.id,type:"function",function:{name:Y.function.name,arguments:Y.function.arguments}}));if($.usage)X.usage={promptTokens:$.usage.prompt_tokens,completionTokens:$.usage.completion_tokens,totalTokens:$.usage.total_tokens};return X}}var K1;var SY=A(()=>{B0();
|
|
186
|
+
`);else q=null;let K={role:G.role,content:q};if(G.tool_call_id)K.tool_call_id=G.tool_call_id;if(G.name)K.name=G.name;if(G.tool_calls&&G.tool_calls.length>0)K.tool_calls=G.tool_calls.filter((W)=>W.type==="function"&&("function"in W)).map((W)=>({id:W.id,type:"function",function:{name:W.function.name,arguments:W.function.arguments}}));return K}),J={model:this.config.model,messages:Q,stream:X};if(this.config.temperature!==void 0)J.temperature=this.config.temperature;if(this.config.maxOutputTokens)J.max_tokens=this.config.maxOutputTokens;if(Z&&Z.length>0)J.tools=Z.map((G)=>({type:"function",function:{name:G.name,description:G.description,parameters:this.cleanParameters(G.parameters)}})),J.tool_choice="auto";return J}cleanParameters($){if(!d3($))return{};let Z={};for(let[X,Y]of Object.entries($)){if(["$ref","const","default"].includes(X))continue;if(X==="properties"&&d3(Y)){let Q={};for(let[J,G]of Object.entries(Y))Q[J]=d3(G)?this.cleanParameters(G):G;Z[X]=Q}else if(X==="items"&&d3(Y))Z[X]=this.cleanParameters(Y);else Z[X]=Y}return Z}async makeRequest($,Z,X){let Y=await P$(l8.chatCompletions,{method:"POST",headers:{Authorization:`Bearer ${$}`,"Content-Type":"application/json",Accept:"application/json","Copilot-Integration-Id":"vscode-chat","Editor-Version":"vscode/1.95.0","Editor-Plugin-Version":"copilot-chat/0.22.2024","User-Agent":"GitHubCopilotChat/0.22.2024"},body:JSON.stringify(Z),signal:X});if(!Y.ok){let Q=await Y.text();if(K1.error(`Copilot API error: ${Y.status} - ${Q}`),Y.status===401)throw Error("Copilot token expired or invalid. Please run /login copilot again.");if(Y.status===403)throw Error("Permission denied. Please ensure you have an active GitHub Copilot subscription.");if(Y.status===429)throw Error("Rate limit exceeded. Please wait and try again.");throw Error(`Copilot API error: ${Y.status} - ${Q}`)}return await Y.json()}parseResponse($){let Z=$.choices[0];if(!Z)throw Error("No response from Copilot API");let X={content:Z.message.content||""};if(Z.message.tool_calls&&Z.message.tool_calls.length>0)X.toolCalls=Z.message.tool_calls.map((Y)=>({id:Y.id,type:"function",function:{name:Y.function.name,arguments:Y.function.arguments}}));if($.usage)X.usage={promptTokens:$.usage.prompt_tokens,completionTokens:$.usage.completion_tokens,totalTokens:$.usage.total_tokens};return X}}var K1;var SY=A(()=>{B0();k4();n8();i8();K1=i("Chat")});import{GoogleGenAI as CY}from"@google/genai";function kY($){let Z=new Set;for(let X of $)if(X.role==="assistant"&&X.tool_calls)for(let Y of X.tool_calls)Z.add(Y.id);return $.filter((X)=>{if(X.role==="tool"){if(!X.tool_call_id)return!1;return Z.has(X.tool_call_id)}return!0})}function w7($){if(typeof $==="string")return $;return $.filter((Z)=>Z.type==="text").map((Z)=>Z.text).join(`
|
|
187
187
|
`)}function N7($){let Z={};for(let[X,Y]of Object.entries($)){if(X==="$schema"||X==="additionalProperties")continue;if(Y&&typeof Y==="object"&&!Array.isArray(Y))Z[X]=N7(Y);else if(Array.isArray(Y))Z[X]=Y.map((Q)=>Q&&typeof Q==="object"&&!Array.isArray(Q)?N7(Q):Q);else Z[X]=Y}return Z}class b7{client;config;constructor($){if(this.config=$,f0.debug("\uD83D\uDE80 [GeminiChatService] Initializing"),f0.debug("⚙️ [GeminiChatService] Config:",{model:$.model,baseUrl:$.baseUrl,temperature:$.temperature,maxContextTokens:$.maxContextTokens,timeout:$.timeout,hasApiKey:!!$.apiKey}),!$.apiKey)throw f0.error("❌ [GeminiChatService] apiKey is required"),Error("apiKey is required in ChatConfig");if(!$.model)throw f0.error("❌ [GeminiChatService] model is required"),Error("model is required in ChatConfig");this.client=new CY({apiKey:$.apiKey}),f0.debug("✅ [GeminiChatService] Initialized successfully")}convertToGeminiMessages($){let Z=$.find((q)=>q.role==="system"),X=Z?w7(Z.content):void 0,Y=[],Q=$.filter((q)=>q.role!=="system"),J=new Map;for(let q of Q)if(q.role==="assistant"&&q.tool_calls){for(let K of q.tool_calls)if(K.type==="function")J.set(K.id,K.function.name)}for(let q of Q)if(q.role==="user"){let K=[];if(Array.isArray(q.content)){for(let W of q.content)if(W.type==="text")K.push({text:W.text});else if(W.type==="image_url"){let U=W.image_url.url;if(U.startsWith("data:")){let H=U.match(/^data:([^;,]+);base64,(.+)$/);if(H)K.push({inlineData:{mimeType:H[1],data:H[2]}})}else K.push({text:`[Image: ${U}]`})}}else K.push({text:q.content});Y.push({role:"user",parts:K})}else if(q.role==="assistant"){let K=[],W=w7(q.content);if(W)K.push({text:W});if(q.tool_calls)for(let U of q.tool_calls){if(U.type!=="function")continue;let H={};try{H=JSON.parse(U.function.arguments||"{}")}catch{f0.warn(`⚠️ [GeminiChatService] Failed to parse tool arguments: ${U.function.arguments}`)}K.push({functionCall:{name:U.function.name,args:H}})}if(K.length>0)Y.push({role:"model",parts:K})}else if(q.role==="tool"){let K=J.get(q.tool_call_id||"");if(K)Y.push({role:"user",parts:[{functionResponse:{name:K,response:{result:w7(q.content)}}}]})}let G=[];for(let q of Y){let K=G[G.length-1];if(K?.role===q.role){let W=K.parts||[],U=q.parts||[];K.parts=[...W,...U]}else G.push(q)}if(G.length>0&&G[0].role!=="user")G.unshift({role:"user",parts:[{text:"[Conversation start]"}]});return{systemInstruction:X,contents:G}}convertToGeminiTools($){if(!$||$.length===0)return;return[{functionDeclarations:$.map((X)=>({name:X.name,description:X.description,parameters:N7(X.parameters||{type:"object",properties:{}})}))}]}async chat($,Z,X){let Y=Date.now();f0.debug("\uD83D\uDE80 [GeminiChatService] Starting chat request"),f0.debug("\uD83D\uDCDD [GeminiChatService] Messages count:",$.length);let Q=kY($);if(Q.length<$.length)f0.debug(`\uD83D\uDD27 [GeminiChatService] 过滤掉 ${$.length-Q.length} 条孤儿 tool 消息`);let{systemInstruction:J,contents:G}=this.convertToGeminiMessages(Q),q=this.convertToGeminiTools(Z);f0.debug("\uD83D\uDD27 [GeminiChatService] Tools count:",q?.[0]?.functionDeclarations?.length||0),f0.debug("\uD83D\uDCE4 [GeminiChatService] Request params:",{model:this.config.model,contentsCount:G.length,hasSystemInstruction:!!J,toolsCount:q?.[0]?.functionDeclarations?.length||0,maxOutputTokens:this.config.maxOutputTokens??4096,temperature:this.config.temperature??0});try{let K=await this.client.models.generateContent({model:this.config.model,contents:G,config:{systemInstruction:J||void 0,maxOutputTokens:this.config.maxOutputTokens??4096,temperature:this.config.temperature??0,tools:q}}),W=Date.now()-Y;f0.debug("\uD83D\uDCE5 [GeminiChatService] Response received in",W,"ms");let U="",H=[],O=K.candidates?.[0]?.content?.parts||[];for(let B of O)if("text"in B&&B.text)U+=B.text;else if("functionCall"in B&&B.functionCall){let L=B.functionCall;H.push({id:`call_${Date.now()}_${Math.random().toString(36).slice(2,9)}`,type:"function",function:{name:L.name||"",arguments:JSON.stringify(L.args||{})}})}let z=K.usageMetadata,_={content:U,toolCalls:H.length>0?H:void 0,usage:{promptTokens:z?.promptTokenCount||0,completionTokens:z?.candidatesTokenCount||0,totalTokens:z?.totalTokenCount||0}};return f0.debug("✅ [GeminiChatService] Chat completed successfully"),f0.debug("\uD83D\uDCCA [GeminiChatService] Final response:",{contentLength:_.content.length,toolCallsCount:_.toolCalls?.length||0,usage:_.usage}),_}catch(K){let W=Date.now()-Y;throw f0.error("❌ [GeminiChatService] Chat request failed after",W,"ms"),f0.error("❌ [GeminiChatService] Error details:",K),K}}async*streamChat($,Z,X){let Y=Date.now();f0.debug("\uD83D\uDE80 [GeminiChatService] Starting stream request"),f0.debug("\uD83D\uDCDD [GeminiChatService] Messages count:",$.length);let Q=kY($);if(Q.length<$.length)f0.debug(`\uD83D\uDD27 [GeminiChatService] 过滤掉 ${$.length-Q.length} 条孤儿 tool 消息`);let{systemInstruction:J,contents:G}=this.convertToGeminiMessages(Q),q=this.convertToGeminiTools(Z);f0.debug("\uD83D\uDD27 [GeminiChatService] Stream tools count:",q?.[0]?.functionDeclarations?.length||0),f0.debug("\uD83D\uDCE4 [GeminiChatService] Stream request params:",{model:this.config.model,contentsCount:G.length,hasSystemInstruction:!!J,toolsCount:q?.[0]?.functionDeclarations?.length||0,maxOutputTokens:this.config.maxOutputTokens??4096,temperature:this.config.temperature??0});try{let K=await this.client.models.generateContentStream({model:this.config.model,contents:G,config:{systemInstruction:J||void 0,maxOutputTokens:this.config.maxOutputTokens??4096,temperature:this.config.temperature??0,tools:q}}),W=Date.now()-Y;f0.debug("\uD83D\uDCE5 [GeminiChatService] Stream started in",W,"ms");let U=0,H="",F=!1;for await(let O of K){U++;let z=O.candidates?.[0],_=z?.content?.parts||[],B=O.usageMetadata;for(let w of _)if("text"in w&&w.text)H+=w.text,yield{content:w.text};else if("functionCall"in w&&w.functionCall){F=!0;let R=w.functionCall;yield{toolCalls:[{id:`call_${Date.now()}_${Math.random().toString(36).slice(2,9)}`,type:"function",function:{name:R.name||"",arguments:JSON.stringify(R.args||{})}}]}}let L=z?.finishReason;if(L){f0.debug("\uD83C\uDFC1 [GeminiChatService] Stream finished:",L),f0.debug("\uD83D\uDCCA [GeminiChatService] Stream summary:",{totalEvents:U,totalContentLength:H.length,hadToolCalls:F,duration:Date.now()-Y+"ms"});let w;if(L==="STOP")w="stop";else if(L==="MAX_TOKENS")w="length";else w=L.toLowerCase();let R={finishReason:w};if(B)R.usage={promptTokens:B.promptTokenCount||0,completionTokens:B.candidatesTokenCount||0,totalTokens:B.totalTokenCount||0};yield R}else if(B)yield{usage:{promptTokens:B.promptTokenCount||0,completionTokens:B.candidatesTokenCount||0,totalTokens:B.totalTokenCount||0}}}f0.debug("✅ [GeminiChatService] Stream completed successfully")}catch(K){let W=Date.now()-Y;throw f0.error("❌ [GeminiChatService] Stream request failed after",W,"ms"),f0.error("❌ [GeminiChatService] Stream error details:",K),K}}getConfig(){return{...this.config}}updateConfig($){f0.debug("\uD83D\uDD04 [GeminiChatService] Updating configuration"),this.config={...this.config,...$},this.client=new CY({apiKey:this.config.apiKey}),f0.debug("✅ [GeminiChatService] Configuration updated successfully")}}var f0;var fY=A(()=>{B0();f0=i("Chat")});import{isPlainObject as EF}from"lodash-es";import hY from"openai";function PF($){for(let Z of pY){let X=$[Z];if(X)return{content:X,fieldName:Z}}return}function xY($){let Z=new Set;for(let X of $)if(X.role==="assistant"&&X.tool_calls)for(let Y of X.tool_calls)Z.add(Y.id);return $.filter((X)=>{if(X.role==="tool"){if(!X.tool_call_id)return!1;return Z.has(X.tool_call_id)}return!0})}class m3{config;client;detectedReasoningFieldName=null;convertToOpenAIMessages($){return $.map((Z)=>{if(Z.role==="tool")return{role:"tool",content:typeof Z.content==="string"?Z.content:Z.content.filter((Y)=>Y.type==="text").map((Y)=>Y.text).join(`
|
|
188
188
|
`),tool_call_id:Z.tool_call_id};if(Z.role==="assistant"&&Z.tool_calls){let Y={role:"assistant",content:(typeof Z.content==="string"?Z.content:Z.content.filter((Q)=>Q.type==="text").map((Q)=>Q.text).join(`
|
|
189
189
|
`))||null,tool_calls:Z.tool_calls};if(this.config.supportsThinking){let Q="reasoningContent"in Z&&Z.reasoningContent?Z.reasoningContent:"";if(this.detectedReasoningFieldName)Y[this.detectedReasoningFieldName]=Q;else for(let J of pY)Y[J]=Q}return Y}if(Z.role==="user"&&Array.isArray(Z.content))return{role:"user",content:Z.content.map((X)=>{if(X.type==="text")return{type:"text",text:X.text};return{type:"image_url",image_url:{url:X.image_url.url}}})};return{role:Z.role,content:typeof Z.content==="string"?Z.content:Z.content.filter((X)=>X.type==="text").map((X)=>X.text).join(`
|
|
@@ -192,7 +192,7 @@ If the browser does not open automatically, copy and paste this URL:`),console.l
|
|
|
192
192
|
`),J=Q.length,G=Y,q=!1,K=J;if(J>this.MAX_LINES_PER_FILE)G=Q.slice(0,this.MAX_LINES_PER_FILE).join(`
|
|
193
193
|
`),G+=`
|
|
194
194
|
|
|
195
|
-
... (truncated ${J-this.MAX_LINES_PER_FILE} lines)`,q=!0,K=this.MAX_LINES_PER_FILE;Z.push({path:X,content:G,truncated:q,lines:J,includedLines:K})}catch(Y){console.warn(`[FileAnalyzer] 无法读取文件: ${X}`,Y)}return Z}static extractFilePathsFromContent($){let Z=new Set,X=/```(?:\w+)?\s*\n?([\s\S]*?)```/g,Y=Array.from($.matchAll(X));for(let J of Y){let G=J[1];this.extractPathsFromText(G).forEach((K)=>Z.add(K))}return this.extractPathsFromText($).forEach((J)=>Z.add(J)),Array.from(Z)}static extractPathsFromText($){let Z=[],X=[/(?: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 Y of X){let Q=Array.from($.matchAll(Y));for(let J of Q){let G=J[0];if(G=G.replace(/[,。;:!?""''()【】《》]$/g,""),G=G.replace(/[,.;:!?"'()[\]<>]$/g,""),this.isValidFilePath(G))Z.push(G)}}return Z}static extractFilePathsFromToolCall($){let Z=[];try{let X=$.function?.name,Y=typeof $.function?.arguments==="string"?JSON.parse($.function.arguments):$.function?.arguments||{};if(["Read","Write","Edit","Glob","Grep","NotebookEdit","mcp__github__get_file_contents","mcp__github__create_or_update_file"].includes(X)){let J=["file_path","path","notebook_path","filePath"];for(let G of J)if(Y[G]&&typeof Y[G]==="string")Z.push(Y[G])}}catch(X){}return Z}static updateFileReference($,Z,X,Y){let Q=$.get(Z);if(Q)Q.mentions++,Q.lastMentioned=X,Q.wasModified=Q.wasModified||Y;else $.set(Z,{path:Z,mentions:1,lastMentioned:X,wasModified:Y})}static isValidFilePath($){if(!$.includes("/"))return!1;let Z=$.split("/"),X=Z[Z.length-1];if(!X.includes("."))return!1;let Y=["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"],Q=X.split(".").pop()?.toLowerCase();if(!Q||!Y.includes(Q))return!1;return!0}}var uY=()=>{};import{encodingForModel as gY}from"js-tiktoken";var
|
|
195
|
+
... (truncated ${J-this.MAX_LINES_PER_FILE} lines)`,q=!0,K=this.MAX_LINES_PER_FILE;Z.push({path:X,content:G,truncated:q,lines:J,includedLines:K})}catch(Y){console.warn(`[FileAnalyzer] 无法读取文件: ${X}`,Y)}return Z}static extractFilePathsFromContent($){let Z=new Set,X=/```(?:\w+)?\s*\n?([\s\S]*?)```/g,Y=Array.from($.matchAll(X));for(let J of Y){let G=J[1];this.extractPathsFromText(G).forEach((K)=>Z.add(K))}return this.extractPathsFromText($).forEach((J)=>Z.add(J)),Array.from(Z)}static extractPathsFromText($){let Z=[],X=[/(?: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 Y of X){let Q=Array.from($.matchAll(Y));for(let J of Q){let G=J[0];if(G=G.replace(/[,。;:!?""''()【】《》]$/g,""),G=G.replace(/[,.;:!?"'()[\]<>]$/g,""),this.isValidFilePath(G))Z.push(G)}}return Z}static extractFilePathsFromToolCall($){let Z=[];try{let X=$.function?.name,Y=typeof $.function?.arguments==="string"?JSON.parse($.function.arguments):$.function?.arguments||{};if(["Read","Write","Edit","Glob","Grep","NotebookEdit","mcp__github__get_file_contents","mcp__github__create_or_update_file"].includes(X)){let J=["file_path","path","notebook_path","filePath"];for(let G of J)if(Y[G]&&typeof Y[G]==="string")Z.push(Y[G])}}catch(X){}return Z}static updateFileReference($,Z,X,Y){let Q=$.get(Z);if(Q)Q.mentions++,Q.lastMentioned=X,Q.wasModified=Q.wasModified||Y;else $.set(Z,{path:Z,mentions:1,lastMentioned:X,wasModified:Y})}static isValidFilePath($){if(!$.includes("/"))return!1;let Z=$.split("/"),X=Z[Z.length-1];if(!X.includes("."))return!1;let Y=["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"],Q=X.split(".").pop()?.toLowerCase();if(!Q||!Y.includes(Q))return!1;return!0}}var uY=()=>{};import{encodingForModel as gY}from"js-tiktoken";var Z2;var c3=A(()=>{Z2=class Z2{static encodingCache=new Map;static countTokens($,Z){let X=this.getEncoding(Z),Y=0;for(let Q of $){if(Y+=4,Q.role)Y+=X.encode(Q.role).length;if(Q.content)if(typeof Q.content==="string")Y+=X.encode(Q.content).length;else Y+=X.encode(JSON.stringify(Q.content)).length;if(Q.tool_calls&&Array.isArray(Q.tool_calls))Y+=this.countToolCallTokens(Q.tool_calls,X);if(Q.name)Y+=X.encode(Q.name).length}return Y}static getTokenLimit($){return $}static shouldCompact($,Z,X,Y=0.8){let Q=this.countTokens($,Z),J=Math.floor(X*Y);return Q>=J}static getEncoding($){if(!this.encodingCache.has($))try{let Z=gY($);this.encodingCache.set($,Z)}catch{try{let Z=gY("gpt-4");this.encodingCache.set($,Z)}catch{console.warn(`[TokenCounter] 无法为模型 ${$} 获取 encoding,使用粗略估算`),this.encodingCache.set($,{encode:(Z)=>{return Array(Math.ceil(Z.length/4))}})}}return this.encodingCache.get($)}static countToolCallTokens($,Z){let X=0;for(let Y of $){if(X+=4,Y.type==="function"&&Y.function?.name)X+=Z.encode(Y.function.name).length;if(Y.type==="function"&&Y.function?.arguments)X+=Z.encode(Y.function.arguments).length;if(Y.id)X+=Z.encode(Y.id).length}return X}static clearCache(){this.encodingCache.clear()}static estimateTokens($){let Z=($.match(/[\u4e00-\u9fa5]/g)||[]).length,X=$.length-Z;return Math.ceil(Z/1.5+X/4)}}});import{nanoid as f4}from"nanoid";class h4{static THRESHOLD_PERCENT=0.8;static RETAIN_PERCENT=0.2;static FALLBACK_RETAIN_PERCENT=0.3;static async compact($,Z){let X=Z.actualPreTokens??Z2.countTokens($,Z.modelName),Y=Z.actualPreTokens?"actual (from LLM usage)":"estimated";console.log(`[CompactionService] preTokens source: ${Y}`);try{let J=await M0.getInstance().executeCompactionHooks(Z.trigger,{projectDir:process.cwd(),sessionId:Z.sessionId||"unknown",permissionMode:Z.permissionMode||"default",messagesBefore:$.length,tokensBefore:X});if(J.blockCompaction)return console.log(`[CompactionService] Compaction hook 阻止压缩: ${J.blockReason||"(无原因)"}`),{success:!1,summary:"",preTokens:X,postTokens:X,filesIncluded:[],compactedMessages:$,boundaryMessage:{role:"system",content:""},summaryMessage:{role:"user",content:""},error:J.blockReason||"Compaction blocked by hook"};if(J.warning)console.warn(`[CompactionService] Compaction hook warning: ${J.warning}`)}catch(Q){console.warn("[CompactionService] Compaction hook execution failed:",Q)}try{console.log("[CompactionService] 开始压缩,消息数:",$.length),console.log("[CompactionService] 压缩前 tokens:",X);let J=g3.analyzeFiles($).map((w)=>w.path);console.log("[CompactionService] 提取重点文件:",J);let G=await g3.readFilesContent(J);console.log("[CompactionService] 成功读取文件:",G.length);let q=await this.generateSummary($,G,Z);console.log("[CompactionService] 生成总结,长度:",q.length);let K=Math.ceil($.length*this.RETAIN_PERCENT),W=$.slice(-K),U=new Set;for(let w of W)if(w.role==="assistant"&&w.tool_calls)for(let R of w.tool_calls)U.add(R.id);let H=W.filter((w)=>{if(w.role==="tool"&&w.tool_call_id)return U.has(w.tool_call_id);return!0});console.log("[CompactionService] 保留消息数:",K),console.log("[CompactionService] 过滤后保留消息数:",H.length);let F=f4(),O=this.createBoundaryMessage(F,Z.trigger,X),z=f4(),_=this.createSummaryMessage(z,q),B=[_,...H],L=Z2.countTokens(B,Z.modelName);return console.log("[CompactionService] 压缩完成!"),console.log("[CompactionService] Token 变化:",X,"→",L,`(-${((1-L/X)*100).toFixed(1)}%)`),{success:!0,summary:q,preTokens:X,postTokens:L,filesIncluded:J,compactedMessages:B,boundaryMessage:O,summaryMessage:_}}catch(Q){return console.error("[CompactionService] 压缩失败,使用降级策略",Q),this.fallbackCompact($,Z,X,Q)}}static async generateSummary($,Z,X){let Y=this.buildCompactionPrompt($,Z);console.log("[CompactionService] 使用压缩模型:",X.modelName);let G=(await(await u3({apiKey:X.apiKey||process.env.BLADE_API_KEY||"",baseUrl:X.baseURL||process.env.BLADE_BASE_URL||"https://api.openai.com/v1",model:X.modelName,temperature:0.3,maxOutputTokens:8000,timeout:60000,provider:"openai-compatible"})).chat([{role:"user",content:Y}])).content||"",q=G.match(/<summary>([\s\S]*?)<\/summary>/);if(!q)return console.warn("[CompactionService] 总结格式不正确,使用完整响应"),G;return q[1].trim()}static buildCompactionPrompt($,Z){let X=$.map((J,G)=>{let q=J.role||"unknown",K=typeof J.content==="string"?J.content:JSON.stringify(J.content),W=5000,U=K.length>5000?K.substring(0,5000)+"...":K;return`[${G+1}] ${q}: ${U}`}).join(`
|
|
196
196
|
|
|
197
197
|
`),Y=Z.map((J)=>{return`### ${J.path}
|
|
198
198
|
\`\`\`
|
|
@@ -265,13 +265,13 @@ ${Z.length>0?`## Important Files
|
|
|
265
265
|
|
|
266
266
|
${Y}`:""}
|
|
267
267
|
|
|
268
|
-
Please provide your summary following the structure specified above, with both <analysis> and <summary> sections.`}static createBoundaryMessage($,Z,X){return{id:
|
|
268
|
+
Please provide your summary following the structure specified above, with both <analysis> and <summary> sections.`}static createBoundaryMessage($,Z,X){return{id:f4(),role:"system",content:"Conversation compacted",metadata:{type:"system",subtype:"compact_boundary",parentId:$,compactMetadata:{trigger:Z,preTokens:X}}}}static createSummaryMessage($,Z){return{id:f4(),role:"user",content:Z,metadata:{parentId:$,isCompactSummary:!0}}}static fallbackCompact($,Z,X,Y){let Q=Math.ceil($.length*this.FALLBACK_RETAIN_PERCENT),J=$.slice(-Q),G=new Set;for(let _ of J)if(_.role==="assistant"&&_.tool_calls)for(let B of _.tool_calls)G.add(B.id);let q=J.filter((_)=>{if(_.role==="tool"&&_.tool_call_id)return G.has(_.tool_call_id);return!0}),K=f4(),W=this.createBoundaryMessage(K,Z.trigger,X),U=Y instanceof Error?Y.message:String(Y),H=f4(),F=this.createSummaryMessage(H,`[Automatic compaction failed; using fallback]
|
|
269
269
|
|
|
270
270
|
An error occurred during compaction. Retained the latest ${Q} messages (~30%).
|
|
271
271
|
|
|
272
272
|
Error: ${U}
|
|
273
273
|
|
|
274
|
-
The conversation can continue, but consider retrying compaction later with /compact.`),O=[F,...q],z=
|
|
274
|
+
The conversation can continue, but consider retrying compaction later with /compact.`),O=[F,...q],z=Z2.countTokens(O,Z.modelName);return{success:!1,summary:typeof F.content==="string"?F.content:F.content.filter((_)=>_.type==="text").map((_)=>_.text).join(`
|
|
275
275
|
`),preTokens:X,postTokens:z,filesIncluded:[],compactedMessages:O,boundaryMessage:W,summaryMessage:F,error:U}}}var R7=A(()=>{U$();r$();A7();uY();c3()});import{appendFileSync as CF,mkdirSync as kF,writeFileSync as fF}from"node:fs";import hF from"node:os";import lY from"node:path";function xF(){if(cY)return;let $=lY.dirname(V7);kF($,{recursive:!0}),fF(V7,`=== Stream Debug Log Started: ${new Date().toISOString()} ===
|
|
276
276
|
`),cY=!0}function W1($,Z,X){xF();let Y=new Date().toISOString(),Q=X?` | ${JSON.stringify(X)}`:"",J=`[${Y}] [${$}] ${Z}${Q}
|
|
277
277
|
`;CF(V7,J)}var V7,cY=!1;var D7=A(()=>{V7=lY.join(hF.homedir(),".blade","logs","stream-debug.log")});import pF from"fs/promises";import dF from"path";async function aY($){for(let Z of $)try{let X;if(Z.trim().startsWith("{")){let J=JSON.parse(Z);if(J.name&&J.type){let{name:G,...q}=J;X={[G]:q}}else X=J}else{let J=dF.resolve(process.cwd(),Z),G=await pF.readFile(J,"utf-8"),q=JSON.parse(G);X=q.mcpServers||q}let Q={...G1(),...X};K0().config.actions.updateConfig({mcpServers:Q}),iY.debug(`✅ Loaded MCP config from CLI: ${Object.keys(X).join(", ")}`)}catch(X){iY.warn(`⚠️ Failed to load MCP config "${Z}":`,X)}}var iY;var rY=A(()=>{B0();C0();iY=i("General")});function nY(){return{metadata:l3,instructions:`# Skill Creator
|
|
@@ -458,9 +458,9 @@ user-invocable: true
|
|
|
458
458
|
\`\`\`
|
|
459
459
|
\`\`\`
|
|
460
460
|
`}}var l3;var oY=A(()=>{l3={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"}});import{exec as mF}from"node:child_process";import*as O$ from"node:fs/promises";import{homedir as uF}from"node:os";import*as D1 from"node:path";import{promisify as gF}from"node:util";class sY{skillsDir;constructor($){this.skillsDir=$||D1.join(uF(),".blade","skills")}async isInstalled($){let Z=D1.join(this.skillsDir,$,"SKILL.md");try{return await O$.access(Z),!0}catch{return!1}}async isGitAvailable(){try{return await M7("git --version"),!0}catch{return!1}}async installOfficialSkill($){let{url:Z,branch:X}=j7,Y=D1.join(this.skillsDir,$),Q=D1.join(this.skillsDir,`.tmp-${$}-${Date.now()}`);try{if(!await this.isGitAvailable())return k1.warn("Git not available, skipping skill installation"),!1;k1.info(`Installing official skill: ${$}...`),await O$.mkdir(this.skillsDir,{recursive:!0}),await M7(`git clone --depth 1 --branch ${X} --single-branch ${Z} "${Q}"`,{timeout:30000});let J=D1.join(Q,"skills",$);try{await O$.access(J)}catch{return k1.warn(`Skill ${$} not found in official repository`),await O$.rm(Q,{recursive:!0,force:!0}),!1}try{await O$.rm(Y,{recursive:!0,force:!0})}catch{}return await O$.cp(J,Y,{recursive:!0}),await O$.rm(Q,{recursive:!0,force:!0}),k1.info(`Successfully installed: ${$}`),!0}catch(J){try{await O$.rm(Q,{recursive:!0,force:!0})}catch{}return k1.warn(`Failed to install ${$}: ${J instanceof Error?J.message:"Unknown error"}`),!1}}async ensureDefaultSkillsInstalled(){await O$.mkdir(this.skillsDir,{recursive:!0});for(let $ of j7.defaultSkills)if(!await this.isInstalled($))await this.installOfficialSkill($)}async installAllOfficialSkills(){let{url:$,branch:Z}=j7,X=D1.join(this.skillsDir,`.tmp-all-${Date.now()}`),Y=[],Q=[];try{if(!await this.isGitAvailable())return k1.warn("Git not available, skipping skill installation"),{installed:Y,failed:Q};await O$.mkdir(this.skillsDir,{recursive:!0}),k1.info("Cloning official skills repository..."),await M7(`git clone --depth 1 --branch ${Z} --single-branch ${$} "${X}"`,{timeout:60000});let J=D1.join(X,"skills"),G=await O$.readdir(J,{withFileTypes:!0});for(let q of G){if(!q.isDirectory())continue;let K=q.name,W=D1.join(J,K),U=D1.join(this.skillsDir,K);try{await O$.access(D1.join(W,"SKILL.md")),await O$.rm(U,{recursive:!0,force:!0}),await O$.cp(W,U,{recursive:!0}),k1.info(`Installed: ${K}`),Y.push(K)}catch(H){k1.warn(`Failed to install ${K}`),Q.push(K)}}await O$.rm(X,{recursive:!0,force:!0})}catch(J){try{await O$.rm(X,{recursive:!0,force:!0})}catch{}k1.warn(`Failed to install skills: ${J instanceof Error?J.message:"Unknown error"}`)}return{installed:Y,failed:Q}}}function tY($){if(!I7)I7=new sY($);return I7}var M7,k1,j7,I7=null;var eY=A(()=>{B0();M7=gF(mF),k1=i("General"),j7={url:"https://github.com/anthropics/skills.git",branch:"main",defaultSkills:["skill-creator"]}});import*as o8 from"node:fs/promises";import*as i3 from"node:path";import{parse as cF}from"yaml";function aF($){if(!$)return;if(typeof $==="string")return $.split(",").map((Z)=>Z.trim()).filter(Boolean);if(Array.isArray($))return $.map((Z)=>String(Z).trim()).filter(Boolean);return}function ZQ($){if($===void 0)return;if(typeof $==="boolean")return $;if(typeof $==="string"){let Z=$.toLowerCase().trim();if(Z==="true"||Z==="yes"||Z==="1")return!0;if(Z==="false"||Z==="no"||Z==="0")return!1}return}function rF($,Z){if(!$.name)return{valid:!1,error:"Missing required field: name"};if(!iF.test($.name))return{valid:!1,error:`Invalid name "${$.name}": must be lowercase letters, numbers, and hyphens only, 1-64 characters`};if(!$.description)return{valid:!1,error:"Missing required field: description"};if($.description.length>$Q)return{valid:!1,error:`Description too long: ${$.description.length} characters (max ${$Q})`};let X;if($.model)X=$.model==="inherit"?"inherit":$.model;return{valid:!0,metadata:{name:$.name,description:$.description.trim(),allowedTools:aF($["allowed-tools"]),version:$.version,argumentHint:$["argument-hint"]?.trim(),userInvocable:ZQ($["user-invocable"]),disableModelInvocation:ZQ($["disable-model-invocation"]),model:X,whenToUse:$.when_to_use?.trim()}}}function XQ($,Z,X){let Y=$.match(lF);if(!Y)return{success:!1,error:"Invalid SKILL.md format: missing YAML frontmatter (must start with ---)"};let[,Q,J]=Y,G;try{G=cF(Q)}catch(W){return{success:!1,error:`Failed to parse YAML frontmatter: ${W instanceof Error?W.message:String(W)}`}}let q=rF(G,Z);if(!q.valid)return{success:!1,error:q.error};let K=i3.dirname(Z);return{success:!0,content:{metadata:{...q.metadata,path:Z,basePath:K,source:X},instructions:J.trim()}}}async function a3($,Z){try{let X=await o8.readFile($,"utf-8");return XQ(X,$,Z)}catch(X){if(X.code==="ENOENT")return{success:!1,error:`File not found: ${$}`};return{success:!1,error:`Failed to read file: ${X instanceof Error?X.message:String(X)}`}}}async function YQ($){try{let Z=await o8.readFile($.path,"utf-8"),X=XQ(Z,$.path,$.source);return X.success?X.content:null}catch{return null}}async function QQ($){try{return await o8.access(i3.join($,"SKILL.md")),!0}catch{return!1}}var lF,iF,$Q=1024;var y7=A(()=>{lF=/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/,iF=/^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]?$/});import*as n3 from"node:fs/promises";import{homedir as JQ}from"node:os";import*as f1 from"node:path";class v7{skills=new Map;pluginSkills=new Map;config;initialized=!1;constructor($){this.config={...nF,...$}}static getInstance($){if(!r3)r3=new v7($);return r3}static resetInstance(){r3=null}async initialize(){if(this.initialized)return{skills:Array.from(this.skills.values()),errors:[]};let $=[],Z=[];try{await tY(this.config.userSkillsDir).ensureDefaultSkillsInstalled()}catch(K){$.push({path:"SkillInstaller",error:`Failed to install default skills: ${K instanceof Error?K.message:"Unknown error"}`})}this.loadBuiltinSkills();let X=await this.scanDirectory(this.config.claudeUserSkillsDir,"user");Z.push(...X.skills),$.push(...X.errors);let Y=await this.scanDirectory(this.config.userSkillsDir,"user");Z.push(...Y.skills),$.push(...Y.errors);let Q=f1.isAbsolute(this.config.claudeProjectSkillsDir)?this.config.claudeProjectSkillsDir:f1.join(this.config.cwd,this.config.claudeProjectSkillsDir),J=await this.scanDirectory(Q,"project");Z.push(...J.skills),$.push(...J.errors);let G=f1.isAbsolute(this.config.projectSkillsDir)?this.config.projectSkillsDir:f1.join(this.config.cwd,this.config.projectSkillsDir),q=await this.scanDirectory(G,"project");Z.push(...q.skills),$.push(...q.errors);for(let K of Z)this.skills.set(K.name,K);return this.initialized=!0,{skills:Array.from(this.skills.values()),errors:$}}loadBuiltinSkills(){this.skills.set(l3.name,l3)}async scanDirectory($,Z){let X=[],Y=[];try{await n3.access($)}catch{return{skills:X,errors:Y}}try{let Q=await n3.readdir($,{withFileTypes:!0});for(let J of Q){if(!J.isDirectory())continue;let G=f1.join($,J.name),q=f1.join(G,"SKILL.md");if(!await QQ(G))continue;let K=await a3(q,Z);if(K.success&&K.content)X.push(K.content.metadata);else Y.push({path:q,error:K.error||"Unknown error"})}}catch(Q){Y.push({path:$,error:`Failed to scan directory: ${Q instanceof Error?Q.message:String(Q)}`})}return{skills:X,errors:Y}}getAll(){return Array.from(this.skills.values())}get($){return this.skills.get($)}has($){return this.skills.has($)}async loadContent($){let Z=this.skills.get($);if(!Z)return null;if(Z.source==="builtin")return this.loadBuiltinContent($);return YQ(Z)}loadBuiltinContent($){switch($){case"skill-creator":return nY();default:return null}}getModelInvocableSkills(){return Array.from(this.skills.values()).filter(($)=>!$.disableModelInvocation)}getUserInvocableSkills(){return Array.from(this.skills.values()).filter(($)=>$.userInvocable===!0)}generateAvailableSkillsList(){let $=this.getModelInvocableSkills();if($.length===0)return"";let Z=[];for(let X of $){let Y=X.description.length>100?`${X.description.substring(0,97)}...`:X.description,Q=X.argumentHint?`${X.name} ${X.argumentHint}`:X.name;Z.push(`- ${Q}: ${Y}`)}return Z.join(`
|
|
461
|
-
`)}get size(){return this.skills.size}async refresh(){return this.skills.clear(),this.pluginSkills.clear(),this.initialized=!1,this.initialize()}registerPluginSkill($){this.pluginSkills.set($.namespacedName,$),this.skills.set($.namespacedName,$.metadata)}findPluginSkill($){let Z=this.pluginSkills.get($);if(Z)return Z;let X=[];for(let Y of this.pluginSkills.values())if(Y.originalName===$)X.push(Y);if(X.length===1)return X[0];return}getAllPluginSkills(){return Array.from(this.pluginSkills.values())}clearPluginSkills(){for(let $ of this.pluginSkills.values())this.skills.delete($.namespacedName);this.pluginSkills.clear()}getPluginSkillCount(){return this.pluginSkills.size}}function b$($){return v7.getInstance($)}async function
|
|
461
|
+
`)}get size(){return this.skills.size}async refresh(){return this.skills.clear(),this.pluginSkills.clear(),this.initialized=!1,this.initialize()}registerPluginSkill($){this.pluginSkills.set($.namespacedName,$),this.skills.set($.namespacedName,$.metadata)}findPluginSkill($){let Z=this.pluginSkills.get($);if(Z)return Z;let X=[];for(let Y of this.pluginSkills.values())if(Y.originalName===$)X.push(Y);if(X.length===1)return X[0];return}getAllPluginSkills(){return Array.from(this.pluginSkills.values())}clearPluginSkills(){for(let $ of this.pluginSkills.values())this.skills.delete($.namespacedName);this.pluginSkills.clear()}getPluginSkillCount(){return this.pluginSkills.size}}function b$($){return v7.getInstance($)}async function e2($){return b$($).initialize()}var nF,r3=null;var E7=A(()=>{oY();eY();y7();nF={userSkillsDir:f1.join(JQ(),".blade","skills"),projectSkillsDir:".blade/skills",claudeUserSkillsDir:f1.join(JQ(),".claude","skills"),claudeProjectSkillsDir:".claude/skills",cwd:process.cwd()}});function P7($){let X=b$().generateAvailableSkillsList();if(!X)return $;return $.map((Y)=>{if(Y.name!==oF)return Y;let Q=Y.description.replace(sF,`<available_skills>
|
|
462
462
|
${X}
|
|
463
|
-
</available_skills>`);if(Q===Y.description)return Y;return{...Y,description:Q}})}var oF="Skill",sF;var GQ=A(()=>{E7();sF=/<available_skills>\s*<\/available_skills>/});var
|
|
463
|
+
</available_skills>`);if(Q===Y.description)return Y;return{...Y,description:Q}})}var oF="Skill",sF;var GQ=A(()=>{E7();sF=/<available_skills>\s*<\/available_skills>/});var X2=A(()=>{GQ();E7()});import{execSync as tF}from"child_process";import*as p4 from"os";import*as x4 from"path";function eF(){let $=process.cwd(),Z=$O($);return{workingDirectory:$,projectRoot:Z,platform:`${p4.platform()} (${p4.arch()})`,nodeVersion:process.version,currentDate:new Date().toISOString().split("T")[0],homeDirectory:p4.homedir()}}function o3(){let $=eF();return`# Environment Context
|
|
464
464
|
|
|
465
465
|
## Working Directory
|
|
466
466
|
**Current**: \`${$.workingDirectory}\`
|
|
@@ -478,7 +478,7 @@ When using file tools (read, write, edit), provide **absolute paths**:
|
|
|
478
478
|
- ❌ Incorrect: \`/package.json\` (root directory)
|
|
479
479
|
- ❌ Incorrect: \`package.json\` (relative path without context)
|
|
480
480
|
|
|
481
|
-
**Always use** \`${$.workingDirectory}/\` as the base for file paths.`}function $O($){let Z=$;while(Z!==
|
|
481
|
+
**Always use** \`${$.workingDirectory}/\` as the base for file paths.`}function $O($){let Z=$;while(Z!==x4.dirname(Z)){if(qQ(x4.join(Z,".git")))return Z;if(qQ(x4.join(Z,"package.json")))return Z;Z=x4.dirname(Z)}return $}function qQ($){try{return tF(`test -e "${$}"`,{stdio:"ignore"}),!0}catch{return!1}}var T7=()=>{};function s8($){return`<system-reminder>Plan mode is active. You MUST NOT make any file changes or run non-readonly tools. Research only, then call ExitPlanMode with your plan.</system-reminder>
|
|
482
482
|
|
|
483
483
|
`+$}var KQ=`You are Blade Code, an interactive CLI tool that helps users with software engineering tasks. Use the instructions below and the tools available to you to assist the user.
|
|
484
484
|
|
|
@@ -865,7 +865,7 @@ Show current progress and suggest next steps based on actual project state.
|
|
|
865
865
|
|
|
866
866
|
`);return z=JO(z),{prompt:z,sources:W}}function JO($){let X=b$().generateAvailableSkillsList();if(!X)return $;return $.replace(QO,`<available_skills>
|
|
867
867
|
${X}
|
|
868
|
-
</available_skills>`)}async function GO($){let Z=YO.join($,"BLADE.md");try{return(await UQ.readFile(Z,"utf-8")).trim()||null}catch{return null}}var QO;var HQ=A(()=>{U$();
|
|
868
|
+
</available_skills>`)}async function GO($){let Z=YO.join($,"BLADE.md");try{return(await UQ.readFile(Z,"utf-8")).trim()||null}catch{return null}}var QO;var HQ=A(()=>{U$();X2();T7();S7();QO=/<available_skills>\s*<\/available_skills>/});var FQ=A(()=>{HQ()});import*as $6 from"fs/promises";import*as c$ from"path";class Z6{static normalize($,Z){let X=c$.isAbsolute($)?$:c$.resolve(Z,$),Y=c$.normalize(X),Q=c$.normalize(Z);if(!Y.startsWith(Q))throw new $4(`Path outside workspace: ${$} (resolved to ${Y}, workspace: ${Q})`,"PATH_OUTSIDE_WORKSPACE");return Y}static checkRestricted($){let Z=$.split(c$.sep);for(let X of OQ)if(Z.includes(X))throw new $4(`Access denied: "${X}" is a protected directory`,"RESTRICTED_PATH")}static checkTraversal($){if($.includes(".."))throw new $4(`Path traversal not allowed: ${$}`,"PATH_TRAVERSAL")}static async validatePath($,Z){this.checkTraversal($);let X=this.normalize($,Z);this.checkRestricted(X);try{await $6.access(X)}catch(Y){throw new $4(`Path not found: ${$}`,"PATH_NOT_FOUND")}return X}static async resolveSymlink($,Z){try{let X=await $6.realpath($),Y=c$.normalize(Z);if(!X.startsWith(Y))throw new $4(`Symlink points outside workspace: ${$} -> ${X}`,"SYMLINK_OUTSIDE_WORKSPACE");return X}catch(X){if(X instanceof $4)throw X;return $}}static getRelativePath($,Z){return c$.relative(Z,$)}static isWithinWorkspace($,Z){let X=c$.normalize($),Y=c$.normalize(Z);return X.startsWith(Y)}static isRestricted($){let Z=$.split(c$.sep);return OQ.some((X)=>Z.includes(X))}}var OQ,$4;var zQ=A(()=>{OQ=[".git",".claude","node_modules",".env",".env.local",".env.production",".env.development",".env.test"];$4=class $4 extends Error{code;constructor($,Z){super($);this.code=Z;this.name="PathSecurityError"}}});var X6;var _Q=A(()=>{X6=class X6{static PATTERN=/@"([^"]+)"|@([^\s]+)/g;static LINE_RANGE_PATTERN=/#L(\d+)(?:-(\d+))?$/;static GLOB_PATTERN=/[*?[\]]/;static extract($){let Z=[],X;this.PATTERN.lastIndex=0;while((X=this.PATTERN.exec($))!==null){let Y=X[0],Q=X[1]||X[2],J=this.parseLineRange(Q);if(J)Q=Q.replace(this.LINE_RANGE_PATTERN,"");let G=this.GLOB_PATTERN.test(Q);Z.push({raw:Y,path:Q.trim(),lineRange:J,startIndex:X.index,endIndex:X.index+Y.length,isGlob:G})}return Z}static parseLineRange($){let Z=$.match(this.LINE_RANGE_PATTERN);if(!Z)return;let X=parseInt(Z[1],10),Y=Z[2]?parseInt(Z[2],10):void 0;return{start:X,end:Y}}static hasAtMentions($){return $.includes("@")}static isValidPath($){if(!$||$.trim().length===0)return!1;let Z=["<",">","|","\x00"];for(let X of Z)if($.includes(X))return!1;return!0}static removeAtMentions($){return this.PATTERN.lastIndex=0,$.replace(this.PATTERN,"")}}});import BQ from"fast-glob";import*as d4 from"fs/promises";import*as LQ from"path";function Y6($){return $ instanceof Map}class C7{fileCache=new Map;options;constructor($){this.options={maxFileSize:1048576,maxLines:2000,maxTokens:32000,...$},M1.debug("AttachmentCollector initialized",{maxFileSize:this.options.maxFileSize,maxLines:this.options.maxLines})}async collect($){if(!X6.hasAtMentions($))return[];let Z=X6.extract($);if(Z.length===0)return[];M1.debug(`Found ${Z.length} @ mentions`);let X=Z.map((Q)=>this.processOne(Q));return(await Promise.allSettled(X)).map((Q,J)=>{if(Q.status==="fulfilled")return Q.value;else{let G=Z[J],q=Q.reason instanceof Error?Q.reason.message:String(Q.reason);return M1.warn(`Failed to process @${G.path}:`,q),{type:"error",path:G.path,content:"",error:q}}})}async processOne($){if($.isGlob)return M1.debug(`Processing glob pattern: ${$.path}`),await this.processGlob($.path);let Z=await Z6.validatePath($.path,this.options.cwd),X=await Z6.resolveSymlink(Z,this.options.cwd);if((await d4.stat(X)).isDirectory())return M1.debug(`Processing directory: ${$.path}`),await this.renderDirectoryTree(X,$.path);return M1.debug(`Processing file: ${$.path}`,{lineRange:$.lineRange}),await this.readFile(X,$.path,$.lineRange)}async readFile($,Z,X){let Y=this.fileCache.get($);if(Y&&Date.now()-Y.timestamp<60000)return M1.debug(`Cache hit: ${Z}`),this.formatFileAttachment(Z,Y.content,X);let Q=await d4.stat($);if(Q.size>this.options.maxFileSize)throw Error(`File too large: ${Math.round(Q.size/1024/1024)}MB (max ${Math.round(this.options.maxFileSize/1024/1024)}MB)`);let J;try{J=await d4.readFile($,"utf-8")}catch(G){throw Error(`Cannot read file as text: ${Z}. It may be a binary file.`)}return this.fileCache.set($,{content:J,timestamp:Date.now()}),this.formatFileAttachment(Z,J,X)}formatFileAttachment($,Z,X){let Y=Z.split(`
|
|
869
869
|
`),Q=Z,J=!1,G=X;if(X){let q=Math.max(0,X.start-1),K=X.end?X.end:X.start;if(q>=Y.length)throw Error(`Line range start (${X.start}) exceeds file length (${Y.length} lines)`);let W=Math.min(K,Y.length);Q=Y.slice(q,W).join(`
|
|
870
870
|
`);let U=Array.from({length:W-q},(F,O)=>q+O+1);Q=Q.split(`
|
|
871
871
|
`).map((F,O)=>`${U[O]}: ${F}`).join(`
|
|
@@ -875,7 +875,7 @@ ${X}
|
|
|
875
875
|
[... truncated ${Y.length-this.options.maxLines} lines ...]`,J=!0;return{type:"file",path:$,content:Q,metadata:{size:Z.length,lines:Y.length,truncated:J,lineRange:G}}}async renderDirectoryTree($,Z){let X=await BQ("**/*",{cwd:$,dot:!1,followSymbolicLinks:!1,onlyFiles:!0,unique:!0,ignore:["node_modules/**",".git/**","dist/**","build/**",".next/**",".cache/**","coverage/**"]});if(X.length===0)return{type:"directory",path:Z,content:"(empty directory)"};M1.debug(`Found ${X.length} files in directory: ${Z}`);let Y=this.buildFileTree(X),Q=this.printTree(Y,Z),J=500,G=X.length>J?`
|
|
876
876
|
|
|
877
877
|
[... and ${X.length-J} more files]`:"";return{type:"directory",path:Z,content:Q+G,metadata:{lines:X.length,truncated:X.length>J}}}buildFileTree($){let Z=new Map;for(let X of $){let Y=X.split("/"),Q=Z;for(let J=0;J<Y.length;J++){let G=Y[J],q=J===Y.length-1;if(!Q.has(G))Q.set(G,q?null:new Map);if(!q){let K=Q.get(G);if(K&&Y6(K))Q=K}}}return Z}printTree($,Z,X="",Y=!0){let Q=[];if(X==="")Q.push(`${Z}/`);let J=Array.from($.entries()).sort((G,q)=>{let K=Y6(G[1]),W=Y6(q[1]);if(K!==W)return W?1:-1;return G[0].localeCompare(q[0])});return J.forEach(([G,q],K)=>{let W=K===J.length-1,U=W?"└── ":"├── ",H=Y6(q);if(Q.push(`${X}${U}${G}${H?"/":""}`),H&&q.size>0){let F=X+(W?" ":"│ ");Q.push(this.printTree(q,"",F,W))}}),Q.filter((G)=>G).join(`
|
|
878
|
-
`)}async processGlob($){let Z=await BQ($,{cwd:this.options.cwd,dot:!1,followSymbolicLinks:!1,onlyFiles:!0,unique:!0,ignore:["node_modules/**",".git/**","dist/**","build/**",".next/**",".cache/**","coverage/**"]});if(Z.length===0)return{type:"error",path:$,content:"",error:`No files matched pattern: ${$}`};M1.debug(`Glob pattern "${$}" matched ${Z.length} files`);let X=30,Y=Z.slice(0,X),J=(await Promise.allSettled(Y.map(async(W)=>{let U=LQ.join(this.options.cwd,W);try{let H=await
|
|
878
|
+
`)}async processGlob($){let Z=await BQ($,{cwd:this.options.cwd,dot:!1,followSymbolicLinks:!1,onlyFiles:!0,unique:!0,ignore:["node_modules/**",".git/**","dist/**","build/**",".next/**",".cache/**","coverage/**"]});if(Z.length===0)return{type:"error",path:$,content:"",error:`No files matched pattern: ${$}`};M1.debug(`Glob pattern "${$}" matched ${Z.length} files`);let X=30,Y=Z.slice(0,X),J=(await Promise.allSettled(Y.map(async(W)=>{let U=LQ.join(this.options.cwd,W);try{let H=await d4.readFile(U,"utf-8"),F=H.split(`
|
|
879
879
|
`),O=200,z=H,_=!1;if(F.length>200)z=F.slice(0,200).join(`
|
|
880
880
|
`),z+=`
|
|
881
881
|
|
|
@@ -884,7 +884,7 @@ ${W.content}`).join(`
|
|
|
884
884
|
|
|
885
885
|
`),K=Z.length>X?`
|
|
886
886
|
|
|
887
|
-
[... and ${Z.length-X} more files matched]`:"";return{type:"file",path:$,content:q+K,metadata:{lines:J.reduce((W,U)=>W+U.lines,0),truncated:Z.length>X||J.some((W)=>W.truncated)}}}clearExpiredCache(){let $=Date.now(),Z=0;for(let[X,Y]of this.fileCache.entries())if($-Y.timestamp>60000)this.fileCache.delete(X),Z++;if(Z>0)M1.debug(`Cleared ${Z} expired cache entries`)}clearCache(){this.fileCache.clear(),M1.debug("Cleared all cache")}getCacheStats(){return{size:this.fileCache.size,keys:Array.from(this.fileCache.keys())}}}var M1;var wQ=A(()=>{B0();zQ();_Q();M1=i("Prompts")});import{nanoid as qO}from"nanoid";class d0{static instance=null;fileManager=null;constructor(){}static getInstance(){if(!d0.instance)d0.instance=new d0;return d0.instance}static resetInstance(){d0.instance=null}getStoreState(){return
|
|
887
|
+
[... and ${Z.length-X} more files matched]`:"";return{type:"file",path:$,content:q+K,metadata:{lines:J.reduce((W,U)=>W+U.lines,0),truncated:Z.length>X||J.some((W)=>W.truncated)}}}clearExpiredCache(){let $=Date.now(),Z=0;for(let[X,Y]of this.fileCache.entries())if($-Y.timestamp>60000)this.fileCache.delete(X),Z++;if(Z>0)M1.debug(`Cleared ${Z} expired cache entries`)}clearCache(){this.fileCache.clear(),M1.debug("Cleared all cache")}getCacheStats(){return{size:this.fileCache.size,keys:Array.from(this.fileCache.keys())}}}var M1;var wQ=A(()=>{B0();zQ();_Q();M1=i("Prompts")});import{nanoid as qO}from"nanoid";class d0{static instance=null;fileManager=null;constructor(){}static getInstance(){if(!d0.instance)d0.instance=new d0;return d0.instance}static resetInstance(){d0.instance=null}getStoreState(){return E4.getState().spec}updateStoreState($){E4.setState((Z)=>({spec:{...Z.spec,...$}}))}async initialize($){if(this.fileManager){Q6.debug("SpecManager already initialized, skipping...");return}this.fileManager=new o2($),await this.fileManager.initializeDirectories();let Z=await this.fileManager.readSteeringContext();this.updateStoreState({steeringContext:Z}),Q6.debug("SpecManager initialized successfully")}getFileManager(){if(!this.fileManager)throw Error("SpecManager not initialized. Call initialize() first.");return this.fileManager}getState(){return{...this.getStoreState()}}getCurrentSpec(){return this.getStoreState().currentSpec}isActive(){return this.getStoreState().isActive}getSteeringContext(){return this.getStoreState().steeringContext}async getSteeringContextString(){let $=this.getStoreState().steeringContext;if(!$)return null;let Z=[];if($.constitution)Z.push(`## Constitution (Project Governance)
|
|
888
888
|
|
|
889
889
|
${$.constitution}`);if($.product)Z.push(`## Product Vision
|
|
890
890
|
|
|
@@ -930,7 +930,7 @@ ${Z}
|
|
|
930
930
|
<!-- What needs to be clarified before proceeding? -->
|
|
931
931
|
|
|
932
932
|
1.
|
|
933
|
-
`}calculateTaskProgress($){let Z=$.length,X=$.filter((Y)=>Y.status==="completed").length;return{total:Z,completed:X}}}var Q6;var U1=A(()=>{U$();B0();C0();C9();b1();Q6=i("Spec")});import*as j1 from"fs/promises";class A4{async readTextFile($){return j1.readFile($,"utf-8")}async writeTextFile($,Z){await j1.writeFile($,Z,"utf-8")}async exists($){try{return await j1.access($),!0}catch{return!1}}async readBinaryFile($){return j1.readFile($)}async stat($){try{let Z=await j1.stat($);return{size:Z.size,isDirectory:Z.isDirectory(),isFile:Z.isFile(),mtime:Z.mtime}}catch{return null}}async mkdir($,Z){await j1.mkdir($,{recursive:Z?.recursive??!1})}}function m2(){return k7}function J6($){k7=$}function NQ(){k7=new A4}var k7;var u2=A(()=>{k7=new A4});class f7{connection;sessionId;capabilities;fallback;constructor($,Z,X,Y=new A4){this.connection=$;this.sessionId=Z;this.capabilities=X;this.fallback=Y}async readTextFile($){if(!this.capabilities.readTextFile)return e$.debug(`[AcpFileSystem] readTextFile fallback: ${$}`),this.fallback.readTextFile($);try{return e$.debug(`[AcpFileSystem] readTextFile via ACP: ${$}`),(await this.connection.readTextFile({path:$,sessionId:this.sessionId})).content}catch(Z){return e$.warn(`[AcpFileSystem] readTextFile ACP failed, fallback: ${Z}`),this.fallback.readTextFile($)}}async writeTextFile($,Z){if(!this.capabilities.writeTextFile)return e$.debug(`[AcpFileSystem] writeTextFile fallback: ${$}`),this.fallback.writeTextFile($,Z);try{e$.debug(`[AcpFileSystem] writeTextFile via ACP: ${$}`),await this.connection.writeTextFile({path:$,content:Z,sessionId:this.sessionId})}catch(X){return e$.warn(`[AcpFileSystem] writeTextFile ACP failed, fallback: ${X}`),this.fallback.writeTextFile($,Z)}}async exists($){if(!this.capabilities.readTextFile)return e$.debug(`[AcpFileSystem] exists fallback to local: ${$}`),this.fallback.exists($);try{return await this.connection.readTextFile({path:$,sessionId:this.sessionId}),e$.debug(`[AcpFileSystem] exists(${$}): true (ACP read success)`),!0}catch(Z){let X=String(Z).toLowerCase();if(["not found","no such file","enoent","does not exist","file not found","path not found"].some((G)=>X.includes(G)))return e$.debug(`[AcpFileSystem] exists(${$}): false (ACP: not found)`),!1;let J=KO(X);return e$.warn(`[AcpFileSystem] exists(${$}): assuming exists due to ${J} error`,{error:String(Z),errorType:J,filePath:$}),!0}}async readBinaryFile($){return e$.debug(`[AcpFileSystem] readBinaryFile fallback: ${$}`),this.fallback.readBinaryFile($)}async stat($){return e$.debug(`[AcpFileSystem] stat fallback: ${$}`),this.fallback.stat($)}async mkdir($,Z){return e$.debug(`[AcpFileSystem] mkdir fallback: ${$}`),this.fallback.mkdir($,Z)}getCapabilities(){return this.capabilities}canReadTextFile(){return this.capabilities.readTextFile??!1}canWriteTextFile(){return this.capabilities.writeTextFile??!1}}function KO($){if($.includes("permission")||$.includes("access denied"))return"permission";if($.includes("timeout")||$.includes("timed out"))return"timeout";if($.includes("binary")||$.includes("encoding"))return"binary";if($.includes("too large")||$.includes("size"))return"size";if($.includes("connection")||$.includes("network"))return"network";return"unknown"}var e$;var bQ=A(()=>{B0();u2();e$=i("Agent")});import{spawn as WO}from"child_process";class h7{async execute($,Z){return new Promise((X)=>{let Y=process.platform==="win32"?"cmd.exe":"/bin/bash",Q=process.platform==="win32"?["/c",$]:["-c",$],J=WO(Y,Q,{cwd:Z?.cwd||process.cwd(),env:{...process.env,...Z?.env},stdio:["pipe","pipe","pipe"]}),G="",q="",K=!1,W=Z?.timeout?setTimeout(()=>{K=!0,J.kill("SIGTERM")},Z.timeout):null,U=null,H=()=>{if(W)clearTimeout(W);if(U&&Z?.signal)Z.signal.removeEventListener("abort",U),U=null};if(Z?.signal)U=()=>{K=!0,J.kill("SIGTERM")},Z.signal.addEventListener("abort",U);J.stdout.on("data",(F)=>{let O=F.toString();G+=O,Z?.onOutput?.(O)}),J.stderr.on("data",(F)=>{let O=F.toString();q+=O,Z?.onOutput?.(O)}),J.on("close",(F)=>{H(),X({success:F===0&&!K,stdout:G,stderr:q,exitCode:F,error:K?"Command was terminated":void 0})}),J.on("error",(F)=>{H(),X({success:!1,stdout:G,stderr:q,exitCode:null,error:F.message})})})}isAvailable(){return!0}}class AQ{connection;sessionId;fallback;constructor($,Z,X=new h7){this.connection=$;this.sessionId=Z;this.fallback=X}async execute($,Z){try{h1.debug(`[AcpTerminal] Executing command via ACP: ${$}`);let X=await this.connection.createTerminal({sessionId:this.sessionId,command:$,cwd:Z?.cwd,env:Z?.env?Object.entries(Z.env).map(([W,U])=>({name:W,value:U})):void 0}),Y=0,Q=null;if(Z?.onOutput)Q=setInterval(async()=>{try{let U=(await X.currentOutput()).output||"";if(U.length>Y){let H=U.slice(Y);Y=U.length,Z.onOutput?.(H)}}catch{}},100);let J=(W=!1)=>{if(Q)clearInterval(Q),Q=null;(W?X.kill().then(()=>h1.debug("[AcpTerminal] Killed remote command")).catch(()=>{}).then(()=>X.release()).catch(()=>{}):X.release().catch(()=>{})).catch(()=>{})},G=[];if(G.push(X.waitForExit().then((W)=>({type:"completed",exitCode:W.exitCode??null}))),Z?.timeout)G.push(new Promise((W)=>{setTimeout(()=>W({type:"timeout"}),Z.timeout)}));if(Z?.signal)G.push(new Promise((W)=>{if(Z.signal.aborted)W({type:"aborted"});else Z.signal.addEventListener("abort",()=>W({type:"aborted"}),{once:!0})}));let q=await Promise.race(G),K="";try{if(K=(await X.currentOutput()).output||"",Z?.onOutput&&K.length>Y)Z.onOutput(K.slice(Y))}catch{}switch(q.type){case"completed":return J(!1),{success:q.exitCode===0,stdout:K,stderr:"",exitCode:q.exitCode};case"timeout":return h1.debug(`[AcpTerminal] Command timed out, killing: ${$}`),J(!0),{success:!1,stdout:K,stderr:"",exitCode:null,error:"Command timed out"};case"aborted":return h1.debug(`[AcpTerminal] Command aborted, killing: ${$}`),J(!0),{success:!1,stdout:K,stderr:"",exitCode:null,error:"Command was aborted"}}}catch(X){return h1.warn("[AcpTerminal] ACP terminal failed, using fallback:",X),this.fallback.execute($,Z)}}isAvailable(){return!0}}function RQ(){return O0.getInstance().getTerminalService()}function R4(){return O0.getInstance().isAcpMode()}var h1,O0;var g2=A(()=>{B0();u2();bQ();h1=i("Agent");O0=class O0{static sessions=new Map;static currentSessionId=null;constructor(){}static getInstance(){return new O0}static initializeSession($,Z,X,Y){let Q=X?.fs?new f7($,Z,X.fs):new A4;if(X?.fs)h1.debug(`[AcpServiceContext:${Z}] Using ACP file system service`);let J=new AQ($,Z);h1.debug(`[AcpServiceContext:${Z}] Using ACP terminal service`),O0.sessions.set(Z,{fileSystemService:Q,terminalService:J,connection:$,clientCapabilities:X||null,cwd:Y}),O0.currentSessionId=Z,J6(Q),h1.debug(`[AcpServiceContext:${Z}] Initialized with capabilities:`,{fs:!!X?.fs,readTextFile:X?.fs?.readTextFile,writeTextFile:X?.fs?.writeTextFile,cwd:Y})}static destroySession($){if(O0.sessions.delete($),O0.currentSessionId===$){let Z=Array.from(O0.sessions.keys());if(O0.currentSessionId=Z[0]||null,!O0.currentSessionId)NQ();else{let X=O0.sessions.get(O0.currentSessionId);if(X)J6(X.fileSystemService)}}h1.debug(`[AcpServiceContext:${$}] Session destroyed`)}static getSessionServices($){return O0.sessions.get($)||null}static setCurrentSession($){if(O0.sessions.has($)){O0.currentSessionId=$;let Z=O0.sessions.get($);if(Z)J6(Z.fileSystemService)}}static getCurrentSessionId(){return O0.currentSessionId}initialize($,Z,X,Y){O0.initializeSession($,Z,X,Y||process.cwd())}reset(){if(O0.currentSessionId)O0.destroySession(O0.currentSessionId)}isAcpMode(){return O0.currentSessionId!==null}getFileSystemService(){if(O0.currentSessionId){let $=O0.sessions.get(O0.currentSessionId);if($)return $.fileSystemService}return new A4}getTerminalService(){if(O0.currentSessionId){let $=O0.sessions.get(O0.currentSessionId);if($)return $.terminalService}return new h7}getConnection(){if(O0.currentSessionId){let $=O0.sessions.get(O0.currentSessionId);if($)return $.connection}return null}getSessionId(){return O0.currentSessionId}getClientCapabilities(){if(O0.currentSessionId){let $=O0.sessions.get(O0.currentSessionId);if($)return $.clientCapabilities}return null}async sendToolUpdate($,Z,X,Y,Q){let J=O0.currentSessionId;if(!J)return;let G=O0.sessions.get(J);if(!G)return;try{await G.connection.sessionUpdate({sessionId:J,update:{sessionUpdate:"tool_call",toolCallId:$,status:Z,title:X,content:Y||[],kind:Q||"other"}})}catch(q){h1.warn("[AcpServiceContext] Failed to send tool update:",q)}}}});import{isAbsolute as VQ}from"path";import{z as A$}from"zod";var r0;var V4=A(()=>{r0={filePath:($)=>A$.string().min(1,"File path is required").refine((Z)=>VQ(Z),{message:"Path must be absolute"}).describe($?.description||"Absolute file path"),encoding:()=>A$.enum(["utf8","base64","binary"]).default("utf8").describe("File encoding"),timeout:($=1000,Z=300000,X=30000)=>A$.number().int("Must be an integer").min($,`Cannot be less than ${$}ms`).max(Z,`Cannot exceed ${Z}ms`).default(X).describe(`Timeout in milliseconds (default ${X}ms)`),pattern:($)=>A$.string().min(1,"Pattern is required").describe($?.description||"Regex or glob pattern"),glob:($)=>A$.string().min(1,"Glob pattern is required").describe($?.description||'Glob pattern (e.g., "*.js", "**/*.ts")'),lineNumber:($)=>A$.number().int("Line number must be an integer").min($?.min??0,`Line number cannot be less than ${$?.min??0}`).describe($?.description||"Line number"),lineLimit:($)=>A$.number().int("Line count must be an integer").min($?.min??1,`Line count cannot be less than ${$?.min??1}`).max($?.max??1e4,`Line count cannot exceed ${$?.max??1e4}`).describe($?.description||"Limit on lines to read"),workingDirectory:()=>A$.string().min(1,"Working directory is required").refine(($)=>VQ($),{message:"Path must be absolute"}).describe("Absolute working directory"),environment:()=>A$.record(A$.string(),A$.string()).describe("Environment variables (key-value)").optional(),outputMode:($,Z)=>{let X=A$.enum($);return Z?X.default(Z):X},flag:($)=>A$.boolean().default($?.defaultValue??!1).describe($?.description||"Boolean flag"),url:($)=>A$.string().url("Must be a valid URL").describe($?.description||"URL"),port:()=>A$.number().int("Port must be an integer").min(1,"Port cannot be less than 1").max(65535,"Port cannot exceed 65535").describe("Port number"),command:($)=>A$.string().min(1,"Command is required").describe($?.description||"Command to execute"),sessionId:()=>A$.string().min(1,"Session ID is required").uuid("Must be a valid UUID").optional().describe("Session identifier (UUID)"),nonNegativeInt:($)=>A$.number().int("Must be an integer").min(0,"Cannot be negative").describe($?.description||"Non-negative integer"),positiveInt:($)=>A$.number().int("Must be an integer").min(1,"Must be greater than 0").describe($?.description||"Positive integer")}});import*as x7 from"diff";function DQ($,Z,X=4){if($===Z)return null;let Y=x7.createPatch("file",$,Z,"","",{context:X}),Q=Y.split(`
|
|
933
|
+
`}calculateTaskProgress($){let Z=$.length,X=$.filter((Y)=>Y.status==="completed").length;return{total:Z,completed:X}}}var Q6;var U1=A(()=>{U$();B0();C0();C9();b1();Q6=i("Spec")});import*as j1 from"fs/promises";class A2{async readTextFile($){return j1.readFile($,"utf-8")}async writeTextFile($,Z){await j1.writeFile($,Z,"utf-8")}async exists($){try{return await j1.access($),!0}catch{return!1}}async readBinaryFile($){return j1.readFile($)}async stat($){try{let Z=await j1.stat($);return{size:Z.size,isDirectory:Z.isDirectory(),isFile:Z.isFile(),mtime:Z.mtime}}catch{return null}}async mkdir($,Z){await j1.mkdir($,{recursive:Z?.recursive??!1})}}function m4(){return k7}function J6($){k7=$}function NQ(){k7=new A2}var k7;var u4=A(()=>{k7=new A2});class f7{connection;sessionId;capabilities;fallback;constructor($,Z,X,Y=new A2){this.connection=$;this.sessionId=Z;this.capabilities=X;this.fallback=Y}async readTextFile($){if(!this.capabilities.readTextFile)return e$.debug(`[AcpFileSystem] readTextFile fallback: ${$}`),this.fallback.readTextFile($);try{return e$.debug(`[AcpFileSystem] readTextFile via ACP: ${$}`),(await this.connection.readTextFile({path:$,sessionId:this.sessionId})).content}catch(Z){return e$.warn(`[AcpFileSystem] readTextFile ACP failed, fallback: ${Z}`),this.fallback.readTextFile($)}}async writeTextFile($,Z){if(!this.capabilities.writeTextFile)return e$.debug(`[AcpFileSystem] writeTextFile fallback: ${$}`),this.fallback.writeTextFile($,Z);try{e$.debug(`[AcpFileSystem] writeTextFile via ACP: ${$}`),await this.connection.writeTextFile({path:$,content:Z,sessionId:this.sessionId})}catch(X){return e$.warn(`[AcpFileSystem] writeTextFile ACP failed, fallback: ${X}`),this.fallback.writeTextFile($,Z)}}async exists($){if(!this.capabilities.readTextFile)return e$.debug(`[AcpFileSystem] exists fallback to local: ${$}`),this.fallback.exists($);try{return await this.connection.readTextFile({path:$,sessionId:this.sessionId}),e$.debug(`[AcpFileSystem] exists(${$}): true (ACP read success)`),!0}catch(Z){let X=String(Z).toLowerCase();if(["not found","no such file","enoent","does not exist","file not found","path not found"].some((G)=>X.includes(G)))return e$.debug(`[AcpFileSystem] exists(${$}): false (ACP: not found)`),!1;let J=KO(X);return e$.warn(`[AcpFileSystem] exists(${$}): assuming exists due to ${J} error`,{error:String(Z),errorType:J,filePath:$}),!0}}async readBinaryFile($){return e$.debug(`[AcpFileSystem] readBinaryFile fallback: ${$}`),this.fallback.readBinaryFile($)}async stat($){return e$.debug(`[AcpFileSystem] stat fallback: ${$}`),this.fallback.stat($)}async mkdir($,Z){return e$.debug(`[AcpFileSystem] mkdir fallback: ${$}`),this.fallback.mkdir($,Z)}getCapabilities(){return this.capabilities}canReadTextFile(){return this.capabilities.readTextFile??!1}canWriteTextFile(){return this.capabilities.writeTextFile??!1}}function KO($){if($.includes("permission")||$.includes("access denied"))return"permission";if($.includes("timeout")||$.includes("timed out"))return"timeout";if($.includes("binary")||$.includes("encoding"))return"binary";if($.includes("too large")||$.includes("size"))return"size";if($.includes("connection")||$.includes("network"))return"network";return"unknown"}var e$;var bQ=A(()=>{B0();u4();e$=i("Agent")});import{spawn as WO}from"child_process";class h7{async execute($,Z){return new Promise((X)=>{let Y=process.platform==="win32"?"cmd.exe":"/bin/bash",Q=process.platform==="win32"?["/c",$]:["-c",$],J=WO(Y,Q,{cwd:Z?.cwd||process.cwd(),env:{...process.env,...Z?.env},stdio:["pipe","pipe","pipe"]}),G="",q="",K=!1,W=Z?.timeout?setTimeout(()=>{K=!0,J.kill("SIGTERM")},Z.timeout):null,U=null,H=()=>{if(W)clearTimeout(W);if(U&&Z?.signal)Z.signal.removeEventListener("abort",U),U=null};if(Z?.signal)U=()=>{K=!0,J.kill("SIGTERM")},Z.signal.addEventListener("abort",U);J.stdout.on("data",(F)=>{let O=F.toString();G+=O,Z?.onOutput?.(O)}),J.stderr.on("data",(F)=>{let O=F.toString();q+=O,Z?.onOutput?.(O)}),J.on("close",(F)=>{H(),X({success:F===0&&!K,stdout:G,stderr:q,exitCode:F,error:K?"Command was terminated":void 0})}),J.on("error",(F)=>{H(),X({success:!1,stdout:G,stderr:q,exitCode:null,error:F.message})})})}isAvailable(){return!0}}class AQ{connection;sessionId;fallback;constructor($,Z,X=new h7){this.connection=$;this.sessionId=Z;this.fallback=X}async execute($,Z){try{h1.debug(`[AcpTerminal] Executing command via ACP: ${$}`);let X=await this.connection.createTerminal({sessionId:this.sessionId,command:$,cwd:Z?.cwd,env:Z?.env?Object.entries(Z.env).map(([W,U])=>({name:W,value:U})):void 0}),Y=0,Q=null;if(Z?.onOutput)Q=setInterval(async()=>{try{let U=(await X.currentOutput()).output||"";if(U.length>Y){let H=U.slice(Y);Y=U.length,Z.onOutput?.(H)}}catch{}},100);let J=(W=!1)=>{if(Q)clearInterval(Q),Q=null;(W?X.kill().then(()=>h1.debug("[AcpTerminal] Killed remote command")).catch(()=>{}).then(()=>X.release()).catch(()=>{}):X.release().catch(()=>{})).catch(()=>{})},G=[];if(G.push(X.waitForExit().then((W)=>({type:"completed",exitCode:W.exitCode??null}))),Z?.timeout)G.push(new Promise((W)=>{setTimeout(()=>W({type:"timeout"}),Z.timeout)}));if(Z?.signal)G.push(new Promise((W)=>{if(Z.signal.aborted)W({type:"aborted"});else Z.signal.addEventListener("abort",()=>W({type:"aborted"}),{once:!0})}));let q=await Promise.race(G),K="";try{if(K=(await X.currentOutput()).output||"",Z?.onOutput&&K.length>Y)Z.onOutput(K.slice(Y))}catch{}switch(q.type){case"completed":return J(!1),{success:q.exitCode===0,stdout:K,stderr:"",exitCode:q.exitCode};case"timeout":return h1.debug(`[AcpTerminal] Command timed out, killing: ${$}`),J(!0),{success:!1,stdout:K,stderr:"",exitCode:null,error:"Command timed out"};case"aborted":return h1.debug(`[AcpTerminal] Command aborted, killing: ${$}`),J(!0),{success:!1,stdout:K,stderr:"",exitCode:null,error:"Command was aborted"}}}catch(X){return h1.warn("[AcpTerminal] ACP terminal failed, using fallback:",X),this.fallback.execute($,Z)}}isAvailable(){return!0}}function RQ(){return O0.getInstance().getTerminalService()}function R2(){return O0.getInstance().isAcpMode()}var h1,O0;var g4=A(()=>{B0();u4();bQ();h1=i("Agent");O0=class O0{static sessions=new Map;static currentSessionId=null;constructor(){}static getInstance(){return new O0}static initializeSession($,Z,X,Y){let Q=X?.fs?new f7($,Z,X.fs):new A2;if(X?.fs)h1.debug(`[AcpServiceContext:${Z}] Using ACP file system service`);let J=new AQ($,Z);h1.debug(`[AcpServiceContext:${Z}] Using ACP terminal service`),O0.sessions.set(Z,{fileSystemService:Q,terminalService:J,connection:$,clientCapabilities:X||null,cwd:Y}),O0.currentSessionId=Z,J6(Q),h1.debug(`[AcpServiceContext:${Z}] Initialized with capabilities:`,{fs:!!X?.fs,readTextFile:X?.fs?.readTextFile,writeTextFile:X?.fs?.writeTextFile,cwd:Y})}static destroySession($){if(O0.sessions.delete($),O0.currentSessionId===$){let Z=Array.from(O0.sessions.keys());if(O0.currentSessionId=Z[0]||null,!O0.currentSessionId)NQ();else{let X=O0.sessions.get(O0.currentSessionId);if(X)J6(X.fileSystemService)}}h1.debug(`[AcpServiceContext:${$}] Session destroyed`)}static getSessionServices($){return O0.sessions.get($)||null}static setCurrentSession($){if(O0.sessions.has($)){O0.currentSessionId=$;let Z=O0.sessions.get($);if(Z)J6(Z.fileSystemService)}}static getCurrentSessionId(){return O0.currentSessionId}initialize($,Z,X,Y){O0.initializeSession($,Z,X,Y||process.cwd())}reset(){if(O0.currentSessionId)O0.destroySession(O0.currentSessionId)}isAcpMode(){return O0.currentSessionId!==null}getFileSystemService(){if(O0.currentSessionId){let $=O0.sessions.get(O0.currentSessionId);if($)return $.fileSystemService}return new A2}getTerminalService(){if(O0.currentSessionId){let $=O0.sessions.get(O0.currentSessionId);if($)return $.terminalService}return new h7}getConnection(){if(O0.currentSessionId){let $=O0.sessions.get(O0.currentSessionId);if($)return $.connection}return null}getSessionId(){return O0.currentSessionId}getClientCapabilities(){if(O0.currentSessionId){let $=O0.sessions.get(O0.currentSessionId);if($)return $.clientCapabilities}return null}async sendToolUpdate($,Z,X,Y,Q){let J=O0.currentSessionId;if(!J)return;let G=O0.sessions.get(J);if(!G)return;try{await G.connection.sessionUpdate({sessionId:J,update:{sessionUpdate:"tool_call",toolCallId:$,status:Z,title:X,content:Y||[],kind:Q||"other"}})}catch(q){h1.warn("[AcpServiceContext] Failed to send tool update:",q)}}}});import{isAbsolute as VQ}from"path";import{z as A$}from"zod";var r0;var V2=A(()=>{r0={filePath:($)=>A$.string().min(1,"File path is required").refine((Z)=>VQ(Z),{message:"Path must be absolute"}).describe($?.description||"Absolute file path"),encoding:()=>A$.enum(["utf8","base64","binary"]).default("utf8").describe("File encoding"),timeout:($=1000,Z=300000,X=30000)=>A$.number().int("Must be an integer").min($,`Cannot be less than ${$}ms`).max(Z,`Cannot exceed ${Z}ms`).default(X).describe(`Timeout in milliseconds (default ${X}ms)`),pattern:($)=>A$.string().min(1,"Pattern is required").describe($?.description||"Regex or glob pattern"),glob:($)=>A$.string().min(1,"Glob pattern is required").describe($?.description||'Glob pattern (e.g., "*.js", "**/*.ts")'),lineNumber:($)=>A$.number().int("Line number must be an integer").min($?.min??0,`Line number cannot be less than ${$?.min??0}`).describe($?.description||"Line number"),lineLimit:($)=>A$.number().int("Line count must be an integer").min($?.min??1,`Line count cannot be less than ${$?.min??1}`).max($?.max??1e4,`Line count cannot exceed ${$?.max??1e4}`).describe($?.description||"Limit on lines to read"),workingDirectory:()=>A$.string().min(1,"Working directory is required").refine(($)=>VQ($),{message:"Path must be absolute"}).describe("Absolute working directory"),environment:()=>A$.record(A$.string(),A$.string()).describe("Environment variables (key-value)").optional(),outputMode:($,Z)=>{let X=A$.enum($);return Z?X.default(Z):X},flag:($)=>A$.boolean().default($?.defaultValue??!1).describe($?.description||"Boolean flag"),url:($)=>A$.string().url("Must be a valid URL").describe($?.description||"URL"),port:()=>A$.number().int("Port must be an integer").min(1,"Port cannot be less than 1").max(65535,"Port cannot exceed 65535").describe("Port number"),command:($)=>A$.string().min(1,"Command is required").describe($?.description||"Command to execute"),sessionId:()=>A$.string().min(1,"Session ID is required").uuid("Must be a valid UUID").optional().describe("Session identifier (UUID)"),nonNegativeInt:($)=>A$.number().int("Must be an integer").min(0,"Cannot be negative").describe($?.description||"Non-negative integer"),positiveInt:($)=>A$.number().int("Must be an integer").min(1,"Must be greater than 0").describe($?.description||"Positive integer")}});import*as x7 from"diff";function DQ($,Z,X=4){if($===Z)return null;let Y=x7.createPatch("file",$,Z,"","",{context:X}),Q=Y.split(`
|
|
934
934
|
`),J=1;for(let G of Q){let q=G.match(/@@ -(\d+),?(\d*) \+(\d+),?(\d*) @@/);if(q){J=parseInt(q[1],10);break}}return`
|
|
935
935
|
<<<DIFF>>>
|
|
936
936
|
${JSON.stringify({patch:Y,startLine:Math.max(1,J-X),matchLine:J})}
|
|
@@ -954,7 +954,7 @@ ${JSON.stringify({patch:L,startLine:F+1,matchLine:q+1})}
|
|
|
954
954
|
`),K=$.split(`
|
|
955
955
|
`);for(let W=0;W<=K.length-X.length;W++){let U=K[W].match(/^(\s+)/),H=U?U[1]:"",F=K.slice(W,W+X.length);if(F.map((_)=>{if(_.startsWith(H))return _.slice(H.length);return _}).join(`
|
|
956
956
|
`)===q)return F.join(`
|
|
957
|
-
`)}return null}var yQ=()=>{};import{promises as G6}from"node:fs";class n${static instance=null;accessedFiles=new Map;constructor(){}static getInstance(){if(!n$.instance)n$.instance=new n$;return n$.instance}async recordFileRead($,Z){try{let X=await G6.stat($),Y={filePath:$,accessTime:Date.now(),mtime:X.mtimeMs,sessionId:Z,lastOperation:"read"};this.accessedFiles.set($,Y),t8.debug(`记录文件读取: ${$}`)}catch(X){t8.warn(`记录文件读取失败: ${$}`,X)}}async recordFileEdit($,Z,X="edit"){try{let Y=await G6.stat($),Q={filePath:$,accessTime:Date.now(),mtime:Y.mtimeMs,sessionId:Z,lastOperation:X};this.accessedFiles.set($,Q),t8.debug(`记录文件${X==="edit"?"编辑":"写入"}: ${$}`)}catch(Y){t8.warn(`记录文件${X==="edit"?"编辑":"写入"}失败: ${$}`,Y)}}hasFileBeenRead($,Z){let X=this.accessedFiles.get($);if(!X)return!1;if(Z&&X.sessionId!==Z)return!1;return!0}async checkFileModification($){let Z=this.accessedFiles.get($);if(!Z)return{modified:!1,message:"文件未被跟踪"};try{let X=await G6.stat($);if(Math.abs(X.mtimeMs-Z.mtime)>1)return{modified:!0,message:`文件在访问后被修改(访问时间: ${new Date(Z.accessTime).toISOString()}, 当前修改时间: ${X.mtime.toISOString()})`};return{modified:!1}}catch(X){if(X.code==="ENOENT")return{modified:!0,message:"文件已被删除"};return{modified:!1,message:`无法检查文件状态: ${X.message}`}}}async checkExternalModification($){let Z=this.accessedFiles.get($);if(!Z)return{isExternal:!1,message:"文件未被跟踪"};try{let X=await G6.stat($);if(X.mtimeMs-Z.mtime>2000)return{isExternal:!0,message:`文件在 ${new Date(Z.accessTime).toISOString()} (${Z.lastOperation}) 之后被外部程序修改(当前修改时间: ${X.mtime.toISOString()})`};return{isExternal:!1}}catch(X){if(X.code==="ENOENT")return{isExternal:!0,message:"文件已被删除"};return t8.warn(`检查文件外部修改失败: ${$}`,X),{isExternal:!1,message:`无法检查文件状态: ${X.message}`}}}getFileRecord($){return this.accessedFiles.get($)}clearFileRecord($){this.accessedFiles.delete($)}clearAll(){this.accessedFiles.clear()}clearSession($){for(let[Z,X]of this.accessedFiles.entries())if(X.sessionId===$)this.accessedFiles.delete(Z)}getTrackedFiles(){return Array.from(this.accessedFiles.keys())}getTrackedFileCount(){return this.accessedFiles.size}static resetInstance(){n$.instance=null}}var t8;var q6=A(()=>{B0();t8=i("Tool")});import{execSync as UO}from"node:child_process";import*as d7 from"node:os";import*as
|
|
957
|
+
`)}return null}var yQ=()=>{};import{promises as G6}from"node:fs";class n${static instance=null;accessedFiles=new Map;constructor(){}static getInstance(){if(!n$.instance)n$.instance=new n$;return n$.instance}async recordFileRead($,Z){try{let X=await G6.stat($),Y={filePath:$,accessTime:Date.now(),mtime:X.mtimeMs,sessionId:Z,lastOperation:"read"};this.accessedFiles.set($,Y),t8.debug(`记录文件读取: ${$}`)}catch(X){t8.warn(`记录文件读取失败: ${$}`,X)}}async recordFileEdit($,Z,X="edit"){try{let Y=await G6.stat($),Q={filePath:$,accessTime:Date.now(),mtime:Y.mtimeMs,sessionId:Z,lastOperation:X};this.accessedFiles.set($,Q),t8.debug(`记录文件${X==="edit"?"编辑":"写入"}: ${$}`)}catch(Y){t8.warn(`记录文件${X==="edit"?"编辑":"写入"}失败: ${$}`,Y)}}hasFileBeenRead($,Z){let X=this.accessedFiles.get($);if(!X)return!1;if(Z&&X.sessionId!==Z)return!1;return!0}async checkFileModification($){let Z=this.accessedFiles.get($);if(!Z)return{modified:!1,message:"文件未被跟踪"};try{let X=await G6.stat($);if(Math.abs(X.mtimeMs-Z.mtime)>1)return{modified:!0,message:`文件在访问后被修改(访问时间: ${new Date(Z.accessTime).toISOString()}, 当前修改时间: ${X.mtime.toISOString()})`};return{modified:!1}}catch(X){if(X.code==="ENOENT")return{modified:!0,message:"文件已被删除"};return{modified:!1,message:`无法检查文件状态: ${X.message}`}}}async checkExternalModification($){let Z=this.accessedFiles.get($);if(!Z)return{isExternal:!1,message:"文件未被跟踪"};try{let X=await G6.stat($);if(X.mtimeMs-Z.mtime>2000)return{isExternal:!0,message:`文件在 ${new Date(Z.accessTime).toISOString()} (${Z.lastOperation}) 之后被外部程序修改(当前修改时间: ${X.mtime.toISOString()})`};return{isExternal:!1}}catch(X){if(X.code==="ENOENT")return{isExternal:!0,message:"文件已被删除"};return t8.warn(`检查文件外部修改失败: ${$}`,X),{isExternal:!1,message:`无法检查文件状态: ${X.message}`}}}getFileRecord($){return this.accessedFiles.get($)}clearFileRecord($){this.accessedFiles.delete($)}clearAll(){this.accessedFiles.clear()}clearSession($){for(let[Z,X]of this.accessedFiles.entries())if(X.sessionId===$)this.accessedFiles.delete(Z)}getTrackedFiles(){return Array.from(this.accessedFiles.keys())}getTrackedFileCount(){return this.accessedFiles.size}static resetInstance(){n$.instance=null}}var t8;var q6=A(()=>{B0();t8=i("Tool")});import{execSync as UO}from"node:child_process";import*as d7 from"node:os";import*as Z4 from"node:path";function HO($){return Z4.resolve($).replace(/\//g,"-")}function vQ($){if($.startsWith("-"))return"/"+$.slice(1).replace(/-/g,"/");return $.replace(/-/g,"/")}function e8($){let Z=d7.homedir(),X=HO($);return Z4.join(Z,".blade","projects",X)}function H1($,Z){return Z4.join(e8($),`${Z}.jsonl`)}function c4($){try{return UO("git rev-parse --abbrev-ref HEAD",{cwd:$,encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim()||void 0}catch{return}}function X4(){return Z4.join(d7.homedir(),".blade")}async function EQ(){let{readdir:$}=await import("node:fs/promises");try{let Z=Z4.join(X4(),"projects");return(await $(Z,{withFileTypes:!0})).filter((Y)=>Y.isDirectory()).map((Y)=>Y.name)}catch{return[]}}var $3=()=>{};import*as PQ from"node:crypto";import{promises as x1}from"node:fs";import*as Y4 from"node:path";class Z3{sessionId;enableCheckpoints;maxSnapshots;snapshotDir;trackedFileBackups=new Map;snapshots=[];constructor($){this.sessionId=$.sessionId,this.enableCheckpoints=$.enableCheckpoints??!0,this.maxSnapshots=$.maxSnapshots??10;let Z=X4();this.snapshotDir=Y4.join(Z,"file-history",this.sessionId)}async initialize(){if(!this.enableCheckpoints)return;try{await x1.mkdir(this.snapshotDir,{recursive:!0}),console.log(`[SnapshotManager] 初始化快照目录: ${this.snapshotDir}`)}catch($){throw console.warn("[SnapshotManager] 创建快照目录失败:",$),$}}async createSnapshot($,Z){if(!this.enableCheckpoints)return console.log("[SnapshotManager] 检查点已禁用,跳过快照创建"),{backupFileName:"",version:0,backupTime:new Date};try{await x1.access($)}catch{return console.warn(`[SnapshotManager] 文件不存在,跳过快照: ${$}`),{backupFileName:"",version:0,backupTime:new Date}}let X=this.trackedFileBackups.get($),Y=X?X.version+1:1,Q=this.generateFileHash($,Y),J=Y4.join(this.snapshotDir,`${Q}@v${Y}`);try{let G=await x1.readFile($,{encoding:"utf-8"});await x1.writeFile(J,G,{encoding:"utf-8"});let q={backupFileName:Q,version:Y,backupTime:new Date};return this.trackedFileBackups.set($,q),this.snapshots.push({messageId:Z,backupFileName:Q,timestamp:new Date,filePath:$}),console.log(`[SnapshotManager] 创建快照: ${$} -> ${Q}@v${Y}`),await this.cleanupOldSnapshots($),q}catch(G){throw console.error(`[SnapshotManager] 创建快照失败: ${$}`,G),G}}async restoreSnapshot($,Z){let X=this.snapshots.slice().reverse().find((J)=>J.messageId===Z&&J.filePath===$);if(!X)throw Error(`未找到快照: messageId=${Z}, filePath=${$}`);let Y=this.trackedFileBackups.get($);if(!Y)throw Error(`未找到文件追踪信息: ${$}`);let Q=Y4.join(this.snapshotDir,`${X.backupFileName}@v${Y.version}`);try{let J=await x1.readFile(Q,{encoding:"utf-8"});await x1.writeFile($,J,{encoding:"utf-8"}),console.log(`[SnapshotManager] 恢复快照: ${$} <- ${X.backupFileName}@v${Y.version}`)}catch(J){throw console.error(`[SnapshotManager] 恢复快照失败: ${$}`,J),J}}async listSnapshots($){return this.snapshots.filter((Z)=>Z.filePath===$)}async cleanupOldSnapshots($){let Z=this.snapshots.filter((Q)=>Q.filePath===$);if(Z.length<=this.maxSnapshots)return;let Y=Z.sort((Q,J)=>Q.timestamp.getTime()-J.timestamp.getTime()).slice(0,Z.length-this.maxSnapshots);for(let Q of Y){let J=this.trackedFileBackups.get(Q.filePath);if(!J)continue;let G=Y4.join(this.snapshotDir,`${Q.backupFileName}@v${J.version}`);try{await x1.unlink(G),console.log(`[SnapshotManager] 删除旧快照: ${G}`)}catch(K){console.warn(`[SnapshotManager] 删除快照失败: ${G}`,K)}let q=this.snapshots.indexOf(Q);if(q>-1)this.snapshots.splice(q,1)}}async cleanup($=0){try{let Z=await x1.readdir(this.snapshotDir);if(Z.length<=$)return;let X=await Promise.all(Z.map(async(Q)=>{let J=Y4.join(this.snapshotDir,Q),G=await x1.stat(J);return{file:Q,mtime:G.mtime.getTime()}}));X.sort((Q,J)=>J.mtime-Q.mtime);let Y=X.slice($);for(let{file:Q}of Y){let J=Y4.join(this.snapshotDir,Q);await x1.unlink(J),console.log(`[SnapshotManager] 清理快照: ${J}`)}}catch(Z){console.warn("[SnapshotManager] 清理快照失败:",Z)}}generateFileHash($,Z){let X=PQ.createHash("md5");return X.update(`${$}:${Z}`),X.digest("hex").substring(0,16)}getSnapshotDir(){return this.snapshotDir}getSessionId(){return this.sessionId}getTrackedFileCount(){return this.trackedFileBackups.size}getSnapshotCount(){return this.snapshots.length}}var m7=A(()=>{$3()});import{extname as FO}from"path";import{z as K6}from"zod";function TQ($){return $.replaceAll("‘","'").replaceAll("’","'").replaceAll("“",'"').replaceAll("”",'"')}function OO($,Z){if($.includes(Z))return{matched:Z,strategy:"exact"};let X=TQ(Z),Q=TQ($).indexOf(X);if(Q!==-1)return{matched:$.substring(Q,Q+Z.length),strategy:"normalize_quotes"};let J=jQ(Z);if(J!==Z&&$.includes(J))return{matched:J,strategy:"unescape"};let G=IQ($,Z);if(G)return{matched:G,strategy:"flexible"};return{matched:null,strategy:"failed"}}function zO($,Z){if(Z.length===0)return[];let X=[],Y=$.indexOf(Z);while(Y!==-1)X.push(Y),Y=$.indexOf(Z,Y+Z.length);return X}function _O($,Z){let{file_path:X,matches_found:Y,replacements_made:Q,replace_all:J,size_diff:G}=$,q=`✅ 成功编辑文件: ${X}`;if(q+=`
|
|
958
958
|
\uD83D\uDCDD 替换了 ${Q} 个匹配项`,!J&&Y>1)q+=` (共找到 ${Y} 个匹配项)`;if(G!==0){let K=G>0?`增加${G}`:`减少${Math.abs(G)}`;q+=`
|
|
959
959
|
\uD83D\uDCCA 文件大小${K}个字符`}if(Z)q+=Z;return q}function BO($,Z,X){let Y=$.split(`
|
|
960
960
|
`),Q=Y.length,J=LO($,Z,3),G=0,q=Math.min(20,Q);if(J.length>0){let O=J[0];G=Math.max(0,O.lineNumber-10),q=Math.min(Q,O.lineNumber+10)}let W=Y.slice(G,q).map((O,z)=>{return` ${(G+z+1).toString().padStart(4)}: ${O}`}).join(`
|
|
@@ -1006,7 +1006,7 @@ ${W}
|
|
|
1006
1006
|
`,F+=" 3. 提供更多上下文代码确保唯一性",{llmContent:U,displayContent:F,metadata:{searchStringLength:Z.length,fuzzyMatches:J.map((O)=>({line:O.lineNumber,similarity:O.similarity,preview:O.text.substring(0,100)})),excerptRange:[G+1,q],totalLines:Q}}}function LO($,Z,X=3){let Y=$.split(`
|
|
1007
1007
|
`),Q=Z.split(`
|
|
1008
1008
|
`);if(Q.length===1)return Y.map((K,W)=>({text:K,lineNumber:W+1,similarity:SQ(Z.trim(),K.trim())})).filter((K)=>K.similarity>0.5).sort((K,W)=>W.similarity-K.similarity).slice(0,X);let J=Q.length,G=[];for(let q=0;q<=Y.length-J;q++){let K=Y.slice(q,q+J).join(`
|
|
1009
|
-
`),W=SQ(Z,K);if(W>0.5)G.push({text:K,lineNumber:q+1,similarity:W})}return G.sort((q,K)=>K.similarity-q.similarity).slice(0,X)}function SQ($,Z){let X=(F)=>F.trim().replace(/\s+/g," ").replace(/[\u201c\u201d"]/g,'"').replace(/[\u2018\u2019']/g,"'"),Y=X($),Q=X(Z);if(Y===Q)return 1;let J=Y.length,G=Q.length;if(J===0)return G===0?1:0;if(G===0)return 0;let q=200,K=Y.substring(0,q),W=Q.substring(0,q),U=wO(K,W),H=Math.max(K.length,W.length);return 1-U/H}function wO($,Z){let X=$.length,Y=Z.length,Q=Array(X+1).fill(null).map(()=>Array(Y+1).fill(0));for(let J=0;J<=X;J++)Q[J][0]=J;for(let J=0;J<=Y;J++)Q[0][J]=J;for(let J=1;J<=X;J++)for(let G=1;G<=Y;G++){let q=$[J-1]===Z[G-1]?0:1;Q[J][G]=Math.min(Q[J-1][G]+1,Q[J][G-1]+1,Q[J-1][G-1]+q)}return Q[X][Y]}var u7;var CQ=A(()=>{
|
|
1009
|
+
`),W=SQ(Z,K);if(W>0.5)G.push({text:K,lineNumber:q+1,similarity:W})}return G.sort((q,K)=>K.similarity-q.similarity).slice(0,X)}function SQ($,Z){let X=(F)=>F.trim().replace(/\s+/g," ").replace(/[\u201c\u201d"]/g,'"').replace(/[\u2018\u2019']/g,"'"),Y=X($),Q=X(Z);if(Y===Q)return 1;let J=Y.length,G=Q.length;if(J===0)return G===0?1:0;if(G===0)return 0;let q=200,K=Y.substring(0,q),W=Q.substring(0,q),U=wO(K,W),H=Math.max(K.length,W.length);return 1-U/H}function wO($,Z){let X=$.length,Y=Z.length,Q=Array(X+1).fill(null).map(()=>Array(Y+1).fill(0));for(let J=0;J<=X;J++)Q[J][0]=J;for(let J=0;J<=Y;J++)Q[0][J]=J;for(let J=1;J<=X;J++)for(let G=1;G<=Y;G++){let q=$[J-1]===Z[G-1]?0:1;Q[J][G]=Math.min(Q[J-1][G]+1,Q[J][G-1]+1,Q[J-1][G-1]+q)}return Q[X][Y]}var u7;var CQ=A(()=>{g4();u4();p0();E$();V2();p7();yQ();q6();m7();u7=e({name:"Edit",displayName:"File Edit",kind:"write",strict:!0,isConcurrencySafe:!1,schema:K6.object({file_path:r0.filePath({description:"Absolute path of the file to edit"}),old_string:K6.string().min(1,"old_string cannot be empty").describe("String to replace"),new_string:K6.string().describe("Replacement string (can be empty)"),replace_all:K6.boolean().default(!1).describe("Replace all matches (default: first only)")}),description:{short:"Performs exact string replacements in files",long:"Performs exact string replacements in files.",usageNotes:["You must use your Read tool at least once in the conversation before editing. This tool will error if you attempt an edit without reading the file.","When editing text from Read tool output, ensure you preserve the exact indentation (tabs/spaces) as it appears AFTER the line number prefix. The line number prefix format is: spaces + line number + tab. Everything after that tab is the actual file content to match. Never include any part of the line number prefix in the old_string or new_string.","ALWAYS prefer editing existing files in the codebase. NEVER write new files unless explicitly required.","Only use emojis if the user explicitly requests it. Avoid adding emojis to files unless asked.","The edit will FAIL if old_string is not unique in the file. Either provide a larger string with more surrounding context to make it unique or use replace_all to change every instance of old_string.","Use replace_all for replacing and renaming strings across the file. This parameter is useful if you want to rename a variable for instance."]},async execute($,Z){let{file_path:X,old_string:Y,new_string:Q,replace_all:J}=$,{updateOutput:G,sessionId:q,messageId:K}=Z,W=Z.signal??new AbortController().signal;try{G?.("Starting to read file...");let U=m4(),H=R2(),F;try{if(H)G?.("通过 IDE 读取文件...");F=await U.readTextFile(X)}catch(N){if(N.code==="ENOENT"||N.message?.includes("not found"))return{success:!1,llmContent:`File not found: ${X}`,displayContent:`❌ 文件不存在: ${X}`,error:{type:"execution_error",message:"文件不存在"}};throw N}if(W.throwIfAborted(),q){let N=n$.getInstance();if(!N.hasFileBeenRead(X,q))return{success:!1,llmContent:"You must use your Read tool at least once in the conversation before editing. This tool will error if you attempt an edit without reading the file.",displayContent:`❌ 编辑失败:必须先使用 Read 工具读取文件
|
|
1010
1010
|
|
|
1011
1011
|
请先用 Read 工具查看文件内容,再进行编辑。`,error:{type:"validation_error",message:"File not read before edit"}};let k=await N.checkExternalModification(X);if(k.isExternal)return{success:!1,llmContent:`The file has been modified by an external program since you last read it. You must use the Read tool again to see the current content before editing.
|
|
1012
1012
|
|
|
@@ -1019,7 +1019,7 @@ ${k.message}
|
|
|
1019
1019
|
`),S=["⚠️ 编辑暂停:需要更精确的定位","",`在文件中找到 ${_.length} 处相似代码:`,...m.map((T,c)=>` • 第 ${T.line} 行 (匹配 ${c+1}/${_.length})`),"","AI 正在自动调整,添加更多上下文以精确定位...","通常需要 1-2 次尝试即可成功","","\uD83D\uDCA1 如果多次失败,可能需要:"," • 包含函数/类名等独特标识符"," • 添加目标代码前后 3-5 行完整上下文",` • 或使用 replace_all=true 同时替换所有 ${_.length} 处匹配`].join(`
|
|
1020
1020
|
`);return{success:!1,llmContent:s,displayContent:S,error:{type:"validation_error",message:"old_string is not unique",details:{matches:m.map((T)=>({line:T.line,column:T.column})),count:_.length}}}}else G?.(`找到 ${_.length} 个匹配项,开始替换...`);let B,L;if(J)B=F.split(z).join(Q),L=_.length;else{let N=F.indexOf(z);B=F.substring(0,N)+Q+F.substring(N+z.length),L=1}if(W.throwIfAborted(),H)G?.("通过 IDE 写入文件...");if(await U.writeTextFile(X,B),q)await n$.getInstance().recordFileEdit(X,q,"edit");let w=await U.stat(X),R=MQ(F,B,z,Q,4),D=X.split("/").pop()||X,V=L===1?`替换 1 处匹配到 ${D}`:`替换 ${L} 处匹配到 ${D}`,I={file_path:X,matches_found:_.length,replacements_made:L,replace_all:J,old_string_length:Y.length,new_string_length:Q.length,original_size:F.length,new_size:B.length,size_diff:B.length-F.length,last_modified:w?.mtime instanceof Date?w.mtime.toISOString():void 0,snapshot_created:!!(q&&K),session_id:q,message_id:K,diff_snippet:R,summary:V,kind:"edit",oldContent:F,newContent:B},v=_O(I,R);return{success:!0,llmContent:{file_path:X,replacements:L,total_matches:_.length},displayContent:v,metadata:I}}catch(U){if(U.name==="AbortError")return{success:!1,llmContent:"File edit aborted",displayContent:"⚠️ 文件编辑被用户中止",error:{type:"execution_error",message:"操作被中止"}};return{success:!1,llmContent:`File edit failed: ${U.message}`,displayContent:`❌ 编辑文件失败: ${U.message}`,error:{type:"execution_error",message:U.message,details:U}}}},version:"2.0.0",category:"文件操作",tags:["file","edit","replace","modify"],extractSignatureContent:($)=>$.file_path,abstractPermissionRule:($)=>{let Z=FO($.file_path);return Z?`**/*${Z}`:"**/*"}})});import{extname as kQ}from"path";import{z as NO}from"zod";function bO($){return[".txt",".md",".js",".ts",".jsx",".tsx",".json",".xml",".html",".htm",".css",".scss",".sass",".less",".yml",".yaml",".toml",".ini",".cfg",".py",".rb",".php",".java",".cpp",".c",".h",".hpp",".rs",".go",".sh",".bash",".zsh",".fish",".ps1",".bat",".cmd",".sql",".graphql",".vue",".svelte",".astro",".dockerfile",".gitignore",".env"].includes($)||$===""}function AO($){return[".jpg",".jpeg",".png",".gif",".bmp",".svg",".ico",".webp",".mp3",".wav",".mp4",".avi",".mov",".wmv",".flv",".webm",".pdf",".doc",".docx",".xls",".xlsx",".ppt",".pptx",".zip",".tar",".gz",".rar",".7z",".exe",".dll",".so",".ttf",".otf",".woff",".woff2",".eot"].includes($)}function RO($,Z){let X=`✅ 成功读取文件: ${$}`;if(Z.file_size!==void 0)X+=` (${VO(Z.file_size)})`;if(Z.lines_read!==void 0)X+=`
|
|
1021
1021
|
\uD83D\uDCC4 读取了 ${Z.lines_read} 行 (第${Z.start_line}-${Z.end_line}行,共${Z.total_lines}行)`;if(Z.is_binary)X+=`
|
|
1022
|
-
\uD83D\uDD10 文件以 base64 编码显示`;return X}function VO($){let Z=["B","KB","MB","GB"],X=$,Y=0;while(X>=1024&&Y<Z.length-1)X/=1024,Y++;return`${X.toFixed(1)}${Z[Y]}`}var g7;var fQ=A(()=>{
|
|
1022
|
+
\uD83D\uDD10 文件以 base64 编码显示`;return X}function VO($){let Z=["B","KB","MB","GB"],X=$,Y=0;while(X>=1024&&Y<Z.length-1)X/=1024,Y++;return`${X.toFixed(1)}${Z[Y]}`}var g7;var fQ=A(()=>{g4();u4();p0();E$();V2();q6();g7=e({name:"Read",displayName:"File Read",kind:"readonly",schema:NO.object({file_path:r0.filePath({description:"File path to read (must be absolute)"}),offset:r0.lineNumber({description:"Starting line number (0-based, text files only)"}).optional(),limit:r0.lineLimit({description:"Number of lines to read (text files only)"}).optional(),encoding:r0.encoding()}),description:{short:"Read files from the local filesystem",long:"Reads a file from the local filesystem. You can access any file directly by using this tool. Assume this tool is able to read all files on the machine. If the User provides a path to a file assume that path is valid. It is okay to read a file that does not exist; an error will be returned.",usageNotes:["The file_path parameter must be an absolute path, not a relative path","By default, it reads up to 2000 lines starting from the beginning of the file","You can optionally specify a line offset and limit (especially handy for long files), but it's recommended to read the whole file by not providing these parameters","Any lines longer than 2000 characters will be truncated","Results are returned using cat -n format, with line numbers starting at 1","This tool allows reading images (eg PNG, JPG, etc). When reading an image file the contents are presented visually as this is a multimodal LLM.","This tool can read PDF files (.pdf). PDFs are processed page by page, extracting both text and visual content for analysis.","This tool can read Jupyter notebooks (.ipynb files) and returns all cells with their outputs, combining code, text, and visualizations.","This tool can only read files, not directories. To read a directory, use an ls command via the Bash tool.","You can call multiple tools in a single response. It is always better to speculatively read multiple potentially useful files in parallel.","You will regularly be asked to read screenshots. If the user provides a path to a screenshot, ALWAYS use this tool to view the file at the path. This tool will work with all temporary file paths.","If you read a file that exists but has empty contents you will receive a system reminder warning in place of file contents."],examples:[{description:"Read the entire file (recommended)",params:{file_path:"/path/to/file.ts"}},{description:"Read the first 100 lines",params:{file_path:"/path/to/file.txt",limit:100}},{description:"Read 100 lines starting at line 50 (large file)",params:{file_path:"/path/to/large-file.log",offset:50,limit:100}}],important:["file_path must be absolute","Prefer reading the entire file (omit offset and limit)","Use offset/limit only for very large files","Line numbers start at 1 (cat -n format)"]},async execute($,Z){let{file_path:X,offset:Y,limit:Q,encoding:J="utf8"}=$,{updateOutput:G,sessionId:q}=Z,K=Z.signal??new AbortController().signal;try{G?.("Starting file read...");let W=m4(),U=R2();try{if(!await W.exists(X))throw Error("File not found")}catch(V){return{success:!1,llmContent:`File not found: ${X}`,displayContent:`❌ 文件不存在: ${X}`,error:{type:"execution_error",message:`File not found: ${X}`}}}if(K.throwIfAborted(),q)await n$.getInstance().recordFileRead(X,q);let H=await W.stat(X);if(H?.isDirectory)return{success:!1,llmContent:`Cannot read a directory: ${X}`,displayContent:`❌ 无法读取目录: ${X}`,error:{type:"execution_error",message:"Target is a directory, not a file"}};let F=kQ(X).toLowerCase(),O=bO(F),z=AO(F),_,B={file_path:X,file_size:H?.size,file_type:F,last_modified:H?.mtime instanceof Date?H.mtime.toISOString():void 0,encoding:J,acp_mode:U};if(z&&J==="utf8"){if(U)G?.("⚠️ 二进制文件通过本地读取(ACP 不支持)..."),B.acp_fallback=!0;else G?.("检测到二进制文件,使用 base64 编码...");_=(await W.readBinaryFile(X)).toString("base64"),B.encoding="base64",B.is_binary=!0}else if(O){if(U)G?.("通过 IDE 读取文件...");_=await W.readTextFile(X)}else{if(U)B.acp_fallback=!0;let V=await W.readBinaryFile(X);if(J==="base64")_=V.toString("base64");else if(J==="binary")_=V.toString("binary");else _=V.toString("utf8")}if(K.throwIfAborted(),(Y!==void 0||Q!==void 0)&&J==="utf8"&&O){let V=_.split(`
|
|
1023
1023
|
`),I=Y||0,v=Q!==void 0?I+Q:V.length,N=V.slice(I,v);_=N.map((k,m)=>{let s=I+m+1,S=k.length>2000?`${k.substring(0,2000)}...`:k;return`${s.toString().padStart(6)}→${S}`}).join(`
|
|
1024
1024
|
`),B.lines_read=N.length,B.total_lines=V.length,B.start_line=I+1,B.end_line=Math.min(v,V.length)}let L=X.split("/").pop()||X,w=B.lines_read||B.total_lines,R=w?`读取 ${w} 行从 ${L}`:`读取 ${L}`;B.summary=R;let D=RO(X,B);return{success:!0,llmContent:_,displayContent:D,metadata:B}}catch(W){if(W.name==="AbortError")return{success:!1,llmContent:"File read aborted",displayContent:"⚠️ 文件读取被用户中止",error:{type:"execution_error",message:"Operation aborted"}};return{success:!1,llmContent:`File read failed: ${W.message}`,displayContent:`❌ 读取文件失败: ${W.message}`,error:{type:"execution_error",message:W.message,details:W}}}},version:"2.0.0",category:"文件操作",tags:["file","io","read"],extractSignatureContent:($)=>$.file_path,abstractPermissionRule:($)=>{let Z=kQ($.file_path);return Z?`**/*${Z}`:"**/*"}})});import{promises as DO}from"fs";import{dirname as MO,extname as hQ}from"path";import{z as c7}from"zod";function jO($,Z,X,Y){let Q=`✅ 成功写入文件: ${$}`;if(Z.file_size!==void 0)Q+=` (${xQ(Z.file_size)})`;if(Z.snapshot_created)Q+=`
|
|
1025
1025
|
\uD83D\uDCF8 已创建快照 (可回滚)`;if(Z.encoding!=="utf8")Q+=`
|
|
@@ -1034,7 +1034,7 @@ ${k.message}
|
|
|
1034
1034
|
`))U+=`
|
|
1035
1035
|
`;if(U+="```",K)U+=`
|
|
1036
1036
|
|
|
1037
|
-
⚠️ 内容已截断(完整文件共 ${W.length} 行,${Z.length} 字符)`;return U}function xQ($){let Z=["B","KB","MB","GB"],X=$,Y=0;while(X>=1024&&Y<Z.length-1)X/=1024,Y++;return`${X.toFixed(1)}${Z[Y]}`}var l7;var pQ=A(()=>{
|
|
1037
|
+
⚠️ 内容已截断(完整文件共 ${W.length} 行,${Z.length} 字符)`;return U}function xQ($){let Z=["B","KB","MB","GB"],X=$,Y=0;while(X>=1024&&Y<Z.length-1)X/=1024,Y++;return`${X.toFixed(1)}${Z[Y]}`}var l7;var pQ=A(()=>{g4();u4();p0();E$();V2();p7();q6();m7();l7=e({name:"Write",displayName:"File Write",kind:"write",strict:!0,isConcurrencySafe:!1,schema:c7.object({file_path:r0.filePath({description:"Absolute file path to write"}),content:c7.string().describe("Content to write"),encoding:r0.encoding(),create_directories:c7.boolean().default(!0).describe("Automatically create missing parent directories")}),description:{short:"Writes a file to the local filesystem",long:"Writes a file to the local filesystem.",usageNotes:["This tool will overwrite the existing file if there is one at the provided path.","If this is an existing file, you MUST use the Read tool first to read the file's contents. This tool will fail if you did not read the file first.","ALWAYS prefer editing existing files in the codebase. NEVER write new files unless explicitly required.","NEVER proactively create documentation files (*.md) or README files. Only create documentation files if explicitly requested by the User.","Only use emojis if the user explicitly requests it. Avoid writing emojis to files unless asked."]},async execute($,Z){let{file_path:X,content:Y,encoding:Q,create_directories:J}=$,{updateOutput:G,sessionId:q,messageId:K}=Z,W=Z.signal??new AbortController().signal;try{G?.("开始写入文件...");let U=m4(),H=R2();if(J){let V=MO(X);try{await U.mkdir(V,{recursive:!0})}catch(I){if(I.code!=="EEXIST")throw I}}W.throwIfAborted();let F=!1,O=null;try{if(F=await U.exists(X),F&&Q==="utf8")try{O=await U.readTextFile(X)}catch(V){console.warn("[WriteTool] 读取旧文件内容失败:",V)}}catch{}if(F&&q){let V=n$.getInstance();if(!V.hasFileBeenRead(X,q))return{success:!1,llmContent:"If this is an existing file, you MUST use the Read tool first to read the file's contents. This tool will fail if you did not read the file first.",displayContent:`❌ 写入失败:必须先使用 Read 工具读取文件
|
|
1038
1038
|
|
|
1039
1039
|
文件 ${X} 已存在,请先用 Read 工具查看其内容。`,error:{type:"validation_error",message:"File not read before write"}};let I=await V.checkExternalModification(X);if(I.isExternal)return{success:!1,llmContent:`The file has been modified by an external program since you last read it. You must use the Read tool again to see the current content before writing.
|
|
1040
1040
|
|
|
@@ -1049,7 +1049,7 @@ ${I.message}
|
|
|
1049
1049
|
\uD83D\uDCA1 建议:
|
|
1050
1050
|
• 如果是文本文件,使用 encoding='utf8'
|
|
1051
1051
|
• 如果必须写入二进制文件,请在本地终端执行`,error:{type:"validation_error",message:"Binary writes not supported in ACP mode"}};let V;if(Q==="base64")V=Buffer.from(Y,"base64");else if(Q==="binary")V=Buffer.from(Y,"binary");else V=Buffer.from(Y,"utf8");await DO.writeFile(X,V)}if(q)await n$.getInstance().recordFileEdit(X,q,"write");W.throwIfAborted();let _=await U.stat(X),B=Q==="utf8"?Y.split(`
|
|
1052
|
-
`).length:0,L=X.split("/").pop()||X,w=null;if(O&&Q==="utf8"&&O!==Y){if(O.length<1048576&&Y.length<1048576)w=DQ(O,Y,4)}let R={file_path:X,content_size:Y.length,file_size:_?.size,encoding:Q,created_directories:J,snapshot_created:z,session_id:q,message_id:K,last_modified:_?.mtime instanceof Date?_.mtime.toISOString():void 0,has_diff:!!w,summary:Q==="utf8"?`写入 ${B} 行到 ${L}`:`写入 ${_?.size?xQ(_.size):"unknown"} 到 ${L}`,kind:"edit",oldContent:O||"",newContent:Q==="utf8"?Y:void 0},D=jO(X,R,Y,w);return{success:!0,llmContent:{file_path:X,size:_?.size,modified:_?.mtime instanceof Date?_.mtime.toISOString():void 0},displayContent:D,metadata:R}}catch(U){if(U.name==="AbortError")return{success:!1,llmContent:"File write aborted",displayContent:"⚠️ 文件写入被用户中止",error:{type:"execution_error",message:"操作被中止"}};return{success:!1,llmContent:`File write failed: ${U.message}`,displayContent:`❌ 写入文件失败: ${U.message}`,error:{type:"execution_error",message:U.message,details:U}}}},version:"2.0.0",category:"文件操作",tags:["file","io","write","create"],extractSignatureContent:($)=>$.file_path,abstractPermissionRule:($)=>{let Z=hQ($.file_path);return Z?`**/*${Z}`:"**/*"}})});var dQ=A(()=>{CQ();fQ();pQ()});import*as W6 from"fs/promises";import{z as
|
|
1052
|
+
`).length:0,L=X.split("/").pop()||X,w=null;if(O&&Q==="utf8"&&O!==Y){if(O.length<1048576&&Y.length<1048576)w=DQ(O,Y,4)}let R={file_path:X,content_size:Y.length,file_size:_?.size,encoding:Q,created_directories:J,snapshot_created:z,session_id:q,message_id:K,last_modified:_?.mtime instanceof Date?_.mtime.toISOString():void 0,has_diff:!!w,summary:Q==="utf8"?`写入 ${B} 行到 ${L}`:`写入 ${_?.size?xQ(_.size):"unknown"} 到 ${L}`,kind:"edit",oldContent:O||"",newContent:Q==="utf8"?Y:void 0},D=jO(X,R,Y,w);return{success:!0,llmContent:{file_path:X,size:_?.size,modified:_?.mtime instanceof Date?_.mtime.toISOString():void 0},displayContent:D,metadata:R}}catch(U){if(U.name==="AbortError")return{success:!1,llmContent:"File write aborted",displayContent:"⚠️ 文件写入被用户中止",error:{type:"execution_error",message:"操作被中止"}};return{success:!1,llmContent:`File write failed: ${U.message}`,displayContent:`❌ 写入文件失败: ${U.message}`,error:{type:"execution_error",message:U.message,details:U}}}},version:"2.0.0",category:"文件操作",tags:["file","io","write","create"],extractSignatureContent:($)=>$.file_path,abstractPermissionRule:($)=>{let Z=hQ($.file_path);return Z?`**/*${Z}`:"**/*"}})});var dQ=A(()=>{CQ();fQ();pQ()});import*as W6 from"fs/promises";import{z as l4}from"zod";var i7;var mQ=A(()=>{p0();w$();i7=e({name:"NotebookEdit",displayName:"Notebook Edit",kind:"write",schema:l4.object({notebook_path:l4.string().describe("The absolute path to the Jupyter notebook file to edit (must be absolute, not relative)"),cell_id:l4.string().optional().describe("The ID of the cell to edit. When inserting a new cell, the new cell will be inserted after the cell with this ID, or at the beginning if not specified."),new_source:l4.string().describe("The new source for the cell"),cell_type:l4.enum(["code","markdown"]).optional().describe("The type of the cell (code or markdown). If not specified, it defaults to the current cell type. If using edit_mode=insert, this is required."),edit_mode:l4.enum(["replace","insert","delete"]).optional().default("replace").describe("The type of edit to make (replace, insert, delete). Defaults to replace.")}),description:{short:"Completely replaces the contents of a specific cell in a Jupyter notebook",long:"Completely replaces the contents of a specific cell in a Jupyter notebook (.ipynb file) with new source. Jupyter notebooks are interactive documents that combine code, text, and visualizations, commonly used for data analysis and scientific computing. The notebook_path parameter must be an absolute path, not a relative path. The cell_number is 0-indexed. Use edit_mode=insert to add a new cell at the index specified by cell_number. Use edit_mode=delete to delete the cell at the index specified by cell_number."},async execute($,Z){let{notebook_path:X,cell_id:Y,new_source:Q,cell_type:J,edit_mode:G="replace"}=$;try{let q=await W6.readFile(X,"utf-8"),K=JSON.parse(q);if(!K.cells||!Array.isArray(K.cells))return{success:!1,llmContent:"Invalid notebook format: no cells array found",displayContent:"Invalid notebook format",error:{type:"validation_error",message:"Invalid notebook format"}};let W=-1;if(Y){if(W=K.cells.findIndex((H)=>H.id===Y),W===-1&&G!=="insert")return{success:!1,llmContent:`Cell with ID "${Y}" not found`,displayContent:"Cell not found",error:{type:"validation_error",message:`Cell ID "${Y}" not found`}}}switch(G){case"replace":{if(W===-1)return{success:!1,llmContent:"Cell ID required for replace operation",displayContent:"Cell ID required",error:{type:"validation_error",message:"Cell ID required for replace"}};let H=K.cells[W];if(H.source=Q.split(`
|
|
1053
1053
|
`).map((F,O,z)=>O<z.length-1?F+`
|
|
1054
1054
|
`:F),J)H.cell_type=J;break}case"insert":{if(!J)return{success:!1,llmContent:"cell_type is required for insert operation",displayContent:"cell_type required",error:{type:"validation_error",message:"cell_type required for insert"}};let H={cell_type:J,source:Q.split(`
|
|
1055
1055
|
`).map((O,z,_)=>z<_.length-1?O+`
|
|
@@ -1196,19 +1196,19 @@ The agent has stopped and control is returned to the user. The user can now prov
|
|
|
1196
1196
|
`+"Proceeding with implementation.",displayContent:"Plan mode exit (non-interactive)",metadata:{approved:null}}}})});var aQ=A(()=>{gQ();iQ()});import{existsSync as EO,readFileSync as PO}from"node:fs";import{readFile as TO}from"node:fs/promises";import{dirname as SO,join as nQ}from"node:path";import CO from"fast-glob";import{LRUCache as kO}from"lru-cache";import X3 from"picomatch";function fO($){if(!EO($))return{patterns:[],negatePatterns:[]};try{let Z=PO($,"utf-8"),X=[],Y=[];for(let Q of Z.split(`
|
|
1197
1197
|
`)){let J=Q.trim();if(!J||J.startsWith("#"))continue;if(J.startsWith("!"))Y.push(J.slice(1));else X.push(J)}return{patterns:X,negatePatterns:Y}}catch(Z){return console.warn(`Failed to read .gitignore: ${Z}`),{patterns:[],negatePatterns:[]}}}async function hO($,Z){let X=[...p1.map((K)=>`${K}/**`),...Z?.scanIgnore??[]],Y=`${$}|${X.join(",")}`,Q=rQ.get(Y);if(Q)return Q;let J=await CO("**/.gitignore",{cwd:$,dot:!0,onlyFiles:!0,followSymbolicLinks:!1,unique:!0,ignore:X});J.sort((K,W)=>K.split("/").length-W.split("/").length);let G=[];for(let K of J){let W=SO(K).replace(/\\/g,"/"),U=W==="."?"":W,F=(await TO(nQ($,K),"utf-8")).split(`
|
|
1198
1198
|
`);for(let O of F){let z=O.trim();if(!z||z.startsWith("#"))continue;let _=z.startsWith("!"),L=(_?z.slice(1):z).trim();if(!L)continue;let w="";if(L.startsWith("/")){let R=L.slice(1).replace(/\\/g,"/");if(w=(U?U+"/":"")+R,G.push({type:_?"negate":"ignore",pattern:w}),L.endsWith("/")){let D=w+"**";G.push({type:_?"negate":"ignore",pattern:D});let V=w.replace(/\/$/,"");if(V!==w)G.push({type:_?"negate":"ignore",pattern:V})}}else{let R=L.replace(/\\/g,"/");if(R.includes("/")){if(w=(U?U+"/":"")+R,G.push({type:_?"negate":"ignore",pattern:w}),R.endsWith("/")){let D=w+"**";G.push({type:_?"negate":"ignore",pattern:D});let V=w.replace(/\/$/,"");if(V!==w)G.push({type:_?"negate":"ignore",pattern:V})}}else w=(U?U+"/**/":"**/")+R,G.push({type:_?"negate":"ignore",pattern:w})}}}let q=Z?.cacheTTL??30000;return rQ.set(Y,G,{ttl:q}),G}class U6{orderedRules=[];ignorePatterns=[];negatePatterns=[];constructor($={}){this.initialize($)}static async create($={}){let Z=new U6({...$,useGitignore:!1}),{cwd:X=process.cwd(),useGitignore:Y=!0,gitignoreScanMode:Q="root",customScanIgnore:J=[],cacheTTL:G}=$;if(Y&&Q==="recursive"){let q=await hO(X,{scanIgnore:J,cacheTTL:G});for(let K of q)if(Z.orderedRules.push({type:K.type,matcher:X3(K.pattern,{dot:!0})}),K.type==="ignore")Z.ignorePatterns.push(K.pattern);else Z.negatePatterns.push(K.pattern)}return Z}initialize($){let{cwd:Z=process.cwd(),useGitignore:X=!0,useDefaults:Y=!0,customPatterns:Q=[]}=$,J=[],G=[];if(Y){let q=[...p1.map((K)=>`${K}/**`),...p1,...o7];J.push(...q);for(let K of q)this.orderedRules.push({type:"ignore",matcher:X3(K,{dot:!0})})}if(X){let q=nQ(Z,".gitignore"),{patterns:K,negatePatterns:W}=fO(q);for(let U of K)this.orderedRules.push({type:"ignore",matcher:X3(U,{dot:!0})}),J.push(U);for(let U of W)this.orderedRules.push({type:"negate",matcher:X3(U,{dot:!0})}),G.push(U)}J.push(...Q);for(let q of Q)this.orderedRules.push({type:"ignore",matcher:X3(q,{dot:!0})});this.ignorePatterns=J,this.negatePatterns=G}shouldIgnore($){let Z=$.replace(/\\/g,"/"),X=void 0;for(let Y of this.orderedRules)if(Y.matcher(Z))X=Y.type==="ignore";return X===!0}shouldIgnoreDirectory($){let Z=$.replace(/\\/g,"/");return this.shouldIgnore(Z)||this.shouldIgnore(`${Z}/`)}filter($){return $.filter((Z)=>!this.shouldIgnore(Z))}getIgnorePatterns(){return this.ignorePatterns}getNegatePatterns(){return this.negatePatterns}}var p1,o7,rQ;var H6=A(()=>{p1=["node_modules",".git","dist","build","out",".next",".nuxt",".cache",".parcel-cache","coverage",".nyc_output",".idea",".vscode",".vs","bower_components","jspm_packages"],o7=["*.log","npm-debug.log*","yarn-debug.log*","pnpm-debug.log*","*.lock","package-lock.json","yarn.lock","pnpm-lock.yaml","*.tmp","*.temp","*.swp","*.bak","*~",".DS_Store","Thumbs.db","*.pid","*.seed"];rQ=new kO({max:100,ttl:30000,updateAgeOnGet:!0})});import{stat as xO}from"node:fs/promises";import pO from"fast-glob";import{join as dO,resolve as mO}from"path";import{z as F6}from"zod";function s7($){let Z=Error($);return Z.name="AbortError",Z}async function uO($,Z,X,Y){let Q=Y.getIgnorePatterns(),J=[],G=!1;return await new Promise((q,K)=>{if(X.signal.aborted){K(s7("文件搜索被用户中止"));return}let W=pO.stream(Z,{cwd:$,dot:!0,followSymbolicLinks:!1,unique:!0,caseSensitiveMatch:X.caseSensitive,objectMode:!0,stats:!0,onlyFiles:!X.includeDirectories,ignore:Q}),U=!1,H=null,F=()=>{if(H){if(X.signal.removeEventListener)X.signal.removeEventListener("abort",H);else if("onabort"in X.signal)X.signal.onabort=null;H=null}},O=()=>{if(!U)U=!0,G=!0,W.destroy(),F(),q({matches:J,wasTruncated:G})},z=(_)=>{if(X.signal.aborted){if(!U)U=!0,W.destroy(s7("文件搜索被用户中止"));return}if(J.length>=X.maxResults){O();return}let B=_.path.replace(/\\/g,"/"),L=dO($,B);if(Y.shouldIgnore(B))return;let w=_.stats?_.stats.isDirectory():!1;if(w&&Y.shouldIgnoreDirectory(B))return;let R=_.stats&&_.stats.isFile()?_.stats.size:void 0,D=_.stats?_.stats.mtime.toISOString():void 0;if(J.push({path:L,relative_path:B,is_directory:w,size:R,modified:D}),J.length>=X.maxResults)O()};if(W.on("data",z),H=()=>{if(!U)U=!0,F(),W.destroy(s7("文件搜索被用户中止"))},X.signal.addEventListener)X.signal.addEventListener("abort",H);else if("onabort"in X.signal)X.signal.onabort=H;W.once("error",(_)=>{if(!U)U=!0,F(),K(_)}),W.once("end",()=>{if(!U)U=!0,F(),q({matches:J,wasTruncated:G})})})}function gO($){return $.sort((Z,X)=>{if(Z.is_directory!==X.is_directory)return Z.is_directory?1:-1;if(Z.modified&&X.modified)return new Date(X.modified).getTime()-new Date(Z.modified).getTime();return Z.relative_path.localeCompare(X.relative_path)})}function cO($){let{search_path:Z,pattern:X,total_matches:Y,returned_matches:Q,truncated:J}=$,G;if(J)G=`✅ 在 ${Z} 中找到至少 ${Y} 个匹配 "${X}" 的文件(已截断)`,G+=`
|
|
1199
|
-
\uD83D\uDCCB 显示前 ${Q} 个结果`;else G=`✅ 在 ${Z} 中找到 ${Y} 个匹配 "${X}" 的文件`;return G}var t7;var oQ=A(()=>{H6();p0();E$();
|
|
1199
|
+
\uD83D\uDCCB 显示前 ${Q} 个结果`;else G=`✅ 在 ${Z} 中找到 ${Y} 个匹配 "${X}" 的文件`;return G}var t7;var oQ=A(()=>{H6();p0();E$();V2();t7=e({name:"Glob",displayName:"File Pattern Match",kind:"readonly",schema:F6.object({pattern:r0.glob({description:"Glob pattern string (supports *, ?, ** wildcards)"}),path:F6.string().optional().describe("Search path (optional, defaults to cwd)"),max_results:r0.positiveInt({description:"Maximum number of results"}).max(1000,"At most 1000 results can be returned").default(100),include_directories:F6.boolean().default(!1).describe("Include directories in results"),case_sensitive:F6.boolean().default(!1).describe("Case sensitive matching")}),description:{short:"Fast file pattern matching tool that works with any codebase size",long:'Fast file pattern matching tool that works with any codebase size. Supports glob patterns like "**/*.js" or "src/**/*.ts". Returns matching file paths sorted by modification time.',usageNotes:["Use this tool when you need to find files by name patterns","When you are doing an open ended search that may require multiple rounds of globbing and grepping, use the Agent tool instead","You can call multiple tools in a single response. It is always better to speculatively perform multiple searches in parallel if they are potentially useful."]},async execute($,Z){let{pattern:X,path:Y=process.cwd(),max_results:Q,include_directories:J,case_sensitive:G}=$,{updateOutput:q}=Z,K=Z.signal??new AbortController().signal;try{q?.(`Searching in ${Y} for pattern "${X}"...`);let W=mO(Y);try{if(!(await xO(W)).isDirectory())return{success:!1,llmContent:`Search path must be a directory: ${W}`,displayContent:`❌ 搜索路径必须是目录: ${W}`,error:{type:"validation_error",message:"搜索路径必须是目录"}}}catch(L){if(L.code==="ENOENT")return{success:!1,llmContent:`Search path does not exist: ${W}`,displayContent:`❌ 搜索路径不存在: ${W}`,error:{type:"execution_error",message:"搜索路径不存在"}};throw L}K.throwIfAborted();let U=await U6.create({cwd:W,useGitignore:!0,useDefaults:!0,gitignoreScanMode:"recursive",customScanIgnore:[],cacheTTL:30000}),{matches:H,wasTruncated:F}=await uO(W,X,{maxResults:Q,includeDirectories:J,caseSensitive:G,signal:K},U),O=gO(H),z={search_path:W,pattern:X,total_matches:H.length,returned_matches:H.length,max_results:Q,include_directories:J,case_sensitive:G,truncated:F},_=cO(z),B;if(O.length>0)B=`${F?`Found at least ${O.length} file(s) matching "${X}" (truncated)`:`Found ${O.length} file(s) matching "${X}"`}:
|
|
1200
1200
|
|
|
1201
1201
|
`+O.map((w)=>`- ${w.relative_path}`).join(`
|
|
1202
1202
|
`)+`
|
|
1203
1203
|
|
|
1204
|
-
Use the relative_path values above for Read/Edit operations.`;else B=`No files found matching "${X}"`;return{success:!0,llmContent:B,displayContent:_,metadata:{...z,matches:O}}}catch(W){if(W.name==="AbortError")return{success:!1,llmContent:"File search aborted",displayContent:"⚠️ 文件搜索被用户中止",error:{type:"execution_error",message:"操作被中止"}};return{success:!1,llmContent:`Search failed: ${W.message}`,displayContent:`❌ 搜索失败: ${W.message}`,error:{type:"execution_error",message:W.message,details:W}}}},version:"2.0.0",category:"搜索工具",tags:["file","search","glob","pattern","wildcard"],extractSignatureContent:($)=>$.pattern,abstractPermissionRule:()=>"*"})});import{execSync as e7,spawn as $5}from"child_process";import{existsSync as O6}from"fs";import{readdir as lO,readFile as iO}from"fs/promises";import{join as sQ,relative as aO}from"path";import rO from"picomatch";import{z as
|
|
1204
|
+
Use the relative_path values above for Read/Edit operations.`;else B=`No files found matching "${X}"`;return{success:!0,llmContent:B,displayContent:_,metadata:{...z,matches:O}}}catch(W){if(W.name==="AbortError")return{success:!1,llmContent:"File search aborted",displayContent:"⚠️ 文件搜索被用户中止",error:{type:"execution_error",message:"操作被中止"}};return{success:!1,llmContent:`Search failed: ${W.message}`,displayContent:`❌ 搜索失败: ${W.message}`,error:{type:"execution_error",message:W.message,details:W}}}},version:"2.0.0",category:"搜索工具",tags:["file","search","glob","pattern","wildcard"],extractSignatureContent:($)=>$.pattern,abstractPermissionRule:()=>"*"})});import{execSync as e7,spawn as $5}from"child_process";import{existsSync as O6}from"fs";import{readdir as lO,readFile as iO}from"fs/promises";import{join as sQ,relative as aO}from"path";import rO from"picomatch";import{z as D2}from"zod";function nO(){let{platform:$,arch:Z}=process,X={"darwin-arm64":"darwin-arm64/rg","darwin-x64":"darwin-x64/rg","linux-arm64":"linux-arm64/rg","linux-x64":"linux-x64/rg","win32-x64":"win32-x64/rg.exe"},Y=`${$}-${Z}`,Q=X[Y];if(!Q)return null;let J=sQ(process.cwd(),"vendor","ripgrep",Q);if(O6(J))return J;try{let G=new URL("../../../../vendor/ripgrep/"+Q,import.meta.url).pathname;if(O6(G))return G}catch{}return null}function tQ(){try{let Z=process.platform==="win32"?"where rg":"command -v rg 2>/dev/null || which rg 2>/dev/null",X=e7(Z,{encoding:"utf8",stdio:["pipe","pipe","ignore"]}).split(/\r?\n/)[0].trim();if(X)return X}catch{}let $=nO();if($&&O6($))return $;try{let Z=V$("@vscode/ripgrep");if(Z?.rgPath&&O6(Z.rgPath))return Z.rgPath}catch{}return null}async function oO($){try{return e7("git rev-parse --git-dir",{cwd:$,stdio:"ignore"}),!0}catch{return!1}}function sO(){try{return e7("grep --version",{stdio:"ignore"}),!0}catch{return!1}}async function tO($,Z,X,Y){let Q=tQ();if(!Q)throw Error("ripgrep not available");return new Promise((J,G)=>{let q=$5(Q,$,{stdio:["pipe","pipe","pipe"]}),K="",W="";q.stdout.on("data",(H)=>{K+=H.toString()}),q.stderr.on("data",(H)=>{W+=H.toString()}),q.on("close",(H)=>{J({stdout:K,stderr:W,exitCode:H||0})}),q.on("error",(H)=>{G(H)});let U=()=>{q.kill("SIGTERM"),G(Error("搜索被用户中止"))};X.addEventListener("abort",U),q.on("close",()=>{X.removeEventListener("abort",U)})})}async function eO($,Z,X,Y){let Q=["grep","-n"];if(X.caseInsensitive)Q.push("-i");if(X.contextLines!==void 0)Q.push(`-C${X.contextLines}`);if(Q.push("-e",$),X.glob)Q.push("--",X.glob);return new Promise((J,G)=>{let q=$5("git",Q,{cwd:Z,stdio:["pipe","pipe","pipe"]}),K="",W="";q.stdout.on("data",(H)=>{K+=H.toString()}),q.stderr.on("data",(H)=>{W+=H.toString()}),q.on("close",(H)=>{J({stdout:K,stderr:W,exitCode:H||0})}),q.on("error",(H)=>{G(H)});let U=()=>{q.kill("SIGTERM"),G(Error("搜索被用户中止"))};Y.addEventListener("abort",U),q.on("close",()=>{Y.removeEventListener("abort",U)})})}async function $z($,Z,X,Y){let Q=["-rn"];if(X.caseInsensitive)Q.push("-i");if(X.contextLines!==void 0)Q.push(`-C${X.contextLines}`);for(let J of p1)Q.push("--exclude-dir="+J.replace(/^\./,""));return Q.push("-e",$,Z),new Promise((J,G)=>{let q=$5("grep",Q,{stdio:["pipe","pipe","pipe"]}),K="",W="";q.stdout.on("data",(H)=>{K+=H.toString()}),q.stderr.on("data",(H)=>{W+=H.toString()}),q.on("close",(H)=>{J({stdout:K,stderr:W,exitCode:H||0})}),q.on("error",(H)=>{G(H)});let U=()=>{q.kill("SIGTERM"),G(Error("搜索被用户中止"))};Y.addEventListener("abort",U),q.on("close",()=>{Y.removeEventListener("abort",U)})})}async function Zz($,Z,X,Y){let Q=[],J=new RegExp($,X.caseInsensitive?"gi":"g"),G=await Xz(Z,Y),q=0;for(let K of G){if(Y.throwIfAborted(),eQ(K))continue;if(X.glob&&!Yz(K,X.glob))continue;try{(await iO(K,"utf-8")).split(`
|
|
1205
1205
|
`).forEach((H,F)=>{if(J.test(H))Q.push({file_path:aO(Z,K),line_number:F+1,content:H})}),q++}catch(W){continue}}return{matches:Q,totalFiles:q}}async function Xz($,Z){let X=[];async function Y(Q){Z.throwIfAborted();try{let J=await lO(Q,{withFileTypes:!0});for(let G of J){Z.throwIfAborted();let q=sQ(Q,G.name);if(G.isDirectory()){if(!eQ(q))await Y(q)}else if(G.isFile())X.push(q)}}catch(J){}}return await Y($),X}function eQ($){for(let Z of p1)if($.includes(Z))return!0;return!1}function Yz($,Z){return rO(Z)($)}function Qz($){let Z=[];if($.case_insensitive)Z.push("-i");if($.multiline)Z.push("-U","--multiline-dotall");switch($.output_mode){case"files_with_matches":Z.push("-l");break;case"count":Z.push("-c");break;case"content":if($.line_numbers)Z.push("-n");break}if($.context!==void 0&&$.output_mode==="content")Z.push("-C",$.context.toString());else{if($.context_before!==void 0&&$.output_mode==="content")Z.push("-B",$.context_before.toString());if($.context_after!==void 0&&$.output_mode==="content")Z.push("-A",$.context_after.toString())}if($.type)Z.push("--type",$.type);for(let X of p1)Z.push("--glob",`!${X}/**`);if($.glob)Z.push("--glob",$.glob);if($.head_limit!==void 0){let X=($.offset??0)+$.head_limit;Z.push("-m",X.toString())}return Z.push($.pattern),Z.push($.path),Z}function Jz($,Z){if(!$.trim())return[];let X=$.trim().split(`
|
|
1206
1206
|
`),Y=[];switch(Z){case"files_with_matches":return X.map((Q)=>({file_path:Q.trim()}));case"count":return X.map((Q)=>{let[J,G]=Q.split(":");return{file_path:J,count:parseInt(G,10)}});case"content":for(let Q of X){let J=Gz(Q);if(J)Y.push(J)}return Y;default:return[]}}function Gz($){let Z=$.indexOf(":");if(Z===-1)return null;let X=$.substring(0,Z),Y=$.substring(Z+1),Q=Y.indexOf(":");if(Q!==-1&&/^\d+$/.test(Y.substring(0,Q))){let J=parseInt(Y.substring(0,Q),10),G=Y.substring(Q+1);return{file_path:X,line_number:J,content:G}}else return{file_path:X,content:Y}}function qz($){let{search_pattern:Z,search_path:X,output_mode:Y,total_matches:Q,strategy:J}=$,G=`✅ 在 ${X} 中搜索 "${Z}"`;if(J)G+=`
|
|
1207
1207
|
\uD83D\uDD27 使用策略: ${J}`;switch(Y){case"files_with_matches":G+=`
|
|
1208
1208
|
\uD83D\uDCC1 找到 ${Q} 个包含匹配内容的文件`;break;case"count":G+=`
|
|
1209
1209
|
\uD83D\uDD22 统计了 ${Q} 个文件的匹配数量`;break;case"content":G+=`
|
|
1210
|
-
\uD83D\uDCDD 找到 ${Q} 个匹配行`;break}return G}var Z5;var $J=A(()=>{H6();p0();E$();
|
|
1211
|
-
[error] ${J.message}`}),this.processes.set(Z,Q),Q}consumeOutput($){let Z=this.processes.get($);if(!Z)return;let X={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="",X}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()}}var
|
|
1210
|
+
\uD83D\uDCDD 找到 ${Q} 个匹配行`;break}return G}var Z5;var $J=A(()=>{H6();p0();E$();V2();Z5=e({name:"Grep",displayName:"内容搜索",kind:"readonly",schema:D2.object({pattern:r0.pattern({description:"The regular expression pattern to search for in file contents"}),path:D2.string().optional().describe("File or directory to search in (rg PATH). Defaults to current working directory"),glob:D2.string().optional().describe('Glob pattern to filter files (e.g. "*.js", "*.{ts,tsx}") - maps to rg --glob'),type:D2.string().optional().describe("File type to search (rg --type). Common types: js, py, rust, go, java, etc. More efficient than include for standard file types"),output_mode:D2.enum(["content","files_with_matches","count"]).default("files_with_matches").describe('Output mode: "content" shows matching lines (supports -A/-B/-C context, -n line numbers, head_limit), "files_with_matches" shows file paths (supports head_limit), "count" shows match counts (supports head_limit). Defaults to "files_with_matches"'),"-i":D2.boolean().optional().describe("Case insensitive search (rg -i)"),"-n":D2.boolean().default(!0).describe('Show line numbers in output (rg -n). Requires output_mode: "content", ignored otherwise. Defaults to true'),"-B":r0.nonNegativeInt().optional().describe('Number of lines to show before each match (rg -B). Requires output_mode: "content", ignored otherwise'),"-A":r0.nonNegativeInt().optional().describe('Number of lines to show after each match (rg -A). Requires output_mode: "content", ignored otherwise'),"-C":r0.nonNegativeInt().optional().describe('Number of lines to show before and after each match (rg -C). Requires output_mode: "content", ignored otherwise'),head_limit:r0.positiveInt().optional().describe('Limit output to first N lines/entries, equivalent to "| head -N". Works across all output modes: content (limits output lines), files_with_matches (limits file paths), count (limits count entries). Defaults based on "cap" experiment value: 0 (unlimited), 20, or 100'),offset:r0.nonNegativeInt().optional().describe('Skip first N lines/entries before applying head_limit, equivalent to "| tail -n +N | head -N". Works across all output modes. Defaults to 0'),multiline:D2.boolean().default(!1).describe("Enable multiline mode where . matches newlines and patterns can span lines (rg -U --multiline-dotall). Default: false")}),description:{short:"A powerful search tool built on ripgrep",long:'A powerful search tool built on ripgrep\n\n Usage:\n - ALWAYS use Grep for search tasks. NEVER invoke `grep` or `rg` as a Bash command. The Grep tool has been optimized for correct permissions and access.\n - Supports full regex syntax (e.g., "log.*Error", "function\\s+\\w+")\n - Filter files with glob parameter (e.g., "*.js", "**/*.tsx") or type parameter (e.g., "js", "py", "rust")\n - Output modes: "content" shows matching lines, "files_with_matches" shows only file paths (default), "count" shows match counts\n - Use Task tool for open-ended searches requiring multiple rounds\n - Pattern syntax: Uses ripgrep (not grep) - literal braces need escaping (use `interface\\{\\}` to find `interface{}` in Go code)\n - Multiline matching: By default patterns match within single lines only. For cross-line patterns like `struct \\{[\\s\\S]*?field`, use `multiline: true`\n'},async execute($,Z){let{pattern:X,path:Y=process.cwd(),glob:Q,type:J,output_mode:G,"-i":q,"-n":K=!0,"-B":W,"-A":U,"-C":H,head_limit:F,offset:O,multiline:z}=$,{updateOutput:_}=Z,B=Z.signal??new AbortController().signal;try{_?.(`使用智能搜索策略查找模式 "${X}"...`);let L=null,w="ripgrep",R=[],D=tQ();if(D)try{_?.(`\uD83D\uDE80 使用 ripgrep (${D})`);let N=Qz({pattern:X,path:Y,glob:Q,type:J,output_mode:G,case_insensitive:q??!1,line_numbers:K,context_before:W,context_after:U,context:H,head_limit:F,offset:O,multiline:z??!1});L=await tO(N,G,B,_),w="ripgrep"}catch(N){_?.("⚠️ ripgrep 失败,尝试降级策略..."),L=null}if(!L&&await oO(Y))try{_?.("\uD83D\uDCE6 使用 git grep"),L=await eO(X,Y,{caseInsensitive:q??!1,glob:Q,contextLines:H},B),w="git-grep"}catch(N){_?.("⚠️ git grep 失败,继续尝试其他策略..."),L=null}if(!L&&sO())try{_?.("\uD83D\uDD27 使用系统 grep"),L=await $z(X,Y,{caseInsensitive:q??!1,contextLines:H},B),w="system-grep"}catch(N){_?.("⚠️ 系统 grep 失败,使用纯 JavaScript 实现..."),L=null}if(!L)_?.("\uD83D\uDCA1 使用纯 JavaScript 搜索实现"),R=(await Zz(X,Y,{caseInsensitive:q??!1,glob:Q,multiline:z??!1},B)).matches,w="fallback",L={stdout:"",stderr:"",exitCode:0};else R=Jz(L.stdout,G);let V=R.length;if(O!==void 0&&O>0)R=R.slice(O);if(F!==void 0&&R.length>F)R=R.slice(0,F);let I={search_pattern:X,search_path:Y,output_mode:G,case_insensitive:q??!1,total_matches:R.length,original_total:V,offset:O,head_limit:F,strategy:w,exit_code:L?.exitCode};if(L&&L.exitCode!==0&&L.stderr)return{success:!1,llmContent:`Search execution failed: ${L.stderr}`,displayContent:`❌ 搜索执行失败: ${L.stderr}`,error:{type:"execution_error",message:L.stderr}};let v=qz(I);return{success:!0,llmContent:R,displayContent:v,metadata:I}}catch(L){if(L.name==="AbortError")return{success:!1,llmContent:"Search aborted",displayContent:"⚠️ 搜索被用户中止",error:{type:"execution_error",message:"操作被中止"}};return{success:!1,llmContent:`Search failed: ${L.message}`,displayContent:`❌ 搜索失败: ${L.message}`,error:{type:"execution_error",message:L.message,details:L}}}},version:"3.0.0",category:"搜索工具",tags:["search","grep","ripgrep","regex","text","fallback"],extractSignatureContent:($)=>$.pattern,abstractPermissionRule:()=>"*"})});var ZJ=A(()=>{oQ();$J()});import{spawn as Kz}from"child_process";import{randomUUID as Wz}from"crypto";class T${static instance=null;processes=new Map;static getInstance(){if(!T$.instance)T$.instance=new T$;return T$.instance}startBackgroundProcess($){let Z=`bash_${Wz()}`,X={};for(let[J,G]of Object.entries({...process.env,...$.env,BLADE_CLI:"1"}))if(G!==void 0)X[J]=G;let Y=Kz("bash",["-c",$.command],{cwd:$.cwd||process.cwd(),env:X,stdio:["ignore","pipe","pipe"]}),Q={id:Z,command:$.command,sessionId:$.sessionId,cwd:$.cwd,env:$.env,process:Y,pid:Y.pid,status:"running",startTime:Date.now(),pendingStdout:"",pendingStderr:""};return Y.stdout?.setEncoding("utf8"),Y.stderr?.setEncoding("utf8"),Y.stdout?.on("data",(J)=>{Q.pendingStdout+=J.toString()}),Y.stderr?.on("data",(J)=>{Q.pendingStderr+=J.toString()}),Y.on("close",(J,G)=>{Q.status=Q.status==="killed"?"killed":"exited",Q.exitCode=J,Q.signal=G,Q.endTime=Date.now(),Q.process=void 0}),Y.on("error",(J)=>{Q.status="error",Q.errorMessage=J.message,Q.endTime=Date.now(),Q.process=void 0,Q.pendingStderr+=`
|
|
1211
|
+
[error] ${J.message}`}),this.processes.set(Z,Q),Q}consumeOutput($){let Z=this.processes.get($);if(!Z)return;let X={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="",X}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()}}var i4=()=>{};import{spawn as Uz}from"child_process";import{randomUUID as Hz}from"crypto";import{z as X5}from"zod";function Fz($,Z,X){let Q=T$.getInstance().startBackgroundProcess({command:$,sessionId:Hz(),cwd:Z||process.cwd(),env:X}),G=`后台启动命令: ${$.length>30?`${$.substring(0,30)}...`:$}`,q={command:$,background:!0,pid:Q.pid,bash_id:Q.id,shell_id:Q.id,message:"命令已在后台启动",summary:G},K=`✅ 命令已在后台启动
|
|
1212
1212
|
`+`\uD83C\uDD94 进程 ID: ${Q.pid}
|
|
1213
1213
|
`+`\uD83D\uDCA1 Bash ID: ${Q.id}
|
|
1214
1214
|
`+"⚠️ 使用 TaskOutput/KillShell 管理后台进程";return{success:!0,llmContent:{command:$,background:!0,pid:Q.pid,bash_id:Q.id,shell_id:Q.id},displayContent:K,metadata:q}}async function Oz($,Z,X,Y,Q,J){let G=Date.now();try{let K=await RQ().execute($,{cwd:Z||process.cwd(),env:X,timeout:Y,signal:Q,onOutput:(z)=>{J?.(z)}}),W=Date.now()-G;if(Q.aborted||K.error==="Command was aborted"||K.error==="Command was terminated")return{success:!1,llmContent:"Command execution aborted by user",displayContent:`⚠️ 命令执行被用户中止
|
|
@@ -1226,7 +1226,7 @@ Use the relative_path values above for Read/Edit operations.`;else B=`No files f
|
|
|
1226
1226
|
\uD83D\uDCE4 输出:
|
|
1227
1227
|
${Z.trim()}`;if(X&&X.trim())q+=`
|
|
1228
1228
|
⚠️ 错误输出:
|
|
1229
|
-
${X.trim()}`;return q}var Y5;var YJ=A(()=>{
|
|
1229
|
+
${X.trim()}`;return q}var Y5;var YJ=A(()=>{g4();p0();E$();V2();i4();Y5=e({name:"Bash",displayName:"Bash Command",kind:"execute",schema:X5.object({command:r0.command({description:"Bash command to execute"}),timeout:r0.timeout(1000,300000,30000),cwd:X5.string().optional().describe("Working directory (optional; applies only to this command). To persist, use cd"),env:r0.environment(),run_in_background:X5.boolean().default(!1).describe("Run in background (suitable for long-running commands)")}),description:{short:"Execute bash commands in a persistent shell session with optional timeout",long:`Executes bash commands with proper handling and security measures.
|
|
1230
1230
|
|
|
1231
1231
|
IMPORTANT: This tool is for terminal operations like git, npm, docker, etc. DO NOT use it for file operations (reading, writing, editing, searching, finding files) - use the specialized tools for this instead.
|
|
1232
1232
|
|
|
@@ -1242,13 +1242,13 @@ Before executing commands:
|
|
|
1242
1242
|
* cd "/Users/name/My Documents" (correct)
|
|
1243
1243
|
* cd /Users/name/My Documents (incorrect - will fail)
|
|
1244
1244
|
* python "/path/with spaces/script.py" (correct)
|
|
1245
|
-
* python /path/with spaces/script.py (incorrect - will fail)`,usageNotes:["The command argument is required","You can specify an optional timeout in milliseconds (up to 600000ms / 10 minutes). If not specified, commands will timeout after 30000ms (30 seconds)","It is very helpful if you write a clear, concise description of what this command does in 5-10 words","If the output exceeds 30000 characters, output will be truncated before being returned to you",'You can use the run_in_background parameter to run the command in the background, which allows you to continue working while the command runs. You can monitor the output using the TaskOutput tool. You do not need to use "&" at the end of the command when using this parameter',"Avoid using Bash with the find, grep, cat, head, tail, sed, awk, or echo commands, unless explicitly instructed or when these commands are truly necessary for the task. Instead, always prefer using the dedicated tools for these commands:"," - File search: Use Glob (NOT find or ls)"," - Content search: Use Grep (NOT grep or rg)"," - Read files: Use Read (NOT cat/head/tail)"," - Edit files: Use Edit (NOT sed/awk)"," - Write files: Use Write (NOT echo >/cat <<EOF)"," - Communication: Output text directly (NOT echo/printf)","When issuing multiple commands:",' - If the commands are independent and can run in parallel, make multiple Bash tool calls in a single message. For example, if you need to run "git status" and "git diff", send a single message with two Bash tool calls in parallel',' - If the commands depend on each other and must run sequentially, use a single Bash call with "&&" to chain them together (e.g., git add . && git commit -m "message" && git push). For instance, if one operation must complete before another starts (like mkdir before cp, Write before Bash for git operations, or git add before git commit), run these operations sequentially instead',` - Use ";" only when you need to run commands sequentially but don't care if earlier commands fail`," - DO NOT use newlines to separate commands (newlines are ok in quoted strings)","Try to maintain your current working directory throughout the session by using absolute paths and avoiding usage of cd. You may use cd if the User explicitly requests it"," Good example: pytest /foo/bar/tests"," Bad example: cd /foo/bar && pytest tests"],examples:[{description:"Run a simple command",params:{command:"ls -la",description:"List files in current directory"}},{description:"Temporarily change working directory (this command only)",params:{command:"npm install",cwd:"/path/to/project",description:"Install package dependencies"}},{description:"Persistently change working directory",params:{command:"cd /path/to/project && npm install",description:"Change directory and install dependencies"}},{description:"Run a long-running command in background",params:{command:"npm run dev",run_in_background:!0,description:"Start development server in background"}},{description:"Run multiple independent commands in parallel",params:{command:"git status",description:"Show working tree status"}}],important:["Committing changes with git:"," - Only create commits when requested by the user. If unclear, ask first"," - Git Safety Protocol:"," * NEVER update the git config"," * NEVER run destructive/irreversible git commands (like push --force, hard reset, etc) unless the user explicitly requests them"," * NEVER skip hooks (--no-verify, --no-gpg-sign, etc) unless the user explicitly requests it"," * NEVER run force push to main/master, warn the user if they request it"," * Avoid git commit --amend. ONLY use --amend when either (1) user explicitly requested amend OR (2) adding edits from pre-commit hook",' * Before amending: ALWAYS check authorship (git log -1 --format="%an %ae")'," * NEVER commit changes unless the user explicitly asks you to"," - When creating commits:"," 1. Run git status, git diff, and git log in parallel to understand changes",' 2. Analyze staged changes and draft a concise commit message (1-2 sentences) focusing on "why" rather than "what"'," 3. Add relevant untracked files, create the commit, and run git status to verify"," 4. Always pass commit message via HEREDOC format"," - DO NOT push to remote repository unless explicitly requested"," - NEVER use git commands with the -i flag (no interactive input supported)"," - If no changes to commit, do not create an empty commit","Creating pull requests:"," - Use the gh command for ALL GitHub-related tasks"," - When creating a PR:"," 1. Run git status, git diff, and git log in parallel to understand branch changes"," 2. Analyze all commits (not just the latest) and draft a PR summary"," 3. Create new branch if needed, push with -u flag, and create PR using gh pr create with HEREDOC body format"," - Return the PR URL when done","Other important notes:"," - Dangerous commands (rm -rf, sudo, etc.) require user confirmation"," - Background commands require manual termination using KillShell"," - NEVER use find, grep, cat, sed, etc. — use dedicated tools instead"]},async execute($,Z){let{command:X,timeout:Y=30000,cwd:Q,env:J,run_in_background:G=!1}=$,{updateOutput:q}=Z,K=Z.signal??new AbortController().signal;try{if(q?.(`Executing Bash command: ${X}`),G)return Fz(X,Q,J);if(
|
|
1245
|
+
* python /path/with spaces/script.py (incorrect - will fail)`,usageNotes:["The command argument is required","You can specify an optional timeout in milliseconds (up to 600000ms / 10 minutes). If not specified, commands will timeout after 30000ms (30 seconds)","It is very helpful if you write a clear, concise description of what this command does in 5-10 words","If the output exceeds 30000 characters, output will be truncated before being returned to you",'You can use the run_in_background parameter to run the command in the background, which allows you to continue working while the command runs. You can monitor the output using the TaskOutput tool. You do not need to use "&" at the end of the command when using this parameter',"Avoid using Bash with the find, grep, cat, head, tail, sed, awk, or echo commands, unless explicitly instructed or when these commands are truly necessary for the task. Instead, always prefer using the dedicated tools for these commands:"," - File search: Use Glob (NOT find or ls)"," - Content search: Use Grep (NOT grep or rg)"," - Read files: Use Read (NOT cat/head/tail)"," - Edit files: Use Edit (NOT sed/awk)"," - Write files: Use Write (NOT echo >/cat <<EOF)"," - Communication: Output text directly (NOT echo/printf)","When issuing multiple commands:",' - If the commands are independent and can run in parallel, make multiple Bash tool calls in a single message. For example, if you need to run "git status" and "git diff", send a single message with two Bash tool calls in parallel',' - If the commands depend on each other and must run sequentially, use a single Bash call with "&&" to chain them together (e.g., git add . && git commit -m "message" && git push). For instance, if one operation must complete before another starts (like mkdir before cp, Write before Bash for git operations, or git add before git commit), run these operations sequentially instead',` - Use ";" only when you need to run commands sequentially but don't care if earlier commands fail`," - DO NOT use newlines to separate commands (newlines are ok in quoted strings)","Try to maintain your current working directory throughout the session by using absolute paths and avoiding usage of cd. You may use cd if the User explicitly requests it"," Good example: pytest /foo/bar/tests"," Bad example: cd /foo/bar && pytest tests"],examples:[{description:"Run a simple command",params:{command:"ls -la",description:"List files in current directory"}},{description:"Temporarily change working directory (this command only)",params:{command:"npm install",cwd:"/path/to/project",description:"Install package dependencies"}},{description:"Persistently change working directory",params:{command:"cd /path/to/project && npm install",description:"Change directory and install dependencies"}},{description:"Run a long-running command in background",params:{command:"npm run dev",run_in_background:!0,description:"Start development server in background"}},{description:"Run multiple independent commands in parallel",params:{command:"git status",description:"Show working tree status"}}],important:["Committing changes with git:"," - Only create commits when requested by the user. If unclear, ask first"," - Git Safety Protocol:"," * NEVER update the git config"," * NEVER run destructive/irreversible git commands (like push --force, hard reset, etc) unless the user explicitly requests them"," * NEVER skip hooks (--no-verify, --no-gpg-sign, etc) unless the user explicitly requests it"," * NEVER run force push to main/master, warn the user if they request it"," * Avoid git commit --amend. ONLY use --amend when either (1) user explicitly requested amend OR (2) adding edits from pre-commit hook",' * Before amending: ALWAYS check authorship (git log -1 --format="%an %ae")'," * NEVER commit changes unless the user explicitly asks you to"," - When creating commits:"," 1. Run git status, git diff, and git log in parallel to understand changes",' 2. Analyze staged changes and draft a concise commit message (1-2 sentences) focusing on "why" rather than "what"'," 3. Add relevant untracked files, create the commit, and run git status to verify"," 4. Always pass commit message via HEREDOC format"," - DO NOT push to remote repository unless explicitly requested"," - NEVER use git commands with the -i flag (no interactive input supported)"," - If no changes to commit, do not create an empty commit","Creating pull requests:"," - Use the gh command for ALL GitHub-related tasks"," - When creating a PR:"," 1. Run git status, git diff, and git log in parallel to understand branch changes"," 2. Analyze all commits (not just the latest) and draft a PR summary"," 3. Create new branch if needed, push with -u flag, and create PR using gh pr create with HEREDOC body format"," - Return the PR URL when done","Other important notes:"," - Dangerous commands (rm -rf, sudo, etc.) require user confirmation"," - Background commands require manual termination using KillShell"," - NEVER use find, grep, cat, sed, etc. — use dedicated tools instead"]},async execute($,Z){let{command:X,timeout:Y=30000,cwd:Q,env:J,run_in_background:G=!1}=$,{updateOutput:q}=Z,K=Z.signal??new AbortController().signal;try{if(q?.(`Executing Bash command: ${X}`),G)return Fz(X,Q,J);if(R2())return q?.("通过 IDE 终端执行命令..."),Oz(X,Q,J,Y,K,q);else return zz(X,Q,J,Y,K,q)}catch(W){let U=W;if(U.name==="AbortError")return{success:!1,llmContent:"Command execution aborted",displayContent:"⚠️ 命令执行被用户中止",error:{type:"execution_error",message:"Operation aborted"}};return{success:!1,llmContent:`Command execution failed: ${U.message}`,displayContent:`❌ 命令执行失败: ${U.message}`,error:{type:"execution_error",message:U.message,details:U}}}},version:"2.0.0",category:"命令工具",tags:["bash","shell","non-interactive","event-driven"],extractSignatureContent:($)=>{return $.command.trim()},abstractPermissionRule:($)=>{let X=$.command.trim().split(/\s+/);if(X.length===1)return X[0];if(["run","exec","test","start","build","dev"].includes(X[1])){if(X.length===2)return`${X[0]} ${X[1]}`;return`${X[0]} ${X[1]} *`}if(X.length===2)return`${X[0]} ${X[1]}`;return`${X[0]} ${X[1]} *`}})});import{z as QJ}from"zod";var Q5;var JJ=A(()=>{p0();E$();i4();Q5=e({name:"KillShell",displayName:"终止后台 Shell",kind:"execute",schema:QJ.object({shell_id:QJ.string().min(1).describe("Background Shell ID to terminate")}),description:{short:"Kills a running background bash shell by its ID",long:`
|
|
1246
1246
|
- Kills a running background bash shell by its ID
|
|
1247
1247
|
- Takes a shell_id parameter identifying the shell to kill
|
|
1248
1248
|
- Returns a success or failure status
|
|
1249
1249
|
- Use this tool when you need to terminate a long-running shell
|
|
1250
1250
|
- Shell IDs can be found using the /tasks command
|
|
1251
|
-
`},async execute($,Z){let Y=T$.getInstance().kill($.shell_id);if(!Y)return{success:!1,llmContent:`Shell not found: ${$.shell_id}`,displayContent:`❌ 未找到 Shell: ${$.shell_id}`,error:{type:"execution_error",message:"Shell ID 不存在或已清理"}};if(!Y.success&&!Y.alreadyExited){let J={...Y};return{success:!1,llmContent:`Failed to terminate Shell: ${$.shell_id}`,displayContent:`❌ 无法终止 Shell (${$.shell_id})`,error:{type:"execution_error",message:"发送终止信号失败"},metadata:J}}let Q=Y.alreadyExited?`Shell ${$.shell_id} 已经处于 ${Y.status} 状态`:`已向 Shell ${$.shell_id} 发送终止信号`;return{success:!0,llmContent:{shell_id:$.shell_id,status:Y.status,already_exited:Y.alreadyExited,pid:Y.pid,exit_code:Y.exitCode,signal:Y.signal},displayContent:Y.alreadyExited?`ℹ️ ${Q}`:`✂️ ${Q}`,metadata:{...Y}}},version:"1.0.0",category:"命令工具",tags:["bash","shell","terminate"],extractSignatureContent:($)=>$.shell_id,abstractPermissionRule:()=>"*"})});var GJ=A(()=>{YJ();JJ()});import{z as
|
|
1251
|
+
`},async execute($,Z){let Y=T$.getInstance().kill($.shell_id);if(!Y)return{success:!1,llmContent:`Shell not found: ${$.shell_id}`,displayContent:`❌ 未找到 Shell: ${$.shell_id}`,error:{type:"execution_error",message:"Shell ID 不存在或已清理"}};if(!Y.success&&!Y.alreadyExited){let J={...Y};return{success:!1,llmContent:`Failed to terminate Shell: ${$.shell_id}`,displayContent:`❌ 无法终止 Shell (${$.shell_id})`,error:{type:"execution_error",message:"发送终止信号失败"},metadata:J}}let Q=Y.alreadyExited?`Shell ${$.shell_id} 已经处于 ${Y.status} 状态`:`已向 Shell ${$.shell_id} 发送终止信号`;return{success:!0,llmContent:{shell_id:$.shell_id,status:Y.status,already_exited:Y.alreadyExited,pid:Y.pid,exit_code:Y.exitCode,signal:Y.signal},displayContent:Y.alreadyExited?`ℹ️ ${Q}`:`✂️ ${Q}`,metadata:{...Y}}},version:"1.0.0",category:"命令工具",tags:["bash","shell","terminate"],extractSignatureContent:($)=>$.shell_id,abstractPermissionRule:()=>"*"})});var GJ=A(()=>{YJ();JJ()});import{z as M2}from"zod";var qJ;var KJ=A(()=>{U1();p0();w$();qJ=e({name:"AddTask",displayName:"Add Task",kind:"write",schema:M2.object({title:M2.string().min(1).describe("Brief title of the task"),description:M2.string().min(1).describe("Detailed description of what needs to be done"),complexity:M2.enum(["low","medium","high"]).optional().default("medium").describe("Estimated complexity of the task"),affectedFiles:M2.array(M2.string()).optional().default([]).describe("List of files that will be modified by this task"),dependencies:M2.array(M2.string()).optional().default([]).describe("IDs of tasks that must be completed before this one")}),description:{short:"Add a task to the current Spec project",long:`Use this tool to add tasks to the current Spec-Driven Development project.
|
|
1252
1252
|
|
|
1253
1253
|
## Task Structure
|
|
1254
1254
|
|
|
@@ -1694,7 +1694,7 @@ ${Z}
|
|
|
1694
1694
|
|
|
1695
1695
|
---
|
|
1696
1696
|
|
|
1697
|
-
Remember: Follow the above instructions carefully to complete the user's request.`}var U5;var yJ=A(()=>{
|
|
1697
|
+
Remember: Follow the above instructions carefully to complete the user's request.`}var U5;var yJ=A(()=>{X2();p0();w$();U5=e({name:"Skill",displayName:"Skill",kind:"execute",schema:W5.object({skill:W5.string().describe('The skill name. E.g., "commit-message" or "code-review"'),args:W5.string().optional().describe("Optional arguments for the skill")}),description:{short:"Execute a skill within the main conversation",long:`Execute a skill within the main conversation
|
|
1698
1698
|
|
|
1699
1699
|
<skills_instructions>
|
|
1700
1700
|
When users ask you to perform tasks, check if any of the available skills below can help complete the task more effectively. Skills provide specialized capabilities and domain knowledge.
|
|
@@ -1715,7 +1715,7 @@ Important:
|
|
|
1715
1715
|
</available_skills>
|
|
1716
1716
|
`},async execute($,Z){let{skill:X}=$,Y=b$();if(!Y.has(X))return{success:!1,llmContent:`Skill "${X}" not found. Available skills: ${Y.getAll().map((G)=>G.name).join(", ")||"none"}`,displayContent:`❌ Skill "${X}" not found`,error:{type:"validation_error",message:`Skill "${X}" is not registered`}};let Q=await Y.loadContent(X);if(!Q)return{success:!1,llmContent:`Failed to load skill "${X}" content`,displayContent:`❌ Failed to load skill "${X}"`,error:{type:"execution_error",message:`Could not read SKILL.md for "${X}"`}};return{success:!0,llmContent:Az(Q.metadata.name,Q.instructions,Q.metadata.basePath),displayContent:`<command-message>The "${X}" skill is loading</command-message>`,metadata:{skillName:X,basePath:Q.metadata.basePath,version:Q.metadata.version,allowedTools:Q.metadata.allowedTools}}}})});import{execSync as Rz}from"node:child_process";import vJ from"node:fs";import EJ from"node:path";class H5{async execute($,Z){let X=$.content;if(Z.signal?.aborted)throw Error("Command execution aborted");return X=this.interpolateArgs(X,Z.args),X=await this.executeBashEmbeds(X,Z),X=await this.resolveFileReferences(X,Z.workspaceRoot),X}interpolateArgs($,Z){$=$.replace(/\$ARGUMENTS/g,Z.join(" "));for(let X=9;X>=1;X--){let Y=`$${X}`,Q=Z[X-1]??"";$=$.split(Y).join(Q)}return $}async executeBashEmbeds($,Z){let X=/!`([^`]+)`/g,Y=[];for(let J of $.matchAll(X))Y.push({match:J[0],command:J[1]});let Q=$;for(let{match:J,command:G}of Y){if(Z.signal?.aborted){Q=Q.replace(J,"[Execution aborted]");continue}try{let q=Rz(G,{cwd:Z.workspaceRoot,encoding:"utf-8",timeout:30000,maxBuffer:1048576,stdio:["pipe","pipe","pipe"]}).trim();Q=Q.replace(J,q)}catch(q){let K=q instanceof Error?q.message:String(q);Q=Q.replace(J,`[Error executing '${G}': ${K}]`)}}return Q}async resolveFileReferences($,Z){let X=/@([\w./-]+(?:\/[\w./-]+|\.[\w]+))/g,Y=[];for(let J of $.matchAll(X))Y.push({match:J[0],relativePath:J[1]});let Q=$;for(let{match:J,relativePath:G}of Y){let q=EJ.resolve(Z,G);try{if(vJ.statSync(q).isFile()){let W=vJ.readFileSync(q,"utf-8"),H=`\`\`\`${EJ.extname(G).slice(1)||"text"}
|
|
1717
1717
|
${W}
|
|
1718
|
-
\`\`\``;Q=Q.replace(J,H)}}catch{}}return Q}hasDynamicContent($){return{hasArgs:/\$ARGUMENTS|\$\d/.test($),hasBashEmbeds:/!`[^`]+`/.test($),hasFileRefs:/@[\w./-]+(?:\/[\w./-]+|\.[\w]+)/.test($)}}}var PJ=()=>{};import Vz from"node:fs";import TJ from"node:path";import Dz from"gray-matter";class F5{parse($,Z,X,Y){try{let Q=Vz.readFileSync($,"utf-8"),{data:J,content:G}=Dz(Q),{name:q,namespace:K}=this.extractNameAndNamespace($,Z);if(!q)return null;return{name:q,namespace:K,config:this.normalizeConfig(J),content:G.trim(),path:$,source:X,sourceDir:Y}}catch(Q){return console.error(`Failed to parse command file: ${$}`,Q),null}}normalizeConfig($){return{description:this.asString($.description),allowedTools:this.parseAllowedTools($["allowed-tools"]),argumentHint:this.asString($["argument-hint"]),model:this.asString($.model),disableModelInvocation:$["disable-model-invocation"]===!0}}asString($){if(typeof $==="string"&&$.trim())return $.trim();return}parseAllowedTools($){if(!$)return;if(Array.isArray($))return $.map((Z)=>String(Z).trim()).filter(Boolean);if(typeof $==="string")return $.split(",").map((Z)=>Z.trim()).filter(Boolean);return}extractNameAndNamespace($,Z){let Y=TJ.relative(Z,$).split(TJ.sep),Q=Y.pop();if(!Q)return{name:""};let J=Q.replace(/\.md$/i,""),G=Y.length>0?Y.join("/"):void 0;return{name:J,namespace:G}}validateConfig($){let Z=[];if($.model&&!this.isValidModelId($.model))Z.push(`Invalid model ID: ${$.model}`);return Z}isValidModelId($){return $.length>0&&$.length<200}}var SJ=()=>{};import O5 from"node:fs";import CJ from"node:os";import
|
|
1718
|
+
\`\`\``;Q=Q.replace(J,H)}}catch{}}return Q}hasDynamicContent($){return{hasArgs:/\$ARGUMENTS|\$\d/.test($),hasBashEmbeds:/!`[^`]+`/.test($),hasFileRefs:/@[\w./-]+(?:\/[\w./-]+|\.[\w]+)/.test($)}}}var PJ=()=>{};import Vz from"node:fs";import TJ from"node:path";import Dz from"gray-matter";class F5{parse($,Z,X,Y){try{let Q=Vz.readFileSync($,"utf-8"),{data:J,content:G}=Dz(Q),{name:q,namespace:K}=this.extractNameAndNamespace($,Z);if(!q)return null;return{name:q,namespace:K,config:this.normalizeConfig(J),content:G.trim(),path:$,source:X,sourceDir:Y}}catch(Q){return console.error(`Failed to parse command file: ${$}`,Q),null}}normalizeConfig($){return{description:this.asString($.description),allowedTools:this.parseAllowedTools($["allowed-tools"]),argumentHint:this.asString($["argument-hint"]),model:this.asString($.model),disableModelInvocation:$["disable-model-invocation"]===!0}}asString($){if(typeof $==="string"&&$.trim())return $.trim();return}parseAllowedTools($){if(!$)return;if(Array.isArray($))return $.map((Z)=>String(Z).trim()).filter(Boolean);if(typeof $==="string")return $.split(",").map((Z)=>Z.trim()).filter(Boolean);return}extractNameAndNamespace($,Z){let Y=TJ.relative(Z,$).split(TJ.sep),Q=Y.pop();if(!Q)return{name:""};let J=Q.replace(/\.md$/i,""),G=Y.length>0?Y.join("/"):void 0;return{name:J,namespace:G}}validateConfig($){let Z=[];if($.model&&!this.isValidModelId($.model))Z.push(`Invalid model ID: ${$.model}`);return Z}isValidModelId($){return $.length>0&&$.length<200}}var SJ=()=>{};import O5 from"node:fs";import CJ from"node:os";import Y2 from"node:path";class z5{parser=new F5;async discover($){let Z=[],X=[],Y=[],Q=this.getSearchDirs($);for(let J of Q){if(!O5.existsSync(J.path))continue;X.push(J.path);try{let G=await this.scanDirectory(J.path);for(let q of G)try{let K=this.parser.parse(q,J.path,J.source,J.sourceDir);if(K)Z.push(K)}catch(K){Y.push({path:q,error:K instanceof Error?K.message:String(K)})}}catch(G){Y.push({path:J.path,error:G instanceof Error?G.message:String(G)})}}return{commands:Z,scannedDirs:X,errors:Y}}getSearchDirs($){let Z=CJ.homedir();return[{path:Y2.join(Z,".blade","commands"),source:"user",sourceDir:"blade"},{path:Y2.join(Z,".claude","commands"),source:"user",sourceDir:"claude"},{path:Y2.join($,".blade","commands"),source:"project",sourceDir:"blade"},{path:Y2.join($,".claude","commands"),source:"project",sourceDir:"claude"}]}async scanDirectory($){let Z=[],X=async(Y)=>{let Q=await O5.promises.readdir(Y,{withFileTypes:!0});for(let J of Q){let G=Y2.join(Y,J.name);if(J.isDirectory())await X(G);else if(J.isFile()&&J.name.endsWith(".md"))Z.push(G)}};return await X($),Z}async hasCommands($){let Z=this.getSearchDirs($);for(let X of Z){if(!O5.existsSync(X.path))continue;if((await this.scanDirectory(X.path)).length>0)return!0}return!1}getCommandDirs($){let Z=CJ.homedir();return{projectBlade:Y2.join($,".blade","commands"),projectClaude:Y2.join($,".claude","commands"),userBlade:Y2.join(Z,".blade","commands"),userClaude:Y2.join(Z,".claude","commands")}}}var kJ=A(()=>{SJ()});class B${static instance;commands=new Map;pluginCommands=new Map;loader=new z5;executor=new H5;initialized=!1;workspaceRoot="";lastDiscoveryResult=null;static getInstance(){if(!B$.instance)B$.instance=new B$;return B$.instance}static resetInstance(){B$.instance=new B$}constructor(){}async initialize($){this.workspaceRoot=$;let Z=await this.loader.discover($);this.lastDiscoveryResult=Z,this.commands.clear();for(let X of Z.commands)this.commands.set(X.name,X);return this.initialized=!0,Z}async refresh(){if(!this.workspaceRoot)throw Error("Registry not initialized. Call initialize() first.");return this.initialize(this.workspaceRoot)}isInitialized(){return this.initialized}getCommand($){return this.commands.get($)}hasCommand($){return this.commands.has($)}getAllCommands(){return Array.from(this.commands.values())}getCommandCount(){return this.commands.size}getModelInvocableCommands(){return this.getAllCommands().filter(($)=>$.config.description&&!$.config.disableModelInvocation)}async executeCommand($,Z){let X=this.getCommand($);if(!X)return null;return this.executor.execute(X,Z)}getCommandLabel($){let Z=$.source==="project"?"project":"user";if($.namespace)return`(${Z}:${$.namespace})`;return`(${Z})`}getCommandDisplayName($){let Z=[`/${$.name}`];if($.config.argumentHint)Z.push($.config.argumentHint);if($.config.description)Z.push("-",$.config.description);return Z.push(this.getCommandLabel($)),Z.join(" ")}getCommandsBySource(){let $=[],Z=[];for(let X of this.commands.values())if(X.source==="project")$.push(X);else Z.push(X);return{project:$,user:Z}}getLastDiscoveryResult(){return this.lastDiscoveryResult}getCommandDirs(){if(!this.workspaceRoot)return null;return this.loader.getCommandDirs(this.workspaceRoot)}generateCommandListDescription($=15000){let Z=this.getModelInvocableCommands(),X=Z.length;if(X===0)return{text:"No custom commands available.",includedCount:0,totalCount:0};let Y=`Available custom commands:
|
|
1719
1719
|
|
|
1720
1720
|
`,Q=Y.length,J=0;for(let G of Z){let q=this.getCommandLabel(G),K=G.config.argumentHint?` ${G.config.argumentHint}`:"",W=`- /${G.name}${K}: ${G.config.description} ${q}
|
|
1721
1721
|
`;if(Q+W.length>$)break;Y+=W,Q+=W.length,J++}if(J<X)Y+=`
|
|
@@ -1763,7 +1763,7 @@ Notes:
|
|
|
1763
1763
|
- Only custom slash commands with descriptions are listed in Available Commands
|
|
1764
1764
|
- Commands with \`disable-model-invocation: true\` cannot be invoked by this tool
|
|
1765
1765
|
- If a command is not listed, ask the user to check the slash command file
|
|
1766
|
-
${jz()}`},async execute($,Z){let{command:X,arguments:Y}=$,Q=B$.getInstance();if(!Q.isInitialized())return{success:!1,llmContent:"Custom command system not initialized. Please wait for the application to fully initialize.",displayContent:"❌ Custom command system not initialized",error:{type:"execution_error",message:"CustomCommandRegistry not initialized"}};let J=Q.getCommand(X);if(!J){let q=Q.getModelInvocableCommands().map((K)=>`/${K.name}`).join(", ");return{success:!1,llmContent:`Command "/${X}" not found. Available commands: ${q||"none"}`,displayContent:`❌ Command "/${X}" not found`,error:{type:"validation_error",message:`Command "/${X}" is not registered`}}}if(J.config.disableModelInvocation)return{success:!1,llmContent:`Command "/${X}" has disabled model invocation. This command can only be executed by the user directly.`,displayContent:`❌ Command "/${X}" disabled for AI`,error:{type:"permission_denied",message:`Command "/${X}" has disable-model-invocation: true`}};if(!J.config.description)return{success:!1,llmContent:`Command "/${X}" does not have a description and cannot be invoked by AI. Add a description in the command's frontmatter to enable AI invocation.`,displayContent:`❌ Command "/${X}" has no description`,error:{type:"validation_error",message:`Command "/${X}" missing description for AI invocation`}};let G=Y?Y.split(/\s+/).filter(Boolean):[];try{let q=await Q.executeCommand(X,{args:G,workspaceRoot:process.cwd()});if(!q)return{success:!1,llmContent:`Failed to execute command "/${X}"`,displayContent:`❌ Failed to execute "/${X}"`,error:{type:"execution_error",message:"Command execution returned null"}};return{success:!0,llmContent:Iz(J.name,q,J.config),displayContent:`<command-message>/${X} is running...</command-message>`,metadata:{commandName:X,allowedTools:J.config.allowedTools,model:J.config.model,source:J.source,namespace:J.namespace}}}catch(q){let K=q instanceof Error?q.message:String(q);return{success:!1,llmContent:`Error executing command "/${X}": ${K}`,displayContent:`❌ Error executing "/${X}"`,error:{type:"execution_error",message:K}}}}})});var hJ=A(()=>{IJ();yJ();fJ()});import
|
|
1766
|
+
${jz()}`},async execute($,Z){let{command:X,arguments:Y}=$,Q=B$.getInstance();if(!Q.isInitialized())return{success:!1,llmContent:"Custom command system not initialized. Please wait for the application to fully initialize.",displayContent:"❌ Custom command system not initialized",error:{type:"execution_error",message:"CustomCommandRegistry not initialized"}};let J=Q.getCommand(X);if(!J){let q=Q.getModelInvocableCommands().map((K)=>`/${K.name}`).join(", ");return{success:!1,llmContent:`Command "/${X}" not found. Available commands: ${q||"none"}`,displayContent:`❌ Command "/${X}" not found`,error:{type:"validation_error",message:`Command "/${X}" is not registered`}}}if(J.config.disableModelInvocation)return{success:!1,llmContent:`Command "/${X}" has disabled model invocation. This command can only be executed by the user directly.`,displayContent:`❌ Command "/${X}" disabled for AI`,error:{type:"permission_denied",message:`Command "/${X}" has disable-model-invocation: true`}};if(!J.config.description)return{success:!1,llmContent:`Command "/${X}" does not have a description and cannot be invoked by AI. Add a description in the command's frontmatter to enable AI invocation.`,displayContent:`❌ Command "/${X}" has no description`,error:{type:"validation_error",message:`Command "/${X}" missing description for AI invocation`}};let G=Y?Y.split(/\s+/).filter(Boolean):[];try{let q=await Q.executeCommand(X,{args:G,workspaceRoot:process.cwd()});if(!q)return{success:!1,llmContent:`Failed to execute command "/${X}"`,displayContent:`❌ Failed to execute "/${X}"`,error:{type:"execution_error",message:"Command execution returned null"}};return{success:!0,llmContent:Iz(J.name,q,J.config),displayContent:`<command-message>/${X} is running...</command-message>`,metadata:{commandName:X,allowedTools:J.config.allowedTools,model:J.config.model,source:J.source,namespace:J.namespace}}}catch(q){let K=q instanceof Error?q.message:String(q);return{success:!1,llmContent:`Error executing command "/${X}": ${K}`,displayContent:`❌ Error executing "/${X}"`,error:{type:"execution_error",message:K}}}}})});var hJ=A(()=>{IJ();yJ();fJ()});import j2 from"node:fs";import yz from"node:os";import xJ from"node:path";class Q4{static instance=null;sessionsDir;cache=new Map;constructor(){this.sessionsDir=xJ.join(yz.homedir(),".blade","agents","sessions"),this.ensureDirectory()}static getInstance(){if(!Q4.instance)Q4.instance=new Q4;return Q4.instance}ensureDirectory(){if(!j2.existsSync(this.sessionsDir))j2.mkdirSync(this.sessionsDir,{recursive:!0})}getSessionPath($){let Z=$.replace(/[^a-zA-Z0-9_-]/g,"_");return xJ.join(this.sessionsDir,`${Z}.json`)}saveSession($){try{let Z=this.getSessionPath($.id),X=JSON.stringify($,null,2);j2.writeFileSync(Z,X,"utf-8"),this.cache.set($.id,$),a4.debug(`Session saved: ${$.id}`)}catch(Z){a4.warn(`Failed to save session ${$.id}:`,Z)}}loadSession($){if(this.cache.has($))return this.cache.get($);try{let Z=this.getSessionPath($);if(!j2.existsSync(Z))return;let X=j2.readFileSync(Z,"utf-8"),Y=JSON.parse(X);return this.cache.set($,Y),Y}catch(Z){a4.warn(`Failed to load session ${$}:`,Z);return}}updateSession($,Z){let X=this.loadSession($);if(!X)return;let Y={...X,...Z,lastActiveAt:Date.now()};return this.saveSession(Y),Y}appendMessages($,Z){let X=this.loadSession($);if(!X)return;return this.updateSession($,{messages:[...X.messages,...Z]})}markCompleted($,Z,X){return this.updateSession($,{status:Z.success?"completed":"failed",result:Z,stats:X,completedAt:Date.now()})}deleteSession($){try{let Z=this.getSessionPath($);if(j2.existsSync(Z))j2.unlinkSync(Z);return this.cache.delete($),!0}catch(Z){return a4.warn(`Failed to delete session ${$}:`,Z),!1}}listSessions(){try{let $=j2.readdirSync(this.sessionsDir),Z=[];for(let X of $){if(!X.endsWith(".json"))continue;let Y=X.replace(".json",""),Q=this.loadSession(Y);if(Q)Z.push(Q)}return Z.sort((X,Y)=>Y.lastActiveAt-X.lastActiveAt)}catch($){return a4.warn("Failed to list sessions:",$),[]}}listRunningSessions(){return this.listSessions().filter(($)=>$.status==="running")}cleanupExpiredSessions($=604800000){let Z=Date.now(),X=this.listSessions(),Y=0;for(let Q of X){if(Q.status==="running")continue;if(Z-Q.lastActiveAt>$){if(this.deleteSession(Q.id))Y++}}if(Y>0)a4.info(`Cleaned up ${Y} expired agent sessions`);return Y}clearCache(){this.cache.clear()}}var a4;var pJ=A(()=>{B0();a4=i("Agent")});import{randomUUID as vz}from"crypto";class $1{static instance=null;runningAgents=new Map;sessionStore=Q4.getInstance();constructor(){this.cleanupOrphanedSessions()}static getInstance(){if(!$1.instance)$1.instance=new $1;return $1.instance}cleanupOrphanedSessions(){let $=this.sessionStore.listSessions(),Z=Date.now(),X=1800000;for(let Y of $)if(Y.status==="running"){let Q=this.runningAgents.has(Y.id),J=Z-Y.lastActiveAt;if(!Q||J>1800000)J4.warn(`Cleaning up orphaned agent session: ${Y.id}`),this.sessionStore.updateSession(Y.id,{status:"failed",result:{success:!1,message:"",error:"Session was orphaned (process restart or timeout)"},completedAt:Z})}}startBackgroundAgent($){let{config:Z,description:X,prompt:Y,parentSessionId:Q,permissionMode:J,agentId:G,existingMessages:q}=$,K=G||`agent_${vz()}`,W=new AbortController,U={id:K,subagentType:Z.name,description:X,prompt:Y,messages:q||[],status:"running",createdAt:Date.now(),lastActiveAt:Date.now(),parentSessionId:Q};this.sessionStore.saveSession(U);let H=Date.now(),F=this.executeAgent(K,Z,Y,Q,J,W.signal,q);return this.runningAgents.set(K,{id:K,promise:F,abortController:W,startTime:H}),F.finally(()=>{this.runningAgents.delete(K)}),J4.info(`Background agent started: ${K} (${Z.name})`),K}async executeAgent($,Z,X,Y,Q,J,G){let q=Date.now();try{if(J.aborted)throw Error("Agent execution was cancelled");let K=Z.systemPrompt||"",W=await z$.create({systemPrompt:K,toolWhitelist:Z.tools}),U={messages:G||[],userId:"subagent",sessionId:Y||`subagent_${$}`,workspaceRoot:process.cwd(),permissionMode:Q},H=await W.runAgenticLoop(X,U,{signal:J});this.sessionStore.updateSession($,{messages:U.messages});let F=Date.now()-q,O=H.success?{success:!0,message:H.finalMessage||"",stats:{tokens:H.metadata?.tokensUsed||0,toolCalls:H.metadata?.toolCallsCount||0,duration:F}}:{success:!1,message:"",error:H.error?.message||"Unknown error",stats:{duration:F}};return this.sessionStore.markCompleted($,{success:O.success,message:O.message,error:O.error},O.stats),J4.info(`Background agent completed: ${$} (success=${O.success})`),O}catch(K){let W=Date.now()-q,U=K instanceof Error?K.message:String(K);return this.sessionStore.markCompleted($,{success:!1,message:"",error:U},{duration:W}),J4.warn(`Background agent failed: ${$}`,K),{success:!1,message:"",error:U,stats:{duration:W}}}}getAgent($){return this.sessionStore.loadSession($)}isRunning($){return this.runningAgents.has($)}async waitForCompletion($,Z=30000){let X=this.runningAgents.get($);if(!X)return this.sessionStore.loadSession($);if(Z>0){let Y=new Promise((J)=>setTimeout(()=>J("timeout"),Z));if(await Promise.race([X.promise,Y])==="timeout")return this.sessionStore.loadSession($)}else await X.promise;return this.sessionStore.loadSession($)}resumeAgent($,Z,X,Y,Q){let J=this.sessionStore.loadSession($);if(!J){J4.warn(`Cannot resume agent ${$}: session not found`);return}if(this.isRunning($)){J4.warn(`Cannot resume agent ${$}: still running`);return}return this.startBackgroundAgent({config:X,description:J.description,prompt:Z,parentSessionId:Y||J.parentSessionId,permissionMode:Q,agentId:$,existingMessages:J.messages})}killAgent($){let Z=this.runningAgents.get($);if(!Z){let X=this.sessionStore.loadSession($);if(X&&X.status==="running")this.sessionStore.updateSession($,{status:"cancelled"});return!1}return Z.abortController.abort(),this.sessionStore.updateSession($,{status:"cancelled"}),J4.info(`Background agent cancelled: ${$}`),!0}listAll(){return this.sessionStore.listSessions()}listRunning(){return this.sessionStore.listRunningSessions()}getRunningCount(){return this.runningAgents.size}killAll(){for(let[$]of this.runningAgents)this.killAgent($)}cleanupExpiredSessions($){return this.sessionStore.cleanupExpiredSessions($)}}var J4;var L6=A(()=>{B0();Q2();pJ();J4=i("Agent")});class w5{config;constructor($){this.config=$}async execute($){let Z=Date.now();try{let X=this.buildSystemPrompt($),Y=await z$.create({systemPrompt:X,toolWhitelist:this.config.tools}),Q=[{role:"user",content:$.prompt}],J="",G=0,q=0,K=await Y.runAgenticLoop($.prompt,{messages:[],userId:"subagent",sessionId:$.parentSessionId||`subagent_${Date.now()}`,workspaceRoot:process.cwd(),permissionMode:$.permissionMode});if(K.success)J=K.finalMessage||"",G=K.metadata?.toolCallsCount||0,q=K.metadata?.tokensUsed||0;else throw Error(K.error?.message||"Subagent execution failed");let W=Date.now()-Z;return{success:!0,message:J,stats:{tokens:q,toolCalls:G,duration:W}}}catch(X){let Y=Date.now()-Z;return{success:!1,message:"",error:X instanceof Error?X.message:String(X),stats:{duration:Y}}}}buildSystemPrompt($){return this.config.systemPrompt||""}}var dJ=A(()=>{Q2()});var N5;var mJ=A(()=>{N5=[{name:"general-purpose",description:"General-purpose agent for researching complex questions, searching for code, and executing multi-step tasks. When you are searching for a keyword or file and are not confident that you will find the right match in the first few tries use this agent to perform the search for you.",tools:[]},{name:"Explore",description:'Fast agent specialized for exploring codebases. Use this when you need to quickly find files by patterns (eg. "src/components/**/*.tsx"), search code for keywords (eg. "API endpoints"), or answer questions about the codebase (eg. "how do API endpoints work?"). When calling this agent, specify the desired thoroughness level: "quick" for basic searches, "medium" for moderate exploration, or "very thorough" for comprehensive analysis across multiple locations and naming conventions.',tools:["Glob","Grep","Read","WebFetch","WebSearch"],systemPrompt:`# Explore Subagent
|
|
1767
1767
|
|
|
1768
1768
|
You are a specialized code exploration agent. Your job is to **directly execute searches** using the tools available to you.
|
|
1769
1769
|
|
|
@@ -1830,9 +1830,9 @@ You are a software architect specializing in implementation planning.
|
|
|
1830
1830
|
**Risks**:
|
|
1831
1831
|
- [Potential issue and mitigation]
|
|
1832
1832
|
|
|
1833
|
-
Be thorough but concise. Focus on actionable steps.`},{name:"statusline-setup",description:"Use this agent to configure the user's Claude Code status line setting.",tools:["Read","Edit"]}]});function uJ($){switch($){case"default":case"ignore":case void 0:return"default";case"acceptEdits":return"autoEdit";case"dontAsk":case"bypassPermissions":return"yolo";case"plan":return"plan";default:return"default"}}var gJ=A(()=>{U$()});import b5 from"node:fs";import w6 from"node:os";import
|
|
1833
|
+
Be thorough but concise. Focus on actionable steps.`},{name:"statusline-setup",description:"Use this agent to configure the user's Claude Code status line setting.",tools:["Read","Edit"]}]});function uJ($){switch($){case"default":case"ignore":case void 0:return"default";case"acceptEdits":return"autoEdit";case"dontAsk":case"bypassPermissions":return"yolo";case"plan":return"plan";default:return"default"}}var gJ=A(()=>{U$()});import b5 from"node:fs";import w6 from"node:os";import J2 from"node:path";import Ez from"yaml";class cJ{subagents=new Map;register($){if(this.subagents.has($.name))throw Error(`Subagent '${$.name}' already registered`);this.subagents.set($.name,$)}getSubagent($){return this.subagents.get($)}getAllNames(){return Array.from(this.subagents.keys())}getAllSubagents(){return Array.from(this.subagents.values())}getDescriptionsForPrompt(){let $=this.getAllSubagents();if($.length===0)return"No subagents available.";return`Available agent types and the tools they have access to:
|
|
1834
1834
|
${$.map((X)=>{let Y=!X.tools||X.tools.length===0?"All tools":X.tools.join(", ");return`- ${X.name}: ${X.description} (Tools: ${Y})`}).join(`
|
|
1835
|
-
`)}`}loadFromDirectory($,Z){if(!b5.existsSync($))return;let X=b5.readdirSync($);for(let Y of X){if(!Y.endsWith(".md"))continue;let Q=
|
|
1835
|
+
`)}`}loadFromDirectory($,Z){if(!b5.existsSync($))return;let X=b5.readdirSync($);for(let Y of X){if(!Y.endsWith(".md"))continue;let Q=J2.join($,Y);try{let J=this.parseConfigFile(Q,Z);this.subagents.set(J.name,J)}catch(J){A5.warn(`Failed to load subagent config from ${Q}:`,J)}}}parseConfigFile($,Z){let Y=b5.readFileSync($,"utf-8").match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n([\s\S]*)$/);if(!Y)throw Error(`No YAML frontmatter found in ${$}`);let[,Q,J]=Y,G=Ez.parse(Q);if(!G.name||!G.description)throw Error(`Missing required fields (name, description) in ${$}`);let q=J.trim(),K=this.parseStringOrArray(G.tools),W=this.parseStringOrArray(G.skills),U=uJ(G.permissionMode);return{name:G.name,description:G.description,systemPrompt:q,tools:K,color:G.color,configPath:$,model:G.model||"inherit",permissionMode:U,skills:W,source:Z}}parseStringOrArray($){if(!$)return;if(Array.isArray($))return $.map((Z)=>Z.trim()).filter(Boolean);return $.split(",").map((Z)=>Z.trim()).filter(Boolean)}loadFromStandardLocations(){this.loadBuiltinAgents();let $=J2.join(w6.homedir(),".claude","agents");this.loadFromDirectory($,"claude-code-user");let Z=J2.join(process.cwd(),".claude","agents");this.loadFromDirectory(Z,"claude-code-project");let X=J2.join(w6.homedir(),".blade","agents");this.loadFromDirectory(X,"blade-user");let Y=J2.join(process.cwd(),".blade","agents");this.loadFromDirectory(Y,"blade-project");let Q=this.getAllNames().length;return A5.debug(`\uD83D\uDCE6 Loaded ${Q} subagents from standard locations`),Q}loadBuiltinAgents(){for(let $ of N5)this.subagents.set($.name,{...$,model:$.model||"inherit",source:"builtin"});A5.debug(`Loaded ${N5.length} builtin subagents`)}clear(){this.subagents.clear()}getSubagentsBySource(){let $={builtin:[],"claude-code-user":[],"claude-code-project":[],"blade-user":[],"blade-project":[],plugin:[]};for(let Z of this.subagents.values()){let X=Z.source||"builtin",Y=X.startsWith("plugin:")?"plugin":X;$[Y].push(Z)}return $}clearPluginAgents(){let $=[];for(let[Z,X]of this.subagents.entries())if(X.source?.startsWith("plugin:"))$.push(Z);for(let Z of $)this.subagents.delete(Z)}static getClaudeCodeAgentsDir($){if($==="user")return J2.join(w6.homedir(),".claude","agents");return J2.join(process.cwd(),".claude","agents")}static getBladeAgentsDir($){if($==="user")return J2.join(w6.homedir(),".blade","agents");return J2.join(process.cwd(),".blade","agents")}}var A5,J$;var G4=A(()=>{B0();mJ();gJ();A5=i("Agent");J$=new cJ});import{z as r4}from"zod";function Pz(){let $=J$.getAllNames();if($.length===0)return["Explore"];return $}function Tz(){return`
|
|
1836
1836
|
## Task
|
|
1837
1837
|
|
|
1838
1838
|
Launch a new agent to handle complex, multi-step tasks autonomously.
|
|
@@ -1880,7 +1880,7 @@ Agent 仍在运行中,请使用 TaskOutput 获取结果`,error:{type:"executio
|
|
|
1880
1880
|
`+`类型: ${X.name}
|
|
1881
1881
|
`+`任务: ${Y}
|
|
1882
1882
|
|
|
1883
|
-
`+"\uD83D\uDCA1 使用 TaskOutput 工具获取结果",metadata:{agent_id:q,resumed_from:$,subagent_type:X.name,description:Y,background:!0}}}var R5;var lJ=A(()=>{L6();dJ();
|
|
1883
|
+
`+"\uD83D\uDCA1 使用 TaskOutput 工具获取结果",metadata:{agent_id:q,resumed_from:$,subagent_type:X.name,description:Y,background:!0}}}var R5;var lJ=A(()=>{L6();dJ();G4();U$();r$();p0();E$();R5=e({name:"Task",displayName:"Subagent Scheduler",kind:"readonly",isReadOnly:!0,schema:r4.object({subagent_type:r4.enum(Pz()).describe('Subagent type to use (e.g., "Explore", "Plan")'),description:r4.string().min(3).max(100).describe("Short task description (3-5 words)"),prompt:r4.string().min(10).describe("Detailed task instructions"),run_in_background:r4.boolean().default(!1).describe("Set to true to run this agent in the background. Use TaskOutput to read the output later."),resume:r4.string().optional().describe("Optional agent ID to resume from. If provided, the agent will continue from the previous execution transcript.")}),description:{short:"Launch a new agent to handle complex, multi-step tasks autonomously",get long(){return Tz()},usageNotes:["subagent_type is required - choose from available agent types",'description should be 3-5 words (e.g., "Explore error handling")',"prompt should contain a highly detailed task description and specify exactly what information to return","Launch multiple agents concurrently when possible for better performance"],examples:[{description:"Explore codebase for API endpoints",params:{subagent_type:"Explore",description:"Find API endpoints",prompt:"Search the codebase for all API endpoint definitions. Look for route handlers, REST endpoints, and GraphQL resolvers. Return a structured list with file paths, endpoint URLs, HTTP methods, and descriptions."}},{description:"Plan authentication feature",params:{subagent_type:"Plan",description:"Plan user auth",prompt:"Create a detailed implementation plan for adding user authentication to this project. Analyze the existing architecture, then provide step-by-step instructions including: 1) Database schema changes 2) API routes to create 3) Frontend components needed 4) Security considerations 5) Testing strategy. Be specific about file names and code locations."}}]},async execute($,Z){let{subagent_type:X,description:Y,prompt:Q,run_in_background:J=!1,resume:G}=$,{updateOutput:q}=Z;try{let K=J$.getAllNames(),W=J$.getSubagent(X);if(!W)return{success:!1,llmContent:`Unknown subagent type: ${X}. Available types: ${K.join(", ")||"none"}`,displayContent:`❌ 未知的 subagent 类型: ${X}
|
|
1884
1884
|
|
|
1885
1885
|
可用类型: ${K.join(", ")||"无"}`,error:{type:"execution_error",message:`Unknown subagent type: ${X}`}};if(G)return Cz(G,Q,W,Y,Z);if(J)return Sz(W,Y,Q,Z);q?.(`\uD83D\uDE80 启动 ${X} subagent: ${Y}`);let U=new w5(W),H={prompt:Q,parentSessionId:Z.sessionId,permissionMode:Z.permissionMode};q?.("⚙️ 执行任务中...");let F=Date.now(),O=await U.execute(H),z=Date.now()-F;try{let B=await M0.getInstance().executeSubagentStopHooks(X,{projectDir:process.cwd(),sessionId:Z.sessionId||"unknown",permissionMode:Z.permissionMode||"default",taskDescription:Y,success:O.success,resultSummary:O.message.slice(0,500),error:O.error});if(!B.shouldStop&&B.continueReason){console.log(`[Task] SubagentStop hook 阻止停止,继续执行: ${B.continueReason}`);let L={prompt:B.continueReason,parentSessionId:Z.sessionId,permissionMode:Z.permissionMode},w=Date.now();O=await U.execute(L),z+=Date.now()-w}if(B.warning)console.warn(`[Task] SubagentStop hook warning: ${B.warning}`)}catch(_){console.warn("[Task] SubagentStop hook execution failed:",_)}if(O.success){let _=O.message.length>1000?O.message.slice(0,1000)+`
|
|
1886
1886
|
...(截断)`:O.message;return{success:!0,llmContent:O.message,displayContent:`✅ Subagent 任务完成
|
|
@@ -1919,7 +1919,7 @@ ${J.stderr}`:"");return{success:!0,llmContent:G,displayContent:K,metadata:G}}asy
|
|
|
1919
1919
|
`:"")+(Q.result?.message?`
|
|
1920
1920
|
结果:
|
|
1921
1921
|
${Q.result.message}`:"")+(Q.result?.error?`
|
|
1922
|
-
错误: ${Q.result.error}`:"");return{success:!0,llmContent:J,displayContent:q,metadata:J}}async function kz($,Z){let X=T$.getInstance(),Y=Date.now();return new Promise((Q)=>{let J=setInterval(()=>{let G=X.getProcess($);if(!G||G.status!=="running"){clearInterval(J),Q();return}if(Date.now()-Y>=Z){clearInterval(J),Q();return}},100)})}function rJ($){switch($){case"running":return"⏳";case"completed":case"exited":return"✅";case"failed":case"error":return"❌";case"killed":case"cancelled":return"✂️";default:return"❓"}}var V5;var nJ=A(()=>{L6();p0();E$();
|
|
1922
|
+
错误: ${Q.result.error}`:"");return{success:!0,llmContent:J,displayContent:q,metadata:J}}async function kz($,Z){let X=T$.getInstance(),Y=Date.now();return new Promise((Q)=>{let J=setInterval(()=>{let G=X.getProcess($);if(!G||G.status!=="running"){clearInterval(J),Q();return}if(Date.now()-Y>=Z){clearInterval(J),Q();return}},100)})}function rJ($){switch($){case"running":return"⏳";case"completed":case"exited":return"✅";case"failed":case"error":return"❌";case"killed":case"cancelled":return"✂️";default:return"❓"}}var V5;var nJ=A(()=>{L6();p0();E$();i4();V5=e({name:"TaskOutput",displayName:"Task Output",kind:"readonly",schema:N6.object({task_id:N6.string().min(1).describe("The task ID to get output from"),block:N6.boolean().default(!0).describe("Whether to wait for completion"),timeout:N6.number().min(0).max(600000).default(30000).describe("Max wait time in ms")}),description:{short:"Retrieves output from a running or completed task",long:`
|
|
1923
1923
|
- Retrieves output from a running or completed task (background shell, agent, or remote session)
|
|
1924
1924
|
- Takes a task_id parameter identifying the task
|
|
1925
1925
|
- Returns the task output along with status information
|
|
@@ -1931,7 +1931,7 @@ ${Q.result.message}`:"")+(Q.result?.error?`
|
|
|
1931
1931
|
|
|
1932
1932
|
任务 ID 格式:
|
|
1933
1933
|
- bash_xxx: 后台 shell
|
|
1934
|
-
- agent_xxx: 后台 agent`,error:{type:"validation_error",message:`Unknown task ID: ${X}`}}}},version:"1.0.0",category:"Task",tags:["task","output","background","shell","agent"],extractSignatureContent:($)=>$.task_id,abstractPermissionRule:()=>"*"})});var oJ=A(()=>{lJ();nJ()});import{randomUUID as fz}from"crypto";import*as
|
|
1934
|
+
- agent_xxx: 后台 agent`,error:{type:"validation_error",message:`Unknown task ID: ${X}`}}}},version:"1.0.0",category:"Task",tags:["task","output","background","shell","agent"],extractSignatureContent:($)=>$.task_id,abstractPermissionRule:()=>"*"})});var oJ=A(()=>{lJ();nJ()});import{randomUUID as fz}from"crypto";import*as n4 from"fs/promises";import*as b6 from"path";var q4;var sJ=A(()=>{q4=class q4{static instances=new Map;todos=[];filePath;loaded=!1;constructor($,Z){this.filePath=b6.join(Z,"todos",`${$}-agent-${$}.json`)}static getInstance($,Z){let X=`${$}-${Z}`;if(!q4.instances.has(X))q4.instances.set(X,new q4($,Z));return q4.instances.get(X)}validate($){if($.filter((X)=>X.status==="in_progress").length>1)return{valid:!1,error:"同时只能有一个任务处于 in_progress 状态"};return{valid:!0}}async updateTodos($){await this.ensureLoaded();let Z=new Date().toISOString(),X=$.map((Q)=>{let J=Q,G=this.todos.find((q)=>q.id===J.id||q.content===Q.content);return{...Q,id:J.id||G?.id||fz(),priority:Q.priority||G?.priority||"medium",createdAt:G?.createdAt||Z,startedAt:Q.status==="in_progress"&&!G?.startedAt?Z:G?.startedAt,completedAt:Q.status==="completed"&&!G?.completedAt?Z:G?.completedAt}}),Y=this.validate(X);if(!Y.valid)throw Error(Y.error);this.todos=X,await this.saveTodos()}getSortedTodos(){let $={completed:0,in_progress:1,pending:2},Z={high:0,medium:1,low:2};return[...this.todos].sort((X,Y)=>{let Q=$[X.status]-$[Y.status];if(Q!==0)return Q;return Z[X.priority]-Z[Y.priority]})}getTodos(){return this.getSortedTodos()}async ensureLoaded(){if(!this.loaded)await this.loadTodos(),this.loaded=!0}async loadTodos(){try{let $=await n4.readFile(this.filePath,"utf-8");this.todos=JSON.parse($)}catch($){if($.code==="ENOENT")this.todos=[];else console.warn("加载 TODO 列表失败:",$),this.todos=[]}}async saveTodos(){try{await n4.mkdir(b6.dirname(this.filePath),{recursive:!0}),await n4.writeFile(this.filePath,JSON.stringify(this.todos,null,2),"utf-8")}catch($){throw console.error("保存 TODO 列表失败:",$),$}}}});import{z as o4}from"zod";var tJ;var eJ=A(()=>{tJ=o4.object({id:o4.string().optional(),content:o4.string().min(1,"Content cannot be empty"),status:o4.enum(["pending","in_progress","completed"]),activeForm:o4.string().min(1,"ActiveForm cannot be empty"),priority:o4.enum(["high","medium","low"]).default("medium")})});import{z as $G}from"zod";function D5($){let{sessionId:Z,configDir:X}=$;return e({name:"TodoWrite",displayName:"Todo Write",kind:"readonly",schema:$G.object({todos:$G.array(tJ).min(1,"At least one task is required")}),description:{short:"Use this tool to create and manage a structured task list for your current coding session",long:`Use this tool to create and manage a structured task list for your current coding session. This helps you track progress, organize complex tasks, and demonstrate thoroughness to the user.
|
|
1935
1935
|
It also helps the user understand the progress of the task and overall progress of their requests.
|
|
1936
1936
|
|
|
1937
1937
|
## When to Use This Tool
|
|
@@ -1992,16 +1992,16 @@ NOTE that you should not use this tool if there is only one trivial task to do.
|
|
|
1992
1992
|
- activeForm: "Fixing authentication bug"
|
|
1993
1993
|
|
|
1994
1994
|
When in doubt, use this tool. Being proactive with task management demonstrates attentiveness and ensures you complete all requirements successfully.
|
|
1995
|
-
`},async execute(Y,Q){let{todos:J}=Y,{updateOutput:G}=Q;try{let q=Q.sessionId||Z,K=
|
|
1995
|
+
`},async execute(Y,Q){let{todos:J}=Y,{updateOutput:G}=Q;try{let q=Q.sessionId||Z,K=q4.getInstance(q,X);G?.("Updating TODO list..."),await K.updateTodos(J);let W=K.getTodos(),U=hz(W),H=xz(W,U);return G?.(`✅ TODO list updated (${U.completed}/${U.total} completed)`),{success:!0,llmContent:{todos:W,stats:U},displayContent:H,metadata:{stats:U}}}catch(q){return{success:!1,llmContent:`Update failed: ${q.message}`,displayContent:`❌ 更新 TODO 列表失败: ${q.message}`,error:{type:"execution_error",message:q.message,details:q}}}},version:"1.0.0",category:"TODO tools",tags:["todo","task","management","planning"],extractSignatureContent:(Y)=>`${Y.todos.length} todos`,abstractPermissionRule:()=>"*"})}function hz($){return{total:$.length,completed:$.filter((Z)=>Z.status==="completed").length,inProgress:$.filter((Z)=>Z.status==="in_progress").length,pending:$.filter((Z)=>Z.status==="pending").length}}function xz($,Z){let X=[],Y=Z.total>0?Math.round(Z.completed/Z.total*100):0;if(X.push(`\uD83D\uDCCB TODO 列表 (${Z.completed}/${Z.total} 完成,${Y}%)`),X.push(""),$.length===0)return X.push(" (暂无任务)"),X.join(`
|
|
1996
1996
|
`);for(let Q of $){let J=Q.status==="completed"?"☑":"☐",G=`(P${Q.priority==="high"?0:Q.priority==="medium"?1:2})`,q=Q.status==="in_progress"?" ⚡":"",K=Q.status==="completed"?"~~":"";X.push(` ${J} ${G} ${K}${Q.content}${K}${q}`)}return X.join(`
|
|
1997
|
-
`)}var ZG=A(()=>{p0();E$();sJ();eJ()});var XG=A(()=>{ZG()});import{z as
|
|
1997
|
+
`)}var ZG=A(()=>{p0();E$();sJ();eJ()});var XG=A(()=>{ZG()});import{z as G2}from"zod";import{isPlainObject as QG}from"lodash-es";function JG($){if(!QG($))return;let Z=$;return typeof Z.name==="string"?Z.name:void 0}function pz($){if($ instanceof Error)return $.message;if(typeof $==="string")return $;if(QG($)){let Z=$;if(typeof Z.message==="string")return Z.message}return String($)}async function dz($){let{url:Z,method:X,headers:Y,body:Q,timeout:J,follow_redirects:G,max_redirects:q,signal:K}=$,W={"User-Agent":"Blade-AI/1.0",...Y},U=Z,H=X,F=Q,O=0,z=[];while(!0){let _={...W};if(F&&H!=="GET"&&H!=="HEAD"&&!iz(_,"content-type"))_["Content-Type"]="application/json";let B=await gz(U,{method:H,headers:_,body:F&&H!=="GET"&&H!=="HEAD"?F:void 0,redirect:"manual"},J,K),L=B.headers.get("location"),w=B.status>=300&&B.status<400,R=G&&w&&L&&O<q;if(w&&G&&!L)throw Error(`收到状态码 ${B.status} 但响应缺少 Location 头`);if(w&&G&&O>=q)throw Error(`超过最大重定向次数 (${q})`);if(R&&L){O++;let I=cz(L,U);if(z.push(`${B.status} → ${I}`),B.status===303||(B.status===301||B.status===302)&&H!=="GET"&&H!=="HEAD")H="GET",F=void 0;U=I;continue}let D=await B.text(),V=lz(B.headers);return{status:B.status,status_text:B.statusText,headers:V,body:D,url:B.url||U,redirected:O>0,redirect_count:O,redirect_chain:z,content_type:V["content-type"],response_time:0}}}function YG($,Z,X){let{url:Y,method:Q,status:J,response_time:G,content_length:q}=Z,K=X?`❌ ${Q} ${Y} - ${J} ${$.status_text}`:`✅ ${Q} ${Y} - ${J} ${$.status_text}`;if(K+=`
|
|
1998
1998
|
响应时间: ${G}ms`,K+=`
|
|
1999
1999
|
内容长度: ${q} 字节`,Z.content_type)K+=`
|
|
2000
2000
|
Content-Type: ${Z.content_type}`;if($.redirected&&Z.final_url&&Z.final_url!==Y){if(K+=`
|
|
2001
2001
|
最终URL: ${Z.final_url}`,Z.redirect_count)K+=`
|
|
2002
2002
|
重定向次数: ${Z.redirect_count}`}let W=mz($.body,$.content_type);if(W)K+=`
|
|
2003
2003
|
响应内容:
|
|
2004
|
-
${W}`;return K}function mz($,Z){if(!$)return"(空响应)";if(uz(Z,$))return"[binary content omitted]";let X=$.trim();if(!X)return"(仅包含空白字符)";return X.length>800?`${X.slice(0,800)}...`:X}function uz($,Z){if($){let Q=$.toLowerCase();if(["image/","audio/","video/","application/pdf","application/zip","application/octet-stream"].some((G)=>Q.startsWith(G)))return!0}if(!Z)return!1;let X=0,Y=Math.min(Z.length,200);for(let Q=0;Q<Y;Q++){let J=Z.charCodeAt(Q);if(J===9||J===10||J===13)continue;if(J<32||J>126)X++}return X/(Y||1)>0.3}async function gz($,Z,X,Y){let Q=new AbortController,J=setTimeout(()=>Q.abort(),X),G=()=>Q.abort();Y?.addEventListener("abort",G);try{return await fetch($,{...Z,signal:Q.signal})}catch(q){if(JG(q)==="AbortError"){if(q instanceof Error)throw q.message="请求被中止或超时",q;let K=Error("请求被中止或超时");throw K.name="AbortError",K}throw q}finally{clearTimeout(J),Y?.removeEventListener("abort",G)}}function cz($,Z){try{return new URL($,Z).toString()}catch{return $}}function lz($){let Z={};return $.forEach((X,Y)=>{Z[Y.toLowerCase()]=X}),Z}function iz($,Z){let X=Z.toLowerCase();return Object.keys($).some((Y)=>Y.toLowerCase()===X)}var M5;var GG=A(()=>{p0();E$();
|
|
2004
|
+
${W}`;return K}function mz($,Z){if(!$)return"(空响应)";if(uz(Z,$))return"[binary content omitted]";let X=$.trim();if(!X)return"(仅包含空白字符)";return X.length>800?`${X.slice(0,800)}...`:X}function uz($,Z){if($){let Q=$.toLowerCase();if(["image/","audio/","video/","application/pdf","application/zip","application/octet-stream"].some((G)=>Q.startsWith(G)))return!0}if(!Z)return!1;let X=0,Y=Math.min(Z.length,200);for(let Q=0;Q<Y;Q++){let J=Z.charCodeAt(Q);if(J===9||J===10||J===13)continue;if(J<32||J>126)X++}return X/(Y||1)>0.3}async function gz($,Z,X,Y){let Q=new AbortController,J=setTimeout(()=>Q.abort(),X),G=()=>Q.abort();Y?.addEventListener("abort",G);try{return await fetch($,{...Z,signal:Q.signal})}catch(q){if(JG(q)==="AbortError"){if(q instanceof Error)throw q.message="请求被中止或超时",q;let K=Error("请求被中止或超时");throw K.name="AbortError",K}throw q}finally{clearTimeout(J),Y?.removeEventListener("abort",G)}}function cz($,Z){try{return new URL($,Z).toString()}catch{return $}}function lz($){let Z={};return $.forEach((X,Y)=>{Z[Y.toLowerCase()]=X}),Z}function iz($,Z){let X=Z.toLowerCase();return Object.keys($).some((Y)=>Y.toLowerCase()===X)}var M5;var GG=A(()=>{p0();E$();V2();M5=e({name:"WebFetch",displayName:"Web Fetch",kind:"readonly",schema:G2.object({url:G2.string().url().describe("URL to request"),method:G2.enum(["GET","POST","PUT","DELETE","HEAD"]).default("GET").describe("HTTP method"),headers:G2.record(G2.string()).optional().describe("Request headers (optional)"),body:G2.string().optional().describe("Request body (optional)"),timeout:r0.timeout(1000,120000,30000),follow_redirects:G2.boolean().default(!0).describe("Follow redirects"),max_redirects:G2.number().int().min(0).max(10).default(5).describe("Maximum redirect hops"),return_headers:G2.boolean().default(!1).describe("Return response headers")}),description:{short:"Fetches content from a specified URL and processes it using an AI model",long:`
|
|
2005
2005
|
- Fetches content from a specified URL and processes it using an AI model
|
|
2006
2006
|
- Takes a URL and a prompt as input
|
|
2007
2007
|
- Fetches the URL content, converts HTML to markdown
|
|
@@ -2018,12 +2018,12 @@ Usage notes:
|
|
|
2018
2018
|
- Results may be summarized if the content is very large
|
|
2019
2019
|
- Includes a self-cleaning 15-minute cache for faster responses when repeatedly accessing the same URL
|
|
2020
2020
|
- When a URL redirects to a different host, the tool will inform you and provide the redirect URL in a special format. You should then make a new WebFetch request with the redirect URL to fetch the content.
|
|
2021
|
-
`},async execute($,Z){let{url:X,method:Y="GET",headers:Q={},body:J,timeout:G=30000,follow_redirects:q=!0,max_redirects:K=5,return_headers:W=!1}=$,{updateOutput:U}=Z,H=Z.signal??new AbortController().signal;try{U?.(`发送 ${Y} 请求到: ${X}`);let F=Date.now(),O=await dz({url:X,method:Y,headers:Q,body:J,timeout:G,follow_redirects:q,max_redirects:K,signal:H}),z=Date.now()-F;if(O.response_time=z,!W)delete O.headers;let _={url:X,method:Y,status:O.status,response_time:z,content_length:Buffer.byteLength(O.body||"","utf8"),redirected:O.redirected||!1,redirect_count:O.redirect_count??0,final_url:O.url,content_type:O.content_type,redirect_chain:O.redirect_chain};if(O.status>=400)return{success:!1,llmContent:`HTTP error ${O.status}: ${O.status_text}`,displayContent:YG(O,_,!0),error:{type:"execution_error",message:`HTTP error ${O.status}: ${O.status_text}`,details:{..._,response_body:O.body}},metadata:_};return{success:!0,llmContent:O,displayContent:YG(O,_,!1),metadata:_}}catch(F){if(JG(F)==="AbortError")return{success:!1,llmContent:"Request aborted",displayContent:"⚠️ 请求被用户中止",error:{type:"execution_error",message:"操作被中止"}};let O=pz(F);return{success:!1,llmContent:`Network request failed: ${O}`,displayContent:`❌ 网络请求失败: ${O}`,error:{type:"execution_error",message:O,details:F}}}},version:"2.0.0",category:"网络工具",tags:["web","http","fetch","request","api"],extractSignatureContent:($)=>{try{return`domain:${new URL($.url).hostname}`}catch{return $.url}},abstractPermissionRule:($)=>{try{return`domain:${new URL($.url).hostname}`}catch{return"*"}}})});function az($){return $.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,'"').replace(/'/g,"'")}function qG($){let Z=az($).trim();if(!Z.includes(" - "))return{title:Z,snippet:Z};let[X,...Y]=Z.split(" - "),Q=X.trim(),J=Y.join(" - ").trim()||Z;return{title:Q,snippet:J}}function j5($){try{let Z=new URL($),X=Z.pathname==="/"?"":Z.pathname;return`${Z.hostname}${X}`}catch{return $}}function I5($){try{return new URL($).hostname.toLowerCase()}catch{return""}}function rz($){if(!$.FirstURL||!$.Text)return null;let{title:Z,snippet:X}=qG($.Text);return{title:Z,snippet:X,url:$.FirstURL,display_url:j5($.FirstURL),source:I5($.FirstURL)}}function KG($){let Z=[];for(let X of $){if(X.Topics&&X.Topics.length>0){Z.push(...KG(X.Topics));continue}if(X.FirstURL&&X.Text){let{title:Y,snippet:Q}=qG(X.Text);Z.push({title:Y,snippet:Q,url:X.FirstURL,display_url:j5(X.FirstURL),source:I5(X.FirstURL)})}}return Z}function nz($){let Z=$,X=(Z.Results??[]).map((Q)=>rz(Q)).filter((Q)=>Q!==null),Y=KG(Z.RelatedTopics??[]);return[...X,...Y]}function sz($){let Z=$,X=[];for(let Y of Z.results??[]){if(!Y.url||!Y.title)continue;X.push({title:Y.title,snippet:Y.content||Y.title,url:Y.url,display_url:j5(Y.url),source:I5(Y.url)})}return X}function tz($){return{name:`SearXNG(${(()=>{try{return new URL($).hostname}catch{return $}})()})`,endpoint:$,buildUrl:(X)=>{let Y=new URL(`${$}/search`);return Y.searchParams.set("q",X),Y.searchParams.set("format","json"),Y.searchParams.set("categories","general"),Y.toString()},parseResponse:sz,getHeaders:()=>({Accept:"application/json","User-Agent":"Blade-AI-WebSearch/1.0"})}}function UG(){return[oz,...WG.map(tz)]}function HG(){return 1+WG.length}var oz,WG;var FG=A(()=>{oz={name:"DuckDuckGo",endpoint:"https://duckduckgo.com/",buildUrl:($)=>{let Z=new URL("https://duckduckgo.com/");return Z.searchParams.set("q",$),Z.searchParams.set("format","json"),Z.searchParams.set("no_html","1"),Z.searchParams.set("skip_disambig","1"),Z.searchParams.set("t","blade-code"),Z.searchParams.set("kl","us-en"),Z.toString()},parseResponse:nz,getHeaders:()=>({Accept:"application/json, text/plain;q=0.9","User-Agent":"Blade-AI-WebSearch/1.0"})};WG=["https://searx.be","https://search.ononoki.org","https://searx.tiekoetter.com","https://searx.work"]});import{ProxyAgent as ez,fetch as $_}from"undici";import{z as
|
|
2021
|
+
`},async execute($,Z){let{url:X,method:Y="GET",headers:Q={},body:J,timeout:G=30000,follow_redirects:q=!0,max_redirects:K=5,return_headers:W=!1}=$,{updateOutput:U}=Z,H=Z.signal??new AbortController().signal;try{U?.(`发送 ${Y} 请求到: ${X}`);let F=Date.now(),O=await dz({url:X,method:Y,headers:Q,body:J,timeout:G,follow_redirects:q,max_redirects:K,signal:H}),z=Date.now()-F;if(O.response_time=z,!W)delete O.headers;let _={url:X,method:Y,status:O.status,response_time:z,content_length:Buffer.byteLength(O.body||"","utf8"),redirected:O.redirected||!1,redirect_count:O.redirect_count??0,final_url:O.url,content_type:O.content_type,redirect_chain:O.redirect_chain};if(O.status>=400)return{success:!1,llmContent:`HTTP error ${O.status}: ${O.status_text}`,displayContent:YG(O,_,!0),error:{type:"execution_error",message:`HTTP error ${O.status}: ${O.status_text}`,details:{..._,response_body:O.body}},metadata:_};return{success:!0,llmContent:O,displayContent:YG(O,_,!1),metadata:_}}catch(F){if(JG(F)==="AbortError")return{success:!1,llmContent:"Request aborted",displayContent:"⚠️ 请求被用户中止",error:{type:"execution_error",message:"操作被中止"}};let O=pz(F);return{success:!1,llmContent:`Network request failed: ${O}`,displayContent:`❌ 网络请求失败: ${O}`,error:{type:"execution_error",message:O,details:F}}}},version:"2.0.0",category:"网络工具",tags:["web","http","fetch","request","api"],extractSignatureContent:($)=>{try{return`domain:${new URL($.url).hostname}`}catch{return $.url}},abstractPermissionRule:($)=>{try{return`domain:${new URL($.url).hostname}`}catch{return"*"}}})});function az($){return $.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,'"').replace(/'/g,"'")}function qG($){let Z=az($).trim();if(!Z.includes(" - "))return{title:Z,snippet:Z};let[X,...Y]=Z.split(" - "),Q=X.trim(),J=Y.join(" - ").trim()||Z;return{title:Q,snippet:J}}function j5($){try{let Z=new URL($),X=Z.pathname==="/"?"":Z.pathname;return`${Z.hostname}${X}`}catch{return $}}function I5($){try{return new URL($).hostname.toLowerCase()}catch{return""}}function rz($){if(!$.FirstURL||!$.Text)return null;let{title:Z,snippet:X}=qG($.Text);return{title:Z,snippet:X,url:$.FirstURL,display_url:j5($.FirstURL),source:I5($.FirstURL)}}function KG($){let Z=[];for(let X of $){if(X.Topics&&X.Topics.length>0){Z.push(...KG(X.Topics));continue}if(X.FirstURL&&X.Text){let{title:Y,snippet:Q}=qG(X.Text);Z.push({title:Y,snippet:Q,url:X.FirstURL,display_url:j5(X.FirstURL),source:I5(X.FirstURL)})}}return Z}function nz($){let Z=$,X=(Z.Results??[]).map((Q)=>rz(Q)).filter((Q)=>Q!==null),Y=KG(Z.RelatedTopics??[]);return[...X,...Y]}function sz($){let Z=$,X=[];for(let Y of Z.results??[]){if(!Y.url||!Y.title)continue;X.push({title:Y.title,snippet:Y.content||Y.title,url:Y.url,display_url:j5(Y.url),source:I5(Y.url)})}return X}function tz($){return{name:`SearXNG(${(()=>{try{return new URL($).hostname}catch{return $}})()})`,endpoint:$,buildUrl:(X)=>{let Y=new URL(`${$}/search`);return Y.searchParams.set("q",X),Y.searchParams.set("format","json"),Y.searchParams.set("categories","general"),Y.toString()},parseResponse:sz,getHeaders:()=>({Accept:"application/json","User-Agent":"Blade-AI-WebSearch/1.0"})}}function UG(){return[oz,...WG.map(tz)]}function HG(){return 1+WG.length}var oz,WG;var FG=A(()=>{oz={name:"DuckDuckGo",endpoint:"https://duckduckgo.com/",buildUrl:($)=>{let Z=new URL("https://duckduckgo.com/");return Z.searchParams.set("q",$),Z.searchParams.set("format","json"),Z.searchParams.set("no_html","1"),Z.searchParams.set("skip_disambig","1"),Z.searchParams.set("t","blade-code"),Z.searchParams.set("kl","us-en"),Z.toString()},parseResponse:nz,getHeaders:()=>({Accept:"application/json, text/plain;q=0.9","User-Agent":"Blade-AI-WebSearch/1.0"})};WG=["https://searx.be","https://search.ononoki.org","https://searx.tiekoetter.com","https://searx.work"]});import{ProxyAgent as ez,fetch as $_}from"undici";import{z as s4}from"zod";function Y_(){let $=process.env.HTTPS_PROXY||process.env.HTTP_PROXY||process.env.https_proxy||process.env.http_proxy;if($)try{return new ez($)}catch(Z){console.warn(`Invalid proxy URL: ${$}`)}return}async function Q_($,Z,X,Y,Q){let J=new AbortController,G=setTimeout(()=>J.abort(),X),q=()=>J.abort();Y?.addEventListener("abort",q);try{return await $_($,{...Z,signal:J.signal,dispatcher:Q})}catch(K){if(K.name==="AbortError")throw Error("搜索请求超时或被中止");throw K}finally{clearTimeout(G),Y?.removeEventListener("abort",q)}}async function J_($,Z,X,Y,Q,J){let G=null;for(let q=0;q<Y3.maxRetries;q++)try{return await Q_($,Z,X,Y,Q)}catch(K){if(G=K,Y?.aborted)throw K;if(q<Y3.maxRetries-1){let W=Math.min(Y3.baseDelay*Math.pow(2,q),Y3.maxDelay);J?.(`⏳ 请求失败,${W/1000}s 后重试 (${q+1}/${Y3.maxRetries})...`),await new Promise((U)=>setTimeout(U,W))}}throw G}async function G_($,Z,X,Y,Q,J){let G=$.buildUrl(Z),q=await J_(G,{headers:$.getHeaders()},X,Y,Q,J);if(!q.ok)throw Error(`HTTP ${q.status}`);let K=await q.text(),W;try{W=JSON.parse(K)}catch{throw Error("Failed to parse search result JSON")}return{results:$.parseResponse(W),providerName:$.name}}async function q_($,Z,X,Y){let Q=UG(),J=Y_(),G=[];for(let q=0;q<Q.length;q++){let K=Q[q];if(X?.aborted)throw Error("搜索被用户中止");try{return Y?.(`\uD83D\uDD0E 使用 ${K.name} 搜索...`),await G_(K,$,Z,X,J,Y)}catch(W){let U=`${K.name}: ${W.message}`;if(G.push(U),Y?.(`⚠️ ${U}`),q===Q.length-1)throw Error(`所有搜索提供商都失败了:
|
|
2022
2022
|
${G.join(`
|
|
2023
2023
|
`)}`)}}throw Error("No search providers available")}function K_($){try{return new URL($).hostname.toLowerCase()}catch{return null}}function W_($){return $.trim().toLowerCase()}function OG($){if(!$||$.length===0)return[];return $.map(W_).filter(Boolean)}function zG($,Z){return $===Z||$.endsWith(`.${Z}`)}function U_($,Z,X){return $.filter((Y)=>{let Q=K_(Y.url);if(!Q)return!1;if(X.length>0&&X.some((J)=>zG(Q,J)))return!1;if(Z.length>0&&!Z.some((J)=>zG(Q,J)))return!1;return!0})}function H_($,Z,X,Y){let Q=`\uD83D\uDD0E WebSearch("${$}") via ${Y} - 返回 ${Z.length}/${X} 条结果`,J=Z.map((G,q)=>`${q+1}. ${G.title}
|
|
2024
2024
|
${G.display_url}
|
|
2025
2025
|
${G.snippet}`);return[Q,...J].join(`
|
|
2026
|
-
`)}function F_($){let Z=$.trim().toLowerCase();return Z.length>80?Z.slice(0,80):Z}var Z_=15000,X_=8,Y3,y5;var _G=A(()=>{p0();E$();FG();Y3={maxRetries:3,baseDelay:1000,maxDelay:8000};y5=e({name:"WebSearch",displayName:"Web Search",kind:"readonly",schema:
|
|
2026
|
+
`)}function F_($){let Z=$.trim().toLowerCase();return Z.length>80?Z.slice(0,80):Z}var Z_=15000,X_=8,Y3,y5;var _G=A(()=>{p0();E$();FG();Y3={maxRetries:3,baseDelay:1000,maxDelay:8000};y5=e({name:"WebSearch",displayName:"Web Search",kind:"readonly",schema:s4.object({query:s4.string().min(2,"Search query must be at least 2 characters").describe("Search query"),allowed_domains:s4.array(s4.string().min(1)).optional().describe("Return results only from these domains (optional)"),blocked_domains:s4.array(s4.string().min(1)).optional().describe("Exclude results from these domains (optional)")}),description:{short:"Search the web and use the results to inform responses",long:`
|
|
2027
2027
|
- Search the web and use the results to inform responses
|
|
2028
2028
|
- Provides up-to-date information for current events and recent data
|
|
2029
2029
|
- Returns search result information formatted as search result blocks, including links as markdown hyperlinks
|
|
@@ -2051,11 +2051,11 @@ Usage notes:
|
|
|
2051
2051
|
IMPORTANT - Use the correct year in search queries:
|
|
2052
2052
|
- You MUST use the current year when searching for recent information, documentation, or current events.
|
|
2053
2053
|
- Example: If the user asks for "latest React docs", search for "React documentation 2025", NOT "React documentation 2024"
|
|
2054
|
-
`},async execute($,Z){let{query:X}=$,Y=OG($.allowed_domains),Q=OG($.blocked_domains),{updateOutput:J}=Z,G=Z.signal??new AbortController().signal;J?.(`\uD83D\uDD0E Searching: "${X}" (${HG()} providers available)`);try{let{results:q,providerName:K}=await q_(X,Z_,G,J),W=U_(q,Y,Q),U=W.slice(0,X_),H={query:X,results:U,provider:K,total_results:W.length,fetched_at:new Date().toISOString()},F={query:X,provider:K,fetched_at:H.fetched_at,total_results:W.length,returned_results:U.length,allowed_domains:Y,blocked_domains:Q};if(U.length===0)return{success:!0,llmContent:H,displayContent:`\uD83D\uDD0D WebSearch("${X}") via ${K} - 未找到匹配结果`,metadata:F};return{success:!0,llmContent:H,displayContent:H_(X,U,W.length,K),metadata:F}}catch(q){return{success:!1,llmContent:`WebSearch call failed: ${q.message}`,displayContent:`❌ WebSearch 调用失败: ${q.message}`,error:{type:"execution_error",message:q.message,details:{query:X,allowedDomains:Y,blockedDomains:Q}}}}},version:"2.0.0",category:"网络工具",tags:["web","search","internet","news"],extractSignatureContent:($)=>`search:${F_($.query)}`,abstractPermissionRule:()=>"search:*"})});var BG=A(()=>{GG();_G()});import*as LG from"os";import*as wG from"path";async function O_(){try{return await N$.getInstance().getAvailableTools()}catch($){return console.warn("MCP协议工具加载失败:",$),[]}}async function NG($){let Z=$?.sessionId||`session_${Date.now()}`,X=$?.configDir||wG.join(LG.homedir(),".blade"),Y=[g7,u7,l7,i7,t7,Z5,Y5,Q5,M5,y5,R5,V5,D5({sessionId:Z,configDir:X}),a7,n7,...MJ,K5,U5,L5],Q=await O_();return[...Y,...Q]}var bG=A(()=>{
|
|
2054
|
+
`},async execute($,Z){let{query:X}=$,Y=OG($.allowed_domains),Q=OG($.blocked_domains),{updateOutput:J}=Z,G=Z.signal??new AbortController().signal;J?.(`\uD83D\uDD0E Searching: "${X}" (${HG()} providers available)`);try{let{results:q,providerName:K}=await q_(X,Z_,G,J),W=U_(q,Y,Q),U=W.slice(0,X_),H={query:X,results:U,provider:K,total_results:W.length,fetched_at:new Date().toISOString()},F={query:X,provider:K,fetched_at:H.fetched_at,total_results:W.length,returned_results:U.length,allowed_domains:Y,blocked_domains:Q};if(U.length===0)return{success:!0,llmContent:H,displayContent:`\uD83D\uDD0D WebSearch("${X}") via ${K} - 未找到匹配结果`,metadata:F};return{success:!0,llmContent:H,displayContent:H_(X,U,W.length,K),metadata:F}}catch(q){return{success:!1,llmContent:`WebSearch call failed: ${q.message}`,displayContent:`❌ WebSearch 调用失败: ${q.message}`,error:{type:"execution_error",message:q.message,details:{query:X,allowedDomains:Y,blockedDomains:Q}}}}},version:"2.0.0",category:"网络工具",tags:["web","search","internet","news"],extractSignatureContent:($)=>`search:${F_($.query)}`,abstractPermissionRule:()=>"search:*"})});var BG=A(()=>{GG();_G()});import*as LG from"os";import*as wG from"path";async function O_(){try{return await N$.getInstance().getAvailableTools()}catch($){return console.warn("MCP协议工具加载失败:",$),[]}}async function NG($){let Z=$?.sessionId||`session_${Date.now()}`,X=$?.configDir||wG.join(LG.homedir(),".blade"),Y=[g7,u7,l7,i7,t7,Z5,Y5,Q5,M5,y5,R5,V5,D5({sessionId:Z,configDir:X}),a7,n7,...MJ,K5,U5,L5],Q=await O_();return[...Y,...Q]}var bG=A(()=>{s2();dQ();uQ();aQ();ZJ();GJ();jJ();hJ();oJ();XG();BG()});import{nanoid as z_}from"nanoid";class v5{name="hook";hookManager;constructor(){this.hookManager=M0.getInstance()}async process($){if(!this.hookManager.isEnabled())return;let Z=$._internal.tool;if(!Z)return;try{let X=$.context.messageId||`tool_${z_()}`;$._internal.hookToolUseId=X;let Y=$.context.workspaceRoot||process.cwd(),Q=await this.hookManager.executePreToolHooks(Z.name,X,$.params,{projectDir:Y,sessionId:$.context.sessionId||"unknown",permissionMode:$.context.permissionMode??"default",abortSignal:$.context.signal});if(Q.decision==="deny"){$.abort(Q.reason||"Hook blocked execution");return}if(Q.decision==="ask"){$._internal.needsConfirmation=!0,$._internal.confirmationReason=Q.reason||"Hook requires confirmation";return}if(Q.modifiedInput){let J={...$.params,...Q.modifiedInput};if(Z.build)try{Z.build(J),$.params=J}catch(G){$.abort(`Hook modified parameters are invalid: ${G instanceof Error?G.message:String(G)}`);return}}if(Q.warning)console.warn(`[Hook Warning] ${Q.warning}`)}catch(X){console.error("[HookStage] Error executing hooks:",X)}}}var AG=A(()=>{U$();r$()});import{nanoid as __}from"nanoid";function B_($){return typeof $==="object"&&$!==null&&!Array.isArray($)}class E5{name="post-hook";hookManager;constructor(){this.hookManager=M0.getInstance()}async process($){if(!this.hookManager.isEnabled())return;let Z=$._internal.tool;if(!Z)return;let X=$.getResult();if(!X)return;try{let Y=$._internal.hookToolUseId||$.context.messageId||`tool_${__()}`,Q=$.context.workspaceRoot||process.cwd(),J=await this.hookManager.executePostToolHooks(Z.name,Y,$.params,X,{projectDir:Q,sessionId:$.context.sessionId||"unknown",permissionMode:$.context.permissionMode??"default",abortSignal:$.context.signal});if(J.additionalContext){let G=X.llmContent||X.displayContent||"";X.llmContent=`${G}
|
|
2055
2055
|
|
|
2056
2056
|
---
|
|
2057
2057
|
**Hook Context:**
|
|
2058
|
-
${J.additionalContext}`}if(J.modifiedOutput!==void 0){let G=J.modifiedOutput;if(B_(G))Object.assign(X,G)}if(J.warning)console.warn(`[PostToolUseHook Warning] ${J.warning}`)}catch(Y){console.error("[PostToolUseHookStage] Error executing post-tool hooks:",Y)}}}var RG=A(()=>{U$();r$()});class
|
|
2058
|
+
${J.additionalContext}`}if(J.modifiedOutput!==void 0){let G=J.modifiedOutput;if(B_(G))Object.assign(X,G)}if(J.warning)console.warn(`[PostToolUseHook Warning] ${J.warning}`)}catch(Y){console.error("[PostToolUseHookStage] Error executing post-tool hooks:",Y)}}}var RG=A(()=>{U$();r$()});class I2{static instance=null;locks=new Map;constructor(){}static getInstance(){if(!I2.instance)I2.instance=new I2;return I2.instance}async acquireLock($,Z){let X=this.locks.get($);if(X)try{await X}catch{}let Y=this.executeWithLock($,Z);return this.locks.set($,Y.then(()=>{return})),Y}async executeWithLock($,Z){P5.debug(`获取文件锁: ${$}`);try{let X=await Z();return P5.debug(`释放文件锁: ${$}`),X}catch(X){throw P5.debug(`操作失败,释放文件锁: ${$}`),X}}isLocked($){return this.locks.has($)}clearLock($){this.locks.delete($)}clearAll(){this.locks.clear()}getLockedFiles(){return Array.from(this.locks.keys())}getLockedFileCount(){return this.locks.size}static resetInstance(){I2.instance=null}}var P5;var VG=A(()=>{B0();P5=i("Execution")});import L_ from"node:os";import T5 from"node:path";var S5;var DG=A(()=>{S5=class S5{static SENSITIVE_PATTERNS=[{pattern:/^\.?id_rsa$/i,level:"high",description:"SSH 私钥"},{pattern:/^\.?id_ed25519$/i,level:"high",description:"SSH Ed25519 私钥"},{pattern:/^\.?id_ecdsa$/i,level:"high",description:"SSH ECDSA 私钥"},{pattern:/\.pem$/i,level:"high",description:"PEM 格式私钥"},{pattern:/\.key$/i,level:"high",description:"密钥文件"},{pattern:/\.p12$/i,level:"high",description:"PKCS#12 证书"},{pattern:/\.pfx$/i,level:"high",description:"PFX 证书"},{pattern:/^\.?keystore$/i,level:"high",description:"Java Keystore"},{pattern:/^\.?pgpass$/i,level:"high",description:"PostgreSQL 密码文件"},{pattern:/^\.?my\.cnf$/i,level:"high",description:"MySQL 配置文件(可能含密码)"},{pattern:/credentials\.json$/i,level:"high",description:"Google Cloud 凭证"},{pattern:/^\.?aws[\\/]credentials$/i,level:"high",description:"AWS 凭证"},{pattern:/^\.?gcp[\\/]credentials$/i,level:"high",description:"GCP 凭证"},{pattern:/^\.?azure[\\/]credentials$/i,level:"high",description:"Azure 凭证"},{pattern:/^service-account.*\.json$/i,level:"high",description:"服务账号密钥"},{pattern:/^\.env$/i,level:"medium",description:"环境变量文件"},{pattern:/^\.env\./i,level:"medium",description:"环境变量文件(带环境后缀)"},{pattern:/^\.?npmrc$/i,level:"medium",description:"npm 配置文件(可能含 token)"},{pattern:/^\.?pypirc$/i,level:"medium",description:"PyPI 配置文件(可能含密码)"},{pattern:/^\.?dockercfg$/i,level:"medium",description:"Docker 配置文件"},{pattern:/^\.?docker[\\/]config\.json$/i,level:"medium",description:"Docker 配置文件"},{pattern:/^\.?netrc$/i,level:"medium",description:"FTP/HTTP 认证文件"},{pattern:/^\.?git-credentials$/i,level:"medium",description:"Git 凭证文件"},{pattern:/^config\.toml$/i,level:"medium",description:"配置文件(可能含敏感信息)"},{pattern:/^secrets\./i,level:"medium",description:"密钥配置文件"},{pattern:/\.sqlite$/i,level:"low",description:"SQLite 数据库"},{pattern:/\.db$/i,level:"low",description:"数据库文件"},{pattern:/\.sql$/i,level:"low",description:"SQL 文件(可能含敏感数据)"}];static SENSITIVE_PATHS=[{path:/\.ssh[\\/]/i,level:"high",description:"SSH 配置目录"},{path:/\.aws[\\/]/i,level:"high",description:"AWS 配置目录"},{path:/\.config[\\/]gcloud[\\/]/i,level:"high",description:"Google Cloud 配置目录"},{path:/\.kube[\\/]/i,level:"high",description:"Kubernetes 配置目录"}];static check($){let Z=this.normalizePath($),X=T5.basename(Z);for(let Y of this.SENSITIVE_PATTERNS)if(this.matchPattern(X,Y.pattern))return{isSensitive:!0,level:Y.level,matchedPattern:Y.pattern instanceof RegExp?Y.pattern.source:Y.pattern,reason:Y.description};for(let Y of this.SENSITIVE_PATHS)if(this.matchPattern(Z,Y.path))return{isSensitive:!0,level:Y.level,matchedPattern:Y.path instanceof RegExp?Y.path.source:Y.path,reason:Y.description};return{isSensitive:!1}}static checkMultiple($){let Z=new Map;for(let X of $)Z.set(X,this.check(X));return Z}static filterSensitive($,Z="low"){let X={["high"]:3,["medium"]:2,["low"]:1},Y=X[Z];return $.map((Q)=>({path:Q,result:this.check(Q)})).filter(({result:Q})=>Q.isSensitive&&Q.level&&X[Q.level]>=Y)}static normalizePath($){if($.startsWith("~/")||$==="~")return T5.join(L_.homedir(),$.slice(1));return T5.resolve($)}static matchPattern($,Z){if(Z instanceof RegExp)return Z.test($);let X=Z.replace(/\*/g,".*");return new RegExp(`^${X}$`,"i").test($)}static getSensitivePatterns(){return[...this.SENSITIVE_PATTERNS]}static getSensitivePaths(){return[...this.SENSITIVE_PATHS]}}});class C5{registry;name="discovery";constructor($){this.registry=$}async process($){let Z=this.registry.get($.toolName);if(!Z){$.abort(`Tool "${$.toolName}" not found`);return}$._internal.tool=Z}}class k5{name="permission";permissionChecker;sessionApprovals;defaultPermissionMode;constructor($,Z,X){this.permissionChecker=new l2($),this.sessionApprovals=Z,this.defaultPermissionMode=X}getPermissionChecker(){return this.permissionChecker}async process($){let Z=$._internal.tool;if(!Z){$.abort("Discovery stage failed; cannot perform permission check");return}try{let X=Z.build($.params),Y=X.getAffectedPaths(),Q={toolName:Z.name,params:$.params,affectedPaths:Y,tool:Z},J=l2.buildSignature(Q);$._internal.permissionSignature=J;let G=this.permissionChecker.check(Q),q=$.context.permissionMode||this.defaultPermissionMode;switch(G=this.applyModeOverrides(Z.kind,G,q),G.result){case"deny":$.abort(G.reason||`Tool invocation "${Z.name}" was denied by permission rules: ${G.matchedRule}`);return;case"ask":if(this.sessionApprovals.has(J))G={result:"allow",matchedRule:"remembered:session",reason:"User already allowed this operation in this session"};else $._internal.needsConfirmation=!0,$._internal.confirmationReason=G.reason||"User confirmation required";break;case"allow":break}if(Y.length>0){let K=["/etc/","/sys/","/proc/","/dev/","/boot/","/root/","C:\\Windows\\System32","C:\\Program Files","C:\\ProgramData"],W=Y.filter((H)=>{if(H.includes(".."))return!0;return K.some((F)=>H.includes(F))});if(W.length>0){$.abort(`Access to dangerous system paths denied: ${W.join(", ")}`);return}let U=S5.filterSensitive(Y,"medium");if(U.length>0){let H=U.map(({path:O,result:z})=>`${O} (${z.level}: ${z.reason})`);if(U.filter(({result:O})=>O.level==="high").length>0&&G.result!=="allow"){$.abort(`Access to highly sensitive files denied:
|
|
2059
2059
|
${H.join(`
|
|
2060
2060
|
`)}
|
|
2061
2061
|
|
|
@@ -2063,7 +2063,7 @@ If access is required, add an explicit allow rule in permissions.`);return}if(G.
|
|
|
2063
2063
|
${H.join(`
|
|
2064
2064
|
`)}
|
|
2065
2065
|
|
|
2066
|
-
Confirm to proceed?`,$._internal.needsConfirmation=!0}}$._internal.invocation=X,$._internal.permissionCheckResult=G}catch(X){$.abort(`Permission check failed: ${X.message}`)}}applyModeOverrides($,Z,X){if(X==="yolo")return{result:"allow",matchedRule:"mode:yolo",reason:"YOLO mode: automatically approve all tool invocations"};if(X==="plan"){if(!S8($))return{result:"deny",matchedRule:"mode:plan",reason:"Plan mode: modification tools are blocked; only read-only tools are allowed (Read/Glob/Grep/WebFetch/WebSearch/Task)"}}if(Z.result==="deny")return Z;if(Z.result==="allow")return Z;if(S8($))return{result:"allow",matchedRule:`mode:${X}:readonly`,reason:"Read-only tools do not require confirmation"};if(X==="autoEdit"&&$==="write")return{result:"allow",matchedRule:"mode:autoEdit:write",reason:"AUTO_EDIT mode: automatically approve write tools"};return Z}}class f5{sessionApprovals;name="confirmation";permissionChecker;constructor($,Z){this.sessionApprovals=$;this.permissionChecker=Z}async process($){let{tool:Z,invocation:X,needsConfirmation:Y,confirmationReason:Q,permissionCheckResult:J}=$._internal;if(!Z||!X){$.abort("Pre-confirmation stage failed; cannot request user approval");return}if(!Y)return;try{let G=Z.extractSignatureContent?Z.extractSignatureContent($.params):Z.name,q=M0.getInstance();if(q.isEnabled()){let U=await q.executePermissionRequestHooks(Z.name,$.context.sessionId||"unknown",$.params,{projectDir:process.cwd(),sessionId:$.context.sessionId||"unknown",permissionMode:$.context.permissionMode||"default"});switch(U.decision){case"approve":
|
|
2066
|
+
Confirm to proceed?`,$._internal.needsConfirmation=!0}}$._internal.invocation=X,$._internal.permissionCheckResult=G}catch(X){$.abort(`Permission check failed: ${X.message}`)}}applyModeOverrides($,Z,X){if(X==="yolo")return{result:"allow",matchedRule:"mode:yolo",reason:"YOLO mode: automatically approve all tool invocations"};if(X==="plan"){if(!S8($))return{result:"deny",matchedRule:"mode:plan",reason:"Plan mode: modification tools are blocked; only read-only tools are allowed (Read/Glob/Grep/WebFetch/WebSearch/Task)"}}if(Z.result==="deny")return Z;if(Z.result==="allow")return Z;if(S8($))return{result:"allow",matchedRule:`mode:${X}:readonly`,reason:"Read-only tools do not require confirmation"};if(X==="autoEdit"&&$==="write")return{result:"allow",matchedRule:"mode:autoEdit:write",reason:"AUTO_EDIT mode: automatically approve write tools"};return Z}}class f5{sessionApprovals;name="confirmation";permissionChecker;constructor($,Z){this.sessionApprovals=$;this.permissionChecker=Z}async process($){let{tool:Z,invocation:X,needsConfirmation:Y,confirmationReason:Q,permissionCheckResult:J}=$._internal;if(!Z||!X){$.abort("Pre-confirmation stage failed; cannot request user approval");return}if(!Y)return;try{let G=Z.extractSignatureContent?Z.extractSignatureContent($.params):Z.name,q=M0.getInstance();if(q.isEnabled()){let U=await q.executePermissionRequestHooks(Z.name,$.context.sessionId||"unknown",$.params,{projectDir:process.cwd(),sessionId:$.context.sessionId||"unknown",permissionMode:$.context.permissionMode||"default"});switch(U.decision){case"approve":y2.debug(`PermissionRequest hook 自动批准: ${Z.name}`);return;case"deny":$.abort(U.reason||`PermissionRequest hook denied: ${Z.name}`,{shouldExitLoop:!0});return;case"ask":default:break}}let K={title:`权限确认: ${G}`,message:Q||"此操作需要用户确认",kind:Z.kind,details:this.generatePreviewForTool(Z.name,$.params),risks:this.extractRisksFromPermissionCheck(Z,$.params,J),affectedFiles:X.getAffectedPaths()||[]};if(y2.warn(`工具 "${Z.name}" 需要用户确认: ${K.title}`),y2.warn(`详情: ${K.message}`),K.risks&&K.risks.length>0)y2.warn(`风险: ${K.risks.join(", ")}`);let W=$.context.confirmationHandler;if(W){let U=await W.requestConfirmation(K);if(!U.approved){$.abort(`User rejected execution: ${U.reason||"No reason provided"}`,{shouldExitLoop:!0});return}if((U.scope||"once")==="session"&&$._internal.permissionSignature){let F=$._internal.permissionSignature;this.sessionApprovals.add(F);let O={toolName:Z.name,params:$.params,affectedPaths:X.getAffectedPaths()||[],tool:Z};await this.persistSessionApproval(F,O)}}else y2.warn("⚠️ No ConfirmationHandler; auto-approving tool execution (non-interactive environment only)")}catch(G){$.abort(`User confirmation failed: ${G.message}`)}}async persistSessionApproval($,Z){try{let X=l2.abstractPattern(Z);y2.debug(`保存权限规则: "${X}"`),await x0().appendLocalPermissionAllowRule(X,{immediate:!0});let Y=H$();if(Y?.permissions)y2.debug("同步权限配置到 PermissionChecker:",Y.permissions),this.permissionChecker.replaceConfig(Y.permissions)}catch(X){y2.warn(`Failed to persist permission rule "${$}": ${X instanceof Error?X.message:"Unknown error"}`)}}generatePreviewForTool($,Z){switch($){case"Edit":{let{old_string:X,new_string:Y}=Z;if(!X&&!Y)return;let Q=20,J=(G)=>{let q=G.split(`
|
|
2067
2067
|
`);if(q.length<=Q)return G;return`${q.slice(0,Q).join(`
|
|
2068
2068
|
`)}
|
|
2069
2069
|
... (还有 ${q.length-Q} 行)`};return`**变更前:**
|
|
@@ -2084,20 +2084,20 @@ ${X}
|
|
|
2084
2084
|
${G}
|
|
2085
2085
|
\`\`\`
|
|
2086
2086
|
|
|
2087
|
-
... (还有 ${J.length-Q} 行)`}case"Bash":case"Shell":return;default:return}}extractRisksFromPermissionCheck($,Z,X){let Y=[];if(X?.reason)Y.push(X.reason);if($.name==="Bash"){let Q=Z.command||"",J=Q.trim().split(/\s+/)[0];if(J==="cat"||J==="head"||J==="tail")Y.push(`\uD83D\uDCA1 建议使用 Read 工具代替 ${J} 命令(性能更好,支持大文件分页)`);else if(J==="grep"||J==="rg")Y.push("\uD83D\uDCA1 建议使用 Grep 工具代替 grep/rg 命令(支持更强大的过滤和上下文)");else if(J==="find")Y.push("\uD83D\uDCA1 建议使用 Glob 工具代替 find 命令(更快,支持 glob 模式)");else if(J==="sed"||J==="awk")Y.push(`\uD83D\uDCA1 建议使用 Edit 工具代替 ${J} 命令(更安全,支持预览和回滚)`);if(Q.includes("rm"))Y.push("⚠️ 此命令可能删除文件");if(Q.includes("sudo"))Y.push("⚠️ 此命令需要管理员权限");if(Q.includes("git push"))Y.push("⚠️ 此命令将推送代码到远程仓库")}else if($.name==="Write"||$.name==="Edit")Y.push("此操作将修改文件内容");else if($.name==="Delete")Y.push("此操作将永久删除文件");return Y}}class h5{name="execution";async process($){let Z=$._internal.invocation;if(!Z){$.abort("Pre-execution stage failed; cannot run tool");return}try{let X=await Z.execute($.context.signal??new AbortController().signal,$.context.onProgress,$.context);$.setResult(X)}catch(X){$.abort(`Tool execution failed: ${X.message}`)}}}class x5{name="formatting";async process($){try{let Z=$.getResult();if(!Z.llmContent)Z.llmContent="Execution completed";if(!Z.displayContent)Z.displayContent=Z.success?"执行成功":"执行失败";if(!Z.metadata)Z.metadata={};Z.metadata.executionId=$.context.sessionId,Z.metadata.toolName=$.toolName,Z.metadata.timestamp=Date.now(),$.setResult(Z)}catch(Z){$.abort(`Result formatting failed: ${Z.message}`)}}}var
|
|
2087
|
+
... (还有 ${J.length-Q} 行)`}case"Bash":case"Shell":return;default:return}}extractRisksFromPermissionCheck($,Z,X){let Y=[];if(X?.reason)Y.push(X.reason);if($.name==="Bash"){let Q=Z.command||"",J=Q.trim().split(/\s+/)[0];if(J==="cat"||J==="head"||J==="tail")Y.push(`\uD83D\uDCA1 建议使用 Read 工具代替 ${J} 命令(性能更好,支持大文件分页)`);else if(J==="grep"||J==="rg")Y.push("\uD83D\uDCA1 建议使用 Grep 工具代替 grep/rg 命令(支持更强大的过滤和上下文)");else if(J==="find")Y.push("\uD83D\uDCA1 建议使用 Glob 工具代替 find 命令(更快,支持 glob 模式)");else if(J==="sed"||J==="awk")Y.push(`\uD83D\uDCA1 建议使用 Edit 工具代替 ${J} 命令(更安全,支持预览和回滚)`);if(Q.includes("rm"))Y.push("⚠️ 此命令可能删除文件");if(Q.includes("sudo"))Y.push("⚠️ 此命令需要管理员权限");if(Q.includes("git push"))Y.push("⚠️ 此命令将推送代码到远程仓库")}else if($.name==="Write"||$.name==="Edit")Y.push("此操作将修改文件内容");else if($.name==="Delete")Y.push("此操作将永久删除文件");return Y}}class h5{name="execution";async process($){let Z=$._internal.invocation;if(!Z){$.abort("Pre-execution stage failed; cannot run tool");return}try{let X=await Z.execute($.context.signal??new AbortController().signal,$.context.onProgress,$.context);$.setResult(X)}catch(X){$.abort(`Tool execution failed: ${X.message}`)}}}class x5{name="formatting";async process($){try{let Z=$.getResult();if(!Z.llmContent)Z.llmContent="Execution completed";if(!Z.displayContent)Z.displayContent=Z.success?"执行成功":"执行失败";if(!Z.metadata)Z.metadata={};Z.metadata.executionId=$.context.sessionId,Z.metadata.toolName=$.toolName,Z.metadata.timestamp=Date.now(),$.setResult(Z)}catch(Z){$.abort(`Result formatting failed: ${Z.message}`)}}}var y2;var MG=A(()=>{A9();U$();r$();B0();C0();E$();DG();y2=i("Execution")});import{EventEmitter as w_}from"events";var p5;var jG=A(()=>{U$();r$();AG();RG();x9();w$();VG();MG();p5=class p5 extends w_{registry;stages;executionHistory=[];maxHistorySize;sessionApprovals=new Set;constructor($,Z={}){super();this.registry=$;this.maxHistorySize=Z.maxHistorySize||1000;let X=Z.permissionConfig||{allow:[],ask:[],deny:[]},Y=Z.permissionMode??"default",Q=new k5(X,this.sessionApprovals,Y);this.stages=[new C5(this.registry),Q,new v5,new f5(this.sessionApprovals,Q.getPermissionChecker()),new h5,new E5,new x5]}async execute($,Z,X){let Y=Date.now(),Q=this.generateExecutionId(),J=new h9($,Z,{...X,sessionId:X.sessionId||Q});this.emit("executionStarted",{executionId:Q,toolName:$,params:Z,context:X,timestamp:Y});let G=this.registry.get($),q=G&&!G.isConcurrencySafe,K=q&&Z.file_path?String(Z.file_path):null;if(q&&K)return I2.getInstance().acquireLock(K,()=>this.executeWithPipeline(J,Q,Y));return this.executeWithPipeline(J,Q,Y)}async executeWithPipeline($,Z,X){try{for(let J of this.stages){if($.context.signal?.aborted){$.abort("任务已被用户中止");break}if(this.emit("stageStarted",{executionId:Z,stageName:J.name,timestamp:Date.now()}),await J.process($),this.emit("stageCompleted",{executionId:Z,stageName:J.name,timestamp:Date.now()}),$.shouldAbort())break}let Y=$.getResult(),Q=Date.now();return this.addToHistory({executionId:Z,toolName:$.toolName,params:$.params,result:Y,startTime:X,endTime:Q,context:$.context}),this.emit("executionCompleted",{executionId:Z,toolName:$.toolName,result:Y,duration:Q-X,timestamp:Q}),Y}catch(Y){let Q=Date.now(),J=Y.message?.includes("timeout")||Y.name==="TimeoutError",G={success:!1,llmContent:`Tool execution failed: ${Y.message}`,displayContent:`错误: ${Y.message}`,error:{type:"execution_error",message:Y.message}};try{let K=await M0.getInstance().executePostToolUseFailureHooks($.toolName,`tool_use_${Z}`,$.params,Y.message,{projectDir:process.cwd(),sessionId:$.context.sessionId||"unknown",permissionMode:$.context.permissionMode||"default",isInterrupt:!1,isTimeout:J,abortSignal:$.context.signal});if(K.additionalContext)G={...G,llmContent:`${G.llmContent}
|
|
2088
2088
|
|
|
2089
|
-
${K.additionalContext}`};if(K.warning)console.warn(`[ExecutionPipeline] PostToolUseFailure hook warning: ${K.warning}`)}catch(q){console.warn("[ExecutionPipeline] PostToolUseFailure hook execution failed:",q)}return this.addToHistory({executionId:Z,toolName:$.toolName,params:$.params,result:G,startTime:X,endTime:Q,context:$.context}),this.emit("executionFailed",{executionId:Z,toolName:$.toolName,error:Y,duration:Q-X,timestamp:Q}),G}}async executeAll($){let Z=$.map((X)=>this.execute(X.toolName,X.params,X.context));return Promise.all(Z)}async executeParallel($,Z=5){let X=[],Y=[];for(let Q=0;Q<$.length;Q++){let J=$[Q],G=this.execute(J.toolName,J.params,J.context);if(Y.push(G),Y.length>=Z||Q===$.length-1){let q=await Promise.all(Y);X.push(...q),Y.length=0}}return X}getExecutionHistory($){let Z=[...this.executionHistory];return $?Z.slice(-$):Z}clearHistory(){this.executionHistory=[],this.emit("historyClear",{timestamp:Date.now()})}getStats(){let $={totalExecutions:this.executionHistory.length,successfulExecutions:0,failedExecutions:0,averageDuration:0,toolUsage:new Map,recentExecutions:this.executionHistory.slice(-10)},Z=0;for(let X of this.executionHistory){if(X.result.success)$.successfulExecutions++;else $.failedExecutions++;let Y=X.endTime-X.startTime;Z+=Y;let Q=$.toolUsage.get(X.toolName)||0;$.toolUsage.set(X.toolName,Q+1)}return $.averageDuration=$.totalExecutions>0?Z/$.totalExecutions:0,$}addStage($,Z=-1){if(Z===-1){let X=this.stages.findIndex((Y)=>Y.name==="execution");this.stages.splice(X,0,$)}else this.stages.splice(Z,0,$);this.emit("stageAdded",{stageName:$.name,position:Z,timestamp:Date.now()})}removeStage($){let Z=this.stages.findIndex((X)=>X.name===$);if(Z===-1)return!1;return this.stages.splice(Z,1),this.emit("stageRemoved",{stageName:$,timestamp:Date.now()}),!0}getStages(){return[...this.stages]}getRegistry(){return this.registry}generateExecutionId(){return`exec_${Date.now()}_${Math.random().toString(36).substr(2,9)}`}addToHistory($){if(this.executionHistory.push($),this.executionHistory.length>this.maxHistorySize)this.executionHistory=this.executionHistory.slice(-this.maxHistorySize)}}});import{EventEmitter as N_}from"events";var A6;var IG=A(()=>{U$();A6=class A6 extends N_{tools=new Map;mcpTools=new Map;categories=new Map;tags=new Map;constructor(){super()}register($){if(this.tools.has($.name))throw Error(`工具 '${$.name}' 已注册`);this.tools.set($.name,$),this.updateIndexes($),this.emit("toolRegistered",{type:"builtin",tool:$,timestamp:Date.now()})}registerAll($){let Z=[];for(let X of $)try{this.register(X)}catch(Y){Z.push(`${X.name}: ${Y.message}`)}if(Z.length>0)throw Error(`批量注册失败: ${Z.join(", ")}`)}unregister($){let Z=this.tools.get($);if(!Z)return!1;return this.tools.delete($),this.removeFromIndexes(Z),this.emit("toolUnregistered",{type:"builtin",toolName:$,timestamp:Date.now()}),!0}get($){return this.tools.get($)||this.mcpTools.get($)}has($){return this.tools.has($)||this.mcpTools.has($)}getAll(){return[...Array.from(this.tools.values()),...Array.from(this.mcpTools.values())]}getBuiltinTools(){return Array.from(this.tools.values())}getMcpTools(){return Array.from(this.mcpTools.values())}getByCategory($){let Z=this.categories.get($);if(!Z)return[];return Array.from(Z).map((X)=>this.get(X)).filter((X)=>X!==void 0)}getByTag($){let Z=this.tags.get($);if(!Z)return[];return Array.from(Z).map((X)=>this.get(X)).filter((X)=>X!==void 0)}search($){let Z=$.toLowerCase();return this.getAll().filter((X)=>{let Y=typeof X.description==="string"?X.description:X.description.short;return X.name.toLowerCase().includes(Z)||Y.toLowerCase().includes(Z)||X.displayName.toLowerCase().includes(Z)||X.category&&X.category.toLowerCase().includes(Z)||X.tags.some((Q)=>Q.toLowerCase().includes(Z))})}getFunctionDeclarations(){return this.getAll().map(($)=>$.getFunctionDeclaration())}getReadOnlyFunctionDeclarations(){return this.getAll().filter(($)=>$.isReadOnly).map(($)=>$.getFunctionDeclaration())}getFunctionDeclarationsByMode($){if($==="plan")return this.getReadOnlyFunctionDeclarations();if($==="spec")return this.getSpecModeFunctionDeclarations();return this.getFunctionDeclarations()}static SPEC_TOOLS=["EnterSpecMode","UpdateSpec","GetSpecContext","TransitionSpecPhase","AddTask","UpdateTaskStatus","ValidateSpec","ExitSpecMode"];getSpecModeFunctionDeclarations(){return this.getFunctionDeclarations()}isSpecTool($){return A6.SPEC_TOOLS.includes($)}getReadOnlyTools(){return this.getAll().filter(($)=>$.isReadOnly)}getCategories(){return Array.from(this.categories.keys())}getTags(){return Array.from(this.tags.keys())}getStats(){return{totalTools:this.tools.size+this.mcpTools.size,builtinTools:this.tools.size,mcpTools:this.mcpTools.size,categories:this.categories.size,tags:this.tags.size,toolsByCategory:Object.fromEntries(Array.from(this.categories.entries()).map(([$,Z])=>[$,Z.size]))}}registerMcpTool($){if(this.mcpTools.has($.name))this.mcpTools.delete($.name);this.mcpTools.set($.name,$),this.updateIndexes($),this.emit("toolRegistered",{type:"mcp",tool:$,timestamp:Date.now()})}removeMcpTools($){let Z=0,X=`mcp__${$}__`;for(let[Y,Q]of this.mcpTools.entries())if(Y.startsWith(X))this.mcpTools.delete(Y),this.removeFromIndexes(Q),Z++,this.emit("toolUnregistered",{type:"mcp",toolName:Y,serverName:$,timestamp:Date.now()});return Z}updateIndexes($){if($.category){if(!this.categories.has($.category))this.categories.set($.category,new Set);this.categories.get($.category).add($.name)}for(let Z of $.tags){if(!this.tags.has(Z))this.tags.set(Z,new Set);this.tags.get(Z).add($.name)}}removeFromIndexes($){if($.category){let Z=this.categories.get($.category);if(Z){if(Z.delete($.name),Z.size===0)this.categories.delete($.category)}}for(let Z of $.tags){let X=this.tags.get(Z);if(X){if(X.delete($.name),X.size===0)this.tags.delete(Z)}}}}});function A_($){return b_.some((Z)=>Z.test($))}function R_($){if($.supportsThinking!==void 0)return{supportsThinking:$.supportsThinking,thinkingBudget:$.thinkingBudget};return{supportsThinking:A_($.model),thinkingBudget:void 0}}function t2($){return R_($).supportsThinking}var b_;var R6=A(()=>{b_=[/deepseek.*r1/i,/deepseek.*reasoner/i,/o1-preview/i,/o1-mini/i,/o1/i,/qwen.*qwq/i,/qwen.*think/i,/kimi.*k1/i,/moonshot.*think/i,/k1-32k/i,/doubao.*think/i,/doubao.*pro.*think/i,/claude.*opus.*4/i,/glm-4\.7/i]});class d5{maxSummaryLength;keyPointsLimit;recentMessagesLimit;constructor($=500,Z=10,X=20){this.maxSummaryLength=$,this.keyPointsLimit=Z,this.recentMessagesLimit=X}async compress($){let Z=$.layers.conversation.messages,X=$.layers.tool.recentCalls,Y=Z.filter((H)=>H.role==="system"),Q=Z.filter((H)=>H.role!=="system"),J=this.getRecentMessages(Q),G=Q.slice(0,-this.recentMessagesLimit),q=await this.generateSummary(G),K=this.extractKeyPoints(G,X),W=this.generateToolSummary(X),U=this.estimateTokenCount(q,K,J,W);return{summary:q,keyPoints:K,recentMessages:[...Y,...J],toolSummary:W,tokenCount:U}}getRecentMessages($){return $.slice(-this.recentMessagesLimit)}async generateSummary($){if($.length===0)return"";let Z=new Set,X=new Set,Y=new Set;for(let J of $){let G=J.content.toLowerCase();["关于","讨论","问题","项目","功能","需求"].forEach((U)=>{if(G.includes(U)){let H=this.extractContext(G,U,50);if(H)Z.add(H)}}),["创建","删除","修改","更新","实现","开发"].forEach((U)=>{if(G.includes(U)){let H=this.extractContext(G,U,30);if(H)X.add(H)}}),["决定","选择","确定","采用","使用"].forEach((U)=>{if(G.includes(U)){let H=this.extractContext(G,U,40);if(H)Y.add(H)}})}let Q=`对话涉及 ${$.length} 条消息。`;if(Z.size>0)Q+=` 主要讨论:${Array.from(Z).slice(0,3).join("、")}。`;if(X.size>0)Q+=` 执行操作:${Array.from(X).slice(0,3).join("、")}。`;if(Y.size>0)Q+=` 关键决策:${Array.from(Y).slice(0,2).join("、")}。`;return Q.length>this.maxSummaryLength?Q.substring(0,this.maxSummaryLength)+"...":Q}extractKeyPoints($,Z){let X=new Set;for(let Q of $)if(Q.role==="user")this.extractQuestions(Q.content).forEach((q)=>X.add(`用户问题:${q}`)),this.extractRequests(Q.content).forEach((q)=>X.add(`用户请求:${q}`));else if(Q.role==="assistant")this.extractSolutions(Q.content).forEach((G)=>X.add(`解决方案:${G}`));return this.summarizeToolUsage(Z).forEach((Q)=>X.add(`工具使用:${Q}`)),Array.from(X).slice(0,this.keyPointsLimit)}generateToolSummary($){if($.length===0)return"";let Z=new Map,X=Date.now()-600000;for(let Q of $){let J=Z.get(Q.name)||{count:0,success:0,recent:0};if(J.count++,Q.status==="success")J.success++;if(Q.timestamp>X)J.recent++;Z.set(Q.name,J)}let Y=[];for(let[Q,J]of Array.from(Z.entries())){let G=Math.round(J.success/J.count*100);Y.push(`${Q}(${J.count}次,成功率${G}%)`)}return`工具调用:${Y.join("、")}`}estimateTokenCount($,Z,X,Y){let Q=$.length+Z.join(" ").length;if(Y)Q+=Y.length;for(let J of X)Q+=J.content.length;return Math.ceil(Q/4)}extractContext($,Z,X){let Y=$.indexOf(Z);if(Y===-1)return null;let Q=Math.max(0,Y-X/2),J=Math.min($.length,Y+X/2);return $.substring(Q,J).trim()}extractQuestions($){let Z=[],X=["?","?","如何","怎么","什么","为什么"],Y=$.split(/[。!.!]/);for(let Q of Y)if(X.some((J)=>Q.includes(J))){let J=Q.trim();if(J.length>5&&J.length<100)Z.push(J)}return Z.slice(0,3)}extractRequests($){let Z=[],X=["请","帮我","需要","想要","希望","能否"],Y=$.split(/[。!.!]/);for(let Q of Y)if(X.some((J)=>Q.includes(J))){let J=Q.trim();if(J.length>5&&J.length<100)Z.push(J)}return Z.slice(0,3)}extractSolutions($){let Z=[],X=["可以","建议","推荐","应该","最好","解决方案"],Y=$.split(/[。!.!]/);for(let Q of Y)if(X.some((J)=>Q.includes(J))){let J=Q.trim();if(J.length>10&&J.length<150)Z.push(J)}return Z.slice(0,3)}summarizeToolUsage($){let Z=[],X=$.filter((Y)=>Date.now()-Y.timestamp<1800000);if(X.length>0){let Y=new Map;X.forEach((Q)=>{let J=Y.get(Q.name)||[];J.push(Q),Y.set(Q.name,J)});for(let[Q,J]of Array.from(Y.entries())){let G=J.filter((q)=>q.status==="success").length;Z.push(`${Q}(${J.length}次,${G}成功)`)}}return Z.slice(0,5)}shouldCompress($,Z){return this.estimateCurrentTokens($)>Z*0.8}estimateCurrentTokens($){let X=$.layers.conversation.messages.reduce((Y,Q)=>Y+Q.content.length,0);return Math.ceil(X/4)}}class K2{defaultOptions;constructor($){this.defaultOptions={maxTokens:32000,maxMessages:50,timeWindow:86400000,priority:1,includeTools:!0,includeWorkspace:!0,...$}}filter($,Z){let X={...this.defaultOptions,...Z},Y={layers:{system:$.layers.system,session:$.layers.session,conversation:this.filterConversation($.layers.conversation,X),tool:X.includeTools?this.filterTools($.layers.tool,X):{recentCalls:[],toolStates:{},dependencies:{}},workspace:X.includeWorkspace?$.layers.workspace:{currentFiles:[],recentFiles:[],environment:{}}},metadata:{...$.metadata,lastUpdated:Date.now()}};return Y.metadata.totalTokens=this.estimateTokens(Y),Y}filterConversation($,Z){let X=[...$.messages];if(Z.timeWindow>0){let Y=Date.now()-Z.timeWindow;X=X.filter((Q)=>Q.timestamp>=Y||Q.role==="system")}if(Z.priority>1)X=this.filterByPriority(X,Z.priority);if(Z.maxMessages>0)X=this.limitMessages(X,Z.maxMessages);if(Z.maxTokens>0)X=this.limitByTokens(X,Z.maxTokens);return{messages:X,summary:$.summary,topics:this.updateTopics(X,$.topics),lastActivity:$.lastActivity}}filterTools($,Z){let X=[...$.recentCalls];if(Z.timeWindow>0){let K=Date.now()-Z.timeWindow;X=X.filter((W)=>W.timestamp>=K)}let Y=X.filter((K)=>K.status==="success"),Q=X.filter((K)=>K.status==="error"),J=Math.min(20,Y.length),G=Math.min(10,Q.length);return{recentCalls:[...Y.slice(-J),...Q.slice(-G)].sort((K,W)=>K.timestamp-W.timestamp),toolStates:$.toolStates,dependencies:$.dependencies}}filterByPriority($,Z){return $.filter((X)=>{if(X.role==="system")return!0;return this.calculateMessagePriority(X)>=Z})}calculateMessagePriority($){let Z=1;if($.role==="system")Z+=3;else if($.role==="assistant")Z+=1;let X=$.content.toLowerCase();if(["错误","警告","重要","关键","问题","解决"].some((J)=>X.includes(J)))Z+=2;if(X.includes("```")||X.includes("function")||X.includes("class"))Z+=1;let Q=(Date.now()-$.timestamp)/3600000;if(Q<1)Z+=2;else if(Q<6)Z+=1;return Z}limitMessages($,Z){if($.length<=Z)return $;let X=$.filter((G)=>G.role==="system"),Y=$.filter((G)=>G.role!=="system"),Q=Z-X.length,J=Q>0?Y.slice(-Q):[];return[...X,...J].sort((G,q)=>G.timestamp-q.timestamp)}limitByTokens($,Z){if(Z<=0)return $;let X=0,Y=[];for(let Q=$.length-1;Q>=0;Q--){let J=$[Q],G=this.estimateMessageTokens(J);if(J.role==="system")if(X+G<=Z)Y.unshift(J),X+=G;else{let q=this.compressMessage(J,Z-X);Y.unshift(q),X+=this.estimateMessageTokens(q)}else if(X+G<=Z)Y.unshift(J),X+=G;else break}return Y.sort((Q,J)=>Q.timestamp-J.timestamp)}estimateMessageTokens($){return Math.ceil($.content.length/4)}compressMessage($,Z){let X=Z*4;if($.content.length<=X)return $;let Y=$.content.substring(0,X-3)+"...";return{...$,content:Y,metadata:{...$.metadata,compressed:!0,originalLength:$.content.length}}}updateTopics($,Z){let X=new Set(Z);for(let Y of $)this.extractTopicsFromMessage(Y).forEach((J)=>X.add(J));return Array.from(X).slice(0,10)}extractTopicsFromMessage($){let Z=$.content.toLowerCase(),X=[];return["项目","功能","模块","组件","服务","接口","数据库","前端","后端","算法","架构","设计"].forEach((Q)=>{if(Z.includes(Q))X.push(Q)}),X}estimateTokens($){let Z=0;for(let Y of $.layers.conversation.messages)Z+=this.estimateMessageTokens(Y);let X=JSON.stringify($.layers.system);if(Z+=Math.ceil(X.length/4),$.layers.tool.recentCalls.length>0){let Y=JSON.stringify($.layers.tool);Z+=Math.ceil(Y.length/8)}return Z}static createPresets(){return{lightweight:new K2({maxTokens:1000,maxMessages:10,timeWindow:7200000,includeTools:!1,includeWorkspace:!1}),standard:new K2({maxTokens:4000,maxMessages:30,timeWindow:43200000,includeTools:!0,includeWorkspace:!0}),comprehensive:new K2({maxTokens:8000,maxMessages:100,timeWindow:86400000,includeTools:!0,includeWorkspace:!0}),debug:new K2({maxTokens:2000,maxMessages:20,timeWindow:21600000,priority:2,includeTools:!0,includeWorkspace:!1})}}}class m5{cache=new Map;maxSize;defaultTTL;constructor($=100,Z=300000){this.maxSize=$,this.defaultTTL=Z}set($,Z,X){let Y=Date.now(),Q={data:Z,timestamp:Y,accessCount:0,lastAccess:Y,ttl:X||this.defaultTTL};if(this.cache.size>=this.maxSize&&!this.cache.has($))this.evictLeastUsed();this.cache.set($,Q)}get($){let Z=this.cache.get($);if(!Z)return null;let X=Date.now();if(X-Z.timestamp>Z.ttl)return this.cache.delete($),null;return Z.accessCount++,Z.lastAccess=X,Z.data}has($){let Z=this.cache.get($);if(!Z)return!1;if(Date.now()-Z.timestamp>Z.ttl)return this.cache.delete($),!1;return!0}delete($){return this.cache.delete($)}clear(){this.cache.clear()}size(){return this.cleanExpired(),this.cache.size}cacheMessageSummary($,Z,X){let Y=`summary:${$}:${Z.length}`;this.set(Y,{summary:X,messageCount:Z.length,lastMessage:Z[Z.length-1]?.timestamp||0},600000)}getMessageSummary($,Z){let X=`summary:${$}:${Z}`;return this.get(X)}cacheToolResult($,Z,X){let Y=this.hashInput(Z),Q=`tool:${$}:${Y}`;this.set(Q,X,1800000)}getToolResult($,Z){let X=this.hashInput(Z),Y=`tool:${$}:${X}`;return this.get(Y)}cacheCompressedContext($,Z){let X=`compressed:${$}`;this.set(X,Z,900000)}getCompressedContext($){let Z=`compressed:${$}`;return this.get(Z)}getStats(){this.cleanExpired();let $=0,Z=0,X=[];for(let[Y,Q]of Array.from(this.cache.entries()))$+=Q.accessCount,Z+=this.estimateItemSize(Q),X.push({key:Y,accessCount:Q.accessCount,lastAccess:Q.lastAccess});return X.sort((Y,Q)=>Q.accessCount-Y.accessCount),{size:this.cache.size,maxSize:this.maxSize,hitRate:$>0?$/($+this.cache.size):0,memoryUsage:Z,topKeys:X.slice(0,10)}}cleanExpired(){let $=Date.now(),Z=[];for(let[X,Y]of Array.from(this.cache.entries()))if($-Y.timestamp>Y.ttl)Z.push(X);Z.forEach((X)=>this.cache.delete(X))}evictLeastUsed(){let $=null,Z=1/0,X=Date.now();for(let[Y,Q]of Array.from(this.cache.entries())){let J=1/(X-Q.lastAccess+1),G=Q.accessCount,q=J*G;if(q<Z)Z=q,$=Y}if($)this.cache.delete($)}hashInput($){let Z=JSON.stringify($),X=0;for(let Y=0;Y<Z.length;Y++){let Q=Z.charCodeAt(Y);X=(X<<5)-X+Q,X=X&X}return Math.abs(X).toString(36)}estimateItemSize($){try{return JSON.stringify($).length*2}catch{return 1000}}setTTL($,Z){let X=this.cache.get($);if(X)return X.ttl=Z,X.timestamp=Date.now(),!0;return!1}getRemainingTTL($){let Z=this.cache.get($);if(!Z)return-1;let X=Z.ttl-(Date.now()-Z.timestamp);return Math.max(0,X)}warmup($){$.forEach(({key:Z,value:X,ttl:Y})=>{this.set(Z,X,Y)})}}class u5{contextData=null;maxSize;accessLog=new Map;constructor($=1000){this.maxSize=$}setContext($){this.contextData={...$},this.contextData.metadata.lastUpdated=Date.now(),this.recordAccess("context")}getContext(){if(this.contextData)this.recordAccess("context");return this.contextData}addMessage($){if(!this.contextData)throw Error("上下文数据未初始化");this.contextData.layers.conversation.messages.push($),this.contextData.layers.conversation.lastActivity=Date.now(),this.contextData.metadata.lastUpdated=Date.now(),this.enforceMemoryLimit(),this.recordAccess("messages")}getRecentMessages($=10){if(!this.contextData)return[];let Z=this.contextData.layers.conversation.messages;return this.recordAccess("messages"),Z.slice(-$)}addToolCall($){if(!this.contextData)throw Error("上下文数据未初始化");if(this.contextData.layers.tool.recentCalls.push($),this.contextData.metadata.lastUpdated=Date.now(),this.contextData.layers.tool.recentCalls.length>50)this.contextData.layers.tool.recentCalls=this.contextData.layers.tool.recentCalls.slice(-25);this.recordAccess("tools")}updateToolState($,Z){if(!this.contextData)throw Error("上下文数据未初始化");this.contextData.layers.tool.toolStates[$]=Z,this.contextData.metadata.lastUpdated=Date.now(),this.recordAccess("tools")}getToolState($){if(!this.contextData)return null;return this.recordAccess("tools"),this.contextData.layers.tool.toolStates[$]}updateWorkspace($){if(!this.contextData)throw Error("上下文数据未初始化");Object.assign(this.contextData.layers.workspace,$),this.contextData.metadata.lastUpdated=Date.now(),this.recordAccess("workspace")}clear(){this.contextData=null,this.accessLog.clear()}getMemoryInfo(){if(!this.contextData)return{hasData:!1,messageCount:0,toolCallCount:0,lastUpdated:null};return{hasData:!0,messageCount:this.contextData.layers.conversation.messages.length,toolCallCount:this.contextData.layers.tool.recentCalls.length,lastUpdated:this.contextData.metadata.lastUpdated}}recordAccess($){this.accessLog.set($,Date.now())}enforceMemoryLimit(){if(!this.contextData)return;let $=this.contextData.layers.conversation.messages;if($.length>this.maxSize){let Z=Math.floor(this.maxSize*0.8);this.contextData.layers.conversation.messages=$.slice(-Z)}}getMemoryUsage(){if(!this.contextData)return 0;return JSON.stringify(this.contextData).length}}import*as V6 from"node:fs";import{createReadStream as V_}from"node:fs";import*as l$ from"node:fs/promises";import*as g5 from"node:path";import{createInterface as D_}from"node:readline";class I1{filePath;constructor($){this.filePath=$}async append($){try{await l$.mkdir(g5.dirname(this.filePath),{recursive:!0});let Z=JSON.stringify($)+`
|
|
2089
|
+
${K.additionalContext}`};if(K.warning)console.warn(`[ExecutionPipeline] PostToolUseFailure hook warning: ${K.warning}`)}catch(q){console.warn("[ExecutionPipeline] PostToolUseFailure hook execution failed:",q)}return this.addToHistory({executionId:Z,toolName:$.toolName,params:$.params,result:G,startTime:X,endTime:Q,context:$.context}),this.emit("executionFailed",{executionId:Z,toolName:$.toolName,error:Y,duration:Q-X,timestamp:Q}),G}}async executeAll($){let Z=$.map((X)=>this.execute(X.toolName,X.params,X.context));return Promise.all(Z)}async executeParallel($,Z=5){let X=[],Y=[];for(let Q=0;Q<$.length;Q++){let J=$[Q],G=this.execute(J.toolName,J.params,J.context);if(Y.push(G),Y.length>=Z||Q===$.length-1){let q=await Promise.all(Y);X.push(...q),Y.length=0}}return X}getExecutionHistory($){let Z=[...this.executionHistory];return $?Z.slice(-$):Z}clearHistory(){this.executionHistory=[],this.emit("historyClear",{timestamp:Date.now()})}getStats(){let $={totalExecutions:this.executionHistory.length,successfulExecutions:0,failedExecutions:0,averageDuration:0,toolUsage:new Map,recentExecutions:this.executionHistory.slice(-10)},Z=0;for(let X of this.executionHistory){if(X.result.success)$.successfulExecutions++;else $.failedExecutions++;let Y=X.endTime-X.startTime;Z+=Y;let Q=$.toolUsage.get(X.toolName)||0;$.toolUsage.set(X.toolName,Q+1)}return $.averageDuration=$.totalExecutions>0?Z/$.totalExecutions:0,$}addStage($,Z=-1){if(Z===-1){let X=this.stages.findIndex((Y)=>Y.name==="execution");this.stages.splice(X,0,$)}else this.stages.splice(Z,0,$);this.emit("stageAdded",{stageName:$.name,position:Z,timestamp:Date.now()})}removeStage($){let Z=this.stages.findIndex((X)=>X.name===$);if(Z===-1)return!1;return this.stages.splice(Z,1),this.emit("stageRemoved",{stageName:$,timestamp:Date.now()}),!0}getStages(){return[...this.stages]}getRegistry(){return this.registry}generateExecutionId(){return`exec_${Date.now()}_${Math.random().toString(36).substr(2,9)}`}addToHistory($){if(this.executionHistory.push($),this.executionHistory.length>this.maxHistorySize)this.executionHistory=this.executionHistory.slice(-this.maxHistorySize)}}});import{EventEmitter as N_}from"events";var A6;var IG=A(()=>{U$();A6=class A6 extends N_{tools=new Map;mcpTools=new Map;categories=new Map;tags=new Map;constructor(){super()}register($){if(this.tools.has($.name))throw Error(`工具 '${$.name}' 已注册`);this.tools.set($.name,$),this.updateIndexes($),this.emit("toolRegistered",{type:"builtin",tool:$,timestamp:Date.now()})}registerAll($){let Z=[];for(let X of $)try{this.register(X)}catch(Y){Z.push(`${X.name}: ${Y.message}`)}if(Z.length>0)throw Error(`批量注册失败: ${Z.join(", ")}`)}unregister($){let Z=this.tools.get($);if(!Z)return!1;return this.tools.delete($),this.removeFromIndexes(Z),this.emit("toolUnregistered",{type:"builtin",toolName:$,timestamp:Date.now()}),!0}get($){return this.tools.get($)||this.mcpTools.get($)}has($){return this.tools.has($)||this.mcpTools.has($)}getAll(){return[...Array.from(this.tools.values()),...Array.from(this.mcpTools.values())]}getBuiltinTools(){return Array.from(this.tools.values())}getMcpTools(){return Array.from(this.mcpTools.values())}getByCategory($){let Z=this.categories.get($);if(!Z)return[];return Array.from(Z).map((X)=>this.get(X)).filter((X)=>X!==void 0)}getByTag($){let Z=this.tags.get($);if(!Z)return[];return Array.from(Z).map((X)=>this.get(X)).filter((X)=>X!==void 0)}search($){let Z=$.toLowerCase();return this.getAll().filter((X)=>{let Y=typeof X.description==="string"?X.description:X.description.short;return X.name.toLowerCase().includes(Z)||Y.toLowerCase().includes(Z)||X.displayName.toLowerCase().includes(Z)||X.category&&X.category.toLowerCase().includes(Z)||X.tags.some((Q)=>Q.toLowerCase().includes(Z))})}getFunctionDeclarations(){return this.getAll().map(($)=>$.getFunctionDeclaration())}getReadOnlyFunctionDeclarations(){return this.getAll().filter(($)=>$.isReadOnly).map(($)=>$.getFunctionDeclaration())}getFunctionDeclarationsByMode($){if($==="plan")return this.getReadOnlyFunctionDeclarations();if($==="spec")return this.getSpecModeFunctionDeclarations();return this.getFunctionDeclarations()}static SPEC_TOOLS=["EnterSpecMode","UpdateSpec","GetSpecContext","TransitionSpecPhase","AddTask","UpdateTaskStatus","ValidateSpec","ExitSpecMode"];getSpecModeFunctionDeclarations(){return this.getFunctionDeclarations()}isSpecTool($){return A6.SPEC_TOOLS.includes($)}getReadOnlyTools(){return this.getAll().filter(($)=>$.isReadOnly)}getCategories(){return Array.from(this.categories.keys())}getTags(){return Array.from(this.tags.keys())}getStats(){return{totalTools:this.tools.size+this.mcpTools.size,builtinTools:this.tools.size,mcpTools:this.mcpTools.size,categories:this.categories.size,tags:this.tags.size,toolsByCategory:Object.fromEntries(Array.from(this.categories.entries()).map(([$,Z])=>[$,Z.size]))}}registerMcpTool($){if(this.mcpTools.has($.name))this.mcpTools.delete($.name);this.mcpTools.set($.name,$),this.updateIndexes($),this.emit("toolRegistered",{type:"mcp",tool:$,timestamp:Date.now()})}removeMcpTools($){let Z=0,X=`mcp__${$}__`;for(let[Y,Q]of this.mcpTools.entries())if(Y.startsWith(X))this.mcpTools.delete(Y),this.removeFromIndexes(Q),Z++,this.emit("toolUnregistered",{type:"mcp",toolName:Y,serverName:$,timestamp:Date.now()});return Z}updateIndexes($){if($.category){if(!this.categories.has($.category))this.categories.set($.category,new Set);this.categories.get($.category).add($.name)}for(let Z of $.tags){if(!this.tags.has(Z))this.tags.set(Z,new Set);this.tags.get(Z).add($.name)}}removeFromIndexes($){if($.category){let Z=this.categories.get($.category);if(Z){if(Z.delete($.name),Z.size===0)this.categories.delete($.category)}}for(let Z of $.tags){let X=this.tags.get(Z);if(X){if(X.delete($.name),X.size===0)this.tags.delete(Z)}}}}});function A_($){return b_.some((Z)=>Z.test($))}function R_($){if($.supportsThinking!==void 0)return{supportsThinking:$.supportsThinking,thinkingBudget:$.thinkingBudget};return{supportsThinking:A_($.model),thinkingBudget:void 0}}function t4($){return R_($).supportsThinking}var b_;var R6=A(()=>{b_=[/deepseek.*r1/i,/deepseek.*reasoner/i,/o1-preview/i,/o1-mini/i,/o1/i,/qwen.*qwq/i,/qwen.*think/i,/kimi.*k1/i,/moonshot.*think/i,/k1-32k/i,/doubao.*think/i,/doubao.*pro.*think/i,/claude.*opus.*4/i,/glm-4\.7/i]});class d5{maxSummaryLength;keyPointsLimit;recentMessagesLimit;constructor($=500,Z=10,X=20){this.maxSummaryLength=$,this.keyPointsLimit=Z,this.recentMessagesLimit=X}async compress($){let Z=$.layers.conversation.messages,X=$.layers.tool.recentCalls,Y=Z.filter((H)=>H.role==="system"),Q=Z.filter((H)=>H.role!=="system"),J=this.getRecentMessages(Q),G=Q.slice(0,-this.recentMessagesLimit),q=await this.generateSummary(G),K=this.extractKeyPoints(G,X),W=this.generateToolSummary(X),U=this.estimateTokenCount(q,K,J,W);return{summary:q,keyPoints:K,recentMessages:[...Y,...J],toolSummary:W,tokenCount:U}}getRecentMessages($){return $.slice(-this.recentMessagesLimit)}async generateSummary($){if($.length===0)return"";let Z=new Set,X=new Set,Y=new Set;for(let J of $){let G=J.content.toLowerCase();["关于","讨论","问题","项目","功能","需求"].forEach((U)=>{if(G.includes(U)){let H=this.extractContext(G,U,50);if(H)Z.add(H)}}),["创建","删除","修改","更新","实现","开发"].forEach((U)=>{if(G.includes(U)){let H=this.extractContext(G,U,30);if(H)X.add(H)}}),["决定","选择","确定","采用","使用"].forEach((U)=>{if(G.includes(U)){let H=this.extractContext(G,U,40);if(H)Y.add(H)}})}let Q=`对话涉及 ${$.length} 条消息。`;if(Z.size>0)Q+=` 主要讨论:${Array.from(Z).slice(0,3).join("、")}。`;if(X.size>0)Q+=` 执行操作:${Array.from(X).slice(0,3).join("、")}。`;if(Y.size>0)Q+=` 关键决策:${Array.from(Y).slice(0,2).join("、")}。`;return Q.length>this.maxSummaryLength?Q.substring(0,this.maxSummaryLength)+"...":Q}extractKeyPoints($,Z){let X=new Set;for(let Q of $)if(Q.role==="user")this.extractQuestions(Q.content).forEach((q)=>X.add(`用户问题:${q}`)),this.extractRequests(Q.content).forEach((q)=>X.add(`用户请求:${q}`));else if(Q.role==="assistant")this.extractSolutions(Q.content).forEach((G)=>X.add(`解决方案:${G}`));return this.summarizeToolUsage(Z).forEach((Q)=>X.add(`工具使用:${Q}`)),Array.from(X).slice(0,this.keyPointsLimit)}generateToolSummary($){if($.length===0)return"";let Z=new Map,X=Date.now()-600000;for(let Q of $){let J=Z.get(Q.name)||{count:0,success:0,recent:0};if(J.count++,Q.status==="success")J.success++;if(Q.timestamp>X)J.recent++;Z.set(Q.name,J)}let Y=[];for(let[Q,J]of Array.from(Z.entries())){let G=Math.round(J.success/J.count*100);Y.push(`${Q}(${J.count}次,成功率${G}%)`)}return`工具调用:${Y.join("、")}`}estimateTokenCount($,Z,X,Y){let Q=$.length+Z.join(" ").length;if(Y)Q+=Y.length;for(let J of X)Q+=J.content.length;return Math.ceil(Q/4)}extractContext($,Z,X){let Y=$.indexOf(Z);if(Y===-1)return null;let Q=Math.max(0,Y-X/2),J=Math.min($.length,Y+X/2);return $.substring(Q,J).trim()}extractQuestions($){let Z=[],X=["?","?","如何","怎么","什么","为什么"],Y=$.split(/[。!.!]/);for(let Q of Y)if(X.some((J)=>Q.includes(J))){let J=Q.trim();if(J.length>5&&J.length<100)Z.push(J)}return Z.slice(0,3)}extractRequests($){let Z=[],X=["请","帮我","需要","想要","希望","能否"],Y=$.split(/[。!.!]/);for(let Q of Y)if(X.some((J)=>Q.includes(J))){let J=Q.trim();if(J.length>5&&J.length<100)Z.push(J)}return Z.slice(0,3)}extractSolutions($){let Z=[],X=["可以","建议","推荐","应该","最好","解决方案"],Y=$.split(/[。!.!]/);for(let Q of Y)if(X.some((J)=>Q.includes(J))){let J=Q.trim();if(J.length>10&&J.length<150)Z.push(J)}return Z.slice(0,3)}summarizeToolUsage($){let Z=[],X=$.filter((Y)=>Date.now()-Y.timestamp<1800000);if(X.length>0){let Y=new Map;X.forEach((Q)=>{let J=Y.get(Q.name)||[];J.push(Q),Y.set(Q.name,J)});for(let[Q,J]of Array.from(Y.entries())){let G=J.filter((q)=>q.status==="success").length;Z.push(`${Q}(${J.length}次,${G}成功)`)}}return Z.slice(0,5)}shouldCompress($,Z){return this.estimateCurrentTokens($)>Z*0.8}estimateCurrentTokens($){let X=$.layers.conversation.messages.reduce((Y,Q)=>Y+Q.content.length,0);return Math.ceil(X/4)}}class K4{defaultOptions;constructor($){this.defaultOptions={maxTokens:32000,maxMessages:50,timeWindow:86400000,priority:1,includeTools:!0,includeWorkspace:!0,...$}}filter($,Z){let X={...this.defaultOptions,...Z},Y={layers:{system:$.layers.system,session:$.layers.session,conversation:this.filterConversation($.layers.conversation,X),tool:X.includeTools?this.filterTools($.layers.tool,X):{recentCalls:[],toolStates:{},dependencies:{}},workspace:X.includeWorkspace?$.layers.workspace:{currentFiles:[],recentFiles:[],environment:{}}},metadata:{...$.metadata,lastUpdated:Date.now()}};return Y.metadata.totalTokens=this.estimateTokens(Y),Y}filterConversation($,Z){let X=[...$.messages];if(Z.timeWindow>0){let Y=Date.now()-Z.timeWindow;X=X.filter((Q)=>Q.timestamp>=Y||Q.role==="system")}if(Z.priority>1)X=this.filterByPriority(X,Z.priority);if(Z.maxMessages>0)X=this.limitMessages(X,Z.maxMessages);if(Z.maxTokens>0)X=this.limitByTokens(X,Z.maxTokens);return{messages:X,summary:$.summary,topics:this.updateTopics(X,$.topics),lastActivity:$.lastActivity}}filterTools($,Z){let X=[...$.recentCalls];if(Z.timeWindow>0){let K=Date.now()-Z.timeWindow;X=X.filter((W)=>W.timestamp>=K)}let Y=X.filter((K)=>K.status==="success"),Q=X.filter((K)=>K.status==="error"),J=Math.min(20,Y.length),G=Math.min(10,Q.length);return{recentCalls:[...Y.slice(-J),...Q.slice(-G)].sort((K,W)=>K.timestamp-W.timestamp),toolStates:$.toolStates,dependencies:$.dependencies}}filterByPriority($,Z){return $.filter((X)=>{if(X.role==="system")return!0;return this.calculateMessagePriority(X)>=Z})}calculateMessagePriority($){let Z=1;if($.role==="system")Z+=3;else if($.role==="assistant")Z+=1;let X=$.content.toLowerCase();if(["错误","警告","重要","关键","问题","解决"].some((J)=>X.includes(J)))Z+=2;if(X.includes("```")||X.includes("function")||X.includes("class"))Z+=1;let Q=(Date.now()-$.timestamp)/3600000;if(Q<1)Z+=2;else if(Q<6)Z+=1;return Z}limitMessages($,Z){if($.length<=Z)return $;let X=$.filter((G)=>G.role==="system"),Y=$.filter((G)=>G.role!=="system"),Q=Z-X.length,J=Q>0?Y.slice(-Q):[];return[...X,...J].sort((G,q)=>G.timestamp-q.timestamp)}limitByTokens($,Z){if(Z<=0)return $;let X=0,Y=[];for(let Q=$.length-1;Q>=0;Q--){let J=$[Q],G=this.estimateMessageTokens(J);if(J.role==="system")if(X+G<=Z)Y.unshift(J),X+=G;else{let q=this.compressMessage(J,Z-X);Y.unshift(q),X+=this.estimateMessageTokens(q)}else if(X+G<=Z)Y.unshift(J),X+=G;else break}return Y.sort((Q,J)=>Q.timestamp-J.timestamp)}estimateMessageTokens($){return Math.ceil($.content.length/4)}compressMessage($,Z){let X=Z*4;if($.content.length<=X)return $;let Y=$.content.substring(0,X-3)+"...";return{...$,content:Y,metadata:{...$.metadata,compressed:!0,originalLength:$.content.length}}}updateTopics($,Z){let X=new Set(Z);for(let Y of $)this.extractTopicsFromMessage(Y).forEach((J)=>X.add(J));return Array.from(X).slice(0,10)}extractTopicsFromMessage($){let Z=$.content.toLowerCase(),X=[];return["项目","功能","模块","组件","服务","接口","数据库","前端","后端","算法","架构","设计"].forEach((Q)=>{if(Z.includes(Q))X.push(Q)}),X}estimateTokens($){let Z=0;for(let Y of $.layers.conversation.messages)Z+=this.estimateMessageTokens(Y);let X=JSON.stringify($.layers.system);if(Z+=Math.ceil(X.length/4),$.layers.tool.recentCalls.length>0){let Y=JSON.stringify($.layers.tool);Z+=Math.ceil(Y.length/8)}return Z}static createPresets(){return{lightweight:new K4({maxTokens:1000,maxMessages:10,timeWindow:7200000,includeTools:!1,includeWorkspace:!1}),standard:new K4({maxTokens:4000,maxMessages:30,timeWindow:43200000,includeTools:!0,includeWorkspace:!0}),comprehensive:new K4({maxTokens:8000,maxMessages:100,timeWindow:86400000,includeTools:!0,includeWorkspace:!0}),debug:new K4({maxTokens:2000,maxMessages:20,timeWindow:21600000,priority:2,includeTools:!0,includeWorkspace:!1})}}}class m5{cache=new Map;maxSize;defaultTTL;constructor($=100,Z=300000){this.maxSize=$,this.defaultTTL=Z}set($,Z,X){let Y=Date.now(),Q={data:Z,timestamp:Y,accessCount:0,lastAccess:Y,ttl:X||this.defaultTTL};if(this.cache.size>=this.maxSize&&!this.cache.has($))this.evictLeastUsed();this.cache.set($,Q)}get($){let Z=this.cache.get($);if(!Z)return null;let X=Date.now();if(X-Z.timestamp>Z.ttl)return this.cache.delete($),null;return Z.accessCount++,Z.lastAccess=X,Z.data}has($){let Z=this.cache.get($);if(!Z)return!1;if(Date.now()-Z.timestamp>Z.ttl)return this.cache.delete($),!1;return!0}delete($){return this.cache.delete($)}clear(){this.cache.clear()}size(){return this.cleanExpired(),this.cache.size}cacheMessageSummary($,Z,X){let Y=`summary:${$}:${Z.length}`;this.set(Y,{summary:X,messageCount:Z.length,lastMessage:Z[Z.length-1]?.timestamp||0},600000)}getMessageSummary($,Z){let X=`summary:${$}:${Z}`;return this.get(X)}cacheToolResult($,Z,X){let Y=this.hashInput(Z),Q=`tool:${$}:${Y}`;this.set(Q,X,1800000)}getToolResult($,Z){let X=this.hashInput(Z),Y=`tool:${$}:${X}`;return this.get(Y)}cacheCompressedContext($,Z){let X=`compressed:${$}`;this.set(X,Z,900000)}getCompressedContext($){let Z=`compressed:${$}`;return this.get(Z)}getStats(){this.cleanExpired();let $=0,Z=0,X=[];for(let[Y,Q]of Array.from(this.cache.entries()))$+=Q.accessCount,Z+=this.estimateItemSize(Q),X.push({key:Y,accessCount:Q.accessCount,lastAccess:Q.lastAccess});return X.sort((Y,Q)=>Q.accessCount-Y.accessCount),{size:this.cache.size,maxSize:this.maxSize,hitRate:$>0?$/($+this.cache.size):0,memoryUsage:Z,topKeys:X.slice(0,10)}}cleanExpired(){let $=Date.now(),Z=[];for(let[X,Y]of Array.from(this.cache.entries()))if($-Y.timestamp>Y.ttl)Z.push(X);Z.forEach((X)=>this.cache.delete(X))}evictLeastUsed(){let $=null,Z=1/0,X=Date.now();for(let[Y,Q]of Array.from(this.cache.entries())){let J=1/(X-Q.lastAccess+1),G=Q.accessCount,q=J*G;if(q<Z)Z=q,$=Y}if($)this.cache.delete($)}hashInput($){let Z=JSON.stringify($),X=0;for(let Y=0;Y<Z.length;Y++){let Q=Z.charCodeAt(Y);X=(X<<5)-X+Q,X=X&X}return Math.abs(X).toString(36)}estimateItemSize($){try{return JSON.stringify($).length*2}catch{return 1000}}setTTL($,Z){let X=this.cache.get($);if(X)return X.ttl=Z,X.timestamp=Date.now(),!0;return!1}getRemainingTTL($){let Z=this.cache.get($);if(!Z)return-1;let X=Z.ttl-(Date.now()-Z.timestamp);return Math.max(0,X)}warmup($){$.forEach(({key:Z,value:X,ttl:Y})=>{this.set(Z,X,Y)})}}class u5{contextData=null;maxSize;accessLog=new Map;constructor($=1000){this.maxSize=$}setContext($){this.contextData={...$},this.contextData.metadata.lastUpdated=Date.now(),this.recordAccess("context")}getContext(){if(this.contextData)this.recordAccess("context");return this.contextData}addMessage($){if(!this.contextData)throw Error("上下文数据未初始化");this.contextData.layers.conversation.messages.push($),this.contextData.layers.conversation.lastActivity=Date.now(),this.contextData.metadata.lastUpdated=Date.now(),this.enforceMemoryLimit(),this.recordAccess("messages")}getRecentMessages($=10){if(!this.contextData)return[];let Z=this.contextData.layers.conversation.messages;return this.recordAccess("messages"),Z.slice(-$)}addToolCall($){if(!this.contextData)throw Error("上下文数据未初始化");if(this.contextData.layers.tool.recentCalls.push($),this.contextData.metadata.lastUpdated=Date.now(),this.contextData.layers.tool.recentCalls.length>50)this.contextData.layers.tool.recentCalls=this.contextData.layers.tool.recentCalls.slice(-25);this.recordAccess("tools")}updateToolState($,Z){if(!this.contextData)throw Error("上下文数据未初始化");this.contextData.layers.tool.toolStates[$]=Z,this.contextData.metadata.lastUpdated=Date.now(),this.recordAccess("tools")}getToolState($){if(!this.contextData)return null;return this.recordAccess("tools"),this.contextData.layers.tool.toolStates[$]}updateWorkspace($){if(!this.contextData)throw Error("上下文数据未初始化");Object.assign(this.contextData.layers.workspace,$),this.contextData.metadata.lastUpdated=Date.now(),this.recordAccess("workspace")}clear(){this.contextData=null,this.accessLog.clear()}getMemoryInfo(){if(!this.contextData)return{hasData:!1,messageCount:0,toolCallCount:0,lastUpdated:null};return{hasData:!0,messageCount:this.contextData.layers.conversation.messages.length,toolCallCount:this.contextData.layers.tool.recentCalls.length,lastUpdated:this.contextData.metadata.lastUpdated}}recordAccess($){this.accessLog.set($,Date.now())}enforceMemoryLimit(){if(!this.contextData)return;let $=this.contextData.layers.conversation.messages;if($.length>this.maxSize){let Z=Math.floor(this.maxSize*0.8);this.contextData.layers.conversation.messages=$.slice(-Z)}}getMemoryUsage(){if(!this.contextData)return 0;return JSON.stringify(this.contextData).length}}import*as V6 from"node:fs";import{createReadStream as V_}from"node:fs";import*as l$ from"node:fs/promises";import*as g5 from"node:path";import{createInterface as D_}from"node:readline";class I1{filePath;constructor($){this.filePath=$}async append($){try{await l$.mkdir(g5.dirname(this.filePath),{recursive:!0});let Z=JSON.stringify($)+`
|
|
2090
2090
|
`;await l$.appendFile(this.filePath,Z,"utf-8")}catch(Z){throw console.error(`[JSONLStore] 追加写入失败: ${this.filePath}`,Z),Z}}async appendBatch($){try{await l$.mkdir(g5.dirname(this.filePath),{recursive:!0});let Z=$.map((X)=>JSON.stringify(X)).join(`
|
|
2091
2091
|
`)+`
|
|
2092
2092
|
`;await l$.appendFile(this.filePath,Z,"utf-8")}catch(Z){throw console.error(`[JSONLStore] 批量追加写入失败: ${this.filePath}`,Z),Z}}async readAll(){try{if(!V6.existsSync(this.filePath))return[];let Z=(await l$.readFile(this.filePath,"utf-8")).split(`
|
|
2093
2093
|
`).filter((Y)=>Y.trim().length>0),X=[];for(let Y of Z)try{X.push(JSON.parse(Y))}catch(Q){console.warn(`[JSONLStore] 解析 JSON 行失败: ${Y}`,Q)}return X}catch($){return console.error(`[JSONLStore] 读取文件失败: ${this.filePath}`,$),[]}}async readStream($){return new Promise((Z,X)=>{if(!V6.existsSync(this.filePath)){Z();return}let Y=V_(this.filePath,"utf-8"),Q=D_({input:Y,crlfDelay:Number.POSITIVE_INFINITY});Q.on("line",async(J)=>{let G=J.trim();if(G.length===0)return;try{let q=JSON.parse(G);await $(q)}catch(q){console.warn(`[JSONLStore] 解析 JSON 行失败: ${G}`,q)}}),Q.on("close",()=>Z()),Q.on("error",X),Y.on("error",X)})}async filter($){let Z=[];return await this.readStream((X)=>{if($(X))Z.push(X)}),Z}async readLast($){return(await this.readAll()).slice(-$)}async getStats(){try{if(!V6.existsSync(this.filePath))return{exists:!1,size:0,lineCount:0};let $=await l$.stat(this.filePath),X=(await l$.readFile(this.filePath,"utf-8")).split(`
|
|
2094
|
-
`).filter((Y)=>Y.trim().length>0).length;return{exists:!0,size:$.size,lineCount:X}}catch($){return console.error(`[JSONLStore] 获取统计信息失败: ${this.filePath}`,$),{exists:!1,size:0,lineCount:0}}}async exists(){try{return await l$.access(this.filePath),!0}catch{return!1}}async delete(){try{if(await this.exists())await l$.unlink(this.filePath)}catch($){throw console.error(`[JSONLStore] 删除文件失败: ${this.filePath}`,$),$}}getFilePath(){return this.filePath}}var yG=()=>{};import{nanoid as e2}from"nanoid";import*as q4 from"node:fs/promises";import*as vG from"node:path";class c5{projectPath;maxSessions;version;constructor($=process.cwd(),Z=100,X="0.0.10"){this.projectPath=$,this.maxSessions=Z,this.version=X}async initialize(){try{let $=e8(this.projectPath);await q4.mkdir($,{recursive:!0}),console.log(`[PersistentStore] 初始化存储目录: ${$}`)}catch($){console.warn("[PersistentStore] 无法创建持久化存储目录:",$)}}async saveMessage($,Z,X,Y=null,Q){try{let J=H1(this.projectPath,$),G=new I1(J),q={uuid:e2(),parentUuid:Y,sessionId:$,timestamp:new Date().toISOString(),type:Z==="user"?"user":Z==="assistant"?"assistant":Z==="tool"?"tool_result":"system",cwd:this.projectPath,gitBranch:c2(this.projectPath),version:this.version,message:{role:Z,content:X,...Q||{}}};return await G.append(q),q.uuid}catch(J){throw console.error(`[PersistentStore] 保存消息失败 (session: ${$}):`,J),J}}async saveToolUse($,Z,X,Y=null){try{let Q=H1(this.projectPath,$),J=new I1(Q),G={uuid:e2(),parentUuid:Y,sessionId:$,timestamp:new Date().toISOString(),type:"tool_use",cwd:this.projectPath,gitBranch:c2(this.projectPath),version:this.version,message:{role:"assistant",content:""},tool:{id:e2(),name:Z,input:X}};return await J.append(G),G.uuid}catch(Q){throw console.error(`[PersistentStore] 保存工具调用失败 (session: ${$}):`,Q),Q}}async saveToolResult($,Z,X,Y=null,Q){try{let J=H1(this.projectPath,$),G=new I1(J),q={uuid:e2(),parentUuid:Y,sessionId:$,timestamp:new Date().toISOString(),type:"tool_result",cwd:this.projectPath,gitBranch:c2(this.projectPath),version:this.version,message:{role:"assistant",content:""},toolResult:{id:Z,output:X,error:Q}};return await G.append(q),q.uuid}catch(J){throw console.error(`[PersistentStore] 保存工具结果失败 (session: ${$}):`,J),J}}async saveCompaction($,Z,X,Y=null){try{let Q=H1(this.projectPath,$),J=new I1(Q),G={uuid:e2(),parentUuid:Y,sessionId:$,timestamp:new Date().toISOString(),type:"system",subtype:"compact_boundary",cwd:this.projectPath,gitBranch:c2(this.projectPath),version:this.version,message:{role:"system",content:"=== 上下文压缩边界 ==="},compactMetadata:X};await J.append(G),console.log("[PersistentStore] 保存压缩边界标记");let q={uuid:e2(),parentUuid:G.uuid,logicalParentUuid:Y??void 0,sessionId:$,timestamp:new Date().toISOString(),type:"user",isCompactSummary:!0,cwd:this.projectPath,gitBranch:c2(this.projectPath),version:this.version,message:{role:"user",content:Z},compactMetadata:X};return await J.append(q),console.log("[PersistentStore] 保存压缩总结消息"),q.uuid}catch(Q){throw console.error(`[PersistentStore] 保存压缩失败 (session: ${$}):`,Q),Q}}async saveContext($,Z){try{let{conversation:X}=Z.layers;for(let Y of X.messages)await this.saveMessage($,Y.role,Y.content,null)}catch(X){console.warn(`[PersistentStore] 保存上下文失败 (session: ${$}):`,X)}}async saveSession($,Z){console.warn("[PersistentStore] saveSession 方法已废弃,请使用 saveMessage")}async saveConversation($,Z){console.warn("[PersistentStore] saveConversation 方法已废弃,请使用 saveMessage")}async loadSession($){try{let Z=H1(this.projectPath,$),Y=await new I1(Z).readAll();if(Y.length===0)return null;let Q=Y[0];return{sessionId:$,userId:void 0,preferences:{},configuration:{},startTime:new Date(Q.timestamp).getTime()}}catch{return null}}async loadConversation($){try{let Z=H1(this.projectPath,$),Y=await new I1(Z).readAll();if(Y.length===0)return null;let Q=Y.filter((q)=>["user","assistant","system"].includes(q.type)).map((q)=>({id:q.uuid,role:q.message.role,content:q.message.content,timestamp:new Date(q.timestamp).getTime()})),J=Y[Y.length-1],G=new Date(J.timestamp).getTime();return{messages:Q,topics:[],lastActivity:G}}catch{return null}}async listSessions(){try{let $=e8(this.projectPath);return(await q4.readdir($)).filter((X)=>X.endsWith(".jsonl")).map((X)=>X.replace(".jsonl","")).sort()}catch{return[]}}async getSessionSummary($){try{let Z=H1(this.projectPath,$),X=new I1(Z);if(!(await X.getStats()).exists)return null;let Q=await X.readAll();if(Q.length===0)return null;let J=Q[Q.length-1];return{sessionId:$,lastActivity:new Date(J.timestamp).getTime(),messageCount:Q.filter((G)=>["user","assistant"].includes(G.type)).length,topics:[]}}catch{return null}}async deleteSession($){try{let Z=H1(this.projectPath,$);await new I1(Z).delete()}catch(Z){console.warn(`[PersistentStore] 删除会话失败 (session: ${$}):`,Z)}}async cleanupOldSessions(){try{let $=await this.listSessions();if($.length<=this.maxSessions)return;let Y=(await Promise.all($.map((Q)=>this.getSessionSummary(Q)))).filter((Q)=>Q!==null).sort((Q,J)=>J.lastActivity-Q.lastActivity).slice(this.maxSessions).map((Q)=>Q.sessionId);await Promise.all(Y.map((Q)=>this.deleteSession(Q))),console.log(`[PersistentStore] 已清理 ${Y.length} 个旧会话`)}catch($){console.error("[PersistentStore] 清理旧会话失败:",$)}}async getStorageStats(){try{let $=await this.listSessions(),Z=0;for(let X of $){let Y=H1(this.projectPath,X),J=await new I1(Y).getStats();Z+=J.size}return{totalSessions:$.length,totalSize:Z,projectPath:this.projectPath}}catch{return{totalSessions:0,totalSize:0,projectPath:this.projectPath}}}async checkStorageHealth(){try{let $=e8(this.projectPath);await q4.mkdir($,{recursive:!0});let Z=vG.join($,".health-check");return await q4.writeFile(Z,"test","utf-8"),await q4.unlink(Z),{isAvailable:!0,canWrite:!0}}catch($){return{isAvailable:!1,canWrite:!1,error:$ instanceof Error?$.message:String($)}}}static async listAllProjects(){return EQ()}}var EG=A(()=>{yG();$3()});import*as TG from"crypto";import{nanoid as PG}from"nanoid";class Q3{memory;persistent;cache;compressor;filter;options;currentSessionId=null;initialized=!1;constructor($={}){let Z=$.storage?.persistentPath||X2();this.options={storage:{maxMemorySize:1000,persistentPath:Z,cacheSize:100,compressionEnabled:!0,...$.storage},defaultFilter:{maxTokens:32000,maxMessages:50,timeWindow:86400000,...$.defaultFilter},compressionThreshold:$.compressionThreshold||6000,enableVectorSearch:$.enableVectorSearch||!1},this.memory=new u5(this.options.storage.maxMemorySize),this.persistent=new c5(process.cwd(),100),this.cache=new m5(this.options.storage.cacheSize,300000),this.compressor=new d5,this.filter=new K2(this.options.defaultFilter)}async initialize(){if(this.initialized)return;try{if(await this.persistent.initialize(),!(await this.persistent.checkStorageHealth()).isAvailable)console.warn("警告:持久化存储不可用,将仅使用内存存储");this.initialized=!0,console.log("上下文管理器初始化完成")}catch($){throw console.error("上下文管理器初始化失败:",$),$}}async createSession($,Z={},X={}){let Y=X.sessionId||this.generateSessionId(),Q=Date.now(),J={layers:{system:await this.createSystemContext(),session:{sessionId:Y,userId:$,preferences:Z,configuration:X,startTime:Q},conversation:{messages:[],topics:[],lastActivity:Q},tool:{recentCalls:[],toolStates:{},dependencies:{}},workspace:await this.createWorkspaceContext()},metadata:{totalTokens:0,priority:1,lastUpdated:Q}};return this.memory.setContext(J),await this.persistent.saveContext(Y,J),this.currentSessionId=Y,console.log(`新会话已创建: ${Y}`),Y}async loadSession($){try{let Z=this.memory.getContext();if(!Z||Z.layers.session.sessionId!==$){let[X,Y]=await Promise.all([this.persistent.loadSession($),this.persistent.loadConversation($)]);if(!X||!Y)return!1;Z={layers:{system:await this.createSystemContext(),session:X,conversation:Y,tool:{recentCalls:[],toolStates:{},dependencies:{}},workspace:await this.createWorkspaceContext()},metadata:{totalTokens:0,priority:1,lastUpdated:Date.now()}},this.memory.setContext(Z)}return this.currentSessionId=$,console.log(`会话已加载: ${$}`),!0}catch(Z){return console.error("加载会话失败:",Z),!1}}async addMessage($,Z,X){if(!this.currentSessionId)throw Error("没有活动会话");let Y={id:this.generateMessageId(),role:$,content:Z,timestamp:Date.now(),metadata:X};this.memory.addMessage(Y);let Q=this.memory.getContext();if(Q&&this.shouldCompress(Q))await this.compressCurrentContext();this.saveCurrentSessionAsync()}async addToolCall($){if(!this.currentSessionId)throw Error("没有活动会话");if(this.memory.addToolCall($),$.status==="success"&&$.output)this.cache.cacheToolResult($.name,$.input,$.output);this.saveCurrentSessionAsync()}async saveMessage($,Z,X,Y=null,Q){return this.persistent.saveMessage($,Z,X,Y,Q)}async saveToolUse($,Z,X,Y=null){return this.persistent.saveToolUse($,Z,X,Y)}async saveToolResult($,Z,X,Y=null,Q){return this.persistent.saveToolResult($,Z,X,Y,Q)}async saveCompaction($,Z,X,Y=null){return this.persistent.saveCompaction($,Z,X,Y)}updateToolState($,Z){if(!this.currentSessionId)throw Error("没有活动会话");this.memory.updateToolState($,Z)}updateWorkspace($){if(!this.currentSessionId)throw Error("没有活动会话");this.memory.updateWorkspace($)}async getFormattedContext($){let Z=this.memory.getContext();if(!Z)throw Error("没有可用的上下文数据");let X=this.filter.filter(Z,$),Y=this.shouldCompress(X),Q;if(Y){let J=this.hashContext(X);if(Q=this.cache.getCompressedContext(J)??void 0,!Q)Q=await this.compressor.compress(X),this.cache.cacheCompressedContext(J,Q)}return{context:X,compressed:Q,tokenCount:Q?Q.tokenCount:X.metadata.totalTokens}}async searchSessions($,Z=10){let X=await this.persistent.listSessions(),Y=[];for(let Q of X){let J=await this.persistent.getSessionSummary(Q);if(J){let G=this.calculateRelevance($,J.topics);if(G>0)Y.push({sessionId:Q,summary:`${J.messageCount}条消息,主题:${J.topics.join("、")}`,lastActivity:J.lastActivity,relevanceScore:G})}}return Y.sort((Q,J)=>J.relevanceScore-Q.relevanceScore).slice(0,Z)}getCachedToolResult($,Z){return this.cache.getToolResult($,Z)}async getStats(){let[$,Z,X]=await Promise.all([Promise.resolve(this.memory.getMemoryInfo()),Promise.resolve(this.cache.getStats()),this.persistent.getStorageStats()]);return{currentSession:this.currentSessionId,memory:$,cache:Z,storage:X}}async cleanup(){if(this.currentSessionId)await this.saveCurrentSession();this.memory.clear(),this.cache.clear(),await this.persistent.cleanupOldSessions(),this.currentSessionId=null,console.log("上下文管理器资源清理完成")}generateSessionId(){return PG()}generateMessageId(){return PG()}async createSystemContext(){return{role:"AI助手",capabilities:["对话","工具调用","代码生成","文档分析"],tools:["文件操作","Git操作","代码分析"],version:"1.0.0"}}async createWorkspaceContext(){try{let $=process.cwd();return{projectPath:$,currentFiles:[],recentFiles:[],environment:{nodeVersion:process.version,platform:process.platform,cwd:$}}}catch($){return{currentFiles:[],recentFiles:[],environment:{}}}}shouldCompress($){return $.metadata.totalTokens>this.options.compressionThreshold}async compressCurrentContext(){let $=this.memory.getContext();if(!$)return;let Z=await this.compressor.compress($);$.layers.conversation.summary=Z.summary,this.memory.setContext($)}async saveCurrentSession(){if(!this.currentSessionId)return;let $=this.memory.getContext();if($)await this.persistent.saveContext(this.currentSessionId,$)}saveCurrentSessionAsync(){this.saveCurrentSession().catch(($)=>{console.warn("异步保存会话失败:",$)})}hashContext($){let Z=JSON.stringify({messageCount:$.layers.conversation.messages.length,lastMessage:$.layers.conversation.messages[$.layers.conversation.messages.length-1]?.id,toolCallCount:$.layers.tool.recentCalls.length});return TG.createHash("md5").update(Z).digest("hex")}calculateRelevance($,Z){let X=$.toLowerCase(),Y=0;for(let Q of Z)if(X.includes(Q.toLowerCase())||Q.toLowerCase().includes(X))Y+=1;return Y}}var l5=A(()=>{EG();$3()});class i5{chatService;contextManager;memoryAdapter;constructor($,Z){this.chatService=$,this.contextManager=Z||new Q3,this.memoryAdapter=this.createMemoryAdapter()}createMemoryAdapter(){let $=[];return{getMessages:()=>[...$],addMessage:(Z)=>{$.push(Z)},clearContext:()=>{$.length=0},getContextSize:()=>$.length}}getContextManager(){return this.contextManager}getMemoryAdapter(){return this.memoryAdapter}async executeTask($){let Z=[{role:"user",content:$.prompt}],X=await this.chatService.chat(Z);return{taskId:$.id,content:X.content,metadata:{taskType:$.type}}}}var SG=A(()=>{l5()});import*as CG from"os";import*as kG from"path";function M_($){if(typeof $==="string")return $;try{return JSON.parse(JSON.stringify($))}catch{return String($)}}class z${config;runtimeOptions;isInitialized=!1;activeTask;executionPipeline;systemPrompt;chatService;executionEngine;attachmentCollector;activeSkillContext;currentModelMaxContextTokens;constructor($,Z={},X){this.config=$,this.runtimeOptions=Z,this.executionPipeline=X||this.createDefaultPipeline()}createDefaultPipeline(){let $=new A6,Z={...this.config.permissions,...this.runtimeOptions.permissions},X=this.runtimeOptions.permissionMode??this.config.permissionMode??"default";return new p5($,{permissionConfig:Z,permissionMode:X,maxHistorySize:1000})}static async create($={}){if(await y3(),T8().length===0)throw Error(`❌ 没有可用的模型配置
|
|
2094
|
+
`).filter((Y)=>Y.trim().length>0).length;return{exists:!0,size:$.size,lineCount:X}}catch($){return console.error(`[JSONLStore] 获取统计信息失败: ${this.filePath}`,$),{exists:!1,size:0,lineCount:0}}}async exists(){try{return await l$.access(this.filePath),!0}catch{return!1}}async delete(){try{if(await this.exists())await l$.unlink(this.filePath)}catch($){throw console.error(`[JSONLStore] 删除文件失败: ${this.filePath}`,$),$}}getFilePath(){return this.filePath}}var yG=()=>{};import{nanoid as e4}from"nanoid";import*as q2 from"node:fs/promises";import*as vG from"node:path";class c5{projectPath;maxSessions;version;constructor($=process.cwd(),Z=100,X="0.0.10"){this.projectPath=$,this.maxSessions=Z,this.version=X}async initialize(){try{let $=e8(this.projectPath);await q2.mkdir($,{recursive:!0}),console.log(`[PersistentStore] 初始化存储目录: ${$}`)}catch($){console.warn("[PersistentStore] 无法创建持久化存储目录:",$)}}async saveMessage($,Z,X,Y=null,Q){try{let J=H1(this.projectPath,$),G=new I1(J),q={uuid:e4(),parentUuid:Y,sessionId:$,timestamp:new Date().toISOString(),type:Z==="user"?"user":Z==="assistant"?"assistant":Z==="tool"?"tool_result":"system",cwd:this.projectPath,gitBranch:c4(this.projectPath),version:this.version,message:{role:Z,content:X,...Q||{}}};return await G.append(q),q.uuid}catch(J){throw console.error(`[PersistentStore] 保存消息失败 (session: ${$}):`,J),J}}async saveToolUse($,Z,X,Y=null){try{let Q=H1(this.projectPath,$),J=new I1(Q),G={uuid:e4(),parentUuid:Y,sessionId:$,timestamp:new Date().toISOString(),type:"tool_use",cwd:this.projectPath,gitBranch:c4(this.projectPath),version:this.version,message:{role:"assistant",content:""},tool:{id:e4(),name:Z,input:X}};return await J.append(G),G.uuid}catch(Q){throw console.error(`[PersistentStore] 保存工具调用失败 (session: ${$}):`,Q),Q}}async saveToolResult($,Z,X,Y=null,Q){try{let J=H1(this.projectPath,$),G=new I1(J),q={uuid:e4(),parentUuid:Y,sessionId:$,timestamp:new Date().toISOString(),type:"tool_result",cwd:this.projectPath,gitBranch:c4(this.projectPath),version:this.version,message:{role:"assistant",content:""},toolResult:{id:Z,output:X,error:Q}};return await G.append(q),q.uuid}catch(J){throw console.error(`[PersistentStore] 保存工具结果失败 (session: ${$}):`,J),J}}async saveCompaction($,Z,X,Y=null){try{let Q=H1(this.projectPath,$),J=new I1(Q),G={uuid:e4(),parentUuid:Y,sessionId:$,timestamp:new Date().toISOString(),type:"system",subtype:"compact_boundary",cwd:this.projectPath,gitBranch:c4(this.projectPath),version:this.version,message:{role:"system",content:"=== 上下文压缩边界 ==="},compactMetadata:X};await J.append(G),console.log("[PersistentStore] 保存压缩边界标记");let q={uuid:e4(),parentUuid:G.uuid,logicalParentUuid:Y??void 0,sessionId:$,timestamp:new Date().toISOString(),type:"user",isCompactSummary:!0,cwd:this.projectPath,gitBranch:c4(this.projectPath),version:this.version,message:{role:"user",content:Z},compactMetadata:X};return await J.append(q),console.log("[PersistentStore] 保存压缩总结消息"),q.uuid}catch(Q){throw console.error(`[PersistentStore] 保存压缩失败 (session: ${$}):`,Q),Q}}async saveContext($,Z){try{let{conversation:X}=Z.layers;for(let Y of X.messages)await this.saveMessage($,Y.role,Y.content,null)}catch(X){console.warn(`[PersistentStore] 保存上下文失败 (session: ${$}):`,X)}}async saveSession($,Z){console.warn("[PersistentStore] saveSession 方法已废弃,请使用 saveMessage")}async saveConversation($,Z){console.warn("[PersistentStore] saveConversation 方法已废弃,请使用 saveMessage")}async loadSession($){try{let Z=H1(this.projectPath,$),Y=await new I1(Z).readAll();if(Y.length===0)return null;let Q=Y[0];return{sessionId:$,userId:void 0,preferences:{},configuration:{},startTime:new Date(Q.timestamp).getTime()}}catch{return null}}async loadConversation($){try{let Z=H1(this.projectPath,$),Y=await new I1(Z).readAll();if(Y.length===0)return null;let Q=Y.filter((q)=>["user","assistant","system"].includes(q.type)).map((q)=>({id:q.uuid,role:q.message.role,content:q.message.content,timestamp:new Date(q.timestamp).getTime()})),J=Y[Y.length-1],G=new Date(J.timestamp).getTime();return{messages:Q,topics:[],lastActivity:G}}catch{return null}}async listSessions(){try{let $=e8(this.projectPath);return(await q2.readdir($)).filter((X)=>X.endsWith(".jsonl")).map((X)=>X.replace(".jsonl","")).sort()}catch{return[]}}async getSessionSummary($){try{let Z=H1(this.projectPath,$),X=new I1(Z);if(!(await X.getStats()).exists)return null;let Q=await X.readAll();if(Q.length===0)return null;let J=Q[Q.length-1];return{sessionId:$,lastActivity:new Date(J.timestamp).getTime(),messageCount:Q.filter((G)=>["user","assistant"].includes(G.type)).length,topics:[]}}catch{return null}}async deleteSession($){try{let Z=H1(this.projectPath,$);await new I1(Z).delete()}catch(Z){console.warn(`[PersistentStore] 删除会话失败 (session: ${$}):`,Z)}}async cleanupOldSessions(){try{let $=await this.listSessions();if($.length<=this.maxSessions)return;let Y=(await Promise.all($.map((Q)=>this.getSessionSummary(Q)))).filter((Q)=>Q!==null).sort((Q,J)=>J.lastActivity-Q.lastActivity).slice(this.maxSessions).map((Q)=>Q.sessionId);await Promise.all(Y.map((Q)=>this.deleteSession(Q))),console.log(`[PersistentStore] 已清理 ${Y.length} 个旧会话`)}catch($){console.error("[PersistentStore] 清理旧会话失败:",$)}}async getStorageStats(){try{let $=await this.listSessions(),Z=0;for(let X of $){let Y=H1(this.projectPath,X),J=await new I1(Y).getStats();Z+=J.size}return{totalSessions:$.length,totalSize:Z,projectPath:this.projectPath}}catch{return{totalSessions:0,totalSize:0,projectPath:this.projectPath}}}async checkStorageHealth(){try{let $=e8(this.projectPath);await q2.mkdir($,{recursive:!0});let Z=vG.join($,".health-check");return await q2.writeFile(Z,"test","utf-8"),await q2.unlink(Z),{isAvailable:!0,canWrite:!0}}catch($){return{isAvailable:!1,canWrite:!1,error:$ instanceof Error?$.message:String($)}}}static async listAllProjects(){return EQ()}}var EG=A(()=>{yG();$3()});import*as TG from"crypto";import{nanoid as PG}from"nanoid";class Q3{memory;persistent;cache;compressor;filter;options;currentSessionId=null;initialized=!1;constructor($={}){let Z=$.storage?.persistentPath||X4();this.options={storage:{maxMemorySize:1000,persistentPath:Z,cacheSize:100,compressionEnabled:!0,...$.storage},defaultFilter:{maxTokens:32000,maxMessages:50,timeWindow:86400000,...$.defaultFilter},compressionThreshold:$.compressionThreshold||6000,enableVectorSearch:$.enableVectorSearch||!1},this.memory=new u5(this.options.storage.maxMemorySize),this.persistent=new c5(process.cwd(),100),this.cache=new m5(this.options.storage.cacheSize,300000),this.compressor=new d5,this.filter=new K4(this.options.defaultFilter)}async initialize(){if(this.initialized)return;try{if(await this.persistent.initialize(),!(await this.persistent.checkStorageHealth()).isAvailable)console.warn("警告:持久化存储不可用,将仅使用内存存储");this.initialized=!0,console.log("上下文管理器初始化完成")}catch($){throw console.error("上下文管理器初始化失败:",$),$}}async createSession($,Z={},X={}){let Y=X.sessionId||this.generateSessionId(),Q=Date.now(),J={layers:{system:await this.createSystemContext(),session:{sessionId:Y,userId:$,preferences:Z,configuration:X,startTime:Q},conversation:{messages:[],topics:[],lastActivity:Q},tool:{recentCalls:[],toolStates:{},dependencies:{}},workspace:await this.createWorkspaceContext()},metadata:{totalTokens:0,priority:1,lastUpdated:Q}};return this.memory.setContext(J),await this.persistent.saveContext(Y,J),this.currentSessionId=Y,console.log(`新会话已创建: ${Y}`),Y}async loadSession($){try{let Z=this.memory.getContext();if(!Z||Z.layers.session.sessionId!==$){let[X,Y]=await Promise.all([this.persistent.loadSession($),this.persistent.loadConversation($)]);if(!X||!Y)return!1;Z={layers:{system:await this.createSystemContext(),session:X,conversation:Y,tool:{recentCalls:[],toolStates:{},dependencies:{}},workspace:await this.createWorkspaceContext()},metadata:{totalTokens:0,priority:1,lastUpdated:Date.now()}},this.memory.setContext(Z)}return this.currentSessionId=$,console.log(`会话已加载: ${$}`),!0}catch(Z){return console.error("加载会话失败:",Z),!1}}async addMessage($,Z,X){if(!this.currentSessionId)throw Error("没有活动会话");let Y={id:this.generateMessageId(),role:$,content:Z,timestamp:Date.now(),metadata:X};this.memory.addMessage(Y);let Q=this.memory.getContext();if(Q&&this.shouldCompress(Q))await this.compressCurrentContext();this.saveCurrentSessionAsync()}async addToolCall($){if(!this.currentSessionId)throw Error("没有活动会话");if(this.memory.addToolCall($),$.status==="success"&&$.output)this.cache.cacheToolResult($.name,$.input,$.output);this.saveCurrentSessionAsync()}async saveMessage($,Z,X,Y=null,Q){return this.persistent.saveMessage($,Z,X,Y,Q)}async saveToolUse($,Z,X,Y=null){return this.persistent.saveToolUse($,Z,X,Y)}async saveToolResult($,Z,X,Y=null,Q){return this.persistent.saveToolResult($,Z,X,Y,Q)}async saveCompaction($,Z,X,Y=null){return this.persistent.saveCompaction($,Z,X,Y)}updateToolState($,Z){if(!this.currentSessionId)throw Error("没有活动会话");this.memory.updateToolState($,Z)}updateWorkspace($){if(!this.currentSessionId)throw Error("没有活动会话");this.memory.updateWorkspace($)}async getFormattedContext($){let Z=this.memory.getContext();if(!Z)throw Error("没有可用的上下文数据");let X=this.filter.filter(Z,$),Y=this.shouldCompress(X),Q;if(Y){let J=this.hashContext(X);if(Q=this.cache.getCompressedContext(J)??void 0,!Q)Q=await this.compressor.compress(X),this.cache.cacheCompressedContext(J,Q)}return{context:X,compressed:Q,tokenCount:Q?Q.tokenCount:X.metadata.totalTokens}}async searchSessions($,Z=10){let X=await this.persistent.listSessions(),Y=[];for(let Q of X){let J=await this.persistent.getSessionSummary(Q);if(J){let G=this.calculateRelevance($,J.topics);if(G>0)Y.push({sessionId:Q,summary:`${J.messageCount}条消息,主题:${J.topics.join("、")}`,lastActivity:J.lastActivity,relevanceScore:G})}}return Y.sort((Q,J)=>J.relevanceScore-Q.relevanceScore).slice(0,Z)}getCachedToolResult($,Z){return this.cache.getToolResult($,Z)}async getStats(){let[$,Z,X]=await Promise.all([Promise.resolve(this.memory.getMemoryInfo()),Promise.resolve(this.cache.getStats()),this.persistent.getStorageStats()]);return{currentSession:this.currentSessionId,memory:$,cache:Z,storage:X}}async cleanup(){if(this.currentSessionId)await this.saveCurrentSession();this.memory.clear(),this.cache.clear(),await this.persistent.cleanupOldSessions(),this.currentSessionId=null,console.log("上下文管理器资源清理完成")}generateSessionId(){return PG()}generateMessageId(){return PG()}async createSystemContext(){return{role:"AI助手",capabilities:["对话","工具调用","代码生成","文档分析"],tools:["文件操作","Git操作","代码分析"],version:"1.0.0"}}async createWorkspaceContext(){try{let $=process.cwd();return{projectPath:$,currentFiles:[],recentFiles:[],environment:{nodeVersion:process.version,platform:process.platform,cwd:$}}}catch($){return{currentFiles:[],recentFiles:[],environment:{}}}}shouldCompress($){return $.metadata.totalTokens>this.options.compressionThreshold}async compressCurrentContext(){let $=this.memory.getContext();if(!$)return;let Z=await this.compressor.compress($);$.layers.conversation.summary=Z.summary,this.memory.setContext($)}async saveCurrentSession(){if(!this.currentSessionId)return;let $=this.memory.getContext();if($)await this.persistent.saveContext(this.currentSessionId,$)}saveCurrentSessionAsync(){this.saveCurrentSession().catch(($)=>{console.warn("异步保存会话失败:",$)})}hashContext($){let Z=JSON.stringify({messageCount:$.layers.conversation.messages.length,lastMessage:$.layers.conversation.messages[$.layers.conversation.messages.length-1]?.id,toolCallCount:$.layers.tool.recentCalls.length});return TG.createHash("md5").update(Z).digest("hex")}calculateRelevance($,Z){let X=$.toLowerCase(),Y=0;for(let Q of Z)if(X.includes(Q.toLowerCase())||Q.toLowerCase().includes(X))Y+=1;return Y}}var l5=A(()=>{EG();$3()});class i5{chatService;contextManager;memoryAdapter;constructor($,Z){this.chatService=$,this.contextManager=Z||new Q3,this.memoryAdapter=this.createMemoryAdapter()}createMemoryAdapter(){let $=[];return{getMessages:()=>[...$],addMessage:(Z)=>{$.push(Z)},clearContext:()=>{$.length=0},getContextSize:()=>$.length}}getContextManager(){return this.contextManager}getMemoryAdapter(){return this.memoryAdapter}async executeTask($){let Z=[{role:"user",content:$.prompt}],X=await this.chatService.chat(Z);return{taskId:$.id,content:X.content,metadata:{taskType:$.type}}}}var SG=A(()=>{l5()});import*as CG from"os";import*as kG from"path";function M_($){if(typeof $==="string")return $;try{return JSON.parse(JSON.stringify($))}catch{return String($)}}class z${config;runtimeOptions;isInitialized=!1;activeTask;executionPipeline;systemPrompt;chatService;executionEngine;attachmentCollector;activeSkillContext;currentModelMaxContextTokens;constructor($,Z={},X){this.config=$,this.runtimeOptions=Z,this.executionPipeline=X||this.createDefaultPipeline()}createDefaultPipeline(){let $=new A6,Z={...this.config.permissions,...this.runtimeOptions.permissions},X=this.runtimeOptions.permissionMode??this.config.permissionMode??"default";return new p5($,{permissionConfig:Z,permissionMode:X,maxHistorySize:1000})}static async create($={}){if(await y3(),T8().length===0)throw Error(`❌ 没有可用的模型配置
|
|
2095
2095
|
|
|
2096
2096
|
`+`请先使用以下命令添加模型:
|
|
2097
2097
|
`+` /model add
|
|
2098
2098
|
|
|
2099
2099
|
`+`或运行初始化向导:
|
|
2100
|
-
`+" /init");let X=H$();if(!X)throw Error("❌ 配置未初始化,请确保应用已正确启动");u$.getInstance().validateConfig(X);let Q=new z$(X,$);if(await Q.initialize(),$.toolWhitelist&&$.toolWhitelist.length>0)Q.applyToolWhitelist($.toolWhitelist);return Q}async initialize(){if(this.isInitialized)return;try{this.log("初始化Agent..."),await this.initializeSystemPrompt(),await this.registerBuiltinTools(),await this.loadSubagents(),await this.discoverSkills();let $=
|
|
2100
|
+
`+" /init");let X=H$();if(!X)throw Error("❌ 配置未初始化,请确保应用已正确启动");u$.getInstance().validateConfig(X);let Q=new z$(X,$);if(await Q.initialize(),$.toolWhitelist&&$.toolWhitelist.length>0)Q.applyToolWhitelist($.toolWhitelist);return Q}async initialize(){if(this.isInitialized)return;try{this.log("初始化Agent..."),await this.initializeSystemPrompt(),await this.registerBuiltinTools(),await this.loadSubagents(),await this.discoverSkills();let $=P4();if(!$)throw Error("❌ 当前模型配置未找到");this.log(`\uD83D\uDE80 使用模型: ${$.name} (${$.model})`);let Z=t4($),X=uX(),Y=Z&&X;if(Z&&!X)this.log("\uD83E\uDDE0 模型支持 Thinking,但用户未开启(按 Tab 开启)");else if(Y)this.log("\uD83E\uDDE0 Thinking 模式已启用,启用 reasoning_content 支持");this.currentModelMaxContextTokens=$.maxContextTokens??this.config.maxContextTokens,this.chatService=await u3({provider:$.provider,apiKey:$.apiKey,model:$.model,baseUrl:$.baseUrl,temperature:$.temperature??this.config.temperature,maxContextTokens:this.currentModelMaxContextTokens,maxOutputTokens:$.maxOutputTokens??this.config.maxOutputTokens,timeout:this.config.timeout,supportsThinking:Y}),this.executionEngine=new i5(this.chatService),this.attachmentCollector=new C7({cwd:process.cwd(),maxFileSize:1048576,maxLines:2000,maxTokens:32000}),this.isInitialized=!0,this.log(`Agent初始化完成,已加载 ${this.executionPipeline.getRegistry().getAll().length} 个工具`)}catch($){throw this.error("Agent初始化失败",$),$}}async executeTask($){if(!this.isInitialized)throw Error("Agent未初始化");this.activeTask=$;try{this.log(`开始执行任务: ${$.id}`);let Z=await this.executionEngine.executeTask($);return this.activeTask=void 0,this.log(`任务执行完成: ${$.id}`),Z}catch(Z){throw this.activeTask=void 0,this.error(`任务执行失败: ${$.id}`,Z),Z}}async chat($,Z,X){if(!this.isInitialized)throw Error("Agent未初始化");let Y=await this.processAtMentionsForContent($);if(Z){let q={signal:Z.signal,...X},K;if(Z.permissionMode==="plan")K=await this.runPlanLoop(Y,Z,q);else if(Z.permissionMode==="spec")K=await this.runSpecLoop(Y,Z,q);else K=await this.runLoop(Y,Z,q);if(!K.success){if(K.error?.type==="aborted"||K.metadata?.shouldExitLoop)return"";throw Error(K.error?.message||"执行失败")}if(K.metadata?.targetMode&&Z.permissionMode==="plan"){let W=K.metadata.targetMode,U=K.metadata.planContent;f.debug(`\uD83D\uDD04 Plan 模式已批准,切换到 ${W} 模式并重新执行`),await x0().setPermissionMode(W),f.debug(`✅ 权限模式已更新: ${W}`);let H={...Z,permissionMode:W},F=Y;if(U){let O=`
|
|
2101
2101
|
|
|
2102
2102
|
<approved-plan>
|
|
2103
2103
|
${U}
|
|
@@ -2130,9 +2130,9 @@ ${n.continueReason}
|
|
|
2130
2130
|
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.
|
|
2131
2131
|
</system-reminder>`;H.push({role:"user",content:y});continue}if(n.warning)f.warn(`[Agent] Stop hook warning: ${n.warning}`)}catch(b){f.warn("[Agent] Stop hook execution failed:",b)}try{let b=this.executionEngine?.getContextManager();if(b&&Z.sessionId&&N.content)if(N.content.trim()!=="")F=await b.saveMessage(Z.sessionId,"assistant",N.content,F);else f.debug("[Agent] 跳过保存空响应(任务完成时)")}catch(b){f.warn("[Agent] 保存助手消息失败:",b)}return{success:!0,finalMessage:N.content,metadata:{turnsCount:L,toolCallsCount:w.length,duration:Date.now()-Q,tokensUsed:R}}}H.push({role:"assistant",content:N.content||"",reasoningContent:N.reasoningContent,tool_calls:N.toolCalls});try{let S=this.executionEngine?.getContextManager();if(S&&Z.sessionId&&N.content)if(N.content.trim()!=="")F=await S.saveMessage(Z.sessionId,"assistant",N.content,F);else f.debug("[Agent] 跳过保存空响应(工具调用时)")}catch(S){f.warn("[Agent] 保存助手工具调用消息失败:",S)}if(X?.signal?.aborted)return f.info("[Agent] Aborting before tool execution due to signal.aborted=true"),{success:!1,error:{type:"aborted",message:"任务已被用户中止"},metadata:{turnsCount:L,toolCallsCount:w.length,duration:Date.now()-Q}};let k=N.toolCalls.filter((S)=>S.type==="function");if(X?.onToolStart&&!X.signal?.aborted)for(let S of k){let c=this.executionPipeline.getRegistry().get(S.function.name)?.kind;X.onToolStart(S,c)}let m=async(S)=>{try{let T=JSON.parse(S.function.arguments);if(T.todos&&typeof T.todos==="string")try{T.todos=JSON.parse(T.todos),this.log("[Agent] 自动修复了字符串化的 todos 参数")}catch{this.error("[Agent] todos 参数格式异常,将由验证层处理")}let c=null;try{let b=this.executionEngine?.getContextManager();if(b&&Z.sessionId)c=await b.saveToolUse(Z.sessionId,S.function.name,T,F)}catch(b){f.warn("[Agent] 保存工具调用失败:",b)}let j=X?.signal;if(!j)f.error("[Agent] Missing signal in tool execution, this should not happen");f.debug("[Agent] Passing confirmationHandler to ExecutionPipeline.execute:",{toolName:S.function.name,hasHandler:!!Z.confirmationHandler,hasMethod:!!Z.confirmationHandler?.requestConfirmation,methodType:typeof Z.confirmationHandler?.requestConfirmation});let M=await this.executionPipeline.execute(S.function.name,T,{sessionId:Z.sessionId,userId:Z.userId||"default",workspaceRoot:Z.workspaceRoot||process.cwd(),signal:j,confirmationHandler:Z.confirmationHandler,permissionMode:Z.permissionMode});if(f.debug(`
|
|
2132
2132
|
========== 工具执行结果 ==========`),f.debug("工具名称:",S.function.name),f.debug("成功:",M.success),f.debug("LLM Content:",M.llmContent),f.debug("Display Content:",M.displayContent),M.error)f.debug("错误:",M.error);return f.debug(`==================================
|
|
2133
|
-
`),{toolCall:S,result:M,toolUseUuid:c}}catch(T){return f.error(`Tool execution failed for ${S.function.name}:`,T),{toolCall:S,result:{success:!1,llmContent:"",displayContent:"",error:{type:"execution_error",message:T instanceof Error?T.message:"Unknown error"}},toolUseUuid:null,error:T instanceof Error?T:Error("Unknown error")}}};f.info(`[Agent] Executing ${k.length} tool calls in parallel`);let s=await Promise.all(k.map(m));for(let{toolCall:S,result:T,toolUseUuid:c}of s){if(w.push(T),T.metadata?.shouldExitLoop){f.debug("\uD83D\uDEAA 检测到退出循环标记,结束 Agent 循环");let b=typeof T.llmContent==="string"?T.llmContent:"循环已退出";return{success:T.success,finalMessage:b,metadata:{turnsCount:L,toolCallsCount:w.length,duration:Date.now()-Q,shouldExitLoop:!0,targetMode:T.metadata?.targetMode}}}if(X?.onToolResult&&!X.signal?.aborted){f.debug("[Agent] Calling onToolResult:",{toolName:S.function.name,hasCallback:!0,resultSuccess:T.success,resultKeys:Object.keys(T),hasMetadata:!!T.metadata,metadataKeys:T.metadata?Object.keys(T.metadata):[],hasSummary:!!T.metadata?.summary,summary:T.metadata?.summary});try{await X.onToolResult(S,T),f.debug("[Agent] onToolResult callback completed successfully")}catch(b){f.error("[Agent] onToolResult callback error:",b)}}try{let b=this.executionEngine?.getContextManager();if(b&&Z.sessionId)F=await b.saveToolResult(Z.sessionId,S.id,T.success?M_(T.llmContent):null,c,T.success?void 0:T.error?.message)}catch(b){f.warn("[Agent] 保存工具结果失败:",b)}if(S.function.name==="TodoWrite"&&T.success&&T.llmContent){let b=typeof T.llmContent==="object"?T.llmContent:{},y=Array.isArray(b)?b:b.todos||[];$
|
|
2133
|
+
`),{toolCall:S,result:M,toolUseUuid:c}}catch(T){return f.error(`Tool execution failed for ${S.function.name}:`,T),{toolCall:S,result:{success:!1,llmContent:"",displayContent:"",error:{type:"execution_error",message:T instanceof Error?T.message:"Unknown error"}},toolUseUuid:null,error:T instanceof Error?T:Error("Unknown error")}}};f.info(`[Agent] Executing ${k.length} tool calls in parallel`);let s=await Promise.all(k.map(m));for(let{toolCall:S,result:T,toolUseUuid:c}of s){if(w.push(T),T.metadata?.shouldExitLoop){f.debug("\uD83D\uDEAA 检测到退出循环标记,结束 Agent 循环");let b=typeof T.llmContent==="string"?T.llmContent:"循环已退出";return{success:T.success,finalMessage:b,metadata:{turnsCount:L,toolCallsCount:w.length,duration:Date.now()-Q,shouldExitLoop:!0,targetMode:T.metadata?.targetMode}}}if(X?.onToolResult&&!X.signal?.aborted){f.debug("[Agent] Calling onToolResult:",{toolName:S.function.name,hasCallback:!0,resultSuccess:T.success,resultKeys:Object.keys(T),hasMetadata:!!T.metadata,metadataKeys:T.metadata?Object.keys(T.metadata):[],hasSummary:!!T.metadata?.summary,summary:T.metadata?.summary});try{await X.onToolResult(S,T),f.debug("[Agent] onToolResult callback completed successfully")}catch(b){f.error("[Agent] onToolResult callback error:",b)}}try{let b=this.executionEngine?.getContextManager();if(b&&Z.sessionId)F=await b.saveToolResult(Z.sessionId,S.id,T.success?M_(T.llmContent):null,c,T.success?void 0:T.error?.message)}catch(b){f.warn("[Agent] 保存工具结果失败:",b)}if(S.function.name==="TodoWrite"&&T.success&&T.llmContent){let b=typeof T.llmContent==="object"?T.llmContent:{},y=Array.isArray(b)?b:b.todos||[];$2().setTodos(y),X?.onTodoUpdate?.(y)}if(S.function.name==="Skill"&&T.success&&T.metadata){let b=T.metadata;if(b.skillName)this.activeSkillContext={skillName:b.skillName,allowedTools:b.allowedTools,basePath:b.basePath||""},f.debug(`\uD83C\uDFAF Skill "${this.activeSkillContext.skillName}" activated`+(this.activeSkillContext.allowedTools?` with allowed tools: ${this.activeSkillContext.allowedTools.join(", ")}`:""))}let j=T.success?T.llmContent||T.displayContent||"":T.error?.message||"执行失败";if(typeof j==="object"&&j!==null)j=JSON.stringify(j,null,2);let M=typeof j==="string"?j:JSON.stringify(j);H.push({role:"tool",tool_call_id:S.id,name:S.function.name,content:M})}if(X?.signal?.aborted)return{success:!1,error:{type:"aborted",message:"任务已被用户中止"},metadata:{turnsCount:L,toolCallsCount:w.length,duration:Date.now()-Q}};if(L>=B&&!z){if(f.info(`⚠️ 达到轮次上限 ${B} 轮,等待用户确认...`),X?.onTurnLimitReached){let S=await X.onTurnLimitReached({turnsCount:L});if(S?.continue){f.info("✅ 用户选择继续,压缩上下文...");try{let T=this.chatService.getConfig(),c=await h4.compact(Z.messages,{trigger:"auto",modelName:T.model,maxContextTokens:T.maxContextTokens??this.config.maxContextTokens,apiKey:T.apiKey,baseURL:T.baseUrl,actualPreTokens:D});Z.messages=c.compactedMessages;let j=H.find((b)=>b.role==="system");if(H.length=0,j)H.push(j);H.push(...Z.messages);let M={role:"user",content:`This session is being continued from a previous conversation. The conversation is summarized above.
|
|
2134
2134
|
|
|
2135
|
-
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.`};H.push(M),Z.messages.push(M);try{let b=this.executionEngine?.getContextManager();if(b&&Z.sessionId)await b.saveCompaction(Z.sessionId,c.summary,{trigger:"auto",preTokens:c.preTokens,postTokens:c.postTokens,filesIncluded:c.filesIncluded},null)}catch(b){f.warn("[Agent] 保存压缩数据失败:",b)}f.info(`✅ 上下文已压缩 (${c.preTokens} → ${c.postTokens} tokens),重置轮次计数`)}catch(T){f.error("[Agent] 压缩失败,使用降级策略:",T);let c=H.find((M)=>M.role==="system"),j=H.slice(-80);if(H.length=0,c&&!j.some((M)=>M.role==="system"))H.push(c);H.push(...j),Z.messages=H.filter((M)=>M.role!=="system"),f.warn(`⚠️ 降级压缩完成,保留 ${H.length} 条消息`)}L=0;continue}return{success:!0,finalMessage:S?.reason||"已达到对话轮次上限,用户选择停止",metadata:{turnsCount:L,toolCallsCount:w.length,duration:Date.now()-Q,tokensUsed:R}}}return{success:!1,error:{type:"max_turns_exceeded",message:`已达到轮次上限 (${B} 轮)。使用 --permission-mode yolo 跳过此限制。`},metadata:{turnsCount:L,toolCallsCount:w.length,duration:Date.now()-Q,tokensUsed:R}}}}}catch(J){if(J instanceof Error&&(J.name==="AbortError"||J.message.includes("aborted")))return{success:!1,error:{type:"aborted",message:"任务已被用户中止"},metadata:{turnsCount:0,toolCallsCount:0,duration:Date.now()-Q}};return f.error("Enhanced chat processing error:",J),{success:!1,error:{type:"api_error",message:`处理消息时发生错误: ${J instanceof Error?J.message:"未知错误"}`,details:J},metadata:{turnsCount:0,toolCallsCount:0,duration:Date.now()-Q}}}}async processStreamResponse($,Z,X){let Y="",Q="",J,G=new Map;try{let q=this.chatService.streamChat($,Z,X?.signal),K=0;for await(let W of q){if(K++,X?.signal?.aborted)break;if(W.content){let U=W.content.length;Y+=W.content,W1("processStreamResponse","onContentDelta BEFORE",{chunkLen:U,accumulatedLen:Y.length}),X?.onContentDelta?.(W.content),W1("processStreamResponse","onContentDelta AFTER",{chunkLen:U,accumulatedLen:Y.length})}if(W.reasoningContent)Q+=W.reasoningContent,X?.onThinkingDelta?.(W.reasoningContent);if(W.usage)J=W.usage;if(W.toolCalls)for(let U of W.toolCalls)this.accumulateToolCall(G,U);if(W.finishReason){W1("processStreamResponse","finishReason received",{finishReason:W.finishReason,fullContentLen:Y.length,fullReasoningContentLen:Q.length,toolCallAccumulatorSize:G.size});break}}if(W1("processStreamResponse","stream ended",{fullContentLen:Y.length,fullReasoningContentLen:Q.length,toolCallAccumulatorSize:G.size}),K===0&&!X?.signal?.aborted&&Y.length===0&&G.size===0)return f.warn("[Agent] 流式响应返回0个chunk,回退到非流式模式"),this.chatService.chat($,Z,X?.signal);return{content:Y,reasoningContent:Q||void 0,toolCalls:this.buildFinalToolCalls(G),usage:J}}catch(q){if(this.isStreamingNotSupportedError(q))return f.warn("[Agent] 流式请求失败,降级到非流式模式"),this.chatService.chat($,Z,X?.signal);throw q}}accumulateToolCall($,Z){let X=Z,Y=X.index??0;if(!$.has(Y))$.set(Y,{id:X.id||"",name:X.function?.name||"",arguments:""});let Q=$.get(Y);if(X.id&&!Q.id)Q.id=X.id;if(X.function?.name&&!Q.name)Q.name=X.function.name;if(X.function?.arguments)Q.arguments+=X.function.arguments}buildFinalToolCalls($){if($.size===0)return;return Array.from($.values()).filter((Z)=>Z.id&&Z.name).map((Z)=>({id:Z.id,type:"function",function:{name:Z.name,arguments:Z.arguments}}))}isStreamingNotSupportedError($){if(!($ instanceof Error))return!1;return["stream not supported","streaming is not available","sse not supported","does not support streaming"].some((X)=>$.message.toLowerCase().includes(X.toLowerCase()))}async runAgenticLoop($,Z,X){if(!this.isInitialized)throw Error("Agent未初始化");let Y={messages:Z.messages,userId:Z.userId||"subagent",sessionId:Z.sessionId||`subagent_${Date.now()}`,workspaceRoot:Z.workspaceRoot||process.cwd(),signal:Z.signal,confirmationHandler:Z.confirmationHandler};return await this.runLoop($,Y,X)}async chatWithSystem($,Z){if(!this.isInitialized)throw Error("Agent未初始化");let X=[{role:"system",content:$},{role:"user",content:Z}];return(await this.chatService.chat(X)).content}getActiveTask(){return this.activeTask}getChatService(){return this.chatService}getContextManager(){return this.executionEngine?.getContextManager()}getStats(){return{initialized:this.isInitialized,activeTask:this.activeTask?.id,components:{chatService:this.chatService?"ready":"not_loaded",executionEngine:this.executionEngine?"ready":"not_loaded"}}}getAvailableTools(){return this.executionPipeline?this.executionPipeline.getRegistry().getAll():[]}getToolRegistry(){return this.executionPipeline.getRegistry()}applyToolWhitelist($){let Z=this.executionPipeline.getRegistry(),Y=Z.getAll().filter((Q)=>!$.includes(Q.name));for(let Q of Y)Z.unregister(Q.name);f.debug(`\uD83D\uDD12 Applied tool whitelist: ${$.join(", ")} (removed ${Y.length} tools)`)}getToolStats(){let $=this.getAvailableTools(),Z=new Map;return $.forEach((X)=>{let Y=Z.get(X.kind)||0;Z.set(X.kind,Y+1)}),{totalTools:$.length,toolsByKind:Object.fromEntries(Z),toolNames:$.map((X)=>X.name)}}async destroy(){this.log("销毁Agent...");try{this.isInitialized=!1,this.log("Agent已销毁")}catch($){throw this.error("Agent销毁失败",$),$}}generateTaskId(){return`task_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}log($,Z){f.debug(`[MainAgent] ${$}`,Z||"")}error($,Z){f.error(`[MainAgent] ${$}`,Z||"")}async initializeSystemPrompt(){try{let $=this.runtimeOptions.systemPrompt,Z=this.runtimeOptions.appendSystemPrompt,X=await e3({projectPath:process.cwd(),replaceDefault:$,append:Z,includeEnvironment:!1});if(this.systemPrompt=X.prompt,this.systemPrompt)this.log("系统提示已加载"),f.debug(`[SystemPrompt] 加载来源: ${X.sources.filter((Y)=>Y.loaded).map((Y)=>Y.name).join(", ")}`)}catch($){this.error("初始化系统提示失败",$)}}getSystemPrompt(){return this.systemPrompt}async checkAndCompactInLoop($,Z,X,Y){if(X===void 0)return f.debug(`[Agent] [轮次 ${Z}] 压缩检查: 跳过(无历史 usage 数据)`),!1;let Q=this.chatService.getConfig(),J=Q.model,G=Q.maxContextTokens??this.config.maxContextTokens,q=Q.maxOutputTokens??this.config.maxOutputTokens,K=G-q,W=Math.floor(K*0.8);if(f.debug(`[Agent] [轮次 ${Z}] 压缩检查:`,{promptTokens:X,maxContextTokens:G,maxOutputTokens:q,availableForInput:K,threshold:W,shouldCompact:X>=W}),X<W)return!1;let U=Z===0?"[Agent] 触发自动压缩":`[Agent] [轮次 ${Z}] 触发循环内自动压缩`;f.debug(U),Y?.(!0);try{let H=await
|
|
2135
|
+
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.`};H.push(M),Z.messages.push(M);try{let b=this.executionEngine?.getContextManager();if(b&&Z.sessionId)await b.saveCompaction(Z.sessionId,c.summary,{trigger:"auto",preTokens:c.preTokens,postTokens:c.postTokens,filesIncluded:c.filesIncluded},null)}catch(b){f.warn("[Agent] 保存压缩数据失败:",b)}f.info(`✅ 上下文已压缩 (${c.preTokens} → ${c.postTokens} tokens),重置轮次计数`)}catch(T){f.error("[Agent] 压缩失败,使用降级策略:",T);let c=H.find((M)=>M.role==="system"),j=H.slice(-80);if(H.length=0,c&&!j.some((M)=>M.role==="system"))H.push(c);H.push(...j),Z.messages=H.filter((M)=>M.role!=="system"),f.warn(`⚠️ 降级压缩完成,保留 ${H.length} 条消息`)}L=0;continue}return{success:!0,finalMessage:S?.reason||"已达到对话轮次上限,用户选择停止",metadata:{turnsCount:L,toolCallsCount:w.length,duration:Date.now()-Q,tokensUsed:R}}}return{success:!1,error:{type:"max_turns_exceeded",message:`已达到轮次上限 (${B} 轮)。使用 --permission-mode yolo 跳过此限制。`},metadata:{turnsCount:L,toolCallsCount:w.length,duration:Date.now()-Q,tokensUsed:R}}}}}catch(J){if(J instanceof Error&&(J.name==="AbortError"||J.message.includes("aborted")))return{success:!1,error:{type:"aborted",message:"任务已被用户中止"},metadata:{turnsCount:0,toolCallsCount:0,duration:Date.now()-Q}};return f.error("Enhanced chat processing error:",J),{success:!1,error:{type:"api_error",message:`处理消息时发生错误: ${J instanceof Error?J.message:"未知错误"}`,details:J},metadata:{turnsCount:0,toolCallsCount:0,duration:Date.now()-Q}}}}async processStreamResponse($,Z,X){let Y="",Q="",J,G=new Map;try{let q=this.chatService.streamChat($,Z,X?.signal),K=0;for await(let W of q){if(K++,X?.signal?.aborted)break;if(W.content){let U=W.content.length;Y+=W.content,W1("processStreamResponse","onContentDelta BEFORE",{chunkLen:U,accumulatedLen:Y.length}),X?.onContentDelta?.(W.content),W1("processStreamResponse","onContentDelta AFTER",{chunkLen:U,accumulatedLen:Y.length})}if(W.reasoningContent)Q+=W.reasoningContent,X?.onThinkingDelta?.(W.reasoningContent);if(W.usage)J=W.usage;if(W.toolCalls)for(let U of W.toolCalls)this.accumulateToolCall(G,U);if(W.finishReason){W1("processStreamResponse","finishReason received",{finishReason:W.finishReason,fullContentLen:Y.length,fullReasoningContentLen:Q.length,toolCallAccumulatorSize:G.size});break}}if(W1("processStreamResponse","stream ended",{fullContentLen:Y.length,fullReasoningContentLen:Q.length,toolCallAccumulatorSize:G.size}),K===0&&!X?.signal?.aborted&&Y.length===0&&G.size===0)return f.warn("[Agent] 流式响应返回0个chunk,回退到非流式模式"),this.chatService.chat($,Z,X?.signal);return{content:Y,reasoningContent:Q||void 0,toolCalls:this.buildFinalToolCalls(G),usage:J}}catch(q){if(this.isStreamingNotSupportedError(q))return f.warn("[Agent] 流式请求失败,降级到非流式模式"),this.chatService.chat($,Z,X?.signal);throw q}}accumulateToolCall($,Z){let X=Z,Y=X.index??0;if(!$.has(Y))$.set(Y,{id:X.id||"",name:X.function?.name||"",arguments:""});let Q=$.get(Y);if(X.id&&!Q.id)Q.id=X.id;if(X.function?.name&&!Q.name)Q.name=X.function.name;if(X.function?.arguments)Q.arguments+=X.function.arguments}buildFinalToolCalls($){if($.size===0)return;return Array.from($.values()).filter((Z)=>Z.id&&Z.name).map((Z)=>({id:Z.id,type:"function",function:{name:Z.name,arguments:Z.arguments}}))}isStreamingNotSupportedError($){if(!($ instanceof Error))return!1;return["stream not supported","streaming is not available","sse not supported","does not support streaming"].some((X)=>$.message.toLowerCase().includes(X.toLowerCase()))}async runAgenticLoop($,Z,X){if(!this.isInitialized)throw Error("Agent未初始化");let Y={messages:Z.messages,userId:Z.userId||"subagent",sessionId:Z.sessionId||`subagent_${Date.now()}`,workspaceRoot:Z.workspaceRoot||process.cwd(),signal:Z.signal,confirmationHandler:Z.confirmationHandler};return await this.runLoop($,Y,X)}async chatWithSystem($,Z){if(!this.isInitialized)throw Error("Agent未初始化");let X=[{role:"system",content:$},{role:"user",content:Z}];return(await this.chatService.chat(X)).content}getActiveTask(){return this.activeTask}getChatService(){return this.chatService}getContextManager(){return this.executionEngine?.getContextManager()}getStats(){return{initialized:this.isInitialized,activeTask:this.activeTask?.id,components:{chatService:this.chatService?"ready":"not_loaded",executionEngine:this.executionEngine?"ready":"not_loaded"}}}getAvailableTools(){return this.executionPipeline?this.executionPipeline.getRegistry().getAll():[]}getToolRegistry(){return this.executionPipeline.getRegistry()}applyToolWhitelist($){let Z=this.executionPipeline.getRegistry(),Y=Z.getAll().filter((Q)=>!$.includes(Q.name));for(let Q of Y)Z.unregister(Q.name);f.debug(`\uD83D\uDD12 Applied tool whitelist: ${$.join(", ")} (removed ${Y.length} tools)`)}getToolStats(){let $=this.getAvailableTools(),Z=new Map;return $.forEach((X)=>{let Y=Z.get(X.kind)||0;Z.set(X.kind,Y+1)}),{totalTools:$.length,toolsByKind:Object.fromEntries(Z),toolNames:$.map((X)=>X.name)}}async destroy(){this.log("销毁Agent...");try{this.isInitialized=!1,this.log("Agent已销毁")}catch($){throw this.error("Agent销毁失败",$),$}}generateTaskId(){return`task_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}log($,Z){f.debug(`[MainAgent] ${$}`,Z||"")}error($,Z){f.error(`[MainAgent] ${$}`,Z||"")}async initializeSystemPrompt(){try{let $=this.runtimeOptions.systemPrompt,Z=this.runtimeOptions.appendSystemPrompt,X=await e3({projectPath:process.cwd(),replaceDefault:$,append:Z,includeEnvironment:!1});if(this.systemPrompt=X.prompt,this.systemPrompt)this.log("系统提示已加载"),f.debug(`[SystemPrompt] 加载来源: ${X.sources.filter((Y)=>Y.loaded).map((Y)=>Y.name).join(", ")}`)}catch($){this.error("初始化系统提示失败",$)}}getSystemPrompt(){return this.systemPrompt}async checkAndCompactInLoop($,Z,X,Y){if(X===void 0)return f.debug(`[Agent] [轮次 ${Z}] 压缩检查: 跳过(无历史 usage 数据)`),!1;let Q=this.chatService.getConfig(),J=Q.model,G=Q.maxContextTokens??this.config.maxContextTokens,q=Q.maxOutputTokens??this.config.maxOutputTokens,K=G-q,W=Math.floor(K*0.8);if(f.debug(`[Agent] [轮次 ${Z}] 压缩检查:`,{promptTokens:X,maxContextTokens:G,maxOutputTokens:q,availableForInput:K,threshold:W,shouldCompact:X>=W}),X<W)return!1;let U=Z===0?"[Agent] 触发自动压缩":`[Agent] [轮次 ${Z}] 触发循环内自动压缩`;f.debug(U),Y?.(!0);try{let H=await h4.compact($.messages,{trigger:"auto",modelName:J,maxContextTokens:G,apiKey:Q.apiKey,baseURL:Q.baseUrl,actualPreTokens:X});if(H.success)$.messages=H.compactedMessages,f.debug(`[Agent] [轮次 ${Z}] 压缩完成: ${H.preTokens} → ${H.postTokens} tokens (-${((1-H.postTokens/H.preTokens)*100).toFixed(1)}%)`);else $.messages=H.compactedMessages,f.warn(`[Agent] [轮次 ${Z}] 压缩使用降级策略: ${H.preTokens} → ${H.postTokens} tokens`);try{let F=this.executionEngine?.getContextManager();if(F&&$.sessionId)await F.saveCompaction($.sessionId,H.summary,{trigger:"auto",preTokens:H.preTokens,postTokens:H.postTokens,filesIncluded:H.filesIncluded},null),f.debug(`[Agent] [轮次 ${Z}] 压缩数据已保存到 JSONL`)}catch(F){f.warn(`[Agent] [轮次 ${Z}] 保存压缩数据失败:`,F)}return Y?.(!1),!0}catch(H){return Y?.(!1),f.error(`[Agent] [轮次 ${Z}] 压缩失败,继续执行`,H),!1}}async registerBuiltinTools(){try{let $=await NG({sessionId:"default",configDir:kG.join(CG.homedir(),".blade")});f.debug(`\uD83D\uDCE6 Registering ${$.length} builtin tools...`),this.executionPipeline.getRegistry().registerAll($);let Z=this.executionPipeline.getRegistry().getAll().length;f.debug(`✅ Builtin tools registered: ${Z} tools`),f.debug(`[Tools] ${this.executionPipeline.getRegistry().getAll().map((X)=>X.name).join(", ")}`),await this.registerMcpTools()}catch($){throw f.error("Failed to register builtin tools:",$),$}}async registerMcpTools(){try{if(this.runtimeOptions.mcpConfig&&this.runtimeOptions.mcpConfig.length>0)await aY(this.runtimeOptions.mcpConfig);let $=G1();if(Object.keys($).length===0){f.debug("\uD83D\uDCE6 No MCP servers configured");return}let Z=N$.getInstance();for(let[Y,Q]of Object.entries($))try{f.debug(`\uD83D\uDD0C Connecting to MCP server: ${Y}`),await Z.registerServer(Y,Q),f.debug(`✅ MCP server "${Y}" connected`)}catch(J){f.warn(`⚠️ MCP server "${Y}" connection failed:`,J)}let X=await Z.getAvailableTools();if(X.length>0)this.executionPipeline.getRegistry().registerAll(X),f.debug(`✅ Registered ${X.length} MCP tools`),f.debug(`[MCP Tools] ${X.map((Y)=>Y.name).join(", ")}`)}catch($){f.warn("Failed to register MCP tools:",$)}}async loadSubagents(){if(J$.getAllNames().length>0){f.debug(`\uD83D\uDCE6 Subagents already loaded: ${J$.getAllNames().join(", ")}`);return}try{let $=J$.loadFromStandardLocations();if($>0)f.debug(`✅ Loaded ${$} subagents: ${J$.getAllNames().join(", ")}`);else f.debug("\uD83D\uDCE6 No subagents configured")}catch($){f.warn("Failed to load subagents:",$)}}async discoverSkills(){try{let $=await e2({cwd:process.cwd()});if($.skills.length>0)f.debug(`✅ Discovered ${$.skills.length} skills: ${$.skills.map((Z)=>Z.name).join(", ")}`);else f.debug("\uD83D\uDCE6 No skills configured");for(let Z of $.errors)f.warn(`⚠️ Skill loading error at ${Z.path}: ${Z.error}`)}catch($){f.warn("Failed to discover skills:",$)}}applySkillToolRestrictions($){if(!this.activeSkillContext?.allowedTools)return $;let Z=this.activeSkillContext.allowedTools;f.debug(`\uD83D\uDD12 Applying Skill tool restrictions: ${Z.join(", ")}`);let X=$.filter((Y)=>{return Z.some((Q)=>{if(Q===Y.name)return!0;let J=Q.match(/^(\w+)\(.*\)$/);if(J&&J[1]===Y.name)return!0;return!1})});return f.debug(`\uD83D\uDD12 Filtered tools: ${X.map((Y)=>Y.name).join(", ")} (${X.length}/${$.length})`),X}clearSkillContext(){if(this.activeSkillContext)f.debug(`\uD83C\uDFAF Skill "${this.activeSkillContext.skillName}" deactivated`),this.activeSkillContext=void 0}async processAtMentionsForContent($){if(!this.attachmentCollector)return $;if(typeof $==="string")return this.processAtMentions($);let Z=[];for(let Y of $)if(Y.type==="text")Z.push(Y.text);if(Z.length===0)return $;let X=Z.join(`
|
|
2136
2136
|
`);try{let Y=await this.attachmentCollector.collect(X);if(Y.length===0)return $;f.debug(`✅ Processed ${Y.length} @ file mentions in multimodal message`);let Q=this.buildAttachmentText(Y);if(!Q)return $;return[...$,{type:"text",text:Q}]}catch(Y){return f.error("Failed to process @ mentions in multimodal message:",Y),$}}buildAttachmentText($){let Z=[],X=[];for(let Q of $)if(Q.type==="file"){let J=Q.metadata?.lineRange?` (lines ${Q.metadata.lineRange.start}${Q.metadata.lineRange.end?`-${Q.metadata.lineRange.end}`:""})`:"";Z.push(`<file path="${Q.path}"${J?` range="${J}"`:""}>`,Q.content,"</file>")}else if(Q.type==="directory")Z.push(`<directory path="${Q.path}">`,Q.content,"</directory>");else if(Q.type==="error")X.push(`- @${Q.path}: ${Q.error}`);let Y="";if(Z.length>0)Y+=`
|
|
2137
2137
|
|
|
2138
2138
|
<system-reminder>
|
|
@@ -2155,10 +2155,10 @@ Please continue the conversation from where we left it off without asking the us
|
|
|
2155
2155
|
|
|
2156
2156
|
⚠️ Some files could not be loaded:
|
|
2157
2157
|
`,Q+=Y.join(`
|
|
2158
|
-
`);return Q}}var f;var Q4=A(()=>{y2();R7();r$();B0();D7();rY();s4();FQ();wQ();S7();A7();X4();U1();C0();bG();jG();IG();E$();T7();R6();SG();G2();f=i("Agent")});import{z as U0}from"zod";function xG($){return v_.safeParse($)}var j_,I_,y_,hG,fG,v_;var a5=A(()=>{j_=U0.string().min(2,"Plugin name must be at least 2 characters").max(64,"Plugin name must be at most 64 characters").regex(/^[a-z0-9][a-z0-9-]*[a-z0-9]$|^[a-z0-9]{1,2}$/,{message:"Plugin name must be lowercase letters, numbers, and hyphens only, starting and ending with alphanumeric"}),I_=U0.string().regex(/^\d+\.\d+\.\d+(-[\w.]+)?(\+[\w.]+)?$/,{message:"Version must be a valid semantic version (e.g., 1.0.0)"}),y_=U0.object({name:U0.string().min(1,"Author name is required"),email:U0.string().email().optional(),url:U0.string().url().optional()}),hG=U0.object({name:j_,description:U0.string().min(1,"Description is required").max(500,"Description must be at most 500 characters"),version:I_,author:y_.optional(),license:U0.string().optional(),repository:U0.string().url().optional(),homepage:U0.string().url().optional(),keywords:U0.array(U0.string()).optional(),dependencies:U0.record(U0.string()).optional(),bladeVersion:U0.string().optional()}),fG=U0.object({type:U0.enum(["stdio","sse","http"]),command:U0.string().optional(),args:U0.array(U0.string()).optional(),env:U0.record(U0.string()).optional(),url:U0.string().url().optional(),headers:U0.record(U0.string()).optional(),timeout:U0.number().positive().optional(),oauth:U0.object({enabled:U0.boolean().optional(),clientId:U0.string().optional(),clientSecret:U0.string().optional(),authorizationUrl:U0.string().url().optional(),tokenUrl:U0.string().url().optional(),scopes:U0.array(U0.string()).optional(),redirectUri:U0.string().url().optional()}).optional(),healthCheck:U0.object({enabled:U0.boolean().optional(),interval:U0.number().positive().optional(),timeout:U0.number().positive().optional(),failureThreshold:U0.number().positive().optional()}).optional()}),v_=U0.union([U0.object({mcpServers:U0.record(fG)}),U0.record(fG)])});import*as D6 from"node:fs/promises";import*as pG from"node:path";async function $8($){for(let{dir:Z,source:X}of E_){let Y=pG.join($,Z,"plugin.json");try{await D6.access(Y)}catch{continue}try{let Q=await D6.readFile(Y,"utf-8"),J=JSON.parse(Q),G=hG.safeParse(J);if(!G.success){let q=G.error.issues.map((K)=>`${K.path.join(".")}: ${K.message}`).join("; ");throw Error(`Invalid plugin.json: ${q}`)}return u0.debug(`Parsed plugin manifest from ${Y}`),{manifest:G.data,source:X,manifestPath:Y}}catch(Q){if(Q instanceof SyntaxError)throw Error(`Invalid JSON in ${Y}: ${Q.message}`);throw Q}}return null}async function dG($){try{return await $8($)!==null}catch{return!1}}var E_;var r5=A(()=>{B0();a5();E_=[{dir:".blade-plugin",source:"blade"},{dir:".claude-plugin",source:"claude"}]});import{execSync as mG}from"node:child_process";import*as i$ from"node:fs/promises";import{homedir as P_}from"node:os";import*as Z8 from"node:path";class uG{userPluginsDir;constructor($){this.userPluginsDir=$||Z8.join(P_(),".blade","plugins")}async install($){try{let Z=this.parseGitUrl($);if(!Z)return{success:!1,error:`Invalid source URL: ${$}`};let X=this.extractPluginName(Z);if(!X)return{success:!1,error:`Could not extract plugin name from URL: ${Z}`};await i$.mkdir(this.userPluginsDir,{recursive:!0});let Y=Z8.join(this.userPluginsDir,X);try{return await i$.access(Y),{success:!1,pluginName:X,pluginPath:Y,error:`Plugin "${X}" already exists at ${Y}. Use /plugins uninstall first.`}}catch{}u0.info(`Cloning ${Z} to ${Y}...`);try{mG(`git clone --depth 1 "${Z}" "${Y}"`,{stdio:"pipe",timeout:60000})}catch(J){return{success:!1,pluginName:X,error:`Failed to clone repository: ${J instanceof Error?J.message:String(J)}`}}if(!await dG(Y))return await i$.rm(Y,{recursive:!0,force:!0}),{success:!1,pluginName:X,error:"Invalid plugin: No .blade-plugin/plugin.json or .claude-plugin/plugin.json found"};let Q;try{Q=await $8(Y)}catch(J){return await i$.rm(Y,{recursive:!0,force:!0}),{success:!1,pluginName:X,error:`Invalid plugin manifest: ${J instanceof Error?J.message:String(J)}`}}if(!Q)return await i$.rm(Y,{recursive:!0,force:!0}),{success:!1,pluginName:X,error:"Invalid plugin manifest: No manifest found"};return u0.info(`Successfully installed plugin: ${Q.manifest.name}`),{success:!0,pluginName:Q.manifest.name,pluginPath:Y,manifest:Q.manifest}}catch(Z){return{success:!1,error:`Installation failed: ${Z instanceof Error?Z.message:String(Z)}`}}}async uninstall($){try{let Z=Z8.join(this.userPluginsDir,$);try{await i$.access(Z)}catch{return{success:!1,pluginName:$,error:`Plugin "${$}" not found at ${Z}`}}return await i$.rm(Z,{recursive:!0,force:!0}),u0.info(`Successfully uninstalled plugin: ${$}`),{success:!0,pluginName:$,pluginPath:Z}}catch(Z){return{success:!1,pluginName:$,error:`Uninstallation failed: ${Z instanceof Error?Z.message:String(Z)}`}}}async listInstalled(){try{return await i$.access(this.userPluginsDir),(await i$.readdir(this.userPluginsDir,{withFileTypes:!0})).filter((Z)=>Z.isDirectory()).map((Z)=>Z.name)}catch{return[]}}async update($){try{let Z=Z8.join(this.userPluginsDir,$);try{await i$.access(Z)}catch{return{success:!1,pluginName:$,error:`Plugin "${$}" not found at ${Z}`}}let X=Z8.join(Z,".git");try{await i$.access(X)}catch{return{success:!1,pluginName:$,error:`Plugin "${$}" is not a git repository`}}u0.info(`Updating plugin: ${$}...`);try{mG(`git -C "${Z}" pull --ff-only`,{stdio:"pipe",timeout:60000})}catch(Q){return{success:!1,pluginName:$,error:`Failed to update: ${Q instanceof Error?Q.message:String(Q)}`}}let Y;try{Y=await $8(Z)}catch(Q){return{success:!1,pluginName:$,error:`Plugin manifest invalid after update: ${Q instanceof Error?Q.message:String(Q)}`}}if(!Y)return{success:!1,pluginName:$,error:"Plugin manifest not found after update"};return u0.info(`Successfully updated plugin: ${Y.manifest.name}`),{success:!0,pluginName:Y.manifest.name,pluginPath:Z,manifest:Y.manifest}}catch(Z){return{success:!1,pluginName:$,error:`Update failed: ${Z instanceof Error?Z.message:String(Z)}`}}}parseGitUrl($){if($.startsWith("https://")||$.startsWith("git@"))return $;if(/^[a-zA-Z0-9_-]+\/[a-zA-Z0-9_.-]+$/.test($))return`https://github.com/${$}.git`;return null}extractPluginName($){let Z=$.match(/\/([a-zA-Z0-9_.-]+?)(?:\.git)?$/);if(Z)return Z[1];let X=$.match(/:([a-zA-Z0-9_-]+\/)?([a-zA-Z0-9_.-]+?)(?:\.git)?$/);if(X)return X[2];return null}}function J3($){if(!n5)n5=new uG($);return n5}var n5=null;var gG=A(()=>{B0();r5()});function M6($,Z){return`${$}:${Z}`}function cG($,Z){return`${$}__${Z}`}import*as Z1 from"node:fs/promises";import{homedir as T_}from"node:os";import*as _$ from"node:path";import lG from"gray-matter";class j6{async loadPlugin($,Z,X={}){let Y=await $8($);if(!Y)throw Error(`Not a valid plugin directory: ${$}`);let{manifest:Q,source:J}=Y,G=Q.name;u0.debug(`Loading plugin "${G}" from ${$}`);let q=X.skipCommands?[]:await this.loadCommands($,G),K=X.skipAgents?[]:await this.loadAgents($,G),W=X.skipSkills?[]:await this.loadSkills($,G),U=X.skipHooks?void 0:await this.loadHooks($),H=X.skipMcp?void 0:await this.loadMcpConfig($,G);return u0.debug(`Plugin "${G}" loaded: ${q.length} commands, ${K.length} agents, ${W.length} skills`),{manifest:Q,basePath:$,source:Z,manifestSource:J,commands:q,agents:K,skills:W,hooks:U,mcpServers:H,status:"active",loadedAt:new Date}}async loadCommands($,Z){let X=_$.join($,"commands"),Y=[];if(!await this.dirExists(X))return Y;let Q=await this.scanMarkdownFiles(X);for(let J of Q)try{let G=await this.parseCommandFile(J,X,Z);if(G)Y.push(G)}catch(G){u0.warn(`Failed to load command from ${J}: ${G instanceof Error?G.message:String(G)}`)}return Y}async parseCommandFile($,Z,X){let Y=await Z1.readFile($,"utf-8"),{data:Q,content:J}=lG(Y),q=_$.relative(Z,$).split(_$.sep),K=q.pop();if(!K)return null;let W=K.replace(/\.md$/i,""),U=W;if(q.length>0)U=[...q,W].join("/");let H=M6(X,U),F=this.normalizeCommandConfig(Q);return{originalName:U,namespacedName:H,pluginName:X,config:F,content:J.trim(),path:$}}normalizeCommandConfig($){return{description:this.asString($.description),allowedTools:this.parseStringArray($["allowed-tools"]),argumentHint:this.asString($["argument-hint"]),model:this.asString($.model),disableModelInvocation:$["disable-model-invocation"]===!0}}async loadAgents($,Z){let X=_$.join($,"agents"),Y=[];if(!await this.dirExists(X))return Y;let Q=await this.scanMarkdownFiles(X);for(let J of Q)try{let G=await this.parseAgentFile(J,X,Z);if(G)Y.push(G)}catch(G){u0.warn(`Failed to load agent from ${J}: ${G instanceof Error?G.message:String(G)}`)}return Y}async parseAgentFile($,Z,X){let Y=await Z1.readFile($,"utf-8"),{data:Q,content:J}=lG(Y),G=_$.relative(Z,$),q=_$.basename(G,".md"),K=Q.name||q,W=M6(X,K),U={name:W,description:this.asString(Q.description)||"",tools:this.parseStringArray(Q.tools),color:this.asString(Q.color),model:this.asString(Q.model),permissionMode:this.asString(Q.permissionMode),skills:this.parseStringArray(Q.skills),systemPrompt:J.trim(),source:`plugin:${X}`};return{originalName:K,namespacedName:W,pluginName:X,config:U,path:$}}async loadSkills($,Z){let X=_$.join($,"skills"),Y=[];if(!await this.dirExists(X))return Y;let Q=await Z1.readdir(X,{withFileTypes:!0});for(let J of Q){if(!J.isDirectory())continue;let G=_$.join(X,J.name),q=_$.join(G,"SKILL.md");try{let K=await a3(q,"project");if(K.success&&K.content){let W=K.content.metadata.name,U=M6(Z,W);Y.push({originalName:W,namespacedName:U,pluginName:Z,metadata:{...K.content.metadata,name:U},path:G})}}catch(K){u0.warn(`Failed to load skill from ${q}: ${K instanceof Error?K.message:String(K)}`)}}return Y}async loadHooks($){let Z=_$.join($,"hooks","hooks.json");try{let X=await Z1.readFile(Z,"utf-8"),Y=JSON.parse(X);return Y.hooks||Y}catch{return}}async loadMcpConfig($,Z){let X=_$.join($,".mcp.json");try{let Y=await Z1.readFile(X,"utf-8"),Q=JSON.parse(Y),J=xG(Q);if(!J.success){u0.warn(`Invalid .mcp.json in ${$}: ${J.error}`);return}let G="mcpServers"in Q?Q.mcpServers:Q,q={};for(let[K,W]of Object.entries(G)){let U=cG(Z,K);q[U]=W}return q}catch{return}}async scanMarkdownFiles($){let Z=[],X=async(Y)=>{let Q=await Z1.readdir(Y,{withFileTypes:!0});for(let J of Q){let G=_$.join(Y,J.name);if(J.isDirectory())await X(G);else if(J.name.endsWith(".md"))Z.push(G)}};return await X($),Z}async dirExists($){try{return(await Z1.stat($)).isDirectory()}catch{return!1}}asString($){if(typeof $==="string"&&$.trim())return $.trim();return}parseStringArray($){if(!$)return;if(Array.isArray($))return $.map((Z)=>String(Z).trim()).filter(Boolean);if(typeof $==="string")return $.split(",").map((Z)=>Z.trim()).filter(Boolean);return}static getPluginDirs($){let Z=T_();return[{path:_$.join(Z,".claude","plugins"),source:"user",type:"claude"},{path:_$.join(Z,".blade","plugins"),source:"user",type:"blade"},{path:_$.join($,".claude","plugins"),source:"project",type:"claude"},{path:_$.join($,".blade","plugins"),source:"project",type:"blade"}]}async discoverPluginsInDir($,Z){let X=[],Y=[];try{await Z1.access($)}catch{return{plugins:X,errors:Y}}let Q=await Z1.readdir($,{withFileTypes:!0});for(let J of Q){if(!J.isDirectory())continue;let G=_$.join($,J.name);try{let q=await this.loadPlugin(G,Z);X.push(q)}catch(q){Y.push({path:G,error:q instanceof Error?q.message:String(q)})}}return{plugins:X,errors:Y}}}var iG=A(()=>{B0();y7();r5();a5()});class W2{static instance=null;plugins=new Map;loader=new j6;initialized=!1;workspaceRoot="";cliPluginDirs=[];constructor(){}static getInstance(){if(!W2.instance)W2.instance=new W2;return W2.instance}static resetInstance(){W2.instance=null}async initialize($,Z=[]){this.workspaceRoot=$,this.cliPluginDirs=Z;let X=[],Y=[];for(let J of Z)try{let G=await this.loader.loadPlugin(J,"cli");this.plugins.set(G.manifest.name,G),X.push(G),u0.info(`Loaded CLI plugin: ${G.manifest.name} from ${J}`)}catch(G){Y.push({path:J,error:G instanceof Error?G.message:String(G)}),u0.warn(`Failed to load CLI plugin from ${J}: ${G}`)}let Q=j6.getPluginDirs($);for(let{path:J,source:G}of Q){let q=await this.loader.discoverPluginsInDir(J,G);for(let K of q.plugins){let W=this.plugins.get(K.manifest.name);if(!W||W.source!=="cli")this.plugins.set(K.manifest.name,K),X.push(K)}Y.push(...q.errors)}return this.initialized=!0,u0.info(`Plugin system initialized: ${this.plugins.size} plugins loaded`+(Y.length>0?`, ${Y.length} errors`:"")),{plugins:Array.from(this.plugins.values()),errors:Y}}isInitialized(){return this.initialized}getAll(){return Array.from(this.plugins.values())}getActive(){return Array.from(this.plugins.values()).filter(($)=>$.status==="active")}get($){return this.plugins.get($)}has($){return this.plugins.has($)}getBySource(){let $={cli:[],project:[],user:[]};for(let Z of this.plugins.values())$[Z.source].push(Z);return $}getAllCommands(){let $=[];for(let Z of this.plugins.values())if(Z.status==="active")$.push(...Z.commands);return $}getAllSkills(){let $=[];for(let Z of this.plugins.values())if(Z.status==="active")$.push(...Z.skills);return $}getAllAgents(){let $=[];for(let Z of this.plugins.values())if(Z.status==="active")$.push(...Z.agents);return $}findCommand($){for(let X of this.plugins.values()){if(X.status!=="active")continue;for(let Y of X.commands)if(Y.namespacedName===$)return Y}let Z=[];for(let X of this.plugins.values()){if(X.status!=="active")continue;for(let Y of X.commands)if(Y.originalName===$)Z.push(Y)}if(Z.length===1)return Z[0];return}findSkill($){for(let X of this.plugins.values()){if(X.status!=="active")continue;for(let Y of X.skills)if(Y.namespacedName===$)return Y}let Z=[];for(let X of this.plugins.values()){if(X.status!=="active")continue;for(let Y of X.skills)if(Y.originalName===$)Z.push(Y)}if(Z.length===1)return Z[0];return}findAgent($){for(let X of this.plugins.values()){if(X.status!=="active")continue;for(let Y of X.agents)if(Y.namespacedName===$)return Y}let Z=[];for(let X of this.plugins.values()){if(X.status!=="active")continue;for(let Y of X.agents)if(Y.originalName===$)Z.push(Y)}if(Z.length===1)return Z[0];return}hasCommandConflict($){let Z=0;for(let X of this.plugins.values()){if(X.status!=="active")continue;for(let Y of X.commands)if(Y.originalName===$){if(Z++,Z>1)return!0}}return!1}getCommandProviders($){let Z=[];for(let X of this.plugins.values()){if(X.status!=="active")continue;for(let Y of X.commands)if(Y.originalName===$){Z.push(X.manifest.name);break}}return Z}disable($){let Z=this.plugins.get($);if(Z&&Z.status==="active")return Z.status="inactive",u0.info(`Plugin "${$}" disabled`),!0;return!1}enable($){let Z=this.plugins.get($);if(Z&&Z.status==="inactive")return Z.status="active",u0.info(`Plugin "${$}" enabled`),!0;return!1}async refresh(){return u0.info("Refreshing plugin list..."),this.plugins.clear(),this.initialized=!1,this.initialize(this.workspaceRoot,this.cliPluginDirs)}getStats(){let $=0,Z=0,X=0,Y=0,Q=0;for(let J of this.plugins.values())if(J.status==="active")$++,X+=J.commands.length,Y+=J.skills.length,Q+=J.agents.length;else Z++;return{total:this.plugins.size,active:$,inactive:Z,commands:X,skills:Y,agents:Q}}formatPluginList(){if(this.getAll().length===0)return"没有已加载的插件。";let Z=[],X=this.getBySource();if(X.cli.length>0){Z.push("## CLI 指定的插件");for(let Y of X.cli){let Q=Y.status==="inactive"?" (禁用)":"";Z.push(`- **${Y.manifest.name}** v${Y.manifest.version}${Q}`),Z.push(` ${Y.manifest.description}`)}Z.push("")}if(X.project.length>0){Z.push("## 项目级插件");for(let Y of X.project){let Q=Y.status==="inactive"?" (禁用)":"";Z.push(`- **${Y.manifest.name}** v${Y.manifest.version}${Q}`),Z.push(` ${Y.manifest.description}`)}Z.push("")}if(X.user.length>0){Z.push("## 用户级插件");for(let Y of X.user){let Q=Y.status==="inactive"?" (禁用)":"";Z.push(`- **${Y.manifest.name}** v${Y.manifest.version}${Q}`),Z.push(` ${Y.manifest.description}`)}}return Z.join(`
|
|
2159
|
-
`)}}function a$(){return
|
|
2158
|
+
`);return Q}}var f;var Q2=A(()=>{y4();R7();r$();B0();D7();rY();s2();FQ();wQ();S7();A7();X2();U1();C0();bG();jG();IG();E$();T7();R6();SG();G4();f=i("Agent")});import{z as U0}from"zod";function xG($){return v_.safeParse($)}var j_,I_,y_,hG,fG,v_;var a5=A(()=>{j_=U0.string().min(2,"Plugin name must be at least 2 characters").max(64,"Plugin name must be at most 64 characters").regex(/^[a-z0-9][a-z0-9-]*[a-z0-9]$|^[a-z0-9]{1,2}$/,{message:"Plugin name must be lowercase letters, numbers, and hyphens only, starting and ending with alphanumeric"}),I_=U0.string().regex(/^\d+\.\d+\.\d+(-[\w.]+)?(\+[\w.]+)?$/,{message:"Version must be a valid semantic version (e.g., 1.0.0)"}),y_=U0.object({name:U0.string().min(1,"Author name is required"),email:U0.string().email().optional(),url:U0.string().url().optional()}),hG=U0.object({name:j_,description:U0.string().min(1,"Description is required").max(500,"Description must be at most 500 characters"),version:I_,author:y_.optional(),license:U0.string().optional(),repository:U0.string().url().optional(),homepage:U0.string().url().optional(),keywords:U0.array(U0.string()).optional(),dependencies:U0.record(U0.string()).optional(),bladeVersion:U0.string().optional()}),fG=U0.object({type:U0.enum(["stdio","sse","http"]),command:U0.string().optional(),args:U0.array(U0.string()).optional(),env:U0.record(U0.string()).optional(),url:U0.string().url().optional(),headers:U0.record(U0.string()).optional(),timeout:U0.number().positive().optional(),oauth:U0.object({enabled:U0.boolean().optional(),clientId:U0.string().optional(),clientSecret:U0.string().optional(),authorizationUrl:U0.string().url().optional(),tokenUrl:U0.string().url().optional(),scopes:U0.array(U0.string()).optional(),redirectUri:U0.string().url().optional()}).optional(),healthCheck:U0.object({enabled:U0.boolean().optional(),interval:U0.number().positive().optional(),timeout:U0.number().positive().optional(),failureThreshold:U0.number().positive().optional()}).optional()}),v_=U0.union([U0.object({mcpServers:U0.record(fG)}),U0.record(fG)])});import*as D6 from"node:fs/promises";import*as pG from"node:path";async function $8($){for(let{dir:Z,source:X}of E_){let Y=pG.join($,Z,"plugin.json");try{await D6.access(Y)}catch{continue}try{let Q=await D6.readFile(Y,"utf-8"),J=JSON.parse(Q),G=hG.safeParse(J);if(!G.success){let q=G.error.issues.map((K)=>`${K.path.join(".")}: ${K.message}`).join("; ");throw Error(`Invalid plugin.json: ${q}`)}return u0.debug(`Parsed plugin manifest from ${Y}`),{manifest:G.data,source:X,manifestPath:Y}}catch(Q){if(Q instanceof SyntaxError)throw Error(`Invalid JSON in ${Y}: ${Q.message}`);throw Q}}return null}async function dG($){try{return await $8($)!==null}catch{return!1}}var E_;var r5=A(()=>{B0();a5();E_=[{dir:".blade-plugin",source:"blade"},{dir:".claude-plugin",source:"claude"}]});import{execSync as mG}from"node:child_process";import*as i$ from"node:fs/promises";import{homedir as P_}from"node:os";import*as Z8 from"node:path";class uG{userPluginsDir;constructor($){this.userPluginsDir=$||Z8.join(P_(),".blade","plugins")}async install($){try{let Z=this.parseGitUrl($);if(!Z)return{success:!1,error:`Invalid source URL: ${$}`};let X=this.extractPluginName(Z);if(!X)return{success:!1,error:`Could not extract plugin name from URL: ${Z}`};await i$.mkdir(this.userPluginsDir,{recursive:!0});let Y=Z8.join(this.userPluginsDir,X);try{return await i$.access(Y),{success:!1,pluginName:X,pluginPath:Y,error:`Plugin "${X}" already exists at ${Y}. Use /plugins uninstall first.`}}catch{}u0.info(`Cloning ${Z} to ${Y}...`);try{mG(`git clone --depth 1 "${Z}" "${Y}"`,{stdio:"pipe",timeout:60000})}catch(J){return{success:!1,pluginName:X,error:`Failed to clone repository: ${J instanceof Error?J.message:String(J)}`}}if(!await dG(Y))return await i$.rm(Y,{recursive:!0,force:!0}),{success:!1,pluginName:X,error:"Invalid plugin: No .blade-plugin/plugin.json or .claude-plugin/plugin.json found"};let Q;try{Q=await $8(Y)}catch(J){return await i$.rm(Y,{recursive:!0,force:!0}),{success:!1,pluginName:X,error:`Invalid plugin manifest: ${J instanceof Error?J.message:String(J)}`}}if(!Q)return await i$.rm(Y,{recursive:!0,force:!0}),{success:!1,pluginName:X,error:"Invalid plugin manifest: No manifest found"};return u0.info(`Successfully installed plugin: ${Q.manifest.name}`),{success:!0,pluginName:Q.manifest.name,pluginPath:Y,manifest:Q.manifest}}catch(Z){return{success:!1,error:`Installation failed: ${Z instanceof Error?Z.message:String(Z)}`}}}async uninstall($){try{let Z=Z8.join(this.userPluginsDir,$);try{await i$.access(Z)}catch{return{success:!1,pluginName:$,error:`Plugin "${$}" not found at ${Z}`}}return await i$.rm(Z,{recursive:!0,force:!0}),u0.info(`Successfully uninstalled plugin: ${$}`),{success:!0,pluginName:$,pluginPath:Z}}catch(Z){return{success:!1,pluginName:$,error:`Uninstallation failed: ${Z instanceof Error?Z.message:String(Z)}`}}}async listInstalled(){try{return await i$.access(this.userPluginsDir),(await i$.readdir(this.userPluginsDir,{withFileTypes:!0})).filter((Z)=>Z.isDirectory()).map((Z)=>Z.name)}catch{return[]}}async update($){try{let Z=Z8.join(this.userPluginsDir,$);try{await i$.access(Z)}catch{return{success:!1,pluginName:$,error:`Plugin "${$}" not found at ${Z}`}}let X=Z8.join(Z,".git");try{await i$.access(X)}catch{return{success:!1,pluginName:$,error:`Plugin "${$}" is not a git repository`}}u0.info(`Updating plugin: ${$}...`);try{mG(`git -C "${Z}" pull --ff-only`,{stdio:"pipe",timeout:60000})}catch(Q){return{success:!1,pluginName:$,error:`Failed to update: ${Q instanceof Error?Q.message:String(Q)}`}}let Y;try{Y=await $8(Z)}catch(Q){return{success:!1,pluginName:$,error:`Plugin manifest invalid after update: ${Q instanceof Error?Q.message:String(Q)}`}}if(!Y)return{success:!1,pluginName:$,error:"Plugin manifest not found after update"};return u0.info(`Successfully updated plugin: ${Y.manifest.name}`),{success:!0,pluginName:Y.manifest.name,pluginPath:Z,manifest:Y.manifest}}catch(Z){return{success:!1,pluginName:$,error:`Update failed: ${Z instanceof Error?Z.message:String(Z)}`}}}parseGitUrl($){if($.startsWith("https://")||$.startsWith("git@"))return $;if(/^[a-zA-Z0-9_-]+\/[a-zA-Z0-9_.-]+$/.test($))return`https://github.com/${$}.git`;return null}extractPluginName($){let Z=$.match(/\/([a-zA-Z0-9_.-]+?)(?:\.git)?$/);if(Z)return Z[1];let X=$.match(/:([a-zA-Z0-9_-]+\/)?([a-zA-Z0-9_.-]+?)(?:\.git)?$/);if(X)return X[2];return null}}function J3($){if(!n5)n5=new uG($);return n5}var n5=null;var gG=A(()=>{B0();r5()});function M6($,Z){return`${$}:${Z}`}function cG($,Z){return`${$}__${Z}`}import*as Z1 from"node:fs/promises";import{homedir as T_}from"node:os";import*as _$ from"node:path";import lG from"gray-matter";class j6{async loadPlugin($,Z,X={}){let Y=await $8($);if(!Y)throw Error(`Not a valid plugin directory: ${$}`);let{manifest:Q,source:J}=Y,G=Q.name;u0.debug(`Loading plugin "${G}" from ${$}`);let q=X.skipCommands?[]:await this.loadCommands($,G),K=X.skipAgents?[]:await this.loadAgents($,G),W=X.skipSkills?[]:await this.loadSkills($,G),U=X.skipHooks?void 0:await this.loadHooks($),H=X.skipMcp?void 0:await this.loadMcpConfig($,G);return u0.debug(`Plugin "${G}" loaded: ${q.length} commands, ${K.length} agents, ${W.length} skills`),{manifest:Q,basePath:$,source:Z,manifestSource:J,commands:q,agents:K,skills:W,hooks:U,mcpServers:H,status:"active",loadedAt:new Date}}async loadCommands($,Z){let X=_$.join($,"commands"),Y=[];if(!await this.dirExists(X))return Y;let Q=await this.scanMarkdownFiles(X);for(let J of Q)try{let G=await this.parseCommandFile(J,X,Z);if(G)Y.push(G)}catch(G){u0.warn(`Failed to load command from ${J}: ${G instanceof Error?G.message:String(G)}`)}return Y}async parseCommandFile($,Z,X){let Y=await Z1.readFile($,"utf-8"),{data:Q,content:J}=lG(Y),q=_$.relative(Z,$).split(_$.sep),K=q.pop();if(!K)return null;let W=K.replace(/\.md$/i,""),U=W;if(q.length>0)U=[...q,W].join("/");let H=M6(X,U),F=this.normalizeCommandConfig(Q);return{originalName:U,namespacedName:H,pluginName:X,config:F,content:J.trim(),path:$}}normalizeCommandConfig($){return{description:this.asString($.description),allowedTools:this.parseStringArray($["allowed-tools"]),argumentHint:this.asString($["argument-hint"]),model:this.asString($.model),disableModelInvocation:$["disable-model-invocation"]===!0}}async loadAgents($,Z){let X=_$.join($,"agents"),Y=[];if(!await this.dirExists(X))return Y;let Q=await this.scanMarkdownFiles(X);for(let J of Q)try{let G=await this.parseAgentFile(J,X,Z);if(G)Y.push(G)}catch(G){u0.warn(`Failed to load agent from ${J}: ${G instanceof Error?G.message:String(G)}`)}return Y}async parseAgentFile($,Z,X){let Y=await Z1.readFile($,"utf-8"),{data:Q,content:J}=lG(Y),G=_$.relative(Z,$),q=_$.basename(G,".md"),K=Q.name||q,W=M6(X,K),U={name:W,description:this.asString(Q.description)||"",tools:this.parseStringArray(Q.tools),color:this.asString(Q.color),model:this.asString(Q.model),permissionMode:this.asString(Q.permissionMode),skills:this.parseStringArray(Q.skills),systemPrompt:J.trim(),source:`plugin:${X}`};return{originalName:K,namespacedName:W,pluginName:X,config:U,path:$}}async loadSkills($,Z){let X=_$.join($,"skills"),Y=[];if(!await this.dirExists(X))return Y;let Q=await Z1.readdir(X,{withFileTypes:!0});for(let J of Q){if(!J.isDirectory())continue;let G=_$.join(X,J.name),q=_$.join(G,"SKILL.md");try{let K=await a3(q,"project");if(K.success&&K.content){let W=K.content.metadata.name,U=M6(Z,W);Y.push({originalName:W,namespacedName:U,pluginName:Z,metadata:{...K.content.metadata,name:U},path:G})}}catch(K){u0.warn(`Failed to load skill from ${q}: ${K instanceof Error?K.message:String(K)}`)}}return Y}async loadHooks($){let Z=_$.join($,"hooks","hooks.json");try{let X=await Z1.readFile(Z,"utf-8"),Y=JSON.parse(X);return Y.hooks||Y}catch{return}}async loadMcpConfig($,Z){let X=_$.join($,".mcp.json");try{let Y=await Z1.readFile(X,"utf-8"),Q=JSON.parse(Y),J=xG(Q);if(!J.success){u0.warn(`Invalid .mcp.json in ${$}: ${J.error}`);return}let G="mcpServers"in Q?Q.mcpServers:Q,q={};for(let[K,W]of Object.entries(G)){let U=cG(Z,K);q[U]=W}return q}catch{return}}async scanMarkdownFiles($){let Z=[],X=async(Y)=>{let Q=await Z1.readdir(Y,{withFileTypes:!0});for(let J of Q){let G=_$.join(Y,J.name);if(J.isDirectory())await X(G);else if(J.name.endsWith(".md"))Z.push(G)}};return await X($),Z}async dirExists($){try{return(await Z1.stat($)).isDirectory()}catch{return!1}}asString($){if(typeof $==="string"&&$.trim())return $.trim();return}parseStringArray($){if(!$)return;if(Array.isArray($))return $.map((Z)=>String(Z).trim()).filter(Boolean);if(typeof $==="string")return $.split(",").map((Z)=>Z.trim()).filter(Boolean);return}static getPluginDirs($){let Z=T_();return[{path:_$.join(Z,".claude","plugins"),source:"user",type:"claude"},{path:_$.join(Z,".blade","plugins"),source:"user",type:"blade"},{path:_$.join($,".claude","plugins"),source:"project",type:"claude"},{path:_$.join($,".blade","plugins"),source:"project",type:"blade"}]}async discoverPluginsInDir($,Z){let X=[],Y=[];try{await Z1.access($)}catch{return{plugins:X,errors:Y}}let Q=await Z1.readdir($,{withFileTypes:!0});for(let J of Q){if(!J.isDirectory())continue;let G=_$.join($,J.name);try{let q=await this.loadPlugin(G,Z);X.push(q)}catch(q){Y.push({path:G,error:q instanceof Error?q.message:String(q)})}}return{plugins:X,errors:Y}}}var iG=A(()=>{B0();y7();r5();a5()});class W4{static instance=null;plugins=new Map;loader=new j6;initialized=!1;workspaceRoot="";cliPluginDirs=[];constructor(){}static getInstance(){if(!W4.instance)W4.instance=new W4;return W4.instance}static resetInstance(){W4.instance=null}async initialize($,Z=[]){this.workspaceRoot=$,this.cliPluginDirs=Z;let X=[],Y=[];for(let J of Z)try{let G=await this.loader.loadPlugin(J,"cli");this.plugins.set(G.manifest.name,G),X.push(G),u0.info(`Loaded CLI plugin: ${G.manifest.name} from ${J}`)}catch(G){Y.push({path:J,error:G instanceof Error?G.message:String(G)}),u0.warn(`Failed to load CLI plugin from ${J}: ${G}`)}let Q=j6.getPluginDirs($);for(let{path:J,source:G}of Q){let q=await this.loader.discoverPluginsInDir(J,G);for(let K of q.plugins){let W=this.plugins.get(K.manifest.name);if(!W||W.source!=="cli")this.plugins.set(K.manifest.name,K),X.push(K)}Y.push(...q.errors)}return this.initialized=!0,u0.info(`Plugin system initialized: ${this.plugins.size} plugins loaded`+(Y.length>0?`, ${Y.length} errors`:"")),{plugins:Array.from(this.plugins.values()),errors:Y}}isInitialized(){return this.initialized}getAll(){return Array.from(this.plugins.values())}getActive(){return Array.from(this.plugins.values()).filter(($)=>$.status==="active")}get($){return this.plugins.get($)}has($){return this.plugins.has($)}getBySource(){let $={cli:[],project:[],user:[]};for(let Z of this.plugins.values())$[Z.source].push(Z);return $}getAllCommands(){let $=[];for(let Z of this.plugins.values())if(Z.status==="active")$.push(...Z.commands);return $}getAllSkills(){let $=[];for(let Z of this.plugins.values())if(Z.status==="active")$.push(...Z.skills);return $}getAllAgents(){let $=[];for(let Z of this.plugins.values())if(Z.status==="active")$.push(...Z.agents);return $}findCommand($){for(let X of this.plugins.values()){if(X.status!=="active")continue;for(let Y of X.commands)if(Y.namespacedName===$)return Y}let Z=[];for(let X of this.plugins.values()){if(X.status!=="active")continue;for(let Y of X.commands)if(Y.originalName===$)Z.push(Y)}if(Z.length===1)return Z[0];return}findSkill($){for(let X of this.plugins.values()){if(X.status!=="active")continue;for(let Y of X.skills)if(Y.namespacedName===$)return Y}let Z=[];for(let X of this.plugins.values()){if(X.status!=="active")continue;for(let Y of X.skills)if(Y.originalName===$)Z.push(Y)}if(Z.length===1)return Z[0];return}findAgent($){for(let X of this.plugins.values()){if(X.status!=="active")continue;for(let Y of X.agents)if(Y.namespacedName===$)return Y}let Z=[];for(let X of this.plugins.values()){if(X.status!=="active")continue;for(let Y of X.agents)if(Y.originalName===$)Z.push(Y)}if(Z.length===1)return Z[0];return}hasCommandConflict($){let Z=0;for(let X of this.plugins.values()){if(X.status!=="active")continue;for(let Y of X.commands)if(Y.originalName===$){if(Z++,Z>1)return!0}}return!1}getCommandProviders($){let Z=[];for(let X of this.plugins.values()){if(X.status!=="active")continue;for(let Y of X.commands)if(Y.originalName===$){Z.push(X.manifest.name);break}}return Z}disable($){let Z=this.plugins.get($);if(Z&&Z.status==="active")return Z.status="inactive",u0.info(`Plugin "${$}" disabled`),!0;return!1}enable($){let Z=this.plugins.get($);if(Z&&Z.status==="inactive")return Z.status="active",u0.info(`Plugin "${$}" enabled`),!0;return!1}async refresh(){return u0.info("Refreshing plugin list..."),this.plugins.clear(),this.initialized=!1,this.initialize(this.workspaceRoot,this.cliPluginDirs)}getStats(){let $=0,Z=0,X=0,Y=0,Q=0;for(let J of this.plugins.values())if(J.status==="active")$++,X+=J.commands.length,Y+=J.skills.length,Q+=J.agents.length;else Z++;return{total:this.plugins.size,active:$,inactive:Z,commands:X,skills:Y,agents:Q}}formatPluginList(){if(this.getAll().length===0)return"没有已加载的插件。";let Z=[],X=this.getBySource();if(X.cli.length>0){Z.push("## CLI 指定的插件");for(let Y of X.cli){let Q=Y.status==="inactive"?" (禁用)":"";Z.push(`- **${Y.manifest.name}** v${Y.manifest.version}${Q}`),Z.push(` ${Y.manifest.description}`)}Z.push("")}if(X.project.length>0){Z.push("## 项目级插件");for(let Y of X.project){let Q=Y.status==="inactive"?" (禁用)":"";Z.push(`- **${Y.manifest.name}** v${Y.manifest.version}${Q}`),Z.push(` ${Y.manifest.description}`)}Z.push("")}if(X.user.length>0){Z.push("## 用户级插件");for(let Y of X.user){let Q=Y.status==="inactive"?" (禁用)":"";Z.push(`- **${Y.manifest.name}** v${Y.manifest.version}${Q}`),Z.push(` ${Y.manifest.description}`)}}return Z.join(`
|
|
2159
|
+
`)}}function a$(){return W4.getInstance()}var o5=A(()=>{B0();iG()});class s5{commandRegistry;hookManager;mcpRegistry;constructor(){this.commandRegistry=B$.getInstance(),this.hookManager=M0.getInstance(),this.mcpRegistry=N$.getInstance()}clearAllPluginResources(){this.commandRegistry.clearPluginCommands(),b$().clearPluginSkills(),J$.clearPluginAgents(),u0.debug("Cleared all plugin resources from subsystems")}async integrateAll(){let Z=a$().getActive(),X=[],Y=[],Q=0,J=0,G=0,q=0;for(let K of Z){let W=await this.integratePlugin(K);X.push(W),Q+=W.commandsRegistered,J+=W.skillsRegistered,G+=W.agentsRegistered,q+=W.mcpServersRegistered,Y.push(...W.errors)}if(Q+J+G>0)u0.info(`Plugin integration complete: ${Q} commands, ${J} skills, ${G} agents, ${q} MCP servers`);return{plugins:X,totalCommands:Q,totalSkills:J,totalAgents:G,totalMcpServers:q,errors:Y}}async integratePlugin($){let Z={pluginName:$.manifest.name,commandsRegistered:0,skillsRegistered:0,agentsRegistered:0,hooksRegistered:!1,mcpServersRegistered:0,errors:[]};try{Z.commandsRegistered=this.integrateCommands($)}catch(X){Z.errors.push(`Failed to integrate commands: ${X instanceof Error?X.message:String(X)}`)}try{Z.skillsRegistered=this.integrateSkills($)}catch(X){Z.errors.push(`Failed to integrate skills: ${X instanceof Error?X.message:String(X)}`)}try{Z.agentsRegistered=this.integrateAgents($)}catch(X){Z.errors.push(`Failed to integrate agents: ${X instanceof Error?X.message:String(X)}`)}try{Z.hooksRegistered=this.integrateHooks($)}catch(X){Z.errors.push(`Failed to integrate hooks: ${X instanceof Error?X.message:String(X)}`)}try{Z.mcpServersRegistered=await this.integrateMcp($)}catch(X){Z.errors.push(`Failed to integrate MCP servers: ${X instanceof Error?X.message:String(X)}`)}return u0.debug(`Integrated plugin "${$.manifest.name}": ${Z.commandsRegistered} commands, ${Z.skillsRegistered} skills, ${Z.agentsRegistered} agents`),Z}integrateCommands($){let Z=0;for(let X of $.commands)this.commandRegistry.registerPluginCommand(X),Z++;return Z}integrateSkills($){let Z=b$(),X=0;for(let Y of $.skills)Z.registerPluginSkill(Y),X++;return X}integrateAgents($){let Z=0;for(let X of $.agents)J$.register({...X.config,name:X.namespacedName}),Z++;return Z}integrateHooks($){if(!$.hooks)return!1;let Z=this.hookManager.getConfig();return this.hookManager.loadConfig({...Z,...$.hooks}),!0}async integrateMcp($){if(!$.mcpServers)return 0;let Z=0;for(let[X,Y]of Object.entries($.mcpServers))try{await this.mcpRegistry.registerServer(X,Y),Z++}catch(Q){u0.warn(`Failed to register MCP server "${X}" from plugin "${$.manifest.name}": ${Q instanceof Error?Q.message:String(Q)}`)}return Z}}async function v2(){return new s5().integrateAll()}function I6(){new s5().clearAllPluginResources()}var aG=A(()=>{G4();r$();B0();s2();X2();_5();o5()});var X8=A(()=>{gG();aG();o5()});function m0($){if($.acp)return{sendMessage:(Z)=>$.acp.sendMessage(`• ${Z}
|
|
2160
2160
|
|
|
2161
|
-
`),sendToolStart:$.acp.sendToolStart,sendToolResult:$.acp.sendToolResult};return{sendMessage:(Z)=>z0().addAssistantMessage(Z),sendToolStart:void 0,sendToolResult:void 0}}var y1=A(()=>{C0()});import S_ from"node:os";import rG from"node:path";var nG;var oG=A(()=>{
|
|
2161
|
+
`),sendToolStart:$.acp.sendToolStart,sendToolResult:$.acp.sendToolResult};return{sendMessage:(Z)=>z0().addAssistantMessage(Z),sendToolStart:void 0,sendToolResult:void 0}}var y1=A(()=>{C0()});import S_ from"node:os";import rG from"node:path";var nG;var oG=A(()=>{G4();y1();nG={name:"agents",description:"Manage agent configurations",fullDescription:"Create, edit, or delete custom subagents. Subagents are specialized agents that Claude can delegate tasks to.",usage:"/agents [list|create|help]",category:"System",examples:["/agents","/agents list","/agents help"],async handler($,Z){let X=$[0],Y=m0(Z);if(!X)return{success:!0,message:"show_agents_manager",data:{action:"show_agents_manager"}};if(X==="list"){let J=J$.getAllNames().map((H)=>J$.getSubagent(H)).filter((H)=>H!==void 0);if(J.length===0){let H=`\uD83D\uDCCB **Agents 管理**
|
|
2162
2162
|
|
|
2163
2163
|
`+`❌ 没有找到任何 agent 配置
|
|
2164
2164
|
|
|
@@ -2203,12 +2203,12 @@ Please continue the conversation from where we left it off without asking the us
|
|
|
2203
2203
|
`+"- 项目级 (`.blade/agents/`) - 最高优先级\n"+"- 用户级 (`~/.blade/agents/`) - 较低优先级\n\n"+`**可用工具:**
|
|
2204
2204
|
`+"- `Glob` - 文件搜索\n"+"- `Grep` - 内容搜索\n"+"- `Read` - 读取文件\n"+"- `Write` - 写入文件\n"+"- `Edit` - 编辑文件\n"+"- `Bash` - 执行命令\n"+"- 省略 `tools` 字段 = 继承所有工具\n\n"+"\uD83D\uDCA1 **提示:** 创建文件后,重启 Blade 使配置生效";return Y.sendMessage(J),{success:!0,message:"Help displayed"}}if(X==="create")return{success:!0,message:"show_agent_creation_wizard",data:{action:"show_agent_creation_wizard"}};let Q=`❌ 未知子命令: \`${X}\`
|
|
2205
2205
|
|
|
2206
|
-
`+"使用 `/agents help` 查看可用命令";return Y.sendMessage(Q),{success:!1,error:`Unknown subcommand: ${X}`}}}});async function C_($,Z){let X=m0(Z);try{let Y=H$(),Q=
|
|
2206
|
+
`+"使用 `/agents help` 查看可用命令";return Y.sendMessage(Q),{success:!1,error:`Unknown subcommand: ${X}`}}}});async function C_($,Z){let X=m0(Z);try{let Y=H$(),Q=P4();if(!Y||!Q)return{success:!1,error:"配置未初始化"};let J=K0().session,G=J.messages,q=J.sessionId;if(!G||G.length===0)return X.sendMessage("⚠️ 当前会话没有消息,无需压缩"),{success:!1,error:"没有消息需要压缩"};let K=G.map((O)=>({role:O.role,content:O.content})),W=Z2.countTokens(K,Q.model),U=Q.maxContextTokens??Y.maxContextTokens,H=(W/U*100).toFixed(1);if(X.sendMessage(`\uD83D\uDCCA **当前上下文统计**
|
|
2207
2207
|
• 消息数量: ${K.length}
|
|
2208
2208
|
• Token 数量: ${W.toLocaleString()}
|
|
2209
2209
|
• Token 限制: ${U.toLocaleString()}
|
|
2210
2210
|
• 使用率: ${H}%`),W<U*0.5)return X.sendMessage(`\uD83D\uDCA1 提示: 当前 token 使用率较低(${H}%),可以暂时不压缩。
|
|
2211
|
-
系统会在达到 80% 时自动触发压缩。`),{success:!0,message:"无需压缩"};X.sendMessage("⏳ **正在压缩上下文...**");let F=await
|
|
2211
|
+
系统会在达到 80% 时自动触发压缩。`),{success:!0,message:"无需压缩"};X.sendMessage("⏳ **正在压缩上下文...**");let F=await h4.compact(K,{trigger:"manual",modelName:Q.model,maxContextTokens:U,apiKey:Q.apiKey,baseURL:Q.baseUrl});if(F.success){try{if(q)await new Q3().saveCompaction(q,F.summary,{trigger:"manual",preTokens:F.preTokens,postTokens:F.postTokens,filesIncluded:F.filesIncluded},null),console.log("[/compact] 压缩数据已保存到 JSONL")}catch(z){console.warn("[/compact] 保存压缩数据失败:",z)}let O=`✅ **压缩完成!**
|
|
2212
2212
|
|
|
2213
2213
|
\uD83D\uDCC9 **Token 变化**
|
|
2214
2214
|
• 压缩前: ${F.preTokens.toLocaleString()} tokens
|
|
@@ -2295,9 +2295,9 @@ Please continue the conversation from where we left it off without asking the us
|
|
|
2295
2295
|
|
|
2296
2296
|
`;continue}G+=U.length;for(let H of U){if(J+=` • ${H.name}`,H.description){let F=H.description.length>60?H.description.substring(0,57)+"...":H.description;J+=` - ${F}`}J+=`
|
|
2297
2297
|
`}J+=`
|
|
2298
|
-
`}J+=`**总计:** ${G} 个工具可用`,$.sendMessage(J)}var m_,Zq;var Xq=A(()=>{
|
|
2299
|
-
`).filter((K)=>K.trim());if(Q.length===0)throw Error("空的 JSONL 文件");let J=JSON.parse(Q[0]),G=JSON.parse(Q[Q.length-1]),q=Q.some((K)=>{try{let W=JSON.parse(K);return W.type==="tool_result"&&W.toolResult?.error}catch{return!1}});return{sessionId:Z,projectPath:X,gitBranch:J.gitBranch,messageCount:Q.length,firstMessageTime:J.timestamp,lastMessageTime:G.timestamp,hasErrors:q,filePath:$}}static async loadSession($,Z){try{if(Z){let Q=this.getSessionFilePath(Z,$);return await this.loadSessionFromFile(Q)}let Y=(await this.listSessions()).find((Q)=>Q.sessionId===$);if(!Y)throw Error(`未找到会话: ${$}`);return await this.loadSessionFromFile(Y.filePath)}catch(X){throw
|
|
2300
|
-
`).filter((Q)=>Q.trim()).map((Q)=>JSON.parse(Q));return this.convertJSONLToMessages(Y)}static convertJSONLToMessages($){let Z=[],X=-1;for(let Q=$.length-1;Q>=0;Q--)if($[Q].subtype==="compact_boundary"){X=Q,
|
|
2298
|
+
`}J+=`**总计:** ${G} 个工具可用`,$.sendMessage(J)}var m_,Zq;var Xq=A(()=>{s2();T4();C0();y1();m_={name:"mcp",description:"Display MCP server status and available tools",fullDescription:"显示 MCP 服务器状态、连接信息和可用工具列表",usage:"/mcp [server-name | tools]",category:"MCP",examples:["/mcp - 显示所有服务器概览","/mcp chrome-devtools - 显示特定服务器详情","/mcp tools - 显示所有可用工具"],async handler($,Z){let X=m0(Z);try{if(console.log("[MCP Command] Received args:",$),$.length===0)return await f_(X),{success:!0,message:"MCP 服务器概览已显示"};let Y=$[0];if(console.log("[MCP Command] Subcommand:",Y),Y==="tools")return await d_(X),{success:!0,message:"MCP 工具列表已显示"};return await x_(X,Y),{success:!0,message:`服务器 "${Y}" 详情已显示`}}catch(Y){return{success:!1,error:`显示 MCP 信息失败: ${Y instanceof Error?Y.message:"未知错误"}`}}}},Zq=m_});async function u_($,Z){return{success:!0,message:"show_permissions_editor",data:{action:"show_permissions_editor"}}}var g_,y6;var t5=A(()=>{g_={name:"permissions",description:"管理项目的本地权限规则",fullDescription:"打开权限管理器,管理 .blade/settings.local.json 中的权限规则",usage:"/permissions",aliases:["perm"],category:"ui",handler:u_},y6=g_});import{readdir as Yq,readFile as Qq}from"node:fs/promises";import*as v6 from"node:path";class m1{static async listSessions(){let $=[],Z=v6.join(X4(),"projects");try{let X=await Yq(Z,{withFileTypes:!0});for(let Y of X){if(!Y.isDirectory())continue;let Q=v6.join(Z,Y.name),J=vQ(Y.name),q=(await Yq(Q)).filter((K)=>K.endsWith(".jsonl"));for(let K of q){let W=v6.join(Q,K),U=K.replace(".jsonl","");try{let H=await this.extractMetadata(W,U,J);$.push(H)}catch(H){U4.warn(`[SessionService] 跳过损坏的会话文件: ${W}`,H)}}}return $.sort((Y,Q)=>new Date(Q.lastMessageTime).getTime()-new Date(Y.lastMessageTime).getTime()),$}catch(X){return U4.error("[SessionService] 列出会话失败:",X),[]}}static async extractMetadata($,Z,X){let Q=(await Qq($,"utf-8")).trim().split(`
|
|
2299
|
+
`).filter((K)=>K.trim());if(Q.length===0)throw Error("空的 JSONL 文件");let J=JSON.parse(Q[0]),G=JSON.parse(Q[Q.length-1]),q=Q.some((K)=>{try{let W=JSON.parse(K);return W.type==="tool_result"&&W.toolResult?.error}catch{return!1}});return{sessionId:Z,projectPath:X,gitBranch:J.gitBranch,messageCount:Q.length,firstMessageTime:J.timestamp,lastMessageTime:G.timestamp,hasErrors:q,filePath:$}}static async loadSession($,Z){try{if(Z){let Q=this.getSessionFilePath(Z,$);return await this.loadSessionFromFile(Q)}let Y=(await this.listSessions()).find((Q)=>Q.sessionId===$);if(!Y)throw Error(`未找到会话: ${$}`);return await this.loadSessionFromFile(Y.filePath)}catch(X){throw U4.error(`[SessionService] 加载会话失败 (${$}):`,X),X}}static async loadSessionFromFile($){let Y=(await Qq($,"utf-8")).trim().split(`
|
|
2300
|
+
`).filter((Q)=>Q.trim()).map((Q)=>JSON.parse(Q));return this.convertJSONLToMessages(Y)}static convertJSONLToMessages($){let Z=[],X=-1;for(let Q=$.length-1;Q>=0;Q--)if($[Q].subtype==="compact_boundary"){X=Q,U4.debug(`[SessionService] 检测到压缩边界 at index ${Q}`);break}let Y=X>=0?X:0;for(let Q=Y;Q<$.length;Q++){let J=$[Q];if(J.subtype==="compact_boundary"){U4.debug("[SessionService] 跳过 compact_boundary 消息");continue}switch(J.type){case"user":case"assistant":case"system":{let G={role:J.message.role,content:typeof J.message.content==="string"?J.message.content:JSON.stringify(J.message.content)};if(J.isCompactSummary)U4.debug("[SessionService] 加载压缩总结消息");Z.push(G);break}case"tool_result":if(J.toolResult){let G=J.toolResult.error?`Error: ${J.toolResult.error}`:typeof J.toolResult.output==="string"?J.toolResult.output:JSON.stringify(J.toolResult.output);Z.push({role:"tool",content:G,tool_call_id:J.toolResult.id,name:J.tool?.name})}break;case"tool_use":break;default:break}}if(X>=0)U4.debug(`[SessionService] 会话已压缩,跳过前 ${X} 条历史,加载 ${Z.length} 条消息`);return Z}static getSessionFilePath($,Z){return H1($,Z)}}var U4;var E6=A(()=>{$3();B0();U4=i("Service")});var c_,Jq;var Gq=A(()=>{E6();C0();y1();c_={name:"resume",description:"Resume a conversation",fullDescription:"恢复历史会话。可以指定 sessionId 直接恢复,或不带参数打开会话选择器",usage:"/resume [sessionId]",aliases:["r"],category:"Session",examples:["/resume - 打开会话选择器","/resume abc123xyz - 直接恢复指定的会话"],async handler($,Z){let X=m0(Z),Y=z0().restoreSession;if($.length>0){let Q=$[0];try{let J=await m1.loadSession(Q);if(J.length===0)return X.sendMessage(`❌ 会话 \`${Q}\` 为空或无法加载`),{success:!1,error:"会话为空"};let G=J.filter((q)=>q.role!=="tool").map((q,K)=>({id:`restored-${Date.now()}-${K}`,role:q.role,content:typeof q.content==="string"?q.content:JSON.stringify(q.content),timestamp:Date.now()-(J.length-K)*1000}));return Y(Q,G),X.sendMessage(`✅ 已恢复会话 \`${Q}\`
|
|
2301
2301
|
|
|
2302
2302
|
共 ${G.length} 条消息已加载,可以继续对话`),{success:!0,message:"session_restored",data:{sessionId:Q,messageCount:G.length}}}catch(J){let G=J instanceof Error?J.message:"未知错误";return X.sendMessage(`❌ 加载会话失败: ${G}`),{success:!1,error:`加载会话失败: ${G}`}}}try{let Q=await m1.listSessions();if(Q.length===0)return X.sendMessage("\uD83D\uDCED **没有找到历史会话**\n\n开始一次对话后,会话历史将自动保存到 `~/.blade/projects/`"),{success:!0,message:"没有可用会话"};return{success:!0,message:"show_session_selector",data:{sessions:Q}}}catch(Q){let J=Q instanceof Error?Q.message:"未知错误";return X.sendMessage(`❌ 获取会话列表失败: ${J}`),{success:!1,error:`获取会话列表失败: ${J}`}}}},Jq=c_});import qq from"node:fs/promises";import Kq from"node:path";var l_,i_,a_,r_,n_,o_,Wq;var Uq=A(()=>{c3();C0();j8();oG();tG();B6();Xq();t5();Gq();y1();l_={name:"help",description:"Show all available slash commands",fullDescription:"显示所有可用的 slash commands 及其使用方法",usage:"/help",aliases:["h"],async handler($,Z){let X=m0(Z),Y=`\uD83D\uDD27 **可用的 Slash Commands:**
|
|
2303
2303
|
|
|
@@ -2326,7 +2326,7 @@ Please continue the conversation from where we left it off without asking the us
|
|
|
2326
2326
|
- 在命令前加上 \`/\` 即可执行 slash command
|
|
2327
2327
|
- 普通消息会发送给 AI 助手处理
|
|
2328
2328
|
- 按 Ctrl+C 退出程序
|
|
2329
|
-
- 按 Ctrl+L 快速清屏`,X.sendMessage(Y),{success:!0,message:"帮助信息已显示"}}},i_={name:"clear",description:"Clear conversation history and free up context",fullDescription:"清除屏幕内容和对话历史",usage:"/clear",aliases:["cls"],async handler($,Z){return{success:!0,message:"clear_screen"}}},a_={name:"version",description:"Show Blade Code version information",fullDescription:"显示 Blade Code 版本信息和构建详情",usage:"/version",aliases:["v"],async handler($,Z){let X=m0(Z),Q=`\uD83D\uDDE1️ **Blade Code v${
|
|
2329
|
+
- 按 Ctrl+L 快速清屏`,X.sendMessage(Y),{success:!0,message:"帮助信息已显示"}}},i_={name:"clear",description:"Clear conversation history and free up context",fullDescription:"清除屏幕内容和对话历史",usage:"/clear",aliases:["cls"],async handler($,Z){return{success:!0,message:"clear_screen"}}},a_={name:"version",description:"Show Blade Code version information",fullDescription:"显示 Blade Code 版本信息和构建详情",usage:"/version",aliases:["v"],async handler($,Z){let X=m0(Z),Q=`\uD83D\uDDE1️ **Blade Code v${M4()}**
|
|
2330
2330
|
|
|
2331
2331
|
**构建信息:**
|
|
2332
2332
|
- Node.js: ${process.version}
|
|
@@ -2351,7 +2351,7 @@ Please continue the conversation from where we left it off without asking the us
|
|
|
2351
2351
|
- 工作目录: ${process.cwd()}
|
|
2352
2352
|
- Node.js: ${process.version}
|
|
2353
2353
|
|
|
2354
|
-
${!J?"\n\uD83D\uDCA1 **建议:** 运行 `/init` 命令来创建项目配置文件":""}`;return X.sendMessage(W),{success:!0,message:"状态信息已显示"}}catch(Q){return{success:!1,error:`获取状态信息失败: ${Q instanceof Error?Q.message:"未知错误"}`}}}},n_={name:"exit",description:"Exit the REPL",fullDescription:"退出 Blade Code 命令行界面",usage:"/exit",aliases:["quit","q"],async handler($,Z){return{success:!0,message:"exit_application"}}},o_={name:"context",description:"Visualize current context usage as a colored grid",fullDescription:"可视化显示当前上下文使用情况",usage:"/context",async handler($,Z){let X=m0(Z),Y=H$(),Q=
|
|
2354
|
+
${!J?"\n\uD83D\uDCA1 **建议:** 运行 `/init` 命令来创建项目配置文件":""}`;return X.sendMessage(W),{success:!0,message:"状态信息已显示"}}catch(Q){return{success:!1,error:`获取状态信息失败: ${Q instanceof Error?Q.message:"未知错误"}`}}}},n_={name:"exit",description:"Exit the REPL",fullDescription:"退出 Blade Code 命令行界面",usage:"/exit",aliases:["quit","q"],async handler($,Z){return{success:!0,message:"exit_application"}}},o_={name:"context",description:"Visualize current context usage as a colored grid",fullDescription:"可视化显示当前上下文使用情况",usage:"/context",async handler($,Z){let X=m0(Z),Y=H$(),Q=P4(),G=K0().session.messages||[],q=G.map((B)=>({role:B.role,content:B.content})),K=Q?.model||"gpt-4",W=q.length>0?Z2.countTokens(q,K):0,U=Q?.maxContextTokens??Y?.maxContextTokens??128000,H=U>0?(W/U*100).toFixed(1):"0",F=(100-parseFloat(H)).toFixed(1),O=parseFloat(H),z;if(O<50)z="\uD83D\uDFE2 正常";else if(O<80)z="\uD83D\uDFE1 中等";else z="\uD83D\uDD34 高负载";let _=`\uD83D\uDCCA **上下文使用情况**
|
|
2355
2355
|
|
|
2356
2356
|
**当前会话:**
|
|
2357
2357
|
- 消息数量: ${G.length}
|
|
@@ -2443,9 +2443,9 @@ ${X}
|
|
|
2443
2443
|
1. ${Y?"严格模仿历史提交的语言和格式风格":"使用英文,遵循 Conventional Commits 格式(feat:, fix:, docs:, refactor:, chore: 等)"}
|
|
2444
2444
|
2. 第一行简明扼要,不超过 72 字符
|
|
2445
2445
|
3. 如有必要,可添加空行后的详细说明
|
|
2446
|
-
4. 只输出 commit message 内容,不要其他解释或代码块标记`}var $B,wq;var Nq=A(()=>{
|
|
2446
|
+
4. 只输出 commit message 内容,不要其他解释或代码块标记`}var $B,wq;var Nq=A(()=>{Q2();C0();$Z();y1();$B={name:"git",description:"Git 仓库查询和 AI 辅助",usage:"/git [status|log|diff|review|commit|pre-commit]",aliases:["g"],examples:["/git","/git status","/git log 10","/git review","/git commit","/git pre-commit"],async handler($,Z){let{cwd:X}=Z,Y=$[0]?.toLowerCase();if(!await q3(X))return{success:!1,error:"❌ 当前目录不在 Git 仓库中"};try{switch(Y){case"status":case"s":return Bq(Z);case"log":case"l":return ZB(Z,$[1]);case"diff":case"d":return XB(Z);case"review":case"r":return YB(Z);case"commit":case"c":return JB(Z);case"pre-commit":case"pc":return QB(Z);default:return Bq(Z)}}catch(Q){return{success:!1,error:`Git 命令失败: ${Q instanceof Error?Q.message:"未知错误"}`}}}};wq=$B});function qB($){let Z=$.isEnabled(),X=$.getConfig(),Y={};for(let J of Object.values(C1)){let G=X[J];if(G&&Array.isArray(G)){let q=G.reduce((K,W)=>K+(W.hooks?.length||0),0);if(q>0)Y[J]=q}}let Q=["## Hooks 状态","",`**状态**: ${Z?"✅ 启用":"⏸️ 禁用"}`,""];if(Object.keys(Y).length>0){Q.push("**已配置的 Hooks**:"),Q.push("");for(let[J,G]of Object.entries(Y))Q.push(`- ${J}: ${G} 个 hook`)}else Q.push("*没有配置任何 hooks*");return Q.push(""),Q.push("---"),Q.push("使用 `/hooks list` 查看详细配置"),Q.push("使用 `/hooks enable` 或 `/hooks disable` 切换状态"),z0().addAssistantMessage(Q.join(`
|
|
2447
2447
|
`)),{success:!0,message:"Hooks status displayed"}}function KB($){let Z=$.getConfig(),X=["## Hooks 配置详情",""],Y=!1;for(let Q of Object.values(C1)){let J=Z[Q];if(!J||!Array.isArray(J)||J.length===0)continue;Y=!0,X.push(`### ${Q}`),X.push("");for(let G=0;G<J.length;G++){let q=J[G],K=q.name||`Matcher ${G+1}`,W=q.matcher,U="所有";if(W){let H=[];if(W.tools){let F=Array.isArray(W.tools)?W.tools.join(", "):W.tools;H.push(`工具: ${F}`)}if(W.paths){let F=Array.isArray(W.paths)?W.paths.join(", "):W.paths;H.push(`路径: ${F}`)}if(W.commands){let F=Array.isArray(W.commands)?W.commands.join(", "):W.commands;H.push(`命令: ${F}`)}if(H.length>0)U=H.join("; ")}X.push(`**${K}** (匹配: ${U})`);for(let H of q.hooks||[])if(H.type==="command")X.push(` - \`${H.command}\``);else if(H.type==="prompt"){let F=H.prompt.slice(0,50)+(H.prompt.length>50?"...":"");X.push(` - [prompt] ${F}`)}X.push("")}}if(!Y)X.push("*没有配置任何 hooks*"),X.push(""),X.push("在 `.blade/settings.local.json` 或 `~/.blade/settings.json` 中配置 hooks。");return z0().addAssistantMessage(X.join(`
|
|
2448
|
-
`)),{success:!0,message:"Hooks config listed"}}var GB,bq;var Aq=A(()=>{r$();
|
|
2448
|
+
`)),{success:!0,message:"Hooks config listed"}}var GB,bq;var Aq=A(()=>{r$();C4();C0();GB={name:"hooks",description:"Manage hook configurations for tool events",fullDescription:`管理 Hook 配置,查看当前启用的 hooks 和执行统计。
|
|
2449
2449
|
|
|
2450
2450
|
子命令:
|
|
2451
2451
|
/hooks - 打开交互式 hooks 管理界面(添加新 hook)
|
|
@@ -2500,7 +2500,7 @@ ${X}
|
|
|
2500
2500
|
... (+${Y.length-Q} line(s))`}case"Edit":{let X=Z.metadata?.diff_snippet;if(X){let Y=X.split(`
|
|
2501
2501
|
`),Q=6;if(Y.length>6)return Y.slice(0,6).join(`
|
|
2502
2502
|
`)+`
|
|
2503
|
-
... (+${Y.length-6} line(s))`;return X}return null}default:{let X=Z.metadata?.detail;return typeof X==="string"?X:null}}}import{promises as F3}from"fs";import*as Tq from"path";var Q8,VB,Sq;var Cq=A(()=>{
|
|
2503
|
+
... (+${Y.length-6} line(s))`;return X}return null}default:{let X=Z.metadata?.detail;return typeof X==="string"?X:null}}}import{promises as F3}from"fs";import*as Tq from"path";var Q8,VB,Sq;var Cq=A(()=>{Q2();B0();C0();y1();Q8=i("Agent"),VB={name:"init",description:"分析当前项目并生成 BLADE.md 配置文件",usage:"/init",async handler($,Z){try{let{cwd:X,signal:Y}=Z,Q=m0(Z),J=(O)=>{Q.sendMessage(`${O}`)},G=K0().session.sessionId,q=Tq.join(X,"BLADE.md"),K=!1,W=!1;try{if(K=(await F3.stat(q)).isFile(),K)W=(await F3.readFile(q,"utf-8")).trim().length===0}catch{K=!1}if(K&&!W){Q.sendMessage("⚠️ BLADE.md 已存在。"),Q.sendMessage("\uD83D\uDCA1 正在分析现有文件并提供改进建议...");let O=await z$.create();if(Y?.aborted)return{success:!1,message:"操作已取消"};let z=`Please analyze the existing BLADE.md file and provide improvement suggestions.
|
|
2504
2504
|
|
|
2505
2505
|
**Important**:
|
|
2506
2506
|
- After each step, briefly describe what you found before proceeding
|
|
@@ -2633,7 +2633,7 @@ ${X}
|
|
|
2633
2633
|
|
|
2634
2634
|
`+"使用 `--plugin-dir <path>` 参数加载插件,或将插件放置在:\n"+"- `~/.blade/plugins/` - 用户级插件\n"+"- `.blade/plugins/` - 项目级插件"),{success:!0,message:"No plugins loaded"};let X=["## 已加载的插件",""],Y=$.getBySource();if(Y.cli.length>0){X.push("### CLI 指定");for(let Q of Y.cli){let J=Q.status==="inactive"?" ⏸️":" ✅";X.push(`- **${Q.manifest.name}** v${Q.manifest.version}${J}`),X.push(` ${Q.manifest.description}`)}X.push("")}if(Y.project.length>0){X.push("### 项目级");for(let Q of Y.project){let J=Q.status==="inactive"?" ⏸️":" ✅";X.push(`- **${Q.manifest.name}** v${Q.manifest.version}${J}`),X.push(` ${Q.manifest.description}`)}X.push("")}if(Y.user.length>0){X.push("### 用户级");for(let Q of Y.user){let J=Q.status==="inactive"?" ⏸️":" ✅";X.push(`- **${Q.manifest.name}** v${Q.manifest.version}${J}`),X.push(` ${Q.manifest.description}`)}}return z0().addAssistantMessage(X.join(`
|
|
2635
2635
|
`)),{success:!0,message:"Plugins listed"}}function vB($,Z){if(!Z)return z0().addAssistantMessage("请指定插件名称: `/plugins info <name>`"),{success:!1,error:"Plugin name required"};let X=$.get(Z);if(!X)return z0().addAssistantMessage(`未找到插件: ${Z}`),{success:!1,error:`Plugin not found: ${Z}`};let Y=[`## ${X.manifest.name}`,"",`**版本**: ${X.manifest.version}`,`**描述**: ${X.manifest.description}`,`**状态**: ${X.status==="active"?"✅ 启用":"⏸️ 禁用"}`,`**来源**: ${kB(X.source)}`,`**路径**: \`${X.basePath}\``,""];if(X.manifest.author)Y.push(`**作者**: ${X.manifest.author.name}`);if(X.manifest.license)Y.push(`**许可证**: ${X.manifest.license}`);if(X.manifest.repository)Y.push(`**仓库**: ${X.manifest.repository}`);if(X.commands.length>0){Y.push(""),Y.push(`### 命令 (${X.commands.length})`);for(let Q of X.commands){let J=Q.config.argumentHint?` ${Q.config.argumentHint}`:"",G=Q.config.description?` - ${Q.config.description}`:"";Y.push(`- \`/${Q.namespacedName}${J}\`${G}`)}}if(X.skills.length>0){Y.push(""),Y.push(`### 技能 (${X.skills.length})`);for(let Q of X.skills)Y.push(`- \`${Q.namespacedName}\` - ${Q.metadata.description}`)}if(X.agents.length>0){Y.push(""),Y.push(`### 代理 (${X.agents.length})`);for(let Q of X.agents)Y.push(`- \`${Q.namespacedName}\` - ${Q.config.description}`)}if(X.mcpServers){let Q=Object.keys(X.mcpServers).length;Y.push(""),Y.push(`### MCP 服务器 (${Q})`);for(let J of Object.keys(X.mcpServers))Y.push(`- \`${J}\``)}if(X.hooks)Y.push(""),Y.push("### Hooks"),Y.push("插件已配置 hooks");return z0().addAssistantMessage(Y.join(`
|
|
2636
|
-
`)),{success:!0,message:"Plugin info displayed"}}function EB($,Z){if(!Z)return z0().addAssistantMessage("请指定插件名称: `/plugins enable <name>`"),{success:!1,error:"Plugin name required"};if($.enable(Z))return z0().addAssistantMessage(`✅ 已启用插件: ${Z}`),{success:!0,message:`Plugin ${Z} enabled`};if(!$.get(Z))return z0().addAssistantMessage(`未找到插件: ${Z}`),{success:!1,error:`Plugin not found: ${Z}`};return z0().addAssistantMessage(`插件 ${Z} 已经是启用状态`),{success:!0,message:`Plugin ${Z} already enabled`}}function PB($,Z){if(!Z)return z0().addAssistantMessage("请指定插件名称: `/plugins disable <name>`"),{success:!1,error:"Plugin name required"};if($.disable(Z))return z0().addAssistantMessage(`⏸️ 已禁用插件: ${Z}`),{success:!0,message:`Plugin ${Z} disabled`};if(!$.get(Z))return z0().addAssistantMessage(`未找到插件: ${Z}`),{success:!1,error:`Plugin not found: ${Z}`};return z0().addAssistantMessage(`插件 ${Z} 已经是禁用状态`),{success:!0,message:`Plugin ${Z} already disabled`}}async function TB($){I6(),await $.refresh(),await
|
|
2636
|
+
`)),{success:!0,message:"Plugin info displayed"}}function EB($,Z){if(!Z)return z0().addAssistantMessage("请指定插件名称: `/plugins enable <name>`"),{success:!1,error:"Plugin name required"};if($.enable(Z))return z0().addAssistantMessage(`✅ 已启用插件: ${Z}`),{success:!0,message:`Plugin ${Z} enabled`};if(!$.get(Z))return z0().addAssistantMessage(`未找到插件: ${Z}`),{success:!1,error:`Plugin not found: ${Z}`};return z0().addAssistantMessage(`插件 ${Z} 已经是启用状态`),{success:!0,message:`Plugin ${Z} already enabled`}}function PB($,Z){if(!Z)return z0().addAssistantMessage("请指定插件名称: `/plugins disable <name>`"),{success:!1,error:"Plugin name required"};if($.disable(Z))return z0().addAssistantMessage(`⏸️ 已禁用插件: ${Z}`),{success:!0,message:`Plugin ${Z} disabled`};if(!$.get(Z))return z0().addAssistantMessage(`未找到插件: ${Z}`),{success:!1,error:`Plugin not found: ${Z}`};return z0().addAssistantMessage(`插件 ${Z} 已经是禁用状态`),{success:!0,message:`Plugin ${Z} already disabled`}}async function TB($){I6(),await $.refresh(),await v2()}async function SB($){try{I6();let Z=await $.refresh(),X=await v2(),Y=["✅ 已刷新插件列表","",`- 加载了 ${Z.plugins.length} 个插件`,`- 集成了 ${X.totalCommands} 个命令, ${X.totalSkills} 个技能, ${X.totalAgents} 个代理`];if(Z.errors.length>0){Y.push(`- ${Z.errors.length} 个加载错误`),Y.push(""),Y.push("### 错误");for(let Q of Z.errors)Y.push(`- \`${Q.path}\`: ${Q.error}`)}if(X.errors.length>0){Y.push(""),Y.push("### 集成错误");for(let Q of X.errors)Y.push(`- ${Q}`)}return z0().addAssistantMessage(Y.join(`
|
|
2637
2637
|
`)),{success:!0,message:"Plugins refreshed"}}catch(Z){let X=Z instanceof Error?Z.message:String(Z);return z0().addAssistantMessage(`❌ 刷新失败: ${X}`),{success:!1,error:X}}}function CB($){let Z=$.getStats(),X=["## 插件统计","","| 指标 | 数量 |","|------|------|",`| 总插件数 | ${Z.total} |`,`| 启用 | ${Z.active} |`,`| 禁用 | ${Z.inactive} |`,`| 命令 | ${Z.commands} |`,`| 技能 | ${Z.skills} |`,`| 代理 | ${Z.agents} |`];return z0().addAssistantMessage(X.join(`
|
|
2638
2638
|
`)),{success:!0,message:"Stats displayed"}}function kB($){switch($){case"cli":return"CLI 参数";case"project":return"项目级";case"user":return"用户级";default:return $}}async function fB($){if(!$)return z0().addAssistantMessage("请指定插件 URL: `/plugins install <url>`\n\n"+`支持的格式:
|
|
2639
2639
|
`+"- GitHub 简写: `user/repo`\n"+"- 完整 URL: `https://github.com/user/repo`"),{success:!1,error:"Plugin URL required"};z0().addAssistantMessage(`正在安装插件: ${$}...`);let X=await J3().install($);if(X.success){let Y=["✅ 插件安装成功!","",`**名称**: ${X.pluginName}`,`**路径**: \`${X.pluginPath}\``];if(X.manifest)Y.push(`**版本**: ${X.manifest.version}`),Y.push(`**描述**: ${X.manifest.description}`);return Y.push(""),Y.push("使用 `/plugins refresh` 加载新安装的插件。"),z0().addAssistantMessage(Y.join(`
|
|
@@ -2653,13 +2653,13 @@ ${X}
|
|
|
2653
2653
|
/plugins disable <name> - 禁用插件
|
|
2654
2654
|
/plugins refresh - 刷新插件列表
|
|
2655
2655
|
/plugins stats - 显示插件统计信息`,usage:"/plugins [list|info|install|uninstall|update|enable|disable|refresh|stats] [name/url]",category:"system",examples:["/plugins","/plugins list","/plugins info my-plugin","/plugins install user/repo","/plugins install https://github.com/user/repo","/plugins uninstall my-plugin","/plugins update my-plugin","/plugins enable my-plugin","/plugins disable my-plugin","/plugins refresh","/plugins stats"],handler:async($,Z)=>{let X=$[0]?.toLowerCase()||"",Y=a$();switch(X){case"":return await TB(Y),{success:!0,message:"show_plugins_manager",data:{action:"show_plugins_manager"}};case"list":case"ls":return yB(Y);case"info":return vB(Y,$[1]);case"install":case"add":return fB($[1]);case"uninstall":case"remove":case"rm":return hB($[1]);case"update":case"upgrade":return xB($[1]);case"enable":return EB(Y,$[1]);case"disable":return PB(Y,$[1]);case"refresh":return SB(Y);case"stats":return CB(Y);default:return z0().addAssistantMessage(`未知子命令: ${X}
|
|
2656
|
-
使用 /plugins 查看帮助`),{success:!1,error:`Unknown subcommand: ${X}`}}}};mq=IB});var pB,gq;var cq=A(()=>{
|
|
2656
|
+
使用 /plugins 查看帮助`),{success:!1,error:`Unknown subcommand: ${X}`}}}};mq=IB});var pB,gq;var cq=A(()=>{X2();C0();pB={name:"skills",description:"查看所有可用的 Skills",fullDescription:"显示所有已发现的 Skills 及其详细信息,包括名称、描述、来源和允许的工具。",usage:"/skills",category:"system",examples:["/skills"],handler:async($,Z)=>{try{return await b$().refresh(),{success:!0,message:"show_skills_manager",data:{action:"show_skills_manager"}}}catch(X){let Y=`获取 Skills 失败: ${X instanceof Error?X.message:"未知错误"}`;return z0().addAssistantMessage(Y),{success:!1,error:Y}}}},gq=pB});function C6($){if($<1000)return`${$}ms`;let Z=Math.floor($/1000);if(Z<60)return`${Z}s`;let X=Math.floor(Z/60);if(X<60)return`${X}m ${Z%60}s`;return`${Math.floor(X/60)}h ${X%60}m`}function lq($){switch($){case"running":return"⏳";case"completed":case"exited":return"✅";case"failed":case"error":return"❌";case"killed":case"cancelled":return"✂️";default:return"❓"}}function iq($,Z){if($.length<=Z)return $;return $.slice(0,Z-3)+"..."}async function dB($,Z){let X=m0(Z),Y=$[0],Q=T$.getInstance(),J=$1.getInstance();if(Y==="clean"){let F=J.cleanupExpiredSessions(0);return X.sendMessage(`\uD83E\uDDF9 已清理 ${F} 个已完成的 Agent 会话`),{success:!0,message:`Cleaned ${F} agent sessions`}}let G=[`\uD83D\uDCCB **后台任务列表**
|
|
2657
2657
|
`],q=Q.processes,K=Array.from(q?.values()||[]);if(K.length>0){G.push(`### \uD83D\uDC1A Shells
|
|
2658
2658
|
`),G.push("| ID | 状态 | 命令 | PID | 运行时间 |"),G.push("|:---|:-----|:-----|:----|:---------|");for(let F of K){let O=F.endTime?C6(F.endTime-F.startTime):C6(Date.now()-F.startTime),z=lq(F.status);G.push(`| \`${F.id.slice(0,12)}...\` | ${z} ${F.status} | \`${iq(F.command,30)}\` | ${F.pid||"-"} | ${O} |`)}G.push("")}let W=J.listAll();if(W.length>0){G.push(`### \uD83E\uDD16 Agents
|
|
2659
2659
|
`),G.push("| ID | 状态 | 类型 | 描述 | 运行时间 |"),G.push("|:---|:-----|:-----|:-----|:---------|");for(let F of W){let O=F.completedAt?C6(F.completedAt-F.createdAt):C6(Date.now()-F.createdAt),z=lq(F.status);G.push(`| \`${F.id.slice(0,12)}...\` | ${z} ${F.status} | ${F.subagentType} | ${iq(F.description,25)} | ${O} |`)}G.push("")}let U=K.filter((F)=>F.status==="running").length,H=J.getRunningCount();if(K.length===0&&W.length===0)G.push(`*暂无后台任务*
|
|
2660
2660
|
`);else G.push(`**统计**: ${K.length} shells (${U} 运行中), ${W.length} agents (${H} 运行中)`);return G.push(`
|
|
2661
2661
|
---`),G.push("\uD83D\uDCA1 **命令**:"),G.push("- `/tasks` - 列出所有后台任务"),G.push("- `/tasks clean` - 清理已完成的 Agent 会话"),X.sendMessage(G.join(`
|
|
2662
|
-
`)),{success:!0,message:`Listed ${K.length} shells and ${W.length} agents`}}var mB,aq;var rq=A(()=>{L6();
|
|
2662
|
+
`)),{success:!0,message:`Listed ${K.length} shells and ${W.length} agents`}}var mB,aq;var rq=A(()=>{L6();i4();y1();mB={name:"tasks",description:"列出所有后台任务(shells 和 agents)",fullDescription:`查看和管理后台运行的任务。
|
|
2663
2663
|
|
|
2664
2664
|
**功能**:
|
|
2665
2665
|
- 列出所有后台 shell 进程
|
|
@@ -2670,46 +2670,46 @@ ${X}
|
|
|
2670
2670
|
- \`/tasks\` - 显示所有后台任务
|
|
2671
2671
|
- \`/tasks clean\` - 清理已完成的 agent 会话`,usage:"/tasks [clean]",category:"system",examples:["/tasks","/tasks clean"],handler:dB},aq=mB});async function uB($,Z){return{success:!0,message:"show_theme_selector",data:{action:"show_theme_selector"}}}var gB,nq;var oq=A(()=>{gB={name:"theme",description:"打开交互式主题选择器",aliases:["themes","style"],usage:"/theme",examples:["/theme"],category:"ui",handler:uB},nq=gB});import cB from"fuse.js";function J8($){return $.trim().startsWith("/")}function lB($){let Z=$.trim();if(!Z.startsWith("/"))throw Error("不是有效的 slash command");let X=Z.slice(1).split(/\s+/),Y=X[0]||"",Q=X.slice(1);return{command:Y,args:Q}}function iB($){if(O3[$])return O3[$];for(let Z of Object.values(O3))if(Z.aliases?.includes($))return Z;return}function sq($){let Z=$.argumentHint?`/${$.name} ${$.argumentHint}`:`/${$.name}`;return{name:$.name,description:$.description,fullDescription:`[Skill] ${$.description}${$.whenToUse?`
|
|
2672
2672
|
|
|
2673
|
-
**When to use:** ${$.whenToUse}`:""}`,usage:Z,category:"skill",examples:[Z],handler:async(X,Y)=>{return{success:!0,message:`Invoking skill: ${$.name}`,data:{action:"invoke_skill",skillName:$.name,skillArgs:X.join(" ")}}}}}function aB($){return b$().getUserInvocableSkills().find((Y)=>Y.name===$)}async function rB(){await
|
|
2674
|
-
使用 /help 查看可用命令`}}catch(X){return{success:!1,error:`命令执行失败: ${X instanceof Error?X.message:"未知错误"}`}}}function eq(){let $=Object.values(O3),X=B$.getInstance().getAllCommands().map((q)=>({name:q.name,description:q.config.description||q.content.slice(0,50),usage:q.config.argumentHint?`/${q.name} ${q.config.argumentHint}`:`/${q.name}`,category:"custom",handler:async()=>({success:!0})})),Q=a$().getAllCommands().map((q)=>({name:q.namespacedName,description:q.config.description||q.content.slice(0,50),usage:q.config.argumentHint?`/${q.namespacedName} ${q.config.argumentHint}`:`/${q.namespacedName}`,category:"plugin",handler:async()=>({success:!0})})),G=b$().getUserInvocableSkills().map(sq);return[...$,...X,...Q,...G]}function $K($){let Z=($.startsWith("/")?$.slice(1):$).trim(),X=Object.values(O3).map((O)=>({name:O.name,description:O.description,aliases:O.aliases||[],label:void 0,argumentHint:void 0,isCustom:!1,isSkill:!1,isPlugin:!1})),Y=B$.getInstance(),Q=Y.getAllCommands().map((O)=>({name:O.name,description:O.config.description||O.content.slice(0,50),aliases:[],label:Y.getCommandLabel(O),argumentHint:O.config.argumentHint,isCustom:!0,isSkill:!1,isPlugin:!1})),G=a$().getAllCommands().map((O)=>({name:O.namespacedName,description:O.config.description||O.content.slice(0,50),aliases:[O.originalName],label:`(plugin: ${O.pluginName})`,argumentHint:O.config.argumentHint,isCustom:!1,isSkill:!1,isPlugin:!0})),K=b$().getUserInvocableSkills().map((O)=>({name:O.name,description:O.description,aliases:[],label:"(skill)",argumentHint:O.argumentHint,isCustom:!1,isSkill:!0,isPlugin:!1})),W=[...X,...Q,...G,...K];if(!Z)return W.map((O)=>({command:`/${O.name}`,description:O.label?`${O.description} ${O.label}`:O.description,argumentHint:O.argumentHint,matchScore:50}));return new cB(W,{keys:[{name:"name",weight:3},{name:"aliases",weight:2.5},{name:"description",weight:0.5}],threshold:0.4,includeScore:!0,ignoreLocation:!0,minMatchCharLength:1}).search(Z).map((O)=>{let z=O.score??1,_=Math.round((1-z)*100),B=O.item;return{command:`/${B.name}`,description:B.label?`${B.description} ${B.label}`:B.description,argumentHint:B.argumentHint,matchScore:_}}).filter((O)=>(O.matchScore||0)>=40)}var O3;var q8=A(()=>{X8();
|
|
2673
|
+
**When to use:** ${$.whenToUse}`:""}`,usage:Z,category:"skill",examples:[Z],handler:async(X,Y)=>{return{success:!0,message:`Invoking skill: ${$.name}`,data:{action:"invoke_skill",skillName:$.name,skillArgs:X.join(" ")}}}}}function aB($){return b$().getUserInvocableSkills().find((Y)=>Y.name===$)}async function rB(){await e2()}async function tq($){return await B$.getInstance().initialize($)}async function G8($,Z){try{let{command:X,args:Y}=lB($),Q=iB(X);if(Q)return await Q.handler(Y,Z);let J=B$.getInstance();if(J.hasCommand(X)){let W=J.getCommand(X);if(W){let U=Z.workspaceRoot||process.cwd(),H=await J.executeCommand(X,{args:Y,workspaceRoot:U,signal:Z.signal});if(H)return{success:!0,message:`执行自定义命令: /${X}`,data:{action:"invoke_custom_command",commandName:X,processedContent:H,config:W.config}}}}let q=a$().findCommand(X);if(q){let W=Z.workspaceRoot||process.cwd(),U=await J.executePluginCommand(q.namespacedName,{args:Y,workspaceRoot:W,signal:Z.signal});if(U)return{success:!0,message:`执行插件命令: /${q.namespacedName}`,data:{action:"invoke_plugin_command",commandName:q.namespacedName,pluginName:q.pluginName,processedContent:U,config:q.config}}}await rB();let K=aB(X);if(K)return await sq(K).handler(Y,Z);return{success:!1,error:`未知命令: /${X}
|
|
2674
|
+
使用 /help 查看可用命令`}}catch(X){return{success:!1,error:`命令执行失败: ${X instanceof Error?X.message:"未知错误"}`}}}function eq(){let $=Object.values(O3),X=B$.getInstance().getAllCommands().map((q)=>({name:q.name,description:q.config.description||q.content.slice(0,50),usage:q.config.argumentHint?`/${q.name} ${q.config.argumentHint}`:`/${q.name}`,category:"custom",handler:async()=>({success:!0})})),Q=a$().getAllCommands().map((q)=>({name:q.namespacedName,description:q.config.description||q.content.slice(0,50),usage:q.config.argumentHint?`/${q.namespacedName} ${q.config.argumentHint}`:`/${q.namespacedName}`,category:"plugin",handler:async()=>({success:!0})})),G=b$().getUserInvocableSkills().map(sq);return[...$,...X,...Q,...G]}function $K($){let Z=($.startsWith("/")?$.slice(1):$).trim(),X=Object.values(O3).map((O)=>({name:O.name,description:O.description,aliases:O.aliases||[],label:void 0,argumentHint:void 0,isCustom:!1,isSkill:!1,isPlugin:!1})),Y=B$.getInstance(),Q=Y.getAllCommands().map((O)=>({name:O.name,description:O.config.description||O.content.slice(0,50),aliases:[],label:Y.getCommandLabel(O),argumentHint:O.config.argumentHint,isCustom:!0,isSkill:!1,isPlugin:!1})),G=a$().getAllCommands().map((O)=>({name:O.namespacedName,description:O.config.description||O.content.slice(0,50),aliases:[O.originalName],label:`(plugin: ${O.pluginName})`,argumentHint:O.config.argumentHint,isCustom:!1,isSkill:!1,isPlugin:!0})),K=b$().getUserInvocableSkills().map((O)=>({name:O.name,description:O.description,aliases:[],label:"(skill)",argumentHint:O.argumentHint,isCustom:!1,isSkill:!0,isPlugin:!1})),W=[...X,...Q,...G,...K];if(!Z)return W.map((O)=>({command:`/${O.name}`,description:O.label?`${O.description} ${O.label}`:O.description,argumentHint:O.argumentHint,matchScore:50}));return new cB(W,{keys:[{name:"name",weight:3},{name:"aliases",weight:2.5},{name:"description",weight:0.5}],threshold:0.4,includeScore:!0,ignoreLocation:!0,minMatchCharLength:1}).search(Z).map((O)=>{let z=O.score??1,_=Math.round((1-z)*100),B=O.item;return{command:`/${B.name}`,description:B.label?`${B.description} ${B.label}`:B.description,argumentHint:B.argumentHint,matchScore:_}}).filter((O)=>(O.matchScore||0)>=40)}var O3;var q8=A(()=>{X8();X2();Uq();B6();Nq();Aq();vq();Cq();fq();xq();dq();t5();uq();cq();rq();oq();O3={...Wq,init:Sq,theme:nq,permissions:y6,model:pq,git:wq,ide:yq,skills:gq,hooks:bq,login:kq,logout:hq,tasks:aq,plugins:mq}});import{nanoid as Lb}from"nanoid";class sZ{id;cwd;connection;clientCapabilities;agent=null;pendingPrompt=null;messages=[];mode="default";sessionApprovals=new Set;constructor($,Z,X,Y){this.id=$;this.cwd=Z;this.connection=X;this.clientCapabilities=Y}async initialize(){Z$.debug(`[AcpSession ${this.id}] Initializing...`),O0.initializeSession(this.connection,this.id,this.clientCapabilities,this.cwd),Z$.debug(`[AcpSession ${this.id}] ACP service context initialized`),this.agent=await z$.create({}),Z$.debug(`[AcpSession ${this.id}] Agent created successfully`)}sendAvailableCommandsDelayed(){Z$.debug(`[AcpSession ${this.id}] Scheduling available commands update (500ms delay)`),setTimeout(()=>{this.sendAvailableCommands()},500)}async handleSlashCommand($,Z){try{Z$.debug(`[AcpSession ${this.id}] Executing slash command: ${$}`);let X={cwd:this.cwd,signal:Z,acp:{sendMessage:(J)=>{this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:J}})},sendToolStart:(J,G,q)=>{let K=`tool_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,W=this.mapToolKind(q);this.sendUpdate({sessionUpdate:"tool_call",toolCallId:K,status:"in_progress",title:`${J}`,content:[{type:"content",content:{type:"text",text:JSON.stringify(G,null,2)}}],kind:W})},sendToolResult:(J,G)=>{if(G.summary)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:G.summary}})}}},Y=await G8($,X),Q=Y.content||Y.message;if(Q)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:Q}});if(Y.error)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`❌ ${Y.error}`}});return{stopReason:Y.success?"end_turn":"cancelled"}}catch(X){return Z$.error(`[AcpSession ${this.id}] Slash command error:`,X),this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`❌ 命令执行失败: ${X instanceof Error?X.message:"未知错误"}`}}),{stopReason:"cancelled"}}}async sendAvailableCommands(){try{let $=eq(),Z=["model","permissions","theme","config","exit","ide"],Y=$.filter((Q)=>!Z.includes(Q.name)).map((Q)=>{let J;if(Q.usage){let G=Q.usage.replace(/^\/\w+\s*/,"").trim();if(G)J=G}if(Q.aliases?.length){let G=`Aliases: ${Q.aliases.join(", ")}`;J=J?`${J} | ${G}`:G}return{name:Q.name,description:Q.description,input:J?{hint:J}:void 0}});Z$.info(`[AcpSession ${this.id}] Sending available commands: ${JSON.stringify(Y.map((Q)=>Q.name))}`),this.sendUpdate({sessionUpdate:"available_commands_update",availableCommands:Y}),Z$.info(`[AcpSession ${this.id}] Sent ${Y.length} available commands`)}catch($){Z$.error(`[AcpSession ${this.id}] Failed to send available commands:`,$)}}async prompt($){O0.setCurrentSession(this.id),this.pendingPrompt?.abort();let Z=new AbortController;if(this.pendingPrompt=Z,!this.agent)throw Error("Session not initialized");try{let X=this.resolvePrompt($.prompt);if(Z$.debug(`[AcpSession ${this.id}] Received prompt: ${X.slice(0,100)}...`),J8(X))return await this.handleSlashCommand(X,Z.signal);let Y={sessionId:this.id,userId:"acp-user",workspaceRoot:this.cwd,messages:[...this.messages],signal:Z.signal,permissionMode:this.mapModeToPermissionMode(),confirmationHandler:{requestConfirmation:async(G)=>{return this.requestPermission(G)}}},Q={signal:Z.signal,onContent:(G)=>{this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:G}})},onThinking:(G)=>{this.sendUpdate({sessionUpdate:"agent_thought_chunk",content:{type:"text",text:G}})},onToolStart:(G,q)=>{let K="function"in G?G.function.name:G.type,W=this.mapToolKind(q);this.sendUpdate({sessionUpdate:"tool_call",toolCallId:G.id,status:"in_progress",title:`Executing ${K}`,content:[],kind:W})},onToolResult:async(G,q)=>{let K=[],W=q.metadata;if(W?.kind==="edit"&&W.file_path&&W.oldContent!==void 0&&W.newContent!==void 0)K.push({type:"diff",path:W.file_path,oldText:W.oldContent,newText:W.newContent});else if(q.displayContent){let F=typeof q.displayContent==="string"?q.displayContent:JSON.stringify(q.displayContent);K.push({type:"content",content:{type:"text",text:F}})}let U="function"in G?G.function.name:G.type,H=q.success?"completed":"failed";this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:G.id,status:H,content:K})},onTodoUpdate:(G)=>{this.sendPlanUpdate(G)}},J=await this.agent.chat(X,Y,Q);if(J)this.messages.push({role:"user",content:X}),this.messages.push({role:"assistant",content:J});if(Z.signal.aborted)return{stopReason:"cancelled"};return{stopReason:"end_turn"}}catch(X){if(Z.signal.aborted||X instanceof Error&&X.name==="AbortError")return{stopReason:"cancelled"};throw Z$.error(`[AcpSession ${this.id}] Prompt error:`,X),X}finally{if(this.pendingPrompt===Z)this.pendingPrompt=null}}cancel(){if(Z$.info(`[AcpSession ${this.id}] Cancel requested`),this.pendingPrompt)this.pendingPrompt.abort(),this.pendingPrompt=null,Z$.info(`[AcpSession ${this.id}] Cancelled successfully`);else Z$.warn(`[AcpSession ${this.id}] No pending prompt to cancel`)}async setMode($){let Z=["default","auto-edit","yolo","plan"];this.mode=Z.includes($)?$:"default",Z$.info(`[AcpSession ${this.id}] Mode set to: ${this.mode}`),this.sendUpdate({sessionUpdate:"current_mode_update",currentModeId:this.mode})}mapModeToPermissionMode(){switch(this.mode){case"yolo":return"yolo";case"auto-edit":return"autoEdit";case"plan":return"plan";case"default":default:return"default"}}shouldAutoApprove($){switch(this.mode){case"yolo":return!0;case"auto-edit":return $==="readonly"||$==="write";case"plan":return $==="readonly";case"default":default:return!1}}async setModel($){if(Z$.info(`[AcpSession ${this.id}] Model set to: ${$}`),this.agent)Z$.warn(`[AcpSession ${this.id}] Runtime model switching not yet implemented`)}async destroy(){if(this.cancel(),this.agent)await this.agent.destroy(),this.agent=null;O0.destroySession(this.id),Z$.debug(`[AcpSession ${this.id}] Destroyed`)}resolvePrompt($){let Z=[];for(let X of $)if(X.type==="text")Z.push(X.text);else if(X.type==="image")Z.push(`[Image: ${X.mimeType}]`);else if(X.type==="resource"){let Y=X.resource;if("text"in Y)Z.push(`<file path="${Y.uri}">
|
|
2675
2675
|
${Y.text}
|
|
2676
2676
|
</file>`)}else if(X.type==="resource_link")Z.push(`[Resource: ${X.uri}]`);return Z.join(`
|
|
2677
2677
|
`)}sendUpdate($){let Z={sessionId:this.id,update:$};this.connection.sessionUpdate(Z).catch((X)=>{Z$.warn(`[AcpSession ${this.id}] Failed to send update:`,X)})}sendPlanUpdate($){let Z=$.map((X)=>({content:X.content,priority:X.priority,status:X.status}));Z$.debug(`[AcpSession ${this.id}] Sending plan update with ${Z.length} entries`),this.sendUpdate({sessionUpdate:"plan",entries:Z})}async requestPermission($){let Z=$.kind?.toLowerCase()||"execute";if(this.shouldAutoApprove(Z))return Z$.debug(`[AcpSession ${this.id}] Auto-approving ${Z} in mode: ${this.mode}`),{approved:!0};if(this.mode==="plan"&&(Z==="write"||Z==="execute"))return Z$.debug(`[AcpSession ${this.id}] Rejecting ${Z} in plan mode`),{approved:!1,reason:"Write and execute operations are not allowed in Plan mode"};let X=`${Z}:${$.title||"unknown"}`;if(this.sessionApprovals.has(X))return Z$.debug(`[AcpSession ${this.id}] Using cached approval for: ${X}`),{approved:!0};try{let Y=Lb(),Q=[];if($.message)Q.push({type:"content",content:{type:"text",text:$.message}});if($.risks&&$.risks.length>0)Q.push({type:"content",content:{type:"text",text:`Risks:
|
|
2678
2678
|
- ${$.risks.join(`
|
|
2679
|
-
- `)}`}});let J=this.mapToolKind(Z),G={sessionId:this.id,options:[{optionId:"allow_once",name:"Allow once",kind:"allow_once"},{optionId:"allow_always",name:"Always allow",kind:"allow_always"},{optionId:"reject_once",name:"Deny once",kind:"reject_once"},{optionId:"reject_always",name:"Always deny",kind:"reject_always"}],toolCall:{toolCallId:Y,status:"pending",title:$.title||"Permission Required",content:Q,kind:J}},K=(await this.connection.requestPermission(G)).outcome;if(K.outcome==="cancelled")return{approved:!1,reason:"User cancelled the permission request"};let W=K.optionId,U=W==="allow_once"||W==="allow_always";if(W==="allow_always")this.sessionApprovals.add(X),Z$.debug(`[AcpSession ${this.id}] Cached approval for: ${X}`);return{approved:U,reason:U?void 0:"User denied the operation"}}catch(Y){return Z$.warn(`[AcpSession ${this.id}] Permission request failed:`,Y),{approved:!1,reason:"Permission request failed"}}}mapToolKind($){return{readonly:"read",write:"edit",execute:"execute",read:"read",edit:"edit",delete:"delete",move:"move",search:"search",think:"think",fetch:"fetch"}[$||""]||"other"}}var Z$;var IU=A(()=>{
|
|
2679
|
+
- `)}`}});let J=this.mapToolKind(Z),G={sessionId:this.id,options:[{optionId:"allow_once",name:"Allow once",kind:"allow_once"},{optionId:"allow_always",name:"Always allow",kind:"allow_always"},{optionId:"reject_once",name:"Deny once",kind:"reject_once"},{optionId:"reject_always",name:"Always deny",kind:"reject_always"}],toolCall:{toolCallId:Y,status:"pending",title:$.title||"Permission Required",content:Q,kind:J}},K=(await this.connection.requestPermission(G)).outcome;if(K.outcome==="cancelled")return{approved:!1,reason:"User cancelled the permission request"};let W=K.optionId,U=W==="allow_once"||W==="allow_always";if(W==="allow_always")this.sessionApprovals.add(X),Z$.debug(`[AcpSession ${this.id}] Cached approval for: ${X}`);return{approved:U,reason:U?void 0:"User denied the operation"}}catch(Y){return Z$.warn(`[AcpSession ${this.id}] Permission request failed:`,Y),{approved:!1,reason:"Permission request failed"}}}mapToolKind($){return{readonly:"read",write:"edit",execute:"execute",read:"read",edit:"edit",delete:"delete",move:"move",search:"search",think:"think",fetch:"fetch"}[$||""]||"other"}}var Z$;var IU=A(()=>{Q2();U$();B0();q8();g4();Z$=i("Agent")});import{PROTOCOL_VERSION as wb}from"@agentclientprotocol/sdk";import{nanoid as Nb}from"nanoid";class tZ{connection;sessions=new Map;clientCapabilities;constructor($){this.connection=$}async initialize($){return a1.info("[BladeAgent] Initializing ACP connection"),a1.debug(`[BladeAgent] Client capabilities: ${JSON.stringify($.clientCapabilities)}`),this.clientCapabilities=$.clientCapabilities,{protocolVersion:wb,agentCapabilities:{loadSession:!1,promptCapabilities:{image:!0,audio:!1,embeddedContext:!0},mcpCapabilities:{http:!0,sse:!0}}}}async authenticate($){return}async newSession($){let Z=Nb();a1.info(`[BladeAgent] Creating new session: ${Z}`),a1.debug(`[BladeAgent] Session cwd: ${$.cwd||process.cwd()}`);let X=new sZ(Z,$.cwd||process.cwd(),this.connection,this.clientCapabilities);await X.initialize(),this.sessions.set(Z,X),a1.info(`[BladeAgent] Session ${Z} created, scheduling available commands update`),X.sendAvailableCommandsDelayed();let Y=H$(),Q=Y?.models||[],J=Y?.currentModelId||Q[0]?.id,G=Q.map((K)=>({modelId:K.id,name:K.name||K.id,description:K.provider?`Provider: ${K.provider}`:void 0}));return{sessionId:Z,modes:{availableModes:[{id:"default",name:"Default",description:"Ask for confirmation before all file edits and commands"},{id:"auto-edit",name:"Auto Edit",description:"Auto-approve file edits, ask for shell commands"},{id:"yolo",name:"Full Auto",description:"Auto-approve everything without confirmation"},{id:"plan",name:"Plan Only",description:"Read-only mode, no file changes or commands"}],currentModeId:"default"},models:G.length>0?{availableModels:G,currentModelId:J}:void 0}}async prompt($){let Z=this.sessions.get($.sessionId);if(!Z)throw Error(`Session not found: ${$.sessionId}`);return Z.prompt($)}async cancel($){a1.info(`[BladeAgent] Cancel notification received for session: ${$.sessionId}`);let Z=this.sessions.get($.sessionId);if(Z)a1.info("[BladeAgent] Found session, calling session.cancel()"),Z.cancel();else a1.warn(`[BladeAgent] Session not found for cancel: ${$.sessionId}`)}async setSessionMode($){a1.info(`[BladeAgent] Setting session mode: ${$.modeId}`);let Z=this.sessions.get($.sessionId);if(Z)await Z.setMode($.modeId);return{}}async unstable_setSessionModel($){a1.info(`[BladeAgent] Setting session model: ${$.modelId}`);let Z=this.sessions.get($.sessionId);if(Z)await Z.setModel($.modelId);return{}}async destroy(){for(let $ of this.sessions.values())await $.destroy();this.sessions.clear()}}var a1;var yU=A(()=>{B0();C0();IU();a1=i("Agent")});var vU={};hU(vU,{runAcpIntegration:()=>Rb});import{Readable as bb,Writable as Ab}from"node:stream";import*as L9 from"@agentclientprotocol/sdk";async function Rb(){let $=Ab.toWeb(process.stdout),Z=bb.toWeb(process.stdin),X=L9.ndJsonStream($,Z);await new L9.AgentSideConnection((Q)=>new tZ(Q),X).closed}var EU=A(()=>{yU()});import{render as Vb}from"ink";import Db from"react";import Mb from"yargs";import{hideBin as TU}from"yargs/helpers";j8();var JX={debug:{alias:"d",type:"string",describe:'Enable debug mode with optional category filtering (e.g., "agent,ui" or "!chat,!loop")',group:"Debug Options:"},print:{alias:"p",type:"boolean",describe:"Print response and exit (useful for pipes)",group:"Output Options:"},"output-format":{alias:["outputFormat"],type:"string",choices:["text","json","stream-json"],default:"text",describe:"Output format (only works with --print)",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:($)=>{if($===void 0||$===!0||$==="")return"true";return String($)}},"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:"}},c2={scriptName:"blade",usage:"$0 [command] [options]",description:YX(),version:M4(),locale:"en",showHelpOnFail:!0,demandCommand:!1,recommendCommands:!0,strict:!1};y4();B0();C0();var f9=i("General"),gX=($)=>{if($.yolo){if($.permissionMode&&$.permissionMode!=="yolo")throw Error("Cannot use both --yolo and --permission-mode with different values");$.permissionMode="yolo"}if(Array.isArray($.allowedTools)&&Array.isArray($.disallowedTools)){let Z=$.allowedTools.filter((X)=>$.disallowedTools.includes(X));if(Z.length>0)throw Error(`Tools cannot be both allowed and disallowed: ${Z.join(", ")}`)}},cX=async($)=>{try{let X=await u$.getInstance().initialize();if(K0().config.actions.setConfig(X),$.debug)f9.info("[CLI] 配置已加载到 Store")}catch(Z){f9.error("[CLI] ❌ 配置初始化失败",Z instanceof Error?Z.message:Z),console.error(`
|
|
2680
2680
|
❌ 配置初始化失败
|
|
2681
2681
|
`),console.error("原因:",Z instanceof Error?Z.message:"未知错误"),console.error(`
|
|
2682
2682
|
请检查:`),console.error(" 1. 配置文件格式是否正确 (~/.blade/config.json)"),console.error(" 2. 是否需要运行 blade 进行首次配置"),console.error(` 3. 配置文件权限是否正确
|
|
2683
|
-
`),process.exit(1)}if($.continue&&$.resume)throw Error("Cannot use both --continue and --resume flags simultaneously")},lX=($)=>{if($.outputFormat&&$.outputFormat!=="text"&&!$.print)throw Error("--output-format can only be used with --print flag");if($.inputFormat==="stream-json"&&$.print)f9.warn("⚠️ Warning: stream-json input format may not work as expected with --print")};
|
|
2683
|
+
`),process.exit(1)}if($.continue&&$.resume)throw Error("Cannot use both --continue and --resume flags simultaneously")},lX=($)=>{if($.outputFormat&&$.outputFormat!=="text"&&!$.print)throw Error("--output-format can only be used with --print flag");if($.inputFormat==="stream-json"&&$.print)f9.warn("⚠️ Warning: stream-json input format may not work as expected with --print")};y4();var iX={command:"doctor",describe:"Check the health of your Blade installation",handler:async()=>{console.log(`\uD83D\uDD0D Running Blade health check...
|
|
2684
2684
|
`);let $=0;try{await u$.getInstance().initialize(),console.log("✅ Configuration: OK")}catch(Y){console.log("❌ Configuration: FAILED"),console.log(` Error: ${Y instanceof Error?Y.message:"未知错误"}`),$++}let Z=process.version;if(parseInt(Z.slice(1).split(".")[0])>=18)console.log(`✅ Node.js version: ${Z}`);else console.log(`⚠️ Node.js version: ${Z} (recommended: v18+)`),$++;try{let Y=await import("fs/promises"),Q=process.cwd();await Y.access(Q,(await import("fs")).constants.R_OK|(await import("fs")).constants.W_OK),console.log("✅ File system permissions: OK")}catch(Y){console.log("❌ File system permissions: FAILED"),console.log(" Error: Cannot read/write in current directory"),$++}try{await import("ink"),console.log("✅ Dependencies: OK")}catch(Y){console.log("❌ Dependencies: FAILED"),console.log(" Error: Missing required dependencies"),$++}if(console.log(`
|
|
2685
|
-
\uD83D\uDCCA Health Check Summary:`),$===0)console.log("\uD83C\uDF89 All checks passed! Blade is ready to use.");else console.log(`⚠️ Found ${$} issue(s). Please resolve them for optimal performance.`),process.exit(1)}};var aX={command:"install [target]",describe:"Install Blade native build. Use [target] to specify version (stable, latest, or specific version)",builder:($)=>{return $.positional("target",{describe:"Version to install",type:"string",default:"stable",choices:["stable","latest"]}).option("force",{type:"boolean",describe:"Force reinstall",default:!1}).example([["$0 install","Install stable version"],["$0 install latest","Install latest version"],["$0 install --force","Force reinstall stable version"]])},handler:async($)=>{console.log(`\uD83D\uDCE6 Installing Blade ${$.target}...`);try{if($.force)console.log("\uD83D\uDD04 Force reinstall enabled");console.log("⬇️ Downloading..."),console.log("\uD83D\uDD27 Installing..."),console.log("✅ Installation completed successfully")}catch(Z){console.error(`❌ Installation failed: ${Z instanceof Error?Z.message:"未知错误"}`),process.exit(1)}}};
|
|
2685
|
+
\uD83D\uDCCA Health Check Summary:`),$===0)console.log("\uD83C\uDF89 All checks passed! Blade is ready to use.");else console.log(`⚠️ Found ${$} issue(s). Please resolve them for optimal performance.`),process.exit(1)}};var aX={command:"install [target]",describe:"Install Blade native build. Use [target] to specify version (stable, latest, or specific version)",builder:($)=>{return $.positional("target",{describe:"Version to install",type:"string",default:"stable",choices:["stable","latest"]}).option("force",{type:"boolean",describe:"Force reinstall",default:!1}).example([["$0 install","Install stable version"],["$0 install latest","Install latest version"],["$0 install --force","Force reinstall stable version"]])},handler:async($)=>{console.log(`\uD83D\uDCE6 Installing Blade ${$.target}...`);try{if($.force)console.log("\uD83D\uDD04 Force reinstall enabled");console.log("⬇️ Downloading..."),console.log("\uD83D\uDD27 Installing..."),console.log("✅ Installation completed successfully")}catch(Z){console.error(`❌ Installation failed: ${Z instanceof Error?Z.message:"未知错误"}`),process.exit(1)}}};s2();T4();C0();import qY from"os";import S3 from"path";function S4($){return typeof $==="string"?$:void 0}function a9($){if(!Array.isArray($))return;let Z=[];for(let X of $)if(typeof X==="string")Z.push(X);else if(X!=null)Z.push(String(X));return Z}function xH(){console.log(`
|
|
2686
2686
|
blade mcp
|
|
2687
2687
|
`),console.log(`管理 MCP 服务器
|
|
2688
2688
|
`),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 字符串添加服务器
|
|
2689
2689
|
`),console.log("Options:"),console.log(` -h, --help 显示帮助信息 [boolean]
|
|
2690
2690
|
`),console.log("Examples:"),console.log(" blade mcp list"),console.log(" blade mcp add github npx -y @modelcontextprotocol/server-github"),console.log(" blade mcp add api --transport http http://localhost:3000"),console.log(` blade mcp remove github
|
|
2691
2691
|
`),console.log(`使用 blade mcp <command> --help 查看各子命令的详细帮助
|
|
2692
|
-
`)}function pH($){return $.reduce((Z,X)=>{let[Y,...Q]=X.split("=");return Z[Y]=Q.join("="),Z},{})}function dH($){return $.reduce((Z,X)=>{let[Y,...Q]=X.split(":");return Z[Y.trim()]=Q.join(":").trim(),Z},{})}var mH={command:"add <name> [commandOrUrl] [args...]",describe:"添加 MCP 服务器",builder:($)=>{return $.positional("name",{type:"string",describe:"服务器名称",demandOption:!0}).positional("commandOrUrl",{type:"string",describe:"stdio: 命令 | http/sse: URL"}).positional("args",{type:"string",array:!0,describe:"stdio 命令参数",default:[]}).option("transport",{alias:"t",choices:["stdio","sse","http"],default:"stdio",describe:"传输类型"}).option("env",{alias:"e",type:"array",describe:"环境变量 (KEY=value)"}).option("header",{alias:"H",type:"array",describe:"HTTP 头 (Key: Value)"}).option("timeout",{type:"number",describe:"超时时间(毫秒)"}).option("global",{alias:"g",type:"boolean",default:!1,describe:"存储到全局配置(~/.blade/config.json)"}).example([["$0 mcp add github -- npx -y @modelcontextprotocol/server-github","Add stdio server (recommended)"],["$0 mcp add github npx @modelcontextprotocol/server-github -e GITHUB_TOKEN=xxx","Add stdio server with env"],['$0 mcp add api --transport http http://localhost:3000 -H "Auth: Bearer token"',"Add HTTP server"]])},handler:async($)=>{try{let{name:Z,commandOrUrl:X,args:Y,transport:Q,env:J,header:G,timeout:q}=$,K=$.global===!0,W=
|
|
2692
|
+
`)}function pH($){return $.reduce((Z,X)=>{let[Y,...Q]=X.split("=");return Z[Y]=Q.join("="),Z},{})}function dH($){return $.reduce((Z,X)=>{let[Y,...Q]=X.split(":");return Z[Y.trim()]=Q.join(":").trim(),Z},{})}var mH={command:"add <name> [commandOrUrl] [args...]",describe:"添加 MCP 服务器",builder:($)=>{return $.positional("name",{type:"string",describe:"服务器名称",demandOption:!0}).positional("commandOrUrl",{type:"string",describe:"stdio: 命令 | http/sse: URL"}).positional("args",{type:"string",array:!0,describe:"stdio 命令参数",default:[]}).option("transport",{alias:"t",choices:["stdio","sse","http"],default:"stdio",describe:"传输类型"}).option("env",{alias:"e",type:"array",describe:"环境变量 (KEY=value)"}).option("header",{alias:"H",type:"array",describe:"HTTP 头 (Key: Value)"}).option("timeout",{type:"number",describe:"超时时间(毫秒)"}).option("global",{alias:"g",type:"boolean",default:!1,describe:"存储到全局配置(~/.blade/config.json)"}).example([["$0 mcp add github -- npx -y @modelcontextprotocol/server-github","Add stdio server (recommended)"],["$0 mcp add github npx @modelcontextprotocol/server-github -e GITHUB_TOKEN=xxx","Add stdio server with env"],['$0 mcp add api --transport http http://localhost:3000 -H "Auth: Bearer token"',"Add HTTP server"]])},handler:async($)=>{try{let{name:Z,commandOrUrl:X,args:Y,transport:Q,env:J,header:G,timeout:q}=$,K=$.global===!0,W=S4(Z),U=S4(X),H=a9(Y)||[],F=a9(J),O=a9(G),z=typeof q==="number"?q:void 0,_=Q==="stdio"||Q==="sse"||Q==="http"?Q:"stdio",B=$["--"];if(Array.isArray(B)&&B.length>0)U=String(B[0]),H=B.slice(1).map((R)=>String(R));if(!W||!U)console.error("❌ 缺少必需参数: name 和 commandOrUrl"),console.log(`
|
|
2693
2693
|
\uD83D\uDCA1 用法:`),console.log(" blade mcp add <name> <command> [args...]"),console.log(" blade mcp add <name> -- <command> [args...]"),console.log(`
|
|
2694
|
-
示例:`),console.log(" blade mcp add github npx -y @modelcontextprotocol/server-github"),console.log(" blade mcp add github -- npx -y @modelcontextprotocol/server-github"),process.exit(1);let L={type:_};if(_==="stdio"){if(L.command=U,L.args=H,F)L.env=pH(F)}else if(L.url=U,O)L.headers=dH(O);if(z!==void 0)L.timeout=z;await x0().addMcpServer(W,L,{scope:K?"global":"project"});let w=K?S3.join(qY.homedir(),".blade","config.json"):S3.join(process.cwd(),".blade","config.json");console.log(`✅ MCP 服务器 "${W}" 已添加`),console.log(` 配置文件: ${w}`)}catch(Z){console.error(`❌ 添加失败: ${Z instanceof Error?Z.message:"未知错误"}`),process.exit(1)}}},uH={command:"remove <name>",describe:"删除 MCP 服务器",aliases:["rm"],builder:($)=>{return $.positional("name",{type:"string",describe:"服务器名称",demandOption:!0}).option("global",{alias:"g",type:"boolean",default:!1,describe:"从全局配置删除(~/.blade/config.json)"}).example([["$0 mcp remove github","Remove the specified MCP server"]])},handler:async($)=>{try{let Z=G1(),X=$.global===!0,Y=
|
|
2695
|
-
`);let Z=N$.getInstance(),X=Object.entries($).map(async([Q,J])=>{try{let G=Z.getServerStatus(Q);if(!G)await Z.registerServer(Q,J),G=Z.getServerStatus(Q);else if(G.status==="disconnected")await Z.connectServer(Q);return{name:Q,config:J,serverInfo:G}}catch(G){return{name:Q,config:J,serverInfo:null,error:G}}}),Y=await Promise.all(X);for(let{name:Q,config:J,serverInfo:G,error:q}of Y){let K=G?.status||"disconnected",W=K==="connected"?"✓":"✗",U=K==="connected"?"Connected":"Failed";if(console.log(`${Q}: ${J.type==="stdio"?J.command:J.url} - ${W} ${U}`),q&&K!=="connected")console.log(` 错误: ${q instanceof Error?q.message:String(q)}`)}console.log("");for(let{name:Q}of Y)try{await Z.unregisterServer(Q)}catch(J){}process.exit(0)}catch($){console.error(`❌ 列表获取失败: ${$ instanceof Error?$.message:"未知错误"}`),process.exit(1)}}},cH={command:"get <name>",describe:"获取服务器详情",builder:($)=>{return $.positional("name",{type:"string",describe:"服务器名称",demandOption:!0}).example([["$0 mcp get github","Get details of the specified server"]])},handler:async($)=>{try{let Z=G1(),X=
|
|
2694
|
+
示例:`),console.log(" blade mcp add github npx -y @modelcontextprotocol/server-github"),console.log(" blade mcp add github -- npx -y @modelcontextprotocol/server-github"),process.exit(1);let L={type:_};if(_==="stdio"){if(L.command=U,L.args=H,F)L.env=pH(F)}else if(L.url=U,O)L.headers=dH(O);if(z!==void 0)L.timeout=z;await x0().addMcpServer(W,L,{scope:K?"global":"project"});let w=K?S3.join(qY.homedir(),".blade","config.json"):S3.join(process.cwd(),".blade","config.json");console.log(`✅ MCP 服务器 "${W}" 已添加`),console.log(` 配置文件: ${w}`)}catch(Z){console.error(`❌ 添加失败: ${Z instanceof Error?Z.message:"未知错误"}`),process.exit(1)}}},uH={command:"remove <name>",describe:"删除 MCP 服务器",aliases:["rm"],builder:($)=>{return $.positional("name",{type:"string",describe:"服务器名称",demandOption:!0}).option("global",{alias:"g",type:"boolean",default:!1,describe:"从全局配置删除(~/.blade/config.json)"}).example([["$0 mcp remove github","Remove the specified MCP server"]])},handler:async($)=>{try{let Z=G1(),X=$.global===!0,Y=S4($.name);if(!Y)console.error("❌ 缺少必需参数: name"),process.exit(1);if(!Z[Y])console.error(`❌ 服务器 "${Y}" 不存在`),process.exit(1);await x0().removeMcpServer(Y,{scope:X?"global":"project"}),console.log(`✅ MCP 服务器 "${Y}" 已删除`)}catch(Z){console.error(`❌ 删除失败: ${Z instanceof Error?Z.message:"未知错误"}`),process.exit(1)}}},gH={command:"list",describe:"列出所有 MCP 服务器并检查健康状态",aliases:["ls"],handler:async()=>{try{let $=G1();if(console.log(""),Object.keys($).length===0){console.log("暂无配置的 MCP 服务器");return}console.log(`检查 MCP 服务器健康状态...
|
|
2695
|
+
`);let Z=N$.getInstance(),X=Object.entries($).map(async([Q,J])=>{try{let G=Z.getServerStatus(Q);if(!G)await Z.registerServer(Q,J),G=Z.getServerStatus(Q);else if(G.status==="disconnected")await Z.connectServer(Q);return{name:Q,config:J,serverInfo:G}}catch(G){return{name:Q,config:J,serverInfo:null,error:G}}}),Y=await Promise.all(X);for(let{name:Q,config:J,serverInfo:G,error:q}of Y){let K=G?.status||"disconnected",W=K==="connected"?"✓":"✗",U=K==="connected"?"Connected":"Failed";if(console.log(`${Q}: ${J.type==="stdio"?J.command:J.url} - ${W} ${U}`),q&&K!=="connected")console.log(` 错误: ${q instanceof Error?q.message:String(q)}`)}console.log("");for(let{name:Q}of Y)try{await Z.unregisterServer(Q)}catch(J){}process.exit(0)}catch($){console.error(`❌ 列表获取失败: ${$ instanceof Error?$.message:"未知错误"}`),process.exit(1)}}},cH={command:"get <name>",describe:"获取服务器详情",builder:($)=>{return $.positional("name",{type:"string",describe:"服务器名称",demandOption:!0}).example([["$0 mcp get github","Get details of the specified server"]])},handler:async($)=>{try{let Z=G1(),X=S4($.name);if(!X)console.error("❌ 缺少必需参数: name"),process.exit(1);let Y=Z[X];if(!Y)console.error(`❌ 服务器 "${X}" 不存在`),process.exit(1);console.log(`
|
|
2696
2696
|
服务器: ${X}
|
|
2697
|
-
`),console.log(JSON.stringify(Y,null,2))}catch(Z){console.error(`❌ 获取失败: ${Z instanceof Error?Z.message:"未知错误"}`),process.exit(1)}}},lH={command:"add-json <name> <json>",describe:"从 JSON 字符串添加服务器",builder:($)=>{return $.positional("name",{type:"string",describe:"服务器名称",demandOption:!0}).positional("json",{type:"string",describe:"JSON 配置字符串",demandOption:!0}).option("global",{alias:"g",type:"boolean",default:!1,describe:"存储到全局配置(~/.blade/config.json)"}).example([[`$0 mcp add-json my-server '{"type":"stdio","command":"npx","args":["-y","@example/server"]}'`,"Add server from JSON string"]])},handler:async($)=>{try{let Z=
|
|
2697
|
+
`),console.log(JSON.stringify(Y,null,2))}catch(Z){console.error(`❌ 获取失败: ${Z instanceof Error?Z.message:"未知错误"}`),process.exit(1)}}},lH={command:"add-json <name> <json>",describe:"从 JSON 字符串添加服务器",builder:($)=>{return $.positional("name",{type:"string",describe:"服务器名称",demandOption:!0}).positional("json",{type:"string",describe:"JSON 配置字符串",demandOption:!0}).option("global",{alias:"g",type:"boolean",default:!1,describe:"存储到全局配置(~/.blade/config.json)"}).example([[`$0 mcp add-json my-server '{"type":"stdio","command":"npx","args":["-y","@example/server"]}'`,"Add server from JSON string"]])},handler:async($)=>{try{let Z=S4($.json),X=S4($.name);if(!Z||!X)throw Error("缺少必需参数: name 或 json");let Y=JSON.parse(Z),Q=$.global===!0;if(!Y.type)throw Error('配置必须包含 "type" 字段');await x0().addMcpServer(X,Y,{scope:Q?"global":"project"});let J=Q?S3.join(qY.homedir(),".blade","config.json"):S3.join(process.cwd(),".blade","config.json");console.log(`✅ MCP 服务器 "${X}" 已添加`),console.log(` 配置文件: ${J}`)}catch(Z){console.error(`❌ 添加失败: ${Z instanceof Error?Z.message:"未知错误"}`),process.exit(1)}}},KY={command:"mcp",describe:"管理 MCP 服务器",builder:($)=>{return $.command(mH).command(uH).command(gH).command(cH).command(lH).demandCommand(0).help(!1).option("help",{alias:"h",type:"boolean",describe:"显示帮助信息"})},handler:($)=>{let Z=["add","remove","list","ls","get","add-json"];if(!(Array.isArray($._)?$._:[]).some((Q)=>typeof Q==="string"&&Z.includes(Q))||$.help)xH(),process.exit(0)}};Q2();X8();q8();function nB($){return $.command("* [message]","Print response and exit (useful for pipes)",(Z)=>{return Z.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(Z)=>{if(!Z.print)return;try{if((await a$().initialize(process.cwd(),[])).plugins.length>0)await v2();let Q="",J=Z.message||Z._?.[0];if(J&&typeof J==="string")Q=J;else if(!process.stdin.isTTY){let K=[];for await(let W of process.stdin)K.push(W);Q=Buffer.concat(K).toString("utf-8").trim()}else Q="Hello";if(J8(Q)){let K=await G8(Q,{cwd:process.cwd(),workspaceRoot:process.cwd()});if(!K.success)console.error(`Error: ${K.error||"未知错误"}`),process.exit(1);let W=K.data;if(W?.action==="invoke_skill"){let{skillName:U,skillArgs:H}=W;Q=H?`Please use the "${U}" skill to help me with: ${H}`:`Please use the "${U}" skill.`}else if(W?.action==="invoke_custom_command"||W?.action==="invoke_plugin_command"){let U=W.processedContent;Q=`# Custom Command: /${W.commandName}
|
|
2698
2698
|
|
|
2699
|
-
${U}`}else{if(K.message)console.log(K.message);process.exit(0)}}let G=await z$.create({systemPrompt:Z.systemPrompt,appendSystemPrompt:Z.appendSystemPrompt,maxTurns:Z.maxTurns}),q;if(Z.appendSystemPrompt)q=await G.chatWithSystem(Z.appendSystemPrompt,Q);else q=await G.chat(Q,{messages:[],userId:"cli-user",sessionId:`print-${Date.now()}`,workspaceRoot:process.cwd()});if(Z.outputFormat==="json")console.log(JSON.stringify({response:q,input:Q,model:Z.model,timestamp:new Date().toISOString()},null,2));else if(Z.outputFormat==="stream-json")console.log(JSON.stringify({type:"response",content:q}));else console.log(q);process.exit(0)}catch(X){console.error(`Error: ${X instanceof Error?X.message:"未知错误"}`),process.exit(1)}})}async function ZK(){if(process.argv.slice(2).findIndex((X)=>X==="--print"||X==="-p")===-1)return!1;try{let X=(await import("yargs")).default,{hideBin:Y}=await import("yargs/helpers"),Q=X(Y(process.argv)).scriptName("blade").strict(!1);return nB(Q),await Q.parse(),!0}catch(X){console.error(`Print mode error: ${X instanceof Error?X.message:"未知错误"}`),process.exit(1)}}import{execSync as XL}from"child_process";k2();import*as H2 from"fs/promises";import*as E4 from"path";import XK from"semver";import{fileURLToPath as oB}from"url";var QZ="blade-code",sB="https://cdn.jsdelivr.net/npm/blade-code@latest/CHANGELOG.md",YK=E4.join(process.env.HOME||process.env.USERPROFILE||".",".blade"),QK=E4.join(YK,"version-cache.json"),tB=3600000,eB=`https://registry.npmjs.org/${QZ}/latest`;async function $L(){try{if(process.env.BLADE_VERSION)return process.env.BLADE_VERSION;let $=oB(import.meta.url),Z=E4.dirname($),X=[E4.join(Z,"..","..","package.json"),E4.join(Z,"..","package.json"),E4.join(process.cwd(),"package.json")];for(let Y of X)try{let Q=await H2.readFile(Y,"utf-8"),J=JSON.parse(Q);if(J.name===QZ&&J.version)return J.version}catch{}return"unknown"}catch{return"unknown"}}async function JK(){try{let $=await H2.readFile(QK,"utf-8"),Z=JSON.parse($);if(Date.now()-Z.checkedAt<tB)return Z;return{...Z,checkedAt:0}}catch{return null}}async function GK($){try{await H2.mkdir(YK,{recursive:!0}),await H2.writeFile(QK,JSON.stringify($,null,2))}catch{}}async function ZL(){try{let $=await P$(eB,{timeout:5000,headers:{Accept:"application/json"}});if(!$.ok)return null;return(await $.json()).version||null}catch{return null}}async function JZ($=!1){let Z=await $L(),X=sB;if(Z==="unknown")return{currentVersion:Z,latestVersion:null,hasUpdate:!1,shouldPrompt:!1,releaseNotesUrl:X,error:"Unable to determine current version"};let Y=await JK(),Q=Y?.skipUntilVersion,J=null;if(!$&&Y&&Y.checkedAt>0)J=Y.latestVersion;else if(J=await ZL(),J)await GK({latestVersion:J,checkedAt:Date.now(),skipUntilVersion:Q});if(!J)return{currentVersion:Z,latestVersion:null,hasUpdate:!1,shouldPrompt:!1,releaseNotesUrl:X,error:"Unable to check for updates"};let G=XK.gt(J,Z),q=G;if(G&&Q)q=XK.gt(J,Q);return{currentVersion:Z,latestVersion:J,hasUpdate:G,shouldPrompt:q,releaseNotesUrl:X}}async function qK($){let Z=await JK();await GK({latestVersion:Z?.latestVersion||$,checkedAt:Z?.checkedAt||Date.now(),skipUntilVersion:$})}function GZ(){return`npm install -g ${QZ}@latest --registry https://registry.npmjs.org`}async function KK(){let{spawn:$}=await import("child_process");return new Promise((Z)=>{let X=GZ(),Y=$(X,{stdio:"inherit",shell:!0});Y.on("close",(Q)=>{if(Q===0)Z({success:!0,message:"✅ 升级成功!请重新启动 blade。"});else Z({success:!1,message:`❌ 升级失败 (exit code: ${Q})`})}),Y.on("error",(Q)=>{Z({success:!1,message:`❌ 升级失败: ${Q.message}`})})})}async function WK(){try{let $=await JZ();return $.shouldPrompt?$:null}catch{return null}}var UK={command:"update",describe:"Check for updates and install if available",handler:async()=>{console.log("\uD83D\uDD0D Checking for updates...");try{let $=await JZ(!0);if(console.log(`\uD83D\uDCE6 Current version: ${$.currentVersion}`),$.error){console.log(`⚠️ ${$.error}`);return}if($.latestVersion)console.log(`\uD83D\uDCE6 Latest version: ${$.latestVersion}`);if($.hasUpdate&&$.latestVersion){console.log(""),console.log(`\x1B[33m⚠️ Update available: ${$.currentVersion} → ${$.latestVersion}\x1B[0m`),console.log(""),console.log("\uD83D\uDE80 Updating...");try{XL("npm install -g blade-code@latest --registry https://registry.npmjs.org",{stdio:"inherit"}),console.log(""),console.log("✅ Update complete!")}catch(Z){console.error("❌ Update failed. Please run manually:"),console.error(" npm install -g blade-code@latest"),process.exit(1)}}else console.log("✅ You are running the latest version of Blade")}catch($){console.error(`❌ Failed to check for updates: ${$ instanceof Error?$.message:"未知错误"}`),process.exit(1)}}};B0();U$();r$();B0();C0();function HK(){process.stdout.write("\x1B[?25h"),process.stdout.write("\x1B[0m")}var g1=i("Service");function YL($){switch($){case"SIGINT":return"ctrl_c";case"esc":return"esc";case"uncaughtException":case"unhandledRejection":return"error";case"SIGTERM":case"normal":default:return"user_exit"}}class K8{static instance=null;cleanupHandlers=[];isShuttingDown=!1;initialized=!1;constructor(){}static getInstance(){if(!K8.instance)K8.instance=new K8;return K8.instance}initialize(){if(this.initialized){g1.debug("[GracefulShutdown] 已初始化,跳过重复初始化");return}if(process.on("uncaughtException",($)=>{this.handleFatalError("uncaughtException",$)}),process.on("unhandledRejection",($)=>{let Z=$ instanceof Error?$:Error(String($));this.handleFatalError("unhandledRejection",Z)}),process.on("SIGTERM",()=>{g1.info("[GracefulShutdown] 收到 SIGTERM 信号"),this.shutdown("SIGTERM",0)}),process.env.BLADE_NON_INTERACTIVE==="true")process.on("SIGINT",()=>{g1.info("[GracefulShutdown] 收到 SIGINT 信号(非交互模式)"),this.shutdown("SIGINT",0)});this.initialized=!0,g1.debug("[GracefulShutdown] 全局错误处理器已初始化")}registerCleanup($){return this.cleanupHandlers.push($),g1.debug(`[GracefulShutdown] 注册清理函数,当前共 ${this.cleanupHandlers.length} 个`),()=>{let Z=this.cleanupHandlers.indexOf($);if(Z!==-1)this.cleanupHandlers.splice(Z,1),g1.debug(`[GracefulShutdown] 取消注册清理函数,剩余 ${this.cleanupHandlers.length} 个`)}}handleFatalError($,Z){if(this.isShuttingDown){console.error(`[GracefulShutdown] 退出过程中发生额外错误 (${$}):`,Z);return}if(console.error(""),console.error("═".repeat(60)),console.error(`\uD83D\uDCA5 发生未捕获的错误 (${$})`),console.error("═".repeat(60)),console.error(""),console.error("错误信息:",Z.message),console.error(""),Z.stack)console.error("堆栈跟踪:"),console.error(Z.stack);console.error(""),console.error("═".repeat(60)),console.error(""),this.shutdown($,1)}async shutdown($,Z=0){if(this.isShuttingDown){g1.debug("[GracefulShutdown] 已在退出过程中,跳过重复退出");return}this.isShuttingDown=!0,g1.info(`[GracefulShutdown] 开始优雅退出 (原因: ${$})`);try{let Q=M0.getInstance();if(Q.isEnabled()){let J=K0(),G=J.session?.sessionId||"unknown",q=J.config?.config?.permissionMode||"default";await Q.executeSessionEndHooks(YL($),{projectDir:process.cwd(),sessionId:G,permissionMode:q})}}catch(Q){g1.debug("[GracefulShutdown] SessionEnd hooks 执行失败:",Q)}let X=5000,Y=new Promise((Q,J)=>{setTimeout(()=>{J(Error(`清理超时 (${X}ms)`))},X)});try{let Q=this.runCleanupHandlers();await Promise.race([Q,Y]),g1.info("[GracefulShutdown] 所有清理函数执行完成")}catch(Q){console.error("[GracefulShutdown] 清理过程中发生错误:",Q)}finally{HK(),setTimeout(()=>{process.exit(Z)},100)}}async runCleanupHandlers(){let $=[...this.cleanupHandlers].reverse();for(let Z of $)try{let X=Z();if(X instanceof Promise)await X}catch(X){console.error("[GracefulShutdown] 清理函数执行失败:",X)}}isExiting(){return this.isShuttingDown}reset(){this.isShuttingDown=!1,this.cleanupHandlers=[],this.initialized=!1}}var F2=()=>{return K8.getInstance()},FK=($)=>{return F2().registerCleanup($)},OK=()=>{F2().initialize()},W8=($=0)=>{HK(),process.exit($)};G2();C3();y2();r$();s4();X8();import{useMemoizedFn as MU}from"ahooks";import{useEffect as _b,useState as oZ}from"react";X4();q8();C0();i2();U$();B0();import{useMemoizedFn as s$}from"ahooks";import{Box as u4,useApp as Hb}from"ink";import{useEffect as V2,useRef as O9}from"react";E6();U1();i4();import{useShallow as zK}from"zustand/react/shallow";C0();import{useStore as QL}from"zustand";function N0($){return QL(E2,$)}U$();var JL=[],_K=()=>N0(($)=>$.session.sessionId),k6=()=>N0(($)=>$.session.messages),BK=()=>N0(($)=>$.session.clearCount),LK=()=>N0(($)=>$.session.isCompacting),P4=()=>N0(($)=>$.session.actions),wK=()=>N0(($)=>{let{inputTokens:Z,maxContextTokens:X}=$.session.tokenUsage;if(X<=0)return 100;let Y=Math.max(0,100-Z/X*100);return Math.round(Y)}),NK=()=>N0(($)=>$.app.initializationStatus),bK=()=>N0(($)=>$.app.initializationError),f6=()=>N0(($)=>$.app.activeModal),AK=()=>N0(($)=>$.app.todos),RK=()=>N0(($)=>$.app.modelEditorTarget),VK=()=>N0(($)=>$.app.sessionSelectorData),DK=()=>N0(($)=>$.app.awaitingSecondCtrlC),T4=()=>N0(($)=>$.app.actions),h6=()=>N0(($)=>$.app.initializationStatus==="ready"),MK=()=>N0(($)=>$.app.todos.length>0),U8=()=>N0(($)=>$.config.config?.permissionMode||"default"),jK=()=>N0(($)=>$.config.config?.models??JL),x6=()=>N0(($)=>{let Z=$.config.config;if(!Z)return;let X=Z.currentModelId;return Z.models.find((Q)=>Q.id===X)??Z.models[0]}),IK=()=>N0(($)=>$.config.config?.currentModelId),e0=()=>N0(($)=>{let Z=$.config.config?.theme??"default";if(g$.getCurrentThemeName()!==Z)try{g$.setTheme(Z)}catch{}return g$.getTheme()}),o$=()=>N0(($)=>$.focus.currentFocus),yK=()=>N0(($)=>$.focus.actions),S4=()=>N0(($)=>$.command.isProcessing),vK=()=>N0(($)=>$.command.actions),EK=()=>N0(($)=>$.command.pendingCommands),p6=()=>N0(($)=>$.app.thinkingModeEnabled),PK=()=>N0(($)=>$.session.currentThinkingContent),TK=()=>N0(($)=>$.session.thinkingExpanded),SK=()=>N0(($)=>$.session.currentStreamingMessageId),CK=()=>N0(zK(($)=>({lines:$.session.currentStreamingLines,tail:$.session.currentStreamingTail,lineCount:$.session.currentStreamingLineCount,version:$.session.currentStreamingVersion}))),kK=()=>N0(($)=>$.session.finalizingStreamingMessageId),fK=()=>N0(($)=>$.session.historyExpanded),hK=()=>N0(($)=>$.session.expandedMessageCount),xK=()=>N0(zK(($)=>{let Z=$.spec.currentSpec;if(!Z)return{phase:null,completed:0,total:0};let X=Z.tasks??[],Y=X.filter((Q)=>Q.status==="completed").length;return{phase:Z.phase,completed:Y,total:X.length}}));C0();r$();B0();D7();import{useMemoizedFn as C4}from"ahooks";import{useEffect as mK,useRef as z3}from"react";q8();C0();P8();Q4();import{useMemoizedFn as pK}from"ahooks";import{useRef as GL}from"react";function dK($){let Z=GL(void 0),X=pK(async()=>{let Q=await z$.create({systemPrompt:$.systemPrompt,appendSystemPrompt:$.appendSystemPrompt,maxTurns:$.maxTurns});return Z.current=Q,Q}),Y=pK(()=>{if(Z.current)Z.current=void 0});return{agentRef:Z,createAgent:X,cleanupAgent:Y}}var uK=i("UI");function qL($,Z,X,Y){switch($){case"show_theme_selector":return X.setActiveModal("themeSelector"),!0;case"show_model_selector":return X.setActiveModal("modelSelector"),!0;case"show_model_add_wizard":return X.setActiveModal("modelAddWizard"),!0;case"show_permissions_manager":return X.setActiveModal("permissionsManager"),!0;case"show_agents_manager":return X.setActiveModal("agentsManager"),!0;case"show_skills_manager":return X.setActiveModal("skillsManager"),!0;case"show_hooks_manager":return X.setActiveModal("hooksManager"),!0;case"show_plugins_manager":return X.setActiveModal("pluginsManager"),!0;case"show_agent_creation_wizard":return X.setActiveModal("agentCreationWizard"),!0;case"show_session_selector":{let Q=Z?.sessions;return X.showSessionSelector(Q),!0}case"clear_screen":return Y.clearMessages(),Y.setError(null),Y.resetTokenUsage(),X.setTodos([]),!0;case"compact_completed":case"compact_fallback":return Y.resetTokenUsage(),!0;case"exit_application":return W8(0),!0;default:return!1}}function KL($){return typeof $==="object"&&$!==null&&$.action==="invoke_skill"&&typeof $.skillName==="string"}function WL($){return typeof $==="object"&&$!==null&&$.action==="invoke_custom_command"&&typeof $.commandName==="string"&&typeof $.processedContent==="string"}function UL($){return typeof $==="object"&&$!==null&&$.action==="invoke_plugin_command"&&typeof $.commandName==="string"&&typeof $.processedContent==="string"}function HL($){let{text:Z,images:X,parts:Y}=$;if(X.length===0)return Z;let Q=[];for(let J of Y)if(J.type==="text")Q.push({type:"text",text:J.text});else Q.push({type:"image_url",image_url:{url:`data:${J.mimeType};base64,${J.base64}`}});return Q}var gK=($,Z,X,Y)=>{let Q=S4(),J=k6(),G=_K(),q=U8(),K=p6(),W=P4(),U=T4(),H=vK(),F=z3(!1),{createAgent:O,cleanupAgent:z}=dK({systemPrompt:$,appendSystemPrompt:Z,maxTurns:Y}),_=300,B=5,L=400,w=z3(""),R=z3(null),D=z3(""),V=z3(null),I=C4(()=>{if(w.current){let j=w.current,M=W.appendAssistantContent(j);E9(M,j),w.current=""}if(R.current)clearTimeout(R.current),R.current=null}),v=C4(()=>{if(D.current)W.appendThinkingContent(D.current),D.current="";if(V.current)clearTimeout(V.current),V.current=null}),N=(j)=>{let M=0;for(let b of j)if(b===`
|
|
2700
|
-
`)M++;return M},k=
|
|
2699
|
+
${U}`}else{if(K.message)console.log(K.message);process.exit(0)}}let G=await z$.create({systemPrompt:Z.systemPrompt,appendSystemPrompt:Z.appendSystemPrompt,maxTurns:Z.maxTurns}),q;if(Z.appendSystemPrompt)q=await G.chatWithSystem(Z.appendSystemPrompt,Q);else q=await G.chat(Q,{messages:[],userId:"cli-user",sessionId:`print-${Date.now()}`,workspaceRoot:process.cwd()});if(Z.outputFormat==="json")console.log(JSON.stringify({response:q,input:Q,model:Z.model,timestamp:new Date().toISOString()},null,2));else if(Z.outputFormat==="stream-json")console.log(JSON.stringify({type:"response",content:q}));else console.log(q);process.exit(0)}catch(X){console.error(`Error: ${X instanceof Error?X.message:"未知错误"}`),process.exit(1)}})}async function ZK(){if(process.argv.slice(2).findIndex((X)=>X==="--print"||X==="-p")===-1)return!1;try{let X=(await import("yargs")).default,{hideBin:Y}=await import("yargs/helpers"),Q=X(Y(process.argv)).scriptName("blade").strict(!1);return nB(Q),await Q.parse(),!0}catch(X){console.error(`Print mode error: ${X instanceof Error?X.message:"未知错误"}`),process.exit(1)}}import{execSync as XL}from"child_process";k4();import*as H4 from"fs/promises";import*as E2 from"path";import XK from"semver";import{fileURLToPath as oB}from"url";var QZ="blade-code",sB="https://cdn.jsdelivr.net/npm/blade-code@latest/CHANGELOG.md",YK=E2.join(process.env.HOME||process.env.USERPROFILE||".",".blade"),QK=E2.join(YK,"version-cache.json"),tB=3600000,eB=`https://registry.npmjs.org/${QZ}/latest`;async function $L(){try{if(process.env.BLADE_VERSION)return process.env.BLADE_VERSION;let $=oB(import.meta.url),Z=E2.dirname($),X=[E2.join(Z,"..","..","package.json"),E2.join(Z,"..","package.json"),E2.join(process.cwd(),"package.json")];for(let Y of X)try{let Q=await H4.readFile(Y,"utf-8"),J=JSON.parse(Q);if(J.name===QZ&&J.version)return J.version}catch{}return"unknown"}catch{return"unknown"}}async function JK(){try{let $=await H4.readFile(QK,"utf-8"),Z=JSON.parse($);if(Date.now()-Z.checkedAt<tB)return Z;return{...Z,checkedAt:0}}catch{return null}}async function GK($){try{await H4.mkdir(YK,{recursive:!0}),await H4.writeFile(QK,JSON.stringify($,null,2))}catch{}}async function ZL(){try{let $=await P$(eB,{timeout:5000,headers:{Accept:"application/json"}});if(!$.ok)return null;return(await $.json()).version||null}catch{return null}}async function JZ($=!1){let Z=await $L(),X=sB;if(Z==="unknown")return{currentVersion:Z,latestVersion:null,hasUpdate:!1,shouldPrompt:!1,releaseNotesUrl:X,error:"Unable to determine current version"};let Y=await JK(),Q=Y?.skipUntilVersion,J=null;if(!$&&Y&&Y.checkedAt>0)J=Y.latestVersion;else if(J=await ZL(),J)await GK({latestVersion:J,checkedAt:Date.now(),skipUntilVersion:Q});if(!J)return{currentVersion:Z,latestVersion:null,hasUpdate:!1,shouldPrompt:!1,releaseNotesUrl:X,error:"Unable to check for updates"};let G=XK.gt(J,Z),q=G;if(G&&Q)q=XK.gt(J,Q);return{currentVersion:Z,latestVersion:J,hasUpdate:G,shouldPrompt:q,releaseNotesUrl:X}}async function qK($){let Z=await JK();await GK({latestVersion:Z?.latestVersion||$,checkedAt:Z?.checkedAt||Date.now(),skipUntilVersion:$})}function GZ(){return`npm install -g ${QZ}@latest --registry https://registry.npmjs.org`}async function KK(){let{spawn:$}=await import("child_process");return new Promise((Z)=>{let X=GZ(),Y=$(X,{stdio:"inherit",shell:!0});Y.on("close",(Q)=>{if(Q===0)Z({success:!0,message:"✅ 升级成功!请重新启动 blade。"});else Z({success:!1,message:`❌ 升级失败 (exit code: ${Q})`})}),Y.on("error",(Q)=>{Z({success:!1,message:`❌ 升级失败: ${Q.message}`})})})}async function WK(){try{let $=await JZ();return $.shouldPrompt?$:null}catch{return null}}var UK={command:"update",describe:"Check for updates and install if available",handler:async()=>{console.log("\uD83D\uDD0D Checking for updates...");try{let $=await JZ(!0);if(console.log(`\uD83D\uDCE6 Current version: ${$.currentVersion}`),$.error){console.log(`⚠️ ${$.error}`);return}if($.latestVersion)console.log(`\uD83D\uDCE6 Latest version: ${$.latestVersion}`);if($.hasUpdate&&$.latestVersion){console.log(""),console.log(`\x1B[33m⚠️ Update available: ${$.currentVersion} → ${$.latestVersion}\x1B[0m`),console.log(""),console.log("\uD83D\uDE80 Updating...");try{XL("npm install -g blade-code@latest --registry https://registry.npmjs.org",{stdio:"inherit"}),console.log(""),console.log("✅ Update complete!")}catch(Z){console.error("❌ Update failed. Please run manually:"),console.error(" npm install -g blade-code@latest"),process.exit(1)}}else console.log("✅ You are running the latest version of Blade")}catch($){console.error(`❌ Failed to check for updates: ${$ instanceof Error?$.message:"未知错误"}`),process.exit(1)}}};B0();U$();r$();B0();C0();function HK(){process.stdout.write("\x1B[?25h"),process.stdout.write("\x1B[0m")}var g1=i("Service");function YL($){switch($){case"SIGINT":return"ctrl_c";case"esc":return"esc";case"uncaughtException":case"unhandledRejection":return"error";case"SIGTERM":case"normal":default:return"user_exit"}}class K8{static instance=null;cleanupHandlers=[];isShuttingDown=!1;initialized=!1;constructor(){}static getInstance(){if(!K8.instance)K8.instance=new K8;return K8.instance}initialize(){if(this.initialized){g1.debug("[GracefulShutdown] 已初始化,跳过重复初始化");return}if(process.on("uncaughtException",($)=>{this.handleFatalError("uncaughtException",$)}),process.on("unhandledRejection",($)=>{let Z=$ instanceof Error?$:Error(String($));this.handleFatalError("unhandledRejection",Z)}),process.on("SIGTERM",()=>{g1.info("[GracefulShutdown] 收到 SIGTERM 信号"),this.shutdown("SIGTERM",0)}),process.env.BLADE_NON_INTERACTIVE==="true")process.on("SIGINT",()=>{g1.info("[GracefulShutdown] 收到 SIGINT 信号(非交互模式)"),this.shutdown("SIGINT",0)});this.initialized=!0,g1.debug("[GracefulShutdown] 全局错误处理器已初始化")}registerCleanup($){return this.cleanupHandlers.push($),g1.debug(`[GracefulShutdown] 注册清理函数,当前共 ${this.cleanupHandlers.length} 个`),()=>{let Z=this.cleanupHandlers.indexOf($);if(Z!==-1)this.cleanupHandlers.splice(Z,1),g1.debug(`[GracefulShutdown] 取消注册清理函数,剩余 ${this.cleanupHandlers.length} 个`)}}handleFatalError($,Z){if(this.isShuttingDown){console.error(`[GracefulShutdown] 退出过程中发生额外错误 (${$}):`,Z);return}if(console.error(""),console.error("═".repeat(60)),console.error(`\uD83D\uDCA5 发生未捕获的错误 (${$})`),console.error("═".repeat(60)),console.error(""),console.error("错误信息:",Z.message),console.error(""),Z.stack)console.error("堆栈跟踪:"),console.error(Z.stack);console.error(""),console.error("═".repeat(60)),console.error(""),this.shutdown($,1)}async shutdown($,Z=0){if(this.isShuttingDown){g1.debug("[GracefulShutdown] 已在退出过程中,跳过重复退出");return}this.isShuttingDown=!0,g1.info(`[GracefulShutdown] 开始优雅退出 (原因: ${$})`);try{let Q=M0.getInstance();if(Q.isEnabled()){let J=K0(),G=J.session?.sessionId||"unknown",q=J.config?.config?.permissionMode||"default";await Q.executeSessionEndHooks(YL($),{projectDir:process.cwd(),sessionId:G,permissionMode:q})}}catch(Q){g1.debug("[GracefulShutdown] SessionEnd hooks 执行失败:",Q)}let X=5000,Y=new Promise((Q,J)=>{setTimeout(()=>{J(Error(`清理超时 (${X}ms)`))},X)});try{let Q=this.runCleanupHandlers();await Promise.race([Q,Y]),g1.info("[GracefulShutdown] 所有清理函数执行完成")}catch(Q){console.error("[GracefulShutdown] 清理过程中发生错误:",Q)}finally{HK(),setTimeout(()=>{process.exit(Z)},100)}}async runCleanupHandlers(){let $=[...this.cleanupHandlers].reverse();for(let Z of $)try{let X=Z();if(X instanceof Promise)await X}catch(X){console.error("[GracefulShutdown] 清理函数执行失败:",X)}}isExiting(){return this.isShuttingDown}reset(){this.isShuttingDown=!1,this.cleanupHandlers=[],this.initialized=!1}}var F4=()=>{return K8.getInstance()},FK=($)=>{return F4().registerCleanup($)},OK=()=>{F4().initialize()},W8=($=0)=>{HK(),process.exit($)};G4();C3();y4();r$();s2();X8();import{useMemoizedFn as MU}from"ahooks";import{useEffect as _b,useState as oZ}from"react";X2();q8();C0();i4();U$();B0();import{useMemoizedFn as s$}from"ahooks";import{Box as u2,useApp as Hb}from"ink";import{useEffect as V4,useRef as O9}from"react";E6();U1();i2();import{useShallow as zK}from"zustand/react/shallow";C0();import{useStore as QL}from"zustand";function N0($){return QL(E4,$)}U$();var JL=[],_K=()=>N0(($)=>$.session.sessionId),k6=()=>N0(($)=>$.session.messages),BK=()=>N0(($)=>$.session.clearCount),LK=()=>N0(($)=>$.session.isCompacting),P2=()=>N0(($)=>$.session.actions),wK=()=>N0(($)=>{let{inputTokens:Z,maxContextTokens:X}=$.session.tokenUsage;if(X<=0)return 100;let Y=Math.max(0,100-Z/X*100);return Math.round(Y)}),NK=()=>N0(($)=>$.app.initializationStatus),bK=()=>N0(($)=>$.app.initializationError),f6=()=>N0(($)=>$.app.activeModal),AK=()=>N0(($)=>$.app.todos),RK=()=>N0(($)=>$.app.modelEditorTarget),VK=()=>N0(($)=>$.app.sessionSelectorData),DK=()=>N0(($)=>$.app.awaitingSecondCtrlC),T2=()=>N0(($)=>$.app.actions),h6=()=>N0(($)=>$.app.initializationStatus==="ready"),MK=()=>N0(($)=>$.app.todos.length>0),U8=()=>N0(($)=>$.config.config?.permissionMode||"default"),jK=()=>N0(($)=>$.config.config?.models??JL),x6=()=>N0(($)=>{let Z=$.config.config;if(!Z)return;let X=Z.currentModelId;return Z.models.find((Q)=>Q.id===X)??Z.models[0]}),IK=()=>N0(($)=>$.config.config?.currentModelId),e0=()=>N0(($)=>{let Z=$.config.config?.theme??"default";if(g$.getCurrentThemeName()!==Z)try{g$.setTheme(Z)}catch{}return g$.getTheme()}),o$=()=>N0(($)=>$.focus.currentFocus),yK=()=>N0(($)=>$.focus.actions),S2=()=>N0(($)=>$.command.isProcessing),vK=()=>N0(($)=>$.command.actions),EK=()=>N0(($)=>$.command.pendingCommands),p6=()=>N0(($)=>$.app.thinkingModeEnabled),PK=()=>N0(($)=>$.session.currentThinkingContent),TK=()=>N0(($)=>$.session.thinkingExpanded),SK=()=>N0(($)=>$.session.currentStreamingMessageId),CK=()=>N0(zK(($)=>({lines:$.session.currentStreamingLines,tail:$.session.currentStreamingTail,lineCount:$.session.currentStreamingLineCount,version:$.session.currentStreamingVersion}))),kK=()=>N0(($)=>$.session.finalizingStreamingMessageId),fK=()=>N0(($)=>$.session.historyExpanded),hK=()=>N0(($)=>$.session.expandedMessageCount),xK=()=>N0(zK(($)=>{let Z=$.spec.currentSpec;if(!Z)return{phase:null,completed:0,total:0};let X=Z.tasks??[],Y=X.filter((Q)=>Q.status==="completed").length;return{phase:Z.phase,completed:Y,total:X.length}}));C0();r$();B0();D7();import{useMemoizedFn as C2}from"ahooks";import{useEffect as mK,useRef as z3}from"react";q8();C0();P8();Q2();import{useMemoizedFn as pK}from"ahooks";import{useRef as GL}from"react";function dK($){let Z=GL(void 0),X=pK(async()=>{let Q=await z$.create({systemPrompt:$.systemPrompt,appendSystemPrompt:$.appendSystemPrompt,maxTurns:$.maxTurns});return Z.current=Q,Q}),Y=pK(()=>{if(Z.current)Z.current=void 0});return{agentRef:Z,createAgent:X,cleanupAgent:Y}}var uK=i("UI");function qL($,Z,X,Y){switch($){case"show_theme_selector":return X.setActiveModal("themeSelector"),!0;case"show_model_selector":return X.setActiveModal("modelSelector"),!0;case"show_model_add_wizard":return X.setActiveModal("modelAddWizard"),!0;case"show_permissions_manager":return X.setActiveModal("permissionsManager"),!0;case"show_agents_manager":return X.setActiveModal("agentsManager"),!0;case"show_skills_manager":return X.setActiveModal("skillsManager"),!0;case"show_hooks_manager":return X.setActiveModal("hooksManager"),!0;case"show_plugins_manager":return X.setActiveModal("pluginsManager"),!0;case"show_agent_creation_wizard":return X.setActiveModal("agentCreationWizard"),!0;case"show_session_selector":{let Q=Z?.sessions;return X.showSessionSelector(Q),!0}case"clear_screen":return Y.clearMessages(),Y.setError(null),Y.resetTokenUsage(),X.setTodos([]),!0;case"compact_completed":case"compact_fallback":return Y.resetTokenUsage(),!0;case"exit_application":return W8(0),!0;default:return!1}}function KL($){return typeof $==="object"&&$!==null&&$.action==="invoke_skill"&&typeof $.skillName==="string"}function WL($){return typeof $==="object"&&$!==null&&$.action==="invoke_custom_command"&&typeof $.commandName==="string"&&typeof $.processedContent==="string"}function UL($){return typeof $==="object"&&$!==null&&$.action==="invoke_plugin_command"&&typeof $.commandName==="string"&&typeof $.processedContent==="string"}function HL($){let{text:Z,images:X,parts:Y}=$;if(X.length===0)return Z;let Q=[];for(let J of Y)if(J.type==="text")Q.push({type:"text",text:J.text});else Q.push({type:"image_url",image_url:{url:`data:${J.mimeType};base64,${J.base64}`}});return Q}var gK=($,Z,X,Y)=>{let Q=S2(),J=k6(),G=_K(),q=U8(),K=p6(),W=P2(),U=T2(),H=vK(),F=z3(!1),{createAgent:O,cleanupAgent:z}=dK({systemPrompt:$,appendSystemPrompt:Z,maxTurns:Y}),_=300,B=5,L=400,w=z3(""),R=z3(null),D=z3(""),V=z3(null),I=C2(()=>{if(w.current){let j=w.current,M=W.appendAssistantContent(j);E9(M,j),w.current=""}if(R.current)clearTimeout(R.current),R.current=null}),v=C2(()=>{if(D.current)W.appendThinkingContent(D.current),D.current="";if(V.current)clearTimeout(V.current),V.current=null}),N=(j)=>{let M=0;for(let b of j)if(b===`
|
|
2700
|
+
`)M++;return M},k=C2((j)=>{w.current+=j;let M=w.current;if(N(M)>=5||M.length>=400){I();return}if(!R.current)R.current=setTimeout(I,300)}),m=C2((j)=>{D.current+=j;let M=D.current;if(N(M)>=5||M.length>=400){v();return}if(!V.current)V.current=setTimeout(v,300)}),s=C2(()=>{if(w.current="",R.current)clearTimeout(R.current),R.current=null;if(D.current="",V.current)clearTimeout(V.current),V.current=null});mK(()=>{return()=>{z(),s()}},[z,s]),mK(()=>{if(!K)W.setCurrentThinkingContent(null)},[K,W]);let S=C2(()=>{if(!Q)return;I(),v(),H.abort(),U.setTodos([]);let j=K0().session.currentStreamingMessageId;if(j)P9(j);if(W.finalizeStreamingMessage(),!F.current)W.addAssistantMessage("✋ 任务已停止"),F.current=!0}),T=C2(async(j)=>{let{text:M}=j,b=!1;try{if(J8(M)){await y3();let Q0=H.createAbortController(),R$={cwd:process.cwd(),signal:Q0.signal},V0=await G8(M,R$);if(V0.message){if(qL(V0.message,V0.data,U,W))return{success:!0}}let n1=!1;if(KL(V0.data)){let{skillName:d$,skillArgs:B2}=V0.data,w1=B2?`Please use the "${d$}" skill to help me with: ${B2}`:`Please use the "${d$}" skill.`;W.addUserMessage(w1),b=!0,n1=!0,j={displayText:w1,text:w1,images:[],parts:[{type:"text",text:w1}]}}if(WL(V0.data)){let{commandName:d$,processedContent:B2}=V0.data;W.addUserMessage(M),b=!0,n1=!0;let w1=`# Custom Command: /${d$}
|
|
2701
2701
|
|
|
2702
2702
|
The user has invoked the custom command "/${d$}". Follow the instructions below to complete the task.
|
|
2703
2703
|
|
|
2704
2704
|
---
|
|
2705
2705
|
|
|
2706
|
-
${
|
|
2706
|
+
${B2}
|
|
2707
2707
|
|
|
2708
2708
|
---
|
|
2709
2709
|
|
|
2710
|
-
Remember: Follow the above instructions carefully to complete the user's request.`;j={displayText:M,text:w1,images:[],parts:[{type:"text",text:w1}]}}if(UL(V0.data)){let{commandName:d$,pluginName:
|
|
2710
|
+
Remember: Follow the above instructions carefully to complete the user's request.`;j={displayText:M,text:w1,images:[],parts:[{type:"text",text:w1}]}}if(UL(V0.data)){let{commandName:d$,pluginName:B2,processedContent:w1}=V0.data;W.addUserMessage(M),b=!0,n1=!0;let D8=`# Plugin Command: /${d$}
|
|
2711
2711
|
|
|
2712
|
-
The user has invoked the plugin command "/${d$}" from plugin "${
|
|
2712
|
+
The user has invoked the plugin command "/${d$}" from plugin "${B2}". Follow the instructions below to complete the task.
|
|
2713
2713
|
|
|
2714
2714
|
---
|
|
2715
2715
|
|
|
@@ -2719,7 +2719,7 @@ ${w1}
|
|
|
2719
2719
|
|
|
2720
2720
|
Remember: Follow the above instructions carefully to complete the user's request.`;j={displayText:M,text:D8,images:[],parts:[{type:"text",text:D8}]}}if(!n1){if(!V0.success&&V0.error)return W.addAssistantMessage(`❌ ${V0.error}`),{success:V0.success,output:V0.message,error:V0.error,metadata:V0.data};let d$=V0.message;if(V0.success&&typeof d$==="string"&&d$.trim()!=="")W.addAssistantMessage(d$);return{success:V0.success,output:V0.message,error:V0.error,metadata:V0.data}}}let n=M0.getInstance(),y=j,u,t=await n.executeUserPromptSubmitHooks(j.text,{projectDir:process.cwd(),sessionId:G,permissionMode:q,hasImages:j.images.length>0,imageCount:j.images.length});if(!t.proceed){if(t.warning)W.addAssistantMessage(`⚠️ ${t.warning}`);return{success:!1,error:"blocked by hook"}}if(t.updatedPrompt)y={...j,text:t.updatedPrompt,displayText:t.updatedPrompt,parts:[{type:"text",text:t.updatedPrompt}]};if(t.contextInjection)u=t.contextInjection;if(!b)W.addUserMessage(y.displayText);let g=HL(y),X0=H.createAbortController(),h=await O();if(X0.signal.aborted)return uK.info("[handleCommandSubmit] Agent 创建期间已被中止"),{success:!1,error:"aborted"};let L0=J.map((Q0)=>({role:Q0.role,content:Q0.content}));if(u)L0.push({role:"system",content:`<user-prompt-submit-hook>
|
|
2721
2721
|
${u}
|
|
2722
|
-
</user-prompt-submit-hook>`});let G0={messages:L0,userId:"cli-user",sessionId:G,workspaceRoot:process.cwd(),signal:X0.signal,confirmationHandler:X,permissionMode:q},w0=0,Y$=0,G$=0,r1={stream:!0,onContentDelta:(Q0)=>{w0++,Y$+=Q0.length,W1("useCommandHandler","onContentDelta",{callCount:w0,deltaLen:Q0.length,totalLen:Y$}),k(Q0)},onThinkingDelta:K?(Q0)=>{m(Q0)}:void 0,onThinking:K?(Q0)=>{W.setCurrentThinkingContent(Q0)}:void 0,onStreamEnd:()=>{if(W1("useCommandHandler","onStreamEnd",{contentDeltaCallCount:w0,contentDeltaTotalLen:Y$,remainingBuffer:w.current.length}),R.current)clearTimeout(R.current),R.current=null;if(V.current)clearTimeout(V.current),V.current=null;let Q0=w.current,R$=D.current;w.current="",D.current="";let V0=K0().session.currentStreamingMessageId;if(V0){if(Q0)E9(V0,Q0);P9(V0)}W.finalizeStreamingMessage(Q0,R$)},onContent:(Q0)=>{if(G$++,!Q0.trim())return;W1("useCommandHandler","onContent (non-stream)",{callCount:G$,contentLen:Q0.length}),W.addAssistantMessageAndClearThinking(Q0)},onToolStart:(Q0)=>{if(Q0.type!=="function")return;if(Q0.function.name==="TodoWrite")return;try{let R$=JSON.parse(Q0.function.arguments),V0=H3(Q0.function.name,R$);W.addToolMessage(V0,{toolName:Q0.function.name,phase:"start",summary:V0,params:R$})}catch(R$){uK.error("[useCommandHandler] onToolStart error:",R$)}},onToolResult:async(Q0,R$)=>{if(Q0.type!=="function")return;let V0=R$.metadata?.summary;if(!V0)return;let n1;if(Eq(Q0.function.name,R$))n1=Pq(Q0.function.name,R$)||R$.displayContent;W.addToolMessage(V0,{toolName:Q0.function.name,phase:"complete",summary:V0,detail:n1})},onTokenUsage:(Q0)=>{W.updateTokenUsage(Q0)},onCompacting:(Q0)=>{if(W.setCompacting(Q0),!Q0)W.resetTokenUsage()},onTurnLimitReached:X?async(Q0)=>{let R$=await X.requestConfirmation({type:"maxTurnsExceeded",title:"对话轮次上限",message:`已进行 ${Q0.turnsCount} 轮对话。是否继续?`,risks:["继续执行可能导致更长的等待时间","可能产生更多的 API 费用"]});return{continue:R$.approved,reason:R$.reason}}:void 0},Q$=await h.chat(g,G0,r1);if(!Q$||Q$.trim()===""){if(!F.current&&w0===0)return W.addAssistantMessage("⏹ 已取消"),{success:!0,output:"已取消"};return{success:!0,output:Q$??""}}return{success:!0,output:Q$}}catch(n){if(F.current)return{success:!1,error:"aborted"};let y=n instanceof Error?n.message:"未知错误",u=y.includes("can only concatenate str")||y.includes("image_url")||y.includes("multimodal")||y.includes("vision")||y.includes("does not support images"),t=y;if(u)t="当前模型不支持图片理解功能。请切换到支持视觉能力的模型(如 Claude 4.5、GPT-5.2、Gemini 3 Pro、Qwen3-VL-Plus 等)后重试。";let g={success:!1,error:t};return W.addAssistantMessage(`❌ ${t}`),g}}),c=C4(async(j)=>{if(!j.text.trim()&&j.images.length===0)return;if(Q){H.enqueueCommand({displayText:j.displayText,text:j.text,images:j.images,parts:j.parts});return}U.setTodos([]),F.current=!1;let M=H.createAbortController();s(),W.clearFinalizingStreamingMessageId(),H.setProcessing(!0);try{let b=await T(j);if(!b.success&&b.error&&b.error!=="aborted")W.setError(b.error)}catch(b){if(b instanceof Error&&(b.name==="AbortError"||b.message.includes("aborted")));else{let n=b instanceof Error?b.message:"未知错误";W.setError(`执行失败: ${n}`)}}finally{if(H.getAbortController()===M){H.setProcessing(!1),H.clearAbortController(M),W.setCurrentThinkingContent(null);let y=H.dequeueCommand();if(y)setTimeout(()=>c({displayText:y.displayText,text:y.text,images:y.images,parts:y.parts}),100)}}});return{executeCommand:c,handleAbort:S,isProcessing:Q}};import{useMemoizedFn as d6}from"ahooks";import{useState as cK}from"react";var lK=()=>{let[$,Z]=cK([]),[X,Y]=cK(-1),Q=d6((K,W)=>{let U={display:K,pasteMappings:W?new Map(W):new Map};Z((H)=>[...H,U]),Y(-1)}),J=d6(()=>{if($.length===0)return null;let K=X===-1?$.length-1:Math.max(0,X-1);return Y(K),$[K]||null}),G=d6(()=>{if(X===-1)return null;let K=X+1;if(K>=$.length)return Y(-1),null;else return Y(K),$[K]||null}),q=d6(()=>{Y(-1)});return{commandHistory:$,historyIndex:X,addToHistory:Q,getPreviousCommand:J,getNextCommand:G,resetHistoryIndex:q}};import{useMemoizedFn as iK}from"ahooks";import{useMemo as FL,useState as OL}from"react";var aK=()=>{let[$,Z]=OL({isVisible:!1,details:null,resolver:null}),X=iK((J)=>{return new Promise((G)=>{Z({isVisible:!0,details:J,resolver:G})})}),Y=iK((J)=>{if($.resolver)$.resolver(J);Z({isVisible:!1,details:null,resolver:null})}),Q=FL(()=>({requestConfirmation:X}),[X]);return{confirmationState:$,confirmationHandler:Q,handleResponse:Y}};import{useMemoizedFn as O2}from"ahooks";import{useRef as rK,useState as zL}from"react";var m6="␞",u6="␟";function g6($){return`${m6}PASTE:${$}:`}function qZ(){return u6}var xf=new RegExp(`${m6}PASTE:(\\d+):[\\s\\S]*?${u6}`,"g");function _L($){return $.includes(m6)&&$.includes(u6)}function nK($="",Z=0){let[X,Y]=zL({value:$,cursorPosition:Z}),Q=rK(0),J=rK(new Map),G=O2((O)=>{Y((z)=>({value:O,cursorPosition:z.cursorPosition}));for(let z of J.current.keys()){let _=g6(z);if(!O.includes(_))J.current.delete(z)}}),q=O2((O)=>{Y((z)=>({...z,cursorPosition:Math.max(0,Math.min(O,z.value.length))}))}),K=O2(()=>{Y({value:"",cursorPosition:0}),J.current.clear()}),W=O2((O)=>{Q.current+=1;let z=Q.current;return J.current.set(z,{type:"text",data:O}),z}),U=O2((O,z)=>{Q.current+=1;let _=Q.current;return J.current.set(_,{type:"image",data:O,mimeType:z}),_}),H=O2((O)=>{for(let[z,_]of O)if(J.current.set(z,_),z>=Q.current)Q.current=z}),F=O2((O)=>{let z=[],_=[];if(!_L(O)){let k=O.trim();if(k)_.push({type:"text",text:k});return{displayText:O,text:O,images:z,parts:_}}let B=new RegExp(`${m6}PASTE:(\\d+):[\\s\\S]*?${u6}`,"g"),L=Array.from(O.matchAll(B)),w=0,R="",D="";for(let k of L){let m=k.index,s=m+k[0].length,S=parseInt(k[1],10),T=J.current.get(S);if(m>w){let c=O.slice(w,m);_.push({type:"text",text:c}),R+=c,D+=c}if(!T)R+=k[0],D+=k[0],_.push({type:"text",text:k[0]});else if(T.type==="text")R+=T.data,D+=T.data,_.push({type:"text",text:T.data});else{let c={id:S,base64:T.data,mimeType:T.mimeType};z.push(c),_.push({type:"image",...c}),D+=`[Image #${S}]`}w=s}if(w<O.length){let k=O.slice(w);_.push({type:"text",text:k}),R+=k,D+=k}let V=[];for(let k of _)if(k.type==="text"&&V.length>0&&V[V.length-1].type==="text")V[V.length-1].text+=k.text;else V.push(k);let I=0,v=V.length;while(I<V.length&&V[I].type==="text"&&V[I].text.trim()==="")I++;while(v>I&&V[v-1].type==="text"&&V[v-1].text.trim()==="")v--;let N=V.slice(I,v);return{displayText:D.trim(),text:R.trim(),images:z,parts:N}});return{value:X.value,cursorPosition:X.cursorPosition,setValue:G,setCursorPosition:q,clear:K,pasteMap:J.current,addPasteMapping:W,addImagePasteMapping:U,restorePasteMappings:H,resolveInput:F}}B0();q8();import{useMemoizedFn as ZW}from"ahooks";import{useInput as RL}from"ink";import{useEffect as XW,useRef as YW,useState as HZ}from"react";R6();H6();import BL from"fast-glob";import LL from"fuse.js";import{useEffect as oK,useMemo as KZ,useState as WZ}from"react";var H8=null,wL=5000;function NL($,Z){let X=[...$.matchAll(/(?:^|\s)(@(?:"[^"]*"|(?:[^\\ ]|\\ )*))/g)];for(let Y of X){let Q=Y[1],J=Y.index+(Y[0].length-Q.length),G=J+Q.length;if(Z>=J&&Z<=G){let q=Q.slice(1),K=!1;if(q.startsWith('"')){if(K=!0,q=q.slice(1),q.endsWith('"'))q=q.slice(0,-1)}return{hasQuery:!0,query:q,startIndex:J,endIndex:G,quoted:K}}}return{hasQuery:!1,query:"",startIndex:-1,endIndex:-1,quoted:!1}}var bL=[...p1.map(($)=>`${$}/**`),...p1,...o7.map(($)=>`**/${$}`)];function sK($,Z,X={}){let{cwd:Y=process.cwd(),maxSuggestions:Q=15,ignorePatterns:J=bL,debounceDelay:G=300,fuzzyMatch:q=!0}=X,[K,W]=WZ([]),[U,H]=WZ(!1),[F,O]=WZ(0),z=KZ(()=>JSON.stringify(J),[J]),_=KZ(()=>{if(Z===void 0)return{hasQuery:!1,query:"",startIndex:-1,endIndex:-1,quoted:!1};return NL($,Z)},[$,Z]);oK(()=>{if(!$.includes("@")){W([]),H(!1);return}let L=Date.now();if(H8&&H8.cwd===Y&&H8.ignoreKey===z&&L-H8.timestamp<wL){W(H8.files),H(!1);return}let w=!1,D=setTimeout(async()=>{H(!0);try{let I=(await BL("**/*",{cwd:Y,dot:!1,followSymbolicLinks:!1,onlyFiles:!1,markDirectories:!0,unique:!0,ignore:J})).map((v)=>v.replace(/\\/g,"/"));if(!w)W(I),H8={cwd:Y,ignoreKey:z,files:I,timestamp:L}}catch(V){if(console.error("Failed to load files for @ completion:",V),!w)W([])}finally{if(!w)H(!1)}},G);return()=>{w=!0,clearTimeout(D)}},[$,Y,G,z]);let B=KZ(()=>{if(!_.hasQuery||K.length===0)return[];let L=_.query.toLowerCase();if(L==="")return K.slice(0,Q);if(q)return new LL(K,{threshold:0.4,ignoreLocation:!0,minMatchCharLength:1}).search(L).slice(0,Q).map((D)=>D.item);return K.filter((w)=>w.toLowerCase().includes(L)).slice(0,Q)},[_,K,Q,q]);return oK(()=>{O(0)},[B]),{..._,suggestions:B,selectedIndex:F,loading:U}}function AL($,Z=!1){if($.includes(" ")||Z)return`@"${$}"`;return`@${$}`}function UZ($,Z,X){if(!Z.hasQuery)return{newInput:$,newCursorPos:$.length};let Y=AL(X,Z.quoted),Q=$.slice(0,Z.startIndex),J=$.slice(Z.endIndex),G=Q+Y+" "+J,q=Z.startIndex+Y.length+1;return{newInput:G,newCursorPos:q}}import{useMemoizedFn as tK}from"ahooks";import{useEffect as eK,useRef as $W}from"react";C0();var X$=($,Z)=>{let X=$W(!1),Y=$W(null),Q=tK(()=>{if(Y.current)clearTimeout(Y.current);Y.current=setTimeout(()=>{$4().setAwaitingSecondCtrlC(!1),X.current=!1,Y.current=null},3000)}),J=()=>{F2().shutdown("SIGINT",0)},G=tK(()=>{if(!X.current){if(X.current=!0,$&&Z)Z();$4().setAwaitingSecondCtrlC(!0),Q()}else{if(Y.current)clearTimeout(Y.current),Y.current=null;$4().setAwaitingSecondCtrlC(!1),J()}});return eK(()=>{if($){if($4().setAwaitingSecondCtrlC(!1),X.current=!1,Y.current)clearTimeout(Y.current),Y.current=null}},[$]),eK(()=>{return()=>{if(Y.current)clearTimeout(Y.current)}},[]),G};var c6=i("UI"),QW=($,Z,X,Y,Q,J,G,q,K,W)=>{let H=o$()==="main-input",F=$.value,O=$.setValue,z=$.cursorPosition,_=P4(),B=T4(),L=x6(),w=L?t2(L):!1,[R,D]=HZ(!1),[V,I]=HZ([]),[v,N]=HZ(0),k=sK(F,z,{cwd:process.cwd(),maxSuggestions:10}),m=X$(G||!1,J),s=YW(0),S=500,T=YW(!1);XW(()=>{if(G)T.current=!1},[G]),XW(()=>{if(k.hasQuery&&k.suggestions.length>0){let M=k.suggestions.map((b)=>({command:b,description:b.endsWith("/")?`Directory: ${b}`:`File: ${b}`,matchScore:1}));I(M),D(!0),N(0)}else if(F.startsWith("/"))if(F.includes(" "))D(!1),I([]);else{let b=$K(F);I(b),D(b.length>0),N(0)}else D(!1),I([])},[F,k.hasQuery,k.suggestions]);let c=ZW(()=>{_.clearMessages(),_.setError(null)}),j=ZW(()=>{c6.debug("[DIAG] handleSubmit called:",{input:F,showSuggestions:R});let M=F.trim();if(M){let b=$.resolveInput(M);c6.debug("[DIAG] Submitting command:",{displayText:M,textLength:b.text.length,imageCount:b.images.length}),D(!1),I([]);let n=$.pasteMap.size>0?new Map($.pasteMap):new Map;Q(M,n),$.clear(),Z(b),c6.debug("[DIAG] Command submitted to onSubmit callback")}else c6.debug("[DIAG] Empty command, not submitting")});return RL((M,b)=>{if(M==="?"&&!F){K?.(),setTimeout(()=>$.clear(),0);return}if(b.backspace||b.delete||b.leftArrow||b.rightArrow||b.pageUp||b.pageDown||!b.ctrl&&!b.meta&&!b.escape&&!b.tab&&!b.upArrow&&!b.downArrow&&!b.return&&!(M==="?"&&!F))return;if(b.ctrl&&M==="c"||b.meta&&M==="c"||b.ctrl&&M==="d"||b.meta&&M==="d"){m();return}if(b.ctrl&&M==="l"||b.meta&&M==="l"){c();return}if(b.ctrl&&M==="t"||b.meta&&M==="t"){_.toggleThinkingExpanded();return}if(b.ctrl&&M==="o"||b.meta&&M==="o"){_.toggleHistoryExpanded();return}if(b.escape){if(W)K?.();else if(G&&J){if(T.current)return;T.current=!0,J()}else if(R)D(!1),I([]);else if(F){let y=Date.now();if(y-s.current<500)$.clear(),s.current=0;else s.current=y}return}if(b.tab&&b.shift){q?.();return}if(b.tab){if(R&&V.length>0){let y=V[v].command;if(k.hasQuery&&k.suggestions.includes(y)){let{newInput:u,newCursorPos:t}=UZ(F,k,y);O(u),$.setCursorPosition(t)}else{let u=y+" ";O(u),$.setCursorPosition(u.length)}D(!1),I([])}else if(w)B.toggleThinkingMode();return}if(b.return){if(R&&V.length>0){let y=V[v].command;if(k.hasQuery&&k.suggestions.includes(y)){let{newInput:u,newCursorPos:t}=UZ(F,k,y);O(u),$.setCursorPosition(t)}else{let u=y+" ";O(u),$.setCursorPosition(u.length)}D(!1),I([])}else j();return}if(b.upArrow){if(R&&V.length>0){let y=V.length-1;N((u)=>u>0?u-1:y)}else{let y=X();if(y){if(y.pasteMappings.size>0)$.restorePasteMappings(y.pasteMappings);O(y.display),$.setCursorPosition(y.display.length)}}return}if(b.downArrow){if(R&&V.length>0){let y=V.length-1;N((u)=>u<y?u+1:0)}else{let y=Y();if(y){if(y.pasteMappings.size>0)$.restorePasteMappings(y.pasteMappings);O(y.display),$.setCursorPosition(y.display.length)}}return}},{isActive:H}),{handleSubmit:j,showSuggestions:R,suggestions:V,selectedSuggestionIndex:v}};import IL from"ansi-escapes";import{useStdout as yL}from"ink";import{useCallback as vL,useEffect as EL,useRef as PL}from"react";import{useStdout as VL}from"ink";import{debounce as DL}from"lodash-es";import{useEffect as ML,useState as jL}from"react";function F8($=200){let{stdout:Z}=VL(),[X,Y]=jL(Z.columns||80);return ML(()=>{let Q=DL(()=>{Y(Z.columns||80)},$);return Q(),Z.on("resize",Q),()=>{Z.off("resize",Q),Q.cancel()}},[Z,$]),X}function JW(){let{stdout:$}=yL(),Z=F8(),X=PL(!0),Y=N0((J)=>J.session.actions.incrementClearCount),Q=vL(()=>{if($)$.write(IL.clearTerminal);Y()},[$,Y]);return EL(()=>{if(X.current){X.current=!1;return}let J=setTimeout(()=>{Q()},300);return()=>{clearTimeout(J)}},[Z,Q]),{refreshStatic:Q}}Q4();import GW from"node:fs";import TL from"node:os";import FZ from"node:path";import{MultiSelect as SL}from"@inkjs/ui";import{useMemoizedFn as l6}from"ahooks";import{Box as W0,Text as $0,useFocus as CL,useFocusManager as kL,useInput as KW}from"ink";import i6 from"ink-select-input";import fL from"ink-spinner";import _3 from"ink-text-input";import{useEffect as qW,useState as O8}from"react";import{jsxDEV as C}from"react/jsx-dev-runtime";var hL=[{label:"\uD83D\uDD0D Glob - 文件搜索",value:"Glob"},{label:"\uD83D\uDD0E Grep - 内容搜索",value:"Grep"},{label:"\uD83D\uDCD6 Read - 读取文件",value:"Read"},{label:"✍️ Write - 写入文件",value:"Write"},{label:"✏️ Edit - 编辑文件",value:"Edit"},{label:"\uD83D\uDCBB Bash - 执行命令",value:"Bash"},{label:"✅ 所有工具 (不限制)",value:"all"}],xL=[{label:"\uD83D\uDD34 红色 (red)",value:"red"},{label:"\uD83D\uDD35 蓝色 (blue)",value:"blue"},{label:"\uD83D\uDFE2 绿色 (green)",value:"green"},{label:"\uD83D\uDFE1 黄色 (yellow)",value:"yellow"},{label:"\uD83D\uDFE3 紫色 (purple)",value:"purple"},{label:"\uD83D\uDFE0 橙色 (orange)",value:"orange"},{label:"\uD83E\uDE77 粉色 (pink)",value:"pink"},{label:"\uD83E\uDE75 青色 (cyan)",value:"cyan"},{label:"⚪ 不设置颜色",value:"none"}];function pL($){if(!$||$.trim()==="")return"名称不能为空";if(!/^[a-z0-9-]+$/.test($))return"名称只能包含小写字母、数字和连字符";if($.startsWith("-")||$.endsWith("-"))return"名称不能以连字符开头或结尾";return null}function B3({onComplete:$,onCancel:Z,initialConfig:X}){let[Y,Q]=O8(X?"name":"mode"),[J,G]=O8({name:X?.name||"",description:X?.description||"",tools:X?.tools||[],color:X?.color,location:X?.location||"project",systemPrompt:X?.systemPrompt||""}),[q,K]=O8(""),[W,U]=O8(!1),[H,F]=O8(""),[O,z]=O8(X?"edit":"manual"),{focus:_}=kL(),L={manual:["mode","name","description","tools","color","location","systemPrompt","confirm"],ai:["mode","aiPrompt","aiGenerating","confirm"],edit:["name","description","tools","color","location","systemPrompt","confirm"]}[O];qW(()=>{if(Y==="name"||Y==="description"||Y==="systemPrompt"||Y==="aiPrompt")return;_(`step-${Y}`)},[Y,_]);let w=l6(()=>{let v=L.indexOf(Y);if(v<L.length-1)Q(L[v+1])}),R=l6(()=>{if(H)F("");if(Y==="confirm"&&O==="ai"){Q("aiPrompt");return}let v=L.indexOf(Y);if(v>0)Q(L[v-1]);else Z()}),D=l6(async()=>{U(!0),F("");try{let v=await z$.create(),N=`你是一个 Subagent 配置生成专家。用户会描述他们想要创建的 agent,你需要根据描述生成一个完整的 agent 配置。
|
|
2722
|
+
</user-prompt-submit-hook>`});let G0={messages:L0,userId:"cli-user",sessionId:G,workspaceRoot:process.cwd(),signal:X0.signal,confirmationHandler:X,permissionMode:q},w0=0,Y$=0,G$=0,r1={stream:!0,onContentDelta:(Q0)=>{w0++,Y$+=Q0.length,W1("useCommandHandler","onContentDelta",{callCount:w0,deltaLen:Q0.length,totalLen:Y$}),k(Q0)},onThinkingDelta:K?(Q0)=>{m(Q0)}:void 0,onThinking:K?(Q0)=>{W.setCurrentThinkingContent(Q0)}:void 0,onStreamEnd:()=>{if(W1("useCommandHandler","onStreamEnd",{contentDeltaCallCount:w0,contentDeltaTotalLen:Y$,remainingBuffer:w.current.length}),R.current)clearTimeout(R.current),R.current=null;if(V.current)clearTimeout(V.current),V.current=null;let Q0=w.current,R$=D.current;w.current="",D.current="";let V0=K0().session.currentStreamingMessageId;if(V0){if(Q0)E9(V0,Q0);P9(V0)}W.finalizeStreamingMessage(Q0,R$)},onContent:(Q0)=>{if(G$++,!Q0.trim())return;W1("useCommandHandler","onContent (non-stream)",{callCount:G$,contentLen:Q0.length}),W.addAssistantMessageAndClearThinking(Q0)},onToolStart:(Q0)=>{if(Q0.type!=="function")return;if(Q0.function.name==="TodoWrite")return;try{let R$=JSON.parse(Q0.function.arguments),V0=H3(Q0.function.name,R$);W.addToolMessage(V0,{toolName:Q0.function.name,phase:"start",summary:V0,params:R$})}catch(R$){uK.error("[useCommandHandler] onToolStart error:",R$)}},onToolResult:async(Q0,R$)=>{if(Q0.type!=="function")return;let V0=R$.metadata?.summary;if(!V0)return;let n1;if(Eq(Q0.function.name,R$))n1=Pq(Q0.function.name,R$)||R$.displayContent;W.addToolMessage(V0,{toolName:Q0.function.name,phase:"complete",summary:V0,detail:n1})},onTokenUsage:(Q0)=>{W.updateTokenUsage(Q0)},onCompacting:(Q0)=>{if(W.setCompacting(Q0),!Q0)W.resetTokenUsage()},onTurnLimitReached:X?async(Q0)=>{let R$=await X.requestConfirmation({type:"maxTurnsExceeded",title:"对话轮次上限",message:`已进行 ${Q0.turnsCount} 轮对话。是否继续?`,risks:["继续执行可能导致更长的等待时间","可能产生更多的 API 费用"]});return{continue:R$.approved,reason:R$.reason}}:void 0},Q$=await h.chat(g,G0,r1);if(!Q$||Q$.trim()===""){if(!F.current&&w0===0)return W.addAssistantMessage("⏹ 已取消"),{success:!0,output:"已取消"};return{success:!0,output:Q$??""}}return{success:!0,output:Q$}}catch(n){if(F.current)return{success:!1,error:"aborted"};let y=n instanceof Error?n.message:"未知错误",u=y.includes("can only concatenate str")||y.includes("image_url")||y.includes("multimodal")||y.includes("vision")||y.includes("does not support images"),t=y;if(u)t="当前模型不支持图片理解功能。请切换到支持视觉能力的模型(如 Claude 4.5、GPT-5.2、Gemini 3 Pro、Qwen3-VL-Plus 等)后重试。";let g={success:!1,error:t};return W.addAssistantMessage(`❌ ${t}`),g}}),c=C2(async(j)=>{if(!j.text.trim()&&j.images.length===0)return;if(Q){H.enqueueCommand({displayText:j.displayText,text:j.text,images:j.images,parts:j.parts});return}U.setTodos([]),F.current=!1;let M=H.createAbortController();s(),W.clearFinalizingStreamingMessageId(),H.setProcessing(!0);try{let b=await T(j);if(!b.success&&b.error&&b.error!=="aborted")W.setError(b.error)}catch(b){if(b instanceof Error&&(b.name==="AbortError"||b.message.includes("aborted")));else{let n=b instanceof Error?b.message:"未知错误";W.setError(`执行失败: ${n}`)}}finally{if(H.getAbortController()===M){H.setProcessing(!1),H.clearAbortController(M),W.setCurrentThinkingContent(null);let y=H.dequeueCommand();if(y)setTimeout(()=>c({displayText:y.displayText,text:y.text,images:y.images,parts:y.parts}),100)}}});return{executeCommand:c,handleAbort:S,isProcessing:Q}};import{useMemoizedFn as d6}from"ahooks";import{useState as cK}from"react";var lK=()=>{let[$,Z]=cK([]),[X,Y]=cK(-1),Q=d6((K,W)=>{let U={display:K,pasteMappings:W?new Map(W):new Map};Z((H)=>[...H,U]),Y(-1)}),J=d6(()=>{if($.length===0)return null;let K=X===-1?$.length-1:Math.max(0,X-1);return Y(K),$[K]||null}),G=d6(()=>{if(X===-1)return null;let K=X+1;if(K>=$.length)return Y(-1),null;else return Y(K),$[K]||null}),q=d6(()=>{Y(-1)});return{commandHistory:$,historyIndex:X,addToHistory:Q,getPreviousCommand:J,getNextCommand:G,resetHistoryIndex:q}};import{useMemoizedFn as iK}from"ahooks";import{useMemo as FL,useState as OL}from"react";var aK=()=>{let[$,Z]=OL({isVisible:!1,details:null,resolver:null}),X=iK((J)=>{return new Promise((G)=>{Z({isVisible:!0,details:J,resolver:G})})}),Y=iK((J)=>{if($.resolver)$.resolver(J);Z({isVisible:!1,details:null,resolver:null})}),Q=FL(()=>({requestConfirmation:X}),[X]);return{confirmationState:$,confirmationHandler:Q,handleResponse:Y}};import{useMemoizedFn as O4}from"ahooks";import{useRef as rK,useState as zL}from"react";var m6="␞",u6="␟";function g6($){return`${m6}PASTE:${$}:`}function qZ(){return u6}var xf=new RegExp(`${m6}PASTE:(\\d+):[\\s\\S]*?${u6}`,"g");function _L($){return $.includes(m6)&&$.includes(u6)}function nK($="",Z=0){let[X,Y]=zL({value:$,cursorPosition:Z}),Q=rK(0),J=rK(new Map),G=O4((O)=>{Y((z)=>({value:O,cursorPosition:z.cursorPosition}));for(let z of J.current.keys()){let _=g6(z);if(!O.includes(_))J.current.delete(z)}}),q=O4((O)=>{Y((z)=>({...z,cursorPosition:Math.max(0,Math.min(O,z.value.length))}))}),K=O4(()=>{Y({value:"",cursorPosition:0}),J.current.clear()}),W=O4((O)=>{Q.current+=1;let z=Q.current;return J.current.set(z,{type:"text",data:O}),z}),U=O4((O,z)=>{Q.current+=1;let _=Q.current;return J.current.set(_,{type:"image",data:O,mimeType:z}),_}),H=O4((O)=>{for(let[z,_]of O)if(J.current.set(z,_),z>=Q.current)Q.current=z}),F=O4((O)=>{let z=[],_=[];if(!_L(O)){let k=O.trim();if(k)_.push({type:"text",text:k});return{displayText:O,text:O,images:z,parts:_}}let B=new RegExp(`${m6}PASTE:(\\d+):[\\s\\S]*?${u6}`,"g"),L=Array.from(O.matchAll(B)),w=0,R="",D="";for(let k of L){let m=k.index,s=m+k[0].length,S=parseInt(k[1],10),T=J.current.get(S);if(m>w){let c=O.slice(w,m);_.push({type:"text",text:c}),R+=c,D+=c}if(!T)R+=k[0],D+=k[0],_.push({type:"text",text:k[0]});else if(T.type==="text")R+=T.data,D+=T.data,_.push({type:"text",text:T.data});else{let c={id:S,base64:T.data,mimeType:T.mimeType};z.push(c),_.push({type:"image",...c}),D+=`[Image #${S}]`}w=s}if(w<O.length){let k=O.slice(w);_.push({type:"text",text:k}),R+=k,D+=k}let V=[];for(let k of _)if(k.type==="text"&&V.length>0&&V[V.length-1].type==="text")V[V.length-1].text+=k.text;else V.push(k);let I=0,v=V.length;while(I<V.length&&V[I].type==="text"&&V[I].text.trim()==="")I++;while(v>I&&V[v-1].type==="text"&&V[v-1].text.trim()==="")v--;let N=V.slice(I,v);return{displayText:D.trim(),text:R.trim(),images:z,parts:N}});return{value:X.value,cursorPosition:X.cursorPosition,setValue:G,setCursorPosition:q,clear:K,pasteMap:J.current,addPasteMapping:W,addImagePasteMapping:U,restorePasteMappings:H,resolveInput:F}}B0();q8();import{useMemoizedFn as ZW}from"ahooks";import{useInput as RL}from"ink";import{useEffect as XW,useRef as YW,useState as HZ}from"react";R6();H6();import BL from"fast-glob";import LL from"fuse.js";import{useEffect as oK,useMemo as KZ,useState as WZ}from"react";var H8=null,wL=5000;function NL($,Z){let X=[...$.matchAll(/(?:^|\s)(@(?:"[^"]*"|(?:[^\\ ]|\\ )*))/g)];for(let Y of X){let Q=Y[1],J=Y.index+(Y[0].length-Q.length),G=J+Q.length;if(Z>=J&&Z<=G){let q=Q.slice(1),K=!1;if(q.startsWith('"')){if(K=!0,q=q.slice(1),q.endsWith('"'))q=q.slice(0,-1)}return{hasQuery:!0,query:q,startIndex:J,endIndex:G,quoted:K}}}return{hasQuery:!1,query:"",startIndex:-1,endIndex:-1,quoted:!1}}var bL=[...p1.map(($)=>`${$}/**`),...p1,...o7.map(($)=>`**/${$}`)];function sK($,Z,X={}){let{cwd:Y=process.cwd(),maxSuggestions:Q=15,ignorePatterns:J=bL,debounceDelay:G=300,fuzzyMatch:q=!0}=X,[K,W]=WZ([]),[U,H]=WZ(!1),[F,O]=WZ(0),z=KZ(()=>JSON.stringify(J),[J]),_=KZ(()=>{if(Z===void 0)return{hasQuery:!1,query:"",startIndex:-1,endIndex:-1,quoted:!1};return NL($,Z)},[$,Z]);oK(()=>{if(!$.includes("@")){W([]),H(!1);return}let L=Date.now();if(H8&&H8.cwd===Y&&H8.ignoreKey===z&&L-H8.timestamp<wL){W(H8.files),H(!1);return}let w=!1,D=setTimeout(async()=>{H(!0);try{let I=(await BL("**/*",{cwd:Y,dot:!1,followSymbolicLinks:!1,onlyFiles:!1,markDirectories:!0,unique:!0,ignore:J})).map((v)=>v.replace(/\\/g,"/"));if(!w)W(I),H8={cwd:Y,ignoreKey:z,files:I,timestamp:L}}catch(V){if(console.error("Failed to load files for @ completion:",V),!w)W([])}finally{if(!w)H(!1)}},G);return()=>{w=!0,clearTimeout(D)}},[$,Y,G,z]);let B=KZ(()=>{if(!_.hasQuery||K.length===0)return[];let L=_.query.toLowerCase();if(L==="")return K.slice(0,Q);if(q)return new LL(K,{threshold:0.4,ignoreLocation:!0,minMatchCharLength:1}).search(L).slice(0,Q).map((D)=>D.item);return K.filter((w)=>w.toLowerCase().includes(L)).slice(0,Q)},[_,K,Q,q]);return oK(()=>{O(0)},[B]),{..._,suggestions:B,selectedIndex:F,loading:U}}function AL($,Z=!1){if($.includes(" ")||Z)return`@"${$}"`;return`@${$}`}function UZ($,Z,X){if(!Z.hasQuery)return{newInput:$,newCursorPos:$.length};let Y=AL(X,Z.quoted),Q=$.slice(0,Z.startIndex),J=$.slice(Z.endIndex),G=Q+Y+" "+J,q=Z.startIndex+Y.length+1;return{newInput:G,newCursorPos:q}}import{useMemoizedFn as tK}from"ahooks";import{useEffect as eK,useRef as $W}from"react";C0();var X$=($,Z)=>{let X=$W(!1),Y=$W(null),Q=tK(()=>{if(Y.current)clearTimeout(Y.current);Y.current=setTimeout(()=>{$2().setAwaitingSecondCtrlC(!1),X.current=!1,Y.current=null},3000)}),J=()=>{F4().shutdown("SIGINT",0)},G=tK(()=>{if(!X.current){if(X.current=!0,$&&Z)Z();$2().setAwaitingSecondCtrlC(!0),Q()}else{if(Y.current)clearTimeout(Y.current),Y.current=null;$2().setAwaitingSecondCtrlC(!1),J()}});return eK(()=>{if($){if($2().setAwaitingSecondCtrlC(!1),X.current=!1,Y.current)clearTimeout(Y.current),Y.current=null}},[$]),eK(()=>{return()=>{if(Y.current)clearTimeout(Y.current)}},[]),G};var c6=i("UI"),QW=($,Z,X,Y,Q,J,G,q,K,W)=>{let H=o$()==="main-input",F=$.value,O=$.setValue,z=$.cursorPosition,_=P2(),B=T2(),L=x6(),w=L?t4(L):!1,[R,D]=HZ(!1),[V,I]=HZ([]),[v,N]=HZ(0),k=sK(F,z,{cwd:process.cwd(),maxSuggestions:10}),m=X$(G||!1,J),s=YW(0),S=500,T=YW(!1);XW(()=>{if(G)T.current=!1},[G]),XW(()=>{if(k.hasQuery&&k.suggestions.length>0){let M=k.suggestions.map((b)=>({command:b,description:b.endsWith("/")?`Directory: ${b}`:`File: ${b}`,matchScore:1}));I(M),D(!0),N(0)}else if(F.startsWith("/"))if(F.includes(" "))D(!1),I([]);else{let b=$K(F);I(b),D(b.length>0),N(0)}else D(!1),I([])},[F,k.hasQuery,k.suggestions]);let c=ZW(()=>{_.clearMessages(),_.setError(null)}),j=ZW(()=>{c6.debug("[DIAG] handleSubmit called:",{input:F,showSuggestions:R});let M=F.trim();if(M){let b=$.resolveInput(M);c6.debug("[DIAG] Submitting command:",{displayText:M,textLength:b.text.length,imageCount:b.images.length}),D(!1),I([]);let n=$.pasteMap.size>0?new Map($.pasteMap):new Map;Q(M,n),$.clear(),Z(b),c6.debug("[DIAG] Command submitted to onSubmit callback")}else c6.debug("[DIAG] Empty command, not submitting")});return RL((M,b)=>{if(M==="?"&&!F){K?.(),setTimeout(()=>$.clear(),0);return}if(b.backspace||b.delete||b.leftArrow||b.rightArrow||b.pageUp||b.pageDown||!b.ctrl&&!b.meta&&!b.escape&&!b.tab&&!b.upArrow&&!b.downArrow&&!b.return&&!(M==="?"&&!F))return;if(b.ctrl&&M==="c"||b.meta&&M==="c"||b.ctrl&&M==="d"||b.meta&&M==="d"){m();return}if(b.ctrl&&M==="l"||b.meta&&M==="l"){c();return}if(b.ctrl&&M==="t"||b.meta&&M==="t"){_.toggleThinkingExpanded();return}if(b.ctrl&&M==="o"||b.meta&&M==="o"){_.toggleHistoryExpanded();return}if(b.escape){if(W)K?.();else if(G&&J){if(T.current)return;T.current=!0,J()}else if(R)D(!1),I([]);else if(F){let y=Date.now();if(y-s.current<500)$.clear(),s.current=0;else s.current=y}return}if(b.tab&&b.shift){q?.();return}if(b.tab){if(R&&V.length>0){let y=V[v].command;if(k.hasQuery&&k.suggestions.includes(y)){let{newInput:u,newCursorPos:t}=UZ(F,k,y);O(u),$.setCursorPosition(t)}else{let u=y+" ";O(u),$.setCursorPosition(u.length)}D(!1),I([])}else if(w)B.toggleThinkingMode();return}if(b.return){if(R&&V.length>0){let y=V[v].command;if(k.hasQuery&&k.suggestions.includes(y)){let{newInput:u,newCursorPos:t}=UZ(F,k,y);O(u),$.setCursorPosition(t)}else{let u=y+" ";O(u),$.setCursorPosition(u.length)}D(!1),I([])}else j();return}if(b.upArrow){if(R&&V.length>0){let y=V.length-1;N((u)=>u>0?u-1:y)}else{let y=X();if(y){if(y.pasteMappings.size>0)$.restorePasteMappings(y.pasteMappings);O(y.display),$.setCursorPosition(y.display.length)}}return}if(b.downArrow){if(R&&V.length>0){let y=V.length-1;N((u)=>u<y?u+1:0)}else{let y=Y();if(y){if(y.pasteMappings.size>0)$.restorePasteMappings(y.pasteMappings);O(y.display),$.setCursorPosition(y.display.length)}}return}},{isActive:H}),{handleSubmit:j,showSuggestions:R,suggestions:V,selectedSuggestionIndex:v}};import IL from"ansi-escapes";import{useStdout as yL}from"ink";import{useCallback as vL,useEffect as EL,useRef as PL}from"react";import{useStdout as VL}from"ink";import{debounce as DL}from"lodash-es";import{useEffect as ML,useState as jL}from"react";function F8($=200){let{stdout:Z}=VL(),[X,Y]=jL(Z.columns||80);return ML(()=>{let Q=DL(()=>{Y(Z.columns||80)},$);return Q(),Z.on("resize",Q),()=>{Z.off("resize",Q),Q.cancel()}},[Z,$]),X}function JW(){let{stdout:$}=yL(),Z=F8(),X=PL(!0),Y=N0((J)=>J.session.actions.incrementClearCount),Q=vL(()=>{if($)$.write(IL.clearTerminal);Y()},[$,Y]);return EL(()=>{if(X.current){X.current=!1;return}let J=setTimeout(()=>{Q()},300);return()=>{clearTimeout(J)}},[Z,Q]),{refreshStatic:Q}}Q2();import GW from"node:fs";import TL from"node:os";import FZ from"node:path";import{MultiSelect as SL}from"@inkjs/ui";import{useMemoizedFn as l6}from"ahooks";import{Box as W0,Text as $0,useFocus as CL,useFocusManager as kL,useInput as KW}from"ink";import i6 from"ink-select-input";import fL from"ink-spinner";import _3 from"ink-text-input";import{useEffect as qW,useState as O8}from"react";import{jsxDEV as C}from"react/jsx-dev-runtime";var hL=[{label:"\uD83D\uDD0D Glob - 文件搜索",value:"Glob"},{label:"\uD83D\uDD0E Grep - 内容搜索",value:"Grep"},{label:"\uD83D\uDCD6 Read - 读取文件",value:"Read"},{label:"✍️ Write - 写入文件",value:"Write"},{label:"✏️ Edit - 编辑文件",value:"Edit"},{label:"\uD83D\uDCBB Bash - 执行命令",value:"Bash"},{label:"✅ 所有工具 (不限制)",value:"all"}],xL=[{label:"\uD83D\uDD34 红色 (red)",value:"red"},{label:"\uD83D\uDD35 蓝色 (blue)",value:"blue"},{label:"\uD83D\uDFE2 绿色 (green)",value:"green"},{label:"\uD83D\uDFE1 黄色 (yellow)",value:"yellow"},{label:"\uD83D\uDFE3 紫色 (purple)",value:"purple"},{label:"\uD83D\uDFE0 橙色 (orange)",value:"orange"},{label:"\uD83E\uDE77 粉色 (pink)",value:"pink"},{label:"\uD83E\uDE75 青色 (cyan)",value:"cyan"},{label:"⚪ 不设置颜色",value:"none"}];function pL($){if(!$||$.trim()==="")return"名称不能为空";if(!/^[a-z0-9-]+$/.test($))return"名称只能包含小写字母、数字和连字符";if($.startsWith("-")||$.endsWith("-"))return"名称不能以连字符开头或结尾";return null}function B3({onComplete:$,onCancel:Z,initialConfig:X}){let[Y,Q]=O8(X?"name":"mode"),[J,G]=O8({name:X?.name||"",description:X?.description||"",tools:X?.tools||[],color:X?.color,location:X?.location||"project",systemPrompt:X?.systemPrompt||""}),[q,K]=O8(""),[W,U]=O8(!1),[H,F]=O8(""),[O,z]=O8(X?"edit":"manual"),{focus:_}=kL(),L={manual:["mode","name","description","tools","color","location","systemPrompt","confirm"],ai:["mode","aiPrompt","aiGenerating","confirm"],edit:["name","description","tools","color","location","systemPrompt","confirm"]}[O];qW(()=>{if(Y==="name"||Y==="description"||Y==="systemPrompt"||Y==="aiPrompt")return;_(`step-${Y}`)},[Y,_]);let w=l6(()=>{let v=L.indexOf(Y);if(v<L.length-1)Q(L[v+1])}),R=l6(()=>{if(H)F("");if(Y==="confirm"&&O==="ai"){Q("aiPrompt");return}let v=L.indexOf(Y);if(v>0)Q(L[v-1]);else Z()}),D=l6(async()=>{U(!0),F("");try{let v=await z$.create(),N=`你是一个 Subagent 配置生成专家。用户会描述他们想要创建的 agent,你需要根据描述生成一个完整的 agent 配置。
|
|
2723
2723
|
|
|
2724
2724
|
## 可用工具列表
|
|
2725
2725
|
|
|
@@ -2795,34 +2795,34 @@ ${u}
|
|
|
2795
2795
|
|
|
2796
2796
|
**重要**:请直接返回 JSON,不要添加任何额外的解释或文字。`,q)).trim(),s=m.match(/```(?:json)?\s*\n([\s\S]*?)\n```/);if(s)m=s[1];let S=JSON.parse(m);if(!S.name||!S.description||!S.systemPrompt)throw Error("Missing required fields: name, description, or systemPrompt");if(!/^[a-z0-9]+(-[a-z0-9]+)*$/.test(S.name))throw Error("Invalid name format. Must be kebab-case (lowercase, numbers, hyphens only)");G({name:S.name,description:S.description,tools:Array.isArray(S.tools)?S.tools:[],color:S.color||"blue",location:"project",systemPrompt:S.systemPrompt}),Q("confirm")}catch(v){F(v instanceof Error?v.message:String(v))}finally{U(!1)}});qW(()=>{if(Y==="aiGenerating"&&!W&&!H)D()},[Y,W,H,D]);let V=l6(async()=>{try{let v=J.location==="project"?FZ.join(process.cwd(),".blade","agents"):FZ.join(TL.homedir(),".blade","agents");await GW.promises.mkdir(v,{recursive:!0});let N=["---",`name: ${J.name}`,`description: ${J.description}`];if(J.tools.length>0&&!J.tools.includes("all")){N.push("tools:");for(let s of J.tools)N.push(` - ${s}`)}if(J.color)N.push(`color: ${J.color}`);N.push("---");let k=[N.join(`
|
|
2797
2797
|
`),"",`# ${J.name} Subagent`,"",J.systemPrompt||"你是一个专门的代理,负责执行特定任务。",""].join(`
|
|
2798
|
-
`),m=FZ.join(v,`${J.name}.md`);await GW.promises.writeFile(m,k,"utf-8"),$()}catch(v){console.error("保存配置失败:",v)}}),I=X$(!1,Z);if(KW((v,N)=>{if(N.escape)R();else if(N.ctrl&&v==="c"||N.meta&&v==="c")I()},{isActive:Y!=="tools"}),Y==="mode")return C(W0,{flexDirection:"column",paddingY:1,children:[C(W0,{marginBottom:1,children:C($0,{bold:!0,color:"cyan",children:"\uD83C\uDFAF 选择创建方式"},void 0,!1,void 0,this)},void 0,!1,void 0,this),C(W0,{marginBottom:1,children:C($0,{dimColor:!0,children:"你可以手动配置每个细节,或让 AI 根据你的描述自动生成配置"},void 0,!1,void 0,this)},void 0,!1,void 0,this),C(i6,{items:[{label:"\uD83E\uDD16 AI 智能生成 - 根据描述自动生成完整配置",value:"ai"},{label:"✍️ 手动配置 - 逐步配置每个选项",value:"manual"}],onSelect:(v)=>{if(v.value==="ai")z("ai"),Q("aiPrompt");else z("manual"),Q("name")}},void 0,!1,void 0,this),C(W0,{marginTop:1,children:C($0,{dimColor:!0,children:"使用方向键选择 | Enter 确认 | ESC 取消"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this);if(Y==="aiPrompt")return C(W0,{flexDirection:"column",paddingY:1,children:[C(W0,{marginBottom:1,children:C($0,{bold:!0,color:"cyan",children:"\uD83E\uDD16 AI 智能生成"},void 0,!1,void 0,this)},void 0,!1,void 0,this),C(W0,{marginBottom:1,children:C($0,{dimColor:!0,children:'描述你想要创建的 Agent(例如:"一个专门用于代码审查的 agent,能够分析代码质量和潜在bug")'},void 0,!1,void 0,this)},void 0,!1,void 0,this),C(W0,{marginBottom:1,children:[C($0,{color:"green",children:"描述: "},void 0,!1,void 0,this),C(_3,{value:q,onChange:K,onSubmit:(v)=>{if(!v.trim())return;Q("aiGenerating")}},void 0,!1,void 0,this)]},void 0,!0,void 0,this),C(W0,{children:C($0,{dimColor:!0,children:"按 Enter 开始生成 | ESC 返回"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this);if(Y==="aiGenerating"){if(H)return C(W0,{flexDirection:"column",paddingY:1,children:[C(W0,{marginBottom:1,children:C($0,{bold:!0,color:"red",children:"❌ AI 生成失败"},void 0,!1,void 0,this)},void 0,!1,void 0,this),C(W0,{marginBottom:1,children:C($0,{color:"red",children:H},void 0,!1,void 0,this)},void 0,!1,void 0,this),C(W0,{marginBottom:1,children:C($0,{dimColor:!0,children:"按 ESC 返回修改描述"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this);return C(W0,{flexDirection:"column",paddingY:1,children:[C(W0,{marginBottom:1,children:C($0,{bold:!0,color:"yellow",children:[C(fL,{type:"dots"},void 0,!1,void 0,this)," AI 正在生成配置..."]},void 0,!0,void 0,this)},void 0,!1,void 0,this),C(W0,{marginBottom:1,children:C($0,{dimColor:!0,children:['根据你的描述:"',q,'"']},void 0,!0,void 0,this)},void 0,!1,void 0,this),C(W0,{marginBottom:1,children:C($0,{color:"gray",children:"正在调用 LLM 生成 agent 配置,请稍候..."},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}if(Y==="name"){let v=O==="edit";return C(W0,{flexDirection:"column",paddingY:1,children:[C(W0,{marginBottom:1,children:C($0,{bold:!0,color:"cyan",children:["\uD83D\uDCDD Step 1/7: ",v?"Agent 名称(不可修改)":"输入 Agent 名称"]},void 0,!0,void 0,this)},void 0,!1,void 0,this),C(W0,{marginBottom:1,children:C($0,{dimColor:!0,children:v?"编辑模式下名称不可修改(修改名称相当于创建新 Agent)":"名称只能包含小写字母、数字和连字符(例如:code-reviewer)"},void 0,!1,void 0,this)},void 0,!1,void 0,this),C(W0,{marginBottom:1,children:[C($0,{color:"green",children:"名称: "},void 0,!1,void 0,this),v?C($0,{children:J.name},void 0,!1,void 0,this):C(_3,{value:J.name,onChange:(N)=>G({...J,name:N}),onSubmit:(N)=>{if(pL(N))return;w()}},void 0,!1,void 0,this)]},void 0,!0,void 0,this),C(W0,{children:C($0,{dimColor:!0,children:v?"按 Enter 继续 | ESC 返回":"按 Enter 继续 | ESC 返回"},void 0,!1,void 0,this)},void 0,!1,void 0,this),v&&C(_3,{value:"",onChange:()=>{},onSubmit:w,showCursor:!1},"edit-mode-dummy-input",!1,void 0,this)]},void 0,!0,void 0,this)}if(Y==="description")return C(W0,{flexDirection:"column",paddingY:1,children:[C(W0,{marginBottom:1,children:C($0,{bold:!0,color:"cyan",children:"\uD83D\uDCDD Step 2/7: 输入描述信息"},void 0,!1,void 0,this)},void 0,!1,void 0,this),C(W0,{marginBottom:1,children:C($0,{dimColor:!0,children:"简短描述这个 Agent 的用途和使用场景(这将帮助主 Agent 决定何时使用它)"},void 0,!1,void 0,this)},void 0,!1,void 0,this),C(W0,{marginBottom:1,children:[C($0,{color:"green",children:"描述: "},void 0,!1,void 0,this),C(_3,{value:J.description,onChange:(v)=>G({...J,description:v}),onSubmit:(v)=>{if(!v.trim())return;w()}},void 0,!1,void 0,this)]},void 0,!0,void 0,this),C(W0,{children:C($0,{dimColor:!0,children:"按 Enter 继续 | ESC 返回"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this);if(Y==="tools")return C(dL,{config:J,setConfig:G,onNext:w,onPrev:R},void 0,!1,void 0,this);if(Y==="color")return C(W0,{flexDirection:"column",paddingY:1,children:[C(W0,{marginBottom:1,children:C($0,{bold:!0,color:"cyan",children:"\uD83C\uDFA8 Step 4/7: 选择背景颜色"},void 0,!1,void 0,this)},void 0,!1,void 0,this),C(W0,{marginBottom:1,children:C($0,{dimColor:!0,children:"为 Agent 选择一个颜色标识(用于在 UI 中区分不同的 Agents)"},void 0,!1,void 0,this)},void 0,!1,void 0,this),C(i6,{items:xL,onSelect:(v)=>{let N=v.value==="none"?void 0:v.value;G({...J,color:N}),w()}},void 0,!1,void 0,this),C(W0,{marginTop:1,children:C($0,{dimColor:!0,children:"使用方向键选择 | Enter 确认 | ESC 返回"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this);if(Y==="location")return C(W0,{flexDirection:"column",paddingY:1,children:[C(W0,{marginBottom:1,children:C($0,{bold:!0,color:"cyan",children:"\uD83D\uDCC2 Step 5/7: 选择保存位置"},void 0,!1,void 0,this)},void 0,!1,void 0,this),C(W0,{marginBottom:1,children:C($0,{dimColor:!0,children:"项目级配置仅在当前项目生效,用户级配置全局可用"},void 0,!1,void 0,this)},void 0,!1,void 0,this),C(i6,{items:[{label:"\uD83D\uDCC1 项目级 (.blade/agents/) - 仅当前项目",value:"project"},{label:"\uD83C\uDFE0 用户级 (~/.blade/agents/) - 全局可用",value:"user"}],onSelect:(v)=>{G({...J,location:v.value}),w()}},void 0,!1,void 0,this),C(W0,{marginTop:1,children:C($0,{dimColor:!0,children:"使用方向键选择 | Enter 确认 | ESC 返回"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this);if(Y==="systemPrompt")return C(W0,{flexDirection:"column",paddingY:1,children:[C(W0,{marginBottom:1,children:C($0,{bold:!0,color:"cyan",children:"\uD83D\uDCAC Step 6/7: 输入系统提示词"},void 0,!1,void 0,this)},void 0,!1,void 0,this),C(W0,{marginBottom:1,children:C($0,{dimColor:!0,children:"定义 Agent 的行为和职责(可选,留空将使用默认提示)"},void 0,!1,void 0,this)},void 0,!1,void 0,this),C(W0,{marginBottom:1,children:[C($0,{color:"green",children:"提示词: "},void 0,!1,void 0,this),C(_3,{value:J.systemPrompt,onChange:(v)=>G({...J,systemPrompt:v}),onSubmit:()=>w()},void 0,!1,void 0,this)]},void 0,!0,void 0,this),C(W0,{children:C($0,{dimColor:!0,children:"按 Enter 继续 | ESC 返回"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this);if(Y==="confirm")return C(W0,{flexDirection:"column",paddingY:1,children:[C(W0,{marginBottom:1,children:C($0,{bold:!0,color:"cyan",children:"✅ Step 7/7: 确认配置"},void 0,!1,void 0,this)},void 0,!1,void 0,this),C(W0,{flexDirection:"column",paddingLeft:2,marginBottom:1,children:[C($0,{children:[C($0,{bold:!0,color:"green",children:["名称:"," "]},void 0,!0,void 0,this),C($0,{children:J.name},void 0,!1,void 0,this)]},void 0,!0,void 0,this),C($0,{children:[C($0,{bold:!0,color:"green",children:["描述:"," "]},void 0,!0,void 0,this),C($0,{children:J.description},void 0,!1,void 0,this)]},void 0,!0,void 0,this),C($0,{children:[C($0,{bold:!0,color:"green",children:["工具:"," "]},void 0,!0,void 0,this),C($0,{children:J.tools.includes("all")?"所有工具":J.tools.join(", ")||"所有工具"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),C($0,{children:[C($0,{bold:!0,color:"green",children:["颜色:"," "]},void 0,!0,void 0,this),C($0,{children:J.color||"默认"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),C($0,{children:[C($0,{bold:!0,color:"green",children:["位置:"," "]},void 0,!0,void 0,this),C($0,{children:J.location==="project"?"项目级":"用户级"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),C($0,{children:[C($0,{bold:!0,color:"green",children:["提示词:"," "]},void 0,!0,void 0,this),C($0,{children:J.systemPrompt||"(使用默认)"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),C(i6,{items:[{label:"✅ 确认并保存",value:"save"},{label:"⬅️ 返回上一步",value:"back"},{label:"❌ 取消",value:"cancel"}],onSelect:(v)=>{if(v.value==="save")V();else if(v.value==="back")R();else Z()}},void 0,!1,void 0,this)]},void 0,!0,void 0,this);return null}function dL({config:$,setConfig:Z,onNext:X,onPrev:Y}){let{isFocused:Q}=CL({id:"step-tools"});KW((G,q)=>{if(q.escape)Y()},{isActive:Q});let J=(G)=>{if(G.includes("all"))Z({...$,tools:["all"]});else Z({...$,tools:G});X()};return C(W0,{flexDirection:"column",paddingY:1,children:[C(W0,{marginBottom:1,children:C($0,{bold:!0,color:"cyan",children:"\uD83D\uDD27 Step 3/7: 选择可用工具"},void 0,!1,void 0,this)},void 0,!1,void 0,this),C(W0,{marginBottom:1,children:C($0,{dimColor:!0,children:"方向键导航,空格切换勾选,Enter 确认进入下一步 | ESC 返回上一步"},void 0,!1,void 0,this)},void 0,!1,void 0,this),C(SL,{options:hL,defaultValue:$.tools,onSubmit:J},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}G2();import mL from"node:fs";import{useMemoizedFn as _2}from"ahooks";import{Box as c0,Text as n0,useInput as uL}from"ink";import OZ from"ink-select-input";import{useEffect as gL,useMemo as WW,useState as a6}from"react";import{jsxDEV as o}from"react/jsx-dev-runtime";var zZ=10;function UW({initialMode:$="menu",onComplete:Z,onCancel:X}){let[Y,Q]=a6($),[J,G]=a6(null),[q,K]=a6(0),[W,U]=a6(0),H=_2(()=>{J$.clear(),J$.loadFromStandardLocations(),K((N)=>N+1)}),F=WW(()=>{return J$.getAllSubagents()},[q]),O=Math.ceil(F.length/zZ)||1,z=WW(()=>{let N=W*zZ;return F.slice(N,N+zZ)},[F,W]);gL(()=>{let N=Math.max(0,O-1);if(W>N)U(N)},[O,W]);let _=_2(()=>{if(W<O-1)U((N)=>N+1)}),B=_2(()=>{if(W>0)U((N)=>N-1)}),L=[{key:"list",label:"\uD83D\uDCCB 查看所有 Agents",value:"list"},{key:"create",label:"➕ 创建新 Agent",value:"create"},{key:"edit",label:"✏️ 编辑 Agent",value:"edit"},{key:"delete",label:"\uD83D\uDDD1️ 删除 Agent",value:"delete"},{key:"cancel",label:"❌ 取消",value:"cancel"}],w=_2((N)=>{if(N.value==="cancel"){X?.();return}Q(N.value)}),R=_2((N)=>{if(G(N.value),Y==="edit")Q("editWizard");else if(Y==="delete")Q("deleteConfirm")}),D=_2(async()=>{if(!J?.configPath)return;try{await mL.promises.unlink(J.configPath),H(),V()}catch(N){console.error("删除失败:",N)}}),V=_2(()=>{Q("menu"),G(null)}),I=X$(!1,X);if(uL((N,k)=>{if(k.escape){if(Y==="menu")X?.();else if(Y==="list"||Y==="edit"||Y==="delete")U(0),V();else if(Y==="deleteConfirm")V()}else if(k.ctrl&&N==="c"||k.meta&&N==="c")I();else if(Y==="list"){if(k.leftArrow||N==="h")B();else if(k.rightArrow||N==="l")_()}},{isActive:Y!=="create"&&Y!=="editWizard"}),Y==="menu")return o(c0,{flexDirection:"column",paddingY:1,children:[o(c0,{marginBottom:1,children:o(n0,{bold:!0,color:"cyan",children:"\uD83D\uDCCB Agents 管理"},void 0,!1,void 0,this)},void 0,!1,void 0,this),o(OZ,{items:L,onSelect:w},void 0,!1,void 0,this),o(c0,{marginTop:1,children:o(n0,{dimColor:!0,children:"使用方向键选择 | Enter 确认 | ESC 退出"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this);if(Y==="list"){if(F.length===0)return o(c0,{flexDirection:"column",paddingY:1,children:[o(c0,{marginBottom:1,children:o(n0,{bold:!0,color:"cyan",children:"\uD83D\uDCCB 所有 Agents"},void 0,!1,void 0,this)},void 0,!1,void 0,this),o(c0,{paddingLeft:2,children:o(n0,{color:"gray",children:"❌ 没有找到任何 agent 配置"},void 0,!1,void 0,this)},void 0,!1,void 0,this),o(c0,{marginTop:1,paddingLeft:2,children:o(n0,{color:"gray",children:"\uD83D\uDCA1 配置文件位置: .blade/agents/ 或 ~/.blade/agents/"},void 0,!1,void 0,this)},void 0,!1,void 0,this),o(c0,{marginTop:1,paddingLeft:2,children:o(n0,{dimColor:!0,children:"按 ESC 返回菜单"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this);return o(c0,{flexDirection:"column",paddingY:1,children:[o(c0,{marginBottom:1,children:[o(n0,{bold:!0,color:"cyan",children:"\uD83D\uDCCB 所有 Agents"},void 0,!1,void 0,this),o(n0,{color:"gray",children:[" (共 ",F.length," 个)"]},void 0,!0,void 0,this),O>1&&o(n0,{color:"yellow",children:[" ","第 ",W+1,"/",O," 页"]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),z.map((N)=>o(c0,{flexDirection:"column",paddingLeft:2,children:[o(c0,{children:o(n0,{children:[o(n0,{bold:!0,color:N.color||"white",children:["• ",N.name]},void 0,!0,void 0,this),o(n0,{color:"gray",children:[" - ",N.description]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this),N.tools&&N.tools.length>0&&o(c0,{paddingLeft:2,children:o(n0,{color:"gray",children:["工具: ",N.tools.join(", ")]},void 0,!0,void 0,this)},void 0,!1,void 0,this),N.configPath&&o(c0,{paddingLeft:2,children:o(n0,{color:"gray",dimColor:!0,children:N.configPath},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},N.name,!0,void 0,this)),o(c0,{marginTop:1,paddingLeft:2,children:O>1?o(n0,{dimColor:!0,children:"← → 翻页 | ESC 返回菜单"},void 0,!1,void 0,this):o(n0,{dimColor:!0,children:"按 ESC 返回菜单"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}let v=(N)=>{if(F.length===0)return o(c0,{flexDirection:"column",paddingY:1,children:[o(c0,{marginBottom:1,children:o(n0,{bold:!0,color:"cyan",children:N},void 0,!1,void 0,this)},void 0,!1,void 0,this),o(c0,{paddingLeft:2,children:o(n0,{color:"gray",children:"❌ 没有找到任何 agent 配置"},void 0,!1,void 0,this)},void 0,!1,void 0,this),o(c0,{marginTop:1,paddingLeft:2,children:o(n0,{dimColor:!0,children:"按 ESC 返回菜单"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this);let k=F.map((m)=>({key:m.name,label:`${m.name} - ${m.description}`,value:m}));return o(c0,{flexDirection:"column",paddingY:1,children:[o(c0,{marginBottom:1,children:o(n0,{bold:!0,color:"cyan",children:N},void 0,!1,void 0,this)},void 0,!1,void 0,this),o(OZ,{items:k,onSelect:R},void 0,!1,void 0,this),o(c0,{marginTop:1,children:o(n0,{dimColor:!0,children:"使用方向键选择 | Enter 确认 | ESC 返回"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)};if(Y==="create")return o(B3,{onComplete:()=>{H(),V()},onCancel:V},void 0,!1,void 0,this);if(Y==="edit")return v("✏️ 编辑 Agent");if(Y==="editWizard"&&J){let N={name:J.name,description:J.description,tools:J.tools||[],color:J.color,location:J.configPath?.includes(".blade/agents")?"project":"user",systemPrompt:J.systemPrompt||""};return o(B3,{initialConfig:N,onComplete:()=>{H(),V()},onCancel:V},void 0,!1,void 0,this)}if(Y==="delete")return v("\uD83D\uDDD1️ 删除 Agent");if(Y==="deleteConfirm"&&J)return o(c0,{flexDirection:"column",paddingY:1,children:[o(c0,{marginBottom:1,children:o(n0,{bold:!0,color:"red",children:"⚠️ 确认删除"},void 0,!1,void 0,this)},void 0,!1,void 0,this),o(c0,{marginBottom:1,paddingLeft:2,children:o(n0,{children:["你确定要删除 Agent"," ",o(n0,{bold:!0,color:"yellow",children:J.name},void 0,!1,void 0,this)," ","吗?"]},void 0,!0,void 0,this)},void 0,!1,void 0,this),o(c0,{marginBottom:1,paddingLeft:2,children:o(n0,{dimColor:!0,children:["文件路径: ",J.configPath]},void 0,!0,void 0,this)},void 0,!1,void 0,this),o(c0,{marginBottom:1,paddingLeft:2,children:o(n0,{color:"red",children:"此操作无法撤销!"},void 0,!1,void 0,this)},void 0,!1,void 0,this),o(OZ,{items:[{label:"\uD83D\uDDD1️ 确认删除",value:"confirm"},{label:"❌ 取消",value:"cancel"}],onSelect:(N)=>{if(N.value==="confirm")D();else V()}},void 0,!1,void 0,this)]},void 0,!0,void 0,this);return null}U$();import{Box as z8,Text as o0}from"ink";import lL from"react";R6();$Z();import{useEffect as cL,useState as HW}from"react";function FW($=process.cwd(),Z=5000){let[X,Y]=HW(null),[Q,J]=HW(!0);return cL(()=>{let G=!0,q=async()=>{try{let W=await q3($);if(!G)return;if(!W){Y(null),J(!1);return}let U=await Fq($);if(!G)return;Y(U)}catch{if(G)Y(null)}finally{if(G)J(!1)}};q();let K=null;if(Z>0)K=setInterval(q,Z);return()=>{if(G=!1,K)clearInterval(K)}},[$,Z]),{branch:X,loading:Q}}import{jsxDEV as A0,Fragment as r6}from"react/jsx-dev-runtime";var OW=lL.memo(()=>{let $=h6(),Z=U8(),Y=f6()==="shortcuts",Q=DK(),{branch:J}=FW(),G=x6(),q=wK(),K=LK(),W=p6(),U=xK(),H=G?t2(G):!1,O=(()=>{if(Z==="default")return null;if(Z==="autoEdit")return A0(o0,{color:"magenta",children:["▶▶ auto edit on ",A0(o0,{color:"gray",children:"(shift+tab to cycle)"},void 0,!1,void 0,this)]},void 0,!0,void 0,this);if(Z==="plan")return A0(o0,{color:"cyan",children:["‖ plan mode on ",A0(o0,{color:"gray",children:"(shift+tab to cycle)"},void 0,!1,void 0,this)]},void 0,!0,void 0,this);if(Z==="yolo")return A0(o0,{color:"red",children:["⚡ yolo mode on ",A0(o0,{color:"gray",children:"(all tools auto-approved)"},void 0,!1,void 0,this)]},void 0,!0,void 0,this);if(Z==="spec"){let{phase:B,completed:L,total:w}=U,R;if(!B)R="init";else if((B==="tasks"||B==="implementation")&&w>0)R=`${B} ${L}/${w}`;else R=B;return A0(o0,{color:"blue",children:["\uD83D\uDCCB spec: ",R," ",A0(o0,{color:"gray",children:"(shift+tab to cycle)"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}return null})(),z=O!==null,_=[["Enter:发送","Shift+Enter:换行","Esc:中止"],["Shift+Tab:切换模式","↑/↓:历史","Tab:补全"],["Ctrl+A:行首","Ctrl+E:行尾","Ctrl+K:删到尾"],["Ctrl+U:删到首","Ctrl+W:删单词","Ctrl+C:退出"]];return A0(z8,{flexDirection:"row",justifyContent:"space-between",paddingX:2,paddingY:0,children:[Y?A0(z8,{flexDirection:"column",gap:0,children:_.map((B,L)=>A0(z8,{flexDirection:"row",children:[B.map((w,R)=>{let[D,V]=w.split(":");return A0(z8,{flexDirection:"row",width:20,children:[A0(o0,{color:"yellow",children:D},void 0,!1,void 0,this),A0(o0,{color:"gray",children:":"},void 0,!1,void 0,this),A0(o0,{color:"white",children:V},void 0,!1,void 0,this)]},R,!0,void 0,this)}),L===_.length-1&&A0(o0,{color:"cyan",children:" ? 关闭"},void 0,!1,void 0,this)]},L,!0,void 0,this))},void 0,!1,void 0,this):A0(z8,{flexDirection:"row",gap:1,children:[J&&A0(r6,{children:[A0(o0,{color:"gray",children:[" ",J]},void 0,!0,void 0,this),A0(o0,{color:"gray",children:"·"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),O,z&&A0(o0,{color:"gray",children:"·"},void 0,!1,void 0,this),A0(o0,{color:"gray",children:"? for shortcuts"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),A0(z8,{flexDirection:"row",gap:1,children:!$?A0(o0,{color:"red",children:"⚠ API 密钥未配置"},void 0,!1,void 0,this):A0(r6,{children:[H&&A0(r6,{children:[W?A0(o0,{color:"cyan",children:"Thinking on"},void 0,!1,void 0,this):A0(o0,{color:"gray",children:"Tab:Thinking"},void 0,!1,void 0,this),A0(o0,{color:"gray",children:"·"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),G&&A0(o0,{color:"gray",children:G.model},void 0,!1,void 0,this),A0(o0,{color:"gray",children:"·"},void 0,!1,void 0,this),K?A0(o0,{color:"yellow",children:"压缩中..."},void 0,!1,void 0,this):A0(o0,{color:q<20?"red":q<50?"yellow":"gray",children:[q,"%"]},void 0,!0,void 0,this),Q&&A0(r6,{children:[A0(o0,{color:"gray",children:"·"},void 0,!1,void 0,this),A0(o0,{color:"yellow",children:"再按一次 Ctrl+C 退出"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)});import{Box as _Z,Text as BZ}from"ink";import iL from"react";import{jsxDEV as _8}from"react/jsx-dev-runtime";var zW=iL.memo(({suggestions:$,selectedIndex:Z,visible:X,maxDisplay:Y=8})=>{if(!X||$.length===0)return null;let Q=0,J=Math.min(Y,$.length),G=Z>=$.length;if(Z>=Y&&!G)Q=Z-Y+1,J=Z+1;let q=$.slice(Q,J),K=$.length>Y;return _8(_Z,{flexDirection:"column",paddingX:2,paddingY:0,children:[q.map((W,U)=>{let F=Q+U===Z;return _8(_Z,{flexDirection:"row",paddingX:1,gap:2,children:[_8(BZ,{color:F?"cyan":"white",bold:F,children:W.command},void 0,!1,void 0,this),_8(BZ,{color:F?"cyan":"gray",dimColor:!F,children:["- ",W.description]},void 0,!0,void 0,this)]},W.command,!0,void 0,this)}),K&&_8(_Z,{paddingX:1,children:_8(BZ,{color:G?"cyan":"gray",bold:G,dimColor:!G,children:["... and ",$.length-Y," more"]},void 0,!0,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)});U$();import{Box as B1,Text as E1,useInput as bw,useStdout as Aw}from"ink";import Rw from"ink-select-input";import PZ,{useMemo as jW}from"react";import{Box as R0,Text as s0}from"ink";import w2,{useEffect as EZ,useMemo as w8,useRef as MW}from"react";P8();y9();import{Box as o6,Text as c1}from"ink";import{isPlainObject as AZ}from"lodash-es";import{common as sL,createLowlight as tL}from"lowlight";import NW from"react";i4();import{Box as n6,Text as L3}from"ink";import W4,{Fragment as LW}from"react";import aL from"string-width";var _W=new Map,BW=1000;function wZ($){let Z=!0;for(let Y=0;Y<$.length;Y++)if($.charCodeAt(Y)>127){Z=!1;break}if(Z)return $.split("");if($.length<=BW){let Y=_W.get($);if(Y)return Y}let X=Array.from($);if($.length<=BW)_W.set($,X);return X}var LZ=new Map;function K4($){if(/^[\x20-\x7E]*$/.test($))return $.length;if(LZ.has($))return LZ.get($);let Z=aL($);return LZ.set($,Z),Z}import{jsxDEV as B8}from"react/jsx-dev-runtime";var NZ=2,wW=W4.memo(({children:$,maxWidth:Z,maxHeight:X,overflowDirection:Y="top",additionalHiddenLinesCount:Q=0})=>{let J=e0(),G=[],q=Math.max(Math.round(X??Number.MAX_SAFE_INTEGER),NZ);function K(_){if(!W4.isValidElement(_))return;if(_.type===LW){W4.Children.forEach(_.props.children,K);return}if(_.type===n6){nL(_,Z,G);return}}W4.Children.forEach($,K);let U=G.length>q||Q>0?q-1:q,H=U!==void 0?Math.max(0,G.length-U):0,F=H+Q,z=(H>0?Y==="top"?G.slice(H):G.slice(0,U):G).map((_,B)=>B8(n6,{children:_.length>0?_.map((L,w)=>B8(L3,{...L.props,children:L.text},w,!1,void 0,this)):B8(L3,{children:" "},void 0,!1,void 0,this)},B,!1,void 0,this));return B8(n6,{flexDirection:"column",width:Z,flexShrink:0,children:[F>0&&Y==="top"&&B8(L3,{color:J.colors.text.muted,dimColor:!0,children:["... ",F," line",F===1?"":"s"," hidden ..."]},void 0,!0,void 0,this),z,F>0&&Y==="bottom"&&B8(L3,{color:J.colors.text.muted,dimColor:!0,children:["... ",F," line",F===1?"":"s"," hidden ..."]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)});function rL($){if(!W4.isValidElement($)||$.type!==n6)return{noWrapSegments:[],segments:[]};let Z={noWrapSegments:[],segments:[]},X=!1;function Y(Q,J){if(Q===null||Q===void 0)return;if(typeof Q==="string"||typeof Q==="number"){let W=String(Q);if(!W)return;let U={text:W,props:J??{}};if(J===void 0||J.wrap==="wrap")X=!0,Z.segments.push(U);else if(!X)Z.noWrapSegments.push(U);else Z.segments.push(U);return}if(!W4.isValidElement(Q))return;if(Q.type===LW){W4.Children.forEach(Q.props.children,(W)=>Y(W,J));return}if(Q.type!==L3)return;let{children:G,...q}=Q.props,K=J===void 0?q:{...J,...q};W4.Children.forEach(G,(W)=>Y(W,K))}return W4.Children.forEach($.props.children,(Q)=>Y(Q,void 0)),Z}function nL($,Z,X){let Y=rL($);if(Y.segments.length===0&&Y.noWrapSegments.length===0){X.push([]);return}let Q=0;for(let H of Y.noWrapSegments)Q+=K4(H.text);if(Y.segments.length===0){let H=[],F=[];for(let O of Y.noWrapSegments){let z=O.text.split(`
|
|
2798
|
+
`),m=FZ.join(v,`${J.name}.md`);await GW.promises.writeFile(m,k,"utf-8"),$()}catch(v){console.error("保存配置失败:",v)}}),I=X$(!1,Z);if(KW((v,N)=>{if(N.escape)R();else if(N.ctrl&&v==="c"||N.meta&&v==="c")I()},{isActive:Y!=="tools"}),Y==="mode")return C(W0,{flexDirection:"column",paddingY:1,children:[C(W0,{marginBottom:1,children:C($0,{bold:!0,color:"cyan",children:"\uD83C\uDFAF 选择创建方式"},void 0,!1,void 0,this)},void 0,!1,void 0,this),C(W0,{marginBottom:1,children:C($0,{dimColor:!0,children:"你可以手动配置每个细节,或让 AI 根据你的描述自动生成配置"},void 0,!1,void 0,this)},void 0,!1,void 0,this),C(i6,{items:[{label:"\uD83E\uDD16 AI 智能生成 - 根据描述自动生成完整配置",value:"ai"},{label:"✍️ 手动配置 - 逐步配置每个选项",value:"manual"}],onSelect:(v)=>{if(v.value==="ai")z("ai"),Q("aiPrompt");else z("manual"),Q("name")}},void 0,!1,void 0,this),C(W0,{marginTop:1,children:C($0,{dimColor:!0,children:"使用方向键选择 | Enter 确认 | ESC 取消"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this);if(Y==="aiPrompt")return C(W0,{flexDirection:"column",paddingY:1,children:[C(W0,{marginBottom:1,children:C($0,{bold:!0,color:"cyan",children:"\uD83E\uDD16 AI 智能生成"},void 0,!1,void 0,this)},void 0,!1,void 0,this),C(W0,{marginBottom:1,children:C($0,{dimColor:!0,children:'描述你想要创建的 Agent(例如:"一个专门用于代码审查的 agent,能够分析代码质量和潜在bug")'},void 0,!1,void 0,this)},void 0,!1,void 0,this),C(W0,{marginBottom:1,children:[C($0,{color:"green",children:"描述: "},void 0,!1,void 0,this),C(_3,{value:q,onChange:K,onSubmit:(v)=>{if(!v.trim())return;Q("aiGenerating")}},void 0,!1,void 0,this)]},void 0,!0,void 0,this),C(W0,{children:C($0,{dimColor:!0,children:"按 Enter 开始生成 | ESC 返回"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this);if(Y==="aiGenerating"){if(H)return C(W0,{flexDirection:"column",paddingY:1,children:[C(W0,{marginBottom:1,children:C($0,{bold:!0,color:"red",children:"❌ AI 生成失败"},void 0,!1,void 0,this)},void 0,!1,void 0,this),C(W0,{marginBottom:1,children:C($0,{color:"red",children:H},void 0,!1,void 0,this)},void 0,!1,void 0,this),C(W0,{marginBottom:1,children:C($0,{dimColor:!0,children:"按 ESC 返回修改描述"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this);return C(W0,{flexDirection:"column",paddingY:1,children:[C(W0,{marginBottom:1,children:C($0,{bold:!0,color:"yellow",children:[C(fL,{type:"dots"},void 0,!1,void 0,this)," AI 正在生成配置..."]},void 0,!0,void 0,this)},void 0,!1,void 0,this),C(W0,{marginBottom:1,children:C($0,{dimColor:!0,children:['根据你的描述:"',q,'"']},void 0,!0,void 0,this)},void 0,!1,void 0,this),C(W0,{marginBottom:1,children:C($0,{color:"gray",children:"正在调用 LLM 生成 agent 配置,请稍候..."},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}if(Y==="name"){let v=O==="edit";return C(W0,{flexDirection:"column",paddingY:1,children:[C(W0,{marginBottom:1,children:C($0,{bold:!0,color:"cyan",children:["\uD83D\uDCDD Step 1/7: ",v?"Agent 名称(不可修改)":"输入 Agent 名称"]},void 0,!0,void 0,this)},void 0,!1,void 0,this),C(W0,{marginBottom:1,children:C($0,{dimColor:!0,children:v?"编辑模式下名称不可修改(修改名称相当于创建新 Agent)":"名称只能包含小写字母、数字和连字符(例如:code-reviewer)"},void 0,!1,void 0,this)},void 0,!1,void 0,this),C(W0,{marginBottom:1,children:[C($0,{color:"green",children:"名称: "},void 0,!1,void 0,this),v?C($0,{children:J.name},void 0,!1,void 0,this):C(_3,{value:J.name,onChange:(N)=>G({...J,name:N}),onSubmit:(N)=>{if(pL(N))return;w()}},void 0,!1,void 0,this)]},void 0,!0,void 0,this),C(W0,{children:C($0,{dimColor:!0,children:v?"按 Enter 继续 | ESC 返回":"按 Enter 继续 | ESC 返回"},void 0,!1,void 0,this)},void 0,!1,void 0,this),v&&C(_3,{value:"",onChange:()=>{},onSubmit:w,showCursor:!1},"edit-mode-dummy-input",!1,void 0,this)]},void 0,!0,void 0,this)}if(Y==="description")return C(W0,{flexDirection:"column",paddingY:1,children:[C(W0,{marginBottom:1,children:C($0,{bold:!0,color:"cyan",children:"\uD83D\uDCDD Step 2/7: 输入描述信息"},void 0,!1,void 0,this)},void 0,!1,void 0,this),C(W0,{marginBottom:1,children:C($0,{dimColor:!0,children:"简短描述这个 Agent 的用途和使用场景(这将帮助主 Agent 决定何时使用它)"},void 0,!1,void 0,this)},void 0,!1,void 0,this),C(W0,{marginBottom:1,children:[C($0,{color:"green",children:"描述: "},void 0,!1,void 0,this),C(_3,{value:J.description,onChange:(v)=>G({...J,description:v}),onSubmit:(v)=>{if(!v.trim())return;w()}},void 0,!1,void 0,this)]},void 0,!0,void 0,this),C(W0,{children:C($0,{dimColor:!0,children:"按 Enter 继续 | ESC 返回"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this);if(Y==="tools")return C(dL,{config:J,setConfig:G,onNext:w,onPrev:R},void 0,!1,void 0,this);if(Y==="color")return C(W0,{flexDirection:"column",paddingY:1,children:[C(W0,{marginBottom:1,children:C($0,{bold:!0,color:"cyan",children:"\uD83C\uDFA8 Step 4/7: 选择背景颜色"},void 0,!1,void 0,this)},void 0,!1,void 0,this),C(W0,{marginBottom:1,children:C($0,{dimColor:!0,children:"为 Agent 选择一个颜色标识(用于在 UI 中区分不同的 Agents)"},void 0,!1,void 0,this)},void 0,!1,void 0,this),C(i6,{items:xL,onSelect:(v)=>{let N=v.value==="none"?void 0:v.value;G({...J,color:N}),w()}},void 0,!1,void 0,this),C(W0,{marginTop:1,children:C($0,{dimColor:!0,children:"使用方向键选择 | Enter 确认 | ESC 返回"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this);if(Y==="location")return C(W0,{flexDirection:"column",paddingY:1,children:[C(W0,{marginBottom:1,children:C($0,{bold:!0,color:"cyan",children:"\uD83D\uDCC2 Step 5/7: 选择保存位置"},void 0,!1,void 0,this)},void 0,!1,void 0,this),C(W0,{marginBottom:1,children:C($0,{dimColor:!0,children:"项目级配置仅在当前项目生效,用户级配置全局可用"},void 0,!1,void 0,this)},void 0,!1,void 0,this),C(i6,{items:[{label:"\uD83D\uDCC1 项目级 (.blade/agents/) - 仅当前项目",value:"project"},{label:"\uD83C\uDFE0 用户级 (~/.blade/agents/) - 全局可用",value:"user"}],onSelect:(v)=>{G({...J,location:v.value}),w()}},void 0,!1,void 0,this),C(W0,{marginTop:1,children:C($0,{dimColor:!0,children:"使用方向键选择 | Enter 确认 | ESC 返回"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this);if(Y==="systemPrompt")return C(W0,{flexDirection:"column",paddingY:1,children:[C(W0,{marginBottom:1,children:C($0,{bold:!0,color:"cyan",children:"\uD83D\uDCAC Step 6/7: 输入系统提示词"},void 0,!1,void 0,this)},void 0,!1,void 0,this),C(W0,{marginBottom:1,children:C($0,{dimColor:!0,children:"定义 Agent 的行为和职责(可选,留空将使用默认提示)"},void 0,!1,void 0,this)},void 0,!1,void 0,this),C(W0,{marginBottom:1,children:[C($0,{color:"green",children:"提示词: "},void 0,!1,void 0,this),C(_3,{value:J.systemPrompt,onChange:(v)=>G({...J,systemPrompt:v}),onSubmit:()=>w()},void 0,!1,void 0,this)]},void 0,!0,void 0,this),C(W0,{children:C($0,{dimColor:!0,children:"按 Enter 继续 | ESC 返回"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this);if(Y==="confirm")return C(W0,{flexDirection:"column",paddingY:1,children:[C(W0,{marginBottom:1,children:C($0,{bold:!0,color:"cyan",children:"✅ Step 7/7: 确认配置"},void 0,!1,void 0,this)},void 0,!1,void 0,this),C(W0,{flexDirection:"column",paddingLeft:2,marginBottom:1,children:[C($0,{children:[C($0,{bold:!0,color:"green",children:["名称:"," "]},void 0,!0,void 0,this),C($0,{children:J.name},void 0,!1,void 0,this)]},void 0,!0,void 0,this),C($0,{children:[C($0,{bold:!0,color:"green",children:["描述:"," "]},void 0,!0,void 0,this),C($0,{children:J.description},void 0,!1,void 0,this)]},void 0,!0,void 0,this),C($0,{children:[C($0,{bold:!0,color:"green",children:["工具:"," "]},void 0,!0,void 0,this),C($0,{children:J.tools.includes("all")?"所有工具":J.tools.join(", ")||"所有工具"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),C($0,{children:[C($0,{bold:!0,color:"green",children:["颜色:"," "]},void 0,!0,void 0,this),C($0,{children:J.color||"默认"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),C($0,{children:[C($0,{bold:!0,color:"green",children:["位置:"," "]},void 0,!0,void 0,this),C($0,{children:J.location==="project"?"项目级":"用户级"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),C($0,{children:[C($0,{bold:!0,color:"green",children:["提示词:"," "]},void 0,!0,void 0,this),C($0,{children:J.systemPrompt||"(使用默认)"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),C(i6,{items:[{label:"✅ 确认并保存",value:"save"},{label:"⬅️ 返回上一步",value:"back"},{label:"❌ 取消",value:"cancel"}],onSelect:(v)=>{if(v.value==="save")V();else if(v.value==="back")R();else Z()}},void 0,!1,void 0,this)]},void 0,!0,void 0,this);return null}function dL({config:$,setConfig:Z,onNext:X,onPrev:Y}){let{isFocused:Q}=CL({id:"step-tools"});KW((G,q)=>{if(q.escape)Y()},{isActive:Q});let J=(G)=>{if(G.includes("all"))Z({...$,tools:["all"]});else Z({...$,tools:G});X()};return C(W0,{flexDirection:"column",paddingY:1,children:[C(W0,{marginBottom:1,children:C($0,{bold:!0,color:"cyan",children:"\uD83D\uDD27 Step 3/7: 选择可用工具"},void 0,!1,void 0,this)},void 0,!1,void 0,this),C(W0,{marginBottom:1,children:C($0,{dimColor:!0,children:"方向键导航,空格切换勾选,Enter 确认进入下一步 | ESC 返回上一步"},void 0,!1,void 0,this)},void 0,!1,void 0,this),C(SL,{options:hL,defaultValue:$.tools,onSubmit:J},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}G4();import mL from"node:fs";import{useMemoizedFn as _4}from"ahooks";import{Box as c0,Text as n0,useInput as uL}from"ink";import OZ from"ink-select-input";import{useEffect as gL,useMemo as WW,useState as a6}from"react";import{jsxDEV as o}from"react/jsx-dev-runtime";var zZ=10;function UW({initialMode:$="menu",onComplete:Z,onCancel:X}){let[Y,Q]=a6($),[J,G]=a6(null),[q,K]=a6(0),[W,U]=a6(0),H=_4(()=>{J$.clear(),J$.loadFromStandardLocations(),K((N)=>N+1)}),F=WW(()=>{return J$.getAllSubagents()},[q]),O=Math.ceil(F.length/zZ)||1,z=WW(()=>{let N=W*zZ;return F.slice(N,N+zZ)},[F,W]);gL(()=>{let N=Math.max(0,O-1);if(W>N)U(N)},[O,W]);let _=_4(()=>{if(W<O-1)U((N)=>N+1)}),B=_4(()=>{if(W>0)U((N)=>N-1)}),L=[{key:"list",label:"\uD83D\uDCCB 查看所有 Agents",value:"list"},{key:"create",label:"➕ 创建新 Agent",value:"create"},{key:"edit",label:"✏️ 编辑 Agent",value:"edit"},{key:"delete",label:"\uD83D\uDDD1️ 删除 Agent",value:"delete"},{key:"cancel",label:"❌ 取消",value:"cancel"}],w=_4((N)=>{if(N.value==="cancel"){X?.();return}Q(N.value)}),R=_4((N)=>{if(G(N.value),Y==="edit")Q("editWizard");else if(Y==="delete")Q("deleteConfirm")}),D=_4(async()=>{if(!J?.configPath)return;try{await mL.promises.unlink(J.configPath),H(),V()}catch(N){console.error("删除失败:",N)}}),V=_4(()=>{Q("menu"),G(null)}),I=X$(!1,X);if(uL((N,k)=>{if(k.escape){if(Y==="menu")X?.();else if(Y==="list"||Y==="edit"||Y==="delete")U(0),V();else if(Y==="deleteConfirm")V()}else if(k.ctrl&&N==="c"||k.meta&&N==="c")I();else if(Y==="list"){if(k.leftArrow||N==="h")B();else if(k.rightArrow||N==="l")_()}},{isActive:Y!=="create"&&Y!=="editWizard"}),Y==="menu")return o(c0,{flexDirection:"column",paddingY:1,children:[o(c0,{marginBottom:1,children:o(n0,{bold:!0,color:"cyan",children:"\uD83D\uDCCB Agents 管理"},void 0,!1,void 0,this)},void 0,!1,void 0,this),o(OZ,{items:L,onSelect:w},void 0,!1,void 0,this),o(c0,{marginTop:1,children:o(n0,{dimColor:!0,children:"使用方向键选择 | Enter 确认 | ESC 退出"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this);if(Y==="list"){if(F.length===0)return o(c0,{flexDirection:"column",paddingY:1,children:[o(c0,{marginBottom:1,children:o(n0,{bold:!0,color:"cyan",children:"\uD83D\uDCCB 所有 Agents"},void 0,!1,void 0,this)},void 0,!1,void 0,this),o(c0,{paddingLeft:2,children:o(n0,{color:"gray",children:"❌ 没有找到任何 agent 配置"},void 0,!1,void 0,this)},void 0,!1,void 0,this),o(c0,{marginTop:1,paddingLeft:2,children:o(n0,{color:"gray",children:"\uD83D\uDCA1 配置文件位置: .blade/agents/ 或 ~/.blade/agents/"},void 0,!1,void 0,this)},void 0,!1,void 0,this),o(c0,{marginTop:1,paddingLeft:2,children:o(n0,{dimColor:!0,children:"按 ESC 返回菜单"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this);return o(c0,{flexDirection:"column",paddingY:1,children:[o(c0,{marginBottom:1,children:[o(n0,{bold:!0,color:"cyan",children:"\uD83D\uDCCB 所有 Agents"},void 0,!1,void 0,this),o(n0,{color:"gray",children:[" (共 ",F.length," 个)"]},void 0,!0,void 0,this),O>1&&o(n0,{color:"yellow",children:[" ","第 ",W+1,"/",O," 页"]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),z.map((N)=>o(c0,{flexDirection:"column",paddingLeft:2,children:[o(c0,{children:o(n0,{children:[o(n0,{bold:!0,color:N.color||"white",children:["• ",N.name]},void 0,!0,void 0,this),o(n0,{color:"gray",children:[" - ",N.description]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this),N.tools&&N.tools.length>0&&o(c0,{paddingLeft:2,children:o(n0,{color:"gray",children:["工具: ",N.tools.join(", ")]},void 0,!0,void 0,this)},void 0,!1,void 0,this),N.configPath&&o(c0,{paddingLeft:2,children:o(n0,{color:"gray",dimColor:!0,children:N.configPath},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},N.name,!0,void 0,this)),o(c0,{marginTop:1,paddingLeft:2,children:O>1?o(n0,{dimColor:!0,children:"← → 翻页 | ESC 返回菜单"},void 0,!1,void 0,this):o(n0,{dimColor:!0,children:"按 ESC 返回菜单"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}let v=(N)=>{if(F.length===0)return o(c0,{flexDirection:"column",paddingY:1,children:[o(c0,{marginBottom:1,children:o(n0,{bold:!0,color:"cyan",children:N},void 0,!1,void 0,this)},void 0,!1,void 0,this),o(c0,{paddingLeft:2,children:o(n0,{color:"gray",children:"❌ 没有找到任何 agent 配置"},void 0,!1,void 0,this)},void 0,!1,void 0,this),o(c0,{marginTop:1,paddingLeft:2,children:o(n0,{dimColor:!0,children:"按 ESC 返回菜单"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this);let k=F.map((m)=>({key:m.name,label:`${m.name} - ${m.description}`,value:m}));return o(c0,{flexDirection:"column",paddingY:1,children:[o(c0,{marginBottom:1,children:o(n0,{bold:!0,color:"cyan",children:N},void 0,!1,void 0,this)},void 0,!1,void 0,this),o(OZ,{items:k,onSelect:R},void 0,!1,void 0,this),o(c0,{marginTop:1,children:o(n0,{dimColor:!0,children:"使用方向键选择 | Enter 确认 | ESC 返回"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)};if(Y==="create")return o(B3,{onComplete:()=>{H(),V()},onCancel:V},void 0,!1,void 0,this);if(Y==="edit")return v("✏️ 编辑 Agent");if(Y==="editWizard"&&J){let N={name:J.name,description:J.description,tools:J.tools||[],color:J.color,location:J.configPath?.includes(".blade/agents")?"project":"user",systemPrompt:J.systemPrompt||""};return o(B3,{initialConfig:N,onComplete:()=>{H(),V()},onCancel:V},void 0,!1,void 0,this)}if(Y==="delete")return v("\uD83D\uDDD1️ 删除 Agent");if(Y==="deleteConfirm"&&J)return o(c0,{flexDirection:"column",paddingY:1,children:[o(c0,{marginBottom:1,children:o(n0,{bold:!0,color:"red",children:"⚠️ 确认删除"},void 0,!1,void 0,this)},void 0,!1,void 0,this),o(c0,{marginBottom:1,paddingLeft:2,children:o(n0,{children:["你确定要删除 Agent"," ",o(n0,{bold:!0,color:"yellow",children:J.name},void 0,!1,void 0,this)," ","吗?"]},void 0,!0,void 0,this)},void 0,!1,void 0,this),o(c0,{marginBottom:1,paddingLeft:2,children:o(n0,{dimColor:!0,children:["文件路径: ",J.configPath]},void 0,!0,void 0,this)},void 0,!1,void 0,this),o(c0,{marginBottom:1,paddingLeft:2,children:o(n0,{color:"red",children:"此操作无法撤销!"},void 0,!1,void 0,this)},void 0,!1,void 0,this),o(OZ,{items:[{label:"\uD83D\uDDD1️ 确认删除",value:"confirm"},{label:"❌ 取消",value:"cancel"}],onSelect:(N)=>{if(N.value==="confirm")D();else V()}},void 0,!1,void 0,this)]},void 0,!0,void 0,this);return null}U$();import{Box as z8,Text as o0}from"ink";import lL from"react";R6();$Z();import{useEffect as cL,useState as HW}from"react";function FW($=process.cwd(),Z=5000){let[X,Y]=HW(null),[Q,J]=HW(!0);return cL(()=>{let G=!0,q=async()=>{try{let W=await q3($);if(!G)return;if(!W){Y(null),J(!1);return}let U=await Fq($);if(!G)return;Y(U)}catch{if(G)Y(null)}finally{if(G)J(!1)}};q();let K=null;if(Z>0)K=setInterval(q,Z);return()=>{if(G=!1,K)clearInterval(K)}},[$,Z]),{branch:X,loading:Q}}import{jsxDEV as A0,Fragment as r6}from"react/jsx-dev-runtime";var OW=lL.memo(()=>{let $=h6(),Z=U8(),Y=f6()==="shortcuts",Q=DK(),{branch:J}=FW(),G=x6(),q=wK(),K=LK(),W=p6(),U=xK(),H=G?t4(G):!1,O=(()=>{if(Z==="default")return null;if(Z==="autoEdit")return A0(o0,{color:"magenta",children:["▶▶ auto edit on ",A0(o0,{color:"gray",children:"(shift+tab to cycle)"},void 0,!1,void 0,this)]},void 0,!0,void 0,this);if(Z==="plan")return A0(o0,{color:"cyan",children:["‖ plan mode on ",A0(o0,{color:"gray",children:"(shift+tab to cycle)"},void 0,!1,void 0,this)]},void 0,!0,void 0,this);if(Z==="yolo")return A0(o0,{color:"red",children:["⚡ yolo mode on ",A0(o0,{color:"gray",children:"(all tools auto-approved)"},void 0,!1,void 0,this)]},void 0,!0,void 0,this);if(Z==="spec"){let{phase:B,completed:L,total:w}=U,R;if(!B)R="init";else if((B==="tasks"||B==="implementation")&&w>0)R=`${B} ${L}/${w}`;else R=B;return A0(o0,{color:"blue",children:["\uD83D\uDCCB spec: ",R," ",A0(o0,{color:"gray",children:"(shift+tab to cycle)"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}return null})(),z=O!==null,_=[["Enter:发送","Shift+Enter:换行","Esc:中止"],["Shift+Tab:切换模式","↑/↓:历史","Tab:补全"],["Ctrl+A:行首","Ctrl+E:行尾","Ctrl+K:删到尾"],["Ctrl+U:删到首","Ctrl+W:删单词","Ctrl+C:退出"]];return A0(z8,{flexDirection:"row",justifyContent:"space-between",paddingX:2,paddingY:0,children:[Y?A0(z8,{flexDirection:"column",gap:0,children:_.map((B,L)=>A0(z8,{flexDirection:"row",children:[B.map((w,R)=>{let[D,V]=w.split(":");return A0(z8,{flexDirection:"row",width:20,children:[A0(o0,{color:"yellow",children:D},void 0,!1,void 0,this),A0(o0,{color:"gray",children:":"},void 0,!1,void 0,this),A0(o0,{color:"white",children:V},void 0,!1,void 0,this)]},R,!0,void 0,this)}),L===_.length-1&&A0(o0,{color:"cyan",children:" ? 关闭"},void 0,!1,void 0,this)]},L,!0,void 0,this))},void 0,!1,void 0,this):A0(z8,{flexDirection:"row",gap:1,children:[J&&A0(r6,{children:[A0(o0,{color:"gray",children:[" ",J]},void 0,!0,void 0,this),A0(o0,{color:"gray",children:"·"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),O,z&&A0(o0,{color:"gray",children:"·"},void 0,!1,void 0,this),A0(o0,{color:"gray",children:"? for shortcuts"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),A0(z8,{flexDirection:"row",gap:1,children:!$?A0(o0,{color:"red",children:"⚠ API 密钥未配置"},void 0,!1,void 0,this):A0(r6,{children:[H&&A0(r6,{children:[W?A0(o0,{color:"cyan",children:"Thinking on"},void 0,!1,void 0,this):A0(o0,{color:"gray",children:"Tab:Thinking"},void 0,!1,void 0,this),A0(o0,{color:"gray",children:"·"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),G&&A0(o0,{color:"gray",children:G.model},void 0,!1,void 0,this),A0(o0,{color:"gray",children:"·"},void 0,!1,void 0,this),K?A0(o0,{color:"yellow",children:"压缩中..."},void 0,!1,void 0,this):A0(o0,{color:q<20?"red":q<50?"yellow":"gray",children:[q,"%"]},void 0,!0,void 0,this),Q&&A0(r6,{children:[A0(o0,{color:"gray",children:"·"},void 0,!1,void 0,this),A0(o0,{color:"yellow",children:"再按一次 Ctrl+C 退出"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)});import{Box as _Z,Text as BZ}from"ink";import iL from"react";import{jsxDEV as _8}from"react/jsx-dev-runtime";var zW=iL.memo(({suggestions:$,selectedIndex:Z,visible:X,maxDisplay:Y=8})=>{if(!X||$.length===0)return null;let Q=0,J=Math.min(Y,$.length),G=Z>=$.length;if(Z>=Y&&!G)Q=Z-Y+1,J=Z+1;let q=$.slice(Q,J),K=$.length>Y;return _8(_Z,{flexDirection:"column",paddingX:2,paddingY:0,children:[q.map((W,U)=>{let F=Q+U===Z;return _8(_Z,{flexDirection:"row",paddingX:1,gap:2,children:[_8(BZ,{color:F?"cyan":"white",bold:F,children:W.command},void 0,!1,void 0,this),_8(BZ,{color:F?"cyan":"gray",dimColor:!F,children:["- ",W.description]},void 0,!0,void 0,this)]},W.command,!0,void 0,this)}),K&&_8(_Z,{paddingX:1,children:_8(BZ,{color:G?"cyan":"gray",bold:G,dimColor:!G,children:["... and ",$.length-Y," more"]},void 0,!0,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)});U$();import{Box as B1,Text as E1,useInput as bw,useStdout as Aw}from"ink";import Rw from"ink-select-input";import PZ,{useMemo as jW}from"react";import{Box as R0,Text as s0}from"ink";import w4,{useEffect as EZ,useMemo as w8,useRef as MW}from"react";P8();y9();import{Box as o6,Text as c1}from"ink";import{isPlainObject as AZ}from"lodash-es";import{common as sL,createLowlight as tL}from"lowlight";import NW from"react";i2();import{Box as n6,Text as L3}from"ink";import W2,{Fragment as LW}from"react";import aL from"string-width";var _W=new Map,BW=1000;function wZ($){let Z=!0;for(let Y=0;Y<$.length;Y++)if($.charCodeAt(Y)>127){Z=!1;break}if(Z)return $.split("");if($.length<=BW){let Y=_W.get($);if(Y)return Y}let X=Array.from($);if($.length<=BW)_W.set($,X);return X}var LZ=new Map;function K2($){if(/^[\x20-\x7E]*$/.test($))return $.length;if(LZ.has($))return LZ.get($);let Z=aL($);return LZ.set($,Z),Z}import{jsxDEV as B8}from"react/jsx-dev-runtime";var NZ=2,wW=W2.memo(({children:$,maxWidth:Z,maxHeight:X,overflowDirection:Y="top",additionalHiddenLinesCount:Q=0})=>{let J=e0(),G=[],q=Math.max(Math.round(X??Number.MAX_SAFE_INTEGER),NZ);function K(_){if(!W2.isValidElement(_))return;if(_.type===LW){W2.Children.forEach(_.props.children,K);return}if(_.type===n6){nL(_,Z,G);return}}W2.Children.forEach($,K);let U=G.length>q||Q>0?q-1:q,H=U!==void 0?Math.max(0,G.length-U):0,F=H+Q,z=(H>0?Y==="top"?G.slice(H):G.slice(0,U):G).map((_,B)=>B8(n6,{children:_.length>0?_.map((L,w)=>B8(L3,{...L.props,children:L.text},w,!1,void 0,this)):B8(L3,{children:" "},void 0,!1,void 0,this)},B,!1,void 0,this));return B8(n6,{flexDirection:"column",width:Z,flexShrink:0,children:[F>0&&Y==="top"&&B8(L3,{color:J.colors.text.muted,dimColor:!0,children:["... ",F," line",F===1?"":"s"," hidden ..."]},void 0,!0,void 0,this),z,F>0&&Y==="bottom"&&B8(L3,{color:J.colors.text.muted,dimColor:!0,children:["... ",F," line",F===1?"":"s"," hidden ..."]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)});function rL($){if(!W2.isValidElement($)||$.type!==n6)return{noWrapSegments:[],segments:[]};let Z={noWrapSegments:[],segments:[]},X=!1;function Y(Q,J){if(Q===null||Q===void 0)return;if(typeof Q==="string"||typeof Q==="number"){let W=String(Q);if(!W)return;let U={text:W,props:J??{}};if(J===void 0||J.wrap==="wrap")X=!0,Z.segments.push(U);else if(!X)Z.noWrapSegments.push(U);else Z.segments.push(U);return}if(!W2.isValidElement(Q))return;if(Q.type===LW){W2.Children.forEach(Q.props.children,(W)=>Y(W,J));return}if(Q.type!==L3)return;let{children:G,...q}=Q.props,K=J===void 0?q:{...J,...q};W2.Children.forEach(G,(W)=>Y(W,K))}return W2.Children.forEach($.props.children,(Q)=>Y(Q,void 0)),Z}function nL($,Z,X){let Y=rL($);if(Y.segments.length===0&&Y.noWrapSegments.length===0){X.push([]);return}let Q=0;for(let H of Y.noWrapSegments)Q+=K2(H.text);if(Y.segments.length===0){let H=[],F=[];for(let O of Y.noWrapSegments){let z=O.text.split(`
|
|
2799
2799
|
`);for(let _=0;_<z.length;_++){if(_>0)H.push(F),F=[];if(z[_])F.push({text:z[_],props:O.props})}}if(F.length>0)H.push(F);for(let O of H)X.push(O);return}let J=Z-Q;if(J<1){oL(Y.noWrapSegments,Z,X);return}let G=[],q=[],K=0;function W(){if(G.length===0)G.push([...Y.noWrapSegments,...q]);else if(Q>0)G.push([{text:" ".repeat(Q),props:{}},...q]);else G.push(q);q=[],K=0}function U(H,F){if(q.length>0&&q[q.length-1].props===F)q[q.length-1].text+=H;else q.push({text:H,props:F})}for(let H of Y.segments){let F=H.text.split(`
|
|
2800
|
-
`);for(let O=0;O<F.length;O++){if(O>0)W();let _=F[O].split(/(\s+)/);for(let B of _){if(!B)continue;let L=
|
|
2800
|
+
`);for(let O=0;O<F.length;O++){if(O>0)W();let _=F[O].split(/(\s+)/);for(let B of _){if(!B)continue;let L=K2(B);if(K+L>J&&K>0){if(W(),/^\s+$/.test(B))continue}if(L>J){let R=wZ(B);while(R.length>0){let D=0,V=0;for(let I of R){let v=K2(I);if(K+V+v>J)break;V+=v,D++}if(D>0){let I=R.slice(0,D).join("");U(I,H.props),K+=K2(I),R=R.slice(D)}if(R.length>0)W()}}else U(B,H.props),K+=L}}if(H.text.endsWith(`
|
|
2801
2801
|
`))W()}if(q.length>0)W();for(let H of G)X.push(H)}function oL($,Z,X){let Y=[],Q=[],J=0;for(let G of $){let q=G.text.split(`
|
|
2802
|
-
`);for(let K=0;K<q.length;K++){if(K>0)Y.push(Q),Q=[],J=0;let W=q[K];if(!W)continue;let U=
|
|
2802
|
+
`);for(let K=0;K<q.length;K++){if(K>0)Y.push(Q),Q=[],J=0;let W=q[K];if(!W)continue;let U=K2(W),H=Math.max(0,Z-K2("…"));if(U<=H&&J===0)Q.push({text:W,props:G.props}),J+=U;else{let F=wZ(W),O=J,z=0;for(let B of F){let L=K2(B);if(O+L>H)break;O+=L,z++}let _=F.slice(0,z).join("");if(_)Q.push({text:_,props:G.props});Q.push({text:"…",props:{}}),J=O+K2("…")}}}if(Q.length>0)Y.push(Q);if(Y.length===0)Y.push([{text:"…",props:{}}]);for(let G of Y)X.push(G)}import{jsxDEV as k$}from"react/jsx-dev-runtime";var bZ=tL(sL);function eL($){return AZ($)&&$.type==="text"&&typeof $.value==="string"}function $w($){return AZ($)&&$.type==="element"}function Zw($){return AZ($)&&$.type==="root"&&Array.isArray($.children)}function s6($,Z,X=0){if(eL($))return k$(c1,{wrap:"wrap",children:$.value},X,!1,void 0,this);if($w($)){let Y=$.properties?.className?.[0]||"",Q=Z.default;if(Y.includes("comment"))Q=Z.comment;else if(Y.includes("string"))Q=Z.string;else if(Y.includes("number"))Q=Z.number;else if(Y.includes("keyword"))Q=Z.keyword;else if(Y.includes("function"))Q=Z.function;else if(Y.includes("variable"))Q=Z.variable;else if(Y.includes("operator"))Q=Z.operator;else if(Y.includes("type"))Q=Z.type;else if(Y.includes("tag"))Q=Z.tag;else if(Y.includes("attr"))Q=Z.attr;let J=$.children?.map((G,q)=>s6(G,Z,q));return k$(c1,{color:Q,wrap:"wrap",children:J},X,!1,void 0,this)}if(Zw($))return k$(NW.Fragment,{children:$.children.map((Y,Q)=>s6(Y,Z,Q))},X,!1,void 0,this);return k$(c1,{},X,!1,void 0,this)}function Xw($,Z,X){let Y=X||g$.getTheme().colors.syntax;try{if(!Z||!bZ.registered(Z)){let J=bZ.highlightAuto($);if(!J.children||J.children.length===0)return k$(c1,{color:Y.default,wrap:"wrap",children:$},void 0,!1,void 0,this);return s6(J,Y)}let Q=bZ.highlight(Z,$);if(!Q.children||Q.children.length===0)return k$(c1,{color:Y.default,wrap:"wrap",children:$},void 0,!1,void 0,this);return s6(Q,Y)}catch(Q){return k$(c1,{color:Y.default,wrap:"wrap",children:$},void 0,!1,void 0,this)}}var t6=NW.memo(({content:$,language:Z,showLineNumbers:X=!0,terminalWidth:Y,availableHeight:Q})=>{let J=e0(),G=$.split(`
|
|
2803
2803
|
`),q=0;if(Q&&G.length>Q){let H=Math.max(Q,NZ);if(G.length>H)q=G.length-H,G=G.slice(q)}let K=G.length+q,W=String(K).length+1,U=Math.max(20,Y-4);return k$(o6,{borderStyle:"round",borderColor:J.colors.border.light,paddingX:1,paddingY:0,marginY:1,flexDirection:"column",children:[Z&&k$(o6,{marginBottom:0,children:k$(c1,{color:J.colors.text.secondary,children:Z},void 0,!1,void 0,this)},void 0,!1,void 0,this),q>0&&k$(o6,{marginBottom:0,children:k$(c1,{color:J.colors.text.muted,dimColor:!0,children:["... ",q," lines hidden ..."]},void 0,!0,void 0,this)},void 0,!1,void 0,this),k$(wW,{maxWidth:U,maxHeight:Q,children:G.map((H,F)=>{let O=F+q+1;return k$(o6,{flexDirection:"row",children:[X&&k$(c1,{color:J.colors.text.muted,dimColor:!0,wrap:"truncate",children:[String(O).padStart(W-1," ")," "]},void 0,!0,void 0,this),H.trim()===""?k$(c1,{wrap:"wrap",children:" "},void 0,!1,void 0,this):Xw(H,Z,J.colors.syntax)]},F,!0,void 0,this)})},void 0,!1,void 0,this)]},void 0,!0,void 0,this)});import{Box as bW,Text as l1}from"ink";import Yw from"react";import{jsxDEV as F1}from"react/jsx-dev-runtime";function Qw($){let Z=$.split(`
|
|
2804
|
-
`),X=[],Y=0,Q=0;for(let J of Z){if(J.startsWith("---")||J.startsWith("+++"))continue;if(J.startsWith("@@")){let G=J.match(/@@ -(\d+),?(\d*) \+(\d+),?(\d*) @@/);if(G)Y=parseInt(G[1],10),Q=parseInt(G[3],10);X.push({type:"header",content:J});continue}if(J.startsWith("-")){X.push({type:"remove",content:J.substring(1),lineNumber:Y}),Y++;continue}if(J.startsWith("+")){X.push({type:"add",content:J.substring(1),lineNumber:Q}),Q++;continue}if(J.startsWith(" ")||J===""){X.push({type:"context",content:J.substring(1),lineNumber:Q}),Y++,Q++;continue}}return X}var RZ=Yw.memo(({patch:$,startLine:Z,matchLine:X,terminalWidth:Y,maxLines:Q=20})=>{let J=e0(),G=Qw($),K=Math.max(...G.map((O)=>O.lineNumber||0)).toString().length+1,W=G.length,U=W>Q,H=U?G.slice(0,Q):G,F=W-Q;return F1(bW,{flexDirection:"column",marginTop:1,marginBottom:1,children:[F1(l1,{color:J.colors.muted,children:"─".repeat(Math.max(0,Math.min(60,Y)))},void 0,!1,void 0,this),U&&F1(l1,{color:J.colors.info,children:["\uD83D\uDCCA 显示前 ",Q," 行,共 ",W," 行 diff"]},void 0,!0,void 0,this),U&&F1(l1,{color:J.colors.muted,children:"─".repeat(Math.max(0,Math.min(60,Y)))},void 0,!1,void 0,this),H.map((O,z)=>{if(O.type==="header")return F1(l1,{color:J.colors.muted,dimColor:!0,children:O.content},z,!1,void 0,this);let _=O.lineNumber?O.lineNumber.toString().padStart(K," "):" ".repeat(K),B=" ",L,w;if(O.type==="add")B="+",w=J.colors.success,L=void 0;else if(O.type==="remove")B="-",w=J.colors.error,L=void 0;else w=J.colors.text.primary;let R=Math.max(0,Y-K-2),D=O.content;if(D.length>R)D=D.substring(0,R-3)+"...";return F1(l1,{color:w,backgroundColor:L,children:[F1(l1,{dimColor:!0,children:_},void 0,!1,void 0,this),F1(l1,{children:B},void 0,!1,void 0,this),F1(l1,{children:[" ",D]},void 0,!0,void 0,this)]},z,!0,void 0,this)}),U&&F1(bW,{marginTop:1,children:F1(l1,{color:J.colors.warning,dimColor:!0,children:["⚠️ 已隐藏剩余 ",F," 行 diff(总共 ",W," 行)"]},void 0,!0,void 0,this)},void 0,!1,void 0,this),F1(l1,{color:J.colors.muted,children:"─".repeat(Math.max(0,Math.min(60,Y)))},void 0,!1,void 0,this)]},void 0,!0,void 0,this)});import{Text as v1}from"ink";import Gw from"react";import Jw from"string-width";var
|
|
2804
|
+
`),X=[],Y=0,Q=0;for(let J of Z){if(J.startsWith("---")||J.startsWith("+++"))continue;if(J.startsWith("@@")){let G=J.match(/@@ -(\d+),?(\d*) \+(\d+),?(\d*) @@/);if(G)Y=parseInt(G[1],10),Q=parseInt(G[3],10);X.push({type:"header",content:J});continue}if(J.startsWith("-")){X.push({type:"remove",content:J.substring(1),lineNumber:Y}),Y++;continue}if(J.startsWith("+")){X.push({type:"add",content:J.substring(1),lineNumber:Q}),Q++;continue}if(J.startsWith(" ")||J===""){X.push({type:"context",content:J.substring(1),lineNumber:Q}),Y++,Q++;continue}}return X}var RZ=Yw.memo(({patch:$,startLine:Z,matchLine:X,terminalWidth:Y,maxLines:Q=20})=>{let J=e0(),G=Qw($),K=Math.max(...G.map((O)=>O.lineNumber||0)).toString().length+1,W=G.length,U=W>Q,H=U?G.slice(0,Q):G,F=W-Q;return F1(bW,{flexDirection:"column",marginTop:1,marginBottom:1,children:[F1(l1,{color:J.colors.muted,children:"─".repeat(Math.max(0,Math.min(60,Y)))},void 0,!1,void 0,this),U&&F1(l1,{color:J.colors.info,children:["\uD83D\uDCCA 显示前 ",Q," 行,共 ",W," 行 diff"]},void 0,!0,void 0,this),U&&F1(l1,{color:J.colors.muted,children:"─".repeat(Math.max(0,Math.min(60,Y)))},void 0,!1,void 0,this),H.map((O,z)=>{if(O.type==="header")return F1(l1,{color:J.colors.muted,dimColor:!0,children:O.content},z,!1,void 0,this);let _=O.lineNumber?O.lineNumber.toString().padStart(K," "):" ".repeat(K),B=" ",L,w;if(O.type==="add")B="+",w=J.colors.success,L=void 0;else if(O.type==="remove")B="-",w=J.colors.error,L=void 0;else w=J.colors.text.primary;let R=Math.max(0,Y-K-2),D=O.content;if(D.length>R)D=D.substring(0,R-3)+"...";return F1(l1,{color:w,backgroundColor:L,children:[F1(l1,{dimColor:!0,children:_},void 0,!1,void 0,this),F1(l1,{children:B},void 0,!1,void 0,this),F1(l1,{children:[" ",D]},void 0,!0,void 0,this)]},z,!0,void 0,this)}),U&&F1(bW,{marginTop:1,children:F1(l1,{color:J.colors.warning,dimColor:!0,children:["⚠️ 已隐藏剩余 ",F," 行 diff(总共 ",W," 行)"]},void 0,!0,void 0,this)},void 0,!1,void 0,this),F1(l1,{color:J.colors.muted,children:"─".repeat(Math.max(0,Math.min(60,Y)))},void 0,!1,void 0,this)]},void 0,!0,void 0,this)});import{Text as v1}from"ink";import Gw from"react";import Jw from"string-width";var B4=($)=>{let Z=$.replace(/\*\*(.*?)\*\*/g,"$1").replace(/\*(.*?)\*/g,"$1").replace(/_(.*?)_/g,"$1").replace(/~~(.*?)~~/g,"$1").replace(/`(.*?)`/g,"$1").replace(/<u>(.*?)<\/u>/g,"$1").replace(/\[(.*?)\]\(.*?\)/g,"$1");return Jw(Z)},AW=($,Z,X="...")=>{if(B4($)<=Z)return $;if(Z<=X.length)return X.substring(0,Z);let Q=0,J=$.length,G="";while(Q<=J){let q=Math.floor((Q+J)/2),K=$.substring(0,q);if(B4(K)<=Z-X.length)G=K,Q=q+1;else J=q-1}return G+X},RW=($)=>{return/[*_~`<[\]https?:]/.test($)};import{jsxDEV as O1,Fragment as Kw}from"react/jsx-dev-runtime";var VZ=2,DZ=1,MZ=2;function jZ($,Z){return`inline-${$}-${Z}`}var qw=({text:$})=>{let Z=e0();if(!RW($))return O1(v1,{children:$},void 0,!1,void 0,this);let X=[],Y=0,Q=0,J=0,G=/(\*\*.*?\*\*|\*(?!\s).*?(?<!\s)\*|_(?!\s).*?(?<!\s)_|~~.*?~~|`+[^`]+`+|\[.*?\]\(.*?\)|https?:\/\/\S+)/g,q;while((q=G.exec($))!==null){if(q.index>Y){let H=$.slice(Y,q.index);X.push(O1(v1,{children:H},jZ("text",Q++),!1,void 0,this))}let K=q[0],W=null,U=jZ("match",J++);try{if(K.startsWith("**")&&K.endsWith("**")&&K.length>VZ*2)W=O1(v1,{bold:!0,children:K.slice(VZ,-VZ)},U,!1,void 0,this);else if(K.length>DZ*2&&(K.startsWith("*")&&K.endsWith("*")||K.startsWith("_")&&K.endsWith("_"))){let H=$.substring(q.index-1,q.index),F=$.substring(G.lastIndex,G.lastIndex+1);if(!(/\w/.test(H)||/\w/.test(F)||/[./\\]/.test(H+F)))W=O1(v1,{italic:!0,children:K.slice(DZ,-DZ)},U,!1,void 0,this)}else if(K.startsWith("~~")&&K.endsWith("~~")&&K.length>MZ*2)W=O1(v1,{strikethrough:!0,children:K.slice(MZ,-MZ)},U,!1,void 0,this);else if(K.startsWith("`")&&K.endsWith("`")){let H=K.match(/^(`+)([^`]+)\1$/);if(H&&H[2])W=O1(v1,{color:Z.colors.syntax.keyword,backgroundColor:Z.colors.background.secondary,bold:!0,children:` ${H[2]} `},U,!1,void 0,this)}else if(K.startsWith("[")&&K.includes("](")&&K.endsWith(")")){let H=K.match(/\[(.*?)\]\((.*?)\)/);if(H){let F=H[1],O=H[2];W=O1(v1,{children:[F,O1(v1,{color:Z.colors.info,children:[" (",O,")"]},void 0,!0,void 0,this)]},U,!0,void 0,this)}}else if(K.match(/^https?:\/\//))W=O1(v1,{color:Z.colors.info,children:K},U,!1,void 0,this)}catch(H){console.error("InlineRenderer 解析错误:",K,H),W=null}X.push(W??O1(v1,{children:K},U,!1,void 0,this)),Y=G.lastIndex}if(Y<$.length){let K=$.slice(Y);X.push(O1(v1,{children:K},jZ("text",Q++),!1,void 0,this))}return O1(Kw,{children:X.filter((K)=>K!==null)},void 0,!1,void 0,this)},z1=Gw.memo(qw);import{Box as IZ,Text as VW}from"ink";import Ww from"react";import{jsxDEV as L8}from"react/jsx-dev-runtime";var Uw=({itemText:$,type:Z,marker:X,leadingWhitespace:Y=""})=>{let Q=Z==="ol"?`${X}. `:`${X} `,J=Q.length,G=Y.length;return L8(IZ,{paddingLeft:G+1,flexDirection:"row",children:[L8(IZ,{width:J,children:L8(VW,{children:Q},void 0,!1,void 0,this)},void 0,!1,void 0,this),L8(IZ,{flexGrow:1,children:L8(VW,{wrap:"wrap",children:L8(z1,{text:$},void 0,!1,void 0,this)},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},yZ=Ww.memo(Uw);import{Box as Hw,Text as L4}from"ink";import vZ from"react";import{jsxDEV as _1}from"react/jsx-dev-runtime";var DW=vZ.memo(({headers:$,rows:Z,terminalWidth:X})=>{let Y=e0();if($.length===0||Z.length===0)return null;let Q=$.map((F,O)=>{let z=B4(F),_=Math.max(...Z.map((B)=>B4(B[O]||"")));return Math.max(z,_)+2}),J=$.length+1,G=Q.reduce((F,O)=>F+O,0)+J,q=G>X?X/G:1,K=Q.map((F)=>Math.floor(F*q)),W=(F,O,z=!1)=>{let _=Math.max(0,O-2),B=B4(F),L=F;if(B>_)L=AW(F,_);let w=B4(L),R=Math.max(0,_-w);return _1(L4,{children:[z?_1(L4,{bold:!0,color:Y.colors.primary,children:_1(z1,{text:L},void 0,!1,void 0,this)},void 0,!1,void 0,this):_1(z1,{text:L},void 0,!1,void 0,this)," ".repeat(R)]},void 0,!0,void 0,this)},U=(F)=>{let z={top:{left:"┌",middle:"┬",right:"┐",horizontal:"─"},middle:{left:"├",middle:"┼",right:"┤",horizontal:"─"},bottom:{left:"└",middle:"┴",right:"┘",horizontal:"─"}}[F],_=K.map((L)=>z.horizontal.repeat(L)),B=z.left+_.join(z.middle)+z.right;return _1(L4,{color:Y.colors.text.muted,dimColor:!0,children:B},void 0,!1,void 0,this)},H=(F,O=!1)=>{let z=F.map((_,B)=>{let L=K[B]||0;return W(_||"",L,O)});return _1(L4,{children:[_1(L4,{color:Y.colors.text.muted,children:"│ "},void 0,!1,void 0,this),z.map((_,B)=>_1(vZ.Fragment,{children:[_,B<z.length-1&&_1(L4,{color:Y.colors.text.muted,children:" │ "},void 0,!1,void 0,this)]},B,!0,void 0,this)),_1(L4,{color:Y.colors.text.muted,children:" │"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)};return _1(Hw,{flexDirection:"column",marginY:1,children:[U("top"),H($,!0),U("middle"),Z.map((F,O)=>_1(vZ.Fragment,{children:H(F)},O,!1,void 0,this)),U("bottom")]},void 0,!0,void 0,this)});import{jsxDEV as x}from"react/jsx-dev-runtime";var Fw=($,Z,X)=>{switch($){case"user":return{color:Z.info,prefix:"> "};case"assistant":return{color:Z.success,prefix:"• "};case"system":return{color:Z.warning,prefix:"⚙ "};case"tool":{let Y=X&&"phase"in X?X.phase:void 0;return{color:Z.text.secondary,prefix:Y==="start"?"• ":Y==="complete"?" └ ":" "}}default:return{color:Z.text.primary,prefix:" "}}},Ow=w4.memo(({content:$,language:Z,terminalWidth:X,isPending:Y=!1,availableHeight:Q})=>{let J=e0();if(Y&&Q!==void 0){let G=$.split(`
|
|
2805
2805
|
`),q=4,K=Math.max(1,Q-4);if(G.length>K){let W=G.slice(0,K).join(`
|
|
2806
|
-
`);return x(R0,{flexDirection:"column",flexShrink:0,children:[x(t6,{content:W,language:Z,showLineNumbers:!0,terminalWidth:X},void 0,!1,void 0,this),x(s0,{color:J.colors.text.muted,dimColor:!0,children:"... generating more code ..."},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}}return x(t6,{content:$,language:Z,showLineNumbers:!0,terminalWidth:X},void 0,!1,void 0,this)}),zw=
|
|
2806
|
+
`);return x(R0,{flexDirection:"column",flexShrink:0,children:[x(t6,{content:W,language:Z,showLineNumbers:!0,terminalWidth:X},void 0,!1,void 0,this),x(s0,{color:J.colors.text.muted,dimColor:!0,children:"... generating more code ..."},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}}return x(t6,{content:$,language:Z,showLineNumbers:!0,terminalWidth:X},void 0,!1,void 0,this)}),zw=w4.memo(({content:$,level:Z})=>{let X=e0();switch(Z){case 1:return x(s0,{bold:!0,color:X.colors.primary,children:x(z1,{text:$},void 0,!1,void 0,this)},void 0,!1,void 0,this);case 2:return x(s0,{bold:!0,color:X.colors.primary,children:x(z1,{text:$},void 0,!1,void 0,this)},void 0,!1,void 0,this);case 3:return x(s0,{bold:!0,color:X.colors.text.primary,children:x(z1,{text:$},void 0,!1,void 0,this)},void 0,!1,void 0,this);case 4:return x(s0,{italic:!0,color:X.colors.text.muted,children:x(z1,{text:$},void 0,!1,void 0,this)},void 0,!1,void 0,this);default:return x(s0,{children:x(z1,{text:$},void 0,!1,void 0,this)},void 0,!1,void 0,this)}}),_w=w4.memo(({terminalWidth:$})=>{let Z=e0(),X=Math.max(0,Math.min($-4,80));return x(s0,{dimColor:!0,color:Z.colors.text.muted,children:"─".repeat(X)},void 0,!1,void 0,this)}),Bw=w4.memo(({content:$})=>{return x(s0,{wrap:"wrap",children:x(z1,{text:$},void 0,!1,void 0,this)},void 0,!1,void 0,this)}),Lw=w4.memo(({content:$})=>{let Z=e0();return x(R0,{flexDirection:"row",gap:1,children:[x(s0,{color:Z.colors.info,children:"⏳"},void 0,!1,void 0,this),x(s0,{color:Z.colors.text.muted,italic:!0,children:$},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}),ww=w4.memo(({detail:$,terminalWidth:Z})=>{let X=e0(),Y=50,Q=$.split(`
|
|
2807
2807
|
`);while(Q.length>0&&Q[0].trim()==="")Q.shift();while(Q.length>0&&Q[Q.length-1].trim()==="")Q.pop();let J=Q.length>50,G=J?Q.slice(0,50):Q,q=G.join(`
|
|
2808
2808
|
`),K=q.includes("<<<DIFF>>>"),W=q.includes("```");if(K){let U=q.match(/<<<DIFF>>>\s*({[\s\S]*?})\s*<<<\/DIFF>>>/);if(U)try{let H=JSON.parse(U[1]);return x(R0,{flexDirection:"column",children:[x(RZ,{patch:H.patch,startLine:H.startLine,matchLine:H.matchLine,terminalWidth:Z},void 0,!1,void 0,this),J&&x(R0,{marginTop:1,children:x(s0,{dimColor:!0,color:X.colors.text.muted,children:["... 省略 ",Q.length-50," 行 ..."]},void 0,!0,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}catch{}}if(W){let U=q.match(/```(\w+)?\s*\n([\s\S]*?)\n```/);if(U){let H=U[1]||"text",F=U[2];return x(R0,{flexDirection:"column",children:[x(t6,{content:F,language:H,showLineNumbers:!1,terminalWidth:Z},void 0,!1,void 0,this),J&&x(R0,{marginTop:1,children:x(s0,{dimColor:!0,color:X.colors.text.muted,children:["... 省略 ",Q.length-50," 行 ..."]},void 0,!0,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}}return x(R0,{flexDirection:"column",children:[G.map((U,H)=>x(s0,{color:X.colors.text.primary,children:U},H,!1,void 0,this)),J&&x(R0,{marginTop:1,children:x(s0,{dimColor:!0,color:X.colors.text.muted,children:["... 省略 ",Q.length-50," 行 ..."]},void 0,!0,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)});function Nw($,Z,X,Y=80){if(!X||Z===void 0||Z<=0)return{content:$,isTruncated:!1,hiddenLines:0};let J=Math.max(1,Z-8),G=Math.max(40,Y*0.8),q=J*G;if($.length<=q)return{content:$,isTruncated:!1,hiddenLines:0};let K=Math.floor(q*0.9),W=$.length-K,U=W,H=$.indexOf(`
|
|
2809
|
-
`,W);if(H!==-1&&H-W<G)U=H+1;let F=$.slice(U),z=($.slice(0,U).match(/\n/g)||[]).length+1;return{content:F,isTruncated:!0,hiddenLines:z}}var
|
|
2810
|
-
`);if(y===-1)return{completedContent:"",currentLine:S};return{completedContent:S.slice(0,y+1),currentLine:S.slice(y+1)}},[S,Q,L,O]),b=MW({content:"",blocks:[]}),n=w8(()=>{if(L)return F??[];if(m)return m;if(k.current&&k.current.messageId===H)return k.current.blocks;let y=b.current;if(!Q||!j.startsWith(y.content)){let X0=a4(j);return b.current={content:j,blocks:X0},X0}if(j===y.content)return y.blocks;let u=j.slice(y.content.length),t=a4(u),g=[...y.blocks,...t];return b.current={content:j,blocks:g},g},[j,Q,L,F]);return x(R0,{flexDirection:"column",marginBottom:v?1:0,flexShrink:0,children:[T&&x(R0,{flexDirection:"row",flexShrink:0,children:[x(R0,{width:V,flexShrink:0},void 0,!1,void 0,this),x(s0,{color:B.colors.text.muted,dimColor:!0,children:["↑ ",c," lines above (streaming...)"]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),n.map((y,u)=>{if(y.type==="empty")return x(R0,{height:1,flexShrink:0},u,!1,void 0,this);return x(R0,{flexDirection:"row",flexShrink:0,children:[u===0&&!G&&x(R0,{marginRight:1,flexShrink:0,children:x(s0,{color:R,bold:!0,children:D},void 0,!1,void 0,this)},void 0,!1,void 0,this),(u>0||G)&&x(R0,{width:V,flexShrink:0},void 0,!1,void 0,this),x(R0,{flexGrow:1,flexShrink:0,children:y.type==="code"?_?x(s0,{wrap:"wrap",children:y.content},void 0,!1,void 0,this):x(Ow,{content:y.content,language:y.language,terminalWidth:X-V,isPending:Q,availableHeight:J},void 0,!1,void 0,this):y.type==="table"&&y.tableData?x(DW,{headers:y.tableData.headers,rows:y.tableData.rows,terminalWidth:X-V},void 0,!1,void 0,this):y.type==="heading"?x(zw,{content:y.content,level:y.level||1},void 0,!1,void 0,this):y.type==="list"?x(yZ,{type:y.listType||"ul",marker:y.marker||"-",itemText:y.content,leadingWhitespace:" ".repeat(y.indentation||0)},void 0,!1,void 0,this):y.type==="hr"?x(_w,{terminalWidth:X-V},void 0,!1,void 0,this):y.type==="diff"&&y.diffData?x(RZ,{patch:y.diffData.patch,startLine:y.diffData.startLine,matchLine:y.diffData.matchLine,terminalWidth:X-V},void 0,!1,void 0,this):y.type==="command-message"?x(Lw,{content:y.content},void 0,!1,void 0,this):x(Bw,{content:y.content},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},u,!0,void 0,this)}),M&&x(R0,{flexDirection:"row",flexShrink:0,children:[n.length===0&&!G?x(R0,{marginRight:1,flexShrink:0,children:x(s0,{color:R,bold:!0,children:D},void 0,!1,void 0,this)},void 0,!1,void 0,this):x(R0,{width:V,flexShrink:0},void 0,!1,void 0,this),x(R0,{flexGrow:1,flexShrink:0,children:x(s0,{wrap:"wrap",children:M},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)},($,Z)=>{return $.content===Z.content&&$.role===Z.role&&$.terminalWidth===Z.terminalWidth&&$.isPending===Z.isPending&&$.availableTerminalHeight===Z.availableTerminalHeight&&$.hidePrefix===Z.hidePrefix&&$.noMargin===Z.noMargin&&$.renderPlainTextOnly===Z.renderPlainTextOnly&&$.streamingHiddenLines===Z.streamingHiddenLines&&$.streamingLines===Z.streamingLines&&$.messageId===Z.messageId&&$.metadata===Z.metadata&&$.blocksOverride===Z.blocksOverride&&$.currentLineOverride===Z.currentLineOverride&&$.streamingMode===Z.streamingMode&&$.renderCodeBlocksAsPlainText===Z.renderCodeBlocksAsPlainText});import{jsxDEV as l0,Fragment as Mw}from"react/jsx-dev-runtime";var Vw=PZ.memo(({label:$,isSelected:Z})=>l0(E1,{color:Z?"yellow":void 0,children:$},void 0,!1,void 0,this)),Dw=PZ.memo(({details:$,headerColor:Z,isPlanModeExit:X,isPlanModeEnter:Y,terminalWidth:Q})=>l0(Mw,{children:[$.title&&l0(B1,{marginBottom:1,children:l0(E1,{bold:!0,children:$.title},void 0,!1,void 0,this)},void 0,!1,void 0,this),l0(B1,{marginBottom:1,children:l0(E1,{children:$.message},void 0,!1,void 0,this)},void 0,!1,void 0,this),($.planContent||$.details)&&l0(B1,{flexDirection:"column",marginBottom:1,borderStyle:"single",borderColor:Z,padding:1,children:[l0(E1,{bold:!0,color:Z,children:X?"\uD83D\uDCCB Implementation Plan:":Y?"\uD83D\uDCDD Details:":"\uD83D\uDCC4 Operation Details:"},void 0,!1,void 0,this),l0(B1,{marginTop:1,children:l0(k4,{content:$.planContent||$.details||"",role:"assistant",terminalWidth:Q-4},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),$.risks&&$.risks.length>0&&l0(B1,{flexDirection:"column",marginBottom:1,children:[l0(E1,{color:"red",bold:!0,children:"⚠️ 风险提示:"},void 0,!1,void 0,this),$.risks.map((J,G)=>l0(B1,{marginLeft:2,children:l0(E1,{color:"red",children:["• ",J]},void 0,!0,void 0,this)},G,!1,void 0,this))]},void 0,!0,void 0,this),$.affectedFiles&&$.affectedFiles.length>0&&l0(B1,{flexDirection:"column",marginBottom:1,children:[l0(E1,{color:"yellow",children:"\uD83D\uDCC1 影响的文件:"},void 0,!1,void 0,this),$.affectedFiles.slice(0,3).map((J,G)=>l0(B1,{marginLeft:2,children:l0(E1,{children:["• ",J]},void 0,!0,void 0,this)},G,!1,void 0,this)),$.affectedFiles.length>3&&l0(B1,{marginLeft:2,children:l0(E1,{color:"gray",children:["...还有 ",$.affectedFiles.length-3," 个文件"]},void 0,!0,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)),IW=PZ.memo(({details:$,onResponse:Z})=>{let{stdout:X}=Aw(),Y=X.columns||80,J=o$()==="confirmation-prompt",G=X$(!1),q=$.type==="exitPlanMode",K=$.type==="enterPlanMode",W=$.type==="maxTurnsExceeded";bw((F,O)=>{if(O.ctrl&&F==="c"||O.meta&&F==="c"){G();return}if(O.escape){Z({approved:!1,reason:"用户取消"});return}let z=F.toLowerCase();if(q){if(z==="y"){Z({approved:!0,targetMode:"autoEdit"});return}if(z==="s"){Z({approved:!0,targetMode:"default"});return}if(z==="n"){Z({approved:!1,reason:"方案需要改进"});return}}else if(K){if(z==="y"){Z({approved:!0});return}if(z==="n"){Z({approved:!1,reason:"用户拒绝进入 Plan 模式"});return}}else if(W){if(z==="y"){Z({approved:!0});return}if(z==="n"){Z({approved:!1,reason:"用户选择停止"});return}}else{if(z==="y"){Z({approved:!0,scope:"once"});return}if(z==="s"){Z({approved:!0,scope:"session"});return}if(z==="n"){Z({approved:!1,reason:"用户拒绝"});return}}},{isActive:J});let U=jW(()=>{if(q)return[{key:"approve-auto",label:"[Y] Yes, execute with auto-edit mode",value:{approved:!0,targetMode:"autoEdit"}},{key:"approve-default",label:"[S] Yes, execute with default mode (ask for each operation)",value:{approved:!0,targetMode:"default"}},{key:"reject",label:"[N] No, keep planning",value:{approved:!1,reason:"方案需要改进"}}];if(K)return[{key:"approve",label:"[Y] Yes, enter Plan mode",value:{approved:!0}},{key:"reject",label:"[N] No, proceed directly",value:{approved:!1,reason:"用户拒绝进入 Plan 模式"}}];if(W)return[{key:"continue",label:"[Y] Yes, continue",value:{approved:!0}},{key:"stop",label:"[N] No, stop here",value:{approved:!1,reason:"用户选择停止"}}];return[{key:"approve-once",label:"[Y] Yes (once only)",value:{approved:!0,scope:"once"}},{key:"approve-session",label:"[S] Yes, remember for this project (Shift+Tab)",value:{approved:!0,scope:"session"}},{key:"reject",label:"[N] No",value:{approved:!1,reason:"用户拒绝"}}]},[q,K,W]),H=jW(()=>{if(q)return{color:"cyan",title:"\uD83D\uDD35 Plan Mode - Review Implementation Plan"};if(K)return{color:"magenta",title:"\uD83D\uDFE3 Enter Plan Mode?"};if(W)return{color:"yellow",title:"⚡ Max Turns Exceeded"};return{color:"yellow",title:"\uD83D\uDD14 Confirmation Required"}},[q,K,W]);return l0(B1,{flexDirection:"column",borderStyle:"round",borderColor:J?H.color:"gray",padding:1,children:[l0(B1,{marginBottom:1,children:l0(E1,{bold:!0,color:H.color,children:H.title},void 0,!1,void 0,this)},void 0,!1,void 0,this),l0(Dw,{details:$,headerColor:H.color,isPlanModeExit:q,isPlanModeEnter:K,terminalWidth:Y},void 0,!1,void 0,this),l0(B1,{flexDirection:"column",children:[l0(E1,{color:"gray",children:"使用 ↑ ↓ 选择,回车确认(支持 Y/S/N 快捷键,ESC 取消)"},void 0,!1,void 0,this),l0(Rw,{items:U,isFocused:J,itemComponent:Vw,onSelect:(F)=>{Z(F.value)}},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)});r$();C2();i4();import{Box as j0,Text as F0,useInput as jw}from"ink";import yW from"ink-text-input";import{useState as U4}from"react";import{jsxDEV as p}from"react/jsx-dev-runtime";var w3=[{action:"add",description:"Add a new hook"},{action:"status",description:"Show hooks status"},{action:"list",description:"List all configured hooks"}],e6=[{location:"local",name:"Project settings (local)",description:"Saved in .blade/settings.local.json"},{location:"project",name:"Project settings",description:"Checked in at .blade/settings.json"},{location:"user",name:"User settings",description:"Saved in at ~/.blade/settings.json"}],$9=[{event:"PreToolUse",description:"Before tool execution"},{event:"PostToolUse",description:"After tool execution"},{event:"PostToolUseFailure",description:"After tool execution fails"},{event:"PermissionRequest",description:"When permission is requested"},{event:"UserPromptSubmit",description:"Before processing user prompt"},{event:"Stop",description:"When Claude stops responding"},{event:"SubagentStop",description:"When subagent stops"},{event:"SessionStart",description:"When session starts"},{event:"SessionEnd",description:"When session ends"},{event:"Notification",description:"When notification is sent"},{event:"Compaction",description:"Before context compaction"}],Iw=[`jq -r '.tool_input.file_path | select(endswith(".go"))' | xargs -r gofmt -w`,`jq -r '"\\(.tool_input.command) - \\(.tool_input.description // "No description")"' >> ~/.blade/bash-command-log.txt`,"/usr/local/bin/security_check.sh","python3 ~/hooks/validate_changes.py"],vW=({onClose:$,onSave:Z})=>{let X=g$.getTheme(),[Y,Q]=U4("action"),[J,G]=U4(0),[q,K]=U4(0),[W,U]=U4(0),[H,F]=U4(""),[O,z]=U4(""),[_,B]=U4(null),[L,w]=U4(!1),[R,D]=U4(null),V=w3[J],I=$9[q],v=e6[W],N=()=>{if(R){D(null);return}switch(Y){case"action":$();break;case"event":Q("action");break;case"matcher":Q("event");break;case"command":Q("matcher");break;case"location":Q("command");break;case"confirm":Q("location");break}};jw((j,M)=>{if(M.escape){N();return}if(Y==="action"){if(M.upArrow)G((b)=>b>0?b-1:w3.length-1);else if(M.downArrow)G((b)=>b<w3.length-1?b+1:0);else if(M.return)k()}else if(Y==="event"){if(M.upArrow)K((b)=>b>0?b-1:$9.length-1);else if(M.downArrow)K((b)=>b<$9.length-1?b+1:0);else if(M.return)Q("matcher")}else if(Y==="location"){if(M.upArrow)U((b)=>b>0?b-1:e6.length-1);else if(M.downArrow)U((b)=>b<e6.length-1?b+1:0);else if(M.return)Q("confirm")}else if(Y==="confirm"){if(M.return)c()}});let k=()=>{let j=w3[J].action;if(j==="add")Q("event");else if(j==="status")m();else if(j==="list")s()},m=()=>{let j=M0.getInstance(),M=j.isEnabled(),b=j.getConfig(),n={};for(let u of Object.values(C1)){let t=b[u];if(t&&Array.isArray(t)){let g=t.reduce((X0,h)=>X0+(h.hooks?.length||0),0);if(g>0)n[u]=g}}let y=[`Status: ${M?"✅ Enabled":"⏸️ Disabled"}`,""];if(Object.keys(n).length>0){y.push("Configured hooks:");for(let[u,t]of Object.entries(n))y.push(` ${u}: ${t} hook(s)`)}else y.push("No hooks configured");D(y.join(`
|
|
2809
|
+
`,W);if(H!==-1&&H-W<G)U=H+1;let F=$.slice(U),z=($.slice(0,U).match(/\n/g)||[]).length+1;return{content:F,isTruncated:!0,hiddenLines:z}}var k2=w4.memo(({content:$,role:Z,terminalWidth:X,metadata:Y,isPending:Q=!1,availableTerminalHeight:J,hidePrefix:G=!1,noMargin:q=!1,renderPlainTextOnly:K=!1,streamingLines:W,streamingHiddenLines:U,messageId:H,blocksOverride:F,currentLineOverride:O,streamingMode:z="text",renderCodeBlocksAsPlainText:_=!1})=>{let B=e0(),L=F!==void 0,w=w8(()=>Fw(Z,B.colors,Y),[Z,B.colors,Y]),{color:R,prefix:D}=w,V=D.length+1,I=Z==="tool"&&Y?.phase==="start",v=!q&&!I,N=w8(()=>{if(!K)return[];return $.split(/\r?\n/)},[$,K]);if(!L&&Q){let y=W??$.split(/\r?\n/),u=U??0,t=!1,g=!1,X0=!1;if(z!=="text")t=z==="code",g=z==="diff",X0=z==="table";return x(R0,{flexDirection:"column",marginBottom:v?1:0,flexShrink:0,children:[u>0&&x(R0,{flexDirection:"row",flexShrink:0,children:[x(R0,{width:V,flexShrink:0},void 0,!1,void 0,this),x(s0,{color:B.colors.text.muted,dimColor:!0,children:["↑ ",u," lines above (streaming...)"]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),y.map((h,L0)=>{if(z==="text"){if(h.match(I0.codeBlock))t=!t;else if(h.match(I0.diffStart))g=!0;else if(h.match(I0.diffEnd))g=!1;else if(h.match(I0.table))X0=!0;else if(X0&&!h.match(I0.table))X0=!1}let G0=z==="text"&&!t&&!g&&!X0,w0=G0?h.match(I0.ulItem):null,Y$=G0?h.match(I0.olItem):null,G$=w0??Y$;return x(R0,{flexDirection:"row",flexShrink:0,children:[L0===0&&!G?x(R0,{marginRight:1,flexShrink:0,children:x(s0,{color:R,bold:!0,children:D},void 0,!1,void 0,this)},void 0,!1,void 0,this):x(R0,{width:V,flexShrink:0},void 0,!1,void 0,this),x(R0,{flexGrow:1,flexShrink:0,children:G$?x(yZ,{type:w0?"ul":"ol",marker:G$[2],itemText:G$[3],leadingWhitespace:G$[1]},void 0,!1,void 0,this):x(s0,{wrap:"wrap",children:h===""?" ":h},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},L0,!0,void 0,this)})]},void 0,!0,void 0,this)}if(!L&&K)return x(R0,{flexDirection:"column",marginBottom:v?1:0,flexShrink:0,children:N.map((y,u)=>x(R0,{flexDirection:"row",flexShrink:0,children:[u===0&&!G?x(R0,{marginRight:1,flexShrink:0,children:x(s0,{color:R,bold:!0,children:D},void 0,!1,void 0,this)},void 0,!1,void 0,this):x(R0,{width:V,flexShrink:0},void 0,!1,void 0,this),x(R0,{flexGrow:1,flexShrink:0,children:x(s0,{wrap:"wrap",children:y===""?" ":y},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},u,!0,void 0,this))},void 0,!1,void 0,this);let k=MW(null);EZ(()=>{k.current=null},[H]);let m=w8(()=>{if(L)return null;if(!H)return null;return jX(H)},[H,L]);EZ(()=>{if(L)return;if(!m||!H)return;k.current={messageId:H,blocks:m}},[m,H,L]),EZ(()=>{if(L)return;if(!m||!H)return;yX(H)},[m,H,L]);let s=w8(()=>L?{content:$,isTruncated:!1,hiddenLines:0}:Nw($,J,Q,X),[$,J,Q,X,L]),{content:S,isTruncated:T,hiddenLines:c}=s;if(!L&&Z==="tool"&&Y&&"detail"in Y){let y=Y;if(y.detail)return x(R0,{flexDirection:"column",marginBottom:q?0:1,children:[x(R0,{flexDirection:"row",children:[x(R0,{marginRight:1,children:x(s0,{color:R,bold:!0,children:D},void 0,!1,void 0,this)},void 0,!1,void 0,this),x(s0,{color:R,children:$},void 0,!1,void 0,this)]},void 0,!0,void 0,this),x(R0,{marginLeft:D.length+1,children:x(ww,{detail:y.detail,terminalWidth:X-(D.length+1)},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}let{completedContent:j,currentLine:M}=w8(()=>{if(L)return{completedContent:"",currentLine:O??""};if(!Q)return{completedContent:S,currentLine:""};let y=S.lastIndexOf(`
|
|
2810
|
+
`);if(y===-1)return{completedContent:"",currentLine:S};return{completedContent:S.slice(0,y+1),currentLine:S.slice(y+1)}},[S,Q,L,O]),b=MW({content:"",blocks:[]}),n=w8(()=>{if(L)return F??[];if(m)return m;if(k.current&&k.current.messageId===H)return k.current.blocks;let y=b.current;if(!Q||!j.startsWith(y.content)){let X0=a2(j);return b.current={content:j,blocks:X0},X0}if(j===y.content)return y.blocks;let u=j.slice(y.content.length),t=a2(u),g=[...y.blocks,...t];return b.current={content:j,blocks:g},g},[j,Q,L,F]);return x(R0,{flexDirection:"column",marginBottom:v?1:0,flexShrink:0,children:[T&&x(R0,{flexDirection:"row",flexShrink:0,children:[x(R0,{width:V,flexShrink:0},void 0,!1,void 0,this),x(s0,{color:B.colors.text.muted,dimColor:!0,children:["↑ ",c," lines above (streaming...)"]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),n.map((y,u)=>{if(y.type==="empty")return x(R0,{height:1,flexShrink:0},u,!1,void 0,this);return x(R0,{flexDirection:"row",flexShrink:0,children:[u===0&&!G&&x(R0,{marginRight:1,flexShrink:0,children:x(s0,{color:R,bold:!0,children:D},void 0,!1,void 0,this)},void 0,!1,void 0,this),(u>0||G)&&x(R0,{width:V,flexShrink:0},void 0,!1,void 0,this),x(R0,{flexGrow:1,flexShrink:0,children:y.type==="code"?_?x(s0,{wrap:"wrap",children:y.content},void 0,!1,void 0,this):x(Ow,{content:y.content,language:y.language,terminalWidth:X-V,isPending:Q,availableHeight:J},void 0,!1,void 0,this):y.type==="table"&&y.tableData?x(DW,{headers:y.tableData.headers,rows:y.tableData.rows,terminalWidth:X-V},void 0,!1,void 0,this):y.type==="heading"?x(zw,{content:y.content,level:y.level||1},void 0,!1,void 0,this):y.type==="list"?x(yZ,{type:y.listType||"ul",marker:y.marker||"-",itemText:y.content,leadingWhitespace:" ".repeat(y.indentation||0)},void 0,!1,void 0,this):y.type==="hr"?x(_w,{terminalWidth:X-V},void 0,!1,void 0,this):y.type==="diff"&&y.diffData?x(RZ,{patch:y.diffData.patch,startLine:y.diffData.startLine,matchLine:y.diffData.matchLine,terminalWidth:X-V},void 0,!1,void 0,this):y.type==="command-message"?x(Lw,{content:y.content},void 0,!1,void 0,this):x(Bw,{content:y.content},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},u,!0,void 0,this)}),M&&x(R0,{flexDirection:"row",flexShrink:0,children:[n.length===0&&!G?x(R0,{marginRight:1,flexShrink:0,children:x(s0,{color:R,bold:!0,children:D},void 0,!1,void 0,this)},void 0,!1,void 0,this):x(R0,{width:V,flexShrink:0},void 0,!1,void 0,this),x(R0,{flexGrow:1,flexShrink:0,children:x(s0,{wrap:"wrap",children:M},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)},($,Z)=>{return $.content===Z.content&&$.role===Z.role&&$.terminalWidth===Z.terminalWidth&&$.isPending===Z.isPending&&$.availableTerminalHeight===Z.availableTerminalHeight&&$.hidePrefix===Z.hidePrefix&&$.noMargin===Z.noMargin&&$.renderPlainTextOnly===Z.renderPlainTextOnly&&$.streamingHiddenLines===Z.streamingHiddenLines&&$.streamingLines===Z.streamingLines&&$.messageId===Z.messageId&&$.metadata===Z.metadata&&$.blocksOverride===Z.blocksOverride&&$.currentLineOverride===Z.currentLineOverride&&$.streamingMode===Z.streamingMode&&$.renderCodeBlocksAsPlainText===Z.renderCodeBlocksAsPlainText});import{jsxDEV as l0,Fragment as Mw}from"react/jsx-dev-runtime";var Vw=PZ.memo(({label:$,isSelected:Z})=>l0(E1,{color:Z?"yellow":void 0,children:$},void 0,!1,void 0,this)),Dw=PZ.memo(({details:$,headerColor:Z,isPlanModeExit:X,isPlanModeEnter:Y,terminalWidth:Q})=>l0(Mw,{children:[$.title&&l0(B1,{marginBottom:1,children:l0(E1,{bold:!0,children:$.title},void 0,!1,void 0,this)},void 0,!1,void 0,this),l0(B1,{marginBottom:1,children:l0(E1,{children:$.message},void 0,!1,void 0,this)},void 0,!1,void 0,this),($.planContent||$.details)&&l0(B1,{flexDirection:"column",marginBottom:1,borderStyle:"single",borderColor:Z,padding:1,children:[l0(E1,{bold:!0,color:Z,children:X?"\uD83D\uDCCB Implementation Plan:":Y?"\uD83D\uDCDD Details:":"\uD83D\uDCC4 Operation Details:"},void 0,!1,void 0,this),l0(B1,{marginTop:1,children:l0(k2,{content:$.planContent||$.details||"",role:"assistant",terminalWidth:Q-4},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),$.risks&&$.risks.length>0&&l0(B1,{flexDirection:"column",marginBottom:1,children:[l0(E1,{color:"red",bold:!0,children:"⚠️ 风险提示:"},void 0,!1,void 0,this),$.risks.map((J,G)=>l0(B1,{marginLeft:2,children:l0(E1,{color:"red",children:["• ",J]},void 0,!0,void 0,this)},G,!1,void 0,this))]},void 0,!0,void 0,this),$.affectedFiles&&$.affectedFiles.length>0&&l0(B1,{flexDirection:"column",marginBottom:1,children:[l0(E1,{color:"yellow",children:"\uD83D\uDCC1 影响的文件:"},void 0,!1,void 0,this),$.affectedFiles.slice(0,3).map((J,G)=>l0(B1,{marginLeft:2,children:l0(E1,{children:["• ",J]},void 0,!0,void 0,this)},G,!1,void 0,this)),$.affectedFiles.length>3&&l0(B1,{marginLeft:2,children:l0(E1,{color:"gray",children:["...还有 ",$.affectedFiles.length-3," 个文件"]},void 0,!0,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)),IW=PZ.memo(({details:$,onResponse:Z})=>{let{stdout:X}=Aw(),Y=X.columns||80,J=o$()==="confirmation-prompt",G=X$(!1),q=$.type==="exitPlanMode",K=$.type==="enterPlanMode",W=$.type==="maxTurnsExceeded";bw((F,O)=>{if(O.ctrl&&F==="c"||O.meta&&F==="c"){G();return}if(O.escape){Z({approved:!1,reason:"用户取消"});return}let z=F.toLowerCase();if(q){if(z==="y"){Z({approved:!0,targetMode:"autoEdit"});return}if(z==="s"){Z({approved:!0,targetMode:"default"});return}if(z==="n"){Z({approved:!1,reason:"方案需要改进"});return}}else if(K){if(z==="y"){Z({approved:!0});return}if(z==="n"){Z({approved:!1,reason:"用户拒绝进入 Plan 模式"});return}}else if(W){if(z==="y"){Z({approved:!0});return}if(z==="n"){Z({approved:!1,reason:"用户选择停止"});return}}else{if(z==="y"){Z({approved:!0,scope:"once"});return}if(z==="s"){Z({approved:!0,scope:"session"});return}if(z==="n"){Z({approved:!1,reason:"用户拒绝"});return}}},{isActive:J});let U=jW(()=>{if(q)return[{key:"approve-auto",label:"[Y] Yes, execute with auto-edit mode",value:{approved:!0,targetMode:"autoEdit"}},{key:"approve-default",label:"[S] Yes, execute with default mode (ask for each operation)",value:{approved:!0,targetMode:"default"}},{key:"reject",label:"[N] No, keep planning",value:{approved:!1,reason:"方案需要改进"}}];if(K)return[{key:"approve",label:"[Y] Yes, enter Plan mode",value:{approved:!0}},{key:"reject",label:"[N] No, proceed directly",value:{approved:!1,reason:"用户拒绝进入 Plan 模式"}}];if(W)return[{key:"continue",label:"[Y] Yes, continue",value:{approved:!0}},{key:"stop",label:"[N] No, stop here",value:{approved:!1,reason:"用户选择停止"}}];return[{key:"approve-once",label:"[Y] Yes (once only)",value:{approved:!0,scope:"once"}},{key:"approve-session",label:"[S] Yes, remember for this project (Shift+Tab)",value:{approved:!0,scope:"session"}},{key:"reject",label:"[N] No",value:{approved:!1,reason:"用户拒绝"}}]},[q,K,W]),H=jW(()=>{if(q)return{color:"cyan",title:"\uD83D\uDD35 Plan Mode - Review Implementation Plan"};if(K)return{color:"magenta",title:"\uD83D\uDFE3 Enter Plan Mode?"};if(W)return{color:"yellow",title:"⚡ Max Turns Exceeded"};return{color:"yellow",title:"\uD83D\uDD14 Confirmation Required"}},[q,K,W]);return l0(B1,{flexDirection:"column",borderStyle:"round",borderColor:J?H.color:"gray",padding:1,children:[l0(B1,{marginBottom:1,children:l0(E1,{bold:!0,color:H.color,children:H.title},void 0,!1,void 0,this)},void 0,!1,void 0,this),l0(Dw,{details:$,headerColor:H.color,isPlanModeExit:q,isPlanModeEnter:K,terminalWidth:Y},void 0,!1,void 0,this),l0(B1,{flexDirection:"column",children:[l0(E1,{color:"gray",children:"使用 ↑ ↓ 选择,回车确认(支持 Y/S/N 快捷键,ESC 取消)"},void 0,!1,void 0,this),l0(Rw,{items:U,isFocused:J,itemComponent:Vw,onSelect:(F)=>{Z(F.value)}},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)});r$();C4();i2();import{Box as j0,Text as F0,useInput as jw}from"ink";import yW from"ink-text-input";import{useState as U2}from"react";import{jsxDEV as p}from"react/jsx-dev-runtime";var w3=[{action:"add",description:"Add a new hook"},{action:"status",description:"Show hooks status"},{action:"list",description:"List all configured hooks"}],e6=[{location:"local",name:"Project settings (local)",description:"Saved in .blade/settings.local.json"},{location:"project",name:"Project settings",description:"Checked in at .blade/settings.json"},{location:"user",name:"User settings",description:"Saved in at ~/.blade/settings.json"}],$9=[{event:"PreToolUse",description:"Before tool execution"},{event:"PostToolUse",description:"After tool execution"},{event:"PostToolUseFailure",description:"After tool execution fails"},{event:"PermissionRequest",description:"When permission is requested"},{event:"UserPromptSubmit",description:"Before processing user prompt"},{event:"Stop",description:"When Claude stops responding"},{event:"SubagentStop",description:"When subagent stops"},{event:"SessionStart",description:"When session starts"},{event:"SessionEnd",description:"When session ends"},{event:"Notification",description:"When notification is sent"},{event:"Compaction",description:"Before context compaction"}],Iw=[`jq -r '.tool_input.file_path | select(endswith(".go"))' | xargs -r gofmt -w`,`jq -r '"\\(.tool_input.command) - \\(.tool_input.description // "No description")"' >> ~/.blade/bash-command-log.txt`,"/usr/local/bin/security_check.sh","python3 ~/hooks/validate_changes.py"],vW=({onClose:$,onSave:Z})=>{let X=g$.getTheme(),[Y,Q]=U2("action"),[J,G]=U2(0),[q,K]=U2(0),[W,U]=U2(0),[H,F]=U2(""),[O,z]=U2(""),[_,B]=U2(null),[L,w]=U2(!1),[R,D]=U2(null),V=w3[J],I=$9[q],v=e6[W],N=()=>{if(R){D(null);return}switch(Y){case"action":$();break;case"event":Q("action");break;case"matcher":Q("event");break;case"command":Q("matcher");break;case"location":Q("command");break;case"confirm":Q("location");break}};jw((j,M)=>{if(M.escape){N();return}if(Y==="action"){if(M.upArrow)G((b)=>b>0?b-1:w3.length-1);else if(M.downArrow)G((b)=>b<w3.length-1?b+1:0);else if(M.return)k()}else if(Y==="event"){if(M.upArrow)K((b)=>b>0?b-1:$9.length-1);else if(M.downArrow)K((b)=>b<$9.length-1?b+1:0);else if(M.return)Q("matcher")}else if(Y==="location"){if(M.upArrow)U((b)=>b>0?b-1:e6.length-1);else if(M.downArrow)U((b)=>b<e6.length-1?b+1:0);else if(M.return)Q("confirm")}else if(Y==="confirm"){if(M.return)c()}});let k=()=>{let j=w3[J].action;if(j==="add")Q("event");else if(j==="status")m();else if(j==="list")s()},m=()=>{let j=M0.getInstance(),M=j.isEnabled(),b=j.getConfig(),n={};for(let u of Object.values(C1)){let t=b[u];if(t&&Array.isArray(t)){let g=t.reduce((X0,h)=>X0+(h.hooks?.length||0),0);if(g>0)n[u]=g}}let y=[`Status: ${M?"✅ Enabled":"⏸️ Disabled"}`,""];if(Object.keys(n).length>0){y.push("Configured hooks:");for(let[u,t]of Object.entries(n))y.push(` ${u}: ${t} hook(s)`)}else y.push("No hooks configured");D(y.join(`
|
|
2811
2811
|
`))},s=()=>{let M=M0.getInstance().getConfig(),b=[],n=!1;for(let y of Object.values(C1)){let u=M[y];if(!u||!Array.isArray(u)||u.length===0)continue;n=!0,b.push(`${y}:`);for(let t of u){let g=t.matcher,X0="all";if(g?.tools)X0=`tools: ${Array.isArray(g.tools)?g.tools.join(", "):g.tools}`;b.push(` [${X0}]`);for(let h of t.hooks||[])if(h.type==="command")b.push(` → ${h.command}`)}b.push("")}if(!n)b.push("No hooks configured"),b.push(""),b.push("Configure hooks in .blade/settings.local.json");D(b.join(`
|
|
2812
|
-
`))},S=()=>{Q("command")},T=()=>{if(!O.trim()){B("Command cannot be empty");return}B(null),Q("location")},c=async()=>{w(!0),B(null);try{let j=M0.getInstance(),M=await import("node:fs/promises"),b=await import("node:path"),n=await import("node:os"),y={matcher:H.trim()?{tools:H.trim()}:{},hooks:[{type:"command",command:O.trim()}]},u;switch(v.location){case"local":u=b.join(process.cwd(),".blade","settings.local.json");break;case"project":u=b.join(process.cwd(),".blade","settings.json");break;case"user":u=b.join(n.homedir(),".blade","settings.json");break}await M.mkdir(b.dirname(u),{recursive:!0});let t={};try{let L0=await M.readFile(u,"utf-8");t=JSON.parse(L0)}catch{}let g=t.hooks||{},X0=g[I.event]||[],h={...g,enabled:!0,[I.event]:[...X0,y]};if(t.hooks=h,await M.writeFile(u,JSON.stringify(t,null,2),"utf-8"),await j.reloadConfig(),Z)Z({event:I.event,matcher:H.trim(),command:O.trim()});$()}catch(j){B(`Failed to save hook: ${j instanceof Error?j.message:"Unknown error"}`),w(!1)}};return p(j0,{flexDirection:"column",padding:1,children:[p(j0,{marginBottom:1,children:p(F0,{bold:!0,color:X.colors.success,children:"Hooks Manager"},void 0,!1,void 0,this)},void 0,!1,void 0,this),p(j0,{marginBottom:1,children:p(F0,{color:X.colors.warning,children:"⚠ Hooks execute shell commands with your full user permissions. Only use hooks from trusted sources."},void 0,!1,void 0,this)},void 0,!1,void 0,this),R&&p(j0,{flexDirection:"column",marginBottom:1,children:[p(F0,{children:R},void 0,!1,void 0,this),p(j0,{marginTop:1,children:p(F0,{color:X.colors.muted,children:"Esc to go back"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),Y==="action"&&!R&&p(j0,{flexDirection:"column",children:[p(j0,{flexDirection:"column",marginTop:1,children:w3.map((j,M)=>p(j0,{children:[p(F0,{color:M===J?X.colors.primary:void 0,bold:M===J,children:[M===J?"❯ ":" ",j.action]},void 0,!0,void 0,this),p(F0,{color:X.colors.muted,children:[" - ",j.description]},void 0,!0,void 0,this)]},j.action,!0,void 0,this))},void 0,!1,void 0,this),p(j0,{marginTop:1,children:p(F0,{color:X.colors.muted,children:"↑/↓ to select · Enter to continue · Esc to close"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),Y==="event"&&p(j0,{flexDirection:"column",children:[p(F0,{bold:!0,children:"Select Event:"},void 0,!1,void 0,this),p(j0,{flexDirection:"column",marginTop:1,children:$9.map((j,M)=>p(j0,{children:[p(F0,{color:M===q?X.colors.primary:void 0,bold:M===q,children:[M===q?"❯ ":" ",j.event]},void 0,!0,void 0,this),p(F0,{color:X.colors.muted,children:[" - ",j.description]},void 0,!0,void 0,this)]},j.event,!0,void 0,this))},void 0,!1,void 0,this),p(j0,{marginTop:1,children:p(F0,{color:X.colors.muted,children:"↑/↓ to select · Enter to continue · Esc to go back"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),Y!=="event"&&p(j0,{marginBottom:1,children:p(F0,{children:["Event:"," ",p(F0,{bold:!0,color:X.colors.primary,children:I.event},void 0,!1,void 0,this),p(F0,{color:X.colors.muted,children:[" - ",I.description]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this),(Y==="matcher"||Y==="command"||Y==="confirm")&&p(j0,{flexDirection:"column",marginBottom:1,children:[p(F0,{color:X.colors.muted,children:"Input to command is JSON of tool call arguments."},void 0,!1,void 0,this),p(F0,{color:X.colors.muted,children:"Exit code 0 - stdout/stderr not shown"},void 0,!1,void 0,this),p(F0,{color:X.colors.muted,children:"Exit code 2 - show stderr to model and block tool call"},void 0,!1,void 0,this),p(F0,{color:X.colors.muted,children:"Other exit codes - show stderr to user only but continue with tool call"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),Y==="matcher"&&p(j0,{flexDirection:"column",children:[p(j0,{children:[p(F0,{bold:!0,children:"Matcher: "},void 0,!1,void 0,this),p(yW,{value:H,onChange:F,onSubmit:S,placeholder:"e.g., Read, Bash, Edit|Write (empty = all tools)"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),p(j0,{marginTop:1,children:p(F0,{color:X.colors.muted,children:"Tool name pattern (supports | for multiple). Leave empty to match all."},void 0,!1,void 0,this)},void 0,!1,void 0,this),p(j0,{marginTop:1,children:p(F0,{color:X.colors.muted,children:"Enter to continue · Esc to go back"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),(Y==="command"||Y==="confirm")&&p(j0,{marginBottom:1,children:p(F0,{children:["Matcher: ",p(F0,{bold:!0,children:H||"(all tools)"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this),Y==="command"&&p(j0,{flexDirection:"column",children:[p(j0,{children:p(F0,{bold:!0,children:"Command: "},void 0,!1,void 0,this)},void 0,!1,void 0,this),p(j0,{borderStyle:"single",borderColor:X.colors.border.light,paddingX:1,marginTop:1,children:p(yW,{value:O,onChange:z,onSubmit:T,placeholder:"Enter shell command..."},void 0,!1,void 0,this)},void 0,!1,void 0,this),p(j0,{flexDirection:"column",marginTop:1,children:[p(F0,{bold:!0,children:"Examples:"},void 0,!1,void 0,this),Iw.map((j,M)=>p(F0,{color:X.colors.muted,children:["• ",j]},M,!0,void 0,this))]},void 0,!0,void 0,this),p(j0,{marginTop:1,children:p(F0,{color:X.colors.muted,children:"Enter to continue · Esc to go back"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),Y==="location"&&p(j0,{flexDirection:"column",children:[p(j0,{flexDirection:"column",borderStyle:"round",borderColor:X.colors.border.light,paddingX:2,paddingY:1,marginBottom:1,children:[p(F0,{bold:!0,color:X.colors.primary,children:"Save hook configuration"},void 0,!1,void 0,this),p(F0,{children:" "},void 0,!1,void 0,this),p(F0,{children:[" ","Event: ",I.event," - ",I.description]},void 0,!0,void 0,this),p(F0,{children:[" Matcher: ",H||"(all)"]},void 0,!0,void 0,this),p(F0,{children:[" Command: ",O]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),p(F0,{bold:!0,children:"Where should this hook be saved?"},void 0,!1,void 0,this),p(j0,{flexDirection:"column",marginTop:1,children:e6.map((j,M)=>p(j0,{children:[p(F0,{color:M===W?X.colors.primary:void 0,bold:M===W,children:[M===W?"❯ ":" ",M+1,". ",j.name]},void 0,!0,void 0,this),p(F0,{color:X.colors.muted,children:[" ",j.description]},void 0,!0,void 0,this)]},j.location,!0,void 0,this))},void 0,!1,void 0,this),p(j0,{marginTop:1,children:p(F0,{color:X.colors.muted,children:"Enter to confirm · Esc to go back"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),Y==="confirm"&&p(j0,{flexDirection:"column",children:[p(j0,{flexDirection:"column",borderStyle:"round",borderColor:X.colors.success,paddingX:2,paddingY:1,children:[p(F0,{bold:!0,children:["Saving hook to ",v.description,"..."]},void 0,!0,void 0,this),p(F0,{children:" "},void 0,!1,void 0,this),p(F0,{children:["Event: ",I.event]},void 0,!0,void 0,this),p(F0,{children:["Matcher: ",H||"(all tools)"]},void 0,!0,void 0,this),p(F0,{children:["Command: ",O]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),p(j0,{marginTop:1,children:p(F0,{color:X.colors.muted,children:L?"Saving...":"Enter to confirm · Esc to go back"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),_&&p(j0,{marginTop:1,children:p(F0,{color:X.colors.error,children:["❌ ",_]},void 0,!0,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)};import{useMemoizedFn as pW}from"ahooks";import{Box as xw,Text as pw}from"ink";import dw from"react";import{useMemoizedFn as Tw}from"ahooks";import N2 from"chalk";import{Text as Sw,useInput as Cw}from"ink";import{useEffect as CZ,useRef as kZ}from"react";var H4={TIMEOUT_MS:100,RAPID_INPUT_THRESHOLD_MS:150,LARGE_INPUT_THRESHOLD:300,MEDIUM_SIZE_MULTI_CHUNK_THRESHOLD:200};import{execSync as N8}from"node:child_process";import{existsSync as yw,readFileSync as TZ}from"node:fs";import{basename as EW,isAbsolute as vw}from"node:path";function PW($){try{let Z=Buffer.from($,"base64");if(Z.length<4)return"image/png";if(Z[0]===137&&Z[1]===80&&Z[2]===78&&Z[3]===71)return"image/png";if(Z[0]===255&&Z[1]===216&&Z[2]===255)return"image/jpeg";if(Z[0]===71&&Z[1]===73&&Z[2]===70)return"image/gif";if(Z[0]===82&&Z[1]===73&&Z[2]===70&&Z[3]===70){if(Z.length>=12&&Z[8]===87&&Z[9]===69&&Z[10]===66&&Z[11]===80)return"image/webp"}return"image/png"}catch{return"image/png"}}function TW(){let $=process.platform,Z={darwin:"/tmp/blade_cli_latest_screenshot.png",linux:"/tmp/blade_cli_latest_screenshot.png",win32:process.env.TEMP?`${process.env.TEMP}\\blade_cli_latest_screenshot.png`:"C:\\Temp\\blade_cli_latest_screenshot.png"},X={darwin:{checkImage:"osascript -e 'the clipboard as «class PNGf»'",saveImage:(Y)=>`osascript -e 'set png_data to (the clipboard as «class PNGf»)' -e 'set fp to open for access POSIX file "${Y}" with write permission' -e 'write png_data to fp' -e 'close access fp'`,getPath:"osascript -e 'get POSIX path of (the clipboard as «class furl»)'",deleteFile:(Y)=>`rm -f "${Y}"`},linux:{checkImage:'xclip -selection clipboard -t TARGETS -o | grep -E "image/(png|jpeg|jpg|gif|webp)"',saveImage:(Y)=>`xclip -selection clipboard -t image/png -o > "${Y}" || wl-paste --type image/png > "${Y}"`,getPath:"xclip -selection clipboard -t text/plain -o",deleteFile:(Y)=>`rm -f "${Y}"`},win32:{checkImage:'powershell -Command "(Get-Clipboard -Format Image) -ne $null"',saveImage:(Y)=>`powershell -Command "$img = Get-Clipboard -Format Image; if ($img) { $img.Save('${Y.replace(/\\/g,"\\\\")}', [System.Drawing.Imaging.ImageFormat]::Png) }"`,getPath:'powershell -Command "Get-Clipboard"',deleteFile:(Y)=>`del /f "${Y}"`}};return{commands:X[$]||X.linux,screenshotPath:Z[$]||Z.linux}}function Ew(){let{commands:$}=TW();try{return N8($.getPath,{encoding:"utf-8"}).trim()}catch(Z){return console.error("Failed to get clipboard path:",Z),null}}function SW($){if($.startsWith('"')&&$.endsWith('"')||$.startsWith("'")&&$.endsWith("'"))return $.slice(1,-1);return $}function CW($){if(process.platform==="win32")return $;let Z="__DOUBLE_BACKSLASH__";return $.replace(/\\\\/g,Z).replace(/\\(.)/g,"$1").replace(new RegExp(Z,"g"),"\\")}function SZ($){let Z=SW($.trim()),X=CW(Z);return/\.(png|jpe?g|gif|webp)$/i.test(X)}function Pw($){let Z=SW($.trim()),X=CW(Z);if(SZ(X))return X;return null}async function kW($){let Z=Pw($);if(!Z)return null;let X;try{if(vw(Z))X=TZ(Z);else{let G=Ew();if(G&&Z===EW(G))X=TZ(G);else return null}}catch(G){return console.error("Failed to read image file:",G),null}let Y=X.toString("base64"),Q=PW(Y),J=EW(Z);return{path:Z,base64:Y,mediaType:Q,filename:J}}async function fW(){let $=process.platform,Z={darwin:"pbpaste",linux:"xclip -selection clipboard -o || wl-paste",win32:'powershell -Command "Get-Clipboard"'},X=Z[$]||Z.linux;try{return N8(X,{encoding:"utf-8"})||null}catch{return null}}async function hW(){let{commands:$,screenshotPath:Z}=TW();try{if(N8($.checkImage,{stdio:"ignore"}),N8($.saveImage(Z),{stdio:"ignore"}),!yw(Z))return null;let Y=TZ(Z).toString("base64"),Q=PW(Y);return N8($.deleteFile(Z),{stdio:"ignore"}),{base64:Y,mediaType:Q}}catch(X){try{N8($.deleteFile(Z),{stdio:"ignore"})}catch{}return null}}import{jsxDEV as hw}from"react/jsx-dev-runtime";var kw=/\r\n/g,fw=/\r/g;function b2($){if(!$.includes("\r"))return $;return $.replace(kw,`
|
|
2812
|
+
`))},S=()=>{Q("command")},T=()=>{if(!O.trim()){B("Command cannot be empty");return}B(null),Q("location")},c=async()=>{w(!0),B(null);try{let j=M0.getInstance(),M=await import("node:fs/promises"),b=await import("node:path"),n=await import("node:os"),y={matcher:H.trim()?{tools:H.trim()}:{},hooks:[{type:"command",command:O.trim()}]},u;switch(v.location){case"local":u=b.join(process.cwd(),".blade","settings.local.json");break;case"project":u=b.join(process.cwd(),".blade","settings.json");break;case"user":u=b.join(n.homedir(),".blade","settings.json");break}await M.mkdir(b.dirname(u),{recursive:!0});let t={};try{let L0=await M.readFile(u,"utf-8");t=JSON.parse(L0)}catch{}let g=t.hooks||{},X0=g[I.event]||[],h={...g,enabled:!0,[I.event]:[...X0,y]};if(t.hooks=h,await M.writeFile(u,JSON.stringify(t,null,2),"utf-8"),await j.reloadConfig(),Z)Z({event:I.event,matcher:H.trim(),command:O.trim()});$()}catch(j){B(`Failed to save hook: ${j instanceof Error?j.message:"Unknown error"}`),w(!1)}};return p(j0,{flexDirection:"column",padding:1,children:[p(j0,{marginBottom:1,children:p(F0,{bold:!0,color:X.colors.success,children:"Hooks Manager"},void 0,!1,void 0,this)},void 0,!1,void 0,this),p(j0,{marginBottom:1,children:p(F0,{color:X.colors.warning,children:"⚠ Hooks execute shell commands with your full user permissions. Only use hooks from trusted sources."},void 0,!1,void 0,this)},void 0,!1,void 0,this),R&&p(j0,{flexDirection:"column",marginBottom:1,children:[p(F0,{children:R},void 0,!1,void 0,this),p(j0,{marginTop:1,children:p(F0,{color:X.colors.muted,children:"Esc to go back"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),Y==="action"&&!R&&p(j0,{flexDirection:"column",children:[p(j0,{flexDirection:"column",marginTop:1,children:w3.map((j,M)=>p(j0,{children:[p(F0,{color:M===J?X.colors.primary:void 0,bold:M===J,children:[M===J?"❯ ":" ",j.action]},void 0,!0,void 0,this),p(F0,{color:X.colors.muted,children:[" - ",j.description]},void 0,!0,void 0,this)]},j.action,!0,void 0,this))},void 0,!1,void 0,this),p(j0,{marginTop:1,children:p(F0,{color:X.colors.muted,children:"↑/↓ to select · Enter to continue · Esc to close"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),Y==="event"&&p(j0,{flexDirection:"column",children:[p(F0,{bold:!0,children:"Select Event:"},void 0,!1,void 0,this),p(j0,{flexDirection:"column",marginTop:1,children:$9.map((j,M)=>p(j0,{children:[p(F0,{color:M===q?X.colors.primary:void 0,bold:M===q,children:[M===q?"❯ ":" ",j.event]},void 0,!0,void 0,this),p(F0,{color:X.colors.muted,children:[" - ",j.description]},void 0,!0,void 0,this)]},j.event,!0,void 0,this))},void 0,!1,void 0,this),p(j0,{marginTop:1,children:p(F0,{color:X.colors.muted,children:"↑/↓ to select · Enter to continue · Esc to go back"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),Y!=="event"&&p(j0,{marginBottom:1,children:p(F0,{children:["Event:"," ",p(F0,{bold:!0,color:X.colors.primary,children:I.event},void 0,!1,void 0,this),p(F0,{color:X.colors.muted,children:[" - ",I.description]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this),(Y==="matcher"||Y==="command"||Y==="confirm")&&p(j0,{flexDirection:"column",marginBottom:1,children:[p(F0,{color:X.colors.muted,children:"Input to command is JSON of tool call arguments."},void 0,!1,void 0,this),p(F0,{color:X.colors.muted,children:"Exit code 0 - stdout/stderr not shown"},void 0,!1,void 0,this),p(F0,{color:X.colors.muted,children:"Exit code 2 - show stderr to model and block tool call"},void 0,!1,void 0,this),p(F0,{color:X.colors.muted,children:"Other exit codes - show stderr to user only but continue with tool call"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),Y==="matcher"&&p(j0,{flexDirection:"column",children:[p(j0,{children:[p(F0,{bold:!0,children:"Matcher: "},void 0,!1,void 0,this),p(yW,{value:H,onChange:F,onSubmit:S,placeholder:"e.g., Read, Bash, Edit|Write (empty = all tools)"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),p(j0,{marginTop:1,children:p(F0,{color:X.colors.muted,children:"Tool name pattern (supports | for multiple). Leave empty to match all."},void 0,!1,void 0,this)},void 0,!1,void 0,this),p(j0,{marginTop:1,children:p(F0,{color:X.colors.muted,children:"Enter to continue · Esc to go back"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),(Y==="command"||Y==="confirm")&&p(j0,{marginBottom:1,children:p(F0,{children:["Matcher: ",p(F0,{bold:!0,children:H||"(all tools)"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this),Y==="command"&&p(j0,{flexDirection:"column",children:[p(j0,{children:p(F0,{bold:!0,children:"Command: "},void 0,!1,void 0,this)},void 0,!1,void 0,this),p(j0,{borderStyle:"single",borderColor:X.colors.border.light,paddingX:1,marginTop:1,children:p(yW,{value:O,onChange:z,onSubmit:T,placeholder:"Enter shell command..."},void 0,!1,void 0,this)},void 0,!1,void 0,this),p(j0,{flexDirection:"column",marginTop:1,children:[p(F0,{bold:!0,children:"Examples:"},void 0,!1,void 0,this),Iw.map((j,M)=>p(F0,{color:X.colors.muted,children:["• ",j]},M,!0,void 0,this))]},void 0,!0,void 0,this),p(j0,{marginTop:1,children:p(F0,{color:X.colors.muted,children:"Enter to continue · Esc to go back"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),Y==="location"&&p(j0,{flexDirection:"column",children:[p(j0,{flexDirection:"column",borderStyle:"round",borderColor:X.colors.border.light,paddingX:2,paddingY:1,marginBottom:1,children:[p(F0,{bold:!0,color:X.colors.primary,children:"Save hook configuration"},void 0,!1,void 0,this),p(F0,{children:" "},void 0,!1,void 0,this),p(F0,{children:[" ","Event: ",I.event," - ",I.description]},void 0,!0,void 0,this),p(F0,{children:[" Matcher: ",H||"(all)"]},void 0,!0,void 0,this),p(F0,{children:[" Command: ",O]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),p(F0,{bold:!0,children:"Where should this hook be saved?"},void 0,!1,void 0,this),p(j0,{flexDirection:"column",marginTop:1,children:e6.map((j,M)=>p(j0,{children:[p(F0,{color:M===W?X.colors.primary:void 0,bold:M===W,children:[M===W?"❯ ":" ",M+1,". ",j.name]},void 0,!0,void 0,this),p(F0,{color:X.colors.muted,children:[" ",j.description]},void 0,!0,void 0,this)]},j.location,!0,void 0,this))},void 0,!1,void 0,this),p(j0,{marginTop:1,children:p(F0,{color:X.colors.muted,children:"Enter to confirm · Esc to go back"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),Y==="confirm"&&p(j0,{flexDirection:"column",children:[p(j0,{flexDirection:"column",borderStyle:"round",borderColor:X.colors.success,paddingX:2,paddingY:1,children:[p(F0,{bold:!0,children:["Saving hook to ",v.description,"..."]},void 0,!0,void 0,this),p(F0,{children:" "},void 0,!1,void 0,this),p(F0,{children:["Event: ",I.event]},void 0,!0,void 0,this),p(F0,{children:["Matcher: ",H||"(all tools)"]},void 0,!0,void 0,this),p(F0,{children:["Command: ",O]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),p(j0,{marginTop:1,children:p(F0,{color:X.colors.muted,children:L?"Saving...":"Enter to confirm · Esc to go back"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),_&&p(j0,{marginTop:1,children:p(F0,{color:X.colors.error,children:["❌ ",_]},void 0,!0,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)};import{useMemoizedFn as pW}from"ahooks";import{Box as xw,Text as pw}from"ink";import dw from"react";import{useMemoizedFn as Tw}from"ahooks";import N4 from"chalk";import{Text as Sw,useInput as Cw}from"ink";import{useEffect as CZ,useRef as kZ}from"react";var H2={TIMEOUT_MS:100,RAPID_INPUT_THRESHOLD_MS:150,LARGE_INPUT_THRESHOLD:300,MEDIUM_SIZE_MULTI_CHUNK_THRESHOLD:200};import{execSync as N8}from"node:child_process";import{existsSync as yw,readFileSync as TZ}from"node:fs";import{basename as EW,isAbsolute as vw}from"node:path";function PW($){try{let Z=Buffer.from($,"base64");if(Z.length<4)return"image/png";if(Z[0]===137&&Z[1]===80&&Z[2]===78&&Z[3]===71)return"image/png";if(Z[0]===255&&Z[1]===216&&Z[2]===255)return"image/jpeg";if(Z[0]===71&&Z[1]===73&&Z[2]===70)return"image/gif";if(Z[0]===82&&Z[1]===73&&Z[2]===70&&Z[3]===70){if(Z.length>=12&&Z[8]===87&&Z[9]===69&&Z[10]===66&&Z[11]===80)return"image/webp"}return"image/png"}catch{return"image/png"}}function TW(){let $=process.platform,Z={darwin:"/tmp/blade_cli_latest_screenshot.png",linux:"/tmp/blade_cli_latest_screenshot.png",win32:process.env.TEMP?`${process.env.TEMP}\\blade_cli_latest_screenshot.png`:"C:\\Temp\\blade_cli_latest_screenshot.png"},X={darwin:{checkImage:"osascript -e 'the clipboard as «class PNGf»'",saveImage:(Y)=>`osascript -e 'set png_data to (the clipboard as «class PNGf»)' -e 'set fp to open for access POSIX file "${Y}" with write permission' -e 'write png_data to fp' -e 'close access fp'`,getPath:"osascript -e 'get POSIX path of (the clipboard as «class furl»)'",deleteFile:(Y)=>`rm -f "${Y}"`},linux:{checkImage:'xclip -selection clipboard -t TARGETS -o | grep -E "image/(png|jpeg|jpg|gif|webp)"',saveImage:(Y)=>`xclip -selection clipboard -t image/png -o > "${Y}" || wl-paste --type image/png > "${Y}"`,getPath:"xclip -selection clipboard -t text/plain -o",deleteFile:(Y)=>`rm -f "${Y}"`},win32:{checkImage:'powershell -Command "(Get-Clipboard -Format Image) -ne $null"',saveImage:(Y)=>`powershell -Command "$img = Get-Clipboard -Format Image; if ($img) { $img.Save('${Y.replace(/\\/g,"\\\\")}', [System.Drawing.Imaging.ImageFormat]::Png) }"`,getPath:'powershell -Command "Get-Clipboard"',deleteFile:(Y)=>`del /f "${Y}"`}};return{commands:X[$]||X.linux,screenshotPath:Z[$]||Z.linux}}function Ew(){let{commands:$}=TW();try{return N8($.getPath,{encoding:"utf-8"}).trim()}catch(Z){return console.error("Failed to get clipboard path:",Z),null}}function SW($){if($.startsWith('"')&&$.endsWith('"')||$.startsWith("'")&&$.endsWith("'"))return $.slice(1,-1);return $}function CW($){if(process.platform==="win32")return $;let Z="__DOUBLE_BACKSLASH__";return $.replace(/\\\\/g,Z).replace(/\\(.)/g,"$1").replace(new RegExp(Z,"g"),"\\")}function SZ($){let Z=SW($.trim()),X=CW(Z);return/\.(png|jpe?g|gif|webp)$/i.test(X)}function Pw($){let Z=SW($.trim()),X=CW(Z);if(SZ(X))return X;return null}async function kW($){let Z=Pw($);if(!Z)return null;let X;try{if(vw(Z))X=TZ(Z);else{let G=Ew();if(G&&Z===EW(G))X=TZ(G);else return null}}catch(G){return console.error("Failed to read image file:",G),null}let Y=X.toString("base64"),Q=PW(Y),J=EW(Z);return{path:Z,base64:Y,mediaType:Q,filename:J}}async function fW(){let $=process.platform,Z={darwin:"pbpaste",linux:"xclip -selection clipboard -o || wl-paste",win32:'powershell -Command "Get-Clipboard"'},X=Z[$]||Z.linux;try{return N8(X,{encoding:"utf-8"})||null}catch{return null}}async function hW(){let{commands:$,screenshotPath:Z}=TW();try{if(N8($.checkImage,{stdio:"ignore"}),N8($.saveImage(Z),{stdio:"ignore"}),!yw(Z))return null;let Y=TZ(Z).toString("base64"),Q=PW(Y);return N8($.deleteFile(Z),{stdio:"ignore"}),{base64:Y,mediaType:Q}}catch(X){try{N8($.deleteFile(Z),{stdio:"ignore"})}catch{}return null}}import{jsxDEV as hw}from"react/jsx-dev-runtime";var kw=/\r\n/g,fw=/\r/g;function b4($){if(!$.includes("\r"))return $;return $.replace(kw,`
|
|
2813
2813
|
`).replace(fw,`
|
|
2814
|
-
`)}function
|
|
2815
|
-
`),N=R>
|
|
2816
|
-
`),S=m.length>
|
|
2817
|
-
`&&(L.shift||L.meta)){let{newValue:N,newCursorPosition:k}=
|
|
2818
|
-
`)&&w.length>1,s=N<
|
|
2819
|
-
`).length,F=U.length,O=500,z=10;if(F>500||H>10){let _=Q(U),B=U.slice(0,30).replace(/\n/g," "),L=`${F} chars, ${H} lines: ${B}...`;return{prompt:`${g6(_)}${L}${qZ()}`}}return{}}),W=pW(async(U,H,F)=>{try{let O=J(U,H);return{prompt:`${g6(O)}[Image #${O}]${qZ()}`}}catch(O){return console.error("[Image Paste] Failed to process image:",O),{prompt:`[Image paste failed: ${O instanceof Error?O.message:"Unknown error"}] `}}});return fZ(xw,{flexDirection:"row",width:"100%",paddingX:2,paddingY:0,flexShrink:0,flexGrow:0,overflow:"hidden",borderStyle:"round",borderColor:"gray",children:[fZ(pw,{color:"blue",bold:!0,children:"> "},void 0,!1,void 0,this),fZ(xW,{value:$,cursorPosition:Z,onChange:X,onChangeCursorPosition:Y,onPaste:K,onImagePaste:W,placeholder:" 输入命令...",focus:q,disabledKeys:["upArrow","downArrow","tab","return","escape"]},void 0,!1,void 0,this)]},void 0,!0,void 0,this)});import{Box as Z9,Text as P1}from"ink";import lw,{useEffect as iw,useState as aw}from"react";import{useEffect as cw,useState as cW}from"react";import{useEffect as mw,useState as uw}from"react";var gw=15000,mW=["炼化代码灵气...","参悟 AST 道法...","推演算法天机...","重铸代码根基...","破解逻辑封印...","凝练类型真元...","铸就函数金丹...","渡劫编译雷劫...","打通模块任督二脉...","修炼 Tree-shaking 神功...","压缩代码乾坤...","布下 Source Map 阵法...","推演 Token 灵数...","炼制 Prompt 仙丹...","调息温度参数...","参透困惑度玄机...","驱动 LLM 灵力...","施展向量搜索术...","构筑 RAG 法阵...","凝聚 Embedding 道果...","勾连向量宝库...","破译函数咒语...","验证 Schema 真意...","封印工具参数...","注入系统道韵...","串联历史因果...","炼化抽象语法树...","破境重构神功...","感悟类型天道...","筑基模块根基...","施展词法轻功...","破解语法阵法...","参悟语义心法...","凝练中间内力...","修炼优化神功...","调息寄存器真气...","运转指令招式...","消除死码杂念...","折叠常量真元...","内联函数身法...","逃逸分析密探...","垃圾回收扫地僧...","标记清除掌法...","分代回收心诀...","增量收功法门...","JIT 即时顿悟...","解读字节码暗器...","V8 引擎神功...","召唤 WASM 傀儡...","开辟虚拟洞府...","丹田分配内存...","掌控栈帧乾坤...","捕获异常剑气...","尾调优化身法...","动态链接飞剑...","建立 TCP 金桥...","三次握手结契...","传送 HTTP 信使...","破译响应符文...","TLS 秘境握手...","验证 SSL 信物...","WebSocket 通灵...","流式传功大法...","gRPC 御剑飞行...","Protobuf 封印术...","GraphQL 问道...","DNS 测算域名...","负载均衡五行阵...","CDN 边缘瞬移...","HTTP/2 分身术...","QUIC 闪现神通...","gzip 缩地成寸...","Brotli 玄冰压缩...","断点续传接续术...","分片上传合璧功...","参研 SQL 真经...","推演查询路径...","索引扫描神识...","全表扫描暴力突破...","执行 JOIN 双修大法...","聚合数据炼丹...","事务提交天地誓...","ACID 四象护法...","乐观锁道心无畏...","悲观锁剑阵守护...","分布式锁万里封禁...","Redis 炼药鼎缓存...","LRU 新陈代谢...","WAL 预写因果簿...","B+ 树平衡阴阳...","LSM 树合璧压缩...","向量宝库搜寻...","余弦相似度测算...","KNN 近邻追踪...","倒排索引翻阅秘籍...","快速排序剑法...","归并排序双刀...","堆排优化内功...","二分查找闪现...","深度优先潜行...","广度优先横扫...","Dijkstra 寻路神算...","A* 天机推演...","动态规划填棋盘...","回溯剑法剪枝...","贪心策略奇谋...","分治递归化身术...","哈希表扩容开天...","红黑树旋转太极...","AVL 树平衡阴阳...","跳表纵身轻功...","Trie 树千头万绪...","布隆过滤天罗地网...","一致性哈希环定乾坤...","最小生成树扎根...","Docker 镜像炼制...","Kubernetes 调兵遣将...","容器结界布阵...","卷挂载空间挪移...","Helm 符箓展开...","CI/CD 流水线作业...","GitHub 门派行动...","代码品鉴术...","漏洞探查密探...","依赖追溯寻根...","蓝绿部署换防...","金丝雀试探...","回滚时光倒流...","健康探查望闻问切...","日志归档藏经阁...","监控预警千里眼...","告警通知飞鸽传书...","性能调优筋骨重塑...","扩容缩容易筋经...","灰度发布声东击西...","React 虚影对决...","组件树调和大法...","Hooks 勾魂术...","useEffect 副作用因果...","Redux 中枢天宫...","Zustand 灵台藏识...","CSS-in-JS 画地为牢...","Tailwind 疾风步...","Webpack 热更换血重生...","Vite 按需凝形...","ESBuild 极速神行...","SWC 闪电炼形...","SSR 天地初开...","Hydration 魂归肉身...","Ink 终端墨宝...","虚拟 DOM 镜花水月...","事件冒泡顺流而上...","状态提升登峰造极...","懒加载厚积薄发...","代码分割庖丁解牛...","SHA-256 炼心咒...","AES-256 玄冰封印...","RSA 阴阳双钥...","JWT 信物令牌...","OAuth 门派授权...","CSRF 防御结界...","XSS 祛邪过滤...","SQL 注入克星...","PBKDF2 淬炼秘钥...","零知识誓言验证...","HTTPS 金钟罩...","签名验证印玺鉴定...","盐值加密炼丹配方...","双因素认证双重认证...","权限控制天条律令...","拜见图灵祖师爷...","冯·诺依曼传道...","Linus 大侠坐镇...","参悟 Rust 生命轮回...","逃离回调地狱轮回...","await 静待天时...","捕获野生 Bug 妖兽...","喂养橡皮鸭灵兽 \uD83E\uDD86...","炼丹调参秘术...","0xDEADBEEF 死亡凝视...","递归无限轮回...","闭包封印记忆...","Promise 未来契约...","async 异步神功...","Generator 分身术...","Proxy 替身傀儡...","Reflect 返照镜...","Symbol 独一无二印记...","WeakMap 过眼云烟...","Iterator 周而复始...","GitHub 武林大会...","Star 点赞声望...","Fork 拜师学艺...","Pull Request 挑战切磋...","Code Review 武功点评...","Issue 悬赏令...","Merge 收徒入门...","Commit 闭关修炼记录...","Branch 分支独辟蹊径...","Tag 里程碑界碑...","Release 出关发布...","License 门规戒律...","README 入门心法...","Documentation 武学秘籍...","Open Source 广纳贤才..."],uW=["Esc - 停止任务 / 隐藏建议 / 双击清空输入","Shift+Tab - 切换模式 (DEFAULT → AUTO_EDIT → PLAN → SPEC)","Tab - 选中建议 / 切换 thinking 模式","↑↓ - 浏览建议或输入历史记录","? - 显示快捷键帮助面板(输入框为空时)","Ctrl+C - 停止任务(双击退出应用)","Ctrl+L - 清屏(清除所有消息)","Ctrl+T - 切换 thinking 内容展开/折叠","Ctrl+O - 切换历史消息展开/折叠","Ctrl+U - 删除从行首到光标的内容","Ctrl+K - 删除从光标到行尾的内容","Shift+Enter - 插入换行(多行输入)","/help - 显示所有可用的 slash commands","/init - 分析项目并生成 BLADE.md 配置","/resume - 恢复历史会话","/compact - 手动压缩当前会话上下文","/theme - 打开交互式主题选择器","/model - 管理和切换模型配置","/model add - 添加新模型配置","/permissions - 管理项目的本地权限规则","/mcp - 显示 MCP 服务器状态和可用工具","/agents - 管理 subagent 配置","/version - 显示版本信息和构建详情","/clear - 清除屏幕内容和对话历史","/status - 显示当前项目配置状态","/context - 可视化当前上下文 Token 使用情况","/git - Git 仓库查询和 AI 辅助","/git review - AI Code Review","/hooks - 管理 Hook 配置","/tasks - 列出所有后台任务","@ 文件路径 - 附加文件到上下文","@dir/ - 附加整个目录","@file.ts:10-20 - 附加指定行范围","Plan 模式 - 先规划后编码(Shift+Tab 切换)","Auto Edit 模式 - 自动批准工具调用","MCP 协议 - 扩展外部工具集成","Subagents - 并行执行子任务","Hooks 系统 - 自定义工具执行流程","Context 压缩 - 自动总结历史对话","Loop 检测 - 防止无限循环","提示:使用 /init 让 AI 理解你的项目结构","提示:Plan 模式适合复杂多步骤任务","提示:Auto Edit 可加速重复性操作","提示:@ 引用可提供更精准的上下文","提示:定期 /compact 节省 token 成本","提示:使用 /permissions 控制工具权限","提示:Shift+Tab 快速切换模式","提示:Esc 可随时中断长时间任务","提示:/resume 继续未完成的对话","提示:/git commit 让 AI 生成 commit message"];function gW($,Z,X=!1){let[Y,Q]=uw("");return mw(()=>{if(Z){Q("等待用户确认...");return}if(!$){Q("");return}if(X)return;let J=()=>{if(Math.random()<0.16666666666666666){let W=Math.floor(Math.random()*uW.length);return uW[W]}let K=Math.floor(Math.random()*mW.length);return mW[K]};Q(J());let G=setInterval(()=>{Q(J())},gw);return()=>{clearInterval(G)}},[$,Z,X]),Y}function lW($,Z=!1,X=!1){let[Y,Q]=cW(0),[J,G]=cW(null),q=gW($,Z,X);return cw(()=>{if(!$){Q(0),G(null);return}if(X)return;if(J===null)G(Date.now());let K=setInterval(()=>{if(J!==null){let W=Math.floor((Date.now()-J)/1000);Q(W)}},1000);return()=>{clearInterval(K)}},[$,J,X]),{currentPhrase:q,elapsedTime:Y}}import{jsxDEV as f$,Fragment as nw}from"react/jsx-dev-runtime";var hZ=["⠋","⠙","⠹","⠸","⠼","⠴","⠦","⠧","⠇","⠏"],rw=80;function iW($){if($<60)return`${$}s`;let Z=Math.floor($/60),X=$%60;return`${Z}m ${X}s`}var aW=lw.memo(({message:$,paused:Z=!1})=>{let X=
|
|
2814
|
+
`)}function A4($,Z,X){let Y=Math.max(0,Math.min(X,Z.length)),Q=Z.slice(0,Y),J=Z.slice(Y);return{newValue:Q+$+J,newCursorPosition:Y+$.length}}function xW({value:$,placeholder:Z="",focus:X=!0,onChange:Y,cursorPosition:Q,onChangeCursorPosition:J,onPaste:G,onImagePaste:q,disabledKeys:K=[]}){let W=kZ({chunks:[],timeoutId:null,firstInputTime:null,lastInputTime:null,totalLength:0}),U=kZ($),H=kZ(Q);CZ(()=>{U.current=$,H.current=Q},[$,Q]),CZ(()=>{return()=>{if(W.current.timeoutId)clearTimeout(W.current.timeoutId)}},[]),CZ(()=>{if(Q>$.length)J($.length)},[$,Q,J]);let F=Tw(()=>{let B=W.current;if(B.timeoutId)clearTimeout(B.timeoutId);let L=setTimeout(async()=>{let w=W.current.chunks,R=W.current.totalLength;if(w.length===0)return;let D=b4(w.join(""));W.current={chunks:[],timeoutId:null,firstInputTime:null,lastInputTime:null,totalLength:0};let V=U.current,I=H.current;if(q&&SZ(D))try{let S=await kW(D);if(S){let T=await q(S.base64,S.mediaType,S.filename);if(T?.prompt){let c=b4(T.prompt),{newValue:j,newCursorPosition:M}=A4(c,V,I);Y(j),J(M)}return}}catch(S){console.error("Failed to process image path:",S)}let v=D.includes(`
|
|
2815
|
+
`),N=R>H2.MEDIUM_SIZE_MULTI_CHUNK_THRESHOLD&&w.length>3;if((R>H2.LARGE_INPUT_THRESHOLD||v||N)&&G){let S=await G(D);if(S?.prompt){let T=b4(S.prompt),{newValue:c,newCursorPosition:j}=A4(T,V,I);Y(c),J(j);return}}let{newValue:m,newCursorPosition:s}=A4(D,V,I);Y(m),J(s)},H2.TIMEOUT_MS);W.current.timeoutId=L});Cw((B,L)=>{let w=b4(B);if(K.some((N)=>L[N])||L.ctrl&&B==="c"||L.ctrl&&B==="l"||L.ctrl&&B==="t"||L.ctrl&&B==="o"||L.meta&&B==="l"||L.meta&&B==="t"||L.meta&&B==="o"||L.shift&&L.tab||w==="?"&&$==="")return;let D=Date.now(),V=W.current,I=Q,v=$;if(L.leftArrow)I--;else if(L.rightArrow)I++;else if(L.backspace||L.delete){if(B===""){if(Q>0)v=$.slice(0,Q-1)+$.slice(Q,$.length),I--}else if(Q<$.length)v=$.slice(0,Q)+$.slice(Q+1,$.length)}else if(L.ctrl&&w==="a")I=0;else if(L.ctrl&&w==="e")I=$.length;else if(L.ctrl&&w==="k")v=$.slice(0,Q);else if(L.ctrl&&w==="u")v=$.slice(Q),I=0;else if(L.ctrl&&w==="w"){let k=$.slice(0,Q).match(/\s*\S+\s*$/);if(k){let m=k[0].length;v=$.slice(0,Q-m)+$.slice(Q),I-=m}}else if(L.ctrl&&w==="v"){let N=process.platform==="darwin";(async()=>{if(q){let m=await hW();if(m){let s=await q(m.base64,m.mediaType,"clipboard.png");if(s?.prompt){let S=b4(s.prompt),{newValue:T,newCursorPosition:c}=A4(S,U.current,H.current);Y(T),J(c)}return}}if(N)return;let k=await fW();if(k){let m=b4(k),s=m.includes(`
|
|
2816
|
+
`),S=m.length>H2.LARGE_INPUT_THRESHOLD;if((s||S)&&G){let j=await G(m);if(j?.prompt){let M=b4(j.prompt),{newValue:b,newCursorPosition:n}=A4(M,U.current,H.current);Y(b),J(n);return}}let{newValue:T,newCursorPosition:c}=A4(m,U.current,H.current);Y(T),J(c)}})().catch(()=>{});return}else if(L.pageUp)I=0;else if(L.pageDown)I=$.length;else if(w===`
|
|
2817
|
+
`&&(L.shift||L.meta)){let{newValue:N,newCursorPosition:k}=A4(w,$,Q);Y(N),J(k);return}else if(!L.ctrl&&!L.meta){if(!V.firstInputTime)V.firstInputTime=D;V.lastInputTime=D;let N=D-(V.firstInputTime||D),k=w.length>H2.LARGE_INPUT_THRESHOLD,m=w.includes(`
|
|
2818
|
+
`)&&w.length>1,s=N<H2.RAPID_INPUT_THRESHOLD_MS&&V.chunks.length>0,S=N<H2.RAPID_INPUT_THRESHOLD_MS&&w.length>10,T=V.timeoutId!==null;if(G&&(k||m||s||S||T)){V.chunks.push(w),V.totalLength+=w.length,F();return}if(w.length===1&&!V.timeoutId)V.chunks=[],V.firstInputTime=null,V.lastInputTime=null,V.totalLength=0;v=$.slice(0,Q)+w+$.slice(Q,$.length),I+=w.length}if(I<0)I=0;if(I>v.length)I=v.length;if(v!==$)Y(v);if(I!==Q)J(I)},{isActive:X});let O=X,z=$,_=Z?N4.grey(Z):void 0;if(O)if(_=Z.length>0?N4.inverse(Z[0])+N4.grey(Z.slice(1)):N4.inverse(" "),$.length===0)z=N4.inverse(" ");else{z="";for(let B=0;B<$.length;B++)if(B===Q&&Q<$.length)z+=N4.inverse($[B]);else z+=$[B];if(Q>=$.length)z+=N4.inverse(" ")}return hw(Sw,{children:Z?$.length>0?z:_:z},void 0,!1,void 0,this)}import{jsxDEV as fZ}from"react/jsx-dev-runtime";var dW=dw.memo(({input:$,cursorPosition:Z,onChange:X,onChangeCursorPosition:Y,onAddPasteMapping:Q,onAddImagePasteMapping:J})=>{let q=o$()==="main-input",K=pW((U)=>{let H=U.split(`
|
|
2819
|
+
`).length,F=U.length,O=500,z=10;if(F>500||H>10){let _=Q(U),B=U.slice(0,30).replace(/\n/g," "),L=`${F} chars, ${H} lines: ${B}...`;return{prompt:`${g6(_)}${L}${qZ()}`}}return{}}),W=pW(async(U,H,F)=>{try{let O=J(U,H);return{prompt:`${g6(O)}[Image #${O}]${qZ()}`}}catch(O){return console.error("[Image Paste] Failed to process image:",O),{prompt:`[Image paste failed: ${O instanceof Error?O.message:"Unknown error"}] `}}});return fZ(xw,{flexDirection:"row",width:"100%",paddingX:2,paddingY:0,flexShrink:0,flexGrow:0,overflow:"hidden",borderStyle:"round",borderColor:"gray",children:[fZ(pw,{color:"blue",bold:!0,children:"> "},void 0,!1,void 0,this),fZ(xW,{value:$,cursorPosition:Z,onChange:X,onChangeCursorPosition:Y,onPaste:K,onImagePaste:W,placeholder:" 输入命令...",focus:q,disabledKeys:["upArrow","downArrow","tab","return","escape"]},void 0,!1,void 0,this)]},void 0,!0,void 0,this)});import{Box as Z9,Text as P1}from"ink";import lw,{useEffect as iw,useState as aw}from"react";import{useEffect as cw,useState as cW}from"react";import{useEffect as mw,useState as uw}from"react";var gw=15000,mW=["炼化代码灵气...","参悟 AST 道法...","推演算法天机...","重铸代码根基...","破解逻辑封印...","凝练类型真元...","铸就函数金丹...","渡劫编译雷劫...","打通模块任督二脉...","修炼 Tree-shaking 神功...","压缩代码乾坤...","布下 Source Map 阵法...","推演 Token 灵数...","炼制 Prompt 仙丹...","调息温度参数...","参透困惑度玄机...","驱动 LLM 灵力...","施展向量搜索术...","构筑 RAG 法阵...","凝聚 Embedding 道果...","勾连向量宝库...","破译函数咒语...","验证 Schema 真意...","封印工具参数...","注入系统道韵...","串联历史因果...","炼化抽象语法树...","破境重构神功...","感悟类型天道...","筑基模块根基...","施展词法轻功...","破解语法阵法...","参悟语义心法...","凝练中间内力...","修炼优化神功...","调息寄存器真气...","运转指令招式...","消除死码杂念...","折叠常量真元...","内联函数身法...","逃逸分析密探...","垃圾回收扫地僧...","标记清除掌法...","分代回收心诀...","增量收功法门...","JIT 即时顿悟...","解读字节码暗器...","V8 引擎神功...","召唤 WASM 傀儡...","开辟虚拟洞府...","丹田分配内存...","掌控栈帧乾坤...","捕获异常剑气...","尾调优化身法...","动态链接飞剑...","建立 TCP 金桥...","三次握手结契...","传送 HTTP 信使...","破译响应符文...","TLS 秘境握手...","验证 SSL 信物...","WebSocket 通灵...","流式传功大法...","gRPC 御剑飞行...","Protobuf 封印术...","GraphQL 问道...","DNS 测算域名...","负载均衡五行阵...","CDN 边缘瞬移...","HTTP/2 分身术...","QUIC 闪现神通...","gzip 缩地成寸...","Brotli 玄冰压缩...","断点续传接续术...","分片上传合璧功...","参研 SQL 真经...","推演查询路径...","索引扫描神识...","全表扫描暴力突破...","执行 JOIN 双修大法...","聚合数据炼丹...","事务提交天地誓...","ACID 四象护法...","乐观锁道心无畏...","悲观锁剑阵守护...","分布式锁万里封禁...","Redis 炼药鼎缓存...","LRU 新陈代谢...","WAL 预写因果簿...","B+ 树平衡阴阳...","LSM 树合璧压缩...","向量宝库搜寻...","余弦相似度测算...","KNN 近邻追踪...","倒排索引翻阅秘籍...","快速排序剑法...","归并排序双刀...","堆排优化内功...","二分查找闪现...","深度优先潜行...","广度优先横扫...","Dijkstra 寻路神算...","A* 天机推演...","动态规划填棋盘...","回溯剑法剪枝...","贪心策略奇谋...","分治递归化身术...","哈希表扩容开天...","红黑树旋转太极...","AVL 树平衡阴阳...","跳表纵身轻功...","Trie 树千头万绪...","布隆过滤天罗地网...","一致性哈希环定乾坤...","最小生成树扎根...","Docker 镜像炼制...","Kubernetes 调兵遣将...","容器结界布阵...","卷挂载空间挪移...","Helm 符箓展开...","CI/CD 流水线作业...","GitHub 门派行动...","代码品鉴术...","漏洞探查密探...","依赖追溯寻根...","蓝绿部署换防...","金丝雀试探...","回滚时光倒流...","健康探查望闻问切...","日志归档藏经阁...","监控预警千里眼...","告警通知飞鸽传书...","性能调优筋骨重塑...","扩容缩容易筋经...","灰度发布声东击西...","React 虚影对决...","组件树调和大法...","Hooks 勾魂术...","useEffect 副作用因果...","Redux 中枢天宫...","Zustand 灵台藏识...","CSS-in-JS 画地为牢...","Tailwind 疾风步...","Webpack 热更换血重生...","Vite 按需凝形...","ESBuild 极速神行...","SWC 闪电炼形...","SSR 天地初开...","Hydration 魂归肉身...","Ink 终端墨宝...","虚拟 DOM 镜花水月...","事件冒泡顺流而上...","状态提升登峰造极...","懒加载厚积薄发...","代码分割庖丁解牛...","SHA-256 炼心咒...","AES-256 玄冰封印...","RSA 阴阳双钥...","JWT 信物令牌...","OAuth 门派授权...","CSRF 防御结界...","XSS 祛邪过滤...","SQL 注入克星...","PBKDF2 淬炼秘钥...","零知识誓言验证...","HTTPS 金钟罩...","签名验证印玺鉴定...","盐值加密炼丹配方...","双因素认证双重认证...","权限控制天条律令...","拜见图灵祖师爷...","冯·诺依曼传道...","Linus 大侠坐镇...","参悟 Rust 生命轮回...","逃离回调地狱轮回...","await 静待天时...","捕获野生 Bug 妖兽...","喂养橡皮鸭灵兽 \uD83E\uDD86...","炼丹调参秘术...","0xDEADBEEF 死亡凝视...","递归无限轮回...","闭包封印记忆...","Promise 未来契约...","async 异步神功...","Generator 分身术...","Proxy 替身傀儡...","Reflect 返照镜...","Symbol 独一无二印记...","WeakMap 过眼云烟...","Iterator 周而复始...","GitHub 武林大会...","Star 点赞声望...","Fork 拜师学艺...","Pull Request 挑战切磋...","Code Review 武功点评...","Issue 悬赏令...","Merge 收徒入门...","Commit 闭关修炼记录...","Branch 分支独辟蹊径...","Tag 里程碑界碑...","Release 出关发布...","License 门规戒律...","README 入门心法...","Documentation 武学秘籍...","Open Source 广纳贤才..."],uW=["Esc - 停止任务 / 隐藏建议 / 双击清空输入","Shift+Tab - 切换模式 (DEFAULT → AUTO_EDIT → PLAN → SPEC)","Tab - 选中建议 / 切换 thinking 模式","↑↓ - 浏览建议或输入历史记录","? - 显示快捷键帮助面板(输入框为空时)","Ctrl+C - 停止任务(双击退出应用)","Ctrl+L - 清屏(清除所有消息)","Ctrl+T - 切换 thinking 内容展开/折叠","Ctrl+O - 切换历史消息展开/折叠","Ctrl+U - 删除从行首到光标的内容","Ctrl+K - 删除从光标到行尾的内容","Shift+Enter - 插入换行(多行输入)","/help - 显示所有可用的 slash commands","/init - 分析项目并生成 BLADE.md 配置","/resume - 恢复历史会话","/compact - 手动压缩当前会话上下文","/theme - 打开交互式主题选择器","/model - 管理和切换模型配置","/model add - 添加新模型配置","/permissions - 管理项目的本地权限规则","/mcp - 显示 MCP 服务器状态和可用工具","/agents - 管理 subagent 配置","/version - 显示版本信息和构建详情","/clear - 清除屏幕内容和对话历史","/status - 显示当前项目配置状态","/context - 可视化当前上下文 Token 使用情况","/git - Git 仓库查询和 AI 辅助","/git review - AI Code Review","/hooks - 管理 Hook 配置","/tasks - 列出所有后台任务","@ 文件路径 - 附加文件到上下文","@dir/ - 附加整个目录","@file.ts:10-20 - 附加指定行范围","Plan 模式 - 先规划后编码(Shift+Tab 切换)","Auto Edit 模式 - 自动批准工具调用","MCP 协议 - 扩展外部工具集成","Subagents - 并行执行子任务","Hooks 系统 - 自定义工具执行流程","Context 压缩 - 自动总结历史对话","Loop 检测 - 防止无限循环","提示:使用 /init 让 AI 理解你的项目结构","提示:Plan 模式适合复杂多步骤任务","提示:Auto Edit 可加速重复性操作","提示:@ 引用可提供更精准的上下文","提示:定期 /compact 节省 token 成本","提示:使用 /permissions 控制工具权限","提示:Shift+Tab 快速切换模式","提示:Esc 可随时中断长时间任务","提示:/resume 继续未完成的对话","提示:/git commit 让 AI 生成 commit message"];function gW($,Z,X=!1){let[Y,Q]=uw("");return mw(()=>{if(Z){Q("等待用户确认...");return}if(!$){Q("");return}if(X)return;let J=()=>{if(Math.random()<0.16666666666666666){let W=Math.floor(Math.random()*uW.length);return uW[W]}let K=Math.floor(Math.random()*mW.length);return mW[K]};Q(J());let G=setInterval(()=>{Q(J())},gw);return()=>{clearInterval(G)}},[$,Z,X]),Y}function lW($,Z=!1,X=!1){let[Y,Q]=cW(0),[J,G]=cW(null),q=gW($,Z,X);return cw(()=>{if(!$){Q(0),G(null);return}if(X)return;if(J===null)G(Date.now());let K=setInterval(()=>{if(J!==null){let W=Math.floor((Date.now()-J)/1000);Q(W)}},1000);return()=>{clearInterval(K)}},[$,J,X]),{currentPhrase:q,elapsedTime:Y}}import{jsxDEV as f$,Fragment as nw}from"react/jsx-dev-runtime";var hZ=["⠋","⠙","⠹","⠸","⠼","⠴","⠦","⠧","⠇","⠏"],rw=80;function iW($){if($<60)return`${$}s`;let Z=Math.floor($/60),X=$%60;return`${Z}m ${X}s`}var aW=lw.memo(({message:$,paused:Z=!1})=>{let X=S2(),Y=h6(),Q=X||!Y,[J,G]=aw(0),q=e0(),W=F8()>=rw,{currentPhrase:U,elapsedTime:H}=lW(Q,!1,Z);if(iw(()=>{if(!Q||Z){G(0);return}let O=setInterval(()=>{G((z)=>(z+1)%hZ.length)},80);return()=>clearInterval(O)},[Q,Z]),!Q)return null;let F=U||$||"正在思考中...";if(W)return f$(Z9,{paddingX:2,paddingBottom:1,flexDirection:"row",gap:1,children:[f$(P1,{color:q.colors.warning,bold:!0,children:hZ[J]},void 0,!1,void 0,this),f$(P1,{color:q.colors.text.primary,children:F},void 0,!1,void 0,this),H>0&&f$(nw,{children:[f$(P1,{color:q.colors.muted,children:"|"},void 0,!1,void 0,this),f$(P1,{color:q.colors.info,children:["已用时: ",iW(H)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),f$(P1,{color:q.colors.muted,children:"|"},void 0,!1,void 0,this),f$(P1,{color:q.colors.secondary,children:"Esc 取消"},void 0,!1,void 0,this)]},void 0,!0,void 0,this);return f$(Z9,{paddingX:2,paddingBottom:1,flexDirection:"column",children:[f$(Z9,{flexDirection:"row",gap:1,children:[f$(P1,{color:q.colors.warning,bold:!0,children:hZ[J]},void 0,!1,void 0,this),f$(P1,{color:q.colors.text.primary,children:F},void 0,!1,void 0,this)]},void 0,!0,void 0,this),H>0&&f$(Z9,{marginLeft:2,flexDirection:"row",gap:1,children:[f$(P1,{color:q.colors.info,children:["已用时: ",iW(H)]},void 0,!0,void 0,this),f$(P1,{color:q.colors.muted,children:"|"},void 0,!1,void 0,this),f$(P1,{color:q.colors.secondary,children:"Esc 取消"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)});import gZ from"ansi-escapes";import{Box as O2,Static as $U,useStdout as WN}from"ink";import UN,{useEffect as R4,useMemo as Y9,useRef as h2,useState as cZ}from"react";import{useStdout as ow}from"ink";import{debounce as sw}from"lodash-es";import{useEffect as tw,useState as ew}from"react";function rW($=200){let{stdout:Z}=ow(),[X,Y]=ew(Z.rows||24);return tw(()=>{let Q=sw(()=>{Y(Z.rows||24)},$);return Q(),Z.on("resize",Q),()=>{Z.off("resize",Q),Q.cancel()}},[Z,$]),X}P8();import{Box as $N,Text as nW}from"ink";import ZN from"react";import{jsxDEV as xZ}from"react/jsx-dev-runtime";var pZ=ZN.memo(({collapsedCount:$})=>{let Z=e0();if($<=0)return null;let X=Z.colors.text.muted;return xZ($N,{flexDirection:"row",marginBottom:1,children:[xZ(nW,{color:X,children:["▶ ",$," 条历史消息"]},void 0,!0,void 0,this),xZ(nW,{color:X,children:" [Ctrl+O 展开]"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)});pZ.displayName="CollapsedHistorySummary";j8();import{Box as N3,Text as b3}from"ink";import XN from"ink-big-text";import YN from"ink-gradient";import QN from"react";import{jsxDEV as L1}from"react/jsx-dev-runtime";var oW=QN.memo(()=>{return L1(N3,{flexDirection:"column",paddingX:2,paddingTop:1,paddingBottom:1,children:[L1(N3,{flexDirection:"column",children:L1(YN,{name:"pastel",children:L1(XN,{text:"BLADE",font:"block"},void 0,!1,void 0,this)},void 0,!1,void 0,this)},void 0,!1,void 0,this),L1(N3,{marginBottom:1,children:L1(b3,{color:"white",dimColor:!0,children:QX()},void 0,!1,void 0,this)},void 0,!1,void 0,this),L1(N3,{flexDirection:"column",marginBottom:1,children:[L1(N3,{marginBottom:1,children:L1(b3,{color:"white",bold:!0,children:"使用指南:"},void 0,!1,void 0,this)},void 0,!1,void 0,this),L1(b3,{color:"white",children:"1. 输入问题、编辑文件或运行命令"},void 0,!1,void 0,this),L1(b3,{color:"white",children:"2. 使用 /init 创建项目配置文件"},void 0,!1,void 0,this),L1(b3,{color:"white",children:"3. 输入 /help 查看所有 slash 命令"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)});import{Box as dZ,Text as b8}from"ink";import JN,{useMemo as sW}from"react";import{jsxDEV as F2}from"react/jsx-dev-runtime";function GN($,Z=60){if(!$)return"";let X=$.split(`
|
|
2820
2820
|
`)[0]||"";if(X.length<=Z)return X;return`${X.slice(0,Z)}...`}function qN($){if(!$)return 0;return $.split(`
|
|
2821
|
-
`).length}var mZ=JN.memo(({content:$,isStreaming:Z=!1,isExpanded:X})=>{let Y=e0(),Q=sW(()=>qN($),[$]),J=sW(()=>GN($),[$]),G=Y.colors.info,q=Y.colors.muted;return
|
|
2822
|
-
`)},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),E(Z0,{children:[E(l,{bold:!0,color:"cyan",children:["▶"," "]},void 0,!0,void 0,this),E(FN,{value:G,onChange:U,onSubmit:H,placeholder:q,mask:K},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)},_N=({provider:$,onLogin:Z,onCancel:X,isLoggingIn:Y})=>{let{isFocused:Q}=G9({id:"oauth-login-step"});A8((G,q)=>{if(Y)return;if(G==="y"||G==="Y")Z();else if(G==="n"||G==="N"||q.escape)X()},{isActive:Q&&!Y});let J=$==="antigravity"?{name:"Google Antigravity",icon:"\uD83D\uDE80",loginCommand:"/login",description:"通过 Google OAuth 登录,使用 Claude/Gemini 模型"}:{name:"GitHub Copilot",icon:"\uD83D\uDC19",loginCommand:"/login copilot",description:"通过 GitHub Device Flow 登录,使用 GPT/Claude/Gemini 模型"};return E(Z0,{flexDirection:"column",marginBottom:1,children:[E(Z0,{marginBottom:1,children:E(l,{bold:!0,color:"yellow",children:[J.icon," 需要登录 ",J.name]},void 0,!0,void 0,this)},void 0,!1,void 0,this),E(Z0,{marginBottom:1,children:E(l,{children:J.description},void 0,!1,void 0,this)},void 0,!1,void 0,this),E(Z0,{marginBottom:1,paddingLeft:2,children:E(l,{dimColor:!0,children:["您也可以稍后手动执行 ",E(l,{bold:!0,children:J.loginCommand},void 0,!1,void 0,this)," 命令登录"]},void 0,!0,void 0,this)},void 0,!1,void 0,this),!Y&&E(Z0,{marginTop:1,children:E(l,{children:["现在登录? [",E(l,{bold:!0,color:"green",children:"Y"},void 0,!1,void 0,this),"/",E(l,{bold:!0,color:"red",children:"n"},void 0,!1,void 0,this),"]"]},void 0,!0,void 0,this)},void 0,!1,void 0,this),Y&&E(Z0,{marginTop:1,children:E(l,{color:"yellow",children:"⏳ 正在启动登录流程..."},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},BN=({provider:$,onSelect:Z,onCancel:X})=>{let{isFocused:Y}=G9({id:"oauth-model-step"}),[Q,J]=x4([]),[G,q]=x4(!0);YU(()=>{(async()=>{q(!0);try{if($==="copilot")J(Object.values(p3));else if(await M$.getInstance().getConfigType()==="gemini-cli")J(Object.values(k3));else J(Object.values(d8))}catch{J(Object.values(d8))}finally{q(!1)}})()},[$]),A8((U,H)=>{if(H.escape)X()},{isActive:Y});let K=Q.map((U)=>({label:`${U.name} - ${U.description}`,value:U.id})),W=$==="antigravity"?"Antigravity":"Copilot";if(G)return E(Z0,{flexDirection:"column",marginBottom:1,children:E(Z0,{marginBottom:1,children:E(l,{bold:!0,color:"blue",children:["\uD83E\uDD16 加载 ",W," 模型列表..."]},void 0,!0,void 0,this)},void 0,!1,void 0,this)},void 0,!1,void 0,this);return E(Z0,{flexDirection:"column",marginBottom:1,children:[E(Z0,{marginBottom:1,children:E(l,{bold:!0,color:"blue",children:["\uD83E\uDD16 选择 ",W," 模型"]},void 0,!0,void 0,this)},void 0,!1,void 0,this),E(Z0,{marginBottom:1,children:E(l,{children:"从可用模型列表中选择一个"},void 0,!1,void 0,this)},void 0,!1,void 0,this),E(Z0,{marginBottom:1,children:E(XU,{items:K,onSelect:(U)=>Z(U.value),indicatorComponent:QU,itemComponent:JU},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},LN=({mode:$,config:Z,isSaving:X,stepNumber:Y,onConfirm:Q,onBack:J,onCancel:G})=>{let{isFocused:q}=G9({id:"confirm-step"});return A8((K,W)=>{if(X)return;if(K==="y"||K==="Y")Q();else if(K==="n"||K==="N")J();else if(W.escape)G()},{isActive:q&&!X}),E(Z0,{flexDirection:"column",marginBottom:1,children:[E(Z0,{marginBottom:1,children:E(l,{bold:!0,color:$==="edit"?"yellow":"blue",children:$==="edit"?"\uD83D\uDCBE 确认修改":`✅ Step ${Y}: 确认配置`},void 0,!1,void 0,this)},void 0,!1,void 0,this),E(Z0,{marginBottom:1,children:E(l,{children:$==="edit"?"请确认修改内容,保存后将立即生效。":"请确认以下配置信息:"},void 0,!1,void 0,this)},void 0,!1,void 0,this),E(Z0,{flexDirection:"column",marginBottom:1,paddingLeft:2,children:[E(Z0,{marginBottom:1,children:[E(l,{dimColor:!0,children:"名称: "},void 0,!1,void 0,this),E(l,{bold:!0,color:"cyan",children:Z.name},void 0,!1,void 0,this)]},void 0,!0,void 0,this),E(Z0,{marginBottom:1,children:[E(l,{dimColor:!0,children:"Provider: "},void 0,!1,void 0,this),E(l,{bold:!0,color:"cyan",children:ON(Z.provider)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),E(Z0,{marginBottom:1,children:[E(l,{dimColor:!0,children:"Base URL: "},void 0,!1,void 0,this),E(l,{bold:!0,color:"blue",children:Z.baseUrl},void 0,!1,void 0,this)]},void 0,!0,void 0,this),E(Z0,{marginBottom:1,children:[E(l,{dimColor:!0,children:"API Key: "},void 0,!1,void 0,this),E(l,{bold:!0,color:"yellow",children:Z.apiKey==="oauth"?"\uD83D\uDD10 OAuth 认证(使用 /login 登录)":E(A3,{children:[Z.apiKey?.slice(0,8),"*".repeat(Math.min(32,(Z.apiKey?.length||0)-8))]},void 0,!0,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),E(Z0,{children:[E(l,{dimColor:!0,children:"Model: "},void 0,!1,void 0,this),E(l,{bold:!0,color:"cyan",children:Z.model},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),!X&&E(Z0,{marginTop:1,children:E(l,{children:[$==="edit"?"保存修改? ":"确认保存配置? ","[",E(l,{bold:!0,color:"green",children:"Y"},void 0,!1,void 0,this),"/",E(l,{bold:!0,color:"red",children:"n"},void 0,!1,void 0,this),"]"]},void 0,!0,void 0,this)},void 0,!1,void 0,this),X&&E(Z0,{children:E(l,{color:"yellow",children:"⏳ 正在保存配置到 ~/.blade/config.json..."},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},iZ=({mode:$,initialConfig:Z,modelId:X,onComplete:Y,onCancel:Q})=>{let J=$==="edit",[G,q]=x4("provider"),[K,W]=x4(()=>J&&Z?{...Z}:{}),[U,H]=x4(""),[F,O]=x4(!1),[z,_]=x4(!1),[B,L]=x4(null),w=X$(!1);A8((y,u)=>{if(u.ctrl&&y==="c"||u.meta&&y==="c")if($==="setup")w();else Q()},{isActive:!0});let{focus:R}=HN();YU(()=>{if(G==="provider")R("provider-step");else if(G==="confirm")R("confirm-step");else if(G==="oauthLogin")R("oauth-login-step");else if(G==="oauthModelSelect")R("oauth-model-step")},[G,R]);let D=()=>{if(!U.trim()){L("配置名称不能为空");return}W({...K,name:U}),H(""),L(null),q("confirm")},V=async(y)=>{if(W({...K,provider:y}),I(y)){let g=y==="antigravity"?M$.getInstance():C$.getInstance();try{if(await g.isLoggedIn())q("oauthModelSelect");else q("oauthLogin")}catch{q("oauthLogin")}return}let u=lZ(y),t=J?K.baseUrl??Z?.baseUrl??"":u??"";H(t),q("baseUrl")},I=(y)=>{return J9[y].isOAuth},v=()=>{if(!U.trim()){L("Base URL 不能为空");return}try{new URL(U)}catch{L("请输入有效的 URL (例如: https://api.openai.com/v1)");return}if(W({...K,baseUrl:U}),L(null),I(K.provider)){W((u)=>({...u,baseUrl:U,apiKey:"oauth"}));let y=J?K.model??Z?.model??"":"";H(y),q("model")}else{let y=J?K.apiKey??Z?.apiKey??"":"";H(y),q("apiKey")}},N=()=>{if(!U.trim()){L("API Key 不能为空");return}W({...K,apiKey:U});let y=J?K.model??Z?.model??"":"";H(y),L(null),q("model")},k=()=>{if(!U.trim()){L("Model 不能为空");return}W({...K,model:U});let y=J?K.name??Z?.name??"":"";H(y),L(null),q("name")},m=async()=>{let u=K.provider==="antigravity"?M$.getInstance():C$.getInstance();_(!0),L(null);try{await u.login(),q("oauthModelSelect")}catch(t){L(t instanceof Error?t.message:"登录失败")}finally{_(!1)}},s=(y)=>{let u=K.provider,t=lZ(u)||"";W({...K,baseUrl:t,apiKey:"oauth",model:y}),H(""),q("name")},S=async()=>{O(!0),L(null);try{let y={name:K.name,provider:K.provider,baseUrl:K.baseUrl,apiKey:K.apiKey,model:K.model};if($==="setup")Y(y);else if($==="add"){let u=await x0().addModel(y);await x0().setCurrentModel(u.id),Y(y)}else{if(!X)throw Error("未提供模型 ID,无法编辑");await x0().updateModel(X,y),Y(y)}}catch(y){L(y instanceof Error?y.message:"配置失败"),O(!1)}},T=()=>{switch(L(null),H(""),G){case"provider":Q();break;case"baseUrl":q("provider");break;case"apiKey":H(K.baseUrl||""),q("baseUrl");break;case"model":q("apiKey");break;case"oauthLogin":q("provider");break;case"oauthModelSelect":q("provider");break;case"name":if(I(K.provider))q("oauthModelSelect");else H(K.model||""),q("model");break;case"confirm":H(K.name||""),q("name");break}},c=K.provider&&I(K.provider),j=c?4:6,M=(()=>{if(G==="provider")return 1;if(c){if(G==="oauthLogin"||G==="oauthModelSelect")return 2;if(G==="name")return 3;return 4}if(G==="baseUrl")return 2;if(G==="apiKey")return 3;if(G==="model")return 4;if(G==="name")return 5;return 6})(),b=Math.floor((M-1)/(j-1)*40);return E(Z0,{...$==="setup"?{flexDirection:"column",padding:1}:$==="add"?{flexDirection:"column",borderStyle:"round",borderColor:"blue",padding:1}:{flexDirection:"column",borderStyle:"round",borderColor:"yellow",padding:1},children:[$==="setup"?E(A3,{children:[E(Z0,{marginBottom:1,children:E(l,{bold:!0,color:"blue",children:"\uD83D\uDE80 欢迎使用 Blade Code"},void 0,!1,void 0,this)},void 0,!1,void 0,this),E(Z0,{marginBottom:1,children:E(l,{children:"AI 驱动的代码助手 - 让我们开始配置您的助手"},void 0,!1,void 0,this)},void 0,!1,void 0,this),E(Z0,{marginBottom:1,children:[E(l,{bold:!0,color:"blue",children:"█".repeat(b)},void 0,!1,void 0,this),E(l,{dimColor:!0,children:"░".repeat(40-b)},void 0,!1,void 0,this),E(l,{children:" "},void 0,!1,void 0,this),E(l,{bold:!0,color:"cyan",children:[M,"/",j]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),E(Z0,{marginBottom:1,children:E(l,{dimColor:!0,children:"━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this):$==="add"?E(A3,{children:[E(Z0,{justifyContent:"center",marginBottom:1,children:E(l,{bold:!0,color:"blue",children:"添加新模型配置"},void 0,!1,void 0,this)},void 0,!1,void 0,this),E(Z0,{marginBottom:1,children:E(l,{children:["步骤: ",M,"/",j]},void 0,!0,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this):E(A3,{children:[E(Z0,{justifyContent:"center",marginBottom:1,children:E(l,{bold:!0,color:"yellow",children:"编辑模型配置"},void 0,!1,void 0,this)},void 0,!1,void 0,this),E(Z0,{marginBottom:1,children:E(l,{children:["步骤: ",M,"/",j]},void 0,!0,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),G==="name"&&E(Q9,{stepNumber:5,icon:"\uD83D\uDCDD",title:"配置名称",description:"给这个模型配置起一个易于识别的名称(可选,用于区分多个配置)",value:U,placeholder:"例如: 千问工作账号",onChange:H,onSubmit:D,onCancel:Q},void 0,!1,void 0,this),G==="provider"&&E(zN,{onSelect:V,onCancel:Q,initialProvider:K.provider},void 0,!1,void 0,this),G==="oauthLogin"&&K.provider&&I(K.provider)&&E(_N,{provider:K.provider,onLogin:m,onCancel:Q,isLoggingIn:z},void 0,!1,void 0,this),G==="oauthModelSelect"&&K.provider&&I(K.provider)&&E(BN,{provider:K.provider,onSelect:s,onCancel:Q},void 0,!1,void 0,this),G==="baseUrl"&&E(Q9,{stepNumber:2,icon:"\uD83C\uDF10",title:"配置 Base URL",description:"输入您的 API 端点地址(完整的 URL 包含协议)",hint:K.provider&&lZ(K.provider)?"\uD83D\uDCA1 已预填充官方 URL,直接回车使用。如需代理服务(如 OpenRouter),请修改。":void 0,examples:["• OpenAI: https://api.openai.com/v1","• Anthropic: https://api.anthropic.com","• Gemini: https://generativelanguage.googleapis.com/v1beta","• Azure: https://{resource}.openai.azure.com","• 代理: https://openrouter.ai/api/v1"],value:U,placeholder:"https://api.example.com/v1",onChange:H,onSubmit:v,onCancel:Q},void 0,!1,void 0,this),G==="apiKey"&&E(Q9,{stepNumber:3,icon:"\uD83D\uDD11",title:"输入 API Key",description:"您的 API 密钥将被安全存储在 ~/.blade/config.json (权限 600)",hint:"\uD83D\uDCA1 提示: 输入时字符会被隐藏,支持粘贴 (Ctrl+V / Cmd+V)",previousValue:K.baseUrl?`✓ Base URL: ${K.baseUrl}`:void 0,value:U,placeholder:"sk-...",mask:"*",onChange:H,onSubmit:N,onCancel:Q},void 0,!1,void 0,this),G==="model"&&E(Q9,{stepNumber:4,icon:"\uD83E\uDD16",title:"选择模型",description:"输入您想使用的模型名称(请参考您的 API 提供商文档)",examples:K.provider==="antigravity"?["• Claude: claude-sonnet-4-5, claude-opus-4-5-thinking","• Gemini: gemini-3-pro-high, gemini-3-pro-low","• GPT-OSS: gpt-oss-120b-medium"]:["• OpenAI: gpt-4o, gpt-4o-mini, o1-preview","• Claude: claude-sonnet-4-20250514, claude-opus-4-20250514","• Gemini: gemini-2.5-pro, gemini-2.5-flash","• Azure: {deployment-name}","• 千问: qwen3-max, qwen3-235b, qwen3-32b","• DeepSeek: deepseek-v3.1, deepseek-r1-0528"],value:U,placeholder:"例如: gpt-5",onChange:H,onSubmit:k,onCancel:Q},void 0,!1,void 0,this),G==="confirm"&&E(LN,{mode:$,config:K,isSaving:F,stepNumber:j,onConfirm:S,onBack:T,onCancel:Q},void 0,!1,void 0,this),B&&E(Z0,{marginTop:1,borderStyle:"round",borderColor:"red",paddingX:1,children:E(l,{color:"red",children:["❌ ",B]},void 0,!0,void 0,this)},void 0,!1,void 0,this),E(Z0,{marginTop:1,children:E(l,{dimColor:!0,children:"━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"},void 0,!1,void 0,this)},void 0,!1,void 0,this),!F&&!z&&G==="provider"&&E(Z0,{marginTop:1,children:E(l,{dimColor:!0,children:["\uD83D\uDCA1 使用 ",E(l,{bold:!0,children:"↑/↓"},void 0,!1,void 0,this)," 键选择,",E(l,{bold:!0,children:"Enter"},void 0,!1,void 0,this)," 确认,",E(l,{bold:!0,children:"Esc"},void 0,!1,void 0,this)," 取消"]},void 0,!0,void 0,this)},void 0,!1,void 0,this),!F&&!z&&G==="oauthModelSelect"&&E(Z0,{marginTop:1,children:E(l,{dimColor:!0,children:["\uD83D\uDCA1 使用 ",E(l,{bold:!0,children:"↑/↓"},void 0,!1,void 0,this)," 键选择模型,",E(l,{bold:!0,children:"Enter"},void 0,!1,void 0,this)," 确认,",E(l,{bold:!0,children:"Esc"},void 0,!1,void 0,this)," 返回"]},void 0,!0,void 0,this)},void 0,!1,void 0,this),!F&&!z&&G==="oauthLogin"&&E(Z0,{marginTop:1,children:E(l,{dimColor:!0,children:["\uD83D\uDCA1 按"," ",E(l,{bold:!0,color:"green",children:"Y"},void 0,!1,void 0,this)," ","登录,",E(l,{bold:!0,color:"red",children:"N"},void 0,!1,void 0,this)," ","返回,",E(l,{bold:!0,children:"Esc"},void 0,!1,void 0,this)," 取消"]},void 0,!0,void 0,this)},void 0,!1,void 0,this),!F&&!z&&G!=="confirm"&&G!=="provider"&&G!=="oauthLogin"&&G!=="oauthModelSelect"&&E(Z0,{marginTop:1,children:E(l,{dimColor:!0,children:["\uD83D\uDCA1 输入完成后按 ",E(l,{bold:!0,children:"Enter"},void 0,!1,void 0,this),",",E(l,{bold:!0,children:"Ctrl+C"},void 0,!1,void 0,this)," 退出"]},void 0,!0,void 0,this)},void 0,!1,void 0,this),!F&&!z&&G==="confirm"&&E(Z0,{marginTop:1,children:E(l,{dimColor:!0,children:["\uD83D\uDCA1 按"," ",E(l,{bold:!0,color:"green",children:"Y"},void 0,!1,void 0,this)," ","保存,",E(l,{bold:!0,color:"red",children:"N"},void 0,!1,void 0,this)," ","返回修改,",E(l,{bold:!0,children:"Esc"},void 0,!1,void 0,this)," 取消"]},void 0,!0,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)};C3();import{useMemoizedFn as q9,useMount as wN}from"ahooks";import{Box as X1,Text as T0,useFocus as NN,useFocusManager as bN,useInput as AN}from"ink";import RN from"ink-select-input";import{memo as VN,useMemo as DN,useState as K9}from"react";C0();import{jsxDEV as H0}from"react/jsx-dev-runtime";function MN($){switch($){case"openai-compatible":return"⚡ OpenAI Compatible";case"anthropic":return"\uD83E\uDD16 Anthropic Claude";case"gemini":return"✨ Google Gemini";case"azure-openai":return"☁️ Azure OpenAI";default:return $}}var jN=({isSelected:$})=>H0(X1,{marginRight:1,children:H0(T0,{color:$?"yellow":"gray",children:$?"▶":" "},void 0,!1,void 0,this)},void 0,!1,void 0,this),IN=({isSelected:$,label:Z})=>H0(T0,{bold:$,color:$?"yellow":void 0,children:Z},void 0,!1,void 0,this),GU=VN(({onClose:$,onEdit:Z})=>{let X=jK(),Y=IK()??"",{isFocused:Q}=NN({id:"model-selector"}),J=bN(),[G,q]=K9(""),[K,W]=K9(!1),[U,H]=K9(null),F=X$(!1),[O]=K9(()=>{let I=process.stdout?.columns||80;return Math.max(20,I-8)});wN(()=>{if(J?.focus("model-selector"),X.length>0)q(X[0].id)}),AN((I,v)=>{if(K)return;if(v.ctrl&&I==="c"||v.meta&&I==="c"){F();return}if(v.escape){$();return}if(!Q)return;if(I==="d"||I==="D"){_();return}if((I==="e"||I==="E")&&Z)B()},{isActive:!0});let z=q9(async(I)=>{if(K)return;let v=I.value;if(v===Y){$();return}W(!0),H(null);try{await x0().setCurrentModel(v),$()}catch(N){H(N.message),W(!1)}}),_=q9(async()=>{if(K||G===Y)return;W(!0),H(null);try{if(await x0().removeModel(G),X.length<=1)$()}catch(I){H(I.message)}finally{W(!1)}}),B=q9(()=>{if(K||!Z)return;let I=X.find((v)=>v.id===G);if(!I)return;Z(I)}),L=q9((I)=>{q(I.value)}),w=DN(()=>{return X.find((I)=>I.id===G)},[X,G]),R=X.map((I)=>{let v=I.id===Y?" (当前)":"";return{label:I.name+v,value:I.id}}),D=G===Y;return H0(X1,{flexDirection:"column",borderStyle:"round",borderColor:"gray",padding:1,width:"100%",children:[H0(X1,{flexDirection:"row",justifyContent:"space-between",marginBottom:1,children:[H0(T0,{bold:!0,color:"cyan",children:"模型管理"},void 0,!1,void 0,this),H0(T0,{dimColor:!0,children:[K?"⏳ 处理中...":D?"Enter=关闭 • E=编辑 • Esc=取消":"Enter=切换 • D=删除 • E=编辑 • Esc=取消"," • Ctrl+C=退出"]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),H0(X1,{flexDirection:"row",children:[H0(X1,{flexDirection:"column",flexGrow:2,marginRight:2,borderStyle:"single",borderColor:"gray",padding:1,children:[H0(T0,{dimColor:!0,children:["已配置模型 (",X.length,")"]},void 0,!0,void 0,this),H0(X1,{marginTop:1,children:H0(RN,{items:R,onSelect:z,onHighlight:L,indicatorComponent:jN,itemComponent:IN},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),H0(X1,{flexDirection:"column",flexGrow:3,borderStyle:"single",borderColor:"gray",padding:1,children:[H0(T0,{dimColor:!0,children:"模型详情"},void 0,!1,void 0,this),H0(X1,{marginY:1,children:H0(T0,{color:D?"green":"yellow",children:D?"● 当前使用":"● 可切换"},void 0,!1,void 0,this)},void 0,!1,void 0,this),w?H0(X1,{flexDirection:"column",children:[H0(T0,{children:[H0(T0,{dimColor:!0,children:"名称: "},void 0,!1,void 0,this),H0(T0,{bold:!0,color:"cyan",children:w.name},void 0,!1,void 0,this),q7(w)&&H0(T0,{color:"green",children:" (内置免费)"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),H0(T0,{children:[H0(T0,{dimColor:!0,children:"Provider: "},void 0,!1,void 0,this),H0(T0,{bold:!0,children:MN(w.provider)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),H0(T0,{children:[H0(T0,{dimColor:!0,children:"Model: "},void 0,!1,void 0,this),H0(T0,{bold:!0,children:w.model},void 0,!1,void 0,this)]},void 0,!0,void 0,this),H0(T0,{children:[H0(T0,{dimColor:!0,children:"Base URL: "},void 0,!1,void 0,this),H0(T0,{color:"blueBright",children:w.baseUrl},void 0,!1,void 0,this)]},void 0,!0,void 0,this),w.temperature!==void 0&&H0(T0,{children:[H0(T0,{dimColor:!0,children:"Temperature: "},void 0,!1,void 0,this),H0(T0,{children:w.temperature},void 0,!1,void 0,this)]},void 0,!0,void 0,this),w.maxContextTokens!==void 0&&H0(T0,{children:[H0(T0,{dimColor:!0,children:"Context Window: "},void 0,!1,void 0,this),H0(T0,{children:w.maxContextTokens},void 0,!1,void 0,this)]},void 0,!0,void 0,this),q7(w)&&H0(X1,{marginTop:1,children:H0(T0,{color:"green",dimColor:!0,children:"\uD83D\uDCA1 此模型由 Blade 提供免费额度"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this):H0(T0,{dimColor:!0,children:"请选择一个模型查看详情"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),U&&H0(X1,{marginTop:1,children:H0(T0,{color:"red",children:["❌ ",U]},void 0,!0,void 0,this)},void 0,!1,void 0,this),H0(X1,{justifyContent:"center",marginTop:1,children:H0(T0,{dimColor:!0,children:"─".repeat(O)},void 0,!1,void 0,this)},void 0,!1,void 0,this),H0(X1,{justifyContent:"center",children:H0(T0,{dimColor:!0,children:"提示:D=删除 • E=编辑 • ↑↓=移动 • Enter/ESC=确认"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)});import{useMemoizedFn as R3}from"ahooks";import{promises as UU}from"fs";import{Box as Y1,Text as $$,useInput as yN}from"ink";import qU from"ink-select-input";import vN from"ink-text-input";import EN from"os";import W9 from"path";import{useEffect as PN,useMemo as U9,useRef as TN,useState as p4}from"react";C0();import{jsxDEV as _0}from"react/jsx-dev-runtime";var V3=[{key:"allow",label:"Allow"},{key:"ask",label:"Ask"},{key:"deny",label:"Deny"},{key:"info",label:"Info"}],SN={allow:"Add a new rule...",ask:"Add a new rule...",deny:"Add a new rule..."},CN={allow:"Allow permission rules",ask:"Ask permission rules",deny:"Deny permission rules"},KU={project:"[项目共享配置]",global:"[用户全局配置]",local:"[本地配置]"},kN=["project","global","local"],fN={allow:[],ask:[],deny:[]},hN={localExists:!1,projectExists:!1,globalExists:!1},WU={allow:[],ask:[],deny:[]};function xN($){let Z=(Y)=>Array.isArray(Y)?Y.filter((Q)=>typeof Q==="string"):[],X=$?.permissions??{};return{allow:Z(X?.allow),ask:Z(X?.ask),deny:Z(X?.deny)}}async function pN($){try{let Z=await UU.readFile($,"utf-8"),X=JSON.parse(Z);return{exists:!0,raw:X,permissions:xN(X)}}catch(Z){if(Z.code==="ENOENT")return{exists:!1,raw:{},permissions:{...WU}};return console.warn(`[PermissionsManager] Failed to read ${$}:`,Z),{exists:!0,raw:{},permissions:{...WU}}}}function dN($,Z){let X=$.padEnd(32," "),Y=Z==="local"?`${KU[Z]} ← 可删除`:KU[Z];return`${X} ${Y}`}var HU=({onClose:$})=>{let X=o$()==="permissions-manager",Y=X$(!1),[Q,J]=p4(0),G=V3[Q].key,[q,K]=p4(fN),[W,U]=p4(hN),[H,F]=p4(!0),[O,z]=p4("list"),[_,B]=p4(""),[L,w]=p4(null),[R,D]=p4(null),V=TN(!1),I=U9(()=>W9.join(process.cwd(),".blade","settings.local.json"),[]),v=U9(()=>W9.join(process.cwd(),".blade","settings.json"),[]),N=U9(()=>W9.join(EN.homedir(),".blade","settings.json"),[]),k=R3(async()=>{F(!0);let g=[{source:"local",path:I},{source:"project",path:v},{source:"global",path:N}],X0=await Promise.all(g.map(async({source:w0,path:Y$})=>{let G$=await pN(Y$);return{source:w0,path:Y$,...G$}})),h={localExists:X0.find((w0)=>w0.source==="local")?.exists??!1,projectExists:X0.find((w0)=>w0.source==="project")?.exists??!1,globalExists:X0.find((w0)=>w0.source==="global")?.exists??!1};U(h);let L0={allow:[],ask:[],deny:[]},G0=Object.fromEntries(X0.map((w0)=>[w0.source,w0]));["allow","ask","deny"].forEach((w0)=>{kN.forEach((Y$)=>{(G0[Y$]?.permissions[w0]??[]).forEach((r1,Q$)=>{let Q0={key:`${Y$}:${Q$}:${r1}`,rule:r1,source:Y$};L0[w0].push(Q0)})})}),K(L0),F(!1)});PN(()=>{k()},[k]);let m=R3(async(g,X0)=>{try{let h=W9.join(process.cwd(),".blade","settings.local.json"),L0={allow:[],ask:[],deny:[]};try{let w0=await UU.readFile(h,"utf-8"),G$=JSON.parse(w0).permissions||{};L0={allow:Array.isArray(G$.allow)?G$.allow:[],ask:Array.isArray(G$.ask)?G$.ask:[],deny:Array.isArray(G$.deny)?G$.deny:[]}}catch(w0){}let G0=X0(L0);await x0().updateConfig({permissions:G0},{scope:"local",immediate:!0}),await k()}catch(h){throw console.error("[PermissionsManager] 修改权限规则失败:",h),h}});yN((g,X0)=>{if(X0.ctrl&&g==="c"||X0.meta&&g==="c"){Y();return}if(O==="locked"){if(V.current){V.current=!1;return}z("list"),w(null),D(null);return}if(X0.escape){if(O==="list"||G==="info")$();else z("list"),B(""),w(null),D(null);return}if(O==="list"){if(X0.tab&&X0.shift)J((h)=>(h-1+V3.length)%V3.length);else if(X0.tab)J((h)=>(h+1)%V3.length);else if(g?.toLowerCase()==="q")$()}},{isActive:X});let s=R3((g)=>{let X0=g.value;if(G==="info")return;if(X0.type==="add"){z("add"),B(""),D(null);return}if(X0.entry.source!=="local"){z("locked"),V.current=!0,w({tab:G,entry:X0.entry}),D({type:"error",text:X0.entry.source==="project"?"此规则定义在项目共享配置中,无法在此删除。":"此规则来自用户全局配置,无法在此删除。"});return}z("confirm-delete"),w({tab:G,entry:X0.entry}),D(null)}),S=R3(async()=>{if(G==="info")return;let g=_.trim();if(!g){D({type:"error",text:"Permission rule 不能为空"});return}if(q[G].map((h)=>h.rule).includes(g)){D({type:"error",text:"该规则已存在"});return}try{await m(G,(h)=>{let L0={allow:[...h.allow],ask:[...h.ask],deny:[...h.deny]};return L0[G]=[...new Set([...h[G],g])],L0}),z("list"),B(""),D({type:"success",text:"已添加本地权限规则"})}catch(h){D({type:"error",text:`保存失败: ${h instanceof Error?h.message:"未知错误"}`})}}),T=R3(async()=>{if(!L)return;let{tab:g,entry:X0}=L;try{await m(g,(h)=>{let L0={allow:[...h.allow],ask:[...h.ask],deny:[...h.deny]};return L0[g]=h[g].filter((G0)=>G0!==X0.rule),L0}),z("list"),w(null),D({type:"success",text:"已删除本地权限规则"})}catch(h){D({type:"error",text:`删除失败: ${h instanceof Error?h.message:"未知错误"}`})}}),c=U9(()=>{if(G==="info")return[];let g=G;return[{key:"add-new-rule",label:`› ${SN[g]}`,value:{type:"add"}},...q[g].map((h)=>({key:h.key,label:dN(h.rule,h.source),value:{type:"rule",entry:h}}))]},[G,q]),j=()=>_0(Y1,{marginBottom:1,children:V3.map((g,X0)=>_0(Y1,{marginRight:2,children:_0($$,{color:X0===Q?"yellow":"gray",children:["[",g.label,"]"]},void 0,!0,void 0,this)},g.key,!1,void 0,this))},void 0,!1,void 0,this),M=()=>_0(Y1,{flexDirection:"column",gap:1,children:[_0($$,{children:"配置文件优先级(从高到低):"},void 0,!1,void 0,this),_0(Y1,{flexDirection:"column",marginLeft:2,children:[_0($$,{children:["1. .blade/settings.local.json (本地配置,不提交 Git)"," ",W.localExists?"✓ 存在":"✗ 不存在"]},void 0,!0,void 0,this),_0($$,{children:["2. .blade/settings.json (项目配置,提交 Git)"," ",W.projectExists?"✓ 存在":"✗ 不存在"]},void 0,!0,void 0,this),_0($$,{children:["3. ~/.blade/settings.json (用户全局配置)"," ",W.globalExists?"✓ 存在":"✗ 不存在"]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),_0($$,{children:"说明:"},void 0,!1,void 0,this),_0(Y1,{flexDirection:"column",marginLeft:2,children:[_0($$,{children:"- /permissions 命令只管理本地配置 (.blade/settings.local.json)"},void 0,!1,void 0,this),_0($$,{children:"- 修改全局或项目配置请直接编辑对应文件"},void 0,!1,void 0,this),_0($$,{children:"- 本地配置不会提交到 Git"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),b=(g)=>_0(Y1,{flexDirection:"column",gap:1,children:[_0($$,{bold:!0,children:CN[g]},void 0,!1,void 0,this),_0($$,{children:"Permission rules are a tool name, optionally followed by a specifier in parentheses."},void 0,!1,void 0,this),_0($$,{color:"gray",children:"例如: WebFetch 或 Bash(ls:*)"},void 0,!1,void 0,this),_0(Y1,{marginTop:1,children:_0(vN,{value:_,onChange:B,onSubmit:S},void 0,!1,void 0,this)},void 0,!1,void 0,this),_0($$,{color:"gray",children:"Enter 提交 · Esc 取消"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),n=(g,X0)=>_0(Y1,{flexDirection:"column",gap:1,children:[_0($$,{bold:!0,children:["Delete ",g," permission rule?"]},void 0,!0,void 0,this),_0($$,{children:X0.rule},void 0,!1,void 0,this),_0($$,{color:"gray",children:"From project local settings"},void 0,!1,void 0,this),_0($$,{children:"Are you sure you want to delete this permission rule?"},void 0,!1,void 0,this),_0(qU,{items:[{label:"Yes",value:"yes"},{label:"No",value:"no"}],onSelect:(h)=>{if(h.value==="yes")T();else z("list"),w(null)}},void 0,!1,void 0,this)]},void 0,!0,void 0,this),y=(g)=>_0(Y1,{flexDirection:"column",gap:1,children:[_0($$,{bold:!0,children:"Cannot delete this rule"},void 0,!1,void 0,this),_0($$,{children:g.rule},void 0,!1,void 0,this),_0($$,{color:"gray",children:g.source==="project"?"This rule is defined in .blade/settings.json. 请手动编辑该文件以移除规则。":"This rule is defined in ~/.blade/settings.json. 请手动编辑该文件以移除规则。"},void 0,!1,void 0,this),_0($$,{color:"gray",children:"按任意键继续"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),u=(g)=>_0(qU,{items:c,isFocused:O==="list",onSelect:s},void 0,!1,void 0,this),t=()=>{if(H)return _0($$,{children:"加载中..."},void 0,!1,void 0,this);if(G==="info")return M();if(O==="add")return b(G);if(O==="confirm-delete"&&L)return n(L.tab,L.entry);if(O==="locked"&&L)return y(L.entry);return u(G)};return _0(Y1,{flexDirection:"column",borderStyle:"round",borderColor:X?"cyan":"gray",padding:1,width:80,children:[_0($$,{color:"cyan",bold:!0,children:"⚙️ 权限管理器"},void 0,!1,void 0,this),j(),_0(Y1,{flexDirection:"column",gap:1,children:t()},void 0,!1,void 0,this),R&&_0(Y1,{marginTop:1,children:_0($$,{color:R.type==="success"?"green":"red",children:R.text},void 0,!1,void 0,this)},void 0,!1,void 0,this),_0(Y1,{marginTop:1,children:_0($$,{color:"gray",children:"Tab 切换视图 · Esc 关闭 · Q 退出"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)};X8();import{Box as t0,Text as b0,useInput as mN}from"ink";import{jsxDEV as r}from"react/jsx-dev-runtime";function FU({onCancel:$}){let Z=a$(),X=Z.getAll(),Y=Z.getBySource(),Q=Z.getStats(),J=X$(!1,$);if(mN((G,q)=>{if(q.escape)$?.();else if(q.ctrl&&G==="c"||q.meta&&G==="c")J()}),X.length===0)return r(t0,{flexDirection:"column",paddingY:1,children:[r(t0,{marginBottom:1,children:r(b0,{bold:!0,color:"cyan",children:"\uD83D\uDD0C 插件管理器"},void 0,!1,void 0,this)},void 0,!1,void 0,this),r(t0,{paddingLeft:2,children:r(b0,{color:"gray",children:"没有已加载的插件"},void 0,!1,void 0,this)},void 0,!1,void 0,this),r(t0,{marginTop:1,paddingLeft:2,flexDirection:"column",children:[r(b0,{color:"gray",children:"插件目录位置:"},void 0,!1,void 0,this),r(b0,{color:"gray",dimColor:!0,children:[" ","• ~/.blade/plugins/ - 用户级插件"]},void 0,!0,void 0,this),r(b0,{color:"gray",dimColor:!0,children:[" ","• .blade/plugins/ - 项目级插件"]},void 0,!0,void 0,this),r(b0,{color:"gray",dimColor:!0,children:[" ","• --plugin-dir - CLI 指定的插件"]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),r(t0,{marginTop:1,paddingLeft:2,children:r(b0,{color:"gray",children:"使用 /plugins install <url> 安装新插件"},void 0,!1,void 0,this)},void 0,!1,void 0,this),r(t0,{marginTop:1,children:r(b0,{dimColor:!0,children:"按 ESC 返回菜单"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this);return r(t0,{flexDirection:"column",paddingY:1,children:[r(t0,{marginBottom:1,children:[r(b0,{bold:!0,color:"cyan",children:"\uD83D\uDD0C 插件管理器"},void 0,!1,void 0,this),r(b0,{color:"gray",children:[" (共 ",Q.total," 个插件)"]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),r(t0,{paddingLeft:2,marginBottom:1,children:r(b0,{color:"gray",children:["启用: ",Q.active," | 禁用: ",Q.inactive," | 命令: ",Q.commands," | 技能:"," ",Q.skills," | 代理: ",Q.agents]},void 0,!0,void 0,this)},void 0,!1,void 0,this),Y.cli.length>0&&r(t0,{flexDirection:"column",marginBottom:1,children:[r(t0,{paddingLeft:1,children:[r(b0,{bold:!0,color:"magenta",children:"CLI 指定"},void 0,!1,void 0,this),r(b0,{color:"gray",children:" (--plugin-dir)"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),Y.cli.map((G)=>{let q=G.status==="active"?"✅":"⏸️";return r(t0,{flexDirection:"column",paddingLeft:2,children:[r(b0,{children:[r(b0,{bold:!0,color:"green",children:[q," ",G.manifest.name]},void 0,!0,void 0,this),r(b0,{color:"gray",children:[" v",G.manifest.version]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),r(t0,{paddingLeft:2,children:r(b0,{color:"gray",children:G.manifest.description},void 0,!1,void 0,this)},void 0,!1,void 0,this),G.commands.length>0&&r(t0,{paddingLeft:2,children:r(b0,{color:"blue",children:["命令:"," ",G.commands.map((K)=>`/${K.namespacedName}`).join(", ")]},void 0,!0,void 0,this)},void 0,!1,void 0,this)]},G.manifest.name,!0,void 0,this)})]},void 0,!0,void 0,this),Y.project.length>0&&r(t0,{flexDirection:"column",marginBottom:1,children:[r(t0,{paddingLeft:1,children:[r(b0,{bold:!0,color:"yellow",children:"项目级"},void 0,!1,void 0,this),r(b0,{color:"gray",children:" (.blade/plugins/)"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),Y.project.map((G)=>{let q=G.status==="active"?"✅":"⏸️";return r(t0,{flexDirection:"column",paddingLeft:2,children:[r(b0,{children:[r(b0,{bold:!0,color:"green",children:[q," ",G.manifest.name]},void 0,!0,void 0,this),r(b0,{color:"gray",children:[" v",G.manifest.version]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),r(t0,{paddingLeft:2,children:r(b0,{color:"gray",children:G.manifest.description},void 0,!1,void 0,this)},void 0,!1,void 0,this),G.commands.length>0&&r(t0,{paddingLeft:2,children:r(b0,{color:"blue",children:["命令:"," ",G.commands.map((K)=>`/${K.namespacedName}`).join(", ")]},void 0,!0,void 0,this)},void 0,!1,void 0,this)]},G.manifest.name,!0,void 0,this)})]},void 0,!0,void 0,this),Y.user.length>0&&r(t0,{flexDirection:"column",marginBottom:1,children:[r(t0,{paddingLeft:1,children:[r(b0,{bold:!0,color:"cyan",children:"用户级"},void 0,!1,void 0,this),r(b0,{color:"gray",children:" (~/.blade/plugins/)"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),Y.user.map((G)=>{let q=G.status==="active"?"✅":"⏸️";return r(t0,{flexDirection:"column",paddingLeft:2,children:[r(b0,{children:[r(b0,{bold:!0,color:"green",children:[q," ",G.manifest.name]},void 0,!0,void 0,this),r(b0,{color:"gray",children:[" v",G.manifest.version]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),r(t0,{paddingLeft:2,children:r(b0,{color:"gray",children:G.manifest.description},void 0,!1,void 0,this)},void 0,!1,void 0,this),G.commands.length>0&&r(t0,{paddingLeft:2,children:r(b0,{color:"blue",children:["命令:"," ",G.commands.map((K)=>`/${K.namespacedName}`).join(", ")]},void 0,!0,void 0,this)},void 0,!1,void 0,this)]},G.manifest.name,!0,void 0,this)})]},void 0,!0,void 0,this),r(t0,{marginTop:1,paddingLeft:2,flexDirection:"column",children:[r(b0,{color:"gray",children:"可用命令:"},void 0,!1,void 0,this),r(b0,{color:"gray",dimColor:!0,children:[" ","• /plugins list - 列出所有插件"]},void 0,!0,void 0,this),r(b0,{color:"gray",dimColor:!0,children:[" ","• /plugins info <name> - 显示插件详情"]},void 0,!0,void 0,this),r(b0,{color:"gray",dimColor:!0,children:[" ","• /plugins install <url> - 安装插件"]},void 0,!0,void 0,this),r(b0,{color:"gray",dimColor:!0,children:[" ","• /plugins enable/disable <name> - 启用/禁用插件"]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),r(t0,{marginTop:1,children:r(b0,{dimColor:!0,children:"按 ESC 返回菜单"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}import{Box as h$,Text as x$,useInput as OU,useStdout as uN}from"ink";import gN from"ink-text-input";import aZ,{useCallback as D3,useMemo as cN,useState as d4}from"react";import{jsxDEV as D0}from"react/jsx-dev-runtime";var lN=aZ.memo(({option:$,index:Z,isSelected:X,isMultiSelect:Y,isHighlighted:Q})=>D0(h$,{flexDirection:"column",marginBottom:1,children:[D0(x$,{color:Q?"yellow":X?"green":void 0,bold:Q,children:[Y?X?"● ":"○ ":Q?"❯ ":" ",Z+1,". ",$.label]},void 0,!0,void 0,this),D0(h$,{marginLeft:4,children:D0(x$,{color:"gray",children:$.description},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)),iN=aZ.memo(({questions:$,answers:Z})=>D0(h$,{flexDirection:"column",marginBottom:1,children:$.map((X)=>{let Y=Z[X.header],Q=Array.isArray(Y)?Y.join(", "):Y||"(no answer)";return D0(h$,{marginBottom:1,children:[D0(x$,{backgroundColor:"blue",color:"white",children:[" ",X.header," "]},void 0,!0,void 0,this),D0(x$,{color:"green",children:[" ",Q]},void 0,!0,void 0,this)]},X.header,!0,void 0,this)})},void 0,!1,void 0,this)),zU=aZ.memo(({questions:$,onComplete:Z,onCancel:X})=>{let{stdout:Y}=uN(),Q=Y.columns||80,G=o$()==="confirmation-prompt",q=X$(!1),[K,W]=d4("answering"),[U,H]=d4(0),[F,O]=d4({}),[z,_]=d4(0),[B,L]=d4([]),[w,R]=d4(!1),[D,V]=d4(""),[I,v]=d4(0),N=$[U],k=cN(()=>{if(!N)return[];return[...N.options.map((j)=>({label:j.label,value:j.label,description:j.description})),{label:"Type something...",value:"__other__",description:"Enter custom response"}]},[N]),m=D3((j)=>{let M={...F,[N.header]:j};if(O(M),U<$.length-1)H(U+1),_(0),L([]),R(!1),V("");else W("submit"),v(0)},[F,N?.header,U,$.length]),s=D3((j)=>{let M=k[j];if(!M)return;if(M.value==="__other__"){R(!0);return}if(N.multiSelect)L((b)=>b.includes(M.value)?b.filter((n)=>n!==M.value):[...b,M.value]);else m(M.value)},[k,N?.multiSelect,m]),S=D3((j)=>{if(j.trim())m(j.trim())},[m]),T=D3(()=>{W("answering"),H(0),_(0),L([]),R(!1)},[]),c=D3(()=>{Z(F)},[F,Z]);if(OU((j,M)=>{if(M.ctrl&&j==="c"||M.meta&&j==="c"){q();return}if(w){if(M.escape)R(!1),V("");return}if(M.escape){X();return}let b=parseInt(j);if(b>=1&&b<=k.length){s(b-1);return}if(M.upArrow){_((n)=>n>0?n-1:k.length-1);return}if(M.downArrow||M.tab){_((n)=>n<k.length-1?n+1:0);return}if(M.return){if(N.multiSelect&&B.length>0)m(B);else s(z);return}if(j===" "&&N.multiSelect){let n=k[z];if(n&&n.value!=="__other__")L((y)=>y.includes(n.value)?y.filter((u)=>u!==n.value):[...y,n.value]);return}},{isActive:G&&K==="answering"&&!w}),OU((j,M)=>{if(M.ctrl&&j==="c"||M.meta&&j==="c"){q();return}if(M.escape){X();return}if(M.upArrow||M.downArrow||M.tab){v((b)=>b===0?1:0);return}if(M.return){if(I===0)c();else T();return}if(j.toLowerCase()==="y"){c();return}if(j.toLowerCase()==="e"){T();return}},{isActive:G&&K==="submit"}),K==="submit")return D0(h$,{flexDirection:"column",borderStyle:"round",borderColor:G?"green":"gray",padding:1,width:Math.min(Q-4,80),children:[D0(h$,{marginBottom:1,children:D0(x$,{bold:!0,color:"green",children:"✓ Review Your Answers"},void 0,!1,void 0,this)},void 0,!1,void 0,this),D0(iN,{questions:$,answers:F},void 0,!1,void 0,this),D0(h$,{flexDirection:"column",marginTop:1,children:[D0(x$,{color:I===0?"yellow":void 0,bold:I===0,children:[I===0?"❯ ":" ","[Y] Submit answers"]},void 0,!0,void 0,this),D0(x$,{color:I===1?"yellow":void 0,bold:I===1,children:[I===1?"❯ ":" ","[E] Edit answers"]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),D0(h$,{marginTop:1,children:D0(x$,{color:"gray",children:"Enter to confirm · ↑↓ to navigate · Y/E for quick select"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this);if(!N)return null;return D0(h$,{flexDirection:"column",borderStyle:"round",borderColor:G?"cyan":"gray",padding:1,width:Math.min(Q-4,80),children:[D0(h$,{marginBottom:1,children:[D0(x$,{backgroundColor:"blue",color:"white",children:[" ",N.header," "]},void 0,!0,void 0,this),D0(x$,{children:[" ",N.question]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),w?D0(h$,{flexDirection:"column",marginTop:1,children:[D0(x$,{color:"yellow",children:"Enter your response:"},void 0,!1,void 0,this),D0(h$,{marginTop:1,children:[D0(x$,{color:"cyan",children:"❯ "},void 0,!1,void 0,this),D0(gN,{value:D,onChange:V,onSubmit:S,focus:G},void 0,!1,void 0,this)]},void 0,!0,void 0,this),D0(h$,{marginTop:1,children:D0(x$,{color:"gray",children:"(Press Enter to submit, ESC to go back)"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this):D0(h$,{flexDirection:"column",children:k.map((j,M)=>D0(lN,{option:j,index:M,isSelected:B.includes(j.value),isMultiSelect:N.multiSelect,isHighlighted:z===M},j.value,!1,void 0,this))},void 0,!1,void 0,this),!w&&D0(h$,{marginTop:1,flexDirection:"column",children:[D0(x$,{color:"gray",children:N.multiSelect?"Space to toggle · Enter to confirm · 1-9 for quick select":"Enter to select · ↑↓ or Tab to navigate · 1-9 for quick select"},void 0,!1,void 0,this),N.multiSelect&&B.length>0&&D0(x$,{color:"green",children:["Selected: ",B.join(", ")]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),$.length>1&&D0(h$,{marginTop:1,children:D0(x$,{color:"gray",children:["Question ",U+1," of ",$.length]},void 0,!0,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)});E6();import{Box as R8,Text as T1,useInput as aN}from"ink";import rN from"ink-select-input";import{useEffect as _U,useMemo as H9,useState as rZ}from"react";import{jsxDEV as j$}from"react/jsx-dev-runtime";function nN($){let Z=new Date($),Y=new Date().getTime()-Z.getTime(),Q=Math.floor(Y/86400000);if(Q===0)return`今天 ${Z.getHours().toString().padStart(2,"0")}:${Z.getMinutes().toString().padStart(2,"0")}`;if(Q===1)return"昨天";if(Q<7)return`${Q}天前`;return`${Z.getMonth()+1}/${Z.getDate()}`}function oN($){let Z=$.split("/");return Z[Z.length-1]||$}var sN=({isSelected:$})=>j$(R8,{marginRight:1,children:j$(T1,{color:$?"cyan":"gray",children:$?"❯":" "},void 0,!1,void 0,this)},void 0,!1,void 0,this),tN=({isSelected:$,label:Z})=>j$(T1,{color:$?"cyan":"white",bold:$,children:Z},void 0,!1,void 0,this),M3=20,BU=({sessions:$,onSelect:Z,onCancel:X})=>{let[Y,Q]=rZ([]),[J,G]=rZ(!1),[q,K]=rZ(0),U=o$()==="session-selector",H=X$(!1);aN((w,R)=>{if(R.ctrl&&w==="c"||R.meta&&w==="c"){H();return}if(R.escape&&X){X();return}if(R.leftArrow||w==="h"||w==="H"){if(q>0)K((D)=>D-1);return}if(R.rightArrow||w==="l"||w==="L"){if(q<z-1)K((D)=>D+1);return}},{isActive:U}),_U(()=>{if($){Q($);return}(async()=>{G(!0);try{let R=await m1.listSessions();Q(R)}catch(R){console.error("[SessionSelector] Failed to load sessions:",R),Q([])}finally{G(!1)}})()},[$]);let F=$||Y,O=H9(()=>{return F.map((w)=>{let R=oN(w.projectPath),D=nN(w.lastMessageTime),V=w.gitBranch?` (${w.gitBranch})`:"",I=w.hasErrors?" ⚠️":"";return{label:`\uD83D\uDCC5 ${D} | ${R}${V} | ${w.messageCount} 条消息${I}`,value:w.sessionId}})},[F]),z=H9(()=>Math.max(1,Math.ceil(O.length/M3)),[O.length]),_=H9(()=>{let w=q*M3;return O.slice(w,w+M3)},[O,q]),B=H9(()=>({start:q*M3+1,end:Math.min((q+1)*M3,O.length)}),[q,O.length]);_U(()=>{K(0)},[F.length]);let L=(w)=>{Z(w.value)};if(J)return j$(R8,{flexDirection:"column",paddingX:2,paddingY:1,children:j$(T1,{children:"⏳ 正在加载会话列表..."},void 0,!1,void 0,this)},void 0,!1,void 0,this);if(F.length===0)return j$(R8,{flexDirection:"column",paddingX:2,paddingY:1,children:[j$(T1,{color:"yellow",children:"⚠️ 没有找到历史会话"},void 0,!1,void 0,this),j$(T1,{dimColor:!0,children:[`
|
|
2821
|
+
`).length}var mZ=JN.memo(({content:$,isStreaming:Z=!1,isExpanded:X})=>{let Y=e0(),Q=sW(()=>qN($),[$]),J=sW(()=>GN($),[$]),G=Y.colors.info,q=Y.colors.muted;return F2(dZ,{flexDirection:"column",marginBottom:1,children:[F2(dZ,{flexDirection:"row",children:[F2(b8,{color:G,children:X?"▼":"▶"},void 0,!1,void 0,this),F2(b8,{children:" "},void 0,!1,void 0,this),F2(b8,{color:q,children:["Thinking",Z?"...":` (${Q} lines)`]},void 0,!0,void 0,this),!X&&!Z&&J&&F2(b8,{color:q,children:[" - ",J]},void 0,!0,void 0,this),F2(b8,{color:q,dimColor:!0,children:[" ","[Ctrl+T]"]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),X&&$&&F2(dZ,{marginLeft:2,marginTop:1,borderStyle:"round",borderColor:"gray",paddingX:1,paddingY:0,children:F2(b8,{color:q,children:$},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)});mZ.displayName="ThinkingBlock";import{Box as X9,Text as uZ}from"ink";import tW from"react";import{jsxDEV as f2}from"react/jsx-dev-runtime";var eW=tW.memo(({todos:$,visible:Z=!0,compact:X=!1})=>{let{colors:Y}=e0();if(!Z||$.length===0)return null;let Q={total:$.length,completed:$.filter((J)=>J.status==="completed").length,inProgress:$.filter((J)=>J.status==="in_progress").length};return f2(X9,{flexDirection:"column",borderStyle:"single",borderColor:Y.border.light,paddingX:1,paddingY:X?0:1,marginBottom:1,children:[f2(X9,{marginBottom:X?0:1,children:[f2(uZ,{dimColor:!0,children:"Tasks "},void 0,!1,void 0,this),f2(uZ,{color:Y.text.muted,children:[Q.completed,"/",Q.total]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),f2(X9,{flexDirection:"column",children:$.map((J,G)=>f2(KN,{todo:J,compact:X},J.id||G,!1,void 0,this))},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}),KN=tW.memo(({todo:$,compact:Z})=>{let X,Y=!1,Q;switch($.status){case"completed":X="✓",Y=!0,Q=$.content;break;case"in_progress":X="▶",Y=!1,Q=$.activeForm;break;case"pending":default:X="○",Y=!0,Q=$.content;break}return f2(X9,{paddingY:Z?0:0,children:f2(uZ,{dimColor:Y,children:[X," ",Q]},void 0,!0,void 0,this)},void 0,!1,void 0,this)});import{jsxDEV as L$}from"react/jsx-dev-runtime";var ZU=UN.memo(()=>{let $=k6(),Z=SK(),X=CK(),Y=kK(),Q=S2(),J=AK(),G=MK(),q=EK(),K=PK(),W=TK(),U=BK(),H=hK(),F=fK(),O=F8(),z=rW(),{stdout:_}=WN(),B=P2(),[L,w]=cZ(null),[R,D]=cZ([]),[V,I]=cZ(new Set),v=h2(F),N=h2(null),k=h2(0),m=h2(0),s=h2(new Set),S=h2(new Set),T=h2([]),c=h2(null);R4(()=>{if(v.current!==F){if(_)_.write(gZ.clearTerminal);B.incrementClearCount(),v.current=F}},[F,_,B]);let j=$,M=Y;R4(()=>{if(!Y||Q){c.current=null;return}if(c.current===Y)return;c.current=Y;let h=setTimeout(()=>{if(_)_.write(gZ.clearTerminal);s.current=new Set,S.current=new Set(j.filter((L0)=>L0.role==="tool").map((L0)=>L0.id)),N.current=null,k.current=0,m.current=0,T.current=[],D([]),I(new Set),B.incrementClearCount(),B.clearFinalizingStreamingMessageId()},50);return()=>clearTimeout(h)},[Y,Q,_,B,j]);let b=Z??Y;R4(()=>{N.current=null,k.current=0,m.current=0,s.current=new Set,S.current=new Set(j.filter((h)=>h.role==="tool").map((h)=>h.id)),T.current=[],D([]),I(new Set)},[U]),R4(()=>{if(!b)return;if(N.current===b)return;N.current=b,k.current=0,m.current=0,S.current=new Set(j.filter((h)=>h.role==="tool").map((h)=>h.id)),T.current=[],D([])},[b,j]),R4(()=>{if(!b)return;let h=T9(b);if(!h||h.length<=k.current)return;let L0=h.slice(k.current);k.current=h.length;let G0=L0,w0=T.current;if(w0.length>0)if(G0.some((Q$)=>Q$.type!=="empty"))G0=[...w0,...G0],T.current=[];else{T.current=[...w0,...G0];return}let Y$=G0.length;while(Y$>0&&G0[Y$-1].type==="empty")Y$-=1;if(Y$!==G0.length)T.current=G0.slice(Y$),G0=G0.slice(0,Y$);if(G0.length===0)return;let G$=m.current;m.current+=1;let r1=G$>0;I((Q$)=>{if(!b||Q$.has(b))return Q$;let Q0=new Set(Q$);return Q0.add(b),Q0}),D((Q$)=>[...Q$,L$(O2,{flexDirection:"column",children:L$(k2,{content:"",role:"assistant",terminalWidth:O,isPending:!1,hidePrefix:r1,noMargin:!0,blocksOverride:G0,renderCodeBlocksAsPlainText:!0},void 0,!1,void 0,this)},`streaming-${b}-${G$}`,!1,void 0,this)])},[b,X.version,O,U]),R4(()=>{if(!b)return;let h=S.current,L0=j.filter((G0)=>G0.role==="tool"&&!h.has(G0.id)&&!s.current.has(G0.id));if(L0.length===0)return;for(let G0 of L0)s.current.add(G0.id);D((G0)=>[...G0,...L0.map((w0)=>L$(O2,{flexDirection:"column",children:L$(k2,{content:w0.content,role:w0.role,terminalWidth:O,metadata:w0.metadata,isPending:!1,messageId:w0.id},void 0,!1,void 0,this)},`streaming-tool-${w0.id}`,!1,void 0,this))])},[b,j,O]);let n=Y9(()=>{if(!b)return null;let h=IX(b);if(!h||h.lines.length===0)return null;let G0=Math.max(1,z-8),w0=Math.max(0,h.lines.length-G0);return{visibleLines:h.lines.slice(-G0),hiddenLines:w0,mode:h.mode}},[b,X.version,z]),y=Y9(()=>{if(!b)return!1;return(T9(b)?.length??0)>0},[b,X.version]);R4(()=>{if(L===null&&j.length>H){if(w(j.length),_)_.write(gZ.clearTerminal);B.incrementClearCount()}},[j.length,H,L,_,B]);let u=Y9(()=>{return J.some((h)=>h.status==="pending"||h.status==="in_progress")},[J]),t=F?0:L??0,g=t,X0=Y9(()=>{let h=[];if(h.push(L$(oW,{},"header",!1,void 0,this)),g>0)h.push(L$(pZ,{collapsedCount:g},"collapsed-summary",!1,void 0,this));for(let L0=t;L0<j.length;L0++){let G0=j[L0];if(M&&G0.id===M)continue;if(G0.role==="tool"&&s.current.has(G0.id))continue;if(G0.role==="assistant"&&V.has(G0.id))continue;h.push(L$(O2,{flexDirection:"column",children:L$(k2,{content:G0.content,role:G0.role,terminalWidth:O,metadata:G0.metadata,isPending:!1,messageId:G0.id},void 0,!1,void 0,this)},G0.id,!1,void 0,this))}return h},[j,t,g,O,M,V]);return L$(O2,{flexDirection:"column",flexGrow:1,paddingX:2,children:L$(O2,{flexDirection:"column",flexGrow:1,children:[L$($U,{items:X0,children:(h)=>h},U,!1,void 0,this),K&&L$(O2,{marginBottom:1,children:L$(mZ,{content:K,isStreaming:Q,isExpanded:W},void 0,!1,void 0,this)},void 0,!1,void 0,this),R.length>0&&L$($U,{items:R,children:(h)=>h},`streaming-${U}`,!1,void 0,this),n&&L$(O2,{flexDirection:"column",children:L$(k2,{content:"",role:"assistant",terminalWidth:O,isPending:!0,hidePrefix:y,streamingLines:n.visibleLines,streamingHiddenLines:n.hiddenLines,streamingMode:n.mode},void 0,!1,void 0,this)},void 0,!1,void 0,this),G&&u&&L$(O2,{marginTop:1,children:L$(eW,{todos:J,visible:!0,compact:!1},void 0,!1,void 0,this)},void 0,!1,void 0,this),q.map((h,L0)=>L$(O2,{flexDirection:"column",children:L$(k2,{content:h.displayText,role:"user",terminalWidth:O},void 0,!1,void 0,this)},`pending-${L0}`,!1,void 0,this))]},void 0,!0,void 0,this)},void 0,!1,void 0,this)});c8();m8();n8();i8();C0();import{Box as Z0,Text as l,useFocus as G9,useFocusManager as HN,useInput as A8}from"ink";import XU from"ink-select-input";import FN from"ink-text-input";import{useEffect as YU,useState as x2}from"react";import{jsxDEV as E,Fragment as A3}from"react/jsx-dev-runtime";var QU=({isSelected:$})=>E(Z0,{marginRight:1,children:E(l,{color:$?"yellow":"gray",children:$?"▶":" "},void 0,!1,void 0,this)},void 0,!1,void 0,this),JU=({isSelected:$,label:Z})=>E(l,{bold:$,color:$?"yellow":void 0,children:Z},void 0,!1,void 0,this),J9={"openai-compatible":{icon:"⚡",name:"OpenAI Compatible",description:"兼容 OpenAI API 的服务 (千问/豆包/DeepSeek/Ollama等)",isOAuth:!1},anthropic:{icon:"\uD83E\uDD16",name:"Anthropic Claude",description:"Claude 官方 API",isOAuth:!1},gemini:{icon:"✨",name:"Google Gemini",description:"Gemini 官方 API",isOAuth:!1},antigravity:{icon:"\uD83D\uDE80",name:"Google Antigravity",description:"OAuth 登录使用 Claude/Gemini (需 Code Assist 订阅)",isOAuth:!0},copilot:{icon:"\uD83D\uDC19",name:"GitHub Copilot",description:"OAuth 登录使用 GPT/Claude/Gemini (需 Copilot 订阅)",isOAuth:!0},"azure-openai":{icon:"☁️",name:"Azure OpenAI",description:"微软 Azure OpenAI 服务",isOAuth:!1}};function ON($){let Z=J9[$];return`${Z.icon} ${Z.name}`}function lZ($){switch($){case"anthropic":return"https://api.anthropic.com";case"gemini":return"https://generativelanguage.googleapis.com/v1beta";case"antigravity":return"https://cloudcode-pa.googleapis.com";case"copilot":return"https://api.githubcopilot.com";default:return null}}var zN=({onSelect:$,onCancel:Z,initialProvider:X})=>{let{isFocused:Y}=G9({id:"provider-step"});A8((G,q)=>{if(q.escape)Z()},{isActive:Y});let Q=Object.keys(J9).map((G)=>{let q=J9[G];return{label:`${q.icon} ${q.name} - ${q.description}`,value:G}}),J=X?Math.max(0,Q.findIndex((G)=>G.value===X)):0;return E(Z0,{flexDirection:"column",marginBottom:1,children:[E(Z0,{marginBottom:1,children:E(l,{bold:!0,color:"blue",children:"\uD83D\uDCE1 Step 1: 选择 API 提供商"},void 0,!1,void 0,this)},void 0,!1,void 0,this),E(Z0,{marginBottom:1,children:E(l,{children:"根据您使用的 LLM 服务选择对应的 API 类型"},void 0,!1,void 0,this)},void 0,!1,void 0,this),E(Z0,{marginBottom:1,children:E(XU,{items:Q,onSelect:(G)=>$(G.value),indicatorComponent:QU,itemComponent:JU,initialIndex:J},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},Q9=({stepNumber:$,icon:Z,title:X,description:Y,hint:Q,examples:J,value:G,placeholder:q,mask:K,previousValue:W,onChange:U,onSubmit:H,onCancel:F})=>{return A8((O,z)=>{if(z.escape)F()},{isActive:!0}),E(Z0,{flexDirection:"column",marginBottom:1,children:[E(Z0,{marginBottom:1,children:E(l,{bold:!0,color:"blue",children:[Z," Step ",$,": ",X]},void 0,!0,void 0,this)},void 0,!1,void 0,this),E(Z0,{marginBottom:1,children:E(l,{children:Y},void 0,!1,void 0,this)},void 0,!1,void 0,this),W&&E(Z0,{marginBottom:1,children:E(l,{color:"green",children:["✓ ",W]},void 0,!0,void 0,this)},void 0,!1,void 0,this),Q&&E(Z0,{marginBottom:1,children:E(l,{dimColor:!0,children:Q},void 0,!1,void 0,this)},void 0,!1,void 0,this),J&&J.length>0&&E(A3,{children:[E(Z0,{marginBottom:1,children:E(l,{dimColor:!0,children:"常见示例:"},void 0,!1,void 0,this)},void 0,!1,void 0,this),E(Z0,{marginBottom:1,paddingLeft:2,children:E(l,{dimColor:!0,children:J.join(`
|
|
2822
|
+
`)},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),E(Z0,{children:[E(l,{bold:!0,color:"cyan",children:["▶"," "]},void 0,!0,void 0,this),E(FN,{value:G,onChange:U,onSubmit:H,placeholder:q,mask:K},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)},_N=({provider:$,onLogin:Z,onCancel:X,isLoggingIn:Y})=>{let{isFocused:Q}=G9({id:"oauth-login-step"});A8((G,q)=>{if(Y)return;if(G==="y"||G==="Y")Z();else if(G==="n"||G==="N"||q.escape)X()},{isActive:Q&&!Y});let J=$==="antigravity"?{name:"Google Antigravity",icon:"\uD83D\uDE80",loginCommand:"/login",description:"通过 Google OAuth 登录,使用 Claude/Gemini 模型"}:{name:"GitHub Copilot",icon:"\uD83D\uDC19",loginCommand:"/login copilot",description:"通过 GitHub Device Flow 登录,使用 GPT/Claude/Gemini 模型"};return E(Z0,{flexDirection:"column",marginBottom:1,children:[E(Z0,{marginBottom:1,children:E(l,{bold:!0,color:"yellow",children:[J.icon," 需要登录 ",J.name]},void 0,!0,void 0,this)},void 0,!1,void 0,this),E(Z0,{marginBottom:1,children:E(l,{children:J.description},void 0,!1,void 0,this)},void 0,!1,void 0,this),E(Z0,{marginBottom:1,paddingLeft:2,children:E(l,{dimColor:!0,children:["您也可以稍后手动执行 ",E(l,{bold:!0,children:J.loginCommand},void 0,!1,void 0,this)," 命令登录"]},void 0,!0,void 0,this)},void 0,!1,void 0,this),!Y&&E(Z0,{marginTop:1,children:E(l,{children:["现在登录? [",E(l,{bold:!0,color:"green",children:"Y"},void 0,!1,void 0,this),"/",E(l,{bold:!0,color:"red",children:"n"},void 0,!1,void 0,this),"]"]},void 0,!0,void 0,this)},void 0,!1,void 0,this),Y&&E(Z0,{marginTop:1,children:E(l,{color:"yellow",children:"⏳ 正在启动登录流程..."},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},BN=({provider:$,onSelect:Z,onCancel:X})=>{let{isFocused:Y}=G9({id:"oauth-model-step"}),[Q,J]=x2([]),[G,q]=x2(!0);YU(()=>{(async()=>{q(!0);try{if($==="copilot")J(Object.values(p3));else if(await M$.getInstance().getConfigType()==="gemini-cli")J(Object.values(k3));else J(Object.values(d8))}catch{J(Object.values(d8))}finally{q(!1)}})()},[$]),A8((U,H)=>{if(H.escape)X()},{isActive:Y});let K=Q.map((U)=>({label:`${U.name} - ${U.description}`,value:U.id})),W=$==="antigravity"?"Antigravity":"Copilot";if(G)return E(Z0,{flexDirection:"column",marginBottom:1,children:E(Z0,{marginBottom:1,children:E(l,{bold:!0,color:"blue",children:["\uD83E\uDD16 加载 ",W," 模型列表..."]},void 0,!0,void 0,this)},void 0,!1,void 0,this)},void 0,!1,void 0,this);return E(Z0,{flexDirection:"column",marginBottom:1,children:[E(Z0,{marginBottom:1,children:E(l,{bold:!0,color:"blue",children:["\uD83E\uDD16 选择 ",W," 模型"]},void 0,!0,void 0,this)},void 0,!1,void 0,this),E(Z0,{marginBottom:1,children:E(l,{children:"从可用模型列表中选择一个"},void 0,!1,void 0,this)},void 0,!1,void 0,this),E(Z0,{marginBottom:1,children:E(XU,{items:K,onSelect:(U)=>Z(U.value),indicatorComponent:QU,itemComponent:JU},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},LN=({mode:$,config:Z,isSaving:X,stepNumber:Y,onConfirm:Q,onBack:J,onCancel:G})=>{let{isFocused:q}=G9({id:"confirm-step"});return A8((K,W)=>{if(X)return;if(K==="y"||K==="Y")Q();else if(K==="n"||K==="N")J();else if(W.escape)G()},{isActive:q&&!X}),E(Z0,{flexDirection:"column",marginBottom:1,children:[E(Z0,{marginBottom:1,children:E(l,{bold:!0,color:$==="edit"?"yellow":"blue",children:$==="edit"?"\uD83D\uDCBE 确认修改":`✅ Step ${Y}: 确认配置`},void 0,!1,void 0,this)},void 0,!1,void 0,this),E(Z0,{marginBottom:1,children:E(l,{children:$==="edit"?"请确认修改内容,保存后将立即生效。":"请确认以下配置信息:"},void 0,!1,void 0,this)},void 0,!1,void 0,this),E(Z0,{flexDirection:"column",marginBottom:1,paddingLeft:2,children:[E(Z0,{marginBottom:1,children:[E(l,{dimColor:!0,children:"名称: "},void 0,!1,void 0,this),E(l,{bold:!0,color:"cyan",children:Z.name},void 0,!1,void 0,this)]},void 0,!0,void 0,this),E(Z0,{marginBottom:1,children:[E(l,{dimColor:!0,children:"Provider: "},void 0,!1,void 0,this),E(l,{bold:!0,color:"cyan",children:ON(Z.provider)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),E(Z0,{marginBottom:1,children:[E(l,{dimColor:!0,children:"Base URL: "},void 0,!1,void 0,this),E(l,{bold:!0,color:"blue",children:Z.baseUrl},void 0,!1,void 0,this)]},void 0,!0,void 0,this),E(Z0,{marginBottom:1,children:[E(l,{dimColor:!0,children:"API Key: "},void 0,!1,void 0,this),E(l,{bold:!0,color:"yellow",children:Z.apiKey==="oauth"?"\uD83D\uDD10 OAuth 认证(使用 /login 登录)":E(A3,{children:[Z.apiKey?.slice(0,8),"*".repeat(Math.min(32,(Z.apiKey?.length||0)-8))]},void 0,!0,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),E(Z0,{children:[E(l,{dimColor:!0,children:"Model: "},void 0,!1,void 0,this),E(l,{bold:!0,color:"cyan",children:Z.model},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),!X&&E(Z0,{marginTop:1,children:E(l,{children:[$==="edit"?"保存修改? ":"确认保存配置? ","[",E(l,{bold:!0,color:"green",children:"Y"},void 0,!1,void 0,this),"/",E(l,{bold:!0,color:"red",children:"n"},void 0,!1,void 0,this),"]"]},void 0,!0,void 0,this)},void 0,!1,void 0,this),X&&E(Z0,{children:E(l,{color:"yellow",children:"⏳ 正在保存配置到 ~/.blade/config.json..."},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},iZ=({mode:$,initialConfig:Z,modelId:X,onComplete:Y,onCancel:Q})=>{let J=$==="edit",[G,q]=x2("provider"),[K,W]=x2(()=>J&&Z?{...Z}:{}),[U,H]=x2(""),[F,O]=x2(!1),[z,_]=x2(!1),[B,L]=x2(null),w=X$(!1);A8((y,u)=>{if(u.ctrl&&y==="c"||u.meta&&y==="c")if($==="setup")w();else Q()},{isActive:!0});let{focus:R}=HN();YU(()=>{if(G==="provider")R("provider-step");else if(G==="confirm")R("confirm-step");else if(G==="oauthLogin")R("oauth-login-step");else if(G==="oauthModelSelect")R("oauth-model-step")},[G,R]);let D=()=>{if(!U.trim()){L("配置名称不能为空");return}W({...K,name:U}),H(""),L(null),q("confirm")},V=async(y)=>{if(W({...K,provider:y}),I(y)){let g=y==="antigravity"?M$.getInstance():C$.getInstance();try{if(await g.isLoggedIn())q("oauthModelSelect");else q("oauthLogin")}catch{q("oauthLogin")}return}let u=lZ(y),t=J?K.baseUrl??Z?.baseUrl??"":u??"";H(t),q("baseUrl")},I=(y)=>{return J9[y].isOAuth},v=()=>{if(!U.trim()){L("Base URL 不能为空");return}try{new URL(U)}catch{L("请输入有效的 URL (例如: https://api.openai.com/v1)");return}if(W({...K,baseUrl:U}),L(null),I(K.provider)){W((u)=>({...u,baseUrl:U,apiKey:"oauth"}));let y=J?K.model??Z?.model??"":"";H(y),q("model")}else{let y=J?K.apiKey??Z?.apiKey??"":"";H(y),q("apiKey")}},N=()=>{if(!U.trim()){L("API Key 不能为空");return}W({...K,apiKey:U});let y=J?K.model??Z?.model??"":"";H(y),L(null),q("model")},k=()=>{if(!U.trim()){L("Model 不能为空");return}W({...K,model:U});let y=J?K.name??Z?.name??"":"";H(y),L(null),q("name")},m=async()=>{let u=K.provider==="antigravity"?M$.getInstance():C$.getInstance();_(!0),L(null);try{await u.login(),q("oauthModelSelect")}catch(t){L(t instanceof Error?t.message:"登录失败")}finally{_(!1)}},s=(y)=>{let u=K.provider,t=lZ(u)||"";W({...K,baseUrl:t,apiKey:"oauth",model:y}),H(""),q("name")},S=async()=>{O(!0),L(null);try{let y={name:K.name,provider:K.provider,baseUrl:K.baseUrl,apiKey:K.apiKey,model:K.model};if($==="setup")Y(y);else if($==="add"){let u=await x0().addModel(y);await x0().setCurrentModel(u.id),Y(y)}else{if(!X)throw Error("未提供模型 ID,无法编辑");await x0().updateModel(X,y),Y(y)}}catch(y){L(y instanceof Error?y.message:"配置失败"),O(!1)}},T=()=>{switch(L(null),H(""),G){case"provider":Q();break;case"baseUrl":q("provider");break;case"apiKey":H(K.baseUrl||""),q("baseUrl");break;case"model":q("apiKey");break;case"oauthLogin":q("provider");break;case"oauthModelSelect":q("provider");break;case"name":if(I(K.provider))q("oauthModelSelect");else H(K.model||""),q("model");break;case"confirm":H(K.name||""),q("name");break}},c=K.provider&&I(K.provider),j=c?4:6,M=(()=>{if(G==="provider")return 1;if(c){if(G==="oauthLogin"||G==="oauthModelSelect")return 2;if(G==="name")return 3;return 4}if(G==="baseUrl")return 2;if(G==="apiKey")return 3;if(G==="model")return 4;if(G==="name")return 5;return 6})(),b=Math.floor((M-1)/(j-1)*40);return E(Z0,{...$==="setup"?{flexDirection:"column",padding:1}:$==="add"?{flexDirection:"column",borderStyle:"round",borderColor:"blue",padding:1}:{flexDirection:"column",borderStyle:"round",borderColor:"yellow",padding:1},children:[$==="setup"?E(A3,{children:[E(Z0,{marginBottom:1,children:E(l,{bold:!0,color:"blue",children:"\uD83D\uDE80 欢迎使用 Blade Code"},void 0,!1,void 0,this)},void 0,!1,void 0,this),E(Z0,{marginBottom:1,children:E(l,{children:"AI 驱动的代码助手 - 让我们开始配置您的助手"},void 0,!1,void 0,this)},void 0,!1,void 0,this),E(Z0,{marginBottom:1,children:[E(l,{bold:!0,color:"blue",children:"█".repeat(b)},void 0,!1,void 0,this),E(l,{dimColor:!0,children:"░".repeat(40-b)},void 0,!1,void 0,this),E(l,{children:" "},void 0,!1,void 0,this),E(l,{bold:!0,color:"cyan",children:[M,"/",j]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),E(Z0,{marginBottom:1,children:E(l,{dimColor:!0,children:"━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this):$==="add"?E(A3,{children:[E(Z0,{justifyContent:"center",marginBottom:1,children:E(l,{bold:!0,color:"blue",children:"添加新模型配置"},void 0,!1,void 0,this)},void 0,!1,void 0,this),E(Z0,{marginBottom:1,children:E(l,{children:["步骤: ",M,"/",j]},void 0,!0,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this):E(A3,{children:[E(Z0,{justifyContent:"center",marginBottom:1,children:E(l,{bold:!0,color:"yellow",children:"编辑模型配置"},void 0,!1,void 0,this)},void 0,!1,void 0,this),E(Z0,{marginBottom:1,children:E(l,{children:["步骤: ",M,"/",j]},void 0,!0,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),G==="name"&&E(Q9,{stepNumber:5,icon:"\uD83D\uDCDD",title:"配置名称",description:"给这个模型配置起一个易于识别的名称(可选,用于区分多个配置)",value:U,placeholder:"例如: 千问工作账号",onChange:H,onSubmit:D,onCancel:Q},void 0,!1,void 0,this),G==="provider"&&E(zN,{onSelect:V,onCancel:Q,initialProvider:K.provider},void 0,!1,void 0,this),G==="oauthLogin"&&K.provider&&I(K.provider)&&E(_N,{provider:K.provider,onLogin:m,onCancel:Q,isLoggingIn:z},void 0,!1,void 0,this),G==="oauthModelSelect"&&K.provider&&I(K.provider)&&E(BN,{provider:K.provider,onSelect:s,onCancel:Q},void 0,!1,void 0,this),G==="baseUrl"&&E(Q9,{stepNumber:2,icon:"\uD83C\uDF10",title:"配置 Base URL",description:"输入您的 API 端点地址(完整的 URL 包含协议)",hint:K.provider&&lZ(K.provider)?"\uD83D\uDCA1 已预填充官方 URL,直接回车使用。如需代理服务(如 OpenRouter),请修改。":void 0,examples:["• OpenAI: https://api.openai.com/v1","• Anthropic: https://api.anthropic.com","• Gemini: https://generativelanguage.googleapis.com/v1beta","• Azure: https://{resource}.openai.azure.com","• 代理: https://openrouter.ai/api/v1"],value:U,placeholder:"https://api.example.com/v1",onChange:H,onSubmit:v,onCancel:Q},void 0,!1,void 0,this),G==="apiKey"&&E(Q9,{stepNumber:3,icon:"\uD83D\uDD11",title:"输入 API Key",description:"您的 API 密钥将被安全存储在 ~/.blade/config.json (权限 600)",hint:"\uD83D\uDCA1 提示: 输入时字符会被隐藏,支持粘贴 (Ctrl+V / Cmd+V)",previousValue:K.baseUrl?`✓ Base URL: ${K.baseUrl}`:void 0,value:U,placeholder:"sk-...",mask:"*",onChange:H,onSubmit:N,onCancel:Q},void 0,!1,void 0,this),G==="model"&&E(Q9,{stepNumber:4,icon:"\uD83E\uDD16",title:"选择模型",description:"输入您想使用的模型名称(请参考您的 API 提供商文档)",examples:K.provider==="antigravity"?["• Claude: claude-sonnet-4-5, claude-opus-4-5-thinking","• Gemini: gemini-3-pro-high, gemini-3-pro-low","• GPT-OSS: gpt-oss-120b-medium"]:["• OpenAI: gpt-4o, gpt-4o-mini, o1-preview","• Claude: claude-sonnet-4-20250514, claude-opus-4-20250514","• Gemini: gemini-2.5-pro, gemini-2.5-flash","• Azure: {deployment-name}","• 千问: qwen3-max, qwen3-235b, qwen3-32b","• DeepSeek: deepseek-v3.1, deepseek-r1-0528"],value:U,placeholder:"例如: gpt-5",onChange:H,onSubmit:k,onCancel:Q},void 0,!1,void 0,this),G==="confirm"&&E(LN,{mode:$,config:K,isSaving:F,stepNumber:j,onConfirm:S,onBack:T,onCancel:Q},void 0,!1,void 0,this),B&&E(Z0,{marginTop:1,borderStyle:"round",borderColor:"red",paddingX:1,children:E(l,{color:"red",children:["❌ ",B]},void 0,!0,void 0,this)},void 0,!1,void 0,this),E(Z0,{marginTop:1,children:E(l,{dimColor:!0,children:"━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"},void 0,!1,void 0,this)},void 0,!1,void 0,this),!F&&!z&&G==="provider"&&E(Z0,{marginTop:1,children:E(l,{dimColor:!0,children:["\uD83D\uDCA1 使用 ",E(l,{bold:!0,children:"↑/↓"},void 0,!1,void 0,this)," 键选择,",E(l,{bold:!0,children:"Enter"},void 0,!1,void 0,this)," 确认,",E(l,{bold:!0,children:"Esc"},void 0,!1,void 0,this)," 取消"]},void 0,!0,void 0,this)},void 0,!1,void 0,this),!F&&!z&&G==="oauthModelSelect"&&E(Z0,{marginTop:1,children:E(l,{dimColor:!0,children:["\uD83D\uDCA1 使用 ",E(l,{bold:!0,children:"↑/↓"},void 0,!1,void 0,this)," 键选择模型,",E(l,{bold:!0,children:"Enter"},void 0,!1,void 0,this)," 确认,",E(l,{bold:!0,children:"Esc"},void 0,!1,void 0,this)," 返回"]},void 0,!0,void 0,this)},void 0,!1,void 0,this),!F&&!z&&G==="oauthLogin"&&E(Z0,{marginTop:1,children:E(l,{dimColor:!0,children:["\uD83D\uDCA1 按"," ",E(l,{bold:!0,color:"green",children:"Y"},void 0,!1,void 0,this)," ","登录,",E(l,{bold:!0,color:"red",children:"N"},void 0,!1,void 0,this)," ","返回,",E(l,{bold:!0,children:"Esc"},void 0,!1,void 0,this)," 取消"]},void 0,!0,void 0,this)},void 0,!1,void 0,this),!F&&!z&&G!=="confirm"&&G!=="provider"&&G!=="oauthLogin"&&G!=="oauthModelSelect"&&E(Z0,{marginTop:1,children:E(l,{dimColor:!0,children:["\uD83D\uDCA1 输入完成后按 ",E(l,{bold:!0,children:"Enter"},void 0,!1,void 0,this),",",E(l,{bold:!0,children:"Ctrl+C"},void 0,!1,void 0,this)," 退出"]},void 0,!0,void 0,this)},void 0,!1,void 0,this),!F&&!z&&G==="confirm"&&E(Z0,{marginTop:1,children:E(l,{dimColor:!0,children:["\uD83D\uDCA1 按"," ",E(l,{bold:!0,color:"green",children:"Y"},void 0,!1,void 0,this)," ","保存,",E(l,{bold:!0,color:"red",children:"N"},void 0,!1,void 0,this)," ","返回修改,",E(l,{bold:!0,children:"Esc"},void 0,!1,void 0,this)," 取消"]},void 0,!0,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)};C3();import{useMemoizedFn as q9,useMount as wN}from"ahooks";import{Box as X1,Text as T0,useFocus as NN,useFocusManager as bN,useInput as AN}from"ink";import RN from"ink-select-input";import{memo as VN,useMemo as DN,useState as K9}from"react";C0();import{jsxDEV as H0}from"react/jsx-dev-runtime";function MN($){switch($){case"openai-compatible":return"⚡ OpenAI Compatible";case"anthropic":return"\uD83E\uDD16 Anthropic Claude";case"gemini":return"✨ Google Gemini";case"azure-openai":return"☁️ Azure OpenAI";default:return $}}var jN=({isSelected:$})=>H0(X1,{marginRight:1,children:H0(T0,{color:$?"yellow":"gray",children:$?"▶":" "},void 0,!1,void 0,this)},void 0,!1,void 0,this),IN=({isSelected:$,label:Z})=>H0(T0,{bold:$,color:$?"yellow":void 0,children:Z},void 0,!1,void 0,this),GU=VN(({onClose:$,onEdit:Z})=>{let X=jK(),Y=IK()??"",{isFocused:Q}=NN({id:"model-selector"}),J=bN(),[G,q]=K9(""),[K,W]=K9(!1),[U,H]=K9(null),F=X$(!1),[O]=K9(()=>{let I=process.stdout?.columns||80;return Math.max(20,I-8)});wN(()=>{if(J?.focus("model-selector"),X.length>0)q(X[0].id)}),AN((I,v)=>{if(K)return;if(v.ctrl&&I==="c"||v.meta&&I==="c"){F();return}if(v.escape){$();return}if(!Q)return;if(I==="d"||I==="D"){_();return}if((I==="e"||I==="E")&&Z)B()},{isActive:!0});let z=q9(async(I)=>{if(K)return;let v=I.value;if(v===Y){$();return}W(!0),H(null);try{await x0().setCurrentModel(v),$()}catch(N){H(N.message),W(!1)}}),_=q9(async()=>{if(K||G===Y)return;W(!0),H(null);try{if(await x0().removeModel(G),X.length<=1)$()}catch(I){H(I.message)}finally{W(!1)}}),B=q9(()=>{if(K||!Z)return;let I=X.find((v)=>v.id===G);if(!I)return;Z(I)}),L=q9((I)=>{q(I.value)}),w=DN(()=>{return X.find((I)=>I.id===G)},[X,G]),R=X.map((I)=>{let v=I.id===Y?" (当前)":"";return{label:I.name+v,value:I.id}}),D=G===Y;return H0(X1,{flexDirection:"column",borderStyle:"round",borderColor:"gray",padding:1,width:"100%",children:[H0(X1,{flexDirection:"row",justifyContent:"space-between",marginBottom:1,children:[H0(T0,{bold:!0,color:"cyan",children:"模型管理"},void 0,!1,void 0,this),H0(T0,{dimColor:!0,children:[K?"⏳ 处理中...":D?"Enter=关闭 • E=编辑 • Esc=取消":"Enter=切换 • D=删除 • E=编辑 • Esc=取消"," • Ctrl+C=退出"]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),H0(X1,{flexDirection:"row",children:[H0(X1,{flexDirection:"column",flexGrow:2,marginRight:2,borderStyle:"single",borderColor:"gray",padding:1,children:[H0(T0,{dimColor:!0,children:["已配置模型 (",X.length,")"]},void 0,!0,void 0,this),H0(X1,{marginTop:1,children:H0(RN,{items:R,onSelect:z,onHighlight:L,indicatorComponent:jN,itemComponent:IN},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),H0(X1,{flexDirection:"column",flexGrow:3,borderStyle:"single",borderColor:"gray",padding:1,children:[H0(T0,{dimColor:!0,children:"模型详情"},void 0,!1,void 0,this),H0(X1,{marginY:1,children:H0(T0,{color:D?"green":"yellow",children:D?"● 当前使用":"● 可切换"},void 0,!1,void 0,this)},void 0,!1,void 0,this),w?H0(X1,{flexDirection:"column",children:[H0(T0,{children:[H0(T0,{dimColor:!0,children:"名称: "},void 0,!1,void 0,this),H0(T0,{bold:!0,color:"cyan",children:w.name},void 0,!1,void 0,this),q7(w)&&H0(T0,{color:"green",children:" (内置免费)"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),H0(T0,{children:[H0(T0,{dimColor:!0,children:"Provider: "},void 0,!1,void 0,this),H0(T0,{bold:!0,children:MN(w.provider)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),H0(T0,{children:[H0(T0,{dimColor:!0,children:"Model: "},void 0,!1,void 0,this),H0(T0,{bold:!0,children:w.model},void 0,!1,void 0,this)]},void 0,!0,void 0,this),H0(T0,{children:[H0(T0,{dimColor:!0,children:"Base URL: "},void 0,!1,void 0,this),H0(T0,{color:"blueBright",children:w.baseUrl},void 0,!1,void 0,this)]},void 0,!0,void 0,this),w.temperature!==void 0&&H0(T0,{children:[H0(T0,{dimColor:!0,children:"Temperature: "},void 0,!1,void 0,this),H0(T0,{children:w.temperature},void 0,!1,void 0,this)]},void 0,!0,void 0,this),w.maxContextTokens!==void 0&&H0(T0,{children:[H0(T0,{dimColor:!0,children:"Context Window: "},void 0,!1,void 0,this),H0(T0,{children:w.maxContextTokens},void 0,!1,void 0,this)]},void 0,!0,void 0,this),q7(w)&&H0(X1,{marginTop:1,children:H0(T0,{color:"green",dimColor:!0,children:"\uD83D\uDCA1 此模型由 Blade 提供免费额度"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this):H0(T0,{dimColor:!0,children:"请选择一个模型查看详情"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),U&&H0(X1,{marginTop:1,children:H0(T0,{color:"red",children:["❌ ",U]},void 0,!0,void 0,this)},void 0,!1,void 0,this),H0(X1,{justifyContent:"center",marginTop:1,children:H0(T0,{dimColor:!0,children:"─".repeat(O)},void 0,!1,void 0,this)},void 0,!1,void 0,this),H0(X1,{justifyContent:"center",children:H0(T0,{dimColor:!0,children:"提示:D=删除 • E=编辑 • ↑↓=移动 • Enter/ESC=确认"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)});import{useMemoizedFn as R3}from"ahooks";import{promises as UU}from"fs";import{Box as Y1,Text as $$,useInput as yN}from"ink";import qU from"ink-select-input";import vN from"ink-text-input";import EN from"os";import W9 from"path";import{useEffect as PN,useMemo as U9,useRef as TN,useState as p2}from"react";C0();import{jsxDEV as _0}from"react/jsx-dev-runtime";var V3=[{key:"allow",label:"Allow"},{key:"ask",label:"Ask"},{key:"deny",label:"Deny"},{key:"info",label:"Info"}],SN={allow:"Add a new rule...",ask:"Add a new rule...",deny:"Add a new rule..."},CN={allow:"Allow permission rules",ask:"Ask permission rules",deny:"Deny permission rules"},KU={project:"[项目共享配置]",global:"[用户全局配置]",local:"[本地配置]"},kN=["project","global","local"],fN={allow:[],ask:[],deny:[]},hN={localExists:!1,projectExists:!1,globalExists:!1},WU={allow:[],ask:[],deny:[]};function xN($){let Z=(Y)=>Array.isArray(Y)?Y.filter((Q)=>typeof Q==="string"):[],X=$?.permissions??{};return{allow:Z(X?.allow),ask:Z(X?.ask),deny:Z(X?.deny)}}async function pN($){try{let Z=await UU.readFile($,"utf-8"),X=JSON.parse(Z);return{exists:!0,raw:X,permissions:xN(X)}}catch(Z){if(Z.code==="ENOENT")return{exists:!1,raw:{},permissions:{...WU}};return console.warn(`[PermissionsManager] Failed to read ${$}:`,Z),{exists:!0,raw:{},permissions:{...WU}}}}function dN($,Z){let X=$.padEnd(32," "),Y=Z==="local"?`${KU[Z]} ← 可删除`:KU[Z];return`${X} ${Y}`}var HU=({onClose:$})=>{let X=o$()==="permissions-manager",Y=X$(!1),[Q,J]=p2(0),G=V3[Q].key,[q,K]=p2(fN),[W,U]=p2(hN),[H,F]=p2(!0),[O,z]=p2("list"),[_,B]=p2(""),[L,w]=p2(null),[R,D]=p2(null),V=TN(!1),I=U9(()=>W9.join(process.cwd(),".blade","settings.local.json"),[]),v=U9(()=>W9.join(process.cwd(),".blade","settings.json"),[]),N=U9(()=>W9.join(EN.homedir(),".blade","settings.json"),[]),k=R3(async()=>{F(!0);let g=[{source:"local",path:I},{source:"project",path:v},{source:"global",path:N}],X0=await Promise.all(g.map(async({source:w0,path:Y$})=>{let G$=await pN(Y$);return{source:w0,path:Y$,...G$}})),h={localExists:X0.find((w0)=>w0.source==="local")?.exists??!1,projectExists:X0.find((w0)=>w0.source==="project")?.exists??!1,globalExists:X0.find((w0)=>w0.source==="global")?.exists??!1};U(h);let L0={allow:[],ask:[],deny:[]},G0=Object.fromEntries(X0.map((w0)=>[w0.source,w0]));["allow","ask","deny"].forEach((w0)=>{kN.forEach((Y$)=>{(G0[Y$]?.permissions[w0]??[]).forEach((r1,Q$)=>{let Q0={key:`${Y$}:${Q$}:${r1}`,rule:r1,source:Y$};L0[w0].push(Q0)})})}),K(L0),F(!1)});PN(()=>{k()},[k]);let m=R3(async(g,X0)=>{try{let h=W9.join(process.cwd(),".blade","settings.local.json"),L0={allow:[],ask:[],deny:[]};try{let w0=await UU.readFile(h,"utf-8"),G$=JSON.parse(w0).permissions||{};L0={allow:Array.isArray(G$.allow)?G$.allow:[],ask:Array.isArray(G$.ask)?G$.ask:[],deny:Array.isArray(G$.deny)?G$.deny:[]}}catch(w0){}let G0=X0(L0);await x0().updateConfig({permissions:G0},{scope:"local",immediate:!0}),await k()}catch(h){throw console.error("[PermissionsManager] 修改权限规则失败:",h),h}});yN((g,X0)=>{if(X0.ctrl&&g==="c"||X0.meta&&g==="c"){Y();return}if(O==="locked"){if(V.current){V.current=!1;return}z("list"),w(null),D(null);return}if(X0.escape){if(O==="list"||G==="info")$();else z("list"),B(""),w(null),D(null);return}if(O==="list"){if(X0.tab&&X0.shift)J((h)=>(h-1+V3.length)%V3.length);else if(X0.tab)J((h)=>(h+1)%V3.length);else if(g?.toLowerCase()==="q")$()}},{isActive:X});let s=R3((g)=>{let X0=g.value;if(G==="info")return;if(X0.type==="add"){z("add"),B(""),D(null);return}if(X0.entry.source!=="local"){z("locked"),V.current=!0,w({tab:G,entry:X0.entry}),D({type:"error",text:X0.entry.source==="project"?"此规则定义在项目共享配置中,无法在此删除。":"此规则来自用户全局配置,无法在此删除。"});return}z("confirm-delete"),w({tab:G,entry:X0.entry}),D(null)}),S=R3(async()=>{if(G==="info")return;let g=_.trim();if(!g){D({type:"error",text:"Permission rule 不能为空"});return}if(q[G].map((h)=>h.rule).includes(g)){D({type:"error",text:"该规则已存在"});return}try{await m(G,(h)=>{let L0={allow:[...h.allow],ask:[...h.ask],deny:[...h.deny]};return L0[G]=[...new Set([...h[G],g])],L0}),z("list"),B(""),D({type:"success",text:"已添加本地权限规则"})}catch(h){D({type:"error",text:`保存失败: ${h instanceof Error?h.message:"未知错误"}`})}}),T=R3(async()=>{if(!L)return;let{tab:g,entry:X0}=L;try{await m(g,(h)=>{let L0={allow:[...h.allow],ask:[...h.ask],deny:[...h.deny]};return L0[g]=h[g].filter((G0)=>G0!==X0.rule),L0}),z("list"),w(null),D({type:"success",text:"已删除本地权限规则"})}catch(h){D({type:"error",text:`删除失败: ${h instanceof Error?h.message:"未知错误"}`})}}),c=U9(()=>{if(G==="info")return[];let g=G;return[{key:"add-new-rule",label:`› ${SN[g]}`,value:{type:"add"}},...q[g].map((h)=>({key:h.key,label:dN(h.rule,h.source),value:{type:"rule",entry:h}}))]},[G,q]),j=()=>_0(Y1,{marginBottom:1,children:V3.map((g,X0)=>_0(Y1,{marginRight:2,children:_0($$,{color:X0===Q?"yellow":"gray",children:["[",g.label,"]"]},void 0,!0,void 0,this)},g.key,!1,void 0,this))},void 0,!1,void 0,this),M=()=>_0(Y1,{flexDirection:"column",gap:1,children:[_0($$,{children:"配置文件优先级(从高到低):"},void 0,!1,void 0,this),_0(Y1,{flexDirection:"column",marginLeft:2,children:[_0($$,{children:["1. .blade/settings.local.json (本地配置,不提交 Git)"," ",W.localExists?"✓ 存在":"✗ 不存在"]},void 0,!0,void 0,this),_0($$,{children:["2. .blade/settings.json (项目配置,提交 Git)"," ",W.projectExists?"✓ 存在":"✗ 不存在"]},void 0,!0,void 0,this),_0($$,{children:["3. ~/.blade/settings.json (用户全局配置)"," ",W.globalExists?"✓ 存在":"✗ 不存在"]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),_0($$,{children:"说明:"},void 0,!1,void 0,this),_0(Y1,{flexDirection:"column",marginLeft:2,children:[_0($$,{children:"- /permissions 命令只管理本地配置 (.blade/settings.local.json)"},void 0,!1,void 0,this),_0($$,{children:"- 修改全局或项目配置请直接编辑对应文件"},void 0,!1,void 0,this),_0($$,{children:"- 本地配置不会提交到 Git"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),b=(g)=>_0(Y1,{flexDirection:"column",gap:1,children:[_0($$,{bold:!0,children:CN[g]},void 0,!1,void 0,this),_0($$,{children:"Permission rules are a tool name, optionally followed by a specifier in parentheses."},void 0,!1,void 0,this),_0($$,{color:"gray",children:"例如: WebFetch 或 Bash(ls:*)"},void 0,!1,void 0,this),_0(Y1,{marginTop:1,children:_0(vN,{value:_,onChange:B,onSubmit:S},void 0,!1,void 0,this)},void 0,!1,void 0,this),_0($$,{color:"gray",children:"Enter 提交 · Esc 取消"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),n=(g,X0)=>_0(Y1,{flexDirection:"column",gap:1,children:[_0($$,{bold:!0,children:["Delete ",g," permission rule?"]},void 0,!0,void 0,this),_0($$,{children:X0.rule},void 0,!1,void 0,this),_0($$,{color:"gray",children:"From project local settings"},void 0,!1,void 0,this),_0($$,{children:"Are you sure you want to delete this permission rule?"},void 0,!1,void 0,this),_0(qU,{items:[{label:"Yes",value:"yes"},{label:"No",value:"no"}],onSelect:(h)=>{if(h.value==="yes")T();else z("list"),w(null)}},void 0,!1,void 0,this)]},void 0,!0,void 0,this),y=(g)=>_0(Y1,{flexDirection:"column",gap:1,children:[_0($$,{bold:!0,children:"Cannot delete this rule"},void 0,!1,void 0,this),_0($$,{children:g.rule},void 0,!1,void 0,this),_0($$,{color:"gray",children:g.source==="project"?"This rule is defined in .blade/settings.json. 请手动编辑该文件以移除规则。":"This rule is defined in ~/.blade/settings.json. 请手动编辑该文件以移除规则。"},void 0,!1,void 0,this),_0($$,{color:"gray",children:"按任意键继续"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),u=(g)=>_0(qU,{items:c,isFocused:O==="list",onSelect:s},void 0,!1,void 0,this),t=()=>{if(H)return _0($$,{children:"加载中..."},void 0,!1,void 0,this);if(G==="info")return M();if(O==="add")return b(G);if(O==="confirm-delete"&&L)return n(L.tab,L.entry);if(O==="locked"&&L)return y(L.entry);return u(G)};return _0(Y1,{flexDirection:"column",borderStyle:"round",borderColor:X?"cyan":"gray",padding:1,width:80,children:[_0($$,{color:"cyan",bold:!0,children:"⚙️ 权限管理器"},void 0,!1,void 0,this),j(),_0(Y1,{flexDirection:"column",gap:1,children:t()},void 0,!1,void 0,this),R&&_0(Y1,{marginTop:1,children:_0($$,{color:R.type==="success"?"green":"red",children:R.text},void 0,!1,void 0,this)},void 0,!1,void 0,this),_0(Y1,{marginTop:1,children:_0($$,{color:"gray",children:"Tab 切换视图 · Esc 关闭 · Q 退出"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)};X8();import{Box as t0,Text as b0,useInput as mN}from"ink";import{jsxDEV as r}from"react/jsx-dev-runtime";function FU({onCancel:$}){let Z=a$(),X=Z.getAll(),Y=Z.getBySource(),Q=Z.getStats(),J=X$(!1,$);if(mN((G,q)=>{if(q.escape)$?.();else if(q.ctrl&&G==="c"||q.meta&&G==="c")J()}),X.length===0)return r(t0,{flexDirection:"column",paddingY:1,children:[r(t0,{marginBottom:1,children:r(b0,{bold:!0,color:"cyan",children:"\uD83D\uDD0C 插件管理器"},void 0,!1,void 0,this)},void 0,!1,void 0,this),r(t0,{paddingLeft:2,children:r(b0,{color:"gray",children:"没有已加载的插件"},void 0,!1,void 0,this)},void 0,!1,void 0,this),r(t0,{marginTop:1,paddingLeft:2,flexDirection:"column",children:[r(b0,{color:"gray",children:"插件目录位置:"},void 0,!1,void 0,this),r(b0,{color:"gray",dimColor:!0,children:[" ","• ~/.blade/plugins/ - 用户级插件"]},void 0,!0,void 0,this),r(b0,{color:"gray",dimColor:!0,children:[" ","• .blade/plugins/ - 项目级插件"]},void 0,!0,void 0,this),r(b0,{color:"gray",dimColor:!0,children:[" ","• --plugin-dir - CLI 指定的插件"]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),r(t0,{marginTop:1,paddingLeft:2,children:r(b0,{color:"gray",children:"使用 /plugins install <url> 安装新插件"},void 0,!1,void 0,this)},void 0,!1,void 0,this),r(t0,{marginTop:1,children:r(b0,{dimColor:!0,children:"按 ESC 返回菜单"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this);return r(t0,{flexDirection:"column",paddingY:1,children:[r(t0,{marginBottom:1,children:[r(b0,{bold:!0,color:"cyan",children:"\uD83D\uDD0C 插件管理器"},void 0,!1,void 0,this),r(b0,{color:"gray",children:[" (共 ",Q.total," 个插件)"]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),r(t0,{paddingLeft:2,marginBottom:1,children:r(b0,{color:"gray",children:["启用: ",Q.active," | 禁用: ",Q.inactive," | 命令: ",Q.commands," | 技能:"," ",Q.skills," | 代理: ",Q.agents]},void 0,!0,void 0,this)},void 0,!1,void 0,this),Y.cli.length>0&&r(t0,{flexDirection:"column",marginBottom:1,children:[r(t0,{paddingLeft:1,children:[r(b0,{bold:!0,color:"magenta",children:"CLI 指定"},void 0,!1,void 0,this),r(b0,{color:"gray",children:" (--plugin-dir)"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),Y.cli.map((G)=>{let q=G.status==="active"?"✅":"⏸️";return r(t0,{flexDirection:"column",paddingLeft:2,children:[r(b0,{children:[r(b0,{bold:!0,color:"green",children:[q," ",G.manifest.name]},void 0,!0,void 0,this),r(b0,{color:"gray",children:[" v",G.manifest.version]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),r(t0,{paddingLeft:2,children:r(b0,{color:"gray",children:G.manifest.description},void 0,!1,void 0,this)},void 0,!1,void 0,this),G.commands.length>0&&r(t0,{paddingLeft:2,children:r(b0,{color:"blue",children:["命令:"," ",G.commands.map((K)=>`/${K.namespacedName}`).join(", ")]},void 0,!0,void 0,this)},void 0,!1,void 0,this)]},G.manifest.name,!0,void 0,this)})]},void 0,!0,void 0,this),Y.project.length>0&&r(t0,{flexDirection:"column",marginBottom:1,children:[r(t0,{paddingLeft:1,children:[r(b0,{bold:!0,color:"yellow",children:"项目级"},void 0,!1,void 0,this),r(b0,{color:"gray",children:" (.blade/plugins/)"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),Y.project.map((G)=>{let q=G.status==="active"?"✅":"⏸️";return r(t0,{flexDirection:"column",paddingLeft:2,children:[r(b0,{children:[r(b0,{bold:!0,color:"green",children:[q," ",G.manifest.name]},void 0,!0,void 0,this),r(b0,{color:"gray",children:[" v",G.manifest.version]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),r(t0,{paddingLeft:2,children:r(b0,{color:"gray",children:G.manifest.description},void 0,!1,void 0,this)},void 0,!1,void 0,this),G.commands.length>0&&r(t0,{paddingLeft:2,children:r(b0,{color:"blue",children:["命令:"," ",G.commands.map((K)=>`/${K.namespacedName}`).join(", ")]},void 0,!0,void 0,this)},void 0,!1,void 0,this)]},G.manifest.name,!0,void 0,this)})]},void 0,!0,void 0,this),Y.user.length>0&&r(t0,{flexDirection:"column",marginBottom:1,children:[r(t0,{paddingLeft:1,children:[r(b0,{bold:!0,color:"cyan",children:"用户级"},void 0,!1,void 0,this),r(b0,{color:"gray",children:" (~/.blade/plugins/)"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),Y.user.map((G)=>{let q=G.status==="active"?"✅":"⏸️";return r(t0,{flexDirection:"column",paddingLeft:2,children:[r(b0,{children:[r(b0,{bold:!0,color:"green",children:[q," ",G.manifest.name]},void 0,!0,void 0,this),r(b0,{color:"gray",children:[" v",G.manifest.version]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),r(t0,{paddingLeft:2,children:r(b0,{color:"gray",children:G.manifest.description},void 0,!1,void 0,this)},void 0,!1,void 0,this),G.commands.length>0&&r(t0,{paddingLeft:2,children:r(b0,{color:"blue",children:["命令:"," ",G.commands.map((K)=>`/${K.namespacedName}`).join(", ")]},void 0,!0,void 0,this)},void 0,!1,void 0,this)]},G.manifest.name,!0,void 0,this)})]},void 0,!0,void 0,this),r(t0,{marginTop:1,paddingLeft:2,flexDirection:"column",children:[r(b0,{color:"gray",children:"可用命令:"},void 0,!1,void 0,this),r(b0,{color:"gray",dimColor:!0,children:[" ","• /plugins list - 列出所有插件"]},void 0,!0,void 0,this),r(b0,{color:"gray",dimColor:!0,children:[" ","• /plugins info <name> - 显示插件详情"]},void 0,!0,void 0,this),r(b0,{color:"gray",dimColor:!0,children:[" ","• /plugins install <url> - 安装插件"]},void 0,!0,void 0,this),r(b0,{color:"gray",dimColor:!0,children:[" ","• /plugins enable/disable <name> - 启用/禁用插件"]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),r(t0,{marginTop:1,children:r(b0,{dimColor:!0,children:"按 ESC 返回菜单"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}import{Box as h$,Text as x$,useInput as OU,useStdout as uN}from"ink";import gN from"ink-text-input";import aZ,{useCallback as D3,useMemo as cN,useState as d2}from"react";import{jsxDEV as D0}from"react/jsx-dev-runtime";var lN=aZ.memo(({option:$,index:Z,isSelected:X,isMultiSelect:Y,isHighlighted:Q})=>D0(h$,{flexDirection:"column",marginBottom:1,children:[D0(x$,{color:Q?"yellow":X?"green":void 0,bold:Q,children:[Y?X?"● ":"○ ":Q?"❯ ":" ",Z+1,". ",$.label]},void 0,!0,void 0,this),D0(h$,{marginLeft:4,children:D0(x$,{color:"gray",children:$.description},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)),iN=aZ.memo(({questions:$,answers:Z})=>D0(h$,{flexDirection:"column",marginBottom:1,children:$.map((X)=>{let Y=Z[X.header],Q=Array.isArray(Y)?Y.join(", "):Y||"(no answer)";return D0(h$,{marginBottom:1,children:[D0(x$,{backgroundColor:"blue",color:"white",children:[" ",X.header," "]},void 0,!0,void 0,this),D0(x$,{color:"green",children:[" ",Q]},void 0,!0,void 0,this)]},X.header,!0,void 0,this)})},void 0,!1,void 0,this)),zU=aZ.memo(({questions:$,onComplete:Z,onCancel:X})=>{let{stdout:Y}=uN(),Q=Y.columns||80,G=o$()==="confirmation-prompt",q=X$(!1),[K,W]=d2("answering"),[U,H]=d2(0),[F,O]=d2({}),[z,_]=d2(0),[B,L]=d2([]),[w,R]=d2(!1),[D,V]=d2(""),[I,v]=d2(0),N=$[U],k=cN(()=>{if(!N)return[];return[...N.options.map((j)=>({label:j.label,value:j.label,description:j.description})),{label:"Type something...",value:"__other__",description:"Enter custom response"}]},[N]),m=D3((j)=>{let M={...F,[N.header]:j};if(O(M),U<$.length-1)H(U+1),_(0),L([]),R(!1),V("");else W("submit"),v(0)},[F,N?.header,U,$.length]),s=D3((j)=>{let M=k[j];if(!M)return;if(M.value==="__other__"){R(!0);return}if(N.multiSelect)L((b)=>b.includes(M.value)?b.filter((n)=>n!==M.value):[...b,M.value]);else m(M.value)},[k,N?.multiSelect,m]),S=D3((j)=>{if(j.trim())m(j.trim())},[m]),T=D3(()=>{W("answering"),H(0),_(0),L([]),R(!1)},[]),c=D3(()=>{Z(F)},[F,Z]);if(OU((j,M)=>{if(M.ctrl&&j==="c"||M.meta&&j==="c"){q();return}if(w){if(M.escape)R(!1),V("");return}if(M.escape){X();return}let b=parseInt(j);if(b>=1&&b<=k.length){s(b-1);return}if(M.upArrow){_((n)=>n>0?n-1:k.length-1);return}if(M.downArrow||M.tab){_((n)=>n<k.length-1?n+1:0);return}if(M.return){if(N.multiSelect&&B.length>0)m(B);else s(z);return}if(j===" "&&N.multiSelect){let n=k[z];if(n&&n.value!=="__other__")L((y)=>y.includes(n.value)?y.filter((u)=>u!==n.value):[...y,n.value]);return}},{isActive:G&&K==="answering"&&!w}),OU((j,M)=>{if(M.ctrl&&j==="c"||M.meta&&j==="c"){q();return}if(M.escape){X();return}if(M.upArrow||M.downArrow||M.tab){v((b)=>b===0?1:0);return}if(M.return){if(I===0)c();else T();return}if(j.toLowerCase()==="y"){c();return}if(j.toLowerCase()==="e"){T();return}},{isActive:G&&K==="submit"}),K==="submit")return D0(h$,{flexDirection:"column",borderStyle:"round",borderColor:G?"green":"gray",padding:1,width:Math.min(Q-4,80),children:[D0(h$,{marginBottom:1,children:D0(x$,{bold:!0,color:"green",children:"✓ Review Your Answers"},void 0,!1,void 0,this)},void 0,!1,void 0,this),D0(iN,{questions:$,answers:F},void 0,!1,void 0,this),D0(h$,{flexDirection:"column",marginTop:1,children:[D0(x$,{color:I===0?"yellow":void 0,bold:I===0,children:[I===0?"❯ ":" ","[Y] Submit answers"]},void 0,!0,void 0,this),D0(x$,{color:I===1?"yellow":void 0,bold:I===1,children:[I===1?"❯ ":" ","[E] Edit answers"]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),D0(h$,{marginTop:1,children:D0(x$,{color:"gray",children:"Enter to confirm · ↑↓ to navigate · Y/E for quick select"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this);if(!N)return null;return D0(h$,{flexDirection:"column",borderStyle:"round",borderColor:G?"cyan":"gray",padding:1,width:Math.min(Q-4,80),children:[D0(h$,{marginBottom:1,children:[D0(x$,{backgroundColor:"blue",color:"white",children:[" ",N.header," "]},void 0,!0,void 0,this),D0(x$,{children:[" ",N.question]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),w?D0(h$,{flexDirection:"column",marginTop:1,children:[D0(x$,{color:"yellow",children:"Enter your response:"},void 0,!1,void 0,this),D0(h$,{marginTop:1,children:[D0(x$,{color:"cyan",children:"❯ "},void 0,!1,void 0,this),D0(gN,{value:D,onChange:V,onSubmit:S,focus:G},void 0,!1,void 0,this)]},void 0,!0,void 0,this),D0(h$,{marginTop:1,children:D0(x$,{color:"gray",children:"(Press Enter to submit, ESC to go back)"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this):D0(h$,{flexDirection:"column",children:k.map((j,M)=>D0(lN,{option:j,index:M,isSelected:B.includes(j.value),isMultiSelect:N.multiSelect,isHighlighted:z===M},j.value,!1,void 0,this))},void 0,!1,void 0,this),!w&&D0(h$,{marginTop:1,flexDirection:"column",children:[D0(x$,{color:"gray",children:N.multiSelect?"Space to toggle · Enter to confirm · 1-9 for quick select":"Enter to select · ↑↓ or Tab to navigate · 1-9 for quick select"},void 0,!1,void 0,this),N.multiSelect&&B.length>0&&D0(x$,{color:"green",children:["Selected: ",B.join(", ")]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),$.length>1&&D0(h$,{marginTop:1,children:D0(x$,{color:"gray",children:["Question ",U+1," of ",$.length]},void 0,!0,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)});E6();import{Box as R8,Text as T1,useInput as aN}from"ink";import rN from"ink-select-input";import{useEffect as _U,useMemo as H9,useState as rZ}from"react";import{jsxDEV as j$}from"react/jsx-dev-runtime";function nN($){let Z=new Date($),Y=new Date().getTime()-Z.getTime(),Q=Math.floor(Y/86400000);if(Q===0)return`今天 ${Z.getHours().toString().padStart(2,"0")}:${Z.getMinutes().toString().padStart(2,"0")}`;if(Q===1)return"昨天";if(Q<7)return`${Q}天前`;return`${Z.getMonth()+1}/${Z.getDate()}`}function oN($){let Z=$.split("/");return Z[Z.length-1]||$}var sN=({isSelected:$})=>j$(R8,{marginRight:1,children:j$(T1,{color:$?"cyan":"gray",children:$?"❯":" "},void 0,!1,void 0,this)},void 0,!1,void 0,this),tN=({isSelected:$,label:Z})=>j$(T1,{color:$?"cyan":"white",bold:$,children:Z},void 0,!1,void 0,this),M3=20,BU=({sessions:$,onSelect:Z,onCancel:X})=>{let[Y,Q]=rZ([]),[J,G]=rZ(!1),[q,K]=rZ(0),U=o$()==="session-selector",H=X$(!1);aN((w,R)=>{if(R.ctrl&&w==="c"||R.meta&&w==="c"){H();return}if(R.escape&&X){X();return}if(R.leftArrow||w==="h"||w==="H"){if(q>0)K((D)=>D-1);return}if(R.rightArrow||w==="l"||w==="L"){if(q<z-1)K((D)=>D+1);return}},{isActive:U}),_U(()=>{if($){Q($);return}(async()=>{G(!0);try{let R=await m1.listSessions();Q(R)}catch(R){console.error("[SessionSelector] Failed to load sessions:",R),Q([])}finally{G(!1)}})()},[$]);let F=$||Y,O=H9(()=>{return F.map((w)=>{let R=oN(w.projectPath),D=nN(w.lastMessageTime),V=w.gitBranch?` (${w.gitBranch})`:"",I=w.hasErrors?" ⚠️":"";return{label:`\uD83D\uDCC5 ${D} | ${R}${V} | ${w.messageCount} 条消息${I}`,value:w.sessionId}})},[F]),z=H9(()=>Math.max(1,Math.ceil(O.length/M3)),[O.length]),_=H9(()=>{let w=q*M3;return O.slice(w,w+M3)},[O,q]),B=H9(()=>({start:q*M3+1,end:Math.min((q+1)*M3,O.length)}),[q,O.length]);_U(()=>{K(0)},[F.length]);let L=(w)=>{Z(w.value)};if(J)return j$(R8,{flexDirection:"column",paddingX:2,paddingY:1,children:j$(T1,{children:"⏳ 正在加载会话列表..."},void 0,!1,void 0,this)},void 0,!1,void 0,this);if(F.length===0)return j$(R8,{flexDirection:"column",paddingX:2,paddingY:1,children:[j$(T1,{color:"yellow",children:"⚠️ 没有找到历史会话"},void 0,!1,void 0,this),j$(T1,{dimColor:!0,children:[`
|
|
2823
2823
|
`,"提示: 开始一次对话后,会话历史将保存到 ~/.blade/projects/"]},void 0,!0,void 0,this)]},void 0,!0,void 0,this);return j$(R8,{flexDirection:"column",paddingX:2,paddingY:1,children:[j$(T1,{bold:!0,color:"cyan",children:"\uD83D\uDCC2 选择要恢复的会话:"},void 0,!1,void 0,this),j$(T1,{dimColor:!0,children:[`
|
|
2824
2824
|
`,"(←→ 翻页 | ↑↓ 选择 | Enter 确认 | Esc 取消)",`
|
|
2825
|
-
`]},void 0,!0,void 0,this),j$(rN,{items:_,onSelect:L,indicatorComponent:sN,itemComponent:tN},void 0,!1,void 0,this),j$(R8,{marginTop:1,flexDirection:"column",children:[j$(T1,{dimColor:!0,children:["第 ",q+1,"/",z," 页 · 共 ",F.length," 个会话 · 显示"," ",B.start,"-",B.end]},void 0,!0,void 0,this),z>1&&j$(R8,{marginTop:1,children:[j$(T1,{color:q>0?"cyan":"gray",children:q>0?"◀ ← 上一页":" "},void 0,!1,void 0,this),j$(T1,{children:" "},void 0,!1,void 0,this),j$(T1,{color:q<z-1?"cyan":"gray",children:q<z-1?"下一页 → ▶":""},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)};X4();import{Box as K$,Text as i0,useInput as eN}from"ink";import{jsxDEV as J0}from"react/jsx-dev-runtime";function LU({onCancel:$}){let X=b$().getAll(),Y=X.filter((q)=>q.source==="builtin"),Q=X.filter((q)=>q.source==="user"),J=X.filter((q)=>q.source==="project"),G=X$(!1,$);if(eN((q,K)=>{if(K.escape)$?.();else if(K.ctrl&&q==="c"||K.meta&&q==="c")G()}),X.length===0)return J0(K$,{flexDirection:"column",paddingY:1,children:[J0(K$,{marginBottom:1,children:J0(i0,{bold:!0,color:"cyan",children:"\uD83D\uDCDA 所有 Skills"},void 0,!1,void 0,this)},void 0,!1,void 0,this),J0(K$,{paddingLeft:2,children:J0(i0,{color:"gray",children:"没有找到任何 Skill"},void 0,!1,void 0,this)},void 0,!1,void 0,this),J0(K$,{marginTop:1,paddingLeft:2,children:J0(i0,{color:"gray",children:"配置文件位置: ~/.blade/skills/ 或 .blade/skills/"},void 0,!1,void 0,this)},void 0,!1,void 0,this),J0(K$,{marginTop:1,children:J0(i0,{dimColor:!0,children:"按 ESC 返回菜单"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this);return J0(K$,{flexDirection:"column",paddingY:1,children:[J0(K$,{marginBottom:1,children:[J0(i0,{bold:!0,color:"cyan",children:"\uD83D\uDCDA 所有 Skills"},void 0,!1,void 0,this),J0(i0,{color:"gray",children:[" (找到 ",X.length," 个)"]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),J.length>0&&J0(K$,{flexDirection:"column",marginBottom:1,children:[J0(K$,{paddingLeft:1,children:[J0(i0,{bold:!0,color:"yellow",children:"项目级"},void 0,!1,void 0,this),J0(i0,{color:"gray",children:" (.blade/skills/)"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),J.map((q)=>{let W=q.description.length>80?`${q.description.substring(0,80)}...`:q.description;return J0(K$,{flexDirection:"column",paddingLeft:2,children:[J0(i0,{children:[J0(i0,{bold:!0,color:"green",children:["• ",q.name]},void 0,!0,void 0,this),J0(i0,{color:"gray",children:[" - ",W]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),q.allowedTools&&q.allowedTools.length>0&&J0(K$,{paddingLeft:2,children:J0(i0,{color:"gray",children:["工具: ",q.allowedTools.join(", ")]},void 0,!0,void 0,this)},void 0,!1,void 0,this),J0(K$,{paddingLeft:2,children:J0(i0,{color:"gray",dimColor:!0,children:q.path},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},q.name,!0,void 0,this)})]},void 0,!0,void 0,this),Q.length>0&&J0(K$,{flexDirection:"column",marginBottom:1,children:[J0(K$,{paddingLeft:1,children:[J0(i0,{bold:!0,color:"yellow",children:"用户级"},void 0,!1,void 0,this),J0(i0,{color:"gray",children:" (~/.blade/skills/)"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),Q.map((q)=>{let W=q.description.length>80?`${q.description.substring(0,80)}...`:q.description;return J0(K$,{flexDirection:"column",paddingLeft:2,children:[J0(i0,{children:[J0(i0,{bold:!0,color:"green",children:["• ",q.name]},void 0,!0,void 0,this),J0(i0,{color:"gray",children:[" - ",W]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),q.allowedTools&&q.allowedTools.length>0&&J0(K$,{paddingLeft:2,children:J0(i0,{color:"gray",children:["工具: ",q.allowedTools.join(", ")]},void 0,!0,void 0,this)},void 0,!1,void 0,this),J0(K$,{paddingLeft:2,children:J0(i0,{color:"gray",dimColor:!0,children:q.path},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},q.name,!0,void 0,this)})]},void 0,!0,void 0,this),Y.length>0&&J0(K$,{flexDirection:"column",marginBottom:1,children:[J0(K$,{paddingLeft:1,children:[J0(i0,{bold:!0,color:"cyan",children:"内置"},void 0,!1,void 0,this),J0(i0,{color:"gray",children:" (builtin)"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),Y.map((q)=>{let W=q.description.length>80?`${q.description.substring(0,80)}...`:q.description;return J0(K$,{flexDirection:"column",paddingLeft:2,children:[J0(i0,{children:[J0(i0,{bold:!0,color:"green",children:["• ",q.name]},void 0,!0,void 0,this),J0(i0,{color:"gray",children:[" - ",W]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),q.userInvocable&&J0(K$,{paddingLeft:2,children:J0(i0,{color:"blue",children:["命令: /",q.name]},void 0,!0,void 0,this)},void 0,!1,void 0,this)]},q.name,!0,void 0,this)})]},void 0,!0,void 0,this),J0(K$,{marginTop:1,children:J0(i0,{dimColor:!0,children:"按 ESC 返回菜单"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}U1();b1();import{Box as m4,Text as Q1}from"ink";import wU,{useEffect as $b,useState as Zb}from"react";import{jsxDEV as W$}from"react/jsx-dev-runtime";var Xb={init:"\uD83D\uDCDD",requirements:"\uD83D\uDCCB",design:"\uD83C\uDFA8",tasks:"\uD83D\uDCCC",implementation:"\uD83D\uDD27",done:"✅"},F9=["init","requirements","design","tasks","implementation","done"],Yb={pending:"○",in_progress:"◐",completed:"●",blocked:"✕"},Qb={pending:"gray",in_progress:"yellow",completed:"green",blocked:"red"},NU=wU.memo(({expanded:$=!1,maxTasks:Z=5})=>{let[X,Y]=Zb(null);if($b(()=>{let G=d0.getInstance();Y(G.getCurrentSpec());let q=setInterval(()=>{Y(G.getCurrentSpec())},1000);return()=>clearInterval(q)},[]),!X)return null;let Q=F9.indexOf(X.phase),J=X.tasks.length>0?Math.round(X.tasks.filter((G)=>G.status==="completed").length/X.tasks.length*100):0;return W$(m4,{flexDirection:"column",borderStyle:"round",borderColor:"blue",paddingX:1,marginBottom:1,children:[W$(m4,{flexDirection:"row",justifyContent:"space-between",children:[W$(Q1,{color:"blue",bold:!0,children:["\uD83D\uDCCB Spec: ",X.name]},void 0,!0,void 0,this),W$(Q1,{color:"gray",children:[Xb[X.phase]," ",y$[X.phase]]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),W$(m4,{flexDirection:"row",marginTop:1,children:[F9.map((G,q)=>{let K=q<Q,W=q===Q;return W$(m4,{flexDirection:"row",children:[W$(Q1,{color:K?"green":W?"blue":"gray",children:K?"●":W?"◉":"○"},void 0,!1,void 0,this),q<F9.length-1&&W$(Q1,{color:K?"green":"gray",children:"──"},void 0,!1,void 0,this)]},G,!0,void 0,this)}),W$(Q1,{color:"gray",children:[" (",J,"%)"]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),W$(m4,{flexDirection:"row",marginTop:0,children:W$(Q1,{color:"gray",dimColor:!0,children:F9.map((G,q)=>{let K=G.slice(0,3).toUpperCase();return q===Q?`[${K}]`:` ${K} `}).join("")},void 0,!1,void 0,this)},void 0,!1,void 0,this),$&&X.tasks.length>0&&W$(m4,{flexDirection:"column",marginTop:1,children:[W$(Q1,{color:"gray",dimColor:!0,children:["─── Tasks (",X.tasks.filter((G)=>G.status==="completed").length,"/",X.tasks.length,") ───"]},void 0,!0,void 0,this),X.tasks.slice(0,Z).map((G)=>W$(Jb,{task:G,isCurrent:G.id===X.currentTaskId},G.id,!1,void 0,this)),X.tasks.length>Z&&W$(Q1,{color:"gray",dimColor:!0,children:["... and ",X.tasks.length-Z," more tasks"]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),!$&&X.currentTaskId&&W$(m4,{flexDirection:"row",marginTop:1,children:[W$(Q1,{color:"gray",children:"Current: "},void 0,!1,void 0,this),W$(Q1,{color:"yellow",children:X.tasks.find((G)=>G.id===X.currentTaskId)?.title||"Unknown"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)}),Jb=wU.memo(({task:$,isCurrent:Z})=>{let X=Yb[$.status]||"?",Y=Qb[$.status]||"gray";return W$(m4,{flexDirection:"row",children:[W$(Q1,{color:Y,children:[X," "]},void 0,!0,void 0,this),W$(Q1,{color:Z?"yellow":"white",bold:Z,children:$.title},void 0,!1,void 0,this),$.complexity&&W$(Q1,{color:"gray",dimColor:!0,children:[" ","[",$.complexity,"]"]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)});import{useMemoizedFn as Gb}from"ahooks";import{Box as i1,Text as a,useInput as qb}from"ink";import Kb from"ink-select-input";import{useState as bU}from"react";C0();R9();i4();import{jsxDEV as d}from"react/jsx-dev-runtime";var AU=t1.map(($)=>({label:$.label,value:$.id})),Wb=({theme:$})=>{let{colors:Z}=$;return d(i1,{flexDirection:"column",paddingLeft:1,paddingTop:1,children:[d(a,{bold:!0,color:Z.text.primary,children:"代码预览"},void 0,!1,void 0,this),d(a,{children:" "},void 0,!1,void 0,this),d(a,{color:Z.syntax.comment,children:"# function"},void 0,!1,void 0,this),d(a,{children:[d(a,{color:Z.syntax.keyword,children:"def"},void 0,!1,void 0,this)," ",d(a,{color:Z.syntax.function,children:"fibonacci"},void 0,!1,void 0,this),d(a,{color:Z.text.primary,children:"("},void 0,!1,void 0,this),d(a,{color:Z.syntax.variable,children:"n"},void 0,!1,void 0,this),d(a,{color:Z.text.primary,children:"):"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),d(a,{children:[" ",d(a,{color:Z.syntax.variable,children:"a"},void 0,!1,void 0,this),d(a,{color:Z.syntax.operator,children:","},void 0,!1,void 0,this)," ",d(a,{color:Z.syntax.variable,children:"b"},void 0,!1,void 0,this)," ",d(a,{color:Z.syntax.operator,children:"="},void 0,!1,void 0,this)," ",d(a,{color:Z.syntax.number,children:"0"},void 0,!1,void 0,this),d(a,{color:Z.syntax.operator,children:","},void 0,!1,void 0,this)," ",d(a,{color:Z.syntax.number,children:"1"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),d(a,{children:[" ",d(a,{color:Z.syntax.keyword,children:"for"},void 0,!1,void 0,this)," ",d(a,{color:Z.syntax.variable,children:"_"},void 0,!1,void 0,this)," ",d(a,{color:Z.syntax.keyword,children:"in"},void 0,!1,void 0,this)," ",d(a,{color:Z.syntax.function,children:"range"},void 0,!1,void 0,this),d(a,{color:Z.text.primary,children:"("},void 0,!1,void 0,this),d(a,{color:Z.syntax.variable,children:"n"},void 0,!1,void 0,this),d(a,{color:Z.text.primary,children:"):"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),d(a,{children:[" ",d(a,{color:Z.syntax.variable,children:"a"},void 0,!1,void 0,this),d(a,{color:Z.syntax.operator,children:","},void 0,!1,void 0,this)," ",d(a,{color:Z.syntax.variable,children:"b"},void 0,!1,void 0,this)," ",d(a,{color:Z.syntax.operator,children:"="},void 0,!1,void 0,this)," ",d(a,{color:Z.syntax.variable,children:"b"},void 0,!1,void 0,this),d(a,{color:Z.syntax.operator,children:","},void 0,!1,void 0,this)," ",d(a,{color:Z.syntax.variable,children:"a"},void 0,!1,void 0,this)," ",d(a,{color:Z.syntax.operator,children:"+"},void 0,!1,void 0,this)," ",d(a,{color:Z.syntax.variable,children:"b"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),d(a,{children:[" ",d(a,{color:Z.syntax.keyword,children:"return"},void 0,!1,void 0,this)," ",d(a,{color:Z.syntax.variable,children:"a"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),d(a,{children:" "},void 0,!1,void 0,this),d(a,{color:Z.error,children:["- print(",d(a,{color:Z.syntax.string,children:'"Hello, "'},void 0,!1,void 0,this)," + name)"]},void 0,!0,void 0,this),d(a,{color:Z.success,children:["+ print(",d(a,{color:Z.syntax.string,children:['f"Hello, ',"{","name","}",'"']},void 0,!0,void 0,this),")"]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)},Ub=({theme:$})=>{let{colors:Z}=$;return d(i1,{flexDirection:"column",paddingLeft:1,paddingTop:1,children:[d(a,{children:" "},void 0,!1,void 0,this),d(a,{bold:!0,color:Z.text.primary,children:"颜色配置"},void 0,!1,void 0,this),d(a,{children:" "},void 0,!1,void 0,this),d(a,{children:[d(a,{color:Z.text.muted,children:"Primary: "},void 0,!1,void 0,this),d(a,{color:Z.primary,children:Z.primary},void 0,!1,void 0,this)]},void 0,!0,void 0,this),d(a,{children:[d(a,{color:Z.text.muted,children:"Success: "},void 0,!1,void 0,this),d(a,{color:Z.success,children:Z.success},void 0,!1,void 0,this)]},void 0,!0,void 0,this),d(a,{children:[d(a,{color:Z.text.muted,children:"Error: "},void 0,!1,void 0,this),d(a,{color:Z.error,children:Z.error},void 0,!1,void 0,this)]},void 0,!0,void 0,this),d(a,{children:[d(a,{color:Z.text.muted,children:"Warning: "},void 0,!1,void 0,this),d(a,{color:Z.warning,children:Z.warning},void 0,!1,void 0,this)]},void 0,!0,void 0,this),d(a,{children:[d(a,{color:Z.text.muted,children:"Info: "},void 0,!1,void 0,this),d(a,{color:Z.info,children:Z.info},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)},RU=()=>{let $=T4(),Z=g$.getCurrentThemeName(),X=t1.findIndex((z)=>z.label===Z),Y=X>=0?t1[X].theme:t1[0].theme,[Q,J]=bU(Y),[G,q]=bU(!1),K=Gb(async(z)=>{if(G)return;q(!0);try{await x0().setTheme(z.value),$.closeModal()}catch(_){console.error("❌ 主题切换失败:",_ instanceof Error?_.message:_)}finally{q(!1)}}),W=(z)=>{let _=t1.find((B)=>B.id===z.value);if(_)J(_.theme)},H=o$()==="theme-selector",F=X$(!1);qb((z,_)=>{if(_.ctrl&&z==="c"||_.meta&&z==="c"){F();return}if(_.escape&&!G)$.closeModal()},{isActive:H});let O=(z)=>{let{isSelected:_,label:B}=z,w=B===Z?"✓":" ";return d(a,{color:_?Q.colors.primary:Q.colors.text.primary,children:[w," ",B]},void 0,!0,void 0,this)};return d(i1,{flexDirection:"column",height:"100%",children:[d(i1,{paddingX:2,paddingY:1,borderStyle:"single",borderColor:Q.colors.border.light,children:d(a,{bold:!0,color:Q.colors.primary,children:"\uD83C\uDFA8 主题选择器"},void 0,!1,void 0,this)},void 0,!1,void 0,this),d(i1,{flexDirection:"row",flexGrow:1,children:[d(i1,{width:"40%",borderStyle:"single",borderColor:Q.colors.border.light,paddingX:1,children:d(i1,{flexDirection:"column",children:[d(i1,{paddingTop:1,paddingBottom:1,children:d(a,{bold:!0,color:Q.colors.text.primary,children:["可用主题 (",AU.length,")"]},void 0,!0,void 0,this)},void 0,!1,void 0,this),d(Kb,{items:AU,initialIndex:X>=0?X:0,onSelect:K,onHighlight:W,itemComponent:O},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this),d(i1,{width:"60%",flexDirection:"column",borderStyle:"single",borderColor:Q.colors.border.light,children:[d(Wb,{theme:Q},void 0,!1,void 0,this),d(Ub,{theme:Q},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),d(i1,{paddingX:2,paddingY:1,borderStyle:"single",borderColor:Q.colors.border.light,children:d(a,{color:Q.colors.text.muted,children:G?"正在保存...":"Enter: 选择主题 | Esc: 取消"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)};import{jsxDEV as a0}from"react/jsx-dev-runtime";var t$=i("UI"),VU=({debug:$,...Z})=>{if($)t$.debug("[Debug] BladeInterface props:",{permissionMode:Z.permissionMode,yolo:Z.yolo,maxTurns:Z.maxTurns});let X=O9(!1),Y=O9(!1),Q=O9(!1),J=O9(null),G=NK(),q=bK(),K=f6(),W=VK(),U=RK(),H=T4(),F=P4(),O=yK(),z=U8(),_=S4(),{exit:B}=Hb(),L=G==="ready",w=G==="needsSetup",R=G==="idle",{confirmationState:D,confirmationHandler:V,handleResponse:I}=aK(),{executeCommand:v,handleAbort:N}=gK(Z.systemPrompt,Z.appendSystemPrompt,V,Z.maxTurns),{getPreviousCommand:k,getNextCommand:m,addToHistory:s}=lK();JW();let S=nK("",0),T=s$(async()=>{let q0=z,S0;if(q0==="default")S0="autoEdit";else if(q0==="autoEdit")S0="plan";else if(q0==="plan")S0="spec";else if(q0==="spec")S0="default";else S0="default";try{if(await x0().setPermissionMode(S0),S0==="spec")try{let I$=d0.getInstance();await I$.initialize(process.cwd());let J1=await I$.listSpecs();if(J1.length>0){let o1=J1[0];await I$.loadSpec(o1.name),F.addAssistantMessage(`\uD83D\uDCCB **已进入 Spec 模式**
|
|
2825
|
+
`]},void 0,!0,void 0,this),j$(rN,{items:_,onSelect:L,indicatorComponent:sN,itemComponent:tN},void 0,!1,void 0,this),j$(R8,{marginTop:1,flexDirection:"column",children:[j$(T1,{dimColor:!0,children:["第 ",q+1,"/",z," 页 · 共 ",F.length," 个会话 · 显示"," ",B.start,"-",B.end]},void 0,!0,void 0,this),z>1&&j$(R8,{marginTop:1,children:[j$(T1,{color:q>0?"cyan":"gray",children:q>0?"◀ ← 上一页":" "},void 0,!1,void 0,this),j$(T1,{children:" "},void 0,!1,void 0,this),j$(T1,{color:q<z-1?"cyan":"gray",children:q<z-1?"下一页 → ▶":""},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)};X2();import{Box as K$,Text as i0,useInput as eN}from"ink";import{jsxDEV as J0}from"react/jsx-dev-runtime";function LU({onCancel:$}){let X=b$().getAll(),Y=X.filter((q)=>q.source==="builtin"),Q=X.filter((q)=>q.source==="user"),J=X.filter((q)=>q.source==="project"),G=X$(!1,$);if(eN((q,K)=>{if(K.escape)$?.();else if(K.ctrl&&q==="c"||K.meta&&q==="c")G()}),X.length===0)return J0(K$,{flexDirection:"column",paddingY:1,children:[J0(K$,{marginBottom:1,children:J0(i0,{bold:!0,color:"cyan",children:"\uD83D\uDCDA 所有 Skills"},void 0,!1,void 0,this)},void 0,!1,void 0,this),J0(K$,{paddingLeft:2,children:J0(i0,{color:"gray",children:"没有找到任何 Skill"},void 0,!1,void 0,this)},void 0,!1,void 0,this),J0(K$,{marginTop:1,paddingLeft:2,children:J0(i0,{color:"gray",children:"配置文件位置: ~/.blade/skills/ 或 .blade/skills/"},void 0,!1,void 0,this)},void 0,!1,void 0,this),J0(K$,{marginTop:1,children:J0(i0,{dimColor:!0,children:"按 ESC 返回菜单"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this);return J0(K$,{flexDirection:"column",paddingY:1,children:[J0(K$,{marginBottom:1,children:[J0(i0,{bold:!0,color:"cyan",children:"\uD83D\uDCDA 所有 Skills"},void 0,!1,void 0,this),J0(i0,{color:"gray",children:[" (找到 ",X.length," 个)"]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),J.length>0&&J0(K$,{flexDirection:"column",marginBottom:1,children:[J0(K$,{paddingLeft:1,children:[J0(i0,{bold:!0,color:"yellow",children:"项目级"},void 0,!1,void 0,this),J0(i0,{color:"gray",children:" (.blade/skills/)"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),J.map((q)=>{let W=q.description.length>80?`${q.description.substring(0,80)}...`:q.description;return J0(K$,{flexDirection:"column",paddingLeft:2,children:[J0(i0,{children:[J0(i0,{bold:!0,color:"green",children:["• ",q.name]},void 0,!0,void 0,this),J0(i0,{color:"gray",children:[" - ",W]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),q.allowedTools&&q.allowedTools.length>0&&J0(K$,{paddingLeft:2,children:J0(i0,{color:"gray",children:["工具: ",q.allowedTools.join(", ")]},void 0,!0,void 0,this)},void 0,!1,void 0,this),J0(K$,{paddingLeft:2,children:J0(i0,{color:"gray",dimColor:!0,children:q.path},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},q.name,!0,void 0,this)})]},void 0,!0,void 0,this),Q.length>0&&J0(K$,{flexDirection:"column",marginBottom:1,children:[J0(K$,{paddingLeft:1,children:[J0(i0,{bold:!0,color:"yellow",children:"用户级"},void 0,!1,void 0,this),J0(i0,{color:"gray",children:" (~/.blade/skills/)"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),Q.map((q)=>{let W=q.description.length>80?`${q.description.substring(0,80)}...`:q.description;return J0(K$,{flexDirection:"column",paddingLeft:2,children:[J0(i0,{children:[J0(i0,{bold:!0,color:"green",children:["• ",q.name]},void 0,!0,void 0,this),J0(i0,{color:"gray",children:[" - ",W]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),q.allowedTools&&q.allowedTools.length>0&&J0(K$,{paddingLeft:2,children:J0(i0,{color:"gray",children:["工具: ",q.allowedTools.join(", ")]},void 0,!0,void 0,this)},void 0,!1,void 0,this),J0(K$,{paddingLeft:2,children:J0(i0,{color:"gray",dimColor:!0,children:q.path},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},q.name,!0,void 0,this)})]},void 0,!0,void 0,this),Y.length>0&&J0(K$,{flexDirection:"column",marginBottom:1,children:[J0(K$,{paddingLeft:1,children:[J0(i0,{bold:!0,color:"cyan",children:"内置"},void 0,!1,void 0,this),J0(i0,{color:"gray",children:" (builtin)"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),Y.map((q)=>{let W=q.description.length>80?`${q.description.substring(0,80)}...`:q.description;return J0(K$,{flexDirection:"column",paddingLeft:2,children:[J0(i0,{children:[J0(i0,{bold:!0,color:"green",children:["• ",q.name]},void 0,!0,void 0,this),J0(i0,{color:"gray",children:[" - ",W]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),q.userInvocable&&J0(K$,{paddingLeft:2,children:J0(i0,{color:"blue",children:["命令: /",q.name]},void 0,!0,void 0,this)},void 0,!1,void 0,this)]},q.name,!0,void 0,this)})]},void 0,!0,void 0,this),J0(K$,{marginTop:1,children:J0(i0,{dimColor:!0,children:"按 ESC 返回菜单"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}U1();b1();import{Box as m2,Text as Q1}from"ink";import wU,{useEffect as $b,useState as Zb}from"react";import{jsxDEV as W$}from"react/jsx-dev-runtime";var Xb={init:"\uD83D\uDCDD",requirements:"\uD83D\uDCCB",design:"\uD83C\uDFA8",tasks:"\uD83D\uDCCC",implementation:"\uD83D\uDD27",done:"✅"},F9=["init","requirements","design","tasks","implementation","done"],Yb={pending:"○",in_progress:"◐",completed:"●",blocked:"✕"},Qb={pending:"gray",in_progress:"yellow",completed:"green",blocked:"red"},NU=wU.memo(({expanded:$=!1,maxTasks:Z=5})=>{let[X,Y]=Zb(null);if($b(()=>{let G=d0.getInstance();Y(G.getCurrentSpec());let q=setInterval(()=>{Y(G.getCurrentSpec())},1000);return()=>clearInterval(q)},[]),!X)return null;let Q=F9.indexOf(X.phase),J=X.tasks.length>0?Math.round(X.tasks.filter((G)=>G.status==="completed").length/X.tasks.length*100):0;return W$(m2,{flexDirection:"column",borderStyle:"round",borderColor:"blue",paddingX:1,marginBottom:1,children:[W$(m2,{flexDirection:"row",justifyContent:"space-between",children:[W$(Q1,{color:"blue",bold:!0,children:["\uD83D\uDCCB Spec: ",X.name]},void 0,!0,void 0,this),W$(Q1,{color:"gray",children:[Xb[X.phase]," ",y$[X.phase]]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),W$(m2,{flexDirection:"row",marginTop:1,children:[F9.map((G,q)=>{let K=q<Q,W=q===Q;return W$(m2,{flexDirection:"row",children:[W$(Q1,{color:K?"green":W?"blue":"gray",children:K?"●":W?"◉":"○"},void 0,!1,void 0,this),q<F9.length-1&&W$(Q1,{color:K?"green":"gray",children:"──"},void 0,!1,void 0,this)]},G,!0,void 0,this)}),W$(Q1,{color:"gray",children:[" (",J,"%)"]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),W$(m2,{flexDirection:"row",marginTop:0,children:W$(Q1,{color:"gray",dimColor:!0,children:F9.map((G,q)=>{let K=G.slice(0,3).toUpperCase();return q===Q?`[${K}]`:` ${K} `}).join("")},void 0,!1,void 0,this)},void 0,!1,void 0,this),$&&X.tasks.length>0&&W$(m2,{flexDirection:"column",marginTop:1,children:[W$(Q1,{color:"gray",dimColor:!0,children:["─── Tasks (",X.tasks.filter((G)=>G.status==="completed").length,"/",X.tasks.length,") ───"]},void 0,!0,void 0,this),X.tasks.slice(0,Z).map((G)=>W$(Jb,{task:G,isCurrent:G.id===X.currentTaskId},G.id,!1,void 0,this)),X.tasks.length>Z&&W$(Q1,{color:"gray",dimColor:!0,children:["... and ",X.tasks.length-Z," more tasks"]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),!$&&X.currentTaskId&&W$(m2,{flexDirection:"row",marginTop:1,children:[W$(Q1,{color:"gray",children:"Current: "},void 0,!1,void 0,this),W$(Q1,{color:"yellow",children:X.tasks.find((G)=>G.id===X.currentTaskId)?.title||"Unknown"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)}),Jb=wU.memo(({task:$,isCurrent:Z})=>{let X=Yb[$.status]||"?",Y=Qb[$.status]||"gray";return W$(m2,{flexDirection:"row",children:[W$(Q1,{color:Y,children:[X," "]},void 0,!0,void 0,this),W$(Q1,{color:Z?"yellow":"white",bold:Z,children:$.title},void 0,!1,void 0,this),$.complexity&&W$(Q1,{color:"gray",dimColor:!0,children:[" ","[",$.complexity,"]"]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)});import{useMemoizedFn as Gb}from"ahooks";import{Box as i1,Text as a,useInput as qb}from"ink";import Kb from"ink-select-input";import{useState as bU}from"react";C0();R9();i2();import{jsxDEV as d}from"react/jsx-dev-runtime";var AU=t1.map(($)=>({label:$.label,value:$.id})),Wb=({theme:$})=>{let{colors:Z}=$;return d(i1,{flexDirection:"column",paddingLeft:1,paddingTop:1,children:[d(a,{bold:!0,color:Z.text.primary,children:"代码预览"},void 0,!1,void 0,this),d(a,{children:" "},void 0,!1,void 0,this),d(a,{color:Z.syntax.comment,children:"# function"},void 0,!1,void 0,this),d(a,{children:[d(a,{color:Z.syntax.keyword,children:"def"},void 0,!1,void 0,this)," ",d(a,{color:Z.syntax.function,children:"fibonacci"},void 0,!1,void 0,this),d(a,{color:Z.text.primary,children:"("},void 0,!1,void 0,this),d(a,{color:Z.syntax.variable,children:"n"},void 0,!1,void 0,this),d(a,{color:Z.text.primary,children:"):"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),d(a,{children:[" ",d(a,{color:Z.syntax.variable,children:"a"},void 0,!1,void 0,this),d(a,{color:Z.syntax.operator,children:","},void 0,!1,void 0,this)," ",d(a,{color:Z.syntax.variable,children:"b"},void 0,!1,void 0,this)," ",d(a,{color:Z.syntax.operator,children:"="},void 0,!1,void 0,this)," ",d(a,{color:Z.syntax.number,children:"0"},void 0,!1,void 0,this),d(a,{color:Z.syntax.operator,children:","},void 0,!1,void 0,this)," ",d(a,{color:Z.syntax.number,children:"1"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),d(a,{children:[" ",d(a,{color:Z.syntax.keyword,children:"for"},void 0,!1,void 0,this)," ",d(a,{color:Z.syntax.variable,children:"_"},void 0,!1,void 0,this)," ",d(a,{color:Z.syntax.keyword,children:"in"},void 0,!1,void 0,this)," ",d(a,{color:Z.syntax.function,children:"range"},void 0,!1,void 0,this),d(a,{color:Z.text.primary,children:"("},void 0,!1,void 0,this),d(a,{color:Z.syntax.variable,children:"n"},void 0,!1,void 0,this),d(a,{color:Z.text.primary,children:"):"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),d(a,{children:[" ",d(a,{color:Z.syntax.variable,children:"a"},void 0,!1,void 0,this),d(a,{color:Z.syntax.operator,children:","},void 0,!1,void 0,this)," ",d(a,{color:Z.syntax.variable,children:"b"},void 0,!1,void 0,this)," ",d(a,{color:Z.syntax.operator,children:"="},void 0,!1,void 0,this)," ",d(a,{color:Z.syntax.variable,children:"b"},void 0,!1,void 0,this),d(a,{color:Z.syntax.operator,children:","},void 0,!1,void 0,this)," ",d(a,{color:Z.syntax.variable,children:"a"},void 0,!1,void 0,this)," ",d(a,{color:Z.syntax.operator,children:"+"},void 0,!1,void 0,this)," ",d(a,{color:Z.syntax.variable,children:"b"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),d(a,{children:[" ",d(a,{color:Z.syntax.keyword,children:"return"},void 0,!1,void 0,this)," ",d(a,{color:Z.syntax.variable,children:"a"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),d(a,{children:" "},void 0,!1,void 0,this),d(a,{color:Z.error,children:["- print(",d(a,{color:Z.syntax.string,children:'"Hello, "'},void 0,!1,void 0,this)," + name)"]},void 0,!0,void 0,this),d(a,{color:Z.success,children:["+ print(",d(a,{color:Z.syntax.string,children:['f"Hello, ',"{","name","}",'"']},void 0,!0,void 0,this),")"]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)},Ub=({theme:$})=>{let{colors:Z}=$;return d(i1,{flexDirection:"column",paddingLeft:1,paddingTop:1,children:[d(a,{children:" "},void 0,!1,void 0,this),d(a,{bold:!0,color:Z.text.primary,children:"颜色配置"},void 0,!1,void 0,this),d(a,{children:" "},void 0,!1,void 0,this),d(a,{children:[d(a,{color:Z.text.muted,children:"Primary: "},void 0,!1,void 0,this),d(a,{color:Z.primary,children:Z.primary},void 0,!1,void 0,this)]},void 0,!0,void 0,this),d(a,{children:[d(a,{color:Z.text.muted,children:"Success: "},void 0,!1,void 0,this),d(a,{color:Z.success,children:Z.success},void 0,!1,void 0,this)]},void 0,!0,void 0,this),d(a,{children:[d(a,{color:Z.text.muted,children:"Error: "},void 0,!1,void 0,this),d(a,{color:Z.error,children:Z.error},void 0,!1,void 0,this)]},void 0,!0,void 0,this),d(a,{children:[d(a,{color:Z.text.muted,children:"Warning: "},void 0,!1,void 0,this),d(a,{color:Z.warning,children:Z.warning},void 0,!1,void 0,this)]},void 0,!0,void 0,this),d(a,{children:[d(a,{color:Z.text.muted,children:"Info: "},void 0,!1,void 0,this),d(a,{color:Z.info,children:Z.info},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)},RU=()=>{let $=T2(),Z=g$.getCurrentThemeName(),X=t1.findIndex((z)=>z.label===Z),Y=X>=0?t1[X].theme:t1[0].theme,[Q,J]=bU(Y),[G,q]=bU(!1),K=Gb(async(z)=>{if(G)return;q(!0);try{await x0().setTheme(z.value),$.closeModal()}catch(_){console.error("❌ 主题切换失败:",_ instanceof Error?_.message:_)}finally{q(!1)}}),W=(z)=>{let _=t1.find((B)=>B.id===z.value);if(_)J(_.theme)},H=o$()==="theme-selector",F=X$(!1);qb((z,_)=>{if(_.ctrl&&z==="c"||_.meta&&z==="c"){F();return}if(_.escape&&!G)$.closeModal()},{isActive:H});let O=(z)=>{let{isSelected:_,label:B}=z,w=B===Z?"✓":" ";return d(a,{color:_?Q.colors.primary:Q.colors.text.primary,children:[w," ",B]},void 0,!0,void 0,this)};return d(i1,{flexDirection:"column",height:"100%",children:[d(i1,{paddingX:2,paddingY:1,borderStyle:"single",borderColor:Q.colors.border.light,children:d(a,{bold:!0,color:Q.colors.primary,children:"\uD83C\uDFA8 主题选择器"},void 0,!1,void 0,this)},void 0,!1,void 0,this),d(i1,{flexDirection:"row",flexGrow:1,children:[d(i1,{width:"40%",borderStyle:"single",borderColor:Q.colors.border.light,paddingX:1,children:d(i1,{flexDirection:"column",children:[d(i1,{paddingTop:1,paddingBottom:1,children:d(a,{bold:!0,color:Q.colors.text.primary,children:["可用主题 (",AU.length,")"]},void 0,!0,void 0,this)},void 0,!1,void 0,this),d(Kb,{items:AU,initialIndex:X>=0?X:0,onSelect:K,onHighlight:W,itemComponent:O},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this),d(i1,{width:"60%",flexDirection:"column",borderStyle:"single",borderColor:Q.colors.border.light,children:[d(Wb,{theme:Q},void 0,!1,void 0,this),d(Ub,{theme:Q},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),d(i1,{paddingX:2,paddingY:1,borderStyle:"single",borderColor:Q.colors.border.light,children:d(a,{color:Q.colors.text.muted,children:G?"正在保存...":"Enter: 选择主题 | Esc: 取消"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)};import{jsxDEV as a0}from"react/jsx-dev-runtime";var t$=i("UI"),VU=({debug:$,...Z})=>{if($)t$.debug("[Debug] BladeInterface props:",{permissionMode:Z.permissionMode,yolo:Z.yolo,maxTurns:Z.maxTurns});let X=O9(!1),Y=O9(!1),Q=O9(!1),J=O9(null),G=NK(),q=bK(),K=f6(),W=VK(),U=RK(),H=T2(),F=P2(),O=yK(),z=U8(),_=S2(),{exit:B}=Hb(),L=G==="ready",w=G==="needsSetup",R=G==="idle",{confirmationState:D,confirmationHandler:V,handleResponse:I}=aK(),{executeCommand:v,handleAbort:N}=gK(Z.systemPrompt,Z.appendSystemPrompt,V,Z.maxTurns),{getPreviousCommand:k,getNextCommand:m,addToHistory:s}=lK();JW();let S=nK("",0),T=s$(async()=>{let q0=z,S0;if(q0==="default")S0="autoEdit";else if(q0==="autoEdit")S0="plan";else if(q0==="plan")S0="spec";else if(q0==="spec")S0="default";else S0="default";try{if(await x0().setPermissionMode(S0),S0==="spec")try{let I$=d0.getInstance();await I$.initialize(process.cwd());let J1=await I$.listSpecs();if(J1.length>0){let o1=J1[0];await I$.loadSpec(o1.name),F.addAssistantMessage(`\uD83D\uDCCB **已进入 Spec 模式**
|
|
2826
2826
|
|
|
2827
2827
|
`+`检测到已存在的 Spec: **${o1.name}**
|
|
2828
2828
|
`+`当前阶段: ${o1.phase}
|
|
@@ -2833,6 +2833,6 @@ ${u}
|
|
|
2833
2833
|
`+"`提案 → 需求 → 设计 → 任务 → 实现`\n\n"+'例如:"实现用户认证功能" 或 "添加暗黑模式支持"')}catch(I$){t$.warn("Failed to initialize SpecManager:",I$),F.addAssistantMessage(`\uD83D\uDCCB **已进入 Spec 模式**
|
|
2834
2834
|
|
|
2835
2835
|
`+`请告诉我你想实现什么功能,我会引导你完成整个工作流:
|
|
2836
|
-
`+"`提案 → 需求 → 设计 → 任务 → 实现`\n\n"+'例如:"实现用户认证功能" 或 "添加暗黑模式支持"')}}catch(I$){t$.error("❌ 权限模式切换失败:",I$ instanceof Error?I$.message:I$)}}),c=s$(async(q0)=>{try{await x0().addModel({name:q0.name,provider:q0.provider,apiKey:q0.apiKey,baseUrl:q0.baseUrl,model:q0.model}),H.setInitializationStatus("ready")}catch(S0){t$.error("❌ 初始化配置保存失败:",S0 instanceof Error?S0.message:S0),H.setInitializationStatus("ready")}}),j=s$(()=>{if(K==="shortcuts")H.closeModal();else H.setActiveModal("shortcuts")}),{showSuggestions:M,suggestions:b,selectedSuggestionIndex:n}=QW(S,v,k,m,s,N,_,T,j,K==="shortcuts");V2(()=>{if(S.value&&K==="shortcuts")H.closeModal()},[S.value,K,H]);let y=s$(async()=>{try{if(typeof Z.resume==="string"&&Z.resume!=="true"){let S0=await m1.loadSession(Z.resume),I$=S0.map((J1,o1)=>({id:`restored-${Date.now()}-${o1}`,role:J1.role,content:typeof J1.content==="string"?J1.content:JSON.stringify(J1.content),timestamp:Date.now()-(S0.length-o1)*1000}));F.restoreSession(Z.resume,I$);return}let q0=await m1.listSessions();if(q0.length===0)t$.error("没有找到历史会话"),W8(1);H.showSessionSelector(q0)}catch(q0){t$.error("[BladeInterface] 加载会话失败:",q0),W8(1)}});V2(()=>{if(X.current)return;if(!Z.resume)return;X.current=!0,y()},[Z.resume,y]);let u=s$(async(q0)=>{let S0=D.details?.type;if(S0==="enterPlanMode"&&q0.approved)try{await x0().setPermissionMode("plan"),t$.debug("[BladeInterface] Entered Plan mode")}catch(I$){t$.error("[BladeInterface] Failed to enter Plan mode:",I$)}if(S0==="exitPlanMode"&&q0.approved)t$.debug("[BladeInterface] ExitPlanMode approved, Store auto-synced");I(q0)}),t=s$(()=>{F.addAssistantMessage("❌ 设置已取消"),F.addAssistantMessage("Blade 需要 API 配置才能正常工作。"),F.addAssistantMessage("您可以稍后运行 Blade 重新进入设置向导。"),W8(0)}),g=s$(()=>{H.closeModal()}),X0=s$(async(q0)=>{try{let S0=await m1.loadSession(q0),I$=S0.map((J1,o1)=>({id:`restored-${Date.now()}-${o1}`,role:J1.role,content:typeof J1.content==="string"?J1.content:JSON.stringify(J1.content),timestamp:Date.now()-(S0.length-o1)*1000}));F.restoreSession(q0,I$),H.closeModal()}catch(S0){t$.error("[BladeInterface] Failed to restore session:",S0),H.closeModal()}}),h=s$(()=>{if(Z.resume)B();else H.closeModal()}),L0=s$((q0)=>{H.showModelEditWizard(q0)}),G0=s$((q0)=>{F.addAssistantMessage(`✅ 已添加模型配置: ${q0.name},并已切换到该模型`),g()}),w0=s$((q0)=>{F.addAssistantMessage(`✅ 已更新模型配置: ${q0.name}`),g()});V2(()=>{if(w){O.setFocus("model-config-wizard");return}if(D.isVisible)O.setFocus("confirmation-prompt");else if(K==="sessionSelector")O.setFocus("session-selector");else if(K==="themeSelector")O.setFocus("theme-selector");else if(K==="modelSelector")O.setFocus("model-selector");else if(K==="modelAddWizard"||K==="modelEditWizard")O.setFocus("model-config-wizard");else if(K==="permissionsManager")O.setFocus("permissions-manager");else if(K==="agentsManager")O.setFocus("agents-manager");else if(K==="agentCreationWizard")O.setFocus("agent-creation-wizard");else if(K==="hooksManager")O.setFocus("hooks-manager");else if(K==="shortcuts")O.setFocus("main-input");else O.setFocus("main-input")},[w,D.isVisible,K,O.setFocus]),V2(()=>{if(!L||Q.current)return;if(mX().length>0){Q.current=!0;return}Q.current=!0,F.addAssistantMessage("请输入您的问题,我将为您提供帮助。")},[L]),V2(()=>{if(!q)return;if(J.current===q)return;if(J.current=q,G==="error")F.addAssistantMessage(`❌ 初始化失败: ${q}`);else F.addAssistantMessage(`❌ ${q}`),F.addAssistantMessage("请重新尝试设置,或检查文件权限")},[q,G,F.addAssistantMessage]);let Y$=s$(async(q0)=>{try{await v({displayText:q0,text:q0,images:[],parts:[{type:"text",text:q0}]})}catch(S0){let I$=S0 instanceof Error?S0.message:"无法发送初始消息";F.addAssistantMessage(`❌ 初始消息发送失败:${I$}`)}});V2(()=>{let q0=Z.initialMessage?.trim();if(!q0||Y.current||!L||w)return;Y.current=!0,s(q0),Y$(q0)},[Z.initialMessage,L,w,v,s]);let G$=s$(async(q0)=>{try{await x0().setPermissionMode(q0)}catch(S0){t$.error("❌ 权限模式初始化失败:",S0 instanceof Error?S0.message:S0)}});if(V2(()=>{let q0=Z.permissionMode;if($)t$.debug("[Debug] permissionMode from CLI:",q0),t$.debug("[Debug] current permissionMode:",z);if(!q0||q0===z)return;G$(q0)},[Z.permissionMode,z]),R)return null;if(w)return a0(iZ,{mode:"setup",onComplete:c,onCancel:t},void 0,!1,void 0,this);if($)t$.debug("[Debug] 渲染主界面,条件检查:",{confirmationVisible:D.isVisible,activeModal:K});let r1=K==="modelSelector",Q$=U,Q0=K==="modelAddWizard"?"add":K==="modelEditWizard"&&Q$?"edit":null,R$=r1||Boolean(Q0),V0=K==="agentsManager",n1=K==="agentCreationWizard",d$=K==="skillsManager",B4=K==="pluginsManager",w1=Q$?{name:Q$.name,provider:Q$.provider,baseUrl:Q$.baseUrl,apiKey:Q$.apiKey,model:Q$.model}:void 0,D8=D.isVisible&&D.details?D.details.type==="askUserQuestion"&&D.details.questions?a0(zU,{questions:D.details.questions,onComplete:(q0)=>u({approved:!0,answers:q0}),onCancel:()=>u({approved:!1})},void 0,!1,void 0,this):a0(IW,{details:D.details,onResponse:u},void 0,!1,void 0,this):K==="themeSelector"?a0(RU,{},void 0,!1,void 0,this):K==="permissionsManager"?a0(HU,{onClose:g},void 0,!1,void 0,this):K==="sessionSelector"?a0(BU,{sessions:W,onSelect:X0,onCancel:h},void 0,!1,void 0,this):K==="hooksManager"?a0(vW,{onClose:g},void 0,!1,void 0,this):null,$X=Boolean(D8);return a0(u4,{flexDirection:"column",width:"100%",overflow:"hidden",children:[D8,a0(u4,{flexDirection:"column",display:$X?"none":"flex",children:[z==="spec"&&a0(NU,{},void 0,!1,void 0,this),a0(ZU,{},void 0,!1,void 0,this),a0(aW,{paused:$X},void 0,!1,void 0,this),a0(dW,{input:S.value,cursorPosition:S.cursorPosition,onChange:S.setValue,onChangeCursorPosition:S.setCursorPosition,onAddPasteMapping:S.addPasteMapping,onAddImagePasteMapping:S.addImagePasteMapping},void 0,!1,void 0,this),r1&&a0(u4,{marginTop:1,paddingX:2,children:a0(GU,{onClose:g,onEdit:L0},void 0,!1,void 0,this)},void 0,!1,void 0,this),Q0&&a0(u4,{marginTop:1,paddingX:2,children:a0(iZ,{mode:Q0,modelId:Q$?.id,initialConfig:Q0==="edit"?w1:void 0,onComplete:Q0==="edit"?w0:G0,onCancel:g},void 0,!1,void 0,this)},void 0,!1,void 0,this),V0&&a0(u4,{marginTop:1,paddingX:2,children:a0(UW,{onComplete:g,onCancel:g},void 0,!1,void 0,this)},void 0,!1,void 0,this),n1&&a0(u4,{marginTop:1,paddingX:2,children:a0(B3,{onComplete:g,onCancel:g},void 0,!1,void 0,this)},void 0,!1,void 0,this),d$&&a0(u4,{marginTop:1,paddingX:2,children:a0(LU,{onComplete:g,onCancel:g},void 0,!1,void 0,this)},void 0,!1,void 0,this),B4&&a0(u4,{marginTop:1,paddingX:2,children:a0(FU,{onComplete:g,onCancel:g},void 0,!1,void 0,this)},void 0,!1,void 0,this),a0(zW,{suggestions:b,selectedIndex:n,visible:M&&!R$},void 0,!1,void 0,this),a0(OW,{},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)};import{Box as Fb,Text as g4}from"ink";import Ob from"react";import{jsxDEV as z4}from"react/jsx-dev-runtime";class z9 extends Ob.Component{constructor($){super($);this.state={hasError:!1,error:null,errorInfo:null}}static getDerivedStateFromError($){return{hasError:!0,error:$,errorInfo:null}}componentDidCatch($,Z){this.setState({error:$,errorInfo:Z}),console.error("未捕获的错误:",$,Z)}render(){if(this.state.hasError)return z4(Fb,{flexDirection:"column",padding:1,borderStyle:"round",borderColor:"red",children:[z4(g4,{color:"red",children:"\uD83D\uDCA5 应用发生错误"},void 0,!1,void 0,this),z4(g4,{children:" "},void 0,!1,void 0,this),z4(g4,{color:"red",children:this.state.error?.message},void 0,!1,void 0,this),z4(g4,{children:" "},void 0,!1,void 0,this),z4(g4,{color:"gray",children:"错误详情:"},void 0,!1,void 0,this),z4(g4,{color:"gray",children:this.state.error?.stack},void 0,!1,void 0,this),z4(g4,{children:" "},void 0,!1,void 0,this),z4(g4,{color:"yellow",children:"请重启应用或联系开发者"},void 0,!1,void 0,this)]},void 0,!0,void 0,this);return this.props.children}}import{Box as D2,Text as _4,useInput as zb}from"ink";import{useState as nZ}from"react";import{jsxDEV as p$}from"react/jsx-dev-runtime";var _9=[{key:"update",label:"Update now",description:`runs \`${GZ()}\``},{key:"skip",label:"Skip",description:""},{key:"skip_until_next",label:"Skip until next version",description:""}],DU=({versionInfo:$,onComplete:Z})=>{let[X,Y]=nZ(0),[Q,J]=nZ(!1),[G,q]=nZ(null);zb((W,U)=>{if(U.ctrl&&W==="c"){F2().shutdown("SIGINT",0);return}if(Q||G)return;if(U.upArrow||W==="k")Y((H)=>H>0?H-1:_9.length-1);else if(U.downArrow||W==="j")Y((H)=>H<_9.length-1?H+1:0);else if(U.return)K(_9[X].key);else if(W==="1")K("update");else if(W==="2")K("skip");else if(W==="3")K("skip_until_next")});let K=async(W)=>{switch(W){case"update":{J(!0);let U=await KK();q(U.message),setTimeout(()=>{F2().shutdown("SIGINT",0)},1500);break}case"skip":Z();break;case"skip_until_next":if($.latestVersion)await qK($.latestVersion);Z();break}};if(G)return p$(D2,{flexDirection:"column",marginY:1,children:p$(_4,{children:G},void 0,!1,void 0,this)},void 0,!1,void 0,this);if(Q)return p$(D2,{flexDirection:"column",marginY:1,children:p$(_4,{color:"cyan",children:"Updating..."},void 0,!1,void 0,this)},void 0,!1,void 0,this);return p$(D2,{flexDirection:"column",marginY:1,children:[p$(_4,{color:"yellow",bold:!0,children:["✨ Update available! ",p$(_4,{color:"gray",children:[$.currentVersion," ","→"," ",$.latestVersion]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),p$(D2,{marginTop:1,children:p$(_4,{color:"gray",children:["Release notes:"," ",p$(_4,{color:"cyan",underline:!0,children:$.releaseNotesUrl},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this),p$(D2,{flexDirection:"column",marginTop:1,children:_9.map((W,U)=>{let H=U===X,F=H?"› ":" ",O=`${U+1}. `;return p$(D2,{children:p$(_4,{color:H?"cyan":void 0,children:[F,O,W.label,W.description&&p$(_4,{color:"gray",children:[" (",W.description,")"]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)},W.key,!1,void 0,this)})},void 0,!1,void 0,this),p$(D2,{marginTop:1,children:p$(_4,{color:"gray",children:"Press enter to continue"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)};i4();function V8($){return($ instanceof Error?$.message:String($)).replace(/sk-[a-zA-Z0-9]{32,}/g,"sk-***").replace(/apiKey['":\s]+[a-zA-Z0-9-_]+/gi,"apiKey: ***").replace(/API_KEY['":\s=]+[a-zA-Z0-9-_]+/gi,"API_KEY=***")}import{jsxDEV as B9}from"react/jsx-dev-runtime";function Bb($){let Z=wY();if(!$.models)$.models=[];let X=LY();if(!$.models.some((Q)=>Q.id===X)){if($.models.unshift(Z),$.debug)console.log("[Debug] 已添加内置免费模型到模型列表")}if(!$.currentModelId)$.currentModelId=Z.id,console.log("✨ 已自动配置内置免费模型: GLM-4.7");if(K0().config.actions.setConfig($),$.debug)console.log("[Debug] 模型配置检查通过,准备就绪");$4().setInitializationStatus("ready")}var jU=($)=>{let[Z,X]=oZ(!1),[Y,Q]=oZ(null),[J,G]=oZ(!1),q=MU(async()=>{let W=K0().config.config??j2,U=b9(W,$);if(Bb(U),U.debug)console.error("[Debug] 运行时配置:",U);let H=U.theme;if(H&&g$.hasTheme(H)){if(g$.setTheme(H),$.debug)console.log(`✓ 已加载主题: ${H}`)}try{let F=J$.loadFromStandardLocations();if($.debug&&F>0)console.log(`✓ 已加载 ${F} 个 subagents: ${J$.getAllNames().join(", ")}`)}catch(F){if($.debug)console.warn("⚠️ Subagents 加载失败:",V8(F))}try{let F=M0.getInstance();if(F.loadConfig(U.hooks||{}),$.debug&&U.hooks?.enabled)console.log("✓ Hooks 系统已启用");if(F.isEnabled()){let O=K0(),z=O.session.sessionId,_=O.config.config?.permissionMode||"default",B=!!$.resume,L=await F.executeSessionStartHooks({projectDir:process.cwd(),sessionId:z,permissionMode:_,isResume:B,resumeSessionId:typeof $.resume==="string"?$.resume:void 0});if(L.env){for(let[w,R]of Object.entries(L.env))process.env[w]=R;if($.debug)console.log("✓ SessionStart hooks 注入环境变量:",Object.keys(L.env).join(", "))}if(L.warning&&$.debug)console.warn("⚠️ SessionStart hooks 警告:",L.warning)}}catch(F){if($.debug)console.warn("⚠️ Hooks 初始化失败:",V8(F))}try{let F=await e4();if($.debug&&F.skills.length>0)console.log(`✓ 已加载 ${F.skills.length} 个 skills: ${F.skills.map((O)=>O.name).join(", ")}`);if(F.errors.length>0&&$.debug)for(let O of F.errors)console.warn(`⚠️ Skill 加载错误 (${O.path}): ${O.error}`)}catch(F){if($.debug)console.warn("⚠️ Skills 初始化失败:",V8(F))}try{let F=await tq(process.cwd());if($.debug&&F.commands.length>0)console.log(`✓ 已加载 ${F.commands.length} 个自定义命令: ${F.commands.map((O)=>O.name).join(", ")}`);if(F.errors.length>0&&$.debug)for(let O of F.errors)console.warn(`⚠️ 自定义命令加载错误 (${O.path}): ${O.error}`)}catch(F){if($.debug)console.warn("⚠️ 自定义命令初始化失败:",V8(F))}try{let O=await a$().initialize(process.cwd(),$.pluginDir||[]);if($.debug&&O.plugins.length>0)console.log(`✓ 已加载 ${O.plugins.length} 个插件: ${O.plugins.map((z)=>z.manifest.name).join(", ")}`);if(O.plugins.length>0){let z=await v4();if($.debug){let{totalCommands:_,totalSkills:B,totalAgents:L,totalMcpServers:w}=z;console.log(` ✓ 已集成: ${_} 命令, ${B} 技能, ${L} 代理, ${w} MCP 服务器`)}}if(O.errors.length>0&&$.debug)for(let z of O.errors)console.warn(`⚠️ 插件加载错误 (${z.path}): ${z.error}`)}catch(F){if($.debug)console.warn("⚠️ 插件系统初始化失败:",V8(F))}FK(async()=>{T$.getInstance().killAll(),await N$.getInstance().disconnectAll(),M0.getInstance().cleanup()}),X(!0)}),K=MU(async()=>{if($.versionCheckPromise){let W=await $.versionCheckPromise;if(W){Q(W),G(!0);return}}await q()});if(_b(()=>{K()},[]),J&&Y)return B9(z9,{children:B9(DU,{versionInfo:Y,onComplete:()=>{G(!1),q()}},void 0,!1,void 0,this)},void 0,!1,void 0,this);if(!Z)return null;return B9(z9,{children:B9(VU,{...$},void 0,!1,void 0,this)},void 0,!1,void 0,this)};var eZ=TU(process.argv),PU=eZ.indexOf("--debug");if(PU!==-1){let $=eZ[PU+1],Z=$&&!$.startsWith("-")?$:!0;N1.setGlobalDebug(Z)}async function jb(){OK();let $=WK();if(await ZK())return;if(eZ.includes("--acp")){let{runAcpIntegration:X}=await Promise.resolve().then(() => (EU(),vU));await X();return}let Z=Mb(TU(process.argv)).scriptName(c4.scriptName).usage(c4.usage).version(c4.version).locale(c4.locale).showHelpOnFail(c4.showHelpOnFail).demandCommand(0,"").recommendCommands().strict(c4.strict).parserConfiguration({"populate--":!0}).options(JX).middleware([gX,cX,lX]).command(KY).command(iX).command(UK).command(aX).completion("completion",!1).help("help","Show help").alias("help","h").alias("version","V").fail((X,Y,Q)=>{if(Y)console.error("\uD83D\uDCA5 An error occurred:"),console.error(Y.message),console.error(`
|
|
2836
|
+
`+"`提案 → 需求 → 设计 → 任务 → 实现`\n\n"+'例如:"实现用户认证功能" 或 "添加暗黑模式支持"')}}catch(I$){t$.error("❌ 权限模式切换失败:",I$ instanceof Error?I$.message:I$)}}),c=s$(async(q0)=>{try{await x0().addModel({name:q0.name,provider:q0.provider,apiKey:q0.apiKey,baseUrl:q0.baseUrl,model:q0.model}),H.setInitializationStatus("ready")}catch(S0){t$.error("❌ 初始化配置保存失败:",S0 instanceof Error?S0.message:S0),H.setInitializationStatus("ready")}}),j=s$(()=>{if(K==="shortcuts")H.closeModal();else H.setActiveModal("shortcuts")}),{showSuggestions:M,suggestions:b,selectedSuggestionIndex:n}=QW(S,v,k,m,s,N,_,T,j,K==="shortcuts");V4(()=>{if(S.value&&K==="shortcuts")H.closeModal()},[S.value,K,H]);let y=s$(async()=>{try{if(typeof Z.resume==="string"&&Z.resume!=="true"){let S0=await m1.loadSession(Z.resume),I$=S0.map((J1,o1)=>({id:`restored-${Date.now()}-${o1}`,role:J1.role,content:typeof J1.content==="string"?J1.content:JSON.stringify(J1.content),timestamp:Date.now()-(S0.length-o1)*1000}));F.restoreSession(Z.resume,I$);return}let q0=await m1.listSessions();if(q0.length===0)t$.error("没有找到历史会话"),W8(1);H.showSessionSelector(q0)}catch(q0){t$.error("[BladeInterface] 加载会话失败:",q0),W8(1)}});V4(()=>{if(X.current)return;if(!Z.resume)return;X.current=!0,y()},[Z.resume,y]);let u=s$(async(q0)=>{let S0=D.details?.type;if(S0==="enterPlanMode"&&q0.approved)try{await x0().setPermissionMode("plan"),t$.debug("[BladeInterface] Entered Plan mode")}catch(I$){t$.error("[BladeInterface] Failed to enter Plan mode:",I$)}if(S0==="exitPlanMode"&&q0.approved)t$.debug("[BladeInterface] ExitPlanMode approved, Store auto-synced");I(q0)}),t=s$(()=>{F.addAssistantMessage("❌ 设置已取消"),F.addAssistantMessage("Blade 需要 API 配置才能正常工作。"),F.addAssistantMessage("您可以稍后运行 Blade 重新进入设置向导。"),W8(0)}),g=s$(()=>{H.closeModal()}),X0=s$(async(q0)=>{try{let S0=await m1.loadSession(q0),I$=S0.map((J1,o1)=>({id:`restored-${Date.now()}-${o1}`,role:J1.role,content:typeof J1.content==="string"?J1.content:JSON.stringify(J1.content),timestamp:Date.now()-(S0.length-o1)*1000}));F.restoreSession(q0,I$),H.closeModal()}catch(S0){t$.error("[BladeInterface] Failed to restore session:",S0),H.closeModal()}}),h=s$(()=>{if(Z.resume)B();else H.closeModal()}),L0=s$((q0)=>{H.showModelEditWizard(q0)}),G0=s$((q0)=>{F.addAssistantMessage(`✅ 已添加模型配置: ${q0.name},并已切换到该模型`),g()}),w0=s$((q0)=>{F.addAssistantMessage(`✅ 已更新模型配置: ${q0.name}`),g()});V4(()=>{if(w){O.setFocus("model-config-wizard");return}if(D.isVisible)O.setFocus("confirmation-prompt");else if(K==="sessionSelector")O.setFocus("session-selector");else if(K==="themeSelector")O.setFocus("theme-selector");else if(K==="modelSelector")O.setFocus("model-selector");else if(K==="modelAddWizard"||K==="modelEditWizard")O.setFocus("model-config-wizard");else if(K==="permissionsManager")O.setFocus("permissions-manager");else if(K==="agentsManager")O.setFocus("agents-manager");else if(K==="agentCreationWizard")O.setFocus("agent-creation-wizard");else if(K==="hooksManager")O.setFocus("hooks-manager");else if(K==="shortcuts")O.setFocus("main-input");else O.setFocus("main-input")},[w,D.isVisible,K,O.setFocus]),V4(()=>{if(!L||Q.current)return;if(mX().length>0){Q.current=!0;return}Q.current=!0,F.addAssistantMessage("请输入您的问题,我将为您提供帮助。")},[L]),V4(()=>{if(!q)return;if(J.current===q)return;if(J.current=q,G==="error")F.addAssistantMessage(`❌ 初始化失败: ${q}`);else F.addAssistantMessage(`❌ ${q}`),F.addAssistantMessage("请重新尝试设置,或检查文件权限")},[q,G,F.addAssistantMessage]);let Y$=s$(async(q0)=>{try{await v({displayText:q0,text:q0,images:[],parts:[{type:"text",text:q0}]})}catch(S0){let I$=S0 instanceof Error?S0.message:"无法发送初始消息";F.addAssistantMessage(`❌ 初始消息发送失败:${I$}`)}});V4(()=>{let q0=Z.initialMessage?.trim();if(!q0||Y.current||!L||w)return;Y.current=!0,s(q0),Y$(q0)},[Z.initialMessage,L,w,v,s]);let G$=s$(async(q0)=>{try{await x0().setPermissionMode(q0)}catch(S0){t$.error("❌ 权限模式初始化失败:",S0 instanceof Error?S0.message:S0)}});if(V4(()=>{let q0=Z.permissionMode;if($)t$.debug("[Debug] permissionMode from CLI:",q0),t$.debug("[Debug] current permissionMode:",z);if(!q0||q0===z)return;G$(q0)},[Z.permissionMode,z]),R)return null;if(w)return a0(iZ,{mode:"setup",onComplete:c,onCancel:t},void 0,!1,void 0,this);if($)t$.debug("[Debug] 渲染主界面,条件检查:",{confirmationVisible:D.isVisible,activeModal:K});let r1=K==="modelSelector",Q$=U,Q0=K==="modelAddWizard"?"add":K==="modelEditWizard"&&Q$?"edit":null,R$=r1||Boolean(Q0),V0=K==="agentsManager",n1=K==="agentCreationWizard",d$=K==="skillsManager",B2=K==="pluginsManager",w1=Q$?{name:Q$.name,provider:Q$.provider,baseUrl:Q$.baseUrl,apiKey:Q$.apiKey,model:Q$.model}:void 0,D8=D.isVisible&&D.details?D.details.type==="askUserQuestion"&&D.details.questions?a0(zU,{questions:D.details.questions,onComplete:(q0)=>u({approved:!0,answers:q0}),onCancel:()=>u({approved:!1})},void 0,!1,void 0,this):a0(IW,{details:D.details,onResponse:u},void 0,!1,void 0,this):K==="themeSelector"?a0(RU,{},void 0,!1,void 0,this):K==="permissionsManager"?a0(HU,{onClose:g},void 0,!1,void 0,this):K==="sessionSelector"?a0(BU,{sessions:W,onSelect:X0,onCancel:h},void 0,!1,void 0,this):K==="hooksManager"?a0(vW,{onClose:g},void 0,!1,void 0,this):null,$X=Boolean(D8);return a0(u2,{flexDirection:"column",width:"100%",overflow:"hidden",children:[D8,a0(u2,{flexDirection:"column",display:$X?"none":"flex",children:[z==="spec"&&a0(NU,{},void 0,!1,void 0,this),a0(ZU,{},void 0,!1,void 0,this),a0(aW,{paused:$X},void 0,!1,void 0,this),a0(dW,{input:S.value,cursorPosition:S.cursorPosition,onChange:S.setValue,onChangeCursorPosition:S.setCursorPosition,onAddPasteMapping:S.addPasteMapping,onAddImagePasteMapping:S.addImagePasteMapping},void 0,!1,void 0,this),r1&&a0(u2,{marginTop:1,paddingX:2,children:a0(GU,{onClose:g,onEdit:L0},void 0,!1,void 0,this)},void 0,!1,void 0,this),Q0&&a0(u2,{marginTop:1,paddingX:2,children:a0(iZ,{mode:Q0,modelId:Q$?.id,initialConfig:Q0==="edit"?w1:void 0,onComplete:Q0==="edit"?w0:G0,onCancel:g},void 0,!1,void 0,this)},void 0,!1,void 0,this),V0&&a0(u2,{marginTop:1,paddingX:2,children:a0(UW,{onComplete:g,onCancel:g},void 0,!1,void 0,this)},void 0,!1,void 0,this),n1&&a0(u2,{marginTop:1,paddingX:2,children:a0(B3,{onComplete:g,onCancel:g},void 0,!1,void 0,this)},void 0,!1,void 0,this),d$&&a0(u2,{marginTop:1,paddingX:2,children:a0(LU,{onComplete:g,onCancel:g},void 0,!1,void 0,this)},void 0,!1,void 0,this),B2&&a0(u2,{marginTop:1,paddingX:2,children:a0(FU,{onComplete:g,onCancel:g},void 0,!1,void 0,this)},void 0,!1,void 0,this),a0(zW,{suggestions:b,selectedIndex:n,visible:M&&!R$},void 0,!1,void 0,this),a0(OW,{},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)};import{Box as Fb,Text as g2}from"ink";import Ob from"react";import{jsxDEV as z2}from"react/jsx-dev-runtime";class z9 extends Ob.Component{constructor($){super($);this.state={hasError:!1,error:null,errorInfo:null}}static getDerivedStateFromError($){return{hasError:!0,error:$,errorInfo:null}}componentDidCatch($,Z){this.setState({error:$,errorInfo:Z}),console.error("未捕获的错误:",$,Z)}render(){if(this.state.hasError)return z2(Fb,{flexDirection:"column",padding:1,borderStyle:"round",borderColor:"red",children:[z2(g2,{color:"red",children:"\uD83D\uDCA5 应用发生错误"},void 0,!1,void 0,this),z2(g2,{children:" "},void 0,!1,void 0,this),z2(g2,{color:"red",children:this.state.error?.message},void 0,!1,void 0,this),z2(g2,{children:" "},void 0,!1,void 0,this),z2(g2,{color:"gray",children:"错误详情:"},void 0,!1,void 0,this),z2(g2,{color:"gray",children:this.state.error?.stack},void 0,!1,void 0,this),z2(g2,{children:" "},void 0,!1,void 0,this),z2(g2,{color:"yellow",children:"请重启应用或联系开发者"},void 0,!1,void 0,this)]},void 0,!0,void 0,this);return this.props.children}}import{Box as D4,Text as _2,useInput as zb}from"ink";import{useState as nZ}from"react";import{jsxDEV as p$}from"react/jsx-dev-runtime";var _9=[{key:"update",label:"Update now",description:`runs \`${GZ()}\``},{key:"skip",label:"Skip",description:""},{key:"skip_until_next",label:"Skip until next version",description:""}],DU=({versionInfo:$,onComplete:Z})=>{let[X,Y]=nZ(0),[Q,J]=nZ(!1),[G,q]=nZ(null);zb((W,U)=>{if(U.ctrl&&W==="c"){F4().shutdown("SIGINT",0);return}if(Q||G)return;if(U.upArrow||W==="k")Y((H)=>H>0?H-1:_9.length-1);else if(U.downArrow||W==="j")Y((H)=>H<_9.length-1?H+1:0);else if(U.return)K(_9[X].key);else if(W==="1")K("update");else if(W==="2")K("skip");else if(W==="3")K("skip_until_next")});let K=async(W)=>{switch(W){case"update":{J(!0);let U=await KK();q(U.message),setTimeout(()=>{F4().shutdown("SIGINT",0)},1500);break}case"skip":Z();break;case"skip_until_next":if($.latestVersion)await qK($.latestVersion);Z();break}};if(G)return p$(D4,{flexDirection:"column",marginY:1,children:p$(_2,{children:G},void 0,!1,void 0,this)},void 0,!1,void 0,this);if(Q)return p$(D4,{flexDirection:"column",marginY:1,children:p$(_2,{color:"cyan",children:"Updating..."},void 0,!1,void 0,this)},void 0,!1,void 0,this);return p$(D4,{flexDirection:"column",marginY:1,children:[p$(_2,{color:"yellow",bold:!0,children:["✨ Update available! ",p$(_2,{color:"gray",children:[$.currentVersion," ","→"," ",$.latestVersion]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),p$(D4,{marginTop:1,children:p$(_2,{color:"gray",children:["Release notes:"," ",p$(_2,{color:"cyan",underline:!0,children:$.releaseNotesUrl},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this),p$(D4,{flexDirection:"column",marginTop:1,children:_9.map((W,U)=>{let H=U===X,F=H?"› ":" ",O=`${U+1}. `;return p$(D4,{children:p$(_2,{color:H?"cyan":void 0,children:[F,O,W.label,W.description&&p$(_2,{color:"gray",children:[" (",W.description,")"]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)},W.key,!1,void 0,this)})},void 0,!1,void 0,this),p$(D4,{marginTop:1,children:p$(_2,{color:"gray",children:"Press enter to continue"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)};i2();function V8($){return($ instanceof Error?$.message:String($)).replace(/sk-[a-zA-Z0-9]{32,}/g,"sk-***").replace(/apiKey['":\s]+[a-zA-Z0-9-_]+/gi,"apiKey: ***").replace(/API_KEY['":\s=]+[a-zA-Z0-9-_]+/gi,"API_KEY=***")}import{jsxDEV as B9}from"react/jsx-dev-runtime";function Bb($){let Z=wY();if(!$.models)$.models=[];let X=LY();if(!$.models.some((Q)=>Q.id===X)){if($.models.unshift(Z),$.debug)console.log("[Debug] 已添加内置免费模型到模型列表")}if(!$.currentModelId)$.currentModelId=Z.id,console.log("✨ 已自动配置内置免费模型: GLM-4.7");if(K0().config.actions.setConfig($),$.debug)console.log("[Debug] 模型配置检查通过,准备就绪");$2().setInitializationStatus("ready")}var jU=($)=>{let[Z,X]=oZ(!1),[Y,Q]=oZ(null),[J,G]=oZ(!1),q=MU(async()=>{let W=K0().config.config??j4,U=b9(W,$);if(Bb(U),U.debug)console.error("[Debug] 运行时配置:",U);let H=U.theme;if(H&&g$.hasTheme(H)){if(g$.setTheme(H),$.debug)console.log(`✓ 已加载主题: ${H}`)}try{let F=J$.loadFromStandardLocations();if($.debug&&F>0)console.log(`✓ 已加载 ${F} 个 subagents: ${J$.getAllNames().join(", ")}`)}catch(F){if($.debug)console.warn("⚠️ Subagents 加载失败:",V8(F))}try{let F=M0.getInstance();if(F.loadConfig(U.hooks||{}),$.debug&&U.hooks?.enabled)console.log("✓ Hooks 系统已启用");if(F.isEnabled()){let O=K0(),z=O.session.sessionId,_=O.config.config?.permissionMode||"default",B=!!$.resume,L=await F.executeSessionStartHooks({projectDir:process.cwd(),sessionId:z,permissionMode:_,isResume:B,resumeSessionId:typeof $.resume==="string"?$.resume:void 0});if(L.env){for(let[w,R]of Object.entries(L.env))process.env[w]=R;if($.debug)console.log("✓ SessionStart hooks 注入环境变量:",Object.keys(L.env).join(", "))}if(L.warning&&$.debug)console.warn("⚠️ SessionStart hooks 警告:",L.warning)}}catch(F){if($.debug)console.warn("⚠️ Hooks 初始化失败:",V8(F))}try{let F=await e2();if($.debug&&F.skills.length>0)console.log(`✓ 已加载 ${F.skills.length} 个 skills: ${F.skills.map((O)=>O.name).join(", ")}`);if(F.errors.length>0&&$.debug)for(let O of F.errors)console.warn(`⚠️ Skill 加载错误 (${O.path}): ${O.error}`)}catch(F){if($.debug)console.warn("⚠️ Skills 初始化失败:",V8(F))}try{let F=await tq(process.cwd());if($.debug&&F.commands.length>0)console.log(`✓ 已加载 ${F.commands.length} 个自定义命令: ${F.commands.map((O)=>O.name).join(", ")}`);if(F.errors.length>0&&$.debug)for(let O of F.errors)console.warn(`⚠️ 自定义命令加载错误 (${O.path}): ${O.error}`)}catch(F){if($.debug)console.warn("⚠️ 自定义命令初始化失败:",V8(F))}try{let O=await a$().initialize(process.cwd(),$.pluginDir||[]);if($.debug&&O.plugins.length>0)console.log(`✓ 已加载 ${O.plugins.length} 个插件: ${O.plugins.map((z)=>z.manifest.name).join(", ")}`);if(O.plugins.length>0){let z=await v2();if($.debug){let{totalCommands:_,totalSkills:B,totalAgents:L,totalMcpServers:w}=z;console.log(` ✓ 已集成: ${_} 命令, ${B} 技能, ${L} 代理, ${w} MCP 服务器`)}}if(O.errors.length>0&&$.debug)for(let z of O.errors)console.warn(`⚠️ 插件加载错误 (${z.path}): ${z.error}`)}catch(F){if($.debug)console.warn("⚠️ 插件系统初始化失败:",V8(F))}FK(async()=>{T$.getInstance().killAll(),await N$.getInstance().disconnectAll(),M0.getInstance().cleanup()}),X(!0)}),K=MU(async()=>{if($.versionCheckPromise){let W=await $.versionCheckPromise;if(W){Q(W),G(!0);return}}await q()});if(_b(()=>{K()},[]),J&&Y)return B9(z9,{children:B9(DU,{versionInfo:Y,onComplete:()=>{G(!1),q()}},void 0,!1,void 0,this)},void 0,!1,void 0,this);if(!Z)return null;return B9(z9,{children:B9(VU,{...$},void 0,!1,void 0,this)},void 0,!1,void 0,this)};var eZ=TU(process.argv),PU=eZ.indexOf("--debug");if(PU!==-1){let $=eZ[PU+1],Z=$&&!$.startsWith("-")?$:!0;N1.setGlobalDebug(Z)}async function jb(){OK();let $=WK();if(await ZK())return;if(eZ.includes("--acp")){let{runAcpIntegration:X}=await Promise.resolve().then(() => (EU(),vU));await X();return}let Z=Mb(TU(process.argv)).scriptName(c2.scriptName).usage(c2.usage).version(c2.version).locale(c2.locale).showHelpOnFail(c2.showHelpOnFail).demandCommand(0,"").recommendCommands().strict(c2.strict).parserConfiguration({"populate--":!0}).options(JX).middleware([gX,cX,lX]).command(KY).command(iX).command(UK).command(aX).completion("completion",!1).help("help","Show help").alias("help","h").alias("version","V").fail((X,Y,Q)=>{if(Y)console.error("\uD83D\uDCA5 An error occurred:"),console.error(Y.message),console.error(`
|
|
2837
2837
|
Stack trace:`),console.error(Y.stack),process.exit(1);if(X)console.error("❌ Invalid arguments:"),console.error(X),console.error(`
|
|
2838
2838
|
\uD83D\uDCA1 Did you mean:`),Q.showHelp(),process.exit(1)}).command("$0",!1,()=>{},async(X)=>{let Y=X._.slice(1),Q=Y.length>0?Y.join(" "):void 0,J={...X,initialMessage:Q,debug:X.debug,print:Boolean(X.print),versionCheckPromise:$};delete J._,delete J.$0,delete J.message,Vb(Db.createElement(jU,J),{patchConsole:!0,exitOnCtrlC:!1,alternateBuffer:!1})});try{await Z.parse()}catch(X){console.error("❌ Parse error:",X),process.exit(1)}}if(V$.main==V$.module)jb().catch(console.error);export{jb as main};
|