blade-code 0.5.0 → 0.5.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/blade.js +2 -2
- package/dist/{chunk-8x1q3vwk.js → chunk-0wnfkb8d.js} +2 -2
- package/dist/{chunk-202egebq.js → chunk-1a46066d.js} +1 -1
- package/dist/{chunk-91wsnfpn.js → chunk-2jtsf34p.js} +1 -1
- package/dist/{chunk-tz6q08jc.js → chunk-3naaq2ja.js} +1 -1
- package/dist/{chunk-6cx876s5.js → chunk-5nsz499s.js} +1 -1
- package/dist/{chunk-pp1y3ffx.js → chunk-6p67rccg.js} +1 -1
- package/dist/{chunk-csme56h3.js → chunk-9ps80ba3.js} +1 -1
- package/dist/{chunk-j16cr4bf.js → chunk-9symwryt.js} +2 -2
- package/dist/{chunk-c6ay4323.js → chunk-ax1tyzb9.js} +123 -123
- package/dist/{chunk-n9ffrfe8.js → chunk-bnrmmbes.js} +1 -1
- package/dist/{chunk-5zhx4vxz.js → chunk-cybgk58q.js} +17 -17
- package/dist/{chunk-56yaw2xt.js → chunk-hqk3sgqq.js} +1 -1
- package/dist/{chunk-cwrgw7yz.js → chunk-kwhsrpzc.js} +1 -1
- package/dist/{chunk-hbyrtx4b.js → chunk-rfm11em7.js} +1 -1
- package/dist/chunk-shb198ys.js +1 -0
- package/dist/{chunk-x7dzvenm.js → chunk-st14tav8.js} +1 -1
- package/dist/{chunk-1bjte98q.js → chunk-xxv4r2s8.js} +1 -1
- package/package.json +1 -1
- package/dist/chunk-5fw10kfn.js +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as y,b as A,c as C,d as D}from"./chunk-
|
|
1
|
+
import{a as y,b as A,c as C,d as D}from"./chunk-6p67rccg.js";import"./chunk-z0ktwnc4.js";import"./chunk-ax1tyzb9.js";import"./chunk-hqk3sgqq.js";import"./chunk-esnkk33h.js";import"./chunk-2jtsf34p.js";import"./chunk-cj5w17y3.js";import{Aa as q}from"./chunk-j73schtj.js";import"./chunk-n2dcjqbe.js";import"./chunk-cybgk58q.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,12 +1,12 @@
|
|
|
1
|
-
import{nb as W0}from"./chunk-p3znznzd.js";import{rb as
|
|
1
|
+
import{nb as W0}from"./chunk-p3znznzd.js";import{rb as e0}from"./chunk-9rz6rpcc.js";import{xb as h}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:h(),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
|
-
`:"")+"请继续执行下一个未完成的任务,不要停止。";return r.info(`[RalphLoop] Spec "${J.name}" 进度 ${z}/${G},自动继续`),{action:"continue",reason:W}}catch{return{action:"none"}}}var s=P("Agent");function
|
|
4
|
+
`:"")+"请继续执行下一个未完成的任务,不要停止。";return r.info(`[RalphLoop] Spec "${J.name}" 进度 ${z}/${G},自动继续`),{action:"continue",reason:W}}catch{return{action:"none"}}}var s=P("Agent");function e($){return $.executionEngine?.getContextManager()}async function m($,Q,Z,J=null){try{let V=e($),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=e($);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=e($);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=e($);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=e($);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}function x$($,Q){if($.function.name!=="Task")return null;let Z=Q.metadata;if(!Z?.subagentSessionId)return null;let J=Z.subagentSessionId,V=Z.subagentType||"Task",z=Z.subagentStatus;if(z==="completed"||z==="failed"||z==="cancelled")return{kind:"subagent_completed",sessionId:J,success:z==="completed",summary:Z.subagentSummary};if(z==="running"){let G="";try{G=JSON.parse($.function.arguments).prompt||""}catch{}return{kind:"subagent_spawned",sessionId:J,type:V,prompt:G}}return null}async function M0($,Q,Z){let J=a0($,Q),V=x$($,Q);l0($,Q,Z);let z=r0(Q);if(z)await Z.onModelSwitch?.(z);return V||J}import{nanoid as z3}from"nanoid";import{promises as C$}from"node:fs";import{nanoid as c}from"nanoid";import{promises as X0}from"node:fs";var t=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),t.debug(`记录文件读取: ${$}`)}catch(Z){t.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),t.debug(`记录文件${Z==="edit"?"编辑":"写入"}: ${$}`)}catch(J){t.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 t.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 k$}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(`
|
|
5
5
|
`);if(this.extractFilePathsFromContent(z).forEach((q)=>{this.updateFileReference(Q,q,V,!1)}),J.tool_calls&&Array.isArray(J.tool_calls))J.tool_calls.forEach((q)=>{let W=this.extractFilePathsFromToolCall(q),K=q.type==="function"&&"function"in q?q.function?.name:"",B=["Write","Edit"].includes(K||"");W.forEach((D)=>{this.updateFileReference(Q,D,V,B)})})}),Array.from(Q.values()).sort((J,V)=>{if(J.wasModified!==V.wasModified)return J.wasModified?-1:1;if(J.mentions!==V.mentions)return V.mentions-J.mentions;return V.lastMentioned-J.lastMentioned}).slice(0,this.MAX_FILES)}static async readFilesContent($){let Q=[];for(let Z of $)try{let J=await h$(Z,"utf-8"),V=J.split(`
|
|
6
6
|
`),z=V.length,G=J,q=!1,W=z;if(z>this.MAX_LINES_PER_FILE)G=V.slice(0,this.MAX_LINES_PER_FILE).join(`
|
|
7
7
|
`),G+=`
|
|
8
8
|
|
|
9
|
-
... (truncated ${z-this.MAX_LINES_PER_FILE} lines)`,q=!0,W=this.MAX_LINES_PER_FILE;Q.push({path:Z,content:G,truncated:q,lines:z,includedLines:W})}catch(J){console.warn(`[FileAnalyzer] 无法读取文件: ${Z}`,J)}return Q}static extractFilePathsFromContent($){let Q=new Set,Z=/```(?:\w+)?\s*\n?([\s\S]*?)```/g,J=Array.from($.matchAll(Z));for(let z of J){let G=z[1];this.extractPathsFromText(G).forEach((W)=>Q.add(W))}return this.extractPathsFromText($).forEach((z)=>Q.add(z)),Array.from(Q)}static extractPathsFromText($){let Q=[],Z=[/(?:src|tests?|docs?|lib|config|scripts?|bin|utils?|components?|services?|hooks?)\/[\w\-/.]+\.[\w]+/g,/(?:package|tsconfig|vite\.config|webpack\.config|next\.config|babel\.config)\.[\w]+/g,/(?:\.\.?\/|\/)[a-zA-Z0-9\-_/.]+\.[\w]+/g];for(let J of Z){let V=Array.from($.matchAll(J));for(let z of V){let G=z[0];if(G=G.replace(/[,。;:!?""''()【】《》]$/g,""),G=G.replace(/[,.;:!?"'()[\]<>]$/g,""),this.isValidFilePath(G))Q.push(G)}}return Q}static extractFilePathsFromToolCall($){let Q=[];if($.type!=="function"||!$.function)return Q;try{let Z=$.function.name,J=JSON.parse($.function.arguments||"{}");if(["Read","Write","Edit","Glob","Grep","NotebookEdit","mcp__github__get_file_contents","mcp__github__create_or_update_file"].includes(Z)){let z=["file_path","path","notebook_path","filePath"];for(let G of z)if(J[G]&&typeof J[G]==="string")Q.push(J[G])}}catch{}return Q}static updateFileReference($,Q,Z,J){let V=$.get(Q);if(V)V.mentions++,V.lastMentioned=Z,V.wasModified=V.wasModified||J;else $.set(Q,{path:Q,mentions:1,lastMentioned:Z,wasModified:J})}static isValidFilePath($){if(!$.includes("/"))return!1;let Q=
|
|
9
|
+
... (truncated ${z-this.MAX_LINES_PER_FILE} lines)`,q=!0,W=this.MAX_LINES_PER_FILE;Q.push({path:Z,content:G,truncated:q,lines:z,includedLines:W})}catch(J){console.warn(`[FileAnalyzer] 无法读取文件: ${Z}`,J)}return Q}static extractFilePathsFromContent($){let Q=new Set,Z=/```(?:\w+)?\s*\n?([\s\S]*?)```/g,J=Array.from($.matchAll(Z));for(let z of J){let G=z[1];this.extractPathsFromText(G).forEach((W)=>Q.add(W))}return this.extractPathsFromText($).forEach((z)=>Q.add(z)),Array.from(Q)}static extractPathsFromText($){let Q=[],Z=[/(?:src|tests?|docs?|lib|config|scripts?|bin|utils?|components?|services?|hooks?)\/[\w\-/.]+\.[\w]+/g,/(?:package|tsconfig|vite\.config|webpack\.config|next\.config|babel\.config)\.[\w]+/g,/(?:\.\.?\/|\/)[a-zA-Z0-9\-_/.]+\.[\w]+/g];for(let J of Z){let V=Array.from($.matchAll(J));for(let z of V){let G=z[0];if(G=G.replace(/[,。;:!?""''()【】《》]$/g,""),G=G.replace(/[,.;:!?"'()[\]<>]$/g,""),this.isValidFilePath(G))Q.push(G)}}return Q}static extractFilePathsFromToolCall($){let Q=[];if($.type!=="function"||!$.function)return Q;try{let Z=$.function.name,J=JSON.parse($.function.arguments||"{}");if(["Read","Write","Edit","Glob","Grep","NotebookEdit","mcp__github__get_file_contents","mcp__github__create_or_update_file"].includes(Z)){let z=["file_path","path","notebook_path","filePath"];for(let G of z)if(J[G]&&typeof J[G]==="string")Q.push(J[G])}}catch{}return Q}static updateFileReference($,Q,Z,J){let V=$.get(Q);if(V)V.mentions++,V.lastMentioned=Z,V.wasModified=V.wasModified||J;else $.set(Q,{path:Q,mentions:1,lastMentioned:Z,wasModified:J})}static isValidFilePath($){if(!$.includes("/"))return!1;let Q=k$($);if(!Q.includes("."))return!1;let Z=["ts","tsx","js","jsx","json","md","py","java","go","rs","c","cpp","h","css","scss","html","xml","yaml","yml","toml","sh","bash","sql","graphql","vue","svelte"],J=Q.split(".").pop()?.toLowerCase();if(!J||!Z.includes(J))return!1;return!0}}import{encodingForModel as o0}from"js-tiktoken";class $0{static encodingCache=new Map;static countTokens($,Q){let Z=this.getEncoding(Q),J=0;for(let V of $){if(J+=4,V.role)J+=Z.encode(V.role).length;if(V.content)if(typeof V.content==="string")J+=Z.encode(V.content).length;else J+=Z.encode(JSON.stringify(V.content)).length;if(V.tool_calls&&Array.isArray(V.tool_calls))J+=this.countToolCallTokens(V.tool_calls,Z);if(V.name)J+=Z.encode(V.name).length}return J}static getTokenLimit($){return $}static shouldCompact($,Q,Z,J=0.8){let V=this.countTokens($,Q),z=Math.floor(Z*J);return V>=z}static getEncoding($){if(!this.encodingCache.has($))try{let Q=o0($);this.encodingCache.set($,Q)}catch{try{let Q=o0("gpt-4");this.encodingCache.set($,Q)}catch{console.warn(`[TokenCounter] 无法为模型 ${$} 获取 encoding,使用粗略估算`),this.encodingCache.set($,{encode:(Q)=>{return Array(Math.ceil(Q.length/4))}})}}return this.encodingCache.get($)}static countToolCallTokens($,Q){let Z=0;for(let J of $){if(Z+=4,J.type==="function"&&J.function?.name)Z+=Q.encode(J.function.name).length;if(J.type==="function"&&J.function?.arguments)Z+=Q.encode(J.function.arguments).length;if(J.id)Z+=Q.encode(J.id).length}return Z}static clearCache(){this.encodingCache.clear()}static estimateTokens($){let Q=($.match(/[\u4e00-\u9fa5]/g)||[]).length,Z=$.length-Q;return Math.ceil(Q/1.5+Z/4)}}function g($){if(!($ instanceof Error))return!1;if($.name==="AbortError")return!0;if($ instanceof DOMException&&$.name==="AbortError")return!0;if($.message.includes("aborted"))return!0;return!1}function s0(...$){let Q=$.filter(Boolean);if(Q.length===0)return new AbortController().signal;if(Q.length===1)return Q[0];let Z=AbortSignal;if(typeof Z.any==="function")return Z.any(Q);for(let z of Q)if(z.aborted)return z;let J=new AbortController,V=new Map;for(let z of Q){let G=()=>{J.abort(z.reason);for(let[q,W]of V)q.removeEventListener("abort",W)};V.set(z,G)}for(let[z,G]of V)z.addEventListener("abort",G,{once:!0});return J.signal}var H0=new Map,p$=3;class i{static THRESHOLD_PERCENT=0.8;static RETAIN_PERCENT=0.2;static FALLBACK_RETAIN_PERCENT=0.3;static async compact($,Q){if(Q.signal?.aborted)throw new DOMException("Aborted","AbortError");let Z=Q.actualPreTokens??$0.countTokens($,Q.modelName),J=Q.actualPreTokens?"actual (from LLM usage)":"estimated";console.log(`[CompactionService] preTokens source: ${J}`);try{let q=await W0.getInstance().executeCompactionHooks(Q.trigger,{projectDir:h(),sessionId:Q.sessionId||"unknown",permissionMode:Q.permissionMode||"default",messagesBefore:$.length,tokensBefore:Z});if(q.blockCompaction)return console.log(`[CompactionService] Compaction hook 阻止压缩: ${q.blockReason||"(无原因)"}`),{success:!1,summary:"",preTokens:Z,postTokens:Z,filesIncluded:[],compactedMessages:$,boundaryMessage:{role:"system",content:""},summaryMessage:{role:"user",content:""},error:q.blockReason||"Compaction blocked by hook"};if(q.warning)console.warn(`[CompactionService] Compaction hook warning: ${q.warning}`)}catch(G){console.warn("[CompactionService] Compaction hook execution failed:",G)}let V=Q.sessionId??"_default",z=H0.get(V)??0;if(z>=p$)return console.warn(`[CompactionService] Circuit breaker open (${z} consecutive failures for session ${V}), using fallback`),this.fallbackCompact($,Q,Z,Error("Circuit breaker open"));try{console.log("[CompactionService] 开始压缩,消息数:",$.length),console.log("[CompactionService] 压缩前 tokens:",Z);let q=K0.analyzeFiles($).map((A)=>A.path);console.log("[CompactionService] 提取重点文件:",q);let W=await K0.readFilesContent(q);console.log("[CompactionService] 成功读取文件:",W.length);let K=await this.generateSummary($,W,Q);console.log("[CompactionService] 生成总结,长度:",K.length);let B=Math.ceil($.length*this.RETAIN_PERCENT),D=$.slice(-B),j=new Set;for(let A of D)if(A.role==="assistant"&&A.tool_calls)for(let a of A.tool_calls)j.add(a.id);let _=D.filter((A)=>{if(A.role==="tool"&&A.tool_call_id)return j.has(A.tool_call_id);return!0});console.log("[CompactionService] 保留消息数:",B),console.log("[CompactionService] 过滤后保留消息数:",_.length);let H=c(),F=this.createBoundaryMessage(H,Q.trigger,Z),y=c(),C=this.createSummaryMessage(y,K),M=[C,..._],T=await this.buildFileRestorationMessage();if(T)M.push(T);let x=$0.countTokens(M,Q.modelName);return console.log("[CompactionService] 压缩完成!"),console.log("[CompactionService] Token 变化:",Z,"->",x,`(-${((1-x/Z)*100).toFixed(1)}%)`),H0.delete(V),{success:!0,summary:K,preTokens:Z,postTokens:x,filesIncluded:q,compactedMessages:M,boundaryMessage:F,summaryMessage:C}}catch(G){if(g(G))throw G;return H0.set(V,(H0.get(V)??0)+1),console.error("[CompactionService] 压缩失败,使用降级策略",G),this.fallbackCompact($,Q,Z,G)}}static async generateSummary($,Q,Z){let J=this.buildCompactionPrompt($,Q);if(console.log("[CompactionService] 使用压缩模型:",Z.modelName),Z.signal?.aborted)throw new DOMException("Aborted","AbortError");let G=(await(await e0({apiKey:Z.apiKey||process.env.BLADE_API_KEY||"",baseUrl:Z.baseURL||process.env.BLADE_BASE_URL||"https://api.openai.com/v1",model:Z.modelName,temperature:0.3,maxOutputTokens:8000,timeout:60000,provider:"openai-compatible"})).chat([{role:"user",content:J}],[],Z.signal)).content||"",q=G.match(/<summary>([\s\S]*?)<\/summary>/);if(!q)return console.warn("[CompactionService] 总结格式不正确,使用完整响应"),G;return q[1].trim()}static buildCompactionPrompt($,Q){let Z=$.map((z,G)=>{let q=z.role||"unknown",W=typeof z.content==="string"?z.content:JSON.stringify(z.content),K=5000,B=W.length>5000?W.substring(0,5000)+"...":W;return`[${G+1}] ${q}: ${B}`}).join(`
|
|
10
10
|
|
|
11
11
|
`),J=Q.map((z)=>{return`### ${z.path}
|
|
12
12
|
\`\`\`
|
|
@@ -79,7 +79,7 @@ ${Q.length>0?`## Important Files
|
|
|
79
79
|
|
|
80
80
|
${J}`:""}
|
|
81
81
|
|
|
82
|
-
Please provide your summary following the structure specified above, with both <analysis> and <summary> sections.`}static createBoundaryMessage($,Q,Z){return{id:c(),role:"system",content:"Conversation compacted",metadata:{type:"system",subtype:"compact_boundary",parentId:$,compactMetadata:{trigger:Q,preTokens:Z}}}}static createSummaryMessage($,Q){return{id:c(),role:"user",content:Q,metadata:{parentId:$,isCompactSummary:!0}}}static getRecentlyAccessedFiles($){let Q=p.getInstance();return Q.getTrackedFiles().map((V)=>({filePath:V,record:Q.getFileRecord(V)})).filter((V)=>V.record!==void 0).sort((V,z)=>z.record.accessTime-V.record.accessTime).slice(0,$).map((V)=>V.filePath)}static async buildFileRestorationMessage(){let $=this.getRecentlyAccessedFiles(5);if($.length===0)return null;let Q=[];for(let J of $)try{let z=(await
|
|
82
|
+
Please provide your summary following the structure specified above, with both <analysis> and <summary> sections.`}static createBoundaryMessage($,Q,Z){return{id:c(),role:"system",content:"Conversation compacted",metadata:{type:"system",subtype:"compact_boundary",parentId:$,compactMetadata:{trigger:Q,preTokens:Z}}}}static createSummaryMessage($,Q){return{id:c(),role:"user",content:Q,metadata:{parentId:$,isCompactSummary:!0}}}static getRecentlyAccessedFiles($){let Q=p.getInstance();return Q.getTrackedFiles().map((V)=>({filePath:V,record:Q.getFileRecord(V)})).filter((V)=>V.record!==void 0).sort((V,z)=>z.record.accessTime-V.record.accessTime).slice(0,$).map((V)=>V.filePath)}static async buildFileRestorationMessage(){let $=this.getRecentlyAccessedFiles(5);if($.length===0)return null;let Q=[];for(let J of $)try{let z=(await C$.readFile(J,"utf-8")).split(`
|
|
83
83
|
`),G=z.slice(0,200).join(`
|
|
84
84
|
`),q=z.length>200?`
|
|
85
85
|
... (${z.length-200} more lines)`:"";Q.push(`<file path="${J}" lines="${z.length}">
|
|
@@ -92,14 +92,14 @@ An error occurred during compaction. Retained the latest ${V} messages (~30%).
|
|
|
92
92
|
Error: ${B}
|
|
93
93
|
|
|
94
94
|
The conversation can continue, but consider retrying compaction later with /compact.`),_=[j,...q],H=$0.countTokens(_,Q.modelName);return{success:!1,summary:typeof j.content==="string"?j.content:j.content.filter((F)=>F.type==="text").map((F)=>F.text).join(`
|
|
95
|
-
`),preTokens:Z,postTokens:H,filesIncluded:[],compactedMessages:_,boundaryMessage:K,summaryMessage:j,error:B}}}function F0($,Q){let Z=Q?.keepRecentTurns??10,J=Q?.minMessagesForSnip??30;if($.length<J)return{messages:$,snippedCount:0,estimatedTokensFreed:0};let V=[];for(let B=0;B<$.length;B++){let D=$[B];if(D.role==="assistant"&&D.tool_calls&&D.tool_calls.length>0){let j=new Set(D.tool_calls.map((H)=>H.id)),_=[];for(let H=B+1;H<$.length;H++){let F=$[H];if(F.role==="tool"&&F.tool_call_id&&j.has(F.tool_call_id))_.push(H);if(F.role==="assistant"||F.role==="user")break}V.push({assistantIdx:B,toolResultIdxs:_})}}let z=V.slice(0,Math.max(0,V.length-Z));if(z.length===0)return{messages:$,snippedCount:0,estimatedTokensFreed:0};let G=new Set,q=0;for(let B of z){G.add(B.assistantIdx);for(let D of B.toolResultIdxs)G.add(D)}for(let B of G){let D=$[B],j=typeof D.content==="string"?D.content:JSON.stringify(D.content);if(q+=j.length,D.tool_calls)q+=JSON.stringify(D.tool_calls).length}let W=[],K=!1;for(let B=0;B<$.length;B++){if(G.has(B)){if(!K)W.push({role:"system",content:`[${z.length} earlier tool interaction${z.length===1?"":"s"} snipped for brevity]`}),K=!0;continue}W.push($[B])}return{messages:W,snippedCount:z.length,estimatedTokensFreed:Math.floor(q/4)}}class P0{hasAttempted=!1;async tryReactiveCompact($,Q){if(this.hasAttempted)return{success:!1,messages:$};this.hasAttempted=!0;let Z=F0($,{keepRecentTurns:3,minMessagesForSnip:10}),J=Z.messages;try{let V=await i.compact(J,{trigger:"auto",modelName:Q.modelName,maxContextTokens:Q.maxContextTokens,apiKey:Q.apiKey,baseURL:Q.baseURL,signal:Q.signal});if(V.success)return{success:!0,messages:V.compactedMessages};if(Z.snippedCount>0)return{success:!0,messages:J};return{success:!1,messages:$}}catch(V){if(g(V))throw V;if(Z.snippedCount>0)return{success:!0,messages:J};return{success:!1,messages:$}}}reset(){this.hasAttempted=!1}}import*as n from"fs";import*as f0 from"os";import*as Q0 from"path";import{nanoid as Q$}from"nanoid";var
|
|
95
|
+
`),preTokens:Z,postTokens:H,filesIncluded:[],compactedMessages:_,boundaryMessage:K,summaryMessage:j,error:B}}}function F0($,Q){let Z=Q?.keepRecentTurns??10,J=Q?.minMessagesForSnip??30;if($.length<J)return{messages:$,snippedCount:0,estimatedTokensFreed:0};let V=[];for(let B=0;B<$.length;B++){let D=$[B];if(D.role==="assistant"&&D.tool_calls&&D.tool_calls.length>0){let j=new Set(D.tool_calls.map((H)=>H.id)),_=[];for(let H=B+1;H<$.length;H++){let F=$[H];if(F.role==="tool"&&F.tool_call_id&&j.has(F.tool_call_id))_.push(H);if(F.role==="assistant"||F.role==="user")break}V.push({assistantIdx:B,toolResultIdxs:_})}}let z=V.slice(0,Math.max(0,V.length-Z));if(z.length===0)return{messages:$,snippedCount:0,estimatedTokensFreed:0};let G=new Set,q=0;for(let B of z){G.add(B.assistantIdx);for(let D of B.toolResultIdxs)G.add(D)}for(let B of G){let D=$[B],j=typeof D.content==="string"?D.content:JSON.stringify(D.content);if(q+=j.length,D.tool_calls)q+=JSON.stringify(D.tool_calls).length}let W=[],K=!1;for(let B=0;B<$.length;B++){if(G.has(B)){if(!K)W.push({role:"system",content:`[${z.length} earlier tool interaction${z.length===1?"":"s"} snipped for brevity]`}),K=!0;continue}W.push($[B])}return{messages:W,snippedCount:z.length,estimatedTokensFreed:Math.floor(q/4)}}class P0{hasAttempted=!1;async tryReactiveCompact($,Q){if(this.hasAttempted)return{success:!1,messages:$};this.hasAttempted=!0;let Z=F0($,{keepRecentTurns:3,minMessagesForSnip:10}),J=Z.messages;try{let V=await i.compact(J,{trigger:"auto",modelName:Q.modelName,maxContextTokens:Q.maxContextTokens,apiKey:Q.apiKey,baseURL:Q.baseURL,signal:Q.signal});if(V.success)return{success:!0,messages:V.compactedMessages};if(Z.snippedCount>0)return{success:!0,messages:J};return{success:!1,messages:$}}catch(V){if(g(V))throw V;if(Z.snippedCount>0)return{success:!0,messages:J};return{success:!1,messages:$}}}reset(){this.hasAttempted=!1}}import*as n from"fs";import*as f0 from"os";import*as Q0 from"path";import{nanoid as Q$}from"nanoid";var d$=1e5,m$=2000,t0=200000;class R0{currentChars=0;track($){this.currentChars+=$}remaining(){return Math.max(0,t0-this.currentChars)}isExhausted(){return this.currentChars>=t0}reset(){this.currentChars=0}}function Z$($,Q,Z){let J=Z?.maxCharsPerResult??d$,V=Z?.previewChars??m$,z=Z?.messageBudget,G=typeof $==="string"?$:JSON.stringify($,null,2);if(G.length<=J)return g$($,G,Q,V,z,Z);let q=Z?.outputDir??Q0.join(f0.homedir(),".blade","tool-results"),W=`${Q}-${Q$(8)}.txt`,K=Q0.join(q,W);try{n.mkdirSync(q,{recursive:!0}),n.writeFileSync(K,G,"utf-8")}catch{let j=G.slice(0,J)+`
|
|
96
96
|
|
|
97
97
|
... (truncated, ${G.length} total chars)`;if(z)z.track(j.length);return j}let B=G.slice(0,V),D=`Result too large (${G.length} chars). Full output saved to: ${K}
|
|
98
98
|
|
|
99
99
|
Preview:
|
|
100
100
|
${B}
|
|
101
101
|
|
|
102
|
-
... (${G.length-V} more chars in file)`;if(z)z.track(D.length);return D}function
|
|
102
|
+
... (${G.length-V} more chars in file)`;if(z)z.track(D.length);return D}function g$($,Q,Z,J,V,z){if(!V)return $;let G=V.remaining();if(G<=0){let q=Q.slice(0,J),W=$$(Q,q,Z,z,"[Message budget exhausted. Full output saved to disk.]");return V.track(typeof W==="string"?W.length:J),W}if(Q.length>G){let q=Math.max(J,G),W=Q.slice(0,q),K=$$(Q,W,Z,z,`... (truncated by message budget, ${Q.length} total chars)`);return V.track(typeof K==="string"?K.length:q),K}return V.track(Q.length),$}function $$($,Q,Z,J,V){let z=J?.outputDir??Q0.join(f0.homedir(),".blade","tool-results"),G=`${Z}-${Q$(8)}.txt`,q=Q0.join(z,G);try{return n.mkdirSync(z,{recursive:!0}),n.writeFileSync(q,$,"utf-8"),`${Q}
|
|
103
103
|
|
|
104
104
|
${V}
|
|
105
105
|
Full output saved to: ${q}`}catch{return`${Q}
|
|
@@ -560,11 +560,11 @@ ConfigTool({
|
|
|
560
560
|
2. **permissions 字段使用 replace 策略**:设置 permissions 会完全替换现有值。如果只想添加规则,先 GET 当前值,合并后再 SET
|
|
561
561
|
3. **env 字段使用 deep-merge 策略**:可以逐个添加环境变量
|
|
562
562
|
4. **scope 默认值**:不指定 scope 时,根据字段路由表决定(hooks/permissions/env 默认 local,temperature/theme 等默认 global)
|
|
563
|
-
`}}import{exec as
|
|
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
|
|
563
|
+
`}}import{exec as c$}from"node:child_process";import*as w from"node:fs/promises";import{homedir as u$}from"node:os";import*as I from"node:path";import{promisify as i$}from"node:util";var D0=i$(c$),E=P("General"),T0={url:"https://github.com/anthropics/skills.git",branch:"main",defaultSkills:["skill-creator"]};class z${skillsDir;constructor($){this.skillsDir=$||I.join(u$(),".blade","skills")}async isInstalled($){let Q=I.join(this.skillsDir,$,"SKILL.md");try{return await w.access(Q),!0}catch{return!1}}async isGitAvailable(){try{return await D0("git --version"),!0}catch{return!1}}async installOfficialSkill($){let{url:Q,branch:Z}=T0,J=I.join(this.skillsDir,$),V=I.join(this.skillsDir,`.tmp-${$}-${Date.now()}`);try{if(!await this.isGitAvailable())return E.warn("Git not available, skipping skill installation"),!1;E.info(`Installing official skill: ${$}...`),await w.mkdir(this.skillsDir,{recursive:!0,mode:493}),await D0(`git clone --depth 1 --branch ${Z} --single-branch ${Q} "${V}"`,{timeout:30000});let z=I.join(V,"skills",$);try{await w.access(z)}catch{return E.warn(`Skill ${$} not found in official repository`),await w.rm(V,{recursive:!0,force:!0}),!1}try{await w.rm(J,{recursive:!0,force:!0})}catch{}return await w.cp(z,J,{recursive:!0}),await w.rm(V,{recursive:!0,force:!0}),E.info(`Successfully installed: ${$}`),!0}catch(z){try{await w.rm(V,{recursive:!0,force:!0})}catch{}return E.warn(`Failed to install ${$}: ${z instanceof Error?z.message:"Unknown error"}`),!1}}async ensureDefaultSkillsInstalled(){await w.mkdir(this.skillsDir,{recursive:!0,mode:493});for(let $ of T0.defaultSkills)if(!await this.isInstalled($))await this.installOfficialSkill($)}async installFromRepo($,Q){let Z=Q||this.extractRepoName($),J=I.join(this.skillsDir,Z),V=I.join(this.skillsDir,`.tmp-repo-${Z}-${Date.now()}`);try{if(!await this.isGitAvailable())return E.warn("Git not available, cannot install from repo"),!1;E.info(`Installing skill from repo: ${$}...`),await w.mkdir(this.skillsDir,{recursive:!0,mode:493}),await D0(`git clone --depth 1 "${$}" "${V}"`,{timeout:60000});let z=I.join(V,"SKILL.md");try{await w.access(z)}catch{return E.warn(`No SKILL.md found in repository ${$}`),await w.rm(V,{recursive:!0,force:!0}),!1}await w.rm(J,{recursive:!0,force:!0}),await w.rename(V,J);try{await w.rm(I.join(J,".git"),{recursive:!0,force:!0})}catch{}return E.info(`Successfully installed skill from repo: ${Z}`),!0}catch(z){try{await w.rm(V,{recursive:!0,force:!0})}catch{}return E.warn(`Failed to install from repo ${$}: ${z instanceof Error?z.message:"Unknown error"}`),!1}}async installFromLocal($,Q,Z=!0){let J=Q||I.basename($),V=I.join(this.skillsDir,J);try{let z=I.resolve($);try{await w.access(z)}catch{return E.warn(`Local path does not exist: ${z}`),!1}let G=I.join(z,"SKILL.md");try{await w.access(G)}catch{return E.warn(`No SKILL.md found in local path: ${z}`),!1}if(E.info(`Installing skill from local path: ${z}...`),await w.mkdir(this.skillsDir,{recursive:!0,mode:493}),await w.rm(V,{recursive:!0,force:!0}),Z)await w.symlink(z,V,"dir"),E.info(`Created symlink for skill: ${J}`);else await w.cp(z,V,{recursive:!0}),E.info(`Copied skill to: ${J}`);return!0}catch(z){return E.warn(`Failed to install from local path ${$}: ${z instanceof Error?z.message:"Unknown error"}`),!1}}extractRepoName($){return $.match(/\/([^/]+?)(\.git)?$/)?.[1]||"unknown-skill"}async installAllOfficialSkills(){let{url:$,branch:Q}=T0,Z=I.join(this.skillsDir,`.tmp-all-${Date.now()}`),J=[],V=[];try{if(!await this.isGitAvailable())return E.warn("Git not available, skipping skill installation"),{installed:J,failed:V};await w.mkdir(this.skillsDir,{recursive:!0,mode:493}),E.info("Cloning official skills repository..."),await D0(`git clone --depth 1 --branch ${Q} --single-branch ${$} "${Z}"`,{timeout:60000});let z=I.join(Z,"skills"),G=await w.readdir(z,{withFileTypes:!0});for(let q of G){if(!q.isDirectory())continue;let W=q.name,K=I.join(z,W),B=I.join(this.skillsDir,W);try{await w.access(I.join(K,"SKILL.md")),await w.rm(B,{recursive:!0,force:!0}),await w.cp(K,B,{recursive:!0}),E.info(`Installed: ${W}`),J.push(W)}catch(D){E.warn(`Failed to install ${W}`),V.push(W)}}await w.rm(Z,{recursive:!0,force:!0})}catch(z){try{await w.rm(Z,{recursive:!0,force:!0})}catch{}E.warn(`Failed to install skills: ${z instanceof Error?z.message:"Unknown error"}`)}return{installed:J,failed:V}}}var x0=null;function G$($){if(!x0)x0=new z$($);return x0}import*as Z0 from"node:fs/promises";import*as w0 from"node:path";import{parse as n$}from"yaml";var a$=/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/,l$=/^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]?$/,q$=1024;function r$($){if(!$)return;if(typeof $==="string")return $.split(",").map((Q)=>Q.trim()).filter(Boolean);if(Array.isArray($))return $.map((Q)=>String(Q).trim()).filter(Boolean);return}function W$($){if($===void 0)return;if(typeof $==="boolean")return $;if(typeof $==="string"){let Q=$.toLowerCase().trim();if(Q==="true"||Q==="yes"||Q==="1")return!0;if(Q==="false"||Q==="no"||Q==="0")return!1}return}function o$($,Q){if(!$.name)return{valid:!1,error:"Missing required field: name"};if(!l$.test($.name))return{valid:!1,error:`Invalid name "${$.name}": must be lowercase letters, numbers, and hyphens only, 1-64 characters`};if(!$.description)return{valid:!1,error:"Missing required field: description"};if($.description.length>q$)return{valid:!1,error:`Description too long: ${$.description.length} characters (max ${q$})`};let Z;if($.model)Z=$.model==="inherit"?"inherit":$.model;return{valid:!0,metadata:{name:$.name,description:$.description.trim(),allowedTools:r$($["allowed-tools"]),version:$.version,argumentHint:$["argument-hint"]?.trim(),userInvocable:W$($["user-invocable"]),disableModelInvocation:W$($["disable-model-invocation"]),model:Z,whenToUse:$.when_to_use?.trim()}}}function Y$($,Q,Z){let J=$.match(a$);if(!J)return{success:!1,error:"Invalid SKILL.md format: missing YAML frontmatter (must start with ---)"};let[,V,z]=J,G;try{G=n$(V)}catch(K){return{success:!1,error:`Failed to parse YAML frontmatter: ${K instanceof Error?K.message:String(K)}`}}let q=o$(G,Q);if(!q.valid)return{success:!1,error:q.error};let W=w0.dirname(Q);return{success:!0,content:{metadata:{...q.metadata,path:Q,basePath:W,source:Z},instructions:z.trim()}}}async function X$($,Q){try{let Z=await Z0.readFile($,"utf-8");return Y$(Z,$,Q)}catch(Z){if(Z.code==="ENOENT")return{success:!1,error:`File not found: ${$}`};return{success:!1,error:`Failed to read file: ${Z instanceof Error?Z.message:String(Z)}`}}}async function K$($){try{let Q=await Z0.readFile($.path,"utf-8"),Z=Y$(Q,$.path,$.source);return Z.success?Z.content:null}catch{return null}}async function H$($){try{return await Z0.access(w0.join($,"SKILL.md")),!0}catch{return!1}}var s$={userSkillsDir:R.join(F$(),".blade","skills"),projectSkillsDir:".blade/skills",claudeUserSkillsDir:R.join(F$(),".claude","skills"),claudeProjectSkillsDir:".claude/skills"},L0=null;class h0{skills=new Map;pluginSkills=new Map;config;initialized=!1;constructor($){this.config={...s$,cwd:h(),...$}}static getInstance($){if(!L0)L0=new h0($);return L0}static resetInstance(){L0=null}async initialize(){if(this.initialized)return{skills:Array.from(this.skills.values()),errors:[]};let $=[],Q=[];try{await G$(this.config.userSkillsDir).ensureDefaultSkillsInstalled()}catch(W){$.push({path:"SkillInstaller",error:`Failed to install default skills: ${W instanceof Error?W.message:"Unknown error"}`})}this.loadBuiltinSkills();let Z=await this.scanDirectory(this.config.claudeUserSkillsDir,"user");Q.push(...Z.skills),$.push(...Z.errors);let J=await this.scanDirectory(this.config.userSkillsDir,"user");Q.push(...J.skills),$.push(...J.errors);let V=R.isAbsolute(this.config.claudeProjectSkillsDir)?this.config.claudeProjectSkillsDir:R.join(this.config.cwd,this.config.claudeProjectSkillsDir),z=await this.scanDirectory(V,"project");Q.push(...z.skills),$.push(...z.errors);let G=R.isAbsolute(this.config.projectSkillsDir)?this.config.projectSkillsDir:R.join(this.config.cwd,this.config.projectSkillsDir),q=await this.scanDirectory(G,"project");Q.push(...q.skills),$.push(...q.errors);for(let W of Q)this.skills.set(W.name,W);return this.initialized=!0,{skills:Array.from(this.skills.values()),errors:$}}loadBuiltinSkills(){this.skills.set(B0.name,B0),this.skills.set(j0.name,j0)}async scanDirectory($,Q){let Z=[],J=[];try{await O0.access($)}catch{return{skills:Z,errors:J}}try{let V=await O0.readdir($,{withFileTypes:!0});for(let z of V){if(!z.isDirectory())continue;let G=R.join($,z.name),q=R.join(G,"SKILL.md");if(!await H$(G))continue;let W=await X$(q,Q);if(W.success&&W.content)Z.push(W.content.metadata);else J.push({path:q,error:W.error||"Unknown error"})}}catch(V){J.push({path:$,error:`Failed to scan directory: ${V instanceof Error?V.message:String(V)}`})}return{skills:Z,errors:J}}getAll(){return Array.from(this.skills.values())}get($){return this.skills.get($)}has($){return this.skills.has($)}async loadContent($){let Q=this.skills.get($);if(!Q)return null;if(Q.source==="builtin")return this.loadBuiltinContent($);return K$(Q)}loadBuiltinContent($){switch($){case"skill-creator":return J$();case"update-config":return V$();default:return null}}getModelInvocableSkills(){return Array.from(this.skills.values()).filter(($)=>!$.disableModelInvocation)}getUserInvocableSkills(){return Array.from(this.skills.values()).filter(($)=>$.userInvocable===!0)}generateAvailableSkillsList(){let $=this.getModelInvocableSkills();if($.length===0)return"";let Q=[];for(let Z of $){let J=Z.description.length>100?`${Z.description.substring(0,97)}...`:Z.description,V=Z.argumentHint?`${Z.name} ${Z.argumentHint}`:Z.name;Q.push(`- ${V}: ${J}`)}return Q.join(`
|
|
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 h0.getInstance($)}async function e$($){return b0($).initialize()}var t$="Skill",$3=/<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($3,`<available_skills>
|
|
565
565
|
${Z}
|
|
566
|
-
</available_skills>`);if(V===J.description)return J;return{...J,description:V}})}var
|
|
567
|
-
`)}var d=P("Agent"),
|
|
566
|
+
</available_skills>`);if(V===J.description)return J;return{...J,description:V}})}var Q3=new Set(["user-cancel","interrupt","sibling-error","timeout"]);function B$($){if(!$.aborted)return;if(typeof $.reason==="string"&&Q3.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 Z3($,Q){return($.consecutiveFailures.get(Q)??0)>=3}function L$($,Q){if(!Z3($,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"),V3=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),V3.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"),G3=0.1,q3=8192,W3=32768,_$=100,Y3=`
|
|
568
568
|
|
|
569
569
|
# Task Execution Strategy
|
|
570
570
|
When facing complex multi-step tasks:
|
|
@@ -572,14 +572,14 @@ 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
|
|
576
|
-
`)}function
|
|
575
|
+
5. Prefer the smallest change that achieves the goal — avoid unnecessary refactoring.`;function X3($){if(typeof $==="string")return $;try{return JSON.parse(JSON.stringify($))}catch{return String($)}}function K3($){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 H3($){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 F3($,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 B3($){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 j3($,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 D3($){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*w3($,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(j3(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}},x=$.executionPipeline.getRegistry().get(y.name)?.kind;V.addTool(M,C),yield{kind:"tool_start",toolCall:M,toolKind:x}}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:D3(K),usage:q,finishReason:W}}catch(B){if(H3(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*G3),q3),W3),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*L3($,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
|
-
${l}`}if(_)_+=
|
|
578
|
+
${l}`}if(_)_+=Y3;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,x,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,x,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||
|
|
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||h(),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*w3($,H.toLLMMessages(),D,J?.signal,J0);else X=await $.chatService.chat(H.toLLMMessages(),D,J?.signal)}catch(b){if(B3(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;x=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:`
|
|
583
583
|
|
|
584
584
|
<system-reminder>
|
|
585
585
|
${Y.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:
|
|
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:z3();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||h(),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?X3(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||"":F3(O.function.name,Y.error);if(!Y.success){let U=L$(j,O.function.name);if(U&&typeof N==="string")N=`${N}
|
|
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:
|
|
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:x,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=
|
|
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=K3(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,e$ 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,L3 as hb};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{ba as S,ca as h}from"./chunk-
|
|
1
|
+
import{ba as S,ca as h}from"./chunk-2jtsf34p.js";import{kb as M}from"./chunk-yddnm9n2.js";import{Db as c}from"./chunk-j2ag7hh6.js";import{EventEmitter as r}from"events";import{z as L}from"zod";import{isPlainObject as v}from"lodash-es";function b(B){if(B===void 0)return"undefined";if(typeof B==="string")return B;try{let G=JSON.stringify(B);return G===void 0?String(B):G}catch{return String(B)}}class R extends Error{issues;type;constructor(B,G,Q="validation_error"){super(B);this.issues=G;this.type=Q;this.name="ToolValidationError"}}function g(B){let{code:G}=B,Q=B,X=Q.received;switch(G){case"invalid_type":{let Y=Q.expected;return`类型错误:期望 ${b(Y)},实际收到 ${b(X)}`}case"too_small":{let{minimum:Y,inclusive:$}=Q,W=typeof Q.type==="string"?Q.type:void 0;if(W==="string"&&typeof Y==="number")return`长度不能少于 ${Y} 个字符`;if(W==="number"&&typeof Y==="number")return`不能小于${$?"等于":""} ${Y}`;if(W==="array"&&typeof Y==="number")return`数组长度不能少于 ${Y}`;return"值太小"}case"too_big":{let{maximum:Y,inclusive:$}=Q,W=typeof Q.type==="string"?Q.type:void 0;if(W==="string"&&typeof Y==="number")return`长度不能超过 ${Y} 个字符`;if(W==="number"&&typeof Y==="number")return`不能大于${$?"等于":""} ${Y}`;if(W==="array"&&typeof Y==="number")return`数组长度不能超过 ${Y}`;return"值太大"}case"invalid_string":{let Y=Q.validation;if(Y==="email")return"必须是有效的电子邮件地址";if(Y==="url")return"必须是有效的 URL";if(Y==="uuid")return"必须是有效的 UUID";if(v(Y)){let $=Y;if(typeof $.includes==="string")return`必须包含 "${$.includes}"`;if(typeof $.startsWith==="string")return`必须以 "${$.startsWith}" 开头`;if(typeof $.endsWith==="string")return`必须以 "${$.endsWith}" 结尾`}return"字符串格式不正确"}case"invalid_enum_value":{let Y=Q.options;if(Array.isArray(Y))return`必须是以下值之一:${Y.map(($)=>b($)).join(", ")}`;return"必须是枚举允许的值之一"}case"invalid_literal":{let Y=Q.expected;return`必须是字面量值:${b(Y)}`}case"unrecognized_keys":{let Y=Q.keys;if(Array.isArray(Y))return`包含未知的参数:${Y.map(($)=>b($)).join(", ")}`;return"包含未知的参数"}case"invalid_union":return"不符合任何有效的类型定义";case"invalid_date":return"必须是有效的日期";case"custom":return B.message||"自定义验证失败";default:return B.message||"验证失败"}}function u(B){let G=B.issues.map((X)=>{let Y=X.path.join("."),$=g(X),W=X.received;return{field:Y||"root",message:$,value:W}}),Q=G.length===1?`参数验证失败 [${G[0].field}]: ${G[0].message}`:`参数验证失败 (${G.length} 个错误):
|
|
2
2
|
${G.map((X)=>` - ${X.field}: ${X.message}`).join(`
|
|
3
3
|
`)}`;return new R(Q,G)}function y(B,G){let Q=B.safeParse(G);if(!Q.success)throw u(Q.error);return Q.data}import{zodToJsonSchema as l}from"zod-to-json-schema";function H(B){let G=l(B,{target:"jsonSchema7",$refStrategy:"none"});if(G.type==="object"&&G.properties&&!Array.isArray(G.required))G.required=[];return G}class w{toolName;params;executeFn;descriptionFn;affectedPathsFn;constructor(B,G,Q,X,Y){this.toolName=B;this.params=G;this.executeFn=Q;this.descriptionFn=X;this.affectedPathsFn=Y}getDescription(){if(this.descriptionFn)return this.descriptionFn(this.params);return`执行工具: ${this.toolName}`}getAffectedPaths(){if(this.affectedPathsFn)return this.affectedPathsFn(this.params);return[]}async execute(B,G,Q){let X={signal:B,updateOutput:G,...Q};return this.executeFn(this.params,X)}}function k(B){return{name:B.name,displayName:B.displayName,kind:B.kind,isReadOnly:B.isReadOnly??M(B.kind),isConcurrencySafe:B.isConcurrencySafe??!1,strict:B.strict??!1,description:B.description,version:B.version||"1.0.0",category:B.category,tags:B.tags||[],getFunctionDeclaration(){let G=H(B.schema),Q=B.description.short;if(B.description.long)Q+=`
|
|
4
4
|
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{N as l,O as c,P as m,S as g,U as d}from"./chunk-
|
|
1
|
+
import{N as l,O as c,P as m,S as g,U as d}from"./chunk-ax1tyzb9.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{p as _,q as x,r as E,s as N}from"./chunk-
|
|
1
|
+
import{p as _,q as x,r as E,s as N}from"./chunk-kwhsrpzc.js";import{t as A}from"./chunk-3naaq2ja.js";import{v as B,w as D,x as L}from"./chunk-2be9zcm4.js";import{G as $,M as b}from"./chunk-ax1tyzb9.js";import"./chunk-hqk3sgqq.js";import"./chunk-esnkk33h.js";import"./chunk-2jtsf34p.js";import"./chunk-cj5w17y3.js";import"./chunk-j73schtj.js";import"./chunk-n2dcjqbe.js";import{Sa as Z}from"./chunk-cybgk58q.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-3naaq2ja.js";import"./chunk-2jtsf34p.js";import"./chunk-j2ag7hh6.js";export{a as globalOptions,b as cliConfig};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{Y as O}from"./chunk-
|
|
1
|
+
import{Y as O}from"./chunk-hqk3sgqq.js";import"./chunk-2jtsf34p.js";import{Ea as J,Ga as L}from"./chunk-j73schtj.js";import"./chunk-n2dcjqbe.js";import"./chunk-yddnm9n2.js";import{xb as H}from"./chunk-7ycmx7c2.js";import"./chunk-set7v1rf.js";import"./chunk-j2ag7hh6.js";import P from"os";import E from"path";function _(q){return typeof q==="string"?q:void 0}function T(q){if(!Array.isArray(q))return;let z=[];for(let F of q)if(typeof F==="string")z.push(F);else if(F!=null)z.push(String(F));return z}function G(){console.log(`
|
|
2
2
|
blade mcp
|
|
3
3
|
`),console.log(`管理 MCP 服务器
|
|
4
4
|
`),console.log("Commands:"),console.log(" blade mcp add <name> <commandOrUrl> [args...] 添加 MCP 服务器"),console.log(" blade mcp remove <name> 删除 MCP 服务器 [aliases: rm]"),console.log(" blade mcp list 列出所有 MCP 服务器并检查健康状态 [aliases: ls]"),console.log(" blade mcp get <name> 获取服务器详情"),console.log(` blade mcp add-json <name> <json> 从 JSON 字符串添加服务器
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{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-
|
|
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-ax1tyzb9.js";import{Y as M}from"./chunk-hqk3sgqq.js";import"./chunk-esnkk33h.js";import"./chunk-2jtsf34p.js";import"./chunk-cj5w17y3.js";import{za as y}from"./chunk-j73schtj.js";import"./chunk-n2dcjqbe.js";import{Sa as O}from"./chunk-cybgk58q.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:
|
package/package.json
CHANGED
package/dist/chunk-5fw10kfn.js
DELETED
|
@@ -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};
|