blade-code 0.7.7 → 0.7.8
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-60se4kxq.js → chunk-0e0z8yc1.js} +2 -2
- package/dist/{chunk-x466sb8s.js → chunk-1w6tqkxd.js} +2 -2
- package/dist/{chunk-8e0rv3j5.js → chunk-2049tv49.js} +3 -3
- package/dist/chunk-4745ktjj.js +1570 -0
- package/dist/{chunk-54vk4tw8.js → chunk-48q9msfk.js} +43 -43
- package/dist/{chunk-v61bja34.js → chunk-4dmdn3a9.js} +1 -1
- package/dist/{chunk-4n7fsts0.js → chunk-5be6qr2v.js} +1 -1
- package/dist/chunk-67vzgcs5.js +2 -0
- package/dist/{chunk-2j3tb2dm.js → chunk-6811kbxn.js} +1 -1
- package/dist/{chunk-p7rf3zp8.js → chunk-6hn2jgw5.js} +1 -1
- package/dist/chunk-6js5wp6t.js +1 -0
- package/dist/{chunk-0y895nft.js → chunk-6kp3z956.js} +2 -2
- package/dist/{chunk-7e5hzpmp.js → chunk-71n472hj.js} +1 -1
- package/dist/chunk-78txnq4n.js +151 -0
- package/dist/{chunk-x24ddbhs.js → chunk-7r1hm0qz.js} +1 -1
- package/dist/{chunk-6087cgst.js → chunk-9kejtkey.js} +1 -1
- package/dist/{chunk-h79044h0.js → chunk-a7yjnqhd.js} +2 -2
- package/dist/chunk-bwaqaktn.js +1 -0
- package/dist/chunk-cb82rf5h.js +1 -0
- package/dist/chunk-ce11m8bq.js +1 -0
- package/dist/{chunk-2qckpa16.js → chunk-cjmxggke.js} +1 -1
- package/dist/chunk-e4rhdg3h.js +1 -0
- package/dist/{chunk-zet4zjc3.js → chunk-f9ybv4ph.js} +1 -1
- package/dist/{chunk-89j9pm90.js → chunk-faq7ay4j.js} +2 -2
- package/dist/{chunk-w1m1ehs1.js → chunk-fb7amc2s.js} +1 -1
- package/dist/{chunk-c6rtexw1.js → chunk-g6ted982.js} +1 -1
- package/dist/{chunk-9ad7tt9s.js → chunk-g7caymjr.js} +1 -1
- package/dist/{chunk-6y58y4rx.js → chunk-jm2xhnrv.js} +1 -1
- package/dist/chunk-ky8ctbdc.js +1 -0
- package/dist/chunk-mpskff34.js +1 -0
- package/dist/{chunk-6cry51vb.js → chunk-pd1yqxcv.js} +5 -5
- package/dist/{chunk-d61d6m07.js → chunk-phhmmybg.js} +2 -2
- package/dist/{chunk-ebcmqx1k.js → chunk-qnevwq1q.js} +1 -1
- package/dist/{chunk-778h8815.js → chunk-r1spf93b.js} +2 -2
- package/dist/{chunk-0b3m5qn6.js → chunk-rnfd5ebv.js} +1 -1
- package/dist/{chunk-yyw9bbfd.js → chunk-s4mke0t6.js} +1 -1
- package/dist/{chunk-5xjj88wd.js → chunk-t2spryz0.js} +1 -1
- package/dist/{chunk-2n8a87ds.js → chunk-t70aqrm4.js} +1 -1
- package/dist/{chunk-ptt8s7nd.js → chunk-z4c68ve0.js} +1 -1
- package/dist/chunk-z9zbcenc.js +6 -0
- package/dist/web/assets/{FilePreview-B2anY2d1.js → FilePreview-DRKRs8i2.js} +1 -1
- package/dist/web/assets/{MarkdownRenderer-BVfRG88x.js → MarkdownRenderer-DFqPpAnM.js} +1 -1
- package/dist/web/assets/{McpModal-BVvb-dzr.js → McpModal-CX5-hlNv.js} +1 -1
- package/dist/web/assets/{SettingsModal-aseVv-gp.js → SettingsModal-CfR_q6N7.js} +1 -1
- package/dist/web/assets/{SettingsStore-B87y64B4.js → SettingsStore-jup_Kikq.js} +1 -1
- package/dist/web/assets/{SkillsModal-BXYaF2KK.js → SkillsModal-DaAUrwXO.js} +1 -1
- package/dist/web/assets/{TerminalPanel-B-NRhOXN.js → TerminalPanel-DzlllDH7.js} +1 -1
- package/dist/web/assets/index-BJTSF3fc.js +9 -0
- package/dist/web/assets/index-CL6apjgo.css +1 -0
- package/dist/web/index.html +2 -2
- package/package.json +1 -1
- package/dist/chunk-3fcze972.js +0 -1
- package/dist/chunk-8p98nt9v.js +0 -151
- package/dist/chunk-94vj1hjp.js +0 -1
- package/dist/chunk-c8cxeve8.js +0 -1
- package/dist/chunk-gsn659hw.js +0 -1
- package/dist/chunk-kppxkh33.js +0 -1
- package/dist/chunk-qnh7np1s.js +0 -6
- package/dist/chunk-ran4gsmy.js +0 -1
- package/dist/chunk-swyvd7hd.js +0 -1
- package/dist/chunk-t9zdypqp.js +0 -2
- package/dist/chunk-x1khkevy.js +0 -1563
- package/dist/web/assets/index-9kl44E8k.js +0 -9
- package/dist/web/assets/index-CUVe9dGs.css +0 -1
|
@@ -1,23 +1,23 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{ub as x0}from"./chunk-2049tv49.js";import{vb as yZ}from"./chunk-t70aqrm4.js";import{Bb as c,Cb as AZ}from"./chunk-4dmdn3a9.js";import{Ib as SZ,Jb as X0,Kb as IZ,Lb as eQ}from"./chunk-6kp3z956.js";import{Nb as aQ,Zb as i}from"./chunk-a7yjnqhd.js";function P0(Q){return Q.role==="system"&&Array.isArray(Q.content)}class f0{systemMessages;_history;_pending=[];context;constructor(Q,$){this.context=Q;let Z=Q.messages.find(P0);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)=>!P0(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(($)=>!P0($))}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 RZ(Q,$){let Z;while(!(Z=await Q.next()).done)if($)await $(Z.value);return Z.value}function hQ(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 TQ(Q){return{budget:Q.budget,usage:0,consecutiveContinuations:0,lastOutputDelta:0,isSubagent:Q.isSubagent??!1}}function kQ(Q,$,Z){return{...Q,usage:Q.usage+$,lastOutputDelta:$,consecutiveContinuations:Z?Q.consecutiveContinuations+1:0}}var HQ=i("Agent"),CZ=3;function KQ(Q,$,Z){if(Q!=="length")return{action:"none"};if($>=CZ)return{action:"truncated"};if(hQ(Z)==="stop")return HQ.info("[Loop] Token budget: diminishing returns detected, skipping recovery"),{action:"budget_stop"};return{action:"recover"}}var pZ=[/:\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],gZ=/```[\s\S]{50,}```/,RQ="请执行你提到的操作,不要只是描述。使用 Edit/Write/Bash 工具来实际修改文件。",dZ=2;function jQ(Q,$,Z=!0){if(!Q||$>=dZ)return{action:"none"};if(!Z&&gZ.test(Q))return{action:"retry",prompt:RQ};let J=Q.slice(-200),G=J.match(/```/g);if(G&&G.length%2!==0)return{action:"none"};if(pZ.some((z)=>z.test(J)))return{action:"retry",prompt:RQ};return{action:"none"}}var mZ=[/\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}(?:测试|单测|集成测试|检查|构建)/],cZ=/(?:^|\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,CQ={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},uZ={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},iZ="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.",lZ=3;function BQ(Q){return cZ.test(Q)}function gQ(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&&BQ(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"&&BQ(G))Q.add(G)}function DQ(Q,$,Z){if(!Q||!mZ.some((Y)=>Y.test(Q)))return{action:"none"};let J=Object.keys(CQ).filter((Y)=>CQ[Y].test(Q)),G=[...$],W=J.filter((Y)=>!G.some((H)=>uZ[Y].test(H)));if(J.length>0?W.length===0:G.some(BQ))return{action:"none"};if(Z>=lZ)return{action:"fail",message:nZ};let V=J.length>1&&W.length>0?` Missing successful verification categories: ${W.join(", ")}.`:"";return{action:"retry",prompt:`${iZ}${V}`}}var rZ=[/\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|子代理|子智能体)/],aZ=[/\b(?:do not|don't|never)\s+(?:delegate|call|use|invoke)\b/i,/(?:不要|禁止|无需)(?:委派|调用|使用).{0,20}(?:Task|子代理|子智能体)?/],oZ=[/\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|子代理)/],sZ=[/\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 tZ(Q){if(typeof Q!=="string")return;if(sZ.some(($)=>$.test(Q)))return"multiple-allowed";return oZ.some(($)=>$.test(Q))?"required":void 0}function h0(Q){for(let $ of Q){let Z=tZ($);if(Z!==void 0)return Z==="required"}return!1}var eZ="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.",Q2="Required delegation did not complete before the retry limit.",Z2=3;function dQ(Q,$,Z){let J=(typeof Q==="string"?[Q]:Q??[]).map((z)=>z.trim()).filter(Boolean),G=h0(J),W=!1;if(!G)for(let z of J){if(aZ.some((V)=>V.test(z)))break;if(rZ.some((V)=>V.test(z))){W=!0;break}}if(J.length===0||!G&&!W||$.has("Task"))return{action:"none"};if(Z>=Z2)return{action:"fail",message:Q2};return{action:"retry",prompt:eZ}}var $2=[/\b(?:use|create|enter|start|work\s+(?:in|inside))\b.{0,60}\bworktree\b/i,/(?:使用|创建|进入).{0,30}(?:worktree|工作树)/i],J2=[/\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 T0(Q){return typeof Q==="string"&&$2.some(($)=>$.test(Q))}var G2="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.",W2="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.",z2="Required worktree lifecycle did not complete before the retry limit.",V2=3;function mQ(Q,$,Z){if(!Q||!T0(Q))return{action:"none"};let J=J2.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>=V2)return{action:"fail",message:z2};return{action:"retry",tool:G,prompt:G==="EnterWorktree"?G2:W2}}var pQ=30000;async function FQ(Q){try{let Z=x0.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"),pQ)});try{let W=await Promise.race([Z,G]);if(W==="timeout")return HQ.warn(`[Loop] Stop hook 超时 (${pQ}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 HQ.warn("[Loop] Stop hook execution failed:",$),{action:"stop"}}}var K0=i("Agent"),OQ=`<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 a(Q,
|
|
4
|
-
`),G
|
|
5
|
-
`).trim();if(
|
|
3
|
+
</turn_aborted>`;function j0(Q){return Q.executionEngine?.getContextManager()}async function a(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 g(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 cQ(Q,$,Z){try{let J=j0(Q);if(J&&$.sessionId)return await J.saveMessage($.sessionId,"system",OQ,Z,void 0,$.subagentInfo)}catch(J){K0.warn("[Loop] 保存中断边界失败:",J)}return null}async function LQ(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 k0(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 R0(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 uQ(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 iQ(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 nQ(Q){let $=Q.metadata;if(!$)return;return $.modelId?.toString().trim()||$.model?.toString().trim()||void 0||void 0}function Y2(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 X2(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 bQ(Q,$,Z,J){let G=uQ(Q,$),W=X2(Q,$);iQ(Q,$,Z);let z=nQ($);if(z)await Z.onModelSwitch?.(z);if(J)Y2(Q,$,J);return W||G}import{nanoid as Z0}from"nanoid";import{promises as q2}from"node:fs";import _2 from"node:path";import*as h from"node:fs/promises";import*as W0 from"node:path";var lQ={enabled:!0,maxIndexLines:200};var H2="memory",rQ="MEMORY.md";class qQ{memoryDir;config;initialized=!1;constructor(Q,$,Z){if(Z)this.memoryDir=Z;else{let J=aQ(Q);this.memoryDir=W0.join(J,H2)}this.config={...lQ,...$}}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=W0.join(this.memoryDir,rQ);try{let $=await h.readFile(Q,"utf-8");if(!$.trim())return null;let Z=$.split(`
|
|
4
|
+
`),G=Z.slice(0,this.config.maxIndexLines).join(`
|
|
5
|
+
`).trim();if(Z.length>this.config.maxIndexLines)return G+`
|
|
6
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
|
|
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=W0.join(this.memoryDir,rQ);if($==="append"){let J="";try{J=await h.readFile(Z,"utf-8")}catch{}let G=J&&!J.endsWith(`
|
|
10
10
|
`)?`
|
|
11
|
-
`:"";await h.writeFile(
|
|
12
|
-
`);await
|
|
13
|
-
`,"append"),J.push(W),G+=z.length}return{extracted:G,topics:J}}catch{return{extracted:0,topics:[]}}}import{promises as C0}from"node:fs";import*as V0 from"fs/promises";import*as A from"path";var sQ=[".git",".claude","node_modules",".env",".env.local",".env.production",".env.development",".env.test"];class z0 extends Error{code;constructor(Q
|
|
14
|
-
`);if(this.extractFilePathsFromContent(W).forEach((V)=>{this.updateFileReference(
|
|
15
|
-
`),V=z.length,Y=W,H=!1,
|
|
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=W0.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=W0.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=W0.join(this.memoryDir,Z);if(!J.startsWith(this.memoryDir))throw Error(`Invalid topic name: ${Q}`);return J}}var B2=[{pattern:/(?:记住|remember|note|备注)[::](.+)/i,topic:"preferences"},{pattern:/(?:convention|约定|规范)[::](.+)/i,topic:"conventions"},{pattern:/(?:lesson|教训|踩坑)[::](.+)/i,topic:"lessons"}],K2=/(?:fix|修复|解决|resolved)[::]\s*(.+?)(?:\n|$)/i,j2=/(?:Error|FAIL|错误)[::]\s*(.+?)(?:\n|$)/i;function D2(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 B2){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(K2);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(j2);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 oQ(Q){let $=D2(Q);if($.size===0)return{extracted:0,topics:[]};try{let Z=new qQ(c());await Z.initialize();let J=[],G=0;for(let[W,z]of $){if(z.length===0)continue;let V=new Date().toISOString().split("T")[0],Y=z.map((H)=>`- [${V}] ${H}`).join(`
|
|
12
|
+
`);await Z.writeTopic(W,Y+`
|
|
13
|
+
`,"append"),J.push(W),G+=z.length}return{extracted:G,topics:J}}catch{return{extracted:0,topics:[]}}}import{promises as C0}from"node:fs";import*as V0 from"fs/promises";import*as A from"path";var sQ=[".git",".claude","node_modules",".env",".env.local",".env.production",".env.development",".env.test"];class z0 extends Error{code;constructor(Q,$){super(Q);this.code=$;this.name="PathSecurityError"}}class Y0{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 z0(`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 sQ)if($.includes(Z))throw new z0(`Access denied: "${Z}" is a protected directory`,"RESTRICTED_PATH")}static checkTraversal(Q){if(Q.includes(".."))throw new z0(`Path traversal not allowed: ${Q}`,"PATH_TRAVERSAL")}static async validatePath(Q,$){this.checkTraversal(Q);let Z=this.normalize(Q,$);this.checkRestricted(Z);try{await V0.access(Z)}catch(J){throw new z0(`Path not found: ${Q}`,"PATH_NOT_FOUND")}return Z}static async resolveSymlink(Q,$){try{let Z=await V0.realpath(Q),J=await V0.realpath($);if(!this.isWithinWorkspace(Z,J))throw new z0(`Symlink points outside workspace: ${Q} -> ${Z}`,"SYMLINK_OUTSIDE_WORKSPACE");return Z}catch(Z){if(Z instanceof z0)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 V0.realpath(Z)}catch{return!1}let W=J;while(!0){try{let V=await V0.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 sQ.some((Z)=>$.includes(Z))}}var N0=i("Tool");class Q0{static instance=null;accessedFiles=new Map;constructor(){}static getInstance(){if(!Q0.instance)Q0.instance=new Q0;return Q0.instance}async recordFileRead(Q,$){try{let Z=await C0.stat(Q),J={filePath:Q,accessTime:Date.now(),mtime:Z.mtimeMs,sessionId:$,lastOperation:"read"};this.setRecord(J),N0.debug(`记录文件读取: ${Q}`)}catch(Z){N0.warn(`记录文件读取失败: ${Q}`,Z)}}async recordFileEdit(Q,$,Z="edit"){try{let J=await C0.stat(Q),G={filePath:Q,accessTime:Date.now(),mtime:J.mtimeMs,sessionId:$,lastOperation:Z};this.setRecord(G),N0.debug(`记录文件${Z==="edit"?"编辑":"写入"}: ${Q}`)}catch(J){N0.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 C0.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 C0.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 N0.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($&&!Y0.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(){Q0.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 F2}from"node:fs/promises";import{basename as O2,isAbsolute as L2,resolve as b2}from"node:path";class p0{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:"",j=["Write","Edit"].includes(H||"");Y.forEach((b)=>{this.updateFileReference($,b,G,j)})})}),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=$&&!L2(J)?b2($,J):J;if($&&!await Y0.isWithinWorkspaceResolved(G,$))continue;let W=await F2(G,"utf-8"),z=W.split(`
|
|
15
|
+
`),V=z.length,Y=W,H=!1,j=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,j=this.MAX_LINES_PER_FILE;Z.push({path:J,content:Y,truncated:H,lines:V,includedLines:j})}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 $=O2(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 tQ}from"js-tiktoken";class E0{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 $=tQ(Q);this.encodingCache.set(Q,$)}catch{try{let $=tQ("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 T=i("Context"),g0=new Map,w2=3;function N2(Q,$){return JSON.stringify([_2.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??E0.countTokens(Q,$.modelName),J=$.actualPreTokens?"actual (from LLM usage)":"estimated";T.debug(`[CompactionService] preTokens source: ${J}`);try{let V=await x0.getInstance().executeCompactionHooks($.trigger,{projectDir:$.workspaceRoot??c(),sessionId:$.sessionId||"unknown",permissionMode:$.permissionMode||"default",messagesBefore:Q.length,tokensBefore:Z});if(V.blockCompaction)return T.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)T.warn(`[CompactionService] Compaction hook warning: ${V.warning}`)}catch(z){T.warn("[CompactionService] Compaction hook execution failed:",z)}let G=N2($.workspaceRoot,$.sessionId),W=g0.get(G)??0;if(W>=w2)return T.warn(`[CompactionService] Circuit breaker open (${W} consecutive failures for session ${$.sessionId??"unknown"}), using fallback`),this.fallbackCompact(Q,$,Z,Error("Circuit breaker open"));try{T.debug("[CompactionService] 开始压缩,消息数:",Q.length),T.debug("[CompactionService] 压缩前 tokens:",Z);let V=p0.analyzeFiles(Q).map((d)=>d.path);T.debug("[CompactionService] 提取重点文件:",V);let Y=await p0.readFilesContent(V,$.workspaceRoot);T.debug("[CompactionService] 成功读取文件:",Y.length);let H=await this.generateSummary(Q,Y,$);T.debug("[CompactionService] 生成总结,长度:",H.length);let j=Math.ceil(Q.length*this.RETAIN_PERCENT),b=Q.slice(-j),D=new Set;for(let d of b)if(d.role==="assistant"&&d.tool_calls)for(let O0 of d.tool_calls)D.add(O0.id);let F=b.filter((d)=>{if(d.role==="tool"&&d.tool_call_id)return D.has(d.tool_call_id);return!0});T.debug("[CompactionService] 保留消息数:",j),T.debug("[CompactionService] 过滤后保留消息数:",F.length);let k=Z0(),R=this.createBoundaryMessage(k,$.trigger,Z),v=Z0(),N=this.createSummaryMessage(v,H),K=[N,...F],l=await this.buildFileRestorationMessage($.workspaceRoot,$.sessionId);if(l)K.push(l);let r=this.buildActiveTaskMessage($.activeTask);if(r)K.push(r);let f=E0.countTokens(K,$.modelName);T.debug("[CompactionService] 压缩完成!"),T.debug("[CompactionService] Token 变化:",Z,"->",f,`(-${((1-f/Z)*100).toFixed(1)}%)`),g0.delete(G);let H0=Q.slice(0,Q.length-j);return oQ(H0).catch((d)=>{return}),{success:!0,summary:H,preTokens:Z,postTokens:f,filesIncluded:Y.map((d)=>d.path),compactedMessages:K,boundaryMessage:R,summaryMessage:N}}catch(z){if(X0(z))throw z;return g0.set(G,(g0.get(G)??0)+1),T.error("[CompactionService] 压缩失败,使用降级策略",z),this.fallbackCompact(Q,$,Z,z)}}static async generateSummary(Q,$,Z){let J=this.buildCompactionPrompt(Q,$);if(T.debug("[CompactionService] 使用压缩模型:",Z.modelName),Z.signal?.aborted)throw new DOMException("Aborted","AbortError");let z=(await(await eQ({apiKey:Z.apiKey||process.env.BLADE_API_KEY||"",baseUrl:Z.baseURL||process.env.BLADE_BASE_URL||"https://api.openai.com/v1",model:Z.modelName,temperature:0.3,maxOutputTokens:8000,timeout:60000,provider:"openai-compatible"})).chat([{role:"user",content:J}],[],Z.signal)).content||"",V=z.match(/<summary>([\s\S]*?)<\/summary>/);if(!V)return T.warn("[CompactionService] 总结格式不正确,使用完整响应"),z;return V[1].trim()}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,j=Y.length>5000?Y.substring(0,5000)+"...":Y;return`[${z+1}] ${V}: ${j}`}).join(`
|
|
19
19
|
|
|
20
|
-
`),J
|
|
20
|
+
`),J=$.map((W)=>{return`### ${W.path}
|
|
21
21
|
\`\`\`
|
|
22
22
|
${W.content}
|
|
23
23
|
\`\`\``}).join(`
|
|
@@ -82,39 +82,39 @@ Your summary should include the following sections:
|
|
|
82
82
|
|
|
83
83
|
## Conversation History
|
|
84
84
|
|
|
85
|
-
${
|
|
85
|
+
${Z}
|
|
86
86
|
|
|
87
|
-
${
|
|
87
|
+
${$.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
|
|
91
|
+
Please provide your summary following the structure specified above, with both <analysis> and <summary> sections.`}static createBoundaryMessage(Q,$,Z){return{id:Z0(),role:"system",content:"Conversation compacted",metadata:{type:"system",subtype:"compact_boundary",parentId:Q,compactMetadata:{trigger:$,preTokens:Z}}}}static createSummaryMessage(Q,$){return{id:Z0(),role:"user",content:$,metadata:{parentId:Q,isCompactSummary:!0}}}static async getRecentlyAccessedFiles(Q,$,Z){let G=Q0.getInstance().getTrackedRecords().filter((z)=>!Z||z.sessionId===Z).sort((z,V)=>V.accessTime-z.accessTime),W=[];for(let z of G){if($&&!await Y0.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 q2.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 T.debug("[CompactionService] Post-compact 恢复文件:"
|
|
97
|
+
`);return T.debug("[CompactionService] Post-compact 恢复文件:",Z.length),{id:Z0(),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
|
|
100
|
-
`),metadata:{isPostCompactActiveTask:!0}}}static fallbackCompact(Q,
|
|
99
|
+
`,Q.slice(-($-Z))].join("");return{id:Z0(),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 N of v.tool_calls)z.add(N.id);let V=W.filter((v)=>{if(v.role==="tool"&&v.tool_call_id)return z.has(v.tool_call_id);return!0}),Y=Z0(),H=this.createBoundaryMessage(Y,$.trigger,Z),j=J instanceof Error?J.message:String(J),b=Z0(),D=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: ${j}
|
|
105
105
|
|
|
106
|
-
The conversation can continue, but consider retrying compaction later with /compact.`),F=[
|
|
107
|
-
`),preTokens
|
|
106
|
+
The conversation can continue, but consider retrying compaction later with /compact.`),F=[D,...V],k=this.buildActiveTaskMessage($.activeTask);if(k)F.push(k);let R=E0.countTokens(F,$.modelName);return{success:!1,summary:typeof D.content==="string"?D.content:D.content.filter((v)=>v.type==="text").map((v)=>v.text).join(`
|
|
107
|
+
`),preTokens:Z,postTokens:R,filesIncluded:[],compactedMessages:F,boundaryMessage:H,summaryMessage:D,error:j}}}var E2=new Set(["Read","Grep","Glob","Search","WebSearch","WebFetch","ToolSearch"]);function v2(Q,$){let G=(Q[$.assistantIdx].tool_calls??[]).filter((z)=>z.type==="function").map((z)=>z.function.name).some((z)=>!E2.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 v0(Q,$){let Z=$?.keepRecentTurns??10,J=$?.minMessagesForSnip??30;if(Q.length<J)return{messages:Q,snippedCount:0,estimatedTokensFreed:0};let G=[];for(let D=0;D<Q.length;D++){let F=Q[D];if(F.role==="assistant"&&F.tool_calls&&F.tool_calls.length>0){let k=new Set(F.tool_calls.map((v)=>v.id)),R=[];for(let v=D+1;v<Q.length;v++){let N=Q[v];if(N.role==="tool"&&N.tool_call_id&&k.has(N.tool_call_id))R.push(v);if(N.role==="assistant"||N.role==="user")break}G.push({assistantIdx:D,toolResultIdxs:R,priority:0})}}for(let D of G)D.priority=v2(Q,D);let V=[...G.slice(0,Math.max(0,G.length-Z))].sort((D,F)=>D.priority-F.priority);if(V.length===0)return{messages:Q,snippedCount:0,estimatedTokensFreed:0};let Y=new Set,H=0;for(let D of V){Y.add(D.assistantIdx);for(let F of D.toolResultIdxs)Y.add(F)}for(let D of Y){let F=Q[D],k=typeof F.content==="string"?F.content:JSON.stringify(F.content);if(H+=k.length,F.tool_calls)H+=JSON.stringify(F.tool_calls).length}let j=[],b=!1;for(let D=0;D<Q.length;D++){if(Y.has(D)){if(!b)j.push({role:"system",content:`[${V.length} earlier tool interaction${V.length===1?"":"s"} snipped for brevity]`}),b=!0;continue}j.push(Q[D])}return{messages:j,snippedCount:V.length,estimatedTokensFreed:Math.floor(H/4)}}var I2=60000,U2=3;function QZ(Q,$){if(!$)return null;if(Date.now()-$<I2)return null;let J=v0(Q,{keepRecentTurns:U2,minMessagesForSnip:15});if(J.snippedCount===0)return null;return J}class _Q{hasAttempted=!1;async tryReactiveCompact(Q,$){if(this.hasAttempted)return{success:!1,messages:Q};this.hasAttempted=!0;let Z=v0(Q,{keepRecentTurns:3,minMessagesForSnip:10}),J=Z.messages;try{let G=await D0.compact(J,{trigger:"auto",modelName:$.modelName,maxContextTokens:$.maxContextTokens,apiKey:$.apiKey,baseURL:$.baseURL,signal:$.signal,activeTask:$.activeTask,workspaceRoot:$.workspaceRoot,sessionId:$.sessionId});if(G.success)return{success:!0,messages:G.compactedMessages};if(Z.snippedCount>0)return{success:!0,messages:J};return{success:!1,messages:Q}}catch(G){if(X0(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 wQ from"os";import*as I0 from"path";import{nanoid as JZ}from"nanoid";var A2=1e5,y2=2000,ZZ=200000;class NQ{currentChars=0;track(Q){this.currentChars+=Q}remaining(){return Math.max(0,ZZ-this.currentChars)}isExhausted(){return this.currentChars>=ZZ}reset(){this.currentChars=0}}function GZ(Q,$,Z){let J=Z?.maxCharsPerResult??A2,G=Z?.previewChars??y2,W=Z?.messageBudget,z=typeof Q==="string"?Q:JSON.stringify(Q,null,2);if(z.length<=J)return S2(Q,z,$,G,W,Z);let V=Z?.outputDir??I0.join(wQ.homedir(),".blade","tool-results"),Y=`${$}-${JZ(8)}.txt`,H=I0.join(V,Y);try{F0.mkdirSync(V,{recursive:!0}),F0.writeFileSync(H,z,"utf-8")}catch{let D=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(D.length);return D}let j=z.slice(0,G),b=`Result too large (${z.length} chars). Full output saved to: ${H}
|
|
110
110
|
|
|
111
111
|
Preview:
|
|
112
|
-
${
|
|
112
|
+
${j}
|
|
113
113
|
|
|
114
|
-
... (${z.length-G} more chars in file)`;if(W)W.track(b.length);return b}function S2(Q,
|
|
114
|
+
... (${z.length-G} more chars in file)`;if(W)W.track(b.length);return b}function S2(Q,$,Z,J,G,W){if(!G)return Q;let z=G.remaining();if(z<=0){let V=$.slice(0,J),Y=$Z($,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=$Z($,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 $Z(Q,$,Z,J,G){let W=J?.outputDir??I0.join(wQ.homedir(),".blade","tool-results"),z=`${Z}-${JZ(8)}.txt`,V=I0.join(W,z);try{return F0.mkdirSync(W,{recursive:!0}),F0.writeFileSync(V,Q,"utf-8"),`${$}
|
|
115
115
|
|
|
116
116
|
${G}
|
|
117
|
-
Full output saved to: ${V}`}catch{return`${
|
|
117
|
+
Full output saved to: ${V}`}catch{return`${$}
|
|
118
118
|
|
|
119
119
|
${G}`}}import*as n0 from"node:fs/promises";import{homedir as FZ}from"node:os";import*as o from"node:path";var d0={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 WZ(){return{metadata:d0,instructions:`# Skill Creator
|
|
120
120
|
|
|
@@ -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 M2}from"node:child_process";import*as _ from"node:fs/promises";import{homedir as P2}from"node:os";import*as P from"node:path";import{promisify as f2}from"node:util";var c0=f2(M2),M=i("General"),EQ={url:"https://github.com/anthropics/skills.git",branch:"main",defaultSkills:["skill-creator"]};class VZ{skillsDir;constructor(Q){this.skillsDir=Q||P.join(P2(),".blade","skills")}async isInstalled(Q){let
|
|
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
|
|
577
|
-
${
|
|
578
|
-
</available_skills>`);if(G===J.description)return J;return{...J,description:G}})}function OZ(){return{consecutiveFailures:new Map,totalFailures:0,lastFailedTool:null}}function LZ(Q
|
|
579
|
-
`)}function NZ(){return{recentOutputHashes:[]}}function c2(Q){let
|
|
575
|
+
`}}import{exec as M2}from"node:child_process";import*as _ from"node:fs/promises";import{homedir as P2}from"node:os";import*as P from"node:path";import{promisify as f2}from"node:util";var c0=f2(M2),M=i("General"),EQ={url:"https://github.com/anthropics/skills.git",branch:"main",defaultSkills:["skill-creator"]};class VZ{skillsDir;constructor(Q){this.skillsDir=Q||P.join(P2(),".blade","skills")}async isInstalled(Q){let $=P.join(this.skillsDir,Q,"SKILL.md");try{return await _.access($),!0}catch{return!1}}async isGitAvailable(){try{return await c0("git --version"),!0}catch{return!1}}async installOfficialSkill(Q){let{url:$,branch:Z}=EQ,J=P.join(this.skillsDir,Q),G=P.join(this.skillsDir,`.tmp-${Q}-${Date.now()}`);try{if(!await this.isGitAvailable())return M.warn("Git not available, skipping skill installation"),!1;M.info(`Installing official skill: ${Q}...`),await _.mkdir(this.skillsDir,{recursive:!0,mode:493}),await c0(`git clone --depth 1 --branch ${Z} --single-branch ${$} "${G}"`,{timeout:30000});let W=P.join(G,"skills",Q);try{await _.access(W)}catch{return M.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}),M.info(`Successfully installed: ${Q}`),!0}catch(W){try{await _.rm(G,{recursive:!0,force:!0})}catch{}return M.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 EQ.defaultSkills)if(!await this.isInstalled(Q))await this.installOfficialSkill(Q)}async installFromRepo(Q,$){let Z=$||this.extractRepoName(Q),J=P.join(this.skillsDir,Z),G=P.join(this.skillsDir,`.tmp-repo-${Z}-${Date.now()}`);try{if(!await this.isGitAvailable())return M.warn("Git not available, cannot install from repo"),!1;M.info(`Installing skill from repo: ${Q}...`),await _.mkdir(this.skillsDir,{recursive:!0,mode:493}),await c0(`git clone --depth 1 "${Q}" "${G}"`,{timeout:60000});let W=P.join(G,"SKILL.md");try{await _.access(W)}catch{return M.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(P.join(J,".git"),{recursive:!0,force:!0})}catch{}return M.info(`Successfully installed skill from repo: ${Z}`),!0}catch(W){try{await _.rm(G,{recursive:!0,force:!0})}catch{}return M.warn(`Failed to install from repo ${Q}: ${W instanceof Error?W.message:"Unknown error"}`),!1}}async installFromLocal(Q,$,Z=!0){let J=$||P.basename(Q),G=P.join(this.skillsDir,J);try{let W=P.resolve(Q);try{await _.access(W)}catch{return M.warn(`Local path does not exist: ${W}`),!1}let z=P.join(W,"SKILL.md");try{await _.access(z)}catch{return M.warn(`No SKILL.md found in local path: ${W}`),!1}if(M.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"),M.info(`Created symlink for skill: ${J}`);else await _.cp(W,G,{recursive:!0}),M.info(`Copied skill to: ${J}`);return!0}catch(W){return M.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:$}=EQ,Z=P.join(this.skillsDir,`.tmp-all-${Date.now()}`),J=[],G=[];try{if(!await this.isGitAvailable())return M.warn("Git not available, skipping skill installation"),{installed:J,failed:G};await _.mkdir(this.skillsDir,{recursive:!0,mode:493}),M.info("Cloning official skills repository..."),await c0(`git clone --depth 1 --branch ${$} --single-branch ${Q} "${Z}"`,{timeout:60000});let W=P.join(Z,"skills"),z=await _.readdir(W,{withFileTypes:!0});for(let V of z){if(!V.isDirectory())continue;let Y=V.name,H=P.join(W,Y),j=P.join(this.skillsDir,Y);try{await _.access(P.join(H,"SKILL.md")),await _.rm(j,{recursive:!0,force:!0}),await _.cp(H,j,{recursive:!0}),M.info(`Installed: ${Y}`),J.push(Y)}catch(b){M.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{}M.warn(`Failed to install skills: ${W instanceof Error?W.message:"Unknown error"}`)}return{installed:J,failed:G}}}var vQ=null;function YZ(Q){if(!vQ)vQ=new VZ(Q);return vQ}import*as U0 from"node:fs/promises";import*as u0 from"node:path";import{parse as x2}from"yaml";var h2=/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/,T2=/^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]?$/,XZ=1024;function k2(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 HZ(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 R2(Q,$){if(!Q.name)return{valid:!1,error:"Missing required field: name"};if(!T2.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>XZ)return{valid:!1,error:`Description too long: ${Q.description.length} characters (max ${XZ})`};let Z;if(Q.model)Z=Q.model==="inherit"?"inherit":Q.model;return{valid:!0,metadata:{name:Q.name,description:Q.description.trim(),allowedTools:k2(Q["allowed-tools"]),version:Q.version,argumentHint:Q["argument-hint"]?.trim(),userInvocable:HZ(Q["user-invocable"]),disableModelInvocation:HZ(Q["disable-model-invocation"]),model:Z,whenToUse:Q.when_to_use?.trim()}}}function BZ(Q,$,Z){let J=Q.match(h2);if(!J)return{success:!1,error:"Invalid SKILL.md format: missing YAML frontmatter (must start with ---)"};let[,G,W]=J,z;try{z=x2(G)}catch(H){return{success:!1,error:`Failed to parse YAML frontmatter: ${H instanceof Error?H.message:String(H)}`}}let V=R2(z,$);if(!V.valid)return{success:!1,error:V.error};let Y=u0.dirname($);return{success:!0,content:{metadata:{...V.metadata,path:$,basePath:Y,source:Z},instructions:W.trim()}}}async function KZ(Q,$){try{let Z=await U0.readFile(Q,"utf-8");return BZ(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 jZ(Q){try{let $=await U0.readFile(Q.path,"utf-8"),Z=BZ($,Q.path,Q.source);return Z.success?Z.content:null}catch{return null}}async function DZ(Q){try{return await U0.access(u0.join(Q,"SKILL.md")),!0}catch{return!1}}var C2={userSkillsDir:o.join(FZ(),".blade","skills"),projectSkillsDir:".blade/skills",claudeUserSkillsDir:o.join(FZ(),".claude","skills"),claudeProjectSkillsDir:".claude/skills"},i0=null;class IQ{skills=new Map;pluginSkills=new Map;config;initialized=!1;constructor(Q){this.config={...C2,cwd:c(),...Q}}static getInstance(Q){if(!i0)i0=new IQ(Q);return i0}static resetInstance(){i0=null}async initialize(){if(this.initialized)return{skills:Array.from(this.skills.values()),errors:[]};let Q=[],$=[];try{await YZ(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=o.isAbsolute(this.config.claudeProjectSkillsDir)?this.config.claudeProjectSkillsDir:o.join(this.config.cwd,this.config.claudeProjectSkillsDir),W=await this.scanDirectory(G,"project");$.push(...W.skills),Q.push(...W.errors);let z=o.isAbsolute(this.config.projectSkillsDir)?this.config.projectSkillsDir:o.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(d0.name,d0),this.skills.set(m0.name,m0)}async scanDirectory(Q,$){let Z=[],J=[];try{await n0.access(Q)}catch{return{skills:Z,errors:J}}try{let G=await n0.readdir(Q,{withFileTypes:!0});for(let W of G){if(!W.isDirectory())continue;let z=o.join(Q,W.name),V=o.join(z,"SKILL.md");if(!await DZ(z))continue;let Y=await KZ(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 jZ($)}loadBuiltinContent(Q){switch(Q){case"skill-creator":return WZ();case"update-config":return zZ();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 l0(Q){return IQ.getInstance(Q)}async function p2(Q){return l0(Q).initialize()}var g2="Skill",d2=/<available_skills>\s*<\/available_skills>/;function UQ(Q){let Z=l0().generateAvailableSkillsList();if(!Z)return Q;return Q.map((J)=>{if(J.name!==g2)return J;let G=J.description.replace(d2,`<available_skills>
|
|
577
|
+
${Z}
|
|
578
|
+
</available_skills>`);if(G===J.description)return J;return{...J,description:G}})}function OZ(){return{consecutiveFailures:new Map,totalFailures:0,lastFailedTool:null}}function LZ(Q,$){Q.consecutiveFailures.set($,0),Q.lastFailedTool=null}function bZ(Q,$){let Z=(Q.consecutiveFailures.get($)??0)+1;Q.consecutiveFailures.set($,Z),Q.totalFailures++,Q.lastFailedTool=$}function m2(Q,$){return(Q.consecutiveFailures.get($)??0)>=3}function qZ(Q,$){if(!m2(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 _Z(Q){return Q>0&&Q%5===0}function wZ(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 NZ(){return{recentOutputHashes:[]}}function c2(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 EZ(Q,$){let Z=c2($);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 vZ(){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 $0=i("Agent"),i2=new Set(["Read","Glob","Grep","WebFetch","WebSearch","MemoryRead","GetSpecContext","ValidateSpec","TaskOutput"]);class r0{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 $0.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(i2.has(Q.function.name)){$0.debug(`[StreamingToolExecutor] 立即执行预启动工具: ${Q.function.name}`);let G=this.executeOne(Q,$);return this.pending.set(Q.id,G),"prelaunched"}else return $0.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){$0.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(),$0.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(D){$0.warn("[StreamingToolExecutor] 保存工具调用失败:",D)}let z=[G,J.signal],V=this.execContext.signal;if(V)z.push(V);let Y=IZ(...z),H={...this.execContext,messageId:W??Q.id,signal:Y},j=this.executeTool?await this.executeTool(Q.function.name,$,H):await this.pipeline.execute(Q.function.name,$,H);if(Z!==this.epoch)return $0.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:j,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)");$0.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"),n2=0.1,l2=8192,r2=32768,a2=2,o2=0.95,a0=AZ,s2=`
|
|
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 UZ(Q){let
|
|
588
|
-
`)}function J7(Q){if(!(Q instanceof Error))return!1;let
|
|
587
|
+
5. Prefer the smallest change that achieves the goal — avoid unnecessary refactoring.`;function UZ(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 AQ(Q){let $=UZ(Q);if($)return $;try{let Z=JSON.parse(Q);return typeof Z==="string"?UZ(Z):null}catch{return null}}function t2(Q){if(typeof Q==="string")return Q;try{return JSON.parse(JSON.stringify(Q))}catch{return String(Q)}}function e2(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 Q7(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 Z7(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 $7(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 J7(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 G7(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 W7(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*z7(Q,$,Z,J,G,W){let z="",V="",Y,H,j=new Map;try{let b=Q.chatService.streamChat($,Z,J,G),D=0;for await(let F of b){if(D++,J?.aborted)break;if(F.modelFallback){W?.discard(),z="",V="",Y=void 0,H=void 0,j.clear(),D=0,yield{kind:"model_fallback"};continue}if(F.content)z+=F.content,yield{kind:"content_delta",delta:F.content};if(F.reasoningContent)V+=F.reasoningContent,yield{kind:"thinking_delta",delta:F.reasoningContent};if(F.usage)Y=F.usage;if(F.toolCalls){for(let k of F.toolCalls)if(G7(j,k),W){let v=k.index??0,N=j.get(v);if(N&&N.id&&N.name)try{let K=AQ(N.arguments);if(K===null)continue;let l={id:N.id,type:"function",function:{name:N.name,arguments:N.arguments}},f=Q.toolExecutor.getRegistry().get(N.name)?.kind;if(W.addTool(l,K)==="prelaunched")yield{kind:"tool_start",toolCall:l,toolKind:f}}catch{}}}if(F.finishReason){H=F.finishReason;break}}if(D===0&&!J?.aborted&&z.length===0&&j.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:W7(j),usage:Y,finishReason:H}}catch(b){if(Z7(b))return x.warn("[Loop] 流式请求失败,降级到非流式模式"),W?.discard(),{...await Q.chatService.chat($,Z,J,G),_nonStreamingFallback:!0};throw b}}async function*MZ(Q,$,Z,J,G,W,z,V){if(J===void 0)return x.debug(`[Loop] [轮次 ${Z}] 压缩检查: 跳过(无历史 usage 数据)`),"none";let Y=QZ($.messages,W);if(Y)$.messages=Y.messages,x.debug(`[Loop] [轮次 ${Z}] MicroCompact: 清理 ${Y.snippedCount} 轮旧工具结果(缓存已过期)`);let H=v0($.messages),j=!1;if(H.snippedCount>0)j=!0,x.debug(`[Loop] [轮次 ${Z}] Snip 压缩: 移除 ${H.snippedCount} 轮旧工具调用,释放约 ${H.estimatedTokensFreed} tokens`);let b=Q.chatService.getConfig(),D=b.model,F=b.maxContextTokens??Q.config.maxContextTokens,k=b.maxOutputTokens??Q.config.maxOutputTokens??Math.min(Math.max(Math.floor(F*n2),l2),r2),R=F-k,v=Math.floor(R*0.8);if(x.debug(`[Loop] [轮次 ${Z}] 压缩检查:`,{promptTokens:J,maxContextTokens:F,maxOutputTokens:k,availableForInput:R,threshold:v,shouldCompact:J>=v}),J<v){if(j)$.messages=H.messages;return j?"snipped":"none"}let N=V?.lastCompactionTurn===void 0?void 0:Z-V.lastCompactionTurn,K=N!==void 0&&N<=a2,l=Math.floor(R*o2);if(K&&J<l){if(j)$.messages=H.messages;return x.debug(`[Loop] [轮次 ${Z}] 跳过连续 LLM 压缩,距离上次压缩 ${N} 轮`),j?"snipped":"none"}x.debug(Z===0?"[Loop] 触发自动压缩":`[Loop] [轮次 ${Z}] 触发循环内自动压缩`),yield{kind:"compaction",phase:"start"};try{let r=j?H.messages:$.messages,f=await D0.compact(r,{trigger:"auto",modelName:D,maxContextTokens:F,apiKey:b.apiKey,baseURL:b.baseUrl,actualPreTokens:J,signal:G,activeTask:z,workspaceRoot:$.workspaceRoot||c(),sessionId:$.sessionId});if($.messages=f.compactedMessages,V)V.lastCompactionTurn=Z;if(f.success)x.debug(`[Loop] [轮次 ${Z}] 压缩完成: ${f.preTokens} -> ${f.postTokens} tokens`);else x.warn(`[Loop] [轮次 ${Z}] 压缩使用降级策略: ${f.preTokens} -> ${f.postTokens} tokens`);return await R0(Q,$,f.summary,{trigger:"auto",preTokens:f.preTokens,postTokens:f.postTokens,filesIncluded:f.filesIncluded}),"compacted"}catch(r){if(X0(r))return x.debug(`[Loop] [轮次 ${Z}] 压缩被中止`),"none";if(j)$.messages=H.messages;return x.error(`[Loop] [轮次 ${Z}] 压缩失败,继续执行`,r),j?"snipped":"none"}finally{yield{kind:"compaction",phase:"end"}}}function V7(Q,$,Z,J){let G=J?SZ(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*Y7(Q,$,Z,J,G){let W=Date.now(),z=0,V=[],Y=null,H=!1,j=(b,D,F)=>{return H=!0,V7(b,D,W,F)};try{let b=Q.toolExecutor.getRegistry(),D=Z.permissionMode,F=b.getFunctionDeclarationsByMode(D);F=UQ(F);let k=Q.applySkillToolRestrictions(F),R=OZ(),v=NZ(),N=G;if(typeof b.getDeferredToolsListing==="function"){let E=b.getDeferredToolsListing();if(E&&N)N=`${N}
|
|
589
589
|
|
|
590
|
-
${E}`}if(N)N+=s2;let K=new f0(
|
|
591
|
-
`),$Q=[n
|
|
592
|
-
`),JQ=n.trim()?[n]:[],A0=[Q.runtimeOptions.appendSystemPrompt?.trim()
|
|
590
|
+
${E}`}if(N)N+=s2;let K=new f0(Z,N),l=J?.pendingInputOnly===!0;if(!l){let E=J?.inputMessageId?{inboxMessageId:J.inputMessageId}:void 0,U=E??(J?.transientInput==="goal_continuation"?{transientGoalContinuation:!0}:void 0);if(K.appendUser({role:"user",content:$,metadata:U}),J?.transientInput!=="goal_continuation")Y=await a(Q,Z,$,null,E);if(J?.inputMessageId&&!Y)throw Error(`Failed to persist durable input before applying it: ${J.inputMessageId}`)}let r=Z.permissionMode==="yolo",f=!!Z.subagentInfo,H0=Q.runtimeOptions.maxTurns??J?.maxTurns??Q.config.maxTurns??-1,d=H0>=0;if(H0===0)return{success:!1,error:{type:"chat_disabled",message:"对话功能已被禁用 (maxTurns=0)"},metadata:{turnsCount:0,toolCallsCount:0,duration:0}};let O0=H0===-1?a0:Math.min(H0,a0),s=0,o0,yQ,L0=0,s0=0,t0=0,e0=0,b0,QQ=0,ZQ=new Set,m=new Set(Z.worktreeActive?["EnterWorktree"]:[]),n=typeof $==="string"?$:$.filter((E)=>E.type==="text").map((E)=>E.text).join(`
|
|
591
|
+
`),$Q=[n,Z.completionRequirements?.trim()].filter(Boolean).join(`
|
|
592
|
+
`),JQ=n.trim()?[n]:[],A0=[Q.runtimeOptions.appendSystemPrompt?.trim(),Z.completionRequirements?.trim(),...JQ].filter((E)=>Boolean(E)),y0=T0(n),GQ=!l,q0=e2(Z.messages);if(q0)m.add("Task");let SQ=()=>h0(A0),PZ=()=>{let E="The exactly-once Task delegation has already been started. Do not call Task again; return the final answer after its result.";return{success:!1,llmContent:E,error:{type:"validation_error",message:E},metadata:{summary:"Blocked duplicate exactly-once Task delegation"}}},MQ=(E,U)=>{if(E!=="Task"||!SQ())return;if(q0)return PZ();q0=!0;return},fZ=(E)=>{if(E==="Task"&&SQ())q0=!1},PQ=async(E,U,_0)=>Q.toolExecutor.execute(E,U,_0),WQ=TQ({budget:Q.currentModelMaxContextTokens,isSubagent:f}),fQ=new _Q,xZ={},zQ=async(E)=>{for(let U of E){if(!K.getHistory().some((C)=>{let G0=C.metadata;return G0!==null&&typeof G0==="object"&&!Array.isArray(G0)&&G0.inboxMessageId===U.id})){let C=await a(Q,Z,U.content,Y,{inboxMessageId:U.id});if(!C)throw Error(`Failed to persist steering message before applying it: ${U.id}`);Y=C,K.appendUser({role:"user",content:U.content,metadata:{inboxMessageId:U.id}})}let J0=typeof U.content==="string"?U.content:U.content.filter((C)=>C.type==="text").map((C)=>C.text).join(`
|
|
593
593
|
`);if(J0.trim())n=[n,J0].join(`
|
|
594
|
-
`),JQ.push(J0),$Q=[n
|
|
595
|
-
`),A0=[Q.runtimeOptions.appendSystemPrompt?.trim()
|
|
594
|
+
`),JQ.push(J0),$Q=[n,Z.completionRequirements?.trim()].filter(Boolean).join(`
|
|
595
|
+
`),A0=[Q.runtimeOptions.appendSystemPrompt?.trim(),Z.completionRequirements?.trim(),...JQ].filter((C)=>Boolean(C)),y0=y0||T0(J0)}return{messageIds:E.map((U)=>U.id),count:E.length,recovered:E.filter((U)=>U.recovered).length}};try{while(!0){if(J?.signal?.aborted)return j(z,V.length,J.signal);let E=await J?.turnSteering?.drain()??[];if(E.length>0)yield{kind:"steering_applied",...await zQ(E),delivery:GQ?"current_turn":"next_turn"},GQ=!0;else if(!GQ)return{success:!0,finalMessage:"",metadata:{turnsCount:0,toolCallsCount:0,duration:Date.now()-W}};if(K.writeback(),(yield*MZ(Q,Z,z,o0,J?.signal,yQ,n,xZ))!=="none")K.replaceHistory(Z.messages);if(z++,fQ.reset(),yield{kind:"turn_start",turn:z,maxTurns:O0},J?.signal?.aborted)return j(z-1,V.length,J.signal);if(_Z(z)&&z>1){let w=wZ(z,R.totalFailures);K.appendControl("user",{role:"user",content:`
|
|
596
596
|
|
|
597
597
|
<system-reminder>
|
|
598
598
|
${w}
|
|
599
|
-
</system-reminder>`})}let _0=J?.stream!==!1,J0=q0&&h0(A0)?k.filter((w)=>w.name!=="Task"):k,C=b0;b0=void 0;let G0=C?J0.filter((w)=>w.name===C):J0,xQ=C?{toolChoice:{type:"tool",toolName:C}}:void 0,X,t;try{if(_0)t=new r0(Q.toolExecutor,{sessionId
|
|
599
|
+
</system-reminder>`})}let _0=J?.stream!==!1,J0=q0&&h0(A0)?k.filter((w)=>w.name!=="Task"):k,C=b0;b0=void 0;let G0=C?J0.filter((w)=>w.name===C):J0,xQ=C?{toolChoice:{type:"tool",toolName:C}}:void 0,X,t;try{if(_0)t=new r0(Q.toolExecutor,{sessionId:Z.sessionId,userId:Z.userId||"default",modelId:Q.config.currentModelId,workspaceRoot:Z.workspaceRoot||c(),worktreeIsolationRequired:y0,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),t.setAdmissionPolicy(MQ),t.setAdmissionRollback(fZ),t.setExecutionPolicy(PQ),X=yield*z7(Q,K.toLLMMessages(),G0,J?.signal,xQ,t);else X=await Q.chatService.chat(K.toLLMMessages(),G0,J?.signal,xQ)}catch(w){if(J7(w)){x.warn("[Loop] 检测到 prompt_too_long 错误,尝试反应式压缩");let O=Q.chatService.getConfig(),L=await fQ.tryReactiveCompact(Z.messages,{modelName:O.model,maxContextTokens:O.maxContextTokens??Q.config.maxContextTokens,apiKey:O.apiKey,baseURL:O.baseUrl,signal:J?.signal,activeTask:n,workspaceRoot:Z.workspaceRoot||c(),sessionId:Z.sessionId});if(L.success){Z.messages=L.messages,K.replaceHistory(Z.messages),b0=C,x.info("[Loop] 反应式压缩成功,重试 LLM 调用"),z--;continue}}throw w}if(yQ=Date.now(),X.usage){if(X.usage.totalTokens)s+=X.usage.totalTokens;o0=X.usage.promptTokens,yield{kind:"token_usage",usage:{inputTokens:X.usage.promptTokens??0,outputTokens:X.usage.completionTokens??0,totalTokens:X.usage.totalTokens??0,maxContextTokens:Q.currentModelMaxContextTokens}}}let hZ=X.usage?.completionTokens??0;if(WQ=kQ(WQ,hZ,L0>0),J?.signal?.aborted)return j(z-1,V.length,J.signal);if(!_0||!!X._nonStreamingFallback){if(X.reasoningContent&&X.reasoningContent.trim())yield{kind:"thinking_delta",delta:X.reasoningContent};if(X.content&&X.content.trim())yield{kind:"content_delta",delta:X.content}}yield{kind:"stream_end"};let VQ=KQ(X.finishReason,L0,WQ);if(VQ.action==="recover"){L0++,x.warn(`[Loop] Max output tokens hit (recovery ${L0}/3)`);let w={role:"assistant",content:X.content||"",reasoningContent:X.reasoningContent,tool_calls:X.toolCalls};K.appendToHistory(w);let O=await g(Q,Z,X.content||"",Y);if(O)Y=O;let L={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."};K.appendToHistory(L);let B=await a(Q,Z,L.content,Y);if(B)Y=B;continue}if(VQ.action==="truncated"||VQ.action==="budget_stop"){K.appendAssistant({role:"assistant",content:X.content||"",reasoningContent:X.reasoningContent,tool_calls:X.toolCalls});let w=await g(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:s,outputTruncated:!0}}}if(X.finishReason!=="length")L0=0;if(!X.toolCalls||X.toolCalls.length===0){let w=await J?.turnSteering?.drain()??[];if(w.length>0){K.appendAssistant({role:"assistant",content:X.content||"",reasoningContent:X.reasoningContent});let q=await g(Q,Z,X.content||"",Y);if(q)Y=q;yield{kind:"steering_applied",...await zQ(w),delivery:"current_turn"};continue}if(X.content&&EZ(v,X.content)){K.appendAssistant({role:"assistant",content:X.content||"",reasoningContent:X.reasoningContent}),K.appendControl("user",{role:"user",content:`
|
|
600
600
|
|
|
601
601
|
<system-reminder>
|
|
602
602
|
${vZ()}
|
|
603
|
-
</system-reminder>`});continue}let O=jQ(X.content,s0,!1);if(O.action==="retry"){s0++,K.appendAssistant({role:"assistant",content:X.content||"",reasoningContent:X.reasoningContent});let q=await g(Q
|
|
603
|
+
</system-reminder>`});continue}let O=jQ(X.content,s0,!1);if(O.action==="retry"){s0++,K.appendAssistant({role:"assistant",content:X.content||"",reasoningContent:X.reasoningContent});let q=await g(Q,Z,X.content||"",Y);if(q)Y=q;let u={role:"user",content:O.prompt};K.appendControl("user",u);let p=await a(Q,Z,u.content,Y);if(p)Y=p;continue}s0=0;let L=dQ(A0,m,t0);if(L.action==="retry"){t0++,b0="Task",K.appendAssistant({role:"assistant",content:X.content||"",reasoningContent:X.reasoningContent});let q=await g(Q,Z,X.content||"",Y);if(q)Y=q;let u={role:"user",content:L.prompt};K.appendControl("user",u);let p=await a(Q,Z,u.content,Y);if(p)Y=p;continue}if(L.action==="fail"){K.appendAssistant({role:"assistant",content:X.content||"",reasoningContent:X.reasoningContent});let q=await g(Q,Z,X.content||"",Y);if(q)Y=q;return{success:!1,error:{type:"delegation_protocol_failed",message:L.message},metadata:{turnsCount:z,toolCallsCount:V.length,duration:Date.now()-W,tokensUsed:s}}}t0=0;let B=mQ(n,m,QQ);if(B.action==="retry"){QQ++,K.appendAssistant({role:"assistant",content:X.content||"",reasoningContent:X.reasoningContent});let q=await g(Q,Z,X.content||"",Y);if(q)Y=q;let u={role:"user",content:B.prompt};K.appendControl("user",u);let p=await a(Q,Z,u.content,Y);if(p)Y=p;continue}if(B.action==="fail"){K.appendAssistant({role:"assistant",content:X.content||"",reasoningContent:X.reasoningContent});let q=await g(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:s}}}QQ=0;let S=DQ($Q,ZQ,e0);if(S.action==="retry"){e0++,b0="Bash",K.appendAssistant({role:"assistant",content:X.content||"",reasoningContent:X.reasoningContent});let q=await g(Q,Z,X.content||"",Y);if(q)Y=q;let u={role:"user",content:S.prompt};K.appendControl("user",u);let p=await a(Q,Z,u.content,Y);if(p)Y=p;continue}if(S.action==="fail"){K.appendAssistant({role:"assistant",content:X.content||"",reasoningContent:X.reasoningContent});let q=await g(Q,Z,X.content||"",Y);if(q)Y=q;return{success:!1,error:{type:"verification_failed",message:S.message},metadata:{turnsCount:z,toolCallsCount:V.length,duration:Date.now()-W,tokensUsed:s}}}e0=0;let y=await FQ({sessionId:Z.sessionId,permissionMode:Z.permissionMode,reason:X.content,abortSignal:J?.signal});if(y.action==="continue"){K.appendAssistant({role:"assistant",content:X.content||"",reasoningContent:X.reasoningContent});let q=await g(Q,Z,X.content||"",Y);if(q)Y=q;let p={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>`};K.appendControl("user",p);let w0=await a(Q
|
|
611
|
+
</system-reminder>`};K.appendControl("user",p);let w0=await a(Q,Z,p.content,Y);if(w0)Y=w0;continue}let e=await J?.turnSteering?.drainOrSeal();if(e&&e.messages.length>0){K.appendAssistant({role:"assistant",content:X.content||"",reasoningContent:X.reasoningContent});let q=await g(Q,Z,X.content||"",Y);if(q)Y=q;yield{kind:"steering_applied",...await zQ(e.messages),delivery:"current_turn"};continue}K.appendAssistant({role:"assistant",content:X.content||"",reasoningContent:X.reasoningContent});let I=await g(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:s,toolSuccessRate:V.length>0?V.filter((q)=>q.success).length/V.length:void 0,totalToolFailures:R.totalFailures||void 0}}}K.appendAssistant({role:"assistant",content:X.content||"",reasoningContent:X.reasoningContent,tool_calls:X.toolCalls});{let w=await g(Q,Z,X.content||"",Y);if(w)Y=w}if(J?.signal?.aborted)return j(z,V.length,J.signal);let YQ=X.toolCalls.filter((w)=>w.type==="function"),S0;if(t?.hasTools()){x.debug(`[Loop] 使用 StreamingToolExecutor 收集 ${YQ.length} 个工具结果`),S0=[];for(let w of t.getQueuedToolCalls()){let L=b.get(w.function.name)?.kind;yield{kind:"tool_start",toolCall:w,toolKind:L}}for await(let w of t.getRemainingResults())S0.push(w)}else{let w=new Map;for(let L of YQ){let B=AQ(L.function.arguments),S=B===null?void 0:MQ(L.function.name,B);if(S){w.set(L.id,S);continue}let e=b.get(L.function.name)?.kind;yield{kind:"tool_start",toolCall:L,toolKind:e}}let O=async(L)=>{try{let B=w.get(L.id);if(B)return{toolCall:L,result:B,toolUseUuid:null};let S=AQ(L.function.arguments);if(S===null)return{toolCall:L,result:{success:!1,llmContent:"",error:{type:"validation_error",message:`Invalid JSON object in tool arguments. Raw: ${L.function.arguments.slice(0,200)}`},metadata:void 0},toolUseUuid:null};if(L.function.name==="Task"&&(typeof S.subagent_session_id!=="string"||S.subagent_session_id.length===0))S.subagent_session_id=yZ("agent");let y=null;if(y=await LQ(Q,Z,L.function.name,S,Y),L.function.name==="ExitWorktree"&&m.has("EnterWorktree")&&!m.has("ExitWorktree")&&DQ($Q,ZQ,0).action!=="none"){let q="Run the requested verification before ExitWorktree. The worktree remains active so Bash can run in isolation.";return{toolCall:L,result:{success:!1,llmContent:q,error:{type:"validation_error",message:q},metadata:{summary:"Blocked ExitWorktree until verification succeeds"}},toolUseUuid:y}}let I=await PQ(L.function.name,S,{sessionId:Z.sessionId,userId:Z.userId||"default",modelId:Q.config.currentModelId,workspaceRoot:Z.workspaceRoot||c(),worktreeIsolationRequired:y0,worktreeActive:m.has("EnterWorktree")&&!m.has("ExitWorktree"),signal:J?.signal,confirmationHandler:Z.confirmationHandler,permissionMode:Z.permissionMode,toolRegistry:b,deferredToolManager:b.deferredToolManager});return{toolCall:L,result:I,toolUseUuid:y}}catch(B){return x.error(`Tool execution failed for ${L.function.name}:`,B),{toolCall:L,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")}}};S0=await Promise.all(YQ.map(O))}let TZ=new NQ;for(let{toolCall:w,result:O,toolUseUuid:L}of S0){let B=w;if(V.push(O),O.metadata?.abortedBeforeLaunch){let I=O.error?.message??"任务已被用户中止";if(L){let q=await k0(Q,Z,L,B.function.name,null,L,I);if(q)Y=q}return K.appendToolResult({role:"tool",tool_call_id:B.id,name:B.function.name,content:`Error: ${I}`}),j(z,V.length,J?.signal)}yield{kind:"tool_result",toolCall:B,result:O};{let I=O.metadata&&typeof O.metadata==="object"?O.metadata:void 0,u=((M0)=>M0==="running"||M0==="completed"||M0==="failed"||M0==="cancelled")(I?.subagentStatus)?I.subagentStatus:"completed",p=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,w0=await k0(Q,Z,L??B.id,B.function.name,O.success?t2(O.llmContent):null,L,O.success?void 0:O.error?.message,p);if(w0)Y=w0}let S=await bQ(B,O,Q,Z);if(S)yield S;if(O.success){if(LZ(R,B.function.name),B.function.name==="EnterWorktree"&&O.metadata?.workspaceTransition==="enter")m.add("EnterWorktree"),m.delete("ExitWorktree");else if(B.function.name==="ExitWorktree"&&O.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"&&O.metadata?.isolation==="worktree")m.add("TaskWorktree");gQ(ZQ,B.function.name,O)}else bZ(R,B.function.name);let y=O.success?O.llmContent||"":$7(B.function.name,O.error);if(!O.success){let I=qZ(R,B.function.name);if(I&&typeof y==="string")y=`${y}
|
|
612
612
|
|
|
613
|
-
${
|
|
613
|
+
${I}`}if(typeof y==="object"&&y!==null)y=JSON.stringify(y,null,2);if(typeof y==="string")y=GZ(y,B.function.name,{messageBudget:TZ});let e=typeof y==="string"?y:JSON.stringify(y);if(K.appendToolResult({role:"tool",tool_call_id:B.id,name:B.function.name,content:e,...B.function.name==="Task"?{metadata:{toolCallId:B.id,toolName:B.function.name,error:O.success?null:O.error?.message??null}}:{}}),O.metadata?.shouldExitLoop){let I=typeof O.llmContent==="string"?O.llmContent:"循环已退出";return{success:O.success,finalMessage:I,metadata:{turnsCount:z,toolCallsCount:V.length,duration:Date.now()-W,shouldExitLoop:!0,targetMode:O.metadata?.targetMode,planContent:typeof O.metadata?.planContent==="string"?O.metadata.planContent:void 0}}}}if(J?.signal?.aborted)return j(z,V.length,J.signal);let XQ=z>=a0,kZ=z>=O0&&(d||!r||f);if(XQ||kZ){let w=XQ?a0:O0;if(x.info(`Warning: 达到轮次上限 ${w} 轮`),J?.onTurnLimitReached){let O=await J.onTurnLimitReached({turnsCount:z});if(O?.continue){K.writeback();try{let L=Q.chatService.getConfig(),B=await D0.compact(Z.messages,{trigger:"auto",modelName:L.model,maxContextTokens:L.maxContextTokens??Q.config.maxContextTokens,apiKey:L.apiKey,baseURL:L.baseUrl,actualPreTokens:o0,signal:J?.signal,activeTask:n,workspaceRoot:Z.workspaceRoot||c(),sessionId:Z.sessionId});Z.messages=B.compactedMessages,K.replaceHistory(Z.messages);let S={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.`};K.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.`};K.appendToHistory(S),await R0(Q,Z,B.summary,{trigger:"auto",preTokens:B.preTokens,postTokens:B.postTokens,filesIncluded:B.filesIncluded})}catch(L){x.error("[Loop] 压缩失败,使用降级策略:",L);let S=K.getHistory().slice(-80);K.replaceHistory(S)}z=0;continue}return{success:!0,finalMessage:O?.reason||"已达到对话轮次上限,用户选择停止",metadata:{turnsCount:z,toolCallsCount:V.length,duration:Date.now()-W,tokensUsed:s}}}return{success:!1,error:{type:"max_turns_exceeded",message:f?`子代理已达到轮次上限 (${w} 轮)。`:`已达到${XQ?"安全":"显式"}轮次上限 (${w} 轮)。`},metadata:{turnsCount:z,toolCallsCount:V.length,duration:Date.now()-W,tokensUsed:s}}}}}finally{if(J?.transientInput==="goal_continuation")K.removeMessages((E)=>{let U=E.metadata;return U!==null&&typeof U==="object"&&!Array.isArray(U)&&U.transientGoalContinuation===!0});K.writeback()}}catch(b){if(X0(b))return j(z,V.length,J?.signal);let D=Q7(b);return x.error(`API 调用失败: ${D}`),{success:!1,error:{type:"api_error",message:D,details:b},metadata:{turnsCount:z,toolCallsCount:V.length,duration:Date.now()-W}}}finally{if(H)Z.messages.push({role:"system",content:OQ}),await cQ(Q,Z,Y)}}export{qQ as Oa,YZ as Pa,KZ as Qa,l0 as Ra,p2 as Sa,Y0 as Ta,Q0 as Ua,KQ as Va,jQ as Wa,gQ as Xa,FQ as Ya,P0 as Za,f0 as _a,RZ as $a,a as ab,g as bb,LQ as cb,k0 as db,R0 as eb,uQ as fb,iQ as gb,nQ as hb,bQ as ib,E0 as jb,D0 as kb,r0 as lb,MZ as mb,Y7 as nb};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import{realpathSync as G}from"fs";import{cwd as b}from"process";var _=null;function T(){let N="";if(typeof process<"u"&&typeof process.cwd==="function"&&typeof G==="function"){let R=b();try{N=G(R).normalize("NFC")}catch{N=R.normalize("NFC")}}return{cwd:N,originalCwd:N,projectRoot:N}}function u(){if(!_)_=T();return _}function U(){return u().cwd}function D(N){u().cwd=N.normalize("NFC")}function X(){return u().originalCwd}function E(){return u().projectRoot}function F(N){u().projectRoot=N.normalize("NFC")}var f;((x)=>{x.DEFAULT="default";x.AUTO_EDIT="autoEdit";x.YOLO="yolo";x.PLAN="plan"})(f||={});import{AsyncLocalStorage as A}from"async_hooks";var V=new A;function $(){return V.getStore()??U()}function M(){try{return $()}catch{return X()}}var Y=100;function Z(N){return Number.isInteger(N)&&N>=-1&&N<=100}function z(){return"-1, 0, or an integer from 1 to 100"}
|
|
2
|
-
export{D as
|
|
2
|
+
export{D as wb,X as xb,E as yb,F as zb,f as Ab,M as Bb,Y as Cb,Z as Db,z as Eb};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{Fb as Q,Gb as W,Hb as Y}from"./chunk-6kp3z956.js";import{Zb as X}from"./chunk-a7yjnqhd.js";var J=X("Service"),$="https://models.dev/api.json",j=3600000,G=null,Z=async()=>{if(G&&Date.now()-G.timestamp<j)return G.data;try{J.info("Fetching models.dev data...");let q=await fetch($,{headers:{"User-Agent":"Blade-CLI/1.0"}});if(!q.ok)throw Error(`HTTP ${q.status}: ${q.statusText}`);let x=await q.json();return G={data:x,timestamp:Date.now()},J.info(`Loaded ${Object.keys(x).length} providers from models.dev`),x}catch(q){throw J.error("Failed to fetch models.dev data:",q),q}},y=async()=>{let q=await Z(),x=[];for(let[w,k]of Object.entries(q)){let z=Object.keys(k.models||{}).length;if(z===0)continue;x.push({id:w,name:k.name||w,icon:W[w]||W.default,description:`${z} 个模型`,envVars:k.env||[],docUrl:k.doc,defaultBaseUrl:Y[w]})}return x.sort((w,k)=>{let z=Q.indexOf(w.id),K=Q.indexOf(k.id);if(z!==-1&&K!==-1)return z-K;if(z!==-1)return-1;if(K!==-1)return 1;return w.name.localeCompare(k.name)})},f=async(q)=>{let w=(await Z())[q];if(!w?.models)return J.warn(`No models found for provider: ${q}`),[];return Object.values(w.models).map((k)=>({id:k.id,name:k.name||k.id,contextWindow:k.limit?.context,maxOutput:k.limit?.output,inputCost:k.cost?.input,outputCost:k.cost?.output}))};
|
|
2
2
|
export{y as j,f as k};
|