@blade-ai/agent-sdk 0.1.3 → 0.1.4
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/CHANGELOG.md +8 -0
- package/dist/index.js +469 -442
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,48 +1,48 @@
|
|
|
1
|
-
import{createRequire as F5}from"node:module";var A5=Object.create;var{getPrototypeOf:w5,defineProperty:Y4,getOwnPropertyNames:U5}=Object;var b5=Object.prototype.hasOwnProperty;var m0=($,V,W)=>{W=$!=null?A5(w5($)):{};let Q=V||!$||!$.__esModule?Y4(W,"default",{value:$,enumerable:!0}):W;for(let Z of U5($))if(!b5.call(Q,Z))Y4(Q,Z,{get:()=>$[Z],enumerable:!0});return Q};var b0=F5(import.meta.url);import{nanoid as s9}from"nanoid";import*as Z5 from"os";import*as Y5 from"path";import{nanoid as Z0}from"nanoid";var R1={DEFAULT:"default",AUTO_EDIT:"autoEdit",YOLO:"yolo",BYPASSALL:"bypassAll",PLAN:"plan",SPEC:"spec"},F0;((w)=>{w.PreToolUse="PreToolUse";w.PostToolUse="PostToolUse";w.PostToolUseFailure="PostToolUseFailure";w.PermissionRequest="PermissionRequest";w.UserPromptSubmit="UserPromptSubmit";w.SessionStart="SessionStart";w.SessionEnd="SessionEnd";w.Stop="Stop";w.SubagentStart="SubagentStart";w.SubagentStop="SubagentStop";w.TaskCompleted="TaskCompleted";w.Notification="Notification";w.Compaction="Compaction"})(F0||={});var J4={SYSTEM:"system",USER:"user",ASSISTANT:"assistant",TOOL:"tool"},H5={TURN_START:"turn_start",TURN_END:"turn_end",CONTENT:"content",THINKING:"thinking",TOOL_USE:"tool_use",TOOL_RESULT:"tool_result",USAGE:"usage",RESULT:"result",ERROR:"error"},D5={READONLY:"readonly",WRITE:"write",EXECUTE:"execute"},_5={ALLOW:"allow",DENY:"deny",ASK:"ask"},C5={APPROVE:"approve",BLOCK:"block",ASYNC:"async"},j5={ALLOW:"allow",DENY:"deny",ASK:"ask"},L5={COMMAND:"command",PROMPT:"prompt"},N5={SUCCESS:0,NON_BLOCKING_ERROR:1,BLOCKING_ERROR:2,TIMEOUT:124},R5={VALIDATION_ERROR:"validation_error",PERMISSION_DENIED:"permission_denied",EXECUTION_ERROR:"execution_error",TIMEOUT_ERROR:"timeout_error",NETWORK_ERROR:"network_error"};var S=R1;import{nanoid as G$}from"nanoid";var E1={enabled:!1,defaultTimeout:60,timeoutBehavior:"ignore",failureBehavior:"ignore",maxConcurrentHooks:5,PreToolUse:[],PostToolUse:[],PostToolUseFailure:[],PermissionRequest:[],UserPromptSubmit:[],SessionStart:[],SessionEnd:[],Stop:[],SubagentStart:[],SubagentStop:[],TaskCompleted:[],Notification:[],Compaction:[]};function z1($,V){return{...$,...V,PreToolUse:V.PreToolUse??$.PreToolUse,PostToolUse:V.PostToolUse??$.PostToolUse,PostToolUseFailure:V.PostToolUseFailure??$.PostToolUseFailure,PermissionRequest:V.PermissionRequest??$.PermissionRequest,UserPromptSubmit:V.UserPromptSubmit??$.UserPromptSubmit,SessionStart:V.SessionStart??$.SessionStart,SessionEnd:V.SessionEnd??$.SessionEnd,Stop:V.Stop??$.Stop,SubagentStart:V.SubagentStart??$.SubagentStart,SubagentStop:V.SubagentStop??$.SubagentStop,TaskCompleted:V.TaskCompleted??$.TaskCompleted,Notification:V.Notification??$.Notification,Compaction:V.Compaction??$.Compaction}}function X4(){let $={};if(process.env.BLADE_DISABLE_HOOKS==="true")$.enabled=!1;if(process.env.BLADE_HOOK_TIMEOUT){let V=parseInt(process.env.BLADE_HOOK_TIMEOUT,10);if(!isNaN(V)&&V>0)$.defaultTimeout=V}return $}class M1{executedHooks=new Map;canExecute($,V){if(!this.executedHooks.has($))this.executedHooks.set($,new Set);if(this.executedHooks.get($).has(V))return console.warn(`[HookGuard] Hook ${V} for tool ${$} already executed, skipping`),!1;return!0}markExecuted($,V){let W=this.executedHooks.get($);if(W)W.add(V)}cleanup($){this.executedHooks.delete($)}cleanupAll(){this.executedHooks.clear()}}import{z as U}from"zod";var S1;((Q)=>{Q.Approve="approve";Q.Block="block";Q.Async="async"})(S1||={});var T1;((Q)=>{Q.Allow="allow";Q.Deny="deny";Q.Ask="ask"})(T1||={});var X$=U.object({hook_event_name:U.nativeEnum(F0),hook_execution_id:U.string(),timestamp:U.string(),project_dir:U.string(),session_id:U.string(),permission_mode:U.enum(["default","autoEdit","yolo","plan"]),_metadata:U.object({blade_version:U.string(),hook_timeout_ms:U.number()}).optional()}),z5=X$.extend({hook_event_name:U.literal("PreToolUse"),tool_name:U.string(),tool_use_id:U.string(),tool_input:U.record(U.unknown())}),M5=X$.extend({hook_event_name:U.literal("PostToolUse"),tool_name:U.string(),tool_use_id:U.string(),tool_input:U.record(U.unknown()),tool_response:U.unknown()}),S5=X$.extend({hook_event_name:U.literal("Stop"),reason:U.string().optional()}),T5=X$.extend({hook_event_name:U.literal("PostToolUseFailure"),tool_name:U.string(),tool_use_id:U.string(),tool_input:U.record(U.unknown()),error:U.string(),error_type:U.string().optional(),is_interrupt:U.boolean(),is_timeout:U.boolean()}),y5=X$.extend({hook_event_name:U.literal("PermissionRequest"),tool_name:U.string(),tool_use_id:U.string(),tool_input:U.record(U.unknown())}),v5=X$.extend({hook_event_name:U.literal("UserPromptSubmit"),user_prompt:U.string(),has_images:U.boolean(),image_count:U.number()}),P5=X$.extend({hook_event_name:U.literal("SessionStart"),is_resume:U.boolean(),resume_session_id:U.string().optional()}),k5=X$.extend({hook_event_name:U.literal("SessionEnd"),reason:U.enum(["user_exit","error","max_turns","idle_timeout","ctrl_c","clear","logout","other"])}),I5=X$.extend({hook_event_name:U.literal("SubagentStart"),agent_type:U.string(),task_description:U.string().optional(),parent_agent_id:U.string().optional()}),f5=X$.extend({hook_event_name:U.literal("SubagentStop"),agent_type:U.string(),task_description:U.string().optional(),success:U.boolean(),result_summary:U.string().optional(),error:U.string().optional()}),h5=X$.extend({hook_event_name:U.literal("TaskCompleted"),task_id:U.string(),task_description:U.string(),result_summary:U.string().optional(),success:U.boolean()}),x5=X$.extend({hook_event_name:U.literal("Notification"),notification_type:U.enum(["permission_prompt","idle_prompt","auth_success","elicitation_dialog","info","warning","error"]),title:U.string().optional(),message:U.string()}),p5=X$.extend({hook_event_name:U.literal("Compaction"),trigger:U.enum(["manual","auto"]),messages_before:U.number(),tokens_before:U.number()}),A3=U.discriminatedUnion("hook_event_name",[z5,M5,S5,T5,y5,v5,P5,k5,I5,f5,h5,x5,p5]),g5=U.object({hookEventName:U.literal("PreToolUse"),permissionDecision:U.nativeEnum(T1).optional(),permissionDecisionReason:U.string().optional(),updatedInput:U.record(U.unknown()).optional()}),u5=U.object({hookEventName:U.literal("PostToolUse"),additionalContext:U.string().optional(),updatedOutput:U.unknown().optional()}),d5=U.object({hookEventName:U.literal("Stop"),continue:U.boolean().optional(),continueReason:U.string().optional()}),m5=U.object({hookEventName:U.literal("SubagentStart"),additionalContext:U.string().optional()}),c5=U.object({hookEventName:U.literal("SubagentStop"),continue:U.boolean().optional(),continueReason:U.string().optional(),additionalContext:U.string().optional()}),i5=U.object({hookEventName:U.literal("TaskCompleted"),blockCompletion:U.boolean().optional(),blockReason:U.string().optional()}),l5=U.object({hookEventName:U.literal("PermissionRequest"),permissionDecision:U.enum(["approve","deny","ask"]).optional(),permissionDecisionReason:U.string().optional()}),n5=U.object({hookEventName:U.literal("UserPromptSubmit"),updatedPrompt:U.string().optional(),contextInjection:U.string().optional()}),r5=U.object({hookEventName:U.literal("SessionStart"),env:U.record(U.string()).optional()}),s5=U.object({hookEventName:U.literal("Compaction"),blockCompaction:U.boolean().optional(),blockReason:U.string().optional()}),a5=U.object({decision:U.object({behavior:U.nativeEnum(S1)}).optional(),systemMessage:U.string().optional(),hookSpecificOutput:U.discriminatedUnion("hookEventName",[g5,u5,d5,m5,c5,i5,l5,n5,r5,s5]).optional(),suppressOutput:U.boolean().optional()}),o5=U.object({type:U.literal("command"),command:U.string(),timeout:U.number().positive().optional(),statusMessage:U.string().optional()}),t5=U.object({type:U.literal("prompt"),prompt:U.string(),timeout:U.number().positive().optional()}),e5=U.discriminatedUnion("type",[o5,t5]),y1=U.union([U.string(),U.array(U.string())]),$7=U.object({tools:y1.optional(),paths:y1.optional(),commands:y1.optional()}),J$=U.object({name:U.string().optional(),matcher:$7.optional(),hooks:U.array(e5)}),w3=U.object({enabled:U.boolean().optional(),defaultTimeout:U.number().positive().optional(),timeoutBehavior:U.enum(["ignore","deny","ask"]).optional(),failureBehavior:U.enum(["ignore","deny","ask"]).optional(),maxConcurrentHooks:U.number().positive().optional(),PreToolUse:U.array(J$).optional(),PostToolUse:U.array(J$).optional(),PostToolUseFailure:U.array(J$).optional(),PermissionRequest:U.array(J$).optional(),UserPromptSubmit:U.array(J$).optional(),SessionStart:U.array(J$).optional(),SessionEnd:U.array(J$).optional(),Stop:U.array(J$).optional(),SubagentStart:U.array(J$).optional(),SubagentStop:U.array(J$).optional(),TaskCompleted:U.array(J$).optional(),Notification:U.array(J$).optional(),Compaction:U.array(J$).optional()});function G4($){let V=a5.safeParse($);if(V.success)return{success:!0,data:V.data};return{success:!1,error:V.error}}class v1{parse($,V,W){if($.timedOut){let Z=W?.timeoutBehavior||"ignore",Y="Hook timeout";if(Z==="deny")return{success:!1,blocking:!0,error:"Hook timeout",stdout:$.stdout,stderr:$.stderr,exitCode:$.exitCode,hook:V};else if(Z==="ask")return{success:!1,blocking:!1,needsConfirmation:!0,warning:"Hook timeout. Continue?",stdout:$.stdout,stderr:$.stderr,exitCode:$.exitCode,hook:V};else return{success:!1,blocking:!1,warning:"Hook timeout",stdout:$.stdout,stderr:$.stderr,exitCode:$.exitCode,hook:V}}let Q=this.tryParseJSON($.stdout);if(Q){let Z=G4(Q);if(!Z.success){let J="error"in Z?Z.error.message:"Unknown validation error",X=W?.failureBehavior||"ignore",G=`Invalid hook output JSON: ${J}`;if(X==="deny")return{success:!1,blocking:!0,error:G,stdout:$.stdout,stderr:$.stderr,exitCode:$.exitCode,hook:V};else if(X==="ask")return{success:!1,blocking:!1,needsConfirmation:!0,warning:`${G}. Continue?`,stdout:$.stdout,stderr:$.stderr,exitCode:$.exitCode,hook:V};else return{success:!1,blocking:!1,warning:G,stdout:$.stdout,stderr:$.stderr,exitCode:$.exitCode,hook:V}}let Y=Z.data;if(Y.decision?.behavior==="block")return{success:!1,blocking:!0,error:Y.systemMessage||"Hook blocked execution",output:Y,stdout:$.stdout,stderr:$.stderr,exitCode:$.exitCode,hook:V};if(Y.decision?.behavior==="async")return{success:!0,output:Y,stdout:$.stdout,stderr:$.stderr,exitCode:$.exitCode,hook:V};return{success:!0,output:Y,stdout:$.stdout,stderr:$.stderr,exitCode:$.exitCode,hook:V}}return this.parseByExitCode($,V,W)}parseByExitCode($,V,W){let Q=$.exitCode;switch(Q){case 0:return{success:!0,stdout:$.stdout,stderr:$.stderr,exitCode:Q,hook:V};case 2:return{success:!1,blocking:!0,error:$.stderr||$.stdout||"Hook returned exit code 2",stdout:$.stdout,stderr:$.stderr,exitCode:Q,hook:V};case 124:{let Z=W?.timeoutBehavior||"ignore",Y="Hook timeout";if(Z==="deny")return{success:!1,blocking:!0,error:"Hook timeout",stdout:$.stdout,stderr:$.stderr,exitCode:Q,hook:V};else if(Z==="ask")return{success:!1,blocking:!1,needsConfirmation:!0,warning:"Hook timeout. Continue?",stdout:$.stdout,stderr:$.stderr,exitCode:Q,hook:V};else return{success:!1,blocking:!1,warning:"Hook timeout",stdout:$.stdout,stderr:$.stderr,exitCode:Q,hook:V}}default:{let Z=W?.failureBehavior||"ignore",Y=$.stderr||$.stdout||`Hook failed with exit code ${Q}`;if(Z==="deny")return{success:!1,blocking:!0,error:Y,stdout:$.stdout,stderr:$.stderr,exitCode:Q,hook:V};else if(Z==="ask")return{success:!1,blocking:!1,needsConfirmation:!0,warning:`${Y}. Continue?`,stdout:$.stdout,stderr:$.stderr,exitCode:Q,hook:V};else return{success:!1,blocking:!1,warning:Y,stdout:$.stdout,stderr:$.stderr,exitCode:Q,hook:V}}}}tryParseJSON($){try{let V=$.trim();if(!V)return null;let W=V.match(/^\s*(\{[\s\S]*\})\s*$/);if(!W)return null;return JSON.parse(W[1])}catch{return null}}}import{spawn as V7}from"child_process";class P1{content="";maxSize;constructor($){this.maxSize=$}append($){if(this.content.length<this.maxSize){let V=this.maxSize-this.content.length;this.content+=$.substring(0,V)}}getContent(){return this.content}isFull(){return this.content.length>=this.maxSize}}class k1{MAX_STDOUT_SIZE=1048576;MAX_STDERR_SIZE=1048576;MAX_INPUT_SIZE=102400;async execute($,V,W,Q){let Z=JSON.stringify(V);if(Z.length>this.MAX_INPUT_SIZE)throw Error(`Hook input too large: ${Z.length} bytes (max ${this.MAX_INPUT_SIZE})`);let Y=this.createSafeEnv(V),J=V7($,[],{shell:!0,env:Y,cwd:W.projectDir,timeout:Q}),X=new P1(this.MAX_STDOUT_SIZE),G=new P1(this.MAX_STDERR_SIZE);J.stdout.setEncoding("utf8"),J.stderr.setEncoding("utf8"),J.stdout.on("data",(B)=>{X.append(B)}),J.stderr.on("data",(B)=>{G.append(B)});try{J.stdin.write(Z),J.stdin.end()}catch(B){throw J.kill("SIGTERM"),Error(`Failed to write hook input: ${B}`)}return new Promise((B,K)=>{let q=!1,O=!1,w=null,b=()=>{if(w&&W.abortSignal)W.abortSignal.removeEventListener("abort",w),w=null},A=setTimeout(()=>{q=!0,J.kill("SIGKILL")},Q);if(J.on("close",(H)=>{if(O)return;O=!0,clearTimeout(A),b(),B({stdout:X.getContent(),stderr:G.getContent(),exitCode:q?124:H??1,timedOut:q})}),J.on("error",(H)=>{if(O)return;O=!0,clearTimeout(A),b(),K(H)}),W.abortSignal)w=()=>{if(O)return;O=!0,clearTimeout(A),b(),J.kill("SIGTERM"),B({stdout:X.getContent(),stderr:"Hook cancelled by abort signal",exitCode:1,timedOut:!1})},W.abortSignal.addEventListener("abort",w)})}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"}}}class I1{processExecutor=new k1;outputParser=new v1;async executePreToolHooks($,V,W){if($.length===0)return{decision:"allow"};let Q="tool_input"in V?V.tool_input:{},Z=[];for(let Y of $)try{let J={...V,...Q&&{tool_input:Q}},X=await this.executeHook(Y,J,W);if(!X.success){if(X.blocking)return{decision:"deny",reason:X.error};if(X.needsConfirmation)return{decision:"ask",reason:X.warning||X.error};if(X.warning)Z.push(X.warning);continue}let G=X.output?.hookSpecificOutput;if(G&&"permissionDecision"in G){switch(G.permissionDecision){case"deny":return{decision:"deny",reason:G.permissionDecisionReason};case"ask":return{decision:"ask",reason:G.permissionDecisionReason};case"allow":break}if("updatedInput"in G&&G.updatedInput)Q={...Q,...G.updatedInput}}}catch(J){let X=J instanceof Error?J.message:String(J);if(Z.push(`Hook failed: ${X}`),W.config.failureBehavior==="deny")return{decision:"deny",reason:X};else if(W.config.failureBehavior==="ask")return{decision:"ask",reason:`Hook failed: ${X}. Continue?`}}return{decision:"allow",modifiedInput:Q,warning:Z.length>0?Z.join(`
|
|
2
|
-
`):void 0}}async executePostToolHooks($,
|
|
3
|
-
|
|
4
|
-
`):void 0,modifiedOutput:
|
|
5
|
-
`):void 0}}async executeStopHooks($,
|
|
6
|
-
`):void 0}}catch(
|
|
7
|
-
`):void 0}}async executeSubagentStartHooks($,
|
|
8
|
-
|
|
9
|
-
`):void 0,warning:
|
|
10
|
-
`):void 0}}async executeSubagentStopHooks($,
|
|
11
|
-
`):void 0};if("additionalContext"in
|
|
12
|
-
|
|
13
|
-
`):void 0,warning:
|
|
14
|
-
`):void 0}}async executeTaskCompletedHooks($,
|
|
15
|
-
`):void 0};if(
|
|
16
|
-
`):void 0}}catch(
|
|
17
|
-
`):void 0}}async executePermissionRequestHooks($,
|
|
18
|
-
`):void 0}}}catch(
|
|
19
|
-
`):void 0}}async executeUserPromptSubmitHooks($,
|
|
20
|
-
|
|
21
|
-
`):void 0,warning:
|
|
22
|
-
`):void 0}}async executeSessionStartHooks($,
|
|
23
|
-
`):void 0}}async executeSessionEndHooks($,
|
|
24
|
-
`):void 0}}async executePostToolUseFailureHooks($,
|
|
25
|
-
|
|
26
|
-
`):void 0,warning:
|
|
27
|
-
`):void 0}}async executeNotificationHooks($,
|
|
28
|
-
`):void 0}}async executeCompactionHooks($,
|
|
29
|
-
`):void 0}}catch(
|
|
30
|
-
`):void 0}}async executeHook($,V,W){if($.type==="command")return this.executeCommandHook($,V,W);throw Error(`Hook type ${$.type} not yet implemented`)}async executeCommandHook($,V,W){let Q=($.timeout??W.config.defaultTimeout??60)*1000;try{let Z=await this.processExecutor.execute($.command,V,W,Q);return this.outputParser.parse(Z,$,{timeoutBehavior:W.config.timeoutBehavior,failureBehavior:W.config.failureBehavior})}catch(Z){return{success:!1,blocking:!1,error:Z instanceof Error?Z.message:String(Z),hook:$}}}async executeHooksConcurrently($,V,W,Q){let Z=[],Y=new Set;for(let J of $){if(Y.size>=Q)await Promise.race(Y);let X=this.executeHook(J,V,W).catch((B)=>({success:!1,blocking:!1,error:B instanceof Error?B.message:String(B),hook:J})),G=X.then(()=>{Y.delete(G)}).catch(()=>{Y.delete(G)});Y.add(G),Z.push(X)}return Promise.all(Z)}}import f1 from"picomatch";var W7=/^([A-Za-z0-9_|]+)\((.+)\)$/;class h1{matches($,V){if(!$)return!0;if($.tools&&V.toolName){if(!this.matchTools($.tools,V))return!1}if($.paths&&V.filePath){if(!this.matchPaths($.paths,V.filePath))return!1}if($.commands&&V.command){if(!this.matchCommands($.commands,V.command))return!1}return!0}matchTools($,V){if(Array.isArray($))return $.some((W)=>this.matchToolWithParams(W,V));return this.matchToolWithParams($,V)}matchPaths($,V){if(Array.isArray($))return $.some((Q)=>{return f1(Q)(V)});return f1($)(V)}matchCommands($,V){if(Array.isArray($))return $.some((W)=>this.matchPattern(V,W));return this.matchPattern(V,$)}matchToolWithParams($,V){let{toolName:W,command:Q,filePath:Z}=V,Y=W7.exec($);if(!Y)return this.matchPattern(W,$);let[,J,X]=Y;if(!this.matchPattern(W,J))return!1;let G=this.getArgValue(W,Q,Z);if(!G)return!1;return this.matchGlobOrPattern(G,X)}getArgValue($,V,W){if($==="Bash"||$==="BashTool")return V;if(["Read","Edit","Write","Glob","Grep"].includes($))return W;return V||W}matchGlobOrPattern($,V){if(/[*?[\]{}!]/.test(V))try{return f1(V,{bash:!0,dot:!0})($)}catch{}if(V.endsWith("*")){let W=V.slice(0,-1);return $.startsWith(W)}return $===V}matchPattern($,V){if(V==="*")return!0;if(!V.includes("|")&&!/[.*+?^${}()|[\]\\]/.test(V))return $===V;if(V.includes("|"))return V.split("|").map((Q)=>Q.trim()).includes($);try{return new RegExp(V).test($)}catch{return $===V}}}class l{static instance=null;config=E1;executor=new I1;guard=new M1;matcher=new h1;sessionDisabled=!1;constructor(){}static getInstance(){if(!l.instance)l.instance=new l;return l.instance}loadConfig($){let V=z1(E1,$),W=X4();V=z1(V,W),this.config=V}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"),V=await import("node:path");try{let W=V.join(process.cwd(),".blade","settings.local.json"),Q=await $.readFile(W,"utf-8"),Z=JSON.parse(Q);if(Z.hooks)this.loadConfig(Z.hooks)}catch{}}async executePreToolHooks($,V,W,Q){if(!this.isEnabled())return{decision:"allow"};if(Q.permissionMode==="plan")return{decision:"allow"};if(!this.guard.canExecute(V,"PreToolUse"))return{decision:"allow"};let Z={hook_event_name:"PreToolUse",hook_execution_id:G$(),timestamp:new Date().toISOString(),tool_name:$,tool_use_id:V,tool_input:W,project_dir:Q.projectDir,session_id:Q.sessionId,permission_mode:Q.permissionMode},Y=this.getMatchingHooks("PreToolUse",{toolName:$,filePath:this.extractFilePath(W),command:this.extractCommand($,W)});if(Y.length===0)return{decision:"allow"};let J={projectDir:Q.projectDir,sessionId:Q.sessionId,permissionMode:Q.permissionMode,config:this.config,abortSignal:Q.abortSignal};try{let X=await this.executor.executePreToolHooks(Y,Z,J);if(this.guard.markExecuted(V,"PreToolUse"),Q.permissionMode==="yolo"){if(X.decision==="deny")return X;return{decision:"allow",modifiedInput:X.modifiedInput,warning:X.warning,reason:X.reason}}return X}catch(X){return console.error("[HookManager] Error executing PreToolUse hooks:",X),{decision:"allow",warning:`Hook execution failed: ${X instanceof Error?X.message:String(X)}`}}}async executePostToolHooks($,V,W,Q,Z){if(!this.isEnabled())return{};if(Z.permissionMode==="plan")return{};if(!this.guard.canExecute(V,"PostToolUse"))return{};let Y={hook_event_name:"PostToolUse",hook_execution_id:G$(),timestamp:new Date().toISOString(),tool_name:$,tool_use_id:V,tool_input:W,tool_response:Q,project_dir:Z.projectDir,session_id:Z.sessionId,permission_mode:Z.permissionMode},J=this.getMatchingHooks("PostToolUse",{toolName:$,filePath:this.extractFilePath(W),command:this.extractCommand($,W)});if(J.length===0)return{};let X={projectDir:Z.projectDir,sessionId:Z.sessionId,permissionMode:Z.permissionMode,config:this.config,abortSignal:Z.abortSignal};try{let G=await this.executor.executePostToolHooks(J,Y,X);return this.guard.markExecuted(V,"PostToolUse"),G}catch(G){return console.error("[HookManager] Error executing PostToolUse hooks:",G),{warning:`Hook execution failed: ${G instanceof Error?G.message:String(G)}`}}finally{this.guard.cleanup(V)}}async executeStopHooks($){if(!this.isEnabled())return{shouldStop:!0};let V={hook_event_name:"Stop",hook_execution_id:G$(),timestamp:new Date().toISOString(),project_dir:$.projectDir,session_id:$.sessionId,permission_mode:$.permissionMode,reason:$.reason},W=this.getMatchingHooks("Stop",{});if(W.length===0)return{shouldStop:!0};let Q={projectDir:$.projectDir,sessionId:$.sessionId,permissionMode:$.permissionMode,config:this.config,abortSignal:$.abortSignal};try{return await this.executor.executeStopHooks(W,V,Q)}catch(Z){return console.error("[HookManager] Error executing Stop hooks:",Z),{shouldStop:!0,warning:`Hook execution failed: ${Z instanceof Error?Z.message:String(Z)}`}}}async executeSubagentStartHooks($,V){if(!this.isEnabled())return{proceed:!0};let W={hook_event_name:"SubagentStart",hook_execution_id:G$(),timestamp:new Date().toISOString(),project_dir:V.projectDir,session_id:V.sessionId,permission_mode:V.permissionMode,agent_type:$,task_description:V.taskDescription,parent_agent_id:V.parentAgentId},Q=this.getMatchingHooks("SubagentStart",{toolName:$});if(Q.length===0)return{proceed:!0};let Z={projectDir:V.projectDir,sessionId:V.sessionId,permissionMode:V.permissionMode,config:this.config,abortSignal:V.abortSignal};try{return await this.executor.executeSubagentStartHooks(Q,W,Z)}catch(Y){return console.error("[HookManager] Error executing SubagentStart hooks:",Y),{proceed:!0,warning:`Hook execution failed: ${Y instanceof Error?Y.message:String(Y)}`}}}async executeSubagentStopHooks($,V){if(!this.isEnabled())return{shouldStop:!0};let W={hook_event_name:"SubagentStop",hook_execution_id:G$(),timestamp:new Date().toISOString(),project_dir:V.projectDir,session_id:V.sessionId,permission_mode:V.permissionMode,agent_type:$,task_description:V.taskDescription,success:V.success,result_summary:V.resultSummary,error:V.error},Q=this.getMatchingHooks("SubagentStop",{});if(Q.length===0)return{shouldStop:!0};let Z={projectDir:V.projectDir,sessionId:V.sessionId,permissionMode:V.permissionMode,config:this.config,abortSignal:V.abortSignal};try{return await this.executor.executeSubagentStopHooks(Q,W,Z)}catch(Y){return console.error("[HookManager] Error executing SubagentStop hooks:",Y),{shouldStop:!0,warning:`Hook execution failed: ${Y instanceof Error?Y.message:String(Y)}`}}}async executeTaskCompletedHooks($,V){if(!this.isEnabled())return{allowCompletion:!0};let W={hook_event_name:"TaskCompleted",hook_execution_id:G$(),timestamp:new Date().toISOString(),project_dir:V.projectDir,session_id:V.sessionId,permission_mode:V.permissionMode,task_id:$,task_description:V.taskDescription,result_summary:V.resultSummary,success:V.success},Q=this.getMatchingHooks("TaskCompleted",{});if(Q.length===0)return{allowCompletion:!0};let Z={projectDir:V.projectDir,sessionId:V.sessionId,permissionMode:V.permissionMode,config:this.config,abortSignal:V.abortSignal};try{return await this.executor.executeTaskCompletedHooks(Q,W,Z)}catch(Y){return console.error("[HookManager] Error executing TaskCompleted hooks:",Y),{allowCompletion:!0,warning:`Hook execution failed: ${Y instanceof Error?Y.message:String(Y)}`}}}async executePermissionRequestHooks($,V,W,Q){if(!this.isEnabled())return{decision:"ask"};let Z={hook_event_name:"PermissionRequest",hook_execution_id:G$(),timestamp:new Date().toISOString(),tool_name:$,tool_use_id:V,tool_input:W,project_dir:Q.projectDir,session_id:Q.sessionId,permission_mode:Q.permissionMode},Y=this.getMatchingHooks("PermissionRequest",{toolName:$,filePath:this.extractFilePath(W),command:this.extractCommand($,W)});if(Y.length===0)return{decision:"ask"};let J={projectDir:Q.projectDir,sessionId:Q.sessionId,permissionMode:Q.permissionMode,config:this.config,abortSignal:Q.abortSignal};try{return await this.executor.executePermissionRequestHooks(Y,Z,J)}catch(X){return console.error("[HookManager] Error executing PermissionRequest hooks:",X),{decision:"ask",warning:`Hook execution failed: ${X instanceof Error?X.message:String(X)}`}}}async executeUserPromptSubmitHooks($,V){if(!this.isEnabled())return{proceed:!0};let W={hook_event_name:"UserPromptSubmit",hook_execution_id:G$(),timestamp:new Date().toISOString(),user_prompt:$,has_images:V.hasImages,image_count:V.imageCount,project_dir:V.projectDir,session_id:V.sessionId,permission_mode:V.permissionMode},Q=this.getMatchingHooks("UserPromptSubmit",{});if(Q.length===0)return{proceed:!0};let Z={projectDir:V.projectDir,sessionId:V.sessionId,permissionMode:V.permissionMode,config:this.config,abortSignal:V.abortSignal};try{return await this.executor.executeUserPromptSubmitHooks(Q,W,Z)}catch(Y){return console.error("[HookManager] Error executing UserPromptSubmit hooks:",Y),{proceed:!0,warning:`Hook execution failed: ${Y instanceof Error?Y.message:String(Y)}`}}}async executeSessionStartHooks($){if(!this.isEnabled())return{proceed:!0};let V={hook_event_name:"SessionStart",hook_execution_id:G$(),timestamp:new Date().toISOString(),project_dir:$.projectDir,session_id:$.sessionId,permission_mode:$.permissionMode,is_resume:$.isResume,resume_session_id:$.resumeSessionId},W=this.getMatchingHooks("SessionStart",{});if(W.length===0)return{proceed:!0};let Q={projectDir:$.projectDir,sessionId:$.sessionId,permissionMode:$.permissionMode,config:this.config,abortSignal:$.abortSignal};try{return await this.executor.executeSessionStartHooks(W,V,Q)}catch(Z){return console.error("[HookManager] Error executing SessionStart hooks:",Z),{proceed:!0,warning:`Hook execution failed: ${Z instanceof Error?Z.message:String(Z)}`}}}async executeSessionEndHooks($,V){if(!this.isEnabled())return{};let W={hook_event_name:"SessionEnd",hook_execution_id:G$(),timestamp:new Date().toISOString(),project_dir:V.projectDir,session_id:V.sessionId,permission_mode:V.permissionMode,reason:$},Q=this.getMatchingHooks("SessionEnd",{});if(Q.length===0)return{};let Z={projectDir:V.projectDir,sessionId:V.sessionId,permissionMode:V.permissionMode,config:this.config,abortSignal:V.abortSignal};try{return await this.executor.executeSessionEndHooks(Q,W,Z),{}}catch(Y){return console.error("[HookManager] Error executing SessionEnd hooks:",Y),{warning:`Hook execution failed: ${Y instanceof Error?Y.message:String(Y)}`}}}async executePostToolUseFailureHooks($,V,W,Q,Z){if(!this.isEnabled())return{};let Y={hook_event_name:"PostToolUseFailure",hook_execution_id:G$(),timestamp:new Date().toISOString(),tool_name:$,tool_use_id:V,tool_input:W,error:Q,error_type:Z.errorType,is_interrupt:Z.isInterrupt,is_timeout:Z.isTimeout,project_dir:Z.projectDir,session_id:Z.sessionId,permission_mode:Z.permissionMode},J=this.getMatchingHooks("PostToolUseFailure",{toolName:$,filePath:this.extractFilePath(W),command:this.extractCommand($,W)});if(J.length===0)return{};let X={projectDir:Z.projectDir,sessionId:Z.sessionId,permissionMode:Z.permissionMode,config:this.config,abortSignal:Z.abortSignal};try{return await this.executor.executePostToolUseFailureHooks(J,Y,X)}catch(G){return console.error("[HookManager] Error executing PostToolUseFailure hooks:",G),{warning:`Hook execution failed: ${G instanceof Error?G.message:String(G)}`}}}async executeNotificationHooks($,V,W){if(!this.isEnabled())return{suppress:!1,message:V};let Q={hook_event_name:"Notification",hook_execution_id:G$(),timestamp:new Date().toISOString(),project_dir:W.projectDir,session_id:W.sessionId,permission_mode:W.permissionMode,notification_type:$,title:W.title,message:V},Z=this.getMatchingHooks("Notification",{});if(Z.length===0)return{suppress:!1,message:V};let Y={projectDir:W.projectDir,sessionId:W.sessionId,permissionMode:W.permissionMode,config:this.config,abortSignal:W.abortSignal};try{return await this.executor.executeNotificationHooks(Z,Q,Y)}catch(J){return console.error("[HookManager] Error executing Notification hooks:",J),{suppress:!1,message:V,warning:`Hook execution failed: ${J instanceof Error?J.message:String(J)}`}}}async executeCompactionHooks($,V){if(!this.isEnabled())return{blockCompaction:!1};let W={hook_event_name:"Compaction",hook_execution_id:G$(),timestamp:new Date().toISOString(),project_dir:V.projectDir,session_id:V.sessionId,permission_mode:V.permissionMode,trigger:$,messages_before:V.messagesBefore,tokens_before:V.tokensBefore},Q=this.getMatchingHooks("Compaction",{});if(Q.length===0)return{blockCompaction:!1};let Z={projectDir:V.projectDir,sessionId:V.sessionId,permissionMode:V.permissionMode,config:this.config,abortSignal:V.abortSignal};try{return await this.executor.executeCompactionHooks(Q,W,Z)}catch(Y){return console.error("[HookManager] Error executing Compaction hooks:",Y),{blockCompaction:!1,warning:`Hook execution failed: ${Y instanceof Error?Y.message:String(Y)}`}}}getMatchingHooks($,V){let W=this.config[$]||[],Q=[];for(let Z of W)if(this.matcher.matches(Z.matcher,V))Q.push(...Z.hooks);return Q}extractFilePath($){let V=["file_path","path","filePath","source","target"];for(let W of V){let Q=$[W];if(typeof Q==="string")return Q}return}extractCommand($,V){if($==="Bash"||$==="BashTool"){let W=V.command;if(typeof W==="string")return W}return}cleanup(){this.guard.cleanupAll()}}import{appendFileSync as Q7,existsSync as Z7,mkdirSync as Y7,readdirSync as J7,statSync as q4,unlinkSync as X7}from"node:fs";import G7 from"node:os";import p1 from"node:path";var g1;((Z)=>{Z[Z.DEBUG=0]="DEBUG";Z[Z.INFO=1]="INFO";Z[Z.WARN=2]="WARN";Z[Z.ERROR=3]="ERROR"})(g1||={});var n;((O)=>{O.AGENT="Agent";O.UI="UI";O.TOOL="Tool";O.SERVICE="Service";O.CONFIG="Config";O.CONTEXT="Context";O.EXECUTION="Execution";O.LOOP="Loop";O.CHAT="Chat";O.GENERAL="General";O.PROMPTS="Prompts";O.SPEC="Spec"})(n||={});var x1=null,B4=null,K4=!1;function f3($){if(x1!==$)x1=$}async function h3(){}function B7(){if(K4)return B4;K4=!0;try{let $=p1.join(G7.homedir(),".blade","logs");if(!Z7($))Y7($,{recursive:!0,mode:493});if(q4($).uid===0&&process.getuid&&process.getuid()!==0)return console.error(""),console.error("❌ 权限错误:~/.blade/logs 目录属于 root 用户"),console.error(""),console.error("这通常是因为您曾经使用 sudo 运行过 blade。"),console.error(""),console.error("解决方法:"),console.error(" sudo chown -R $USER:$USER ~/.blade/"),console.error(""),console.error("然后重新运行 blade(不要使用 sudo)"),console.error(""),null;return K7($,30),B4=$,$}catch($){return console.error("[Logger] 无法创建日志目录:",$),null}}function K7($,V){try{let W=J7($),Q=Date.now(),Z=V*24*60*60*1000;for(let Y of W){if(!Y.startsWith("blade-")||!Y.endsWith(".log")&&!Y.endsWith(".jsonl"))continue;let J=p1.join($,Y);try{let X=q4(J);if(Q-X.mtimeMs>Z)X7(J)}catch(X){}}}catch(W){}}function q7(){let $=B7();if(!$)return null;let V=x1||"default";return p1.join($,`blade-${V}.jsonl`)}function O7($,V,W){let Q=q7();if(!Q)return;try{let Z={timestamp:new Date().toISOString(),level:g1[V],category:$,message:W};Q7(Q,JSON.stringify(Z)+`
|
|
31
|
-
`)}catch(
|
|
32
|
-
`+"请检查网络连接或使用自己的 API Key (/config)")}}import{createAnthropic as
|
|
33
|
-
`)}function
|
|
34
|
-
`);if(
|
|
35
|
-
`),
|
|
36
|
-
`),
|
|
37
|
-
|
|
38
|
-
... (truncated ${
|
|
39
|
-
|
|
40
|
-
`),
|
|
1
|
+
import{createRequire as Y8}from"node:module";var V8=Object.create;var{getPrototypeOf:W8,defineProperty:hw,getOwnPropertyNames:Q8}=Object;var Z8=Object.prototype.hasOwnProperty;var Ob=($,b,w)=>{w=$!=null?V8(W8($)):{};let V=b||!$||!$.__esModule?hw(w,"default",{value:$,enumerable:!0}):w;for(let W of Q8($))if(!Z8.call(V,W))hw(V,W,{get:()=>$[W],enumerable:!0});return V};var I0=Y8(import.meta.url);import{nanoid as aV}from"nanoid";import*as h2 from"os";import*as x2 from"path";import{nanoid as U0}from"nanoid";var w1={DEFAULT:"default",AUTO_EDIT:"autoEdit",YOLO:"yolo",BYPASSALL:"bypassAll",PLAN:"plan",SPEC:"spec"},P0;((q)=>{q.PreToolUse="PreToolUse";q.PostToolUse="PostToolUse";q.PostToolUseFailure="PostToolUseFailure";q.PermissionRequest="PermissionRequest";q.UserPromptSubmit="UserPromptSubmit";q.SessionStart="SessionStart";q.SessionEnd="SessionEnd";q.Stop="Stop";q.SubagentStart="SubagentStart";q.SubagentStop="SubagentStop";q.TaskCompleted="TaskCompleted";q.Notification="Notification";q.Compaction="Compaction"})(P0||={});var xw={SYSTEM:"system",USER:"user",ASSISTANT:"assistant",TOOL:"tool"},J8={TURN_START:"turn_start",TURN_END:"turn_end",CONTENT:"content",THINKING:"thinking",TOOL_USE:"tool_use",TOOL_RESULT:"tool_result",USAGE:"usage",RESULT:"result",ERROR:"error"},X8={READONLY:"readonly",WRITE:"write",EXECUTE:"execute"},O8={ALLOW:"allow",DENY:"deny",ASK:"ask"},G8={APPROVE:"approve",BLOCK:"block",ASYNC:"async"},B8={ALLOW:"allow",DENY:"deny",ASK:"ask"},K8={COMMAND:"command",PROMPT:"prompt"},q8={SUCCESS:0,NON_BLOCKING_ERROR:1,BLOCKING_ERROR:2,TIMEOUT:124},C8={VALIDATION_ERROR:"validation_error",PERMISSION_DENIED:"permission_denied",EXECUTION_ERROR:"execution_error",TIMEOUT_ERROR:"timeout_error",NETWORK_ERROR:"network_error"};var v=w1;import{nanoid as q$}from"nanoid";var V1={enabled:!1,defaultTimeout:60,timeoutBehavior:"ignore",failureBehavior:"ignore",maxConcurrentHooks:5,PreToolUse:[],PostToolUse:[],PostToolUseFailure:[],PermissionRequest:[],UserPromptSubmit:[],SessionStart:[],SessionEnd:[],Stop:[],SubagentStart:[],SubagentStop:[],TaskCompleted:[],Notification:[],Compaction:[]};function W1($,b){return{...$,...b,PreToolUse:b.PreToolUse??$.PreToolUse,PostToolUse:b.PostToolUse??$.PostToolUse,PostToolUseFailure:b.PostToolUseFailure??$.PostToolUseFailure,PermissionRequest:b.PermissionRequest??$.PermissionRequest,UserPromptSubmit:b.UserPromptSubmit??$.UserPromptSubmit,SessionStart:b.SessionStart??$.SessionStart,SessionEnd:b.SessionEnd??$.SessionEnd,Stop:b.Stop??$.Stop,SubagentStart:b.SubagentStart??$.SubagentStart,SubagentStop:b.SubagentStop??$.SubagentStop,TaskCompleted:b.TaskCompleted??$.TaskCompleted,Notification:b.Notification??$.Notification,Compaction:b.Compaction??$.Compaction}}function pw(){let $={};if(process.env.BLADE_DISABLE_HOOKS==="true")$.enabled=!1;if(process.env.BLADE_HOOK_TIMEOUT){let b=parseInt(process.env.BLADE_HOOK_TIMEOUT,10);if(!isNaN(b)&&b>0)$.defaultTimeout=b}return $}class Q1{executedHooks=new Map;canExecute($,b){if(!this.executedHooks.has($))this.executedHooks.set($,new Set);if(this.executedHooks.get($).has(b))return console.warn(`[HookGuard] Hook ${b} for tool ${$} already executed, skipping`),!1;return!0}markExecuted($,b){let w=this.executedHooks.get($);if(w)w.add(b)}cleanup($){this.executedHooks.delete($)}cleanupAll(){this.executedHooks.clear()}}import{z as C}from"zod";var Z1;((V)=>{V.Approve="approve";V.Block="block";V.Async="async"})(Z1||={});var Y1;((V)=>{V.Allow="allow";V.Deny="deny";V.Ask="ask"})(Y1||={});var K$=C.object({hook_event_name:C.nativeEnum(P0),hook_execution_id:C.string(),timestamp:C.string(),project_dir:C.string(),session_id:C.string(),permission_mode:C.enum(["default","autoEdit","yolo","plan"]),_metadata:C.object({blade_version:C.string(),hook_timeout_ms:C.number()}).optional()}),U8=K$.extend({hook_event_name:C.literal("PreToolUse"),tool_name:C.string(),tool_use_id:C.string(),tool_input:C.record(C.unknown())}),F8=K$.extend({hook_event_name:C.literal("PostToolUse"),tool_name:C.string(),tool_use_id:C.string(),tool_input:C.record(C.unknown()),tool_response:C.unknown()}),H8=K$.extend({hook_event_name:C.literal("Stop"),reason:C.string().optional()}),_8=K$.extend({hook_event_name:C.literal("PostToolUseFailure"),tool_name:C.string(),tool_use_id:C.string(),tool_input:C.record(C.unknown()),error:C.string(),error_type:C.string().optional(),is_interrupt:C.boolean(),is_timeout:C.boolean()}),R8=K$.extend({hook_event_name:C.literal("PermissionRequest"),tool_name:C.string(),tool_use_id:C.string(),tool_input:C.record(C.unknown())}),E8=K$.extend({hook_event_name:C.literal("UserPromptSubmit"),user_prompt:C.string(),has_images:C.boolean(),image_count:C.number()}),L8=K$.extend({hook_event_name:C.literal("SessionStart"),is_resume:C.boolean(),resume_session_id:C.string().optional()}),D8=K$.extend({hook_event_name:C.literal("SessionEnd"),reason:C.enum(["user_exit","error","max_turns","idle_timeout","ctrl_c","clear","logout","other"])}),j8=K$.extend({hook_event_name:C.literal("SubagentStart"),agent_type:C.string(),task_description:C.string().optional(),parent_agent_id:C.string().optional()}),N8=K$.extend({hook_event_name:C.literal("SubagentStop"),agent_type:C.string(),task_description:C.string().optional(),success:C.boolean(),result_summary:C.string().optional(),error:C.string().optional()}),S8=K$.extend({hook_event_name:C.literal("TaskCompleted"),task_id:C.string(),task_description:C.string(),result_summary:C.string().optional(),success:C.boolean()}),M8=K$.extend({hook_event_name:C.literal("Notification"),notification_type:C.enum(["permission_prompt","idle_prompt","auth_success","elicitation_dialog","info","warning","error"]),title:C.string().optional(),message:C.string()}),z8=K$.extend({hook_event_name:C.literal("Compaction"),trigger:C.enum(["manual","auto"]),messages_before:C.number(),tokens_before:C.number()}),RW=C.discriminatedUnion("hook_event_name",[U8,F8,H8,_8,R8,E8,L8,D8,j8,N8,S8,M8,z8]),y8=C.object({hookEventName:C.literal("PreToolUse"),permissionDecision:C.nativeEnum(Y1).optional(),permissionDecisionReason:C.string().optional(),updatedInput:C.record(C.unknown()).optional()}),v8=C.object({hookEventName:C.literal("PostToolUse"),additionalContext:C.string().optional(),updatedOutput:C.unknown().optional()}),T8=C.object({hookEventName:C.literal("Stop"),continue:C.boolean().optional(),continueReason:C.string().optional()}),k8=C.object({hookEventName:C.literal("SubagentStart"),additionalContext:C.string().optional()}),f8=C.object({hookEventName:C.literal("SubagentStop"),continue:C.boolean().optional(),continueReason:C.string().optional(),additionalContext:C.string().optional()}),I8=C.object({hookEventName:C.literal("TaskCompleted"),blockCompletion:C.boolean().optional(),blockReason:C.string().optional()}),P8=C.object({hookEventName:C.literal("PermissionRequest"),permissionDecision:C.enum(["approve","deny","ask"]).optional(),permissionDecisionReason:C.string().optional()}),h8=C.object({hookEventName:C.literal("UserPromptSubmit"),updatedPrompt:C.string().optional(),contextInjection:C.string().optional()}),x8=C.object({hookEventName:C.literal("SessionStart"),env:C.record(C.string()).optional()}),p8=C.object({hookEventName:C.literal("Compaction"),blockCompaction:C.boolean().optional(),blockReason:C.string().optional()}),d8=C.object({decision:C.object({behavior:C.nativeEnum(Z1)}).optional(),systemMessage:C.string().optional(),hookSpecificOutput:C.discriminatedUnion("hookEventName",[y8,v8,T8,k8,f8,I8,P8,h8,x8,p8]).optional(),suppressOutput:C.boolean().optional()}),u8=C.object({type:C.literal("command"),command:C.string(),timeout:C.number().positive().optional(),statusMessage:C.string().optional()}),g8=C.object({type:C.literal("prompt"),prompt:C.string(),timeout:C.number().positive().optional()}),m8=C.discriminatedUnion("type",[u8,g8]),J1=C.union([C.string(),C.array(C.string())]),c8=C.object({tools:J1.optional(),paths:J1.optional(),commands:J1.optional()}),B$=C.object({name:C.string().optional(),matcher:c8.optional(),hooks:C.array(m8)}),EW=C.object({enabled:C.boolean().optional(),defaultTimeout:C.number().positive().optional(),timeoutBehavior:C.enum(["ignore","deny","ask"]).optional(),failureBehavior:C.enum(["ignore","deny","ask"]).optional(),maxConcurrentHooks:C.number().positive().optional(),PreToolUse:C.array(B$).optional(),PostToolUse:C.array(B$).optional(),PostToolUseFailure:C.array(B$).optional(),PermissionRequest:C.array(B$).optional(),UserPromptSubmit:C.array(B$).optional(),SessionStart:C.array(B$).optional(),SessionEnd:C.array(B$).optional(),Stop:C.array(B$).optional(),SubagentStart:C.array(B$).optional(),SubagentStop:C.array(B$).optional(),TaskCompleted:C.array(B$).optional(),Notification:C.array(B$).optional(),Compaction:C.array(B$).optional()});function dw($){let b=d8.safeParse($);if(b.success)return{success:!0,data:b.data};return{success:!1,error:b.error}}class X1{parse($,b,w){if($.timedOut){let W=w?.timeoutBehavior||"ignore",Q="Hook timeout";if(W==="deny")return{success:!1,blocking:!0,error:"Hook timeout",stdout:$.stdout,stderr:$.stderr,exitCode:$.exitCode,hook:b};else if(W==="ask")return{success:!1,blocking:!1,needsConfirmation:!0,warning:"Hook timeout. Continue?",stdout:$.stdout,stderr:$.stderr,exitCode:$.exitCode,hook:b};else return{success:!1,blocking:!1,warning:"Hook timeout",stdout:$.stdout,stderr:$.stderr,exitCode:$.exitCode,hook:b}}let V=this.tryParseJSON($.stdout);if(V){let W=dw(V);if(!W.success){let Z="error"in W?W.error.message:"Unknown validation error",Y=w?.failureBehavior||"ignore",J=`Invalid hook output JSON: ${Z}`;if(Y==="deny")return{success:!1,blocking:!0,error:J,stdout:$.stdout,stderr:$.stderr,exitCode:$.exitCode,hook:b};else if(Y==="ask")return{success:!1,blocking:!1,needsConfirmation:!0,warning:`${J}. Continue?`,stdout:$.stdout,stderr:$.stderr,exitCode:$.exitCode,hook:b};else return{success:!1,blocking:!1,warning:J,stdout:$.stdout,stderr:$.stderr,exitCode:$.exitCode,hook:b}}let Q=W.data;if(Q.decision?.behavior==="block")return{success:!1,blocking:!0,error:Q.systemMessage||"Hook blocked execution",output:Q,stdout:$.stdout,stderr:$.stderr,exitCode:$.exitCode,hook:b};if(Q.decision?.behavior==="async")return{success:!0,output:Q,stdout:$.stdout,stderr:$.stderr,exitCode:$.exitCode,hook:b};return{success:!0,output:Q,stdout:$.stdout,stderr:$.stderr,exitCode:$.exitCode,hook:b}}return this.parseByExitCode($,b,w)}parseByExitCode($,b,w){let V=$.exitCode;switch(V){case 0:return{success:!0,stdout:$.stdout,stderr:$.stderr,exitCode:V,hook:b};case 2:return{success:!1,blocking:!0,error:$.stderr||$.stdout||"Hook returned exit code 2",stdout:$.stdout,stderr:$.stderr,exitCode:V,hook:b};case 124:{let W=w?.timeoutBehavior||"ignore",Q="Hook timeout";if(W==="deny")return{success:!1,blocking:!0,error:"Hook timeout",stdout:$.stdout,stderr:$.stderr,exitCode:V,hook:b};else if(W==="ask")return{success:!1,blocking:!1,needsConfirmation:!0,warning:"Hook timeout. Continue?",stdout:$.stdout,stderr:$.stderr,exitCode:V,hook:b};else return{success:!1,blocking:!1,warning:"Hook timeout",stdout:$.stdout,stderr:$.stderr,exitCode:V,hook:b}}default:{let W=w?.failureBehavior||"ignore",Q=$.stderr||$.stdout||`Hook failed with exit code ${V}`;if(W==="deny")return{success:!1,blocking:!0,error:Q,stdout:$.stdout,stderr:$.stderr,exitCode:V,hook:b};else if(W==="ask")return{success:!1,blocking:!1,needsConfirmation:!0,warning:`${Q}. Continue?`,stdout:$.stdout,stderr:$.stderr,exitCode:V,hook:b};else return{success:!1,blocking:!1,warning:Q,stdout:$.stdout,stderr:$.stderr,exitCode:V,hook:b}}}}tryParseJSON($){try{let b=$.trim();if(!b)return null;let w=b.match(/^\s*(\{[\s\S]*\})\s*$/);if(!w)return null;return JSON.parse(w[1])}catch{return null}}}import{spawn as i8}from"child_process";class O1{content="";maxSize;constructor($){this.maxSize=$}append($){if(this.content.length<this.maxSize){let b=this.maxSize-this.content.length;this.content+=$.substring(0,b)}}getContent(){return this.content}isFull(){return this.content.length>=this.maxSize}}class G1{MAX_STDOUT_SIZE=1048576;MAX_STDERR_SIZE=1048576;MAX_INPUT_SIZE=102400;async execute($,b,w,V){let W=JSON.stringify(b);if(W.length>this.MAX_INPUT_SIZE)throw Error(`Hook input too large: ${W.length} bytes (max ${this.MAX_INPUT_SIZE})`);let Q=this.createSafeEnv(b),Z=i8($,[],{shell:!0,env:Q,cwd:w.projectDir,timeout:V}),Y=new O1(this.MAX_STDOUT_SIZE),J=new O1(this.MAX_STDERR_SIZE);Z.stdout.setEncoding("utf8"),Z.stderr.setEncoding("utf8"),Z.stdout.on("data",(X)=>{Y.append(X)}),Z.stderr.on("data",(X)=>{J.append(X)});try{Z.stdin.write(W),Z.stdin.end()}catch(X){throw Z.kill("SIGTERM"),Error(`Failed to write hook input: ${X}`)}return new Promise((X,O)=>{let G=!1,B=!1,q=null,A=()=>{if(q&&w.abortSignal)w.abortSignal.removeEventListener("abort",q),q=null},K=setTimeout(()=>{G=!0,Z.kill("SIGKILL")},V);if(Z.on("close",(U)=>{if(B)return;B=!0,clearTimeout(K),A(),X({stdout:Y.getContent(),stderr:J.getContent(),exitCode:G?124:U??1,timedOut:G})}),Z.on("error",(U)=>{if(B)return;B=!0,clearTimeout(K),A(),O(U)}),w.abortSignal)q=()=>{if(B)return;B=!0,clearTimeout(K),A(),Z.kill("SIGTERM"),X({stdout:Y.getContent(),stderr:"Hook cancelled by abort signal",exitCode:1,timedOut:!1})},w.abortSignal.addEventListener("abort",q)})}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"}}}class B1{processExecutor=new G1;outputParser=new X1;async executePreToolHooks($,b,w){if($.length===0)return{decision:"allow"};let V="tool_input"in b?b.tool_input:{},W=[];for(let Q of $)try{let Z={...b,...V&&{tool_input:V}},Y=await this.executeHook(Q,Z,w);if(!Y.success){if(Y.blocking)return{decision:"deny",reason:Y.error};if(Y.needsConfirmation)return{decision:"ask",reason:Y.warning||Y.error};if(Y.warning)W.push(Y.warning);continue}let J=Y.output?.hookSpecificOutput;if(J&&"permissionDecision"in J){switch(J.permissionDecision){case"deny":return{decision:"deny",reason:J.permissionDecisionReason};case"ask":return{decision:"ask",reason:J.permissionDecisionReason};case"allow":break}if("updatedInput"in J&&J.updatedInput)V={...V,...J.updatedInput}}}catch(Z){let Y=Z instanceof Error?Z.message:String(Z);if(W.push(`Hook failed: ${Y}`),w.config.failureBehavior==="deny")return{decision:"deny",reason:Y};else if(w.config.failureBehavior==="ask")return{decision:"ask",reason:`Hook failed: ${Y}. Continue?`}}return{decision:"allow",modifiedInput:V,warning:W.length>0?W.join(`
|
|
2
|
+
`):void 0}}async executePostToolHooks($,b,w){if($.length===0)return{};let V=w.config.maxConcurrentHooks||5,W=await this.executeHooksConcurrently($,b,w,V),Q=[],Z,Y=[];for(let J of W){if(!J.success&&J.warning){Y.push(J.warning);continue}let X=J.output?.hookSpecificOutput;if(X&&"additionalContext"in X){if(X.additionalContext)Q.push(X.additionalContext);if("updatedOutput"in X&&X.updatedOutput!==void 0)Z=X.updatedOutput}}return{additionalContext:Q.length>0?Q.join(`
|
|
3
|
+
|
|
4
|
+
`):void 0,modifiedOutput:Z,warning:Y.length>0?Y.join(`
|
|
5
|
+
`):void 0}}async executeStopHooks($,b,w){if($.length===0)return{shouldStop:!0};let V=[];for(let W of $)try{let Q=await this.executeHook(W,b,w);if(!Q.success){if(Q.warning)V.push(Q.warning);continue}let Z=Q.output?.hookSpecificOutput;if(Z&&"continue"in Z&&Z.continue===!1)return{shouldStop:!1,continueReason:Z.continueReason,warning:V.length>0?V.join(`
|
|
6
|
+
`):void 0}}catch(Q){let Z=Q instanceof Error?Q.message:String(Q);V.push(`Hook failed: ${Z}`)}return{shouldStop:!0,warning:V.length>0?V.join(`
|
|
7
|
+
`):void 0}}async executeSubagentStartHooks($,b,w){if($.length===0)return{proceed:!0};let V=[],W=[];for(let Q of $)try{let Z=await this.executeHook(Q,b,w);if(!Z.success){if(Z.blocking)return{proceed:!1,warning:Z.error};if(Z.warning)V.push(Z.warning);continue}let Y=Z.output?.hookSpecificOutput;if(Y&&"additionalContext"in Y&&Y.additionalContext)W.push(Y.additionalContext)}catch(Z){let Y=Z instanceof Error?Z.message:String(Z);V.push(`Hook failed: ${Y}`)}return{proceed:!0,additionalContext:W.length>0?W.join(`
|
|
8
|
+
|
|
9
|
+
`):void 0,warning:V.length>0?V.join(`
|
|
10
|
+
`):void 0}}async executeSubagentStopHooks($,b,w){if($.length===0)return{shouldStop:!0};let V=[],W=[];for(let Q of $)try{let Z=await this.executeHook(Q,b,w);if(!Z.success){if(Z.warning)V.push(Z.warning);continue}let Y=Z.output?.hookSpecificOutput;if(Y&&"continue"in Y){if(Y.continue===!1)return{shouldStop:!1,continueReason:Y.continueReason,warning:V.length>0?V.join(`
|
|
11
|
+
`):void 0};if("additionalContext"in Y&&Y.additionalContext)W.push(Y.additionalContext)}}catch(Z){let Y=Z instanceof Error?Z.message:String(Z);V.push(`Hook failed: ${Y}`)}return{shouldStop:!0,additionalContext:W.length>0?W.join(`
|
|
12
|
+
|
|
13
|
+
`):void 0,warning:V.length>0?V.join(`
|
|
14
|
+
`):void 0}}async executeTaskCompletedHooks($,b,w){if($.length===0)return{allowCompletion:!0};let V=[];for(let W of $)try{let Q=await this.executeHook(W,b,w);if(!Q.success){if(Q.blocking)return{allowCompletion:!1,blockReason:Q.error,warning:V.length>0?V.join(`
|
|
15
|
+
`):void 0};if(Q.warning)V.push(Q.warning);continue}let Z=Q.output?.hookSpecificOutput;if(Z&&"blockCompletion"in Z&&Z.blockCompletion)return{allowCompletion:!1,blockReason:Z.blockReason,warning:V.length>0?V.join(`
|
|
16
|
+
`):void 0}}catch(Q){let Z=Q instanceof Error?Q.message:String(Q);V.push(`Hook failed: ${Z}`)}return{allowCompletion:!0,warning:V.length>0?V.join(`
|
|
17
|
+
`):void 0}}async executePermissionRequestHooks($,b,w){if($.length===0)return{decision:"ask"};let V=[];for(let W of $)try{let Q=await this.executeHook(W,b,w);if(!Q.success){if(Q.warning)V.push(Q.warning);continue}let Z=Q.output?.hookSpecificOutput;if(Z&&"permissionDecision"in Z){let Y=Z.permissionDecision;if(Y==="approve"||Y==="deny")return{decision:Y,reason:Z.permissionDecisionReason,warning:V.length>0?V.join(`
|
|
18
|
+
`):void 0}}}catch(Q){let Z=Q instanceof Error?Q.message:String(Q);V.push(`Hook failed: ${Z}`)}return{decision:"ask",warning:V.length>0?V.join(`
|
|
19
|
+
`):void 0}}async executeUserPromptSubmitHooks($,b,w){if($.length===0)return{proceed:!0};let V=[],W=[],Q;for(let Z of $)try{let Y=await this.executeHook(Z,b,w);if(!Y.success){if(Y.blocking)return{proceed:!1,warning:Y.error};if(Y.warning)V.push(Y.warning);continue}if(Y.stdout&&Y.stdout.trim())W.push(Y.stdout.trim());let J=Y.output?.hookSpecificOutput;if(J&&"updatedPrompt"in J){if(J.updatedPrompt)Q=J.updatedPrompt;if(J.contextInjection)W.push(J.contextInjection)}}catch(Y){let J=Y instanceof Error?Y.message:String(Y);V.push(`Hook failed: ${J}`)}return{proceed:!0,updatedPrompt:Q,contextInjection:W.length>0?W.join(`
|
|
20
|
+
|
|
21
|
+
`):void 0,warning:V.length>0?V.join(`
|
|
22
|
+
`):void 0}}async executeSessionStartHooks($,b,w){if($.length===0)return{proceed:!0};let V=[],W={};for(let Q of $)try{let Z=await this.executeHook(Q,b,w);if(!Z.success){if(Z.blocking)return{proceed:!1,warning:Z.error};if(Z.warning)V.push(Z.warning);continue}let Y=Z.output?.hookSpecificOutput;if(Y&&"env"in Y&&Y.env)Object.assign(W,Y.env)}catch(Z){let Y=Z instanceof Error?Z.message:String(Z);V.push(`Hook failed: ${Y}`)}return{proceed:!0,env:Object.keys(W).length>0?W:void 0,warning:V.length>0?V.join(`
|
|
23
|
+
`):void 0}}async executeSessionEndHooks($,b,w){if($.length===0)return{};let V=[],W=w.config.maxConcurrentHooks||5,Q=await this.executeHooksConcurrently($,b,w,W);for(let Z of Q)if(!Z.success&&Z.warning)V.push(Z.warning);return{warning:V.length>0?V.join(`
|
|
24
|
+
`):void 0}}async executePostToolUseFailureHooks($,b,w){if($.length===0)return{};let V=[],W=[],Q=w.config.maxConcurrentHooks||5,Z=await this.executeHooksConcurrently($,b,w,Q);for(let Y of Z){if(!Y.success&&Y.warning){V.push(Y.warning);continue}if(Y.stdout&&Y.stdout.trim())W.push(Y.stdout.trim())}return{additionalContext:W.length>0?W.join(`
|
|
25
|
+
|
|
26
|
+
`):void 0,warning:V.length>0?V.join(`
|
|
27
|
+
`):void 0}}async executeNotificationHooks($,b,w){let V="message"in b?b.message:"";if($.length===0)return{suppress:!1,message:V};let W=[],Q=!1,Z=V;for(let Y of $)try{let J=await this.executeHook(Y,b,w);if(!J.success){if(J.warning)W.push(J.warning);continue}if(J.output?.suppressOutput){Q=!0;break}if(J.stdout&&J.stdout.trim())Z=J.stdout.trim()}catch(J){let X=J instanceof Error?J.message:String(J);W.push(`Hook failed: ${X}`)}return{suppress:Q,message:Z,warning:W.length>0?W.join(`
|
|
28
|
+
`):void 0}}async executeCompactionHooks($,b,w){if($.length===0)return{blockCompaction:!1};let V=[];for(let W of $)try{let Q=await this.executeHook(W,b,w);if(!Q.success){if(Q.warning)V.push(Q.warning);continue}let Z=Q.output?.hookSpecificOutput;if(Z&&"blockCompaction"in Z&&Z.blockCompaction)return{blockCompaction:!0,blockReason:Z.blockReason,warning:V.length>0?V.join(`
|
|
29
|
+
`):void 0}}catch(Q){let Z=Q instanceof Error?Q.message:String(Q);V.push(`Hook failed: ${Z}`)}return{blockCompaction:!1,warning:V.length>0?V.join(`
|
|
30
|
+
`):void 0}}async executeHook($,b,w){if($.type==="command")return this.executeCommandHook($,b,w);throw Error(`Hook type ${$.type} not yet implemented`)}async executeCommandHook($,b,w){let V=($.timeout??w.config.defaultTimeout??60)*1000;try{let W=await this.processExecutor.execute($.command,b,w,V);return this.outputParser.parse(W,$,{timeoutBehavior:w.config.timeoutBehavior,failureBehavior:w.config.failureBehavior})}catch(W){return{success:!1,blocking:!1,error:W instanceof Error?W.message:String(W),hook:$}}}async executeHooksConcurrently($,b,w,V){let W=[],Q=new Set;for(let Z of $){if(Q.size>=V)await Promise.race(Q);let Y=this.executeHook(Z,b,w).catch((X)=>({success:!1,blocking:!1,error:X instanceof Error?X.message:String(X),hook:Z})),J=Y.then(()=>{Q.delete(J)}).catch(()=>{Q.delete(J)});Q.add(J),W.push(Y)}return Promise.all(W)}}import K1 from"picomatch";var l8=/^([A-Za-z0-9_|]+)\((.+)\)$/;class q1{matches($,b){if(!$)return!0;if($.tools&&b.toolName){if(!this.matchTools($.tools,b))return!1}if($.paths&&b.filePath){if(!this.matchPaths($.paths,b.filePath))return!1}if($.commands&&b.command){if(!this.matchCommands($.commands,b.command))return!1}return!0}matchTools($,b){if(Array.isArray($))return $.some((w)=>this.matchToolWithParams(w,b));return this.matchToolWithParams($,b)}matchPaths($,b){if(Array.isArray($))return $.some((V)=>{return K1(V)(b)});return K1($)(b)}matchCommands($,b){if(Array.isArray($))return $.some((w)=>this.matchPattern(b,w));return this.matchPattern(b,$)}matchToolWithParams($,b){let{toolName:w,command:V,filePath:W}=b,Q=l8.exec($);if(!Q)return this.matchPattern(w,$);let[,Z,Y]=Q;if(!this.matchPattern(w,Z))return!1;let J=this.getArgValue(w,V,W);if(!J)return!1;return this.matchGlobOrPattern(J,Y)}getArgValue($,b,w){if($==="Bash"||$==="BashTool")return b;if(["Read","Edit","Write","Glob","Grep"].includes($))return w;return b||w}matchGlobOrPattern($,b){if(/[*?[\]{}!]/.test(b))try{return K1(b,{bash:!0,dot:!0})($)}catch{}if(b.endsWith("*")){let w=b.slice(0,-1);return $.startsWith(w)}return $===b}matchPattern($,b){if(b==="*")return!0;if(!b.includes("|")&&!/[.*+?^${}()|[\]\\]/.test(b))return $===b;if(b.includes("|"))return b.split("|").map((V)=>V.trim()).includes($);try{return new RegExp(b).test($)}catch{return $===b}}}class r{static instance=null;config=V1;executor=new B1;guard=new Q1;matcher=new q1;sessionDisabled=!1;constructor(){}static getInstance(){if(!r.instance)r.instance=new r;return r.instance}loadConfig($){let b=W1(V1,$),w=pw();b=W1(b,w),this.config=b}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"),b=await import("node:path");try{let w=b.join(process.cwd(),".blade","settings.local.json"),V=await $.readFile(w,"utf-8"),W=JSON.parse(V);if(W.hooks)this.loadConfig(W.hooks)}catch{}}async executePreToolHooks($,b,w,V){if(!this.isEnabled())return{decision:"allow"};if(V.permissionMode==="plan")return{decision:"allow"};if(!this.guard.canExecute(b,"PreToolUse"))return{decision:"allow"};let W={hook_event_name:"PreToolUse",hook_execution_id:q$(),timestamp:new Date().toISOString(),tool_name:$,tool_use_id:b,tool_input:w,project_dir:V.projectDir,session_id:V.sessionId,permission_mode:V.permissionMode},Q=this.getMatchingHooks("PreToolUse",{toolName:$,filePath:this.extractFilePath(w),command:this.extractCommand($,w)});if(Q.length===0)return{decision:"allow"};let Z={projectDir:V.projectDir,sessionId:V.sessionId,permissionMode:V.permissionMode,config:this.config,abortSignal:V.abortSignal};try{let Y=await this.executor.executePreToolHooks(Q,W,Z);if(this.guard.markExecuted(b,"PreToolUse"),V.permissionMode==="yolo"){if(Y.decision==="deny")return Y;return{decision:"allow",modifiedInput:Y.modifiedInput,warning:Y.warning,reason:Y.reason}}return Y}catch(Y){return console.error("[HookManager] Error executing PreToolUse hooks:",Y),{decision:"allow",warning:`Hook execution failed: ${Y instanceof Error?Y.message:String(Y)}`}}}async executePostToolHooks($,b,w,V,W){if(!this.isEnabled())return{};if(W.permissionMode==="plan")return{};if(!this.guard.canExecute(b,"PostToolUse"))return{};let Q={hook_event_name:"PostToolUse",hook_execution_id:q$(),timestamp:new Date().toISOString(),tool_name:$,tool_use_id:b,tool_input:w,tool_response:V,project_dir:W.projectDir,session_id:W.sessionId,permission_mode:W.permissionMode},Z=this.getMatchingHooks("PostToolUse",{toolName:$,filePath:this.extractFilePath(w),command:this.extractCommand($,w)});if(Z.length===0)return{};let Y={projectDir:W.projectDir,sessionId:W.sessionId,permissionMode:W.permissionMode,config:this.config,abortSignal:W.abortSignal};try{let J=await this.executor.executePostToolHooks(Z,Q,Y);return this.guard.markExecuted(b,"PostToolUse"),J}catch(J){return console.error("[HookManager] Error executing PostToolUse hooks:",J),{warning:`Hook execution failed: ${J instanceof Error?J.message:String(J)}`}}finally{this.guard.cleanup(b)}}async executeStopHooks($){if(!this.isEnabled())return{shouldStop:!0};let b={hook_event_name:"Stop",hook_execution_id:q$(),timestamp:new Date().toISOString(),project_dir:$.projectDir,session_id:$.sessionId,permission_mode:$.permissionMode,reason:$.reason},w=this.getMatchingHooks("Stop",{});if(w.length===0)return{shouldStop:!0};let V={projectDir:$.projectDir,sessionId:$.sessionId,permissionMode:$.permissionMode,config:this.config,abortSignal:$.abortSignal};try{return await this.executor.executeStopHooks(w,b,V)}catch(W){return console.error("[HookManager] Error executing Stop hooks:",W),{shouldStop:!0,warning:`Hook execution failed: ${W instanceof Error?W.message:String(W)}`}}}async executeSubagentStartHooks($,b){if(!this.isEnabled())return{proceed:!0};let w={hook_event_name:"SubagentStart",hook_execution_id:q$(),timestamp:new Date().toISOString(),project_dir:b.projectDir,session_id:b.sessionId,permission_mode:b.permissionMode,agent_type:$,task_description:b.taskDescription,parent_agent_id:b.parentAgentId},V=this.getMatchingHooks("SubagentStart",{toolName:$});if(V.length===0)return{proceed:!0};let W={projectDir:b.projectDir,sessionId:b.sessionId,permissionMode:b.permissionMode,config:this.config,abortSignal:b.abortSignal};try{return await this.executor.executeSubagentStartHooks(V,w,W)}catch(Q){return console.error("[HookManager] Error executing SubagentStart hooks:",Q),{proceed:!0,warning:`Hook execution failed: ${Q instanceof Error?Q.message:String(Q)}`}}}async executeSubagentStopHooks($,b){if(!this.isEnabled())return{shouldStop:!0};let w={hook_event_name:"SubagentStop",hook_execution_id:q$(),timestamp:new Date().toISOString(),project_dir:b.projectDir,session_id:b.sessionId,permission_mode:b.permissionMode,agent_type:$,task_description:b.taskDescription,success:b.success,result_summary:b.resultSummary,error:b.error},V=this.getMatchingHooks("SubagentStop",{});if(V.length===0)return{shouldStop:!0};let W={projectDir:b.projectDir,sessionId:b.sessionId,permissionMode:b.permissionMode,config:this.config,abortSignal:b.abortSignal};try{return await this.executor.executeSubagentStopHooks(V,w,W)}catch(Q){return console.error("[HookManager] Error executing SubagentStop hooks:",Q),{shouldStop:!0,warning:`Hook execution failed: ${Q instanceof Error?Q.message:String(Q)}`}}}async executeTaskCompletedHooks($,b){if(!this.isEnabled())return{allowCompletion:!0};let w={hook_event_name:"TaskCompleted",hook_execution_id:q$(),timestamp:new Date().toISOString(),project_dir:b.projectDir,session_id:b.sessionId,permission_mode:b.permissionMode,task_id:$,task_description:b.taskDescription,result_summary:b.resultSummary,success:b.success},V=this.getMatchingHooks("TaskCompleted",{});if(V.length===0)return{allowCompletion:!0};let W={projectDir:b.projectDir,sessionId:b.sessionId,permissionMode:b.permissionMode,config:this.config,abortSignal:b.abortSignal};try{return await this.executor.executeTaskCompletedHooks(V,w,W)}catch(Q){return console.error("[HookManager] Error executing TaskCompleted hooks:",Q),{allowCompletion:!0,warning:`Hook execution failed: ${Q instanceof Error?Q.message:String(Q)}`}}}async executePermissionRequestHooks($,b,w,V){if(!this.isEnabled())return{decision:"ask"};let W={hook_event_name:"PermissionRequest",hook_execution_id:q$(),timestamp:new Date().toISOString(),tool_name:$,tool_use_id:b,tool_input:w,project_dir:V.projectDir,session_id:V.sessionId,permission_mode:V.permissionMode},Q=this.getMatchingHooks("PermissionRequest",{toolName:$,filePath:this.extractFilePath(w),command:this.extractCommand($,w)});if(Q.length===0)return{decision:"ask"};let Z={projectDir:V.projectDir,sessionId:V.sessionId,permissionMode:V.permissionMode,config:this.config,abortSignal:V.abortSignal};try{return await this.executor.executePermissionRequestHooks(Q,W,Z)}catch(Y){return console.error("[HookManager] Error executing PermissionRequest hooks:",Y),{decision:"ask",warning:`Hook execution failed: ${Y instanceof Error?Y.message:String(Y)}`}}}async executeUserPromptSubmitHooks($,b){if(!this.isEnabled())return{proceed:!0};let w={hook_event_name:"UserPromptSubmit",hook_execution_id:q$(),timestamp:new Date().toISOString(),user_prompt:$,has_images:b.hasImages,image_count:b.imageCount,project_dir:b.projectDir,session_id:b.sessionId,permission_mode:b.permissionMode},V=this.getMatchingHooks("UserPromptSubmit",{});if(V.length===0)return{proceed:!0};let W={projectDir:b.projectDir,sessionId:b.sessionId,permissionMode:b.permissionMode,config:this.config,abortSignal:b.abortSignal};try{return await this.executor.executeUserPromptSubmitHooks(V,w,W)}catch(Q){return console.error("[HookManager] Error executing UserPromptSubmit hooks:",Q),{proceed:!0,warning:`Hook execution failed: ${Q instanceof Error?Q.message:String(Q)}`}}}async executeSessionStartHooks($){if(!this.isEnabled())return{proceed:!0};let b={hook_event_name:"SessionStart",hook_execution_id:q$(),timestamp:new Date().toISOString(),project_dir:$.projectDir,session_id:$.sessionId,permission_mode:$.permissionMode,is_resume:$.isResume,resume_session_id:$.resumeSessionId},w=this.getMatchingHooks("SessionStart",{});if(w.length===0)return{proceed:!0};let V={projectDir:$.projectDir,sessionId:$.sessionId,permissionMode:$.permissionMode,config:this.config,abortSignal:$.abortSignal};try{return await this.executor.executeSessionStartHooks(w,b,V)}catch(W){return console.error("[HookManager] Error executing SessionStart hooks:",W),{proceed:!0,warning:`Hook execution failed: ${W instanceof Error?W.message:String(W)}`}}}async executeSessionEndHooks($,b){if(!this.isEnabled())return{};let w={hook_event_name:"SessionEnd",hook_execution_id:q$(),timestamp:new Date().toISOString(),project_dir:b.projectDir,session_id:b.sessionId,permission_mode:b.permissionMode,reason:$},V=this.getMatchingHooks("SessionEnd",{});if(V.length===0)return{};let W={projectDir:b.projectDir,sessionId:b.sessionId,permissionMode:b.permissionMode,config:this.config,abortSignal:b.abortSignal};try{return await this.executor.executeSessionEndHooks(V,w,W),{}}catch(Q){return console.error("[HookManager] Error executing SessionEnd hooks:",Q),{warning:`Hook execution failed: ${Q instanceof Error?Q.message:String(Q)}`}}}async executePostToolUseFailureHooks($,b,w,V,W){if(!this.isEnabled())return{};let Q={hook_event_name:"PostToolUseFailure",hook_execution_id:q$(),timestamp:new Date().toISOString(),tool_name:$,tool_use_id:b,tool_input:w,error:V,error_type:W.errorType,is_interrupt:W.isInterrupt,is_timeout:W.isTimeout,project_dir:W.projectDir,session_id:W.sessionId,permission_mode:W.permissionMode},Z=this.getMatchingHooks("PostToolUseFailure",{toolName:$,filePath:this.extractFilePath(w),command:this.extractCommand($,w)});if(Z.length===0)return{};let Y={projectDir:W.projectDir,sessionId:W.sessionId,permissionMode:W.permissionMode,config:this.config,abortSignal:W.abortSignal};try{return await this.executor.executePostToolUseFailureHooks(Z,Q,Y)}catch(J){return console.error("[HookManager] Error executing PostToolUseFailure hooks:",J),{warning:`Hook execution failed: ${J instanceof Error?J.message:String(J)}`}}}async executeNotificationHooks($,b,w){if(!this.isEnabled())return{suppress:!1,message:b};let V={hook_event_name:"Notification",hook_execution_id:q$(),timestamp:new Date().toISOString(),project_dir:w.projectDir,session_id:w.sessionId,permission_mode:w.permissionMode,notification_type:$,title:w.title,message:b},W=this.getMatchingHooks("Notification",{});if(W.length===0)return{suppress:!1,message:b};let Q={projectDir:w.projectDir,sessionId:w.sessionId,permissionMode:w.permissionMode,config:this.config,abortSignal:w.abortSignal};try{return await this.executor.executeNotificationHooks(W,V,Q)}catch(Z){return console.error("[HookManager] Error executing Notification hooks:",Z),{suppress:!1,message:b,warning:`Hook execution failed: ${Z instanceof Error?Z.message:String(Z)}`}}}async executeCompactionHooks($,b){if(!this.isEnabled())return{blockCompaction:!1};let w={hook_event_name:"Compaction",hook_execution_id:q$(),timestamp:new Date().toISOString(),project_dir:b.projectDir,session_id:b.sessionId,permission_mode:b.permissionMode,trigger:$,messages_before:b.messagesBefore,tokens_before:b.tokensBefore},V=this.getMatchingHooks("Compaction",{});if(V.length===0)return{blockCompaction:!1};let W={projectDir:b.projectDir,sessionId:b.sessionId,permissionMode:b.permissionMode,config:this.config,abortSignal:b.abortSignal};try{return await this.executor.executeCompactionHooks(V,w,W)}catch(Q){return console.error("[HookManager] Error executing Compaction hooks:",Q),{blockCompaction:!1,warning:`Hook execution failed: ${Q instanceof Error?Q.message:String(Q)}`}}}getMatchingHooks($,b){let w=this.config[$]||[],V=[];for(let W of w)if(this.matcher.matches(W.matcher,b))V.push(...W.hooks);return V}extractFilePath($){let b=["file_path","path","filePath","source","target"];for(let w of b){let V=$[w];if(typeof V==="string")return V}return}extractCommand($,b){if($==="Bash"||$==="BashTool"){let w=b.command;if(typeof w==="string")return w}return}cleanup(){this.guard.cleanupAll()}}import{appendFileSync as n8,existsSync as s8,mkdirSync as r8,readdirSync as a8,statSync as mw,unlinkSync as o8}from"node:fs";import t8 from"node:os";import A1 from"node:path";var U1;((W)=>{W[W.DEBUG=0]="DEBUG";W[W.INFO=1]="INFO";W[W.WARN=2]="WARN";W[W.ERROR=3]="ERROR"})(U1||={});var a;((B)=>{B.AGENT="Agent";B.UI="UI";B.TOOL="Tool";B.SERVICE="Service";B.CONFIG="Config";B.CONTEXT="Context";B.EXECUTION="Execution";B.LOOP="Loop";B.CHAT="Chat";B.GENERAL="General";B.PROMPTS="Prompts";B.SPEC="Spec"})(a||={});var C1=null,uw=null,gw=!1;function cW($){if(C1!==$)C1=$}async function iW(){}function e8(){if(gw)return uw;gw=!0;try{let $=A1.join(t8.homedir(),".blade","logs");if(!s8($))r8($,{recursive:!0,mode:493});if(mw($).uid===0&&process.getuid&&process.getuid()!==0)return console.error(""),console.error("❌ 权限错误:~/.blade/logs 目录属于 root 用户"),console.error(""),console.error("这通常是因为您曾经使用 sudo 运行过 blade。"),console.error(""),console.error("解决方法:"),console.error(" sudo chown -R $USER:$USER ~/.blade/"),console.error(""),console.error("然后重新运行 blade(不要使用 sudo)"),console.error(""),null;return $5($,30),uw=$,$}catch($){return console.error("[Logger] 无法创建日志目录:",$),null}}function $5($,b){try{let w=a8($),V=Date.now(),W=b*24*60*60*1000;for(let Q of w){if(!Q.startsWith("blade-")||!Q.endsWith(".log")&&!Q.endsWith(".jsonl"))continue;let Z=A1.join($,Q);try{let Y=mw(Z);if(V-Y.mtimeMs>W)o8(Z)}catch(Y){}}}catch(w){}}function b5(){let $=e8();if(!$)return null;let b=C1||"default";return A1.join($,`blade-${b}.jsonl`)}function w5($,b,w){let V=b5();if(!V)return;try{let W={timestamp:new Date().toISOString(),level:U1[b],category:$,message:w};n8(V,JSON.stringify(W)+`
|
|
31
|
+
`)}catch(W){}}class x${static globalDebugConfig=null;enabled;minLevel;category;constructor($={}){if($.enabled!==void 0)this.enabled=$.enabled;else if(x$.globalDebugConfig!==null)this.enabled=Boolean(x$.globalDebugConfig);else this.enabled=!1;this.minLevel=$.minLevel??0,this.category=$.category??"General"}static setGlobalDebug($){x$.globalDebugConfig=$}static clearGlobalDebug(){x$.globalDebugConfig=null}setEnabled($){this.enabled=$}parseDebugFilter($){if(!$)return{enabled:!1};if($===!0||$==="true"||$==="1")return{enabled:!0};let b=String($).trim();if(!b)return{enabled:!0};if(b.startsWith("!"))return{enabled:!0,filter:{mode:"exclude",categories:b.split(",").map((W)=>W.trim().replace(/^!/,"")).filter(Boolean)}};return{enabled:!0,filter:{mode:"include",categories:b.split(",").map((V)=>V.trim()).filter(Boolean)}}}shouldLogCategory($){if(!$)return!0;let b=this.category.toLowerCase();if($.mode==="include")return $.categories.some((w)=>b.includes(w.toLowerCase()));return!$.categories.some((w)=>b.includes(w.toLowerCase()))}shouldLogToConsole($){if(x$.globalDebugConfig!==null){let{enabled:b,filter:w}=this.parseDebugFilter(x$.globalDebugConfig);if(!b)return!1;if($<this.minLevel)return!1;return this.shouldLogCategory(w)}return this.enabled&&$>=this.minLevel}log($,...b){let w=b.map((V)=>typeof V==="object"?JSON.stringify(V):String(V)).join(" ");if(w5(this.category,$,w),this.shouldLogToConsole($)){let V=U1[$],W=`[${this.category}] [${V}]`;console.error(W,...b)}}debug(...$){this.log(0,...$)}info(...$){this.log(1,...$)}warn(...$){this.log(2,...$)}error(...$){this.log(3,...$)}}function z($,b){return new x$({...b,category:$})}var u=new x$({category:"General"});import{ProxyAgent as V5,fetch as W5}from"undici";function Q5(){return process.env.HTTPS_PROXY||process.env.HTTP_PROXY||process.env.https_proxy||process.env.http_proxy}function Z5(){let $=Q5();if($)try{return new V5($)}catch(b){console.warn(`[proxyFetch] Invalid proxy URL: ${$}`)}return}async function cw($,b={}){let{timeout:w=30000,signal:V,...W}=b;if(V?.aborted)throw new DOMException("The operation was aborted.","AbortError");let Q=Z5(),Z=new AbortController,Y=!1,J=setTimeout(()=>{Y=!0,Z.abort()},w),X=()=>Z.abort();V?.addEventListener("abort",X);try{let O={method:W.method,headers:W.headers,body:W.body,signal:Z.signal,dispatcher:Q};return await W5($.toString(),O)}catch(O){if(O instanceof Error&&O.name==="AbortError"){if(Y)throw Error(`Request timeout after ${w}ms`);throw O}throw O}finally{clearTimeout(J),V?.removeEventListener("abort",X)}}var h0=z("Service"),Y5="https://blade-api-proxy.137844255.workers.dev/v1/get-zhipu-key",iw="blade-free-tier",Gb=null;async function lw($){if($!==iw)return $;if(Gb)return h0.debug("使用缓存的内置 API Key"),Gb;try{h0.info("\uD83D\uDD11 正在从代理服务获取内置 API Key...");let b=await cw(Y5,{method:"GET",headers:{Authorization:`Bearer ${iw}`,"Content-Type":"application/json"},timeout:1e4});if(!b.ok){let V=await b.text();throw Error(`获取 API Key 失败: ${b.status} - ${V}`)}let w=await b.json();if(!w.apiKey)throw Error("代理服务返回的数据中没有 apiKey");if(Gb=w.apiKey,h0.info("✅ 成功获取内置 API Key"),w.message)h0.debug(`提示: ${w.message}`);return Gb}catch(b){throw h0.error("❌ 获取内置 API Key 失败:",b),Error(`无法获取内置模型的 API Key: ${b instanceof Error?b.message:"未知错误"}
|
|
32
|
+
`+"请检查网络连接或使用自己的 API Key (/config)")}}import{createAnthropic as J5}from"@ai-sdk/anthropic";import{createAzure as X5}from"@ai-sdk/azure";import{createDeepSeek as O5}from"@ai-sdk/deepseek";import{createGoogleGenerativeAI as G5}from"@ai-sdk/google";import{createOpenAICompatible as F1}from"@ai-sdk/openai-compatible";import{generateText as B5,jsonSchema as nw,Output as K5,streamText as q5}from"ai";var j$=z("Chat");function sw($){let b=new Set;for(let w of $)if(w.role==="assistant"&&w.tool_calls)for(let V of w.tool_calls)b.add(V.id);return $.filter((w)=>{if(w.role==="tool"){if(!w.tool_call_id)return!1;return b.has(w.tool_call_id)}return!0})}function Bb($){if(typeof $==="string")return $;return $.filter((b)=>b.type==="text").map((b)=>b.text).join(`
|
|
33
|
+
`)}function C5($,b={}){try{return JSON.parse($)}catch{return j$.warn("⚠️ [VercelAIChatService] Failed to parse JSON, using fallback",{str:$}),b}}class H1{model;config;constructor($){this.config=$,this.model=this.createModel($),j$.debug("\uD83D\uDE80 [VercelAIChatService] Initialized",{provider:$.provider,model:$.model,providerId:$.providerId})}createModel($){let{provider:b,apiKey:w,baseUrl:V,model:W,customHeaders:Q,providerId:Z,apiVersion:Y}=$;switch(b){case"anthropic":return J5({apiKey:w,baseURL:V||void 0,headers:Q})(W);case"gemini":{if(V&&!this.isGeminiOfficialUrl(V))return F1({name:"gemini",apiKey:w,baseURL:V,headers:Q})(W);return G5({apiKey:w,baseURL:V||void 0})(W)}case"azure-openai":{let J=this.extractAzureResourceName(V);if(J)return X5({apiKey:w,resourceName:J,apiVersion:Y||"2024-08-01-preview"})(W);let X=this.buildAzureBaseUrl(V,W);return F1({name:"azure-openai",apiKey:w,baseURL:X,headers:{...Q,"api-key":w},queryParams:{"api-version":Y||"2024-08-01-preview"}})(W)}default:{if(Z==="deepseek")return O5({apiKey:w,baseURL:V||void 0,headers:Q})(W);return F1({name:Z||"custom",apiKey:w,baseURL:V,headers:Q})(W)}}}extractAzureResourceName($){if(!$)return;let b=$.match(/https:\/\/([^.]+)\.openai\.azure(?:\.com|\.us|\.cn|\.de)/);return b?b[1]:void 0}buildAzureBaseUrl($,b){if(!$)return"";let w=$.replace(/\/$/,"").replace(/\?.*$/,"");if(w.includes("/openai/deployments/"))return w;return`${w}/openai/deployments/${b}`}isGeminiOfficialUrl($){return $.includes("generativelanguage.googleapis.com")||$.includes("aiplatform.googleapis.com")}convertMessages($){let b=[];for(let w of $)if(w.role==="system")if(Array.isArray(w.content)){let V=w.content.find((Q)=>Q.type==="text"),W={role:"system",content:Bb(w.content)};if(V?.providerOptions)W.providerOptions=V.providerOptions;b.push(W)}else b.push({role:"system",content:w.content});else if(w.role==="user")if(Array.isArray(w.content)){let V=w.content.map((W)=>{if(W.type==="text"){let Q={type:"text",text:W.text};if(W.providerOptions)Q.providerOptions=W.providerOptions;return Q}return{type:"image",image:W.image_url.url}});b.push({role:"user",content:V})}else b.push({role:"user",content:w.content});else if(w.role==="assistant")if(w.tool_calls&&w.tool_calls.length>0){let V=w.tool_calls.map((Q)=>{let Z=Q.function;return{type:"tool-call",toolCallId:Q.id,toolName:Z?.name||"",input:C5(Z?.arguments||"{}",{})}}),W=Bb(w.content);if(W)b.push({role:"assistant",content:[{type:"text",text:W},...V]});else b.push({role:"assistant",content:V})}else b.push({role:"assistant",content:Bb(w.content)});else if(w.role==="tool")b.push({role:"tool",content:[{type:"tool-result",toolCallId:w.tool_call_id,toolName:w.name||"unknown",output:{type:"text",value:Bb(w.content)}}]});return b}convertTools($){if(!$||$.length===0)return;let b={};for(let w of $)b[w.name]={description:w.description,inputSchema:nw(w.parameters)};return b}convertToolCalls($){return $.map((b)=>({id:b.toolCallId,type:"function",function:{name:b.toolName,arguments:JSON.stringify(b.args??b.input??{})}}))}convertOutputFormat($){if(!$||$.type!=="json_schema")return;let{json_schema:b}=$;return K5.object({schema:nw(b.schema)})}convertUsage($,b){if(!$)return;let w=$.promptTokens??0,V=$.completionTokens??0,W={promptTokens:w,completionTokens:V,totalTokens:$.totalTokens??w+V};if(b?.anthropic){if(b.anthropic.cacheCreationInputTokens!==void 0)W.cacheCreationInputTokens=b.anthropic.cacheCreationInputTokens;if(b.anthropic.cacheReadInputTokens!==void 0)W.cacheReadInputTokens=b.anthropic.cacheReadInputTokens}return W}async chat($,b,w){let V=Date.now();j$.debug("\uD83D\uDE80 [VercelAIChatService] Starting chat request");let W=sw($),Q=this.convertMessages(W),Z=this.convertTools(b),Y=this.convertOutputFormat(this.config.outputFormat);try{let J=await B5({model:this.model,messages:Q,tools:Z,maxOutputTokens:this.config.maxOutputTokens,temperature:this.config.temperature??0,abortSignal:w,experimental_output:Y}),X=Date.now()-V;j$.debug("\uD83D\uDCE5 [VercelAIChatService] Response received in",X,"ms");let O=J.toolCalls&&J.toolCalls.length>0?this.convertToolCalls(J.toolCalls):void 0,G=Array.isArray(J.reasoning)?J.reasoning.map((B)=>B.text).join(""):void 0;return{content:J.text,reasoningContent:G,toolCalls:O,usage:this.convertUsage(J.usage,J.providerMetadata)}}catch(J){let X=Date.now()-V;throw j$.error("❌ [VercelAIChatService] Chat failed after",X,"ms"),J}}async*streamChat($,b,w){let V=Date.now();j$.debug("\uD83D\uDE80 [VercelAIChatService] Starting stream request");let W=sw($),Q=this.convertMessages(W),Z=this.convertTools(b),Y=this.convertOutputFormat(this.config.outputFormat);try{let J=q5({model:this.model,messages:Q,tools:Z,maxOutputTokens:this.config.maxOutputTokens,temperature:this.config.temperature??0,abortSignal:w,experimental_output:Y});j$.debug("\uD83D\uDCE5 [VercelAIChatService] Stream started");let X=0;for await(let G of J.fullStream)switch(G.type){case"text-delta":yield{content:G.text??G.textDelta};break;case"reasoning-delta":yield{reasoningContent:G.textDelta};break;case"tool-call":yield{toolCalls:[{index:X++,id:G.toolCallId,type:"function",function:{name:G.toolName,arguments:JSON.stringify(G.args??G.input??{})}}]};break;case"finish":yield{finishReason:G.finishReason,usage:this.convertUsage(G.totalUsage,G.providerMetadata)};break}let O=Date.now()-V;j$.debug("✅ [VercelAIChatService] Stream completed in",O,"ms")}catch(J){let X=Date.now()-V;throw j$.error("❌ [VercelAIChatService] Stream failed after",X,"ms"),J}}getConfig(){return{...this.config}}updateConfig($){j$.debug("\uD83D\uDD04 [VercelAIChatService] Updating configuration"),this.config={...this.config,...$},this.model=this.createModel(this.config),j$.debug("✅ [VercelAIChatService] Configuration updated")}}var rw=z("Service"),A5="blade-free-tier";function U5($){return $===A5}function F5($){return{}}async function Kb($){let b=$;if(U5($.apiKey)){rw.info("\uD83D\uDD11 检测到内置 API Key,正在获取...");let w=await lw($.apiKey);b={...$,apiKey:w}}if(b.providerId){let w=F5(b.providerId);if(Object.keys(w).length>0)b={...b,customHeaders:{...w,...b.customHeaders}},rw.debug(`\uD83D\uDD27 注入 ${b.providerId} 特定 headers:`,Object.keys(w))}return H5(b)}function H5($){return new H1($)}import{readFile as _5}from"node:fs/promises";import{basename as R5}from"node:path";class $${static MAX_FILES=5;static MAX_LINES_PER_FILE=1000;static analyzeFiles($){let b=new Map;return $.forEach((V,W)=>{let Q=typeof V.content==="string"?V.content:(V.content||[]).filter((Y)=>Y.type==="text").map((Y)=>Y.text).join(`
|
|
34
|
+
`);if($$.extractFilePathsFromContent(Q).forEach((Y)=>{$$.updateFileReference(b,Y,W,!1)}),V.tool_calls&&Array.isArray(V.tool_calls))V.tool_calls.forEach((Y)=>{let J=$$.extractFilePathsFromToolCall(Y),X=Y.type==="function"&&"function"in Y?Y.function?.name:"",O=["Write","Edit"].includes(X||"");J.forEach((G)=>{$$.updateFileReference(b,G,W,O)})})}),Array.from(b.values()).sort((V,W)=>{if(V.wasModified!==W.wasModified)return V.wasModified?-1:1;if(V.mentions!==W.mentions)return W.mentions-V.mentions;return W.lastMentioned-V.lastMentioned}).slice(0,$$.MAX_FILES)}static async readFilesContent($){let b=[];for(let w of $)try{let V=await _5(w,"utf-8"),W=V.split(`
|
|
35
|
+
`),Q=W.length,Z=V,Y=!1,J=Q;if(Q>$$.MAX_LINES_PER_FILE)Z=W.slice(0,$$.MAX_LINES_PER_FILE).join(`
|
|
36
|
+
`),Z+=`
|
|
37
|
+
|
|
38
|
+
... (truncated ${Q-$$.MAX_LINES_PER_FILE} lines)`,Y=!0,J=$$.MAX_LINES_PER_FILE;b.push({path:w,content:Z,truncated:Y,lines:Q,includedLines:J})}catch(V){console.warn(`[FileAnalyzer] 无法读取文件: ${w}`,V)}return b}static extractFilePathsFromContent($){let b=new Set,w=/```(?:\w+)?\s*\n?([\s\S]*?)```/g,V=Array.from($.matchAll(w));for(let Q of V){let Z=Q[1];$$.extractPathsFromText(Z).forEach((J)=>b.add(J))}return $$.extractPathsFromText($).forEach((Q)=>b.add(Q)),Array.from(b)}static extractPathsFromText($){let b=[],w=[/(?: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 V of w){let W=Array.from($.matchAll(V));for(let Q of W){let Z=Q[0];if(Z=Z.replace(/[,。;:!?""''()【】《》]$/g,""),Z=Z.replace(/[,.;:!?"'()[\]<>]$/g,""),$$.isValidFilePath(Z))b.push(Z)}}return b}static extractFilePathsFromToolCall($){let b=[];if($.type!=="function"||!$.function)return b;try{let w=$.function.name,V=JSON.parse($.function.arguments||"{}");if(["Read","Write","Edit","Glob","Grep","NotebookEdit","mcp__github__get_file_contents","mcp__github__create_or_update_file"].includes(w)){let Q=["file_path","path","notebook_path","filePath"];for(let Z of Q)if(V[Z]&&typeof V[Z]==="string")b.push(V[Z])}}catch{}return b}static updateFileReference($,b,w,V){let W=$.get(b);if(W)W.mentions++,W.lastMentioned=w,W.wasModified=W.wasModified||V;else $.set(b,{path:b,mentions:1,lastMentioned:w,wasModified:V})}static isValidFilePath($){if(!$.includes("/"))return!1;let b=R5($);if(!b.includes("."))return!1;let w=["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"],V=b.split(".").pop()?.toLowerCase();if(!V||!w.includes(V))return!1;return!0}}import{encodingForModel as aw}from"js-tiktoken";class Z${static encodingCache=new Map;static countTokens($,b){let w=Z$.getEncoding(b),V=0;for(let W of $){if(V+=4,W.role)V+=w.encode(W.role).length;if(W.content)if(typeof W.content==="string")V+=w.encode(W.content).length;else V+=w.encode(JSON.stringify(W.content)).length;if(W.tool_calls&&Array.isArray(W.tool_calls))V+=Z$.countToolCallTokens(W.tool_calls,w);if(W.name)V+=w.encode(W.name).length}return V}static getTokenLimit($){return $}static shouldCompact($,b,w,V=0.8){let W=Z$.countTokens($,b),Q=Math.floor(w*V);return W>=Q}static getEncoding($){if(!Z$.encodingCache.has($))try{let b=aw($);Z$.encodingCache.set($,b)}catch{try{let b=aw("gpt-4");Z$.encodingCache.set($,b)}catch{console.warn(`[TokenCounter] 无法为模型 ${$} 获取 encoding,使用粗略估算`),Z$.encodingCache.set($,{encode:(b)=>{return Array(Math.ceil(b.length/4))}})}}return Z$.encodingCache.get($)}static countToolCallTokens($,b){let w=0;for(let V of $){if(w+=4,V.type==="function"&&V.function?.name)w+=b.encode(V.function.name).length;if(V.type==="function"&&V.function?.arguments)w+=b.encode(V.function.arguments).length;if(V.id)w+=b.encode(V.id).length}return w}static clearCache(){Z$.encodingCache.clear()}static estimateTokens($){let b=($.match(/[\u4e00-\u9fa5]/g)||[]).length,w=$.length-b;return Math.ceil(b/1.5+w/4)}}class b${static THRESHOLD_PERCENT=0.8;static RETAIN_PERCENT=0.2;static FALLBACK_RETAIN_PERCENT=0.3;static async compact($,b){let w=b.actualPreTokens??Z$.countTokens($,b.modelName),V=b.actualPreTokens?"actual (from LLM usage)":"estimated";console.log(`[CompactionService] preTokens source: ${V}`);try{let Q=await r.getInstance().executeCompactionHooks(b.trigger,{projectDir:process.cwd(),sessionId:b.sessionId||"unknown",permissionMode:b.permissionMode||v.DEFAULT,messagesBefore:$.length,tokensBefore:w});if(Q.blockCompaction)return console.log(`[CompactionService] Compaction hook 阻止压缩: ${Q.blockReason||"(无原因)"}`),{success:!1,summary:"",preTokens:w,postTokens:w,filesIncluded:[],compactedMessages:$,boundaryMessage:{role:"system",content:""},summaryMessage:{role:"user",content:""},error:Q.blockReason||"Compaction blocked by hook"};if(Q.warning)console.warn(`[CompactionService] Compaction hook warning: ${Q.warning}`)}catch(W){console.warn("[CompactionService] Compaction hook execution failed:",W)}try{console.log("[CompactionService] 开始压缩,消息数:",$.length),console.log("[CompactionService] 压缩前 tokens:",w);let Q=$$.analyzeFiles($).map((_)=>_.path);console.log("[CompactionService] 提取重点文件:",Q);let Z=await $$.readFilesContent(Q);console.log("[CompactionService] 成功读取文件:",Z.length);let Y=await b$.generateSummary($,Z,b);console.log("[CompactionService] 生成总结,长度:",Y.length);let J=Math.ceil($.length*b$.RETAIN_PERCENT),X=$.slice(-J),O=new Set;for(let _ of X)if(_.role==="assistant"&&_.tool_calls)for(let D of _.tool_calls)O.add(D.id);let G=X.filter((_)=>{if(_.role==="tool"&&_.tool_call_id)return O.has(_.tool_call_id);return!0});console.log("[CompactionService] 保留消息数:",J),console.log("[CompactionService] 过滤后保留消息数:",G.length);let B=U0(),q=b$.createBoundaryMessage(B,b.trigger,w),A=U0(),K=b$.createSummaryMessage(A,Y),U=[K,...G],F=Z$.countTokens(U,b.modelName);return console.log("[CompactionService] 压缩完成!"),console.log("[CompactionService] Token 变化:",w,"→",F,`(-${((1-F/w)*100).toFixed(1)}%)`),{success:!0,summary:Y,preTokens:w,postTokens:F,filesIncluded:Q,compactedMessages:U,boundaryMessage:q,summaryMessage:K}}catch(W){return console.error("[CompactionService] 压缩失败,使用降级策略",W),b$.fallbackCompact($,b,w,W)}}static async generateSummary($,b,w){let V=b$.buildCompactionPrompt($,b);console.log("[CompactionService] 使用压缩模型:",w.modelName);let Z=(await(await Kb({apiKey:w.apiKey||process.env.BLADE_API_KEY||"",baseUrl:w.baseURL||process.env.BLADE_BASE_URL||"https://api.openai.com/v1",model:w.modelName,temperature:0.3,maxOutputTokens:8000,timeout:60000,provider:"openai-compatible"})).chat([{role:"user",content:V}])).content||"",Y=Z.match(/<summary>([\s\S]*?)<\/summary>/);if(!Y)return console.warn("[CompactionService] 总结格式不正确,使用完整响应"),Z;return Y[1].trim()}static buildCompactionPrompt($,b){let w=$.map((Q,Z)=>{let Y=Q.role||"unknown",J=typeof Q.content==="string"?Q.content:JSON.stringify(Q.content),X=5000,O=J.length>5000?J.substring(0,5000)+"...":J;return`[${Z+1}] ${Y}: ${O}`}).join(`
|
|
39
|
+
|
|
40
|
+
`),V=b.map((Q)=>{return`### ${Q.path}
|
|
41
41
|
\`\`\`
|
|
42
|
-
${
|
|
42
|
+
${Q.content}
|
|
43
43
|
\`\`\``}).join(`
|
|
44
44
|
|
|
45
|
-
`),
|
|
45
|
+
`),W=`Your task is to create a detailed summary of the conversation so far, paying close attention to the user's explicit requests and your previous actions.
|
|
46
46
|
This summary should be thorough in capturing technical details, code patterns, and architectural decisions that would be essential for continuing development work without losing context.
|
|
47
47
|
|
|
48
48
|
Before providing your final summary, wrap your analysis in <analysis> tags to organize your thoughts and ensure you've covered all necessary points. In your analysis process:
|
|
@@ -102,57 +102,57 @@ Your summary should include the following sections:
|
|
|
102
102
|
|
|
103
103
|
## Conversation History
|
|
104
104
|
|
|
105
|
-
${
|
|
105
|
+
${w}
|
|
106
106
|
|
|
107
|
-
${
|
|
107
|
+
${b.length>0?`## Important Files
|
|
108
108
|
|
|
109
|
-
${
|
|
109
|
+
${V}`:""}
|
|
110
110
|
|
|
111
|
-
Please provide your summary following the structure specified above, with both <analysis> and <summary> sections.`}static createBoundaryMessage($,
|
|
111
|
+
Please provide your summary following the structure specified above, with both <analysis> and <summary> sections.`}static createBoundaryMessage($,b,w){return{id:U0(),role:"system",content:"Conversation compacted",metadata:{type:"system",subtype:"compact_boundary",parentId:$,compactMetadata:{trigger:b,preTokens:w}}}}static createSummaryMessage($,b){return{id:U0(),role:"user",content:b,metadata:{parentId:$,isCompactSummary:!0}}}static fallbackCompact($,b,w,V){let W=Math.ceil($.length*b$.FALLBACK_RETAIN_PERCENT),Q=$.slice(-W),Z=new Set;for(let K of Q)if(K.role==="assistant"&&K.tool_calls)for(let U of K.tool_calls)Z.add(U.id);let Y=Q.filter((K)=>{if(K.role==="tool"&&K.tool_call_id)return Z.has(K.tool_call_id);return!0}),J=U0(),X=b$.createBoundaryMessage(J,b.trigger,w),O=V instanceof Error?V.message:String(V),G=U0(),B=b$.createSummaryMessage(G,`[Automatic compaction failed; using fallback]
|
|
112
112
|
|
|
113
|
-
An error occurred during compaction. Retained the latest ${
|
|
113
|
+
An error occurred during compaction. Retained the latest ${W} messages (~30%).
|
|
114
114
|
|
|
115
|
-
Error: ${
|
|
115
|
+
Error: ${O}
|
|
116
116
|
|
|
117
|
-
The conversation can continue, but consider retrying compaction later with /compact.`),
|
|
118
|
-
`),preTokens:
|
|
119
|
-
`),
|
|
120
|
-
`;
|
|
121
|
-
${
|
|
122
|
-
`)}`;return new
|
|
117
|
+
The conversation can continue, but consider retrying compaction later with /compact.`),q=[B,...Y],A=Z$.countTokens(q,b.modelName);return{success:!1,summary:typeof B.content==="string"?B.content:B.content.filter((K)=>K.type==="text").map((K)=>K.text).join(`
|
|
118
|
+
`),preTokens:w,postTokens:A,filesIncluded:[],compactedMessages:q,boundaryMessage:X,summaryMessage:B,error:O}}}import{appendFileSync as E5,mkdirSync as L5,writeFileSync as D5}from"node:fs";import j5 from"node:os";import tw from"node:path";var _1=tw.join(j5.homedir(),".blade","logs","stream-debug.log"),ow=!1;function N5(){if(ow)return;let $=tw.dirname(_1);L5($,{recursive:!0,mode:493}),D5(_1,`=== Stream Debug Log Started: ${new Date().toISOString()} ===
|
|
119
|
+
`),ow=!0}function qb($,b,w){N5();let V=new Date().toISOString(),W=w?` | ${JSON.stringify(w)}`:"",Q=`[${V}] [${$}] ${b}${W}
|
|
120
|
+
`;E5(_1,Q)}import{EventEmitter as u5}from"events";import{z as H$}from"zod";function N9($){return $!==void 0&&typeof $.pattern==="string"&&typeof $.search_path==="string"}function S9($){return $!==void 0&&$.kind==="edit"&&typeof $.matches_found==="number"}function F0($){return $==="readonly"}import{isPlainObject as S5}from"lodash-es";class R1{toolName;params;context;aborted=!1;result;_internal={};constructor($,b,w){this.toolName=$;this.params=b;this.context=w}shouldAbort(){return this.aborted||(this.context.signal?.aborted??!1)}abort($,b){this.aborted=!0,this.result={success:!1,llmContent:`Tool execution aborted: ${$||"Unknown reason"}`,displayContent:`执行已中止: ${$||"未知原因"}`,error:{type:"execution_error",message:$||"Execution aborted"},metadata:b?.shouldExitLoop?{shouldExitLoop:!0}:void 0}}setResult($){this.result=$}getResult(){if(!this.result)throw Error("Tool execution result not set");return this.result}}function x0($){if($===void 0)return"undefined";if(typeof $==="string")return $;try{let b=JSON.stringify($);return b===void 0?String($):b}catch{return String($)}}class ew extends Error{issues;type;constructor($,b,w="validation_error"){super($);this.issues=b;this.type=w;this.name="ToolValidationError"}}function M5($){let{code:b}=$,w=$,V=w.received;switch(b){case"invalid_type":{let W=w.expected;return`类型错误:期望 ${x0(W)},实际收到 ${x0(V)}`}case"too_small":{let{minimum:W,inclusive:Q}=w,Z=typeof w.type==="string"?w.type:void 0;if(Z==="string"&&typeof W==="number")return`长度不能少于 ${W} 个字符`;if(Z==="number"&&typeof W==="number")return`不能小于${Q?"等于":""} ${W}`;if(Z==="array"&&typeof W==="number")return`数组长度不能少于 ${W}`;return"值太小"}case"too_big":{let{maximum:W,inclusive:Q}=w,Z=typeof w.type==="string"?w.type:void 0;if(Z==="string"&&typeof W==="number")return`长度不能超过 ${W} 个字符`;if(Z==="number"&&typeof W==="number")return`不能大于${Q?"等于":""} ${W}`;if(Z==="array"&&typeof W==="number")return`数组长度不能超过 ${W}`;return"值太大"}case"invalid_string":{let W=w.validation;if(W==="email")return"必须是有效的电子邮件地址";if(W==="url")return"必须是有效的 URL";if(W==="uuid")return"必须是有效的 UUID";if(S5(W)){let Q=W;if(typeof Q.includes==="string")return`必须包含 "${Q.includes}"`;if(typeof Q.startsWith==="string")return`必须以 "${Q.startsWith}" 开头`;if(typeof Q.endsWith==="string")return`必须以 "${Q.endsWith}" 结尾`}return"字符串格式不正确"}case"invalid_enum_value":{let W=w.options;if(Array.isArray(W))return`必须是以下值之一:${W.map((Q)=>x0(Q)).join(", ")}`;return"必须是枚举允许的值之一"}case"invalid_literal":{let W=w.expected;return`必须是字面量值:${x0(W)}`}case"unrecognized_keys":{let W=w.keys;if(Array.isArray(W))return`包含未知的参数:${W.map((Q)=>x0(Q)).join(", ")}`;return"包含未知的参数"}case"invalid_union":return"不符合任何有效的类型定义";case"invalid_date":return"必须是有效的日期";case"custom":return $.message||"自定义验证失败";default:return $.message||"验证失败"}}function z5($){let b=$.issues.map((V)=>{let W=V.path.join("."),Q=M5(V),Z=V.received;return{field:W||"root",message:Q,value:Z}}),w=b.length===1?`参数验证失败 [${b[0].field}]: ${b[0].message}`:`参数验证失败 (${b.length} 个错误):
|
|
121
|
+
${b.map((V)=>` - ${V.field}: ${V.message}`).join(`
|
|
122
|
+
`)}`;return new ew(w,b)}function $4($,b){let w=$.safeParse(b);if(!w.success)throw z5(w.error);return w.data}import{zodToJsonSchema as y5}from"zod-to-json-schema";function E1($){return y5($,{target:"jsonSchema7",$refStrategy:"none"})}class Cb{toolName;params;executeFn;descriptionFn;affectedPathsFn;constructor($,b,w,V,W){this.toolName=$;this.params=b;this.executeFn=w;this.descriptionFn=V;this.affectedPathsFn=W}getDescription(){if(this.descriptionFn)return this.descriptionFn(this.params);return`执行工具: ${this.toolName}`}getAffectedPaths(){if(this.affectedPathsFn)return this.affectedPathsFn(this.params);return[]}async execute($,b,w){let V={signal:$,updateOutput:b,...w};return this.executeFn(this.params,V)}}function E($){return{name:$.name,displayName:$.displayName,kind:$.kind,isReadOnly:$.isReadOnly??F0($.kind),isConcurrencySafe:$.isConcurrencySafe??!0,strict:$.strict??!1,description:$.description,version:$.version||"1.0.0",category:$.category,tags:$.tags||[],getFunctionDeclaration(){let b=E1($.schema),w=$.description.short;if($.description.long)w+=`
|
|
123
123
|
|
|
124
|
-
${$.description.long}`;if($.description.usageNotes&&$.description.usageNotes.length>0)
|
|
124
|
+
${$.description.long}`;if($.description.usageNotes&&$.description.usageNotes.length>0)w+=`
|
|
125
125
|
|
|
126
126
|
Usage Notes:
|
|
127
|
-
${$.description.usageNotes.map((
|
|
128
|
-
`)}`;if($.description.important&&$.description.important.length>0)
|
|
127
|
+
${$.description.usageNotes.map((V)=>`- ${V}`).join(`
|
|
128
|
+
`)}`;if($.description.important&&$.description.important.length>0)w+=`
|
|
129
129
|
|
|
130
130
|
Important:
|
|
131
|
-
${$.description.important.map((
|
|
132
|
-
`)}`;return{name:$.name,description:
|
|
131
|
+
${$.description.important.map((V)=>`⚠️ ${V}`).join(`
|
|
132
|
+
`)}`;return{name:$.name,description:w,parameters:b}},getMetadata(){return{name:$.name,displayName:$.displayName,kind:$.kind,version:$.version||"1.0.0",category:$.category,tags:$.tags||[],description:$.description,schema:E1($.schema)}},build(b){let w=$4($.schema,b);return new Cb($.name,w,$.execute)},async execute(b,w){return this.build(b).execute(w||new AbortController().signal)},extractSignatureContent:$.extractSignatureContent?(b)=>$.extractSignatureContent(b):void 0,abstractPermissionRule:$.abstractPermissionRule?(b)=>$.abstractPermissionRule(b):void 0}}function v5($){let b=typeof $.description==="string"?{short:$.description}:$.description;return{name:$.name,displayName:$.displayName||$.name,kind:$.kind||"execute",isReadOnly:$.kind?F0($.kind):!1,isConcurrencySafe:!0,strict:!1,description:b,version:"1.0.0",tags:[],getFunctionDeclaration(){let w=b.short;if(b.long)w+=`
|
|
133
133
|
|
|
134
|
-
${
|
|
134
|
+
${b.long}`;if(b.usageNotes&&b.usageNotes.length>0)w+=`
|
|
135
135
|
|
|
136
136
|
Usage Notes:
|
|
137
|
-
${
|
|
138
|
-
`)}`;if(
|
|
137
|
+
${b.usageNotes.map((V)=>`- ${V}`).join(`
|
|
138
|
+
`)}`;if(b.important&&b.important.length>0)w+=`
|
|
139
139
|
|
|
140
140
|
Important:
|
|
141
|
-
${
|
|
142
|
-
`)}`;return{name:$.name,description:
|
|
143
|
-
`,
|
|
144
|
-
`;else if(
|
|
145
|
-
`,
|
|
146
|
-
`}if(
|
|
147
|
-
${
|
|
141
|
+
${b.important.map((V)=>`⚠️ ${V}`).join(`
|
|
142
|
+
`)}`;return{name:$.name,description:w,parameters:$.parameters}},getMetadata(){return{name:$.name,displayName:$.displayName||$.name,kind:$.kind||"execute",version:"1.0.0",description:b,schema:$.parameters}},build(w){return new Cb($.name,w,async(V,W)=>$.execute(V,W))},async execute(w,V){let W={signal:V};return $.execute(w,W)}}}function T5($){return $}function d0($,b,w,V){let W;try{W=p0(w.inputSchema)}catch(Z){console.warn(`[createMcpTool] Schema 转换失败,使用降级 schema: ${w.name}`,Z),W=H$.any()}let Q=V||w.name;return E({name:Q,displayName:`${b}: ${w.name}`,kind:"execute",schema:W,description:{short:w.description||`MCP Tool: ${w.name}`,important:[`From MCP server: ${b}`,"Executes external tools; user confirmation required"]},category:"MCP tool",tags:["mcp","external",b],async execute(Z,Y){try{let J=await $.callTool(w.name,Z),X="",O="";if(J.content&&Array.isArray(J.content)){for(let G of J.content)if(G.type==="text"&&G.text)X+=G.text,O+=G.text;else if(G.type==="image")O+=`[图片: ${G.mimeType||"unknown"}]
|
|
143
|
+
`,X+=`[image: ${G.mimeType||"unknown"}]
|
|
144
|
+
`;else if(G.type==="resource")O+=`[资源: ${G.mimeType||"unknown"}]
|
|
145
|
+
`,X+=`[resource: ${G.mimeType||"unknown"}]
|
|
146
|
+
`}if(J.isError)return{success:!1,llmContent:X||"MCP tool execution failed",displayContent:`❌ ${O||"MCP工具执行失败"}`,error:{type:"execution_error",message:X||"MCP tool execution failed"}};return{success:!0,llmContent:X||"Execution succeeded",displayContent:`✅ MCP工具 ${w.name} 执行成功
|
|
147
|
+
${O}`,metadata:{serverName:b,toolName:w.name,mcpResult:J}}}catch(J){return{success:!1,llmContent:`MCP tool execution failed: ${J.message}`,displayContent:`❌ ${J.message}`,error:{type:"execution_error",message:J.message}}}}})}function p0($){if($.type==="object"||$.properties){let b={},w=$.required||[];if($.properties){for(let[V,W]of Object.entries($.properties))if(typeof W==="object"&&W!==null){let Q=p0(W);if(!w.includes(V))Q=Q.optional();b[V]=Q}}return H$.object(b)}if($.type==="array"&&$.items){if(typeof $.items==="object"&&!Array.isArray($.items)&&$.items!==null)return H$.array(p0($.items));return H$.array(H$.any())}if($.type==="string"){let b=H$.string();if($.minLength!==void 0)b=b.min($.minLength);if($.maxLength!==void 0)b=b.max($.maxLength);if($.pattern)b=b.regex(new RegExp($.pattern));if($.enum)return H$.enum($.enum);return b}if($.type==="number"||$.type==="integer"){let b=H$.number();if($.minimum!==void 0)b=b.min($.minimum);if($.maximum!==void 0)b=b.max($.maximum);return b}if($.type==="boolean")return H$.boolean();if($.oneOf&&$.oneOf.length>0){let b=$.oneOf.filter((w)=>typeof w==="object"&&w!==null).map((w)=>p0(w));if(b.length>=2)return H$.union(b)}if($.anyOf&&$.anyOf.length>0){let b=$.anyOf.filter((w)=>typeof w==="object"&&w!==null).map((w)=>p0(w));if(b.length>=2)return H$.union(b)}return H$.any()}import{Client as h5}from"@modelcontextprotocol/sdk/client/index.js";import{SSEClientTransport as x5}from"@modelcontextprotocol/sdk/client/sse.js";import{StdioClientTransport as p5}from"@modelcontextprotocol/sdk/client/stdio.js";import{EventEmitter as d5}from"events";var L1={name:"@blade-ai/agent-sdk",version:"0.1.4",private:!1,description:"Blade AI Agent SDK",type:"module",main:"./dist/index.js",types:"./dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js"}},files:["dist","vendor/ripgrep/**","README.md","CHANGELOG.md"],scripts:{build:"bun run scripts/build.ts",test:"bun test",lint:"biome lint src","lint:fix":"biome lint --write src","type-check":"bun x tsc --noEmit",release:"bun run scripts/release.js","release:dry":"bun run scripts/release.js --dry-run","release:major":"bun run scripts/release.js --major","release:minor":"bun run scripts/release.js --minor","release:patch":"bun run scripts/release.js --patch"},keywords:["sdk","blade","ai","assistant","agent","llm","bun"],author:"echoVic",license:"MIT",optionalDependencies:{"@vscode/ripgrep":"^1.17.0","bun-pty":"^0.4.8","node-pty":"1.0.0"},dependencies:{"@agentclientprotocol/sdk":"^0.12.0","@ai-sdk/anthropic":"^3.0.7","@ai-sdk/azure":"^3.0.5","@ai-sdk/deepseek":"^2.0.4","@ai-sdk/google":"^3.0.4","@ai-sdk/openai-compatible":"^2.0.4","@modelcontextprotocol/sdk":"^1.17.4",ai:"^6.0.39","async-mutex":"^0.5.0",axios:"^1.12.2",chalk:"^5.4.1",diff:"^8.0.2","fast-glob":"^3.3.3","fuse.js":"^7.1.0","gray-matter":"^4.0.3",hono:"^4.7.10","js-tiktoken":"^1.0.21","lodash-es":"^4.17.21","lru-cache":"^11.2.4",nanoid:"^5.1.6",open:"^10.1.2",openai:"^6.2.0",picomatch:"^4.0.3",semver:"^7.7.3",undici:"^7.16.0","write-file-atomic":"^7.0.0",ws:"^8.18.0",yaml:"^2.8.1",zod:"^3.24.2","zod-to-json-schema":"^3.24.6",zustand:"^5.0.9"},devDependencies:{"@biomejs/biome":"^2.2.4","@types/json-schema":"^7.0.15","@types/lodash-es":"^4.17.12","@types/picomatch":"^4.0.2","@types/semver":"^7.7.1","@types/write-file-atomic":"^4.0.3","@types/ws":"^8.5.12","bun-types":"latest",typescript:"^5.9.2"}};function b4(){return L1.version}function w4(){return L1.name}import{spawn as I5}from"child_process";import*as g0 from"crypto";import*as Q4 from"http";import{URL as V4}from"url";import{promises as D1}from"fs";import f5 from"os";import j1 from"path";class N1{tokenFilePath;constructor(){let $=f5.homedir(),b=j1.join($,".blade");this.tokenFilePath=j1.join(b,"mcp-oauth-tokens.json")}async ensureConfigDir(){let $=j1.dirname(this.tokenFilePath);try{await D1.mkdir($,{recursive:!0,mode:493})}catch{}}async loadAllCredentials(){let $=new Map;try{let b=await D1.readFile(this.tokenFilePath,"utf-8"),w=JSON.parse(b);for(let V of w)$.set(V.serverName,V)}catch(b){if(b.code!=="ENOENT")console.warn("[OAuthTokenStorage] 加载令牌失败:",b)}return $}async saveAllCredentials($){await this.ensureConfigDir();let b=Array.from($.values());await D1.writeFile(this.tokenFilePath,JSON.stringify(b,null,2),{mode:384})}async saveToken($,b,w,V){let W=await this.loadAllCredentials(),Q={serverName:$,token:b,clientId:w,tokenUrl:V,updatedAt:Date.now()};W.set($,Q),await this.saveAllCredentials(W)}async getCredentials($){return(await this.loadAllCredentials()).get($)||null}async deleteCredentials($){let b=await this.loadAllCredentials();b.delete($),await this.saveAllCredentials(b)}async listServers(){let $=await this.loadAllCredentials();return Array.from($.keys())}isTokenExpired($){if(!$.expiresAt)return!1;let b=300000;return Date.now()>=$.expiresAt-b}}var u0=7777,S1="/oauth/callback",W4=200;class Ab{tokenStorage;constructor($=new N1){this.tokenStorage=$}generatePKCEParams(){let $=g0.randomBytes(32).toString("base64url"),b=g0.createHash("sha256").update($).digest("base64url"),w=g0.randomBytes(16).toString("base64url");return{codeVerifier:$,codeChallenge:b,state:w}}buildAuthorizationUrl($,b){let w=$.redirectUri||`http://localhost:${u0}${S1}`,V=new URLSearchParams({client_id:$.clientId,response_type:"code",redirect_uri:w,state:b.state,code_challenge:b.codeChallenge,code_challenge_method:"S256"});if($.scopes&&$.scopes.length>0)V.append("scope",$.scopes.join(" "));let W=new V4($.authorizationUrl);return V.forEach((Q,Z)=>{W.searchParams.append(Z,Q)}),W.toString()}async startCallbackServer($){return new Promise((b,w)=>{let V=Q4.createServer((W,Q)=>{try{let Z=new V4(W.url,`http://localhost:${u0}`);if(Z.pathname!==S1){Q.writeHead(404),Q.end("Not found");return}let Y=Z.searchParams.get("code"),J=Z.searchParams.get("state"),X=Z.searchParams.get("error");if(X){Q.writeHead(W4,{"Content-Type":"text/html"}),Q.end(`
|
|
148
148
|
<html>
|
|
149
149
|
<body>
|
|
150
150
|
<h1>Authentication Failed</h1>
|
|
151
|
-
<p>Error: ${
|
|
151
|
+
<p>Error: ${X}</p>
|
|
152
152
|
<p>You can close this window.</p>
|
|
153
153
|
</body>
|
|
154
154
|
</html>
|
|
155
|
-
`),
|
|
155
|
+
`),V.close(),w(Error(`OAuth error: ${X}`));return}if(!Y||!J){Q.writeHead(400),Q.end("Missing code or state parameter");return}if(J!==$){Q.writeHead(400),Q.end("Invalid state parameter"),V.close(),w(Error("State mismatch - possible CSRF attack"));return}Q.writeHead(W4,{"Content-Type":"text/html"}),Q.end(`
|
|
156
156
|
<html>
|
|
157
157
|
<body>
|
|
158
158
|
<h1>Authentication Successful!</h1>
|
|
@@ -160,9 +160,9 @@ ${K}`,metadata:{serverName:V,toolName:W.name,mcpResult:G}}}catch(G){return{succe
|
|
|
160
160
|
<script>window.close();</script>
|
|
161
161
|
</body>
|
|
162
162
|
</html>
|
|
163
|
-
`),
|
|
163
|
+
`),V.close(),b(Y)}catch(Z){V.close(),w(Z)}});V.on("error",w),V.listen(u0,()=>{console.log(`[OAuth] Callback server listening on port ${u0}`)}),setTimeout(()=>{V.close(),w(Error("OAuth callback timeout"))},300000)})}async exchangeCodeForToken($,b,w){let V=$.redirectUri||`http://localhost:${u0}${S1}`,W=new URLSearchParams({grant_type:"authorization_code",code:b,redirect_uri:V,code_verifier:w,client_id:$.clientId});if($.clientSecret)W.append("client_secret",$.clientSecret);let Q=await fetch($.tokenUrl,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:W.toString()});if(!Q.ok){let Z=await Q.text();throw Error(`Token exchange failed: ${Q.status} - ${Z}`)}return await Q.json()}async refreshAccessToken($,b){let w=new URLSearchParams({grant_type:"refresh_token",refresh_token:b,client_id:$.clientId});if($.clientSecret)w.append("client_secret",$.clientSecret);if($.scopes&&$.scopes.length>0)w.append("scope",$.scopes.join(" "));let V=await fetch($.tokenUrl,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:w.toString()});if(!V.ok){let W=await V.text();throw Error(`Token refresh failed: ${V.status} - ${W}`)}return await V.json()}async authenticate($,b){if(!b.clientId||!b.authorizationUrl||!b.tokenUrl)throw Error("Missing required OAuth configuration");let w=this.generatePKCEParams(),V=this.buildAuthorizationUrl(b,w);console.log(`
|
|
164
164
|
[OAuth] Opening browser for authentication...`),console.log(`
|
|
165
|
-
If the browser does not open automatically, copy and paste this URL:`),console.log(Q),console.log("");let Z=this.startCallbackServer(W.state);try{await this.openAuthorizationUrl(Q)}catch(G){console.warn("[OAuth] Failed to open browser automatically:",G)}let Y=await Z;console.log("[OAuth] Authorization code received, exchanging for tokens...");let J=await this.exchangeCodeForToken(V,Y,W.codeVerifier),X={accessToken:J.access_token,tokenType:J.token_type||"Bearer",refreshToken:J.refresh_token,scope:J.scope};if(J.expires_in)X.expiresAt=Date.now()+J.expires_in*1000;return await this.tokenStorage.saveToken($,X,V.clientId,V.tokenUrl),console.log("[OAuth] Authentication successful! Token saved."),X}async openAuthorizationUrl($){let{command:V,args:W}=this.getBrowserCommand($);await new Promise((Q,Z)=>{let Y=i7(V,W,{stdio:"ignore"});Y.once("error",Z),Y.once("close",(J)=>{if(J===0||J===null)Q();else Z(Error(`Failed to open browser (exit code ${J})`))})})}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($,V){let W=await this.tokenStorage.getCredentials($);if(!W)return null;let{token:Q}=W;if(!this.tokenStorage.isTokenExpired(Q))return Q.accessToken;if(Q.refreshToken&&V.clientId&&W.tokenUrl)try{console.log(`[OAuth] Refreshing expired token for server: ${$}`);let Z=await this.refreshAccessToken(V,Q.refreshToken),Y={accessToken:Z.access_token,tokenType:Z.token_type,refreshToken:Z.refresh_token||Q.refreshToken,scope:Z.scope||Q.scope};if(Z.expires_in)Y.expiresAt=Date.now()+Z.expires_in*1000;return await this.tokenStorage.saveToken($,Y,V.clientId,W.tokenUrl),Y.accessToken}catch(Z){console.error("[OAuth] Failed to refresh token:",Z),await this.tokenStorage.deleteCredentials($)}return null}}import{EventEmitter as l7}from"events";var d$;((Z)=>{Z.DISCONNECTED="disconnected";Z.CONNECTING="connecting";Z.CONNECTED="connected";Z.ERROR="error"})(d$||={});var o1;((Z)=>{Z.HEALTHY="healthy";Z.DEGRADED="degraded";Z.UNHEALTHY="unhealthy";Z.CHECKING="checking"})(o1||={});class N0 extends l7{client;config;checkTimer=null;isChecking=!1;consecutiveFailures=0;lastCheckTime=0;currentStatus="healthy";constructor($,V={}){super();this.client=$,this.config={interval:V.interval??30000,timeout:V.timeout??1e4,enabled:V.enabled??!1,failureThreshold:V.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 V={status:"healthy",timestamp:Date.now(),consecutiveFailures:0};return this.emit("healthCheck",V),V}else throw Error(`连接状态异常: ${$}`)}catch($){this.consecutiveFailures++;let V=$;console.warn(`[HealthMonitor] 健康检查失败(${this.consecutiveFailures}/${this.config.failureThreshold}):`,V.message);let W;if(this.consecutiveFailures>=this.config.failureThreshold)W="unhealthy",this.emit("unhealthy",this.consecutiveFailures,V),console.log("[HealthMonitor] 达到失败阈值,触发重连..."),this.triggerReconnection().catch((Z)=>{console.error("[HealthMonitor] 重连失败:",Z)});else W="degraded";this.setStatus(W);let Q={status:W,timestamp:Date.now(),consecutiveFailures:this.consecutiveFailures,lastError:V};return this.emit("healthCheck",Q),Q}finally{this.isChecking=!1}}async pingServer(){let $=new Promise((W,Q)=>{setTimeout(()=>Q(Error("Health check timeout")),this.config.timeout)}),V=(async()=>{if(this.client.availableTools.length===0){if(!this.client.server)throw Error("Server info not available")}})();await Promise.race([V,$])}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 V=this.currentStatus;this.currentStatus=$,this.emit("statusChanged",$,V)}}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")}}var t1;((J)=>{J.NETWORK_TEMPORARY="network_temporary";J.NETWORK_PERMANENT="network_permanent";J.CONFIG_ERROR="config_error";J.AUTH_ERROR="auth_error";J.PROTOCOL_ERROR="protocol_error";J.UNKNOWN="unknown"})(t1||={});function z4($){if(!($ instanceof Error))return{type:"unknown",isRetryable:!1,originalError:Error(String($))};let V=$.message.toLowerCase();if(["command not found","no such file","permission denied","invalid configuration","malformed","syntax error"].some((Z)=>V.includes(Z)))return{type:"config_error",isRetryable:!1,originalError:$};if(V.includes("unauthorized")||V.includes("401")||V.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((Z)=>V.includes(Z)))return{type:"network_temporary",isRetryable:!0,originalError:$};return{type:"unknown",isRetryable:!0,originalError:$}}class R0 extends a7{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($,V,W){super();this.config=$;if(this.serverName=V||"default",$.oauth?.enabled)this.oauthProvider=new s0;if(W?.enabled)this.healthMonitor=new N0(this,W),this.healthMonitor.on("unhealthy",(Q,Z)=>{this.emit("unhealthy",Q,Z)}),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,V=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 W=null;for(let Q=1;Q<=$;Q++)try{await this.doConnect(),this.reconnectAttempts=0;return}catch(Z){W=Z;let Y=z4(Z);if(!Y.isRetryable)throw console.error("[McpClient] 检测到永久性错误,放弃重试:",Y.type),Z;if(Q<$){let J=V*2**(Q-1);console.warn(`[McpClient] 连接失败(${Q}/${$}),${J}ms 后重试...`),await new Promise((X)=>setTimeout(X,J))}}throw W||Error("连接失败")}async doConnect(){try{this.setStatus("connecting"),this.sdkClient=new n7({name:L4(),version:j4()},{capabilities:{roots:{listChanged:!0},sampling:{}}}),this.sdkClient.onclose=()=>{this.handleUnexpectedClose()};let $=await this.createTransport();await this.sdkClient.connect($);let V=this.sdkClient.getServerVersion();if(this.serverInfo={name:V?.name||"Unknown",version:V?.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*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(V){if(console.error("[McpClient] 重连失败:",V),z4(V).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($,V={}){if(!this.sdkClient)throw Error("客户端未连接到服务器");if(!this.tools.has($))throw Error(`工具 "${$}" 不存在`);try{return await this.sdkClient.callTool({name:$,arguments:V})}catch(W){throw console.error(`[McpClient] 调用工具 "${$}" 失败:`,W),W}}async createTransport(){let{type:$,command:V,args:W,env:Q,url:Z,headers:Y,oauth:J}=this.config,X={...Y};if(J?.enabled&&this.oauthProvider&&($==="sse"||$==="http"))try{let G=await this.oauthProvider.getValidToken(this.serverName,J);if(!G){console.log(`[McpClient] 服务器 "${this.serverName}" 需要 OAuth 认证`);let B=await this.oauthProvider.authenticate(this.serverName,J);X.Authorization=`Bearer ${B.accessToken}`}else X.Authorization=`Bearer ${G}`}catch(G){throw console.error("[McpClient] OAuth 认证失败:",G),Error(`OAuth 认证失败: ${G instanceof Error?G.message:String(G)}`)}if($==="stdio"){if(!V)throw Error("stdio 传输需要 command 参数");let G={};for(let[B,K]of Object.entries(process.env))if(K!==void 0)G[B]=K;return new s7({command:V,args:W||[],env:{...G,...Q},stderr:"ignore"})}else if($==="sse"){if(!Z)throw Error("sse 传输需要 url 参数");return new r7(new URL(Z),{requestInit:{headers:X}})}else if($==="http"){if(!Z)throw Error("http 传输需要 url 参数");let{StreamableHTTPClientTransport:G}=await import("@modelcontextprotocol/sdk/client/streamableHttp.js");return new G(new URL(Z),{requestInit:{headers:X}})}throw Error(`不支持的传输类型: ${$}`)}async loadTools(){if(!this.sdkClient)return;try{let $=await this.sdkClient.listTools();if(this.tools.clear(),$.tools)for(let V of $.tools)this.tools.set(V.name,V);this.emit("toolsUpdated",this.availableTools)}catch($){throw console.error("[McpClient] 加载工具失败:",$),$}}setStatus($){let V=this.status;this.status=$,this.emit("statusChanged",$,V)}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($,V){if(!this.sdkClient)throw Error("客户端未连接");return(await this.sdkClient.readResource({uri:$})).contents?.[0]||{uri:$,text:""}}}class s extends o7{static instance=null;servers=new Map;isDiscovering=!1;constructor(){super()}static getInstance(){if(!s.instance)s.instance=new s;return s.instance}async registerServer($,V){if(this.servers.has($))throw Error(`MCP服务器 "${$}" 已经注册`);let W=new R0(V,$,V.healthCheck),Q={config:V,client:W,status:"disconnected",tools:[]};this.setupClientEventHandlers(W,Q,$),this.servers.set($,Q),this.emit("serverRegistered",$,Q);try{await this.connectServer($)}catch(Z){console.warn(`MCP服务器 "${$}" 连接失败:`,Z)}}async unregisterServer($){let V=this.servers.get($);if(!V)return;try{await V.client.disconnect()}catch(W){console.warn(`断开MCP服务器 "${$}" 时出错:`,W)}this.servers.delete($),this.emit("serverUnregistered",$)}async connectServer($){let V=this.servers.get($);if(!V)throw Error(`MCP服务器 "${$}" 未注册`);if(V.status==="connected")return;try{V.status="connecting",await V.client.connect(),V.connectedAt=new Date,V.lastError=void 0,V.tools=V.client.availableTools}catch(W){throw V.lastError=W,V.status="error",W}}async disconnectServer($){let V=this.servers.get($);if(!V)return;await V.client.disconnect(),V.connectedAt=void 0}async reconnectServer($){let V=this.servers.get($);if(!V)throw Error(`MCP服务器 "${$}" 未注册`);if(V.status==="connected")await V.client.disconnect();try{V.status="connecting",await V.client.connect(),V.connectedAt=new Date,V.lastError=void 0,V.tools=V.client.availableTools}catch(W){throw V.lastError=W,V.status="error",W}}async getAvailableTools(){let $=[],V=new Map;for(let[W,Q]of this.servers)if(Q.status==="connected")for(let Z of Q.tools){let Y=V.get(Z.name)||0;V.set(Z.name,Y+1)}for(let[W,Q]of this.servers)if(Q.status==="connected")for(let Z of Q.tools){let J=(V.get(Z.name)||0)>1?`${W}__${Z.name}`:Z.name,X=C0(Q.client,W,Z,J);$.push(X)}return $}async findTool($){for(let[V,W]of this.servers)if(W.status==="connected"){let Q=W.tools.find((Z)=>Z.name===$);if(Q)return C0(W.client,V,Q)}return null}getToolsByServer($){let V=this.servers.get($);if(!V||V.status!=="connected")return[];return V.tools.map((W)=>C0(V.client,$,W))}getServerStatus($){return this.servers.get($)||null}getAllServers(){return new Map(this.servers)}async refreshAllTools(){let $=[];for(let[V,W]of this.servers)if(W.status==="connected")$.push(this.refreshServerTools(V));await Promise.allSettled($)}async refreshServerTools($){let V=this.servers.get($);if(!V||V.status!=="connected")return;try{let W=V.client.availableTools,Q=V.tools.length;V.tools=W,this.emit("toolsUpdated",$,W,Q)}catch(W){console.warn(`刷新服务器 "${$}" 工具列表失败:`,W)}}setupClientEventHandlers($,V,W){$.on("connected",(Q)=>{V.status="connected",V.connectedAt=new Date,V.tools=$.availableTools,this.emit("serverConnected",W,Q)}),$.on("disconnected",()=>{V.status="disconnected",V.connectedAt=void 0,V.tools=[],this.emit("serverDisconnected",W)}),$.on("error",(Q)=>{V.status="error",V.lastError=Q,this.emit("serverError",W,Q)}),$.on("toolsUpdated",(Q)=>{let Z=V.tools.length;V.tools=Q,this.emit("toolsUpdated",W,Q,Z)}),$.on("statusChanged",(Q,Z)=>{V.status=Q,this.emit("serverStatusChanged",W,Q,Z)})}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 V=Object.entries($).map(([W,Q])=>this.registerServer(W,Q).catch((Z)=>{return console.warn(`注册MCP服务器 "${W}" 失败:`,Z),Z}));await Promise.allSettled(V)}getStatistics(){let $=0,V=0,W=0;for(let Q of this.servers.values())if(Q.status==="connected")$++,V+=Q.tools.length;else if(Q.status==="error")W++;return{totalServers:this.servers.size,connectedServers:$,errorServers:W,totalTools:V,isDiscovering:this.isDiscovering}}async disconnectAll(){let $=[];for(let[V,W]of this.servers)if(W.status==="connected")$.push(W.client.disconnect().catch((Q)=>{console.warn(`断开 MCP 服务器 "${V}" 时出错:`,Q)}));await Promise.allSettled($),this.servers.clear()}}import{promises as u4}from"fs";import O6 from"path";import*as $1 from"node:fs/promises";import{homedir as h4}from"node:os";import*as L$ from"node:path";var a0={name:"skill-creator",description:"Create new Skills interactively. Use when the user wants to create a new Skill, define a custom workflow, or add a specialized capability to Blade.",allowedTools:["Read","Write","Glob","Bash","AskUserQuestion"],version:"1.0.0",argumentHint:void 0,userInvocable:!0,disableModelInvocation:!1,model:void 0,whenToUse:"User wants to create a new skill, define a custom workflow, or add a specialized capability.",path:"builtin://skill-creator",basePath:"",source:"builtin"};function M4(){return{metadata:a0,instructions:`# Skill Creator
|
|
165
|
+
If the browser does not open automatically, copy and paste this URL:`),console.log(V),console.log("");let W=this.startCallbackServer(w.state);try{await this.openAuthorizationUrl(V)}catch(J){console.warn("[OAuth] Failed to open browser automatically:",J)}let Q=await W;console.log("[OAuth] Authorization code received, exchanging for tokens...");let Z=await this.exchangeCodeForToken(b,Q,w.codeVerifier),Y={accessToken:Z.access_token,tokenType:Z.token_type||"Bearer",refreshToken:Z.refresh_token,scope:Z.scope};if(Z.expires_in)Y.expiresAt=Date.now()+Z.expires_in*1000;return await this.tokenStorage.saveToken($,Y,b.clientId,b.tokenUrl),console.log("[OAuth] Authentication successful! Token saved."),Y}async openAuthorizationUrl($){let{command:b,args:w}=this.getBrowserCommand($);await new Promise((V,W)=>{let Q=I5(b,w,{stdio:"ignore"});Q.once("error",W),Q.once("close",(Z)=>{if(Z===0||Z===null)V();else W(Error(`Failed to open browser (exit code ${Z})`))})})}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($,b){let w=await this.tokenStorage.getCredentials($);if(!w)return null;let{token:V}=w;if(!this.tokenStorage.isTokenExpired(V))return V.accessToken;if(V.refreshToken&&b.clientId&&w.tokenUrl)try{console.log(`[OAuth] Refreshing expired token for server: ${$}`);let W=await this.refreshAccessToken(b,V.refreshToken),Q={accessToken:W.access_token,tokenType:W.token_type,refreshToken:W.refresh_token||V.refreshToken,scope:W.scope||V.scope};if(W.expires_in)Q.expiresAt=Date.now()+W.expires_in*1000;return await this.tokenStorage.saveToken($,Q,b.clientId,w.tokenUrl),Q.accessToken}catch(W){console.error("[OAuth] Failed to refresh token:",W),await this.tokenStorage.deleteCredentials($)}return null}}import{EventEmitter as P5}from"events";var b0;((W)=>{W.DISCONNECTED="disconnected";W.CONNECTING="connecting";W.CONNECTED="connected";W.ERROR="error"})(b0||={});var M1;((W)=>{W.HEALTHY="healthy";W.DEGRADED="degraded";W.UNHEALTHY="unhealthy";W.CHECKING="checking"})(M1||={});class m0 extends P5{client;config;checkTimer=null;isChecking=!1;consecutiveFailures=0;lastCheckTime=0;currentStatus="healthy";constructor($,b={}){super();this.client=$,this.config={interval:b.interval??30000,timeout:b.timeout??1e4,enabled:b.enabled??!1,failureThreshold:b.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 b={status:"healthy",timestamp:Date.now(),consecutiveFailures:0};return this.emit("healthCheck",b),b}else throw Error(`连接状态异常: ${$}`)}catch($){this.consecutiveFailures++;let b=$;console.warn(`[HealthMonitor] 健康检查失败(${this.consecutiveFailures}/${this.config.failureThreshold}):`,b.message);let w;if(this.consecutiveFailures>=this.config.failureThreshold)w="unhealthy",this.emit("unhealthy",this.consecutiveFailures,b),console.log("[HealthMonitor] 达到失败阈值,触发重连..."),this.triggerReconnection().catch((W)=>{console.error("[HealthMonitor] 重连失败:",W)});else w="degraded";this.setStatus(w);let V={status:w,timestamp:Date.now(),consecutiveFailures:this.consecutiveFailures,lastError:b};return this.emit("healthCheck",V),V}finally{this.isChecking=!1}}async pingServer(){let $=new Promise((w,V)=>{setTimeout(()=>V(Error("Health check timeout")),this.config.timeout)}),b=(async()=>{if(this.client.availableTools.length===0){if(!this.client.server)throw Error("Server info not available")}})();await Promise.race([b,$])}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 b=this.currentStatus;this.currentStatus=$,this.emit("statusChanged",$,b)}}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")}}var z1;((Z)=>{Z.NETWORK_TEMPORARY="network_temporary";Z.NETWORK_PERMANENT="network_permanent";Z.CONFIG_ERROR="config_error";Z.AUTH_ERROR="auth_error";Z.PROTOCOL_ERROR="protocol_error";Z.UNKNOWN="unknown"})(z1||={});function Z4($){if(!($ instanceof Error))return{type:"unknown",isRetryable:!1,originalError:Error(String($))};let b=$.message.toLowerCase();if(["command not found","no such file","permission denied","invalid configuration","malformed","syntax error"].some((W)=>b.includes(W)))return{type:"config_error",isRetryable:!1,originalError:$};if(b.includes("unauthorized")||b.includes("401")||b.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((W)=>b.includes(W)))return{type:"network_temporary",isRetryable:!0,originalError:$};return{type:"unknown",isRetryable:!0,originalError:$}}class c0 extends d5{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($,b,w){super();this.config=$;if(this.serverName=b||"default",$.oauth?.enabled)this.oauthProvider=new Ab;if(w?.enabled)this.healthMonitor=new m0(this,w),this.healthMonitor.on("unhealthy",(V,W)=>{this.emit("unhealthy",V,W)}),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,b=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 w=null;for(let V=1;V<=$;V++)try{await this.doConnect(),this.reconnectAttempts=0;return}catch(W){w=W;let Q=Z4(W);if(!Q.isRetryable)throw console.error("[McpClient] 检测到永久性错误,放弃重试:",Q.type),W;if(V<$){let Z=b*2**(V-1);console.warn(`[McpClient] 连接失败(${V}/${$}),${Z}ms 后重试...`),await new Promise((Y)=>setTimeout(Y,Z))}}throw w||Error("连接失败")}async doConnect(){try{this.setStatus("connecting"),this.sdkClient=new h5({name:w4(),version:b4()},{capabilities:{roots:{listChanged:!0},sampling:{}}}),this.sdkClient.onclose=()=>{this.handleUnexpectedClose()};let $=await this.createTransport();await this.sdkClient.connect($);let b=this.sdkClient.getServerVersion();if(this.serverInfo={name:b?.name||"Unknown",version:b?.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*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(b){if(console.error("[McpClient] 重连失败:",b),Z4(b).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($,b={}){if(!this.sdkClient)throw Error("客户端未连接到服务器");if(!this.tools.has($))throw Error(`工具 "${$}" 不存在`);try{return await this.sdkClient.callTool({name:$,arguments:b})}catch(w){throw console.error(`[McpClient] 调用工具 "${$}" 失败:`,w),w}}async createTransport(){let{type:$,command:b,args:w,env:V,url:W,headers:Q,oauth:Z}=this.config,Y={...Q};if(Z?.enabled&&this.oauthProvider&&($==="sse"||$==="http"))try{let J=await this.oauthProvider.getValidToken(this.serverName,Z);if(!J){console.log(`[McpClient] 服务器 "${this.serverName}" 需要 OAuth 认证`);let X=await this.oauthProvider.authenticate(this.serverName,Z);Y.Authorization=`Bearer ${X.accessToken}`}else Y.Authorization=`Bearer ${J}`}catch(J){throw console.error("[McpClient] OAuth 认证失败:",J),Error(`OAuth 认证失败: ${J instanceof Error?J.message:String(J)}`)}if($==="stdio"){if(!b)throw Error("stdio 传输需要 command 参数");let J={};for(let[X,O]of Object.entries(process.env))if(O!==void 0)J[X]=O;return new p5({command:b,args:w||[],env:{...J,...V},stderr:"ignore"})}else if($==="sse"){if(!W)throw Error("sse 传输需要 url 参数");return new x5(new URL(W),{requestInit:{headers:Y}})}else if($==="http"){if(!W)throw Error("http 传输需要 url 参数");let{StreamableHTTPClientTransport:J}=await import("@modelcontextprotocol/sdk/client/streamableHttp.js");return new J(new URL(W),{requestInit:{headers:Y}})}throw Error(`不支持的传输类型: ${$}`)}async loadTools(){if(!this.sdkClient)return;try{let $=await this.sdkClient.listTools();if(this.tools.clear(),$.tools)for(let b of $.tools)this.tools.set(b.name,b);this.emit("toolsUpdated",this.availableTools)}catch($){throw console.error("[McpClient] 加载工具失败:",$),$}}setStatus($){let b=this.status;this.status=$,this.emit("statusChanged",$,b)}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($,b){if(!this.sdkClient)throw Error("客户端未连接");return(await this.sdkClient.readResource({uri:$})).contents?.[0]||{uri:$,text:""}}}class c extends u5{static instance=null;servers=new Map;isDiscovering=!1;constructor(){super()}static getInstance(){if(!c.instance)c.instance=new c;return c.instance}async registerServer($,b){if(this.servers.has($))throw Error(`MCP服务器 "${$}" 已经注册`);let w=new c0(b,$,b.healthCheck),V={config:b,client:w,status:"disconnected",tools:[]};this.setupClientEventHandlers(w,V,$),this.servers.set($,V),this.emit("serverRegistered",$,V);try{await this.connectServer($)}catch(W){console.warn(`MCP服务器 "${$}" 连接失败:`,W)}}async unregisterServer($){let b=this.servers.get($);if(!b)return;try{await b.client.disconnect()}catch(w){console.warn(`断开MCP服务器 "${$}" 时出错:`,w)}this.servers.delete($),this.emit("serverUnregistered",$)}async connectServer($){let b=this.servers.get($);if(!b)throw Error(`MCP服务器 "${$}" 未注册`);if(b.status==="connected")return;try{b.status="connecting",await b.client.connect(),b.connectedAt=new Date,b.lastError=void 0,b.tools=b.client.availableTools}catch(w){throw b.lastError=w,b.status="error",w}}async disconnectServer($){let b=this.servers.get($);if(!b)return;await b.client.disconnect(),b.connectedAt=void 0}async reconnectServer($){let b=this.servers.get($);if(!b)throw Error(`MCP服务器 "${$}" 未注册`);if(b.status==="connected")await b.client.disconnect();try{b.status="connecting",await b.client.connect(),b.connectedAt=new Date,b.lastError=void 0,b.tools=b.client.availableTools}catch(w){throw b.lastError=w,b.status="error",w}}async getAvailableTools(){let $=[],b=new Map;for(let[w,V]of this.servers)if(V.status==="connected")for(let W of V.tools){let Q=b.get(W.name)||0;b.set(W.name,Q+1)}for(let[w,V]of this.servers)if(V.status==="connected")for(let W of V.tools){let Z=(b.get(W.name)||0)>1?`${w}__${W.name}`:W.name,Y=d0(V.client,w,W,Z);$.push(Y)}return $}async findTool($){for(let[b,w]of this.servers)if(w.status==="connected"){let V=w.tools.find((W)=>W.name===$);if(V)return d0(w.client,b,V)}return null}getToolsByServer($){let b=this.servers.get($);if(!b||b.status!=="connected")return[];return b.tools.map((w)=>d0(b.client,$,w))}getServerStatus($){return this.servers.get($)||null}getAllServers(){return new Map(this.servers)}async refreshAllTools(){let $=[];for(let[b,w]of this.servers)if(w.status==="connected")$.push(this.refreshServerTools(b));await Promise.allSettled($)}async refreshServerTools($){let b=this.servers.get($);if(!b||b.status!=="connected")return;try{let w=b.client.availableTools,V=b.tools.length;b.tools=w,this.emit("toolsUpdated",$,w,V)}catch(w){console.warn(`刷新服务器 "${$}" 工具列表失败:`,w)}}setupClientEventHandlers($,b,w){$.on("connected",(V)=>{b.status="connected",b.connectedAt=new Date,b.tools=$.availableTools,this.emit("serverConnected",w,V)}),$.on("disconnected",()=>{b.status="disconnected",b.connectedAt=void 0,b.tools=[],this.emit("serverDisconnected",w)}),$.on("error",(V)=>{b.status="error",b.lastError=V,this.emit("serverError",w,V)}),$.on("toolsUpdated",(V)=>{let W=b.tools.length;b.tools=V,this.emit("toolsUpdated",w,V,W)}),$.on("statusChanged",(V,W)=>{b.status=V,this.emit("serverStatusChanged",w,V,W)})}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 b=Object.entries($).map(([w,V])=>this.registerServer(w,V).catch((W)=>{return console.warn(`注册MCP服务器 "${w}" 失败:`,W),W}));await Promise.allSettled(b)}getStatistics(){let $=0,b=0,w=0;for(let V of this.servers.values())if(V.status==="connected")$++,b+=V.tools.length;else if(V.status==="error")w++;return{totalServers:this.servers.size,connectedServers:$,errorServers:w,totalTools:b,isDiscovering:this.isDiscovering}}async disconnectAll(){let $=[];for(let[b,w]of this.servers)if(w.status==="connected")$.push(w.client.disconnect().catch((V)=>{console.warn(`断开 MCP 服务器 "${b}" 时出错:`,V)}));await Promise.allSettled($),this.servers.clear()}}import{promises as H4}from"fs";import w7 from"path";import*as Eb from"node:fs/promises";import{homedir as C4}from"node:os";import*as v$ from"node:path";var Ub={name:"skill-creator",description:"Create new Skills interactively. Use when the user wants to create a new Skill, define a custom workflow, or add a specialized capability to Blade.",allowedTools:["Read","Write","Glob","Bash","AskUserQuestion"],version:"1.0.0",argumentHint:void 0,userInvocable:!0,disableModelInvocation:!1,model:void 0,whenToUse:"User wants to create a new skill, define a custom workflow, or add a specialized capability.",path:"builtin://skill-creator",basePath:"",source:"builtin"};function Y4(){return{metadata:Ub,instructions:`# Skill Creator
|
|
166
166
|
|
|
167
167
|
帮助用户创建新的 Blade Skills。
|
|
168
168
|
|
|
@@ -345,10 +345,10 @@ user-invocable: true
|
|
|
345
345
|
<footer>
|
|
346
346
|
\`\`\`
|
|
347
347
|
\`\`\`
|
|
348
|
-
`}}import{exec as
|
|
349
|
-
`)}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
|
|
350
|
-
${
|
|
351
|
-
</available_skills>`);if(
|
|
348
|
+
`}}import{exec as g5}from"node:child_process";import*as y from"node:fs/promises";import{homedir as m5}from"node:os";import*as n from"node:path";import{promisify as c5}from"node:util";var Fb=c5(g5),l=z("General"),y1={url:"https://github.com/anthropics/skills.git",branch:"main",defaultSkills:["skill-creator"]};class J4{skillsDir;constructor($){this.skillsDir=$||n.join(m5(),".blade","skills")}async isInstalled($){let b=n.join(this.skillsDir,$,"SKILL.md");try{return await y.access(b),!0}catch{return!1}}async isGitAvailable(){try{return await Fb("git --version"),!0}catch{return!1}}async installOfficialSkill($){let{url:b,branch:w}=y1,V=n.join(this.skillsDir,$),W=n.join(this.skillsDir,`.tmp-${$}-${Date.now()}`);try{if(!await this.isGitAvailable())return l.warn("Git not available, skipping skill installation"),!1;l.info(`Installing official skill: ${$}...`),await y.mkdir(this.skillsDir,{recursive:!0,mode:493}),await Fb(`git clone --depth 1 --branch ${w} --single-branch ${b} "${W}"`,{timeout:30000});let Q=n.join(W,"skills",$);try{await y.access(Q)}catch{return l.warn(`Skill ${$} not found in official repository`),await y.rm(W,{recursive:!0,force:!0}),!1}try{await y.rm(V,{recursive:!0,force:!0})}catch{}return await y.cp(Q,V,{recursive:!0}),await y.rm(W,{recursive:!0,force:!0}),l.info(`Successfully installed: ${$}`),!0}catch(Q){try{await y.rm(W,{recursive:!0,force:!0})}catch{}return l.warn(`Failed to install ${$}: ${Q instanceof Error?Q.message:"Unknown error"}`),!1}}async ensureDefaultSkillsInstalled(){await y.mkdir(this.skillsDir,{recursive:!0,mode:493});for(let $ of y1.defaultSkills)if(!await this.isInstalled($))await this.installOfficialSkill($)}async installFromRepo($,b){let w=b||this.extractRepoName($),V=n.join(this.skillsDir,w),W=n.join(this.skillsDir,`.tmp-repo-${w}-${Date.now()}`);try{if(!await this.isGitAvailable())return l.warn("Git not available, cannot install from repo"),!1;l.info(`Installing skill from repo: ${$}...`),await y.mkdir(this.skillsDir,{recursive:!0,mode:493}),await Fb(`git clone --depth 1 "${$}" "${W}"`,{timeout:60000});let Q=n.join(W,"SKILL.md");try{await y.access(Q)}catch{return l.warn(`No SKILL.md found in repository ${$}`),await y.rm(W,{recursive:!0,force:!0}),!1}await y.rm(V,{recursive:!0,force:!0}),await y.rename(W,V);try{await y.rm(n.join(V,".git"),{recursive:!0,force:!0})}catch{}return l.info(`Successfully installed skill from repo: ${w}`),!0}catch(Q){try{await y.rm(W,{recursive:!0,force:!0})}catch{}return l.warn(`Failed to install from repo ${$}: ${Q instanceof Error?Q.message:"Unknown error"}`),!1}}async installFromLocal($,b,w=!0){let V=b||n.basename($),W=n.join(this.skillsDir,V);try{let Q=n.resolve($);try{await y.access(Q)}catch{return l.warn(`Local path does not exist: ${Q}`),!1}let Z=n.join(Q,"SKILL.md");try{await y.access(Z)}catch{return l.warn(`No SKILL.md found in local path: ${Q}`),!1}if(l.info(`Installing skill from local path: ${Q}...`),await y.mkdir(this.skillsDir,{recursive:!0,mode:493}),await y.rm(W,{recursive:!0,force:!0}),w)await y.symlink(Q,W,"dir"),l.info(`Created symlink for skill: ${V}`);else await y.cp(Q,W,{recursive:!0}),l.info(`Copied skill to: ${V}`);return!0}catch(Q){return l.warn(`Failed to install from local path ${$}: ${Q instanceof Error?Q.message:"Unknown error"}`),!1}}extractRepoName($){return $.match(/\/([^/]+?)(\.git)?$/)?.[1]||"unknown-skill"}async installAllOfficialSkills(){let{url:$,branch:b}=y1,w=n.join(this.skillsDir,`.tmp-all-${Date.now()}`),V=[],W=[];try{if(!await this.isGitAvailable())return l.warn("Git not available, skipping skill installation"),{installed:V,failed:W};await y.mkdir(this.skillsDir,{recursive:!0,mode:493}),l.info("Cloning official skills repository..."),await Fb(`git clone --depth 1 --branch ${b} --single-branch ${$} "${w}"`,{timeout:60000});let Q=n.join(w,"skills"),Z=await y.readdir(Q,{withFileTypes:!0});for(let Y of Z){if(!Y.isDirectory())continue;let J=Y.name,X=n.join(Q,J),O=n.join(this.skillsDir,J);try{await y.access(n.join(X,"SKILL.md")),await y.rm(O,{recursive:!0,force:!0}),await y.cp(X,O,{recursive:!0}),l.info(`Installed: ${J}`),V.push(J)}catch(G){l.warn(`Failed to install ${J}`),W.push(J)}}await y.rm(w,{recursive:!0,force:!0})}catch(Q){try{await y.rm(w,{recursive:!0,force:!0})}catch{}l.warn(`Failed to install skills: ${Q instanceof Error?Q.message:"Unknown error"}`)}return{installed:V,failed:W}}}var v1=null;function X4($){if(!v1)v1=new J4($);return v1}import*as i0 from"node:fs/promises";import*as Hb from"node:path";import{parse as i5}from"yaml";var l5=/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/,n5=/^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]?$/,O4=1024;function s5($){if(!$)return;if(typeof $==="string")return $.split(",").map((b)=>b.trim()).filter(Boolean);if(Array.isArray($))return $.map((b)=>String(b).trim()).filter(Boolean);return}function G4($){if($===void 0)return;if(typeof $==="boolean")return $;if(typeof $==="string"){let b=$.toLowerCase().trim();if(b==="true"||b==="yes"||b==="1")return!0;if(b==="false"||b==="no"||b==="0")return!1}return}function r5($,b){if(!$.name)return{valid:!1,error:"Missing required field: name"};if(!n5.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>O4)return{valid:!1,error:`Description too long: ${$.description.length} characters (max ${O4})`};let w;if($.model)w=$.model==="inherit"?"inherit":$.model;return{valid:!0,metadata:{name:$.name,description:$.description.trim(),allowedTools:s5($["allowed-tools"]),version:$.version,argumentHint:$["argument-hint"]?.trim(),userInvocable:G4($["user-invocable"]),disableModelInvocation:G4($["disable-model-invocation"]),model:w,whenToUse:$.when_to_use?.trim()}}}function B4($,b,w){let V=$.match(l5);if(!V)return{success:!1,error:"Invalid SKILL.md format: missing YAML frontmatter (must start with ---)"};let[,W,Q]=V,Z;try{Z=i5(W)}catch(X){return{success:!1,error:`Failed to parse YAML frontmatter: ${X instanceof Error?X.message:String(X)}`}}let Y=r5(Z,b);if(!Y.valid)return{success:!1,error:Y.error};let J=Hb.dirname(b);return{success:!0,content:{metadata:{...Y.metadata,path:b,basePath:J,source:w},instructions:Q.trim()}}}async function _b($,b){try{let w=await i0.readFile($,"utf-8");return B4(w,$,b)}catch(w){if(w.code==="ENOENT")return{success:!1,error:`File not found: ${$}`};return{success:!1,error:`Failed to read file: ${w instanceof Error?w.message:String(w)}`}}}async function K4($){try{let b=await i0.readFile($.path,"utf-8"),w=B4(b,$.path,$.source);return w.success?w.content:null}catch{return null}}async function q4($){try{return await i0.access(Hb.join($,"SKILL.md")),!0}catch{return!1}}var a5={userSkillsDir:v$.join(C4(),".blade","skills"),projectSkillsDir:".blade/skills",claudeUserSkillsDir:v$.join(C4(),".claude","skills"),claudeProjectSkillsDir:".claude/skills",cwd:process.cwd()},Rb=null;class T1{skills=new Map;pluginSkills=new Map;config;initialized=!1;constructor($){this.config={...a5,...$}}static getInstance($){if(!Rb)Rb=new T1($);return Rb}static resetInstance(){Rb=null}async initialize(){if(this.initialized)return{skills:Array.from(this.skills.values()),errors:[]};let $=[],b=[];try{await X4(this.config.userSkillsDir).ensureDefaultSkillsInstalled()}catch(J){$.push({path:"SkillInstaller",error:`Failed to install default skills: ${J instanceof Error?J.message:"Unknown error"}`})}this.loadBuiltinSkills();let w=await this.scanDirectory(this.config.claudeUserSkillsDir,"user");b.push(...w.skills),$.push(...w.errors);let V=await this.scanDirectory(this.config.userSkillsDir,"user");b.push(...V.skills),$.push(...V.errors);let W=v$.isAbsolute(this.config.claudeProjectSkillsDir)?this.config.claudeProjectSkillsDir:v$.join(this.config.cwd,this.config.claudeProjectSkillsDir),Q=await this.scanDirectory(W,"project");b.push(...Q.skills),$.push(...Q.errors);let Z=v$.isAbsolute(this.config.projectSkillsDir)?this.config.projectSkillsDir:v$.join(this.config.cwd,this.config.projectSkillsDir),Y=await this.scanDirectory(Z,"project");b.push(...Y.skills),$.push(...Y.errors);for(let J of b)this.skills.set(J.name,J);return this.initialized=!0,{skills:Array.from(this.skills.values()),errors:$}}loadBuiltinSkills(){this.skills.set(Ub.name,Ub)}async scanDirectory($,b){let w=[],V=[];try{await Eb.access($)}catch{return{skills:w,errors:V}}try{let W=await Eb.readdir($,{withFileTypes:!0});for(let Q of W){if(!Q.isDirectory())continue;let Z=v$.join($,Q.name),Y=v$.join(Z,"SKILL.md");if(!await q4(Z))continue;let J=await _b(Y,b);if(J.success&&J.content)w.push(J.content.metadata);else V.push({path:Y,error:J.error||"Unknown error"})}}catch(W){V.push({path:$,error:`Failed to scan directory: ${W instanceof Error?W.message:String(W)}`})}return{skills:w,errors:V}}getAll(){return Array.from(this.skills.values())}get($){return this.skills.get($)}has($){return this.skills.has($)}async loadContent($){let b=this.skills.get($);if(!b)return null;if(b.source==="builtin")return this.loadBuiltinContent($);return K4(b)}loadBuiltinContent($){switch($){case"skill-creator":return Y4();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 b=[];for(let w of $){let V=w.description.length>100?`${w.description.substring(0,97)}...`:w.description,W=w.argumentHint?`${w.name} ${w.argumentHint}`:w.name;b.push(`- ${W}: ${V}`)}return b.join(`
|
|
349
|
+
`)}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 b=this.pluginSkills.get($);if(b)return b;let w=[];for(let V of this.pluginSkills.values())if(V.originalName===$)w.push(V);if(w.length===1)return w[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 N$($){return T1.getInstance($)}async function Lb($){return N$($).initialize()}var o5="Skill",t5=/<available_skills>\s*<\/available_skills>/;function Db($){let w=N$().generateAvailableSkillsList();if(!w)return $;return $.map((V)=>{if(V.name!==o5)return V;let W=V.description.replace(t5,`<available_skills>
|
|
350
|
+
${w}
|
|
351
|
+
</available_skills>`);if(W===V.description)return V;return{...V,description:W}})}import{execSync as e5}from"child_process";import*as _0 from"os";import*as H0 from"path";function $7(){let $=process.cwd(),b=b7($);return{workingDirectory:$,projectRoot:b,platform:`${_0.platform()} (${_0.arch()})`,nodeVersion:process.version,currentDate:new Date().toISOString().split("T")[0],homeDirectory:_0.homedir()}}function l0(){let $=$7();return`# Environment Context
|
|
352
352
|
|
|
353
353
|
## Working Directory
|
|
354
354
|
**Current**: \`${$.workingDirectory}\`
|
|
@@ -366,7 +366,7 @@ When using file tools (read, write, edit), provide **absolute paths**:
|
|
|
366
366
|
- ❌ Incorrect: \`/package.json\` (root directory)
|
|
367
367
|
- ❌ Incorrect: \`package.json\` (relative path without context)
|
|
368
368
|
|
|
369
|
-
**Always use** \`${$.workingDirectory}/\` as the base for file paths.`}function
|
|
369
|
+
**Always use** \`${$.workingDirectory}/\` as the base for file paths.`}function b7($){let b=$;while(b!==H0.dirname(b)){if(A4(H0.join(b,".git")))return b;if(A4(H0.join(b,"package.json")))return b;b=H0.dirname(b)}return $}function A4($){try{return e5(`test -e "${$}"`,{stdio:"ignore"}),!0}catch{return!1}}var U4=`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.
|
|
370
370
|
|
|
371
371
|
IMPORTANT: Assist with authorized security testing, defensive security, CTF challenges, and educational contexts. Refuse requests for destructive techniques, DoS attacks, mass targeting, supply chain compromise, or detection evasion for malicious purposes. Dual-use security tools (C2 frameworks, credential testing, exploit development) require clear authorization context: pentesting engagements, CTF competitions, security research, or defensive use cases.
|
|
372
372
|
IMPORTANT: You must NEVER generate or guess URLs for the user unless you are confident that the URLs are for helping the user with programming. You may use URLs provided by the user in their messages or local files.
|
|
@@ -524,7 +524,7 @@ assistant: Clients are marked as failed in the \`connectToServer\` function in s
|
|
|
524
524
|
</example>
|
|
525
525
|
|
|
526
526
|
# Language Requirement
|
|
527
|
-
{{LANGUAGE_INSTRUCTION}}`,
|
|
527
|
+
{{LANGUAGE_INSTRUCTION}}`,F4=`You are in **PLAN MODE** - a read-only research phase for designing implementation plans.
|
|
528
528
|
|
|
529
529
|
## Core Objective
|
|
530
530
|
|
|
@@ -564,71 +564,71 @@ Your plan should include:
|
|
|
564
564
|
3. **Steps** - Detailed implementation steps with file paths
|
|
565
565
|
4. **Testing** - How to verify changes
|
|
566
566
|
5. **Risks** - Potential issues and mitigations
|
|
567
|
-
`;function
|
|
567
|
+
`;function n$($){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>
|
|
568
568
|
|
|
569
|
-
`+$}var
|
|
569
|
+
`+$}var V7=/<available_skills>\s*<\/available_skills>/;async function R0($={}){let{projectPath:b,replaceDefault:w,append:V,mode:W,includeEnvironment:Q=!0,language:Z}=$,Y=[],J=[];if(Q){let q=l0();if(q)Y.push(q),J.push({name:"environment",loaded:!0,length:q.length})}let X=W===v.PLAN,O,G;if(X)O=F4,G="plan_mode_prompt";else O=w??U4,G=w?"replace_default":"default";if(Y.push(O),J.push({name:G,loaded:!0,length:O.length}),b){let q=await Y7(b);if(q)Y.push(q),J.push({name:"blade_md",loaded:!0,length:q.length});else J.push({name:"blade_md",loaded:!1})}if(V?.trim())Y.push(V.trim()),J.push({name:"append",loaded:!0,length:V.trim().length});let B=Y.join(`
|
|
570
570
|
|
|
571
571
|
---
|
|
572
572
|
|
|
573
|
-
`);return
|
|
574
|
-
${
|
|
575
|
-
</available_skills>`)}var
|
|
576
|
-
`),
|
|
573
|
+
`);return B=W7(B),B=Z7(B,Z),{prompt:B,sources:J}}function W7($){let w=N$().generateAvailableSkillsList();if(!w)return $;return $.replace(V7,`<available_skills>
|
|
574
|
+
${w}
|
|
575
|
+
</available_skills>`)}var Q7={"zh-CN":"Chinese (Simplified Chinese)","zh-TW":"Chinese (Traditional Chinese)","en-US":"English","en-GB":"English (British)","ja-JP":"Japanese","ko-KR":"Korean","es-ES":"Spanish","fr-FR":"French","de-DE":"German","pt-BR":"Portuguese (Brazilian)","ru-RU":"Russian"};function Z7($,b){let w=b||"zh-CN",V=Q7[w]||w,W=`IMPORTANT: Always respond in ${V}. All your responses must be in ${V}.`;return $.replace("{{LANGUAGE_INSTRUCTION}}",W)}async function Y7($){let b=w7.join($,"BLADE.md");try{return(await H4.readFile(b,"utf-8")).trim()||null}catch{return null}}import*as S2 from"os";import*as M2 from"path";import{basename as A7,extname as U7}from"path";import{z as Nb}from"zod";function s$(){return!1}function _4(){throw Error("ACP mode is not available")}import{existsSync as k1,readFileSync as J7,unlinkSync as X7,writeFileSync as O7}from"fs";import{dirname as G7}from"path";import{mkdirSync as B7}from"fs";var T$=z("Tool");class p${static instance=null;config={enabled:!1};checkpoints=new Map;checkpointOrder=[];currentFileSnapshots=new Map;pendingChanges=[];constructor(){}static getInstance(){if(!p$.instance)p$.instance=new p$;return p$.instance}static resetInstance(){p$.instance=null}configure($){if(this.config={...this.config,...$},!this.config.enabled)this.clear();T$.debug(`[CheckpointService] Configured: enabled=${this.config.enabled}`)}isEnabled(){return this.config.enabled}clear(){this.checkpoints.clear(),this.checkpointOrder=[],this.currentFileSnapshots.clear(),this.pendingChanges=[],T$.debug("[CheckpointService] Cleared all checkpoints")}shouldExclude($){if(!this.config.excludePatterns||this.config.excludePatterns.length===0)return!1;return this.config.excludePatterns.some((b)=>{if(b.includes("*"))return new RegExp("^"+b.replace(/\*/g,".*")+"$").test($);return $.includes(b)})}captureSnapshot($){let b=k1($),w=null;if(b)try{w=J7($,"utf-8")}catch{w=null}return{filePath:$,content:w,exists:b,timestamp:new Date}}trackFileChange($,b){if(!this.config.enabled)return;if(this.shouldExclude($)){T$.debug(`[CheckpointService] Excluded file: ${$}`);return}let w=this.currentFileSnapshots.get($)||null,V=this.captureSnapshot($),W={filePath:$,operation:b,beforeSnapshot:w,afterSnapshot:V,timestamp:new Date};this.pendingChanges.push(W),this.currentFileSnapshots.set($,V),T$.debug(`[CheckpointService] Tracked ${b}: ${$}`)}captureBeforeWrite($){if(!this.config.enabled)return;if(this.shouldExclude($))return;if(!this.currentFileSnapshots.has($)){let b=this.captureSnapshot($);this.currentFileSnapshots.set($,b),T$.debug(`[CheckpointService] Captured before-write snapshot: ${$}`)}}createCheckpoint($,b){if(!this.config.enabled)return;let w={messageUuid:$,messageRole:b,timestamp:new Date,fileChanges:[...this.pendingChanges],fileSnapshots:new Map(this.currentFileSnapshots)};if(this.checkpoints.set($,w),this.checkpointOrder.push($),this.pendingChanges=[],this.config.maxCheckpoints&&this.checkpointOrder.length>this.config.maxCheckpoints){let V=this.checkpointOrder.shift();if(V)this.checkpoints.delete(V)}T$.debug(`[CheckpointService] Created checkpoint: ${$} (${b})`)}getCheckpoint($){return this.checkpoints.get($)}getAllCheckpoints(){return this.checkpointOrder.map(($)=>this.checkpoints.get($)).filter(Boolean)}async rewindFiles($){if(!this.config.enabled)return{success:!1,restoredFiles:[],deletedFiles:[],errors:[{filePath:"",error:"File checkpointing is not enabled"}]};let b=this.checkpoints.get($);if(!b)return{success:!1,restoredFiles:[],deletedFiles:[],errors:[{filePath:"",error:`Checkpoint not found: ${$}`}]};let w=[],V=[],W=[],Q=this.checkpointOrder.indexOf($),Z=this.checkpointOrder.slice(Q+1),Y=new Map;for(let J=Z.length-1;J>=0;J--){let X=Z[J],O=this.checkpoints.get(X);if(!O)continue;for(let G of O.fileChanges)if(!Y.has(G.filePath)&&G.beforeSnapshot)Y.set(G.filePath,G.beforeSnapshot)}for(let[J,X]of b.fileSnapshots)if(!Y.has(J))Y.set(J,X);for(let[J,X]of Y)try{if(X.exists&&X.content!==null){let O=G7(J);if(!k1(O))B7(O,{recursive:!0});O7(J,X.content,"utf-8"),w.push(J),T$.debug(`[CheckpointService] Restored: ${J}`)}else if(!X.exists&&k1(J))X7(J),V.push(J),T$.debug(`[CheckpointService] Deleted: ${J}`)}catch(O){let G=O instanceof Error?O.message:String(O);W.push({filePath:J,error:G}),T$.error(`[CheckpointService] Failed to restore ${J}: ${G}`)}for(let J of Z)this.checkpoints.delete(J);return this.checkpointOrder=this.checkpointOrder.slice(0,Q+1),this.currentFileSnapshots=new Map(b.fileSnapshots),this.pendingChanges=[],T$.info(`[CheckpointService] Rewound to ${$}: restored=${w.length}, deleted=${V.length}, errors=${W.length}`),{success:W.length===0,restoredFiles:w,deletedFiles:V,errors:W}}getChangedFilesSince($){let b=this.checkpointOrder.indexOf($);if(b===-1)return[];let w=new Set,V=this.checkpointOrder.slice(b+1);for(let W of V){let Q=this.checkpoints.get(W);if(!Q)continue;for(let Z of Q.fileChanges)w.add(Z.filePath)}return Array.from(w)}getStatistics(){return{checkpointCount:this.checkpoints.size,trackedFileCount:this.currentFileSnapshots.size,pendingChangeCount:this.pendingChanges.length}}}function k$(){return p$.getInstance()}import*as S$ from"fs/promises";class R4{async readTextFile($){return S$.readFile($,"utf-8")}async writeTextFile($,b){await S$.writeFile($,b,"utf-8")}async exists($){try{return await S$.access($),!0}catch{return!1}}async readBinaryFile($){return S$.readFile($)}async stat($){try{let b=await S$.stat($);return{size:b.size,isDirectory:b.isDirectory(),isFile:b.isFile(),mtime:b.mtime}}catch{return null}}async mkdir($,b){await S$.mkdir($,{recursive:b?.recursive??!1,mode:b?.mode??493})}}var K7=new R4;function E0(){return K7}import{isAbsolute as E4}from"path";import{z as o}from"zod";var g={filePath:($)=>o.string().min(1,"File path is required").refine((b)=>E4(b),{message:"Path must be absolute"}).describe($?.description||"Absolute file path"),encoding:()=>o.enum(["utf8","base64","binary"]).default("utf8").describe("File encoding"),timeout:($=1000,b=300000,w=30000)=>o.number().int("Must be an integer").min($,`Cannot be less than ${$}ms`).max(b,`Cannot exceed ${b}ms`).default(w).describe(`Timeout in milliseconds (default ${w}ms)`),pattern:($)=>o.string().min(1,"Pattern is required").describe($?.description||"Regex or glob pattern"),glob:($)=>o.string().min(1,"Glob pattern is required").describe($?.description||'Glob pattern (e.g., "*.js", "**/*.ts")'),lineNumber:($)=>o.number().int("Line number must be an integer").min($?.min??0,`Line number cannot be less than ${$?.min??0}`).describe($?.description||"Line number"),lineLimit:($)=>o.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:()=>o.string().min(1,"Working directory is required").refine(($)=>E4($),{message:"Path must be absolute"}).describe("Absolute working directory"),environment:()=>o.record(o.string(),o.string()).describe("Environment variables (key-value)").optional(),outputMode:($,b)=>{let w=o.enum($);return b?w.default(b):w},flag:($)=>o.boolean().default($?.defaultValue??!1).describe($?.description||"Boolean flag"),url:($)=>o.string().url("Must be a valid URL").describe($?.description||"URL"),port:()=>o.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:($)=>o.string().min(1,"Command is required").describe($?.description||"Command to execute"),sessionId:()=>o.string().min(1,"Session ID is required").uuid("Must be a valid UUID").optional().describe("Session identifier (UUID)"),nonNegativeInt:($)=>o.number().int("Must be an integer").min(0,"Cannot be negative").describe($?.description||"Non-negative integer"),positiveInt:($)=>o.number().int("Must be an integer").min(1,"Must be greater than 0").describe($?.description||"Positive integer")};import*as f1 from"diff";function L4($,b,w=4){if($===b)return null;let V=f1.createPatch("file",$,b,"","",{context:w}),W=V.split(`
|
|
576
|
+
`),Q=1;for(let Z of W){let Y=Z.match(/@@ -(\d+),?(\d*) \+(\d+),?(\d*) @@/);if(Y){Q=parseInt(Y[1],10);break}}return`
|
|
577
577
|
<<<DIFF>>>
|
|
578
|
-
${JSON.stringify({patch:
|
|
578
|
+
${JSON.stringify({patch:V,startLine:Math.max(1,Q-w),matchLine:Q})}
|
|
579
579
|
<<</DIFF>>>
|
|
580
|
-
`}function
|
|
581
|
-
`).length-1,
|
|
582
|
-
`),
|
|
583
|
-
`),
|
|
584
|
-
`),
|
|
585
|
-
`),
|
|
586
|
-
`),
|
|
587
|
-
`),F=
|
|
580
|
+
`}function D4($,b,w,V,W=4){let Q=$.indexOf(w);if(Q===-1)return null;let Y=$.substring(0,Q).split(`
|
|
581
|
+
`).length-1,J=$.split(`
|
|
582
|
+
`),X=b.split(`
|
|
583
|
+
`),O=w.split(`
|
|
584
|
+
`),G=V.split(`
|
|
585
|
+
`),B=Math.max(0,Y-W),q=Math.min(J.length,Y+O.length+W),A=Math.min(X.length,Y+G.length+W),K=J.slice(B,q).join(`
|
|
586
|
+
`),U=X.slice(B,A).join(`
|
|
587
|
+
`),F=f1.createPatch("file",K,U,"","",{context:W});return`
|
|
588
588
|
<<<DIFF>>>
|
|
589
|
-
${JSON.stringify({patch:F,startLine:
|
|
589
|
+
${JSON.stringify({patch:F,startLine:B+1,matchLine:Y+1})}
|
|
590
590
|
<<</DIFF>>>
|
|
591
|
-
`}function
|
|
591
|
+
`}function j4($){return $.replace(/\\+(n|t|r|'|"|`|\\|\n)/g,(b,w)=>{switch(w){case"n":return`
|
|
592
592
|
`;case"t":return"\t";case"r":return"\r";case"'":return"'";case'"':return'"';case"`":return"`";case"\\":return"\\";case`
|
|
593
593
|
`:return`
|
|
594
|
-
`;default:return
|
|
595
|
-
`);if(
|
|
596
|
-
`),
|
|
597
|
-
`);for(let
|
|
598
|
-
`)===
|
|
599
|
-
`)}return null}import{promises as
|
|
600
|
-
|
|
601
|
-
Details: ${
|
|
602
|
-
|
|
603
|
-
${
|
|
604
|
-
|
|
605
|
-
\uD83D\uDCA1 我需要重新读取文件内容后再编辑`,error:{type:"validation_error",message:"File modified externally",details:{externalModification:
|
|
606
|
-
`),
|
|
607
|
-
`),
|
|
608
|
-
`);return{success:!1,llmContent:R,displayContent:
|
|
609
|
-
\uD83D\uDCDD 替换了 ${
|
|
610
|
-
\uD83D\uDCCA 文件大小${
|
|
611
|
-
`),
|
|
612
|
-
`),
|
|
613
|
-
|
|
614
|
-
File: ${
|
|
615
|
-
Total lines: ${
|
|
616
|
-
|
|
617
|
-
`,
|
|
618
|
-
... (truncated)`:
|
|
619
|
-
${
|
|
620
|
-
|
|
621
|
-
`,
|
|
622
|
-
${
|
|
623
|
-
|
|
624
|
-
`;else
|
|
625
|
-
${
|
|
626
|
-
|
|
627
|
-
`;if(
|
|
628
|
-
`,
|
|
629
|
-
${
|
|
630
|
-
`}),
|
|
631
|
-
`;
|
|
594
|
+
`;default:return b}})}function N4($,b){let w=b.split(`
|
|
595
|
+
`);if(w.length===1)return null;let W=w[0].match(/^(\s+)/);if(!W)return null;let Q=W[1],Y=w.map((X)=>{if(X.startsWith(Q))return X.slice(Q.length);return X}).join(`
|
|
596
|
+
`),J=$.split(`
|
|
597
|
+
`);for(let X=0;X<=J.length-w.length;X++){let O=J[X].match(/^(\s+)/),G=O?O[1]:"",B=J.slice(X,X+w.length);if(B.map((K)=>{if(K.startsWith(G))return K.slice(G.length);return K}).join(`
|
|
598
|
+
`)===Y)return B.join(`
|
|
599
|
+
`)}return null}import{promises as jb}from"node:fs";var n0=z("Tool");class Y${static instance=null;accessedFiles=new Map;constructor(){}static getInstance(){if(!Y$.instance)Y$.instance=new Y$;return Y$.instance}async recordFileRead($,b){try{let w=await jb.stat($),V={filePath:$,accessTime:Date.now(),mtime:w.mtimeMs,sessionId:b,lastOperation:"read"};this.accessedFiles.set($,V),n0.debug(`记录文件读取: ${$}`)}catch(w){n0.warn(`记录文件读取失败: ${$}`,w)}}async recordFileEdit($,b,w="edit"){try{let V=await jb.stat($),W={filePath:$,accessTime:Date.now(),mtime:V.mtimeMs,sessionId:b,lastOperation:w};this.accessedFiles.set($,W),n0.debug(`记录文件${w==="edit"?"编辑":"写入"}: ${$}`)}catch(V){n0.warn(`记录文件${w==="edit"?"编辑":"写入"}失败: ${$}`,V)}}hasFileBeenRead($,b){let w=this.accessedFiles.get($);if(!w)return!1;if(b&&w.sessionId!==b)return!1;return!0}async checkFileModification($){let b=this.accessedFiles.get($);if(!b)return{modified:!1,message:"文件未被跟踪"};try{let w=await jb.stat($);if(Math.abs(w.mtimeMs-b.mtime)>1)return{modified:!0,message:`文件在访问后被修改(访问时间: ${new Date(b.accessTime).toISOString()}, 当前修改时间: ${w.mtime.toISOString()})`};return{modified:!1}}catch(w){let V=w;if(V.code==="ENOENT")return{modified:!0,message:"文件已被删除"};return{modified:!1,message:`无法检查文件状态: ${V.message}`}}}async checkExternalModification($){let b=this.accessedFiles.get($);if(!b)return{isExternal:!1,message:"文件未被跟踪"};try{let w=await jb.stat($);if(w.mtimeMs-b.mtime>2000)return{isExternal:!0,message:`文件在 ${new Date(b.accessTime).toISOString()} (${b.lastOperation}) 之后被外部程序修改(当前修改时间: ${w.mtime.toISOString()})`};return{isExternal:!1}}catch(w){let V=w;if(V.code==="ENOENT")return{isExternal:!0,message:"文件已被删除"};return n0.warn(`检查文件外部修改失败: ${$}`,w),{isExternal:!1,message:`无法检查文件状态: ${V.message}`}}}getFileRecord($){return this.accessedFiles.get($)}clearFileRecord($){this.accessedFiles.delete($)}clearAll(){this.accessedFiles.clear()}clearSession($){for(let[b,w]of this.accessedFiles.entries())if(w.sessionId===$)this.accessedFiles.delete(b)}getTrackedFiles(){return Array.from(this.accessedFiles.keys())}getTrackedFileCount(){return this.accessedFiles.size}static resetInstance(){Y$.instance=null}}import*as z4 from"node:crypto";import{promises as f$}from"node:fs";import*as V0 from"node:path";import{execSync as q7}from"node:child_process";import*as I1 from"node:os";import*as w0 from"node:path";function C7($){return w0.resolve($).replace(/[/\\]/g,"-").replace(/:/g,"_")}function s0($){let b=I1.homedir(),w=C7($);return w0.join(b,".blade","projects",w)}function C$($,b){return w0.join(s0($),`${b}.jsonl`)}function S4($){try{return q7("git rev-parse --abbrev-ref HEAD",{cwd:$,encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim()||void 0}catch{return}}function r0(){return w0.join(I1.homedir(),".blade")}async function M4(){let{readdir:$}=await import("node:fs/promises");try{let b=w0.join(r0(),"projects");return(await $(b,{withFileTypes:!0})).filter((V)=>V.isDirectory()).map((V)=>V.name)}catch{return[]}}class a0{sessionId;enableCheckpoints;maxSnapshots;snapshotDir;trackedFileBackups=new Map;snapshots=[];constructor($){this.sessionId=$.sessionId,this.enableCheckpoints=$.enableCheckpoints??!0,this.maxSnapshots=$.maxSnapshots??10;let b=r0();this.snapshotDir=V0.join(b,"file-history",this.sessionId)}async initialize(){if(!this.enableCheckpoints)return;try{await f$.mkdir(this.snapshotDir,{recursive:!0,mode:493}),console.log(`[SnapshotManager] 初始化快照目录: ${this.snapshotDir}`)}catch($){throw console.warn("[SnapshotManager] 创建快照目录失败:",$),$}}async createSnapshot($,b){if(!this.enableCheckpoints)return console.log("[SnapshotManager] 检查点已禁用,跳过快照创建"),{backupFileName:"",version:0,backupTime:new Date};try{await f$.access($)}catch{return console.warn(`[SnapshotManager] 文件不存在,跳过快照: ${$}`),{backupFileName:"",version:0,backupTime:new Date}}let w=this.trackedFileBackups.get($),V=w?w.version+1:1,W=this.generateFileHash($,V),Q=V0.join(this.snapshotDir,`${W}@v${V}`);try{let Z=await f$.readFile($,{encoding:"utf-8"});await f$.writeFile(Q,Z,{encoding:"utf-8"});let Y={backupFileName:W,version:V,backupTime:new Date};return this.trackedFileBackups.set($,Y),this.snapshots.push({messageId:b,backupFileName:W,timestamp:new Date,filePath:$}),console.log(`[SnapshotManager] 创建快照: ${$} -> ${W}@v${V}`),await this.cleanupOldSnapshots($),Y}catch(Z){throw console.error(`[SnapshotManager] 创建快照失败: ${$}`,Z),Z}}async restoreSnapshot($,b){let w=this.snapshots.slice().reverse().find((Q)=>Q.messageId===b&&Q.filePath===$);if(!w)throw Error(`未找到快照: messageId=${b}, filePath=${$}`);let V=this.trackedFileBackups.get($);if(!V)throw Error(`未找到文件追踪信息: ${$}`);let W=V0.join(this.snapshotDir,`${w.backupFileName}@v${V.version}`);try{let Q=await f$.readFile(W,{encoding:"utf-8"});await f$.writeFile($,Q,{encoding:"utf-8"}),console.log(`[SnapshotManager] 恢复快照: ${$} <- ${w.backupFileName}@v${V.version}`)}catch(Q){throw console.error(`[SnapshotManager] 恢复快照失败: ${$}`,Q),Q}}async listSnapshots($){return this.snapshots.filter((b)=>b.filePath===$)}async cleanupOldSnapshots($){let b=this.snapshots.filter((W)=>W.filePath===$);if(b.length<=this.maxSnapshots)return;let V=b.sort((W,Q)=>W.timestamp.getTime()-Q.timestamp.getTime()).slice(0,b.length-this.maxSnapshots);for(let W of V){let Q=this.trackedFileBackups.get(W.filePath);if(!Q)continue;let Z=V0.join(this.snapshotDir,`${W.backupFileName}@v${Q.version}`);try{await f$.unlink(Z),console.log(`[SnapshotManager] 删除旧快照: ${Z}`)}catch(J){console.warn(`[SnapshotManager] 删除快照失败: ${Z}`,J)}let Y=this.snapshots.indexOf(W);if(Y>-1)this.snapshots.splice(Y,1)}}async cleanup($=0){try{let b=await f$.readdir(this.snapshotDir);if(b.length<=$)return;let w=await Promise.all(b.map(async(W)=>{let Q=V0.join(this.snapshotDir,W),Z=await f$.stat(Q);return{file:W,mtime:Z.mtime.getTime()}}));w.sort((W,Q)=>Q.mtime-W.mtime);let V=w.slice($);for(let{file:W}of V){let Q=V0.join(this.snapshotDir,W);await f$.unlink(Q),console.log(`[SnapshotManager] 清理快照: ${Q}`)}}catch(b){console.warn("[SnapshotManager] 清理快照失败:",b)}}generateFileHash($,b){let w=z4.createHash("md5");return w.update(`${$}:${b}`),w.digest("hex").substring(0,16)}getSnapshotDir(){return this.snapshotDir}getSessionId(){return this.sessionId}getTrackedFileCount(){return this.trackedFileBackups.size}getSnapshotCount(){return this.snapshots.length}}var P1=E({name:"Edit",displayName:"File Edit",kind:"write",strict:!0,isConcurrencySafe:!1,schema:Nb.object({file_path:g.filePath({description:"Absolute path of the file to edit"}),old_string:Nb.string().min(1,"old_string cannot be empty").describe("String to replace"),new_string:Nb.string().describe("Replacement string (can be empty)"),replace_all:Nb.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($,b){let{file_path:w,old_string:V,new_string:W,replace_all:Q}=$,{updateOutput:Z,sessionId:Y,messageId:J}=b,X=b.signal??new AbortController().signal;try{Z?.("Starting to read file...");let O=E0(),G=s$(),B;try{if(G)Z?.("通过 IDE 读取文件...");B=await O.readTextFile(w)}catch(P){let w$=P;if(w$.code==="ENOENT"||w$.message?.includes("not found"))return{success:!1,llmContent:`File not found: ${w}`,displayContent:`❌ 文件不存在: ${w}`,error:{type:"execution_error",message:"文件不存在"}};throw P}if(typeof X.throwIfAborted==="function")X.throwIfAborted();if(Y){let P=Y$.getInstance();if(!P.hasFileBeenRead(w,Y))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:"\uD83D\uDCD6 我需要先读取文件内容,然后再进行编辑。",error:{type:"validation_error",message:"File not read before edit"},metadata:{requiresRead:!0}};let w$=await P.checkExternalModification(w);if(w$.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.
|
|
600
|
+
|
|
601
|
+
Details: ${w$.message}`,displayContent:`❌ 编辑失败:文件已被外部程序修改
|
|
602
|
+
|
|
603
|
+
${w$.message}
|
|
604
|
+
|
|
605
|
+
\uD83D\uDCA1 我需要重新读取文件内容后再编辑`,error:{type:"validation_error",message:"File modified externally",details:{externalModification:w$.message}}}}if(Y&&J)try{let P=new a0({sessionId:Y});await P.initialize(),await P.createSnapshot(w,J)}catch(P){console.warn("[EditTool] 创建快照失败:",P)}if(V===W)return{success:!1,llmContent:"New string is identical; no replacement needed",displayContent:"⚠️ 新字符串与旧字符串相同,无需进行替换",error:{type:"validation_error",message:"新旧字符串相同"}};let q=F7(B,V);if(!q.matched){let P=R7(B,V,w);return{success:!1,llmContent:P.llmContent,displayContent:P.displayContent,error:{type:"execution_error",message:"未找到匹配内容",details:P.metadata}}}let A=q.matched;if(q.strategy!=="exact")console.log(`[SmartEdit] 使用策略: ${q.strategy}`);let K=H7(B,A);if(K.length>1&&!Q){let P=B.split(`
|
|
606
|
+
`),w$=0,L=[];for(let h=0;h<P.length;h++){let k=P[h],x=w$,m=w$+k.length;for(let e of K)if(e>=x&&e<m){let $1=Math.max(0,h-1),b1=Math.min(P.length-1,h+1),A0=P.slice($1,b1+1).map((w8)=>w8.trim()).join(" ").slice(0,80);L.push({line:h+1,column:e-x+1,context:A0})}w$=m+1}let R=[`⚠️ EDIT PAUSED: old_string matches ${K.length} locations (must be unique).`,"","**Matches found at:**",...L.map((h,k)=>` ${k+1}. Line ${h.line}`),"","**Action Required:** Add 3-5 lines of surrounding context to make old_string unique.","","**Tips for quick success:**","• Include the function/class name that wraps the target code","• Add 2-3 lines before and after the target","• Include unique comments or variable names nearby",`• Or use replace_all=true to change all ${K.length} occurrences`,"","\uD83E\uDD16 **Auto-retry expected** - This usually resolves in 1-2 attempts."].join(`
|
|
607
|
+
`),T=["⚠️ 编辑暂停:需要更精确的定位","",`在文件中找到 ${K.length} 处相似代码:`,...L.map((h,k)=>` • 第 ${h.line} 行 (匹配 ${k+1}/${K.length})`),"","AI 正在自动调整,添加更多上下文以精确定位...","通常需要 1-2 次尝试即可成功","","\uD83D\uDCA1 如果多次失败,可能需要:"," • 包含函数/类名等独特标识符"," • 添加目标代码前后 3-5 行完整上下文",` • 或使用 replace_all=true 同时替换所有 ${K.length} 处匹配`].join(`
|
|
608
|
+
`);return{success:!1,llmContent:R,displayContent:T,error:{type:"validation_error",message:"old_string is not unique",details:{matches:L.map((h)=>({line:h.line,column:h.column})),count:K.length}}}}else Z?.(`找到 ${K.length} 个匹配项,开始替换...`);let U,F;if(Q)U=B.split(A).join(W),F=K.length;else{let P=B.indexOf(A);U=B.substring(0,P)+W+B.substring(P+A.length),F=1}if(typeof X.throwIfAborted==="function")X.throwIfAborted();let _=k$();if(_.captureBeforeWrite(w),G)Z?.("通过 IDE 写入文件...");if(await O.writeTextFile(w,U),_.trackFileChange(w,"modify"),Y)await Y$.getInstance().recordFileEdit(w,Y,"edit");let D=await O.stat(w),I=D4(B,U,A,W,4),N=A7(w),M=F===1?`替换 1 处匹配到 ${N}`:`替换 ${F} 处匹配到 ${N}`,j={file_path:w,matches_found:K.length,replacements_made:F,replace_all:Q,old_string_length:V.length,new_string_length:W.length,original_size:B.length,new_size:U.length,size_diff:U.length-B.length,last_modified:D?.mtime instanceof Date?D.mtime.toISOString():void 0,snapshot_created:!!(Y&&J),session_id:Y,message_id:J,diff_snippet:I,summary:M,kind:"edit",oldContent:B,newContent:U},F$=_7(j,I);return{success:!0,llmContent:{file_path:w,replacements:F,total_matches:K.length},displayContent:F$,metadata:j}}catch(O){let G=O;if(G.name==="AbortError")return{success:!1,llmContent:"File edit aborted",displayContent:"⚠️ 文件编辑被用户中止",error:{type:"execution_error",message:"操作被中止"}};return{success:!1,llmContent:`File edit failed: ${G.message}`,displayContent:`❌ 编辑文件失败: ${G.message}`,error:{type:"execution_error",message:G.message,details:G}}}},version:"2.0.0",category:"文件操作",tags:["file","edit","replace","modify"],extractSignatureContent:($)=>$.file_path,abstractPermissionRule:($)=>{let b=U7($.file_path);return b?`**/*${b}`:"**/*"}});function y4($){return $.replaceAll("‘","'").replaceAll("’","'").replaceAll("“",'"').replaceAll("”",'"')}function F7($,b){if($.includes(b))return{matched:b,strategy:"exact"};let w=y4(b),W=y4($).indexOf(w);if(W!==-1)return{matched:$.substring(W,W+b.length),strategy:"normalize_quotes"};let Q=j4(b);if(Q!==b&&$.includes(Q))return{matched:Q,strategy:"unescape"};let Z=N4($,b);if(Z)return{matched:Z,strategy:"flexible"};return{matched:null,strategy:"failed"}}function H7($,b){if(b.length===0)return[];let w=[],V=$.indexOf(b);while(V!==-1)w.push(V),V=$.indexOf(b,V+b.length);return w}function _7($,b){let{file_path:w,matches_found:V,replacements_made:W,replace_all:Q,size_diff:Z}=$,Y=`✅ 成功编辑文件: ${w}`;if(Y+=`
|
|
609
|
+
\uD83D\uDCDD 替换了 ${W} 个匹配项`,!Q&&V>1)Y+=` (共找到 ${V} 个匹配项)`;if(Z!==0){let J=Z>0?`增加${Z}`:`减少${Math.abs(Z)}`;Y+=`
|
|
610
|
+
\uD83D\uDCCA 文件大小${J}个字符`}if(b)Y+=b;return Y}function R7($,b,w){let V=$.split(`
|
|
611
|
+
`),W=V.length,Q=E7($,b,3),Z=0,Y=Math.min(20,W);if(Q.length>0){let q=Q[0];Z=Math.max(0,q.lineNumber-10),Y=Math.min(W,q.lineNumber+10)}let X=V.slice(Z,Y).map((q,A)=>{return` ${(Z+A+1).toString().padStart(4)}: ${q}`}).join(`
|
|
612
|
+
`),O=`String not found in file.
|
|
613
|
+
|
|
614
|
+
File: ${w}
|
|
615
|
+
Total lines: ${W}
|
|
616
|
+
|
|
617
|
+
`,G=b.length>300?b.substring(0,300)+`
|
|
618
|
+
... (truncated)`:b;if(O+=`You tried to match:
|
|
619
|
+
${G}
|
|
620
|
+
|
|
621
|
+
`,Q.length>0)O+=`File content around possible matches (lines ${Z+1}-${Y}):
|
|
622
|
+
${X}
|
|
623
|
+
|
|
624
|
+
`;else O+=`File content preview (lines ${Z+1}-${Y}):
|
|
625
|
+
${X}
|
|
626
|
+
|
|
627
|
+
`;if(Q.length>0)O+=`Possible similar matches found:
|
|
628
|
+
`,Q.forEach((q,A)=>{let K=q.text.length>100?q.text.substring(0,100)+"...":q.text;O+=` ${A+1}. Line ${q.lineNumber} (similarity: ${Math.round(q.similarity*100)}%)
|
|
629
|
+
${K.replace(/\n/g,"\\n")}
|
|
630
|
+
`}),O+=`
|
|
631
|
+
`;O+=`Recovery suggestions:
|
|
632
632
|
1. Use the Read tool to verify the current file content
|
|
633
633
|
2. Check for typos, whitespace differences, or quote mismatches
|
|
634
634
|
3. Provide more surrounding context to make the match unique
|
|
@@ -638,58 +638,58 @@ Common issues:
|
|
|
638
638
|
- Line breaks: Ensure \\n characters match exactly
|
|
639
639
|
- Indentation: Spaces vs tabs mismatch
|
|
640
640
|
- Smart quotes: " " vs " (use straight quotes)
|
|
641
|
-
- Outdated mental model: File may have changed since you last read it`;let
|
|
642
|
-
|
|
643
|
-
文件: ${
|
|
644
|
-
搜索字符串长度: ${
|
|
645
|
-
`;if(
|
|
646
|
-
\uD83D\uDCA1 找到 ${
|
|
647
|
-
`,
|
|
648
|
-
`});else
|
|
641
|
+
- Outdated mental model: File may have changed since you last read it`;let B=`❌ Edit 失败: 未找到匹配的字符串
|
|
642
|
+
|
|
643
|
+
文件: ${w}
|
|
644
|
+
搜索字符串长度: ${b.length} 字符
|
|
645
|
+
`;if(Q.length>0)B+=`
|
|
646
|
+
\uD83D\uDCA1 找到 ${Q.length} 个相似匹配项:
|
|
647
|
+
`,Q.forEach((q,A)=>{B+=` ${A+1}. 第 ${q.lineNumber} 行 (相似度: ${Math.round(q.similarity*100)}%)
|
|
648
|
+
`});else B+=`
|
|
649
649
|
⚠️ 未找到相似的匹配项
|
|
650
|
-
`;return
|
|
651
|
-
\uD83D\uDCC4 文件内容摘录 (${
|
|
652
|
-
${
|
|
653
|
-
`,
|
|
650
|
+
`;return B+=`
|
|
651
|
+
\uD83D\uDCC4 文件内容摘录 (${Z+1}-${Y} 行):
|
|
652
|
+
${X}
|
|
653
|
+
`,B+=`
|
|
654
654
|
\uD83D\uDD27 接下来我会:
|
|
655
|
-
`,
|
|
656
|
-
`,
|
|
657
|
-
`,
|
|
658
|
-
`),
|
|
659
|
-
`);if(
|
|
660
|
-
`),
|
|
661
|
-
`),
|
|
662
|
-
`),
|
|
663
|
-
\uD83D\uDCC4 读取了 ${
|
|
664
|
-
\uD83D\uDD10 文件以 base64 编码显示`;return
|
|
655
|
+
`,B+=` 1. 重新读取文件内容
|
|
656
|
+
`,B+=` 2. 仔细核对空格、换行符、引号
|
|
657
|
+
`,B+=" 3. 使用更多上下文代码确保唯一性",{llmContent:O,displayContent:B,metadata:{searchStringLength:b.length,fuzzyMatches:Q.map((q)=>({line:q.lineNumber,similarity:q.similarity,preview:q.text.substring(0,100)})),excerptRange:[Z+1,Y],totalLines:W}}}function E7($,b,w=3){let V=$.split(`
|
|
658
|
+
`),W=b.split(`
|
|
659
|
+
`);if(W.length===1)return V.map((J,X)=>({text:J,lineNumber:X+1,similarity:v4(b.trim(),J.trim())})).filter((J)=>J.similarity>0.5).sort((J,X)=>X.similarity-J.similarity).slice(0,w);let Q=W.length,Z=[];for(let Y=0;Y<=V.length-Q;Y++){let J=V.slice(Y,Y+Q).join(`
|
|
660
|
+
`),X=v4(b,J);if(X>0.5)Z.push({text:J,lineNumber:Y+1,similarity:X})}return Z.sort((Y,J)=>J.similarity-Y.similarity).slice(0,w)}function v4($,b){let w=(B)=>B.trim().replace(/\s+/g," ").replace(/[\u201c\u201d"]/g,'"').replace(/[\u2018\u2019']/g,"'"),V=w($),W=w(b);if(V===W)return 1;let Q=V.length,Z=W.length;if(Q===0)return Z===0?1:0;if(Z===0)return 0;let Y=200,J=V.substring(0,Y),X=W.substring(0,Y),O=L7(J,X),G=Math.max(J.length,X.length);return 1-O/G}function L7($,b){let w=$.length,V=b.length,W=Array(w+1).fill(null).map(()=>Array(V+1).fill(0));for(let Q=0;Q<=w;Q++)W[Q][0]=Q;for(let Q=0;Q<=V;Q++)W[0][Q]=Q;for(let Q=1;Q<=w;Q++)for(let Z=1;Z<=V;Z++){let Y=$[Q-1]===b[Z-1]?0:1;W[Q][Z]=Math.min(W[Q-1][Z]+1,W[Q][Z-1]+1,W[Q-1][Z-1]+Y)}return W[w][V]}import{basename as D7,extname as T4}from"path";import{z as j7}from"zod";var h1=E({name:"Read",displayName:"File Read",kind:"readonly",schema:j7.object({file_path:g.filePath({description:"File path to read (must be absolute)"}),offset:g.lineNumber({description:"Starting line number (0-based, text files only)"}).optional(),limit:g.lineLimit({description:"Number of lines to read (text files only)"}).optional(),encoding:g.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($,b){let{file_path:w,offset:V,limit:W,encoding:Q="utf8"}=$,{updateOutput:Z,sessionId:Y}=b,J=b.signal??new AbortController().signal;try{Z?.("Starting file read...");let X=E0(),O=s$();try{if(!await X.exists(w))throw Error("File not found")}catch(N){return{success:!1,llmContent:`File not found: ${w}`,displayContent:`❌ 文件不存在: ${w}`,error:{type:"execution_error",message:`File not found: ${w}`}}}if(typeof J.throwIfAborted==="function")J.throwIfAborted();if(Y)await Y$.getInstance().recordFileRead(w,Y);let G=await X.stat(w);if(G?.isDirectory)return{success:!1,llmContent:`Cannot read a directory: ${w}`,displayContent:`❌ 无法读取目录: ${w}`,error:{type:"execution_error",message:"Target is a directory, not a file"}};let B=T4(w).toLowerCase(),q=N7(B),A=S7(B),K,U={file_path:w,file_size:G?.size,file_type:B,last_modified:G?.mtime instanceof Date?G.mtime.toISOString():void 0,encoding:Q,acp_mode:O};if(A&&Q==="utf8"){if(O)Z?.("⚠️ 二进制文件通过本地读取(ACP 不支持)..."),U.acp_fallback=!0;else Z?.("检测到二进制文件,使用 base64 编码...");K=(await X.readBinaryFile(w)).toString("base64"),U.encoding="base64",U.is_binary=!0}else if(q){if(O)Z?.("通过 IDE 读取文件...");K=await X.readTextFile(w)}else{if(O)U.acp_fallback=!0;let N=await X.readBinaryFile(w);if(Q==="base64")K=N.toString("base64");else if(Q==="binary")K=N.toString("binary");else K=N.toString("utf8")}if(typeof J.throwIfAborted==="function")J.throwIfAborted();if((V!==void 0||W!==void 0)&&Q==="utf8"&&q){let N=K.split(`
|
|
661
|
+
`),M=V||0,j=W!==void 0?M+W:N.length,F$=N.slice(M,j);K=F$.map((P,w$)=>{let L=M+w$+1,R=P.length>2000?`${P.substring(0,2000)}...`:P;return`${L.toString().padStart(6)}→${R}`}).join(`
|
|
662
|
+
`),U.lines_read=F$.length,U.total_lines=N.length,U.start_line=M+1,U.end_line=Math.min(j,N.length)}let F=D7(w),_=U.lines_read||U.total_lines,D=_?`读取 ${_} 行从 ${F}`:`读取 ${F}`;U.summary=D;let I=M7(w,U);return{success:!0,llmContent:K,displayContent:I,metadata:U}}catch(X){let O=X;if(O.name==="AbortError")return{success:!1,llmContent:"File read aborted",displayContent:"⚠️ 文件读取被用户中止",error:{type:"execution_error",message:"Operation aborted"}};return{success:!1,llmContent:`File read failed: ${O.message}`,displayContent:`❌ 读取文件失败: ${O.message}`,error:{type:"execution_error",message:O.message,details:O}}}},version:"2.0.0",category:"文件操作",tags:["file","io","read"],extractSignatureContent:($)=>$.file_path,abstractPermissionRule:($)=>{let b=T4($.file_path);return b?`**/*${b}`:"**/*"}});function N7($){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 S7($){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 M7($,b){let w=`✅ 成功读取文件: ${$}`;if(b.file_size!==void 0&&typeof b.file_size==="number")w+=` (${z7(b.file_size)})`;if(b.lines_read!==void 0)w+=`
|
|
663
|
+
\uD83D\uDCC4 读取了 ${b.lines_read} 行 (第${b.start_line}-${b.end_line}行,共${b.total_lines}行)`;if(b.is_binary)w+=`
|
|
664
|
+
\uD83D\uDD10 文件以 base64 编码显示`;return w}function z7($){let b=["B","KB","MB","GB"],w=$,V=0;while(w>=1024&&V<b.length-1)w/=1024,V++;return`${w.toFixed(1)}${b[V]}`}import{promises as y7}from"fs";import{basename as v7,dirname as T7,extname as k4}from"path";import{z as x1}from"zod";var p1=E({name:"Write",displayName:"File Write",kind:"write",strict:!0,isConcurrencySafe:!1,schema:x1.object({file_path:g.filePath({description:"Absolute file path to write"}),content:x1.string().describe("Content to write"),encoding:g.encoding(),create_directories:x1.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($,b){let{file_path:w,content:V,encoding:W,create_directories:Q}=$,{updateOutput:Z,sessionId:Y,messageId:J}=b,X=b.signal??new AbortController().signal;try{Z?.("开始写入文件...");let O=E0(),G=s$();if(Q){let M=T7(w);try{await O.mkdir(M,{recursive:!0,mode:493})}catch(j){if(j.code!=="EEXIST")throw j}}if(typeof X.throwIfAborted==="function")X.throwIfAborted();let B=!1,q=null;try{if(B=await O.exists(w),B&&W==="utf8")try{q=await O.readTextFile(w)}catch(M){console.warn("[WriteTool] 读取旧文件内容失败:",M)}}catch{}if(B&&Y){let M=Y$.getInstance();if(!M.hasFileBeenRead(w,Y))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:"\uD83D\uDCD6 我需要先读取文件内容,然后再进行写入。",error:{type:"validation_error",message:"File not read before write"},metadata:{requiresRead:!0}};let j=await M.checkExternalModification(w);if(j.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.
|
|
665
665
|
|
|
666
|
-
Details: ${
|
|
666
|
+
Details: ${j.message}`,displayContent:`❌ 写入失败:文件已被外部程序修改
|
|
667
667
|
|
|
668
|
-
${
|
|
668
|
+
${j.message}
|
|
669
669
|
|
|
670
|
-
\uD83D\uDCA1 我需要重新读取文件内容后再写入`,error:{type:"validation_error",message:"File modified externally",details:{externalModification:
|
|
670
|
+
\uD83D\uDCA1 我需要重新读取文件内容后再写入`,error:{type:"validation_error",message:"File modified externally",details:{externalModification:j.message}}}}let A=!1;if(B&&Y&&J)try{let M=new a0({sessionId:Y});await M.initialize(),await M.createSnapshot(w,J),A=!0}catch(M){console.warn("[WriteTool] 创建快照失败:",M)}let K=k$();if(K.captureBeforeWrite(w),typeof X.throwIfAborted==="function")X.throwIfAborted();if(W==="utf8"){if(G)Z?.("通过 IDE 写入文件...");await O.writeTextFile(w,V)}else{if(G)return{success:!1,llmContent:"Binary file writes are not supported in ACP mode. The IDE only supports text file operations. Please use encoding='utf8' for text files, or ask the user to write the file manually.",displayContent:`❌ ACP 模式不支持二进制文件写入
|
|
671
671
|
|
|
672
672
|
当前通过 IDE 执行文件操作,但 IDE 仅支持文本文件。
|
|
673
673
|
|
|
674
|
-
\uD83D\uDCA1 如果是文本文件,我会使用 encoding='utf8' 重试;如果必须写入二进制文件,需要在本地终端执行`,error:{type:"validation_error",message:"Binary writes not supported in ACP mode"}};let
|
|
675
|
-
`).length:0,
|
|
676
|
-
\uD83D\uDCF8 已创建快照 (可回滚)`;if(
|
|
677
|
-
\uD83D\uDD10 使用编码: ${
|
|
674
|
+
\uD83D\uDCA1 如果是文本文件,我会使用 encoding='utf8' 重试;如果必须写入二进制文件,需要在本地终端执行`,error:{type:"validation_error",message:"Binary writes not supported in ACP mode"}};let M;if(W==="base64")M=Buffer.from(V,"base64");else if(W==="binary")M=Buffer.from(V,"binary");else M=Buffer.from(V,"utf8");await y7.writeFile(w,M)}if(Y)await Y$.getInstance().recordFileEdit(w,Y,"write");if(K.trackFileChange(w,B?"modify":"create"),typeof X.throwIfAborted==="function")X.throwIfAborted();let U=await O.stat(w),F=W==="utf8"?V.split(`
|
|
675
|
+
`).length:0,_=v7(w),D=null;if(q&&W==="utf8"&&q!==V){if(q.length<1048576&&V.length<1048576)D=L4(q,V,4)}let I={file_path:w,content_size:V.length,file_size:U?.size,encoding:W,created_directories:Q,snapshot_created:A,session_id:Y,message_id:J,last_modified:U?.mtime instanceof Date?U.mtime.toISOString():void 0,has_diff:!!D,summary:W==="utf8"?`写入 ${F} 行到 ${_}`:`写入 ${U?.size?f4(U.size):"unknown"} 到 ${_}`,kind:"edit",oldContent:q||"",newContent:W==="utf8"?V:void 0},N=k7(w,I,V,D);return{success:!0,llmContent:{file_path:w,size:U?.size,modified:U?.mtime instanceof Date?U.mtime.toISOString():void 0},displayContent:N,metadata:I}}catch(O){let G=O;if(G.name==="AbortError")return{success:!1,llmContent:"File write aborted",displayContent:"⚠️ 文件写入被用户中止",error:{type:"execution_error",message:"操作被中止"}};return{success:!1,llmContent:`File write failed: ${G.message}`,displayContent:`❌ 写入文件失败: ${G.message}`,error:{type:"execution_error",message:G.message,details:G}}}},version:"2.0.0",category:"文件操作",tags:["file","io","write","create"],extractSignatureContent:($)=>$.file_path,abstractPermissionRule:($)=>{let b=k4($.file_path);return b?`**/*${b}`:"**/*"}});function k7($,b,w,V){let W=`✅ 成功写入文件: ${$}`;if(b.file_size!==void 0)W+=` (${f4(b.file_size)})`;if(b.snapshot_created)W+=`
|
|
676
|
+
\uD83D\uDCF8 已创建快照 (可回滚)`;if(b.encoding!=="utf8")W+=`
|
|
677
|
+
\uD83D\uDD10 使用编码: ${b.encoding}`;if(V)W+=V;if(w&&b.encoding==="utf8"&&!V){let Q=f7($,w);if(Q)W+=`
|
|
678
678
|
|
|
679
|
-
`+
|
|
680
|
-
`);if(
|
|
681
|
-
`),
|
|
679
|
+
`+Q}return W}function f7($,b){let w=k4($).toLowerCase(),W={".ts":"typescript",".tsx":"tsx",".js":"javascript",".jsx":"jsx",".py":"python",".go":"go",".rs":"rust",".java":"java",".c":"c",".cpp":"cpp",".h":"c",".hpp":"cpp",".cs":"csharp",".rb":"ruby",".php":"php",".swift":"swift",".kt":"kotlin",".scala":"scala",".sh":"bash",".bash":"bash",".zsh":"zsh",".json":"json",".yaml":"yaml",".yml":"yaml",".toml":"toml",".xml":"xml",".html":"html",".css":"css",".scss":"scss",".sass":"sass",".less":"less",".md":"markdown",".sql":"sql",".graphql":"graphql",".proto":"protobuf"}[w]||"",Q=100,Z=5000,Y=b,J=!1,X=b.split(`
|
|
680
|
+
`);if(X.length>100)Y=X.slice(0,100).join(`
|
|
681
|
+
`),J=!0;if(Y.length>5000)Y=Y.substring(0,5000),J=!0;let O=`\uD83D\uDCC4 文件内容:
|
|
682
682
|
|
|
683
|
-
`;if(
|
|
684
|
-
`,
|
|
685
|
-
`))
|
|
686
|
-
`;if(
|
|
683
|
+
`;if(O+="```"+W+`
|
|
684
|
+
`,O+=Y,!Y.endsWith(`
|
|
685
|
+
`))O+=`
|
|
686
|
+
`;if(O+="```",J)O+=`
|
|
687
687
|
|
|
688
|
-
⚠️ 内容已截断(完整文件共 ${
|
|
689
|
-
`).map((
|
|
690
|
-
`:
|
|
691
|
-
`).map((
|
|
692
|
-
`:
|
|
688
|
+
⚠️ 内容已截断(完整文件共 ${X.length} 行,${b.length} 字符)`;return O}function f4($){let b=["B","KB","MB","GB"],w=$,V=0;while(w>=1024&&V<b.length-1)w/=1024,V++;return`${w.toFixed(1)}${b[V]}`}import*as Sb from"fs/promises";import{z as L0}from"zod";var Mb=E({name:"NotebookEdit",displayName:"Notebook Edit",kind:"write",schema:L0.object({notebook_path:L0.string().describe("The absolute path to the Jupyter notebook file to edit (must be absolute, not relative)"),cell_id:L0.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:L0.string().describe("The new source for the cell"),cell_type:L0.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:L0.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($,b){let{notebook_path:w,cell_id:V,new_source:W,cell_type:Q,edit_mode:Z="replace"}=$;try{let Y=await Sb.readFile(w,"utf-8"),J=JSON.parse(Y);if(!J.cells||!Array.isArray(J.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 X=-1;if(V){if(X=J.cells.findIndex((G)=>G.id===V),X===-1&&Z!=="insert")return{success:!1,llmContent:`Cell with ID "${V}" not found`,displayContent:"Cell not found",error:{type:"validation_error",message:`Cell ID "${V}" not found`}}}switch(Z){case"replace":{if(X===-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 G=J.cells[X];if(G.source=W.split(`
|
|
689
|
+
`).map((B,q,A)=>q<A.length-1?B+`
|
|
690
|
+
`:B),Q)G.cell_type=Q;break}case"insert":{if(!Q)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 G={cell_type:Q,source:W.split(`
|
|
691
|
+
`).map((q,A,K)=>A<K.length-1?q+`
|
|
692
|
+
`:q),metadata:{},...Q==="code"?{execution_count:null,outputs:[]}:{}},B=X===-1?0:X+1;J.cells.splice(B,0,G);break}case"delete":{if(X===-1)return{success:!1,llmContent:"Cell ID required for delete operation",displayContent:"Cell ID required",error:{type:"validation_error",message:"Cell ID required for delete"}};J.cells.splice(X,1);break}}await Sb.writeFile(w,JSON.stringify(J,null,2));let O=Z==="replace"?"replaced":Z==="insert"?"inserted":"deleted";return{success:!0,llmContent:`Successfully ${O} cell in ${w}`,displayContent:`Cell ${O} in notebook`,metadata:{notebook_path:w,edit_mode:Z,cell_id:V}}}catch(Y){let J=Y instanceof Error?Y.message:"Unknown error";return{success:!1,llmContent:`Failed to edit notebook: ${J}`,displayContent:"Notebook edit failed",error:{type:"execution_error",message:J}}}}});import{z as I7}from"zod";var d1=E({name:"EnterPlanMode",displayName:"Enter Plan Mode",kind:"readonly",schema:I7.object({}),description:{short:"Use this tool to enter plan mode for complex tasks requiring careful planning",long:`Use this tool when you encounter a complex task that requires careful planning and exploration before implementation. This tool transitions you into plan mode where you can thoroughly explore the codebase and design an implementation approach.
|
|
693
693
|
|
|
694
694
|
## When to Use This Tool
|
|
695
695
|
|
|
@@ -762,7 +762,7 @@ User: "What files handle routing?"
|
|
|
762
762
|
- Be thoughtful about when to use it - unnecessary plan mode slows down simple tasks
|
|
763
763
|
- If unsure whether to use it, err on the side of starting implementation
|
|
764
764
|
- You can always ask the user "Would you like me to plan this out first?"
|
|
765
|
-
`},async execute($,
|
|
765
|
+
`},async execute($,b){if(b.confirmationHandler)try{if((await b.confirmationHandler.requestConfirmation({type:"enterPlanMode",message:`The assistant requests to enter Plan mode for this complex task. In Plan mode, the assistant will:
|
|
766
766
|
|
|
767
767
|
1. Research the codebase thoroughly (read-only)
|
|
768
768
|
2. Understand existing patterns and architecture
|
|
@@ -779,9 +779,9 @@ Do you want to enter Plan mode?`,details:"Plan mode enables systematic research
|
|
|
779
779
|
|
|
780
780
|
Begin your research now.`,displayContent:"✅ Entering Plan mode",metadata:{approved:!0,enterPlanMode:!0}};else return{success:!0,llmContent:`⚠️ User declined to enter Plan mode.
|
|
781
781
|
|
|
782
|
-
`+"Proceed with the task directly without planning phase. You can still use search tools to understand the codebase as needed, but implement the solution directly.",displayContent:"⚠️ Plan mode declined, proceeding directly",metadata:{approved:!1,enterPlanMode:!1}}}catch(
|
|
782
|
+
`+"Proceed with the task directly without planning phase. You can still use search tools to understand the codebase as needed, but implement the solution directly.",displayContent:"⚠️ Plan mode declined, proceeding directly",metadata:{approved:!1,enterPlanMode:!1}}}catch(w){return{success:!1,llmContent:`Confirmation flow error: ${w instanceof Error?w.message:"Unknown error"}`,displayContent:"❌ Failed to request confirmation",error:{type:"execution_error",message:"Confirmation flow error"}}}return{success:!0,llmContent:`Plan mode requested but no interactive confirmation available.
|
|
783
783
|
|
|
784
|
-
Proceeding with research phase. Use read-only tools to explore the codebase, then call ExitPlanMode with your implementation plan when ready.`,displayContent:"Plan mode (non-interactive)",metadata:{approved:null,enterPlanMode:!0}}}});import{promises as
|
|
784
|
+
Proceeding with research phase. Use read-only tools to explore the codebase, then call ExitPlanMode with your implementation plan when ready.`,displayContent:"Plan mode (non-interactive)",metadata:{approved:null,enterPlanMode:!0}}}});import{promises as I4}from"node:fs";import{homedir as P7}from"node:os";import*as u1 from"node:path";import{z as P4}from"zod";var g1=E({name:"ExitPlanMode",displayName:"Exit Plan Mode",kind:"readonly",schema:P4.object({plan:P4.string().describe("The complete implementation plan in markdown format")}),description:{short:"Use this tool when you are in plan mode and have finished creating your plan and are ready for user approval",long:`Use this tool when you are in plan mode and have finished creating your implementation plan and are ready for user approval.
|
|
785
785
|
|
|
786
786
|
## \uD83D\uDEA8 PREREQUISITES (MUST be satisfied before calling)
|
|
787
787
|
|
|
@@ -816,7 +816,7 @@ Before using this tool, ensure your plan is clear and unambiguous. If there are
|
|
|
816
816
|
1. Initial task: "Search for and understand the implementation of vim mode in the codebase" - Do not use the exit plan mode tool because you are not planning the implementation steps of a task.
|
|
817
817
|
2. Initial task: "Help me implement yank mode for vim" - Use the exit plan mode tool after you have finished planning the implementation steps of the task.
|
|
818
818
|
3. Initial task: "Add a new feature to handle user authentication" - If unsure about auth method (OAuth, JWT, etc.), use AskUserQuestion first, then use exit plan mode tool after clarifying the approach.
|
|
819
|
-
`},async execute($,
|
|
819
|
+
`},async execute($,b){let w=$.plan||"";if(w&&b.sessionId)try{let V=u1.join(P7(),".blade","plans");await I4.mkdir(V,{recursive:!0,mode:493});let W=u1.join(V,`plan_${b.sessionId}.md`);await I4.writeFile(W,w,"utf-8")}catch(V){console.warn("Failed to save plan file:",V)}if(b.confirmationHandler)try{let V=await b.confirmationHandler.requestConfirmation({type:"exitPlanMode",message:`The assistant has finished planning and is ready for your review.
|
|
820
820
|
|
|
821
821
|
`+`⚠️ Before approving, please verify:
|
|
822
822
|
`+`1. The assistant has written a detailed plan to the plan file
|
|
@@ -824,44 +824,45 @@ Before using this tool, ensure your plan is clear and unambiguous. If there are
|
|
|
824
824
|
3. You have seen text explanations from the assistant (not just tool calls)
|
|
825
825
|
|
|
826
826
|
If the assistant only made tool calls without presenting a plan summary,
|
|
827
|
-
please reject and ask for a proper plan.`,details:"After approval, the assistant will exit Plan mode and begin implementation.",planContent:
|
|
827
|
+
please reject and ask for a proper plan.`,details:"After approval, the assistant will exit Plan mode and begin implementation.",planContent:w||void 0});if(V.approved)return{success:!0,llmContent:"✅ Plan approved by user. Plan mode exited; you can proceed to code changes.",displayContent:"✅ Plan approved, exiting Plan mode",metadata:{approved:!0,shouldExitLoop:!0,targetMode:V.targetMode,planContent:w}};else return{success:!0,llmContent:`⚠️ Plan rejected by user. Awaiting user feedback.
|
|
828
828
|
|
|
829
|
-
`+(
|
|
829
|
+
`+(V.feedback||"No specific feedback provided.")+`
|
|
830
830
|
|
|
831
|
-
The agent has stopped and control is returned to the user. The user can now provide additional information or clarification.`,displayContent:"⚠️ 方案被拒绝,等待用户补充信息",metadata:{approved:!1,shouldExitLoop:!0,feedback:
|
|
832
|
-
`+"Proceeding with implementation.",displayContent:"Plan mode exit (non-interactive)",metadata:{approved:null}}}});import
|
|
833
|
-
`)){let
|
|
834
|
-
`);for(let
|
|
831
|
+
The agent has stopped and control is returned to the user. The user can now provide additional information or clarification.`,displayContent:"⚠️ 方案被拒绝,等待用户补充信息",metadata:{approved:!1,shouldExitLoop:!0,feedback:V.feedback,awaitingUserInput:!0}}}catch(V){return{success:!1,llmContent:`Confirmation flow error: ${V instanceof Error?V.message:"Unknown error"}`,displayContent:"❌ Confirmation failed",error:{type:"execution_error",message:"Confirmation flow error"}}}return{success:!0,llmContent:`✅ Plan mode exit requested. No interactive confirmation available.
|
|
832
|
+
`+"Proceeding with implementation.",displayContent:"Plan mode exit (non-interactive)",metadata:{approved:null}}}});import l7 from"fast-glob";import{stat as n7}from"node:fs/promises";import{join as s7,resolve as r7}from"path";import{z as yb}from"zod";import{existsSync as h7,readFileSync as x7}from"node:fs";import{readFile as p7}from"node:fs/promises";import{dirname as d7,join as x4}from"node:path";import u7 from"fast-glob";import{LRUCache as g7}from"lru-cache";import t0 from"picomatch";function o0($){return $.replace(/\\/g,"/").split("/").filter(Boolean)}var W0=["node_modules",".git","dist","build","out",".next",".nuxt",".cache",".parcel-cache","coverage",".nyc_output",".idea",".vscode",".vs","bower_components","jspm_packages"],m7=["*.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"];function c7($){if(!h7($))return{patterns:[],negatePatterns:[]};try{let b=x7($,"utf-8"),w=[],V=[];for(let W of b.split(`
|
|
833
|
+
`)){let Q=W.trim();if(!Q||Q.startsWith("#"))continue;if(Q.startsWith("!"))V.push(Q.slice(1));else w.push(Q)}return{patterns:w,negatePatterns:V}}catch(b){return console.warn(`Failed to read .gitignore: ${b}`),{patterns:[],negatePatterns:[]}}}var h4=new g7({max:100,ttl:30000,updateAgeOnGet:!0});async function i7($,b){let w=[...W0.map((J)=>`${J}/**`),...b?.scanIgnore??[]],V=`${$}|${w.join(",")}`,W=h4.get(V);if(W)return W;let Q=await u7("**/.gitignore",{cwd:$,dot:!0,onlyFiles:!0,followSymbolicLinks:!1,unique:!0,ignore:w});Q.sort((J,X)=>o0(J).length-o0(X).length);let Z=[];for(let J of Q){let X=d7(J).replace(/\\/g,"/"),O=X==="."?"":X,B=(await p7(x4($,J),"utf-8")).split(`
|
|
834
|
+
`);for(let q of B){let A=q.trim();if(!A||A.startsWith("#"))continue;let K=A.startsWith("!"),F=(K?A.slice(1):A).trim();if(!F)continue;let _="";if(F.startsWith("/")){let D=F.slice(1).replace(/\\/g,"/");if(_=(O?O+"/":"")+D,Z.push({type:K?"negate":"ignore",pattern:_}),F.endsWith("/")){let I=_+"**";Z.push({type:K?"negate":"ignore",pattern:I});let N=_.replace(/\/$/,"");if(N!==_)Z.push({type:K?"negate":"ignore",pattern:N})}}else{let D=F.replace(/\\/g,"/");if(D.includes("/")){if(_=(O?O+"/":"")+D,Z.push({type:K?"negate":"ignore",pattern:_}),D.endsWith("/")){let I=_+"**";Z.push({type:K?"negate":"ignore",pattern:I});let N=_.replace(/\/$/,"");if(N!==_)Z.push({type:K?"negate":"ignore",pattern:N})}}else _=(O?O+"/**/":"**/")+D,Z.push({type:K?"negate":"ignore",pattern:_})}}}let Y=b?.cacheTTL??30000;return h4.set(V,Z,{ttl:Y}),Z}class zb{orderedRules=[];ignorePatterns=[];negatePatterns=[];constructor($={}){this.initialize($)}static async create($={}){let b=new zb({...$,useGitignore:!1}),{cwd:w=process.cwd(),useGitignore:V=!0,gitignoreScanMode:W="root",customScanIgnore:Q=[],cacheTTL:Z}=$;if(V&&W==="recursive"){let Y=await i7(w,{scanIgnore:Q,cacheTTL:Z});for(let J of Y)if(b.orderedRules.push({type:J.type,matcher:t0(J.pattern,{dot:!0})}),J.type==="ignore")b.ignorePatterns.push(J.pattern);else b.negatePatterns.push(J.pattern)}return b}initialize($){let{cwd:b=process.cwd(),useGitignore:w=!0,useDefaults:V=!0,customPatterns:W=[]}=$,Q=[],Z=[];if(V){let Y=[...W0.map((J)=>`${J}/**`),...W0,...m7];Q.push(...Y);for(let J of Y)this.orderedRules.push({type:"ignore",matcher:t0(J,{dot:!0})})}if(w){let Y=x4(b,".gitignore"),{patterns:J,negatePatterns:X}=c7(Y);for(let O of J)this.orderedRules.push({type:"ignore",matcher:t0(O,{dot:!0})}),Q.push(O);for(let O of X)this.orderedRules.push({type:"negate",matcher:t0(O,{dot:!0})}),Z.push(O)}Q.push(...W);for(let Y of W)this.orderedRules.push({type:"ignore",matcher:t0(Y,{dot:!0})});this.ignorePatterns=Q,this.negatePatterns=Z}shouldIgnore($){let b=$.replace(/\\/g,"/"),w;for(let V of this.orderedRules)if(V.matcher(b))w=V.type==="ignore";return w===!0}shouldIgnoreDirectory($){let b=$.replace(/\\/g,"/");return this.shouldIgnore(b)||this.shouldIgnore(`${b}/`)}filter($){return $.filter((b)=>!this.shouldIgnore(b))}getIgnorePatterns(){return this.ignorePatterns}getNegatePatterns(){return this.negatePatterns}}function m1($){let b=Error($);return b.name="AbortError",b}var c1=E({name:"Glob",displayName:"File Pattern Match",kind:"readonly",schema:yb.object({pattern:g.glob({description:"Glob pattern string (supports *, ?, ** wildcards)"}),path:yb.string().optional().describe("Search path (optional, defaults to cwd)"),max_results:g.positiveInt({description:"Maximum number of results"}).max(1000,"At most 1000 results can be returned").default(100),include_directories:yb.boolean().default(!1).describe("Include directories in results"),case_sensitive:yb.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($,b){let{pattern:w,path:V=process.cwd(),max_results:W,include_directories:Q,case_sensitive:Z}=$,{updateOutput:Y}=b,J=b.signal??new AbortController().signal;try{Y?.(`Searching in ${V} for pattern "${w}"...`);let X=r7(V);try{if(!(await n7(X)).isDirectory())return{success:!1,llmContent:`Search path must be a directory: ${X}`,displayContent:`❌ 搜索路径必须是目录: ${X}`,error:{type:"validation_error",message:"搜索路径必须是目录"}}}catch(F){if(F.code==="ENOENT")return{success:!1,llmContent:`Search path does not exist: ${X}`,displayContent:`❌ 搜索路径不存在: ${X}`,error:{type:"execution_error",message:"搜索路径不存在"}};throw F}J.throwIfAborted();let O=await zb.create({cwd:X,useGitignore:!0,useDefaults:!0,gitignoreScanMode:"recursive",customScanIgnore:[],cacheTTL:30000}),{matches:G,wasTruncated:B}=await a7(X,w,{maxResults:W,includeDirectories:Q,caseSensitive:Z,signal:J},O),q=o7(G),A={search_path:X,pattern:w,total_matches:G.length,returned_matches:G.length,max_results:W,include_directories:Q,case_sensitive:Z,truncated:B},K=t7(A),U;if(q.length>0)U=`${B?`Found at least ${q.length} file(s) matching "${w}" (truncated)`:`Found ${q.length} file(s) matching "${w}"`}:
|
|
835
835
|
|
|
836
|
-
`+
|
|
836
|
+
`+q.map((_)=>`- ${_.relative_path}`).join(`
|
|
837
837
|
`)+`
|
|
838
838
|
|
|
839
|
-
Use the relative_path values above for Read/Edit operations.`;else
|
|
840
|
-
\uD83D\uDCCB 显示前 ${
|
|
841
|
-
`).forEach((
|
|
842
|
-
`),
|
|
843
|
-
\uD83D\uDD27 使用策略: ${
|
|
844
|
-
\uD83D\uDCC1 找到 ${
|
|
845
|
-
\uD83D\uDD22 统计了 ${
|
|
846
|
-
\uD83D\uDCDD 找到 ${Z} 个匹配行`;break}return J}var b2=N({name:"Grep",displayName:"内容搜索",kind:"readonly",schema:h$.object({pattern:g.pattern({description:"The regular expression pattern to search for in file contents"}),path:h$.string().optional().describe("File or directory to search in (rg PATH). Defaults to current working directory"),glob:h$.string().optional().describe('Glob pattern to filter files (e.g. "*.js", "*.{ts,tsx}") - maps to rg --glob'),type:h$.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:h$.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":h$.boolean().optional().describe("Case insensitive search (rg -i)"),"-n":h$.boolean().default(!0).describe('Show line numbers in output (rg -n). Requires output_mode: "content", ignored otherwise. Defaults to true'),"-B":g.nonNegativeInt().optional().describe('Number of lines to show before each match (rg -B). Requires output_mode: "content", ignored otherwise'),"-A":g.nonNegativeInt().optional().describe('Number of lines to show after each match (rg -A). Requires output_mode: "content", ignored otherwise'),"-C":g.nonNegativeInt().optional().describe('Number of lines to show before and after each match (rg -C). Requires output_mode: "content", ignored otherwise'),head_limit:g.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:g.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:h$.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($,V){let{pattern:W,path:Q=process.cwd(),glob:Z,type:Y,output_mode:J,"-i":X,"-n":G=!0,"-B":B,"-A":K,"-C":q,head_limit:O,offset:w,multiline:b}=$,{updateOutput:A}=V,H=V.signal??new AbortController().signal;try{A?.(`使用智能搜索策略查找模式 "${W}"...`);let F=null,_="ripgrep",L=[],P=G8();if(P)try{A?.(`\uD83D\uDE80 使用 ripgrep (${P})`);let y=FV({pattern:W,path:Q,glob:Z,type:Y,output_mode:J,case_insensitive:X??!1,line_numbers:G,context_before:B,context_after:K,context:q,head_limit:O,offset:w,multiline:b??!1});F=await qV(y,J,H,A),_="ripgrep"}catch{A?.("⚠️ ripgrep 失败,尝试降级策略..."),F=null}if(!F&&await BV(Q))try{A?.("\uD83D\uDCE6 使用 git grep"),F=await OV(W,Q,{caseInsensitive:X??!1,glob:Z,contextLines:q},H),_="git-grep"}catch{A?.("⚠️ git grep 失败,继续尝试其他策略..."),F=null}if(!F&&KV())try{A?.("\uD83D\uDD27 使用系统 grep"),F=await AV(W,Q,{caseInsensitive:X??!1,contextLines:q},H),_="system-grep"}catch{A?.("⚠️ 系统 grep 失败,使用纯 JavaScript 实现..."),F=null}if(!F)A?.("\uD83D\uDCA1 使用纯 JavaScript 搜索实现"),L=(await wV(W,Q,{caseInsensitive:X??!1,glob:Z,multiline:b??!1},H)).matches,_="fallback",F={stdout:"",stderr:"",exitCode:0};else L=HV(F.stdout,J);let j=L.length;if(w!==void 0&&w>0)L=L.slice(w);if(O!==void 0&&L.length>O)L=L.slice(0,O);let v={search_pattern:W,search_path:Q,output_mode:J,case_insensitive:X??!1,total_matches:L.length,original_total:j,offset:w,head_limit:O,strategy:_,exit_code:F?.exitCode};if(F&&F.exitCode!==0&&F.stderr)return{success:!1,llmContent:`Search execution failed: ${F.stderr}`,displayContent:`❌ 搜索执行失败: ${F.stderr}`,error:{type:"execution_error",message:F.stderr}};let E=_V(v);return{success:!0,llmContent:L,displayContent:E,metadata:v}}catch(F){let _=F;if(_.name==="AbortError")return{success:!1,llmContent:"Search aborted",displayContent:"⚠️ 搜索被用户中止",error:{type:"execution_error",message:"操作被中止"}};return{success:!1,llmContent:`Search failed: ${_.message}`,displayContent:`❌ 搜索失败: ${_.message}`,error:{type:"execution_error",message:_.message,details:_}}}},version:"3.0.0",category:"搜索工具",tags:["search","grep","ripgrep","regex","text","fallback"],extractSignatureContent:($)=>$.pattern,abstractPermissionRule:()=>"*"});import{spawn as RV}from"child_process";import{randomUUID as EV}from"crypto";import{z as F2}from"zod";import{spawn as CV}from"child_process";import{randomUUID as jV}from"crypto";class K${static instance=null;processes=new Map;static getInstance(){if(!K$.instance)K$.instance=new K$;return K$.instance}startBackgroundProcess($){let V=`bash_${jV()}`,W={};for(let[Y,J]of Object.entries({...process.env,...$.env,BLADE_CLI:"1"}))if(J!==void 0)W[Y]=J;let Q=CV("bash",["-c",$.command],{cwd:$.cwd||process.cwd(),env:W,stdio:["ignore","pipe","pipe"]}),Z={id:V,command:$.command,sessionId:$.sessionId,cwd:$.cwd,env:$.env,process:Q,pid:Q.pid,status:"running",startTime:Date.now(),pendingStdout:"",pendingStderr:""};return Q.stdout?.setEncoding("utf8"),Q.stderr?.setEncoding("utf8"),Q.stdout?.on("data",(Y)=>{Z.pendingStdout+=Y.toString()}),Q.stderr?.on("data",(Y)=>{Z.pendingStderr+=Y.toString()}),Q.on("close",(Y,J)=>{Z.status=Z.status==="killed"?"killed":"exited",Z.exitCode=Y,Z.signal=J,Z.endTime=Date.now(),Z.process=void 0}),Q.on("error",(Y)=>{Z.status="error",Z.errorMessage=Y.message,Z.endTime=Date.now(),Z.process=void 0,Z.pendingStderr+=`
|
|
847
|
-
[
|
|
848
|
-
`),
|
|
849
|
-
`);if(
|
|
839
|
+
Use the relative_path values above for Read/Edit operations.`;else U=`No files found matching "${w}"`;return{success:!0,llmContent:U,displayContent:K,metadata:{...A,matches:q}}}catch(X){let O=X;if(O.name==="AbortError")return{success:!1,llmContent:"File search aborted",displayContent:"⚠️ 文件搜索被用户中止",error:{type:"execution_error",message:"操作被中止"}};return{success:!1,llmContent:`Search failed: ${O.message}`,displayContent:`❌ 搜索失败: ${O.message}`,error:{type:"execution_error",message:O.message,details:O}}}},version:"2.0.0",category:"搜索工具",tags:["file","search","glob","pattern","wildcard"],extractSignatureContent:($)=>$.pattern,abstractPermissionRule:()=>"*"});async function a7($,b,w,V){let W=V.getIgnorePatterns(),Q=[],Z=!1;return await new Promise((Y,J)=>{if(w.signal.aborted){J(m1("文件搜索被用户中止"));return}let X=l7.stream(b,{cwd:$,dot:!0,followSymbolicLinks:!1,unique:!0,caseSensitiveMatch:w.caseSensitive,objectMode:!0,stats:!0,onlyFiles:!w.includeDirectories,ignore:W}),O=!1,G=null,B=()=>{if(G){if(w.signal.removeEventListener)w.signal.removeEventListener("abort",G);else if("onabort"in w.signal)w.signal.onabort=null;G=null}},q=()=>{if(!O)O=!0,Z=!0,X.destroy(),B(),Y({matches:Q,wasTruncated:Z})},A=(K)=>{if(w.signal.aborted){if(!O)O=!0,X.destroy(m1("文件搜索被用户中止"));return}if(Q.length>=w.maxResults){q();return}let U=K.path.replace(/\\/g,"/"),F=s7($,U);if(V.shouldIgnore(U))return;let _=K.stats?K.stats.isDirectory():!1;if(_&&V.shouldIgnoreDirectory(U))return;let D=K.stats&&K.stats.isFile()?K.stats.size:void 0,I=K.stats?K.stats.mtime.toISOString():void 0;if(Q.push({path:F,relative_path:U,is_directory:_,size:D,modified:I}),Q.length>=w.maxResults)q()};if(X.on("data",A),G=()=>{if(!O)O=!0,B(),X.destroy(m1("文件搜索被用户中止"))},w.signal.addEventListener)w.signal.addEventListener("abort",G);else if("onabort"in w.signal)w.signal.onabort=G;X.once("error",(K)=>{if(!O)O=!0,B(),J(K)}),X.once("end",()=>{if(!O)O=!0,B(),Y({matches:Q,wasTruncated:Z})})})}function o7($){return $.sort((b,w)=>{if(b.is_directory!==w.is_directory)return b.is_directory?1:-1;if(b.modified&&w.modified)return new Date(w.modified).getTime()-new Date(b.modified).getTime();return b.relative_path.localeCompare(w.relative_path)})}function t7($){let{search_path:b,pattern:w,total_matches:V,returned_matches:W,truncated:Q}=$,Z;if(Q)Z=`✅ 在 ${b} 中找到至少 ${V} 个匹配 "${w}" 的文件(已截断)`,Z+=`
|
|
840
|
+
\uD83D\uDCCB 显示前 ${W} 个结果`;else Z=`✅ 在 ${b} 中找到 ${V} 个匹配 "${w}" 的文件`;return Z}import{execSync as i1,spawn as l1}from"child_process";import{existsSync as vb}from"fs";import{readdir as e7,readFile as $6}from"fs/promises";import{join as p4,relative as b6}from"path";import w6 from"picomatch";import{z as r$}from"zod";function V6(){let{platform:$,arch:b}=process,w={"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"},V=`${$}-${b}`,W=w[V];if(!W)return null;let Q=p4(process.cwd(),"vendor","ripgrep",W);if(vb(Q))return Q;try{let Z=new URL("../../../../vendor/ripgrep/"+W,import.meta.url).pathname;if(vb(Z))return Z}catch{}return null}function d4(){try{let b=process.platform==="win32"?"where rg":"command -v rg 2>/dev/null || which rg 2>/dev/null",w=i1(b,{encoding:"utf8",stdio:["pipe","pipe","ignore"]}).split(/\r?\n/)[0].trim();if(w)return w}catch{}let $=V6();if($&&vb($))return $;try{let b=I0("@vscode/ripgrep");if(b?.rgPath&&vb(b.rgPath))return b.rgPath}catch{}return null}async function W6($){try{return i1("git rev-parse --git-dir",{cwd:$,stdio:"ignore"}),!0}catch{return!1}}function Q6(){try{return i1("grep --version",{stdio:"ignore"}),!0}catch{return!1}}async function Z6($,b,w,V){let W=d4();if(!W)throw Error("ripgrep not available");return new Promise((Q,Z)=>{let Y=l1(W,$,{stdio:["pipe","pipe","pipe"]}),J="",X="";Y.stdout.on("data",(G)=>{J+=G.toString()}),Y.stderr.on("data",(G)=>{X+=G.toString()}),Y.on("close",(G)=>{Q({stdout:J,stderr:X,exitCode:G||0})}),Y.on("error",(G)=>{Z(G)});let O=()=>{Y.kill("SIGTERM"),Z(Error("搜索被用户中止"))};w.addEventListener("abort",O),Y.on("close",()=>{w.removeEventListener("abort",O)})})}async function Y6($,b,w,V){let W=["grep","-n"];if(w.caseInsensitive)W.push("-i");if(w.contextLines!==void 0)W.push(`-C${w.contextLines}`);if(W.push("-e",$),w.glob)W.push("--",w.glob);return new Promise((Q,Z)=>{let Y=l1("git",W,{cwd:b,stdio:["pipe","pipe","pipe"]}),J="",X="";Y.stdout.on("data",(G)=>{J+=G.toString()}),Y.stderr.on("data",(G)=>{X+=G.toString()}),Y.on("close",(G)=>{Q({stdout:J,stderr:X,exitCode:G||0})}),Y.on("error",(G)=>{Z(G)});let O=()=>{Y.kill("SIGTERM"),Z(Error("搜索被用户中止"))};V.addEventListener("abort",O),Y.on("close",()=>{V.removeEventListener("abort",O)})})}async function J6($,b,w,V){let W=["-rn"];if(w.caseInsensitive)W.push("-i");if(w.contextLines!==void 0)W.push(`-C${w.contextLines}`);for(let Q of W0)W.push("--exclude-dir="+Q.replace(/^\./,""));return W.push("-e",$,b),new Promise((Q,Z)=>{let Y=l1("grep",W,{stdio:["pipe","pipe","pipe"]}),J="",X="";Y.stdout.on("data",(G)=>{J+=G.toString()}),Y.stderr.on("data",(G)=>{X+=G.toString()}),Y.on("close",(G)=>{Q({stdout:J,stderr:X,exitCode:G||0})}),Y.on("error",(G)=>{Z(G)});let O=()=>{Y.kill("SIGTERM"),Z(Error("搜索被用户中止"))};V.addEventListener("abort",O),Y.on("close",()=>{V.removeEventListener("abort",O)})})}async function X6($,b,w,V){let W=[],Q=new RegExp($,w.caseInsensitive?"gi":"g"),Z=await O6(b,V),Y=0;for(let J of Z){if(V.throwIfAborted(),u4(J))continue;if(w.glob&&!G6(J,w.glob))continue;try{(await $6(J,"utf-8")).split(`
|
|
841
|
+
`).forEach((G,B)=>{if(Q.test(G))W.push({file_path:b6(b,J),line_number:B+1,content:G})}),Y++}catch(X){}}return{matches:W,totalFiles:Y}}async function O6($,b){let w=[];async function V(W){b.throwIfAborted();try{let Q=await e7(W,{withFileTypes:!0});for(let Z of Q){b.throwIfAborted();let Y=p4(W,Z.name);if(Z.isDirectory()){if(!u4(Y))await V(Y)}else if(Z.isFile())w.push(Y)}}catch(Q){}}return await V($),w}function u4($){for(let b of W0)if($.includes(b))return!0;return!1}function G6($,b){return w6(b)($)}function B6($){let b=[];if($.case_insensitive)b.push("-i");if($.multiline)b.push("-U","--multiline-dotall");switch($.output_mode){case"files_with_matches":b.push("-l");break;case"count":b.push("-c");break;case"content":if($.line_numbers)b.push("-n");break}if($.context!==void 0&&$.output_mode==="content")b.push("-C",$.context.toString());else{if($.context_before!==void 0&&$.output_mode==="content")b.push("-B",$.context_before.toString());if($.context_after!==void 0&&$.output_mode==="content")b.push("-A",$.context_after.toString())}if($.type)b.push("--type",$.type);for(let w of W0)b.push("--glob",`!${w}/**`);if($.glob)b.push("--glob",$.glob);if($.head_limit!==void 0){let w=($.offset??0)+$.head_limit;b.push("-m",w.toString())}return b.push($.pattern),b.push($.path),b}function K6($,b){if(!$.trim())return[];let w=$.trim().split(`
|
|
842
|
+
`),V=[];switch(b){case"files_with_matches":return w.map((W)=>({file_path:W.trim()}));case"count":return w.map((W)=>{let[Q,Z]=W.split(":");return{file_path:Q,count:parseInt(Z,10)}});case"content":for(let W of w){let Q=q6(W);if(Q)V.push(Q)}return V;default:return[]}}function q6($){let b=$.indexOf(":");if(b===-1)return null;let w=$.substring(0,b),V=$.substring(b+1),W=V.indexOf(":");if(W!==-1&&/^\d+$/.test(V.substring(0,W))){let Q=parseInt(V.substring(0,W),10),Z=V.substring(W+1);return{file_path:w,line_number:Q,content:Z}}else return{file_path:w,content:V}}function C6($){let{search_pattern:b,search_path:w,output_mode:V,total_matches:W,strategy:Q}=$,Z=`✅ 在 ${w} 中搜索 "${b}"`;if(Q)Z+=`
|
|
843
|
+
\uD83D\uDD27 使用策略: ${Q}`;switch(V){case"files_with_matches":Z+=`
|
|
844
|
+
\uD83D\uDCC1 找到 ${W} 个包含匹配内容的文件`;break;case"count":Z+=`
|
|
845
|
+
\uD83D\uDD22 统计了 ${W} 个文件的匹配数量`;break;case"content":Z+=`
|
|
846
|
+
\uD83D\uDCDD 找到 ${W} 个匹配行`;break}return Z}var n1=E({name:"Grep",displayName:"内容搜索",kind:"readonly",schema:r$.object({pattern:g.pattern({description:"The regular expression pattern to search for in file contents"}),path:r$.string().optional().describe("File or directory to search in (rg PATH). Defaults to current working directory"),glob:r$.string().optional().describe('Glob pattern to filter files (e.g. "*.js", "*.{ts,tsx}") - maps to rg --glob'),type:r$.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:r$.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":r$.boolean().optional().describe("Case insensitive search (rg -i)"),"-n":r$.boolean().default(!0).describe('Show line numbers in output (rg -n). Requires output_mode: "content", ignored otherwise. Defaults to true'),"-B":g.nonNegativeInt().optional().describe('Number of lines to show before each match (rg -B). Requires output_mode: "content", ignored otherwise'),"-A":g.nonNegativeInt().optional().describe('Number of lines to show after each match (rg -A). Requires output_mode: "content", ignored otherwise'),"-C":g.nonNegativeInt().optional().describe('Number of lines to show before and after each match (rg -C). Requires output_mode: "content", ignored otherwise'),head_limit:g.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:g.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:r$.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($,b){let{pattern:w,path:V=process.cwd(),glob:W,type:Q,output_mode:Z,"-i":Y,"-n":J=!0,"-B":X,"-A":O,"-C":G,head_limit:B,offset:q,multiline:A}=$,{updateOutput:K}=b,U=b.signal??new AbortController().signal;try{K?.(`使用智能搜索策略查找模式 "${w}"...`);let F=null,_="ripgrep",D=[],I=d4();if(I)try{K?.(`\uD83D\uDE80 使用 ripgrep (${I})`);let F$=B6({pattern:w,path:V,glob:W,type:Q,output_mode:Z,case_insensitive:Y??!1,line_numbers:J,context_before:X,context_after:O,context:G,head_limit:B,offset:q,multiline:A??!1});F=await Z6(F$,Z,U,K),_="ripgrep"}catch{K?.("⚠️ ripgrep 失败,尝试降级策略..."),F=null}if(!F&&await W6(V))try{K?.("\uD83D\uDCE6 使用 git grep"),F=await Y6(w,V,{caseInsensitive:Y??!1,glob:W,contextLines:G},U),_="git-grep"}catch{K?.("⚠️ git grep 失败,继续尝试其他策略..."),F=null}if(!F&&Q6())try{K?.("\uD83D\uDD27 使用系统 grep"),F=await J6(w,V,{caseInsensitive:Y??!1,contextLines:G},U),_="system-grep"}catch{K?.("⚠️ 系统 grep 失败,使用纯 JavaScript 实现..."),F=null}if(!F)K?.("\uD83D\uDCA1 使用纯 JavaScript 搜索实现"),D=(await X6(w,V,{caseInsensitive:Y??!1,glob:W,multiline:A??!1},U)).matches,_="fallback",F={stdout:"",stderr:"",exitCode:0};else D=K6(F.stdout,Z);let N=D.length;if(q!==void 0&&q>0)D=D.slice(q);if(B!==void 0&&D.length>B)D=D.slice(0,B);let M={search_pattern:w,search_path:V,output_mode:Z,case_insensitive:Y??!1,total_matches:D.length,original_total:N,offset:q,head_limit:B,strategy:_,exit_code:F?.exitCode};if(F&&F.exitCode!==0&&F.stderr)return{success:!1,llmContent:`Search execution failed: ${F.stderr}`,displayContent:`❌ 搜索执行失败: ${F.stderr}`,error:{type:"execution_error",message:F.stderr}};let j=C6(M);return{success:!0,llmContent:D,displayContent:j,metadata:M}}catch(F){let _=F;if(_.name==="AbortError")return{success:!1,llmContent:"Search aborted",displayContent:"⚠️ 搜索被用户中止",error:{type:"execution_error",message:"操作被中止"}};return{success:!1,llmContent:`Search failed: ${_.message}`,displayContent:`❌ 搜索失败: ${_.message}`,error:{type:"execution_error",message:_.message,details:_}}}},version:"3.0.0",category:"搜索工具",tags:["search","grep","ripgrep","regex","text","fallback"],extractSignatureContent:($)=>$.pattern,abstractPermissionRule:()=>"*"});import{spawn as D6}from"child_process";import{randomUUID as j6}from"crypto";import{z as s1}from"zod";import{execSync as A6}from"child_process";import{existsSync as _$,mkdtempSync as U6,writeFileSync as F6}from"fs";import{tmpdir as H6}from"os";import{join as e0}from"path";var Tb=z("Tool");class d${static instance=null;capabilities=null;settings={};constructor(){}static getInstance(){if(!d$.instance)d$.instance=new d$;return d$.instance}static resetInstance(){d$.instance=null}configure($){this.settings={...$}}getCapabilities(){if(this.capabilities)return this.capabilities;return this.capabilities=this.detectCapabilities(),this.capabilities}detectCapabilities(){let $=process.platform;if($==="linux")return this.detectLinuxCapabilities();else if($==="darwin")return this.detectMacOSCapabilities();return{available:!1,type:"none",features:{fileSystemIsolation:!1,networkIsolation:!1,processIsolation:!1}}}detectLinuxCapabilities(){try{let $=A6("bwrap --version 2>/dev/null",{encoding:"utf-8"}).trim();return Tb.debug(`[SandboxExecutor] Detected bubblewrap: ${$}`),{available:!0,type:"bubblewrap",version:$,features:{fileSystemIsolation:!0,networkIsolation:!0,processIsolation:!0}}}catch{return Tb.debug("[SandboxExecutor] bubblewrap not available on Linux"),{available:!1,type:"none",features:{fileSystemIsolation:!1,networkIsolation:!1,processIsolation:!1}}}}detectMacOSCapabilities(){try{if(_$("/usr/bin/sandbox-exec"))return Tb.debug("[SandboxExecutor] Detected macOS sandbox-exec (Seatbelt)"),{available:!0,type:"seatbelt",version:"macOS built-in",features:{fileSystemIsolation:!0,networkIsolation:!0,processIsolation:!0}}}catch{Tb.debug("[SandboxExecutor] sandbox-exec not available on macOS")}return{available:!1,type:"none",features:{fileSystemIsolation:!1,networkIsolation:!1,processIsolation:!1}}}isEnabled(){return this.settings.enabled===!0}canUseSandbox(){return this.isEnabled()&&this.getCapabilities().available}wrapCommand($,b){if(!this.canUseSandbox())return $;let w=this.getCapabilities();if(w.type==="bubblewrap")return this.wrapWithBubblewrap($,b);else if(w.type==="seatbelt")return this.wrapWithSeatbelt($,b);return $}wrapWithBubblewrap($,b){let w=[];if(w.push("--ro-bind /usr /usr"),w.push("--ro-bind /bin /bin"),_$("/lib"))w.push("--ro-bind /lib /lib");if(_$("/lib64"))w.push("--ro-bind /lib64 /lib64");if(_$("/etc/resolv.conf"))w.push("--ro-bind /etc/resolv.conf /etc/resolv.conf");if(_$("/etc/hosts"))w.push("--ro-bind /etc/hosts /etc/hosts");if(_$("/etc/ssl"))w.push("--ro-bind /etc/ssl /etc/ssl");if(_$("/etc/ca-certificates"))w.push("--ro-bind /etc/ca-certificates /etc/ca-certificates");if(w.push("--proc /proc"),w.push("--dev /dev"),w.push("--tmpfs /tmp"),w.push(`--bind ${b.workDir} ${b.workDir}`),w.push(`--chdir ${b.workDir}`),b.allowedWritePaths){for(let Q of b.allowedWritePaths)if(_$(Q)&&Q!==b.workDir)w.push(`--bind ${Q} ${Q}`)}if(b.allowedReadPaths){for(let Q of b.allowedReadPaths)if(_$(Q))w.push(`--ro-bind ${Q} ${Q}`)}let V=process.env.HOME;if(V){let Q=e0(V,".nvm");if(_$(Q))w.push(`--ro-bind ${Q} ${Q}`);let Z=e0(V,".npm");if(_$(Z))w.push(`--bind ${Z} ${Z}`);let Y=e0(V,".pnpm");if(_$(Y))w.push(`--bind ${Y} ${Y}`)}if(!b.allowNetwork)w.push("--unshare-net");w.push("--unshare-user"),w.push("--unshare-pid"),w.push("--unshare-uts"),w.push("--unshare-cgroup"),w.push("--die-with-parent"),w.push("--new-session");let W=$.replace(/'/g,"'\\''");return`bwrap ${w.join(" ")} -- /bin/bash -c '${W}'`}wrapWithSeatbelt($,b){let w=this.generateSeatbeltProfile(b),V=U6(e0(H6(),"sandbox-")),W=e0(V,"sandbox.sb");F6(W,w,"utf-8");let Q=$.replace(/'/g,"'\\''");return`sandbox-exec -f '${W}' /bin/bash -c '${Q}'; EXIT_CODE=$?; rm -rf '${V}'; exit $EXIT_CODE`}generateSeatbeltProfile($){let b=[];b.push("(version 1)"),b.push("(deny default)"),b.push("(allow process-exec)"),b.push("(allow process-fork)"),b.push("(allow signal)"),b.push("(allow sysctl-read)"),b.push("(allow mach-lookup)"),b.push("(allow mach-register)"),b.push("(allow ipc-posix-shm)"),b.push("(allow file-read-metadata)"),b.push('(allow file-read* (subpath "/usr"))'),b.push('(allow file-read* (subpath "/bin"))'),b.push('(allow file-read* (subpath "/sbin"))'),b.push('(allow file-read* (subpath "/Library"))'),b.push('(allow file-read* (subpath "/System"))'),b.push('(allow file-read* (subpath "/private/var/db"))'),b.push('(allow file-read* (subpath "/private/etc"))'),b.push('(allow file-read* (subpath "/dev"))'),b.push('(allow file-read* (subpath "/var"))'),b.push('(allow file-read* (subpath "/opt/homebrew"))'),b.push('(allow file-read* (subpath "/usr/local"))');let w=process.env.HOME;if(w)b.push(`(allow file-read* (subpath "${w}/.nvm"))`),b.push(`(allow file-read* (subpath "${w}/.npm"))`),b.push(`(allow file-read* (subpath "${w}/.pnpm"))`),b.push(`(allow file-read* (subpath "${w}/.config"))`),b.push(`(allow file-write* (subpath "${w}/.npm"))`),b.push(`(allow file-write* (subpath "${w}/.pnpm"))`);if(b.push(`(allow file-read* (subpath "${$.workDir}"))`),b.push(`(allow file-write* (subpath "${$.workDir}"))`),$.allowedReadPaths)for(let V of $.allowedReadPaths)b.push(`(allow file-read* (subpath "${V}"))`);if($.allowedWritePaths)for(let V of $.allowedWritePaths)b.push(`(allow file-write* (subpath "${V}"))`);if(b.push('(allow file-read* (subpath "/private/tmp"))'),b.push('(allow file-write* (subpath "/private/tmp"))'),b.push('(allow file-read* (subpath "/tmp"))'),b.push('(allow file-write* (subpath "/tmp"))'),$.allowNetwork!==!1)b.push("(allow network*)");else b.push("(allow network-outbound (remote unix-socket))");return b.join(`
|
|
847
|
+
`)}buildExecutionOptions($,b){let w={workDir:$,allowedReadPaths:[],allowedWritePaths:[],allowNetwork:!0};if(b){if(b.allowLocalBinding===!1)w.allowNetwork=!1}let V=process.env.HOME;if(V)w.allowedReadPaths?.push(V);return w}}function D0(){return d$.getInstance()}class u${static instance=null;settings={};constructor(){}static getInstance(){if(!u$.instance)u$.instance=new u$;return u$.instance}static resetInstance(){u$.instance=null}configure($){this.settings={...$},D0().configure($)}getSettings(){return{...this.settings}}isEnabled(){return this.settings.enabled===!0}shouldAutoAllowBash(){return this.isEnabled()&&this.settings.autoAllowBashIfSandboxed===!0}isCommandExcluded($){if(!this.settings.excludedCommands||this.settings.excludedCommands.length===0)return!1;let b=this.extractCommandName($);return this.settings.excludedCommands.some((w)=>b===w||$.startsWith(w+" "))}allowsUnsandboxedCommands(){return this.settings.allowUnsandboxedCommands===!0}checkCommand($){let{command:b,dangerouslyDisableSandbox:w}=$;if(!this.isEnabled())return{allowed:!0,reason:"Sandbox is disabled"};if(this.isCommandExcluded(b))return{allowed:!0,reason:"Command is in excluded list",isExcluded:!0};if(w)if(this.allowsUnsandboxedCommands())return{allowed:!1,reason:"Command requests unsandboxed execution",requiresPermission:!0};else return{allowed:!1,reason:"Unsandboxed commands are not allowed"};return{allowed:!0,reason:"Command will run in sandbox"}}shouldIgnoreFileViolation($){if(!this.settings.ignoreViolations?.file)return!1;return this.settings.ignoreViolations.file.some((b)=>{if(b.includes("*"))return new RegExp("^"+b.replace(/\*/g,".*")+"$").test($);return $.startsWith(b)})}shouldIgnoreNetworkViolation($){if(!this.settings.ignoreViolations?.network)return!1;return this.settings.ignoreViolations.network.some((b)=>{if(b.includes("*"))return new RegExp("^"+b.replace(/\*/g,".*")+"$").test($);return $===b||$.startsWith(b)})}getNetworkSettings(){return this.settings.network||{}}allowsLocalBinding(){return this.settings.network?.allowLocalBinding===!0}isUnixSocketAllowed($){let b=this.settings.network;if(!b)return!1;if(b.allowAllUnixSockets)return!0;if(b.allowUnixSockets&&b.allowUnixSockets.length>0)return b.allowUnixSockets.includes($);return!1}extractCommandName($){return $.trim().split(/\s+/)[0]||""}wrapCommandForSandbox($,b){if(!this.isEnabled())return $;let w=D0();if(!w.canUseSandbox())return $;let V=b||process.cwd(),W=w.buildExecutionOptions(V,this.settings.network);return w.wrapCommand($,W)}getCapabilities(){return D0().getCapabilities()}}function j0(){return u$.getInstance()}import{spawn as _6}from"child_process";import{randomUUID as R6}from"crypto";class A${static instance=null;processes=new Map;static getInstance(){if(!A$.instance)A$.instance=new A$;return A$.instance}startBackgroundProcess($){let b=`bash_${R6()}`,w={};for(let[Q,Z]of Object.entries({...process.env,...$.env,BLADE_CLI:"1"}))if(Z!==void 0)w[Q]=Z;let V=_6("bash",["-c",$.command],{cwd:$.cwd||process.cwd(),env:w,stdio:["ignore","pipe","pipe"]}),W={id:b,command:$.command,sessionId:$.sessionId,cwd:$.cwd,env:$.env,process:V,pid:V.pid,status:"running",startTime:Date.now(),pendingStdout:"",pendingStderr:""};return V.stdout?.setEncoding("utf8"),V.stderr?.setEncoding("utf8"),V.stdout?.on("data",(Q)=>{W.pendingStdout+=Q.toString()}),V.stderr?.on("data",(Q)=>{W.pendingStderr+=Q.toString()}),V.on("close",(Q,Z)=>{W.status=W.status==="killed"?"killed":"exited",W.exitCode=Q,W.signal=Z,W.endTime=Date.now(),W.process=void 0}),V.on("error",(Q)=>{W.status="error",W.errorMessage=Q.message,W.endTime=Date.now(),W.process=void 0,W.pendingStderr+=`
|
|
848
|
+
[error] ${Q.message}`}),this.processes.set(b,W),W}consumeOutput($){let b=this.processes.get($);if(!b)return;let w={id:b.id,command:b.command,status:b.status,stdout:b.pendingStdout,stderr:b.pendingStderr,exitCode:b.exitCode,signal:b.signal,pid:b.pid,startedAt:b.startTime,endedAt:b.endTime,errorMessage:b.errorMessage};return b.pendingStdout="",b.pendingStderr="",w}getProcess($){return this.processes.get($)}kill($){let b=this.processes.get($);if(!b)return;if(b.status!=="running"||!b.process)return{success:!1,alreadyExited:!0,status:b.status,pid:b.pid,exitCode:b.exitCode,signal:b.signal};if(!b.process.kill("SIGTERM"))return{success:!1,alreadyExited:!1,status:b.status,pid:b.pid,exitCode:b.exitCode,signal:b.signal};return b.status="killed",b.endTime=Date.now(),b.process=void 0,{success:!0,alreadyExited:!1,status:b.status,pid:b.pid,exitCode:b.exitCode,signal:b.signal}}killAll(){for(let[$,b]of this.processes)if(b.status==="running"&&b.process)try{b.process.kill("SIGTERM"),b.status="killed",b.endTime=Date.now(),b.process=void 0}catch{}this.processes.clear()}}var kb={maxLines:30,maxChars:3000,keepHead:10,keepTail:10,summarize:!0},Q0={maxLines:100,maxChars:1e4,keepHead:40,keepTail:40,summarize:!0},g4={maxLines:200,maxChars:20000,keepHead:80,keepTail:80,summarize:!1},E6={maxLines:150,maxChars:15000,keepHead:50,keepTail:50,summarize:!0},L6=[{pattern:/^git\s+(rm|add)\s+(-r|--cached|-rf|-f)?\s*/i,config:kb,summaryTemplate:($)=>`Successfully processed ${$} files`},{pattern:/^(npm|pnpm|yarn|bun)\s+(install|i|add|remove|uninstall)/i,config:kb,summaryTemplate:($)=>`Package operation completed (${$} lines of output)`},{pattern:/^(npm|pnpm|yarn|bun)\s+(run|exec)\s+(build|compile|bundle)/i,config:Q0,summaryTemplate:($)=>`Build completed (${$} lines of output)`},{pattern:/^(npm|pnpm|yarn|bun)\s+(run|exec)\s+(test|lint|check)/i,config:g4},{pattern:/^git\s+(status|branch|remote)/i,config:Q0},{pattern:/^git\s+(log|diff|show)/i,config:g4},{pattern:/^(ls|dir|tree)\s+/i,config:Q0,summaryTemplate:($)=>`Listed ${$} items`},{pattern:/^find\s+/i,config:Q0,summaryTemplate:($)=>`Found ${$} matches`},{pattern:/^(grep|rg|ag)\s+/i,config:Q0,summaryTemplate:($)=>`Found ${$} matching lines`},{pattern:/^(docker|podman)\s+(build|pull|push)/i,config:kb,summaryTemplate:($)=>`Docker operation completed (${$} lines)`},{pattern:/^(pip|pip3|poetry|pipenv)\s+(install|uninstall)/i,config:kb,summaryTemplate:($)=>`Python package operation completed (${$} lines)`},{pattern:/^(cargo|rustup)\s+(build|install|update)/i,config:Q0,summaryTemplate:($)=>`Rust operation completed (${$} lines)`},{pattern:/^(go)\s+(build|get|mod)/i,config:Q0,summaryTemplate:($)=>`Go operation completed (${$} lines)`}];class I${static getConfigForCommand($){for(let{pattern:b,config:w,summaryTemplate:V}of L6)if(b.test($))return{config:w,summaryTemplate:V};return{config:E6}}static truncate($,b){let{config:w,summaryTemplate:V}=I$.getConfigForCommand(b);return I$.truncateWithConfig($,w,V)}static truncateWithConfig($,b,w){let V=$.length,W=$.split(`
|
|
849
|
+
`),Q=W.length;if(Q<=b.maxLines&&V<=b.maxChars)return{content:$,truncated:!1,originalLines:Q,originalChars:V};let Z=W.slice(0,b.keepHead),Y=W.slice(-b.keepTail),J=Q-b.keepHead-b.keepTail,X=Z.join(`
|
|
850
|
+
`);if(X+=`
|
|
850
851
|
|
|
851
|
-
... (${
|
|
852
|
+
... (${J} lines truncated, showing first ${b.keepHead} and last ${b.keepTail} of ${Q} total) ...
|
|
852
853
|
|
|
853
|
-
`,
|
|
854
|
-
`),
|
|
854
|
+
`,X+=Y.join(`
|
|
855
|
+
`),X.length>b.maxChars){let G=Math.floor(b.maxChars/2)-50,B=X.slice(0,G),q=X.slice(-G);X=`${B}
|
|
855
856
|
|
|
856
|
-
... (content truncated to ${
|
|
857
|
+
... (content truncated to ${b.maxChars} chars) ...
|
|
857
858
|
|
|
858
|
-
${
|
|
859
|
+
${q}`}let O=b.summarize&&w?w(Q,V):void 0;if(O)X+=`
|
|
859
860
|
|
|
860
|
-
[Summary: ${
|
|
861
|
-
`).length} lines`);if(
|
|
862
|
-
`).length} lines`);
|
|
863
|
-
`).length>
|
|
864
|
-
`).length,chars:$.length,words:$.split(/\s+/).filter(Boolean).length}}}var
|
|
861
|
+
[Summary: ${O}]`;return{content:X,truncated:!0,originalLines:Q,originalChars:V,summary:O}}static truncateForLLM($,b,w){let V=I$.truncate($,w),W=I$.truncate(b,w),Q;if(V.truncated||W.truncated){let Z=[];if(V.truncated)Z.push(`stdout: ${V.originalLines} lines → ${V.content.split(`
|
|
862
|
+
`).length} lines`);if(W.truncated)Z.push(`stderr: ${W.originalLines} lines → ${W.content.split(`
|
|
863
|
+
`).length} lines`);Q=`Output truncated: ${Z.join(", ")}`}return{stdout:V.content,stderr:W.content,truncationInfo:Q}}static shouldTruncate($,b){let{config:w}=I$.getConfigForCommand(b);return $.split(`
|
|
864
|
+
`).length>w.maxLines||$.length>w.maxChars}static getStats($){return{lines:$.split(`
|
|
865
|
+
`).length,chars:$.length,words:$.split(/\s+/).filter(Boolean).length}}}var r1=E({name:"Bash",displayName:"Bash Command",kind:"execute",schema:s1.object({command:g.command({description:"Bash command to execute"}),timeout:g.timeout(1000,300000,30000),cwd:s1.string().optional().describe("Working directory (optional; applies only to this command). To persist, use cd"),env:g.environment(),run_in_background:s1.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.
|
|
865
866
|
|
|
866
867
|
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.
|
|
867
868
|
|
|
@@ -877,53 +878,53 @@ Before executing commands:
|
|
|
877
878
|
* cd "/Users/name/My Documents" (correct)
|
|
878
879
|
* cd /Users/name/My Documents (incorrect - will fail)
|
|
879
880
|
* python "/path/with spaces/script.py" (correct)
|
|
880
|
-
* 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($,
|
|
881
|
-
`+`\uD83C\uDD94 进程 ID: ${
|
|
882
|
-
`+`\uD83D\uDCA1 Bash ID: ${
|
|
883
|
-
`+"⚠️ 使用 TaskOutput/KillShell 管理后台进程";return{success:!0,llmContent:{command:$,background:!0,pid:
|
|
884
|
-
输出: ${
|
|
885
|
-
错误: ${
|
|
886
|
-
输出: ${
|
|
887
|
-
错误: ${
|
|
888
|
-
输出: ${
|
|
889
|
-
错误: ${
|
|
890
|
-
输出: ${
|
|
891
|
-
错误: ${
|
|
892
|
-
⏱️ 执行时间: ${
|
|
893
|
-
\uD83D\uDCCA 退出码: ${
|
|
894
|
-
⚡ 信号: ${
|
|
881
|
+
* 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($,b){let{command:w,timeout:V=30000,cwd:W,env:Q,run_in_background:Z=!1}=$,{updateOutput:Y}=b,J=b.signal??new AbortController().signal;try{let X=j0(),O=X.checkCommand({command:w});if(!O.allowed){if(O.requiresPermission)return{success:!1,llmContent:`Command requires permission: ${O.reason}`,displayContent:"⚠️ Command requires user permission",error:{type:"permission_denied",message:O.reason||"Permission required"}};return{success:!1,llmContent:`Command blocked by sandbox: ${O.reason}`,displayContent:"\uD83D\uDD12 Command blocked by sandbox",error:{type:"permission_denied",message:O.reason||"Blocked by sandbox"}}}let G=W||process.cwd(),B=X.wrapCommandForSandbox(w,G);if(X.isEnabled()&&B!==w)Y?.(`\uD83D\uDD12 Executing in sandbox: ${w}`);else Y?.(`Executing Bash command: ${w}`);if(Z)return N6(B,W,Q);if(s$())return Y?.("通过 IDE 终端执行命令..."),S6(B,W,Q,V,J,Y);else return M6(B,W,Q,V,J,Y)}catch(X){let O=X;if(O.name==="AbortError")return{success:!1,llmContent:"Command execution aborted",displayContent:"⚠️ 命令执行被用户中止",error:{type:"execution_error",message:"Operation aborted"}};return{success:!1,llmContent:`Command execution failed: ${O.message}`,displayContent:`❌ 命令执行失败: ${O.message}`,error:{type:"execution_error",message:O.message,details:O}}}},version:"2.0.0",category:"命令工具",tags:["bash","shell","non-interactive","event-driven"],extractSignatureContent:($)=>{return $.command.trim()},abstractPermissionRule:($)=>{let w=$.command.trim().split(/\s+/);if(w.length===1)return w[0];if(["run","exec","test","start","build","dev"].includes(w[1])){if(w.length===2)return`${w[0]} ${w[1]}`;return`${w[0]} ${w[1]} *`}if(w.length===2)return`${w[0]} ${w[1]}`;return`${w[0]} ${w[1]} *`}});function N6($,b,w){let W=A$.getInstance().startBackgroundProcess({command:$,sessionId:j6(),cwd:b||process.cwd(),env:w}),Z=`后台启动命令: ${$.length>30?`${$.substring(0,30)}...`:$}`,Y={command:$,background:!0,pid:W.pid??0,bash_id:W.id,shell_id:W.id,message:"命令已在后台启动",summary:Z},J=`✅ 命令已在后台启动
|
|
882
|
+
`+`\uD83C\uDD94 进程 ID: ${W.pid}
|
|
883
|
+
`+`\uD83D\uDCA1 Bash ID: ${W.id}
|
|
884
|
+
`+"⚠️ 使用 TaskOutput/KillShell 管理后台进程";return{success:!0,llmContent:{command:$,background:!0,pid:W.pid,bash_id:W.id,shell_id:W.id},displayContent:J,metadata:Y}}async function S6($,b,w,V,W,Q){let Z=Date.now();try{let J=await _4().execute($,{cwd:b||process.cwd(),env:w,timeout:V,signal:W,onOutput:(K)=>{Q?.(K)}}),X=Date.now()-Z;if(W.aborted||J.error==="Command was aborted"||J.error==="Command was terminated")return{success:!1,llmContent:"Command execution aborted by user",displayContent:`⚠️ 命令执行被用户中止
|
|
885
|
+
输出: ${J.stdout}
|
|
886
|
+
错误: ${J.stderr}`,error:{type:"execution_error",message:"操作被中止"},metadata:{command:$,aborted:!0,stdout:J.stdout,stderr:J.stderr,execution_time:X}};if(J.error==="Command timed out")return{success:!1,llmContent:`Command execution timed out (${V}ms)`,displayContent:`⏱️ 命令执行超时 (${V}ms)
|
|
887
|
+
输出: ${J.stdout}
|
|
888
|
+
错误: ${J.stderr}`,error:{type:"timeout_error",message:"命令执行超时"},metadata:{command:$,timeout:!0,stdout:J.stdout,stderr:J.stderr,execution_time:X}};let O=$.length>30?`${$.substring(0,30)}...`:$,G=J.exitCode===0?`执行命令成功 (${X}ms): ${O}`:`执行命令完成 (退出码 ${J.exitCode}, ${X}ms): ${O}`,B={command:$,execution_time:X,exit_code:J.exitCode,stdout_length:J.stdout.length,stderr_length:J.stderr.length,has_stderr:J.stderr.length>0,acp_mode:!0,summary:G},q=m4({stdout:J.stdout,stderr:J.stderr,command:$,execution_time:X,exit_code:J.exitCode,signal:null}),A=I$.truncateForLLM(J.stdout.trim(),J.stderr.trim(),$);return{success:J.success,llmContent:{stdout:A.stdout,stderr:A.stderr,execution_time:X,exit_code:J.exitCode,...A.truncationInfo&&{truncation_info:A.truncationInfo}},displayContent:q,metadata:B}}catch(Y){let J=Y,X=Date.now()-Z;return{success:!1,llmContent:`Command execution failed: ${J.message}`,displayContent:`❌ 命令执行失败: ${J.message}`,error:{type:"execution_error",message:J.message,details:J},metadata:{command:$,execution_time:X,error:J.message}}}}async function M6($,b,w,V,W,Q){return new Promise((Z)=>{let Y=Date.now(),J="",X="",O=!1,G=D6("bash",["-c",$],{cwd:b||process.cwd(),env:{...process.env,...w,BLADE_CLI:"1"},stdio:["pipe","pipe","pipe"]});G.stdout.on("data",(A)=>{J+=A.toString()}),G.stderr.on("data",(A)=>{X+=A.toString()});let B=setTimeout(()=>{O=!0,G.kill("SIGTERM"),setTimeout(()=>{if(!G.killed)G.kill("SIGKILL")},1000)},V),q=()=>{G.kill("SIGTERM"),clearTimeout(B)};if(W.addEventListener)W.addEventListener("abort",q);else if("onabort"in W)W.onabort=q;G.on("close",(A,K)=>{if(clearTimeout(B),W.removeEventListener)W.removeEventListener("abort",q);else if("onabort"in W)W.onabort=null;let U=Date.now()-Y;if(O){Z({success:!1,llmContent:`Command execution timed out (${V}ms)`,displayContent:`⏱️ 命令执行超时 (${V}ms)
|
|
889
|
+
输出: ${J}
|
|
890
|
+
错误: ${X}`,error:{type:"timeout_error",message:"命令执行超时"},metadata:{command:$,timeout:!0,stdout:J,stderr:X,execution_time:U}});return}if(W.aborted){Z({success:!1,llmContent:"Command execution aborted by user",displayContent:`⚠️ 命令执行被用户中止
|
|
891
|
+
输出: ${J}
|
|
892
|
+
错误: ${X}`,error:{type:"execution_error",message:"操作被中止"},metadata:{command:$,aborted:!0,stdout:J,stderr:X,execution_time:U}});return}let F=$.length>30?`${$.substring(0,30)}...`:$,_=A===0?`执行命令成功 (${U}ms): ${F}`:`执行命令完成 (退出码 ${A}, ${U}ms): ${F}`,D={command:$,execution_time:U,exit_code:A,signal:K,stdout_length:J.length,stderr_length:X.length,has_stderr:X.length>0,summary:_},I=m4({stdout:J,stderr:X,command:$,execution_time:U,exit_code:A,signal:K}),N=I$.truncateForLLM(J.trim(),X.trim(),$);Z({success:!0,llmContent:{stdout:N.stdout,stderr:N.stderr,execution_time:U,exit_code:A,signal:K,...N.truncationInfo&&{truncation_info:N.truncationInfo}},displayContent:I,metadata:D})}),G.on("error",(A)=>{if(clearTimeout(B),W.removeEventListener)W.removeEventListener("abort",q);else if("onabort"in W)W.onabort=null;Z({success:!1,llmContent:`Command execution failed: ${A.message}`,displayContent:`❌ 命令执行失败: ${A.message}`,error:{type:"execution_error",message:A.message,details:A}})})})}function m4($){let{stdout:b,stderr:w,command:V,execution_time:W,exit_code:Q,signal:Z}=$,Y=`✅ Bash 命令执行完成: ${V}`;if(Y+=`
|
|
893
|
+
⏱️ 执行时间: ${W}ms`,Y+=`
|
|
894
|
+
\uD83D\uDCCA 退出码: ${Q??"N/A"}`,Z)Y+=`
|
|
895
|
+
⚡ 信号: ${Z}`;if(b&&b.trim())Y+=`
|
|
895
896
|
\uD83D\uDCE4 输出:
|
|
896
|
-
${
|
|
897
|
+
${b.trim()}`;if(w&&w.trim())Y+=`
|
|
897
898
|
⚠️ 错误输出:
|
|
898
|
-
${
|
|
899
|
+
${w.trim()}`;return Y}import{z as c4}from"zod";var a1=E({name:"KillShell",displayName:"终止后台 Shell",kind:"execute",schema:c4.object({shell_id:c4.string().min(1).describe("Background Shell ID to terminate")}),description:{short:"Kills a running background bash shell by its ID",long:`
|
|
899
900
|
- Kills a running background bash shell by its ID
|
|
900
901
|
- Takes a shell_id parameter identifying the shell to kill
|
|
901
902
|
- Returns a success or failure status
|
|
902
903
|
- Use this tool when you need to terminate a long-running shell
|
|
903
904
|
- Shell IDs can be found using the /tasks command
|
|
904
|
-
`},async execute($,
|
|
905
|
+
`},async execute($,b){let V=A$.getInstance().kill($.shell_id);if(!V)return{success:!1,llmContent:`Shell not found: ${$.shell_id}`,displayContent:`❌ 未找到 Shell: ${$.shell_id}`,error:{type:"execution_error",message:"Shell ID 不存在或已清理"}};if(!V.success&&!V.alreadyExited)return{success:!1,llmContent:`Failed to terminate Shell: ${$.shell_id}`,displayContent:`❌ 无法终止 Shell (${$.shell_id})`,error:{type:"execution_error",message:"发送终止信号失败"},metadata:{...V}};let W=V.alreadyExited?`Shell ${$.shell_id} 已经处于 ${V.status} 状态`:`已向 Shell ${$.shell_id} 发送终止信号`;return{success:!0,llmContent:{shell_id:$.shell_id,status:V.status,already_exited:V.alreadyExited,pid:V.pid,exit_code:V.exitCode,signal:V.signal},displayContent:V.alreadyExited?`ℹ️ ${W}`:`✂️ ${W}`,metadata:{...V}}},version:"1.0.0",category:"命令工具",tags:["bash","shell","terminate"],extractSignatureContent:($)=>$.shell_id,abstractPermissionRule:()=>"*"});import{z as a$}from"zod";import{nanoid as k6}from"nanoid";import{promises as t}from"node:fs";import*as d from"node:path";import{fileURLToPath as z6}from"node:url";import{nanoid as y6}from"nanoid";var i4={proposal:"proposal.md",spec:"spec.md",requirements:"requirements.md",design:"design.md",tasks:"tasks.md",meta:".meta.json"},Z0={SPECS:"specs",CHANGES:"changes",ARCHIVE:"archive",STEERING:"steering",SPEC_DELTA:"specs"},Y0={CONSTITUTION:"constitution.md",PRODUCT:"product.md",TECH:"tech.md",STRUCTURE:"structure.md"},mY=["init","requirements","design","tasks","implementation","done"],$b={init:["requirements"],requirements:["design","tasks"],design:["tasks"],tasks:["implementation"],implementation:["done","tasks"],done:[]},R$={init:"初始化",requirements:"需求定义",design:"架构设计",tasks:"任务分解",implementation:"实现中",done:"已完成"},l4={init:"proposal",requirements:"requirements",design:"design",tasks:"tasks",implementation:"tasks",done:null};var v6=z6(import.meta.url),T6=d.dirname(v6),n4=d.join(T6,"templates");class bb{workspaceRoot;bladeDir;constructor($){this.workspaceRoot=$,this.bladeDir=d.join($,".blade")}getSpecsDir(){return d.join(this.bladeDir,Z0.SPECS)}getChangesDir(){return d.join(this.bladeDir,Z0.CHANGES)}getArchiveDir(){return d.join(this.bladeDir,Z0.ARCHIVE)}getSteeringDir(){return d.join(this.bladeDir,Z0.STEERING)}getChangePath($){return d.join(this.getChangesDir(),$)}getChangeFilePath($,b){return d.join(this.getChangePath($),i4[b])}async initializeDirectories(){await t.mkdir(this.getChangesDir(),{recursive:!0,mode:493})}async createChangeDir($){let b=this.getChangePath($);return await t.mkdir(b,{recursive:!0,mode:493}),await t.mkdir(d.join(b,Z0.SPEC_DELTA),{recursive:!0,mode:493}),b}async readFile($){try{return await t.readFile($,"utf-8")}catch(b){if(b.code==="ENOENT")return null;throw b}}async writeFile($,b){let w=d.dirname($);await t.mkdir(w,{recursive:!0,mode:493}),await t.writeFile($,b,"utf-8")}async fileExists($){try{return await t.access($),!0}catch{return!1}}async dirExists($){try{return(await t.stat($)).isDirectory()}catch{return!1}}createMetadata($,b){let w=new Date().toISOString();return{id:y6(),name:$,description:b,phase:"init",createdAt:w,updatedAt:w,tasks:[]}}async readMetadata($){let b=this.getChangeFilePath($,"meta"),w=await this.readFile(b);if(!w)return null;try{return JSON.parse(w)}catch{return null}}async writeMetadata($,b){let w=this.getChangeFilePath($,"meta");b.updatedAt=new Date().toISOString(),await this.writeFile(w,JSON.stringify(b,null,2))}async updatePhase($,b){let w=await this.readMetadata($);if(!w)return null;return w.phase=b,await this.writeMetadata($,w),w}async readSpecFile($,b){let w=this.getChangeFilePath($,b);return this.readFile(w)}async writeSpecFile($,b,w){let V=this.getChangeFilePath($,b);await this.writeFile(V,w);let W=await this.readMetadata($);if(W)await this.writeMetadata($,W)}async getPhaseContent($,b){let w=l4[b];if(!w)return null;return this.readSpecFile($,w)}async readSteeringContext(){let $=this.getSteeringDir(),[b,w,V,W]=await Promise.all([this.readFile(d.join($,Y0.CONSTITUTION)),this.readFile(d.join($,Y0.PRODUCT)),this.readFile(d.join($,Y0.TECH)),this.readFile(d.join($,Y0.STRUCTURE))]);return{constitution:b||void 0,product:w||void 0,tech:V||void 0,structure:W||void 0}}async writeSteeringFile($,b){let w=d.join(this.getSteeringDir(),Y0[$]);await this.writeFile(w,b)}async hasSteeringDocs(){let $=this.getSteeringDir();if(!await this.dirExists($))return!1;return(await t.readdir($)).length>0}async listActiveChanges(){let $=this.getChangesDir();if(!await this.dirExists($))return[];return(await t.readdir($,{withFileTypes:!0})).filter((w)=>w.isDirectory()).map((w)=>w.name)}async listArchivedChanges(){let $=this.getArchiveDir();if(!await this.dirExists($))return[];return(await t.readdir($,{withFileTypes:!0})).filter((w)=>w.isDirectory()).map((w)=>w.name)}async changeExists($){return this.dirExists(this.getChangePath($))}async archiveChange($){let b=this.getChangePath($),w=d.join(this.getArchiveDir(),$);await t.mkdir(d.dirname(w),{recursive:!0,mode:493}),await t.rename(b,w)}async restoreChange($){let b=d.join(this.getArchiveDir(),$),w=this.getChangePath($);await t.rename(b,w)}async listSpecDomains(){let $=this.getSpecsDir();if(!await this.dirExists($))return[];return(await t.readdir($,{withFileTypes:!0})).filter((w)=>w.isDirectory()).map((w)=>w.name)}async readAuthorativeSpec($){let b=d.join(this.getSpecsDir(),$,"spec.md");return this.readFile(b)}async writeAuthorativeSpec($,b){let w=d.join(this.getSpecsDir(),$,"spec.md");await this.writeFile(w,b)}async mergeSpecDeltas($){let b=d.join(this.getChangePath($),Z0.SPEC_DELTA);if(!await this.dirExists(b))return[];let w=[],V=await t.readdir(b,{withFileTypes:!0});for(let W of V){if(!W.isDirectory())continue;let Q=d.join(b,W.name,"spec.md"),Z=await this.readFile(Q);if(Z){let Y=await this.readAuthorativeSpec(W.name),J=Y?`${Y}
|
|
905
906
|
|
|
906
907
|
---
|
|
907
908
|
|
|
908
909
|
<!-- Merged from ${$} -->
|
|
909
910
|
|
|
910
|
-
${
|
|
911
|
+
${Z}`:Z;await this.writeAuthorativeSpec(W.name,J),w.push(W.name)}}return w}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 b=bb.TEMPLATE_NAMES[$];if(!b)return null;let w=d.join(n4,b);return this.readFile(w)}async readSteeringTemplate($){let b=bb.STEERING_TEMPLATE_NAMES[$],w=d.join(n4,b);return this.readFile(w)}fillTemplate($,b){let w=$;for(let[V,W]of Object.entries(b))w=w.replace(new RegExp(`\\{\\{${V}\\}\\}`,"g"),W);return w}async createFromTemplate($,b,w){let V=await this.readTemplate(b);if(!V)return null;let W=this.fillTemplate(V,{name:$,createdAt:new Date().toISOString(),updatedAt:new Date().toISOString(),...w});return await this.writeSpecFile($,b,W),W}async createSteeringFromTemplate($,b={}){let w=await this.readSteeringTemplate($);if(!w)return null;let V=this.fillTemplate(w,{createdAt:new Date().toISOString(),...b});return await this.writeSteeringFile($,V),V}async initializeSteeringDocs(){let $=[],b=this.getSteeringDir();for(let[w,V]of Object.entries(Y0)){let W=d.join(b,V);if(!await this.fileExists(W))await this.createSteeringFromTemplate(w),$.push(V)}return $}}var o1=z("Spec");class i{static instance=null;fileManager=null;state={currentSpec:null,specPath:null,isActive:!1,recentSpecs:[],steeringContext:null};stateChangeCallbacks=[];constructor(){}static getInstance(){if(!i.instance)i.instance=new i;return i.instance}static resetInstance(){i.instance=null}onStateChange($){return this.stateChangeCallbacks.push($),()=>{let b=this.stateChangeCallbacks.indexOf($);if(b>-1)this.stateChangeCallbacks.splice(b,1)}}notifyStateChange(){for(let $ of this.stateChangeCallbacks)$(this.state)}updateState($){this.state={...this.state,...$},this.notifyStateChange()}async initialize($){if(this.fileManager){o1.debug("SpecManager already initialized, skipping...");return}this.fileManager=new bb($),await this.fileManager.initializeDirectories();let b=await this.fileManager.readSteeringContext();this.updateState({steeringContext:b}),o1.debug("SpecManager initialized successfully")}getFileManager(){if(!this.fileManager)throw Error("SpecManager not initialized. Call initialize() first.");return this.fileManager}getState(){return{...this.state}}getCurrentSpec(){return this.state.currentSpec}isActive(){return this.state.isActive}getSteeringContext(){return this.state.steeringContext}async getSteeringContextString(){let $=this.state.steeringContext;if(!$)return null;let b=[];if($.constitution)b.push(`## Constitution (Project Governance)
|
|
911
912
|
|
|
912
|
-
${$.constitution}`);if($.product)
|
|
913
|
+
${$.constitution}`);if($.product)b.push(`## Product Vision
|
|
913
914
|
|
|
914
|
-
${$.product}`);if($.tech)
|
|
915
|
+
${$.product}`);if($.tech)b.push(`## Technology Stack
|
|
915
916
|
|
|
916
|
-
${$.tech}`);if($.structure)
|
|
917
|
+
${$.tech}`);if($.structure)b.push(`## Code Structure
|
|
917
918
|
|
|
918
|
-
${$.structure}`);return
|
|
919
|
+
${$.structure}`);return b.length>0?b.join(`
|
|
919
920
|
|
|
920
921
|
---
|
|
921
922
|
|
|
922
|
-
`):null}async createSpec($,
|
|
923
|
+
`):null}async createSpec($,b){let w=this.getFileManager();if(await w.changeExists($))return{success:!1,message:`Spec "${$}" already exists`,error:"SPEC_EXISTS"};let V=await w.createChangeDir($),W=w.createMetadata($,b);await w.writeMetadata($,W);let Q=this.generateProposalTemplate($,b);await w.writeSpecFile($,"proposal",Q);let Z=this.state.recentSpecs.filter((Y)=>Y!==$);return Z.unshift($),this.updateState({currentSpec:W,specPath:V,isActive:!0,recentSpecs:Z.slice(0,10)}),{success:!0,message:`Spec "${$}" created successfully`,data:{spec:W,path:V}}}async loadSpec($){let b=this.getFileManager(),w=await b.readMetadata($);if(!w)return{success:!1,message:`Spec "${$}" not found`,error:"SPEC_NOT_FOUND"};let V=b.getChangePath($),W=this.state.recentSpecs.filter((Q)=>Q!==$);return W.unshift($),this.updateState({currentSpec:w,specPath:V,isActive:!0,recentSpecs:W.slice(0,10)}),{success:!0,message:`Spec "${$}" loaded successfully`,data:{spec:w,path:V}}}closeSpec(){this.updateState({currentSpec:null,specPath:null,isActive:!1})}exitSpecMode(){this.closeSpec()}async transitionPhase($){let b=this.getCurrentSpec();if(!b)return{success:!1,message:"No active spec",error:"NO_ACTIVE_SPEC"};if(!$b[b.phase].includes($))return{success:!1,message:`Cannot transition from "${b.phase}" to "${$}"`,error:"INVALID_TRANSITION"};let W=await this.getFileManager().updatePhase(b.name,$);if(!W)return{success:!1,message:"Failed to update phase",error:"UPDATE_FAILED"};if(this.updateState({currentSpec:W}),$==="done")o1.info("Spec completed");return{success:!0,message:`Transitioned to "${$}" phase`,data:{spec:W,phase:$}}}getAllowedTransitions(){let $=this.getCurrentSpec();if(!$)return[];return $b[$.phase]}async addTask($,b,w){let V=this.getCurrentSpec();if(!V)return{success:!1,message:"No active spec",error:"NO_ACTIVE_SPEC"};let W={id:k6(8),title:$,description:b,status:"pending",dependencies:w?.dependencies||[],affectedFiles:w?.affectedFiles||[],complexity:w?.complexity||"medium"},Q={...V,tasks:[...V.tasks,W],updatedAt:new Date().toISOString()};return await this.getFileManager().writeMetadata(V.name,Q),this.updateState({currentSpec:Q}),{success:!0,message:`Task "${$}" added`,data:{task:W}}}async updateTaskStatus($,b){let w=this.getCurrentSpec();if(!w)return{success:!1,message:"No active spec",error:"NO_ACTIVE_SPEC"};let V=w.tasks.find((Y)=>Y.id===$);if(!V)return{success:!1,message:`Task "${$}" not found`,error:"TASK_NOT_FOUND"};let W={...V,status:b,completedAt:b==="completed"?new Date().toISOString():V.completedAt},Q=w.tasks.map((Y)=>Y.id===$?W:Y),Z={...w,tasks:Q,currentTaskId:b==="in_progress"?$:w.currentTaskId===$?void 0:w.currentTaskId,updatedAt:new Date().toISOString()};return await this.getFileManager().writeMetadata(w.name,Z),this.updateState({currentSpec:Z}),{success:!0,message:`Task status updated to "${b}"`,data:{task:W}}}getNextTask(){let $=this.getCurrentSpec();if(!$)return null;return $.tasks.find((b)=>{if(b.status!=="pending")return!1;return b.dependencies.every((w)=>{return $.tasks.find((W)=>W.id===w)?.status==="completed"})})||null}getTaskProgress(){let $=this.getCurrentSpec();if(!$||$.tasks.length===0)return{total:0,completed:0,percentage:0};let b=$.tasks.length,w=$.tasks.filter((W)=>W.status==="completed").length,V=Math.round(w/b*100);return{total:b,completed:w,percentage:V}}async listSpecs($){let b=this.getFileManager(),w=[],V=await b.listActiveChanges();for(let W of V){let Q=await b.readMetadata(W);if(!Q)continue;if($?.phase&&Q.phase!==$.phase)continue;if($?.tags&&!$.tags.some((Y)=>Q.tags?.includes(Y)))continue;if($?.query&&!Q.name.toLowerCase().includes($.query.toLowerCase())&&!Q.description.toLowerCase().includes($.query.toLowerCase()))continue;let Z=this.calculateTaskProgress(Q.tasks);w.push({name:Q.name,description:Q.description,phase:Q.phase,updatedAt:Q.updatedAt,path:b.getChangePath(W),isArchived:!1,taskProgress:Z})}if($?.includeArchived){let W=await b.listArchivedChanges();for(let Q of W)w.push({name:Q,description:"(archived)",phase:"done",updatedAt:"",path:`${b.getArchiveDir()}/${Q}`,isArchived:!0,taskProgress:{total:0,completed:0}})}return w.sort((W,Q)=>{if(W.isArchived!==Q.isArchived)return W.isArchived?1:-1;return new Date(Q.updatedAt).getTime()-new Date(W.updatedAt).getTime()}),w}async archiveCurrentSpec(){let $=this.getCurrentSpec();if(!$)return{success:!1,message:"No active spec",error:"NO_ACTIVE_SPEC"};let b=this.getFileManager();return await b.mergeSpecDeltas($.name),await b.updatePhase($.name,"done"),await b.archiveChange($.name),this.closeSpec(),{success:!0,message:`Spec "${$.name}" archived successfully`,data:{spec:{...$,phase:"done"}}}}async validateCurrentSpec(){let $=this.getCurrentSpec();if(!$)return{valid:!1,phase:"init",completeness:{proposal:!1,spec:!1,requirements:!1,design:!1,tasks:!1},issues:[{severity:"error",file:"meta",message:"No active spec"}],suggestions:["Create a new spec with /spec proposal <name>"]};let b=this.getFileManager(),w=[],V=[],[W,Q,Z,Y,J]=await Promise.all([b.readSpecFile($.name,"proposal"),b.readSpecFile($.name,"spec"),b.readSpecFile($.name,"requirements"),b.readSpecFile($.name,"design"),b.readSpecFile($.name,"tasks")]),X={proposal:!!W,spec:!!Q,requirements:!!Z,design:!!Y,tasks:!!J};if($.phase==="requirements"&&!X.requirements)w.push({severity:"warning",file:"requirements",message:"Requirements document is missing"}),V.push("Generate requirements using EARS format");if($.phase==="design"&&!X.design)w.push({severity:"warning",file:"design",message:"Design document is missing"}),V.push("Create architecture diagrams and API contracts");if($.phase==="tasks"&&$.tasks.length===0)w.push({severity:"warning",file:"tasks",message:"No tasks defined"}),V.push("Break down the spec into atomic tasks");if($.phase==="implementation"){let O=this.getTaskProgress();if(O.completed<O.total)w.push({severity:"info",file:"tasks",message:`${O.total-O.completed} tasks remaining`})}return{valid:w.filter((O)=>O.severity==="error").length===0,phase:$.phase,completeness:X,issues:w,suggestions:V}}generateProposalTemplate($,b){return`# ${$}
|
|
923
924
|
|
|
924
925
|
## Summary
|
|
925
926
|
|
|
926
|
-
${
|
|
927
|
+
${b}
|
|
927
928
|
|
|
928
929
|
## Background
|
|
929
930
|
|
|
@@ -953,7 +954,7 @@ ${V}
|
|
|
953
954
|
<!-- What needs to be clarified before proceeding? -->
|
|
954
955
|
|
|
955
956
|
1.
|
|
956
|
-
`}calculateTaskProgress($){let
|
|
957
|
+
`}calculateTaskProgress($){let b=$.length,w=$.filter((V)=>V.status==="completed").length;return{total:b,completed:w}}}var s4=E({name:"AddTask",displayName:"Add Task",kind:"write",schema:a$.object({title:a$.string().min(1).describe("Brief title of the task"),description:a$.string().min(1).describe("Detailed description of what needs to be done"),complexity:a$.enum(["low","medium","high"]).optional().default("medium").describe("Estimated complexity of the task"),affectedFiles:a$.array(a$.string()).optional().default([]).describe("List of files that will be modified by this task"),dependencies:a$.array(a$.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.
|
|
957
958
|
|
|
958
959
|
## Task Structure
|
|
959
960
|
|
|
@@ -988,16 +989,16 @@ AddTask({
|
|
|
988
989
|
- Tasks are tracked in .meta.json, not tasks.md
|
|
989
990
|
- Use UpdateTaskStatus to mark tasks as completed
|
|
990
991
|
- Use GetSpecContext to see current tasks and progress
|
|
991
|
-
`},async execute($,
|
|
992
|
+
`},async execute($,b){let{title:w,description:V,complexity:W,affectedFiles:Q,dependencies:Z}=$,Y=i.getInstance();if(!Y.getCurrentSpec())return{success:!1,llmContent:"No active spec. Use EnterSpecMode to start a new spec project, or use the /spec command to load an existing one.",displayContent:"❌ No active spec",error:{type:"validation_error",message:"No active spec project"}};let X=await Y.addTask(w,V,{complexity:W,affectedFiles:Q,dependencies:Z});if(!X.success)return{success:!1,llmContent:`Failed to add task: ${X.message}`,displayContent:`❌ Failed to add task: ${X.message}`,error:{type:"execution_error",message:X.message}};let O=X.data?.task,G=Y.getTaskProgress();return{success:!0,llmContent:`✅ Task added: "${w}"
|
|
992
993
|
|
|
993
|
-
`+`\uD83D\uDCCB Task ID: ${
|
|
994
|
-
`+`\uD83D\uDCCA Complexity: ${
|
|
995
|
-
`+`\uD83D\uDCC1 Affected files: ${
|
|
996
|
-
`+`\uD83D\uDD17 Dependencies: ${
|
|
994
|
+
`+`\uD83D\uDCCB Task ID: ${O?.id}
|
|
995
|
+
`+`\uD83D\uDCCA Complexity: ${W}
|
|
996
|
+
`+`\uD83D\uDCC1 Affected files: ${Q?.length?Q.join(", "):"None specified"}
|
|
997
|
+
`+`\uD83D\uDD17 Dependencies: ${Z?.length?Z.join(", "):"None"}
|
|
997
998
|
|
|
998
|
-
`+`\uD83D\uDCC8 Progress: ${
|
|
999
|
+
`+`\uD83D\uDCC8 Progress: ${G.completed}/${G.total} tasks (${G.percentage}%)
|
|
999
1000
|
|
|
1000
|
-
`+"\uD83D\uDCA1 Use AddTask to add more tasks, or use /spec apply to start implementation.",displayContent:`✅ Added task: ${
|
|
1001
|
+
`+"\uD83D\uDCA1 Use AddTask to add more tasks, or use /spec apply to start implementation.",displayContent:`✅ Added task: ${w} (ID: ${O?.id})`,metadata:{taskId:O?.id,title:w,complexity:W,affectedFiles:Q,dependencies:Z,totalTasks:G.total}}}});import{z as t1}from"zod";var r4=E({name:"EnterSpecMode",displayName:"Enter Spec Mode",kind:"readonly",schema:t1.object({featureName:t1.string().min(1).describe("The name of the feature/change (used as directory name)"),description:t1.string().min(1).describe("Brief description of what this feature/change does")}),description:{short:"Enter Spec-Driven Development mode for complex features",long:`Use this tool to enter Spec mode when you need to implement a complex feature that benefits from structured planning.
|
|
1001
1002
|
|
|
1002
1003
|
## Spec-Driven Development (SDD)
|
|
1003
1004
|
|
|
@@ -1055,18 +1056,18 @@ For simpler planning needs, consider using EnterPlanMode instead.
|
|
|
1055
1056
|
├── tasks.md # Task breakdown
|
|
1056
1057
|
└── .meta.json # Metadata and progress
|
|
1057
1058
|
\`\`\`
|
|
1058
|
-
`},async execute($,
|
|
1059
|
+
`},async execute($,b){let{featureName:w,description:V}=$;if(!/^[a-zA-Z0-9_-]+$/.test(w))return{success:!1,llmContent:"Invalid feature name. Use only letters, numbers, underscores, and hyphens.",displayContent:"❌ Invalid feature name",error:{type:"validation_error",message:"Feature name must be alphanumeric with underscores/hyphens only"}};if(b.confirmationHandler)try{if((await b.confirmationHandler.requestConfirmation({title:"Enter Spec Mode",message:`The assistant requests to enter Spec mode for: **${w}**
|
|
1059
1060
|
|
|
1060
|
-
Description: ${
|
|
1061
|
+
Description: ${V}
|
|
1061
1062
|
|
|
1062
1063
|
In Spec mode, the assistant will:
|
|
1063
1064
|
1. Create structured specification documents
|
|
1064
1065
|
`+`2. Guide you through Requirements → Design → Tasks → Implementation
|
|
1065
1066
|
`+`3. Track progress and maintain documentation
|
|
1066
1067
|
|
|
1067
|
-
Do you want to enter Spec mode?`,details:`Will create: .blade/changes/${
|
|
1068
|
+
Do you want to enter Spec mode?`,details:`Will create: .blade/changes/${w}/`})).approved){let Q=b.workspaceRoot||process.cwd(),Z=i.getInstance();try{await Z.initialize(Q);let Y=await Z.createSpec(w,V);if(!Y.success)return{success:!1,llmContent:`Failed to create Spec: ${Y.message}`,displayContent:`❌ Failed to create Spec: ${Y.message}`,error:{type:"execution_error",message:Y.message}};return{success:!0,llmContent:`✅ Created Spec: "${w}"
|
|
1068
1069
|
|
|
1069
|
-
`+`\uD83D\uDCC1 Location: .blade/changes/${
|
|
1070
|
+
`+`\uD83D\uDCC1 Location: .blade/changes/${w}/
|
|
1070
1071
|
|
|
1071
1072
|
You are now in SPEC MODE. Your workflow:
|
|
1072
1073
|
|
|
@@ -1088,12 +1089,12 @@ You are now in SPEC MODE. Your workflow:
|
|
|
1088
1089
|
- Use UpdateTaskStatus to track progress
|
|
1089
1090
|
- Call ExitSpecMode when done
|
|
1090
1091
|
|
|
1091
|
-
Start by asking the user for more details about their requirements.`,displayContent:`✅ Created Spec: ${
|
|
1092
|
+
Start by asking the user for more details about their requirements.`,displayContent:`✅ Created Spec: ${w}`,metadata:{approved:!0,enterSpecMode:!0,featureName:w,description:V,specPath:`.blade/changes/${w}/`}}}catch(Y){return{success:!1,llmContent:`Failed to initialize Spec: ${Y instanceof Error?Y.message:"Unknown error"}`,displayContent:"❌ Failed to initialize Spec",error:{type:"execution_error",message:Y instanceof Error?Y.message:"Initialization failed"}}}}else return{success:!0,llmContent:`⚠️ User declined to enter Spec mode.
|
|
1092
1093
|
|
|
1093
|
-
`+"Proceed with the task using regular workflow. You can use Plan mode for lighter planning, or implement directly if the task is straightforward.",displayContent:"⚠️ Spec mode declined",metadata:{approved:!1,enterSpecMode:!1}}}catch(
|
|
1094
|
+
`+"Proceed with the task using regular workflow. You can use Plan mode for lighter planning, or implement directly if the task is straightforward.",displayContent:"⚠️ Spec mode declined",metadata:{approved:!1,enterSpecMode:!1}}}catch(W){return{success:!1,llmContent:`Confirmation error: ${W instanceof Error?W.message:"Unknown error"}`,displayContent:"❌ Confirmation failed",error:{type:"execution_error",message:"Confirmation flow error"}}}return{success:!0,llmContent:`Spec mode requested for "${w}" but no interactive confirmation available.
|
|
1094
1095
|
|
|
1095
1096
|
Proceeding with spec creation. Follow the structured workflow:
|
|
1096
|
-
`+"1. Requirements → 2. Design → 3. Tasks → 4. Implementation",displayContent:`Spec mode: ${
|
|
1097
|
+
`+"1. Requirements → 2. Design → 3. Tasks → 4. Implementation",displayContent:`Spec mode: ${w} (non-interactive)`,metadata:{approved:null,enterSpecMode:!0,featureName:w,description:V}}}});import{z as e1}from"zod";var a4=E({name:"ExitSpecMode",displayName:"Exit Spec Mode",kind:"readonly",schema:e1.object({archive:e1.boolean().optional().default(!1).describe("If true, archive the spec (mark as done and move to archive)"),summary:e1.string().optional().describe("Optional summary of what was accomplished")}),description:{short:"Exit Spec mode and optionally archive the completed spec",long:`Use this tool to exit Spec-Driven Development mode.
|
|
1097
1098
|
|
|
1098
1099
|
## Options
|
|
1099
1100
|
|
|
@@ -1127,30 +1128,30 @@ ExitSpecMode({})
|
|
|
1127
1128
|
// Complete and archive
|
|
1128
1129
|
ExitSpecMode({ archive: true, summary: "Implemented OAuth2 authentication" })
|
|
1129
1130
|
\`\`\`
|
|
1130
|
-
`},async execute($,
|
|
1131
|
+
`},async execute($,b){let{archive:w,summary:V}=$,W=i.getInstance(),Q=W.getCurrentSpec();if(!Q)return{success:!1,llmContent:"No active spec to exit from.",displayContent:"❌ No active spec",error:{type:"validation_error",message:"No active spec project"}};try{let{name:Z,phase:Y}=Q,J=W.getTaskProgress();if(w&&b.confirmationHandler){let X=J.total>0&&J.completed<J.total?`
|
|
1131
1132
|
|
|
1132
|
-
⚠️ Warning: ${
|
|
1133
|
+
⚠️ Warning: ${J.total-J.completed} tasks are not completed.`:"";if(!(await b.confirmationHandler.requestConfirmation({title:"Archive Spec",message:`Archive spec "${Z}"?
|
|
1133
1134
|
|
|
1134
|
-
Phase: ${
|
|
1135
|
-
Tasks: ${
|
|
1135
|
+
Phase: ${R$[Y]}
|
|
1136
|
+
Tasks: ${J.completed}/${J.total} completed`+X,details:"This will move the spec to archive and merge any spec deltas."})).approved)return{success:!0,llmContent:"Archive cancelled. Still in Spec mode.",displayContent:"⚠️ Archive cancelled",metadata:{archived:!1,stillActive:!0}}}if(w){let X=await W.archiveCurrentSpec();if(!X.success)return{success:!1,llmContent:`Failed to archive: ${X.message}`,displayContent:"❌ Archive failed",error:{type:"execution_error",message:X.error||"Archive failed"}};return{success:!0,llmContent:`✅ Spec "${Z}" archived successfully!
|
|
1136
1137
|
|
|
1137
1138
|
`+`\uD83D\uDCCA Final Status:
|
|
1138
|
-
`+`- Phase: ${
|
|
1139
|
-
- Tasks: ${
|
|
1140
|
-
`+(
|
|
1139
|
+
`+`- Phase: ${R$[Y]}
|
|
1140
|
+
- Tasks: ${J.completed}/${J.total} completed
|
|
1141
|
+
`+(V?`- Summary: ${V}
|
|
1141
1142
|
`:"")+`
|
|
1142
|
-
\uD83D\uDCC1 Location: .blade/archive/${
|
|
1143
|
+
\uD83D\uDCC1 Location: .blade/archive/${Z}/
|
|
1143
1144
|
|
|
1144
|
-
Exited Spec mode. You can start a new spec or continue with regular work.`,displayContent:`✅ Archived: ${
|
|
1145
|
+
Exited Spec mode. You can start a new spec or continue with regular work.`,displayContent:`✅ Archived: ${Z}`,metadata:{archived:!0,featureName:Z,phase:Y,taskProgress:J,summary:V,shouldExitSpecMode:!0}}}return W.exitSpecMode(),{success:!0,llmContent:`✅ Exited Spec mode for "${Z}"
|
|
1145
1146
|
|
|
1146
1147
|
`+`\uD83D\uDCCA Current Status:
|
|
1147
|
-
`+`- Phase: ${
|
|
1148
|
-
- Tasks: ${
|
|
1148
|
+
`+`- Phase: ${R$[Y]}
|
|
1149
|
+
- Tasks: ${J.completed}/${J.total} completed
|
|
1149
1150
|
|
|
1150
|
-
`+`\uD83D\uDCC1 Spec preserved at: .blade/changes/${
|
|
1151
|
-
`+`\uD83D\uDCA1 Resume later with: /spec load ${
|
|
1151
|
+
`+`\uD83D\uDCC1 Spec preserved at: .blade/changes/${Z}/
|
|
1152
|
+
`+`\uD83D\uDCA1 Resume later with: /spec load ${Z}
|
|
1152
1153
|
|
|
1153
|
-
You can now work on other tasks or start a new spec.`,displayContent:`✅ Exited: ${
|
|
1154
|
+
You can now work on other tasks or start a new spec.`,displayContent:`✅ Exited: ${Z} (preserved)`,metadata:{archived:!1,featureName:Z,phase:Y,taskProgress:J,shouldExitSpecMode:!0}}}catch(Z){return{success:!1,llmContent:`Exit failed: ${Z instanceof Error?Z.message:"Unknown error"}`,displayContent:"❌ Exit failed",error:{type:"execution_error",message:Z instanceof Error?Z.message:"Exit error"}}}}});import{z as $w}from"zod";var o4=E({name:"GetSpecContext",displayName:"Get Spec Context",kind:"readonly",schema:$w.object({includeFiles:$w.boolean().optional().default(!0).describe("Whether to include file contents in the context"),includeSteering:$w.boolean().optional().default(!0).describe("Whether to include steering documents")}),description:{short:"Get the current Spec context including metadata, files, and steering docs",long:`Use this tool to retrieve the complete context of the current Spec project.
|
|
1154
1155
|
|
|
1155
1156
|
## What's Included
|
|
1156
1157
|
|
|
@@ -1176,8 +1177,8 @@ You can now work on other tasks or start a new spec.`,displayContent:`✅ Exited
|
|
|
1176
1177
|
|
|
1177
1178
|
[File contents and steering docs follow...]
|
|
1178
1179
|
\`\`\`
|
|
1179
|
-
`},async execute($,
|
|
1180
|
-
`),displayContent:`\uD83D\uDCCB Spec context: ${
|
|
1180
|
+
`},async execute($,b){let{includeFiles:w,includeSteering:V}=$,W=i.getInstance(),Q=W.getCurrentSpec();if(!Q)return{success:!1,llmContent:"No active spec. Use EnterSpecMode or /spec load <name> first.",displayContent:"❌ No active spec",error:{type:"validation_error",message:"No active spec project"}};try{let Z=W.getFileManager(),Y=[];Y.push(`# \uD83D\uDCCB Spec: ${Q.name}`),Y.push(`**Description**: ${Q.description}`),Y.push(`**Phase**: ${R$[Q.phase]} (${Q.phase})`),Y.push(`**Created**: ${new Date(Q.createdAt).toLocaleString()}`),Y.push(`**Updated**: ${new Date(Q.updatedAt).toLocaleString()}`);let J=W.getTaskProgress();if(J.total>0){if(Y.push(`**Tasks**: ${J.completed}/${J.total} completed (${J.percentage}%)`),Q.currentTaskId){let G=Q.tasks.find((B)=>B.id===Q.currentTaskId);if(G)Y.push(`**Current Task**: ${G.title}`)}let O=Q.tasks.filter((G)=>G.status==="blocked");if(O.length>0)Y.push(`**⚠️ Blocked**: ${O.map((G)=>G.title).join(", ")}`)}if(Y.push(""),V){let O=await W.getSteeringContextString();if(O)Y.push("---"),Y.push("## \uD83D\uDCD6 Steering Documents"),Y.push(""),Y.push(O),Y.push("")}if(w){let O=["proposal","spec","requirements","design","tasks"];for(let G of O){let B=await Z.readSpecFile(Q.name,G);if(B)Y.push("---"),Y.push(`## \uD83D\uDCC4 ${G}.md`),Y.push(""),Y.push(B),Y.push("")}}if(Q.tasks.length>0){Y.push("---"),Y.push("## \uD83D\uDCDD Task List"),Y.push("");for(let O of Q.tasks){let G={pending:"⏳",in_progress:"\uD83D\uDD04",completed:"✅",blocked:"\uD83D\uDEAB",skipped:"⏭️"}[O.status];if(Y.push(`- ${G} **${O.title}** (${O.complexity}) - ${O.status}`),O.description)Y.push(` ${O.description}`)}}return{success:!0,llmContent:Y.join(`
|
|
1181
|
+
`),displayContent:`\uD83D\uDCCB Spec context: ${Q.name} (${Q.phase})`,metadata:{featureName:Q.name,phase:Q.phase,taskProgress:J,filesIncluded:w,steeringIncluded:V}}}catch(Z){return{success:!1,llmContent:`Failed to get spec context: ${Z instanceof Error?Z.message:"Unknown error"}`,displayContent:"❌ Failed to get spec context",error:{type:"execution_error",message:Z instanceof Error?Z.message:"Read error"}}}}});import{z as t4}from"zod";function f6($){switch($){case"requirements":return`## Requirements Phase Instructions
|
|
1181
1182
|
|
|
1182
1183
|
1. Use UpdateSpec to write requirements.md
|
|
1183
1184
|
2. Use EARS format:
|
|
@@ -1214,7 +1215,7 @@ You can now work on other tasks or start a new spec.`,displayContent:`✅ Exited
|
|
|
1214
1215
|
The spec has been marked as complete. Next steps:
|
|
1215
1216
|
1. The spec will be archived to .blade/archive/
|
|
1216
1217
|
2. Any spec deltas will be merged to .blade/specs/
|
|
1217
|
-
3. You can start a new spec or exit Spec mode`;default:return""}}var
|
|
1218
|
+
3. You can start a new spec or exit Spec mode`;default:return""}}var e4=E({name:"TransitionSpecPhase",displayName:"Transition Spec Phase",kind:"write",schema:t4.object({targetPhase:t4.enum(["requirements","design","tasks","implementation","done"]).describe("The phase to transition to")}),description:{short:"Transition the current Spec to a new workflow phase",long:`Use this tool to move the Spec project to the next phase in the workflow.
|
|
1218
1219
|
|
|
1219
1220
|
## Workflow Phases
|
|
1220
1221
|
|
|
@@ -1243,9 +1244,9 @@ Before transitioning, ensure:
|
|
|
1243
1244
|
\`\`\`
|
|
1244
1245
|
TransitionSpecPhase({ targetPhase: "design" })
|
|
1245
1246
|
\`\`\`
|
|
1246
|
-
`},async execute($,
|
|
1247
|
+
`},async execute($,b){let{targetPhase:w}=$,V=i.getInstance(),W=V.getCurrentSpec();if(!W)return{success:!1,llmContent:"No active spec. Use EnterSpecMode or /spec load <name> first.",displayContent:"❌ No active spec",error:{type:"validation_error",message:"No active spec project"}};let Q=$b[W.phase];if(!Q.includes(w))return{success:!1,llmContent:`Cannot transition from "${W.phase}" to "${w}".
|
|
1247
1248
|
|
|
1248
|
-
Allowed transitions from ${
|
|
1249
|
+
Allowed transitions from ${W.phase}: ${Q.join(", ")||"none"}`,displayContent:"❌ Invalid phase transition",error:{type:"validation_error",message:`Invalid transition: ${W.phase} → ${w}`}};if(W.phase==="tasks"&&w==="implementation"){if(V.getTaskProgress().total===0)return{success:!1,llmContent:`❌ Cannot transition to implementation: No tasks defined!
|
|
1249
1250
|
|
|
1250
1251
|
`+`You MUST use the **AddTask** tool to add tasks before starting implementation.
|
|
1251
1252
|
|
|
@@ -1259,16 +1260,16 @@ AddTask({
|
|
|
1259
1260
|
})
|
|
1260
1261
|
\`\`\`
|
|
1261
1262
|
|
|
1262
|
-
After adding tasks, try transitioning again.`,displayContent:"❌ No tasks defined - 我需要先添加任务",error:{type:"validation_error",message:"No tasks defined. Use AddTask tool to add tasks first."}}}if(
|
|
1263
|
+
After adding tasks, try transitioning again.`,displayContent:"❌ No tasks defined - 我需要先添加任务",error:{type:"validation_error",message:"No tasks defined. Use AddTask tool to add tasks first."}}}if(w==="done"){let Z=V.getTaskProgress();if(Z.total>0&&Z.completed<Z.total){if(b.confirmationHandler){if(!(await b.confirmationHandler.requestConfirmation({title:"Incomplete Tasks",message:`⚠️ ${Z.total-Z.completed} tasks are not completed.
|
|
1263
1264
|
|
|
1264
|
-
Are you sure you want to mark this spec as done?`,details:`Completed: ${
|
|
1265
|
+
Are you sure you want to mark this spec as done?`,details:`Completed: ${Z.completed}/${Z.total}`})).approved)return{success:!1,llmContent:"User cancelled transition to done phase.",displayContent:"⚠️ Transition cancelled",error:{type:"validation_error",message:"User cancelled"}}}}}try{let Z=await V.transitionPhase(w);if(!Z.success)return{success:!1,llmContent:Z.message,displayContent:`❌ ${Z.message}`,error:{type:"execution_error",message:Z.error||"Transition failed"}};let Y=R$[W.phase],J=R$[w];return{success:!0,llmContent:`✅ Transitioned from "${Y}" to "${J}"
|
|
1265
1266
|
|
|
1266
|
-
`+
|
|
1267
|
-
\uD83D\uDCA1 Consider transitioning to "${
|
|
1267
|
+
`+f6(w),displayContent:`✅ Phase: ${Y} → ${J}`,metadata:{fromPhase:W.phase,toPhase:w,featureName:W.name}}}catch(Z){return{success:!1,llmContent:`Transition failed: ${Z instanceof Error?Z.message:"Unknown error"}`,displayContent:"❌ Transition failed",error:{type:"execution_error",message:Z instanceof Error?Z.message:"Transition error"}}}}});import{z as fb}from"zod";function I6($,b){let w=["init","requirements","design","tasks","implementation"],W={proposal:"init",requirements:"requirements",design:"design",tasks:"tasks"}[$];if(!W)return"";let Q=w.indexOf(b);if(w.indexOf(W)>Q)return`
|
|
1268
|
+
\uD83D\uDCA1 Consider transitioning to "${W}" phase using TransitionSpecPhase tool.`;switch($){case"proposal":return`
|
|
1268
1269
|
\uD83D\uDCDD Next: Define requirements in requirements.md using EARS format.`;case"requirements":return`
|
|
1269
1270
|
\uD83D\uDCDD Next: Create technical design in design.md (diagrams, API contracts).`;case"design":return`
|
|
1270
1271
|
\uD83D\uDCDD Next: Break down into tasks in tasks.md (atomic, with dependencies).`;case"tasks":return`
|
|
1271
|
-
\uD83D\uDCDD Next: Start implementation. Update task status as you progress.`;default:return""}}var
|
|
1272
|
+
\uD83D\uDCDD Next: Start implementation. Update task status as you progress.`;default:return""}}var $2=E({name:"UpdateSpec",displayName:"Update Spec",kind:"write",schema:fb.object({fileType:fb.enum(["proposal","spec","requirements","design","tasks"]).describe("The type of spec file to update"),content:fb.string().min(1).describe("The content to write to the file"),append:fb.boolean().optional().default(!1).describe("If true, append to existing content instead of replacing")}),description:{short:"Update a spec file in the current Spec project",long:`Use this tool to update spec files in the current Spec-Driven Development project.
|
|
1272
1273
|
|
|
1273
1274
|
## Available File Types
|
|
1274
1275
|
|
|
@@ -1301,14 +1302,14 @@ UpdateSpec({
|
|
|
1301
1302
|
- You must be in Spec mode (have an active spec) to use this tool
|
|
1302
1303
|
- Content overwrites existing file by default
|
|
1303
1304
|
- Use append: true to add to existing content
|
|
1304
|
-
`},async execute($,
|
|
1305
|
+
`},async execute($,b){let{fileType:w,content:V,append:W}=$,Q=i.getInstance(),Z=Q.getCurrentSpec();if(!Z)return{success:!1,llmContent:"No active spec. Use EnterSpecMode to start a new spec project, or use the /spec command to load an existing one.",displayContent:"❌ No active spec",error:{type:"validation_error",message:"No active spec project"}};try{let Y=Q.getFileManager(),J=V;if(W){let G=await Y.readSpecFile(Z.name,w);J=G?`${G}
|
|
1305
1306
|
|
|
1306
|
-
${
|
|
1307
|
-
`).length,
|
|
1307
|
+
${V}`:V}await Y.writeSpecFile(Z.name,w,J);let X=J.split(`
|
|
1308
|
+
`).length,O=J.length;return{success:!0,llmContent:`✅ Updated ${w}.md for "${Z.name}"
|
|
1308
1309
|
|
|
1309
|
-
`+`\uD83D\uDCCA Stats: ${
|
|
1310
|
+
`+`\uD83D\uDCCA Stats: ${X} lines, ${O} characters
|
|
1310
1311
|
|
|
1311
|
-
`+
|
|
1312
|
+
`+I6(w,Z.phase),displayContent:`✅ Updated ${w}.md (${X} lines)`,metadata:{featureName:Z.name,fileType:w,lines:X,chars:O,append:W}}}catch(Y){return{success:!1,llmContent:`Failed to update ${w}.md: ${Y instanceof Error?Y.message:"Unknown error"}`,displayContent:`❌ Failed to update ${w}.md`,error:{type:"execution_error",message:Y instanceof Error?Y.message:"Write error"}}}}});import{z as Ib}from"zod";var b2={pending:"⏳ 待处理",in_progress:"\uD83D\uDD04 进行中",completed:"✅ 已完成",blocked:"\uD83D\uDEAB 已阻塞",skipped:"⏭️ 已跳过"},w2=E({name:"UpdateTaskStatus",displayName:"Update Task Status",kind:"write",schema:Ib.object({taskId:Ib.string().min(1).describe("The ID of the task to update"),status:Ib.enum(["pending","in_progress","completed","blocked","skipped"]).describe("The new status for the task"),notes:Ib.string().optional().describe("Optional notes about the status change (e.g., why blocked)")}),description:{short:"Update the status of a task in the current Spec",long:`Use this tool to update the status of tasks in the current Spec project.
|
|
1312
1313
|
|
|
1313
1314
|
## Task Statuses
|
|
1314
1315
|
|
|
@@ -1339,21 +1340,21 @@ UpdateTaskStatus({
|
|
|
1339
1340
|
- Use GetSpecContext to see all tasks and their current statuses
|
|
1340
1341
|
- Only one task should be "in_progress" at a time
|
|
1341
1342
|
- Completing a task may unblock dependent tasks
|
|
1342
|
-
`},async execute($,
|
|
1343
|
+
`},async execute($,b){let{taskId:w,status:V,notes:W}=$,Q=i.getInstance(),Z=Q.getCurrentSpec();if(!Z)return{success:!1,llmContent:"No active spec. Use EnterSpecMode to start a new spec project, or use the /spec command to load an existing one.",displayContent:"❌ No active spec",error:{type:"validation_error",message:"No active spec project"}};let Y=Z.tasks.find((B)=>B.id===w);if(!Y)return{success:!1,llmContent:`Task "${w}" not found.
|
|
1343
1344
|
|
|
1344
1345
|
Available tasks:
|
|
1345
|
-
${
|
|
1346
|
-
`)||"No tasks"}`,displayContent:`❌ Task not found: ${
|
|
1346
|
+
${Z.tasks.map((B)=>`- ${B.id}: ${B.title}`).join(`
|
|
1347
|
+
`)||"No tasks"}`,displayContent:`❌ Task not found: ${w}`,error:{type:"validation_error",message:"Task not found"}};let J=await Q.updateTaskStatus(w,V);if(!J.success)return{success:!1,llmContent:`Failed to update task status: ${J.message}`,displayContent:`❌ Failed to update: ${J.message}`,error:{type:"execution_error",message:J.message}};let X=Q.getTaskProgress(),O=Q.getNextTask(),G="";if(V==="completed"&&O)G=`
|
|
1347
1348
|
|
|
1348
|
-
\uD83C\uDFAF Next task: "${
|
|
1349
|
+
\uD83C\uDFAF Next task: "${O.title}" (${O.id})`;else if(V==="completed"&&X.completed===X.total)G=`
|
|
1349
1350
|
|
|
1350
|
-
\uD83C\uDF89 All tasks completed! Use /spec archive to archive this spec.`;return{success:!0,llmContent:`✅ Updated task "${
|
|
1351
|
+
\uD83C\uDF89 All tasks completed! Use /spec archive to archive this spec.`;return{success:!0,llmContent:`✅ Updated task "${Y.title}"
|
|
1351
1352
|
|
|
1352
|
-
`+`\uD83D\uDCCB Task ID: ${
|
|
1353
|
-
`+`\uD83D\uDCCA Status: ${
|
|
1354
|
-
`+(
|
|
1353
|
+
`+`\uD83D\uDCCB Task ID: ${w}
|
|
1354
|
+
`+`\uD83D\uDCCA Status: ${b2[V]}
|
|
1355
|
+
`+(W?`\uD83D\uDCDD Notes: ${W}
|
|
1355
1356
|
`:"")+`
|
|
1356
|
-
\uD83D\uDCC8 Progress: ${
|
|
1357
|
+
\uD83D\uDCC8 Progress: ${X.completed}/${X.total} tasks (${X.percentage}%)`+G,displayContent:`✅ ${Y.title}: ${b2[V]}`,metadata:{taskId:w,title:Y.title,status:V,notes:W,progress:{completed:X.completed,total:X.total,percentage:X.percentage}}}}});import{z as P6}from"zod";var V2=E({name:"ValidateSpec",displayName:"Validate Spec",kind:"readonly",schema:P6.object({}),description:{short:"Validate the completeness and consistency of the current Spec",long:`Use this tool to check if the current Spec project is complete and ready for the next phase.
|
|
1357
1358
|
|
|
1358
1359
|
## What's Validated
|
|
1359
1360
|
|
|
@@ -1374,8 +1375,8 @@ ${J.tasks.map((O)=>`- ${O.id}: ${O.title}`).join(`
|
|
|
1374
1375
|
- To review what's missing
|
|
1375
1376
|
- Before marking spec as done
|
|
1376
1377
|
- To get improvement suggestions
|
|
1377
|
-
`},async execute($,
|
|
1378
|
-
`),displayContent:
|
|
1378
|
+
`},async execute($,b){let w=i.getInstance(),V=w.getCurrentSpec();if(!V)return{success:!1,llmContent:"No active spec. Use EnterSpecMode or /spec load <name> first.",displayContent:"❌ No active spec",error:{type:"validation_error",message:"No active spec project"}};try{let W=await w.validateCurrentSpec(),Q=[];Q.push(`# \uD83D\uDD0D Spec Validation: ${V.name}`),Q.push(""),Q.push(`**Phase**: ${R$[W.phase]}`),Q.push(`**Status**: ${W.valid?"✅ Valid":"⚠️ Has Issues"}`),Q.push(""),Q.push("## \uD83D\uDCC4 File Completeness"),Q.push("");let Z=[["proposal.md",W.completeness.proposal],["spec.md",W.completeness.spec],["requirements.md",W.completeness.requirements],["design.md",W.completeness.design],["tasks.md",W.completeness.tasks]];for(let[X,O]of Z)Q.push(`- ${O?"✅":"❌"} ${X}`);if(Q.push(""),W.issues.length>0){Q.push("## ⚠️ Issues"),Q.push("");for(let X of W.issues){let O={error:"\uD83D\uDD34",warning:"\uD83D\uDFE1",info:"\uD83D\uDD35"}[X.severity];Q.push(`- ${O} **${X.file}**: ${X.message}`)}Q.push("")}if(W.suggestions.length>0){Q.push("## \uD83D\uDCA1 Suggestions"),Q.push("");for(let X of W.suggestions)Q.push(`- ${X}`);Q.push("")}let Y=w.getTaskProgress();if(Y.total>0){Q.push("## \uD83D\uDCCA Task Progress"),Q.push(""),Q.push(`- Total: ${Y.total}`),Q.push(`- Completed: ${Y.completed}`),Q.push(`- Remaining: ${Y.total-Y.completed}`),Q.push(`- Progress: ${Y.percentage}%`),Q.push("");let X=Math.round(Y.percentage/5),O=20-X;Q.push(`[${"█".repeat(X)}${"░".repeat(O)}]`)}if(Q.push(""),Q.push("## \uD83D\uDE80 Next Steps"),Q.push(""),!W.valid)Q.push("1. Address the issues listed above"),Q.push("2. Re-run ValidateSpec to verify fixes");else{let X=w.getAllowedTransitions();if(X.length>0)Q.push(`1. Ready to transition to: ${X.map((O)=>R$[O]).join(", ")}`),Q.push("2. Use TransitionSpecPhase to proceed");else Q.push("1. All phases complete!"),Q.push("2. Use ExitSpecMode to finish and archive")}return{success:!0,llmContent:Q.join(`
|
|
1379
|
+
`),displayContent:W.valid?`✅ Spec valid: ${V.name}`:`⚠️ Spec has ${W.issues.length} issue(s)`,metadata:{valid:W.valid,phase:W.phase,completeness:W.completeness,issueCount:W.issues.length,taskProgress:Y}}}catch(W){return{success:!1,llmContent:`Validation failed: ${W instanceof Error?W.message:"Unknown error"}`,displayContent:"❌ Validation failed",error:{type:"execution_error",message:W instanceof Error?W.message:"Validation error"}}}}});var W2=[r4,$2,o4,e4,s4,w2,V2,a4];import{z as P$}from"zod";var h6=P$.object({label:P$.string().describe("The display text for this option that the user will see and select. Should be concise (1-5 words) and clearly describe the choice."),description:P$.string().describe("Explanation of what this option means or what will happen if chosen. Useful for providing context about trade-offs or implications.")}),x6=P$.object({question:P$.string().describe('The complete question to ask the user. Should be clear, specific, and end with a question mark. Example: "Which library should we use for date formatting?" If multiSelect is true, phrase it accordingly, e.g. "Which features do you want to enable?"'),header:P$.string().max(12).describe('Very short label displayed as a chip/tag (max 12 chars). Examples: "Auth method", "Library", "Approach".'),multiSelect:P$.boolean().describe("Set to true to allow the user to select multiple options instead of just one. Use when choices are not mutually exclusive."),options:P$.array(h6).min(2).max(4).describe('The available choices for this question. Must have 2-4 options. Each option should be a distinct, mutually exclusive choice (unless multiSelect is enabled). There should be no "Other" option, that will be provided automatically.')}),p6=P$.object({questions:P$.array(x6).min(1).max(4).describe("Questions to ask the user (1-4 questions)")}),Pb=E({name:"AskUserQuestion",displayName:"Ask User Question",kind:"readonly",schema:p6,description:{short:"Ask user questions to gather preferences or clarify requirements",long:`Use this tool when you need to ask the user questions during execution. This allows you to:
|
|
1379
1380
|
1. Gather user preferences or requirements
|
|
1380
1381
|
2. Clarify ambiguous instructions
|
|
1381
1382
|
3. Get decisions on implementation choices as you work
|
|
@@ -1384,9 +1385,9 @@ ${J.tasks.map((O)=>`- ${O.id}: ${O.title}`).join(`
|
|
|
1384
1385
|
Usage notes:
|
|
1385
1386
|
- Users will always be able to select "Other" to provide custom text input
|
|
1386
1387
|
- Use multiSelect: true to allow multiple answers to be selected for a question
|
|
1387
|
-
- If you recommend a specific option, make that the first option in the list and add "(Recommended)" at the end of the label`},async execute($,
|
|
1388
|
-
${Object.entries(
|
|
1389
|
-
`)}`,displayContent:"✅ 用户已回答问题",metadata:{answers:
|
|
1388
|
+
- If you recommend a specific option, make that the first option in the list and add "(Recommended)" at the end of the label`},async execute($,b){if(b.confirmationHandler)try{let w=await b.confirmationHandler.requestConfirmation({type:"askUserQuestion",kind:"readonly",message:"Please answer the following questions:",questions:$.questions});if(!w.approved)return{success:!0,llmContent:"User cancelled the question prompt without providing answers.",displayContent:"❌ 用户取消了问题",metadata:{cancelled:!0}};if(w.answers&&Object.keys(w.answers).length>0)return{success:!0,llmContent:`User answers:
|
|
1389
|
+
${Object.entries(w.answers).map(([W,Q])=>{let Z=Array.isArray(Q)?Q.join(", "):Q;return`${W}: ${Z}`}).join(`
|
|
1390
|
+
`)}`,displayContent:"✅ 用户已回答问题",metadata:{answers:w.answers}};return{success:!0,llmContent:"The question was approved but no answers were collected. This typically happens in IDE/ACP sessions where structured question UI is not available. Please ask the user directly in your response or make reasonable assumptions based on context.",displayContent:"⚠️ ACP 模式:无法收集答案",metadata:{acpMode:!0,noAnswersCollected:!0}}}catch(w){return{success:!1,llmContent:`Failed to ask user questions: ${w instanceof Error?w.message:"Unknown error"}`,displayContent:"❌ 问题显示失败",error:{type:"execution_error",message:"Failed to display questions"}}}return{success:!1,llmContent:"No confirmation handler available. Cannot ask user questions in non-interactive mode.",displayContent:"❌ 非交互模式,无法提问",error:{type:"execution_error",message:"No confirmation handler available"}}}});import{z as bw}from"zod";var ww=E({name:"Skill",displayName:"Skill",kind:"execute",schema:bw.object({skill:bw.string().describe('The skill name. E.g., "commit-message" or "code-review"'),args:bw.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
|
|
1390
1391
|
|
|
1391
1392
|
<skills_instructions>
|
|
1392
1393
|
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.
|
|
@@ -1405,20 +1406,20 @@ Important:
|
|
|
1405
1406
|
<available_skills>
|
|
1406
1407
|
|
|
1407
1408
|
</available_skills>
|
|
1408
|
-
`},async execute($,
|
|
1409
|
+
`},async execute($,b){let{skill:w}=$,V=N$();if(!V.has(w))return{success:!1,llmContent:`Skill "${w}" not found. Available skills: ${V.getAll().map((Y)=>Y.name).join(", ")||"none"}`,displayContent:`❌ Skill "${w}" not found`,error:{type:"validation_error",message:`Skill "${w}" is not registered`}};let W=await V.loadContent(w);if(!W)return{success:!1,llmContent:`Failed to load skill "${w}" content`,displayContent:`❌ Failed to load skill "${w}"`,error:{type:"execution_error",message:`Could not read SKILL.md for "${w}"`}};let Q=d6(W.metadata.name,W.instructions,W.metadata.basePath),Z=typeof W.metadata.model==="string"&&W.metadata.model!=="inherit"&&W.metadata.model.trim()!==""?W.metadata.model:void 0;return{success:!0,llmContent:Q,displayContent:`<command-message>The "${w}" skill is loading</command-message>`,metadata:{skillName:w,basePath:W.metadata.basePath,version:W.metadata.version,allowedTools:W.metadata.allowedTools,modelId:Z}}}});function d6($,b,w){return`# Skill: ${$}
|
|
1409
1410
|
|
|
1410
1411
|
You are now operating in the "${$}" skill mode. Follow the instructions below to complete the task.
|
|
1411
1412
|
|
|
1412
|
-
**Skill Base Path:** ${
|
|
1413
|
+
**Skill Base Path:** ${w}
|
|
1413
1414
|
(You can reference scripts, templates, and references relative to this path)
|
|
1414
1415
|
|
|
1415
1416
|
---
|
|
1416
1417
|
|
|
1417
|
-
${
|
|
1418
|
+
${b}
|
|
1418
1419
|
|
|
1419
1420
|
---
|
|
1420
1421
|
|
|
1421
|
-
Remember: Follow the above instructions carefully to complete the user's request.`}import{nanoid as
|
|
1422
|
+
Remember: Follow the above instructions carefully to complete the user's request.`}import{nanoid as i6}from"nanoid";import{z as O0}from"zod";import{nanoid as g6}from"nanoid";import o$ from"node:fs";import u6 from"node:os";import Q2 from"node:path";var N0=z("Agent");class J0{static instance=null;sessionsDir;cache=new Map;constructor(){this.sessionsDir=Q2.join(u6.homedir(),".blade","agents","sessions"),this.ensureDirectory()}static getInstance(){if(!J0.instance)J0.instance=new J0;return J0.instance}ensureDirectory(){if(!o$.existsSync(this.sessionsDir))o$.mkdirSync(this.sessionsDir,{recursive:!0,mode:493})}getSessionPath($){let b=$.replace(/[^a-zA-Z0-9_-]/g,"_");return Q2.join(this.sessionsDir,`${b}.json`)}saveSession($){try{let b=this.getSessionPath($.id),w=JSON.stringify($,null,2);o$.writeFileSync(b,w,"utf-8"),this.cache.set($.id,$),N0.debug(`Session saved: ${$.id}`)}catch(b){N0.warn(`Failed to save session ${$.id}:`,b)}}loadSession($){if(this.cache.has($))return this.cache.get($);try{let b=this.getSessionPath($);if(!o$.existsSync(b))return;let w=o$.readFileSync(b,"utf-8"),V=JSON.parse(w);return this.cache.set($,V),V}catch(b){N0.warn(`Failed to load session ${$}:`,b);return}}updateSession($,b){let w=this.loadSession($);if(!w)return;let V={...w,...b,lastActiveAt:Date.now()};return this.saveSession(V),V}appendMessages($,b){let w=this.loadSession($);if(!w)return;return this.updateSession($,{messages:[...w.messages,...b]})}markCompleted($,b,w){return this.updateSession($,{status:b.success?"completed":"failed",result:b,stats:w,completedAt:Date.now()})}deleteSession($){try{let b=this.getSessionPath($);if(o$.existsSync(b))o$.unlinkSync(b);return this.cache.delete($),!0}catch(b){return N0.warn(`Failed to delete session ${$}:`,b),!1}}listSessions(){try{let $=o$.readdirSync(this.sessionsDir),b=[];for(let w of $){if(!w.endsWith(".json"))continue;let V=w.replace(".json",""),W=this.loadSession(V);if(W)b.push(W)}return b.sort((w,V)=>V.lastActiveAt-w.lastActiveAt)}catch($){return N0.warn("Failed to list sessions:",$),[]}}listRunningSessions(){return this.listSessions().filter(($)=>$.status==="running")}cleanupExpiredSessions($=604800000){let b=Date.now(),w=this.listSessions(),V=0;for(let W of w){if(W.status==="running")continue;if(b-W.lastActiveAt>$){if(this.deleteSession(W.id))V++}}if(V>0)N0.info(`Cleaned up ${V} expired agent sessions`);return V}clearCache(){this.cache.clear()}}var X0=z("Agent");class M${static instance=null;runningAgents=new Map;sessionStore=J0.getInstance();constructor(){this.cleanupOrphanedSessions()}static getInstance(){if(!M$.instance)M$.instance=new M$;return M$.instance}cleanupOrphanedSessions(){let $=this.sessionStore.listSessions(),b=Date.now(),w=1800000;for(let V of $)if(V.status==="running"){let W=this.runningAgents.has(V.id),Q=b-V.lastActiveAt;if(!W||Q>1800000)X0.warn(`Cleaning up orphaned agent session: ${V.id}`),this.sessionStore.updateSession(V.id,{status:"failed",result:{success:!1,message:"",error:"Session was orphaned (process restart or timeout)"},completedAt:b})}}startBackgroundAgent($){let{config:b,bladeConfig:w,description:V,prompt:W,parentSessionId:Q,permissionMode:Z,agentId:Y,existingMessages:J}=$,X=Y||g6(),O=new AbortController,G={id:X,subagentType:b.name,description:V,prompt:W,messages:J||[],status:"running",createdAt:Date.now(),lastActiveAt:Date.now(),parentSessionId:Q};this.sessionStore.saveSession(G);let B=Date.now(),q=this.executeAgent(X,b,w,W,Q,Z,O.signal,J);return this.runningAgents.set(X,{id:X,promise:q,abortController:O,startTime:B}),q.finally(()=>{this.runningAgents.delete(X)}),X0.info(`Background agent started: ${X} (${b.name})`),X}async executeAgent($,b,w,V,W,Q,Z,Y){let J=Date.now();try{if(Z.aborted)throw Error("Agent execution was cancelled");let X=b.systemPrompt||"",O=b.model&&b.model!=="inherit"?b.model:void 0,G=await g$.create(w,{systemPrompt:X,toolWhitelist:b.tools,modelId:O}),B={messages:Y||[],userId:"subagent",sessionId:$,workspaceRoot:process.cwd(),permissionMode:Q,subagentInfo:{parentSessionId:W||"",subagentType:b.name,isSidechain:!1}},q=await G.runAgenticLoop(V,B,{signal:Z});this.sessionStore.updateSession($,{messages:B.messages});let A=Date.now()-J,K=q.success?{success:!0,message:q.finalMessage||"",agentId:$,stats:{tokens:q.metadata?.tokensUsed||0,toolCalls:q.metadata?.toolCallsCount||0,duration:A}}:{success:!1,message:"",agentId:$,error:q.error?.message||"Unknown error",stats:{duration:A}};return this.sessionStore.markCompleted($,{success:K.success,message:K.message,error:K.error},K.stats),X0.info(`Background agent completed: ${$} (success=${K.success})`),K}catch(X){let O=Date.now()-J,G=X instanceof Error?X.message:String(X);return this.sessionStore.markCompleted($,{success:!1,message:"",error:G},{duration:O}),X0.warn(`Background agent failed: ${$}`,X),{success:!1,message:"",agentId:$,error:G,stats:{duration:O}}}}getAgent($){return this.sessionStore.loadSession($)}isRunning($){return this.runningAgents.has($)}async waitForCompletion($,b=30000){let w=this.runningAgents.get($);if(!w)return this.sessionStore.loadSession($);if(b>0){let V=new Promise((Q)=>setTimeout(()=>Q("timeout"),b));if(await Promise.race([w.promise,V])==="timeout")return this.sessionStore.loadSession($)}else await w.promise;return this.sessionStore.loadSession($)}resumeAgent($,b,w,V,W,Q){let Z=this.sessionStore.loadSession($);if(!Z){X0.warn(`Cannot resume agent ${$}: session not found`);return}if(this.isRunning($)){X0.warn(`Cannot resume agent ${$}: still running`);return}return this.startBackgroundAgent({config:w,bladeConfig:V,description:Z.description,prompt:b,parentSessionId:W||Z.parentSessionId,permissionMode:Q,agentId:$,existingMessages:Z.messages})}killAgent($){let b=this.runningAgents.get($);if(!b){let w=this.sessionStore.loadSession($);if(w&&w.status==="running")this.sessionStore.updateSession($,{status:"cancelled"});return!1}return b.abortController.abort(),this.sessionStore.updateSession($,{status:"cancelled"}),X0.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($)}}import{nanoid as m6}from"nanoid";class Vw{config;bladeConfig;constructor($,b){this.config=$;this.bladeConfig=b}async execute($){let b=Date.now(),w=$.subagentSessionId??m6();try{let V=this.buildSystemPrompt($),W=this.config.model&&this.config.model!=="inherit"?this.config.model:void 0,Q=await g$.create(this.bladeConfig,{toolWhitelist:this.config.tools,modelId:W}),Z="",Y=0,J=0,X={parentSessionId:$.parentSessionId||"",subagentType:this.config.name,isSidechain:!1},O=await Q.runAgenticLoop($.prompt,{messages:[],userId:"subagent",sessionId:w,workspaceRoot:process.cwd(),permissionMode:$.permissionMode,systemPrompt:V,subagentInfo:X});if(O.success)Z=O.finalMessage||"",Y=O.metadata?.toolCallsCount||0,J=O.metadata?.tokensUsed||0;else throw Error(O.error?.message||"Subagent execution failed");let G=Date.now()-b;return{success:!0,message:Z,agentId:w,stats:{tokens:J,toolCalls:Y,duration:G}}}catch(V){let W=Date.now()-b;return{success:!1,message:"",agentId:w,error:V instanceof Error?V.message:String(V),stats:{duration:W}}}}buildSystemPrompt($){return this.config.systemPrompt||""}}import Qw from"node:fs";import hb from"node:os";import m$ from"node:path";import c6 from"yaml";var Ww=[{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
|
|
1422
1423
|
|
|
1423
1424
|
You are a specialized code exploration agent. Your job is to **directly execute searches** using the tools available to you.
|
|
1424
1425
|
|
|
@@ -1485,17 +1486,17 @@ You are a software architect specializing in implementation planning.
|
|
|
1485
1486
|
**Risks**:
|
|
1486
1487
|
- [Potential issue and mitigation]
|
|
1487
1488
|
|
|
1488
|
-
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
|
|
1489
|
-
${$.map((
|
|
1490
|
-
`)}`}loadFromDirectory($,
|
|
1491
|
-
`)[0]}function
|
|
1489
|
+
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 Z2($){switch($){case"default":case"ignore":case void 0:return v.DEFAULT;case"acceptEdits":return v.AUTO_EDIT;case"dontAsk":case"bypassPermissions":return v.YOLO;case"plan":return v.PLAN;default:return v.DEFAULT}}var Zw=z("Agent");class Y2{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:
|
|
1490
|
+
${$.map((w)=>{let V=!w.tools||w.tools.length===0?"All tools":w.tools.join(", ");return`- ${w.name}: ${w.description} (Tools: ${V})`}).join(`
|
|
1491
|
+
`)}`}loadFromDirectory($,b){if(!Qw.existsSync($))return;let w=Qw.readdirSync($);for(let V of w){if(!V.endsWith(".md"))continue;let W=m$.join($,V);try{let Q=this.parseConfigFile(W,b);this.subagents.set(Q.name,Q)}catch(Q){Zw.warn(`Failed to load subagent config from ${W}:`,Q)}}}parseConfigFile($,b){let V=Qw.readFileSync($,"utf-8").match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n([\s\S]*)$/);if(!V)throw Error(`No YAML frontmatter found in ${$}`);let[,W,Q]=V,Z=c6.parse(W);if(!Z.name||!Z.description)throw Error(`Missing required fields (name, description) in ${$}`);let Y=Q.trim(),J=this.parseStringOrArray(Z.tools),X=this.parseStringOrArray(Z.skills),O=Z2(Z.permissionMode);return{name:Z.name,description:Z.description,systemPrompt:Y,tools:J,color:Z.color,configPath:$,model:Z.model||"inherit",permissionMode:O,skills:X,source:b}}parseStringOrArray($){if(!$)return;if(Array.isArray($))return $.map((b)=>b.trim()).filter(Boolean);return $.split(",").map((b)=>b.trim()).filter(Boolean)}loadFromStandardLocations(){this.loadBuiltinAgents();let $=m$.join(hb.homedir(),".claude","agents");this.loadFromDirectory($,"claude-code-user");let b=m$.join(process.cwd(),".claude","agents");this.loadFromDirectory(b,"claude-code-project");let w=m$.join(hb.homedir(),".blade","agents");this.loadFromDirectory(w,"blade-user");let V=m$.join(process.cwd(),".blade","agents");this.loadFromDirectory(V,"blade-project");let W=this.getAllNames().length;return Zw.debug(`\uD83D\uDCE6 Loaded ${W} subagents from standard locations`),W}loadBuiltinAgents(){for(let $ of Ww)this.subagents.set($.name,{...$,model:$.model||"inherit",source:"builtin"});Zw.debug(`Loaded ${Ww.length} builtin subagents`)}clear(){this.subagents.clear()}getSubagentsBySource(){let $={builtin:[],"claude-code-user":[],"claude-code-project":[],"blade-user":[],"blade-project":[],plugin:[]};for(let b of this.subagents.values()){let w=b.source||"builtin",V=w.startsWith("plugin:")?"plugin":w;$[V].push(b)}return $}clearPluginAgents(){let $=[];for(let[b,w]of this.subagents.entries())if(w.source?.startsWith("plugin:"))$.push(b);for(let b of $)this.subagents.delete(b)}static getClaudeCodeAgentsDir($){if($==="user")return m$.join(hb.homedir(),".claude","agents");return m$.join(process.cwd(),".claude","agents")}static getBladeAgentsDir($){if($==="user")return m$.join(hb.homedir(),".blade","agents");return m$.join(process.cwd(),".blade","agents")}}var J$=new Y2;function l6($){let b=$.message||"Unknown error";if(b.includes("Too Many Requests")||b.includes("429")){let w=$.cause;if(w?.responseBody)try{let V=JSON.parse(w.responseBody);if(V.message)return V.message}catch{}return"API 请求过于频繁,请稍后重试"}if(b.includes("ECONNREFUSED")||b.includes("ETIMEDOUT"))return"网络连接失败,请检查网络设置";if(b.includes("401")||b.includes("Unauthorized"))return"API 认证失败,请检查 API Key 配置";return b.split(`
|
|
1492
|
+
`)[0]}function n6($){return J$.getAllNames().includes($)}function s6(){let $=J$.getAllNames();return $.length>0?$.join(", "):"none (registry not initialized)"}function r6(){return`
|
|
1492
1493
|
## Task
|
|
1493
1494
|
|
|
1494
1495
|
Launch a new agent to handle complex, multi-step tasks autonomously.
|
|
1495
1496
|
|
|
1496
1497
|
The Task tool launches specialized agents (subprocesses) that autonomously handle complex tasks. Each agent type has specific capabilities and tools available to it.
|
|
1497
1498
|
|
|
1498
|
-
${
|
|
1499
|
+
${J$.getDescriptionsForPrompt()}
|
|
1499
1500
|
|
|
1500
1501
|
When using the Task tool, you must specify a subagent_type parameter to select which agent type to use.
|
|
1501
1502
|
|
|
@@ -1519,45 +1520,45 @@ Usage notes:
|
|
|
1519
1520
|
- Clearly tell the agent whether you expect it to write code or just to do research (search, file reads, web fetches, etc.), since it is not aware of the user's intent
|
|
1520
1521
|
- If the agent description mentions that it should be used proactively, then you should try your best to use it without the user having to ask for it first. Use your judgement.
|
|
1521
1522
|
- If the user specifies that they want you to run agents "in parallel", you MUST send a single message with multiple Task tool use content blocks. For example, if you need to launch both a code-reviewer agent and a test-runner agent in parallel, send a single message with both tool calls.
|
|
1522
|
-
`.trim()}var
|
|
1523
|
+
`.trim()}var Yw=E({name:"Task",displayName:"Subagent Scheduler",kind:"readonly",isReadOnly:!0,schema:O0.object({subagent_type:O0.string().refine(n6,($)=>({message:`Invalid subagent type: "${$}". Available: ${s6()}`})).describe('Subagent type to use (e.g., "Explore", "Plan")'),description:O0.string().min(3).max(100).describe("Short task description (3-5 words)"),prompt:O0.string().min(10).describe("Detailed task instructions"),run_in_background:O0.boolean().default(!1).describe("Set to true to run this agent in the background. Use TaskOutput to read the output later."),resume:O0.string().optional().describe("Optional agent ID to resume from. If provided, the agent will continue from the previous execution transcript."),subagent_session_id:O0.string().optional().describe("Internal subagent session id for tracking")}),description:{short:"Launch a new agent to handle complex, multi-step tasks autonomously",get long(){return r6()},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($,b){let{subagent_type:w,description:V,prompt:W,run_in_background:Q=!1,resume:Z,subagent_session_id:Y}=$,{updateOutput:J}=b,X=typeof Y==="string"&&Y.length>0?Y:typeof Z==="string"&&Z.length>0?Z:i6();try{let O=J$.getAllNames(),G=J$.getSubagent(w);if(!G)return{success:!1,llmContent:`Unknown subagent type: ${w}. Available types: ${O.join(", ")||"none"}`,displayContent:`❌ 未知的 subagent 类型: ${w}
|
|
1523
1524
|
|
|
1524
|
-
可用类型: ${
|
|
1525
|
-
...(截断)`:
|
|
1525
|
+
可用类型: ${O.join(", ")||"无"}`,error:{type:"execution_error",message:`Unknown subagent type: ${w}`}};if(Z)return o6(Z,W,G,V,b);if(Q)return a6(G,V,W,b,X);if(J?.(`\uD83D\uDE80 启动 ${w} subagent: ${V}`),!b.bladeConfig)return{success:!1,llmContent:"BladeConfig is required for subagent execution",displayContent:"❌ 缺少 BladeConfig 配置",error:{type:"execution_error",message:"BladeConfig is required"}};let B=new Vw(G,b.bladeConfig),q={prompt:W,parentSessionId:b.sessionId,permissionMode:b.permissionMode,subagentSessionId:X};J?.("⚙️ 执行任务中...");let A=Date.now(),K=await B.execute(q),U=Date.now()-A;try{let _=await r.getInstance().executeSubagentStopHooks(w,{projectDir:process.cwd(),sessionId:b.sessionId||"unknown",permissionMode:b.permissionMode||v.DEFAULT,taskDescription:V,success:K.success,resultSummary:K.message.slice(0,500),error:K.error});if(!_.shouldStop&&_.continueReason){console.log(`[Task] SubagentStop hook 阻止停止,继续执行: ${_.continueReason}`);let D={prompt:_.continueReason,parentSessionId:b.sessionId,permissionMode:b.permissionMode},I=Date.now();K=await B.execute(D),U+=Date.now()-I}if(_.warning)console.warn(`[Task] SubagentStop hook warning: ${_.warning}`)}catch(F){console.warn("[Task] SubagentStop hook execution failed:",F)}if(K.success){let F=K.message.length>1000?K.message.slice(0,1000)+`
|
|
1526
|
+
...(截断)`:K.message;return{success:!0,llmContent:K.message,displayContent:`✅ Subagent 任务完成
|
|
1526
1527
|
|
|
1527
|
-
`+`类型: ${
|
|
1528
|
-
`+`任务: ${
|
|
1529
|
-
Agent ID: ${
|
|
1530
|
-
`+`耗时: ${
|
|
1531
|
-
`+`工具调用: ${
|
|
1532
|
-
`+`Token: ${
|
|
1528
|
+
`+`类型: ${w}
|
|
1529
|
+
`+`任务: ${V}
|
|
1530
|
+
Agent ID: ${K.agentId||"N/A"}
|
|
1531
|
+
`+`耗时: ${U}ms
|
|
1532
|
+
`+`工具调用: ${K.stats?.toolCalls||0} 次
|
|
1533
|
+
`+`Token: ${K.stats?.tokens||0}
|
|
1533
1534
|
|
|
1534
1535
|
`+`结果:
|
|
1535
|
-
${F}`,metadata:{subagent_type:
|
|
1536
|
+
${F}`,metadata:{subagent_type:w,description:V,duration:U,stats:K.stats,subagentSessionId:X,subagentType:w,subagentStatus:"completed",subagentSummary:K.message.slice(0,500)}}}else return{success:!1,llmContent:`Subagent execution failed: ${K.error}`,displayContent:`⚠️ Subagent 任务失败
|
|
1536
1537
|
|
|
1537
|
-
`+`类型: ${
|
|
1538
|
-
`+`任务: ${
|
|
1539
|
-
Agent ID: ${
|
|
1540
|
-
`+`耗时: ${
|
|
1541
|
-
`+`错误: ${
|
|
1538
|
+
`+`类型: ${w}
|
|
1539
|
+
`+`任务: ${V}
|
|
1540
|
+
Agent ID: ${K.agentId||"N/A"}
|
|
1541
|
+
`+`耗时: ${U}ms
|
|
1542
|
+
`+`错误: ${K.error}`,error:{type:"execution_error",message:K.error||"Unknown error"},metadata:{subagentSessionId:X,subagentType:w,subagentStatus:"failed"}}}catch(O){let G=O,B=l6(G);return{success:!1,llmContent:`Subagent execution error: ${G.message}`,displayContent:`❌ Subagent 执行异常
|
|
1542
1543
|
|
|
1543
|
-
${
|
|
1544
|
+
${B}`,error:{type:"execution_error",message:G.message,details:O}}}},version:"4.0.0",category:"Subagent",tags:["task","subagent","delegation","explore","plan"],extractSignatureContent:($)=>`${$.subagent_type}:${$.description}`,abstractPermissionRule:()=>""});function a6($,b,w,V,W){if(!V.bladeConfig)return{success:!1,llmContent:"BladeConfig is required for background agent execution",displayContent:"❌ 缺少 BladeConfig 配置",error:{type:"execution_error",message:"BladeConfig is required"}};let Z=M$.getInstance().startBackgroundAgent({config:$,bladeConfig:V.bladeConfig,description:b,prompt:w,parentSessionId:V.sessionId,permissionMode:V.permissionMode,agentId:W});return{success:!0,llmContent:{agent_id:Z,status:"running",message:`Agent started in background. Use TaskOutput(task_id: "${Z}") to retrieve results.`},displayContent:`\uD83D\uDE80 后台 Agent 已启动
|
|
1544
1545
|
|
|
1545
|
-
`+`Agent ID: ${
|
|
1546
|
+
`+`Agent ID: ${Z}
|
|
1546
1547
|
`+`类型: ${$.name}
|
|
1547
|
-
`+`任务: ${
|
|
1548
|
+
`+`任务: ${b}
|
|
1548
1549
|
|
|
1549
|
-
`+"\uD83D\uDCA1 使用 TaskOutput 工具获取结果",metadata:{agent_id:
|
|
1550
|
+
`+"\uD83D\uDCA1 使用 TaskOutput 工具获取结果",metadata:{agent_id:Z,subagent_type:$.name,description:b,background:!0,subagentSessionId:Z,subagentType:$.name,subagentStatus:"running"}}}function o6($,b,w,V,W){if(!W.bladeConfig)return{success:!1,llmContent:"BladeConfig is required for agent resume",displayContent:"❌ 缺少 BladeConfig 配置",error:{type:"execution_error",message:"BladeConfig is required"}};let Q=M$.getInstance();if(!Q.getAgent($))return{success:!1,llmContent:`Cannot resume agent ${$}: session not found`,displayContent:`❌ 无法恢复 Agent: ${$}
|
|
1550
1551
|
|
|
1551
|
-
会话不存在或已过期`,error:{type:"execution_error",message:`Agent session not found: ${$}`}};if(
|
|
1552
|
+
会话不存在或已过期`,error:{type:"execution_error",message:`Agent session not found: ${$}`}};if(Q.isRunning($))return{success:!1,llmContent:`Cannot resume agent ${$}: still running`,displayContent:`❌ 无法恢复 Agent: ${$}
|
|
1552
1553
|
|
|
1553
|
-
Agent 仍在运行中,我会使用 TaskOutput 获取结果`,error:{type:"execution_error",message:`Agent is still running: ${$}`}};let
|
|
1554
|
+
Agent 仍在运行中,我会使用 TaskOutput 获取结果`,error:{type:"execution_error",message:`Agent is still running: ${$}`}};let Y=Q.resumeAgent($,b,w,W.bladeConfig,W.sessionId,W.permissionMode);if(!Y)return{success:!1,llmContent:`Failed to resume agent ${$}`,displayContent:`❌ 恢复 Agent 失败: ${$}`,error:{type:"execution_error",message:`Failed to resume agent: ${$}`}};return{success:!0,llmContent:{agent_id:Y,status:"running",resumed_from:$,message:`Agent resumed in background. Use TaskOutput(task_id: "${Y}") to retrieve results.`},displayContent:`\uD83D\uDD04 Agent 已恢复执行
|
|
1554
1555
|
|
|
1555
|
-
`+`Agent ID: ${
|
|
1556
|
+
`+`Agent ID: ${Y}
|
|
1556
1557
|
`+`恢复自: ${$}
|
|
1557
|
-
`+`类型: ${
|
|
1558
|
-
`+`任务: ${
|
|
1558
|
+
`+`类型: ${w.name}
|
|
1559
|
+
`+`任务: ${V}
|
|
1559
1560
|
|
|
1560
|
-
`+"\uD83D\uDCA1 使用 TaskOutput 工具获取结果",metadata:{agent_id:
|
|
1561
|
+
`+"\uD83D\uDCA1 使用 TaskOutput 工具获取结果",metadata:{agent_id:Y,resumed_from:$,subagent_type:w.name,description:V,background:!0,subagentSessionId:Y,subagentType:w.name,subagentStatus:"running"}}}import{z as xb}from"zod";var Jw=E({name:"TaskOutput",displayName:"Task Output",kind:"readonly",schema:xb.object({task_id:xb.string().min(1).describe("The task ID to get output from"),block:xb.boolean().default(!0).describe("Whether to wait for completion"),timeout:xb.number().min(0).max(600000).default(30000).describe("Max wait time in ms")}),description:{short:"Retrieves output from a running or completed task",long:`
|
|
1561
1562
|
- Retrieves output from a running or completed task (background shell, agent, or remote session)
|
|
1562
1563
|
- Takes a task_id parameter identifying the task
|
|
1563
1564
|
- Returns the task output along with status information
|
|
@@ -1565,29 +1566,54 @@ Agent 仍在运行中,我会使用 TaskOutput 获取结果`,error:{type:"execu
|
|
|
1565
1566
|
- Use block=false for non-blocking check of current status
|
|
1566
1567
|
- Task IDs can be found using the /tasks command
|
|
1567
1568
|
- Works with all task types: background shells, async agents, and remote sessions
|
|
1568
|
-
`.trim(),usageNotes:["task_id is required - the ID returned when starting a background task","block=true (default) waits for task completion","block=false returns current status immediately","timeout defaults to 30000ms (30 seconds), max 600000ms (10 minutes)"],examples:[{description:"Get output from a background shell",params:{task_id:"bash_abc123",block:!0,timeout:30000}},{description:"Check agent status without blocking",params:{task_id:"session_xyz789",block:!1}}]},async execute($,
|
|
1569
|
+
`.trim(),usageNotes:["task_id is required - the ID returned when starting a background task","block=true (default) waits for task completion","block=false returns current status immediately","timeout defaults to 30000ms (30 seconds), max 600000ms (10 minutes)"],examples:[{description:"Get output from a background shell",params:{task_id:"bash_abc123",block:!0,timeout:30000}},{description:"Check agent status without blocking",params:{task_id:"session_xyz789",block:!1}}]},async execute($,b){let{task_id:w,block:V,timeout:W}=$;if(w.startsWith("bash_"))return J2(w,V,W);let Q=A$.getInstance(),Z=M$.getInstance();if(Q.getProcess(w))return J2(w,V,W);if(Z.getAgent(w))return t6(w,V,W);return{success:!1,llmContent:`Unknown task ID: ${w}.`,displayContent:`❌ 未知的任务 ID: ${w}
|
|
1569
1570
|
|
|
1570
1571
|
任务 ID 格式:
|
|
1571
1572
|
- bash_xxx: 后台 shell
|
|
1572
|
-
- agent: 后台 agent`,error:{type:"validation_error",message:`Unknown task ID: ${
|
|
1573
|
-
`+`状态: ${
|
|
1574
|
-
`+`命令: ${
|
|
1575
|
-
`+(
|
|
1576
|
-
`:"")+(
|
|
1577
|
-
`:"")+(
|
|
1573
|
+
- agent: 后台 agent`,error:{type:"validation_error",message:`Unknown task ID: ${w}`}}},version:"1.0.0",category:"Task",tags:["task","output","background","shell","agent"],extractSignatureContent:($)=>$.task_id,abstractPermissionRule:()=>"*"});async function J2($,b,w){let V=A$.getInstance(),W=V.getProcess($);if(!W)return{success:!1,llmContent:`Shell not found: ${$}`,displayContent:`❌ 未找到 Shell: ${$}`,error:{type:"execution_error",message:"Shell 会话不存在或已清理"}};if(b&&W.status==="running")await e6($,w);let Q=V.consumeOutput($);if(!Q)return{success:!1,llmContent:`Failed to get output for shell: ${$}`,displayContent:`❌ 获取 Shell 输出失败: ${$}`,error:{type:"execution_error",message:"Failed to consume output"}};let Z={task_id:Q.id,type:"shell",status:Q.status,command:Q.command,pid:Q.pid,exit_code:Q.exitCode,signal:Q.signal,started_at:new Date(Q.startedAt).toISOString(),finished_at:Q.endedAt?new Date(Q.endedAt).toISOString():void 0,stdout:Q.stdout,stderr:Q.stderr},J=`${X2(Q.status)} TaskOutput(${$}) - Shell
|
|
1574
|
+
`+`状态: ${Q.status}
|
|
1575
|
+
`+`命令: ${Q.command}
|
|
1576
|
+
`+(Q.pid?`PID: ${Q.pid}
|
|
1577
|
+
`:"")+(Q.exitCode!==void 0?`退出码: ${Q.exitCode}
|
|
1578
|
+
`:"")+(Q.stdout?`
|
|
1578
1579
|
stdout:
|
|
1579
|
-
${
|
|
1580
|
+
${Q.stdout}`:"")+(Q.stderr?`
|
|
1580
1581
|
stderr:
|
|
1581
|
-
${
|
|
1582
|
-
`+`状态: ${
|
|
1583
|
-
`+`类型: ${
|
|
1584
|
-
`+`描述: ${
|
|
1585
|
-
`+(
|
|
1586
|
-
`:"")+(
|
|
1587
|
-
`:"")+(
|
|
1582
|
+
${Q.stderr}`:"");return{success:!0,llmContent:Z,displayContent:J,metadata:Z}}async function t6($,b,w){let V=M$.getInstance(),W=V.getAgent($);if(!W)return{success:!1,llmContent:`Agent not found: ${$}`,displayContent:`❌ 未找到 Agent: ${$}`,error:{type:"execution_error",message:"Agent 会话不存在或已清理"}};if(b&&W.status==="running"){if(W=await V.waitForCompletion($,w),!W)return{success:!1,llmContent:`Failed to wait for agent: ${$}`,displayContent:`❌ 等待 Agent 失败: ${$}`,error:{type:"execution_error",message:"Wait for completion failed"}}}let Q={task_id:W.id,type:"agent",status:W.status,subagent_type:W.subagentType,description:W.description,created_at:new Date(W.createdAt).toISOString(),last_active_at:new Date(W.lastActiveAt).toISOString(),completed_at:W.completedAt?new Date(W.completedAt).toISOString():void 0,result:W.result,stats:W.stats},Z=W.status==="completed"?"completed":W.status==="failed"?"failed":"running",J=`${X2(W.status)} TaskOutput(${$}) - Agent
|
|
1583
|
+
`+`状态: ${W.status}
|
|
1584
|
+
`+`类型: ${W.subagentType}
|
|
1585
|
+
`+`描述: ${W.description}
|
|
1586
|
+
`+(W.stats?.duration?`耗时: ${W.stats.duration}ms
|
|
1587
|
+
`:"")+(W.stats?.toolCalls?`工具调用: ${W.stats.toolCalls} 次
|
|
1588
|
+
`:"")+(W.result?.message?`
|
|
1588
1589
|
结果:
|
|
1589
|
-
${
|
|
1590
|
-
错误: ${
|
|
1590
|
+
${W.result.message}`:"")+(W.result?.error?`
|
|
1591
|
+
错误: ${W.result.error}`:"");return{success:!0,llmContent:Q,displayContent:J,metadata:{...Q,subagentSessionId:W.id,subagentType:W.subagentType,subagentStatus:Z,subagentSummary:typeof W.result?.message==="string"?W.result.message.slice(0,500):void 0}}}async function e6($,b){let w=A$.getInstance(),V=Date.now();return new Promise((W)=>{let Q=setInterval(()=>{let Z=w.getProcess($);if(!Z||Z.status!=="running"){clearInterval(Q),W();return}if(Date.now()-V>=b){clearInterval(Q),W();return}},100)})}function X2($){switch($){case"running":return"⏳";case"completed":case"exited":return"✅";case"failed":case"error":return"❌";case"killed":case"cancelled":return"✂️";default:return"❓"}}import{z as O2}from"zod";var $V=O2.object({serverName:O2.string().optional().describe("Optional: Filter resources by MCP server name. If not provided, lists resources from all connected servers.")}),pb=E({name:"ListMcpResources",displayName:"List MCP Resources",kind:"readonly",description:{short:"List resources available from connected MCP servers",long:`Lists all resources provided by connected MCP (Model Context Protocol) servers.
|
|
1592
|
+
Resources can include files, database records, API endpoints, or any other data sources
|
|
1593
|
+
that MCP servers expose for reading.
|
|
1594
|
+
|
|
1595
|
+
Use this tool to discover what resources are available before using ReadMcpResource to
|
|
1596
|
+
access their contents.`,usageNotes:["List all resources: ListMcpResources({})",'List resources from specific server: ListMcpResources({ serverName: "my-server" })']},schema:$V,async execute($){try{let w=c.getInstance().getAllServers();if(w.size===0)return{success:!0,llmContent:"No MCP servers are currently connected.",displayContent:"No MCP servers connected",metadata:{resources:[],serverCount:0}};let V=[],W=[];for(let[Y,J]of w){if($.serverName&&Y!==$.serverName)continue;if(!J.client)continue;try{let X=await J.client.listResources(Y);for(let O of X)V.push({uri:O.uri,name:O.name,description:O.description,mimeType:O.mimeType,serverName:Y})}catch(X){W.push(`${Y}: ${X instanceof Error?X.message:String(X)}`)}}if(V.length===0){let Y=$.serverName?`No resources found from server "${$.serverName}".`:"No resources found from any connected MCP server.";return{success:!0,llmContent:Y+(W.length>0?`
|
|
1597
|
+
|
|
1598
|
+
Errors:
|
|
1599
|
+
${W.join(`
|
|
1600
|
+
`)}`:""),displayContent:Y,metadata:{resources:[],errors:W}}}let Q=V.map((Y)=>{let J=`- ${Y.uri} (${Y.name})`;if(Y.description)J+=`
|
|
1601
|
+
${Y.description}`;if(Y.mimeType)J+=`
|
|
1602
|
+
Type: ${Y.mimeType}`;return J+=`
|
|
1603
|
+
Server: ${Y.serverName}`,J}).join(`
|
|
1604
|
+
|
|
1605
|
+
`),Z=`Found ${V.length} resource(s) from ${new Set(V.map((Y)=>Y.serverName)).size} server(s)`;return{success:!0,llmContent:`${Z}
|
|
1606
|
+
|
|
1607
|
+
${Q}`,displayContent:Z,metadata:{resources:V,resourceCount:V.length,errors:W.length>0?W:void 0}}}catch(b){let w=b instanceof Error?b.message:String(b);return{success:!1,llmContent:`Failed to list MCP resources: ${w}`,displayContent:"Failed to list resources",error:{message:w,type:"execution_error"}}}}});import{z as Xw}from"zod";var bV=Xw.object({uri:Xw.string().describe("The URI of the MCP resource to read"),serverName:Xw.string().optional().describe("Optional: The name of the MCP server that provides this resource. If not provided, will search all connected servers.")}),db=E({name:"ReadMcpResource",displayName:"Read MCP Resource",kind:"readonly",description:{short:"Read the contents of an MCP resource by URI",long:`Reads and returns the contents of a resource from a connected MCP (Model Context Protocol) server.
|
|
1608
|
+
Resources are identified by their URI, which can be obtained using the ListMcpResources tool.
|
|
1609
|
+
|
|
1610
|
+
The resource content can be text (returned as-is) or binary data (returned as base64-encoded blob).`,usageNotes:['Read a resource: ReadMcpResource({ uri: "file:///path/to/resource" })','Read from specific server: ReadMcpResource({ uri: "db://table/record", serverName: "database-server" })']},schema:bV,async execute($){try{let w=c.getInstance().getAllServers();if(w.size===0)return{success:!1,llmContent:"No MCP servers are currently connected.",displayContent:"No MCP servers connected",error:{message:"No MCP servers connected",type:"execution_error"}};let V=null,W=null,Q=[];for(let[J,X]of w){if($.serverName&&J!==$.serverName)continue;if(!X.client)continue;try{V=await X.client.readResource($.uri,J),W=J;break}catch(O){let G=O instanceof Error?O.message:String(O);if(!G.includes("not found")&&!G.includes("does not exist"))Q.push(`${J}: ${G}`)}}if(!V){let J=$.serverName?`Resource "${$.uri}" not found on server "${$.serverName}".`:`Resource "${$.uri}" not found on any connected MCP server.`;return{success:!1,llmContent:J+(Q.length>0?`
|
|
1611
|
+
|
|
1612
|
+
Errors:
|
|
1613
|
+
${Q.join(`
|
|
1614
|
+
`)}`:""),displayContent:"Resource not found",error:{message:J,type:"execution_error"}}}let Z,Y;if(V.text!==void 0)Z=`Read ${V.text.length} characters from ${$.uri}`,Y=V.text;else if(V.blob!==void 0)Z=`Read binary resource from ${$.uri} (base64 encoded)`,Y=`[Binary content, base64 encoded, ${V.blob.length} characters]
|
|
1615
|
+
|
|
1616
|
+
${V.blob.slice(0,1000)}${V.blob.length>1000?"...":""}`;else Z=`Read resource from ${$.uri}`,Y=JSON.stringify(V,null,2);return{success:!0,llmContent:Y,displayContent:Z,metadata:{uri:$.uri,serverName:W,mimeType:V.mimeType,hasText:V.text!==void 0,hasBlob:V.blob!==void 0,contentLength:V.text?.length??V.blob?.length??0}}}catch(b){let w=b instanceof Error?b.message:String(b);return{success:!1,llmContent:`Failed to read MCP resource: ${w}`,displayContent:"Failed to read resource",error:{message:w,type:"execution_error"}}}}});import{z as B2}from"zod";import{randomUUID as wV}from"crypto";import*as S0 from"fs/promises";import*as ub from"path";class G0{static instances=new Map;todos=[];filePath;loaded=!1;constructor($,b){this.filePath=ub.join(b,"todos",`${$}-agent-${$}.json`)}static getInstance($,b){let w=`${$}-${b}`;if(!G0.instances.has(w))G0.instances.set(w,new G0($,b));return G0.instances.get(w)}validate($){if($.filter((w)=>w.status==="in_progress").length>1)return{valid:!1,error:"同时只能有一个任务处于 in_progress 状态"};return{valid:!0}}async updateTodos($){await this.ensureLoaded();let b=new Date().toISOString(),w=$.map((W)=>{let Q=W,Z=this.todos.find((Y)=>Y.id===Q.id||Y.content===W.content);return{...W,id:Q.id||Z?.id||wV(),priority:W.priority||Z?.priority||"medium",createdAt:Z?.createdAt||b,startedAt:W.status==="in_progress"&&!Z?.startedAt?b:Z?.startedAt,completedAt:W.status==="completed"&&!Z?.completedAt?b:Z?.completedAt}}),V=this.validate(w);if(!V.valid)throw Error(V.error);this.todos=w,await this.saveTodos()}getSortedTodos(){let $={completed:0,in_progress:1,pending:2},b={high:0,medium:1,low:2};return[...this.todos].sort((w,V)=>{let W=$[w.status]-$[V.status];if(W!==0)return W;return b[w.priority]-b[V.priority]})}getTodos(){return this.getSortedTodos()}async ensureLoaded(){if(!this.loaded)await this.loadTodos(),this.loaded=!0}async loadTodos(){try{let $=await S0.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 S0.mkdir(ub.dirname(this.filePath),{recursive:!0,mode:493}),await S0.writeFile(this.filePath,JSON.stringify(this.todos,null,2),"utf-8")}catch($){throw console.error("保存 TODO 列表失败:",$),$}}}import{z as M0}from"zod";var G2=M0.object({id:M0.string().optional(),content:M0.string().min(1,"Content cannot be empty"),status:M0.enum(["pending","in_progress","completed"]),activeForm:M0.string().min(1,"ActiveForm cannot be empty"),priority:M0.enum(["high","medium","low"]).default("medium")});function Ow($){let{sessionId:b,configDir:w}=$;return E({name:"TodoWrite",displayName:"Todo Write",kind:"readonly",schema:B2.object({todos:B2.array(G2).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.
|
|
1591
1617
|
It also helps the user understand the progress of the task and overall progress of their requests.
|
|
1592
1618
|
|
|
1593
1619
|
## When to Use This Tool
|
|
@@ -1648,9 +1674,9 @@ NOTE that you should not use this tool if there is only one trivial task to do.
|
|
|
1648
1674
|
- activeForm: "Fixing authentication bug"
|
|
1649
1675
|
|
|
1650
1676
|
When in doubt, use this tool. Being proactive with task management demonstrates attentiveness and ensures you complete all requirements successfully.
|
|
1651
|
-
`},async execute(
|
|
1652
|
-
`);for(let
|
|
1653
|
-
`)}import{z as
|
|
1677
|
+
`},async execute(V,W){let{todos:Q}=V,{updateOutput:Z}=W;try{let Y=W.sessionId||b,J=G0.getInstance(Y,w);Z?.("Updating TODO list..."),await J.updateTodos(Q);let X=J.getTodos(),O=VV(X),G=WV(X,O);return Z?.(`✅ TODO list updated (${O.completed}/${O.total} completed)`),{success:!0,llmContent:{todos:X,stats:O},displayContent:G,metadata:{stats:O}}}catch(Y){let J=Y;return{success:!1,llmContent:`Update failed: ${J.message}`,displayContent:`❌ 更新 TODO 列表失败: ${J.message}`,error:{type:"execution_error",message:J.message,details:Y}}}},version:"1.0.0",category:"TODO tools",tags:["todo","task","management","planning"],extractSignatureContent:(V)=>`${V.todos.length} todos`,abstractPermissionRule:()=>"*"})}function VV($){return{total:$.length,completed:$.filter((b)=>b.status==="completed").length,inProgress:$.filter((b)=>b.status==="in_progress").length,pending:$.filter((b)=>b.status==="pending").length}}function WV($,b){let w=[],V=b.total>0?Math.round(b.completed/b.total*100):0;if(w.push(`\uD83D\uDCCB TODO 列表 (${b.completed}/${b.total} 完成,${V}%)`),w.push(""),$.length===0)return w.push(" (暂无任务)"),w.join(`
|
|
1678
|
+
`);for(let W of $){let Q=W.status==="completed"?"☑":"☐",Z=`(P${W.priority==="high"?0:W.priority==="medium"?1:2})`,Y=W.status==="in_progress"?" ⚡":"",J=W.status==="completed"?"~~":"";w.push(` ${Q} ${Z} ${J}${W.content}${J}${Y}`)}return w.join(`
|
|
1679
|
+
`)}import{z as X$}from"zod";import{isPlainObject as K2}from"lodash-es";function q2($){if(!K2($))return;let b=$;return typeof b.name==="string"?b.name:void 0}function QV($){if($ instanceof Error)return $.message;if(typeof $==="string")return $;if(K2($)){let b=$;if(typeof b.message==="string")return b.message}return String($)}var Bw=E({name:"WebFetch",displayName:"Web Fetch",kind:"readonly",schema:X$.object({url:X$.string().url().describe("URL to request"),method:X$.enum(["GET","POST","PUT","DELETE","HEAD"]).default("GET").describe("HTTP method"),extract_content:X$.boolean().default(!1).describe("Use Jina Reader to extract clean content in Markdown format. Removes HTML clutter, scripts, and styling, returning only the main content."),jina_options:X$.object({with_generated_alt:X$.boolean().default(!1).describe("Generate alt text for images"),with_links_summary:X$.boolean().default(!1).describe("Include summary of all links"),wait_for_selector:X$.string().optional().describe("Wait for specific CSS selector to load")}).optional().describe("Jina Reader advanced options (only used when extract_content is true)"),headers:X$.record(X$.string()).optional().describe("Request headers (optional)"),body:X$.string().optional().describe("Request body (optional)"),timeout:g.timeout(1000,120000,30000),follow_redirects:X$.boolean().default(!0).describe("Follow redirects"),max_redirects:X$.number().int().min(0).max(10).default(5).describe("Maximum redirect hops"),return_headers:X$.boolean().default(!1).describe("Return response headers")}),description:{short:"Fetches content from a specified URL and processes it using an AI model",long:`
|
|
1654
1680
|
- Fetches content from a specified URL and processes it using an AI model
|
|
1655
1681
|
- Takes a URL and a prompt as input
|
|
1656
1682
|
- Fetches the URL content, converts HTML to markdown
|
|
@@ -1667,29 +1693,29 @@ Usage notes:
|
|
|
1667
1693
|
- Results may be summarized if the content is very large
|
|
1668
1694
|
- Includes a self-cleaning 15-minute cache for faster responses when repeatedly accessing the same URL
|
|
1669
1695
|
- 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.
|
|
1670
|
-
`},async execute($,
|
|
1671
|
-
响应时间: ${
|
|
1672
|
-
内容长度: ${
|
|
1673
|
-
Content-Type: ${
|
|
1674
|
-
最终URL: ${
|
|
1675
|
-
重定向次数: ${
|
|
1696
|
+
`},async execute($,b){let{url:w,method:V="GET",extract_content:W=!1,jina_options:Q,headers:Z={},body:Y,timeout:J=30000,follow_redirects:X=!0,max_redirects:O=5,return_headers:G=!1}=$,{updateOutput:B}=b,q=b.signal??new AbortController().signal;try{if(W)try{let _=Date.now(),D=await GV({url:w,jinaOptions:Q,timeout:J,signal:q,updateOutput:B}),I=Date.now()-_;if(D.response_time=I,!G)delete D.headers;let N={url:w,method:"GET",status:D.status,response_time:I,content_length:Buffer.byteLength(D.body||"","utf8"),redirected:D.redirected||!1,redirect_count:D.redirect_count??0,final_url:D.url,content_type:D.content_type,redirect_chain:D.redirect_chain};return{success:!0,llmContent:D,displayContent:Gw(D,N,!1),metadata:N}}catch{B?.("⚠️ Jina Reader 失败,使用标准方式获取")}B?.(`发送 ${V} 请求到: ${w}`);let A=Date.now(),K=await ZV({url:w,method:V,headers:Z,body:Y,timeout:J,follow_redirects:X,max_redirects:O,signal:q}),U=Date.now()-A;if(K.response_time=U,!G)delete K.headers;let F={url:w,method:V,status:K.status,response_time:U,content_length:Buffer.byteLength(K.body||"","utf8"),redirected:K.redirected||!1,redirect_count:K.redirect_count??0,final_url:K.url,content_type:K.content_type,redirect_chain:K.redirect_chain};if(K.status>=400)return{success:!1,llmContent:`HTTP error ${K.status}: ${K.status_text}`,displayContent:Gw(K,F,!0),error:{type:"execution_error",message:`HTTP error ${K.status}: ${K.status_text}`,details:{...F,response_body:K.body}},metadata:F};return{success:!0,llmContent:K,displayContent:Gw(K,F,!1),metadata:F}}catch(A){if(q2(A)==="AbortError")return{success:!1,llmContent:"Request aborted",displayContent:"⚠️ 请求被用户中止",error:{type:"execution_error",message:"操作被中止"}};let K=QV(A);return{success:!1,llmContent:`Network request failed: ${K}`,displayContent:`❌ 网络请求失败: ${K}`,error:{type:"execution_error",message:K,details:A}}}},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"*"}}});async function ZV($){let{url:b,method:w,headers:V,body:W,timeout:Q,follow_redirects:Z,max_redirects:Y,signal:J}=$,X={"User-Agent":"Blade-AI/1.0",...V},O=b,G=w,B=W,q=0,A=[];while(!0){let K={...X};if(B&&G!=="GET"&&G!=="HEAD"&&!OV(K,"content-type"))K["Content-Type"]="application/json";let U=await C2(O,{method:G,headers:K,body:B&&G!=="GET"&&G!=="HEAD"?B:void 0,redirect:"manual"},Q,J),F=U.headers.get("location"),_=U.status>=300&&U.status<400,D=Z&&_&&F&&q<Y;if(_&&Z&&!F)throw Error(`收到状态码 ${U.status} 但响应缺少 Location 头`);if(_&&Z&&q>=Y)throw Error(`超过最大重定向次数 (${Y})`);if(D&&F){q++;let M=XV(F,O);if(A.push(`${U.status} → ${M}`),U.status===303||(U.status===301||U.status===302)&&G!=="GET"&&G!=="HEAD")G="GET",B=void 0;O=M;continue}let I=await U.text(),N=A2(U.headers);return{status:U.status,status_text:U.statusText,headers:N,body:I,url:U.url||O,redirected:q>0,redirect_count:q,redirect_chain:A,content_type:N["content-type"],response_time:0}}}function Gw($,b,w){let{url:V,method:W,status:Q,response_time:Z,content_length:Y}=b,J=w?`❌ ${W} ${V} - ${Q} ${$.status_text}`:`✅ ${W} ${V} - ${Q} ${$.status_text}`;if(J+=`
|
|
1697
|
+
响应时间: ${Z}ms`,J+=`
|
|
1698
|
+
内容长度: ${Y} 字节`,b.content_type)J+=`
|
|
1699
|
+
Content-Type: ${b.content_type}`;if($.redirected&&b.final_url&&b.final_url!==V){if(J+=`
|
|
1700
|
+
最终URL: ${b.final_url}`,b.redirect_count)J+=`
|
|
1701
|
+
重定向次数: ${b.redirect_count}`}let X=YV($.body,$.content_type);if(X)J+=`
|
|
1676
1702
|
响应内容:
|
|
1677
|
-
${
|
|
1678
|
-
`),
|
|
1679
|
-
`).trim();return{title:
|
|
1680
|
-
|
|
1681
|
-
`;if($.sourceUrl)
|
|
1682
|
-
|
|
1683
|
-
`;return
|
|
1684
|
-
|
|
1685
|
-
`,
|
|
1686
|
-
`),
|
|
1687
|
-
`);for(let
|
|
1688
|
-
${
|
|
1689
|
-
`)}`)}}throw Error("No search providers available")}function
|
|
1690
|
-
${
|
|
1691
|
-
${
|
|
1692
|
-
`)}function
|
|
1703
|
+
${X}`;return J}function YV($,b){if(!$)return"(空响应)";if(JV(b,$))return"[binary content omitted]";let w=$.trim();if(!w)return"(仅包含空白字符)";return w.length>800?`${w.slice(0,800)}...`:w}function JV($,b){if($){let W=$.toLowerCase();if(["image/","audio/","video/","application/pdf","application/zip","application/octet-stream"].some((Z)=>W.startsWith(Z)))return!0}if(!b)return!1;let w=0,V=Math.min(b.length,200);for(let W=0;W<V;W++){let Q=b.charCodeAt(W);if(Q===9||Q===10||Q===13)continue;if(Q<32||Q>126)w++}return w/(V||1)>0.3}async function C2($,b,w,V){let W=new AbortController,Q=setTimeout(()=>W.abort(),w),Z=()=>W.abort();V?.addEventListener("abort",Z);try{return await fetch($,{...b,signal:W.signal})}catch(Y){if(q2(Y)==="AbortError"){if(Y instanceof Error)throw Y.message="请求被中止或超时",Y;let J=Error("请求被中止或超时");throw J.name="AbortError",J}throw Y}finally{clearTimeout(Q),V?.removeEventListener("abort",Z)}}function XV($,b){try{return new URL($,b).toString()}catch{return $}}function A2($){let b={};return $.forEach((w,V)=>{b[V.toLowerCase()]=w}),b}function OV($,b){let w=b.toLowerCase();return Object.keys($).some((V)=>V.toLowerCase()===w)}async function GV($){let{url:b,jinaOptions:w,timeout:V,signal:W,updateOutput:Q}=$,Z=`https://r.jina.ai/${encodeURIComponent(b)}`;Q?.(`\uD83D\uDD0D 使用 Jina Reader 提取内容: ${b}`);let Y={"User-Agent":"Blade-AI/1.0",Accept:"text/markdown"};if(w?.with_generated_alt)Y["X-With-Generated-Alt"]="true";if(w?.with_links_summary)Y["X-With-Links-Summary"]="true";if(w?.wait_for_selector)Y["X-Wait-For-Selector"]=w.wait_for_selector;try{let J=await C2(Z,{method:"GET",headers:Y},V,W);if(!J.ok)throw Error(`Jina Reader error: ${J.status} ${J.statusText}`);let X=await J.text(),O=BV(X);return Q?.(`✅ Jina Reader 成功提取内容 (${O.content.length} 字符)`),{status:J.status,status_text:J.statusText,headers:A2(J.headers),body:KV(O),url:O.sourceUrl||b,redirected:!1,redirect_count:0,content_type:"text/markdown",response_time:0}}catch(J){throw Q?.("⚠️ Jina Reader 失败,回退到直接获取"),J}}function BV($){let b=$.split(`
|
|
1704
|
+
`),w="",V="",W=0;for(let Z=0;Z<b.length;Z++){let Y=b[Z];if(Y.startsWith("Title: "))w=Y.substring(7).trim();else if(Y.startsWith("URL Source: "))V=Y.substring(12).trim();else if(Y.startsWith("Markdown Content:")){W=Z+1;break}}let Q=b.slice(W).join(`
|
|
1705
|
+
`).trim();return{title:w||"Untitled",sourceUrl:V||"",content:Q||$}}function KV($){let b="";if($.title)b+=`# ${$.title}
|
|
1706
|
+
|
|
1707
|
+
`;if($.sourceUrl)b+=`**Source**: ${$.sourceUrl}
|
|
1708
|
+
|
|
1709
|
+
`;return b+=`---
|
|
1710
|
+
|
|
1711
|
+
`,b+=$.content,b}import{ProxyAgent as DV,fetch as jV}from"undici";import{z as z0}from"zod";import{LRUCache as U2}from"lru-cache";import qV from"node:crypto";class F2{cache;config;hits=0;misses=0;constructor($){this.config={maxSize:$?.maxSize??100,ttl:$?.ttl??3600000,enabled:$?.enabled??!0},this.cache=new U2({max:this.config.maxSize,ttl:this.config.ttl,updateAgeOnGet:!0,updateAgeOnHas:!1})}generateKey($,b){let w=b.toLowerCase().trim(),V=qV.createHash("md5").update(w).digest("hex").substring(0,8);return`${$}:${V}`}get($,b){if(!this.config.enabled)return null;let w=this.generateKey($,b),V=this.cache.get(w);if(!V)return this.misses++,null;if(Date.now()>V.expiresAt)return this.cache.delete(w),this.misses++,null;return this.hits++,V.results}set($,b,w){if(!this.config.enabled||w.length===0)return;let V=this.generateKey($,b),W=Date.now(),Q={query:b,provider:$,results:w,timestamp:W,expiresAt:W+this.config.ttl};this.cache.set(V,Q)}clear(){this.cache.clear(),this.hits=0,this.misses=0}getStats(){let $=this.hits+this.misses,b=$>0?this.hits/$*100:0;return{size:this.cache.size,maxSize:this.config.maxSize,enabled:this.config.enabled,ttl:this.config.ttl,hits:this.hits,misses:this.misses,hitRate:Number.parseFloat(b.toFixed(2))}}cleanup(){let $=Date.now(),b=0;for(let[w,V]of this.cache.entries())if($>V.expiresAt)this.cache.delete(w),b++;return b}enable(){this.config.enabled=!0}disable(){this.config.enabled=!1}isEnabled(){return this.config.enabled}updateConfig($){if($.maxSize!==void 0&&$.maxSize!==this.config.maxSize){this.config.maxSize=$.maxSize;let b=Array.from(this.cache.entries());this.cache=new U2({max:this.config.maxSize,ttl:this.config.ttl,updateAgeOnGet:!0,updateAgeOnHas:!1});for(let[w,V]of b.slice(-this.config.maxSize))this.cache.set(w,V)}if($.ttl!==void 0)this.config.ttl=$.ttl;if($.enabled!==void 0)this.config.enabled=$.enabled}}var CV=new F2;function H2(){return CV}function AV($){return $.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,'"').replace(/'/g,"'")}function _2($){let b=AV($).trim();if(!b.includes(" - "))return{title:b,snippet:b};let[w,...V]=b.split(" - "),W=w.trim(),Q=V.join(" - ").trim()||b;return{title:W,snippet:Q}}function wb($){try{let b=new URL($),w=b.pathname==="/"?"":b.pathname;return`${b.hostname}${w}`}catch{return $}}function Vb($){try{return new URL($).hostname.toLowerCase()}catch{return""}}function UV($){if(!$.FirstURL||!$.Text)return null;let{title:b,snippet:w}=_2($.Text);return{title:b,snippet:w,url:$.FirstURL,display_url:wb($.FirstURL),source:Vb($.FirstURL)}}function R2($){let b=[];for(let w of $){if(w.Topics&&w.Topics.length>0){b.push(...R2(w.Topics));continue}if(w.FirstURL&&w.Text){let{title:V,snippet:W}=_2(w.Text);b.push({title:V,snippet:W,url:w.FirstURL,display_url:wb(w.FirstURL),source:Vb(w.FirstURL)})}}return b}function FV($){let b=$,w=(b.Results??[]).map((W)=>UV(W)).filter((W)=>W!==null),V=R2(b.RelatedTopics??[]);return[...w,...V]}var HV={name:"DuckDuckGo",endpoint:"https://duckduckgo.com/",buildUrl:($)=>{let b=new URL("https://duckduckgo.com/");return b.searchParams.set("q",$),b.searchParams.set("format","json"),b.searchParams.set("no_html","1"),b.searchParams.set("skip_disambig","1"),b.searchParams.set("t","blade-code"),b.searchParams.set("kl","us-en"),b.toString()},parseResponse:FV,getHeaders:()=>({Accept:"application/json, text/plain;q=0.9","User-Agent":"Blade-AI-WebSearch/1.0"})};function _V($){let b=$,w=[];for(let V of b.results??[]){if(!V.url||!V.title)continue;w.push({title:V.title,snippet:V.content||V.title,url:V.url,display_url:wb(V.url),source:Vb(V.url)})}return w}var E2=["https://searx.be","https://search.ononoki.org","https://searx.tiekoetter.com","https://searx.work"];function RV($){return{name:`SearXNG(${(()=>{try{return new URL($).hostname}catch{return $}})()})`,endpoint:$,buildUrl:(w)=>{let V=new URL(`${$}/search`);return V.searchParams.set("q",w),V.searchParams.set("format","json"),V.searchParams.set("categories","general"),V.toString()},parseResponse:_V,getHeaders:()=>({Accept:"application/json","User-Agent":"Blade-AI-WebSearch/1.0"})}}var t$={BASE_URL:"https://mcp.exa.ai",ENDPOINT:"/mcp",DEFAULT_NUM_RESULTS:10,TIMEOUT:25000};function EV($){let b=[],w=$.split(`
|
|
1712
|
+
`),V={};for(let W=0;W<w.length;W++){let Q=w[W].trim();if(Q.startsWith("Title: ")){if(V.title&&V.url)b.push({title:V.title,url:V.url,snippet:V.snippet||V.title,display_url:wb(V.url),source:Vb(V.url)});V={title:Q.substring(7).trim(),snippet:""}}else if(Q.startsWith("URL: "))V.url=Q.substring(5).trim();else if(Q.startsWith("Text: ")){let Y=Q.substring(6).trim().replace(/<[^>]*>/g,"").replace(/\s+/g," ").trim();V.snippet=Y.substring(0,300)}}if(V.title&&V.url)b.push({title:V.title,url:V.url,snippet:V.snippet||V.title,display_url:wb(V.url),source:Vb(V.url)});return b}function LV(){return{name:"Exa",endpoint:`${t$.BASE_URL}${t$.ENDPOINT}`,searchFn:async($)=>{let b={jsonrpc:"2.0",id:1,method:"tools/call",params:{name:"web_search_exa",arguments:{query:$,type:"auto",numResults:t$.DEFAULT_NUM_RESULTS,contextMaxCharacters:1e4}}},w=new AbortController,V=setTimeout(()=>w.abort(),t$.TIMEOUT);try{let W=await fetch(`${t$.BASE_URL}${t$.ENDPOINT}`,{method:"POST",headers:{accept:"application/json, text/event-stream","content-type":"application/json"},body:JSON.stringify(b),signal:w.signal});if(clearTimeout(V),!W.ok)throw Error(`MCP error (${W.status})`);let Z=(await W.text()).split(`
|
|
1713
|
+
`);for(let Y of Z)if(Y.startsWith("data: ")){let J=JSON.parse(Y.substring(6));if(J.result&&J.result.content&&J.result.content.length>0)return EV(J.result.content[0].text)}throw Error("No search results found")}catch(W){if(clearTimeout(V),W.name==="AbortError")throw Error("MCP request timed out");throw W}},buildUrl:()=>`${t$.BASE_URL}${t$.ENDPOINT}`,parseResponse:()=>[],getHeaders:()=>({})}}function L2(){let $=[];return $.push(LV()),$.push(HV),$.push(...E2.map(RV)),$}function D2(){return 2+E2.length}var NV=15000,SV=8,Wb={maxRetries:3,baseDelay:1000,maxDelay:8000};function MV(){let $=process.env.HTTPS_PROXY||process.env.HTTP_PROXY||process.env.https_proxy||process.env.http_proxy;if($)try{return new DV($)}catch(b){console.warn(`Invalid proxy URL: ${$}`)}return}async function zV($,b,w,V,W){let Q=new AbortController,Z=setTimeout(()=>Q.abort(),w),Y=()=>Q.abort();V?.addEventListener("abort",Y);try{return await jV($,{...b,signal:Q.signal,dispatcher:W})}catch(J){if(J.name==="AbortError")throw Error("搜索请求超时或被中止");throw J}finally{clearTimeout(Z),V?.removeEventListener("abort",Y)}}async function yV($,b,w,V,W,Q){let Z=null;for(let Y=0;Y<Wb.maxRetries;Y++)try{return await zV($,b,w,V,W)}catch(J){if(Z=J,V?.aborted)throw J;if(Y<Wb.maxRetries-1){let X=Math.min(Wb.baseDelay*2**Y,Wb.maxDelay);Q?.(`⏳ 请求失败,${X/1000}s 后重试 (${Y+1}/${Wb.maxRetries})...`),await new Promise((O)=>setTimeout(O,X))}}throw Z}async function vV($,b,w,V,W,Q){let Z=H2(),Y=Z.get($.name,b);if(Y)return Q?.(`\uD83D\uDCBE 使用缓存结果 (${$.name})`),{results:Y,providerName:`${$.name} (cached)`};if($.searchFn)try{Q?.(`\uD83D\uDD0D 搜索中 (${$.name})...`);let U=await $.searchFn(b);return Z.set($.name,b,U),{results:U,providerName:$.name}}catch(U){throw Error(`SDK search failed: ${U.message}`)}Q?.(`\uD83D\uDD0D 搜索中 (${$.name})...`);let J=$.buildUrl(b),X=$.method||"GET",G={headers:$.getHeaders(),method:X};if(X==="POST"&&$.buildBody)G.body=JSON.stringify($.buildBody(b));let B=await yV(J,G,w,V,W,Q);if(!B.ok)throw Error(`HTTP ${B.status}`);let q=await B.text(),A;try{A=JSON.parse(q)}catch{throw Error("Failed to parse search result JSON")}let K=$.parseResponse(A);return Z.set($.name,b,K),{results:K,providerName:$.name}}async function TV($,b,w,V){let W=L2(),Q=MV(),Z=[];for(let Y=0;Y<W.length;Y++){let J=W[Y];if(w?.aborted)throw Error("搜索被用户中止");try{return V?.(`\uD83D\uDD0E 使用 ${J.name} 搜索...`),await vV(J,$,b,w,Q,V)}catch(X){let O=X,G=`${J.name}: ${O.message}`;if(Z.push(G),V?.(`⚠️ ${G}`),Y===W.length-1)throw Error(`所有搜索提供商都失败了:
|
|
1714
|
+
${Z.join(`
|
|
1715
|
+
`)}`)}}throw Error("No search providers available")}function kV($){try{return new URL($).hostname.toLowerCase()}catch{return null}}function fV($){return $.trim().toLowerCase()}function j2($){if(!$||$.length===0)return[];return $.map(fV).filter(Boolean)}function N2($,b){return $===b||$.endsWith(`.${b}`)}function IV($,b,w){return $.filter((V)=>{let W=kV(V.url);if(!W)return!1;if(w.length>0&&w.some((Q)=>N2(W,Q)))return!1;if(b.length>0&&!b.some((Q)=>N2(W,Q)))return!1;return!0})}function PV($,b,w,V){let W=`\uD83D\uDD0E WebSearch("${$}") via ${V} - 返回 ${b.length}/${w} 条结果`,Q=b.map((Z,Y)=>`${Y+1}. ${Z.title}
|
|
1716
|
+
${Z.display_url}
|
|
1717
|
+
${Z.snippet}`);return[W,...Q].join(`
|
|
1718
|
+
`)}function hV($){let b=$.trim().toLowerCase();return b.length>80?b.slice(0,80):b}var Kw=E({name:"WebSearch",displayName:"Web Search",kind:"readonly",schema:z0.object({query:z0.string().min(2,"Search query must be at least 2 characters").describe("Search query"),allowed_domains:z0.array(z0.string().min(1)).optional().describe("Return results only from these domains (optional)"),blocked_domains:z0.array(z0.string().min(1)).optional().describe("Exclude results from these domains (optional)")}),description:{short:"Search the web and use the results to inform responses",long:`
|
|
1693
1719
|
- Search the web and use the results to inform responses
|
|
1694
1720
|
- Provides up-to-date information for current events and recent data
|
|
1695
1721
|
- Returns search result information formatted as search result blocks, including links as markdown hyperlinks
|
|
@@ -1717,141 +1743,142 @@ Usage notes:
|
|
|
1717
1743
|
IMPORTANT - Use the correct year in search queries:
|
|
1718
1744
|
- You MUST use the current year when searching for recent information, documentation, or current events.
|
|
1719
1745
|
- Example: If the user asks for "latest React docs", search for "React documentation 2025", NOT "React documentation 2024"
|
|
1720
|
-
`},async execute($,
|
|
1746
|
+
`},async execute($,b){let{query:w}=$,V=j2($.allowed_domains),W=j2($.blocked_domains),{updateOutput:Q}=b,Z=b.signal??new AbortController().signal;Q?.(`\uD83D\uDD0E Searching: "${w}" (${D2()} providers available)`);try{let{results:Y,providerName:J}=await TV(w,NV,Z,Q),X=IV(Y,V,W),O=X.slice(0,SV),G={query:w,results:O,provider:J,total_results:X.length,fetched_at:new Date().toISOString()},B={query:w,provider:J,fetched_at:G.fetched_at,total_results:X.length,returned_results:O.length,allowed_domains:V,blocked_domains:W};if(O.length===0)return{success:!0,llmContent:G,displayContent:`\uD83D\uDD0D WebSearch("${w}") via ${J} - 未找到匹配结果`,metadata:B};return{success:!0,llmContent:G,displayContent:PV(w,O,X.length,J),metadata:B}}catch(Y){let J=Y;return{success:!1,llmContent:`WebSearch call failed: ${J.message}`,displayContent:`❌ WebSearch 调用失败: ${J.message}`,error:{type:"execution_error",message:J.message,details:{query:w,allowedDomains:V,blockedDomains:W}}}}},version:"2.0.0",category:"网络工具",tags:["web","search","internet","news"],extractSignatureContent:($)=>`search:${hV($.query)}`,abstractPermissionRule:()=>"search:*"});async function xV(){try{return await c.getInstance().getAvailableTools()}catch($){return console.warn("MCP协议工具加载失败:",$),[]}}async function qw($){let b=$?.sessionId||`session_${Date.now()}`,w=$?.configDir||M2.join(S2.homedir(),".blade"),V=[h1,P1,p1,Mb,c1,n1,r1,a1,Bw,Kw,Yw,Jw,Ow({sessionId:b,configDir:w}),d1,g1,...W2,Pb,ww,pb,db],W=await xV();return[...V,...W]}import{EventEmitter as mV}from"events";import{nanoid as pV}from"nanoid";class Cw{name="hook";hookManager;constructor(){this.hookManager=r.getInstance()}async process($){if(!this.hookManager.isEnabled())return;let b=$._internal.tool;if(!b)return;try{let w=$.context.messageId||`tool_${pV()}`;$._internal.hookToolUseId=w;let V=$.context.workspaceRoot||process.cwd(),W=await this.hookManager.executePreToolHooks(b.name,w,$.params,{projectDir:V,sessionId:$.context.sessionId||"unknown",permissionMode:$.context.permissionMode??v.DEFAULT,abortSignal:$.context.signal});if(W.decision==="deny"){$.abort(W.reason||"Hook blocked execution");return}if(W.decision==="ask"){$._internal.needsConfirmation=!0,$._internal.confirmationReason=W.reason||"Hook requires confirmation";return}if(W.modifiedInput){let Q={...$.params,...W.modifiedInput};if(b.build)try{b.build(Q),$.params=Q}catch(Z){$.abort(`Hook modified parameters are invalid: ${Z instanceof Error?Z.message:String(Z)}`);return}}if(W.warning)console.warn(`[Hook Warning] ${W.warning}`)}catch(w){console.error("[HookStage] Error executing hooks:",w)}}}import{nanoid as dV}from"nanoid";function uV($){return typeof $==="object"&&$!==null&&!Array.isArray($)}class Aw{name="post-hook";hookManager;constructor(){this.hookManager=r.getInstance()}async process($){if(!this.hookManager.isEnabled())return;let b=$._internal.tool;if(!b)return;let w=$.getResult();if(!w)return;try{let V=$._internal.hookToolUseId||$.context.messageId||`tool_${dV()}`,W=$.context.workspaceRoot||process.cwd(),Q=await this.hookManager.executePostToolHooks(b.name,V,$.params,w,{projectDir:W,sessionId:$.context.sessionId||"unknown",permissionMode:$.context.permissionMode??v.DEFAULT,abortSignal:$.context.signal});if(Q.additionalContext){let Z=w.llmContent||w.displayContent||"";w.llmContent=`${Z}
|
|
1721
1747
|
|
|
1722
1748
|
---
|
|
1723
1749
|
**Hook Context:**
|
|
1724
|
-
${
|
|
1725
|
-
${
|
|
1750
|
+
${Q.additionalContext}`}if(Q.modifiedOutput!==void 0){let Z=Q.modifiedOutput;if(uV(Z))Object.assign(w,Z)}if(Q.warning)console.warn(`[PostToolUseHook Warning] ${Q.warning}`)}catch(V){console.error("[PostToolUseHookStage] Error executing post-tool hooks:",V)}}}var Uw=z("Execution");class e${static instance=null;locks=new Map;constructor(){}static getInstance(){if(!e$.instance)e$.instance=new e$;return e$.instance}async acquireLock($,b){let w=this.locks.get($);if(w)try{await w}catch{}let V=this.executeWithLock($,b);return this.locks.set($,V.then(()=>{return})),V}async executeWithLock($,b){Uw.debug(`获取文件锁: ${$}`);try{let w=await b();return Uw.debug(`释放文件锁: ${$}`),w}catch(w){throw Uw.debug(`操作失败,释放文件锁: ${$}`),w}}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(){e$.instance=null}}import gV from"node:os";import Fw from"node:path";class E${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 b=E$.normalizePath($),w=Fw.basename(b);for(let V of E$.SENSITIVE_PATTERNS)if(E$.matchPattern(w,V.pattern))return{isSensitive:!0,level:V.level,matchedPattern:V.pattern instanceof RegExp?V.pattern.source:V.pattern,reason:V.description};for(let V of E$.SENSITIVE_PATHS)if(E$.matchPattern(b,V.path))return{isSensitive:!0,level:V.level,matchedPattern:V.path instanceof RegExp?V.path.source:V.path,reason:V.description};return{isSensitive:!1}}static checkMultiple($){let b=new Map;for(let w of $)b.set(w,E$.check(w));return b}static filterSensitive($,b="low"){let w={["high"]:3,["medium"]:2,["low"]:1},V=w[b];return $.map((W)=>({path:W,result:E$.check(W)})).filter(({result:W})=>W.isSensitive&&W.level&&w[W.level]>=V)}static normalizePath($){if($.startsWith("~/")||$==="~")return Fw.join(gV.homedir(),$.slice(1));return Fw.resolve($)}static matchPattern($,b){if(b instanceof RegExp)return b.test($);let w=b.replace(/\*/g,".*");return new RegExp(`^${w}$`,"i").test($)}static getSensitivePatterns(){return[...E$.SENSITIVE_PATTERNS]}static getSensitivePaths(){return[...E$.SENSITIVE_PATHS]}}class gb{config;constructor($){this.config=$}static buildSignature($){if($.tool?.extractSignatureContent)return`${$.toolName}:${$.tool.extractSignatureContent($.params)}`;return $.toolName}static abstractPattern($){if($.tool?.abstractPermissionRule)return`${$.toolName}:${$.tool.abstractPermissionRule($.params)}`;return`${$.toolName}:*`}check($){let b=gb.buildSignature($);if(this.config.deny?.some((w)=>this.matchRule(b,w)))return{result:"deny",matchedRule:"deny",reason:"Denied by permission rule"};if(this.config.allow?.some((w)=>this.matchRule(b,w)))return{result:"allow",matchedRule:"allow",reason:"Allowed by permission rule"};if(this.config.ask?.some((w)=>this.matchRule(b,w)))return{result:"ask",matchedRule:"ask",reason:"Requires user confirmation"};return{result:"ask",reason:"Default: requires user confirmation"}}replaceConfig($){this.config={...this.config,...$}}matchRule($,b){if(b==="*")return!0;if(b.endsWith("*"))return $.startsWith(b.slice(0,-1));return $===b}}var B0=z("Execution");class Hw{registry;name="discovery";constructor($){this.registry=$}async process($){let b=this.registry.get($.toolName);if(!b){$.abort(`Tool "${$.toolName}" not found`);return}$._internal.tool=b}}class _w{name="permission";permissionChecker;sessionApprovals;defaultPermissionMode;constructor($,b,w){this.permissionChecker=new gb($),this.sessionApprovals=b,this.defaultPermissionMode=w}getPermissionChecker(){return this.permissionChecker}async process($){let b=$._internal.tool;if(!b){$.abort("Discovery stage failed; cannot perform permission check");return}try{let w=b.build($.params),V=w.getAffectedPaths(),W={toolName:b.name,params:$.params,affectedPaths:V,tool:b},Q=gb.buildSignature(W);$._internal.permissionSignature=Q;let Z=this.permissionChecker.check(W),Y=$.context.permissionMode||this.defaultPermissionMode;switch(Z=this.applyModeOverrides(b.kind,Z,Y),Z.result){case"deny":$.abort(Z.reason||`Tool invocation "${b.name}" was denied by permission rules: ${Z.matchedRule}`);return;case"ask":if(this.sessionApprovals.has(Q))Z={result:"allow",matchedRule:"remembered:session",reason:"User already allowed this operation in this session"};else $._internal.needsConfirmation=!0,$._internal.confirmationReason=Z.reason||"User confirmation required";break;case"allow":break}if(V.length>0){let J=["/etc/","/sys/","/proc/","/dev/","/boot/","/root/","C:\\Windows\\System32","C:\\Program Files","C:\\ProgramData"],X=V.filter((G)=>{if(G.includes(".."))return!0;return J.some((B)=>G.includes(B))});if(X.length>0){$.abort(`Access to dangerous system paths denied: ${X.join(", ")}`);return}let O=E$.filterSensitive(V,"medium");if(O.length>0){let G=O.map(({path:q,result:A})=>`${q} (${A.level}: ${A.reason})`);if(O.filter(({result:q})=>q.level==="high").length>0&&Z.result!=="allow"){$.abort(`Access to highly sensitive files denied:
|
|
1751
|
+
${G.join(`
|
|
1726
1752
|
`)}
|
|
1727
1753
|
|
|
1728
|
-
If access is required, add an explicit allow rule in permissions.`);return}if(
|
|
1729
|
-
${
|
|
1754
|
+
If access is required, add an explicit allow rule in permissions.`);return}if(Z.result==="allow"&&O.length>0)$._internal.confirmationReason=`Sensitive file access detected:
|
|
1755
|
+
${G.join(`
|
|
1730
1756
|
`)}
|
|
1731
1757
|
|
|
1732
|
-
Confirm to proceed?`,$._internal.needsConfirmation=!0}}$._internal.invocation=
|
|
1733
|
-
`);if(
|
|
1758
|
+
Confirm to proceed?`,$._internal.needsConfirmation=!0}}$._internal.invocation=w,$._internal.permissionCheckResult=Z}catch(w){$.abort(`Permission check failed: ${w.message}`)}}applyModeOverrides($,b,w){if(w===v.YOLO)return{result:"allow",matchedRule:"mode:yolo",reason:"YOLO mode: automatically approve all tool invocations"};if(w===v.PLAN){if(!F0($))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(b.result==="deny")return b;if(b.result==="allow")return b;if(F0($))return{result:"allow",matchedRule:`mode:${w}:readonly`,reason:"Read-only tools do not require confirmation"};if(w===v.AUTO_EDIT&&$==="write")return{result:"allow",matchedRule:"mode:autoEdit:write",reason:"AUTO_EDIT mode: automatically approve write tools"};return b}}class Rw{sessionApprovals;permissionChecker;canUseTool;name="confirmation";constructor($,b,w){this.sessionApprovals=$;this.permissionChecker=b;this.canUseTool=w}async process($){let{tool:b,invocation:w,needsConfirmation:V}=$._internal;if(!b||!w){$.abort("Pre-confirmation stage failed; cannot request user approval");return}let W=w.getAffectedPaths()||[];if(this.canUseTool){let Q=await this.canUseTool(b.name,$.params,{signal:$.context.signal||new AbortController().signal,toolKind:b.kind,affectedPaths:W});await this.handleCanUseToolResult(Q,$);return}if(!V)return;await this.handleLegacyConfirmation($,b,w,W)}async handleCanUseToolResult($,b){let{tool:w,invocation:V}=b._internal;switch($.behavior){case"allow":if($.updatedInput){if(Object.assign(b.params,$.updatedInput),w&&V)b._internal.invocation=w.build(b.params)}if($.updatedPermissions)this.applyPermissionUpdates($.updatedPermissions);B0.debug(`canUseTool allowed: ${b.toolName}`);break;case"deny":b.abort($.message,{shouldExitLoop:$.interrupt});break;case"ask":if(b._internal.needsConfirmation=!0,w&&V)await this.handleLegacyConfirmation(b,w,V,V.getAffectedPaths()||[]);break}}applyPermissionUpdates($){for(let b of $)switch(b.type){case"addRules":for(let w of b.rules){let V=w.ruleContent?`${w.toolName}:${w.ruleContent}`:w.toolName;if(b.behavior==="allow")this.sessionApprovals.add(V);B0.debug(`Permission rule added: ${V} -> ${b.behavior}`)}break;case"removeRules":for(let w of b.rules){let V=w.ruleContent?`${w.toolName}:${w.ruleContent}`:w.toolName;this.sessionApprovals.delete(V),B0.debug(`Permission rule removed: ${V}`)}break}}async handleLegacyConfirmation($,b,w,V){let{confirmationReason:W,permissionCheckResult:Q}=$._internal;try{let Y={title:`权限确认: ${b.extractSignatureContent?b.extractSignatureContent($.params):b.name}`,message:W||"此操作需要用户确认",kind:b.kind,details:this.generatePreviewForTool(b.name,$.params),risks:this.extractRisksFromPermissionCheck(b,$.params,Q),affectedFiles:V};B0.warn(`工具 "${b.name}" 需要用户确认: ${Y.title}`);let J=$.context.confirmationHandler;if(J){B0.info(`[ConfirmationStage] Requesting confirmation for ${b.name}`);let X=await J.requestConfirmation(Y);if(B0.info(`[ConfirmationStage] Confirmation response: approved=${X.approved}`),!X.approved){$.abort(`User rejected execution: ${X.reason||"No reason provided"}`,{shouldExitLoop:!0});return}if((X.scope||"once")==="session"&&$._internal.permissionSignature)this.sessionApprovals.add($._internal.permissionSignature)}else B0.warn("⚠️ No ConfirmationHandler; auto-approving tool execution")}catch(Z){$.abort(`User confirmation failed: ${Z.message}`)}}generatePreviewForTool($,b){switch($){case"Edit":{let{old_string:w,new_string:V}=b;if(!w&&!V)return;let W=20,Q=(Z)=>{let Y=Z.split(`
|
|
1759
|
+
`);if(Y.length<=W)return Z;return`${Y.slice(0,W).join(`
|
|
1734
1760
|
`)}
|
|
1735
|
-
... (还有 ${
|
|
1761
|
+
... (还有 ${Y.length-W} 行)`};return`**变更前:**
|
|
1736
1762
|
\`\`\`
|
|
1737
|
-
${
|
|
1763
|
+
${Q(w||"(空)")}
|
|
1738
1764
|
\`\`\`
|
|
1739
1765
|
|
|
1740
1766
|
**变更后:**
|
|
1741
1767
|
\`\`\`
|
|
1742
|
-
${
|
|
1743
|
-
\`\`\``}case"Write":{let
|
|
1744
|
-
`);if(
|
|
1768
|
+
${Q(V||"(删除)")}
|
|
1769
|
+
\`\`\``}case"Write":{let w=b.content,V=b.encoding||"utf8";if(V!=="utf8"||!w)return`将写入 ${V==="base64"?"Base64 编码":V==="binary"?"二进制":""} 内容`;let W=30,Q=w.split(`
|
|
1770
|
+
`);if(Q.length<=W)return`**文件内容预览:**
|
|
1745
1771
|
\`\`\`
|
|
1746
|
-
${
|
|
1747
|
-
\`\`\``;let
|
|
1748
|
-
`);return`**文件内容预览 (前 ${
|
|
1772
|
+
${w}
|
|
1773
|
+
\`\`\``;let Z=Q.slice(0,W).join(`
|
|
1774
|
+
`);return`**文件内容预览 (前 ${W} 行):**
|
|
1749
1775
|
\`\`\`
|
|
1750
|
-
${
|
|
1776
|
+
${Z}
|
|
1751
1777
|
\`\`\`
|
|
1752
1778
|
|
|
1753
|
-
... (还有 ${
|
|
1779
|
+
... (还有 ${Q.length-W} 行)`}default:return}}extractRisksFromPermissionCheck($,b,w){let V=[];if(w?.reason)V.push(w.reason);if($.name==="Bash"){let W=b.command||"",Q=W.trim().split(/\s+/)[0];if(["cat","head","tail"].includes(Q))V.push(`\uD83D\uDCA1 建议使用 Read 工具代替 ${Q} 命令`);else if(["grep","rg"].includes(Q))V.push("\uD83D\uDCA1 建议使用 Grep 工具代替 grep/rg 命令");else if(Q==="find")V.push("\uD83D\uDCA1 建议使用 Glob 工具代替 find 命令");else if(["sed","awk"].includes(Q))V.push(`\uD83D\uDCA1 建议使用 Edit 工具代替 ${Q} 命令`);if(W.includes("rm"))V.push("⚠️ 此命令可能删除文件");if(W.includes("sudo"))V.push("⚠️ 此命令需要管理员权限");if(W.includes("git push"))V.push("⚠️ 此命令将推送代码到远程仓库")}else if(["Write","Edit"].includes($.name))V.push("此操作将修改文件内容");else if($.name==="Delete")V.push("此操作将永久删除文件");return V}}class Ew{name="execution";async process($){let b=$._internal.invocation;if(!b){$.abort("Pre-execution stage failed; cannot run tool");return}try{let w=await b.execute($.context.signal??new AbortController().signal,$.context.onProgress,$.context);$.setResult(w)}catch(w){$.abort(`Tool execution failed: ${w.message}`)}}}class Lw{name="formatting";async process($){try{let b=$.getResult();if(!b.llmContent)b.llmContent="Execution completed";if(!b.displayContent)b.displayContent=b.success?"执行成功":"执行失败";if(!b.metadata)b.metadata={};b.metadata.executionId=$.context.sessionId,b.metadata.toolName=$.toolName,b.metadata.timestamp=Date.now(),$.setResult(b)}catch(b){$.abort(`Result formatting failed: ${b.message}`)}}}class mb extends mV{registry;stages;executionHistory=[];maxHistorySize;sessionApprovals=new Set;constructor($,b={}){super();this.registry=$;this.maxHistorySize=b.maxHistorySize||1000;let w=b.permissionConfig||{allow:[],ask:[],deny:[]},V=b.permissionMode??v.DEFAULT,W=new _w(w,this.sessionApprovals,V);this.stages=[new Hw(this.registry),W,new Cw,new Rw(this.sessionApprovals,W.getPermissionChecker(),b.canUseTool),new Ew,new Aw,new Lw]}async execute($,b,w){let V=Date.now(),W=this.generateExecutionId(),Q=new R1($,b,{...w,sessionId:w.sessionId||W});this.emit("executionStarted",{executionId:W,toolName:$,params:b,context:w,timestamp:V});let Z=this.registry.get($),Y=Z&&!Z.isConcurrencySafe,J=Y&&b.file_path?String(b.file_path):null;if(Y&&J)return e$.getInstance().acquireLock(J,()=>this.executeWithPipeline(Q,W,V));return this.executeWithPipeline(Q,W,V)}async executeWithPipeline($,b,w){try{for(let Q of this.stages){if($.context.signal?.aborted){$.abort("任务已被用户中止");break}if(this.emit("stageStarted",{executionId:b,stageName:Q.name,timestamp:Date.now()}),await Q.process($),this.emit("stageCompleted",{executionId:b,stageName:Q.name,timestamp:Date.now()}),$.shouldAbort())break}let V=$.getResult(),W=Date.now();return this.addToHistory({executionId:b,toolName:$.toolName,params:$.params,result:V,startTime:w,endTime:W,context:$.context}),this.emit("executionCompleted",{executionId:b,toolName:$.toolName,result:V,duration:W-w,timestamp:W}),V}catch(V){let W=Date.now(),Q=V.message?.includes("timeout")||V.name==="TimeoutError",Z={success:!1,llmContent:`Tool execution failed: ${V.message}`,displayContent:`错误: ${V.message}`,error:{type:"execution_error",message:V.message}};try{let J=await r.getInstance().executePostToolUseFailureHooks($.toolName,`tool_use_${b}`,$.params,V.message,{projectDir:process.cwd(),sessionId:$.context.sessionId||"unknown",permissionMode:$.context.permissionMode||v.DEFAULT,isInterrupt:!1,isTimeout:Q,abortSignal:$.context.signal});if(J.additionalContext)Z={...Z,llmContent:`${Z.llmContent}
|
|
1754
1780
|
|
|
1755
|
-
${G.additionalContext}`};if(G.warning)console.warn(`[ExecutionPipeline] PostToolUseFailure hook warning: ${G.warning}`)}catch(X){console.warn("[ExecutionPipeline] PostToolUseFailure hook execution failed:",X)}return this.addToHistory({executionId:V,toolName:$.toolName,params:$.params,result:J,startTime:W,endTime:Z,context:$.context}),this.emit("executionFailed",{executionId:V,toolName:$.toolName,error:Q,duration:Z-W,timestamp:Z}),J}}async executeAll($){let V=$.map((W)=>this.execute(W.toolName,W.params,W.context));return Promise.all(V)}async executeParallel($,V=5){let W=[],Q=[];for(let Z=0;Z<$.length;Z++){let Y=$[Z],J=this.execute(Y.toolName,Y.params,Y.context);if(Q.push(J),Q.length>=V||Z===$.length-1){let X=await Promise.all(Q);W.push(...X),Q.length=0}}return W}getExecutionHistory($){let V=[...this.executionHistory];return $?V.slice(-$):V}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)},V=0;for(let W of this.executionHistory){if(W.result.success)$.successfulExecutions++;else $.failedExecutions++;let Q=W.endTime-W.startTime;V+=Q;let Z=$.toolUsage.get(W.toolName)||0;$.toolUsage.set(W.toolName,Z+1)}return $.averageDuration=$.totalExecutions>0?V/$.totalExecutions:0,$}addStage($,V=-1){if(V===-1){let W=this.stages.findIndex((Q)=>Q.name==="execution");this.stages.splice(W,0,$)}else this.stages.splice(V,0,$);this.emit("stageAdded",{stageName:$.name,position:V,timestamp:Date.now()})}removeStage($){let V=this.stages.findIndex((W)=>W.name===$);if(V===-1)return!1;return this.stages.splice(V,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 m9}from"events";class p0 extends m9{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 V=[];for(let W of $)try{this.register(W)}catch(Q){V.push(`${W.name}: ${Q.message}`)}if(V.length>0)throw Error(`批量注册失败: ${V.join(", ")}`)}unregister($){let V=this.tools.get($);if(!V)return!1;return this.tools.delete($),this.removeFromIndexes(V),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 V=this.categories.get($);if(!V)return[];return Array.from(V).map((W)=>this.get(W)).filter((W)=>W!==void 0)}getByTag($){let V=this.tags.get($);if(!V)return[];return Array.from(V).map((W)=>this.get(W)).filter((W)=>W!==void 0)}search($){let V=$.toLowerCase();return this.getAll().filter((W)=>{let Q=typeof W.description==="string"?W.description:W.description.short;return W.name.toLowerCase().includes(V)||Q.toLowerCase().includes(V)||W.displayName.toLowerCase().includes(V)||W.category&&W.category.toLowerCase().includes(V)||W.tags.some((Z)=>Z.toLowerCase().includes(V))})}getFunctionDeclarations(){return this.getAll().map(($)=>$.getFunctionDeclaration())}getReadOnlyFunctionDeclarations(){return this.getAll().filter(($)=>$.isReadOnly).map(($)=>$.getFunctionDeclaration())}getFunctionDeclarationsByMode($){if($===S.PLAN)return this.getReadOnlyFunctionDeclarations();if($===S.SPEC)return this.getSpecModeFunctionDeclarations();return this.getFunctionDeclarations()}static SPEC_TOOLS=["EnterSpecMode","UpdateSpec","GetSpecContext","TransitionSpecPhase","AddTask","UpdateTaskStatus","ValidateSpec","ExitSpecMode"];getSpecModeFunctionDeclarations(){return this.getFunctionDeclarations()}isSpecTool($){return p0.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(([$,V])=>[$,V.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 V=0,W=`mcp__${$}__`;for(let[Q,Z]of this.mcpTools.entries())if(Q.startsWith(W))this.mcpTools.delete(Q),this.removeFromIndexes(Z),V++,this.emit("toolUnregistered",{type:"mcp",toolName:Q,serverName:$,timestamp:Date.now()});return V}updateIndexes($){if($.category){if(!this.categories.has($.category))this.categories.set($.category,new Set);this.categories.get($.category).add($.name)}for(let V of $.tags){if(!this.tags.has(V))this.tags.set(V,new Set);this.tags.get(V).add($.name)}}removeFromIndexes($){if($.category){let V=this.categories.get($.category);if(V){if(V.delete($.name),V.size===0)this.categories.delete($.category)}}for(let V of $.tags){let W=this.tags.get(V);if(W){if(W.delete($.name),W.size===0)this.tags.delete(V)}}}}var c9=[/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];function i9($){return c9.some((V)=>V.test($))}function l9($){if($.supportsThinking!==void 0)return{supportsThinking:$.supportsThinking,thinkingBudget:$.thinkingBudget};return{supportsThinking:i9($.model),thinkingBudget:void 0}}function a8($){return l9($).supportsThinking}import t8 from"fast-glob";import*as U0 from"fs/promises";import*as e8 from"path";import*as F1 from"fs/promises";import*as e from"path";var o8=[".git",".claude","node_modules",".env",".env.local",".env.production",".env.development",".env.test"];class $0 extends Error{code;constructor($,V){super($);this.code=V;this.name="PathSecurityError"}}class V0{static normalize($,V){let W=e.isAbsolute($)?$:e.resolve(V,$),Q=e.normalize(W),Z=e.normalize(V);if(!Q.startsWith(Z))throw new $0(`Path outside workspace: ${$} (resolved to ${Q}, workspace: ${Z})`,"PATH_OUTSIDE_WORKSPACE");return Q}static checkRestricted($){let V=$.split(e.sep);for(let W of o8)if(V.includes(W))throw new $0(`Access denied: "${W}" is a protected directory`,"RESTRICTED_PATH")}static checkTraversal($){if($.includes(".."))throw new $0(`Path traversal not allowed: ${$}`,"PATH_TRAVERSAL")}static async validatePath($,V){V0.checkTraversal($);let W=V0.normalize($,V);V0.checkRestricted(W);try{await F1.access(W)}catch(Q){throw new $0(`Path not found: ${$}`,"PATH_NOT_FOUND")}return W}static async resolveSymlink($,V){try{let W=await F1.realpath($),Q=e.normalize(V);if(!W.startsWith(Q))throw new $0(`Symlink points outside workspace: ${$} -> ${W}`,"SYMLINK_OUTSIDE_WORKSPACE");return W}catch(W){if(W instanceof $0)throw W;return $}}static getRelativePath($,V){return e.relative(V,$)}static isWithinWorkspace($,V){let W=e.normalize($),Q=e.normalize(V);return W.startsWith(Q)}static isRestricted($){let V=$.split(e.sep);return o8.some((W)=>V.includes(W))}}class w${static PATTERN=/@"([^"]+)"|@([^\s]+)/g;static LINE_RANGE_PATTERN=/#L(\d+)(?:-(\d+))?$/;static GLOB_PATTERN=/[*?[\]]/;static extract($){let V=[],W;w$.PATTERN.lastIndex=0;while((W=w$.PATTERN.exec($))!==null){let Q=W[0],Z=W[1]||W[2],Y=w$.parseLineRange(Z);if(Y)Z=Z.replace(w$.LINE_RANGE_PATTERN,"");let J=w$.GLOB_PATTERN.test(Z);V.push({raw:Q,path:Z.trim(),lineRange:Y,startIndex:W.index,endIndex:W.index+Q.length,isGlob:J})}return V}static parseLineRange($){let V=$.match(w$.LINE_RANGE_PATTERN);if(!V)return;let W=parseInt(V[1],10),Q=V[2]?parseInt(V[2],10):void 0;return{start:W,end:Q}}static hasAtMentions($){return $.includes("@")}static isValidPath($){if(!$||$.trim().length===0)return!1;let V=["<",">","|","\x00"];for(let W of V)if($.includes(W))return!1;return!0}static removeAtMentions($){return w$.PATTERN.lastIndex=0,$.replace(w$.PATTERN,"")}}var _$=T("Prompts");function H1($){return $ instanceof Map}class n2{fileCache=new Map;options;constructor($){this.options={maxFileSize:1048576,maxLines:2000,maxTokens:32000,...$},_$.debug("AttachmentCollector initialized",{maxFileSize:this.options.maxFileSize,maxLines:this.options.maxLines})}async collect($){if(!w$.hasAtMentions($))return[];let V=w$.extract($);if(V.length===0)return[];_$.debug(`Found ${V.length} @ mentions`);let W=V.map((Z)=>this.processOne(Z));return(await Promise.allSettled(W)).map((Z,Y)=>{if(Z.status==="fulfilled")return Z.value;else{let J=V[Y],X=Z.reason instanceof Error?Z.reason.message:String(Z.reason);return _$.warn(`Failed to process @${J.path}:`,X),{type:"error",path:J.path,content:"",error:X}}})}async processOne($){if($.isGlob)return _$.debug(`Processing glob pattern: ${$.path}`),await this.processGlob($.path);let V=await V0.validatePath($.path,this.options.cwd),W=await V0.resolveSymlink(V,this.options.cwd);if((await U0.stat(W)).isDirectory())return _$.debug(`Processing directory: ${$.path}`),await this.renderDirectoryTree(W,$.path);return _$.debug(`Processing file: ${$.path}`,{lineRange:$.lineRange}),await this.readFile(W,$.path,$.lineRange)}async readFile($,V,W){let Q=this.fileCache.get($);if(Q&&Date.now()-Q.timestamp<60000)return _$.debug(`Cache hit: ${V}`),this.formatFileAttachment(V,Q.content,W);let Z=await U0.stat($);if(Z.size>this.options.maxFileSize)throw Error(`File too large: ${Math.round(Z.size/1024/1024)}MB (max ${Math.round(this.options.maxFileSize/1024/1024)}MB)`);let Y;try{Y=await U0.readFile($,"utf-8")}catch(J){throw Error(`Cannot read file as text: ${V}. It may be a binary file.`)}return this.fileCache.set($,{content:Y,timestamp:Date.now()}),this.formatFileAttachment(V,Y,W)}formatFileAttachment($,V,W){let Q=V.split(`
|
|
1756
|
-
`),
|
|
1757
|
-
`);let
|
|
1758
|
-
`).map((
|
|
1759
|
-
`),
|
|
1760
|
-
`),
|
|
1781
|
+
${J.additionalContext}`};if(J.warning)console.warn(`[ExecutionPipeline] PostToolUseFailure hook warning: ${J.warning}`)}catch(Y){console.warn("[ExecutionPipeline] PostToolUseFailure hook execution failed:",Y)}return this.addToHistory({executionId:b,toolName:$.toolName,params:$.params,result:Z,startTime:w,endTime:W,context:$.context}),this.emit("executionFailed",{executionId:b,toolName:$.toolName,error:V,duration:W-w,timestamp:W}),Z}}async executeAll($){let b=$.map((w)=>this.execute(w.toolName,w.params,w.context));return Promise.all(b)}async executeParallel($,b=5){let w=[],V=[];for(let W=0;W<$.length;W++){let Q=$[W],Z=this.execute(Q.toolName,Q.params,Q.context);if(V.push(Z),V.length>=b||W===$.length-1){let Y=await Promise.all(V);w.push(...Y),V.length=0}}return w}getExecutionHistory($){let b=[...this.executionHistory];return $?b.slice(-$):b}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)},b=0;for(let w of this.executionHistory){if(w.result.success)$.successfulExecutions++;else $.failedExecutions++;let V=w.endTime-w.startTime;b+=V;let W=$.toolUsage.get(w.toolName)||0;$.toolUsage.set(w.toolName,W+1)}return $.averageDuration=$.totalExecutions>0?b/$.totalExecutions:0,$}addStage($,b=-1){if(b===-1){let w=this.stages.findIndex((V)=>V.name==="execution");this.stages.splice(w,0,$)}else this.stages.splice(b,0,$);this.emit("stageAdded",{stageName:$.name,position:b,timestamp:Date.now()})}removeStage($){let b=this.stages.findIndex((w)=>w.name===$);if(b===-1)return!1;return this.stages.splice(b,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 cV}from"events";class Qb extends cV{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 b=[];for(let w of $)try{this.register(w)}catch(V){b.push(`${w.name}: ${V.message}`)}if(b.length>0)throw Error(`批量注册失败: ${b.join(", ")}`)}unregister($){let b=this.tools.get($);if(!b)return!1;return this.tools.delete($),this.removeFromIndexes(b),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 b=this.categories.get($);if(!b)return[];return Array.from(b).map((w)=>this.get(w)).filter((w)=>w!==void 0)}getByTag($){let b=this.tags.get($);if(!b)return[];return Array.from(b).map((w)=>this.get(w)).filter((w)=>w!==void 0)}search($){let b=$.toLowerCase();return this.getAll().filter((w)=>{let V=typeof w.description==="string"?w.description:w.description.short;return w.name.toLowerCase().includes(b)||V.toLowerCase().includes(b)||w.displayName.toLowerCase().includes(b)||w.category&&w.category.toLowerCase().includes(b)||w.tags.some((W)=>W.toLowerCase().includes(b))})}getFunctionDeclarations(){return this.getAll().map(($)=>$.getFunctionDeclaration())}getReadOnlyFunctionDeclarations(){return this.getAll().filter(($)=>$.isReadOnly).map(($)=>$.getFunctionDeclaration())}getFunctionDeclarationsByMode($){if($===v.PLAN)return this.getReadOnlyFunctionDeclarations();if($===v.SPEC)return this.getSpecModeFunctionDeclarations();return this.getFunctionDeclarations()}static SPEC_TOOLS=["EnterSpecMode","UpdateSpec","GetSpecContext","TransitionSpecPhase","AddTask","UpdateTaskStatus","ValidateSpec","ExitSpecMode"];getSpecModeFunctionDeclarations(){return this.getFunctionDeclarations()}isSpecTool($){return Qb.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(([$,b])=>[$,b.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 b=0,w=`mcp__${$}__`;for(let[V,W]of this.mcpTools.entries())if(V.startsWith(w))this.mcpTools.delete(V),this.removeFromIndexes(W),b++,this.emit("toolUnregistered",{type:"mcp",toolName:V,serverName:$,timestamp:Date.now()});return b}updateIndexes($){if($.category){if(!this.categories.has($.category))this.categories.set($.category,new Set);this.categories.get($.category).add($.name)}for(let b of $.tags){if(!this.tags.has(b))this.tags.set(b,new Set);this.tags.get(b).add($.name)}}removeFromIndexes($){if($.category){let b=this.categories.get($.category);if(b){if(b.delete($.name),b.size===0)this.categories.delete($.category)}}for(let b of $.tags){let w=this.tags.get(b);if(w){if(w.delete($.name),w.size===0)this.tags.delete(b)}}}}var iV=[/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];function lV($){return iV.some((b)=>b.test($))}function nV($){if($.supportsThinking!==void 0)return{supportsThinking:$.supportsThinking,thinkingBudget:$.thinkingBudget};return{supportsThinking:lV($.model),thinkingBudget:void 0}}function z2($){return nV($).supportsThinking}import v2 from"fast-glob";import*as y0 from"fs/promises";import*as T2 from"path";import*as cb from"fs/promises";import*as V$ from"path";var y2=[".git",".claude","node_modules",".env",".env.local",".env.production",".env.development",".env.test"];class K0 extends Error{code;constructor($,b){super($);this.code=b;this.name="PathSecurityError"}}class q0{static normalize($,b){let w=V$.isAbsolute($)?$:V$.resolve(b,$),V=V$.normalize(w),W=V$.normalize(b);if(!V.startsWith(W))throw new K0(`Path outside workspace: ${$} (resolved to ${V}, workspace: ${W})`,"PATH_OUTSIDE_WORKSPACE");return V}static checkRestricted($){let b=$.split(V$.sep);for(let w of y2)if(b.includes(w))throw new K0(`Access denied: "${w}" is a protected directory`,"RESTRICTED_PATH")}static checkTraversal($){if($.includes(".."))throw new K0(`Path traversal not allowed: ${$}`,"PATH_TRAVERSAL")}static async validatePath($,b){q0.checkTraversal($);let w=q0.normalize($,b);q0.checkRestricted(w);try{await cb.access(w)}catch(V){throw new K0(`Path not found: ${$}`,"PATH_NOT_FOUND")}return w}static async resolveSymlink($,b){try{let w=await cb.realpath($),V=V$.normalize(b);if(!w.startsWith(V))throw new K0(`Symlink points outside workspace: ${$} -> ${w}`,"SYMLINK_OUTSIDE_WORKSPACE");return w}catch(w){if(w instanceof K0)throw w;return $}}static getRelativePath($,b){return V$.relative(b,$)}static isWithinWorkspace($,b){let w=V$.normalize($),V=V$.normalize(b);return w.startsWith(V)}static isRestricted($){let b=$.split(V$.sep);return y2.some((w)=>b.includes(w))}}class L${static PATTERN=/@"([^"]+)"|@([^\s]+)/g;static LINE_RANGE_PATTERN=/#L(\d+)(?:-(\d+))?$/;static GLOB_PATTERN=/[*?[\]]/;static extract($){let b=[],w;L$.PATTERN.lastIndex=0;while((w=L$.PATTERN.exec($))!==null){let V=w[0],W=w[1]||w[2],Q=L$.parseLineRange(W);if(Q)W=W.replace(L$.LINE_RANGE_PATTERN,"");let Z=L$.GLOB_PATTERN.test(W);b.push({raw:V,path:W.trim(),lineRange:Q,startIndex:w.index,endIndex:w.index+V.length,isGlob:Z})}return b}static parseLineRange($){let b=$.match(L$.LINE_RANGE_PATTERN);if(!b)return;let w=parseInt(b[1],10),V=b[2]?parseInt(b[2],10):void 0;return{start:w,end:V}}static hasAtMentions($){return $.includes("@")}static isValidPath($){if(!$||$.trim().length===0)return!1;let b=["<",">","|","\x00"];for(let w of b)if($.includes(w))return!1;return!0}static removeAtMentions($){return L$.PATTERN.lastIndex=0,$.replace(L$.PATTERN,"")}}var z$=z("Prompts");function ib($){return $ instanceof Map}class Dw{fileCache=new Map;options;constructor($){this.options={maxFileSize:1048576,maxLines:2000,maxTokens:32000,...$},z$.debug("AttachmentCollector initialized",{maxFileSize:this.options.maxFileSize,maxLines:this.options.maxLines})}async collect($){if(!L$.hasAtMentions($))return[];let b=L$.extract($);if(b.length===0)return[];z$.debug(`Found ${b.length} @ mentions`);let w=b.map((W)=>this.processOne(W));return(await Promise.allSettled(w)).map((W,Q)=>{if(W.status==="fulfilled")return W.value;else{let Z=b[Q],Y=W.reason instanceof Error?W.reason.message:String(W.reason);return z$.warn(`Failed to process @${Z.path}:`,Y),{type:"error",path:Z.path,content:"",error:Y}}})}async processOne($){if($.isGlob)return z$.debug(`Processing glob pattern: ${$.path}`),await this.processGlob($.path);let b=await q0.validatePath($.path,this.options.cwd),w=await q0.resolveSymlink(b,this.options.cwd);if((await y0.stat(w)).isDirectory())return z$.debug(`Processing directory: ${$.path}`),await this.renderDirectoryTree(w,$.path);return z$.debug(`Processing file: ${$.path}`,{lineRange:$.lineRange}),await this.readFile(w,$.path,$.lineRange)}async readFile($,b,w){let V=this.fileCache.get($);if(V&&Date.now()-V.timestamp<60000)return z$.debug(`Cache hit: ${b}`),this.formatFileAttachment(b,V.content,w);let W=await y0.stat($);if(W.size>this.options.maxFileSize)throw Error(`File too large: ${Math.round(W.size/1024/1024)}MB (max ${Math.round(this.options.maxFileSize/1024/1024)}MB)`);let Q;try{Q=await y0.readFile($,"utf-8")}catch(Z){throw Error(`Cannot read file as text: ${b}. It may be a binary file.`)}return this.fileCache.set($,{content:Q,timestamp:Date.now()}),this.formatFileAttachment(b,Q,w)}formatFileAttachment($,b,w){let V=b.split(`
|
|
1782
|
+
`),W=b,Q=!1,Z=w;if(w){let Y=Math.max(0,w.start-1),J=w.end?w.end:w.start;if(Y>=V.length)throw Error(`Line range start (${w.start}) exceeds file length (${V.length} lines)`);let X=Math.min(J,V.length);W=V.slice(Y,X).join(`
|
|
1783
|
+
`);let O=Array.from({length:X-Y},(B,q)=>Y+q+1);W=W.split(`
|
|
1784
|
+
`).map((B,q)=>`${O[q]}: ${B}`).join(`
|
|
1785
|
+
`),Z={start:w.start,end:X}}else if(V.length>this.options.maxLines)W=V.slice(0,this.options.maxLines).join(`
|
|
1786
|
+
`),W+=`
|
|
1761
1787
|
|
|
1762
|
-
[... truncated ${
|
|
1788
|
+
[... truncated ${V.length-this.options.maxLines} lines ...]`,Q=!0;return{type:"file",path:$,content:W,metadata:{size:b.length,lines:V.length,truncated:Q,lineRange:Z}}}async renderDirectoryTree($,b){let w=await v2("**/*",{cwd:$,dot:!1,followSymbolicLinks:!1,onlyFiles:!0,unique:!0,ignore:["node_modules/**",".git/**","dist/**","build/**",".next/**",".cache/**","coverage/**"]});if(w.length===0)return{type:"directory",path:b,content:"(empty directory)"};z$.debug(`Found ${w.length} files in directory: ${b}`);let V=this.buildFileTree(w),W=this.printTree(V,b),Q=500,Z=w.length>Q?`
|
|
1763
1789
|
|
|
1764
|
-
[... and ${
|
|
1765
|
-
`)}async processGlob($){let
|
|
1766
|
-
`),
|
|
1767
|
-
`),
|
|
1790
|
+
[... and ${w.length-Q} more files]`:"";return{type:"directory",path:b,content:W+Z,metadata:{lines:w.length,truncated:w.length>Q}}}buildFileTree($){let b=new Map;for(let w of $){let V=o0(w),W=b;for(let Q=0;Q<V.length;Q++){let Z=V[Q],Y=Q===V.length-1;if(!W.has(Z))W.set(Z,Y?null:new Map);if(!Y){let J=W.get(Z);if(J&&ib(J))W=J}}}return b}printTree($,b,w="",V=!0){let W=[];if(w==="")W.push(`${b}/`);let Q=Array.from($.entries()).sort((Z,Y)=>{let J=ib(Z[1]),X=ib(Y[1]);if(J!==X)return X?1:-1;return Z[0].localeCompare(Y[0])});return Q.forEach(([Z,Y],J)=>{let X=J===Q.length-1,O=X?"└── ":"├── ",G=ib(Y);if(W.push(`${w}${O}${Z}${G?"/":""}`),G&&Y.size>0){let B=w+(X?" ":"│ ");W.push(this.printTree(Y,"",B,X))}}),W.filter((Z)=>Z).join(`
|
|
1791
|
+
`)}async processGlob($){let b=await v2($,{cwd:this.options.cwd,dot:!1,followSymbolicLinks:!1,onlyFiles:!0,unique:!0,ignore:["node_modules/**",".git/**","dist/**","build/**",".next/**",".cache/**","coverage/**"]});if(b.length===0)return{type:"error",path:$,content:"",error:`No files matched pattern: ${$}`};z$.debug(`Glob pattern "${$}" matched ${b.length} files`);let w=30,V=b.slice(0,w),Q=(await Promise.allSettled(V.map(async(X)=>{let O=T2.join(this.options.cwd,X);try{let G=await y0.readFile(O,"utf-8"),B=G.split(`
|
|
1792
|
+
`),q=200,A=G,K=!1;if(B.length>200)A=B.slice(0,200).join(`
|
|
1793
|
+
`),A+=`
|
|
1768
1794
|
|
|
1769
|
-
[... truncated ${
|
|
1770
|
-
${
|
|
1795
|
+
[... truncated ${B.length-200} lines ...]`,K=!0;return{path:X,content:A,lines:B.length,truncated:K}}catch(G){return{path:X,content:`[Error: ${G instanceof Error?G.message:"unknown error"}]`,lines:0,truncated:!1}}}))).map((X)=>X.status==="fulfilled"?X.value:null).filter((X)=>X!==null),Y=Q.map((X)=>`--- ${X.path} (${X.lines} lines${X.truncated?", truncated":""}) ---
|
|
1796
|
+
${X.content}`).join(`
|
|
1771
1797
|
|
|
1772
|
-
`),
|
|
1798
|
+
`),J=b.length>w?`
|
|
1773
1799
|
|
|
1774
|
-
[... and ${
|
|
1775
|
-
`);try{let
|
|
1800
|
+
[... and ${b.length-w} more files matched]`:"";return{type:"file",path:$,content:Y+J,metadata:{lines:Q.reduce((X,O)=>X+O.lines,0),truncated:b.length>w||Q.some((X)=>X.truncated)}}}clearExpiredCache(){let $=Date.now(),b=0;for(let[w,V]of this.fileCache.entries())if($-V.timestamp>60000)this.fileCache.delete(w),b++;if(b>0)z$.debug(`Cleared ${b} expired cache entries`)}clearCache(){this.fileCache.clear(),z$.debug("Cleared all cache")}getCacheStats(){return{size:this.fileCache.size,keys:Array.from(this.fileCache.keys())}}}var lb=z("Agent");class jw{attachmentCollector;constructor($){this.attachmentCollector=new Dw({cwd:$,maxFileSize:1048576,maxLines:2000,maxTokens:32000})}async processAtMentionsForContent($){if(typeof $==="string")return this.processAtMentions($);let b=[];for(let V of $)if(V.type==="text")b.push(V.text);if(b.length===0)return $;let w=b.join(`
|
|
1801
|
+
`);try{let V=await this.attachmentCollector.collect(w);if(V.length===0)return $;lb.debug(`✅ Processed ${V.length} @ file mentions in multimodal message`);let W=this.buildAttachmentText(V);if(!W)return $;return[...$,{type:"text",text:W}]}catch(V){return lb.error("Failed to process @ mentions in multimodal message:",V),$}}buildAttachmentText($){let b=[],w=[];for(let W of $)if(W.type==="file"){let Q=W.metadata?.lineRange?` (lines ${W.metadata.lineRange.start}${W.metadata.lineRange.end?`-${W.metadata.lineRange.end}`:""})`:"";b.push(`<file path="${W.path}"${Q?` range="${Q}"`:""}>`,W.content,"</file>")}else if(W.type==="directory")b.push(`<directory path="${W.path}">`,W.content,"</directory>");else if(W.type==="error")w.push(`- @${W.path}: ${W.error}`);let V="";if(b.length>0)V+=`
|
|
1776
1802
|
|
|
1777
1803
|
<system-reminder>
|
|
1778
|
-
`,
|
|
1804
|
+
`,V+=`The following files were mentioned with @ syntax:
|
|
1779
1805
|
|
|
1780
|
-
`,
|
|
1781
|
-
`),
|
|
1782
|
-
</system-reminder>`;if(
|
|
1806
|
+
`,V+=b.join(`
|
|
1807
|
+
`),V+=`
|
|
1808
|
+
</system-reminder>`;if(w.length>0)V+=`
|
|
1783
1809
|
|
|
1784
1810
|
⚠️ Some files could not be loaded:
|
|
1785
|
-
`,
|
|
1786
|
-
`);return
|
|
1811
|
+
`,V+=w.join(`
|
|
1812
|
+
`);return V}async processAtMentions($){try{let b=await this.attachmentCollector.collect($);if(b.length===0)return $;return lb.debug(`✅ Processed ${b.length} @ file mentions`),this.appendAttachments($,b)}catch(b){return lb.error("Failed to process @ mentions:",b),$}}appendAttachments($,b){let w=[],V=[];for(let Q of b)if(Q.type==="file"){let Z=Q.metadata?.lineRange?` (lines ${Q.metadata.lineRange.start}${Q.metadata.lineRange.end?`-${Q.metadata.lineRange.end}`:""})`:"";w.push(`<file path="${Q.path}"${Z?` range="${Z}"`:""}>`,Q.content,"</file>")}else if(Q.type==="directory")w.push(`<directory path="${Q.path}">`,Q.content,"</directory>");else if(Q.type==="error")V.push(`- @${Q.path}: ${Q.error}`);let W=$;if(w.length>0)W+=`
|
|
1787
1813
|
|
|
1788
1814
|
<system-reminder>
|
|
1789
|
-
`,
|
|
1815
|
+
`,W+=`The following files were mentioned with @ syntax:
|
|
1790
1816
|
|
|
1791
|
-
`,
|
|
1792
|
-
`),
|
|
1793
|
-
</system-reminder>`;if(
|
|
1817
|
+
`,W+=w.join(`
|
|
1818
|
+
`),W+=`
|
|
1819
|
+
</system-reminder>`;if(V.length>0)W+=`
|
|
1794
1820
|
|
|
1795
1821
|
⚠️ Some files could not be loaded:
|
|
1796
|
-
`,
|
|
1797
|
-
`);return
|
|
1822
|
+
`,W+=V.join(`
|
|
1823
|
+
`);return W}}var D$=z("Agent");class Nw{getChatService;getContextManager;constructor($,b){this.getChatService=$;this.getContextManager=b}async*checkAndCompactInLoop($,b,w){if(w===void 0)return D$.debug(`[Agent] [轮次 ${b}] 压缩检查: 跳过(无历史 usage 数据)`),!1;let W=this.getChatService().getConfig(),Q=W.model,Z=W.maxContextTokens??128000,Y=W.maxOutputTokens??8192,J=Z-Y,X=Math.floor(J*0.8);if(D$.debug(`[Agent] [轮次 ${b}] 压缩检查:`,{promptTokens:w,maxContextTokens:Z,maxOutputTokens:Y,availableForInput:J,threshold:X,shouldCompact:w>=X}),w<X)return!1;let O=b===0?"[Agent] 触发自动压缩":`[Agent] [轮次 ${b}] 触发循环内自动压缩`;D$.debug(O),yield{type:"compacting",isCompacting:!0};try{let G=await b$.compact($.messages,{trigger:"auto",modelName:Q,maxContextTokens:Z,apiKey:W.apiKey,baseURL:W.baseUrl,actualPreTokens:w});if(G.success)$.messages=G.compactedMessages,D$.debug(`[Agent] [轮次 ${b}] 压缩完成: ${G.preTokens} → ${G.postTokens} tokens (-${((1-G.postTokens/G.preTokens)*100).toFixed(1)}%)`);else $.messages=G.compactedMessages,D$.warn(`[Agent] [轮次 ${b}] 压缩使用降级策略: ${G.preTokens} → ${G.postTokens} tokens`);try{let B=this.getContextManager();if(B&&$.sessionId)await B.saveCompaction($.sessionId,G.summary,{trigger:"auto",preTokens:G.preTokens,postTokens:G.postTokens,filesIncluded:G.filesIncluded},null),D$.debug(`[Agent] [轮次 ${b}] 压缩数据已保存到 JSONL`)}catch(B){D$.warn(`[Agent] [轮次 ${b}] 保存压缩数据失败:`,B)}return yield{type:"compacting",isCompacting:!1},!0}catch(G){return yield{type:"compacting",isCompacting:!1},D$.error(`[Agent] [轮次 ${b}] 压缩失败,继续执行`,G),!1}}async compactOnTurnLimit($,b,w){try{let W=this.getChatService().getConfig(),Q=await b$.compact($.messages,{trigger:"auto",modelName:W.model,maxContextTokens:W.maxContextTokens??128000,apiKey:W.apiKey,baseURL:W.baseUrl,actualPreTokens:w});$.messages=Q.compactedMessages;let Z=b.find((X)=>X.role==="system"),Y=[];if(Z)Y.push(Z);Y.push(...$.messages);let J={role:"user",content:`This session is being continued from a previous conversation. The conversation is summarized above.
|
|
1798
1824
|
|
|
1799
|
-
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.`};X.push(G),$.messages.push(G);try{let B=this.getContextManager();if(B&&$.sessionId)await B.saveCompaction($.sessionId,Y.summary,{trigger:"auto",preTokens:Y.preTokens,postTokens:Y.postTokens,filesIncluded:Y.filesIncluded},null)}catch(B){U$.warn("[Agent] 保存压缩数据失败:",B)}return U$.info(`✅ 上下文已压缩 (${Y.preTokens} → ${Y.postTokens} tokens),重置轮次计数`),{success:!0,messages:X}}catch(Q){U$.error("[Agent] 压缩失败,使用降级策略:",Q);let Z=V.find((X)=>X.role==="system"),Y=V.slice(-80),J=[];if(Z&&!Y.some((X)=>X.role==="system"))J.push(Z);return J.push(...Y),$.messages=J.filter((X)=>X.role!=="system"),U$.warn(`⚠️ 降级压缩完成,保留 ${J.length} 条消息`),{success:!1,messages:J}}}}import*as W5 from"crypto";import{nanoid as V5}from"nanoid";class a2{maxSummaryLength;keyPointsLimit;recentMessagesLimit;constructor($=500,V=10,W=20){this.maxSummaryLength=$,this.keyPointsLimit=V,this.recentMessagesLimit=W}async compress($){let V=$.layers.conversation.messages,W=$.layers.tool.recentCalls,Q=V.filter((q)=>q.role==="system"),Z=V.filter((q)=>q.role!=="system"),Y=this.getRecentMessages(Z),J=Z.slice(0,-this.recentMessagesLimit),X=await this.generateSummary(J),G=this.extractKeyPoints(J,W),B=this.generateToolSummary(W),K=this.estimateTokenCount(X,G,Y,B);return{summary:X,keyPoints:G,recentMessages:[...Q,...Y],toolSummary:B,tokenCount:K}}getRecentMessages($){return $.slice(-this.recentMessagesLimit)}async generateSummary($){if($.length===0)return"";let V=new Set,W=new Set,Q=new Set;for(let Y of $){let J=Y.content.toLowerCase();["关于","讨论","问题","项目","功能","需求"].forEach((K)=>{if(J.includes(K)){let q=this.extractContext(J,K,50);if(q)V.add(q)}}),["创建","删除","修改","更新","实现","开发"].forEach((K)=>{if(J.includes(K)){let q=this.extractContext(J,K,30);if(q)W.add(q)}}),["决定","选择","确定","采用","使用"].forEach((K)=>{if(J.includes(K)){let q=this.extractContext(J,K,40);if(q)Q.add(q)}})}let Z=`对话涉及 ${$.length} 条消息。`;if(V.size>0)Z+=` 主要讨论:${Array.from(V).slice(0,3).join("、")}。`;if(W.size>0)Z+=` 执行操作:${Array.from(W).slice(0,3).join("、")}。`;if(Q.size>0)Z+=` 关键决策:${Array.from(Q).slice(0,2).join("、")}。`;return Z.length>this.maxSummaryLength?Z.substring(0,this.maxSummaryLength)+"...":Z}extractKeyPoints($,V){let W=new Set;for(let Z of $)if(Z.role==="user")this.extractQuestions(Z.content).forEach((X)=>W.add(`用户问题:${X}`)),this.extractRequests(Z.content).forEach((X)=>W.add(`用户请求:${X}`));else if(Z.role==="assistant")this.extractSolutions(Z.content).forEach((J)=>W.add(`解决方案:${J}`));return this.summarizeToolUsage(V).forEach((Z)=>W.add(`工具使用:${Z}`)),Array.from(W).slice(0,this.keyPointsLimit)}generateToolSummary($){if($.length===0)return"";let V=new Map,W=Date.now()-600000;for(let Z of $){let Y=V.get(Z.name)||{count:0,success:0,recent:0};if(Y.count++,Z.status==="success")Y.success++;if(Z.timestamp>W)Y.recent++;V.set(Z.name,Y)}let Q=[];for(let[Z,Y]of Array.from(V.entries())){let J=Math.round(Y.success/Y.count*100);Q.push(`${Z}(${Y.count}次,成功率${J}%)`)}return`工具调用:${Q.join("、")}`}estimateTokenCount($,V,W,Q){let Z=$.length+V.join(" ").length;if(Q)Z+=Q.length;for(let Y of W)Z+=Y.content.length;return Math.ceil(Z/4)}extractContext($,V,W){let Q=$.indexOf(V);if(Q===-1)return null;let Z=Math.max(0,Q-W/2),Y=Math.min($.length,Q+W/2);return $.substring(Z,Y).trim()}extractQuestions($){let V=[],W=["?","?","如何","怎么","什么","为什么"],Q=$.split(/[。!.!]/);for(let Z of Q)if(W.some((Y)=>Z.includes(Y))){let Y=Z.trim();if(Y.length>5&&Y.length<100)V.push(Y)}return V.slice(0,3)}extractRequests($){let V=[],W=["请","帮我","需要","想要","希望","能否"],Q=$.split(/[。!.!]/);for(let Z of Q)if(W.some((Y)=>Z.includes(Y))){let Y=Z.trim();if(Y.length>5&&Y.length<100)V.push(Y)}return V.slice(0,3)}extractSolutions($){let V=[],W=["可以","建议","推荐","应该","最好","解决方案"],Q=$.split(/[。!.!]/);for(let Z of Q)if(W.some((Y)=>Z.includes(Y))){let Y=Z.trim();if(Y.length>10&&Y.length<150)V.push(Y)}return V.slice(0,3)}summarizeToolUsage($){let V=[],W=$.filter((Q)=>Date.now()-Q.timestamp<1800000);if(W.length>0){let Q=new Map;W.forEach((Z)=>{let Y=Q.get(Z.name)||[];Y.push(Z),Q.set(Z.name,Y)});for(let[Z,Y]of Array.from(Q.entries())){let J=Y.filter((X)=>X.status==="success").length;V.push(`${Z}(${Y.length}次,${J}成功)`)}}return V.slice(0,5)}shouldCompress($,V){return this.estimateCurrentTokens($)>V*0.8}estimateCurrentTokens($){let W=$.layers.conversation.messages.reduce((Q,Z)=>Q+Z.content.length,0);return Math.ceil(W/4)}}class W0{defaultOptions;constructor($){this.defaultOptions={maxTokens:32000,maxMessages:50,timeWindow:86400000,priority:1,includeTools:!0,includeWorkspace:!0,...$}}filter($,V){let W={...this.defaultOptions,...V},Q={layers:{system:$.layers.system,session:$.layers.session,conversation:this.filterConversation($.layers.conversation,W),tool:W.includeTools?this.filterTools($.layers.tool,W):{recentCalls:[],toolStates:{},dependencies:{}},workspace:W.includeWorkspace?$.layers.workspace:{currentFiles:[],recentFiles:[],environment:{}}},metadata:{...$.metadata,lastUpdated:Date.now()}};return Q.metadata.totalTokens=this.estimateTokens(Q),Q}filterConversation($,V){let W=[...$.messages];if(V.timeWindow>0){let Q=Date.now()-V.timeWindow;W=W.filter((Z)=>Z.timestamp>=Q||Z.role==="system")}if(V.priority>1)W=this.filterByPriority(W,V.priority);if(V.maxMessages>0)W=this.limitMessages(W,V.maxMessages);if(V.maxTokens>0)W=this.limitByTokens(W,V.maxTokens);return{messages:W,summary:$.summary,topics:this.updateTopics(W,$.topics),lastActivity:$.lastActivity}}filterTools($,V){let W=[...$.recentCalls];if(V.timeWindow>0){let G=Date.now()-V.timeWindow;W=W.filter((B)=>B.timestamp>=G)}let Q=W.filter((G)=>G.status==="success"),Z=W.filter((G)=>G.status==="error"),Y=Math.min(20,Q.length),J=Math.min(10,Z.length);return{recentCalls:[...Q.slice(-Y),...Z.slice(-J)].sort((G,B)=>G.timestamp-B.timestamp),toolStates:$.toolStates,dependencies:$.dependencies}}filterByPriority($,V){return $.filter((W)=>{if(W.role==="system")return!0;return this.calculateMessagePriority(W)>=V})}calculateMessagePriority($){let V=1;if($.role==="system")V+=3;else if($.role==="assistant")V+=1;let W=$.content.toLowerCase();if(["错误","警告","重要","关键","问题","解决"].some((Y)=>W.includes(Y)))V+=2;if(W.includes("```")||W.includes("function")||W.includes("class"))V+=1;let Z=(Date.now()-$.timestamp)/3600000;if(Z<1)V+=2;else if(Z<6)V+=1;return V}limitMessages($,V){if($.length<=V)return $;let W=$.filter((J)=>J.role==="system"),Q=$.filter((J)=>J.role!=="system"),Z=V-W.length,Y=Z>0?Q.slice(-Z):[];return[...W,...Y].sort((J,X)=>J.timestamp-X.timestamp)}limitByTokens($,V){if(V<=0)return $;let W=0,Q=[];for(let Z=$.length-1;Z>=0;Z--){let Y=$[Z],J=this.estimateMessageTokens(Y);if(Y.role==="system")if(W+J<=V)Q.unshift(Y),W+=J;else{let X=this.compressMessage(Y,V-W);Q.unshift(X),W+=this.estimateMessageTokens(X)}else if(W+J<=V)Q.unshift(Y),W+=J;else break}return Q.sort((Z,Y)=>Z.timestamp-Y.timestamp)}estimateMessageTokens($){return Math.ceil($.content.length/4)}compressMessage($,V){let W=V*4;if($.content.length<=W)return $;let Q=$.content.substring(0,W-3)+"...";return{...$,content:Q,metadata:{...$.metadata,compressed:!0,originalLength:$.content.length}}}updateTopics($,V){let W=new Set(V);for(let Q of $)this.extractTopicsFromMessage(Q).forEach((Y)=>W.add(Y));return Array.from(W).slice(0,10)}extractTopicsFromMessage($){let V=$.content.toLowerCase(),W=[];return["项目","功能","模块","组件","服务","接口","数据库","前端","后端","算法","架构","设计"].forEach((Z)=>{if(V.includes(Z))W.push(Z)}),W}estimateTokens($){let V=0;for(let Q of $.layers.conversation.messages)V+=this.estimateMessageTokens(Q);let W=JSON.stringify($.layers.system);if(V+=Math.ceil(W.length/4),$.layers.tool.recentCalls.length>0){let Q=JSON.stringify($.layers.tool);V+=Math.ceil(Q.length/8)}return V}static createPresets(){return{lightweight:new W0({maxTokens:1000,maxMessages:10,timeWindow:7200000,includeTools:!1,includeWorkspace:!1}),standard:new W0({maxTokens:4000,maxMessages:30,timeWindow:43200000,includeTools:!0,includeWorkspace:!0}),comprehensive:new W0({maxTokens:8000,maxMessages:100,timeWindow:86400000,includeTools:!0,includeWorkspace:!0}),debug:new W0({maxTokens:2000,maxMessages:20,timeWindow:21600000,priority:2,includeTools:!0,includeWorkspace:!1})}}}class o2{cache=new Map;maxSize;defaultTTL;constructor($=100,V=300000){this.maxSize=$,this.defaultTTL=V}set($,V,W){let Q=Date.now(),Z={data:V,timestamp:Q,accessCount:0,lastAccess:Q,ttl:W||this.defaultTTL};if(this.cache.size>=this.maxSize&&!this.cache.has($))this.evictLeastUsed();this.cache.set($,Z)}get($){let V=this.cache.get($);if(!V)return null;let W=Date.now();if(W-V.timestamp>V.ttl)return this.cache.delete($),null;return V.accessCount++,V.lastAccess=W,V.data}has($){let V=this.cache.get($);if(!V)return!1;if(Date.now()-V.timestamp>V.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($,V,W){let Q=`summary:${$}:${V.length}`;this.set(Q,{summary:W,messageCount:V.length,lastMessage:V[V.length-1]?.timestamp||0},600000)}getMessageSummary($,V){let W=`summary:${$}:${V}`;return this.get(W)}cacheToolResult($,V,W){let Q=this.hashInput(V),Z=`tool:${$}:${Q}`;this.set(Z,W,1800000)}getToolResult($,V){let W=this.hashInput(V),Q=`tool:${$}:${W}`;return this.get(Q)}cacheCompressedContext($,V){let W=`compressed:${$}`;this.set(W,V,900000)}getCompressedContext($){let V=`compressed:${$}`;return this.get(V)}getStats(){this.cleanExpired();let $=0,V=0,W=[];for(let[Q,Z]of Array.from(this.cache.entries()))$+=Z.accessCount,V+=this.estimateItemSize(Z),W.push({key:Q,accessCount:Z.accessCount,lastAccess:Z.lastAccess});return W.sort((Q,Z)=>Z.accessCount-Q.accessCount),{size:this.cache.size,maxSize:this.maxSize,hitRate:$>0?$/($+this.cache.size):0,memoryUsage:V,topKeys:W.slice(0,10)}}cleanExpired(){let $=Date.now(),V=[];for(let[W,Q]of Array.from(this.cache.entries()))if($-Q.timestamp>Q.ttl)V.push(W);V.forEach((W)=>this.cache.delete(W))}evictLeastUsed(){let $=null,V=1/0,W=Date.now();for(let[Q,Z]of Array.from(this.cache.entries())){let Y=1/(W-Z.lastAccess+1),J=Z.accessCount,X=Y*J;if(X<V)V=X,$=Q}if($)this.cache.delete($)}hashInput($){let V=JSON.stringify($),W=0;for(let Q=0;Q<V.length;Q++){let Z=V.charCodeAt(Q);W=(W<<5)-W+Z,W=W&W}return Math.abs(W).toString(36)}estimateItemSize($){try{return JSON.stringify($).length*2}catch{return 1000}}setTTL($,V){let W=this.cache.get($);if(W)return W.ttl=V,W.timestamp=Date.now(),!0;return!1}getRemainingTTL($){let V=this.cache.get($);if(!V)return-1;let W=V.ttl-(Date.now()-V.timestamp);return Math.max(0,W)}warmup($){$.forEach(({key:V,value:W,ttl:Q})=>{this.set(V,W,Q)})}}class t2{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 V=this.contextData.layers.conversation.messages;return this.recordAccess("messages"),V.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($,V){if(!this.contextData)throw Error("上下文数据未初始化");this.contextData.layers.tool.toolStates[$]=V,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 V=Math.floor(this.maxSize*0.8);this.contextData.layers.conversation.messages=$.slice(-V)}}getMemoryUsage(){if(!this.contextData)return 0;return JSON.stringify(this.contextData).length}}import{nanoid as z$}from"nanoid";import*as y$ from"node:fs/promises";import*as $5 from"node:path";import*as _1 from"node:fs";import{createReadStream as n9}from"node:fs";import*as $$ from"node:fs/promises";import*as e2 from"node:path";import{createInterface as r9}from"node:readline";class Y${filePath;constructor($){this.filePath=$}async append($){try{await $$.mkdir(e2.dirname(this.filePath),{recursive:!0,mode:493});let V=JSON.stringify($)+`
|
|
1800
|
-
`;await
|
|
1825
|
+
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.`};Y.push(J),$.messages.push(J);try{let X=this.getContextManager();if(X&&$.sessionId)await X.saveCompaction($.sessionId,Q.summary,{trigger:"auto",preTokens:Q.preTokens,postTokens:Q.postTokens,filesIncluded:Q.filesIncluded},null)}catch(X){D$.warn("[Agent] 保存压缩数据失败:",X)}return D$.info(`✅ 上下文已压缩 (${Q.preTokens} → ${Q.postTokens} tokens),重置轮次计数`),{success:!0,messages:Y}}catch(V){D$.error("[Agent] 压缩失败,使用降级策略:",V);let W=b.find((Y)=>Y.role==="system"),Q=b.slice(-80),Z=[];if(W&&!Q.some((Y)=>Y.role==="system"))Z.push(W);return Z.push(...Q),$.messages=Z.filter((Y)=>Y.role!=="system"),D$.warn(`⚠️ 降级压缩完成,保留 ${Z.length} 条消息`),{success:!1,messages:Z}}}}import*as I2 from"crypto";import{nanoid as f2}from"nanoid";class Sw{maxSummaryLength;keyPointsLimit;recentMessagesLimit;constructor($=500,b=10,w=20){this.maxSummaryLength=$,this.keyPointsLimit=b,this.recentMessagesLimit=w}async compress($){let b=$.layers.conversation.messages,w=$.layers.tool.recentCalls,V=b.filter((G)=>G.role==="system"),W=b.filter((G)=>G.role!=="system"),Q=this.getRecentMessages(W),Z=W.slice(0,-this.recentMessagesLimit),Y=await this.generateSummary(Z),J=this.extractKeyPoints(Z,w),X=this.generateToolSummary(w),O=this.estimateTokenCount(Y,J,Q,X);return{summary:Y,keyPoints:J,recentMessages:[...V,...Q],toolSummary:X,tokenCount:O}}getRecentMessages($){return $.slice(-this.recentMessagesLimit)}async generateSummary($){if($.length===0)return"";let b=new Set,w=new Set,V=new Set;for(let Q of $){let Z=Q.content.toLowerCase();["关于","讨论","问题","项目","功能","需求"].forEach((O)=>{if(Z.includes(O)){let G=this.extractContext(Z,O,50);if(G)b.add(G)}}),["创建","删除","修改","更新","实现","开发"].forEach((O)=>{if(Z.includes(O)){let G=this.extractContext(Z,O,30);if(G)w.add(G)}}),["决定","选择","确定","采用","使用"].forEach((O)=>{if(Z.includes(O)){let G=this.extractContext(Z,O,40);if(G)V.add(G)}})}let W=`对话涉及 ${$.length} 条消息。`;if(b.size>0)W+=` 主要讨论:${Array.from(b).slice(0,3).join("、")}。`;if(w.size>0)W+=` 执行操作:${Array.from(w).slice(0,3).join("、")}。`;if(V.size>0)W+=` 关键决策:${Array.from(V).slice(0,2).join("、")}。`;return W.length>this.maxSummaryLength?W.substring(0,this.maxSummaryLength)+"...":W}extractKeyPoints($,b){let w=new Set;for(let W of $)if(W.role==="user")this.extractQuestions(W.content).forEach((Y)=>w.add(`用户问题:${Y}`)),this.extractRequests(W.content).forEach((Y)=>w.add(`用户请求:${Y}`));else if(W.role==="assistant")this.extractSolutions(W.content).forEach((Z)=>w.add(`解决方案:${Z}`));return this.summarizeToolUsage(b).forEach((W)=>w.add(`工具使用:${W}`)),Array.from(w).slice(0,this.keyPointsLimit)}generateToolSummary($){if($.length===0)return"";let b=new Map,w=Date.now()-600000;for(let W of $){let Q=b.get(W.name)||{count:0,success:0,recent:0};if(Q.count++,W.status==="success")Q.success++;if(W.timestamp>w)Q.recent++;b.set(W.name,Q)}let V=[];for(let[W,Q]of Array.from(b.entries())){let Z=Math.round(Q.success/Q.count*100);V.push(`${W}(${Q.count}次,成功率${Z}%)`)}return`工具调用:${V.join("、")}`}estimateTokenCount($,b,w,V){let W=$.length+b.join(" ").length;if(V)W+=V.length;for(let Q of w)W+=Q.content.length;return Math.ceil(W/4)}extractContext($,b,w){let V=$.indexOf(b);if(V===-1)return null;let W=Math.max(0,V-w/2),Q=Math.min($.length,V+w/2);return $.substring(W,Q).trim()}extractQuestions($){let b=[],w=["?","?","如何","怎么","什么","为什么"],V=$.split(/[。!.!]/);for(let W of V)if(w.some((Q)=>W.includes(Q))){let Q=W.trim();if(Q.length>5&&Q.length<100)b.push(Q)}return b.slice(0,3)}extractRequests($){let b=[],w=["请","帮我","需要","想要","希望","能否"],V=$.split(/[。!.!]/);for(let W of V)if(w.some((Q)=>W.includes(Q))){let Q=W.trim();if(Q.length>5&&Q.length<100)b.push(Q)}return b.slice(0,3)}extractSolutions($){let b=[],w=["可以","建议","推荐","应该","最好","解决方案"],V=$.split(/[。!.!]/);for(let W of V)if(w.some((Q)=>W.includes(Q))){let Q=W.trim();if(Q.length>10&&Q.length<150)b.push(Q)}return b.slice(0,3)}summarizeToolUsage($){let b=[],w=$.filter((V)=>Date.now()-V.timestamp<1800000);if(w.length>0){let V=new Map;w.forEach((W)=>{let Q=V.get(W.name)||[];Q.push(W),V.set(W.name,Q)});for(let[W,Q]of Array.from(V.entries())){let Z=Q.filter((Y)=>Y.status==="success").length;b.push(`${W}(${Q.length}次,${Z}成功)`)}}return b.slice(0,5)}shouldCompress($,b){return this.estimateCurrentTokens($)>b*0.8}estimateCurrentTokens($){let w=$.layers.conversation.messages.reduce((V,W)=>V+W.content.length,0);return Math.ceil(w/4)}}class C0{defaultOptions;constructor($){this.defaultOptions={maxTokens:32000,maxMessages:50,timeWindow:86400000,priority:1,includeTools:!0,includeWorkspace:!0,...$}}filter($,b){let w={...this.defaultOptions,...b},V={layers:{system:$.layers.system,session:$.layers.session,conversation:this.filterConversation($.layers.conversation,w),tool:w.includeTools?this.filterTools($.layers.tool,w):{recentCalls:[],toolStates:{},dependencies:{}},workspace:w.includeWorkspace?$.layers.workspace:{currentFiles:[],recentFiles:[],environment:{}}},metadata:{...$.metadata,lastUpdated:Date.now()}};return V.metadata.totalTokens=this.estimateTokens(V),V}filterConversation($,b){let w=[...$.messages];if(b.timeWindow>0){let V=Date.now()-b.timeWindow;w=w.filter((W)=>W.timestamp>=V||W.role==="system")}if(b.priority>1)w=this.filterByPriority(w,b.priority);if(b.maxMessages>0)w=this.limitMessages(w,b.maxMessages);if(b.maxTokens>0)w=this.limitByTokens(w,b.maxTokens);return{messages:w,summary:$.summary,topics:this.updateTopics(w,$.topics),lastActivity:$.lastActivity}}filterTools($,b){let w=[...$.recentCalls];if(b.timeWindow>0){let J=Date.now()-b.timeWindow;w=w.filter((X)=>X.timestamp>=J)}let V=w.filter((J)=>J.status==="success"),W=w.filter((J)=>J.status==="error"),Q=Math.min(20,V.length),Z=Math.min(10,W.length);return{recentCalls:[...V.slice(-Q),...W.slice(-Z)].sort((J,X)=>J.timestamp-X.timestamp),toolStates:$.toolStates,dependencies:$.dependencies}}filterByPriority($,b){return $.filter((w)=>{if(w.role==="system")return!0;return this.calculateMessagePriority(w)>=b})}calculateMessagePriority($){let b=1;if($.role==="system")b+=3;else if($.role==="assistant")b+=1;let w=$.content.toLowerCase();if(["错误","警告","重要","关键","问题","解决"].some((Q)=>w.includes(Q)))b+=2;if(w.includes("```")||w.includes("function")||w.includes("class"))b+=1;let W=(Date.now()-$.timestamp)/3600000;if(W<1)b+=2;else if(W<6)b+=1;return b}limitMessages($,b){if($.length<=b)return $;let w=$.filter((Z)=>Z.role==="system"),V=$.filter((Z)=>Z.role!=="system"),W=b-w.length,Q=W>0?V.slice(-W):[];return[...w,...Q].sort((Z,Y)=>Z.timestamp-Y.timestamp)}limitByTokens($,b){if(b<=0)return $;let w=0,V=[];for(let W=$.length-1;W>=0;W--){let Q=$[W],Z=this.estimateMessageTokens(Q);if(Q.role==="system")if(w+Z<=b)V.unshift(Q),w+=Z;else{let Y=this.compressMessage(Q,b-w);V.unshift(Y),w+=this.estimateMessageTokens(Y)}else if(w+Z<=b)V.unshift(Q),w+=Z;else break}return V.sort((W,Q)=>W.timestamp-Q.timestamp)}estimateMessageTokens($){return Math.ceil($.content.length/4)}compressMessage($,b){let w=b*4;if($.content.length<=w)return $;let V=$.content.substring(0,w-3)+"...";return{...$,content:V,metadata:{...$.metadata,compressed:!0,originalLength:$.content.length}}}updateTopics($,b){let w=new Set(b);for(let V of $)this.extractTopicsFromMessage(V).forEach((Q)=>w.add(Q));return Array.from(w).slice(0,10)}extractTopicsFromMessage($){let b=$.content.toLowerCase(),w=[];return["项目","功能","模块","组件","服务","接口","数据库","前端","后端","算法","架构","设计"].forEach((W)=>{if(b.includes(W))w.push(W)}),w}estimateTokens($){let b=0;for(let V of $.layers.conversation.messages)b+=this.estimateMessageTokens(V);let w=JSON.stringify($.layers.system);if(b+=Math.ceil(w.length/4),$.layers.tool.recentCalls.length>0){let V=JSON.stringify($.layers.tool);b+=Math.ceil(V.length/8)}return b}static createPresets(){return{lightweight:new C0({maxTokens:1000,maxMessages:10,timeWindow:7200000,includeTools:!1,includeWorkspace:!1}),standard:new C0({maxTokens:4000,maxMessages:30,timeWindow:43200000,includeTools:!0,includeWorkspace:!0}),comprehensive:new C0({maxTokens:8000,maxMessages:100,timeWindow:86400000,includeTools:!0,includeWorkspace:!0}),debug:new C0({maxTokens:2000,maxMessages:20,timeWindow:21600000,priority:2,includeTools:!0,includeWorkspace:!1})}}}class Mw{cache=new Map;maxSize;defaultTTL;constructor($=100,b=300000){this.maxSize=$,this.defaultTTL=b}set($,b,w){let V=Date.now(),W={data:b,timestamp:V,accessCount:0,lastAccess:V,ttl:w||this.defaultTTL};if(this.cache.size>=this.maxSize&&!this.cache.has($))this.evictLeastUsed();this.cache.set($,W)}get($){let b=this.cache.get($);if(!b)return null;let w=Date.now();if(w-b.timestamp>b.ttl)return this.cache.delete($),null;return b.accessCount++,b.lastAccess=w,b.data}has($){let b=this.cache.get($);if(!b)return!1;if(Date.now()-b.timestamp>b.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($,b,w){let V=`summary:${$}:${b.length}`;this.set(V,{summary:w,messageCount:b.length,lastMessage:b[b.length-1]?.timestamp||0},600000)}getMessageSummary($,b){let w=`summary:${$}:${b}`;return this.get(w)}cacheToolResult($,b,w){let V=this.hashInput(b),W=`tool:${$}:${V}`;this.set(W,w,1800000)}getToolResult($,b){let w=this.hashInput(b),V=`tool:${$}:${w}`;return this.get(V)}cacheCompressedContext($,b){let w=`compressed:${$}`;this.set(w,b,900000)}getCompressedContext($){let b=`compressed:${$}`;return this.get(b)}getStats(){this.cleanExpired();let $=0,b=0,w=[];for(let[V,W]of Array.from(this.cache.entries()))$+=W.accessCount,b+=this.estimateItemSize(W),w.push({key:V,accessCount:W.accessCount,lastAccess:W.lastAccess});return w.sort((V,W)=>W.accessCount-V.accessCount),{size:this.cache.size,maxSize:this.maxSize,hitRate:$>0?$/($+this.cache.size):0,memoryUsage:b,topKeys:w.slice(0,10)}}cleanExpired(){let $=Date.now(),b=[];for(let[w,V]of Array.from(this.cache.entries()))if($-V.timestamp>V.ttl)b.push(w);b.forEach((w)=>this.cache.delete(w))}evictLeastUsed(){let $=null,b=1/0,w=Date.now();for(let[V,W]of Array.from(this.cache.entries())){let Q=1/(w-W.lastAccess+1),Z=W.accessCount,Y=Q*Z;if(Y<b)b=Y,$=V}if($)this.cache.delete($)}hashInput($){let b=JSON.stringify($),w=0;for(let V=0;V<b.length;V++){let W=b.charCodeAt(V);w=(w<<5)-w+W,w=w&w}return Math.abs(w).toString(36)}estimateItemSize($){try{return JSON.stringify($).length*2}catch{return 1000}}setTTL($,b){let w=this.cache.get($);if(w)return w.ttl=b,w.timestamp=Date.now(),!0;return!1}getRemainingTTL($){let b=this.cache.get($);if(!b)return-1;let w=b.ttl-(Date.now()-b.timestamp);return Math.max(0,w)}warmup($){$.forEach(({key:b,value:w,ttl:V})=>{this.set(b,w,V)})}}class zw{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 b=this.contextData.layers.conversation.messages;return this.recordAccess("messages"),b.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($,b){if(!this.contextData)throw Error("上下文数据未初始化");this.contextData.layers.tool.toolStates[$]=b,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 b=Math.floor(this.maxSize*0.8);this.contextData.layers.conversation.messages=$.slice(-b)}}getMemoryUsage(){if(!this.contextData)return 0;return JSON.stringify(this.contextData).length}}import{nanoid as h$}from"nanoid";import*as c$ from"node:fs/promises";import*as k2 from"node:path";import*as nb from"node:fs";import{createReadStream as sV}from"node:fs";import*as W$ from"node:fs/promises";import*as yw from"node:path";import{createInterface as rV}from"node:readline";class O${filePath;constructor($){this.filePath=$}async append($){try{await W$.mkdir(yw.dirname(this.filePath),{recursive:!0,mode:493});let b=JSON.stringify($)+`
|
|
1826
|
+
`;await W$.appendFile(this.filePath,b,"utf-8")}catch(b){throw console.error(`[JSONLStore] 追加写入失败: ${this.filePath}`,b),b}}async appendBatch($){try{await W$.mkdir(yw.dirname(this.filePath),{recursive:!0,mode:493});let b=$.map((w)=>JSON.stringify(w)).join(`
|
|
1801
1827
|
`)+`
|
|
1802
|
-
`;await
|
|
1803
|
-
`).filter((
|
|
1804
|
-
`).filter((Q)=>Q.trim().length>0).length;return{exists:!0,size:$.size,lineCount:W}}catch($){return console.error(`[JSONLStore] 获取统计信息失败: ${this.filePath}`,$),{exists:!1,size:0,lineCount:0}}}async exists(){try{return await $$.access(this.filePath),!0}catch{return!1}}async delete(){try{if(await this.exists())await $$.unlink(this.filePath)}catch($){throw console.error(`[JSONLStore] 删除文件失败: ${this.filePath}`,$),$}}getFilePath(){return this.filePath}}class $4{projectPath;maxSessions;version;constructor($=process.cwd(),V=100,W="0.0.10"){this.projectPath=$,this.maxSessions=V,this.version=W}createEvent($,V,W){return{id:z$(),sessionId:V,timestamp:new Date().toISOString(),type:$,cwd:this.projectPath,gitBranch:s4(this.projectPath),version:this.version,data:W}}async ensureSessionCreated($,V){let W=B$(this.projectPath,$),Q=new Y$(W);if((await Q.getStats()).lineCount>0)return;let Y=new Date().toISOString(),J={sessionId:$,rootId:V?.parentSessionId??$,parentId:V?.parentSessionId,relationType:V?"subagent":void 0,title:void 0,status:"running",agentType:V?.subagentType,model:void 0,permission:void 0,createdAt:Y,updatedAt:Y},X=this.createEvent("session_created",$,J);await Q.append(X)}buildCompactionMetadata($){let V={trigger:$.trigger,preTokens:$.preTokens};if($.postTokens!==void 0)V.postTokens=$.postTokens;if($.filesIncluded)V.filesIncluded=$.filesIncluded;return V}async initialize(){try{let $=S0(this.projectPath);await y$.mkdir($,{recursive:!0,mode:493}),console.log(`[PersistentStore] 初始化存储目录: ${$}`)}catch($){console.warn("[PersistentStore] 无法创建持久化存储目录:",$)}}async saveMessage($,V,W,Q=null,Z,Y){try{let J=B$(this.projectPath,$),X=new Y$(J);await this.ensureSessionCreated($,Y);let G=new Date().toISOString(),B=z$(),K={messageId:B,role:V,parentMessageId:Q??void 0,createdAt:G,model:Z?.model,usage:Z?.usage},q=this.createEvent("message_created",$,K),O={partId:z$(),messageId:B,partType:"text",payload:{text:W},createdAt:G},w=this.createEvent("part_created",$,O);return await X.appendBatch([q,w]),B}catch(J){throw console.error(`[PersistentStore] 保存消息失败 (session: ${$}):`,J),J}}async saveToolUse($,V,W,Q=null,Z){try{let Y=B$(this.projectPath,$),J=new Y$(Y);await this.ensureSessionCreated($,Z);let X=new Date().toISOString(),G=Q??z$(),B=[];if(!Q){let O={messageId:G,role:"assistant",parentMessageId:void 0,createdAt:X};B.push(this.createEvent("message_created",$,O))}let K=z$(),q={partId:K,messageId:G,partType:"tool_call",payload:{toolCallId:K,toolName:V,input:W},createdAt:X};if(B.push(this.createEvent("part_created",$,q)),V==="Task"&&W&&typeof W==="object"){let O=W,w=typeof O.subagent_session_id==="string"?O.subagent_session_id:void 0,b=typeof O.subagent_type==="string"?O.subagent_type:void 0;if(w&&b){let A={partId:z$(),messageId:G,partType:"subtask_ref",payload:{childSessionId:w,agentType:b,status:"running",summary:typeof O.description==="string"?O.description:"",startedAt:X},createdAt:X};B.push(this.createEvent("part_created",$,A))}}return await J.appendBatch(B),K}catch(Y){throw console.error(`[PersistentStore] 保存工具调用失败 (session: ${$}):`,Y),Y}}async saveToolResult($,V,W,Q,Z=null,Y,J,X){try{let G=B$(this.projectPath,$),B=new Y$(G);await this.ensureSessionCreated($,J);let K=new Date().toISOString(),q=Z??z$(),O=[];if(!Z){let b={messageId:q,role:"assistant",parentMessageId:void 0,createdAt:K};O.push(this.createEvent("message_created",$,b))}let w={partId:V,messageId:q,partType:"tool_result",payload:{toolCallId:V,toolName:W,output:Q,error:Y??null},createdAt:K};if(O.push(this.createEvent("part_created",$,w)),X){let b=X.subagentStatus==="running"?null:K,A={partId:z$(),messageId:q,partType:"subtask_ref",payload:{childSessionId:X.subagentSessionId,agentType:X.subagentType,status:X.subagentStatus,summary:X.subagentSummary??"",startedAt:K,finishedAt:b},createdAt:K};O.push(this.createEvent("part_created",$,A))}return await B.appendBatch(O),V}catch(G){throw console.error(`[PersistentStore] 保存工具结果失败 (session: ${$}):`,G),G}}async saveCompaction($,V,W,Q=null){try{let Z=B$(this.projectPath,$),Y=new Y$(Z);await this.ensureSessionCreated($);let J=new Date().toISOString(),X=z$(),G={messageId:X,role:"system",parentMessageId:Q??void 0,createdAt:J},B=this.buildCompactionMetadata(W),K={partId:z$(),messageId:X,partType:"summary",payload:{text:V,metadata:B},createdAt:J},q=[this.createEvent("message_created",$,G),this.createEvent("part_created",$,K)];return await Y.appendBatch(q),X}catch(Z){throw console.error(`[PersistentStore] 保存压缩失败 (session: ${$}):`,Z),Z}}async saveContext($,V){try{let{conversation:W}=V.layers;for(let Q of W.messages)await this.saveMessage($,Q.role,Q.content,null)}catch(W){console.warn(`[PersistentStore] 保存上下文失败 (session: ${$}):`,W)}}async saveSession($,V){console.warn("[PersistentStore] saveSession 方法已废弃,请使用 saveMessage")}async saveConversation($,V){console.warn("[PersistentStore] saveConversation 方法已废弃,请使用 saveMessage")}async loadSession($){try{let V=B$(this.projectPath,$),Q=await new Y$(V).readAll();if(Q.length===0)return null;let Z=Q.find((Y)=>Y.type==="session_created");return{sessionId:$,userId:void 0,preferences:{},configuration:{},startTime:new Date(Z?.timestamp??Q[0].timestamp).getTime()}}catch{return null}}async loadConversation($){try{let V=B$(this.projectPath,$),Q=await new Y$(V).readAll();if(Q.length===0)return null;let Z=new Map;for(let G of Q){if(G.type==="message_created")Z.set(G.data.messageId,{id:G.data.messageId,role:G.data.role,content:"",timestamp:new Date(G.timestamp).getTime()});if(G.type==="part_created"&&G.data.partType==="text"){let B=Z.get(G.data.messageId);if(B){let K=G.data.payload;B.content=K.text??""}}}let Y=Array.from(Z.values()),J=Q[Q.length-1],X=new Date(J.timestamp).getTime();return{messages:Y,topics:[],lastActivity:X}}catch{return null}}async listSessions(){try{let $=S0(this.projectPath);return(await y$.readdir($)).filter((W)=>W.endsWith(".jsonl")).map((W)=>W.replace(".jsonl","")).sort()}catch{return[]}}async getSessionSummary($){try{let V=B$(this.projectPath,$),W=new Y$(V);if(!(await W.getStats()).exists)return null;let Z=await W.readAll();if(Z.length===0)return null;let Y=Z[Z.length-1],J=Z.filter((X)=>X.type==="message_created"&&["user","assistant"].includes(X.data.role)).length;return{sessionId:$,lastActivity:new Date(Y.timestamp).getTime(),messageCount:J,topics:[]}}catch{return null}}async deleteSession($){try{let V=B$(this.projectPath,$);await new Y$(V).delete()}catch(V){console.warn(`[PersistentStore] 删除会话失败 (session: ${$}):`,V)}}async cleanupOldSessions(){try{let $=await this.listSessions();if($.length<=this.maxSessions)return;let Q=(await Promise.all($.map((Z)=>this.getSessionSummary(Z)))).filter((Z)=>Z!==null).sort((Z,Y)=>Y.lastActivity-Z.lastActivity).slice(this.maxSessions).map((Z)=>Z.sessionId);await Promise.all(Q.map((Z)=>this.deleteSession(Z))),console.log(`[PersistentStore] 已清理 ${Q.length} 个旧会话`)}catch($){console.error("[PersistentStore] 清理旧会话失败:",$)}}async getStorageStats(){try{let $=await this.listSessions(),V=0;for(let W of $){let Q=B$(this.projectPath,W),Y=await new Y$(Q).getStats();V+=Y.size}return{totalSessions:$.length,totalSize:V,projectPath:this.projectPath}}catch{return{totalSessions:0,totalSize:0,projectPath:this.projectPath}}}async checkStorageHealth(){try{let $=S0(this.projectPath);await y$.mkdir($,{recursive:!0,mode:493});let V=$5.join($,".health-check");return await y$.writeFile(V,"test","utf-8"),await y$.unlink(V),{isAvailable:!0,canWrite:!0}}catch($){return{isAvailable:!1,canWrite:!1,error:$ instanceof Error?$.message:String($)}}}static async listAllProjects(){return a4()}}class C1{memory;persistent;cache;compressor;filter;options;currentSessionId=null;initialized=!1;constructor($={}){let V=$.storage?.persistentPath||T0();this.options={storage:{maxMemorySize:1000,persistentPath:V,cacheSize:100,compressionEnabled:!0,...$.storage},defaultFilter:{maxTokens:32000,maxMessages:50,timeWindow:86400000,...$.defaultFilter},compressionThreshold:$.compressionThreshold||6000,enableVectorSearch:$.enableVectorSearch||!1},this.memory=new t2(this.options.storage.maxMemorySize),this.persistent=new $4(process.cwd(),100),this.cache=new o2(this.options.storage.cacheSize,300000),this.compressor=new a2,this.filter=new W0(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($,V={},W={}){let Q=W.sessionId||this.generateSessionId(),Z=Date.now(),Y={layers:{system:await this.createSystemContext(),session:{sessionId:Q,userId:$,preferences:V,configuration:W,startTime:Z},conversation:{messages:[],topics:[],lastActivity:Z},tool:{recentCalls:[],toolStates:{},dependencies:{}},workspace:await this.createWorkspaceContext()},metadata:{totalTokens:0,priority:1,lastUpdated:Z}};return this.memory.setContext(Y),await this.persistent.saveContext(Q,Y),this.currentSessionId=Q,console.log(`新会话已创建: ${Q}`),Q}async loadSession($){try{let V=this.memory.getContext();if(!V||V.layers.session.sessionId!==$){let[W,Q]=await Promise.all([this.persistent.loadSession($),this.persistent.loadConversation($)]);if(!W||!Q)return!1;V={layers:{system:await this.createSystemContext(),session:W,conversation:Q,tool:{recentCalls:[],toolStates:{},dependencies:{}},workspace:await this.createWorkspaceContext()},metadata:{totalTokens:0,priority:1,lastUpdated:Date.now()}},this.memory.setContext(V)}return this.currentSessionId=$,console.log(`会话已加载: ${$}`),!0}catch(V){return console.error("加载会话失败:",V),!1}}async addMessage($,V,W){if(!this.currentSessionId)throw Error("没有活动会话");let Q={id:this.generateMessageId(),role:$,content:V,timestamp:Date.now(),metadata:W};this.memory.addMessage(Q);let Z=this.memory.getContext();if(Z&&this.shouldCompress(Z))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($,V,W,Q=null,Z,Y){return this.persistent.saveMessage($,V,W,Q,Z,Y)}async saveToolUse($,V,W,Q=null,Z){return this.persistent.saveToolUse($,V,W,Q,Z)}async saveToolResult($,V,W,Q,Z=null,Y,J,X){return this.persistent.saveToolResult($,V,W,Q,Z,Y,J,X)}async saveCompaction($,V,W,Q=null){return this.persistent.saveCompaction($,V,W,Q)}updateToolState($,V){if(!this.currentSessionId)throw Error("没有活动会话");this.memory.updateToolState($,V)}updateWorkspace($){if(!this.currentSessionId)throw Error("没有活动会话");this.memory.updateWorkspace($)}async getFormattedContext($){let V=this.memory.getContext();if(!V)throw Error("没有可用的上下文数据");let W=this.filter.filter(V,$),Q=this.shouldCompress(W),Z;if(Q){let Y=this.hashContext(W);if(Z=this.cache.getCompressedContext(Y)??void 0,!Z)Z=await this.compressor.compress(W),this.cache.cacheCompressedContext(Y,Z)}return{context:W,compressed:Z,tokenCount:Z?Z.tokenCount:W.metadata.totalTokens}}async searchSessions($,V=10){let W=await this.persistent.listSessions(),Q=[];for(let Z of W){let Y=await this.persistent.getSessionSummary(Z);if(Y){let J=this.calculateRelevance($,Y.topics);if(J>0)Q.push({sessionId:Z,summary:`${Y.messageCount}条消息,主题:${Y.topics.join("、")}`,lastActivity:Y.lastActivity,relevanceScore:J})}}return Q.sort((Z,Y)=>Y.relevanceScore-Z.relevanceScore).slice(0,V)}getCachedToolResult($,V){return this.cache.getToolResult($,V)}async getStats(){let[$,V,W]=await Promise.all([Promise.resolve(this.memory.getMemoryInfo()),Promise.resolve(this.cache.getStats()),this.persistent.getStorageStats()]);return{currentSession:this.currentSessionId,memory:$,cache:V,storage:W}}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 V5()}generateMessageId(){return V5()}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 V=await this.compressor.compress($);$.layers.conversation.summary=V.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 V=JSON.stringify({messageCount:$.layers.conversation.messages.length,lastMessage:$.layers.conversation.messages[$.layers.conversation.messages.length-1]?.id,toolCallCount:$.layers.tool.recentCalls.length});return W5.createHash("md5").update(V).digest("hex")}calculateRelevance($,V){let W=$.toLowerCase(),Q=0;for(let Z of V)if(W.includes(Z.toLowerCase())||Z.toLowerCase().includes(W))Q+=1;return Q}}class V4{chatService;contextManager;memoryAdapter;constructor($,V){this.chatService=$,this.contextManager=V||new C1,this.memoryAdapter=this.createMemoryAdapter()}createMemoryAdapter(){let $=[];return{getMessages:()=>[...$],addMessage:(V)=>{$.push(V)},clearContext:()=>{$.length=0},getContextSize:()=>$.length}}getContextManager(){return this.contextManager}getMemoryAdapter(){return this.memoryAdapter}async executeTask($){let V=[{role:"user",content:$.prompt}],W=await this.chatService.chat(V);return{taskId:$.id,content:W.content,metadata:{taskType:$.type}}}}var Q5=T("Agent");class W4{getChatService;constructor($){this.getChatService=$}async*streamResponse($,V,W){let Q=this.getChatService(),Z="",Y="",J,X=new Map;try{let G=Q.streamChat($,V,W),B=0;for await(let K of G){if(B++,W?.aborted)break;if(K.content)Z+=K.content,yield{type:"content_delta",delta:K.content};if(K.reasoningContent)Y+=K.reasoningContent,yield{type:"thinking_delta",delta:K.reasoningContent};if(K.usage)J=K.usage;if(K.toolCalls)for(let q of K.toolCalls)this.accumulateToolCall(X,q);if(K.finishReason){n0("processStreamResponse","finishReason received",{finishReason:K.finishReason,fullContentLen:Z.length,fullReasoningContentLen:Y.length,toolCallAccumulatorSize:X.size});break}}if(B===0&&!W?.aborted&&Z.length===0&&X.size===0)return Q5.warn("[Agent] 流式响应返回0个chunk,回退到非流式模式"),Q.chat($,V,W);return{content:Z,reasoningContent:Y||void 0,toolCalls:this.buildFinalToolCalls(X),usage:J}}catch(G){if(this.isStreamingNotSupportedError(G))return Q5.warn("[Agent] 流式请求失败,降级到非流式模式"),Q.chat($,V,W);throw G}}accumulateToolCall($,V){let W=V,Q=W.index??0;if(!$.has(Q))$.set(Q,{id:W.id||"",name:W.function?.name||"",arguments:""});let Z=$.get(Q);if(W.id&&!Z.id)Z.id=W.id;if(W.function?.name&&!Z.name)Z.name=W.function.name;if(W.function?.arguments)Z.arguments+=W.function.arguments}buildFinalToolCalls($){if($.size===0)return;return Array.from($.values()).filter((V)=>V.id&&V.name).map((V)=>({id:V.id,type:"function",function:{name:V.name,arguments:V.arguments}}))}isStreamingNotSupportedError($){if(!($ instanceof Error))return!1;return["stream not supported","streaming is not available","sse not supported","does not support streaming"].some((W)=>$.message.toLowerCase().includes(W.toLowerCase()))}}function a9($){if(typeof $==="string")return $;try{return JSON.parse(JSON.stringify($))}catch{return String($)}}var D=T("Agent");class S${config;runtimeOptions;isInitialized=!1;activeTask;executionPipeline;chatService;executionEngine;attachmentHandler;streamHandler;compactionHandler;activeSkillContext;currentModelMaxContextTokens;currentModelId;constructor($,V={},W){this.config=$,this.runtimeOptions=V,this.executionPipeline=W||this.createDefaultPipeline()}createDefaultPipeline(){let $=new p0,V={...this.config.permissions,...this.runtimeOptions.permissions},W=this.runtimeOptions.permissionMode??S.DEFAULT;return new b1($,{permissionConfig:V,permissionMode:W,maxHistorySize:1000,canUseTool:this.runtimeOptions.canUseTool})}resolveModelConfig($){let V=$&&$!=="inherit"?$:void 0,W=this.config.models||[],Q=this.config.currentModelId,Z=V?W.find((Y)=>Y.id===V):W.find((Y)=>Y.id===Q)||W[0];if(!Z)throw Error(`❌ 模型配置未找到: ${V??"current"}`);return Z}async applyModelConfig($,V){this.log(`${V} ${$.name} (${$.model})`);let W=a8($),Q=$.thinkingEnabled??!1,Z=W&&Q;if(W&&!Q)this.log("\uD83E\uDDE0 模型支持 Thinking,但用户未开启(按 Tab 开启)");else if(Z)this.log("\uD83E\uDDE0 Thinking 模式已启用,启用 reasoning_content 支持");let Y=$.maxTokens??128000;this.currentModelMaxContextTokens=Y,this.chatService=await l0({provider:$.provider,apiKey:$.apiKey||"",model:$.model,baseUrl:$.baseUrl||"",temperature:$.temperature??this.config.temperature,maxContextTokens:this.currentModelMaxContextTokens,supportsThinking:Z});let J=this.executionEngine?.getContextManager();this.executionEngine=new V4(this.chatService,J),this.currentModelId=$.id}async switchModelIfNeeded($){if(!$||$===this.currentModelId)return;let W=(this.config.models||[]).find((Q)=>Q.id===$);if(!W){this.log(`⚠️ 模型配置未找到: ${$}`);return}await this.applyModelConfig(W,"\uD83D\uDD01 切换模型")}static async create($,V={}){if(($.models||[]).length===0)throw Error(`❌ 没有可用的模型配置
|
|
1828
|
+
`;await W$.appendFile(this.filePath,b,"utf-8")}catch(b){throw console.error(`[JSONLStore] 批量追加写入失败: ${this.filePath}`,b),b}}async readAll(){try{if(!nb.existsSync(this.filePath))return[];let b=(await W$.readFile(this.filePath,"utf-8")).split(`
|
|
1829
|
+
`).filter((V)=>V.trim().length>0),w=[];for(let V of b)try{w.push(JSON.parse(V))}catch(W){console.warn(`[JSONLStore] 解析 JSON 行失败: ${V}`,W)}return w}catch($){return console.error(`[JSONLStore] 读取文件失败: ${this.filePath}`,$),[]}}async readStream($){return new Promise((b,w)=>{if(!nb.existsSync(this.filePath)){b();return}let V=sV(this.filePath,"utf-8"),W=rV({input:V,crlfDelay:Number.POSITIVE_INFINITY});W.on("line",async(Q)=>{let Z=Q.trim();if(Z.length===0)return;try{let Y=JSON.parse(Z);await $(Y)}catch(Y){console.warn(`[JSONLStore] 解析 JSON 行失败: ${Z}`,Y)}}),W.on("close",()=>b()),W.on("error",w),V.on("error",w)})}async filter($){let b=[];return await this.readStream((w)=>{if($(w))b.push(w)}),b}async readLast($){return(await this.readAll()).slice(-$)}async getStats(){try{if(!nb.existsSync(this.filePath))return{exists:!1,size:0,lineCount:0};let $=await W$.stat(this.filePath),w=(await W$.readFile(this.filePath,"utf-8")).split(`
|
|
1830
|
+
`).filter((V)=>V.trim().length>0).length;return{exists:!0,size:$.size,lineCount:w}}catch($){return console.error(`[JSONLStore] 获取统计信息失败: ${this.filePath}`,$),{exists:!1,size:0,lineCount:0}}}async exists(){try{return await W$.access(this.filePath),!0}catch{return!1}}async delete(){try{if(await this.exists())await W$.unlink(this.filePath)}catch($){throw console.error(`[JSONLStore] 删除文件失败: ${this.filePath}`,$),$}}getFilePath(){return this.filePath}}class vw{projectPath;maxSessions;version;constructor($=process.cwd(),b=100,w="0.0.10"){this.projectPath=$,this.maxSessions=b,this.version=w}createEvent($,b,w){return{id:h$(),sessionId:b,timestamp:new Date().toISOString(),type:$,cwd:this.projectPath,gitBranch:S4(this.projectPath),version:this.version,data:w}}async ensureSessionCreated($,b){let w=C$(this.projectPath,$),V=new O$(w);if((await V.getStats()).lineCount>0)return;let Q=new Date().toISOString(),Z={sessionId:$,rootId:b?.parentSessionId??$,parentId:b?.parentSessionId,relationType:b?"subagent":void 0,title:void 0,status:"running",agentType:b?.subagentType,model:void 0,permission:void 0,createdAt:Q,updatedAt:Q},Y=this.createEvent("session_created",$,Z);await V.append(Y)}buildCompactionMetadata($){let b={trigger:$.trigger,preTokens:$.preTokens};if($.postTokens!==void 0)b.postTokens=$.postTokens;if($.filesIncluded)b.filesIncluded=$.filesIncluded;return b}async initialize(){try{let $=s0(this.projectPath);await c$.mkdir($,{recursive:!0,mode:493}),console.log(`[PersistentStore] 初始化存储目录: ${$}`)}catch($){console.warn("[PersistentStore] 无法创建持久化存储目录:",$)}}async saveMessage($,b,w,V=null,W,Q){try{let Z=C$(this.projectPath,$),Y=new O$(Z);await this.ensureSessionCreated($,Q);let J=new Date().toISOString(),X=h$(),O={messageId:X,role:b,parentMessageId:V??void 0,createdAt:J,model:W?.model,usage:W?.usage},G=this.createEvent("message_created",$,O),B={partId:h$(),messageId:X,partType:"text",payload:{text:w},createdAt:J},q=this.createEvent("part_created",$,B);return await Y.appendBatch([G,q]),X}catch(Z){throw console.error(`[PersistentStore] 保存消息失败 (session: ${$}):`,Z),Z}}async saveToolUse($,b,w,V=null,W){try{let Q=C$(this.projectPath,$),Z=new O$(Q);await this.ensureSessionCreated($,W);let Y=new Date().toISOString(),J=V??h$(),X=[];if(!V){let B={messageId:J,role:"assistant",parentMessageId:void 0,createdAt:Y};X.push(this.createEvent("message_created",$,B))}let O=h$(),G={partId:O,messageId:J,partType:"tool_call",payload:{toolCallId:O,toolName:b,input:w},createdAt:Y};if(X.push(this.createEvent("part_created",$,G)),b==="Task"&&w&&typeof w==="object"){let B=w,q=typeof B.subagent_session_id==="string"?B.subagent_session_id:void 0,A=typeof B.subagent_type==="string"?B.subagent_type:void 0;if(q&&A){let K={partId:h$(),messageId:J,partType:"subtask_ref",payload:{childSessionId:q,agentType:A,status:"running",summary:typeof B.description==="string"?B.description:"",startedAt:Y},createdAt:Y};X.push(this.createEvent("part_created",$,K))}}return await Z.appendBatch(X),O}catch(Q){throw console.error(`[PersistentStore] 保存工具调用失败 (session: ${$}):`,Q),Q}}async saveToolResult($,b,w,V,W=null,Q,Z,Y){try{let J=C$(this.projectPath,$),X=new O$(J);await this.ensureSessionCreated($,Z);let O=new Date().toISOString(),G=W??h$(),B=[];if(!W){let A={messageId:G,role:"assistant",parentMessageId:void 0,createdAt:O};B.push(this.createEvent("message_created",$,A))}let q={partId:b,messageId:G,partType:"tool_result",payload:{toolCallId:b,toolName:w,output:V,error:Q??null},createdAt:O};if(B.push(this.createEvent("part_created",$,q)),Y){let A=Y.subagentStatus==="running"?null:O,K={partId:h$(),messageId:G,partType:"subtask_ref",payload:{childSessionId:Y.subagentSessionId,agentType:Y.subagentType,status:Y.subagentStatus,summary:Y.subagentSummary??"",startedAt:O,finishedAt:A},createdAt:O};B.push(this.createEvent("part_created",$,K))}return await X.appendBatch(B),b}catch(J){throw console.error(`[PersistentStore] 保存工具结果失败 (session: ${$}):`,J),J}}async saveCompaction($,b,w,V=null){try{let W=C$(this.projectPath,$),Q=new O$(W);await this.ensureSessionCreated($);let Z=new Date().toISOString(),Y=h$(),J={messageId:Y,role:"system",parentMessageId:V??void 0,createdAt:Z},X=this.buildCompactionMetadata(w),O={partId:h$(),messageId:Y,partType:"summary",payload:{text:b,metadata:X},createdAt:Z},G=[this.createEvent("message_created",$,J),this.createEvent("part_created",$,O)];return await Q.appendBatch(G),Y}catch(W){throw console.error(`[PersistentStore] 保存压缩失败 (session: ${$}):`,W),W}}async saveContext($,b){try{let{conversation:w}=b.layers;for(let V of w.messages)await this.saveMessage($,V.role,V.content,null)}catch(w){console.warn(`[PersistentStore] 保存上下文失败 (session: ${$}):`,w)}}async saveSession($,b){console.warn("[PersistentStore] saveSession 方法已废弃,请使用 saveMessage")}async saveConversation($,b){console.warn("[PersistentStore] saveConversation 方法已废弃,请使用 saveMessage")}async loadSession($){try{let b=C$(this.projectPath,$),V=await new O$(b).readAll();if(V.length===0)return null;let W=V.find((Q)=>Q.type==="session_created");return{sessionId:$,userId:void 0,preferences:{},configuration:{},startTime:new Date(W?.timestamp??V[0].timestamp).getTime()}}catch{return null}}async loadConversation($){try{let b=C$(this.projectPath,$),V=await new O$(b).readAll();if(V.length===0)return null;let W=new Map;for(let J of V){if(J.type==="message_created")W.set(J.data.messageId,{id:J.data.messageId,role:J.data.role,content:"",timestamp:new Date(J.timestamp).getTime()});if(J.type==="part_created"&&J.data.partType==="text"){let X=W.get(J.data.messageId);if(X){let O=J.data.payload;X.content=O.text??""}}}let Q=Array.from(W.values()),Z=V[V.length-1],Y=new Date(Z.timestamp).getTime();return{messages:Q,topics:[],lastActivity:Y}}catch{return null}}async listSessions(){try{let $=s0(this.projectPath);return(await c$.readdir($)).filter((w)=>w.endsWith(".jsonl")).map((w)=>w.replace(".jsonl","")).sort()}catch{return[]}}async getSessionSummary($){try{let b=C$(this.projectPath,$),w=new O$(b);if(!(await w.getStats()).exists)return null;let W=await w.readAll();if(W.length===0)return null;let Q=W[W.length-1],Z=W.filter((Y)=>Y.type==="message_created"&&["user","assistant"].includes(Y.data.role)).length;return{sessionId:$,lastActivity:new Date(Q.timestamp).getTime(),messageCount:Z,topics:[]}}catch{return null}}async deleteSession($){try{let b=C$(this.projectPath,$);await new O$(b).delete()}catch(b){console.warn(`[PersistentStore] 删除会话失败 (session: ${$}):`,b)}}async cleanupOldSessions(){try{let $=await this.listSessions();if($.length<=this.maxSessions)return;let V=(await Promise.all($.map((W)=>this.getSessionSummary(W)))).filter((W)=>W!==null).sort((W,Q)=>Q.lastActivity-W.lastActivity).slice(this.maxSessions).map((W)=>W.sessionId);await Promise.all(V.map((W)=>this.deleteSession(W))),console.log(`[PersistentStore] 已清理 ${V.length} 个旧会话`)}catch($){console.error("[PersistentStore] 清理旧会话失败:",$)}}async getStorageStats(){try{let $=await this.listSessions(),b=0;for(let w of $){let V=C$(this.projectPath,w),Q=await new O$(V).getStats();b+=Q.size}return{totalSessions:$.length,totalSize:b,projectPath:this.projectPath}}catch{return{totalSessions:0,totalSize:0,projectPath:this.projectPath}}}async checkStorageHealth(){try{let $=s0(this.projectPath);await c$.mkdir($,{recursive:!0,mode:493});let b=k2.join($,".health-check");return await c$.writeFile(b,"test","utf-8"),await c$.unlink(b),{isAvailable:!0,canWrite:!0}}catch($){return{isAvailable:!1,canWrite:!1,error:$ instanceof Error?$.message:String($)}}}static async listAllProjects(){return M4()}}class sb{memory;persistent;cache;compressor;filter;options;currentSessionId=null;initialized=!1;constructor($={}){let b=$.storage?.persistentPath||r0();this.options={storage:{maxMemorySize:1000,persistentPath:b,cacheSize:100,compressionEnabled:!0,...$.storage},defaultFilter:{maxTokens:32000,maxMessages:50,timeWindow:86400000,...$.defaultFilter},compressionThreshold:$.compressionThreshold||6000,enableVectorSearch:$.enableVectorSearch||!1},this.memory=new zw(this.options.storage.maxMemorySize),this.persistent=new vw(process.cwd(),100),this.cache=new Mw(this.options.storage.cacheSize,300000),this.compressor=new Sw,this.filter=new C0(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($,b={},w={}){let V=w.sessionId||this.generateSessionId(),W=Date.now(),Q={layers:{system:await this.createSystemContext(),session:{sessionId:V,userId:$,preferences:b,configuration:w,startTime:W},conversation:{messages:[],topics:[],lastActivity:W},tool:{recentCalls:[],toolStates:{},dependencies:{}},workspace:await this.createWorkspaceContext()},metadata:{totalTokens:0,priority:1,lastUpdated:W}};return this.memory.setContext(Q),await this.persistent.saveContext(V,Q),this.currentSessionId=V,console.log(`新会话已创建: ${V}`),V}async loadSession($){try{let b=this.memory.getContext();if(!b||b.layers.session.sessionId!==$){let[w,V]=await Promise.all([this.persistent.loadSession($),this.persistent.loadConversation($)]);if(!w||!V)return!1;b={layers:{system:await this.createSystemContext(),session:w,conversation:V,tool:{recentCalls:[],toolStates:{},dependencies:{}},workspace:await this.createWorkspaceContext()},metadata:{totalTokens:0,priority:1,lastUpdated:Date.now()}},this.memory.setContext(b)}return this.currentSessionId=$,console.log(`会话已加载: ${$}`),!0}catch(b){return console.error("加载会话失败:",b),!1}}async addMessage($,b,w){if(!this.currentSessionId)throw Error("没有活动会话");let V={id:this.generateMessageId(),role:$,content:b,timestamp:Date.now(),metadata:w};this.memory.addMessage(V);let W=this.memory.getContext();if(W&&this.shouldCompress(W))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($,b,w,V=null,W,Q){return this.persistent.saveMessage($,b,w,V,W,Q)}async saveToolUse($,b,w,V=null,W){return this.persistent.saveToolUse($,b,w,V,W)}async saveToolResult($,b,w,V,W=null,Q,Z,Y){return this.persistent.saveToolResult($,b,w,V,W,Q,Z,Y)}async saveCompaction($,b,w,V=null){return this.persistent.saveCompaction($,b,w,V)}updateToolState($,b){if(!this.currentSessionId)throw Error("没有活动会话");this.memory.updateToolState($,b)}updateWorkspace($){if(!this.currentSessionId)throw Error("没有活动会话");this.memory.updateWorkspace($)}async getFormattedContext($){let b=this.memory.getContext();if(!b)throw Error("没有可用的上下文数据");let w=this.filter.filter(b,$),V=this.shouldCompress(w),W;if(V){let Q=this.hashContext(w);if(W=this.cache.getCompressedContext(Q)??void 0,!W)W=await this.compressor.compress(w),this.cache.cacheCompressedContext(Q,W)}return{context:w,compressed:W,tokenCount:W?W.tokenCount:w.metadata.totalTokens}}async searchSessions($,b=10){let w=await this.persistent.listSessions(),V=[];for(let W of w){let Q=await this.persistent.getSessionSummary(W);if(Q){let Z=this.calculateRelevance($,Q.topics);if(Z>0)V.push({sessionId:W,summary:`${Q.messageCount}条消息,主题:${Q.topics.join("、")}`,lastActivity:Q.lastActivity,relevanceScore:Z})}}return V.sort((W,Q)=>Q.relevanceScore-W.relevanceScore).slice(0,b)}getCachedToolResult($,b){return this.cache.getToolResult($,b)}async getStats(){let[$,b,w]=await Promise.all([Promise.resolve(this.memory.getMemoryInfo()),Promise.resolve(this.cache.getStats()),this.persistent.getStorageStats()]);return{currentSession:this.currentSessionId,memory:$,cache:b,storage:w}}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 f2()}generateMessageId(){return f2()}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 b=await this.compressor.compress($);$.layers.conversation.summary=b.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 b=JSON.stringify({messageCount:$.layers.conversation.messages.length,lastMessage:$.layers.conversation.messages[$.layers.conversation.messages.length-1]?.id,toolCallCount:$.layers.tool.recentCalls.length});return I2.createHash("md5").update(b).digest("hex")}calculateRelevance($,b){let w=$.toLowerCase(),V=0;for(let W of b)if(w.includes(W.toLowerCase())||W.toLowerCase().includes(w))V+=1;return V}}class Tw{chatService;contextManager;memoryAdapter;constructor($,b){this.chatService=$,this.contextManager=b||new sb,this.memoryAdapter=this.createMemoryAdapter()}createMemoryAdapter(){let $=[];return{getMessages:()=>[...$],addMessage:(b)=>{$.push(b)},clearContext:()=>{$.length=0},getContextSize:()=>$.length}}getContextManager(){return this.contextManager}getMemoryAdapter(){return this.memoryAdapter}async executeTask($){let b=[{role:"user",content:$.prompt}],w=await this.chatService.chat(b);return{taskId:$.id,content:w.content,metadata:{taskType:$.type}}}}var P2=z("Agent");class kw{getChatService;constructor($){this.getChatService=$}async*streamResponse($,b,w){let V=this.getChatService(),W="",Q="",Z,Y=new Map;try{let J=V.streamChat($,b,w),X=0;for await(let O of J){if(X++,w?.aborted)break;if(O.content)W+=O.content,yield{type:"content_delta",delta:O.content};if(O.reasoningContent)Q+=O.reasoningContent,yield{type:"thinking_delta",delta:O.reasoningContent};if(O.usage)Z=O.usage;if(O.toolCalls)for(let G of O.toolCalls)this.accumulateToolCall(Y,G);if(O.finishReason){qb("processStreamResponse","finishReason received",{finishReason:O.finishReason,fullContentLen:W.length,fullReasoningContentLen:Q.length,toolCallAccumulatorSize:Y.size});break}}if(X===0&&!w?.aborted&&W.length===0&&Y.size===0)return P2.warn("[Agent] 流式响应返回0个chunk,回退到非流式模式"),V.chat($,b,w);return{content:W,reasoningContent:Q||void 0,toolCalls:this.buildFinalToolCalls(Y),usage:Z}}catch(J){if(this.isStreamingNotSupportedError(J))return P2.warn("[Agent] 流式请求失败,降级到非流式模式"),V.chat($,b,w);throw J}}accumulateToolCall($,b){let w=b,V=w.index??0;if(!$.has(V))$.set(V,{id:w.id||"",name:w.function?.name||"",arguments:""});let W=$.get(V);if(w.id&&!W.id)W.id=w.id;if(w.function?.name&&!W.name)W.name=w.function.name;if(w.function?.arguments)W.arguments+=w.function.arguments}buildFinalToolCalls($){if($.size===0)return;return Array.from($.values()).filter((b)=>b.id&&b.name).map((b)=>({id:b.id,type:"function",function:{name:b.name,arguments:b.arguments}}))}isStreamingNotSupportedError($){if(!($ instanceof Error))return!1;return["stream not supported","streaming is not available","sse not supported","does not support streaming"].some((w)=>$.message.toLowerCase().includes(w.toLowerCase()))}}function oV($){if(typeof $==="string")return $;try{return JSON.parse(JSON.stringify($))}catch{return String($)}}var H=z("Agent");class g${config;runtimeOptions;isInitialized=!1;activeTask;executionPipeline;chatService;executionEngine;attachmentHandler;streamHandler;compactionHandler;activeSkillContext;currentModelMaxContextTokens;currentModelId;constructor($,b={},w){this.config=$,this.runtimeOptions=b,this.executionPipeline=w||this.createDefaultPipeline()}createDefaultPipeline(){let $=new Qb,b={...this.config.permissions,...this.runtimeOptions.permissions},w=this.runtimeOptions.permissionMode??v.DEFAULT;return new mb($,{permissionConfig:b,permissionMode:w,maxHistorySize:1000,canUseTool:this.runtimeOptions.canUseTool})}resolveModelConfig($){let b=$&&$!=="inherit"?$:void 0,w=this.config.models||[],V=this.config.currentModelId,W=b?w.find((Q)=>Q.id===b):w.find((Q)=>Q.id===V)||w[0];if(!W)throw Error(`❌ 模型配置未找到: ${b??"current"}`);return W}async applyModelConfig($,b){this.log(`${b} ${$.name} (${$.model})`);let w=z2($),V=$.thinkingEnabled??!1,W=w&&V;if(w&&!V)this.log("\uD83E\uDDE0 模型支持 Thinking,但用户未开启(按 Tab 开启)");else if(W)this.log("\uD83E\uDDE0 Thinking 模式已启用,启用 reasoning_content 支持");let Q=$.maxTokens??128000;this.currentModelMaxContextTokens=Q,this.chatService=await Kb({provider:$.provider,apiKey:$.apiKey||"",model:$.model,baseUrl:$.baseUrl||"",temperature:$.temperature??this.config.temperature,maxContextTokens:this.currentModelMaxContextTokens,supportsThinking:W,outputFormat:this.runtimeOptions.outputFormat});let Z=this.executionEngine?.getContextManager();this.executionEngine=new Tw(this.chatService,Z),this.currentModelId=$.id}async switchModelIfNeeded($){if(!$||$===this.currentModelId)return;let w=(this.config.models||[]).find((V)=>V.id===$);if(!w){this.log(`⚠️ 模型配置未找到: ${$}`);return}await this.applyModelConfig(w,"\uD83D\uDD01 切换模型")}static async create($,b={}){if(($.models||[]).length===0)throw Error(`❌ 没有可用的模型配置
|
|
1805
1831
|
|
|
1806
1832
|
`+`请先使用以下命令添加模型:
|
|
1807
1833
|
`+` /model add
|
|
1808
1834
|
|
|
1809
1835
|
`+`或运行初始化向导:
|
|
1810
|
-
`+" /init");let
|
|
1836
|
+
`+" /init");let V=new g$($,b);if(await V.initialize(),b.toolWhitelist&&b.toolWhitelist.length>0)V.applyToolWhitelist(b.toolWhitelist);return V}async initialize(){if(this.isInitialized)return;try{this.log("初始化Agent..."),await this.initializeSystemPrompt(),await this.registerBuiltinTools(),await this.loadSubagents(),await this.discoverSkills();let $=this.resolveModelConfig(this.runtimeOptions.modelId);await this.applyModelConfig($,"\uD83D\uDE80 使用模型:"),this.attachmentHandler=new jw(process.cwd()),this.streamHandler=new kw(()=>this.chatService),this.compactionHandler=new Nw(()=>this.chatService,()=>this.executionEngine?.getContextManager()),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 b=await this.executionEngine.executeTask($);return this.activeTask=void 0,this.log(`任务执行完成: ${$.id}`),b}catch(b){throw this.activeTask=void 0,this.error(`任务执行失败: ${$.id}`,b),b}}async chat($,b,w){if(!this.isInitialized)throw Error("Agent未初始化");let V=this.attachmentHandler?await this.attachmentHandler.processAtMentionsForContent($):$;if(b){let Y={signal:b.signal,...w},J;if(b.permissionMode==="plan")J=await this.runPlanLoop(V,b,Y);else J=await this.runLoop(V,b,Y);if(!J.success){if(J.error?.type==="aborted"||J.metadata?.shouldExitLoop)return"";throw Error(J.error?.message||"执行失败")}if(J.metadata?.targetMode&&b.permissionMode==="plan"){let X=J.metadata.targetMode,O=J.metadata.planContent;H.debug(`\uD83D\uDD04 Plan 模式已批准,切换到 ${X} 模式并重新执行`);let G={...b,permissionMode:X},B=V;if(O){let q=`
|
|
1811
1837
|
|
|
1812
1838
|
<approved-plan>
|
|
1813
|
-
${
|
|
1839
|
+
${O}
|
|
1814
1840
|
</approved-plan>
|
|
1815
1841
|
|
|
1816
|
-
IMPORTANT: Execute according to the approved plan above. Follow the steps exactly as specified.`;if(typeof
|
|
1817
|
-
`),
|
|
1842
|
+
IMPORTANT: Execute according to the approved plan above. Follow the steps exactly as specified.`;if(typeof V==="string")B=V+q;else B=[...V,{type:"text",text:q}];H.debug(`\uD83D\uDCCB 已将 plan 内容注入到消息中 (${O.length} 字符)`)}return this.runLoop(B,G,Y).then((q)=>{if(!q.success)throw Error(q.error?.message||"执行失败");return q.finalMessage||""})}return J.finalMessage||""}let W=typeof V==="string"?V:V.filter((Y)=>Y.type==="text").map((Y)=>Y.text).join(`
|
|
1843
|
+
`),Q={id:this.generateTaskId(),type:"simple",prompt:W};return(await this.executeTask(Q)).content}streamChat($,b,w){if(!this.isInitialized)throw Error("Agent未初始化");let W=(async()=>{let Z=this.attachmentHandler?await this.attachmentHandler.processAtMentionsForContent($):$;if(!b)throw Error("Context is required for streaming");let Y={signal:b.signal,...w};if(b.permissionMode==="plan"){let J=this.runPlanLoopStream(Z,b,Y),X,O=[];while(!0){let{value:G,done:B}=await J.next();if(B){X=G;break}O.push(G)}if(X?.metadata?.targetMode){let G=X.metadata.targetMode,B=X.metadata.planContent,q={...b,permissionMode:G},A=Z;if(B){let K=`
|
|
1818
1844
|
|
|
1819
1845
|
<approved-plan>
|
|
1820
|
-
${
|
|
1846
|
+
${B}
|
|
1821
1847
|
</approved-plan>
|
|
1822
1848
|
|
|
1823
|
-
IMPORTANT: Execute according to the approved plan above. Follow the steps exactly as specified.`;if(typeof
|
|
1849
|
+
IMPORTANT: Execute according to the approved plan above. Follow the steps exactly as specified.`;if(typeof Z==="string")A=Z+K;else A=[...Z,{type:"text",text:K}]}return{events:O,continuation:this.runLoopStream(A,q,Y)}}return{events:O,result:X}}return{continuation:this.runLoopStream(Z,b,Y)}})();return async function*(){let Z=await W;if("events"in Z&&Z.events)for(let Y of Z.events)yield Y;if("continuation"in Z&&Z.continuation)return yield*Z.continuation;return Z.result}()}async runPlanLoop($,b,w){H.debug("\uD83D\uDD35 Processing Plan mode message...");let{prompt:V}=await R0({projectPath:process.cwd(),mode:v.PLAN,includeEnvironment:!0,language:this.config.language}),W;if(typeof $==="string")W=n$($);else{let Q=$.filter((Z)=>Z.type==="text");if(Q.length>0){let Z=Q[0];W=$.map((Y)=>Y===Z?{type:"text",text:n$(Z.text)}:Y)}else W=[{type:"text",text:n$("")},...$]}return this.executeLoop(W,b,w,V)}async*runPlanLoopStream($,b,w){let{prompt:V}=await R0({projectPath:process.cwd(),mode:v.PLAN,includeEnvironment:!0,language:this.config.language}),W;if(typeof $==="string")W=n$($);else{let Q=$.filter((Z)=>Z.type==="text");if(Q.length>0){let Z=Q[0];W=$.map((Y)=>Y===Z?{type:"text",text:n$(Z.text)}:Y)}else W=[{type:"text",text:n$("")},...$]}return yield*this.executeLoopStream(W,b,w,V)}async runLoop($,b,w){H.debug("\uD83D\uDCAC Processing enhanced chat message...");let V=b.systemPrompt??await this.buildSystemPromptOnDemand(),W=l0(),Q=V?`${W}
|
|
1824
1850
|
|
|
1825
1851
|
---
|
|
1826
1852
|
|
|
1827
|
-
${
|
|
1853
|
+
${V}`:W;return this.executeLoop($,b,w,Q)}async*runLoopStream($,b,w){let V=b.systemPrompt??await this.buildSystemPromptOnDemand(),W=l0(),Q=V?`${W}
|
|
1828
1854
|
|
|
1829
1855
|
---
|
|
1830
1856
|
|
|
1831
|
-
${
|
|
1832
|
-
`);if(
|
|
1857
|
+
${V}`:W;return yield*this.executeLoopStream($,b,w,Q)}async buildSystemPromptOnDemand(){let $=this.runtimeOptions.systemPrompt,b=this.runtimeOptions.appendSystemPrompt;return(await R0({projectPath:process.cwd(),replaceDefault:$,append:b,includeEnvironment:!1,language:this.config.language})).prompt}async executeLoop($,b,w,V){let W=this.executeLoopStream($,b,w,V),Q;while(!0){let{value:Z,done:Y}=await W.next();if(Y){Q=Z;break}}return Q}async*executeLoopStream($,b,w,V){if(!this.isInitialized)throw Error("Agent未初始化");let W=Date.now();try{let Q=this.executionPipeline.getRegistry(),Z=b.permissionMode,Y=Q.getFunctionDeclarationsByMode(Z);Y=Db(Y);let J=this.applySkillToolRestrictions(Y);if(Z===v.PLAN){let N=Q.getReadOnlyTools();H.debug(`\uD83D\uDD12 Plan mode: 使用只读工具 (${N.length} 个): ${N.map((M)=>M.name).join(", ")}`)}let O=b.messages.length===0||!b.messages.some((N)=>N.role==="system"),G=[];if(O&&V)G.push({role:"system",content:[{type:"text",text:V,providerOptions:{anthropic:{cacheControl:{type:"ephemeral"}}}}]});G.push(...b.messages,{role:"user",content:$});let B=null;try{let N=this.executionEngine?.getContextManager(),M=typeof $==="string"?$:$.filter((j)=>j.type==="text").map((j)=>j.text).join(`
|
|
1858
|
+
`);if(N&&b.sessionId&&M.trim()!=="")B=await N.saveMessage(b.sessionId,"user",M,null,void 0,b.subagentInfo);else if(M.trim()==="")H.debug("[Agent] 跳过保存空用户消息")}catch(N){H.warn("[Agent] 保存用户消息失败:",N)}let q=100,A=b.permissionMode===v.YOLO,K=this.runtimeOptions.maxTurns??w?.maxTurns??this.config.maxTurns??-1;if(K===0)return{success:!1,error:{type:"chat_disabled",message:`对话功能已被禁用 (maxTurns=0)。如需启用,请调整配置:
|
|
1833
1859
|
`+` • CLI 参数: blade --max-turns -1
|
|
1834
1860
|
`+` • 配置文件: ~/.blade/config.json 中设置 "maxTurns": -1
|
|
1835
|
-
`+" • 环境变量: export BLADE_MAX_TURNS=-1"},metadata:{turnsCount:0,toolCallsCount:0,duration:0}};let
|
|
1836
|
-
========== 发送给 LLM ==========`),
|
|
1837
|
-
`);let
|
|
1838
|
-
========== LLM 返回 ==========`),
|
|
1839
|
-
`),
|
|
1861
|
+
`+" • 环境变量: export BLADE_MAX_TURNS=-1"},metadata:{turnsCount:0,toolCallsCount:0,duration:0}};let U=K===-1?q:Math.min(K,q);if(this.config.debug)H.debug(`[MaxTurns] runtimeOptions: ${this.runtimeOptions.maxTurns}, options: ${w?.maxTurns}, config: ${this.config.maxTurns}, 最终: ${K} → ${U}, YOLO: ${A}`);let F=0,_=[],D=0,I;while(!0){if(w?.signal?.aborted)return{success:!1,error:{type:"aborted",message:"任务已被用户中止"},metadata:{turnsCount:F,toolCallsCount:_.length,duration:Date.now()-W}};let N=b.messages.length,M=!1;if(this.compactionHandler){let L=this.compactionHandler.checkAndCompactInLoop(b,F,I);while(!0){let{value:R,done:T}=await L.next();if(T){M=R;break}yield R}}if(M){H.debug(`[Agent] [轮次 ${F}] 检测到压缩发生,重建 messages 数组 (${N} → ${b.messages.length} 条历史消息)`);let L=O&&V?1:0,R=L+N,T=G.slice(0,L),h=G.slice(R);G.length=0,G.push(...T,...b.messages,...h),H.debug(`[Agent] [轮次 ${F}] messages 重建完成: ${T.length} system + ${b.messages.length} 历史 + ${h.length} 新增 = ${G.length} 总计`)}if(F++,H.debug(`\uD83D\uDD04 [轮次 ${F}/${U}] 调用 LLM...`),w?.signal?.aborted)return{success:!1,error:{type:"aborted",message:"任务已被用户中止"},metadata:{turnsCount:F-1,toolCallsCount:_.length,duration:Date.now()-W}};yield{type:"turn_start",turn:F,maxTurns:U},H.debug(`
|
|
1862
|
+
========== 发送给 LLM ==========`),H.debug("轮次:",F+1),H.debug("消息数量:",G.length),H.debug("最后 3 条消息:"),G.slice(-3).forEach((L,R)=>{if(H.debug(` [${R}] ${L.role}:`,typeof L.content==="string"?L.content.substring(0,100)+(L.content.length>100?"...":""):JSON.stringify(L.content).substring(0,100)),L.tool_calls)H.debug(" tool_calls:",L.tool_calls.map((T)=>("function"in T)?T.function.name:T.type).join(", "))}),H.debug("可用工具数量:",J.length),H.debug(`================================
|
|
1863
|
+
`);let j;if(this.streamHandler){let L=this.streamHandler.streamResponse(G,J,w?.signal);while(!0){let{value:R,done:T}=await L.next();if(T){j=R;break}if(R.type==="content_delta")yield{type:"content_delta",delta:R.delta};else yield{type:"thinking_delta",delta:R.delta}}}else j=await this.chatService.chat(G,J,w?.signal);if(qb("executeLoop","after processStreamResponse/chat",{turnResultContentLen:j.content?.length??0,turnResultToolCallsLen:j.toolCalls?.length??0,hasReasoningContent:!!j.reasoningContent}),j.usage){if(j.usage.totalTokens)D+=j.usage.totalTokens;I=j.usage.promptTokens,H.debug(`[Agent] LLM usage: prompt=${I}, completion=${j.usage.completionTokens}, total=${j.usage.totalTokens}`),yield{type:"token_usage",usage:{inputTokens:j.usage.promptTokens??0,outputTokens:j.usage.completionTokens??0,totalTokens:D,maxContextTokens:this.currentModelMaxContextTokens}}}if(w?.signal?.aborted)return{success:!1,error:{type:"aborted",message:"任务已被用户中止"},metadata:{turnsCount:F-1,toolCallsCount:_.length,duration:Date.now()-W}};if(H.debug(`
|
|
1864
|
+
========== LLM 返回 ==========`),H.debug("Content:",j.content),H.debug("Tool Calls:",JSON.stringify(j.toolCalls,null,2)),H.debug("当前权限模式:",b.permissionMode),H.debug(`================================
|
|
1865
|
+
`),j.reasoningContent&&!w?.signal?.aborted)yield{type:"thinking",content:j.reasoningContent};if(j.content&&j.content.trim()&&!w?.signal?.aborted)yield{type:"stream_end"};if(!j.toolCalls||j.toolCalls.length===0){let L=[/:\s*$/,/:\s*$/,/\.\.\.\s*$/,/让我(先|来|开始|查看|检查|修复)/,/Let me (first|start|check|look|fix)/i],R=j.content||"",T=L.some((x)=>x.test(R)),h="请执行你提到的操作,不要只是描述。",k=G.slice(-10).filter((x)=>x.role==="user"&&x.content==="请执行你提到的操作,不要只是描述。").length;if(T&&k<2){H.debug(`⚠️ 检测到意图未完成(重试 ${k+1}/2): "${R.slice(-50)}"`),G.push({role:"user",content:"请执行你提到的操作,不要只是描述。"});continue}H.debug("✅ 任务完成 - LLM 未请求工具调用");try{let m=await r.getInstance().executeStopHooks({projectDir:process.cwd(),sessionId:b.sessionId,permissionMode:b.permissionMode,reason:j.content,abortSignal:w?.signal});if(!m.shouldStop){H.debug(`\uD83D\uDD04 Stop hook 阻止停止,继续执行: ${m.continueReason||"(无原因)"}`);let e=m.continueReason?`
|
|
1840
1866
|
|
|
1841
1867
|
<system-reminder>
|
|
1842
|
-
${
|
|
1868
|
+
${m.continueReason}
|
|
1843
1869
|
</system-reminder>`:`
|
|
1844
1870
|
|
|
1845
1871
|
<system-reminder>
|
|
1846
1872
|
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.
|
|
1847
|
-
</system-reminder>`;
|
|
1848
|
-
========== 工具执行结果 ==========`),
|
|
1849
|
-
`),{toolCall:
|
|
1850
|
-
|
|
1851
|
-
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.`};
|
|
1852
|
-
${
|
|
1853
|
-
\`\`\``;
|
|
1854
|
-
|
|
1855
|
-
`,
|
|
1856
|
-
`;if(
|
|
1857
|
-
(${Y} of ${W} commands shown due to character budget)`;return{text:Q,includedCount:Y,totalCount:W}}}import{nanoid as $3}from"nanoid";var j$=T("Agent");class j1{sessionId;agent=null;abortController=null;_messages=[];options;maxTurns;permissionMode;initialized=!1;pendingMessage=null;pendingSendOptions=null;constructor($,V){this.sessionId=V||$3(),this.options=$,this.maxTurns=$.maxTurns??200,this.permissionMode=$.permissionMode??S.DEFAULT}get messages(){return[...this._messages]}async initialize(){if(this.initialized)return;let $=this.buildBladeConfig();this.agent=await S$.create($,{permissionMode:this.permissionMode,systemPrompt:this.options.systemPrompt,maxTurns:this.maxTurns,canUseTool:this.options.canUseTool}),this.initialized=!0,j$.debug(`[Session] Initialized session ${this.sessionId}`)}async loadHistory(){let $=this.options.cwd||process.cwd(),V=B$($,this.sessionId),W=new Y$(V);try{let Q=await W.readAll();if(Q.length===0){j$.debug(`[Session] No history found for session ${this.sessionId}`);return}let Z=new Map,Y=new Map;for(let J of Q){if(J.type==="message_created"){let X=J.data;Z.set(X.messageId,{role:X.role,content:"",toolCalls:[]})}if(J.type==="part_created"){let X=J.data,G=Z.get(X.messageId);if(!G)G={role:X.partType==="tool_result"?"tool":"assistant",content:"",toolCalls:[]},Z.set(X.messageId,G);switch(X.partType){case"text":{let B=X.payload;G.content=B.text??"";break}case"tool_call":{let B=X.payload,K={id:B.toolCallId,type:"function",function:{name:B.toolName,arguments:typeof B.input==="string"?B.input:JSON.stringify(B.input)}};G.toolCalls.push(K),Y.set(B.toolCallId,{messageId:X.messageId,toolCallId:B.toolCallId});break}case"tool_result":{let B=X.payload;if(G.role="tool",G.toolCallId=B.toolCallId,G.name=B.toolName,B.error)G.content=`Error: ${B.error}`;else if(B.output===null||B.output===void 0)G.content="";else if(typeof B.output==="string")G.content=B.output;else G.content=JSON.stringify(B.output);break}case"summary":{let B=X.payload;G.content=B.text??"";break}}}}this._messages=Array.from(Z.values()).map((J)=>{let X={role:J.role,content:J.content};if(J.toolCalls.length>0)X.tool_calls=J.toolCalls;if(J.toolCallId)X.tool_call_id=J.toolCallId;if(J.name)X.name=J.name;return X}),j$.debug(`[Session] Loaded ${this._messages.length} messages from history`)}catch(Q){j$.warn(`[Session] Failed to load history for session ${this.sessionId}:`,Q)}}buildBladeConfig(){let $=this.buildModelConfig();return{models:[$],currentModelId:$.id,temperature:0.7,mcpServers:this.options.mcpServers,permissions:{allow:[],deny:[]}}}buildModelConfig(){let $=this.options.provider;return{id:"default",name:this.options.model,provider:this.mapProviderType($.type),model:this.options.model,apiKey:$.apiKey||"",baseUrl:$.baseUrl||this.getDefaultBaseUrl($.type),maxTokens:128000}}mapProviderType($){return{"openai-compatible":"openai-compatible",anthropic:"anthropic",gemini:"gemini","azure-openai":"azure-openai"}[$]||"openai-compatible"}getDefaultBaseUrl($){return{"openai-compatible":"https://api.openai.com/v1",anthropic:"https://api.anthropic.com",gemini:"https://generativelanguage.googleapis.com","azure-openai":""}[$]||""}async send($,V){if(await this.ensureInitialized(),this.pendingMessage!==null)throw Error("Cannot send a new message while a previous message is pending. Call stream() first.");this.pendingMessage=$,this.pendingSendOptions=V||null}async*stream($){if(this.pendingMessage===null)throw Error("No pending message. Call send() before stream().");let V=this.pendingMessage,W=this.pendingSendOptions;this.pendingMessage=null,this.pendingSendOptions=null;let Q=[],Z={inputTokens:0,outputTokens:0,totalTokens:0,maxContextTokens:0};this.abortController=new AbortController;let Y=W?.signal?this.combineSignals(W.signal,this.abortController.signal):this.abortController.signal,J={messages:this._messages,userId:"sdk-user",sessionId:this.sessionId,workspaceRoot:this.options.cwd||process.cwd(),signal:Y,permissionMode:this.permissionMode},X=this.agent.streamChat(V,J,{maxTurns:W?.maxTurns??this.maxTurns,signal:Y});try{let G;while(!0){let{value:q,done:O}=await X.next();if(O){G=q;break}switch(q.type){case"turn_start":yield{type:"turn_start",turn:q.turn,sessionId:this.sessionId};break;case"content_delta":yield{type:"content",delta:q.delta,sessionId:this.sessionId};break;case"thinking_delta":if($?.includeThinking)yield{type:"thinking",delta:q.delta,sessionId:this.sessionId};break;case"content":yield{type:"content",delta:q.content,sessionId:this.sessionId};break;case"thinking":if($?.includeThinking)yield{type:"thinking",delta:q.content,sessionId:this.sessionId};break;case"tool_start":{if(q.toolCall.type!=="function")break;let w=this.safeParseJson(q.toolCall.function.arguments);Q.push({id:q.toolCall.id,name:q.toolCall.function.name,input:w,output:null,duration:0}),yield{type:"tool_use",id:q.toolCall.id,name:q.toolCall.function.name,input:w,sessionId:this.sessionId};break}case"tool_result":{if(q.toolCall.type!=="function")break;let w=Q.find((b)=>b.id===q.toolCall.id);if(w)w.output=q.result.llmContent,w.isError=!q.result.success;yield{type:"tool_result",id:q.toolCall.id,name:q.toolCall.function.name,output:q.result.llmContent,isError:!q.result.success,sessionId:this.sessionId};break}case"token_usage":Z={inputTokens:q.usage.inputTokens,outputTokens:q.usage.outputTokens,totalTokens:q.usage.totalTokens,maxContextTokens:q.usage.maxContextTokens};break;default:break}}if(!G)throw Error("Stream ended without result");let B=G.error?.type==="aborted",K=G.metadata?.shouldExitLoop;if(!G.success&&!B&&!K){yield{type:"error",message:G.error?.message||"Unknown error",sessionId:this.sessionId};return}yield{type:"usage",usage:Z,sessionId:this.sessionId},this._messages=J.messages,yield{type:"result",subtype:"success",content:G.finalMessage||"",sessionId:this.sessionId}}catch(G){yield{type:"error",message:G instanceof Error?G.message:String(G),sessionId:this.sessionId}}finally{this.abortController=null}}close(){this.abort(),this.agent=null,this.initialized=!1,this.pendingMessage=null,this.pendingSendOptions=null,j$.debug(`[Session] Closed session ${this.sessionId}`)}abort(){if(this.abortController)this.abortController.abort(),this.abortController=null}setPermissionMode($){this.permissionMode=$}async setModel($){j$.warn("[Session] setModel is not yet implemented")}setMaxTurns($){this.maxTurns=$}async supportedCommands(){let $=C$.getInstance();if(!$.isInitialized())await $.initialize(this.options.cwd||process.cwd());return $.getAllCommands().map((V)=>({name:V.name,description:V.config.description||"",usage:V.config.argumentHint}))}async supportedModels(){return[{id:"default",name:this.options.model,provider:this.options.provider.type}]}async mcpServerStatus(){let V=s.getInstance().getAllServers(),W=[];for(let[Q,Z]of V){let Y={connected:"connected",disconnected:"disconnected",connecting:"connecting",error:"error"};W.push({name:Q,status:Y[Z.status],toolCount:Z.tools.length,tools:Z.tools.map((J)=>J.name),connectedAt:Z.connectedAt,error:Z.lastError?.message})}return W}async mcpConnect($){await this.ensureInitialized();let V=s.getInstance();if(!V.getServerStatus($)){let Q=this.options.mcpServers?.[$];if(!Q)throw Error(`MCP server "${$}" not found in configuration`);await V.registerServer($,Q)}else await V.connectServer($);j$.debug(`[Session] Connected to MCP server: ${$}`)}async mcpDisconnect($){await s.getInstance().disconnectServer($),j$.debug(`[Session] Disconnected from MCP server: ${$}`)}async mcpReconnect($){await s.getInstance().reconnectServer($),j$.debug(`[Session] Reconnected to MCP server: ${$}`)}async mcpListTools(){let V=s.getInstance().getAllServers(),W=[];for(let[Q,Z]of V)if(Z.status==="connected")for(let Y of Z.tools)W.push({name:Y.name,description:Y.description,serverName:Q});return W}async[Symbol.asyncDispose](){this.close()}async ensureInitialized(){if(!this.initialized)await this.initialize()}combineSignals($,V){let W=new AbortController,Q=()=>W.abort();if($.aborted||V.aborted)W.abort();else $.addEventListener("abort",Q),V.addEventListener("abort",Q);return W.signal}safeParseJson($){try{return JSON.parse($)}catch{return $}}}async function K5($){let V=new j1($);return await V.initialize(),j$.debug(`[Session] Created new session: ${V.sessionId}`),V}async function q5($){let{sessionId:V,...W}=$,Q=new j1(W,V);return await Q.initialize(),await Q.loadHistory(),j$.debug(`[Session] Resumed session: ${V} with ${Q.messages.length} messages`),Q}async function O5($,V){let W=Date.now(),Q=new j1(V);await Q.initialize();let Z=[],Y={inputTokens:0,outputTokens:0,totalTokens:0,maxContextTokens:0},J=0,X="",G=null;try{await Q.send($);for await(let B of Q.stream())if(B.type==="turn_start")J=B.turn;else if(B.type==="tool_use")Z.push({id:B.id,name:B.name,input:B.input,output:null,duration:0});else if(B.type==="tool_result"){let K=Z.find((q)=>q.id===B.id);if(K)K.output=B.output,K.isError=B.isError}else if(B.type==="usage")Y=B.usage;else if(B.type==="result"&&B.subtype==="success")X=B.content||"";else if(B.type==="error")G=B.message;else if(B.type==="result"&&B.subtype==="error")G=B.error||"Unknown error";if(G)throw Error(G);return{result:X,toolCalls:Z,usage:Y,duration:Date.now()-W,turnsCount:J}}finally{Q.close()}}export{u7 as toolFromDefinition,h3 as shutdownLogger,f3 as setLoggerSessionId,q5 as resumeSession,O5 as prompt,x3 as logger,Y0 as isReadOnlyKind,DW as isGlobMetadata,_W as isEditMetadata,W1 as injectSkillsMetadata,h2 as getBuiltinTools,V1 as discoverSkills,d7 as defineTool,N as createTool,K5 as createSession,T as createLogger,l0 as createChatServiceAsync,p0 as ToolRegistry,D5 as ToolKind,c1 as ToolExecution,R5 as ToolErrorType,H5 as StreamMessageType,u as SpecManager,r$ as STEERING_FILES,A8 as SPEC_FILE_NAMES,n$ as SPEC_DIRS,R1 as PermissionMode,j5 as PermissionDecision,_5 as PermissionBehavior,k0 as PHASE_TRANSITIONS,w8 as PHASE_PRIMARY_FILE,UJ as PHASE_ORDER,O$ as PHASE_DISPLAY_NAMES,J4 as MessageRole,s as McpRegistry,t1 as McpErrorType,d$ as McpConnectionStatus,R0 as McpClient,M$ as Logger,g1 as LogLevel,n as LogCategory,L5 as HookType,l as HookManager,N5 as HookExitCode,F0 as HookEvent,o1 as HealthStatus,N0 as HealthMonitor,b1 as ExecutionPipeline,C5 as DecisionBehavior,C1 as ContextManager,t as CompactionService,C$ as CommandRegistry,u0 as CommandParser,d0 as CommandLoader,g0 as CommandExecutor,S$ as Agent};
|
|
1873
|
+
</system-reminder>`;G.push({role:"user",content:e});continue}if(m.warning)H.warn(`[Agent] Stop hook warning: ${m.warning}`)}catch(x){H.warn("[Agent] Stop hook execution failed:",x)}try{let x=this.executionEngine?.getContextManager();if(x&&b.sessionId&&j.content)if(j.content.trim()!=="")B=await x.saveMessage(b.sessionId,"assistant",j.content,B,void 0,b.subagentInfo);else H.debug("[Agent] 跳过保存空响应(任务完成时)")}catch(x){H.warn("[Agent] 保存助手消息失败:",x)}return{success:!0,finalMessage:j.content,metadata:{turnsCount:F,toolCallsCount:_.length,duration:Date.now()-W,tokensUsed:D}}}G.push({role:"assistant",content:j.content||"",reasoningContent:j.reasoningContent,tool_calls:j.toolCalls});try{let L=this.executionEngine?.getContextManager();if(L&&b.sessionId&&j.content)if(j.content.trim()!=="")B=await L.saveMessage(b.sessionId,"assistant",j.content,B,void 0,b.subagentInfo);else H.debug("[Agent] 跳过保存空响应(工具调用时)")}catch(L){H.warn("[Agent] 保存助手工具调用消息失败:",L)}if(w?.signal?.aborted)return H.info("[Agent] Aborting before tool execution due to signal.aborted=true"),{success:!1,error:{type:"aborted",message:"任务已被用户中止"},metadata:{turnsCount:F,toolCallsCount:_.length,duration:Date.now()-W}};let F$=j.toolCalls.filter((L)=>L.type==="function");for(let L of F$){let T=this.executionPipeline.getRegistry().get(L.function.name)?.kind;yield{type:"tool_start",toolCall:L,toolKind:T}}let P=async(L)=>{try{let R=JSON.parse(L.function.arguments);if(L.function.name==="Task"&&(typeof R.subagent_session_id!=="string"||R.subagent_session_id.length===0))R.subagent_session_id=typeof R.resume==="string"&&R.resume.length>0?R.resume:aV();if(R.todos&&typeof R.todos==="string")try{R.todos=JSON.parse(R.todos),this.log("[Agent] 自动修复了字符串化的 todos 参数")}catch{this.error("[Agent] todos 参数格式异常,将由验证层处理")}let T=null;try{let x=this.executionEngine?.getContextManager();if(x&&b.sessionId)T=await x.saveToolUse(b.sessionId,L.function.name,R,B,b.subagentInfo)}catch(x){H.warn("[Agent] 保存工具调用失败:",x)}let h=w?.signal;if(!h)H.error("[Agent] Missing signal in tool execution, this should not happen");H.debug("[Agent] Passing confirmationHandler to ExecutionPipeline.execute:",{toolName:L.function.name,hasHandler:!!b.confirmationHandler,hasMethod:!!b.confirmationHandler?.requestConfirmation,methodType:typeof b.confirmationHandler?.requestConfirmation});let k=await this.executionPipeline.execute(L.function.name,R,{sessionId:b.sessionId,userId:b.userId||"default",workspaceRoot:b.workspaceRoot||process.cwd(),signal:h,confirmationHandler:b.confirmationHandler,permissionMode:b.permissionMode});if(H.debug(`
|
|
1874
|
+
========== 工具执行结果 ==========`),H.debug("工具名称:",L.function.name),H.debug("成功:",k.success),H.debug("LLM Content:",k.llmContent),H.debug("Display Content:",k.displayContent),k.error)H.debug("错误:",k.error);return H.debug(`==================================
|
|
1875
|
+
`),{toolCall:L,result:k,toolUseUuid:T}}catch(R){return H.error(`Tool execution failed for ${L.function.name}:`,R),{toolCall:L,result:{success:!1,llmContent:"",displayContent:"",error:{type:"execution_error",message:R instanceof Error?R.message:"Unknown error"}},toolUseUuid:null,error:R instanceof Error?R:Error("Unknown error")}}};H.info(`[Agent] Executing ${F$.length} tool calls in parallel`);let w$=await Promise.all(F$.map(P));for(let{toolCall:L,result:R,toolUseUuid:T}of w$){if(_.push(R),R.metadata?.shouldExitLoop){H.debug("\uD83D\uDEAA 检测到退出循环标记,结束 Agent 循环");let m=typeof R.llmContent==="string"?R.llmContent:"循环已退出";return{success:R.success,finalMessage:m,metadata:{turnsCount:F,toolCallsCount:_.length,duration:Date.now()-W,shouldExitLoop:!0,targetMode:R.metadata?.targetMode}}}yield{type:"tool_result",toolCall:L,result:R};try{let m=this.executionEngine?.getContextManager();if(m&&b.sessionId){let e=R.metadata&&typeof R.metadata==="object"?R.metadata:void 0,b1=((A0)=>A0==="running"||A0==="completed"||A0==="failed"||A0==="cancelled")(e?.subagentStatus)?e.subagentStatus:"completed",Pw=e&&typeof e.subagentSessionId==="string"?{subagentSessionId:e.subagentSessionId,subagentType:typeof e.subagentType==="string"?e.subagentType:L.function.name,subagentStatus:b1,subagentSummary:typeof e.subagentSummary==="string"?e.subagentSummary:void 0}:void 0;B=await m.saveToolResult(b.sessionId,L.id,L.function.name,R.success?oV(R.llmContent):null,T,R.success?void 0:R.error?.message,b.subagentInfo,Pw)}}catch(m){H.warn("[Agent] 保存工具结果失败:",m)}if(L.function.name==="TodoWrite"&&R.success&&R.llmContent){let m=typeof R.llmContent==="object"?R.llmContent:{};yield{type:"todo_update",todos:Array.isArray(m)?m:m.todos||[]}}if(L.function.name==="Skill"&&R.success&&R.metadata){let m=R.metadata;if(m.skillName)this.activeSkillContext={skillName:m.skillName,allowedTools:m.allowedTools,basePath:m.basePath||""},H.debug(`\uD83C\uDFAF Skill "${this.activeSkillContext.skillName}" activated`+(this.activeSkillContext.allowedTools?` with allowed tools: ${this.activeSkillContext.allowedTools.join(", ")}`:""))}let h=R.metadata?.modelId?.trim()||R.metadata?.model?.trim()||void 0;if(h)await this.switchModelIfNeeded(h);let k=R.success?R.llmContent||R.displayContent||"":R.error?.message||"执行失败";if(typeof k==="object"&&k!==null)k=JSON.stringify(k,null,2);let x=typeof k==="string"?k:JSON.stringify(k);G.push({role:"tool",tool_call_id:L.id,name:L.function.name,content:x})}if(w?.signal?.aborted)return{success:!1,error:{type:"aborted",message:"任务已被用户中止"},metadata:{turnsCount:F,toolCallsCount:_.length,duration:Date.now()-W}};if(F>=U&&!A){if(H.info(`⚠️ 达到轮次上限 ${U} 轮,等待用户确认...`),w?.onTurnLimitReached){let L=await w.onTurnLimitReached({turnsCount:F});if(L?.continue){H.info("✅ 用户选择继续,压缩上下文...");try{let R=this.chatService.getConfig(),T=await b$.compact(b.messages,{trigger:"auto",modelName:R.model,maxContextTokens:R.maxContextTokens??128000,apiKey:R.apiKey,baseURL:R.baseUrl,actualPreTokens:I});b.messages=T.compactedMessages;let h=G.find((x)=>x.role==="system");if(G.length=0,h)G.push(h);G.push(...b.messages);let k={role:"user",content:`This session is being continued from a previous conversation. The conversation is summarized above.
|
|
1876
|
+
|
|
1877
|
+
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.`};G.push(k),b.messages.push(k);try{let x=this.executionEngine?.getContextManager();if(x&&b.sessionId)await x.saveCompaction(b.sessionId,T.summary,{trigger:"auto",preTokens:T.preTokens,postTokens:T.postTokens,filesIncluded:T.filesIncluded},null)}catch(x){H.warn("[Agent] 保存压缩数据失败:",x)}H.info(`✅ 上下文已压缩 (${T.preTokens} → ${T.postTokens} tokens),重置轮次计数`)}catch(R){H.error("[Agent] 压缩失败,使用降级策略:",R);let T=G.find((k)=>k.role==="system"),h=G.slice(-80);if(G.length=0,T&&!h.some((k)=>k.role==="system"))G.push(T);G.push(...h),b.messages=G.filter((k)=>k.role!=="system"),H.warn(`⚠️ 降级压缩完成,保留 ${G.length} 条消息`)}F=0;continue}return{success:!0,finalMessage:L?.reason||"已达到对话轮次上限,用户选择停止",metadata:{turnsCount:F,toolCallsCount:_.length,duration:Date.now()-W,tokensUsed:D}}}return{success:!1,error:{type:"max_turns_exceeded",message:`已达到轮次上限 (${U} 轮)。使用 --permission-mode yolo 跳过此限制。`},metadata:{turnsCount:F,toolCallsCount:_.length,duration:Date.now()-W,tokensUsed:D}}}}}catch(Q){if(Q instanceof Error&&(Q.name==="AbortError"||Q.message.includes("aborted")))return{success:!1,error:{type:"aborted",message:"任务已被用户中止"},metadata:{turnsCount:0,toolCallsCount:0,duration:Date.now()-W}};return H.error("Enhanced chat processing error:",Q),{success:!1,error:{type:"api_error",message:`处理消息时发生错误: ${Q instanceof Error?Q.message:"未知错误"}`,details:Q},metadata:{turnsCount:0,toolCallsCount:0,duration:Date.now()-W}}}}async runAgenticLoop($,b,w){if(!this.isInitialized)throw Error("Agent未初始化");let V={messages:b.messages,userId:b.userId||"subagent",sessionId:b.sessionId||`subagent_${Date.now()}`,workspaceRoot:b.workspaceRoot||process.cwd(),signal:b.signal,confirmationHandler:b.confirmationHandler,permissionMode:b.permissionMode,systemPrompt:b.systemPrompt,subagentInfo:b.subagentInfo};return await this.runLoop($,V,w)}async chatWithSystem($,b){if(!this.isInitialized)throw Error("Agent未初始化");let w=[{role:"system",content:$},{role:"user",content:b}];return(await this.chatService.chat(w)).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 b=this.executionPipeline.getRegistry(),V=b.getAll().filter((W)=>!$.includes(W.name));for(let W of V)b.unregister(W.name);H.debug(`\uD83D\uDD12 Applied tool whitelist: ${$.join(", ")} (removed ${V.length} tools)`)}getToolStats(){let $=this.getAvailableTools(),b=new Map;return $.forEach((w)=>{let V=b.get(w.kind)||0;b.set(w.kind,V+1)}),{totalTools:$.length,toolsByKind:Object.fromEntries(b),toolNames:$.map((w)=>w.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($,b){H.debug(`[MainAgent] ${$}`,b||"")}error($,b){H.error(`[MainAgent] ${$}`,b||"")}async initializeSystemPrompt(){try{let $=this.runtimeOptions.systemPrompt,b=this.runtimeOptions.appendSystemPrompt,w=await R0({projectPath:process.cwd(),replaceDefault:$,append:b,includeEnvironment:!1,language:this.config.language});if(w.prompt)this.log("系统提示配置验证成功"),H.debug(`[SystemPrompt] 可用来源: ${w.sources.filter((V)=>V.loaded).map((V)=>V.name).join(", ")}`)}catch($){this.error("系统提示配置验证失败",$)}}async getSystemPrompt(){return this.buildSystemPromptOnDemand()}async registerBuiltinTools(){try{let $=await qw({sessionId:"default",configDir:x2.join(h2.homedir(),".blade")});H.debug(`\uD83D\uDCE6 Registering ${$.length} builtin tools...`),this.executionPipeline.getRegistry().registerAll($);let b=this.executionPipeline.getRegistry().getAll().length;H.debug(`✅ Builtin tools registered: ${b} tools`),H.debug(`[Tools] ${this.executionPipeline.getRegistry().getAll().map((w)=>w.name).join(", ")}`),await this.registerMcpTools()}catch($){throw H.error("Failed to register builtin tools:",$),$}}async registerMcpTools(){try{let $=this.config.mcpServers||{};if(Object.keys($).length===0){H.debug("\uD83D\uDCE6 No MCP servers configured");return}let b=c.getInstance();for(let[V,W]of Object.entries($)){if(W.disabled){H.debug(`⏭️ MCP server "${V}" is disabled, skipping`);continue}try{H.debug(`\uD83D\uDD0C Connecting to MCP server: ${V}`),await b.registerServer(V,W),H.debug(`✅ MCP server "${V}" connected`)}catch(Q){H.warn(`⚠️ MCP server "${V}" connection failed:`,Q)}}let w=await b.getAvailableTools();if(w.length>0)this.executionPipeline.getRegistry().registerAll(w),H.debug(`✅ Registered ${w.length} MCP tools`),H.debug(`[MCP Tools] ${w.map((V)=>V.name).join(", ")}`)}catch($){H.warn("Failed to register MCP tools:",$)}}async loadSubagents(){if(J$.getAllNames().length>0){H.debug(`\uD83D\uDCE6 Subagents already loaded: ${J$.getAllNames().join(", ")}`);return}try{let $=J$.loadFromStandardLocations();if($>0)H.debug(`✅ Loaded ${$} subagents: ${J$.getAllNames().join(", ")}`);else H.debug("\uD83D\uDCE6 No subagents configured")}catch($){H.warn("Failed to load subagents:",$)}}async discoverSkills(){try{let $=await Lb({cwd:process.cwd()});if($.skills.length>0)H.debug(`✅ Discovered ${$.skills.length} skills: ${$.skills.map((b)=>b.name).join(", ")}`);else H.debug("\uD83D\uDCE6 No skills configured");for(let b of $.errors)H.warn(`⚠️ Skill loading error at ${b.path}: ${b.error}`)}catch($){H.warn("Failed to discover skills:",$)}}applySkillToolRestrictions($){if(!this.activeSkillContext?.allowedTools)return $;let b=this.activeSkillContext.allowedTools;H.debug(`\uD83D\uDD12 Applying Skill tool restrictions: ${b.join(", ")}`);let w=$.filter((V)=>{return b.some((W)=>{if(W===V.name)return!0;let Q=W.match(/^(\w+)\(.*\)$/);if(Q&&Q[1]===V.name)return!0;return!1})});return H.debug(`\uD83D\uDD12 Filtered tools: ${w.map((V)=>V.name).join(", ")} (${w.length}/${$.length})`),w}clearSkillContext(){if(this.activeSkillContext)H.debug(`\uD83C\uDFAF Skill "${this.activeSkillContext.skillName}" deactivated`),this.activeSkillContext=void 0}}import{execSync as tV}from"node:child_process";import p2 from"node:fs";import d2 from"node:path";class Zb{async execute($,b){let w=$.content;if(b.signal?.aborted)throw Error("Command execution aborted");return w=this.interpolateArgs(w,b.args),w=await this.executeBashEmbeds(w,b),w=await this.resolveFileReferences(w,b.workspaceRoot),w}interpolateArgs($,b){$=$.replace(/\$ARGUMENTS/g,b.join(" "));for(let w=9;w>=1;w--){let V=`$${w}`,W=b[w-1]??"";$=$.split(V).join(W)}return $}async executeBashEmbeds($,b){let w=/!`([^`]+)`/g,V=[];for(let Q of $.matchAll(w))V.push({match:Q[0],command:Q[1]});let W=$;for(let{match:Q,command:Z}of V){if(b.signal?.aborted){W=W.replace(Q,"[Execution aborted]");continue}try{let Y=tV(Z,{cwd:b.workspaceRoot,encoding:"utf-8",timeout:30000,maxBuffer:1048576,stdio:["pipe","pipe","pipe"]}).trim();W=W.replace(Q,Y)}catch(Y){let J=Y instanceof Error?Y.message:String(Y);W=W.replace(Q,`[Error executing '${Z}': ${J}]`)}}return W}async resolveFileReferences($,b){let w=/@([\w./-]+(?:\/[\w./-]+|\.[\w]+))/g,V=[];for(let Q of $.matchAll(w))V.push({match:Q[0],relativePath:Q[1]});let W=$;for(let{match:Q,relativePath:Z}of V){let Y=d2.resolve(b,Z);try{if(p2.statSync(Y).isFile()){let X=p2.readFileSync(Y,"utf-8"),G=`\`\`\`${d2.extname(Z).slice(1)||"text"}
|
|
1878
|
+
${X}
|
|
1879
|
+
\`\`\``;W=W.replace(Q,G)}}catch{}}return W}hasDynamicContent($){return{hasArgs:/\$ARGUMENTS|\$\d/.test($),hasBashEmbeds:/!`[^`]+`/.test($),hasFileRefs:/@[\w./-]+(?:\/[\w./-]+|\.[\w]+)/.test($)}}}import fw from"node:fs";import g2 from"node:os";import i$ from"node:path";import eV from"node:fs";import u2 from"node:path";import $W from"gray-matter";class Yb{parse($,b,w,V){try{let W=eV.readFileSync($,"utf-8"),{data:Q,content:Z}=$W(W),{name:Y,namespace:J}=this.extractNameAndNamespace($,b);if(!Y)return null;return{name:Y,namespace:J,config:this.normalizeConfig(Q),content:Z.trim(),path:$,source:w,sourceDir:V}}catch{return 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((b)=>String(b).trim()).filter(Boolean);if(typeof $==="string")return $.split(",").map((b)=>b.trim()).filter(Boolean);return}extractNameAndNamespace($,b){let V=u2.relative(b,$).split(u2.sep),W=V.pop();if(!W)return{name:""};let Q=W.replace(/\.md$/i,""),Z=V.length>0?V.join("/"):void 0;return{name:Q,namespace:Z}}validateConfig($){let b=[];if($.model&&!this.isValidModelId($.model))b.push(`Invalid model ID: ${$.model}`);return b}isValidModelId($){return $.length>0&&$.length<200}}class Jb{parser=new Yb;async discover($){let b=[],w=[],V=[],W=this.getSearchDirs($);for(let Q of W){if(!fw.existsSync(Q.path))continue;w.push(Q.path);try{let Z=await this.scanDirectory(Q.path);for(let Y of Z)try{let J=this.parser.parse(Y,Q.path,Q.source,Q.sourceDir);if(J)b.push(J)}catch(J){V.push({path:Y,error:J instanceof Error?J.message:String(J)})}}catch(Z){V.push({path:Q.path,error:Z instanceof Error?Z.message:String(Z)})}}return{commands:b,scannedDirs:w,errors:V}}getSearchDirs($){let b=g2.homedir();return[{path:i$.join(b,".blade","commands"),source:"user",sourceDir:"blade"},{path:i$.join(b,".claude","commands"),source:"user",sourceDir:"claude"},{path:i$.join($,".blade","commands"),source:"project",sourceDir:"blade"},{path:i$.join($,".claude","commands"),source:"project",sourceDir:"claude"}]}async scanDirectory($){let b=[],w=async(V)=>{let W=await fw.promises.readdir(V,{withFileTypes:!0});for(let Q of W){let Z=i$.join(V,Q.name);if(Q.isDirectory())await w(Z);else if(Q.isFile()&&Q.name.endsWith(".md"))b.push(Z)}};return await w($),b}async hasCommands($){let b=this.getSearchDirs($);for(let w of b){if(!fw.existsSync(w.path))continue;if((await this.scanDirectory(w.path)).length>0)return!0}return!1}getCommandDirs($){let b=g2.homedir();return{projectBlade:i$.join($,".blade","commands"),projectClaude:i$.join($,".claude","commands"),userBlade:i$.join(b,".blade","commands"),userClaude:i$.join(b,".claude","commands")}}}class y${static instance;commands=new Map;loader=new Jb;executor=new Zb;initialized=!1;workspaceRoot="";lastDiscoveryResult=null;static getInstance(){if(!y$.instance)y$.instance=new y$;return y$.instance}static resetInstance(){y$.instance=new y$}constructor(){}async initialize($){this.workspaceRoot=$;let b=await this.loader.discover($);this.lastDiscoveryResult=b,this.commands.clear();for(let w of b.commands)this.commands.set(w.name,w);return this.initialized=!0,b}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($,b){let w=this.getCommand($);if(!w)return null;return this.executor.execute(w,b)}getCommandLabel($){let b=$.source==="project"?"project":"user";if($.namespace)return`(${b}:${$.namespace})`;return`(${b})`}getCommandDisplayName($){let b=[`/${$.name}`];if($.config.argumentHint)b.push($.config.argumentHint);if($.config.description)b.push("-",$.config.description);return b.push(this.getCommandLabel($)),b.join(" ")}getCommandsBySource(){let $=[],b=[];for(let w of this.commands.values())if(w.source==="project")$.push(w);else b.push(w);return{project:$,user:b}}getLastDiscoveryResult(){return this.lastDiscoveryResult}getCommandDirs(){if(!this.workspaceRoot)return null;return this.loader.getCommandDirs(this.workspaceRoot)}generateCommandListDescription($=15000){let b=this.getModelInvocableCommands(),w=b.length;if(w===0)return{text:"No custom commands available.",includedCount:0,totalCount:0};let V=`Available custom commands:
|
|
1880
|
+
|
|
1881
|
+
`,W=V.length,Q=0;for(let Z of b){let Y=this.getCommandLabel(Z),J=Z.config.argumentHint?` ${Z.config.argumentHint}`:"",X=`- /${Z.name}${J}: ${Z.config.description} ${Y}
|
|
1882
|
+
`;if(W+X.length>$)break;V+=X,W+=X.length,Q++}if(Q<w)V+=`
|
|
1883
|
+
(${Q} of ${w} commands shown due to character budget)`;return{text:V,includedCount:Q,totalCount:w}}}import{execSync as n2}from"node:child_process";import*as Q$ from"node:fs/promises";import{homedir as ZW}from"node:os";import*as v0 from"node:path";import*as rb from"node:fs/promises";import*as l2 from"node:path";import{z as S}from"zod";var bW=S.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"}),wW=S.string().regex(/^\d+\.\d+\.\d+(-[\w.]+)?(\+[\w.]+)?$/,{message:"Version must be a valid semantic version (e.g., 1.0.0)"}),VW=S.object({name:S.string().min(1,"Author name is required"),email:S.string().email().optional(),url:S.string().url().optional()}),c2=S.object({name:bW,description:S.string().min(1,"Description is required").max(500,"Description must be at most 500 characters"),version:wW,author:VW.optional(),license:S.string().optional(),repository:S.string().url().optional(),homepage:S.string().url().optional(),keywords:S.array(S.string()).optional(),dependencies:S.record(S.string()).optional(),bladeVersion:S.string().optional()}),m2=S.object({type:S.enum(["stdio","sse","http"]),command:S.string().optional(),args:S.array(S.string()).optional(),env:S.record(S.string()).optional(),url:S.string().url().optional(),headers:S.record(S.string()).optional(),timeout:S.number().positive().optional(),oauth:S.object({enabled:S.boolean().optional(),clientId:S.string().optional(),clientSecret:S.string().optional(),authorizationUrl:S.string().url().optional(),tokenUrl:S.string().url().optional(),scopes:S.array(S.string()).optional(),redirectUri:S.string().url().optional()}).optional(),healthCheck:S.object({enabled:S.boolean().optional(),interval:S.number().positive().optional(),timeout:S.number().positive().optional(),failureThreshold:S.number().positive().optional()}).optional()}),WW=S.union([S.object({mcpServers:S.record(m2)}),S.record(m2)]);function i2($){return WW.safeParse($)}var QW=[{dir:".blade-plugin",source:"blade"},{dir:".claude-plugin",source:"claude"}];async function $0($){for(let{dir:b,source:w}of QW){let V=l2.join($,b,"plugin.json");try{await rb.access(V)}catch{continue}try{let W=await rb.readFile(V,"utf-8"),Q=JSON.parse(W),Z=c2.safeParse(Q);if(!Z.success){let Y=Z.error.issues.map((J)=>`${J.path.join(".")}: ${J.message}`).join("; ");throw Error(`Invalid plugin.json: ${Y}`)}return u.debug(`Parsed plugin manifest from ${V}`),{manifest:Z.data,source:w,manifestPath:V}}catch(W){if(W instanceof SyntaxError)throw Error(`Invalid JSON in ${V}: ${W.message}`);throw W}}return null}async function ab($){try{return await $0($)!==null}catch{return!1}}class ob{userPluginsDir;constructor($){this.userPluginsDir=$||v0.join(ZW(),".blade","plugins")}async install($){try{let b=this.parseGitUrl($);if(!b)return{success:!1,error:`Invalid source URL: ${$}`};let w=this.extractPluginName(b);if(!w)return{success:!1,error:`Could not extract plugin name from URL: ${b}`};await Q$.mkdir(this.userPluginsDir,{recursive:!0,mode:493});let V=v0.join(this.userPluginsDir,w);try{return await Q$.access(V),{success:!1,pluginName:w,pluginPath:V,error:`Plugin "${w}" already exists at ${V}. Use /plugins uninstall first.`}}catch{}u.info(`Cloning ${b} to ${V}...`);try{n2(`git clone --depth 1 "${b}" "${V}"`,{stdio:"pipe",timeout:60000})}catch(Q){return{success:!1,pluginName:w,error:`Failed to clone repository: ${Q instanceof Error?Q.message:String(Q)}`}}if(!await ab(V))return await Q$.rm(V,{recursive:!0,force:!0}),{success:!1,pluginName:w,error:"Invalid plugin: No .blade-plugin/plugin.json or .claude-plugin/plugin.json found"};let W;try{W=await $0(V)}catch(Q){return await Q$.rm(V,{recursive:!0,force:!0}),{success:!1,pluginName:w,error:`Invalid plugin manifest: ${Q instanceof Error?Q.message:String(Q)}`}}if(!W)return await Q$.rm(V,{recursive:!0,force:!0}),{success:!1,pluginName:w,error:"Invalid plugin manifest: No manifest found"};return u.info(`Successfully installed plugin: ${W.manifest.name}`),{success:!0,pluginName:W.manifest.name,pluginPath:V,manifest:W.manifest}}catch(b){return{success:!1,error:`Installation failed: ${b instanceof Error?b.message:String(b)}`}}}async uninstall($){try{let b=v0.join(this.userPluginsDir,$);try{await Q$.access(b)}catch{return{success:!1,pluginName:$,error:`Plugin "${$}" not found at ${b}`}}return await Q$.rm(b,{recursive:!0,force:!0}),u.info(`Successfully uninstalled plugin: ${$}`),{success:!0,pluginName:$,pluginPath:b}}catch(b){return{success:!1,pluginName:$,error:`Uninstallation failed: ${b instanceof Error?b.message:String(b)}`}}}async listInstalled(){try{return await Q$.access(this.userPluginsDir),(await Q$.readdir(this.userPluginsDir,{withFileTypes:!0})).filter((b)=>b.isDirectory()).map((b)=>b.name)}catch{return[]}}async update($){try{let b=v0.join(this.userPluginsDir,$);try{await Q$.access(b)}catch{return{success:!1,pluginName:$,error:`Plugin "${$}" not found at ${b}`}}let w=v0.join(b,".git");try{await Q$.access(w)}catch{return{success:!1,pluginName:$,error:`Plugin "${$}" is not a git repository`}}u.info(`Updating plugin: ${$}...`);try{n2(`git -C "${b}" pull --ff-only`,{stdio:"pipe",timeout:60000})}catch(W){return{success:!1,pluginName:$,error:`Failed to update: ${W instanceof Error?W.message:String(W)}`}}let V;try{V=await $0(b)}catch(W){return{success:!1,pluginName:$,error:`Plugin manifest invalid after update: ${W instanceof Error?W.message:String(W)}`}}if(!V)return{success:!1,pluginName:$,error:"Plugin manifest not found after update"};return u.info(`Successfully updated plugin: ${V.manifest.name}`),{success:!0,pluginName:V.manifest.name,pluginPath:b,manifest:V.manifest}}catch(b){return{success:!1,pluginName:$,error:`Update failed: ${b instanceof Error?b.message:String(b)}`}}}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 b=$.match(/\/([a-zA-Z0-9_.-]+?)(?:\.git)?$/);if(b)return b[1];let w=$.match(/:([a-zA-Z0-9_-]+\/)?([a-zA-Z0-9_.-]+?)(?:\.git)?$/);if(w)return w[2];return null}}var Iw=null;function s2($){if(!Iw)Iw=new ob($);return Iw}import*as U$ from"node:fs/promises";import{homedir as YW}from"node:os";import*as s from"node:path";import r2 from"gray-matter";function T0($,b){return`${$}:${b}`}function tb($,b){return`${$}__${b}`}class k0{async loadPlugin($,b,w={}){let V=await $0($);if(!V)throw Error(`Not a valid plugin directory: ${$}`);let{manifest:W,source:Q}=V,Z=W.name;u.debug(`Loading plugin "${Z}" from ${$}`);let Y=w.skipCommands?[]:await this.loadCommands($,Z),J=w.skipAgents?[]:await this.loadAgents($,Z),X=w.skipSkills?[]:await this.loadSkills($,Z),O=w.skipHooks?void 0:await this.loadHooks($),G=w.skipMcp?void 0:await this.loadMcpConfig($,Z);return u.debug(`Plugin "${Z}" loaded: ${Y.length} commands, ${J.length} agents, ${X.length} skills`),{manifest:W,basePath:$,source:b,manifestSource:Q,commands:Y,agents:J,skills:X,hooks:O,mcpServers:G,status:"active",loadedAt:new Date}}async loadCommands($,b){let w=s.join($,"commands"),V=[];if(!await this.dirExists(w))return V;let W=await this.scanMarkdownFiles(w);for(let Q of W)try{let Z=await this.parseCommandFile(Q,w,b);if(Z)V.push(Z)}catch(Z){u.warn(`Failed to load command from ${Q}: ${Z instanceof Error?Z.message:String(Z)}`)}return V}async parseCommandFile($,b,w){let V=await U$.readFile($,"utf-8"),{data:W,content:Q}=r2(V),Y=s.relative(b,$).split(s.sep),J=Y.pop();if(!J)return null;let X=J.replace(/\.md$/i,""),O=X;if(Y.length>0)O=[...Y,X].join("/");let G=T0(w,O),B=this.normalizeCommandConfig(W);return{originalName:O,namespacedName:G,pluginName:w,config:B,content:Q.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($,b){let w=s.join($,"agents"),V=[];if(!await this.dirExists(w))return V;let W=await this.scanMarkdownFiles(w);for(let Q of W)try{let Z=await this.parseAgentFile(Q,w,b);if(Z)V.push(Z)}catch(Z){u.warn(`Failed to load agent from ${Q}: ${Z instanceof Error?Z.message:String(Z)}`)}return V}async parseAgentFile($,b,w){let V=await U$.readFile($,"utf-8"),{data:W,content:Q}=r2(V),Z=s.relative(b,$),Y=s.basename(Z,".md"),J=W.name||Y,X=T0(w,J),O={name:X,description:this.asString(W.description)||"",tools:this.parseStringArray(W.tools),color:this.asString(W.color),model:this.asString(W.model),permissionMode:this.asString(W.permissionMode),skills:this.parseStringArray(W.skills),systemPrompt:Q.trim(),source:`plugin:${w}`};return{originalName:J,namespacedName:X,pluginName:w,config:O,path:$}}async loadSkills($,b){let w=s.join($,"skills"),V=[];if(!await this.dirExists(w))return V;let W=await U$.readdir(w,{withFileTypes:!0});for(let Q of W){if(!Q.isDirectory())continue;let Z=s.join(w,Q.name),Y=s.join(Z,"SKILL.md");try{let J=await _b(Y,"project");if(J.success&&J.content){let X=J.content.metadata.name,O=T0(b,X);V.push({originalName:X,namespacedName:O,pluginName:b,metadata:{...J.content.metadata,name:O},path:Z})}}catch(J){u.warn(`Failed to load skill from ${Y}: ${J instanceof Error?J.message:String(J)}`)}}return V}async loadHooks($){let b=s.join($,"hooks","hooks.json");try{let w=await U$.readFile(b,"utf-8"),V=JSON.parse(w);return V.hooks||V}catch{return}}async loadMcpConfig($,b){let w=s.join($,".mcp.json");try{let V=await U$.readFile(w,"utf-8"),W=JSON.parse(V),Q=i2(W);if(!Q.success){u.warn(`Invalid .mcp.json in ${$}: ${Q.error}`);return}let Z="mcpServers"in W?W.mcpServers:W,Y={};for(let[J,X]of Object.entries(Z)){let O=tb(b,J);Y[O]=X}return Y}catch{return}}async scanMarkdownFiles($){let b=[],w=async(V)=>{let W=await U$.readdir(V,{withFileTypes:!0});for(let Q of W){let Z=s.join(V,Q.name);if(Q.isDirectory())await w(Z);else if(Q.name.endsWith(".md"))b.push(Z)}};return await w($),b}async dirExists($){try{return(await U$.stat($)).isDirectory()}catch{return!1}}asString($){if(typeof $==="string"&&$.trim())return $.trim();return}parseStringArray($){if(!$)return;if(Array.isArray($))return $.map((b)=>String(b).trim()).filter(Boolean);if(typeof $==="string")return $.split(",").map((b)=>b.trim()).filter(Boolean);return}static getPluginDirs($){let b=YW();return[{path:s.join(b,".claude","plugins"),source:"user",type:"claude"},{path:s.join(b,".blade","plugins"),source:"user",type:"blade"},{path:s.join($,".claude","plugins"),source:"project",type:"claude"},{path:s.join($,".blade","plugins"),source:"project",type:"blade"}]}async discoverPluginsInDir($,b){let w=[],V=[];try{await U$.access($)}catch{return{plugins:w,errors:V}}let W=await U$.readdir($,{withFileTypes:!0});for(let Q of W){if(!Q.isDirectory())continue;let Z=s.join($,Q.name);try{let Y=await this.loadPlugin(Z,b);w.push(Y)}catch(Y){V.push({path:Z,error:Y instanceof Error?Y.message:String(Y)})}}return{plugins:w,errors:V}}}class l${static instance=null;plugins=new Map;loader=new k0;initialized=!1;workspaceRoot="";cliPluginDirs=[];constructor(){}static getInstance(){if(!l$.instance)l$.instance=new l$;return l$.instance}static resetInstance(){l$.instance=null}async initialize($,b=[]){this.workspaceRoot=$,this.cliPluginDirs=b;let w=[],V=[];for(let Q of b)try{let Z=await this.loader.loadPlugin(Q,"cli");this.plugins.set(Z.manifest.name,Z),w.push(Z),u.info(`Loaded CLI plugin: ${Z.manifest.name} from ${Q}`)}catch(Z){V.push({path:Q,error:Z instanceof Error?Z.message:String(Z)}),u.warn(`Failed to load CLI plugin from ${Q}: ${Z}`)}let W=k0.getPluginDirs($);for(let{path:Q,source:Z}of W){let Y=await this.loader.discoverPluginsInDir(Q,Z);for(let J of Y.plugins){let X=this.plugins.get(J.manifest.name);if(!X||X.source!=="cli")this.plugins.set(J.manifest.name,J),w.push(J)}V.push(...Y.errors)}return this.initialized=!0,u.info(`Plugin system initialized: ${this.plugins.size} plugins loaded`+(V.length>0?`, ${V.length} errors`:"")),{plugins:Array.from(this.plugins.values()),errors:V}}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 b of this.plugins.values())$[b.source].push(b);return $}getAllCommands(){let $=[];for(let b of this.plugins.values())if(b.status==="active")$.push(...b.commands);return $}getAllSkills(){let $=[];for(let b of this.plugins.values())if(b.status==="active")$.push(...b.skills);return $}getAllAgents(){let $=[];for(let b of this.plugins.values())if(b.status==="active")$.push(...b.agents);return $}findCommand($){for(let w of this.plugins.values()){if(w.status!=="active")continue;for(let V of w.commands)if(V.namespacedName===$)return V}let b=[];for(let w of this.plugins.values()){if(w.status!=="active")continue;for(let V of w.commands)if(V.originalName===$)b.push(V)}if(b.length===1)return b[0];return}findSkill($){for(let w of this.plugins.values()){if(w.status!=="active")continue;for(let V of w.skills)if(V.namespacedName===$)return V}let b=[];for(let w of this.plugins.values()){if(w.status!=="active")continue;for(let V of w.skills)if(V.originalName===$)b.push(V)}if(b.length===1)return b[0];return}findAgent($){for(let w of this.plugins.values()){if(w.status!=="active")continue;for(let V of w.agents)if(V.namespacedName===$)return V}let b=[];for(let w of this.plugins.values()){if(w.status!=="active")continue;for(let V of w.agents)if(V.originalName===$)b.push(V)}if(b.length===1)return b[0];return}hasCommandConflict($){let b=0;for(let w of this.plugins.values()){if(w.status!=="active")continue;for(let V of w.commands)if(V.originalName===$){if(b++,b>1)return!0}}return!1}getCommandProviders($){let b=[];for(let w of this.plugins.values()){if(w.status!=="active")continue;for(let V of w.commands)if(V.originalName===$){b.push(w.manifest.name);break}}return b}disable($){let b=this.plugins.get($);if(b&&b.status==="active")return b.status="inactive",u.info(`Plugin "${$}" disabled`),!0;return!1}enable($){let b=this.plugins.get($);if(b&&b.status==="inactive")return b.status="active",u.info(`Plugin "${$}" enabled`),!0;return!1}async refresh(){return u.info("Refreshing plugin list..."),this.plugins.clear(),this.initialized=!1,this.initialize(this.workspaceRoot,this.cliPluginDirs)}getStats(){let $=0,b=0,w=0,V=0,W=0;for(let Q of this.plugins.values())if(Q.status==="active")$++,w+=Q.commands.length,V+=Q.skills.length,W+=Q.agents.length;else b++;return{total:this.plugins.size,active:$,inactive:b,commands:w,skills:V,agents:W}}formatPluginList(){if(this.getAll().length===0)return"没有已加载的插件。";let b=[],w=this.getBySource();if(w.cli.length>0){b.push("## CLI 指定的插件");for(let V of w.cli){let W=V.status==="inactive"?" (禁用)":"";b.push(`- **${V.manifest.name}** v${V.manifest.version}${W}`),b.push(` ${V.manifest.description}`)}b.push("")}if(w.project.length>0){b.push("## 项目级插件");for(let V of w.project){let W=V.status==="inactive"?" (禁用)":"";b.push(`- **${V.manifest.name}** v${V.manifest.version}${W}`),b.push(` ${V.manifest.description}`)}b.push("")}if(w.user.length>0){b.push("## 用户级插件");for(let V of w.user){let W=V.status==="inactive"?" (禁用)":"";b.push(`- **${V.manifest.name}** v${V.manifest.version}${W}`),b.push(` ${V.manifest.description}`)}}return b.join(`
|
|
1884
|
+
`)}}function eb(){return l$.getInstance()}class Xb{hookManager;mcpRegistry;constructor(){this.hookManager=r.getInstance(),this.mcpRegistry=c.getInstance()}clearAllPluginResources(){N$().clearPluginSkills(),J$.clearPluginAgents(),u.debug("Cleared all plugin resources from subsystems")}async integrateAll(){let b=eb().getActive(),w=[],V=[],W=0,Q=0,Z=0,Y=0;for(let J of b){let X=await this.integratePlugin(J);w.push(X),W+=X.commandsRegistered,Q+=X.skillsRegistered,Z+=X.agentsRegistered,Y+=X.mcpServersRegistered,V.push(...X.errors)}if(W+Q+Z>0)u.info(`Plugin integration complete: ${W} commands, ${Q} skills, ${Z} agents, ${Y} MCP servers`);return{plugins:w,totalCommands:W,totalSkills:Q,totalAgents:Z,totalMcpServers:Y,errors:V}}async integratePlugin($){let b={pluginName:$.manifest.name,commandsRegistered:0,skillsRegistered:0,agentsRegistered:0,hooksRegistered:!1,mcpServersRegistered:0,errors:[]};try{b.commandsRegistered=this.integrateCommands($)}catch(w){b.errors.push(`Failed to integrate commands: ${w instanceof Error?w.message:String(w)}`)}try{b.skillsRegistered=this.integrateSkills($)}catch(w){b.errors.push(`Failed to integrate skills: ${w instanceof Error?w.message:String(w)}`)}try{b.agentsRegistered=this.integrateAgents($)}catch(w){b.errors.push(`Failed to integrate agents: ${w instanceof Error?w.message:String(w)}`)}try{b.hooksRegistered=this.integrateHooks($)}catch(w){b.errors.push(`Failed to integrate hooks: ${w instanceof Error?w.message:String(w)}`)}try{b.mcpServersRegistered=await this.integrateMcp($)}catch(w){b.errors.push(`Failed to integrate MCP servers: ${w instanceof Error?w.message:String(w)}`)}return u.debug(`Integrated plugin "${$.manifest.name}": ${b.commandsRegistered} commands, ${b.skillsRegistered} skills, ${b.agentsRegistered} agents`),b}integrateCommands($){return $.commands.length}integrateSkills($){let b=N$(),w=0;for(let V of $.skills)b.registerPluginSkill(V),w++;return w}integrateAgents($){let b=0;for(let w of $.agents)J$.register({...w.config,name:w.namespacedName}),b++;return b}integrateHooks($){if(!$.hooks)return!1;let b=this.hookManager.getConfig();return this.hookManager.loadConfig({...b,...$.hooks}),!0}async integrateMcp($){if(!$.mcpServers)return 0;let b=0;for(let[w,V]of Object.entries($.mcpServers))try{await this.mcpRegistry.registerServer(w,V),b++}catch(W){u.warn(`Failed to register MCP server "${w}" from plugin "${$.manifest.name}": ${W instanceof Error?W.message:String(W)}`)}return b}}async function a2(){return new Xb().integrateAll()}function o2(){new Xb().clearAllPluginResources()}import{nanoid as JW}from"nanoid";var G$=z("Agent");class f0{sessionId;agent=null;abortController=null;_messages=[];options;maxTurns;permissionMode;initialized=!1;pendingMessage=null;pendingSendOptions=null;constructor($,b){this.sessionId=b||JW(),this.options=$,this.maxTurns=$.maxTurns??200,this.permissionMode=$.permissionMode??v.DEFAULT}get messages(){return[...this._messages]}async initialize(){if(this.initialized)return;let $=this.buildBladeConfig();if(this.options.sandbox)j0().configure(this.options.sandbox);if(this.options.enableFileCheckpointing)k$().configure({enabled:!0});this.agent=await g$.create($,{permissionMode:this.permissionMode,systemPrompt:this.options.systemPrompt,maxTurns:this.maxTurns,canUseTool:this.options.canUseTool,outputFormat:this.options.outputFormat,sandbox:this.options.sandbox}),this.initialized=!0,G$.debug(`[Session] Initialized session ${this.sessionId}`)}async loadHistory(){let $=this.options.cwd||process.cwd(),b=C$($,this.sessionId),w=new O$(b);try{let V=await w.readAll();if(V.length===0){G$.debug(`[Session] No history found for session ${this.sessionId}`);return}let W=new Map,Q=new Map;for(let Z of V){if(Z.type==="message_created"){let Y=Z.data;W.set(Y.messageId,{role:Y.role,content:"",toolCalls:[]})}if(Z.type==="part_created"){let Y=Z.data,J=W.get(Y.messageId);if(!J)J={role:Y.partType==="tool_result"?"tool":"assistant",content:"",toolCalls:[]},W.set(Y.messageId,J);switch(Y.partType){case"text":{let X=Y.payload;J.content=X.text??"";break}case"tool_call":{let X=Y.payload,O={id:X.toolCallId,type:"function",function:{name:X.toolName,arguments:typeof X.input==="string"?X.input:JSON.stringify(X.input)}};J.toolCalls.push(O),Q.set(X.toolCallId,{messageId:Y.messageId,toolCallId:X.toolCallId});break}case"tool_result":{let X=Y.payload;if(J.role="tool",J.toolCallId=X.toolCallId,J.name=X.toolName,X.error)J.content=`Error: ${X.error}`;else if(X.output===null||X.output===void 0)J.content="";else if(typeof X.output==="string")J.content=X.output;else J.content=JSON.stringify(X.output);break}case"summary":{let X=Y.payload;J.content=X.text??"";break}}}}this._messages=Array.from(W.values()).map((Z)=>{let Y={role:Z.role,content:Z.content};if(Z.toolCalls.length>0)Y.tool_calls=Z.toolCalls;if(Z.toolCallId)Y.tool_call_id=Z.toolCallId;if(Z.name)Y.name=Z.name;return Y}),G$.debug(`[Session] Loaded ${this._messages.length} messages from history`)}catch(V){G$.warn(`[Session] Failed to load history for session ${this.sessionId}:`,V)}}buildBladeConfig(){let $=this.buildModelConfig();return{models:[$],currentModelId:$.id,temperature:0.7,mcpServers:this.options.mcpServers,permissions:{allow:[],deny:[]}}}buildModelConfig(){let $=this.options.provider;return{id:"default",name:this.options.model,provider:this.mapProviderType($.type),model:this.options.model,apiKey:$.apiKey||"",baseUrl:$.baseUrl||this.getDefaultBaseUrl($.type),maxTokens:128000}}mapProviderType($){return{"openai-compatible":"openai-compatible",anthropic:"anthropic",gemini:"gemini","azure-openai":"azure-openai"}[$]||"openai-compatible"}getDefaultBaseUrl($){return{"openai-compatible":"https://api.openai.com/v1",anthropic:"https://api.anthropic.com",gemini:"https://generativelanguage.googleapis.com","azure-openai":""}[$]||""}async send($,b){if(await this.ensureInitialized(),this.pendingMessage!==null)throw Error("Cannot send a new message while a previous message is pending. Call stream() first.");this.pendingMessage=$,this.pendingSendOptions=b||null}async*stream($){if(this.pendingMessage===null)throw Error("No pending message. Call send() before stream().");let b=this.pendingMessage,w=this.pendingSendOptions;this.pendingMessage=null,this.pendingSendOptions=null;let V=[],W={inputTokens:0,outputTokens:0,totalTokens:0,maxContextTokens:0};this.abortController=new AbortController;let Q=w?.signal?this.combineSignals(w.signal,this.abortController.signal):this.abortController.signal,Z={messages:this._messages,userId:"sdk-user",sessionId:this.sessionId,workspaceRoot:this.options.cwd||process.cwd(),signal:Q,permissionMode:this.permissionMode},Y=this.agent.streamChat(b,Z,{maxTurns:w?.maxTurns??this.maxTurns,signal:Q});try{let J;while(!0){let{value:G,done:B}=await Y.next();if(B){J=G;break}switch(G.type){case"turn_start":yield{type:"turn_start",turn:G.turn,sessionId:this.sessionId};break;case"content_delta":yield{type:"content",delta:G.delta,sessionId:this.sessionId};break;case"thinking_delta":if($?.includeThinking)yield{type:"thinking",delta:G.delta,sessionId:this.sessionId};break;case"content":yield{type:"content",delta:G.content,sessionId:this.sessionId};break;case"thinking":if($?.includeThinking)yield{type:"thinking",delta:G.content,sessionId:this.sessionId};break;case"tool_start":{if(G.toolCall.type!=="function")break;let q=this.safeParseJson(G.toolCall.function.arguments);V.push({id:G.toolCall.id,name:G.toolCall.function.name,input:q,output:null,duration:0}),yield{type:"tool_use",id:G.toolCall.id,name:G.toolCall.function.name,input:q,sessionId:this.sessionId};break}case"tool_result":{if(G.toolCall.type!=="function")break;let q=V.find((A)=>A.id===G.toolCall.id);if(q)q.output=G.result.llmContent,q.isError=!G.result.success;yield{type:"tool_result",id:G.toolCall.id,name:G.toolCall.function.name,output:G.result.llmContent,isError:!G.result.success,sessionId:this.sessionId};break}case"token_usage":W={inputTokens:G.usage.inputTokens,outputTokens:G.usage.outputTokens,totalTokens:G.usage.totalTokens,maxContextTokens:G.usage.maxContextTokens};break;default:break}}if(!J)throw Error("Stream ended without result");let X=J.error?.type==="aborted",O=J.metadata?.shouldExitLoop;if(!J.success&&!X&&!O){yield{type:"error",message:J.error?.message||"Unknown error",sessionId:this.sessionId};return}yield{type:"usage",usage:W,sessionId:this.sessionId},this._messages=Z.messages,yield{type:"result",subtype:"success",content:J.finalMessage||"",sessionId:this.sessionId}}catch(J){yield{type:"error",message:J instanceof Error?J.message:String(J),sessionId:this.sessionId}}finally{this.abortController=null}}close(){this.abort(),this.agent=null,this.initialized=!1,this.pendingMessage=null,this.pendingSendOptions=null,G$.debug(`[Session] Closed session ${this.sessionId}`)}abort(){if(this.abortController)this.abortController.abort(),this.abortController=null}setPermissionMode($){this.permissionMode=$}async setModel($){G$.warn("[Session] setModel is not yet implemented")}setMaxTurns($){this.maxTurns=$}async supportedCommands(){let $=y$.getInstance();if(!$.isInitialized())await $.initialize(this.options.cwd||process.cwd());return $.getAllCommands().map((b)=>({name:b.name,description:b.config.description||"",usage:b.config.argumentHint}))}async supportedModels(){return[{id:"default",name:this.options.model,provider:this.options.provider.type}]}async mcpServerStatus(){let b=c.getInstance().getAllServers(),w=[];for(let[V,W]of b){let Q={connected:"connected",disconnected:"disconnected",connecting:"connecting",error:"error"};w.push({name:V,status:Q[W.status],toolCount:W.tools.length,tools:W.tools.map((Z)=>Z.name),connectedAt:W.connectedAt,error:W.lastError?.message})}return w}async mcpConnect($){await this.ensureInitialized();let b=c.getInstance();if(!b.getServerStatus($)){let V=this.options.mcpServers?.[$];if(!V)throw Error(`MCP server "${$}" not found in configuration`);await b.registerServer($,V)}else await b.connectServer($);G$.debug(`[Session] Connected to MCP server: ${$}`)}async mcpDisconnect($){await c.getInstance().disconnectServer($),G$.debug(`[Session] Disconnected from MCP server: ${$}`)}async mcpReconnect($){await c.getInstance().reconnectServer($),G$.debug(`[Session] Reconnected to MCP server: ${$}`)}async mcpListTools(){let b=c.getInstance().getAllServers(),w=[];for(let[V,W]of b)if(W.status==="connected")for(let Q of W.tools)w.push({name:Q.name,description:Q.description,serverName:V});return w}async[Symbol.asyncDispose](){this.close()}async ensureInitialized(){if(!this.initialized)await this.initialize()}combineSignals($,b){let w=new AbortController,V=()=>w.abort();if($.aborted||b.aborted)w.abort();else $.addEventListener("abort",V),b.addEventListener("abort",V);return w.signal}safeParseJson($){try{return JSON.parse($)}catch{return $}}async rewindFiles($){if(!this.options.enableFileCheckpointing)return{success:!1,restoredFiles:[],deletedFiles:[],errors:[{filePath:"",error:"File checkpointing is not enabled"}]};return k$().rewindFiles($)}getCheckpointStatistics(){if(!this.options.enableFileCheckpointing)return null;return k$().getStatistics()}async fork($){await this.ensureInitialized();let b=$?.messageId,w=[...this._messages];if(b){let W=this.findMessageIndexByUuid(b);if(W===-1)throw Error(`Message with ID "${b}" not found in session history`);w=this._messages.slice(0,W+1)}let V=new f0(this.options);if(await V.initialize(),V._messages=w.map((W)=>({...W})),$?.copyCheckpoints&&this.options.enableFileCheckpointing)G$.debug("[Session] Checkpoint copying is not yet implemented for forked sessions");return G$.debug(`[Session] Forked session ${this.sessionId} -> ${V.sessionId} with ${w.length} messages`),V}findMessageIndexByUuid($){for(let b=0;b<this._messages.length;b++)if(this._messages[b].uuid===$)return b;return this._messages.length>0?this._messages.length-1:-1}}async function t2($){let b=new f0($);return await b.initialize(),G$.debug(`[Session] Created new session: ${b.sessionId}`),b}async function e2($){let{sessionId:b,...w}=$,V=new f0(w,b);return await V.initialize(),await V.loadHistory(),G$.debug(`[Session] Resumed session: ${b} with ${V.messages.length} messages`),V}async function $8($){let{sessionId:b,messageId:w,copyCheckpoints:V,...W}=$,Q=new f0(W,b);await Q.initialize(),await Q.loadHistory();let Z=await Q.fork({messageId:w,copyCheckpoints:V});return Q.close(),G$.debug(`[Session] Forked session ${b} -> ${Z.sessionId} with ${Z.messages.length} messages`),Z}async function b8($,b){let w=Date.now(),V=new f0(b);await V.initialize();let W=[],Q={inputTokens:0,outputTokens:0,totalTokens:0,maxContextTokens:0},Z=0,Y="",J=null;try{await V.send($);for await(let X of V.stream())if(X.type==="turn_start")Z=X.turn;else if(X.type==="tool_use")W.push({id:X.id,name:X.name,input:X.input,output:null,duration:0});else if(X.type==="tool_result"){let O=W.find((G)=>G.id===X.id);if(O)O.output=X.output,O.isError=X.isError}else if(X.type==="usage")Q=X.usage;else if(X.type==="result"&&X.subtype==="success")Y=X.content||"";else if(X.type==="error")J=X.message;else if(X.type==="result"&&X.subtype==="error")J=X.error||"Unknown error";if(J)throw Error(J);return{result:Y,toolCalls:W,usage:Q,duration:Date.now()-w,turnsCount:Z}}finally{V.close()}}export{v5 as toolFromDefinition,iW as shutdownLogger,cW as setLoggerSessionId,e2 as resumeSession,db as readMcpResourceTool,b8 as prompt,$0 as parsePluginManifest,Mb as notebookEditTool,u as logger,pb as listMcpResourcesTool,ab as isValidPluginDir,F0 as isReadOnlyKind,N9 as isGlobMetadata,S9 as isEditMetadata,a2 as integrateAllPlugins,Db as injectSkillsMetadata,j0 as getSandboxService,D0 as getSandboxExecutor,eb as getPluginRegistry,s2 as getPluginInstaller,T0 as getNamespacedName,tb as getMcpNamespacedName,k$ as getCheckpointService,qw as getBuiltinTools,$8 as forkSession,Lb as discoverSkills,T5 as defineTool,E as createTool,t2 as createSession,z as createLogger,Kb as createChatServiceAsync,o2 as clearAllPluginResources,Pb as askUserQuestionTool,Qb as ToolRegistry,X8 as ToolKind,R1 as ToolExecution,C8 as ToolErrorType,J8 as StreamMessageType,i as SpecManager,u$ as SandboxService,d$ as SandboxExecutor,Y0 as STEERING_FILES,i4 as SPEC_FILE_NAMES,Z0 as SPEC_DIRS,l$ as PluginRegistry,k0 as PluginLoader,Xb as PluginIntegrator,ob as PluginInstaller,w1 as PermissionMode,B8 as PermissionDecision,O8 as PermissionBehavior,$b as PHASE_TRANSITIONS,l4 as PHASE_PRIMARY_FILE,mY as PHASE_ORDER,R$ as PHASE_DISPLAY_NAMES,xw as MessageRole,c as McpRegistry,z1 as McpErrorType,b0 as McpConnectionStatus,c0 as McpClient,x$ as Logger,U1 as LogLevel,a as LogCategory,K8 as HookType,r as HookManager,q8 as HookExitCode,P0 as HookEvent,M1 as HealthStatus,m0 as HealthMonitor,mb as ExecutionPipeline,G8 as DecisionBehavior,sb as ContextManager,b$ as CompactionService,y$ as CommandRegistry,Yb as CommandParser,Jb as CommandLoader,Zb as CommandExecutor,p$ as CheckpointService,g$ as Agent};
|