blade-code 0.8.3 → 0.9.0
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-0abtfzm6.js +1 -0
- package/dist/chunk-0zkhjsbv.js +1 -0
- package/dist/{chunk-6msfa7jh.js → chunk-119fhp5q.js} +1 -1
- package/dist/{chunk-fma9cbq5.js → chunk-1rpgvk3r.js} +1 -1
- package/dist/{chunk-7bqkkjxf.js → chunk-1v2n922p.js} +1 -1
- package/dist/{chunk-eyypmc9m.js → chunk-2fbwmdvg.js} +2 -2
- package/dist/chunk-3qgj2y5r.js +1 -0
- package/dist/{chunk-sva5bdgz.js → chunk-45bme7n9.js} +2 -2
- package/dist/{chunk-zj3q4btp.js → chunk-5jq01mg6.js} +2 -2
- package/dist/{chunk-5sccs44n.js → chunk-5nye3k5w.js} +1 -1
- package/dist/chunk-7pevqbfd.js +2 -0
- package/dist/chunk-8dqvnx7n.js +2 -0
- package/dist/chunk-8edsvxf3.js +1 -0
- package/dist/{chunk-hqtskyc1.js → chunk-8vemqfe4.js} +2 -2
- package/dist/{chunk-d7nrqg5b.js → chunk-8vtznxpq.js} +2 -2
- package/dist/chunk-936ft6kq.js +2 -0
- package/dist/{chunk-jc7k8pfn.js → chunk-9ax02vtg.js} +2 -2
- package/dist/chunk-9qknesxs.js +6 -0
- package/dist/chunk-acegy4td.js +3 -0
- package/dist/chunk-aewrn5xp.js +1 -0
- package/dist/{chunk-mqqajem9.js → chunk-aq7wf2zt.js} +2 -2
- package/dist/{chunk-5yt80bn2.js → chunk-ax7bx0j8.js} +1 -1
- package/dist/chunk-b10vr4xj.js +2 -0
- package/dist/{chunk-vxpdjtqc.js → chunk-bc6wbcrs.js} +1 -1
- package/dist/chunk-bfgm5k3e.js +1566 -0
- package/dist/chunk-cf3fhs7j.js +1 -0
- package/dist/chunk-d7y2mf7c.js +4 -0
- package/dist/chunk-e1586s4t.js +1 -0
- package/dist/chunk-enk621t7.js +98 -0
- package/dist/chunk-fpr6d8zc.js +2 -0
- package/dist/{chunk-nbpjzzrg.js → chunk-gagt42k2.js} +1 -1
- package/dist/chunk-gdm1xzvp.js +2 -0
- package/dist/chunk-gm62cfjw.js +1 -0
- package/dist/chunk-h3bjmkvz.js +1 -0
- package/dist/{chunk-qvtahmff.js → chunk-j8en7x02.js} +1 -1
- package/dist/{chunk-2c69g6t9.js → chunk-jyr9417h.js} +2 -2
- package/dist/chunk-mcnfbhpr.js +6 -0
- package/dist/{chunk-wcf80p9y.js → chunk-mns8e65q.js} +1 -1
- package/dist/chunk-mpkr3s6b.js +3 -0
- package/dist/chunk-n9tgxfvw.js +615 -0
- package/dist/{chunk-be7qz4cv.js → chunk-ppyg431d.js} +1 -1
- package/dist/chunk-qxhrzws6.js +1 -0
- package/dist/{chunk-mvww9cmc.js → chunk-r6h7eja3.js} +1 -1
- package/dist/chunk-r8pjwjt6.js +1 -0
- package/dist/{chunk-97qxd4yb.js → chunk-rmfk5f9m.js} +2 -2
- package/dist/chunk-rrg9bw8r.js +25 -0
- package/dist/chunk-w3me85va.js +2 -0
- package/dist/{chunk-b922cq7k.js → chunk-wtxwny0p.js} +3 -3
- package/dist/{chunk-crbh6x86.js → chunk-x40fkg4z.js} +2 -2
- package/dist/{chunk-1m63zddw.js → chunk-x548f12z.js} +1 -1
- package/dist/{chunk-bqhghfmt.js → chunk-xtfzjb72.js} +1 -1
- package/dist/{chunk-ar5564sf.js → chunk-z0qxaky4.js} +1 -1
- package/dist/web/assets/{FilePreview-B5g8yi8d.js → FilePreview-DpovIbME.js} +1 -1
- package/dist/web/assets/{MarkdownRenderer-qBCxzEb_.js → MarkdownRenderer-73wC_SGk.js} +1 -1
- package/dist/web/assets/{McpModal-C7y2Fsqc.js → McpModal-CIpxuyTG.js} +1 -1
- package/dist/web/assets/{SettingsModal-Dmc7Dw_E.js → SettingsModal-BBa1libe.js} +1 -1
- package/dist/web/assets/{SettingsStore-BfoB9tNV.js → SettingsStore-C8YBWQPS.js} +1 -1
- package/dist/web/assets/{SkillsModal-CqFAIfj5.js → SkillsModal-DArZ-nCX.js} +1 -1
- package/dist/web/assets/{TerminalPanel-EHh8-9b9.js → TerminalPanel-BX7C7qiD.js} +1 -1
- package/dist/web/assets/index-DIWzaS2_.js +16 -0
- package/dist/web/index.html +1 -1
- package/package.json +2 -1
- package/dist/chunk-23h9grdr.js +0 -1
- package/dist/chunk-6spmzx13.js +0 -6
- package/dist/chunk-724djh7r.js +0 -1
- package/dist/chunk-804j7say.js +0 -1
- package/dist/chunk-8yk5w2ks.js +0 -1
- package/dist/chunk-9cr3jexy.js +0 -2
- package/dist/chunk-ghf5tgjr.js +0 -1
- package/dist/chunk-kf43f8sy.js +0 -1577
- package/dist/chunk-kjc2aqww.js +0 -2
- package/dist/chunk-kjddt9xy.js +0 -1
- package/dist/chunk-m0ded6ky.js +0 -615
- package/dist/chunk-msr67f6q.js +0 -3
- package/dist/chunk-ncvr73ev.js +0 -1
- package/dist/chunk-qwn46cd6.js +0 -2
- package/dist/chunk-t9cqscfq.js +0 -2
- package/dist/chunk-tzr992v4.js +0 -1
- package/dist/chunk-x8xfx9nv.js +0 -1
- package/dist/chunk-yewg510f.js +0 -24
- package/dist/chunk-zjks0ncc.js +0 -6
- package/dist/chunk-zsyff0ky.js +0 -3
- package/dist/web/assets/index-B-BRpW1c.js +0 -16
|
@@ -0,0 +1,615 @@
|
|
|
1
|
+
import{wb as P0}from"./chunk-wtxwny0p.js";import{Db as NZ}from"./chunk-1v2n922p.js";import{Fb as IZ}from"./chunk-fpr6d8zc.js";import{Ib as vZ,Jb as G0,Kb as qZ,Lb as rQ}from"./chunk-8vtznxpq.js";import{lc as M0,mc as aQ}from"./chunk-936ft6kq.js";import{rc as m}from"./chunk-w3me85va.js";import{vc as i}from"./chunk-2fbwmdvg.js";import{yc as iQ}from"./chunk-gdm1xzvp.js";function N0(Q){return Q.role==="system"&&Array.isArray(Q.content)}class v0{systemMessages;_history;_pending=[];context;constructor(Q,Z){this.context=Q;let $=Q.messages.find(N0);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)=>!N0(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)=>!N0(Z))}removeMessages(Q){this._history=this._history.filter((Z)=>!Q(Z)),this._pending=this._pending.filter((Z)=>!Q(Z))}writeback(){this.commitPending(),this.context.messages=this._history}get hasSystemPrompt(){return this.systemMessages.length>0}}async function hZ(Q,Z){let $;while(!($=await Q.next()).done)if(Z)await Z($.value);return $.value}function SQ(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 UQ(Q){return{budget:Q.budget,usage:0,consecutiveContinuations:0,lastOutputDelta:0,isSubagent:Q.isSubagent??!1}}function MQ(Q,Z,$){return{...Q,usage:Q.usage+Z,lastOutputDelta:Z,consecutiveContinuations:$?Q.consecutiveContinuations+1:0}}var GQ=i("Agent"),kZ=3;function VQ(Q,Z,$){if(Q!=="length")return{action:"none"};if(Z>=kZ)return{action:"truncated"};if(SQ($)==="stop")return GQ.info("[Loop] Token budget: diminishing returns detected, skipping recovery"),{action:"budget_stop"};return{action:"recover"}}var TZ=[/:\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],xZ=/```[\s\S]{50,}```/,fQ="请执行你提到的操作,不要只是描述。使用 Edit/Write/Bash 工具来实际修改文件。",RZ=2;function YQ(Q,Z,$=!0){if(!Q||Z>=RZ)return{action:"none"};if(!$&&xZ.test(Q))return{action:"retry",prompt:fQ};let J=Q.slice(-200),z=J.match(/```/g);if(z&&z.length%2!==0)return{action:"none"};if(TZ.some((W)=>W.test(J)))return{action:"retry",prompt:fQ};return{action:"none"}}var CZ=[/\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}(?:测试|单测|集成测试|检查|构建)/],pZ=/(?:^|\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,hQ={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},dZ={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},gZ="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.",mZ="Required verification did not run successfully before the retry limit.",cZ=3;function WQ(Q){return pZ.test(Q)}function TQ(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&&WQ($.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"&&WQ(z))Q.add(z)}function HQ(Q,Z,$){if(!Q||!CZ.some((Y)=>Y.test(Q)))return{action:"none"};let J=Object.keys(hQ).filter((Y)=>hQ[Y].test(Q)),z=[...Z],G=J.filter((Y)=>!z.some((X)=>dZ[Y].test(X)));if(J.length>0?G.length===0:z.some(WQ))return{action:"none"};if($>=cZ)return{action:"fail",message:mZ};let V=J.length>1&&G.length>0?` Missing successful verification categories: ${G.join(", ")}.`:"";return{action:"retry",prompt:`${gZ}${V}`}}var uZ=[/\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|子代理|子智能体)/],iZ=[/\b(?:do not|don't|never)\s+(?:delegate|call|use|invoke)\b/i,/(?:不要|禁止|无需)(?:委派|调用|使用).{0,20}(?:Task|子代理|子智能体)?/],nZ=[/\b(?:call|use|invoke)\b[\s\S]{0,30}\bTask(?: tool)?\b[\s\S]{0,30}\bexactly once\b/i,/\bexactly once\b[\s\S]{0,30}\b(?:call|use|invoke)\b[\s\S]{0,30}\bTask(?: tool)?\b/i,/\bexactly one\b[\s\S]{0,30}\bTask(?: tool)? calls?\b/i,/(?:Task|子代理).{0,20}(?:恰好|仅|只)(?:调用|使用)?一次/,/(?:恰好|仅|只)(?:调用|使用)?一次.{0,20}(?:Task|子代理)/],lZ=[/\b(?:do not|don't|never)\s+(?:call|use|invoke)\s+(?:the\s+)?Task\b[\s\S]{0,30}\bexactly once\b/i,/\bTask\b[\s\S]{0,30}\b(?:does not|doesn't|need not)\b[\s\S]{0,30}\bexactly once\b/i,/\bmultiple\s+Task(?: tool)?\s+calls?\s+(?:are\s+)?allowed\b/i,/(?:不要|禁止).{0,12}(?:Task|子代理).{0,12}(?:恰好|仅|只)(?:调用|使用)?一次/];function rZ(Q){if(typeof Q!=="string")return;if(lZ.some((Z)=>Z.test(Q)))return"multiple-allowed";return nZ.some((Z)=>Z.test(Q))?"required":void 0}function A0(Q){for(let Z of Q){let $=rZ(Z);if($!==void 0)return $==="required"}return!1}var 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.",oZ="Required delegation did not complete before the retry limit.",sZ=3;function xQ(Q,Z,$){let J=(typeof Q==="string"?[Q]:Q??[]).map((W)=>W.trim()).filter(Boolean),z=A0(J),G=!1;if(!z)for(let W of J){if(iZ.some((V)=>V.test(W)))break;if(uZ.some((V)=>V.test(W))){G=!0;break}}if(J.length===0||!z&&!G||Z.has("Task"))return{action:"none"};if($>=sZ)return{action:"fail",message:oZ};return{action:"retry",prompt:aZ}}var tZ=[/\b(?:use|create|enter|start|work\s+(?:in|inside))\b.{0,60}\bworktree\b/i,/(?:使用|创建|进入).{0,30}(?:worktree|工作树)/i],eZ=[/\b(?:exit|leave)\b.{0,40}\bworktree\b/i,/\bworktree\b.{0,60}\b(?:action\s+)?(?:keep|remove)\b/i,/(?:退出|离开).{0,30}(?:worktree|工作树)/i],Q2=[/\b(?:do not|don't|never|must not|should not)\b[^.!?;\n]{0,80}\b(?:git\s+)?worktree\b/gi,/\bwithout\b[^.!?;\n]{0,60}\b(?:git\s+)?worktree\b/gi,/(?:不要|禁止|不得|无需)[^。!?;\n]{0,50}(?:worktree|工作树)/gi];function RQ(Q){return Q2.reduce((Z,$)=>Z.replace($," "),Q)}function y0(Q){if(typeof Q!=="string")return!1;let Z=RQ(Q);return tZ.some(($)=>$.test(Z))}var Z2="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.",$2="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.",J2="Required worktree lifecycle did not complete before the retry limit.",z2=3;function CQ(Q,Z,$){if(!Q)return{action:"none"};let J=RQ(Q);if(!y0(J))return{action:"none"};let z=eZ.some((W)=>W.test(J));if(Z.has("TaskWorktree"))return{action:"none"};let G=!Z.has("EnterWorktree")?"EnterWorktree":z&&!Z.has("ExitWorktree")?"ExitWorktree":void 0;if(!G)return{action:"none"};if($>=z2)return{action:"fail",message:J2};return{action:"retry",tool:G,prompt:G==="EnterWorktree"?Z2:$2}}var kQ=30000;async function XQ(Q){try{let $=P0.getInstance().executeStopHooks({projectDir:m(),sessionId:Q.sessionId,permissionMode:Q.permissionMode,reason:Q.reason,abortSignal:Q.abortSignal}),J,z=new Promise((G)=>{J=setTimeout(()=>G("timeout"),kQ)});try{let G=await Promise.race([$,z]);if(G==="timeout")return GQ.warn(`[Loop] Stop hook 超时 (${kQ}ms),按 shouldStop: true 处理`),{action:"stop"};let W=G;if(!W.shouldStop)return{action:"continue",reason:W.continueReason};return{action:"stop"}}finally{clearTimeout(J)}}catch(Z){return GQ.warn("[Loop] Stop hook execution failed:",Z),{action:"stop"}}}var W0=i("Agent"),BQ=`<turn_aborted>
|
|
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 V0(Q){return Q.executionEngine?.getContextManager()}async function a(Q,Z,$,J=null,z){try{let G=V0(Q),W=typeof $==="string"?$.trim()!=="":$.some((V)=>V.type==="text"?V.text.trim()!=="":!0);if(G&&Z.sessionId&&W)return await G.saveMessage(Z.sessionId,"user",$,J,z,Z.subagentInfo)}catch(G){W0.warn("[Loop] 保存用户消息失败:",G)}return null}async function d(Q,Z,$,J){try{let z=V0(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 pQ(Q,Z,$){try{let J=V0(Q);if(J&&Z.sessionId)return await J.saveMessage(Z.sessionId,"system",BQ,$,void 0,Z.subagentInfo)}catch(J){W0.warn("[Loop] 保存中断边界失败:",J)}return null}async function KQ(Q,Z,$,J,z){try{let G=V0(Q);if(G&&Z.sessionId)return await G.saveToolUse(Z.sessionId,$,J,z,Z.subagentInfo)}catch(G){W0.warn("[Loop] 保存工具调用失败:",G)}return null}async function S0(Q,Z,$,J,z,G,W,V){try{let Y=V0(Q);if(Y&&Z.sessionId)return await Y.saveToolResult(Z.sessionId,$,J,z,G,W,Z.subagentInfo,V)}catch(Y){W0.warn("[Loop] 保存工具结果失败:",Y)}return null}async function U0(Q,Z,$,J){try{let z=V0(Q);if(z&&Z.sessionId)return await z.saveCompaction(Z.sessionId,$,J,null)}catch(z){W0.warn("[Loop] 保存压缩数据失败:",z)}return null}function dQ(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 gQ(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 mQ(Q){let Z=Q.metadata;if(!Z)return;return Z.modelId?.toString().trim()||Z.model?.toString().trim()||void 0||void 0}function G2(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 W2(Q,Z){if(Q.function.name!=="Task")return null;let $=Z.metadata;if(!$?.subagentSessionId)return null;let J=$.subagentSessionId,z=$.subagentType||"Task",G=$.subagentStatus,W=typeof $.subagentResumedFrom==="string"?$.subagentResumedFrom:void 0,V=typeof $.subagentRootId==="string"?$.subagentRootId:void 0,Y=typeof $.subagentResumeDepth==="number"?$.subagentResumeDepth:void 0;if(G==="completed"||G==="failed"||G==="cancelled")return{kind:"subagent_completed",sessionId:J,success:G==="completed",summary:$.subagentSummary,resumedFrom:W,rootAgentId:V,resumeDepth:Y};if(G==="running"){let X="";try{X=JSON.parse(Q.function.arguments).prompt||""}catch{}return{kind:"subagent_spawned",sessionId:J,type:z,prompt:X,resumedFrom:W,rootAgentId:V,resumeDepth:Y}}return null}async function jQ(Q,Z,$,J){let z=dQ(Q,Z),G=W2(Q,Z);gQ(Q,Z,$);let W=mQ(Z);if(W)await $.onModelSwitch?.(W);if(J)G2(Q,Z,J);return G||z}import{promises as b2}from"node:fs";import L2 from"node:path";import{nanoid as Q0}from"nanoid";import*as h from"node:fs/promises";import*as z0 from"node:path";var cQ={enabled:!0,maxIndexLines:200};var V2="memory",uQ="MEMORY.md";class DQ{memoryDir;config;initialized=!1;constructor(Q,Z,$){if($)this.memoryDir=$;else{let J=iQ(Q);this.memoryDir=z0.join(J,V2)}this.config={...cQ,...Z}}async initialize(){if(this.initialized)return;await h.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,uQ);try{let Z=await h.readFile(Q,"utf-8");if(!Z.trim())return null;let $=Z.split(`
|
|
4
|
+
`),z=$.slice(0,this.config.maxIndexLines).join(`
|
|
5
|
+
`).trim();if($.length>this.config.maxIndexLines)return z+`
|
|
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 h.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 h.readFile(J,"utf-8")}catch{}let G=z&&!z.endsWith(`
|
|
8
|
+
`)?`
|
|
9
|
+
`:"";await h.writeFile(J,z+G+Z,"utf-8")}else await h.writeFile(J,Z,"utf-8")}async updateIndex(Q,Z="overwrite"){await this.initialize();let $=z0.join(this.memoryDir,uQ);if(Z==="append"){let J="";try{J=await h.readFile($,"utf-8")}catch{}let z=J&&!J.endsWith(`
|
|
10
|
+
`)?`
|
|
11
|
+
`:"";await h.writeFile($,J+z+Q,"utf-8")}else await h.writeFile($,Q,"utf-8")}async listTopics(){await this.initialize();try{let Q=await h.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 h.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 h.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 h.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 Y2=[{pattern:/(?:记住|remember|note|备注)[::](.+)/i,topic:"preferences"},{pattern:/(?:convention|约定|规范)[::](.+)/i,topic:"conventions"},{pattern:/(?:lesson|教训|踩坑)[::](.+)/i,topic:"lessons"}],H2=/(?:fix|修复|解决|resolved)[::]\s*(.+?)(?:\n|$)/i,X2=/(?:Error|FAIL|错误)[::]\s*(.+?)(?:\n|$)/i;function B2(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:G}of Y2){let W=J.match(z);if(W?.[1]){let V=Z.get(G)??[];V.push(W[1].trim()),Z.set(G,V)}}if($.role==="assistant"){let z=J.match(H2);if(z?.[1]&&z[1].length>20&&z[1].length<200){let G=Z.get("debugging")??[];G.push(z[1].trim()),Z.set("debugging",G)}}if($.role==="tool"&&$.content?.includes("Error")){let z=J.match(X2);if(z?.[1]&&z[1].length>10){let G=Z.get("debugging")??[];if(G.length<5)G.push(`Tool error pattern: ${z[1].trim().slice(0,150)}`),Z.set("debugging",G)}}}return Z}async function nQ(Q){let Z=B2(Q);if(Z.size===0)return{extracted:0,topics:[]};try{let $=new DQ(m());await $.initialize();let J=[],z=0;for(let[G,W]of Z){if(W.length===0)continue;let V=new Date().toISOString().split("T")[0],Y=W.map((X)=>`- [${V}] ${X}`).join(`
|
|
12
|
+
`);await $.writeTopic(G,Y+`
|
|
13
|
+
`,"append"),J.push(G),z+=W.length}return{extracted:z,topics:J}}catch{return{extracted:0,topics:[]}}}import{readFile as K2}from"node:fs/promises";import{basename as j2,isAbsolute as D2,resolve as F2}from"node:path";class f0{static MAX_FILES=5;static MAX_LINES_PER_FILE=1000;static analyzeFiles(Q){let Z=new Map;return Q.forEach((J,z)=>{let G=typeof J.content==="string"?J.content:(J.content||[]).filter((V)=>V.type==="text").map((V)=>V.text).join(`
|
|
14
|
+
`);if(this.extractFilePathsFromContent(G).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),X=V.type==="function"&&"function"in V?V.function?.name:"",D=["Write","Edit"].includes(X||"");Y.forEach((O)=>{this.updateFileReference(Z,O,z,D)})})}),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,Z){let $=[];for(let J of Q)try{let z=Z&&!D2(J)?F2(Z,J):J;if(Z&&!await M0.isWithinWorkspaceResolved(z,Z))continue;let G=await K2(z,"utf-8"),W=G.split(`
|
|
15
|
+
`),V=W.length,Y=G,X=!1,D=V;if(V>this.MAX_LINES_PER_FILE)Y=W.slice(0,this.MAX_LINES_PER_FILE).join(`
|
|
16
|
+
`),Y+=`
|
|
17
|
+
|
|
18
|
+
... (truncated ${V-this.MAX_LINES_PER_FILE} lines)`,X=!0,D=this.MAX_LINES_PER_FILE;$.push({path:J,content:Y,truncated:X,lines:V,includedLines:D})}catch(z){console.warn(`[FileAnalyzer] 无法读取文件: ${J}`,z)}return $}static extractFilePathsFromContent(Q){let Z=new Set,$=/```(?:\w+)?\s*\n?([\s\S]*?)```/g,J=Array.from(Q.matchAll($));for(let G of J){let W=G[1];this.extractPathsFromText(W).forEach((Y)=>Z.add(Y))}return this.extractPathsFromText(Q).forEach((G)=>Z.add(G)),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 G of z){let W=G[0];if(W=W.replace(/[,。;:!?""''()【】《》]$/g,""),W=W.replace(/[,.;:!?"'()[\]<>]$/g,""),this.isValidFilePath(W))Z.push(W)}}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 G=["file_path","path","notebook_path","filePath"];for(let W of G)if(J[W]&&typeof J[W]==="string")Z.push(J[W])}}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=j2(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 lQ}from"js-tiktoken";class b0{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),G=Math.floor($*J);return z>=G}static getEncoding(Q){if(!this.encodingCache.has(Q))try{let Z=lQ(Q);this.encodingCache.set(Q,Z)}catch{try{let Z=lQ("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 T=i("Context"),h0=new Map,O2=3;function _2(Q,Z){return JSON.stringify([L2.resolve(Q??m()),Z??null])}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??b0.countTokens(Q,Z.modelName),J=Z.actualPreTokens?"actual (from LLM usage)":"estimated";T.debug(`[CompactionService] preTokens source: ${J}`);try{let V=await P0.getInstance().executeCompactionHooks(Z.trigger,{projectDir:Z.workspaceRoot??m(),sessionId:Z.sessionId||"unknown",permissionMode:Z.permissionMode||"default",messagesBefore:Q.length,tokensBefore:$});if(V.blockCompaction)return T.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)T.warn(`[CompactionService] Compaction hook warning: ${V.warning}`)}catch(W){T.warn("[CompactionService] Compaction hook execution failed:",W)}let z=_2(Z.workspaceRoot,Z.sessionId),G=h0.get(z)??0;if(G>=O2)return T.warn(`[CompactionService] Circuit breaker open (${G} consecutive failures for session ${Z.sessionId??"unknown"}), using fallback`),this.fallbackCompact(Q,Z,$,Error("Circuit breaker open"));try{T.debug("[CompactionService] 开始压缩,消息数:",Q.length),T.debug("[CompactionService] 压缩前 tokens:",$);let V=f0.analyzeFiles(Q).map((R)=>R.path);T.debug("[CompactionService] 提取重点文件:",V);let Y=await f0.readFilesContent(V,Z.workspaceRoot);T.debug("[CompactionService] 成功读取文件:",Y.length);let X=await this.generateSummary(Q,Y,Z),{summary:D}=X;T.debug("[CompactionService] 生成总结,长度:",D.length);let O=Math.ceil(Q.length*this.RETAIN_PERCENT),F=Q.slice(-O),b=new Set;for(let R of F)if(R.role==="assistant"&&R.tool_calls)for(let r of R.tool_calls)b.add(r.id);let k=F.filter((R)=>{if(R.role==="tool"&&R.tool_call_id)return b.has(R.tool_call_id);return!0});T.debug("[CompactionService] 保留消息数:",O),T.debug("[CompactionService] 过滤后保留消息数:",k.length);let x=Q0(),N=this.createBoundaryMessage(x,Z.trigger,$),I=Q0(),L=this.createSummaryMessage(I,D),u=[L,...k],l=await this.buildFileRestorationMessage(Z.workspaceRoot,Z.sessionId);if(l)u.push(l);let y=this.buildActiveTaskMessage(Z.activeTask);if(y)u.push(y);let s=b0.countTokens(u,Z.modelName);T.debug("[CompactionService] 压缩完成!"),T.debug("[CompactionService] Token 变化:",$,"->",s,`(-${((1-s/$)*100).toFixed(1)}%)`),h0.delete(z);let u0=Q.slice(0,Q.length-O);return nQ(u0).catch((R)=>{return}),{success:!0,summary:D,preTokens:$,postTokens:s,filesIncluded:Y.map((R)=>R.path),compactedMessages:u,boundaryMessage:N,summaryMessage:L,usage:X.usage}}catch(W){if(G0(W))throw W;return h0.set(z,(h0.get(z)??0)+1),T.error("[CompactionService] 压缩失败,使用降级策略",W),this.fallbackCompact(Q,Z,$,W)}}static async generateSummary(Q,Z,$){let J=this.buildCompactionPrompt(Q,Z);if(T.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,model:$.modelName,temperature:0.3,maxOutputTokens:8000,timeout:60000,provider:$.modelProvider??"openai"})).chat([{role:"user",content:J}],[],$.signal),W=G.content||"",V=W.match(/<summary>([\s\S]*?)<\/summary>/);if(!V)return T.warn("[CompactionService] 总结格式不正确,使用完整响应"),{summary:W,usage:G.usage};return{summary:V[1].trim(),usage:G.usage}}static buildCompactionPrompt(Q,Z){let $=Q.map((G,W)=>{let V=G.role||"unknown",Y=typeof G.content==="string"?G.content:JSON.stringify(G.content),X=5000,D=Y.length>5000?Y.substring(0,5000)+"...":Y;return`[${W+1}] ${V}: ${D}`}).join(`
|
|
19
|
+
|
|
20
|
+
`),J=Z.map((G)=>{return`### ${G.path}
|
|
21
|
+
\`\`\`
|
|
22
|
+
${G.content}
|
|
23
|
+
\`\`\``}).join(`
|
|
24
|
+
|
|
25
|
+
`),z=`Your task is to create a detailed summary of the conversation so far, paying close attention to the user's explicit requests and your previous actions.
|
|
26
|
+
This summary should be thorough in capturing technical details, code patterns, and architectural decisions that would be essential for continuing development work without losing context.
|
|
27
|
+
|
|
28
|
+
Before providing your final summary, wrap your analysis in <analysis> tags to organize your thoughts and ensure you've covered all necessary points. In your analysis process:
|
|
29
|
+
|
|
30
|
+
1. Chronologically analyze each message and section of the conversation. For each section thoroughly identify:
|
|
31
|
+
- The user's explicit requests and intents
|
|
32
|
+
- Your approach to addressing the user's requests
|
|
33
|
+
- Key decisions, technical concepts and code patterns
|
|
34
|
+
- Specific details like:
|
|
35
|
+
- file names
|
|
36
|
+
- full code snippets
|
|
37
|
+
- function signatures
|
|
38
|
+
- file edits
|
|
39
|
+
- Errors that you ran into and how you fixed them
|
|
40
|
+
- Pay special attention to specific user feedback that you received, especially if the user told you to do something differently.
|
|
41
|
+
2. Double-check for technical accuracy and completeness, addressing each required element thoroughly.
|
|
42
|
+
|
|
43
|
+
Your summary should include the following sections:
|
|
44
|
+
|
|
45
|
+
1. Primary Request and Intent: Capture all of the user's explicit requests and intents in detail
|
|
46
|
+
2. Key Technical Concepts: List all important technical concepts, technologies, and frameworks discussed.
|
|
47
|
+
3. Files and Code Sections: Enumerate specific files and code sections examined, modified, or created. Pay special attention to the most recent messages and include full code snippets where applicable and include a summary of why this file read or edit is important.
|
|
48
|
+
4. Errors and fixes: List all errors that you ran into, and how you fixed them. Pay special attention to specific user feedback that you received, especially if the user told you to do something differently.
|
|
49
|
+
5. Problem Solving: Document problems solved and any ongoing troubleshooting efforts.
|
|
50
|
+
6. All user messages: List ALL user messages that are not tool results. These are critical for understanding the users' feedback and changing intent.
|
|
51
|
+
7. Pending Tasks: Outline any pending tasks that you have explicitly been asked to work on.
|
|
52
|
+
8. Current Work: Describe in detail precisely what was being worked on immediately before this summary request, paying special attention to the most recent messages from both user and assistant. Include file names and code snippets where applicable.
|
|
53
|
+
9. Optional Next Step: List the next step that you will take that is related to the most recent work you were doing. IMPORTANT: ensure that this step is DIRECTLY in line with the user's most recent explicit requests, and the task you were working on immediately before this summary request.`;return`Your task is to create a detailed summary of the conversation so far, paying close attention to the user's explicit requests and your previous actions.
|
|
54
|
+
This summary should be thorough in capturing technical details, code patterns, and architectural decisions that would be essential for continuing development work without losing context.
|
|
55
|
+
|
|
56
|
+
Before providing your final summary, wrap your analysis in <analysis> tags to organize your thoughts and ensure you've covered all necessary points. In your analysis process:
|
|
57
|
+
|
|
58
|
+
1. Chronologically analyze each message and section of the conversation. For each section thoroughly identify:
|
|
59
|
+
- The user's explicit requests and intents
|
|
60
|
+
- Your approach to addressing the user's requests
|
|
61
|
+
- Key decisions, technical concepts and code patterns
|
|
62
|
+
- Specific details like:
|
|
63
|
+
- file names
|
|
64
|
+
- full code snippets
|
|
65
|
+
- function signatures
|
|
66
|
+
- file edits
|
|
67
|
+
- Errors that you ran into and how you fixed them
|
|
68
|
+
- Pay special attention to specific user feedback that you received, especially if the user told you to do something differently.
|
|
69
|
+
2. Double-check for technical accuracy and completeness, addressing each required element thoroughly.
|
|
70
|
+
|
|
71
|
+
Your summary should include the following sections:
|
|
72
|
+
|
|
73
|
+
1. Primary Request and Intent: Capture all of the user's explicit requests and intents in detail
|
|
74
|
+
2. Key Technical Concepts: List all important technical concepts, technologies, and frameworks discussed.
|
|
75
|
+
3. Files and Code Sections: Enumerate specific files and code sections examined, modified, or created. Pay special attention to the most recent messages and include full code snippets where applicable and include a summary of why this file read or edit is important.
|
|
76
|
+
4. Errors and fixes: List all errors that you ran into, and how you fixed them. Pay special attention to specific user feedback that you received, especially if the user told you to do something differently.
|
|
77
|
+
5. Problem Solving: Document problems solved and any ongoing troubleshooting efforts.
|
|
78
|
+
6. All user messages: List ALL user messages that are not tool results. These are critical for understanding the users' feedback and changing intent.
|
|
79
|
+
7. Pending Tasks: Outline any pending tasks that you have explicitly been asked to work on.
|
|
80
|
+
8. Current Work: Describe in detail precisely what was being worked on immediately before this summary request, paying special attention to the most recent messages from both user and assistant. Include file names and code snippets where applicable.
|
|
81
|
+
9. Optional Next Step: List the next step that you will take that is related to the most recent work you were doing. IMPORTANT: ensure that this step is DIRECTLY in line with the user's most recent explicit requests, and the task you were working on immediately before this summary request.
|
|
82
|
+
|
|
83
|
+
## Conversation History
|
|
84
|
+
|
|
85
|
+
${$}
|
|
86
|
+
|
|
87
|
+
${Z.length>0?`## Important Files
|
|
88
|
+
|
|
89
|
+
${J}`:""}
|
|
90
|
+
|
|
91
|
+
Please provide your summary following the structure specified above, with both <analysis> and <summary> sections.`}static createBoundaryMessage(Q,Z,$){return{id:Q0(),role:"system",content:"Conversation compacted",metadata:{type:"system",subtype:"compact_boundary",parentId:Q,compactMetadata:{trigger:Z,preTokens:$}}}}static createSummaryMessage(Q,Z){return{id:Q0(),role:"user",content:Z,metadata:{parentId:Q,isCompactSummary:!0}}}static async getRecentlyAccessedFiles(Q,Z,$){let z=aQ.getInstance().getTrackedRecords().filter((W)=>!$||W.sessionId===$).sort((W,V)=>V.accessTime-W.accessTime),G=[];for(let W of z){if(Z&&!await M0.isWithinWorkspaceResolved(W.filePath,Z))continue;if(!G.includes(W.filePath))G.push(W.filePath);if(G.length>=Q)break}return G}static async buildFileRestorationMessage(Q,Z){let $=await this.getRecentlyAccessedFiles(5,Q,Z);if($.length===0)return null;let J=[];for(let G of $)try{let V=(await b2.readFile(G,"utf-8")).split(`
|
|
92
|
+
`),Y=V.slice(0,200).join(`
|
|
93
|
+
`),X=V.length>200?`
|
|
94
|
+
... (${V.length-200} more lines)`:"";J.push(`<file path="${G}" lines="${V.length}">
|
|
95
|
+
${Y}${X}
|
|
96
|
+
</file>`)}catch{}if(J.length===0)return null;let z=["<system-reminder>","Post-compaction file restoration. These files were recently accessed in the conversation:",...J,"</system-reminder>"].join(`
|
|
97
|
+
`);return T.debug("[CompactionService] Post-compact 恢复文件:",$.length),{id:Q0(),role:"user",content:z,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
|
+
...[active task checkpoint truncated]...
|
|
99
|
+
`,Q.slice(-(Z-$))].join("");return{id:Q0(),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),G=Q.slice(-z),W=new Set;for(let N of G)if(N.role==="assistant"&&N.tool_calls)for(let I of N.tool_calls)W.add(I.id);let V=G.filter((N)=>{if(N.role==="tool"&&N.tool_call_id)return W.has(N.tool_call_id);return!0}),Y=Q0(),X=this.createBoundaryMessage(Y,Z.trigger,$),D=J instanceof Error?J.message:String(J),O=Q0(),F=this.createSummaryMessage(O,`[Automatic compaction failed; using fallback]
|
|
101
|
+
|
|
102
|
+
An error occurred during compaction. Retained the latest ${z} messages (~30%).
|
|
103
|
+
|
|
104
|
+
Error: ${D}
|
|
105
|
+
|
|
106
|
+
The conversation can continue, but consider retrying compaction later with /compact.`),b=[F,...V],k=this.buildActiveTaskMessage(Z.activeTask);if(k)b.push(k);let x=b0.countTokens(b,Z.modelName);return{success:!1,summary:typeof F.content==="string"?F.content:F.content.filter((N)=>N.type==="text").map((N)=>N.text).join(`
|
|
107
|
+
`),preTokens:$,postTokens:x,filesIncluded:[],compactedMessages:b,boundaryMessage:X,summaryMessage:F,error:D}}}var w2=new Set(["Read","Grep","Glob","Search","WebSearch","WebFetch","ToolSearch"]);function q2(Q,Z){let z=(Q[Z.assistantIdx].tool_calls??[]).filter((W)=>W.type==="function").map((W)=>W.function.name).some((W)=>!w2.has(W));if(Z.toolResultIdxs.some((W)=>{let V=Q[W]?.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 L0(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 F=0;F<Q.length;F++){let b=Q[F];if(b.role==="assistant"&&b.tool_calls&&b.tool_calls.length>0){let k=new Set(b.tool_calls.map((N)=>N.id)),x=[];for(let N=F+1;N<Q.length;N++){let I=Q[N];if(I.role==="tool"&&I.tool_call_id&&k.has(I.tool_call_id))x.push(N);if(I.role==="assistant"||I.role==="user")break}z.push({assistantIdx:F,toolResultIdxs:x,priority:0})}}for(let F of z)F.priority=q2(Q,F);let V=[...z.slice(0,Math.max(0,z.length-$))].sort((F,b)=>F.priority-b.priority);if(V.length===0)return{messages:Q,snippedCount:0,estimatedTokensFreed:0};let Y=new Set,X=0;for(let F of V){Y.add(F.assistantIdx);for(let b of F.toolResultIdxs)Y.add(b)}for(let F of Y){let b=Q[F],k=typeof b.content==="string"?b.content:JSON.stringify(b.content);if(X+=k.length,b.tool_calls)X+=JSON.stringify(b.tool_calls).length}let D=[],O=!1;for(let F=0;F<Q.length;F++){if(Y.has(F)){if(!O)D.push({role:"system",content:`[${V.length} earlier tool interaction${V.length===1?"":"s"} snipped for brevity]`}),O=!0;continue}D.push(Q[F])}return{messages:D,snippedCount:V.length,estimatedTokensFreed:Math.floor(X/4)}}var E2=60000,I2=3;function oQ(Q,Z){if(!Z)return null;if(Date.now()-Z<E2)return null;let J=L0(Q,{keepRecentTurns:I2,minMessagesForSnip:15});if(J.snippedCount===0)return null;return J}class FQ{hasAttempted=!1;async tryReactiveCompact(Q,Z){if(this.hasAttempted)return{success:!1,messages:Q};this.hasAttempted=!0;let $=L0(Q,{keepRecentTurns:3,minMessagesForSnip:10}),J=$.messages;try{let z=await Y0.compact(J,{trigger:"auto",modelName:Z.modelName,modelProvider:Z.modelProvider,maxContextTokens:Z.maxContextTokens,apiKey:Z.apiKey,baseURL:Z.baseURL,signal:Z.signal,activeTask:Z.activeTask,workspaceRoot:Z.workspaceRoot,sessionId:Z.sessionId});if(z.success)return{success:!0,messages:z.compactedMessages,usage:z.usage};if($.snippedCount>0)return{success:!0,messages:J};return{success:!1,messages:Q}}catch(z){if(G0(z))throw z;if($.snippedCount>0)return{success:!0,messages:J};return{success:!1,messages:Q}}}reset(){this.hasAttempted=!1}}import*as H0 from"fs";import*as bQ from"os";import*as O0 from"path";import{nanoid as eQ}from"nanoid";var N2=1e5,v2=2000,sQ=200000;class LQ{currentChars=0;track(Q){this.currentChars+=Q}remaining(){return Math.max(0,sQ-this.currentChars)}isExhausted(){return this.currentChars>=sQ}reset(){this.currentChars=0}}function QZ(Q,Z,$){let J=$?.maxCharsPerResult??N2,z=$?.previewChars??v2,G=$?.messageBudget,W=typeof Q==="string"?Q:JSON.stringify(Q,null,2);if(W.length<=J)return P2(Q,W,Z,z,G,$);let V=$?.outputDir??O0.join(bQ.homedir(),".blade","tool-results"),Y=`${Z}-${eQ(8)}.txt`,X=O0.join(V,Y);try{H0.mkdirSync(V,{recursive:!0}),H0.writeFileSync(X,W,"utf-8")}catch{let F=W.slice(0,J)+`
|
|
108
|
+
|
|
109
|
+
... (truncated, ${W.length} total chars)`;if(G)G.track(F.length);return F}let D=W.slice(0,z),O=`Result too large (${W.length} chars). Full output saved to: ${X}
|
|
110
|
+
|
|
111
|
+
Preview:
|
|
112
|
+
${D}
|
|
113
|
+
|
|
114
|
+
... (${W.length-z} more chars in file)`;if(G)G.track(O.length);return O}function P2(Q,Z,$,J,z,G){if(!z)return Q;let W=z.remaining();if(W<=0){let V=Z.slice(0,J),Y=tQ(Z,V,$,G,"[Message budget exhausted. Full output saved to disk.]");return z.track(typeof Y==="string"?Y.length:J),Y}if(Z.length>W){let V=Math.max(J,W),Y=Z.slice(0,V),X=tQ(Z,Y,$,G,`... (truncated by message budget, ${Z.length} total chars)`);return z.track(typeof X==="string"?X.length:V),X}return z.track(Z.length),Q}function tQ(Q,Z,$,J,z){let G=J?.outputDir??O0.join(bQ.homedir(),".blade","tool-results"),W=`${$}-${eQ(8)}.txt`,V=O0.join(G,W);try{return H0.mkdirSync(G,{recursive:!0}),H0.writeFileSync(V,Q,"utf-8"),`${Z}
|
|
115
|
+
|
|
116
|
+
${z}
|
|
117
|
+
Full output saved to: ${V}`}catch{return`${Z}
|
|
118
|
+
|
|
119
|
+
${z}`}}import*as p0 from"node:fs/promises";import{homedir as BZ}from"node:os";import*as o from"node:path";var k0={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 ZZ(){return{metadata:k0,instructions:`# Skill Creator
|
|
120
|
+
|
|
121
|
+
帮助用户创建新的 Blade Skills。
|
|
122
|
+
|
|
123
|
+
## Instructions
|
|
124
|
+
|
|
125
|
+
当用户想要创建新 Skill 时,按以下步骤进行:
|
|
126
|
+
|
|
127
|
+
### 1. 了解需求
|
|
128
|
+
|
|
129
|
+
询问用户:
|
|
130
|
+
- Skill 的目的是什么?解决什么问题?
|
|
131
|
+
- 什么场景下应该使用这个 Skill?
|
|
132
|
+
- 需要访问哪些工具?(Read, Write, Bash, Grep, Glob, Task, WebFetch 等)
|
|
133
|
+
- 是否需要支持用户通过 \`/skill-name\` 命令调用?
|
|
134
|
+
|
|
135
|
+
### 2. 设计 Skill
|
|
136
|
+
|
|
137
|
+
根据用户需求,设计以下内容:
|
|
138
|
+
|
|
139
|
+
**必填字段:**
|
|
140
|
+
- \`name\`: kebab-case 格式,≤64 字符(如 \`code-review\`, \`commit-helper\`)
|
|
141
|
+
- \`description\`: 简洁描述,≤1024 字符,包含"什么"和"何时使用"
|
|
142
|
+
|
|
143
|
+
**可选字段:**
|
|
144
|
+
- \`allowed-tools\`: 限制可用工具列表(提高安全性)
|
|
145
|
+
- \`argument-hint\`: 参数提示(如 \`<file_path>\`)
|
|
146
|
+
- \`user-invocable\`: 是否支持 \`/skill-name\` 调用(默认 false)
|
|
147
|
+
- \`disable-model-invocation\`: 是否禁止 AI 自动调用(默认 false)
|
|
148
|
+
- \`version\`: 版本号
|
|
149
|
+
|
|
150
|
+
**系统提示词设计要点:**
|
|
151
|
+
- 清晰的任务描述
|
|
152
|
+
- 具体的执行步骤
|
|
153
|
+
- 边界条件和错误处理
|
|
154
|
+
- 输出格式规范
|
|
155
|
+
|
|
156
|
+
### 3. 确认保存位置
|
|
157
|
+
|
|
158
|
+
询问用户希望将 Skill 保存到:
|
|
159
|
+
- **项目级** (\`.blade/skills/\`): 与团队共享,通过 git 同步(**默认推荐**)
|
|
160
|
+
- **用户级** (\`~/.blade/skills/\`): 个人使用,跨项目可用
|
|
161
|
+
|
|
162
|
+
如果用户没有明确指定,默认使用 **项目级** (\`.blade/skills/\`)。
|
|
163
|
+
|
|
164
|
+
### 4. 生成文件
|
|
165
|
+
|
|
166
|
+
**重要:直接使用 Write 工具创建文件,不要使用外部脚本。**
|
|
167
|
+
|
|
168
|
+
使用 Write 工具创建 SKILL.md 文件:
|
|
169
|
+
|
|
170
|
+
\`\`\`
|
|
171
|
+
.blade/skills/{name}/SKILL.md # 项目级(默认)
|
|
172
|
+
~/.blade/skills/{name}/SKILL.md # 用户级
|
|
173
|
+
\`\`\`
|
|
174
|
+
|
|
175
|
+
文件格式:
|
|
176
|
+
\`\`\`yaml
|
|
177
|
+
---
|
|
178
|
+
name: {name}
|
|
179
|
+
description: {description}
|
|
180
|
+
allowed-tools:
|
|
181
|
+
- {tool1}
|
|
182
|
+
- {tool2}
|
|
183
|
+
user-invocable: true # 如果需要 /skill-name 命令
|
|
184
|
+
---
|
|
185
|
+
|
|
186
|
+
# {Skill Title}
|
|
187
|
+
|
|
188
|
+
## Instructions
|
|
189
|
+
|
|
190
|
+
{详细指令}
|
|
191
|
+
|
|
192
|
+
## Examples
|
|
193
|
+
|
|
194
|
+
{使用示例}
|
|
195
|
+
\`\`\`
|
|
196
|
+
|
|
197
|
+
### 5. 刷新并验证
|
|
198
|
+
|
|
199
|
+
创建完成后,**必须提示用户执行 \`/skills\` 命令刷新 Skills 列表**,否则新创建的 Skill 不会立即生效。
|
|
200
|
+
|
|
201
|
+
验证步骤:
|
|
202
|
+
- 检查目录和文件是否创建成功
|
|
203
|
+
- **重要**:告诉用户执行 \`/skills\` 刷新列表
|
|
204
|
+
- 提示用户可以通过以下方式使用新 Skill:
|
|
205
|
+
- AI 自动调用(如果未禁用)
|
|
206
|
+
- \`/skill-name\` 命令(如果启用了 user-invocable)
|
|
207
|
+
|
|
208
|
+
## Best Practices
|
|
209
|
+
|
|
210
|
+
1. **名称规范**
|
|
211
|
+
- 使用 kebab-case:\`code-review\`, \`commit-helper\`, \`test-generator\`
|
|
212
|
+
- 名称应该简洁且描述性强
|
|
213
|
+
|
|
214
|
+
2. **描述要具体**
|
|
215
|
+
- 包含触发词,帮助 AI 识别何时使用
|
|
216
|
+
- 例如:"Generate commit messages following conventional commits format. Use when the user wants to commit changes or asks for a commit message."
|
|
217
|
+
|
|
218
|
+
3. **限制工具访问**
|
|
219
|
+
- 仅授予必要的工具权限,提高安全性
|
|
220
|
+
- 例如:只读 Skill 只需 Read, Grep, Glob
|
|
221
|
+
|
|
222
|
+
4. **提供清晰的指令**
|
|
223
|
+
- 使用 Markdown 格式组织内容
|
|
224
|
+
- 包含具体步骤和示例
|
|
225
|
+
- 处理边界情况
|
|
226
|
+
|
|
227
|
+
5. **考虑调用方式**
|
|
228
|
+
- 频繁使用的 Skill 可设置 \`user-invocable: true\`
|
|
229
|
+
- 仅限用户手动触发的 Skill 可设置 \`disable-model-invocation: true\`
|
|
230
|
+
|
|
231
|
+
## Example Skills
|
|
232
|
+
|
|
233
|
+
### 代码审查 Skill
|
|
234
|
+
|
|
235
|
+
\`\`\`yaml
|
|
236
|
+
---
|
|
237
|
+
name: code-review
|
|
238
|
+
description: Review code for best practices, bugs, and improvements. Use when reviewing PRs, checking code quality, or before committing.
|
|
239
|
+
allowed-tools:
|
|
240
|
+
- Read
|
|
241
|
+
- Grep
|
|
242
|
+
- Glob
|
|
243
|
+
argument-hint: <file_path>
|
|
244
|
+
user-invocable: true
|
|
245
|
+
---
|
|
246
|
+
|
|
247
|
+
# Code Review
|
|
248
|
+
|
|
249
|
+
审查代码质量、最佳实践和潜在问题。
|
|
250
|
+
|
|
251
|
+
## Instructions
|
|
252
|
+
|
|
253
|
+
1. 读取指定的文件或目录
|
|
254
|
+
2. 检查以下方面:
|
|
255
|
+
- 代码风格一致性
|
|
256
|
+
- 潜在的 bug 或错误
|
|
257
|
+
- 性能问题
|
|
258
|
+
- 安全漏洞
|
|
259
|
+
- 可读性和可维护性
|
|
260
|
+
3. 提供具体的改进建议
|
|
261
|
+
|
|
262
|
+
## Output Format
|
|
263
|
+
|
|
264
|
+
- 问题严重程度:[CRITICAL] 严重 | [WARN] 警告 | [INFO] 建议
|
|
265
|
+
- 具体位置和代码片段
|
|
266
|
+
- 改进建议和示例代码
|
|
267
|
+
\`\`\`
|
|
268
|
+
|
|
269
|
+
### 提交消息生成 Skill
|
|
270
|
+
|
|
271
|
+
\`\`\`yaml
|
|
272
|
+
---
|
|
273
|
+
name: commit-message
|
|
274
|
+
description: Generate conventional commit messages. Use when committing changes or when user asks for a commit message.
|
|
275
|
+
allowed-tools:
|
|
276
|
+
- Bash
|
|
277
|
+
- Read
|
|
278
|
+
user-invocable: true
|
|
279
|
+
---
|
|
280
|
+
|
|
281
|
+
# Commit Message Generator
|
|
282
|
+
|
|
283
|
+
生成符合 Conventional Commits 规范的提交消息。
|
|
284
|
+
|
|
285
|
+
## Instructions
|
|
286
|
+
|
|
287
|
+
1. 运行 \`git diff --staged\` 查看暂存的更改
|
|
288
|
+
2. 分析更改类型(feat/fix/docs/style/refactor/test/chore)
|
|
289
|
+
3. 生成简洁的提交消息
|
|
290
|
+
4. 询问用户是否满意或需要调整
|
|
291
|
+
|
|
292
|
+
## Output Format
|
|
293
|
+
|
|
294
|
+
\`\`\`
|
|
295
|
+
<type>(<scope>): <subject>
|
|
296
|
+
|
|
297
|
+
<body>
|
|
298
|
+
|
|
299
|
+
<footer>
|
|
300
|
+
\`\`\`
|
|
301
|
+
\`\`\`
|
|
302
|
+
`}}var T0={name:"update-config",description:"配置 Blade harness(settings/hooks/permissions)。"+"用户请求自动化行为时使用此 Skill。",allowedTools:["ConfigTool","Read","Bash","AskUserQuestion"],version:"1.0.0",userInvocable:!0,disableModelInvocation:!1,whenToUse:'用户说"从现在起..."、"每次..."、"当...时..."、'+"需要改配置、安装 hooks、修改权限",path:"builtin://update-config",basePath:"",source:"builtin"};function $Z(){return{metadata:T0,instructions:`# Update Config Skill
|
|
303
|
+
|
|
304
|
+
配置 Blade 运行环境。管理 settings、hooks、permissions、环境变量等。
|
|
305
|
+
|
|
306
|
+
## 三层配置体系
|
|
307
|
+
|
|
308
|
+
Blade 采用三层配置,优先级从低到高:
|
|
309
|
+
|
|
310
|
+
| 层级 | 路径 | 用途 | scope 值 |
|
|
311
|
+
|------|------|------|----------|
|
|
312
|
+
| Global | \`~/.blade/config.json\` + \`~/.blade/settings.json\` | 用户全局默认 | \`global\` |
|
|
313
|
+
| Project | \`.blade/settings.json\` | 项目级设置,提交到 git | \`project\` |
|
|
314
|
+
| Local | \`.blade/settings.local.json\` | 本地覆盖,.gitignore | \`local\` |
|
|
315
|
+
|
|
316
|
+
**选择原则:**
|
|
317
|
+
- 个人偏好(theme, language, fontSize)→ \`global\`
|
|
318
|
+
- 团队共享(hooks, permissions, env)→ \`project\`
|
|
319
|
+
- 临时调试(debug, maxTurns)→ \`local\`
|
|
320
|
+
|
|
321
|
+
## ConfigTool 使用
|
|
322
|
+
|
|
323
|
+
### GET - 读取配置
|
|
324
|
+
|
|
325
|
+
\`\`\`
|
|
326
|
+
# 获取全部配置
|
|
327
|
+
ConfigTool({ operation: "get", key: "*" })
|
|
328
|
+
|
|
329
|
+
# 获取特定配置
|
|
330
|
+
ConfigTool({ operation: "get", key: "hooks" })
|
|
331
|
+
|
|
332
|
+
# 获取嵌套值
|
|
333
|
+
ConfigTool({ operation: "get", key: "hooks.PreToolUse" })
|
|
334
|
+
|
|
335
|
+
# 获取权限设置
|
|
336
|
+
ConfigTool({ operation: "get", key: "permissions" })
|
|
337
|
+
\`\`\`
|
|
338
|
+
|
|
339
|
+
### SET - 设置配置
|
|
340
|
+
|
|
341
|
+
\`\`\`
|
|
342
|
+
# 设置温度
|
|
343
|
+
ConfigTool({ operation: "set", key: "temperature", value: 0.7, scope: "global" })
|
|
344
|
+
|
|
345
|
+
# 设置语言
|
|
346
|
+
ConfigTool({ operation: "set", key: "language", value: "zh-CN", scope: "global" })
|
|
347
|
+
|
|
348
|
+
# 设置最大轮次
|
|
349
|
+
ConfigTool({ operation: "set", key: "maxTurns", value: 50, scope: "local" })
|
|
350
|
+
|
|
351
|
+
# 启用调试
|
|
352
|
+
ConfigTool({ operation: "set", key: "debug", value: true, scope: "local" })
|
|
353
|
+
|
|
354
|
+
# 设置环境变量
|
|
355
|
+
ConfigTool({ operation: "set", key: "env", value: { "NODE_ENV": "development" }, scope: "project" })
|
|
356
|
+
\`\`\`
|
|
357
|
+
|
|
358
|
+
### LIST - 列举可配置项
|
|
359
|
+
|
|
360
|
+
\`\`\`
|
|
361
|
+
ConfigTool({ operation: "list" })
|
|
362
|
+
\`\`\`
|
|
363
|
+
|
|
364
|
+
返回所有白名单配置项及其当前值。
|
|
365
|
+
|
|
366
|
+
## 白名单字段
|
|
367
|
+
|
|
368
|
+
以下字段可通过 ConfigTool SET 修改:
|
|
369
|
+
|
|
370
|
+
| 字段 | 类型 | 说明 |
|
|
371
|
+
|------|------|------|
|
|
372
|
+
| temperature | number | 模型温度 |
|
|
373
|
+
| maxContextTokens | number | 上下文窗口大小 |
|
|
374
|
+
| maxOutputTokens | number | 输出 token 限制 |
|
|
375
|
+
| timeout | number | HTTP 请求超时(毫秒)|
|
|
376
|
+
| theme | string | 终端主题 |
|
|
377
|
+
| uiTheme | string | Web UI 主题 |
|
|
378
|
+
| language | string | 界面语言 |
|
|
379
|
+
| fontSize | number | 字体大小 |
|
|
380
|
+
| debug | boolean/string | 调试模式 |
|
|
381
|
+
| autoSaveSessions | boolean | 自动保存会话 |
|
|
382
|
+
| maxTurns | number | Agent 最大轮次 |
|
|
383
|
+
| disableAllHooks | boolean | 禁用所有 hooks |
|
|
384
|
+
| permissions | object | 权限规则 |
|
|
385
|
+
| hooks | object | Hooks 配置 |
|
|
386
|
+
| env | object | 环境变量 |
|
|
387
|
+
| mcpServers | object | MCP 服务器配置 |
|
|
388
|
+
|
|
389
|
+
**禁止修改的字段:** models、currentModelId(保护 API Key 安全)
|
|
390
|
+
|
|
391
|
+
## Hooks 安装指南
|
|
392
|
+
|
|
393
|
+
Hooks 是 Blade 的自动化机制,在特定事件发生时执行 shell 命令。
|
|
394
|
+
|
|
395
|
+
### HookEvent 类型
|
|
396
|
+
|
|
397
|
+
| 事件 | 触发时机 | 典型用途 |
|
|
398
|
+
|------|----------|----------|
|
|
399
|
+
| PreToolUse | 工具执行前 | 代码检查、格式化验证 |
|
|
400
|
+
| PostToolUse | 工具执行后 | 自动运行 lint/test |
|
|
401
|
+
| PostToolUseFailure | 工具执行失败后 | 错误日志 |
|
|
402
|
+
| PermissionRequest | 权限请求时 | 自动批准/拒绝 |
|
|
403
|
+
| UserPromptSubmit | 用户提交提示时 | 注入上下文 |
|
|
404
|
+
| SessionStart | 会话启动时 | 环境初始化 |
|
|
405
|
+
| SessionEnd | 会话结束时 | 清理操作 |
|
|
406
|
+
| Stop | Agent 停止时 | 阻止过早停止 |
|
|
407
|
+
| SubagentStop | 子 Agent 停止时 | 同上 |
|
|
408
|
+
| Notification | 通知事件时 | 自定义通知 |
|
|
409
|
+
| Compaction | 上下文压缩时 | 阻止压缩 |
|
|
410
|
+
|
|
411
|
+
### HookMatcher 结构
|
|
412
|
+
|
|
413
|
+
每个 HookMatcher 包含:
|
|
414
|
+
- \`name\`(可选): 名称,用于日志
|
|
415
|
+
- \`matcher\`(可选): 匹配器,不指定则匹配所有
|
|
416
|
+
- \`tools\`: 工具名匹配(支持字符串或数组,如 \`"Edit"\` 或 \`["Edit", "Write"]\`)
|
|
417
|
+
- \`paths\`: 文件路径匹配(glob 模式,如 \`"**/*.ts"\`)
|
|
418
|
+
- \`commands\`: 命令匹配(正则,如 \`"^git"\`)
|
|
419
|
+
- \`hooks\`: Hook 列表
|
|
420
|
+
|
|
421
|
+
### CommandHook 结构
|
|
422
|
+
|
|
423
|
+
\`\`\`json
|
|
424
|
+
{
|
|
425
|
+
"type": "command",
|
|
426
|
+
"command": "shell command to execute",
|
|
427
|
+
"timeout": 30,
|
|
428
|
+
"statusMessage": "Running check..."
|
|
429
|
+
}
|
|
430
|
+
\`\`\`
|
|
431
|
+
|
|
432
|
+
Hook 接收 JSON 格式的输入通过 stdin,输出 JSON 到 stdout。
|
|
433
|
+
|
|
434
|
+
### 完整安装示例
|
|
435
|
+
|
|
436
|
+
**示例 1:安装 biome check 作为 PostToolUse hook**
|
|
437
|
+
|
|
438
|
+
当 Edit 或 Write 工具修改 .ts/.tsx 文件后,自动运行 biome check:
|
|
439
|
+
|
|
440
|
+
\`\`\`
|
|
441
|
+
ConfigTool({
|
|
442
|
+
operation: "set",
|
|
443
|
+
key: "hooks",
|
|
444
|
+
value: {
|
|
445
|
+
"PostToolUse": [
|
|
446
|
+
{
|
|
447
|
+
"name": "biome-check",
|
|
448
|
+
"matcher": {
|
|
449
|
+
"tools": ["Edit", "Write"],
|
|
450
|
+
"paths": ["**/*.ts", "**/*.tsx"]
|
|
451
|
+
},
|
|
452
|
+
"hooks": [
|
|
453
|
+
{
|
|
454
|
+
"type": "command",
|
|
455
|
+
"command": "biome check --write $(echo $TOOL_INPUT | jq -r '.file_path // empty')",
|
|
456
|
+
"timeout": 30,
|
|
457
|
+
"statusMessage": "Running biome check..."
|
|
458
|
+
}
|
|
459
|
+
]
|
|
460
|
+
}
|
|
461
|
+
]
|
|
462
|
+
},
|
|
463
|
+
scope: "project"
|
|
464
|
+
})
|
|
465
|
+
\`\`\`
|
|
466
|
+
|
|
467
|
+
**示例 2:安装 eslint 作为 PostToolUse hook**
|
|
468
|
+
|
|
469
|
+
\`\`\`
|
|
470
|
+
ConfigTool({
|
|
471
|
+
operation: "set",
|
|
472
|
+
key: "hooks",
|
|
473
|
+
value: {
|
|
474
|
+
"PostToolUse": [
|
|
475
|
+
{
|
|
476
|
+
"name": "eslint-fix",
|
|
477
|
+
"matcher": {
|
|
478
|
+
"tools": ["Edit", "Write"],
|
|
479
|
+
"paths": ["**/*.ts", "**/*.tsx", "**/*.js", "**/*.jsx"]
|
|
480
|
+
},
|
|
481
|
+
"hooks": [
|
|
482
|
+
{
|
|
483
|
+
"type": "command",
|
|
484
|
+
"command": "eslint --fix $(echo $TOOL_INPUT | jq -r '.file_path // empty')",
|
|
485
|
+
"timeout": 30,
|
|
486
|
+
"statusMessage": "Running ESLint..."
|
|
487
|
+
}
|
|
488
|
+
]
|
|
489
|
+
}
|
|
490
|
+
]
|
|
491
|
+
},
|
|
492
|
+
scope: "project"
|
|
493
|
+
})
|
|
494
|
+
\`\`\`
|
|
495
|
+
|
|
496
|
+
**示例 3:安装 SessionStart hook 打印环境信息**
|
|
497
|
+
|
|
498
|
+
\`\`\`
|
|
499
|
+
ConfigTool({
|
|
500
|
+
operation: "set",
|
|
501
|
+
key: "hooks",
|
|
502
|
+
value: {
|
|
503
|
+
"SessionStart": [
|
|
504
|
+
{
|
|
505
|
+
"name": "env-info",
|
|
506
|
+
"hooks": [
|
|
507
|
+
{
|
|
508
|
+
"type": "command",
|
|
509
|
+
"command": "echo 'Node:' $(node -v) '| Git branch:' $(git branch --show-current)",
|
|
510
|
+
"timeout": 10,
|
|
511
|
+
"statusMessage": "Gathering environment info..."
|
|
512
|
+
}
|
|
513
|
+
]
|
|
514
|
+
}
|
|
515
|
+
]
|
|
516
|
+
},
|
|
517
|
+
scope: "project"
|
|
518
|
+
})
|
|
519
|
+
\`\`\`
|
|
520
|
+
|
|
521
|
+
**示例 4:设置权限白名单**
|
|
522
|
+
|
|
523
|
+
\`\`\`
|
|
524
|
+
ConfigTool({
|
|
525
|
+
operation: "set",
|
|
526
|
+
key: "permissions",
|
|
527
|
+
value: {
|
|
528
|
+
"allow": [
|
|
529
|
+
"Bash(git:*)",
|
|
530
|
+
"Bash(npm:*)",
|
|
531
|
+
"Bash(bun:*)",
|
|
532
|
+
"Read(**/*.ts)"
|
|
533
|
+
],
|
|
534
|
+
"ask": [],
|
|
535
|
+
"deny": [
|
|
536
|
+
"Bash(rm -rf:*)"
|
|
537
|
+
]
|
|
538
|
+
},
|
|
539
|
+
scope: "project"
|
|
540
|
+
})
|
|
541
|
+
\`\`\`
|
|
542
|
+
|
|
543
|
+
## 自动行为关键词映射
|
|
544
|
+
|
|
545
|
+
当用户使用以下关键词时,映射到对应的配置操作:
|
|
546
|
+
|
|
547
|
+
| 用户说的 | 映射到 |
|
|
548
|
+
|----------|--------|
|
|
549
|
+
| "从现在起 lint 每个文件" | PostToolUse hook(Edit/Write 后运行 lint)|
|
|
550
|
+
| "每次提交前运行测试" | PreToolUse hook(Bash git commit 前运行 test)|
|
|
551
|
+
| "当编辑 TS 文件时检查类型" | PostToolUse hook(Edit 后运行 tsc)|
|
|
552
|
+
| "允许所有 git 命令" | permissions.allow 添加 \`Bash(git:*)\` |
|
|
553
|
+
| "设置调试模式" | debug = true |
|
|
554
|
+
| "改成中文" | language = "zh-CN" |
|
|
555
|
+
| "提高温度" | temperature 调整 |
|
|
556
|
+
| "限制 50 轮" | maxTurns = 50 |
|
|
557
|
+
| "禁用 hooks" | disableAllHooks = true |
|
|
558
|
+
| "添加环境变量" | env 对象更新 |
|
|
559
|
+
|
|
560
|
+
## 验证流程
|
|
561
|
+
|
|
562
|
+
每次安装 hook 或修改配置后,**必须**验证:
|
|
563
|
+
|
|
564
|
+
1. 用 \`ConfigTool({ operation: "get", key: "<modified-key>" })\` 确认值已生效
|
|
565
|
+
2. 如果是 hooks,检查结构是否正确(包含 matcher 和 hooks 数组)
|
|
566
|
+
3. 如果是 permissions,确认 allow/ask/deny 数组格式正确
|
|
567
|
+
4. 告知用户配置已保存到哪个文件(根据 scope 判断)
|
|
568
|
+
|
|
569
|
+
## 注意事项
|
|
570
|
+
|
|
571
|
+
1. **hooks 字段使用 deep-merge 策略**:设置新的 hook 不会覆盖已有的 hook。但如果同一事件下设置新的 matcher 数组,会替换该事件的整个 matcher 列表
|
|
572
|
+
2. **permissions 字段使用 replace 策略**:设置 permissions 会完全替换现有值。如果只想添加规则,先 GET 当前值,合并后再 SET
|
|
573
|
+
3. **env 字段使用 deep-merge 策略**:可以逐个添加环境变量
|
|
574
|
+
4. **scope 默认值**:不指定 scope 时,根据字段路由表决定(hooks/permissions/env 默认 local,temperature/theme 等默认 global)
|
|
575
|
+
`}}import{exec as A2}from"node:child_process";import*as w from"node:fs/promises";import{homedir as y2}from"node:os";import*as M from"node:path";import{promisify as S2}from"node:util";var x0=S2(A2),U=i("General"),OQ={url:"https://github.com/anthropics/skills.git",branch:"main",defaultSkills:["skill-creator"]};class JZ{skillsDir;constructor(Q){this.skillsDir=Q||M.join(y2(),".blade","skills")}async isInstalled(Q){let Z=M.join(this.skillsDir,Q,"SKILL.md");try{return await w.access(Z),!0}catch{return!1}}async isGitAvailable(){try{return await x0("git --version"),!0}catch{return!1}}async installOfficialSkill(Q){let{url:Z,branch:$}=OQ,J=M.join(this.skillsDir,Q),z=M.join(this.skillsDir,`.tmp-${Q}-${Date.now()}`);try{if(!await this.isGitAvailable())return U.warn("Git not available, skipping skill installation"),!1;U.info(`Installing official skill: ${Q}...`),await w.mkdir(this.skillsDir,{recursive:!0,mode:493}),await x0(`git clone --depth 1 --branch ${$} --single-branch ${Z} "${z}"`,{timeout:30000});let G=M.join(z,"skills",Q);try{await w.access(G)}catch{return U.warn(`Skill ${Q} not found in official repository`),await w.rm(z,{recursive:!0,force:!0}),!1}try{await w.rm(J,{recursive:!0,force:!0})}catch{}return await w.cp(G,J,{recursive:!0}),await w.rm(z,{recursive:!0,force:!0}),U.info(`Successfully installed: ${Q}`),!0}catch(G){try{await w.rm(z,{recursive:!0,force:!0})}catch{}return U.warn(`Failed to install ${Q}: ${G instanceof Error?G.message:"Unknown error"}`),!1}}async ensureDefaultSkillsInstalled(){await w.mkdir(this.skillsDir,{recursive:!0,mode:493});for(let Q of OQ.defaultSkills)if(!await this.isInstalled(Q))await this.installOfficialSkill(Q)}async installFromRepo(Q,Z){let $=Z||this.extractRepoName(Q),J=M.join(this.skillsDir,$),z=M.join(this.skillsDir,`.tmp-repo-${$}-${Date.now()}`);try{if(!await this.isGitAvailable())return U.warn("Git not available, cannot install from repo"),!1;U.info(`Installing skill from repo: ${Q}...`),await w.mkdir(this.skillsDir,{recursive:!0,mode:493}),await x0(`git clone --depth 1 "${Q}" "${z}"`,{timeout:60000});let G=M.join(z,"SKILL.md");try{await w.access(G)}catch{return U.warn(`No SKILL.md found in repository ${Q}`),await w.rm(z,{recursive:!0,force:!0}),!1}await w.rm(J,{recursive:!0,force:!0}),await w.rename(z,J);try{await w.rm(M.join(J,".git"),{recursive:!0,force:!0})}catch{}return U.info(`Successfully installed skill from repo: ${$}`),!0}catch(G){try{await w.rm(z,{recursive:!0,force:!0})}catch{}return U.warn(`Failed to install from repo ${Q}: ${G instanceof Error?G.message:"Unknown error"}`),!1}}async installFromLocal(Q,Z,$=!0){let J=Z||M.basename(Q),z=M.join(this.skillsDir,J);try{let G=M.resolve(Q);try{await w.access(G)}catch{return U.warn(`Local path does not exist: ${G}`),!1}let W=M.join(G,"SKILL.md");try{await w.access(W)}catch{return U.warn(`No SKILL.md found in local path: ${G}`),!1}if(U.info(`Installing skill from local path: ${G}...`),await w.mkdir(this.skillsDir,{recursive:!0,mode:493}),await w.rm(z,{recursive:!0,force:!0}),$)await w.symlink(G,z,"dir"),U.info(`Created symlink for skill: ${J}`);else await w.cp(G,z,{recursive:!0}),U.info(`Copied skill to: ${J}`);return!0}catch(G){return U.warn(`Failed to install from local path ${Q}: ${G instanceof Error?G.message:"Unknown error"}`),!1}}extractRepoName(Q){return Q.match(/\/([^/]+?)(\.git)?$/)?.[1]||"unknown-skill"}async installAllOfficialSkills(){let{url:Q,branch:Z}=OQ,$=M.join(this.skillsDir,`.tmp-all-${Date.now()}`),J=[],z=[];try{if(!await this.isGitAvailable())return U.warn("Git not available, skipping skill installation"),{installed:J,failed:z};await w.mkdir(this.skillsDir,{recursive:!0,mode:493}),U.info("Cloning official skills repository..."),await x0(`git clone --depth 1 --branch ${Z} --single-branch ${Q} "${$}"`,{timeout:60000});let G=M.join($,"skills"),W=await w.readdir(G,{withFileTypes:!0});for(let V of W){if(!V.isDirectory())continue;let Y=V.name,X=M.join(G,Y),D=M.join(this.skillsDir,Y);try{await w.access(M.join(X,"SKILL.md")),await w.rm(D,{recursive:!0,force:!0}),await w.cp(X,D,{recursive:!0}),U.info(`Installed: ${Y}`),J.push(Y)}catch(O){U.warn(`Failed to install ${Y}`),z.push(Y)}}await w.rm($,{recursive:!0,force:!0})}catch(G){try{await w.rm($,{recursive:!0,force:!0})}catch{}U.warn(`Failed to install skills: ${G instanceof Error?G.message:"Unknown error"}`)}return{installed:J,failed:z}}}var _Q=null;function zZ(Q){if(!_Q)_Q=new JZ(Q);return _Q}import*as _0 from"node:fs/promises";import*as R0 from"node:path";import{parse as U2}from"yaml";var M2=/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/,f2=/^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]?$/,GZ=1024;function h2(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 WZ(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 k2(Q,Z){if(!Q.name)return{valid:!1,error:"Missing required field: name"};if(!f2.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>GZ)return{valid:!1,error:`Description too long: ${Q.description.length} characters (max ${GZ})`};let $;if(Q.model)$=Q.model==="inherit"?"inherit":Q.model;return{valid:!0,metadata:{name:Q.name,description:Q.description.trim(),allowedTools:h2(Q["allowed-tools"]),version:Q.version,argumentHint:Q["argument-hint"]?.trim(),userInvocable:WZ(Q["user-invocable"]),disableModelInvocation:WZ(Q["disable-model-invocation"]),model:$,whenToUse:Q.when_to_use?.trim()}}}function VZ(Q,Z,$){let J=Q.match(M2);if(!J)return{success:!1,error:"Invalid SKILL.md format: missing YAML frontmatter (must start with ---)"};let[,z,G]=J,W;try{W=U2(z)}catch(X){return{success:!1,error:`Failed to parse YAML frontmatter: ${X instanceof Error?X.message:String(X)}`}}let V=k2(W,Z);if(!V.valid)return{success:!1,error:V.error};let Y=R0.dirname(Z);return{success:!0,content:{metadata:{...V.metadata,path:Z,basePath:Y,source:$},instructions:G.trim()}}}async function YZ(Q,Z){try{let $=await _0.readFile(Q,"utf-8");return VZ($,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 HZ(Q){try{let Z=await _0.readFile(Q.path,"utf-8"),$=VZ(Z,Q.path,Q.source);return $.success?$.content:null}catch{return null}}async function XZ(Q){try{return await _0.access(R0.join(Q,"SKILL.md")),!0}catch{return!1}}var T2={userSkillsDir:o.join(BZ(),".blade","skills"),projectSkillsDir:".blade/skills",claudeUserSkillsDir:o.join(BZ(),".claude","skills"),claudeProjectSkillsDir:".claude/skills"},C0=null;class wQ{skills=new Map;pluginSkills=new Map;config;initialized=!1;constructor(Q){this.config={...T2,cwd:m(),...Q}}static getInstance(Q){if(!C0)C0=new wQ(Q);return C0}static resetInstance(){C0=null}async initialize(){if(this.initialized)return{skills:Array.from(this.skills.values()),errors:[]};let Q=[],Z=[];try{await zZ(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=o.isAbsolute(this.config.claudeProjectSkillsDir)?this.config.claudeProjectSkillsDir:o.join(this.config.cwd,this.config.claudeProjectSkillsDir),G=await this.scanDirectory(z,"project");Z.push(...G.skills),Q.push(...G.errors);let W=o.isAbsolute(this.config.projectSkillsDir)?this.config.projectSkillsDir:o.join(this.config.cwd,this.config.projectSkillsDir),V=await this.scanDirectory(W,"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(k0.name,k0),this.skills.set(T0.name,T0)}async scanDirectory(Q,Z){let $=[],J=[];try{await p0.access(Q)}catch{return{skills:$,errors:J}}try{let z=await p0.readdir(Q,{withFileTypes:!0});for(let G of z){if(!G.isDirectory())continue;let W=o.join(Q,G.name),V=o.join(W,"SKILL.md");if(!await XZ(W))continue;let Y=await YZ(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 HZ(Z)}loadBuiltinContent(Q){switch(Q){case"skill-creator":return ZZ();case"update-config":return $Z();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 d0(Q){return wQ.getInstance(Q)}async function x2(Q){return d0(Q).initialize()}var R2="Skill",C2=/<available_skills>\s*<\/available_skills>/;function qQ(Q){let $=d0().generateAvailableSkillsList();if(!$)return Q;return Q.map((J)=>{if(J.name!==R2)return J;let z=J.description.replace(C2,`<available_skills>
|
|
577
|
+
${$}
|
|
578
|
+
</available_skills>`);if(z===J.description)return J;return{...J,description:z}})}function KZ(){return{consecutiveFailures:new Map,totalFailures:0,lastFailedTool:null}}function jZ(Q,Z){Q.consecutiveFailures.set(Z,0),Q.lastFailedTool=null}function DZ(Q,Z){let $=(Q.consecutiveFailures.get(Z)??0)+1;Q.consecutiveFailures.set(Z,$),Q.totalFailures++,Q.lastFailedTool=Z}function p2(Q,Z){return(Q.consecutiveFailures.get(Z)??0)>=3}function FZ(Q,Z){if(!p2(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 bZ(Q){return Q>0&&Q%5===0}function LZ(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 OZ(){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 _Z(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((G)=>G===J[0]);if(z)Q.recentOutputHashes=[];return z}function wZ(){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 Z0=i("Agent"),m2=new Set(["Read","Glob","Grep","WebFetch","WebSearch","MemoryRead","GetSpecContext","ValidateSpec","TaskOutput"]);class g0{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;executeTool;admitTool;rollbackAdmission;constructor(Q,Z,$,J,z,G,W){this.pipeline=Q;this.execContext=Z;this.registry=$;this.contextMgr=J;this.sessionId=z;this.lastMessageUuid=G;this.subagentInfo=W}setExecutionPolicy(Q){this.executeTool=Q}setAdmissionPolicy(Q){this.admitTool=Q}setAdmissionRollback(Q){this.rollbackAdmission=Q}addTool(Q,Z){if(this.dispatched.has(Q.id))return Z0.debug(`[StreamingToolExecutor] 跳过已分发工具: ${Q.function.name} (${Q.id})`),"rejected";this.dispatched.add(Q.id),this.order.push(Q.id);let $=this.admitTool?.(Q.function.name,Z);if($)return this.completed.set(Q.id,{toolCall:Q,result:$,toolUseUuid:null}),"rejected";if(m2.has(Q.function.name)){Z0.debug(`[StreamingToolExecutor] 立即执行预启动工具: ${Q.function.name}`);let z=this.executeOne(Q,Z);return this.pending.set(Q.id,z),"prelaunched"}else return Z0.debug(`[StreamingToolExecutor] 排队非预启动工具: ${Q.function.name}`),this.queued.push({toolCall:Q,params:Z}),"queued"}getQueuedToolCalls(){return this.queued.map((Q)=>Q.toolCall)}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){Z0.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(){for(let Q of this.queued)this.rollbackAdmission?.(Q.toolCall.function.name);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(),Z0.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 G=null;try{if(this.contextMgr&&this.sessionId)G=await this.contextMgr.saveToolUse(this.sessionId,Q.function.name,Z,this.lastMessageUuid??null,this.subagentInfo)}catch(F){Z0.warn("[StreamingToolExecutor] 保存工具调用失败:",F)}let W=[z,J.signal],V=this.execContext.signal;if(V)W.push(V);let Y=qZ(...W),X={...this.execContext,messageId:G??Q.id,signal:Y},D=this.executeTool?await this.executeTool(Q.function.name,Z,X):await this.pipeline.execute(Q.function.name,Z,X);if($!==this.epoch)return Z0.debug(`[StreamingToolExecutor] 丢弃旧世代工具结果: ${Q.function.name} (startEpoch=${$}, currentEpoch=${this.epoch})`),this.makeAbortResult(Q,"Tool execution aborted due to epoch mismatch (discard)");let O={toolCall:Q,result:D,toolUseUuid:G};if(this.pending.has(Q.id))this.pending.delete(Q.id),this.completed.set(Q.id,O);return O}catch(G){if($!==this.epoch)return this.makeAbortResult(Q,"Tool execution aborted due to epoch mismatch (discard)");Z0.error(`[StreamingToolExecutor] 工具执行失败: ${Q.function.name}`,G);let W={success:!1,llmContent:"",error:{type:"execution_error",message:G instanceof Error?G.message:"Unknown error"},metadata:void 0},V={toolCall:Q,result:W,toolUseUuid:null,error:G instanceof Error?G: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 f=i("Agent"),c2=0.1,u2=8192,i2=32768,n2=2,l2=0.95,m0=IZ;function c0(Q,Z){return{inputTokens:Q.promptTokens??0,outputTokens:Q.completionTokens??0,totalTokens:Q.totalTokens??0,maxContextTokens:Z,cacheReadTokens:Q.cacheReadInputTokens??0,cacheWriteTokens:Q.cacheCreationInputTokens??0,costUsd:Q.costUsd}}var r2=`
|
|
580
|
+
|
|
581
|
+
# Task Execution Strategy
|
|
582
|
+
When facing complex multi-step tasks:
|
|
583
|
+
1. Break the task into concrete, verifiable steps before acting.
|
|
584
|
+
2. Execute one step at a time — verify each step succeeded before moving to the next.
|
|
585
|
+
3. If a step fails, diagnose the root cause rather than repeating the same approach.
|
|
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 EZ(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 EQ(Q){let Z=EZ(Q);if(Z)return Z;try{let $=JSON.parse(Q);return typeof $==="string"?EZ($):null}catch{return null}}function a2(Q){if(typeof Q==="string")return Q;try{return JSON.parse(JSON.stringify(Q))}catch{return String(Q)}}function o2(Q){let Z=new Set,$=!1;for(let J of Q){if(J.role==="assistant"){if(J.tool_calls&&J.tool_calls.length>0){for(let G of J.tool_calls)if("function"in G&&G.function.name==="Task")Z.add(G.id)}else if($)$=!1;continue}if(J.role!=="tool"||J.name!=="Task"||!J.tool_call_id||!Z.has(J.tool_call_id)||typeof J.metadata!=="object"||J.metadata===null||Array.isArray(J.metadata))continue;let z=J.metadata;if(z.toolCallId===J.tool_call_id&&z.toolName==="Task"&&z.error===null)$=!0}return $}function s2(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,G=z.match(/Last error:\s*(.+)$/);if(G)return G[1];return z}function t2(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 e2(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 Q7(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 Z7(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 $7(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*J7(Q,Z,$,J,z,G){let W="",V="",Y,X,D=new Map;try{let O=Q.chatService.streamChat(Z,$,J,z),F=0;for await(let b of O){if(F++,J?.aborted)break;if(b.modelFallback){G?.discard(),W="",V="",Y=void 0,X=void 0,D.clear(),F=0,yield{kind:"model_fallback"};continue}if(b.content)W+=b.content,yield{kind:"content_delta",delta:b.content};if(b.reasoningContent)V+=b.reasoningContent,yield{kind:"thinking_delta",delta:b.reasoningContent};if(b.usage)Y=b.usage;if(b.toolCalls){for(let k of b.toolCalls)if(Z7(D,k),G){let N=k.index??0,I=D.get(N);if(I&&I.id&&I.name)try{let L=EQ(I.arguments);if(L===null)continue;let u={id:I.id,type:"function",function:{name:I.name,arguments:I.arguments}},y=Q.toolExecutor.getRegistry().get(I.name)?.kind;if(G.addTool(u,L)==="prelaunched")yield{kind:"tool_start",toolCall:u,toolKind:y}}catch{}}}if(b.finishReason){X=b.finishReason;break}}if(F===0&&!J?.aborted&&W.length===0&&D.size===0)return f.warn("[Loop] 流式响应返回0个chunk,回退到非流式模式"),G?.discard(),{...await Q.chatService.chat(Z,$,J,z),_nonStreamingFallback:!0};return{content:W,reasoningContent:V||void 0,toolCalls:$7(D),usage:Y,finishReason:X}}catch(O){if(t2(O))return f.warn("[Loop] 流式请求失败,降级到非流式模式"),G?.discard(),{...await Q.chatService.chat(Z,$,J,z),_nonStreamingFallback:!0};throw O}}async function*PZ(Q,Z,$,J,z,G,W,V){if(J===void 0)return f.debug(`[Loop] [轮次 ${$}] 压缩检查: 跳过(无历史 usage 数据)`),"none";let Y=oQ(Z.messages,G);if(Y)Z.messages=Y.messages,f.debug(`[Loop] [轮次 ${$}] MicroCompact: 清理 ${Y.snippedCount} 轮旧工具结果(缓存已过期)`);let X=L0(Z.messages),D=!1;if(X.snippedCount>0)D=!0,f.debug(`[Loop] [轮次 ${$}] Snip 压缩: 移除 ${X.snippedCount} 轮旧工具调用,释放约 ${X.estimatedTokensFreed} tokens`);let O=Q.chatService.getConfig(),F=O.model,b=O.maxContextTokens??0,k=O.maxOutputTokens??Q.config.maxOutputTokens??Math.min(Math.max(Math.floor(b*c2),u2),i2),x=b-k,N=Math.floor(x*0.8);if(f.debug(`[Loop] [轮次 ${$}] 压缩检查:`,{promptTokens:J,maxContextTokens:b,maxOutputTokens:k,availableForInput:x,threshold:N,shouldCompact:J>=N}),J<N){if(D)Z.messages=X.messages;return D?"snipped":"none"}let I=V?.lastCompactionTurn===void 0?void 0:$-V.lastCompactionTurn,L=I!==void 0&&I<=n2,u=Math.floor(x*l2);if(L&&J<u){if(D)Z.messages=X.messages;return f.debug(`[Loop] [轮次 ${$}] 跳过连续 LLM 压缩,距离上次压缩 ${I} 轮`),D?"snipped":"none"}f.debug($===0?"[Loop] 触发自动压缩":`[Loop] [轮次 ${$}] 触发循环内自动压缩`),yield{kind:"compaction",phase:"start"};try{let l=D?X.messages:Z.messages,y=await Y0.compact(l,{trigger:"auto",modelName:F,modelProvider:O.provider,maxContextTokens:b,apiKey:O.apiKey,baseURL:O.baseUrl,actualPreTokens:J,signal:z,activeTask:W,workspaceRoot:Z.workspaceRoot||m(),sessionId:Z.sessionId});if(y.usage)yield{kind:"token_usage",usage:c0(y.usage,b)};if(Z.messages=y.compactedMessages,V)V.lastCompactionTurn=$;if(y.success)f.debug(`[Loop] [轮次 ${$}] 压缩完成: ${y.preTokens} -> ${y.postTokens} tokens`);else f.warn(`[Loop] [轮次 ${$}] 压缩使用降级策略: ${y.preTokens} -> ${y.postTokens} tokens`);return await U0(Q,Z,y.summary,{trigger:"auto",preTokens:y.preTokens,postTokens:y.postTokens,filesIncluded:y.filesIncluded}),"compacted"}catch(l){if(G0(l))return f.debug(`[Loop] [轮次 ${$}] 压缩被中止`),"none";if(D)Z.messages=X.messages;return f.error(`[Loop] [轮次 ${$}] 压缩失败,继续执行`,l),D?"snipped":"none"}finally{yield{kind:"compaction",phase:"end"}}}function z7(Q,Z,$,J){let z=J?vZ(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*G7(Q,Z,$,J,z){let G=Date.now(),W=0,V=[],Y=null,X=!1,D=(O,F,b)=>{return X=!0,z7(O,F,G,b)};try{let O=Q.toolExecutor.getRegistry(),F=$.permissionMode,b=O.getFunctionDeclarationsByMode(F);b=qQ(b);let k=Q.applySkillToolRestrictions(b),x=KZ(),N=OZ(),I=z;if(typeof O.getDeferredToolsListing==="function"){let E=O.getDeferredToolsListing();if(E&&I)I=`${I}
|
|
589
|
+
|
|
590
|
+
${E}`}if(I)I+=r2;let L=new v0($,I),u=J?.pendingInputOnly===!0;if(!u){let E=J?.inputMessageId?{inboxMessageId:J.inputMessageId}:void 0,P=E??(J?.transientInput==="goal_continuation"?{transientGoalContinuation:!0}:void 0);if(L.appendUser({role:"user",content:Z,metadata:P}),J?.transientInput!=="goal_continuation")Y=await a(Q,$,Z,null,E);if(J?.inputMessageId&&!Y)throw Error(`Failed to persist durable input before applying it: ${J.inputMessageId}`)}let l=$.permissionMode==="yolo",y=!!$.subagentInfo,s=Q.runtimeOptions.maxTurns??J?.maxTurns??Q.config.maxTurns??-1,u0=s>=0;if(s===0)return{success:!1,error:{type:"chat_disabled",message:"对话功能已被禁用 (maxTurns=0)"},metadata:{turnsCount:0,toolCallsCount:0,duration:0}};let R=s===-1?m0:Math.min(s,m0),r=0,i0,IQ,X0=0,n0=0,l0=0,r0=0,B0,a0=0,o0=new Set,g=new Set($.worktreeActive?["EnterWorktree","TaskWorktree"]:[]),n=typeof Z==="string"?Z:Z.filter((E)=>E.type==="text").map((E)=>E.text).join(`
|
|
591
|
+
`),s0=[n,$.completionRequirements?.trim()].filter(Boolean).join(`
|
|
592
|
+
`),t0=n.trim()?[n]:[],w0=[Q.runtimeOptions.appendSystemPrompt?.trim(),$.completionRequirements?.trim(),...t0].filter((E)=>Boolean(E)),q0=y0(n),e0=!u,K0=o2($.messages);if(K0)g.add("Task");let NQ=()=>A0(w0),AZ=()=>{let E="The exactly-once Task delegation has already been started. Do not call Task again; return the final answer after its result.";return{success:!1,llmContent:E,error:{type:"validation_error",message:E},metadata:{summary:"Blocked duplicate exactly-once Task delegation"}}},vQ=(E,P)=>{if(E!=="Task"||!NQ())return;if(K0)return AZ();K0=!0;return},yZ=(E)=>{if(E==="Task"&&NQ())K0=!1},PQ=async(E,P,j0)=>Q.toolExecutor.execute(E,P,j0),QQ=UQ({budget:Q.currentModelMaxContextTokens,isSubagent:y}),AQ=new FQ,SZ={},ZQ=async(E)=>{for(let P of E){if(!L.getHistory().some((C)=>{let J0=C.metadata;return J0!==null&&typeof J0==="object"&&!Array.isArray(J0)&&J0.inboxMessageId===P.id})){let C=await a(Q,$,P.content,Y,{inboxMessageId:P.id});if(!C)throw Error(`Failed to persist steering message before applying it: ${P.id}`);Y=C,L.appendUser({role:"user",content:P.content,metadata:{inboxMessageId:P.id}})}let $0=typeof P.content==="string"?P.content:P.content.filter((C)=>C.type==="text").map((C)=>C.text).join(`
|
|
593
|
+
`);if($0.trim())n=[n,$0].join(`
|
|
594
|
+
`),t0.push($0),s0=[n,$.completionRequirements?.trim()].filter(Boolean).join(`
|
|
595
|
+
`),w0=[Q.runtimeOptions.appendSystemPrompt?.trim(),$.completionRequirements?.trim(),...t0].filter((C)=>Boolean(C)),q0=q0||y0($0)}return{messageIds:E.map((P)=>P.id),count:E.length,recovered:E.filter((P)=>P.recovered).length}};try{while(!0){if(J?.signal?.aborted)return D(W,V.length,J.signal);let E=await J?.turnSteering?.drain()??[];if(E.length>0)yield{kind:"steering_applied",...await ZQ(E),delivery:e0?"current_turn":"next_turn"},e0=!0;else if(!e0)return{success:!0,finalMessage:"",metadata:{turnsCount:0,toolCallsCount:0,duration:Date.now()-G}};if(L.writeback(),(yield*PZ(Q,$,W,i0,J?.signal,IQ,n,SZ))!=="none")L.replaceHistory($.messages);if(W++,AQ.reset(),yield{kind:"turn_start",turn:W,maxTurns:R},J?.signal?.aborted)return D(W-1,V.length,J.signal);if(bZ(W)&&W>1){let q=LZ(W,x.totalFailures);L.appendControl("user",{role:"user",content:`
|
|
596
|
+
|
|
597
|
+
<system-reminder>
|
|
598
|
+
${q}
|
|
599
|
+
</system-reminder>`})}let j0=J?.stream!==!1,$0=K0&&A0(w0)?k.filter((q)=>q.name!=="Task"):k,C=B0;B0=void 0;let J0=C?$0.filter((q)=>q.name===C):$0,yQ=C?{toolChoice:{type:"tool",toolName:C}}:void 0,H,t;try{if(j0)t=new g0(Q.toolExecutor,{sessionId:$.sessionId,userId:$.userId||"default",modelId:Q.config.currentModelId,workspaceRoot:$.workspaceRoot||m(),worktreeIsolationRequired:q0,worktreeActive:g.has("EnterWorktree")&&!g.has("ExitWorktree"),signal:J?.signal,confirmationHandler:$.confirmationHandler,permissionMode:$.permissionMode,toolRegistry:O,deferredToolManager:O.deferredToolManager},Q.toolExecutor.getRegistry(),Q.executionEngine?.getContextManager(),$.sessionId,Y,$.subagentInfo),t.setAdmissionPolicy(vQ),t.setAdmissionRollback(yZ),t.setExecutionPolicy(PQ),H=yield*J7(Q,L.toLLMMessages(),J0,J?.signal,yQ,t);else H=await Q.chatService.chat(L.toLLMMessages(),J0,J?.signal,yQ)}catch(q){if(Q7(q)){f.warn("[Loop] 检测到 prompt_too_long 错误,尝试反应式压缩");let K=Q.chatService.getConfig(),j=await AQ.tryReactiveCompact($.messages,{modelName:K.model,modelProvider:K.provider,maxContextTokens:K.maxContextTokens??0,apiKey:K.apiKey,baseURL:K.baseUrl,signal:J?.signal,activeTask:n,workspaceRoot:$.workspaceRoot||m(),sessionId:$.sessionId});if(j.success){if(j.usage)yield{kind:"token_usage",usage:c0(j.usage,K.maxContextTokens??0)};$.messages=j.messages,L.replaceHistory($.messages),B0=C,f.info("[Loop] 反应式压缩成功,重试 LLM 调用"),W--;continue}}throw q}if(IQ=Date.now(),H.usage){if(H.usage.totalTokens)r+=H.usage.totalTokens;i0=H.usage.promptTokens,yield{kind:"token_usage",usage:c0(H.usage,Q.currentModelMaxContextTokens)}}let UZ=H.usage?.completionTokens??0;if(QQ=MQ(QQ,UZ,X0>0),J?.signal?.aborted)return D(W-1,V.length,J.signal);if(!j0||!!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 $Q=VQ(H.finishReason,X0,QQ);if($Q.action==="recover"){X0++,f.warn(`[Loop] Max output tokens hit (recovery ${X0}/3)`);let q={role:"assistant",content:H.content||"",reasoningContent:H.reasoningContent,tool_calls:H.toolCalls};L.appendToHistory(q);let K=await d(Q,$,H.content||"",Y);if(K)Y=K;let j={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."};L.appendToHistory(j);let B=await a(Q,$,j.content,Y);if(B)Y=B;continue}if($Q.action==="truncated"||$Q.action==="budget_stop"){L.appendAssistant({role:"assistant",content:H.content||"",reasoningContent:H.reasoningContent,tool_calls:H.toolCalls});let q=await d(Q,$,H.content||"",Y);if(q)Y=q;return{success:!0,finalMessage:H.content,metadata:{turnsCount:W,toolCallsCount:V.length,duration:Date.now()-G,tokensUsed:r,outputTruncated:!0}}}if(H.finishReason!=="length")X0=0;if(!H.toolCalls||H.toolCalls.length===0){let q=await J?.turnSteering?.drain()??[];if(q.length>0){L.appendAssistant({role:"assistant",content:H.content||"",reasoningContent:H.reasoningContent});let _=await d(Q,$,H.content||"",Y);if(_)Y=_;yield{kind:"steering_applied",...await ZQ(q),delivery:"current_turn"};continue}if(H.content&&_Z(N,H.content)){L.appendAssistant({role:"assistant",content:H.content||"",reasoningContent:H.reasoningContent}),L.appendControl("user",{role:"user",content:`
|
|
600
|
+
|
|
601
|
+
<system-reminder>
|
|
602
|
+
${wZ()}
|
|
603
|
+
</system-reminder>`});continue}let K=YQ(H.content,n0,!1);if(K.action==="retry"){n0++,L.appendAssistant({role:"assistant",content:H.content||"",reasoningContent:H.reasoningContent});let _=await d(Q,$,H.content||"",Y);if(_)Y=_;let c={role:"user",content:K.prompt};L.appendControl("user",c);let p=await a(Q,$,c.content,Y);if(p)Y=p;continue}n0=0;let j=xQ(w0,g,l0);if(j.action==="retry"){l0++,B0="Task",L.appendAssistant({role:"assistant",content:H.content||"",reasoningContent:H.reasoningContent});let _=await d(Q,$,H.content||"",Y);if(_)Y=_;let c={role:"user",content:j.prompt};L.appendControl("user",c);let p=await a(Q,$,c.content,Y);if(p)Y=p;continue}if(j.action==="fail"){L.appendAssistant({role:"assistant",content:H.content||"",reasoningContent:H.reasoningContent});let _=await d(Q,$,H.content||"",Y);if(_)Y=_;return{success:!1,error:{type:"delegation_protocol_failed",message:j.message},metadata:{turnsCount:W,toolCallsCount:V.length,duration:Date.now()-G,tokensUsed:r}}}l0=0;let B=CQ(n,g,a0);if(B.action==="retry"){a0++,L.appendAssistant({role:"assistant",content:H.content||"",reasoningContent:H.reasoningContent});let _=await d(Q,$,H.content||"",Y);if(_)Y=_;let c={role:"user",content:B.prompt};L.appendControl("user",c);let p=await a(Q,$,c.content,Y);if(p)Y=p;continue}if(B.action==="fail"){L.appendAssistant({role:"assistant",content:H.content||"",reasoningContent:H.reasoningContent});let _=await d(Q,$,H.content||"",Y);if(_)Y=_;return{success:!1,error:{type:"worktree_protocol_failed",message:B.message},metadata:{turnsCount:W,toolCallsCount:V.length,duration:Date.now()-G,tokensUsed:r}}}a0=0;let S=HQ(s0,o0,r0);if(S.action==="retry"){r0++,B0="Bash",L.appendAssistant({role:"assistant",content:H.content||"",reasoningContent:H.reasoningContent});let _=await d(Q,$,H.content||"",Y);if(_)Y=_;let c={role:"user",content:S.prompt};L.appendControl("user",c);let p=await a(Q,$,c.content,Y);if(p)Y=p;continue}if(S.action==="fail"){L.appendAssistant({role:"assistant",content:H.content||"",reasoningContent:H.reasoningContent});let _=await d(Q,$,H.content||"",Y);if(_)Y=_;return{success:!1,error:{type:"verification_failed",message:S.message},metadata:{turnsCount:W,toolCallsCount:V.length,duration:Date.now()-G,tokensUsed:r}}}r0=0;let A=await XQ({sessionId:$.sessionId,permissionMode:$.permissionMode,reason:H.content,abortSignal:J?.signal});if(A.action==="continue"){L.appendAssistant({role:"assistant",content:H.content||"",reasoningContent:H.reasoningContent});let _=await d(Q,$,H.content||"",Y);if(_)Y=_;let p={role:"user",content:A.reason?`
|
|
604
|
+
|
|
605
|
+
<system-reminder>
|
|
606
|
+
${A.reason}
|
|
607
|
+
</system-reminder>`:`
|
|
608
|
+
|
|
609
|
+
<system-reminder>
|
|
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>`};L.appendControl("user",p);let D0=await a(Q,$,p.content,Y);if(D0)Y=D0;continue}let e=await J?.turnSteering?.drainOrSeal();if(e&&e.messages.length>0){L.appendAssistant({role:"assistant",content:H.content||"",reasoningContent:H.reasoningContent});let _=await d(Q,$,H.content||"",Y);if(_)Y=_;yield{kind:"steering_applied",...await ZQ(e.messages),delivery:"current_turn"};continue}L.appendAssistant({role:"assistant",content:H.content||"",reasoningContent:H.reasoningContent});let v=await d(Q,$,H.content||"",Y);if(v)Y=v;return{success:!0,finalMessage:H.content,metadata:{turnsCount:W,toolCallsCount:V.length,duration:Date.now()-G,tokensUsed:r,toolSuccessRate:V.length>0?V.filter((_)=>_.success).length/V.length:void 0,totalToolFailures:x.totalFailures||void 0}}}L.appendAssistant({role:"assistant",content:H.content||"",reasoningContent:H.reasoningContent,tool_calls:H.toolCalls});{let q=await d(Q,$,H.content||"",Y);if(q)Y=q}if(J?.signal?.aborted)return D(W,V.length,J.signal);let JQ=H.toolCalls.filter((q)=>q.type==="function"),E0;if(t?.hasTools()){f.debug(`[Loop] 使用 StreamingToolExecutor 收集 ${JQ.length} 个工具结果`),E0=[];for(let q of t.getQueuedToolCalls()){let j=O.get(q.function.name)?.kind;yield{kind:"tool_start",toolCall:q,toolKind:j}}for await(let q of t.getRemainingResults())E0.push(q)}else{let q=new Map;for(let j of JQ){let B=EQ(j.function.arguments),S=B===null?void 0:vQ(j.function.name,B);if(S){q.set(j.id,S);continue}let e=O.get(j.function.name)?.kind;yield{kind:"tool_start",toolCall:j,toolKind:e}}let K=async(j)=>{try{let B=q.get(j.id);if(B)return{toolCall:j,result:B,toolUseUuid:null};let S=EQ(j.function.arguments);if(S===null)return{toolCall:j,result:{success:!1,llmContent:"",error:{type:"validation_error",message:`Invalid JSON object in tool arguments. Raw: ${j.function.arguments.slice(0,200)}`},metadata:void 0},toolUseUuid:null};if(j.function.name==="Task"&&(typeof S.subagent_session_id!=="string"||S.subagent_session_id.length===0))S.subagent_session_id=NZ("agent");let A=null;if(A=await KQ(Q,$,j.function.name,S,Y),j.function.name==="ExitWorktree"&&g.has("EnterWorktree")&&!g.has("ExitWorktree")&&HQ(s0,o0,0).action!=="none"){let _="Run the requested verification before ExitWorktree. The worktree remains active so Bash can run in isolation.";return{toolCall:j,result:{success:!1,llmContent:_,error:{type:"validation_error",message:_},metadata:{summary:"Blocked ExitWorktree until verification succeeds"}},toolUseUuid:A}}let v=await PQ(j.function.name,S,{sessionId:$.sessionId,userId:$.userId||"default",modelId:Q.config.currentModelId,workspaceRoot:$.workspaceRoot||m(),worktreeIsolationRequired:q0,worktreeActive:g.has("EnterWorktree")&&!g.has("ExitWorktree"),signal:J?.signal,confirmationHandler:$.confirmationHandler,permissionMode:$.permissionMode,toolRegistry:O,deferredToolManager:O.deferredToolManager});return{toolCall:j,result:v,toolUseUuid:A}}catch(B){return f.error(`Tool execution failed for ${j.function.name}:`,B),{toolCall:j,result:{success:!1,llmContent:"",error:{type:"execution_error",message:B instanceof Error?B.message:"Unknown error"},metadata:void 0},toolUseUuid:null,error:B instanceof Error?B:Error("Unknown error")}}};E0=await Promise.all(JQ.map(K))}let MZ=new LQ;for(let{toolCall:q,result:K,toolUseUuid:j}of E0){let B=q;if(V.push(K),K.metadata?.abortedBeforeLaunch){let v=K.error?.message??"任务已被用户中止";if(j){let _=await S0(Q,$,j,B.function.name,null,j,v);if(_)Y=_}return L.appendToolResult({role:"tool",tool_call_id:B.id,name:B.function.name,content:`Error: ${v}`}),D(W,V.length,J?.signal)}yield{kind:"tool_result",toolCall:B,result:K};{let v=K.metadata&&typeof K.metadata==="object"?K.metadata:void 0,c=((I0)=>I0==="running"||I0==="completed"||I0==="failed"||I0==="cancelled")(v?.subagentStatus)?v.subagentStatus:"completed",p=v&&typeof v.subagentSessionId==="string"?{subagentSessionId:v.subagentSessionId,subagentType:typeof v.subagentType==="string"?v.subagentType:B.function.name,subagentStatus:c,subagentSummary:typeof v.subagentSummary==="string"?v.subagentSummary:void 0,subagentResumedFrom:typeof v.subagentResumedFrom==="string"?v.subagentResumedFrom:void 0,subagentRootId:typeof v.subagentRootId==="string"?v.subagentRootId:void 0,subagentResumeDepth:typeof v.subagentResumeDepth==="number"?v.subagentResumeDepth:void 0}:void 0,D0=await S0(Q,$,j??B.id,B.function.name,K.success?a2(K.llmContent):null,j,K.success?void 0:K.error?.message,p);if(D0)Y=D0}let S=await jQ(B,K,Q,$);if(S)yield S;if(K.success){if(jZ(x,B.function.name),B.function.name==="EnterWorktree"&&K.metadata?.workspaceTransition==="enter")g.add("EnterWorktree"),g.delete("ExitWorktree");else if(B.function.name==="ExitWorktree"&&K.metadata?.workspaceTransition==="exit"&&g.has("EnterWorktree"))g.add("ExitWorktree");else if(!["EnterWorktree","ExitWorktree"].includes(B.function.name))g.add(B.function.name);if(B.function.name==="Task"&&K.metadata?.isolation==="worktree")g.add("TaskWorktree");TQ(o0,B.function.name,K)}else DZ(x,B.function.name);let A=K.success?K.llmContent||"":e2(B.function.name,K.error);if(!K.success){let v=FZ(x,B.function.name);if(v&&typeof A==="string")A=`${A}
|
|
612
|
+
|
|
613
|
+
${v}`}if(typeof A==="object"&&A!==null)A=JSON.stringify(A,null,2);if(typeof A==="string")A=QZ(A,B.function.name,{messageBudget:MZ});let e=typeof A==="string"?A:JSON.stringify(A);if(L.appendToolResult({role:"tool",tool_call_id:B.id,name:B.function.name,content:e,...B.function.name==="Task"?{metadata:{toolCallId:B.id,toolName:B.function.name,error:K.success?null:K.error?.message??null}}:{}}),K.metadata?.shouldExitLoop){let v=typeof K.llmContent==="string"?K.llmContent:"循环已退出";return{success:K.success,finalMessage:v,metadata:{turnsCount:W,toolCallsCount:V.length,duration:Date.now()-G,shouldExitLoop:!0,targetMode:K.metadata?.targetMode,planContent:typeof K.metadata?.planContent==="string"?K.metadata.planContent:void 0}}}}if(J?.signal?.aborted)return D(W,V.length,J.signal);let zQ=W>=m0,fZ=W>=R&&(u0||!l||y);if(zQ||fZ){let q=zQ?m0:R;if(f.info(`Warning: 达到轮次上限 ${q} 轮`),J?.onTurnLimitReached){let K=await J.onTurnLimitReached({turnsCount:W});if(K?.continue){L.writeback();try{let j=Q.chatService.getConfig(),B=await Y0.compact($.messages,{trigger:"auto",modelName:j.model,modelProvider:j.provider,maxContextTokens:j.maxContextTokens??0,apiKey:j.apiKey,baseURL:j.baseUrl,actualPreTokens:i0,signal:J?.signal,activeTask:n,workspaceRoot:$.workspaceRoot||m(),sessionId:$.sessionId});if(B.usage)yield{kind:"token_usage",usage:c0(B.usage,j.maxContextTokens??0)};$.messages=B.compactedMessages,L.replaceHistory($.messages);let S={role:"user",content:`This session is being continued from a previous conversation. The conversation is summarized above.
|
|
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.`};L.appendToHistory(S),await U0(Q,$,B.summary,{trigger:"auto",preTokens:B.preTokens,postTokens:B.postTokens,filesIncluded:B.filesIncluded})}catch(j){f.error("[Loop] 压缩失败,使用降级策略:",j);let S=L.getHistory().slice(-80);L.replaceHistory(S)}W=0;continue}return{success:!0,finalMessage:K?.reason||"已达到对话轮次上限,用户选择停止",metadata:{turnsCount:W,toolCallsCount:V.length,duration:Date.now()-G,tokensUsed:r}}}return{success:!1,error:{type:"max_turns_exceeded",message:y?`子代理已达到轮次上限 (${q} 轮)。`:`已达到${zQ?"安全":"显式"}轮次上限 (${q} 轮)。`},metadata:{turnsCount:W,toolCallsCount:V.length,duration:Date.now()-G,tokensUsed:r}}}}}finally{if(J?.transientInput==="goal_continuation")L.removeMessages((E)=>{let P=E.metadata;return P!==null&&typeof P==="object"&&!Array.isArray(P)&&P.transientGoalContinuation===!0});L.writeback()}}catch(O){if(G0(O))return D(W,V.length,J?.signal);let F=s2(O);return f.error(`API 调用失败: ${F}`),{success:!1,error:{type:"api_error",message:F,details:O},metadata:{turnsCount:W,toolCallsCount:V.length,duration:Date.now()-G}}}finally{if(X)$.messages.push({role:"system",content:BQ}),await pQ(Q,$,Y)}}export{DQ as Sa,zZ as Ta,YZ as Ua,d0 as Va,x2 as Wa,VQ as Xa,YQ as Ya,TQ as Za,XQ as _a,N0 as $a,v0 as ab,hZ as bb,a as cb,d as db,KQ as eb,S0 as fb,U0 as gb,dQ as hb,gQ as ib,mQ as jb,jQ as kb,b0 as lb,Y0 as mb,g0 as nb,PZ as ob,G7 as pb};
|