blade-code 0.5.0 → 0.5.1

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.
@@ -1 +1 @@
1
- import{a as y,b as A,c as C,d as D}from"./chunk-pp1y3ffx.js";import"./chunk-z0ktwnc4.js";import"./chunk-c6ay4323.js";import"./chunk-56yaw2xt.js";import"./chunk-esnkk33h.js";import"./chunk-91wsnfpn.js";import"./chunk-cj5w17y3.js";import{Aa as q}from"./chunk-j73schtj.js";import"./chunk-n2dcjqbe.js";import"./chunk-5zhx4vxz.js";import"./chunk-yddnm9n2.js";import"./chunk-p3znznzd.js";import"./chunk-9rz6rpcc.js";import"./chunk-7ycmx7c2.js";import"./chunk-set7v1rf.js";import"./chunk-j2ag7hh6.js";import H from"chalk";var R={command:"serve",describe:"Start a headless Blade server (no browser)",builder:y,handler:async(E)=>{let f=A(E);if(await q(),!process.env.BLADE_SERVER_PASSWORD)console.log(H.yellow("Warning: BLADE_SERVER_PASSWORD is not set; server is unsecured."));let b=await D.listenAsync(f);if(console.log(`Blade server listening on http://${b.hostname}:${b.port}`),f.hostname==="0.0.0.0"){let F=C();for(let G of F)console.log(` Network: http://${G}:${b.port}`)}await new Promise(()=>{}),await b.stop()}};export{R as serveCommand};
1
+ import{a as y,b as A,c as C,d as D}from"./chunk-6ba26b35.js";import"./chunk-z0ktwnc4.js";import"./chunk-93h1rwpj.js";import"./chunk-y5d5g2cs.js";import"./chunk-esnkk33h.js";import"./chunk-57yaytxj.js";import"./chunk-cj5w17y3.js";import{Aa as q}from"./chunk-j73schtj.js";import"./chunk-n2dcjqbe.js";import"./chunk-fr4jznsd.js";import"./chunk-yddnm9n2.js";import"./chunk-p3znznzd.js";import"./chunk-9rz6rpcc.js";import"./chunk-7ycmx7c2.js";import"./chunk-set7v1rf.js";import"./chunk-j2ag7hh6.js";import H from"chalk";var R={command:"serve",describe:"Start a headless Blade server (no browser)",builder:y,handler:async(E)=>{let f=A(E);if(await q(),!process.env.BLADE_SERVER_PASSWORD)console.log(H.yellow("Warning: BLADE_SERVER_PASSWORD is not set; server is unsecured."));let b=await D.listenAsync(f);if(console.log(`Blade server listening on http://${b.hostname}:${b.port}`),f.hostname==="0.0.0.0"){let F=C();for(let G of F)console.log(` Network: http://${G}:${b.port}`)}await new Promise(()=>{}),await b.stop()}};export{R as serveCommand};
@@ -1,4 +1,4 @@
1
- import{a as Q,b as R,c as T,d as W}from"./chunk-pp1y3ffx.js";import"./chunk-z0ktwnc4.js";import"./chunk-c6ay4323.js";import"./chunk-56yaw2xt.js";import"./chunk-esnkk33h.js";import{ba as M}from"./chunk-91wsnfpn.js";import"./chunk-cj5w17y3.js";import{Aa as J}from"./chunk-j73schtj.js";import"./chunk-n2dcjqbe.js";import"./chunk-5zhx4vxz.js";import"./chunk-yddnm9n2.js";import"./chunk-p3znznzd.js";import"./chunk-9rz6rpcc.js";import"./chunk-7ycmx7c2.js";import"./chunk-set7v1rf.js";import"./chunk-j2ag7hh6.js";import b from"chalk";import H from"open";var $=`
1
+ import{a as Q,b as R,c as T,d as W}from"./chunk-6ba26b35.js";import"./chunk-z0ktwnc4.js";import"./chunk-93h1rwpj.js";import"./chunk-y5d5g2cs.js";import"./chunk-esnkk33h.js";import{ba as M}from"./chunk-57yaytxj.js";import"./chunk-cj5w17y3.js";import{Aa as J}from"./chunk-j73schtj.js";import"./chunk-n2dcjqbe.js";import"./chunk-fr4jznsd.js";import"./chunk-yddnm9n2.js";import"./chunk-p3znznzd.js";import"./chunk-9rz6rpcc.js";import"./chunk-7ycmx7c2.js";import"./chunk-set7v1rf.js";import"./chunk-j2ag7hh6.js";import b from"chalk";import H from"open";var $=`
2
2
  ____ _ _
3
3
  | __ )| | __ _ __| | ___
4
4
  | _ \\| |/ _\` |/ _\` |/ _ \\
@@ -1,4 +1,4 @@
1
- import{N as l,O as c,P as m,S as g,U as d}from"./chunk-c6ay4323.js";import{xb as u}from"./chunk-7ycmx7c2.js";async function C(){if((await l().initialize(u(),[])).plugins.length>0)await c()}async function h(t){let e=t.message||t._?.[0];if(typeof e==="string"&&e.trim())return e;let n=t.stdin??process.stdin;if(!n.isTTY){let a=[];for await(let i of n)a.push(i);return Buffer.concat(a).toString("utf-8").trim()}if(t.defaultMessage!==void 0)return t.defaultMessage;throw Error("No input provided")}async function R(t){if(!g(t))return{mode:"agent",content:t};let e=await d(t,{cwd:u(),workspaceRoot:u()});if(!e.success)return{mode:"output",content:`Error: ${e.error||"未知错误"}`,exitCode:1};let n=e.data;if(n?.action==="invoke_skill"){let{skillName:a,skillArgs:i}=n;return{mode:"agent",content:i?`Please use the "${a}" skill to help me with: ${i}`:`Please use the "${a}" skill.`}}if(n?.action==="invoke_custom_command"||n?.action==="invoke_plugin_command"){let a=n.processedContent;return{mode:"agent",content:`# Custom Command: /${n.commandName}
1
+ import{N as l,O as c,P as m,S as g,U as d}from"./chunk-93h1rwpj.js";import{xb as u}from"./chunk-7ycmx7c2.js";async function C(){if((await l().initialize(u(),[])).plugins.length>0)await c()}async function h(t){let e=t.message||t._?.[0];if(typeof e==="string"&&e.trim())return e;let n=t.stdin??process.stdin;if(!n.isTTY){let a=[];for await(let i of n)a.push(i);return Buffer.concat(a).toString("utf-8").trim()}if(t.defaultMessage!==void 0)return t.defaultMessage;throw Error("No input provided")}async function R(t){if(!g(t))return{mode:"agent",content:t};let e=await d(t,{cwd:u(),workspaceRoot:u()});if(!e.success)return{mode:"output",content:`Error: ${e.error||"未知错误"}`,exitCode:1};let n=e.data;if(n?.action==="invoke_skill"){let{skillName:a,skillArgs:i}=n;return{mode:"agent",content:i?`Please use the "${a}" skill to help me with: ${i}`:`Please use the "${a}" skill.`}}if(n?.action==="invoke_custom_command"||n?.action==="invoke_plugin_command"){let a=n.processedContent;return{mode:"agent",content:`# Custom Command: /${n.commandName}
2
2
 
3
3
  ${a}`}}return{mode:"output",content:e.content||e.message||"",exitCode:0}}function r(t){if(!(t instanceof Error))return!1;return t.message.includes("未找到会话")||t.message.includes("ENOENT")||t.message.includes("no such file")}async function s(t){try{return await m.loadSession(t,u())}catch(e){if(r(e))return null;throw e}}async function N(t){if(t.resume===!0||t.resume==="true")throw Error("--resume without a session ID is only supported in interactive UI mode");if(typeof t.resume==="string"&&t.resume.length>0)return{sessionId:t.resume,messages:await m.loadSession(t.resume)};if(t.continue){let e=await m.listSessions();if(e.length>0){let n=e[0].sessionId;return{sessionId:n,messages:await m.loadSession(n)}}}if(t.sessionId)return{sessionId:t.sessionId,messages:await s(t.sessionId)??[]};return{sessionId:`${t.fallbackSessionPrefix}-${Date.now()}`,messages:[]}}
4
4
  export{C as p,h as q,R as r,N as s};
@@ -1,4 +1,4 @@
1
- import{A as V,G as f,J as N,K as L,M as T,S as h,U as P,V as R}from"./chunk-c6ay4323.js";import{Y as M}from"./chunk-56yaw2xt.js";import"./chunk-esnkk33h.js";import"./chunk-91wsnfpn.js";import"./chunk-cj5w17y3.js";import{za as y}from"./chunk-j73schtj.js";import"./chunk-n2dcjqbe.js";import{Sa as O}from"./chunk-5zhx4vxz.js";import"./chunk-yddnm9n2.js";import"./chunk-p3znznzd.js";import"./chunk-9rz6rpcc.js";import{xb as D}from"./chunk-7ycmx7c2.js";import{Bb as W}from"./chunk-set7v1rf.js";import"./chunk-j2ag7hh6.js";import{Readable as K,Writable as k}from"node:stream";import*as _ from"@agentclientprotocol/sdk";import{PROTOCOL_VERSION as I}from"@agentclientprotocol/sdk";import{nanoid as S}from"nanoid";import{nanoid as x}from"nanoid";var X=W("Agent");class B{id;cwd;connection;clientCapabilities;agent=null;runtime=null;pendingPrompt=null;messages=[];mode="default";sessionApprovals=new Set;constructor(z,G,H,Q){this.id=z;this.cwd=G;this.connection=H;this.clientCapabilities=Q}async initialize(){X.debug(`[AcpSession ${this.id}] Initializing...`),V.initializeSession(this.connection,this.id,this.clientCapabilities,this.cwd),X.debug(`[AcpSession ${this.id}] ACP service context initialized`),this.runtime=await f.create({sessionId:this.id}),this.agent=await T.createWithRuntime(this.runtime,{sessionId:this.id}),X.debug(`[AcpSession ${this.id}] Agent created successfully`)}sendAvailableCommandsDelayed(){X.debug(`[AcpSession ${this.id}] Scheduling available commands update (500ms delay)`),setTimeout(()=>{this.sendAvailableCommands()},500)}async handleSlashCommand(z,G){try{X.debug(`[AcpSession ${this.id}] Executing slash command: ${z}`);let H={cwd:this.cwd,signal:G,acp:{sendMessage:(U)=>{this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:U}})},sendToolStart:(U,Y,q)=>{let Z=`tool_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,E=this.mapToolKind(q);this.sendUpdate({sessionUpdate:"tool_call",toolCallId:Z,status:"in_progress",title:`${U}`,content:[{type:"content",content:{type:"text",text:JSON.stringify(Y,null,2)}}],kind:E})},sendToolResult:(U,Y)=>{if(Y.summary)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:Y.summary}})}}},Q=await P(z,H),J=Q.content||Q.message;if(J)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:J}});if(Q.error)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[FAIL] ${Q.error}`}});return{stopReason:Q.success?"end_turn":"cancelled"}}catch(H){return X.error(`[AcpSession ${this.id}] Slash command error:`,H),this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[FAIL] 命令执行失败: ${H instanceof Error?H.message:"未知错误"}`}}),{stopReason:"cancelled"}}}async sendAvailableCommands(){try{let z=R(),G=["model","permissions","theme","config","exit","ide"],Q=z.filter((J)=>!G.includes(J.name)).map((J)=>{let U;if(J.usage){let Y=J.usage.replace(/^\/\w+\s*/,"").trim();if(Y)U=Y}if(J.aliases?.length){let Y=`Aliases: ${J.aliases.join(", ")}`;U=U?`${U} | ${Y}`:Y}return{name:J.name,description:J.description,input:U?{hint:U}:void 0}});X.info(`[AcpSession ${this.id}] Sending available commands: ${JSON.stringify(Q.map((J)=>J.name))}`),this.sendUpdate({sessionUpdate:"available_commands_update",availableCommands:Q}),X.info(`[AcpSession ${this.id}] Sent ${Q.length} available commands`)}catch(z){X.error(`[AcpSession ${this.id}] Failed to send available commands:`,z)}}async prompt(z){V.setCurrentSession(this.id),this.pendingPrompt?.abort();let G=new AbortController;if(this.pendingPrompt=G,!this.agent)throw Error("Session not initialized");try{let H=this.resolvePrompt(z.prompt);if(X.debug(`[AcpSession ${this.id}] Received prompt: ${H.slice(0,100)}...`),h(H))return await this.handleSlashCommand(H,G.signal);let Q={sessionId:this.id,userId:"acp-user",workspaceRoot:this.cwd,messages:[...this.messages],signal:G.signal,permissionMode:this.mapModeToPermissionMode(),confirmationHandler:{requestConfirmation:async(J)=>{return this.requestPermission(J)}}};if(await O(this.agent.chatStream(H,Q),async(J)=>{switch(J.kind){case"content_delta":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:J.delta}});break;case"thinking_delta":this.sendUpdate({sessionUpdate:"agent_thought_chunk",content:{type:"text",text:J.delta}});break;case"tool_start":{let U=J.toolCall,Y="function"in U?U.function.name:U.type,q=this.mapToolKind(J.toolKind);this.sendUpdate({sessionUpdate:"tool_call",toolCallId:U.id,status:"in_progress",title:`Executing ${Y}`,content:[],kind:q});break}case"tool_result":{let{toolCall:U,result:Y}=J,q=[],Z=Y.metadata;if(Z?.kind==="edit"&&typeof Z.file_path==="string"&&typeof Z.oldContent==="string"&&(typeof Z.newContent==="string"||Z.newContent===void 0))q.push({type:"diff",path:Z.file_path,oldText:Z.oldContent,newText:Z.newContent??null});else{let F="function"in U?U.function.name:U.type,j=L(N(F,Y));q.push({type:"content",content:{type:"text",text:j}})}let E=Y.success?"completed":"failed";this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:U.id,status:E,content:q});break}case"task_update":this.sendPlanUpdate(J.tasks);break;default:break}}),this.messages=[...Q.messages],G.signal.aborted)return{stopReason:"cancelled"};return{stopReason:"end_turn"}}catch(H){if(G.signal.aborted||H instanceof Error&&H.name==="AbortError")return{stopReason:"cancelled"};throw X.error(`[AcpSession ${this.id}] Prompt error:`,H),H}finally{if(this.pendingPrompt===G)this.pendingPrompt=null}}cancel(){if(X.info(`[AcpSession ${this.id}] Cancel requested`),this.pendingPrompt)this.pendingPrompt.abort(),this.pendingPrompt=null,X.info(`[AcpSession ${this.id}] Cancelled successfully`);else X.warn(`[AcpSession ${this.id}] No pending prompt to cancel`)}async setMode(z){let G=["default","auto-edit","yolo","plan"];this.mode=G.includes(z)?z:"default",X.info(`[AcpSession ${this.id}] Mode set to: ${this.mode}`),this.sendUpdate({sessionUpdate:"current_mode_update",currentModeId:this.mode})}mapModeToPermissionMode(){switch(this.mode){case"yolo":return"yolo";case"auto-edit":return"autoEdit";case"plan":return"plan";case"default":default:return"default"}}shouldAutoApprove(z){switch(this.mode){case"yolo":return!0;case"auto-edit":return z==="readonly"||z==="write";case"plan":return z==="readonly";case"default":default:return!1}}async setModel(z){if(X.info(`[AcpSession ${this.id}] Model set to: ${z}`),this.agent)X.warn(`[AcpSession ${this.id}] Runtime model switching not yet implemented`)}async destroy(){if(this.cancel(),this.agent)await this.agent.destroy(),this.agent=null;if(this.runtime)await this.runtime.dispose(),this.runtime=null;V.destroySession(this.id),X.debug(`[AcpSession ${this.id}] Destroyed`)}resolvePrompt(z){let G=[];for(let H of z)if(H.type==="text")G.push(H.text);else if(H.type==="image")G.push(`[Image: ${H.mimeType}]`);else if(H.type==="resource"){let Q=H.resource;if("text"in Q)G.push(`<file path="${Q.uri}">
1
+ import{A as V,G as f,J as N,K as L,M as T,S as h,U as P,V as R}from"./chunk-93h1rwpj.js";import{Y as M}from"./chunk-y5d5g2cs.js";import"./chunk-esnkk33h.js";import"./chunk-57yaytxj.js";import"./chunk-cj5w17y3.js";import{za as y}from"./chunk-j73schtj.js";import"./chunk-n2dcjqbe.js";import{Sa as O}from"./chunk-fr4jznsd.js";import"./chunk-yddnm9n2.js";import"./chunk-p3znznzd.js";import"./chunk-9rz6rpcc.js";import{xb as D}from"./chunk-7ycmx7c2.js";import{Bb as W}from"./chunk-set7v1rf.js";import"./chunk-j2ag7hh6.js";import{Readable as K,Writable as k}from"node:stream";import*as _ from"@agentclientprotocol/sdk";import{PROTOCOL_VERSION as I}from"@agentclientprotocol/sdk";import{nanoid as S}from"nanoid";import{nanoid as x}from"nanoid";var X=W("Agent");class B{id;cwd;connection;clientCapabilities;agent=null;runtime=null;pendingPrompt=null;messages=[];mode="default";sessionApprovals=new Set;constructor(z,G,H,Q){this.id=z;this.cwd=G;this.connection=H;this.clientCapabilities=Q}async initialize(){X.debug(`[AcpSession ${this.id}] Initializing...`),V.initializeSession(this.connection,this.id,this.clientCapabilities,this.cwd),X.debug(`[AcpSession ${this.id}] ACP service context initialized`),this.runtime=await f.create({sessionId:this.id}),this.agent=await T.createWithRuntime(this.runtime,{sessionId:this.id}),X.debug(`[AcpSession ${this.id}] Agent created successfully`)}sendAvailableCommandsDelayed(){X.debug(`[AcpSession ${this.id}] Scheduling available commands update (500ms delay)`),setTimeout(()=>{this.sendAvailableCommands()},500)}async handleSlashCommand(z,G){try{X.debug(`[AcpSession ${this.id}] Executing slash command: ${z}`);let H={cwd:this.cwd,signal:G,acp:{sendMessage:(U)=>{this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:U}})},sendToolStart:(U,Y,q)=>{let Z=`tool_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,E=this.mapToolKind(q);this.sendUpdate({sessionUpdate:"tool_call",toolCallId:Z,status:"in_progress",title:`${U}`,content:[{type:"content",content:{type:"text",text:JSON.stringify(Y,null,2)}}],kind:E})},sendToolResult:(U,Y)=>{if(Y.summary)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:Y.summary}})}}},Q=await P(z,H),J=Q.content||Q.message;if(J)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:J}});if(Q.error)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[FAIL] ${Q.error}`}});return{stopReason:Q.success?"end_turn":"cancelled"}}catch(H){return X.error(`[AcpSession ${this.id}] Slash command error:`,H),this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[FAIL] 命令执行失败: ${H instanceof Error?H.message:"未知错误"}`}}),{stopReason:"cancelled"}}}async sendAvailableCommands(){try{let z=R(),G=["model","permissions","theme","config","exit","ide"],Q=z.filter((J)=>!G.includes(J.name)).map((J)=>{let U;if(J.usage){let Y=J.usage.replace(/^\/\w+\s*/,"").trim();if(Y)U=Y}if(J.aliases?.length){let Y=`Aliases: ${J.aliases.join(", ")}`;U=U?`${U} | ${Y}`:Y}return{name:J.name,description:J.description,input:U?{hint:U}:void 0}});X.info(`[AcpSession ${this.id}] Sending available commands: ${JSON.stringify(Q.map((J)=>J.name))}`),this.sendUpdate({sessionUpdate:"available_commands_update",availableCommands:Q}),X.info(`[AcpSession ${this.id}] Sent ${Q.length} available commands`)}catch(z){X.error(`[AcpSession ${this.id}] Failed to send available commands:`,z)}}async prompt(z){V.setCurrentSession(this.id),this.pendingPrompt?.abort();let G=new AbortController;if(this.pendingPrompt=G,!this.agent)throw Error("Session not initialized");try{let H=this.resolvePrompt(z.prompt);if(X.debug(`[AcpSession ${this.id}] Received prompt: ${H.slice(0,100)}...`),h(H))return await this.handleSlashCommand(H,G.signal);let Q={sessionId:this.id,userId:"acp-user",workspaceRoot:this.cwd,messages:[...this.messages],signal:G.signal,permissionMode:this.mapModeToPermissionMode(),confirmationHandler:{requestConfirmation:async(J)=>{return this.requestPermission(J)}}};if(await O(this.agent.chatStream(H,Q),async(J)=>{switch(J.kind){case"content_delta":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:J.delta}});break;case"thinking_delta":this.sendUpdate({sessionUpdate:"agent_thought_chunk",content:{type:"text",text:J.delta}});break;case"tool_start":{let U=J.toolCall,Y="function"in U?U.function.name:U.type,q=this.mapToolKind(J.toolKind);this.sendUpdate({sessionUpdate:"tool_call",toolCallId:U.id,status:"in_progress",title:`Executing ${Y}`,content:[],kind:q});break}case"tool_result":{let{toolCall:U,result:Y}=J,q=[],Z=Y.metadata;if(Z?.kind==="edit"&&typeof Z.file_path==="string"&&typeof Z.oldContent==="string"&&(typeof Z.newContent==="string"||Z.newContent===void 0))q.push({type:"diff",path:Z.file_path,oldText:Z.oldContent,newText:Z.newContent??null});else{let F="function"in U?U.function.name:U.type,j=L(N(F,Y));q.push({type:"content",content:{type:"text",text:j}})}let E=Y.success?"completed":"failed";this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:U.id,status:E,content:q});break}case"task_update":this.sendPlanUpdate(J.tasks);break;default:break}}),this.messages=[...Q.messages],G.signal.aborted)return{stopReason:"cancelled"};return{stopReason:"end_turn"}}catch(H){if(G.signal.aborted||H instanceof Error&&H.name==="AbortError")return{stopReason:"cancelled"};throw X.error(`[AcpSession ${this.id}] Prompt error:`,H),H}finally{if(this.pendingPrompt===G)this.pendingPrompt=null}}cancel(){if(X.info(`[AcpSession ${this.id}] Cancel requested`),this.pendingPrompt)this.pendingPrompt.abort(),this.pendingPrompt=null,X.info(`[AcpSession ${this.id}] Cancelled successfully`);else X.warn(`[AcpSession ${this.id}] No pending prompt to cancel`)}async setMode(z){let G=["default","auto-edit","yolo","plan"];this.mode=G.includes(z)?z:"default",X.info(`[AcpSession ${this.id}] Mode set to: ${this.mode}`),this.sendUpdate({sessionUpdate:"current_mode_update",currentModeId:this.mode})}mapModeToPermissionMode(){switch(this.mode){case"yolo":return"yolo";case"auto-edit":return"autoEdit";case"plan":return"plan";case"default":default:return"default"}}shouldAutoApprove(z){switch(this.mode){case"yolo":return!0;case"auto-edit":return z==="readonly"||z==="write";case"plan":return z==="readonly";case"default":default:return!1}}async setModel(z){if(X.info(`[AcpSession ${this.id}] Model set to: ${z}`),this.agent)X.warn(`[AcpSession ${this.id}] Runtime model switching not yet implemented`)}async destroy(){if(this.cancel(),this.agent)await this.agent.destroy(),this.agent=null;if(this.runtime)await this.runtime.dispose(),this.runtime=null;V.destroySession(this.id),X.debug(`[AcpSession ${this.id}] Destroyed`)}resolvePrompt(z){let G=[];for(let H of z)if(H.type==="text")G.push(H.text);else if(H.type==="image")G.push(`[Image: ${H.mimeType}]`);else if(H.type==="resource"){let Q=H.resource;if("text"in Q)G.push(`<file path="${Q.uri}">
2
2
  ${Q.text}
3
3
  </file>`)}else if(H.type==="resource_link")G.push(`[Resource: ${H.uri}]`);return G.join(`
4
4
  `)}sendUpdate(z){let G={sessionId:this.id,update:z};this.connection.sessionUpdate(G).catch((H)=>{X.warn(`[AcpSession ${this.id}] Failed to send update:`,H)})}sendPlanUpdate(z){let G=z.map((H)=>({content:H.subject,priority:H.priority,status:H.status}));X.debug(`[AcpSession ${this.id}] Sending plan update with ${G.length} entries`),this.sendUpdate({sessionUpdate:"plan",entries:G})}async requestPermission(z){let G=z.kind?.toLowerCase()||"execute";if(this.shouldAutoApprove(G))return X.debug(`[AcpSession ${this.id}] Auto-approving ${G} in mode: ${this.mode}`),{approved:!0};if(this.mode==="plan"&&(G==="write"||G==="execute"))return X.debug(`[AcpSession ${this.id}] Rejecting ${G} in plan mode`),{approved:!1,reason:"Write and execute operations are not allowed in Plan mode"};let H=`${G}:${z.title||"unknown"}`;if(this.sessionApprovals.has(H))return X.debug(`[AcpSession ${this.id}] Using cached approval for: ${H}`),{approved:!0};try{let Q=x(),J=[];if(z.message)J.push({type:"content",content:{type:"text",text:z.message}});if(z.risks&&z.risks.length>0)J.push({type:"content",content:{type:"text",text:`Risks:
@@ -1,2 +1,2 @@
1
- import{ba as d,da as h}from"./chunk-91wsnfpn.js";var q={debug:{alias:"d",type:"string",describe:'Enable debug mode with optional category filtering (e.g., "agent,ui" or "!chat,!loop")',group:"Debug Options:"},model:{type:"string",describe:"Override the current run model using a model config ID (TUI / print / headless)",group:"AI Options:"},print:{alias:"p",type:"boolean",describe:"Print response and exit (useful for pipes)",group:"Output Options:"},headless:{type:"boolean",describe:"Run full agent loop without Ink UI and print all events to the terminal",group:"Output Options:"},"output-format":{alias:["outputFormat"],type:"string",choices:["text","json","stream-json","jsonl"],default:"text",describe:"Output format: --print supports text|json|stream-json; --headless supports text|jsonl",group:"Output Options:"},"include-partial-messages":{alias:["includePartialMessages"],type:"boolean",describe:"Include partial message chunks as they arrive",group:"Output Options:"},"input-format":{alias:["inputFormat"],type:"string",choices:["text","stream-json"],default:"text",describe:"Input format",group:"Input Options:"},"replay-user-messages":{alias:["replayUserMessages"],type:"boolean",describe:"Re-emit user messages from stdin",group:"Input Options:"},"allowed-tools":{alias:["allowedTools"],type:"array",string:!0,describe:"Comma or space-separated list of tool names to allow",group:"Security Options:"},"disallowed-tools":{alias:["disallowedTools"],type:"array",string:!0,describe:"Comma or space-separated list of tool names to deny",group:"Security Options:"},"mcp-config":{alias:["mcpConfig"],type:"array",string:!0,describe:"Load MCP servers from JSON files or strings",group:"MCP Options:"},"system-prompt":{alias:["systemPrompt"],type:"string",describe:"System prompt to use for the session (replaces default)",group:"AI Options:"},"append-system-prompt":{alias:["appendSystemPrompt"],type:"string",describe:"Append a system prompt to the default system prompt",group:"AI Options:"},"max-turns":{alias:["maxTurns"],type:"number",describe:"Maximum conversation turns (-1: unlimited, 0: disable chat, N>0: limit to N turns)",group:"AI Options:",default:void 0},"permission-mode":{alias:["permissionMode"],type:"string",choices:["default","autoEdit","yolo","plan"],describe:"Permission mode (default: ask for non-read tools, autoEdit: auto-approve edits, yolo: auto-approve all, plan: reserved)",group:"Security Options:"},yolo:{type:"boolean",describe:"Auto-approve all tools (shortcut for --permission-mode=yolo)",group:"Security Options:"},continue:{alias:"c",type:"boolean",describe:"Continue the most recent conversation",group:"Session Options:"},resume:{alias:"r",describe:"Resume a conversation - provide a session ID or interactively select a conversation to resume",group:"Session Options:",coerce:(b)=>{if(b===void 0||b===!0||b==="")return"true";return String(b)}},"fork-session":{alias:["forkSession"],type:"boolean",describe:"Create a new session ID when resuming",group:"Session Options:"},settings:{type:"string",describe:"Path to a settings JSON file or JSON string",group:"Configuration:"},"add-dir":{alias:["addDir"],type:"array",string:!0,describe:"Additional directories to allow tool access to",group:"Security Options:"},ide:{type:"boolean",describe:"Automatically connect to IDE on startup",group:"Integration:"},acp:{type:"boolean",describe:"Run in ACP (Agent Client Protocol) mode for IDE integration",group:"Integration:"},"strict-mcp-config":{alias:["strictMcpConfig"],type:"boolean",describe:"Only use MCP servers from --mcp-config",group:"MCP Options:"},"session-id":{alias:["sessionId"],type:"string",describe:"Use a specific session ID for the conversation",group:"Session Options:"},agents:{type:"string",describe:"JSON object defining custom agents",group:"AI Options:"},"setting-sources":{alias:["settingSources"],type:"string",describe:"Comma-separated list of setting sources to load",group:"Configuration:"},"plugin-dir":{alias:["pluginDir"],type:"array",string:!0,describe:"Load plugins from specified directories",group:"Plugin Options:"}},w={scriptName:"blade",usage:"$0 [command] [options]",description:h(),version:d(),locale:"en",showHelpOnFail:!0,demandCommand:!1,recommendCommands:!0,strict:!1};
1
+ import{ba as d,da as h}from"./chunk-57yaytxj.js";var q={debug:{alias:"d",type:"string",describe:'Enable debug mode with optional category filtering (e.g., "agent,ui" or "!chat,!loop")',group:"Debug Options:"},model:{type:"string",describe:"Override the current run model using a model config ID (TUI / print / headless)",group:"AI Options:"},print:{alias:"p",type:"boolean",describe:"Print response and exit (useful for pipes)",group:"Output Options:"},headless:{type:"boolean",describe:"Run full agent loop without Ink UI and print all events to the terminal",group:"Output Options:"},"output-format":{alias:["outputFormat"],type:"string",choices:["text","json","stream-json","jsonl"],default:"text",describe:"Output format: --print supports text|json|stream-json; --headless supports text|jsonl",group:"Output Options:"},"include-partial-messages":{alias:["includePartialMessages"],type:"boolean",describe:"Include partial message chunks as they arrive",group:"Output Options:"},"input-format":{alias:["inputFormat"],type:"string",choices:["text","stream-json"],default:"text",describe:"Input format",group:"Input Options:"},"replay-user-messages":{alias:["replayUserMessages"],type:"boolean",describe:"Re-emit user messages from stdin",group:"Input Options:"},"allowed-tools":{alias:["allowedTools"],type:"array",string:!0,describe:"Comma or space-separated list of tool names to allow",group:"Security Options:"},"disallowed-tools":{alias:["disallowedTools"],type:"array",string:!0,describe:"Comma or space-separated list of tool names to deny",group:"Security Options:"},"mcp-config":{alias:["mcpConfig"],type:"array",string:!0,describe:"Load MCP servers from JSON files or strings",group:"MCP Options:"},"system-prompt":{alias:["systemPrompt"],type:"string",describe:"System prompt to use for the session (replaces default)",group:"AI Options:"},"append-system-prompt":{alias:["appendSystemPrompt"],type:"string",describe:"Append a system prompt to the default system prompt",group:"AI Options:"},"max-turns":{alias:["maxTurns"],type:"number",describe:"Maximum conversation turns (-1: unlimited, 0: disable chat, N>0: limit to N turns)",group:"AI Options:",default:void 0},"permission-mode":{alias:["permissionMode"],type:"string",choices:["default","autoEdit","yolo","plan"],describe:"Permission mode (default: ask for non-read tools, autoEdit: auto-approve edits, yolo: auto-approve all, plan: reserved)",group:"Security Options:"},yolo:{type:"boolean",describe:"Auto-approve all tools (shortcut for --permission-mode=yolo)",group:"Security Options:"},continue:{alias:"c",type:"boolean",describe:"Continue the most recent conversation",group:"Session Options:"},resume:{alias:"r",describe:"Resume a conversation - provide a session ID or interactively select a conversation to resume",group:"Session Options:",coerce:(b)=>{if(b===void 0||b===!0||b==="")return"true";return String(b)}},"fork-session":{alias:["forkSession"],type:"boolean",describe:"Create a new session ID when resuming",group:"Session Options:"},settings:{type:"string",describe:"Path to a settings JSON file or JSON string",group:"Configuration:"},"add-dir":{alias:["addDir"],type:"array",string:!0,describe:"Additional directories to allow tool access to",group:"Security Options:"},ide:{type:"boolean",describe:"Automatically connect to IDE on startup",group:"Integration:"},acp:{type:"boolean",describe:"Run in ACP (Agent Client Protocol) mode for IDE integration",group:"Integration:"},"strict-mcp-config":{alias:["strictMcpConfig"],type:"boolean",describe:"Only use MCP servers from --mcp-config",group:"MCP Options:"},"session-id":{alias:["sessionId"],type:"string",describe:"Use a specific session ID for the conversation",group:"Session Options:"},agents:{type:"string",describe:"JSON object defining custom agents",group:"AI Options:"},"setting-sources":{alias:["settingSources"],type:"string",describe:"Comma-separated list of setting sources to load",group:"Configuration:"},"plugin-dir":{alias:["pluginDir"],type:"array",string:!0,describe:"Load plugins from specified directories",group:"Plugin Options:"}},w={scriptName:"blade",usage:"$0 [command] [options]",description:h(),version:d(),locale:"en",showHelpOnFail:!0,demandCommand:!1,recommendCommands:!0,strict:!1};
2
2
  export{q as t,w as u};
@@ -1 +1 @@
1
- import{$a as l,Qa as a,Ra as b,Sa as c,Ta as d,Ua as e,Va as f,Wa as g,Xa as h,Ya as i,Za as j,_a as k,ab as m,bb as n,cb as o,fb as p,gb as q,hb as r}from"./chunk-5zhx4vxz.js";import"./chunk-yddnm9n2.js";import"./chunk-p3znznzd.js";import"./chunk-9rz6rpcc.js";import"./chunk-7ycmx7c2.js";import"./chunk-set7v1rf.js";import"./chunk-j2ag7hh6.js";export{g as saveUserMessage,i as saveToolUse,j as saveToolResult,k as saveCompaction,h as saveAssistantMessage,a as isRootSystemPrompt,l as handleTaskListUpdate,m as handleSkillActivation,n as extractModelSwitch,r as executeLoopGenerator,c as drainLoop,f as checkStopHook,d as checkOutputRecovery,e as checkIncompleteIntent,q as checkAndCompactInLoop,o as applyToolDomainEffects,p as StreamingToolExecutor,b as ConversationState};
1
+ import{$a as l,Qa as a,Ra as b,Sa as c,Ta as d,Ua as e,Va as f,Wa as g,Xa as h,Ya as i,Za as j,_a as k,ab as m,bb as n,cb as o,fb as p,gb as q,hb as r}from"./chunk-fr4jznsd.js";import"./chunk-yddnm9n2.js";import"./chunk-p3znznzd.js";import"./chunk-9rz6rpcc.js";import"./chunk-7ycmx7c2.js";import"./chunk-set7v1rf.js";import"./chunk-j2ag7hh6.js";export{g as saveUserMessage,i as saveToolUse,j as saveToolResult,k as saveCompaction,h as saveAssistantMessage,a as isRootSystemPrompt,l as handleTaskListUpdate,m as handleSkillActivation,n as extractModelSwitch,r as executeLoopGenerator,c as drainLoop,f as checkStopHook,d as checkOutputRecovery,e as checkIncompleteIntent,q as checkAndCompactInLoop,o as applyToolDomainEffects,p as StreamingToolExecutor,b as ConversationState};
@@ -1,4 +1,4 @@
1
- import{nb as W0}from"./chunk-p3znznzd.js";import{rb as t0}from"./chunk-9rz6rpcc.js";import{xb as x}from"./chunk-7ycmx7c2.js";import{Bb as P}from"./chunk-set7v1rf.js";import{Db as S$}from"./chunk-j2ag7hh6.js";function G0($){return $.role==="system"&&Array.isArray($.content)}class q0{systemMessages;_history;_pending=[];context;constructor($,Q){this.context=$;let Z=$.messages.find(G0);if(Z)this.systemMessages=[Z];else if(Q)this.systemMessages=[{role:"system",content:[{type:"text",text:Q,providerOptions:{anthropic:{cacheControl:{type:"ephemeral"}}}}]}];else this.systemMessages=[];this._history=$.messages.filter((J)=>!G0(J))}get historyLength(){return this._history.length}get history(){return this._history}get pending(){return this._pending}toLLMMessages(){return[...this.systemMessages,...this._history,...this._pending]}getMessagesForLLM(){return this.toLLMMessages()}getHistory(){return this._history}appendPending($){this._pending.push($)}appendUser($){this._pending.push($)}appendAssistant($){this._pending.push($)}appendToolResult($){this._pending.push($)}appendControl($,Q){if($==="system")throw Error("Cannot append system control message via appendControl. Use constructor for root system prompt.");this._pending.push(Q)}appendToHistory($){this._history.push($)}commitPending(){if(this._pending.length>0)this._history.push(...this._pending),this._pending=[]}replaceHistory($){this._history=$.filter((Q)=>!G0(Q))}writeback(){this.commitPending(),this.context.messages=this._history}get hasSystemPrompt(){return this.systemMessages.length>0}}async function y$($,Q){let Z;while(!(Z=await $.next()).done)if(Q)await Q(Z.value);return Z.value}function m0($){if($.isSubagent)return"continue";if(!$.budget||$.budget<=0)return"continue";if($.consecutiveContinuations>=3&&$.lastOutputDelta<500)return"stop";if($.usage/$.budget>=0.9)return"stop";return"continue"}function g0($){return{budget:$.budget,usage:0,consecutiveContinuations:0,lastOutputDelta:0,isSubagent:$.isSubagent??!1}}function c0($,Q,Z){return{...$,usage:$.usage+Q,lastOutputDelta:Q,consecutiveContinuations:Z?$.consecutiveContinuations+1:0}}var r=P("Agent"),M$=3;function v0($,Q,Z){if($!=="length")return{action:"none"};if(Q>=M$)return{action:"truncated"};if(m0(Z)==="stop")return r.info("[Loop] Token budget: diminishing returns detected, skipping recovery"),{action:"budget_stop"};return{action:"recover"}}var P$=[/:\s*$/,/:\s*$/,/\.\.\.\s*$/,/让我(先|来|开始|查看|检查|修复)/,/Let me (first|start|check|look|fix)/i,/I('ll| will) (now |)(create|write|edit|update|modify|fix|add|implement)/i,/我(现在就|来|要)(创建|写入|编辑|修改|修复|添加|实现)/],f$=/```[\s\S]{50,}```/,u0="请执行你提到的操作,不要只是描述。使用 Edit/Write/Bash 工具来实际修改文件。",R$=2;function U0($,Q,Z=!0){if(!$||Q>=R$)return{action:"none"};if(!Z&&f$.test($))return{action:"retry",prompt:u0};let J=$.slice(-200),V=J.match(/```/g);if(V&&V.length%2!==0)return{action:"none"};if(P$.some((G)=>G.test(J)))return{action:"retry",prompt:u0};return{action:"none"}}var i0=30000;async function A0($){try{let Z=W0.getInstance().executeStopHooks({projectDir:x(),sessionId:$.sessionId,permissionMode:$.permissionMode,reason:$.reason,abortSignal:$.abortSignal}),J,V=new Promise((z)=>{J=setTimeout(()=>z("timeout"),i0)});try{let z=await Promise.race([Z,V]);if(z==="timeout")return r.warn(`[Loop] Stop hook 超时 (${i0}ms),按 shouldStop: true 处理`),{action:"stop"};let G=z;if(!G.shouldStop)return{action:"continue",reason:G.continueReason};return{action:"stop"}}finally{clearTimeout(J)}}catch(Q){return r.warn("[Loop] Stop hook execution failed:",Q),{action:"stop"}}}var T$=0.9;async function n0($){try{let{SpecManager:Q}=await import("./chunk-jmsm3eam.js"),Z=Q.getInstance();if(!Z.isActive())return{action:"none"};let J=Z.getCurrentSpec();if(!J||J.phase!=="implementation")return{action:"none"};if($.maxTurns>0&&$.turnsCount>=$.maxTurns*T$)return r.info(`[RalphLoop] 轮次接近上限 (${$.turnsCount}/${$.maxTurns}),停止自动继续`),{action:"none"};let V=J.tasks??[],z=V.filter((K)=>K.status==="completed"||K.status==="skipped").length,G=V.length;if(z>=G)return{action:"none"};let q=V.find((K)=>K.status==="pending"||K.status==="in_progress"),W=`[Ralph Loop] Spec "${J.name}" 仍有未完成任务。
1
+ import{nb as W0}from"./chunk-p3znznzd.js";import{rb as t0}from"./chunk-9rz6rpcc.js";import{xb as x}from"./chunk-7ycmx7c2.js";import{Bb as P}from"./chunk-set7v1rf.js";import{Db as S$}from"./chunk-j2ag7hh6.js";function G0($){return $.role==="system"&&Array.isArray($.content)}class q0{systemMessages;_history;_pending=[];context;constructor($,Q){this.context=$;let Z=$.messages.find(G0);if(Z)this.systemMessages=[Z];else if(Q)this.systemMessages=[{role:"system",content:[{type:"text",text:Q,providerOptions:{anthropic:{cacheControl:{type:"ephemeral"}}}}]}];else this.systemMessages=[];this._history=$.messages.filter((J)=>!G0(J))}get historyLength(){return this._history.length}get history(){return this._history}get pending(){return this._pending}toLLMMessages(){return[...this.systemMessages,...this._history,...this._pending]}getMessagesForLLM(){return this.toLLMMessages()}getHistory(){return this._history}appendPending($){this._pending.push($)}appendUser($){this._pending.push($)}appendAssistant($){this._pending.push($)}appendToolResult($){this._pending.push($)}appendControl($,Q){if($==="system")throw Error("Cannot append system control message via appendControl. Use constructor for root system prompt.");this._pending.push(Q)}appendToHistory($){this._history.push($)}commitPending(){if(this._pending.length>0)this._history.push(...this._pending),this._pending=[]}replaceHistory($){this._history=$.filter((Q)=>!G0(Q))}writeback(){this.commitPending(),this.context.messages=this._history}get hasSystemPrompt(){return this.systemMessages.length>0}}async function y$($,Q){let Z;while(!(Z=await $.next()).done)if(Q)await Q(Z.value);return Z.value}function m0($){if($.isSubagent)return"continue";if(!$.budget||$.budget<=0)return"continue";if($.consecutiveContinuations>=3&&$.lastOutputDelta<500)return"stop";if($.usage/$.budget>=0.9)return"stop";return"continue"}function g0($){return{budget:$.budget,usage:0,consecutiveContinuations:0,lastOutputDelta:0,isSubagent:$.isSubagent??!1}}function c0($,Q,Z){return{...$,usage:$.usage+Q,lastOutputDelta:Q,consecutiveContinuations:Z?$.consecutiveContinuations+1:0}}var r=P("Agent"),M$=3;function N0($,Q,Z){if($!=="length")return{action:"none"};if(Q>=M$)return{action:"truncated"};if(m0(Z)==="stop")return r.info("[Loop] Token budget: diminishing returns detected, skipping recovery"),{action:"budget_stop"};return{action:"recover"}}var P$=[/:\s*$/,/:\s*$/,/\.\.\.\s*$/,/让我(先|来|开始|查看|检查|修复)/,/Let me (first|start|check|look|fix)/i,/I('ll| will) (now |)(create|write|edit|update|modify|fix|add|implement)/i,/我(现在就|来|要)(创建|写入|编辑|修改|修复|添加|实现)/],f$=/```[\s\S]{50,}```/,u0="请执行你提到的操作,不要只是描述。使用 Edit/Write/Bash 工具来实际修改文件。",R$=2;function U0($,Q,Z=!0){if(!$||Q>=R$)return{action:"none"};if(!Z&&f$.test($))return{action:"retry",prompt:u0};let J=$.slice(-200),V=J.match(/```/g);if(V&&V.length%2!==0)return{action:"none"};if(P$.some((G)=>G.test(J)))return{action:"retry",prompt:u0};return{action:"none"}}var i0=30000;async function A0($){try{let Z=W0.getInstance().executeStopHooks({projectDir:x(),sessionId:$.sessionId,permissionMode:$.permissionMode,reason:$.reason,abortSignal:$.abortSignal}),J,V=new Promise((z)=>{J=setTimeout(()=>z("timeout"),i0)});try{let z=await Promise.race([Z,V]);if(z==="timeout")return r.warn(`[Loop] Stop hook 超时 (${i0}ms),按 shouldStop: true 处理`),{action:"stop"};let G=z;if(!G.shouldStop)return{action:"continue",reason:G.continueReason};return{action:"stop"}}finally{clearTimeout(J)}}catch(Q){return r.warn("[Loop] Stop hook execution failed:",Q),{action:"stop"}}}var T$=0.9;async function n0($){try{let{SpecManager:Q}=await import("./chunk-jmsm3eam.js"),Z=Q.getInstance();if(!Z.isActive())return{action:"none"};let J=Z.getCurrentSpec();if(!J||J.phase!=="implementation")return{action:"none"};if($.maxTurns>0&&$.turnsCount>=$.maxTurns*T$)return r.info(`[RalphLoop] 轮次接近上限 (${$.turnsCount}/${$.maxTurns}),停止自动继续`),{action:"none"};let V=J.tasks??[],z=V.filter((K)=>K.status==="completed"||K.status==="skipped").length,G=V.length;if(z>=G)return{action:"none"};let q=V.find((K)=>K.status==="pending"||K.status==="in_progress"),W=`[Ralph Loop] Spec "${J.name}" 仍有未完成任务。
2
2
  `+`进度: ${z}/${G} 任务已完成。
3
3
  `+(q?`下一个任务: ${q.title}${q.description?` — ${q.description}`:""}
4
4
  `:"")+"请继续执行下一个未完成的任务,不要停止。";return r.info(`[RalphLoop] Spec "${J.name}" 进度 ${z}/${G},自动继续`),{action:"continue",reason:W}}catch{return{action:"none"}}}var s=P("Agent");function t($){return $.executionEngine?.getContextManager()}async function m($,Q,Z,J=null){try{let V=t($),z=typeof Z==="string"?Z.trim()!=="":Z.some((G)=>G.type==="text"?G.text.trim()!=="":!0);if(V&&Q.sessionId&&z)return await V.saveMessage(Q.sessionId,"user",Z,J,void 0,Q.subagentInfo)}catch(V){s.warn("[Loop] 保存用户消息失败:",V)}return null}async function k($,Q,Z,J){try{let V=t($);if(V&&Q.sessionId&&Z.trim())return await V.saveMessage(Q.sessionId,"assistant",Z,J,void 0,Q.subagentInfo)}catch(V){s.warn("[Loop] 保存助手消息失败:",V)}return null}async function y0($,Q,Z,J,V){try{let z=t($);if(z&&Q.sessionId)return await z.saveToolUse(Q.sessionId,Z,J,V,Q.subagentInfo)}catch(z){s.warn("[Loop] 保存工具调用失败:",z)}return null}async function S0($,Q,Z,J,V,z,G,q){try{let W=t($);if(W&&Q.sessionId)return await W.saveToolResult(Q.sessionId,Z,J,V,z,G,Q.subagentInfo,q)}catch(W){s.warn("[Loop] 保存工具结果失败:",W)}return null}async function Y0($,Q,Z,J){try{let V=t($);if(V&&Q.sessionId)return await V.saveCompaction(Q.sessionId,Z,J,null)}catch(V){s.warn("[Loop] 保存压缩数据失败:",V)}return null}function a0($,Q){if(!["TaskCreate","TaskUpdate","TaskList"].includes($.function.name)||!Q.success||!Q.llmContent&&!Q.metadata)return null;let Z=typeof Q.llmContent==="object"?Q.llmContent:{};return{kind:"task_update",tasks:Q.metadata?.tasks||Z.tasks||[]}}function l0($,Q,Z){if($.function.name!=="Skill"||!Q.success||!Q.metadata)return;let J=Q.metadata;if(J.skillName)Z.onSkillActivated?.({skillName:J.skillName,allowedTools:J.allowedTools,basePath:J.basePath||""})}function r0($){let Q=$.metadata;if(!Q)return;return Q.modelId?.toString().trim()||Q.model?.toString().trim()||void 0||void 0}async function M0($,Q,Z){let J=a0($,Q);l0($,Q,Z);let V=r0(Q);if(V)await Z.onModelSwitch?.(V);return J}import{nanoid as V3}from"nanoid";import{promises as k$}from"node:fs";import{nanoid as c}from"nanoid";import{promises as X0}from"node:fs";var e=P("Tool");class p{static instance=null;accessedFiles=new Map;constructor(){}static getInstance(){if(!p.instance)p.instance=new p;return p.instance}async recordFileRead($,Q){try{let Z=await X0.stat($),J={filePath:$,accessTime:Date.now(),mtime:Z.mtimeMs,sessionId:Q,lastOperation:"read"};this.accessedFiles.set($,J),e.debug(`记录文件读取: ${$}`)}catch(Z){e.warn(`记录文件读取失败: ${$}`,Z)}}async recordFileEdit($,Q,Z="edit"){try{let J=await X0.stat($),V={filePath:$,accessTime:Date.now(),mtime:J.mtimeMs,sessionId:Q,lastOperation:Z};this.accessedFiles.set($,V),e.debug(`记录文件${Z==="edit"?"编辑":"写入"}: ${$}`)}catch(J){e.warn(`记录文件${Z==="edit"?"编辑":"写入"}失败: ${$}`,J)}}hasFileBeenRead($,Q){let Z=this.accessedFiles.get($);if(!Z)return!1;if(Q&&Z.sessionId!==Q)return!1;return!0}async checkFileModification($){let Q=this.accessedFiles.get($);if(!Q)return{modified:!1,message:"文件未被跟踪"};try{let Z=await X0.stat($);if(Math.abs(Z.mtimeMs-Q.mtime)>1)return{modified:!0,message:`文件在访问后被修改(访问时间: ${new Date(Q.accessTime).toISOString()}, 当前修改时间: ${Z.mtime.toISOString()})`};return{modified:!1}}catch(Z){let J=Z;if(J.code==="ENOENT")return{modified:!0,message:"文件已被删除"};return{modified:!1,message:`无法检查文件状态: ${J.message}`}}}async checkExternalModification($){let Q=this.accessedFiles.get($);if(!Q)return{isExternal:!1,message:"文件未被跟踪"};try{let Z=await X0.stat($);if(Z.mtimeMs-Q.mtime>2000)return{isExternal:!0,message:`文件在 ${new Date(Q.accessTime).toISOString()} (${Q.lastOperation}) 之后被外部程序修改(当前修改时间: ${Z.mtime.toISOString()})`};return{isExternal:!1}}catch(Z){let J=Z;if(J.code==="ENOENT")return{isExternal:!0,message:"文件已被删除"};return e.warn(`检查文件外部修改失败: ${$}`,Z),{isExternal:!1,message:`无法检查文件状态: ${J.message}`}}}getFileRecord($){return this.accessedFiles.get($)}clearFileRecord($){this.accessedFiles.delete($)}clearAll(){this.accessedFiles.clear()}clearSession($){for(let[Q,Z]of this.accessedFiles.entries())if(Z.sessionId===$)this.accessedFiles.delete(Q)}getTrackedFiles(){return Array.from(this.accessedFiles.keys())}getTrackedFileCount(){return this.accessedFiles.size}static resetInstance(){p.instance=null}}import{readFile as h$}from"node:fs/promises";import{basename as x$}from"node:path";class K0{static MAX_FILES=5;static MAX_LINES_PER_FILE=1000;static analyzeFiles($){let Q=new Map;return $.forEach((J,V)=>{let z=typeof J.content==="string"?J.content:(J.content||[]).filter((q)=>q.type==="text").map((q)=>q.text).join(`
@@ -564,7 +564,7 @@ ConfigTool({
564
564
  `)}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 Q=this.pluginSkills.get($);if(Q)return Q;let Z=[];for(let J of this.pluginSkills.values())if(J.originalName===$)Z.push(J);if(Z.length===1)return Z[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 b0($){return x0.getInstance($)}async function s$($){return b0($).initialize()}var t$="Skill",e$=/<available_skills>\s*<\/available_skills>/;function k0($){let Z=b0().generateAvailableSkillsList();if(!Z)return $;return $.map((J)=>{if(J.name!==t$)return J;let V=J.description.replace(e$,`<available_skills>
565
565
  ${Z}
566
566
  </available_skills>`);if(V===J.description)return J;return{...J,description:V}})}var $3=new Set(["user-cancel","interrupt","sibling-error","timeout"]);function B$($){if(!$.aborted)return;if(typeof $.reason==="string"&&$3.has($.reason))return $.reason;return"user-cancel"}function j$(){return{consecutiveFailures:new Map,totalFailures:0,lastFailedTool:null}}function D$($,Q){$.consecutiveFailures.set(Q,0),$.lastFailedTool=null}function w$($,Q){let Z=($.consecutiveFailures.get(Q)??0)+1;$.consecutiveFailures.set(Q,Z),$.totalFailures++,$.lastFailedTool=Q}function Q3($,Q){return($.consecutiveFailures.get(Q)??0)>=3}function L$($,Q){if(!Q3($,Q))return;let Z=$.consecutiveFailures.get(Q)??0;return`WARNING: ${Q} has failed ${Z} consecutive times. Consider a different approach: use a different tool, verify your parameters, or break the task into smaller steps.`}function O$($){return $>0&&$%5===0}function b$($,Q){let Z=[`[Self-check at turn ${$}]`,"Before continuing, briefly assess:","1. Are you making progress toward the goal?","2. Have any approaches failed repeatedly that you should abandon?","3. Is there a simpler path you haven't tried?"];if(Q>3)Z.push(`Note: ${Q} tool failures so far. Consider whether your current strategy needs adjustment.`);return Z.join(`
567
- `)}var d=P("Agent"),J3=new Set(["Read","Glob","Grep","WebFetch","WebSearch","MemoryRead","GetSpecContext","ValidateSpec","TaskOutput"]);class _0{pipeline;execContext;registry;contextMgr;sessionId;lastMessageUuid;subagentInfo;pending=new Map;completed=new Map;queued=[];order=[];dispatched=new Set;abortController=new AbortController;epoch=0;activeAborts=new Map;constructor($,Q,Z,J,V,z,G){this.pipeline=$;this.execContext=Q;this.registry=Z;this.contextMgr=J;this.sessionId=V;this.lastMessageUuid=z;this.subagentInfo=G}addTool($,Q){if(this.dispatched.has($.id)){d.debug(`[StreamingToolExecutor] 跳过已分发工具: ${$.function.name} (${$.id})`);return}if(this.dispatched.add($.id),this.order.push($.id),J3.has($.function.name)){d.debug(`[StreamingToolExecutor] 立即执行预启动工具: ${$.function.name}`);let J=this.executeOne($,Q);this.pending.set($.id,J)}else d.debug(`[StreamingToolExecutor] 排队非预启动工具: ${$.function.name}`),this.queued.push({toolCall:$,params:Q})}async*getRemainingResults(){for(let $ of this.order){if(this.completed.has($)){yield this.completed.get($),this.completed.delete($);continue}if(this.pending.has($)){let Z=await this.pending.get($);this.pending.delete($),yield Z;continue}let Q=this.queued.findIndex((Z)=>Z.toolCall.id===$);if(Q!==-1){let{toolCall:Z,params:J}=this.queued[Q];if(this.queued.splice(Q,1),this.execContext.signal?.aborted){d.debug(`[StreamingToolExecutor] Signal aborted, 跳过排队工具: ${Z.function.name} (${Z.id})`),yield this.makeAbortResult(Z,"Tool execution skipped: task aborted before launch");continue}yield await this.executeOne(Z,J)}}}getCompletedResults(){let $=Array.from(this.completed.values());return this.completed.clear(),$}discard(){this.epoch++,this.abortController.abort(),this.abortController=new AbortController;for(let[,$]of this.activeAborts)$.abort();this.activeAborts.clear(),this.queued=[],this.order=[],this.dispatched.clear(),this.completed.clear(),this.pending.clear(),d.debug(`[StreamingToolExecutor] 已丢弃所有挂起工作并重置状态 (epoch=${this.epoch})`)}hasTools(){return this.order.length>0}getEpoch(){return this.epoch}makeAbortResult($,Q){return{toolCall:$,result:{success:!1,llmContent:"",error:{type:"execution_error",message:Q},metadata:{abortedBeforeLaunch:!0}},toolUseUuid:null}}async executeOne($,Q){let Z=this.epoch,J=new AbortController;this.activeAborts.set($.id,J);let V=this.abortController.signal;try{if(V.aborted||J.signal.aborted)return this.makeAbortResult($,"Tool execution aborted due to discard");let z=null;try{if(this.contextMgr&&this.sessionId)z=await this.contextMgr.saveToolUse(this.sessionId,$.function.name,Q,this.lastMessageUuid??null,this.subagentInfo)}catch(j){d.warn("[StreamingToolExecutor] 保存工具调用失败:",j)}let G=[V,J.signal],q=this.execContext.signal;if(q)G.push(q);let W=s0(...G),K={...this.execContext,signal:W},B=await this.pipeline.execute($.function.name,Q,K);if(Z!==this.epoch)return d.debug(`[StreamingToolExecutor] 丢弃旧世代工具结果: ${$.function.name} (startEpoch=${Z}, currentEpoch=${this.epoch})`),this.makeAbortResult($,"Tool execution aborted due to epoch mismatch (discard)");let D={toolCall:$,result:B,toolUseUuid:z};if(this.pending.has($.id))this.pending.delete($.id),this.completed.set($.id,D);return D}catch(z){if(Z!==this.epoch)return this.makeAbortResult($,"Tool execution aborted due to epoch mismatch (discard)");d.error(`[StreamingToolExecutor] 工具执行失败: ${$.function.name}`,z);let G={success:!1,llmContent:"",error:{type:"execution_error",message:z instanceof Error?z.message:"Unknown error"},metadata:void 0},q={toolCall:$,result:G,toolUseUuid:null,error:z instanceof Error?z:Error("Unknown error")};if(this.pending.has($.id))this.pending.delete($.id),this.completed.set($.id,q);return q}finally{this.activeAborts.delete($.id)}}}var v=P("Agent"),z3=0.1,G3=8192,q3=32768,_$=100,W3=`
567
+ `)}var d=P("Agent"),J3=new Set(["Read","Glob","Grep","WebFetch","WebSearch","MemoryRead","GetSpecContext","ValidateSpec","TaskOutput"]);class _0{pipeline;execContext;registry;contextMgr;sessionId;lastMessageUuid;subagentInfo;pending=new Map;completed=new Map;queued=[];order=[];dispatched=new Set;abortController=new AbortController;epoch=0;activeAborts=new Map;constructor($,Q,Z,J,V,z,G){this.pipeline=$;this.execContext=Q;this.registry=Z;this.contextMgr=J;this.sessionId=V;this.lastMessageUuid=z;this.subagentInfo=G}addTool($,Q){if(this.dispatched.has($.id)){d.debug(`[StreamingToolExecutor] 跳过已分发工具: ${$.function.name} (${$.id})`);return}if(this.dispatched.add($.id),this.order.push($.id),J3.has($.function.name)){d.debug(`[StreamingToolExecutor] 立即执行预启动工具: ${$.function.name}`);let J=this.executeOne($,Q);this.pending.set($.id,J)}else d.debug(`[StreamingToolExecutor] 排队非预启动工具: ${$.function.name}`),this.queued.push({toolCall:$,params:Q})}async*getRemainingResults(){for(let $ of this.order){if(this.completed.has($)){yield this.completed.get($),this.completed.delete($);continue}if(this.pending.has($)){let Z=await this.pending.get($);this.pending.delete($),yield Z;continue}let Q=this.queued.findIndex((Z)=>Z.toolCall.id===$);if(Q!==-1){let{toolCall:Z,params:J}=this.queued[Q];if(this.queued.splice(Q,1),this.execContext.signal?.aborted){d.debug(`[StreamingToolExecutor] Signal aborted, 跳过排队工具: ${Z.function.name} (${Z.id})`),yield this.makeAbortResult(Z,"Tool execution skipped: task aborted before launch");continue}yield await this.executeOne(Z,J)}}}getCompletedResults(){let $=Array.from(this.completed.values());return this.completed.clear(),$}discard(){this.epoch++,this.abortController.abort(),this.abortController=new AbortController;for(let[,$]of this.activeAborts)$.abort();this.activeAborts.clear(),this.queued=[],this.order=[],this.dispatched.clear(),this.completed.clear(),this.pending.clear(),d.debug(`[StreamingToolExecutor] 已丢弃所有挂起工作并重置状态 (epoch=${this.epoch})`)}hasTools(){return this.order.length>0}getEpoch(){return this.epoch}makeAbortResult($,Q){return{toolCall:$,result:{success:!1,llmContent:"",error:{type:"execution_error",message:Q},metadata:{abortedBeforeLaunch:!0}},toolUseUuid:null}}async executeOne($,Q){let Z=this.epoch,J=new AbortController;this.activeAborts.set($.id,J);let V=this.abortController.signal;try{if(V.aborted||J.signal.aborted)return this.makeAbortResult($,"Tool execution aborted due to discard");let z=null;try{if(this.contextMgr&&this.sessionId)z=await this.contextMgr.saveToolUse(this.sessionId,$.function.name,Q,this.lastMessageUuid??null,this.subagentInfo)}catch(j){d.warn("[StreamingToolExecutor] 保存工具调用失败:",j)}let G=[V,J.signal],q=this.execContext.signal;if(q)G.push(q);let W=s0(...G),K={...this.execContext,signal:W},B=await this.pipeline.execute($.function.name,Q,K);if(Z!==this.epoch)return d.debug(`[StreamingToolExecutor] 丢弃旧世代工具结果: ${$.function.name} (startEpoch=${Z}, currentEpoch=${this.epoch})`),this.makeAbortResult($,"Tool execution aborted due to epoch mismatch (discard)");let D={toolCall:$,result:B,toolUseUuid:z};if(this.pending.has($.id))this.pending.delete($.id),this.completed.set($.id,D);return D}catch(z){if(Z!==this.epoch)return this.makeAbortResult($,"Tool execution aborted due to epoch mismatch (discard)");d.error(`[StreamingToolExecutor] 工具执行失败: ${$.function.name}`,z);let G={success:!1,llmContent:"",error:{type:"execution_error",message:z instanceof Error?z.message:"Unknown error"},metadata:void 0},q={toolCall:$,result:G,toolUseUuid:null,error:z instanceof Error?z:Error("Unknown error")};if(this.pending.has($.id))this.pending.delete($.id),this.completed.set($.id,q);return q}finally{this.activeAborts.delete($.id)}}}var N=P("Agent"),z3=0.1,G3=8192,q3=32768,_$=100,W3=`
568
568
 
569
569
  # Task Execution Strategy
570
570
  When facing complex multi-step tasks:
@@ -572,18 +572,18 @@ When facing complex multi-step tasks:
572
572
  2. Execute one step at a time — verify each step succeeded before moving to the next.
573
573
  3. If a step fails, diagnose the root cause rather than repeating the same approach.
574
574
  4. When uncertain about file paths or project structure, use Grep/Glob/Read to gather facts first.
575
- 5. Prefer the smallest change that achieves the goal — avoid unnecessary refactoring.`;function Y3($){if(typeof $==="string")return $;try{return JSON.parse(JSON.stringify($))}catch{return String($)}}function X3($){if(!($ instanceof Error))return"未知错误";let J=$.lastError??$;if(J.responseBody)try{let q=JSON.parse(J.responseBody)?.error?.message;if(q){let W=J.statusCode?` (HTTP ${J.statusCode})`:"";return`${q}${W}`}}catch{}let V=$.message,z=V.match(/Last error:\s*(.+)$/);if(z)return z[1];return V}function K3($){if(!($ instanceof Error))return!1;return["stream not supported","streaming is not available","sse not supported","does not support streaming"].some((Z)=>$.message.toLowerCase().includes(Z.toLowerCase()))}function H3($,Q){if(!Q)return"Tool execution failed (no details).";let Z=[`Error: ${Q.message||"Unknown error"}`];if(Q.type==="validation_error")Z.push("Hint: Check the tool parameters — a required field may be missing or have the wrong type.");else if(Q.type==="permission_denied")Z.push("Hint: This operation requires user approval. Try a different approach or ask the user.");else if(Q.type==="timeout_error")Z.push("Hint: The operation timed out. Consider breaking it into smaller steps or increasing timeout.");else if(Q.type==="execution_error"){if(Q.message?.includes("ENOENT")||Q.message?.includes("no such file"))Z.push("Hint: File or directory not found. Use Glob or Grep to find the correct path first.");else if(Q.message?.includes("EACCES")||Q.message?.includes("permission"))Z.push("Hint: Permission denied. The file may be read-only or owned by another user.")}return Z.join(`
576
- `)}function F3($){if(!($ instanceof Error))return!1;let Q=$.message.toLowerCase();return Q.includes("prompt_too_long")||Q.includes("prompt is too long")||Q.includes("maximum context length")||Q.includes("request too large")||$.status===413}function B3($,Q){let Z=Q,J=Z.index??0;if(!$.has(J))$.set(J,{id:Z.id||"",name:Z.function?.name||"",arguments:""});let V=$.get(J);if(Z.id&&!V.id)V.id=Z.id;if(Z.function?.name&&!V.name)V.name=Z.function.name;if(Z.function?.arguments)V.arguments+=Z.function.arguments}function j3($){if($.size===0)return;return Array.from($.values()).filter((Q)=>Q.id&&Q.name).map((Q)=>({id:Q.id,type:"function",function:{name:Q.name,arguments:Q.arguments}}))}async function*D3($,Q,Z,J,V){let z="",G="",q,W,K=new Map;try{let B=$.chatService.streamChat(Q,Z,J),D=0;for await(let j of B){if(D++,J?.aborted)break;if(j.modelFallback){V?.discard(),z="",G="",q=void 0,W=void 0,K.clear(),D=0,yield{kind:"model_fallback"};continue}if(j.content)z+=j.content,yield{kind:"content_delta",delta:j.content};if(j.reasoningContent)G+=j.reasoningContent,yield{kind:"thinking_delta",delta:j.reasoningContent};if(j.usage)q=j.usage;if(j.toolCalls){for(let _ of j.toolCalls)if(B3(K,_),V){let F=_.index??0,y=K.get(F);if(y&&y.id&&y.name)try{let C=JSON.parse(y.arguments),M={id:y.id,type:"function",function:{name:y.name,arguments:y.arguments}},h=$.executionPipeline.getRegistry().get(y.name)?.kind;V.addTool(M,C),yield{kind:"tool_start",toolCall:M,toolKind:h}}catch{}}}if(j.finishReason){W=j.finishReason;break}}if(D===0&&!J?.aborted&&z.length===0&&K.size===0)return v.warn("[Loop] 流式响应返回0个chunk,回退到非流式模式"),V?.discard(),{...await $.chatService.chat(Q,Z,J),_nonStreamingFallback:!0};return{content:z,reasoningContent:G||void 0,toolCalls:j3(K),usage:q,finishReason:W}}catch(B){if(K3(B))return v.warn("[Loop] 流式请求失败,降级到非流式模式"),V?.discard(),{...await $.chatService.chat(Q,Z,J),_nonStreamingFallback:!0};throw B}}async function E$($,Q,Z,J,V){if(J===void 0)return v.debug(`[Loop] [轮次 ${Z}] 压缩检查: 跳过(无历史 usage 数据)`),"none";let z=F0(Q.messages),G=!1;if(z.snippedCount>0)G=!0,v.debug(`[Loop] [轮次 ${Z}] Snip 压缩: 移除 ${z.snippedCount} 轮旧工具调用,释放约 ${z.estimatedTokensFreed} tokens`);let q=$.chatService.getConfig(),W=q.model,K=q.maxContextTokens??$.config.maxContextTokens,B=q.maxOutputTokens??$.config.maxOutputTokens??Math.min(Math.max(Math.floor(K*z3),G3),q3),D=K-B,j=Math.floor(D*0.8);if(v.debug(`[Loop] [轮次 ${Z}] 压缩检查:`,{promptTokens:J,maxContextTokens:K,maxOutputTokens:B,availableForInput:D,threshold:j,shouldCompact:J>=j}),J<j){if(G)Q.messages=z.messages;return G?"snipped":"none"}v.debug(Z===0?"[Loop] 触发自动压缩":`[Loop] [轮次 ${Z}] 触发循环内自动压缩`);try{let _=G?z.messages:Q.messages,H=await i.compact(_,{trigger:"auto",modelName:W,maxContextTokens:K,apiKey:q.apiKey,baseURL:q.baseUrl,actualPreTokens:J,signal:V});if(Q.messages=H.compactedMessages,H.success)v.debug(`[Loop] [轮次 ${Z}] 压缩完成: ${H.preTokens} -> ${H.postTokens} tokens`);else v.warn(`[Loop] [轮次 ${Z}] 压缩使用降级策略: ${H.preTokens} -> ${H.postTokens} tokens`);return await Y0($,Q,H.summary,{trigger:"auto",preTokens:H.preTokens,postTokens:H.postTokens,filesIncluded:H.filesIncluded}),"compacted"}catch(_){if(g(_))return v.debug(`[Loop] [轮次 ${Z}] 压缩被中止`),"none";if(G)Q.messages=z.messages;return v.error(`[Loop] [轮次 ${Z}] 压缩失败,继续执行`,_),G?"snipped":"none"}}function u($,Q,Z,J){let V=J?B$(J):"user-cancel";return{success:!1,error:{type:"aborted",message:(V==="interrupt"?void 0:"任务已被用户中止")??"任务已中断"},metadata:{turnsCount:$,toolCallsCount:Q,duration:Date.now()-Z,abortReason:V}}}async function*w3($,Q,Z,J,V){let z=Date.now(),G=0,q=[];try{let W=$.executionPipeline.getRegistry(),K=Z.permissionMode,B=W.getFunctionDeclarationsByMode(K);B=k0(B);let D=$.applySkillToolRestrictions(B),j=j$(),_=V;if(typeof W.getDeferredToolsListing==="function"){let l=W.getDeferredToolsListing();if(l&&_)_=`${_}
575
+ 5. Prefer the smallest change that achieves the goal — avoid unnecessary refactoring.`;function Y3($){if(typeof $==="string")return $;try{return JSON.parse(JSON.stringify($))}catch{return String($)}}function X3($){if(!($ instanceof Error))return"未知错误";let J=$.lastError??$;if(J.responseBody)try{let q=JSON.parse(J.responseBody)?.error?.message;if(q){let W=J.statusCode?` (HTTP ${J.statusCode})`:"";return`${q}${W}`}}catch{}let V=$.message,z=V.match(/Last error:\s*(.+)$/);if(z)return z[1];return V}function K3($){if(!($ instanceof Error))return!1;return["stream not supported","streaming is not available","sse not supported","does not support streaming"].some((Z)=>$.message.toLowerCase().includes(Z.toLowerCase()))}function H3($,Q){if(!Q)return"Tool execution failed (no details).";let Z=[`Error: ${Q.message||"Unknown error"}`];if(Q.type==="validation_error")Z.push("Hint: Check the tool parameters — a required field may be missing or have the wrong type.");else if(Q.type==="permission_denied")Z.push("Hint: This operation requires user approval. Try a different approach or ask the user.");else if(Q.type==="timeout_error")Z.push("Hint: The operation timed out. Consider breaking it into smaller steps or increasing timeout.");else if(Q.type==="execution_error"){let J=Q.message??"";if(J.includes("ENOENT")||J.includes("no such file"))Z.push("Hint: File or directory not found. Use Glob or Grep to find the correct path first.");else if(J.includes("EACCES")||J.includes("permission"))Z.push("Hint: Permission denied. The file may be read-only or owned by another user.");else if(J.includes("not found in file")||J.includes("old_string"))Z.push(`Hint: The target text was not found. Use Read to view the current file content, then retry ${$} with the exact text.`);else if(J.includes("ENOTDIR"))Z.push("Hint: A path component is not a directory. Verify the full path with Glob.")}return Z.join(`
576
+ `)}function F3($){if(!($ instanceof Error))return!1;let Q=$.message.toLowerCase();return Q.includes("prompt_too_long")||Q.includes("prompt is too long")||Q.includes("maximum context length")||Q.includes("request too large")||$.status===413}function B3($,Q){let Z=Q,J=Z.index??0;if(!$.has(J))$.set(J,{id:Z.id||"",name:Z.function?.name||"",arguments:""});let V=$.get(J);if(Z.id&&!V.id)V.id=Z.id;if(Z.function?.name&&!V.name)V.name=Z.function.name;if(Z.function?.arguments)V.arguments+=Z.function.arguments}function j3($){if($.size===0)return;return Array.from($.values()).filter((Q)=>Q.id&&Q.name).map((Q)=>({id:Q.id,type:"function",function:{name:Q.name,arguments:Q.arguments}}))}async function*D3($,Q,Z,J,V){let z="",G="",q,W,K=new Map;try{let B=$.chatService.streamChat(Q,Z,J),D=0;for await(let j of B){if(D++,J?.aborted)break;if(j.modelFallback){V?.discard(),z="",G="",q=void 0,W=void 0,K.clear(),D=0,yield{kind:"model_fallback"};continue}if(j.content)z+=j.content,yield{kind:"content_delta",delta:j.content};if(j.reasoningContent)G+=j.reasoningContent,yield{kind:"thinking_delta",delta:j.reasoningContent};if(j.usage)q=j.usage;if(j.toolCalls){for(let _ of j.toolCalls)if(B3(K,_),V){let F=_.index??0,y=K.get(F);if(y&&y.id&&y.name)try{let C=JSON.parse(y.arguments),M={id:y.id,type:"function",function:{name:y.name,arguments:y.arguments}},h=$.executionPipeline.getRegistry().get(y.name)?.kind;V.addTool(M,C),yield{kind:"tool_start",toolCall:M,toolKind:h}}catch{}}}if(j.finishReason){W=j.finishReason;break}}if(D===0&&!J?.aborted&&z.length===0&&K.size===0)return N.warn("[Loop] 流式响应返回0个chunk,回退到非流式模式"),V?.discard(),{...await $.chatService.chat(Q,Z,J),_nonStreamingFallback:!0};return{content:z,reasoningContent:G||void 0,toolCalls:j3(K),usage:q,finishReason:W}}catch(B){if(K3(B))return N.warn("[Loop] 流式请求失败,降级到非流式模式"),V?.discard(),{...await $.chatService.chat(Q,Z,J),_nonStreamingFallback:!0};throw B}}async function E$($,Q,Z,J,V){if(J===void 0)return N.debug(`[Loop] [轮次 ${Z}] 压缩检查: 跳过(无历史 usage 数据)`),"none";let z=F0(Q.messages),G=!1;if(z.snippedCount>0)G=!0,N.debug(`[Loop] [轮次 ${Z}] Snip 压缩: 移除 ${z.snippedCount} 轮旧工具调用,释放约 ${z.estimatedTokensFreed} tokens`);let q=$.chatService.getConfig(),W=q.model,K=q.maxContextTokens??$.config.maxContextTokens,B=q.maxOutputTokens??$.config.maxOutputTokens??Math.min(Math.max(Math.floor(K*z3),G3),q3),D=K-B,j=Math.floor(D*0.8);if(N.debug(`[Loop] [轮次 ${Z}] 压缩检查:`,{promptTokens:J,maxContextTokens:K,maxOutputTokens:B,availableForInput:D,threshold:j,shouldCompact:J>=j}),J<j){if(G)Q.messages=z.messages;return G?"snipped":"none"}N.debug(Z===0?"[Loop] 触发自动压缩":`[Loop] [轮次 ${Z}] 触发循环内自动压缩`);try{let _=G?z.messages:Q.messages,H=await i.compact(_,{trigger:"auto",modelName:W,maxContextTokens:K,apiKey:q.apiKey,baseURL:q.baseUrl,actualPreTokens:J,signal:V});if(Q.messages=H.compactedMessages,H.success)N.debug(`[Loop] [轮次 ${Z}] 压缩完成: ${H.preTokens} -> ${H.postTokens} tokens`);else N.warn(`[Loop] [轮次 ${Z}] 压缩使用降级策略: ${H.preTokens} -> ${H.postTokens} tokens`);return await Y0($,Q,H.summary,{trigger:"auto",preTokens:H.preTokens,postTokens:H.postTokens,filesIncluded:H.filesIncluded}),"compacted"}catch(_){if(g(_))return N.debug(`[Loop] [轮次 ${Z}] 压缩被中止`),"none";if(G)Q.messages=z.messages;return N.error(`[Loop] [轮次 ${Z}] 压缩失败,继续执行`,_),G?"snipped":"none"}}function u($,Q,Z,J){let V=J?B$(J):"user-cancel";return{success:!1,error:{type:"aborted",message:(V==="interrupt"?void 0:"任务已被用户中止")??"任务已中断"},metadata:{turnsCount:$,toolCallsCount:Q,duration:Date.now()-Z,abortReason:V}}}async function*w3($,Q,Z,J,V){let z=Date.now(),G=0,q=[];try{let W=$.executionPipeline.getRegistry(),K=Z.permissionMode,B=W.getFunctionDeclarationsByMode(K);B=k0(B);let D=$.applySkillToolRestrictions(B),j=j$(),_=V;if(typeof W.getDeferredToolsListing==="function"){let l=W.getDeferredToolsListing();if(l&&_)_=`${_}
577
577
 
578
578
  ${l}`}if(_)_+=W3;let H=new q0(Z,_);H.appendUser({role:"user",content:Q});let F=await m($,Z,Q),y=Z.permissionMode==="yolo",C=$.runtimeOptions.maxTurns??J?.maxTurns??$.config.maxTurns??-1;if(C===0)return{success:!1,error:{type:"chat_disabled",message:"对话功能已被禁用 (maxTurns=0)"},metadata:{turnsCount:0,toolCallsCount:0,duration:0}};let M=C===-1?_$:Math.min(C,_$),T=0,h,A=0,a=0,I$=!!Z.subagentInfo,E0=g0({budget:$.currentModelMaxContextTokens,isSubagent:I$}),C0=new P0;try{while(!0){if(J?.signal?.aborted)return u(G,q.length,z,J.signal);H.writeback();let l=await E$($,Z,G,h,J?.signal);if(l!=="none"){if(l==="compacted")yield{kind:"compaction",phase:"start"},yield{kind:"compaction",phase:"end"};H.replaceHistory(Z.messages)}if(G++,C0.reset(),yield{kind:"turn_start",turn:G,maxTurns:M},J?.signal?.aborted)return u(G-1,q.length,z,J.signal);if(O$(G)&&G>1){let b=b$(G,j.totalFailures);H.appendControl("user",{role:"user",content:`
579
579
 
580
580
  <system-reminder>
581
581
  ${b}
582
- </system-reminder>`})}let p0=J?.stream!==!1,X,J0;try{if(p0)J0=new _0($.executionPipeline,{sessionId:Z.sessionId,userId:Z.userId||"default",workspaceRoot:Z.workspaceRoot||x(),signal:J?.signal,confirmationHandler:Z.confirmationHandler,permissionMode:Z.permissionMode,toolRegistry:W,deferredToolManager:W.deferredToolManager},$.executionPipeline.getRegistry(),$.executionEngine?.getContextManager(),Z.sessionId,F,Z.subagentInfo),X=yield*D3($,H.toLLMMessages(),D,J?.signal,J0);else X=await $.chatService.chat(H.toLLMMessages(),D,J?.signal)}catch(b){if(F3(b)){v.warn("[Loop] 检测到 prompt_too_long 错误,尝试反应式压缩");let Y=$.chatService.getConfig(),L=await C0.tryReactiveCompact(Z.messages,{modelName:Y.model,maxContextTokens:Y.maxContextTokens??$.config.maxContextTokens,apiKey:Y.apiKey,baseURL:Y.baseUrl,signal:J?.signal});if(L.success){Z.messages=L.messages,H.replaceHistory(Z.messages),v.info("[Loop] 反应式压缩成功,重试 LLM 调用"),G--;continue}}throw b}if(X.usage){if(X.usage.totalTokens)T+=X.usage.totalTokens;h=X.usage.promptTokens,yield{kind:"token_usage",usage:{inputTokens:X.usage.promptTokens??0,outputTokens:X.usage.completionTokens??0,totalTokens:X.usage.totalTokens??0,maxContextTokens:$.currentModelMaxContextTokens}}}let N$=X.usage?.completionTokens??0;if(E0=c0(E0,N$,A>0),J?.signal?.aborted)return u(G-1,q.length,z,J.signal);if(!p0||!!X._nonStreamingFallback){if(X.reasoningContent&&X.reasoningContent.trim())yield{kind:"thinking_delta",delta:X.reasoningContent};if(X.content&&X.content.trim())yield{kind:"content_delta",delta:X.content}}yield{kind:"stream_end"};let I0=v0(X.finishReason,A,E0);if(I0.action==="recover"){A++,v.warn(`[Loop] Max output tokens hit (recovery ${A}/3)`);let b={role:"assistant",content:X.content||"",reasoningContent:X.reasoningContent,tool_calls:X.toolCalls};H.appendToHistory(b);let Y=await k($,Z,X.content||"",F);if(Y)F=Y;let L={role:"user",content:"Output token limit hit. Resume directly — no apology, no recap. "+"Pick up mid-thought if that is where the cut happened. Break remaining work into smaller pieces."};H.appendToHistory(L);let O=await m($,Z,L.content,F);if(O)F=O;continue}if(I0.action==="truncated"||I0.action==="budget_stop"){H.appendAssistant({role:"assistant",content:X.content||"",reasoningContent:X.reasoningContent,tool_calls:X.toolCalls});let b=await k($,Z,X.content||"",F);if(b)F=b;return{success:!0,finalMessage:X.content,metadata:{turnsCount:G,toolCallsCount:q.length,duration:Date.now()-z,tokensUsed:T,outputTruncated:!0}}}if(X.finishReason!=="length")A=0;if(!X.toolCalls||X.toolCalls.length===0){let b=U0(X.content,a);if(b.action==="retry"){a++,H.appendAssistant({role:"assistant",content:X.content||"",reasoningContent:X.reasoningContent});let S=await k($,Z,X.content||"",F);if(S)F=S;let N={role:"user",content:b.prompt};H.appendControl("user",N);let f=await m($,Z,N.content,F);if(f)F=f;continue}a=0;let Y=await n0({turnsCount:G,maxTurns:M});if(Y.action==="continue"){H.appendAssistant({role:"assistant",content:X.content||"",reasoningContent:X.reasoningContent});let S=await k($,Z,X.content||"",F);if(S)F=S;let N={role:"user",content:`
582
+ </system-reminder>`})}let p0=J?.stream!==!1,X,J0;try{if(p0)J0=new _0($.executionPipeline,{sessionId:Z.sessionId,userId:Z.userId||"default",workspaceRoot:Z.workspaceRoot||x(),signal:J?.signal,confirmationHandler:Z.confirmationHandler,permissionMode:Z.permissionMode,toolRegistry:W,deferredToolManager:W.deferredToolManager},$.executionPipeline.getRegistry(),$.executionEngine?.getContextManager(),Z.sessionId,F,Z.subagentInfo),X=yield*D3($,H.toLLMMessages(),D,J?.signal,J0);else X=await $.chatService.chat(H.toLLMMessages(),D,J?.signal)}catch(b){if(F3(b)){N.warn("[Loop] 检测到 prompt_too_long 错误,尝试反应式压缩");let Y=$.chatService.getConfig(),L=await C0.tryReactiveCompact(Z.messages,{modelName:Y.model,maxContextTokens:Y.maxContextTokens??$.config.maxContextTokens,apiKey:Y.apiKey,baseURL:Y.baseUrl,signal:J?.signal});if(L.success){Z.messages=L.messages,H.replaceHistory(Z.messages),N.info("[Loop] 反应式压缩成功,重试 LLM 调用"),G--;continue}}throw b}if(X.usage){if(X.usage.totalTokens)T+=X.usage.totalTokens;h=X.usage.promptTokens,yield{kind:"token_usage",usage:{inputTokens:X.usage.promptTokens??0,outputTokens:X.usage.completionTokens??0,totalTokens:X.usage.totalTokens??0,maxContextTokens:$.currentModelMaxContextTokens}}}let v$=X.usage?.completionTokens??0;if(E0=c0(E0,v$,A>0),J?.signal?.aborted)return u(G-1,q.length,z,J.signal);if(!p0||!!X._nonStreamingFallback){if(X.reasoningContent&&X.reasoningContent.trim())yield{kind:"thinking_delta",delta:X.reasoningContent};if(X.content&&X.content.trim())yield{kind:"content_delta",delta:X.content}}yield{kind:"stream_end"};let I0=N0(X.finishReason,A,E0);if(I0.action==="recover"){A++,N.warn(`[Loop] Max output tokens hit (recovery ${A}/3)`);let b={role:"assistant",content:X.content||"",reasoningContent:X.reasoningContent,tool_calls:X.toolCalls};H.appendToHistory(b);let Y=await k($,Z,X.content||"",F);if(Y)F=Y;let L={role:"user",content:"Output token limit hit. Resume directly — no apology, no recap. "+"Pick up mid-thought if that is where the cut happened. Break remaining work into smaller pieces."};H.appendToHistory(L);let O=await m($,Z,L.content,F);if(O)F=O;continue}if(I0.action==="truncated"||I0.action==="budget_stop"){H.appendAssistant({role:"assistant",content:X.content||"",reasoningContent:X.reasoningContent,tool_calls:X.toolCalls});let b=await k($,Z,X.content||"",F);if(b)F=b;return{success:!0,finalMessage:X.content,metadata:{turnsCount:G,toolCallsCount:q.length,duration:Date.now()-z,tokensUsed:T,outputTruncated:!0}}}if(X.finishReason!=="length")A=0;if(!X.toolCalls||X.toolCalls.length===0){let b=U0(X.content,a);if(b.action==="retry"){a++,H.appendAssistant({role:"assistant",content:X.content||"",reasoningContent:X.reasoningContent});let S=await k($,Z,X.content||"",F);if(S)F=S;let v={role:"user",content:b.prompt};H.appendControl("user",v);let f=await m($,Z,v.content,F);if(f)F=f;continue}a=0;let Y=await n0({turnsCount:G,maxTurns:M});if(Y.action==="continue"){H.appendAssistant({role:"assistant",content:X.content||"",reasoningContent:X.reasoningContent});let S=await k($,Z,X.content||"",F);if(S)F=S;let v={role:"user",content:`
583
583
 
584
584
  <system-reminder>
585
585
  ${Y.reason}
586
- </system-reminder>`};H.appendControl("user",N);let f=await m($,Z,N.content,F);if(f)F=f;continue}let L=await A0({sessionId:Z.sessionId,permissionMode:Z.permissionMode,reason:X.content,abortSignal:J?.signal});if(L.action==="continue"){H.appendAssistant({role:"assistant",content:X.content||"",reasoningContent:X.reasoningContent});let S=await k($,Z,X.content||"",F);if(S)F=S;let f={role:"user",content:L.reason?`
586
+ </system-reminder>`};H.appendControl("user",v);let f=await m($,Z,v.content,F);if(f)F=f;continue}let L=await A0({sessionId:Z.sessionId,permissionMode:Z.permissionMode,reason:X.content,abortSignal:J?.signal});if(L.action==="continue"){H.appendAssistant({role:"assistant",content:X.content||"",reasoningContent:X.reasoningContent});let S=await k($,Z,X.content||"",F);if(S)F=S;let f={role:"user",content:L.reason?`
587
587
 
588
588
  <system-reminder>
589
589
  ${L.reason}
@@ -591,8 +591,8 @@ ${L.reason}
591
591
 
592
592
  <system-reminder>
593
593
  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.
594
- </system-reminder>`};H.appendControl("user",f);let U=await m($,Z,f.content,F);if(U)F=U;continue}H.appendAssistant({role:"assistant",content:X.content||"",reasoningContent:X.reasoningContent});let O=await k($,Z,X.content||"",F);if(O)F=O;return{success:!0,finalMessage:X.content,metadata:{turnsCount:G,toolCallsCount:q.length,duration:Date.now()-z,tokensUsed:T}}}H.appendAssistant({role:"assistant",content:X.content||"",reasoningContent:X.reasoningContent,tool_calls:X.toolCalls});{let b=await k($,Z,X.content||"",F);if(b)F=b}if(J?.signal?.aborted)return u(G,q.length,z,J.signal);let N0=X.toolCalls.filter((b)=>b.type==="function"),V0;if(J0?.hasTools()){v.debug(`[Loop] 使用 StreamingToolExecutor 收集 ${N0.length} 个工具结果`),V0=[];for await(let b of J0.getRemainingResults())V0.push(b)}else{for(let Y of N0){let O=W.get(Y.function.name)?.kind;yield{kind:"tool_start",toolCall:Y,toolKind:O}}let b=async(Y)=>{try{let L=JSON.parse(Y.function.arguments);if(Y.function.name==="Task"&&(typeof L.subagent_session_id!=="string"||L.subagent_session_id.length===0))L.subagent_session_id=typeof L.resume==="string"&&L.resume.length>0?L.resume:V3();let O=null;O=await y0($,Z,Y.function.name,L,F);let S=await $.executionPipeline.execute(Y.function.name,L,{sessionId:Z.sessionId,userId:Z.userId||"default",workspaceRoot:Z.workspaceRoot||x(),signal:J?.signal,confirmationHandler:Z.confirmationHandler,permissionMode:Z.permissionMode,toolRegistry:W,deferredToolManager:W.deferredToolManager});return{toolCall:Y,result:S,toolUseUuid:O}}catch(L){return v.error(`Tool execution failed for ${Y.function.name}:`,L),{toolCall:Y,result:{success:!1,llmContent:"",error:{type:"execution_error",message:L instanceof Error?L.message:"Unknown error"},metadata:void 0},toolUseUuid:null,error:L instanceof Error?L:Error("Unknown error")}}};V0=await Promise.all(N0.map(b))}let v$=new R0;for(let{toolCall:b,result:Y,toolUseUuid:L}of V0){let O=b;if(q.push(Y),Y.metadata?.abortedBeforeLaunch)return u(G,q.length,z,J?.signal);yield{kind:"tool_result",toolCall:O,result:Y};{let U=Y.metadata&&typeof Y.metadata==="object"?Y.metadata:void 0,U$=((z0)=>z0==="running"||z0==="completed"||z0==="failed"||z0==="cancelled")(U?.subagentStatus)?U.subagentStatus:"completed",A$=U&&typeof U.subagentSessionId==="string"?{subagentSessionId:U.subagentSessionId,subagentType:typeof U.subagentType==="string"?U.subagentType:O.function.name,subagentStatus:U$,subagentSummary:typeof U.subagentSummary==="string"?U.subagentSummary:void 0}:void 0,d0=await S0($,Z,O.id,O.function.name,Y.success?Y3(Y.llmContent):null,L,Y.success?void 0:Y.error?.message,A$);if(d0)F=d0}let S=await M0(O,Y,$);if(S)yield S;if(Y.success)D$(j,O.function.name);else w$(j,O.function.name);let N=Y.success?Y.llmContent||"":H3(O.function.name,Y.error);if(!Y.success){let U=L$(j,O.function.name);if(U&&typeof N==="string")N=`${N}
594
+ </system-reminder>`};H.appendControl("user",f);let U=await m($,Z,f.content,F);if(U)F=U;continue}H.appendAssistant({role:"assistant",content:X.content||"",reasoningContent:X.reasoningContent});let O=await k($,Z,X.content||"",F);if(O)F=O;return{success:!0,finalMessage:X.content,metadata:{turnsCount:G,toolCallsCount:q.length,duration:Date.now()-z,tokensUsed:T}}}H.appendAssistant({role:"assistant",content:X.content||"",reasoningContent:X.reasoningContent,tool_calls:X.toolCalls});{let b=await k($,Z,X.content||"",F);if(b)F=b}if(J?.signal?.aborted)return u(G,q.length,z,J.signal);let v0=X.toolCalls.filter((b)=>b.type==="function"),V0;if(J0?.hasTools()){N.debug(`[Loop] 使用 StreamingToolExecutor 收集 ${v0.length} 个工具结果`),V0=[];for await(let b of J0.getRemainingResults())V0.push(b)}else{for(let Y of v0){let O=W.get(Y.function.name)?.kind;yield{kind:"tool_start",toolCall:Y,toolKind:O}}let b=async(Y)=>{try{let L=JSON.parse(Y.function.arguments);if(Y.function.name==="Task"&&(typeof L.subagent_session_id!=="string"||L.subagent_session_id.length===0))L.subagent_session_id=typeof L.resume==="string"&&L.resume.length>0?L.resume:V3();let O=null;O=await y0($,Z,Y.function.name,L,F);let S=await $.executionPipeline.execute(Y.function.name,L,{sessionId:Z.sessionId,userId:Z.userId||"default",workspaceRoot:Z.workspaceRoot||x(),signal:J?.signal,confirmationHandler:Z.confirmationHandler,permissionMode:Z.permissionMode,toolRegistry:W,deferredToolManager:W.deferredToolManager});return{toolCall:Y,result:S,toolUseUuid:O}}catch(L){return N.error(`Tool execution failed for ${Y.function.name}:`,L),{toolCall:Y,result:{success:!1,llmContent:"",error:{type:"execution_error",message:L instanceof Error?L.message:"Unknown error"},metadata:void 0},toolUseUuid:null,error:L instanceof Error?L:Error("Unknown error")}}};V0=await Promise.all(v0.map(b))}let N$=new R0;for(let{toolCall:b,result:Y,toolUseUuid:L}of V0){let O=b;if(q.push(Y),Y.metadata?.abortedBeforeLaunch)return u(G,q.length,z,J?.signal);yield{kind:"tool_result",toolCall:O,result:Y};{let U=Y.metadata&&typeof Y.metadata==="object"?Y.metadata:void 0,U$=((z0)=>z0==="running"||z0==="completed"||z0==="failed"||z0==="cancelled")(U?.subagentStatus)?U.subagentStatus:"completed",A$=U&&typeof U.subagentSessionId==="string"?{subagentSessionId:U.subagentSessionId,subagentType:typeof U.subagentType==="string"?U.subagentType:O.function.name,subagentStatus:U$,subagentSummary:typeof U.subagentSummary==="string"?U.subagentSummary:void 0}:void 0,d0=await S0($,Z,O.id,O.function.name,Y.success?Y3(Y.llmContent):null,L,Y.success?void 0:Y.error?.message,A$);if(d0)F=d0}let S=await M0(O,Y,$);if(S)yield S;if(Y.success)D$(j,O.function.name);else w$(j,O.function.name);let v=Y.success?Y.llmContent||"":H3(O.function.name,Y.error);if(!Y.success){let U=L$(j,O.function.name);if(U&&typeof v==="string")v=`${v}
595
595
 
596
- ${U}`}if(typeof N==="object"&&N!==null)N=JSON.stringify(N,null,2);if(typeof N==="string")N=Z$(N,O.function.name,{messageBudget:v$});let f=typeof N==="string"?N:JSON.stringify(N);if(H.appendToolResult({role:"tool",tool_call_id:O.id,name:O.function.name,content:f}),Y.metadata?.shouldExitLoop){let U=typeof Y.llmContent==="string"?Y.llmContent:"循环已退出";return{success:Y.success,finalMessage:U,metadata:{turnsCount:G,toolCallsCount:q.length,duration:Date.now()-z,shouldExitLoop:!0,targetMode:Y.metadata?.targetMode,planContent:typeof Y.metadata?.planContent==="string"?Y.metadata.planContent:void 0}}}}if(J?.signal?.aborted)return u(G,q.length,z,J.signal);if(G>=M&&!y){if(v.info(`Warning: 达到轮次上限 ${M} 轮`),J?.onTurnLimitReached){let b=await J.onTurnLimitReached({turnsCount:G});if(b?.continue){H.writeback();try{let Y=$.chatService.getConfig(),L=await i.compact(Z.messages,{trigger:"auto",modelName:Y.model,maxContextTokens:Y.maxContextTokens??$.config.maxContextTokens,apiKey:Y.apiKey,baseURL:Y.baseUrl,actualPreTokens:h,signal:J?.signal});Z.messages=L.compactedMessages,H.replaceHistory(Z.messages);let O={role:"user",content:`This session is being continued from a previous conversation. The conversation is summarized above.
596
+ ${U}`}if(typeof v==="object"&&v!==null)v=JSON.stringify(v,null,2);if(typeof v==="string")v=Z$(v,O.function.name,{messageBudget:N$});let f=typeof v==="string"?v:JSON.stringify(v);if(H.appendToolResult({role:"tool",tool_call_id:O.id,name:O.function.name,content:f}),Y.metadata?.shouldExitLoop){let U=typeof Y.llmContent==="string"?Y.llmContent:"循环已退出";return{success:Y.success,finalMessage:U,metadata:{turnsCount:G,toolCallsCount:q.length,duration:Date.now()-z,shouldExitLoop:!0,targetMode:Y.metadata?.targetMode,planContent:typeof Y.metadata?.planContent==="string"?Y.metadata.planContent:void 0}}}}if(J?.signal?.aborted)return u(G,q.length,z,J.signal);if(G>=M&&!y){if(N.info(`Warning: 达到轮次上限 ${M} 轮`),J?.onTurnLimitReached){let b=await J.onTurnLimitReached({turnsCount:G});if(b?.continue){H.writeback();try{let Y=$.chatService.getConfig(),L=await i.compact(Z.messages,{trigger:"auto",modelName:Y.model,maxContextTokens:Y.maxContextTokens??$.config.maxContextTokens,apiKey:Y.apiKey,baseURL:Y.baseUrl,actualPreTokens:h,signal:J?.signal});Z.messages=L.compactedMessages,H.replaceHistory(Z.messages);let O={role:"user",content:`This session is being continued from a previous conversation. The conversation is summarized above.
597
597
 
598
- Please continue the conversation from where we left it off without asking the user any further questions. Continue with the last task that you were asked to work on.`};H.appendToHistory(O),await Y0($,Z,L.summary,{trigger:"auto",preTokens:L.preTokens,postTokens:L.postTokens,filesIncluded:L.filesIncluded})}catch(Y){v.error("[Loop] 压缩失败,使用降级策略:",Y);let O=H.getHistory().slice(-80);H.replaceHistory(O)}G=0;continue}return{success:!0,finalMessage:b?.reason||"已达到对话轮次上限,用户选择停止",metadata:{turnsCount:G,toolCallsCount:q.length,duration:Date.now()-z,tokensUsed:T}}}return{success:!1,error:{type:"max_turns_exceeded",message:`已达到轮次上限 (${M} 轮)。使用 --permission-mode yolo 跳过此限制。`},metadata:{turnsCount:G,toolCallsCount:q.length,duration:Date.now()-z,tokensUsed:T}}}}}finally{H.writeback()}}catch(W){if(g(W))return u(G,q.length,z,J?.signal);let K=X3(W);return v.error(`API 调用失败: ${K}`),{success:!1,error:{type:"api_error",message:K,details:W},metadata:{turnsCount:G,toolCallsCount:q.length,duration:Date.now()-z}}}}export{G$ as La,X$ as Ma,b0 as Na,s$ as Oa,p as Pa,G0 as Qa,q0 as Ra,y$ as Sa,v0 as Ta,U0 as Ua,A0 as Va,m as Wa,k as Xa,y0 as Ya,S0 as Za,Y0 as _a,a0 as $a,l0 as ab,r0 as bb,M0 as cb,$0 as db,i as eb,_0 as fb,E$ as gb,w3 as hb};
598
+ Please continue the conversation from where we left it off without asking the user any further questions. Continue with the last task that you were asked to work on.`};H.appendToHistory(O),await Y0($,Z,L.summary,{trigger:"auto",preTokens:L.preTokens,postTokens:L.postTokens,filesIncluded:L.filesIncluded})}catch(Y){N.error("[Loop] 压缩失败,使用降级策略:",Y);let O=H.getHistory().slice(-80);H.replaceHistory(O)}G=0;continue}return{success:!0,finalMessage:b?.reason||"已达到对话轮次上限,用户选择停止",metadata:{turnsCount:G,toolCallsCount:q.length,duration:Date.now()-z,tokensUsed:T}}}return{success:!1,error:{type:"max_turns_exceeded",message:`已达到轮次上限 (${M} 轮)。使用 --permission-mode yolo 跳过此限制。`},metadata:{turnsCount:G,toolCallsCount:q.length,duration:Date.now()-z,tokensUsed:T}}}}}finally{H.writeback()}}catch(W){if(g(W))return u(G,q.length,z,J?.signal);let K=X3(W);return N.error(`API 调用失败: ${K}`),{success:!1,error:{type:"api_error",message:K,details:W},metadata:{turnsCount:G,toolCallsCount:q.length,duration:Date.now()-z}}}}export{G$ as La,X$ as Ma,b0 as Na,s$ as Oa,p as Pa,G0 as Qa,q0 as Ra,y$ as Sa,N0 as Ta,U0 as Ua,A0 as Va,m as Wa,k as Xa,y0 as Ya,S0 as Za,Y0 as _a,a0 as $a,l0 as ab,r0 as bb,M0 as cb,$0 as db,i as eb,_0 as fb,E$ as gb,w3 as hb};
@@ -1,4 +1,4 @@
1
- import{p as z,q as g,r as v,s as p}from"./chunk-cwrgw7yz.js";import{t as E}from"./chunk-tz6q08jc.js";import{v as S,w as h,x as c}from"./chunk-2be9zcm4.js";import{G as w,I as F,J as y,L as x,M as C}from"./chunk-c6ay4323.js";import"./chunk-56yaw2xt.js";import"./chunk-esnkk33h.js";import"./chunk-91wsnfpn.js";import"./chunk-cj5w17y3.js";import"./chunk-j73schtj.js";import"./chunk-n2dcjqbe.js";import{Sa as O}from"./chunk-5zhx4vxz.js";import"./chunk-yddnm9n2.js";import"./chunk-p3znznzd.js";import"./chunk-9rz6rpcc.js";import{wb as H,xb as T}from"./chunk-7ycmx7c2.js";import"./chunk-set7v1rf.js";import"./chunk-j2ag7hh6.js";import bq from"yargs";import{hideBin as Uq}from"yargs/helpers";import{z as b}from"zod";import{z as Q}from"zod";var L=1,V=Q.object({event_version:Q.literal(L)}),i=V.extend({type:Q.literal("content_delta"),delta:Q.string()}),n=V.extend({type:Q.literal("thinking_delta"),delta:Q.string()}),r=V.extend({type:Q.literal("thinking"),content:Q.string()}),s=V.extend({type:Q.literal("stream_end")}),o=V.extend({type:Q.literal("content"),content:Q.string()}),a=V.extend({type:Q.literal("tool_start"),tool_name:Q.string(),summary:Q.string(),target:Q.string().optional(),tool_kind:Q.enum(["readonly","write","execute"]).optional()}),t=V.extend({type:Q.literal("tool_result"),tool_name:Q.string(),summary:Q.string(),target:Q.string().optional(),tool_kind:Q.enum(["readonly","write","execute"]).optional()}),e=V.extend({type:Q.literal("phase"),phase:Q.enum(["turn","searching","inspecting","target_hit","executing","completed"]),status:Q.enum(["ongoing","hit","done"]),message:Q.string(),turn:Q.number().optional(),tool_name:Q.string().optional(),target:Q.string().optional()}),qq=V.extend({type:Q.literal("tool_detail"),tool_name:Q.string(),detail:Q.string()}),Gq=V.extend({type:Q.literal("task_update"),tasks:Q.array(x)}),Qq=V.extend({type:Q.literal("token_usage"),input_tokens:Q.number(),output_tokens:Q.number(),total_tokens:Q.number(),max_context_tokens:Q.number()}),Xq=V.extend({type:Q.literal("compacting"),state:Q.enum(["started","completed"])}),Yq=V.extend({type:Q.literal("turn_limit"),turns_count:Q.number(),action:Q.literal("continue")}),Zq=V.extend({type:Q.literal("output"),content:Q.string(),exit_code:Q.number()}),$q=V.extend({type:Q.literal("error"),message:Q.string()}),Nq=Q.discriminatedUnion("type",[i,n,r,s,o,a,t,e,qq,Gq,Qq,Xq,Yq,Zq,$q]);function N(G,X){return{event_version:L,type:G,...X}}var Kq=b.enum(["text","jsonl"]),Aq=b.object({headless:b.boolean().optional(),message:b.string().optional(),_:b.array(b.union([b.string(),b.number()])).optional(),model:b.string().optional(),systemPrompt:b.string().optional(),appendSystemPrompt:b.string().optional(),maxTurns:b.number().int().refine((G)=>G===-1||G>0,{message:"must be -1 or a positive integer"}).optional(),permissionMode:b.nativeEnum(H).optional(),mcpConfig:b.array(b.string()).optional(),strictMcpConfig:b.boolean().optional(),sessionId:b.string().optional(),allowedTools:b.array(b.string()).optional(),disallowedTools:b.array(b.string()).optional(),continue:b.boolean().optional(),resume:b.union([b.string(),b.boolean()]).optional(),outputFormat:Kq.optional()});class d{openedThinking=!1;wroteAssistantContent=!1;markAssistantContent(){this.wroteAssistantContent=!0}setThinkingOpened(G){this.openedThinking=G}hasOpenThinking(){return this.openedThinking}completeStream(){let G={openedThinking:this.openedThinking,wroteAssistantContent:this.wroteAssistantContent};return this.openedThinking=!1,this.wroteAssistantContent=!1,G}}function Rq(G){return G.issues.map((X)=>`${X.path.join(".")||"options"}: ${X.message}`).join("; ")}function Vq(G){let X=Aq.safeParse(G);if(!X.success)throw Error(`Invalid headless options: ${Rq(X.error)}`);return X.data}function _q(G){return G.command("* [message]","Run full agent loop without Ink UI and print events to the terminal",(X)=>X.positional("message",{describe:"Message to process",type:"string"}).option("headless",{type:"boolean",describe:"Run full agent loop without Ink UI and print events to the terminal"}).option("model",{describe:"Model ID for this run",type:"string"}).option("system-prompt",{describe:"Replace the default system prompt",type:"string"}).option("append-system-prompt",{describe:"Append a system prompt to the default system prompt",type:"string"}).option("max-turns",{alias:["maxTurns"],describe:"Maximum conversation turns (-1: unlimited, N>0: limit to N turns)",type:"number"}).option("output-format",{alias:["outputFormat"],choices:["text","jsonl"],describe:"Headless output format",type:"string"}),async(X)=>{if(!X.headless)return;let Y=await Bq(X);process.exit(Y)})}function _(G,X=""){G.write(`${X}
1
+ import{p as z,q as g,r as v,s as p}from"./chunk-c9cc5nq1.js";import{t as E}from"./chunk-cwb6xkrn.js";import{v as S,w as h,x as c}from"./chunk-2be9zcm4.js";import{G as w,I as F,J as y,L as x,M as C}from"./chunk-93h1rwpj.js";import"./chunk-y5d5g2cs.js";import"./chunk-esnkk33h.js";import"./chunk-57yaytxj.js";import"./chunk-cj5w17y3.js";import"./chunk-j73schtj.js";import"./chunk-n2dcjqbe.js";import{Sa as O}from"./chunk-fr4jznsd.js";import"./chunk-yddnm9n2.js";import"./chunk-p3znznzd.js";import"./chunk-9rz6rpcc.js";import{wb as H,xb as T}from"./chunk-7ycmx7c2.js";import"./chunk-set7v1rf.js";import"./chunk-j2ag7hh6.js";import bq from"yargs";import{hideBin as Uq}from"yargs/helpers";import{z as b}from"zod";import{z as Q}from"zod";var L=1,V=Q.object({event_version:Q.literal(L)}),i=V.extend({type:Q.literal("content_delta"),delta:Q.string()}),n=V.extend({type:Q.literal("thinking_delta"),delta:Q.string()}),r=V.extend({type:Q.literal("thinking"),content:Q.string()}),s=V.extend({type:Q.literal("stream_end")}),o=V.extend({type:Q.literal("content"),content:Q.string()}),a=V.extend({type:Q.literal("tool_start"),tool_name:Q.string(),summary:Q.string(),target:Q.string().optional(),tool_kind:Q.enum(["readonly","write","execute"]).optional()}),t=V.extend({type:Q.literal("tool_result"),tool_name:Q.string(),summary:Q.string(),target:Q.string().optional(),tool_kind:Q.enum(["readonly","write","execute"]).optional()}),e=V.extend({type:Q.literal("phase"),phase:Q.enum(["turn","searching","inspecting","target_hit","executing","completed"]),status:Q.enum(["ongoing","hit","done"]),message:Q.string(),turn:Q.number().optional(),tool_name:Q.string().optional(),target:Q.string().optional()}),qq=V.extend({type:Q.literal("tool_detail"),tool_name:Q.string(),detail:Q.string()}),Gq=V.extend({type:Q.literal("task_update"),tasks:Q.array(x)}),Qq=V.extend({type:Q.literal("token_usage"),input_tokens:Q.number(),output_tokens:Q.number(),total_tokens:Q.number(),max_context_tokens:Q.number()}),Xq=V.extend({type:Q.literal("compacting"),state:Q.enum(["started","completed"])}),Yq=V.extend({type:Q.literal("turn_limit"),turns_count:Q.number(),action:Q.literal("continue")}),Zq=V.extend({type:Q.literal("output"),content:Q.string(),exit_code:Q.number()}),$q=V.extend({type:Q.literal("error"),message:Q.string()}),Nq=Q.discriminatedUnion("type",[i,n,r,s,o,a,t,e,qq,Gq,Qq,Xq,Yq,Zq,$q]);function N(G,X){return{event_version:L,type:G,...X}}var Kq=b.enum(["text","jsonl"]),Aq=b.object({headless:b.boolean().optional(),message:b.string().optional(),_:b.array(b.union([b.string(),b.number()])).optional(),model:b.string().optional(),systemPrompt:b.string().optional(),appendSystemPrompt:b.string().optional(),maxTurns:b.number().int().refine((G)=>G===-1||G>0,{message:"must be -1 or a positive integer"}).optional(),permissionMode:b.nativeEnum(H).optional(),mcpConfig:b.array(b.string()).optional(),strictMcpConfig:b.boolean().optional(),sessionId:b.string().optional(),allowedTools:b.array(b.string()).optional(),disallowedTools:b.array(b.string()).optional(),continue:b.boolean().optional(),resume:b.union([b.string(),b.boolean()]).optional(),outputFormat:Kq.optional()});class d{openedThinking=!1;wroteAssistantContent=!1;markAssistantContent(){this.wroteAssistantContent=!0}setThinkingOpened(G){this.openedThinking=G}hasOpenThinking(){return this.openedThinking}completeStream(){let G={openedThinking:this.openedThinking,wroteAssistantContent:this.wroteAssistantContent};return this.openedThinking=!1,this.wroteAssistantContent=!1,G}}function Rq(G){return G.issues.map((X)=>`${X.path.join(".")||"options"}: ${X.message}`).join("; ")}function Vq(G){let X=Aq.safeParse(G);if(!X.success)throw Error(`Invalid headless options: ${Rq(X.error)}`);return X.data}function _q(G){return G.command("* [message]","Run full agent loop without Ink UI and print events to the terminal",(X)=>X.positional("message",{describe:"Message to process",type:"string"}).option("headless",{type:"boolean",describe:"Run full agent loop without Ink UI and print events to the terminal"}).option("model",{describe:"Model ID for this run",type:"string"}).option("system-prompt",{describe:"Replace the default system prompt",type:"string"}).option("append-system-prompt",{describe:"Append a system prompt to the default system prompt",type:"string"}).option("max-turns",{alias:["maxTurns"],describe:"Maximum conversation turns (-1: unlimited, N>0: limit to N turns)",type:"number"}).option("output-format",{alias:["outputFormat"],choices:["text","jsonl"],describe:"Headless output format",type:"string"}),async(X)=>{if(!X.headless)return;let Y=await Bq(X);process.exit(Y)})}function _(G,X=""){G.write(`${X}
2
2
  `)}function Dq(G){return`[task] [${G.status}] ${G.subject}`}function Mq(){return{requestConfirmation:async(G)=>({approved:!0,reason:"headless-auto-approved",scope:"session"})}}function jq(G){if(!(G instanceof Error))return"Unknown error";let q=G.lastError??G;if(q.responseBody)try{let A=JSON.parse(q.responseBody)?.error?.message;if(A)return q.statusCode?`${A} (HTTP ${q.statusCode})`:A}catch{}let Z=G.message.match(/Last error:\s*(.+)$/);if(Z)return Z[1];return G.message}function fq(G){return G==="jsonl"?"jsonl":"text"}function W(G,X){let Y=(...q)=>{for(let Z of q){let U=X[Z];if(typeof U==="string"&&U.trim()!=="")return U}return};switch(G){case"Read":case"Edit":case"Write":case"UndoEdit":return Y("file_path");case"NotebookEdit":return Y("notebook_path");case"Grep":return Y("path","pattern");case"Glob":return Y("pattern");case"WebFetch":return Y("url");case"WebSearch":return Y("query");case"Bash":return Y("description","command");case"Task":return Y("description");case"LSP":return Y("filePath","operation");default:return}}function Pq(G,X,Y,q){let Z=new Set(["Glob","Grep","WebSearch","LS"]),U=new Set(["Read","WebFetch"]);if(new Set(["Edit","Write","NotebookEdit","Bash","LSP","UndoEdit"]).has(G)&&!q.targetLocked)return{phase:"target_hit",status:"hit",message:`Target locked: ${X}`,shouldLockTarget:!0};if(q.targetLocked)return{phase:"executing",status:"hit",message:Y?`Working within target: ${X}`:`Executing: ${X}`,shouldLockTarget:!1};if(Z.has(G))return{phase:"searching",status:"ongoing",message:`Still searching: ${X}`,shouldLockTarget:!1};if(U.has(G))return{phase:"inspecting",status:"ongoing",message:`Inspecting candidate: ${X}`,shouldLockTarget:!1};return{phase:"executing",status:q.targetLocked?"hit":"ongoing",message:`Executing: ${X}`,shouldLockTarget:!1}}function k(G,X){let Y=(q,Z)=>{G.stdout.write(`${JSON.stringify(N(q,Z))}
3
3
  `)};return{contentDelta(q){if(X==="jsonl"){Y("content_delta",{delta:q});return}G.stdout.write(q)},thinkingDelta(q,Z){if(X==="jsonl")return Y("thinking_delta",{delta:q}),Z;if(!Z)G.stderr.write("[thinking] ");return G.stderr.write(q),!0},thinking(q){if(X==="jsonl"){Y("thinking",{content:q});return}_(G.stderr,`[thinking] ${q}`)},streamEnd(q,Z){if(X==="jsonl"){Y("stream_end",{});return}if(Z)G.stderr.write(`
4
4
  `);if(q)G.stdout.write(`
@@ -1,4 +1,4 @@
1
- import{p as _,q as x,r as E,s as N}from"./chunk-cwrgw7yz.js";import{t as A}from"./chunk-tz6q08jc.js";import{v as B,w as D,x as L}from"./chunk-2be9zcm4.js";import{G as $,M as b}from"./chunk-c6ay4323.js";import"./chunk-56yaw2xt.js";import"./chunk-esnkk33h.js";import"./chunk-91wsnfpn.js";import"./chunk-cj5w17y3.js";import"./chunk-j73schtj.js";import"./chunk-n2dcjqbe.js";import{Sa as Z}from"./chunk-5zhx4vxz.js";import"./chunk-yddnm9n2.js";import"./chunk-p3znznzd.js";import"./chunk-9rz6rpcc.js";import{wb as X,xb as Y}from"./chunk-7ycmx7c2.js";import"./chunk-set7v1rf.js";import"./chunk-j2ag7hh6.js";import f from"yargs";import{hideBin as h}from"yargs/helpers";var R=new Set(Object.values(X));function W(k){if(k&&R.has(k))return k;return}function w(k){return k.command("* [message]","Print response and exit (useful for pipes)",(F)=>F.positional("message",{describe:"Message to process",type:"string"}).option("p",{alias:"print",describe:"Print response and exit (useful for pipes)",type:"boolean"}).option("output-format",{describe:'Output format: "text", "json", "stream-json"',type:"string",default:"text"}).option("include-partial-messages",{describe:"Include partial message chunks as they arrive",type:"boolean"}).option("input-format",{describe:'Input format: "text", "stream-json"',type:"string",default:"text"}).option("model",{describe:"Model for the current session",type:"string"}).option("append-system-prompt",{describe:"Append a system prompt to the default system prompt",type:"string"}).option("system-prompt",{describe:"Replace the default system prompt",type:"string"}).option("max-turns",{alias:["maxTurns"],describe:"Maximum conversation turns (-1: unlimited, N>0: limit to N turns)",type:"number"}),async(F)=>{if(!F.p)return;let q=await M(F);process.exit(q)})}async function M(k,F=process){let q;try{await _();let J=await x({message:k.message,_:k._,defaultMessage:"Hello"}),G=await E(J);if(G.mode==="output"){if(G.content)F.stdout.write(`${G.content}
1
+ import{p as _,q as x,r as E,s as N}from"./chunk-c9cc5nq1.js";import{t as A}from"./chunk-cwb6xkrn.js";import{v as B,w as D,x as L}from"./chunk-2be9zcm4.js";import{G as $,M as b}from"./chunk-93h1rwpj.js";import"./chunk-y5d5g2cs.js";import"./chunk-esnkk33h.js";import"./chunk-57yaytxj.js";import"./chunk-cj5w17y3.js";import"./chunk-j73schtj.js";import"./chunk-n2dcjqbe.js";import{Sa as Z}from"./chunk-fr4jznsd.js";import"./chunk-yddnm9n2.js";import"./chunk-p3znznzd.js";import"./chunk-9rz6rpcc.js";import{wb as X,xb as Y}from"./chunk-7ycmx7c2.js";import"./chunk-set7v1rf.js";import"./chunk-j2ag7hh6.js";import f from"yargs";import{hideBin as h}from"yargs/helpers";var R=new Set(Object.values(X));function W(k){if(k&&R.has(k))return k;return}function w(k){return k.command("* [message]","Print response and exit (useful for pipes)",(F)=>F.positional("message",{describe:"Message to process",type:"string"}).option("p",{alias:"print",describe:"Print response and exit (useful for pipes)",type:"boolean"}).option("output-format",{describe:'Output format: "text", "json", "stream-json"',type:"string",default:"text"}).option("include-partial-messages",{describe:"Include partial message chunks as they arrive",type:"boolean"}).option("input-format",{describe:'Input format: "text", "stream-json"',type:"string",default:"text"}).option("model",{describe:"Model for the current session",type:"string"}).option("append-system-prompt",{describe:"Append a system prompt to the default system prompt",type:"string"}).option("system-prompt",{describe:"Replace the default system prompt",type:"string"}).option("max-turns",{alias:["maxTurns"],describe:"Maximum conversation turns (-1: unlimited, N>0: limit to N turns)",type:"number"}),async(F)=>{if(!F.p)return;let q=await M(F);process.exit(q)})}async function M(k,F=process){let q;try{await _();let J=await x({message:k.message,_:k._,defaultMessage:"Hello"}),G=await E(J);if(G.mode==="output"){if(G.content)F.stdout.write(`${G.content}
2
2
  `);return G.exitCode??0}let Q=G.content,{sessionId:K,messages:T}=await N({sessionId:k.sessionId,continue:k.continue,resume:k.resume,fallbackSessionPrefix:"print"});q=await $.create({sessionId:K,modelId:k.model,mcpConfig:k.mcpConfig,strictMcpConfig:k.strictMcpConfig});let U=await b.createWithRuntime(q,{sessionId:K,systemPrompt:k.systemPrompt,appendSystemPrompt:k.appendSystemPrompt,maxTurns:k.maxTurns,modelId:k.model,permissionMode:W(k.permissionMode),toolWhitelist:k.allowedTools,toolBlacklist:k.disallowedTools,mcpConfig:k.mcpConfig,strictMcpConfig:k.strictMcpConfig}),H=(await Z(U.chatStream(Q,{messages:[...T],userId:"cli-user",sessionId:K,workspaceRoot:Y(),permissionMode:W(k.permissionMode)}))).finalMessage||"";if(k.outputFormat==="json")F.stdout.write(`${JSON.stringify({response:H,input:Q,model:k.model,timestamp:new Date().toISOString()},null,2)}
3
3
  `);else if(k.outputFormat==="stream-json")F.stdout.write(`${JSON.stringify({type:"response",content:H})}
4
4
  `);else F.stdout.write(`${H}
@@ -0,0 +1 @@
1
+ import{t as a,u as b}from"./chunk-cwb6xkrn.js";import"./chunk-57yaytxj.js";import"./chunk-j2ag7hh6.js";export{a as globalOptions,b as cliConfig};
@@ -1,4 +1,4 @@
1
- import{ba as S,ca as h}from"./chunk-91wsnfpn.js";import{kb as M}from"./chunk-yddnm9n2.js";import{Db as c}from"./chunk-j2ag7hh6.js";import{EventEmitter as r}from"events";import{z as L}from"zod";import{isPlainObject as v}from"lodash-es";function b(B){if(B===void 0)return"undefined";if(typeof B==="string")return B;try{let G=JSON.stringify(B);return G===void 0?String(B):G}catch{return String(B)}}class R extends Error{issues;type;constructor(B,G,Q="validation_error"){super(B);this.issues=G;this.type=Q;this.name="ToolValidationError"}}function g(B){let{code:G}=B,Q=B,X=Q.received;switch(G){case"invalid_type":{let Y=Q.expected;return`类型错误:期望 ${b(Y)},实际收到 ${b(X)}`}case"too_small":{let{minimum:Y,inclusive:$}=Q,W=typeof Q.type==="string"?Q.type:void 0;if(W==="string"&&typeof Y==="number")return`长度不能少于 ${Y} 个字符`;if(W==="number"&&typeof Y==="number")return`不能小于${$?"等于":""} ${Y}`;if(W==="array"&&typeof Y==="number")return`数组长度不能少于 ${Y}`;return"值太小"}case"too_big":{let{maximum:Y,inclusive:$}=Q,W=typeof Q.type==="string"?Q.type:void 0;if(W==="string"&&typeof Y==="number")return`长度不能超过 ${Y} 个字符`;if(W==="number"&&typeof Y==="number")return`不能大于${$?"等于":""} ${Y}`;if(W==="array"&&typeof Y==="number")return`数组长度不能超过 ${Y}`;return"值太大"}case"invalid_string":{let Y=Q.validation;if(Y==="email")return"必须是有效的电子邮件地址";if(Y==="url")return"必须是有效的 URL";if(Y==="uuid")return"必须是有效的 UUID";if(v(Y)){let $=Y;if(typeof $.includes==="string")return`必须包含 "${$.includes}"`;if(typeof $.startsWith==="string")return`必须以 "${$.startsWith}" 开头`;if(typeof $.endsWith==="string")return`必须以 "${$.endsWith}" 结尾`}return"字符串格式不正确"}case"invalid_enum_value":{let Y=Q.options;if(Array.isArray(Y))return`必须是以下值之一:${Y.map(($)=>b($)).join(", ")}`;return"必须是枚举允许的值之一"}case"invalid_literal":{let Y=Q.expected;return`必须是字面量值:${b(Y)}`}case"unrecognized_keys":{let Y=Q.keys;if(Array.isArray(Y))return`包含未知的参数:${Y.map(($)=>b($)).join(", ")}`;return"包含未知的参数"}case"invalid_union":return"不符合任何有效的类型定义";case"invalid_date":return"必须是有效的日期";case"custom":return B.message||"自定义验证失败";default:return B.message||"验证失败"}}function u(B){let G=B.issues.map((X)=>{let Y=X.path.join("."),$=g(X),W=X.received;return{field:Y||"root",message:$,value:W}}),Q=G.length===1?`参数验证失败 [${G[0].field}]: ${G[0].message}`:`参数验证失败 (${G.length} 个错误):
1
+ import{ba as S,ca as h}from"./chunk-57yaytxj.js";import{kb as M}from"./chunk-yddnm9n2.js";import{Db as c}from"./chunk-j2ag7hh6.js";import{EventEmitter as r}from"events";import{z as L}from"zod";import{isPlainObject as v}from"lodash-es";function b(B){if(B===void 0)return"undefined";if(typeof B==="string")return B;try{let G=JSON.stringify(B);return G===void 0?String(B):G}catch{return String(B)}}class R extends Error{issues;type;constructor(B,G,Q="validation_error"){super(B);this.issues=G;this.type=Q;this.name="ToolValidationError"}}function g(B){let{code:G}=B,Q=B,X=Q.received;switch(G){case"invalid_type":{let Y=Q.expected;return`类型错误:期望 ${b(Y)},实际收到 ${b(X)}`}case"too_small":{let{minimum:Y,inclusive:$}=Q,W=typeof Q.type==="string"?Q.type:void 0;if(W==="string"&&typeof Y==="number")return`长度不能少于 ${Y} 个字符`;if(W==="number"&&typeof Y==="number")return`不能小于${$?"等于":""} ${Y}`;if(W==="array"&&typeof Y==="number")return`数组长度不能少于 ${Y}`;return"值太小"}case"too_big":{let{maximum:Y,inclusive:$}=Q,W=typeof Q.type==="string"?Q.type:void 0;if(W==="string"&&typeof Y==="number")return`长度不能超过 ${Y} 个字符`;if(W==="number"&&typeof Y==="number")return`不能大于${$?"等于":""} ${Y}`;if(W==="array"&&typeof Y==="number")return`数组长度不能超过 ${Y}`;return"值太大"}case"invalid_string":{let Y=Q.validation;if(Y==="email")return"必须是有效的电子邮件地址";if(Y==="url")return"必须是有效的 URL";if(Y==="uuid")return"必须是有效的 UUID";if(v(Y)){let $=Y;if(typeof $.includes==="string")return`必须包含 "${$.includes}"`;if(typeof $.startsWith==="string")return`必须以 "${$.startsWith}" 开头`;if(typeof $.endsWith==="string")return`必须以 "${$.endsWith}" 结尾`}return"字符串格式不正确"}case"invalid_enum_value":{let Y=Q.options;if(Array.isArray(Y))return`必须是以下值之一:${Y.map(($)=>b($)).join(", ")}`;return"必须是枚举允许的值之一"}case"invalid_literal":{let Y=Q.expected;return`必须是字面量值:${b(Y)}`}case"unrecognized_keys":{let Y=Q.keys;if(Array.isArray(Y))return`包含未知的参数:${Y.map(($)=>b($)).join(", ")}`;return"包含未知的参数"}case"invalid_union":return"不符合任何有效的类型定义";case"invalid_date":return"必须是有效的日期";case"custom":return B.message||"自定义验证失败";default:return B.message||"验证失败"}}function u(B){let G=B.issues.map((X)=>{let Y=X.path.join("."),$=g(X),W=X.received;return{field:Y||"root",message:$,value:W}}),Q=G.length===1?`参数验证失败 [${G[0].field}]: ${G[0].message}`:`参数验证失败 (${G.length} 个错误):
2
2
  ${G.map((X)=>` - ${X.field}: ${X.message}`).join(`
3
3
  `)}`;return new R(Q,G)}function y(B,G){let Q=B.safeParse(G);if(!Q.success)throw u(Q.error);return Q.data}import{zodToJsonSchema as l}from"zod-to-json-schema";function H(B){let G=l(B,{target:"jsonSchema7",$refStrategy:"none"});if(G.type==="object"&&G.properties&&!Array.isArray(G.required))G.required=[];return G}class w{toolName;params;executeFn;descriptionFn;affectedPathsFn;constructor(B,G,Q,X,Y){this.toolName=B;this.params=G;this.executeFn=Q;this.descriptionFn=X;this.affectedPathsFn=Y}getDescription(){if(this.descriptionFn)return this.descriptionFn(this.params);return`执行工具: ${this.toolName}`}getAffectedPaths(){if(this.affectedPathsFn)return this.affectedPathsFn(this.params);return[]}async execute(B,G,Q){let X={signal:B,updateOutput:G,...Q};return this.executeFn(this.params,X)}}function k(B){return{name:B.name,displayName:B.displayName,kind:B.kind,isReadOnly:B.isReadOnly??M(B.kind),isConcurrencySafe:B.isConcurrencySafe??!1,strict:B.strict??!1,description:B.description,version:B.version||"1.0.0",category:B.category,tags:B.tags||[],getFunctionDeclaration(){let G=H(B.schema),Q=B.description.short;if(B.description.long)Q+=`
4
4
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "blade-code",
3
- "version": "0.5.0",
3
+ "version": "0.5.1",
4
4
  "private": false,
5
5
  "description": "🗡️ Blade Code - 智能代码助手命令行工具",
6
6
  "type": "module",
@@ -1 +0,0 @@
1
- import{t as a,u as b}from"./chunk-tz6q08jc.js";import"./chunk-91wsnfpn.js";import"./chunk-j2ag7hh6.js";export{a as globalOptions,b as cliConfig};