@blade-ai/agent-sdk 0.1.4 → 0.1.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +10 -0
- package/README.md +277 -27
- package/dist/index.js +138 -138
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
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(`
|
|
1
|
+
import{createRequire as W8}from"node:module";var P0=W8(import.meta.url);import{nanoid as nV}from"nanoid";import*as P2 from"os";import*as h2 from"path";import{nanoid as U0}from"nanoid";var b1={DEFAULT:"default",AUTO_EDIT:"autoEdit",YOLO:"yolo",BYPASSALL:"bypassAll",PLAN:"plan",SPEC:"spec"},h0;((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"})(h0||={});var hw={SYSTEM:"system",USER:"user",ASSISTANT:"assistant",TOOL:"tool"},Q8={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"},Z8={READONLY:"readonly",WRITE:"write",EXECUTE:"execute"},Y8={ALLOW:"allow",DENY:"deny",ASK:"ask"},J8={APPROVE:"approve",BLOCK:"block",ASYNC:"async"},X8={ALLOW:"allow",DENY:"deny",ASK:"ask"},O8={COMMAND:"command",PROMPT:"prompt"},G8={SUCCESS:0,NON_BLOCKING_ERROR:1,BLOCKING_ERROR:2,TIMEOUT:124},B8={VALIDATION_ERROR:"validation_error",PERMISSION_DENIED:"permission_denied",EXECUTION_ERROR:"execution_error",TIMEOUT_ERROR:"timeout_error",NETWORK_ERROR:"network_error"};var v=b1;import{nanoid as q$}from"nanoid";var w1={enabled:!1,defaultTimeout:60,timeoutBehavior:"ignore",failureBehavior:"ignore",maxConcurrentHooks:5,PreToolUse:[],PostToolUse:[],PostToolUseFailure:[],PermissionRequest:[],UserPromptSubmit:[],SessionStart:[],SessionEnd:[],Stop:[],SubagentStart:[],SubagentStop:[],TaskCompleted:[],Notification:[],Compaction:[]};function V1($,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 xw(){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 W1{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 Q1;((V)=>{V.Approve="approve";V.Block="block";V.Async="async"})(Q1||={});var Z1;((V)=>{V.Allow="allow";V.Deny="deny";V.Ask="ask"})(Z1||={});var K$=C.object({hook_event_name:C.nativeEnum(h0),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()}),q8=K$.extend({hook_event_name:C.literal("PreToolUse"),tool_name:C.string(),tool_use_id:C.string(),tool_input:C.record(C.unknown())}),C8=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()}),A8=K$.extend({hook_event_name:C.literal("Stop"),reason:C.string().optional()}),U8=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()}),F8=K$.extend({hook_event_name:C.literal("PermissionRequest"),tool_name:C.string(),tool_use_id:C.string(),tool_input:C.record(C.unknown())}),H8=K$.extend({hook_event_name:C.literal("UserPromptSubmit"),user_prompt:C.string(),has_images:C.boolean(),image_count:C.number()}),_8=K$.extend({hook_event_name:C.literal("SessionStart"),is_resume:C.boolean(),resume_session_id:C.string().optional()}),R8=K$.extend({hook_event_name:C.literal("SessionEnd"),reason:C.enum(["user_exit","error","max_turns","idle_timeout","ctrl_c","clear","logout","other"])}),E8=K$.extend({hook_event_name:C.literal("SubagentStart"),agent_type:C.string(),task_description:C.string().optional(),parent_agent_id:C.string().optional()}),L8=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()}),D8=K$.extend({hook_event_name:C.literal("TaskCompleted"),task_id:C.string(),task_description:C.string(),result_summary:C.string().optional(),success:C.boolean()}),j8=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()}),N8=K$.extend({hook_event_name:C.literal("Compaction"),trigger:C.enum(["manual","auto"]),messages_before:C.number(),tokens_before:C.number()}),_W=C.discriminatedUnion("hook_event_name",[q8,C8,A8,U8,F8,H8,_8,R8,E8,L8,D8,j8,N8]),S8=C.object({hookEventName:C.literal("PreToolUse"),permissionDecision:C.nativeEnum(Z1).optional(),permissionDecisionReason:C.string().optional(),updatedInput:C.record(C.unknown()).optional()}),M8=C.object({hookEventName:C.literal("PostToolUse"),additionalContext:C.string().optional(),updatedOutput:C.unknown().optional()}),y8=C.object({hookEventName:C.literal("Stop"),continue:C.boolean().optional(),continueReason:C.string().optional()}),z8=C.object({hookEventName:C.literal("SubagentStart"),additionalContext:C.string().optional()}),v8=C.object({hookEventName:C.literal("SubagentStop"),continue:C.boolean().optional(),continueReason:C.string().optional(),additionalContext:C.string().optional()}),T8=C.object({hookEventName:C.literal("TaskCompleted"),blockCompletion:C.boolean().optional(),blockReason:C.string().optional()}),k8=C.object({hookEventName:C.literal("PermissionRequest"),permissionDecision:C.enum(["approve","deny","ask"]).optional(),permissionDecisionReason:C.string().optional()}),f8=C.object({hookEventName:C.literal("UserPromptSubmit"),updatedPrompt:C.string().optional(),contextInjection:C.string().optional()}),I8=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()}),h8=C.object({decision:C.object({behavior:C.nativeEnum(Q1)}).optional(),systemMessage:C.string().optional(),hookSpecificOutput:C.discriminatedUnion("hookEventName",[S8,M8,y8,z8,v8,T8,k8,f8,I8,P8]).optional(),suppressOutput:C.boolean().optional()}),x8=C.object({type:C.literal("command"),command:C.string(),timeout:C.number().positive().optional(),statusMessage:C.string().optional()}),p8=C.object({type:C.literal("prompt"),prompt:C.string(),timeout:C.number().positive().optional()}),d8=C.discriminatedUnion("type",[x8,p8]),Y1=C.union([C.string(),C.array(C.string())]),u8=C.object({tools:Y1.optional(),paths:Y1.optional(),commands:Y1.optional()}),B$=C.object({name:C.string().optional(),matcher:u8.optional(),hooks:C.array(d8)}),RW=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 pw($){let b=h8.safeParse($);if(b.success)return{success:!0,data:b.data};return{success:!1,error:b.error}}class J1{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=pw(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 g8}from"child_process";class X1{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 O1{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=g8($,[],{shell:!0,env:Q,cwd:w.projectDir,timeout:V}),Y=new X1(this.MAX_STDOUT_SIZE),J=new X1(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 G1{processExecutor=new O1;outputParser=new J1;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
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
3
|
|
|
4
4
|
`):void 0,modifiedOutput:Z,warning:Y.length>0?Y.join(`
|
|
@@ -27,15 +27,15 @@ import{createRequire as Y8}from"node:module";var V8=Object.create;var{getPrototy
|
|
|
27
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
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
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(
|
|
32
|
-
`+"请检查网络连接或使用自己的 API Key (/config)")}}import{createAnthropic as
|
|
33
|
-
`)}function
|
|
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
|
|
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 B1 from"picomatch";var m8=/^([A-Za-z0-9_|]+)\((.+)\)$/;class K1{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 B1(V)(b)});return B1($)(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=m8.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 B1(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=w1;executor=new G1;guard=new W1;matcher=new K1;sessionDisabled=!1;constructor(){}static getInstance(){if(!r.instance)r.instance=new r;return r.instance}loadConfig($){let b=V1(w1,$),w=xw();b=V1(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 c8,existsSync as i8,mkdirSync as l8,readdirSync as n8,statSync as gw,unlinkSync as s8}from"node:fs";import r8 from"node:os";import C1 from"node:path";var A1;((W)=>{W[W.DEBUG=0]="DEBUG";W[W.INFO=1]="INFO";W[W.WARN=2]="WARN";W[W.ERROR=3]="ERROR"})(A1||={});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 q1=null,dw=null,uw=!1;function mW($){if(q1!==$)q1=$}async function cW(){}function a8(){if(uw)return dw;uw=!0;try{let $=C1.join(r8.homedir(),".blade","logs");if(!i8($))l8($,{recursive:!0,mode:493});if(gw($).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 o8($,30),dw=$,$}catch($){return console.error("[Logger] 无法创建日志目录:",$),null}}function o8($,b){try{let w=n8($),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=C1.join($,Q);try{let Y=gw(Z);if(V-Y.mtimeMs>W)s8(Z)}catch(Y){}}}catch(w){}}function t8(){let $=a8();if(!$)return null;let b=q1||"default";return C1.join($,`blade-${b}.jsonl`)}function e8($,b,w){let V=t8();if(!V)return;try{let W={timestamp:new Date().toISOString(),level:A1[b],category:$,message:w};c8(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(e8(this.category,$,w),this.shouldLogToConsole($)){let V=A1[$],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 y($,b){return new x$({...b,category:$})}var u=new x$({category:"General"});import{ProxyAgent as $5,fetch as b5}from"undici";function w5(){return process.env.HTTPS_PROXY||process.env.HTTP_PROXY||process.env.https_proxy||process.env.http_proxy}function V5(){let $=w5();if($)try{return new $5($)}catch(b){console.warn(`[proxyFetch] Invalid proxy URL: ${$}`)}return}async function mw($,b={}){let{timeout:w=30000,signal:V,...W}=b;if(V?.aborted)throw new DOMException("The operation was aborted.","AbortError");let Q=V5(),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 b5($.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 x0=y("Service"),W5="https://blade-api-proxy.137844255.workers.dev/v1/get-zhipu-key",cw="blade-free-tier",Ob=null;async function iw($){if($!==cw)return $;if(Ob)return x0.debug("使用缓存的内置 API Key"),Ob;try{x0.info("\uD83D\uDD11 正在从代理服务获取内置 API Key...");let b=await mw(W5,{method:"GET",headers:{Authorization:`Bearer ${cw}`,"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(Ob=w.apiKey,x0.info("✅ 成功获取内置 API Key"),w.message)x0.debug(`提示: ${w.message}`);return Ob}catch(b){throw x0.error("❌ 获取内置 API Key 失败:",b),Error(`无法获取内置模型的 API Key: ${b instanceof Error?b.message:"未知错误"}
|
|
32
|
+
`+"请检查网络连接或使用自己的 API Key (/config)")}}import{createAnthropic as Q5}from"@ai-sdk/anthropic";import{createAzure as Z5}from"@ai-sdk/azure";import{createDeepSeek as Y5}from"@ai-sdk/deepseek";import{createGoogleGenerativeAI as J5}from"@ai-sdk/google";import{createOpenAICompatible as U1}from"@ai-sdk/openai-compatible";import{generateText as X5,jsonSchema as lw,Output as O5,streamText as G5}from"ai";var j$=y("Chat");function nw($){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 Gb($){if(typeof $==="string")return $;return $.filter((b)=>b.type==="text").map((b)=>b.text).join(`
|
|
33
|
+
`)}function B5($,b={}){try{return JSON.parse($)}catch{return j$.warn("⚠️ [VercelAIChatService] Failed to parse JSON, using fallback",{str:$}),b}}class F1{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 Q5({apiKey:w,baseURL:V||void 0,headers:Q})(W);case"gemini":{if(V&&!this.isGeminiOfficialUrl(V))return U1({name:"gemini",apiKey:w,baseURL:V,headers:Q})(W);return J5({apiKey:w,baseURL:V||void 0})(W)}case"azure-openai":{let J=this.extractAzureResourceName(V);if(J)return Z5({apiKey:w,resourceName:J,apiVersion:Y||"2024-08-01-preview"})(W);let X=this.buildAzureBaseUrl(V,W);return U1({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 Y5({apiKey:w,baseURL:V||void 0,headers:Q})(W);return U1({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:Gb(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:B5(Z?.arguments||"{}",{})}}),W=Gb(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:Gb(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:Gb(w.content)}}]});return b}convertTools($){if(!$||$.length===0)return;let b={};for(let w of $)b[w.name]={description:w.description,inputSchema:lw(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 O5.object({schema:lw(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=nw($),Q=this.convertMessages(W),Z=this.convertTools(b),Y=this.convertOutputFormat(this.config.outputFormat);try{let J=await X5({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=nw($),Q=this.convertMessages(W),Z=this.convertTools(b),Y=this.convertOutputFormat(this.config.outputFormat);try{let J=G5({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 sw=y("Service"),K5="blade-free-tier";function q5($){return $===K5}function C5($){return{}}async function Bb($){let b=$;if(q5($.apiKey)){sw.info("\uD83D\uDD11 检测到内置 API Key,正在获取...");let w=await iw($.apiKey);b={...$,apiKey:w}}if(b.providerId){let w=C5(b.providerId);if(Object.keys(w).length>0)b={...b,customHeaders:{...w,...b.customHeaders}},sw.debug(`\uD83D\uDD27 注入 ${b.providerId} 特定 headers:`,Object.keys(w))}return A5(b)}function A5($){return new F1($)}import{readFile as U5}from"node:fs/promises";import{basename as F5}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 U5(w,"utf-8"),W=V.split(`
|
|
35
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
36
|
`),Z+=`
|
|
37
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=
|
|
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=F5($);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 rw}from"js-tiktoken";class Y${static encodingCache=new Map;static countTokens($,b){let w=Y$.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+=Y$.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=Y$.countTokens($,b),Q=Math.floor(w*V);return W>=Q}static getEncoding($){if(!Y$.encodingCache.has($))try{let b=rw($);Y$.encodingCache.set($,b)}catch{try{let b=rw("gpt-4");Y$.encodingCache.set($,b)}catch{console.warn(`[TokenCounter] 无法为模型 ${$} 获取 encoding,使用粗略估算`),Y$.encodingCache.set($,{encode:(b)=>{return Array(Math.ceil(b.length/4))}})}}return Y$.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(){Y$.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??Y$.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=Y$.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 Bb({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
39
|
|
|
40
40
|
`),V=b.map((Q)=>{return`### ${Q.path}
|
|
41
41
|
\`\`\`
|
|
@@ -114,12 +114,12 @@ An error occurred during compaction. Retained the latest ${W} messages (~30%).
|
|
|
114
114
|
|
|
115
115
|
Error: ${O}
|
|
116
116
|
|
|
117
|
-
The conversation can continue, but consider retrying compaction later with /compact.`),q=[B,...Y],A=
|
|
118
|
-
`),preTokens:w,postTokens:A,filesIncluded:[],compactedMessages:q,boundaryMessage:X,summaryMessage:B,error:O}}}import{appendFileSync as
|
|
119
|
-
`),
|
|
120
|
-
`;
|
|
117
|
+
The conversation can continue, but consider retrying compaction later with /compact.`),q=[B,...Y],A=Y$.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 H5,mkdirSync as _5,writeFileSync as R5}from"node:fs";import E5 from"node:os";import ow from"node:path";var H1=ow.join(E5.homedir(),".blade","logs","stream-debug.log"),aw=!1;function L5(){if(aw)return;let $=ow.dirname(H1);_5($,{recursive:!0,mode:493}),R5(H1,`=== Stream Debug Log Started: ${new Date().toISOString()} ===
|
|
119
|
+
`),aw=!0}function Kb($,b,w){L5();let V=new Date().toISOString(),W=w?` | ${JSON.stringify(w)}`:"",Q=`[${V}] [${$}] ${b}${W}
|
|
120
|
+
`;H5(H1,Q)}import{EventEmitter as x5}from"events";import{z as H$}from"zod";function j9($){return $!==void 0&&typeof $.pattern==="string"&&typeof $.search_path==="string"}function N9($){return $!==void 0&&$.kind==="edit"&&typeof $.matches_found==="number"}function F0($){return $==="readonly"}import{isPlainObject as D5}from"lodash-es";class _1{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 p0($){if($===void 0)return"undefined";if(typeof $==="string")return $;try{let b=JSON.stringify($);return b===void 0?String($):b}catch{return String($)}}class tw extends Error{issues;type;constructor($,b,w="validation_error"){super($);this.issues=b;this.type=w;this.name="ToolValidationError"}}function j5($){let{code:b}=$,w=$,V=w.received;switch(b){case"invalid_type":{let W=w.expected;return`类型错误:期望 ${p0(W)},实际收到 ${p0(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(D5(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)=>p0(Q)).join(", ")}`;return"必须是枚举允许的值之一"}case"invalid_literal":{let W=w.expected;return`必须是字面量值:${p0(W)}`}case"unrecognized_keys":{let W=w.keys;if(Array.isArray(W))return`包含未知的参数:${W.map((Q)=>p0(Q)).join(", ")}`;return"包含未知的参数"}case"invalid_union":return"不符合任何有效的类型定义";case"invalid_date":return"必须是有效的日期";case"custom":return $.message||"自定义验证失败";default:return $.message||"验证失败"}}function N5($){let b=$.issues.map((V)=>{let W=V.path.join("."),Q=j5(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
121
|
${b.map((V)=>` - ${V.field}: ${V.message}`).join(`
|
|
122
|
-
`)}`;return new
|
|
122
|
+
`)}`;return new tw(w,b)}function ew($,b){let w=$.safeParse(b);if(!w.success)throw N5(w.error);return w.data}import{zodToJsonSchema as S5}from"zod-to-json-schema";function R1($){return S5($,{target:"jsonSchema7",$refStrategy:"none"})}class qb{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=R1($.schema),w=$.description.short;if($.description.long)w+=`
|
|
123
123
|
|
|
124
124
|
${$.description.long}`;if($.description.usageNotes&&$.description.usageNotes.length>0)w+=`
|
|
125
125
|
|
|
@@ -129,7 +129,7 @@ ${$.description.usageNotes.map((V)=>`- ${V}`).join(`
|
|
|
129
129
|
|
|
130
130
|
Important:
|
|
131
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:
|
|
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:R1($.schema)}},build(b){let w=ew($.schema,b);return new qb($.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 M5($){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
|
|
|
@@ -139,12 +139,12 @@ ${b.usageNotes.map((V)=>`- ${V}`).join(`
|
|
|
139
139
|
|
|
140
140
|
Important:
|
|
141
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
|
|
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 qb($.name,w,async(V,W)=>$.execute(V,W))},async execute(w,V){let W={signal:V};return $.execute(w,W)}}}function y5($){return $}function u0($,b,w,V){let W;try{W=d0(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
143
|
`,X+=`[image: ${G.mimeType||"unknown"}]
|
|
144
144
|
`;else if(G.type==="resource")O+=`[资源: ${G.mimeType||"unknown"}]
|
|
145
145
|
`,X+=`[resource: ${G.mimeType||"unknown"}]
|
|
146
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
|
|
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 d0($){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=d0(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(d0($.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)=>d0(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)=>d0(w));if(b.length>=2)return H$.union(b)}return H$.any()}import{Client as f5}from"@modelcontextprotocol/sdk/client/index.js";import{SSEClientTransport as I5}from"@modelcontextprotocol/sdk/client/sse.js";import{StdioClientTransport as P5}from"@modelcontextprotocol/sdk/client/stdio.js";import{EventEmitter as h5}from"events";var E1={name:"@blade-ai/agent-sdk",version:"0.1.6",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 $4(){return E1.version}function b4(){return E1.name}import{spawn as T5}from"child_process";import*as m0 from"crypto";import*as W4 from"http";import{URL as w4}from"url";import{promises as L1}from"fs";import v5 from"os";import D1 from"path";class j1{tokenFilePath;constructor(){let $=v5.homedir(),b=D1.join($,".blade");this.tokenFilePath=D1.join(b,"mcp-oauth-tokens.json")}async ensureConfigDir(){let $=D1.dirname(this.tokenFilePath);try{await L1.mkdir($,{recursive:!0,mode:493})}catch{}}async loadAllCredentials(){let $=new Map;try{let b=await L1.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 L1.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 g0=7777,N1="/oauth/callback",V4=200;class Cb{tokenStorage;constructor($=new j1){this.tokenStorage=$}generatePKCEParams(){let $=m0.randomBytes(32).toString("base64url"),b=m0.createHash("sha256").update($).digest("base64url"),w=m0.randomBytes(16).toString("base64url");return{codeVerifier:$,codeChallenge:b,state:w}}buildAuthorizationUrl($,b){let w=$.redirectUri||`http://localhost:${g0}${N1}`,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 w4($.authorizationUrl);return V.forEach((Q,Z)=>{W.searchParams.append(Z,Q)}),W.toString()}async startCallbackServer($){return new Promise((b,w)=>{let V=W4.createServer((W,Q)=>{try{let Z=new w4(W.url,`http://localhost:${g0}`);if(Z.pathname!==N1){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(V4,{"Content-Type":"text/html"}),Q.end(`
|
|
148
148
|
<html>
|
|
149
149
|
<body>
|
|
150
150
|
<h1>Authentication Failed</h1>
|
|
@@ -152,7 +152,7 @@ ${O}`,metadata:{serverName:b,toolName:w.name,mcpResult:J}}}catch(J){return{succe
|
|
|
152
152
|
<p>You can close this window.</p>
|
|
153
153
|
</body>
|
|
154
154
|
</html>
|
|
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(
|
|
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(V4,{"Content-Type":"text/html"}),Q.end(`
|
|
156
156
|
<html>
|
|
157
157
|
<body>
|
|
158
158
|
<h1>Authentication Successful!</h1>
|
|
@@ -160,9 +160,9 @@ ${O}`,metadata:{serverName:b,toolName:w.name,mcpResult:J}}}catch(J){return{succe
|
|
|
160
160
|
<script>window.close();</script>
|
|
161
161
|
</body>
|
|
162
162
|
</html>
|
|
163
|
-
`),V.close(),b(Y)}catch(Z){V.close(),w(Z)}});V.on("error",w),V.listen(
|
|
163
|
+
`),V.close(),b(Y)}catch(Z){V.close(),w(Z)}});V.on("error",w),V.listen(g0,()=>{console.log(`[OAuth] Callback server listening on port ${g0}`)}),setTimeout(()=>{V.close(),w(Error("OAuth callback timeout"))},300000)})}async exchangeCodeForToken($,b,w){let V=$.redirectUri||`http://localhost:${g0}${N1}`,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(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
|
|
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=T5(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 k5}from"events";var b0;((W)=>{W.DISCONNECTED="disconnected";W.CONNECTING="connecting";W.CONNECTED="connected";W.ERROR="error"})(b0||={});var S1;((W)=>{W.HEALTHY="healthy";W.DEGRADED="degraded";W.UNHEALTHY="unhealthy";W.CHECKING="checking"})(S1||={});class c0 extends k5{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 M1;((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"})(M1||={});function Q4($){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 H0 extends h5{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;inProcessHandle=null;constructor($,b,w,V){super();this.config=$;if(this.serverName=b||"default",this.inProcessHandle=V||null,$.oauth?.enabled)this.oauthProvider=new Cb;if(w?.enabled)this.healthMonitor=new c0(this,w),this.healthMonitor.on("unhealthy",(W,Q)=>{this.emit("unhealthy",W,Q)}),this.healthMonitor.on("reconnected",()=>{this.emit("healthMonitorReconnected")})}get connectionStatus(){return this.status}get availableTools(){return Array.from(this.tools.values())}get server(){return this.serverInfo}get healthCheck(){return this.healthMonitor}async connect(){return this.connectWithRetry(3,1000)}async connectWithRetry($=3,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=Q4(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 f5({name:b4(),version:$4()},{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),Q4(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(this.inProcessHandle)return this.inProcessHandle.createClientTransport();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 I5(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 x5{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 H0(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 registerInProcessServer($,b){let w=this.servers.get($);if(w){if(w.inProcessHandle===b){if(w.status==="connecting")await this.waitForServerConnected($);else if(w.status!=="connected")await this.connectServer($);return}throw Error(`MCP server "${$}" is already registered with a different handle. In-process servers cannot be replaced while other sessions may be using them.`)}let V={command:""},W=new H0(V,$,void 0,b),Q={config:V,client:W,status:"disconnected",tools:[],inProcessHandle:b};this.setupClientEventHandlers(W,Q,$),this.servers.set($,Q),this.emit("serverRegistered",$,Q);try{await this.connectServer($)}catch(Z){console.warn(`In-process MCP服务器 "${$}" 连接失败:`,Z)}}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;if(b.status==="connecting"){await this.waitForServerConnected($);return}try{b.status="connecting",await b.client.connect(),b.status="connected",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.status="connected",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(){return this.getAvailableToolsByServerNames(Array.from(this.servers.keys()))}async getAvailableToolsByServerNames($){let b=[],w=new Map,V=new Set($);for(let[W,Q]of this.servers){if(!V.has(W))continue;if(Q.status==="connected")for(let Z of Q.tools){let Y=w.get(Z.name)||0;w.set(Z.name,Y+1)}}for(let[W,Q]of this.servers){if(!V.has(W))continue;if(Q.status==="connected")for(let Z of Q.tools){let J=(w.get(Z.name)||0)>1?`${W}__${Z.name}`:Z.name,X=u0(Q.client,W,Z,J);b.push(X)}}return b}async waitForServerConnected($,b=1e4){let w=this.servers.get($);if(!w)throw Error(`MCP服务器 "${$}" 未注册`);if(w.status==="connected")return;if(w.status==="error")throw w.lastError||Error(`MCP服务器 "${$}" 连接失败`);await new Promise((V,W)=>{let Q=(X,O)=>{if(X!==$)return;if(O==="connected"){Z(),V();return}if(O==="error"||O==="disconnected"){Z();let G=this.servers.get($);W(G?.lastError||Error(`MCP服务器 "${$}" 连接失败`))}},Z=()=>{clearTimeout(Y),this.off("serverStatusChanged",Q)},Y=setTimeout(()=>{Z(),W(Error(`等待MCP服务器 "${$}" 连接超时`))},b);this.on("serverStatusChanged",Q);let J=this.servers.get($)?.status;if(J==="connected")Z(),V();else if(J==="error"||J==="disconnected"){Z();let X=this.servers.get($);W(X?.lastError||Error(`MCP服务器 "${$}" 连接失败`))}})}async findTool($){for(let[b,w]of this.servers)if(w.status==="connected"){let V=w.tools.find((W)=>W.name===$);if(V)return u0(w.client,b,V)}return null}getToolsByServer($){let b=this.servers.get($);if(!b||b.status!=="connected")return[];return b.tools.map((w)=>u0(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 F4}from"fs";import e5 from"path";import*as Rb from"node:fs/promises";import{homedir as q4}from"node:os";import*as v$ from"node:path";var Ab={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 Z4(){return{metadata:Ab,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 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
|
|
348
|
+
`}}import{exec as p5}from"node:child_process";import*as z from"node:fs/promises";import{homedir as d5}from"node:os";import*as n from"node:path";import{promisify as u5}from"node:util";var Ub=u5(p5),l=y("General"),y1={url:"https://github.com/anthropics/skills.git",branch:"main",defaultSkills:["skill-creator"]};class Y4{skillsDir;constructor($){this.skillsDir=$||n.join(d5(),".blade","skills")}async isInstalled($){let b=n.join(this.skillsDir,$,"SKILL.md");try{return await z.access(b),!0}catch{return!1}}async isGitAvailable(){try{return await Ub("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 z.mkdir(this.skillsDir,{recursive:!0,mode:493}),await Ub(`git clone --depth 1 --branch ${w} --single-branch ${b} "${W}"`,{timeout:30000});let Q=n.join(W,"skills",$);try{await z.access(Q)}catch{return l.warn(`Skill ${$} not found in official repository`),await z.rm(W,{recursive:!0,force:!0}),!1}try{await z.rm(V,{recursive:!0,force:!0})}catch{}return await z.cp(Q,V,{recursive:!0}),await z.rm(W,{recursive:!0,force:!0}),l.info(`Successfully installed: ${$}`),!0}catch(Q){try{await z.rm(W,{recursive:!0,force:!0})}catch{}return l.warn(`Failed to install ${$}: ${Q instanceof Error?Q.message:"Unknown error"}`),!1}}async ensureDefaultSkillsInstalled(){await z.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 z.mkdir(this.skillsDir,{recursive:!0,mode:493}),await Ub(`git clone --depth 1 "${$}" "${W}"`,{timeout:60000});let Q=n.join(W,"SKILL.md");try{await z.access(Q)}catch{return l.warn(`No SKILL.md found in repository ${$}`),await z.rm(W,{recursive:!0,force:!0}),!1}await z.rm(V,{recursive:!0,force:!0}),await z.rename(W,V);try{await z.rm(n.join(V,".git"),{recursive:!0,force:!0})}catch{}return l.info(`Successfully installed skill from repo: ${w}`),!0}catch(Q){try{await z.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 z.access(Q)}catch{return l.warn(`Local path does not exist: ${Q}`),!1}let Z=n.join(Q,"SKILL.md");try{await z.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 z.mkdir(this.skillsDir,{recursive:!0,mode:493}),await z.rm(W,{recursive:!0,force:!0}),w)await z.symlink(Q,W,"dir"),l.info(`Created symlink for skill: ${V}`);else await z.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 z.mkdir(this.skillsDir,{recursive:!0,mode:493}),l.info("Cloning official skills repository..."),await Ub(`git clone --depth 1 --branch ${b} --single-branch ${$} "${w}"`,{timeout:60000});let Q=n.join(w,"skills"),Z=await z.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 z.access(n.join(X,"SKILL.md")),await z.rm(O,{recursive:!0,force:!0}),await z.cp(X,O,{recursive:!0}),l.info(`Installed: ${J}`),V.push(J)}catch(G){l.warn(`Failed to install ${J}`),W.push(J)}}await z.rm(w,{recursive:!0,force:!0})}catch(Q){try{await z.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 z1=null;function J4($){if(!z1)z1=new Y4($);return z1}import*as i0 from"node:fs/promises";import*as Fb from"node:path";import{parse as g5}from"yaml";var m5=/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/,c5=/^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]?$/,X4=1024;function i5($){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 O4($){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 l5($,b){if(!$.name)return{valid:!1,error:"Missing required field: name"};if(!c5.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>X4)return{valid:!1,error:`Description too long: ${$.description.length} characters (max ${X4})`};let w;if($.model)w=$.model==="inherit"?"inherit":$.model;return{valid:!0,metadata:{name:$.name,description:$.description.trim(),allowedTools:i5($["allowed-tools"]),version:$.version,argumentHint:$["argument-hint"]?.trim(),userInvocable:O4($["user-invocable"]),disableModelInvocation:O4($["disable-model-invocation"]),model:w,whenToUse:$.when_to_use?.trim()}}}function G4($,b,w){let V=$.match(m5);if(!V)return{success:!1,error:"Invalid SKILL.md format: missing YAML frontmatter (must start with ---)"};let[,W,Q]=V,Z;try{Z=g5(W)}catch(X){return{success:!1,error:`Failed to parse YAML frontmatter: ${X instanceof Error?X.message:String(X)}`}}let Y=l5(Z,b);if(!Y.valid)return{success:!1,error:Y.error};let J=Fb.dirname(b);return{success:!0,content:{metadata:{...Y.metadata,path:b,basePath:J,source:w},instructions:Q.trim()}}}async function Hb($,b){try{let w=await i0.readFile($,"utf-8");return G4(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 B4($){try{let b=await i0.readFile($.path,"utf-8"),w=G4(b,$.path,$.source);return w.success?w.content:null}catch{return null}}async function K4($){try{return await i0.access(Fb.join($,"SKILL.md")),!0}catch{return!1}}var n5={userSkillsDir:v$.join(q4(),".blade","skills"),projectSkillsDir:".blade/skills",claudeUserSkillsDir:v$.join(q4(),".claude","skills"),claudeProjectSkillsDir:".claude/skills",cwd:process.cwd()},_b=null;class v1{skills=new Map;pluginSkills=new Map;config;initialized=!1;constructor($){this.config={...n5,...$}}static getInstance($){if(!_b)_b=new v1($);return _b}static resetInstance(){_b=null}async initialize(){if(this.initialized)return{skills:Array.from(this.skills.values()),errors:[]};let $=[],b=[];try{await J4(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(Ab.name,Ab)}async scanDirectory($,b){let w=[],V=[];try{await Rb.access($)}catch{return{skills:w,errors:V}}try{let W=await Rb.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 K4(Z))continue;let J=await Hb(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 B4(b)}loadBuiltinContent($){switch($){case"skill-creator":return Z4();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 v1.getInstance($)}async function Eb($){return N$($).initialize()}var s5="Skill",r5=/<available_skills>\s*<\/available_skills>/;function Lb($){let w=N$().generateAvailableSkillsList();if(!w)return $;return $.map((V)=>{if(V.name!==s5)return V;let W=V.description.replace(r5,`<available_skills>
|
|
350
350
|
${w}
|
|
351
|
-
</available_skills>`);if(W===V.description)return V;return{...V,description:W}})}import{execSync as
|
|
351
|
+
</available_skills>`);if(W===V.description)return V;return{...V,description:W}})}import{execSync as a5}from"child_process";import*as R0 from"os";import*as _0 from"path";function o5(){let $=process.cwd(),b=t5($);return{workingDirectory:$,projectRoot:b,platform:`${R0.platform()} (${R0.arch()})`,nodeVersion:process.version,currentDate:new Date().toISOString().split("T")[0],homeDirectory:R0.homedir()}}function l0(){let $=o5();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 t5($){let b=$;while(b!==_0.dirname(b)){if(C4(_0.join(b,".git")))return b;if(C4(_0.join(b,"package.json")))return b;b=_0.dirname(b)}return $}function C4($){try{return a5(`test -e "${$}"`,{stdio:"ignore"}),!0}catch{return!1}}var A4=`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}}`,U4=`You are in **PLAN MODE** - a read-only research phase for designing implementation plans.
|
|
528
528
|
|
|
529
529
|
## Core Objective
|
|
530
530
|
|
|
@@ -566,49 +566,49 @@ Your plan should include:
|
|
|
566
566
|
5. **Risks** - Potential issues and mitigations
|
|
567
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 $6=/<available_skills>\s*<\/available_skills>/;async function E0($={}){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=U4,G="plan_mode_prompt";else O=w??A4,G=w?"replace_default":"default";if(Y.push(O),J.push({name:G,loaded:!0,length:O.length}),b){let q=await W6(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 B=
|
|
573
|
+
`);return B=b6(B),B=V6(B,Z),{prompt:B,sources:J}}function b6($){let w=N$().generateAvailableSkillsList();if(!w)return $;return $.replace($6,`<available_skills>
|
|
574
574
|
${w}
|
|
575
|
-
</available_skills>`)}var
|
|
575
|
+
</available_skills>`)}var w6={"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 V6($,b){let w=b||"zh-CN",V=w6[w]||w,W=`IMPORTANT: Always respond in ${V}. All your responses must be in ${V}.`;return $.replace("{{LANGUAGE_INSTRUCTION}}",W)}async function W6($){let b=e5.join($,"BLADE.md");try{return(await F4.readFile(b,"utf-8")).trim()||null}catch{return null}}import*as N2 from"os";import*as S2 from"path";import{basename as K6,extname as q6}from"path";import{z as jb}from"zod";function s$(){return!1}function H4(){throw Error("ACP mode is not available")}import{existsSync as T1,readFileSync as Q6,unlinkSync as Z6,writeFileSync as Y6}from"fs";import{dirname as J6}from"path";import{mkdirSync as X6}from"fs";var T$=y("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=T1($),w=null;if(b)try{w=Q6($,"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=J6(J);if(!T1(O))X6(O,{recursive:!0});Y6(J,X.content,"utf-8"),w.push(J),T$.debug(`[CheckpointService] Restored: ${J}`)}else if(!X.exists&&T1(J))Z6(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 _4{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 O6=new _4;function L0(){return O6}import{isAbsolute as R4}from"path";import{z as o}from"zod";var g={filePath:($)=>o.string().min(1,"File path is required").refine((b)=>R4(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(($)=>R4($),{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 k1 from"diff";function E4($,b,w=4){if($===b)return null;let V=k1.createPatch("file",$,b,"","",{context:w}),W=V.split(`
|
|
576
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
578
|
${JSON.stringify({patch:V,startLine:Math.max(1,Q-w),matchLine:Q})}
|
|
579
579
|
<<</DIFF>>>
|
|
580
|
-
`}function
|
|
580
|
+
`}function L4($,b,w,V,W=4){let Q=$.indexOf(w);if(Q===-1)return null;let Y=$.substring(0,Q).split(`
|
|
581
581
|
`).length-1,J=$.split(`
|
|
582
582
|
`),X=b.split(`
|
|
583
583
|
`),O=w.split(`
|
|
584
584
|
`),G=V.split(`
|
|
585
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
586
|
`),U=X.slice(B,A).join(`
|
|
587
|
-
`),F=
|
|
587
|
+
`),F=k1.createPatch("file",K,U,"","",{context:W});return`
|
|
588
588
|
<<<DIFF>>>
|
|
589
589
|
${JSON.stringify({patch:F,startLine:B+1,matchLine:Y+1})}
|
|
590
590
|
<<</DIFF>>>
|
|
591
|
-
`}function
|
|
591
|
+
`}function D4($){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 b}})}function
|
|
594
|
+
`;default:return b}})}function j4($,b){let w=b.split(`
|
|
595
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
596
|
`),J=$.split(`
|
|
597
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
598
|
`)===Y)return B.join(`
|
|
599
|
-
`)}return null}import{promises as
|
|
599
|
+
`)}return null}import{promises as Db}from"node:fs";var n0=y("Tool");class J${static instance=null;accessedFiles=new Map;constructor(){}static getInstance(){if(!J$.instance)J$.instance=new J$;return J$.instance}async recordFileRead($,b){try{let w=await Db.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 Db.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 Db.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 Db.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(){J$.instance=null}}import*as M4 from"node:crypto";import{promises as f$}from"node:fs";import*as V0 from"node:path";import{execSync as G6}from"node:child_process";import*as f1 from"node:os";import*as w0 from"node:path";function B6($){return w0.resolve($).replace(/[/\\]/g,"-").replace(/:/g,"_")}function s0($){let b=f1.homedir(),w=B6($);return w0.join(b,".blade","projects",w)}function C$($,b){return w0.join(s0($),`${b}.jsonl`)}function N4($){try{return G6("git rev-parse --abbrev-ref HEAD",{cwd:$,encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim()||void 0}catch{return}}function r0(){return w0.join(f1.homedir(),".blade")}async function S4(){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=M4.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 I1=E({name:"Edit",displayName:"File Edit",kind:"write",strict:!0,isConcurrencySafe:!1,schema:jb.object({file_path:g.filePath({description:"Absolute path of the file to edit"}),old_string:jb.string().min(1,"old_string cannot be empty").describe("String to replace"),new_string:jb.string().describe("Replacement string (can be empty)"),replace_all:jb.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=L0(),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=J$.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
600
|
|
|
601
601
|
Details: ${w$.message}`,displayContent:`❌ 编辑失败:文件已被外部程序修改
|
|
602
602
|
|
|
603
603
|
${w$.message}
|
|
604
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=
|
|
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
|
|
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=C6(B,V);if(!q.matched){let P=F6(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=A6(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 eb=Math.max(0,h-1),$1=Math.min(P.length-1,h+1),A0=P.slice(eb,$1+1).map((V8)=>V8.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
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
|
|
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 J$.getInstance().recordFileEdit(w,Y,"edit");let D=await O.stat(w),I=L4(B,U,A,W,4),N=K6(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$=U6(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=q6($.file_path);return b?`**/*${b}`:"**/*"}});function y4($){return $.replaceAll("‘","'").replaceAll("’","'").replaceAll("“",'"').replaceAll("”",'"')}function C6($,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=D4(b);if(Q!==b&&$.includes(Q))return{matched:Q,strategy:"unescape"};let Z=j4($,b);if(Z)return{matched:Z,strategy:"flexible"};return{matched:null,strategy:"failed"}}function A6($,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 U6($,b){let{file_path:w,matches_found:V,replacements_made:W,replace_all:Q,size_diff:Z}=$,Y=`✅ 成功编辑文件: ${w}`;if(Y+=`
|
|
609
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
|
|
611
|
-
`),W=V.length,Q=
|
|
610
|
+
\uD83D\uDCCA 文件大小${J}个字符`}if(b)Y+=b;return Y}function F6($,b,w){let V=$.split(`
|
|
611
|
+
`),W=V.length,Q=H6($,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
612
|
`),O=`String not found in file.
|
|
613
613
|
|
|
614
614
|
File: ${w}
|
|
@@ -654,14 +654,14 @@ ${X}
|
|
|
654
654
|
\uD83D\uDD27 接下来我会:
|
|
655
655
|
`,B+=` 1. 重新读取文件内容
|
|
656
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
|
|
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 H6($,b,w=3){let V=$.split(`
|
|
658
658
|
`),W=b.split(`
|
|
659
|
-
`);if(W.length===1)return V.map((J,X)=>({text:J,lineNumber:X+1,similarity:
|
|
660
|
-
`),X=
|
|
659
|
+
`);if(W.length===1)return V.map((J,X)=>({text:J,lineNumber:X+1,similarity:z4(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=z4(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 z4($,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=_6(J,X),G=Math.max(J.length,X.length);return 1-O/G}function _6($,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 R6,extname as v4}from"path";import{z as E6}from"zod";var P1=E({name:"Read",displayName:"File Read",kind:"readonly",schema:E6.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=L0(),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 J$.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=v4(w).toLowerCase(),q=L6(B),A=D6(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
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=
|
|
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=R6(w),_=U.lines_read||U.total_lines,D=_?`读取 ${_} 行从 ${F}`:`读取 ${F}`;U.summary=D;let I=j6(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=v4($.file_path);return b?`**/*${b}`:"**/*"}});function L6($){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 D6($){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 j6($,b){let w=`✅ 成功读取文件: ${$}`;if(b.file_size!==void 0&&typeof b.file_size==="number")w+=` (${N6(b.file_size)})`;if(b.lines_read!==void 0)w+=`
|
|
663
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
|
|
664
|
+
\uD83D\uDD10 文件以 base64 编码显示`;return w}function N6($){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 S6}from"fs";import{basename as M6,dirname as y6,extname as T4}from"path";import{z as h1}from"zod";var x1=E({name:"Write",displayName:"File Write",kind:"write",strict:!0,isConcurrencySafe:!1,schema:h1.object({file_path:g.filePath({description:"Absolute file path to write"}),content:h1.string().describe("Content to write"),encoding:g.encoding(),create_directories:h1.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=L0(),G=s$();if(Q){let M=y6(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=J$.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
666
|
Details: ${j.message}`,displayContent:`❌ 写入失败:文件已被外部程序修改
|
|
667
667
|
|
|
@@ -671,12 +671,12 @@ ${j.message}
|
|
|
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 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
|
|
675
|
-
`).length:0,_=
|
|
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 S6.writeFile(w,M)}if(Y)await J$.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,_=M6(w),D=null;if(q&&W==="utf8"&&q!==V){if(q.length<1048576&&V.length<1048576)D=E4(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?k4(U.size):"unknown"} 到 ${_}`,kind:"edit",oldContent:q||"",newContent:W==="utf8"?V:void 0},N=z6(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=T4($.file_path);return b?`**/*${b}`:"**/*"}});function z6($,b,w,V){let W=`✅ 成功写入文件: ${$}`;if(b.file_size!==void 0)W+=` (${k4(b.file_size)})`;if(b.snapshot_created)W+=`
|
|
676
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=
|
|
677
|
+
\uD83D\uDD10 使用编码: ${b.encoding}`;if(V)W+=V;if(w&&b.encoding==="utf8"&&!V){let Q=v6($,w);if(Q)W+=`
|
|
678
678
|
|
|
679
|
-
`+Q}return W}function
|
|
679
|
+
`+Q}return W}function v6($,b){let w=T4($).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
680
|
`);if(X.length>100)Y=X.slice(0,100).join(`
|
|
681
681
|
`),J=!0;if(Y.length>5000)Y=Y.substring(0,5000),J=!0;let O=`\uD83D\uDCC4 文件内容:
|
|
682
682
|
|
|
@@ -685,11 +685,11 @@ ${j.message}
|
|
|
685
685
|
`))O+=`
|
|
686
686
|
`;if(O+="```",J)O+=`
|
|
687
687
|
|
|
688
|
-
⚠️ 内容已截断(完整文件共 ${X.length} 行,${b.length} 字符)`;return O}function
|
|
688
|
+
⚠️ 内容已截断(完整文件共 ${X.length} 行,${b.length} 字符)`;return O}function k4($){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 Nb from"fs/promises";import{z as D0}from"zod";var Sb=E({name:"NotebookEdit",displayName:"Notebook Edit",kind:"write",schema:D0.object({notebook_path:D0.string().describe("The absolute path to the Jupyter notebook file to edit (must be absolute, not relative)"),cell_id:D0.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:D0.string().describe("The new source for the cell"),cell_type:D0.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:D0.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 Nb.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
689
|
`).map((B,q,A)=>q<A.length-1?B+`
|
|
690
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
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
|
|
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 Nb.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 T6}from"zod";var p1=E({name:"EnterPlanMode",displayName:"Enter Plan Mode",kind:"readonly",schema:T6.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
|
|
|
@@ -781,7 +781,7 @@ Begin your research now.`,displayContent:"✅ Entering Plan mode",metadata:{appr
|
|
|
781
781
|
|
|
782
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 f4}from"node:fs";import{homedir as k6}from"node:os";import*as d1 from"node:path";import{z as I4}from"zod";var u1=E({name:"ExitPlanMode",displayName:"Exit Plan Mode",kind:"readonly",schema:I4.object({plan:I4.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($,b){let w=$.plan||"";if(w&&b.sessionId)try{let V=
|
|
819
|
+
`},async execute($,b){let w=$.plan||"";if(w&&b.sessionId)try{let V=d1.join(k6(),".blade","plans");await f4.mkdir(V,{recursive:!0,mode:493});let W=d1.join(V,`plan_${b.sessionId}.md`);await f4.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
|
|
@@ -829,23 +829,23 @@ please reject and ask for a proper plan.`,details:"After approval, the assistant
|
|
|
829
829
|
`+(V.feedback||"No specific feedback provided.")+`
|
|
830
830
|
|
|
831
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
|
|
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
|
|
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
|
|
832
|
+
`+"Proceeding with implementation.",displayContent:"Plan mode exit (non-interactive)",metadata:{approved:null}}}});import m6 from"fast-glob";import{stat as c6}from"node:fs/promises";import{join as i6,resolve as l6}from"path";import{z as yb}from"zod";import{existsSync as f6,readFileSync as I6}from"node:fs";import{readFile as P6}from"node:fs/promises";import{dirname as h6,join as h4}from"node:path";import x6 from"fast-glob";import{LRUCache as p6}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"],d6=["*.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 u6($){if(!f6($))return{patterns:[],negatePatterns:[]};try{let b=I6($,"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 P4=new p6({max:100,ttl:30000,updateAgeOnGet:!0});async function g6($,b){let w=[...W0.map((J)=>`${J}/**`),...b?.scanIgnore??[]],V=`${$}|${w.join(",")}`,W=P4.get(V);if(W)return W;let Q=await x6("**/.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=h6(J).replace(/\\/g,"/"),O=X==="."?"":X,B=(await P6(h4($,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 P4.set(V,Z,{ttl:Y}),Z}class Mb{orderedRules=[];ignorePatterns=[];negatePatterns=[];constructor($={}){this.initialize($)}static async create($={}){let b=new Mb({...$,useGitignore:!1}),{cwd:w=process.cwd(),useGitignore:V=!0,gitignoreScanMode:W="root",customScanIgnore:Q=[],cacheTTL:Z}=$;if(V&&W==="recursive"){let Y=await g6(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,...d6];Q.push(...Y);for(let J of Y)this.orderedRules.push({type:"ignore",matcher:t0(J,{dot:!0})})}if(w){let Y=h4(b,".gitignore"),{patterns:J,negatePatterns:X}=u6(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 g1($){let b=Error($);return b.name="AbortError",b}var m1=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=l6(V);try{if(!(await c6(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 Mb.create({cwd:X,useGitignore:!0,useDefaults:!0,gitignoreScanMode:"recursive",customScanIgnore:[],cacheTTL:30000}),{matches:G,wasTruncated:B}=await n6(X,w,{maxResults:W,includeDirectories:Q,caseSensitive:Z,signal:J},O),q=s6(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=r6(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 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
|
|
840
|
-
\uD83D\uDCCB 显示前 ${W} 个结果`;else Z=`✅ 在 ${b} 中找到 ${V} 个匹配 "${w}" 的文件`;return Z}import{execSync as
|
|
841
|
-
`).forEach((G,B)=>{if(Q.test(G))W.push({file_path:
|
|
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=
|
|
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 n6($,b,w,V){let W=V.getIgnorePatterns(),Q=[],Z=!1;return await new Promise((Y,J)=>{if(w.signal.aborted){J(g1("文件搜索被用户中止"));return}let X=m6.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(g1("文件搜索被用户中止"));return}if(Q.length>=w.maxResults){q();return}let U=K.path.replace(/\\/g,"/"),F=i6($,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(g1("文件搜索被用户中止"))},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 s6($){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 r6($){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 c1,spawn as i1}from"child_process";import{existsSync as zb}from"fs";import{readdir as a6,readFile as o6}from"fs/promises";import{join as x4,relative as t6}from"path";import e6 from"picomatch";import{z as r$}from"zod";function $7(){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=x4(process.cwd(),"vendor","ripgrep",W);if(zb(Q))return Q;try{let Z=new URL("../../../../vendor/ripgrep/"+W,import.meta.url).pathname;if(zb(Z))return Z}catch{}return null}function p4(){try{let b=process.platform==="win32"?"where rg":"command -v rg 2>/dev/null || which rg 2>/dev/null",w=c1(b,{encoding:"utf8",stdio:["pipe","pipe","ignore"]}).split(/\r?\n/)[0].trim();if(w)return w}catch{}let $=$7();if($&&zb($))return $;try{let b=P0("@vscode/ripgrep");if(b?.rgPath&&zb(b.rgPath))return b.rgPath}catch{}return null}async function b7($){try{return c1("git rev-parse --git-dir",{cwd:$,stdio:"ignore"}),!0}catch{return!1}}function w7(){try{return c1("grep --version",{stdio:"ignore"}),!0}catch{return!1}}async function V7($,b,w,V){let W=p4();if(!W)throw Error("ripgrep not available");return new Promise((Q,Z)=>{let Y=i1(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 W7($,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=i1("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 Q7($,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=i1("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 Z7($,b,w,V){let W=[],Q=new RegExp($,w.caseInsensitive?"gi":"g"),Z=await Y7(b,V),Y=0;for(let J of Z){if(V.throwIfAborted(),d4(J))continue;if(w.glob&&!J7(J,w.glob))continue;try{(await o6(J,"utf-8")).split(`
|
|
841
|
+
`).forEach((G,B)=>{if(Q.test(G))W.push({file_path:t6(b,J),line_number:B+1,content:G})}),Y++}catch(X){}}return{matches:W,totalFiles:Y}}async function Y7($,b){let w=[];async function V(W){b.throwIfAborted();try{let Q=await a6(W,{withFileTypes:!0});for(let Z of Q){b.throwIfAborted();let Y=x4(W,Z.name);if(Z.isDirectory()){if(!d4(Y))await V(Y)}else if(Z.isFile())w.push(Y)}}catch(Q){}}return await V($),w}function d4($){for(let b of W0)if($.includes(b))return!0;return!1}function J7($,b){return e6(b)($)}function X7($){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 O7($,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=G7(W);if(Q)V.push(Q)}return V;default:return[]}}function G7($){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 B7($){let{search_pattern:b,search_path:w,output_mode:V,total_matches:W,strategy:Q}=$,Z=`✅ 在 ${w} 中搜索 "${b}"`;if(Q)Z+=`
|
|
843
843
|
\uD83D\uDD27 使用策略: ${Q}`;switch(V){case"files_with_matches":Z+=`
|
|
844
844
|
\uD83D\uDCC1 找到 ${W} 个包含匹配内容的文件`;break;case"count":Z+=`
|
|
845
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
|
|
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
|
|
846
|
+
\uD83D\uDCDD 找到 ${W} 个匹配行`;break}return Z}var l1=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=p4();if(I)try{K?.(`\uD83D\uDE80 使用 ripgrep (${I})`);let F$=X7({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 V7(F$,Z,U,K),_="ripgrep"}catch{K?.("⚠️ ripgrep 失败,尝试降级策略..."),F=null}if(!F&&await b7(V))try{K?.("\uD83D\uDCE6 使用 git grep"),F=await W7(w,V,{caseInsensitive:Y??!1,glob:W,contextLines:G},U),_="git-grep"}catch{K?.("⚠️ git grep 失败,继续尝试其他策略..."),F=null}if(!F&&w7())try{K?.("\uD83D\uDD27 使用系统 grep"),F=await Q7(w,V,{caseInsensitive:Y??!1,contextLines:G},U),_="system-grep"}catch{K?.("⚠️ 系统 grep 失败,使用纯 JavaScript 实现..."),F=null}if(!F)K?.("\uD83D\uDCA1 使用纯 JavaScript 搜索实现"),D=(await Z7(w,V,{caseInsensitive:Y??!1,glob:W,multiline:A??!1},U)).matches,_="fallback",F={stdout:"",stderr:"",exitCode:0};else D=O7(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=B7(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 R7}from"child_process";import{randomUUID as E7}from"crypto";import{z as n1}from"zod";import{execSync as K7}from"child_process";import{existsSync as _$,mkdtempSync as q7,writeFileSync as C7}from"fs";import{tmpdir as A7}from"os";import{join as e0}from"path";var vb=y("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 $=K7("bwrap --version 2>/dev/null",{encoding:"utf-8"}).trim();return vb.debug(`[SandboxExecutor] Detected bubblewrap: ${$}`),{available:!0,type:"bubblewrap",version:$,features:{fileSystemIsolation:!0,networkIsolation:!0,processIsolation:!0}}}catch{return vb.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 vb.debug("[SandboxExecutor] Detected macOS sandbox-exec (Seatbelt)"),{available:!0,type:"seatbelt",version:"macOS built-in",features:{fileSystemIsolation:!0,networkIsolation:!0,processIsolation:!0}}}catch{vb.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=q7(e0(A7(),"sandbox-")),W=e0(V,"sandbox.sb");C7(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 j0(){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={...$},j0().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=j0();if(!w.canUseSandbox())return $;let V=b||process.cwd(),W=w.buildExecutionOptions(V,this.settings.network);return w.wrapCommand($,W)}getCapabilities(){return j0().getCapabilities()}}function N0(){return u$.getInstance()}import{spawn as U7}from"child_process";import{randomUUID as F7}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_${F7()}`,w={};for(let[Q,Z]of Object.entries({...process.env,...$.env,BLADE_CLI:"1"}))if(Z!==void 0)w[Q]=Z;let V=U7("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 Tb={maxLines:30,maxChars:3000,keepHead:10,keepTail:10,summarize:!0},Q0={maxLines:100,maxChars:1e4,keepHead:40,keepTail:40,summarize:!0},u4={maxLines:200,maxChars:20000,keepHead:80,keepTail:80,summarize:!1},H7={maxLines:150,maxChars:15000,keepHead:50,keepTail:50,summarize:!0},_7=[{pattern:/^git\s+(rm|add)\s+(-r|--cached|-rf|-f)?\s*/i,config:Tb,summaryTemplate:($)=>`Successfully processed ${$} files`},{pattern:/^(npm|pnpm|yarn|bun)\s+(install|i|add|remove|uninstall)/i,config:Tb,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:u4},{pattern:/^git\s+(status|branch|remote)/i,config:Q0},{pattern:/^git\s+(log|diff|show)/i,config:u4},{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:Tb,summaryTemplate:($)=>`Docker operation completed (${$} lines)`},{pattern:/^(pip|pip3|poetry|pipenv)\s+(install|uninstall)/i,config:Tb,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 _7)if(b.test($))return{config:w,summaryTemplate:V};return{config:H7}}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
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
850
|
`);if(X+=`
|
|
851
851
|
|
|
@@ -862,7 +862,7 @@ ${q}`}let O=b.summarize&&w?w(Q,V):void 0;if(O)X+=`
|
|
|
862
862
|
`).length} lines`);if(W.truncated)Z.push(`stderr: ${W.originalLines} lines → ${W.content.split(`
|
|
863
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
864
|
`).length>w.maxLines||$.length>w.maxChars}static getStats($){return{lines:$.split(`
|
|
865
|
-
`).length,chars:$.length,words:$.split(/\s+/).filter(Boolean).length}}}var
|
|
865
|
+
`).length,chars:$.length,words:$.split(/\s+/).filter(Boolean).length}}}var s1=E({name:"Bash",displayName:"Bash Command",kind:"execute",schema:n1.object({command:g.command({description:"Bash command to execute"}),timeout:g.timeout(1000,300000,30000),cwd:n1.string().optional().describe("Working directory (optional; applies only to this command). To persist, use cd"),env:g.environment(),run_in_background:n1.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.
|
|
866
866
|
|
|
867
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.
|
|
868
868
|
|
|
@@ -878,37 +878,37 @@ Before executing commands:
|
|
|
878
878
|
* cd "/Users/name/My Documents" (correct)
|
|
879
879
|
* cd /Users/name/My Documents (incorrect - will fail)
|
|
880
880
|
* python "/path/with spaces/script.py" (correct)
|
|
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=
|
|
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=N0(),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 L7(B,W,Q);if(s$())return Y?.("通过 IDE 终端执行命令..."),D7(B,W,Q,V,J,Y);else return j7(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 L7($,b,w){let W=A$.getInstance().startBackgroundProcess({command:$,sessionId:E7(),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
882
|
`+`\uD83C\uDD94 进程 ID: ${W.pid}
|
|
883
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
|
|
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 D7($,b,w,V,W,Q){let Z=Date.now();try{let J=await H4().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
885
|
输出: ${J.stdout}
|
|
886
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
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=
|
|
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=g4({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 j7($,b,w,V,W,Q){return new Promise((Z)=>{let Y=Date.now(),J="",X="",O=!1,G=R7("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
889
|
输出: ${J}
|
|
890
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
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=
|
|
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=g4({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 g4($){let{stdout:b,stderr:w,command:V,execution_time:W,exit_code:Q,signal:Z}=$,Y=`✅ Bash 命令执行完成: ${V}`;if(Y+=`
|
|
893
893
|
⏱️ 执行时间: ${W}ms`,Y+=`
|
|
894
894
|
\uD83D\uDCCA 退出码: ${Q??"N/A"}`,Z)Y+=`
|
|
895
895
|
⚡ 信号: ${Z}`;if(b&&b.trim())Y+=`
|
|
896
896
|
\uD83D\uDCE4 输出:
|
|
897
897
|
${b.trim()}`;if(w&&w.trim())Y+=`
|
|
898
898
|
⚠️ 错误输出:
|
|
899
|
-
${w.trim()}`;return Y}import{z as
|
|
899
|
+
${w.trim()}`;return Y}import{z as m4}from"zod";var r1=E({name:"KillShell",displayName:"终止后台 Shell",kind:"execute",schema:m4.object({shell_id:m4.string().min(1).describe("Background Shell ID to terminate")}),description:{short:"Kills a running background bash shell by its ID",long:`
|
|
900
900
|
- Kills a running background bash shell by its ID
|
|
901
901
|
- Takes a shell_id parameter identifying the shell to kill
|
|
902
902
|
- Returns a success or failure status
|
|
903
903
|
- Use this tool when you need to terminate a long-running shell
|
|
904
904
|
- Shell IDs can be found using the /tasks command
|
|
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
|
|
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 z7}from"nanoid";import{promises as t}from"node:fs";import*as d from"node:path";import{fileURLToPath as N7}from"node:url";import{nanoid as S7}from"nanoid";var c4={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"},gY=["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:"已完成"},i4={init:"proposal",requirements:"requirements",design:"design",tasks:"tasks",implementation:"tasks",done:null};var M7=N7(import.meta.url),y7=d.dirname(M7),l4=d.join(y7,"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($),c4[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:S7(),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=i4[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}
|
|
906
906
|
|
|
907
907
|
---
|
|
908
908
|
|
|
909
909
|
<!-- Merged from ${$} -->
|
|
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(
|
|
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(l4,b);return this.readFile(w)}async readSteeringTemplate($){let b=bb.STEERING_TEMPLATE_NAMES[$],w=d.join(l4,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 a1=y("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){a1.debug("SpecManager already initialized, skipping...");return}this.fileManager=new bb($),await this.fileManager.initializeDirectories();let b=await this.fileManager.readSteeringContext();this.updateState({steeringContext:b}),a1.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)
|
|
912
912
|
|
|
913
913
|
${$.constitution}`);if($.product)b.push(`## Product Vision
|
|
914
914
|
|
|
@@ -920,7 +920,7 @@ ${$.structure}`);return b.length>0?b.join(`
|
|
|
920
920
|
|
|
921
921
|
---
|
|
922
922
|
|
|
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")
|
|
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")a1.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:z7(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`# ${$}
|
|
924
924
|
|
|
925
925
|
## Summary
|
|
926
926
|
|
|
@@ -954,7 +954,7 @@ ${b}
|
|
|
954
954
|
<!-- What needs to be clarified before proceeding? -->
|
|
955
955
|
|
|
956
956
|
1.
|
|
957
|
-
`}calculateTaskProgress($){let b=$.length,w=$.filter((V)=>V.status==="completed").length;return{total:b,completed:w}}}var
|
|
957
|
+
`}calculateTaskProgress($){let b=$.length,w=$.filter((V)=>V.status==="completed").length;return{total:b,completed:w}}}var n4=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.
|
|
958
958
|
|
|
959
959
|
## Task Structure
|
|
960
960
|
|
|
@@ -998,7 +998,7 @@ AddTask({
|
|
|
998
998
|
|
|
999
999
|
`+`\uD83D\uDCC8 Progress: ${G.completed}/${G.total} tasks (${G.percentage}%)
|
|
1000
1000
|
|
|
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
|
|
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 o1}from"zod";var s4=E({name:"EnterSpecMode",displayName:"Enter Spec Mode",kind:"readonly",schema:o1.object({featureName:o1.string().min(1).describe("The name of the feature/change (used as directory name)"),description:o1.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.
|
|
1002
1002
|
|
|
1003
1003
|
## Spec-Driven Development (SDD)
|
|
1004
1004
|
|
|
@@ -1094,7 +1094,7 @@ Start by asking the user for more details about their requirements.`,displayCont
|
|
|
1094
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.
|
|
1095
1095
|
|
|
1096
1096
|
Proceeding with spec creation. Follow the structured workflow:
|
|
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
|
|
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 t1}from"zod";var r4=E({name:"ExitSpecMode",displayName:"Exit Spec Mode",kind:"readonly",schema:t1.object({archive:t1.boolean().optional().default(!1).describe("If true, archive the spec (mark as done and move to archive)"),summary:t1.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.
|
|
1098
1098
|
|
|
1099
1099
|
## Options
|
|
1100
1100
|
|
|
@@ -1151,7 +1151,7 @@ Exited Spec mode. You can start a new spec or continue with regular work.`,displ
|
|
|
1151
1151
|
`+`\uD83D\uDCC1 Spec preserved at: .blade/changes/${Z}/
|
|
1152
1152
|
`+`\uD83D\uDCA1 Resume later with: /spec load ${Z}
|
|
1153
1153
|
|
|
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
|
|
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 e1}from"zod";var a4=E({name:"GetSpecContext",displayName:"Get Spec Context",kind:"readonly",schema:e1.object({includeFiles:e1.boolean().optional().default(!0).describe("Whether to include file contents in the context"),includeSteering:e1.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.
|
|
1155
1155
|
|
|
1156
1156
|
## What's Included
|
|
1157
1157
|
|
|
@@ -1178,7 +1178,7 @@ You can now work on other tasks or start a new spec.`,displayContent:`✅ Exited
|
|
|
1178
1178
|
[File contents and steering docs follow...]
|
|
1179
1179
|
\`\`\`
|
|
1180
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
|
|
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 o4}from"zod";function v7($){switch($){case"requirements":return`## Requirements Phase Instructions
|
|
1182
1182
|
|
|
1183
1183
|
1. Use UpdateSpec to write requirements.md
|
|
1184
1184
|
2. Use EARS format:
|
|
@@ -1215,7 +1215,7 @@ You can now work on other tasks or start a new spec.`,displayContent:`✅ Exited
|
|
|
1215
1215
|
The spec has been marked as complete. Next steps:
|
|
1216
1216
|
1. The spec will be archived to .blade/archive/
|
|
1217
1217
|
2. Any spec deltas will be merged to .blade/specs/
|
|
1218
|
-
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 t4=E({name:"TransitionSpecPhase",displayName:"Transition Spec Phase",kind:"write",schema:o4.object({targetPhase:o4.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.
|
|
1219
1219
|
|
|
1220
1220
|
## Workflow Phases
|
|
1221
1221
|
|
|
@@ -1264,12 +1264,12 @@ After adding tasks, try transitioning again.`,displayContent:"❌ No tasks defin
|
|
|
1264
1264
|
|
|
1265
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}"
|
|
1266
1266
|
|
|
1267
|
-
`+
|
|
1267
|
+
`+v7(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 kb}from"zod";function T7($,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
1268
|
\uD83D\uDCA1 Consider transitioning to "${W}" phase using TransitionSpecPhase tool.`;switch($){case"proposal":return`
|
|
1269
1269
|
\uD83D\uDCDD Next: Define requirements in requirements.md using EARS format.`;case"requirements":return`
|
|
1270
1270
|
\uD83D\uDCDD Next: Create technical design in design.md (diagrams, API contracts).`;case"design":return`
|
|
1271
1271
|
\uD83D\uDCDD Next: Break down into tasks in tasks.md (atomic, with dependencies).`;case"tasks":return`
|
|
1272
|
-
\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 e4=E({name:"UpdateSpec",displayName:"Update Spec",kind:"write",schema:kb.object({fileType:kb.enum(["proposal","spec","requirements","design","tasks"]).describe("The type of spec file to update"),content:kb.string().min(1).describe("The content to write to the file"),append:kb.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.
|
|
1273
1273
|
|
|
1274
1274
|
## Available File Types
|
|
1275
1275
|
|
|
@@ -1309,7 +1309,7 @@ ${V}`:V}await Y.writeSpecFile(Z.name,w,J);let X=J.split(`
|
|
|
1309
1309
|
|
|
1310
1310
|
`+`\uD83D\uDCCA Stats: ${X} lines, ${O} characters
|
|
1311
1311
|
|
|
1312
|
-
`+
|
|
1312
|
+
`+T7(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 fb}from"zod";var $2={pending:"⏳ 待处理",in_progress:"\uD83D\uDD04 进行中",completed:"✅ 已完成",blocked:"\uD83D\uDEAB 已阻塞",skipped:"⏭️ 已跳过"},b2=E({name:"UpdateTaskStatus",displayName:"Update Task Status",kind:"write",schema:fb.object({taskId:fb.string().min(1).describe("The ID of the task to update"),status:fb.enum(["pending","in_progress","completed","blocked","skipped"]).describe("The new status for the task"),notes:fb.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.
|
|
1313
1313
|
|
|
1314
1314
|
## Task Statuses
|
|
1315
1315
|
|
|
@@ -1351,10 +1351,10 @@ ${Z.tasks.map((B)=>`- ${B.id}: ${B.title}`).join(`
|
|
|
1351
1351
|
\uD83C\uDF89 All tasks completed! Use /spec archive to archive this spec.`;return{success:!0,llmContent:`✅ Updated task "${Y.title}"
|
|
1352
1352
|
|
|
1353
1353
|
`+`\uD83D\uDCCB Task ID: ${w}
|
|
1354
|
-
`+`\uD83D\uDCCA Status: ${
|
|
1354
|
+
`+`\uD83D\uDCCA Status: ${$2[V]}
|
|
1355
1355
|
`+(W?`\uD83D\uDCDD Notes: ${W}
|
|
1356
1356
|
`:"")+`
|
|
1357
|
-
\uD83D\uDCC8 Progress: ${X.completed}/${X.total} tasks (${X.percentage}%)`+G,displayContent:`✅ ${Y.title}: ${
|
|
1357
|
+
\uD83D\uDCC8 Progress: ${X.completed}/${X.total} tasks (${X.percentage}%)`+G,displayContent:`✅ ${Y.title}: ${$2[V]}`,metadata:{taskId:w,title:Y.title,status:V,notes:W,progress:{completed:X.completed,total:X.total,percentage:X.percentage}}}}});import{z as k7}from"zod";var w2=E({name:"ValidateSpec",displayName:"Validate Spec",kind:"readonly",schema:k7.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.
|
|
1358
1358
|
|
|
1359
1359
|
## What's Validated
|
|
1360
1360
|
|
|
@@ -1376,7 +1376,7 @@ ${Z.tasks.map((B)=>`- ${B.id}: ${B.title}`).join(`
|
|
|
1376
1376
|
- Before marking spec as done
|
|
1377
1377
|
- To get improvement suggestions
|
|
1378
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
|
|
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 V2=[s4,e4,a4,t4,n4,b2,w2,r4];import{z as P$}from"zod";var f7=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.")}),I7=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(f7).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.')}),P7=P$.object({questions:P$.array(I7).min(1).max(4).describe("Questions to ask the user (1-4 questions)")}),Ib=E({name:"AskUserQuestion",displayName:"Ask User Question",kind:"readonly",schema:P7,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:
|
|
1380
1380
|
1. Gather user preferences or requirements
|
|
1381
1381
|
2. Clarify ambiguous instructions
|
|
1382
1382
|
3. Get decisions on implementation choices as you work
|
|
@@ -1387,7 +1387,7 @@ Usage notes:
|
|
|
1387
1387
|
- Use multiSelect: true to allow multiple answers to be selected for a question
|
|
1388
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
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
|
|
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 $w}from"zod";var bw=E({name:"Skill",displayName:"Skill",kind:"execute",schema:$w.object({skill:$w.string().describe('The skill name. E.g., "commit-message" or "code-review"'),args:$w.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
|
|
1391
1391
|
|
|
1392
1392
|
<skills_instructions>
|
|
1393
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.
|
|
@@ -1406,7 +1406,7 @@ Important:
|
|
|
1406
1406
|
<available_skills>
|
|
1407
1407
|
|
|
1408
1408
|
</available_skills>
|
|
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=
|
|
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=h7(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 h7($,b,w){return`# Skill: ${$}
|
|
1410
1410
|
|
|
1411
1411
|
You are now operating in the "${$}" skill mode. Follow the instructions below to complete the task.
|
|
1412
1412
|
|
|
@@ -1419,7 +1419,7 @@ ${b}
|
|
|
1419
1419
|
|
|
1420
1420
|
---
|
|
1421
1421
|
|
|
1422
|
-
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 g7}from"nanoid";import{z as O0}from"zod";import{nanoid as p7}from"nanoid";import o$ from"node:fs";import x7 from"node:os";import W2 from"node:path";var S0=y("Agent");class J0{static instance=null;sessionsDir;cache=new Map;constructor(){this.sessionsDir=W2.join(x7.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 W2.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,$),S0.debug(`Session saved: ${$.id}`)}catch(b){S0.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){S0.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 S0.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 S0.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)S0.info(`Cleaned up ${V} expired agent sessions`);return V}clearCache(){this.cache.clear()}}var X0=y("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||p7(),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 d7}from"nanoid";class ww{config;bladeConfig;constructor($,b){this.config=$;this.bladeConfig=b}async execute($){let b=Date.now(),w=$.subagentSessionId??d7();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 Ww from"node:fs";import Pb from"node:os";import m$ from"node:path";import u7 from"yaml";var Vw=[{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
|
|
1423
1423
|
|
|
1424
1424
|
You are a specialized code exploration agent. Your job is to **directly execute searches** using the tools available to you.
|
|
1425
1425
|
|
|
@@ -1486,17 +1486,17 @@ You are a software architect specializing in implementation planning.
|
|
|
1486
1486
|
**Risks**:
|
|
1487
1487
|
- [Potential issue and mitigation]
|
|
1488
1488
|
|
|
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
|
|
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 Q2($){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 Qw=y("Agent");class Z2{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
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(!
|
|
1492
|
-
`)[0]}function
|
|
1491
|
+
`)}`}loadFromDirectory($,b){if(!Ww.existsSync($))return;let w=Ww.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){Qw.warn(`Failed to load subagent config from ${W}:`,Q)}}}parseConfigFile($,b){let V=Ww.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=u7.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=Q2(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(Pb.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(Pb.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 Qw.debug(`\uD83D\uDCE6 Loaded ${W} subagents from standard locations`),W}loadBuiltinAgents(){for(let $ of Vw)this.subagents.set($.name,{...$,model:$.model||"inherit",source:"builtin"});Qw.debug(`Loaded ${Vw.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(Pb.homedir(),".claude","agents");return m$.join(process.cwd(),".claude","agents")}static getBladeAgentsDir($){if($==="user")return m$.join(Pb.homedir(),".blade","agents");return m$.join(process.cwd(),".blade","agents")}}var X$=new Z2;function m7($){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 c7($){return X$.getAllNames().includes($)}function i7(){let $=X$.getAllNames();return $.length>0?$.join(", "):"none (registry not initialized)"}function l7(){return`
|
|
1493
1493
|
## Task
|
|
1494
1494
|
|
|
1495
1495
|
Launch a new agent to handle complex, multi-step tasks autonomously.
|
|
1496
1496
|
|
|
1497
1497
|
The Task tool launches specialized agents (subprocesses) that autonomously handle complex tasks. Each agent type has specific capabilities and tools available to it.
|
|
1498
1498
|
|
|
1499
|
-
${
|
|
1499
|
+
${X$.getDescriptionsForPrompt()}
|
|
1500
1500
|
|
|
1501
1501
|
When using the Task tool, you must specify a subagent_type parameter to select which agent type to use.
|
|
1502
1502
|
|
|
@@ -1520,9 +1520,9 @@ Usage notes:
|
|
|
1520
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
|
|
1521
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.
|
|
1522
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.
|
|
1523
|
-
`.trim()}var
|
|
1523
|
+
`.trim()}var Zw=E({name:"Task",displayName:"Subagent Scheduler",kind:"readonly",isReadOnly:!0,schema:O0.object({subagent_type:O0.string().refine(c7,($)=>({message:`Invalid subagent type: "${$}". Available: ${i7()}`})).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 l7()},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:g7();try{let O=X$.getAllNames(),G=X$.getSubagent(w);if(!G)return{success:!1,llmContent:`Unknown subagent type: ${w}. Available types: ${O.join(", ")||"none"}`,displayContent:`❌ 未知的 subagent 类型: ${w}
|
|
1524
1524
|
|
|
1525
|
-
可用类型: ${O.join(", ")||"无"}`,error:{type:"execution_error",message:`Unknown subagent type: ${w}`}};if(Z)return
|
|
1525
|
+
可用类型: ${O.join(", ")||"无"}`,error:{type:"execution_error",message:`Unknown subagent type: ${w}`}};if(Z)return s7(Z,W,G,V,b);if(Q)return n7(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 ww(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
1526
|
...(截断)`:K.message;return{success:!0,llmContent:K.message,displayContent:`✅ Subagent 任务完成
|
|
1527
1527
|
|
|
1528
1528
|
`+`类型: ${w}
|
|
@@ -1539,15 +1539,15 @@ ${F}`,metadata:{subagent_type:w,description:V,duration:U,stats:K.stats,subagentS
|
|
|
1539
1539
|
`+`任务: ${V}
|
|
1540
1540
|
Agent ID: ${K.agentId||"N/A"}
|
|
1541
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=
|
|
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=m7(G);return{success:!1,llmContent:`Subagent execution error: ${G.message}`,displayContent:`❌ Subagent 执行异常
|
|
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
|
|
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 n7($,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 已启动
|
|
1545
1545
|
|
|
1546
1546
|
`+`Agent ID: ${Z}
|
|
1547
1547
|
`+`类型: ${$.name}
|
|
1548
1548
|
`+`任务: ${b}
|
|
1549
1549
|
|
|
1550
|
-
`+"\uD83D\uDCA1 使用 TaskOutput 工具获取结果",metadata:{agent_id:Z,subagent_type:$.name,description:b,background:!0,subagentSessionId:Z,subagentType:$.name,subagentStatus:"running"}}}function
|
|
1550
|
+
`+"\uD83D\uDCA1 使用 TaskOutput 工具获取结果",metadata:{agent_id:Z,subagent_type:$.name,description:b,background:!0,subagentSessionId:Z,subagentType:$.name,subagentStatus:"running"}}}function s7($,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: ${$}
|
|
1551
1551
|
|
|
1552
1552
|
会话不存在或已过期`,error:{type:"execution_error",message:`Agent session not found: ${$}`}};if(Q.isRunning($))return{success:!1,llmContent:`Cannot resume agent ${$}: still running`,displayContent:`❌ 无法恢复 Agent: ${$}
|
|
1553
1553
|
|
|
@@ -1558,7 +1558,7 @@ Agent 仍在运行中,我会使用 TaskOutput 获取结果`,error:{type:"execu
|
|
|
1558
1558
|
`+`类型: ${w.name}
|
|
1559
1559
|
`+`任务: ${V}
|
|
1560
1560
|
|
|
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
|
|
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 hb}from"zod";var Yw=E({name:"TaskOutput",displayName:"Task Output",kind:"readonly",schema:hb.object({task_id:hb.string().min(1).describe("The task ID to get output from"),block:hb.boolean().default(!0).describe("Whether to wait for completion"),timeout:hb.number().min(0).max(600000).default(30000).describe("Max wait time in ms")}),description:{short:"Retrieves output from a running or completed task",long:`
|
|
1562
1562
|
- Retrieves output from a running or completed task (background shell, agent, or remote session)
|
|
1563
1563
|
- Takes a task_id parameter identifying the task
|
|
1564
1564
|
- Returns the task output along with status information
|
|
@@ -1566,11 +1566,11 @@ Agent 仍在运行中,我会使用 TaskOutput 获取结果`,error:{type:"execu
|
|
|
1566
1566
|
- Use block=false for non-blocking check of current status
|
|
1567
1567
|
- Task IDs can be found using the /tasks command
|
|
1568
1568
|
- Works with all task types: background shells, async agents, and remote sessions
|
|
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
|
|
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 Y2(w,V,W);let Q=A$.getInstance(),Z=M$.getInstance();if(Q.getProcess(w))return Y2(w,V,W);if(Z.getAgent(w))return r7(w,V,W);return{success:!1,llmContent:`Unknown task ID: ${w}.`,displayContent:`❌ 未知的任务 ID: ${w}
|
|
1570
1570
|
|
|
1571
1571
|
任务 ID 格式:
|
|
1572
1572
|
- bash_xxx: 后台 shell
|
|
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
|
|
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 Y2($,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 a7($,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=`${J2(Q.status)} TaskOutput(${$}) - Shell
|
|
1574
1574
|
`+`状态: ${Q.status}
|
|
1575
1575
|
`+`命令: ${Q.command}
|
|
1576
1576
|
`+(Q.pid?`PID: ${Q.pid}
|
|
@@ -1579,7 +1579,7 @@ Agent 仍在运行中,我会使用 TaskOutput 获取结果`,error:{type:"execu
|
|
|
1579
1579
|
stdout:
|
|
1580
1580
|
${Q.stdout}`:"")+(Q.stderr?`
|
|
1581
1581
|
stderr:
|
|
1582
|
-
${Q.stderr}`:"");return{success:!0,llmContent:Z,displayContent:J,metadata:Z}}async function
|
|
1582
|
+
${Q.stderr}`:"");return{success:!0,llmContent:Z,displayContent:J,metadata:Z}}async function r7($,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=`${J2(W.status)} TaskOutput(${$}) - Agent
|
|
1583
1583
|
`+`状态: ${W.status}
|
|
1584
1584
|
`+`类型: ${W.subagentType}
|
|
1585
1585
|
`+`描述: ${W.description}
|
|
@@ -1588,12 +1588,12 @@ ${Q.stderr}`:"");return{success:!0,llmContent:Z,displayContent:J,metadata:Z}}asy
|
|
|
1588
1588
|
`:"")+(W.result?.message?`
|
|
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
|
|
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 a7($,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 J2($){switch($){case"running":return"⏳";case"completed":case"exited":return"✅";case"failed":case"error":return"❌";case"killed":case"cancelled":return"✂️";default:return"❓"}}import{z as X2}from"zod";var o7=X2.object({serverName:X2.string().optional().describe("Optional: Filter resources by MCP server name. If not provided, lists resources from all connected servers.")}),xb=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
1592
|
Resources can include files, database records, API endpoints, or any other data sources
|
|
1593
1593
|
that MCP servers expose for reading.
|
|
1594
1594
|
|
|
1595
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
|
|
1596
|
+
access their contents.`,usageNotes:["List all resources: ListMcpResources({})",'List resources from specific server: ListMcpResources({ serverName: "my-server" })']},schema:o7,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
1597
|
|
|
1598
1598
|
Errors:
|
|
1599
1599
|
${W.join(`
|
|
@@ -1604,16 +1604,16 @@ ${W.join(`
|
|
|
1604
1604
|
|
|
1605
1605
|
`),Z=`Found ${V.length} resource(s) from ${new Set(V.map((Y)=>Y.serverName)).size} server(s)`;return{success:!0,llmContent:`${Z}
|
|
1606
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
|
|
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 Jw}from"zod";var t7=Jw.object({uri:Jw.string().describe("The URI of the MCP resource to read"),serverName:Jw.string().optional().describe("Optional: The name of the MCP server that provides this resource. If not provided, will search all connected servers.")}),pb=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
1608
|
Resources are identified by their URI, which can be obtained using the ListMcpResources tool.
|
|
1609
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:
|
|
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:t7,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
1611
|
|
|
1612
1612
|
Errors:
|
|
1613
1613
|
${Q.join(`
|
|
1614
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
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
|
|
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 G2}from"zod";import{randomUUID as e7}from"crypto";import*as M0 from"fs/promises";import*as db from"path";class G0{static instances=new Map;todos=[];filePath;loaded=!1;constructor($,b){this.filePath=db.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||e7(),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 M0.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 M0.mkdir(db.dirname(this.filePath),{recursive:!0,mode:493}),await M0.writeFile(this.filePath,JSON.stringify(this.todos,null,2),"utf-8")}catch($){throw console.error("保存 TODO 列表失败:",$),$}}}import{z as y0}from"zod";var O2=y0.object({id:y0.string().optional(),content:y0.string().min(1,"Content cannot be empty"),status:y0.enum(["pending","in_progress","completed"]),activeForm:y0.string().min(1,"ActiveForm cannot be empty"),priority:y0.enum(["high","medium","low"]).default("medium")});function Xw($){let{sessionId:b,configDir:w}=$;return E({name:"TodoWrite",displayName:"Todo Write",kind:"readonly",schema:G2.object({todos:G2.array(O2).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.
|
|
1617
1617
|
It also helps the user understand the progress of the task and overall progress of their requests.
|
|
1618
1618
|
|
|
1619
1619
|
## When to Use This Tool
|
|
@@ -1674,9 +1674,9 @@ NOTE that you should not use this tool if there is only one trivial task to do.
|
|
|
1674
1674
|
- activeForm: "Fixing authentication bug"
|
|
1675
1675
|
|
|
1676
1676
|
When in doubt, use this tool. Being proactive with task management demonstrates attentiveness and ensures you complete all requirements successfully.
|
|
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
|
|
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=$V(X),G=bV(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 $V($){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 bV($,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
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
|
|
1679
|
+
`)}import{z as O$}from"zod";import{isPlainObject as B2}from"lodash-es";function K2($){if(!B2($))return;let b=$;return typeof b.name==="string"?b.name:void 0}function wV($){if($ instanceof Error)return $.message;if(typeof $==="string")return $;if(B2($)){let b=$;if(typeof b.message==="string")return b.message}return String($)}var Gw=E({name:"WebFetch",displayName:"Web Fetch",kind:"readonly",schema:O$.object({url:O$.string().url().describe("URL to request"),method:O$.enum(["GET","POST","PUT","DELETE","HEAD"]).default("GET").describe("HTTP method"),extract_content:O$.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:O$.object({with_generated_alt:O$.boolean().default(!1).describe("Generate alt text for images"),with_links_summary:O$.boolean().default(!1).describe("Include summary of all links"),wait_for_selector:O$.string().optional().describe("Wait for specific CSS selector to load")}).optional().describe("Jina Reader advanced options (only used when extract_content is true)"),headers:O$.record(O$.string()).optional().describe("Request headers (optional)"),body:O$.string().optional().describe("Request body (optional)"),timeout:g.timeout(1000,120000,30000),follow_redirects:O$.boolean().default(!0).describe("Follow redirects"),max_redirects:O$.number().int().min(0).max(10).default(5).describe("Maximum redirect hops"),return_headers:O$.boolean().default(!1).describe("Return response headers")}),description:{short:"Fetches content from a specified URL and processes it using an AI model",long:`
|
|
1680
1680
|
- Fetches content from a specified URL and processes it using an AI model
|
|
1681
1681
|
- Takes a URL and a prompt as input
|
|
1682
1682
|
- Fetches the URL content, converts HTML to markdown
|
|
@@ -1693,29 +1693,29 @@ Usage notes:
|
|
|
1693
1693
|
- Results may be summarized if the content is very large
|
|
1694
1694
|
- Includes a self-cleaning 15-minute cache for faster responses when repeatedly accessing the same URL
|
|
1695
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.
|
|
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
|
|
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 JV({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:Ow(D,N,!1),metadata:N}}catch{B?.("⚠️ Jina Reader 失败,使用标准方式获取")}B?.(`发送 ${V} 请求到: ${w}`);let A=Date.now(),K=await VV({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:Ow(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:Ow(K,F,!1),metadata:F}}catch(A){if(K2(A)==="AbortError")return{success:!1,llmContent:"Request aborted",displayContent:"⚠️ 请求被用户中止",error:{type:"execution_error",message:"操作被中止"}};let K=wV(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 VV($){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"&&!YV(K,"content-type"))K["Content-Type"]="application/json";let U=await q2(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=ZV(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=C2(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 Ow($,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
1697
|
响应时间: ${Z}ms`,J+=`
|
|
1698
1698
|
内容长度: ${Y} 字节`,b.content_type)J+=`
|
|
1699
1699
|
Content-Type: ${b.content_type}`;if($.redirected&&b.final_url&&b.final_url!==V){if(J+=`
|
|
1700
1700
|
最终URL: ${b.final_url}`,b.redirect_count)J+=`
|
|
1701
|
-
重定向次数: ${b.redirect_count}`}let X=
|
|
1701
|
+
重定向次数: ${b.redirect_count}`}let X=WV($.body,$.content_type);if(X)J+=`
|
|
1702
1702
|
响应内容:
|
|
1703
|
-
${X}`;return J}function
|
|
1703
|
+
${X}`;return J}function WV($,b){if(!$)return"(空响应)";if(QV(b,$))return"[binary content omitted]";let w=$.trim();if(!w)return"(仅包含空白字符)";return w.length>800?`${w.slice(0,800)}...`:w}function QV($,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 q2($,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(K2(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 ZV($,b){try{return new URL($,b).toString()}catch{return $}}function C2($){let b={};return $.forEach((w,V)=>{b[V.toLowerCase()]=w}),b}function YV($,b){let w=b.toLowerCase();return Object.keys($).some((V)=>V.toLowerCase()===w)}async function JV($){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 q2(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=XV(X);return Q?.(`✅ Jina Reader 成功提取内容 (${O.content.length} 字符)`),{status:J.status,status_text:J.statusText,headers:C2(J.headers),body:OV(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 XV($){let b=$.split(`
|
|
1704
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
|
|
1705
|
+
`).trim();return{title:w||"Untitled",sourceUrl:V||"",content:Q||$}}function OV($){let b="";if($.title)b+=`# ${$.title}
|
|
1706
1706
|
|
|
1707
1707
|
`;if($.sourceUrl)b+=`**Source**: ${$.sourceUrl}
|
|
1708
1708
|
|
|
1709
1709
|
`;return b+=`---
|
|
1710
1710
|
|
|
1711
|
-
`,b+=$.content,b}import{ProxyAgent as
|
|
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
|
|
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
|
|
1711
|
+
`,b+=$.content,b}import{ProxyAgent as RV,fetch as EV}from"undici";import{z as z0}from"zod";import{LRUCache as A2}from"lru-cache";import GV from"node:crypto";class U2{cache;config;hits=0;misses=0;constructor($){this.config={maxSize:$?.maxSize??100,ttl:$?.ttl??3600000,enabled:$?.enabled??!0},this.cache=new A2({max:this.config.maxSize,ttl:this.config.ttl,updateAgeOnGet:!0,updateAgeOnHas:!1})}generateKey($,b){let w=b.toLowerCase().trim(),V=GV.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 A2({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 BV=new U2;function F2(){return BV}function KV($){return $.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,'"').replace(/'/g,"'")}function H2($){let b=KV($).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 qV($){if(!$.FirstURL||!$.Text)return null;let{title:b,snippet:w}=H2($.Text);return{title:b,snippet:w,url:$.FirstURL,display_url:wb($.FirstURL),source:Vb($.FirstURL)}}function _2($){let b=[];for(let w of $){if(w.Topics&&w.Topics.length>0){b.push(..._2(w.Topics));continue}if(w.FirstURL&&w.Text){let{title:V,snippet:W}=H2(w.Text);b.push({title:V,snippet:W,url:w.FirstURL,display_url:wb(w.FirstURL),source:Vb(w.FirstURL)})}}return b}function CV($){let b=$,w=(b.Results??[]).map((W)=>qV(W)).filter((W)=>W!==null),V=_2(b.RelatedTopics??[]);return[...w,...V]}var AV={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:CV,getHeaders:()=>({Accept:"application/json, text/plain;q=0.9","User-Agent":"Blade-AI-WebSearch/1.0"})};function UV($){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 R2=["https://searx.be","https://search.ononoki.org","https://searx.tiekoetter.com","https://searx.work"];function FV($){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:UV,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 HV($){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 _V(){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 HV(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 E2(){let $=[];return $.push(_V()),$.push(AV),$.push(...R2.map(FV)),$}function L2(){return 2+R2.length}var LV=15000,DV=8,Wb={maxRetries:3,baseDelay:1000,maxDelay:8000};function jV(){let $=process.env.HTTPS_PROXY||process.env.HTTP_PROXY||process.env.https_proxy||process.env.http_proxy;if($)try{return new RV($)}catch(b){console.warn(`Invalid proxy URL: ${$}`)}return}async function NV($,b,w,V,W){let Q=new AbortController,Z=setTimeout(()=>Q.abort(),w),Y=()=>Q.abort();V?.addEventListener("abort",Y);try{return await EV($,{...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 SV($,b,w,V,W,Q){let Z=null;for(let Y=0;Y<Wb.maxRetries;Y++)try{return await NV($,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 MV($,b,w,V,W,Q){let Z=F2(),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 SV(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 yV($,b,w,V){let W=E2(),Q=jV(),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 MV(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
1714
|
${Z.join(`
|
|
1715
|
-
`)}`)}}throw Error("No search providers available")}function
|
|
1715
|
+
`)}`)}}throw Error("No search providers available")}function zV($){try{return new URL($).hostname.toLowerCase()}catch{return null}}function vV($){return $.trim().toLowerCase()}function D2($){if(!$||$.length===0)return[];return $.map(vV).filter(Boolean)}function j2($,b){return $===b||$.endsWith(`.${b}`)}function TV($,b,w){return $.filter((V)=>{let W=zV(V.url);if(!W)return!1;if(w.length>0&&w.some((Q)=>j2(W,Q)))return!1;if(b.length>0&&!b.some((Q)=>j2(W,Q)))return!1;return!0})}function kV($,b,w,V){let W=`\uD83D\uDD0E WebSearch("${$}") via ${V} - 返回 ${b.length}/${w} 条结果`,Q=b.map((Z,Y)=>`${Y+1}. ${Z.title}
|
|
1716
1716
|
${Z.display_url}
|
|
1717
1717
|
${Z.snippet}`);return[W,...Q].join(`
|
|
1718
|
-
`)}function
|
|
1718
|
+
`)}function fV($){let b=$.trim().toLowerCase();return b.length>80?b.slice(0,80):b}var Bw=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:`
|
|
1719
1719
|
- Search the web and use the results to inform responses
|
|
1720
1720
|
- Provides up-to-date information for current events and recent data
|
|
1721
1721
|
- Returns search result information formatted as search result blocks, including links as markdown hyperlinks
|
|
@@ -1743,11 +1743,11 @@ Usage notes:
|
|
|
1743
1743
|
IMPORTANT - Use the correct year in search queries:
|
|
1744
1744
|
- You MUST use the current year when searching for recent information, documentation, or current events.
|
|
1745
1745
|
- Example: If the user asks for "latest React docs", search for "React documentation 2025", NOT "React documentation 2024"
|
|
1746
|
-
`},async execute($,b){let{query:w}=$,V=
|
|
1746
|
+
`},async execute($,b){let{query:w}=$,V=D2($.allowed_domains),W=D2($.blocked_domains),{updateOutput:Q}=b,Z=b.signal??new AbortController().signal;Q?.(`\uD83D\uDD0E Searching: "${w}" (${L2()} providers available)`);try{let{results:Y,providerName:J}=await yV(w,LV,Z,Q),X=TV(Y,V,W),O=X.slice(0,DV),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:kV(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:${fV($.query)}`,abstractPermissionRule:()=>"search:*"});async function IV(){try{return await c.getInstance().getAvailableTools()}catch($){return console.warn("MCP协议工具加载失败:",$),[]}}async function Kw($){let b=$?.sessionId||`session_${Date.now()}`,w=$?.configDir||S2.join(N2.homedir(),".blade"),V=[P1,I1,x1,Sb,m1,l1,s1,r1,Gw,Bw,Zw,Yw,Xw({sessionId:b,configDir:w}),p1,u1,...V2,Ib,bw,xb,pb],W=await IV();return[...V,...W]}import{EventEmitter as dV}from"events";import{nanoid as PV}from"nanoid";class qw{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 hV}from"nanoid";function xV($){return typeof $==="object"&&$!==null&&!Array.isArray($)}class Cw{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_${hV()}`,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}
|
|
1747
1747
|
|
|
1748
1748
|
---
|
|
1749
1749
|
**Hook Context:**
|
|
1750
|
-
${Q.additionalContext}`}if(Q.modifiedOutput!==void 0){let Z=Q.modifiedOutput;if(
|
|
1750
|
+
${Q.additionalContext}`}if(Q.modifiedOutput!==void 0){let Z=Q.modifiedOutput;if(xV(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 Aw=y("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){Aw.debug(`获取文件锁: ${$}`);try{let w=await b();return Aw.debug(`释放文件锁: ${$}`),w}catch(w){throw Aw.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 pV from"node:os";import Uw 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=Uw.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 Uw.join(pV.homedir(),$.slice(1));return Uw.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 ub{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=ub.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=y("Execution");class Fw{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 Hw{name="permission";permissionChecker;sessionApprovals;defaultPermissionMode;constructor($,b,w){this.permissionChecker=new ub($),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=ub.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
1751
|
${G.join(`
|
|
1752
1752
|
`)}
|
|
1753
1753
|
|
|
@@ -1755,7 +1755,7 @@ If access is required, add an explicit allow rule in permissions.`);return}if(Z.
|
|
|
1755
1755
|
${G.join(`
|
|
1756
1756
|
`)}
|
|
1757
1757
|
|
|
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
|
|
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 _w{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
1759
|
`);if(Y.length<=W)return Z;return`${Y.slice(0,W).join(`
|
|
1760
1760
|
`)}
|
|
1761
1761
|
... (还有 ${Y.length-W} 行)`};return`**变更前:**
|
|
@@ -1776,19 +1776,19 @@ ${w}
|
|
|
1776
1776
|
${Z}
|
|
1777
1777
|
\`\`\`
|
|
1778
1778
|
|
|
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
|
|
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 Rw{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 Ew{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 gb extends dV{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 Hw(w,this.sessionApprovals,V);this.stages=[new Fw(this.registry),W,new qw,new _w(this.sessionApprovals,W.getPermissionChecker(),b.canUseTool),new Rw,new Cw,new Ew]}async execute($,b,w){let V=Date.now(),W=this.generateExecutionId(),Q=new _1($,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}
|
|
1780
1780
|
|
|
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(`
|
|
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 uV}from"events";class Qb extends uV{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 gV=[/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 mV($){return gV.some((b)=>b.test($))}function cV($){if($.supportsThinking!==void 0)return{supportsThinking:$.supportsThinking,thinkingBudget:$.thinkingBudget};return{supportsThinking:mV($.model),thinkingBudget:void 0}}function M2($){return cV($).supportsThinking}import z2 from"fast-glob";import*as v0 from"fs/promises";import*as v2 from"path";import*as mb 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 mb.access(w)}catch(V){throw new K0(`Path not found: ${$}`,"PATH_NOT_FOUND")}return w}static async resolveSymlink($,b){try{let w=await mb.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 y$=y("Prompts");function cb($){return $ instanceof Map}class Lw{fileCache=new Map;options;constructor($){this.options={maxFileSize:1048576,maxLines:2000,maxTokens:32000,...$},y$.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[];y$.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 y$.warn(`Failed to process @${Z.path}:`,Y),{type:"error",path:Z.path,content:"",error:Y}}})}async processOne($){if($.isGlob)return y$.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 v0.stat(w)).isDirectory())return y$.debug(`Processing directory: ${$.path}`),await this.renderDirectoryTree(w,$.path);return y$.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 y$.debug(`Cache hit: ${b}`),this.formatFileAttachment(b,V.content,w);let W=await v0.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 v0.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
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
1783
|
`);let O=Array.from({length:X-Y},(B,q)=>Y+q+1);W=W.split(`
|
|
1784
1784
|
`).map((B,q)=>`${O[q]}: ${B}`).join(`
|
|
1785
1785
|
`),Z={start:w.start,end:X}}else if(V.length>this.options.maxLines)W=V.slice(0,this.options.maxLines).join(`
|
|
1786
1786
|
`),W+=`
|
|
1787
1787
|
|
|
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
|
|
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 z2("**/*",{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)"};y$.debug(`Found ${w.length} files in directory: ${b}`);let V=this.buildFileTree(w),W=this.printTree(V,b),Q=500,Z=w.length>Q?`
|
|
1789
1789
|
|
|
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&&
|
|
1791
|
-
`)}async processGlob($){let b=await
|
|
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&&cb(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=cb(Z[1]),X=cb(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=cb(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 z2($,{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: ${$}`};y$.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=v2.join(this.options.cwd,X);try{let G=await v0.readFile(O,"utf-8"),B=G.split(`
|
|
1792
1792
|
`),q=200,A=G,K=!1;if(B.length>200)A=B.slice(0,200).join(`
|
|
1793
1793
|
`),A+=`
|
|
1794
1794
|
|
|
@@ -1797,8 +1797,8 @@ ${X.content}`).join(`
|
|
|
1797
1797
|
|
|
1798
1798
|
`),J=b.length>w?`
|
|
1799
1799
|
|
|
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)
|
|
1801
|
-
`);try{let V=await this.attachmentCollector.collect(w);if(V.length===0)return $;
|
|
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)y$.debug(`Cleared ${b} expired cache entries`)}clearCache(){this.fileCache.clear(),y$.debug("Cleared all cache")}getCacheStats(){return{size:this.fileCache.size,keys:Array.from(this.fileCache.keys())}}}var ib=y("Agent");class Dw{attachmentCollector;constructor($){this.attachmentCollector=new Lw({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 $;ib.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 ib.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+=`
|
|
1802
1802
|
|
|
1803
1803
|
<system-reminder>
|
|
1804
1804
|
`,V+=`The following files were mentioned with @ syntax:
|
|
@@ -1809,7 +1809,7 @@ ${X.content}`).join(`
|
|
|
1809
1809
|
|
|
1810
1810
|
⚠️ Some files could not be loaded:
|
|
1811
1811
|
`,V+=w.join(`
|
|
1812
|
-
`);return V}async processAtMentions($){try{let b=await this.attachmentCollector.collect($);if(b.length===0)return $;return
|
|
1812
|
+
`);return V}async processAtMentions($){try{let b=await this.attachmentCollector.collect($);if(b.length===0)return $;return ib.debug(`✅ Processed ${b.length} @ file mentions`),this.appendAttachments($,b)}catch(b){return ib.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+=`
|
|
1813
1813
|
|
|
1814
1814
|
<system-reminder>
|
|
1815
1815
|
`,W+=`The following files were mentioned with @ syntax:
|
|
@@ -1820,20 +1820,20 @@ ${X.content}`).join(`
|
|
|
1820
1820
|
|
|
1821
1821
|
⚠️ Some files could not be loaded:
|
|
1822
1822
|
`,W+=V.join(`
|
|
1823
|
-
`);return W}}var D$=
|
|
1823
|
+
`);return W}}var D$=y("Agent");class jw{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.
|
|
1824
1824
|
|
|
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($)+`
|
|
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 f2 from"crypto";import{nanoid as k2}from"nanoid";class Nw{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 Sw{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 Mw{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 T2 from"node:path";import*as lb from"node:fs";import{createReadStream as iV}from"node:fs";import*as W$ from"node:fs/promises";import*as yw from"node:path";import{createInterface as lV}from"node:readline";class G${filePath;constructor($){this.filePath=$}async append($){try{await W$.mkdir(yw.dirname(this.filePath),{recursive:!0,mode:493});let b=JSON.stringify($)+`
|
|
1826
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(`
|
|
1827
1827
|
`)+`
|
|
1828
|
-
`;await W$.appendFile(this.filePath,b,"utf-8")}catch(b){throw console.error(`[JSONLStore] 批量追加写入失败: ${this.filePath}`,b),b}}async readAll(){try{if(!
|
|
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(!
|
|
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(`❌ 没有可用的模型配置
|
|
1828
|
+
`;await W$.appendFile(this.filePath,b,"utf-8")}catch(b){throw console.error(`[JSONLStore] 批量追加写入失败: ${this.filePath}`,b),b}}async readAll(){try{if(!lb.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(!lb.existsSync(this.filePath)){b();return}let V=iV(this.filePath,"utf-8"),W=lV({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(!lb.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 zw{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:N4(this.projectPath),version:this.version,data:w}}async ensureSessionCreated($,b){let w=C$(this.projectPath,$),V=new G$(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 G$(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 G$(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 G$(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 G$(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 G$(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 G$(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 G$(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 G$(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 G$(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=T2.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 S4()}}class nb{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 Mw(this.options.storage.maxMemorySize),this.persistent=new zw(process.cwd(),100),this.cache=new Sw(this.options.storage.cacheSize,300000),this.compressor=new Nw,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 k2()}generateMessageId(){return k2()}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 f2.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 vw{chatService;contextManager;memoryAdapter;constructor($,b){this.chatService=$,this.contextManager=b||new nb,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 I2=y("Agent");class Tw{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){Kb("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 I2.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 I2.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 sV($){if(typeof $==="string")return $;try{return JSON.parse(JSON.stringify($))}catch{return String($)}}var H=y("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 gb($,{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=M2($),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=$.maxContextTokens??128000;this.currentModelMaxContextTokens=Q,this.chatService=await Bb({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 vw(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(`❌ 没有可用的模型配置
|
|
1831
1831
|
|
|
1832
1832
|
`+`请先使用以下命令添加模型:
|
|
1833
1833
|
`+` /model add
|
|
1834
1834
|
|
|
1835
1835
|
`+`或运行初始化向导:
|
|
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
|
|
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 Dw(process.cwd()),this.streamHandler=new Tw(()=>this.chatService),this.compactionHandler=new jw(()=>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=`
|
|
1837
1837
|
|
|
1838
1838
|
<approved-plan>
|
|
1839
1839
|
${O}
|
|
@@ -1846,7 +1846,7 @@ IMPORTANT: Execute according to the approved plan above. Follow the steps exactl
|
|
|
1846
1846
|
${B}
|
|
1847
1847
|
</approved-plan>
|
|
1848
1848
|
|
|
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
|
|
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 E0({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 E0({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}
|
|
1850
1850
|
|
|
1851
1851
|
---
|
|
1852
1852
|
|
|
@@ -1854,13 +1854,13 @@ ${V}`:W;return this.executeLoop($,b,w,Q)}async*runLoopStream($,b,w){let V=b.syst
|
|
|
1854
1854
|
|
|
1855
1855
|
---
|
|
1856
1856
|
|
|
1857
|
-
${V}`:W;return yield*this.executeLoopStream($,b,w,Q)}async buildSystemPromptOnDemand(){let $=this.runtimeOptions.systemPrompt,b=this.runtimeOptions.appendSystemPrompt;return(await
|
|
1857
|
+
${V}`:W;return yield*this.executeLoopStream($,b,w,Q)}async buildSystemPromptOnDemand(){let $=this.runtimeOptions.systemPrompt,b=this.runtimeOptions.appendSystemPrompt;return(await E0({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=Lb(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
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)。如需启用,请调整配置:
|
|
1859
1859
|
`+` • CLI 参数: blade --max-turns -1
|
|
1860
1860
|
`+` • 配置文件: ~/.blade/config.json 中设置 "maxTurns": -1
|
|
1861
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
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(
|
|
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(Kb("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
1864
|
========== LLM 返回 ==========`),H.debug("Content:",j.content),H.debug("Tool Calls:",JSON.stringify(j.toolCalls,null,2)),H.debug("当前权限模式:",b.permissionMode),H.debug(`================================
|
|
1865
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?`
|
|
1866
1866
|
|
|
@@ -1870,15 +1870,15 @@ ${m.continueReason}
|
|
|
1870
1870
|
|
|
1871
1871
|
<system-reminder>
|
|
1872
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.
|
|
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:
|
|
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:nV();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
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
|
|
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,$1=((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:$1,subagentSummary:typeof e.subagentSummary==="string"?e.subagentSummary:void 0}:void 0;B=await m.saveToolResult(b.sessionId,L.id,L.function.name,R.success?sV(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
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
|
|
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 E0({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 Kw({sessionId:"default",configDir:h2.join(P2.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||{},b=new Set(Object.keys($));for(let W of this.config.inProcessMcpServerNames||[])b.add(W);if(b.size===0){H.debug("\uD83D\uDCE6 No MCP servers configured");return}let w=c.getInstance();for(let[W,Q]of Object.entries($)){if(Q.disabled){H.debug(`⏭️ MCP server "${W}" is disabled, skipping`);continue}try{H.debug(`\uD83D\uDD0C Connecting to MCP server: ${W}`),await w.registerServer(W,Q),H.debug(`✅ MCP server "${W}" connected`)}catch(Z){H.warn(`⚠️ MCP server "${W}" connection failed:`,Z)}}let V=await w.getAvailableToolsByServerNames(Array.from(b));if(V.length>0)this.executionPipeline.getRegistry().registerAll(V),H.debug(`✅ Registered ${V.length} MCP tools`),H.debug(`[MCP Tools] ${V.map((W)=>W.name).join(", ")}`);else H.debug("\uD83D\uDCE6 No MCP tools available")}catch($){H.warn("Failed to register MCP tools:",$)}}async loadSubagents(){if(X$.getAllNames().length>0){H.debug(`\uD83D\uDCE6 Subagents already loaded: ${X$.getAllNames().join(", ")}`);return}try{let $=X$.loadFromStandardLocations();if($>0)H.debug(`✅ Loaded ${$} subagents: ${X$.getAllNames().join(", ")}`);else H.debug("\uD83D\uDCE6 No subagents configured")}catch($){H.warn("Failed to load subagents:",$)}}async discoverSkills(){try{let $=await Eb({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 rV}from"node:child_process";import x2 from"node:fs";import p2 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=rV(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=p2.resolve(b,Z);try{if(x2.statSync(Y).isFile()){let X=x2.readFileSync(Y,"utf-8"),G=`\`\`\`${p2.extname(Z).slice(1)||"text"}
|
|
1878
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
|
|
1879
|
+
\`\`\``;W=W.replace(Q,G)}}catch{}}return W}hasDynamicContent($){return{hasArgs:/\$ARGUMENTS|\$\d/.test($),hasBashEmbeds:/!`[^`]+`/.test($),hasFileRefs:/@[\w./-]+(?:\/[\w./-]+|\.[\w]+)/.test($)}}}import kw from"node:fs";import u2 from"node:os";import i$ from"node:path";import aV from"node:fs";import d2 from"node:path";import oV from"gray-matter";class Yb{parse($,b,w,V){try{let W=aV.readFileSync($,"utf-8"),{data:Q,content:Z}=oV(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=d2.relative(b,$).split(d2.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(!kw.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=u2.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 kw.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(!kw.existsSync(w.path))continue;if((await this.scanDirectory(w.path)).length>0)return!0}return!1}getCommandDirs($){let b=u2.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 z${static instance;commands=new Map;loader=new Jb;executor=new Zb;initialized=!1;workspaceRoot="";lastDiscoveryResult=null;static getInstance(){if(!z$.instance)z$.instance=new z$;return z$.instance}static resetInstance(){z$.instance=new z$}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
1880
|
|
|
1881
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
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};
|
|
1883
|
+
(${Q} of ${w} commands shown due to character budget)`;return{text:V,includedCount:Q,totalCount:w}}}import{InMemoryTransport as tV}from"@modelcontextprotocol/sdk/inMemory.js";import{McpServer as eV}from"@modelcontextprotocol/sdk/server/mcp.js";function g2($,b,w,V){return{name:$,description:b,schema:w,handler:V}}async function m2($){let b=new eV({name:$.name,version:$.version});for(let V of $.tools)b.tool(V.name,V.description,V.schema,async(W)=>{return V.handler(W)});let w=async()=>{let[V,W]=tV.createLinkedPair();return await b.connect(W),V};return{name:$.name,version:$.version,createClientTransport:w,server:b}}import{execSync as s2}from"node:child_process";import*as Q$ from"node:fs/promises";import{homedir as QW}from"node:os";import*as T0 from"node:path";import*as sb from"node:fs/promises";import*as n2 from"node:path";import{z as S}from"zod";var $W=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"}),bW=S.string().regex(/^\d+\.\d+\.\d+(-[\w.]+)?(\+[\w.]+)?$/,{message:"Version must be a valid semantic version (e.g., 1.0.0)"}),wW=S.object({name:S.string().min(1,"Author name is required"),email:S.string().email().optional(),url:S.string().url().optional()}),i2=S.object({name:$W,description:S.string().min(1,"Description is required").max(500,"Description must be at most 500 characters"),version:bW,author:wW.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()}),c2=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()}),VW=S.union([S.object({mcpServers:S.record(c2)}),S.record(c2)]);function l2($){return VW.safeParse($)}var WW=[{dir:".blade-plugin",source:"blade"},{dir:".claude-plugin",source:"claude"}];async function $0($){for(let{dir:b,source:w}of WW){let V=n2.join($,b,"plugin.json");try{await sb.access(V)}catch{continue}try{let W=await sb.readFile(V,"utf-8"),Q=JSON.parse(W),Z=i2.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 rb($){try{return await $0($)!==null}catch{return!1}}class ab{userPluginsDir;constructor($){this.userPluginsDir=$||T0.join(QW(),".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=T0.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{s2(`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 rb(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=T0.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=T0.join(this.userPluginsDir,$);try{await Q$.access(b)}catch{return{success:!1,pluginName:$,error:`Plugin "${$}" not found at ${b}`}}let w=T0.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{s2(`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 fw=null;function r2($){if(!fw)fw=new ab($);return fw}import*as U$ from"node:fs/promises";import{homedir as ZW}from"node:os";import*as s from"node:path";import a2 from"gray-matter";function k0($,b){return`${$}:${b}`}function ob($,b){return`${$}__${b}`}class f0{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}=a2(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=k0(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}=a2(V),Z=s.relative(b,$),Y=s.basename(Z,".md"),J=W.name||Y,X=k0(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 Hb(Y,"project");if(J.success&&J.content){let X=J.content.metadata.name,O=k0(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=l2(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=ob(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=ZW();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 f0;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=f0.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 tb(){return l$.getInstance()}class Xb{hookManager;mcpRegistry;constructor(){this.hookManager=r.getInstance(),this.mcpRegistry=c.getInstance()}clearAllPluginResources(){N$().clearPluginSkills(),X$.clearPluginAgents(),u.debug("Cleared all plugin resources from subsystems")}async integrateAll(){let b=tb().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)X$.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 o2(){return new Xb().integrateAll()}function t2(){new Xb().clearAllPluginResources()}import{nanoid as YW}from"nanoid";var Z$=y("Agent");function Iw($){return"createClientTransport"in $&&"server"in $}class I0{sessionId;agent=null;abortController=null;_messages=[];options;maxTurns;permissionMode;initialized=!1;pendingMessage=null;pendingSendOptions=null;constructor($,b){this.sessionId=b||YW(),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)N0().configure(this.options.sandbox);if(this.options.enableFileCheckpointing)k$().configure({enabled:!0});await this.registerInProcessMcpServers(),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,Z$.debug(`[Session] Initialized session ${this.sessionId}`)}async registerInProcessMcpServers(){if(!this.options.mcpServers)return;let $=c.getInstance();for(let[b,w]of Object.entries(this.options.mcpServers))if(Iw(w))await $.registerInProcessServer(b,w),Z$.debug(`[Session] Registered in-process MCP server: ${b}`)}async loadHistory(){let $=this.options.cwd||process.cwd(),b=C$($,this.sessionId),w=new G$(b);try{let V=await w.readAll();if(V.length===0){Z$.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}),Z$.debug(`[Session] Loaded ${this._messages.length} messages from history`)}catch(V){Z$.warn(`[Session] Failed to load history for session ${this.sessionId}:`,V)}}buildBladeConfig(){let $=this.buildModelConfig(),b,w;if(this.options.mcpServers){let V={},W=[];for(let[Q,Z]of Object.entries(this.options.mcpServers))if(Iw(Z))W.push(Q);else V[Q]=Z;b=Object.keys(V).length>0?V:void 0,w=W.length>0?W:void 0}return{models:[$],currentModelId:$.id,temperature:0.7,mcpServers:b,inProcessMcpServerNames:w,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),maxContextTokens: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,Z$.debug(`[Session] Closed session ${this.sessionId}`)}abort(){if(this.abortController)this.abortController.abort(),this.abortController=null}setPermissionMode($){this.permissionMode=$}async setModel($){Z$.warn("[Session] setModel is not yet implemented")}setMaxTurns($){this.maxTurns=$}async supportedCommands(){let $=z$.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`);if(Iw(V))await b.registerInProcessServer($,V);else await b.registerServer($,V)}else await b.connectServer($);Z$.debug(`[Session] Connected to MCP server: ${$}`)}async mcpDisconnect($){await c.getInstance().disconnectServer($),Z$.debug(`[Session] Disconnected from MCP server: ${$}`)}async mcpReconnect($){await c.getInstance().reconnectServer($),Z$.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 I0(this.options);if(await V.initialize(),V._messages=w.map((W)=>({...W})),$?.copyCheckpoints&&this.options.enableFileCheckpointing)Z$.debug("[Session] Checkpoint copying is not yet implemented for forked sessions");return Z$.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 e2($){let b=new I0($);return await b.initialize(),Z$.debug(`[Session] Created new session: ${b.sessionId}`),b}async function $8($){let{sessionId:b,...w}=$,V=new I0(w,b);return await V.initialize(),await V.loadHistory(),Z$.debug(`[Session] Resumed session: ${b} with ${V.messages.length} messages`),V}async function b8($){let{sessionId:b,messageId:w,copyCheckpoints:V,...W}=$,Q=new I0(W,b);await Q.initialize(),await Q.loadHistory();let Z=await Q.fork({messageId:w,copyCheckpoints:V});return Q.close(),Z$.debug(`[Session] Forked session ${b} -> ${Z.sessionId} with ${Z.messages.length} messages`),Z}async function w8($,b){let w=Date.now(),V=new I0(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{M5 as toolFromDefinition,g2 as tool,cW as shutdownLogger,mW as setLoggerSessionId,$8 as resumeSession,pb as readMcpResourceTool,w8 as prompt,$0 as parsePluginManifest,Sb as notebookEditTool,u as logger,xb as listMcpResourcesTool,rb as isValidPluginDir,F0 as isReadOnlyKind,j9 as isGlobMetadata,N9 as isEditMetadata,o2 as integrateAllPlugins,Lb as injectSkillsMetadata,N0 as getSandboxService,j0 as getSandboxExecutor,tb as getPluginRegistry,r2 as getPluginInstaller,k0 as getNamespacedName,ob as getMcpNamespacedName,k$ as getCheckpointService,Kw as getBuiltinTools,b8 as forkSession,Eb as discoverSkills,y5 as defineTool,E as createTool,e2 as createSession,m2 as createSdkMcpServer,y as createLogger,Bb as createChatServiceAsync,t2 as clearAllPluginResources,Ib as askUserQuestionTool,Qb as ToolRegistry,Z8 as ToolKind,_1 as ToolExecution,B8 as ToolErrorType,Q8 as StreamMessageType,i as SpecManager,u$ as SandboxService,d$ as SandboxExecutor,Y0 as STEERING_FILES,c4 as SPEC_FILE_NAMES,Z0 as SPEC_DIRS,l$ as PluginRegistry,f0 as PluginLoader,Xb as PluginIntegrator,ab as PluginInstaller,b1 as PermissionMode,X8 as PermissionDecision,Y8 as PermissionBehavior,$b as PHASE_TRANSITIONS,i4 as PHASE_PRIMARY_FILE,gY as PHASE_ORDER,R$ as PHASE_DISPLAY_NAMES,hw as MessageRole,c as McpRegistry,M1 as McpErrorType,b0 as McpConnectionStatus,H0 as McpClient,x$ as Logger,A1 as LogLevel,a as LogCategory,O8 as HookType,r as HookManager,G8 as HookExitCode,h0 as HookEvent,S1 as HealthStatus,c0 as HealthMonitor,gb as ExecutionPipeline,J8 as DecisionBehavior,nb as ContextManager,b$ as CompactionService,z$ as CommandRegistry,Yb as CommandParser,Jb as CommandLoader,Zb as CommandExecutor,p$ as CheckpointService,g$ as Agent};
|