blade-code 0.6.4 → 0.7.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/dist/blade.js +2 -2
- package/dist/{chunk-j7nh0j36.js → chunk-0afbeec0.js} +1 -1
- package/dist/chunk-0k8js58t.js +6 -0
- package/dist/chunk-0vd9antx.js +1 -0
- package/dist/{chunk-w96xaeyd.js → chunk-1dt2y16n.js} +1 -1
- package/dist/{chunk-jm9r362m.js → chunk-2dvn9y9f.js} +1 -1
- package/dist/{chunk-hc91pmdk.js → chunk-56frm8dx.js} +1 -1
- package/dist/chunk-6jezjq4h.js +6 -0
- package/dist/chunk-6k4vs71p.js +1 -0
- package/dist/chunk-70ya127f.js +1 -0
- package/dist/{chunk-sfr69fw8.js → chunk-7v7s2aag.js} +2 -2
- package/dist/{chunk-nm2w2ftg.js → chunk-7z6ba6t9.js} +1 -1
- package/dist/{chunk-m41xq6d0.js → chunk-867h27ke.js} +4 -4
- package/dist/chunk-92qcc3gj.js +2138 -0
- package/dist/{chunk-ck43cs45.js → chunk-a2nshjdc.js} +2 -2
- package/dist/chunk-a7dw8fwn.js +1 -0
- package/dist/chunk-a8eedntd.js +6 -0
- package/dist/{chunk-59e6eg4b.js → chunk-aam53te2.js} +6 -6
- package/dist/{chunk-evc1xkeb.js → chunk-b0q2q0ax.js} +1 -1
- package/dist/{chunk-ey640ttd.js → chunk-bmxgshct.js} +1 -1
- package/dist/chunk-d3db8wrw.js +1 -0
- package/dist/chunk-dzmrdtpc.js +612 -0
- package/dist/chunk-e06p3dkw.js +157 -0
- package/dist/{chunk-f24ahjpc.js → chunk-f76d6jxg.js} +1 -1
- package/dist/chunk-f8mjpmdx.js +4 -0
- package/dist/chunk-h7qab07x.js +2 -0
- package/dist/{chunk-h46kk20y.js → chunk-k9h9bw13.js} +2 -2
- package/dist/chunk-m51xzgwt.js +1 -0
- package/dist/{chunk-bpx8x87m.js → chunk-mt1c5da4.js} +2 -2
- package/dist/chunk-qdnx9x5g.js +2 -0
- package/dist/chunk-qds0yxfy.js +41 -0
- package/dist/chunk-qyfdt8h1.js +2 -0
- package/dist/chunk-r6paqm6d.js +1 -0
- package/dist/chunk-v0rjbvky.js +9 -0
- package/dist/{chunk-cfe1fywb.js → chunk-v1d0d4b4.js} +2 -2
- package/dist/chunk-vs915jzz.js +1 -0
- package/dist/chunk-xmdpc0y5.js +2 -0
- package/dist/chunk-zbtb3jxm.js +1 -0
- package/dist/{chunk-sh1pk5j3.js → chunk-zm4jr1k2.js} +1 -1
- package/dist/chunk-zvk6ktj1.js +6 -0
- package/dist/{chunk-m26jr2tg.js → chunk-zxddgwsb.js} +1 -1
- package/dist/web/assets/{FilePreview-R1mRzyRz.js → FilePreview-DLnUh-wQ.js} +1 -1
- package/dist/web/assets/{MarkdownRenderer-B46lJYAn.js → MarkdownRenderer-C5KTk9XG.js} +1 -1
- package/dist/web/assets/{McpModal-QRv5Ij61.js → McpModal-B9qJ4ewt.js} +1 -1
- package/dist/web/assets/{SettingsModal-D-mi6mUR.js → SettingsModal-DpeZ6cJb.js} +1 -1
- package/dist/web/assets/{SettingsStore-Dmo3sZ_R.js → SettingsStore-IzKtyAnM.js} +1 -1
- package/dist/web/assets/{SkillsModal-DNXjbjEs.js → SkillsModal-BDfzgJIj.js} +1 -1
- package/dist/web/assets/{TerminalPanel-DG_Q4UKr.js → TerminalPanel-B2iTF_CR.js} +1 -1
- package/dist/web/assets/{dialog-CsiChiYt.js → dialog-sI3ihAze.js} +1 -1
- package/dist/web/assets/{index-BeYCsOvo.js → index-D8mo0jzF.js} +8 -8
- package/dist/web/index.html +1 -1
- package/package.json +4 -2
- package/dist/chunk-07xv0cqp.js +0 -1
- package/dist/chunk-0e9dhemy.js +0 -41
- package/dist/chunk-2zk921d9.js +0 -1
- package/dist/chunk-3mmm8g84.js +0 -1
- package/dist/chunk-5bs94pb1.js +0 -157
- package/dist/chunk-6mfmy7nq.js +0 -8
- package/dist/chunk-7c9k2c9m.js +0 -1
- package/dist/chunk-7t23swne.js +0 -2125
- package/dist/chunk-9p4fe43p.js +0 -1
- package/dist/chunk-9vsbmtqj.js +0 -1
- package/dist/chunk-dmc5gf4f.js +0 -6
- package/dist/chunk-k063tt5h.js +0 -1
- package/dist/chunk-mpn4zfcn.js +0 -6
- package/dist/chunk-njq4w631.js +0 -613
- package/dist/chunk-p8pggabj.js +0 -2
- package/dist/chunk-qnvkxpkw.js +0 -2
- package/dist/chunk-tdarh4fh.js +0 -1
- package/dist/chunk-tz44akn7.js +0 -6
- package/dist/chunk-vxgexcsm.js +0 -1
- package/dist/chunk-zm78rg9t.js +0 -6
- package/dist/chunk-zwwvv85t.js +0 -4
|
@@ -0,0 +1,612 @@
|
|
|
1
|
+
import{rb as F0}from"./chunk-qds0yxfy.js";import{xb as p}from"./chunk-7ycmx7c2.js";import{Bb as zZ,Cb as o,Db as $Z,Eb as PQ}from"./chunk-v0rjbvky.js";import{Gb as EQ,Ob as R}from"./chunk-mt1c5da4.js";function D0(Q){return Q.role==="system"&&Array.isArray(Q.content)}class b0{systemMessages;_history;_pending=[];context;constructor(Q,Z){this.context=Q;let $=Q.messages.find(D0);if($)this.systemMessages=[$];else if(Z)this.systemMessages=[{role:"system",content:[{type:"text",text:Z,providerOptions:{anthropic:{cacheControl:{type:"ephemeral"}}}}]}];else this.systemMessages=[];this._history=Q.messages.filter((J)=>!D0(J))}get historyLength(){return this._history.length}get history(){return this._history}get pending(){return this._pending}toLLMMessages(){return[...this.systemMessages,...this._history,...this._pending]}getMessagesForLLM(){return this.toLLMMessages()}getHistory(){return this._history}appendPending(Q){this._pending.push(Q)}appendUser(Q){this._pending.push(Q)}appendAssistant(Q){this._pending.push(Q)}appendToolResult(Q){this._pending.push(Q)}appendControl(Q,Z){if(Q==="system")throw Error("Cannot append system control message via appendControl. Use constructor for root system prompt.");this._pending.push(Z)}appendToHistory(Q){this._history.push(Q)}commitPending(){if(this._pending.length>0)this._history.push(...this._pending),this._pending=[]}replaceHistory(Q){this._history=Q.filter((Z)=>!D0(Z))}writeback(){this.commitPending(),this.context.messages=this._history}get hasSystemPrompt(){return this.systemMessages.length>0}}async function KZ(Q,Z){let $;while(!($=await Q.next()).done)if(Z)await Z($.value);return $.value}function BQ(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 jQ(Q){return{budget:Q.budget,usage:0,consecutiveContinuations:0,lastOutputDelta:0,isSubagent:Q.isSubagent??!1}}function qQ(Q,Z,$){return{...Q,usage:Q.usage+Z,lastOutputDelta:Z,consecutiveContinuations:$?Q.consecutiveContinuations+1:0}}var g0=R("Agent"),BZ=3;function c0(Q,Z,$){if(Q!=="length")return{action:"none"};if(Z>=BZ)return{action:"truncated"};if(BQ($)==="stop")return g0.info("[Loop] Token budget: diminishing returns detected, skipping recovery"),{action:"budget_stop"};return{action:"recover"}}var jZ=[/:\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],qZ=/```[\s\S]{50,}```/,DQ="请执行你提到的操作,不要只是描述。使用 Edit/Write/Bash 工具来实际修改文件。",DZ=2;function u0(Q,Z,$=!0){if(!Q||Z>=DZ)return{action:"none"};if(!$&&qZ.test(Q))return{action:"retry",prompt:DQ};let J=Q.slice(-200),z=J.match(/```/g);if(z&&z.length%2!==0)return{action:"none"};if(jZ.some((G)=>G.test(J)))return{action:"retry",prompt:DQ};return{action:"none"}}var bZ=[/\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}(?:测试|单测|集成测试|检查|构建)/],FZ=/(?:^|\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,bQ={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},OZ={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},wZ="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.",LZ="Required verification did not run successfully before the retry limit.",_Z=3;function m0(Q){return FZ.test(Q)}function OQ(Q,Z,$){if(!$.success)return;if(["Edit","Write","NotebookEdit"].includes(Z)){Q.clear();return}if(Z==="Bash"&&typeof $.metadata?.command==="string"&&$.metadata.exit_code===0&&m0($.metadata.command)){Q.add($.metadata.command);return}if(!["Task","TaskOutput"].includes(Z))return;let J=$.metadata?.verificationCommands;if(!Array.isArray(J))return;for(let z of J)if(typeof z==="string"&&m0(z))Q.add(z)}function i0(Q,Z,$){if(!Q||!bZ.some((Y)=>Y.test(Q)))return{action:"none"};let J=Object.keys(bQ).filter((Y)=>bQ[Y].test(Q)),z=[...Z],W=J.filter((Y)=>!z.some((B)=>OZ[Y].test(B)));if(J.length>0?W.length===0:z.some(m0))return{action:"none"};if($>=_Z)return{action:"fail",message:LZ};let V=J.length>1&&W.length>0?` Missing successful verification categories: ${W.join(", ")}.`:"";return{action:"retry",prompt:`${wZ}${V}`}}var vZ=[/\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|子代理|子智能体)/],NZ=[/\b(?:do not|don't|never)\s+(?:delegate|call|use|invoke)\b/i,/(?:不要|禁止|无需)(?:委派|调用|使用).{0,20}(?:Task|子代理|子智能体)?/],IZ="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.",SZ="Required delegation did not complete before the retry limit.",UZ=3;function wQ(Q,Z,$){if(!Q||NZ.some((J)=>J.test(Q))||!vZ.some((J)=>J.test(Q))||Z.has("Task"))return{action:"none"};if($>=UZ)return{action:"fail",message:SZ};return{action:"retry",prompt:IZ}}var EZ=[/\b(?:use|create|enter|start|work\s+(?:in|inside))\b.{0,60}\bworktree\b/i,/(?:使用|创建|进入).{0,30}(?:worktree|工作树)/i],yZ=[/\b(?:exit|leave)\b.{0,40}\bworktree\b/i,/\bworktree\b.{0,60}\b(?:action\s+)?(?:keep|remove)\b/i,/(?:退出|离开).{0,30}(?:worktree|工作树)/i];function n0(Q){return typeof Q==="string"&&EZ.some((Z)=>Z.test(Q))}var AZ="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.",PZ="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.",MZ="Required worktree lifecycle did not complete before the retry limit.",fZ=3;function LQ(Q,Z,$){if(!Q||!n0(Q))return{action:"none"};let J=yZ.some((W)=>W.test(Q));if(Z.has("TaskWorktree"))return{action:"none"};let z=!Z.has("EnterWorktree")?"EnterWorktree":J&&!Z.has("ExitWorktree")?"ExitWorktree":void 0;if(!z)return{action:"none"};if($>=fZ)return{action:"fail",message:MZ};return{action:"retry",tool:z,prompt:z==="EnterWorktree"?AZ:PZ}}var FQ=30000;async function l0(Q){try{let $=F0.getInstance().executeStopHooks({projectDir:p(),sessionId:Q.sessionId,permissionMode:Q.permissionMode,reason:Q.reason,abortSignal:Q.abortSignal}),J,z=new Promise((W)=>{J=setTimeout(()=>W("timeout"),FQ)});try{let W=await Promise.race([$,z]);if(W==="timeout")return g0.warn(`[Loop] Stop hook 超时 (${FQ}ms),按 shouldStop: true 处理`),{action:"stop"};let G=W;if(!G.shouldStop)return{action:"continue",reason:G.continueReason};return{action:"stop"}}finally{clearTimeout(J)}}catch(Z){return g0.warn("[Loop] Stop hook execution failed:",Z),{action:"stop"}}}var t=R("Agent"),a0=`<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 e(Q){return Q.executionEngine?.getContextManager()}async function m(Q,Z,$,J=null){try{let z=e(Q),W=typeof $==="string"?$.trim()!=="":$.some((G)=>G.type==="text"?G.text.trim()!=="":!0);if(z&&Z.sessionId&&W)return await z.saveMessage(Z.sessionId,"user",$,J,void 0,Z.subagentInfo)}catch(z){t.warn("[Loop] 保存用户消息失败:",z)}return null}async function T(Q,Z,$,J){try{let z=e(Q);if(z&&Z.sessionId&&$.trim())return await z.saveMessage(Z.sessionId,"assistant",$,J,void 0,Z.subagentInfo)}catch(z){t.warn("[Loop] 保存助手消息失败:",z)}return null}async function _Q(Q,Z,$){try{let J=e(Q);if(J&&Z.sessionId)return await J.saveMessage(Z.sessionId,"system",a0,$,void 0,Z.subagentInfo)}catch(J){t.warn("[Loop] 保存中断边界失败:",J)}return null}async function r0(Q,Z,$,J,z){try{let W=e(Q);if(W&&Z.sessionId)return await W.saveToolUse(Z.sessionId,$,J,z,Z.subagentInfo)}catch(W){t.warn("[Loop] 保存工具调用失败:",W)}return null}async function o0(Q,Z,$,J,z,W,G,V){try{let Y=e(Q);if(Y&&Z.sessionId)return await Y.saveToolResult(Z.sessionId,$,J,z,W,G,Z.subagentInfo,V)}catch(Y){t.warn("[Loop] 保存工具结果失败:",Y)}return null}async function O0(Q,Z,$,J){try{let z=e(Q);if(z&&Z.sessionId)return await z.saveCompaction(Z.sessionId,$,J,null)}catch(z){t.warn("[Loop] 保存压缩数据失败:",z)}return null}function vQ(Q,Z){if(!["TaskCreate","TaskUpdate","TaskList"].includes(Q.function.name)||!Z.success||!Z.llmContent&&!Z.metadata)return null;let $=typeof Z.llmContent==="object"?Z.llmContent:{};return{kind:"task_update",tasks:Z.metadata?.tasks||$.tasks||[]}}function NQ(Q,Z,$){if(Q.function.name!=="Skill"||!Z.success||!Z.metadata)return;let J=Z.metadata;if(J.skillName)$.onSkillActivated?.({skillName:J.skillName,allowedTools:J.allowedTools,basePath:J.basePath||""})}function IQ(Q){let Z=Q.metadata;if(!Z)return;return Z.modelId?.toString().trim()||Z.model?.toString().trim()||void 0||void 0}function hZ(Q,Z,$){if(!["EnterWorktree","ExitWorktree"].includes(Q.function.name)||!Z.success)return;let J=Z.metadata,z=J?.workspaceRoot;if(!["enter","exit"].includes(String(J?.workspaceTransition))||typeof z!=="string"||z.trim()==="")return;return $.workspaceRoot=z,$.worktreeActive=J?.workspaceTransition==="enter",z}function kZ(Q,Z){if(Q.function.name!=="Task")return null;let $=Z.metadata;if(!$?.subagentSessionId)return null;let J=$.subagentSessionId,z=$.subagentType||"Task",W=$.subagentStatus;if(W==="completed"||W==="failed"||W==="cancelled")return{kind:"subagent_completed",sessionId:J,success:W==="completed",summary:$.subagentSummary};if(W==="running"){let G="";try{G=JSON.parse(Q.function.arguments).prompt||""}catch{}return{kind:"subagent_spawned",sessionId:J,type:z,prompt:G}}return null}async function s0(Q,Z,$,J){let z=vQ(Q,Z),W=kZ(Q,Z);NQ(Q,Z,$);let G=IQ(Z);if(G)await $.onModelSwitch?.(G);if(J)hZ(Q,Z,J);return W||z}import{nanoid as j2}from"nanoid";import{promises as mZ}from"node:fs";import{nanoid as i}from"nanoid";import*as E from"node:fs/promises";import*as r from"node:path";var SQ={enabled:!0,maxIndexLines:200};var xZ="memory",UQ="MEMORY.md";class t0{memoryDir;config;initialized=!1;constructor(Q,Z,$){if($)this.memoryDir=$;else{let J=EQ(Q);this.memoryDir=r.join(J,xZ)}this.config={...SQ,...Z}}async initialize(){if(this.initialized)return;await E.mkdir(this.memoryDir,{recursive:!0}),this.initialized=!0}async loadIndex(){if(!this.config.enabled)return null;await this.initialize();let Q=r.join(this.memoryDir,UQ);try{let Z=await E.readFile(Q,"utf-8");if(!Z.trim())return null;let $=Z.split(`
|
|
4
|
+
`),z=$.slice(0,this.config.maxIndexLines).join(`
|
|
5
|
+
`).trim();if($.length>this.config.maxIndexLines)return z+`
|
|
6
|
+
|
|
7
|
+
<!-- ${$.length-this.config.maxIndexLines} more lines in MEMORY.md, use MemoryRead to access -->`;return z||null}catch(Z){if(Z instanceof Error&&"code"in Z&&Z.code==="ENOENT")return null;throw Z}}async readTopic(Q){await this.initialize();let Z=this.resolveTopicPath(Q);try{return await E.readFile(Z,"utf-8")||null}catch($){if($ instanceof Error&&"code"in $&&$.code==="ENOENT")return null;throw $}}async writeTopic(Q,Z,$="append"){await this.initialize();let J=this.resolveTopicPath(Q);if($==="append"){let z="";try{z=await E.readFile(J,"utf-8")}catch{}let W=z&&!z.endsWith(`
|
|
8
|
+
`)?`
|
|
9
|
+
`:"";await E.writeFile(J,z+W+Z,"utf-8")}else await E.writeFile(J,Z,"utf-8")}async updateIndex(Q,Z="overwrite"){await this.initialize();let $=r.join(this.memoryDir,UQ);if(Z==="append"){let J="";try{J=await E.readFile($,"utf-8")}catch{}let z=J&&!J.endsWith(`
|
|
10
|
+
`)?`
|
|
11
|
+
`:"";await E.writeFile($,J+z+Q,"utf-8")}else await E.writeFile($,Q,"utf-8")}async listTopics(){await this.initialize();try{let Q=await E.readdir(this.memoryDir,{withFileTypes:!0}),Z=[];for(let $ of Q){if(!$.isFile()||!$.name.endsWith(".md"))continue;let J=r.join(this.memoryDir,$.name),z=await E.stat(J);Z.push({name:$.name.replace(/\.md$/,""),size:z.size,lastModified:z.mtime})}return Z.sort(($,J)=>J.lastModified.getTime()-$.lastModified.getTime())}catch{return[]}}async deleteTopic(Q){let Z=this.resolveTopicPath(Q);try{return await E.unlink(Z),!0}catch{return!1}}async clearAll(){let Q=await this.listTopics(),Z=0;for(let $ of Q){let J=r.join(this.memoryDir,`${$.name}.md`);try{await E.unlink(J),Z++}catch{}}return Z}getMemoryDir(){return this.memoryDir}resolveTopicPath(Q){let Z=Q.replace(/[/\\:*?"<>|]/g,"-"),$=Z.endsWith(".md")?Z:`${Z}.md`,J=r.join(this.memoryDir,$);if(!J.startsWith(this.memoryDir))throw Error(`Invalid topic name: ${Q}`);return J}}var RZ=[{pattern:/(?:记住|remember|note|备注)[::](.+)/i,topic:"preferences"},{pattern:/(?:convention|约定|规范)[::](.+)/i,topic:"conventions"},{pattern:/(?:lesson|教训|踩坑)[::](.+)/i,topic:"lessons"}],TZ=/(?:fix|修复|解决|resolved)[::]\s*(.+?)(?:\n|$)/i,CZ=/(?:Error|FAIL|错误)[::]\s*(.+?)(?:\n|$)/i;function pZ(Q){let Z=new Map;for(let $ of Q){if(!$.content||typeof $.content!=="string")continue;let J=$.content;if($.role==="user")for(let{pattern:z,topic:W}of RZ){let G=J.match(z);if(G?.[1]){let V=Z.get(W)??[];V.push(G[1].trim()),Z.set(W,V)}}if($.role==="assistant"){let z=J.match(TZ);if(z?.[1]&&z[1].length>20&&z[1].length<200){let W=Z.get("debugging")??[];W.push(z[1].trim()),Z.set("debugging",W)}}if($.role==="tool"&&$.content?.includes("Error")){let z=J.match(CZ);if(z?.[1]&&z[1].length>10){let W=Z.get("debugging")??[];if(W.length<5)W.push(`Tool error pattern: ${z[1].trim().slice(0,150)}`),Z.set("debugging",W)}}}return Z}async function yQ(Q){let Z=pZ(Q);if(Z.size===0)return{extracted:0,topics:[]};try{let $=new t0(p());await $.initialize();let J=[],z=0;for(let[W,G]of Z){if(G.length===0)continue;let V=new Date().toISOString().split("T")[0],Y=G.map((B)=>`- [${V}] ${B}`).join(`
|
|
12
|
+
`);await $.writeTopic(W,Y+`
|
|
13
|
+
`,"append"),J.push(W),z+=G.length}return{extracted:z,topics:J}}catch{return{extracted:0,topics:[]}}}import{promises as w0}from"node:fs";var G0=R("Tool");class u{static instance=null;accessedFiles=new Map;constructor(){}static getInstance(){if(!u.instance)u.instance=new u;return u.instance}async recordFileRead(Q,Z){try{let $=await w0.stat(Q),J={filePath:Q,accessTime:Date.now(),mtime:$.mtimeMs,sessionId:Z,lastOperation:"read"};this.accessedFiles.set(Q,J),G0.debug(`记录文件读取: ${Q}`)}catch($){G0.warn(`记录文件读取失败: ${Q}`,$)}}async recordFileEdit(Q,Z,$="edit"){try{let J=await w0.stat(Q),z={filePath:Q,accessTime:Date.now(),mtime:J.mtimeMs,sessionId:Z,lastOperation:$};this.accessedFiles.set(Q,z),G0.debug(`记录文件${$==="edit"?"编辑":"写入"}: ${Q}`)}catch(J){G0.warn(`记录文件${$==="edit"?"编辑":"写入"}失败: ${Q}`,J)}}hasFileBeenRead(Q,Z){let $=this.accessedFiles.get(Q);if(!$)return!1;if(Z&&$.sessionId!==Z)return!1;return!0}async checkFileModification(Q){let Z=this.accessedFiles.get(Q);if(!Z)return{modified:!1,message:"文件未被跟踪"};try{let $=await w0.stat(Q);if(Math.abs($.mtimeMs-Z.mtime)>1)return{modified:!0,message:`文件在访问后被修改(访问时间: ${new Date(Z.accessTime).toISOString()}, 当前修改时间: ${$.mtime.toISOString()})`};return{modified:!1}}catch($){let J=$;if(J.code==="ENOENT")return{modified:!0,message:"文件已被删除"};return{modified:!1,message:`无法检查文件状态: ${J.message}`}}}async checkExternalModification(Q){let Z=this.accessedFiles.get(Q);if(!Z)return{isExternal:!1,message:"文件未被跟踪"};try{let $=await w0.stat(Q);if($.mtimeMs-Z.mtime>2000)return{isExternal:!0,message:`文件在 ${new Date(Z.accessTime).toISOString()} (${Z.lastOperation}) 之后被外部程序修改(当前修改时间: ${$.mtime.toISOString()})`};return{isExternal:!1}}catch($){let J=$;if(J.code==="ENOENT")return{isExternal:!0,message:"文件已被删除"};return G0.warn(`检查文件外部修改失败: ${Q}`,$),{isExternal:!1,message:`无法检查文件状态: ${J.message}`}}}getFileRecord(Q){return this.accessedFiles.get(Q)}clearFileRecord(Q){this.accessedFiles.delete(Q)}clearAll(){this.accessedFiles.clear()}clearSession(Q){for(let[Z,$]of this.accessedFiles.entries())if($.sessionId===Q)this.accessedFiles.delete(Z)}getTrackedFiles(){return Array.from(this.accessedFiles.keys())}getTrackedFileCount(){return this.accessedFiles.size}static resetInstance(){u.instance=null}}import{readFile as dZ}from"node:fs/promises";import{basename as gZ}from"node:path";class L0{static MAX_FILES=5;static MAX_LINES_PER_FILE=1000;static analyzeFiles(Q){let Z=new Map;return Q.forEach((J,z)=>{let W=typeof J.content==="string"?J.content:(J.content||[]).filter((V)=>V.type==="text").map((V)=>V.text).join(`
|
|
14
|
+
`);if(this.extractFilePathsFromContent(W).forEach((V)=>{this.updateFileReference(Z,V,z,!1)}),J.tool_calls&&Array.isArray(J.tool_calls))J.tool_calls.forEach((V)=>{let Y=this.extractFilePathsFromToolCall(V),B=V.type==="function"&&"function"in V?V.function?.name:"",q=["Write","Edit"].includes(B||"");Y.forEach((b)=>{this.updateFileReference(Z,b,z,q)})})}),Array.from(Z.values()).sort((J,z)=>{if(J.wasModified!==z.wasModified)return J.wasModified?-1:1;if(J.mentions!==z.mentions)return z.mentions-J.mentions;return z.lastMentioned-J.lastMentioned}).slice(0,this.MAX_FILES)}static async readFilesContent(Q){let Z=[];for(let $ of Q)try{let J=await dZ($,"utf-8"),z=J.split(`
|
|
15
|
+
`),W=z.length,G=J,V=!1,Y=W;if(W>this.MAX_LINES_PER_FILE)G=z.slice(0,this.MAX_LINES_PER_FILE).join(`
|
|
16
|
+
`),G+=`
|
|
17
|
+
|
|
18
|
+
... (truncated ${W-this.MAX_LINES_PER_FILE} lines)`,V=!0,Y=this.MAX_LINES_PER_FILE;Z.push({path:$,content:G,truncated:V,lines:W,includedLines:Y})}catch(J){console.warn(`[FileAnalyzer] 无法读取文件: ${$}`,J)}return Z}static extractFilePathsFromContent(Q){let Z=new Set,$=/```(?:\w+)?\s*\n?([\s\S]*?)```/g,J=Array.from(Q.matchAll($));for(let W of J){let G=W[1];this.extractPathsFromText(G).forEach((Y)=>Z.add(Y))}return this.extractPathsFromText(Q).forEach((W)=>Z.add(W)),Array.from(Z)}static extractPathsFromText(Q){let Z=[],$=[/(?:src|tests?|docs?|lib|config|scripts?|bin|utils?|components?|services?|hooks?)\/[\w\-/.]+\.[\w]+/g,/(?:package|tsconfig|vite\.config|webpack\.config|next\.config|babel\.config)\.[\w]+/g,/(?:\.\.?\/|\/)[a-zA-Z0-9\-_/.]+\.[\w]+/g];for(let J of $){let z=Array.from(Q.matchAll(J));for(let W of z){let G=W[0];if(G=G.replace(/[,。;:!?""''()【】《》]$/g,""),G=G.replace(/[,.;:!?"'()[\]<>]$/g,""),this.isValidFilePath(G))Z.push(G)}}return Z}static extractFilePathsFromToolCall(Q){let Z=[];if(Q.type!=="function"||!Q.function)return Z;try{let $=Q.function.name,J=JSON.parse(Q.function.arguments||"{}");if(["Read","Write","Edit","Glob","Grep","NotebookEdit","mcp__github__get_file_contents","mcp__github__create_or_update_file"].includes($)){let W=["file_path","path","notebook_path","filePath"];for(let G of W)if(J[G]&&typeof J[G]==="string")Z.push(J[G])}}catch{}return Z}static updateFileReference(Q,Z,$,J){let z=Q.get(Z);if(z)z.mentions++,z.lastMentioned=$,z.wasModified=z.wasModified||J;else Q.set(Z,{path:Z,mentions:1,lastMentioned:$,wasModified:J})}static isValidFilePath(Q){if(!Q.includes("/"))return!1;let Z=gZ(Q);if(!Z.includes("."))return!1;let $=["ts","tsx","js","jsx","json","md","py","java","go","rs","c","cpp","h","css","scss","html","xml","yaml","yml","toml","sh","bash","sql","graphql","vue","svelte"],J=Z.split(".").pop()?.toLowerCase();if(!J||!$.includes(J))return!1;return!0}}import{encodingForModel as AQ}from"js-tiktoken";class Y0{static encodingCache=new Map;static countTokens(Q,Z){let $=this.getEncoding(Z),J=0;for(let z of Q){if(J+=4,z.role)J+=$.encode(z.role).length;if(z.content)if(typeof z.content==="string")J+=$.encode(z.content).length;else J+=$.encode(JSON.stringify(z.content)).length;if(z.tool_calls&&Array.isArray(z.tool_calls))J+=this.countToolCallTokens(z.tool_calls,$);if(z.name)J+=$.encode(z.name).length}return J}static getTokenLimit(Q){return Q}static shouldCompact(Q,Z,$,J=0.8){let z=this.countTokens(Q,Z),W=Math.floor($*J);return z>=W}static getEncoding(Q){if(!this.encodingCache.has(Q))try{let Z=AQ(Q);this.encodingCache.set(Q,Z)}catch{try{let Z=AQ("gpt-4");this.encodingCache.set(Q,Z)}catch{console.warn(`[TokenCounter] 无法为模型 ${Q} 获取 encoding,使用粗略估算`),this.encodingCache.set(Q,{encode:(Z)=>{return Array(Math.ceil(Z.length/4))}})}}return this.encodingCache.get(Q)}static countToolCallTokens(Q,Z){let $=0;for(let J of Q){if($+=4,J.type==="function"&&J.function?.name)$+=Z.encode(J.function.name).length;if(J.type==="function"&&J.function?.arguments)$+=Z.encode(J.function.arguments).length;if(J.id)$+=Z.encode(J.id).length}return $}static clearCache(){this.encodingCache.clear()}static estimateTokens(Q){let Z=(Q.match(/[\u4e00-\u9fa5]/g)||[]).length,$=Q.length-Z;return Math.ceil(Z/1.5+$/4)}}var M=R("Context"),_0=new Map,cZ=3;class Q0{static THRESHOLD_PERCENT=0.8;static RETAIN_PERCENT=0.2;static FALLBACK_RETAIN_PERCENT=0.3;static ACTIVE_TASK_MAX_CHARS=6000;static async compact(Q,Z){if(Z.signal?.aborted)throw new DOMException("Aborted","AbortError");let $=Z.actualPreTokens??Y0.countTokens(Q,Z.modelName),J=Z.actualPreTokens?"actual (from LLM usage)":"estimated";M.debug(`[CompactionService] preTokens source: ${J}`);try{let V=await F0.getInstance().executeCompactionHooks(Z.trigger,{projectDir:p(),sessionId:Z.sessionId||"unknown",permissionMode:Z.permissionMode||"default",messagesBefore:Q.length,tokensBefore:$});if(V.blockCompaction)return M.debug(`[CompactionService] Compaction hook 阻止压缩: ${V.blockReason||"(无原因)"}`),{success:!1,summary:"",preTokens:$,postTokens:$,filesIncluded:[],compactedMessages:Q,boundaryMessage:{role:"system",content:""},summaryMessage:{role:"user",content:""},error:V.blockReason||"Compaction blocked by hook"};if(V.warning)M.warn(`[CompactionService] Compaction hook warning: ${V.warning}`)}catch(G){M.warn("[CompactionService] Compaction hook execution failed:",G)}let z=Z.sessionId??"_default",W=_0.get(z)??0;if(W>=cZ)return M.warn(`[CompactionService] Circuit breaker open (${W} consecutive failures for session ${z}), using fallback`),this.fallbackCompact(Q,Z,$,Error("Circuit breaker open"));try{M.debug("[CompactionService] 开始压缩,消息数:",Q.length),M.debug("[CompactionService] 压缩前 tokens:",$);let V=L0.analyzeFiles(Q).map((h)=>h.path);M.debug("[CompactionService] 提取重点文件:",V);let Y=await L0.readFilesContent(V);M.debug("[CompactionService] 成功读取文件:",Y.length);let B=await this.generateSummary(Q,Y,Z);M.debug("[CompactionService] 生成总结,长度:",B.length);let q=Math.ceil(Q.length*this.RETAIN_PERCENT),b=Q.slice(-q),X=new Set;for(let h of b)if(h.role==="assistant"&&h.tool_calls)for(let d of h.tool_calls)X.add(d.id);let L=b.filter((h)=>{if(h.role==="tool"&&h.tool_call_id)return X.has(h.tool_call_id);return!0});M.debug("[CompactionService] 保留消息数:",q),M.debug("[CompactionService] 过滤后保留消息数:",L.length);let f=i(),A=this.createBoundaryMessage(f,Z.trigger,$),F=i(),_=this.createSummaryMessage(F,B),j=[_,...L],$0=await this.buildFileRestorationMessage();if($0)j.push($0);let c=this.buildActiveTaskMessage(Z.activeTask);if(c)j.push(c);let J0=Y0.countTokens(j,Z.modelName);M.debug("[CompactionService] 压缩完成!"),M.debug("[CompactionService] Token 变化:",$,"->",J0,`(-${((1-J0/$)*100).toFixed(1)}%)`),_0.delete(z);let z0=Q.slice(0,Q.length-q);return yQ(z0).catch((h)=>{return}),{success:!0,summary:B,preTokens:$,postTokens:J0,filesIncluded:V,compactedMessages:j,boundaryMessage:A,summaryMessage:_}}catch(G){if(o(G))throw G;return _0.set(z,(_0.get(z)??0)+1),M.error("[CompactionService] 压缩失败,使用降级策略",G),this.fallbackCompact(Q,Z,$,G)}}static async generateSummary(Q,Z,$){let J=this.buildCompactionPrompt(Q,Z);if(M.debug("[CompactionService] 使用压缩模型:",$.modelName),$.signal?.aborted)throw new DOMException("Aborted","AbortError");let G=(await(await PQ({apiKey:$.apiKey||process.env.BLADE_API_KEY||"",baseUrl:$.baseURL||process.env.BLADE_BASE_URL||"https://api.openai.com/v1",model:$.modelName,temperature:0.3,maxOutputTokens:8000,timeout:60000,provider:"openai-compatible"})).chat([{role:"user",content:J}],[],$.signal)).content||"",V=G.match(/<summary>([\s\S]*?)<\/summary>/);if(!V)return M.warn("[CompactionService] 总结格式不正确,使用完整响应"),G;return V[1].trim()}static buildCompactionPrompt(Q,Z){let $=Q.map((W,G)=>{let V=W.role||"unknown",Y=typeof W.content==="string"?W.content:JSON.stringify(W.content),B=5000,q=Y.length>5000?Y.substring(0,5000)+"...":Y;return`[${G+1}] ${V}: ${q}`}).join(`
|
|
19
|
+
|
|
20
|
+
`),J=Z.map((W)=>{return`### ${W.path}
|
|
21
|
+
\`\`\`
|
|
22
|
+
${W.content}
|
|
23
|
+
\`\`\``}).join(`
|
|
24
|
+
|
|
25
|
+
`),z=`Your task is to create a detailed summary of the conversation so far, paying close attention to the user's explicit requests and your previous actions.
|
|
26
|
+
This summary should be thorough in capturing technical details, code patterns, and architectural decisions that would be essential for continuing development work without losing context.
|
|
27
|
+
|
|
28
|
+
Before providing your final summary, wrap your analysis in <analysis> tags to organize your thoughts and ensure you've covered all necessary points. In your analysis process:
|
|
29
|
+
|
|
30
|
+
1. Chronologically analyze each message and section of the conversation. For each section thoroughly identify:
|
|
31
|
+
- The user's explicit requests and intents
|
|
32
|
+
- Your approach to addressing the user's requests
|
|
33
|
+
- Key decisions, technical concepts and code patterns
|
|
34
|
+
- Specific details like:
|
|
35
|
+
- file names
|
|
36
|
+
- full code snippets
|
|
37
|
+
- function signatures
|
|
38
|
+
- file edits
|
|
39
|
+
- Errors that you ran into and how you fixed them
|
|
40
|
+
- Pay special attention to specific user feedback that you received, especially if the user told you to do something differently.
|
|
41
|
+
2. Double-check for technical accuracy and completeness, addressing each required element thoroughly.
|
|
42
|
+
|
|
43
|
+
Your summary should include the following sections:
|
|
44
|
+
|
|
45
|
+
1. Primary Request and Intent: Capture all of the user's explicit requests and intents in detail
|
|
46
|
+
2. Key Technical Concepts: List all important technical concepts, technologies, and frameworks discussed.
|
|
47
|
+
3. Files and Code Sections: Enumerate specific files and code sections examined, modified, or created. Pay special attention to the most recent messages and include full code snippets where applicable and include a summary of why this file read or edit is important.
|
|
48
|
+
4. Errors and fixes: List all errors that you ran into, and how you fixed them. Pay special attention to specific user feedback that you received, especially if the user told you to do something differently.
|
|
49
|
+
5. Problem Solving: Document problems solved and any ongoing troubleshooting efforts.
|
|
50
|
+
6. All user messages: List ALL user messages that are not tool results. These are critical for understanding the users' feedback and changing intent.
|
|
51
|
+
7. Pending Tasks: Outline any pending tasks that you have explicitly been asked to work on.
|
|
52
|
+
8. Current Work: Describe in detail precisely what was being worked on immediately before this summary request, paying special attention to the most recent messages from both user and assistant. Include file names and code snippets where applicable.
|
|
53
|
+
9. Optional Next Step: List the next step that you will take that is related to the most recent work you were doing. IMPORTANT: ensure that this step is DIRECTLY in line with the user's most recent explicit requests, and the task you were working on immediately before this summary request.`;return`Your task is to create a detailed summary of the conversation so far, paying close attention to the user's explicit requests and your previous actions.
|
|
54
|
+
This summary should be thorough in capturing technical details, code patterns, and architectural decisions that would be essential for continuing development work without losing context.
|
|
55
|
+
|
|
56
|
+
Before providing your final summary, wrap your analysis in <analysis> tags to organize your thoughts and ensure you've covered all necessary points. In your analysis process:
|
|
57
|
+
|
|
58
|
+
1. Chronologically analyze each message and section of the conversation. For each section thoroughly identify:
|
|
59
|
+
- The user's explicit requests and intents
|
|
60
|
+
- Your approach to addressing the user's requests
|
|
61
|
+
- Key decisions, technical concepts and code patterns
|
|
62
|
+
- Specific details like:
|
|
63
|
+
- file names
|
|
64
|
+
- full code snippets
|
|
65
|
+
- function signatures
|
|
66
|
+
- file edits
|
|
67
|
+
- Errors that you ran into and how you fixed them
|
|
68
|
+
- Pay special attention to specific user feedback that you received, especially if the user told you to do something differently.
|
|
69
|
+
2. Double-check for technical accuracy and completeness, addressing each required element thoroughly.
|
|
70
|
+
|
|
71
|
+
Your summary should include the following sections:
|
|
72
|
+
|
|
73
|
+
1. Primary Request and Intent: Capture all of the user's explicit requests and intents in detail
|
|
74
|
+
2. Key Technical Concepts: List all important technical concepts, technologies, and frameworks discussed.
|
|
75
|
+
3. Files and Code Sections: Enumerate specific files and code sections examined, modified, or created. Pay special attention to the most recent messages and include full code snippets where applicable and include a summary of why this file read or edit is important.
|
|
76
|
+
4. Errors and fixes: List all errors that you ran into, and how you fixed them. Pay special attention to specific user feedback that you received, especially if the user told you to do something differently.
|
|
77
|
+
5. Problem Solving: Document problems solved and any ongoing troubleshooting efforts.
|
|
78
|
+
6. All user messages: List ALL user messages that are not tool results. These are critical for understanding the users' feedback and changing intent.
|
|
79
|
+
7. Pending Tasks: Outline any pending tasks that you have explicitly been asked to work on.
|
|
80
|
+
8. Current Work: Describe in detail precisely what was being worked on immediately before this summary request, paying special attention to the most recent messages from both user and assistant. Include file names and code snippets where applicable.
|
|
81
|
+
9. Optional Next Step: List the next step that you will take that is related to the most recent work you were doing. IMPORTANT: ensure that this step is DIRECTLY in line with the user's most recent explicit requests, and the task you were working on immediately before this summary request.
|
|
82
|
+
|
|
83
|
+
## Conversation History
|
|
84
|
+
|
|
85
|
+
${$}
|
|
86
|
+
|
|
87
|
+
${Z.length>0?`## Important Files
|
|
88
|
+
|
|
89
|
+
${J}`:""}
|
|
90
|
+
|
|
91
|
+
Please provide your summary following the structure specified above, with both <analysis> and <summary> sections.`}static createBoundaryMessage(Q,Z,$){return{id:i(),role:"system",content:"Conversation compacted",metadata:{type:"system",subtype:"compact_boundary",parentId:Q,compactMetadata:{trigger:Z,preTokens:$}}}}static createSummaryMessage(Q,Z){return{id:i(),role:"user",content:Z,metadata:{parentId:Q,isCompactSummary:!0}}}static getRecentlyAccessedFiles(Q){let Z=u.getInstance();return Z.getTrackedFiles().map((z)=>({filePath:z,record:Z.getFileRecord(z)})).filter((z)=>z.record!==void 0).sort((z,W)=>W.record.accessTime-z.record.accessTime).slice(0,Q).map((z)=>z.filePath)}static async buildFileRestorationMessage(){let Q=this.getRecentlyAccessedFiles(5);if(Q.length===0)return null;let Z=[];for(let J of Q)try{let W=(await mZ.readFile(J,"utf-8")).split(`
|
|
92
|
+
`),G=W.slice(0,200).join(`
|
|
93
|
+
`),V=W.length>200?`
|
|
94
|
+
... (${W.length-200} more lines)`:"";Z.push(`<file path="${J}" lines="${W.length}">
|
|
95
|
+
${G}${V}
|
|
96
|
+
</file>`)}catch{}if(Z.length===0)return null;let $=["<system-reminder>","Post-compaction file restoration. These files were recently accessed in the conversation:",...Z,"</system-reminder>"].join(`
|
|
97
|
+
`);return M.debug("[CompactionService] Post-compact 恢复文件:",Q.length),{id:i(),role:"user",content:$,metadata:{isPostCompactRestoration:!0}}}static buildActiveTaskMessage(Q){if(!Q)return null;let Z=this.ACTIVE_TASK_MAX_CHARS,$=Math.floor(Z*0.75),J=Q.length<=Z?Q:[Q.slice(0,$),`
|
|
98
|
+
...[active task checkpoint truncated]...
|
|
99
|
+
`,Q.slice(-(Z-$))].join("");return{id:i(),role:"user",content:["<system-reminder>","Post-compaction active task checkpoint. Continue this user-authored request; preserve its exact literals and constraints:",J,"</system-reminder>"].join(`
|
|
100
|
+
`),metadata:{isPostCompactActiveTask:!0}}}static fallbackCompact(Q,Z,$,J){let z=Math.ceil(Q.length*this.FALLBACK_RETAIN_PERCENT),W=Q.slice(-z),G=new Set;for(let F of W)if(F.role==="assistant"&&F.tool_calls)for(let _ of F.tool_calls)G.add(_.id);let V=W.filter((F)=>{if(F.role==="tool"&&F.tool_call_id)return G.has(F.tool_call_id);return!0}),Y=i(),B=this.createBoundaryMessage(Y,Z.trigger,$),q=J instanceof Error?J.message:String(J),b=i(),X=this.createSummaryMessage(b,`[Automatic compaction failed; using fallback]
|
|
101
|
+
|
|
102
|
+
An error occurred during compaction. Retained the latest ${z} messages (~30%).
|
|
103
|
+
|
|
104
|
+
Error: ${q}
|
|
105
|
+
|
|
106
|
+
The conversation can continue, but consider retrying compaction later with /compact.`),L=[X,...V],f=this.buildActiveTaskMessage(Z.activeTask);if(f)L.push(f);let A=Y0.countTokens(L,Z.modelName);return{success:!1,summary:typeof X.content==="string"?X.content:X.content.filter((F)=>F.type==="text").map((F)=>F.text).join(`
|
|
107
|
+
`),preTokens:$,postTokens:A,filesIncluded:[],compactedMessages:L,boundaryMessage:B,summaryMessage:X,error:q}}}var uZ=new Set(["Read","Grep","Glob","Search","WebSearch","WebFetch","ToolSearch"]);function iZ(Q,Z){let z=(Q[Z.assistantIdx].tool_calls??[]).filter((G)=>G.type==="function").map((G)=>G.function.name).some((G)=>!uZ.has(G));if(Z.toolResultIdxs.some((G)=>{let V=Q[G]?.content;if(typeof V!=="string")return!1;return V.startsWith("Error:")||V.includes("failed")||V.includes("ENOENT")}))return 3;if(z)return 2;return 1}function V0(Q,Z){let $=Z?.keepRecentTurns??10,J=Z?.minMessagesForSnip??30;if(Q.length<J)return{messages:Q,snippedCount:0,estimatedTokensFreed:0};let z=[];for(let X=0;X<Q.length;X++){let L=Q[X];if(L.role==="assistant"&&L.tool_calls&&L.tool_calls.length>0){let f=new Set(L.tool_calls.map((F)=>F.id)),A=[];for(let F=X+1;F<Q.length;F++){let _=Q[F];if(_.role==="tool"&&_.tool_call_id&&f.has(_.tool_call_id))A.push(F);if(_.role==="assistant"||_.role==="user")break}z.push({assistantIdx:X,toolResultIdxs:A,priority:0})}}for(let X of z)X.priority=iZ(Q,X);let V=[...z.slice(0,Math.max(0,z.length-$))].sort((X,L)=>X.priority-L.priority);if(V.length===0)return{messages:Q,snippedCount:0,estimatedTokensFreed:0};let Y=new Set,B=0;for(let X of V){Y.add(X.assistantIdx);for(let L of X.toolResultIdxs)Y.add(L)}for(let X of Y){let L=Q[X],f=typeof L.content==="string"?L.content:JSON.stringify(L.content);if(B+=f.length,L.tool_calls)B+=JSON.stringify(L.tool_calls).length}let q=[],b=!1;for(let X=0;X<Q.length;X++){if(Y.has(X)){if(!b)q.push({role:"system",content:`[${V.length} earlier tool interaction${V.length===1?"":"s"} snipped for brevity]`}),b=!0;continue}q.push(Q[X])}return{messages:q,snippedCount:V.length,estimatedTokensFreed:Math.floor(B/4)}}var nZ=60000,lZ=3;function MQ(Q,Z){if(!Z)return null;if(Date.now()-Z<nZ)return null;let J=V0(Q,{keepRecentTurns:lZ,minMessagesForSnip:15});if(J.snippedCount===0)return null;return J}class e0{hasAttempted=!1;async tryReactiveCompact(Q,Z){if(this.hasAttempted)return{success:!1,messages:Q};this.hasAttempted=!0;let $=V0(Q,{keepRecentTurns:3,minMessagesForSnip:10}),J=$.messages;try{let z=await Q0.compact(J,{trigger:"auto",modelName:Z.modelName,maxContextTokens:Z.maxContextTokens,apiKey:Z.apiKey,baseURL:Z.baseURL,signal:Z.signal,activeTask:Z.activeTask});if(z.success)return{success:!0,messages:z.compactedMessages};if($.snippedCount>0)return{success:!0,messages:J};return{success:!1,messages:Q}}catch(z){if(o(z))throw z;if($.snippedCount>0)return{success:!0,messages:J};return{success:!1,messages:Q}}}reset(){this.hasAttempted=!1}}import*as Z0 from"fs";import*as QQ from"os";import*as H0 from"path";import{nanoid as kQ}from"nanoid";var aZ=1e5,rZ=2000,fQ=200000;class ZQ{currentChars=0;track(Q){this.currentChars+=Q}remaining(){return Math.max(0,fQ-this.currentChars)}isExhausted(){return this.currentChars>=fQ}reset(){this.currentChars=0}}function xQ(Q,Z,$){let J=$?.maxCharsPerResult??aZ,z=$?.previewChars??rZ,W=$?.messageBudget,G=typeof Q==="string"?Q:JSON.stringify(Q,null,2);if(G.length<=J)return oZ(Q,G,Z,z,W,$);let V=$?.outputDir??H0.join(QQ.homedir(),".blade","tool-results"),Y=`${Z}-${kQ(8)}.txt`,B=H0.join(V,Y);try{Z0.mkdirSync(V,{recursive:!0}),Z0.writeFileSync(B,G,"utf-8")}catch{let X=G.slice(0,J)+`
|
|
108
|
+
|
|
109
|
+
... (truncated, ${G.length} total chars)`;if(W)W.track(X.length);return X}let q=G.slice(0,z),b=`Result too large (${G.length} chars). Full output saved to: ${B}
|
|
110
|
+
|
|
111
|
+
Preview:
|
|
112
|
+
${q}
|
|
113
|
+
|
|
114
|
+
... (${G.length-z} more chars in file)`;if(W)W.track(b.length);return b}function oZ(Q,Z,$,J,z,W){if(!z)return Q;let G=z.remaining();if(G<=0){let V=Z.slice(0,J),Y=hQ(Z,V,$,W,"[Message budget exhausted. Full output saved to disk.]");return z.track(typeof Y==="string"?Y.length:J),Y}if(Z.length>G){let V=Math.max(J,G),Y=Z.slice(0,V),B=hQ(Z,Y,$,W,`... (truncated by message budget, ${Z.length} total chars)`);return z.track(typeof B==="string"?B.length:V),B}return z.track(Z.length),Q}function hQ(Q,Z,$,J,z){let W=J?.outputDir??H0.join(QQ.homedir(),".blade","tool-results"),G=`${$}-${kQ(8)}.txt`,V=H0.join(W,G);try{return Z0.mkdirSync(W,{recursive:!0}),Z0.writeFileSync(V,Q,"utf-8"),`${Z}
|
|
115
|
+
|
|
116
|
+
${z}
|
|
117
|
+
Full output saved to: ${V}`}catch{return`${Z}
|
|
118
|
+
|
|
119
|
+
${z}`}}import*as E0 from"node:fs/promises";import{homedir as nQ}from"node:os";import*as g from"node:path";var v0={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 RQ(){return{metadata:v0,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 N0={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 TQ(){return{metadata:N0,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 sZ}from"node:child_process";import*as w from"node:fs/promises";import{homedir as tZ}from"node:os";import*as U from"node:path";import{promisify as eZ}from"node:util";var I0=eZ(sZ),S=R("General"),$Q={url:"https://github.com/anthropics/skills.git",branch:"main",defaultSkills:["skill-creator"]};class CQ{skillsDir;constructor(Q){this.skillsDir=Q||U.join(tZ(),".blade","skills")}async isInstalled(Q){let Z=U.join(this.skillsDir,Q,"SKILL.md");try{return await w.access(Z),!0}catch{return!1}}async isGitAvailable(){try{return await I0("git --version"),!0}catch{return!1}}async installOfficialSkill(Q){let{url:Z,branch:$}=$Q,J=U.join(this.skillsDir,Q),z=U.join(this.skillsDir,`.tmp-${Q}-${Date.now()}`);try{if(!await this.isGitAvailable())return S.warn("Git not available, skipping skill installation"),!1;S.info(`Installing official skill: ${Q}...`),await w.mkdir(this.skillsDir,{recursive:!0,mode:493}),await I0(`git clone --depth 1 --branch ${$} --single-branch ${Z} "${z}"`,{timeout:30000});let W=U.join(z,"skills",Q);try{await w.access(W)}catch{return S.warn(`Skill ${Q} not found in official repository`),await w.rm(z,{recursive:!0,force:!0}),!1}try{await w.rm(J,{recursive:!0,force:!0})}catch{}return await w.cp(W,J,{recursive:!0}),await w.rm(z,{recursive:!0,force:!0}),S.info(`Successfully installed: ${Q}`),!0}catch(W){try{await w.rm(z,{recursive:!0,force:!0})}catch{}return S.warn(`Failed to install ${Q}: ${W instanceof Error?W.message:"Unknown error"}`),!1}}async ensureDefaultSkillsInstalled(){await w.mkdir(this.skillsDir,{recursive:!0,mode:493});for(let Q of $Q.defaultSkills)if(!await this.isInstalled(Q))await this.installOfficialSkill(Q)}async installFromRepo(Q,Z){let $=Z||this.extractRepoName(Q),J=U.join(this.skillsDir,$),z=U.join(this.skillsDir,`.tmp-repo-${$}-${Date.now()}`);try{if(!await this.isGitAvailable())return S.warn("Git not available, cannot install from repo"),!1;S.info(`Installing skill from repo: ${Q}...`),await w.mkdir(this.skillsDir,{recursive:!0,mode:493}),await I0(`git clone --depth 1 "${Q}" "${z}"`,{timeout:60000});let W=U.join(z,"SKILL.md");try{await w.access(W)}catch{return S.warn(`No SKILL.md found in repository ${Q}`),await w.rm(z,{recursive:!0,force:!0}),!1}await w.rm(J,{recursive:!0,force:!0}),await w.rename(z,J);try{await w.rm(U.join(J,".git"),{recursive:!0,force:!0})}catch{}return S.info(`Successfully installed skill from repo: ${$}`),!0}catch(W){try{await w.rm(z,{recursive:!0,force:!0})}catch{}return S.warn(`Failed to install from repo ${Q}: ${W instanceof Error?W.message:"Unknown error"}`),!1}}async installFromLocal(Q,Z,$=!0){let J=Z||U.basename(Q),z=U.join(this.skillsDir,J);try{let W=U.resolve(Q);try{await w.access(W)}catch{return S.warn(`Local path does not exist: ${W}`),!1}let G=U.join(W,"SKILL.md");try{await w.access(G)}catch{return S.warn(`No SKILL.md found in local path: ${W}`),!1}if(S.info(`Installing skill from local path: ${W}...`),await w.mkdir(this.skillsDir,{recursive:!0,mode:493}),await w.rm(z,{recursive:!0,force:!0}),$)await w.symlink(W,z,"dir"),S.info(`Created symlink for skill: ${J}`);else await w.cp(W,z,{recursive:!0}),S.info(`Copied skill to: ${J}`);return!0}catch(W){return S.warn(`Failed to install from local path ${Q}: ${W instanceof Error?W.message:"Unknown error"}`),!1}}extractRepoName(Q){return Q.match(/\/([^/]+?)(\.git)?$/)?.[1]||"unknown-skill"}async installAllOfficialSkills(){let{url:Q,branch:Z}=$Q,$=U.join(this.skillsDir,`.tmp-all-${Date.now()}`),J=[],z=[];try{if(!await this.isGitAvailable())return S.warn("Git not available, skipping skill installation"),{installed:J,failed:z};await w.mkdir(this.skillsDir,{recursive:!0,mode:493}),S.info("Cloning official skills repository..."),await I0(`git clone --depth 1 --branch ${Z} --single-branch ${Q} "${$}"`,{timeout:60000});let W=U.join($,"skills"),G=await w.readdir(W,{withFileTypes:!0});for(let V of G){if(!V.isDirectory())continue;let Y=V.name,B=U.join(W,Y),q=U.join(this.skillsDir,Y);try{await w.access(U.join(B,"SKILL.md")),await w.rm(q,{recursive:!0,force:!0}),await w.cp(B,q,{recursive:!0}),S.info(`Installed: ${Y}`),J.push(Y)}catch(b){S.warn(`Failed to install ${Y}`),z.push(Y)}}await w.rm($,{recursive:!0,force:!0})}catch(W){try{await w.rm($,{recursive:!0,force:!0})}catch{}S.warn(`Failed to install skills: ${W instanceof Error?W.message:"Unknown error"}`)}return{installed:J,failed:z}}}var JQ=null;function pQ(Q){if(!JQ)JQ=new CQ(Q);return JQ}import*as X0 from"node:fs/promises";import*as S0 from"node:path";import{parse as Q2}from"yaml";var Z2=/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/,$2=/^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]?$/,dQ=1024;function J2(Q){if(!Q)return;if(typeof Q==="string")return Q.split(",").map((Z)=>Z.trim()).filter(Boolean);if(Array.isArray(Q))return Q.map((Z)=>String(Z).trim()).filter(Boolean);return}function gQ(Q){if(Q===void 0)return;if(typeof Q==="boolean")return Q;if(typeof Q==="string"){let Z=Q.toLowerCase().trim();if(Z==="true"||Z==="yes"||Z==="1")return!0;if(Z==="false"||Z==="no"||Z==="0")return!1}return}function z2(Q,Z){if(!Q.name)return{valid:!1,error:"Missing required field: name"};if(!$2.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>dQ)return{valid:!1,error:`Description too long: ${Q.description.length} characters (max ${dQ})`};let $;if(Q.model)$=Q.model==="inherit"?"inherit":Q.model;return{valid:!0,metadata:{name:Q.name,description:Q.description.trim(),allowedTools:J2(Q["allowed-tools"]),version:Q.version,argumentHint:Q["argument-hint"]?.trim(),userInvocable:gQ(Q["user-invocable"]),disableModelInvocation:gQ(Q["disable-model-invocation"]),model:$,whenToUse:Q.when_to_use?.trim()}}}function mQ(Q,Z,$){let J=Q.match(Z2);if(!J)return{success:!1,error:"Invalid SKILL.md format: missing YAML frontmatter (must start with ---)"};let[,z,W]=J,G;try{G=Q2(z)}catch(B){return{success:!1,error:`Failed to parse YAML frontmatter: ${B instanceof Error?B.message:String(B)}`}}let V=z2(G,Z);if(!V.valid)return{success:!1,error:V.error};let Y=S0.dirname(Z);return{success:!0,content:{metadata:{...V.metadata,path:Z,basePath:Y,source:$},instructions:W.trim()}}}async function cQ(Q,Z){try{let $=await X0.readFile(Q,"utf-8");return mQ($,Q,Z)}catch($){if($.code==="ENOENT")return{success:!1,error:`File not found: ${Q}`};return{success:!1,error:`Failed to read file: ${$ instanceof Error?$.message:String($)}`}}}async function uQ(Q){try{let Z=await X0.readFile(Q.path,"utf-8"),$=mQ(Z,Q.path,Q.source);return $.success?$.content:null}catch{return null}}async function iQ(Q){try{return await X0.access(S0.join(Q,"SKILL.md")),!0}catch{return!1}}var W2={userSkillsDir:g.join(nQ(),".blade","skills"),projectSkillsDir:".blade/skills",claudeUserSkillsDir:g.join(nQ(),".claude","skills"),claudeProjectSkillsDir:".claude/skills"},U0=null;class zQ{skills=new Map;pluginSkills=new Map;config;initialized=!1;constructor(Q){this.config={...W2,cwd:p(),...Q}}static getInstance(Q){if(!U0)U0=new zQ(Q);return U0}static resetInstance(){U0=null}async initialize(){if(this.initialized)return{skills:Array.from(this.skills.values()),errors:[]};let Q=[],Z=[];try{await pQ(this.config.userSkillsDir).ensureDefaultSkillsInstalled()}catch(Y){Q.push({path:"SkillInstaller",error:`Failed to install default skills: ${Y instanceof Error?Y.message:"Unknown error"}`})}this.loadBuiltinSkills();let $=await this.scanDirectory(this.config.claudeUserSkillsDir,"user");Z.push(...$.skills),Q.push(...$.errors);let J=await this.scanDirectory(this.config.userSkillsDir,"user");Z.push(...J.skills),Q.push(...J.errors);let z=g.isAbsolute(this.config.claudeProjectSkillsDir)?this.config.claudeProjectSkillsDir:g.join(this.config.cwd,this.config.claudeProjectSkillsDir),W=await this.scanDirectory(z,"project");Z.push(...W.skills),Q.push(...W.errors);let G=g.isAbsolute(this.config.projectSkillsDir)?this.config.projectSkillsDir:g.join(this.config.cwd,this.config.projectSkillsDir),V=await this.scanDirectory(G,"project");Z.push(...V.skills),Q.push(...V.errors);for(let Y of Z)this.skills.set(Y.name,Y);return this.initialized=!0,{skills:Array.from(this.skills.values()),errors:Q}}loadBuiltinSkills(){this.skills.set(v0.name,v0),this.skills.set(N0.name,N0)}async scanDirectory(Q,Z){let $=[],J=[];try{await E0.access(Q)}catch{return{skills:$,errors:J}}try{let z=await E0.readdir(Q,{withFileTypes:!0});for(let W of z){if(!W.isDirectory())continue;let G=g.join(Q,W.name),V=g.join(G,"SKILL.md");if(!await iQ(G))continue;let Y=await cQ(V,Z);if(Y.success&&Y.content)$.push(Y.content.metadata);else J.push({path:V,error:Y.error||"Unknown error"})}}catch(z){J.push({path:Q,error:`Failed to scan directory: ${z instanceof Error?z.message:String(z)}`})}return{skills:$,errors:J}}getAll(){return Array.from(this.skills.values())}get(Q){return this.skills.get(Q)}has(Q){return this.skills.has(Q)}async loadContent(Q){let Z=this.skills.get(Q);if(!Z)return null;if(Z.source==="builtin")return this.loadBuiltinContent(Q);return uQ(Z)}loadBuiltinContent(Q){switch(Q){case"skill-creator":return RQ();case"update-config":return TQ();default:return null}}getModelInvocableSkills(){return Array.from(this.skills.values()).filter((Q)=>!Q.disableModelInvocation)}getUserInvocableSkills(){return Array.from(this.skills.values()).filter((Q)=>Q.userInvocable===!0)}generateAvailableSkillsList(){let Q=this.getModelInvocableSkills();if(Q.length===0)return"";let Z=[];for(let $ of Q){let J=$.description.length>100?`${$.description.substring(0,97)}...`:$.description,z=$.argumentHint?`${$.name} ${$.argumentHint}`:$.name;Z.push(`- ${z}: ${J}`)}return Z.join(`
|
|
576
|
+
`)}get size(){return this.skills.size}async refresh(){return this.skills.clear(),this.pluginSkills.clear(),this.initialized=!1,this.initialize()}registerPluginSkill(Q){this.pluginSkills.set(Q.namespacedName,Q),this.skills.set(Q.namespacedName,Q.metadata)}findPluginSkill(Q){let Z=this.pluginSkills.get(Q);if(Z)return Z;let $=[];for(let J of this.pluginSkills.values())if(J.originalName===Q)$.push(J);if($.length===1)return $[0];return}getAllPluginSkills(){return Array.from(this.pluginSkills.values())}clearPluginSkills(){for(let Q of this.pluginSkills.values())this.skills.delete(Q.namespacedName);this.pluginSkills.clear()}getPluginSkillCount(){return this.pluginSkills.size}}function y0(Q){return zQ.getInstance(Q)}async function G2(Q){return y0(Q).initialize()}var Y2="Skill",V2=/<available_skills>\s*<\/available_skills>/;function WQ(Q){let $=y0().generateAvailableSkillsList();if(!$)return Q;return Q.map((J)=>{if(J.name!==Y2)return J;let z=J.description.replace(V2,`<available_skills>
|
|
577
|
+
${$}
|
|
578
|
+
</available_skills>`);if(z===J.description)return J;return{...J,description:z}})}function lQ(){return{consecutiveFailures:new Map,totalFailures:0,lastFailedTool:null}}function aQ(Q,Z){Q.consecutiveFailures.set(Z,0),Q.lastFailedTool=null}function rQ(Q,Z){let $=(Q.consecutiveFailures.get(Z)??0)+1;Q.consecutiveFailures.set(Z,$),Q.totalFailures++,Q.lastFailedTool=Z}function H2(Q,Z){return(Q.consecutiveFailures.get(Z)??0)>=3}function oQ(Q,Z){if(!H2(Q,Z))return;let $=Q.consecutiveFailures.get(Z)??0;return`WARNING: ${Z} has failed ${$} consecutive times. Consider a different approach: use a different tool, verify your parameters, or break the task into smaller steps.`}function sQ(Q){return Q>0&&Q%5===0}function tQ(Q,Z){let $=[`[Self-check at turn ${Q}]`,"Before continuing, briefly assess:","1. Are you making progress toward the goal?","2. Have any approaches failed repeatedly that you should abandon?","3. Is there a simpler path you haven't tried?"];if(Z>3)$.push(`Note: ${Z} tool failures so far. Consider whether your current strategy needs adjustment.`);return $.join(`
|
|
579
|
+
`)}function eQ(){return{recentOutputHashes:[]}}function X2(Q){let Z=Q.trim().slice(0,500),$=0;for(let J=0;J<Z.length;J++)$=($<<5)-$+Z.charCodeAt(J)|0;return $.toString(36)}function QZ(Q,Z){let $=X2(Z);if(Q.recentOutputHashes.push($),Q.recentOutputHashes.length>4)Q.recentOutputHashes.shift();if(Q.recentOutputHashes.length<3)return!1;let J=Q.recentOutputHashes.slice(-3),z=J.every((W)=>W===J[0]);if(z)Q.recentOutputHashes=[];return z}function ZZ(){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 n=R("Agent"),B2=new Set(["Read","Glob","Grep","WebFetch","WebSearch","MemoryRead","GetSpecContext","ValidateSpec","TaskOutput"]);class A0{pipeline;execContext;registry;contextMgr;sessionId;lastMessageUuid;subagentInfo;pending=new Map;completed=new Map;queued=[];order=[];dispatched=new Set;abortController=new AbortController;epoch=0;activeAborts=new Map;constructor(Q,Z,$,J,z,W,G){this.pipeline=Q;this.execContext=Z;this.registry=$;this.contextMgr=J;this.sessionId=z;this.lastMessageUuid=W;this.subagentInfo=G}addTool(Q,Z){if(this.dispatched.has(Q.id)){n.debug(`[StreamingToolExecutor] 跳过已分发工具: ${Q.function.name} (${Q.id})`);return}if(this.dispatched.add(Q.id),this.order.push(Q.id),B2.has(Q.function.name)){n.debug(`[StreamingToolExecutor] 立即执行预启动工具: ${Q.function.name}`);let J=this.executeOne(Q,Z);this.pending.set(Q.id,J)}else n.debug(`[StreamingToolExecutor] 排队非预启动工具: ${Q.function.name}`),this.queued.push({toolCall:Q,params:Z})}async*getRemainingResults(){for(let Q of this.order){if(this.completed.has(Q)){yield this.completed.get(Q),this.completed.delete(Q);continue}if(this.pending.has(Q)){let $=await this.pending.get(Q);this.pending.delete(Q),yield $;continue}let Z=this.queued.findIndex(($)=>$.toolCall.id===Q);if(Z!==-1){let{toolCall:$,params:J}=this.queued[Z];if(this.queued.splice(Z,1),this.execContext.signal?.aborted){n.debug(`[StreamingToolExecutor] Signal aborted, 跳过排队工具: ${$.function.name} (${$.id})`),yield this.makeAbortResult($,"Tool execution skipped: task aborted before launch");continue}yield await this.executeOne($,J)}}}getCompletedResults(){let Q=Array.from(this.completed.values());return this.completed.clear(),Q}discard(){this.epoch++,this.abortController.abort(),this.abortController=new AbortController;for(let[,Q]of this.activeAborts)Q.abort();this.activeAborts.clear(),this.queued=[],this.order=[],this.dispatched.clear(),this.completed.clear(),this.pending.clear(),n.debug(`[StreamingToolExecutor] 已丢弃所有挂起工作并重置状态 (epoch=${this.epoch})`)}hasTools(){return this.order.length>0}getEpoch(){return this.epoch}makeAbortResult(Q,Z){return{toolCall:Q,result:{success:!1,llmContent:"",error:{type:"execution_error",message:Z},metadata:{abortedBeforeLaunch:!0}},toolUseUuid:null}}async executeOne(Q,Z){let $=this.epoch,J=new AbortController;this.activeAborts.set(Q.id,J);let z=this.abortController.signal;try{if(z.aborted||J.signal.aborted)return this.makeAbortResult(Q,"Tool execution aborted due to discard");let W=null;try{if(this.contextMgr&&this.sessionId)W=await this.contextMgr.saveToolUse(this.sessionId,Q.function.name,Z,this.lastMessageUuid??null,this.subagentInfo)}catch(X){n.warn("[StreamingToolExecutor] 保存工具调用失败:",X)}let G=[z,J.signal],V=this.execContext.signal;if(V)G.push(V);let Y=$Z(...G),B={...this.execContext,signal:Y},q=await this.pipeline.execute(Q.function.name,Z,B);if($!==this.epoch)return n.debug(`[StreamingToolExecutor] 丢弃旧世代工具结果: ${Q.function.name} (startEpoch=${$}, currentEpoch=${this.epoch})`),this.makeAbortResult(Q,"Tool execution aborted due to epoch mismatch (discard)");let b={toolCall:Q,result:q,toolUseUuid:W};if(this.pending.has(Q.id))this.pending.delete(Q.id),this.completed.set(Q.id,b);return b}catch(W){if($!==this.epoch)return this.makeAbortResult(Q,"Tool execution aborted due to epoch mismatch (discard)");n.error(`[StreamingToolExecutor] 工具执行失败: ${Q.function.name}`,W);let G={success:!1,llmContent:"",error:{type:"execution_error",message:W instanceof Error?W.message:"Unknown error"},metadata:void 0},V={toolCall:Q,result:G,toolUseUuid:null,error:W instanceof Error?W:Error("Unknown error")};if(this.pending.has(Q.id))this.pending.delete(Q.id),this.completed.set(Q.id,V);return V}finally{this.activeAborts.delete(Q.id)}}}var y=R("Agent"),q2=0.1,D2=8192,b2=32768,P0=100,F2=`
|
|
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 JZ(Q){let Z=Q.trim();if(Z=Z.replace(/,\s*([}\]])/g,"$1"),Z.startsWith("{")&&!Z.endsWith("}"))Z+="}";Z=Z.replace(/,\s*([}\]])/g,"$1");try{let $=JSON.parse(Z);if(typeof $==="object"&&$!==null&&!Array.isArray($))return $;return null}catch{return null}}function WZ(Q){let Z=JZ(Q);if(Z)return Z;try{let $=JSON.parse(Q);return typeof $==="string"?JZ($):null}catch{return null}}function O2(Q){if(typeof Q==="string")return Q;try{return JSON.parse(JSON.stringify(Q))}catch{return String(Q)}}function w2(Q){if(!(Q instanceof Error))return"未知错误";let J=Q.lastError??Q;if(J.responseBody)try{let V=JSON.parse(J.responseBody)?.error?.message;if(V){let Y=J.statusCode?` (HTTP ${J.statusCode})`:"";return`${V}${Y}`}}catch{}let z=Q.message,W=z.match(/Last error:\s*(.+)$/);if(W)return W[1];return z}function L2(Q){if(!(Q instanceof Error))return!1;return["stream not supported","streaming is not available","sse not supported","does not support streaming"].some(($)=>Q.message.toLowerCase().includes($.toLowerCase()))}function _2(Q,Z){if(!Z)return"Tool execution failed (no details).";let $=[`Error: ${Z.message||"Unknown error"}`];if(Z.type==="validation_error")$.push("Hint: Check the tool parameters — a required field may be missing or have the wrong type.");else if(Z.type==="permission_denied")$.push("Hint: This operation requires user approval. Try a different approach or ask the user.");else if(Z.type==="timeout_error")$.push("Hint: The operation timed out. Consider breaking it into smaller steps or increasing timeout.");else if(Z.type==="execution_error"){let J=Z.message??"";if(J.includes("ENOENT")||J.includes("no such file"))$.push("Hint: File or directory not found. Use Glob or Grep to find the correct path first.");else if(J.includes("EACCES")||J.includes("permission"))$.push("Hint: Permission denied. The file may be read-only or owned by another user.");else if(J.includes("not found in file")||J.includes("old_string"))$.push(`Hint: The target text was not found. Use Read to view the current file content, then retry ${Q} with the exact text.`);else if(J.includes("ENOTDIR"))$.push("Hint: A path component is not a directory. Verify the full path with Glob.")}return $.join(`
|
|
588
|
+
`)}function v2(Q){if(!(Q instanceof Error))return!1;let Z=Q.message.toLowerCase();return Z.includes("prompt_too_long")||Z.includes("prompt is too long")||Z.includes("maximum context length")||Z.includes("request too large")||Q.status===413}function N2(Q,Z){let $=Z,J=$.index??0;if(!Q.has(J))Q.set(J,{id:$.id||"",name:$.function?.name||"",arguments:""});let z=Q.get(J);if($.id&&!z.id)z.id=$.id;if($.function?.name&&!z.name)z.name=$.function.name;if($.function?.arguments)z.arguments+=$.function.arguments}function I2(Q){if(Q.size===0)return;return Array.from(Q.values()).filter((Z)=>Z.id&&Z.name).map((Z)=>({id:Z.id,type:"function",function:{name:Z.name,arguments:Z.arguments}}))}async function*S2(Q,Z,$,J,z){let W="",G="",V,Y,B=new Map;try{let q=Q.chatService.streamChat(Z,$,J),b=0;for await(let X of q){if(b++,J?.aborted)break;if(X.modelFallback){z?.discard(),W="",G="",V=void 0,Y=void 0,B.clear(),b=0,yield{kind:"model_fallback"};continue}if(X.content)W+=X.content,yield{kind:"content_delta",delta:X.content};if(X.reasoningContent)G+=X.reasoningContent,yield{kind:"thinking_delta",delta:X.reasoningContent};if(X.usage)V=X.usage;if(X.toolCalls){for(let L of X.toolCalls)if(N2(B,L),z){let A=L.index??0,F=B.get(A);if(F&&F.id&&F.name)try{let _=WZ(F.arguments);if(_===null)continue;let j={id:F.id,type:"function",function:{name:F.name,arguments:F.arguments}},c=Q.toolExecutor.getRegistry().get(F.name)?.kind;z.addTool(j,_),yield{kind:"tool_start",toolCall:j,toolKind:c}}catch{}}}if(X.finishReason){Y=X.finishReason;break}}if(b===0&&!J?.aborted&&W.length===0&&B.size===0)return y.warn("[Loop] 流式响应返回0个chunk,回退到非流式模式"),z?.discard(),{...await Q.chatService.chat(Z,$,J),_nonStreamingFallback:!0};return{content:W,reasoningContent:G||void 0,toolCalls:I2(B),usage:V,finishReason:Y}}catch(q){if(L2(q))return y.warn("[Loop] 流式请求失败,降级到非流式模式"),z?.discard(),{...await Q.chatService.chat(Z,$,J),_nonStreamingFallback:!0};throw q}}async function*GZ(Q,Z,$,J,z,W,G){if(J===void 0)return y.debug(`[Loop] [轮次 ${$}] 压缩检查: 跳过(无历史 usage 数据)`),"none";let V=MQ(Z.messages,W);if(V)Z.messages=V.messages,y.debug(`[Loop] [轮次 ${$}] MicroCompact: 清理 ${V.snippedCount} 轮旧工具结果(缓存已过期)`);let Y=V0(Z.messages),B=!1;if(Y.snippedCount>0)B=!0,y.debug(`[Loop] [轮次 ${$}] Snip 压缩: 移除 ${Y.snippedCount} 轮旧工具调用,释放约 ${Y.estimatedTokensFreed} tokens`);let q=Q.chatService.getConfig(),b=q.model,X=q.maxContextTokens??Q.config.maxContextTokens,L=q.maxOutputTokens??Q.config.maxOutputTokens??Math.min(Math.max(Math.floor(X*q2),D2),b2),f=X-L,A=Math.floor(f*0.8);if(y.debug(`[Loop] [轮次 ${$}] 压缩检查:`,{promptTokens:J,maxContextTokens:X,maxOutputTokens:L,availableForInput:f,threshold:A,shouldCompact:J>=A}),J<A){if(B)Z.messages=Y.messages;return B?"snipped":"none"}y.debug($===0?"[Loop] 触发自动压缩":`[Loop] [轮次 ${$}] 触发循环内自动压缩`),yield{kind:"compaction",phase:"start"};try{let F=B?Y.messages:Z.messages,_=await Q0.compact(F,{trigger:"auto",modelName:b,maxContextTokens:X,apiKey:q.apiKey,baseURL:q.baseUrl,actualPreTokens:J,signal:z,activeTask:G});if(Z.messages=_.compactedMessages,_.success)y.debug(`[Loop] [轮次 ${$}] 压缩完成: ${_.preTokens} -> ${_.postTokens} tokens`);else y.warn(`[Loop] [轮次 ${$}] 压缩使用降级策略: ${_.preTokens} -> ${_.postTokens} tokens`);return await O0(Q,Z,_.summary,{trigger:"auto",preTokens:_.preTokens,postTokens:_.postTokens,filesIncluded:_.filesIncluded}),"compacted"}catch(F){if(o(F))return y.debug(`[Loop] [轮次 ${$}] 压缩被中止`),"none";if(B)Z.messages=Y.messages;return y.error(`[Loop] [轮次 ${$}] 压缩失败,继续执行`,F),B?"snipped":"none"}finally{yield{kind:"compaction",phase:"end"}}}function U2(Q,Z,$,J){let z=J?zZ(J):"user-cancel";return{success:!1,error:{type:"aborted",message:(z==="interrupt"?void 0:"任务已被用户中止")??"任务已中断"},metadata:{turnsCount:Q,toolCallsCount:Z,duration:Date.now()-$,abortReason:z}}}async function*E2(Q,Z,$,J,z){let W=Date.now(),G=0,V=[],Y=null,B=!1,q=(b,X,L)=>{return B=!0,U2(b,X,W,L)};try{let b=Q.toolExecutor.getRegistry(),X=$.permissionMode,L=b.getFunctionDeclarationsByMode(X);L=WQ(L);let f=Q.applySkillToolRestrictions(L),A=lQ(),F=eQ(),_=z;if(typeof b.getDeferredToolsListing==="function"){let a=b.getDeferredToolsListing();if(a&&_)_=`${_}
|
|
589
|
+
|
|
590
|
+
${a}`}if(_)_+=F2;let j=new b0($,_);j.appendUser({role:"user",content:Z}),Y=await m(Q,$,Z);let $0=$.permissionMode==="yolo",c=!!$.subagentInfo,J0=Q.runtimeOptions.maxTurns!==void 0||J?.maxTurns!==void 0,z0=Q.runtimeOptions.maxTurns??J?.maxTurns??Q.config.maxTurns??-1;if(z0===0)return{success:!1,error:{type:"chat_disabled",message:"对话功能已被禁用 (maxTurns=0)"},metadata:{turnsCount:0,toolCallsCount:0,duration:0}};let h=z0===-1?P0:Math.min(z0,P0),d=0,M0,GQ,W0=0,f0=0,h0=0,k0=0,x0=0,R0=new Set,x=new Set($.worktreeActive?["EnterWorktree"]:[]),l=typeof Z==="string"?Z:Z.filter((a)=>a.type==="text").map((a)=>a.text).join(`
|
|
591
|
+
`),YQ=[l,$.completionRequirements?.trim()].filter(Boolean).join(`
|
|
592
|
+
`),VQ=n0(l),T0=jQ({budget:Q.currentModelMaxContextTokens,isSubagent:c}),HQ=new e0;try{while(!0){if(J?.signal?.aborted)return q(G,V.length,J.signal);if(j.writeback(),(yield*GZ(Q,$,G,M0,J?.signal,GQ,l))!=="none")j.replaceHistory($.messages);if(G++,HQ.reset(),yield{kind:"turn_start",turn:G,maxTurns:h},J?.signal?.aborted)return q(G-1,V.length,J.signal);if(sQ(G)&&G>1){let N=tQ(G,A.totalFailures);j.appendControl("user",{role:"user",content:`
|
|
593
|
+
|
|
594
|
+
<system-reminder>
|
|
595
|
+
${N}
|
|
596
|
+
</system-reminder>`})}let XQ=J?.stream!==!1,H,K0;try{if(XQ)K0=new A0(Q.toolExecutor,{sessionId:$.sessionId,userId:$.userId||"default",workspaceRoot:$.workspaceRoot||p(),worktreeIsolationRequired:VQ,worktreeActive:x.has("EnterWorktree")&&!x.has("ExitWorktree"),signal:J?.signal,confirmationHandler:$.confirmationHandler,permissionMode:$.permissionMode,toolRegistry:b,deferredToolManager:b.deferredToolManager},Q.toolExecutor.getRegistry(),Q.executionEngine?.getContextManager(),$.sessionId,Y,$.subagentInfo),H=yield*S2(Q,j.toLLMMessages(),f,J?.signal,K0);else H=await Q.chatService.chat(j.toLLMMessages(),f,J?.signal)}catch(N){if(v2(N)){y.warn("[Loop] 检测到 prompt_too_long 错误,尝试反应式压缩");let K=Q.chatService.getConfig(),O=await HQ.tryReactiveCompact($.messages,{modelName:K.model,maxContextTokens:K.maxContextTokens??Q.config.maxContextTokens,apiKey:K.apiKey,baseURL:K.baseUrl,signal:J?.signal,activeTask:l});if(O.success){$.messages=O.messages,j.replaceHistory($.messages),y.info("[Loop] 反应式压缩成功,重试 LLM 调用"),G--;continue}}throw N}if(GQ=Date.now(),H.usage){if(H.usage.totalTokens)d+=H.usage.totalTokens;M0=H.usage.promptTokens,yield{kind:"token_usage",usage:{inputTokens:H.usage.promptTokens??0,outputTokens:H.usage.completionTokens??0,totalTokens:H.usage.totalTokens??0,maxContextTokens:Q.currentModelMaxContextTokens}}}let YZ=H.usage?.completionTokens??0;if(T0=qQ(T0,YZ,W0>0),J?.signal?.aborted)return q(G-1,V.length,J.signal);if(!XQ||!!H._nonStreamingFallback){if(H.reasoningContent&&H.reasoningContent.trim())yield{kind:"thinking_delta",delta:H.reasoningContent};if(H.content&&H.content.trim())yield{kind:"content_delta",delta:H.content}}yield{kind:"stream_end"};let C0=c0(H.finishReason,W0,T0);if(C0.action==="recover"){W0++,y.warn(`[Loop] Max output tokens hit (recovery ${W0}/3)`);let N={role:"assistant",content:H.content||"",reasoningContent:H.reasoningContent,tool_calls:H.toolCalls};j.appendToHistory(N);let K=await T(Q,$,H.content||"",Y);if(K)Y=K;let O={role:"user",content:"Output token limit hit. Resume directly — no apology, no recap. "+"Pick up mid-thought if that is where the cut happened. Break remaining work into smaller pieces."};j.appendToHistory(O);let D=await m(Q,$,O.content,Y);if(D)Y=D;continue}if(C0.action==="truncated"||C0.action==="budget_stop"){j.appendAssistant({role:"assistant",content:H.content||"",reasoningContent:H.reasoningContent,tool_calls:H.toolCalls});let N=await T(Q,$,H.content||"",Y);if(N)Y=N;return{success:!0,finalMessage:H.content,metadata:{turnsCount:G,toolCallsCount:V.length,duration:Date.now()-W,tokensUsed:d,outputTruncated:!0}}}if(H.finishReason!=="length")W0=0;if(!H.toolCalls||H.toolCalls.length===0){if(H.content&&QZ(F,H.content)){j.appendAssistant({role:"assistant",content:H.content||"",reasoningContent:H.reasoningContent}),j.appendControl("user",{role:"user",content:`
|
|
597
|
+
|
|
598
|
+
<system-reminder>
|
|
599
|
+
${ZZ()}
|
|
600
|
+
</system-reminder>`});continue}let N=u0(H.content,f0,!1);if(N.action==="retry"){f0++,j.appendAssistant({role:"assistant",content:H.content||"",reasoningContent:H.reasoningContent});let v=await T(Q,$,H.content||"",Y);if(v)Y=v;let I={role:"user",content:N.prompt};j.appendControl("user",I);let k=await m(Q,$,I.content,Y);if(k)Y=k;continue}f0=0;let K=wQ(l,x,h0);if(K.action==="retry"){h0++,j.appendAssistant({role:"assistant",content:H.content||"",reasoningContent:H.reasoningContent});let v=await T(Q,$,H.content||"",Y);if(v)Y=v;let I={role:"user",content:K.prompt};j.appendControl("user",I);let k=await m(Q,$,I.content,Y);if(k)Y=k;continue}if(K.action==="fail"){j.appendAssistant({role:"assistant",content:H.content||"",reasoningContent:H.reasoningContent});let v=await T(Q,$,H.content||"",Y);if(v)Y=v;return{success:!1,error:{type:"delegation_protocol_failed",message:K.message},metadata:{turnsCount:G,toolCallsCount:V.length,duration:Date.now()-W,tokensUsed:d}}}h0=0;let O=LQ(l,x,x0);if(O.action==="retry"){x0++,j.appendAssistant({role:"assistant",content:H.content||"",reasoningContent:H.reasoningContent});let v=await T(Q,$,H.content||"",Y);if(v)Y=v;let I={role:"user",content:O.prompt};j.appendControl("user",I);let k=await m(Q,$,I.content,Y);if(k)Y=k;continue}if(O.action==="fail"){j.appendAssistant({role:"assistant",content:H.content||"",reasoningContent:H.reasoningContent});let v=await T(Q,$,H.content||"",Y);if(v)Y=v;return{success:!1,error:{type:"worktree_protocol_failed",message:O.message},metadata:{turnsCount:G,toolCallsCount:V.length,duration:Date.now()-W,tokensUsed:d}}}x0=0;let D=i0(YQ,R0,k0);if(D.action==="retry"){k0++,j.appendAssistant({role:"assistant",content:H.content||"",reasoningContent:H.reasoningContent});let v=await T(Q,$,H.content||"",Y);if(v)Y=v;let I={role:"user",content:D.prompt};j.appendControl("user",I);let k=await m(Q,$,I.content,Y);if(k)Y=k;continue}if(D.action==="fail"){j.appendAssistant({role:"assistant",content:H.content||"",reasoningContent:H.reasoningContent});let v=await T(Q,$,H.content||"",Y);if(v)Y=v;return{success:!1,error:{type:"verification_failed",message:D.message},metadata:{turnsCount:G,toolCallsCount:V.length,duration:Date.now()-W,tokensUsed:d}}}k0=0;let C=await l0({sessionId:$.sessionId,permissionMode:$.permissionMode,reason:H.content,abortSignal:J?.signal});if(C.action==="continue"){j.appendAssistant({role:"assistant",content:H.content||"",reasoningContent:H.reasoningContent});let v=await T(Q,$,H.content||"",Y);if(v)Y=v;let k={role:"user",content:C.reason?`
|
|
601
|
+
|
|
602
|
+
<system-reminder>
|
|
603
|
+
${C.reason}
|
|
604
|
+
</system-reminder>`:`
|
|
605
|
+
|
|
606
|
+
<system-reminder>
|
|
607
|
+
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.
|
|
608
|
+
</system-reminder>`};j.appendControl("user",k);let j0=await m(Q,$,k.content,Y);if(j0)Y=j0;continue}j.appendAssistant({role:"assistant",content:H.content||"",reasoningContent:H.reasoningContent});let P=await T(Q,$,H.content||"",Y);if(P)Y=P;return{success:!0,finalMessage:H.content,metadata:{turnsCount:G,toolCallsCount:V.length,duration:Date.now()-W,tokensUsed:d,toolSuccessRate:V.length>0?V.filter((v)=>v.success).length/V.length:void 0,totalToolFailures:A.totalFailures||void 0}}}j.appendAssistant({role:"assistant",content:H.content||"",reasoningContent:H.reasoningContent,tool_calls:H.toolCalls});{let N=await T(Q,$,H.content||"",Y);if(N)Y=N}if(J?.signal?.aborted)return q(G,V.length,J.signal);let p0=H.toolCalls.filter((N)=>N.type==="function"),B0;if(K0?.hasTools()){y.debug(`[Loop] 使用 StreamingToolExecutor 收集 ${p0.length} 个工具结果`),B0=[];for await(let N of K0.getRemainingResults())B0.push(N)}else{for(let K of p0){let D=b.get(K.function.name)?.kind;yield{kind:"tool_start",toolCall:K,toolKind:D}}let N=async(K)=>{try{let O=WZ(K.function.arguments);if(O===null)return{toolCall:K,result:{success:!1,llmContent:"",error:{type:"validation_error",message:`Invalid JSON object in tool arguments. Raw: ${K.function.arguments.slice(0,200)}`},metadata:void 0},toolUseUuid:null};if(K.function.name==="Task"&&(typeof O.subagent_session_id!=="string"||O.subagent_session_id.length===0))O.subagent_session_id=typeof O.resume==="string"&&O.resume.length>0?O.resume:j2();let D=null;if(D=await r0(Q,$,K.function.name,O,Y),K.function.name==="ExitWorktree"&&x.has("EnterWorktree")&&!x.has("ExitWorktree")&&i0(YQ,R0,0).action!=="none"){let v="Run the requested verification before ExitWorktree. The worktree remains active so Bash can run in isolation.";return{toolCall:K,result:{success:!1,llmContent:v,error:{type:"validation_error",message:v},metadata:{summary:"Blocked ExitWorktree until verification succeeds"}},toolUseUuid:D}}let P=await Q.toolExecutor.execute(K.function.name,O,{sessionId:$.sessionId,userId:$.userId||"default",workspaceRoot:$.workspaceRoot||p(),worktreeIsolationRequired:VQ,worktreeActive:x.has("EnterWorktree")&&!x.has("ExitWorktree"),signal:J?.signal,confirmationHandler:$.confirmationHandler,permissionMode:$.permissionMode,toolRegistry:b,deferredToolManager:b.deferredToolManager});return{toolCall:K,result:P,toolUseUuid:D}}catch(O){return y.error(`Tool execution failed for ${K.function.name}:`,O),{toolCall:K,result:{success:!1,llmContent:"",error:{type:"execution_error",message:O instanceof Error?O.message:"Unknown error"},metadata:void 0},toolUseUuid:null,error:O instanceof Error?O:Error("Unknown error")}}};B0=await Promise.all(p0.map(N))}let VZ=new ZQ;for(let{toolCall:N,result:K,toolUseUuid:O}of B0){let D=N;if(V.push(K),K.metadata?.abortedBeforeLaunch)return q(G,V.length,J?.signal);yield{kind:"tool_result",toolCall:D,result:K};{let I=K.metadata&&typeof K.metadata==="object"?K.metadata:void 0,j0=((q0)=>q0==="running"||q0==="completed"||q0==="failed"||q0==="cancelled")(I?.subagentStatus)?I.subagentStatus:"completed",XZ=I&&typeof I.subagentSessionId==="string"?{subagentSessionId:I.subagentSessionId,subagentType:typeof I.subagentType==="string"?I.subagentType:D.function.name,subagentStatus:j0,subagentSummary:typeof I.subagentSummary==="string"?I.subagentSummary:void 0}:void 0,KQ=await o0(Q,$,D.id,D.function.name,K.success?O2(K.llmContent):null,O,K.success?void 0:K.error?.message,XZ);if(KQ)Y=KQ}let C=await s0(D,K,Q,$);if(C)yield C;if(K.success){if(aQ(A,D.function.name),D.function.name==="EnterWorktree"&&K.metadata?.workspaceTransition==="enter")x.add("EnterWorktree"),x.delete("ExitWorktree");else if(D.function.name==="ExitWorktree"&&K.metadata?.workspaceTransition==="exit"&&x.has("EnterWorktree"))x.add("ExitWorktree");else if(!["EnterWorktree","ExitWorktree"].includes(D.function.name))x.add(D.function.name);if(D.function.name==="Task"&&K.metadata?.isolation==="worktree")x.add("TaskWorktree");OQ(R0,D.function.name,K)}else rQ(A,D.function.name);let P=K.success?K.llmContent||"":_2(D.function.name,K.error);if(!K.success){let I=oQ(A,D.function.name);if(I&&typeof P==="string")P=`${P}
|
|
609
|
+
|
|
610
|
+
${I}`}if(typeof P==="object"&&P!==null)P=JSON.stringify(P,null,2);if(typeof P==="string")P=xQ(P,D.function.name,{messageBudget:VZ});let v=typeof P==="string"?P:JSON.stringify(P);if(j.appendToolResult({role:"tool",tool_call_id:D.id,name:D.function.name,content:v}),K.metadata?.shouldExitLoop){let I=typeof K.llmContent==="string"?K.llmContent:"循环已退出";return{success:K.success,finalMessage:I,metadata:{turnsCount:G,toolCallsCount:V.length,duration:Date.now()-W,shouldExitLoop:!0,targetMode:K.metadata?.targetMode,planContent:typeof K.metadata?.planContent==="string"?K.metadata.planContent:void 0}}}}if(J?.signal?.aborted)return q(G,V.length,J.signal);let d0=G>=P0,HZ=G>=h&&(J0||!$0||c);if(d0||HZ){let N=d0?P0:h;if(y.info(`Warning: 达到轮次上限 ${N} 轮`),J?.onTurnLimitReached){let K=await J.onTurnLimitReached({turnsCount:G});if(K?.continue){j.writeback();try{let O=Q.chatService.getConfig(),D=await Q0.compact($.messages,{trigger:"auto",modelName:O.model,maxContextTokens:O.maxContextTokens??Q.config.maxContextTokens,apiKey:O.apiKey,baseURL:O.baseUrl,actualPreTokens:M0,signal:J?.signal,activeTask:l});$.messages=D.compactedMessages,j.replaceHistory($.messages);let C={role:"user",content:`This session is being continued from a previous conversation. The conversation is summarized above.
|
|
611
|
+
|
|
612
|
+
Please continue the conversation from where we left it off without asking the user any further questions. Continue with the last task that you were asked to work on.`};j.appendToHistory(C),await O0(Q,$,D.summary,{trigger:"auto",preTokens:D.preTokens,postTokens:D.postTokens,filesIncluded:D.filesIncluded})}catch(O){y.error("[Loop] 压缩失败,使用降级策略:",O);let C=j.getHistory().slice(-80);j.replaceHistory(C)}G=0;continue}return{success:!0,finalMessage:K?.reason||"已达到对话轮次上限,用户选择停止",metadata:{turnsCount:G,toolCallsCount:V.length,duration:Date.now()-W,tokensUsed:d}}}return{success:!1,error:{type:"max_turns_exceeded",message:c?`子代理已达到轮次上限 (${N} 轮)。`:`已达到${d0?"安全":"显式"}轮次上限 (${N} 轮)。`},metadata:{turnsCount:G,toolCallsCount:V.length,duration:Date.now()-W,tokensUsed:d}}}}}finally{j.writeback()}}catch(b){if(o(b))return q(G,V.length,J?.signal);let X=w2(b);return y.error(`API 调用失败: ${X}`),{success:!1,error:{type:"api_error",message:X,details:b},metadata:{turnsCount:G,toolCallsCount:V.length,duration:Date.now()-W}}}finally{if(B)$.messages.push({role:"system",content:a0}),await _Q(Q,$,Y)}}export{t0 as Na,pQ as Oa,cQ as Pa,y0 as Qa,G2 as Ra,u as Sa,c0 as Ta,u0 as Ua,OQ as Va,l0 as Wa,D0 as Xa,b0 as Ya,KZ as Za,m as _a,T as $a,r0 as ab,o0 as bb,O0 as cb,vQ as db,NQ as eb,IQ as fb,s0 as gb,Y0 as hb,Q0 as ib,A0 as jb,GZ as kb,E2 as lb};
|