blade-code 0.10.117 → 0.10.118
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-hy20r5ze.js → chunk-1w74gwns.js} +1 -1
- package/dist/{chunk-jcxpq57d.js → chunk-2aysvx6k.js} +1 -1
- package/dist/{chunk-0msthyzv.js → chunk-53aapkv1.js} +1 -1
- package/dist/chunk-5j419kbp.js +1 -0
- package/dist/{chunk-bh7bswhj.js → chunk-74m1zc1r.js} +1 -1
- package/dist/{chunk-1tshkx4p.js → chunk-90q4206c.js} +1 -1
- package/dist/{chunk-bp4s6mbz.js → chunk-9aqs02va.js} +4 -4
- package/dist/{chunk-b1w2mtq8.js → chunk-9n9506vy.js} +1 -1
- package/dist/chunk-bpz7a5yn.js +1 -0
- package/dist/{chunk-fgmwse2v.js → chunk-bxjc7pg7.js} +1 -1
- package/dist/{chunk-53rm14qc.js → chunk-c5wrmq2e.js} +1 -1
- package/dist/{chunk-ymcekh5x.js → chunk-cxbrqnqs.js} +1 -1
- package/dist/{chunk-n9ws6dzb.js → chunk-fys5xx87.js} +3 -3
- package/dist/{chunk-gmcwgmnr.js → chunk-gbjk078c.js} +1 -1
- package/dist/{chunk-c3evbzpa.js → chunk-gjw8100g.js} +1 -1
- package/dist/{chunk-vpz847k8.js → chunk-j3cmytrt.js} +1 -1
- package/dist/{chunk-erqfqfcj.js → chunk-jdm0jffr.js} +1 -1
- package/dist/{chunk-yxg6xbr1.js → chunk-jhsdden6.js} +1 -1
- package/dist/{chunk-yt629r3s.js → chunk-k3tqna1w.js} +1 -1
- package/dist/{chunk-khtbjdf7.js → chunk-kbkdhvk7.js} +1 -1
- package/dist/{chunk-y9vh6qxz.js → chunk-kk6rg27n.js} +1 -1
- package/dist/{chunk-k5nfe6pe.js → chunk-kr8rv2b9.js} +1 -1
- package/dist/{chunk-zbkr8pvx.js → chunk-m56bj6c6.js} +1 -1
- package/dist/{chunk-c3mdtd39.js → chunk-mdczqnc0.js} +1 -1
- package/dist/{chunk-1dttmp46.js → chunk-mnkdxt1v.js} +1 -1
- package/dist/{chunk-rsc9mwdw.js → chunk-nbhgg5p2.js} +1 -1
- package/dist/{chunk-ttv1n12k.js → chunk-nha6m2tx.js} +1 -1
- package/dist/{chunk-cz9mrg18.js → chunk-nyhqdpb6.js} +1 -1
- package/dist/{chunk-ae7bcbmy.js → chunk-qw4hh3sv.js} +1 -1
- package/dist/{chunk-3fsr03k4.js → chunk-scc9kbd1.js} +1 -1
- package/dist/{chunk-6rj0ek81.js → chunk-swtap0bs.js} +1 -1
- package/dist/{chunk-j0pjrq3v.js → chunk-vnbsq6ps.js} +2 -2
- package/dist/{chunk-2gcwzk6m.js → chunk-y1msyved.js} +1 -1
- package/dist/{chunk-4cq70wxs.js → chunk-y21nw7g1.js} +1 -1
- package/dist/{chunk-psatd34r.js → chunk-yqygarpr.js} +1 -1
- package/dist/{chunk-b54vham2.js → chunk-z8xgk0m6.js} +1 -1
- package/dist/{chunk-5dgnnf3n.js → chunk-z9g2x0vm.js} +1 -1
- package/package.json +1 -1
- package/dist/chunk-8p475et7.js +0 -1
- package/dist/chunk-97qjsb8n.js +0 -1
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{pd as C}from"./chunk-
|
|
1
|
+
import{pd as C}from"./chunk-bxjc7pg7.js";import{jh as F,kh as L}from"./chunk-y21nw7g1.js";import{Mutex as G}from"async-mutex";class $ extends Error{limit;resource="resident_runtimes";retryable=!0;constructor(j){super("Session runtime capacity is full");this.limit=j;this.name="SessionRuntimeCapacityError"}}class X extends Error{constructor(){super("Session runtime residency is closed");this.name="SessionRuntimeResidencyClosedError"}}class W extends Error{constructor(j){super(`Session runtime residency already owns key: ${j}`);this.name="SessionRuntimeResidencyConflictError"}}class U{maxResident;idleMs;now;residents=new Map;reservations=new Map;operations=new G;nextGeneration=1;closed=!1;constructor(j){if(!F(j.maxResident))throw Error("Invalid max resident Session Runtime limit");if(!L(j.idleMs))throw Error("Invalid Session Runtime idle timeout");this.maxResident=j.maxResident,this.idleMs=j.idleMs,this.now=j.now??Date.now}acquire(j){let q=this.residents.get(j);if(!q||q.poisoned)return;return q.pins++,q.lastUsedAt=this.now(),this.createLease(q)}owns(j,q){let z=this.residents.get(j);return Boolean(z&&(q===void 0||z.value===q))}async reserve(j,q){if(!j.trim())throw Error("Session runtime residency key must not be blank");return this.operations.runExclusive(async()=>{if(this.closed)throw new X;if(this.residents.has(j)||this.reservations.has(j))throw new W(j);while(this.retainedCount()>=this.maxResident){if(!q.allowEviction)throw new $(this.maxResident);let H=this.oldestEvictableWebResident();if(!H)throw new $(this.maxResident);await this.disposeResident(H,!0)}let z={generation:this.allocateGeneration(),surface:q.surface};return this.reservations.set(j,z),this.createReservation(j,z)})}async remove(j,q){return this.operations.runExclusive(async()=>{let z=this.residents.get(j);if(!z||q!==void 0&&z.value!==q)return!1;if(z.pins>0)return!1;return await this.disposeResident(z,!0),!0})}async forget(j,q){return this.operations.runExclusive(async()=>{let z=this.residents.get(j);if(!z||q!==void 0&&z.value!==q||z.pins>0)return!1;return this.residents.delete(j),!0})}async sweepIdle(){return this.operations.runExclusive(async()=>{if(this.closed)return 0;let j=0;while(!0){let q=this.oldestIdleWebResident();if(!q)return j;await this.disposeResident(q,!0),j++}})}async disposeAll(){await this.operations.runExclusive(async()=>{this.closed=!0,this.reservations.clear();let j;for(let q of[...this.residents.values()])try{await this.disposeResident(q,!1)}catch(z){j??=z}if(this.residents.clear(),j!==void 0)throw j})}getStats(){let j=0;for(let q of this.residents.values())if(q.pins>0)j++;return{resident:this.residents.size,reserved:this.reservations.size,pinned:j,maxResident:this.maxResident}}retainedCount(){return this.residents.size+this.reservations.size}allocateGeneration(){let j=this.nextGeneration;return this.nextGeneration=this.nextGeneration===Number.MAX_SAFE_INTEGER?1:this.nextGeneration+1,j}createReservation(j,q){let z=!1;return{commit:(H)=>{if(z)throw new W(j);if(H.key!==j||H.surface!==q.surface||this.reservations.get(j)!==q||this.closed)throw this.reservations.delete(j),z=!0,this.closed?new X:new W(j);this.reservations.delete(j);let J={...H,generation:q.generation,pins:1,lastUsedAt:this.now(),poisoned:!1};return this.residents.set(j,J),z=!0,this.createLease(J)},cancel:()=>{if(z)return;if(this.reservations.get(j)===q)this.reservations.delete(j);z=!0}}}createLease(j){let q=!1;return{value:j.value,release:()=>{if(q)return;q=!0;let z=this.residents.get(j.key);if(z!==j||z.generation!==j.generation)return;z.pins=Math.max(0,z.pins-1),z.lastUsedAt=this.now()}}}oldestEvictableWebResident(){return this.sortedWebResidents().find((j)=>this.canEvict(j))}oldestIdleWebResident(){let j=this.now();return this.sortedWebResidents().find((q)=>j-q.lastUsedAt>=this.idleMs&&this.canEvict(q))}sortedWebResidents(){return[...this.residents.values()].filter((j)=>j.surface==="web").sort((j,q)=>j.lastUsedAt-q.lastUsedAt||j.generation-q.generation)}canEvict(j){if(j.pins>0||j.poisoned)return!1;try{return j.canEvict()}catch{return!1}}async disposeResident(j,q){if(this.residents.get(j.key)!==j)return;this.residents.delete(j.key);try{await j.dispose()}catch(z){if(q&&!this.closed&&!this.residents.has(j.key))j.lastUsedAt=this.now(),j.poisoned=!0,this.residents.set(j.key,j);throw z}}}import{createHash as B}from"node:crypto";var P=4,b=1000,Y=4000,D=120000,O=0.2;function w(j){try{return C(j)&&j.retryable}catch{return!1}}function N(j,q){let z=Number.isSafeInteger(q)&&q>0?q:1,H=z-1,J=Math.min(b*2**H,Y),K=B("sha256").update(`${j}\x00${z}`).digest().readUInt32BE(0)/4294967295,Q=1-O+2*O*K;return Math.min(Y,Math.max(0,Math.round(J*Q)))}function _(j){let q=N(j.sessionIdentity,j.failedAttempt),z=j.evidence,H=j.workStillPending===!0&&z!==void 0&&w(z.taskFailure)&&z.outputStarted===!1&&z.toolExecutionStarted===!1&&Number.isInteger(z.toolCallsCount)&&z.toolCallsCount===0,J=Number.isSafeInteger(j.failedAttempt)&&j.failedAttempt>0&&j.failedAttempt<P,Z=j.now??Date.now(),K=Z-j.recoveryStartedAt,Q=Number.isFinite(Z)&&Number.isFinite(j.recoveryStartedAt)&&Number.isFinite(K)&&K>=0&&K+q<=D;return{phase:H?J&&Q?"retry_scheduled":"exhausted":"failed",delayMs:q,retryable:H,withinAttemptBudget:J,withinTimeBudget:Q}}
|
|
2
2
|
export{$ as s,U as t,P as u,D as v,_ as w};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{h as a,i as b,j as c,k as d,l as e}from"./chunk-kk6rg27n.js";import"./chunk-53aapkv1.js";import"./chunk-tf7ezqew.js";export{b as setSkipUntilVersion,d as performUpgrade,c as getUpgradeCommand,e as checkVersionOnStartup,a as checkVersion};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{$d as F$,_d as n,ae as h_,be as D$,ce as j,de as c_,ee as f$,fe as n_,ge as z$,he as l_,ie as p_,ke as d0,ne as i_,oe as x$}from"./chunk-qdv0n8yt.js";import{tf as D0}from"./chunk-hv6hrsnk.js";import{lg as f0}from"./chunk-9g64g1np.js";import{xg as a1}from"./chunk-eyb9psbc.js";import{Kh as K$,Lh as M$,Mh as B0,Nh as g0,Oh as W0}from"./chunk-p3m1jyg5.js";import{Sh as B1}from"./chunk-ecd727xh.js";import{si as h0}from"./chunk-dvv28pkc.js";import{Ci as F0,zi as M0}from"./chunk-z52s82k7.js";import{Gi as a}from"./chunk-
|
|
1
|
+
import{$d as F$,_d as n,ae as h_,be as D$,ce as j,de as c_,ee as f$,fe as n_,ge as z$,he as l_,ie as p_,ke as d0,ne as i_,oe as x$}from"./chunk-qdv0n8yt.js";import{tf as D0}from"./chunk-hv6hrsnk.js";import{lg as f0}from"./chunk-9g64g1np.js";import{xg as a1}from"./chunk-eyb9psbc.js";import{Kh as K$,Lh as M$,Mh as B0,Nh as g0,Oh as W0}from"./chunk-p3m1jyg5.js";import{Sh as B1}from"./chunk-ecd727xh.js";import{si as h0}from"./chunk-dvv28pkc.js";import{Ci as F0,zi as M0}from"./chunk-z52s82k7.js";import{Gi as a}from"./chunk-53aapkv1.js";import{Qi as q$,Ri as Q0,Si as A$,Ti as x,Ui as u,Wi as A0,Xi as t,Yi as k}from"./chunk-rkdxqx8m.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]...
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{ta as F,va as L}from"./chunk-
|
|
1
|
+
import{ta as F,va as L}from"./chunk-fys5xx87.js";import{Jd as $,Ld as B,Td as Q}from"./chunk-bxjc7pg7.js";import{Vf as y}from"./chunk-90q4206c.js";import{Sh as V}from"./chunk-ecd727xh.js";async function j(){await y(V())}async function I(b){let q=b.message||b._?.[0];if(typeof q==="string"&&q.trim())return q;let z=b.stdin??process.stdin;if(!z.isTTY){let G=[];for await(let K of z)G.push(K);return Buffer.concat(G).toString("utf-8").trim()}if(b.defaultMessage!==void 0)return b.defaultMessage;throw Error("No input provided")}async function M(b){let q=b.message||b._?.[0];if(typeof q==="string"&&q.trim())return q;let z=b.stdin??process.stdin;if(z.isTTY)return;let G=[];for await(let Z of z)G.push(Buffer.isBuffer(Z)?Z:Buffer.from(Z));return Buffer.concat(G).toString("utf-8").trim()||void 0}async function R(b){if(!F(b))return{mode:"agent",content:b};let q=await L(b,{cwd:V(),surface:"headless",workspaceRoot:V()});if(!q.success)return{mode:"output",content:`Error: ${q.error||"未知错误"}`,exitCode:1};let z=q.data;if(z?.action==="invoke_skill"){let{skillName:G,skillArgs:K}=z;return{mode:"agent",content:K?`Please use the "${G}" skill to help me with: ${K}`:`Please use the "${G}" skill.`}}if(z?.action==="invoke_custom_command"||z?.action==="invoke_plugin_command"){let G=z.processedContent;return{mode:"agent",content:`# Custom Command: /${z.commandName}
|
|
2
2
|
|
|
3
3
|
${G}`}}return{mode:"output",content:q.content||q.message||"",exitCode:0}}import{readFile as D,stat as H}from"node:fs/promises";import J from"node:path";function x(b,q){let z;try{z=JSON.parse(b)}catch(G){throw Error(`Invalid JSON output schema from ${q}`,{cause:G})}return B(z).schema}async function _(b){if(b.jsonSchema!==void 0&&b.outputSchema!==void 0)throw Error("--json-schema cannot be combined with --output-schema");if(b.jsonSchema!==void 0)return x(b.jsonSchema,"--json-schema");if(b.outputSchema===void 0)return;let q=J.resolve(b.outputSchema),z=await H(q);if(!z.isFile())throw Error(`Output schema path is not a regular file: ${q}`);if(z.size>$)throw Error(`Output schema exceeds ${$} bytes: ${q}`);return x(await D(q,"utf8"),q)}function N(b){if(!(b instanceof Error))return!1;return b.message.includes("未找到会话")||b.message.includes("ENOENT")||b.message.includes("no such file")}async function W(b){try{return await Q.loadSessionModelContext(b,V())}catch(q){if(N(q))return null;throw q}}async function C(b){if(b.resume===!0||b.resume==="true")throw Error("--resume without a session ID is only supported in interactive UI mode");if(typeof b.resume==="string"&&b.resume.length>0){if(b.forkSession){let G=V(),K=await Q.forkSession(b.resume,{newSessionId:b.sessionId,sourceProjectPath:G,targetProjectPath:G});return{...K,messages:await Q.loadSessionModelContext(K.sessionId,G)}}let[q,z]=await Promise.all([Q.loadSessionModelContext(b.resume),Q.findSessionMetadata(b.resume)]);return{sessionId:b.resume,messages:q,metadata:z}}if(b.continue){let q=b.forkSession?await Q.listSessions({cwd:V()}):await Q.listSessions();if(q.length>0){let z=q[0].sessionId;if(b.forkSession){let G=V(),K=await Q.forkSession(z,{newSessionId:b.sessionId,sourceProjectPath:G,targetProjectPath:G});return{...K,messages:await Q.loadSessionModelContext(K.sessionId,G)}}return{sessionId:z,messages:await Q.loadSessionModelContext(z),metadata:q[0]}}if(b.forkSession)throw Error("Cannot fork: no sessions are available to continue")}if(b.sessionId){let q=await W(b.sessionId);return{sessionId:b.sessionId,messages:q??[],...q?{metadata:await Q.findSessionMetadata(b.sessionId,V())}:{}}}return{sessionId:`${b.fallbackSessionPrefix}-${Date.now()}`,messages:[]}}
|
|
4
4
|
export{j as m,I as n,M as o,R as p,_ as q,C as r};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{S as I}from"./chunk-
|
|
1
|
+
import{S as I}from"./chunk-fys5xx87.js";import{Td as M}from"./chunk-bxjc7pg7.js";import P from"node:path";function w(s){let a=s.replace(/\s+/g," ").trim();return a.length<=72?a:`${a.slice(0,69)}...`}function W(s){let a=s.replace(/\s+/g," ").trim();return a.length<=500?a:`${a.slice(0,497)}...`}function A(s){return`task/${s.replace(/[^a-zA-Z0-9_-]/g,"-").slice(0,40)}`}class C{static async createSessionTask(s){if(!s.prompt.trim())throw Error("Task prompt must not be blank");if(!P.isAbsolute(s.sourceProjectPath))throw Error("Task source project path must be absolute");let a=P.resolve(s.sourceProjectPath),t;try{return t=s.isolation==="worktree"?await I.enter({sessionId:s.sessionId,workspaceRoot:a,name:A(s.sessionId)}):void 0,{metadata:await M.createSessionMetadata(s.sessionId,t?.workspaceRoot??a,{title:s.title?.trim()||w(s.prompt),taskPromptSummary:W(s.prompt),taskPriority:s.taskPriority,taskKind:s.taskKind,taskDueAt:s.taskDueAt,taskDispatch:s.dispatch,taskModelId:s.dispatch?.modelId,selectedModelId:s.dispatch?.modelId,permissionMode:s.dispatch?.permissionMode,reasoningEffort:s.dispatch?.reasoningEffort,serviceTier:s.dispatch?.serviceTier,responseVerbosity:s.dispatch?.responseVerbosity,communicationStyle:s.dispatch?.communicationStyle,communicationStyleDigest:s.dispatch?.communicationStyleDigest,projectInstructionsDigest:s.dispatch?.projectInstructionsDigest,taskRetriedFrom:s.retriedFrom,taskIsolation:s.isolation,taskSourceProjectPath:a,taskWorktree:t}),taskWorktree:t}}catch(k){if(t)await I.exit({sessionId:s.sessionId,action:"remove",discardChanges:!0}).catch(()=>{return});throw k}}}var $=256,V=8388608,x=30000;class i extends Error{kind;pendingItems;pendingBytes;constructor(s,a,t){super(a,t);this.kind=s;this.name="BoundedSerialEgressError",this.pendingItems=t?.pendingItems,this.pendingBytes=t?.pendingBytes}}function T(s){s.catch(()=>{return})}class K{options;pending=[];flushWaiters=[];pendingBytes=0;nextSequence=0;completedSequence=0;draining=!1;closed=!1;failure;activeWriteAbort;activeWriteStop;activeWriteTimeout;constructor(s){this.options=s;if(this.assertPositiveInteger(s.maxPendingItems,"maxPendingItems"),this.assertPositiveInteger(s.maxPendingBytes,"maxPendingBytes"),this.assertPositiveInteger(s.writeTimeoutMs,"writeTimeoutMs"),s.signal?.addEventListener("abort",this.handleAbort,{once:!0}),s.signal?.aborted)this.handleAbort()}offer(s){if(this.closed)return{accepted:!1,error:this.failure??new i("closed","Egress is already closed")};let a;try{a=this.options.sizeOf(s)}catch(h){return this.rejectAdmission(new i("invalid_size","Egress size calculation failed",{cause:h}))}if(!Number.isSafeInteger(a)||a<0)return this.rejectAdmission(new i("invalid_size","Egress size must be a non-negative safe integer"));if(a>this.options.maxPendingBytes)return this.rejectAdmission(new i("oversized",`Egress value requires ${a} bytes; limit is ${this.options.maxPendingBytes}`));if(this.pending.length>=this.options.maxPendingItems||this.pendingBytes+a>this.options.maxPendingBytes)return this.rejectAdmission(new i("overflow",`Egress pending limit exceeded (${this.pending.length} items, ${this.pendingBytes} bytes)`));let t,k,c=new Promise((h,m)=>{t=h,k=m});return T(c),this.nextSequence+=1,this.pending.push({value:s,bytes:a,sequence:this.nextSequence,resolve:t,reject:k,completion:c}),this.pendingBytes+=a,this.startDrain(),{accepted:!0,completion:c}}flush(){if(this.failure){let c=Promise.reject(this.failure);return T(c),c}let s=this.nextSequence;if(s<=this.completedSequence)return Promise.resolve();let a,t,k=new Promise((c,h)=>{a=c,t=h});return T(k),this.flushWaiters.push({targetSequence:s,resolve:a,reject:t}),k}close(s){let a=s instanceof i?s:new i("closed","Egress was closed",{cause:s});this.fail(a)}stats(){return{closed:this.closed,pendingItems:this.pending.length,pendingBytes:this.pendingBytes}}handleAbort=()=>{this.fail(new i("aborted","Egress was aborted",{cause:this.options.signal?.reason}))};rejectAdmission(s){return this.fail(s),{accepted:!1,error:s}}startDrain(){if(this.draining||this.closed)return;this.draining=!0;let s=this.drain();T(s)}async drain(){try{while(!this.closed){let s=this.pending[0];if(!s)return;try{await this.writeOne(s.value)}catch(a){this.fail(this.normalizeWriteError(a));return}if(this.closed||this.pending[0]!==s)return;this.pending.shift(),this.pendingBytes-=s.bytes,this.completedSequence=s.sequence,s.resolve(),this.settleFlushWaiters()}}finally{if(this.draining=!1,!this.closed&&this.pending.length>0)this.startDrain()}}async writeOne(s){let a=new AbortController;this.activeWriteAbort=a;let t,k,c=new Promise((S,f)=>{k=f});T(c),this.activeWriteStop=k;let h=Promise.resolve().then(()=>this.options.write(s,a.signal));T(h);let m=new Promise((S,f)=>{t=setTimeout(()=>{let D=new i("write_timeout",`Egress write timed out after ${this.options.writeTimeoutMs}ms`);a.abort(D),f(D)},this.options.writeTimeoutMs),this.activeWriteTimeout=t});T(m);try{await Promise.race([h,m,c])}finally{if(t!==void 0)clearTimeout(t);if(this.activeWriteTimeout===t)this.activeWriteTimeout=void 0;if(this.activeWriteAbort===a)this.activeWriteAbort=void 0;if(this.activeWriteStop===k)this.activeWriteStop=void 0}}normalizeWriteError(s){if(s instanceof i)return s;return new i("write_failed","Egress write failed",{cause:s})}fail(s){if(this.closed)return;if(s.pendingItems??=this.pending.length,s.pendingBytes??=this.pendingBytes,this.closed=!0,this.failure=s,this.options.signal?.removeEventListener("abort",this.handleAbort),this.activeWriteTimeout!==void 0)clearTimeout(this.activeWriteTimeout),this.activeWriteTimeout=void 0;this.activeWriteAbort?.abort(s),this.activeWriteStop?.(s),this.activeWriteAbort=void 0,this.activeWriteStop=void 0;let a=this.pending.splice(0);this.pendingBytes=0;for(let t of a)t.reject(s);for(let t of this.flushWaiters.splice(0))t.reject(s);try{this.options.onFailure?.(s)}catch{}}settleFlushWaiters(){for(let s=0;s<this.flushWaiters.length;){let a=this.flushWaiters[s];if(a.targetSequence>this.completedSequence){s+=1;continue}this.flushWaiters.splice(s,1),a.resolve()}}assertPositiveInteger(s,a){if(!Number.isSafeInteger(s)||s<=0)throw RangeError(`${a} must be a positive safe integer`)}}
|
|
2
2
|
export{C as y,$ as z,V as A,x as B,i as C,K as D};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{za as EZ}from"./chunk-ypbnczjp.js";import{Ca as A,Da as n0,Ia as dY,Ja as A7,Ka as i0}from"./chunk-
|
|
1
|
+
import{za as EZ}from"./chunk-ypbnczjp.js";import{Ca as A,Da as n0,Ia as dY,Ja as A7,Ka as i0}from"./chunk-z9g2x0vm.js";import{La as Y8,Na as AQ,Pa as CQ,Qa as VZ,gb as MQ}from"./chunk-23v8c9b8.js";import{Bb as B5,Cb as U4,Db as X4,Fb as g9,Gb as G$,Mb as C4,Nb as TY,Ob as rJ,Qb as S2,Rb as BY,Wb as m7,Zb as p7,hb as h$,ib as x1,jb as X7,kb as B1,lb as i3,mb as H7,nb as o3,ob as K7,pb as w7,qb as YJ,ub as V0,wb as u1,zb as W4}from"./chunk-gbjk078c.js";import{Ac as MZ,Ad as GZ,Bc as V2,Bd as r0,Cc as a4,Cd as h1,Dc as X1,Dd as HY,Ec as C1,Ed as KY,Fc as H2,Gc as M1,Hc as P1,Hd as IY,Ic as Q6,Jc as R1,Kc as W6,Lc as U6,Ld as d7,Mc as q$,Nc as X6,Oc as xZ,Pc as B2,Qc as V6,Qd as wY,Rc as H6,Rd as zY,Sc as K6,Tc as w6,Td as t,Uc as hZ,Vc as gZ,Xc as uZ,dc as G9,ec as _0,fc as $2,gc as Z1,hc as t2,ic as BZ,jc as Y4,kc as Q4,lc as t3,mc as e3,nc as VY,oc as NZ,od as b4,pc as U1,qc as OZ,qd as A0,rc as r4,rd as V$,sc as y$,tc as I$,uc as w2,vc as K2,wc as z2,xc as J6,yc as Y6,zc as X2}from"./chunk-bxjc7pg7.js";import{Ud as d,Vd as XJ,Wd as VJ,Xd as a9,Zd as g1}from"./chunk-53h87fmt.js";import{_d as RQ,be as TQ,ke as fQ,qe as SQ}from"./chunk-qdv0n8yt.js";import{Be as y9,Ce as k9}from"./chunk-ng96f4xd.js";import{Oe as V4,Pe as B0,Qe as y,Te as L0,Ue as i6,Ve as d1,We as l$,Xe as E5,Ye as V1,Ze as g7,cf as y1}from"./chunk-kr8rv2b9.js";import{df as q1}from"./chunk-pshyn3yy.js";import{hf as F5,if as u7,jf as x7,of as EY,pf as n6}from"./chunk-q2exry0f.js";import{rf as y0,sf as e$}from"./chunk-tj2efrs1.js";import{tf as SY}from"./chunk-hv6hrsnk.js";import{vf as YY,wf as QY,xf as WY}from"./chunk-gjw8100g.js";import{Af as $4,Cf as Z4,Df as J4,Ef as s$,Ff as BJ,Hf as O$,If as H$,Jf as Y$,Kf as Z8,Lf as S1,Mf as j4,Nf as b1,Of as N1,Pf as XY,Tf as d5,Vf as I0,Wf as D$,Yf as r6,Zf as GY,yf as t6,zf as e6}from"./chunk-90q4206c.js";import{$f as n$,bg as B$,cg as I6,dg as J9,eg as Y9,fg as _2,gg as Q9,hg as W9,ig as L6,jg as U9,kg as _6}from"./chunk-cqqmkwvn.js";import{lg as sY,ng as UY,og as O4,pg as I9}from"./chunk-9g64g1np.js";import{rg as JZ,tg as T0}from"./chunk-swtap0bs.js";import{ug as c2,vg as zZ,wg as l2,xg as E1}from"./chunk-eyb9psbc.js";import{Ah as H0,Eg as O9,Gg as s5,Lg as uY,Pg as b9,Rg as eJ,Tg as W7,Ug as U7,_g as D1,bh as a3,lh as M7,mh as P7,nh as R7,oh as T7,ph as b5,qh as f7,rh as c$,sh as S7,th as k7,uh as v7,wh as w9,yh as _Y,zg as L9,zh as JY}from"./chunk-y21nw7g1.js";import{Dh as x$}from"./chunk-4w4wjm49.js";import{Eh as z6,Fh as F6,Gh as z,Hh as iZ,Ih as f,Jh as I}from"./chunk-6k5k40p8.js";import{Lh as iJ,Nh as nJ}from"./chunk-p3m1jyg5.js";import{Qh as E6,Sh as M}from"./chunk-ecd727xh.js";import{si as a}from"./chunk-dvv28pkc.js";import{xi as $Y,yi as ZY}from"./chunk-dgf2xzzd.js";import{Ci as aY,zi as eY}from"./chunk-z52s82k7.js";import{Gi as YQ}from"./chunk-53aapkv1.js";import{Mi as DY,Ni as d0}from"./chunk-vbwvsgs1.js";import{Ri as s2,Ti as m$,Vi as tJ,Wi as Z9,Yi as s}from"./chunk-rkdxqx8m.js";import{_i as a0}from"./chunk-tf7ezqew.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-3fsr03k4.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-scc9kbd1.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-fqnqeca5.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-fqnqeca5.js"),W=await fQ();if(!W)return null;let{SessionService:U}=await import("./chunk-mdczqnc0.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{cc as M4}from"./chunk-cnhw5mqv.js";import{$c as l2,Id as g0,Kd as Q6,Ld as h1,Md as X6,Td as o$,Wc as IJ,Yc as uJ,Zc as gJ,_c as m2,ec as X$,fd as pJ,gd as R4,hd as h4,id as u2,jd as v1,kd as x4,ld as k4,md as S1,qd as wJ,yd as K1}from"./chunk-fgmwse2v.js";import{Yd as T4}from"./chunk-53h87fmt.js";import{_d as B0,be as EJ,ce as I0}from"./chunk-qdv0n8yt.js";import{df as $4}from"./chunk-pshyn3yy.js";import{ef as E4,ff as i0,gf as y4,hf as jJ,kf as E1,lf as K6,mf as BJ,nf as UJ,pf as DJ}from"./chunk-q2exry0f.js";import{$f as r0,_f as J$,cg as S4,gg as z4}from"./chunk-cqqmkwvn.js";import{tg as P$}from"./chunk-6rj0ek81.js";import{Dh as oJ}from"./chunk-4w4wjm49.js";import{Sh as j0}from"./chunk-ecd727xh.js";import{si as v0}from"./chunk-dvv28pkc.js";import{Gi as CJ}from"./chunk-0msthyzv.js";import{Ri as b$,Ti as n6,Ui as _0,Vi as R1,Xi as xJ,Yi as kJ,Zi as vJ}from"./chunk-rkdxqx8m.js";import{_i as O8}from"./chunk-tf7ezqew.js";function y$($){return $.role==="system"&&Array.isArray($.content)}function f$($){if($.role!=="system"||!$.metadata||Array.isArray($.metadata))return!1;return typeof $.metadata==="object"&&$.metadata.contextualProjectRules===!0}class y1{systemMessages;_contextualSystemMessages;_history;_pending=[];_contextRevision=0;context;constructor($,J){this.context=$;let Z=$.messages.find(y$);if(this._contextualSystemMessages=$.messages.filter(f$),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)=>!y$(W)&&!f$(W))}get historyLength(){return this._history.length}get history(){return this._history}get pending(){return this._pending}get contextRevision(){return this._contextRevision}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(!f$($))throw Error("Contextual project instructions require safe metadata");this._contextualSystemMessages.push($),this.systemMessages.push($)}syncContextualSystemMessages(){let $=this.systemMessages.filter(y$);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)=>!y$(J)&&!f$(J)),this._contextRevision++}restoreDurableHistory($){this._contextualSystemMessages=$.filter(f$),this._history=$.filter((J)=>!y$(J)&&!f$(J)),this._pending=[],this.syncContextualSystemMessages(),this._contextRevision++}removeMessages($){let J=[this._history.length,this._pending.length,this._contextualSystemMessages.length];if(this._history=this._history.filter((Z)=>!$(Z)),this._pending=this._pending.filter((Z)=>!$(Z)),this._contextualSystemMessages=this._contextualSystemMessages.filter((Z)=>!$(Z)),this.syncContextualSystemMessages(),this._history.length!==J[0]||this._pending.length!==J[1]||this._contextualSystemMessages.length!==J[2])this._contextRevision++}writeback(){this.commitPending(),this.context.messages=[...this._contextualSystemMessages,...this._history]}get hasSystemPrompt(){return this.systemMessages.length>0}}function E6($){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 S6($){return{budget:$.budget,usage:0,consecutiveContinuations:0,lastOutputDelta:0,isSubagent:$.isSubagent??!1}}function T6($,J,Z){return{...$,usage:$.usage+J,lastOutputDelta:J,consecutiveContinuations:Z?$.consecutiveContinuations+1:0}}import Q$ from"node:path";var l4=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"]),i4=/^(LD_.+|DYLD_.+|PATH)$/,M6=/^([A-Za-z_][A-Za-z0-9_]*)=([\w./:@-]*)$/;function l$($){let J=$;while(!0){let Z=J.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!Z)break;let W=Z[1],Y=Z[2],V=W.match(M6);if(!V)break;let K=V[1];if(!l4.has(K))break;J=Y}return J}function gZ($){let J=$;while(!0){let Z=J.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!Z)break;let W=Z[1],Y=Z[2],V=W.match(M6);if(!V)break;let K=V[1];if(i4.test(K))break;J=Y}return J}var r4=[/^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 w2($){let J=$,Z=!0;while(Z){Z=!1;for(let W of r4){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 i$($){let J=[],Z="",W=!1,Y=!1,V=!1;for(let K=0;K<$.length;K++){let Q=$[K];if(V){Z+=Q,V=!1;continue}if(Q==="\\"&&!W){Z+=Q,V=!0;continue}if(Q==="'"&&!Y){W=!W,Z+=Q;continue}if(Q==='"'&&!W){Y=!Y,Z+=Q;continue}if(W||Y){Z+=Q;continue}if(Q==="|"){if(K+1<$.length&&$[K+1]==="|"){if(Z.trim())J.push(Z.trim());Z="",K++;continue}return null}if(Q===">"||Q==="<")return null;if(Q==="&"&&K+1<$.length&&$[K+1]==="&"){if(Z.trim())J.push(Z.trim());Z="",K++;continue}if(Q==="&")return null;if(Q===";"){if(Z.trim())J.push(Z.trim());Z="";continue}Z+=Q}if(Z.trim())J.push(Z.trim());return J.length>0?J:null}function R6($){let J=!1,Z=!1,W=!1;for(let Y=0;Y<$.length;Y++){let V=$[Y];if(W){W=!1;continue}if(V==="\\"&&!J){W=!0;continue}if(V==="'"&&!Z){J=!J;continue}if(V==='"'&&!J){Z=!Z;continue}if(J)continue;if(V==="$"){let K=$[Y+1];if(K&&/[A-Za-z_@*#?!$0-9({]/.test(K))return!0}if(V==="`")return!0;if(Z)continue;if(V==="|")return!0;if(V===">"||V==="<")return!0;if(V==="{"){let K=$.slice(Y);if(/^\{[^}]*,[^}]*\}/.test(K)||/^\{[^}]*\.\.[^}]*\}/.test(K))return!0}}return!1}function K$($){let J=[],Z="",W=!1,Y=!1,V=!1;for(let K=0;K<$.length;K++){let Q=$[K];if(V){Z+=Q,V=!1;continue}if(Q==="\\"&&!W){if(V=!0,Y){let X=$[K+1];if(X&&'$`"\\'.includes(X))continue;Z+=Q,V=!1}continue}if(Q==="'"&&!Y){W=!W;continue}if(Q==='"'&&!W){Y=!Y;continue}if(!W&&!Y&&/[ \t]/.test(Q)){if(Z)J.push(Z),Z="";continue}Z+=Q}if(Z)J.push(Z);return J}var n4=new Set(["npm","pnpm","yarn","bun"]),h6=new Set(["biome","eslint","jest","mypy","pyright","pytest","ruff","tsc","vitest"]),o4=new Set(["-u","--fix","--update","--update-snapshot","--updateSnapshot","--watch","--watchAll","--write"]),a4=/[ \t]*;[ \t]*echo[ \t]+"[A-Za-z0-9 _:=.-]*(?:\$\{PIPESTATUS\[0\]\}|\$\?)[A-Za-z0-9 _:=.-]*"[ \t]*$/;function s4($){return $!==void 0&&/^(?:test|lint|build|type-?check)(?::[\w.-]+)*$/i.test($)}function x6($){return $.replace(/\s+2>&1\s*$/,"").trim()}function t4($,J,Z){if(!Z||J.length!==2)return;let W=/^(.+?)[ \t]+&&[ \t]+([\s\S]+)$/.exec($);if(!W)return;let Y=K$(W[1]??"");if(Y.length!==2||Y[0]!=="cd")return;let V=Y[1];if(!V||V==="-")return;let K=Q$.isAbsolute(V)?Q$.resolve(V):Q$.resolve(Z,V);if(!X$.isWithinWorkspace(K,Z))return;return W[2]?.trim()||void 0}function e4($){let J=[],Z=!1,W=!1,Y=!1;for(let V=0;V<$.length;V++){let K=$[V];if(Y){Y=!1;continue}if(K==="\\"&&!Z){Y=!0;continue}if(K==="'"&&!W){Z=!Z;continue}if(K==='"'&&!Z){W=!W;continue}if(K!=="|"||Z||W)continue;if($[V+1]==="|")return;J.push(V)}return J}function $5($){let J=K$($),[Z,W,Y]=J;if(Z!=="head"&&Z!=="tail")return!1;if(J.length===1)return!0;let V=(K)=>K!==void 0&&/^[1-9]\d{0,4}$/.test(K);if(J.length===2)return W?.startsWith("--lines=")&&V(W.slice(8))||W?.startsWith("-")&&V(W.slice(1));return J.length===3&&(W==="-n"||W==="--lines")&&V(Y)}function J5($){let J=x6($.replace(a4,"").trim()),Z=e4(J);if(!Z)return;if(Z.length===0)return k6(J);if(Z.length!==1)return;let W=Z[0];if(W===void 0)return;let Y=x6(J.slice(0,W).trim()),V=J.slice(W+1).trim();if(!Y||!$5(V))return;return k6(Y)}function k6($){let Z=i$($)?.at(-1);if(!Z)return $;let W=K$(Z),[Y,V]=W;if(!(Y==="vitest"||(Y==="npx"||Y==="bunx")&&V==="vitest")||W.some((Q)=>Q==="--configLoader"||Q.startsWith("--configLoader=")))return $;return`${$} --configLoader runner`}function A$($,J){let Z=J5($);if(!Z)return!1;let W=l$(Z),Y=i$(W);if(!Y||R6(W)||/[\r\n]/.test(W))return!1;let V=Y.length===1?Y[0]:t4(W,Y,J);if(!V)return!1;let K=K$(V);if(K.length===0||K.some((j)=>[...o4].some((B)=>j===B||j.startsWith(`${B}=`))))return!1;let[Q,X,H]=K;if(n4.has(Q??""))return s4(X==="run"?H:X)||X==="--test";if((Q==="npx"||Q==="bunx")&&h6.has(X??""))return!0;if(h6.has(Q??""))return!0;if(Q==="node"&&X==="--test")return!0;if(Q==="go"&&["build","test","vet"].includes(X??""))return!0;return Q==="cargo"&&["build","check","clippy","test"].includes(X??"")}function lZ($,J){if($===void 0)return!0;if(typeof $!=="string"||$.split(/[\\/]/).includes(".."))return!1;if(!J)return!Q$.isAbsolute($);let Z=Q$.isAbsolute($)?Q$.resolve($):Q$.resolve(J,$);return X$.isWithinWorkspace(Z,J)}var q2=v0("Agent"),Z5=3;function G2($,J,Z){if($!=="length")return{action:"none"};if(J>=Z5)return{action:"truncated"};if(E6(Z)==="stop")return q2.info("[Loop] Token budget: diminishing returns detected, skipping recovery"),{action:"budget_stop"};return{action:"recover"}}var W5=[/:\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],Y5=/```[\s\S]{50,}```/,v6="请执行你提到的操作,不要只是描述。使用 Edit/Write/ApplyPatch/Bash 工具来实际修改文件。",V5=2;function F2($,J,Z=!0){if(!$||J>=V5)return{action:"none"};if(!Z&&Y5.test($))return{action:"retry",prompt:v6};let W=$.slice(-200),Y=W.match(/```/g);if(Y&&Y.length%2!==0)return{action:"none"};if(W5.some((K)=>K.test(W)))return{action:"retry",prompt:v6};return{action:"none"}}var K5=[/\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}(?:测试|单测|集成测试|检查|构建)/],C6={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},Q5={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},X5="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.",H5="Required verification did not run successfully before the retry limit.",z5=3;function u6($,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&&A$(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 V of Y)if(typeof V==="string"&&A$(V,W))$.add(V)}function L2($,J,Z){if(!$||!K5.some((X)=>X.test($)))return{action:"none"};let W=Object.keys(C6).filter((X)=>C6[X].test($)),Y=[...J],V=W.filter((X)=>!Y.some((H)=>Q5[X].test(H)));if(W.length>0?V.length===0:Y.some((X)=>A$(X)))return{action:"none"};if(Z>=z5)return{action:"fail",message:H5};let Q=W.length>1&&V.length>0?` Missing successful verification categories: ${V.join(", ")}.`:"";return{action:"retry",prompt:`${X5}${Q}`}}var j5=[/\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|子代理|子智能体)/],g6=[/\b(?:do not|don't|never)\s+(?:delegate|call|use|invoke)\b/i,/(?:不要|禁止|无需)(?:委派|调用|使用).{0,20}(?:Task|子代理|子智能体)?/];function p6($){return typeof $==="string"&&g6.some((J)=>J.test($))}var B5=[/\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|子代理)/],U5=[/\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 D5($){if(typeof $!=="string")return;if(U5.some((J)=>J.test($)))return"multiple-allowed";return B5.some((J)=>J.test($))?"required":void 0}function r$($){for(let J of $){let Z=D5(J);if(Z!==void 0)return Z==="required"}return!1}var w5="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.",q5="Required delegation did not complete before the retry limit.",G5=3;function d6($,J,Z){let W=(typeof $==="string"?[$]:$??[]).map((K)=>K.trim()).filter(Boolean),Y=r$(W),V=!1;if(!Y)for(let K of W){if(g6.some((Q)=>Q.test(K)))break;if(j5.some((Q)=>Q.test(K))){V=!0;break}}if(W.length===0||!Y&&!V||J.has("Task"))return{action:"none"};if(Z>=G5)return{action:"fail",message:q5};return{action:"retry",prompt:w5}}var F5=[/\b(?:use|create|enter|start|work\s+(?:in|inside))\b.{0,60}\bworktree\b/i,/(?:使用|创建|进入).{0,30}(?:worktree|工作树)/i],L5=[/\b(?:exit|leave)\b.{0,40}\bworktree\b/i,/\bworktree\b.{0,60}\b(?:action\s+)?(?:keep|remove)\b/i,/(?:退出|离开).{0,30}(?:worktree|工作树)/i],O5=[/\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 c6($){return O5.reduce((J,Z)=>J.replace(Z," "),$)}function P1($){if(typeof $!=="string")return!1;let J=c6($);return F5.some((Z)=>Z.test(J))}var f5="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.",y5="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.",A5="Required worktree lifecycle did not complete before the retry limit.",P5=3;function m6($,J,Z){if(!$)return{action:"none"};let W=c6($);if(!P1(W))return{action:"none"};let Y=L5.some((K)=>K.test(W));if(J.has("TaskWorktree"))return{action:"none"};let V=!J.has("EnterWorktree")?"EnterWorktree":Y&&!J.has("ExitWorktree")?"ExitWorktree":void 0;if(!V)return{action:"none"};if(Z>=P5)return{action:"fail",message:A5};return{action:"retry",tool:V,prompt:V==="EnterWorktree"?f5:y5}}var I6=30000;async function O2($){try{let Z=P$.getInstance().executeStopHooks({projectDir:$.workspaceRoot??j0(),sessionId:$.sessionId,permissionMode:$.permissionMode,reason:$.reason,abortSignal:$.abortSignal}),W,Y=new Promise((V)=>{W=setTimeout(()=>V("timeout"),I6)});try{let V=await Promise.race([Z,Y]);if(V==="timeout")return q2.warn(`[Loop] Stop hook 超时 (${I6}ms),按 shouldStop: true 处理`),{action:"stop"};let K=V;if(!K.shouldStop)return{action:"continue",reason:K.continueReason};return{action:"stop"}}finally{clearTimeout(W)}}catch(J){return q2.warn("[Loop] Stop hook execution failed:",J),{action:"stop"}}}async function N5($,J){let Z;while(!(Z=await $.next()).done)if(J)await J(Z.value);return Z.value}var _5=[/<system-reminder>[\s\S]*?<\/system-reminder>/gi,/<file[^>]*>[\s\S]*?<\/file>/gi,/<hooks_context>[\s\S]*?<\/hooks_context>/gi,/<[^>]+>/g];function b5($){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 E5($){let J=$;for(let X of _5)J=J.replace(X," ");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 V=Y.slice(0,60),K=V.lastIndexOf(" ");return`${(K>36?V.slice(0,K):V).trimEnd()}…`}function l6($){return E5(b5($))}import{EventEmitter as S5}from"events";import i6 from"node:path";function f2($){if(n6($.sessionId),!i6.isAbsolute($.projectPath))throw Error("projectPath must be absolute");return{sessionId:$.sessionId,projectPath:i6.resolve($.projectPath)}}function r6($){let J=f2($);return JSON.stringify([J.projectPath,J.sessionId])}function W3($,J){return r6($)===r6(J)}class N$ extends S5{static instance;constructor(){super();this.setMaxListeners(100)}static getInstance(){if(!N$.instance)N$.instance=new N$;return N$.instance}publish($,J,Z,W){let Y=f2($);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 n$=N$.getInstance();var t0=v0("Agent"),N1=new Set;async function T5($,J){let Z=$.sessionId;if(!Z||$.subagentInfo)return;if(N1.has(Z))return;if(N1.size>=5000)N1.clear();N1.add(Z);try{let W=$.workspaceRoot,Y=await o$.findSessionMetadata(Z,W);if(!Y)return;if(Y.title&&Y.title.trim())return;let V=l6(J);if(!V)return;await o$.updateSessionMetadata(Z,Y.projectPath,{title:V}),n$.publish({sessionId:Z,projectPath:Y.projectPath},"session.updated",{title:V})}catch(W){t0.debug?.("[Loop] 自动生成会话标题失败:",W)}}var y2=`<turn_aborted>
|
|
1
|
+
import{cc as M4}from"./chunk-cnhw5mqv.js";import{$c as l2,Id as g0,Kd as Q6,Ld as h1,Md as X6,Td as o$,Wc as IJ,Yc as uJ,Zc as gJ,_c as m2,ec as X$,fd as pJ,gd as R4,hd as h4,id as u2,jd as v1,kd as x4,ld as k4,md as S1,qd as wJ,yd as K1}from"./chunk-bxjc7pg7.js";import{Yd as T4}from"./chunk-53h87fmt.js";import{_d as B0,be as EJ,ce as I0}from"./chunk-qdv0n8yt.js";import{df as $4}from"./chunk-pshyn3yy.js";import{ef as E4,ff as i0,gf as y4,hf as jJ,kf as E1,lf as K6,mf as BJ,nf as UJ,pf as DJ}from"./chunk-q2exry0f.js";import{$f as r0,_f as J$,cg as S4,gg as z4}from"./chunk-cqqmkwvn.js";import{tg as P$}from"./chunk-swtap0bs.js";import{Dh as oJ}from"./chunk-4w4wjm49.js";import{Sh as j0}from"./chunk-ecd727xh.js";import{si as v0}from"./chunk-dvv28pkc.js";import{Gi as CJ}from"./chunk-53aapkv1.js";import{Ri as b$,Ti as n6,Ui as _0,Vi as R1,Xi as xJ,Yi as kJ,Zi as vJ}from"./chunk-rkdxqx8m.js";import{_i as O8}from"./chunk-tf7ezqew.js";function y$($){return $.role==="system"&&Array.isArray($.content)}function f$($){if($.role!=="system"||!$.metadata||Array.isArray($.metadata))return!1;return typeof $.metadata==="object"&&$.metadata.contextualProjectRules===!0}class y1{systemMessages;_contextualSystemMessages;_history;_pending=[];_contextRevision=0;context;constructor($,J){this.context=$;let Z=$.messages.find(y$);if(this._contextualSystemMessages=$.messages.filter(f$),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)=>!y$(W)&&!f$(W))}get historyLength(){return this._history.length}get history(){return this._history}get pending(){return this._pending}get contextRevision(){return this._contextRevision}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(!f$($))throw Error("Contextual project instructions require safe metadata");this._contextualSystemMessages.push($),this.systemMessages.push($)}syncContextualSystemMessages(){let $=this.systemMessages.filter(y$);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)=>!y$(J)&&!f$(J)),this._contextRevision++}restoreDurableHistory($){this._contextualSystemMessages=$.filter(f$),this._history=$.filter((J)=>!y$(J)&&!f$(J)),this._pending=[],this.syncContextualSystemMessages(),this._contextRevision++}removeMessages($){let J=[this._history.length,this._pending.length,this._contextualSystemMessages.length];if(this._history=this._history.filter((Z)=>!$(Z)),this._pending=this._pending.filter((Z)=>!$(Z)),this._contextualSystemMessages=this._contextualSystemMessages.filter((Z)=>!$(Z)),this.syncContextualSystemMessages(),this._history.length!==J[0]||this._pending.length!==J[1]||this._contextualSystemMessages.length!==J[2])this._contextRevision++}writeback(){this.commitPending(),this.context.messages=[...this._contextualSystemMessages,...this._history]}get hasSystemPrompt(){return this.systemMessages.length>0}}function E6($){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 S6($){return{budget:$.budget,usage:0,consecutiveContinuations:0,lastOutputDelta:0,isSubagent:$.isSubagent??!1}}function T6($,J,Z){return{...$,usage:$.usage+J,lastOutputDelta:J,consecutiveContinuations:Z?$.consecutiveContinuations+1:0}}import Q$ from"node:path";var l4=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"]),i4=/^(LD_.+|DYLD_.+|PATH)$/,M6=/^([A-Za-z_][A-Za-z0-9_]*)=([\w./:@-]*)$/;function l$($){let J=$;while(!0){let Z=J.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!Z)break;let W=Z[1],Y=Z[2],V=W.match(M6);if(!V)break;let K=V[1];if(!l4.has(K))break;J=Y}return J}function gZ($){let J=$;while(!0){let Z=J.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!Z)break;let W=Z[1],Y=Z[2],V=W.match(M6);if(!V)break;let K=V[1];if(i4.test(K))break;J=Y}return J}var r4=[/^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 w2($){let J=$,Z=!0;while(Z){Z=!1;for(let W of r4){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 i$($){let J=[],Z="",W=!1,Y=!1,V=!1;for(let K=0;K<$.length;K++){let Q=$[K];if(V){Z+=Q,V=!1;continue}if(Q==="\\"&&!W){Z+=Q,V=!0;continue}if(Q==="'"&&!Y){W=!W,Z+=Q;continue}if(Q==='"'&&!W){Y=!Y,Z+=Q;continue}if(W||Y){Z+=Q;continue}if(Q==="|"){if(K+1<$.length&&$[K+1]==="|"){if(Z.trim())J.push(Z.trim());Z="",K++;continue}return null}if(Q===">"||Q==="<")return null;if(Q==="&"&&K+1<$.length&&$[K+1]==="&"){if(Z.trim())J.push(Z.trim());Z="",K++;continue}if(Q==="&")return null;if(Q===";"){if(Z.trim())J.push(Z.trim());Z="";continue}Z+=Q}if(Z.trim())J.push(Z.trim());return J.length>0?J:null}function R6($){let J=!1,Z=!1,W=!1;for(let Y=0;Y<$.length;Y++){let V=$[Y];if(W){W=!1;continue}if(V==="\\"&&!J){W=!0;continue}if(V==="'"&&!Z){J=!J;continue}if(V==='"'&&!J){Z=!Z;continue}if(J)continue;if(V==="$"){let K=$[Y+1];if(K&&/[A-Za-z_@*#?!$0-9({]/.test(K))return!0}if(V==="`")return!0;if(Z)continue;if(V==="|")return!0;if(V===">"||V==="<")return!0;if(V==="{"){let K=$.slice(Y);if(/^\{[^}]*,[^}]*\}/.test(K)||/^\{[^}]*\.\.[^}]*\}/.test(K))return!0}}return!1}function K$($){let J=[],Z="",W=!1,Y=!1,V=!1;for(let K=0;K<$.length;K++){let Q=$[K];if(V){Z+=Q,V=!1;continue}if(Q==="\\"&&!W){if(V=!0,Y){let X=$[K+1];if(X&&'$`"\\'.includes(X))continue;Z+=Q,V=!1}continue}if(Q==="'"&&!Y){W=!W;continue}if(Q==='"'&&!W){Y=!Y;continue}if(!W&&!Y&&/[ \t]/.test(Q)){if(Z)J.push(Z),Z="";continue}Z+=Q}if(Z)J.push(Z);return J}var n4=new Set(["npm","pnpm","yarn","bun"]),h6=new Set(["biome","eslint","jest","mypy","pyright","pytest","ruff","tsc","vitest"]),o4=new Set(["-u","--fix","--update","--update-snapshot","--updateSnapshot","--watch","--watchAll","--write"]),a4=/[ \t]*;[ \t]*echo[ \t]+"[A-Za-z0-9 _:=.-]*(?:\$\{PIPESTATUS\[0\]\}|\$\?)[A-Za-z0-9 _:=.-]*"[ \t]*$/;function s4($){return $!==void 0&&/^(?:test|lint|build|type-?check)(?::[\w.-]+)*$/i.test($)}function x6($){return $.replace(/\s+2>&1\s*$/,"").trim()}function t4($,J,Z){if(!Z||J.length!==2)return;let W=/^(.+?)[ \t]+&&[ \t]+([\s\S]+)$/.exec($);if(!W)return;let Y=K$(W[1]??"");if(Y.length!==2||Y[0]!=="cd")return;let V=Y[1];if(!V||V==="-")return;let K=Q$.isAbsolute(V)?Q$.resolve(V):Q$.resolve(Z,V);if(!X$.isWithinWorkspace(K,Z))return;return W[2]?.trim()||void 0}function e4($){let J=[],Z=!1,W=!1,Y=!1;for(let V=0;V<$.length;V++){let K=$[V];if(Y){Y=!1;continue}if(K==="\\"&&!Z){Y=!0;continue}if(K==="'"&&!W){Z=!Z;continue}if(K==='"'&&!Z){W=!W;continue}if(K!=="|"||Z||W)continue;if($[V+1]==="|")return;J.push(V)}return J}function $5($){let J=K$($),[Z,W,Y]=J;if(Z!=="head"&&Z!=="tail")return!1;if(J.length===1)return!0;let V=(K)=>K!==void 0&&/^[1-9]\d{0,4}$/.test(K);if(J.length===2)return W?.startsWith("--lines=")&&V(W.slice(8))||W?.startsWith("-")&&V(W.slice(1));return J.length===3&&(W==="-n"||W==="--lines")&&V(Y)}function J5($){let J=x6($.replace(a4,"").trim()),Z=e4(J);if(!Z)return;if(Z.length===0)return k6(J);if(Z.length!==1)return;let W=Z[0];if(W===void 0)return;let Y=x6(J.slice(0,W).trim()),V=J.slice(W+1).trim();if(!Y||!$5(V))return;return k6(Y)}function k6($){let Z=i$($)?.at(-1);if(!Z)return $;let W=K$(Z),[Y,V]=W;if(!(Y==="vitest"||(Y==="npx"||Y==="bunx")&&V==="vitest")||W.some((Q)=>Q==="--configLoader"||Q.startsWith("--configLoader=")))return $;return`${$} --configLoader runner`}function A$($,J){let Z=J5($);if(!Z)return!1;let W=l$(Z),Y=i$(W);if(!Y||R6(W)||/[\r\n]/.test(W))return!1;let V=Y.length===1?Y[0]:t4(W,Y,J);if(!V)return!1;let K=K$(V);if(K.length===0||K.some((j)=>[...o4].some((B)=>j===B||j.startsWith(`${B}=`))))return!1;let[Q,X,H]=K;if(n4.has(Q??""))return s4(X==="run"?H:X)||X==="--test";if((Q==="npx"||Q==="bunx")&&h6.has(X??""))return!0;if(h6.has(Q??""))return!0;if(Q==="node"&&X==="--test")return!0;if(Q==="go"&&["build","test","vet"].includes(X??""))return!0;return Q==="cargo"&&["build","check","clippy","test"].includes(X??"")}function lZ($,J){if($===void 0)return!0;if(typeof $!=="string"||$.split(/[\\/]/).includes(".."))return!1;if(!J)return!Q$.isAbsolute($);let Z=Q$.isAbsolute($)?Q$.resolve($):Q$.resolve(J,$);return X$.isWithinWorkspace(Z,J)}var q2=v0("Agent"),Z5=3;function G2($,J,Z){if($!=="length")return{action:"none"};if(J>=Z5)return{action:"truncated"};if(E6(Z)==="stop")return q2.info("[Loop] Token budget: diminishing returns detected, skipping recovery"),{action:"budget_stop"};return{action:"recover"}}var W5=[/:\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],Y5=/```[\s\S]{50,}```/,v6="请执行你提到的操作,不要只是描述。使用 Edit/Write/ApplyPatch/Bash 工具来实际修改文件。",V5=2;function F2($,J,Z=!0){if(!$||J>=V5)return{action:"none"};if(!Z&&Y5.test($))return{action:"retry",prompt:v6};let W=$.slice(-200),Y=W.match(/```/g);if(Y&&Y.length%2!==0)return{action:"none"};if(W5.some((K)=>K.test(W)))return{action:"retry",prompt:v6};return{action:"none"}}var K5=[/\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}(?:测试|单测|集成测试|检查|构建)/],C6={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},Q5={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},X5="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.",H5="Required verification did not run successfully before the retry limit.",z5=3;function u6($,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&&A$(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 V of Y)if(typeof V==="string"&&A$(V,W))$.add(V)}function L2($,J,Z){if(!$||!K5.some((X)=>X.test($)))return{action:"none"};let W=Object.keys(C6).filter((X)=>C6[X].test($)),Y=[...J],V=W.filter((X)=>!Y.some((H)=>Q5[X].test(H)));if(W.length>0?V.length===0:Y.some((X)=>A$(X)))return{action:"none"};if(Z>=z5)return{action:"fail",message:H5};let Q=W.length>1&&V.length>0?` Missing successful verification categories: ${V.join(", ")}.`:"";return{action:"retry",prompt:`${X5}${Q}`}}var j5=[/\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|子代理|子智能体)/],g6=[/\b(?:do not|don't|never)\s+(?:delegate|call|use|invoke)\b/i,/(?:不要|禁止|无需)(?:委派|调用|使用).{0,20}(?:Task|子代理|子智能体)?/];function p6($){return typeof $==="string"&&g6.some((J)=>J.test($))}var B5=[/\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|子代理)/],U5=[/\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 D5($){if(typeof $!=="string")return;if(U5.some((J)=>J.test($)))return"multiple-allowed";return B5.some((J)=>J.test($))?"required":void 0}function r$($){for(let J of $){let Z=D5(J);if(Z!==void 0)return Z==="required"}return!1}var w5="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.",q5="Required delegation did not complete before the retry limit.",G5=3;function d6($,J,Z){let W=(typeof $==="string"?[$]:$??[]).map((K)=>K.trim()).filter(Boolean),Y=r$(W),V=!1;if(!Y)for(let K of W){if(g6.some((Q)=>Q.test(K)))break;if(j5.some((Q)=>Q.test(K))){V=!0;break}}if(W.length===0||!Y&&!V||J.has("Task"))return{action:"none"};if(Z>=G5)return{action:"fail",message:q5};return{action:"retry",prompt:w5}}var F5=[/\b(?:use|create|enter|start|work\s+(?:in|inside))\b.{0,60}\bworktree\b/i,/(?:使用|创建|进入).{0,30}(?:worktree|工作树)/i],L5=[/\b(?:exit|leave)\b.{0,40}\bworktree\b/i,/\bworktree\b.{0,60}\b(?:action\s+)?(?:keep|remove)\b/i,/(?:退出|离开).{0,30}(?:worktree|工作树)/i],O5=[/\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 c6($){return O5.reduce((J,Z)=>J.replace(Z," "),$)}function P1($){if(typeof $!=="string")return!1;let J=c6($);return F5.some((Z)=>Z.test(J))}var f5="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.",y5="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.",A5="Required worktree lifecycle did not complete before the retry limit.",P5=3;function m6($,J,Z){if(!$)return{action:"none"};let W=c6($);if(!P1(W))return{action:"none"};let Y=L5.some((K)=>K.test(W));if(J.has("TaskWorktree"))return{action:"none"};let V=!J.has("EnterWorktree")?"EnterWorktree":Y&&!J.has("ExitWorktree")?"ExitWorktree":void 0;if(!V)return{action:"none"};if(Z>=P5)return{action:"fail",message:A5};return{action:"retry",tool:V,prompt:V==="EnterWorktree"?f5:y5}}var I6=30000;async function O2($){try{let Z=P$.getInstance().executeStopHooks({projectDir:$.workspaceRoot??j0(),sessionId:$.sessionId,permissionMode:$.permissionMode,reason:$.reason,abortSignal:$.abortSignal}),W,Y=new Promise((V)=>{W=setTimeout(()=>V("timeout"),I6)});try{let V=await Promise.race([Z,Y]);if(V==="timeout")return q2.warn(`[Loop] Stop hook 超时 (${I6}ms),按 shouldStop: true 处理`),{action:"stop"};let K=V;if(!K.shouldStop)return{action:"continue",reason:K.continueReason};return{action:"stop"}}finally{clearTimeout(W)}}catch(J){return q2.warn("[Loop] Stop hook execution failed:",J),{action:"stop"}}}async function N5($,J){let Z;while(!(Z=await $.next()).done)if(J)await J(Z.value);return Z.value}var _5=[/<system-reminder>[\s\S]*?<\/system-reminder>/gi,/<file[^>]*>[\s\S]*?<\/file>/gi,/<hooks_context>[\s\S]*?<\/hooks_context>/gi,/<[^>]+>/g];function b5($){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 E5($){let J=$;for(let X of _5)J=J.replace(X," ");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 V=Y.slice(0,60),K=V.lastIndexOf(" ");return`${(K>36?V.slice(0,K):V).trimEnd()}…`}function l6($){return E5(b5($))}import{EventEmitter as S5}from"events";import i6 from"node:path";function f2($){if(n6($.sessionId),!i6.isAbsolute($.projectPath))throw Error("projectPath must be absolute");return{sessionId:$.sessionId,projectPath:i6.resolve($.projectPath)}}function r6($){let J=f2($);return JSON.stringify([J.projectPath,J.sessionId])}function W3($,J){return r6($)===r6(J)}class N$ extends S5{static instance;constructor(){super();this.setMaxListeners(100)}static getInstance(){if(!N$.instance)N$.instance=new N$;return N$.instance}publish($,J,Z,W){let Y=f2($);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 n$=N$.getInstance();var t0=v0("Agent"),N1=new Set;async function T5($,J){let Z=$.sessionId;if(!Z||$.subagentInfo)return;if(N1.has(Z))return;if(N1.size>=5000)N1.clear();N1.add(Z);try{let W=$.workspaceRoot,Y=await o$.findSessionMetadata(Z,W);if(!Y)return;if(Y.title&&Y.title.trim())return;let V=l6(J);if(!V)return;await o$.updateSessionMetadata(Z,Y.projectPath,{title:V}),n$.publish({sessionId:Z,projectPath:Y.projectPath},"session.updated",{title:V})}catch(W){t0.debug?.("[Loop] 自动生成会话标题失败:",W)}}var y2=`<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>`,H$="Tool execution was blocked because its durable call record could not be committed. No tool side effect was started.",o6="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 _$ 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 l0($,J,Z,W=null,Y,V={}){let K=V.required??$.executionEngine!==void 0;try{let Q=z$($),X=typeof Z==="string"?Z.trim()!=="":Z.some((H)=>H.type==="text"?H.text.trim()!=="":!0);if(Q&&J.sessionId&&X){let H=await Q.saveMessage(J.sessionId,"user",Z,W,Y,J.subagentInfo);if(K&&!H)throw Error("Durable user-message commit returned no identity");if(Y?.clientVisible!==!1)T5(J,Z);return H}if(K&&J.sessionId&&X)throw Error("Durable user-message storage is unavailable")}catch(Q){if(t0.warn("[Loop] 保存用户消息失败:",Q),K)throw new _$("user_message",{cause:Q})}return null}async function C0($,J,Z,W,Y,V,K={}){let Q=K.required??$.executionEngine!==void 0;try{let X=z$($),H=Boolean(Z.trim()||Y?.trim());if(X&&J.sessionId&&H){let j=await X.saveMessage(J.sessionId,"assistant",Z,W,V,J.subagentInfo,Y);if(Q&&!j)throw Error("Durable assistant-message commit returned no identity");return j}if(Q&&J.sessionId&&H)throw Error("Durable assistant-message storage is unavailable")}catch(X){if(t0.warn("[Loop] 保存助手消息失败:",X),Q)throw new _$("assistant_message",{cause:X})}return null}async function a6($,J,Z){try{let W=z$($);if(W&&J.sessionId)return await W.saveMessage(J.sessionId,"system",y2,Z,void 0,J.subagentInfo)}catch(W){t0.warn("[Loop] 保存中断边界失败:",W)}return null}async function s6($,J,Z,W,Y){try{let V=z$($);if(!V||!J.sessionId||Z.length===0)return null;return await V.saveMessage(J.sessionId,"system",`<contextual-project-instructions-ref count="${Z.length}" />`,Y,{contextualProjectRules:!0,ruleReferences:JSON.parse(JSON.stringify(Z.map((K)=>({...K})))),triggerPaths:[...W]},J.subagentInfo)}catch(V){t0.warn("[Loop] 保存 contextual project rules provenance 失败:",V)}return null}async function A2($,J,Z,W,Y,V={}){try{let K=z$($);if(K&&J.sessionId){let Q=await K.saveToolUse(J.sessionId,Z,W,Y,J.subagentInfo,V.providerToolCallId);if(V.required&&!Q)throw Error("Durable tool-use commit returned no identity");return Q}if(V.required&&J.sessionId)throw Error("Durable tool-use storage is unavailable")}catch(K){if(t0.warn("[Loop] 保存工具调用失败:",K),V.required)throw K}return null}async function _1($,J,Z,W,Y,V,K,Q,X,H={}){try{let j=z$($);if(j&&J.sessionId){let B=await j.saveToolResult(J.sessionId,Z,W,Y,V,K,J.subagentInfo,Q,X);if(H.required&&!B)throw Error("Durable tool-result commit returned no identity");return B}if(H.required&&J.sessionId)throw Error("Durable tool-result storage is unavailable")}catch(j){if(t0.warn("[Loop] 保存工具结果失败:",j),H.required)throw j}return null}async function a$($,J,Z,W,Y={}){try{let V=z$($);if(V&&J.sessionId){let K=await V.saveCompaction(J.sessionId,Z,W,null);if(Y.required&&!K)throw Error("Compaction checkpoint commit returned no identity");return K||null}if(Y.required&&J.sessionId)throw Error("Compaction checkpoint storage is unavailable")}catch(V){if(t0.warn("[Loop] 保存压缩数据失败:",V),Y.required)throw V}return null}async function G0($){let{deps:J,context:Z,state:W,assistantContent:Y,assistantReasoningContent:V,lastMessageUuid:K,controlPrompt:Q,controlMetadata:X}=$;W.appendAssistant({role:"assistant",content:Y,reasoningContent:V});let H=K,j=await C0(J,Z,Y,H,V);if(j)H=j;if(Q!==void 0){let B={role:"user",content:Q};if(X)B.metadata=X;W.appendControl("user",B);let z=await l0(J,Z,B.content,H,X);if(z)H=z}return H}import{createHash as H6}from"node:crypto";import{promises as i5}from"node:fs";import r5 from"node:path";import{nanoid as e0}from"nanoid";import*as Y0 from"node:fs/promises";import*as j$ from"node:path";var t6={enabled:!0,maxIndexLines:200};var M5="memory",e6="MEMORY.md";class P2{memoryDir;config;initialized=!1;constructor($,J,Z){if(Z)this.memoryDir=Z;else{let W=b$($);this.memoryDir=j$.join(W,M5)}this.config={...t6,...J}}async initialize(){if(this.initialized)return;await Y0.mkdir(this.memoryDir,{recursive:!0}),this.initialized=!0}async loadIndex(){if(!this.config.enabled)return null;await this.initialize();let $=j$.join(this.memoryDir,e6);try{let J=await Y0.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{Ah as F}from"./chunk-
|
|
1
|
+
import{Ah as F}from"./chunk-y21nw7g1.js";import{xi as D,yi as E}from"./chunk-dgf2xzzd.js";import G from"node:path";function A(b){if(Array.isArray(b))return b.map((q)=>A(q));if(b!==null&&typeof b==="object"&&Object.getPrototypeOf(b)===Object.prototype)return Object.fromEntries(Object.entries(b).map(([q,w])=>[q,A(w)]));return b}function H(b){return A(b)}function I(b,q){let w=new D(q?.credentials??E().credentials);return w.configureModelProviders(b.modelProviders,b.models),w}async function Q(b,q){let w=G.resolve(b),x=F.getInstance(),[J,K]=await Promise.all([x.loadWorkspaceModelConfig(w,q),x.loadWorkspaceRuntimeSettings(w,q)]),z={...H(q),...J,...K},B=I(z);return x.validateConfig(z,B),{projectRoot:w,config:z,catalog:B}}function T(b){let q=H(b.config);return{projectRoot:G.resolve(b.projectRoot),config:q,catalog:I(q,b.catalog)}}
|
|
2
2
|
export{H as vf,Q as wf,T as xf};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{te as a,ue as b,ve as c}from"./chunk-
|
|
1
|
+
import{te as a,ue as b,ve as c}from"./chunk-2aysvx6k.js";import"./chunk-bksfg23m.js";import"./chunk-kr8rv2b9.js";import"./chunk-v508x7cg.js";import"./chunk-pshyn3yy.js";import"./chunk-935v0gpc.js";import"./chunk-y21nw7g1.js";import"./chunk-4w4wjm49.js";import"./chunk-6k5k40p8.js";import"./chunk-p3m1jyg5.js";import"./chunk-ecd727xh.js";import"./chunk-x05zyqzf.js";import"./chunk-dvv28pkc.js";import"./chunk-dgf2xzzd.js";import"./chunk-z52s82k7.js";import"./chunk-53aapkv1.js";import"./chunk-vbwvsgs1.js";import"./chunk-sr10jsjs.js";import"./chunk-rkdxqx8m.js";import"./chunk-tf7ezqew.js";export{a as validatePermissions,c as validateOutput,b as loadConfiguration};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a,b as i,c as l,d as m}from"./chunk-
|
|
1
|
+
import{a,b as i,c as l,d as m}from"./chunk-9aqs02va.js";import"./chunk-3pwq56je.js";import"./chunk-xv3a1se1.js";import"./chunk-9n9506vy.js";import"./chunk-mnkdxt1v.js";import"./chunk-cxbrqnqs.js";import"./chunk-fys5xx87.js";import"./chunk-ypbnczjp.js";import"./chunk-z9g2x0vm.js";import"./chunk-23v8c9b8.js";import"./chunk-gbjk078c.js";import"./chunk-cnhw5mqv.js";import"./chunk-bxjc7pg7.js";import"./chunk-53h87fmt.js";import"./chunk-qdv0n8yt.js";import{ye as n}from"./chunk-k3tqna1w.js";import"./chunk-ng96f4xd.js";import{Ue as s}from"./chunk-kr8rv2b9.js";import"./chunk-v508x7cg.js";import"./chunk-pshyn3yy.js";import"./chunk-q2exry0f.js";import"./chunk-tj2efrs1.js";import"./chunk-hv6hrsnk.js";import"./chunk-gjw8100g.js";import"./chunk-90q4206c.js";import"./chunk-cqqmkwvn.js";import"./chunk-9g64g1np.js";import"./chunk-935v0gpc.js";import"./chunk-swtap0bs.js";import"./chunk-eyb9psbc.js";import"./chunk-y21nw7g1.js";import"./chunk-4w4wjm49.js";import"./chunk-6k5k40p8.js";import"./chunk-p3m1jyg5.js";import"./chunk-ecd727xh.js";import"./chunk-x05zyqzf.js";import"./chunk-dvv28pkc.js";import"./chunk-dgf2xzzd.js";import"./chunk-z52s82k7.js";import"./chunk-53aapkv1.js";import"./chunk-vbwvsgs1.js";import"./chunk-sr10jsjs.js";import"./chunk-rkdxqx8m.js";import"./chunk-tf7ezqew.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,4 +1,4 @@
|
|
|
1
|
-
import{a as T,b as W,c as X,d as Y}from"./chunk-
|
|
1
|
+
import{a as T,b as W,c as X,d as Y}from"./chunk-9aqs02va.js";import"./chunk-3pwq56je.js";import"./chunk-xv3a1se1.js";import"./chunk-9n9506vy.js";import"./chunk-mnkdxt1v.js";import"./chunk-cxbrqnqs.js";import"./chunk-fys5xx87.js";import"./chunk-ypbnczjp.js";import"./chunk-z9g2x0vm.js";import"./chunk-23v8c9b8.js";import"./chunk-gbjk078c.js";import"./chunk-cnhw5mqv.js";import"./chunk-bxjc7pg7.js";import"./chunk-53h87fmt.js";import"./chunk-qdv0n8yt.js";import{ye as R}from"./chunk-k3tqna1w.js";import"./chunk-ng96f4xd.js";import{Ue as Q}from"./chunk-kr8rv2b9.js";import"./chunk-v508x7cg.js";import"./chunk-pshyn3yy.js";import"./chunk-q2exry0f.js";import"./chunk-tj2efrs1.js";import"./chunk-hv6hrsnk.js";import"./chunk-gjw8100g.js";import"./chunk-90q4206c.js";import"./chunk-cqqmkwvn.js";import"./chunk-9g64g1np.js";import"./chunk-935v0gpc.js";import"./chunk-swtap0bs.js";import"./chunk-eyb9psbc.js";import"./chunk-y21nw7g1.js";import"./chunk-4w4wjm49.js";import"./chunk-6k5k40p8.js";import"./chunk-p3m1jyg5.js";import"./chunk-ecd727xh.js";import"./chunk-x05zyqzf.js";import"./chunk-dvv28pkc.js";import"./chunk-dgf2xzzd.js";import"./chunk-z52s82k7.js";import{Gi as M}from"./chunk-53aapkv1.js";import"./chunk-vbwvsgs1.js";import"./chunk-sr10jsjs.js";import"./chunk-rkdxqx8m.js";import"./chunk-tf7ezqew.js";import m from"chalk";import K from"open";var A=`
|
|
2
2
|
____ _ _
|
|
3
3
|
| __ )| | __ _ __| | ___
|
|
4
4
|
| _ \\| |/ _\` |/ _\` |/ _ \\
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{Pe as N}from"./chunk-
|
|
1
|
+
import{Pe as N}from"./chunk-kr8rv2b9.js";import{tg as $}from"./chunk-swtap0bs.js";import{Sh as _}from"./chunk-ecd727xh.js";import{qi as Y,si as Z}from"./chunk-dvv28pkc.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 xe,y as ye,j as ze,C as Ae};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{s as gz,t as cz,u as Az,v as Nz,w as Pz}from"./chunk-
|
|
1
|
+
import{s as gz,t as cz,u as Az,v as Nz,w as Pz}from"./chunk-9n9506vy.js";import{x as T}from"./chunk-mnkdxt1v.js";import{A as Uz,B as Vz,C as wz,D as Kz,y as uz,z as Gz}from"./chunk-cxbrqnqs.js";import{$ as Bz,K as b,T as Hz,U as Xz,Y as Lz,aa as jz,da as Fz,ta as Dz,ua as _z,va as Oz,wa as qz}from"./chunk-fys5xx87.js";import"./chunk-ypbnczjp.js";import{Ka as fz}from"./chunk-z9g2x0vm.js";import{Ma as Yz}from"./chunk-23v8c9b8.js";import{Gb as Qz,Pb as Wz,ub as $z}from"./chunk-gbjk078c.js";import{_b as f}from"./chunk-cnhw5mqv.js";import{Fd as g,Gd as Jz,Id as E,Ld as Zz,Qd as P,Td as U,dd as n,nd as h,od as u,pd as s,ud as t,xd as e,zd as zz}from"./chunk-bxjc7pg7.js";import"./chunk-53h87fmt.js";import"./chunk-qdv0n8yt.js";import{ye as pz}from"./chunk-k3tqna1w.js";import"./chunk-ng96f4xd.js";import{Te as Mz,Ue as kz}from"./chunk-kr8rv2b9.js";import"./chunk-v508x7cg.js";import{df as c}from"./chunk-pshyn3yy.js";import{if as o}from"./chunk-q2exry0f.js";import"./chunk-tj2efrs1.js";import{tf as Iz}from"./chunk-hv6hrsnk.js";import"./chunk-gjw8100g.js";import"./chunk-90q4206c.js";import"./chunk-cqqmkwvn.js";import{lg as Cz}from"./chunk-9g64g1np.js";import"./chunk-935v0gpc.js";import"./chunk-swtap0bs.js";import"./chunk-eyb9psbc.js";import{dh as Sz,gh as yz}from"./chunk-y21nw7g1.js";import"./chunk-4w4wjm49.js";import"./chunk-6k5k40p8.js";import{Kh as k,Lh as r,Nh as I,Oh as C}from"./chunk-p3m1jyg5.js";import{Sh as Ez}from"./chunk-ecd727xh.js";import"./chunk-x05zyqzf.js";import{si as S}from"./chunk-dvv28pkc.js";import"./chunk-dgf2xzzd.js";import{Ci as hz,zi as Tz}from"./chunk-z52s82k7.js";import"./chunk-53aapkv1.js";import"./chunk-vbwvsgs1.js";import"./chunk-sr10jsjs.js";import{Yi as a}from"./chunk-rkdxqx8m.js";import"./chunk-tf7ezqew.js";import{Readable as tz,Writable as ez}from"node:stream";import*as y from"@agentclientprotocol/sdk";import xz from"node:path";import{PROTOCOL_VERSION as nz,RequestError as sz}from"@agentclientprotocol/sdk";import{RequestError as Rz}from"@agentclientprotocol/sdk";import{nanoid as M}from"nanoid";var G=S("Agent");function i(z){if(!z)return{};return Object.fromEntries(z.map((Z)=>[Z.name,Z.value]))}function vz(z){if("command"in z)return{type:"stdio",command:z.command,args:z.args,env:i(z.env)};if("url"in z)return{type:z.type,url:z.url,headers:i("headers"in z?z.headers:void 0)};return null}function lz(z){let Z={};for(let J of z){let Y=vz(J);if(Y)Z[J.name]=Y}return Z}function bz(z){if(typeof z==="string")return z?[{type:"text",text:z}]:[];return z.flatMap((Z)=>{if(Z.type==="text")return Z.text?[{type:"text",text:Z.text}]:[];let J=Z.image_url.url,Y=/^data:([^;,]+);base64,(.+)$/s.exec(J);if(!Y)return[{type:"text",text:"[Image]"}];return[{type:"image",mimeType:Y[1]??"image/png",data:Y[2]??""}]})}function iz(z){let Z=Jz(z.metadata);return Z?[{type:"text",text:g(Z)}]:bz(z.content)}function az(z){return[`Status: ${z.status}`,`Exit code: ${z.exitCode??"null"}`,`Duration: ${(z.durationMs/1000).toFixed(3)} seconds`].join(`
|
|
2
2
|
`)}function rz(z){if(!o(z)||z.reason!=="queue_full"||z.resource!=="pending_count"&&z.resource!=="pending_bytes")return;return{...h("capacity"),resource:z.resource}}function oz(z){if(!(z instanceof Rz)||!z.data||typeof z.data!=="object")return;let Z=z.data;if(!s(Z.taskFailure)||Z.toolExecutionStarted!==!1||!Number.isInteger(Z.toolCallsCount)||Z.toolCallsCount<0||Z.outputStarted!==!1)return;return{taskFailure:Z.taskFailure,toolExecutionStarted:Z.toolExecutionStarted,toolCallsCount:Z.toolCallsCount,outputStarted:Z.outputStarted}}class x{id;cwd;connection;clientCapabilities;options;agent=null;runtime=null;pendingPrompt=null;pendingPromptCompletion=null;pendingUserShell=null;pendingUserShellCompletion=null;pendingSideConversation=null;pendingSideConversationCompletion=null;pendingResumeRequested=!1;pendingResumeAttempt=0;projectedPendingResumeInputIds=new Set;pendingResumeRecoveryStartedAt=0;pendingResumeInFlight=!1;pendingResumeScheduled=!1;pendingResumeGeneration=0;pendingResumeTimer=null;pendingResumeCompletion=null;pendingResumeNextDelayMs=null;availableCommandsTimer=null;taskStatusUnsubscribe;destroyed=!1;destroyFinished=!1;destroyPromise;messages;contextMessages;mode;updateEgress;constructor(z,Z,J,Y,H={}){this.id=z;this.cwd=Z;this.connection=J;this.clientCapabilities=Y;this.options=H;this.messages=[...H.initialMessages??[]],this.contextMessages=[...this.messages],this.mode=this.mapPermissionModeToMode(H.permissionMode),this.updateEgress=new Kz({maxPendingItems:Gz,maxPendingBytes:Uz,writeTimeoutMs:Vz,signal:J.signal,sizeOf:(X)=>Buffer.byteLength(JSON.stringify(X)),write:async(X)=>{await J.sessionUpdate(X)},onFailure:(X)=>this.handleUpdateEgressFailure(X)})}async refreshPersistedMessages(){let[z,Z]=await Promise.all([U.loadSession(this.id,this.cwd),U.loadSessionModelContext(this.id,this.cwd)]);if(z.length>0)this.messages=z;if(Z.length>0)this.contextMessages=Z}async loadModelContextOr(z){let Z=await U.loadSessionModelContext(this.id,this.cwd);return Z.length>0?Z:[...z]}mapPermissionModeToMode(z){switch(z){case"yolo":return"yolo";case"autoEdit":return"auto-edit";case"plan":return"plan";case"default":default:return"default"}}createAgent(){if(!this.runtime)throw Error("Session runtime is unavailable");return Fz.createWithRuntime(this.runtime,{sessionId:this.id,...this.options.taskWorktree?{toolBlacklist:["EnterWorktree","ExitWorktree"]}:{}})}async initialize(){if(G.debug(`[AcpSession ${this.id}] Initializing...`),await U.setSessionPermissionMode(this.id,this.cwd,this.mapModeToPermissionMode()??"default"),b.initializeSession(this.connection,this.id,this.clientCapabilities,this.cwd,async(W)=>{await this.sendUpdateAndWait(W)}),G.debug(`[AcpSession ${this.id}] ACP service context initialized`),await Wz.resolvePendingWithHandler(this.cwd,this.id,{requestConfirmation:(W)=>this.requestPermission(W)}))await this.refreshPersistedMessages();else if((this.options.initialMessages?.length??0)>0)this.contextMessages=await this.loadModelContextOr(this.options.initialMessages??[]);let Z=this.options.mcpServers?lz(this.options.mcpServers):void 0,J=b.getInstance().getTerminalService(this.id);if(this.runtime=await Lz.create({sessionId:this.id,workspaceRoot:this.cwd,permissionMode:this.mapModeToPermissionMode(),...Z?{mcpServers:Z}:{},...this.options.taskWorktree?{taskWorktree:this.options.taskWorktree}:{},...this.options.taskIsolation?{taskIsolation:this.options.taskIsolation}:{},userShellExecutor:{execute:async(W,B)=>{let L=await J.execute(W,{cwd:B.cwd,env:B.env,timeout:B.timeoutMs,signal:B.signal,allowLocalFallback:!1,onOutput:(j)=>B.onOutput?.("stdout",j)});return{exitCode:L.exitCode,stdout:L.stdout,stderr:L.stderr,...L.error?{error:L.error}:{},timedOut:L.failureKind==="timeout",aborted:L.failureKind==="aborted"}}},...(this.options.initialMessages?.length??0)>0?{sessionStart:{isResume:!0,resumeSessionId:this.id}}:{}}),await T.recoverInterrupted(this.cwd,this.id,this.runtime))await this.refreshPersistedMessages();this.agent=await this.createAgent(),await _z(this.cwd),G.debug(`[AcpSession ${this.id}] Agent created successfully`),this.taskStatusUnsubscribe?.(),this.taskStatusUnsubscribe=$z.subscribe((W)=>{if(W.sessionId!==this.id||W.projectPath!==this.cwd)return;if(W.type==="subagent.completion.queued"){this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/backgroundSubagentCompletion":W.properties}}),this.requestPendingResume();return}if(W.type==="task.delivery"){if(!W.properties.taskDelivery||typeof W.properties.taskDelivery!=="object")return;this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:typeof W.properties.updatedAt==="string"?W.properties.updatedAt:new Date().toISOString(),_meta:{"blade/taskDelivery":W.properties.taskDelivery,...W.properties.taskWorktreeRemoved===!0?{"blade/taskWorktreeRemoved":!0}:{}}});return}if(W.type.startsWith("team.")){let{teamName:B,messageId:L,content:j}=W.properties,F=W.properties.metadata;if(W.type==="team.message.received"&&typeof B==="string"&&typeof L==="string"&&typeof j==="string"&&Xz(F,{messageId:L,teamName:B}))(async()=>{let V=await this.runtime?.enqueueSteering(j,{allowBeforeTurn:!0,messageId:L,origin:"team_message",metadata:F});if(!V?.accepted)return;if(await new Hz(B,a()).markDelivered([L]),V.delivery==="next_turn")this.requestPendingResume()})().catch((V)=>{G.warn(`[AcpSession ${this.id}] Failed to deliver teammate message`,V)});this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/teamEvent":{type:W.type,...W.properties}}});return}if(W.type!=="task.status")return;this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:typeof W.properties.updatedAt==="string"?W.properties.updatedAt:new Date().toISOString(),_meta:{"blade/taskStatus":W.properties.taskStatus,...typeof W.properties.taskStatusReason==="string"?{"blade/taskStatusReason":W.properties.taskStatusReason}:{},...W.properties.taskFailure&&typeof W.properties.taskFailure==="object"?{"blade/taskFailure":W.properties.taskFailure}:{},...typeof W.properties.taskStartedAt==="string"?{"blade/taskStartedAt":W.properties.taskStartedAt}:{},...typeof W.properties.taskCompletedAt==="string"?{"blade/taskCompletedAt":W.properties.taskCompletedAt}:{},...W.properties.taskDiffStat&&typeof W.properties.taskDiffStat==="object"?{"blade/taskDiffStat":W.properties.taskDiffStat}:{},...typeof W.properties.taskQueuePosition==="number"?{"blade/taskQueuePosition":W.properties.taskQueuePosition}:{},...typeof W.properties.taskQueueDepth==="number"?{"blade/taskQueueDepth":W.properties.taskQueueDepth}:{},...typeof W.properties.taskConcurrencyLimit==="number"?{"blade/taskConcurrencyLimit":W.properties.taskConcurrencyLimit}:{},...typeof W.properties.taskInFlight==="number"?{"blade/taskInFlight":W.properties.taskInFlight}:{}}})});let H=await this.runtime.getGoal(),X=this.runtime.getPendingSteeringCount()>0,Q=H?.status==="active"||H?.status==="verifying";if(X||Q)this.requestPendingResume({defer:this.options.initialMessages!==void 0});else{let W=this.runtime.getTurnRecoveryAssessment();if(W.state!=="none")this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/turnRecovery":W}})}}async replayHistory(){for(let Z of this.messages){if(!this.canSendUpdates())return;if(!zz(Z))continue;let J=Z.role==="user"?"user_message_chunk":Z.role==="assistant"?"agent_message_chunk":void 0;if(!J)continue;for(let Y of iz(Z)){if(!this.canSendUpdates())return;if(!await this.sendUpdateAndWait({sessionUpdate:J,content:Y}))return}}let z=await this.runtime?.getGoal();if(z&&!await this.sendUpdateAndWait(this.goalSessionUpdate(z)))return;if(this.pendingResumeRequested)this.ensurePendingResumeScheduled()}sendAvailableCommandsDelayed(){if(this.destroyed||this.connection.signal.aborted)return;if(this.availableCommandsTimer!==null)clearTimeout(this.availableCommandsTimer);G.debug(`[AcpSession ${this.id}] Scheduling available commands update (500ms delay)`),this.availableCommandsTimer=setTimeout(()=>{if(this.availableCommandsTimer=null,this.destroyed||this.connection.signal.aborted)return;this.sendAvailableCommands()},500)}async handleSlashCommand(z,Z){try{G.debug(`[AcpSession ${this.id}] Executing slash command: ${z}`);let J={cwd:this.cwd,surface:"acp",workspaceRoot:this.cwd,sessionId:this.id,messages:[...this.contextMessages],rewind:{listCheckpoints:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.listRewindCheckpoints()},execute:async(Q)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let W=await this.runtime.rewindSession(Q);return this.messages=[...W.messages],this.contextMessages=await this.loadModelContextOr(W.messages),await this.agent?.destroy(),this.agent=await this.createAgent(),W}},reasoning:{get:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getReasoningConfiguration()},set:async(Q)=>{if(await this.setReasoningEffort(Q),!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getReasoningConfiguration()}},serviceTier:{get:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getServiceTierConfiguration()},set:async(Q)=>{if(await this.setServiceTier(Q),!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getServiceTierConfiguration()}},responseVerbosity:{get:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getResponseVerbosityConfiguration()},set:async(Q)=>{if(await this.setResponseVerbosity(Q),!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getResponseVerbosityConfiguration()}},communicationStyle:{get:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getCommunicationStyleConfiguration()},set:async(Q)=>{if(await this.setCommunicationStyle(Q),!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getCommunicationStyleConfiguration()}},subagents:{list:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.listSubagents()},resume:async(Q,W)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let B=!1,L,j=(V)=>{this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:V.id,status:V.status==="completed"?"completed":"failed",content:[{type:"content",content:{type:"text",text:V.result?.message||V.result?.error||`Subagent ${V.status}`}}]})},F=this.runtime.resumeSubagent({agentId:Q,prompt:W,onCompleted:(V)=>{if(B)j(V);else L=V}});if(this.sendUpdate({sessionUpdate:"tool_call",toolCallId:F.session.id,status:"in_progress",title:`Resuming ${F.session.subagentType} subagent`,content:[{type:"content",content:{type:"text",text:`Resumed from ${F.source.id} at depth ${F.session.resumeDepth}`}}],kind:this.mapToolKind("readonly")}),B=!0,L)j(L);return F}},mcp:{getCatalog:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpContentCatalog()},refresh:async(Q)=>{if(!this.runtime)throw Error("Session runtime is unavailable");await this.runtime.refreshMcpContentCatalogs(Q)},getPrompt:async(Q,W,B)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpPrompt(Q,W,B)},complete:async(Q,W,B)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.completeMcpArgument(Q,W,B)},listTasks:async(Q)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.listMcpTasks(Q)},getTask:async(Q)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpTask(Q)},cancelTask:async(Q,W)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.cancelMcpTask(Q,W)},getLogs:async(Q,W)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpLogs(Q,W)},setLoggingLevel:async(Q,W)=>{if(!this.runtime)throw Error("Session runtime is unavailable");await this.runtime.setMcpLoggingLevel(Q,W)},getInstructions:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpInstructions()}},sideConversation:{ask:async(Q,W)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.askSideQuestion(Q,{signal:W})}},codeReview:{run:async(Q,W)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let B=await T.start({sessionId:this.id,projectPath:this.cwd,runtime:this.runtime,request:Q,signal:W,onEvent:(F)=>{if(F.kind==="tool_start")this.sendUpdate({sessionUpdate:"tool_call",toolCallId:F.toolCall.id,status:"in_progress",title:`Review: ${F.toolCall.function.name}`,content:[],kind:this.mapToolKind(F.toolKind)});else if(F.kind==="tool_result")this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:F.toolCall.id,status:F.result.success?"completed":"failed",content:[]})}}),L=await B.completion,j=(await T.list(this.cwd,this.id)).find((F)=>F.start.reviewId===B.reviewId);if(!j)throw Error(`Review not found: ${B.reviewId}`);return await this.refreshPersistedMessages(),{reviewId:B.reviewId,status:L.status,findings:L.findings.length,content:n(j.start,L)}}},signal:Z,acp:{sendMessage:(Q)=>{this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:Q}})},sendToolStart:(Q,W,B)=>{let L=`tool_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,j=this.mapToolKind(B);this.sendUpdate({sessionUpdate:"tool_call",toolCallId:L,status:"in_progress",title:`${Q}`,content:[{type:"content",content:{type:"text",text:JSON.stringify(W,null,2)}}],kind:j})},sendToolResult:(Q,W)=>{if(W.summary)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:W.summary}})}}},Y=await Oz(z,J),H=Y.data?.action;if(H==="start_goal"||H==="resume_goal")this.requestPendingResume();if(H==="rewind_session"&&Array.isArray(Y.data?.messages))this.messages=[...Y.data.messages],this.contextMessages=await this.loadModelContextOr(Y.data.messages);if((Y.message==="compact_completed"||Y.message==="compact_fallback")&&Y.data?.compactedMessages){this.contextMessages=[...Y.data.compactedMessages];let Q=await U.loadSession(this.id,this.cwd);if(Q.length>0)this.messages=Q}let X=Y.content||Y.message;if(X)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:X}});if(Y.error)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[FAIL] ${Y.error}`}});return await this.flushUpdates(),{stopReason:Y.success?"end_turn":"cancelled"}}catch(J){if(Z.aborted||J instanceof Error&&J.name==="AbortError")return{stopReason:"cancelled"};return G.error(`[AcpSession ${this.id}] Slash command error:`,J),this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[FAIL] 命令执行失败: ${J instanceof Error?J.message:"未知错误"}`}}),{stopReason:"cancelled"}}}async handleSideConversationCommand(z){if(this.pendingSideConversation)throw Error("A side conversation is already running");let Z=new AbortController,J,Y=new Promise((H)=>{J=H});this.pendingSideConversation=Z,this.pendingSideConversationCompletion=Y;try{return await this.handleSlashCommand(z,Z.signal)}catch(H){if(Z.signal.aborted||H instanceof Error&&H.name==="AbortError")return{stopReason:"cancelled"};throw H}finally{if(J(),this.pendingSideConversationCompletion===Y)this.pendingSideConversationCompletion=null;if(this.pendingSideConversation===Z){if(this.pendingSideConversation=null,!this.destroyed&&this.pendingResumeRequested)this.ensurePendingResumeScheduled()}}}async sendAvailableCommands(){try{let z=qz(this.cwd,this.runtime?.getAgentResources()),Z=["model","permissions","theme","config","exit","ide"],Y=z.filter((H)=>!Z.includes(H.name)&&(H.name!=="team"||this.runtime?.getConfig().agentTeamsEnabled===!0)).map((H)=>{let X;if(H.usage){let Q=H.usage.replace(/^\/\w+\s*/,"").trim();if(Q)X=Q}if(H.aliases?.length){let Q=`Aliases: ${H.aliases.join(", ")}`;X=X?`${X} | ${Q}`:Q}return{name:H.name,description:H.description,input:X?{hint:X}:void 0}});G.info(`[AcpSession ${this.id}] Sending available commands: ${JSON.stringify(Y.map((H)=>H.name))}`),this.sendUpdate({sessionUpdate:"available_commands_update",availableCommands:Y}),G.info(`[AcpSession ${this.id}] Sent ${Y.length} available commands`)}catch(z){G.error(`[AcpSession ${this.id}] Failed to send available commands:`,z)}}async prompt(z,Z={}){if(b.setCurrentSession(this.id),!this.agent||!this.runtime)throw Error("Session not initialized");let J=this.resolvePrompt(z.prompt),Y=J.content,H=J.displayText,X=z._meta?.outputSchema??(Z.pendingInputOnly?this.runtime.getPendingSteeringMessages().find((K)=>K.outputSchema)?.outputSchema:void 0),Q;if(X!==void 0)Q=Zz(X).schema;if(H.trimStart().startsWith("!")){if(Q)throw Error("Output schemas cannot be combined with user shell commands");return this.handleUserShellCommand(H)}let W=Yz(H);if(W){if(Q)throw Error("Output schemas cannot be combined with slash commands");if(Array.isArray(Y)&&Y.some((K)=>K.type==="image_url"))throw Error("Side conversations do not accept image attachments");return this.handleSideConversationCommand(W.question?`/btw ${W.question}`:"/btw")}if(this.pendingPrompt){if(Q)throw Error("Wait for the active turn to finish before setting an output schema");if(/^\/goal(?:\s|$)/i.test(H.trim()))return this.handleSlashCommand(H,this.pendingPrompt.signal);let K=await this.runtime.enqueueSteering(Y,{allowBeforeTurn:!0});if(!K.accepted)throw Error(K.reason==="queue_full"?"Active turn steering queue is full":"Active turn is no longer steerable");if(G.debug(`[AcpSession ${this.id}] Queued steering for active turn (${K.queued})`),K.delivery==="next_turn")this.requestPendingResume();return{stopReason:"end_turn"}}let B=new AbortController,L=()=>{B.abort(Z.abortSignal?.reason)};if(Z.abortSignal?.aborted)L();else Z.abortSignal?.addEventListener("abort",L,{once:!0});let j=!1,F=!1,V=!1,m,d=new Promise((K)=>{m=K});this.pendingPrompt=B,this.pendingPromptCompletion=d;try{if(G.debug(`[AcpSession ${this.id}] Received prompt: ${H.slice(0,100)}...`),Dz(H)){if(Q)throw Error("Output schemas cannot be combined with slash commands");return await this.handleSlashCommand(H,B.signal)}let K={sessionId:this.id,userId:"acp-user",workspaceRoot:this.cwd,messages:[...this.contextMessages],signal:B.signal,permissionMode:this.mapModeToPermissionMode(),onPermissionModeChange:async($)=>{this.mode=this.mapPermissionModeToMode($),this.sendUpdate({sessionUpdate:"current_mode_update",currentModeId:this.mode})},...this.options.taskWorktree?{worktreeActive:!0}:{},confirmationHandler:{requestConfirmation:async($)=>{return this.requestPermission($)}}},O=await Qz(this.agent.chatStream(Y,K,{pendingInputOnly:Z.pendingInputOnly,goalContinuationOnly:Z.goalContinuationOnly,outputSchema:Q}),async($)=>{switch($.kind){case"content_delta":if(Q)break;if($.delta.length>0)F=!0;this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:$.delta}});break;case"thinking_delta":if($.delta.length>0)F=!0;this.sendUpdate({sessionUpdate:"agent_thought_chunk",content:{type:"text",text:$.delta}});break;case"tool_start":{V=!0;let w=$.toolCall,q=w.function.name;if(q===E)break;let N=this.mapToolKind($.toolKind),D=`Executing ${q}`;if(q==="Task"&&"function"in w)try{let R=JSON.parse(w.function.arguments),_=R.resume_from??R.resume;if(typeof _==="string")D=`Resuming ${String(R.subagent_type||"subagent")} from ${_}`}catch{}this.sendUpdate({sessionUpdate:"tool_call",toolCallId:w.id,status:"in_progress",title:D,content:[],kind:N});break}case"tool_progress":{V=!0;let w=$.toolCall;if(w.function.name===E)break;this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:w.id,status:"in_progress",content:[{type:"content",content:{type:"text",text:$.update.message}}]});break}case"tool_result":{V=!0;let w=$.toolCall;if(w.function.name===E)break;let q=$.result,N=[],D=q.metadata;if(D?.kind==="patch"&&Array.isArray(D.changes))for(let _ of D.changes){if(!_||typeof _!=="object"||!("path"in _)||typeof _.path!=="string")continue;N.push({type:"diff",path:_.path,oldText:"oldContent"in _&&typeof _.oldContent==="string"?_.oldContent:null,newText:"newContent"in _&&typeof _.newContent==="string"?_.newContent:null})}else if(D?.kind==="edit"&&typeof D.file_path==="string"&&typeof D.oldContent==="string"&&(typeof D.newContent==="string"||D.newContent===void 0))N.push({type:"diff",path:D.file_path,oldText:D.oldContent,newText:D.newContent??null});else{let _=w.function.name,mz=jz(e(Bz(_,q),t));N.push({type:"content",content:{type:"text",text:mz}})}if(w.function.name==="Task"&&(D?.verificationVerdict==="pass"||D?.verificationVerdict==="fail"||D?.verificationVerdict==="partial"))N.unshift({type:"content",content:{type:"text",text:`Verification result: ${D.verificationVerdict.toUpperCase()}`}});let R=q.success?"completed":"failed";this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:w.id,status:R,content:N});break}case"structured_output":F=!0,this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:JSON.stringify($.output)}});break;case"mcp_catalog_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP catalog r${$.revision} (${$.serverName}): +${$.added.length} -${$.removed.length} ~${$.updated.length}
|
|
3
3
|
`}});break;case"mcp_content_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP ${$.contentKind} r${$.revision} (${$.serverName}): +${$.added.length} -${$.removed.length} ~${$.updated.length}
|
|
4
4
|
`}});break;case"mcp_resource_updated":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP resource updated r${$.revision} (${$.serverName}): ${$.uri}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{Gi as S}from"./chunk-
|
|
1
|
+
import{Gi as S}from"./chunk-53aapkv1.js";import{_i as f}from"./chunk-tf7ezqew.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};
|