blade-code 0.5.19 → 0.6.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-rpdww3y7.js → chunk-02dgzrzh.js} +1 -1
- package/dist/{chunk-w5bqfcdd.js → chunk-1cb2kqqm.js} +2 -2
- package/dist/{chunk-yk91w5p2.js → chunk-3w1zqywq.js} +3 -3
- package/dist/{chunk-q5yn875m.js → chunk-3z8h9j4f.js} +1 -1
- package/dist/{chunk-pfsft4nd.js → chunk-49pjm1fc.js} +1 -1
- package/dist/{chunk-7gje20de.js → chunk-4h4y84d6.js} +1 -1
- package/dist/chunk-4s0brhtr.js +1 -0
- package/dist/{chunk-yddnm9n2.js → chunk-50qc4e5g.js} +1 -1
- package/dist/{chunk-x9zj0r7s.js → chunk-6c5v0yas.js} +1 -1
- package/dist/{chunk-s9vcpyaq.js → chunk-7qy4kfe7.js} +1 -1
- package/dist/{chunk-bhjw4b73.js → chunk-7rjrzngk.js} +1 -1
- package/dist/chunk-9x5w4as8.js +1 -0
- package/dist/{chunk-k65n39by.js → chunk-bs9fg1qz.js} +1 -1
- package/dist/{chunk-7841654x.js → chunk-cwbszfye.js} +1 -1
- package/dist/chunk-dr1bb8ya.js +28 -0
- package/dist/{chunk-0a5rp0hh.js → chunk-e5ngx3x1.js} +37 -27
- package/dist/{chunk-q6e7ttyy.js → chunk-ekfmr2cb.js} +351 -330
- package/dist/{chunk-4jcdk905.js → chunk-gky78ctd.js} +1 -1
- package/dist/{chunk-g5pasj7t.js → chunk-gn1acna6.js} +1 -1
- package/dist/{chunk-yvs4mhkv.js → chunk-h9q2wpcp.js} +1 -1
- package/dist/{chunk-5mqvwzj8.js → chunk-hhtpxjqn.js} +1 -1
- package/dist/{chunk-zxame725.js → chunk-hy4dsdpp.js} +1 -1
- package/dist/{chunk-set7v1rf.js → chunk-ktag2d1c.js} +1 -1
- package/dist/chunk-mganjb5p.js +1 -0
- package/dist/{chunk-h6vkcgcb.js → chunk-n5xfrmrp.js} +1 -1
- package/dist/chunk-n9mwp62v.js +1 -0
- package/dist/{chunk-gym5t6r6.js → chunk-nhmdze8s.js} +1 -1
- package/dist/chunk-qv3wcc4p.js +2 -0
- package/dist/{chunk-j2ag7hh6.js → chunk-s53zeref.js} +1 -1
- package/dist/chunk-szbfafff.js +1 -0
- package/dist/{chunk-mz6n4w13.js → chunk-t1ex4e6g.js} +1 -1
- package/dist/{chunk-4fkv1hhp.js → chunk-tcqrc6pc.js} +1 -1
- package/dist/{chunk-37rethcy.js → chunk-v0z4bwcv.js} +2 -2
- package/dist/{chunk-68ctb04g.js → chunk-vwcjwzw3.js} +1 -1
- package/dist/{chunk-kt9197hs.js → chunk-w0hbjyzt.js} +1 -1
- package/dist/{chunk-7ycmx7c2.js → chunk-wre40mf1.js} +1 -1
- package/dist/{chunk-8kawkyrj.js → chunk-yjrx2q95.js} +1 -1
- package/dist/{chunk-e2h6cdnx.js → chunk-yz1nbhxn.js} +1 -1
- package/dist/{chunk-qwfywxs2.js → chunk-zfy765hj.js} +1 -1
- package/package.json +1 -1
- package/dist/chunk-bx4d9898.js +0 -1
- package/dist/chunk-c7rvs5ev.js +0 -2
- package/dist/chunk-fe7g701v.js +0 -1
- package/dist/chunk-mxrre2n3.js +0 -24
- package/dist/chunk-th432d0b.js +0 -1
- package/dist/chunk-z4ds84bg.js +0 -1
- package/dist/chunk-zh3ndtvg.js +0 -1
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import{Eb as L,zb as I}from"./chunk-wre40mf1.js";import{execSync as T}from"child_process";import{existsSync as Q,readFileSync as F,realpathSync as O}from"fs";import{basename as b,isAbsolute as J,resolve as j}from"path";import*as V from"os";import*as H from"path";function R(){let B=L(),q=G(B);return{workingDirectory:B,projectRoot:q,platform:`${V.platform()} (${V.arch()})`,nodeVersion:process.version,currentDate:new Date().toISOString().split("T")[0],homeDirectory:V.homedir()}}function X(B,q){try{return T(q,{cwd:B,encoding:"utf8",stdio:["pipe","pipe","ignore"]}).trim()}catch{return null}}function S(B={}){let{includeGitSnapshot:q=!0,includeDirectoryListing:M=!0}=B,z=R(),Z=Q(H.join(z.projectRoot,".git")),_=b(process.env.SHELL||"unknown"),$=["package.json","tsconfig.json","BLADE.md",".env.example"].filter((K)=>Q(H.join(z.projectRoot,K))).map((K)=>`- \`${H.join(z.projectRoot,K)}\``),N=`# Environment
|
|
2
|
+
You have been invoked in the following environment:
|
|
3
|
+
- Primary working directory: ${z.workingDirectory}
|
|
4
|
+
- Is a git repository: ${Z?"true":"false"}
|
|
5
|
+
- Platform: ${z.platform}
|
|
6
|
+
- Shell: ${_}
|
|
7
|
+
- Node.js: ${z.nodeVersion}`;if(q&&Z){let K=X(z.projectRoot,"git rev-parse --abbrev-ref HEAD"),Y=X(z.projectRoot,"git status --short"),U=X(z.projectRoot,"git log --oneline -n 3");if(K)N+=`
|
|
8
|
+
- Current branch: ${K}`;if(Y)N+=`
|
|
9
|
+
|
|
10
|
+
Working tree status:
|
|
11
|
+
${Y}`;if(U)N+=`
|
|
12
|
+
|
|
13
|
+
Recent commits:
|
|
14
|
+
${U}`}if(N+=`
|
|
15
|
+
|
|
16
|
+
When using file tools (read, write, edit), provide absolute paths based on: \`${z.workingDirectory}/\``,$.length>0)N+=`
|
|
17
|
+
|
|
18
|
+
Key project files at root for quick reference:
|
|
19
|
+
${$.join(`
|
|
20
|
+
`)}`;let A=H.join(z.projectRoot,"package.json");if(Q(A))try{let K=F(A,"utf-8"),U=JSON.parse(K).scripts;if(U){let E=["test","lint","type-check","build","dev","start"].filter((W)=>U[W]).map((W)=>` ${W}: ${U[W].slice(0,60)}`);if(E.length>0)N+=`
|
|
21
|
+
|
|
22
|
+
Available npm scripts:
|
|
23
|
+
${E.join(`
|
|
24
|
+
`)}`}}catch{}if(M){let K=X(z.projectRoot,"ls -1 | head -30");if(K)N+=`
|
|
25
|
+
|
|
26
|
+
Project root directory listing:
|
|
27
|
+
${K}`}return N}function G(B){let q=B,M=null;while(q!==H.dirname(q)){if(Q(H.join(q,".git")))return q;if(Q(H.join(q,".blade")))return q;if(Q(H.join(q,".claude")))return q;if(!M&&Q(H.join(q,"package.json")))M=q;q=H.dirname(q)}return M??B}function g(B,q){let M=J(B)?B:j(q||process.cwd(),B),z;try{z=O(M)}catch{z=M}I(z)}
|
|
28
|
+
export{S as Z,G as _,g as $};
|
|
@@ -1,12 +1,22 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{ub as B0}from"./chunk-3w1zqywq.js";import{yb as KQ}from"./chunk-v0z4bwcv.js";import{Eb as k}from"./chunk-wre40mf1.js";import{Ib as R}from"./chunk-ktag2d1c.js";import{Kb as QQ}from"./chunk-s53zeref.js";function X0(Q){return Q.role==="system"&&Array.isArray(Q.content)}class H0{systemMessages;_history;_pending=[];context;constructor(Q,Z){this.context=Q;let $=Q.messages.find(X0);if($)this.systemMessages=[$];else if(Z)this.systemMessages=[{role:"system",content:[{type:"text",text:Z,providerOptions:{anthropic:{cacheControl:{type:"ephemeral"}}}}]}];else this.systemMessages=[];this._history=Q.messages.filter((J)=>!X0(J))}get historyLength(){return this._history.length}get history(){return this._history}get pending(){return this._pending}toLLMMessages(){return[...this.systemMessages,...this._history,...this._pending]}getMessagesForLLM(){return this.toLLMMessages()}getHistory(){return this._history}appendPending(Q){this._pending.push(Q)}appendUser(Q){this._pending.push(Q)}appendAssistant(Q){this._pending.push(Q)}appendToolResult(Q){this._pending.push(Q)}appendControl(Q,Z){if(Q==="system")throw Error("Cannot append system control message via appendControl. Use constructor for root system prompt.");this._pending.push(Z)}appendToHistory(Q){this._history.push(Q)}commitPending(){if(this._pending.length>0)this._history.push(...this._pending),this._pending=[]}replaceHistory(Q){this._history=Q.filter((Z)=>!X0(Z))}writeback(){this.commitPending(),this.context.messages=this._history}get hasSystemPrompt(){return this.systemMessages.length>0}}async function cQ(Q,Z){let $;while(!($=await Q.next()).done)if(Z)await Z($.value);return $.value}function r0(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 o0(Q){return{budget:Q.budget,usage:0,consecutiveContinuations:0,lastOutputDelta:0,isSubagent:Q.isSubagent??!1}}function s0(Q,Z,$){return{...Q,usage:Q.usage+Z,lastOutputDelta:Z,consecutiveContinuations:$?Q.consecutiveContinuations+1:0}}var e=R("Agent"),iQ=3;function M0(Q,Z,$){if(Q!=="length")return{action:"none"};if(Z>=iQ)return{action:"truncated"};if(r0($)==="stop")return e.info("[Loop] Token budget: diminishing returns detected, skipping recovery"),{action:"budget_stop"};return{action:"recover"}}var nQ=[/:\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],lQ=/```[\s\S]{50,}```/,t0="请执行你提到的操作,不要只是描述。使用 Edit/Write/Bash 工具来实际修改文件。",aQ=2;function P0(Q,Z,$=!0){if(!Q||Z>=aQ)return{action:"none"};if(!$&&lQ.test(Q))return{action:"retry",prompt:t0};let J=Q.slice(-200),q=J.match(/```/g);if(q&&q.length%2!==0)return{action:"none"};if(nQ.some((G)=>G.test(J)))return{action:"retry",prompt:t0};return{action:"none"}}var e0=30000;async function f0(Q){try{let $=B0.getInstance().executeStopHooks({projectDir:k(),sessionId:Q.sessionId,permissionMode:Q.permissionMode,reason:Q.reason,abortSignal:Q.abortSignal}),J,q=new Promise((z)=>{J=setTimeout(()=>z("timeout"),e0)});try{let z=await Promise.race([$,q]);if(z==="timeout")return e.warn(`[Loop] Stop hook 超时 (${e0}ms),按 shouldStop: true 处理`),{action:"stop"};let G=z;if(!G.shouldStop)return{action:"continue",reason:G.continueReason};return{action:"stop"}}finally{clearTimeout(J)}}catch(Z){return e.warn("[Loop] Stop hook execution failed:",Z),{action:"stop"}}}var rQ=0.9;async function ZQ(Q){try{let{SpecManager:Z}=await import("./chunk-mganjb5p.js"),$=Z.getInstance();if(!$.isActive())return{action:"none"};let J=$.getCurrentSpec();if(!J||J.phase!=="implementation")return{action:"none"};if(Q.maxTurns>0&&Q.turnsCount>=Q.maxTurns*rQ)return e.info(`[RalphLoop] 轮次接近上限 (${Q.turnsCount}/${Q.maxTurns}),停止自动继续`),{action:"none"};let q=J.tasks??[],z=q.filter((B)=>B.status==="completed"||B.status==="skipped").length,G=q.length;if(z>=G)return{action:"none"};let V=q.find((B)=>B.status==="pending"||B.status==="in_progress"),W=`[Ralph Loop] Spec "${J.name}" 仍有未完成任务。
|
|
2
2
|
`+`进度: ${z}/${G} 任务已完成。
|
|
3
3
|
`+(V?`下一个任务: ${V.title}${V.description?` — ${V.description}`:""}
|
|
4
|
-
`:"")+"请继续执行下一个未完成的任务,不要停止。";return
|
|
5
|
-
`)
|
|
4
|
+
`:"")+"请继续执行下一个未完成的任务,不要停止。";return e.info(`[RalphLoop] Spec "${J.name}" 进度 ${z}/${G},自动继续`),{action:"continue",reason:W}}catch{return{action:"none"}}}var Z0=R("Agent");function $0(Q){return Q.executionEngine?.getContextManager()}async function u(Q,Z,$,J=null){try{let q=$0(Q),z=typeof $==="string"?$.trim()!=="":$.some((G)=>G.type==="text"?G.text.trim()!=="":!0);if(q&&Z.sessionId&&z)return await q.saveMessage(Z.sessionId,"user",$,J,void 0,Z.subagentInfo)}catch(q){Z0.warn("[Loop] 保存用户消息失败:",q)}return null}async function p(Q,Z,$,J){try{let q=$0(Q);if(q&&Z.sessionId&&$.trim())return await q.saveMessage(Z.sessionId,"assistant",$,J,void 0,Z.subagentInfo)}catch(q){Z0.warn("[Loop] 保存助手消息失败:",q)}return null}async function R0(Q,Z,$,J,q){try{let z=$0(Q);if(z&&Z.sessionId)return await z.saveToolUse(Z.sessionId,$,J,q,Z.subagentInfo)}catch(z){Z0.warn("[Loop] 保存工具调用失败:",z)}return null}async function T0(Q,Z,$,J,q,z,G,V){try{let W=$0(Q);if(W&&Z.sessionId)return await W.saveToolResult(Z.sessionId,$,J,q,z,G,Z.subagentInfo,V)}catch(W){Z0.warn("[Loop] 保存工具结果失败:",W)}return null}async function D0(Q,Z,$,J){try{let q=$0(Q);if(q&&Z.sessionId)return await q.saveCompaction(Z.sessionId,$,J,null)}catch(q){Z0.warn("[Loop] 保存压缩数据失败:",q)}return null}function $Q(Q,Z){if(!["TaskCreate","TaskUpdate","TaskList"].includes(Q.function.name)||!Z.success||!Z.llmContent&&!Z.metadata)return null;let $=typeof Z.llmContent==="object"?Z.llmContent:{};return{kind:"task_update",tasks:Z.metadata?.tasks||$.tasks||[]}}function JQ(Q,Z,$){if(Q.function.name!=="Skill"||!Z.success||!Z.metadata)return;let J=Z.metadata;if(J.skillName)$.onSkillActivated?.({skillName:J.skillName,allowedTools:J.allowedTools,basePath:J.basePath||""})}function qQ(Q){let Z=Q.metadata;if(!Z)return;return Z.modelId?.toString().trim()||Z.model?.toString().trim()||void 0||void 0}function oQ(Q,Z){if(Q.function.name!=="Task")return null;let $=Z.metadata;if(!$?.subagentSessionId)return null;let J=$.subagentSessionId,q=$.subagentType||"Task",z=$.subagentStatus;if(z==="completed"||z==="failed"||z==="cancelled")return{kind:"subagent_completed",sessionId:J,success:z==="completed",summary:$.subagentSummary};if(z==="running"){let G="";try{G=JSON.parse(Q.function.arguments).prompt||""}catch{}return{kind:"subagent_spawned",sessionId:J,type:q,prompt:G}}return null}async function k0(Q,Z,$){let J=$Q(Q,Z),q=oQ(Q,Z);JQ(Q,Z,$);let z=qQ(Z);if(z)await $.onModelSwitch?.(z);return q||J}import{nanoid as RZ}from"nanoid";import{nanoid as l}from"nanoid";import{promises as VZ}from"node:fs";import*as N from"node:fs/promises";import*as i from"node:path";import{execSync as sQ}from"node:child_process";import*as x0 from"node:os";import*as c from"node:path";function tQ(Q){return c.resolve(Q).replace(/[/\\]/g,"-").replace(/:/g,"_")}function W2(Q){let Z=Q.replace(/_/g,":");if(Z.startsWith("-"))Z="/"+Z.slice(1);return Z.replace(/-/g,"/")}function h0(Q){let Z=x0.homedir(),$=tQ(Q);return c.join(Z,".blade","projects",$)}function Y2(Q,Z){return c.join(h0(Q),`${Z}.jsonl`)}function K2(Q){try{return sQ("git rev-parse --abbrev-ref HEAD",{cwd:Q,encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim()||void 0}catch{return}}function eQ(){return c.join(x0.homedir(),".blade")}async function X2(){let{readdir:Q}=await import("node:fs/promises");try{let Z=c.join(eQ(),"projects");return(await Q(Z,{withFileTypes:!0})).filter((J)=>J.isDirectory()).map((J)=>J.name)}catch{return[]}}var zQ={enabled:!0,maxIndexLines:200};var QZ="memory",GQ="MEMORY.md";class C0{memoryDir;config;initialized=!1;constructor(Q,Z,$){if($)this.memoryDir=$;else{let J=h0(Q);this.memoryDir=i.join(J,QZ)}this.config={...zQ,...Z}}async initialize(){if(this.initialized)return;await N.mkdir(this.memoryDir,{recursive:!0}),this.initialized=!0}async loadIndex(){if(!this.config.enabled)return null;await this.initialize();let Q=i.join(this.memoryDir,GQ);try{let Z=await N.readFile(Q,"utf-8");if(!Z.trim())return null;let $=Z.split(`
|
|
5
|
+
`),q=$.slice(0,this.config.maxIndexLines).join(`
|
|
6
|
+
`).trim();if($.length>this.config.maxIndexLines)return q+`
|
|
7
|
+
|
|
8
|
+
<!-- ${$.length-this.config.maxIndexLines} more lines in MEMORY.md, use MemoryRead to access -->`;return q||null}catch(Z){if(Z instanceof Error&&"code"in Z&&Z.code==="ENOENT")return null;throw Z}}async readTopic(Q){await this.initialize();let Z=this.resolveTopicPath(Q);try{return await N.readFile(Z,"utf-8")||null}catch($){if($ instanceof Error&&"code"in $&&$.code==="ENOENT")return null;throw $}}async writeTopic(Q,Z,$="append"){await this.initialize();let J=this.resolveTopicPath(Q);if($==="append"){let q="";try{q=await N.readFile(J,"utf-8")}catch{}let z=q&&!q.endsWith(`
|
|
9
|
+
`)?`
|
|
10
|
+
`:"";await N.writeFile(J,q+z+Z,"utf-8")}else await N.writeFile(J,Z,"utf-8")}async updateIndex(Q,Z="overwrite"){await this.initialize();let $=i.join(this.memoryDir,GQ);if(Z==="append"){let J="";try{J=await N.readFile($,"utf-8")}catch{}let q=J&&!J.endsWith(`
|
|
11
|
+
`)?`
|
|
12
|
+
`:"";await N.writeFile($,J+q+Q,"utf-8")}else await N.writeFile($,Q,"utf-8")}async listTopics(){await this.initialize();try{let Q=await N.readdir(this.memoryDir,{withFileTypes:!0}),Z=[];for(let $ of Q){if(!$.isFile()||!$.name.endsWith(".md"))continue;let J=i.join(this.memoryDir,$.name),q=await N.stat(J);Z.push({name:$.name.replace(/\.md$/,""),size:q.size,lastModified:q.mtime})}return Z.sort(($,J)=>J.lastModified.getTime()-$.lastModified.getTime())}catch{return[]}}async deleteTopic(Q){let Z=this.resolveTopicPath(Q);try{return await N.unlink(Z),!0}catch{return!1}}async clearAll(){let Q=await this.listTopics(),Z=0;for(let $ of Q){let J=i.join(this.memoryDir,`${$.name}.md`);try{await N.unlink(J),Z++}catch{}}return Z}getMemoryDir(){return this.memoryDir}resolveTopicPath(Q){let Z=Q.replace(/[/\\:*?"<>|]/g,"-"),$=Z.endsWith(".md")?Z:`${Z}.md`,J=i.join(this.memoryDir,$);if(!J.startsWith(this.memoryDir))throw Error(`Invalid topic name: ${Q}`);return J}}var ZZ=[{pattern:/(?:记住|remember|note|备注)[::](.+)/i,topic:"preferences"},{pattern:/(?:convention|约定|规范)[::](.+)/i,topic:"conventions"},{pattern:/(?:lesson|教训|踩坑)[::](.+)/i,topic:"lessons"}],$Z=/(?:fix|修复|解决|resolved)[::]\s*(.+?)(?:\n|$)/i,JZ=/(?:Error|FAIL|错误)[::]\s*(.+?)(?:\n|$)/i;function qZ(Q){let Z=new Map;for(let $ of Q){if(!$.content||typeof $.content!=="string")continue;let J=$.content;if($.role==="user")for(let{pattern:q,topic:z}of ZZ){let G=J.match(q);if(G?.[1]){let V=Z.get(z)??[];V.push(G[1].trim()),Z.set(z,V)}}if($.role==="assistant"){let q=J.match($Z);if(q?.[1]&&q[1].length>20&&q[1].length<200){let z=Z.get("debugging")??[];z.push(q[1].trim()),Z.set("debugging",z)}}if($.role==="tool"&&$.content?.includes("Error")){let q=J.match(JZ);if(q?.[1]&&q[1].length>10){let z=Z.get("debugging")??[];if(z.length<5)z.push(`Tool error pattern: ${q[1].trim().slice(0,150)}`),Z.set("debugging",z)}}}return Z}async function VQ(Q){let Z=qZ(Q);if(Z.size===0)return{extracted:0,topics:[]};try{let $=new C0(k());await $.initialize();let J=[],q=0;for(let[z,G]of Z){if(G.length===0)continue;let V=new Date().toISOString().split("T")[0],W=G.map((B)=>`- [${V}] ${B}`).join(`
|
|
13
|
+
`);await $.writeTopic(z,W+`
|
|
14
|
+
`,"append"),J.push(z),q+=G.length}return{extracted:q,topics:J}}catch{return{extracted:0,topics:[]}}}import{promises as j0}from"node:fs";var J0=R("Tool");class d{static instance=null;accessedFiles=new Map;constructor(){}static getInstance(){if(!d.instance)d.instance=new d;return d.instance}async recordFileRead(Q,Z){try{let $=await j0.stat(Q),J={filePath:Q,accessTime:Date.now(),mtime:$.mtimeMs,sessionId:Z,lastOperation:"read"};this.accessedFiles.set(Q,J),J0.debug(`记录文件读取: ${Q}`)}catch($){J0.warn(`记录文件读取失败: ${Q}`,$)}}async recordFileEdit(Q,Z,$="edit"){try{let J=await j0.stat(Q),q={filePath:Q,accessTime:Date.now(),mtime:J.mtimeMs,sessionId:Z,lastOperation:$};this.accessedFiles.set(Q,q),J0.debug(`记录文件${$==="edit"?"编辑":"写入"}: ${Q}`)}catch(J){J0.warn(`记录文件${$==="edit"?"编辑":"写入"}失败: ${Q}`,J)}}hasFileBeenRead(Q,Z){let $=this.accessedFiles.get(Q);if(!$)return!1;if(Z&&$.sessionId!==Z)return!1;return!0}async checkFileModification(Q){let Z=this.accessedFiles.get(Q);if(!Z)return{modified:!1,message:"文件未被跟踪"};try{let $=await j0.stat(Q);if(Math.abs($.mtimeMs-Z.mtime)>1)return{modified:!0,message:`文件在访问后被修改(访问时间: ${new Date(Z.accessTime).toISOString()}, 当前修改时间: ${$.mtime.toISOString()})`};return{modified:!1}}catch($){let J=$;if(J.code==="ENOENT")return{modified:!0,message:"文件已被删除"};return{modified:!1,message:`无法检查文件状态: ${J.message}`}}}async checkExternalModification(Q){let Z=this.accessedFiles.get(Q);if(!Z)return{isExternal:!1,message:"文件未被跟踪"};try{let $=await j0.stat(Q);if($.mtimeMs-Z.mtime>2000)return{isExternal:!0,message:`文件在 ${new Date(Z.accessTime).toISOString()} (${Z.lastOperation}) 之后被外部程序修改(当前修改时间: ${$.mtime.toISOString()})`};return{isExternal:!1}}catch($){let J=$;if(J.code==="ENOENT")return{isExternal:!0,message:"文件已被删除"};return J0.warn(`检查文件外部修改失败: ${Q}`,$),{isExternal:!1,message:`无法检查文件状态: ${J.message}`}}}getFileRecord(Q){return this.accessedFiles.get(Q)}clearFileRecord(Q){this.accessedFiles.delete(Q)}clearAll(){this.accessedFiles.clear()}clearSession(Q){for(let[Z,$]of this.accessedFiles.entries())if($.sessionId===Q)this.accessedFiles.delete(Z)}getTrackedFiles(){return Array.from(this.accessedFiles.keys())}getTrackedFileCount(){return this.accessedFiles.size}static resetInstance(){d.instance=null}}function n(Q){if(!(Q instanceof Error))return!1;if(Q.name==="AbortError")return!0;if(Q instanceof DOMException&&Q.name==="AbortError")return!0;if(Q.message.includes("aborted"))return!0;return!1}function WQ(...Q){let Z=Q.filter(Boolean);if(Z.length===0)return new AbortController().signal;if(Z.length===1)return Z[0];let $=AbortSignal;if(typeof $.any==="function")return $.any(Z);for(let z of Z)if(z.aborted)return z;let J=new AbortController,q=new Map;for(let z of Z){let G=()=>{J.abort(z.reason);for(let[V,W]of q)V.removeEventListener("abort",W)};q.set(z,G)}for(let[z,G]of q)z.addEventListener("abort",G,{once:!0});return J.signal}import{readFile as zZ}from"node:fs/promises";import{basename as GZ}from"node:path";class w0{static MAX_FILES=5;static MAX_LINES_PER_FILE=1000;static analyzeFiles(Q){let Z=new Map;return Q.forEach((J,q)=>{let z=typeof J.content==="string"?J.content:(J.content||[]).filter((V)=>V.type==="text").map((V)=>V.text).join(`
|
|
15
|
+
`);if(this.extractFilePathsFromContent(z).forEach((V)=>{this.updateFileReference(Z,V,q,!1)}),J.tool_calls&&Array.isArray(J.tool_calls))J.tool_calls.forEach((V)=>{let W=this.extractFilePathsFromToolCall(V),B=V.type==="function"&&"function"in V?V.function?.name:"",F=["Write","Edit"].includes(B||"");W.forEach((L)=>{this.updateFileReference(Z,L,q,F)})})}),Array.from(Z.values()).sort((J,q)=>{if(J.wasModified!==q.wasModified)return J.wasModified?-1:1;if(J.mentions!==q.mentions)return q.mentions-J.mentions;return q.lastMentioned-J.lastMentioned}).slice(0,this.MAX_FILES)}static async readFilesContent(Q){let Z=[];for(let $ of Q)try{let J=await zZ($,"utf-8"),q=J.split(`
|
|
6
16
|
`),z=q.length,G=J,V=!1,W=z;if(z>this.MAX_LINES_PER_FILE)G=q.slice(0,this.MAX_LINES_PER_FILE).join(`
|
|
7
17
|
`),G+=`
|
|
8
18
|
|
|
9
|
-
... (truncated ${z-this.MAX_LINES_PER_FILE} lines)`,V=!0,W=this.MAX_LINES_PER_FILE;Z.push({path:$,content:G,truncated:V,lines:z,includedLines:W})}catch(J){console.warn(`[FileAnalyzer] 无法读取文件: ${$}`,J)}return Z}static extractFilePathsFromContent(Q){let Z=new Set,$=/```(?:\w+)?\s*\n?([\s\S]*?)```/g,J=Array.from(Q.matchAll($));for(let z of J){let G=z[1];this.extractPathsFromText(G).forEach((W)=>Z.add(W))}return this.extractPathsFromText(Q).forEach((z)=>Z.add(z)),Array.from(Z)}static extractPathsFromText(Q){let Z=[],$=[/(?:src|tests?|docs?|lib|config|scripts?|bin|utils?|components?|services?|hooks?)\/[\w\-/.]+\.[\w]+/g,/(?:package|tsconfig|vite\.config|webpack\.config|next\.config|babel\.config)\.[\w]+/g,/(?:\.\.?\/|\/)[a-zA-Z0-9\-_/.]+\.[\w]+/g];for(let J of $){let q=Array.from(Q.matchAll(J));for(let z of q){let G=z[0];if(G=G.replace(/[,。;:!?""''()【】《》]$/g,""),G=G.replace(/[,.;:!?"'()[\]<>]$/g,""),this.isValidFilePath(G))Z.push(G)}}return Z}static extractFilePathsFromToolCall(Q){let Z=[];if(Q.type!=="function"||!Q.function)return Z;try{let $=Q.function.name,J=JSON.parse(Q.function.arguments||"{}");if(["Read","Write","Edit","Glob","Grep","NotebookEdit","mcp__github__get_file_contents","mcp__github__create_or_update_file"].includes($)){let z=["file_path","path","notebook_path","filePath"];for(let G of z)if(J[G]&&typeof J[G]==="string")Z.push(J[G])}}catch{}return Z}static updateFileReference(Q,Z,$,J){let q=Q.get(Z);if(q)q.mentions++,q.lastMentioned=$,q.wasModified=q.wasModified||J;else Q.set(Z,{path:Z,mentions:1,lastMentioned:$,wasModified:J})}static isValidFilePath(Q){if(!Q.includes("/"))return!1;let Z=
|
|
19
|
+
... (truncated ${z-this.MAX_LINES_PER_FILE} lines)`,V=!0,W=this.MAX_LINES_PER_FILE;Z.push({path:$,content:G,truncated:V,lines:z,includedLines:W})}catch(J){console.warn(`[FileAnalyzer] 无法读取文件: ${$}`,J)}return Z}static extractFilePathsFromContent(Q){let Z=new Set,$=/```(?:\w+)?\s*\n?([\s\S]*?)```/g,J=Array.from(Q.matchAll($));for(let z of J){let G=z[1];this.extractPathsFromText(G).forEach((W)=>Z.add(W))}return this.extractPathsFromText(Q).forEach((z)=>Z.add(z)),Array.from(Z)}static extractPathsFromText(Q){let Z=[],$=[/(?:src|tests?|docs?|lib|config|scripts?|bin|utils?|components?|services?|hooks?)\/[\w\-/.]+\.[\w]+/g,/(?:package|tsconfig|vite\.config|webpack\.config|next\.config|babel\.config)\.[\w]+/g,/(?:\.\.?\/|\/)[a-zA-Z0-9\-_/.]+\.[\w]+/g];for(let J of $){let q=Array.from(Q.matchAll(J));for(let z of q){let G=z[0];if(G=G.replace(/[,。;:!?""''()【】《》]$/g,""),G=G.replace(/[,.;:!?"'()[\]<>]$/g,""),this.isValidFilePath(G))Z.push(G)}}return Z}static extractFilePathsFromToolCall(Q){let Z=[];if(Q.type!=="function"||!Q.function)return Z;try{let $=Q.function.name,J=JSON.parse(Q.function.arguments||"{}");if(["Read","Write","Edit","Glob","Grep","NotebookEdit","mcp__github__get_file_contents","mcp__github__create_or_update_file"].includes($)){let z=["file_path","path","notebook_path","filePath"];for(let G of z)if(J[G]&&typeof J[G]==="string")Z.push(J[G])}}catch{}return Z}static updateFileReference(Q,Z,$,J){let q=Q.get(Z);if(q)q.mentions++,q.lastMentioned=$,q.wasModified=q.wasModified||J;else Q.set(Z,{path:Z,mentions:1,lastMentioned:$,wasModified:J})}static isValidFilePath(Q){if(!Q.includes("/"))return!1;let Z=GZ(Q);if(!Z.includes("."))return!1;let $=["ts","tsx","js","jsx","json","md","py","java","go","rs","c","cpp","h","css","scss","html","xml","yaml","yml","toml","sh","bash","sql","graphql","vue","svelte"],J=Z.split(".").pop()?.toLowerCase();if(!J||!$.includes(J))return!1;return!0}}import{encodingForModel as YQ}from"js-tiktoken";class q0{static encodingCache=new Map;static countTokens(Q,Z){let $=this.getEncoding(Z),J=0;for(let q of Q){if(J+=4,q.role)J+=$.encode(q.role).length;if(q.content)if(typeof q.content==="string")J+=$.encode(q.content).length;else J+=$.encode(JSON.stringify(q.content)).length;if(q.tool_calls&&Array.isArray(q.tool_calls))J+=this.countToolCallTokens(q.tool_calls,$);if(q.name)J+=$.encode(q.name).length}return J}static getTokenLimit(Q){return Q}static shouldCompact(Q,Z,$,J=0.8){let q=this.countTokens(Q,Z),z=Math.floor($*J);return q>=z}static getEncoding(Q){if(!this.encodingCache.has(Q))try{let Z=YQ(Q);this.encodingCache.set(Q,Z)}catch{try{let Z=YQ("gpt-4");this.encodingCache.set(Q,Z)}catch{console.warn(`[TokenCounter] 无法为模型 ${Q} 获取 encoding,使用粗略估算`),this.encodingCache.set(Q,{encode:(Z)=>{return Array(Math.ceil(Z.length/4))}})}}return this.encodingCache.get(Q)}static countToolCallTokens(Q,Z){let $=0;for(let J of Q){if($+=4,J.type==="function"&&J.function?.name)$+=Z.encode(J.function.name).length;if(J.type==="function"&&J.function?.arguments)$+=Z.encode(J.function.arguments).length;if(J.id)$+=Z.encode(J.id).length}return $}static clearCache(){this.encodingCache.clear()}static estimateTokens(Q){let Z=(Q.match(/[\u4e00-\u9fa5]/g)||[]).length,$=Q.length-Z;return Math.ceil(Z/1.5+$/4)}}var F0=new Map,WZ=3;class r{static THRESHOLD_PERCENT=0.8;static RETAIN_PERCENT=0.2;static FALLBACK_RETAIN_PERCENT=0.3;static async compact(Q,Z){if(Z.signal?.aborted)throw new DOMException("Aborted","AbortError");let $=Z.actualPreTokens??q0.countTokens(Q,Z.modelName),J=Z.actualPreTokens?"actual (from LLM usage)":"estimated";console.log(`[CompactionService] preTokens source: ${J}`);try{let V=await B0.getInstance().executeCompactionHooks(Z.trigger,{projectDir:k(),sessionId:Z.sessionId||"unknown",permissionMode:Z.permissionMode||"default",messagesBefore:Q.length,tokensBefore:$});if(V.blockCompaction)return console.log(`[CompactionService] Compaction hook 阻止压缩: ${V.blockReason||"(无原因)"}`),{success:!1,summary:"",preTokens:$,postTokens:$,filesIncluded:[],compactedMessages:Q,boundaryMessage:{role:"system",content:""},summaryMessage:{role:"user",content:""},error:V.blockReason||"Compaction blocked by hook"};if(V.warning)console.warn(`[CompactionService] Compaction hook warning: ${V.warning}`)}catch(G){console.warn("[CompactionService] Compaction hook execution failed:",G)}let q=Z.sessionId??"_default",z=F0.get(q)??0;if(z>=WZ)return console.warn(`[CompactionService] Circuit breaker open (${z} consecutive failures for session ${q}), using fallback`),this.fallbackCompact(Q,Z,$,Error("Circuit breaker open"));try{console.log("[CompactionService] 开始压缩,消息数:",Q.length),console.log("[CompactionService] 压缩前 tokens:",$);let V=w0.analyzeFiles(Q).map((M)=>M.path);console.log("[CompactionService] 提取重点文件:",V);let W=await w0.readFilesContent(V);console.log("[CompactionService] 成功读取文件:",W.length);let B=await this.generateSummary(Q,W,Z);console.log("[CompactionService] 生成总结,长度:",B.length);let F=Math.ceil(Q.length*this.RETAIN_PERCENT),L=Q.slice(-F),Y=new Set;for(let M of L)if(M.role==="assistant"&&M.tool_calls)for(let m of M.tool_calls)Y.add(m.id);let b=L.filter((M)=>{if(M.role==="tool"&&M.tool_call_id)return Y.has(M.tool_call_id);return!0});console.log("[CompactionService] 保留消息数:",F),console.log("[CompactionService] 过滤后保留消息数:",b.length);let E=l(),D=this.createBoundaryMessage(E,Z.trigger,$),K=l(),f=this.createSummaryMessage(K,B),x=[f,...b],C=await this.buildFileRestorationMessage();if(C)x.push(C);let T=q0.countTokens(x,Z.modelName);console.log("[CompactionService] 压缩完成!"),console.log("[CompactionService] Token 变化:",$,"->",T,`(-${((1-T/$)*100).toFixed(1)}%)`),F0.delete(q);let s=Q.slice(0,Q.length-F);return VQ(s).catch((M)=>{return}),{success:!0,summary:B,preTokens:$,postTokens:T,filesIncluded:V,compactedMessages:x,boundaryMessage:D,summaryMessage:f}}catch(G){if(n(G))throw G;return F0.set(q,(F0.get(q)??0)+1),console.error("[CompactionService] 压缩失败,使用降级策略",G),this.fallbackCompact(Q,Z,$,G)}}static async generateSummary(Q,Z,$){let J=this.buildCompactionPrompt(Q,Z);if(console.log("[CompactionService] 使用压缩模型:",$.modelName),$.signal?.aborted)throw new DOMException("Aborted","AbortError");let G=(await(await KQ({apiKey:$.apiKey||process.env.BLADE_API_KEY||"",baseUrl:$.baseURL||process.env.BLADE_BASE_URL||"https://api.openai.com/v1",model:$.modelName,temperature:0.3,maxOutputTokens:8000,timeout:60000,provider:"openai-compatible"})).chat([{role:"user",content:J}],[],$.signal)).content||"",V=G.match(/<summary>([\s\S]*?)<\/summary>/);if(!V)return console.warn("[CompactionService] 总结格式不正确,使用完整响应"),G;return V[1].trim()}static buildCompactionPrompt(Q,Z){let $=Q.map((z,G)=>{let V=z.role||"unknown",W=typeof z.content==="string"?z.content:JSON.stringify(z.content),B=5000,F=W.length>5000?W.substring(0,5000)+"...":W;return`[${G+1}] ${V}: ${F}`}).join(`
|
|
10
20
|
|
|
11
21
|
`),J=Z.map((z)=>{return`### ${z.path}
|
|
12
22
|
\`\`\`
|
|
@@ -79,32 +89,32 @@ ${Z.length>0?`## Important Files
|
|
|
79
89
|
|
|
80
90
|
${J}`:""}
|
|
81
91
|
|
|
82
|
-
Please provide your summary following the structure specified above, with both <analysis> and <summary> sections.`}static createBoundaryMessage(Q,Z,$){return{id:
|
|
92
|
+
Please provide your summary following the structure specified above, with both <analysis> and <summary> sections.`}static createBoundaryMessage(Q,Z,$){return{id:l(),role:"system",content:"Conversation compacted",metadata:{type:"system",subtype:"compact_boundary",parentId:Q,compactMetadata:{trigger:Z,preTokens:$}}}}static createSummaryMessage(Q,Z){return{id:l(),role:"user",content:Z,metadata:{parentId:Q,isCompactSummary:!0}}}static getRecentlyAccessedFiles(Q){let Z=d.getInstance();return Z.getTrackedFiles().map((q)=>({filePath:q,record:Z.getFileRecord(q)})).filter((q)=>q.record!==void 0).sort((q,z)=>z.record.accessTime-q.record.accessTime).slice(0,Q).map((q)=>q.filePath)}static async buildFileRestorationMessage(){let Q=this.getRecentlyAccessedFiles(5);if(Q.length===0)return null;let Z=[];for(let J of Q)try{let z=(await VZ.readFile(J,"utf-8")).split(`
|
|
83
93
|
`),G=z.slice(0,200).join(`
|
|
84
94
|
`),V=z.length>200?`
|
|
85
95
|
... (${z.length-200} more lines)`:"";Z.push(`<file path="${J}" lines="${z.length}">
|
|
86
96
|
${G}${V}
|
|
87
97
|
</file>`)}catch{}if(Z.length===0)return null;let $=["<system-reminder>","Post-compaction file restoration. These files were recently accessed in the conversation:",...Z,"</system-reminder>"].join(`
|
|
88
|
-
`);return console.log("[CompactionService] Post-compact 恢复文件:",Q.length),{id:
|
|
98
|
+
`);return console.log("[CompactionService] Post-compact 恢复文件:",Q.length),{id:l(),role:"user",content:$,metadata:{isPostCompactRestoration:!0}}}static fallbackCompact(Q,Z,$,J){let q=Math.ceil(Q.length*this.FALLBACK_RETAIN_PERCENT),z=Q.slice(-q),G=new Set;for(let D of z)if(D.role==="assistant"&&D.tool_calls)for(let K of D.tool_calls)G.add(K.id);let V=z.filter((D)=>{if(D.role==="tool"&&D.tool_call_id)return G.has(D.tool_call_id);return!0}),W=l(),B=this.createBoundaryMessage(W,Z.trigger,$),F=J instanceof Error?J.message:String(J),L=l(),Y=this.createSummaryMessage(L,`[Automatic compaction failed; using fallback]
|
|
89
99
|
|
|
90
100
|
An error occurred during compaction. Retained the latest ${q} messages (~30%).
|
|
91
101
|
|
|
92
102
|
Error: ${F}
|
|
93
103
|
|
|
94
|
-
The conversation can continue, but consider retrying compaction later with /compact.`),
|
|
95
|
-
`),preTokens:$,postTokens:E,filesIncluded:[],compactedMessages:
|
|
104
|
+
The conversation can continue, but consider retrying compaction later with /compact.`),b=[Y,...V],E=q0.countTokens(b,Z.modelName);return{success:!1,summary:typeof Y.content==="string"?Y.content:Y.content.filter((D)=>D.type==="text").map((D)=>D.text).join(`
|
|
105
|
+
`),preTokens:$,postTokens:E,filesIncluded:[],compactedMessages:b,boundaryMessage:B,summaryMessage:Y,error:F}}}var YZ=new Set(["Read","Grep","Glob","Search","WebSearch","WebFetch","ToolSearch"]);function KZ(Q,Z){let q=(Q[Z.assistantIdx].tool_calls??[]).filter((G)=>G.type==="function").map((G)=>G.function.name).some((G)=>!YZ.has(G));if(Z.toolResultIdxs.some((G)=>{let V=Q[G]?.content;if(typeof V!=="string")return!1;return V.startsWith("Error:")||V.includes("failed")||V.includes("ENOENT")}))return 3;if(q)return 2;return 1}function z0(Q,Z){let $=Z?.keepRecentTurns??10,J=Z?.minMessagesForSnip??30;if(Q.length<J)return{messages:Q,snippedCount:0,estimatedTokensFreed:0};let q=[];for(let Y=0;Y<Q.length;Y++){let b=Q[Y];if(b.role==="assistant"&&b.tool_calls&&b.tool_calls.length>0){let E=new Set(b.tool_calls.map((K)=>K.id)),D=[];for(let K=Y+1;K<Q.length;K++){let f=Q[K];if(f.role==="tool"&&f.tool_call_id&&E.has(f.tool_call_id))D.push(K);if(f.role==="assistant"||f.role==="user")break}q.push({assistantIdx:Y,toolResultIdxs:D,priority:0})}}for(let Y of q)Y.priority=KZ(Q,Y);let V=[...q.slice(0,Math.max(0,q.length-$))].sort((Y,b)=>Y.priority-b.priority);if(V.length===0)return{messages:Q,snippedCount:0,estimatedTokensFreed:0};let W=new Set,B=0;for(let Y of V){W.add(Y.assistantIdx);for(let b of Y.toolResultIdxs)W.add(b)}for(let Y of W){let b=Q[Y],E=typeof b.content==="string"?b.content:JSON.stringify(b.content);if(B+=E.length,b.tool_calls)B+=JSON.stringify(b.tool_calls).length}let F=[],L=!1;for(let Y=0;Y<Q.length;Y++){if(W.has(Y)){if(!L)F.push({role:"system",content:`[${V.length} earlier tool interaction${V.length===1?"":"s"} snipped for brevity]`}),L=!0;continue}F.push(Q[Y])}return{messages:F,snippedCount:V.length,estimatedTokensFreed:Math.floor(B/4)}}var XZ=60000,HZ=3;function XQ(Q,Z){if(!Z)return null;if(Date.now()-Z<XZ)return null;let J=z0(Q,{keepRecentTurns:HZ,minMessagesForSnip:15});if(J.snippedCount===0)return null;return J}class p0{hasAttempted=!1;async tryReactiveCompact(Q,Z){if(this.hasAttempted)return{success:!1,messages:Q};this.hasAttempted=!0;let $=z0(Q,{keepRecentTurns:3,minMessagesForSnip:10}),J=$.messages;try{let q=await r.compact(J,{trigger:"auto",modelName:Z.modelName,maxContextTokens:Z.maxContextTokens,apiKey:Z.apiKey,baseURL:Z.baseURL,signal:Z.signal});if(q.success)return{success:!0,messages:q.compactedMessages};if($.snippedCount>0)return{success:!0,messages:J};return{success:!1,messages:Q}}catch(q){if(n(q))throw q;if($.snippedCount>0)return{success:!0,messages:J};return{success:!1,messages:Q}}}reset(){this.hasAttempted=!1}}import*as o from"fs";import*as d0 from"os";import*as G0 from"path";import{nanoid as DQ}from"nanoid";var BZ=1e5,DZ=2000,HQ=200000;class g0{currentChars=0;track(Q){this.currentChars+=Q}remaining(){return Math.max(0,HQ-this.currentChars)}isExhausted(){return this.currentChars>=HQ}reset(){this.currentChars=0}}function jQ(Q,Z,$){let J=$?.maxCharsPerResult??BZ,q=$?.previewChars??DZ,z=$?.messageBudget,G=typeof Q==="string"?Q:JSON.stringify(Q,null,2);if(G.length<=J)return jZ(Q,G,Z,q,z,$);let V=$?.outputDir??G0.join(d0.homedir(),".blade","tool-results"),W=`${Z}-${DQ(8)}.txt`,B=G0.join(V,W);try{o.mkdirSync(V,{recursive:!0}),o.writeFileSync(B,G,"utf-8")}catch{let Y=G.slice(0,J)+`
|
|
96
106
|
|
|
97
|
-
... (truncated, ${G.length} total chars)`;if(z)z.track(Y.length);return Y}let F=G.slice(0,q),
|
|
107
|
+
... (truncated, ${G.length} total chars)`;if(z)z.track(Y.length);return Y}let F=G.slice(0,q),L=`Result too large (${G.length} chars). Full output saved to: ${B}
|
|
98
108
|
|
|
99
109
|
Preview:
|
|
100
110
|
${F}
|
|
101
111
|
|
|
102
|
-
... (${G.length-q} more chars in file)`;if(z)z.track(
|
|
112
|
+
... (${G.length-q} more chars in file)`;if(z)z.track(L.length);return L}function jZ(Q,Z,$,J,q,z){if(!q)return Q;let G=q.remaining();if(G<=0){let V=Z.slice(0,J),W=BQ(Z,V,$,z,"[Message budget exhausted. Full output saved to disk.]");return q.track(typeof W==="string"?W.length:J),W}if(Z.length>G){let V=Math.max(J,G),W=Z.slice(0,V),B=BQ(Z,W,$,z,`... (truncated by message budget, ${Z.length} total chars)`);return q.track(typeof B==="string"?B.length:V),B}return q.track(Z.length),Q}function BQ(Q,Z,$,J,q){let z=J?.outputDir??G0.join(d0.homedir(),".blade","tool-results"),G=`${$}-${DQ(8)}.txt`,V=G0.join(z,G);try{return o.mkdirSync(z,{recursive:!0}),o.writeFileSync(V,Q,"utf-8"),`${Z}
|
|
103
113
|
|
|
104
114
|
${q}
|
|
105
115
|
Full output saved to: ${V}`}catch{return`${Z}
|
|
106
116
|
|
|
107
|
-
${q}`}}import*as
|
|
117
|
+
${q}`}}import*as v0 from"node:fs/promises";import{homedir as NQ}from"node:os";import*as h from"node:path";var L0={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 wQ(){return{metadata:L0,instructions:`# Skill Creator
|
|
108
118
|
|
|
109
119
|
帮助用户创建新的 Blade Skills。
|
|
110
120
|
|
|
@@ -287,7 +297,7 @@ user-invocable: true
|
|
|
287
297
|
<footer>
|
|
288
298
|
\`\`\`
|
|
289
299
|
\`\`\`
|
|
290
|
-
`}}var
|
|
300
|
+
`}}var b0={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 FQ(){return{metadata:b0,instructions:`# Update Config Skill
|
|
291
301
|
|
|
292
302
|
配置 Blade 运行环境。管理 settings、hooks、permissions、环境变量等。
|
|
293
303
|
|
|
@@ -560,11 +570,11 @@ ConfigTool({
|
|
|
560
570
|
2. **permissions 字段使用 replace 策略**:设置 permissions 会完全替换现有值。如果只想添加规则,先 GET 当前值,合并后再 SET
|
|
561
571
|
3. **env 字段使用 deep-merge 策略**:可以逐个添加环境变量
|
|
562
572
|
4. **scope 默认值**:不指定 scope 时,根据字段路由表决定(hooks/permissions/env 默认 local,temperature/theme 等默认 global)
|
|
563
|
-
`}}import{exec as
|
|
564
|
-
`)}get size(){return this.skills.size}async refresh(){return this.skills.clear(),this.pluginSkills.clear(),this.initialized=!1,this.initialize()}registerPluginSkill(Q){this.pluginSkills.set(Q.namespacedName,Q),this.skills.set(Q.namespacedName,Q.metadata)}findPluginSkill(Q){let Z=this.pluginSkills.get(Q);if(Z)return Z;let $=[];for(let J of this.pluginSkills.values())if(J.originalName===Q)$.push(J);if($.length===1)return $[0];return}getAllPluginSkills(){return Array.from(this.pluginSkills.values())}clearPluginSkills(){for(let Q of this.pluginSkills.values())this.skills.delete(Q.namespacedName);this.pluginSkills.clear()}getPluginSkillCount(){return this.pluginSkills.size}}function
|
|
573
|
+
`}}import{exec as wZ}from"node:child_process";import*as w from"node:fs/promises";import{homedir as FZ}from"node:os";import*as I from"node:path";import{promisify as LZ}from"node:util";var O0=LZ(wZ),v=R("General"),m0={url:"https://github.com/anthropics/skills.git",branch:"main",defaultSkills:["skill-creator"]};class LQ{skillsDir;constructor(Q){this.skillsDir=Q||I.join(FZ(),".blade","skills")}async isInstalled(Q){let Z=I.join(this.skillsDir,Q,"SKILL.md");try{return await w.access(Z),!0}catch{return!1}}async isGitAvailable(){try{return await O0("git --version"),!0}catch{return!1}}async installOfficialSkill(Q){let{url:Z,branch:$}=m0,J=I.join(this.skillsDir,Q),q=I.join(this.skillsDir,`.tmp-${Q}-${Date.now()}`);try{if(!await this.isGitAvailable())return v.warn("Git not available, skipping skill installation"),!1;v.info(`Installing official skill: ${Q}...`),await w.mkdir(this.skillsDir,{recursive:!0,mode:493}),await O0(`git clone --depth 1 --branch ${$} --single-branch ${Z} "${q}"`,{timeout:30000});let z=I.join(q,"skills",Q);try{await w.access(z)}catch{return v.warn(`Skill ${Q} not found in official repository`),await w.rm(q,{recursive:!0,force:!0}),!1}try{await w.rm(J,{recursive:!0,force:!0})}catch{}return await w.cp(z,J,{recursive:!0}),await w.rm(q,{recursive:!0,force:!0}),v.info(`Successfully installed: ${Q}`),!0}catch(z){try{await w.rm(q,{recursive:!0,force:!0})}catch{}return v.warn(`Failed to install ${Q}: ${z instanceof Error?z.message:"Unknown error"}`),!1}}async ensureDefaultSkillsInstalled(){await w.mkdir(this.skillsDir,{recursive:!0,mode:493});for(let Q of m0.defaultSkills)if(!await this.isInstalled(Q))await this.installOfficialSkill(Q)}async installFromRepo(Q,Z){let $=Z||this.extractRepoName(Q),J=I.join(this.skillsDir,$),q=I.join(this.skillsDir,`.tmp-repo-${$}-${Date.now()}`);try{if(!await this.isGitAvailable())return v.warn("Git not available, cannot install from repo"),!1;v.info(`Installing skill from repo: ${Q}...`),await w.mkdir(this.skillsDir,{recursive:!0,mode:493}),await O0(`git clone --depth 1 "${Q}" "${q}"`,{timeout:60000});let z=I.join(q,"SKILL.md");try{await w.access(z)}catch{return v.warn(`No SKILL.md found in repository ${Q}`),await w.rm(q,{recursive:!0,force:!0}),!1}await w.rm(J,{recursive:!0,force:!0}),await w.rename(q,J);try{await w.rm(I.join(J,".git"),{recursive:!0,force:!0})}catch{}return v.info(`Successfully installed skill from repo: ${$}`),!0}catch(z){try{await w.rm(q,{recursive:!0,force:!0})}catch{}return v.warn(`Failed to install from repo ${Q}: ${z instanceof Error?z.message:"Unknown error"}`),!1}}async installFromLocal(Q,Z,$=!0){let J=Z||I.basename(Q),q=I.join(this.skillsDir,J);try{let z=I.resolve(Q);try{await w.access(z)}catch{return v.warn(`Local path does not exist: ${z}`),!1}let G=I.join(z,"SKILL.md");try{await w.access(G)}catch{return v.warn(`No SKILL.md found in local path: ${z}`),!1}if(v.info(`Installing skill from local path: ${z}...`),await w.mkdir(this.skillsDir,{recursive:!0,mode:493}),await w.rm(q,{recursive:!0,force:!0}),$)await w.symlink(z,q,"dir"),v.info(`Created symlink for skill: ${J}`);else await w.cp(z,q,{recursive:!0}),v.info(`Copied skill to: ${J}`);return!0}catch(z){return v.warn(`Failed to install from local path ${Q}: ${z instanceof Error?z.message:"Unknown error"}`),!1}}extractRepoName(Q){return Q.match(/\/([^/]+?)(\.git)?$/)?.[1]||"unknown-skill"}async installAllOfficialSkills(){let{url:Q,branch:Z}=m0,$=I.join(this.skillsDir,`.tmp-all-${Date.now()}`),J=[],q=[];try{if(!await this.isGitAvailable())return v.warn("Git not available, skipping skill installation"),{installed:J,failed:q};await w.mkdir(this.skillsDir,{recursive:!0,mode:493}),v.info("Cloning official skills repository..."),await O0(`git clone --depth 1 --branch ${Z} --single-branch ${Q} "${$}"`,{timeout:60000});let z=I.join($,"skills"),G=await w.readdir(z,{withFileTypes:!0});for(let V of G){if(!V.isDirectory())continue;let W=V.name,B=I.join(z,W),F=I.join(this.skillsDir,W);try{await w.access(I.join(B,"SKILL.md")),await w.rm(F,{recursive:!0,force:!0}),await w.cp(B,F,{recursive:!0}),v.info(`Installed: ${W}`),J.push(W)}catch(L){v.warn(`Failed to install ${W}`),q.push(W)}}await w.rm($,{recursive:!0,force:!0})}catch(z){try{await w.rm($,{recursive:!0,force:!0})}catch{}v.warn(`Failed to install skills: ${z instanceof Error?z.message:"Unknown error"}`)}return{installed:J,failed:q}}}var u0=null;function bQ(Q){if(!u0)u0=new LQ(Q);return u0}import*as V0 from"node:fs/promises";import*as _0 from"node:path";import{parse as bZ}from"yaml";var OZ=/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/,_Z=/^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]?$/,OQ=1024;function UZ(Q){if(!Q)return;if(typeof Q==="string")return Q.split(",").map((Z)=>Z.trim()).filter(Boolean);if(Array.isArray(Q))return Q.map((Z)=>String(Z).trim()).filter(Boolean);return}function _Q(Q){if(Q===void 0)return;if(typeof Q==="boolean")return Q;if(typeof Q==="string"){let Z=Q.toLowerCase().trim();if(Z==="true"||Z==="yes"||Z==="1")return!0;if(Z==="false"||Z==="no"||Z==="0")return!1}return}function vZ(Q,Z){if(!Q.name)return{valid:!1,error:"Missing required field: name"};if(!_Z.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>OQ)return{valid:!1,error:`Description too long: ${Q.description.length} characters (max ${OQ})`};let $;if(Q.model)$=Q.model==="inherit"?"inherit":Q.model;return{valid:!0,metadata:{name:Q.name,description:Q.description.trim(),allowedTools:UZ(Q["allowed-tools"]),version:Q.version,argumentHint:Q["argument-hint"]?.trim(),userInvocable:_Q(Q["user-invocable"]),disableModelInvocation:_Q(Q["disable-model-invocation"]),model:$,whenToUse:Q.when_to_use?.trim()}}}function UQ(Q,Z,$){let J=Q.match(OZ);if(!J)return{success:!1,error:"Invalid SKILL.md format: missing YAML frontmatter (must start with ---)"};let[,q,z]=J,G;try{G=bZ(q)}catch(B){return{success:!1,error:`Failed to parse YAML frontmatter: ${B instanceof Error?B.message:String(B)}`}}let V=vZ(G,Z);if(!V.valid)return{success:!1,error:V.error};let W=_0.dirname(Z);return{success:!0,content:{metadata:{...V.metadata,path:Z,basePath:W,source:$},instructions:z.trim()}}}async function vQ(Q,Z){try{let $=await V0.readFile(Q,"utf-8");return UQ($,Q,Z)}catch($){if($.code==="ENOENT")return{success:!1,error:`File not found: ${Q}`};return{success:!1,error:`Failed to read file: ${$ instanceof Error?$.message:String($)}`}}}async function IQ(Q){try{let Z=await V0.readFile(Q.path,"utf-8"),$=UQ(Z,Q.path,Q.source);return $.success?$.content:null}catch{return null}}async function EQ(Q){try{return await V0.access(_0.join(Q,"SKILL.md")),!0}catch{return!1}}var IZ={userSkillsDir:h.join(NQ(),".blade","skills"),projectSkillsDir:".blade/skills",claudeUserSkillsDir:h.join(NQ(),".claude","skills"),claudeProjectSkillsDir:".claude/skills"},U0=null;class c0{skills=new Map;pluginSkills=new Map;config;initialized=!1;constructor(Q){this.config={...IZ,cwd:k(),...Q}}static getInstance(Q){if(!U0)U0=new c0(Q);return U0}static resetInstance(){U0=null}async initialize(){if(this.initialized)return{skills:Array.from(this.skills.values()),errors:[]};let Q=[],Z=[];try{await bQ(this.config.userSkillsDir).ensureDefaultSkillsInstalled()}catch(W){Q.push({path:"SkillInstaller",error:`Failed to install default skills: ${W instanceof Error?W.message:"Unknown error"}`})}this.loadBuiltinSkills();let $=await this.scanDirectory(this.config.claudeUserSkillsDir,"user");Z.push(...$.skills),Q.push(...$.errors);let J=await this.scanDirectory(this.config.userSkillsDir,"user");Z.push(...J.skills),Q.push(...J.errors);let q=h.isAbsolute(this.config.claudeProjectSkillsDir)?this.config.claudeProjectSkillsDir:h.join(this.config.cwd,this.config.claudeProjectSkillsDir),z=await this.scanDirectory(q,"project");Z.push(...z.skills),Q.push(...z.errors);let G=h.isAbsolute(this.config.projectSkillsDir)?this.config.projectSkillsDir:h.join(this.config.cwd,this.config.projectSkillsDir),V=await this.scanDirectory(G,"project");Z.push(...V.skills),Q.push(...V.errors);for(let W of Z)this.skills.set(W.name,W);return this.initialized=!0,{skills:Array.from(this.skills.values()),errors:Q}}loadBuiltinSkills(){this.skills.set(L0.name,L0),this.skills.set(b0.name,b0)}async scanDirectory(Q,Z){let $=[],J=[];try{await v0.access(Q)}catch{return{skills:$,errors:J}}try{let q=await v0.readdir(Q,{withFileTypes:!0});for(let z of q){if(!z.isDirectory())continue;let G=h.join(Q,z.name),V=h.join(G,"SKILL.md");if(!await EQ(G))continue;let W=await vQ(V,Z);if(W.success&&W.content)$.push(W.content.metadata);else J.push({path:V,error:W.error||"Unknown error"})}}catch(q){J.push({path:Q,error:`Failed to scan directory: ${q instanceof Error?q.message:String(q)}`})}return{skills:$,errors:J}}getAll(){return Array.from(this.skills.values())}get(Q){return this.skills.get(Q)}has(Q){return this.skills.has(Q)}async loadContent(Q){let Z=this.skills.get(Q);if(!Z)return null;if(Z.source==="builtin")return this.loadBuiltinContent(Q);return IQ(Z)}loadBuiltinContent(Q){switch(Q){case"skill-creator":return wQ();case"update-config":return FQ();default:return null}}getModelInvocableSkills(){return Array.from(this.skills.values()).filter((Q)=>!Q.disableModelInvocation)}getUserInvocableSkills(){return Array.from(this.skills.values()).filter((Q)=>Q.userInvocable===!0)}generateAvailableSkillsList(){let Q=this.getModelInvocableSkills();if(Q.length===0)return"";let Z=[];for(let $ of Q){let J=$.description.length>100?`${$.description.substring(0,97)}...`:$.description,q=$.argumentHint?`${$.name} ${$.argumentHint}`:$.name;Z.push(`- ${q}: ${J}`)}return Z.join(`
|
|
574
|
+
`)}get size(){return this.skills.size}async refresh(){return this.skills.clear(),this.pluginSkills.clear(),this.initialized=!1,this.initialize()}registerPluginSkill(Q){this.pluginSkills.set(Q.namespacedName,Q),this.skills.set(Q.namespacedName,Q.metadata)}findPluginSkill(Q){let Z=this.pluginSkills.get(Q);if(Z)return Z;let $=[];for(let J of this.pluginSkills.values())if(J.originalName===Q)$.push(J);if($.length===1)return $[0];return}getAllPluginSkills(){return Array.from(this.pluginSkills.values())}clearPluginSkills(){for(let Q of this.pluginSkills.values())this.skills.delete(Q.namespacedName);this.pluginSkills.clear()}getPluginSkillCount(){return this.pluginSkills.size}}function I0(Q){return c0.getInstance(Q)}async function EZ(Q){return I0(Q).initialize()}var NZ="Skill",AZ=/<available_skills>\s*<\/available_skills>/;function i0(Q){let $=I0().generateAvailableSkillsList();if(!$)return Q;return Q.map((J)=>{if(J.name!==NZ)return J;let q=J.description.replace(AZ,`<available_skills>
|
|
565
575
|
${$}
|
|
566
|
-
</available_skills>`);if(q===J.description)return J;return{...J,description:q}})}var
|
|
567
|
-
`)}function
|
|
576
|
+
</available_skills>`);if(q===J.description)return J;return{...J,description:q}})}var yZ=new Set(["user-cancel","interrupt","sibling-error","timeout"]);function AQ(Q){if(!Q.aborted)return;if(typeof Q.reason==="string"&&yZ.has(Q.reason))return Q.reason;return"user-cancel"}function yQ(){return{consecutiveFailures:new Map,totalFailures:0,lastFailedTool:null}}function SQ(Q,Z){Q.consecutiveFailures.set(Z,0),Q.lastFailedTool=null}function MQ(Q,Z){let $=(Q.consecutiveFailures.get(Z)??0)+1;Q.consecutiveFailures.set(Z,$),Q.totalFailures++,Q.lastFailedTool=Z}function SZ(Q,Z){return(Q.consecutiveFailures.get(Z)??0)>=3}function PQ(Q,Z){if(!SZ(Q,Z))return;let $=Q.consecutiveFailures.get(Z)??0;return`WARNING: ${Z} has failed ${$} consecutive times. Consider a different approach: use a different tool, verify your parameters, or break the task into smaller steps.`}function fQ(Q){return Q>0&&Q%5===0}function RQ(Q,Z){let $=[`[Self-check at turn ${Q}]`,"Before continuing, briefly assess:","1. Are you making progress toward the goal?","2. Have any approaches failed repeatedly that you should abandon?","3. Is there a simpler path you haven't tried?"];if(Z>3)$.push(`Note: ${Z} tool failures so far. Consider whether your current strategy needs adjustment.`);return $.join(`
|
|
577
|
+
`)}function TQ(){return{recentOutputHashes:[]}}function MZ(Q){let Z=Q.trim().slice(0,500),$=0;for(let J=0;J<Z.length;J++)$=($<<5)-$+Z.charCodeAt(J)|0;return $.toString(36)}function kQ(Q,Z){let $=MZ(Z);if(Q.recentOutputHashes.push($),Q.recentOutputHashes.length>4)Q.recentOutputHashes.shift();if(Q.recentOutputHashes.length<3)return!1;let J=Q.recentOutputHashes.slice(-3);return J.every((q)=>q===J[0])}function xQ(){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 g=R("Agent"),fZ=new Set(["Read","Glob","Grep","WebFetch","WebSearch","MemoryRead","GetSpecContext","ValidateSpec","TaskOutput"]);class E0{pipeline;execContext;registry;contextMgr;sessionId;lastMessageUuid;subagentInfo;pending=new Map;completed=new Map;queued=[];order=[];dispatched=new Set;abortController=new AbortController;epoch=0;activeAborts=new Map;constructor(Q,Z,$,J,q,z,G){this.pipeline=Q;this.execContext=Z;this.registry=$;this.contextMgr=J;this.sessionId=q;this.lastMessageUuid=z;this.subagentInfo=G}addTool(Q,Z){if(this.dispatched.has(Q.id)){g.debug(`[StreamingToolExecutor] 跳过已分发工具: ${Q.function.name} (${Q.id})`);return}if(this.dispatched.add(Q.id),this.order.push(Q.id),fZ.has(Q.function.name)){g.debug(`[StreamingToolExecutor] 立即执行预启动工具: ${Q.function.name}`);let J=this.executeOne(Q,Z);this.pending.set(Q.id,J)}else g.debug(`[StreamingToolExecutor] 排队非预启动工具: ${Q.function.name}`),this.queued.push({toolCall:Q,params:Z})}async*getRemainingResults(){for(let Q of this.order){if(this.completed.has(Q)){yield this.completed.get(Q),this.completed.delete(Q);continue}if(this.pending.has(Q)){let $=await this.pending.get(Q);this.pending.delete(Q),yield $;continue}let Z=this.queued.findIndex(($)=>$.toolCall.id===Q);if(Z!==-1){let{toolCall:$,params:J}=this.queued[Z];if(this.queued.splice(Z,1),this.execContext.signal?.aborted){g.debug(`[StreamingToolExecutor] Signal aborted, 跳过排队工具: ${$.function.name} (${$.id})`),yield this.makeAbortResult($,"Tool execution skipped: task aborted before launch");continue}yield await this.executeOne($,J)}}}getCompletedResults(){let Q=Array.from(this.completed.values());return this.completed.clear(),Q}discard(){this.epoch++,this.abortController.abort(),this.abortController=new AbortController;for(let[,Q]of this.activeAborts)Q.abort();this.activeAborts.clear(),this.queued=[],this.order=[],this.dispatched.clear(),this.completed.clear(),this.pending.clear(),g.debug(`[StreamingToolExecutor] 已丢弃所有挂起工作并重置状态 (epoch=${this.epoch})`)}hasTools(){return this.order.length>0}getEpoch(){return this.epoch}makeAbortResult(Q,Z){return{toolCall:Q,result:{success:!1,llmContent:"",error:{type:"execution_error",message:Z},metadata:{abortedBeforeLaunch:!0}},toolUseUuid:null}}async executeOne(Q,Z){let $=this.epoch,J=new AbortController;this.activeAborts.set(Q.id,J);let q=this.abortController.signal;try{if(q.aborted||J.signal.aborted)return this.makeAbortResult(Q,"Tool execution aborted due to discard");let z=null;try{if(this.contextMgr&&this.sessionId)z=await this.contextMgr.saveToolUse(this.sessionId,Q.function.name,Z,this.lastMessageUuid??null,this.subagentInfo)}catch(Y){g.warn("[StreamingToolExecutor] 保存工具调用失败:",Y)}let G=[q,J.signal],V=this.execContext.signal;if(V)G.push(V);let W=WQ(...G),B={...this.execContext,signal:W},F=await this.pipeline.execute(Q.function.name,Z,B);if($!==this.epoch)return g.debug(`[StreamingToolExecutor] 丢弃旧世代工具结果: ${Q.function.name} (startEpoch=${$}, currentEpoch=${this.epoch})`),this.makeAbortResult(Q,"Tool execution aborted due to epoch mismatch (discard)");let L={toolCall:Q,result:F,toolUseUuid:z};if(this.pending.has(Q.id))this.pending.delete(Q.id),this.completed.set(Q.id,L);return L}catch(z){if($!==this.epoch)return this.makeAbortResult(Q,"Tool execution aborted due to epoch mismatch (discard)");g.error(`[StreamingToolExecutor] 工具执行失败: ${Q.function.name}`,z);let G={success:!1,llmContent:"",error:{type:"execution_error",message:z instanceof Error?z.message:"Unknown error"},metadata:void 0},V={toolCall:Q,result:G,toolUseUuid:null,error:z instanceof Error?z: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 A=R("Agent"),TZ=0.1,kZ=8192,xZ=32768,hQ=100,hZ=`
|
|
568
578
|
|
|
569
579
|
# Task Execution Strategy
|
|
570
580
|
When facing complex multi-step tasks:
|
|
@@ -572,31 +582,31 @@ When facing complex multi-step tasks:
|
|
|
572
582
|
2. Execute one step at a time — verify each step succeeded before moving to the next.
|
|
573
583
|
3. If a step fails, diagnose the root cause rather than repeating the same approach.
|
|
574
584
|
4. When uncertain about file paths or project structure, use Grep/Glob/Read to gather facts first.
|
|
575
|
-
5. Prefer the smallest change that achieves the goal — avoid unnecessary refactoring.`;function
|
|
576
|
-
`)}function
|
|
585
|
+
5. Prefer the smallest change that achieves the goal — avoid unnecessary refactoring.`;function CZ(Q){let Z=Q.trim();if(Z=Z.replace(/,\s*([}\]])/g,"$1"),Z.startsWith("{")&&!Z.endsWith("}"))Z+="}";Z=Z.replace(/,\s*([}\]])/g,"$1");try{let $=JSON.parse(Z);if(typeof $==="object"&&$!==null&&!Array.isArray($))return $;return null}catch{return null}}function pZ(Q){if(typeof Q==="string")return Q;try{return JSON.parse(JSON.stringify(Q))}catch{return String(Q)}}function dZ(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 W=J.statusCode?` (HTTP ${J.statusCode})`:"";return`${V}${W}`}}catch{}let q=Q.message,z=q.match(/Last error:\s*(.+)$/);if(z)return z[1];return q}function gZ(Q){if(!(Q instanceof Error))return!1;return["stream not supported","streaming is not available","sse not supported","does not support streaming"].some(($)=>Q.message.toLowerCase().includes($.toLowerCase()))}function mZ(Q,Z){if(!Z)return"Tool execution failed (no details).";let $=[`Error: ${Z.message||"Unknown error"}`];if(Z.type==="validation_error")$.push("Hint: Check the tool parameters — a required field may be missing or have the wrong type.");else if(Z.type==="permission_denied")$.push("Hint: This operation requires user approval. Try a different approach or ask the user.");else if(Z.type==="timeout_error")$.push("Hint: The operation timed out. Consider breaking it into smaller steps or increasing timeout.");else if(Z.type==="execution_error"){let J=Z.message??"";if(J.includes("ENOENT")||J.includes("no such file"))$.push("Hint: File or directory not found. Use Glob or Grep to find the correct path first.");else if(J.includes("EACCES")||J.includes("permission"))$.push("Hint: Permission denied. The file may be read-only or owned by another user.");else if(J.includes("not found in file")||J.includes("old_string"))$.push(`Hint: The target text was not found. Use Read to view the current file content, then retry ${Q} with the exact text.`);else if(J.includes("ENOTDIR"))$.push("Hint: A path component is not a directory. Verify the full path with Glob.")}return $.join(`
|
|
586
|
+
`)}function uZ(Q){if(!(Q instanceof Error))return!1;let Z=Q.message.toLowerCase();return Z.includes("prompt_too_long")||Z.includes("prompt is too long")||Z.includes("maximum context length")||Z.includes("request too large")||Q.status===413}function cZ(Q,Z){let $=Z,J=$.index??0;if(!Q.has(J))Q.set(J,{id:$.id||"",name:$.function?.name||"",arguments:""});let q=Q.get(J);if($.id&&!q.id)q.id=$.id;if($.function?.name&&!q.name)q.name=$.function.name;if($.function?.arguments)q.arguments+=$.function.arguments}function iZ(Q){if(Q.size===0)return;return Array.from(Q.values()).filter((Z)=>Z.id&&Z.name).map((Z)=>({id:Z.id,type:"function",function:{name:Z.name,arguments:Z.arguments}}))}async function*nZ(Q,Z,$,J,q){let z="",G="",V,W,B=new Map;try{let F=Q.chatService.streamChat(Z,$,J),L=0;for await(let Y of F){if(L++,J?.aborted)break;if(Y.modelFallback){q?.discard(),z="",G="",V=void 0,W=void 0,B.clear(),L=0,yield{kind:"model_fallback"};continue}if(Y.content)z+=Y.content,yield{kind:"content_delta",delta:Y.content};if(Y.reasoningContent)G+=Y.reasoningContent,yield{kind:"thinking_delta",delta:Y.reasoningContent};if(Y.usage)V=Y.usage;if(Y.toolCalls){for(let b of Y.toolCalls)if(cZ(B,b),q){let D=b.index??0,K=B.get(D);if(K&&K.id&&K.name)try{let f=JSON.parse(K.arguments),x={id:K.id,type:"function",function:{name:K.name,arguments:K.arguments}},T=Q.executionPipeline.getRegistry().get(K.name)?.kind;q.addTool(x,f),yield{kind:"tool_start",toolCall:x,toolKind:T}}catch{}}}if(Y.finishReason){W=Y.finishReason;break}}if(L===0&&!J?.aborted&&z.length===0&&B.size===0)return A.warn("[Loop] 流式响应返回0个chunk,回退到非流式模式"),q?.discard(),{...await Q.chatService.chat(Z,$,J),_nonStreamingFallback:!0};return{content:z,reasoningContent:G||void 0,toolCalls:iZ(B),usage:V,finishReason:W}}catch(F){if(gZ(F))return A.warn("[Loop] 流式请求失败,降级到非流式模式"),q?.discard(),{...await Q.chatService.chat(Z,$,J),_nonStreamingFallback:!0};throw F}}async function CQ(Q,Z,$,J,q,z){if(J===void 0)return A.debug(`[Loop] [轮次 ${$}] 压缩检查: 跳过(无历史 usage 数据)`),"none";let G=XQ(Z.messages,z);if(G)Z.messages=G.messages,A.debug(`[Loop] [轮次 ${$}] MicroCompact: 清理 ${G.snippedCount} 轮旧工具结果(缓存已过期)`);let V=z0(Z.messages),W=!1;if(V.snippedCount>0)W=!0,A.debug(`[Loop] [轮次 ${$}] Snip 压缩: 移除 ${V.snippedCount} 轮旧工具调用,释放约 ${V.estimatedTokensFreed} tokens`);let B=Q.chatService.getConfig(),F=B.model,L=B.maxContextTokens??Q.config.maxContextTokens,Y=B.maxOutputTokens??Q.config.maxOutputTokens??Math.min(Math.max(Math.floor(L*TZ),kZ),xZ),b=L-Y,E=Math.floor(b*0.8);if(A.debug(`[Loop] [轮次 ${$}] 压缩检查:`,{promptTokens:J,maxContextTokens:L,maxOutputTokens:Y,availableForInput:b,threshold:E,shouldCompact:J>=E}),J<E){if(W)Z.messages=V.messages;return W?"snipped":"none"}A.debug($===0?"[Loop] 触发自动压缩":`[Loop] [轮次 ${$}] 触发循环内自动压缩`);try{let D=W?V.messages:Z.messages,K=await r.compact(D,{trigger:"auto",modelName:F,maxContextTokens:L,apiKey:B.apiKey,baseURL:B.baseUrl,actualPreTokens:J,signal:q});if(Z.messages=K.compactedMessages,K.success)A.debug(`[Loop] [轮次 ${$}] 压缩完成: ${K.preTokens} -> ${K.postTokens} tokens`);else A.warn(`[Loop] [轮次 ${$}] 压缩使用降级策略: ${K.preTokens} -> ${K.postTokens} tokens`);return await D0(Q,Z,K.summary,{trigger:"auto",preTokens:K.preTokens,postTokens:K.postTokens,filesIncluded:K.filesIncluded}),"compacted"}catch(D){if(n(D))return A.debug(`[Loop] [轮次 ${$}] 压缩被中止`),"none";if(W)Z.messages=V.messages;return A.error(`[Loop] [轮次 ${$}] 压缩失败,继续执行`,D),W?"snipped":"none"}}function a(Q,Z,$,J){let q=J?AQ(J):"user-cancel";return{success:!1,error:{type:"aborted",message:(q==="interrupt"?void 0:"任务已被用户中止")??"任务已中断"},metadata:{turnsCount:Q,toolCallsCount:Z,duration:Date.now()-$,abortReason:q}}}async function*lZ(Q,Z,$,J,q){let z=Date.now(),G=0,V=[];try{let W=Q.executionPipeline.getRegistry(),B=$.permissionMode,F=W.getFunctionDeclarationsByMode(B);F=i0(F);let L=Q.applySkillToolRestrictions(F),Y=yQ(),b=TQ(),E=q;if(typeof W.getDeferredToolsListing==="function"){let t=W.getDeferredToolsListing();if(t&&E)E=`${E}
|
|
577
587
|
|
|
578
|
-
${
|
|
588
|
+
${t}`}if(E)E+=hZ;let D=new H0($,E);D.appendUser({role:"user",content:Z});let K=await u(Q,$,Z),f=$.permissionMode==="yolo",x=Q.runtimeOptions.maxTurns??J?.maxTurns??Q.config.maxTurns??-1;if(x===0)return{success:!1,error:{type:"chat_disabled",message:"对话功能已被禁用 (maxTurns=0)"},metadata:{turnsCount:0,toolCallsCount:0,duration:0}};let C=x===-1?hQ:Math.min(x,hQ),T=0,s,M,m=0,N0=0,pQ=!!$.subagentInfo,A0=o0({budget:Q.currentModelMaxContextTokens,isSubagent:pQ}),n0=new p0;try{while(!0){if(J?.signal?.aborted)return a(G,V.length,z,J.signal);D.writeback();let t=await CQ(Q,$,G,s,J?.signal,M);if(t!=="none"){if(t==="compacted")yield{kind:"compaction",phase:"start"},yield{kind:"compaction",phase:"end"};D.replaceHistory($.messages)}if(G++,n0.reset(),yield{kind:"turn_start",turn:G,maxTurns:C},J?.signal?.aborted)return a(G-1,V.length,z,J.signal);if(fQ(G)&&G>1){let _=RQ(G,Y.totalFailures);D.appendControl("user",{role:"user",content:`
|
|
579
589
|
|
|
580
590
|
<system-reminder>
|
|
581
591
|
${_}
|
|
582
|
-
</system-reminder>`})}let
|
|
592
|
+
</system-reminder>`})}let l0=J?.stream!==!1,H,W0;try{if(l0)W0=new E0(Q.executionPipeline,{sessionId:$.sessionId,userId:$.userId||"default",workspaceRoot:$.workspaceRoot||k(),signal:J?.signal,confirmationHandler:$.confirmationHandler,permissionMode:$.permissionMode,toolRegistry:W,deferredToolManager:W.deferredToolManager},Q.executionPipeline.getRegistry(),Q.executionEngine?.getContextManager(),$.sessionId,K,$.subagentInfo),H=yield*nZ(Q,D.toLLMMessages(),L,J?.signal,W0);else H=await Q.chatService.chat(D.toLLMMessages(),L,J?.signal)}catch(_){if(uZ(_)){A.warn("[Loop] 检测到 prompt_too_long 错误,尝试反应式压缩");let X=Q.chatService.getConfig(),j=await n0.tryReactiveCompact($.messages,{modelName:X.model,maxContextTokens:X.maxContextTokens??Q.config.maxContextTokens,apiKey:X.apiKey,baseURL:X.baseUrl,signal:J?.signal});if(j.success){$.messages=j.messages,D.replaceHistory($.messages),A.info("[Loop] 反应式压缩成功,重试 LLM 调用"),G--;continue}}throw _}if(M=Date.now(),H.usage){if(H.usage.totalTokens)T+=H.usage.totalTokens;s=H.usage.promptTokens,yield{kind:"token_usage",usage:{inputTokens:H.usage.promptTokens??0,outputTokens:H.usage.completionTokens??0,totalTokens:H.usage.totalTokens??0,maxContextTokens:Q.currentModelMaxContextTokens}}}let dQ=H.usage?.completionTokens??0;if(A0=s0(A0,dQ,m>0),J?.signal?.aborted)return a(G-1,V.length,z,J.signal);if(!l0||!!H._nonStreamingFallback){if(H.reasoningContent&&H.reasoningContent.trim())yield{kind:"thinking_delta",delta:H.reasoningContent};if(H.content&&H.content.trim())yield{kind:"content_delta",delta:H.content}}yield{kind:"stream_end"};let y0=M0(H.finishReason,m,A0);if(y0.action==="recover"){m++,A.warn(`[Loop] Max output tokens hit (recovery ${m}/3)`);let _={role:"assistant",content:H.content||"",reasoningContent:H.reasoningContent,tool_calls:H.toolCalls};D.appendToHistory(_);let X=await p(Q,$,H.content||"",K);if(X)K=X;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."};D.appendToHistory(j);let O=await u(Q,$,j.content,K);if(O)K=O;continue}if(y0.action==="truncated"||y0.action==="budget_stop"){D.appendAssistant({role:"assistant",content:H.content||"",reasoningContent:H.reasoningContent,tool_calls:H.toolCalls});let _=await p(Q,$,H.content||"",K);if(_)K=_;return{success:!0,finalMessage:H.content,metadata:{turnsCount:G,toolCallsCount:V.length,duration:Date.now()-z,tokensUsed:T,outputTruncated:!0}}}if(H.finishReason!=="length")m=0;if(!H.toolCalls||H.toolCalls.length===0){if(H.content&&kQ(b,H.content)){D.appendAssistant({role:"assistant",content:H.content||"",reasoningContent:H.reasoningContent}),D.appendControl("user",{role:"user",content:`
|
|
583
593
|
|
|
584
594
|
<system-reminder>
|
|
585
|
-
${
|
|
586
|
-
</system-reminder>`});continue}let _=
|
|
595
|
+
${xQ()}
|
|
596
|
+
</system-reminder>`});continue}let _=P0(H.content,N0,!1);if(_.action==="retry"){N0++,D.appendAssistant({role:"assistant",content:H.content||"",reasoningContent:H.reasoningContent});let S=await p(Q,$,H.content||"",K);if(S)K=S;let U={role:"user",content:_.prompt};D.appendControl("user",U);let P=await u(Q,$,U.content,K);if(P)K=P;continue}N0=0;let X=await ZQ({turnsCount:G,maxTurns:C});if(X.action==="continue"){D.appendAssistant({role:"assistant",content:H.content||"",reasoningContent:H.reasoningContent});let S=await p(Q,$,H.content||"",K);if(S)K=S;let U={role:"user",content:`
|
|
587
597
|
|
|
588
598
|
<system-reminder>
|
|
589
599
|
${X.reason}
|
|
590
|
-
</system-reminder>`};
|
|
600
|
+
</system-reminder>`};D.appendControl("user",U);let P=await u(Q,$,U.content,K);if(P)K=P;continue}let j=await f0({sessionId:$.sessionId,permissionMode:$.permissionMode,reason:H.content,abortSignal:J?.signal});if(j.action==="continue"){D.appendAssistant({role:"assistant",content:H.content||"",reasoningContent:H.reasoningContent});let S=await p(Q,$,H.content||"",K);if(S)K=S;let P={role:"user",content:j.reason?`
|
|
591
601
|
|
|
592
602
|
<system-reminder>
|
|
593
|
-
${
|
|
603
|
+
${j.reason}
|
|
594
604
|
</system-reminder>`:`
|
|
595
605
|
|
|
596
606
|
<system-reminder>
|
|
597
607
|
Please continue the conversation from where we left it off without asking the user any further questions. Continue with the last task that you were asked to work on.
|
|
598
|
-
</system-reminder>`};
|
|
608
|
+
</system-reminder>`};D.appendControl("user",P);let y=await u(Q,$,P.content,K);if(y)K=y;continue}D.appendAssistant({role:"assistant",content:H.content||"",reasoningContent:H.reasoningContent});let O=await p(Q,$,H.content||"",K);if(O)K=O;return{success:!0,finalMessage:H.content,metadata:{turnsCount:G,toolCallsCount:V.length,duration:Date.now()-z,tokensUsed:T,toolSuccessRate:V.length>0?V.filter((S)=>S.success).length/V.length:void 0,totalToolFailures:Y.totalFailures||void 0}}}D.appendAssistant({role:"assistant",content:H.content||"",reasoningContent:H.reasoningContent,tool_calls:H.toolCalls});{let _=await p(Q,$,H.content||"",K);if(_)K=_}if(J?.signal?.aborted)return a(G,V.length,z,J.signal);let S0=H.toolCalls.filter((_)=>_.type==="function"),Y0;if(W0?.hasTools()){A.debug(`[Loop] 使用 StreamingToolExecutor 收集 ${S0.length} 个工具结果`),Y0=[];for await(let _ of W0.getRemainingResults())Y0.push(_)}else{for(let X of S0){let O=W.get(X.function.name)?.kind;yield{kind:"tool_start",toolCall:X,toolKind:O}}let _=async(X)=>{try{let j;try{j=JSON.parse(X.function.arguments)}catch(U){let P=CZ(X.function.arguments);if(P===null)return{toolCall:X,result:{success:!1,llmContent:"",error:{type:"validation_error",message:`Invalid JSON in tool arguments: ${U.message}. Raw: ${X.function.arguments.slice(0,200)}`},metadata:void 0},toolUseUuid:null};j=P}if(X.function.name==="Task"&&(typeof j.subagent_session_id!=="string"||j.subagent_session_id.length===0))j.subagent_session_id=typeof j.resume==="string"&&j.resume.length>0?j.resume:RZ();let O=null;O=await R0(Q,$,X.function.name,j,K);let S=await Q.executionPipeline.execute(X.function.name,j,{sessionId:$.sessionId,userId:$.userId||"default",workspaceRoot:$.workspaceRoot||k(),signal:J?.signal,confirmationHandler:$.confirmationHandler,permissionMode:$.permissionMode,toolRegistry:W,deferredToolManager:W.deferredToolManager});return{toolCall:X,result:S,toolUseUuid:O}}catch(j){return A.error(`Tool execution failed for ${X.function.name}:`,j),{toolCall:X,result:{success:!1,llmContent:"",error:{type:"execution_error",message:j instanceof Error?j.message:"Unknown error"},metadata:void 0},toolUseUuid:null,error:j instanceof Error?j:Error("Unknown error")}}};Y0=await Promise.all(S0.map(_))}let gQ=new g0;for(let{toolCall:_,result:X,toolUseUuid:j}of Y0){let O=_;if(V.push(X),X.metadata?.abortedBeforeLaunch)return a(G,V.length,z,J?.signal);yield{kind:"tool_result",toolCall:O,result:X};{let y=X.metadata&&typeof X.metadata==="object"?X.metadata:void 0,mQ=((K0)=>K0==="running"||K0==="completed"||K0==="failed"||K0==="cancelled")(y?.subagentStatus)?y.subagentStatus:"completed",uQ=y&&typeof y.subagentSessionId==="string"?{subagentSessionId:y.subagentSessionId,subagentType:typeof y.subagentType==="string"?y.subagentType:O.function.name,subagentStatus:mQ,subagentSummary:typeof y.subagentSummary==="string"?y.subagentSummary:void 0}:void 0,a0=await T0(Q,$,O.id,O.function.name,X.success?pZ(X.llmContent):null,j,X.success?void 0:X.error?.message,uQ);if(a0)K=a0}let S=await k0(O,X,Q);if(S)yield S;if(X.success)SQ(Y,O.function.name);else MQ(Y,O.function.name);let U=X.success?X.llmContent||"":mZ(O.function.name,X.error);if(!X.success){let y=PQ(Y,O.function.name);if(y&&typeof U==="string")U=`${U}
|
|
599
609
|
|
|
600
|
-
${y}`}if(typeof
|
|
610
|
+
${y}`}if(typeof U==="object"&&U!==null)U=JSON.stringify(U,null,2);if(typeof U==="string")U=jQ(U,O.function.name,{messageBudget:gQ});let P=typeof U==="string"?U:JSON.stringify(U);if(D.appendToolResult({role:"tool",tool_call_id:O.id,name:O.function.name,content:P}),X.metadata?.shouldExitLoop){let y=typeof X.llmContent==="string"?X.llmContent:"循环已退出";return{success:X.success,finalMessage:y,metadata:{turnsCount:G,toolCallsCount:V.length,duration:Date.now()-z,shouldExitLoop:!0,targetMode:X.metadata?.targetMode,planContent:typeof X.metadata?.planContent==="string"?X.metadata.planContent:void 0}}}}if(J?.signal?.aborted)return a(G,V.length,z,J.signal);if(G>=C&&!f){if(A.info(`Warning: 达到轮次上限 ${C} 轮`),J?.onTurnLimitReached){let _=await J.onTurnLimitReached({turnsCount:G});if(_?.continue){D.writeback();try{let X=Q.chatService.getConfig(),j=await r.compact($.messages,{trigger:"auto",modelName:X.model,maxContextTokens:X.maxContextTokens??Q.config.maxContextTokens,apiKey:X.apiKey,baseURL:X.baseUrl,actualPreTokens:s,signal:J?.signal});$.messages=j.compactedMessages,D.replaceHistory($.messages);let O={role:"user",content:`This session is being continued from a previous conversation. The conversation is summarized above.
|
|
601
611
|
|
|
602
|
-
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.`};
|
|
612
|
+
Please continue the conversation from where we left it off without asking the user any further questions. Continue with the last task that you were asked to work on.`};D.appendToHistory(O),await D0(Q,$,j.summary,{trigger:"auto",preTokens:j.preTokens,postTokens:j.postTokens,filesIncluded:j.filesIncluded})}catch(X){A.error("[Loop] 压缩失败,使用降级策略:",X);let O=D.getHistory().slice(-80);D.replaceHistory(O)}G=0;continue}return{success:!0,finalMessage:_?.reason||"已达到对话轮次上限,用户选择停止",metadata:{turnsCount:G,toolCallsCount:V.length,duration:Date.now()-z,tokensUsed:T}}}return{success:!1,error:{type:"max_turns_exceeded",message:`已达到轮次上限 (${C} 轮)。使用 --permission-mode yolo 跳过此限制。`},metadata:{turnsCount:G,toolCallsCount:V.length,duration:Date.now()-z,tokensUsed:T}}}}}finally{D.writeback()}}catch(W){if(n(W))return a(G,V.length,z,J?.signal);let B=dZ(W);return A.error(`API 调用失败: ${B}`),{success:!1,error:{type:"api_error",message:B,details:W},metadata:{turnsCount:G,toolCallsCount:V.length,duration:Date.now()-z}}}}export{W2 as La,h0 as Ma,Y2 as Na,K2 as Oa,eQ as Pa,X2 as Qa,C0 as Ra,bQ as Sa,vQ as Ta,I0 as Ua,EZ as Va,d as Wa,X0 as Xa,H0 as Ya,cQ as Za,M0 as _a,P0 as $a,f0 as ab,u as bb,p as cb,R0 as db,T0 as eb,D0 as fb,$Q as gb,JQ as hb,qQ as ib,k0 as jb,q0 as kb,r as lb,E0 as mb,CQ as nb,lZ as ob};
|