blade-code 0.10.74 → 0.10.75
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-2e6pcscc.js → chunk-0jmvv2vb.js} +1 -1
- package/dist/{chunk-8w1gtvy0.js → chunk-1zwq624e.js} +1 -1
- package/dist/{chunk-y67yrm3k.js → chunk-22sw5bv4.js} +1 -1
- package/dist/{chunk-1ykz47d9.js → chunk-57jj40er.js} +1 -1
- package/dist/{chunk-ntvm6t83.js → chunk-5a132j64.js} +1 -1
- package/dist/{chunk-bawbgvm3.js → chunk-5dz30k5z.js} +1 -1
- package/dist/{chunk-54va5hc4.js → chunk-5tat9wy9.js} +1 -1
- package/dist/{chunk-fhxy024n.js → chunk-6bka1j4q.js} +1 -1
- package/dist/chunk-7yppfbgr.js +1 -0
- package/dist/{chunk-6ra5d8ng.js → chunk-agxs6rwh.js} +1 -1
- package/dist/{chunk-453tf6d0.js → chunk-c74e0jx1.js} +1 -1
- package/dist/{chunk-bxtw5f52.js → chunk-d2eahefk.js} +1 -1
- package/dist/{chunk-7kf3hwp3.js → chunk-egp0crrc.js} +1 -1
- package/dist/chunk-fefz145r.js +1 -0
- package/dist/{chunk-yrbbx1pr.js → chunk-fpkq3ch3.js} +1 -1
- package/dist/{chunk-8zpsw401.js → chunk-g3fbgp1k.js} +1 -1
- package/dist/{chunk-map4165w.js → chunk-gz2fx7th.js} +1 -1
- package/dist/{chunk-d51pge1m.js → chunk-hzy5jzkp.js} +1 -1
- package/dist/{chunk-21bb1xda.js → chunk-kb5xaar0.js} +3 -3
- package/dist/{chunk-cpky2bgy.js → chunk-m6yfwyva.js} +1 -1
- package/dist/{chunk-16k0tc6h.js → chunk-m88zk362.js} +1 -1
- package/dist/{chunk-7hc84akg.js → chunk-n0x5z56v.js} +2 -2
- package/dist/{chunk-k3ddw7q3.js → chunk-nfyxb2q5.js} +1 -1
- package/dist/{chunk-8asewt01.js → chunk-pdansrbx.js} +1 -1
- package/dist/{chunk-74wb5e1h.js → chunk-rdtgv0n8.js} +1 -1
- package/dist/{chunk-shx5e10e.js → chunk-s7gf2ds9.js} +1 -1
- package/dist/{chunk-1qde0g23.js → chunk-ssfvcnat.js} +1 -1
- package/dist/{chunk-63c25yhj.js → chunk-swvp6j18.js} +1 -1
- package/dist/{chunk-0m2bs3s2.js → chunk-tnjq10zs.js} +1 -1
- package/dist/{chunk-kheaqr7j.js → chunk-v0znd20r.js} +1 -1
- package/dist/{chunk-xgmn301g.js → chunk-v4ek6q8t.js} +1 -1
- package/dist/{chunk-vm5bzhrm.js → chunk-vbxtqh24.js} +1 -1
- package/dist/{chunk-wgztvasm.js → chunk-vkpddj6a.js} +1 -1
- package/dist/{chunk-cvbacjwr.js → chunk-w1m7wz1y.js} +1 -1
- package/dist/{chunk-ytce7gnt.js → chunk-xts31qj4.js} +1 -1
- package/dist/{chunk-fx19tpcm.js → chunk-yk8s8kjt.js} +1 -1
- package/dist/{chunk-465tgzab.js → chunk-zph2jekm.js} +1 -1
- package/package.json +1 -1
- package/dist/chunk-aqzbsxjh.js +0 -1
- package/dist/chunk-x5579r4w.js +0 -1
|
@@ -25,7 +25,7 @@ import{mf as YO}from"./chunk-03947xkg.js";import{tg as qO,vg as S,yg as y}from".
|
|
|
25
25
|
`):void 0}}async executeNotificationHooks(O,q,Q){let Z="message"in q?q.message:"";if(O.length===0)return{suppress:!1,message:Z};let Y=[],$=!1,X=Z;for(let W of O)try{let J=await this.executeHook(W,q,Q);if(!J.success){if(J.warning)Y.push(J.warning);continue}if(J.output?.suppressOutput){$=!0;break}if(J.stdout&&J.stdout.trim())X=J.stdout.trim()}catch(J){let G=J instanceof Error?J.message:String(J);Y.push(`Hook failed: ${G}`)}return{suppress:$,message:X,warning:Y.length>0?Y.join(`
|
|
26
26
|
`):void 0}}async executeCompactionHooks(O,q,Q){if(O.length===0)return{blockCompaction:!1};let Z=[];for(let Y of O)try{let $=await this.executeHook(Y,q,Q);if(!$.success){if($.warning)Z.push($.warning);continue}let X=$.output?.hookSpecificOutput;if(X&&"blockCompaction"in X&&X.blockCompaction)return{blockCompaction:!0,blockReason:X.blockReason,warning:Z.length>0?Z.join(`
|
|
27
27
|
`):void 0}}catch($){let X=$ instanceof Error?$.message:String($);Z.push(`Hook failed: ${X}`)}return{blockCompaction:!1,warning:Z.length>0?Z.join(`
|
|
28
|
-
`):void 0}}async executeHook(O,q,Q){if(O.type!=="function"){let Y=await A.getInstance().getStatus(Q.projectDir,Q.config);if(Y.state!=="trusted"){let $=`${Y.trustRoot}:${Y.currentDigest}:${Y.state}`;if(!this.trustWarnings.has($)){if(this.trustWarnings.size>=512)this.trustWarnings.clear();this.trustWarnings.add($),$O.warn(`[HookTrust] Skipping configured hooks for ${Y.trustRoot}: ${Y.state}`)}return{success:!0,hook:O,warning:`Hook skipped: project hook trust is ${Y.state}`}}}let Z=this.withHookEnvironment(Q,O);if(O.type==="command")return this.executeCommandHook(O,q,Z);if(O.type==="prompt")return this.executePromptHook(O,q,Z);if(O.type==="function")return this.executeFunctionHook(O,q,Z);if(O.type==="http")return this.executeHttpHook(O,q,Z);throw Error(`Hook type ${O.type} not supported`)}async executeCommandHook(O,q,Q){let Z=(O.timeout??Q.config.defaultTimeout??60)*1000;try{let Y=await this.processExecutor.execute(O.command,q,Q,Z);return this.outputParser.parse(Y,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}catch(Y){return{success:!1,blocking:!1,error:Y instanceof Error?Y.message:String(Y),hook:O}}}async executePromptHook(O,q,Q){let Z=(O.timeout??Q.config.defaultTimeout??60)*1000;try{let Y=await this.getOrCreateChatService(O.model,Q),$="hook_event_name"in q?String(q.hook_event_name):"Unknown",X=this.buildPromptHookSystemMessage(O,$),W=JSON.stringify(q,null,2),J=new AbortController,G=setTimeout(()=>J.abort(),Z),L;try{L=(await Y.chat([{role:"system",content:X},{role:"user",content:W}],void 0,J.signal,{providerAdmission:{sessionId:Q.sessionId,ownerId:Q.sessionId,requestClass:"background"}})).content}catch(z){if(J.signal.aborted||z instanceof Error&&z.name==="AbortError")return this.outputParser.parse({stdout:"",stderr:"",exitCode:0,timedOut:!0},O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior});throw z}finally{clearTimeout(G)}let F=this.extractJsonFromLLMResponse(L);return this.outputParser.parse({stdout:F,stderr:"",exitCode:0,timedOut:!1},O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}catch(Y){return $O.warn(`[PromptHook] 执行失败: ${Y instanceof Error?Y.message:String(Y)}`),{success:!1,blocking:!1,error:Y instanceof Error?Y.message:String(Y),hook:O}}}async executeFunctionHook(O,q,Q){let Z=(O.timeout??10)*1000;try{let Y=await this.runFunctionWithTimeout(O.handler,q,Q,Z);if(Y===void 0||Y===null)return{success:!0,hook:O};let $={stdout:JSON.stringify(Y),stderr:"",exitCode:0,timedOut:!1};return this.outputParser.parse($,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}catch(Y){if(Y.isTimeout){let $={stdout:"",stderr:`Function hook timeout after ${Z}ms`,exitCode:124,timedOut:!0};return this.outputParser.parse($,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}return{success:!1,blocking:!1,error:Y instanceof Error?Y.message:String(Y),hook:O}}}runFunctionWithTimeout(O,q,Q,Z){return new Promise((Y,$)=>{let X=!1,W=setTimeout(()=>{if(X)return;X=!0;let G=Object.assign(Error(`Function hook timed out after ${Z}ms`),{isTimeout:!0});$(G)},Z),J=()=>{if(X)return;X=!0,clearTimeout(W),$(Error("Function hook aborted"))};Q.abortSignal?.addEventListener("abort",J,{once:!0}),Promise.resolve().then(()=>O(q,Q)).then((G)=>{if(X)return;X=!0,clearTimeout(W),Q.abortSignal?.removeEventListener("abort",J),Y(G)},(G)=>{if(X)return;X=!0,clearTimeout(W),Q.abortSignal?.removeEventListener("abort",J),$(G)})})}async executeHttpHook(O,q,Q){let Z=(O.timeout??10)*1000,Y=O.maxResponseBytes??262144,$=Math.max(1,(O.retries??0)+1);try{e(O.url,Q.config.httpPolicy)}catch(G){return{success:!1,blocking:!0,error:G instanceof Error?G.message:String(G),hook:O}}let X={"Content-Type":"application/json",...OO(O.headers)},W=JSON.stringify(q),J;for(let G=0;G<$;G++){if(G>0){let V=Math.min(2**G*200,5000);await new Promise((B)=>setTimeout(B,V))}let L=new AbortController,F=setTimeout(()=>L.abort(),Z),z=()=>L.abort();Q.abortSignal?.addEventListener("abort",z,{once:!0});try{let V=await fetch(O.url,{method:"POST",headers:X,body:W,redirect:"manual",signal:L.signal});if(V.status>=300&&V.status<400){J=Error(`HTTP hook received redirect (${V.status}); redirects are disabled`);continue}if(!V.ok){if(J=Error(`HTTP hook returned ${V.status} ${V.statusText}`),V.status>=400&&V.status<500)break;continue}let U={stdout:await HO(V,Y),stderr:"",exitCode:0,timedOut:!1};return this.outputParser.parse(U,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}catch(V){let B=V.name==="AbortError"||V.code==="ABORT_ERR";if(B&&Q.abortSignal?.aborted){J=Error("HTTP hook aborted by caller");break}if(B){let U={stdout:"",stderr:`HTTP hook timeout after ${Z}ms`,exitCode:124,timedOut:!0};if(G===$-1)return this.outputParser.parse(U,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior});J=Error(`HTTP hook timeout attempt ${G+1}`);continue}J=V}finally{clearTimeout(F),Q.abortSignal?.removeEventListener("abort",z)}}return{success:!1,blocking:!1,error:J?.message??"HTTP hook failed",hook:O}}async getOrCreateChatService(O,q){let Q=this.sessionResourceKey(q.sessionId,q.projectDir),Z=`${Q}\x00${O||"__default__"}`,Y=this.chatServiceCache.get(Z);if(Y)return Y;let{ensureStoreInitialized:$,getConfig:X}=await import("./chunk-
|
|
28
|
+
`):void 0}}async executeHook(O,q,Q){if(O.type!=="function"){let Y=await A.getInstance().getStatus(Q.projectDir,Q.config);if(Y.state!=="trusted"){let $=`${Y.trustRoot}:${Y.currentDigest}:${Y.state}`;if(!this.trustWarnings.has($)){if(this.trustWarnings.size>=512)this.trustWarnings.clear();this.trustWarnings.add($),$O.warn(`[HookTrust] Skipping configured hooks for ${Y.trustRoot}: ${Y.state}`)}return{success:!0,hook:O,warning:`Hook skipped: project hook trust is ${Y.state}`}}}let Z=this.withHookEnvironment(Q,O);if(O.type==="command")return this.executeCommandHook(O,q,Z);if(O.type==="prompt")return this.executePromptHook(O,q,Z);if(O.type==="function")return this.executeFunctionHook(O,q,Z);if(O.type==="http")return this.executeHttpHook(O,q,Z);throw Error(`Hook type ${O.type} not supported`)}async executeCommandHook(O,q,Q){let Z=(O.timeout??Q.config.defaultTimeout??60)*1000;try{let Y=await this.processExecutor.execute(O.command,q,Q,Z);return this.outputParser.parse(Y,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}catch(Y){return{success:!1,blocking:!1,error:Y instanceof Error?Y.message:String(Y),hook:O}}}async executePromptHook(O,q,Q){let Z=(O.timeout??Q.config.defaultTimeout??60)*1000;try{let Y=await this.getOrCreateChatService(O.model,Q),$="hook_event_name"in q?String(q.hook_event_name):"Unknown",X=this.buildPromptHookSystemMessage(O,$),W=JSON.stringify(q,null,2),J=new AbortController,G=setTimeout(()=>J.abort(),Z),L;try{L=(await Y.chat([{role:"system",content:X},{role:"user",content:W}],void 0,J.signal,{providerAdmission:{sessionId:Q.sessionId,ownerId:Q.sessionId,requestClass:"background"}})).content}catch(z){if(J.signal.aborted||z instanceof Error&&z.name==="AbortError")return this.outputParser.parse({stdout:"",stderr:"",exitCode:0,timedOut:!0},O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior});throw z}finally{clearTimeout(G)}let F=this.extractJsonFromLLMResponse(L);return this.outputParser.parse({stdout:F,stderr:"",exitCode:0,timedOut:!1},O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}catch(Y){return $O.warn(`[PromptHook] 执行失败: ${Y instanceof Error?Y.message:String(Y)}`),{success:!1,blocking:!1,error:Y instanceof Error?Y.message:String(Y),hook:O}}}async executeFunctionHook(O,q,Q){let Z=(O.timeout??10)*1000;try{let Y=await this.runFunctionWithTimeout(O.handler,q,Q,Z);if(Y===void 0||Y===null)return{success:!0,hook:O};let $={stdout:JSON.stringify(Y),stderr:"",exitCode:0,timedOut:!1};return this.outputParser.parse($,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}catch(Y){if(Y.isTimeout){let $={stdout:"",stderr:`Function hook timeout after ${Z}ms`,exitCode:124,timedOut:!0};return this.outputParser.parse($,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}return{success:!1,blocking:!1,error:Y instanceof Error?Y.message:String(Y),hook:O}}}runFunctionWithTimeout(O,q,Q,Z){return new Promise((Y,$)=>{let X=!1,W=setTimeout(()=>{if(X)return;X=!0;let G=Object.assign(Error(`Function hook timed out after ${Z}ms`),{isTimeout:!0});$(G)},Z),J=()=>{if(X)return;X=!0,clearTimeout(W),$(Error("Function hook aborted"))};Q.abortSignal?.addEventListener("abort",J,{once:!0}),Promise.resolve().then(()=>O(q,Q)).then((G)=>{if(X)return;X=!0,clearTimeout(W),Q.abortSignal?.removeEventListener("abort",J),Y(G)},(G)=>{if(X)return;X=!0,clearTimeout(W),Q.abortSignal?.removeEventListener("abort",J),$(G)})})}async executeHttpHook(O,q,Q){let Z=(O.timeout??10)*1000,Y=O.maxResponseBytes??262144,$=Math.max(1,(O.retries??0)+1);try{e(O.url,Q.config.httpPolicy)}catch(G){return{success:!1,blocking:!0,error:G instanceof Error?G.message:String(G),hook:O}}let X={"Content-Type":"application/json",...OO(O.headers)},W=JSON.stringify(q),J;for(let G=0;G<$;G++){if(G>0){let V=Math.min(2**G*200,5000);await new Promise((B)=>setTimeout(B,V))}let L=new AbortController,F=setTimeout(()=>L.abort(),Z),z=()=>L.abort();Q.abortSignal?.addEventListener("abort",z,{once:!0});try{let V=await fetch(O.url,{method:"POST",headers:X,body:W,redirect:"manual",signal:L.signal});if(V.status>=300&&V.status<400){J=Error(`HTTP hook received redirect (${V.status}); redirects are disabled`);continue}if(!V.ok){if(J=Error(`HTTP hook returned ${V.status} ${V.statusText}`),V.status>=400&&V.status<500)break;continue}let U={stdout:await HO(V,Y),stderr:"",exitCode:0,timedOut:!1};return this.outputParser.parse(U,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}catch(V){let B=V.name==="AbortError"||V.code==="ABORT_ERR";if(B&&Q.abortSignal?.aborted){J=Error("HTTP hook aborted by caller");break}if(B){let U={stdout:"",stderr:`HTTP hook timeout after ${Z}ms`,exitCode:124,timedOut:!0};if(G===$-1)return this.outputParser.parse(U,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior});J=Error(`HTTP hook timeout attempt ${G+1}`);continue}J=V}finally{clearTimeout(F),Q.abortSignal?.removeEventListener("abort",z)}}return{success:!1,blocking:!1,error:J?.message??"HTTP hook failed",hook:O}}async getOrCreateChatService(O,q){let Q=this.sessionResourceKey(q.sessionId,q.projectDir),Z=`${Q}\x00${O||"__default__"}`,Y=this.chatServiceCache.get(Z);if(Y)return Y;let{ensureStoreInitialized:$,getConfig:X}=await import("./chunk-v0znd20r.js"),{createChatServiceAsync:W}=await import("./chunk-ffkdx471.js"),{resolveModelConfig:J}=await import("./chunk-a6kbpq05.js"),{resolveWorkspaceModelResources:G}=await import("./chunk-0jmvv2vb.js");await $();let L=X();if(!L)throw Error("PromptHook: 配置未初始化");let F=this.sessionModelResources.get(Q)??await G(q.projectDir,L),z=O?F.config.models.find((B)=>B.id===O):F.config.models.find((B)=>B.id===F.config.currentModelId)??F.config.models[0];if(!z)throw Error("PromptHook: 无法获取模型配置。请确保至少配置了一个模型。");let V=await W(J(z,F.config,"off",F.catalog).chat);return this.chatServiceCache.set(Z,V),V}sessionResourceKey(O,q){return`${O}\x00${DO.resolve(q)}`}withSessionEnvironment(O){let q=this.sessionEnvironments.get(this.sessionResourceKey(O.sessionId,O.projectDir));return q?{...O,environment:q}:O}withHookEnvironment(O,q){let Q=this.withSessionEnvironment(O);if(!q.source)return Q;return{...Q,environment:{...Q.environment,BLADE_PLUGIN_ROOT:q.source.pluginRoot,CLAUDE_PLUGIN_ROOT:q.source.pluginRoot,BLADE_PLUGIN_NAME:q.source.pluginName}}}buildPromptHookSystemMessage(O,q){let Q=yO[q]||"{ ... 根据事件类型返回相应字段 }";return`你是一个代码质量评估器,作为 Hook 在 ${q} 事件中被触发。
|
|
29
29
|
|
|
30
30
|
`+`## 评估指令
|
|
31
31
|
${O.prompt}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a,b,c,d,e}from"./chunk-tnjq10zs.js";import"./chunk-c74e0jx1.js";import"./chunk-99nevk7k.js";export{b as setSkipUntilVersion,d as performUpgrade,c as getUpgradeCommand,e as checkVersionOnStartup,a as checkVersion};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Qc as a,Rc as b,Sc as c,Tc as d,Uc as e,Vc as f,Wc as g}from"./chunk-
|
|
1
|
+
import{Qc as a,Rc as b,Sc as c,Tc as d,Uc as e,Vc as f,Wc as g}from"./chunk-57jj40er.js";import"./chunk-qyxbee3w.js";import"./chunk-r297pq3s.js";import"./chunk-xbj18hxh.js";import"./chunk-0cbpjhq7.js";import"./chunk-03947xkg.js";import"./chunk-yjbq4jeg.js";import"./chunk-22aaybx2.js";import"./chunk-2qqmmxqf.js";import"./chunk-bj5msq36.js";import"./chunk-c74e0jx1.js";import"./chunk-qw5j84ny.js";import"./chunk-99nevk7k.js";export{b as __setSessionSnapshotIOForTesting,c as __resetSessionSnapshotIOForTesting,g as SessionService,d as SessionMissingCreationError,e as SessionArchivedError,f as SessionArchiveConflictError,a as STALE_EMPTY_SESSION_AGE_MS};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{Ub as dJ}from"./chunk-fbgzeb3m.js";import{Bc as i$,Lc as b0,Nc as R2,Oc as O1,Pc as C2,Vb as $$,Wc as R$,ac as s6,bc as t6,cc as q2,dc as O2,jc as e6,kc as cJ,lc as iJ,mc as j2,nc as F1,oc as lJ,pc as rJ,qc as U1,tc as k6}from"./chunk-1ykz47d9.js";import{$c as V0,cd as d6,dd as _0}from"./chunk-r297pq3s.js";import{ee as jJ}from"./chunk-xkz9ecdx.js";import{fe as gJ,ge as c0,he as hJ,ke as uJ,le as h2,ne as x6}from"./chunk-rjgfy07e.js";import{$e as mJ,Xe as l0,Ye as R0}from"./chunk-kaf6m50a.js";import{if as z$}from"./chunk-7kf3hwp3.js";import{sg as QJ}from"./chunk-qp8mejbn.js";import{Fg as J0}from"./chunk-22aaybx2.js";import{fh as y0}from"./chunk-2qqmmxqf.js";import{th as a6}from"./chunk-453tf6d0.js";import{Eh as j$,Gh as y6,Hh as D0,Ih as q1,Kh as n6,Mh as o6}from"./chunk-qw5j84ny.js";import{Nh as y5}from"./chunk-99nevk7k.js";function Q$($){return $.role==="system"&&Array.isArray($.content)}function X$($){if($.role!=="system"||!$.metadata||Array.isArray($.metadata))return!1;return typeof $.metadata==="object"&&$.metadata.contextualProjectRules===!0}class X1{systemMessages;_contextualSystemMessages;_history;_pending=[];context;constructor($,J){this.context=$;let Z=$.messages.find(Q$);if(this._contextualSystemMessages=$.messages.filter(X$),Z)this.systemMessages=[Z,...this._contextualSystemMessages];else if(J)this.systemMessages=[{role:"system",content:[{type:"text",text:J,providerOptions:{anthropic:{cacheControl:{type:"ephemeral"}}}}]},...this._contextualSystemMessages];else this.systemMessages=[...this._contextualSystemMessages];this._history=$.messages.filter((W)=>!Q$(W)&&!X$(W))}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($){this._pending.push($)}appendUser($){this._pending.push($)}appendAssistant($){this._pending.push($)}appendToolResult($){this._pending.push($)}appendContextualProjectInstructions($){if(!X$($))throw Error("Contextual project instructions require safe metadata");this._contextualSystemMessages.push($),this.systemMessages.push($)}syncContextualSystemMessages(){let $=this.systemMessages.filter(Q$);this.systemMessages.splice(0,this.systemMessages.length,...$,...this._contextualSystemMessages)}appendControl($,J){if($==="system")throw Error("Cannot append system control message via appendControl. Use constructor for root system prompt.");this._pending.push(J)}appendDurableControl($){if(!$.id||$.role!=="user")throw Error("Durable control messages require a user role and identity");if(this._history.some((J)=>J.id===$.id))return;this._history.push($)}appendToHistory($){this._history.push($)}commitPending(){if(this._pending.length>0)this._history.push(...this._pending),this._pending=[]}replaceHistory($){this._history=$.filter((J)=>!Q$(J)&&!X$(J))}restoreDurableHistory($){this._contextualSystemMessages=$.filter(X$),this._history=$.filter((J)=>!Q$(J)&&!X$(J)),this._pending=[],this.syncContextualSystemMessages()}removeMessages($){this._history=this._history.filter((J)=>!$(J)),this._pending=this._pending.filter((J)=>!$(J)),this._contextualSystemMessages=this._contextualSystemMessages.filter((J)=>!$(J)),this.syncContextualSystemMessages()}writeback(){this.commitPending(),this.context.messages=[...this._contextualSystemMessages,...this._history]}get hasSystemPrompt(){return this.systemMessages.length>0}}function Z6($){if($.isSubagent)return"continue";if(!$.budget||$.budget<=0)return"continue";if($.consecutiveContinuations>=3&&$.lastOutputDelta<500)return"stop";if($.usage/$.budget>=0.9)return"stop";return"continue"}function W6($){return{budget:$.budget,usage:0,consecutiveContinuations:0,lastOutputDelta:0,isSubagent:$.isSubagent??!1}}function Y6($,J,Z){return{...$,usage:$.usage+J,lastOutputDelta:J,consecutiveContinuations:Z?$.consecutiveContinuations+1:0}}import e0 from"node:path";var Z4=new Set(["GOEXPERIMENT","GOOS","GOARCH","CGO_ENABLED","GO111MODULE","RUST_BACKTRACE","RUST_LOG","NODE_ENV","PYTHONUNBUFFERED","PYTHONDONTWRITEBYTECODE","GIT_TERMINAL_PROMPT","LANG","LANGUAGE","LC_ALL","LC_CTYPE","LC_TIME","CHARSET","TERM","COLORTERM","NO_COLOR","FORCE_COLOR","TZ","LS_COLORS","LSCOLORS","GREP_COLOR","GREP_COLORS"]),W4=/^(LD_.+|DYLD_.+|PATH)$/,K6=/^([A-Za-z_][A-Za-z0-9_]*)=([\w./:@-]*)$/;function k$($){let J=$;while(!0){let Z=J.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!Z)break;let W=Z[1],Y=Z[2],K=W.match(K6);if(!K)break;let H=K[1];if(!Z4.has(H))break;J=Y}return J}function g8($){let J=$;while(!0){let Z=J.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!Z)break;let W=Z[1],Y=Z[2],K=W.match(K6);if(!K)break;let H=K[1];if(W4.test(H))break;J=Y}return J}var Y4=[/^timeout[ \t]+(?:--foreground[ \t]+|--preserve-status[ \t]+|-v[ \t]+|--verbose[ \t]+|-k[ \t]+\S+[ \t]+|--kill-after[= ]\S+[ \t]+|-s[ \t]+\S+[ \t]+|--signal[= ]\S+[ \t]+)*\S+[ \t]+/,/^time[ \t]+/,/^nice[ \t]+(?:-n[ \t]+\d+[ \t]+|-\d+[ \t]+)?/,/^nohup[ \t]+/];function a1($){let J=$,Z=!0;while(Z){Z=!1;for(let W of Y4){let Y=J.match(W);if(Y){J=J.slice(Y[0].length),Z=!0;break}}if(J.startsWith("-- "))J=J.slice(3),Z=!0}return J}function M$($){let J=[],Z="",W=!1,Y=!1,K=!1;for(let H=0;H<$.length;H++){let X=$[H];if(K){Z+=X,K=!1;continue}if(X==="\\"&&!W){Z+=X,K=!0;continue}if(X==="'"&&!Y){W=!W,Z+=X;continue}if(X==='"'&&!W){Y=!Y,Z+=X;continue}if(W||Y){Z+=X;continue}if(X==="|"){if(H+1<$.length&&$[H+1]==="|"){if(Z.trim())J.push(Z.trim());Z="",H++;continue}return null}if(X===">"||X==="<")return null;if(X==="&"&&H+1<$.length&&$[H+1]==="&"){if(Z.trim())J.push(Z.trim());Z="",H++;continue}if(X==="&")return null;if(X===";"){if(Z.trim())J.push(Z.trim());Z="";continue}Z+=X}if(Z.trim())J.push(Z.trim());return J.length>0?J:null}function H6($){let J=!1,Z=!1,W=!1;for(let Y=0;Y<$.length;Y++){let K=$[Y];if(W){W=!1;continue}if(K==="\\"&&!J){W=!0;continue}if(K==="'"&&!Z){J=!J;continue}if(K==='"'&&!J){Z=!Z;continue}if(J)continue;if(K==="$"){let H=$[Y+1];if(H&&/[A-Za-z_@*#?!$0-9({]/.test(H))return!0}if(K==="`")return!0;if(Z)continue;if(K==="|")return!0;if(K===">"||K==="<")return!0;if(K==="{"){let H=$.slice(Y);if(/^\{[^}]*,[^}]*\}/.test(H)||/^\{[^}]*\.\.[^}]*\}/.test(H))return!0}}return!1}function t0($){let J=[],Z="",W=!1,Y=!1,K=!1;for(let H=0;H<$.length;H++){let X=$[H];if(K){Z+=X,K=!1;continue}if(X==="\\"&&!W){if(K=!0,Y){let Q=$[H+1];if(Q&&'$`"\\'.includes(Q))continue;Z+=X,K=!1}continue}if(X==="'"&&!Y){W=!W;continue}if(X==='"'&&!W){Y=!Y;continue}if(!W&&!Y&&/[ \t]/.test(X)){if(Z)J.push(Z),Z="";continue}Z+=X}if(Z)J.push(Z);return J}var K4=new Set(["npm","pnpm","yarn","bun"]),X6=new Set(["biome","eslint","jest","mypy","pyright","pytest","ruff","tsc","vitest"]),H4=new Set(["-u","--fix","--update","--update-snapshot","--updateSnapshot","--watch","--watchAll","--write"]),X4=/[ \t]*;[ \t]*echo[ \t]+"[A-Za-z0-9 _:=.-]*(?:\$\{PIPESTATUS\[0\]\}|\$\?)[A-Za-z0-9 _:=.-]*"[ \t]*$/;function Q4($){return $!==void 0&&/^(?:test|lint|build|type-?check)(?::[\w.-]+)*$/i.test($)}function Q6($){return $.replace(/\s+2>&1\s*$/,"").trim()}function V4($,J,Z){if(!Z||J.length!==2)return;let W=/^(.+?)[ \t]+&&[ \t]+([\s\S]+)$/.exec($);if(!W)return;let Y=t0(W[1]??"");if(Y.length!==2||Y[0]!=="cd")return;let K=Y[1];if(!K||K==="-")return;let H=e0.isAbsolute(K)?e0.resolve(K):e0.resolve(Z,K);if(!$$.isWithinWorkspace(H,Z))return;return W[2]?.trim()||void 0}function z4($){let J=[],Z=!1,W=!1,Y=!1;for(let K=0;K<$.length;K++){let H=$[K];if(Y){Y=!1;continue}if(H==="\\"&&!Z){Y=!0;continue}if(H==="'"&&!W){Z=!Z;continue}if(H==='"'&&!Z){W=!W;continue}if(H!=="|"||Z||W)continue;if($[K+1]==="|")return;J.push(K)}return J}function B4($){let J=t0($),[Z,W,Y]=J;if(Z!=="head"&&Z!=="tail")return!1;if(J.length===1)return!0;let K=(H)=>H!==void 0&&/^[1-9]\d{0,4}$/.test(H);if(J.length===2)return W?.startsWith("--lines=")&&K(W.slice(8))||W?.startsWith("-")&&K(W.slice(1));return J.length===3&&(W==="-n"||W==="--lines")&&K(Y)}function D4($){let J=Q6($.replace(X4,"").trim()),Z=z4(J);if(!Z)return;if(Z.length===0)return V6(J);if(Z.length!==1)return;let W=Z[0];if(W===void 0)return;let Y=Q6(J.slice(0,W).trim()),K=J.slice(W+1).trim();if(!Y||!B4(K))return;return V6(Y)}function V6($){let Z=M$($)?.at(-1);if(!Z)return $;let W=t0(Z),[Y,K]=W;if(!(Y==="vitest"||(Y==="npx"||Y==="bunx")&&K==="vitest")||W.some((X)=>X==="--configLoader"||X.startsWith("--configLoader=")))return $;return`${$} --configLoader runner`}function V$($,J){let Z=D4($);if(!Z)return!1;let W=k$(Z),Y=M$(W);if(!Y||H6(W)||/[\r\n]/.test(W))return!1;let K=Y.length===1?Y[0]:V4(W,Y,J);if(!K)return!1;let H=t0(K);if(H.length===0||H.some((D)=>[...H4].some((w)=>D===w||D.startsWith(`${w}=`))))return!1;let[X,Q,V]=H;if(K4.has(X??""))return Q4(Q==="run"?V:Q)||Q==="--test";if((X==="npx"||X==="bunx")&&X6.has(Q??""))return!0;if(X6.has(X??""))return!0;if(X==="node"&&Q==="--test")return!0;if(X==="go"&&["build","test","vet"].includes(Q??""))return!0;return X==="cargo"&&["build","check","clippy","test"].includes(Q??"")}function i8($,J){if($===void 0)return!0;if(typeof $!=="string"||$.split(/[\\/]/).includes(".."))return!1;if(!J)return!e0.isAbsolute($);let Z=e0.isAbsolute($)?e0.resolve($):e0.resolve(J,$);return $$.isWithinWorkspace(Z,J)}var s1=y0("Agent"),j4=3;function t1($,J,Z){if($!=="length")return{action:"none"};if(J>=j4)return{action:"truncated"};if(Z6(Z)==="stop")return s1.info("[Loop] Token budget: diminishing returns detected, skipping recovery"),{action:"budget_stop"};return{action:"recover"}}var w4=[/:\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],U4=/```[\s\S]{50,}```/,z6="请执行你提到的操作,不要只是描述。使用 Edit/Write/ApplyPatch/Bash 工具来实际修改文件。",L4=2;function e1($,J,Z=!0){if(!$||J>=L4)return{action:"none"};if(!Z&&U4.test($))return{action:"retry",prompt:z6};let W=$.slice(-200),Y=W.match(/```/g);if(Y&&Y.length%2!==0)return{action:"none"};if(w4.some((H)=>H.test(W)))return{action:"retry",prompt:z6};return{action:"none"}}var G4=[/\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}(?:测试|单测|集成测试|检查|构建)/],B6={test:/\b(?:tests?|test suite)\b|(?:测试|单测|集成测试)/i,lint:/\blint(?:ing)?\b/i,"type-check":/\btype[\s-]?check(?:ing)?\b|\btsc\b|类型检查/i,build:/\bbuild\b|构建/i},q4={test:/(?:^|\s)(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?test\b|(?:^|\s)(?:node|bun)\s+--test\b|(?:^|\s)(?:vitest|jest|pytest|go\s+test|cargo\s+test)\b/i,lint:/(?:^|\s)(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?lint\b/i,"type-check":/(?:^|\s)(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?type-?check\b|(?:^|\s)tsc\b/i,build:/(?:^|\s)(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?build\b/i},O4="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.",N4="Required verification did not run successfully before the retry limit.",F4=3;function j6($,J,Z,W){if(!Z.success)return;if(["Edit","Write","ApplyPatch","NotebookEdit"].includes(J)){$.clear();return}if(J==="Bash"&&typeof Z.metadata?.command==="string"&&Z.metadata.exit_code===0&&V$(Z.metadata.command,W)){$.add(Z.metadata.command);return}if(!["Task","TaskOutput"].includes(J))return;let Y=Z.metadata?.verificationCommands;if(!Array.isArray(Y))return;for(let K of Y)if(typeof K==="string"&&V$(K,W))$.add(K)}function $2($,J,Z){if(!$||!G4.some((Q)=>Q.test($)))return{action:"none"};let W=Object.keys(B6).filter((Q)=>B6[Q].test($)),Y=[...J],K=W.filter((Q)=>!Y.some((V)=>q4[Q].test(V)));if(W.length>0?K.length===0:Y.some((Q)=>V$(Q)))return{action:"none"};if(Z>=F4)return{action:"fail",message:N4};let X=W.length>1&&K.length>0?` Missing successful verification categories: ${K.join(", ")}.`:"";return{action:"retry",prompt:`${O4}${X}`}}var y4=[/\bdelegate\b[\s\S]{0,120}\b(?:Task tool|subagent|agent)\b/i,/\b(?:call|use|invoke)\b[\s\S]{0,80}\bTask tool\b/i,/(?:委派|交给|调用|使用).{0,60}(?:Task|子代理|子智能体)/],w6=[/\b(?:do not|don't|never)\s+(?:delegate|call|use|invoke)\b/i,/(?:不要|禁止|无需)(?:委派|调用|使用).{0,20}(?:Task|子代理|子智能体)?/];function U6($){return typeof $==="string"&&w6.some((J)=>J.test($))}var P4=[/\b(?:call|use|invoke)\b[\s\S]{0,30}\bTask(?: tool)?\b[\s\S]{0,30}\bexactly once\b/i,/\bexactly once\b[\s\S]{0,30}\b(?:call|use|invoke)\b[\s\S]{0,30}\bTask(?: tool)?\b/i,/\bexactly one\b[\s\S]{0,30}\bTask(?: tool)? calls?\b/i,/(?:Task|子代理).{0,20}(?:恰好|仅|只)(?:调用|使用)?一次/,/(?:恰好|仅|只)(?:调用|使用)?一次.{0,20}(?:Task|子代理)/],_4=[/\b(?:do not|don't|never)\s+(?:call|use|invoke)\s+(?:the\s+)?Task\b[\s\S]{0,30}\bexactly once\b/i,/\bTask\b[\s\S]{0,30}\b(?:does not|doesn't|need not)\b[\s\S]{0,30}\bexactly once\b/i,/\bmultiple\s+Task(?: tool)?\s+calls?\s+(?:are\s+)?allowed\b/i,/(?:不要|禁止).{0,12}(?:Task|子代理).{0,12}(?:恰好|仅|只)(?:调用|使用)?一次/];function A4($){if(typeof $!=="string")return;if(_4.some((J)=>J.test($)))return"multiple-allowed";return P4.some((J)=>J.test($))?"required":void 0}function V1($){for(let J of $){let Z=A4(J);if(Z!==void 0)return Z==="required"}return!1}var f4="The user explicitly required delegation, but no Task tool call completed successfully. Do not solve the task directly or explain. Your next action must be a Task tool call using the requested subagent.",b4="Required delegation did not complete before the retry limit.",T4=3;function L6($,J,Z){let W=(typeof $==="string"?[$]:$??[]).map((H)=>H.trim()).filter(Boolean),Y=V1(W),K=!1;if(!Y)for(let H of W){if(w6.some((X)=>X.test(H)))break;if(y4.some((X)=>X.test(H))){K=!0;break}}if(W.length===0||!Y&&!K||J.has("Task"))return{action:"none"};if(Z>=T4)return{action:"fail",message:b4};return{action:"retry",prompt:f4}}var E4=[/\b(?:use|create|enter|start|work\s+(?:in|inside))\b.{0,60}\bworktree\b/i,/(?:使用|创建|进入).{0,30}(?:worktree|工作树)/i],S4=[/\b(?:exit|leave)\b.{0,40}\bworktree\b/i,/\bworktree\b.{0,60}\b(?:action\s+)?(?:keep|remove)\b/i,/(?:退出|离开).{0,30}(?:worktree|工作树)/i],x4=[/\b(?:do not|don't|never|must not|should not)\b[^.!?;\n]{0,80}\b(?:git\s+)?worktree\b/gi,/\bwithout\b[^.!?;\n]{0,60}\b(?:git\s+)?worktree\b/gi,/(?:不要|禁止|不得|无需)[^。!?;\n]{0,50}(?:worktree|工作树)/gi];function G6($){return x4.reduce((J,Z)=>J.replace(Z," "),$)}function z1($){if(typeof $!=="string")return!1;let J=G6($);return E4.some((Z)=>Z.test(J))}var k4="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.",M4="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.",h4="Required worktree lifecycle did not complete before the retry limit.",R4=3;function q6($,J,Z){if(!$)return{action:"none"};let W=G6($);if(!z1(W))return{action:"none"};let Y=S4.some((H)=>H.test(W));if(J.has("TaskWorktree"))return{action:"none"};let K=!J.has("EnterWorktree")?"EnterWorktree":Y&&!J.has("ExitWorktree")?"ExitWorktree":void 0;if(!K)return{action:"none"};if(Z>=R4)return{action:"fail",message:h4};return{action:"retry",tool:K,prompt:K==="EnterWorktree"?k4:M4}}var D6=30000;async function J2($){try{let Z=z$.getInstance().executeStopHooks({projectDir:$.workspaceRoot??J0(),sessionId:$.sessionId,permissionMode:$.permissionMode,reason:$.reason,abortSignal:$.abortSignal}),W,Y=new Promise((K)=>{W=setTimeout(()=>K("timeout"),D6)});try{let K=await Promise.race([Z,Y]);if(K==="timeout")return s1.warn(`[Loop] Stop hook 超时 (${D6}ms),按 shouldStop: true 处理`),{action:"stop"};let H=K;if(!H.shouldStop)return{action:"continue",reason:H.continueReason};return{action:"stop"}}finally{clearTimeout(W)}}catch(J){return s1.warn("[Loop] Stop hook execution failed:",J),{action:"stop"}}}async function C4($,J){let Z;while(!(Z=await $.next()).done)if(J)await J(Z.value);return Z.value}var I4=[/<system-reminder>[\s\S]*?<\/system-reminder>/gi,/<file[^>]*>[\s\S]*?<\/file>/gi,/<hooks_context>[\s\S]*?<\/hooks_context>/gi,/<[^>]+>/g];function v4($){if(typeof $==="string")return $;if(Array.isArray($))return $.map((J)=>{if(typeof J==="string")return J;if(J&&typeof J==="object"&&"text"in J){let Z=J.text;return typeof Z==="string"?Z:""}return""}).join(" ");return""}function p4($){let J=$;for(let Q of I4)J=J.replace(Q," ");J=J.replace(/^\s*\/[a-zA-Z][\w-]*\s+/,"");let Z=J.replace(/\s+/g," ").trim();if(!Z)return"";let W=Z.match(/^(.+?)(?:[.!?]\s|[。!?](?=\S|$)|$)/),Y=W&&W[1].length>=6?W[1]:Z;if(Y=Y.trim().replace(/[\s.。!!??,,;;::-]+$/,""),Y.length<=60)return Y;let K=Y.slice(0,60),H=K.lastIndexOf(" ");return`${(H>36?K.slice(0,H):K).trimEnd()}…`}function O6($){return p4(v4($))}import{EventEmitter as g4}from"events";import N6 from"node:path";function Z2($){if(y6($.sessionId),!N6.isAbsolute($.projectPath))throw Error("projectPath must be absolute");return{sessionId:$.sessionId,projectPath:N6.resolve($.projectPath)}}function F6($){let J=Z2($);return JSON.stringify([J.projectPath,J.sessionId])}function WZ($,J){return F6($)===F6(J)}class B$ extends g4{static instance;constructor(){super();this.setMaxListeners(100)}static getInstance(){if(!B$.instance)B$.instance=new B$;return B$.instance}publish($,J,Z,W){let Y=Z2($);this.emit("event",{sessionId:Y.sessionId,projectPath:Y.projectPath,type:J,...W!==void 0?{seq:W}:{},properties:Z})}subscribe($){return this.on("event",$),()=>this.off("event",$)}}var h$=B$.getInstance();var u0=y0("Agent"),B1=new Set;async function u4($,J){let Z=$.sessionId;if(!Z||$.subagentInfo)return;if(B1.has(Z))return;if(B1.size>=5000)B1.clear();B1.add(Z);try{let W=$.workspaceRoot,Y=await R$.findSessionMetadata(Z,W);if(!Y)return;if(Y.title&&Y.title.trim())return;let K=O6(J);if(!K)return;await R$.updateSessionMetadata(Z,Y.projectPath,{title:K}),h$.publish({sessionId:Z,projectPath:Y.projectPath},"session.updated",{title:K})}catch(W){u0.debug?.("[Loop] 自动生成会话标题失败:",W)}}var W2=`<turn_aborted>
|
|
1
|
+
import{Ub as dJ}from"./chunk-fbgzeb3m.js";import{Bc as i$,Lc as b0,Nc as R2,Oc as O1,Pc as C2,Vb as $$,Wc as R$,ac as s6,bc as t6,cc as q2,dc as O2,jc as e6,kc as cJ,lc as iJ,mc as j2,nc as F1,oc as lJ,pc as rJ,qc as U1,tc as k6}from"./chunk-57jj40er.js";import{$c as V0,cd as d6,dd as _0}from"./chunk-r297pq3s.js";import{ee as jJ}from"./chunk-xkz9ecdx.js";import{fe as gJ,ge as c0,he as hJ,ke as uJ,le as h2,ne as x6}from"./chunk-rjgfy07e.js";import{$e as mJ,Xe as l0,Ye as R0}from"./chunk-kaf6m50a.js";import{if as z$}from"./chunk-egp0crrc.js";import{sg as QJ}from"./chunk-qp8mejbn.js";import{Fg as J0}from"./chunk-22aaybx2.js";import{fh as y0}from"./chunk-2qqmmxqf.js";import{th as a6}from"./chunk-c74e0jx1.js";import{Eh as j$,Gh as y6,Hh as D0,Ih as q1,Kh as n6,Mh as o6}from"./chunk-qw5j84ny.js";import{Nh as y5}from"./chunk-99nevk7k.js";function Q$($){return $.role==="system"&&Array.isArray($.content)}function X$($){if($.role!=="system"||!$.metadata||Array.isArray($.metadata))return!1;return typeof $.metadata==="object"&&$.metadata.contextualProjectRules===!0}class X1{systemMessages;_contextualSystemMessages;_history;_pending=[];context;constructor($,J){this.context=$;let Z=$.messages.find(Q$);if(this._contextualSystemMessages=$.messages.filter(X$),Z)this.systemMessages=[Z,...this._contextualSystemMessages];else if(J)this.systemMessages=[{role:"system",content:[{type:"text",text:J,providerOptions:{anthropic:{cacheControl:{type:"ephemeral"}}}}]},...this._contextualSystemMessages];else this.systemMessages=[...this._contextualSystemMessages];this._history=$.messages.filter((W)=>!Q$(W)&&!X$(W))}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($){this._pending.push($)}appendUser($){this._pending.push($)}appendAssistant($){this._pending.push($)}appendToolResult($){this._pending.push($)}appendContextualProjectInstructions($){if(!X$($))throw Error("Contextual project instructions require safe metadata");this._contextualSystemMessages.push($),this.systemMessages.push($)}syncContextualSystemMessages(){let $=this.systemMessages.filter(Q$);this.systemMessages.splice(0,this.systemMessages.length,...$,...this._contextualSystemMessages)}appendControl($,J){if($==="system")throw Error("Cannot append system control message via appendControl. Use constructor for root system prompt.");this._pending.push(J)}appendDurableControl($){if(!$.id||$.role!=="user")throw Error("Durable control messages require a user role and identity");if(this._history.some((J)=>J.id===$.id))return;this._history.push($)}appendToHistory($){this._history.push($)}commitPending(){if(this._pending.length>0)this._history.push(...this._pending),this._pending=[]}replaceHistory($){this._history=$.filter((J)=>!Q$(J)&&!X$(J))}restoreDurableHistory($){this._contextualSystemMessages=$.filter(X$),this._history=$.filter((J)=>!Q$(J)&&!X$(J)),this._pending=[],this.syncContextualSystemMessages()}removeMessages($){this._history=this._history.filter((J)=>!$(J)),this._pending=this._pending.filter((J)=>!$(J)),this._contextualSystemMessages=this._contextualSystemMessages.filter((J)=>!$(J)),this.syncContextualSystemMessages()}writeback(){this.commitPending(),this.context.messages=[...this._contextualSystemMessages,...this._history]}get hasSystemPrompt(){return this.systemMessages.length>0}}function Z6($){if($.isSubagent)return"continue";if(!$.budget||$.budget<=0)return"continue";if($.consecutiveContinuations>=3&&$.lastOutputDelta<500)return"stop";if($.usage/$.budget>=0.9)return"stop";return"continue"}function W6($){return{budget:$.budget,usage:0,consecutiveContinuations:0,lastOutputDelta:0,isSubagent:$.isSubagent??!1}}function Y6($,J,Z){return{...$,usage:$.usage+J,lastOutputDelta:J,consecutiveContinuations:Z?$.consecutiveContinuations+1:0}}import e0 from"node:path";var Z4=new Set(["GOEXPERIMENT","GOOS","GOARCH","CGO_ENABLED","GO111MODULE","RUST_BACKTRACE","RUST_LOG","NODE_ENV","PYTHONUNBUFFERED","PYTHONDONTWRITEBYTECODE","GIT_TERMINAL_PROMPT","LANG","LANGUAGE","LC_ALL","LC_CTYPE","LC_TIME","CHARSET","TERM","COLORTERM","NO_COLOR","FORCE_COLOR","TZ","LS_COLORS","LSCOLORS","GREP_COLOR","GREP_COLORS"]),W4=/^(LD_.+|DYLD_.+|PATH)$/,K6=/^([A-Za-z_][A-Za-z0-9_]*)=([\w./:@-]*)$/;function k$($){let J=$;while(!0){let Z=J.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!Z)break;let W=Z[1],Y=Z[2],K=W.match(K6);if(!K)break;let H=K[1];if(!Z4.has(H))break;J=Y}return J}function g8($){let J=$;while(!0){let Z=J.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!Z)break;let W=Z[1],Y=Z[2],K=W.match(K6);if(!K)break;let H=K[1];if(W4.test(H))break;J=Y}return J}var Y4=[/^timeout[ \t]+(?:--foreground[ \t]+|--preserve-status[ \t]+|-v[ \t]+|--verbose[ \t]+|-k[ \t]+\S+[ \t]+|--kill-after[= ]\S+[ \t]+|-s[ \t]+\S+[ \t]+|--signal[= ]\S+[ \t]+)*\S+[ \t]+/,/^time[ \t]+/,/^nice[ \t]+(?:-n[ \t]+\d+[ \t]+|-\d+[ \t]+)?/,/^nohup[ \t]+/];function a1($){let J=$,Z=!0;while(Z){Z=!1;for(let W of Y4){let Y=J.match(W);if(Y){J=J.slice(Y[0].length),Z=!0;break}}if(J.startsWith("-- "))J=J.slice(3),Z=!0}return J}function M$($){let J=[],Z="",W=!1,Y=!1,K=!1;for(let H=0;H<$.length;H++){let X=$[H];if(K){Z+=X,K=!1;continue}if(X==="\\"&&!W){Z+=X,K=!0;continue}if(X==="'"&&!Y){W=!W,Z+=X;continue}if(X==='"'&&!W){Y=!Y,Z+=X;continue}if(W||Y){Z+=X;continue}if(X==="|"){if(H+1<$.length&&$[H+1]==="|"){if(Z.trim())J.push(Z.trim());Z="",H++;continue}return null}if(X===">"||X==="<")return null;if(X==="&"&&H+1<$.length&&$[H+1]==="&"){if(Z.trim())J.push(Z.trim());Z="",H++;continue}if(X==="&")return null;if(X===";"){if(Z.trim())J.push(Z.trim());Z="";continue}Z+=X}if(Z.trim())J.push(Z.trim());return J.length>0?J:null}function H6($){let J=!1,Z=!1,W=!1;for(let Y=0;Y<$.length;Y++){let K=$[Y];if(W){W=!1;continue}if(K==="\\"&&!J){W=!0;continue}if(K==="'"&&!Z){J=!J;continue}if(K==='"'&&!J){Z=!Z;continue}if(J)continue;if(K==="$"){let H=$[Y+1];if(H&&/[A-Za-z_@*#?!$0-9({]/.test(H))return!0}if(K==="`")return!0;if(Z)continue;if(K==="|")return!0;if(K===">"||K==="<")return!0;if(K==="{"){let H=$.slice(Y);if(/^\{[^}]*,[^}]*\}/.test(H)||/^\{[^}]*\.\.[^}]*\}/.test(H))return!0}}return!1}function t0($){let J=[],Z="",W=!1,Y=!1,K=!1;for(let H=0;H<$.length;H++){let X=$[H];if(K){Z+=X,K=!1;continue}if(X==="\\"&&!W){if(K=!0,Y){let Q=$[H+1];if(Q&&'$`"\\'.includes(Q))continue;Z+=X,K=!1}continue}if(X==="'"&&!Y){W=!W;continue}if(X==='"'&&!W){Y=!Y;continue}if(!W&&!Y&&/[ \t]/.test(X)){if(Z)J.push(Z),Z="";continue}Z+=X}if(Z)J.push(Z);return J}var K4=new Set(["npm","pnpm","yarn","bun"]),X6=new Set(["biome","eslint","jest","mypy","pyright","pytest","ruff","tsc","vitest"]),H4=new Set(["-u","--fix","--update","--update-snapshot","--updateSnapshot","--watch","--watchAll","--write"]),X4=/[ \t]*;[ \t]*echo[ \t]+"[A-Za-z0-9 _:=.-]*(?:\$\{PIPESTATUS\[0\]\}|\$\?)[A-Za-z0-9 _:=.-]*"[ \t]*$/;function Q4($){return $!==void 0&&/^(?:test|lint|build|type-?check)(?::[\w.-]+)*$/i.test($)}function Q6($){return $.replace(/\s+2>&1\s*$/,"").trim()}function V4($,J,Z){if(!Z||J.length!==2)return;let W=/^(.+?)[ \t]+&&[ \t]+([\s\S]+)$/.exec($);if(!W)return;let Y=t0(W[1]??"");if(Y.length!==2||Y[0]!=="cd")return;let K=Y[1];if(!K||K==="-")return;let H=e0.isAbsolute(K)?e0.resolve(K):e0.resolve(Z,K);if(!$$.isWithinWorkspace(H,Z))return;return W[2]?.trim()||void 0}function z4($){let J=[],Z=!1,W=!1,Y=!1;for(let K=0;K<$.length;K++){let H=$[K];if(Y){Y=!1;continue}if(H==="\\"&&!Z){Y=!0;continue}if(H==="'"&&!W){Z=!Z;continue}if(H==='"'&&!Z){W=!W;continue}if(H!=="|"||Z||W)continue;if($[K+1]==="|")return;J.push(K)}return J}function B4($){let J=t0($),[Z,W,Y]=J;if(Z!=="head"&&Z!=="tail")return!1;if(J.length===1)return!0;let K=(H)=>H!==void 0&&/^[1-9]\d{0,4}$/.test(H);if(J.length===2)return W?.startsWith("--lines=")&&K(W.slice(8))||W?.startsWith("-")&&K(W.slice(1));return J.length===3&&(W==="-n"||W==="--lines")&&K(Y)}function D4($){let J=Q6($.replace(X4,"").trim()),Z=z4(J);if(!Z)return;if(Z.length===0)return V6(J);if(Z.length!==1)return;let W=Z[0];if(W===void 0)return;let Y=Q6(J.slice(0,W).trim()),K=J.slice(W+1).trim();if(!Y||!B4(K))return;return V6(Y)}function V6($){let Z=M$($)?.at(-1);if(!Z)return $;let W=t0(Z),[Y,K]=W;if(!(Y==="vitest"||(Y==="npx"||Y==="bunx")&&K==="vitest")||W.some((X)=>X==="--configLoader"||X.startsWith("--configLoader=")))return $;return`${$} --configLoader runner`}function V$($,J){let Z=D4($);if(!Z)return!1;let W=k$(Z),Y=M$(W);if(!Y||H6(W)||/[\r\n]/.test(W))return!1;let K=Y.length===1?Y[0]:V4(W,Y,J);if(!K)return!1;let H=t0(K);if(H.length===0||H.some((D)=>[...H4].some((w)=>D===w||D.startsWith(`${w}=`))))return!1;let[X,Q,V]=H;if(K4.has(X??""))return Q4(Q==="run"?V:Q)||Q==="--test";if((X==="npx"||X==="bunx")&&X6.has(Q??""))return!0;if(X6.has(X??""))return!0;if(X==="node"&&Q==="--test")return!0;if(X==="go"&&["build","test","vet"].includes(Q??""))return!0;return X==="cargo"&&["build","check","clippy","test"].includes(Q??"")}function i8($,J){if($===void 0)return!0;if(typeof $!=="string"||$.split(/[\\/]/).includes(".."))return!1;if(!J)return!e0.isAbsolute($);let Z=e0.isAbsolute($)?e0.resolve($):e0.resolve(J,$);return $$.isWithinWorkspace(Z,J)}var s1=y0("Agent"),j4=3;function t1($,J,Z){if($!=="length")return{action:"none"};if(J>=j4)return{action:"truncated"};if(Z6(Z)==="stop")return s1.info("[Loop] Token budget: diminishing returns detected, skipping recovery"),{action:"budget_stop"};return{action:"recover"}}var w4=[/:\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],U4=/```[\s\S]{50,}```/,z6="请执行你提到的操作,不要只是描述。使用 Edit/Write/ApplyPatch/Bash 工具来实际修改文件。",L4=2;function e1($,J,Z=!0){if(!$||J>=L4)return{action:"none"};if(!Z&&U4.test($))return{action:"retry",prompt:z6};let W=$.slice(-200),Y=W.match(/```/g);if(Y&&Y.length%2!==0)return{action:"none"};if(w4.some((H)=>H.test(W)))return{action:"retry",prompt:z6};return{action:"none"}}var G4=[/\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}(?:测试|单测|集成测试|检查|构建)/],B6={test:/\b(?:tests?|test suite)\b|(?:测试|单测|集成测试)/i,lint:/\blint(?:ing)?\b/i,"type-check":/\btype[\s-]?check(?:ing)?\b|\btsc\b|类型检查/i,build:/\bbuild\b|构建/i},q4={test:/(?:^|\s)(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?test\b|(?:^|\s)(?:node|bun)\s+--test\b|(?:^|\s)(?:vitest|jest|pytest|go\s+test|cargo\s+test)\b/i,lint:/(?:^|\s)(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?lint\b/i,"type-check":/(?:^|\s)(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?type-?check\b|(?:^|\s)tsc\b/i,build:/(?:^|\s)(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?build\b/i},O4="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.",N4="Required verification did not run successfully before the retry limit.",F4=3;function j6($,J,Z,W){if(!Z.success)return;if(["Edit","Write","ApplyPatch","NotebookEdit"].includes(J)){$.clear();return}if(J==="Bash"&&typeof Z.metadata?.command==="string"&&Z.metadata.exit_code===0&&V$(Z.metadata.command,W)){$.add(Z.metadata.command);return}if(!["Task","TaskOutput"].includes(J))return;let Y=Z.metadata?.verificationCommands;if(!Array.isArray(Y))return;for(let K of Y)if(typeof K==="string"&&V$(K,W))$.add(K)}function $2($,J,Z){if(!$||!G4.some((Q)=>Q.test($)))return{action:"none"};let W=Object.keys(B6).filter((Q)=>B6[Q].test($)),Y=[...J],K=W.filter((Q)=>!Y.some((V)=>q4[Q].test(V)));if(W.length>0?K.length===0:Y.some((Q)=>V$(Q)))return{action:"none"};if(Z>=F4)return{action:"fail",message:N4};let X=W.length>1&&K.length>0?` Missing successful verification categories: ${K.join(", ")}.`:"";return{action:"retry",prompt:`${O4}${X}`}}var y4=[/\bdelegate\b[\s\S]{0,120}\b(?:Task tool|subagent|agent)\b/i,/\b(?:call|use|invoke)\b[\s\S]{0,80}\bTask tool\b/i,/(?:委派|交给|调用|使用).{0,60}(?:Task|子代理|子智能体)/],w6=[/\b(?:do not|don't|never)\s+(?:delegate|call|use|invoke)\b/i,/(?:不要|禁止|无需)(?:委派|调用|使用).{0,20}(?:Task|子代理|子智能体)?/];function U6($){return typeof $==="string"&&w6.some((J)=>J.test($))}var P4=[/\b(?:call|use|invoke)\b[\s\S]{0,30}\bTask(?: tool)?\b[\s\S]{0,30}\bexactly once\b/i,/\bexactly once\b[\s\S]{0,30}\b(?:call|use|invoke)\b[\s\S]{0,30}\bTask(?: tool)?\b/i,/\bexactly one\b[\s\S]{0,30}\bTask(?: tool)? calls?\b/i,/(?:Task|子代理).{0,20}(?:恰好|仅|只)(?:调用|使用)?一次/,/(?:恰好|仅|只)(?:调用|使用)?一次.{0,20}(?:Task|子代理)/],_4=[/\b(?:do not|don't|never)\s+(?:call|use|invoke)\s+(?:the\s+)?Task\b[\s\S]{0,30}\bexactly once\b/i,/\bTask\b[\s\S]{0,30}\b(?:does not|doesn't|need not)\b[\s\S]{0,30}\bexactly once\b/i,/\bmultiple\s+Task(?: tool)?\s+calls?\s+(?:are\s+)?allowed\b/i,/(?:不要|禁止).{0,12}(?:Task|子代理).{0,12}(?:恰好|仅|只)(?:调用|使用)?一次/];function A4($){if(typeof $!=="string")return;if(_4.some((J)=>J.test($)))return"multiple-allowed";return P4.some((J)=>J.test($))?"required":void 0}function V1($){for(let J of $){let Z=A4(J);if(Z!==void 0)return Z==="required"}return!1}var f4="The user explicitly required delegation, but no Task tool call completed successfully. Do not solve the task directly or explain. Your next action must be a Task tool call using the requested subagent.",b4="Required delegation did not complete before the retry limit.",T4=3;function L6($,J,Z){let W=(typeof $==="string"?[$]:$??[]).map((H)=>H.trim()).filter(Boolean),Y=V1(W),K=!1;if(!Y)for(let H of W){if(w6.some((X)=>X.test(H)))break;if(y4.some((X)=>X.test(H))){K=!0;break}}if(W.length===0||!Y&&!K||J.has("Task"))return{action:"none"};if(Z>=T4)return{action:"fail",message:b4};return{action:"retry",prompt:f4}}var E4=[/\b(?:use|create|enter|start|work\s+(?:in|inside))\b.{0,60}\bworktree\b/i,/(?:使用|创建|进入).{0,30}(?:worktree|工作树)/i],S4=[/\b(?:exit|leave)\b.{0,40}\bworktree\b/i,/\bworktree\b.{0,60}\b(?:action\s+)?(?:keep|remove)\b/i,/(?:退出|离开).{0,30}(?:worktree|工作树)/i],x4=[/\b(?:do not|don't|never|must not|should not)\b[^.!?;\n]{0,80}\b(?:git\s+)?worktree\b/gi,/\bwithout\b[^.!?;\n]{0,60}\b(?:git\s+)?worktree\b/gi,/(?:不要|禁止|不得|无需)[^。!?;\n]{0,50}(?:worktree|工作树)/gi];function G6($){return x4.reduce((J,Z)=>J.replace(Z," "),$)}function z1($){if(typeof $!=="string")return!1;let J=G6($);return E4.some((Z)=>Z.test(J))}var k4="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.",M4="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.",h4="Required worktree lifecycle did not complete before the retry limit.",R4=3;function q6($,J,Z){if(!$)return{action:"none"};let W=G6($);if(!z1(W))return{action:"none"};let Y=S4.some((H)=>H.test(W));if(J.has("TaskWorktree"))return{action:"none"};let K=!J.has("EnterWorktree")?"EnterWorktree":Y&&!J.has("ExitWorktree")?"ExitWorktree":void 0;if(!K)return{action:"none"};if(Z>=R4)return{action:"fail",message:h4};return{action:"retry",tool:K,prompt:K==="EnterWorktree"?k4:M4}}var D6=30000;async function J2($){try{let Z=z$.getInstance().executeStopHooks({projectDir:$.workspaceRoot??J0(),sessionId:$.sessionId,permissionMode:$.permissionMode,reason:$.reason,abortSignal:$.abortSignal}),W,Y=new Promise((K)=>{W=setTimeout(()=>K("timeout"),D6)});try{let K=await Promise.race([Z,Y]);if(K==="timeout")return s1.warn(`[Loop] Stop hook 超时 (${D6}ms),按 shouldStop: true 处理`),{action:"stop"};let H=K;if(!H.shouldStop)return{action:"continue",reason:H.continueReason};return{action:"stop"}}finally{clearTimeout(W)}}catch(J){return s1.warn("[Loop] Stop hook execution failed:",J),{action:"stop"}}}async function C4($,J){let Z;while(!(Z=await $.next()).done)if(J)await J(Z.value);return Z.value}var I4=[/<system-reminder>[\s\S]*?<\/system-reminder>/gi,/<file[^>]*>[\s\S]*?<\/file>/gi,/<hooks_context>[\s\S]*?<\/hooks_context>/gi,/<[^>]+>/g];function v4($){if(typeof $==="string")return $;if(Array.isArray($))return $.map((J)=>{if(typeof J==="string")return J;if(J&&typeof J==="object"&&"text"in J){let Z=J.text;return typeof Z==="string"?Z:""}return""}).join(" ");return""}function p4($){let J=$;for(let Q of I4)J=J.replace(Q," ");J=J.replace(/^\s*\/[a-zA-Z][\w-]*\s+/,"");let Z=J.replace(/\s+/g," ").trim();if(!Z)return"";let W=Z.match(/^(.+?)(?:[.!?]\s|[。!?](?=\S|$)|$)/),Y=W&&W[1].length>=6?W[1]:Z;if(Y=Y.trim().replace(/[\s.。!!??,,;;::-]+$/,""),Y.length<=60)return Y;let K=Y.slice(0,60),H=K.lastIndexOf(" ");return`${(H>36?K.slice(0,H):K).trimEnd()}…`}function O6($){return p4(v4($))}import{EventEmitter as g4}from"events";import N6 from"node:path";function Z2($){if(y6($.sessionId),!N6.isAbsolute($.projectPath))throw Error("projectPath must be absolute");return{sessionId:$.sessionId,projectPath:N6.resolve($.projectPath)}}function F6($){let J=Z2($);return JSON.stringify([J.projectPath,J.sessionId])}function WZ($,J){return F6($)===F6(J)}class B$ extends g4{static instance;constructor(){super();this.setMaxListeners(100)}static getInstance(){if(!B$.instance)B$.instance=new B$;return B$.instance}publish($,J,Z,W){let Y=Z2($);this.emit("event",{sessionId:Y.sessionId,projectPath:Y.projectPath,type:J,...W!==void 0?{seq:W}:{},properties:Z})}subscribe($){return this.on("event",$),()=>this.off("event",$)}}var h$=B$.getInstance();var u0=y0("Agent"),B1=new Set;async function u4($,J){let Z=$.sessionId;if(!Z||$.subagentInfo)return;if(B1.has(Z))return;if(B1.size>=5000)B1.clear();B1.add(Z);try{let W=$.workspaceRoot,Y=await R$.findSessionMetadata(Z,W);if(!Y)return;if(Y.title&&Y.title.trim())return;let K=O6(J);if(!K)return;await R$.updateSessionMetadata(Z,Y.projectPath,{title:K}),h$.publish({sessionId:Z,projectPath:Y.projectPath},"session.updated",{title:K})}catch(W){u0.debug?.("[Loop] 自动生成会话标题失败:",W)}}var W2=`<turn_aborted>
|
|
2
2
|
The previous turn was interrupted. Commands or tool calls may have partially completed; inspect the workspace and running processes before retrying.
|
|
3
3
|
</turn_aborted>`,J$="Tool execution was blocked because its durable call record could not be committed. No tool side effect was started.",P6="Tool execution completed, but its durable result record could not be committed. Further model and tool execution was stopped. The operation may have completed; inspect external state before retrying.";class D$ extends Error{phase;constructor($,J){super($==="user_message"?"Conversation input could not be committed. No further model request was started.":"Model output could not be committed. The run was stopped before any further model request or successful completion.",J);this.phase=$;this.name="DurableConversationPersistenceError"}}function Z$($){return $.executionEngine?.getContextManager()}async function h0($,J,Z,W=null,Y,K={}){let H=K.required??$.executionEngine!==void 0;try{let X=Z$($),Q=typeof Z==="string"?Z.trim()!=="":Z.some((V)=>V.type==="text"?V.text.trim()!=="":!0);if(X&&J.sessionId&&Q){let V=await X.saveMessage(J.sessionId,"user",Z,W,Y,J.subagentInfo);if(H&&!V)throw Error("Durable user-message commit returned no identity");if(Y?.clientVisible!==!1)u4(J,Z);return V}if(H&&J.sessionId&&Q)throw Error("Durable user-message storage is unavailable")}catch(X){if(u0.warn("[Loop] 保存用户消息失败:",X),H)throw new D$("user_message",{cause:X})}return null}async function P0($,J,Z,W,Y,K,H={}){let X=H.required??$.executionEngine!==void 0;try{let Q=Z$($),V=Boolean(Z.trim()||Y?.trim());if(Q&&J.sessionId&&V){let D=await Q.saveMessage(J.sessionId,"assistant",Z,W,K,J.subagentInfo,Y);if(X&&!D)throw Error("Durable assistant-message commit returned no identity");return D}if(X&&J.sessionId&&V)throw Error("Durable assistant-message storage is unavailable")}catch(Q){if(u0.warn("[Loop] 保存助手消息失败:",Q),X)throw new D$("assistant_message",{cause:Q})}return null}async function _6($,J,Z){try{let W=Z$($);if(W&&J.sessionId)return await W.saveMessage(J.sessionId,"system",W2,Z,void 0,J.subagentInfo)}catch(W){u0.warn("[Loop] 保存中断边界失败:",W)}return null}async function A6($,J,Z,W,Y){try{let K=Z$($);if(!K||!J.sessionId||Z.length===0)return null;return await K.saveMessage(J.sessionId,"system",`<contextual-project-instructions-ref count="${Z.length}" />`,Y,{contextualProjectRules:!0,ruleReferences:JSON.parse(JSON.stringify(Z.map((H)=>({...H})))),triggerPaths:[...W]},J.subagentInfo)}catch(K){u0.warn("[Loop] 保存 contextual project rules provenance 失败:",K)}return null}async function Y2($,J,Z,W,Y,K={}){try{let H=Z$($);if(H&&J.sessionId){let X=await H.saveToolUse(J.sessionId,Z,W,Y,J.subagentInfo,K.providerToolCallId);if(K.required&&!X)throw Error("Durable tool-use commit returned no identity");return X}if(K.required&&J.sessionId)throw Error("Durable tool-use storage is unavailable")}catch(H){if(u0.warn("[Loop] 保存工具调用失败:",H),K.required)throw H}return null}async function D1($,J,Z,W,Y,K,H,X,Q,V={}){try{let D=Z$($);if(D&&J.sessionId){let w=await D.saveToolResult(J.sessionId,Z,W,Y,K,H,J.subagentInfo,X,Q);if(V.required&&!w)throw Error("Durable tool-result commit returned no identity");return w}if(V.required&&J.sessionId)throw Error("Durable tool-result storage is unavailable")}catch(D){if(u0.warn("[Loop] 保存工具结果失败:",D),V.required)throw D}return null}async function C$($,J,Z,W,Y={}){try{let K=Z$($);if(K&&J.sessionId){let H=await K.saveCompaction(J.sessionId,Z,W,null);if(Y.required&&!H)throw Error("Compaction checkpoint commit returned no identity");return H||null}if(Y.required&&J.sessionId)throw Error("Compaction checkpoint storage is unavailable")}catch(K){if(u0.warn("[Loop] 保存压缩数据失败:",K),Y.required)throw K}return null}async function H0($){let{deps:J,context:Z,state:W,assistantContent:Y,assistantReasoningContent:K,lastMessageUuid:H,controlPrompt:X,controlMetadata:Q}=$;W.appendAssistant({role:"assistant",content:Y,reasoningContent:K});let V=H,D=await P0(J,Z,Y,V,K);if(D)V=D;if(X!==void 0){let w={role:"user",content:X};if(Q)w.metadata=Q;W.appendControl("user",w);let B=await h0(J,Z,w.content,V,Q);if(B)V=B}return V}import{createHash as nJ}from"node:crypto";import{promises as s4}from"node:fs";import t4 from"node:path";import{nanoid as d0}from"nanoid";import*as r from"node:fs/promises";import*as W$ from"node:path";var f6={enabled:!0,maxIndexLines:200};var m4="memory",b6="MEMORY.md";class K2{memoryDir;config;initialized=!1;constructor($,J,Z){if(Z)this.memoryDir=Z;else{let W=j$($);this.memoryDir=W$.join(W,m4)}this.config={...f6,...J}}async initialize(){if(this.initialized)return;await r.mkdir(this.memoryDir,{recursive:!0}),this.initialized=!0}async loadIndex(){if(!this.config.enabled)return null;await this.initialize();let $=W$.join(this.memoryDir,b6);try{let J=await r.readFile($,"utf-8");if(!J.trim())return null;let Z=J.split(`
|
|
4
4
|
`),Y=Z.slice(0,this.config.maxIndexLines).join(`
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{th as d,vh as h}from"./chunk-
|
|
1
|
+
import{th as d,vh as h}from"./chunk-c74e0jx1.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:"},"json-schema":{alias:["jsonSchema"],type:"string",describe:"Inline JSON Schema for the turn-scoped structured final response",group:"Output Options:"},"output-schema":{alias:["outputSchema"],type:"string",describe:"Path to a JSON Schema file for the structured final response",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},"max-concurrent-tasks":{alias:["maxConcurrentTasks"],type:"number",describe:"Maximum top-level tasks running concurrently in this process",group:"AI Options:",default:void 0},"max-queued-tasks":{alias:["maxQueuedTasks"],type:"number",describe:"Maximum top-level tasks waiting for an admission slot",group:"AI Options:",default:void 0},"max-queued-task-bytes":{alias:["maxQueuedTaskBytes"],type:"number",describe:"Maximum retained bytes across queued top-level tasks",group:"AI Options:",default:void 0},"max-resident-session-runtimes":{alias:["maxResidentSessionRuntimes"],type:"number",describe:"Maximum initialized Session runtimes resident in this process",group:"AI Options:",default:void 0},"session-runtime-idle-ms":{alias:["sessionRuntimeIdleMs"],type:"number",describe:"Idle time before an evictable Web Session runtime is disposed",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:"},"trust-workspace":{alias:["trustWorkspace"],type:"boolean",describe:"Trust the current workspace before loading project models, MCP, LSP, permissions, or plugins",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 sd,w as td};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{Aa as H}from"./chunk-
|
|
1
|
+
import{Aa as H}from"./chunk-yk8s8kjt.js";import"./chunk-fbgzeb3m.js";import"./chunk-qyxbee3w.js";import{Zd as $,de as T}from"./chunk-xts31qj4.js";import"./chunk-v508x7cg.js";import"./chunk-xkz9ecdx.js";import"./chunk-egp0crrc.js";import"./chunk-03947xkg.js";import"./chunk-zph2jekm.js";import"./chunk-qp8mejbn.js";import"./chunk-c03xn5s3.js";import"./chunk-yjbq4jeg.js";import{Fg as k}from"./chunk-22aaybx2.js";import"./chunk-qtt17d5s.js";import"./chunk-2qqmmxqf.js";import"./chunk-gbrwzpyg.js";import"./chunk-bj5msq36.js";import"./chunk-c74e0jx1.js";import"./chunk-yz80dp1a.js";import"./chunk-p7ww2tcn.js";import"./chunk-qw5j84ny.js";import"./chunk-99nevk7k.js";import U from"os";import J from"path";function X(z){return typeof z==="string"?z:void 0}function N(z){if(!Array.isArray(z))return;let q=[];for(let K of z)if(typeof K==="string")q.push(K);else if(K!=null)q.push(String(K));return q}function b(){console.log(`
|
|
2
2
|
blade mcp
|
|
3
3
|
`),console.log(`管理 MCP 服务器
|
|
4
4
|
`),console.log("Commands:"),console.log(" blade mcp add <name> <commandOrUrl> [args...] 添加 MCP 服务器"),console.log(" blade mcp remove <name> 删除 MCP 服务器 [aliases: rm]"),console.log(" blade mcp list 列出所有 MCP 服务器并检查健康状态 [aliases: ls]"),console.log(" blade mcp get <name> 获取服务器详情"),console.log(" blade mcp login <name> 登录远程 MCP OAuth"),console.log(" blade mcp logout <name> 清除远程 MCP OAuth 凭证"),console.log(` blade mcp add-json <name> <json> 从 JSON 字符串添加服务器
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{Aa as g0,sa as R,ta as u0,ya as WJ,za as I9}from"./chunk-
|
|
1
|
+
import{Aa as g0,sa as R,ta as u0,ya as WJ,za as I9}from"./chunk-yk8s8kjt.js";import{Ba as J6,Da as dJ,Fa as pJ,Ga as WZ,Ya as cJ}from"./chunk-22s3r2xy.js";import{$a as w9,Cb as k5,Db as r3,Eb as K3,Gb as e1,Hb as P3,Mb as e9,Pb as $7,Za as b$,_a as K1,ab as r$,bb as V9,cb as b9,db as K9,eb as A9,fb as j9,gb as _7,kb as W0,mb as e2,pb as H5,rb as z4,sb as K5,tb as O5,vb as U8,wb as X$}from"./chunk-g3fbgp1k.js";import{$b as G5,Dc as GZ,Ec as d0,Fc as O1,Gc as M3,Hc as C3,Kc as e3,Oc as s9,Tc as T3,Uc as R3,Vb as _0,Wb as S1,Wc as r,Xb as g$,Yb as w2,Zb as zZ,_b as z5,sc as T5,tc as L0,uc as $$}from"./chunk-57jj40er.js";import{Xc as x,Yc as q7,Zc as L7,_c as a$}from"./chunk-qyxbee3w.js";import{$c as iJ,cd as rJ,ld as nJ,rd as aJ}from"./chunk-r297pq3s.js";import{Cd as Z8,Dd as eZ}from"./chunk-2m4mgw58.js";import{Pd as _5,Qd as H0,Rd as f,Ud as B0,Vd as $5,Wd as _1,Xd as P$,Yd as q4,Zd as c$,_d as o9,de as G1}from"./chunk-xts31qj4.js";import{ee as s$}from"./chunk-xkz9ecdx.js";import{ie as t9,je as n9,me as u3,ne as Z5}from"./chunk-rjgfy07e.js";import{pe as P0,qe as h$}from"./chunk-2faga011.js";import{re as a3}from"./chunk-xbj18hxh.js";import{te as w3,ue as N3,ve as b3}from"./chunk-22sw5bv4.js";import{Ae as V5,Be as v$,Ce as A7,Ee as H$,Fe as Z$,Ge as a0,He as e5,Ie as V1,Je as S5,Ke as J1,Le as Y1,Me as j3,Qe as x4,Se as S0,Te as Q$,Ve as J5,We as S3,we as U5,xe as X5,ze as Q5}from"./chunk-rdtgv0n8.js";import{$e as p2,Ye as F1,_e as U$}from"./chunk-kaf6m50a.js";import{af as _J,cf as A3,df as C5,ef as J8}from"./chunk-0cbpjhq7.js";import{gf as s4,if as j0}from"./chunk-egp0crrc.js";import{jf as O2,kf as VZ,lf as _2,mf as U1}from"./chunk-03947xkg.js";import{Af as YJ,Ef as dZ,Gf as D3,If as L9,Jf as E9,Pf as o$,Sf as H9,ag as h9,bg as g9,cg as u9,dg as m9,eg as B4,fg as d9,gg as R$,hg as p9,ig as c9,jg as l9,lg as RZ,ng as k3,of as uZ,og as E3,pg as X0,tf as mZ,vf as r4}from"./chunk-zph2jekm.js";import{sg as N$}from"./chunk-qp8mejbn.js";import{tg as j2,ug as a5,vg as O,wg as R7,xg as S,yg as m}from"./chunk-c03xn5s3.js";import{Ag as G3,Bg as H3}from"./chunk-yjbq4jeg.js";import{Dg as S2,Fg as T}from"./chunk-22aaybx2.js";import{fh as l}from"./chunk-2qqmmxqf.js";import{kh as q3,lh as L3}from"./chunk-gbrwzpyg.js";import{mh as BJ,ph as KJ}from"./chunk-bj5msq36.js";import{th as EJ}from"./chunk-c74e0jx1.js";import{Ah as y0,zh as f3}from"./chunk-yz80dp1a.js";import{Eh as E2,Gh as C$,Ih as B3,Jh as bZ,Lh as s}from"./chunk-qw5j84ny.js";import{Nh as t0}from"./chunk-99nevk7k.js";import{randomUUID as r5}from"crypto";import{randomUUID as OY}from"node:crypto";var VY=String.raw`
|
|
2
2
|
const { spawn } = require('node:child_process');
|
|
3
3
|
const [ownerPidValue, command, ...args] = process.argv.slice(1);
|
|
4
4
|
const ownerPid = Number(ownerPidValue);
|
|
@@ -815,7 +815,7 @@ ${n}
|
|
|
815
815
|
</approved-plan>
|
|
816
816
|
|
|
817
817
|
IMPORTANT: Execute according to the approved plan above. Follow the steps exactly as specified.`;if(typeof K==="string")e=K+y;else e=[...K,{type:"text",text:y}]}P=yield*this.runLoop(e,_,{...C,inputMessageId:void 0})}if(!this.sessionRuntime||!b)return P;let k=await this.sessionRuntime.recordGoalProgress({tokens:P.metadata?.tokensUsed??0,elapsedMs:P.metadata?.duration??0,prematureStopPattern:P.success?q9(P.finalMessage):void 0});if(k)yield{kind:"goal_updated",goal:k};if(!P.success||_.signal?.aborted){if(k=await this.sessionRuntime.pauseActiveGoal(_.signal?.aborted?"goal paused after user cancellation":P.error?.message??"goal paused after turn failure"),k)yield{kind:"goal_updated",goal:k}}if(P.success&&!_.signal?.aborted&&E<20)await this.sessionRuntime.waitForBackgroundSubagentFollowUp(b,_.signal);let a=P.success&&!_.signal?.aborted&&E<20,g=xX(P);if(N=await this.sessionRuntime.finishTurn(b,{continuePending:a,...g?{acknowledgeInput:!0}:{},outcome:P.success&&!_.signal?.aborted?{status:"completed",turnsCount:P.metadata?.turnsCount??0,toolCallsCount:P.metadata?.toolCallsCount??0,durationMs:P.metadata?.duration??0}:{status:"aborted",cause:_.signal?.aborted?"cancelled":"failed",turnsCount:P.metadata?.turnsCount??0,toolCallsCount:P.metadata?.toolCallsCount??0,durationMs:P.metadata?.duration??0}}),N){E++,B=!0,F=!1,L=null,K="",q=void 0,D=M(),yield{kind:"follow_up_started",queued:this.sessionRuntime.getPendingSteeringCount(),recovered:this.sessionRuntime.getRecoveredSteeringCount(),messages:j()};continue}if(!P.success||_.signal?.aborted)return P;if(k=await this.sessionRuntime.getGoal(),!k||k.status!=="active"&&k.status!=="verifying")return P;if(L=await this.sessionRuntime.beginGoalContinuation(),!L)return P;N=await this.sessionRuntime.beginTurn("goal"),B=!1,F=!0,K=j6(L),q=void 0,D=void 0,yield{kind:"goal_continuation_started",goal:L,continuation:L.continuationCount,...L.prematureStop?{prematureStopPattern:L.prematureStop.pattern,prematureStopCount:L.prematureStop.consecutiveCount}:{}},yield{kind:"goal_updated",goal:L}}}finally{if(this.sessionRuntime&&N)await this.sessionRuntime.finishTurn(N)}}let z=typeof Q==="string"?Q:Q.filter((K)=>K.type==="text").map((K)=>K.text).join(`
|
|
818
|
-
`),G={id:this.generateTaskId(),type:"simple",prompt:z};return{success:!0,finalMessage:(await this.executeTask(G)).content,metadata:{turnsCount:1,toolCallsCount:0,duration:0}}}async chat($,Z,J){let{drainLoop:Y}=await import("./chunk-
|
|
818
|
+
`),G={id:this.generateTaskId(),type:"simple",prompt:z};return{success:!0,finalMessage:(await this.executeTask(G)).content,metadata:{turnsCount:1,toolCallsCount:0,duration:0}}}async chat($,Z,J){let{drainLoop:Y}=await import("./chunk-5a132j64.js");return Y(this.chatStream($,Z,J))}async*runPlanLoop($,Z,J){p.debug("Processing Plan mode message...");let{prompt:Y}=await A$({projectPath:Z.workspaceRoot||T(),mode:"plan",includeEnvironment:!0,environmentOptions:e1,language:this.config.language,availableSkills:this.agentResources?.skills.generateAvailableSkillsList(),communicationStyle:this.sessionRuntime?.getCommunicationStyleConfiguration().selection,communicationStyleCatalog:this.sessionRuntime?.getCommunicationStyleCatalog(),projectRuleCatalog:this.sessionRuntime?.getProjectRuleCatalog(),projectInstructionSourcePath:this.sessionRuntime?.projectRoot}),W;if(typeof $==="string")W=u1($);else{let U=$.filter((X)=>X.type==="text");if(U.length>0){let X=U[0];W=$.map((Q)=>Q===X?{type:"text",text:u1(X.text)}:Q)}else W=[{type:"text",text:u1("")},...$]}return yield*this.executeLoop(W,Z,J,Y)}async*runLoop($,Z,J){p.debug("Processing enhanced chat message...");let Y=Z.systemPrompt??await this.buildSystemPromptOnDemand(Z.workspaceRoot||T());return yield*this.executeLoop($,Z,J,Y)}async buildSystemPromptOnDemand($){let Z=this.runtimeOptions.systemPrompt,J=this.runtimeOptions.appendSystemPrompt;return(await A$({projectPath:$,replaceDefault:Z,append:J,includeEnvironment:!0,environmentOptions:e1,language:this.config.language,availableSkills:this.agentResources?.skills.generateAvailableSkillsList(),communicationStyle:this.sessionRuntime?.getCommunicationStyleConfiguration().selection,communicationStyleCatalog:this.sessionRuntime?.getCommunicationStyleCatalog(),projectRuleCatalog:this.sessionRuntime?.getProjectRuleCatalog(),projectInstructionSourcePath:this.sessionRuntime?.projectRoot})).prompt}executeLoop($,Z,J,Y){if(!this.isInitialized)throw Error("Agent未初始化");let W=this.buildLoopDependencies();return $7(W,$,Z,J,Y)}takeStartupAdoptedToolResultEvents(){return(this.sessionRuntime?.takeStartupAdoptedToolResults()??[]).flatMap(({call:Z,result:J})=>{let Y={id:Z.toolCallId,type:"function",function:{name:Z.toolName,arguments:JSON.stringify(Z.input)}},W=J.metadata&&typeof J.metadata==="object"&&!Array.isArray(J.metadata)?J.metadata:void 0,U=J.error===void 0,X=J.output,Q={success:U,llmContent:typeof X==="string"||X!==null&&typeof X==="object"?X:X===null?J.error?`Subagent execution failed: ${J.error}.`:"":String(X),...J.error?{error:{type:"execution_error",message:J.error}}:{},...W?{metadata:W}:{}},V=[{kind:"tool_result",toolCall:Y,result:Q}],z=e9(Y,Q);if(z)V.push(z);return V})}buildLoopDependencies(){return{chatService:this.chatService,toolExecutor:this.toolExecutor,executionEngine:this.executionEngine,config:this.config,runtimeOptions:this.runtimeOptions,currentModelMaxContextTokens:this.currentModelMaxContextTokens,activeSkillContext:this.activeSkillContext,onSkillActivated:($)=>{this.activeSkillContext=$,p.debug(`Skill "${$.skillName}" activated`+($.allowedTools?` with allowed tools: ${$.allowedTools.join(", ")}`:""))},onModelSwitch:($)=>this.switchModelIfNeeded($),applySkillToolRestrictions:($)=>this.applySkillToolRestrictions($),staticProjectRules:this.sessionRuntime?.getStaticProjectRules(),hydrateProjectRules:this.sessionRuntime?($)=>this.sessionRuntime.hydrateProjectRules($):void 0,resolveContextualProjectRules:this.sessionRuntime?($,Z,J,Y)=>this.sessionRuntime.resolveContextualProjectRules($,Z,J,Y):void 0}}async chatWithSystem($,Z){if(!this.isInitialized)throw Error("Agent未初始化");let J=[{role:"system",content:$},{role:"user",content:Z}];return(await this.chatService.chat(J)).content}getActiveTask(){return this.activeTask}getChatService(){return this.chatService}getContextManager(){return this.executionEngine?.getContextManager()}getStats(){return{initialized:this.isInitialized,activeTask:this.activeTask?.id,components:{chatService:this.chatService?"ready":"not_loaded",executionEngine:this.executionEngine?"ready":"not_loaded"}}}getAvailableTools(){return this.toolExecutor?this.toolExecutor.getRegistry().getAll():[]}getToolRegistry(){return this.toolExecutor.getRegistry()}applyToolWhitelist($){let Z=this.toolExecutor.getRegistry(),Y=Z.getAll().filter((W)=>!$.includes(W.name));for(let W of Y)Z.unregister(W.name);p.debug(`Applied tool whitelist: ${$.join(", ")} (removed ${Y.length} tools)`)}applyToolBlacklist($){let Z=this.toolExecutor.getRegistry(),J=new Set($);for(let Y of Z.getAll())if(J.has(Y.name))Z.unregister(Y.name);p.debug(`Applied tool blacklist: ${$.join(", ")}`)}getToolStats(){let $=this.getAvailableTools(),Z=new Map;return $.forEach((J)=>{let Y=Z.get(J.kind)||0;Z.set(J.kind,Y+1)}),{totalTools:$.length,toolsByKind:Object.fromEntries(Z),toolNames:$.map((J)=>J.name)}}async destroy(){if(this.destroyPromise)return this.destroyPromise;return this.destroyPromise=(async()=>{this.log("销毁Agent..."),await this.activeOperations.shutdown("agent-destroy");try{await this.legacyMcpRegistry?.disconnectAll(),this.legacyMcpRegistry=void 0,this.log("Agent已销毁")}catch($){throw this.error("Agent销毁失败",$),$}finally{this.toolExecutor.dispose(),this.isInitialized=!1}})(),this.destroyPromise}syncRuntimeState(){if(!this.sessionRuntime)return;this.chatService=this.sessionRuntime.getChatService(),this.executionEngine=this.sessionRuntime.getExecutionEngine(),this.attachmentCollector=this.sessionRuntime.getAttachmentCollector(),this.currentModelId=this.sessionRuntime.getCurrentModelId(),this.currentModelMaxContextTokens=this.sessionRuntime.getCurrentModelMaxContextTokens()}generateTaskId(){return`task_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}log($,Z){p.debug(`[MainAgent] ${$}`,Z||"")}error($,Z){p.error(`[MainAgent] ${$}`,Z||"")}async initializeSystemPrompt(){try{let $=this.runtimeOptions.systemPrompt,Z=this.runtimeOptions.appendSystemPrompt,J=await A$({projectPath:this.sessionRuntime?.workspaceRoot??T(),replaceDefault:$,append:Z,includeEnvironment:!1,language:this.config.language,availableSkills:this.agentResources?.skills.generateAvailableSkillsList(),communicationStyle:this.sessionRuntime?.getCommunicationStyleConfiguration().selection,communicationStyleCatalog:this.sessionRuntime?.getCommunicationStyleCatalog(),projectRuleCatalog:this.sessionRuntime?.getProjectRuleCatalog(),projectInstructionSourcePath:this.sessionRuntime?.projectRoot});if(J.prompt)this.log("系统提示配置验证成功"),p.debug(`[SystemPrompt] 可用来源: ${J.sources.filter((Y)=>Y.loaded).map((Y)=>Y.name).join(", ")}`)}catch($){this.error("系统提示配置验证失败",$)}}async registerBuiltinTools(){try{let $=await Y5({sessionId:"default",configDir:s(),workspaceRoot:T(),resourceRoot:T(),agentResources:this.agentResources});p.debug(`Registering ${$.length} builtin tools...`),this.toolExecutor.getRegistry().registerAll($);let Z=this.toolExecutor.getRegistry().getAll().length;p.debug(`Builtin tools registered: ${Z} tools`),p.debug(`[Tools] ${this.toolExecutor.getRegistry().getAll().map((J)=>J.name).join(", ")}`),await this.registerMcpTools()}catch($){throw p.error("Failed to register builtin tools:",$),$}}async registerMcpTools(){try{let $=await f2({workspaceRoot:T(),storeServers:this.config.mcpServers??{},cliConfigs:this.runtimeOptions.mcpConfig,strictCliConfig:this.runtimeOptions.strictMcpConfig});if(Object.keys($).length===0){p.debug("No MCP servers configured");return}let Z=g0.createIsolated({artifactWriter:new g1(`legacy-${IX()}`)});this.legacyMcpRegistry=Z;for(let[U,X]of Object.entries($))try{p.debug(`Connecting to MCP server: ${U}`),await Z.registerServer(U,X),p.debug(`MCP server "${U}" connected`)}catch(Q){p.warn(`Warning: MCP server "${U}" connection failed:`,Q)}let J=this.toolExecutor.getRegistry();J.setMcpCatalogBarrier(()=>Z.waitForCatalogIdle());let Y=Z.getCatalogSnapshot();J.replaceMcpTools(Y.tools),J.registerAll(l1(Z));let W=Z.getInstructionsSnapshot();if(J.queueMcpInstructionsChange({revision:W.revision,reason:"snapshot",replace:!0,instructions:W.instructions,removed:[]}),Z.on("catalogChanged",(U)=>{J.replaceMcpTools(U.tools,U)}),Z.on("contentCatalogChanged",(U)=>{J.queueMcpContentChange(U)}),Z.on("resourceUpdated",(U)=>{J.queueMcpResourceUpdated(U)}),Z.on("connectionLifecycleChanged",(U)=>{J.queueMcpConnectionChange(U)}),Z.on("log",(U)=>{J.queueMcpLog(U)}),Z.on("instructionsChanged",(U)=>{J.queueMcpInstructionsChange({revision:U.revision,reason:U.reason,replace:!1,instructions:U.action==="added"&&U.instruction?[{serverName:U.serverName,...U.instruction}]:[],removed:U.action==="removed"?[U.serverName]:[]})}),Y.tools.length>0)p.debug(`Registered ${Y.tools.length} MCP tools`),p.debug(`[MCP Tools] ${Y.tools.map((U)=>U.name).join(", ")}`)}catch($){p.warn("Failed to register MCP tools:",$)}}async loadSubagents(){let $=await S0(T());if(this.agentResources=J5($),this.subagentRegistry=this.agentResources.subagents,this.runtimeOptions.agents?.length)this.subagentRegistry.applyOverrides(this.runtimeOptions.agents);let Z=this.subagentRegistry.getAllNames().length;if(Z>0)p.debug(`Loaded ${Z} subagents: ${this.subagentRegistry.getAllNames().join(", ")}`);else p.debug("No subagents configured")}applySkillToolRestrictions($){if(!this.activeSkillContext?.allowedTools)return $;let Z=this.activeSkillContext.allowedTools;p.debug(`Applying Skill tool restrictions: ${Z.join(", ")}`);let J=$.filter((Y)=>{return Z.some((W)=>{if(W===Y.name)return!0;let U=W.match(/^(\w+)\(.*\)$/);if(U&&U[1]===Y.name)return!0;return!1})});return p.debug(`Filtered tools: ${J.map((Y)=>Y.name).join(", ")} (${J.length}/${$.length})`),J}clearSkillContext(){if(this.activeSkillContext)p.debug(`Skill "${this.activeSkillContext.skillName}" deactivated`),this.activeSkillContext=void 0}async processAtMentionsForContent($){if(!this.attachmentCollector)return $;if(typeof $==="string")return this.processAtMentions($);let Z=[];for(let Y of $)if(Y.type==="text")Z.push(Y.text);if(Z.length===0)return $;let J=Z.join(`
|
|
819
819
|
`);try{let Y=await this.attachmentCollector.collect(J);if(Y.length===0)return $;p.debug(`Processed ${Y.length} @ file mentions in multimodal message`);let W=this.buildAttachmentText(Y);if(!W)return $;return[...$,{type:"text",text:W}]}catch(Y){return p.error("Failed to process @ mentions in multimodal message:",Y),$}}buildAttachmentText($){let Z=[],J=[];for(let W of $)if(W.type==="file"){let U=W.metadata?.lineRange?` (lines ${W.metadata.lineRange.start}${W.metadata.lineRange.end?`-${W.metadata.lineRange.end}`:""})`:"";Z.push(`<file path="${W.path}"${U?` range="${U}"`:""}>`,W.content,"</file>")}else if(W.type==="directory")Z.push(`<directory path="${W.path}">`,W.content,"</directory>");else if(W.type==="error")J.push(`- @${W.path}: ${W.error}`);let Y="";if(Z.length>0)Y+=`
|
|
820
820
|
|
|
821
821
|
<system-reminder>
|
|
@@ -1615,7 +1615,7 @@ ${J}
|
|
|
1615
1615
|
`)),{success:!0,message:"Schedules listed",content:V.join(`
|
|
1616
1616
|
`)}}case"create":{let Q=FH(U);if("error"in Q)return Y.sendMessage(`创建失败:${Q.error}`),{success:!1,error:Q.error};let V={prompt:Q.prompt,projectPath:X,trigger:Q.trigger,isolation:"worktree",permissionMode:"default",enabled:!0};try{let z=await $.create(V),G=z.nextRunAt?new Date(z.nextRunAt).toLocaleString():"(无)";return Y.sendMessage(`[OK] 已创建定时任务 \`${z.id}\`
|
|
1617
1617
|
${WZ(z.trigger)} · 下次运行: ${G}`),{success:!0,message:`Schedule ${z.id} created`}}catch(z){let G=z instanceof Error?z.message:String(z);return Y.sendMessage(`创建失败:${G}`),{success:!1,error:G}}}case"remove":case"rm":{let Q=U[0];if(!Q)return Y.sendMessage("用法:/schedule remove <id>"),{success:!1,error:"Missing schedule id"};let V=await $.remove(Q);return Y.sendMessage(V?`[OK] 已删除 \`${Q}\``:`未找到 \`${Q}\``),{success:V,message:V?"Removed":"Not found"}}case"enable":case"disable":{let Q=U[0];if(!Q)return Y.sendMessage(`用法:/schedule ${W} <id>`),{success:!1,error:"Missing schedule id"};let V=await $.setEnabled(Q,W==="enable");return Y.sendMessage(V?`[OK] 已${W==="enable"?"启用":"停用"} \`${Q}\``:`未找到 \`${Q}\``),{success:Boolean(V),message:V?"Updated":"Not found"}}case"run":{let Q=U[0];if(!Q)return Y.sendMessage("用法:/schedule run <id>"),{success:!1,error:"Missing schedule id"};try{return await BH(Q),Y.sendMessage(`[OK] 已触发 \`${Q}\``),{success:!0,message:"Schedule triggered"}}catch(V){let z=V instanceof Error?V.message:String(V);return Y.sendMessage(`运行失败:${z}`),{success:!1,error:z}}}default:return Y.sendMessage(`未知子命令: ${W}
|
|
1618
|
-
使用 /schedule 查看帮助`),{success:!1,error:`Unknown subcommand: ${W}`}}}}}var lJ=DH();import*as T1 from"node:fs/promises";import*as R1 from"node:path";async function oJ($,Z={}){let{maxResults:J=20,caseSensitive:Y=!1,projectPath:W,storagePath:U}=Z,X=U??E2(W??T());if(!U){let K=await qH($,W??T(),J,Y);if(K)return K}let Q;try{Q=(await T1.readdir(X)).filter((_)=>_.endsWith(".jsonl")&&!_.startsWith("agent_")).map((_)=>R1.join(X,_))}catch{return[]}let z=(await Promise.all(Q.map(async(K)=>{try{let _=await T1.stat(K);return{path:K,mtime:_.mtimeMs}}catch{return null}}))).filter((K)=>K!==null).sort((K,_)=>_.mtime-K.mtime).map((K)=>K.path),G=[],H=Y?$:$.toLowerCase();for(let K of z){if(G.length>=J)break;let _=R1.basename(K,".jsonl"),B=await LH(K,H,Y,_);if(G.push(...B),G.length>=J){G.length=J;break}}return G}async function qH($,Z,J,Y){try{let{syncAll:W}=await import("./chunk-4mgjj8zg.js"),U=await nJ();if(!U)return null;let{SessionService:X}=await import("./chunk-
|
|
1618
|
+
使用 /schedule 查看帮助`),{success:!1,error:`Unknown subcommand: ${W}`}}}}}var lJ=DH();import*as T1 from"node:fs/promises";import*as R1 from"node:path";async function oJ($,Z={}){let{maxResults:J=20,caseSensitive:Y=!1,projectPath:W,storagePath:U}=Z,X=U??E2(W??T());if(!U){let K=await qH($,W??T(),J,Y);if(K)return K}let Q;try{Q=(await T1.readdir(X)).filter((_)=>_.endsWith(".jsonl")&&!_.startsWith("agent_")).map((_)=>R1.join(X,_))}catch{return[]}let z=(await Promise.all(Q.map(async(K)=>{try{let _=await T1.stat(K);return{path:K,mtime:_.mtimeMs}}catch{return null}}))).filter((K)=>K!==null).sort((K,_)=>_.mtime-K.mtime).map((K)=>K.path),G=[],H=Y?$:$.toLowerCase();for(let K of z){if(G.length>=J)break;let _=R1.basename(K,".jsonl"),B=await LH(K,H,Y,_);if(G.push(...B),G.length>=J){G.length=J;break}}return G}async function qH($,Z,J,Y){try{let{syncAll:W}=await import("./chunk-4mgjj8zg.js"),U=await nJ();if(!U)return null;let{SessionService:X}=await import("./chunk-fpkq3ch3.js");await W(U,X.projectionDeriverForSearch());let Q=R1.resolve(Z),V=aJ(U,$,Q,J*4),z=Y?$:$.toLowerCase(),G=[];for(let H of V){if(H.role!=="user"&&H.role!=="assistant")continue;let K=UZ(H.text,z,Y,H.session_id,H.role,H.timestamp??void 0,0);if(K)G.push(K);if(G.length>=J)break}return G}catch{return null}}async function LH($,Z,J,Y){try{let W=await T1.readFile($,"utf8"),X=W.split(`
|
|
1619
1619
|
`).flatMap((H,K)=>{if(!H.trim())return[];try{return[{event:JSON.parse(H),index:K}]}catch{return[]}});if(!X.some(({event:H})=>H.type==="session_created"))return EH(X,Z,J,Y);let V=new Map(X.flatMap(({event:H,index:K})=>typeof H.id==="string"?[[H.id,K+1]]:[])),z=iJ(rJ(W,$)),G=new Map;for(let H of z){if(H.type==="message_created"&&(H.data.role==="user"||H.data.role==="assistant"))G.set(H.data.messageId,{role:H.data.role,content:[],timestamp:H.timestamp,lineNumber:V.get(H.id)??0});if(H.type==="part_created"&&H.data.partType==="text"){let K=G.get(H.data.messageId),_=H.data.payload.text;if(K&&typeof _==="string")K.content.push(_)}}return[...G.values()].flatMap((H)=>{let K=UZ(H.content.join(" "),Z,J,Y,H.role,H.timestamp,H.lineNumber);return K?[K]:[]})}catch{return[]}}function EH($,Z,J,Y){return $.flatMap(({event:W,index:U})=>{if(W.type!=="message")return[];let X=W.message;if(X?.role!=="user"&&X?.role!=="assistant"||!X.content)return[];let Q=typeof X.content==="string"?X.content:Array.isArray(X.content)?X.content.filter((z)=>typeof z==="object"&&z!==null&&z.type==="text"&&typeof z.text==="string").map((z)=>z.text).join(" "):"",V=UZ(Q,Z,J,Y,X.role,typeof W.timestamp==="string"?W.timestamp:void 0,U+1);return V?[V]:[]})}function UZ($,Z,J,Y,W,U,X){if(!$)return;let Q=J?$:$.toLowerCase();if(!Q.includes(Z))return;let V=Q.indexOf(Z),z=Math.max(0,V-80),G=Math.min($.length,V+Z.length+80);return{sessionId:Y,role:W,content:(z>0?"...":"")+$.slice(z,G).replace(/\n/g," ")+(G<$.length?"...":""),timestamp:U,lineNumber:X}}function tJ($){if($.length===0)return"没有找到匹配的历史记录";let Z=[`**找到 ${$.length} 条匹配:**
|
|
1620
1620
|
`];for(let J of $){let Y=J.timestamp?new Date(J.timestamp).toLocaleString("zh-CN",{timeZone:"Asia/Shanghai"}):"?",W=J.role==="user"?"\uD83D\uDC64":"\uD83E\uDD16";Z.push(`${W} \`${J.sessionId.slice(0,8)}\` (${Y})`),Z.push(` ${J.content}`),Z.push("")}return Z.join(`
|
|
1621
1621
|
`)}var wH={name:"search",description:"Search past session transcripts",fullDescription:"搜索历史会话记录,查找过去的对话内容",usage:"/search <keyword>",aliases:["find","history"],category:"Session",examples:['/search 断路器 - 搜索包含"断路器"的历史对话',"/search edit tool - 搜索 edit tool 相关讨论"],async handler($,Z){let J=I(Z);if($.length===0)return J.sendMessage("**用法:** `/search <关键词>`\n\n在历史会话中搜索包含指定关键词的对话"),{success:!0,message:"显示帮助"};let Y=$.join(" ");J.sendMessage(`正在搜索: "${Y}" ...`);try{let W=await oJ(Y,{maxResults:15,projectPath:Z.cwd}),U=tJ(W);return J.sendMessage(U),{success:!0,message:`found ${W.length} results`,data:{matches:W.length}}}catch(W){let U=W instanceof Error?W.message:"未知错误";return J.sendMessage(`搜索失败: ${U}`),{success:!1,error:U}}}},sJ=wH;var NH={name:"skills",description:"查看所有可用的 Skills",fullDescription:"显示所有已发现的 Skills 及其详细信息,包括名称、描述、来源和允许的工具。",usage:"/skills",category:"system",examples:["/skills"],handler:async($,Z)=>{try{let J=Z.workspaceRoot??Z.cwd;return await Q$(J,async(Y)=>{await Y.skills.refresh(),Y1(J),await J1(J)}),{success:!0,message:"show_skills_manager",data:{action:"show_skills_manager"}}}catch(J){let Y=`获取 Skills 失败: ${J instanceof Error?J.message:"未知错误"}`;return f().addAssistantMessage(Y),{success:!1,error:Y}}}},eJ=NH;import bH from"node:path";function m5($){if($<1000)return`${$}ms`;let Z=Math.floor($/1000);if(Z<60)return`${Z}s`;let J=Math.floor(Z/60);if(J<60)return`${J}m ${Z%60}s`;return`${Math.floor(J/60)}h ${J%60}m`}function $Y($){switch($){case"running":return"[RUNNING]";case"completed":case"exited":return"[OK]";case"failed":case"error":return"[FAIL]";case"killed":case"cancelled":return"[STOPPED]";default:return"[?]"}}function ZY($,Z){if($.length<=Z)return $;return $.slice(0,Z-3)+"..."}async function AH($,Z){let J=I(Z),Y=$[0],W=o.getInstance(),U=Q0.getInstance(),X=Z.sessionId??"",Q=Z.sessionId?{sessionId:Z.sessionId,projectPath:bH.resolve(Z.workspaceRoot??Z.cwd)}:void 0;if(Y==="resume"){let _=$[1],B=$.slice(2).join(" ").trim();if(!_||!B)return{success:!1,error:"Usage: /tasks resume <agentId> <prompt>"};if(!Z.subagents)return{success:!1,error:"This surface does not own a subagent runtime"};let F=await Z.subagents.resume(_,B),D=`Resumed \`${_}\` as \`${F.session.id}\` (depth ${F.session.resumeDepth}).`;return J.sendMessage(D),{success:!0,message:D,data:{action:"subagent_resumed",sourceAgentId:_,subagent:F.session}}}if(Y==="clean"){let _=U.cleanupExpiredSessionsForParent(Q??X,0);return J.sendMessage(`已清理 ${_} 个已完成的 Agent 会话`),{success:!0,message:`Cleaned ${_} agent sessions`}}let V=[`**后台任务列表**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as o}from"./chunk-
|
|
1
|
+
import{a as o}from"./chunk-tnjq10zs.js";import"./chunk-c74e0jx1.js";import"./chunk-99nevk7k.js";import{execSync as r}from"child_process";var l={command:"update",describe:"Check for updates and install if available",handler:async()=>{console.log("Checking for updates...");try{let e=await o(!0);if(console.log(`Current version: ${e.currentVersion}`),e.error){console.log(`Warning: ${e.error}`);return}if(e.latestVersion)console.log(`Latest version: ${e.latestVersion}`);if(e.hasUpdate&&e.latestVersion){console.log(""),console.log(`\x1B[33mUpdate available: ${e.currentVersion} -> ${e.latestVersion}\x1B[0m`),console.log(""),console.log("Updating...");try{r("npm install -g blade-code@latest --registry https://registry.npmjs.org",{stdio:"inherit"}),console.log(""),console.log("Update complete!")}catch(t){console.error("Error: Update failed. Please run manually:"),console.error(" npm install -g blade-code@latest"),process.exit(1)}}else console.log("You are running the latest version of Blade")}catch(e){console.error(`Error: Failed to check for updates: ${e instanceof Error?e.message:"未知错误"}`),process.exit(1)}}};export{l as updateCommands};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{b as RY,c as MY,d as TY}from"./chunk-
|
|
1
|
+
import{b as RY,c as MY,d as TY}from"./chunk-tnjq10zs.js";import{j as DJ,k as VJ}from"./chunk-1zkwxaa0.js";import{u as s2}from"./chunk-agxs6rwh.js";import{$ as tJ,C as c6,E as gY,G as OQ,H as XQ,I as v6,M as A6,N as P6,R as j1,T as e4,U as $6,X as y6,Z as z2,_ as nJ,ca as sJ,da as eJ,ha as L4,ia as $9,ka as t6,la as s6,ma as mY,na as O6,pa as z6,ra as x6}from"./chunk-kb5xaar0.js";import{Aa as EY,va as qJ,wa as OJ,xa as zJ}from"./chunk-yk8s8kjt.js";import{Ca as b6}from"./chunk-22s3r2xy.js";import{Fb as QQ,jb as L6,kb as B6,wb as w6}from"./chunk-g3fbgp1k.js";import{Qb as W2}from"./chunk-fbgzeb3m.js";import{Ac as s4,Hc as Y6,Ic as $Q,Jc as Z6,Lc as d2,Tc as O2,Wc as C0,hc as _6,vc as t4}from"./chunk-57jj40er.js";import"./chunk-qyxbee3w.js";import"./chunk-r297pq3s.js";import{xd as PY}from"./chunk-4ppgfhqd.js";import{Bd as C1,yd as H2,zd as e2}from"./chunk-s7gf2ds9.js";import"./chunk-2m4mgw58.js";import{Fd as k$,Gd as a0,Hd as Q$,Id as jQ,Jd as g$,Kd as r2,Ld as v9,Md as Q4,Nd as MJ,Od as D9,Pd as V$,Qd as l0,Rd as jY,Sd as o0,Td as AY,Ud as D8,Vd as N2,Yd as U6,de as p0}from"./chunk-xts31qj4.js";import"./chunk-v508x7cg.js";import"./chunk-xkz9ecdx.js";import"./chunk-rjgfy07e.js";import{qe as J4}from"./chunk-2faga011.js";import"./chunk-xbj18hxh.js";import"./chunk-22sw5bv4.js";import{Be as Q8,Ee as _Y,Je as iJ,Se as hY}from"./chunk-rdtgv0n8.js";import"./chunk-kaf6m50a.js";import"./chunk-0cbpjhq7.js";import"./chunk-rc7jnds2.js";import{gf as gQ,if as q1}from"./chunk-egp0crrc.js";import"./chunk-03947xkg.js";import{kg as DY,pg as oJ,qg as VY}from"./chunk-zph2jekm.js";import"./chunk-qp8mejbn.js";import"./chunk-c03xn5s3.js";import{Ag as a2,Bg as mQ,zg as m$}from"./chunk-yjbq4jeg.js";import{Fg as d0}from"./chunk-22aaybx2.js";import"./chunk-qtt17d5s.js";import{ch as vY,fh as t1}from"./chunk-2qqmmxqf.js";import{hh as kJ,ih as SJ,lh as h1}from"./chunk-gbrwzpyg.js";import"./chunk-bj5msq36.js";import{xh as bJ}from"./chunk-c74e0jx1.js";import{Ah as F4}from"./chunk-yz80dp1a.js";import"./chunk-p7ww2tcn.js";import{Lh as e8}from"./chunk-qw5j84ny.js";import{Nh as EQ}from"./chunk-99nevk7k.js";import{useMemoizedFn as u8}from"ahooks";import{useEffect as S7,useState as l8}from"react";import{useMemoizedFn as s0}from"ahooks";import{Box as z$}from"ink";import{useEffect as _$,useMemo as R7,useRef as p8}from"react";import{useShallow as uY}from"zustand/react/shallow";import{useStore as xY}from"zustand";function t($){return xY(V$,$)}var lY=[],j$=()=>t(($)=>$.session.sessionId),T1=()=>t(($)=>$.session.workspaceRoot),B4=()=>t(($)=>$.session.messages),w4=()=>t(($)=>$.session.clearCount),b4=()=>t(($)=>$.session.isCompacting),A4=()=>t(($)=>$.session.tokenUsage.estimatedCostUsd),P4=()=>t(($)=>{let{totalInputTokens:Q,cacheReadTokens:Y,cacheWriteTokens:J}=$.session.tokenUsage;return L4({totalInputTokens:Q,cacheReadTokens:Y,cacheWriteTokens:J}).hitRate}),y4=()=>t(($)=>$.session.providerCircuit),R4=()=>t(($)=>$.session.providerAdmission),M4=()=>t(($)=>$.session.providerRetry),T4=()=>t(($)=>$.session.providerStall),C4=()=>t(($)=>$.session.actionStationarity),i1=()=>t(($)=>$.session.actions),I4=()=>t(($)=>{let{inputTokens:Q,maxContextTokens:Y}=$.session.tokenUsage;if(Y<=0)return 100;let J=Math.max(0,100-Q/Y*100);return Math.round(J)}),f4=()=>t(($)=>$.app.initializationStatus),k4=()=>t(($)=>$.app.initializationError),D2=()=>t(($)=>$.app.activeModal),S4=()=>t(($)=>$.app.tasks),v4=()=>t(($)=>$.app.modelEditorTarget),D4=()=>t(($)=>$.app.sessionSelectorData),V4=()=>t(($)=>$.app.awaitingSecondCtrlC),n1=()=>t(($)=>$.app.actions),V2=()=>t(($)=>$.app.sideConversation),j4=()=>t(($)=>$.app.teams),j2=()=>t(($)=>$.app.initializationStatus==="ready"),h4=()=>t(($)=>$.app.tasks.length>0),h$=()=>t(($)=>$.config.config?.permissionMode||"default"),E4=()=>t(($)=>$.config.config?.models??lY),h2=()=>t(($)=>{let Q=$.config.config;if(!Q)return;let Y=Q.currentModelId;return Q.models.find((Z)=>Z.id===Y)??Q.models[0]}),E2=()=>t(($)=>$.config.config?.currentModelId),g4=()=>t(($)=>$.config.config?.agentTeamsEnabled===!0),b0=()=>t(($)=>{return a0.getTheme()}),m4=()=>t(($)=>$.config.config?.codeTheme??"default"),e0=()=>t(($)=>$.focus.currentFocus),p4=()=>t(($)=>$.focus.actions),E$=()=>t(($)=>$.command.isProcessing),c4=()=>t(($)=>$.command.actions),g2=()=>t(($)=>$.command.pendingCommands),x4=()=>t(($)=>$.command.recoveredSteeringCount),m2=()=>t(($)=>$.app.reasoningEffort!=="off"),p2=()=>t(($)=>$.app.reasoningEffort),c2=()=>t(($)=>$.app.serviceTier),x2=()=>t(($)=>$.app.responseVerbosity),u2=()=>t(($)=>$.app.communicationStyle),u4=()=>t(($)=>$.session.currentThinkingContent),l4=()=>t(($)=>$.session.thinkingExpanded),d4=()=>t(($)=>$.session.currentStreamingMessageId),r4=()=>t(uY(($)=>({lines:$.session.currentStreamingLines,tail:$.session.currentStreamingTail,lineCount:$.session.currentStreamingLineCount,version:$.session.currentStreamingVersion}))),a4=()=>t(($)=>$.session.finalizingStreamingMessageId),o4=()=>t(($)=>$.session.historyExpanded),i4=()=>t(($)=>$.session.expandedMessageCount);import{useMemoizedFn as s1}from"ahooks";import{useEffect as c$,useRef as s8}from"react";function dY($){if(!($ instanceof Error))return"未知错误";let J=$.lastError??$;if(J.responseBody)try{let K=JSON.parse(J.responseBody)?.error?.message;if(K){let U=J.statusCode?` (HTTP ${J.statusCode})`:"";return`${K}${U}`}}catch{}let Z=$.message.match(/Last error:\s*(.+)$/);if(Z)return Z[1];return $.message}function rY($){if(!($ instanceof Error))return!1;return $.name==="AbortError"||$.message.includes("aborted")}function aY($){if(!($ instanceof Error))return!1;let Q=$.message;return Q.includes("can only concatenate str")||Q.includes("image_url")||Q.includes("multimodal")||Q.includes("vision")||Q.includes("does not support images")}function l2($){let Q=rY($),Y=aY($),J;if(Y)J="当前模型不支持图片理解功能。请切换到支持视觉能力的模型(如 Claude 4.5、GPT-5.2、Gemini 3 Pro、Qwen3-VL-Plus 等)后重试。";else J=dY($);return{displayMessage:J,isAbort:Q,isVisionNotSupported:Y}}import{appendFileSync as oY,mkdirSync as iY,writeFileSync as nY}from"node:fs";import tY from"node:os";import a8 from"node:path";var n4=null;function sY(){let $=process.env.BLADE_STORAGE_ROOT||a8.join(tY.homedir(),".blade");return a8.join($,"logs","stream-debug.log")}function eY($){if(n4===$)return;let Q=a8.dirname($);iY(Q,{recursive:!0,mode:493}),nY($,`=== Stream Debug Log Started: ${new Date().toISOString()} ===
|
|
2
2
|
`),n4=$}function o8($,Q,Y){try{let J=sY();eY(J);let Z=new Date().toISOString(),X=Y?` | ${JSON.stringify(Y)}`:"",K=`[${Z}] [${$}] ${Q}${X}
|
|
3
3
|
`;oY(J,K)}catch{}}var q2=t1("UI");function Q6($,Q){let Y=!1;return(J)=>{switch(J.kind){case"content_delta":if(Y||$.signal.aborted)break;Q.contentDeltaCount++,Q.contentDeltaTotalLen+=J.delta.length,o8("loopEventHandler","onContentDelta",{callCount:Q.contentDeltaCount,deltaLen:J.delta.length,totalLen:Q.contentDeltaTotalLen}),$.streamingBuffer.batchAppendContent(J.delta);break;case"thinking_delta":if(Y||$.signal.aborted)break;if($.thinkingModeEnabled)$.streamingBuffer.batchAppendThinking(J.delta);break;case"stream_end":{if($.sessionActions.setProviderCircuit(null),$.sessionActions.setProviderRetry(null),$.sessionActions.setProviderStall(null),q2.debug("[loopEventHandler] stream_end",{contentDeltaCount:Q.contentDeltaCount,contentDeltaTotalLen:Q.contentDeltaTotalLen,streamFinalized:Y,signalAborted:$.signal.aborted}),o8("loopEventHandler","onStreamEnd",{contentDeltaCallCount:Q.contentDeltaCount,contentDeltaTotalLen:Q.contentDeltaTotalLen,streamFinalized:Y,signalAborted:$.signal.aborted}),Y||$.signal.aborted){Y=!0;break}let{extraContent:Z,extraThinking:X}=$.streamingBuffer.drainPendingBuffers(),K=$.getStreamingMessageId();if(K){if(Z)g$(K,Z);r2(K)}$.sessionActions.finalizeStreamingMessage(Z,X),Y=!0;break}case"model_fallback":Y=!0,$.sessionActions.setProviderAdmission(null),$.sessionActions.setProviderCircuit(null),$.sessionActions.setProviderRetry(null),$.sessionActions.setProviderStall(null),$.streamingBuffer.resetStreamingBuffers(),$.sessionActions.discardStreamingMessage(),$.sessionActions.setCurrentThinkingContent(null);break;case"provider_admission":{let{kind:Z,...X}=J;$.sessionActions.setProviderAdmission(J.phase==="queued"?X:null);break}case"provider_circuit":{let{kind:Z,...X}=J;$.sessionActions.setProviderCircuit(J.phase==="closed"?null:X);break}case"provider_retry":{let{kind:Z,...X}=J;$.sessionActions.setProviderRetry(J.phase==="recovered"?null:X);break}case"provider_stall":{let{kind:Z,...X}=J;$.sessionActions.setProviderStall(J.phase==="detected"?X:null);break}case"action_stationarity":{let{kind:Z,...X}=J;$.sessionActions.setActionStationarity(J.phase==="recovered"?null:X);break}case"tool_start":{let Z=J.toolCall;if(!("function"in Z))break;if(Z.function.name===d2)break;if(q2.debug("[loopEventHandler] tool_start",{toolName:Z.function.name,toolKind:J.toolKind}),["TaskCreate","TaskUpdate","TaskList"].includes(Z.function.name))break;try{let X=JSON.parse(Z.function.arguments),K=e4(Z.function.name,X);$.sessionActions.addToolMessage(K,{toolCallId:Z.id,toolName:Z.function.name,phase:"start",summary:K,params:X})}catch(X){q2.error("[loopEventHandler] onToolStart error:",X)}break}case"tool_progress":{let Z=J.toolCall;if(!("function"in Z))break;if(Z.function.name===d2)break;let X=J.update.total!==void 0?` ${Math.max(0,Math.min(100,Math.round((J.update.progress??0)/J.update.total*100)))}%`:"",K=`${Z.function.name}${X}: ${J.update.message}`;$.sessionActions.addToolMessage(K,{toolCallId:Z.id,toolName:Z.function.name,phase:"progress",summary:K,...J.update.admission?{admission:J.update.admission}:{}});break}case"tool_result":{let Z=J.toolCall;if(!("function"in Z))break;if(Z.function.name===d2)break;q2.debug("[loopEventHandler] tool_result",{toolName:Z.function.name,success:J.result.success});let X=s4($6(Z.function.name,J.result),t4);$.sessionActions.addToolMessage(X.summary,{toolCallId:Z.id,toolName:Z.function.name,phase:"complete",summary:X.summary,detail:X.detail});break}case"structured_output":$.sessionActions.replaceLastAssistantMessage(JSON.stringify(J.output,null,2));break;case"token_usage":$.sessionActions.updateTokenUsage(J.usage);break;case"compaction":if($.sessionActions.setCompacting(J.phase==="start"),J.phase==="end"){if($.sessionActions.resetContextUsage(),J.outcome!=="failed")Q.compactionCount=(Q.compactionCount??0)+1}break;case"turn_start":q2.debug("[loopEventHandler] turn_start",{turn:J.turn,maxTurns:J.maxTurns}),$.sessionActions.updateTokenUsage({turnCount:J.turn}),$.sessionActions.setProviderCircuit(null),$.sessionActions.setProviderRetry(null),$.sessionActions.setProviderStall(null),Y=!1;break;case"task_update":$.appActions.setTasks(J.tasks);break;case"mcp_catalog_changed":{let Z=`MCP catalog r${J.revision}: +${J.added.length} -${J.removed.length} ~${J.updated.length}`;$.sessionActions.addToolMessage(Z,{toolName:"MCP Catalog",phase:"complete",summary:Z,detail:[J.added.length>0?`Added: ${J.added.join(", ")}`:"",J.removed.length>0?`Removed: ${J.removed.join(", ")}`:"",J.updated.length>0?`Updated: ${J.updated.join(", ")}`:""].filter(Boolean).join(`
|
|
4
4
|
`)});break}case"mcp_content_changed":{let Z=`MCP ${J.contentKind} r${J.revision}: +${J.added.length} -${J.removed.length} ~${J.updated.length}`;$.sessionActions.addToolMessage(Z,{toolName:"MCP Content",phase:"complete",summary:Z,detail:[J.added.length>0?`Added: ${J.added.join(", ")}`:"",J.removed.length>0?`Removed: ${J.removed.join(", ")}`:"",J.updated.length>0?`Updated: ${J.updated.join(", ")}`:""].filter(Boolean).join(`
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import"./chunk-v508x7cg.js";import{pg as Q}from"./chunk-
|
|
2
|
-
`);try{let{rebuildProjectionIndex:z}=await import("./chunk-4mgjj8zg.js"),{SessionService:B}=await import("./chunk-
|
|
1
|
+
import"./chunk-v508x7cg.js";import{pg as Q}from"./chunk-zph2jekm.js";import"./chunk-qp8mejbn.js";import"./chunk-c03xn5s3.js";import"./chunk-yjbq4jeg.js";import{Fg as L}from"./chunk-22aaybx2.js";import"./chunk-qtt17d5s.js";import"./chunk-2qqmmxqf.js";import"./chunk-gbrwzpyg.js";import"./chunk-bj5msq36.js";import"./chunk-c74e0jx1.js";import"./chunk-yz80dp1a.js";import"./chunk-p7ww2tcn.js";import"./chunk-qw5j84ny.js";import{Nh as F}from"./chunk-99nevk7k.js";var K=[22,19,0];function T(G){let A=/^v?(\d+)\.(\d+)\.(\d+)/.exec(G);if(!A)return!1;let H=A.slice(1).map(Number);for(let z=0;z<K.length;z++){let B=H[z]??0,J=K[z];if(B!==J)return B>J}return!0}var X={command:"doctor",describe:"Check the health of your Blade installation",builder:(G)=>G.option("rebuild-index",{type:"boolean",default:!1,describe:"Rebuild the SQLite session index from JSONL transcripts"}),handler:async(G)=>{if(G.rebuildIndex){console.log(`Rebuilding session index from JSONL transcripts...
|
|
2
|
+
`);try{let{rebuildProjectionIndex:z}=await import("./chunk-4mgjj8zg.js"),{SessionService:B}=await import("./chunk-fpkq3ch3.js"),J=await z(B.projectionDeriverForSearch());if(J===null)console.log("[WARN] Session index unavailable (SQLite driver missing); reads fall back to JSONL scan.");else console.log(`[OK] Session index rebuilt: ${J} session(s) indexed.`)}catch(z){console.log("[FAIL] Session index rebuild failed"),console.log(` Error: ${z instanceof Error?z.message:"未知错误"}`),process.exit(1)}return}console.log(`Running Blade health check...
|
|
3
3
|
`);let A=0;try{await Q.getInstance().initialize(),console.log("[OK] Configuration: OK")}catch(z){console.log("[FAIL] Configuration: FAILED"),console.log(` Error: ${z instanceof Error?z.message:"未知错误"}`),A++}let H=process.version;if(T(H))console.log(`[OK] Node.js version: ${H}`);else console.log(`[WARN] Node.js version: ${H} (required: >=22.19.0)`),A++;try{let z=await import("fs/promises"),B=L();await z.access(B,(await import("fs")).constants.R_OK|(await import("fs")).constants.W_OK),console.log("[OK] File system permissions: OK")}catch(z){console.log("[FAIL] File system permissions: FAILED"),console.log(" Error: Cannot read/write in current directory"),A++}try{await import("ink"),console.log("[OK] Dependencies: OK")}catch(z){console.log("[FAIL] Dependencies: FAILED"),console.log(" Error: Missing required dependencies"),A++}if(console.log(`
|
|
4
4
|
Health Check Summary:`),A===0)console.log("All checks passed! Blade is ready to use.");else console.log(`Warning: Found ${A} issue(s). Please resolve them for optimal performance.`),process.exit(1)}};export{T as isSupportedNodeVersion,X as doctorCommands};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{$f as I,_f as H}from"./chunk-
|
|
1
|
+
import{$f as I,_f as H}from"./chunk-zph2jekm.js";import{Mutex as J}from"async-mutex";class B extends Error{limit;resource="resident_runtimes";retryable=!0;constructor(b){super("Session runtime capacity is full");this.limit=b;this.name="SessionRuntimeCapacityError"}}class D extends Error{constructor(){super("Session runtime residency is closed");this.name="SessionRuntimeResidencyClosedError"}}class A extends Error{constructor(b){super(`Session runtime residency already owns key: ${b}`);this.name="SessionRuntimeResidencyConflictError"}}class K{maxResident;idleMs;now;residents=new Map;reservations=new Map;operations=new J;nextGeneration=1;closed=!1;constructor(b){if(!H(b.maxResident))throw Error("Invalid max resident Session Runtime limit");if(!I(b.idleMs))throw Error("Invalid Session Runtime idle timeout");this.maxResident=b.maxResident,this.idleMs=b.idleMs,this.now=b.now??Date.now}acquire(b){let j=this.residents.get(b);if(!j||j.poisoned)return;return j.pins++,j.lastUsedAt=this.now(),this.createLease(j)}owns(b,j){let q=this.residents.get(b);return Boolean(q&&(j===void 0||q.value===j))}async reserve(b,j){if(!b.trim())throw Error("Session runtime residency key must not be blank");return this.operations.runExclusive(async()=>{if(this.closed)throw new D;if(this.residents.has(b)||this.reservations.has(b))throw new A(b);while(this.retainedCount()>=this.maxResident){if(!j.allowEviction)throw new B(this.maxResident);let z=this.oldestEvictableWebResident();if(!z)throw new B(this.maxResident);await this.disposeResident(z,!0)}let q={generation:this.allocateGeneration(),surface:j.surface};return this.reservations.set(b,q),this.createReservation(b,q)})}async remove(b,j){return this.operations.runExclusive(async()=>{let q=this.residents.get(b);if(!q||j!==void 0&&q.value!==j)return!1;if(q.pins>0)return!1;return await this.disposeResident(q,!0),!0})}async forget(b,j){return this.operations.runExclusive(async()=>{let q=this.residents.get(b);if(!q||j!==void 0&&q.value!==j||q.pins>0)return!1;return this.residents.delete(b),!0})}async sweepIdle(){return this.operations.runExclusive(async()=>{if(this.closed)return 0;let b=0;while(!0){let j=this.oldestIdleWebResident();if(!j)return b;await this.disposeResident(j,!0),b++}})}async disposeAll(){await this.operations.runExclusive(async()=>{this.closed=!0,this.reservations.clear();let b;for(let j of[...this.residents.values()])try{await this.disposeResident(j,!1)}catch(q){b??=q}if(this.residents.clear(),b!==void 0)throw b})}getStats(){let b=0;for(let j of this.residents.values())if(j.pins>0)b++;return{resident:this.residents.size,reserved:this.reservations.size,pinned:b,maxResident:this.maxResident}}retainedCount(){return this.residents.size+this.reservations.size}allocateGeneration(){let b=this.nextGeneration;return this.nextGeneration=this.nextGeneration===Number.MAX_SAFE_INTEGER?1:this.nextGeneration+1,b}createReservation(b,j){let q=!1;return{commit:(z)=>{if(q)throw new A(b);if(z.key!==b||z.surface!==j.surface||this.reservations.get(b)!==j||this.closed)throw this.reservations.delete(b),q=!0,this.closed?new D:new A(b);this.reservations.delete(b);let G={...z,generation:j.generation,pins:1,lastUsedAt:this.now(),poisoned:!1};return this.residents.set(b,G),q=!0,this.createLease(G)},cancel:()=>{if(q)return;if(this.reservations.get(b)===j)this.reservations.delete(b);q=!0}}}createLease(b){let j=!1;return{value:b.value,release:()=>{if(j)return;j=!0;let q=this.residents.get(b.key);if(q!==b||q.generation!==b.generation)return;q.pins=Math.max(0,q.pins-1),q.lastUsedAt=this.now()}}}oldestEvictableWebResident(){return this.sortedWebResidents().find((b)=>this.canEvict(b))}oldestIdleWebResident(){let b=this.now();return this.sortedWebResidents().find((j)=>b-j.lastUsedAt>=this.idleMs&&this.canEvict(j))}sortedWebResidents(){return[...this.residents.values()].filter((b)=>b.surface==="web").sort((b,j)=>b.lastUsedAt-j.lastUsedAt||b.generation-j.generation)}canEvict(b){if(b.pins>0||b.poisoned)return!1;try{return b.canEvict()}catch{return!1}}async disposeResident(b,j){if(this.residents.get(b.key)!==b)return;this.residents.delete(b.key);try{await b.dispose()}catch(q){if(j&&!this.closed&&!this.residents.has(b.key))b.lastUsedAt=this.now(),b.poisoned=!0,this.residents.set(b.key,b);throw q}}}
|
|
2
2
|
export{B as s,K as t};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{m as R,n as c,o as g,p as d,q as m,r as l}from"./chunk-
|
|
1
|
+
import{m as R,n as c,o as g,p as d,q as m,r as l}from"./chunk-v4ek6q8t.js";import{R as M,Z as y}from"./chunk-kb5xaar0.js";import"./chunk-yk8s8kjt.js";import"./chunk-22s3r2xy.js";import{Fb as A,wb as h}from"./chunk-g3fbgp1k.js";import"./chunk-fbgzeb3m.js";import{Ic as w,Wc as U}from"./chunk-57jj40er.js";import"./chunk-qyxbee3w.js";import"./chunk-r297pq3s.js";import{sd as C}from"./chunk-gz2fx7th.js";import{ud as I,vd as S,wd as v}from"./chunk-d2eahefk.js";import{xd as O}from"./chunk-4ppgfhqd.js";import"./chunk-2m4mgw58.js";import{Ud as P}from"./chunk-xts31qj4.js";import"./chunk-v508x7cg.js";import"./chunk-xkz9ecdx.js";import"./chunk-rjgfy07e.js";import"./chunk-2faga011.js";import"./chunk-xbj18hxh.js";import"./chunk-22sw5bv4.js";import"./chunk-rdtgv0n8.js";import"./chunk-kaf6m50a.js";import"./chunk-0cbpjhq7.js";import"./chunk-rc7jnds2.js";import"./chunk-egp0crrc.js";import"./chunk-03947xkg.js";import"./chunk-zph2jekm.js";import{rg as F}from"./chunk-qp8mejbn.js";import"./chunk-c03xn5s3.js";import"./chunk-yjbq4jeg.js";import{Fg as z}from"./chunk-22aaybx2.js";import"./chunk-qtt17d5s.js";import"./chunk-2qqmmxqf.js";import"./chunk-gbrwzpyg.js";import"./chunk-bj5msq36.js";import"./chunk-c74e0jx1.js";import"./chunk-yz80dp1a.js";import"./chunk-p7ww2tcn.js";import"./chunk-qw5j84ny.js";import"./chunk-99nevk7k.js";import p from"yargs";import{hideBin as e}from"yargs/helpers";var s=new Set(Object.values(F));function t(j){if(j&&s.has(j))return j;return}function x(j){if(j.options.outputFormat==="json")j.io.stdout.write(`${JSON.stringify({response:j.response,...j.structuredOutput?{structured_output:j.structuredOutput,output_schema_digest:j.structuredOutputSchemaDigest}:{},input:j.requestInput,model:j.options.model,timestamp:new Date().toISOString()},null,2)}
|
|
2
2
|
`);else if(j.options.outputFormat==="stream-json")j.io.stdout.write(`${JSON.stringify(j.structuredOutput?{type:"structured_output",output:j.structuredOutput,schema_digest:j.structuredOutputSchemaDigest}:{type:"response",content:j.response})}
|
|
3
3
|
`);else j.io.stdout.write(`${j.response}
|
|
4
4
|
`)}function i(j){return j.command("* [message]","Print response and exit (useful for pipes)",(B)=>B.positional("message",{describe:"Message to process",type:"string"}).option("p",{alias:"print",describe:"Print response and exit (useful for pipes)",type:"boolean"}).option("output-format",{describe:'Output format: "text", "json", "stream-json"',type:"string",default:"text"}).option("include-partial-messages",{describe:"Include partial message chunks as they arrive",type:"boolean"}).option("input-format",{describe:'Input format: "text", "stream-json"',type:"string",default:"text"}).option("json-schema",{alias:["jsonSchema"],describe:"Inline JSON Schema for the structured final response",type:"string"}).option("output-schema",{alias:["outputSchema"],describe:"Path to a JSON Schema file for the structured final response",type:"string"}).option("model",{describe:"Model for the current session",type:"string"}).option("append-system-prompt",{describe:"Append a system prompt to the default system prompt",type:"string"}).option("system-prompt",{describe:"Replace the default system prompt",type:"string"}).option("max-turns",{alias:["maxTurns"],describe:"Maximum conversation turns (-1: unlimited, N>0: limit to N turns)",type:"number"}),async(B)=>{if(!B.p)return;let q=await n(B);process.exit(q)})}async function n(j,B=process){let q;try{await R();let _=j.forkSession!==!0&&(j.continue===!0||typeof j.resume==="string"&&j.resume.length>0)?await g({message:j.message,_:j._}):await c({message:j.message,_:j._,defaultMessage:"Hello"}),J=_===void 0,T=J?{mode:"agent",content:""}:await d(_);if(T.mode==="output"){if(T.content)B.stdout.write(`${T.content}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{Xe as j1,Ye as L0,Ze as F1}from"./chunk-kaf6m50a.js";import{bf as WO,cf as IO}from"./chunk-0cbpjhq7.js";import{ff as B1}from"./chunk-rc7jnds2.js";import{gf as b0,if as J0}from"./chunk-
|
|
1
|
+
import{Xe as j1,Ye as L0,Ze as F1}from"./chunk-kaf6m50a.js";import{bf as WO,cf as IO}from"./chunk-0cbpjhq7.js";import{ff as B1}from"./chunk-rc7jnds2.js";import{gf as b0,if as J0}from"./chunk-egp0crrc.js";import{kg as z0,lg as $O,pg as I0}from"./chunk-zph2jekm.js";import{tg as u,vg as L,yg as P1}from"./chunk-c03xn5s3.js";import{Fg as M}from"./chunk-22aaybx2.js";import{fh as k,gh as z}from"./chunk-2qqmmxqf.js";import{th as g0}from"./chunk-c74e0jx1.js";import{Ah as N}from"./chunk-yz80dp1a.js";import Y1 from"node:path";import QO from"node:path";import R0 from"node:fs";import X0 from"node:os";import R from"node:path";import EO from"yaml";var Q4={type:"object",properties:{verdict:{type:"string",enum:["pass","fail","partial"]},summary:{type:"string",minLength:1,maxLength:2000},findings:{type:"array",maxItems:50,items:{type:"string",minLength:1,maxLength:1000}}},required:["verdict","summary","findings"],additionalProperties:!1};function Z4(O){if(!O||typeof O!=="object"||Array.isArray(O))return;let $=O.verdict;return $==="pass"||$==="fail"||$==="partial"?$:void 0}var NO=`# Goal Completion Verifier
|
|
2
2
|
|
|
3
3
|
You are a fresh, independent, adversarial verifier. The parent Agent has claimed
|
|
4
4
|
that a persisted goal is complete. Your job is to refute that claim unless the
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{Qd as N}from"./chunk-
|
|
1
|
+
import{Qd as N}from"./chunk-xts31qj4.js";import{if as $}from"./chunk-egp0crrc.js";import{Fg as _}from"./chunk-22aaybx2.js";import{dh as Y,fh as Z}from"./chunk-2qqmmxqf.js";function X(){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[?1004l"),process.stdout.write("\x1B[?1l\x1B>"),process.stdout.write("\x1B[?25h"),process.stdout.write("\x1B[0m")}var z=Z("Service");function E(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 B{static instance=null;cleanupHandlers=[];isShuttingDown=!1;initialized=!1;lastSigintTime=0;SIGINT_DOUBLE_CLICK_WINDOW=3000;constructor(){}static getInstance(){if(!B.instance)B.instance=new B;return B.instance}initialize(){if(this.initialized){z.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",()=>{z.info("[GracefulShutdown] 收到 SIGTERM 信号"),this.shutdown("SIGTERM",0)}),process.on("SIGINT",()=>{let b=Date.now();if(b-this.lastSigintTime<this.SIGINT_DOUBLE_CLICK_WINDOW)z.info("[GracefulShutdown] 收到第二次 SIGINT 信号,执行退出"),this.shutdown("SIGINT",0);else z.info("[GracefulShutdown] 收到第一次 SIGINT 信号,再按一次退出"),this.lastSigintTime=b,console.log(`
|
|
2
2
|
再按一次 Ctrl+C 退出
|
|
3
3
|
`)}),this.initialized=!0,z.debug("[GracefulShutdown] 全局错误处理器已初始化")}registerCleanup(b){return this.cleanupHandlers.push(b),z.debug(`[GracefulShutdown] 注册清理函数,当前共 ${this.cleanupHandlers.length} 个`),()=>{let q=this.cleanupHandlers.indexOf(b);if(q!==-1)this.cleanupHandlers.splice(q,1),z.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){z.debug("[GracefulShutdown] 已在退出过程中,跳过重复退出");return}this.isShuttingDown=!0;try{N().command.actions.abort("process-shutdown")}catch(A){z.warn("[GracefulShutdown] Failed to abort the active command",A)}z.info(`[GracefulShutdown] 开始优雅退出 (原因: ${b})`);let Q=setTimeout(()=>{X(),process.exit(q)},5000);Q.unref?.();let U=4000,K;try{await Promise.race([this.runCleanupHandlers(),new Promise((A,J)=>{K=setTimeout(()=>{J(Error(`清理超时 (${U}ms)`))},U),K.unref?.()})])}catch(A){console.error("[GracefulShutdown] 清理过程中发生错误:",A)}finally{if(K)clearTimeout(K)}try{let A=$.getInstance(),J=N(),V=J.session?.sessionId||"unknown",W=J.session?.workspaceRoot||_();if(A.isEnabled(W,V)){let v=J.config?.config?.permissionMode||"default";await A.executeSessionEndHooks(E(b),{projectDir:W,sessionId:V,permissionMode:v})}}catch(A){console.error("[GracefulShutdown] SessionEnd hooks 执行失败:",A)}try{await Y()}catch{}clearTimeout(Q),X(),setTimeout(()=>{process.exit(q)},100)}async runCleanupHandlers(){let b=[...this.cleanupHandlers].reverse();for(let q of b)try{let F=q();if(F instanceof Promise)await F}catch(F){console.error("[GracefulShutdown] 清理函数执行失败:",F)}}isExiting(){return this.isShuttingDown}reset(){this.isShuttingDown=!1,this.cleanupHandlers=[],this.initialized=!1}}var O=()=>{return B.getInstance()},y=(b)=>{return O().registerCleanup(b)},j=()=>{O().initialize()},C=(b=0)=>{O().shutdown("normal",b)};
|
|
4
4
|
export{O as yd,y as zd,j as Ad,C as Bd};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{f as a,g as i,h as l,i as m}from"./chunk-
|
|
1
|
+
import{f as a,g as i,h as l,i as m}from"./chunk-5tat9wy9.js";import"./chunk-1zkwxaa0.js";import"./chunk-h4d37zt2.js";import"./chunk-nfyxb2q5.js";import"./chunk-agxs6rwh.js";import"./chunk-6bka1j4q.js";import"./chunk-kb5xaar0.js";import"./chunk-yk8s8kjt.js";import"./chunk-22s3r2xy.js";import"./chunk-g3fbgp1k.js";import"./chunk-fbgzeb3m.js";import"./chunk-57jj40er.js";import"./chunk-qyxbee3w.js";import"./chunk-r297pq3s.js";import{zd as n}from"./chunk-s7gf2ds9.js";import"./chunk-2m4mgw58.js";import{Vd as s}from"./chunk-xts31qj4.js";import"./chunk-v508x7cg.js";import"./chunk-xkz9ecdx.js";import"./chunk-rjgfy07e.js";import"./chunk-2faga011.js";import"./chunk-xbj18hxh.js";import"./chunk-22sw5bv4.js";import"./chunk-rdtgv0n8.js";import"./chunk-kaf6m50a.js";import"./chunk-0cbpjhq7.js";import"./chunk-rc7jnds2.js";import"./chunk-egp0crrc.js";import"./chunk-03947xkg.js";import"./chunk-zph2jekm.js";import"./chunk-qp8mejbn.js";import"./chunk-c03xn5s3.js";import"./chunk-yjbq4jeg.js";import"./chunk-22aaybx2.js";import"./chunk-qtt17d5s.js";import"./chunk-2qqmmxqf.js";import"./chunk-gbrwzpyg.js";import"./chunk-bj5msq36.js";import"./chunk-c74e0jx1.js";import"./chunk-yz80dp1a.js";import"./chunk-p7ww2tcn.js";import"./chunk-qw5j84ny.js";import"./chunk-99nevk7k.js";import v from"chalk";var C={command:"serve",describe:"Start a headless Blade server (no browser)",builder:a,handler:async(p)=>{let r=i(p);if(await s(),!process.env.BLADE_SERVER_PASSWORD)console.log(v.yellow("Warning: BLADE_SERVER_PASSWORD is not set; server is unsecured."));let e=await m.listenAsync(r);if(console.log(`Blade server listening on http://${e.hostname}:${e.port}`),r.hostname==="0.0.0.0"){let o=l();for(let g of o)console.log(` Network: http://${g}:${e.port}`)}let t,c=new Promise((o)=>{t=o}),d=n(async()=>{await e.stop(),t()});try{await c}finally{d(),await e.stop()}}};export{C as serveCommand};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Ne as a,Oe as b,Pe as c,Qe as d,Re as e,Se as f,Te as g,Ue as h,Ve as i,We as j}from"./chunk-
|
|
1
|
+
import{Ne as a,Oe as b,Pe as c,Qe as d,Re as e,Se as f,Te as g,Ue as h,Ve as i,We as j}from"./chunk-rdtgv0n8.js";import"./chunk-kaf6m50a.js";import"./chunk-0cbpjhq7.js";import"./chunk-rc7jnds2.js";import"./chunk-egp0crrc.js";import"./chunk-03947xkg.js";import"./chunk-zph2jekm.js";import"./chunk-qp8mejbn.js";import"./chunk-c03xn5s3.js";import"./chunk-yjbq4jeg.js";import"./chunk-22aaybx2.js";import"./chunk-qtt17d5s.js";import"./chunk-2qqmmxqf.js";import"./chunk-gbrwzpyg.js";import"./chunk-bj5msq36.js";import"./chunk-c74e0jx1.js";import"./chunk-yz80dp1a.js";import"./chunk-p7ww2tcn.js";import"./chunk-qw5j84ny.js";import"./chunk-99nevk7k.js";export{g as withWorkspaceAgentResources,i as snapshotWorkspaceAgentResources,f as resolveWorkspaceAgentResources,j as resetWorkspaceAgentResources,d as refreshWorkspaceCommunicationStyles,h as getWorkspaceAgentResourceCacheStats,e as configureInvocationPluginDirs,c as WorkspaceAgentResourceCapacityError,a as MAX_RESIDENT_WORKSPACE_AGENT_RESOURCES,b as MAX_ACTIVE_WORKSPACE_AGENT_RESOURCES};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{th as S}from"./chunk-
|
|
1
|
+
import{th as S}from"./chunk-c74e0jx1.js";import{Nh as f}from"./chunk-99nevk7k.js";import*as $ from"fs/promises";import*as K from"path";import j from"semver";import{ProxyAgent as H,fetch as I}from"undici";function R(){return process.env.HTTPS_PROXY||process.env.HTTP_PROXY||process.env.https_proxy||process.env.http_proxy}function N(){let q=R();if(q)try{return new H(q)}catch(z){console.warn(`[proxyFetch] Invalid proxy URL: ${q}`)}return}async function M(q,z={}){let{timeout:W=30000,signal:Q,...B}=z;if(Q?.aborted)throw new DOMException("The operation was aborted.","AbortError");let J=N(),X=new AbortController,Y=!1,F=setTimeout(()=>{Y=!0,X.abort()},W),b=()=>X.abort();Q?.addEventListener("abort",b);try{let Z={method:B.method,headers:B.headers,body:B.body,signal:X.signal,dispatcher:J};return await I(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",b)}}var w="blade-code",y="https://cdn.jsdelivr.net/npm/blade-code@latest/CHANGELOG.md",G=K.join(process.env.HOME||process.env.USERPROFILE||".",".blade"),O=K.join(G,"version-cache.json"),P=3600000,k=`https://registry.npmjs.org/${w}/latest`;async function L(){try{if(process.env.BLADE_VERSION)return process.env.BLADE_VERSION;return S()}catch{return"unknown"}}async function T(){try{let q=await $.readFile(O,"utf-8"),z=JSON.parse(q);if(Date.now()-z.checkedAt<P)return z;return{...z,checkedAt:0}}catch{return null}}async function D(q){try{await $.mkdir(G,{recursive:!0,mode:493}),await $.writeFile(O,JSON.stringify(q,null,2))}catch{}}async function x(){try{let q=await M(k,{timeout:5000,headers:{Accept:"application/json"}});if(!q.ok)return null;return(await q.json()).version||null}catch{return null}}async function _(q=!1){let z=await L(),W=y;if(z==="unknown")return{currentVersion:z,latestVersion:null,hasUpdate:!1,shouldPrompt:!1,releaseNotesUrl:W,error:"Unable to determine current version"};let Q=await T(),B=Q?.skipUntilVersion,J=null;if(!q&&Q?.latestVersion&&Q.checkedAt>0)J=Q.latestVersion;else if(J=await x(),J)await D({latestVersion:J,checkedAt:Date.now(),skipUntilVersion:B});else if(Q?.latestVersion)await D({checkedAt:0,skipUntilVersion:B});if(!J||!j.valid(J))return{currentVersion:z,latestVersion:null,hasUpdate:!1,shouldPrompt:!1,releaseNotesUrl:W,error:"Unable to check for updates"};if(j.lt(J,z))J=z,await D({latestVersion:J,checkedAt:Date.now(),skipUntilVersion:B});let X=j.gt(J,z),Y=X;if(X&&B)Y=j.gt(J,B);return{currentVersion:z,latestVersion:J,hasUpdate:X,shouldPrompt:Y,releaseNotesUrl:W}}async function u(q){let z=await T();await D({latestVersion:z?.latestVersion??q,checkedAt:z?.checkedAt||Date.now(),skipUntilVersion:q})}function g(){return`npm install -g ${w}@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 V(){try{let q=await _();return q.shouldPrompt?q:null}catch{return null}}
|
|
2
2
|
export{_ as a,u as b,g as c,C as d,V as e};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{$d as m,Pd as a,Qd as b,Rd as c,Sd as d,Td as e,Ud as f,Vd as g,Wd as h,Xd as i,Yd as j,Zd as k,_d as l,ae as n,be as o,ce as p,de as q}from"./chunk-
|
|
1
|
+
import{$d as m,Pd as a,Qd as b,Rd as c,Sd as d,Td as e,Ud as f,Vd as g,Wd as h,Xd as i,Yd as j,Zd as k,_d as l,ae as n,be as o,ce as p,de as q}from"./chunk-xts31qj4.js";import"./chunk-v508x7cg.js";import"./chunk-xkz9ecdx.js";import"./chunk-zph2jekm.js";import"./chunk-qp8mejbn.js";import"./chunk-c03xn5s3.js";import"./chunk-yjbq4jeg.js";import"./chunk-22aaybx2.js";import"./chunk-qtt17d5s.js";import"./chunk-2qqmmxqf.js";import"./chunk-gbrwzpyg.js";import"./chunk-bj5msq36.js";import"./chunk-c74e0jx1.js";import"./chunk-yz80dp1a.js";import"./chunk-p7ww2tcn.js";import"./chunk-qw5j84ny.js";import"./chunk-99nevk7k.js";export{a as vanillaStore,c as sessionActions,l as getThinkingModeEnabled,b as getState,n as getServiceTier,o as getResponseVerbosity,m as getReasoningEffort,j as getModelById,e as getMessages,k as getMcpServers,i as getCurrentModel,f as getConfig,p as getCommunicationStyle,h as getAllModels,g as ensureStoreInitialized,q as configActions,d as appActions};
|