blade-code 0.6.2 → 0.6.4
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-07xv0cqp.js +1 -0
- package/dist/{chunk-t44946na.js → chunk-0e9dhemy.js} +3 -3
- package/dist/{chunk-k4sbqc14.js → chunk-2zk921d9.js} +1 -1
- package/dist/chunk-3mmm8g84.js +1 -0
- package/dist/{chunk-3j3v297d.js → chunk-59e6eg4b.js} +1 -1
- package/dist/{chunk-9ce1fadm.js → chunk-5bs94pb1.js} +9 -9
- package/dist/{chunk-t7hd45rg.js → chunk-6mfmy7nq.js} +2 -2
- package/dist/chunk-7c9k2c9m.js +1 -0
- package/dist/chunk-7t23swne.js +2125 -0
- package/dist/{chunk-39h8jdm3.js → chunk-7ycmx7c2.js} +1 -1
- package/dist/chunk-9p4fe43p.js +1 -0
- package/dist/{chunk-kevt8v3j.js → chunk-9vsbmtqj.js} +1 -1
- package/dist/{chunk-j1ehsp0x.js → chunk-bpx8x87m.js} +2 -2
- package/dist/{chunk-m7xm1ssb.js → chunk-cfe1fywb.js} +1 -1
- package/dist/{chunk-b5nhr3na.js → chunk-ck43cs45.js} +1 -1
- package/dist/{chunk-1cm8qqth.js → chunk-dmc5gf4f.js} +1 -1
- package/dist/chunk-evc1xkeb.js +28 -0
- package/dist/{chunk-mpafvahb.js → chunk-ey640ttd.js} +1 -1
- package/dist/chunk-f24ahjpc.js +1 -0
- package/dist/{chunk-21zps3hb.js → chunk-h46kk20y.js} +1 -1
- package/dist/{chunk-7rjrzngk.js → chunk-hc91pmdk.js} +1 -1
- package/dist/{chunk-s53zeref.js → chunk-j7nh0j36.js} +1 -1
- package/dist/{chunk-ythh98wk.js → chunk-jm9r362m.js} +1 -1
- package/dist/{chunk-dyaxme6k.js → chunk-k063tt5h.js} +1 -1
- package/dist/{chunk-y57hcnk6.js → chunk-m26jr2tg.js} +1 -1
- package/dist/{chunk-67dzm8te.js → chunk-m41xq6d0.js} +1 -1
- package/dist/{chunk-6gycrrb9.js → chunk-mpn4zfcn.js} +1 -1
- package/dist/{chunk-7v6xxyd3.js → chunk-njq4w631.js} +10 -10
- package/dist/{chunk-gn1acna6.js → chunk-nm2w2ftg.js} +1 -1
- package/dist/{chunk-fkttsa1n.js → chunk-p8pggabj.js} +1 -1
- package/dist/{chunk-7010r8zb.js → chunk-qnvkxpkw.js} +1 -1
- package/dist/{chunk-zfy765hj.js → chunk-sfr69fw8.js} +1 -1
- package/dist/{chunk-63954vzc.js → chunk-sh1pk5j3.js} +1 -1
- package/dist/{chunk-2ahbedmp.js → chunk-tdarh4fh.js} +1 -1
- package/dist/{chunk-8a2z6mgp.js → chunk-tz44akn7.js} +1 -1
- package/dist/chunk-vxgexcsm.js +1 -0
- package/dist/{chunk-6vwc66b4.js → chunk-w96xaeyd.js} +1 -1
- package/dist/{chunk-9zbmef4r.js → chunk-zm78rg9t.js} +1 -1
- package/dist/{chunk-cydswa20.js → chunk-zwwvv85t.js} +1 -1
- package/package.json +2 -1
- package/dist/chunk-1t0cavth.js +0 -28
- package/dist/chunk-3ak4p05x.js +0 -1
- package/dist/chunk-4e20kfa4.js +0 -1
- package/dist/chunk-563zye36.js +0 -1
- package/dist/chunk-9pg8nttx.js +0 -2121
- package/dist/chunk-caw1bxy6.js +0 -1
- package/dist/chunk-g7xh4e99.js +0 -1
- package/dist/chunk-n9mwp62v.js +0 -1
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{nb as D0}from"./chunk-0e9dhemy.js";import{rb as LQ}from"./chunk-6mfmy7nq.js";import{xb as T}from"./chunk-7ycmx7c2.js";import{Hb as R,zb as DQ}from"./chunk-bpx8x87m.js";import{Jb as eQ}from"./chunk-j7nh0j36.js";function B0(Q){return Q.role==="system"&&Array.isArray(Q.content)}class j0{systemMessages;_history;_pending=[];context;constructor(Q,Z){this.context=Q;let $=Q.messages.find(B0);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)=>!B0(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)=>!B0(Z))}writeback(){this.commitPending(),this.context.messages=this._history}get hasSystemPrompt(){return this.systemMessages.length>0}}async function tQ(Q,Z){let $;while(!($=await Q.next()).done)if(Z)await Z($.value);return $.value}function ZQ(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 $Q(Q){return{budget:Q.budget,usage:0,consecutiveContinuations:0,lastOutputDelta:0,isSubagent:Q.isSubagent??!1}}function JQ(Q,Z,$){return{...Q,usage:Q.usage+Z,lastOutputDelta:Z,consecutiveContinuations:$?Q.consecutiveContinuations+1:0}}var Q0=R("Agent"),QZ=3;function x0(Q,Z,$){if(Q!=="length")return{action:"none"};if(Z>=QZ)return{action:"truncated"};if(ZQ($)==="stop")return Q0.info("[Loop] Token budget: diminishing returns detected, skipping recovery"),{action:"budget_stop"};return{action:"recover"}}var ZZ=[/:\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],$Z=/```[\s\S]{50,}```/,zQ="请执行你提到的操作,不要只是描述。使用 Edit/Write/Bash 工具来实际修改文件。",JZ=2;function T0(Q,Z,$=!0){if(!Q||Z>=JZ)return{action:"none"};if(!$&&$Z.test(Q))return{action:"retry",prompt:zQ};let J=Q.slice(-200),z=J.match(/```/g);if(z&&z.length%2!==0)return{action:"none"};if(ZZ.some((W)=>W.test(J)))return{action:"retry",prompt:zQ};return{action:"none"}}var zZ=[/\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}(?:测试|单测|集成测试|检查|构建)/],GZ=/(?:^|\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)\b/i,WZ="The user explicitly required verification, but it has not run successfully. Do not finish or explain. Your next action must be a Bash tool call that runs the requested test, lint, type-check, or build command. Inspect the command result and fix any failure before finishing.",VZ="Required verification did not run successfully before the retry limit.",YZ=3;function WQ(Q){return GZ.test(Q)}function VQ(Q,Z,$){if(!Q||!zZ.some((J)=>J.test(Q)))return{action:"none"};if(Z.has("Bash"))return{action:"none"};if($>=YZ)return{action:"fail",message:VZ};return{action:"retry",prompt:WZ}}var KZ=[/\b(?:use|create|enter|start|work\s+(?:in|inside))\b.{0,60}\bworktree\b/i,/(?:使用|创建|进入).{0,30}(?:worktree|工作树)/i],qZ=[/\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 C0(Q){return typeof Q==="string"&&KZ.some((Z)=>Z.test(Q))}var XZ="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.",HZ="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.",BZ="Required worktree lifecycle did not complete before the retry limit.",jZ=3;function YQ(Q,Z,$){if(!Q||!C0(Q))return{action:"none"};let J=qZ.some((G)=>G.test(Q));if(Z.has("TaskWorktree"))return{action:"none"};let z=!Z.has("EnterWorktree")?"EnterWorktree":J&&!Z.has("ExitWorktree")?"ExitWorktree":void 0;if(!z)return{action:"none"};if($>=jZ)return{action:"fail",message:BZ};return{action:"retry",tool:z,prompt:z==="EnterWorktree"?XZ:HZ}}var GQ=30000;async function p0(Q){try{let $=D0.getInstance().executeStopHooks({projectDir:T(),sessionId:Q.sessionId,permissionMode:Q.permissionMode,reason:Q.reason,abortSignal:Q.abortSignal}),J,z=new Promise((G)=>{J=setTimeout(()=>G("timeout"),GQ)});try{let G=await Promise.race([$,z]);if(G==="timeout")return Q0.warn(`[Loop] Stop hook 超时 (${GQ}ms),按 shouldStop: true 处理`),{action:"stop"};let W=G;if(!W.shouldStop)return{action:"continue",reason:W.continueReason};return{action:"stop"}}finally{clearTimeout(J)}}catch(Z){return Q0.warn("[Loop] Stop hook execution failed:",Z),{action:"stop"}}}var DZ=0.9;async function KQ(Q){try{let{SpecManager:Z}=await import("./chunk-07xv0cqp.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*DZ)return Q0.info(`[RalphLoop] 轮次接近上限 (${Q.turnsCount}/${Q.maxTurns}),停止自动继续`),{action:"none"};let z=J.tasks??[],G=z.filter((j)=>j.status==="completed"||j.status==="skipped").length,W=z.length;if(G>=W)return{action:"none"};let V=z.find((j)=>j.status==="pending"||j.status==="in_progress"),Y=`[Ralph Loop] Spec "${J.name}" 仍有未完成任务。
|
|
2
2
|
`+`进度: ${G}/${W} 任务已完成。
|
|
3
3
|
`+(V?`下一个任务: ${V.title}${V.description?` — ${V.description}`:""}
|
|
4
|
-
`:"")+"请继续执行下一个未完成的任务,不要停止。";return Q0.info(`[RalphLoop] Spec "${J.name}" 进度 ${G}/${W},自动继续`),{action:"continue",reason:Y}}catch{return{action:"none"}}}var $0=R("Agent");function J0(Q){return Q.executionEngine?.getContextManager()}async function g(Q,Z,$,J=null){try{let z=J0(Q),G=typeof $==="string"?$.trim()!=="":$.some((W)=>W.type==="text"?W.text.trim()!=="":!0);if(z&&Z.sessionId&&G)return await z.saveMessage(Z.sessionId,"user",$,J,void 0,Z.subagentInfo)}catch(z){$0.warn("[Loop] 保存用户消息失败:",z)}return null}async function h(Q,Z,$,J){try{let z=J0(Q);if(z&&Z.sessionId&&$.trim())return await z.saveMessage(Z.sessionId,"assistant",$,J,void 0,Z.subagentInfo)}catch(z){$0.warn("[Loop] 保存助手消息失败:",z)}return null}async function d0(Q,Z,$,J,z){try{let G=J0(Q);if(G&&Z.sessionId)return await G.saveToolUse(Z.sessionId,$,J,z,Z.subagentInfo)}catch(G){$0.warn("[Loop] 保存工具调用失败:",G)}return null}async function m0(Q,Z,$,J,z,G,W,V){try{let Y=J0(Q);if(Y&&Z.sessionId)return await Y.saveToolResult(Z.sessionId,$,J,z,G,W,Z.subagentInfo,V)}catch(Y){$0.warn("[Loop] 保存工具结果失败:",Y)}return null}async function F0(Q,Z,$,J){try{let z=J0(Q);if(z&&Z.sessionId)return await z.saveCompaction(Z.sessionId,$,J,null)}catch(z){$0.warn("[Loop] 保存压缩数据失败:",z)}return null}function qQ(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 XQ(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 HQ(Q){let Z=Q.metadata;if(!Z)return;return Z.modelId?.toString().trim()||Z.model?.toString().trim()||void 0||void 0}function FZ(Q,Z,$){if(!["EnterWorktree","ExitWorktree"].includes(Q.function.name)||!Z.success)return;let J=Z.metadata,z=J?.workspaceRoot;if(!["enter","exit"].includes(String(J?.workspaceTransition))||typeof z!=="string"||z.trim()==="")return;return $.workspaceRoot=z,z}function bZ(Q,Z){if(Q.function.name!=="Task")return null;let $=Z.metadata;if(!$?.subagentSessionId)return null;let J=$.subagentSessionId,z=$.subagentType||"Task",G=$.subagentStatus;if(G==="completed"||G==="failed"||G==="cancelled")return{kind:"subagent_completed",sessionId:J,success:G==="completed",summary:$.subagentSummary};if(G==="running"){let W="";try{W=JSON.parse(Q.function.arguments).prompt||""}catch{}return{kind:"subagent_spawned",sessionId:J,type:z,prompt:W}}return null}async function g0(Q,Z,$,J){let z=qQ(Q,Z),G=bZ(Q,Z);XQ(Q,Z,$);let W=HQ(Z);if(W)await $.onModelSwitch?.(W);if(J)FZ(Q,Z,J);return G||z}import{nanoid as sZ}from"nanoid";import{nanoid as r}from"nanoid";import{promises as UZ}from"node:fs";import*as E from"node:fs/promises";import*as l from"node:path";var BQ={enabled:!0,maxIndexLines:200};var wZ="memory",jQ="MEMORY.md";class c0{memoryDir;config;initialized=!1;constructor(Q,Z,$){if($)this.memoryDir=$;else{let J=DQ(Q);this.memoryDir=l.join(J,wZ)}this.config={...BQ,...Z}}async initialize(){if(this.initialized)return;await E.mkdir(this.memoryDir,{recursive:!0}),this.initialized=!0}async loadIndex(){if(!this.config.enabled)return null;await this.initialize();let Q=l.join(this.memoryDir,jQ);try{let Z=await E.readFile(Q,"utf-8");if(!Z.trim())return null;let $=Z.split(`
|
|
4
|
+
`:"")+"请继续执行下一个未完成的任务,不要停止。";return Q0.info(`[RalphLoop] Spec "${J.name}" 进度 ${G}/${W},自动继续`),{action:"continue",reason:Y}}catch{return{action:"none"}}}var $0=R("Agent");function J0(Q){return Q.executionEngine?.getContextManager()}async function g(Q,Z,$,J=null){try{let z=J0(Q),G=typeof $==="string"?$.trim()!=="":$.some((W)=>W.type==="text"?W.text.trim()!=="":!0);if(z&&Z.sessionId&&G)return await z.saveMessage(Z.sessionId,"user",$,J,void 0,Z.subagentInfo)}catch(z){$0.warn("[Loop] 保存用户消息失败:",z)}return null}async function h(Q,Z,$,J){try{let z=J0(Q);if(z&&Z.sessionId&&$.trim())return await z.saveMessage(Z.sessionId,"assistant",$,J,void 0,Z.subagentInfo)}catch(z){$0.warn("[Loop] 保存助手消息失败:",z)}return null}async function d0(Q,Z,$,J,z){try{let G=J0(Q);if(G&&Z.sessionId)return await G.saveToolUse(Z.sessionId,$,J,z,Z.subagentInfo)}catch(G){$0.warn("[Loop] 保存工具调用失败:",G)}return null}async function m0(Q,Z,$,J,z,G,W,V){try{let Y=J0(Q);if(Y&&Z.sessionId)return await Y.saveToolResult(Z.sessionId,$,J,z,G,W,Z.subagentInfo,V)}catch(Y){$0.warn("[Loop] 保存工具结果失败:",Y)}return null}async function F0(Q,Z,$,J){try{let z=J0(Q);if(z&&Z.sessionId)return await z.saveCompaction(Z.sessionId,$,J,null)}catch(z){$0.warn("[Loop] 保存压缩数据失败:",z)}return null}function qQ(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 XQ(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 HQ(Q){let Z=Q.metadata;if(!Z)return;return Z.modelId?.toString().trim()||Z.model?.toString().trim()||void 0||void 0}function FZ(Q,Z,$){if(!["EnterWorktree","ExitWorktree"].includes(Q.function.name)||!Z.success)return;let J=Z.metadata,z=J?.workspaceRoot;if(!["enter","exit"].includes(String(J?.workspaceTransition))||typeof z!=="string"||z.trim()==="")return;return $.workspaceRoot=z,$.worktreeActive=J?.workspaceTransition==="enter",z}function bZ(Q,Z){if(Q.function.name!=="Task")return null;let $=Z.metadata;if(!$?.subagentSessionId)return null;let J=$.subagentSessionId,z=$.subagentType||"Task",G=$.subagentStatus;if(G==="completed"||G==="failed"||G==="cancelled")return{kind:"subagent_completed",sessionId:J,success:G==="completed",summary:$.subagentSummary};if(G==="running"){let W="";try{W=JSON.parse(Q.function.arguments).prompt||""}catch{}return{kind:"subagent_spawned",sessionId:J,type:z,prompt:W}}return null}async function g0(Q,Z,$,J){let z=qQ(Q,Z),G=bZ(Q,Z);XQ(Q,Z,$);let W=HQ(Z);if(W)await $.onModelSwitch?.(W);if(J)FZ(Q,Z,J);return G||z}import{nanoid as sZ}from"nanoid";import{nanoid as r}from"nanoid";import{promises as UZ}from"node:fs";import*as E from"node:fs/promises";import*as l from"node:path";var BQ={enabled:!0,maxIndexLines:200};var wZ="memory",jQ="MEMORY.md";class c0{memoryDir;config;initialized=!1;constructor(Q,Z,$){if($)this.memoryDir=$;else{let J=DQ(Q);this.memoryDir=l.join(J,wZ)}this.config={...BQ,...Z}}async initialize(){if(this.initialized)return;await E.mkdir(this.memoryDir,{recursive:!0}),this.initialized=!0}async loadIndex(){if(!this.config.enabled)return null;await this.initialize();let Q=l.join(this.memoryDir,jQ);try{let Z=await E.readFile(Q,"utf-8");if(!Z.trim())return null;let $=Z.split(`
|
|
5
5
|
`),z=$.slice(0,this.config.maxIndexLines).join(`
|
|
6
6
|
`).trim();if($.length>this.config.maxIndexLines)return z+`
|
|
7
7
|
|
|
@@ -9,14 +9,14 @@ import{ob as D0}from"./chunk-t44946na.js";import{sb as LQ}from"./chunk-t7hd45rg.
|
|
|
9
9
|
`)?`
|
|
10
10
|
`:"";await E.writeFile(J,z+G+Z,"utf-8")}else await E.writeFile(J,Z,"utf-8")}async updateIndex(Q,Z="overwrite"){await this.initialize();let $=l.join(this.memoryDir,jQ);if(Z==="append"){let J="";try{J=await E.readFile($,"utf-8")}catch{}let z=J&&!J.endsWith(`
|
|
11
11
|
`)?`
|
|
12
|
-
`:"";await E.writeFile($,J+z+Q,"utf-8")}else await E.writeFile($,Q,"utf-8")}async listTopics(){await this.initialize();try{let Q=await E.readdir(this.memoryDir,{withFileTypes:!0}),Z=[];for(let $ of Q){if(!$.isFile()||!$.name.endsWith(".md"))continue;let J=l.join(this.memoryDir,$.name),z=await E.stat(J);Z.push({name:$.name.replace(/\.md$/,""),size:z.size,lastModified:z.mtime})}return Z.sort(($,J)=>J.lastModified.getTime()-$.lastModified.getTime())}catch{return[]}}async deleteTopic(Q){let Z=this.resolveTopicPath(Q);try{return await E.unlink(Z),!0}catch{return!1}}async clearAll(){let Q=await this.listTopics(),Z=0;for(let $ of Q){let J=l.join(this.memoryDir,`${$.name}.md`);try{await E.unlink(J),Z++}catch{}}return Z}getMemoryDir(){return this.memoryDir}resolveTopicPath(Q){let Z=Q.replace(/[/\\:*?"<>|]/g,"-"),$=Z.endsWith(".md")?Z:`${Z}.md`,J=l.join(this.memoryDir,$);if(!J.startsWith(this.memoryDir))throw Error(`Invalid topic name: ${Q}`);return J}}var LZ=[{pattern:/(?:记住|remember|note|备注)[::](.+)/i,topic:"preferences"},{pattern:/(?:convention|约定|规范)[::](.+)/i,topic:"conventions"},{pattern:/(?:lesson|教训|踩坑)[::](.+)/i,topic:"lessons"}],OZ=/(?:fix|修复|解决|resolved)[::]\s*(.+?)(?:\n|$)/i,vZ=/(?:Error|FAIL|错误)[::]\s*(.+?)(?:\n|$)/i;function _Z(Q){let Z=new Map;for(let $ of Q){if(!$.content||typeof $.content!=="string")continue;let J=$.content;if($.role==="user")for(let{pattern:z,topic:G}of LZ){let W=J.match(z);if(W?.[1]){let V=Z.get(G)??[];V.push(W[1].trim()),Z.set(G,V)}}if($.role==="assistant"){let z=J.match(OZ);if(z?.[1]&&z[1].length>20&&z[1].length<200){let G=Z.get("debugging")??[];G.push(z[1].trim()),Z.set("debugging",G)}}if($.role==="tool"&&$.content?.includes("Error")){let z=J.match(vZ);if(z?.[1]&&z[1].length>10){let G=Z.get("debugging")??[];if(G.length<5)G.push(`Tool error pattern: ${z[1].trim().slice(0,150)}`),Z.set("debugging",G)}}}return Z}async function FQ(Q){let Z=_Z(Q);if(Z.size===0)return{extracted:0,topics:[]};try{let $=new c0(
|
|
12
|
+
`:"";await E.writeFile($,J+z+Q,"utf-8")}else await E.writeFile($,Q,"utf-8")}async listTopics(){await this.initialize();try{let Q=await E.readdir(this.memoryDir,{withFileTypes:!0}),Z=[];for(let $ of Q){if(!$.isFile()||!$.name.endsWith(".md"))continue;let J=l.join(this.memoryDir,$.name),z=await E.stat(J);Z.push({name:$.name.replace(/\.md$/,""),size:z.size,lastModified:z.mtime})}return Z.sort(($,J)=>J.lastModified.getTime()-$.lastModified.getTime())}catch{return[]}}async deleteTopic(Q){let Z=this.resolveTopicPath(Q);try{return await E.unlink(Z),!0}catch{return!1}}async clearAll(){let Q=await this.listTopics(),Z=0;for(let $ of Q){let J=l.join(this.memoryDir,`${$.name}.md`);try{await E.unlink(J),Z++}catch{}}return Z}getMemoryDir(){return this.memoryDir}resolveTopicPath(Q){let Z=Q.replace(/[/\\:*?"<>|]/g,"-"),$=Z.endsWith(".md")?Z:`${Z}.md`,J=l.join(this.memoryDir,$);if(!J.startsWith(this.memoryDir))throw Error(`Invalid topic name: ${Q}`);return J}}var LZ=[{pattern:/(?:记住|remember|note|备注)[::](.+)/i,topic:"preferences"},{pattern:/(?:convention|约定|规范)[::](.+)/i,topic:"conventions"},{pattern:/(?:lesson|教训|踩坑)[::](.+)/i,topic:"lessons"}],OZ=/(?:fix|修复|解决|resolved)[::]\s*(.+?)(?:\n|$)/i,vZ=/(?:Error|FAIL|错误)[::]\s*(.+?)(?:\n|$)/i;function _Z(Q){let Z=new Map;for(let $ of Q){if(!$.content||typeof $.content!=="string")continue;let J=$.content;if($.role==="user")for(let{pattern:z,topic:G}of LZ){let W=J.match(z);if(W?.[1]){let V=Z.get(G)??[];V.push(W[1].trim()),Z.set(G,V)}}if($.role==="assistant"){let z=J.match(OZ);if(z?.[1]&&z[1].length>20&&z[1].length<200){let G=Z.get("debugging")??[];G.push(z[1].trim()),Z.set("debugging",G)}}if($.role==="tool"&&$.content?.includes("Error")){let z=J.match(vZ);if(z?.[1]&&z[1].length>10){let G=Z.get("debugging")??[];if(G.length<5)G.push(`Tool error pattern: ${z[1].trim().slice(0,150)}`),Z.set("debugging",G)}}}return Z}async function FQ(Q){let Z=_Z(Q);if(Z.size===0)return{extracted:0,topics:[]};try{let $=new c0(T());await $.initialize();let J=[],z=0;for(let[G,W]of Z){if(W.length===0)continue;let V=new Date().toISOString().split("T")[0],Y=W.map((j)=>`- [${V}] ${j}`).join(`
|
|
13
13
|
`);await $.writeTopic(G,Y+`
|
|
14
14
|
`,"append"),J.push(G),z+=W.length}return{extracted:z,topics:J}}catch{return{extracted:0,topics:[]}}}import{promises as b0}from"node:fs";var z0=R("Tool");class u{static instance=null;accessedFiles=new Map;constructor(){}static getInstance(){if(!u.instance)u.instance=new u;return u.instance}async recordFileRead(Q,Z){try{let $=await b0.stat(Q),J={filePath:Q,accessTime:Date.now(),mtime:$.mtimeMs,sessionId:Z,lastOperation:"read"};this.accessedFiles.set(Q,J),z0.debug(`记录文件读取: ${Q}`)}catch($){z0.warn(`记录文件读取失败: ${Q}`,$)}}async recordFileEdit(Q,Z,$="edit"){try{let J=await b0.stat(Q),z={filePath:Q,accessTime:Date.now(),mtime:J.mtimeMs,sessionId:Z,lastOperation:$};this.accessedFiles.set(Q,z),z0.debug(`记录文件${$==="edit"?"编辑":"写入"}: ${Q}`)}catch(J){z0.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 b0.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 b0.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 z0.warn(`检查文件外部修改失败: ${Q}`,$),{isExternal:!1,message:`无法检查文件状态: ${J.message}`}}}getFileRecord(Q){return this.accessedFiles.get(Q)}clearFileRecord(Q){this.accessedFiles.delete(Q)}clearAll(){this.accessedFiles.clear()}clearSession(Q){for(let[Z,$]of this.accessedFiles.entries())if($.sessionId===Q)this.accessedFiles.delete(Z)}getTrackedFiles(){return Array.from(this.accessedFiles.keys())}getTrackedFileCount(){return this.accessedFiles.size}static resetInstance(){u.instance=null}}function a(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 bQ(...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 G of Z)if(G.aborted)return G;let J=new AbortController,z=new Map;for(let G of Z){let W=()=>{J.abort(G.reason);for(let[V,Y]of z)V.removeEventListener("abort",Y)};z.set(G,W)}for(let[G,W]of z)G.addEventListener("abort",W,{once:!0});return J.signal}import{readFile as NZ}from"node:fs/promises";import{basename as IZ}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,z)=>{let G=typeof J.content==="string"?J.content:(J.content||[]).filter((V)=>V.type==="text").map((V)=>V.text).join(`
|
|
15
15
|
`);if(this.extractFilePathsFromContent(G).forEach((V)=>{this.updateFileReference(Z,V,z,!1)}),J.tool_calls&&Array.isArray(J.tool_calls))J.tool_calls.forEach((V)=>{let Y=this.extractFilePathsFromToolCall(V),j=V.type==="function"&&"function"in V?V.function?.name:"",w=["Write","Edit"].includes(j||"");Y.forEach((L)=>{this.updateFileReference(Z,L,z,w)})})}),Array.from(Z.values()).sort((J,z)=>{if(J.wasModified!==z.wasModified)return J.wasModified?-1:1;if(J.mentions!==z.mentions)return z.mentions-J.mentions;return z.lastMentioned-J.lastMentioned}).slice(0,this.MAX_FILES)}static async readFilesContent(Q){let Z=[];for(let $ of Q)try{let J=await NZ($,"utf-8"),z=J.split(`
|
|
16
16
|
`),G=z.length,W=J,V=!1,Y=G;if(G>this.MAX_LINES_PER_FILE)W=z.slice(0,this.MAX_LINES_PER_FILE).join(`
|
|
17
17
|
`),W+=`
|
|
18
18
|
|
|
19
|
-
... (truncated ${G-this.MAX_LINES_PER_FILE} lines)`,V=!0,Y=this.MAX_LINES_PER_FILE;Z.push({path:$,content:W,truncated:V,lines:G,includedLines:Y})}catch(J){console.warn(`[FileAnalyzer] 无法读取文件: ${$}`,J)}return Z}static extractFilePathsFromContent(Q){let Z=new Set,$=/```(?:\w+)?\s*\n?([\s\S]*?)```/g,J=Array.from(Q.matchAll($));for(let G of J){let W=G[1];this.extractPathsFromText(W).forEach((Y)=>Z.add(Y))}return this.extractPathsFromText(Q).forEach((G)=>Z.add(G)),Array.from(Z)}static extractPathsFromText(Q){let Z=[],$=[/(?:src|tests?|docs?|lib|config|scripts?|bin|utils?|components?|services?|hooks?)\/[\w\-/.]+\.[\w]+/g,/(?:package|tsconfig|vite\.config|webpack\.config|next\.config|babel\.config)\.[\w]+/g,/(?:\.\.?\/|\/)[a-zA-Z0-9\-_/.]+\.[\w]+/g];for(let J of $){let z=Array.from(Q.matchAll(J));for(let G of z){let W=G[0];if(W=W.replace(/[,。;:!?""''()【】《》]$/g,""),W=W.replace(/[,.;:!?"'()[\]<>]$/g,""),this.isValidFilePath(W))Z.push(W)}}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 G=["file_path","path","notebook_path","filePath"];for(let W of G)if(J[W]&&typeof J[W]==="string")Z.push(J[W])}}catch{}return Z}static updateFileReference(Q,Z,$,J){let z=Q.get(Z);if(z)z.mentions++,z.lastMentioned=$,z.wasModified=z.wasModified||J;else Q.set(Z,{path:Z,mentions:1,lastMentioned:$,wasModified:J})}static isValidFilePath(Q){if(!Q.includes("/"))return!1;let Z=IZ(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 wQ}from"js-tiktoken";class G0{static encodingCache=new Map;static countTokens(Q,Z){let $=this.getEncoding(Z),J=0;for(let z of Q){if(J+=4,z.role)J+=$.encode(z.role).length;if(z.content)if(typeof z.content==="string")J+=$.encode(z.content).length;else J+=$.encode(JSON.stringify(z.content)).length;if(z.tool_calls&&Array.isArray(z.tool_calls))J+=this.countToolCallTokens(z.tool_calls,$);if(z.name)J+=$.encode(z.name).length}return J}static getTokenLimit(Q){return Q}static shouldCompact(Q,Z,$,J=0.8){let z=this.countTokens(Q,Z),G=Math.floor($*J);return z>=G}static getEncoding(Q){if(!this.encodingCache.has(Q))try{let Z=wQ(Q);this.encodingCache.set(Q,Z)}catch{try{let Z=wQ("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 L0=new Map,yZ=3;class s{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??G0.countTokens(Q,Z.modelName),J=Z.actualPreTokens?"actual (from LLM usage)":"estimated";console.log(`[CompactionService] preTokens source: ${J}`);try{let V=await D0.getInstance().executeCompactionHooks(Z.trigger,{projectDir:
|
|
19
|
+
... (truncated ${G-this.MAX_LINES_PER_FILE} lines)`,V=!0,Y=this.MAX_LINES_PER_FILE;Z.push({path:$,content:W,truncated:V,lines:G,includedLines:Y})}catch(J){console.warn(`[FileAnalyzer] 无法读取文件: ${$}`,J)}return Z}static extractFilePathsFromContent(Q){let Z=new Set,$=/```(?:\w+)?\s*\n?([\s\S]*?)```/g,J=Array.from(Q.matchAll($));for(let G of J){let W=G[1];this.extractPathsFromText(W).forEach((Y)=>Z.add(Y))}return this.extractPathsFromText(Q).forEach((G)=>Z.add(G)),Array.from(Z)}static extractPathsFromText(Q){let Z=[],$=[/(?:src|tests?|docs?|lib|config|scripts?|bin|utils?|components?|services?|hooks?)\/[\w\-/.]+\.[\w]+/g,/(?:package|tsconfig|vite\.config|webpack\.config|next\.config|babel\.config)\.[\w]+/g,/(?:\.\.?\/|\/)[a-zA-Z0-9\-_/.]+\.[\w]+/g];for(let J of $){let z=Array.from(Q.matchAll(J));for(let G of z){let W=G[0];if(W=W.replace(/[,。;:!?""''()【】《》]$/g,""),W=W.replace(/[,.;:!?"'()[\]<>]$/g,""),this.isValidFilePath(W))Z.push(W)}}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 G=["file_path","path","notebook_path","filePath"];for(let W of G)if(J[W]&&typeof J[W]==="string")Z.push(J[W])}}catch{}return Z}static updateFileReference(Q,Z,$,J){let z=Q.get(Z);if(z)z.mentions++,z.lastMentioned=$,z.wasModified=z.wasModified||J;else Q.set(Z,{path:Z,mentions:1,lastMentioned:$,wasModified:J})}static isValidFilePath(Q){if(!Q.includes("/"))return!1;let Z=IZ(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 wQ}from"js-tiktoken";class G0{static encodingCache=new Map;static countTokens(Q,Z){let $=this.getEncoding(Z),J=0;for(let z of Q){if(J+=4,z.role)J+=$.encode(z.role).length;if(z.content)if(typeof z.content==="string")J+=$.encode(z.content).length;else J+=$.encode(JSON.stringify(z.content)).length;if(z.tool_calls&&Array.isArray(z.tool_calls))J+=this.countToolCallTokens(z.tool_calls,$);if(z.name)J+=$.encode(z.name).length}return J}static getTokenLimit(Q){return Q}static shouldCompact(Q,Z,$,J=0.8){let z=this.countTokens(Q,Z),G=Math.floor($*J);return z>=G}static getEncoding(Q){if(!this.encodingCache.has(Q))try{let Z=wQ(Q);this.encodingCache.set(Q,Z)}catch{try{let Z=wQ("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 L0=new Map,yZ=3;class s{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??G0.countTokens(Q,Z.modelName),J=Z.actualPreTokens?"actual (from LLM usage)":"estimated";console.log(`[CompactionService] preTokens source: ${J}`);try{let V=await D0.getInstance().executeCompactionHooks(Z.trigger,{projectDir:T(),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(W){console.warn("[CompactionService] Compaction hook execution failed:",W)}let z=Z.sessionId??"_default",G=L0.get(z)??0;if(G>=yZ)return console.warn(`[CompactionService] Circuit breaker open (${G} consecutive failures for session ${z}), 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 Y=await w0.readFilesContent(V);console.log("[CompactionService] 成功读取文件:",Y.length);let j=await this.generateSummary(Q,Y,Z);console.log("[CompactionService] 生成总结,长度:",j.length);let w=Math.ceil(Q.length*this.RETAIN_PERCENT),L=Q.slice(-w),H=new Set;for(let M of L)if(M.role==="assistant"&&M.tool_calls)for(let n of M.tool_calls)H.add(n.id);let O=L.filter((M)=>{if(M.role==="tool"&&M.tool_call_id)return H.has(M.tool_call_id);return!0});console.log("[CompactionService] 保留消息数:",w),console.log("[CompactionService] 过滤后保留消息数:",O.length);let y=r(),B=this.createBoundaryMessage(y,Z.trigger,$),K=r(),k=this.createSummaryMessage(K,j),C=[k,...O],d=await this.buildFileRestorationMessage();if(d)C.push(d);let f=G0.countTokens(C,Z.modelName);console.log("[CompactionService] 压缩完成!"),console.log("[CompactionService] Token 变化:",$,"->",f,`(-${((1-f/$)*100).toFixed(1)}%)`),L0.delete(z);let e=Q.slice(0,Q.length-w);return FQ(e).catch((M)=>{return}),{success:!0,summary:j,preTokens:$,postTokens:f,filesIncluded:V,compactedMessages:C,boundaryMessage:B,summaryMessage:k}}catch(W){if(a(W))throw W;return L0.set(z,(L0.get(z)??0)+1),console.error("[CompactionService] 压缩失败,使用降级策略",W),this.fallbackCompact(Q,Z,$,W)}}static async generateSummary(Q,Z,$){let J=this.buildCompactionPrompt(Q,Z);if(console.log("[CompactionService] 使用压缩模型:",$.modelName),$.signal?.aborted)throw new DOMException("Aborted","AbortError");let W=(await(await LQ({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=W.match(/<summary>([\s\S]*?)<\/summary>/);if(!V)return console.warn("[CompactionService] 总结格式不正确,使用完整响应"),W;return V[1].trim()}static buildCompactionPrompt(Q,Z){let $=Q.map((G,W)=>{let V=G.role||"unknown",Y=typeof G.content==="string"?G.content:JSON.stringify(G.content),j=5000,w=Y.length>5000?Y.substring(0,5000)+"...":Y;return`[${W+1}] ${V}: ${w}`}).join(`
|
|
20
20
|
|
|
21
21
|
`),J=Z.map((G)=>{return`### ${G.path}
|
|
22
22
|
\`\`\`
|
|
@@ -570,7 +570,7 @@ ConfigTool({
|
|
|
570
570
|
2. **permissions 字段使用 replace 策略**:设置 permissions 会完全替换现有值。如果只想添加规则,先 GET 当前值,合并后再 SET
|
|
571
571
|
3. **env 字段使用 deep-merge 策略**:可以逐个添加环境变量
|
|
572
572
|
4. **scope 默认值**:不指定 scope 时,根据字段路由表决定(hooks/permissions/env 默认 local,temperature/theme 等默认 global)
|
|
573
|
-
`}}import{exec as kZ}from"node:child_process";import*as F from"node:fs/promises";import{homedir as RZ}from"node:os";import*as U from"node:path";import{promisify as xZ}from"node:util";var _0=xZ(kZ),I=R("General"),l0={url:"https://github.com/anthropics/skills.git",branch:"main",defaultSkills:["skill-creator"]};class EQ{skillsDir;constructor(Q){this.skillsDir=Q||U.join(RZ(),".blade","skills")}async isInstalled(Q){let Z=U.join(this.skillsDir,Q,"SKILL.md");try{return await F.access(Z),!0}catch{return!1}}async isGitAvailable(){try{return await _0("git --version"),!0}catch{return!1}}async installOfficialSkill(Q){let{url:Z,branch:$}=l0,J=U.join(this.skillsDir,Q),z=U.join(this.skillsDir,`.tmp-${Q}-${Date.now()}`);try{if(!await this.isGitAvailable())return I.warn("Git not available, skipping skill installation"),!1;I.info(`Installing official skill: ${Q}...`),await F.mkdir(this.skillsDir,{recursive:!0,mode:493}),await _0(`git clone --depth 1 --branch ${$} --single-branch ${Z} "${z}"`,{timeout:30000});let G=U.join(z,"skills",Q);try{await F.access(G)}catch{return I.warn(`Skill ${Q} not found in official repository`),await F.rm(z,{recursive:!0,force:!0}),!1}try{await F.rm(J,{recursive:!0,force:!0})}catch{}return await F.cp(G,J,{recursive:!0}),await F.rm(z,{recursive:!0,force:!0}),I.info(`Successfully installed: ${Q}`),!0}catch(G){try{await F.rm(z,{recursive:!0,force:!0})}catch{}return I.warn(`Failed to install ${Q}: ${G instanceof Error?G.message:"Unknown error"}`),!1}}async ensureDefaultSkillsInstalled(){await F.mkdir(this.skillsDir,{recursive:!0,mode:493});for(let Q of l0.defaultSkills)if(!await this.isInstalled(Q))await this.installOfficialSkill(Q)}async installFromRepo(Q,Z){let $=Z||this.extractRepoName(Q),J=U.join(this.skillsDir,$),z=U.join(this.skillsDir,`.tmp-repo-${$}-${Date.now()}`);try{if(!await this.isGitAvailable())return I.warn("Git not available, cannot install from repo"),!1;I.info(`Installing skill from repo: ${Q}...`),await F.mkdir(this.skillsDir,{recursive:!0,mode:493}),await _0(`git clone --depth 1 "${Q}" "${z}"`,{timeout:60000});let G=U.join(z,"SKILL.md");try{await F.access(G)}catch{return I.warn(`No SKILL.md found in repository ${Q}`),await F.rm(z,{recursive:!0,force:!0}),!1}await F.rm(J,{recursive:!0,force:!0}),await F.rename(z,J);try{await F.rm(U.join(J,".git"),{recursive:!0,force:!0})}catch{}return I.info(`Successfully installed skill from repo: ${$}`),!0}catch(G){try{await F.rm(z,{recursive:!0,force:!0})}catch{}return I.warn(`Failed to install from repo ${Q}: ${G instanceof Error?G.message:"Unknown error"}`),!1}}async installFromLocal(Q,Z,$=!0){let J=Z||U.basename(Q),z=U.join(this.skillsDir,J);try{let G=U.resolve(Q);try{await F.access(G)}catch{return I.warn(`Local path does not exist: ${G}`),!1}let W=U.join(G,"SKILL.md");try{await F.access(W)}catch{return I.warn(`No SKILL.md found in local path: ${G}`),!1}if(I.info(`Installing skill from local path: ${G}...`),await F.mkdir(this.skillsDir,{recursive:!0,mode:493}),await F.rm(z,{recursive:!0,force:!0}),$)await F.symlink(G,z,"dir"),I.info(`Created symlink for skill: ${J}`);else await F.cp(G,z,{recursive:!0}),I.info(`Copied skill to: ${J}`);return!0}catch(G){return I.warn(`Failed to install from local path ${Q}: ${G instanceof Error?G.message:"Unknown error"}`),!1}}extractRepoName(Q){return Q.match(/\/([^/]+?)(\.git)?$/)?.[1]||"unknown-skill"}async installAllOfficialSkills(){let{url:Q,branch:Z}=l0,$=U.join(this.skillsDir,`.tmp-all-${Date.now()}`),J=[],z=[];try{if(!await this.isGitAvailable())return I.warn("Git not available, skipping skill installation"),{installed:J,failed:z};await F.mkdir(this.skillsDir,{recursive:!0,mode:493}),I.info("Cloning official skills repository..."),await _0(`git clone --depth 1 --branch ${Z} --single-branch ${Q} "${$}"`,{timeout:60000});let G=U.join($,"skills"),W=await F.readdir(G,{withFileTypes:!0});for(let V of W){if(!V.isDirectory())continue;let Y=V.name,j=U.join(G,Y),w=U.join(this.skillsDir,Y);try{await F.access(U.join(j,"SKILL.md")),await F.rm(w,{recursive:!0,force:!0}),await F.cp(j,w,{recursive:!0}),I.info(`Installed: ${Y}`),J.push(Y)}catch(L){I.warn(`Failed to install ${Y}`),z.push(Y)}}await F.rm($,{recursive:!0,force:!0})}catch(G){try{await F.rm($,{recursive:!0,force:!0})}catch{}I.warn(`Failed to install skills: ${G instanceof Error?G.message:"Unknown error"}`)}return{installed:J,failed:z}}}var a0=null;function SQ(Q){if(!a0)a0=new EQ(Q);return a0}import*as Y0 from"node:fs/promises";import*as N0 from"node:path";import{parse as TZ}from"yaml";var CZ=/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/,pZ=/^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]?$/,AQ=1024;function dZ(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 PQ(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 mZ(Q,Z){if(!Q.name)return{valid:!1,error:"Missing required field: name"};if(!pZ.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>AQ)return{valid:!1,error:`Description too long: ${Q.description.length} characters (max ${AQ})`};let $;if(Q.model)$=Q.model==="inherit"?"inherit":Q.model;return{valid:!0,metadata:{name:Q.name,description:Q.description.trim(),allowedTools:dZ(Q["allowed-tools"]),version:Q.version,argumentHint:Q["argument-hint"]?.trim(),userInvocable:PQ(Q["user-invocable"]),disableModelInvocation:PQ(Q["disable-model-invocation"]),model:$,whenToUse:Q.when_to_use?.trim()}}}function MQ(Q,Z,$){let J=Q.match(CZ);if(!J)return{success:!1,error:"Invalid SKILL.md format: missing YAML frontmatter (must start with ---)"};let[,z,G]=J,W;try{W=TZ(z)}catch(j){return{success:!1,error:`Failed to parse YAML frontmatter: ${j instanceof Error?j.message:String(j)}`}}let V=mZ(W,Z);if(!V.valid)return{success:!1,error:V.error};let Y=N0.dirname(Z);return{success:!0,content:{metadata:{...V.metadata,path:Z,basePath:Y,source:$},instructions:G.trim()}}}async function fQ(Q,Z){try{let $=await Y0.readFile(Q,"utf-8");return MQ($,Q,Z)}catch($){if($.code==="ENOENT")return{success:!1,error:`File not found: ${Q}`};return{success:!1,error:`Failed to read file: ${$ instanceof Error?$.message:String($)}`}}}async function hQ(Q){try{let Z=await Y0.readFile(Q.path,"utf-8"),$=MQ(Z,Q.path,Q.source);return $.success?$.content:null}catch{return null}}async function kQ(Q){try{return await Y0.access(N0.join(Q,"SKILL.md")),!0}catch{return!1}}var gZ={userSkillsDir:p.join(RQ(),".blade","skills"),projectSkillsDir:".blade/skills",claudeUserSkillsDir:p.join(RQ(),".claude","skills"),claudeProjectSkillsDir:".claude/skills"},I0=null;class r0{skills=new Map;pluginSkills=new Map;config;initialized=!1;constructor(Q){this.config={...gZ,cwd:
|
|
573
|
+
`}}import{exec as kZ}from"node:child_process";import*as F from"node:fs/promises";import{homedir as RZ}from"node:os";import*as U from"node:path";import{promisify as xZ}from"node:util";var _0=xZ(kZ),I=R("General"),l0={url:"https://github.com/anthropics/skills.git",branch:"main",defaultSkills:["skill-creator"]};class EQ{skillsDir;constructor(Q){this.skillsDir=Q||U.join(RZ(),".blade","skills")}async isInstalled(Q){let Z=U.join(this.skillsDir,Q,"SKILL.md");try{return await F.access(Z),!0}catch{return!1}}async isGitAvailable(){try{return await _0("git --version"),!0}catch{return!1}}async installOfficialSkill(Q){let{url:Z,branch:$}=l0,J=U.join(this.skillsDir,Q),z=U.join(this.skillsDir,`.tmp-${Q}-${Date.now()}`);try{if(!await this.isGitAvailable())return I.warn("Git not available, skipping skill installation"),!1;I.info(`Installing official skill: ${Q}...`),await F.mkdir(this.skillsDir,{recursive:!0,mode:493}),await _0(`git clone --depth 1 --branch ${$} --single-branch ${Z} "${z}"`,{timeout:30000});let G=U.join(z,"skills",Q);try{await F.access(G)}catch{return I.warn(`Skill ${Q} not found in official repository`),await F.rm(z,{recursive:!0,force:!0}),!1}try{await F.rm(J,{recursive:!0,force:!0})}catch{}return await F.cp(G,J,{recursive:!0}),await F.rm(z,{recursive:!0,force:!0}),I.info(`Successfully installed: ${Q}`),!0}catch(G){try{await F.rm(z,{recursive:!0,force:!0})}catch{}return I.warn(`Failed to install ${Q}: ${G instanceof Error?G.message:"Unknown error"}`),!1}}async ensureDefaultSkillsInstalled(){await F.mkdir(this.skillsDir,{recursive:!0,mode:493});for(let Q of l0.defaultSkills)if(!await this.isInstalled(Q))await this.installOfficialSkill(Q)}async installFromRepo(Q,Z){let $=Z||this.extractRepoName(Q),J=U.join(this.skillsDir,$),z=U.join(this.skillsDir,`.tmp-repo-${$}-${Date.now()}`);try{if(!await this.isGitAvailable())return I.warn("Git not available, cannot install from repo"),!1;I.info(`Installing skill from repo: ${Q}...`),await F.mkdir(this.skillsDir,{recursive:!0,mode:493}),await _0(`git clone --depth 1 "${Q}" "${z}"`,{timeout:60000});let G=U.join(z,"SKILL.md");try{await F.access(G)}catch{return I.warn(`No SKILL.md found in repository ${Q}`),await F.rm(z,{recursive:!0,force:!0}),!1}await F.rm(J,{recursive:!0,force:!0}),await F.rename(z,J);try{await F.rm(U.join(J,".git"),{recursive:!0,force:!0})}catch{}return I.info(`Successfully installed skill from repo: ${$}`),!0}catch(G){try{await F.rm(z,{recursive:!0,force:!0})}catch{}return I.warn(`Failed to install from repo ${Q}: ${G instanceof Error?G.message:"Unknown error"}`),!1}}async installFromLocal(Q,Z,$=!0){let J=Z||U.basename(Q),z=U.join(this.skillsDir,J);try{let G=U.resolve(Q);try{await F.access(G)}catch{return I.warn(`Local path does not exist: ${G}`),!1}let W=U.join(G,"SKILL.md");try{await F.access(W)}catch{return I.warn(`No SKILL.md found in local path: ${G}`),!1}if(I.info(`Installing skill from local path: ${G}...`),await F.mkdir(this.skillsDir,{recursive:!0,mode:493}),await F.rm(z,{recursive:!0,force:!0}),$)await F.symlink(G,z,"dir"),I.info(`Created symlink for skill: ${J}`);else await F.cp(G,z,{recursive:!0}),I.info(`Copied skill to: ${J}`);return!0}catch(G){return I.warn(`Failed to install from local path ${Q}: ${G instanceof Error?G.message:"Unknown error"}`),!1}}extractRepoName(Q){return Q.match(/\/([^/]+?)(\.git)?$/)?.[1]||"unknown-skill"}async installAllOfficialSkills(){let{url:Q,branch:Z}=l0,$=U.join(this.skillsDir,`.tmp-all-${Date.now()}`),J=[],z=[];try{if(!await this.isGitAvailable())return I.warn("Git not available, skipping skill installation"),{installed:J,failed:z};await F.mkdir(this.skillsDir,{recursive:!0,mode:493}),I.info("Cloning official skills repository..."),await _0(`git clone --depth 1 --branch ${Z} --single-branch ${Q} "${$}"`,{timeout:60000});let G=U.join($,"skills"),W=await F.readdir(G,{withFileTypes:!0});for(let V of W){if(!V.isDirectory())continue;let Y=V.name,j=U.join(G,Y),w=U.join(this.skillsDir,Y);try{await F.access(U.join(j,"SKILL.md")),await F.rm(w,{recursive:!0,force:!0}),await F.cp(j,w,{recursive:!0}),I.info(`Installed: ${Y}`),J.push(Y)}catch(L){I.warn(`Failed to install ${Y}`),z.push(Y)}}await F.rm($,{recursive:!0,force:!0})}catch(G){try{await F.rm($,{recursive:!0,force:!0})}catch{}I.warn(`Failed to install skills: ${G instanceof Error?G.message:"Unknown error"}`)}return{installed:J,failed:z}}}var a0=null;function SQ(Q){if(!a0)a0=new EQ(Q);return a0}import*as Y0 from"node:fs/promises";import*as N0 from"node:path";import{parse as TZ}from"yaml";var CZ=/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/,pZ=/^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]?$/,AQ=1024;function dZ(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 PQ(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 mZ(Q,Z){if(!Q.name)return{valid:!1,error:"Missing required field: name"};if(!pZ.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>AQ)return{valid:!1,error:`Description too long: ${Q.description.length} characters (max ${AQ})`};let $;if(Q.model)$=Q.model==="inherit"?"inherit":Q.model;return{valid:!0,metadata:{name:Q.name,description:Q.description.trim(),allowedTools:dZ(Q["allowed-tools"]),version:Q.version,argumentHint:Q["argument-hint"]?.trim(),userInvocable:PQ(Q["user-invocable"]),disableModelInvocation:PQ(Q["disable-model-invocation"]),model:$,whenToUse:Q.when_to_use?.trim()}}}function MQ(Q,Z,$){let J=Q.match(CZ);if(!J)return{success:!1,error:"Invalid SKILL.md format: missing YAML frontmatter (must start with ---)"};let[,z,G]=J,W;try{W=TZ(z)}catch(j){return{success:!1,error:`Failed to parse YAML frontmatter: ${j instanceof Error?j.message:String(j)}`}}let V=mZ(W,Z);if(!V.valid)return{success:!1,error:V.error};let Y=N0.dirname(Z);return{success:!0,content:{metadata:{...V.metadata,path:Z,basePath:Y,source:$},instructions:G.trim()}}}async function fQ(Q,Z){try{let $=await Y0.readFile(Q,"utf-8");return MQ($,Q,Z)}catch($){if($.code==="ENOENT")return{success:!1,error:`File not found: ${Q}`};return{success:!1,error:`Failed to read file: ${$ instanceof Error?$.message:String($)}`}}}async function hQ(Q){try{let Z=await Y0.readFile(Q.path,"utf-8"),$=MQ(Z,Q.path,Q.source);return $.success?$.content:null}catch{return null}}async function kQ(Q){try{return await Y0.access(N0.join(Q,"SKILL.md")),!0}catch{return!1}}var gZ={userSkillsDir:p.join(RQ(),".blade","skills"),projectSkillsDir:".blade/skills",claudeUserSkillsDir:p.join(RQ(),".claude","skills"),claudeProjectSkillsDir:".claude/skills"},I0=null;class r0{skills=new Map;pluginSkills=new Map;config;initialized=!1;constructor(Q){this.config={...gZ,cwd:T(),...Q}}static getInstance(Q){if(!I0)I0=new r0(Q);return I0}static resetInstance(){I0=null}async initialize(){if(this.initialized)return{skills:Array.from(this.skills.values()),errors:[]};let Q=[],Z=[];try{await SQ(this.config.userSkillsDir).ensureDefaultSkillsInstalled()}catch(Y){Q.push({path:"SkillInstaller",error:`Failed to install default skills: ${Y instanceof Error?Y.message:"Unknown error"}`})}this.loadBuiltinSkills();let $=await this.scanDirectory(this.config.claudeUserSkillsDir,"user");Z.push(...$.skills),Q.push(...$.errors);let J=await this.scanDirectory(this.config.userSkillsDir,"user");Z.push(...J.skills),Q.push(...J.errors);let z=p.isAbsolute(this.config.claudeProjectSkillsDir)?this.config.claudeProjectSkillsDir:p.join(this.config.cwd,this.config.claudeProjectSkillsDir),G=await this.scanDirectory(z,"project");Z.push(...G.skills),Q.push(...G.errors);let W=p.isAbsolute(this.config.projectSkillsDir)?this.config.projectSkillsDir:p.join(this.config.cwd,this.config.projectSkillsDir),V=await this.scanDirectory(W,"project");Z.push(...V.skills),Q.push(...V.errors);for(let Y of Z)this.skills.set(Y.name,Y);return this.initialized=!0,{skills:Array.from(this.skills.values()),errors:Q}}loadBuiltinSkills(){this.skills.set(O0.name,O0),this.skills.set(v0.name,v0)}async scanDirectory(Q,Z){let $=[],J=[];try{await U0.access(Q)}catch{return{skills:$,errors:J}}try{let z=await U0.readdir(Q,{withFileTypes:!0});for(let G of z){if(!G.isDirectory())continue;let W=p.join(Q,G.name),V=p.join(W,"SKILL.md");if(!await kQ(W))continue;let Y=await fQ(V,Z);if(Y.success&&Y.content)$.push(Y.content.metadata);else J.push({path:V,error:Y.error||"Unknown error"})}}catch(z){J.push({path:Q,error:`Failed to scan directory: ${z instanceof Error?z.message:String(z)}`})}return{skills:$,errors:J}}getAll(){return Array.from(this.skills.values())}get(Q){return this.skills.get(Q)}has(Q){return this.skills.has(Q)}async loadContent(Q){let Z=this.skills.get(Q);if(!Z)return null;if(Z.source==="builtin")return this.loadBuiltinContent(Q);return hQ(Z)}loadBuiltinContent(Q){switch(Q){case"skill-creator":return UQ();case"update-config":return yQ();default:return null}}getModelInvocableSkills(){return Array.from(this.skills.values()).filter((Q)=>!Q.disableModelInvocation)}getUserInvocableSkills(){return Array.from(this.skills.values()).filter((Q)=>Q.userInvocable===!0)}generateAvailableSkillsList(){let Q=this.getModelInvocableSkills();if(Q.length===0)return"";let Z=[];for(let $ of Q){let J=$.description.length>100?`${$.description.substring(0,97)}...`:$.description,z=$.argumentHint?`${$.name} ${$.argumentHint}`:$.name;Z.push(`- ${z}: ${J}`)}return Z.join(`
|
|
574
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 y0(Q){return r0.getInstance(Q)}async function cZ(Q){return y0(Q).initialize()}var uZ="Skill",iZ=/<available_skills>\s*<\/available_skills>/;function o0(Q){let $=y0().generateAvailableSkillsList();if(!$)return Q;return Q.map((J)=>{if(J.name!==uZ)return J;let z=J.description.replace(iZ,`<available_skills>
|
|
575
575
|
${$}
|
|
576
576
|
</available_skills>`);if(z===J.description)return J;return{...J,description:z}})}var nZ=new Set(["user-cancel","interrupt","sibling-error","timeout"]);function xQ(Q){if(!Q.aborted)return;if(typeof Q.reason==="string"&&nZ.has(Q.reason))return Q.reason;return"user-cancel"}function TQ(){return{consecutiveFailures:new Map,totalFailures:0,lastFailedTool:null}}function CQ(Q,Z){Q.consecutiveFailures.set(Z,0),Q.lastFailedTool=null}function pQ(Q,Z){let $=(Q.consecutiveFailures.get(Z)??0)+1;Q.consecutiveFailures.set(Z,$),Q.totalFailures++,Q.lastFailedTool=Z}function lZ(Q,Z){return(Q.consecutiveFailures.get(Z)??0)>=3}function dQ(Q,Z){if(!lZ(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 mQ(Q){return Q>0&&Q%5===0}function gQ(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(`
|
|
@@ -583,18 +583,18 @@ When facing complex multi-step tasks:
|
|
|
583
583
|
3. If a step fails, diagnose the root cause rather than repeating the same approach.
|
|
584
584
|
4. When uncertain about file paths or project structure, use Grep/Glob/Read to gather facts first.
|
|
585
585
|
5. Prefer the smallest change that achieves the goal — avoid unnecessary refactoring.`;function $2(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 J2(Q){if(typeof Q==="string")return Q;try{return JSON.parse(JSON.stringify(Q))}catch{return String(Q)}}function z2(Q){if(!(Q instanceof Error))return"未知错误";let J=Q.lastError??Q;if(J.responseBody)try{let V=JSON.parse(J.responseBody)?.error?.message;if(V){let Y=J.statusCode?` (HTTP ${J.statusCode})`:"";return`${V}${Y}`}}catch{}let z=Q.message,G=z.match(/Last error:\s*(.+)$/);if(G)return G[1];return z}function G2(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 W2(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 V2(Q){if(!(Q instanceof Error))return!1;let Z=Q.message.toLowerCase();return Z.includes("prompt_too_long")||Z.includes("prompt is too long")||Z.includes("maximum context length")||Z.includes("request too large")||Q.status===413}function Y2(Q,Z){let $=Z,J=$.index??0;if(!Q.has(J))Q.set(J,{id:$.id||"",name:$.function?.name||"",arguments:""});let z=Q.get(J);if($.id&&!z.id)z.id=$.id;if($.function?.name&&!z.name)z.name=$.function.name;if($.function?.arguments)z.arguments+=$.function.arguments}function K2(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*q2(Q,Z,$,J,z){let G="",W="",V,Y,j=new Map;try{let w=Q.chatService.streamChat(Z,$,J),L=0;for await(let H of w){if(L++,J?.aborted)break;if(H.modelFallback){z?.discard(),G="",W="",V=void 0,Y=void 0,j.clear(),L=0,yield{kind:"model_fallback"};continue}if(H.content)G+=H.content,yield{kind:"content_delta",delta:H.content};if(H.reasoningContent)W+=H.reasoningContent,yield{kind:"thinking_delta",delta:H.reasoningContent};if(H.usage)V=H.usage;if(H.toolCalls){for(let O of H.toolCalls)if(Y2(j,O),z){let B=O.index??0,K=j.get(B);if(K&&K.id&&K.name)try{let k=JSON.parse(K.arguments),
|
|
586
|
+
`)}function V2(Q){if(!(Q instanceof Error))return!1;let Z=Q.message.toLowerCase();return Z.includes("prompt_too_long")||Z.includes("prompt is too long")||Z.includes("maximum context length")||Z.includes("request too large")||Q.status===413}function Y2(Q,Z){let $=Z,J=$.index??0;if(!Q.has(J))Q.set(J,{id:$.id||"",name:$.function?.name||"",arguments:""});let z=Q.get(J);if($.id&&!z.id)z.id=$.id;if($.function?.name&&!z.name)z.name=$.function.name;if($.function?.arguments)z.arguments+=$.function.arguments}function K2(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*q2(Q,Z,$,J,z){let G="",W="",V,Y,j=new Map;try{let w=Q.chatService.streamChat(Z,$,J),L=0;for await(let H of w){if(L++,J?.aborted)break;if(H.modelFallback){z?.discard(),G="",W="",V=void 0,Y=void 0,j.clear(),L=0,yield{kind:"model_fallback"};continue}if(H.content)G+=H.content,yield{kind:"content_delta",delta:H.content};if(H.reasoningContent)W+=H.reasoningContent,yield{kind:"thinking_delta",delta:H.reasoningContent};if(H.usage)V=H.usage;if(H.toolCalls){for(let O of H.toolCalls)if(Y2(j,O),z){let B=O.index??0,K=j.get(B);if(K&&K.id&&K.name)try{let k=JSON.parse(K.arguments),C={id:K.id,type:"function",function:{name:K.name,arguments:K.arguments}},f=Q.toolExecutor.getRegistry().get(K.name)?.kind;z.addTool(C,k),yield{kind:"tool_start",toolCall:C,toolKind:f}}catch{}}}if(H.finishReason){Y=H.finishReason;break}}if(L===0&&!J?.aborted&&G.length===0&&j.size===0)return S.warn("[Loop] 流式响应返回0个chunk,回退到非流式模式"),z?.discard(),{...await Q.chatService.chat(Z,$,J),_nonStreamingFallback:!0};return{content:G,reasoningContent:W||void 0,toolCalls:K2(j),usage:V,finishReason:Y}}catch(w){if(G2(w))return S.warn("[Loop] 流式请求失败,降级到非流式模式"),z?.discard(),{...await Q.chatService.chat(Z,$,J),_nonStreamingFallback:!0};throw w}}async function lQ(Q,Z,$,J,z,G){if(J===void 0)return S.debug(`[Loop] [轮次 ${$}] 压缩检查: 跳过(无历史 usage 数据)`),"none";let W=OQ(Z.messages,G);if(W)Z.messages=W.messages,S.debug(`[Loop] [轮次 ${$}] MicroCompact: 清理 ${W.snippedCount} 轮旧工具结果(缓存已过期)`);let V=W0(Z.messages),Y=!1;if(V.snippedCount>0)Y=!0,S.debug(`[Loop] [轮次 ${$}] Snip 压缩: 移除 ${V.snippedCount} 轮旧工具调用,释放约 ${V.estimatedTokensFreed} tokens`);let j=Q.chatService.getConfig(),w=j.model,L=j.maxContextTokens??Q.config.maxContextTokens,H=j.maxOutputTokens??Q.config.maxOutputTokens??Math.min(Math.max(Math.floor(L*tZ),eZ),Q2),O=L-H,y=Math.floor(O*0.8);if(S.debug(`[Loop] [轮次 ${$}] 压缩检查:`,{promptTokens:J,maxContextTokens:L,maxOutputTokens:H,availableForInput:O,threshold:y,shouldCompact:J>=y}),J<y){if(Y)Z.messages=V.messages;return Y?"snipped":"none"}S.debug($===0?"[Loop] 触发自动压缩":`[Loop] [轮次 ${$}] 触发循环内自动压缩`);try{let B=Y?V.messages:Z.messages,K=await s.compact(B,{trigger:"auto",modelName:w,maxContextTokens:L,apiKey:j.apiKey,baseURL:j.baseUrl,actualPreTokens:J,signal:z});if(Z.messages=K.compactedMessages,K.success)S.debug(`[Loop] [轮次 ${$}] 压缩完成: ${K.preTokens} -> ${K.postTokens} tokens`);else S.warn(`[Loop] [轮次 ${$}] 压缩使用降级策略: ${K.preTokens} -> ${K.postTokens} tokens`);return await F0(Q,Z,K.summary,{trigger:"auto",preTokens:K.preTokens,postTokens:K.postTokens,filesIncluded:K.filesIncluded}),"compacted"}catch(B){if(a(B))return S.debug(`[Loop] [轮次 ${$}] 压缩被中止`),"none";if(Y)Z.messages=V.messages;return S.error(`[Loop] [轮次 ${$}] 压缩失败,继续执行`,B),Y?"snipped":"none"}}function o(Q,Z,$,J){let z=J?xQ(J):"user-cancel";return{success:!1,error:{type:"aborted",message:(z==="interrupt"?void 0:"任务已被用户中止")??"任务已中断"},metadata:{turnsCount:Q,toolCallsCount:Z,duration:Date.now()-$,abortReason:z}}}async function*X2(Q,Z,$,J,z){let G=Date.now(),W=0,V=[];try{let Y=Q.toolExecutor.getRegistry(),j=$.permissionMode,w=Y.getFunctionDeclarationsByMode(j);w=o0(w);let L=Q.applySkillToolRestrictions(w),H=TQ(),O=cQ(),y=z;if(typeof Y.getDeferredToolsListing==="function"){let m=Y.getDeferredToolsListing();if(m&&y)y=`${y}
|
|
587
587
|
|
|
588
|
-
${m}`}if(y)y+=Z2;let B=new j0($,y);B.appendUser({role:"user",content:Z});let K=await g(Q,$,Z),k=$.permissionMode==="yolo",
|
|
588
|
+
${m}`}if(y)y+=Z2;let B=new j0($,y);B.appendUser({role:"user",content:Z});let K=await g(Q,$,Z),k=$.permissionMode==="yolo",C=Q.runtimeOptions.maxTurns??J?.maxTurns??Q.config.maxTurns??-1;if(C===0)return{success:!1,error:{type:"chat_disabled",message:"对话功能已被禁用 (maxTurns=0)"},metadata:{turnsCount:0,toolCallsCount:0,duration:0}};let d=C===-1?nQ:Math.min(C,nQ),f=0,e,M,n=0,S0=0,A0=0,P0=0,M0=new Set,x=new Set($.worktreeActive?["EnterWorktree"]:[]),f0=typeof Z==="string"?Z:Z.filter((m)=>m.type==="text").map((m)=>m.text).join(`
|
|
589
589
|
`),s0=C0(f0),aQ=!!$.subagentInfo,h0=$Q({budget:Q.currentModelMaxContextTokens,isSubagent:aQ}),t0=new u0;try{while(!0){if(J?.signal?.aborted)return o(W,V.length,G,J.signal);B.writeback();let m=await lQ(Q,$,W,e,J?.signal,M);if(m!=="none"){if(m==="compacted")yield{kind:"compaction",phase:"start"},yield{kind:"compaction",phase:"end"};B.replaceHistory($.messages)}if(W++,t0.reset(),yield{kind:"turn_start",turn:W,maxTurns:d},J?.signal?.aborted)return o(W-1,V.length,G,J.signal);if(mQ(W)&&W>1){let N=gQ(W,H.totalFailures);B.appendControl("user",{role:"user",content:`
|
|
590
590
|
|
|
591
591
|
<system-reminder>
|
|
592
592
|
${N}
|
|
593
|
-
</system-reminder>`})}let e0=J?.stream!==!1,q,K0;try{if(e0)K0=new E0(Q.
|
|
593
|
+
</system-reminder>`})}let e0=J?.stream!==!1,q,K0;try{if(e0)K0=new E0(Q.toolExecutor,{sessionId:$.sessionId,userId:$.userId||"default",workspaceRoot:$.workspaceRoot||T(),worktreeIsolationRequired:s0,worktreeActive:x.has("EnterWorktree")&&!x.has("ExitWorktree"),signal:J?.signal,confirmationHandler:$.confirmationHandler,permissionMode:$.permissionMode,toolRegistry:Y,deferredToolManager:Y.deferredToolManager},Q.toolExecutor.getRegistry(),Q.executionEngine?.getContextManager(),$.sessionId,K,$.subagentInfo),q=yield*q2(Q,B.toLLMMessages(),L,J?.signal,K0);else q=await Q.chatService.chat(B.toLLMMessages(),L,J?.signal)}catch(N){if(V2(N)){S.warn("[Loop] 检测到 prompt_too_long 错误,尝试反应式压缩");let X=Q.chatService.getConfig(),D=await t0.tryReactiveCompact($.messages,{modelName:X.model,maxContextTokens:X.maxContextTokens??Q.config.maxContextTokens,apiKey:X.apiKey,baseURL:X.baseUrl,signal:J?.signal});if(D.success){$.messages=D.messages,B.replaceHistory($.messages),S.info("[Loop] 反应式压缩成功,重试 LLM 调用"),W--;continue}}throw N}if(M=Date.now(),q.usage){if(q.usage.totalTokens)f+=q.usage.totalTokens;e=q.usage.promptTokens,yield{kind:"token_usage",usage:{inputTokens:q.usage.promptTokens??0,outputTokens:q.usage.completionTokens??0,totalTokens:q.usage.totalTokens??0,maxContextTokens:Q.currentModelMaxContextTokens}}}let rQ=q.usage?.completionTokens??0;if(h0=JQ(h0,rQ,n>0),J?.signal?.aborted)return o(W-1,V.length,G,J.signal);if(!e0||!!q._nonStreamingFallback){if(q.reasoningContent&&q.reasoningContent.trim())yield{kind:"thinking_delta",delta:q.reasoningContent};if(q.content&&q.content.trim())yield{kind:"content_delta",delta:q.content}}yield{kind:"stream_end"};let k0=x0(q.finishReason,n,h0);if(k0.action==="recover"){n++,S.warn(`[Loop] Max output tokens hit (recovery ${n}/3)`);let N={role:"assistant",content:q.content||"",reasoningContent:q.reasoningContent,tool_calls:q.toolCalls};B.appendToHistory(N);let X=await h(Q,$,q.content||"",K);if(X)K=X;let D={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."};B.appendToHistory(D);let b=await g(Q,$,D.content,K);if(b)K=b;continue}if(k0.action==="truncated"||k0.action==="budget_stop"){B.appendAssistant({role:"assistant",content:q.content||"",reasoningContent:q.reasoningContent,tool_calls:q.toolCalls});let N=await h(Q,$,q.content||"",K);if(N)K=N;return{success:!0,finalMessage:q.content,metadata:{turnsCount:W,toolCallsCount:V.length,duration:Date.now()-G,tokensUsed:f,outputTruncated:!0}}}if(q.finishReason!=="length")n=0;if(!q.toolCalls||q.toolCalls.length===0){if(q.content&&uQ(O,q.content)){B.appendAssistant({role:"assistant",content:q.content||"",reasoningContent:q.reasoningContent}),B.appendControl("user",{role:"user",content:`
|
|
594
594
|
|
|
595
595
|
<system-reminder>
|
|
596
596
|
${iQ()}
|
|
597
|
-
</system-reminder>`});continue}let N=T0(q.content,S0,!1);if(N.action==="retry"){S0++,B.appendAssistant({role:"assistant",content:q.content||"",reasoningContent:q.reasoningContent});let v=await h(Q,$,q.content||"",K);if(v)K=v;let _={role:"user",content:N.prompt};B.appendControl("user",_);let P=await g(Q,$,_.content,K);if(P)K=P;continue}S0=0;let X=YQ(f0,
|
|
597
|
+
</system-reminder>`});continue}let N=T0(q.content,S0,!1);if(N.action==="retry"){S0++,B.appendAssistant({role:"assistant",content:q.content||"",reasoningContent:q.reasoningContent});let v=await h(Q,$,q.content||"",K);if(v)K=v;let _={role:"user",content:N.prompt};B.appendControl("user",_);let P=await g(Q,$,_.content,K);if(P)K=P;continue}S0=0;let X=YQ(f0,x,P0);if(X.action==="retry"){P0++,B.appendAssistant({role:"assistant",content:q.content||"",reasoningContent:q.reasoningContent});let v=await h(Q,$,q.content||"",K);if(v)K=v;let _={role:"user",content:X.prompt};B.appendControl("user",_);let P=await g(Q,$,_.content,K);if(P)K=P;continue}if(X.action==="fail"){B.appendAssistant({role:"assistant",content:q.content||"",reasoningContent:q.reasoningContent});let v=await h(Q,$,q.content||"",K);if(v)K=v;return{success:!1,error:{type:"worktree_protocol_failed",message:X.message},metadata:{turnsCount:W,toolCallsCount:V.length,duration:Date.now()-G,tokensUsed:f}}}P0=0;let D=VQ(f0,M0,A0);if(D.action==="retry"){A0++,B.appendAssistant({role:"assistant",content:q.content||"",reasoningContent:q.reasoningContent});let v=await h(Q,$,q.content||"",K);if(v)K=v;let _={role:"user",content:D.prompt};B.appendControl("user",_);let P=await g(Q,$,_.content,K);if(P)K=P;continue}if(D.action==="fail"){B.appendAssistant({role:"assistant",content:q.content||"",reasoningContent:q.reasoningContent});let v=await h(Q,$,q.content||"",K);if(v)K=v;return{success:!1,error:{type:"verification_failed",message:D.message},metadata:{turnsCount:W,toolCallsCount:V.length,duration:Date.now()-G,tokensUsed:f}}}A0=0;let b=await KQ({turnsCount:W,maxTurns:d});if(b.action==="continue"){B.appendAssistant({role:"assistant",content:q.content||"",reasoningContent:q.reasoningContent});let v=await h(Q,$,q.content||"",K);if(v)K=v;let _={role:"user",content:`
|
|
598
598
|
|
|
599
599
|
<system-reminder>
|
|
600
600
|
${b.reason}
|
|
@@ -606,7 +606,7 @@ ${c.reason}
|
|
|
606
606
|
|
|
607
607
|
<system-reminder>
|
|
608
608
|
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.
|
|
609
|
-
</system-reminder>`};B.appendControl("user",P);let X0=await g(Q,$,P.content,K);if(X0)K=X0;continue}B.appendAssistant({role:"assistant",content:q.content||"",reasoningContent:q.reasoningContent});let A=await h(Q,$,q.content||"",K);if(A)K=A;return{success:!0,finalMessage:q.content,metadata:{turnsCount:W,toolCallsCount:V.length,duration:Date.now()-G,tokensUsed:f,toolSuccessRate:V.length>0?V.filter((v)=>v.success).length/V.length:void 0,totalToolFailures:H.totalFailures||void 0}}}B.appendAssistant({role:"assistant",content:q.content||"",reasoningContent:q.reasoningContent,tool_calls:q.toolCalls});{let N=await h(Q,$,q.content||"",K);if(N)K=N}if(J?.signal?.aborted)return o(W,V.length,G,J.signal);let R0=q.toolCalls.filter((N)=>N.type==="function"),q0;if(K0?.hasTools()){S.debug(`[Loop] 使用 StreamingToolExecutor 收集 ${R0.length} 个工具结果`),q0=[];for await(let N of K0.getRemainingResults())q0.push(N)}else{for(let X of R0){let b=Y.get(X.function.name)?.kind;yield{kind:"tool_start",toolCall:X,toolKind:b}}let N=async(X)=>{try{let D;try{D=JSON.parse(X.function.arguments)}catch(A){let v=$2(X.function.arguments);if(v===null)return{toolCall:X,result:{success:!1,llmContent:"",error:{type:"validation_error",message:`Invalid JSON in tool arguments: ${A.message}. Raw: ${X.function.arguments.slice(0,200)}`},metadata:void 0},toolUseUuid:null};D=v}if(X.function.name==="Task"&&(typeof D.subagent_session_id!=="string"||D.subagent_session_id.length===0))D.subagent_session_id=typeof D.resume==="string"&&D.resume.length>0?D.resume:sZ();let b=null;b=await d0(Q,$,X.function.name,D,K);let c=await Q.
|
|
609
|
+
</system-reminder>`};B.appendControl("user",P);let X0=await g(Q,$,P.content,K);if(X0)K=X0;continue}B.appendAssistant({role:"assistant",content:q.content||"",reasoningContent:q.reasoningContent});let A=await h(Q,$,q.content||"",K);if(A)K=A;return{success:!0,finalMessage:q.content,metadata:{turnsCount:W,toolCallsCount:V.length,duration:Date.now()-G,tokensUsed:f,toolSuccessRate:V.length>0?V.filter((v)=>v.success).length/V.length:void 0,totalToolFailures:H.totalFailures||void 0}}}B.appendAssistant({role:"assistant",content:q.content||"",reasoningContent:q.reasoningContent,tool_calls:q.toolCalls});{let N=await h(Q,$,q.content||"",K);if(N)K=N}if(J?.signal?.aborted)return o(W,V.length,G,J.signal);let R0=q.toolCalls.filter((N)=>N.type==="function"),q0;if(K0?.hasTools()){S.debug(`[Loop] 使用 StreamingToolExecutor 收集 ${R0.length} 个工具结果`),q0=[];for await(let N of K0.getRemainingResults())q0.push(N)}else{for(let X of R0){let b=Y.get(X.function.name)?.kind;yield{kind:"tool_start",toolCall:X,toolKind:b}}let N=async(X)=>{try{let D;try{D=JSON.parse(X.function.arguments)}catch(A){let v=$2(X.function.arguments);if(v===null)return{toolCall:X,result:{success:!1,llmContent:"",error:{type:"validation_error",message:`Invalid JSON in tool arguments: ${A.message}. Raw: ${X.function.arguments.slice(0,200)}`},metadata:void 0},toolUseUuid:null};D=v}if(X.function.name==="Task"&&(typeof D.subagent_session_id!=="string"||D.subagent_session_id.length===0))D.subagent_session_id=typeof D.resume==="string"&&D.resume.length>0?D.resume:sZ();let b=null;b=await d0(Q,$,X.function.name,D,K);let c=await Q.toolExecutor.execute(X.function.name,D,{sessionId:$.sessionId,userId:$.userId||"default",workspaceRoot:$.workspaceRoot||T(),worktreeIsolationRequired:s0,worktreeActive:x.has("EnterWorktree")&&!x.has("ExitWorktree"),signal:J?.signal,confirmationHandler:$.confirmationHandler,permissionMode:$.permissionMode,toolRegistry:Y,deferredToolManager:Y.deferredToolManager});return{toolCall:X,result:c,toolUseUuid:b}}catch(D){return S.error(`Tool execution failed for ${X.function.name}:`,D),{toolCall:X,result:{success:!1,llmContent:"",error:{type:"execution_error",message:D instanceof Error?D.message:"Unknown error"},metadata:void 0},toolUseUuid:null,error:D instanceof Error?D:Error("Unknown error")}}};q0=await Promise.all(R0.map(N))}let oQ=new n0;for(let{toolCall:N,result:X,toolUseUuid:D}of q0){let b=N;if(V.push(X),X.metadata?.abortedBeforeLaunch)return o(W,V.length,G,J?.signal);yield{kind:"tool_result",toolCall:b,result:X};{let _=X.metadata&&typeof X.metadata==="object"?X.metadata:void 0,X0=((H0)=>H0==="running"||H0==="completed"||H0==="failed"||H0==="cancelled")(_?.subagentStatus)?_.subagentStatus:"completed",sQ=_&&typeof _.subagentSessionId==="string"?{subagentSessionId:_.subagentSessionId,subagentType:typeof _.subagentType==="string"?_.subagentType:b.function.name,subagentStatus:X0,subagentSummary:typeof _.subagentSummary==="string"?_.subagentSummary:void 0}:void 0,QQ=await m0(Q,$,b.id,b.function.name,X.success?J2(X.llmContent):null,D,X.success?void 0:X.error?.message,sQ);if(QQ)K=QQ}let c=await g0(b,X,Q,$);if(c)yield c;if(X.success){if(CQ(H,b.function.name),b.function.name==="EnterWorktree"&&X.metadata?.workspaceTransition==="enter")x.add("EnterWorktree"),x.delete("ExitWorktree");else if(b.function.name==="ExitWorktree"&&X.metadata?.workspaceTransition==="exit"&&x.has("EnterWorktree"))x.add("ExitWorktree");else if(!["EnterWorktree","ExitWorktree"].includes(b.function.name))x.add(b.function.name);if(b.function.name==="Task"&&X.metadata?.isolation==="worktree")x.add("TaskWorktree");if(["Edit","Write","NotebookEdit"].includes(b.function.name))M0.delete("Bash");else if(b.function.name==="Bash"&&typeof X.metadata?.command==="string"&&X.metadata.exit_code===0&&WQ(X.metadata.command))M0.add("Bash")}else pQ(H,b.function.name);let A=X.success?X.llmContent||"":W2(b.function.name,X.error);if(!X.success){let _=dQ(H,b.function.name);if(_&&typeof A==="string")A=`${A}
|
|
610
610
|
|
|
611
611
|
${_}`}if(typeof A==="object"&&A!==null)A=JSON.stringify(A,null,2);if(typeof A==="string")A=IQ(A,b.function.name,{messageBudget:oQ});let v=typeof A==="string"?A:JSON.stringify(A);if(B.appendToolResult({role:"tool",tool_call_id:b.id,name:b.function.name,content:v}),X.metadata?.shouldExitLoop){let _=typeof X.llmContent==="string"?X.llmContent:"循环已退出";return{success:X.success,finalMessage:_,metadata:{turnsCount:W,toolCallsCount:V.length,duration:Date.now()-G,shouldExitLoop:!0,targetMode:X.metadata?.targetMode,planContent:typeof X.metadata?.planContent==="string"?X.metadata.planContent:void 0}}}}if(J?.signal?.aborted)return o(W,V.length,G,J.signal);if(W>=d&&!k){if(S.info(`Warning: 达到轮次上限 ${d} 轮`),J?.onTurnLimitReached){let N=await J.onTurnLimitReached({turnsCount:W});if(N?.continue){B.writeback();try{let X=Q.chatService.getConfig(),D=await s.compact($.messages,{trigger:"auto",modelName:X.model,maxContextTokens:X.maxContextTokens??Q.config.maxContextTokens,apiKey:X.apiKey,baseURL:X.baseUrl,actualPreTokens:e,signal:J?.signal});$.messages=D.compactedMessages,B.replaceHistory($.messages);let b={role:"user",content:`This session is being continued from a previous conversation. The conversation is summarized above.
|
|
612
612
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import"./chunk-
|
|
1
|
+
import"./chunk-j7nh0j36.js";var d={command:"install [target]",describe:"Install Blade native build. Use [target] to specify version (stable, latest, or specific version)",builder:(b)=>{return b.positional("target",{describe:"Version to install",type:"string",default:"stable",choices:["stable","latest"]}).option("force",{type:"boolean",describe:"Force reinstall",default:!1}).example([["$0 install","Install stable version"],["$0 install latest","Install latest version"],["$0 install --force","Force reinstall stable version"]])},handler:async(b)=>{console.log(`Installing Blade ${b.target}...`);try{if(b.force)console.log("Force reinstall enabled");console.log("Downloading..."),console.log("Installing..."),console.log("Installation completed successfully")}catch(c){console.error(`Error: Installation failed: ${c instanceof Error?c.message:"未知错误"}`),process.exit(1)}}};export{d as installCommands};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var e={name:"blade-code",version:"0.6.
|
|
1
|
+
var e={name:"blade-code",version:"0.6.4",private:!1,description:"🗡️ Blade Code - 智能代码助手命令行工具",type:"module",bin:{blade:"dist/blade.js"},files:["dist","vendor/ripgrep/**","README.md"],scripts:{dev:"node scripts/run-bun.js --watch src/blade.tsx","dev:serve":"node scripts/run-bun.js --watch src/blade.tsx serve --port 4097",build:"rm -rf dist && node scripts/run-bun.js run scripts/build.ts",start:"node scripts/run-bun.js run dist/blade.js",test:"node scripts/test.js","test:all":"vitest run --config vitest.config.ts","test:unit":"node scripts/test.js unit","test:integration":"node scripts/test.js integration","test:real-api":"node scripts/test.js realApi","test:cli":"node scripts/test.js cli","test:headless-core":"node scripts/test.js headlessCore","test:e2e":"node scripts/test.js e2e","test:performance":"node scripts/test.js performance","test:snapshot":"node scripts/test.js snapshot","test:security":"node scripts/test.js security","test:coverage":"node scripts/test.js all --coverage","test:watch":"vitest --watch --config vitest.config.ts","benchmark:repo":"node scripts/run-bun.js run scripts/run-real-repo-benchmark.ts","test:update-snapshots":"node scripts/test.js snapshot --update",lint:"biome lint src tests","lint:fix":"biome lint --write src tests","type-check":"tsc --noEmit","format:check":"biome format src tests",ready:"node scripts/run-bun.js run scripts/ready.ts","detect-unused":"node scripts/run-bun.js run scripts/detect-unused.ts",release:"node scripts/release.js","release:dry":"node scripts/release.js --dry-run","release:major":"node scripts/release.js --major","release:minor":"node scripts/release.js --minor","release:patch":"node scripts/release.js --patch"},keywords:["cli","blade","ai","assistant","agent","llm"],author:"echoVic",license:"MIT",engines:{node:">=20.0.0"},optionalDependencies:{"@vscode/ripgrep":"^1.17.0","bun-pty":"^0.4.8","node-pty":"1.0.0"},dependencies:{"@agentclientprotocol/sdk":"^0.12.0","@ai-sdk/anthropic":"^3.0.7","@ai-sdk/azure":"^3.0.5","@ai-sdk/deepseek":"^2.0.4","@ai-sdk/google":"^3.0.4","@ai-sdk/openai":"^3.0.26","@ai-sdk/openai-compatible":"^2.0.4","@anthropic-ai/sandbox-runtime":"0.0.67","@inkjs/ui":"^2.0.0","@modelcontextprotocol/sdk":"^1.17.4",ahooks:"^3.9.6",ai:"^6.0.39","ansi-escapes":"^7.2.0","async-mutex":"^0.5.0",axios:"^1.12.2",chalk:"^5.4.1",diff:"^8.0.2","fast-glob":"^3.3.3","fuse.js":"^7.1.0","gray-matter":"^4.0.3",hono:"^4.7.10",ink:"npm:@jrichman/ink@6.4.10","ink-big-text":"^2.0.0","ink-gradient":"^3.0.0","ink-select-input":"^6.2.0","ink-spinner":"^5.0.0","ink-text-input":"^6.0.0","js-tiktoken":"^1.0.21","lodash-es":"^4.17.21",lowlight:"^3.3.0","lru-cache":"^11.2.4",nanoid:"^5.1.6",open:"^10.1.2",openai:"^6.2.0",picomatch:"^4.0.3",react:"^19.1.1","react-dom":"^19.1.1",semver:"^7.7.3","string-width":"^8.1.0",undici:"^7.16.0","write-file-atomic":"^7.0.0",ws:"^8.18.0",yaml:"^2.8.1",yargs:"^18.0.0",zod:"^3.24.2","zod-to-json-schema":"^3.24.6",zustand:"^5.0.9"},devDependencies:{"@biomejs/biome":"^2.2.4","@types/bun":"^1.3.4","@types/json-schema":"^7.0.15","@types/lodash-es":"^4.17.12","@types/node":"^22.15.24","@types/picomatch":"^4.0.2","@types/react":"^19.1.1","@types/react-dom":"^19.1.1","@types/semver":"^7.7.1","@types/write-file-atomic":"^4.0.3","@types/ws":"^8.5.12","@types/yargs":"^17.0.33","@vitest/coverage-v8":"^3.0.0",jsdom:"^26.0.0",typescript:"^5.9.2",vitest:"^3.0.0"}};function r(){return{name:e.name,version:e.version,description:e.description}}function n(){return e.version}function o(){return e.name}function c(){return e.description}function d(){return`v${e.version}`}function a(){return`v${e.version} © 2025 Blade Code`}
|
|
2
2
|
export{r as aa,n as ba,o as ca,c as da,d as ea,a as fa};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{e as zf,f as Tf}from"./chunk-
|
|
1
|
+
import{e as zf,f as Tf}from"./chunk-cfe1fywb.js";import{B as s,C as Mf,G as Ff,H as g,J as Uf,K as qf,M as Bf,P as h,W as Lf,z as wf}from"./chunk-7t23swne.js";import{Y as T}from"./chunk-59e6eg4b.js";import{ba as u}from"./chunk-p8pggabj.js";import{Ba as xf,Ca as Rf,Ga as z,za as S}from"./chunk-h46kk20y.js";import{Ma as _f,Oa as t,Ta as Ef}from"./chunk-njq4w631.js";import{xb as R}from"./chunk-7ycmx7c2.js";import{Hb as x}from"./chunk-bpx8x87m.js";import{Jb as jf}from"./chunk-j7nh0j36.js";var I0={port:{type:"number",describe:"Port to listen on (0 for auto)",default:0},hostname:{type:"string",describe:"Hostname to listen on",default:"127.0.0.1"},cors:{type:"array",describe:"Additional domains to allow for CORS",default:[]}};function v0(V){return{port:V.port??0,hostname:V.hostname??"127.0.0.1",cors:V.cors??[]}}import{Hono as T0}from"hono";import{cors as y0}from"hono/cors";import{existsSync as gf,readFileSync as e}from"node:fs";import{createServer as _0}from"node:http";import{networkInterfaces as D0}from"node:os";import{dirname as b0,extname as w0,join as w}from"node:path";import{fileURLToPath as L0}from"node:url";import{WebSocketServer as P0}from"ws";import{z as c}from"zod";class p extends Error{code;statusCode;constructor(V,$,f=500){super($);this.code=V;this.statusCode=f;this.name="BladeServerError"}toObject(){return{error:{code:this.code,message:this.message}}}}class P extends p{constructor(V,$){super("NOT_FOUND",$?`${V} not found: ${$}`:`${V} not found`,404)}}class A extends p{constructor(V){super("BAD_REQUEST",V,400)}}var g0=c.object({error:c.object({code:c.string(),message:c.string()})});import{Hono as cf}from"hono";import{z as k}from"zod";var $f=x("Service"),af=k.object({updates:k.record(k.any()),options:k.object({scope:k.enum(["local","project","global"]).optional(),immediate:k.boolean().optional()}).optional()}),Gf=()=>{let V=new cf;return V.get("/",async($)=>{try{let f=S();return $.json(f||{})}catch(f){return $f.error("[ConfigRoutes] Failed to get config:",f),$.json({})}}),V.put("/",async($)=>{try{let f=await $.req.json(),O=af.safeParse(f);if(!O.success)throw new A("Invalid config update format");let{updates:M,options:J}=O.data;return await z().updateConfig(M,J),$.json({success:!0,updates:M})}catch(f){throw $f.error("[ConfigRoutes] Failed to update config:",f),f}}),V.get("/permissions",async($)=>{try{let f=S();return $.json(f?.permissions||{})}catch(f){return $f.error("[ConfigRoutes] Failed to get permissions:",f),$.json({})}}),V};import{Hono as tf}from"hono";var Nf=()=>{let V=new tf;return V.get("/health",($)=>{return $.json({healthy:!0,version:u()})}),V.get("/info",($)=>{return $.json({version:u(),platform:process.platform,arch:process.arch,nodeVersion:process.version,cwd:R()})}),V};import{Hono as nf}from"hono";var o=x("Service"),mf=()=>{let V=new nf;return V.get("/",async($)=>{try{let O=T.getInstance().getAllServers(),M=Array.from(O.entries()).map(([J,j])=>({id:J,name:J,status:j.status==="connected"?"connected":j.status==="connecting"?"connecting":j.lastError?"error":"offline",endpoint:j.config.command?`${j.config.command} ${(j.config.args||[]).join(" ")}`.trim():j.config.url||"Unknown",description:`MCP server: ${J}`,tools:j.tools.map((Y)=>Y.name),connectedAt:j.connectedAt?.toISOString(),error:j.lastError?.message}));return $.json(M)}catch(f){return o.error("[McpRoutes] Failed to get MCP servers:",f),$.json([])}}),V.post("/:name/connect",async($)=>{try{let f=$.req.param("name");return await T.getInstance().connectServer(f),$.json({success:!0})}catch(f){return o.error("[McpRoutes] Failed to connect MCP server:",f),$.json({success:!1,error:f.message},500)}}),V.post("/:name/disconnect",async($)=>{try{let f=$.req.param("name");return await T.getInstance().disconnectServer(f),$.json({success:!0})}catch(f){return o.error("[McpRoutes] Failed to disconnect MCP server:",f),$.json({success:!1,error:f.message},500)}}),V.delete("/:name",async($)=>{try{let f=$.req.param("name");await T.getInstance().unregisterServer(f);let M=S();if(M?.mcpServers){let{[f]:J,...j}=M.mcpServers;await z().updateConfig({mcpServers:j})}return $.json({success:!0})}catch(f){return o.error("[McpRoutes] Failed to delete MCP server:",f),$.json({success:!1,error:f.message},500)}}),V.post("/",async($)=>{try{let f=await $.req.json(),{name:O,config:M}=f;if(!O||!M)return $.json({success:!1,error:"Missing name or config"},400);await T.getInstance().registerServer(O,M);let j=S();return await z().updateConfig({mcpServers:{...j?.mcpServers,[O]:M}}),$.json({success:!0})}catch(f){return o.error("[McpRoutes] Failed to add MCP server:",f),$.json({success:!1,error:f.message},500)}}),V};import{Hono as sf}from"hono";var a=x("Service"),Xf=()=>{let V=new sf;return V.get("/",async($)=>{try{let f=xf(),O=Rf();return $.json({configured:f,current:O})}catch(f){return a.error("[ModelsRoutes] Failed to get models:",f),$.json({configured:[],current:null})}}),V.post("/",async($)=>{try{let f=await $.req.json(),{provider:O,name:M,model:J,baseUrl:j,apiKey:Y}=f;if(!J)throw new A("model is required");let K=await z().addModel({provider:O||"openai-compatible",name:M||J,model:J,baseUrl:j||void 0,apiKey:Y||void 0});return $.json({success:!0,model:K})}catch(f){throw a.error("[ModelsRoutes] Failed to add model:",f),f}}),V.put("/:modelId",async($)=>{try{let f=$.req.param("modelId"),O=await $.req.json(),{baseUrl:M,apiKey:J,model:j}=O;return await z().updateModel(f,{baseUrl:M||void 0,apiKey:J||void 0,model:j||void 0}),$.json({success:!0})}catch(f){throw a.error("[ModelsRoutes] Failed to update model:",f),f}}),V.delete("/:modelId",async($)=>{try{let f=$.req.param("modelId");return await z().removeModel(f),$.json({success:!0})}catch(f){throw a.error("[ModelsRoutes] Failed to delete model:",f),f}}),V};import{Hono as Z0}from"hono";import{z as C}from"zod";import{Hono as ef}from"hono";import{streamSSE as f0}from"hono/streaming";import{LRUCache as $0}from"lru-cache";import{nanoid as d}from"nanoid";import{z as U}from"zod";var X=x("Service"),V0=U.object({title:U.string().optional(),projectPath:U.string().optional()}),O0=U.object({content:U.string(),attachments:U.array(U.object({type:U.enum(["file","image","url"]),path:U.string().optional(),url:U.string().optional(),content:U.string().optional(),mimeType:U.string().optional(),name:U.string().optional()})).optional(),permissionMode:U.enum(["default","autoEdit","plan","spec","yolo"]).optional()}),M0=U.object({title:U.string().optional()}),B=new Map,D=new $0({max:100,ttl:1800000,dispose:(V,$)=>{if(V.status==="running"||V.status==="waiting_permission")V.abortController.abort(),X.debug(`[SessionRoutes] Run ${$} disposed due to cache eviction`)}}),j0=(V)=>{if(!V||typeof V!=="object")return V;let $={...V},f=200000;if(typeof $.oldContent==="string"&&$.oldContent.length>f)delete $.oldContent;if(typeof $.newContent==="string"&&$.newContent.length>f)delete $.newContent;return $};function J0(V){if(typeof V==="string")return V;return V.filter(($)=>$.type==="text").map(($)=>$.text).join(`
|
|
2
2
|
`)}function Q0(V,$){let f=($??[]).filter((M)=>M.type==="image"&&typeof M.content==="string").map((M)=>({type:"image_url",image_url:{url:M.content}}));if(f.length===0)return V;let O=[];if(V.trim())O.push({type:"text",text:V});return O.push(...f),O}var Wf=()=>{let V=new ef,$=new Map;return V.get("/",async(f)=>{try{let O=await h.listSessions(),M=new Set(O.filter((G)=>G.relationType==="subagent").map((G)=>G.sessionId)),J=Array.from(B.values()).filter((G)=>!M.has(G.id)&&G.relationType!=="subagent").map((G)=>({sessionId:G.id,projectPath:G.projectPath,title:G.title,parentId:void 0,relationType:void 0,status:void 0,agentType:void 0,model:void 0,messageCount:G.messages.length,firstMessageTime:G.createdAt.toISOString(),lastMessageTime:new Date().toISOString(),hasErrors:!1,isActive:!0})),j=new Set(J.map((G)=>G.sessionId)),Y=O.filter((G)=>!B.has(G.sessionId)&&!j.has(G.sessionId)&&G.relationType!=="subagent"),K=new Set(j),Q=Y.filter((G)=>{if(K.has(G.sessionId))return!1;return K.add(G.sessionId),!0}),Z=[...J,...Q];return f.json(Z)}catch(O){return X.error("[SessionRoutes] Failed to list sessions:",O),f.json([])}}),V.post("/",async(f)=>{try{let O=await f.req.json(),M=V0.safeParse(O);if(!M.success)throw new A("Invalid request body");let{title:J,projectPath:j}=M.data,Y=d(12),K=j||f.get("directory")||R(),Q={id:Y,projectPath:K,title:J||`Session ${Y.slice(0,6)}`,createdAt:new Date,messages:[]};return B.set(Y,Q),f.json({sessionId:Y,projectPath:K,title:Q.title,parentId:void 0,relationType:void 0,status:void 0,agentType:void 0,model:void 0,messageCount:0,firstMessageTime:Q.createdAt.toISOString(),lastMessageTime:Q.createdAt.toISOString(),hasErrors:!1})}catch(O){throw X.error("[SessionRoutes] Failed to create session:",O),O}}),V.get("/:sessionId",async(f)=>{let O=f.req.param("sessionId"),M=B.get(O);if(M)return f.json({sessionId:M.id,projectPath:M.projectPath,title:M.title,messageCount:M.messages.length,firstMessageTime:M.createdAt.toISOString(),lastMessageTime:new Date().toISOString(),hasErrors:!1,isActive:!0});try{let j=(await h.listSessions()).find((Y)=>Y.sessionId===O);if(!j)throw new P("Session",O);return f.json(j)}catch(J){if(J instanceof P)throw J;throw X.error("[SessionRoutes] Failed to get session:",J),J}}),V.patch("/:sessionId",async(f)=>{let O=f.req.param("sessionId");try{let M=await f.req.json(),J=M0.safeParse(M);if(!J.success)throw new A("Invalid request body");let{title:j}=J.data,Y=B.get(O);if(Y&&j)Y.title=j;return f.json({success:!0,title:j})}catch(M){throw X.error("[SessionRoutes] Failed to update session:",M),M}}),V.delete("/:sessionId",async(f)=>{let O=f.req.param("sessionId"),M=B.get(O);if(M?.currentRunId){let j=D.get(M.currentRunId);if(j)j.abortController.abort(),g.publish(O,"run.cancelled",{runId:j.id}),D.delete(M.currentRunId)}try{await h.deleteSession(O)}catch(j){X.warn("[SessionRoutes] Failed to delete session file:",j)}B.delete(O);let J=$.get(O);if(J){if(await J.dispose(),$.delete(O),$.size===0)await T.getInstance().disconnectAll()}return f.json({success:!0})}),V.get("/:sessionId/message",async(f)=>{let O=f.req.param("sessionId");try{let M=await h.loadSession(O);return f.json(M)}catch(M){return X.error("[SessionRoutes] Failed to get messages:",M),f.json([])}}),V.get("/:sessionId/events",async(f)=>{let O=f.req.param("sessionId"),M=B.get(O);if(!M){let J=f.get("directory")||R();M={id:O,projectPath:J,title:`Session ${O.slice(0,6)}`,createdAt:new Date,messages:[]},B.set(O,M)}return f0(f,async(J)=>{await J.writeSSE({data:JSON.stringify({type:"connected",properties:{sessionId:O,timestamp:Date.now()}})});let Y=g.subscribe((Q)=>{if(Q.sessionId!==O)return;J.writeSSE({data:JSON.stringify({type:Q.type,properties:{sessionId:Q.sessionId,...Q.properties}})}).catch(()=>{})}),K=setInterval(()=>{if(!J.aborted)J.writeSSE({data:JSON.stringify({type:"heartbeat",properties:{timestamp:Date.now()}})}).catch(()=>{})},15000);J.onAbort(()=>{clearInterval(K),Y()});while(!0)if(await new Promise((Q)=>setTimeout(Q,1000)),J.aborted)break})}),V.post("/:sessionId/message",async(f)=>{let O=f.req.param("sessionId"),M=await f.req.json(),J=O0.safeParse(M);if(!J.success)throw new A("Invalid message format");let{content:j,attachments:Y,permissionMode:K}=J.data,Q=K||"default",Z=f.get("directory")||R(),G=Q0(j,Y),m=B.get(O);if(!m){let N=await h.loadSession(O).catch(()=>[]);m={id:O,projectPath:Z,title:`Session ${O.slice(0,6)}`,createdAt:new Date,messages:N},B.set(O,m)}let q=d(12),L=new AbortController,E={id:q,sessionId:O,status:"running",abortController:L,createdAt:new Date};return D.set(q,E),m.currentRunId=q,Y0(E,m,G,Q,$).catch((N)=>{X.error(`[SessionRoutes] Run ${q} failed:`,N)}),f.json({runId:q,status:"running"},202)}),V.post("/:sessionId/abort",async(f)=>{let O=f.req.param("sessionId"),M=B.get(O);if(M?.currentRunId){let J=D.get(M.currentRunId);if(J)J.abortController.abort(),J.status="cancelled",g.publish(O,"run.cancelled",{runId:J.id})}return f.json({success:!0})}),V.get("/:sessionId/status",async(f)=>{let O=f.req.param("sessionId"),M=B.get(O);if(!M?.currentRunId)return f.json({sessionId:O,status:"idle"});let J=D.get(M.currentRunId);return f.json({sessionId:O,runId:M.currentRunId,status:J?.status||"idle"})}),V};async function Y0(V,$,f,O,M){let{abortController:J,sessionId:j,id:Y}=V,K=d(12),Q=d(12),Z=(G,m)=>{g.publish(j,G,m)};try{Z("message.created",{messageId:K,role:"user",content:J0(f)}),Z("session.status",{status:"running"}),Z("message.created",{messageId:Q,role:"assistant",content:""});let G=M.get(j);if(!G)G=await Ff.create({sessionId:j}),M.set(j,G);let m=await Bf.createWithRuntime(G,{sessionId:j}),q=async(N)=>{let F=d(12),l=300000;V.status="waiting_permission";let ff=new Promise((Kf)=>{let rf=setTimeout(()=>{X.warn(`[SessionRoutes] Permission ${F} timed out after 300000ms`),Z("permission.timeout",{requestId:F}),Kf({approved:!1,reason:"timeout"})},300000);V.pendingPermission={permissionId:F,resolve:(lf)=>{clearTimeout(rf),Kf(lf)},details:N}});Z("permission.asked",{requestId:F,toolName:N.toolName,description:N.message,args:N.args,details:N}),X.info(`[SessionRoutes] Permission request created: ${F}, runId: ${Y}`);let Zf=await ff;return X.info(`[SessionRoutes] Permission response received: ${F}, approved: ${Zf.approved}`),V.status="running",V.pendingPermission=void 0,Zf},L={messages:[...$.messages],userId:"web-user",sessionId:j,workspaceRoot:$.projectPath,signal:J.signal,permissionMode:O,confirmationHandler:{requestConfirmation:q}},E=await Ef(m.chatStream(f,L,{stream:!0}),async(N)=>{switch(N.kind){case"content_delta":Z("message.delta",{messageId:Q,delta:N.delta});break;case"thinking_delta":Z("thinking.delta",{delta:N.delta});break;case"tool_start":if("function"in N.toolCall)Z("tool.start",{messageId:Q,toolName:N.toolCall.function.name,toolCallId:N.toolCall.id,arguments:N.toolCall.function.arguments,toolKind:N.toolKind});break;case"tool_result":if("function"in N.toolCall)Z("tool.result",{messageId:Q,toolName:N.toolCall.function.name,toolCallId:N.toolCall.id,success:!N.result.error,summary:N.result.metadata?.summary,output:qf(Uf(N.toolCall.function.name,N.result)),metadata:j0(N.result.metadata)});break;case"token_usage":Z("token.usage",{...N.usage});break;case"task_update":Z("task.updated",{tasks:N.tasks});break;default:break}});$.messages=[...L.messages],Z("message.complete",{messageId:Q}),Z("thinking.completed",{}),V.status="completed",Z("session.completed",{runId:Y,outputTruncated:E.metadata?.outputTruncated??!1}),Z("session.status",{status:"idle"})}catch(G){X.error("[SessionRoutes] Agent execution error:",G),V.status="failed",Z("session.error",{error:G instanceof Error?G.message:"Unknown error"}),Z("session.status",{status:"error"})}}function Af(V,$,f){X.info(`[SessionRoutes] Looking for permission ${$} in session ${V}`),X.info(`[SessionRoutes] Active runs: ${D.size}`);for(let[O,M]of D.entries())if(X.info(`[SessionRoutes] Checking run ${O}: sessionId=${M.sessionId}, pendingPermission=${M.pendingPermission?.permissionId}`),M.sessionId===V&&M.pendingPermission?.permissionId===$)return M.pendingPermission.resolve(f),X.info(`[SessionRoutes] Permission ${$} responded, runId: ${M.id}`),!0;return X.error(`[SessionRoutes] Permission not found: ${$}`),!1}var Vf=x("Service"),K0=C.object({approved:C.boolean(),remember:C.boolean().optional(),scope:C.enum(["once","session"]).optional(),targetMode:C.enum(["default","autoEdit","plan","spec","yolo"]).optional(),feedback:C.string().optional(),answers:C.record(C.union([C.string(),C.array(C.string())])).optional()}),Cf=()=>{let V=new Z0;return V.post("/:permissionId",async($)=>{let f=$.req.param("permissionId"),O=$.req.query("sessionId");Vf.info(`[PermissionRoutes] Received permission response: permissionId=${f}, sessionId=${O}`);try{let M=await $.req.json(),J=K0.safeParse(M);if(!J.success)throw new A("Invalid permission response format");let{approved:j,remember:Y,scope:K,targetMode:Q,feedback:Z,answers:G}=J.data;if(!O)throw new A("sessionId query parameter is required");if(!Af(O,f,{approved:j,reason:Z,scope:K,targetMode:Q,feedback:Z,answers:G}))throw new P("Permission request",f);return Vf.info(`[PermissionRoutes] Permission ${f} ${j?"approved":"denied"}`),$.json({success:!0,approved:j,remember:Y})}catch(M){throw Vf.error("[PermissionRoutes] Failed to respond to permission:",M),M}}),V};import{Hono as G0}from"hono";var Hf=x("Service"),yf=()=>{let V=new G0;return V.get("/",async($)=>{try{let f=await zf();return $.json(f)}catch(f){return Hf.error("[ProviderRoutes] Failed to list providers:",f),$.json([])}}),V.get("/:provider/models",async($)=>{let f=$.req.param("provider");try{let O=await Tf(f);return $.json(O)}catch(O){return Hf.error("[ProviderRoutes] Failed to list models:",O),$.json([])}}),V};import{Hono as N0}from"hono";import*as y from"node:fs/promises";import{homedir as m0}from"node:os";import*as n from"node:path";var b=x("Service"),Of=n.join(m0(),".blade","skills-config.json");async function Df(){try{let V=await y.readFile(Of,"utf-8");return JSON.parse(V)}catch{return{disabled:[]}}}async function x0(V){await y.mkdir(n.dirname(Of),{recursive:!0}),await y.writeFile(Of,JSON.stringify(V,null,2))}async function R0(V,$){let f=await Df();if($)f.disabled=f.disabled.filter((O)=>O!==V);else if(!f.disabled.includes(V))f.disabled.push(V);await x0(f)}var I=null,X0=300000;async function E0(){if(I&&Date.now()-I.timestamp<X0)return I.data;try{let V=await fetch("https://api.github.com/repos/anthropics/skills/contents/skills",{headers:{Accept:"application/vnd.github.v3+json","User-Agent":"Blade-Skills-Catalog"}});if(!V.ok)return b.warn(`GitHub API returned ${V.status}`),I?.data||[];let $=await V.json(),f=[];for(let O of $){if(O.type!=="dir")continue;let M=`Official ${O.name} skill`;try{let J=await fetch(`https://raw.githubusercontent.com/anthropics/skills/main/skills/${O.name}/SKILL.md`,{headers:{"User-Agent":"Blade-Skills-Catalog"}});if(J.ok){let Y=(await J.text()).match(/^#[^\n]*\n+([^\n#]+)/);if(Y)M=Y[1].trim().slice(0,100)}}catch{}f.push({name:O.name,description:M,tag:"Official",author:"Anthropic"})}return I={data:f,timestamp:Date.now()},f}catch(V){return b.warn("Failed to fetch skills catalog from GitHub:",V),I?.data||[]}}var bf=()=>{let V=new N0;return V.get("/",async($)=>{try{let f=t();await f.initialize();let O=f.getAll(),M=await Df(),J=O.map((j)=>({id:j.name,name:j.name,enabled:!M.disabled.includes(j.name),description:j.description||"",version:j.version||"1.0.0",provider:"Local",location:j.source==="builtin"?"Built-in":j.basePath,capabilities:["prompts"],allowedTools:j.allowedTools||[]}));return $.json(J)}catch(f){return b.error("[SkillsRoutes] Failed to get skills:",f),$.json([])}}),V.post("/:name/toggle",async($)=>{try{let f=$.req.param("name"),O=await $.req.json();return await R0(f,O.enabled),$.json({success:!0,enabled:O.enabled})}catch(f){return b.error("[SkillsRoutes] Failed to toggle skill:",f),$.json({success:!1,error:f.message},500)}}),V.delete("/:name",async($)=>{try{let f=$.req.param("name"),O=`${process.env.HOME}/.blade/skills/${f}`;return await y.rm(O,{recursive:!0,force:!0}),await t().refresh(),$.json({success:!0})}catch(f){return b.error("[SkillsRoutes] Failed to uninstall skill:",f),$.json({success:!1,error:f.message},500)}}),V.post("/install",async($)=>{try{let f=await $.req.json(),O=_f(),M=t(),J=!1;if(f.source==="catalog"&&f.name){if(J=await O.installOfficialSkill(f.name),!J)return $.json({success:!1,error:"Failed to install skill from catalog"},500)}else if(f.source==="repo"&&f.url){if(J=await O.installFromRepo(f.url,f.name),!J)return $.json({success:!1,error:"Failed to install skill from repository. Make sure the repo contains a SKILL.md file."},500)}else if(f.source==="local"&&f.path){if(J=await O.installFromLocal(f.path,f.name),!J)return $.json({success:!1,error:"Failed to install skill from local path. Make sure the path exists and contains a SKILL.md file."},500)}else return $.json({success:!1,error:"Invalid install parameters. Required: source with corresponding url/path/name"},400);return await M.refresh(),$.json({success:!0})}catch(f){return b.error("[SkillsRoutes] Failed to install skill:",f),$.json({success:!1,error:f.message},500)}}),V.get("/catalog",async($)=>{try{let f=await E0();return $.json(f)}catch(f){return b.error("[SkillsRoutes] Failed to get catalog:",f),$.json([])}}),V};import F0 from"fast-glob";import{Hono as U0}from"hono";import{execSync as q0}from"node:child_process";import{readdir as B0}from"node:fs/promises";import i from"node:path";var r=x("Service"),W0=(V)=>{try{return q0("git rev-parse --abbrev-ref HEAD",{cwd:V,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||null}catch{return null}},A0=[...s.map((V)=>`${V}/**`),...s,...Mf.map((V)=>`**/${V}`)],C0=new Set(["/theme","/model","/permissions","/mcp","/skills","/exit","/resume","/ide","/login","/logout"]),Pf=()=>{let V=new U0;return V.get("/commands",async($)=>{try{let f=$.req.query("q")||"",O=Lf(f).filter((M)=>!C0.has(M.command));return $.json(O)}catch(f){return r.error("[SuggestionsRoutes] Failed to get command suggestions:",f),$.json([])}}),V.get("/files",async($)=>{try{let f=$.req.query("q")||"",O=$.get("directory")||R(),M=Math.min(Number($.req.query("limit"))||100,1000),j=(await F0("**/*",{cwd:O,dot:!1,followSymbolicLinks:!1,onlyFiles:!1,markDirectories:!0,unique:!0,ignore:A0})).map((Q)=>Q.replace(/\\/g,"/"));if(!f)return $.json(j.slice(0,M));let Y=f.toLowerCase(),K=j.filter((Q)=>Q.toLowerCase().includes(Y)).slice(0,M);return $.json(K)}catch(f){return r.error("[SuggestionsRoutes] Failed to get file suggestions:",f),$.json([])}}),V.get("/files/tree",async($)=>{try{let f=$.get("directory")||R(),O=$.req.query("path")||"",M=O?i.join(f,O):f,j=(await B0(M,{withFileTypes:!0})).map((Q)=>({name:Q.name,path:O?`${O}/${Q.name}`:Q.name,type:Q.isDirectory()?"dir":"file"}));j.sort((Q,Z)=>{if(Q.type!==Z.type)return Q.type==="dir"?-1:1;return Q.name.localeCompare(Z.name)});let Y=new Set(s),K=j.filter((Q)=>{let Z=Q.name;if(Z.startsWith("."))return!1;if(Y.has(Z))return!1;for(let G of Mf)if(Z.match(new RegExp(G.replace("*",".*"))))return!1;return!0});return $.json(K)}catch(f){return r.error("[SuggestionsRoutes] Failed to get file tree:",f),$.json([])}}),V.get("/files/content",async($)=>{try{let f=$.req.query("path");if(!f)return $.json({error:"Missing file path"},400);let O=$.get("directory")||R(),M=i.resolve(O,f),J=i.relative(O,M);if(J.startsWith("..")||i.isAbsolute(J))return $.json({error:"Invalid file path"},400);let j=wf(),Y=await j.stat(M);if(!Y?.isFile)return $.json({error:"File not found"},404);let K=200000,Q=await j.readTextFile(M),Z=Q.length>K;return $.json({path:f,content:Z?Q.slice(0,K):Q,truncated:Z,size:Y.size})}catch(f){return r.error("[SuggestionsRoutes] Failed to get file content:",f),$.json({error:"Failed to read file"},500)}}),V.get("/git-info",async($)=>{try{let f=$.get("directory")||R(),O=W0(f);return $.json({branch:O})}catch(f){return r.error("[SuggestionsRoutes] Failed to get git info:",f),$.json({branch:null})}}),V};import{Hono as H0}from"hono";var _=x("Service"),v=new Map,kf=2097152,Sf=65536;function uf(){return typeof globalThis.Bun<"u"}async function z0(V,$,f){if(uf()){let{spawn:J}=await import("bun-pty"),j=J(V,$,{name:"xterm-256color",cwd:f.cwd,env:f.env});return{pid:j.pid,write:(Y)=>j.write(Y),resize:(Y,K)=>j.resize(Y,K),kill:()=>j.kill(),onData:(Y)=>j.onData(Y),onExit:(Y)=>j.onExit(Y)}}let M=(await import("node-pty")).spawn(V,$,{name:"xterm-256color",cwd:f.cwd,env:f.env,cols:80,rows:24});return{pid:M.pid,write:(J)=>M.write(J),resize:(J,j)=>M.resize(J,j),kill:()=>M.kill(),onData:(J)=>{M.onData(J)},onExit:(J)=>{M.onExit(J)}}}var Qf=void 0,Jf;if(uf())try{let{createBunWebSocket:V}=await import("hono/bun"),$=V();Jf=$.upgradeWebSocket,Qf=$.websocket}catch(V){_.warn("[Terminal] Failed to initialize Bun WebSocket support:",V)}async function hf(V,$){let f=`term-${Date.now()}`;_.info(`[Terminal] New connection: ${f}, cwd: ${V}`);let O=process.platform==="win32"?"powershell.exe":process.env.SHELL||"/bin/zsh",M=O.endsWith("sh")?["-l"]:[],J=await z0(O,M,{cwd:V,env:{...process.env,TERM:"xterm-256color",COLORTERM:"truecolor"}}),j={id:f,process:J,cwd:V,buffer:"",subscribers:new Set};if(v.set(f,j),j.subscribers.add($),J.onData((Y)=>{let K=!1;for(let Q of j.subscribers)try{Q.send(Y),K=!0}catch{j.subscribers.delete(Q)}if(K)return;if(j.buffer+=Y,j.buffer.length>kf)j.buffer=j.buffer.slice(-kf)}),J.onExit(({exitCode:Y})=>{_.info(`[Terminal] Process exited: ${f}, code: ${Y}`);for(let K of j.subscribers)try{K.close()}catch{}v.delete(f)}),j.buffer){let Y=j.buffer;j.buffer="";for(let K=0;K<Y.length;K+=Sf)$.send(Y.slice(K,K+Sf))}return{session:j,cleanup:()=>{if(_.info(`[Terminal] Connection closed: ${f}`),j.subscribers.delete($),j.subscribers.size===0){try{j.process.kill()}catch{}v.delete(f)}}}}function If(V,$){V.on("connection",async(f,O)=>{let M=new URL(O.url||"/",`http://${O.headers.host}`);if(!M.pathname.endsWith("/terminal/ws")){f.close();return}let J=M.searchParams.get("cwd")||$()||R();try{let{session:j,cleanup:Y}=await hf(J,{send:(K)=>f.send(K),close:()=>f.close()});f.on("message",(K)=>{try{j.process.write(String(K))}catch(Q){_.error("[Terminal] Failed to write to PTY:",Q)}}),f.on("close",Y),f.on("error",Y)}catch(j){_.error("[Terminal] Failed to spawn PTY:",j),f.close()}})}var vf=()=>{let V=new H0;if(V.get("/status",($)=>{let f=Array.from(v.values()).map((O)=>({id:O.id,cwd:O.cwd}));return $.json({active:f.length,terminals:f})}),V.post("/kill/:terminalId",($)=>{let f=$.req.param("terminalId"),O=v.get(f);if(O){try{O.process.kill()}catch{}for(let M of O.subscribers)M.close();return v.delete(f),$.json({success:!0})}return $.json({success:!1,error:"Terminal not found"},404)}),Jf)V.get("/ws",Jf(($)=>{let f=$.req.query("cwd")||$.get("directory")||R(),O;return{async onOpen(M,J){try{O=await hf(f,{send:(j)=>J.send(j),close:()=>J.close()})}catch(j){_.error("[Terminal] Failed to spawn PTY:",j),J.close()}},onMessage(M){if(!O)return;try{O.session.process.write(String(M.data))}catch(J){_.error("[Terminal] Failed to write to PTY:",J)}},onClose(){O?.cleanup()}}}));else V.get("/ws",($)=>{return $.json({message:"WebSocket endpoint - connect via ws:// protocol",hint:"Use WebSocket client to connect to this endpoint"})});return V};var W=x("Service"),Yf=[];function k0(){let V=b0(L0(import.meta.url)),$=[w(V,"web"),w(R(),"dist/web"),w(R(),"packages/cli/dist/web")];for(let f of $){let O=w(f,"index.html");if(gf(O)){if(e(O,"utf-8").includes("/assets/"))return W.debug(`[Server] Found web dist at: ${f}`),f}}return null}function S0(){let V=new T0;V.onError((f,O)=>{if(W.error("[Server] Request error:",f),f instanceof p)return O.json(f.toObject(),f.statusCode);let M=f instanceof Error?f.message:String(f);return O.json({error:{code:"INTERNAL_ERROR",message:M}},500)}),V.use(async(f,O)=>{let M=process.env.BLADE_SERVER_PASSWORD;if(!M)return O();let J=f.req.path;if(J==="/"||J.startsWith("/assets/")||J.endsWith(".html")||J.endsWith(".js")||J.endsWith(".css"))return O();let j=f.req.header("Authorization");if(!j?.startsWith("Basic "))return f.header("WWW-Authenticate",'Basic realm="Blade Server"'),f.json({error:{code:"UNAUTHORIZED",message:"Authentication required"}},401);let Y=Buffer.from(j.slice(6),"base64").toString(),[K,Q]=Y.split(":"),Z=process.env.BLADE_SERVER_USERNAME??"blade";if(K!==Z||Q!==M)return f.json({error:{code:"UNAUTHORIZED",message:"Invalid credentials"}},401);return O()}),V.use(async(f,O)=>{let M=f.req.path==="/health"||f.req.path==="/global/health"||f.req.path.startsWith("/assets/");if(!M)W.debug(`[Server] ${f.req.method} ${f.req.path}`);let J=Date.now();if(await O(),!M){let j=Date.now()-J;W.debug(`[Server] ${f.req.method} ${f.req.path} - ${f.res.status} (${j}ms)`)}}),V.use(y0({origin(f){if(!f)return;if(f.startsWith("http://localhost:"))return f;if(f.startsWith("http://127.0.0.1:"))return f;if(f==="tauri://localhost"||f==="http://tauri.localhost")return f;if(Yf.includes(f))return f;return}})),V.use(async(f,O)=>{let M=f.req.query("directory")||f.req.header("x-blade-directory")||R();try{M=decodeURIComponent(M)}catch{}return f.set("directory",M),O()}),V.route("/global",Nf()),V.route("/sessions",Wf()),V.route("/configs",Gf()),V.route("/permissions",Cf()),V.route("/providers",yf()),V.route("/models",Xf()),V.route("/suggestions",Pf()),V.route("/terminal",vf()),V.route("/mcp",mf()),V.route("/skills",bf()),V.get("/health",(f)=>{return f.json({healthy:!0,version:u()})});let $=k0();if($)W.info(`[Server] Serving static files from ${$}`),V.get("/assets/*",(f)=>{let O=w($,f.req.path);if(!gf(O))return f.json({error:{code:"NOT_FOUND",message:`File not found: ${f.req.path}`}},404);let M=e(O),J=w0(O).toLowerCase(),Y={".js":"application/javascript",".css":"text/css",".html":"text/html",".json":"application/json",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".svg":"image/svg+xml",".ico":"image/x-icon",".woff":"font/woff",".woff2":"font/woff2",".ttf":"font/ttf",".eot":"application/vnd.ms-fontobject"}[J]||"application/octet-stream";return new Response(M,{headers:{"Content-Type":Y,"Cache-Control":"public, max-age=31536000, immutable"}})}),V.get("/",(f)=>{let O=w($,"index.html"),M=e(O,"utf-8");return f.html(M)}),V.get("*",(f)=>{let O=f.req.path;if(O.includes("."))return f.json({error:{code:"NOT_FOUND",message:`File not found: ${O}`}},404);let M=w($,"index.html"),J=e(M,"utf-8");return f.html(J)});else W.warn('[Server] Web UI not found. Run "cd packages/cli/web && bun run build" to enable web interface.'),V.get("/",(f)=>{return f.json({message:"Blade API Server",version:u(),webUI:!1,hint:'Web UI not built. Run "cd packages/cli/web && bun run build" to enable.',endpoints:{health:"/health",sessions:"/sessions",configs:"/configs",permissions:"/permissions",providers:"/providers"}})}),V.all("*",(f)=>{return f.json({error:{code:"NOT_FOUND",message:`Route not found: ${f.req.path}`}},404)});return V}function u0(){let V=D0(),$=[];for(let f of Object.keys(V)){let O=V[f];if(!O)continue;for(let M of O){if(M.internal||M.family!=="IPv4")continue;if(M.address.startsWith("172."))continue;$.push(M.address)}}return $}function pf(){return typeof globalThis.Bun<"u"}function of(V,$){let f=globalThis.Bun,O=(J)=>{try{return f.serve({hostname:$.hostname,port:J,fetch:V.fetch,idleTimeout:0,websocket:Qf})}catch(j){W.error("Failed to start Bun server:",j);return}},M=$.port===0?O(4096)??O(0):O($.port);if(!M)throw Error(`Failed to start Bun server on port ${$.port}`);return{url:M.url,port:M.port,hostname:M.hostname,stop:async()=>{M.stop(!0)}}}function h0(V,$){return new Promise((f,O)=>{let M=_0(async(Q,Z)=>{let G=new URL(Q.url||"/",`http://${Q.headers.host}`),m=new Headers;for(let[E,N]of Object.entries(Q.headers))if(N)if(Array.isArray(N))for(let F of N)m.append(E,F);else m.set(E,N);let q;if(Q.method!=="GET"&&Q.method!=="HEAD")q=(await new Promise((N)=>{let F=[];Q.on("data",(l)=>F.push(l)),Q.on("end",()=>N(Buffer.concat(F)))})).toString();let L=new Request(G.toString(),{method:Q.method,headers:m,body:q});try{let E=await V.fetch(L);if(Z.statusCode=E.status,E.headers.forEach((N,F)=>{Z.setHeader(F,N)}),E.body){let N=E.body.getReader(),F=async()=>{let{done:l,value:ff}=await N.read();if(l){Z.end();return}return Z.write(ff),F()};await F()}else{let N=await E.text();Z.end(N)}}catch(E){W.error("[Server] Node request error:",E),Z.statusCode=500,Z.end(JSON.stringify({error:{code:"INTERNAL_ERROR",message:"Internal server error"}}))}}),J=new P0({noServer:!0}),j=R();If(J,()=>j),M.on("upgrade",(Q,Z,G)=>{if(new URL(Q.url||"/",`http://${Q.headers.host}`).pathname==="/terminal/ws")J.handleUpgrade(Q,Z,G,(q)=>{J.emit("connection",q,Q)});else Z.destroy()});let Y=(Q)=>{return new Promise((Z,G)=>{M.once("error",(m)=>{if(m.code==="EADDRINUSE")G(m);else G(m)}),M.listen(Q,$.hostname,()=>{let m=M.address();if(m&&typeof m==="object")Z(m.port);else Z(Q)})})};(async()=>{let Q;if($.port===0)try{Q=await Y(4096)}catch{Q=await Y(0)}else Q=await Y($.port);let Z=new URL(`http://${$.hostname==="0.0.0.0"?"localhost":$.hostname}:${Q}`);f({url:Z,port:Q,hostname:$.hostname,stop:async()=>{return new Promise((G)=>{J.close(()=>{M.close(()=>G())})})}})})().catch(O)})}var df;((DV)=>{let V,$;function f(){if(!$)$=S0();return $}DV.getApp=f;function O(j){Yf=j.cors??[];let Y=f();if(pf())V=of(Y,j),W.info(`[Server] Blade server listening on ${V.url} (Bun runtime)`);else throw Error("Blade web server requires Bun runtime. Please run with Bun: `bun run blade web` or install Bun from https://bun.sh");let K=V;return{url:K.url,port:K.port,hostname:K.hostname,stop:async()=>{if(V)await V.stop(),V=void 0,$=void 0,W.info("[Server] Blade server stopped")}}}DV.listen=O;async function M(j){Yf=j.cors??[];let Y=f();if(pf())V=of(Y,j),W.info(`[Server] Blade server listening on ${V.url} (Bun runtime)`);else V=await h0(Y,j),W.info(`[Server] Blade server listening on ${V.url} (Node.js runtime)`);let K=V;return{url:K.url,port:K.port,hostname:K.hostname,stop:async()=>{if(V)await V.stop(),V=void 0,$=void 0,W.info("[Server] Blade server stopped")}}}DV.listenAsync=M;function J(){return V!==void 0}DV.isRunning=J})(df||={});export{I0 as a,v0 as b,u0 as c,df as d};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{Jb as y}from"./chunk-j7nh0j36.js";import*as j from"fs/promises";import*as $ from"path";import b from"semver";import{fileURLToPath as N}from"url";import{ProxyAgent as G,fetch as H}from"undici";function T(){return process.env.HTTPS_PROXY||process.env.HTTP_PROXY||process.env.https_proxy||process.env.http_proxy}function R(){let q=T();if(q)try{return new G(q)}catch(z){console.warn(`[proxyFetch] Invalid proxy URL: ${q}`)}return}async function K(q,z={}){let{timeout:W=30000,signal:Q,...B}=z;if(Q?.aborted)throw new DOMException("The operation was aborted.","AbortError");let J=R(),X=new AbortController,Y=!1,F=setTimeout(()=>{Y=!0,X.abort()},W),w=()=>X.abort();Q?.addEventListener("abort",w);try{let Z={method:B.method,headers:B.headers,body:B.body,signal:X.signal,dispatcher:J};return await H(q.toString(),Z)}catch(Z){if(Z instanceof Error&&Z.name==="AbortError"){if(Y)throw Error(`Request timeout after ${W}ms`);throw Z}throw Z}finally{clearTimeout(F),Q?.removeEventListener("abort",w)}}var D="blade-code",f="https://cdn.jsdelivr.net/npm/blade-code@latest/CHANGELOG.md",M=$.join(process.env.HOME||process.env.USERPROFILE||".",".blade"),S=$.join(M,"version-cache.json"),k=3600000,L=`https://registry.npmjs.org/${D}/latest`;async function x(){try{if(process.env.BLADE_VERSION)return process.env.BLADE_VERSION;let q=N(import.meta.url),z=$.dirname(q),W=[$.join(z,"..","..","package.json"),$.join(z,"..","package.json")];for(let Q of W)try{let B=await j.readFile(Q,"utf-8"),J=JSON.parse(B);if(J.name===D&&J.version)return J.version}catch{}return"unknown"}catch{return"unknown"}}async function I(){try{let q=await j.readFile(S,"utf-8"),z=JSON.parse(q);if(Date.now()-z.checkedAt<k)return z;return{...z,checkedAt:0}}catch{return null}}async function O(q){try{await j.mkdir(M,{recursive:!0,mode:493}),await j.writeFile(S,JSON.stringify(q,null,2))}catch{}}async function P(){try{let q=await K(L,{timeout:5000,headers:{Accept:"application/json"}});if(!q.ok)return null;return(await q.json()).version||null}catch{return null}}async function v(q=!1){let z=await x(),W=f;if(z==="unknown")return{currentVersion:z,latestVersion:null,hasUpdate:!1,shouldPrompt:!1,releaseNotesUrl:W,error:"Unable to determine current version"};let Q=await I(),B=Q?.skipUntilVersion,J=null;if(!q&&Q&&Q.checkedAt>0)J=Q.latestVersion;else if(J=await P(),J)await O({latestVersion:J,checkedAt:Date.now(),skipUntilVersion:B});if(!J)return{currentVersion:z,latestVersion:null,hasUpdate:!1,shouldPrompt:!1,releaseNotesUrl:W,error:"Unable to check for updates"};let X=b.gt(J,z),Y=X;if(X&&B)Y=b.gt(J,B);return{currentVersion:z,latestVersion:J,hasUpdate:X,shouldPrompt:Y,releaseNotesUrl:W}}async function u(q){let z=await I();await O({latestVersion:z?.latestVersion||q,checkedAt:z?.checkedAt||Date.now(),skipUntilVersion:q})}function g(){return`npm install -g ${D}@latest --registry https://registry.npmjs.org`}async function C(){let{spawn:q}=await import("child_process");return new Promise((z)=>{let W=g(),Q=q(W,{stdio:"inherit",shell:!0});Q.on("close",(B)=>{if(B===0)z({success:!0,message:"Upgrade successful! Please restart blade."});else z({success:!1,message:`Upgrade failed (exit code: ${B})`})}),Q.on("error",(B)=>{z({success:!1,message:`Upgrade failed: ${B.message}`})})})}async function d(){try{let q=await v();return q.shouldPrompt?q:null}catch{return null}}
|
|
2
2
|
export{v as g,u as h,g as i,C as j,d as k};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{va as Q}from"./chunk-
|
|
1
|
+
import{va as Q}from"./chunk-h46kk20y.js";import{nb as U}from"./chunk-0e9dhemy.js";import{xb as O}from"./chunk-7ycmx7c2.js";import{Fb as K,Hb as N}from"./chunk-bpx8x87m.js";function Y(){if(process.stdin.isTTY&&typeof process.stdin.setRawMode==="function")try{process.stdin.setRawMode(!1)}catch{}process.stdout.write("\x1B[<u"),process.stdout.write("\x1B[>4;0m"),process.stdout.write("\x1B[?2004l"),process.stdout.write("\x1B[?1l\x1B>"),process.stdout.write("\x1B[?25h"),process.stdout.write("\x1B[0m")}var A=N("Service");function Z(b){switch(b){case"SIGINT":return"ctrl_c";case"esc":return"esc";case"uncaughtException":case"unhandledRejection":return"error";case"SIGTERM":case"normal":default:return"user_exit"}}class D{static instance=null;cleanupHandlers=[];isShuttingDown=!1;initialized=!1;lastSigintTime=0;SIGINT_DOUBLE_CLICK_WINDOW=3000;constructor(){}static getInstance(){if(!D.instance)D.instance=new D;return D.instance}initialize(){if(this.initialized){A.debug("[GracefulShutdown] 已初始化,跳过重复初始化");return}process.on("uncaughtException",(b)=>{this.handleFatalError("uncaughtException",b)}),process.on("unhandledRejection",(b)=>{let q=b instanceof Error?b:Error(String(b));this.handleFatalError("unhandledRejection",q)}),process.on("SIGTERM",()=>{A.info("[GracefulShutdown] 收到 SIGTERM 信号"),this.shutdown("SIGTERM",0)}),process.on("SIGINT",()=>{let b=Date.now();if(b-this.lastSigintTime<this.SIGINT_DOUBLE_CLICK_WINDOW)A.info("[GracefulShutdown] 收到第二次 SIGINT 信号,执行退出"),this.shutdown("SIGINT",0);else A.info("[GracefulShutdown] 收到第一次 SIGINT 信号,再按一次退出"),this.lastSigintTime=b,console.log(`
|
|
2
2
|
再按一次 Ctrl+C 退出
|
|
3
3
|
`)}),this.initialized=!0,A.debug("[GracefulShutdown] 全局错误处理器已初始化")}registerCleanup(b){return this.cleanupHandlers.push(b),A.debug(`[GracefulShutdown] 注册清理函数,当前共 ${this.cleanupHandlers.length} 个`),()=>{let q=this.cleanupHandlers.indexOf(b);if(q!==-1)this.cleanupHandlers.splice(q,1),A.debug(`[GracefulShutdown] 取消注册清理函数,剩余 ${this.cleanupHandlers.length} 个`)}}handleFatalError(b,q){if(this.isShuttingDown){console.error(`[GracefulShutdown] 退出过程中发生额外错误 (${b}):`,q);return}if(console.error(""),console.error("═".repeat(60)),console.error(`Uncaught error (${b})`),console.error("═".repeat(60)),console.error(""),console.error("错误信息:",q.message),console.error(""),q.stack)console.error("堆栈跟踪:"),console.error(q.stack);console.error(""),console.error("═".repeat(60)),console.error(""),this.shutdown(b,1)}async shutdown(b,q=0){if(this.isShuttingDown){A.debug("[GracefulShutdown] 已在退出过程中,跳过重复退出");return}this.isShuttingDown=!0,A.info(`[GracefulShutdown] 开始优雅退出 (原因: ${b})`);try{await K()}catch(z){}try{let z=U.getInstance();if(z.isEnabled()){let F=Q(),W=F.session?.sessionId||"unknown",X=F.config?.config?.permissionMode||"default";await z.executeSessionEndHooks(Z(b),{projectDir:O(),sessionId:W,permissionMode:X})}}catch(z){console.error("[GracefulShutdown] SessionEnd hooks 执行失败:",z)}let B=5000,V=new Promise((z,F)=>{setTimeout(()=>{F(Error(`清理超时 (${B}ms)`))},B)});try{let z=this.runCleanupHandlers();await Promise.race([z,V])}catch(z){console.error("[GracefulShutdown] 清理过程中发生错误:",z)}finally{Y(),setTimeout(()=>{process.exit(q)},100)}}async runCleanupHandlers(){let b=[...this.cleanupHandlers].reverse();for(let q of b)try{let B=q();if(B instanceof Promise)await B}catch(B){console.error("[GracefulShutdown] 清理函数执行失败:",B)}}isExiting(){return this.isShuttingDown}reset(){this.isShuttingDown=!1,this.cleanupHandlers=[],this.initialized=!1}}var J=()=>{return D.getInstance()},H=(b)=>{return J().registerCleanup(b)},P=()=>{J().initialize()},L=(b=0)=>{J().shutdown("normal",b)};
|
|
4
4
|
export{J as l,H as m,P as n,L as o};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as y,b as A,c as C,d as D}from"./chunk-
|
|
1
|
+
import{a as y,b as A,c as C,d as D}from"./chunk-qnvkxpkw.js";import"./chunk-cfe1fywb.js";import"./chunk-7t23swne.js";import"./chunk-59e6eg4b.js";import"./chunk-evc1xkeb.js";import"./chunk-p8pggabj.js";import"./chunk-ck43cs45.js";import{Aa as q}from"./chunk-h46kk20y.js";import"./chunk-m41xq6d0.js";import"./chunk-njq4w631.js";import"./chunk-f24ahjpc.js";import"./chunk-0e9dhemy.js";import"./chunk-6mfmy7nq.js";import"./chunk-7ycmx7c2.js";import"./chunk-bpx8x87m.js";import"./chunk-j7nh0j36.js";import H from"chalk";var R={command:"serve",describe:"Start a headless Blade server (no browser)",builder:y,handler:async(E)=>{let f=A(E);if(await q(),!process.env.BLADE_SERVER_PASSWORD)console.log(H.yellow("Warning: BLADE_SERVER_PASSWORD is not set; server is unsecured."));let b=await D.listenAsync(f);if(console.log(`Blade server listening on http://${b.hostname}:${b.port}`),f.hostname==="0.0.0.0"){let F=C();for(let G of F)console.log(` Network: http://${G}:${b.port}`)}await new Promise(()=>{}),await b.stop()}};export{R as serveCommand};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{va as z}from"./chunk-
|
|
1
|
+
import{va as z}from"./chunk-h46kk20y.js";import{Ia as w}from"./chunk-m41xq6d0.js";import{Hb as u}from"./chunk-bpx8x87m.js";var q=u("General"),F=(b)=>{if(b.yolo){if(b.permissionMode&&b.permissionMode!=="yolo")throw Error("Cannot use both --yolo and --permission-mode with different values");b.permissionMode="yolo"}if(Array.isArray(b.allowedTools))b.allowedTools=b.allowedTools.flatMap((h)=>h.split(",").map((k)=>k.trim()).filter((k)=>k.length>0));if(Array.isArray(b.disallowedTools))b.disallowedTools=b.disallowedTools.flatMap((h)=>h.split(",").map((k)=>k.trim()).filter((k)=>k.length>0));if(Array.isArray(b.allowedTools)&&Array.isArray(b.disallowedTools)){let h=b.allowedTools.filter((k)=>b.disallowedTools.includes(k));if(h.length>0)throw Error(`Tools cannot be both allowed and disallowed: ${h.join(", ")}`)}},G=async(b)=>{try{let k=await w.getInstance().initialize();if(z().config.actions.setConfig(k),b.debug)q.info("[CLI] 配置已加载到 Store")}catch(h){q.error("[CLI] [FAIL] 配置初始化失败",h instanceof Error?h.message:h),console.error(`
|
|
2
2
|
[FAIL] 配置初始化失败
|
|
3
3
|
`),console.error("原因:",h instanceof Error?h.message:"未知错误"),console.error(`
|
|
4
4
|
请检查:`),console.error(" 1. 配置文件格式是否正确 (~/.blade/config.json)"),console.error(" 2. 是否需要运行 blade 进行首次配置"),console.error(` 3. 配置文件权限是否正确
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{rb as a}from"./chunk-6mfmy7nq.js";import"./chunk-bpx8x87m.js";import"./chunk-j7nh0j36.js";export{a as createChatServiceAsync};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{ba as d,da as h}from"./chunk-
|
|
1
|
+
import{ba as d,da as h}from"./chunk-p8pggabj.js";var q={debug:{alias:"d",type:"string",describe:'Enable debug mode with optional category filtering (e.g., "agent,ui" or "!chat,!loop")',group:"Debug Options:"},model:{type:"string",describe:"Override the current run model using a model config ID (TUI / print / headless)",group:"AI Options:"},print:{alias:"p",type:"boolean",describe:"Print response and exit (useful for pipes)",group:"Output Options:"},headless:{type:"boolean",describe:"Run full agent loop without Ink UI and print all events to the terminal",group:"Output Options:"},"output-format":{alias:["outputFormat"],type:"string",choices:["text","json","stream-json","jsonl"],default:"text",describe:"Output format: --print supports text|json|stream-json; --headless supports text|jsonl",group:"Output Options:"},"include-partial-messages":{alias:["includePartialMessages"],type:"boolean",describe:"Include partial message chunks as they arrive",group:"Output Options:"},"input-format":{alias:["inputFormat"],type:"string",choices:["text","stream-json"],default:"text",describe:"Input format",group:"Input Options:"},"replay-user-messages":{alias:["replayUserMessages"],type:"boolean",describe:"Re-emit user messages from stdin",group:"Input Options:"},"allowed-tools":{alias:["allowedTools"],type:"array",string:!0,describe:"Comma or space-separated list of tool names to allow",group:"Security Options:"},"disallowed-tools":{alias:["disallowedTools"],type:"array",string:!0,describe:"Comma or space-separated list of tool names to deny",group:"Security Options:"},"mcp-config":{alias:["mcpConfig"],type:"array",string:!0,describe:"Load MCP servers from JSON files or strings",group:"MCP Options:"},"system-prompt":{alias:["systemPrompt"],type:"string",describe:"System prompt to use for the session (replaces default)",group:"AI Options:"},"append-system-prompt":{alias:["appendSystemPrompt"],type:"string",describe:"Append a system prompt to the default system prompt",group:"AI Options:"},"max-turns":{alias:["maxTurns"],type:"number",describe:"Maximum conversation turns (-1: unlimited, 0: disable chat, N>0: limit to N turns)",group:"AI Options:",default:void 0},"permission-mode":{alias:["permissionMode"],type:"string",choices:["default","autoEdit","yolo","plan"],describe:"Permission mode (default: ask for non-read tools, autoEdit: auto-approve edits, yolo: auto-approve all, plan: reserved)",group:"Security Options:"},yolo:{type:"boolean",describe:"Auto-approve all tools (shortcut for --permission-mode=yolo)",group:"Security Options:"},continue:{alias:"c",type:"boolean",describe:"Continue the most recent conversation",group:"Session Options:"},resume:{alias:"r",describe:"Resume a conversation - provide a session ID or interactively select a conversation to resume",group:"Session Options:",coerce:(b)=>{if(b===void 0||b===!0||b==="")return"true";return String(b)}},"fork-session":{alias:["forkSession"],type:"boolean",describe:"Create a new session ID when resuming",group:"Session Options:"},settings:{type:"string",describe:"Path to a settings JSON file or JSON string",group:"Configuration:"},"add-dir":{alias:["addDir"],type:"array",string:!0,describe:"Additional directories to allow tool access to",group:"Security Options:"},ide:{type:"boolean",describe:"Automatically connect to IDE on startup",group:"Integration:"},acp:{type:"boolean",describe:"Run in ACP (Agent Client Protocol) mode for IDE integration",group:"Integration:"},"strict-mcp-config":{alias:["strictMcpConfig"],type:"boolean",describe:"Only use MCP servers from --mcp-config",group:"MCP Options:"},"session-id":{alias:["sessionId"],type:"string",describe:"Use a specific session ID for the conversation",group:"Session Options:"},agents:{type:"string",describe:"JSON object defining custom agents",group:"AI Options:"},"setting-sources":{alias:["settingSources"],type:"string",describe:"Comma-separated list of setting sources to load",group:"Configuration:"},"plugin-dir":{alias:["pluginDir"],type:"array",string:!0,describe:"Load plugins from specified directories",group:"Plugin Options:"}},w={scriptName:"blade",usage:"$0 [command] [options]",description:h(),version:d(),locale:"en",showHelpOnFail:!0,demandCommand:!1,recommendCommands:!0,strict:!1};
|
|
2
2
|
export{q as t,w as u};
|