blade-code 0.7.4 → 0.7.5
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-byxazdwv.js → chunk-0rw4tdqy.js} +1 -1
- package/dist/{chunk-3mhbped9.js → chunk-7pcm8vy5.js} +35 -35
- package/dist/{chunk-n5rg9dbv.js → chunk-8ea9h3mb.js} +1 -1
- package/dist/{chunk-6rszb7xd.js → chunk-8w1hd9ct.js} +255 -255
- package/dist/{chunk-7mnefph6.js → chunk-a8znntss.js} +1 -1
- package/dist/{chunk-pa364yr9.js → chunk-apb1p5q4.js} +1 -1
- package/dist/{chunk-erpgkabk.js → chunk-ay3rhhx8.js} +1 -1
- package/dist/{chunk-egavbybx.js → chunk-c3yn8ds8.js} +1 -1
- package/dist/{chunk-jpry8h07.js → chunk-g1eb7f4q.js} +1 -1
- package/dist/{chunk-501my8nh.js → chunk-jfykets9.js} +1 -1
- package/dist/{chunk-4e2fzyf2.js → chunk-jsn8476q.js} +1 -1
- package/dist/chunk-kssr4fbg.js +1 -0
- package/dist/{chunk-b1d49byc.js → chunk-n969rv4v.js} +1 -1
- package/dist/{chunk-ctbhcw8h.js → chunk-vhc1yr3v.js} +1 -1
- package/dist/{chunk-by93yn92.js → chunk-yaj4nmmp.js} +1 -1
- package/dist/{chunk-z7x21493.js → chunk-yz2jztga.js} +1 -1
- package/dist/chunk-zye2s6f0.js +2 -0
- package/package.json +1 -1
- package/dist/chunk-dftaxwg9.js +0 -1
- package/dist/chunk-gzc9n5d6.js +0 -2
package/dist/blade.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{n as B}from"./chunk-bmcc85nj.js";import{aa as D,ba as F}from"./chunk-rtn0rb16.js";import"./chunk-5smacbk0.js";import"./chunk-rkhhzc4r.js";import"./chunk-jf48kahn.js";import{rb as E,tb as q}from"./chunk-63dzf6hr.js";import{Kb as H}from"./chunk-w1zb8zac.js";import{Nb as J}from"./chunk-kfg3vx5z.js";var X=process.argv.slice(2),$=v(X),w=$!==null;if($!==null)H.setGlobalDebug($);function v(Q){for(let W=0;W<Q.length;W+=1){let T=Q[W];if(T==="--debug"||T==="-d"){let N=Q[W+1];return N&&!N.startsWith("-")?N:!0}if(T.startsWith("--debug="))return T.slice(8)||!0}return null}function C(Q){return Q.length===1&&(Q[0]==="--version"||Q[0]==="-V")}function z(Q,...W){return Q.some((T)=>W.some((N)=>T===N||T.startsWith(`${N}=`)))}async function f(){if(C(X)){let{getVersion:K}=await import("./chunk-
|
|
2
|
+
import{n as B}from"./chunk-bmcc85nj.js";import{aa as D,ba as F}from"./chunk-rtn0rb16.js";import"./chunk-5smacbk0.js";import"./chunk-rkhhzc4r.js";import"./chunk-jf48kahn.js";import{rb as E,tb as q}from"./chunk-63dzf6hr.js";import{Kb as H}from"./chunk-w1zb8zac.js";import{Nb as J}from"./chunk-kfg3vx5z.js";var X=process.argv.slice(2),$=v(X),w=$!==null;if($!==null)H.setGlobalDebug($);function v(Q){for(let W=0;W<Q.length;W+=1){let T=Q[W];if(T==="--debug"||T==="-d"){let N=Q[W+1];return N&&!N.startsWith("-")?N:!0}if(T.startsWith("--debug="))return T.slice(8)||!0}return null}function C(Q){return Q.length===1&&(Q[0]==="--version"||Q[0]==="-V")}function z(Q,...W){return Q.some((T)=>W.some((N)=>T===N||T.startsWith(`${N}=`)))}async function f(){if(C(X)){let{getVersion:K}=await import("./chunk-apb1p5q4.js");console.log(K());return}let Q=D(process.cwd());if(F(Q),E(q()),process.getuid&&process.getuid()===0){let K=!!process.env.SUDO_USER,U=!!process.env.BLADE_ALLOW_ROOT;if(K&&!U)console.error(""),console.error("Error: 请不要使用 sudo 运行 blade"),console.error(""),console.error("原因:"),console.error(" 使用 sudo 会创建属于 root 的配置文件,"),console.error(" 导致普通用户无法访问。"),console.error(""),console.error("正确用法:"),console.error(" blade # 直接运行,不要加 sudo"),console.error(""),console.error("如果遇到权限错误,请运行:"),console.error(" sudo chown -R $USER:$USER ~/.blade/"),console.error(""),console.error("如果你确实需要以 root 运行(容器/CI),设置环境变量:"),console.error(" BLADE_ALLOW_ROOT=1 blade"),console.error(""),process.exit(1)}if(z(X,"--headless")){let{handleHeadlessMode:K}=await import("./chunk-c3yn8ds8.js");if(await K())return}if(B(),z(X,"--print","-p")){let{handlePrintMode:K}=await import("./chunk-jfykets9.js");if(await K())return}if(X.includes("--acp")){let{runAcpIntegration:K}=await import("./chunk-yz2jztga.js");await K();return}let[{default:W},{hideBin:T},{cliConfig:N,globalOptions:G},{loadConfiguration:I,validateOutput:L,validatePermissions:M},{doctorCommands:_},{installCommands:y},{mcpCommands:R},{serveCommand:S},{updateCommands:k},{webCommand:O}]=await Promise.all([import("yargs"),import("yargs/helpers"),import("./chunk-kssr4fbg.js"),import("./chunk-aevyre2t.js"),import("./chunk-38h3yh6z.js"),import("./chunk-qxvp127d.js"),import("./chunk-ay3rhhx8.js"),import("./chunk-vhc1yr3v.js"),import("./chunk-373pmz70.js"),import("./chunk-0rw4tdqy.js")]),x=W(T(process.argv)).scriptName(N.scriptName).usage(N.usage).version(N.version).locale(N.locale).showHelpOnFail(N.showHelpOnFail).demandCommand(0,"").recommendCommands().strict(N.strict).parserConfiguration({"populate--":!0}).options(G).middleware([I,M,L]).command(R).command(_).command(k).command(y).command(O).command(S).completion("completion",!1).help("help","Show help").alias("help","h").alias("version","V").fail((K,U,Z)=>{if(U){if(console.error("An error occurred:"),console.error(U.message),w&&U.stack)console.error(`
|
|
3
3
|
Stack trace:`),console.error(U.stack);else console.error(`
|
|
4
4
|
Run with --debug to show the stack trace.`);process.exit(1)}if(K)console.error("Error: Invalid arguments:"),console.error(K),console.error(`
|
|
5
|
-
Hint: Did you mean:`),Z.showHelp(),process.exit(1)}).command("$0",!1,()=>{},async(K)=>{let U=K._.slice(1),Z=U.length>0?U.join(" "):void 0,V=import("./chunk-cqrg2pp7.js").then(({checkVersionOnStartup:A})=>A()),[{render:b},{createElement:P},{AppWrapper:h}]=await Promise.all([import("ink"),import("react"),import("./chunk-
|
|
5
|
+
Hint: Did you mean:`),Z.showHelp(),process.exit(1)}).command("$0",!1,()=>{},async(K)=>{let U=K._.slice(1),Z=U.length>0?U.join(" "):void 0,V=import("./chunk-cqrg2pp7.js").then(({checkVersionOnStartup:A})=>A()),[{render:b},{createElement:P},{AppWrapper:h}]=await Promise.all([import("ink"),import("react"),import("./chunk-8ea9h3mb.js")]),Y={...K,initialMessage:Z,debug:K.debug,print:Boolean(K.print),versionCheckPromise:V};delete Y._,delete Y.$0,delete Y.message,b(P(h,Y),{patchConsole:!0,exitOnCtrlC:!1,alternateBuffer:!1})});try{await x.parse()}catch(K){console.error("Error: Parse error:",K),process.exit(1)}}if(J.main==J.module)f().catch(console.error);export{f as main};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{f as Q,g as R,h as T,i as W}from"./chunk-
|
|
1
|
+
import{f as Q,g as R,h as T,i as W}from"./chunk-zye2s6f0.js";import"./chunk-pvxp2gzr.js";import"./chunk-8w1hd9ct.js";import"./chunk-e21htmg4.js";import"./chunk-a8znntss.js";import"./chunk-rtn0rb16.js";import{sa as J}from"./chunk-5smacbk0.js";import"./chunk-rkhhzc4r.js";import{Ea as M}from"./chunk-jsn8476q.js";import"./chunk-7pcm8vy5.js";import"./chunk-cyxb6fxe.js";import"./chunk-jf48kahn.js";import"./chunk-63dzf6hr.js";import"./chunk-98jpdmgc.js";import"./chunk-w1zb8zac.js";import"./chunk-kfg3vx5z.js";import b from"chalk";import H from"open";var $=`
|
|
2
2
|
____ _ _
|
|
3
3
|
| __ )| | __ _ __| | ___
|
|
4
4
|
| _ \\| |/ _\` |/ _\` |/ _ \\
|
|
@@ -1,21 +1,21 @@
|
|
|
1
|
-
import{nb as N0}from"./chunk-jf48kahn.js";import{tb as
|
|
1
|
+
import{nb as N0}from"./chunk-jf48kahn.js";import{tb as i}from"./chunk-63dzf6hr.js";import{Ab as RQ,xb as XZ,yb as $0,zb as VZ}from"./chunk-98jpdmgc.js";import{Cb as hQ,Lb as g}from"./chunk-w1zb8zac.js";function L0(Q){return Q.role==="system"&&Array.isArray(Q.content)}class _0{systemMessages;_history;_pending=[];context;constructor(Q,Z){this.context=Q;let $=Q.messages.find(L0);if($)this.systemMessages=[$];else if(Z)this.systemMessages=[{role:"system",content:[{type:"text",text:Z,providerOptions:{anthropic:{cacheControl:{type:"ephemeral"}}}}]}];else this.systemMessages=[];this._history=Q.messages.filter((J)=>!L0(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(Q){this._pending.push(Q)}appendUser(Q){this._pending.push(Q)}appendAssistant(Q){this._pending.push(Q)}appendToolResult(Q){this._pending.push(Q)}appendControl(Q,Z){if(Q==="system")throw Error("Cannot append system control message via appendControl. Use constructor for root system prompt.");this._pending.push(Z)}appendToHistory(Q){this._history.push(Q)}commitPending(){if(this._pending.length>0)this._history.push(...this._pending),this._pending=[]}replaceHistory(Q){this._history=Q.filter((Z)=>!L0(Z))}writeback(){this.commitPending(),this.context.messages=this._history}get hasSystemPrompt(){return this.systemMessages.length>0}}async function bZ(Q,Z){let $;while(!($=await Q.next()).done)if(Z)await Z($.value);return $.value}function OQ(Q){if(Q.isSubagent)return"continue";if(!Q.budget||Q.budget<=0)return"continue";if(Q.consecutiveContinuations>=3&&Q.lastOutputDelta<500)return"stop";if(Q.usage/Q.budget>=0.9)return"stop";return"continue"}function wQ(Q){return{budget:Q.budget,usage:0,consecutiveContinuations:0,lastOutputDelta:0,isSubagent:Q.isSubagent??!1}}function LQ(Q,Z,$){return{...Q,usage:Q.usage+Z,lastOutputDelta:Z,consecutiveContinuations:$?Q.consecutiveContinuations+1:0}}var t0=g("Agent"),FZ=3;function QQ(Q,Z,$){if(Q!=="length")return{action:"none"};if(Z>=FZ)return{action:"truncated"};if(OQ($)==="stop")return t0.info("[Loop] Token budget: diminishing returns detected, skipping recovery"),{action:"budget_stop"};return{action:"recover"}}var OZ=[/:\s*$/,/:\s*$/,/\.\.\.\s*$/,/让我(先|来|开始|查看|检查|修复)/,/Let me (first|start|check|look|fix)/i,/I('ll| will) (now |)(create|write|edit|update|modify|fix|add|implement)/i,/我(现在就|来|要)(创建|写入|编辑|修改|修复|添加|实现)/,/\d+\.\s+(First|Next|Then|Finally)/i],wZ=/```[\s\S]{50,}```/,_Q="请执行你提到的操作,不要只是描述。使用 Edit/Write/Bash 工具来实际修改文件。",LZ=2;function ZQ(Q,Z,$=!0){if(!Q||Z>=LZ)return{action:"none"};if(!$&&wZ.test(Q))return{action:"retry",prompt:_Q};let J=Q.slice(-200),z=J.match(/```/g);if(z&&z.length%2!==0)return{action:"none"};if(OZ.some((G)=>G.test(J)))return{action:"retry",prompt:_Q};return{action:"none"}}var _Z=[/\b(?:run|execute|rerun|re-run)\b[\s\S]{0,60}\b(?:tests?|test suite|lint|type-?check|build)\b/i,/\b(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?(?:test|lint|build|type-?check)\b/i,/(?:运行|执行|跑|重新运行).{0,30}(?:测试|单测|集成测试|检查|构建)/],NZ=/(?:^|\s)(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?(?:test|lint|build|type-?check)\b|(?:^|\s)(?:node|bun)\s+--test\b|(?:^|\s)(?:vitest|jest|pytest|go\s+test|cargo\s+test|tsc)\b/i,NQ={test:/\b(?:tests?|test suite)\b|(?:测试|单测|集成测试)/i,lint:/\blint(?:ing)?\b/i,"type-check":/\btype[\s-]?check(?:ing)?\b|\btsc\b|类型检查/i,build:/\bbuild\b|构建/i},vZ={test:/(?:^|\s)(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?test\b|(?:^|\s)(?:node|bun)\s+--test\b|(?:^|\s)(?:vitest|jest|pytest|go\s+test|cargo\s+test)\b/i,lint:/(?:^|\s)(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?lint\b/i,"type-check":/(?:^|\s)(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?type-?check\b|(?:^|\s)tsc\b/i,build:/(?:^|\s)(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?build\b/i},EZ="The user explicitly required verification, but it has not run successfully. Do not finish or explain. Your next action must be a Bash tool call that runs the requested test, lint, type-check, or build command. Inspect the command result and fix any failure before finishing.",IZ="Required verification did not run successfully before the retry limit.",UZ=3;function e0(Q){return NZ.test(Q)}function EQ(Q,Z,$){if(!$.success)return;if(["Edit","Write","NotebookEdit"].includes(Z)){Q.clear();return}if(Z==="Bash"&&typeof $.metadata?.command==="string"&&$.metadata.exit_code===0&&e0($.metadata.command)){Q.add($.metadata.command);return}if(!["Task","TaskOutput"].includes(Z))return;let J=$.metadata?.verificationCommands;if(!Array.isArray(J))return;for(let z of J)if(typeof z==="string"&&e0(z))Q.add(z)}function $Q(Q,Z,$){if(!Q||!_Z.some((Y)=>Y.test(Q)))return{action:"none"};let J=Object.keys(NQ).filter((Y)=>NQ[Y].test(Q)),z=[...Z],W=J.filter((Y)=>!z.some((B)=>vZ[Y].test(B)));if(J.length>0?W.length===0:z.some(e0))return{action:"none"};if($>=UZ)return{action:"fail",message:IZ};let V=J.length>1&&W.length>0?` Missing successful verification categories: ${W.join(", ")}.`:"";return{action:"retry",prompt:`${EZ}${V}`}}var SZ=[/\bdelegate\b[\s\S]{0,120}\b(?:Task tool|subagent|agent)\b/i,/\b(?:call|use|invoke)\b[\s\S]{0,80}\bTask tool\b/i,/(?:委派|交给|调用|使用).{0,60}(?:Task|子代理|子智能体)/],yZ=[/\b(?:do not|don't|never)\s+(?:delegate|call|use|invoke)\b/i,/(?:不要|禁止|无需)(?:委派|调用|使用).{0,20}(?:Task|子代理|子智能体)?/],AZ="The user explicitly required delegation, but no Task tool call completed successfully. Do not solve the task directly or explain. Your next action must be a Task tool call using the requested subagent.",PZ="Required delegation did not complete before the retry limit.",MZ=3;function IQ(Q,Z,$){if(!Q||yZ.some((J)=>J.test(Q))||!SZ.some((J)=>J.test(Q))||Z.has("Task"))return{action:"none"};if($>=MZ)return{action:"fail",message:PZ};return{action:"retry",prompt:AZ}}var fZ=[/\b(?:use|create|enter|start|work\s+(?:in|inside))\b.{0,60}\bworktree\b/i,/(?:使用|创建|进入).{0,30}(?:worktree|工作树)/i],hZ=[/\b(?:exit|leave)\b.{0,40}\bworktree\b/i,/\bworktree\b.{0,60}\b(?:action\s+)?(?:keep|remove)\b/i,/(?:退出|离开).{0,30}(?:worktree|工作树)/i];function v0(Q){return typeof Q==="string"&&fZ.some((Z)=>Z.test(Q))}var kZ="The user explicitly required git worktree isolation, but EnterWorktree has not completed successfully. Do not continue in the original workspace. Your next action must be an EnterWorktree tool call. Wait for its result before using file or Bash tools.",xZ="The user explicitly required leaving the managed worktree, but ExitWorktree has not completed successfully. Do not finish or explain. Your next action must be an ExitWorktree tool call using the action requested by the user.",RZ="Required worktree lifecycle did not complete before the retry limit.",TZ=3;function UQ(Q,Z,$){if(!Q||!v0(Q))return{action:"none"};let J=hZ.some((W)=>W.test(Q));if(Z.has("TaskWorktree"))return{action:"none"};let z=!Z.has("EnterWorktree")?"EnterWorktree":J&&!Z.has("ExitWorktree")?"ExitWorktree":void 0;if(!z)return{action:"none"};if($>=TZ)return{action:"fail",message:RZ};return{action:"retry",tool:z,prompt:z==="EnterWorktree"?kZ:xZ}}var vQ=30000;async function JQ(Q){try{let $=N0.getInstance().executeStopHooks({projectDir:i(),sessionId:Q.sessionId,permissionMode:Q.permissionMode,reason:Q.reason,abortSignal:Q.abortSignal}),J,z=new Promise((W)=>{J=setTimeout(()=>W("timeout"),vQ)});try{let W=await Promise.race([$,z]);if(W==="timeout")return t0.warn(`[Loop] Stop hook 超时 (${vQ}ms),按 shouldStop: true 处理`),{action:"stop"};let G=W;if(!G.shouldStop)return{action:"continue",reason:G.continueReason};return{action:"stop"}}finally{clearTimeout(J)}}catch(Z){return t0.warn("[Loop] Stop hook execution failed:",Z),{action:"stop"}}}var W0=g("Agent"),zQ=`<turn_aborted>
|
|
2
2
|
The previous turn was interrupted. Commands or tool calls may have partially completed; inspect the workspace and running processes before retrying.
|
|
3
|
-
</turn_aborted>`;function G0(Q){return Q.executionEngine?.getContextManager()}async function
|
|
3
|
+
</turn_aborted>`;function G0(Q){return Q.executionEngine?.getContextManager()}async function l(Q,Z,$,J=null,z){try{let W=G0(Q),G=typeof $==="string"?$.trim()!=="":$.some((V)=>V.type==="text"?V.text.trim()!=="":!0);if(W&&Z.sessionId&&G)return await W.saveMessage(Z.sessionId,"user",$,J,z,Z.subagentInfo)}catch(W){W0.warn("[Loop] 保存用户消息失败:",W)}return null}async function x(Q,Z,$,J){try{let z=G0(Q);if(z&&Z.sessionId&&$.trim())return await z.saveMessage(Z.sessionId,"assistant",$,J,void 0,Z.subagentInfo)}catch(z){W0.warn("[Loop] 保存助手消息失败:",z)}return null}async function SQ(Q,Z,$){try{let J=G0(Q);if(J&&Z.sessionId)return await J.saveMessage(Z.sessionId,"system",zQ,$,void 0,Z.subagentInfo)}catch(J){W0.warn("[Loop] 保存中断边界失败:",J)}return null}async function WQ(Q,Z,$,J,z){try{let W=G0(Q);if(W&&Z.sessionId)return await W.saveToolUse(Z.sessionId,$,J,z,Z.subagentInfo)}catch(W){W0.warn("[Loop] 保存工具调用失败:",W)}return null}async function GQ(Q,Z,$,J,z,W,G,V){try{let Y=G0(Q);if(Y&&Z.sessionId)return await Y.saveToolResult(Z.sessionId,$,J,z,W,G,Z.subagentInfo,V)}catch(Y){W0.warn("[Loop] 保存工具结果失败:",Y)}return null}async function E0(Q,Z,$,J){try{let z=G0(Q);if(z&&Z.sessionId)return await z.saveCompaction(Z.sessionId,$,J,null)}catch(z){W0.warn("[Loop] 保存压缩数据失败:",z)}return null}function yQ(Q,Z){if(!["TaskCreate","TaskUpdate","TaskList"].includes(Q.function.name)||!Z.success||!Z.llmContent&&!Z.metadata)return null;let $=typeof Z.llmContent==="object"?Z.llmContent:{};return{kind:"task_update",tasks:Z.metadata?.tasks||$.tasks||[]}}function AQ(Q,Z,$){if(Q.function.name!=="Skill"||!Z.success||!Z.metadata)return;let J=Z.metadata;if(J.skillName)$.onSkillActivated?.({skillName:J.skillName,allowedTools:J.allowedTools,basePath:J.basePath||""})}function PQ(Q){let Z=Q.metadata;if(!Z)return;return Z.modelId?.toString().trim()||Z.model?.toString().trim()||void 0||void 0}function CZ(Q,Z,$){if(!["EnterWorktree","ExitWorktree"].includes(Q.function.name)||!Z.success)return;let J=Z.metadata,z=J?.workspaceRoot;if(!["enter","exit"].includes(String(J?.workspaceTransition))||typeof z!=="string"||z.trim()==="")return;return $.workspaceRoot=z,$.worktreeActive=J?.workspaceTransition==="enter",z}function pZ(Q,Z){if(Q.function.name!=="Task")return null;let $=Z.metadata;if(!$?.subagentSessionId)return null;let J=$.subagentSessionId,z=$.subagentType||"Task",W=$.subagentStatus;if(W==="completed"||W==="failed"||W==="cancelled")return{kind:"subagent_completed",sessionId:J,success:W==="completed",summary:$.subagentSummary};if(W==="running"){let G="";try{G=JSON.parse(Q.function.arguments).prompt||""}catch{}return{kind:"subagent_spawned",sessionId:J,type:z,prompt:G}}return null}async function YQ(Q,Z,$,J){let z=yQ(Q,Z),W=pZ(Q,Z);AQ(Q,Z,$);let G=PQ(Z);if(G)await $.onModelSwitch?.(G);if(J)CZ(Q,Z,J);return W||z}import{nanoid as O2}from"nanoid";import{nanoid as e}from"nanoid";import{promises as lZ}from"node:fs";import*as y from"node:fs/promises";import*as Z0 from"node:path";var MQ={enabled:!0,maxIndexLines:200};var dZ="memory",fQ="MEMORY.md";class VQ{memoryDir;config;initialized=!1;constructor(Q,Z,$){if($)this.memoryDir=$;else{let J=hQ(Q);this.memoryDir=Z0.join(J,dZ)}this.config={...MQ,...Z}}async initialize(){if(this.initialized)return;await y.mkdir(this.memoryDir,{recursive:!0}),this.initialized=!0}async loadIndex(){if(!this.config.enabled)return null;await this.initialize();let Q=Z0.join(this.memoryDir,fQ);try{let Z=await y.readFile(Q,"utf-8");if(!Z.trim())return null;let $=Z.split(`
|
|
4
4
|
`),z=$.slice(0,this.config.maxIndexLines).join(`
|
|
5
5
|
`).trim();if($.length>this.config.maxIndexLines)return z+`
|
|
6
6
|
|
|
7
|
-
<!-- ${$.length-this.config.maxIndexLines} more lines in MEMORY.md, use MemoryRead to access -->`;return z||null}catch(Z){if(Z instanceof Error&&"code"in Z&&Z.code==="ENOENT")return null;throw Z}}async readTopic(Q){await this.initialize();let Z=this.resolveTopicPath(Q);try{return await
|
|
7
|
+
<!-- ${$.length-this.config.maxIndexLines} more lines in MEMORY.md, use MemoryRead to access -->`;return z||null}catch(Z){if(Z instanceof Error&&"code"in Z&&Z.code==="ENOENT")return null;throw Z}}async readTopic(Q){await this.initialize();let Z=this.resolveTopicPath(Q);try{return await y.readFile(Z,"utf-8")||null}catch($){if($ instanceof Error&&"code"in $&&$.code==="ENOENT")return null;throw $}}async writeTopic(Q,Z,$="append"){await this.initialize();let J=this.resolveTopicPath(Q);if($==="append"){let z="";try{z=await y.readFile(J,"utf-8")}catch{}let W=z&&!z.endsWith(`
|
|
8
8
|
`)?`
|
|
9
|
-
`:"";await
|
|
9
|
+
`:"";await y.writeFile(J,z+W+Z,"utf-8")}else await y.writeFile(J,Z,"utf-8")}async updateIndex(Q,Z="overwrite"){await this.initialize();let $=Z0.join(this.memoryDir,fQ);if(Z==="append"){let J="";try{J=await y.readFile($,"utf-8")}catch{}let z=J&&!J.endsWith(`
|
|
10
10
|
`)?`
|
|
11
|
-
`:"";await
|
|
11
|
+
`:"";await y.writeFile($,J+z+Q,"utf-8")}else await y.writeFile($,Q,"utf-8")}async listTopics(){await this.initialize();try{let Q=await y.readdir(this.memoryDir,{withFileTypes:!0}),Z=[];for(let $ of Q){if(!$.isFile()||!$.name.endsWith(".md"))continue;let J=Z0.join(this.memoryDir,$.name),z=await y.stat(J);Z.push({name:$.name.replace(/\.md$/,""),size:z.size,lastModified:z.mtime})}return Z.sort(($,J)=>J.lastModified.getTime()-$.lastModified.getTime())}catch{return[]}}async deleteTopic(Q){let Z=this.resolveTopicPath(Q);try{return await y.unlink(Z),!0}catch{return!1}}async clearAll(){let Q=await this.listTopics(),Z=0;for(let $ of Q){let J=Z0.join(this.memoryDir,`${$.name}.md`);try{await y.unlink(J),Z++}catch{}}return Z}getMemoryDir(){return this.memoryDir}resolveTopicPath(Q){let Z=Q.replace(/[/\\:*?"<>|]/g,"-"),$=Z.endsWith(".md")?Z:`${Z}.md`,J=Z0.join(this.memoryDir,$);if(!J.startsWith(this.memoryDir))throw Error(`Invalid topic name: ${Q}`);return J}}var gZ=[{pattern:/(?:记住|remember|note|备注)[::](.+)/i,topic:"preferences"},{pattern:/(?:convention|约定|规范)[::](.+)/i,topic:"conventions"},{pattern:/(?:lesson|教训|踩坑)[::](.+)/i,topic:"lessons"}],mZ=/(?:fix|修复|解决|resolved)[::]\s*(.+?)(?:\n|$)/i,cZ=/(?:Error|FAIL|错误)[::]\s*(.+?)(?:\n|$)/i;function uZ(Q){let Z=new Map;for(let $ of Q){if(!$.content||typeof $.content!=="string")continue;let J=$.content;if($.role==="user")for(let{pattern:z,topic:W}of gZ){let G=J.match(z);if(G?.[1]){let V=Z.get(W)??[];V.push(G[1].trim()),Z.set(W,V)}}if($.role==="assistant"){let z=J.match(mZ);if(z?.[1]&&z[1].length>20&&z[1].length<200){let W=Z.get("debugging")??[];W.push(z[1].trim()),Z.set("debugging",W)}}if($.role==="tool"&&$.content?.includes("Error")){let z=J.match(cZ);if(z?.[1]&&z[1].length>10){let W=Z.get("debugging")??[];if(W.length<5)W.push(`Tool error pattern: ${z[1].trim().slice(0,150)}`),Z.set("debugging",W)}}}return Z}async function kQ(Q){let Z=uZ(Q);if(Z.size===0)return{extracted:0,topics:[]};try{let $=new VQ(i());await $.initialize();let J=[],z=0;for(let[W,G]of Z){if(G.length===0)continue;let V=new Date().toISOString().split("T")[0],Y=G.map((B)=>`- [${V}] ${B}`).join(`
|
|
12
12
|
`);await $.writeTopic(W,Y+`
|
|
13
|
-
`,"append"),J.push(W),z+=G.length}return{extracted:z,topics:J}}catch{return{extracted:0,topics:[]}}}import{promises as
|
|
14
|
-
`);if(this.extractFilePathsFromContent(W).forEach((V)=>{this.updateFileReference(Z,V,z,!1)}),J.tool_calls&&Array.isArray(J.tool_calls))J.tool_calls.forEach((V)=>{let Y=this.extractFilePathsFromToolCall(V),B=V.type==="function"&&"function"in V?V.function?.name:"",q=["Write","Edit"].includes(B||"");Y.forEach((
|
|
13
|
+
`,"append"),J.push(W),z+=G.length}return{extracted:z,topics:J}}catch{return{extracted:0,topics:[]}}}import{promises as I0}from"node:fs";var B0=g("Tool");class t{static instance=null;accessedFiles=new Map;constructor(){}static getInstance(){if(!t.instance)t.instance=new t;return t.instance}async recordFileRead(Q,Z){try{let $=await I0.stat(Q),J={filePath:Q,accessTime:Date.now(),mtime:$.mtimeMs,sessionId:Z,lastOperation:"read"};this.accessedFiles.set(Q,J),B0.debug(`记录文件读取: ${Q}`)}catch($){B0.warn(`记录文件读取失败: ${Q}`,$)}}async recordFileEdit(Q,Z,$="edit"){try{let J=await I0.stat(Q),z={filePath:Q,accessTime:Date.now(),mtime:J.mtimeMs,sessionId:Z,lastOperation:$};this.accessedFiles.set(Q,z),B0.debug(`记录文件${$==="edit"?"编辑":"写入"}: ${Q}`)}catch(J){B0.warn(`记录文件${$==="edit"?"编辑":"写入"}失败: ${Q}`,J)}}hasFileBeenRead(Q,Z){let $=this.accessedFiles.get(Q);if(!$)return!1;if(Z&&$.sessionId!==Z)return!1;return!0}async checkFileModification(Q){let Z=this.accessedFiles.get(Q);if(!Z)return{modified:!1,message:"文件未被跟踪"};try{let $=await I0.stat(Q);if(Math.abs($.mtimeMs-Z.mtime)>1)return{modified:!0,message:`文件在访问后被修改(访问时间: ${new Date(Z.accessTime).toISOString()}, 当前修改时间: ${$.mtime.toISOString()})`};return{modified:!1}}catch($){let J=$;if(J.code==="ENOENT")return{modified:!0,message:"文件已被删除"};return{modified:!1,message:`无法检查文件状态: ${J.message}`}}}async checkExternalModification(Q){let Z=this.accessedFiles.get(Q);if(!Z)return{isExternal:!1,message:"文件未被跟踪"};try{let $=await I0.stat(Q);if($.mtimeMs-Z.mtime>2000)return{isExternal:!0,message:`文件在 ${new Date(Z.accessTime).toISOString()} (${Z.lastOperation}) 之后被外部程序修改(当前修改时间: ${$.mtime.toISOString()})`};return{isExternal:!1}}catch($){let J=$;if(J.code==="ENOENT")return{isExternal:!0,message:"文件已被删除"};return B0.warn(`检查文件外部修改失败: ${Q}`,$),{isExternal:!1,message:`无法检查文件状态: ${J.message}`}}}getFileRecord(Q){return this.accessedFiles.get(Q)}clearFileRecord(Q){this.accessedFiles.delete(Q)}clearAll(){this.accessedFiles.clear()}clearSession(Q){for(let[Z,$]of this.accessedFiles.entries())if($.sessionId===Q)this.accessedFiles.delete(Z)}getTrackedFiles(){return Array.from(this.accessedFiles.keys())}getTrackedFileCount(){return this.accessedFiles.size}static resetInstance(){t.instance=null}}import{readFile as iZ}from"node:fs/promises";import{basename as nZ}from"node:path";class U0{static MAX_FILES=5;static MAX_LINES_PER_FILE=1000;static analyzeFiles(Q){let Z=new Map;return Q.forEach((J,z)=>{let W=typeof J.content==="string"?J.content:(J.content||[]).filter((V)=>V.type==="text").map((V)=>V.text).join(`
|
|
14
|
+
`);if(this.extractFilePathsFromContent(W).forEach((V)=>{this.updateFileReference(Z,V,z,!1)}),J.tool_calls&&Array.isArray(J.tool_calls))J.tool_calls.forEach((V)=>{let Y=this.extractFilePathsFromToolCall(V),B=V.type==="function"&&"function"in V?V.function?.name:"",q=["Write","Edit"].includes(B||"");Y.forEach((D)=>{this.updateFileReference(Z,D,z,q)})})}),Array.from(Z.values()).sort((J,z)=>{if(J.wasModified!==z.wasModified)return J.wasModified?-1:1;if(J.mentions!==z.mentions)return z.mentions-J.mentions;return z.lastMentioned-J.lastMentioned}).slice(0,this.MAX_FILES)}static async readFilesContent(Q){let Z=[];for(let $ of Q)try{let J=await iZ($,"utf-8"),z=J.split(`
|
|
15
15
|
`),W=z.length,G=J,V=!1,Y=W;if(W>this.MAX_LINES_PER_FILE)G=z.slice(0,this.MAX_LINES_PER_FILE).join(`
|
|
16
16
|
`),G+=`
|
|
17
17
|
|
|
18
|
-
... (truncated ${W-this.MAX_LINES_PER_FILE} lines)`,V=!0,Y=this.MAX_LINES_PER_FILE;Z.push({path:$,content:G,truncated:V,lines:W,includedLines:Y})}catch(J){console.warn(`[FileAnalyzer] 无法读取文件: ${$}`,J)}return Z}static extractFilePathsFromContent(Q){let Z=new Set,$=/```(?:\w+)?\s*\n?([\s\S]*?)```/g,J=Array.from(Q.matchAll($));for(let W of J){let G=W[1];this.extractPathsFromText(G).forEach((Y)=>Z.add(Y))}return this.extractPathsFromText(Q).forEach((W)=>Z.add(W)),Array.from(Z)}static extractPathsFromText(Q){let 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 $){let z=Array.from(Q.matchAll(J));for(let W of z){let G=W[0];if(G=G.replace(/[,。;:!?""''()【】《》]$/g,""),G=G.replace(/[,.;:!?"'()[\]<>]$/g,""),this.isValidFilePath(G))Z.push(G)}}return Z}static extractFilePathsFromToolCall(Q){let Z=[];if(Q.type!=="function"||!Q.function)return Z;try{let $=Q.function.name,J=JSON.parse(Q.function.arguments||"{}");if(["Read","Write","Edit","Glob","Grep","NotebookEdit","mcp__github__get_file_contents","mcp__github__create_or_update_file"].includes($)){let W=["file_path","path","notebook_path","filePath"];for(let G of W)if(J[G]&&typeof J[G]==="string")Z.push(J[G])}}catch{}return Z}static updateFileReference(Q,Z,$,J){let z=Q.get(Z);if(z)z.mentions++,z.lastMentioned=$,z.wasModified=z.wasModified||J;else Q.set(Z,{path:Z,mentions:1,lastMentioned:$,wasModified:J})}static isValidFilePath(Q){if(!Q.includes("/"))return!1;let Z=
|
|
18
|
+
... (truncated ${W-this.MAX_LINES_PER_FILE} lines)`,V=!0,Y=this.MAX_LINES_PER_FILE;Z.push({path:$,content:G,truncated:V,lines:W,includedLines:Y})}catch(J){console.warn(`[FileAnalyzer] 无法读取文件: ${$}`,J)}return Z}static extractFilePathsFromContent(Q){let Z=new Set,$=/```(?:\w+)?\s*\n?([\s\S]*?)```/g,J=Array.from(Q.matchAll($));for(let W of J){let G=W[1];this.extractPathsFromText(G).forEach((Y)=>Z.add(Y))}return this.extractPathsFromText(Q).forEach((W)=>Z.add(W)),Array.from(Z)}static extractPathsFromText(Q){let 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 $){let z=Array.from(Q.matchAll(J));for(let W of z){let G=W[0];if(G=G.replace(/[,。;:!?""''()【】《》]$/g,""),G=G.replace(/[,.;:!?"'()[\]<>]$/g,""),this.isValidFilePath(G))Z.push(G)}}return Z}static extractFilePathsFromToolCall(Q){let Z=[];if(Q.type!=="function"||!Q.function)return Z;try{let $=Q.function.name,J=JSON.parse(Q.function.arguments||"{}");if(["Read","Write","Edit","Glob","Grep","NotebookEdit","mcp__github__get_file_contents","mcp__github__create_or_update_file"].includes($)){let W=["file_path","path","notebook_path","filePath"];for(let G of W)if(J[G]&&typeof J[G]==="string")Z.push(J[G])}}catch{}return Z}static updateFileReference(Q,Z,$,J){let z=Q.get(Z);if(z)z.mentions++,z.lastMentioned=$,z.wasModified=z.wasModified||J;else Q.set(Z,{path:Z,mentions:1,lastMentioned:$,wasModified:J})}static isValidFilePath(Q){if(!Q.includes("/"))return!1;let Z=nZ(Q);if(!Z.includes("."))return!1;let $=["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=Z.split(".").pop()?.toLowerCase();if(!J||!$.includes(J))return!1;return!0}}import{encodingForModel as xQ}from"js-tiktoken";class j0{static encodingCache=new Map;static countTokens(Q,Z){let $=this.getEncoding(Z),J=0;for(let z of Q){if(J+=4,z.role)J+=$.encode(z.role).length;if(z.content)if(typeof z.content==="string")J+=$.encode(z.content).length;else J+=$.encode(JSON.stringify(z.content)).length;if(z.tool_calls&&Array.isArray(z.tool_calls))J+=this.countToolCallTokens(z.tool_calls,$);if(z.name)J+=$.encode(z.name).length}return J}static getTokenLimit(Q){return Q}static shouldCompact(Q,Z,$,J=0.8){let z=this.countTokens(Q,Z),W=Math.floor($*J);return z>=W}static getEncoding(Q){if(!this.encodingCache.has(Q))try{let Z=xQ(Q);this.encodingCache.set(Q,Z)}catch{try{let Z=xQ("gpt-4");this.encodingCache.set(Q,Z)}catch{console.warn(`[TokenCounter] 无法为模型 ${Q} 获取 encoding,使用粗略估算`),this.encodingCache.set(Q,{encode:(Z)=>{return Array(Math.ceil(Z.length/4))}})}}return this.encodingCache.get(Q)}static countToolCallTokens(Q,Z){let $=0;for(let J of Q){if($+=4,J.type==="function"&&J.function?.name)$+=Z.encode(J.function.name).length;if(J.type==="function"&&J.function?.arguments)$+=Z.encode(J.function.arguments).length;if(J.id)$+=Z.encode(J.id).length}return $}static clearCache(){this.encodingCache.clear()}static estimateTokens(Q){let Z=(Q.match(/[\u4e00-\u9fa5]/g)||[]).length,$=Q.length-Z;return Math.ceil(Z/1.5+$/4)}}var M=g("Context"),S0=new Map,rZ=3;class Y0{static THRESHOLD_PERCENT=0.8;static RETAIN_PERCENT=0.2;static FALLBACK_RETAIN_PERCENT=0.3;static ACTIVE_TASK_MAX_CHARS=6000;static async compact(Q,Z){if(Z.signal?.aborted)throw new DOMException("Aborted","AbortError");let $=Z.actualPreTokens??j0.countTokens(Q,Z.modelName),J=Z.actualPreTokens?"actual (from LLM usage)":"estimated";M.debug(`[CompactionService] preTokens source: ${J}`);try{let V=await N0.getInstance().executeCompactionHooks(Z.trigger,{projectDir:i(),sessionId:Z.sessionId||"unknown",permissionMode:Z.permissionMode||"default",messagesBefore:Q.length,tokensBefore:$});if(V.blockCompaction)return M.debug(`[CompactionService] Compaction hook 阻止压缩: ${V.blockReason||"(无原因)"}`),{success:!1,summary:"",preTokens:$,postTokens:$,filesIncluded:[],compactedMessages:Q,boundaryMessage:{role:"system",content:""},summaryMessage:{role:"user",content:""},error:V.blockReason||"Compaction blocked by hook"};if(V.warning)M.warn(`[CompactionService] Compaction hook warning: ${V.warning}`)}catch(G){M.warn("[CompactionService] Compaction hook execution failed:",G)}let z=Z.sessionId??"_default",W=S0.get(z)??0;if(W>=rZ)return M.warn(`[CompactionService] Circuit breaker open (${W} consecutive failures for session ${z}), using fallback`),this.fallbackCompact(Q,Z,$,Error("Circuit breaker open"));try{M.debug("[CompactionService] 开始压缩,消息数:",Q.length),M.debug("[CompactionService] 压缩前 tokens:",$);let V=U0.analyzeFiles(Q).map((T)=>T.path);M.debug("[CompactionService] 提取重点文件:",V);let Y=await U0.readFilesContent(V);M.debug("[CompactionService] 成功读取文件:",Y.length);let B=await this.generateSummary(Q,Y,Z);M.debug("[CompactionService] 生成总结,长度:",B.length);let q=Math.ceil(Q.length*this.RETAIN_PERCENT),D=Q.slice(-q),X=new Set;for(let T of D)if(T.role==="assistant"&&T.tool_calls)for(let H0 of T.tool_calls)X.add(H0.id);let w=D.filter((T)=>{if(T.role==="tool"&&T.tool_call_id)return X.has(T.tool_call_id);return!0});M.debug("[CompactionService] 保留消息数:",q),M.debug("[CompactionService] 过滤后保留消息数:",w.length);let R=e(),A=this.createBoundaryMessage(R,Z.trigger,$),L=e(),v=this.createSummaryMessage(L,B),j=[v,...w],a=await this.buildFileRestorationMessage();if(a)j.push(a);let u=this.buildActiveTaskMessage(Z.activeTask);if(u)j.push(u);let P=j0.countTokens(j,Z.modelName);M.debug("[CompactionService] 压缩完成!"),M.debug("[CompactionService] Token 变化:",$,"->",P,`(-${((1-P/$)*100).toFixed(1)}%)`),S0.delete(z);let T0=Q.slice(0,Q.length-q);return kQ(T0).catch((T)=>{return}),{success:!0,summary:B,preTokens:$,postTokens:P,filesIncluded:V,compactedMessages:j,boundaryMessage:A,summaryMessage:v}}catch(G){if($0(G))throw G;return S0.set(z,(S0.get(z)??0)+1),M.error("[CompactionService] 压缩失败,使用降级策略",G),this.fallbackCompact(Q,Z,$,G)}}static async generateSummary(Q,Z,$){let J=this.buildCompactionPrompt(Q,Z);if(M.debug("[CompactionService] 使用压缩模型:",$.modelName),$.signal?.aborted)throw new DOMException("Aborted","AbortError");let G=(await(await RQ({apiKey:$.apiKey||process.env.BLADE_API_KEY||"",baseUrl:$.baseURL||process.env.BLADE_BASE_URL||"https://api.openai.com/v1",model:$.modelName,temperature:0.3,maxOutputTokens:8000,timeout:60000,provider:"openai-compatible"})).chat([{role:"user",content:J}],[],$.signal)).content||"",V=G.match(/<summary>([\s\S]*?)<\/summary>/);if(!V)return M.warn("[CompactionService] 总结格式不正确,使用完整响应"),G;return V[1].trim()}static buildCompactionPrompt(Q,Z){let $=Q.map((W,G)=>{let V=W.role||"unknown",Y=typeof W.content==="string"?W.content:JSON.stringify(W.content),B=5000,q=Y.length>5000?Y.substring(0,5000)+"...":Y;return`[${G+1}] ${V}: ${q}`}).join(`
|
|
19
19
|
|
|
20
20
|
`),J=Z.map((W)=>{return`### ${W.path}
|
|
21
21
|
\`\`\`
|
|
@@ -88,35 +88,35 @@ ${Z.length>0?`## Important Files
|
|
|
88
88
|
|
|
89
89
|
${J}`:""}
|
|
90
90
|
|
|
91
|
-
Please provide your summary following the structure specified above, with both <analysis> and <summary> sections.`}static createBoundaryMessage(Q,Z,$){return{id:
|
|
91
|
+
Please provide your summary following the structure specified above, with both <analysis> and <summary> sections.`}static createBoundaryMessage(Q,Z,$){return{id:e(),role:"system",content:"Conversation compacted",metadata:{type:"system",subtype:"compact_boundary",parentId:Q,compactMetadata:{trigger:Z,preTokens:$}}}}static createSummaryMessage(Q,Z){return{id:e(),role:"user",content:Z,metadata:{parentId:Q,isCompactSummary:!0}}}static getRecentlyAccessedFiles(Q){let Z=t.getInstance();return Z.getTrackedFiles().map((z)=>({filePath:z,record:Z.getFileRecord(z)})).filter((z)=>z.record!==void 0).sort((z,W)=>W.record.accessTime-z.record.accessTime).slice(0,Q).map((z)=>z.filePath)}static async buildFileRestorationMessage(){let Q=this.getRecentlyAccessedFiles(5);if(Q.length===0)return null;let Z=[];for(let J of Q)try{let W=(await lZ.readFile(J,"utf-8")).split(`
|
|
92
92
|
`),G=W.slice(0,200).join(`
|
|
93
93
|
`),V=W.length>200?`
|
|
94
94
|
... (${W.length-200} more lines)`:"";Z.push(`<file path="${J}" lines="${W.length}">
|
|
95
95
|
${G}${V}
|
|
96
96
|
</file>`)}catch{}if(Z.length===0)return null;let $=["<system-reminder>","Post-compaction file restoration. These files were recently accessed in the conversation:",...Z,"</system-reminder>"].join(`
|
|
97
|
-
`);return
|
|
97
|
+
`);return M.debug("[CompactionService] Post-compact 恢复文件:",Q.length),{id:e(),role:"user",content:$,metadata:{isPostCompactRestoration:!0}}}static buildActiveTaskMessage(Q){if(!Q)return null;let Z=this.ACTIVE_TASK_MAX_CHARS,$=Math.floor(Z*0.75),J=Q.length<=Z?Q:[Q.slice(0,$),`
|
|
98
98
|
...[active task checkpoint truncated]...
|
|
99
|
-
`,Q.slice(-(Z-$))].join("");return{id:
|
|
100
|
-
`),metadata:{isPostCompactActiveTask:!0}}}static fallbackCompact(Q,Z,$,J){let z=Math.ceil(Q.length*this.FALLBACK_RETAIN_PERCENT),W=Q.slice(-z),G=new Set;for(let
|
|
99
|
+
`,Q.slice(-(Z-$))].join("");return{id:e(),role:"user",content:["<system-reminder>","Post-compaction active task checkpoint. Continue this user-authored request; preserve its exact literals and constraints:",J,"</system-reminder>"].join(`
|
|
100
|
+
`),metadata:{isPostCompactActiveTask:!0}}}static fallbackCompact(Q,Z,$,J){let z=Math.ceil(Q.length*this.FALLBACK_RETAIN_PERCENT),W=Q.slice(-z),G=new Set;for(let L of W)if(L.role==="assistant"&&L.tool_calls)for(let v of L.tool_calls)G.add(v.id);let V=W.filter((L)=>{if(L.role==="tool"&&L.tool_call_id)return G.has(L.tool_call_id);return!0}),Y=e(),B=this.createBoundaryMessage(Y,Z.trigger,$),q=J instanceof Error?J.message:String(J),D=e(),X=this.createSummaryMessage(D,`[Automatic compaction failed; using fallback]
|
|
101
101
|
|
|
102
102
|
An error occurred during compaction. Retained the latest ${z} messages (~30%).
|
|
103
103
|
|
|
104
104
|
Error: ${q}
|
|
105
105
|
|
|
106
|
-
The conversation can continue, but consider retrying compaction later with /compact.`),
|
|
107
|
-
`),preTokens:$,postTokens:A,filesIncluded:[],compactedMessages:
|
|
106
|
+
The conversation can continue, but consider retrying compaction later with /compact.`),w=[X,...V],R=this.buildActiveTaskMessage(Z.activeTask);if(R)w.push(R);let A=j0.countTokens(w,Z.modelName);return{success:!1,summary:typeof X.content==="string"?X.content:X.content.filter((L)=>L.type==="text").map((L)=>L.text).join(`
|
|
107
|
+
`),preTokens:$,postTokens:A,filesIncluded:[],compactedMessages:w,boundaryMessage:B,summaryMessage:X,error:q}}}var aZ=new Set(["Read","Grep","Glob","Search","WebSearch","WebFetch","ToolSearch"]);function oZ(Q,Z){let z=(Q[Z.assistantIdx].tool_calls??[]).filter((G)=>G.type==="function").map((G)=>G.function.name).some((G)=>!aZ.has(G));if(Z.toolResultIdxs.some((G)=>{let V=Q[G]?.content;if(typeof V!=="string")return!1;return V.startsWith("Error:")||V.includes("failed")||V.includes("ENOENT")}))return 3;if(z)return 2;return 1}function q0(Q,Z){let $=Z?.keepRecentTurns??10,J=Z?.minMessagesForSnip??30;if(Q.length<J)return{messages:Q,snippedCount:0,estimatedTokensFreed:0};let z=[];for(let X=0;X<Q.length;X++){let w=Q[X];if(w.role==="assistant"&&w.tool_calls&&w.tool_calls.length>0){let R=new Set(w.tool_calls.map((L)=>L.id)),A=[];for(let L=X+1;L<Q.length;L++){let v=Q[L];if(v.role==="tool"&&v.tool_call_id&&R.has(v.tool_call_id))A.push(L);if(v.role==="assistant"||v.role==="user")break}z.push({assistantIdx:X,toolResultIdxs:A,priority:0})}}for(let X of z)X.priority=oZ(Q,X);let V=[...z.slice(0,Math.max(0,z.length-$))].sort((X,w)=>X.priority-w.priority);if(V.length===0)return{messages:Q,snippedCount:0,estimatedTokensFreed:0};let Y=new Set,B=0;for(let X of V){Y.add(X.assistantIdx);for(let w of X.toolResultIdxs)Y.add(w)}for(let X of Y){let w=Q[X],R=typeof w.content==="string"?w.content:JSON.stringify(w.content);if(B+=R.length,w.tool_calls)B+=JSON.stringify(w.tool_calls).length}let q=[],D=!1;for(let X=0;X<Q.length;X++){if(Y.has(X)){if(!D)q.push({role:"system",content:`[${V.length} earlier tool interaction${V.length===1?"":"s"} snipped for brevity]`}),D=!0;continue}q.push(Q[X])}return{messages:q,snippedCount:V.length,estimatedTokensFreed:Math.floor(B/4)}}var sZ=60000,tZ=3;function TQ(Q,Z){if(!Z)return null;if(Date.now()-Z<sZ)return null;let J=q0(Q,{keepRecentTurns:tZ,minMessagesForSnip:15});if(J.snippedCount===0)return null;return J}class HQ{hasAttempted=!1;async tryReactiveCompact(Q,Z){if(this.hasAttempted)return{success:!1,messages:Q};this.hasAttempted=!0;let $=q0(Q,{keepRecentTurns:3,minMessagesForSnip:10}),J=$.messages;try{let z=await Y0.compact(J,{trigger:"auto",modelName:Z.modelName,maxContextTokens:Z.maxContextTokens,apiKey:Z.apiKey,baseURL:Z.baseURL,signal:Z.signal,activeTask:Z.activeTask});if(z.success)return{success:!0,messages:z.compactedMessages};if($.snippedCount>0)return{success:!0,messages:J};return{success:!1,messages:Q}}catch(z){if($0(z))throw z;if($.snippedCount>0)return{success:!0,messages:J};return{success:!1,messages:Q}}}reset(){this.hasAttempted=!1}}import*as V0 from"fs";import*as XQ from"os";import*as D0 from"path";import{nanoid as dQ}from"nanoid";var eZ=1e5,Q2=2000,CQ=200000;class KQ{currentChars=0;track(Q){this.currentChars+=Q}remaining(){return Math.max(0,CQ-this.currentChars)}isExhausted(){return this.currentChars>=CQ}reset(){this.currentChars=0}}function gQ(Q,Z,$){let J=$?.maxCharsPerResult??eZ,z=$?.previewChars??Q2,W=$?.messageBudget,G=typeof Q==="string"?Q:JSON.stringify(Q,null,2);if(G.length<=J)return Z2(Q,G,Z,z,W,$);let V=$?.outputDir??D0.join(XQ.homedir(),".blade","tool-results"),Y=`${Z}-${dQ(8)}.txt`,B=D0.join(V,Y);try{V0.mkdirSync(V,{recursive:!0}),V0.writeFileSync(B,G,"utf-8")}catch{let X=G.slice(0,J)+`
|
|
108
108
|
|
|
109
|
-
... (truncated, ${G.length} total chars)`;if(W)W.track(X.length);return X}let q=G.slice(0,z),
|
|
109
|
+
... (truncated, ${G.length} total chars)`;if(W)W.track(X.length);return X}let q=G.slice(0,z),D=`Result too large (${G.length} chars). Full output saved to: ${B}
|
|
110
110
|
|
|
111
111
|
Preview:
|
|
112
112
|
${q}
|
|
113
113
|
|
|
114
|
-
... (${G.length-z} more chars in file)`;if(W)W.track(
|
|
114
|
+
... (${G.length-z} more chars in file)`;if(W)W.track(D.length);return D}function Z2(Q,Z,$,J,z,W){if(!z)return Q;let G=z.remaining();if(G<=0){let V=Z.slice(0,J),Y=pQ(Z,V,$,W,"[Message budget exhausted. Full output saved to disk.]");return z.track(typeof Y==="string"?Y.length:J),Y}if(Z.length>G){let V=Math.max(J,G),Y=Z.slice(0,V),B=pQ(Z,Y,$,W,`... (truncated by message budget, ${Z.length} total chars)`);return z.track(typeof B==="string"?B.length:V),B}return z.track(Z.length),Q}function pQ(Q,Z,$,J,z){let W=J?.outputDir??D0.join(XQ.homedir(),".blade","tool-results"),G=`${$}-${dQ(8)}.txt`,V=D0.join(W,G);try{return V0.mkdirSync(W,{recursive:!0}),V0.writeFileSync(V,Q,"utf-8"),`${Z}
|
|
115
115
|
|
|
116
116
|
${z}
|
|
117
117
|
Full output saved to: ${V}`}catch{return`${Z}
|
|
118
118
|
|
|
119
|
-
${z}`}}import*as h0 from"node:fs/promises";import{homedir as tQ}from"node:os";import*as
|
|
119
|
+
${z}`}}import*as h0 from"node:fs/promises";import{homedir as tQ}from"node:os";import*as r from"node:path";var y0={name:"skill-creator",description:"Create new Skills interactively. Use when the user wants to create a new Skill, define a custom workflow, or add a specialized capability to Blade.",allowedTools:["Read","Write","Glob","Bash","AskUserQuestion"],version:"1.0.0",argumentHint:void 0,userInvocable:!0,disableModelInvocation:!1,model:void 0,whenToUse:"User wants to create a new skill, define a custom workflow, or add a specialized capability.",path:"builtin://skill-creator",basePath:"",source:"builtin"};function mQ(){return{metadata:y0,instructions:`# Skill Creator
|
|
120
120
|
|
|
121
121
|
帮助用户创建新的 Blade Skills。
|
|
122
122
|
|
|
@@ -572,11 +572,11 @@ ConfigTool({
|
|
|
572
572
|
2. **permissions 字段使用 replace 策略**:设置 permissions 会完全替换现有值。如果只想添加规则,先 GET 当前值,合并后再 SET
|
|
573
573
|
3. **env 字段使用 deep-merge 策略**:可以逐个添加环境变量
|
|
574
574
|
4. **scope 默认值**:不指定 scope 时,根据字段路由表决定(hooks/permissions/env 默认 local,temperature/theme 等默认 global)
|
|
575
|
-
`}}import{exec as
|
|
576
|
-
`)}get size(){return this.skills.size}async refresh(){return this.skills.clear(),this.pluginSkills.clear(),this.initialized=!1,this.initialize()}registerPluginSkill(Q){this.pluginSkills.set(Q.namespacedName,Q),this.skills.set(Q.namespacedName,Q.metadata)}findPluginSkill(Q){let Z=this.pluginSkills.get(Q);if(Z)return Z;let $=[];for(let J of this.pluginSkills.values())if(J.originalName===Q)$.push(J);if($.length===1)return $[0];return}getAllPluginSkills(){return Array.from(this.pluginSkills.values())}clearPluginSkills(){for(let Q of this.pluginSkills.values())this.skills.delete(Q.namespacedName);this.pluginSkills.clear()}getPluginSkillCount(){return this.pluginSkills.size}}function k0(Q){return qQ.getInstance(Q)}async function
|
|
575
|
+
`}}import{exec as $2}from"node:child_process";import*as O from"node:fs/promises";import{homedir as J2}from"node:os";import*as I from"node:path";import{promisify as z2}from"node:util";var P0=z2($2),E=g("General"),BQ={url:"https://github.com/anthropics/skills.git",branch:"main",defaultSkills:["skill-creator"]};class uQ{skillsDir;constructor(Q){this.skillsDir=Q||I.join(J2(),".blade","skills")}async isInstalled(Q){let Z=I.join(this.skillsDir,Q,"SKILL.md");try{return await O.access(Z),!0}catch{return!1}}async isGitAvailable(){try{return await P0("git --version"),!0}catch{return!1}}async installOfficialSkill(Q){let{url:Z,branch:$}=BQ,J=I.join(this.skillsDir,Q),z=I.join(this.skillsDir,`.tmp-${Q}-${Date.now()}`);try{if(!await this.isGitAvailable())return E.warn("Git not available, skipping skill installation"),!1;E.info(`Installing official skill: ${Q}...`),await O.mkdir(this.skillsDir,{recursive:!0,mode:493}),await P0(`git clone --depth 1 --branch ${$} --single-branch ${Z} "${z}"`,{timeout:30000});let W=I.join(z,"skills",Q);try{await O.access(W)}catch{return E.warn(`Skill ${Q} not found in official repository`),await O.rm(z,{recursive:!0,force:!0}),!1}try{await O.rm(J,{recursive:!0,force:!0})}catch{}return await O.cp(W,J,{recursive:!0}),await O.rm(z,{recursive:!0,force:!0}),E.info(`Successfully installed: ${Q}`),!0}catch(W){try{await O.rm(z,{recursive:!0,force:!0})}catch{}return E.warn(`Failed to install ${Q}: ${W instanceof Error?W.message:"Unknown error"}`),!1}}async ensureDefaultSkillsInstalled(){await O.mkdir(this.skillsDir,{recursive:!0,mode:493});for(let Q of BQ.defaultSkills)if(!await this.isInstalled(Q))await this.installOfficialSkill(Q)}async installFromRepo(Q,Z){let $=Z||this.extractRepoName(Q),J=I.join(this.skillsDir,$),z=I.join(this.skillsDir,`.tmp-repo-${$}-${Date.now()}`);try{if(!await this.isGitAvailable())return E.warn("Git not available, cannot install from repo"),!1;E.info(`Installing skill from repo: ${Q}...`),await O.mkdir(this.skillsDir,{recursive:!0,mode:493}),await P0(`git clone --depth 1 "${Q}" "${z}"`,{timeout:60000});let W=I.join(z,"SKILL.md");try{await O.access(W)}catch{return E.warn(`No SKILL.md found in repository ${Q}`),await O.rm(z,{recursive:!0,force:!0}),!1}await O.rm(J,{recursive:!0,force:!0}),await O.rename(z,J);try{await O.rm(I.join(J,".git"),{recursive:!0,force:!0})}catch{}return E.info(`Successfully installed skill from repo: ${$}`),!0}catch(W){try{await O.rm(z,{recursive:!0,force:!0})}catch{}return E.warn(`Failed to install from repo ${Q}: ${W instanceof Error?W.message:"Unknown error"}`),!1}}async installFromLocal(Q,Z,$=!0){let J=Z||I.basename(Q),z=I.join(this.skillsDir,J);try{let W=I.resolve(Q);try{await O.access(W)}catch{return E.warn(`Local path does not exist: ${W}`),!1}let G=I.join(W,"SKILL.md");try{await O.access(G)}catch{return E.warn(`No SKILL.md found in local path: ${W}`),!1}if(E.info(`Installing skill from local path: ${W}...`),await O.mkdir(this.skillsDir,{recursive:!0,mode:493}),await O.rm(z,{recursive:!0,force:!0}),$)await O.symlink(W,z,"dir"),E.info(`Created symlink for skill: ${J}`);else await O.cp(W,z,{recursive:!0}),E.info(`Copied skill to: ${J}`);return!0}catch(W){return E.warn(`Failed to install from local path ${Q}: ${W instanceof Error?W.message:"Unknown error"}`),!1}}extractRepoName(Q){return Q.match(/\/([^/]+?)(\.git)?$/)?.[1]||"unknown-skill"}async installAllOfficialSkills(){let{url:Q,branch:Z}=BQ,$=I.join(this.skillsDir,`.tmp-all-${Date.now()}`),J=[],z=[];try{if(!await this.isGitAvailable())return E.warn("Git not available, skipping skill installation"),{installed:J,failed:z};await O.mkdir(this.skillsDir,{recursive:!0,mode:493}),E.info("Cloning official skills repository..."),await P0(`git clone --depth 1 --branch ${Z} --single-branch ${Q} "${$}"`,{timeout:60000});let W=I.join($,"skills"),G=await O.readdir(W,{withFileTypes:!0});for(let V of G){if(!V.isDirectory())continue;let Y=V.name,B=I.join(W,Y),q=I.join(this.skillsDir,Y);try{await O.access(I.join(B,"SKILL.md")),await O.rm(q,{recursive:!0,force:!0}),await O.cp(B,q,{recursive:!0}),E.info(`Installed: ${Y}`),J.push(Y)}catch(D){E.warn(`Failed to install ${Y}`),z.push(Y)}}await O.rm($,{recursive:!0,force:!0})}catch(W){try{await O.rm($,{recursive:!0,force:!0})}catch{}E.warn(`Failed to install skills: ${W instanceof Error?W.message:"Unknown error"}`)}return{installed:J,failed:z}}}var jQ=null;function iQ(Q){if(!jQ)jQ=new uQ(Q);return jQ}import*as b0 from"node:fs/promises";import*as M0 from"node:path";import{parse as W2}from"yaml";var G2=/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/,Y2=/^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]?$/,nQ=1024;function V2(Q){if(!Q)return;if(typeof Q==="string")return Q.split(",").map((Z)=>Z.trim()).filter(Boolean);if(Array.isArray(Q))return Q.map((Z)=>String(Z).trim()).filter(Boolean);return}function lQ(Q){if(Q===void 0)return;if(typeof Q==="boolean")return Q;if(typeof Q==="string"){let Z=Q.toLowerCase().trim();if(Z==="true"||Z==="yes"||Z==="1")return!0;if(Z==="false"||Z==="no"||Z==="0")return!1}return}function H2(Q,Z){if(!Q.name)return{valid:!1,error:"Missing required field: name"};if(!Y2.test(Q.name))return{valid:!1,error:`Invalid name "${Q.name}": must be lowercase letters, numbers, and hyphens only, 1-64 characters`};if(!Q.description)return{valid:!1,error:"Missing required field: description"};if(Q.description.length>nQ)return{valid:!1,error:`Description too long: ${Q.description.length} characters (max ${nQ})`};let $;if(Q.model)$=Q.model==="inherit"?"inherit":Q.model;return{valid:!0,metadata:{name:Q.name,description:Q.description.trim(),allowedTools:V2(Q["allowed-tools"]),version:Q.version,argumentHint:Q["argument-hint"]?.trim(),userInvocable:lQ(Q["user-invocable"]),disableModelInvocation:lQ(Q["disable-model-invocation"]),model:$,whenToUse:Q.when_to_use?.trim()}}}function rQ(Q,Z,$){let J=Q.match(G2);if(!J)return{success:!1,error:"Invalid SKILL.md format: missing YAML frontmatter (must start with ---)"};let[,z,W]=J,G;try{G=W2(z)}catch(B){return{success:!1,error:`Failed to parse YAML frontmatter: ${B instanceof Error?B.message:String(B)}`}}let V=H2(G,Z);if(!V.valid)return{success:!1,error:V.error};let Y=M0.dirname(Z);return{success:!0,content:{metadata:{...V.metadata,path:Z,basePath:Y,source:$},instructions:W.trim()}}}async function aQ(Q,Z){try{let $=await b0.readFile(Q,"utf-8");return rQ($,Q,Z)}catch($){if($.code==="ENOENT")return{success:!1,error:`File not found: ${Q}`};return{success:!1,error:`Failed to read file: ${$ instanceof Error?$.message:String($)}`}}}async function oQ(Q){try{let Z=await b0.readFile(Q.path,"utf-8"),$=rQ(Z,Q.path,Q.source);return $.success?$.content:null}catch{return null}}async function sQ(Q){try{return await b0.access(M0.join(Q,"SKILL.md")),!0}catch{return!1}}var X2={userSkillsDir:r.join(tQ(),".blade","skills"),projectSkillsDir:".blade/skills",claudeUserSkillsDir:r.join(tQ(),".claude","skills"),claudeProjectSkillsDir:".claude/skills"},f0=null;class qQ{skills=new Map;pluginSkills=new Map;config;initialized=!1;constructor(Q){this.config={...X2,cwd:i(),...Q}}static getInstance(Q){if(!f0)f0=new qQ(Q);return f0}static resetInstance(){f0=null}async initialize(){if(this.initialized)return{skills:Array.from(this.skills.values()),errors:[]};let Q=[],Z=[];try{await iQ(this.config.userSkillsDir).ensureDefaultSkillsInstalled()}catch(Y){Q.push({path:"SkillInstaller",error:`Failed to install default skills: ${Y instanceof Error?Y.message:"Unknown error"}`})}this.loadBuiltinSkills();let $=await this.scanDirectory(this.config.claudeUserSkillsDir,"user");Z.push(...$.skills),Q.push(...$.errors);let J=await this.scanDirectory(this.config.userSkillsDir,"user");Z.push(...J.skills),Q.push(...J.errors);let z=r.isAbsolute(this.config.claudeProjectSkillsDir)?this.config.claudeProjectSkillsDir:r.join(this.config.cwd,this.config.claudeProjectSkillsDir),W=await this.scanDirectory(z,"project");Z.push(...W.skills),Q.push(...W.errors);let G=r.isAbsolute(this.config.projectSkillsDir)?this.config.projectSkillsDir:r.join(this.config.cwd,this.config.projectSkillsDir),V=await this.scanDirectory(G,"project");Z.push(...V.skills),Q.push(...V.errors);for(let Y of Z)this.skills.set(Y.name,Y);return this.initialized=!0,{skills:Array.from(this.skills.values()),errors:Q}}loadBuiltinSkills(){this.skills.set(y0.name,y0),this.skills.set(A0.name,A0)}async scanDirectory(Q,Z){let $=[],J=[];try{await h0.access(Q)}catch{return{skills:$,errors:J}}try{let z=await h0.readdir(Q,{withFileTypes:!0});for(let W of z){if(!W.isDirectory())continue;let G=r.join(Q,W.name),V=r.join(G,"SKILL.md");if(!await sQ(G))continue;let Y=await aQ(V,Z);if(Y.success&&Y.content)$.push(Y.content.metadata);else J.push({path:V,error:Y.error||"Unknown error"})}}catch(z){J.push({path:Q,error:`Failed to scan directory: ${z instanceof Error?z.message:String(z)}`})}return{skills:$,errors:J}}getAll(){return Array.from(this.skills.values())}get(Q){return this.skills.get(Q)}has(Q){return this.skills.has(Q)}async loadContent(Q){let Z=this.skills.get(Q);if(!Z)return null;if(Z.source==="builtin")return this.loadBuiltinContent(Q);return oQ(Z)}loadBuiltinContent(Q){switch(Q){case"skill-creator":return mQ();case"update-config":return cQ();default:return null}}getModelInvocableSkills(){return Array.from(this.skills.values()).filter((Q)=>!Q.disableModelInvocation)}getUserInvocableSkills(){return Array.from(this.skills.values()).filter((Q)=>Q.userInvocable===!0)}generateAvailableSkillsList(){let Q=this.getModelInvocableSkills();if(Q.length===0)return"";let Z=[];for(let $ of Q){let J=$.description.length>100?`${$.description.substring(0,97)}...`:$.description,z=$.argumentHint?`${$.name} ${$.argumentHint}`:$.name;Z.push(`- ${z}: ${J}`)}return Z.join(`
|
|
576
|
+
`)}get size(){return this.skills.size}async refresh(){return this.skills.clear(),this.pluginSkills.clear(),this.initialized=!1,this.initialize()}registerPluginSkill(Q){this.pluginSkills.set(Q.namespacedName,Q),this.skills.set(Q.namespacedName,Q.metadata)}findPluginSkill(Q){let Z=this.pluginSkills.get(Q);if(Z)return Z;let $=[];for(let J of this.pluginSkills.values())if(J.originalName===Q)$.push(J);if($.length===1)return $[0];return}getAllPluginSkills(){return Array.from(this.pluginSkills.values())}clearPluginSkills(){for(let Q of this.pluginSkills.values())this.skills.delete(Q.namespacedName);this.pluginSkills.clear()}getPluginSkillCount(){return this.pluginSkills.size}}function k0(Q){return qQ.getInstance(Q)}async function K2(Q){return k0(Q).initialize()}var B2="Skill",j2=/<available_skills>\s*<\/available_skills>/;function DQ(Q){let $=k0().generateAvailableSkillsList();if(!$)return Q;return Q.map((J)=>{if(J.name!==B2)return J;let z=J.description.replace(j2,`<available_skills>
|
|
577
577
|
${$}
|
|
578
|
-
</available_skills>`);if(z===J.description)return J;return{...J,description:z}})}function eQ(){return{consecutiveFailures:new Map,totalFailures:0,lastFailedTool:null}}function QZ(Q,Z){Q.consecutiveFailures.set(Z,0),Q.lastFailedTool=null}function ZZ(Q,Z){let $=(Q.consecutiveFailures.get(Z)??0)+1;Q.consecutiveFailures.set(Z,$),Q.totalFailures++,Q.lastFailedTool=Z}function
|
|
579
|
-
`)}function WZ(){return{recentOutputHashes:[]}}function
|
|
578
|
+
</available_skills>`);if(z===J.description)return J;return{...J,description:z}})}function eQ(){return{consecutiveFailures:new Map,totalFailures:0,lastFailedTool:null}}function QZ(Q,Z){Q.consecutiveFailures.set(Z,0),Q.lastFailedTool=null}function ZZ(Q,Z){let $=(Q.consecutiveFailures.get(Z)??0)+1;Q.consecutiveFailures.set(Z,$),Q.totalFailures++,Q.lastFailedTool=Z}function q2(Q,Z){return(Q.consecutiveFailures.get(Z)??0)>=3}function $Z(Q,Z){if(!q2(Q,Z))return;let $=Q.consecutiveFailures.get(Z)??0;return`WARNING: ${Z} has failed ${$} consecutive times. Consider a different approach: use a different tool, verify your parameters, or break the task into smaller steps.`}function JZ(Q){return Q>0&&Q%5===0}function zZ(Q,Z){let $=[`[Self-check at turn ${Q}]`,"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(Z>3)$.push(`Note: ${Z} tool failures so far. Consider whether your current strategy needs adjustment.`);return $.join(`
|
|
579
|
+
`)}function WZ(){return{recentOutputHashes:[]}}function D2(Q){let Z=Q.trim().slice(0,500),$=0;for(let J=0;J<Z.length;J++)$=($<<5)-$+Z.charCodeAt(J)|0;return $.toString(36)}function GZ(Q,Z){let $=D2(Z);if(Q.recentOutputHashes.push($),Q.recentOutputHashes.length>4)Q.recentOutputHashes.shift();if(Q.recentOutputHashes.length<3)return!1;let J=Q.recentOutputHashes.slice(-3),z=J.every((W)=>W===J[0]);if(z)Q.recentOutputHashes=[];return z}function YZ(){return"WARNING: You appear to be repeating the same output. Stop and try a fundamentally different approach. If the task cannot be completed, explain why and stop."}var Q0=g("Agent"),F2=new Set(["Read","Glob","Grep","WebFetch","WebSearch","MemoryRead","GetSpecContext","ValidateSpec","TaskOutput"]);class x0{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,z,W,G){this.pipeline=Q;this.execContext=Z;this.registry=$;this.contextMgr=J;this.sessionId=z;this.lastMessageUuid=W;this.subagentInfo=G}addTool(Q,Z){if(this.dispatched.has(Q.id)){Q0.debug(`[StreamingToolExecutor] 跳过已分发工具: ${Q.function.name} (${Q.id})`);return}if(this.dispatched.add(Q.id),this.order.push(Q.id),F2.has(Q.function.name)){Q0.debug(`[StreamingToolExecutor] 立即执行预启动工具: ${Q.function.name}`);let J=this.executeOne(Q,Z);this.pending.set(Q.id,J)}else Q0.debug(`[StreamingToolExecutor] 排队非预启动工具: ${Q.function.name}`),this.queued.push({toolCall:Q,params:Z})}async*getRemainingResults(){for(let Q of this.order){if(this.completed.has(Q)){yield this.completed.get(Q),this.completed.delete(Q);continue}if(this.pending.has(Q)){let $=await this.pending.get(Q);this.pending.delete(Q),yield $;continue}let Z=this.queued.findIndex(($)=>$.toolCall.id===Q);if(Z!==-1){let{toolCall:$,params:J}=this.queued[Z];if(this.queued.splice(Z,1),this.execContext.signal?.aborted){Q0.debug(`[StreamingToolExecutor] Signal aborted, 跳过排队工具: ${$.function.name} (${$.id})`),yield this.makeAbortResult($,"Tool execution skipped: task aborted before launch");continue}yield await this.executeOne($,J)}}}getCompletedResults(){let Q=Array.from(this.completed.values());return this.completed.clear(),Q}discard(){this.epoch++,this.abortController.abort(),this.abortController=new AbortController;for(let[,Q]of this.activeAborts)Q.abort();this.activeAborts.clear(),this.queued=[],this.order=[],this.dispatched.clear(),this.completed.clear(),this.pending.clear(),Q0.debug(`[StreamingToolExecutor] 已丢弃所有挂起工作并重置状态 (epoch=${this.epoch})`)}hasTools(){return this.order.length>0}getEpoch(){return this.epoch}makeAbortResult(Q,Z){return{toolCall:Q,result:{success:!1,llmContent:"",error:{type:"execution_error",message:Z},metadata:{abortedBeforeLaunch:!0}},toolUseUuid:null}}async executeOne(Q,Z){let $=this.epoch,J=new AbortController;this.activeAborts.set(Q.id,J);let z=this.abortController.signal;try{if(z.aborted||J.signal.aborted)return this.makeAbortResult(Q,"Tool execution aborted due to discard");let W=null;try{if(this.contextMgr&&this.sessionId)W=await this.contextMgr.saveToolUse(this.sessionId,Q.function.name,Z,this.lastMessageUuid??null,this.subagentInfo)}catch(X){Q0.warn("[StreamingToolExecutor] 保存工具调用失败:",X)}let G=[z,J.signal],V=this.execContext.signal;if(V)G.push(V);let Y=VZ(...G),B={...this.execContext,signal:Y},q=await this.pipeline.execute(Q.function.name,Z,B);if($!==this.epoch)return Q0.debug(`[StreamingToolExecutor] 丢弃旧世代工具结果: ${Q.function.name} (startEpoch=${$}, currentEpoch=${this.epoch})`),this.makeAbortResult(Q,"Tool execution aborted due to epoch mismatch (discard)");let D={toolCall:Q,result:q,toolUseUuid:W};if(this.pending.has(Q.id))this.pending.delete(Q.id),this.completed.set(Q.id,D);return D}catch(W){if($!==this.epoch)return this.makeAbortResult(Q,"Tool execution aborted due to epoch mismatch (discard)");Q0.error(`[StreamingToolExecutor] 工具执行失败: ${Q.function.name}`,W);let G={success:!1,llmContent:"",error:{type:"execution_error",message:W instanceof Error?W.message:"Unknown error"},metadata:void 0},V={toolCall:Q,result:G,toolUseUuid:null,error:W instanceof Error?W:Error("Unknown error")};if(this.pending.has(Q.id))this.pending.delete(Q.id),this.completed.set(Q.id,V);return V}finally{this.activeAborts.delete(Q.id)}}}var U=g("Agent"),w2=0.1,L2=8192,_2=32768,N2=2,v2=0.95,R0=100,E2=`
|
|
580
580
|
|
|
581
581
|
# Task Execution Strategy
|
|
582
582
|
When facing complex multi-step tasks:
|
|
@@ -584,23 +584,23 @@ When facing complex multi-step tasks:
|
|
|
584
584
|
2. Execute one step at a time — verify each step succeeded before moving to the next.
|
|
585
585
|
3. If a step fails, diagnose the root cause rather than repeating the same approach.
|
|
586
586
|
4. When uncertain about file paths or project structure, use Grep/Glob/Read to gather facts first.
|
|
587
|
-
5. Prefer the smallest change that achieves the goal — avoid unnecessary refactoring.`;function HZ(Q){let Z=Q.trim();if(Z=Z.replace(/,\s*([}\]])/g,"$1"),Z.startsWith("{")&&!Z.endsWith("}"))Z+="}";Z=Z.replace(/,\s*([}\]])/g,"$1");try{let $=JSON.parse(Z);if(typeof $==="object"&&$!==null&&!Array.isArray($))return $;return null}catch{return null}}function KZ(Q){let Z=HZ(Q);if(Z)return Z;try{let $=JSON.parse(Q);return typeof $==="string"?HZ($):null}catch{return null}}function
|
|
588
|
-
`)}function
|
|
587
|
+
5. Prefer the smallest change that achieves the goal — avoid unnecessary refactoring.`;function HZ(Q){let Z=Q.trim();if(Z=Z.replace(/,\s*([}\]])/g,"$1"),Z.startsWith("{")&&!Z.endsWith("}"))Z+="}";Z=Z.replace(/,\s*([}\]])/g,"$1");try{let $=JSON.parse(Z);if(typeof $==="object"&&$!==null&&!Array.isArray($))return $;return null}catch{return null}}function KZ(Q){let Z=HZ(Q);if(Z)return Z;try{let $=JSON.parse(Q);return typeof $==="string"?HZ($):null}catch{return null}}function I2(Q){if(typeof Q==="string")return Q;try{return JSON.parse(JSON.stringify(Q))}catch{return String(Q)}}function U2(Q){if(!(Q instanceof Error))return"未知错误";let J=Q.lastError??Q;if(J.responseBody)try{let V=JSON.parse(J.responseBody)?.error?.message;if(V){let Y=J.statusCode?` (HTTP ${J.statusCode})`:"";return`${V}${Y}`}}catch{}let z=Q.message,W=z.match(/Last error:\s*(.+)$/);if(W)return W[1];return z}function S2(Q){if(!(Q instanceof Error))return!1;return["stream not supported","streaming is not available","sse not supported","does not support streaming"].some(($)=>Q.message.toLowerCase().includes($.toLowerCase()))}function y2(Q,Z){if(!Z)return"Tool execution failed (no details).";let $=[`Error: ${Z.message||"Unknown error"}`];if(Z.type==="validation_error")$.push("Hint: Check the tool parameters — a required field may be missing or have the wrong type.");else if(Z.type==="permission_denied")$.push("Hint: This operation requires user approval. Try a different approach or ask the user.");else if(Z.type==="timeout_error")$.push("Hint: The operation timed out. Consider breaking it into smaller steps or increasing timeout.");else if(Z.type==="execution_error"){let J=Z.message??"";if(J.includes("ENOENT")||J.includes("no such file"))$.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"))$.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"))$.push(`Hint: The target text was not found. Use Read to view the current file content, then retry ${Q} with the exact text.`);else if(J.includes("ENOTDIR"))$.push("Hint: A path component is not a directory. Verify the full path with Glob.")}return $.join(`
|
|
588
|
+
`)}function A2(Q){if(!(Q instanceof Error))return!1;let Z=Q.message.toLowerCase();return Z.includes("prompt_too_long")||Z.includes("prompt is too long")||Z.includes("maximum context length")||Z.includes("request too large")||Q.status===413}function P2(Q,Z){let $=Z,J=$.index??0;if(!Q.has(J))Q.set(J,{id:$.id||"",name:$.function?.name||"",arguments:""});let z=Q.get(J);if($.id&&!z.id)z.id=$.id;if($.function?.name&&!z.name)z.name=$.function.name;if($.function?.arguments)z.arguments+=$.function.arguments}function M2(Q){if(Q.size===0)return;return Array.from(Q.values()).filter((Z)=>Z.id&&Z.name).map((Z)=>({id:Z.id,type:"function",function:{name:Z.name,arguments:Z.arguments}}))}async function*f2(Q,Z,$,J,z){let W="",G="",V,Y,B=new Map;try{let q=Q.chatService.streamChat(Z,$,J),D=0;for await(let X of q){if(D++,J?.aborted)break;if(X.modelFallback){z?.discard(),W="",G="",V=void 0,Y=void 0,B.clear(),D=0,yield{kind:"model_fallback"};continue}if(X.content)W+=X.content,yield{kind:"content_delta",delta:X.content};if(X.reasoningContent)G+=X.reasoningContent,yield{kind:"thinking_delta",delta:X.reasoningContent};if(X.usage)V=X.usage;if(X.toolCalls){for(let w of X.toolCalls)if(P2(B,w),z){let A=w.index??0,L=B.get(A);if(L&&L.id&&L.name)try{let v=KZ(L.arguments);if(v===null)continue;let j={id:L.id,type:"function",function:{name:L.name,arguments:L.arguments}},u=Q.toolExecutor.getRegistry().get(L.name)?.kind;z.addTool(j,v),yield{kind:"tool_start",toolCall:j,toolKind:u}}catch{}}}if(X.finishReason){Y=X.finishReason;break}}if(D===0&&!J?.aborted&&W.length===0&&B.size===0)return U.warn("[Loop] 流式响应返回0个chunk,回退到非流式模式"),z?.discard(),{...await Q.chatService.chat(Z,$,J),_nonStreamingFallback:!0};return{content:W,reasoningContent:G||void 0,toolCalls:M2(B),usage:V,finishReason:Y}}catch(q){if(S2(q))return U.warn("[Loop] 流式请求失败,降级到非流式模式"),z?.discard(),{...await Q.chatService.chat(Z,$,J),_nonStreamingFallback:!0};throw q}}async function*BZ(Q,Z,$,J,z,W,G,V){if(J===void 0)return U.debug(`[Loop] [轮次 ${$}] 压缩检查: 跳过(无历史 usage 数据)`),"none";let Y=TQ(Z.messages,W);if(Y)Z.messages=Y.messages,U.debug(`[Loop] [轮次 ${$}] MicroCompact: 清理 ${Y.snippedCount} 轮旧工具结果(缓存已过期)`);let B=q0(Z.messages),q=!1;if(B.snippedCount>0)q=!0,U.debug(`[Loop] [轮次 ${$}] Snip 压缩: 移除 ${B.snippedCount} 轮旧工具调用,释放约 ${B.estimatedTokensFreed} tokens`);let D=Q.chatService.getConfig(),X=D.model,w=D.maxContextTokens??Q.config.maxContextTokens,R=D.maxOutputTokens??Q.config.maxOutputTokens??Math.min(Math.max(Math.floor(w*w2),L2),_2),A=w-R,L=Math.floor(A*0.8);if(U.debug(`[Loop] [轮次 ${$}] 压缩检查:`,{promptTokens:J,maxContextTokens:w,maxOutputTokens:R,availableForInput:A,threshold:L,shouldCompact:J>=L}),J<L){if(q)Z.messages=B.messages;return q?"snipped":"none"}let v=V?.lastCompactionTurn===void 0?void 0:$-V.lastCompactionTurn,j=v!==void 0&&v<=N2,a=Math.floor(A*v2);if(j&&J<a){if(q)Z.messages=B.messages;return U.debug(`[Loop] [轮次 ${$}] 跳过连续 LLM 压缩,距离上次压缩 ${v} 轮`),q?"snipped":"none"}U.debug($===0?"[Loop] 触发自动压缩":`[Loop] [轮次 ${$}] 触发循环内自动压缩`),yield{kind:"compaction",phase:"start"};try{let u=q?B.messages:Z.messages,P=await Y0.compact(u,{trigger:"auto",modelName:X,maxContextTokens:w,apiKey:D.apiKey,baseURL:D.baseUrl,actualPreTokens:J,signal:z,activeTask:G});if(Z.messages=P.compactedMessages,V)V.lastCompactionTurn=$;if(P.success)U.debug(`[Loop] [轮次 ${$}] 压缩完成: ${P.preTokens} -> ${P.postTokens} tokens`);else U.warn(`[Loop] [轮次 ${$}] 压缩使用降级策略: ${P.preTokens} -> ${P.postTokens} tokens`);return await E0(Q,Z,P.summary,{trigger:"auto",preTokens:P.preTokens,postTokens:P.postTokens,filesIncluded:P.filesIncluded}),"compacted"}catch(u){if($0(u))return U.debug(`[Loop] [轮次 ${$}] 压缩被中止`),"none";if(q)Z.messages=B.messages;return U.error(`[Loop] [轮次 ${$}] 压缩失败,继续执行`,u),q?"snipped":"none"}finally{yield{kind:"compaction",phase:"end"}}}function h2(Q,Z,$,J){let z=J?XZ(J):"user-cancel";return{success:!1,error:{type:"aborted",message:(z==="interrupt"?void 0:"任务已被用户中止")??"任务已中断"},metadata:{turnsCount:Q,toolCallsCount:Z,duration:Date.now()-$,abortReason:z}}}async function*k2(Q,Z,$,J,z){let W=Date.now(),G=0,V=[],Y=null,B=!1,q=(D,X,w)=>{return B=!0,h2(D,X,W,w)};try{let D=Q.toolExecutor.getRegistry(),X=$.permissionMode,w=D.getFunctionDeclarationsByMode(X);w=DQ(w);let R=Q.applySkillToolRestrictions(w),A=eQ(),L=WZ(),v=z;if(typeof D.getDeferredToolsListing==="function"){let f=D.getDeferredToolsListing();if(f&&v)v=`${v}
|
|
589
589
|
|
|
590
|
-
${
|
|
591
|
-
`),u0=[
|
|
592
|
-
`),F0=v0(
|
|
593
|
-
`);if(H.trim())
|
|
594
|
-
`),u0=[
|
|
595
|
-
`),F0=F0||v0(H)}return{messageIds:
|
|
590
|
+
${f}`}if(v)v+=E2;let j=new _0($,v),a=J?.pendingInputOnly===!0;if(!a){let f=J?.inputMessageId?{inboxMessageId:J.inputMessageId}:void 0;if(j.appendUser({role:"user",content:Z,metadata:f}),Y=await l(Q,$,Z,null,f),J?.inputMessageId&&!Y)throw Error(`Failed to persist durable input before applying it: ${J.inputMessageId}`)}let u=$.permissionMode==="yolo",P=!!$.subagentInfo,T0=Q.runtimeOptions.maxTurns!==void 0||J?.maxTurns!==void 0,T=Q.runtimeOptions.maxTurns??J?.maxTurns??Q.config.maxTurns??-1;if(T===0)return{success:!1,error:{type:"chat_disabled",message:"对话功能已被禁用 (maxTurns=0)"},metadata:{turnsCount:0,toolCallsCount:0,duration:0}};let H0=T===-1?R0:Math.min(T,R0),o=0,C0,bQ,X0=0,p0=0,d0=0,g0=0,m0=0,c0=new Set,C=new Set($.worktreeActive?["EnterWorktree"]:[]),n=typeof Z==="string"?Z:Z.filter((f)=>f.type==="text").map((f)=>f.text).join(`
|
|
591
|
+
`),u0=[n,$.completionRequirements?.trim()].filter(Boolean).join(`
|
|
592
|
+
`),F0=v0(n),i0=!a,n0=wQ({budget:Q.currentModelMaxContextTokens,isSubagent:P}),FQ=new HQ,jZ={},l0=async(f)=>{for(let p of f){if(!j.getHistory().some((m)=>{let J0=m.metadata;return J0!==null&&typeof J0==="object"&&!Array.isArray(J0)&&J0.inboxMessageId===p.id})){let m=await l(Q,$,p.content,Y,{inboxMessageId:p.id});if(!m)throw Error(`Failed to persist steering message before applying it: ${p.id}`);Y=m,j.appendUser({role:"user",content:p.content,metadata:{inboxMessageId:p.id}})}let H=typeof p.content==="string"?p.content:p.content.filter((m)=>m.type==="text").map((m)=>m.text).join(`
|
|
593
|
+
`);if(H.trim())n=[n,H].join(`
|
|
594
|
+
`),u0=[n,$.completionRequirements?.trim()].filter(Boolean).join(`
|
|
595
|
+
`),F0=F0||v0(H)}return{messageIds:f.map((p)=>p.id),count:f.length,recovered:f.filter((p)=>p.recovered).length}};try{while(!0){if(J?.signal?.aborted)return q(G,V.length,J.signal);let f=await J?.turnSteering?.drain()??[];if(f.length>0)yield{kind:"steering_applied",...await l0(f),delivery:i0?"current_turn":"next_turn"},i0=!0;else if(!i0)return{success:!0,finalMessage:"",metadata:{turnsCount:0,toolCallsCount:0,duration:Date.now()-W}};if(j.writeback(),(yield*BZ(Q,$,G,C0,J?.signal,bQ,n,jZ))!=="none")j.replaceHistory($.messages);if(G++,FQ.reset(),yield{kind:"turn_start",turn:G,maxTurns:H0},J?.signal?.aborted)return q(G-1,V.length,J.signal);if(JZ(G)&&G>1){let N=zZ(G,A.totalFailures);j.appendControl("user",{role:"user",content:`
|
|
596
596
|
|
|
597
597
|
<system-reminder>
|
|
598
|
-
${
|
|
599
|
-
</system-reminder>`})}let r0=J?.stream!==!1,H,m;try{if(r0)m=new x0(Q.toolExecutor,{sessionId:$.sessionId,userId:$.userId||"default",workspaceRoot:$.workspaceRoot||
|
|
598
|
+
${N}
|
|
599
|
+
</system-reminder>`})}let r0=J?.stream!==!1,H,m;try{if(r0)m=new x0(Q.toolExecutor,{sessionId:$.sessionId,userId:$.userId||"default",workspaceRoot:$.workspaceRoot||i(),worktreeIsolationRequired:F0,worktreeActive:C.has("EnterWorktree")&&!C.has("ExitWorktree"),signal:J?.signal,confirmationHandler:$.confirmationHandler,permissionMode:$.permissionMode,toolRegistry:D,deferredToolManager:D.deferredToolManager},Q.toolExecutor.getRegistry(),Q.executionEngine?.getContextManager(),$.sessionId,Y,$.subagentInfo),H=yield*f2(Q,j.toLLMMessages(),R,J?.signal,m);else H=await Q.chatService.chat(j.toLLMMessages(),R,J?.signal)}catch(N){if(A2(N)){U.warn("[Loop] 检测到 prompt_too_long 错误,尝试反应式压缩");let K=Q.chatService.getConfig(),F=await FQ.tryReactiveCompact($.messages,{modelName:K.model,maxContextTokens:K.maxContextTokens??Q.config.maxContextTokens,apiKey:K.apiKey,baseURL:K.baseUrl,signal:J?.signal,activeTask:n});if(F.success){$.messages=F.messages,j.replaceHistory($.messages),U.info("[Loop] 反应式压缩成功,重试 LLM 调用"),G--;continue}}throw N}if(bQ=Date.now(),H.usage){if(H.usage.totalTokens)o+=H.usage.totalTokens;C0=H.usage.promptTokens,yield{kind:"token_usage",usage:{inputTokens:H.usage.promptTokens??0,outputTokens:H.usage.completionTokens??0,totalTokens:H.usage.totalTokens??0,maxContextTokens:Q.currentModelMaxContextTokens}}}let J0=H.usage?.completionTokens??0;if(n0=LQ(n0,J0,X0>0),J?.signal?.aborted)return q(G-1,V.length,J.signal);if(!r0||!!H._nonStreamingFallback){if(H.reasoningContent&&H.reasoningContent.trim())yield{kind:"thinking_delta",delta:H.reasoningContent};if(H.content&&H.content.trim())yield{kind:"content_delta",delta:H.content}}yield{kind:"stream_end"};let a0=QQ(H.finishReason,X0,n0);if(a0.action==="recover"){X0++,U.warn(`[Loop] Max output tokens hit (recovery ${X0}/3)`);let N={role:"assistant",content:H.content||"",reasoningContent:H.reasoningContent,tool_calls:H.toolCalls};j.appendToHistory(N);let K=await x(Q,$,H.content||"",Y);if(K)Y=K;let F={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."};j.appendToHistory(F);let b=await l(Q,$,F.content,Y);if(b)Y=b;continue}if(a0.action==="truncated"||a0.action==="budget_stop"){j.appendAssistant({role:"assistant",content:H.content||"",reasoningContent:H.reasoningContent,tool_calls:H.toolCalls});let N=await x(Q,$,H.content||"",Y);if(N)Y=N;return{success:!0,finalMessage:H.content,metadata:{turnsCount:G,toolCallsCount:V.length,duration:Date.now()-W,tokensUsed:o,outputTruncated:!0}}}if(H.finishReason!=="length")X0=0;if(!H.toolCalls||H.toolCalls.length===0){let N=await J?.turnSteering?.drain()??[];if(N.length>0){j.appendAssistant({role:"assistant",content:H.content||"",reasoningContent:H.reasoningContent});let _=await x(Q,$,H.content||"",Y);if(_)Y=_;yield{kind:"steering_applied",...await l0(N),delivery:"current_turn"};continue}if(H.content&&GZ(L,H.content)){j.appendAssistant({role:"assistant",content:H.content||"",reasoningContent:H.reasoningContent}),j.appendControl("user",{role:"user",content:`
|
|
600
600
|
|
|
601
601
|
<system-reminder>
|
|
602
602
|
${YZ()}
|
|
603
|
-
</system-reminder>`});continue}let K=ZQ(H.content,p0,!1);if(K.action==="retry"){p0++,j.appendAssistant({role:"assistant",content:H.content||"",reasoningContent:H.reasoningContent});let _=await
|
|
603
|
+
</system-reminder>`});continue}let K=ZQ(H.content,p0,!1);if(K.action==="retry"){p0++,j.appendAssistant({role:"assistant",content:H.content||"",reasoningContent:H.reasoningContent});let _=await x(Q,$,H.content||"",Y);if(_)Y=_;let d={role:"user",content:K.prompt};j.appendControl("user",d);let k=await l(Q,$,d.content,Y);if(k)Y=k;continue}p0=0;let F=IQ(n,C,d0);if(F.action==="retry"){d0++,j.appendAssistant({role:"assistant",content:H.content||"",reasoningContent:H.reasoningContent});let _=await x(Q,$,H.content||"",Y);if(_)Y=_;let d={role:"user",content:F.prompt};j.appendControl("user",d);let k=await l(Q,$,d.content,Y);if(k)Y=k;continue}if(F.action==="fail"){j.appendAssistant({role:"assistant",content:H.content||"",reasoningContent:H.reasoningContent});let _=await x(Q,$,H.content||"",Y);if(_)Y=_;return{success:!1,error:{type:"delegation_protocol_failed",message:F.message},metadata:{turnsCount:G,toolCallsCount:V.length,duration:Date.now()-W,tokensUsed:o}}}d0=0;let b=UQ(n,C,m0);if(b.action==="retry"){m0++,j.appendAssistant({role:"assistant",content:H.content||"",reasoningContent:H.reasoningContent});let _=await x(Q,$,H.content||"",Y);if(_)Y=_;let d={role:"user",content:b.prompt};j.appendControl("user",d);let k=await l(Q,$,d.content,Y);if(k)Y=k;continue}if(b.action==="fail"){j.appendAssistant({role:"assistant",content:H.content||"",reasoningContent:H.reasoningContent});let _=await x(Q,$,H.content||"",Y);if(_)Y=_;return{success:!1,error:{type:"worktree_protocol_failed",message:b.message},metadata:{turnsCount:G,toolCallsCount:V.length,duration:Date.now()-W,tokensUsed:o}}}m0=0;let c=$Q(u0,c0,g0);if(c.action==="retry"){g0++,j.appendAssistant({role:"assistant",content:H.content||"",reasoningContent:H.reasoningContent});let _=await x(Q,$,H.content||"",Y);if(_)Y=_;let d={role:"user",content:c.prompt};j.appendControl("user",d);let k=await l(Q,$,d.content,Y);if(k)Y=k;continue}if(c.action==="fail"){j.appendAssistant({role:"assistant",content:H.content||"",reasoningContent:H.reasoningContent});let _=await x(Q,$,H.content||"",Y);if(_)Y=_;return{success:!1,error:{type:"verification_failed",message:c.message},metadata:{turnsCount:G,toolCallsCount:V.length,duration:Date.now()-W,tokensUsed:o}}}g0=0;let S=await JQ({sessionId:$.sessionId,permissionMode:$.permissionMode,reason:H.content,abortSignal:J?.signal});if(S.action==="continue"){j.appendAssistant({role:"assistant",content:H.content||"",reasoningContent:H.reasoningContent});let _=await x(Q,$,H.content||"",Y);if(_)Y=_;let k={role:"user",content:S.reason?`
|
|
604
604
|
|
|
605
605
|
<system-reminder>
|
|
606
606
|
${S.reason}
|
|
@@ -608,8 +608,8 @@ ${S.reason}
|
|
|
608
608
|
|
|
609
609
|
<system-reminder>
|
|
610
610
|
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.
|
|
611
|
-
</system-reminder>`};j.appendControl("user",
|
|
611
|
+
</system-reminder>`};j.appendControl("user",k);let K0=await l(Q,$,k.content,Y);if(K0)Y=K0;continue}let s=await J?.turnSteering?.drainOrSeal();if(s&&s.messages.length>0){j.appendAssistant({role:"assistant",content:H.content||"",reasoningContent:H.reasoningContent});let _=await x(Q,$,H.content||"",Y);if(_)Y=_;yield{kind:"steering_applied",...await l0(s.messages),delivery:"current_turn"};continue}j.appendAssistant({role:"assistant",content:H.content||"",reasoningContent:H.reasoningContent});let h=await x(Q,$,H.content||"",Y);if(h)Y=h;return{success:!0,finalMessage:H.content,metadata:{turnsCount:G,toolCallsCount:V.length,duration:Date.now()-W,tokensUsed:o,toolSuccessRate:V.length>0?V.filter((_)=>_.success).length/V.length:void 0,totalToolFailures:A.totalFailures||void 0}}}j.appendAssistant({role:"assistant",content:H.content||"",reasoningContent:H.reasoningContent,tool_calls:H.toolCalls});{let N=await x(Q,$,H.content||"",Y);if(N)Y=N}if(J?.signal?.aborted)return q(G,V.length,J.signal);let o0=H.toolCalls.filter((N)=>N.type==="function"),O0;if(m?.hasTools()){U.debug(`[Loop] 使用 StreamingToolExecutor 收集 ${o0.length} 个工具结果`),O0=[];for await(let N of m.getRemainingResults())O0.push(N)}else{for(let K of o0){let b=D.get(K.function.name)?.kind;yield{kind:"tool_start",toolCall:K,toolKind:b}}let N=async(K)=>{try{let F=KZ(K.function.arguments);if(F===null)return{toolCall:K,result:{success:!1,llmContent:"",error:{type:"validation_error",message:`Invalid JSON object in tool arguments. Raw: ${K.function.arguments.slice(0,200)}`},metadata:void 0},toolUseUuid:null};if(K.function.name==="Task"&&(typeof F.subagent_session_id!=="string"||F.subagent_session_id.length===0))F.subagent_session_id=typeof F.resume==="string"&&F.resume.length>0?F.resume:O2();let b=null;if(b=await WQ(Q,$,K.function.name,F,Y),K.function.name==="ExitWorktree"&&C.has("EnterWorktree")&&!C.has("ExitWorktree")&&$Q(u0,c0,0).action!=="none"){let s="Run the requested verification before ExitWorktree. The worktree remains active so Bash can run in isolation.";return{toolCall:K,result:{success:!1,llmContent:s,error:{type:"validation_error",message:s},metadata:{summary:"Blocked ExitWorktree until verification succeeds"}},toolUseUuid:b}}let S=await Q.toolExecutor.execute(K.function.name,F,{sessionId:$.sessionId,userId:$.userId||"default",workspaceRoot:$.workspaceRoot||i(),worktreeIsolationRequired:F0,worktreeActive:C.has("EnterWorktree")&&!C.has("ExitWorktree"),signal:J?.signal,confirmationHandler:$.confirmationHandler,permissionMode:$.permissionMode,toolRegistry:D,deferredToolManager:D.deferredToolManager});return{toolCall:K,result:S,toolUseUuid:b}}catch(F){return U.error(`Tool execution failed for ${K.function.name}:`,F),{toolCall:K,result:{success:!1,llmContent:"",error:{type:"execution_error",message:F instanceof Error?F.message:"Unknown error"},metadata:void 0},toolUseUuid:null,error:F instanceof Error?F:Error("Unknown error")}}};O0=await Promise.all(o0.map(N))}let qZ=new KQ;for(let{toolCall:N,result:K,toolUseUuid:F}of O0){let b=N;if(V.push(K),K.metadata?.abortedBeforeLaunch)return q(G,V.length,J?.signal);yield{kind:"tool_result",toolCall:b,result:K};{let h=K.metadata&&typeof K.metadata==="object"?K.metadata:void 0,d=((w0)=>w0==="running"||w0==="completed"||w0==="failed"||w0==="cancelled")(h?.subagentStatus)?h.subagentStatus:"completed",k=h&&typeof h.subagentSessionId==="string"?{subagentSessionId:h.subagentSessionId,subagentType:typeof h.subagentType==="string"?h.subagentType:b.function.name,subagentStatus:d,subagentSummary:typeof h.subagentSummary==="string"?h.subagentSummary:void 0}:void 0,K0=await GQ(Q,$,b.id,b.function.name,K.success?I2(K.llmContent):null,F,K.success?void 0:K.error?.message,k);if(K0)Y=K0}let c=await YQ(b,K,Q,$);if(c)yield c;if(K.success){if(QZ(A,b.function.name),b.function.name==="EnterWorktree"&&K.metadata?.workspaceTransition==="enter")C.add("EnterWorktree"),C.delete("ExitWorktree");else if(b.function.name==="ExitWorktree"&&K.metadata?.workspaceTransition==="exit"&&C.has("EnterWorktree"))C.add("ExitWorktree");else if(!["EnterWorktree","ExitWorktree"].includes(b.function.name))C.add(b.function.name);if(b.function.name==="Task"&&K.metadata?.isolation==="worktree")C.add("TaskWorktree");EQ(c0,b.function.name,K)}else ZZ(A,b.function.name);let S=K.success?K.llmContent||"":y2(b.function.name,K.error);if(!K.success){let h=$Z(A,b.function.name);if(h&&typeof S==="string")S=`${S}
|
|
612
612
|
|
|
613
|
-
${
|
|
613
|
+
${h}`}if(typeof S==="object"&&S!==null)S=JSON.stringify(S,null,2);if(typeof S==="string")S=gQ(S,b.function.name,{messageBudget:qZ});let s=typeof S==="string"?S:JSON.stringify(S);if(j.appendToolResult({role:"tool",tool_call_id:b.id,name:b.function.name,content:s}),K.metadata?.shouldExitLoop){let h=typeof K.llmContent==="string"?K.llmContent:"循环已退出";return{success:K.success,finalMessage:h,metadata:{turnsCount:G,toolCallsCount:V.length,duration:Date.now()-W,shouldExitLoop:!0,targetMode:K.metadata?.targetMode,planContent:typeof K.metadata?.planContent==="string"?K.metadata.planContent:void 0}}}}if(J?.signal?.aborted)return q(G,V.length,J.signal);let s0=G>=R0,DZ=G>=H0&&(T0||!u||P);if(s0||DZ){let N=s0?R0:H0;if(U.info(`Warning: 达到轮次上限 ${N} 轮`),J?.onTurnLimitReached){let K=await J.onTurnLimitReached({turnsCount:G});if(K?.continue){j.writeback();try{let F=Q.chatService.getConfig(),b=await Y0.compact($.messages,{trigger:"auto",modelName:F.model,maxContextTokens:F.maxContextTokens??Q.config.maxContextTokens,apiKey:F.apiKey,baseURL:F.baseUrl,actualPreTokens:C0,signal:J?.signal,activeTask:n});$.messages=b.compactedMessages,j.replaceHistory($.messages);let c={role:"user",content:`This session is being continued from a previous conversation. The conversation is summarized above.
|
|
614
614
|
|
|
615
|
-
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.`};j.appendToHistory(
|
|
615
|
+
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.`};j.appendToHistory(c),await E0(Q,$,b.summary,{trigger:"auto",preTokens:b.preTokens,postTokens:b.postTokens,filesIncluded:b.filesIncluded})}catch(F){U.error("[Loop] 压缩失败,使用降级策略:",F);let c=j.getHistory().slice(-80);j.replaceHistory(c)}G=0;continue}return{success:!0,finalMessage:K?.reason||"已达到对话轮次上限,用户选择停止",metadata:{turnsCount:G,toolCallsCount:V.length,duration:Date.now()-W,tokensUsed:o}}}return{success:!1,error:{type:"max_turns_exceeded",message:P?`子代理已达到轮次上限 (${N} 轮)。`:`已达到${s0?"安全":"显式"}轮次上限 (${N} 轮)。`},metadata:{turnsCount:G,toolCallsCount:V.length,duration:Date.now()-W,tokensUsed:o}}}}}finally{j.writeback()}}catch(D){if($0(D))return q(G,V.length,J?.signal);let X=U2(D);return U.error(`API 调用失败: ${X}`),{success:!1,error:{type:"api_error",message:X,details:D},metadata:{turnsCount:G,toolCallsCount:V.length,duration:Date.now()-W}}}finally{if(B)$.messages.push({role:"system",content:zQ}),await SQ(Q,$,Y)}}export{VQ as Ja,iQ as Ka,aQ as La,k0 as Ma,K2 as Na,t as Oa,QQ as Pa,ZQ as Qa,EQ as Ra,JQ as Sa,L0 as Ta,_0 as Ua,bZ as Va,l as Wa,x as Xa,WQ as Ya,GQ as Za,E0 as _a,yQ as $a,AQ as ab,PQ as bb,YQ as cb,j0 as db,Y0 as eb,x0 as fb,BZ as gb,k2 as hb};
|