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
package/dist/chunk-m0ded6ky.js
DELETED
|
@@ -1,615 +0,0 @@
|
|
|
1
|
-
import{Fb as f0}from"./chunk-b922cq7k.js";import{Mb as MZ}from"./chunk-7bqkkjxf.js";import{Sb as c,Tb as SZ}from"./chunk-kjc2aqww.js";import{Wb as PZ,Xb as H0,Yb as AZ,Zb as ZZ}from"./chunk-d7nrqg5b.js";import{bc as i}from"./chunk-eyypmc9m.js";import{ec as sQ}from"./chunk-zsyff0ky.js";function M0(Q){return Q.role==="system"&&Array.isArray(Q.content)}class P0{systemMessages;_history;_pending=[];context;constructor(Q,$){this.context=Q;let Z=Q.messages.find(M0);if(Z)this.systemMessages=[Z];else if($)this.systemMessages=[{role:"system",content:[{type:"text",text:$,providerOptions:{anthropic:{cacheControl:{type:"ephemeral"}}}}]}];else this.systemMessages=[];this._history=Q.messages.filter((J)=>!M0(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,$){if(Q==="system")throw Error("Cannot append system control message via appendControl. Use constructor for root system prompt.");this._pending.push($)}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(($)=>!M0($))}removeMessages(Q){this._history=this._history.filter(($)=>!Q($)),this._pending=this._pending.filter(($)=>!Q($))}writeback(){this.commitPending(),this.context.messages=this._history}get hasSystemPrompt(){return this.systemMessages.length>0}}async function pZ(Q,$){let Z;while(!(Z=await Q.next()).done)if($)await $(Z.value);return Z.value}function TQ(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 kQ(Q){return{budget:Q.budget,usage:0,consecutiveContinuations:0,lastOutputDelta:0,isSubagent:Q.isSubagent??!1}}function RQ(Q,$,Z){return{...Q,usage:Q.usage+$,lastOutputDelta:$,consecutiveContinuations:Z?Q.consecutiveContinuations+1:0}}var BQ=i("Agent"),gZ=3;function jQ(Q,$,Z){if(Q!=="length")return{action:"none"};if($>=gZ)return{action:"truncated"};if(TQ(Z)==="stop")return BQ.info("[Loop] Token budget: diminishing returns detected, skipping recovery"),{action:"budget_stop"};return{action:"recover"}}var dZ=[/:\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],mZ=/```[\s\S]{50,}```/,CQ="请执行你提到的操作,不要只是描述。使用 Edit/Write/Bash 工具来实际修改文件。",cZ=2;function DQ(Q,$,Z=!0){if(!Q||$>=cZ)return{action:"none"};if(!Z&&mZ.test(Q))return{action:"retry",prompt:CQ};let J=Q.slice(-200),G=J.match(/```/g);if(G&&G.length%2!==0)return{action:"none"};if(dZ.some((z)=>z.test(J)))return{action:"retry",prompt:CQ};return{action:"none"}}var uZ=[/\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}(?:测试|单测|集成测试|检查|构建)/],iZ=/(?:^|\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,pQ={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},nZ={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},lZ="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.",rZ="Required verification did not run successfully before the retry limit.",aZ=3;function KQ(Q){return iZ.test(Q)}function dQ(Q,$,Z){if(!Z.success)return;if(["Edit","Write","NotebookEdit"].includes($)){Q.clear();return}if($==="Bash"&&typeof Z.metadata?.command==="string"&&Z.metadata.exit_code===0&&KQ(Z.metadata.command)){Q.add(Z.metadata.command);return}if(!["Task","TaskOutput"].includes($))return;let J=Z.metadata?.verificationCommands;if(!Array.isArray(J))return;for(let G of J)if(typeof G==="string"&&KQ(G))Q.add(G)}function FQ(Q,$,Z){if(!Q||!uZ.some((Y)=>Y.test(Q)))return{action:"none"};let J=Object.keys(pQ).filter((Y)=>pQ[Y].test(Q)),G=[...$],W=J.filter((Y)=>!G.some((H)=>nZ[Y].test(H)));if(J.length>0?W.length===0:G.some(KQ))return{action:"none"};if(Z>=aZ)return{action:"fail",message:rZ};let V=J.length>1&&W.length>0?` Missing successful verification categories: ${W.join(", ")}.`:"";return{action:"retry",prompt:`${lZ}${V}`}}var oZ=[/\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|子代理|子智能体)/],sZ=[/\b(?:do not|don't|never)\s+(?:delegate|call|use|invoke)\b/i,/(?:不要|禁止|无需)(?:委派|调用|使用).{0,20}(?:Task|子代理|子智能体)?/],tZ=[/\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|子代理)/],eZ=[/\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 Q2(Q){if(typeof Q!=="string")return;if(eZ.some(($)=>$.test(Q)))return"multiple-allowed";return tZ.some(($)=>$.test(Q))?"required":void 0}function x0(Q){for(let $ of Q){let Z=Q2($);if(Z!==void 0)return Z==="required"}return!1}var Z2="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.",$2="Required delegation did not complete before the retry limit.",J2=3;function mQ(Q,$,Z){let J=(typeof Q==="string"?[Q]:Q??[]).map((z)=>z.trim()).filter(Boolean),G=x0(J),W=!1;if(!G)for(let z of J){if(sZ.some((V)=>V.test(z)))break;if(oZ.some((V)=>V.test(z))){W=!0;break}}if(J.length===0||!G&&!W||$.has("Task"))return{action:"none"};if(Z>=J2)return{action:"fail",message:$2};return{action:"retry",prompt:Z2}}var G2=[/\b(?:use|create|enter|start|work\s+(?:in|inside))\b.{0,60}\bworktree\b/i,/(?:使用|创建|进入).{0,30}(?:worktree|工作树)/i],W2=[/\b(?:exit|leave)\b.{0,40}\bworktree\b/i,/\bworktree\b.{0,60}\b(?:action\s+)?(?:keep|remove)\b/i,/(?:退出|离开).{0,30}(?:worktree|工作树)/i],z2=[/\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 cQ(Q){return z2.reduce(($,Z)=>$.replace(Z," "),Q)}function h0(Q){if(typeof Q!=="string")return!1;let $=cQ(Q);return G2.some((Z)=>Z.test($))}var V2="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.",Y2="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.",X2="Required worktree lifecycle did not complete before the retry limit.",H2=3;function uQ(Q,$,Z){if(!Q)return{action:"none"};let J=cQ(Q);if(!h0(J))return{action:"none"};let G=W2.some((z)=>z.test(J));if($.has("TaskWorktree"))return{action:"none"};let W=!$.has("EnterWorktree")?"EnterWorktree":G&&!$.has("ExitWorktree")?"ExitWorktree":void 0;if(!W)return{action:"none"};if(Z>=H2)return{action:"fail",message:X2};return{action:"retry",tool:W,prompt:W==="EnterWorktree"?V2:Y2}}var gQ=30000;async function OQ(Q){try{let Z=f0.getInstance().executeStopHooks({projectDir:c(),sessionId:Q.sessionId,permissionMode:Q.permissionMode,reason:Q.reason,abortSignal:Q.abortSignal}),J,G=new Promise((W)=>{J=setTimeout(()=>W("timeout"),gQ)});try{let W=await Promise.race([Z,G]);if(W==="timeout")return BQ.warn(`[Loop] Stop hook 超时 (${gQ}ms),按 shouldStop: true 处理`),{action:"stop"};let z=W;if(!z.shouldStop)return{action:"continue",reason:z.continueReason};return{action:"stop"}}finally{clearTimeout(J)}}catch($){return BQ.warn("[Loop] Stop hook execution failed:",$),{action:"stop"}}}var K0=i("Agent"),LQ=`<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 j0(Q){return Q.executionEngine?.getContextManager()}async function o(Q,$,Z,J=null,G){try{let W=j0(Q),z=typeof Z==="string"?Z.trim()!=="":Z.some((V)=>V.type==="text"?V.text.trim()!=="":!0);if(W&&$.sessionId&&z)return await W.saveMessage($.sessionId,"user",Z,J,G,$.subagentInfo)}catch(W){K0.warn("[Loop] 保存用户消息失败:",W)}return null}async function d(Q,$,Z,J){try{let G=j0(Q);if(G&&$.sessionId&&Z.trim())return await G.saveMessage($.sessionId,"assistant",Z,J,void 0,$.subagentInfo)}catch(G){K0.warn("[Loop] 保存助手消息失败:",G)}return null}async function iQ(Q,$,Z){try{let J=j0(Q);if(J&&$.sessionId)return await J.saveMessage($.sessionId,"system",LQ,Z,void 0,$.subagentInfo)}catch(J){K0.warn("[Loop] 保存中断边界失败:",J)}return null}async function bQ(Q,$,Z,J,G){try{let W=j0(Q);if(W&&$.sessionId)return await W.saveToolUse($.sessionId,Z,J,G,$.subagentInfo)}catch(W){K0.warn("[Loop] 保存工具调用失败:",W)}return null}async function T0(Q,$,Z,J,G,W,z,V){try{let Y=j0(Q);if(Y&&$.sessionId)return await Y.saveToolResult($.sessionId,Z,J,G,W,z,$.subagentInfo,V)}catch(Y){K0.warn("[Loop] 保存工具结果失败:",Y)}return null}async function k0(Q,$,Z,J){try{let G=j0(Q);if(G&&$.sessionId)return await G.saveCompaction($.sessionId,Z,J,null)}catch(G){K0.warn("[Loop] 保存压缩数据失败:",G)}return null}function nQ(Q,$){if(!["TaskCreate","TaskUpdate","TaskList"].includes(Q.function.name)||!$.success||!$.llmContent&&!$.metadata)return null;let Z=typeof $.llmContent==="object"?$.llmContent:{};return{kind:"task_update",tasks:$.metadata?.tasks||Z.tasks||[]}}function lQ(Q,$,Z){if(Q.function.name!=="Skill"||!$.success||!$.metadata)return;let J=$.metadata;if(J.skillName)Z.onSkillActivated?.({skillName:J.skillName,allowedTools:J.allowedTools,basePath:J.basePath||""})}function rQ(Q){let $=Q.metadata;if(!$)return;return $.modelId?.toString().trim()||$.model?.toString().trim()||void 0||void 0}function B2(Q,$,Z){if(!["EnterWorktree","ExitWorktree"].includes(Q.function.name)||!$.success)return;let J=$.metadata,G=J?.workspaceRoot;if(!["enter","exit"].includes(String(J?.workspaceTransition))||typeof G!=="string"||G.trim()==="")return;return Z.workspaceRoot=G,Z.worktreeActive=J?.workspaceTransition==="enter",G}function K2(Q,$){if(Q.function.name!=="Task")return null;let Z=$.metadata;if(!Z?.subagentSessionId)return null;let J=Z.subagentSessionId,G=Z.subagentType||"Task",W=Z.subagentStatus,z=typeof Z.subagentResumedFrom==="string"?Z.subagentResumedFrom:void 0,V=typeof Z.subagentRootId==="string"?Z.subagentRootId:void 0,Y=typeof Z.subagentResumeDepth==="number"?Z.subagentResumeDepth:void 0;if(W==="completed"||W==="failed"||W==="cancelled")return{kind:"subagent_completed",sessionId:J,success:W==="completed",summary:Z.subagentSummary,resumedFrom:z,rootAgentId:V,resumeDepth:Y};if(W==="running"){let H="";try{H=JSON.parse(Q.function.arguments).prompt||""}catch{}return{kind:"subagent_spawned",sessionId:J,type:G,prompt:H,resumedFrom:z,rootAgentId:V,resumeDepth:Y}}return null}async function _Q(Q,$,Z,J){let G=nQ(Q,$),W=K2(Q,$);lQ(Q,$,Z);let z=rQ($);if(z)await Z.onModelSwitch?.(z);if(J)B2(Q,$,J);return W||G}import{promises as N2}from"node:fs";import E2 from"node:path";import{nanoid as $0}from"nanoid";import*as h from"node:fs/promises";import*as z0 from"node:path";var aQ={enabled:!0,maxIndexLines:200};var j2="memory",oQ="MEMORY.md";class qQ{memoryDir;config;initialized=!1;constructor(Q,$,Z){if(Z)this.memoryDir=Z;else{let J=sQ(Q);this.memoryDir=z0.join(J,j2)}this.config={...aQ,...$}}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,oQ);try{let $=await h.readFile(Q,"utf-8");if(!$.trim())return null;let Z=$.split(`
|
|
4
|
-
`),G=Z.slice(0,this.config.maxIndexLines).join(`
|
|
5
|
-
`).trim();if(Z.length>this.config.maxIndexLines)return G+`
|
|
6
|
-
|
|
7
|
-
<!-- ${Z.length-this.config.maxIndexLines} more lines in MEMORY.md, use MemoryRead to access -->`;return G||null}catch($){if($ instanceof Error&&"code"in $&&$.code==="ENOENT")return null;throw $}}async readTopic(Q){await this.initialize();let $=this.resolveTopicPath(Q);try{return await h.readFile($,"utf-8")||null}catch(Z){if(Z instanceof Error&&"code"in Z&&Z.code==="ENOENT")return null;throw Z}}async writeTopic(Q,$,Z="append"){await this.initialize();let J=this.resolveTopicPath(Q);if(Z==="append"){let G="";try{G=await h.readFile(J,"utf-8")}catch{}let W=G&&!G.endsWith(`
|
|
8
|
-
`)?`
|
|
9
|
-
`:"";await h.writeFile(J,G+W+$,"utf-8")}else await h.writeFile(J,$,"utf-8")}async updateIndex(Q,$="overwrite"){await this.initialize();let Z=z0.join(this.memoryDir,oQ);if($==="append"){let J="";try{J=await h.readFile(Z,"utf-8")}catch{}let G=J&&!J.endsWith(`
|
|
10
|
-
`)?`
|
|
11
|
-
`:"";await h.writeFile(Z,J+G+Q,"utf-8")}else await h.writeFile(Z,Q,"utf-8")}async listTopics(){await this.initialize();try{let Q=await h.readdir(this.memoryDir,{withFileTypes:!0}),$=[];for(let Z of Q){if(!Z.isFile()||!Z.name.endsWith(".md"))continue;let J=z0.join(this.memoryDir,Z.name),G=await h.stat(J);$.push({name:Z.name.replace(/\.md$/,""),size:G.size,lastModified:G.mtime})}return $.sort((Z,J)=>J.lastModified.getTime()-Z.lastModified.getTime())}catch{return[]}}async deleteTopic(Q){let $=this.resolveTopicPath(Q);try{return await h.unlink($),!0}catch{return!1}}async clearAll(){let Q=await this.listTopics(),$=0;for(let Z of Q){let J=z0.join(this.memoryDir,`${Z.name}.md`);try{await h.unlink(J),$++}catch{}}return $}getMemoryDir(){return this.memoryDir}resolveTopicPath(Q){let $=Q.replace(/[/\\:*?"<>|]/g,"-"),Z=$.endsWith(".md")?$:`${$}.md`,J=z0.join(this.memoryDir,Z);if(!J.startsWith(this.memoryDir))throw Error(`Invalid topic name: ${Q}`);return J}}var D2=[{pattern:/(?:记住|remember|note|备注)[::](.+)/i,topic:"preferences"},{pattern:/(?:convention|约定|规范)[::](.+)/i,topic:"conventions"},{pattern:/(?:lesson|教训|踩坑)[::](.+)/i,topic:"lessons"}],F2=/(?:fix|修复|解决|resolved)[::]\s*(.+?)(?:\n|$)/i,O2=/(?:Error|FAIL|错误)[::]\s*(.+?)(?:\n|$)/i;function L2(Q){let $=new Map;for(let Z of Q){if(!Z.content||typeof Z.content!=="string")continue;let J=Z.content;if(Z.role==="user")for(let{pattern:G,topic:W}of D2){let z=J.match(G);if(z?.[1]){let V=$.get(W)??[];V.push(z[1].trim()),$.set(W,V)}}if(Z.role==="assistant"){let G=J.match(F2);if(G?.[1]&&G[1].length>20&&G[1].length<200){let W=$.get("debugging")??[];W.push(G[1].trim()),$.set("debugging",W)}}if(Z.role==="tool"&&Z.content?.includes("Error")){let G=J.match(O2);if(G?.[1]&&G[1].length>10){let W=$.get("debugging")??[];if(W.length<5)W.push(`Tool error pattern: ${G[1].trim().slice(0,150)}`),$.set("debugging",W)}}}return $}async function tQ(Q){let $=L2(Q);if($.size===0)return{extracted:0,topics:[]};try{let Z=new qQ(c());await Z.initialize();let J=[],G=0;for(let[W,z]of $){if(z.length===0)continue;let V=new Date().toISOString().split("T")[0],Y=z.map((H)=>`- [${V}] ${H}`).join(`
|
|
12
|
-
`);await Z.writeTopic(W,Y+`
|
|
13
|
-
`,"append"),J.push(W),G+=z.length}return{extracted:G,topics:J}}catch{return{extracted:0,topics:[]}}}import{promises as R0}from"node:fs";import*as Y0 from"fs/promises";import*as A from"path";var eQ=[".git",".claude","node_modules",".env",".env.local",".env.production",".env.development",".env.test"];class V0 extends Error{code;constructor(Q,$){super(Q);this.code=$;this.name="PathSecurityError"}}class X0{static normalize(Q,$){let Z=A.isAbsolute(Q)?Q:A.resolve($,Q),J=A.normalize(Z),G=A.normalize($);if(!this.isWithinWorkspace(J,G))throw new V0(`Path outside workspace: ${Q} (resolved to ${J}, workspace: ${G})`,"PATH_OUTSIDE_WORKSPACE");return J}static checkRestricted(Q){let $=Q.split(A.sep);for(let Z of eQ)if($.includes(Z))throw new V0(`Access denied: "${Z}" is a protected directory`,"RESTRICTED_PATH")}static checkTraversal(Q){if(Q.includes(".."))throw new V0(`Path traversal not allowed: ${Q}`,"PATH_TRAVERSAL")}static async validatePath(Q,$){this.checkTraversal(Q);let Z=this.normalize(Q,$);this.checkRestricted(Z);try{await Y0.access(Z)}catch(J){throw new V0(`Path not found: ${Q}`,"PATH_NOT_FOUND")}return Z}static async resolveSymlink(Q,$){try{let Z=await Y0.realpath(Q),J=await Y0.realpath($);if(!this.isWithinWorkspace(Z,J))throw new V0(`Symlink points outside workspace: ${Q} -> ${Z}`,"SYMLINK_OUTSIDE_WORKSPACE");return Z}catch(Z){if(Z instanceof V0)throw Z;return Q}}static getRelativePath(Q,$){return A.relative($,Q)}static isWithinWorkspace(Q,$){let Z=A.resolve(Q),J=A.resolve($),G=A.relative(J,Z);return G===""||G!==".."&&!G.startsWith(`..${A.sep}`)&&!A.isAbsolute(G)}static async isWithinWorkspaceResolved(Q,$){let Z=A.resolve($),J=A.isAbsolute(Q)?A.resolve(Q):A.resolve(Z,Q);if(!this.isWithinWorkspace(J,Z))return!1;let G;try{G=await Y0.realpath(Z)}catch{return!1}let W=J;while(!0){try{let V=await Y0.realpath(W);return this.isWithinWorkspace(V,G)}catch(V){let Y=V.code;if(Y!=="ENOENT"&&Y!=="ENOTDIR")return!1}let z=A.dirname(W);if(z===W)return!1;W=z}}static isRestricted(Q){let $=Q.split(A.sep);return eQ.some((Z)=>$.includes(Z))}}var w0=i("Tool");class Z0{static instance=null;accessedFiles=new Map;constructor(){}static getInstance(){if(!Z0.instance)Z0.instance=new Z0;return Z0.instance}async recordFileRead(Q,$){try{let Z=await R0.stat(Q),J={filePath:Q,accessTime:Date.now(),mtime:Z.mtimeMs,sessionId:$,lastOperation:"read"};this.setRecord(J),w0.debug(`记录文件读取: ${Q}`)}catch(Z){w0.warn(`记录文件读取失败: ${Q}`,Z)}}async recordFileEdit(Q,$,Z="edit"){try{let J=await R0.stat(Q),G={filePath:Q,accessTime:Date.now(),mtime:J.mtimeMs,sessionId:$,lastOperation:Z};this.setRecord(G),w0.debug(`记录文件${Z==="edit"?"编辑":"写入"}: ${Q}`)}catch(J){w0.warn(`记录文件${Z==="edit"?"编辑":"写入"}失败: ${Q}`,J)}}hasFileBeenRead(Q,$){let Z=this.accessedFiles.get(Q);if(!Z)return!1;return $?Z.has($):Z.size>0}async checkFileModification(Q,$){let Z=this.getFileRecord(Q,$);if(!Z)return{modified:!1,message:"文件未被跟踪"};try{let J=await R0.stat(Q);if(Math.abs(J.mtimeMs-Z.mtime)>1)return{modified:!0,message:`文件在访问后被修改(访问时间: ${new Date(Z.accessTime).toISOString()}, 当前修改时间: ${J.mtime.toISOString()})`};return{modified:!1}}catch(J){let G=J;if(G.code==="ENOENT")return{modified:!0,message:"文件已被删除"};return{modified:!1,message:`无法检查文件状态: ${G.message}`}}}async checkExternalModification(Q,$){let Z=this.getFileRecord(Q,$);if(!Z)return{isExternal:!1,message:"文件未被跟踪"};try{let J=await R0.stat(Q);if(J.mtimeMs-Z.mtime>2000)return{isExternal:!0,message:`文件在 ${new Date(Z.accessTime).toISOString()} (${Z.lastOperation}) 之后被外部程序修改(当前修改时间: ${J.mtime.toISOString()})`};return{isExternal:!1}}catch(J){let G=J;if(G.code==="ENOENT")return{isExternal:!0,message:"文件已被删除"};return w0.warn(`检查文件外部修改失败: ${Q}`,J),{isExternal:!1,message:`无法检查文件状态: ${G.message}`}}}getFileRecord(Q,$){let Z=this.accessedFiles.get(Q);if(!Z)return;if($)return Z.get($);return[...Z.values()].sort((J,G)=>G.accessTime-J.accessTime)[0]}getTrackedRecords(){return[...this.accessedFiles.values()].flatMap((Q)=>[...Q.values()])}clearFileRecord(Q){this.accessedFiles.delete(Q)}clearAll(){this.accessedFiles.clear()}clearSession(Q,$){for(let[Z,J]of this.accessedFiles.entries()){if($&&!X0.isWithinWorkspace(Z,$))continue;if(J.delete(Q),J.size===0)this.accessedFiles.delete(Z)}}getTrackedFiles(){return Array.from(this.accessedFiles.keys())}getTrackedFileCount(){return this.accessedFiles.size}static resetInstance(){Z0.instance=null}setRecord(Q){let $=this.accessedFiles.get(Q.filePath);if(!$)$=new Map,this.accessedFiles.set(Q.filePath,$);$.set(Q.sessionId,Q)}}import{readFile as b2}from"node:fs/promises";import{basename as _2,isAbsolute as q2,resolve as w2}from"node:path";class C0{static MAX_FILES=5;static MAX_LINES_PER_FILE=1000;static analyzeFiles(Q){let $=new Map;return Q.forEach((J,G)=>{let W=typeof J.content==="string"?J.content:(J.content||[]).filter((V)=>V.type==="text").map((V)=>V.text).join(`
|
|
14
|
-
`);if(this.extractFilePathsFromContent(W).forEach((V)=>{this.updateFileReference($,V,G,!1)}),J.tool_calls&&Array.isArray(J.tool_calls))J.tool_calls.forEach((V)=>{let Y=this.extractFilePathsFromToolCall(V),H=V.type==="function"&&"function"in V?V.function?.name:"",D=["Write","Edit"].includes(H||"");Y.forEach((b)=>{this.updateFileReference($,b,G,D)})})}),Array.from($.values()).sort((J,G)=>{if(J.wasModified!==G.wasModified)return J.wasModified?-1:1;if(J.mentions!==G.mentions)return G.mentions-J.mentions;return G.lastMentioned-J.lastMentioned}).slice(0,this.MAX_FILES)}static async readFilesContent(Q,$){let Z=[];for(let J of Q)try{let G=$&&!q2(J)?w2($,J):J;if($&&!await X0.isWithinWorkspaceResolved(G,$))continue;let W=await b2(G,"utf-8"),z=W.split(`
|
|
15
|
-
`),V=z.length,Y=W,H=!1,D=V;if(V>this.MAX_LINES_PER_FILE)Y=z.slice(0,this.MAX_LINES_PER_FILE).join(`
|
|
16
|
-
`),Y+=`
|
|
17
|
-
|
|
18
|
-
... (truncated ${V-this.MAX_LINES_PER_FILE} lines)`,H=!0,D=this.MAX_LINES_PER_FILE;Z.push({path:J,content:Y,truncated:H,lines:V,includedLines:D})}catch(G){console.warn(`[FileAnalyzer] 无法读取文件: ${J}`,G)}return Z}static extractFilePathsFromContent(Q){let $=new Set,Z=/```(?:\w+)?\s*\n?([\s\S]*?)```/g,J=Array.from(Q.matchAll(Z));for(let W of J){let z=W[1];this.extractPathsFromText(z).forEach((Y)=>$.add(Y))}return this.extractPathsFromText(Q).forEach((W)=>$.add(W)),Array.from($)}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 Z){let G=Array.from(Q.matchAll(J));for(let W of G){let z=W[0];if(z=z.replace(/[,。;:!?""''()【】《》]$/g,""),z=z.replace(/[,.;:!?"'()[\]<>]$/g,""),this.isValidFilePath(z))$.push(z)}}return $}static extractFilePathsFromToolCall(Q){let $=[];if(Q.type!=="function"||!Q.function)return $;try{let Z=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(Z)){let W=["file_path","path","notebook_path","filePath"];for(let z of W)if(J[z]&&typeof J[z]==="string")$.push(J[z])}}catch{}return $}static updateFileReference(Q,$,Z,J){let G=Q.get($);if(G)G.mentions++,G.lastMentioned=Z,G.wasModified=G.wasModified||J;else Q.set($,{path:$,mentions:1,lastMentioned:Z,wasModified:J})}static isValidFilePath(Q){if(!Q.includes("/"))return!1;let $=_2(Q);if(!$.includes("."))return!1;let Z=["ts","tsx","js","jsx","json","md","py","java","go","rs","c","cpp","h","css","scss","html","xml","yaml","yml","toml","sh","bash","sql","graphql","vue","svelte"],J=$.split(".").pop()?.toLowerCase();if(!J||!Z.includes(J))return!1;return!0}}import{encodingForModel as QZ}from"js-tiktoken";class N0{static encodingCache=new Map;static countTokens(Q,$){let Z=this.getEncoding($),J=0;for(let G of Q){if(J+=4,G.role)J+=Z.encode(G.role).length;if(G.content)if(typeof G.content==="string")J+=Z.encode(G.content).length;else J+=Z.encode(JSON.stringify(G.content)).length;if(G.tool_calls&&Array.isArray(G.tool_calls))J+=this.countToolCallTokens(G.tool_calls,Z);if(G.name)J+=Z.encode(G.name).length}return J}static getTokenLimit(Q){return Q}static shouldCompact(Q,$,Z,J=0.8){let G=this.countTokens(Q,$),W=Math.floor(Z*J);return G>=W}static getEncoding(Q){if(!this.encodingCache.has(Q))try{let $=QZ(Q);this.encodingCache.set(Q,$)}catch{try{let $=QZ("gpt-4");this.encodingCache.set(Q,$)}catch{console.warn(`[TokenCounter] 无法为模型 ${Q} 获取 encoding,使用粗略估算`),this.encodingCache.set(Q,{encode:($)=>{return Array(Math.ceil($.length/4))}})}}return this.encodingCache.get(Q)}static countToolCallTokens(Q,$){let Z=0;for(let J of Q){if(Z+=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 Z}static clearCache(){this.encodingCache.clear()}static estimateTokens(Q){let $=(Q.match(/[\u4e00-\u9fa5]/g)||[]).length,Z=Q.length-$;return Math.ceil($/1.5+Z/4)}}var k=i("Context"),p0=new Map,v2=3;function I2(Q,$){return JSON.stringify([E2.resolve(Q??c()),$??null])}class D0{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,$){if($.signal?.aborted)throw new DOMException("Aborted","AbortError");let Z=$.actualPreTokens??N0.countTokens(Q,$.modelName),J=$.actualPreTokens?"actual (from LLM usage)":"estimated";k.debug(`[CompactionService] preTokens source: ${J}`);try{let V=await f0.getInstance().executeCompactionHooks($.trigger,{projectDir:$.workspaceRoot??c(),sessionId:$.sessionId||"unknown",permissionMode:$.permissionMode||"default",messagesBefore:Q.length,tokensBefore:Z});if(V.blockCompaction)return k.debug(`[CompactionService] Compaction hook 阻止压缩: ${V.blockReason||"(无原因)"}`),{success:!1,summary:"",preTokens:Z,postTokens:Z,filesIncluded:[],compactedMessages:Q,boundaryMessage:{role:"system",content:""},summaryMessage:{role:"user",content:""},error:V.blockReason||"Compaction blocked by hook"};if(V.warning)k.warn(`[CompactionService] Compaction hook warning: ${V.warning}`)}catch(z){k.warn("[CompactionService] Compaction hook execution failed:",z)}let G=I2($.workspaceRoot,$.sessionId),W=p0.get(G)??0;if(W>=v2)return k.warn(`[CompactionService] Circuit breaker open (${W} consecutive failures for session ${$.sessionId??"unknown"}), using fallback`),this.fallbackCompact(Q,$,Z,Error("Circuit breaker open"));try{k.debug("[CompactionService] 开始压缩,消息数:",Q.length),k.debug("[CompactionService] 压缩前 tokens:",Z);let V=C0.analyzeFiles(Q).map((C)=>C.path);k.debug("[CompactionService] 提取重点文件:",V);let Y=await C0.readFilesContent(V,$.workspaceRoot);k.debug("[CompactionService] 成功读取文件:",Y.length);let H=await this.generateSummary(Q,Y,$),{summary:D}=H;k.debug("[CompactionService] 生成总结,长度:",D.length);let b=Math.ceil(Q.length*this.RETAIN_PERCENT),F=Q.slice(-b),O=new Set;for(let C of F)if(C.role==="assistant"&&C.tool_calls)for(let a of C.tool_calls)O.add(a.id);let T=F.filter((C)=>{if(C.role==="tool"&&C.tool_call_id)return O.has(C.tool_call_id);return!0});k.debug("[CompactionService] 保留消息数:",b),k.debug("[CompactionService] 过滤后保留消息数:",T.length);let R=$0(),v=this.createBoundaryMessage(R,$.trigger,Z),E=$0(),L=this.createSummaryMessage(E,D),n=[L,...T],r=await this.buildFileRestorationMessage($.workspaceRoot,$.sessionId);if(r)n.push(r);let S=this.buildActiveTaskMessage($.activeTask);if(S)n.push(S);let t=N0.countTokens(n,$.modelName);k.debug("[CompactionService] 压缩完成!"),k.debug("[CompactionService] Token 变化:",Z,"->",t,`(-${((1-t/Z)*100).toFixed(1)}%)`),p0.delete(G);let o0=Q.slice(0,Q.length-b);return tQ(o0).catch((C)=>{return}),{success:!0,summary:D,preTokens:Z,postTokens:t,filesIncluded:Y.map((C)=>C.path),compactedMessages:n,boundaryMessage:v,summaryMessage:L,usage:H.usage}}catch(z){if(H0(z))throw z;return p0.set(G,(p0.get(G)??0)+1),k.error("[CompactionService] 压缩失败,使用降级策略",z),this.fallbackCompact(Q,$,Z,z)}}static async generateSummary(Q,$,Z){let J=this.buildCompactionPrompt(Q,$);if(k.debug("[CompactionService] 使用压缩模型:",Z.modelName),Z.signal?.aborted)throw new DOMException("Aborted","AbortError");let W=await(await ZZ({apiKey:Z.apiKey||process.env.BLADE_API_KEY,baseUrl:Z.baseURL||process.env.BLADE_BASE_URL,model:Z.modelName,temperature:0.3,maxOutputTokens:8000,timeout:60000,provider:Z.modelProvider??"openai"})).chat([{role:"user",content:J}],[],Z.signal),z=W.content||"",V=z.match(/<summary>([\s\S]*?)<\/summary>/);if(!V)return k.warn("[CompactionService] 总结格式不正确,使用完整响应"),{summary:z,usage:W.usage};return{summary:V[1].trim(),usage:W.usage}}static buildCompactionPrompt(Q,$){let Z=Q.map((W,z)=>{let V=W.role||"unknown",Y=typeof W.content==="string"?W.content:JSON.stringify(W.content),H=5000,D=Y.length>5000?Y.substring(0,5000)+"...":Y;return`[${z+1}] ${V}: ${D}`}).join(`
|
|
19
|
-
|
|
20
|
-
`),J=$.map((W)=>{return`### ${W.path}
|
|
21
|
-
\`\`\`
|
|
22
|
-
${W.content}
|
|
23
|
-
\`\`\``}).join(`
|
|
24
|
-
|
|
25
|
-
`),G=`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
|
-
${Z}
|
|
86
|
-
|
|
87
|
-
${$.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:$0(),role:"system",content:"Conversation compacted",metadata:{type:"system",subtype:"compact_boundary",parentId:Q,compactMetadata:{trigger:$,preTokens:Z}}}}static createSummaryMessage(Q,$){return{id:$0(),role:"user",content:$,metadata:{parentId:Q,isCompactSummary:!0}}}static async getRecentlyAccessedFiles(Q,$,Z){let G=Z0.getInstance().getTrackedRecords().filter((z)=>!Z||z.sessionId===Z).sort((z,V)=>V.accessTime-z.accessTime),W=[];for(let z of G){if($&&!await X0.isWithinWorkspaceResolved(z.filePath,$))continue;if(!W.includes(z.filePath))W.push(z.filePath);if(W.length>=Q)break}return W}static async buildFileRestorationMessage(Q,$){let Z=await this.getRecentlyAccessedFiles(5,Q,$);if(Z.length===0)return null;let J=[];for(let W of Z)try{let V=(await N2.readFile(W,"utf-8")).split(`
|
|
92
|
-
`),Y=V.slice(0,200).join(`
|
|
93
|
-
`),H=V.length>200?`
|
|
94
|
-
... (${V.length-200} more lines)`:"";J.push(`<file path="${W}" lines="${V.length}">
|
|
95
|
-
${Y}${H}
|
|
96
|
-
</file>`)}catch{}if(J.length===0)return null;let G=["<system-reminder>","Post-compaction file restoration. These files were recently accessed in the conversation:",...J,"</system-reminder>"].join(`
|
|
97
|
-
`);return k.debug("[CompactionService] Post-compact 恢复文件:",Z.length),{id:$0(),role:"user",content:G,metadata:{isPostCompactRestoration:!0}}}static buildActiveTaskMessage(Q){if(!Q)return null;let $=this.ACTIVE_TASK_MAX_CHARS,Z=Math.floor($*0.75),J=Q.length<=$?Q:[Q.slice(0,Z),`
|
|
98
|
-
...[active task checkpoint truncated]...
|
|
99
|
-
`,Q.slice(-($-Z))].join("");return{id:$0(),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 G=Math.ceil(Q.length*this.FALLBACK_RETAIN_PERCENT),W=Q.slice(-G),z=new Set;for(let v of W)if(v.role==="assistant"&&v.tool_calls)for(let E of v.tool_calls)z.add(E.id);let V=W.filter((v)=>{if(v.role==="tool"&&v.tool_call_id)return z.has(v.tool_call_id);return!0}),Y=$0(),H=this.createBoundaryMessage(Y,$.trigger,Z),D=J instanceof Error?J.message:String(J),b=$0(),F=this.createSummaryMessage(b,`[Automatic compaction failed; using fallback]
|
|
101
|
-
|
|
102
|
-
An error occurred during compaction. Retained the latest ${G} messages (~30%).
|
|
103
|
-
|
|
104
|
-
Error: ${D}
|
|
105
|
-
|
|
106
|
-
The conversation can continue, but consider retrying compaction later with /compact.`),O=[F,...V],T=this.buildActiveTaskMessage($.activeTask);if(T)O.push(T);let R=N0.countTokens(O,$.modelName);return{success:!1,summary:typeof F.content==="string"?F.content:F.content.filter((v)=>v.type==="text").map((v)=>v.text).join(`
|
|
107
|
-
`),preTokens:Z,postTokens:R,filesIncluded:[],compactedMessages:O,boundaryMessage:H,summaryMessage:F,error:D}}}var U2=new Set(["Read","Grep","Glob","Search","WebSearch","WebFetch","ToolSearch"]);function A2(Q,$){let G=(Q[$.assistantIdx].tool_calls??[]).filter((z)=>z.type==="function").map((z)=>z.function.name).some((z)=>!U2.has(z));if($.toolResultIdxs.some((z)=>{let V=Q[z]?.content;if(typeof V!=="string")return!1;return V.startsWith("Error:")||V.includes("failed")||V.includes("ENOENT")}))return 3;if(G)return 2;return 1}function E0(Q,$){let Z=$?.keepRecentTurns??10,J=$?.minMessagesForSnip??30;if(Q.length<J)return{messages:Q,snippedCount:0,estimatedTokensFreed:0};let G=[];for(let F=0;F<Q.length;F++){let O=Q[F];if(O.role==="assistant"&&O.tool_calls&&O.tool_calls.length>0){let T=new Set(O.tool_calls.map((v)=>v.id)),R=[];for(let v=F+1;v<Q.length;v++){let E=Q[v];if(E.role==="tool"&&E.tool_call_id&&T.has(E.tool_call_id))R.push(v);if(E.role==="assistant"||E.role==="user")break}G.push({assistantIdx:F,toolResultIdxs:R,priority:0})}}for(let F of G)F.priority=A2(Q,F);let V=[...G.slice(0,Math.max(0,G.length-Z))].sort((F,O)=>F.priority-O.priority);if(V.length===0)return{messages:Q,snippedCount:0,estimatedTokensFreed:0};let Y=new Set,H=0;for(let F of V){Y.add(F.assistantIdx);for(let O of F.toolResultIdxs)Y.add(O)}for(let F of Y){let O=Q[F],T=typeof O.content==="string"?O.content:JSON.stringify(O.content);if(H+=T.length,O.tool_calls)H+=JSON.stringify(O.tool_calls).length}let D=[],b=!1;for(let F=0;F<Q.length;F++){if(Y.has(F)){if(!b)D.push({role:"system",content:`[${V.length} earlier tool interaction${V.length===1?"":"s"} snipped for brevity]`}),b=!0;continue}D.push(Q[F])}return{messages:D,snippedCount:V.length,estimatedTokensFreed:Math.floor(H/4)}}var y2=60000,S2=3;function $Z(Q,$){if(!$)return null;if(Date.now()-$<y2)return null;let J=E0(Q,{keepRecentTurns:S2,minMessagesForSnip:15});if(J.snippedCount===0)return null;return J}class wQ{hasAttempted=!1;async tryReactiveCompact(Q,$){if(this.hasAttempted)return{success:!1,messages:Q};this.hasAttempted=!0;let Z=E0(Q,{keepRecentTurns:3,minMessagesForSnip:10}),J=Z.messages;try{let G=await D0.compact(J,{trigger:"auto",modelName:$.modelName,modelProvider:$.modelProvider,maxContextTokens:$.maxContextTokens,apiKey:$.apiKey,baseURL:$.baseURL,signal:$.signal,activeTask:$.activeTask,workspaceRoot:$.workspaceRoot,sessionId:$.sessionId});if(G.success)return{success:!0,messages:G.compactedMessages,usage:G.usage};if(Z.snippedCount>0)return{success:!0,messages:J};return{success:!1,messages:Q}}catch(G){if(H0(G))throw G;if(Z.snippedCount>0)return{success:!0,messages:J};return{success:!1,messages:Q}}}reset(){this.hasAttempted=!1}}import*as F0 from"fs";import*as NQ from"os";import*as v0 from"path";import{nanoid as WZ}from"nanoid";var M2=1e5,P2=2000,JZ=200000;class EQ{currentChars=0;track(Q){this.currentChars+=Q}remaining(){return Math.max(0,JZ-this.currentChars)}isExhausted(){return this.currentChars>=JZ}reset(){this.currentChars=0}}function zZ(Q,$,Z){let J=Z?.maxCharsPerResult??M2,G=Z?.previewChars??P2,W=Z?.messageBudget,z=typeof Q==="string"?Q:JSON.stringify(Q,null,2);if(z.length<=J)return f2(Q,z,$,G,W,Z);let V=Z?.outputDir??v0.join(NQ.homedir(),".blade","tool-results"),Y=`${$}-${WZ(8)}.txt`,H=v0.join(V,Y);try{F0.mkdirSync(V,{recursive:!0}),F0.writeFileSync(H,z,"utf-8")}catch{let F=z.slice(0,J)+`
|
|
108
|
-
|
|
109
|
-
... (truncated, ${z.length} total chars)`;if(W)W.track(F.length);return F}let D=z.slice(0,G),b=`Result too large (${z.length} chars). Full output saved to: ${H}
|
|
110
|
-
|
|
111
|
-
Preview:
|
|
112
|
-
${D}
|
|
113
|
-
|
|
114
|
-
... (${z.length-G} more chars in file)`;if(W)W.track(b.length);return b}function f2(Q,$,Z,J,G,W){if(!G)return Q;let z=G.remaining();if(z<=0){let V=$.slice(0,J),Y=GZ($,V,Z,W,"[Message budget exhausted. Full output saved to disk.]");return G.track(typeof Y==="string"?Y.length:J),Y}if($.length>z){let V=Math.max(J,z),Y=$.slice(0,V),H=GZ($,Y,Z,W,`... (truncated by message budget, ${$.length} total chars)`);return G.track(typeof H==="string"?H.length:V),H}return G.track($.length),Q}function GZ(Q,$,Z,J,G){let W=J?.outputDir??v0.join(NQ.homedir(),".blade","tool-results"),z=`${Z}-${WZ(8)}.txt`,V=v0.join(W,z);try{return F0.mkdirSync(W,{recursive:!0}),F0.writeFileSync(V,Q,"utf-8"),`${$}
|
|
115
|
-
|
|
116
|
-
${G}
|
|
117
|
-
Full output saved to: ${V}`}catch{return`${$}
|
|
118
|
-
|
|
119
|
-
${G}`}}import*as i0 from"node:fs/promises";import{homedir as LZ}from"node:os";import*as s from"node:path";var g0={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 VZ(){return{metadata:g0,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 d0={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 YZ(){return{metadata:d0,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 x2}from"node:child_process";import*as q from"node:fs/promises";import{homedir as h2}from"node:os";import*as f from"node:path";import{promisify as T2}from"node:util";var m0=T2(x2),P=i("General"),vQ={url:"https://github.com/anthropics/skills.git",branch:"main",defaultSkills:["skill-creator"]};class XZ{skillsDir;constructor(Q){this.skillsDir=Q||f.join(h2(),".blade","skills")}async isInstalled(Q){let $=f.join(this.skillsDir,Q,"SKILL.md");try{return await q.access($),!0}catch{return!1}}async isGitAvailable(){try{return await m0("git --version"),!0}catch{return!1}}async installOfficialSkill(Q){let{url:$,branch:Z}=vQ,J=f.join(this.skillsDir,Q),G=f.join(this.skillsDir,`.tmp-${Q}-${Date.now()}`);try{if(!await this.isGitAvailable())return P.warn("Git not available, skipping skill installation"),!1;P.info(`Installing official skill: ${Q}...`),await q.mkdir(this.skillsDir,{recursive:!0,mode:493}),await m0(`git clone --depth 1 --branch ${Z} --single-branch ${$} "${G}"`,{timeout:30000});let W=f.join(G,"skills",Q);try{await q.access(W)}catch{return P.warn(`Skill ${Q} not found in official repository`),await q.rm(G,{recursive:!0,force:!0}),!1}try{await q.rm(J,{recursive:!0,force:!0})}catch{}return await q.cp(W,J,{recursive:!0}),await q.rm(G,{recursive:!0,force:!0}),P.info(`Successfully installed: ${Q}`),!0}catch(W){try{await q.rm(G,{recursive:!0,force:!0})}catch{}return P.warn(`Failed to install ${Q}: ${W instanceof Error?W.message:"Unknown error"}`),!1}}async ensureDefaultSkillsInstalled(){await q.mkdir(this.skillsDir,{recursive:!0,mode:493});for(let Q of vQ.defaultSkills)if(!await this.isInstalled(Q))await this.installOfficialSkill(Q)}async installFromRepo(Q,$){let Z=$||this.extractRepoName(Q),J=f.join(this.skillsDir,Z),G=f.join(this.skillsDir,`.tmp-repo-${Z}-${Date.now()}`);try{if(!await this.isGitAvailable())return P.warn("Git not available, cannot install from repo"),!1;P.info(`Installing skill from repo: ${Q}...`),await q.mkdir(this.skillsDir,{recursive:!0,mode:493}),await m0(`git clone --depth 1 "${Q}" "${G}"`,{timeout:60000});let W=f.join(G,"SKILL.md");try{await q.access(W)}catch{return P.warn(`No SKILL.md found in repository ${Q}`),await q.rm(G,{recursive:!0,force:!0}),!1}await q.rm(J,{recursive:!0,force:!0}),await q.rename(G,J);try{await q.rm(f.join(J,".git"),{recursive:!0,force:!0})}catch{}return P.info(`Successfully installed skill from repo: ${Z}`),!0}catch(W){try{await q.rm(G,{recursive:!0,force:!0})}catch{}return P.warn(`Failed to install from repo ${Q}: ${W instanceof Error?W.message:"Unknown error"}`),!1}}async installFromLocal(Q,$,Z=!0){let J=$||f.basename(Q),G=f.join(this.skillsDir,J);try{let W=f.resolve(Q);try{await q.access(W)}catch{return P.warn(`Local path does not exist: ${W}`),!1}let z=f.join(W,"SKILL.md");try{await q.access(z)}catch{return P.warn(`No SKILL.md found in local path: ${W}`),!1}if(P.info(`Installing skill from local path: ${W}...`),await q.mkdir(this.skillsDir,{recursive:!0,mode:493}),await q.rm(G,{recursive:!0,force:!0}),Z)await q.symlink(W,G,"dir"),P.info(`Created symlink for skill: ${J}`);else await q.cp(W,G,{recursive:!0}),P.info(`Copied skill to: ${J}`);return!0}catch(W){return P.warn(`Failed to install from local path ${Q}: ${W instanceof Error?W.message:"Unknown error"}`),!1}}extractRepoName(Q){return Q.match(/\/([^/]+?)(\.git)?$/)?.[1]||"unknown-skill"}async installAllOfficialSkills(){let{url:Q,branch:$}=vQ,Z=f.join(this.skillsDir,`.tmp-all-${Date.now()}`),J=[],G=[];try{if(!await this.isGitAvailable())return P.warn("Git not available, skipping skill installation"),{installed:J,failed:G};await q.mkdir(this.skillsDir,{recursive:!0,mode:493}),P.info("Cloning official skills repository..."),await m0(`git clone --depth 1 --branch ${$} --single-branch ${Q} "${Z}"`,{timeout:60000});let W=f.join(Z,"skills"),z=await q.readdir(W,{withFileTypes:!0});for(let V of z){if(!V.isDirectory())continue;let Y=V.name,H=f.join(W,Y),D=f.join(this.skillsDir,Y);try{await q.access(f.join(H,"SKILL.md")),await q.rm(D,{recursive:!0,force:!0}),await q.cp(H,D,{recursive:!0}),P.info(`Installed: ${Y}`),J.push(Y)}catch(b){P.warn(`Failed to install ${Y}`),G.push(Y)}}await q.rm(Z,{recursive:!0,force:!0})}catch(W){try{await q.rm(Z,{recursive:!0,force:!0})}catch{}P.warn(`Failed to install skills: ${W instanceof Error?W.message:"Unknown error"}`)}return{installed:J,failed:G}}}var IQ=null;function HZ(Q){if(!IQ)IQ=new XZ(Q);return IQ}import*as I0 from"node:fs/promises";import*as c0 from"node:path";import{parse as k2}from"yaml";var R2=/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/,C2=/^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]?$/,BZ=1024;function p2(Q){if(!Q)return;if(typeof Q==="string")return Q.split(",").map(($)=>$.trim()).filter(Boolean);if(Array.isArray(Q))return Q.map(($)=>String($).trim()).filter(Boolean);return}function KZ(Q){if(Q===void 0)return;if(typeof Q==="boolean")return Q;if(typeof Q==="string"){let $=Q.toLowerCase().trim();if($==="true"||$==="yes"||$==="1")return!0;if($==="false"||$==="no"||$==="0")return!1}return}function g2(Q,$){if(!Q.name)return{valid:!1,error:"Missing required field: name"};if(!C2.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>BZ)return{valid:!1,error:`Description too long: ${Q.description.length} characters (max ${BZ})`};let Z;if(Q.model)Z=Q.model==="inherit"?"inherit":Q.model;return{valid:!0,metadata:{name:Q.name,description:Q.description.trim(),allowedTools:p2(Q["allowed-tools"]),version:Q.version,argumentHint:Q["argument-hint"]?.trim(),userInvocable:KZ(Q["user-invocable"]),disableModelInvocation:KZ(Q["disable-model-invocation"]),model:Z,whenToUse:Q.when_to_use?.trim()}}}function jZ(Q,$,Z){let J=Q.match(R2);if(!J)return{success:!1,error:"Invalid SKILL.md format: missing YAML frontmatter (must start with ---)"};let[,G,W]=J,z;try{z=k2(G)}catch(H){return{success:!1,error:`Failed to parse YAML frontmatter: ${H instanceof Error?H.message:String(H)}`}}let V=g2(z,$);if(!V.valid)return{success:!1,error:V.error};let Y=c0.dirname($);return{success:!0,content:{metadata:{...V.metadata,path:$,basePath:Y,source:Z},instructions:W.trim()}}}async function DZ(Q,$){try{let Z=await I0.readFile(Q,"utf-8");return jZ(Z,Q,$)}catch(Z){if(Z.code==="ENOENT")return{success:!1,error:`File not found: ${Q}`};return{success:!1,error:`Failed to read file: ${Z instanceof Error?Z.message:String(Z)}`}}}async function FZ(Q){try{let $=await I0.readFile(Q.path,"utf-8"),Z=jZ($,Q.path,Q.source);return Z.success?Z.content:null}catch{return null}}async function OZ(Q){try{return await I0.access(c0.join(Q,"SKILL.md")),!0}catch{return!1}}var d2={userSkillsDir:s.join(LZ(),".blade","skills"),projectSkillsDir:".blade/skills",claudeUserSkillsDir:s.join(LZ(),".claude","skills"),claudeProjectSkillsDir:".claude/skills"},u0=null;class UQ{skills=new Map;pluginSkills=new Map;config;initialized=!1;constructor(Q){this.config={...d2,cwd:c(),...Q}}static getInstance(Q){if(!u0)u0=new UQ(Q);return u0}static resetInstance(){u0=null}async initialize(){if(this.initialized)return{skills:Array.from(this.skills.values()),errors:[]};let Q=[],$=[];try{await HZ(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 Z=await this.scanDirectory(this.config.claudeUserSkillsDir,"user");$.push(...Z.skills),Q.push(...Z.errors);let J=await this.scanDirectory(this.config.userSkillsDir,"user");$.push(...J.skills),Q.push(...J.errors);let G=s.isAbsolute(this.config.claudeProjectSkillsDir)?this.config.claudeProjectSkillsDir:s.join(this.config.cwd,this.config.claudeProjectSkillsDir),W=await this.scanDirectory(G,"project");$.push(...W.skills),Q.push(...W.errors);let z=s.isAbsolute(this.config.projectSkillsDir)?this.config.projectSkillsDir:s.join(this.config.cwd,this.config.projectSkillsDir),V=await this.scanDirectory(z,"project");$.push(...V.skills),Q.push(...V.errors);for(let Y of $)this.skills.set(Y.name,Y);return this.initialized=!0,{skills:Array.from(this.skills.values()),errors:Q}}loadBuiltinSkills(){this.skills.set(g0.name,g0),this.skills.set(d0.name,d0)}async scanDirectory(Q,$){let Z=[],J=[];try{await i0.access(Q)}catch{return{skills:Z,errors:J}}try{let G=await i0.readdir(Q,{withFileTypes:!0});for(let W of G){if(!W.isDirectory())continue;let z=s.join(Q,W.name),V=s.join(z,"SKILL.md");if(!await OZ(z))continue;let Y=await DZ(V,$);if(Y.success&&Y.content)Z.push(Y.content.metadata);else J.push({path:V,error:Y.error||"Unknown error"})}}catch(G){J.push({path:Q,error:`Failed to scan directory: ${G instanceof Error?G.message:String(G)}`})}return{skills:Z,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 $=this.skills.get(Q);if(!$)return null;if($.source==="builtin")return this.loadBuiltinContent(Q);return FZ($)}loadBuiltinContent(Q){switch(Q){case"skill-creator":return VZ();case"update-config":return YZ();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 $=[];for(let Z of Q){let J=Z.description.length>100?`${Z.description.substring(0,97)}...`:Z.description,G=Z.argumentHint?`${Z.name} ${Z.argumentHint}`:Z.name;$.push(`- ${G}: ${J}`)}return $.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 $=this.pluginSkills.get(Q);if($)return $;let Z=[];for(let J of this.pluginSkills.values())if(J.originalName===Q)Z.push(J);if(Z.length===1)return Z[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 n0(Q){return UQ.getInstance(Q)}async function m2(Q){return n0(Q).initialize()}var c2="Skill",u2=/<available_skills>\s*<\/available_skills>/;function AQ(Q){let Z=n0().generateAvailableSkillsList();if(!Z)return Q;return Q.map((J)=>{if(J.name!==c2)return J;let G=J.description.replace(u2,`<available_skills>
|
|
577
|
-
${Z}
|
|
578
|
-
</available_skills>`);if(G===J.description)return J;return{...J,description:G}})}function bZ(){return{consecutiveFailures:new Map,totalFailures:0,lastFailedTool:null}}function _Z(Q,$){Q.consecutiveFailures.set($,0),Q.lastFailedTool=null}function qZ(Q,$){let Z=(Q.consecutiveFailures.get($)??0)+1;Q.consecutiveFailures.set($,Z),Q.totalFailures++,Q.lastFailedTool=$}function i2(Q,$){return(Q.consecutiveFailures.get($)??0)>=3}function wZ(Q,$){if(!i2(Q,$))return;let Z=Q.consecutiveFailures.get($)??0;return`WARNING: ${$} has failed ${Z} consecutive times. Consider a different approach: use a different tool, verify your parameters, or break the task into smaller steps.`}function NZ(Q){return Q>0&&Q%5===0}function EZ(Q,$){let Z=[`[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($>3)Z.push(`Note: ${$} tool failures so far. Consider whether your current strategy needs adjustment.`);return Z.join(`
|
|
579
|
-
`)}function vZ(){return{recentOutputHashes:[]}}function n2(Q){let $=Q.trim().slice(0,500),Z=0;for(let J=0;J<$.length;J++)Z=(Z<<5)-Z+$.charCodeAt(J)|0;return Z.toString(36)}function IZ(Q,$){let Z=n2($);if(Q.recentOutputHashes.push(Z),Q.recentOutputHashes.length>4)Q.recentOutputHashes.shift();if(Q.recentOutputHashes.length<3)return!1;let J=Q.recentOutputHashes.slice(-3),G=J.every((W)=>W===J[0]);if(G)Q.recentOutputHashes=[];return G}function UZ(){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 J0=i("Agent"),r2=new Set(["Read","Glob","Grep","WebFetch","WebSearch","MemoryRead","GetSpecContext","ValidateSpec","TaskOutput"]);class l0{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,G,W,z){this.pipeline=Q;this.execContext=$;this.registry=Z;this.contextMgr=J;this.sessionId=G;this.lastMessageUuid=W;this.subagentInfo=z}setExecutionPolicy(Q){this.executeTool=Q}setAdmissionPolicy(Q){this.admitTool=Q}setAdmissionRollback(Q){this.rollbackAdmission=Q}addTool(Q,$){if(this.dispatched.has(Q.id))return J0.debug(`[StreamingToolExecutor] 跳过已分发工具: ${Q.function.name} (${Q.id})`),"rejected";this.dispatched.add(Q.id),this.order.push(Q.id);let Z=this.admitTool?.(Q.function.name,$);if(Z)return this.completed.set(Q.id,{toolCall:Q,result:Z,toolUseUuid:null}),"rejected";if(r2.has(Q.function.name)){J0.debug(`[StreamingToolExecutor] 立即执行预启动工具: ${Q.function.name}`);let G=this.executeOne(Q,$);return this.pending.set(Q.id,G),"prelaunched"}else return J0.debug(`[StreamingToolExecutor] 排队非预启动工具: ${Q.function.name}`),this.queued.push({toolCall:Q,params:$}),"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 Z=await this.pending.get(Q);this.pending.delete(Q),yield Z;continue}let $=this.queued.findIndex((Z)=>Z.toolCall.id===Q);if($!==-1){let{toolCall:Z,params:J}=this.queued[$];if(this.queued.splice($,1),this.execContext.signal?.aborted){J0.debug(`[StreamingToolExecutor] Signal aborted, 跳过排队工具: ${Z.function.name} (${Z.id})`),yield this.makeAbortResult(Z,"Tool execution skipped: task aborted before launch");continue}yield await this.executeOne(Z,J)}}}getCompletedResults(){let 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(),J0.debug(`[StreamingToolExecutor] 已丢弃所有挂起工作并重置状态 (epoch=${this.epoch})`)}hasTools(){return this.order.length>0}getEpoch(){return this.epoch}makeAbortResult(Q,$){return{toolCall:Q,result:{success:!1,llmContent:"",error:{type:"execution_error",message:$},metadata:{abortedBeforeLaunch:!0}},toolUseUuid:null}}async executeOne(Q,$){let Z=this.epoch,J=new AbortController;this.activeAborts.set(Q.id,J);let G=this.abortController.signal;try{if(G.aborted||J.signal.aborted)return this.makeAbortResult(Q,"Tool execution aborted due to discard");let W=null;try{if(this.contextMgr&&this.sessionId)W=await this.contextMgr.saveToolUse(this.sessionId,Q.function.name,$,this.lastMessageUuid??null,this.subagentInfo)}catch(F){J0.warn("[StreamingToolExecutor] 保存工具调用失败:",F)}let z=[G,J.signal],V=this.execContext.signal;if(V)z.push(V);let Y=AZ(...z),H={...this.execContext,messageId:W??Q.id,signal:Y},D=this.executeTool?await this.executeTool(Q.function.name,$,H):await this.pipeline.execute(Q.function.name,$,H);if(Z!==this.epoch)return J0.debug(`[StreamingToolExecutor] 丢弃旧世代工具结果: ${Q.function.name} (startEpoch=${Z}, currentEpoch=${this.epoch})`),this.makeAbortResult(Q,"Tool execution aborted due to epoch mismatch (discard)");let b={toolCall:Q,result:D,toolUseUuid:W};if(this.pending.has(Q.id))this.pending.delete(Q.id),this.completed.set(Q.id,b);return b}catch(W){if(Z!==this.epoch)return this.makeAbortResult(Q,"Tool execution aborted due to epoch mismatch (discard)");J0.error(`[StreamingToolExecutor] 工具执行失败: ${Q.function.name}`,W);let z={success:!1,llmContent:"",error:{type:"execution_error",message:W instanceof Error?W.message:"Unknown error"},metadata:void 0},V={toolCall:Q,result:z,toolUseUuid:null,error:W instanceof Error?W:Error("Unknown error")};if(this.pending.has(Q.id))this.pending.delete(Q.id),this.completed.set(Q.id,V);return V}finally{this.activeAborts.delete(Q.id)}}}var x=i("Agent"),a2=0.1,o2=8192,s2=32768,t2=2,e2=0.95,r0=SZ;function a0(Q,$){return{inputTokens:Q.promptTokens??0,outputTokens:Q.completionTokens??0,totalTokens:Q.totalTokens??0,maxContextTokens:$,cacheReadTokens:Q.cacheReadInputTokens??0,cacheWriteTokens:Q.cacheCreationInputTokens??0,costUsd:Q.costUsd}}var Q7=`
|
|
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 yZ(Q){let $=Q.trim();if($=$.replace(/,\s*([}\]])/g,"$1"),$.startsWith("{")&&!$.endsWith("}"))$+="}";$=$.replace(/,\s*([}\]])/g,"$1");try{let Z=JSON.parse($);if(typeof Z==="object"&&Z!==null&&!Array.isArray(Z))return Z;return null}catch{return null}}function yQ(Q){let $=yZ(Q);if($)return $;try{let Z=JSON.parse(Q);return typeof Z==="string"?yZ(Z):null}catch{return null}}function Z7(Q){if(typeof Q==="string")return Q;try{return JSON.parse(JSON.stringify(Q))}catch{return String(Q)}}function $7(Q){let $=new Set,Z=!1;for(let J of Q){if(J.role==="assistant"){if(J.tool_calls&&J.tool_calls.length>0){for(let W of J.tool_calls)if("function"in W&&W.function.name==="Task")$.add(W.id)}else if(Z)Z=!1;continue}if(J.role!=="tool"||J.name!=="Task"||!J.tool_call_id||!$.has(J.tool_call_id)||typeof J.metadata!=="object"||J.metadata===null||Array.isArray(J.metadata))continue;let G=J.metadata;if(G.toolCallId===J.tool_call_id&&G.toolName==="Task"&&G.error===null)Z=!0}return Z}function J7(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 G=Q.message,W=G.match(/Last error:\s*(.+)$/);if(W)return W[1];return G}function G7(Q){if(!(Q instanceof Error))return!1;return["stream not supported","streaming is not available","sse not supported","does not support streaming"].some((Z)=>Q.message.toLowerCase().includes(Z.toLowerCase()))}function W7(Q,$){if(!$)return"Tool execution failed (no details).";let Z=[`Error: ${$.message||"Unknown error"}`];if($.type==="validation_error")Z.push("Hint: Check the tool parameters — a required field may be missing or have the wrong type.");else if($.type==="permission_denied")Z.push("Hint: This operation requires user approval. Try a different approach or ask the user.");else if($.type==="timeout_error")Z.push("Hint: The operation timed out. Consider breaking it into smaller steps or increasing timeout.");else if($.type==="execution_error"){let J=$.message??"";if(J.includes("ENOENT")||J.includes("no such file"))Z.push("Hint: File or directory not found. Use Glob or Grep to find the correct path first.");else if(J.includes("EACCES")||J.includes("permission"))Z.push("Hint: Permission denied. The file may be read-only or owned by another user.");else if(J.includes("not found in file")||J.includes("old_string"))Z.push(`Hint: The target text was not found. Use Read to view the current file content, then retry ${Q} with the exact text.`);else if(J.includes("ENOTDIR"))Z.push("Hint: A path component is not a directory. Verify the full path with Glob.")}return Z.join(`
|
|
588
|
-
`)}function z7(Q){if(!(Q instanceof Error))return!1;let $=Q.message.toLowerCase();return $.includes("prompt_too_long")||$.includes("prompt is too long")||$.includes("maximum context length")||$.includes("request too large")||Q.status===413}function V7(Q,$){let Z=$,J=Z.index??0;if(!Q.has(J))Q.set(J,{id:Z.id||"",name:Z.function?.name||"",arguments:""});let G=Q.get(J);if(Z.id&&!G.id)G.id=Z.id;if(Z.function?.name&&!G.name)G.name=Z.function.name;if(Z.function?.arguments)G.arguments+=Z.function.arguments}function Y7(Q){if(Q.size===0)return;return Array.from(Q.values()).filter(($)=>$.id&&$.name).map(($)=>({id:$.id,type:"function",function:{name:$.name,arguments:$.arguments}}))}async function*X7(Q,$,Z,J,G,W){let z="",V="",Y,H,D=new Map;try{let b=Q.chatService.streamChat($,Z,J,G),F=0;for await(let O of b){if(F++,J?.aborted)break;if(O.modelFallback){W?.discard(),z="",V="",Y=void 0,H=void 0,D.clear(),F=0,yield{kind:"model_fallback"};continue}if(O.content)z+=O.content,yield{kind:"content_delta",delta:O.content};if(O.reasoningContent)V+=O.reasoningContent,yield{kind:"thinking_delta",delta:O.reasoningContent};if(O.usage)Y=O.usage;if(O.toolCalls){for(let T of O.toolCalls)if(V7(D,T),W){let v=T.index??0,E=D.get(v);if(E&&E.id&&E.name)try{let L=yQ(E.arguments);if(L===null)continue;let n={id:E.id,type:"function",function:{name:E.name,arguments:E.arguments}},S=Q.toolExecutor.getRegistry().get(E.name)?.kind;if(W.addTool(n,L)==="prelaunched")yield{kind:"tool_start",toolCall:n,toolKind:S}}catch{}}}if(O.finishReason){H=O.finishReason;break}}if(F===0&&!J?.aborted&&z.length===0&&D.size===0)return x.warn("[Loop] 流式响应返回0个chunk,回退到非流式模式"),W?.discard(),{...await Q.chatService.chat($,Z,J,G),_nonStreamingFallback:!0};return{content:z,reasoningContent:V||void 0,toolCalls:Y7(D),usage:Y,finishReason:H}}catch(b){if(G7(b))return x.warn("[Loop] 流式请求失败,降级到非流式模式"),W?.discard(),{...await Q.chatService.chat($,Z,J,G),_nonStreamingFallback:!0};throw b}}async function*fZ(Q,$,Z,J,G,W,z,V){if(J===void 0)return x.debug(`[Loop] [轮次 ${Z}] 压缩检查: 跳过(无历史 usage 数据)`),"none";let Y=$Z($.messages,W);if(Y)$.messages=Y.messages,x.debug(`[Loop] [轮次 ${Z}] MicroCompact: 清理 ${Y.snippedCount} 轮旧工具结果(缓存已过期)`);let H=E0($.messages),D=!1;if(H.snippedCount>0)D=!0,x.debug(`[Loop] [轮次 ${Z}] Snip 压缩: 移除 ${H.snippedCount} 轮旧工具调用,释放约 ${H.estimatedTokensFreed} tokens`);let b=Q.chatService.getConfig(),F=b.model,O=b.maxContextTokens??0,T=b.maxOutputTokens??Q.config.maxOutputTokens??Math.min(Math.max(Math.floor(O*a2),o2),s2),R=O-T,v=Math.floor(R*0.8);if(x.debug(`[Loop] [轮次 ${Z}] 压缩检查:`,{promptTokens:J,maxContextTokens:O,maxOutputTokens:T,availableForInput:R,threshold:v,shouldCompact:J>=v}),J<v){if(D)$.messages=H.messages;return D?"snipped":"none"}let E=V?.lastCompactionTurn===void 0?void 0:Z-V.lastCompactionTurn,L=E!==void 0&&E<=t2,n=Math.floor(R*e2);if(L&&J<n){if(D)$.messages=H.messages;return x.debug(`[Loop] [轮次 ${Z}] 跳过连续 LLM 压缩,距离上次压缩 ${E} 轮`),D?"snipped":"none"}x.debug(Z===0?"[Loop] 触发自动压缩":`[Loop] [轮次 ${Z}] 触发循环内自动压缩`),yield{kind:"compaction",phase:"start"};try{let r=D?H.messages:$.messages,S=await D0.compact(r,{trigger:"auto",modelName:F,modelProvider:b.provider,maxContextTokens:O,apiKey:b.apiKey,baseURL:b.baseUrl,actualPreTokens:J,signal:G,activeTask:z,workspaceRoot:$.workspaceRoot||c(),sessionId:$.sessionId});if(S.usage)yield{kind:"token_usage",usage:a0(S.usage,O)};if($.messages=S.compactedMessages,V)V.lastCompactionTurn=Z;if(S.success)x.debug(`[Loop] [轮次 ${Z}] 压缩完成: ${S.preTokens} -> ${S.postTokens} tokens`);else x.warn(`[Loop] [轮次 ${Z}] 压缩使用降级策略: ${S.preTokens} -> ${S.postTokens} tokens`);return await k0(Q,$,S.summary,{trigger:"auto",preTokens:S.preTokens,postTokens:S.postTokens,filesIncluded:S.filesIncluded}),"compacted"}catch(r){if(H0(r))return x.debug(`[Loop] [轮次 ${Z}] 压缩被中止`),"none";if(D)$.messages=H.messages;return x.error(`[Loop] [轮次 ${Z}] 压缩失败,继续执行`,r),D?"snipped":"none"}finally{yield{kind:"compaction",phase:"end"}}}function H7(Q,$,Z,J){let G=J?PZ(J):"user-cancel";return{success:!1,error:{type:"aborted",message:(G==="interrupt"?void 0:"任务已被用户中止")??"任务已中断"},metadata:{turnsCount:Q,toolCallsCount:$,duration:Date.now()-Z,abortReason:G}}}async function*B7(Q,$,Z,J,G){let W=Date.now(),z=0,V=[],Y=null,H=!1,D=(b,F,O)=>{return H=!0,H7(b,F,W,O)};try{let b=Q.toolExecutor.getRegistry(),F=Z.permissionMode,O=b.getFunctionDeclarationsByMode(F);O=AQ(O);let T=Q.applySkillToolRestrictions(O),R=bZ(),v=vZ(),E=G;if(typeof b.getDeferredToolsListing==="function"){let N=b.getDeferredToolsListing();if(N&&E)E=`${E}
|
|
589
|
-
|
|
590
|
-
${N}`}if(E)E+=Q7;let L=new P0(Z,E),n=J?.pendingInputOnly===!0;if(!n){let N=J?.inputMessageId?{inboxMessageId:J.inputMessageId}:void 0,U=N??(J?.transientInput==="goal_continuation"?{transientGoalContinuation:!0}:void 0);if(L.appendUser({role:"user",content:$,metadata:U}),J?.transientInput!=="goal_continuation")Y=await o(Q,Z,$,null,N);if(J?.inputMessageId&&!Y)throw Error(`Failed to persist durable input before applying it: ${J.inputMessageId}`)}let r=Z.permissionMode==="yolo",S=!!Z.subagentInfo,t=Q.runtimeOptions.maxTurns??J?.maxTurns??Q.config.maxTurns??-1,o0=t>=0;if(t===0)return{success:!1,error:{type:"chat_disabled",message:"对话功能已被禁用 (maxTurns=0)"},metadata:{turnsCount:0,toolCallsCount:0,duration:0}};let C=t===-1?r0:Math.min(t,r0),a=0,s0,SQ,O0=0,t0=0,e0=0,QQ=0,L0,ZQ=0,$Q=new Set,m=new Set(Z.worktreeActive?["EnterWorktree","TaskWorktree"]:[]),l=typeof $==="string"?$:$.filter((N)=>N.type==="text").map((N)=>N.text).join(`
|
|
591
|
-
`),JQ=[l,Z.completionRequirements?.trim()].filter(Boolean).join(`
|
|
592
|
-
`),GQ=l.trim()?[l]:[],U0=[Q.runtimeOptions.appendSystemPrompt?.trim(),Z.completionRequirements?.trim(),...GQ].filter((N)=>Boolean(N)),A0=h0(l),WQ=!n,b0=$7(Z.messages);if(b0)m.add("Task");let MQ=()=>x0(U0),xZ=()=>{let N="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:N,error:{type:"validation_error",message:N},metadata:{summary:"Blocked duplicate exactly-once Task delegation"}}},PQ=(N,U)=>{if(N!=="Task"||!MQ())return;if(b0)return xZ();b0=!0;return},hZ=(N)=>{if(N==="Task"&&MQ())b0=!1},fQ=async(N,U,_0)=>Q.toolExecutor.execute(N,U,_0),zQ=kQ({budget:Q.currentModelMaxContextTokens,isSubagent:S}),xQ=new wQ,TZ={},VQ=async(N)=>{for(let U of N){if(!L.getHistory().some((p)=>{let W0=p.metadata;return W0!==null&&typeof W0==="object"&&!Array.isArray(W0)&&W0.inboxMessageId===U.id})){let p=await o(Q,Z,U.content,Y,{inboxMessageId:U.id});if(!p)throw Error(`Failed to persist steering message before applying it: ${U.id}`);Y=p,L.appendUser({role:"user",content:U.content,metadata:{inboxMessageId:U.id}})}let G0=typeof U.content==="string"?U.content:U.content.filter((p)=>p.type==="text").map((p)=>p.text).join(`
|
|
593
|
-
`);if(G0.trim())l=[l,G0].join(`
|
|
594
|
-
`),GQ.push(G0),JQ=[l,Z.completionRequirements?.trim()].filter(Boolean).join(`
|
|
595
|
-
`),U0=[Q.runtimeOptions.appendSystemPrompt?.trim(),Z.completionRequirements?.trim(),...GQ].filter((p)=>Boolean(p)),A0=A0||h0(G0)}return{messageIds:N.map((U)=>U.id),count:N.length,recovered:N.filter((U)=>U.recovered).length}};try{while(!0){if(J?.signal?.aborted)return D(z,V.length,J.signal);let N=await J?.turnSteering?.drain()??[];if(N.length>0)yield{kind:"steering_applied",...await VQ(N),delivery:WQ?"current_turn":"next_turn"},WQ=!0;else if(!WQ)return{success:!0,finalMessage:"",metadata:{turnsCount:0,toolCallsCount:0,duration:Date.now()-W}};if(L.writeback(),(yield*fZ(Q,Z,z,s0,J?.signal,SQ,l,TZ))!=="none")L.replaceHistory(Z.messages);if(z++,xQ.reset(),yield{kind:"turn_start",turn:z,maxTurns:C},J?.signal?.aborted)return D(z-1,V.length,J.signal);if(NZ(z)&&z>1){let w=EZ(z,R.totalFailures);L.appendControl("user",{role:"user",content:`
|
|
596
|
-
|
|
597
|
-
<system-reminder>
|
|
598
|
-
${w}
|
|
599
|
-
</system-reminder>`})}let _0=J?.stream!==!1,G0=b0&&x0(U0)?T.filter((w)=>w.name!=="Task"):T,p=L0;L0=void 0;let W0=p?G0.filter((w)=>w.name===p):G0,hQ=p?{toolChoice:{type:"tool",toolName:p}}:void 0,X,e;try{if(_0)e=new l0(Q.toolExecutor,{sessionId:Z.sessionId,userId:Z.userId||"default",modelId:Q.config.currentModelId,workspaceRoot:Z.workspaceRoot||c(),worktreeIsolationRequired:A0,worktreeActive:m.has("EnterWorktree")&&!m.has("ExitWorktree"),signal:J?.signal,confirmationHandler:Z.confirmationHandler,permissionMode:Z.permissionMode,toolRegistry:b,deferredToolManager:b.deferredToolManager},Q.toolExecutor.getRegistry(),Q.executionEngine?.getContextManager(),Z.sessionId,Y,Z.subagentInfo),e.setAdmissionPolicy(PQ),e.setAdmissionRollback(hZ),e.setExecutionPolicy(fQ),X=yield*X7(Q,L.toLLMMessages(),W0,J?.signal,hQ,e);else X=await Q.chatService.chat(L.toLLMMessages(),W0,J?.signal,hQ)}catch(w){if(z7(w)){x.warn("[Loop] 检测到 prompt_too_long 错误,尝试反应式压缩");let K=Q.chatService.getConfig(),j=await xQ.tryReactiveCompact(Z.messages,{modelName:K.model,modelProvider:K.provider,maxContextTokens:K.maxContextTokens??0,apiKey:K.apiKey,baseURL:K.baseUrl,signal:J?.signal,activeTask:l,workspaceRoot:Z.workspaceRoot||c(),sessionId:Z.sessionId});if(j.success){if(j.usage)yield{kind:"token_usage",usage:a0(j.usage,K.maxContextTokens??0)};Z.messages=j.messages,L.replaceHistory(Z.messages),L0=p,x.info("[Loop] 反应式压缩成功,重试 LLM 调用"),z--;continue}}throw w}if(SQ=Date.now(),X.usage){if(X.usage.totalTokens)a+=X.usage.totalTokens;s0=X.usage.promptTokens,yield{kind:"token_usage",usage:a0(X.usage,Q.currentModelMaxContextTokens)}}let kZ=X.usage?.completionTokens??0;if(zQ=RQ(zQ,kZ,O0>0),J?.signal?.aborted)return D(z-1,V.length,J.signal);if(!_0||!!X._nonStreamingFallback){if(X.reasoningContent&&X.reasoningContent.trim())yield{kind:"thinking_delta",delta:X.reasoningContent};if(X.content&&X.content.trim())yield{kind:"content_delta",delta:X.content}}yield{kind:"stream_end"};let YQ=jQ(X.finishReason,O0,zQ);if(YQ.action==="recover"){O0++,x.warn(`[Loop] Max output tokens hit (recovery ${O0}/3)`);let w={role:"assistant",content:X.content||"",reasoningContent:X.reasoningContent,tool_calls:X.toolCalls};L.appendToHistory(w);let K=await d(Q,Z,X.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 o(Q,Z,j.content,Y);if(B)Y=B;continue}if(YQ.action==="truncated"||YQ.action==="budget_stop"){L.appendAssistant({role:"assistant",content:X.content||"",reasoningContent:X.reasoningContent,tool_calls:X.toolCalls});let w=await d(Q,Z,X.content||"",Y);if(w)Y=w;return{success:!0,finalMessage:X.content,metadata:{turnsCount:z,toolCallsCount:V.length,duration:Date.now()-W,tokensUsed:a,outputTruncated:!0}}}if(X.finishReason!=="length")O0=0;if(!X.toolCalls||X.toolCalls.length===0){let w=await J?.turnSteering?.drain()??[];if(w.length>0){L.appendAssistant({role:"assistant",content:X.content||"",reasoningContent:X.reasoningContent});let _=await d(Q,Z,X.content||"",Y);if(_)Y=_;yield{kind:"steering_applied",...await VQ(w),delivery:"current_turn"};continue}if(X.content&&IZ(v,X.content)){L.appendAssistant({role:"assistant",content:X.content||"",reasoningContent:X.reasoningContent}),L.appendControl("user",{role:"user",content:`
|
|
600
|
-
|
|
601
|
-
<system-reminder>
|
|
602
|
-
${UZ()}
|
|
603
|
-
</system-reminder>`});continue}let K=DQ(X.content,t0,!1);if(K.action==="retry"){t0++,L.appendAssistant({role:"assistant",content:X.content||"",reasoningContent:X.reasoningContent});let _=await d(Q,Z,X.content||"",Y);if(_)Y=_;let u={role:"user",content:K.prompt};L.appendControl("user",u);let g=await o(Q,Z,u.content,Y);if(g)Y=g;continue}t0=0;let j=mQ(U0,m,e0);if(j.action==="retry"){e0++,L0="Task",L.appendAssistant({role:"assistant",content:X.content||"",reasoningContent:X.reasoningContent});let _=await d(Q,Z,X.content||"",Y);if(_)Y=_;let u={role:"user",content:j.prompt};L.appendControl("user",u);let g=await o(Q,Z,u.content,Y);if(g)Y=g;continue}if(j.action==="fail"){L.appendAssistant({role:"assistant",content:X.content||"",reasoningContent:X.reasoningContent});let _=await d(Q,Z,X.content||"",Y);if(_)Y=_;return{success:!1,error:{type:"delegation_protocol_failed",message:j.message},metadata:{turnsCount:z,toolCallsCount:V.length,duration:Date.now()-W,tokensUsed:a}}}e0=0;let B=uQ(l,m,ZQ);if(B.action==="retry"){ZQ++,L.appendAssistant({role:"assistant",content:X.content||"",reasoningContent:X.reasoningContent});let _=await d(Q,Z,X.content||"",Y);if(_)Y=_;let u={role:"user",content:B.prompt};L.appendControl("user",u);let g=await o(Q,Z,u.content,Y);if(g)Y=g;continue}if(B.action==="fail"){L.appendAssistant({role:"assistant",content:X.content||"",reasoningContent:X.reasoningContent});let _=await d(Q,Z,X.content||"",Y);if(_)Y=_;return{success:!1,error:{type:"worktree_protocol_failed",message:B.message},metadata:{turnsCount:z,toolCallsCount:V.length,duration:Date.now()-W,tokensUsed:a}}}ZQ=0;let M=FQ(JQ,$Q,QQ);if(M.action==="retry"){QQ++,L0="Bash",L.appendAssistant({role:"assistant",content:X.content||"",reasoningContent:X.reasoningContent});let _=await d(Q,Z,X.content||"",Y);if(_)Y=_;let u={role:"user",content:M.prompt};L.appendControl("user",u);let g=await o(Q,Z,u.content,Y);if(g)Y=g;continue}if(M.action==="fail"){L.appendAssistant({role:"assistant",content:X.content||"",reasoningContent:X.reasoningContent});let _=await d(Q,Z,X.content||"",Y);if(_)Y=_;return{success:!1,error:{type:"verification_failed",message:M.message},metadata:{turnsCount:z,toolCallsCount:V.length,duration:Date.now()-W,tokensUsed:a}}}QQ=0;let y=await OQ({sessionId:Z.sessionId,permissionMode:Z.permissionMode,reason:X.content,abortSignal:J?.signal});if(y.action==="continue"){L.appendAssistant({role:"assistant",content:X.content||"",reasoningContent:X.reasoningContent});let _=await d(Q,Z,X.content||"",Y);if(_)Y=_;let g={role:"user",content:y.reason?`
|
|
604
|
-
|
|
605
|
-
<system-reminder>
|
|
606
|
-
${y.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",g);let q0=await o(Q,Z,g.content,Y);if(q0)Y=q0;continue}let Q0=await J?.turnSteering?.drainOrSeal();if(Q0&&Q0.messages.length>0){L.appendAssistant({role:"assistant",content:X.content||"",reasoningContent:X.reasoningContent});let _=await d(Q,Z,X.content||"",Y);if(_)Y=_;yield{kind:"steering_applied",...await VQ(Q0.messages),delivery:"current_turn"};continue}L.appendAssistant({role:"assistant",content:X.content||"",reasoningContent:X.reasoningContent});let I=await d(Q,Z,X.content||"",Y);if(I)Y=I;return{success:!0,finalMessage:X.content,metadata:{turnsCount:z,toolCallsCount:V.length,duration:Date.now()-W,tokensUsed:a,toolSuccessRate:V.length>0?V.filter((_)=>_.success).length/V.length:void 0,totalToolFailures:R.totalFailures||void 0}}}L.appendAssistant({role:"assistant",content:X.content||"",reasoningContent:X.reasoningContent,tool_calls:X.toolCalls});{let w=await d(Q,Z,X.content||"",Y);if(w)Y=w}if(J?.signal?.aborted)return D(z,V.length,J.signal);let XQ=X.toolCalls.filter((w)=>w.type==="function"),y0;if(e?.hasTools()){x.debug(`[Loop] 使用 StreamingToolExecutor 收集 ${XQ.length} 个工具结果`),y0=[];for(let w of e.getQueuedToolCalls()){let j=b.get(w.function.name)?.kind;yield{kind:"tool_start",toolCall:w,toolKind:j}}for await(let w of e.getRemainingResults())y0.push(w)}else{let w=new Map;for(let j of XQ){let B=yQ(j.function.arguments),M=B===null?void 0:PQ(j.function.name,B);if(M){w.set(j.id,M);continue}let Q0=b.get(j.function.name)?.kind;yield{kind:"tool_start",toolCall:j,toolKind:Q0}}let K=async(j)=>{try{let B=w.get(j.id);if(B)return{toolCall:j,result:B,toolUseUuid:null};let M=yQ(j.function.arguments);if(M===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 M.subagent_session_id!=="string"||M.subagent_session_id.length===0))M.subagent_session_id=MZ("agent");let y=null;if(y=await bQ(Q,Z,j.function.name,M,Y),j.function.name==="ExitWorktree"&&m.has("EnterWorktree")&&!m.has("ExitWorktree")&&FQ(JQ,$Q,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:y}}let I=await fQ(j.function.name,M,{sessionId:Z.sessionId,userId:Z.userId||"default",modelId:Q.config.currentModelId,workspaceRoot:Z.workspaceRoot||c(),worktreeIsolationRequired:A0,worktreeActive:m.has("EnterWorktree")&&!m.has("ExitWorktree"),signal:J?.signal,confirmationHandler:Z.confirmationHandler,permissionMode:Z.permissionMode,toolRegistry:b,deferredToolManager:b.deferredToolManager});return{toolCall:j,result:I,toolUseUuid:y}}catch(B){return x.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")}}};y0=await Promise.all(XQ.map(K))}let RZ=new EQ;for(let{toolCall:w,result:K,toolUseUuid:j}of y0){let B=w;if(V.push(K),K.metadata?.abortedBeforeLaunch){let I=K.error?.message??"任务已被用户中止";if(j){let _=await T0(Q,Z,j,B.function.name,null,j,I);if(_)Y=_}return L.appendToolResult({role:"tool",tool_call_id:B.id,name:B.function.name,content:`Error: ${I}`}),D(z,V.length,J?.signal)}yield{kind:"tool_result",toolCall:B,result:K};{let I=K.metadata&&typeof K.metadata==="object"?K.metadata:void 0,u=((S0)=>S0==="running"||S0==="completed"||S0==="failed"||S0==="cancelled")(I?.subagentStatus)?I.subagentStatus:"completed",g=I&&typeof I.subagentSessionId==="string"?{subagentSessionId:I.subagentSessionId,subagentType:typeof I.subagentType==="string"?I.subagentType:B.function.name,subagentStatus:u,subagentSummary:typeof I.subagentSummary==="string"?I.subagentSummary:void 0,subagentResumedFrom:typeof I.subagentResumedFrom==="string"?I.subagentResumedFrom:void 0,subagentRootId:typeof I.subagentRootId==="string"?I.subagentRootId:void 0,subagentResumeDepth:typeof I.subagentResumeDepth==="number"?I.subagentResumeDepth:void 0}:void 0,q0=await T0(Q,Z,j??B.id,B.function.name,K.success?Z7(K.llmContent):null,j,K.success?void 0:K.error?.message,g);if(q0)Y=q0}let M=await _Q(B,K,Q,Z);if(M)yield M;if(K.success){if(_Z(R,B.function.name),B.function.name==="EnterWorktree"&&K.metadata?.workspaceTransition==="enter")m.add("EnterWorktree"),m.delete("ExitWorktree");else if(B.function.name==="ExitWorktree"&&K.metadata?.workspaceTransition==="exit"&&m.has("EnterWorktree"))m.add("ExitWorktree");else if(!["EnterWorktree","ExitWorktree"].includes(B.function.name))m.add(B.function.name);if(B.function.name==="Task"&&K.metadata?.isolation==="worktree")m.add("TaskWorktree");dQ($Q,B.function.name,K)}else qZ(R,B.function.name);let y=K.success?K.llmContent||"":W7(B.function.name,K.error);if(!K.success){let I=wZ(R,B.function.name);if(I&&typeof y==="string")y=`${y}
|
|
612
|
-
|
|
613
|
-
${I}`}if(typeof y==="object"&&y!==null)y=JSON.stringify(y,null,2);if(typeof y==="string")y=zZ(y,B.function.name,{messageBudget:RZ});let Q0=typeof y==="string"?y:JSON.stringify(y);if(L.appendToolResult({role:"tool",tool_call_id:B.id,name:B.function.name,content:Q0,...B.function.name==="Task"?{metadata:{toolCallId:B.id,toolName:B.function.name,error:K.success?null:K.error?.message??null}}:{}}),K.metadata?.shouldExitLoop){let I=typeof K.llmContent==="string"?K.llmContent:"循环已退出";return{success:K.success,finalMessage:I,metadata:{turnsCount:z,toolCallsCount:V.length,duration:Date.now()-W,shouldExitLoop:!0,targetMode:K.metadata?.targetMode,planContent:typeof K.metadata?.planContent==="string"?K.metadata.planContent:void 0}}}}if(J?.signal?.aborted)return D(z,V.length,J.signal);let HQ=z>=r0,CZ=z>=C&&(o0||!r||S);if(HQ||CZ){let w=HQ?r0:C;if(x.info(`Warning: 达到轮次上限 ${w} 轮`),J?.onTurnLimitReached){let K=await J.onTurnLimitReached({turnsCount:z});if(K?.continue){L.writeback();try{let j=Q.chatService.getConfig(),B=await D0.compact(Z.messages,{trigger:"auto",modelName:j.model,modelProvider:j.provider,maxContextTokens:j.maxContextTokens??0,apiKey:j.apiKey,baseURL:j.baseUrl,actualPreTokens:s0,signal:J?.signal,activeTask:l,workspaceRoot:Z.workspaceRoot||c(),sessionId:Z.sessionId});if(B.usage)yield{kind:"token_usage",usage:a0(B.usage,j.maxContextTokens??0)};Z.messages=B.compactedMessages,L.replaceHistory(Z.messages);let M={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(M),await k0(Q,Z,B.summary,{trigger:"auto",preTokens:B.preTokens,postTokens:B.postTokens,filesIncluded:B.filesIncluded})}catch(j){x.error("[Loop] 压缩失败,使用降级策略:",j);let M=L.getHistory().slice(-80);L.replaceHistory(M)}z=0;continue}return{success:!0,finalMessage:K?.reason||"已达到对话轮次上限,用户选择停止",metadata:{turnsCount:z,toolCallsCount:V.length,duration:Date.now()-W,tokensUsed:a}}}return{success:!1,error:{type:"max_turns_exceeded",message:S?`子代理已达到轮次上限 (${w} 轮)。`:`已达到${HQ?"安全":"显式"}轮次上限 (${w} 轮)。`},metadata:{turnsCount:z,toolCallsCount:V.length,duration:Date.now()-W,tokensUsed:a}}}}}finally{if(J?.transientInput==="goal_continuation")L.removeMessages((N)=>{let U=N.metadata;return U!==null&&typeof U==="object"&&!Array.isArray(U)&&U.transientGoalContinuation===!0});L.writeback()}}catch(b){if(H0(b))return D(z,V.length,J?.signal);let F=J7(b);return x.error(`API 调用失败: ${F}`),{success:!1,error:{type:"api_error",message:F,details:b},metadata:{turnsCount:z,toolCallsCount:V.length,duration:Date.now()-W}}}finally{if(H)Z.messages.push({role:"system",content:LQ}),await iQ(Q,Z,Y)}}export{qQ as Za,HZ as _a,DZ as $a,n0 as ab,m2 as bb,X0 as cb,Z0 as db,jQ as eb,DQ as fb,dQ as gb,OQ as hb,M0 as ib,P0 as jb,pZ as kb,o as lb,d as mb,bQ as nb,T0 as ob,k0 as pb,nQ as qb,lQ as rb,rQ as sb,_Q as tb,N0 as ub,D0 as vb,l0 as wb,fZ as xb,B7 as yb};
|