blade-code 0.10.169 → 0.10.170
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-g5fa6sd6.js → chunk-07e9sc9n.js} +1 -1
- package/dist/{chunk-jjjvz6v7.js → chunk-0qm48ayf.js} +1 -1
- package/dist/{chunk-zemryzk4.js → chunk-17byp73e.js} +1 -1
- package/dist/{chunk-r26t032c.js → chunk-1yqh46am.js} +1 -1
- package/dist/{chunk-bzg3srr2.js → chunk-2r44bj6y.js} +1 -1
- package/dist/{chunk-0pc47mx8.js → chunk-2yemw0fh.js} +1 -1
- package/dist/{chunk-b0y58dgr.js → chunk-4m7ewvvb.js} +1 -1
- package/dist/{chunk-x7m8kmxg.js → chunk-5ab6mc7b.js} +1 -1
- package/dist/{chunk-a6w3tc5c.js → chunk-5d3797ak.js} +2 -2
- package/dist/chunk-74phbp7d.js +1 -0
- package/dist/{chunk-hzqx7m6b.js → chunk-8cwh9mdm.js} +1 -1
- package/dist/{chunk-xpgyht2q.js → chunk-8z6dxj69.js} +1 -1
- package/dist/{chunk-v42pvdk8.js → chunk-9b1web2r.js} +1 -1
- package/dist/{chunk-q14w6rtd.js → chunk-ba39rhgf.js} +1 -1
- package/dist/{chunk-wrqzfxx5.js → chunk-dpnf1agz.js} +1 -1
- package/dist/{chunk-d720v6e4.js → chunk-g6xfgk99.js} +1 -1
- package/dist/{chunk-tkdcwqk6.js → chunk-gbqb0fsm.js} +1 -1
- package/dist/{chunk-ttrrwfab.js → chunk-hh9r5103.js} +1 -1
- package/dist/{chunk-rq4ambxc.js → chunk-kk4jv54b.js} +1 -1
- package/dist/{chunk-99ydmdy1.js → chunk-mv64vm7f.js} +1 -1
- package/dist/{chunk-aewhntwx.js → chunk-n7jw5gqx.js} +1 -1
- package/dist/{chunk-d70w1cmz.js → chunk-nm4pdxrb.js} +1 -1
- package/dist/{chunk-23ywf3pv.js → chunk-q7mnac52.js} +1 -1
- package/dist/{chunk-fq1kd635.js → chunk-qy0ggk73.js} +1 -1
- package/dist/{chunk-rc7pvr30.js → chunk-setw4w14.js} +1 -1
- package/dist/{chunk-qb80hv8n.js → chunk-sst34ye1.js} +1 -1
- package/dist/{chunk-dhtw8jzf.js → chunk-svsajyty.js} +1 -1
- package/dist/{chunk-3dv3evbn.js → chunk-tjzzps6w.js} +3 -3
- package/dist/{chunk-8mpcm1jr.js → chunk-tt4c5n1v.js} +1 -1
- package/dist/{chunk-6sy070p9.js → chunk-vpv800pg.js} +1 -1
- package/dist/{chunk-nmcv402m.js → chunk-w0bpde9y.js} +1 -1
- package/dist/{chunk-n0njjq63.js → chunk-wd9e2h6g.js} +1 -1
- package/dist/{chunk-8jej5dnz.js → chunk-wv9wrj45.js} +1 -1
- package/dist/{chunk-a1k6bqb2.js → chunk-xpg6mpsz.js} +1 -1
- package/dist/{chunk-04m1jgng.js → chunk-xyy1wbam.js} +1 -1
- package/dist/{chunk-p251twzc.js → chunk-z5a69var.js} +1 -1
- package/dist/{chunk-jkkzc1qt.js → chunk-zge9jv78.js} +1 -1
- package/dist/chunk-zkp8dxe7.js +1 -0
- package/dist/web/assets/ChatView-xL5LeO6a.js +70 -0
- package/dist/web/assets/{CodeBlockHighlighter-y0h2qpHE.js → CodeBlockHighlighter-CVUla53r.js} +1 -1
- package/dist/web/assets/{FilePreview-D3mhQ088.js → FilePreview-D3azvs19.js} +1 -1
- package/dist/web/assets/{KanbanBoard-CVg8k1mE.js → KanbanBoard-64E8Pawa.js} +1 -1
- package/dist/web/assets/{MarkdownRenderer-CNBuegIp.js → MarkdownRenderer-C0qG955Z.js} +3 -3
- package/dist/web/assets/{ScrollArea-nKClMHtv.js → ScrollArea-BZA_aDrt.js} +1 -1
- package/dist/web/assets/{SessionHistorySurface-DxS7TPaS.js → SessionHistorySurface-DQzIAPBp.js} +1 -1
- package/dist/web/assets/{SettingsModal-CUn7pWF9.js → SettingsModal-5D8rvv8X.js} +1 -1
- package/dist/web/assets/{Sidebar-CfxwNI2v.js → Sidebar-DfbcORzU.js} +1 -1
- package/dist/web/assets/{TaskSwitcher-CSoJ4y5B.js → TaskSwitcher-BE9Gj90M.js} +1 -1
- package/dist/web/assets/{TerminalPanel-BQuhnBca.js → TerminalPanel-BDsxrjAF.js} +1 -1
- package/dist/web/assets/{archive-BboAmbOv.js → archive-bhK4W3hV.js} +1 -1
- package/dist/web/assets/{arrow-left-DAUtSPbk.js → arrow-left-DvXZ2MDU.js} +1 -1
- package/dist/web/assets/{calendar-clock-Vl0t-Nd3.js → calendar-clock-Lm1ZA_v6.js} +1 -1
- package/dist/web/assets/{chevron-right-CF4tZJv_.js → chevron-right-CXhb1JXh.js} +1 -1
- package/dist/web/assets/{clock-3-UujBmwyg.js → clock-3-Bo0lqjDs.js} +1 -1
- package/dist/web/assets/{copy-DqhAOOxU.js → copy-DKXy_pO1.js} +1 -1
- package/dist/web/assets/{download-9K17cUAi.js → download-iLvgaNUA.js} +1 -1
- package/dist/web/assets/{external-link-ZWYy4pMB.js → external-link-zAQkLBr2.js} +1 -1
- package/dist/web/assets/{folder-CWkv_E0L.js → folder-VtRPgKzv.js} +1 -1
- package/dist/web/assets/{index-C6zClU0B.js → index-Dje2ptfP.js} +44 -44
- package/dist/web/assets/{message-square-plus-DOcUaurY.js → message-square-plus-zWD5cJO-.js} +1 -1
- package/dist/web/assets/{pause-CvRQWY37.js → pause-Cri04TG4.js} +1 -1
- package/dist/web/assets/{pencil-CrKIc9az.js → pencil-UrgL5bz4.js} +1 -1
- package/dist/web/assets/{play-DN4KhXKM.js → play-AcQCw4q2.js} +1 -1
- package/dist/web/assets/{plus-jGKGKGzn.js → plus-C27WGV-F.js} +1 -1
- package/dist/web/assets/{settings-DkVTw2qw.js → settings-TS0X4uR1.js} +1 -1
- package/dist/web/assets/{team-BBLJq3rO.js → team-DqKQ1qQz.js} +1 -1
- package/dist/web/assets/{teamService-B6W5r_Z_.js → teamService-D9CAIcv9.js} +1 -1
- package/dist/web/assets/{terminal-C30CbzhP.js → terminal-CqLrMzuv.js} +1 -1
- package/dist/web/index.html +1 -1
- package/package.json +1 -1
- package/dist/chunk-00t4z2ez.js +0 -1
- package/dist/chunk-gh8ngyxe.js +0 -1
- package/dist/web/assets/ChatView-er_sxPPR.js +0 -70
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Ag as d,xg as a,yg as b,zg as c}from"./chunk-
|
|
1
|
+
import{Ag as d,xg as a,yg as b,zg as c}from"./chunk-w0bpde9y.js";import"./chunk-2r44bj6y.js";import"./chunk-kv458q06.js";import"./chunk-5v0jcyea.js";import"./chunk-2f8d0km4.js";import"./chunk-ddvdc2p0.js";import"./chunk-2mk914vk.js";import"./chunk-j8hbddjp.js";import"./chunk-4cdk4mds.js";import"./chunk-07e9sc9n.js";import"./chunk-rvs364rz.js";import"./chunk-vw9paban.js";import"./chunk-4wx5sya5.js";import"./chunk-eg3ms291.js";export{c as snapshotWorkspaceModelResources,b as resolveWorkspaceModelResources,d as createProcessModelResources,a as cloneWorkspaceModelConfig};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{Ai as H,Bi as I}from"./chunk-
|
|
1
|
+
import{Ai as H,Bi as I}from"./chunk-2r44bj6y.js";import{Mutex as J}from"async-mutex";class B extends Error{limit;resource="resident_runtimes";retryable=!0;constructor(b){super("Session runtime capacity is full");this.limit=b;this.name="SessionRuntimeCapacityError"}}class D extends Error{constructor(){super("Session runtime residency is closed");this.name="SessionRuntimeResidencyClosedError"}}class A extends Error{constructor(b){super(`Session runtime residency already owns key: ${b}`);this.name="SessionRuntimeResidencyConflictError"}}class K{maxResident;idleMs;now;residents=new Map;reservations=new Map;operations=new J;nextGeneration=1;closed=!1;constructor(b){if(!H(b.maxResident))throw Error("Invalid max resident Session Runtime limit");if(!I(b.idleMs))throw Error("Invalid Session Runtime idle timeout");this.maxResident=b.maxResident,this.idleMs=b.idleMs,this.now=b.now??Date.now}acquire(b){let j=this.residents.get(b);if(!j||j.poisoned)return;return j.pins++,j.lastUsedAt=this.now(),this.createLease(j)}owns(b,j){let q=this.residents.get(b);return Boolean(q&&(j===void 0||q.value===j))}async reserve(b,j){if(!b.trim())throw Error("Session runtime residency key must not be blank");return this.operations.runExclusive(async()=>{if(this.closed)throw new D;if(this.residents.has(b)||this.reservations.has(b))throw new A(b);while(this.retainedCount()>=this.maxResident){if(!j.allowEviction)throw new B(this.maxResident);let z=this.oldestEvictableWebResident();if(!z)throw new B(this.maxResident);await this.disposeResident(z,!0)}let q={generation:this.allocateGeneration(),surface:j.surface};return this.reservations.set(b,q),this.createReservation(b,q)})}async remove(b,j){return this.operations.runExclusive(async()=>{let q=this.residents.get(b);if(!q||j!==void 0&&q.value!==j)return!1;if(q.pins>0)return!1;return await this.disposeResident(q,!0),!0})}async forget(b,j){return this.operations.runExclusive(async()=>{let q=this.residents.get(b);if(!q||j!==void 0&&q.value!==j||q.pins>0)return!1;return this.residents.delete(b),!0})}async sweepIdle(){return this.operations.runExclusive(async()=>{if(this.closed)return 0;let b=0;while(!0){let j=this.oldestIdleWebResident();if(!j)return b;await this.disposeResident(j,!0),b++}})}async disposeAll(){await this.operations.runExclusive(async()=>{this.closed=!0,this.reservations.clear();let b;for(let j of[...this.residents.values()])try{await this.disposeResident(j,!1)}catch(q){b??=q}if(this.residents.clear(),b!==void 0)throw b})}getStats(){let b=0;for(let j of this.residents.values())if(j.pins>0)b++;return{resident:this.residents.size,reserved:this.reservations.size,pinned:b,maxResident:this.maxResident}}retainedCount(){return this.residents.size+this.reservations.size}allocateGeneration(){let b=this.nextGeneration;return this.nextGeneration=this.nextGeneration===Number.MAX_SAFE_INTEGER?1:this.nextGeneration+1,b}createReservation(b,j){let q=!1;return{commit:(z)=>{if(q)throw new A(b);if(z.key!==b||z.surface!==j.surface||this.reservations.get(b)!==j||this.closed)throw this.reservations.delete(b),q=!0,this.closed?new D:new A(b);this.reservations.delete(b);let G={...z,generation:j.generation,pins:1,lastUsedAt:this.now(),poisoned:!1};return this.residents.set(b,G),q=!0,this.createLease(G)},cancel:()=>{if(q)return;if(this.reservations.get(b)===j)this.reservations.delete(b);q=!0}}}createLease(b){let j=!1;return{value:b.value,release:()=>{if(j)return;j=!0;let q=this.residents.get(b.key);if(q!==b||q.generation!==b.generation)return;q.pins=Math.max(0,q.pins-1),q.lastUsedAt=this.now()}}}oldestEvictableWebResident(){return this.sortedWebResidents().find((b)=>this.canEvict(b))}oldestIdleWebResident(){let b=this.now();return this.sortedWebResidents().find((j)=>b-j.lastUsedAt>=this.idleMs&&this.canEvict(j))}sortedWebResidents(){return[...this.residents.values()].filter((b)=>b.surface==="web").sort((b,j)=>b.lastUsedAt-j.lastUsedAt||b.generation-j.generation)}canEvict(b){if(b.pins>0||b.poisoned)return!1;try{return b.canEvict()}catch{return!1}}async disposeResident(b,j){if(this.residents.get(b.key)!==b)return;this.residents.delete(b.key);try{await b.dispose()}catch(q){if(j&&!this.closed&&!this.residents.has(b.key))b.lastUsedAt=this.now(),b.poisoned=!0,this.residents.set(b.key,b);throw q}}}
|
|
2
2
|
export{B as v,K as w};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{$g as j,Sg as a,Tg as b,Ug as c,Vg as d,Wg as e,Xg as f,Yg as g,Zg as h,_g as i,ah as k}from"./chunk-
|
|
1
|
+
import{$g as j,Sg as a,Tg as b,Ug as c,Vg as d,Wg as e,Xg as f,Yg as g,Zg as h,_g as i,ah as k}from"./chunk-sst34ye1.js";import"./chunk-3kszepm6.js";import"./chunk-wcps5gjm.js";import"./chunk-vbjgcn49.js";import"./chunk-06hkf59s.js";import"./chunk-wd9e2h6g.js";import"./chunk-3y2x6fb6.js";import"./chunk-2r44bj6y.js";import"./chunk-kv458q06.js";import"./chunk-5v0jcyea.js";import"./chunk-2f8d0km4.js";import"./chunk-ddvdc2p0.js";import"./chunk-2mk914vk.js";import"./chunk-j8hbddjp.js";import"./chunk-4cdk4mds.js";import"./chunk-07e9sc9n.js";import"./chunk-rvs364rz.js";import"./chunk-vw9paban.js";import"./chunk-4wx5sya5.js";import"./chunk-eg3ms291.js";export{g as withWorkspaceAgentResources,i as snapshotWorkspaceAgentResources,f as resolveWorkspaceAgentResources,k as resetWorkspaceAgentResources,d as refreshWorkspaceCommunicationStyles,h as getWorkspaceAgentResourceCacheStats,j as createEmptySessionAgentResources,e as configureInvocationPluginDirs,c as WorkspaceAgentResourceCapacityError,a as MAX_RESIDENT_WORKSPACE_AGENT_RESOURCES,b as MAX_ACTIVE_WORKSPACE_AGENT_RESOURCES};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{bh as j1,ch as K0,dh as F1}from"./chunk-3kszepm6.js";import{jh as w0}from"./chunk-wcps5gjm.js";import{sh as YO,th as L1}from"./chunk-vbjgcn49.js";import{wh as I1}from"./chunk-06hkf59s.js";import{xh as B0,zh as $0}from"./chunk-
|
|
1
|
+
import{bh as j1,ch as K0,dh as F1}from"./chunk-3kszepm6.js";import{jh as w0}from"./chunk-wcps5gjm.js";import{sh as YO,th as L1}from"./chunk-vbjgcn49.js";import{wh as I1}from"./chunk-06hkf59s.js";import{xh as B0,zh as $0}from"./chunk-wd9e2h6g.js";import{Mi as S0,Ni as $O,Ri as I0}from"./chunk-2r44bj6y.js";import{bj as B}from"./chunk-2f8d0km4.js";import{Dj as P,Ej as j,Fj as p,Hj as q,Kj as k1}from"./chunk-2mk914vk.js";import{Xj as k0}from"./chunk-07e9sc9n.js";import{ck as D}from"./chunk-rvs364rz.js";import{zk as t1}from"./chunk-4wx5sya5.js";import T0 from"node:path";import QO from"node:path";import C0 from"node:fs";import L0 from"node:os";import w from"node:path";import RO from"yaml";var G1=2000,W1=50,Y1=1000,O4={type:"object",properties:{verdict:{type:"string",enum:["pass","fail","partial"]},summary:{type:"string",minLength:1,maxLength:G1},findings:{type:"array",maxItems:W1,items:{type:"string",minLength:1,maxLength:Y1}}},required:["verdict","summary","findings"],additionalProperties:!1};function q1(O,$){let Q=O.trim().replaceAll(/\s+/g," ");if($)Q=Q.replaceAll($,".");return Q.replace(/\bBearer\s+[^\s"'`]+/gi,"Bearer [redacted]").replace(/\bsk-[A-Za-z0-9_-]{8,}\b/g,"[redacted-key]").replace(/\b(api(?:[_-]?|\s+)key|access(?:[_-]?|\s+)token|authorization|cookie|password|passwd|refresh(?:[_-]?|\s+)token|secret|session(?:[_-]?|\s+)token)\b(\s*[:=]\s*)([^\s,;]+)/gi,"$1$2[redacted]")}function NO(O){if(O.length<=w0)return O;let $=" [verification feedback truncated]",Q=O.slice(0,w0-$.length);if(/[\uD800-\uDBFF]$/.test(Q))Q=Q.slice(0,-1);return Q.trimEnd()+$}function X1(O){if(!O||typeof O!=="object"||Array.isArray(O))return;let $=O;if($.verdict!=="pass"&&$.verdict!=="fail"&&$.verdict!=="partial"||typeof $.summary!=="string"||!$.summary.trim()||$.summary.length>G1||!Array.isArray($.findings)||$.findings.length>W1||!$.findings.every((Q)=>typeof Q==="string"&&Q.trim().length>0&&Q.length<=Y1))return;return{verdict:$.verdict,summary:$.summary.trim(),findings:$.findings.map((Q)=>Q.trim())}}function $4(O,$){let Q=X1(O);if(!Q)return;let Z=q1(Q.summary,$),J=Q.findings.map((L)=>q1(L,$));return NO([Z,J.length>0?`Findings:
|
|
2
2
|
${J.map((L)=>`- ${L}`).join(`
|
|
3
3
|
`)}`:""].filter(Boolean).join(`
|
|
4
4
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{tf as a,uf as b,vf as c}from"./chunk-
|
|
1
|
+
import{tf as a,uf as b,vf as c}from"./chunk-vpv800pg.js";import"./chunk-nheny8xp.js";import"./chunk-4m7ewvvb.js";import"./chunk-v508x7cg.js";import"./chunk-t0gm0pn1.js";import"./chunk-06hkf59s.js";import"./chunk-2r44bj6y.js";import"./chunk-kv458q06.js";import"./chunk-5v0jcyea.js";import"./chunk-2f8d0km4.js";import"./chunk-ddvdc2p0.js";import"./chunk-2mk914vk.js";import"./chunk-j8hbddjp.js";import"./chunk-4cdk4mds.js";import"./chunk-07e9sc9n.js";import"./chunk-rvs364rz.js";import"./chunk-vw9paban.js";import"./chunk-4wx5sya5.js";import"./chunk-eg3ms291.js";export{a as validatePermissions,c as validateOutput,b as loadConfiguration};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{Ga as z3}from"./chunk-g01mth5d.js";import{Ja as T,Ka as $$,Pa as Vz,Qa as RY,Ra as e0}from"./chunk-
|
|
1
|
+
import{Ga as z3}from"./chunk-g01mth5d.js";import{Ja as T,Ka as $$,Pa as Vz,Qa as RY,Ra as e0}from"./chunk-tt4c5n1v.js";import{$a as HX,Sa as Y5,Va as pZ,Za as tZ,_a as UX,bb as rz,db as nz,eb as A9,wb as az}from"./chunk-30x3mcsb.js";import{Ab as c7,Bb as D2,Cb as BY,Db as x1,Eb as a7,Fb as KY,Gb as $Y,Hb as DY,Ib as qY,Jb as WQ,Lb as JX,Nb as W0,Pb as _2,Sb as p4,Ub as _Z,Vb as l4,Wb as i4,Yb as AJ,Zb as R$,dc as aX,ec as G8,fc as sX,gc as ZX,ic as u1,jc as SX,oc as iY,rc as rY,xb as s5,yb as h7,zb as J1}from"./chunk-xyy1wbam.js";import{$c as r8,$d as lY,Ac as k3,Bc as T1,Cc as ZJ,Dc as _0,Ec as S2,Fc as N1,Gc as S6,Hc as f9,Ic as m4,Jc as c4,Kc as JY,Lc as YY,Mc as CX,Nc as X3,Nd as W8,Oc as A1,Pc as Y3,Pd as f0,Qc as i8,Qd as b$,Rc as $1,Sc as Z1,Tc as l2,Uc as p2,Vc as i2,Wc as g6,Xc as u6,Xd as Jz,Yc as d2,Yd as VX,Zc as H3,_c as m2,ad as M1,bd as e1,cd as c2,dd as $2,ed as Z2,ee as fX,fd as d6,fe as PX,gd as J2,hd as m6,he as s,id as c6,jd as k$,kd as p6,ld as O3,md as r2,nd as l6,od as i6,pd as r6,qd as n6,rd as N3,sd as b3,ud as j3,xc as v$,yc as MX,zc as r3}from"./chunk-mv64vm7f.js";import{ie as l,je as BQ,ke as GQ,le as IJ,ne as F2}from"./chunk-53fc0yrq.js";import{Ge as P9,He as J$,Ie as q2,Je as $9,Ke as TX,Le as RX,Ue as ez,ff as $W,pe as oz,se as tz}from"./chunk-y5wngtz0.js";import{Bf as NJ,Cf as LJ}from"./chunk-jj4ggb04.js";import{Of as r4,Pf as q0,Qf as d,Tf as j0,Uf as P4,Vf as L2,Wf as G1,Xf as CZ,Yf as R1,Zf as cY,cg as B2}from"./chunk-4m7ewvvb.js";import{dg as d1}from"./chunk-t0gm0pn1.js";import{hg as jZ,ig as pY,ng as dY,og as mX,pg as S4}from"./chunk-1yq72zb7.js";import{qg as nZ}from"./chunk-kqvzmnja.js";import{tg as m0,ug as O1}from"./chunk-0mr8nexh.js";import{vg as tX}from"./chunk-50vwafn5.js";import{Ag as bX,xg as LX,yg as OX,zg as NX}from"./chunk-w0bpde9y.js";import{$g as AX,Bg as I4,Cg as h4,Dg as g4,Fg as u4,Gg as d4,Hg as _1,Ig as FQ,Jg as I$,Kg as j$,Lg as G$,Mg as $5,Ng as W2,Og as H8,Pg as l1,Qg as i1,Rg as EX,Vg as J9,Xg as c0,Yg as f$,_g as k4,ah as kX}from"./chunk-sst34ye1.js";import{ch as D1,eh as T$,fh as O4}from"./chunk-3kszepm6.js";import{gh as d3,hh as z2,ih as m3,jh as s2,kh as c3,lh as p3,mh as Z4,nh as $4,oh as l3,ph as i3,qh as e6}from"./chunk-wcps5gjm.js";import{rh as _z,th as jX,uh as z8,vh as bJ}from"./chunk-vbjgcn49.js";import{xh as L9,zh as x0}from"./chunk-wd9e2h6g.js";import{Ah as E6,Bh as R9,Ch as A6,Dh as r1}from"./chunk-3y2x6fb6.js";import{Ci as PY,Di as SY,Ei as kY,Fh as XJ,Fi as vY,Gi as AZ,Hi as yY,Ii as B1,Ji as xY,Kh as zJ,Ki as IY,Li as hY,Mh as D9,Ni as t3,Pi as yX,Qi as _X,Rh as Wz,Ri as B0,Vh as WJ,Xh as qX,Zh as UY,_h as HY,pi as h1,si as e7}from"./chunk-2r44bj6y.js";import{Ui as L$}from"./chunk-kv458q06.js";import{Wi as eQ,Yi as $X}from"./chunk-5v0jcyea.js";import{$i as X4,bj as C}from"./chunk-2f8d0km4.js";import{Dj as e,Fj as a6,Gj as X2,Hj as K,Ij as R3,Jj as P,Kj as u}from"./chunk-2mk914vk.js";import{Oj as wX,Pj as FX}from"./chunk-j8hbddjp.js";import{Qj as Oz,Tj as wz}from"./chunk-4cdk4mds.js";import{Xj as Ez}from"./chunk-07e9sc9n.js";import{bk as vX,ck as a0}from"./chunk-rvs364rz.js";import{Bk as E$,Gk as u3,fk as t,gk as N$,hk as D$,ik as t1,jk as o9,kk as u2,lk as X$,mk as t7,pk as I6,yk as P6}from"./chunk-4wx5sya5.js";import{Mk as Y$}from"./chunk-eg3ms291.js";import{randomUUID as M8}from"crypto";import{randomUUID as _W}from"node:crypto";var KW=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);
|
|
@@ -859,7 +859,7 @@ ${A0}
|
|
|
859
859
|
</approved-plan>
|
|
860
860
|
|
|
861
861
|
IMPORTANT: Execute according to the approved plan above. Follow the steps exactly as specified.`;if(typeof O==="string")S$=O+j6;else S$=[...O,{type:"text",text:j6}]}v=yield*this.runLoop(S$,b,{...x,inputMessageId:void 0})}if(!this.sessionRuntime||!I)return v;let p=await this.sessionRuntime.recordGoalProgress({tokens:v.metadata?.tokensUsed??0,elapsedMs:v.metadata?.duration??0,...k?{goalId:k.goalId,objective:k.objective,turnId:I.id}:{},executionHostFailureCategory:v.metadata?.executionHostFailureCategory,prematureStopPattern:v.success?VY(v.finalMessage):void 0});if(p)yield{kind:"goal_updated",goal:p};if(!v.success||b.signal?.aborted){if(p=await this.sessionRuntime.pauseActiveGoal(b.signal?.aborted?"goal paused after user cancellation":v.error?.message??"goal paused after turn failure"),p)yield{kind:"goal_updated",goal:p}}if(v.success&&!b.signal?.aborted&&h<20)await this.sessionRuntime.waitForBackgroundSubagentFollowUp(I,b.signal);let n=v.success&&!b.signal?.aborted&&h<20,p0=XG(v)||!v.success&&v.error?.type==="max_turns_exceeded";if(R=await this.sessionRuntime.finishTurn(I,{continuePending:n,...p0?{acknowledgeInput:!0}:{},outcome:v.success&&!b.signal?.aborted?{status:"completed",turnsCount:v.metadata?.turnsCount??0,toolCallsCount:v.metadata?.toolCallsCount??0,durationMs:v.metadata?.duration??0}:{status:"aborted",cause:b.signal?.aborted?"cancelled":"failed",turnsCount:v.metadata?.turnsCount??0,toolCallsCount:v.metadata?.toolCallsCount??0,durationMs:v.metadata?.duration??0}}),R){h++,N=!0,M=!1,j=null,O="",o=void 0,A="",S=void 0,E=Z0(),yield{kind:"follow_up_started",queued:this.sessionRuntime.getPendingSteeringCount(),recovered:this.sessionRuntime.getRecoveredSteeringCount(),messages:$0(),queue:await this.sessionRuntime.getFollowUpQueueSnapshot()};continue}if(yield{kind:"follow_up_queue_changed",queue:await this.sessionRuntime.getFollowUpQueueSnapshot()},!v.success||b.signal?.aborted)return v;if(p=await this.sessionRuntime.getGoal(),!p||p.status!=="active"&&p.status!=="verifying")return v;let J0=await this.sessionRuntime.prepareGoalContinuation(p);if(!J0.ok){if(J0.goal)yield{kind:"goal_updated",goal:J0.goal};return{success:!1,error:{type:"goal_frontier_unavailable",message:J0.error.message},metadata:{turnsCount:v.metadata?.turnsCount??0,toolCallsCount:v.metadata?.toolCallsCount??0,duration:v.metadata?.duration??0}}}let h0=await this.sessionRuntime.beginGoalTurn(J0.goal);if(!h0)return v;j=h0.goal,q={...J0,goal:h0.goal},R=h0.handle,N=!1,M=!0,O=S5(j),o=void 0,E=void 0,yield{kind:"goal_frontier_updated",goal:j,frontier:J0.frontier,tasks:J0.tasks},yield{kind:"goal_continuation_started",goal:j,continuation:j.continuationCount,...j.prematureStop?{prematureStopPattern:j.prematureStop.pattern,prematureStopCount:j.prematureStop.consecutiveCount}:{}},yield{kind:"goal_updated",goal:j}}}finally{if(this.sessionRuntime&&R)await this.sessionRuntime.finishTurn(R)}}let _=typeof H==="string"?H:H.filter((O)=>O.type==="text").map((O)=>O.text).join(`
|
|
862
|
-
`),L={id:this.generateTaskId(),type:"simple",prompt:_};return{success:!0,finalMessage:(await this.executeTask(L)).content,metadata:{turnsCount:1,toolCallsCount:0,duration:0}}}async chat($,Z,J){let{drainLoop:Y}=await import("./chunk-d70w1cmz.js");return Y(this.chatStream($,Z,J))}async*runPlanLoop($,Z,J){a.debug("Processing Plan mode message...");let{prompt:Y}=await Y1({...Z.workspaceKind==="acp-remote"?{workspaceAccess:"none"}:{projectPath:Z.workspaceRoot||C()},mode:"plan",includeEnvironment:!0,environmentOptions:{...u1,workingDirectory:Z.executionRoot??Z.workspaceRoot??C()},language:this.config.language,availableSkills:this.agentResources?.skills.generateAvailableSkillsList(),communicationStyle:this.sessionRuntime?.getCommunicationStyleConfiguration().selection,communicationStyleCatalog:this.sessionRuntime?.getCommunicationStyleCatalog(),projectRuleCatalog:this.sessionRuntime?.getProjectRuleCatalog(),...Z.workspaceKind==="acp-remote"?{}:{projectInstructionSourcePath:this.sessionRuntime?.projectRoot}}),Q;if(typeof $==="string")Q=t2($);else{let X=$.filter((z)=>z.type==="text");if(X.length>0){let z=X[0];Q=$.map((W)=>W===z?{type:"text",text:t2(z.text)}:W)}else Q=[{type:"text",text:t2("")},...$]}return yield*this.executeLoop(Q,Z,J,Y)}async*runLoop($,Z,J){a.debug("Processing enhanced chat message...");let Y=Z.systemPrompt??await this.buildSystemPromptOnDemand(Z);return yield*this.executeLoop($,Z,J,Y)}async buildSystemPromptOnDemand($){let Z=this.runtimeOptions.systemPrompt,J=this.runtimeOptions.appendSystemPrompt;return(await Y1({...$.workspaceKind==="acp-remote"?{workspaceAccess:"none"}:{projectPath:$.workspaceRoot||C()},replaceDefault:Z,append:J,includeEnvironment:!0,environmentOptions:{...u1,workingDirectory:$.executionRoot??$.workspaceRoot??C()},language:this.config.language,availableSkills:this.agentResources?.skills.generateAvailableSkillsList(),communicationStyle:this.sessionRuntime?.getCommunicationStyleConfiguration().selection,communicationStyleCatalog:this.sessionRuntime?.getCommunicationStyleCatalog(),projectRuleCatalog:this.sessionRuntime?.getProjectRuleCatalog(),...$.workspaceKind==="acp-remote"?{}:{projectInstructionSourcePath:this.sessionRuntime?.projectRoot}})).prompt}executeLoop($,Z,J,Y){if(!this.isInitialized)throw Error("Agent未初始化");let Q=this.buildLoopDependencies();return rY(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,X=J.error===void 0,z=J.output,W={success:X,llmContent:typeof z==="string"||z!==null&&typeof z==="object"?z:z===null?J.error?`Subagent execution failed: ${J.error}.`:"":String(z),...J.error?{error:{type:"execution_error",message:J.error}}:{},...Q?{metadata:Q}:{}},V=[{kind:"tool_result",toolCall:Y,result:W}],U=iY(Y,W);if(U)V.push(U);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=$,a.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);a.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);a.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){a.debug(`[MainAgent] ${$}`,Z||"")}error($,Z){a.error(`[MainAgent] ${$}`,Z||"")}async initializeSystemPrompt(){try{let $=this.runtimeOptions.systemPrompt,Z=this.runtimeOptions.appendSystemPrompt,J=await Y1({...this.sessionRuntime?.isRemoteWorkspace()?{workspaceAccess:"none"}:{projectPath:this.sessionRuntime?.workspaceRoot??C()},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(),...this.sessionRuntime?.isRemoteWorkspace()?{}:{projectInstructionSourcePath:this.sessionRuntime?.projectRoot},...this.sessionRuntime?{environmentOptions:{...u1,workingDirectory:this.sessionRuntime.executionRoot}}:{}});if(J.prompt)this.log("系统提示配置验证成功"),a.debug(`[SystemPrompt] 可用来源: ${J.sources.filter((Y)=>Y.loaded).map((Y)=>Y.name).join(", ")}`)}catch($){this.error("系统提示配置验证失败",$)}}async registerBuiltinTools(){try{let $=await v4({sessionId:"default",configDir:t(),workspaceRoot:C(),resourceRoot:C(),agentResources:this.agentResources});a.debug(`Registering ${$.length} builtin tools...`),this.toolExecutor.getRegistry().registerAll($);let Z=this.toolExecutor.getRegistry().getAll().length;a.debug(`Builtin tools registered: ${Z} tools`),a.debug(`[Tools] ${this.toolExecutor.getRegistry().getAll().map((J)=>J.name).join(", ")}`),await this.registerMcpTools()}catch($){throw a.error("Failed to register builtin tools:",$),$}}async registerMcpTools(){try{let $=await z4({workspaceRoot:C(),storeServers:this.config.mcpServers??{},cliConfigs:this.runtimeOptions.mcpConfig,strictCliConfig:this.runtimeOptions.strictMcpConfig});if(Object.keys($).length===0){a.debug("No MCP servers configured");return}let Z=e0.createIsolated({artifactWriter:new o2(`legacy-${QG()}`)});this.legacyMcpRegistry=Z;for(let[X,z]of Object.entries($))try{a.debug(`Connecting to MCP server: ${X}`),await Z.registerServer(X,z),a.debug(`MCP server "${X}" connected`)}catch(W){a.warn(`Warning: MCP server "${X}" connection failed:`,W)}let J=this.toolExecutor.getRegistry();J.setMcpCatalogBarrier(()=>Z.waitForCatalogIdle());let Y=Z.getCatalogSnapshot();J.replaceMcpTools(Y.tools),J.registerAll(Y6(Z));let Q=Z.getInstructionsSnapshot();if(J.queueMcpInstructionsChange({revision:Q.revision,reason:"snapshot",replace:!0,instructions:Q.instructions,removed:[]}),Z.on("catalogChanged",(X)=>{J.replaceMcpTools(X.tools,X)}),Z.on("contentCatalogChanged",(X)=>{J.queueMcpContentChange(X)}),Z.on("resourceUpdated",(X)=>{J.queueMcpResourceUpdated(X)}),Z.on("connectionLifecycleChanged",(X)=>{J.queueMcpConnectionChange(X)}),Z.on("log",(X)=>{J.queueMcpLog(X)}),Z.on("instructionsChanged",(X)=>{J.queueMcpInstructionsChange({revision:X.revision,reason:X.reason,replace:!1,instructions:X.action==="added"&&X.instruction?[{serverName:X.serverName,...X.instruction}]:[],removed:X.action==="removed"?[X.serverName]:[]})}),Y.tools.length>0)a.debug(`Registered ${Y.tools.length} MCP tools`),a.debug(`[MCP Tools] ${Y.tools.map((X)=>X.name).join(", ")}`)}catch($){a.warn("Failed to register MCP tools:",$)}}async loadSubagents(){let $=await c0(C());if(this.agentResources=k4($),this.subagentRegistry=this.agentResources.subagents,this.runtimeOptions.agents?.length)this.subagentRegistry.applyOverrides(this.runtimeOptions.agents);let Z=this.subagentRegistry.getAllNames().length;if(Z>0)a.debug(`Loaded ${Z} subagents: ${this.subagentRegistry.getAllNames().join(", ")}`);else a.debug("No subagents configured")}applySkillToolRestrictions($){if(!this.activeSkillContext?.allowedTools)return $;let Z=this.activeSkillContext.allowedTools;a.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 X=Q.match(/^(\w+)\(.*\)$/);if(X&&X[1]===Y.name)return!0;return!1})});return a.debug(`Filtered tools: ${J.map((Y)=>Y.name).join(", ")} (${J.length}/${$.length})`),J}clearSkillContext(){if(this.activeSkillContext)a.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(`
|
|
862
|
+
`),L={id:this.generateTaskId(),type:"simple",prompt:_};return{success:!0,finalMessage:(await this.executeTask(L)).content,metadata:{turnsCount:1,toolCallsCount:0,duration:0}}}async chat($,Z,J){let{drainLoop:Y}=await import("./chunk-nm4pdxrb.js");return Y(this.chatStream($,Z,J))}async*runPlanLoop($,Z,J){a.debug("Processing Plan mode message...");let{prompt:Y}=await Y1({...Z.workspaceKind==="acp-remote"?{workspaceAccess:"none"}:{projectPath:Z.workspaceRoot||C()},mode:"plan",includeEnvironment:!0,environmentOptions:{...u1,workingDirectory:Z.executionRoot??Z.workspaceRoot??C()},language:this.config.language,availableSkills:this.agentResources?.skills.generateAvailableSkillsList(),communicationStyle:this.sessionRuntime?.getCommunicationStyleConfiguration().selection,communicationStyleCatalog:this.sessionRuntime?.getCommunicationStyleCatalog(),projectRuleCatalog:this.sessionRuntime?.getProjectRuleCatalog(),...Z.workspaceKind==="acp-remote"?{}:{projectInstructionSourcePath:this.sessionRuntime?.projectRoot}}),Q;if(typeof $==="string")Q=t2($);else{let X=$.filter((z)=>z.type==="text");if(X.length>0){let z=X[0];Q=$.map((W)=>W===z?{type:"text",text:t2(z.text)}:W)}else Q=[{type:"text",text:t2("")},...$]}return yield*this.executeLoop(Q,Z,J,Y)}async*runLoop($,Z,J){a.debug("Processing enhanced chat message...");let Y=Z.systemPrompt??await this.buildSystemPromptOnDemand(Z);return yield*this.executeLoop($,Z,J,Y)}async buildSystemPromptOnDemand($){let Z=this.runtimeOptions.systemPrompt,J=this.runtimeOptions.appendSystemPrompt;return(await Y1({...$.workspaceKind==="acp-remote"?{workspaceAccess:"none"}:{projectPath:$.workspaceRoot||C()},replaceDefault:Z,append:J,includeEnvironment:!0,environmentOptions:{...u1,workingDirectory:$.executionRoot??$.workspaceRoot??C()},language:this.config.language,availableSkills:this.agentResources?.skills.generateAvailableSkillsList(),communicationStyle:this.sessionRuntime?.getCommunicationStyleConfiguration().selection,communicationStyleCatalog:this.sessionRuntime?.getCommunicationStyleCatalog(),projectRuleCatalog:this.sessionRuntime?.getProjectRuleCatalog(),...$.workspaceKind==="acp-remote"?{}:{projectInstructionSourcePath:this.sessionRuntime?.projectRoot}})).prompt}executeLoop($,Z,J,Y){if(!this.isInitialized)throw Error("Agent未初始化");let Q=this.buildLoopDependencies();return rY(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,X=J.error===void 0,z=J.output,W={success:X,llmContent:typeof z==="string"||z!==null&&typeof z==="object"?z:z===null?J.error?`Subagent execution failed: ${J.error}.`:"":String(z),...J.error?{error:{type:"execution_error",message:J.error}}:{},...Q?{metadata:Q}:{}},V=[{kind:"tool_result",toolCall:Y,result:W}],U=iY(Y,W);if(U)V.push(U);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=$,a.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);a.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);a.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){a.debug(`[MainAgent] ${$}`,Z||"")}error($,Z){a.error(`[MainAgent] ${$}`,Z||"")}async initializeSystemPrompt(){try{let $=this.runtimeOptions.systemPrompt,Z=this.runtimeOptions.appendSystemPrompt,J=await Y1({...this.sessionRuntime?.isRemoteWorkspace()?{workspaceAccess:"none"}:{projectPath:this.sessionRuntime?.workspaceRoot??C()},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(),...this.sessionRuntime?.isRemoteWorkspace()?{}:{projectInstructionSourcePath:this.sessionRuntime?.projectRoot},...this.sessionRuntime?{environmentOptions:{...u1,workingDirectory:this.sessionRuntime.executionRoot}}:{}});if(J.prompt)this.log("系统提示配置验证成功"),a.debug(`[SystemPrompt] 可用来源: ${J.sources.filter((Y)=>Y.loaded).map((Y)=>Y.name).join(", ")}`)}catch($){this.error("系统提示配置验证失败",$)}}async registerBuiltinTools(){try{let $=await v4({sessionId:"default",configDir:t(),workspaceRoot:C(),resourceRoot:C(),agentResources:this.agentResources});a.debug(`Registering ${$.length} builtin tools...`),this.toolExecutor.getRegistry().registerAll($);let Z=this.toolExecutor.getRegistry().getAll().length;a.debug(`Builtin tools registered: ${Z} tools`),a.debug(`[Tools] ${this.toolExecutor.getRegistry().getAll().map((J)=>J.name).join(", ")}`),await this.registerMcpTools()}catch($){throw a.error("Failed to register builtin tools:",$),$}}async registerMcpTools(){try{let $=await z4({workspaceRoot:C(),storeServers:this.config.mcpServers??{},cliConfigs:this.runtimeOptions.mcpConfig,strictCliConfig:this.runtimeOptions.strictMcpConfig});if(Object.keys($).length===0){a.debug("No MCP servers configured");return}let Z=e0.createIsolated({artifactWriter:new o2(`legacy-${QG()}`)});this.legacyMcpRegistry=Z;for(let[X,z]of Object.entries($))try{a.debug(`Connecting to MCP server: ${X}`),await Z.registerServer(X,z),a.debug(`MCP server "${X}" connected`)}catch(W){a.warn(`Warning: MCP server "${X}" connection failed:`,W)}let J=this.toolExecutor.getRegistry();J.setMcpCatalogBarrier(()=>Z.waitForCatalogIdle());let Y=Z.getCatalogSnapshot();J.replaceMcpTools(Y.tools),J.registerAll(Y6(Z));let Q=Z.getInstructionsSnapshot();if(J.queueMcpInstructionsChange({revision:Q.revision,reason:"snapshot",replace:!0,instructions:Q.instructions,removed:[]}),Z.on("catalogChanged",(X)=>{J.replaceMcpTools(X.tools,X)}),Z.on("contentCatalogChanged",(X)=>{J.queueMcpContentChange(X)}),Z.on("resourceUpdated",(X)=>{J.queueMcpResourceUpdated(X)}),Z.on("connectionLifecycleChanged",(X)=>{J.queueMcpConnectionChange(X)}),Z.on("log",(X)=>{J.queueMcpLog(X)}),Z.on("instructionsChanged",(X)=>{J.queueMcpInstructionsChange({revision:X.revision,reason:X.reason,replace:!1,instructions:X.action==="added"&&X.instruction?[{serverName:X.serverName,...X.instruction}]:[],removed:X.action==="removed"?[X.serverName]:[]})}),Y.tools.length>0)a.debug(`Registered ${Y.tools.length} MCP tools`),a.debug(`[MCP Tools] ${Y.tools.map((X)=>X.name).join(", ")}`)}catch($){a.warn("Failed to register MCP tools:",$)}}async loadSubagents(){let $=await c0(C());if(this.agentResources=k4($),this.subagentRegistry=this.agentResources.subagents,this.runtimeOptions.agents?.length)this.subagentRegistry.applyOverrides(this.runtimeOptions.agents);let Z=this.subagentRegistry.getAllNames().length;if(Z>0)a.debug(`Loaded ${Z} subagents: ${this.subagentRegistry.getAllNames().join(", ")}`);else a.debug("No subagents configured")}applySkillToolRestrictions($){if(!this.activeSkillContext?.allowedTools)return $;let Z=this.activeSkillContext.allowedTools;a.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 X=Q.match(/^(\w+)\(.*\)$/);if(X&&X[1]===Y.name)return!0;return!1})});return a.debug(`Filtered tools: ${J.map((Y)=>Y.name).join(", ")} (${J.length}/${$.length})`),J}clearSkillContext(){if(this.activeSkillContext)a.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(`
|
|
863
863
|
`);try{let Y=await this.attachmentCollector.collect(J);if(Y.length===0)return $;a.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 a.error("Failed to process @ mentions in multimodal message:",Y),$}}buildAttachmentText($){let Z=[],J=[];for(let Q of $)if(Q.type==="file"){let X=Q.metadata?.lineRange?` (lines ${Q.metadata.lineRange.start}${Q.metadata.lineRange.end?`-${Q.metadata.lineRange.end}`:""})`:"";Z.push(`<file path="${Q.path}"${X?` range="${X}"`:""}>`,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+=`
|
|
864
864
|
|
|
865
865
|
<system-reminder>
|
|
@@ -1675,7 +1675,7 @@ ${J}
|
|
|
1675
1675
|
`)),{success:!0,message:"Schedules listed",content:V.join(`
|
|
1676
1676
|
`)}}case"create":{let W=aw(X);if("error"in W)return Y.sendMessage(`创建失败:${W.error}`),{success:!1,error:W.error};let V={prompt:W.prompt,projectPath:z,trigger:W.trigger,isolation:"worktree",permissionMode:"default",enabled:!0};try{let U=await $.create(V),H=U.nextRunAt?new Date(U.nextRunAt).toLocaleString():"(无)";return Y.sendMessage(`[OK] 已创建定时任务 \`${U.id}\`
|
|
1677
1677
|
${A9(U.trigger)} · 下次运行: ${H}`),{success:!0,message:`Schedule ${U.id} created`}}catch(U){let H=U instanceof Error?U.message:String(U);return Y.sendMessage(`创建失败:${H}`),{success:!1,error:H}}}case"remove":case"rm":{let W=X[0];if(!W)return Y.sendMessage("用法:/schedule remove <id>"),{success:!1,error:"Missing schedule id"};let V=await $.remove(W);return Y.sendMessage(V?`[OK] 已删除 \`${W}\``:`未找到 \`${W}\``),{success:V,message:V?"Removed":"Not found"}}case"enable":case"disable":{let W=X[0];if(!W)return Y.sendMessage(`用法:/schedule ${Q} <id>`),{success:!1,error:"Missing schedule id"};let V=await $.setEnabled(W,Q==="enable");return Y.sendMessage(V?`[OK] 已${Q==="enable"?"启用":"停用"} \`${W}\``:`未找到 \`${W}\``),{success:Boolean(V),message:V?"Updated":"Not found"}}case"run":{let W=X[0];if(!W)return Y.sendMessage("用法:/schedule run <id>"),{success:!1,error:"Missing schedule id"};try{return await sw(W),Y.sendMessage(`[OK] 已触发 \`${W}\``),{success:!0,message:"Schedule triggered"}}catch(V){let U=V instanceof Error?V.message:String(V);return Y.sendMessage(`运行失败:${U}`),{success:!1,error:U}}}default:return Y.sendMessage(`未知子命令: ${Q}
|
|
1678
|
-
使用 /schedule 查看帮助`),{success:!1,error:`Unknown subcommand: ${Q}`}}}}}var sz=ow();import*as f2 from"node:fs/promises";import*as P2 from"node:path";async function ZW($,Z={}){let{maxResults:J=20,caseSensitive:Y=!1,projectPath:Q,storagePath:X}=Z,z=X??P6(Q??C());if(!X){let G=await tw($,Q??C(),J,Y);if(G)return G}let W;try{W=(await f2.readdir(z)).filter((D)=>D.endsWith(".jsonl")&&!D.startsWith("agent_")).map((D)=>P2.join(z,D))}catch{return[]}let U=(await Promise.all(W.map(async(G)=>{try{let D=await f2.stat(G);return{path:G,mtime:D.mtimeMs}}catch{return null}}))).filter((G)=>G!==null).sort((G,D)=>D.mtime-G.mtime).map((G)=>G.path),H=[],B=Y?$:$.toLowerCase();for(let G of U){if(H.length>=J)break;let D=P2.basename(G,".jsonl"),w=await ew(G,B,Y,D);if(H.push(...w),H.length>=J){H.length=J;break}}return H}async function tw($,Z,J,Y){try{let{syncAll:Q}=await import("./chunk-d420fs8m.js"),X=await ez();if(!X)return null;let{SessionService:z}=await import("./chunk-
|
|
1678
|
+
使用 /schedule 查看帮助`),{success:!1,error:`Unknown subcommand: ${Q}`}}}}}var sz=ow();import*as f2 from"node:fs/promises";import*as P2 from"node:path";async function ZW($,Z={}){let{maxResults:J=20,caseSensitive:Y=!1,projectPath:Q,storagePath:X}=Z,z=X??P6(Q??C());if(!X){let G=await tw($,Q??C(),J,Y);if(G)return G}let W;try{W=(await f2.readdir(z)).filter((D)=>D.endsWith(".jsonl")&&!D.startsWith("agent_")).map((D)=>P2.join(z,D))}catch{return[]}let U=(await Promise.all(W.map(async(G)=>{try{let D=await f2.stat(G);return{path:G,mtime:D.mtimeMs}}catch{return null}}))).filter((G)=>G!==null).sort((G,D)=>D.mtime-G.mtime).map((G)=>G.path),H=[],B=Y?$:$.toLowerCase();for(let G of U){if(H.length>=J)break;let D=P2.basename(G,".jsonl"),w=await ew(G,B,Y,D);if(H.push(...w),H.length>=J){H.length=J;break}}return H}async function tw($,Z,J,Y){try{let{syncAll:Q}=await import("./chunk-d420fs8m.js"),X=await ez();if(!X)return null;let{SessionService:z}=await import("./chunk-5ab6mc7b.js");await Q(X,z.projectionDeriverForSearch());let W=P2.resolve(Z),V=$W(X,$,W,J*4),U=Y?$:$.toLowerCase(),H=[];for(let B of V){if(B.role!=="user"&&B.role!=="assistant")continue;let G=M9(B.text,U,Y,B.session_id,B.role,B.timestamp??void 0,0);if(G)H.push(G);if(H.length>=J)break}return H}catch{return null}}async function ew($,Z,J,Y){try{let Q=await f2.readFile($,"utf8"),z=Q.split(`
|
|
1679
1679
|
`).flatMap((B,G)=>{if(!B.trim())return[];try{return[{event:JSON.parse(B),index:G}]}catch{return[]}});if(!z.some(({event:B})=>B.type==="session_created"))return $F(z,Z,J,Y);let V=new Map(z.flatMap(({event:B,index:G})=>typeof B.id==="string"?[[B.id,G+1]]:[])),U=oz(tz(Q,$)),H=new Map;for(let B of U){if(B.type==="message_created"&&(B.data.role==="user"||B.data.role==="assistant"))H.set(B.data.messageId,{role:B.data.role,content:[],timestamp:B.timestamp,lineNumber:V.get(B.id)??0});if(B.type==="part_created"&&B.data.partType==="text"){let G=H.get(B.data.messageId),D=B.data.payload.text;if(G&&typeof D==="string")G.content.push(D)}}return[...H.values()].flatMap((B)=>{let G=M9(B.content.join(" "),Z,J,Y,B.role,B.timestamp,B.lineNumber);return G?[G]:[]})}catch{return[]}}function $F($,Z,J,Y){return $.flatMap(({event:Q,index:X})=>{if(Q.type!=="message")return[];let z=Q.message;if(z?.role!=="user"&&z?.role!=="assistant"||!z.content)return[];let W=typeof z.content==="string"?z.content:Array.isArray(z.content)?z.content.filter((U)=>typeof U==="object"&&U!==null&&U.type==="text"&&typeof U.text==="string").map((U)=>U.text).join(" "):"",V=M9(W,Z,J,Y,z.role,typeof Q.timestamp==="string"?Q.timestamp:void 0,X+1);return V?[V]:[]})}function M9($,Z,J,Y,Q,X,z){if(!$)return;let W=J?$:$.toLowerCase();if(!W.includes(Z))return;let V=W.indexOf(Z),U=Math.max(0,V-80),H=Math.min($.length,V+Z.length+80);return{sessionId:Y,role:Q,content:(U>0?"...":"")+$.slice(U,H).replace(/\n/g," ")+(H<$.length?"...":""),timestamp:X,lineNumber:z}}function JW($){if($.length===0)return"没有找到匹配的历史记录";let Z=[`**找到 ${$.length} 条匹配:**
|
|
1680
1680
|
`];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(`
|
|
1681
1681
|
`)}var ZF={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=c(Z);if($.length===0)return J.sendMessage("**用法:** `/search <关键词>`\n\n在历史会话中搜索包含指定关键词的对话"),{success:!0,message:"显示帮助"};let Y=$.join(" ");J.sendMessage(`正在搜索: "${Y}" ...`);try{let Q=await ZW(Y,{maxResults:15,projectPath:Z.cwd}),X=JW(Q);return J.sendMessage(X),{success:!0,message:`found ${Q.length} results`,data:{matches:Q.length}}}catch(Q){let X=Q instanceof Error?Q.message:"未知错误";return J.sendMessage(`搜索失败: ${X}`),{success:!1,error:X}}}},YW=ZF;var JF={name:"skills",description:"查看所有可用的 Skills",fullDescription:"显示所有已发现的 Skills 及其详细信息,包括名称、描述、来源和允许的工具。",usage:"/skills",category:"system",examples:["/skills"],handler:async($,Z)=>{try{let J=Z.workspaceRoot??Z.cwd;return await f$(J,async(Y)=>{await Y.skills.refresh(),i1(J),await l1(J)}),{success:!0,message:"show_skills_manager",data:{action:"show_skills_manager"}}}catch(J){let Y=`获取 Skills 失败: ${J instanceof Error?J.message:"未知错误"}`;return d().addAssistantMessage(Y),{success:!1,error:Y}}}},QW=JF;import YF from"node:path";function O8($){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 XW($){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 zW($,Z){if($.length<=Z)return $;return $.slice(0,Z-3)+"..."}async function QF($,Z){let J=c(Z),Y=$[0],Q=Y0.getInstance(),X=D0.getInstance(),z=Z.sessionId??"",W=Z.sessionId?{sessionId:Z.sessionId,projectPath:YF.resolve(Z.workspaceRoot??Z.cwd)}:void 0;if(Y==="resume"){let D=$[1],w=$.slice(2).join(" ").trim();if(!D||!w)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 q=await Z.subagents.resume(D,w),_=`Resumed \`${D}\` as \`${q.session.id}\` (depth ${q.session.resumeDepth}).`;return J.sendMessage(_),{success:!0,message:_,data:{action:"subagent_resumed",sourceAgentId:D,subagent:q.session}}}if(Y==="clean"){let D=X.cleanupExpiredSessionsForParent(W??z,0);return J.sendMessage(`已清理 ${D} 个已完成的 Agent 会话`),{success:!0,message:`Cleaned ${D} agent sessions`}}let V=[`**后台任务列表**
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{sc as Xt,tc as En,uc as yn,vc as bn}from"./chunk-zzvs471p.js";import{zh as Bt}from"./chunk-
|
|
1
|
+
import{sc as Xt,tc as En,uc as yn,vc as bn}from"./chunk-zzvs471p.js";import{zh as Bt}from"./chunk-wd9e2h6g.js";import{$h as wn,Eh as xt,Fh as vi,Gh as sn,Hh as zt,Ih as U,Jh as en,Kh as gt,Lh as mt,Nh as rn,Oh as Tn,Ph as B,Qh as dn,Rh as on,Sh as pn,Th as lt,Uh as un,Vh as cn,Wh as Mn,Yh as S,ai as Gt,bi as Ut,ci as h,di as Ht}from"./chunk-2r44bj6y.js";import{bj as It}from"./chunk-2f8d0km4.js";import{Fj as X,Hj as x}from"./chunk-2mk914vk.js";import{Xj as tn,Yj as nn}from"./chunk-07e9sc9n.js";import{Mk as ns}from"./chunk-eg3ms291.js";import{EventEmitter as fs}from"events";import Un from"node:path";function hn(t){if(t===void 0)return"undefined";if(typeof t==="string")return t;try{let i=JSON.stringify(t);return i===void 0?String(t):i}catch{return String(t)}}function An(t){let i=t;switch(t.code){case"type":return`类型错误:${t.message}`;case"required":return"缺少必需参数";case"minLength":return`字符串过短:${t.message}`;case"maxLength":return`字符串过长:${t.message}`;case"minimum":case"exclusiveMinimum":return`数值太小:${t.message}`;case"maximum":case"exclusiveMaximum":return`数值太大:${t.message}`;case"minItems":return`数组元素过少:${t.message}`;case"maxItems":return`数组元素过多:${t.message}`;case"format":return`格式错误:${t.message}`;case"enum":return`必须是枚举允许的值之一:${t.message}`;case"const":return`必须是指定的字面量值:${t.message}`;case"additionalProperties":case"unevaluatedProperties":return`包含未知参数:${t.message}`;case"anyOf":case"oneOf":return"不符合任何有效的类型定义";case"~refine":return t.message||"自定义验证失败";default:return t.message||`验证失败:${hn(i)}`}}class Jt extends Error{issues;type;constructor(t,i,n="validation_error"){super(t);this.issues=i;this.type=n;this.name="ToolValidationError"}}function Vt(t,i){let n=X(t,i);if(n.success)return n.data;let s=n.error.issues.map((r)=>({field:r.path.length>0?r.path.join("."):"root",message:An(r),value:r.value})),e=s.length===1?`参数验证失败 [${s[0].field}]: ${s[0].message}`:`参数验证失败 (${s.length} 个错误):
|
|
2
2
|
${s.map((r)=>` - ${r.field}: ${r.message}`).join(`
|
|
3
3
|
`)}`;throw new Jt(e,s)}function st(t){if(!t||typeof t!=="object")return;let i=t;if(i.type==="object"&&i.properties)i.required??=[],i.additionalProperties??=!1;for(let n of Object.values(i))if(Array.isArray(n))for(let s of n)st(s);else st(n)}function et(t){let i=JSON.parse(JSON.stringify(t,(n,s)=>n.startsWith("~")?void 0:s));return st(i),i}class rt{toolName;params;executeFn;descriptionFn;affectedPathsFn;isRetrySafe;constructor(t,i,n,s,e,r=!1){this.toolName=t;this.params=i;this.executeFn=n;this.descriptionFn=s;this.affectedPathsFn=e;this.isRetrySafe=r}getDescription(){if(this.descriptionFn)return this.descriptionFn(this.params);return`执行工具: ${this.toolName}`}getAffectedPaths(){if(this.affectedPathsFn)return this.affectedPathsFn(this.params);return[]}async execute(t,i,n){let s={signal:t,updateOutput:i,...n};return this.executeFn(this.params,s)}}function jt(t){return{name:t.name,displayName:t.displayName,kind:t.kind,isConcurrencySafe:t.isConcurrencySafe??!1,isRetrySafe:t.isRetrySafe??!1,parallelism:t.parallelism??(t.isConcurrencySafe?"shared":"exclusive"),strict:t.strict??!1,description:t.description,version:t.version||"1.0.0",category:t.category,tags:t.tags||[],getFunctionDeclaration(){let i=et(t.schema),n=t.description.short;if(t.description.long)n+=`
|
|
4
4
|
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{wf as v}from"./chunk-nheny8xp.js";import{Pf as e}from"./chunk-
|
|
1
|
+
import{wf as v}from"./chunk-nheny8xp.js";import{Pf as e}from"./chunk-4m7ewvvb.js";import{Ci as S,Di as m,Ei as c,Fi as p,Hi as u,Ii as d,Mi as l,Ri as i,Si as t,ei as y,gi as D,hi as h,ji as A,qi as P,ri as T,ti as E,vi as _,wi as f,yi as C}from"./chunk-2r44bj6y.js";import{Ti as Y}from"./chunk-kv458q06.js";import{$i as X}from"./chunk-2f8d0km4.js";import{dj as U,ej as L,kj as M,lj as O,nj as $,oj as I,pj as G,rj as N,sj as j,uj as F,vj as R}from"./chunk-ddvdc2p0.js";import{Dj as s,Fj as x,Hj as k,Kj as Z}from"./chunk-2mk914vk.js";import{promises as a}from"node:fs";import g from"node:path";var r=["systemPrompt","appendSystemPrompt","initialMessage","resumeSessionId","forkSession","allowedTools","disallowedTools","mcpConfigPaths","strictMcpConfig","model","addDirs","outputFormat","inputFormat","print","includePartialMessages","replayUserMessages","agentsConfig","settingSources"],kk=new Set([...Object.keys(l),...r,"providerRequestConcurrency","providerGlobalConcurrency","providerOwnerConcurrency"]),W=k.Number({exclusiveMinimum:0}),z=k.String({minLength:1}),b=k.Array(k.String()),qk=k.Object({currentModelId:k.Optional(k.String()),modelProviders:k.Optional(k.Record(z,k.Object({name:z,baseUrl:z,wireApi:Z(["openai-completions","anthropic-messages"]),apiKeyEnv:k.Optional(z)}))),models:k.Optional(k.Array(k.Object({id:z,displayName:k.Optional(z),provider:z,model:z,overrides:k.Optional(k.Object({baseUrl:k.Optional(k.String()),temperature:k.Optional(k.Number()),maxOutputTokens:k.Optional(W),timeout:k.Optional(W),streamIdleTimeout:k.Optional(k.Number({minimum:1000})),apiVersion:k.Optional(k.String()),customHeaders:k.Optional(k.Record(k.String(),k.String())),maxRetries:k.Optional(k.Integer({minimum:0})),enablePromptCaching:k.Optional(k.Boolean())})),fallbackModels:k.Optional(k.Array(k.Object({provider:z,model:z,configId:k.Optional(z)})))}))),temperature:k.Optional(k.Number()),maxOutputTokens:k.Optional(W),stream:k.Optional(k.Boolean()),topP:k.Optional(k.Number()),topK:k.Optional(k.Number()),timeout:k.Optional(W),bashForegroundHandoffMs:k.Optional(k.Union([k.Literal(0),k.Integer({minimum:P,maximum:T})])),providerForegroundRecoveryMs:k.Optional(k.Union([k.Literal(0),k.Integer({minimum:U,maximum:L})])),providerCircuitBreakerOpenMs:k.Optional(k.Union([k.Literal(0),k.Integer({minimum:M,maximum:O})])),providerRequestConcurrency:k.Optional(k.Integer({minimum:$,maximum:I})),providerGlobalConcurrency:k.Optional(k.Integer({minimum:$,maximum:G})),providerOwnerConcurrency:k.Optional(k.Integer({minimum:$,maximum:G})),providerRequestAdmissionMs:k.Optional(k.Union([k.Literal(0),k.Integer({minimum:N,maximum:j})])),providerRequestPendingBytes:k.Optional(k.Integer({minimum:F,maximum:R})),agentTeamsEnabled:k.Optional(k.Boolean()),codeTheme:k.Optional(k.String()),uiTheme:k.Optional(Z(["light","dark","system"])),language:k.Optional(k.String()),fontSize:k.Optional(W),autoSaveSessions:k.Optional(k.Boolean()),notifyBuild:k.Optional(k.Boolean()),notifyErrors:k.Optional(k.Boolean()),notifySounds:k.Optional(k.Boolean()),privacyTelemetry:k.Optional(k.Boolean()),privacyCrash:k.Optional(k.Boolean()),debug:k.Optional(k.Union([k.Boolean(),k.String()])),mcpEnabled:k.Optional(k.Boolean()),mcpServers:k.Optional(k.Record(k.String(),k.Record(k.String(),k.Unknown()))),lspServers:k.Optional(k.Record(z,k.Object({command:z,args:k.Optional(k.Array(k.String())),extensionToLanguage:k.Record(z,z),env:k.Optional(k.Record(k.String(),k.String())),initializationOptions:k.Optional(k.Unknown()),settings:k.Optional(k.Unknown()),enabled:k.Optional(k.Boolean()),priority:k.Optional(k.Integer()),startupTimeout:k.Optional(k.Integer({minimum:100})),shutdownTimeout:k.Optional(k.Integer({minimum:100})),requestTimeout:k.Optional(k.Integer({minimum:100})),diagnosticWaitTimeout:k.Optional(k.Integer({minimum:0})),maxRestarts:k.Optional(k.Integer({minimum:0,maximum:10}))}))),permissionMode:k.Optional(k.Enum(Y)),maxTurns:k.Optional(k.Integer({minimum:-1})),maxConcurrentTasks:k.Optional(k.Integer({minimum:S,maximum:m})),maxQueuedTasks:k.Optional(k.Integer({minimum:c,maximum:p})),maxQueuedTaskBytes:k.Optional(k.Integer({minimum:u,maximum:d})),maxResidentSessionRuntimes:k.Optional(k.Integer({minimum:E,maximum:_})),sessionRuntimeIdleMs:k.Optional(k.Integer({minimum:f,maximum:C})),maxResidentSessionProjections:k.Optional(k.Integer({minimum:y,maximum:D})),sessionProjectionIdleMs:k.Optional(k.Integer({minimum:h,maximum:A})),systemPrompt:k.Optional(k.String()),appendSystemPrompt:k.Optional(k.String()),initialMessage:k.Optional(k.String()),resumeSessionId:k.Optional(k.String()),forkSession:k.Optional(k.Boolean()),allowedTools:k.Optional(k.Array(z)),disallowedTools:k.Optional(k.Array(z)),mcpConfigPaths:k.Optional(k.Array(z)),strictMcpConfig:k.Optional(k.Boolean()),model:k.Optional(z),addDirs:k.Optional(k.Array(z)),outputFormat:k.Optional(Z(["text","json","stream-json","jsonl"])),inputFormat:k.Optional(Z(["text","stream-json"])),print:k.Optional(k.Boolean()),includePartialMessages:k.Optional(k.Boolean()),replayUserMessages:k.Optional(k.Boolean()),agentsConfig:k.Optional(k.String()),settingSources:k.Optional(k.String()),permissions:k.Optional(k.Object({allow:k.Optional(b),ask:k.Optional(b),deny:k.Optional(b)})),env:k.Optional(k.Record(k.String(),k.String())),hooks:k.Optional(k.Record(k.String(),k.Unknown())),enabledPlugins:k.Optional(k.Record(z,k.Boolean())),pluginSourcePolicy:k.Optional(k.Object({restrictToAllowedSources:k.Optional(k.Boolean()),requireGitCommitSha:k.Optional(k.Boolean()),allowedGitHosts:k.Optional(k.Array(z)),allowedMarketplaces:k.Optional(k.Array(z)),allowedLocalRoots:k.Optional(k.Array(z))})),disableAllHooks:k.Optional(k.Boolean())}),wk=[["systemPrompt","systemPrompt"],["appendSystemPrompt","appendSystemPrompt"],["initialMessage","initialMessage"],["resumeSessionId","sessionId"],["forkSession","forkSession"],["allowedTools","allowedTools"],["disallowedTools","disallowedTools"],["mcpConfigPaths","mcpConfig"],["strictMcpConfig","strictMcpConfig"],["model","model"],["addDirs","addDir"],["outputFormat","outputFormat"],["inputFormat","inputFormat"],["print","print"],["includePartialMessages","includePartialMessages"],["replayUserMessages","replayUserMessages"],["agentsConfig","agents"],["settingSources","settingSources"],["permissionMode","permissionMode"],["maxTurns","maxTurns"],["maxConcurrentTasks","maxConcurrentTasks"],["maxQueuedTasks","maxQueuedTasks"],["maxQueuedTaskBytes","maxQueuedTaskBytes"],["maxResidentSessionRuntimes","maxResidentSessionRuntimes"],["sessionRuntimeIdleMs","sessionRuntimeIdleMs"],["maxResidentSessionProjections","maxResidentSessionProjections"],["sessionProjectionIdleMs","sessionProjectionIdleMs"]];function V(q,B){let w;try{w=JSON.parse(q)}catch(H){let K=H instanceof Error?`: ${H.message}`:"";throw Error(`Invalid JSON provided to --settings (${B})${K}`)}if(!w||typeof w!=="object"||Array.isArray(w))throw Error("--settings must contain a JSON object");for(let H of Object.keys(w))if(!kk.has(H))throw Error(`Unknown --settings field: ${H}`);let J=x(qk,w);if(!J.success){let H=J.error.issues.map((K)=>`${K.path.join(".")||"settings"}: ${K.message}`).join("; ");throw Error(`Invalid --settings value: ${H}`)}return J.data}async function n(q){if(q===void 0)return;let B=q.trim();if(!B)throw Error("--settings requires a JSON object or file path");if(B.startsWith("{"))return V(B,"inline JSON");let w=g.resolve(X(),B),J;try{J=await a.readFile(w,"utf8")}catch(H){let K=H instanceof Error?`: ${H.message}`:"";throw Error(`Unable to read --settings file ${w}${K}`)}return V(J,w)}function o(q,B){if(!B)return;let w=B;for(let[J,H]of wk){if(J==="permissionMode"&&q.yolo===!0)continue;if(q[H]===void 0&&w[J]!==void 0)q[H]=w[J]}}var Q=s("General"),Uk=(q)=>{if(q.yolo){if(q.permissionMode&&q.permissionMode!=="yolo")throw Error("Cannot use both --yolo and --permission-mode with different values");q.permissionMode="yolo"}if(Array.isArray(q.allowedTools))q.allowedTools=q.allowedTools.flatMap((B)=>B.split(",").map((w)=>w.trim()).filter((w)=>w.length>0));if(Array.isArray(q.disallowedTools))q.disallowedTools=q.disallowedTools.flatMap((B)=>B.split(",").map((w)=>w.trim()).filter((w)=>w.length>0));if(Array.isArray(q.allowedTools)&&Array.isArray(q.disallowedTools)){let B=q.allowedTools.filter((w)=>q.disallowedTools.includes(w));if(B.length>0)throw Error(`Tools cannot be both allowed and disallowed: ${B.join(", ")}`)}},Lk=async(q)=>{let B=await n(typeof q.settings==="string"?q.settings:void 0);if(o(q,B),typeof q.agents==="string")v(q.agents);zk(q);try{let J=await i.getInstance().initialize(B),H=t(J,q);if(e().config.actions.setConfig(H),q.debug)Q.info("[CLI] 配置已加载到 Store")}catch(w){Q.error("[CLI] [FAIL] 配置初始化失败",w instanceof Error?w.message:w),console.error(`
|
|
2
2
|
[FAIL] 配置初始化失败
|
|
3
3
|
`),console.error("原因:",w instanceof Error?w.message:"未知错误"),console.error(`
|
|
4
4
|
请检查:`),console.error(" 1. 配置文件格式是否正确 (~/.blade/config.json)"),console.error(" 2. 是否需要运行 blade 进行首次配置"),console.error(` 3. 配置文件权限是否正确
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{Ri as I}from"./chunk-
|
|
1
|
+
import{Ri as I}from"./chunk-2r44bj6y.js";import{Oj as G,Pj as H}from"./chunk-j8hbddjp.js";import B 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 D(b){return A(b)}function E(b,q){let w=new G(q?.credentials??H().credentials);return w.configureModelProviders(b.modelProviders,b.models),w}async function Q(b,q){let w=B.resolve(b),x=I.getInstance(),[J,K]=await Promise.all([x.loadWorkspaceModelConfig(w,q),x.loadWorkspaceRuntimeSettings(w,q)]),z={...D(q),...J,...K},F=E(z);return x.validateConfig(z,F),{projectRoot:w,config:z,catalog:F}}function T(b){let q=D(b.config);return{projectRoot:B.resolve(b.projectRoot),config:q,catalog:E(q,b.catalog)}}function U(b,q){let w=D(q);return{projectRoot:B.resolve(b),config:w,catalog:E(w)}}
|
|
2
2
|
export{D as xg,Q as yg,T as zg,U as Ag};
|
|
@@ -25,7 +25,7 @@ import{Dh as YO}from"./chunk-3y2x6fb6.js";import{bj as P}from"./chunk-2f8d0km4.j
|
|
|
25
25
|
`):void 0}}async executeNotificationHooks(O,q,Q){let Z="message"in q?q.message:"";if(O.length===0)return{suppress:!1,message:Z};let Y=[],$=!1,X=Z;for(let W of O)try{let J=await this.executeHook(W,q,Q);if(!J.success){if(J.warning)Y.push(J.warning);continue}if(J.output?.suppressOutput){$=!0;break}if(J.stdout&&J.stdout.trim())X=J.stdout.trim()}catch(J){let G=J instanceof Error?J.message:String(J);Y.push(`Hook failed: ${G}`)}return{suppress:$,message:X,warning:Y.length>0?Y.join(`
|
|
26
26
|
`):void 0}}async executeCompactionHooks(O,q,Q){if(O.length===0)return{blockCompaction:!1};let Z=[];for(let Y of O)try{let $=await this.executeHook(Y,q,Q);if(!$.success){if($.warning)Z.push($.warning);continue}let X=$.output?.hookSpecificOutput;if(X&&"blockCompaction"in X&&X.blockCompaction)return{blockCompaction:!0,blockReason:X.blockReason,warning:Z.length>0?Z.join(`
|
|
27
27
|
`):void 0}}catch($){let X=$ instanceof Error?$.message:String($);Z.push(`Hook failed: ${X}`)}return{blockCompaction:!1,warning:Z.length>0?Z.join(`
|
|
28
|
-
`):void 0}}async executeHook(O,q,Q){if(O.type!=="function"){let Y=await A.getInstance().getStatus(Q.projectDir,Q.config);if(Y.state!=="trusted"){let $=`${Y.trustRoot}:${Y.currentDigest}:${Y.state}`;if(!this.trustWarnings.has($)){if(this.trustWarnings.size>=512)this.trustWarnings.clear();this.trustWarnings.add($),$O.warn(`[HookTrust] Skipping configured hooks for ${Y.trustRoot}: ${Y.state}`)}return{success:!0,hook:O,warning:`Hook skipped: project hook trust is ${Y.state}`}}}let Z=this.withHookEnvironment(Q,O);if(O.type==="command")return this.executeCommandHook(O,q,Z);if(O.type==="prompt")return this.executePromptHook(O,q,Z);if(O.type==="function")return this.executeFunctionHook(O,q,Z);if(O.type==="http")return this.executeHttpHook(O,q,Z);throw Error(`Hook type ${O.type} not supported`)}async executeCommandHook(O,q,Q){let Z=(O.timeout??Q.config.defaultTimeout??60)*1000;try{let Y=await this.processExecutor.execute(O.command,q,Q,Z);return this.outputParser.parse(Y,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}catch(Y){return{success:!1,blocking:!1,error:Y instanceof Error?Y.message:String(Y),hook:O}}}async executePromptHook(O,q,Q){let Z=(O.timeout??Q.config.defaultTimeout??60)*1000;try{let Y=await this.getOrCreateChatService(O.model,Q),$="hook_event_name"in q?String(q.hook_event_name):"Unknown",X=this.buildPromptHookSystemMessage(O,$),W=JSON.stringify(q,null,2),J=new AbortController,G=setTimeout(()=>J.abort(),Z),L;try{L=(await Y.chat([{role:"system",content:X},{role:"user",content:W}],void 0,J.signal,{providerAdmission:{sessionId:Q.sessionId,ownerId:Q.sessionId,requestClass:"background"}})).content}catch(z){if(J.signal.aborted||z instanceof Error&&z.name==="AbortError")return this.outputParser.parse({stdout:"",stderr:"",exitCode:0,timedOut:!0},O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior});throw z}finally{clearTimeout(G)}let F=this.extractJsonFromLLMResponse(L);return this.outputParser.parse({stdout:F,stderr:"",exitCode:0,timedOut:!1},O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}catch(Y){return $O.warn(`[PromptHook] 执行失败: ${Y instanceof Error?Y.message:String(Y)}`),{success:!1,blocking:!1,error:Y instanceof Error?Y.message:String(Y),hook:O}}}async executeFunctionHook(O,q,Q){let Z=(O.timeout??10)*1000;try{let Y=await this.runFunctionWithTimeout(O.handler,q,Q,Z);if(Y===void 0||Y===null)return{success:!0,hook:O};let $={stdout:JSON.stringify(Y),stderr:"",exitCode:0,timedOut:!1};return this.outputParser.parse($,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}catch(Y){if(Y.isTimeout){let $={stdout:"",stderr:`Function hook timeout after ${Z}ms`,exitCode:124,timedOut:!0};return this.outputParser.parse($,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}return{success:!1,blocking:!1,error:Y instanceof Error?Y.message:String(Y),hook:O}}}runFunctionWithTimeout(O,q,Q,Z){return new Promise((Y,$)=>{let X=!1,W=setTimeout(()=>{if(X)return;X=!0;let G=Object.assign(Error(`Function hook timed out after ${Z}ms`),{isTimeout:!0});$(G)},Z),J=()=>{if(X)return;X=!0,clearTimeout(W),$(Error("Function hook aborted"))};Q.abortSignal?.addEventListener("abort",J,{once:!0}),Promise.resolve().then(()=>O(q,Q)).then((G)=>{if(X)return;X=!0,clearTimeout(W),Q.abortSignal?.removeEventListener("abort",J),Y(G)},(G)=>{if(X)return;X=!0,clearTimeout(W),Q.abortSignal?.removeEventListener("abort",J),$(G)})})}async executeHttpHook(O,q,Q){let Z=(O.timeout??10)*1000,Y=O.maxResponseBytes??262144,$=Math.max(1,(O.retries??0)+1);try{e(O.url,Q.config.httpPolicy)}catch(G){return{success:!1,blocking:!0,error:G instanceof Error?G.message:String(G),hook:O}}let X={"Content-Type":"application/json",...OO(O.headers)},W=JSON.stringify(q),J;for(let G=0;G<$;G++){if(G>0){let V=Math.min(2**G*200,5000);await new Promise((B)=>setTimeout(B,V))}let L=new AbortController,F=setTimeout(()=>L.abort(),Z),z=()=>L.abort();Q.abortSignal?.addEventListener("abort",z,{once:!0});try{let V=await fetch(O.url,{method:"POST",headers:X,body:W,redirect:"manual",signal:L.signal});if(V.status>=300&&V.status<400){J=Error(`HTTP hook received redirect (${V.status}); redirects are disabled`);continue}if(!V.ok){if(J=Error(`HTTP hook returned ${V.status} ${V.statusText}`),V.status>=400&&V.status<500)break;continue}let U={stdout:await HO(V,Y),stderr:"",exitCode:0,timedOut:!1};return this.outputParser.parse(U,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}catch(V){let B=V.name==="AbortError"||V.code==="ABORT_ERR";if(B&&Q.abortSignal?.aborted){J=Error("HTTP hook aborted by caller");break}if(B){let U={stdout:"",stderr:`HTTP hook timeout after ${Z}ms`,exitCode:124,timedOut:!0};if(G===$-1)return this.outputParser.parse(U,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior});J=Error(`HTTP hook timeout attempt ${G+1}`);continue}J=V}finally{clearTimeout(F),Q.abortSignal?.removeEventListener("abort",z)}}return{success:!1,blocking:!1,error:J?.message??"HTTP hook failed",hook:O}}async getOrCreateChatService(O,q){let Q=this.sessionResourceKey(q.sessionId,q.projectDir),Z=`${Q}\x00${O||"__default__"}`,Y=this.chatServiceCache.get(Z);if(Y)return Y;let{ensureStoreInitialized:$,getConfig:X}=await import("./chunk-
|
|
28
|
+
`):void 0}}async executeHook(O,q,Q){if(O.type!=="function"){let Y=await A.getInstance().getStatus(Q.projectDir,Q.config);if(Y.state!=="trusted"){let $=`${Y.trustRoot}:${Y.currentDigest}:${Y.state}`;if(!this.trustWarnings.has($)){if(this.trustWarnings.size>=512)this.trustWarnings.clear();this.trustWarnings.add($),$O.warn(`[HookTrust] Skipping configured hooks for ${Y.trustRoot}: ${Y.state}`)}return{success:!0,hook:O,warning:`Hook skipped: project hook trust is ${Y.state}`}}}let Z=this.withHookEnvironment(Q,O);if(O.type==="command")return this.executeCommandHook(O,q,Z);if(O.type==="prompt")return this.executePromptHook(O,q,Z);if(O.type==="function")return this.executeFunctionHook(O,q,Z);if(O.type==="http")return this.executeHttpHook(O,q,Z);throw Error(`Hook type ${O.type} not supported`)}async executeCommandHook(O,q,Q){let Z=(O.timeout??Q.config.defaultTimeout??60)*1000;try{let Y=await this.processExecutor.execute(O.command,q,Q,Z);return this.outputParser.parse(Y,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}catch(Y){return{success:!1,blocking:!1,error:Y instanceof Error?Y.message:String(Y),hook:O}}}async executePromptHook(O,q,Q){let Z=(O.timeout??Q.config.defaultTimeout??60)*1000;try{let Y=await this.getOrCreateChatService(O.model,Q),$="hook_event_name"in q?String(q.hook_event_name):"Unknown",X=this.buildPromptHookSystemMessage(O,$),W=JSON.stringify(q,null,2),J=new AbortController,G=setTimeout(()=>J.abort(),Z),L;try{L=(await Y.chat([{role:"system",content:X},{role:"user",content:W}],void 0,J.signal,{providerAdmission:{sessionId:Q.sessionId,ownerId:Q.sessionId,requestClass:"background"}})).content}catch(z){if(J.signal.aborted||z instanceof Error&&z.name==="AbortError")return this.outputParser.parse({stdout:"",stderr:"",exitCode:0,timedOut:!0},O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior});throw z}finally{clearTimeout(G)}let F=this.extractJsonFromLLMResponse(L);return this.outputParser.parse({stdout:F,stderr:"",exitCode:0,timedOut:!1},O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}catch(Y){return $O.warn(`[PromptHook] 执行失败: ${Y instanceof Error?Y.message:String(Y)}`),{success:!1,blocking:!1,error:Y instanceof Error?Y.message:String(Y),hook:O}}}async executeFunctionHook(O,q,Q){let Z=(O.timeout??10)*1000;try{let Y=await this.runFunctionWithTimeout(O.handler,q,Q,Z);if(Y===void 0||Y===null)return{success:!0,hook:O};let $={stdout:JSON.stringify(Y),stderr:"",exitCode:0,timedOut:!1};return this.outputParser.parse($,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}catch(Y){if(Y.isTimeout){let $={stdout:"",stderr:`Function hook timeout after ${Z}ms`,exitCode:124,timedOut:!0};return this.outputParser.parse($,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}return{success:!1,blocking:!1,error:Y instanceof Error?Y.message:String(Y),hook:O}}}runFunctionWithTimeout(O,q,Q,Z){return new Promise((Y,$)=>{let X=!1,W=setTimeout(()=>{if(X)return;X=!0;let G=Object.assign(Error(`Function hook timed out after ${Z}ms`),{isTimeout:!0});$(G)},Z),J=()=>{if(X)return;X=!0,clearTimeout(W),$(Error("Function hook aborted"))};Q.abortSignal?.addEventListener("abort",J,{once:!0}),Promise.resolve().then(()=>O(q,Q)).then((G)=>{if(X)return;X=!0,clearTimeout(W),Q.abortSignal?.removeEventListener("abort",J),Y(G)},(G)=>{if(X)return;X=!0,clearTimeout(W),Q.abortSignal?.removeEventListener("abort",J),$(G)})})}async executeHttpHook(O,q,Q){let Z=(O.timeout??10)*1000,Y=O.maxResponseBytes??262144,$=Math.max(1,(O.retries??0)+1);try{e(O.url,Q.config.httpPolicy)}catch(G){return{success:!1,blocking:!0,error:G instanceof Error?G.message:String(G),hook:O}}let X={"Content-Type":"application/json",...OO(O.headers)},W=JSON.stringify(q),J;for(let G=0;G<$;G++){if(G>0){let V=Math.min(2**G*200,5000);await new Promise((B)=>setTimeout(B,V))}let L=new AbortController,F=setTimeout(()=>L.abort(),Z),z=()=>L.abort();Q.abortSignal?.addEventListener("abort",z,{once:!0});try{let V=await fetch(O.url,{method:"POST",headers:X,body:W,redirect:"manual",signal:L.signal});if(V.status>=300&&V.status<400){J=Error(`HTTP hook received redirect (${V.status}); redirects are disabled`);continue}if(!V.ok){if(J=Error(`HTTP hook returned ${V.status} ${V.statusText}`),V.status>=400&&V.status<500)break;continue}let U={stdout:await HO(V,Y),stderr:"",exitCode:0,timedOut:!1};return this.outputParser.parse(U,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}catch(V){let B=V.name==="AbortError"||V.code==="ABORT_ERR";if(B&&Q.abortSignal?.aborted){J=Error("HTTP hook aborted by caller");break}if(B){let U={stdout:"",stderr:`HTTP hook timeout after ${Z}ms`,exitCode:124,timedOut:!0};if(G===$-1)return this.outputParser.parse(U,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior});J=Error(`HTTP hook timeout attempt ${G+1}`);continue}J=V}finally{clearTimeout(F),Q.abortSignal?.removeEventListener("abort",z)}}return{success:!1,blocking:!1,error:J?.message??"HTTP hook failed",hook:O}}async getOrCreateChatService(O,q){let Q=this.sessionResourceKey(q.sessionId,q.projectDir),Z=`${Q}\x00${O||"__default__"}`,Y=this.chatServiceCache.get(Z);if(Y)return Y;let{ensureStoreInitialized:$,getConfig:X}=await import("./chunk-dpnf1agz.js"),{createChatServiceAsync:W}=await import("./chunk-n6mv8p83.js"),{resolveModelConfig:J}=await import("./chunk-pzqy0x7r.js"),{resolveWorkspaceModelResources:G}=await import("./chunk-q7mnac52.js");await $();let L=X();if(!L)throw Error("PromptHook: 配置未初始化");let F=this.sessionModelResources.get(Q)??await G(q.projectDir,L),z=O?F.config.models.find((B)=>B.id===O):F.config.models.find((B)=>B.id===F.config.currentModelId)??F.config.models[0];if(!z)throw Error("PromptHook: 无法获取模型配置。请确保至少配置了一个模型。");let V=await W(J(z,F.config,"off",F.catalog).chat);return this.chatServiceCache.set(Z,V),V}sessionResourceKey(O,q){return`${O}\x00${DO.resolve(q)}`}withSessionEnvironment(O){let q=this.sessionEnvironments.get(this.sessionResourceKey(O.sessionId,O.projectDir));return q?{...O,environment:q}:O}withHookEnvironment(O,q){let Q=this.withSessionEnvironment(O);if(!q.source)return Q;return{...Q,environment:{...Q.environment,BLADE_PLUGIN_ROOT:q.source.pluginRoot,CLAUDE_PLUGIN_ROOT:q.source.pluginRoot,BLADE_PLUGIN_NAME:q.source.pluginName}}}buildPromptHookSystemMessage(O,q){let Q=yO[q]||"{ ... 根据事件类型返回相应字段 }";return`你是一个代码质量评估器,作为 Hook 在 ${q} 事件中被触发。
|
|
29
29
|
|
|
30
30
|
`+`## 评估指令
|
|
31
31
|
${O.prompt}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{Xj as I}from"./chunk-
|
|
1
|
+
import{Xj as I}from"./chunk-07e9sc9n.js";import{Mk as f}from"./chunk-eg3ms291.js";import*as j from"fs/promises";import*as S from"path";import X from"semver";import{ProxyAgent as R,fetch as k}from"undici";function x(){return process.env.HTTPS_PROXY||process.env.HTTP_PROXY||process.env.https_proxy||process.env.http_proxy}function L(){let z=x();if(z)try{return new R(z)}catch(q){console.warn(`[proxyFetch] Invalid proxy URL: ${z}`)}return}async function F(z,q,Z){let{timeout:W=30000,signal:J,...Q}=q;if(J?.aborted)throw new DOMException("The operation was aborted.","AbortError");let Y=L(),$=new AbortController,w=!1,y=setTimeout(()=>{w=!0,$.abort()},W),T=()=>$.abort();J?.addEventListener("abort",T);let D;try{let B={method:Q.method,headers:Q.headers,body:Q.body,signal:$.signal,dispatcher:Y};return D=await k(z.toString(),B),await Z(D)}catch(B){if(B instanceof Error&&B.name==="AbortError"){if(w)throw Error(`Request timeout after ${W}ms`);throw B}throw B}finally{if(clearTimeout(y),J?.removeEventListener("abort",T),$.abort(),D?.body&&!D.body.locked)await D.body.cancel().catch(()=>{return});await Y?.destroy?.().catch(()=>{return})}}var O="blade-code",G="https://cdn.jsdelivr.net/npm/blade-code@latest/CHANGELOG.md",H=S.join(process.env.HOME||process.env.USERPROFILE||".",".blade"),N=S.join(H,"version-cache.json"),_=3600000,g=`https://registry.npmjs.org/${O}/latest`,M=null;async function P(){try{if(process.env.BLADE_VERSION)return process.env.BLADE_VERSION;return I()}catch{return"unknown"}}async function b(){try{let z=await j.readFile(N,"utf-8"),q=JSON.parse(z);if(Date.now()-q.checkedAt<_)return q;return{...q,checkedAt:0}}catch{return null}}async function K(z){try{await j.mkdir(H,{recursive:!0,mode:493}),await j.writeFile(N,JSON.stringify(z,null,2))}catch{}}async function E(){try{return await F(g,{timeout:5000,headers:{Accept:"application/json"}},async(z)=>{if(!z.ok)return null;let q=await z.json();if(!q||typeof q!=="object"||!("version"in q))return null;return typeof q.version==="string"&&X.valid(q.version)?q.version:null})}catch{return null}}async function A(z=!1){let q=await P(),Z=G;if(q==="unknown")return{currentVersion:q,latestVersion:null,hasUpdate:!1,shouldPrompt:!1,releaseNotesUrl:Z,error:"Unable to determine current version"};let W=await b(),J=W?.skipUntilVersion,Q=null;if(!z&&W?.latestVersion&&W.checkedAt>0)Q=W.latestVersion;else if(Q=await E(),J=(await b())?.skipUntilVersion??J,Q)await K({latestVersion:Q,checkedAt:Date.now(),skipUntilVersion:J});else if(W?.latestVersion)await K({checkedAt:0,skipUntilVersion:J});if(!Q||!X.valid(Q))return{currentVersion:q,latestVersion:null,hasUpdate:!1,shouldPrompt:!1,releaseNotesUrl:Z,error:"Unable to check for updates"};if(X.lt(Q,q))Q=q,await K({latestVersion:Q,checkedAt:Date.now(),skipUntilVersion:J});let Y=X.gt(Q,q),$=Y;if(Y&&J)$=X.gt(Q,J);return{currentVersion:q,latestVersion:Q,hasUpdate:Y,shouldPrompt:$,releaseNotesUrl:Z}}async function V(z){let q=await b();await K({latestVersion:q?.latestVersion??z,checkedAt:q?.checkedAt||Date.now(),skipUntilVersion:z})}function v(){return`npm install -g ${O}@latest --registry https://registry.npmjs.org`}async function p(){let{spawn:z}=await import("child_process");return new Promise((q)=>{let Z=v(),W=z(Z,{stdio:"inherit",shell:!0});W.on("close",(J)=>{if(J===0)q({success:!0,message:"Upgrade successful! Please restart blade."});else q({success:!1,message:`Upgrade failed (exit code: ${J})`})}),W.on("error",(J)=>{q({success:!1,message:`Upgrade failed: ${J.message}`})})})}async function h(){try{let z=await b();if(!z?.latestVersion||!X.valid(z.latestVersion)||!z.checkedAt){if(!M)M=A(!0).then(()=>{return},()=>{return}).finally(()=>{M=null});return null}let q=await P();if(!X.valid(q)||!X.gt(z.latestVersion,q)||z.skipUntilVersion&&X.valid(z.skipUntilVersion)&&!X.gt(z.latestVersion,z.skipUntilVersion))return null;return{currentVersion:q,latestVersion:z.latestVersion,hasUpdate:!0,shouldPrompt:!0,releaseNotesUrl:G}}catch{return null}}
|
|
2
2
|
export{A as k,V as l,v as m,p as n,h as o};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{e as $X,f as JX,h as S$,i as M4}from"./chunk-jjjvz6v7.js";import{l as eX,m as $Z,n as JZ}from"./chunk-8jej5dnz.js";import{A as q4,y as A9,z as b9}from"./chunk-r26t032c.js";import{Aa as XY,Ca as ZY,Ea as uY,I as cY,M as WZ,O as h6,P as R6,Q as vY,W as wY,X as PY,_ as AY,da as r$,fa as y9,ga as I9,ia as bY,ka as K8,la as LX,ma as BX,pa as wX,qa as PX,ua as lJ,va as B3,xa as H3,ya as F3,za as HZ}from"./chunk-3dv3evbn.js";import"./chunk-g01mth5d.js";import{Ma as E5,Na as h5,Oa as g5,Ra as NZ}from"./chunk-8mpcm1jr.js";import{Ta as BY}from"./chunk-30x3mcsb.js";import{Mb as FY,Nb as F4,Zb as LY,hc as P6}from"./chunk-04m1jgng.js";import{sc as O8}from"./chunk-zzvs471p.js";import{Cd as zY,Md as P9,Nd as h2,Rd as R9,Wd as C9,Yd as t8,ee as U8,he as a0}from"./chunk-99ydmdy1.js";import"./chunk-53fc0yrq.js";import{Le as D9,Me as w6,Ne as f9}from"./chunk-y5wngtz0.js";import{if as e9,jf as G4}from"./chunk-w33zjw8m.js";import{wf as tX}from"./chunk-nheny8xp.js";import{Af as J1,xf as N8,yf as _4}from"./chunk-q14w6rtd.js";import"./chunk-jj4ggb04.js";import{Ef as R2,Ff as L$,Gf as r1,Hf as UJ,If as o8,Jf as M9,Kf as t3,Lf as CJ,Mf as r5,Nf as s3,Of as f2,Pf as m0,Qf as _Z,Rf as B$,Sf as nX,Tf as a4,Uf as q8,Xf as s9,cg as z$}from"./chunk-b0y58dgr.js";import"./chunk-v508x7cg.js";import"./chunk-t0gm0pn1.js";import"./chunk-1yq72zb7.js";import"./chunk-kqvzmnja.js";import{ug as yJ}from"./chunk-0mr8nexh.js";import"./chunk-50vwafn5.js";import"./chunk-nmcv402m.js";import{Hg as H4,Jg as hX,Og as FX,Xg as OZ}from"./chunk-qb80hv8n.js";import"./chunk-3kszepm6.js";import"./chunk-wcps5gjm.js";import"./chunk-vbjgcn49.js";import"./chunk-06hkf59s.js";import{xh as qJ,zh as E$}from"./chunk-n0njjq63.js";import"./chunk-3y2x6fb6.js";import{Mi as zZ,Ri as HX,Si as qZ}from"./chunk-bzg3srr2.js";import{Ui as h9}from"./chunk-kv458q06.js";import{Vi as g2,Wi as e8,Yi as _J}from"./chunk-5v0jcyea.js";import{bj as K$}from"./chunk-2f8d0km4.js";import"./chunk-ddvdc2p0.js";import{Aj as KZ,Dj as O1}from"./chunk-2mk914vk.js";import{Lj as t5,Mj as s5,Pj as T1}from"./chunk-j8hbddjp.js";import"./chunk-4cdk4mds.js";import{$j as x5}from"./chunk-g5fa6sd6.js";import{ck as uJ}from"./chunk-rvs364rz.js";import"./chunk-vw9paban.js";import{fk as G8,zk as t9}from"./chunk-4wx5sya5.js";import{Mk as Y4}from"./chunk-eg3ms291.js";import{useMemoizedFn as Q6}from"ahooks";import{useEffect as Gz,useState as G6}from"react";import{useMemoizedFn as i0}from"ahooks";import iX from"ansi-escapes";import{Box as h1,useStdout as eK}from"ink";import{useEffect as $1,useMemo as $z,useRef as y2,useState as oX}from"react";import{useShallow as BZ}from"zustand/react/shallow";import{useStore as LZ}from"zustand";function z0($){return LZ(f2,$)}var wZ=[],v2=()=>z0(($)=>$.session.sessionId),_1=()=>z0(($)=>$.session.workspaceRoot),v8=()=>z0(($)=>$.session.messages),rJ=()=>z0(($)=>$.session.clearCount),aJ=()=>z0(($)=>$.session.isCompacting),iJ=()=>z0(($)=>$.session.tokenUsage.estimatedCostUsd),oJ=()=>z0(($)=>{let{totalInputTokens:J,cacheReadTokens:Y,cacheWriteTokens:Z}=$.session.tokenUsage;return lJ({totalInputTokens:J,cacheReadTokens:Y,cacheWriteTokens:Z}).hitRate});var V8=()=>z0(($)=>$.session.providerRecovery),nJ=()=>z0(($)=>$.session.turnActivity),tJ=()=>z0(($)=>$.session.actionStationarity),c1=()=>z0(($)=>$.session.actions),sJ=()=>z0(($)=>{let{totalTokens:J,maxContextTokens:Y}=$.session.tokenUsage;if(Y<=0)return 100;let Z=Math.max(0,100-J/Y*100);return Math.round(Z)}),eJ=()=>z0(($)=>$.app.initializationStatus),$9=()=>z0(($)=>$.app.initializationError),j8=()=>z0(($)=>$.app.activeModal),J9=()=>z0(($)=>$.app.tasks),Y9=()=>z0(($)=>$.app.modelEditorTarget),X9=()=>z0(($)=>$.app.sessionSelectorData),Z9=()=>z0(($)=>$.app.sessionHistoryViewerData),Q9=()=>z0(($)=>$.app.taskAttentionStatus),E8=()=>z0(($)=>$.app.taskAttentionUnreadKeys),G9=()=>z0(($)=>$.app.awaitingSecondCtrlC),u1=()=>z0(($)=>$.app.actions),V2=()=>z0(($)=>$.app.sideConversation),U9=()=>z0(($)=>$.app.teams),h8=()=>z0(($)=>$.app.initializationStatus==="ready"),K9=()=>z0(($)=>$.app.tasks.length>0),j2=()=>z0(($)=>$.config.config?.permissionMode||"default"),z9=()=>z0(($)=>$.config.config?.models??wZ),g8=()=>z0(($)=>{let J=$.config.config;if(!J)return;let Y=J.currentModelId;return J.models.find((X)=>X.id===Y)??J.models[0]}),m8=()=>z0(($)=>$.config.config?.currentModelId),q9=()=>z0(($)=>$.config.config?.agentTeamsEnabled===!0),D0=()=>z0(($)=>{return L$.getTheme()}),_9=()=>z0(($)=>$.config.config?.codeTheme??"default"),Z$=()=>z0(($)=>$.focus.currentFocus),O9=()=>z0(($)=>$.focus.actions),E2=()=>z0(($)=>$.command.isProcessing),N9=()=>z0(($)=>$.command.actions),p8=()=>z0(($)=>$.app.followUpQueue),W9=()=>z0(($)=>$.app.followUpQueueMutation),H9=()=>z0(($)=>$.command.recoveredSteeringCount),x8=()=>z0(($)=>$.app.reasoningEffort!=="off"),c8=()=>z0(($)=>$.app.reasoningEffort),u8=()=>z0(($)=>$.app.serviceTier),d8=()=>z0(($)=>$.app.responseVerbosity),l8=()=>z0(($)=>$.app.communicationStyle),r8=()=>z0(($)=>$.session.currentThinkingContent),F9=()=>z0(($)=>$.session.thinkingExpanded),a8=()=>z0(($)=>$.session.currentStreamingMessageId),i8=()=>z0(BZ(($)=>({lines:$.session.currentStreamingLines,tail:$.session.currentStreamingTail,lineCount:$.session.currentStreamingLineCount,version:$.session.currentStreamingVersion}))),L9=()=>z0(($)=>$.session.finalizingStreamingMessageId),B9=()=>z0(($)=>$.session.historyExpanded),w9=()=>z0(($)=>$.session.expandedMessageCount);import{randomUUID as _7}from"node:crypto";import{useMemoizedFn as Y1}from"ahooks";import{useEffect as d1,useMemo as WY,useRef as N4}from"react";function PZ($,J){try{return $.code===J.code&&$.message===J.message&&$.retryable===J.retryable&&$.resource===J.resource}catch{return!1}}class K6{options;requested=!1;waitingForIdle=!1;disposed=!1;generation=0;wakeEpoch=0;idleEpoch=0;attempt=0;recoveryStartedAt=null;scheduledToken=null;activeAttemptToken=null;activeRunController=null;retryTimer=null;deadlineTimer=null;now;scheduleCallback;setTimerCallback;clearTimerCallback;constructor($){this.options=$;this.now=$.now??Date.now,this.scheduleCallback=$.scheduleMicrotask??queueMicrotask,this.setTimerCallback=$.setTimer??setTimeout,this.clearTimerCallback=$.clearTimer??clearTimeout}request(){if(this.disposed)return;if(this.wakeEpoch++,this.requested=!0,this.waitingForIdle||this.retryTimer)return;this.scheduleIfRunnable()}notifyIdle(){if(this.disposed)return;if(this.idleEpoch++,this.retryTimer)return;this.waitingForIdle=!1,this.scheduleIfRunnable()}dispose(){if(this.disposed)return;this.disposed=!0,this.generation++,this.requested=!1,this.waitingForIdle=!1,this.scheduledToken=null,this.clearOwnedTimer("retry"),this.clearOwnedTimer("deadline"),this.activeAttemptToken=null;let $=this.activeRunController;this.activeRunController=null,$?.abort("pending-resume-coordinator-disposed"),this.resetEpisodeBudget()}scheduleIfRunnable(){if(this.disposed||!this.requested||this.scheduledToken||this.activeAttemptToken||this.retryTimer||this.waitingForIdle)return;if(!this.options.canRun()){this.waitingForIdle=!0;return}let $=this.generation,J={};this.scheduledToken=J;try{this.scheduleCallback(()=>{if(this.disposed||$!==this.generation||this.scheduledToken!==J)return;this.scheduledToken=null,this.flush($).catch((Y)=>{this.handleUnexpectedFailure(Y,$)})})}catch(Y){this.handleUnexpectedFailure(Y,$)}}async flush($){if(this.disposed||$!==this.generation||this.activeAttemptToken||!this.requested||this.retryTimer||this.waitingForIdle)return;if(!this.options.canRun()){this.waitingForIdle=!0;return}let J={},Y=new AbortController,Z=this.wakeEpoch,X=this.idleEpoch;if(this.attempt++,this.recoveryStartedAt===null)this.recoveryStartedAt=this.now(),this.installDeadlineTimer($);this.activeAttemptToken=J,this.activeRunController=Y;let Q;try{Q=await this.options.run(Y.signal)}finally{if(this.activeAttemptToken===J){if(this.activeAttemptToken=null,this.activeRunController=null,!this.disposed&&$!==this.generation)this.scheduleIfRunnable()}}if(this.disposed||$!==this.generation)return;if(Q.status==="completed"){let G=this.wakeEpoch!==Z;if(this.clearEpisode(),G)this.requested=!0,this.scheduleIfRunnable();return}if(Q.status==="deferred"){if(this.attempt--,this.attempt===0)this.clearOwnedTimer("deadline"),this.resetEpisodeBudget();if(this.requested=!0,this.idleEpoch!==X)this.waitingForIdle=!1,this.scheduleIfRunnable();else this.waitingForIdle=!0;return}this.handleFailure(Q,$)}handleFailure($,J){let Y=h2($.taskFailure),Z=this.options.sessionIdentity;if($.workKind!=="pending_input"||!$.evidence||!Z||!PZ($.taskFailure,$.evidence.taskFailure)){this.terminate("failed",this.attempt,Y);return}let X=b9({sessionIdentity:Z,failedAttempt:this.attempt,recoveryStartedAt:this.recoveryStartedAt??this.now(),now:this.now(),workStillPending:$.workStillPending,evidence:$.evidence});if(X.phase!=="retry_scheduled"){this.terminate(X.phase,this.attempt,Y);return}this.requested=!0,this.waitingForIdle=!1;let Q={},G=this.setTimerCallback(()=>{if(this.disposed||J!==this.generation||this.retryTimer?.token!==Q)return;this.retryTimer=null,this.scheduleIfRunnable()},X.delayMs);this.retryTimer={handle:G,token:Q},G.unref?.()}handleUnexpectedFailure($,J){if(this.disposed||J!==this.generation)return;this.terminate("failed",Math.max(1,this.attempt),h2($),"pending-resume-coordinator-failed")}installDeadlineTimer($){let J={},Y=this.setTimerCallback(()=>{if(this.disposed||$!==this.generation||this.deadlineTimer?.token!==J)return;this.deadlineTimer=null,this.terminate("exhausted",Math.max(1,this.attempt),P9("timeout"),"pending-resume-recovery-deadline-exceeded")},A9);this.deadlineTimer={handle:Y,token:J},Y.unref?.()}terminate($,J,Y,Z){let X=this.activeRunController;if(this.generation++,this.requested=!1,this.waitingForIdle=!1,this.scheduledToken=null,this.clearOwnedTimer("retry"),this.clearOwnedTimer("deadline"),this.resetEpisodeBudget(),Z)X?.abort(Z);try{this.options.onTerminalFailure?.({phase:$,attempt:J,taskFailure:Y})}catch{}}clearEpisode(){this.requested=!1,this.waitingForIdle=!1,this.clearOwnedTimer("retry"),this.clearOwnedTimer("deadline"),this.resetEpisodeBudget()}resetEpisodeBudget(){this.attempt=0,this.recoveryStartedAt=null}clearOwnedTimer($){let J=$==="retry"?this.retryTimer:this.deadlineTimer;if(!J)return;if($==="retry")this.retryTimer=null;else this.deadlineTimer=null;this.clearTimerCallback(J.handle)}}class Z8{options;finalized=!1;constructor($){this.options=$}get isFinalized(){return this.finalized}acceptsDeltas(){return!this.finalized&&!this.options.signal.aborted}startTurn(){this.finalized=!1}finalize(){if(!this.acceptsDeltas())return!1;return this.finalized=!0,this.commit(this.options.streamingBuffer.drainPendingBuffers()),!0}abortAndFinalize($){if(this.finalized)return $(),!1;this.finalized=!0;let J=this.options.streamingBuffer.drainPendingBuffers();return $(),this.commit(J),!0}discard(){this.finalized=!0,this.options.streamingBuffer.resetStreamingBuffers(),this.options.discardStreamingMessage(),this.options.clearThinking()}commit($){let J=this.options.getStreamingMessageId();if(J){if($.extraContent)o8(J,$.extraContent);M9(J)}this.options.finalizeStreamingMessage($.extraContent,$.extraThinking)}}function AZ($){if(!($ instanceof Error))return"未知错误";let Z=$.lastError??$;if(Z.responseBody)try{let G=JSON.parse(Z.responseBody)?.error?.message;if(G){let U=Z.statusCode?` (HTTP ${Z.statusCode})`:"";return`${G}${U}`}}catch{}let X=$.message.match(/Last error:\s*(.+)$/);if(X)return X[1];return $.message}function bZ($){if(!($ instanceof Error))return!1;return $.name==="AbortError"||$.message.includes("aborted")}function MZ($){if(!($ instanceof Error))return!1;let J=$.message;return J.includes("can only concatenate str")||J.includes("image_url")||J.includes("multimodal")||J.includes("vision")||J.includes("does not support images")}function n8($){let J=bZ($),Y=MZ($),Z;if(Y)Z="当前模型不支持图片理解功能。请切换到支持视觉能力的模型(如 Claude 4.5、GPT-5.2、Gemini 3 Pro、Qwen3-VL-Plus 等)后重试。";else Z=AZ($);return{displayMessage:Z,isAbort:J,isVisionNotSupported:Y}}import{appendFileSync as TZ,mkdirSync as RZ,writeFileSync as CZ}from"node:fs";import yZ from"node:os";import z6 from"node:path";var T9=null;function IZ(){let $=process.env.BLADE_STORAGE_ROOT||z6.join(yZ.homedir(),".blade");return z6.join($,"logs","stream-debug.log")}function SZ($){if(T9===$)return;let J=z6.dirname($);RZ(J,{recursive:!0,mode:493}),CZ($,`=== Stream Debug Log Started: ${new Date().toISOString()} ===
|
|
1
|
+
import{e as $X,f as JX,h as S$,i as M4}from"./chunk-0qm48ayf.js";import{l as eX,m as $Z,n as JZ}from"./chunk-wv9wrj45.js";import{A as q4,y as A9,z as b9}from"./chunk-1yqh46am.js";import{Aa as XY,Ca as ZY,Ea as uY,I as cY,M as WZ,O as h6,P as R6,Q as vY,W as wY,X as PY,_ as AY,da as r$,fa as y9,ga as I9,ia as bY,ka as K8,la as LX,ma as BX,pa as wX,qa as PX,ua as lJ,va as B3,xa as H3,ya as F3,za as HZ}from"./chunk-tjzzps6w.js";import"./chunk-g01mth5d.js";import{Ma as E5,Na as h5,Oa as g5,Ra as NZ}from"./chunk-tt4c5n1v.js";import{Ta as BY}from"./chunk-30x3mcsb.js";import{Mb as FY,Nb as F4,Zb as LY,hc as P6}from"./chunk-xyy1wbam.js";import{sc as O8}from"./chunk-zzvs471p.js";import{Cd as zY,Md as P9,Nd as h2,Rd as R9,Wd as C9,Yd as t8,ee as U8,he as a0}from"./chunk-mv64vm7f.js";import"./chunk-53fc0yrq.js";import{Le as D9,Me as w6,Ne as f9}from"./chunk-y5wngtz0.js";import{if as e9,jf as G4}from"./chunk-w33zjw8m.js";import{wf as tX}from"./chunk-nheny8xp.js";import{Af as J1,xf as N8,yf as _4}from"./chunk-ba39rhgf.js";import"./chunk-jj4ggb04.js";import{Ef as R2,Ff as L$,Gf as r1,Hf as UJ,If as o8,Jf as M9,Kf as t3,Lf as CJ,Mf as r5,Nf as s3,Of as f2,Pf as m0,Qf as _Z,Rf as B$,Sf as nX,Tf as a4,Uf as q8,Xf as s9,cg as z$}from"./chunk-4m7ewvvb.js";import"./chunk-v508x7cg.js";import"./chunk-t0gm0pn1.js";import"./chunk-1yq72zb7.js";import"./chunk-kqvzmnja.js";import{ug as yJ}from"./chunk-0mr8nexh.js";import"./chunk-50vwafn5.js";import"./chunk-w0bpde9y.js";import{Hg as H4,Jg as hX,Og as FX,Xg as OZ}from"./chunk-sst34ye1.js";import"./chunk-3kszepm6.js";import"./chunk-wcps5gjm.js";import"./chunk-vbjgcn49.js";import"./chunk-06hkf59s.js";import{xh as qJ,zh as E$}from"./chunk-wd9e2h6g.js";import"./chunk-3y2x6fb6.js";import{Mi as zZ,Ri as HX,Si as qZ}from"./chunk-2r44bj6y.js";import{Ui as h9}from"./chunk-kv458q06.js";import{Vi as g2,Wi as e8,Yi as _J}from"./chunk-5v0jcyea.js";import{bj as K$}from"./chunk-2f8d0km4.js";import"./chunk-ddvdc2p0.js";import{Aj as KZ,Dj as O1}from"./chunk-2mk914vk.js";import{Lj as t5,Mj as s5,Pj as T1}from"./chunk-j8hbddjp.js";import"./chunk-4cdk4mds.js";import{$j as x5}from"./chunk-07e9sc9n.js";import{ck as uJ}from"./chunk-rvs364rz.js";import"./chunk-vw9paban.js";import{fk as G8,zk as t9}from"./chunk-4wx5sya5.js";import{Mk as Y4}from"./chunk-eg3ms291.js";import{useMemoizedFn as Q6}from"ahooks";import{useEffect as Gz,useState as G6}from"react";import{useMemoizedFn as i0}from"ahooks";import iX from"ansi-escapes";import{Box as h1,useStdout as eK}from"ink";import{useEffect as $1,useMemo as $z,useRef as y2,useState as oX}from"react";import{useShallow as BZ}from"zustand/react/shallow";import{useStore as LZ}from"zustand";function z0($){return LZ(f2,$)}var wZ=[],v2=()=>z0(($)=>$.session.sessionId),_1=()=>z0(($)=>$.session.workspaceRoot),v8=()=>z0(($)=>$.session.messages),rJ=()=>z0(($)=>$.session.clearCount),aJ=()=>z0(($)=>$.session.isCompacting),iJ=()=>z0(($)=>$.session.tokenUsage.estimatedCostUsd),oJ=()=>z0(($)=>{let{totalInputTokens:J,cacheReadTokens:Y,cacheWriteTokens:Z}=$.session.tokenUsage;return lJ({totalInputTokens:J,cacheReadTokens:Y,cacheWriteTokens:Z}).hitRate});var V8=()=>z0(($)=>$.session.providerRecovery),nJ=()=>z0(($)=>$.session.turnActivity),tJ=()=>z0(($)=>$.session.actionStationarity),c1=()=>z0(($)=>$.session.actions),sJ=()=>z0(($)=>{let{totalTokens:J,maxContextTokens:Y}=$.session.tokenUsage;if(Y<=0)return 100;let Z=Math.max(0,100-J/Y*100);return Math.round(Z)}),eJ=()=>z0(($)=>$.app.initializationStatus),$9=()=>z0(($)=>$.app.initializationError),j8=()=>z0(($)=>$.app.activeModal),J9=()=>z0(($)=>$.app.tasks),Y9=()=>z0(($)=>$.app.modelEditorTarget),X9=()=>z0(($)=>$.app.sessionSelectorData),Z9=()=>z0(($)=>$.app.sessionHistoryViewerData),Q9=()=>z0(($)=>$.app.taskAttentionStatus),E8=()=>z0(($)=>$.app.taskAttentionUnreadKeys),G9=()=>z0(($)=>$.app.awaitingSecondCtrlC),u1=()=>z0(($)=>$.app.actions),V2=()=>z0(($)=>$.app.sideConversation),U9=()=>z0(($)=>$.app.teams),h8=()=>z0(($)=>$.app.initializationStatus==="ready"),K9=()=>z0(($)=>$.app.tasks.length>0),j2=()=>z0(($)=>$.config.config?.permissionMode||"default"),z9=()=>z0(($)=>$.config.config?.models??wZ),g8=()=>z0(($)=>{let J=$.config.config;if(!J)return;let Y=J.currentModelId;return J.models.find((X)=>X.id===Y)??J.models[0]}),m8=()=>z0(($)=>$.config.config?.currentModelId),q9=()=>z0(($)=>$.config.config?.agentTeamsEnabled===!0),D0=()=>z0(($)=>{return L$.getTheme()}),_9=()=>z0(($)=>$.config.config?.codeTheme??"default"),Z$=()=>z0(($)=>$.focus.currentFocus),O9=()=>z0(($)=>$.focus.actions),E2=()=>z0(($)=>$.command.isProcessing),N9=()=>z0(($)=>$.command.actions),p8=()=>z0(($)=>$.app.followUpQueue),W9=()=>z0(($)=>$.app.followUpQueueMutation),H9=()=>z0(($)=>$.command.recoveredSteeringCount),x8=()=>z0(($)=>$.app.reasoningEffort!=="off"),c8=()=>z0(($)=>$.app.reasoningEffort),u8=()=>z0(($)=>$.app.serviceTier),d8=()=>z0(($)=>$.app.responseVerbosity),l8=()=>z0(($)=>$.app.communicationStyle),r8=()=>z0(($)=>$.session.currentThinkingContent),F9=()=>z0(($)=>$.session.thinkingExpanded),a8=()=>z0(($)=>$.session.currentStreamingMessageId),i8=()=>z0(BZ(($)=>({lines:$.session.currentStreamingLines,tail:$.session.currentStreamingTail,lineCount:$.session.currentStreamingLineCount,version:$.session.currentStreamingVersion}))),L9=()=>z0(($)=>$.session.finalizingStreamingMessageId),B9=()=>z0(($)=>$.session.historyExpanded),w9=()=>z0(($)=>$.session.expandedMessageCount);import{randomUUID as _7}from"node:crypto";import{useMemoizedFn as Y1}from"ahooks";import{useEffect as d1,useMemo as WY,useRef as N4}from"react";function PZ($,J){try{return $.code===J.code&&$.message===J.message&&$.retryable===J.retryable&&$.resource===J.resource}catch{return!1}}class K6{options;requested=!1;waitingForIdle=!1;disposed=!1;generation=0;wakeEpoch=0;idleEpoch=0;attempt=0;recoveryStartedAt=null;scheduledToken=null;activeAttemptToken=null;activeRunController=null;retryTimer=null;deadlineTimer=null;now;scheduleCallback;setTimerCallback;clearTimerCallback;constructor($){this.options=$;this.now=$.now??Date.now,this.scheduleCallback=$.scheduleMicrotask??queueMicrotask,this.setTimerCallback=$.setTimer??setTimeout,this.clearTimerCallback=$.clearTimer??clearTimeout}request(){if(this.disposed)return;if(this.wakeEpoch++,this.requested=!0,this.waitingForIdle||this.retryTimer)return;this.scheduleIfRunnable()}notifyIdle(){if(this.disposed)return;if(this.idleEpoch++,this.retryTimer)return;this.waitingForIdle=!1,this.scheduleIfRunnable()}dispose(){if(this.disposed)return;this.disposed=!0,this.generation++,this.requested=!1,this.waitingForIdle=!1,this.scheduledToken=null,this.clearOwnedTimer("retry"),this.clearOwnedTimer("deadline"),this.activeAttemptToken=null;let $=this.activeRunController;this.activeRunController=null,$?.abort("pending-resume-coordinator-disposed"),this.resetEpisodeBudget()}scheduleIfRunnable(){if(this.disposed||!this.requested||this.scheduledToken||this.activeAttemptToken||this.retryTimer||this.waitingForIdle)return;if(!this.options.canRun()){this.waitingForIdle=!0;return}let $=this.generation,J={};this.scheduledToken=J;try{this.scheduleCallback(()=>{if(this.disposed||$!==this.generation||this.scheduledToken!==J)return;this.scheduledToken=null,this.flush($).catch((Y)=>{this.handleUnexpectedFailure(Y,$)})})}catch(Y){this.handleUnexpectedFailure(Y,$)}}async flush($){if(this.disposed||$!==this.generation||this.activeAttemptToken||!this.requested||this.retryTimer||this.waitingForIdle)return;if(!this.options.canRun()){this.waitingForIdle=!0;return}let J={},Y=new AbortController,Z=this.wakeEpoch,X=this.idleEpoch;if(this.attempt++,this.recoveryStartedAt===null)this.recoveryStartedAt=this.now(),this.installDeadlineTimer($);this.activeAttemptToken=J,this.activeRunController=Y;let Q;try{Q=await this.options.run(Y.signal)}finally{if(this.activeAttemptToken===J){if(this.activeAttemptToken=null,this.activeRunController=null,!this.disposed&&$!==this.generation)this.scheduleIfRunnable()}}if(this.disposed||$!==this.generation)return;if(Q.status==="completed"){let G=this.wakeEpoch!==Z;if(this.clearEpisode(),G)this.requested=!0,this.scheduleIfRunnable();return}if(Q.status==="deferred"){if(this.attempt--,this.attempt===0)this.clearOwnedTimer("deadline"),this.resetEpisodeBudget();if(this.requested=!0,this.idleEpoch!==X)this.waitingForIdle=!1,this.scheduleIfRunnable();else this.waitingForIdle=!0;return}this.handleFailure(Q,$)}handleFailure($,J){let Y=h2($.taskFailure),Z=this.options.sessionIdentity;if($.workKind!=="pending_input"||!$.evidence||!Z||!PZ($.taskFailure,$.evidence.taskFailure)){this.terminate("failed",this.attempt,Y);return}let X=b9({sessionIdentity:Z,failedAttempt:this.attempt,recoveryStartedAt:this.recoveryStartedAt??this.now(),now:this.now(),workStillPending:$.workStillPending,evidence:$.evidence});if(X.phase!=="retry_scheduled"){this.terminate(X.phase,this.attempt,Y);return}this.requested=!0,this.waitingForIdle=!1;let Q={},G=this.setTimerCallback(()=>{if(this.disposed||J!==this.generation||this.retryTimer?.token!==Q)return;this.retryTimer=null,this.scheduleIfRunnable()},X.delayMs);this.retryTimer={handle:G,token:Q},G.unref?.()}handleUnexpectedFailure($,J){if(this.disposed||J!==this.generation)return;this.terminate("failed",Math.max(1,this.attempt),h2($),"pending-resume-coordinator-failed")}installDeadlineTimer($){let J={},Y=this.setTimerCallback(()=>{if(this.disposed||$!==this.generation||this.deadlineTimer?.token!==J)return;this.deadlineTimer=null,this.terminate("exhausted",Math.max(1,this.attempt),P9("timeout"),"pending-resume-recovery-deadline-exceeded")},A9);this.deadlineTimer={handle:Y,token:J},Y.unref?.()}terminate($,J,Y,Z){let X=this.activeRunController;if(this.generation++,this.requested=!1,this.waitingForIdle=!1,this.scheduledToken=null,this.clearOwnedTimer("retry"),this.clearOwnedTimer("deadline"),this.resetEpisodeBudget(),Z)X?.abort(Z);try{this.options.onTerminalFailure?.({phase:$,attempt:J,taskFailure:Y})}catch{}}clearEpisode(){this.requested=!1,this.waitingForIdle=!1,this.clearOwnedTimer("retry"),this.clearOwnedTimer("deadline"),this.resetEpisodeBudget()}resetEpisodeBudget(){this.attempt=0,this.recoveryStartedAt=null}clearOwnedTimer($){let J=$==="retry"?this.retryTimer:this.deadlineTimer;if(!J)return;if($==="retry")this.retryTimer=null;else this.deadlineTimer=null;this.clearTimerCallback(J.handle)}}class Z8{options;finalized=!1;constructor($){this.options=$}get isFinalized(){return this.finalized}acceptsDeltas(){return!this.finalized&&!this.options.signal.aborted}startTurn(){this.finalized=!1}finalize(){if(!this.acceptsDeltas())return!1;return this.finalized=!0,this.commit(this.options.streamingBuffer.drainPendingBuffers()),!0}abortAndFinalize($){if(this.finalized)return $(),!1;this.finalized=!0;let J=this.options.streamingBuffer.drainPendingBuffers();return $(),this.commit(J),!0}discard(){this.finalized=!0,this.options.streamingBuffer.resetStreamingBuffers(),this.options.discardStreamingMessage(),this.options.clearThinking()}commit($){let J=this.options.getStreamingMessageId();if(J){if($.extraContent)o8(J,$.extraContent);M9(J)}this.options.finalizeStreamingMessage($.extraContent,$.extraThinking)}}function AZ($){if(!($ instanceof Error))return"未知错误";let Z=$.lastError??$;if(Z.responseBody)try{let G=JSON.parse(Z.responseBody)?.error?.message;if(G){let U=Z.statusCode?` (HTTP ${Z.statusCode})`:"";return`${G}${U}`}}catch{}let X=$.message.match(/Last error:\s*(.+)$/);if(X)return X[1];return $.message}function bZ($){if(!($ instanceof Error))return!1;return $.name==="AbortError"||$.message.includes("aborted")}function MZ($){if(!($ instanceof Error))return!1;let J=$.message;return J.includes("can only concatenate str")||J.includes("image_url")||J.includes("multimodal")||J.includes("vision")||J.includes("does not support images")}function n8($){let J=bZ($),Y=MZ($),Z;if(Y)Z="当前模型不支持图片理解功能。请切换到支持视觉能力的模型(如 Claude 4.5、GPT-5.2、Gemini 3 Pro、Qwen3-VL-Plus 等)后重试。";else Z=AZ($);return{displayMessage:Z,isAbort:J,isVisionNotSupported:Y}}import{appendFileSync as TZ,mkdirSync as RZ,writeFileSync as CZ}from"node:fs";import yZ from"node:os";import z6 from"node:path";var T9=null;function IZ(){let $=process.env.BLADE_STORAGE_ROOT||z6.join(yZ.homedir(),".blade");return z6.join($,"logs","stream-debug.log")}function SZ($){if(T9===$)return;let J=z6.dirname($);RZ(J,{recursive:!0,mode:493}),CZ($,`=== Stream Debug Log Started: ${new Date().toISOString()} ===
|
|
2
2
|
`),T9=$}function q6($,J,Y){try{let Z=IZ();SZ(Z);let X=new Date().toISOString(),Q=Y?` | ${JSON.stringify(Y)}`:"",G=`[${X}] [${$}] ${J}${Q}
|
|
3
3
|
`;TZ(Z,G)}catch{}}var Q8=O1("UI");function _6($,J){if(J.state==="requires_attention"){let Y=J.reason==="interrupted_tool_call";$.addToolMessage("Turn recovery requires attention",{toolName:"Runtime Recovery",phase:"complete",summary:Y?"An interrupted tool may have partially completed":"A completed tool may already have changed external state",detail:`${J.turnId} · inspect workspace, processes, and external state before retrying`});return}$.addToolMessage(J.state==="completed"?"Recovered completed turn":"Resuming interrupted turn",{toolName:"Runtime Recovery",phase:"complete",summary:J.state==="completed"?"The durable final response was recovered":"No tool execution was recorded before interruption",detail:J.turnId})}function S9($,J){let Y=$.streamSession??new Z8({signal:$.signal,streamingBuffer:$.streamingBuffer,getStreamingMessageId:$.getStreamingMessageId,finalizeStreamingMessage:$.sessionActions.finalizeStreamingMessage,discardStreamingMessage:$.sessionActions.discardStreamingMessage,clearThinking:()=>$.sessionActions.setCurrentThinkingContent(null)}),Z=(X)=>{for(let Q of X){if((Q.origin??"user")!=="user")continue;let G=$.commandActions.takeFollowUpPresentation(Q.id);if(G){$.sessionActions.addUserMessage(G.displayText);continue}if(!Q.recovered||Q.persisted)continue;let U=typeof Q.content==="string"?Q.content:Q.content.map((z)=>z.type==="text"?z.text:"[Image]").join(`
|
|
4
4
|
`);$.sessionActions.addUserMessage(U)}};return(X)=>{switch(X.kind){case"content_delta":if(X.delta.length>0)J.outputStarted=!0;if(!Y.acceptsDeltas())break;J.contentDeltaCount++,J.contentDeltaTotalLen+=X.delta.length,q6("loopEventHandler","onContentDelta",{callCount:J.contentDeltaCount,deltaLen:X.delta.length,totalLen:J.contentDeltaTotalLen}),$.streamingBuffer.batchAppendContent(X.delta);break;case"thinking_delta":if(X.delta.length>0)J.outputStarted=!0;if(!Y.acceptsDeltas())break;if($.thinkingModeEnabled)$.streamingBuffer.batchAppendThinking(X.delta);break;case"stream_end":{$.sessionActions.setProviderCircuit(null),$.sessionActions.setProviderRetry(null),$.sessionActions.setProviderStall(null),Q8.debug("[loopEventHandler] stream_end",{contentDeltaCount:J.contentDeltaCount,contentDeltaTotalLen:J.contentDeltaTotalLen,streamFinalized:Y.isFinalized,signalAborted:$.signal.aborted}),q6("loopEventHandler","onStreamEnd",{contentDeltaCallCount:J.contentDeltaCount,contentDeltaTotalLen:J.contentDeltaTotalLen,streamFinalized:Y.isFinalized,signalAborted:$.signal.aborted}),Y.finalize();break}case"model_fallback":$.sessionActions.setProviderAdmission(null),$.sessionActions.setProviderCircuit(null),$.sessionActions.setProviderRetry(null),$.sessionActions.setProviderStall(null),Y.discard();break;case"provider_admission":{let{kind:Q,...G}=X;$.sessionActions.setProviderAdmission(X.phase==="queued"?G:null);break}case"provider_circuit":{let{kind:Q,...G}=X;$.sessionActions.setProviderCircuit(X.phase==="closed"?null:G);break}case"provider_retry":{let{kind:Q,...G}=X;$.sessionActions.setProviderRetry(X.phase==="recovered"?null:G);break}case"provider_stall":{let{kind:Q,...G}=X;$.sessionActions.setProviderStall(X.phase==="detected"?G:null);break}case"provider_recovery":$.sessionActions.setProviderRecovery(X.recovery);break;case"action_stationarity":{let{kind:Q,...G}=X;$.sessionActions.setActionStationarity(X.phase==="recovered"?null:G);break}case"turn_recovery":{_6($.sessionActions,X.assessment);break}case"tool_start":{J.toolExecutionStarted=!0;let Q=X.toolCall;if(!("function"in Q))break;if(Q.function.name===t8)break;if(Q8.debug("[loopEventHandler] tool_start",{toolName:Q.function.name,toolKind:X.toolKind}),["TaskCreate","TaskUpdate","TaskList"].includes(Q.function.name))break;try{let G=JSON.parse(Q.function.arguments),U=y9(Q.function.name,G);$.sessionActions.addToolMessage(U,{toolCallId:Q.id,toolName:Q.function.name,phase:"start",summary:U,params:G})}catch(G){Q8.error("[loopEventHandler] onToolStart error:",G)}break}case"tool_progress":{J.toolExecutionStarted=!0;let Q=X.toolCall;if(!("function"in Q))break;if(Q.function.name===t8)break;let G=X.update.total!==void 0?` ${Math.max(0,Math.min(100,Math.round((X.update.progress??0)/X.update.total*100)))}%`:"",U=`${Q.function.name}${G}: ${X.update.message}`;$.sessionActions.addToolMessage(U,{toolCallId:Q.id,toolName:Q.function.name,phase:"progress",summary:U,...X.update.admission?{admission:X.update.admission}:{}});break}case"tool_result":{J.toolExecutionStarted=!0;let Q=X.toolCall;if(!("function"in Q))break;if(Q.function.name===t8)break;Q8.debug("[loopEventHandler] tool_result",{toolName:Q.function.name,success:X.result.success});let G=C9(I9(Q.function.name,X.result),R9);$.sessionActions.addToolMessage(G.summary,{toolCallId:Q.id,toolName:Q.function.name,phase:"complete",summary:G.summary,detail:G.detail});break}case"structured_output":J.outputStarted=!0,$.sessionActions.replaceLastAssistantMessage(JSON.stringify(X.output,null,2));break;case"token_usage":$.sessionActions.updateTokenUsage(X.usage);break;case"compaction":if($.sessionActions.setCompacting(X.phase==="start"),X.phase==="end"){if($.sessionActions.resetContextUsage(),X.outcome!=="failed")J.compactionCount=(J.compactionCount??0)+1;if(X.memory?.outcome==="written"){let Q=`Saved ${X.memory.entries} project memories`;$.sessionActions.addToolMessage(Q,{toolName:"Project Memory",phase:"complete",summary:Q})}}break;case"turn_start":Q8.debug("[loopEventHandler] turn_start",{turn:X.turn,maxTurns:X.maxTurns}),$.sessionActions.updateTokenUsage({turnCount:X.turn}),$.sessionActions.setProviderCircuit(null),$.sessionActions.setProviderRetry(null),$.sessionActions.setProviderStall(null),Y.startTurn();break;case"task_update":$.appActions.setTasks(X.tasks);break;case"goal_frontier_updated":$.appActions.setTasks(X.tasks);break;case"mcp_catalog_changed":{let Q=`MCP catalog r${X.revision}: +${X.added.length} -${X.removed.length} ~${X.updated.length}`;$.sessionActions.addToolMessage(Q,{toolName:"MCP Catalog",phase:"complete",summary:Q,detail:[X.added.length>0?`Added: ${X.added.join(", ")}`:"",X.removed.length>0?`Removed: ${X.removed.join(", ")}`:"",X.updated.length>0?`Updated: ${X.updated.join(", ")}`:""].filter(Boolean).join(`
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{wc as U8}from"./chunk-zzvs471p.js";import{$d as n1,Ac as N2,Bc as i1,Dc as z$,Ed as y2,Fd as q8,Gd as G8,Hd as Q6,Id as t1,Jd as L8,Kd as F8,Ld as c1,Pd as lJ,Yd as u0,_d as S6,ae as T6,he as W1,td as _2,vd as A2,wd as b2,xc as U$,xd as B6,yd as D6,zc as w$}from"./chunk-99ydmdy1.js";import{me as w8}from"./chunk-53fc0yrq.js";import{Ee as E0,pe as q0,se as V2,te as C$}from"./chunk-y5wngtz0.js";import{dg as C2}from"./chunk-t0gm0pn1.js";import{eg as B8,fg as r0,gg as X8,hg as uJ,jg as d1,kg as E6,lg as mJ,mg as dJ,pg as cJ}from"./chunk-1yq72zb7.js";import{bh as Y$,ch as n0,fh as D8}from"./chunk-3kszepm6.js";import{kh as n2,oh as J2}from"./chunk-wcps5gjm.js";import{zh as E$}from"./chunk-n0njjq63.js";import{Ui as R$}from"./chunk-kv458q06.js";import{bj as j0}from"./chunk-2f8d0km4.js";import{Dj as T0}from"./chunk-2mk914vk.js";import{Xj as P2}from"./chunk-g5fa6sd6.js";import{Bk as GJ,Ck as s1,Ek as L2,Jk as F2,Kk as O2,fk as G2,uk as B2,vk as D2,yk as K1}from"./chunk-4wx5sya5.js";import{Mk as mZ}from"./chunk-eg3ms291.js";function y$($){return $.role==="system"&&Array.isArray($.content)}function b$($){if($.role!=="system"||!$.metadata||Array.isArray($.metadata))return!1;return typeof $.metadata==="object"&&$.metadata.contextualProjectRules===!0}class I1{systemMessages;_contextualSystemMessages;_history;_pending=[];_contextRevision=0;context;constructor($,Z){this.context=$;let J=$.messages.find(y$);if(this._contextualSystemMessages=$.messages.filter(b$),J)this.systemMessages=[J,...this._contextualSystemMessages];else if(Z)this.systemMessages=[{role:"system",content:[{type:"text",text:Z,providerOptions:{anthropic:{cacheControl:{type:"ephemeral"}}}}]},...this._contextualSystemMessages];else this.systemMessages=[...this._contextualSystemMessages];this._history=$.messages.filter((W)=>!y$(W)&&!b$(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(!b$($))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($,Z){if($==="system")throw Error("Cannot append system control message via appendControl. Use constructor for root system prompt.");this._pending.push({...Z,metadata:{...Z.metadata&&typeof Z.metadata==="object"&&!Array.isArray(Z.metadata)?Z.metadata:{},...E0}})}appendDurableControl($){if(!$.id||$.role!=="user")throw Error("Durable control messages require a user role and identity");if(this._history.some((Z)=>Z.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((Z)=>!y$(Z)&&!b$(Z)),this._contextRevision++}restoreDurableHistory($){this._contextualSystemMessages=$.filter(b$),this._history=$.filter((Z)=>!y$(Z)&&!b$(Z)),this._pending=[],this.syncContextualSystemMessages(),this._contextRevision++}removeMessages($){let Z=[this._history.length,this._pending.length,this._contextualSystemMessages.length];if(this._history=this._history.filter((J)=>!$(J)),this._pending=this._pending.filter((J)=>!$(J)),this._contextualSystemMessages=this._contextualSystemMessages.filter((J)=>!$(J)),this.syncContextualSystemMessages(),this._history.length!==Z[0]||this._pending.length!==Z[1]||this._contextualSystemMessages.length!==Z[2])this._contextRevision++}writeback(){this.commitPending(),this.context.messages=[...this._contextualSystemMessages,...this._history]}get hasSystemPrompt(){return this.systemMessages.length>0}}function s6($){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 t6($){return{budget:$.budget,usage:0,consecutiveContinuations:0,lastOutputDelta:0,isSubagent:$.isSubagent??!1}}function e6($,Z,J){return{...$,usage:$.usage+Z,lastOutputDelta:Z,consecutiveContinuations:J?$.consecutiveContinuations+1:0}}import V$ from"node:path";var R8=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"]),M8=/^(LD_.+|DYLD_.+|PATH)$/,$J=/^([A-Za-z_][A-Za-z0-9_]*)=([\w./:@-]*)$/;function t$($){let Z=$;while(!0){let J=Z.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!J)break;let W=J[1],Y=J[2],K=W.match($J);if(!K)break;let X=K[1];if(!R8.has(X))break;Z=Y}return Z}function l5($){let Z=$;while(!0){let J=Z.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!J)break;let W=J[1],Y=J[2],K=W.match($J);if(!K)break;let X=K[1];if(M8.test(X))break;Z=Y}return Z}var k8=[/^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 RZ($){let Z=$,J=!0;while(J){J=!1;for(let W of k8){let Y=Z.match(W);if(Y){Z=Z.slice(Y[0].length),J=!0;break}}if(Z.startsWith("-- "))Z=Z.slice(3),J=!0}return Z}function e$($){let Z=[],J="",W=!1,Y=!1,K=!1;for(let X=0;X<$.length;X++){let Q=$[X];if(K){J+=Q,K=!1;continue}if(Q==="\\"&&!W){J+=Q,K=!0;continue}if(Q==="'"&&!Y){W=!W,J+=Q;continue}if(Q==='"'&&!W){Y=!Y,J+=Q;continue}if(W||Y){J+=Q;continue}if(Q==="|"){if(X+1<$.length&&$[X+1]==="|"){if(J.trim())Z.push(J.trim());J="",X++;continue}return null}if(Q===">"||Q==="<")return null;if(Q==="&"&&X+1<$.length&&$[X+1]==="&"){if(J.trim())Z.push(J.trim());J="",X++;continue}if(Q==="&")return null;if(Q===";"){if(J.trim())Z.push(J.trim());J="";continue}J+=Q}if(J.trim())Z.push(J.trim());return Z.length>0?Z:null}function ZJ($){let Z=!1,J=!1,W=!1;for(let Y=0;Y<$.length;Y++){let K=$[Y];if(W){W=!1;continue}if(K==="\\"&&!Z){W=!0;continue}if(K==="'"&&!J){Z=!Z;continue}if(K==='"'&&!Z){J=!J;continue}if(Z)continue;if(K==="$"){let X=$[Y+1];if(X&&/[A-Za-z_@*#?!$0-9({]/.test(X))return!0}if(K==="`")return!0;if(J)continue;if(K==="|")return!0;if(K===">"||K==="<")return!0;if(K==="{"){let X=$.slice(Y);if(/^\{[^}]*,[^}]*\}/.test(X)||/^\{[^}]*\.\.[^}]*\}/.test(X))return!0}}return!1}function H$($){let Z=[],J="",W=!1,Y=!1,K=!1;for(let X=0;X<$.length;X++){let Q=$[X];if(K){J+=Q,K=!1;continue}if(Q==="\\"&&!W){if(K=!0,Y){let H=$[X+1];if(H&&'$`"\\'.includes(H))continue;J+=Q,K=!1}continue}if(Q==="'"&&!Y){W=!W;continue}if(Q==='"'&&!W){Y=!Y;continue}if(!W&&!Y&&/[ \t]/.test(Q)){if(J)Z.push(J),J="";continue}J+=Q}if(J)Z.push(J);return Z}var x8=new Set(["npm","pnpm","yarn","bun"]),JJ=new Set(["biome","eslint","jest","mypy","pyright","pytest","ruff","tsc","vitest"]),I8=new Set(["-u","--fix","--update","--update-snapshot","--updateSnapshot","--watch","--watchAll","--write"]),h8=/[ \t]*;[ \t]*echo[ \t]+"[A-Za-z0-9 _:=.-]*(?:\$\{PIPESTATUS\[0\]\}|\$\?)[A-Za-z0-9 _:=.-]*"[ \t]*$/;function v8($){return $!==void 0&&/^(?:test|lint|build|type-?check)(?::[\w.-]+)*$/i.test($)}function WJ($){return $.replace(/\s+2>&1\s*$/,"").trim()}function C8($,Z,J){if(!J||Z.length!==2)return;let W=/^(.+?)[ \t]+&&[ \t]+([\s\S]+)$/.exec($);if(!W)return;let Y=H$(W[1]??"");if(Y.length!==2||Y[0]!=="cd")return;let K=Y[1];if(!K||K==="-")return;let X=V$.isAbsolute(K)?V$.resolve(K):V$.resolve(J,K);if(!z$.isWithinWorkspace(X,J))return;return W[2]?.trim()||void 0}function g8($){let Z=[],J=!1,W=!1,Y=!1;for(let K=0;K<$.length;K++){let X=$[K];if(Y){Y=!1;continue}if(X==="\\"&&!J){Y=!0;continue}if(X==="'"&&!W){J=!J;continue}if(X==='"'&&!J){W=!W;continue}if(X!=="|"||J||W)continue;if($[K+1]==="|")return;Z.push(K)}return Z}function p8($){let Z=H$($),[J,W,Y]=Z;if(J!=="head"&&J!=="tail")return!1;if(Z.length===1)return!0;let K=(X)=>X!==void 0&&/^[1-9]\d{0,4}$/.test(X);if(Z.length===2)return W?.startsWith("--lines=")&&K(W.slice(8))||W?.startsWith("-")&&K(W.slice(1));return Z.length===3&&(W==="-n"||W==="--lines")&&K(Y)}function u8($){let Z=WJ($.replace(h8,"").trim()),J=g8(Z);if(!J)return;if(J.length===0)return YJ(Z);if(J.length!==1)return;let W=J[0];if(W===void 0)return;let Y=WJ(Z.slice(0,W).trim()),K=Z.slice(W+1).trim();if(!Y||!p8(K))return;return YJ(Y)}function YJ($){let J=e$($)?.at(-1);if(!J)return $;let W=H$(J),[Y,K]=W;if(!(Y==="vitest"||(Y==="npx"||Y==="bunx")&&K==="vitest")||W.some((Q)=>Q==="--configLoader"||Q.startsWith("--configLoader=")))return $;return`${$} --configLoader runner`}function f$($,Z){let J=u8($);if(!J)return!1;let W=t$(J),Y=e$(W);if(!Y||ZJ(W)||/[\r\n]/.test(W))return!1;let K=Y.length===1?Y[0]:C8(W,Y,Z);if(!K)return!1;let X=H$(K);if(X.length===0||X.some((z)=>[...I8].some((B)=>z===B||z.startsWith(`${B}=`))))return!1;let[Q,H,V]=X;if(x8.has(Q??""))return v8(H==="run"?V:H)||H==="--test";if((Q==="npx"||Q==="bunx")&&JJ.has(H??""))return!0;if(JJ.has(Q??""))return!0;if(Q==="node"&&H==="--test")return!0;if(Q==="go"&&["build","test","vet"].includes(H??""))return!0;return Q==="cargo"&&["build","check","clippy","test"].includes(H??"")}function a5($,Z){if($===void 0)return!0;if(typeof $!=="string"||$.split(/[\\/]/).includes(".."))return!1;if(!Z)return!V$.isAbsolute($);let J=V$.isAbsolute($)?V$.resolve($):V$.resolve(Z,$);return z$.isWithinWorkspace(J,Z)}var MZ=T0("Agent"),m8=3;function kZ($,Z,J){if($!=="length")return{action:"none"};if(Z>=m8)return{action:"truncated"};if(s6(J)==="stop")return MZ.info("[Loop] Token budget: diminishing returns detected, skipping recovery"),{action:"budget_stop"};return{action:"recover"}}var d8=[/:\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],c8=/```[\s\S]{50,}```/,KJ="请执行你提到的操作,不要只是描述。使用 Edit/Write/ApplyPatch/Bash 工具来实际修改文件。",l8=2;function xZ($,Z,J=!0){if(!$||Z>=l8)return{action:"none"};if(!J&&c8.test($))return{action:"retry",prompt:KJ};let W=$.slice(-200),Y=W.match(/```/g);if(Y&&Y.length%2!==0)return{action:"none"};if(d8.some((X)=>X.test(W)))return{action:"retry",prompt:KJ};return{action:"none"}}var h1=2,i8="The model returned tool-call JSON as text instead of completing the requested tool workflow.",r8="The previous response contained tool-call JSON as ordinary text. It did not execute a tool. If the requested operation is still needed, use the native tool-call interface with an available tool. If it already succeeded, use the recorded result to answer instead of repeating the operation. Do not return another tool-call JSON envelope as your final answer.";function IZ($,Z,J,W){if(!$||$.length>65536||J.length===0)return{action:"none"};let Y=Z.replace(/```[\s\S]*?(?:```|$)/g,"").replace(/^\s*>.*$/gm,"");if(/\b(?:example|schema|serialize|serialization|quote|print|illustrate|verbatim)\b|示例|样例|序列化|引用原文/i.test(Y)||/\b(?:explain|show|return|output)\b[^.!?\n]{0,80}\b(?:json|tool.calls?)\b|(?:解释|展示|输出|返回)[^。!?\n]{0,40}(?:JSON|工具调用格式)/i.test(Y)||/\b(?:do not|don't|never)\s+(?:use|call|invoke|execute)\s+(?:any\s+)?tools?\b|不要(?:使用|调用|执行)(?:任何)?工具/i.test(Y))return{action:"none"};let K;try{K=JSON.parse($)}catch{return{action:"none"}}if(!K||typeof K!=="object"||Array.isArray(K)||Object.keys(K).length!==1||!("tool_calls"in K)||!Array.isArray(K.tool_calls)||K.tool_calls.length===0||K.tool_calls.length>32)return{action:"none"};let X=new Set;for(let Q of K.tool_calls){if(!Q||typeof Q!=="object"||Array.isArray(Q))return{action:"none"};let H="function"in Q;if(Object.keys(Q).some((L)=>!["id","type",...H?["function"]:["name","arguments"]].includes(L)))return{action:"none"};if("type"in Q&&Q.type!=="function")return{action:"none"};let V=H?Q.function:Q;if(!V||typeof V!=="object"||Array.isArray(V)||!("name"in V)||typeof V.name!=="string"||!("arguments"in V))return{action:"none"};if(H&&Object.keys(V).some((L)=>L!=="name"&&L!=="arguments"))return{action:"none"};if(!J.includes(V.name))return{action:"none"};let z=V.arguments;if(typeof z!=="string"&&(!z||typeof z!=="object"||Array.isArray(z)))return{action:"none"};let B=V.name.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),j=new RegExp(`(?:^|[.!?。!?;;\\n])\\s*(?:please\\s+)?(?:call|invoke|execute|run|use)\\s+(?:the\\s+)?(?:tool\\s+)?[\`"']?${B}(?![\\w:-])|(?:^|[。!?;\\n])\\s*(?:请)?(?:调用|使用|执行)\\s*(?:工具\\s*)?[\`"']?${B}(?![\\w:-])`,"i"),w=new RegExp(`(?:do not|don't|never)\\s+(?:call|invoke|execute|run|use)\\s+(?:the\\s+)?(?:tool\\s+)?[\`"']?${B}(?![\\w:-])|(?:不要|禁止)(?:调用|使用|执行)\\s*(?:工具\\s*)?[\`"']?${B}(?![\\w:-])`,"i");if(!j.test(Y)||w.test(Y))return{action:"none"};X.add(V.name)}return W<h1?{action:"retry",prompt:r8,...X.size===1?{toolName:[...X][0]}:{}}:{action:"fail",message:i8}}var n8=[/\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}(?:测试|单测|集成测试|检查|构建)/],XJ={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},o8={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},a8="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.",s8="Required verification did not run successfully before the retry limit.",t8=3;function HJ($,Z,J,W){if(!J.success)return;if(["Edit","Write","ApplyPatch","NotebookEdit"].includes(Z)){$.clear();return}if(Z==="Bash"&&typeof J.metadata?.command==="string"&&J.metadata.exit_code===0&&f$(J.metadata.command,W)){$.add(J.metadata.command);return}if(!["Task","TaskOutput"].includes(Z))return;let Y=J.metadata?.verificationCommands;if(!Array.isArray(Y))return;for(let K of Y)if(typeof K==="string"&&f$(K,W))$.add(K)}function hZ($,Z,J){if(!$||!n8.some((H)=>H.test($)))return{action:"none"};let W=Object.keys(XJ).filter((H)=>XJ[H].test($)),Y=[...Z],K=W.filter((H)=>!Y.some((V)=>o8[H].test(V)));if(W.length>0?K.length===0:Y.some((H)=>f$(H)))return{action:"none"};if(J>=t8)return{action:"fail",message:s8};let Q=W.length>1&&K.length>0?` Missing successful verification categories: ${K.join(", ")}.`:"";return{action:"retry",prompt:`${a8}${Q}`}}var e8=[/\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|子代理|子智能体)/],VJ=[/\b(?:do not|don't|never)\s+(?:delegate|call|use|invoke)\b/i,/(?:不要|禁止|无需)(?:委派|调用|使用).{0,20}(?:Task|子代理|子智能体)?/];function zJ($){return typeof $==="string"&&VJ.some((Z)=>Z.test($))}var $9=[/\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|子代理)/],Z9=[/\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 J9($){if(typeof $!=="string")return;if(Z9.some((Z)=>Z.test($)))return"multiple-allowed";return $9.some((Z)=>Z.test($))?"required":void 0}function Z1($){for(let Z of $){let J=J9(Z);if(J!==void 0)return J==="required"}return!1}var W9="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.",Y9="Required delegation did not complete before the retry limit.",K9=3;function jJ($,Z,J){let W=(typeof $==="string"?[$]:$??[]).map((X)=>X.trim()).filter(Boolean),Y=Z1(W),K=!1;if(!Y)for(let X of W){if(VJ.some((Q)=>Q.test(X)))break;if(e8.some((Q)=>Q.test(X))){K=!0;break}}if(W.length===0||!Y&&!K||Z.has("Task"))return{action:"none"};if(J>=K9)return{action:"fail",message:Y9};return{action:"retry",prompt:W9}}var X9=[/\b(?:use|create|enter|start|work\s+(?:in|inside))\b.{0,60}\bworktree\b/i,/(?:使用|创建|进入).{0,30}(?:worktree|工作树)/i],Q9=[/\b(?:exit|leave)\b.{0,40}\bworktree\b/i,/\bworktree\b.{0,60}\b(?:action\s+)?(?:keep|remove)\b/i,/(?:退出|离开).{0,30}(?:worktree|工作树)/i],H9=[/\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 BJ($){return H9.reduce((Z,J)=>Z.replace(J," "),$)}function v1($){if(typeof $!=="string")return!1;let Z=BJ($);return X9.some((J)=>J.test(Z))}var V9="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.",z9="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.",j9="Required worktree lifecycle did not complete before the retry limit.",B9=3;function DJ($,Z,J){if(!$)return{action:"none"};let W=BJ($);if(!v1(W))return{action:"none"};let Y=Q9.some((X)=>X.test(W));if(Z.has("TaskWorktree"))return{action:"none"};let K=!Z.has("EnterWorktree")?"EnterWorktree":Y&&!Z.has("ExitWorktree")?"ExitWorktree":void 0;if(!K)return{action:"none"};if(J>=B9)return{action:"fail",message:j9};return{action:"retry",tool:K,prompt:K==="EnterWorktree"?V9:z9}}var QJ=30000;async function vZ($){try{let J=E$.getInstance().executeStopHooks({projectDir:$.workspaceRoot??j0(),sessionId:$.sessionId,permissionMode:$.permissionMode,reason:$.reason,abortSignal:$.abortSignal}),W,Y=new Promise((K)=>{W=setTimeout(()=>K("timeout"),QJ)});try{let K=await Promise.race([J,Y]);if(K==="timeout")return MZ.warn(`[Loop] Stop hook 超时 (${QJ}ms),按 shouldStop: true 处理`),{action:"stop"};let X=K;if(!X.shouldStop)return{action:"continue",reason:X.continueReason};return{action:"stop"}}finally{clearTimeout(W)}}catch(Z){return MZ.warn("[Loop] Stop hook execution failed:",Z),{action:"stop"}}}async function D9($,Z){let J;while(!(J=await $.next()).done)if(Z)await Z(J.value);return J.value}var w9=[/<system-reminder>[\s\S]*?<\/system-reminder>/gi,/<file[^>]*>[\s\S]*?<\/file>/gi,/<hooks_context>[\s\S]*?<\/hooks_context>/gi,/<[^>]+>/g];function U9($){if(typeof $==="string")return $;if(Array.isArray($))return $.map((Z)=>{if(typeof Z==="string")return Z;if(Z&&typeof Z==="object"&&"text"in Z){let J=Z.text;return typeof J==="string"?J:""}return""}).join(" ");return""}function q9($){let Z=$;for(let H of w9)Z=Z.replace(H," ");Z=Z.replace(/^\s*\/[a-zA-Z][\w-]*\s+/,"");let J=Z.replace(/\s+/g," ").trim();if(!J)return"";let W=J.match(/^(.+?)(?:[.!?]\s|[。!?](?=\S|$)|$)/),Y=W&&W[1].length>=6?W[1]:J;if(Y=Y.trim().replace(/[\s.。!!??,,;;::-]+$/,""),Y.length<=60)return Y;let K=Y.slice(0,60),X=K.lastIndexOf(" ");return`${(X>36?K.slice(0,X):K).trimEnd()}…`}function wJ($){return q9(U9($))}import{EventEmitter as G9}from"events";import UJ from"node:path";function CZ($){if(GJ($.sessionId),!UJ.isAbsolute($.projectPath))throw Error("projectPath must be absolute");return{sessionId:$.sessionId,projectPath:UJ.resolve($.projectPath)}}function qJ($){let Z=CZ($);return JSON.stringify([Z.projectPath,Z.sessionId])}function V3($,Z){return qJ($)===qJ(Z)}class S$ extends G9{static instance;constructor(){super();this.setMaxListeners(100)}static getInstance(){if(!S$.instance)S$.instance=new S$;return S$.instance}publish($,Z,J,W){let Y=CZ($);this.emit("event",{sessionId:Y.sessionId,projectPath:Y.projectPath,type:Z,...W!==void 0?{seq:W}:{},properties:J})}subscribe($){return this.on("event",$),()=>this.off("event",$)}}var J1=S$.getInstance();var $$=T0("Agent"),C1=new Set;async function L9($,Z){let J=$.sessionId;if(!J||$.subagentInfo)return;if(C1.has(J))return;if(C1.size>=5000)C1.clear();C1.add(J);try{let W=$.workspaceRoot,Y=await W1.findSessionMetadata(J,W);if(!Y)return;if(Y.title&&Y.title.trim())return;let K=wJ(Z);if(!K)return;await W1.updateSessionMetadata(J,Y.projectPath,{title:K}),J1.publish({sessionId:J,projectPath:Y.projectPath},"session.updated",{title:K})}catch(W){$$.debug?.("[Loop] 自动生成会话标题失败:",W)}}var gZ=`<turn_aborted>
|
|
1
|
+
import{wc as U8}from"./chunk-zzvs471p.js";import{$d as n1,Ac as N2,Bc as i1,Dc as z$,Ed as y2,Fd as q8,Gd as G8,Hd as Q6,Id as t1,Jd as L8,Kd as F8,Ld as c1,Pd as lJ,Yd as u0,_d as S6,ae as T6,he as W1,td as _2,vd as A2,wd as b2,xc as U$,xd as B6,yd as D6,zc as w$}from"./chunk-mv64vm7f.js";import{me as w8}from"./chunk-53fc0yrq.js";import{Ee as E0,pe as q0,se as V2,te as C$}from"./chunk-y5wngtz0.js";import{dg as C2}from"./chunk-t0gm0pn1.js";import{eg as B8,fg as r0,gg as X8,hg as uJ,jg as d1,kg as E6,lg as mJ,mg as dJ,pg as cJ}from"./chunk-1yq72zb7.js";import{bh as Y$,ch as n0,fh as D8}from"./chunk-3kszepm6.js";import{kh as n2,oh as J2}from"./chunk-wcps5gjm.js";import{zh as E$}from"./chunk-wd9e2h6g.js";import{Ui as R$}from"./chunk-kv458q06.js";import{bj as j0}from"./chunk-2f8d0km4.js";import{Dj as T0}from"./chunk-2mk914vk.js";import{Xj as P2}from"./chunk-07e9sc9n.js";import{Bk as GJ,Ck as s1,Ek as L2,Jk as F2,Kk as O2,fk as G2,uk as B2,vk as D2,yk as K1}from"./chunk-4wx5sya5.js";import{Mk as mZ}from"./chunk-eg3ms291.js";function y$($){return $.role==="system"&&Array.isArray($.content)}function b$($){if($.role!=="system"||!$.metadata||Array.isArray($.metadata))return!1;return typeof $.metadata==="object"&&$.metadata.contextualProjectRules===!0}class I1{systemMessages;_contextualSystemMessages;_history;_pending=[];_contextRevision=0;context;constructor($,Z){this.context=$;let J=$.messages.find(y$);if(this._contextualSystemMessages=$.messages.filter(b$),J)this.systemMessages=[J,...this._contextualSystemMessages];else if(Z)this.systemMessages=[{role:"system",content:[{type:"text",text:Z,providerOptions:{anthropic:{cacheControl:{type:"ephemeral"}}}}]},...this._contextualSystemMessages];else this.systemMessages=[...this._contextualSystemMessages];this._history=$.messages.filter((W)=>!y$(W)&&!b$(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(!b$($))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($,Z){if($==="system")throw Error("Cannot append system control message via appendControl. Use constructor for root system prompt.");this._pending.push({...Z,metadata:{...Z.metadata&&typeof Z.metadata==="object"&&!Array.isArray(Z.metadata)?Z.metadata:{},...E0}})}appendDurableControl($){if(!$.id||$.role!=="user")throw Error("Durable control messages require a user role and identity");if(this._history.some((Z)=>Z.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((Z)=>!y$(Z)&&!b$(Z)),this._contextRevision++}restoreDurableHistory($){this._contextualSystemMessages=$.filter(b$),this._history=$.filter((Z)=>!y$(Z)&&!b$(Z)),this._pending=[],this.syncContextualSystemMessages(),this._contextRevision++}removeMessages($){let Z=[this._history.length,this._pending.length,this._contextualSystemMessages.length];if(this._history=this._history.filter((J)=>!$(J)),this._pending=this._pending.filter((J)=>!$(J)),this._contextualSystemMessages=this._contextualSystemMessages.filter((J)=>!$(J)),this.syncContextualSystemMessages(),this._history.length!==Z[0]||this._pending.length!==Z[1]||this._contextualSystemMessages.length!==Z[2])this._contextRevision++}writeback(){this.commitPending(),this.context.messages=[...this._contextualSystemMessages,...this._history]}get hasSystemPrompt(){return this.systemMessages.length>0}}function s6($){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 t6($){return{budget:$.budget,usage:0,consecutiveContinuations:0,lastOutputDelta:0,isSubagent:$.isSubagent??!1}}function e6($,Z,J){return{...$,usage:$.usage+Z,lastOutputDelta:Z,consecutiveContinuations:J?$.consecutiveContinuations+1:0}}import V$ from"node:path";var R8=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"]),M8=/^(LD_.+|DYLD_.+|PATH)$/,$J=/^([A-Za-z_][A-Za-z0-9_]*)=([\w./:@-]*)$/;function t$($){let Z=$;while(!0){let J=Z.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!J)break;let W=J[1],Y=J[2],K=W.match($J);if(!K)break;let X=K[1];if(!R8.has(X))break;Z=Y}return Z}function l5($){let Z=$;while(!0){let J=Z.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!J)break;let W=J[1],Y=J[2],K=W.match($J);if(!K)break;let X=K[1];if(M8.test(X))break;Z=Y}return Z}var k8=[/^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 RZ($){let Z=$,J=!0;while(J){J=!1;for(let W of k8){let Y=Z.match(W);if(Y){Z=Z.slice(Y[0].length),J=!0;break}}if(Z.startsWith("-- "))Z=Z.slice(3),J=!0}return Z}function e$($){let Z=[],J="",W=!1,Y=!1,K=!1;for(let X=0;X<$.length;X++){let Q=$[X];if(K){J+=Q,K=!1;continue}if(Q==="\\"&&!W){J+=Q,K=!0;continue}if(Q==="'"&&!Y){W=!W,J+=Q;continue}if(Q==='"'&&!W){Y=!Y,J+=Q;continue}if(W||Y){J+=Q;continue}if(Q==="|"){if(X+1<$.length&&$[X+1]==="|"){if(J.trim())Z.push(J.trim());J="",X++;continue}return null}if(Q===">"||Q==="<")return null;if(Q==="&"&&X+1<$.length&&$[X+1]==="&"){if(J.trim())Z.push(J.trim());J="",X++;continue}if(Q==="&")return null;if(Q===";"){if(J.trim())Z.push(J.trim());J="";continue}J+=Q}if(J.trim())Z.push(J.trim());return Z.length>0?Z:null}function ZJ($){let Z=!1,J=!1,W=!1;for(let Y=0;Y<$.length;Y++){let K=$[Y];if(W){W=!1;continue}if(K==="\\"&&!Z){W=!0;continue}if(K==="'"&&!J){Z=!Z;continue}if(K==='"'&&!Z){J=!J;continue}if(Z)continue;if(K==="$"){let X=$[Y+1];if(X&&/[A-Za-z_@*#?!$0-9({]/.test(X))return!0}if(K==="`")return!0;if(J)continue;if(K==="|")return!0;if(K===">"||K==="<")return!0;if(K==="{"){let X=$.slice(Y);if(/^\{[^}]*,[^}]*\}/.test(X)||/^\{[^}]*\.\.[^}]*\}/.test(X))return!0}}return!1}function H$($){let Z=[],J="",W=!1,Y=!1,K=!1;for(let X=0;X<$.length;X++){let Q=$[X];if(K){J+=Q,K=!1;continue}if(Q==="\\"&&!W){if(K=!0,Y){let H=$[X+1];if(H&&'$`"\\'.includes(H))continue;J+=Q,K=!1}continue}if(Q==="'"&&!Y){W=!W;continue}if(Q==='"'&&!W){Y=!Y;continue}if(!W&&!Y&&/[ \t]/.test(Q)){if(J)Z.push(J),J="";continue}J+=Q}if(J)Z.push(J);return Z}var x8=new Set(["npm","pnpm","yarn","bun"]),JJ=new Set(["biome","eslint","jest","mypy","pyright","pytest","ruff","tsc","vitest"]),I8=new Set(["-u","--fix","--update","--update-snapshot","--updateSnapshot","--watch","--watchAll","--write"]),h8=/[ \t]*;[ \t]*echo[ \t]+"[A-Za-z0-9 _:=.-]*(?:\$\{PIPESTATUS\[0\]\}|\$\?)[A-Za-z0-9 _:=.-]*"[ \t]*$/;function v8($){return $!==void 0&&/^(?:test|lint|build|type-?check)(?::[\w.-]+)*$/i.test($)}function WJ($){return $.replace(/\s+2>&1\s*$/,"").trim()}function C8($,Z,J){if(!J||Z.length!==2)return;let W=/^(.+?)[ \t]+&&[ \t]+([\s\S]+)$/.exec($);if(!W)return;let Y=H$(W[1]??"");if(Y.length!==2||Y[0]!=="cd")return;let K=Y[1];if(!K||K==="-")return;let X=V$.isAbsolute(K)?V$.resolve(K):V$.resolve(J,K);if(!z$.isWithinWorkspace(X,J))return;return W[2]?.trim()||void 0}function g8($){let Z=[],J=!1,W=!1,Y=!1;for(let K=0;K<$.length;K++){let X=$[K];if(Y){Y=!1;continue}if(X==="\\"&&!J){Y=!0;continue}if(X==="'"&&!W){J=!J;continue}if(X==='"'&&!J){W=!W;continue}if(X!=="|"||J||W)continue;if($[K+1]==="|")return;Z.push(K)}return Z}function p8($){let Z=H$($),[J,W,Y]=Z;if(J!=="head"&&J!=="tail")return!1;if(Z.length===1)return!0;let K=(X)=>X!==void 0&&/^[1-9]\d{0,4}$/.test(X);if(Z.length===2)return W?.startsWith("--lines=")&&K(W.slice(8))||W?.startsWith("-")&&K(W.slice(1));return Z.length===3&&(W==="-n"||W==="--lines")&&K(Y)}function u8($){let Z=WJ($.replace(h8,"").trim()),J=g8(Z);if(!J)return;if(J.length===0)return YJ(Z);if(J.length!==1)return;let W=J[0];if(W===void 0)return;let Y=WJ(Z.slice(0,W).trim()),K=Z.slice(W+1).trim();if(!Y||!p8(K))return;return YJ(Y)}function YJ($){let J=e$($)?.at(-1);if(!J)return $;let W=H$(J),[Y,K]=W;if(!(Y==="vitest"||(Y==="npx"||Y==="bunx")&&K==="vitest")||W.some((Q)=>Q==="--configLoader"||Q.startsWith("--configLoader=")))return $;return`${$} --configLoader runner`}function f$($,Z){let J=u8($);if(!J)return!1;let W=t$(J),Y=e$(W);if(!Y||ZJ(W)||/[\r\n]/.test(W))return!1;let K=Y.length===1?Y[0]:C8(W,Y,Z);if(!K)return!1;let X=H$(K);if(X.length===0||X.some((z)=>[...I8].some((B)=>z===B||z.startsWith(`${B}=`))))return!1;let[Q,H,V]=X;if(x8.has(Q??""))return v8(H==="run"?V:H)||H==="--test";if((Q==="npx"||Q==="bunx")&&JJ.has(H??""))return!0;if(JJ.has(Q??""))return!0;if(Q==="node"&&H==="--test")return!0;if(Q==="go"&&["build","test","vet"].includes(H??""))return!0;return Q==="cargo"&&["build","check","clippy","test"].includes(H??"")}function a5($,Z){if($===void 0)return!0;if(typeof $!=="string"||$.split(/[\\/]/).includes(".."))return!1;if(!Z)return!V$.isAbsolute($);let J=V$.isAbsolute($)?V$.resolve($):V$.resolve(Z,$);return z$.isWithinWorkspace(J,Z)}var MZ=T0("Agent"),m8=3;function kZ($,Z,J){if($!=="length")return{action:"none"};if(Z>=m8)return{action:"truncated"};if(s6(J)==="stop")return MZ.info("[Loop] Token budget: diminishing returns detected, skipping recovery"),{action:"budget_stop"};return{action:"recover"}}var d8=[/:\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],c8=/```[\s\S]{50,}```/,KJ="请执行你提到的操作,不要只是描述。使用 Edit/Write/ApplyPatch/Bash 工具来实际修改文件。",l8=2;function xZ($,Z,J=!0){if(!$||Z>=l8)return{action:"none"};if(!J&&c8.test($))return{action:"retry",prompt:KJ};let W=$.slice(-200),Y=W.match(/```/g);if(Y&&Y.length%2!==0)return{action:"none"};if(d8.some((X)=>X.test(W)))return{action:"retry",prompt:KJ};return{action:"none"}}var h1=2,i8="The model returned tool-call JSON as text instead of completing the requested tool workflow.",r8="The previous response contained tool-call JSON as ordinary text. It did not execute a tool. If the requested operation is still needed, use the native tool-call interface with an available tool. If it already succeeded, use the recorded result to answer instead of repeating the operation. Do not return another tool-call JSON envelope as your final answer.";function IZ($,Z,J,W){if(!$||$.length>65536||J.length===0)return{action:"none"};let Y=Z.replace(/```[\s\S]*?(?:```|$)/g,"").replace(/^\s*>.*$/gm,"");if(/\b(?:example|schema|serialize|serialization|quote|print|illustrate|verbatim)\b|示例|样例|序列化|引用原文/i.test(Y)||/\b(?:explain|show|return|output)\b[^.!?\n]{0,80}\b(?:json|tool.calls?)\b|(?:解释|展示|输出|返回)[^。!?\n]{0,40}(?:JSON|工具调用格式)/i.test(Y)||/\b(?:do not|don't|never)\s+(?:use|call|invoke|execute)\s+(?:any\s+)?tools?\b|不要(?:使用|调用|执行)(?:任何)?工具/i.test(Y))return{action:"none"};let K;try{K=JSON.parse($)}catch{return{action:"none"}}if(!K||typeof K!=="object"||Array.isArray(K)||Object.keys(K).length!==1||!("tool_calls"in K)||!Array.isArray(K.tool_calls)||K.tool_calls.length===0||K.tool_calls.length>32)return{action:"none"};let X=new Set;for(let Q of K.tool_calls){if(!Q||typeof Q!=="object"||Array.isArray(Q))return{action:"none"};let H="function"in Q;if(Object.keys(Q).some((L)=>!["id","type",...H?["function"]:["name","arguments"]].includes(L)))return{action:"none"};if("type"in Q&&Q.type!=="function")return{action:"none"};let V=H?Q.function:Q;if(!V||typeof V!=="object"||Array.isArray(V)||!("name"in V)||typeof V.name!=="string"||!("arguments"in V))return{action:"none"};if(H&&Object.keys(V).some((L)=>L!=="name"&&L!=="arguments"))return{action:"none"};if(!J.includes(V.name))return{action:"none"};let z=V.arguments;if(typeof z!=="string"&&(!z||typeof z!=="object"||Array.isArray(z)))return{action:"none"};let B=V.name.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),j=new RegExp(`(?:^|[.!?。!?;;\\n])\\s*(?:please\\s+)?(?:call|invoke|execute|run|use)\\s+(?:the\\s+)?(?:tool\\s+)?[\`"']?${B}(?![\\w:-])|(?:^|[。!?;\\n])\\s*(?:请)?(?:调用|使用|执行)\\s*(?:工具\\s*)?[\`"']?${B}(?![\\w:-])`,"i"),w=new RegExp(`(?:do not|don't|never)\\s+(?:call|invoke|execute|run|use)\\s+(?:the\\s+)?(?:tool\\s+)?[\`"']?${B}(?![\\w:-])|(?:不要|禁止)(?:调用|使用|执行)\\s*(?:工具\\s*)?[\`"']?${B}(?![\\w:-])`,"i");if(!j.test(Y)||w.test(Y))return{action:"none"};X.add(V.name)}return W<h1?{action:"retry",prompt:r8,...X.size===1?{toolName:[...X][0]}:{}}:{action:"fail",message:i8}}var n8=[/\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}(?:测试|单测|集成测试|检查|构建)/],XJ={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},o8={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},a8="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.",s8="Required verification did not run successfully before the retry limit.",t8=3;function HJ($,Z,J,W){if(!J.success)return;if(["Edit","Write","ApplyPatch","NotebookEdit"].includes(Z)){$.clear();return}if(Z==="Bash"&&typeof J.metadata?.command==="string"&&J.metadata.exit_code===0&&f$(J.metadata.command,W)){$.add(J.metadata.command);return}if(!["Task","TaskOutput"].includes(Z))return;let Y=J.metadata?.verificationCommands;if(!Array.isArray(Y))return;for(let K of Y)if(typeof K==="string"&&f$(K,W))$.add(K)}function hZ($,Z,J){if(!$||!n8.some((H)=>H.test($)))return{action:"none"};let W=Object.keys(XJ).filter((H)=>XJ[H].test($)),Y=[...Z],K=W.filter((H)=>!Y.some((V)=>o8[H].test(V)));if(W.length>0?K.length===0:Y.some((H)=>f$(H)))return{action:"none"};if(J>=t8)return{action:"fail",message:s8};let Q=W.length>1&&K.length>0?` Missing successful verification categories: ${K.join(", ")}.`:"";return{action:"retry",prompt:`${a8}${Q}`}}var e8=[/\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|子代理|子智能体)/],VJ=[/\b(?:do not|don't|never)\s+(?:delegate|call|use|invoke)\b/i,/(?:不要|禁止|无需)(?:委派|调用|使用).{0,20}(?:Task|子代理|子智能体)?/];function zJ($){return typeof $==="string"&&VJ.some((Z)=>Z.test($))}var $9=[/\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|子代理)/],Z9=[/\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 J9($){if(typeof $!=="string")return;if(Z9.some((Z)=>Z.test($)))return"multiple-allowed";return $9.some((Z)=>Z.test($))?"required":void 0}function Z1($){for(let Z of $){let J=J9(Z);if(J!==void 0)return J==="required"}return!1}var W9="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.",Y9="Required delegation did not complete before the retry limit.",K9=3;function jJ($,Z,J){let W=(typeof $==="string"?[$]:$??[]).map((X)=>X.trim()).filter(Boolean),Y=Z1(W),K=!1;if(!Y)for(let X of W){if(VJ.some((Q)=>Q.test(X)))break;if(e8.some((Q)=>Q.test(X))){K=!0;break}}if(W.length===0||!Y&&!K||Z.has("Task"))return{action:"none"};if(J>=K9)return{action:"fail",message:Y9};return{action:"retry",prompt:W9}}var X9=[/\b(?:use|create|enter|start|work\s+(?:in|inside))\b.{0,60}\bworktree\b/i,/(?:使用|创建|进入).{0,30}(?:worktree|工作树)/i],Q9=[/\b(?:exit|leave)\b.{0,40}\bworktree\b/i,/\bworktree\b.{0,60}\b(?:action\s+)?(?:keep|remove)\b/i,/(?:退出|离开).{0,30}(?:worktree|工作树)/i],H9=[/\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 BJ($){return H9.reduce((Z,J)=>Z.replace(J," "),$)}function v1($){if(typeof $!=="string")return!1;let Z=BJ($);return X9.some((J)=>J.test(Z))}var V9="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.",z9="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.",j9="Required worktree lifecycle did not complete before the retry limit.",B9=3;function DJ($,Z,J){if(!$)return{action:"none"};let W=BJ($);if(!v1(W))return{action:"none"};let Y=Q9.some((X)=>X.test(W));if(Z.has("TaskWorktree"))return{action:"none"};let K=!Z.has("EnterWorktree")?"EnterWorktree":Y&&!Z.has("ExitWorktree")?"ExitWorktree":void 0;if(!K)return{action:"none"};if(J>=B9)return{action:"fail",message:j9};return{action:"retry",tool:K,prompt:K==="EnterWorktree"?V9:z9}}var QJ=30000;async function vZ($){try{let J=E$.getInstance().executeStopHooks({projectDir:$.workspaceRoot??j0(),sessionId:$.sessionId,permissionMode:$.permissionMode,reason:$.reason,abortSignal:$.abortSignal}),W,Y=new Promise((K)=>{W=setTimeout(()=>K("timeout"),QJ)});try{let K=await Promise.race([J,Y]);if(K==="timeout")return MZ.warn(`[Loop] Stop hook 超时 (${QJ}ms),按 shouldStop: true 处理`),{action:"stop"};let X=K;if(!X.shouldStop)return{action:"continue",reason:X.continueReason};return{action:"stop"}}finally{clearTimeout(W)}}catch(Z){return MZ.warn("[Loop] Stop hook execution failed:",Z),{action:"stop"}}}async function D9($,Z){let J;while(!(J=await $.next()).done)if(Z)await Z(J.value);return J.value}var w9=[/<system-reminder>[\s\S]*?<\/system-reminder>/gi,/<file[^>]*>[\s\S]*?<\/file>/gi,/<hooks_context>[\s\S]*?<\/hooks_context>/gi,/<[^>]+>/g];function U9($){if(typeof $==="string")return $;if(Array.isArray($))return $.map((Z)=>{if(typeof Z==="string")return Z;if(Z&&typeof Z==="object"&&"text"in Z){let J=Z.text;return typeof J==="string"?J:""}return""}).join(" ");return""}function q9($){let Z=$;for(let H of w9)Z=Z.replace(H," ");Z=Z.replace(/^\s*\/[a-zA-Z][\w-]*\s+/,"");let J=Z.replace(/\s+/g," ").trim();if(!J)return"";let W=J.match(/^(.+?)(?:[.!?]\s|[。!?](?=\S|$)|$)/),Y=W&&W[1].length>=6?W[1]:J;if(Y=Y.trim().replace(/[\s.。!!??,,;;::-]+$/,""),Y.length<=60)return Y;let K=Y.slice(0,60),X=K.lastIndexOf(" ");return`${(X>36?K.slice(0,X):K).trimEnd()}…`}function wJ($){return q9(U9($))}import{EventEmitter as G9}from"events";import UJ from"node:path";function CZ($){if(GJ($.sessionId),!UJ.isAbsolute($.projectPath))throw Error("projectPath must be absolute");return{sessionId:$.sessionId,projectPath:UJ.resolve($.projectPath)}}function qJ($){let Z=CZ($);return JSON.stringify([Z.projectPath,Z.sessionId])}function V3($,Z){return qJ($)===qJ(Z)}class S$ extends G9{static instance;constructor(){super();this.setMaxListeners(100)}static getInstance(){if(!S$.instance)S$.instance=new S$;return S$.instance}publish($,Z,J,W){let Y=CZ($);this.emit("event",{sessionId:Y.sessionId,projectPath:Y.projectPath,type:Z,...W!==void 0?{seq:W}:{},properties:J})}subscribe($){return this.on("event",$),()=>this.off("event",$)}}var J1=S$.getInstance();var $$=T0("Agent"),C1=new Set;async function L9($,Z){let J=$.sessionId;if(!J||$.subagentInfo)return;if(C1.has(J))return;if(C1.size>=5000)C1.clear();C1.add(J);try{let W=$.workspaceRoot,Y=await W1.findSessionMetadata(J,W);if(!Y)return;if(Y.title&&Y.title.trim())return;let K=wJ(Z);if(!K)return;await W1.updateSessionMetadata(J,Y.projectPath,{title:K}),J1.publish({sessionId:J,projectPath:Y.projectPath},"session.updated",{title:K})}catch(W){$$.debug?.("[Loop] 自动生成会话标题失败:",W)}}var gZ=`<turn_aborted>
|
|
2
2
|
The previous turn was interrupted. Commands or tool calls may have partially completed; inspect the workspace and running processes before retrying.
|
|
3
3
|
</turn_aborted>`,j$="Tool execution was blocked because its durable call record could not be committed. No tool side effect was started.",LJ="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 T$ extends Error{phase;constructor($,Z){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.",Z);this.phase=$;this.name="DurableConversationPersistenceError"}}function B$($){return $.executionEngine?.getContextManager()}async function i0($,Z,J,W=null,Y,K={}){let X=K.required??$.executionEngine!==void 0;try{let Q=B$($),H=typeof J==="string"?J.trim()!=="":J.some((V)=>V.type==="text"?V.text.trim()!=="":!0);if(Q&&Z.sessionId&&H){let V=await Q.saveMessage(Z.sessionId,"user",J,W,Y,Z.subagentInfo);if(X&&!V)throw Error("Durable user-message commit returned no identity");if(Y?.clientVisible!==!1)L9(Z,J);return V}if(X&&Z.sessionId&&H)throw Error("Durable user-message storage is unavailable")}catch(Q){if($$.warn("[Loop] 保存用户消息失败:",Q),X)throw new T$("user_message",{cause:Q})}return null}async function C0($,Z,J,W,Y,K,X={}){let Q=X.required??$.executionEngine!==void 0;try{let H=B$($),V=Boolean(J.trim()||Y?.trim());if(H&&Z.sessionId&&V){let z=await H.saveMessage(Z.sessionId,"assistant",J,W,K,Z.subagentInfo,Y);if(Q&&!z)throw Error("Durable assistant-message commit returned no identity");return z}if(Q&&Z.sessionId&&V)throw Error("Durable assistant-message storage is unavailable")}catch(H){if($$.warn("[Loop] 保存助手消息失败:",H),Q)throw new T$("assistant_message",{cause:H})}return null}async function FJ($,Z,J){try{let W=B$($);if(W&&Z.sessionId)return await W.saveMessage(Z.sessionId,"system",gZ,J,void 0,Z.subagentInfo)}catch(W){$$.warn("[Loop] 保存中断边界失败:",W)}return null}async function OJ($,Z,J,W,Y){try{let K=B$($);if(!K||!Z.sessionId||J.length===0)return null;return await K.saveMessage(Z.sessionId,"system",`<contextual-project-instructions-ref count="${J.length}" />`,Y,{contextualProjectRules:!0,ruleReferences:JSON.parse(JSON.stringify(J.map((X)=>({...X})))),triggerPaths:[...W]},Z.subagentInfo)}catch(K){$$.warn("[Loop] 保存 contextual project rules provenance 失败:",K)}return null}async function pZ($,Z,J,W,Y,K={}){try{let X=B$($);if(X&&Z.sessionId){let Q=await X.saveToolUse(Z.sessionId,J,W,Y,Z.subagentInfo,K.providerToolCallId);if(K.required&&!Q)throw Error("Durable tool-use commit returned no identity");return Q}if(K.required&&Z.sessionId)throw Error("Durable tool-use storage is unavailable")}catch(X){if($$.warn("[Loop] 保存工具调用失败:",X),K.required)throw X}return null}async function g1($,Z,J,W,Y,K,X,Q,H,V={}){try{let z=B$($);if(z&&Z.sessionId){let B=await z.saveToolResult(Z.sessionId,J,W,Y,K,X,Z.subagentInfo,Q,H);if(V.required&&!B)throw Error("Durable tool-result commit returned no identity");return B}if(V.required&&Z.sessionId)throw Error("Durable tool-result storage is unavailable")}catch(z){if($$.warn("[Loop] 保存工具结果失败:",z),V.required)throw z}return null}async function Y1($,Z,J,W,Y={}){try{let K=B$($);if(K&&Z.sessionId){let X=await K.saveCompaction(Z.sessionId,J,W,null);if(Y.required&&!X)throw Error("Compaction checkpoint commit returned no identity");return X||null}if(Y.required&&Z.sessionId)throw Error("Compaction checkpoint storage is unavailable")}catch(K){if($$.warn("[Loop] 保存压缩数据失败:",K),Y.required)throw K}return null}async function V0($){let{deps:Z,context:J,state:W,assistantContent:Y,assistantReasoningContent:K,lastMessageUuid:X,controlPrompt:Q}=$;W.appendAssistant({role:"assistant",content:Y,reasoningContent:K});let H=X,V=await C0(Z,J,Y,H,K);if(V)H=V;if(Q!==void 0){let z={role:"user",content:Q,metadata:E0};W.appendControl("user",z);let B=await i0(Z,J,Q,H,E0);if(B)H=B}return H}import{createHash as R6}from"node:crypto";import{promises as i9}from"node:fs";import r9 from"node:path";import{nanoid as J$}from"nanoid";import*as t from"node:fs/promises";import*as Z$ from"node:path";import NJ from"write-file-atomic";var PJ={enabled:!0,maxIndexLines:200};var F9="memory",uZ="MEMORY.md",dZ="<!-- blade:auto-memory-topics:start -->",p1="<!-- blade:auto-memory-topics:end -->",O9={realpath:!1,retries:{retries:5,factor:1.2,minTimeout:20,maxTimeout:100,randomize:!0}},P9=new R$,_J;function bJ($){return $.trim().replace(/\s+/g," ")}function N9($){return bJ($.replace(/^- \[\d{4}-\d{2}-\d{2}\] /,""))}function _9($){return[dZ,"## Auto-consolidated topics",...$.map((Z)=>`- [${Z}](${Z}.md)`),p1].join(`
|
|
4
4
|
`)}function A9($,Z){let J=_9(Z),W=$.indexOf(dZ),Y=$.indexOf(p1,Math.max(0,W));if(W>=0&&Y>=W)return $.slice(0,W)+J+$.slice(Y+p1.length);if(!$)return`${J}
|