blade-code 0.7.8 → 0.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/blade.js +2 -2
- package/dist/{chunk-rnfd5ebv.js → chunk-06h100e2.js} +1 -1
- package/dist/chunk-07jvw0kn.js +1 -0
- package/dist/chunk-0dj326ms.js +5 -0
- package/dist/chunk-14erxdhd.js +1 -0
- package/dist/{chunk-48q9msfk.js → chunk-1pt090dg.js} +38 -38
- package/dist/{chunk-cjmxggke.js → chunk-1smf2dj3.js} +2 -2
- package/dist/chunk-34pdtz4q.js +3 -0
- package/dist/chunk-3gw66r7a.js +2 -0
- package/dist/chunk-49g067ek.js +41 -0
- package/dist/chunk-6es6av6j.js +2 -0
- package/dist/{chunk-g7caymjr.js → chunk-9ad7tt9s.js} +1 -1
- package/dist/{chunk-jm2xhnrv.js → chunk-9xkjb87h.js} +1 -1
- package/dist/chunk-a12tmmfr.js +1 -0
- package/dist/chunk-bggvft3z.js +1 -0
- package/dist/{chunk-0e0z8yc1.js → chunk-bm8vwfez.js} +2 -2
- package/dist/chunk-bxbagv76.js +9 -0
- package/dist/chunk-ctqf59q1.js +2 -0
- package/dist/chunk-d08wbxjr.js +1 -0
- package/dist/chunk-d4ex0qvs.js +2 -0
- package/dist/{chunk-f9ybv4ph.js → chunk-dr06x0cw.js} +1 -1
- package/dist/chunk-e4a240t7.js +34 -0
- package/dist/{chunk-4dmdn3a9.js → chunk-gsfkrr25.js} +1 -1
- package/dist/chunk-gytwh5y1.js +6 -0
- package/dist/chunk-hjx5n3dw.js +3 -0
- package/dist/chunk-hrnd3wjg.js +6 -0
- package/dist/chunk-j39q2kx7.js +1 -0
- package/dist/{chunk-4745ktjj.js → chunk-jakzknh3.js} +299 -299
- package/dist/chunk-jqr2pknb.js +151 -0
- package/dist/{chunk-t70aqrm4.js → chunk-jt62ctz7.js} +1 -1
- package/dist/{chunk-t2spryz0.js → chunk-kawv31m3.js} +1 -1
- package/dist/chunk-n8ymp6nd.js +1 -0
- package/dist/{chunk-s4mke0t6.js → chunk-nned222j.js} +1 -1
- package/dist/chunk-qwdbqjh7.js +22 -0
- package/dist/chunk-syj3anec.js +6 -0
- package/dist/chunk-tv4r86ez.js +24 -0
- package/dist/chunk-twem6p0g.js +2 -0
- package/dist/chunk-v3ctg84r.js +1 -0
- package/dist/chunk-v5rn5r1h.js +1 -0
- package/dist/{chunk-fb7amc2s.js → chunk-wmes2tt9.js} +1 -1
- package/dist/chunk-xhnyy54e.js +2 -0
- package/dist/{chunk-9kejtkey.js → chunk-ychj0e5q.js} +1 -1
- package/dist/{chunk-71n472hj.js → chunk-ydb9myhe.js} +1 -1
- package/dist/{chunk-6hn2jgw5.js → chunk-yhpm9azy.js} +1 -1
- package/dist/{chunk-g6ted982.js → chunk-yqxw7zz4.js} +1 -1
- package/dist/web/assets/{FilePreview-DRKRs8i2.js → FilePreview-DvgnEspB.js} +1 -1
- package/dist/web/assets/{MarkdownRenderer-DFqPpAnM.js → MarkdownRenderer-e1ZUy6jV.js} +1 -1
- package/dist/web/assets/{McpModal-CX5-hlNv.js → McpModal-Raois2g1.js} +1 -1
- package/dist/web/assets/SettingsModal-Dzuatoea.js +1 -0
- package/dist/web/assets/{SettingsStore-jup_Kikq.js → SettingsStore-BxDA0Usw.js} +1 -1
- package/dist/web/assets/{SkillsModal-DaAUrwXO.js → SkillsModal-Cg2-befH.js} +1 -1
- package/dist/web/assets/{TerminalPanel-DzlllDH7.js → TerminalPanel-CEoQI9Lu.js} +1 -1
- package/dist/web/assets/index-BvGeIa_-.js +16 -0
- package/dist/web/assets/index-DDJnZJcp.css +1 -0
- package/dist/web/index.html +2 -2
- package/package.json +4 -11
- package/dist/chunk-1w6tqkxd.js +0 -34
- package/dist/chunk-2049tv49.js +0 -41
- package/dist/chunk-5be6qr2v.js +0 -2
- package/dist/chunk-67vzgcs5.js +0 -2
- package/dist/chunk-6811kbxn.js +0 -1
- package/dist/chunk-6js5wp6t.js +0 -1
- package/dist/chunk-6kp3z956.js +0 -9
- package/dist/chunk-78txnq4n.js +0 -151
- package/dist/chunk-7r1hm0qz.js +0 -6
- package/dist/chunk-a7yjnqhd.js +0 -3
- package/dist/chunk-bwaqaktn.js +0 -1
- package/dist/chunk-cb82rf5h.js +0 -1
- package/dist/chunk-ce11m8bq.js +0 -1
- package/dist/chunk-e4rhdg3h.js +0 -1
- package/dist/chunk-faq7ay4j.js +0 -24
- package/dist/chunk-ky8ctbdc.js +0 -1
- package/dist/chunk-mpskff34.js +0 -1
- package/dist/chunk-pd1yqxcv.js +0 -9
- package/dist/chunk-phhmmybg.js +0 -2
- package/dist/chunk-qnevwq1q.js +0 -2
- package/dist/chunk-r1spf93b.js +0 -26
- package/dist/chunk-z4c68ve0.js +0 -6
- package/dist/chunk-z9zbcenc.js +0 -6
- package/dist/web/assets/SettingsModal-CfR_q6N7.js +0 -1
- package/dist/web/assets/index-BJTSF3fc.js +0 -9
- package/dist/web/assets/index-CL6apjgo.css +0 -1
|
@@ -1,21 +1,21 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{vb as f0}from"./chunk-49g067ek.js";import{Cb as SZ}from"./chunk-jt62ctz7.js";import{Ib as c,Jb as yZ}from"./chunk-gsfkrr25.js";import{Mb as MZ,Nb as H0,Ob as UZ,Pb as QZ}from"./chunk-0dj326ms.js";import{Tb as i}from"./chunk-34pdtz4q.js";import{Wb as oQ}from"./chunk-hjx5n3dw.js";function M0(Q){return Q.role==="system"&&Array.isArray(Q.content)}class P0{systemMessages;_history;_pending=[];context;constructor(Q,$){this.context=Q;let Z=Q.messages.find(M0);if(Z)this.systemMessages=[Z];else if($)this.systemMessages=[{role:"system",content:[{type:"text",text:$,providerOptions:{anthropic:{cacheControl:{type:"ephemeral"}}}}]}];else this.systemMessages=[];this._history=Q.messages.filter((J)=>!M0(J))}get historyLength(){return this._history.length}get history(){return this._history}get pending(){return this._pending}toLLMMessages(){return[...this.systemMessages,...this._history,...this._pending]}getMessagesForLLM(){return this.toLLMMessages()}getHistory(){return this._history}appendPending(Q){this._pending.push(Q)}appendUser(Q){this._pending.push(Q)}appendAssistant(Q){this._pending.push(Q)}appendToolResult(Q){this._pending.push(Q)}appendControl(Q,$){if(Q==="system")throw Error("Cannot append system control message via appendControl. Use constructor for root system prompt.");this._pending.push($)}appendToHistory(Q){this._history.push(Q)}commitPending(){if(this._pending.length>0)this._history.push(...this._pending),this._pending=[]}replaceHistory(Q){this._history=Q.filter(($)=>!M0($))}removeMessages(Q){this._history=this._history.filter(($)=>!Q($)),this._pending=this._pending.filter(($)=>!Q($))}writeback(){this.commitPending(),this.context.messages=this._history}get hasSystemPrompt(){return this.systemMessages.length>0}}async function CZ(Q,$){let Z;while(!(Z=await Q.next()).done)if($)await $(Z.value);return Z.value}function TQ(Q){if(Q.isSubagent)return"continue";if(!Q.budget||Q.budget<=0)return"continue";if(Q.consecutiveContinuations>=3&&Q.lastOutputDelta<500)return"stop";if(Q.usage/Q.budget>=0.9)return"stop";return"continue"}function kQ(Q){return{budget:Q.budget,usage:0,consecutiveContinuations:0,lastOutputDelta:0,isSubagent:Q.isSubagent??!1}}function RQ(Q,$,Z){return{...Q,usage:Q.usage+$,lastOutputDelta:$,consecutiveContinuations:Z?Q.consecutiveContinuations+1:0}}var BQ=i("Agent"),pZ=3;function jQ(Q,$,Z){if(Q!=="length")return{action:"none"};if($>=pZ)return{action:"truncated"};if(TQ(Z)==="stop")return BQ.info("[Loop] Token budget: diminishing returns detected, skipping recovery"),{action:"budget_stop"};return{action:"recover"}}var gZ=[/:\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],dZ=/```[\s\S]{50,}```/,CQ="请执行你提到的操作,不要只是描述。使用 Edit/Write/Bash 工具来实际修改文件。",mZ=2;function DQ(Q,$,Z=!0){if(!Q||$>=mZ)return{action:"none"};if(!Z&&dZ.test(Q))return{action:"retry",prompt:CQ};let J=Q.slice(-200),G=J.match(/```/g);if(G&&G.length%2!==0)return{action:"none"};if(gZ.some((z)=>z.test(J)))return{action:"retry",prompt:CQ};return{action:"none"}}var cZ=[/\b(?:run|execute|rerun|re-run)\b[\s\S]{0,60}\b(?:tests?|test suite|lint|type-?check|build)\b/i,/\b(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?(?:test|lint|build|type-?check)\b/i,/(?:运行|执行|跑|重新运行).{0,30}(?:测试|单测|集成测试|检查|构建)/],uZ=/(?:^|\s)(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?(?:test|lint|build|type-?check)\b|(?:^|\s)(?:node|bun)\s+--test\b|(?:^|\s)(?:vitest|jest|pytest|go\s+test|cargo\s+test|tsc)\b/i,pQ={test:/\b(?:tests?|test suite)\b|(?:测试|单测|集成测试)/i,lint:/\blint(?:ing)?\b/i,"type-check":/\btype[\s-]?check(?:ing)?\b|\btsc\b|类型检查/i,build:/\bbuild\b|构建/i},iZ={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},nZ="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.",rZ=3;function KQ(Q){return uZ.test(Q)}function dQ(Q,$,Z){if(!Z.success)return;if(["Edit","Write","NotebookEdit"].includes($)){Q.clear();return}if($==="Bash"&&typeof Z.metadata?.command==="string"&&Z.metadata.exit_code===0&&KQ(Z.metadata.command)){Q.add(Z.metadata.command);return}if(!["Task","TaskOutput"].includes($))return;let J=Z.metadata?.verificationCommands;if(!Array.isArray(J))return;for(let G of J)if(typeof G==="string"&&KQ(G))Q.add(G)}function FQ(Q,$,Z){if(!Q||!cZ.some((Y)=>Y.test(Q)))return{action:"none"};let J=Object.keys(pQ).filter((Y)=>pQ[Y].test(Q)),G=[...$],W=J.filter((Y)=>!G.some((H)=>iZ[Y].test(H)));if(J.length>0?W.length===0:G.some(KQ))return{action:"none"};if(Z>=rZ)return{action:"fail",message:lZ};let V=J.length>1&&W.length>0?` Missing successful verification categories: ${W.join(", ")}.`:"";return{action:"retry",prompt:`${nZ}${V}`}}var aZ=[/\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|子代理|子智能体)/],oZ=[/\b(?:do not|don't|never)\s+(?:delegate|call|use|invoke)\b/i,/(?:不要|禁止|无需)(?:委派|调用|使用).{0,20}(?:Task|子代理|子智能体)?/],sZ=[/\b(?:call|use|invoke)\b[\s\S]{0,30}\bTask(?: tool)?\b[\s\S]{0,30}\bexactly once\b/i,/\bexactly once\b[\s\S]{0,30}\b(?:call|use|invoke)\b[\s\S]{0,30}\bTask(?: tool)?\b/i,/\bexactly one\b[\s\S]{0,30}\bTask(?: tool)? calls?\b/i,/(?:Task|子代理).{0,20}(?:恰好|仅|只)(?:调用|使用)?一次/,/(?:恰好|仅|只)(?:调用|使用)?一次.{0,20}(?:Task|子代理)/],tZ=[/\b(?:do not|don't|never)\s+(?:call|use|invoke)\s+(?:the\s+)?Task\b[\s\S]{0,30}\bexactly once\b/i,/\bTask\b[\s\S]{0,30}\b(?:does not|doesn't|need not)\b[\s\S]{0,30}\bexactly once\b/i,/\bmultiple\s+Task(?: tool)?\s+calls?\s+(?:are\s+)?allowed\b/i,/(?:不要|禁止).{0,12}(?:Task|子代理).{0,12}(?:恰好|仅|只)(?:调用|使用)?一次/];function eZ(Q){if(typeof Q!=="string")return;if(tZ.some(($)=>$.test(Q)))return"multiple-allowed";return sZ.some(($)=>$.test(Q))?"required":void 0}function x0(Q){for(let $ of Q){let Z=eZ($);if(Z!==void 0)return Z==="required"}return!1}var Q2="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.",Z2="Required delegation did not complete before the retry limit.",$2=3;function mQ(Q,$,Z){let J=(typeof Q==="string"?[Q]:Q??[]).map((z)=>z.trim()).filter(Boolean),G=x0(J),W=!1;if(!G)for(let z of J){if(oZ.some((V)=>V.test(z)))break;if(aZ.some((V)=>V.test(z))){W=!0;break}}if(J.length===0||!G&&!W||$.has("Task"))return{action:"none"};if(Z>=$2)return{action:"fail",message:Z2};return{action:"retry",prompt:Q2}}var J2=[/\b(?:use|create|enter|start|work\s+(?:in|inside))\b.{0,60}\bworktree\b/i,/(?:使用|创建|进入).{0,30}(?:worktree|工作树)/i],G2=[/\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 h0(Q){return typeof Q==="string"&&J2.some(($)=>$.test(Q))}var W2="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.",z2="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.",V2="Required worktree lifecycle did not complete before the retry limit.",Y2=3;function cQ(Q,$,Z){if(!Q||!h0(Q))return{action:"none"};let J=G2.some((W)=>W.test(Q));if($.has("TaskWorktree"))return{action:"none"};let G=!$.has("EnterWorktree")?"EnterWorktree":J&&!$.has("ExitWorktree")?"ExitWorktree":void 0;if(!G)return{action:"none"};if(Z>=Y2)return{action:"fail",message:V2};return{action:"retry",tool:G,prompt:G==="EnterWorktree"?W2:z2}}var gQ=30000;async function OQ(Q){try{let Z=f0.getInstance().executeStopHooks({projectDir:c(),sessionId:Q.sessionId,permissionMode:Q.permissionMode,reason:Q.reason,abortSignal:Q.abortSignal}),J,G=new Promise((W)=>{J=setTimeout(()=>W("timeout"),gQ)});try{let W=await Promise.race([Z,G]);if(W==="timeout")return BQ.warn(`[Loop] Stop hook 超时 (${gQ}ms),按 shouldStop: true 处理`),{action:"stop"};let z=W;if(!z.shouldStop)return{action:"continue",reason:z.continueReason};return{action:"stop"}}finally{clearTimeout(J)}}catch($){return BQ.warn("[Loop] Stop hook execution failed:",$),{action:"stop"}}}var K0=i("Agent"),LQ=`<turn_aborted>
|
|
2
2
|
The previous turn was interrupted. Commands or tool calls may have partially completed; inspect the workspace and running processes before retrying.
|
|
3
|
-
</turn_aborted>`;function j0(Q){return Q.executionEngine?.getContextManager()}async function
|
|
3
|
+
</turn_aborted>`;function j0(Q){return Q.executionEngine?.getContextManager()}async function o(Q,$,Z,J=null,G){try{let W=j0(Q),z=typeof Z==="string"?Z.trim()!=="":Z.some((V)=>V.type==="text"?V.text.trim()!=="":!0);if(W&&$.sessionId&&z)return await W.saveMessage($.sessionId,"user",Z,J,G,$.subagentInfo)}catch(W){K0.warn("[Loop] 保存用户消息失败:",W)}return null}async function d(Q,$,Z,J){try{let G=j0(Q);if(G&&$.sessionId&&Z.trim())return await G.saveMessage($.sessionId,"assistant",Z,J,void 0,$.subagentInfo)}catch(G){K0.warn("[Loop] 保存助手消息失败:",G)}return null}async function uQ(Q,$,Z){try{let J=j0(Q);if(J&&$.sessionId)return await J.saveMessage($.sessionId,"system",LQ,Z,void 0,$.subagentInfo)}catch(J){K0.warn("[Loop] 保存中断边界失败:",J)}return null}async function bQ(Q,$,Z,J,G){try{let W=j0(Q);if(W&&$.sessionId)return await W.saveToolUse($.sessionId,Z,J,G,$.subagentInfo)}catch(W){K0.warn("[Loop] 保存工具调用失败:",W)}return null}async function T0(Q,$,Z,J,G,W,z,V){try{let Y=j0(Q);if(Y&&$.sessionId)return await Y.saveToolResult($.sessionId,Z,J,G,W,z,$.subagentInfo,V)}catch(Y){K0.warn("[Loop] 保存工具结果失败:",Y)}return null}async function k0(Q,$,Z,J){try{let G=j0(Q);if(G&&$.sessionId)return await G.saveCompaction($.sessionId,Z,J,null)}catch(G){K0.warn("[Loop] 保存压缩数据失败:",G)}return null}function iQ(Q,$){if(!["TaskCreate","TaskUpdate","TaskList"].includes(Q.function.name)||!$.success||!$.llmContent&&!$.metadata)return null;let Z=typeof $.llmContent==="object"?$.llmContent:{};return{kind:"task_update",tasks:$.metadata?.tasks||Z.tasks||[]}}function nQ(Q,$,Z){if(Q.function.name!=="Skill"||!$.success||!$.metadata)return;let J=$.metadata;if(J.skillName)Z.onSkillActivated?.({skillName:J.skillName,allowedTools:J.allowedTools,basePath:J.basePath||""})}function lQ(Q){let $=Q.metadata;if(!$)return;return $.modelId?.toString().trim()||$.model?.toString().trim()||void 0||void 0}function X2(Q,$,Z){if(!["EnterWorktree","ExitWorktree"].includes(Q.function.name)||!$.success)return;let J=$.metadata,G=J?.workspaceRoot;if(!["enter","exit"].includes(String(J?.workspaceTransition))||typeof G!=="string"||G.trim()==="")return;return Z.workspaceRoot=G,Z.worktreeActive=J?.workspaceTransition==="enter",G}function H2(Q,$){if(Q.function.name!=="Task")return null;let Z=$.metadata;if(!Z?.subagentSessionId)return null;let J=Z.subagentSessionId,G=Z.subagentType||"Task",W=Z.subagentStatus,z=typeof Z.subagentResumedFrom==="string"?Z.subagentResumedFrom:void 0,V=typeof Z.subagentRootId==="string"?Z.subagentRootId:void 0,Y=typeof Z.subagentResumeDepth==="number"?Z.subagentResumeDepth:void 0;if(W==="completed"||W==="failed"||W==="cancelled")return{kind:"subagent_completed",sessionId:J,success:W==="completed",summary:Z.subagentSummary,resumedFrom:z,rootAgentId:V,resumeDepth:Y};if(W==="running"){let H="";try{H=JSON.parse(Q.function.arguments).prompt||""}catch{}return{kind:"subagent_spawned",sessionId:J,type:G,prompt:H,resumedFrom:z,rootAgentId:V,resumeDepth:Y}}return null}async function qQ(Q,$,Z,J){let G=iQ(Q,$),W=H2(Q,$);nQ(Q,$,Z);let z=lQ($);if(z)await Z.onModelSwitch?.(z);if(J)X2(Q,$,J);return W||G}import{promises as _2}from"node:fs";import w2 from"node:path";import{nanoid as $0}from"nanoid";import*as h from"node:fs/promises";import*as z0 from"node:path";var rQ={enabled:!0,maxIndexLines:200};var B2="memory",aQ="MEMORY.md";class _Q{memoryDir;config;initialized=!1;constructor(Q,$,Z){if(Z)this.memoryDir=Z;else{let J=oQ(Q);this.memoryDir=z0.join(J,B2)}this.config={...rQ,...$}}async initialize(){if(this.initialized)return;await h.mkdir(this.memoryDir,{recursive:!0}),this.initialized=!0}async loadIndex(){if(!this.config.enabled)return null;await this.initialize();let Q=z0.join(this.memoryDir,aQ);try{let $=await h.readFile(Q,"utf-8");if(!$.trim())return null;let Z=$.split(`
|
|
4
4
|
`),G=Z.slice(0,this.config.maxIndexLines).join(`
|
|
5
5
|
`).trim();if(Z.length>this.config.maxIndexLines)return G+`
|
|
6
6
|
|
|
7
7
|
<!-- ${Z.length-this.config.maxIndexLines} more lines in MEMORY.md, use MemoryRead to access -->`;return G||null}catch($){if($ instanceof Error&&"code"in $&&$.code==="ENOENT")return null;throw $}}async readTopic(Q){await this.initialize();let $=this.resolveTopicPath(Q);try{return await h.readFile($,"utf-8")||null}catch(Z){if(Z instanceof Error&&"code"in Z&&Z.code==="ENOENT")return null;throw Z}}async writeTopic(Q,$,Z="append"){await this.initialize();let J=this.resolveTopicPath(Q);if(Z==="append"){let G="";try{G=await h.readFile(J,"utf-8")}catch{}let W=G&&!G.endsWith(`
|
|
8
8
|
`)?`
|
|
9
|
-
`:"";await h.writeFile(J,G+W+$,"utf-8")}else await h.writeFile(J,$,"utf-8")}async updateIndex(Q,$="overwrite"){await this.initialize();let Z=
|
|
9
|
+
`:"";await h.writeFile(J,G+W+$,"utf-8")}else await h.writeFile(J,$,"utf-8")}async updateIndex(Q,$="overwrite"){await this.initialize();let Z=z0.join(this.memoryDir,aQ);if($==="append"){let J="";try{J=await h.readFile(Z,"utf-8")}catch{}let G=J&&!J.endsWith(`
|
|
10
10
|
`)?`
|
|
11
|
-
`:"";await h.writeFile(Z,J+G+Q,"utf-8")}else await h.writeFile(Z,Q,"utf-8")}async listTopics(){await this.initialize();try{let Q=await h.readdir(this.memoryDir,{withFileTypes:!0}),$=[];for(let Z of Q){if(!Z.isFile()||!Z.name.endsWith(".md"))continue;let J=
|
|
11
|
+
`:"";await h.writeFile(Z,J+G+Q,"utf-8")}else await h.writeFile(Z,Q,"utf-8")}async listTopics(){await this.initialize();try{let Q=await h.readdir(this.memoryDir,{withFileTypes:!0}),$=[];for(let Z of Q){if(!Z.isFile()||!Z.name.endsWith(".md"))continue;let J=z0.join(this.memoryDir,Z.name),G=await h.stat(J);$.push({name:Z.name.replace(/\.md$/,""),size:G.size,lastModified:G.mtime})}return $.sort((Z,J)=>J.lastModified.getTime()-Z.lastModified.getTime())}catch{return[]}}async deleteTopic(Q){let $=this.resolveTopicPath(Q);try{return await h.unlink($),!0}catch{return!1}}async clearAll(){let Q=await this.listTopics(),$=0;for(let Z of Q){let J=z0.join(this.memoryDir,`${Z.name}.md`);try{await h.unlink(J),$++}catch{}}return $}getMemoryDir(){return this.memoryDir}resolveTopicPath(Q){let $=Q.replace(/[/\\:*?"<>|]/g,"-"),Z=$.endsWith(".md")?$:`${$}.md`,J=z0.join(this.memoryDir,Z);if(!J.startsWith(this.memoryDir))throw Error(`Invalid topic name: ${Q}`);return J}}var K2=[{pattern:/(?:记住|remember|note|备注)[::](.+)/i,topic:"preferences"},{pattern:/(?:convention|约定|规范)[::](.+)/i,topic:"conventions"},{pattern:/(?:lesson|教训|踩坑)[::](.+)/i,topic:"lessons"}],j2=/(?:fix|修复|解决|resolved)[::]\s*(.+?)(?:\n|$)/i,D2=/(?:Error|FAIL|错误)[::]\s*(.+?)(?:\n|$)/i;function F2(Q){let $=new Map;for(let Z of Q){if(!Z.content||typeof Z.content!=="string")continue;let J=Z.content;if(Z.role==="user")for(let{pattern:G,topic:W}of K2){let z=J.match(G);if(z?.[1]){let V=$.get(W)??[];V.push(z[1].trim()),$.set(W,V)}}if(Z.role==="assistant"){let G=J.match(j2);if(G?.[1]&&G[1].length>20&&G[1].length<200){let W=$.get("debugging")??[];W.push(G[1].trim()),$.set("debugging",W)}}if(Z.role==="tool"&&Z.content?.includes("Error")){let G=J.match(D2);if(G?.[1]&&G[1].length>10){let W=$.get("debugging")??[];if(W.length<5)W.push(`Tool error pattern: ${G[1].trim().slice(0,150)}`),$.set("debugging",W)}}}return $}async function sQ(Q){let $=F2(Q);if($.size===0)return{extracted:0,topics:[]};try{let Z=new _Q(c());await Z.initialize();let J=[],G=0;for(let[W,z]of $){if(z.length===0)continue;let V=new Date().toISOString().split("T")[0],Y=z.map((H)=>`- [${V}] ${H}`).join(`
|
|
12
12
|
`);await Z.writeTopic(W,Y+`
|
|
13
|
-
`,"append"),J.push(W),G+=z.length}return{extracted:G,topics:J}}catch{return{extracted:0,topics:[]}}}import{promises as
|
|
14
|
-
`);if(this.extractFilePathsFromContent(W).forEach((V)=>{this.updateFileReference($,V,G,!1)}),J.tool_calls&&Array.isArray(J.tool_calls))J.tool_calls.forEach((V)=>{let Y=this.extractFilePathsFromToolCall(V),H=V.type==="function"&&"function"in V?V.function?.name:"",
|
|
15
|
-
`),V=z.length,Y=W,H=!1,
|
|
13
|
+
`,"append"),J.push(W),G+=z.length}return{extracted:G,topics:J}}catch{return{extracted:0,topics:[]}}}import{promises as R0}from"node:fs";import*as Y0 from"fs/promises";import*as A from"path";var tQ=[".git",".claude","node_modules",".env",".env.local",".env.production",".env.development",".env.test"];class V0 extends Error{code;constructor(Q,$){super(Q);this.code=$;this.name="PathSecurityError"}}class X0{static normalize(Q,$){let Z=A.isAbsolute(Q)?Q:A.resolve($,Q),J=A.normalize(Z),G=A.normalize($);if(!this.isWithinWorkspace(J,G))throw new V0(`Path outside workspace: ${Q} (resolved to ${J}, workspace: ${G})`,"PATH_OUTSIDE_WORKSPACE");return J}static checkRestricted(Q){let $=Q.split(A.sep);for(let Z of tQ)if($.includes(Z))throw new V0(`Access denied: "${Z}" is a protected directory`,"RESTRICTED_PATH")}static checkTraversal(Q){if(Q.includes(".."))throw new V0(`Path traversal not allowed: ${Q}`,"PATH_TRAVERSAL")}static async validatePath(Q,$){this.checkTraversal(Q);let Z=this.normalize(Q,$);this.checkRestricted(Z);try{await Y0.access(Z)}catch(J){throw new V0(`Path not found: ${Q}`,"PATH_NOT_FOUND")}return Z}static async resolveSymlink(Q,$){try{let Z=await Y0.realpath(Q),J=await Y0.realpath($);if(!this.isWithinWorkspace(Z,J))throw new V0(`Symlink points outside workspace: ${Q} -> ${Z}`,"SYMLINK_OUTSIDE_WORKSPACE");return Z}catch(Z){if(Z instanceof V0)throw Z;return Q}}static getRelativePath(Q,$){return A.relative($,Q)}static isWithinWorkspace(Q,$){let Z=A.resolve(Q),J=A.resolve($),G=A.relative(J,Z);return G===""||G!==".."&&!G.startsWith(`..${A.sep}`)&&!A.isAbsolute(G)}static async isWithinWorkspaceResolved(Q,$){let Z=A.resolve($),J=A.isAbsolute(Q)?A.resolve(Q):A.resolve(Z,Q);if(!this.isWithinWorkspace(J,Z))return!1;let G;try{G=await Y0.realpath(Z)}catch{return!1}let W=J;while(!0){try{let V=await Y0.realpath(W);return this.isWithinWorkspace(V,G)}catch(V){let Y=V.code;if(Y!=="ENOENT"&&Y!=="ENOTDIR")return!1}let z=A.dirname(W);if(z===W)return!1;W=z}}static isRestricted(Q){let $=Q.split(A.sep);return tQ.some((Z)=>$.includes(Z))}}var w0=i("Tool");class Z0{static instance=null;accessedFiles=new Map;constructor(){}static getInstance(){if(!Z0.instance)Z0.instance=new Z0;return Z0.instance}async recordFileRead(Q,$){try{let Z=await R0.stat(Q),J={filePath:Q,accessTime:Date.now(),mtime:Z.mtimeMs,sessionId:$,lastOperation:"read"};this.setRecord(J),w0.debug(`记录文件读取: ${Q}`)}catch(Z){w0.warn(`记录文件读取失败: ${Q}`,Z)}}async recordFileEdit(Q,$,Z="edit"){try{let J=await R0.stat(Q),G={filePath:Q,accessTime:Date.now(),mtime:J.mtimeMs,sessionId:$,lastOperation:Z};this.setRecord(G),w0.debug(`记录文件${Z==="edit"?"编辑":"写入"}: ${Q}`)}catch(J){w0.warn(`记录文件${Z==="edit"?"编辑":"写入"}失败: ${Q}`,J)}}hasFileBeenRead(Q,$){let Z=this.accessedFiles.get(Q);if(!Z)return!1;return $?Z.has($):Z.size>0}async checkFileModification(Q,$){let Z=this.getFileRecord(Q,$);if(!Z)return{modified:!1,message:"文件未被跟踪"};try{let J=await R0.stat(Q);if(Math.abs(J.mtimeMs-Z.mtime)>1)return{modified:!0,message:`文件在访问后被修改(访问时间: ${new Date(Z.accessTime).toISOString()}, 当前修改时间: ${J.mtime.toISOString()})`};return{modified:!1}}catch(J){let G=J;if(G.code==="ENOENT")return{modified:!0,message:"文件已被删除"};return{modified:!1,message:`无法检查文件状态: ${G.message}`}}}async checkExternalModification(Q,$){let Z=this.getFileRecord(Q,$);if(!Z)return{isExternal:!1,message:"文件未被跟踪"};try{let J=await R0.stat(Q);if(J.mtimeMs-Z.mtime>2000)return{isExternal:!0,message:`文件在 ${new Date(Z.accessTime).toISOString()} (${Z.lastOperation}) 之后被外部程序修改(当前修改时间: ${J.mtime.toISOString()})`};return{isExternal:!1}}catch(J){let G=J;if(G.code==="ENOENT")return{isExternal:!0,message:"文件已被删除"};return w0.warn(`检查文件外部修改失败: ${Q}`,J),{isExternal:!1,message:`无法检查文件状态: ${G.message}`}}}getFileRecord(Q,$){let Z=this.accessedFiles.get(Q);if(!Z)return;if($)return Z.get($);return[...Z.values()].sort((J,G)=>G.accessTime-J.accessTime)[0]}getTrackedRecords(){return[...this.accessedFiles.values()].flatMap((Q)=>[...Q.values()])}clearFileRecord(Q){this.accessedFiles.delete(Q)}clearAll(){this.accessedFiles.clear()}clearSession(Q,$){for(let[Z,J]of this.accessedFiles.entries()){if($&&!X0.isWithinWorkspace(Z,$))continue;if(J.delete(Q),J.size===0)this.accessedFiles.delete(Z)}}getTrackedFiles(){return Array.from(this.accessedFiles.keys())}getTrackedFileCount(){return this.accessedFiles.size}static resetInstance(){Z0.instance=null}setRecord(Q){let $=this.accessedFiles.get(Q.filePath);if(!$)$=new Map,this.accessedFiles.set(Q.filePath,$);$.set(Q.sessionId,Q)}}import{readFile as O2}from"node:fs/promises";import{basename as L2,isAbsolute as b2,resolve as q2}from"node:path";class C0{static MAX_FILES=5;static MAX_LINES_PER_FILE=1000;static analyzeFiles(Q){let $=new Map;return Q.forEach((J,G)=>{let W=typeof J.content==="string"?J.content:(J.content||[]).filter((V)=>V.type==="text").map((V)=>V.text).join(`
|
|
14
|
+
`);if(this.extractFilePathsFromContent(W).forEach((V)=>{this.updateFileReference($,V,G,!1)}),J.tool_calls&&Array.isArray(J.tool_calls))J.tool_calls.forEach((V)=>{let Y=this.extractFilePathsFromToolCall(V),H=V.type==="function"&&"function"in V?V.function?.name:"",D=["Write","Edit"].includes(H||"");Y.forEach((b)=>{this.updateFileReference($,b,G,D)})})}),Array.from($.values()).sort((J,G)=>{if(J.wasModified!==G.wasModified)return J.wasModified?-1:1;if(J.mentions!==G.mentions)return G.mentions-J.mentions;return G.lastMentioned-J.lastMentioned}).slice(0,this.MAX_FILES)}static async readFilesContent(Q,$){let Z=[];for(let J of Q)try{let G=$&&!b2(J)?q2($,J):J;if($&&!await X0.isWithinWorkspaceResolved(G,$))continue;let W=await O2(G,"utf-8"),z=W.split(`
|
|
15
|
+
`),V=z.length,Y=W,H=!1,D=V;if(V>this.MAX_LINES_PER_FILE)Y=z.slice(0,this.MAX_LINES_PER_FILE).join(`
|
|
16
16
|
`),Y+=`
|
|
17
17
|
|
|
18
|
-
... (truncated ${V-this.MAX_LINES_PER_FILE} lines)`,H=!0,
|
|
18
|
+
... (truncated ${V-this.MAX_LINES_PER_FILE} lines)`,H=!0,D=this.MAX_LINES_PER_FILE;Z.push({path:J,content:Y,truncated:H,lines:V,includedLines:D})}catch(G){console.warn(`[FileAnalyzer] 无法读取文件: ${J}`,G)}return Z}static extractFilePathsFromContent(Q){let $=new Set,Z=/```(?:\w+)?\s*\n?([\s\S]*?)```/g,J=Array.from(Q.matchAll(Z));for(let W of J){let z=W[1];this.extractPathsFromText(z).forEach((Y)=>$.add(Y))}return this.extractPathsFromText(Q).forEach((W)=>$.add(W)),Array.from($)}static extractPathsFromText(Q){let $=[],Z=[/(?:src|tests?|docs?|lib|config|scripts?|bin|utils?|components?|services?|hooks?)\/[\w\-/.]+\.[\w]+/g,/(?:package|tsconfig|vite\.config|webpack\.config|next\.config|babel\.config)\.[\w]+/g,/(?:\.\.?\/|\/)[a-zA-Z0-9\-_/.]+\.[\w]+/g];for(let J of Z){let G=Array.from(Q.matchAll(J));for(let W of G){let z=W[0];if(z=z.replace(/[,。;:!?""''()【】《》]$/g,""),z=z.replace(/[,.;:!?"'()[\]<>]$/g,""),this.isValidFilePath(z))$.push(z)}}return $}static extractFilePathsFromToolCall(Q){let $=[];if(Q.type!=="function"||!Q.function)return $;try{let Z=Q.function.name,J=JSON.parse(Q.function.arguments||"{}");if(["Read","Write","Edit","Glob","Grep","NotebookEdit","mcp__github__get_file_contents","mcp__github__create_or_update_file"].includes(Z)){let W=["file_path","path","notebook_path","filePath"];for(let z of W)if(J[z]&&typeof J[z]==="string")$.push(J[z])}}catch{}return $}static updateFileReference(Q,$,Z,J){let G=Q.get($);if(G)G.mentions++,G.lastMentioned=Z,G.wasModified=G.wasModified||J;else Q.set($,{path:$,mentions:1,lastMentioned:Z,wasModified:J})}static isValidFilePath(Q){if(!Q.includes("/"))return!1;let $=L2(Q);if(!$.includes("."))return!1;let Z=["ts","tsx","js","jsx","json","md","py","java","go","rs","c","cpp","h","css","scss","html","xml","yaml","yml","toml","sh","bash","sql","graphql","vue","svelte"],J=$.split(".").pop()?.toLowerCase();if(!J||!Z.includes(J))return!1;return!0}}import{encodingForModel as eQ}from"js-tiktoken";class N0{static encodingCache=new Map;static countTokens(Q,$){let Z=this.getEncoding($),J=0;for(let G of Q){if(J+=4,G.role)J+=Z.encode(G.role).length;if(G.content)if(typeof G.content==="string")J+=Z.encode(G.content).length;else J+=Z.encode(JSON.stringify(G.content)).length;if(G.tool_calls&&Array.isArray(G.tool_calls))J+=this.countToolCallTokens(G.tool_calls,Z);if(G.name)J+=Z.encode(G.name).length}return J}static getTokenLimit(Q){return Q}static shouldCompact(Q,$,Z,J=0.8){let G=this.countTokens(Q,$),W=Math.floor(Z*J);return G>=W}static getEncoding(Q){if(!this.encodingCache.has(Q))try{let $=eQ(Q);this.encodingCache.set(Q,$)}catch{try{let $=eQ("gpt-4");this.encodingCache.set(Q,$)}catch{console.warn(`[TokenCounter] 无法为模型 ${Q} 获取 encoding,使用粗略估算`),this.encodingCache.set(Q,{encode:($)=>{return Array(Math.ceil($.length/4))}})}}return this.encodingCache.get(Q)}static countToolCallTokens(Q,$){let Z=0;for(let J of Q){if(Z+=4,J.type==="function"&&J.function?.name)Z+=$.encode(J.function.name).length;if(J.type==="function"&&J.function?.arguments)Z+=$.encode(J.function.arguments).length;if(J.id)Z+=$.encode(J.id).length}return Z}static clearCache(){this.encodingCache.clear()}static estimateTokens(Q){let $=(Q.match(/[\u4e00-\u9fa5]/g)||[]).length,Z=Q.length-$;return Math.ceil($/1.5+Z/4)}}var k=i("Context"),p0=new Map,N2=3;function E2(Q,$){return JSON.stringify([w2.resolve(Q??c()),$??null])}class D0{static THRESHOLD_PERCENT=0.8;static RETAIN_PERCENT=0.2;static FALLBACK_RETAIN_PERCENT=0.3;static ACTIVE_TASK_MAX_CHARS=6000;static async compact(Q,$){if($.signal?.aborted)throw new DOMException("Aborted","AbortError");let Z=$.actualPreTokens??N0.countTokens(Q,$.modelName),J=$.actualPreTokens?"actual (from LLM usage)":"estimated";k.debug(`[CompactionService] preTokens source: ${J}`);try{let V=await f0.getInstance().executeCompactionHooks($.trigger,{projectDir:$.workspaceRoot??c(),sessionId:$.sessionId||"unknown",permissionMode:$.permissionMode||"default",messagesBefore:Q.length,tokensBefore:Z});if(V.blockCompaction)return k.debug(`[CompactionService] Compaction hook 阻止压缩: ${V.blockReason||"(无原因)"}`),{success:!1,summary:"",preTokens:Z,postTokens:Z,filesIncluded:[],compactedMessages:Q,boundaryMessage:{role:"system",content:""},summaryMessage:{role:"user",content:""},error:V.blockReason||"Compaction blocked by hook"};if(V.warning)k.warn(`[CompactionService] Compaction hook warning: ${V.warning}`)}catch(z){k.warn("[CompactionService] Compaction hook execution failed:",z)}let G=E2($.workspaceRoot,$.sessionId),W=p0.get(G)??0;if(W>=N2)return k.warn(`[CompactionService] Circuit breaker open (${W} consecutive failures for session ${$.sessionId??"unknown"}), using fallback`),this.fallbackCompact(Q,$,Z,Error("Circuit breaker open"));try{k.debug("[CompactionService] 开始压缩,消息数:",Q.length),k.debug("[CompactionService] 压缩前 tokens:",Z);let V=C0.analyzeFiles(Q).map((C)=>C.path);k.debug("[CompactionService] 提取重点文件:",V);let Y=await C0.readFilesContent(V,$.workspaceRoot);k.debug("[CompactionService] 成功读取文件:",Y.length);let H=await this.generateSummary(Q,Y,$),{summary:D}=H;k.debug("[CompactionService] 生成总结,长度:",D.length);let b=Math.ceil(Q.length*this.RETAIN_PERCENT),F=Q.slice(-b),O=new Set;for(let C of F)if(C.role==="assistant"&&C.tool_calls)for(let a of C.tool_calls)O.add(a.id);let T=F.filter((C)=>{if(C.role==="tool"&&C.tool_call_id)return O.has(C.tool_call_id);return!0});k.debug("[CompactionService] 保留消息数:",b),k.debug("[CompactionService] 过滤后保留消息数:",T.length);let R=$0(),v=this.createBoundaryMessage(R,$.trigger,Z),E=$0(),L=this.createSummaryMessage(E,D),n=[L,...T],r=await this.buildFileRestorationMessage($.workspaceRoot,$.sessionId);if(r)n.push(r);let S=this.buildActiveTaskMessage($.activeTask);if(S)n.push(S);let t=N0.countTokens(n,$.modelName);k.debug("[CompactionService] 压缩完成!"),k.debug("[CompactionService] Token 变化:",Z,"->",t,`(-${((1-t/Z)*100).toFixed(1)}%)`),p0.delete(G);let o0=Q.slice(0,Q.length-b);return sQ(o0).catch((C)=>{return}),{success:!0,summary:D,preTokens:Z,postTokens:t,filesIncluded:Y.map((C)=>C.path),compactedMessages:n,boundaryMessage:v,summaryMessage:L,usage:H.usage}}catch(z){if(H0(z))throw z;return p0.set(G,(p0.get(G)??0)+1),k.error("[CompactionService] 压缩失败,使用降级策略",z),this.fallbackCompact(Q,$,Z,z)}}static async generateSummary(Q,$,Z){let J=this.buildCompactionPrompt(Q,$);if(k.debug("[CompactionService] 使用压缩模型:",Z.modelName),Z.signal?.aborted)throw new DOMException("Aborted","AbortError");let W=await(await QZ({apiKey:Z.apiKey||process.env.BLADE_API_KEY,baseUrl:Z.baseURL||process.env.BLADE_BASE_URL,model:Z.modelName,temperature:0.3,maxOutputTokens:8000,timeout:60000,provider:Z.modelProvider??"openai"})).chat([{role:"user",content:J}],[],Z.signal),z=W.content||"",V=z.match(/<summary>([\s\S]*?)<\/summary>/);if(!V)return k.warn("[CompactionService] 总结格式不正确,使用完整响应"),{summary:z,usage:W.usage};return{summary:V[1].trim(),usage:W.usage}}static buildCompactionPrompt(Q,$){let Z=Q.map((W,z)=>{let V=W.role||"unknown",Y=typeof W.content==="string"?W.content:JSON.stringify(W.content),H=5000,D=Y.length>5000?Y.substring(0,5000)+"...":Y;return`[${z+1}] ${V}: ${D}`}).join(`
|
|
19
19
|
|
|
20
20
|
`),J=$.map((W)=>{return`### ${W.path}
|
|
21
21
|
\`\`\`
|
|
@@ -88,35 +88,35 @@ ${$.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:$0(),role:"system",content:"Conversation compacted",metadata:{type:"system",subtype:"compact_boundary",parentId:Q,compactMetadata:{trigger:$,preTokens:Z}}}}static createSummaryMessage(Q,$){return{id:$0(),role:"user",content:$,metadata:{parentId:Q,isCompactSummary:!0}}}static async getRecentlyAccessedFiles(Q,$,Z){let G=Z0.getInstance().getTrackedRecords().filter((z)=>!Z||z.sessionId===Z).sort((z,V)=>V.accessTime-z.accessTime),W=[];for(let z of G){if($&&!await X0.isWithinWorkspaceResolved(z.filePath,$))continue;if(!W.includes(z.filePath))W.push(z.filePath);if(W.length>=Q)break}return W}static async buildFileRestorationMessage(Q,$){let Z=await this.getRecentlyAccessedFiles(5,Q,$);if(Z.length===0)return null;let J=[];for(let W of Z)try{let V=(await _2.readFile(W,"utf-8")).split(`
|
|
92
92
|
`),Y=V.slice(0,200).join(`
|
|
93
93
|
`),H=V.length>200?`
|
|
94
94
|
... (${V.length-200} more lines)`:"";J.push(`<file path="${W}" lines="${V.length}">
|
|
95
95
|
${Y}${H}
|
|
96
96
|
</file>`)}catch{}if(J.length===0)return null;let G=["<system-reminder>","Post-compaction file restoration. These files were recently accessed in the conversation:",...J,"</system-reminder>"].join(`
|
|
97
|
-
`);return
|
|
97
|
+
`);return k.debug("[CompactionService] Post-compact 恢复文件:",Z.length),{id:$0(),role:"user",content:G,metadata:{isPostCompactRestoration:!0}}}static buildActiveTaskMessage(Q){if(!Q)return null;let $=this.ACTIVE_TASK_MAX_CHARS,Z=Math.floor($*0.75),J=Q.length<=$?Q:[Q.slice(0,Z),`
|
|
98
98
|
...[active task checkpoint truncated]...
|
|
99
|
-
`,Q.slice(-($-Z))].join("");return{id
|
|
100
|
-
`),metadata:{isPostCompactActiveTask:!0}}}static fallbackCompact(Q,$,Z,J){let G=Math.ceil(Q.length*this.FALLBACK_RETAIN_PERCENT),W=Q.slice(-G),z=new Set;for(let v of W)if(v.role==="assistant"&&v.tool_calls)for(let
|
|
99
|
+
`,Q.slice(-($-Z))].join("");return{id:$0(),role:"user",content:["<system-reminder>","Post-compaction active task checkpoint. Continue this user-authored request; preserve its exact literals and constraints:",J,"</system-reminder>"].join(`
|
|
100
|
+
`),metadata:{isPostCompactActiveTask:!0}}}static fallbackCompact(Q,$,Z,J){let G=Math.ceil(Q.length*this.FALLBACK_RETAIN_PERCENT),W=Q.slice(-G),z=new Set;for(let v of W)if(v.role==="assistant"&&v.tool_calls)for(let E of v.tool_calls)z.add(E.id);let V=W.filter((v)=>{if(v.role==="tool"&&v.tool_call_id)return z.has(v.tool_call_id);return!0}),Y=$0(),H=this.createBoundaryMessage(Y,$.trigger,Z),D=J instanceof Error?J.message:String(J),b=$0(),F=this.createSummaryMessage(b,`[Automatic compaction failed; using fallback]
|
|
101
101
|
|
|
102
102
|
An error occurred during compaction. Retained the latest ${G} messages (~30%).
|
|
103
103
|
|
|
104
|
-
Error: ${
|
|
104
|
+
Error: ${D}
|
|
105
105
|
|
|
106
|
-
The conversation can continue, but consider retrying compaction later with /compact.`),
|
|
107
|
-
`),preTokens:Z,postTokens:R,filesIncluded:[],compactedMessages:
|
|
106
|
+
The conversation can continue, but consider retrying compaction later with /compact.`),O=[F,...V],T=this.buildActiveTaskMessage($.activeTask);if(T)O.push(T);let R=N0.countTokens(O,$.modelName);return{success:!1,summary:typeof F.content==="string"?F.content:F.content.filter((v)=>v.type==="text").map((v)=>v.text).join(`
|
|
107
|
+
`),preTokens:Z,postTokens:R,filesIncluded:[],compactedMessages:O,boundaryMessage:H,summaryMessage:F,error:D}}}var v2=new Set(["Read","Grep","Glob","Search","WebSearch","WebFetch","ToolSearch"]);function I2(Q,$){let G=(Q[$.assistantIdx].tool_calls??[]).filter((z)=>z.type==="function").map((z)=>z.function.name).some((z)=>!v2.has(z));if($.toolResultIdxs.some((z)=>{let V=Q[z]?.content;if(typeof V!=="string")return!1;return V.startsWith("Error:")||V.includes("failed")||V.includes("ENOENT")}))return 3;if(G)return 2;return 1}function E0(Q,$){let Z=$?.keepRecentTurns??10,J=$?.minMessagesForSnip??30;if(Q.length<J)return{messages:Q,snippedCount:0,estimatedTokensFreed:0};let G=[];for(let F=0;F<Q.length;F++){let O=Q[F];if(O.role==="assistant"&&O.tool_calls&&O.tool_calls.length>0){let T=new Set(O.tool_calls.map((v)=>v.id)),R=[];for(let v=F+1;v<Q.length;v++){let E=Q[v];if(E.role==="tool"&&E.tool_call_id&&T.has(E.tool_call_id))R.push(v);if(E.role==="assistant"||E.role==="user")break}G.push({assistantIdx:F,toolResultIdxs:R,priority:0})}}for(let F of G)F.priority=I2(Q,F);let V=[...G.slice(0,Math.max(0,G.length-Z))].sort((F,O)=>F.priority-O.priority);if(V.length===0)return{messages:Q,snippedCount:0,estimatedTokensFreed:0};let Y=new Set,H=0;for(let F of V){Y.add(F.assistantIdx);for(let O of F.toolResultIdxs)Y.add(O)}for(let F of Y){let O=Q[F],T=typeof O.content==="string"?O.content:JSON.stringify(O.content);if(H+=T.length,O.tool_calls)H+=JSON.stringify(O.tool_calls).length}let D=[],b=!1;for(let F=0;F<Q.length;F++){if(Y.has(F)){if(!b)D.push({role:"system",content:`[${V.length} earlier tool interaction${V.length===1?"":"s"} snipped for brevity]`}),b=!0;continue}D.push(Q[F])}return{messages:D,snippedCount:V.length,estimatedTokensFreed:Math.floor(H/4)}}var U2=60000,A2=3;function ZZ(Q,$){if(!$)return null;if(Date.now()-$<U2)return null;let J=E0(Q,{keepRecentTurns:A2,minMessagesForSnip:15});if(J.snippedCount===0)return null;return J}class wQ{hasAttempted=!1;async tryReactiveCompact(Q,$){if(this.hasAttempted)return{success:!1,messages:Q};this.hasAttempted=!0;let Z=E0(Q,{keepRecentTurns:3,minMessagesForSnip:10}),J=Z.messages;try{let G=await D0.compact(J,{trigger:"auto",modelName:$.modelName,modelProvider:$.modelProvider,maxContextTokens:$.maxContextTokens,apiKey:$.apiKey,baseURL:$.baseURL,signal:$.signal,activeTask:$.activeTask,workspaceRoot:$.workspaceRoot,sessionId:$.sessionId});if(G.success)return{success:!0,messages:G.compactedMessages,usage:G.usage};if(Z.snippedCount>0)return{success:!0,messages:J};return{success:!1,messages:Q}}catch(G){if(H0(G))throw G;if(Z.snippedCount>0)return{success:!0,messages:J};return{success:!1,messages:Q}}}reset(){this.hasAttempted=!1}}import*as F0 from"fs";import*as NQ from"os";import*as v0 from"path";import{nanoid as GZ}from"nanoid";var y2=1e5,S2=2000,$Z=200000;class EQ{currentChars=0;track(Q){this.currentChars+=Q}remaining(){return Math.max(0,$Z-this.currentChars)}isExhausted(){return this.currentChars>=$Z}reset(){this.currentChars=0}}function WZ(Q,$,Z){let J=Z?.maxCharsPerResult??y2,G=Z?.previewChars??S2,W=Z?.messageBudget,z=typeof Q==="string"?Q:JSON.stringify(Q,null,2);if(z.length<=J)return M2(Q,z,$,G,W,Z);let V=Z?.outputDir??v0.join(NQ.homedir(),".blade","tool-results"),Y=`${$}-${GZ(8)}.txt`,H=v0.join(V,Y);try{F0.mkdirSync(V,{recursive:!0}),F0.writeFileSync(H,z,"utf-8")}catch{let F=z.slice(0,J)+`
|
|
108
108
|
|
|
109
|
-
... (truncated, ${z.length} total chars)`;if(W)W.track(
|
|
109
|
+
... (truncated, ${z.length} total chars)`;if(W)W.track(F.length);return F}let D=z.slice(0,G),b=`Result too large (${z.length} chars). Full output saved to: ${H}
|
|
110
110
|
|
|
111
111
|
Preview:
|
|
112
|
-
${
|
|
112
|
+
${D}
|
|
113
113
|
|
|
114
|
-
... (${z.length-G} more chars in file)`;if(W)W.track(b.length);return b}function
|
|
114
|
+
... (${z.length-G} more chars in file)`;if(W)W.track(b.length);return b}function M2(Q,$,Z,J,G,W){if(!G)return Q;let z=G.remaining();if(z<=0){let V=$.slice(0,J),Y=JZ($,V,Z,W,"[Message budget exhausted. Full output saved to disk.]");return G.track(typeof Y==="string"?Y.length:J),Y}if($.length>z){let V=Math.max(J,z),Y=$.slice(0,V),H=JZ($,Y,Z,W,`... (truncated by message budget, ${$.length} total chars)`);return G.track(typeof H==="string"?H.length:V),H}return G.track($.length),Q}function JZ(Q,$,Z,J,G){let W=J?.outputDir??v0.join(NQ.homedir(),".blade","tool-results"),z=`${Z}-${GZ(8)}.txt`,V=v0.join(W,z);try{return F0.mkdirSync(W,{recursive:!0}),F0.writeFileSync(V,Q,"utf-8"),`${$}
|
|
115
115
|
|
|
116
116
|
${G}
|
|
117
117
|
Full output saved to: ${V}`}catch{return`${$}
|
|
118
118
|
|
|
119
|
-
${G}`}}import*as
|
|
119
|
+
${G}`}}import*as i0 from"node:fs/promises";import{homedir as OZ}from"node:os";import*as s from"node:path";var g0={name:"skill-creator",description:"Create new Skills interactively. Use when the user wants to create a new Skill, define a custom workflow, or add a specialized capability to Blade.",allowedTools:["Read","Write","Glob","Bash","AskUserQuestion"],version:"1.0.0",argumentHint:void 0,userInvocable:!0,disableModelInvocation:!1,model:void 0,whenToUse:"User wants to create a new skill, define a custom workflow, or add a specialized capability.",path:"builtin://skill-creator",basePath:"",source:"builtin"};function zZ(){return{metadata:g0,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 d0={name:"update-config",description:"配置 Blade harness(settings/hooks/permissions)。"+"用户请求自动化行为时使用此 Skill。",allowedTools:["ConfigTool","Read","Bash","AskUserQuestion"],version:"1.0.0",userInvocable:!0,disableModelInvocation:!1,whenToUse:'用户说"从现在起..."、"每次..."、"当...时..."、'+"需要改配置、安装 hooks、修改权限",path:"builtin://update-config",basePath:"",source:"builtin"};function VZ(){return{metadata:d0,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 $=this.pluginSkills.get(Q);if($)return $;let Z=[];for(let J of this.pluginSkills.values())if(J.originalName===Q)Z.push(J);if(Z.length===1)return Z[0];return}getAllPluginSkills(){return Array.from(this.pluginSkills.values())}clearPluginSkills(){for(let Q of this.pluginSkills.values())this.skills.delete(Q.namespacedName);this.pluginSkills.clear()}getPluginSkillCount(){return this.pluginSkills.size}}function
|
|
575
|
+
`}}import{exec as P2}from"node:child_process";import*as _ from"node:fs/promises";import{homedir as f2}from"node:os";import*as f from"node:path";import{promisify as x2}from"node:util";var m0=x2(P2),P=i("General"),vQ={url:"https://github.com/anthropics/skills.git",branch:"main",defaultSkills:["skill-creator"]};class YZ{skillsDir;constructor(Q){this.skillsDir=Q||f.join(f2(),".blade","skills")}async isInstalled(Q){let $=f.join(this.skillsDir,Q,"SKILL.md");try{return await _.access($),!0}catch{return!1}}async isGitAvailable(){try{return await m0("git --version"),!0}catch{return!1}}async installOfficialSkill(Q){let{url:$,branch:Z}=vQ,J=f.join(this.skillsDir,Q),G=f.join(this.skillsDir,`.tmp-${Q}-${Date.now()}`);try{if(!await this.isGitAvailable())return P.warn("Git not available, skipping skill installation"),!1;P.info(`Installing official skill: ${Q}...`),await _.mkdir(this.skillsDir,{recursive:!0,mode:493}),await m0(`git clone --depth 1 --branch ${Z} --single-branch ${$} "${G}"`,{timeout:30000});let W=f.join(G,"skills",Q);try{await _.access(W)}catch{return P.warn(`Skill ${Q} not found in official repository`),await _.rm(G,{recursive:!0,force:!0}),!1}try{await _.rm(J,{recursive:!0,force:!0})}catch{}return await _.cp(W,J,{recursive:!0}),await _.rm(G,{recursive:!0,force:!0}),P.info(`Successfully installed: ${Q}`),!0}catch(W){try{await _.rm(G,{recursive:!0,force:!0})}catch{}return P.warn(`Failed to install ${Q}: ${W instanceof Error?W.message:"Unknown error"}`),!1}}async ensureDefaultSkillsInstalled(){await _.mkdir(this.skillsDir,{recursive:!0,mode:493});for(let Q of vQ.defaultSkills)if(!await this.isInstalled(Q))await this.installOfficialSkill(Q)}async installFromRepo(Q,$){let Z=$||this.extractRepoName(Q),J=f.join(this.skillsDir,Z),G=f.join(this.skillsDir,`.tmp-repo-${Z}-${Date.now()}`);try{if(!await this.isGitAvailable())return P.warn("Git not available, cannot install from repo"),!1;P.info(`Installing skill from repo: ${Q}...`),await _.mkdir(this.skillsDir,{recursive:!0,mode:493}),await m0(`git clone --depth 1 "${Q}" "${G}"`,{timeout:60000});let W=f.join(G,"SKILL.md");try{await _.access(W)}catch{return P.warn(`No SKILL.md found in repository ${Q}`),await _.rm(G,{recursive:!0,force:!0}),!1}await _.rm(J,{recursive:!0,force:!0}),await _.rename(G,J);try{await _.rm(f.join(J,".git"),{recursive:!0,force:!0})}catch{}return P.info(`Successfully installed skill from repo: ${Z}`),!0}catch(W){try{await _.rm(G,{recursive:!0,force:!0})}catch{}return P.warn(`Failed to install from repo ${Q}: ${W instanceof Error?W.message:"Unknown error"}`),!1}}async installFromLocal(Q,$,Z=!0){let J=$||f.basename(Q),G=f.join(this.skillsDir,J);try{let W=f.resolve(Q);try{await _.access(W)}catch{return P.warn(`Local path does not exist: ${W}`),!1}let z=f.join(W,"SKILL.md");try{await _.access(z)}catch{return P.warn(`No SKILL.md found in local path: ${W}`),!1}if(P.info(`Installing skill from local path: ${W}...`),await _.mkdir(this.skillsDir,{recursive:!0,mode:493}),await _.rm(G,{recursive:!0,force:!0}),Z)await _.symlink(W,G,"dir"),P.info(`Created symlink for skill: ${J}`);else await _.cp(W,G,{recursive:!0}),P.info(`Copied skill to: ${J}`);return!0}catch(W){return P.warn(`Failed to install from local path ${Q}: ${W instanceof Error?W.message:"Unknown error"}`),!1}}extractRepoName(Q){return Q.match(/\/([^/]+?)(\.git)?$/)?.[1]||"unknown-skill"}async installAllOfficialSkills(){let{url:Q,branch:$}=vQ,Z=f.join(this.skillsDir,`.tmp-all-${Date.now()}`),J=[],G=[];try{if(!await this.isGitAvailable())return P.warn("Git not available, skipping skill installation"),{installed:J,failed:G};await _.mkdir(this.skillsDir,{recursive:!0,mode:493}),P.info("Cloning official skills repository..."),await m0(`git clone --depth 1 --branch ${$} --single-branch ${Q} "${Z}"`,{timeout:60000});let W=f.join(Z,"skills"),z=await _.readdir(W,{withFileTypes:!0});for(let V of z){if(!V.isDirectory())continue;let Y=V.name,H=f.join(W,Y),D=f.join(this.skillsDir,Y);try{await _.access(f.join(H,"SKILL.md")),await _.rm(D,{recursive:!0,force:!0}),await _.cp(H,D,{recursive:!0}),P.info(`Installed: ${Y}`),J.push(Y)}catch(b){P.warn(`Failed to install ${Y}`),G.push(Y)}}await _.rm(Z,{recursive:!0,force:!0})}catch(W){try{await _.rm(Z,{recursive:!0,force:!0})}catch{}P.warn(`Failed to install skills: ${W instanceof Error?W.message:"Unknown error"}`)}return{installed:J,failed:G}}}var IQ=null;function XZ(Q){if(!IQ)IQ=new YZ(Q);return IQ}import*as I0 from"node:fs/promises";import*as c0 from"node:path";import{parse as h2}from"yaml";var T2=/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/,k2=/^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]?$/,HZ=1024;function R2(Q){if(!Q)return;if(typeof Q==="string")return Q.split(",").map(($)=>$.trim()).filter(Boolean);if(Array.isArray(Q))return Q.map(($)=>String($).trim()).filter(Boolean);return}function BZ(Q){if(Q===void 0)return;if(typeof Q==="boolean")return Q;if(typeof Q==="string"){let $=Q.toLowerCase().trim();if($==="true"||$==="yes"||$==="1")return!0;if($==="false"||$==="no"||$==="0")return!1}return}function C2(Q,$){if(!Q.name)return{valid:!1,error:"Missing required field: name"};if(!k2.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>HZ)return{valid:!1,error:`Description too long: ${Q.description.length} characters (max ${HZ})`};let Z;if(Q.model)Z=Q.model==="inherit"?"inherit":Q.model;return{valid:!0,metadata:{name:Q.name,description:Q.description.trim(),allowedTools:R2(Q["allowed-tools"]),version:Q.version,argumentHint:Q["argument-hint"]?.trim(),userInvocable:BZ(Q["user-invocable"]),disableModelInvocation:BZ(Q["disable-model-invocation"]),model:Z,whenToUse:Q.when_to_use?.trim()}}}function KZ(Q,$,Z){let J=Q.match(T2);if(!J)return{success:!1,error:"Invalid SKILL.md format: missing YAML frontmatter (must start with ---)"};let[,G,W]=J,z;try{z=h2(G)}catch(H){return{success:!1,error:`Failed to parse YAML frontmatter: ${H instanceof Error?H.message:String(H)}`}}let V=C2(z,$);if(!V.valid)return{success:!1,error:V.error};let Y=c0.dirname($);return{success:!0,content:{metadata:{...V.metadata,path:$,basePath:Y,source:Z},instructions:W.trim()}}}async function jZ(Q,$){try{let Z=await I0.readFile(Q,"utf-8");return KZ(Z,Q,$)}catch(Z){if(Z.code==="ENOENT")return{success:!1,error:`File not found: ${Q}`};return{success:!1,error:`Failed to read file: ${Z instanceof Error?Z.message:String(Z)}`}}}async function DZ(Q){try{let $=await I0.readFile(Q.path,"utf-8"),Z=KZ($,Q.path,Q.source);return Z.success?Z.content:null}catch{return null}}async function FZ(Q){try{return await I0.access(c0.join(Q,"SKILL.md")),!0}catch{return!1}}var p2={userSkillsDir:s.join(OZ(),".blade","skills"),projectSkillsDir:".blade/skills",claudeUserSkillsDir:s.join(OZ(),".claude","skills"),claudeProjectSkillsDir:".claude/skills"},u0=null;class UQ{skills=new Map;pluginSkills=new Map;config;initialized=!1;constructor(Q){this.config={...p2,cwd:c(),...Q}}static getInstance(Q){if(!u0)u0=new UQ(Q);return u0}static resetInstance(){u0=null}async initialize(){if(this.initialized)return{skills:Array.from(this.skills.values()),errors:[]};let Q=[],$=[];try{await XZ(this.config.userSkillsDir).ensureDefaultSkillsInstalled()}catch(Y){Q.push({path:"SkillInstaller",error:`Failed to install default skills: ${Y instanceof Error?Y.message:"Unknown error"}`})}this.loadBuiltinSkills();let Z=await this.scanDirectory(this.config.claudeUserSkillsDir,"user");$.push(...Z.skills),Q.push(...Z.errors);let J=await this.scanDirectory(this.config.userSkillsDir,"user");$.push(...J.skills),Q.push(...J.errors);let G=s.isAbsolute(this.config.claudeProjectSkillsDir)?this.config.claudeProjectSkillsDir:s.join(this.config.cwd,this.config.claudeProjectSkillsDir),W=await this.scanDirectory(G,"project");$.push(...W.skills),Q.push(...W.errors);let z=s.isAbsolute(this.config.projectSkillsDir)?this.config.projectSkillsDir:s.join(this.config.cwd,this.config.projectSkillsDir),V=await this.scanDirectory(z,"project");$.push(...V.skills),Q.push(...V.errors);for(let Y of $)this.skills.set(Y.name,Y);return this.initialized=!0,{skills:Array.from(this.skills.values()),errors:Q}}loadBuiltinSkills(){this.skills.set(g0.name,g0),this.skills.set(d0.name,d0)}async scanDirectory(Q,$){let Z=[],J=[];try{await i0.access(Q)}catch{return{skills:Z,errors:J}}try{let G=await i0.readdir(Q,{withFileTypes:!0});for(let W of G){if(!W.isDirectory())continue;let z=s.join(Q,W.name),V=s.join(z,"SKILL.md");if(!await FZ(z))continue;let Y=await jZ(V,$);if(Y.success&&Y.content)Z.push(Y.content.metadata);else J.push({path:V,error:Y.error||"Unknown error"})}}catch(G){J.push({path:Q,error:`Failed to scan directory: ${G instanceof Error?G.message:String(G)}`})}return{skills:Z,errors:J}}getAll(){return Array.from(this.skills.values())}get(Q){return this.skills.get(Q)}has(Q){return this.skills.has(Q)}async loadContent(Q){let $=this.skills.get(Q);if(!$)return null;if($.source==="builtin")return this.loadBuiltinContent(Q);return DZ($)}loadBuiltinContent(Q){switch(Q){case"skill-creator":return zZ();case"update-config":return VZ();default:return null}}getModelInvocableSkills(){return Array.from(this.skills.values()).filter((Q)=>!Q.disableModelInvocation)}getUserInvocableSkills(){return Array.from(this.skills.values()).filter((Q)=>Q.userInvocable===!0)}generateAvailableSkillsList(){let Q=this.getModelInvocableSkills();if(Q.length===0)return"";let $=[];for(let Z of Q){let J=Z.description.length>100?`${Z.description.substring(0,97)}...`:Z.description,G=Z.argumentHint?`${Z.name} ${Z.argumentHint}`:Z.name;$.push(`- ${G}: ${J}`)}return $.join(`
|
|
576
|
+
`)}get size(){return this.skills.size}async refresh(){return this.skills.clear(),this.pluginSkills.clear(),this.initialized=!1,this.initialize()}registerPluginSkill(Q){this.pluginSkills.set(Q.namespacedName,Q),this.skills.set(Q.namespacedName,Q.metadata)}findPluginSkill(Q){let $=this.pluginSkills.get(Q);if($)return $;let Z=[];for(let J of this.pluginSkills.values())if(J.originalName===Q)Z.push(J);if(Z.length===1)return Z[0];return}getAllPluginSkills(){return Array.from(this.pluginSkills.values())}clearPluginSkills(){for(let Q of this.pluginSkills.values())this.skills.delete(Q.namespacedName);this.pluginSkills.clear()}getPluginSkillCount(){return this.pluginSkills.size}}function n0(Q){return UQ.getInstance(Q)}async function g2(Q){return n0(Q).initialize()}var d2="Skill",m2=/<available_skills>\s*<\/available_skills>/;function AQ(Q){let Z=n0().generateAvailableSkillsList();if(!Z)return Q;return Q.map((J)=>{if(J.name!==d2)return J;let G=J.description.replace(m2,`<available_skills>
|
|
577
577
|
${Z}
|
|
578
|
-
</available_skills>`);if(G===J.description)return J;return{...J,description:G}})}function
|
|
579
|
-
`)}function
|
|
578
|
+
</available_skills>`);if(G===J.description)return J;return{...J,description:G}})}function LZ(){return{consecutiveFailures:new Map,totalFailures:0,lastFailedTool:null}}function bZ(Q,$){Q.consecutiveFailures.set($,0),Q.lastFailedTool=null}function qZ(Q,$){let Z=(Q.consecutiveFailures.get($)??0)+1;Q.consecutiveFailures.set($,Z),Q.totalFailures++,Q.lastFailedTool=$}function c2(Q,$){return(Q.consecutiveFailures.get($)??0)>=3}function _Z(Q,$){if(!c2(Q,$))return;let Z=Q.consecutiveFailures.get($)??0;return`WARNING: ${$} has failed ${Z} consecutive times. Consider a different approach: use a different tool, verify your parameters, or break the task into smaller steps.`}function wZ(Q){return Q>0&&Q%5===0}function NZ(Q,$){let Z=[`[Self-check at turn ${Q}]`,"Before continuing, briefly assess:","1. Are you making progress toward the goal?","2. Have any approaches failed repeatedly that you should abandon?","3. Is there a simpler path you haven't tried?"];if($>3)Z.push(`Note: ${$} tool failures so far. Consider whether your current strategy needs adjustment.`);return Z.join(`
|
|
579
|
+
`)}function EZ(){return{recentOutputHashes:[]}}function u2(Q){let $=Q.trim().slice(0,500),Z=0;for(let J=0;J<$.length;J++)Z=(Z<<5)-Z+$.charCodeAt(J)|0;return Z.toString(36)}function vZ(Q,$){let Z=u2($);if(Q.recentOutputHashes.push(Z),Q.recentOutputHashes.length>4)Q.recentOutputHashes.shift();if(Q.recentOutputHashes.length<3)return!1;let J=Q.recentOutputHashes.slice(-3),G=J.every((W)=>W===J[0]);if(G)Q.recentOutputHashes=[];return G}function IZ(){return"WARNING: You appear to be repeating the same output. Stop and try a fundamentally different approach. If the task cannot be completed, explain why and stop."}var J0=i("Agent"),n2=new Set(["Read","Glob","Grep","WebFetch","WebSearch","MemoryRead","GetSpecContext","ValidateSpec","TaskOutput"]);class l0{pipeline;execContext;registry;contextMgr;sessionId;lastMessageUuid;subagentInfo;pending=new Map;completed=new Map;queued=[];order=[];dispatched=new Set;abortController=new AbortController;epoch=0;activeAborts=new Map;executeTool;admitTool;rollbackAdmission;constructor(Q,$,Z,J,G,W,z){this.pipeline=Q;this.execContext=$;this.registry=Z;this.contextMgr=J;this.sessionId=G;this.lastMessageUuid=W;this.subagentInfo=z}setExecutionPolicy(Q){this.executeTool=Q}setAdmissionPolicy(Q){this.admitTool=Q}setAdmissionRollback(Q){this.rollbackAdmission=Q}addTool(Q,$){if(this.dispatched.has(Q.id))return J0.debug(`[StreamingToolExecutor] 跳过已分发工具: ${Q.function.name} (${Q.id})`),"rejected";this.dispatched.add(Q.id),this.order.push(Q.id);let Z=this.admitTool?.(Q.function.name,$);if(Z)return this.completed.set(Q.id,{toolCall:Q,result:Z,toolUseUuid:null}),"rejected";if(n2.has(Q.function.name)){J0.debug(`[StreamingToolExecutor] 立即执行预启动工具: ${Q.function.name}`);let G=this.executeOne(Q,$);return this.pending.set(Q.id,G),"prelaunched"}else return J0.debug(`[StreamingToolExecutor] 排队非预启动工具: ${Q.function.name}`),this.queued.push({toolCall:Q,params:$}),"queued"}getQueuedToolCalls(){return this.queued.map((Q)=>Q.toolCall)}async*getRemainingResults(){for(let Q of this.order){if(this.completed.has(Q)){yield this.completed.get(Q),this.completed.delete(Q);continue}if(this.pending.has(Q)){let Z=await this.pending.get(Q);this.pending.delete(Q),yield Z;continue}let $=this.queued.findIndex((Z)=>Z.toolCall.id===Q);if($!==-1){let{toolCall:Z,params:J}=this.queued[$];if(this.queued.splice($,1),this.execContext.signal?.aborted){J0.debug(`[StreamingToolExecutor] Signal aborted, 跳过排队工具: ${Z.function.name} (${Z.id})`),yield this.makeAbortResult(Z,"Tool execution skipped: task aborted before launch");continue}yield await this.executeOne(Z,J)}}}getCompletedResults(){let Q=Array.from(this.completed.values());return this.completed.clear(),Q}discard(){for(let Q of this.queued)this.rollbackAdmission?.(Q.toolCall.function.name);this.epoch++,this.abortController.abort(),this.abortController=new AbortController;for(let[,Q]of this.activeAborts)Q.abort();this.activeAborts.clear(),this.queued=[],this.order=[],this.dispatched.clear(),this.completed.clear(),this.pending.clear(),J0.debug(`[StreamingToolExecutor] 已丢弃所有挂起工作并重置状态 (epoch=${this.epoch})`)}hasTools(){return this.order.length>0}getEpoch(){return this.epoch}makeAbortResult(Q,$){return{toolCall:Q,result:{success:!1,llmContent:"",error:{type:"execution_error",message:$},metadata:{abortedBeforeLaunch:!0}},toolUseUuid:null}}async executeOne(Q,$){let Z=this.epoch,J=new AbortController;this.activeAborts.set(Q.id,J);let G=this.abortController.signal;try{if(G.aborted||J.signal.aborted)return this.makeAbortResult(Q,"Tool execution aborted due to discard");let W=null;try{if(this.contextMgr&&this.sessionId)W=await this.contextMgr.saveToolUse(this.sessionId,Q.function.name,$,this.lastMessageUuid??null,this.subagentInfo)}catch(F){J0.warn("[StreamingToolExecutor] 保存工具调用失败:",F)}let z=[G,J.signal],V=this.execContext.signal;if(V)z.push(V);let Y=UZ(...z),H={...this.execContext,messageId:W??Q.id,signal:Y},D=this.executeTool?await this.executeTool(Q.function.name,$,H):await this.pipeline.execute(Q.function.name,$,H);if(Z!==this.epoch)return J0.debug(`[StreamingToolExecutor] 丢弃旧世代工具结果: ${Q.function.name} (startEpoch=${Z}, currentEpoch=${this.epoch})`),this.makeAbortResult(Q,"Tool execution aborted due to epoch mismatch (discard)");let b={toolCall:Q,result:D,toolUseUuid:W};if(this.pending.has(Q.id))this.pending.delete(Q.id),this.completed.set(Q.id,b);return b}catch(W){if(Z!==this.epoch)return this.makeAbortResult(Q,"Tool execution aborted due to epoch mismatch (discard)");J0.error(`[StreamingToolExecutor] 工具执行失败: ${Q.function.name}`,W);let z={success:!1,llmContent:"",error:{type:"execution_error",message:W instanceof Error?W.message:"Unknown error"},metadata:void 0},V={toolCall:Q,result:z,toolUseUuid:null,error:W instanceof Error?W:Error("Unknown error")};if(this.pending.has(Q.id))this.pending.delete(Q.id),this.completed.set(Q.id,V);return V}finally{this.activeAborts.delete(Q.id)}}}var x=i("Agent"),l2=0.1,r2=8192,a2=32768,o2=2,s2=0.95,r0=yZ;function a0(Q,$){return{inputTokens:Q.promptTokens??0,outputTokens:Q.completionTokens??0,totalTokens:Q.totalTokens??0,maxContextTokens:$,cacheReadTokens:Q.cacheReadInputTokens??0,cacheWriteTokens:Q.cacheCreationInputTokens??0,costUsd:Q.costUsd}}var t2=`
|
|
580
580
|
|
|
581
581
|
# Task Execution Strategy
|
|
582
582
|
When facing complex multi-step tasks:
|
|
@@ -584,23 +584,23 @@ When facing complex multi-step tasks:
|
|
|
584
584
|
2. Execute one step at a time — verify each step succeeded before moving to the next.
|
|
585
585
|
3. If a step fails, diagnose the root cause rather than repeating the same approach.
|
|
586
586
|
4. When uncertain about file paths or project structure, use Grep/Glob/Read to gather facts first.
|
|
587
|
-
5. Prefer the smallest change that achieves the goal — avoid unnecessary refactoring.`;function
|
|
588
|
-
`)}function
|
|
587
|
+
5. Prefer the smallest change that achieves the goal — avoid unnecessary refactoring.`;function AZ(Q){let $=Q.trim();if($=$.replace(/,\s*([}\]])/g,"$1"),$.startsWith("{")&&!$.endsWith("}"))$+="}";$=$.replace(/,\s*([}\]])/g,"$1");try{let Z=JSON.parse($);if(typeof Z==="object"&&Z!==null&&!Array.isArray(Z))return Z;return null}catch{return null}}function yQ(Q){let $=AZ(Q);if($)return $;try{let Z=JSON.parse(Q);return typeof Z==="string"?AZ(Z):null}catch{return null}}function e2(Q){if(typeof Q==="string")return Q;try{return JSON.parse(JSON.stringify(Q))}catch{return String(Q)}}function Q7(Q){let $=new Set,Z=!1;for(let J of Q){if(J.role==="assistant"){if(J.tool_calls&&J.tool_calls.length>0){for(let W of J.tool_calls)if("function"in W&&W.function.name==="Task")$.add(W.id)}else if(Z)Z=!1;continue}if(J.role!=="tool"||J.name!=="Task"||!J.tool_call_id||!$.has(J.tool_call_id)||typeof J.metadata!=="object"||J.metadata===null||Array.isArray(J.metadata))continue;let G=J.metadata;if(G.toolCallId===J.tool_call_id&&G.toolName==="Task"&&G.error===null)Z=!0}return Z}function Z7(Q){if(!(Q instanceof Error))return"未知错误";let J=Q.lastError??Q;if(J.responseBody)try{let V=JSON.parse(J.responseBody)?.error?.message;if(V){let Y=J.statusCode?` (HTTP ${J.statusCode})`:"";return`${V}${Y}`}}catch{}let G=Q.message,W=G.match(/Last error:\s*(.+)$/);if(W)return W[1];return G}function $7(Q){if(!(Q instanceof Error))return!1;return["stream not supported","streaming is not available","sse not supported","does not support streaming"].some((Z)=>Q.message.toLowerCase().includes(Z.toLowerCase()))}function J7(Q,$){if(!$)return"Tool execution failed (no details).";let Z=[`Error: ${$.message||"Unknown error"}`];if($.type==="validation_error")Z.push("Hint: Check the tool parameters — a required field may be missing or have the wrong type.");else if($.type==="permission_denied")Z.push("Hint: This operation requires user approval. Try a different approach or ask the user.");else if($.type==="timeout_error")Z.push("Hint: The operation timed out. Consider breaking it into smaller steps or increasing timeout.");else if($.type==="execution_error"){let J=$.message??"";if(J.includes("ENOENT")||J.includes("no such file"))Z.push("Hint: File or directory not found. Use Glob or Grep to find the correct path first.");else if(J.includes("EACCES")||J.includes("permission"))Z.push("Hint: Permission denied. The file may be read-only or owned by another user.");else if(J.includes("not found in file")||J.includes("old_string"))Z.push(`Hint: The target text was not found. Use Read to view the current file content, then retry ${Q} with the exact text.`);else if(J.includes("ENOTDIR"))Z.push("Hint: A path component is not a directory. Verify the full path with Glob.")}return Z.join(`
|
|
588
|
+
`)}function G7(Q){if(!(Q instanceof Error))return!1;let $=Q.message.toLowerCase();return $.includes("prompt_too_long")||$.includes("prompt is too long")||$.includes("maximum context length")||$.includes("request too large")||Q.status===413}function W7(Q,$){let Z=$,J=Z.index??0;if(!Q.has(J))Q.set(J,{id:Z.id||"",name:Z.function?.name||"",arguments:""});let G=Q.get(J);if(Z.id&&!G.id)G.id=Z.id;if(Z.function?.name&&!G.name)G.name=Z.function.name;if(Z.function?.arguments)G.arguments+=Z.function.arguments}function z7(Q){if(Q.size===0)return;return Array.from(Q.values()).filter(($)=>$.id&&$.name).map(($)=>({id:$.id,type:"function",function:{name:$.name,arguments:$.arguments}}))}async function*V7(Q,$,Z,J,G,W){let z="",V="",Y,H,D=new Map;try{let b=Q.chatService.streamChat($,Z,J,G),F=0;for await(let O of b){if(F++,J?.aborted)break;if(O.modelFallback){W?.discard(),z="",V="",Y=void 0,H=void 0,D.clear(),F=0,yield{kind:"model_fallback"};continue}if(O.content)z+=O.content,yield{kind:"content_delta",delta:O.content};if(O.reasoningContent)V+=O.reasoningContent,yield{kind:"thinking_delta",delta:O.reasoningContent};if(O.usage)Y=O.usage;if(O.toolCalls){for(let T of O.toolCalls)if(W7(D,T),W){let v=T.index??0,E=D.get(v);if(E&&E.id&&E.name)try{let L=yQ(E.arguments);if(L===null)continue;let n={id:E.id,type:"function",function:{name:E.name,arguments:E.arguments}},S=Q.toolExecutor.getRegistry().get(E.name)?.kind;if(W.addTool(n,L)==="prelaunched")yield{kind:"tool_start",toolCall:n,toolKind:S}}catch{}}}if(O.finishReason){H=O.finishReason;break}}if(F===0&&!J?.aborted&&z.length===0&&D.size===0)return x.warn("[Loop] 流式响应返回0个chunk,回退到非流式模式"),W?.discard(),{...await Q.chatService.chat($,Z,J,G),_nonStreamingFallback:!0};return{content:z,reasoningContent:V||void 0,toolCalls:z7(D),usage:Y,finishReason:H}}catch(b){if($7(b))return x.warn("[Loop] 流式请求失败,降级到非流式模式"),W?.discard(),{...await Q.chatService.chat($,Z,J,G),_nonStreamingFallback:!0};throw b}}async function*PZ(Q,$,Z,J,G,W,z,V){if(J===void 0)return x.debug(`[Loop] [轮次 ${Z}] 压缩检查: 跳过(无历史 usage 数据)`),"none";let Y=ZZ($.messages,W);if(Y)$.messages=Y.messages,x.debug(`[Loop] [轮次 ${Z}] MicroCompact: 清理 ${Y.snippedCount} 轮旧工具结果(缓存已过期)`);let H=E0($.messages),D=!1;if(H.snippedCount>0)D=!0,x.debug(`[Loop] [轮次 ${Z}] Snip 压缩: 移除 ${H.snippedCount} 轮旧工具调用,释放约 ${H.estimatedTokensFreed} tokens`);let b=Q.chatService.getConfig(),F=b.model,O=b.maxContextTokens??0,T=b.maxOutputTokens??Q.config.maxOutputTokens??Math.min(Math.max(Math.floor(O*l2),r2),a2),R=O-T,v=Math.floor(R*0.8);if(x.debug(`[Loop] [轮次 ${Z}] 压缩检查:`,{promptTokens:J,maxContextTokens:O,maxOutputTokens:T,availableForInput:R,threshold:v,shouldCompact:J>=v}),J<v){if(D)$.messages=H.messages;return D?"snipped":"none"}let E=V?.lastCompactionTurn===void 0?void 0:Z-V.lastCompactionTurn,L=E!==void 0&&E<=o2,n=Math.floor(R*s2);if(L&&J<n){if(D)$.messages=H.messages;return x.debug(`[Loop] [轮次 ${Z}] 跳过连续 LLM 压缩,距离上次压缩 ${E} 轮`),D?"snipped":"none"}x.debug(Z===0?"[Loop] 触发自动压缩":`[Loop] [轮次 ${Z}] 触发循环内自动压缩`),yield{kind:"compaction",phase:"start"};try{let r=D?H.messages:$.messages,S=await D0.compact(r,{trigger:"auto",modelName:F,modelProvider:b.provider,maxContextTokens:O,apiKey:b.apiKey,baseURL:b.baseUrl,actualPreTokens:J,signal:G,activeTask:z,workspaceRoot:$.workspaceRoot||c(),sessionId:$.sessionId});if(S.usage)yield{kind:"token_usage",usage:a0(S.usage,O)};if($.messages=S.compactedMessages,V)V.lastCompactionTurn=Z;if(S.success)x.debug(`[Loop] [轮次 ${Z}] 压缩完成: ${S.preTokens} -> ${S.postTokens} tokens`);else x.warn(`[Loop] [轮次 ${Z}] 压缩使用降级策略: ${S.preTokens} -> ${S.postTokens} tokens`);return await k0(Q,$,S.summary,{trigger:"auto",preTokens:S.preTokens,postTokens:S.postTokens,filesIncluded:S.filesIncluded}),"compacted"}catch(r){if(H0(r))return x.debug(`[Loop] [轮次 ${Z}] 压缩被中止`),"none";if(D)$.messages=H.messages;return x.error(`[Loop] [轮次 ${Z}] 压缩失败,继续执行`,r),D?"snipped":"none"}finally{yield{kind:"compaction",phase:"end"}}}function Y7(Q,$,Z,J){let G=J?MZ(J):"user-cancel";return{success:!1,error:{type:"aborted",message:(G==="interrupt"?void 0:"任务已被用户中止")??"任务已中断"},metadata:{turnsCount:Q,toolCallsCount:$,duration:Date.now()-Z,abortReason:G}}}async function*X7(Q,$,Z,J,G){let W=Date.now(),z=0,V=[],Y=null,H=!1,D=(b,F,O)=>{return H=!0,Y7(b,F,W,O)};try{let b=Q.toolExecutor.getRegistry(),F=Z.permissionMode,O=b.getFunctionDeclarationsByMode(F);O=AQ(O);let T=Q.applySkillToolRestrictions(O),R=LZ(),v=EZ(),E=G;if(typeof b.getDeferredToolsListing==="function"){let N=b.getDeferredToolsListing();if(N&&E)E=`${E}
|
|
589
589
|
|
|
590
|
-
${
|
|
591
|
-
`)
|
|
592
|
-
`),
|
|
593
|
-
`);if(
|
|
594
|
-
`),
|
|
595
|
-
`),
|
|
590
|
+
${N}`}if(E)E+=t2;let L=new P0(Z,E),n=J?.pendingInputOnly===!0;if(!n){let N=J?.inputMessageId?{inboxMessageId:J.inputMessageId}:void 0,U=N??(J?.transientInput==="goal_continuation"?{transientGoalContinuation:!0}:void 0);if(L.appendUser({role:"user",content:$,metadata:U}),J?.transientInput!=="goal_continuation")Y=await o(Q,Z,$,null,N);if(J?.inputMessageId&&!Y)throw Error(`Failed to persist durable input before applying it: ${J.inputMessageId}`)}let r=Z.permissionMode==="yolo",S=!!Z.subagentInfo,t=Q.runtimeOptions.maxTurns??J?.maxTurns??Q.config.maxTurns??-1,o0=t>=0;if(t===0)return{success:!1,error:{type:"chat_disabled",message:"对话功能已被禁用 (maxTurns=0)"},metadata:{turnsCount:0,toolCallsCount:0,duration:0}};let C=t===-1?r0:Math.min(t,r0),a=0,s0,SQ,O0=0,t0=0,e0=0,QQ=0,L0,ZQ=0,$Q=new Set,m=new Set(Z.worktreeActive?["EnterWorktree"]:[]),l=typeof $==="string"?$:$.filter((N)=>N.type==="text").map((N)=>N.text).join(`
|
|
591
|
+
`),JQ=[l,Z.completionRequirements?.trim()].filter(Boolean).join(`
|
|
592
|
+
`),GQ=l.trim()?[l]:[],U0=[Q.runtimeOptions.appendSystemPrompt?.trim(),Z.completionRequirements?.trim(),...GQ].filter((N)=>Boolean(N)),A0=h0(l),WQ=!n,b0=Q7(Z.messages);if(b0)m.add("Task");let MQ=()=>x0(U0),fZ=()=>{let N="The exactly-once Task delegation has already been started. Do not call Task again; return the final answer after its result.";return{success:!1,llmContent:N,error:{type:"validation_error",message:N},metadata:{summary:"Blocked duplicate exactly-once Task delegation"}}},PQ=(N,U)=>{if(N!=="Task"||!MQ())return;if(b0)return fZ();b0=!0;return},xZ=(N)=>{if(N==="Task"&&MQ())b0=!1},fQ=async(N,U,q0)=>Q.toolExecutor.execute(N,U,q0),zQ=kQ({budget:Q.currentModelMaxContextTokens,isSubagent:S}),xQ=new wQ,hZ={},VQ=async(N)=>{for(let U of N){if(!L.getHistory().some((p)=>{let W0=p.metadata;return W0!==null&&typeof W0==="object"&&!Array.isArray(W0)&&W0.inboxMessageId===U.id})){let p=await o(Q,Z,U.content,Y,{inboxMessageId:U.id});if(!p)throw Error(`Failed to persist steering message before applying it: ${U.id}`);Y=p,L.appendUser({role:"user",content:U.content,metadata:{inboxMessageId:U.id}})}let G0=typeof U.content==="string"?U.content:U.content.filter((p)=>p.type==="text").map((p)=>p.text).join(`
|
|
593
|
+
`);if(G0.trim())l=[l,G0].join(`
|
|
594
|
+
`),GQ.push(G0),JQ=[l,Z.completionRequirements?.trim()].filter(Boolean).join(`
|
|
595
|
+
`),U0=[Q.runtimeOptions.appendSystemPrompt?.trim(),Z.completionRequirements?.trim(),...GQ].filter((p)=>Boolean(p)),A0=A0||h0(G0)}return{messageIds:N.map((U)=>U.id),count:N.length,recovered:N.filter((U)=>U.recovered).length}};try{while(!0){if(J?.signal?.aborted)return D(z,V.length,J.signal);let N=await J?.turnSteering?.drain()??[];if(N.length>0)yield{kind:"steering_applied",...await VQ(N),delivery:WQ?"current_turn":"next_turn"},WQ=!0;else if(!WQ)return{success:!0,finalMessage:"",metadata:{turnsCount:0,toolCallsCount:0,duration:Date.now()-W}};if(L.writeback(),(yield*PZ(Q,Z,z,s0,J?.signal,SQ,l,hZ))!=="none")L.replaceHistory(Z.messages);if(z++,xQ.reset(),yield{kind:"turn_start",turn:z,maxTurns:C},J?.signal?.aborted)return D(z-1,V.length,J.signal);if(wZ(z)&&z>1){let w=NZ(z,R.totalFailures);L.appendControl("user",{role:"user",content:`
|
|
596
596
|
|
|
597
597
|
<system-reminder>
|
|
598
598
|
${w}
|
|
599
|
-
</system-reminder>`})}let
|
|
599
|
+
</system-reminder>`})}let q0=J?.stream!==!1,G0=b0&&x0(U0)?T.filter((w)=>w.name!=="Task"):T,p=L0;L0=void 0;let W0=p?G0.filter((w)=>w.name===p):G0,hQ=p?{toolChoice:{type:"tool",toolName:p}}:void 0,X,e;try{if(q0)e=new l0(Q.toolExecutor,{sessionId:Z.sessionId,userId:Z.userId||"default",modelId:Q.config.currentModelId,workspaceRoot:Z.workspaceRoot||c(),worktreeIsolationRequired:A0,worktreeActive:m.has("EnterWorktree")&&!m.has("ExitWorktree"),signal:J?.signal,confirmationHandler:Z.confirmationHandler,permissionMode:Z.permissionMode,toolRegistry:b,deferredToolManager:b.deferredToolManager},Q.toolExecutor.getRegistry(),Q.executionEngine?.getContextManager(),Z.sessionId,Y,Z.subagentInfo),e.setAdmissionPolicy(PQ),e.setAdmissionRollback(xZ),e.setExecutionPolicy(fQ),X=yield*V7(Q,L.toLLMMessages(),W0,J?.signal,hQ,e);else X=await Q.chatService.chat(L.toLLMMessages(),W0,J?.signal,hQ)}catch(w){if(G7(w)){x.warn("[Loop] 检测到 prompt_too_long 错误,尝试反应式压缩");let K=Q.chatService.getConfig(),j=await xQ.tryReactiveCompact(Z.messages,{modelName:K.model,modelProvider:K.provider,maxContextTokens:K.maxContextTokens??0,apiKey:K.apiKey,baseURL:K.baseUrl,signal:J?.signal,activeTask:l,workspaceRoot:Z.workspaceRoot||c(),sessionId:Z.sessionId});if(j.success){if(j.usage)yield{kind:"token_usage",usage:a0(j.usage,K.maxContextTokens??0)};Z.messages=j.messages,L.replaceHistory(Z.messages),L0=p,x.info("[Loop] 反应式压缩成功,重试 LLM 调用"),z--;continue}}throw w}if(SQ=Date.now(),X.usage){if(X.usage.totalTokens)a+=X.usage.totalTokens;s0=X.usage.promptTokens,yield{kind:"token_usage",usage:a0(X.usage,Q.currentModelMaxContextTokens)}}let TZ=X.usage?.completionTokens??0;if(zQ=RQ(zQ,TZ,O0>0),J?.signal?.aborted)return D(z-1,V.length,J.signal);if(!q0||!!X._nonStreamingFallback){if(X.reasoningContent&&X.reasoningContent.trim())yield{kind:"thinking_delta",delta:X.reasoningContent};if(X.content&&X.content.trim())yield{kind:"content_delta",delta:X.content}}yield{kind:"stream_end"};let YQ=jQ(X.finishReason,O0,zQ);if(YQ.action==="recover"){O0++,x.warn(`[Loop] Max output tokens hit (recovery ${O0}/3)`);let w={role:"assistant",content:X.content||"",reasoningContent:X.reasoningContent,tool_calls:X.toolCalls};L.appendToHistory(w);let K=await d(Q,Z,X.content||"",Y);if(K)Y=K;let j={role:"user",content:"Output token limit hit. Resume directly — no apology, no recap. "+"Pick up mid-thought if that is where the cut happened. Break remaining work into smaller pieces."};L.appendToHistory(j);let B=await o(Q,Z,j.content,Y);if(B)Y=B;continue}if(YQ.action==="truncated"||YQ.action==="budget_stop"){L.appendAssistant({role:"assistant",content:X.content||"",reasoningContent:X.reasoningContent,tool_calls:X.toolCalls});let w=await d(Q,Z,X.content||"",Y);if(w)Y=w;return{success:!0,finalMessage:X.content,metadata:{turnsCount:z,toolCallsCount:V.length,duration:Date.now()-W,tokensUsed:a,outputTruncated:!0}}}if(X.finishReason!=="length")O0=0;if(!X.toolCalls||X.toolCalls.length===0){let w=await J?.turnSteering?.drain()??[];if(w.length>0){L.appendAssistant({role:"assistant",content:X.content||"",reasoningContent:X.reasoningContent});let q=await d(Q,Z,X.content||"",Y);if(q)Y=q;yield{kind:"steering_applied",...await VQ(w),delivery:"current_turn"};continue}if(X.content&&vZ(v,X.content)){L.appendAssistant({role:"assistant",content:X.content||"",reasoningContent:X.reasoningContent}),L.appendControl("user",{role:"user",content:`
|
|
600
600
|
|
|
601
601
|
<system-reminder>
|
|
602
|
-
${
|
|
603
|
-
</system-reminder>`});continue}let
|
|
602
|
+
${IZ()}
|
|
603
|
+
</system-reminder>`});continue}let K=DQ(X.content,t0,!1);if(K.action==="retry"){t0++,L.appendAssistant({role:"assistant",content:X.content||"",reasoningContent:X.reasoningContent});let q=await d(Q,Z,X.content||"",Y);if(q)Y=q;let u={role:"user",content:K.prompt};L.appendControl("user",u);let g=await o(Q,Z,u.content,Y);if(g)Y=g;continue}t0=0;let j=mQ(U0,m,e0);if(j.action==="retry"){e0++,L0="Task",L.appendAssistant({role:"assistant",content:X.content||"",reasoningContent:X.reasoningContent});let q=await d(Q,Z,X.content||"",Y);if(q)Y=q;let u={role:"user",content:j.prompt};L.appendControl("user",u);let g=await o(Q,Z,u.content,Y);if(g)Y=g;continue}if(j.action==="fail"){L.appendAssistant({role:"assistant",content:X.content||"",reasoningContent:X.reasoningContent});let q=await d(Q,Z,X.content||"",Y);if(q)Y=q;return{success:!1,error:{type:"delegation_protocol_failed",message:j.message},metadata:{turnsCount:z,toolCallsCount:V.length,duration:Date.now()-W,tokensUsed:a}}}e0=0;let B=cQ(l,m,ZQ);if(B.action==="retry"){ZQ++,L.appendAssistant({role:"assistant",content:X.content||"",reasoningContent:X.reasoningContent});let q=await d(Q,Z,X.content||"",Y);if(q)Y=q;let u={role:"user",content:B.prompt};L.appendControl("user",u);let g=await o(Q,Z,u.content,Y);if(g)Y=g;continue}if(B.action==="fail"){L.appendAssistant({role:"assistant",content:X.content||"",reasoningContent:X.reasoningContent});let q=await d(Q,Z,X.content||"",Y);if(q)Y=q;return{success:!1,error:{type:"worktree_protocol_failed",message:B.message},metadata:{turnsCount:z,toolCallsCount:V.length,duration:Date.now()-W,tokensUsed:a}}}ZQ=0;let M=FQ(JQ,$Q,QQ);if(M.action==="retry"){QQ++,L0="Bash",L.appendAssistant({role:"assistant",content:X.content||"",reasoningContent:X.reasoningContent});let q=await d(Q,Z,X.content||"",Y);if(q)Y=q;let u={role:"user",content:M.prompt};L.appendControl("user",u);let g=await o(Q,Z,u.content,Y);if(g)Y=g;continue}if(M.action==="fail"){L.appendAssistant({role:"assistant",content:X.content||"",reasoningContent:X.reasoningContent});let q=await d(Q,Z,X.content||"",Y);if(q)Y=q;return{success:!1,error:{type:"verification_failed",message:M.message},metadata:{turnsCount:z,toolCallsCount:V.length,duration:Date.now()-W,tokensUsed:a}}}QQ=0;let y=await OQ({sessionId:Z.sessionId,permissionMode:Z.permissionMode,reason:X.content,abortSignal:J?.signal});if(y.action==="continue"){L.appendAssistant({role:"assistant",content:X.content||"",reasoningContent:X.reasoningContent});let q=await d(Q,Z,X.content||"",Y);if(q)Y=q;let g={role:"user",content:y.reason?`
|
|
604
604
|
|
|
605
605
|
<system-reminder>
|
|
606
606
|
${y.reason}
|
|
@@ -608,8 +608,8 @@ ${y.reason}
|
|
|
608
608
|
|
|
609
609
|
<system-reminder>
|
|
610
610
|
Please continue the conversation from where we left it off without asking the user any further questions. Continue with the last task that you were asked to work on.
|
|
611
|
-
</system-reminder>`};
|
|
611
|
+
</system-reminder>`};L.appendControl("user",g);let _0=await o(Q,Z,g.content,Y);if(_0)Y=_0;continue}let Q0=await J?.turnSteering?.drainOrSeal();if(Q0&&Q0.messages.length>0){L.appendAssistant({role:"assistant",content:X.content||"",reasoningContent:X.reasoningContent});let q=await d(Q,Z,X.content||"",Y);if(q)Y=q;yield{kind:"steering_applied",...await VQ(Q0.messages),delivery:"current_turn"};continue}L.appendAssistant({role:"assistant",content:X.content||"",reasoningContent:X.reasoningContent});let I=await d(Q,Z,X.content||"",Y);if(I)Y=I;return{success:!0,finalMessage:X.content,metadata:{turnsCount:z,toolCallsCount:V.length,duration:Date.now()-W,tokensUsed:a,toolSuccessRate:V.length>0?V.filter((q)=>q.success).length/V.length:void 0,totalToolFailures:R.totalFailures||void 0}}}L.appendAssistant({role:"assistant",content:X.content||"",reasoningContent:X.reasoningContent,tool_calls:X.toolCalls});{let w=await d(Q,Z,X.content||"",Y);if(w)Y=w}if(J?.signal?.aborted)return D(z,V.length,J.signal);let XQ=X.toolCalls.filter((w)=>w.type==="function"),y0;if(e?.hasTools()){x.debug(`[Loop] 使用 StreamingToolExecutor 收集 ${XQ.length} 个工具结果`),y0=[];for(let w of e.getQueuedToolCalls()){let j=b.get(w.function.name)?.kind;yield{kind:"tool_start",toolCall:w,toolKind:j}}for await(let w of e.getRemainingResults())y0.push(w)}else{let w=new Map;for(let j of XQ){let B=yQ(j.function.arguments),M=B===null?void 0:PQ(j.function.name,B);if(M){w.set(j.id,M);continue}let Q0=b.get(j.function.name)?.kind;yield{kind:"tool_start",toolCall:j,toolKind:Q0}}let K=async(j)=>{try{let B=w.get(j.id);if(B)return{toolCall:j,result:B,toolUseUuid:null};let M=yQ(j.function.arguments);if(M===null)return{toolCall:j,result:{success:!1,llmContent:"",error:{type:"validation_error",message:`Invalid JSON object in tool arguments. Raw: ${j.function.arguments.slice(0,200)}`},metadata:void 0},toolUseUuid:null};if(j.function.name==="Task"&&(typeof M.subagent_session_id!=="string"||M.subagent_session_id.length===0))M.subagent_session_id=SZ("agent");let y=null;if(y=await bQ(Q,Z,j.function.name,M,Y),j.function.name==="ExitWorktree"&&m.has("EnterWorktree")&&!m.has("ExitWorktree")&&FQ(JQ,$Q,0).action!=="none"){let q="Run the requested verification before ExitWorktree. The worktree remains active so Bash can run in isolation.";return{toolCall:j,result:{success:!1,llmContent:q,error:{type:"validation_error",message:q},metadata:{summary:"Blocked ExitWorktree until verification succeeds"}},toolUseUuid:y}}let I=await fQ(j.function.name,M,{sessionId:Z.sessionId,userId:Z.userId||"default",modelId:Q.config.currentModelId,workspaceRoot:Z.workspaceRoot||c(),worktreeIsolationRequired:A0,worktreeActive:m.has("EnterWorktree")&&!m.has("ExitWorktree"),signal:J?.signal,confirmationHandler:Z.confirmationHandler,permissionMode:Z.permissionMode,toolRegistry:b,deferredToolManager:b.deferredToolManager});return{toolCall:j,result:I,toolUseUuid:y}}catch(B){return x.error(`Tool execution failed for ${j.function.name}:`,B),{toolCall:j,result:{success:!1,llmContent:"",error:{type:"execution_error",message:B instanceof Error?B.message:"Unknown error"},metadata:void 0},toolUseUuid:null,error:B instanceof Error?B:Error("Unknown error")}}};y0=await Promise.all(XQ.map(K))}let kZ=new EQ;for(let{toolCall:w,result:K,toolUseUuid:j}of y0){let B=w;if(V.push(K),K.metadata?.abortedBeforeLaunch){let I=K.error?.message??"任务已被用户中止";if(j){let q=await T0(Q,Z,j,B.function.name,null,j,I);if(q)Y=q}return L.appendToolResult({role:"tool",tool_call_id:B.id,name:B.function.name,content:`Error: ${I}`}),D(z,V.length,J?.signal)}yield{kind:"tool_result",toolCall:B,result:K};{let I=K.metadata&&typeof K.metadata==="object"?K.metadata:void 0,u=((S0)=>S0==="running"||S0==="completed"||S0==="failed"||S0==="cancelled")(I?.subagentStatus)?I.subagentStatus:"completed",g=I&&typeof I.subagentSessionId==="string"?{subagentSessionId:I.subagentSessionId,subagentType:typeof I.subagentType==="string"?I.subagentType:B.function.name,subagentStatus:u,subagentSummary:typeof I.subagentSummary==="string"?I.subagentSummary:void 0,subagentResumedFrom:typeof I.subagentResumedFrom==="string"?I.subagentResumedFrom:void 0,subagentRootId:typeof I.subagentRootId==="string"?I.subagentRootId:void 0,subagentResumeDepth:typeof I.subagentResumeDepth==="number"?I.subagentResumeDepth:void 0}:void 0,_0=await T0(Q,Z,j??B.id,B.function.name,K.success?e2(K.llmContent):null,j,K.success?void 0:K.error?.message,g);if(_0)Y=_0}let M=await qQ(B,K,Q,Z);if(M)yield M;if(K.success){if(bZ(R,B.function.name),B.function.name==="EnterWorktree"&&K.metadata?.workspaceTransition==="enter")m.add("EnterWorktree"),m.delete("ExitWorktree");else if(B.function.name==="ExitWorktree"&&K.metadata?.workspaceTransition==="exit"&&m.has("EnterWorktree"))m.add("ExitWorktree");else if(!["EnterWorktree","ExitWorktree"].includes(B.function.name))m.add(B.function.name);if(B.function.name==="Task"&&K.metadata?.isolation==="worktree")m.add("TaskWorktree");dQ($Q,B.function.name,K)}else qZ(R,B.function.name);let y=K.success?K.llmContent||"":J7(B.function.name,K.error);if(!K.success){let I=_Z(R,B.function.name);if(I&&typeof y==="string")y=`${y}
|
|
612
612
|
|
|
613
|
-
${I}`}if(typeof y==="object"&&y!==null)y=JSON.stringify(y,null,2);if(typeof y==="string")y=
|
|
613
|
+
${I}`}if(typeof y==="object"&&y!==null)y=JSON.stringify(y,null,2);if(typeof y==="string")y=WZ(y,B.function.name,{messageBudget:kZ});let Q0=typeof y==="string"?y:JSON.stringify(y);if(L.appendToolResult({role:"tool",tool_call_id:B.id,name:B.function.name,content:Q0,...B.function.name==="Task"?{metadata:{toolCallId:B.id,toolName:B.function.name,error:K.success?null:K.error?.message??null}}:{}}),K.metadata?.shouldExitLoop){let I=typeof K.llmContent==="string"?K.llmContent:"循环已退出";return{success:K.success,finalMessage:I,metadata:{turnsCount:z,toolCallsCount:V.length,duration:Date.now()-W,shouldExitLoop:!0,targetMode:K.metadata?.targetMode,planContent:typeof K.metadata?.planContent==="string"?K.metadata.planContent:void 0}}}}if(J?.signal?.aborted)return D(z,V.length,J.signal);let HQ=z>=r0,RZ=z>=C&&(o0||!r||S);if(HQ||RZ){let w=HQ?r0:C;if(x.info(`Warning: 达到轮次上限 ${w} 轮`),J?.onTurnLimitReached){let K=await J.onTurnLimitReached({turnsCount:z});if(K?.continue){L.writeback();try{let j=Q.chatService.getConfig(),B=await D0.compact(Z.messages,{trigger:"auto",modelName:j.model,modelProvider:j.provider,maxContextTokens:j.maxContextTokens??0,apiKey:j.apiKey,baseURL:j.baseUrl,actualPreTokens:s0,signal:J?.signal,activeTask:l,workspaceRoot:Z.workspaceRoot||c(),sessionId:Z.sessionId});if(B.usage)yield{kind:"token_usage",usage:a0(B.usage,j.maxContextTokens??0)};Z.messages=B.compactedMessages,L.replaceHistory(Z.messages);let M={role:"user",content:`This session is being continued from a previous conversation. The conversation is summarized above.
|
|
614
614
|
|
|
615
|
-
Please continue the conversation from where we left it off without asking the user any further questions. Continue with the last task that you were asked to work on.`};
|
|
615
|
+
Please continue the conversation from where we left it off without asking the user any further questions. Continue with the last task that you were asked to work on.`};L.appendToHistory(M),await k0(Q,Z,B.summary,{trigger:"auto",preTokens:B.preTokens,postTokens:B.postTokens,filesIncluded:B.filesIncluded})}catch(j){x.error("[Loop] 压缩失败,使用降级策略:",j);let M=L.getHistory().slice(-80);L.replaceHistory(M)}z=0;continue}return{success:!0,finalMessage:K?.reason||"已达到对话轮次上限,用户选择停止",metadata:{turnsCount:z,toolCallsCount:V.length,duration:Date.now()-W,tokensUsed:a}}}return{success:!1,error:{type:"max_turns_exceeded",message:S?`子代理已达到轮次上限 (${w} 轮)。`:`已达到${HQ?"安全":"显式"}轮次上限 (${w} 轮)。`},metadata:{turnsCount:z,toolCallsCount:V.length,duration:Date.now()-W,tokensUsed:a}}}}}finally{if(J?.transientInput==="goal_continuation")L.removeMessages((N)=>{let U=N.metadata;return U!==null&&typeof U==="object"&&!Array.isArray(U)&&U.transientGoalContinuation===!0});L.writeback()}}catch(b){if(H0(b))return D(z,V.length,J?.signal);let F=Z7(b);return x.error(`API 调用失败: ${F}`),{success:!1,error:{type:"api_error",message:F,details:b},metadata:{turnsCount:z,toolCallsCount:V.length,duration:Date.now()-W}}}finally{if(H)Z.messages.push({role:"system",content:LQ}),await uQ(Q,Z,Y)}}export{_Q as Pa,XZ as Qa,jZ as Ra,n0 as Sa,g2 as Ta,X0 as Ua,Z0 as Va,jQ as Wa,DQ as Xa,dQ as Ya,OQ as Za,M0 as _a,P0 as $a,CZ as ab,o as bb,d as cb,bQ as db,T0 as eb,k0 as fb,iQ as gb,nQ as hb,lQ as ib,qQ as jb,N0 as kb,D0 as lb,l0 as mb,PZ as nb,X7 as ob};
|