blade-code 0.10.119 → 0.10.120
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-mtaqnt1q.js → chunk-0fyy97rq.js} +1 -1
- package/dist/{chunk-pd9d22ss.js → chunk-150w9kq4.js} +1 -1
- package/dist/{chunk-g8hcxgg8.js → chunk-1qbq7x98.js} +1 -1
- package/dist/{chunk-bzaz3335.js → chunk-2v8fyvmh.js} +1 -1
- package/dist/{chunk-jekst6kh.js → chunk-2w10er3y.js} +1 -1
- package/dist/{chunk-qvqqapft.js → chunk-36k5c6wy.js} +1 -1
- package/dist/{chunk-jvnf66a0.js → chunk-40pzrpjc.js} +1 -1
- package/dist/{chunk-dxjn1stn.js → chunk-49javhkx.js} +1 -1
- package/dist/{chunk-yy0a99es.js → chunk-4de6e3am.js} +1 -1
- package/dist/{chunk-82dckkw7.js → chunk-4jaqzjtw.js} +1 -1
- package/dist/{chunk-6437f0h4.js → chunk-56fb0ece.js} +1 -1
- package/dist/{chunk-b8a0sphn.js → chunk-5hmeb6yk.js} +1 -1
- package/dist/{chunk-ka1915vs.js → chunk-6h0kgpgv.js} +1 -1
- package/dist/{chunk-saasrzn4.js → chunk-6k7s3c7y.js} +1 -1
- package/dist/{chunk-h25505f0.js → chunk-7k72dxwe.js} +1 -1
- package/dist/{chunk-8q0a693b.js → chunk-8mqbaptr.js} +1 -1
- package/dist/{chunk-xede4817.js → chunk-c5291k2x.js} +1 -1
- package/dist/chunk-cmcgqa1d.js +1 -0
- package/dist/{chunk-et8gsz80.js → chunk-dfcc8q87.js} +2 -2
- package/dist/{chunk-xvn45j67.js → chunk-dspjxf4c.js} +1 -1
- package/dist/{chunk-p357ac7b.js → chunk-exv1nb2x.js} +1 -1
- package/dist/{chunk-60092knz.js → chunk-gjw3g2jd.js} +1 -1
- package/dist/{chunk-esk028rd.js → chunk-j2pgrrkb.js} +1 -1
- package/dist/{chunk-h6hjbmk9.js → chunk-j8hzgacj.js} +1 -1
- package/dist/{chunk-2jdnjmbh.js → chunk-jn25d5qv.js} +1 -1
- package/dist/{chunk-057qv2wd.js → chunk-kvf61fb1.js} +1 -1
- package/dist/{chunk-txzgwgqk.js → chunk-kzzw1kwk.js} +1 -1
- package/dist/{chunk-8nm03qtd.js → chunk-m9vhf4dg.js} +1 -1
- package/dist/{chunk-aeyvj4h8.js → chunk-ne40tv38.js} +1 -1
- package/dist/chunk-qp8qcmx0.js +1 -0
- package/dist/{chunk-d5kjq9p5.js → chunk-scgq3g37.js} +4 -4
- package/dist/{chunk-4v2t1xs5.js → chunk-sefdw1mm.js} +1 -1
- package/dist/{chunk-ncsp5n4k.js → chunk-t169d8dc.js} +1 -1
- package/dist/{chunk-yt07a4zp.js → chunk-v95hk3fw.js} +1 -1
- package/dist/{chunk-hna3c2ck.js → chunk-x4t1v4rb.js} +3 -3
- package/dist/{chunk-ar8a7kmt.js → chunk-y1n8nf5w.js} +1 -1
- package/dist/{chunk-5s4knzbg.js → chunk-zp8d0ma8.js} +1 -1
- package/package.json +1 -1
- package/dist/chunk-b916gtwm.js +0 -1
- package/dist/chunk-g7ed3sfy.js +0 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{$d as n,ae as F$,be as h_,ce as D$,de as j,ee as c_,fe as f$,ge as n_,he as z$,ie as l_,je as p_,le as d0,oe as i_,pe as x$}from"./chunk-7dykmcjj.js";import{uf as D0}from"./chunk-8qp8v96d.js";import{mg as f0}from"./chunk-adkpwx6c.js";import{yg as a1}from"./chunk-2t6b962t.js";import{Lh as K$,Mh as M$,Nh as B0,Oh as g0,Ph as W0}from"./chunk-pykxe413.js";import{Th as B1}from"./chunk-kzzty3v5.js";import{ti as h0}from"./chunk-w4xqaw4h.js";import{Ai as M0,Di as F0}from"./chunk-a4dmw23t.js";import{Hi as a}from"./chunk-
|
|
1
|
+
import{$d as n,ae as F$,be as h_,ce as D$,de as j,ee as c_,fe as f$,ge as n_,he as z$,ie as l_,je as p_,le as d0,oe as i_,pe as x$}from"./chunk-7dykmcjj.js";import{uf as D0}from"./chunk-8qp8v96d.js";import{mg as f0}from"./chunk-adkpwx6c.js";import{yg as a1}from"./chunk-2t6b962t.js";import{Lh as K$,Mh as M$,Nh as B0,Oh as g0,Ph as W0}from"./chunk-pykxe413.js";import{Th as B1}from"./chunk-kzzty3v5.js";import{ti as h0}from"./chunk-w4xqaw4h.js";import{Ai as M0,Di as F0}from"./chunk-a4dmw23t.js";import{Hi as a}from"./chunk-5hmeb6yk.js";import{Ri as q$,Si as Q0,Ti as A$,Ui as x,Vi as u,Xi as A0,Yi as t,Zi as k}from"./chunk-spxb931p.js";import{readdir as v_,readFile as T0,rm as G0,stat as o0}from"node:fs/promises";import*as Y from"node:path";import{nanoid as P}from"nanoid";import{createHash as u$,randomUUID as h$}from"node:crypto";import*as h from"node:fs/promises";import*as b0 from"node:path";import{execFileSync as j$}from"node:child_process";import{createHash as y$}from"node:crypto";import{readFileSync as I$}from"node:fs";var m$=/^[a-f0-9]{64}$/;function O1(_){if(!_||typeof _!=="object")return!1;let $=_;return($.platform==="linux"||$.platform==="darwin"||$.platform==="win32")&&typeof $.fingerprint==="string"&&m$.test($.fingerprint)}var T1={readFile:(_)=>I$(_,"utf8"),execFile:(_,$)=>j$(_,$,{encoding:"utf8",timeout:_==="powershell.exe"?3000:2000,windowsHide:!0})},v$=(_)=>{try{return process.kill(_,0),!0}catch($){return $ instanceof Error&&"code"in $&&$.code==="EPERM"}};function X_(_,$){return{platform:_,fingerprint:y$("sha256").update(`${_}\x00${$}`).digest("hex")}}function P$(_,$){let R=$.readFile(`/proc/${_}/stat`).trim(),O=R.lastIndexOf(")");if(O<0)throw Error("Invalid /proc process stat");let T=R.slice(O+2).split(/\s+/)[19];if(!T||!/^\d+$/.test(T))throw Error("Missing process start ticks");return T}function x0(_,$=process.platform,R=T1){if(!Number.isInteger(_)||_<=1)return;try{if($==="linux")return X_($,P$(_,R));if($==="darwin"){let O=R.execFile("ps",["-o","lstart=","-p",String(_)]).trim();return O?X_($,O):void 0}if($==="win32"){let O=`(Get-CimInstance Win32_Process -Filter "ProcessId = ${_}").CreationDate.ToUniversalTime().ToString('O')`,X=R.execFile("powershell.exe",["-NoProfile","-NonInteractive","-Command",O]).trim();return X?X_($,X):void 0}}catch{return}return}function X1(_,$){return x0(_,$.platform)?.fingerprint===$.fingerprint}function j2(_,$,R=T1,O=v$){if(!Number.isInteger(_)||_<=1)return!1;let X=x0(_,$.platform,R);if(X)return X.fingerprint===$.fingerprint;return!O(_)}var C1=1;function c$(_,$){let R=u$("sha256").update($).digest("hex");return b0.join(Q0(_),".locks",`${R}.lock`)}function w0(_,$){return _ instanceof Error&&"code"in _&&_.code===$}async function L_(_){try{let $=JSON.parse(await h.readFile(_,"utf8"));if($.version!==C1||typeof $.sessionId!=="string"||typeof $.ownerId!=="string"||!Number.isInteger($.pid)||($.pid??0)<=0||$.processIdentity!==void 0&&!O1($.processIdentity)||typeof $.acquiredAt!=="string")return;return $}catch{return}}async function L1(_){let $=await L_(_);if($)return $;return await new Promise((R)=>setTimeout(R,10)),L_(_)}function n$(_){try{return process.kill(_,0),!0}catch($){return w0($,"EPERM")}}async function W1(_,$){let R;try{return R=await h.open(_,"wx",384),await R.writeFile(`${JSON.stringify($)}
|
|
2
2
|
`,"utf8"),!0}catch(O){if(w0(O,"EEXIST"))return!1;if(R)await h.unlink(_).catch(()=>{return});throw O}finally{await R?.close().catch(()=>{return})}}class d extends Error{code="BLADE_SESSION_IN_USE";constructor(_){super(_?`Session is already active in another Blade process (PID ${_}). Stop that process or choose a different session.`:"Session is already active in another Blade process. Stop that process or choose a different session.");this.name="SessionInUseError"}}class o{filePath;record;released=!1;constructor(_,$){this.filePath=_;this.record=$}static async acquire(_,$=B1()){let R=c$($,_),O={version:C1,sessionId:_,ownerId:h$(),pid:process.pid,processIdentity:x0(process.pid),acquiredAt:new Date().toISOString()};if(await h.mkdir(b0.dirname(R),{recursive:!0,mode:448}),await W1(R,O))return new o(R,O);let X=await L1(R);if(X&&n$(X.pid)&&(!X.processIdentity||X1(X.pid,X.processIdentity)))throw new d(X.pid);if(await h.unlink(R).catch((T)=>{if(!w0(T,"ENOENT"))throw T}),await W1(R,O))return new o(R,O);throw new d((await L1(R))?.pid)}async release(){if(this.released)return;if(this.released=!0,(await L_(this.filePath))?.ownerId!==this.record.ownerId)return;await h.unlink(this.filePath).catch(($)=>{if(!w0($,"ENOENT"))throw $})}}import{createHash as k0}from"node:crypto";import{constants as s,promises as c}from"node:fs";import i from"node:path";import{Mutex as l$}from"async-mutex";var G1=128,V1=67108864,p$=24576,E1=65536,B_=1,H1=/^[a-f0-9]{64}$/,i$=/^[a-f0-9]{64}\.txt$/,U1=64,d$=new Set(["EBUSY","EAGAIN","EMFILE","ENFILE"]),j0=`
|
|
3
3
|
|
|
4
4
|
...[middle omitted; read the private prompt artifact for the complete request]...
|
|
@@ -25,7 +25,7 @@ import{yg as YO}from"./chunk-2t6b962t.js";import{Fh as qO,Hh as S,Kh 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-36k5c6wy.js"),{createChatServiceAsync:W}=await import("./chunk-p7k7hqtb.js"),{resolveModelConfig:J}=await import("./chunk-v6sfs4qf.js"),{resolveWorkspaceModelResources:G}=await import("./chunk-6k7s3c7y.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}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{Hi as S}from"./chunk-
|
|
1
|
+
import{Hi as S}from"./chunk-5hmeb6yk.js";import{$i as f}from"./chunk-m7b779kd.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 h,u as i,g as j,C as k,V as l};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{Aa as EZ}from"./chunk-dabq8kdx.js";import{Da as A,Ea as n0,Ja as dY,Ka as A7,La as i0}from"./chunk-
|
|
1
|
+
import{Aa as EZ}from"./chunk-dabq8kdx.js";import{Da as A,Ea as n0,Ja as dY,Ka as A7,La as i0}from"./chunk-2v8fyvmh.js";import{Ma as Y8,Oa as AQ,Qa as CQ,Ra as VZ,hb as MQ}from"./chunk-fpjhg6ce.js";import{Ab as W4,Cb as B5,Db as U4,Eb as X4,Gb as g9,Hb as G$,Nb as C4,Ob as TY,Pb as rJ,Rb as S2,Sb as BY,Xb as m7,_b as p7,ib as h$,jb as x1,kb as X7,lb as B1,mb as i3,nb as H7,ob as o3,pb as K7,qb as w7,rb as YJ,vb as V0,xb as u1}from"./chunk-150w9kq4.js";import{Ac as X2,Bc as MZ,Bd as GZ,Cc as V2,Cd as r0,Dc as a4,Dd as h1,Ec as X1,Ed as HY,Fc as C1,Fd as KY,Gc as H2,Hc as M1,Ic as P1,Id as IY,Jc as Q6,Kc as R1,Lc as W6,Mc as U6,Md as d7,Nc as q$,Oc as X6,Pc as xZ,Qc as B2,Rc as V6,Rd as wY,Sc as H6,Sd as zY,Tc as K6,Uc as w6,Ud as t,Vc as hZ,Wc as gZ,Yc as uZ,ec as G9,fc as _0,gc as $2,hc as Z1,ic as t2,jc as BZ,kc as Y4,lc as Q4,mc as t3,nc as e3,oc as VY,pc as NZ,pd as b4,qc as U1,rc as OZ,rd as A0,sc as r4,sd as V$,tc as y$,uc as I$,vc as w2,wc as K2,xc as z2,yc as J6,zc as Y6}from"./chunk-sefdw1mm.js";import{Vd as d,Wd as XJ,Xd as VJ,Yd as a9,_d as g1}from"./chunk-q265drks.js";import{$d as RQ,ce as TQ,le as fQ,re as SQ}from"./chunk-7dykmcjj.js";import{Ce as y9,De as k9}from"./chunk-twdfyk78.js";import{Pe as V4,Qe as B0,Re as y,Ue as L0,Ve as i6,We as d1,Xe as l$,Ye as E5,Ze as V1,_e as g7,df as y1}from"./chunk-1qbq7x98.js";import{ef as q1}from"./chunk-ye4wyq1k.js";import{if as F5,jf as u7,kf as x7,pf as EY,qf as n6}from"./chunk-kpqdfn9z.js";import{sf as y0,tf as e$}from"./chunk-b41den40.js";import{uf as SY}from"./chunk-8qp8v96d.js";import{wf as YY,xf as QY,yf as WY}from"./chunk-6h0kgpgv.js";import{Af as e6,Bf as $4,Df as Z4,Ef as J4,Ff as s$,Gf as BJ,If as O$,Jf as H$,Kf as Y$,Lf as Z8,Mf as S1,Nf as j4,Of as b1,Pf as N1,Qf as XY,Uf as d5,Wf as I0,Xf as D$,Zf as r6,_f as GY,zf as t6}from"./chunk-j2pgrrkb.js";import{ag as n$,cg as B$,dg as I6,eg as J9,fg as Y9,gg as _2,hg as Q9,ig as W9,jg as L6,kg as U9,lg as _6}from"./chunk-0zzh482s.js";import{mg as sY,og as UY,pg as O4,qg as I9}from"./chunk-adkpwx6c.js";import{sg as JZ,ug as T0}from"./chunk-t169d8dc.js";import{vg as c2,wg as zZ,xg as l2,yg as E1}from"./chunk-2t6b962t.js";import{$g as D1,Ag as L9,Ah as JY,Bh as H0,Fg as O9,Hg as s5,Mg as uY,Qg as b9,Sg as eJ,Ug as W7,Vg as U7,ch as a3,mh as M7,nh as P7,oh as R7,ph as T7,qh as b5,rh as f7,sh as c$,th as S7,uh as k7,vh as v7,xh as w9,zh as _Y}from"./chunk-7k72dxwe.js";import{Eh as x$}from"./chunk-kz15jy62.js";import{Fh as z6,Gh as F6,Hh as z,Ih as iZ,Jh as f,Kh as I}from"./chunk-9fgkg1vr.js";import{Mh as iJ,Oh as nJ}from"./chunk-pykxe413.js";import{Rh as E6,Th as M}from"./chunk-kzzty3v5.js";import{ti as a}from"./chunk-w4xqaw4h.js";import{yi as $Y,zi as ZY}from"./chunk-r6svhe3w.js";import{Ai as eY,Di as aY}from"./chunk-a4dmw23t.js";import{Hi as YQ}from"./chunk-5hmeb6yk.js";import{Ni as DY,Oi as d0}from"./chunk-ncqagb27.js";import{Si as s2,Ui as m$,Wi as tJ,Xi as Z9,Zi as s}from"./chunk-spxb931p.js";import{$i as a0}from"./chunk-m7b779kd.js";import{randomUUID as u4}from"crypto";import{randomUUID as sQ}from"node:crypto";var iQ=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);
|
|
@@ -848,7 +848,7 @@ ${$1}
|
|
|
848
848
|
</approved-plan>
|
|
849
849
|
|
|
850
850
|
IMPORTANT: Execute according to the approved plan above. Follow the steps exactly as specified.`;if(typeof q==="string")F0=q+M$;else F0=[...q,{type:"text",text:M$}]}S=yield*this.runLoop(F0,b,{...k,inputMessageId:void 0})}if(!this.sessionRuntime||!v)return S;let r=await this.sessionRuntime.recordGoalProgress({tokens:S.metadata?.tokensUsed??0,elapsedMs:S.metadata?.duration??0,prematureStopPattern:S.success?Q7(S.finalMessage):void 0});if(r)yield{kind:"goal_updated",goal:r};if(!S.success||b.signal?.aborted){if(r=await this.sessionRuntime.pauseActiveGoal(b.signal?.aborted?"goal paused after user cancellation":S.error?.message??"goal paused after turn failure"),r)yield{kind:"goal_updated",goal:r}}if(S.success&&!b.signal?.aborted&&h<20)await this.sessionRuntime.waitForBackgroundSubagentFollowUp(v,b.signal);let $0=S.success&&!b.signal?.aborted&&h<20,p=GH(S);if(x=await this.sessionRuntime.finishTurn(v,{continuePending:$0,...p?{acknowledgeInput:!0}:{},outcome:S.success&&!b.signal?.aborted?{status:"completed",turnsCount:S.metadata?.turnsCount??0,toolCallsCount:S.metadata?.toolCallsCount??0,durationMs:S.metadata?.duration??0}:{status:"aborted",cause:b.signal?.aborted?"cancelled":"failed",turnsCount:S.metadata?.turnsCount??0,toolCallsCount:S.metadata?.toolCallsCount??0,durationMs:S.metadata?.duration??0}}),x){h++,N=!0,E=!1,O=null,q="",R=void 0,T="",C=void 0,j=m(),yield{kind:"follow_up_started",queued:this.sessionRuntime.getPendingSteeringCount(),recovered:this.sessionRuntime.getRecoveredSteeringCount(),messages:e()};continue}if(!S.success||b.signal?.aborted)return S;if(r=await this.sessionRuntime.getGoal(),!r||r.status!=="active"&&r.status!=="verifying")return S;let Q$=await this.sessionRuntime.beginGoalContinuation();if(!Q$)return S;let Y0=await this.sessionRuntime.prepareGoalContinuation(Q$);if(!Y0.ok){if(Y0.goal)yield{kind:"goal_updated",goal:Y0.goal};return{success:!1,error:{type:"goal_frontier_unavailable",message:Y0.error.message},metadata:{turnsCount:S.metadata?.turnsCount??0,toolCallsCount:S.metadata?.toolCallsCount??0,duration:S.metadata?.duration??0}}}O=Y0.goal,_=Y0,x=await this.sessionRuntime.beginTurn("goal"),N=!1,E=!0,q=P8(O),R=void 0,j=void 0,yield{kind:"goal_frontier_updated",goal:Y0.goal,frontier:Y0.frontier,tasks:Y0.tasks},yield{kind:"goal_continuation_started",goal:O,continuation:O.continuationCount,...O.prematureStop?{prematureStopPattern:O.prematureStop.pattern,prematureStopCount:O.prematureStop.consecutiveCount}:{}},yield{kind:"goal_updated",goal:O}}}finally{if(this.sessionRuntime&&x)await this.sessionRuntime.finishTurn(x)}}let D=typeof K==="string"?K:K.filter((q)=>q.type==="text").map((q)=>q.text).join(`
|
|
851
|
-
`),F={id:this.generateTaskId(),type:"simple",prompt:D};return{success:!0,finalMessage:(await this.executeTask(F)).content,metadata:{turnsCount:1,toolCallsCount:0,duration:0}}}async chat($,Z,J){let{drainLoop:Y}=await import("./chunk-xvn45j67.js");return Y(this.chatStream($,Z,J))}async*runPlanLoop($,Z,J){n.debug("Processing Plan mode message...");let{prompt:Y}=await g$({projectPath:Z.workspaceRoot||M(),mode:"plan",includeEnvironment:!0,environmentOptions:S2,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}),Q;if(typeof $==="string")Q=L2($);else{let W=$.filter((U)=>U.type==="text");if(W.length>0){let U=W[0];Q=$.map((X)=>X===U?{type:"text",text:L2(U.text)}:X)}else Q=[{type:"text",text:L2("")},...$]}return yield*this.executeLoop(Q,Z,J,Y)}async*runLoop($,Z,J){n.debug("Processing enhanced chat message...");let Y=Z.systemPrompt??await this.buildSystemPromptOnDemand(Z.workspaceRoot||M());return yield*this.executeLoop($,Z,J,Y)}async buildSystemPromptOnDemand($){let Z=this.runtimeOptions.systemPrompt,J=this.runtimeOptions.appendSystemPrompt;return(await g$({projectPath:$,replaceDefault:Z,append:J,includeEnvironment:!0,environmentOptions:S2,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 Q=this.buildLoopDependencies();return p7(Q,$,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)}},Q=J.metadata&&typeof J.metadata==="object"&&!Array.isArray(J.metadata)?J.metadata:void 0,W=J.error===void 0,U=J.output,X={success:W,llmContent:typeof U==="string"||U!==null&&typeof U==="object"?U:U===null?J.error?`Subagent execution failed: ${J.error}.`:"":String(U),...J.error?{error:{type:"execution_error",message:J.error}}:{},...Q?{metadata:Q}:{}},V=[{kind:"tool_result",toolCall:Y,result:X}],H=m7(Y,X);if(H)V.push(H);return V})}takeStartupRecoveryEvents(){let $=this.sessionRuntime?.getTurnRecoveryAssessment(),Z=$?.state==="requires_attention"?$:this.sessionRuntime?.takeStartupTurnRecoveryAssessment(),J=Z&&Z.state!=="none"?[{kind:"turn_recovery",assessment:Z}]:[];return J.push(...this.takeStartupAdoptedToolResultEvents()),J}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=$,n.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((Q)=>!$.includes(Q.name));for(let Q of Y)Z.unregister(Q.name);n.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);n.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){n.debug(`[MainAgent] ${$}`,Z||"")}error($,Z){n.error(`[MainAgent] ${$}`,Z||"")}async initializeSystemPrompt(){try{let $=this.runtimeOptions.systemPrompt,Z=this.runtimeOptions.appendSystemPrompt,J=await g$({projectPath:this.sessionRuntime?.workspaceRoot??M(),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("系统提示配置验证成功"),n.debug(`[SystemPrompt] 可用来源: ${J.sources.filter((Y)=>Y.loaded).map((Y)=>Y.name).join(", ")}`)}catch($){this.error("系统提示配置验证失败",$)}}async registerBuiltinTools(){try{let $=await a6({sessionId:"default",configDir:s(),workspaceRoot:M(),resourceRoot:M(),agentResources:this.agentResources});n.debug(`Registering ${$.length} builtin tools...`),this.toolExecutor.getRegistry().registerAll($);let Z=this.toolExecutor.getRegistry().getAll().length;n.debug(`Builtin tools registered: ${Z} tools`),n.debug(`[Tools] ${this.toolExecutor.getRegistry().getAll().map((J)=>J.name).join(", ")}`),await this.registerMcpTools()}catch($){throw n.error("Failed to register builtin tools:",$),$}}async registerMcpTools(){try{let $=await j6({workspaceRoot:M(),storeServers:this.config.mcpServers??{},cliConfigs:this.runtimeOptions.mcpConfig,strictCliConfig:this.runtimeOptions.strictMcpConfig});if(Object.keys($).length===0){n.debug("No MCP servers configured");return}let Z=i0.createIsolated({artifactWriter:new F2(`legacy-${BH()}`)});this.legacyMcpRegistry=Z;for(let[W,U]of Object.entries($))try{n.debug(`Connecting to MCP server: ${W}`),await Z.registerServer(W,U),n.debug(`MCP server "${W}" connected`)}catch(X){n.warn(`Warning: MCP server "${W}" connection failed:`,X)}let J=this.toolExecutor.getRegistry();J.setMcpCatalogBarrier(()=>Z.waitForCatalogIdle());let Y=Z.getCatalogSnapshot();J.replaceMcpTools(Y.tools),J.registerAll(j2(Z));let Q=Z.getInstructionsSnapshot();if(J.queueMcpInstructionsChange({revision:Q.revision,reason:"snapshot",replace:!0,instructions:Q.instructions,removed:[]}),Z.on("catalogChanged",(W)=>{J.replaceMcpTools(W.tools,W)}),Z.on("contentCatalogChanged",(W)=>{J.queueMcpContentChange(W)}),Z.on("resourceUpdated",(W)=>{J.queueMcpResourceUpdated(W)}),Z.on("connectionLifecycleChanged",(W)=>{J.queueMcpConnectionChange(W)}),Z.on("log",(W)=>{J.queueMcpLog(W)}),Z.on("instructionsChanged",(W)=>{J.queueMcpInstructionsChange({revision:W.revision,reason:W.reason,replace:!1,instructions:W.action==="added"&&W.instruction?[{serverName:W.serverName,...W.instruction}]:[],removed:W.action==="removed"?[W.serverName]:[]})}),Y.tools.length>0)n.debug(`Registered ${Y.tools.length} MCP tools`),n.debug(`[MCP Tools] ${Y.tools.map((W)=>W.name).join(", ")}`)}catch($){n.warn("Failed to register MCP tools:",$)}}async loadSubagents(){let $=await I0(M());if(this.agentResources=r6($),this.subagentRegistry=this.agentResources.subagents,this.runtimeOptions.agents?.length)this.subagentRegistry.applyOverrides(this.runtimeOptions.agents);let Z=this.subagentRegistry.getAllNames().length;if(Z>0)n.debug(`Loaded ${Z} subagents: ${this.subagentRegistry.getAllNames().join(", ")}`);else n.debug("No subagents configured")}applySkillToolRestrictions($){if(!this.activeSkillContext?.allowedTools)return $;let Z=this.activeSkillContext.allowedTools;n.debug(`Applying Skill tool restrictions: ${Z.join(", ")}`);let J=$.filter((Y)=>{if(Y.name==="ReadPromptArtifact")return!0;return Z.some((Q)=>{if(Q===Y.name)return!0;let W=Q.match(/^(\w+)\(.*\)$/);if(W&&W[1]===Y.name)return!0;return!1})});return n.debug(`Filtered tools: ${J.map((Y)=>Y.name).join(", ")} (${J.length}/${$.length})`),J}clearSkillContext(){if(this.activeSkillContext)n.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(`
|
|
851
|
+
`),F={id:this.generateTaskId(),type:"simple",prompt:D};return{success:!0,finalMessage:(await this.executeTask(F)).content,metadata:{turnsCount:1,toolCallsCount:0,duration:0}}}async chat($,Z,J){let{drainLoop:Y}=await import("./chunk-dspjxf4c.js");return Y(this.chatStream($,Z,J))}async*runPlanLoop($,Z,J){n.debug("Processing Plan mode message...");let{prompt:Y}=await g$({projectPath:Z.workspaceRoot||M(),mode:"plan",includeEnvironment:!0,environmentOptions:S2,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}),Q;if(typeof $==="string")Q=L2($);else{let W=$.filter((U)=>U.type==="text");if(W.length>0){let U=W[0];Q=$.map((X)=>X===U?{type:"text",text:L2(U.text)}:X)}else Q=[{type:"text",text:L2("")},...$]}return yield*this.executeLoop(Q,Z,J,Y)}async*runLoop($,Z,J){n.debug("Processing enhanced chat message...");let Y=Z.systemPrompt??await this.buildSystemPromptOnDemand(Z.workspaceRoot||M());return yield*this.executeLoop($,Z,J,Y)}async buildSystemPromptOnDemand($){let Z=this.runtimeOptions.systemPrompt,J=this.runtimeOptions.appendSystemPrompt;return(await g$({projectPath:$,replaceDefault:Z,append:J,includeEnvironment:!0,environmentOptions:S2,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 Q=this.buildLoopDependencies();return p7(Q,$,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)}},Q=J.metadata&&typeof J.metadata==="object"&&!Array.isArray(J.metadata)?J.metadata:void 0,W=J.error===void 0,U=J.output,X={success:W,llmContent:typeof U==="string"||U!==null&&typeof U==="object"?U:U===null?J.error?`Subagent execution failed: ${J.error}.`:"":String(U),...J.error?{error:{type:"execution_error",message:J.error}}:{},...Q?{metadata:Q}:{}},V=[{kind:"tool_result",toolCall:Y,result:X}],H=m7(Y,X);if(H)V.push(H);return V})}takeStartupRecoveryEvents(){let $=this.sessionRuntime?.getTurnRecoveryAssessment(),Z=$?.state==="requires_attention"?$:this.sessionRuntime?.takeStartupTurnRecoveryAssessment(),J=Z&&Z.state!=="none"?[{kind:"turn_recovery",assessment:Z}]:[];return J.push(...this.takeStartupAdoptedToolResultEvents()),J}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=$,n.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((Q)=>!$.includes(Q.name));for(let Q of Y)Z.unregister(Q.name);n.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);n.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){n.debug(`[MainAgent] ${$}`,Z||"")}error($,Z){n.error(`[MainAgent] ${$}`,Z||"")}async initializeSystemPrompt(){try{let $=this.runtimeOptions.systemPrompt,Z=this.runtimeOptions.appendSystemPrompt,J=await g$({projectPath:this.sessionRuntime?.workspaceRoot??M(),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("系统提示配置验证成功"),n.debug(`[SystemPrompt] 可用来源: ${J.sources.filter((Y)=>Y.loaded).map((Y)=>Y.name).join(", ")}`)}catch($){this.error("系统提示配置验证失败",$)}}async registerBuiltinTools(){try{let $=await a6({sessionId:"default",configDir:s(),workspaceRoot:M(),resourceRoot:M(),agentResources:this.agentResources});n.debug(`Registering ${$.length} builtin tools...`),this.toolExecutor.getRegistry().registerAll($);let Z=this.toolExecutor.getRegistry().getAll().length;n.debug(`Builtin tools registered: ${Z} tools`),n.debug(`[Tools] ${this.toolExecutor.getRegistry().getAll().map((J)=>J.name).join(", ")}`),await this.registerMcpTools()}catch($){throw n.error("Failed to register builtin tools:",$),$}}async registerMcpTools(){try{let $=await j6({workspaceRoot:M(),storeServers:this.config.mcpServers??{},cliConfigs:this.runtimeOptions.mcpConfig,strictCliConfig:this.runtimeOptions.strictMcpConfig});if(Object.keys($).length===0){n.debug("No MCP servers configured");return}let Z=i0.createIsolated({artifactWriter:new F2(`legacy-${BH()}`)});this.legacyMcpRegistry=Z;for(let[W,U]of Object.entries($))try{n.debug(`Connecting to MCP server: ${W}`),await Z.registerServer(W,U),n.debug(`MCP server "${W}" connected`)}catch(X){n.warn(`Warning: MCP server "${W}" connection failed:`,X)}let J=this.toolExecutor.getRegistry();J.setMcpCatalogBarrier(()=>Z.waitForCatalogIdle());let Y=Z.getCatalogSnapshot();J.replaceMcpTools(Y.tools),J.registerAll(j2(Z));let Q=Z.getInstructionsSnapshot();if(J.queueMcpInstructionsChange({revision:Q.revision,reason:"snapshot",replace:!0,instructions:Q.instructions,removed:[]}),Z.on("catalogChanged",(W)=>{J.replaceMcpTools(W.tools,W)}),Z.on("contentCatalogChanged",(W)=>{J.queueMcpContentChange(W)}),Z.on("resourceUpdated",(W)=>{J.queueMcpResourceUpdated(W)}),Z.on("connectionLifecycleChanged",(W)=>{J.queueMcpConnectionChange(W)}),Z.on("log",(W)=>{J.queueMcpLog(W)}),Z.on("instructionsChanged",(W)=>{J.queueMcpInstructionsChange({revision:W.revision,reason:W.reason,replace:!1,instructions:W.action==="added"&&W.instruction?[{serverName:W.serverName,...W.instruction}]:[],removed:W.action==="removed"?[W.serverName]:[]})}),Y.tools.length>0)n.debug(`Registered ${Y.tools.length} MCP tools`),n.debug(`[MCP Tools] ${Y.tools.map((W)=>W.name).join(", ")}`)}catch($){n.warn("Failed to register MCP tools:",$)}}async loadSubagents(){let $=await I0(M());if(this.agentResources=r6($),this.subagentRegistry=this.agentResources.subagents,this.runtimeOptions.agents?.length)this.subagentRegistry.applyOverrides(this.runtimeOptions.agents);let Z=this.subagentRegistry.getAllNames().length;if(Z>0)n.debug(`Loaded ${Z} subagents: ${this.subagentRegistry.getAllNames().join(", ")}`);else n.debug("No subagents configured")}applySkillToolRestrictions($){if(!this.activeSkillContext?.allowedTools)return $;let Z=this.activeSkillContext.allowedTools;n.debug(`Applying Skill tool restrictions: ${Z.join(", ")}`);let J=$.filter((Y)=>{if(Y.name==="ReadPromptArtifact")return!0;return Z.some((Q)=>{if(Q===Y.name)return!0;let W=Q.match(/^(\w+)\(.*\)$/);if(W&&W[1]===Y.name)return!0;return!1})});return n.debug(`Filtered tools: ${J.map((Y)=>Y.name).join(", ")} (${J.length}/${$.length})`),J}clearSkillContext(){if(this.activeSkillContext)n.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(`
|
|
852
852
|
`);try{let Y=await this.attachmentCollector.collect(J);if(Y.length===0)return $;n.debug(`Processed ${Y.length} @ file mentions in multimodal message`);let Q=this.buildAttachmentText(Y);if(!Q)return $;return[...$,{type:"text",text:Q}]}catch(Y){return n.error("Failed to process @ mentions in multimodal message:",Y),$}}buildAttachmentText($){let Z=[],J=[];for(let Q of $)if(Q.type==="file"){let W=Q.metadata?.lineRange?` (lines ${Q.metadata.lineRange.start}${Q.metadata.lineRange.end?`-${Q.metadata.lineRange.end}`:""})`:"";Z.push(`<file path="${Q.path}"${W?` range="${W}"`:""}>`,Q.content,"</file>")}else if(Q.type==="directory")Z.push(`<directory path="${Q.path}">`,Q.content,"</directory>");else if(Q.type==="error")J.push(`- @${Q.path}: ${Q.error}`);let Y="";if(Z.length>0)Y+=`
|
|
853
853
|
|
|
854
854
|
<system-reminder>
|
|
@@ -1658,7 +1658,7 @@ ${J}
|
|
|
1658
1658
|
`)),{success:!0,message:"Schedules listed",content:V.join(`
|
|
1659
1659
|
`)}}case"create":{let X=xB(W);if("error"in X)return Y.sendMessage(`创建失败:${X.error}`),{success:!1,error:X.error};let V={prompt:X.prompt,projectPath:U,trigger:X.trigger,isolation:"worktree",permissionMode:"default",enabled:!0};try{let H=await $.create(V),K=H.nextRunAt?new Date(H.nextRunAt).toLocaleString():"(无)";return Y.sendMessage(`[OK] 已创建定时任务 \`${H.id}\`
|
|
1660
1660
|
${VZ(H.trigger)} · 下次运行: ${K}`),{success:!0,message:`Schedule ${H.id} created`}}catch(H){let K=H instanceof Error?H.message:String(H);return Y.sendMessage(`创建失败:${K}`),{success:!1,error:K}}}case"remove":case"rm":{let X=W[0];if(!X)return Y.sendMessage("用法:/schedule remove <id>"),{success:!1,error:"Missing schedule id"};let V=await $.remove(X);return Y.sendMessage(V?`[OK] 已删除 \`${X}\``:`未找到 \`${X}\``),{success:V,message:V?"Removed":"Not found"}}case"enable":case"disable":{let X=W[0];if(!X)return Y.sendMessage(`用法:/schedule ${Q} <id>`),{success:!1,error:"Missing schedule id"};let V=await $.setEnabled(X,Q==="enable");return Y.sendMessage(V?`[OK] 已${Q==="enable"?"启用":"停用"} \`${X}\``:`未找到 \`${X}\``),{success:Boolean(V),message:V?"Updated":"Not found"}}case"run":{let X=W[0];if(!X)return Y.sendMessage("用法:/schedule run <id>"),{success:!1,error:"Missing schedule id"};try{return await hB(X),Y.sendMessage(`[OK] 已触发 \`${X}\``),{success:!0,message:"Schedule triggered"}}catch(V){let H=V instanceof Error?V.message:String(V);return Y.sendMessage(`运行失败:${H}`),{success:!1,error:H}}}default:return Y.sendMessage(`未知子命令: ${Q}
|
|
1661
|
-
使用 /schedule 查看帮助`),{success:!1,error:`Unknown subcommand: ${Q}`}}}}}var PQ=gB();import*as t1 from"node:fs/promises";import*as e1 from"node:path";async function kQ($,Z={}){let{maxResults:J=20,caseSensitive:Y=!1,projectPath:Q,storagePath:W}=Z,U=W??s2(Q??M());if(!W){let B=await uB($,Q??M(),J,Y);if(B)return B}let X;try{X=(await t1.readdir(U)).filter((G)=>G.endsWith(".jsonl")&&!G.startsWith("agent_")).map((G)=>e1.join(U,G))}catch{return[]}let H=(await Promise.all(X.map(async(B)=>{try{let G=await t1.stat(B);return{path:B,mtime:G.mtimeMs}}catch{return null}}))).filter((B)=>B!==null).sort((B,G)=>G.mtime-B.mtime).map((B)=>B.path),K=[],w=Y?$:$.toLowerCase();for(let B of H){if(K.length>=J)break;let G=e1.basename(B,".jsonl"),_=await dB(B,w,Y,G);if(K.push(..._),K.length>=J){K.length=J;break}}return K}async function uB($,Z,J,Y){try{let{syncAll:Q}=await import("./chunk-v1cmz2bw.js"),W=await fQ();if(!W)return null;let{SessionService:U}=await import("./chunk-
|
|
1661
|
+
使用 /schedule 查看帮助`),{success:!1,error:`Unknown subcommand: ${Q}`}}}}}var PQ=gB();import*as t1 from"node:fs/promises";import*as e1 from"node:path";async function kQ($,Z={}){let{maxResults:J=20,caseSensitive:Y=!1,projectPath:Q,storagePath:W}=Z,U=W??s2(Q??M());if(!W){let B=await uB($,Q??M(),J,Y);if(B)return B}let X;try{X=(await t1.readdir(U)).filter((G)=>G.endsWith(".jsonl")&&!G.startsWith("agent_")).map((G)=>e1.join(U,G))}catch{return[]}let H=(await Promise.all(X.map(async(B)=>{try{let G=await t1.stat(B);return{path:B,mtime:G.mtimeMs}}catch{return null}}))).filter((B)=>B!==null).sort((B,G)=>G.mtime-B.mtime).map((B)=>B.path),K=[],w=Y?$:$.toLowerCase();for(let B of H){if(K.length>=J)break;let G=e1.basename(B,".jsonl"),_=await dB(B,w,Y,G);if(K.push(..._),K.length>=J){K.length=J;break}}return K}async function uB($,Z,J,Y){try{let{syncAll:Q}=await import("./chunk-v1cmz2bw.js"),W=await fQ();if(!W)return null;let{SessionService:U}=await import("./chunk-c5291k2x.js");await Q(W,U.projectionDeriverForSearch());let X=e1.resolve(Z),V=SQ(W,$,X,J*4),H=Y?$:$.toLowerCase(),K=[];for(let w of V){if(w.role!=="user"&&w.role!=="assistant")continue;let B=HZ(w.text,H,Y,w.session_id,w.role,w.timestamp??void 0,0);if(B)K.push(B);if(K.length>=J)break}return K}catch{return null}}async function dB($,Z,J,Y){try{let Q=await t1.readFile($,"utf8"),U=Q.split(`
|
|
1662
1662
|
`).flatMap((w,B)=>{if(!w.trim())return[];try{return[{event:JSON.parse(w),index:B}]}catch{return[]}});if(!U.some(({event:w})=>w.type==="session_created"))return mB(U,Z,J,Y);let V=new Map(U.flatMap(({event:w,index:B})=>typeof w.id==="string"?[[w.id,B+1]]:[])),H=RQ(TQ(Q,$)),K=new Map;for(let w of H){if(w.type==="message_created"&&(w.data.role==="user"||w.data.role==="assistant"))K.set(w.data.messageId,{role:w.data.role,content:[],timestamp:w.timestamp,lineNumber:V.get(w.id)??0});if(w.type==="part_created"&&w.data.partType==="text"){let B=K.get(w.data.messageId),G=w.data.payload.text;if(B&&typeof G==="string")B.content.push(G)}}return[...K.values()].flatMap((w)=>{let B=HZ(w.content.join(" "),Z,J,Y,w.role,w.timestamp,w.lineNumber);return B?[B]:[]})}catch{return[]}}function mB($,Z,J,Y){return $.flatMap(({event:Q,index:W})=>{if(Q.type!=="message")return[];let U=Q.message;if(U?.role!=="user"&&U?.role!=="assistant"||!U.content)return[];let X=typeof U.content==="string"?U.content:Array.isArray(U.content)?U.content.filter((H)=>typeof H==="object"&&H!==null&&H.type==="text"&&typeof H.text==="string").map((H)=>H.text).join(" "):"",V=HZ(X,Z,J,Y,U.role,typeof Q.timestamp==="string"?Q.timestamp:void 0,W+1);return V?[V]:[]})}function HZ($,Z,J,Y,Q,W,U){if(!$)return;let X=J?$:$.toLowerCase();if(!X.includes(Z))return;let V=X.indexOf(Z),H=Math.max(0,V-80),K=Math.min($.length,V+Z.length+80);return{sessionId:Y,role:Q,content:(H>0?"...":"")+$.slice(H,K).replace(/\n/g," ")+(K<$.length?"...":""),timestamp:W,lineNumber:U}}function vQ($){if($.length===0)return"没有找到匹配的历史记录";let Z=[`**找到 ${$.length} 条匹配:**
|
|
1663
1663
|
`];for(let J of $){let Y=J.timestamp?new Date(J.timestamp).toLocaleString("zh-CN",{timeZone:"Asia/Shanghai"}):"?",Q=J.role==="user"?"\uD83D\uDC64":"\uD83E\uDD16";Z.push(`${Q} \`${J.sessionId.slice(0,8)}\` (${Y})`),Z.push(` ${J.content}`),Z.push("")}return Z.join(`
|
|
1664
1664
|
`)}var pB={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=g(Z);if($.length===0)return J.sendMessage("**用法:** `/search <关键词>`\n\n在历史会话中搜索包含指定关键词的对话"),{success:!0,message:"显示帮助"};let Y=$.join(" ");J.sendMessage(`正在搜索: "${Y}" ...`);try{let Q=await kQ(Y,{maxResults:15,projectPath:Z.cwd}),W=vQ(Q);return J.sendMessage(W),{success:!0,message:`found ${Q.length} results`,data:{matches:Q.length}}}catch(Q){let W=Q instanceof Error?Q.message:"未知错误";return J.sendMessage(`搜索失败: ${W}`),{success:!1,error:W}}}},yQ=pB;var cB={name:"skills",description:"查看所有可用的 Skills",fullDescription:"显示所有已发现的 Skills 及其详细信息,包括名称、描述、来源和允许的工具。",usage:"/skills",category:"system",examples:["/skills"],handler:async($,Z)=>{try{let J=Z.workspaceRoot??Z.cwd;return await D$(J,async(Y)=>{await Y.skills.refresh(),N1(J),await b1(J)}),{success:!0,message:"show_skills_manager",data:{action:"show_skills_manager"}}}catch(J){let Y=`获取 Skills 失败: ${J instanceof Error?J.message:"未知错误"}`;return y().addAssistantMessage(Y),{success:!1,error:Y}}}},IQ=cB;import lB from"node:path";function v4($){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 xQ($){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 hQ($,Z){if($.length<=Z)return $;return $.slice(0,Z-3)+"..."}async function iB($,Z){let J=g(Z),Y=$[0],Q=Z0.getInstance(),W=K0.getInstance(),U=Z.sessionId??"",X=Z.sessionId?{sessionId:Z.sessionId,projectPath:lB.resolve(Z.workspaceRoot??Z.cwd)}:void 0;if(Y==="resume"){let G=$[1],_=$.slice(2).join(" ").trim();if(!G||!_)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 D=await Z.subagents.resume(G,_),F=`Resumed \`${G}\` as \`${D.session.id}\` (depth ${D.session.resumeDepth}).`;return J.sendMessage(F),{success:!0,message:F,data:{action:"subagent_resumed",sourceAgentId:G,subagent:D.session}}}if(Y==="clean"){let G=W.cleanupExpiredSessionsForParent(X??U,0);return J.sendMessage(`已清理 ${G} 个已完成的 Agent 会话`),{success:!0,message:`Cleaned ${G} agent sessions`}}let V=[`**后台任务列表**
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{Qe as N}from"./chunk-
|
|
1
|
+
import{Qe as N}from"./chunk-1qbq7x98.js";import{ug as $}from"./chunk-t169d8dc.js";import{Th as _}from"./chunk-kzzty3v5.js";import{ri as Y,ti as Z}from"./chunk-w4xqaw4h.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 ye,y as ze,j as Ae,C as Be};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{ue as a,ve as b,we as c}from"./chunk-
|
|
1
|
+
import{ue as a,ve as b,we as c}from"./chunk-4de6e3am.js";import"./chunk-3jqd18d8.js";import"./chunk-1qbq7x98.js";import"./chunk-v508x7cg.js";import"./chunk-ye4wyq1k.js";import"./chunk-85bamng3.js";import"./chunk-7k72dxwe.js";import"./chunk-kz15jy62.js";import"./chunk-9fgkg1vr.js";import"./chunk-pykxe413.js";import"./chunk-kzzty3v5.js";import"./chunk-9jtjq50j.js";import"./chunk-w4xqaw4h.js";import"./chunk-r6svhe3w.js";import"./chunk-a4dmw23t.js";import"./chunk-5hmeb6yk.js";import"./chunk-ncqagb27.js";import"./chunk-207s8tns.js";import"./chunk-spxb931p.js";import"./chunk-m7b779kd.js";export{a as validatePermissions,c as validateOutput,b as loadConfiguration};
|
package/package.json
CHANGED
package/dist/chunk-b916gtwm.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{se as a,te as b}from"./chunk-txzgwgqk.js";import"./chunk-b8a0sphn.js";import"./chunk-m7b779kd.js";export{a as globalOptions,b as cliConfig};
|
package/dist/chunk-g7ed3sfy.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{h as a,i as b,j as c,k as d,l as e}from"./chunk-yt07a4zp.js";import"./chunk-b8a0sphn.js";import"./chunk-m7b779kd.js";export{b as setSkipUntilVersion,d as performUpgrade,c as getUpgradeCommand,e as checkVersionOnStartup,a as checkVersion};
|