blade-code 0.7.1 → 0.7.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/blade.js +2 -2
- package/dist/{chunk-xmdpc0y5.js → chunk-06awrjgg.js} +2 -2
- package/dist/chunk-1vngdr7p.js +1 -0
- package/dist/{chunk-2dvn9y9f.js → chunk-29pqj0tb.js} +1 -1
- package/dist/{chunk-56frm8dx.js → chunk-373pmz70.js} +1 -1
- package/dist/{chunk-zxddgwsb.js → chunk-38h3yh6z.js} +1 -1
- package/dist/{chunk-bmxgshct.js → chunk-5n7h04jg.js} +1 -1
- package/dist/chunk-5smacbk0.js +24 -0
- package/dist/chunk-63dzf6hr.js +2 -0
- package/dist/{chunk-f8mjpmdx.js → chunk-87gff8b7.js} +1 -1
- package/dist/chunk-98fvxsvc.js +6 -0
- package/dist/chunk-98jpdmgc.js +9 -0
- package/dist/chunk-aevyre2t.js +1 -0
- package/dist/chunk-avebc3bj.js +2 -0
- package/dist/chunk-b4hmtjec.js +1 -0
- package/dist/{chunk-zm4jr1k2.js → chunk-bmcc85nj.js} +1 -1
- package/dist/chunk-cqrg2pp7.js +1 -0
- package/dist/{chunk-zvk6ktj1.js → chunk-cw125vv3.js} +1 -1
- package/dist/{chunk-f76d6jxg.js → chunk-cyxb6fxe.js} +1 -1
- package/dist/{chunk-a7dw8fwn.js → chunk-d0fata6n.js} +1 -1
- package/dist/{chunk-qyfdt8h1.js → chunk-e21htmg4.js} +1 -1
- package/dist/chunk-e9kfbbpm.js +1 -0
- package/dist/chunk-eady1q1w.js +150 -0
- package/dist/{chunk-dzmrdtpc.js → chunk-gb0x14v5.js} +37 -34
- package/dist/{chunk-7v7s2aag.js → chunk-gjf2d2yg.js} +1 -1
- package/dist/chunk-hs4j2fcr.js +6 -0
- package/dist/{chunk-qds0yxfy.js → chunk-jf48kahn.js} +3 -3
- package/dist/{chunk-h7qab07x.js → chunk-k4behavv.js} +1 -1
- package/dist/chunk-k63hr1eg.js +7 -0
- package/dist/{chunk-0afbeec0.js → chunk-kfg3vx5z.js} +1 -1
- package/dist/{chunk-v1d0d4b4.js → chunk-pvxp2gzr.js} +1 -1
- package/dist/{chunk-7z6ba6t9.js → chunk-qxvp127d.js} +1 -1
- package/dist/{chunk-867h27ke.js → chunk-rkhhzc4r.js} +2 -2
- package/dist/{chunk-b0q2q0ax.js → chunk-rtn0rb16.js} +2 -2
- package/dist/chunk-txjvy8qp.js +1 -0
- package/dist/{chunk-1dt2y16n.js → chunk-vw3f4mbt.js} +1 -1
- package/dist/chunk-w1zb8zac.js +3 -0
- package/dist/chunk-wev2rke6.js +1 -0
- package/dist/chunk-wp67n9q7.js +1534 -0
- package/dist/{chunk-aam53te2.js → chunk-y50fy1gq.js} +2 -2
- package/dist/web/assets/{FilePreview-DLnUh-wQ.js → FilePreview-IDRQBiWa.js} +1 -1
- package/dist/web/assets/{MarkdownRenderer-C5KTk9XG.js → MarkdownRenderer-BgDKGD2u.js} +1 -1
- package/dist/web/assets/{McpModal-B9qJ4ewt.js → McpModal-CJ2l7j-5.js} +1 -1
- package/dist/web/assets/{SettingsModal-DpeZ6cJb.js → SettingsModal-BWpbIioU.js} +1 -1
- package/dist/web/assets/{SettingsStore-IzKtyAnM.js → SettingsStore-BZjkLZcL.js} +1 -1
- package/dist/web/assets/{SkillsModal-BDfzgJIj.js → SkillsModal-CRuRJrN-.js} +1 -1
- package/dist/web/assets/{TerminalPanel-B2iTF_CR.js → TerminalPanel-BnZPkS19.js} +1 -1
- package/dist/web/assets/{dialog-sI3ihAze.js → dialog-DYRMhlp_.js} +1 -1
- package/dist/web/assets/index-Bu13aXyE.css +1 -0
- package/dist/web/assets/index-D4CAglTd.js +10 -0
- package/dist/web/index.html +2 -2
- package/package.json +1 -1
- package/dist/chunk-0k8js58t.js +0 -6
- package/dist/chunk-0vd9antx.js +0 -1
- package/dist/chunk-6jezjq4h.js +0 -6
- package/dist/chunk-6k4vs71p.js +0 -1
- package/dist/chunk-70ya127f.js +0 -1
- package/dist/chunk-7ycmx7c2.js +0 -2
- package/dist/chunk-92qcc3gj.js +0 -2138
- package/dist/chunk-a2nshjdc.js +0 -49
- package/dist/chunk-a8eedntd.js +0 -6
- package/dist/chunk-d3db8wrw.js +0 -1
- package/dist/chunk-e06p3dkw.js +0 -157
- package/dist/chunk-k9h9bw13.js +0 -76
- package/dist/chunk-m51xzgwt.js +0 -1
- package/dist/chunk-mt1c5da4.js +0 -3
- package/dist/chunk-qdnx9x5g.js +0 -2
- package/dist/chunk-r6paqm6d.js +0 -1
- package/dist/chunk-v0rjbvky.js +0 -9
- package/dist/chunk-vs915jzz.js +0 -1
- package/dist/chunk-zbtb3jxm.js +0 -1
- package/dist/web/assets/index-D8mo0jzF.js +0 -10
- package/dist/web/assets/index-DmXmCQOW.css +0 -1
|
@@ -1,21 +1,21 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{nb as N0}from"./chunk-jf48kahn.js";import{tb as g}from"./chunk-63dzf6hr.js";import{Ab as hQ,xb as YZ,yb as Q0,zb as WZ}from"./chunk-98jpdmgc.js";import{Cb as PQ,Lb as p}from"./chunk-w1zb8zac.js";function L0(Q){return Q.role==="system"&&Array.isArray(Q.content)}class _0{systemMessages;_history;_pending=[];context;constructor(Q,Z){this.context=Q;let $=Q.messages.find(L0);if($)this.systemMessages=[$];else if(Z)this.systemMessages=[{role:"system",content:[{type:"text",text:Z,providerOptions:{anthropic:{cacheControl:{type:"ephemeral"}}}}]}];else this.systemMessages=[];this._history=Q.messages.filter((J)=>!L0(J))}get historyLength(){return this._history.length}get history(){return this._history}get pending(){return this._pending}toLLMMessages(){return[...this.systemMessages,...this._history,...this._pending]}getMessagesForLLM(){return this.toLLMMessages()}getHistory(){return this._history}appendPending(Q){this._pending.push(Q)}appendUser(Q){this._pending.push(Q)}appendAssistant(Q){this._pending.push(Q)}appendToolResult(Q){this._pending.push(Q)}appendControl(Q,Z){if(Q==="system")throw Error("Cannot append system control message via appendControl. Use constructor for root system prompt.");this._pending.push(Z)}appendToHistory(Q){this._history.push(Q)}commitPending(){if(this._pending.length>0)this._history.push(...this._pending),this._pending=[]}replaceHistory(Q){this._history=Q.filter((Z)=>!L0(Z))}writeback(){this.commitPending(),this.context.messages=this._history}get hasSystemPrompt(){return this.systemMessages.length>0}}async function jZ(Q,Z){let $;while(!($=await Q.next()).done)if(Z)await Z($.value);return $.value}function DQ(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 bQ(Q){return{budget:Q.budget,usage:0,consecutiveContinuations:0,lastOutputDelta:0,isSubagent:Q.isSubagent??!1}}function FQ(Q,Z,$){return{...Q,usage:Q.usage+Z,lastOutputDelta:Z,consecutiveContinuations:$?Q.consecutiveContinuations+1:0}}var r0=p("Agent"),qZ=3;function s0(Q,Z,$){if(Q!=="length")return{action:"none"};if(Z>=qZ)return{action:"truncated"};if(DQ($)==="stop")return r0.info("[Loop] Token budget: diminishing returns detected, skipping recovery"),{action:"budget_stop"};return{action:"recover"}}var DZ=[/:\s*$/,/:\s*$/,/\.\.\.\s*$/,/让我(先|来|开始|查看|检查|修复)/,/Let me (first|start|check|look|fix)/i,/I('ll| will) (now |)(create|write|edit|update|modify|fix|add|implement)/i,/我(现在就|来|要)(创建|写入|编辑|修改|修复|添加|实现)/,/\d+\.\s+(First|Next|Then|Finally)/i],bZ=/```[\s\S]{50,}```/,OQ="请执行你提到的操作,不要只是描述。使用 Edit/Write/Bash 工具来实际修改文件。",FZ=2;function t0(Q,Z,$=!0){if(!Q||Z>=FZ)return{action:"none"};if(!$&&bZ.test(Q))return{action:"retry",prompt:OQ};let J=Q.slice(-200),z=J.match(/```/g);if(z&&z.length%2!==0)return{action:"none"};if(DZ.some((G)=>G.test(J)))return{action:"retry",prompt:OQ};return{action:"none"}}var OZ=[/\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}(?:测试|单测|集成测试|检查|构建)/],wZ=/(?:^|\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,wQ={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},LZ={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},_Z="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.",NZ="Required verification did not run successfully before the retry limit.",vZ=3;function o0(Q){return wZ.test(Q)}function _Q(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&&o0($.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"&&o0(z))Q.add(z)}function e0(Q,Z,$){if(!Q||!OZ.some((Y)=>Y.test(Q)))return{action:"none"};let J=Object.keys(wQ).filter((Y)=>wQ[Y].test(Q)),z=[...Z],W=J.filter((Y)=>!z.some((B)=>LZ[Y].test(B)));if(J.length>0?W.length===0:z.some(o0))return{action:"none"};if($>=vZ)return{action:"fail",message:NZ};let V=J.length>1&&W.length>0?` Missing successful verification categories: ${W.join(", ")}.`:"";return{action:"retry",prompt:`${_Z}${V}`}}var IZ=[/\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|子代理|子智能体)/],EZ=[/\b(?:do not|don't|never)\s+(?:delegate|call|use|invoke)\b/i,/(?:不要|禁止|无需)(?:委派|调用|使用).{0,20}(?:Task|子代理|子智能体)?/],SZ="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.",UZ="Required delegation did not complete before the retry limit.",yZ=3;function NQ(Q,Z,$){if(!Q||EZ.some((J)=>J.test(Q))||!IZ.some((J)=>J.test(Q))||Z.has("Task"))return{action:"none"};if($>=yZ)return{action:"fail",message:UZ};return{action:"retry",prompt:SZ}}var AZ=[/\b(?:use|create|enter|start|work\s+(?:in|inside))\b.{0,60}\bworktree\b/i,/(?:使用|创建|进入).{0,30}(?:worktree|工作树)/i],PZ=[/\b(?:exit|leave)\b.{0,40}\bworktree\b/i,/\bworktree\b.{0,60}\b(?:action\s+)?(?:keep|remove)\b/i,/(?:退出|离开).{0,30}(?:worktree|工作树)/i];function v0(Q){return typeof Q==="string"&&AZ.some((Z)=>Z.test(Q))}var MZ="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.",fZ="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.",hZ="Required worktree lifecycle did not complete before the retry limit.",kZ=3;function vQ(Q,Z,$){if(!Q||!v0(Q))return{action:"none"};let J=PZ.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($>=kZ)return{action:"fail",message:hZ};return{action:"retry",tool:z,prompt:z==="EnterWorktree"?MZ:fZ}}var LQ=30000;async function QQ(Q){try{let $=N0.getInstance().executeStopHooks({projectDir:g(),sessionId:Q.sessionId,permissionMode:Q.permissionMode,reason:Q.reason,abortSignal:Q.abortSignal}),J,z=new Promise((W)=>{J=setTimeout(()=>W("timeout"),LQ)});try{let W=await Promise.race([$,z]);if(W==="timeout")return r0.warn(`[Loop] Stop hook 超时 (${LQ}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 r0.warn("[Loop] Stop hook execution failed:",Z),{action:"stop"}}}var $0=p("Agent"),ZQ=`<turn_aborted>
|
|
2
2
|
The previous turn was interrupted. Commands or tool calls may have partially completed; inspect the workspace and running processes before retrying.
|
|
3
|
-
</turn_aborted>`;function
|
|
3
|
+
</turn_aborted>`;function J0(Q){return Q.executionEngine?.getContextManager()}async function i(Q,Z,$,J=null,z){try{let W=J0(Q),G=typeof $==="string"?$.trim()!=="":$.some((V)=>V.type==="text"?V.text.trim()!=="":!0);if(W&&Z.sessionId&&G)return await W.saveMessage(Z.sessionId,"user",$,J,z,Z.subagentInfo)}catch(W){$0.warn("[Loop] 保存用户消息失败:",W)}return null}async function h(Q,Z,$,J){try{let z=J0(Q);if(z&&Z.sessionId&&$.trim())return await z.saveMessage(Z.sessionId,"assistant",$,J,void 0,Z.subagentInfo)}catch(z){$0.warn("[Loop] 保存助手消息失败:",z)}return null}async function IQ(Q,Z,$){try{let J=J0(Q);if(J&&Z.sessionId)return await J.saveMessage(Z.sessionId,"system",ZQ,$,void 0,Z.subagentInfo)}catch(J){$0.warn("[Loop] 保存中断边界失败:",J)}return null}async function $Q(Q,Z,$,J,z){try{let W=J0(Q);if(W&&Z.sessionId)return await W.saveToolUse(Z.sessionId,$,J,z,Z.subagentInfo)}catch(W){$0.warn("[Loop] 保存工具调用失败:",W)}return null}async function JQ(Q,Z,$,J,z,W,G,V){try{let Y=J0(Q);if(Y&&Z.sessionId)return await Y.saveToolResult(Z.sessionId,$,J,z,W,G,Z.subagentInfo,V)}catch(Y){$0.warn("[Loop] 保存工具结果失败:",Y)}return null}async function I0(Q,Z,$,J){try{let z=J0(Q);if(z&&Z.sessionId)return await z.saveCompaction(Z.sessionId,$,J,null)}catch(z){$0.warn("[Loop] 保存压缩数据失败:",z)}return null}function EQ(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 SQ(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 UQ(Q){let Z=Q.metadata;if(!Z)return;return Z.modelId?.toString().trim()||Z.model?.toString().trim()||void 0||void 0}function xZ(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 RZ(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 zQ(Q,Z,$,J){let z=EQ(Q,Z),W=RZ(Q,Z);SQ(Q,Z,$);let G=UQ(Z);if(G)await $.onModelSwitch?.(G);if(J)xZ(Q,Z,J);return W||z}import{nanoid as D2}from"nanoid";import{promises as uZ}from"node:fs";import{nanoid as s}from"nanoid";import*as U from"node:fs/promises";import*as e from"node:path";var yQ={enabled:!0,maxIndexLines:200};var TZ="memory",AQ="MEMORY.md";class WQ{memoryDir;config;initialized=!1;constructor(Q,Z,$){if($)this.memoryDir=$;else{let J=PQ(Q);this.memoryDir=e.join(J,TZ)}this.config={...yQ,...Z}}async initialize(){if(this.initialized)return;await U.mkdir(this.memoryDir,{recursive:!0}),this.initialized=!0}async loadIndex(){if(!this.config.enabled)return null;await this.initialize();let Q=e.join(this.memoryDir,AQ);try{let Z=await U.readFile(Q,"utf-8");if(!Z.trim())return null;let $=Z.split(`
|
|
4
4
|
`),z=$.slice(0,this.config.maxIndexLines).join(`
|
|
5
5
|
`).trim();if($.length>this.config.maxIndexLines)return z+`
|
|
6
6
|
|
|
7
|
-
<!-- ${$.length-this.config.maxIndexLines} more lines in MEMORY.md, use MemoryRead to access -->`;return z||null}catch(Z){if(Z instanceof Error&&"code"in Z&&Z.code==="ENOENT")return null;throw Z}}async readTopic(Q){await this.initialize();let Z=this.resolveTopicPath(Q);try{return await
|
|
7
|
+
<!-- ${$.length-this.config.maxIndexLines} more lines in MEMORY.md, use MemoryRead to access -->`;return z||null}catch(Z){if(Z instanceof Error&&"code"in Z&&Z.code==="ENOENT")return null;throw Z}}async readTopic(Q){await this.initialize();let Z=this.resolveTopicPath(Q);try{return await U.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 U.readFile(J,"utf-8")}catch{}let W=z&&!z.endsWith(`
|
|
8
8
|
`)?`
|
|
9
|
-
`:"";await
|
|
9
|
+
`:"";await U.writeFile(J,z+W+Z,"utf-8")}else await U.writeFile(J,Z,"utf-8")}async updateIndex(Q,Z="overwrite"){await this.initialize();let $=e.join(this.memoryDir,AQ);if(Z==="append"){let J="";try{J=await U.readFile($,"utf-8")}catch{}let z=J&&!J.endsWith(`
|
|
10
10
|
`)?`
|
|
11
|
-
`:"";await
|
|
11
|
+
`:"";await U.writeFile($,J+z+Q,"utf-8")}else await U.writeFile($,Q,"utf-8")}async listTopics(){await this.initialize();try{let Q=await U.readdir(this.memoryDir,{withFileTypes:!0}),Z=[];for(let $ of Q){if(!$.isFile()||!$.name.endsWith(".md"))continue;let J=e.join(this.memoryDir,$.name),z=await U.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 U.unlink(Z),!0}catch{return!1}}async clearAll(){let Q=await this.listTopics(),Z=0;for(let $ of Q){let J=e.join(this.memoryDir,`${$.name}.md`);try{await U.unlink(J),Z++}catch{}}return Z}getMemoryDir(){return this.memoryDir}resolveTopicPath(Q){let Z=Q.replace(/[/\\:*?"<>|]/g,"-"),$=Z.endsWith(".md")?Z:`${Z}.md`,J=e.join(this.memoryDir,$);if(!J.startsWith(this.memoryDir))throw Error(`Invalid topic name: ${Q}`);return J}}var CZ=[{pattern:/(?:记住|remember|note|备注)[::](.+)/i,topic:"preferences"},{pattern:/(?:convention|约定|规范)[::](.+)/i,topic:"conventions"},{pattern:/(?:lesson|教训|踩坑)[::](.+)/i,topic:"lessons"}],pZ=/(?:fix|修复|解决|resolved)[::]\s*(.+?)(?:\n|$)/i,dZ=/(?:Error|FAIL|错误)[::]\s*(.+?)(?:\n|$)/i;function mZ(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 CZ){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(pZ);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(dZ);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 MQ(Q){let Z=mZ(Q);if(Z.size===0)return{extracted:0,topics:[]};try{let $=new WQ(g());await $.initialize();let J=[],z=0;for(let[W,G]of Z){if(G.length===0)continue;let V=new Date().toISOString().split("T")[0],Y=G.map((B)=>`- [${V}] ${B}`).join(`
|
|
12
12
|
`);await $.writeTopic(W,Y+`
|
|
13
|
-
`,"append"),J.push(W),z+=G.length}return{extracted:z,topics:J}}catch{return{extracted:0,topics:[]}}}import{promises as
|
|
14
|
-
`);if(this.extractFilePathsFromContent(W).forEach((V)=>{this.updateFileReference(Z,V,z,!1)}),J.tool_calls&&Array.isArray(J.tool_calls))J.tool_calls.forEach((V)=>{let Y=this.extractFilePathsFromToolCall(V),B=V.type==="function"&&"function"in V?V.function?.name:"",q=["Write","Edit"].includes(B||"");Y.forEach((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
|
|
13
|
+
`,"append"),J.push(W),z+=G.length}return{extracted:z,topics:J}}catch{return{extracted:0,topics:[]}}}import{promises as E0}from"node:fs";var B0=p("Tool");class o{static instance=null;accessedFiles=new Map;constructor(){}static getInstance(){if(!o.instance)o.instance=new o;return o.instance}async recordFileRead(Q,Z){try{let $=await E0.stat(Q),J={filePath:Q,accessTime:Date.now(),mtime:$.mtimeMs,sessionId:Z,lastOperation:"read"};this.accessedFiles.set(Q,J),B0.debug(`记录文件读取: ${Q}`)}catch($){B0.warn(`记录文件读取失败: ${Q}`,$)}}async recordFileEdit(Q,Z,$="edit"){try{let J=await E0.stat(Q),z={filePath:Q,accessTime:Date.now(),mtime:J.mtimeMs,sessionId:Z,lastOperation:$};this.accessedFiles.set(Q,z),B0.debug(`记录文件${$==="edit"?"编辑":"写入"}: ${Q}`)}catch(J){B0.warn(`记录文件${$==="edit"?"编辑":"写入"}失败: ${Q}`,J)}}hasFileBeenRead(Q,Z){let $=this.accessedFiles.get(Q);if(!$)return!1;if(Z&&$.sessionId!==Z)return!1;return!0}async checkFileModification(Q){let Z=this.accessedFiles.get(Q);if(!Z)return{modified:!1,message:"文件未被跟踪"};try{let $=await E0.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 E0.stat(Q);if($.mtimeMs-Z.mtime>2000)return{isExternal:!0,message:`文件在 ${new Date(Z.accessTime).toISOString()} (${Z.lastOperation}) 之后被外部程序修改(当前修改时间: ${$.mtime.toISOString()})`};return{isExternal:!1}}catch($){let J=$;if(J.code==="ENOENT")return{isExternal:!0,message:"文件已被删除"};return B0.warn(`检查文件外部修改失败: ${Q}`,$),{isExternal:!1,message:`无法检查文件状态: ${J.message}`}}}getFileRecord(Q){return this.accessedFiles.get(Q)}clearFileRecord(Q){this.accessedFiles.delete(Q)}clearAll(){this.accessedFiles.clear()}clearSession(Q){for(let[Z,$]of this.accessedFiles.entries())if($.sessionId===Q)this.accessedFiles.delete(Z)}getTrackedFiles(){return Array.from(this.accessedFiles.keys())}getTrackedFileCount(){return this.accessedFiles.size}static resetInstance(){o.instance=null}}import{readFile as gZ}from"node:fs/promises";import{basename as cZ}from"node:path";class S0{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 gZ($,"utf-8"),z=J.split(`
|
|
15
15
|
`),W=z.length,G=J,V=!1,Y=W;if(W>this.MAX_LINES_PER_FILE)G=z.slice(0,this.MAX_LINES_PER_FILE).join(`
|
|
16
16
|
`),G+=`
|
|
17
17
|
|
|
18
|
-
... (truncated ${W-this.MAX_LINES_PER_FILE} lines)`,V=!0,Y=this.MAX_LINES_PER_FILE;Z.push({path:$,content:G,truncated:V,lines:W,includedLines:Y})}catch(J){console.warn(`[FileAnalyzer] 无法读取文件: ${$}`,J)}return Z}static extractFilePathsFromContent(Q){let Z=new Set,$=/```(?:\w+)?\s*\n?([\s\S]*?)```/g,J=Array.from(Q.matchAll($));for(let W of J){let G=W[1];this.extractPathsFromText(G).forEach((Y)=>Z.add(Y))}return this.extractPathsFromText(Q).forEach((W)=>Z.add(W)),Array.from(Z)}static extractPathsFromText(Q){let Z=[],$=[/(?:src|tests?|docs?|lib|config|scripts?|bin|utils?|components?|services?|hooks?)\/[\w\-/.]+\.[\w]+/g,/(?:package|tsconfig|vite\.config|webpack\.config|next\.config|babel\.config)\.[\w]+/g,/(?:\.\.?\/|\/)[a-zA-Z0-9\-_/.]+\.[\w]+/g];for(let J of $){let z=Array.from(Q.matchAll(J));for(let W of z){let G=W[0];if(G=G.replace(/[,。;:!?""''()【】《》]$/g,""),G=G.replace(/[,.;:!?"'()[\]<>]$/g,""),this.isValidFilePath(G))Z.push(G)}}return Z}static extractFilePathsFromToolCall(Q){let Z=[];if(Q.type!=="function"||!Q.function)return Z;try{let $=Q.function.name,J=JSON.parse(Q.function.arguments||"{}");if(["Read","Write","Edit","Glob","Grep","NotebookEdit","mcp__github__get_file_contents","mcp__github__create_or_update_file"].includes($)){let W=["file_path","path","notebook_path","filePath"];for(let G of W)if(J[G]&&typeof J[G]==="string")Z.push(J[G])}}catch{}return Z}static updateFileReference(Q,Z,$,J){let z=Q.get(Z);if(z)z.mentions++,z.lastMentioned=$,z.wasModified=z.wasModified||J;else Q.set(Z,{path:Z,mentions:1,lastMentioned:$,wasModified:J})}static isValidFilePath(Q){if(!Q.includes("/"))return!1;let Z=
|
|
18
|
+
... (truncated ${W-this.MAX_LINES_PER_FILE} lines)`,V=!0,Y=this.MAX_LINES_PER_FILE;Z.push({path:$,content:G,truncated:V,lines:W,includedLines:Y})}catch(J){console.warn(`[FileAnalyzer] 无法读取文件: ${$}`,J)}return Z}static extractFilePathsFromContent(Q){let Z=new Set,$=/```(?:\w+)?\s*\n?([\s\S]*?)```/g,J=Array.from(Q.matchAll($));for(let W of J){let G=W[1];this.extractPathsFromText(G).forEach((Y)=>Z.add(Y))}return this.extractPathsFromText(Q).forEach((W)=>Z.add(W)),Array.from(Z)}static extractPathsFromText(Q){let Z=[],$=[/(?:src|tests?|docs?|lib|config|scripts?|bin|utils?|components?|services?|hooks?)\/[\w\-/.]+\.[\w]+/g,/(?:package|tsconfig|vite\.config|webpack\.config|next\.config|babel\.config)\.[\w]+/g,/(?:\.\.?\/|\/)[a-zA-Z0-9\-_/.]+\.[\w]+/g];for(let J of $){let z=Array.from(Q.matchAll(J));for(let W of z){let G=W[0];if(G=G.replace(/[,。;:!?""''()【】《》]$/g,""),G=G.replace(/[,.;:!?"'()[\]<>]$/g,""),this.isValidFilePath(G))Z.push(G)}}return Z}static extractFilePathsFromToolCall(Q){let Z=[];if(Q.type!=="function"||!Q.function)return Z;try{let $=Q.function.name,J=JSON.parse(Q.function.arguments||"{}");if(["Read","Write","Edit","Glob","Grep","NotebookEdit","mcp__github__get_file_contents","mcp__github__create_or_update_file"].includes($)){let W=["file_path","path","notebook_path","filePath"];for(let G of W)if(J[G]&&typeof J[G]==="string")Z.push(J[G])}}catch{}return Z}static updateFileReference(Q,Z,$,J){let z=Q.get(Z);if(z)z.mentions++,z.lastMentioned=$,z.wasModified=z.wasModified||J;else Q.set(Z,{path:Z,mentions:1,lastMentioned:$,wasModified:J})}static isValidFilePath(Q){if(!Q.includes("/"))return!1;let Z=cZ(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 fQ}from"js-tiktoken";class j0{static encodingCache=new Map;static countTokens(Q,Z){let $=this.getEncoding(Z),J=0;for(let z of Q){if(J+=4,z.role)J+=$.encode(z.role).length;if(z.content)if(typeof z.content==="string")J+=$.encode(z.content).length;else J+=$.encode(JSON.stringify(z.content)).length;if(z.tool_calls&&Array.isArray(z.tool_calls))J+=this.countToolCallTokens(z.tool_calls,$);if(z.name)J+=$.encode(z.name).length}return J}static getTokenLimit(Q){return Q}static shouldCompact(Q,Z,$,J=0.8){let z=this.countTokens(Q,Z),W=Math.floor($*J);return z>=W}static getEncoding(Q){if(!this.encodingCache.has(Q))try{let Z=fQ(Q);this.encodingCache.set(Q,Z)}catch{try{let Z=fQ("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 P=p("Context"),U0=new Map,iZ=3;class z0{static THRESHOLD_PERCENT=0.8;static RETAIN_PERCENT=0.2;static FALLBACK_RETAIN_PERCENT=0.3;static ACTIVE_TASK_MAX_CHARS=6000;static async compact(Q,Z){if(Z.signal?.aborted)throw new DOMException("Aborted","AbortError");let $=Z.actualPreTokens??j0.countTokens(Q,Z.modelName),J=Z.actualPreTokens?"actual (from LLM usage)":"estimated";P.debug(`[CompactionService] preTokens source: ${J}`);try{let V=await N0.getInstance().executeCompactionHooks(Z.trigger,{projectDir:g(),sessionId:Z.sessionId||"unknown",permissionMode:Z.permissionMode||"default",messagesBefore:Q.length,tokensBefore:$});if(V.blockCompaction)return P.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)P.warn(`[CompactionService] Compaction hook warning: ${V.warning}`)}catch(G){P.warn("[CompactionService] Compaction hook execution failed:",G)}let z=Z.sessionId??"_default",W=U0.get(z)??0;if(W>=iZ)return P.warn(`[CompactionService] Circuit breaker open (${W} consecutive failures for session ${z}), using fallback`),this.fallbackCompact(Q,Z,$,Error("Circuit breaker open"));try{P.debug("[CompactionService] 开始压缩,消息数:",Q.length),P.debug("[CompactionService] 压缩前 tokens:",$);let V=S0.analyzeFiles(Q).map((x)=>x.path);P.debug("[CompactionService] 提取重点文件:",V);let Y=await S0.readFilesContent(V);P.debug("[CompactionService] 成功读取文件:",Y.length);let B=await this.generateSummary(Q,Y,Z);P.debug("[CompactionService] 生成总结,长度:",B.length);let q=Math.ceil(Q.length*this.RETAIN_PERCENT),b=Q.slice(-q),X=new Set;for(let x of b)if(x.role==="assistant"&&x.tool_calls)for(let c of x.tool_calls)X.add(c.id);let L=b.filter((x)=>{if(x.role==="tool"&&x.tool_call_id)return X.has(x.tool_call_id);return!0});P.debug("[CompactionService] 保留消息数:",q),P.debug("[CompactionService] 过滤后保留消息数:",L.length);let k=s(),A=this.createBoundaryMessage(k,Z.trigger,$),F=s(),N=this.createSummaryMessage(F,B),j=[N,...L],G0=await this.buildFileRestorationMessage();if(G0)j.push(G0);let l=this.buildActiveTaskMessage(Z.activeTask);if(l)j.push(l);let Y0=j0.countTokens(j,Z.modelName);P.debug("[CompactionService] 压缩完成!"),P.debug("[CompactionService] Token 变化:",$,"->",Y0,`(-${((1-Y0/$)*100).toFixed(1)}%)`),U0.delete(z);let V0=Q.slice(0,Q.length-q);return MQ(V0).catch((x)=>{return}),{success:!0,summary:B,preTokens:$,postTokens:Y0,filesIncluded:V,compactedMessages:j,boundaryMessage:A,summaryMessage:N}}catch(G){if(Q0(G))throw G;return U0.set(z,(U0.get(z)??0)+1),P.error("[CompactionService] 压缩失败,使用降级策略",G),this.fallbackCompact(Q,Z,$,G)}}static async generateSummary(Q,Z,$){let J=this.buildCompactionPrompt(Q,Z);if(P.debug("[CompactionService] 使用压缩模型:",$.modelName),$.signal?.aborted)throw new DOMException("Aborted","AbortError");let G=(await(await hQ({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 P.warn("[CompactionService] 总结格式不正确,使用完整响应"),G;return V[1].trim()}static buildCompactionPrompt(Q,Z){let $=Q.map((W,G)=>{let V=W.role||"unknown",Y=typeof W.content==="string"?W.content:JSON.stringify(W.content),B=5000,q=Y.length>5000?Y.substring(0,5000)+"...":Y;return`[${G+1}] ${V}: ${q}`}).join(`
|
|
19
19
|
|
|
20
20
|
`),J=Z.map((W)=>{return`### ${W.path}
|
|
21
21
|
\`\`\`
|
|
@@ -88,35 +88,35 @@ ${Z.length>0?`## Important Files
|
|
|
88
88
|
|
|
89
89
|
${J}`:""}
|
|
90
90
|
|
|
91
|
-
Please provide your summary following the structure specified above, with both <analysis> and <summary> sections.`}static createBoundaryMessage(Q,Z,$){return{id:
|
|
91
|
+
Please provide your summary following the structure specified above, with both <analysis> and <summary> sections.`}static createBoundaryMessage(Q,Z,$){return{id:s(),role:"system",content:"Conversation compacted",metadata:{type:"system",subtype:"compact_boundary",parentId:Q,compactMetadata:{trigger:Z,preTokens:$}}}}static createSummaryMessage(Q,Z){return{id:s(),role:"user",content:Z,metadata:{parentId:Q,isCompactSummary:!0}}}static getRecentlyAccessedFiles(Q){let Z=o.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 uZ.readFile(J,"utf-8")).split(`
|
|
92
92
|
`),G=W.slice(0,200).join(`
|
|
93
93
|
`),V=W.length>200?`
|
|
94
94
|
... (${W.length-200} more lines)`:"";Z.push(`<file path="${J}" lines="${W.length}">
|
|
95
95
|
${G}${V}
|
|
96
96
|
</file>`)}catch{}if(Z.length===0)return null;let $=["<system-reminder>","Post-compaction file restoration. These files were recently accessed in the conversation:",...Z,"</system-reminder>"].join(`
|
|
97
|
-
`);return
|
|
97
|
+
`);return P.debug("[CompactionService] Post-compact 恢复文件:",Q.length),{id:s(),role:"user",content:$,metadata:{isPostCompactRestoration:!0}}}static buildActiveTaskMessage(Q){if(!Q)return null;let Z=this.ACTIVE_TASK_MAX_CHARS,$=Math.floor(Z*0.75),J=Q.length<=Z?Q:[Q.slice(0,$),`
|
|
98
98
|
...[active task checkpoint truncated]...
|
|
99
|
-
`,Q.slice(-(Z-$))].join("");return{id:
|
|
100
|
-
`),metadata:{isPostCompactActiveTask:!0}}}static fallbackCompact(Q,Z,$,J){let z=Math.ceil(Q.length*this.FALLBACK_RETAIN_PERCENT),W=Q.slice(-z),G=new Set;for(let F of W)if(F.role==="assistant"&&F.tool_calls)for(let
|
|
99
|
+
`,Q.slice(-(Z-$))].join("");return{id:s(),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 N of F.tool_calls)G.add(N.id);let V=W.filter((F)=>{if(F.role==="tool"&&F.tool_call_id)return G.has(F.tool_call_id);return!0}),Y=s(),B=this.createBoundaryMessage(Y,Z.trigger,$),q=J instanceof Error?J.message:String(J),b=s(),X=this.createSummaryMessage(b,`[Automatic compaction failed; using fallback]
|
|
101
101
|
|
|
102
102
|
An error occurred during compaction. Retained the latest ${z} messages (~30%).
|
|
103
103
|
|
|
104
104
|
Error: ${q}
|
|
105
105
|
|
|
106
|
-
The conversation can continue, but consider retrying compaction later with /compact.`),L=[X,...V],
|
|
107
|
-
`),preTokens:$,postTokens:A,filesIncluded:[],compactedMessages:L,boundaryMessage:B,summaryMessage:X,error:q}}}var
|
|
106
|
+
The conversation can continue, but consider retrying compaction later with /compact.`),L=[X,...V],k=this.buildActiveTaskMessage(Z.activeTask);if(k)L.push(k);let A=j0.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 nZ=new Set(["Read","Grep","Glob","Search","WebSearch","WebFetch","ToolSearch"]);function lZ(Q,Z){let z=(Q[Z.assistantIdx].tool_calls??[]).filter((G)=>G.type==="function").map((G)=>G.function.name).some((G)=>!nZ.has(G));if(Z.toolResultIdxs.some((G)=>{let V=Q[G]?.content;if(typeof V!=="string")return!1;return V.startsWith("Error:")||V.includes("failed")||V.includes("ENOENT")}))return 3;if(z)return 2;return 1}function q0(Q,Z){let $=Z?.keepRecentTurns??10,J=Z?.minMessagesForSnip??30;if(Q.length<J)return{messages:Q,snippedCount:0,estimatedTokensFreed:0};let z=[];for(let X=0;X<Q.length;X++){let L=Q[X];if(L.role==="assistant"&&L.tool_calls&&L.tool_calls.length>0){let k=new Set(L.tool_calls.map((F)=>F.id)),A=[];for(let F=X+1;F<Q.length;F++){let N=Q[F];if(N.role==="tool"&&N.tool_call_id&&k.has(N.tool_call_id))A.push(F);if(N.role==="assistant"||N.role==="user")break}z.push({assistantIdx:X,toolResultIdxs:A,priority:0})}}for(let X of z)X.priority=lZ(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],k=typeof L.content==="string"?L.content:JSON.stringify(L.content);if(B+=k.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 aZ=60000,rZ=3;function kQ(Q,Z){if(!Z)return null;if(Date.now()-Z<aZ)return null;let J=q0(Q,{keepRecentTurns:rZ,minMessagesForSnip:15});if(J.snippedCount===0)return null;return J}class GQ{hasAttempted=!1;async tryReactiveCompact(Q,Z){if(this.hasAttempted)return{success:!1,messages:Q};this.hasAttempted=!0;let $=q0(Q,{keepRecentTurns:3,minMessagesForSnip:10}),J=$.messages;try{let z=await z0.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(Q0(z))throw z;if($.snippedCount>0)return{success:!0,messages:J};return{success:!1,messages:Q}}}reset(){this.hasAttempted=!1}}import*as W0 from"fs";import*as YQ from"os";import*as D0 from"path";import{nanoid as TQ}from"nanoid";var oZ=1e5,sZ=2000,xQ=200000;class VQ{currentChars=0;track(Q){this.currentChars+=Q}remaining(){return Math.max(0,xQ-this.currentChars)}isExhausted(){return this.currentChars>=xQ}reset(){this.currentChars=0}}function CQ(Q,Z,$){let J=$?.maxCharsPerResult??oZ,z=$?.previewChars??sZ,W=$?.messageBudget,G=typeof Q==="string"?Q:JSON.stringify(Q,null,2);if(G.length<=J)return tZ(Q,G,Z,z,W,$);let V=$?.outputDir??D0.join(YQ.homedir(),".blade","tool-results"),Y=`${Z}-${TQ(8)}.txt`,B=D0.join(V,Y);try{W0.mkdirSync(V,{recursive:!0}),W0.writeFileSync(B,G,"utf-8")}catch{let X=G.slice(0,J)+`
|
|
108
108
|
|
|
109
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
110
|
|
|
111
111
|
Preview:
|
|
112
112
|
${q}
|
|
113
113
|
|
|
114
|
-
... (${G.length-z} more chars in file)`;if(W)W.track(b.length);return b}function
|
|
114
|
+
... (${G.length-z} more chars in file)`;if(W)W.track(b.length);return b}function tZ(Q,Z,$,J,z,W){if(!z)return Q;let G=z.remaining();if(G<=0){let V=Z.slice(0,J),Y=RQ(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=RQ(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 RQ(Q,Z,$,J,z){let W=J?.outputDir??D0.join(YQ.homedir(),".blade","tool-results"),G=`${$}-${TQ(8)}.txt`,V=D0.join(W,G);try{return W0.mkdirSync(W,{recursive:!0}),W0.writeFileSync(V,Q,"utf-8"),`${Z}
|
|
115
115
|
|
|
116
116
|
${z}
|
|
117
117
|
Full output saved to: ${V}`}catch{return`${Z}
|
|
118
118
|
|
|
119
|
-
${z}`}}import*as
|
|
119
|
+
${z}`}}import*as h0 from"node:fs/promises";import{homedir as rQ}from"node:os";import*as n from"node:path";var y0={name:"skill-creator",description:"Create new Skills interactively. Use when the user wants to create a new Skill, define a custom workflow, or add a specialized capability to Blade.",allowedTools:["Read","Write","Glob","Bash","AskUserQuestion"],version:"1.0.0",argumentHint:void 0,userInvocable:!0,disableModelInvocation:!1,model:void 0,whenToUse:"User wants to create a new skill, define a custom workflow, or add a specialized capability.",path:"builtin://skill-creator",basePath:"",source:"builtin"};function pQ(){return{metadata:y0,instructions:`# Skill Creator
|
|
120
120
|
|
|
121
121
|
帮助用户创建新的 Blade Skills。
|
|
122
122
|
|
|
@@ -299,7 +299,7 @@ user-invocable: true
|
|
|
299
299
|
<footer>
|
|
300
300
|
\`\`\`
|
|
301
301
|
\`\`\`
|
|
302
|
-
`}}var
|
|
302
|
+
`}}var A0={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 dQ(){return{metadata:A0,instructions:`# Update Config Skill
|
|
303
303
|
|
|
304
304
|
配置 Blade 运行环境。管理 settings、hooks、permissions、环境变量等。
|
|
305
305
|
|
|
@@ -572,11 +572,11 @@ ConfigTool({
|
|
|
572
572
|
2. **permissions 字段使用 replace 策略**:设置 permissions 会完全替换现有值。如果只想添加规则,先 GET 当前值,合并后再 SET
|
|
573
573
|
3. **env 字段使用 deep-merge 策略**:可以逐个添加环境变量
|
|
574
574
|
4. **scope 默认值**:不指定 scope 时,根据字段路由表决定(hooks/permissions/env 默认 local,temperature/theme 等默认 global)
|
|
575
|
-
`}}import{exec as
|
|
576
|
-
`)}get size(){return this.skills.size}async refresh(){return this.skills.clear(),this.pluginSkills.clear(),this.initialized=!1,this.initialize()}registerPluginSkill(Q){this.pluginSkills.set(Q.namespacedName,Q),this.skills.set(Q.namespacedName,Q.metadata)}findPluginSkill(Q){let Z=this.pluginSkills.get(Q);if(Z)return Z;let $=[];for(let J of this.pluginSkills.values())if(J.originalName===Q)$.push(J);if($.length===1)return $[0];return}getAllPluginSkills(){return Array.from(this.pluginSkills.values())}clearPluginSkills(){for(let Q of this.pluginSkills.values())this.skills.delete(Q.namespacedName);this.pluginSkills.clear()}getPluginSkillCount(){return this.pluginSkills.size}}function
|
|
575
|
+
`}}import{exec as eZ}from"node:child_process";import*as w from"node:fs/promises";import{homedir as Q2}from"node:os";import*as E from"node:path";import{promisify as Z2}from"node:util";var P0=Z2(eZ),I=p("General"),HQ={url:"https://github.com/anthropics/skills.git",branch:"main",defaultSkills:["skill-creator"]};class mQ{skillsDir;constructor(Q){this.skillsDir=Q||E.join(Q2(),".blade","skills")}async isInstalled(Q){let Z=E.join(this.skillsDir,Q,"SKILL.md");try{return await w.access(Z),!0}catch{return!1}}async isGitAvailable(){try{return await P0("git --version"),!0}catch{return!1}}async installOfficialSkill(Q){let{url:Z,branch:$}=HQ,J=E.join(this.skillsDir,Q),z=E.join(this.skillsDir,`.tmp-${Q}-${Date.now()}`);try{if(!await this.isGitAvailable())return I.warn("Git not available, skipping skill installation"),!1;I.info(`Installing official skill: ${Q}...`),await w.mkdir(this.skillsDir,{recursive:!0,mode:493}),await P0(`git clone --depth 1 --branch ${$} --single-branch ${Z} "${z}"`,{timeout:30000});let W=E.join(z,"skills",Q);try{await w.access(W)}catch{return I.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}),I.info(`Successfully installed: ${Q}`),!0}catch(W){try{await w.rm(z,{recursive:!0,force:!0})}catch{}return I.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 HQ.defaultSkills)if(!await this.isInstalled(Q))await this.installOfficialSkill(Q)}async installFromRepo(Q,Z){let $=Z||this.extractRepoName(Q),J=E.join(this.skillsDir,$),z=E.join(this.skillsDir,`.tmp-repo-${$}-${Date.now()}`);try{if(!await this.isGitAvailable())return I.warn("Git not available, cannot install from repo"),!1;I.info(`Installing skill from repo: ${Q}...`),await w.mkdir(this.skillsDir,{recursive:!0,mode:493}),await P0(`git clone --depth 1 "${Q}" "${z}"`,{timeout:60000});let W=E.join(z,"SKILL.md");try{await w.access(W)}catch{return I.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(E.join(J,".git"),{recursive:!0,force:!0})}catch{}return I.info(`Successfully installed skill from repo: ${$}`),!0}catch(W){try{await w.rm(z,{recursive:!0,force:!0})}catch{}return I.warn(`Failed to install from repo ${Q}: ${W instanceof Error?W.message:"Unknown error"}`),!1}}async installFromLocal(Q,Z,$=!0){let J=Z||E.basename(Q),z=E.join(this.skillsDir,J);try{let W=E.resolve(Q);try{await w.access(W)}catch{return I.warn(`Local path does not exist: ${W}`),!1}let G=E.join(W,"SKILL.md");try{await w.access(G)}catch{return I.warn(`No SKILL.md found in local path: ${W}`),!1}if(I.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"),I.info(`Created symlink for skill: ${J}`);else await w.cp(W,z,{recursive:!0}),I.info(`Copied skill to: ${J}`);return!0}catch(W){return I.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}=HQ,$=E.join(this.skillsDir,`.tmp-all-${Date.now()}`),J=[],z=[];try{if(!await this.isGitAvailable())return I.warn("Git not available, skipping skill installation"),{installed:J,failed:z};await w.mkdir(this.skillsDir,{recursive:!0,mode:493}),I.info("Cloning official skills repository..."),await P0(`git clone --depth 1 --branch ${Z} --single-branch ${Q} "${$}"`,{timeout:60000});let W=E.join($,"skills"),G=await w.readdir(W,{withFileTypes:!0});for(let V of G){if(!V.isDirectory())continue;let Y=V.name,B=E.join(W,Y),q=E.join(this.skillsDir,Y);try{await w.access(E.join(B,"SKILL.md")),await w.rm(q,{recursive:!0,force:!0}),await w.cp(B,q,{recursive:!0}),I.info(`Installed: ${Y}`),J.push(Y)}catch(b){I.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{}I.warn(`Failed to install skills: ${W instanceof Error?W.message:"Unknown error"}`)}return{installed:J,failed:z}}}var XQ=null;function gQ(Q){if(!XQ)XQ=new mQ(Q);return XQ}import*as b0 from"node:fs/promises";import*as M0 from"node:path";import{parse as $2}from"yaml";var J2=/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/,z2=/^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]?$/,cQ=1024;function W2(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 uQ(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 G2(Q,Z){if(!Q.name)return{valid:!1,error:"Missing required field: name"};if(!z2.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>cQ)return{valid:!1,error:`Description too long: ${Q.description.length} characters (max ${cQ})`};let $;if(Q.model)$=Q.model==="inherit"?"inherit":Q.model;return{valid:!0,metadata:{name:Q.name,description:Q.description.trim(),allowedTools:W2(Q["allowed-tools"]),version:Q.version,argumentHint:Q["argument-hint"]?.trim(),userInvocable:uQ(Q["user-invocable"]),disableModelInvocation:uQ(Q["disable-model-invocation"]),model:$,whenToUse:Q.when_to_use?.trim()}}}function iQ(Q,Z,$){let J=Q.match(J2);if(!J)return{success:!1,error:"Invalid SKILL.md format: missing YAML frontmatter (must start with ---)"};let[,z,W]=J,G;try{G=$2(z)}catch(B){return{success:!1,error:`Failed to parse YAML frontmatter: ${B instanceof Error?B.message:String(B)}`}}let V=G2(G,Z);if(!V.valid)return{success:!1,error:V.error};let Y=M0.dirname(Z);return{success:!0,content:{metadata:{...V.metadata,path:Z,basePath:Y,source:$},instructions:W.trim()}}}async function nQ(Q,Z){try{let $=await b0.readFile(Q,"utf-8");return iQ($,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 lQ(Q){try{let Z=await b0.readFile(Q.path,"utf-8"),$=iQ(Z,Q.path,Q.source);return $.success?$.content:null}catch{return null}}async function aQ(Q){try{return await b0.access(M0.join(Q,"SKILL.md")),!0}catch{return!1}}var Y2={userSkillsDir:n.join(rQ(),".blade","skills"),projectSkillsDir:".blade/skills",claudeUserSkillsDir:n.join(rQ(),".claude","skills"),claudeProjectSkillsDir:".claude/skills"},f0=null;class KQ{skills=new Map;pluginSkills=new Map;config;initialized=!1;constructor(Q){this.config={...Y2,cwd:g(),...Q}}static getInstance(Q){if(!f0)f0=new KQ(Q);return f0}static resetInstance(){f0=null}async initialize(){if(this.initialized)return{skills:Array.from(this.skills.values()),errors:[]};let Q=[],Z=[];try{await gQ(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=n.isAbsolute(this.config.claudeProjectSkillsDir)?this.config.claudeProjectSkillsDir:n.join(this.config.cwd,this.config.claudeProjectSkillsDir),W=await this.scanDirectory(z,"project");Z.push(...W.skills),Q.push(...W.errors);let G=n.isAbsolute(this.config.projectSkillsDir)?this.config.projectSkillsDir:n.join(this.config.cwd,this.config.projectSkillsDir),V=await this.scanDirectory(G,"project");Z.push(...V.skills),Q.push(...V.errors);for(let Y of Z)this.skills.set(Y.name,Y);return this.initialized=!0,{skills:Array.from(this.skills.values()),errors:Q}}loadBuiltinSkills(){this.skills.set(y0.name,y0),this.skills.set(A0.name,A0)}async scanDirectory(Q,Z){let $=[],J=[];try{await h0.access(Q)}catch{return{skills:$,errors:J}}try{let z=await h0.readdir(Q,{withFileTypes:!0});for(let W of z){if(!W.isDirectory())continue;let G=n.join(Q,W.name),V=n.join(G,"SKILL.md");if(!await aQ(G))continue;let Y=await nQ(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 lQ(Z)}loadBuiltinContent(Q){switch(Q){case"skill-creator":return pQ();case"update-config":return dQ();default:return null}}getModelInvocableSkills(){return Array.from(this.skills.values()).filter((Q)=>!Q.disableModelInvocation)}getUserInvocableSkills(){return Array.from(this.skills.values()).filter((Q)=>Q.userInvocable===!0)}generateAvailableSkillsList(){let Q=this.getModelInvocableSkills();if(Q.length===0)return"";let Z=[];for(let $ of Q){let J=$.description.length>100?`${$.description.substring(0,97)}...`:$.description,z=$.argumentHint?`${$.name} ${$.argumentHint}`:$.name;Z.push(`- ${z}: ${J}`)}return Z.join(`
|
|
576
|
+
`)}get size(){return this.skills.size}async refresh(){return this.skills.clear(),this.pluginSkills.clear(),this.initialized=!1,this.initialize()}registerPluginSkill(Q){this.pluginSkills.set(Q.namespacedName,Q),this.skills.set(Q.namespacedName,Q.metadata)}findPluginSkill(Q){let Z=this.pluginSkills.get(Q);if(Z)return Z;let $=[];for(let J of this.pluginSkills.values())if(J.originalName===Q)$.push(J);if($.length===1)return $[0];return}getAllPluginSkills(){return Array.from(this.pluginSkills.values())}clearPluginSkills(){for(let Q of this.pluginSkills.values())this.skills.delete(Q.namespacedName);this.pluginSkills.clear()}getPluginSkillCount(){return this.pluginSkills.size}}function k0(Q){return KQ.getInstance(Q)}async function V2(Q){return k0(Q).initialize()}var H2="Skill",X2=/<available_skills>\s*<\/available_skills>/;function BQ(Q){let $=k0().generateAvailableSkillsList();if(!$)return Q;return Q.map((J)=>{if(J.name!==H2)return J;let z=J.description.replace(X2,`<available_skills>
|
|
577
577
|
${$}
|
|
578
|
-
</available_skills>`);if(z===J.description)return J;return{...J,description:z}})}function
|
|
579
|
-
`)}function
|
|
578
|
+
</available_skills>`);if(z===J.description)return J;return{...J,description:z}})}function oQ(){return{consecutiveFailures:new Map,totalFailures:0,lastFailedTool:null}}function sQ(Q,Z){Q.consecutiveFailures.set(Z,0),Q.lastFailedTool=null}function tQ(Q,Z){let $=(Q.consecutiveFailures.get(Z)??0)+1;Q.consecutiveFailures.set(Z,$),Q.totalFailures++,Q.lastFailedTool=Z}function K2(Q,Z){return(Q.consecutiveFailures.get(Z)??0)>=3}function eQ(Q,Z){if(!K2(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 QZ(Q){return Q>0&&Q%5===0}function ZZ(Q,Z){let $=[`[Self-check at turn ${Q}]`,"Before continuing, briefly assess:","1. Are you making progress toward the goal?","2. Have any approaches failed repeatedly that you should abandon?","3. Is there a simpler path you haven't tried?"];if(Z>3)$.push(`Note: ${Z} tool failures so far. Consider whether your current strategy needs adjustment.`);return $.join(`
|
|
579
|
+
`)}function $Z(){return{recentOutputHashes:[]}}function B2(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 JZ(Q,Z){let $=B2(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 t=p("Agent"),q2=new Set(["Read","Glob","Grep","WebFetch","WebSearch","MemoryRead","GetSpecContext","ValidateSpec","TaskOutput"]);class x0{pipeline;execContext;registry;contextMgr;sessionId;lastMessageUuid;subagentInfo;pending=new Map;completed=new Map;queued=[];order=[];dispatched=new Set;abortController=new AbortController;epoch=0;activeAborts=new Map;constructor(Q,Z,$,J,z,W,G){this.pipeline=Q;this.execContext=Z;this.registry=$;this.contextMgr=J;this.sessionId=z;this.lastMessageUuid=W;this.subagentInfo=G}addTool(Q,Z){if(this.dispatched.has(Q.id)){t.debug(`[StreamingToolExecutor] 跳过已分发工具: ${Q.function.name} (${Q.id})`);return}if(this.dispatched.add(Q.id),this.order.push(Q.id),q2.has(Q.function.name)){t.debug(`[StreamingToolExecutor] 立即执行预启动工具: ${Q.function.name}`);let J=this.executeOne(Q,Z);this.pending.set(Q.id,J)}else t.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){t.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(),t.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){t.warn("[StreamingToolExecutor] 保存工具调用失败:",X)}let G=[z,J.signal],V=this.execContext.signal;if(V)G.push(V);let Y=WZ(...G),B={...this.execContext,signal:Y},q=await this.pipeline.execute(Q.function.name,Z,B);if($!==this.epoch)return t.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)");t.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=p("Agent"),b2=0.1,F2=8192,O2=32768,R0=100,w2=`
|
|
580
580
|
|
|
581
581
|
# Task Execution Strategy
|
|
582
582
|
When facing complex multi-step tasks:
|
|
@@ -584,29 +584,32 @@ When facing complex multi-step tasks:
|
|
|
584
584
|
2. Execute one step at a time — verify each step succeeded before moving to the next.
|
|
585
585
|
3. If a step fails, diagnose the root cause rather than repeating the same approach.
|
|
586
586
|
4. When uncertain about file paths or project structure, use Grep/Glob/Read to gather facts first.
|
|
587
|
-
5. Prefer the smallest change that achieves the goal — avoid unnecessary refactoring.`;function
|
|
588
|
-
`)}function
|
|
587
|
+
5. Prefer the smallest change that achieves the goal — avoid unnecessary refactoring.`;function GZ(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 VZ(Q){let Z=GZ(Q);if(Z)return Z;try{let $=JSON.parse(Q);return typeof $==="string"?GZ($):null}catch{return null}}function L2(Q){if(typeof Q==="string")return Q;try{return JSON.parse(JSON.stringify(Q))}catch{return String(Q)}}function _2(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 N2(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 v2(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 I2(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 E2(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 S2(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*U2(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(E2(B,L),z){let A=L.index??0,F=B.get(A);if(F&&F.id&&F.name)try{let N=VZ(F.arguments);if(N===null)continue;let j={id:F.id,type:"function",function:{name:F.name,arguments:F.arguments}},l=Q.toolExecutor.getRegistry().get(F.name)?.kind;z.addTool(j,N),yield{kind:"tool_start",toolCall:j,toolKind:l}}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:S2(B),usage:V,finishReason:Y}}catch(q){if(N2(q))return y.warn("[Loop] 流式请求失败,降级到非流式模式"),z?.discard(),{...await Q.chatService.chat(Z,$,J),_nonStreamingFallback:!0};throw q}}async function*HZ(Q,Z,$,J,z,W,G){if(J===void 0)return y.debug(`[Loop] [轮次 ${$}] 压缩检查: 跳过(无历史 usage 数据)`),"none";let V=kQ(Z.messages,W);if(V)Z.messages=V.messages,y.debug(`[Loop] [轮次 ${$}] MicroCompact: 清理 ${V.snippedCount} 轮旧工具结果(缓存已过期)`);let Y=q0(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*b2),F2),O2),k=X-L,A=Math.floor(k*0.8);if(y.debug(`[Loop] [轮次 ${$}] 压缩检查:`,{promptTokens:J,maxContextTokens:X,maxOutputTokens:L,availableForInput:k,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,N=await z0.compact(F,{trigger:"auto",modelName:b,maxContextTokens:X,apiKey:q.apiKey,baseURL:q.baseUrl,actualPreTokens:J,signal:z,activeTask:G});if(Z.messages=N.compactedMessages,N.success)y.debug(`[Loop] [轮次 ${$}] 压缩完成: ${N.preTokens} -> ${N.postTokens} tokens`);else y.warn(`[Loop] [轮次 ${$}] 压缩使用降级策略: ${N.preTokens} -> ${N.postTokens} tokens`);return await I0(Q,Z,N.summary,{trigger:"auto",preTokens:N.preTokens,postTokens:N.postTokens,filesIncluded:N.filesIncluded}),"compacted"}catch(F){if(Q0(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 y2(Q,Z,$,J){let z=J?YZ(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*A2(Q,Z,$,J,z){let W=Date.now(),G=0,V=[],Y=null,B=!1,q=(b,X,L)=>{return B=!0,y2(b,X,W,L)};try{let b=Q.toolExecutor.getRegistry(),X=$.permissionMode,L=b.getFunctionDeclarationsByMode(X);L=BQ(L);let k=Q.applySkillToolRestrictions(L),A=oQ(),F=$Z(),N=z;if(typeof b.getDeferredToolsListing==="function"){let T=b.getDeferredToolsListing();if(T&&N)N=`${N}
|
|
589
589
|
|
|
590
|
-
${
|
|
591
|
-
`),
|
|
592
|
-
`),
|
|
590
|
+
${T}`}if(N)N+=w2;let j=new _0($,N);j.appendUser({role:"user",content:Z}),Y=await i(Q,$,Z);let G0=$.permissionMode==="yolo",l=!!$.subagentInfo,Y0=Q.runtimeOptions.maxTurns!==void 0||J?.maxTurns!==void 0,V0=Q.runtimeOptions.maxTurns??J?.maxTurns??Q.config.maxTurns??-1;if(V0===0)return{success:!1,error:{type:"chat_disabled",message:"对话功能已被禁用 (maxTurns=0)"},metadata:{turnsCount:0,toolCallsCount:0,duration:0}};let x=V0===-1?R0:Math.min(V0,R0),c=0,T0,jQ,H0=0,C0=0,p0=0,d0=0,m0=0,g0=new Set,R=new Set($.worktreeActive?["EnterWorktree"]:[]),u=typeof Z==="string"?Z:Z.filter((T)=>T.type==="text").map((T)=>T.text).join(`
|
|
591
|
+
`),c0=[u,$.completionRequirements?.trim()].filter(Boolean).join(`
|
|
592
|
+
`),F0=v0(u),u0=bQ({budget:Q.currentModelMaxContextTokens,isSubagent:l}),qQ=new GQ,i0=async(T)=>{for(let d of T){let X0=await i(Q,$,d.content,Y,{inboxMessageId:d.id});if(!X0)throw Error(`Failed to persist steering message before applying it: ${d.id}`);Y=X0,await J?.turnSteering?.acknowledge([d.id]),j.appendUser({role:"user",content:d.content});let H=typeof d.content==="string"?d.content:d.content.filter((a)=>a.type==="text").map((a)=>a.text).join(`
|
|
593
|
+
`);if(H.trim())u=[u,H].join(`
|
|
594
|
+
`),c0=[u,$.completionRequirements?.trim()].filter(Boolean).join(`
|
|
595
|
+
`),F0=F0||v0(H)}return{messageIds:T.map((d)=>d.id),count:T.length,recovered:T.filter((d)=>d.recovered).length}};try{while(!0){if(J?.signal?.aborted)return q(G,V.length,J.signal);let T=J?.turnSteering?.drain()??[];if(T.length>0)yield{kind:"steering_applied",...await i0(T)};if(j.writeback(),(yield*HZ(Q,$,G,T0,J?.signal,jQ,u))!=="none")j.replaceHistory($.messages);if(G++,qQ.reset(),yield{kind:"turn_start",turn:G,maxTurns:x},J?.signal?.aborted)return q(G-1,V.length,J.signal);if(QZ(G)&&G>1){let v=ZZ(G,A.totalFailures);j.appendControl("user",{role:"user",content:`
|
|
593
596
|
|
|
594
597
|
<system-reminder>
|
|
595
|
-
${
|
|
596
|
-
</system-reminder>`})}let
|
|
598
|
+
${v}
|
|
599
|
+
</system-reminder>`})}let X0=J?.stream!==!1,H,a;try{if(X0)a=new x0(Q.toolExecutor,{sessionId:$.sessionId,userId:$.userId||"default",workspaceRoot:$.workspaceRoot||g(),worktreeIsolationRequired:F0,worktreeActive:R.has("EnterWorktree")&&!R.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*U2(Q,j.toLLMMessages(),k,J?.signal,a);else H=await Q.chatService.chat(j.toLLMMessages(),k,J?.signal)}catch(v){if(I2(v)){y.warn("[Loop] 检测到 prompt_too_long 错误,尝试反应式压缩");let K=Q.chatService.getConfig(),O=await qQ.tryReactiveCompact($.messages,{modelName:K.model,maxContextTokens:K.maxContextTokens??Q.config.maxContextTokens,apiKey:K.apiKey,baseURL:K.baseUrl,signal:J?.signal,activeTask:u});if(O.success){$.messages=O.messages,j.replaceHistory($.messages),y.info("[Loop] 反应式压缩成功,重试 LLM 调用"),G--;continue}}throw v}if(jQ=Date.now(),H.usage){if(H.usage.totalTokens)c+=H.usage.totalTokens;T0=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 XZ=H.usage?.completionTokens??0;if(u0=FQ(u0,XZ,H0>0),J?.signal?.aborted)return q(G-1,V.length,J.signal);if(!X0||!!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 n0=s0(H.finishReason,H0,u0);if(n0.action==="recover"){H0++,y.warn(`[Loop] Max output tokens hit (recovery ${H0}/3)`);let v={role:"assistant",content:H.content||"",reasoningContent:H.reasoningContent,tool_calls:H.toolCalls};j.appendToHistory(v);let K=await h(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 i(Q,$,O.content,Y);if(D)Y=D;continue}if(n0.action==="truncated"||n0.action==="budget_stop"){j.appendAssistant({role:"assistant",content:H.content||"",reasoningContent:H.reasoningContent,tool_calls:H.toolCalls});let v=await h(Q,$,H.content||"",Y);if(v)Y=v;return{success:!0,finalMessage:H.content,metadata:{turnsCount:G,toolCallsCount:V.length,duration:Date.now()-W,tokensUsed:c,outputTruncated:!0}}}if(H.finishReason!=="length")H0=0;if(!H.toolCalls||H.toolCalls.length===0){let v=J?.turnSteering?.drain()??[];if(v.length>0){j.appendAssistant({role:"assistant",content:H.content||"",reasoningContent:H.reasoningContent});let _=await h(Q,$,H.content||"",Y);if(_)Y=_;yield{kind:"steering_applied",...await i0(v)};continue}if(H.content&&JZ(F,H.content)){j.appendAssistant({role:"assistant",content:H.content||"",reasoningContent:H.reasoningContent}),j.appendControl("user",{role:"user",content:`
|
|
597
600
|
|
|
598
601
|
<system-reminder>
|
|
599
|
-
${
|
|
600
|
-
</system-reminder>`});continue}let
|
|
602
|
+
${zZ()}
|
|
603
|
+
</system-reminder>`});continue}let K=t0(H.content,C0,!1);if(K.action==="retry"){C0++,j.appendAssistant({role:"assistant",content:H.content||"",reasoningContent:H.reasoningContent});let _=await h(Q,$,H.content||"",Y);if(_)Y=_;let C={role:"user",content:K.prompt};j.appendControl("user",C);let f=await i(Q,$,C.content,Y);if(f)Y=f;continue}C0=0;let O=NQ(u,R,p0);if(O.action==="retry"){p0++,j.appendAssistant({role:"assistant",content:H.content||"",reasoningContent:H.reasoningContent});let _=await h(Q,$,H.content||"",Y);if(_)Y=_;let C={role:"user",content:O.prompt};j.appendControl("user",C);let f=await i(Q,$,C.content,Y);if(f)Y=f;continue}if(O.action==="fail"){j.appendAssistant({role:"assistant",content:H.content||"",reasoningContent:H.reasoningContent});let _=await h(Q,$,H.content||"",Y);if(_)Y=_;return{success:!1,error:{type:"delegation_protocol_failed",message:O.message},metadata:{turnsCount:G,toolCallsCount:V.length,duration:Date.now()-W,tokensUsed:c}}}p0=0;let D=vQ(u,R,m0);if(D.action==="retry"){m0++,j.appendAssistant({role:"assistant",content:H.content||"",reasoningContent:H.reasoningContent});let _=await h(Q,$,H.content||"",Y);if(_)Y=_;let C={role:"user",content:D.prompt};j.appendControl("user",C);let f=await i(Q,$,C.content,Y);if(f)Y=f;continue}if(D.action==="fail"){j.appendAssistant({role:"assistant",content:H.content||"",reasoningContent:H.reasoningContent});let _=await h(Q,$,H.content||"",Y);if(_)Y=_;return{success:!1,error:{type:"worktree_protocol_failed",message:D.message},metadata:{turnsCount:G,toolCallsCount:V.length,duration:Date.now()-W,tokensUsed:c}}}m0=0;let m=e0(c0,g0,d0);if(m.action==="retry"){d0++,j.appendAssistant({role:"assistant",content:H.content||"",reasoningContent:H.reasoningContent});let _=await h(Q,$,H.content||"",Y);if(_)Y=_;let C={role:"user",content:m.prompt};j.appendControl("user",C);let f=await i(Q,$,C.content,Y);if(f)Y=f;continue}if(m.action==="fail"){j.appendAssistant({role:"assistant",content:H.content||"",reasoningContent:H.reasoningContent});let _=await h(Q,$,H.content||"",Y);if(_)Y=_;return{success:!1,error:{type:"verification_failed",message:m.message},metadata:{turnsCount:G,toolCallsCount:V.length,duration:Date.now()-W,tokensUsed:c}}}d0=0;let S=await QQ({sessionId:$.sessionId,permissionMode:$.permissionMode,reason:H.content,abortSignal:J?.signal});if(S.action==="continue"){j.appendAssistant({role:"assistant",content:H.content||"",reasoningContent:H.reasoningContent});let _=await h(Q,$,H.content||"",Y);if(_)Y=_;let f={role:"user",content:S.reason?`
|
|
601
604
|
|
|
602
605
|
<system-reminder>
|
|
603
|
-
${
|
|
606
|
+
${S.reason}
|
|
604
607
|
</system-reminder>`:`
|
|
605
608
|
|
|
606
609
|
<system-reminder>
|
|
607
610
|
Please continue the conversation from where we left it off without asking the user any further questions. Continue with the last task that you were asked to work on.
|
|
608
|
-
</system-reminder>`};j.appendControl("user",
|
|
611
|
+
</system-reminder>`};j.appendControl("user",f);let K0=await i(Q,$,f.content,Y);if(K0)Y=K0;continue}let r=J?.turnSteering?.drainOrSeal();if(r&&r.messages.length>0){j.appendAssistant({role:"assistant",content:H.content||"",reasoningContent:H.reasoningContent});let _=await h(Q,$,H.content||"",Y);if(_)Y=_;yield{kind:"steering_applied",...await i0(r.messages)};continue}j.appendAssistant({role:"assistant",content:H.content||"",reasoningContent:H.reasoningContent});let M=await h(Q,$,H.content||"",Y);if(M)Y=M;return{success:!0,finalMessage:H.content,metadata:{turnsCount:G,toolCallsCount:V.length,duration:Date.now()-W,tokensUsed:c,toolSuccessRate:V.length>0?V.filter((_)=>_.success).length/V.length:void 0,totalToolFailures:A.totalFailures||void 0}}}j.appendAssistant({role:"assistant",content:H.content||"",reasoningContent:H.reasoningContent,tool_calls:H.toolCalls});{let v=await h(Q,$,H.content||"",Y);if(v)Y=v}if(J?.signal?.aborted)return q(G,V.length,J.signal);let l0=H.toolCalls.filter((v)=>v.type==="function"),O0;if(a?.hasTools()){y.debug(`[Loop] 使用 StreamingToolExecutor 收集 ${l0.length} 个工具结果`),O0=[];for await(let v of a.getRemainingResults())O0.push(v)}else{for(let K of l0){let D=b.get(K.function.name)?.kind;yield{kind:"tool_start",toolCall:K,toolKind:D}}let v=async(K)=>{try{let O=VZ(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:D2();let D=null;if(D=await $Q(Q,$,K.function.name,O,Y),K.function.name==="ExitWorktree"&&R.has("EnterWorktree")&&!R.has("ExitWorktree")&&e0(c0,g0,0).action!=="none"){let r="Run the requested verification before ExitWorktree. The worktree remains active so Bash can run in isolation.";return{toolCall:K,result:{success:!1,llmContent:r,error:{type:"validation_error",message:r},metadata:{summary:"Blocked ExitWorktree until verification succeeds"}},toolUseUuid:D}}let S=await Q.toolExecutor.execute(K.function.name,O,{sessionId:$.sessionId,userId:$.userId||"default",workspaceRoot:$.workspaceRoot||g(),worktreeIsolationRequired:F0,worktreeActive:R.has("EnterWorktree")&&!R.has("ExitWorktree"),signal:J?.signal,confirmationHandler:$.confirmationHandler,permissionMode:$.permissionMode,toolRegistry:b,deferredToolManager:b.deferredToolManager});return{toolCall:K,result:S,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")}}};O0=await Promise.all(l0.map(v))}let KZ=new VQ;for(let{toolCall:v,result:K,toolUseUuid:O}of O0){let D=v;if(V.push(K),K.metadata?.abortedBeforeLaunch)return q(G,V.length,J?.signal);yield{kind:"tool_result",toolCall:D,result:K};{let M=K.metadata&&typeof K.metadata==="object"?K.metadata:void 0,C=((w0)=>w0==="running"||w0==="completed"||w0==="failed"||w0==="cancelled")(M?.subagentStatus)?M.subagentStatus:"completed",f=M&&typeof M.subagentSessionId==="string"?{subagentSessionId:M.subagentSessionId,subagentType:typeof M.subagentType==="string"?M.subagentType:D.function.name,subagentStatus:C,subagentSummary:typeof M.subagentSummary==="string"?M.subagentSummary:void 0}:void 0,K0=await JQ(Q,$,D.id,D.function.name,K.success?L2(K.llmContent):null,O,K.success?void 0:K.error?.message,f);if(K0)Y=K0}let m=await zQ(D,K,Q,$);if(m)yield m;if(K.success){if(sQ(A,D.function.name),D.function.name==="EnterWorktree"&&K.metadata?.workspaceTransition==="enter")R.add("EnterWorktree"),R.delete("ExitWorktree");else if(D.function.name==="ExitWorktree"&&K.metadata?.workspaceTransition==="exit"&&R.has("EnterWorktree"))R.add("ExitWorktree");else if(!["EnterWorktree","ExitWorktree"].includes(D.function.name))R.add(D.function.name);if(D.function.name==="Task"&&K.metadata?.isolation==="worktree")R.add("TaskWorktree");_Q(g0,D.function.name,K)}else tQ(A,D.function.name);let S=K.success?K.llmContent||"":v2(D.function.name,K.error);if(!K.success){let M=eQ(A,D.function.name);if(M&&typeof S==="string")S=`${S}
|
|
609
612
|
|
|
610
|
-
${
|
|
613
|
+
${M}`}if(typeof S==="object"&&S!==null)S=JSON.stringify(S,null,2);if(typeof S==="string")S=CQ(S,D.function.name,{messageBudget:KZ});let r=typeof S==="string"?S:JSON.stringify(S);if(j.appendToolResult({role:"tool",tool_call_id:D.id,name:D.function.name,content:r}),K.metadata?.shouldExitLoop){let M=typeof K.llmContent==="string"?K.llmContent:"循环已退出";return{success:K.success,finalMessage:M,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 a0=G>=R0,BZ=G>=x&&(Y0||!G0||l);if(a0||BZ){let v=a0?R0:x;if(y.info(`Warning: 达到轮次上限 ${v} 轮`),J?.onTurnLimitReached){let K=await J.onTurnLimitReached({turnsCount:G});if(K?.continue){j.writeback();try{let O=Q.chatService.getConfig(),D=await z0.compact($.messages,{trigger:"auto",modelName:O.model,maxContextTokens:O.maxContextTokens??Q.config.maxContextTokens,apiKey:O.apiKey,baseURL:O.baseUrl,actualPreTokens:T0,signal:J?.signal,activeTask:u});$.messages=D.compactedMessages,j.replaceHistory($.messages);let m={role:"user",content:`This session is being continued from a previous conversation. The conversation is summarized above.
|
|
611
614
|
|
|
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(
|
|
615
|
+
Please continue the conversation from where we left it off without asking the user any further questions. Continue with the last task that you were asked to work on.`};j.appendToHistory(m),await I0(Q,$,D.summary,{trigger:"auto",preTokens:D.preTokens,postTokens:D.postTokens,filesIncluded:D.filesIncluded})}catch(O){y.error("[Loop] 压缩失败,使用降级策略:",O);let m=j.getHistory().slice(-80);j.replaceHistory(m)}G=0;continue}return{success:!0,finalMessage:K?.reason||"已达到对话轮次上限,用户选择停止",metadata:{turnsCount:G,toolCallsCount:V.length,duration:Date.now()-W,tokensUsed:c}}}return{success:!1,error:{type:"max_turns_exceeded",message:l?`子代理已达到轮次上限 (${v} 轮)。`:`已达到${a0?"安全":"显式"}轮次上限 (${v} 轮)。`},metadata:{turnsCount:G,toolCallsCount:V.length,duration:Date.now()-W,tokensUsed:c}}}}}finally{j.writeback()}}catch(b){if(Q0(b))return q(G,V.length,J?.signal);let X=_2(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:ZQ}),await IQ(Q,$,Y)}}export{WQ as Ja,gQ as Ka,nQ as La,k0 as Ma,V2 as Na,o as Oa,s0 as Pa,t0 as Qa,_Q as Ra,QQ as Sa,L0 as Ta,_0 as Ua,jZ as Va,i as Wa,h as Xa,$Q as Ya,JQ as Za,I0 as _a,EQ as $a,SQ as ab,UQ as bb,zQ as cb,j0 as db,z0 as eb,x0 as fb,HZ as gb,A2 as hb};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{Nb as y}from"./chunk-kfg3vx5z.js";import*as j from"fs/promises";import*as $ from"path";import b from"semver";import{fileURLToPath as N}from"url";import{ProxyAgent as G,fetch as H}from"undici";function T(){return process.env.HTTPS_PROXY||process.env.HTTP_PROXY||process.env.https_proxy||process.env.http_proxy}function R(){let q=T();if(q)try{return new G(q)}catch(z){console.warn(`[proxyFetch] Invalid proxy URL: ${q}`)}return}async function K(q,z={}){let{timeout:W=30000,signal:Q,...B}=z;if(Q?.aborted)throw new DOMException("The operation was aborted.","AbortError");let J=R(),X=new AbortController,Y=!1,F=setTimeout(()=>{Y=!0,X.abort()},W),w=()=>X.abort();Q?.addEventListener("abort",w);try{let Z={method:B.method,headers:B.headers,body:B.body,signal:X.signal,dispatcher:J};return await H(q.toString(),Z)}catch(Z){if(Z instanceof Error&&Z.name==="AbortError"){if(Y)throw Error(`Request timeout after ${W}ms`);throw Z}throw Z}finally{clearTimeout(F),Q?.removeEventListener("abort",w)}}var D="blade-code",f="https://cdn.jsdelivr.net/npm/blade-code@latest/CHANGELOG.md",M=$.join(process.env.HOME||process.env.USERPROFILE||".",".blade"),S=$.join(M,"version-cache.json"),k=3600000,L=`https://registry.npmjs.org/${D}/latest`;async function x(){try{if(process.env.BLADE_VERSION)return process.env.BLADE_VERSION;let q=N(import.meta.url),z=$.dirname(q),W=[$.join(z,"..","..","package.json"),$.join(z,"..","package.json")];for(let Q of W)try{let B=await j.readFile(Q,"utf-8"),J=JSON.parse(B);if(J.name===D&&J.version)return J.version}catch{}return"unknown"}catch{return"unknown"}}async function I(){try{let q=await j.readFile(S,"utf-8"),z=JSON.parse(q);if(Date.now()-z.checkedAt<k)return z;return{...z,checkedAt:0}}catch{return null}}async function O(q){try{await j.mkdir(M,{recursive:!0,mode:493}),await j.writeFile(S,JSON.stringify(q,null,2))}catch{}}async function P(){try{let q=await K(L,{timeout:5000,headers:{Accept:"application/json"}});if(!q.ok)return null;return(await q.json()).version||null}catch{return null}}async function v(q=!1){let z=await x(),W=f;if(z==="unknown")return{currentVersion:z,latestVersion:null,hasUpdate:!1,shouldPrompt:!1,releaseNotesUrl:W,error:"Unable to determine current version"};let Q=await I(),B=Q?.skipUntilVersion,J=null;if(!q&&Q&&Q.checkedAt>0)J=Q.latestVersion;else if(J=await P(),J)await O({latestVersion:J,checkedAt:Date.now(),skipUntilVersion:B});if(!J)return{currentVersion:z,latestVersion:null,hasUpdate:!1,shouldPrompt:!1,releaseNotesUrl:W,error:"Unable to check for updates"};let X=b.gt(J,z),Y=X;if(X&&B)Y=b.gt(J,B);return{currentVersion:z,latestVersion:J,hasUpdate:X,shouldPrompt:Y,releaseNotesUrl:W}}async function u(q){let z=await I();await O({latestVersion:z?.latestVersion||q,checkedAt:z?.checkedAt||Date.now(),skipUntilVersion:q})}function g(){return`npm install -g ${D}@latest --registry https://registry.npmjs.org`}async function C(){let{spawn:q}=await import("child_process");return new Promise((z)=>{let W=g(),Q=q(W,{stdio:"inherit",shell:!0});Q.on("close",(B)=>{if(B===0)z({success:!0,message:"Upgrade successful! Please restart blade."});else z({success:!1,message:`Upgrade failed (exit code: ${B})`})}),Q.on("error",(B)=>{z({success:!1,message:`Upgrade failed: ${B.message}`})})})}async function d(){try{let q=await v();return q.shouldPrompt?q:null}catch{return null}}
|
|
2
2
|
export{v as a,u as b,g as c,C as d,d as e};
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import{p as A,q as E,r as N,s as f}from"./chunk-87gff8b7.js";import{t as D}from"./chunk-vw3f4mbt.js";import{v as L,w as _,x}from"./chunk-cw125vv3.js";import{y as B}from"./chunk-k4behavv.js";import{H as $,N as b}from"./chunk-wp67n9q7.js";import"./chunk-e21htmg4.js";import"./chunk-y50fy1gq.js";import"./chunk-rtn0rb16.js";import"./chunk-5smacbk0.js";import"./chunk-rkhhzc4r.js";import"./chunk-06awrjgg.js";import{Va as Z}from"./chunk-gb0x14v5.js";import"./chunk-cyxb6fxe.js";import"./chunk-jf48kahn.js";import{sb as Y,tb as T}from"./chunk-63dzf6hr.js";import"./chunk-98jpdmgc.js";import"./chunk-w1zb8zac.js";import"./chunk-kfg3vx5z.js";import h from"yargs";import{hideBin as R}from"yargs/helpers";var w=new Set(Object.values(Y));function X(k){if(k&&w.has(k))return k;return}function M(k){return k.command("* [message]","Print response and exit (useful for pipes)",(F)=>F.positional("message",{describe:"Message to process",type:"string"}).option("p",{alias:"print",describe:"Print response and exit (useful for pipes)",type:"boolean"}).option("output-format",{describe:'Output format: "text", "json", "stream-json"',type:"string",default:"text"}).option("include-partial-messages",{describe:"Include partial message chunks as they arrive",type:"boolean"}).option("input-format",{describe:'Input format: "text", "stream-json"',type:"string",default:"text"}).option("model",{describe:"Model for the current session",type:"string"}).option("append-system-prompt",{describe:"Append a system prompt to the default system prompt",type:"string"}).option("system-prompt",{describe:"Replace the default system prompt",type:"string"}).option("max-turns",{alias:["maxTurns"],describe:"Maximum conversation turns (-1: unlimited, N>0: limit to N turns)",type:"number"}),async(F)=>{if(!F.p)return;let q=await O(F);process.exit(q)})}async function O(k,F=process){let q;try{await A();let J=await E({message:k.message,_:k._,defaultMessage:"Hello"}),G=await N(J);if(G.mode==="output"){if(G.content)F.stdout.write(`${G.content}
|
|
2
|
+
`);return G.exitCode??0}let Q=G.content,{sessionId:K,messages:U}=await f({sessionId:k.sessionId,continue:k.continue,resume:k.resume,forkSession:k.forkSession,fallbackSessionPrefix:"print"});q=await $.create({sessionId:K,workspaceRoot:T(),modelId:k.model,mcpConfig:k.mcpConfig,strictMcpConfig:k.strictMcpConfig,agents:k.agents?B(k.agents):void 0});let V=await b.createWithRuntime(q,{sessionId:K,systemPrompt:k.systemPrompt,appendSystemPrompt:k.appendSystemPrompt,maxTurns:k.maxTurns,modelId:k.model,permissionMode:X(k.permissionMode),toolWhitelist:k.allowedTools,toolBlacklist:k.disallowedTools,mcpConfig:k.mcpConfig,strictMcpConfig:k.strictMcpConfig}),H=(await Z(V.chatStream(Q,{messages:[...U],userId:"cli-user",sessionId:K,workspaceRoot:T(),permissionMode:X(k.permissionMode)}))).finalMessage||"";if(k.outputFormat==="json")F.stdout.write(`${JSON.stringify({response:H,input:Q,model:k.model,timestamp:new Date().toISOString()},null,2)}
|
|
3
|
+
`);else if(k.outputFormat==="stream-json")F.stdout.write(`${JSON.stringify({type:"response",content:H})}
|
|
4
|
+
`);else F.stdout.write(`${H}
|
|
5
|
+
`);return 0}catch(J){return F.stderr.write(`Error: ${J instanceof Error?J.message:"未知错误"}
|
|
6
|
+
`),1}finally{await q?.dispose()}}async function d(){if(process.argv.slice(2).findIndex((q)=>q==="--print"||q==="-p")===-1)return!1;try{let{print:q,"output-format":J,"include-partial-messages":G,"input-format":Q,"system-prompt":K,"append-system-prompt":U,"max-turns":V,...W}=D,H=h(R(process.argv)).scriptName("blade").strict(!1).options(W).middleware([_,L,x]);return M(H),await H.parse(),!0}catch(q){console.error(`Print mode error: ${q instanceof Error?q.message:"未知错误"}`),process.exit(1)}}export{O as runPrint,d as handlePrintMode};
|