blade-code 0.10.103 → 0.10.105

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.
Files changed (62) hide show
  1. package/dist/blade.js +2 -2
  2. package/dist/chunk-0pj7d25e.js +23 -0
  3. package/dist/{chunk-f945dzj6.js → chunk-139frcak.js} +1 -1
  4. package/dist/{chunk-ywarj5j9.js → chunk-151cz9k4.js} +1 -1
  5. package/dist/{chunk-a8x3xygs.js → chunk-1x13nzwe.js} +1 -1
  6. package/dist/chunk-25n07173.js +1 -0
  7. package/dist/{chunk-cpex23zk.js → chunk-26t2mg1v.js} +1 -1
  8. package/dist/{chunk-jaswqpe7.js → chunk-2mck84gx.js} +1 -1
  9. package/dist/{chunk-khtxprbv.js → chunk-3gf34fv5.js} +1 -1
  10. package/dist/{chunk-5sk7q6pw.js → chunk-3vqdyer3.js} +1 -1
  11. package/dist/{chunk-e1tt6b1w.js → chunk-48vc39mb.js} +2 -2
  12. package/dist/{chunk-14bs89sm.js → chunk-4bwr3rcj.js} +1 -1
  13. package/dist/chunk-4z79mh8y.js +1 -0
  14. package/dist/{chunk-q6eb20fz.js → chunk-5y38cfk9.js} +1 -1
  15. package/dist/{chunk-aa5zmwd9.js → chunk-6j482w6k.js} +1 -1
  16. package/dist/{chunk-gr80w0vh.js → chunk-7g984trn.js} +1 -1
  17. package/dist/{chunk-0aa40zbs.js → chunk-8hp650gn.js} +1 -1
  18. package/dist/{chunk-bx82y5ce.js → chunk-9dba1pyq.js} +1 -1
  19. package/dist/{chunk-c479s9v2.js → chunk-bcbssqsn.js} +1 -1
  20. package/dist/{chunk-s66fwx1p.js → chunk-brjjvs4d.js} +1 -1
  21. package/dist/{chunk-6v10cs0h.js → chunk-c0m2vw2q.js} +1 -1
  22. package/dist/{chunk-8zjn51fr.js → chunk-c133kq05.js} +1 -1
  23. package/dist/{chunk-a7ejfmtc.js → chunk-djqbqaxn.js} +1 -1
  24. package/dist/{chunk-42bcht8b.js → chunk-gz4h2y7j.js} +1 -1
  25. package/dist/{chunk-s6vzjear.js → chunk-jqqqg8kv.js} +1 -1
  26. package/dist/{chunk-0kdrgmyy.js → chunk-n1qxq9kv.js} +1 -1
  27. package/dist/{chunk-wzmqkam9.js → chunk-najk5ty4.js} +1 -1
  28. package/dist/{chunk-07w0qapm.js → chunk-p39mmmbt.js} +1 -1
  29. package/dist/{chunk-xtb84adp.js → chunk-p6prp8zc.js} +1 -1
  30. package/dist/{chunk-mgsvn9v4.js → chunk-pf4je2g7.js} +1 -1
  31. package/dist/{chunk-yr56ttgw.js → chunk-q0fv0efv.js} +1 -1
  32. package/dist/{chunk-rahch228.js → chunk-sy117k4g.js} +1 -1
  33. package/dist/{chunk-gxgq70gm.js → chunk-szdz1jmj.js} +1 -1
  34. package/dist/{chunk-03qymy9e.js → chunk-x6z05rfz.js} +1 -1
  35. package/dist/{chunk-k9fveqq6.js → chunk-xvg14dkr.js} +1 -1
  36. package/dist/{chunk-fw2x9p4c.js → chunk-xzjhfw7y.js} +1 -1
  37. package/dist/{chunk-b0j9v359.js → chunk-yeq7qzdb.js} +4 -4
  38. package/dist/{chunk-afa35v3f.js → chunk-zmfm07hj.js} +1 -1
  39. package/dist/web/assets/{ChatView-_4ut_-Jh.js → ChatView-p9tMKcFw.js} +4 -4
  40. package/dist/web/assets/{CodeBlockHighlighter-DkDr6wE9.js → CodeBlockHighlighter-DD7FIfcr.js} +1 -1
  41. package/dist/web/assets/{FilePreview-DCI-oqhJ.js → FilePreview-DDpZFwlq.js} +1 -1
  42. package/dist/web/assets/{KanbanBoard-CB5C4tJC.js → KanbanBoard-1Bkr6fIi.js} +1 -1
  43. package/dist/web/assets/{MarkdownRenderer-ychfmIQK.js → MarkdownRenderer-hkB9aVVA.js} +3 -3
  44. package/dist/web/assets/{SettingsModal-SSdk0Bjr.js → SettingsModal-KpvOJhBi.js} +1 -1
  45. package/dist/web/assets/{TaskSwitcher-EnaUhn3o.js → TaskSwitcher-2FU_n9lh.js} +1 -1
  46. package/dist/web/assets/{TerminalPanel-BcWxLSV3.js → TerminalPanel-C-LpIqOw.js} +1 -1
  47. package/dist/web/assets/{arrow-left-Ob5r20g7.js → arrow-left-Bf8UJl0b.js} +1 -1
  48. package/dist/web/assets/{calendar-clock-eOALT8DB.js → calendar-clock-BTAxrL8A.js} +1 -1
  49. package/dist/web/assets/{chevrons-up-down-BkZBwmbt.js → chevrons-up-down-CTzVylwH.js} +1 -1
  50. package/dist/web/assets/{clock-3-DQp9SzYc.js → clock-3-Cm6_vdYx.js} +1 -1
  51. package/dist/web/assets/{external-link-BuGUowPD.js → external-link-DJln2WFN.js} +1 -1
  52. package/dist/web/assets/{folder-c92kw1oI.js → folder-BXj3pohP.js} +1 -1
  53. package/dist/web/assets/{index-CS8jtO_A.js → index-DQL9otjm.js} +4 -4
  54. package/dist/web/assets/{pause-DP_CXoH7.js → pause-W092j5bW.js} +1 -1
  55. package/dist/web/assets/{play-DcRwtohz.js → play-OpsbZ_PE.js} +1 -1
  56. package/dist/web/assets/{session-events-CrAgnaj2.js → session-events-BuugneNw.js} +1 -1
  57. package/dist/web/assets/{teamService-JyVbGQhi.js → teamService-Aj-8ajEO.js} +1 -1
  58. package/dist/web/index.html +1 -2
  59. package/package.json +1 -1
  60. package/dist/chunk-4qfke0gd.js +0 -23
  61. package/dist/chunk-7ab7jcvn.js +0 -1
  62. package/dist/chunk-nz7kjzc0.js +0 -1
@@ -1,4 +1,4 @@
1
- import{Xb as Xt,Yb as En,Zb as yn,_b as bn}from"./chunk-8hprmrd5.js";import{qg as Bt}from"./chunk-aa5zmwd9.js";import{Ag as en,Bg as gt,Cg as mt,Eg as rn,Fg as Tn,Gg as B,Hg as dn,Ig as on,Jg as pn,Kg as lt,Lg as un,Mg as cn,Ng as Mn,Pg as S,Sg as wn,Tg as Gt,Ug as Ut,Vg as h,Wg as Ht,vg as xt,wg as vi,xg as sn,yg as zt,zg as U}from"./chunk-f945dzj6.js";import{Bh as X,Dh as x}from"./chunk-f3426b1c.js";import{Ph as It}from"./chunk-0hr050ck.js";import{Di as tn,Ei as nn}from"./chunk-14bs89sm.js";import{Xi as ns}from"./chunk-fhfzdyba.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} 个错误):
1
+ import{Xb as Xt,Yb as En,Zb as yn,_b as bn}from"./chunk-8hprmrd5.js";import{qg as Bt}from"./chunk-6j482w6k.js";import{Ag as en,Bg as gt,Cg as mt,Eg as rn,Fg as Tn,Gg as B,Hg as dn,Ig as on,Jg as pn,Kg as lt,Lg as un,Mg as cn,Ng as Mn,Pg as S,Sg as wn,Tg as Gt,Ug as Ut,Vg as h,Wg as Ht,vg as xt,wg as vi,xg as sn,yg as zt,zg as U}from"./chunk-139frcak.js";import{Bh as X,Dh as x}from"./chunk-f3426b1c.js";import{Ph as It}from"./chunk-0hr050ck.js";import{Di as tn,Ei as nn}from"./chunk-4bwr3rcj.js";import{Xi as ns}from"./chunk-fhfzdyba.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{e as u4,f as p4}from"./chunk-7fz3w4rk.js";import{g as wx}from"./chunk-47e6tdbb.js";import{s as N0,t as K4}from"./chunk-afa35v3f.js";import{u as rO}from"./chunk-khtxprbv.js";import{A as J1,v as W4,w as w1,x as Q1,y as Z1,z as Z0}from"./chunk-k9fveqq6.js";import{$ as Y4,D as O4,E as C1,F as r4,I as x4,J as V0,K as Px,L as r0,M as j1,N as jx,O as w4,P as fO,Q as Q4,R as Z4,S as J4,T as Mx,U as gO,V as sO,Y as m0,Z as h0,_ as G$,aa as N4,ba as j4,ca as M4,da as T4,ea as R4,fa as q4,ga as C4,ha as I4,ia as E4,ja as k4,ma as g4,pa as H$,ua as e4}from"./chunk-b0j9v359.js";import{Ba as _1,Ha as KO}from"./chunk-xtb84adp.js";import{$a as V4,La as Xx,Oa as x$,Pa as yx,Qa as X4,Ra as z4,Sa as $$,Ta as w$,Ua as mx,Va as Q$,Wa as x0,Xa as v4,Ya as l4,Za as i4,_a as G4,ab as B4,bb as U4,cb as O1,db as vx}from"./chunk-xm8nyj5z.js";import{Db as Sx,Mb as eO,ob as pO,pb as m,rb as q,sb as $4}from"./chunk-0aa40zbs.js";import{Xb as d1}from"./chunk-8hprmrd5.js";import{Ac as C0,Bc as c1,Cd as s1,Dd as r1,Ec as Ux,Fd as X0,Id as Hx,Nd as e1,Od as bx,Pd as Ax,Qd as C,Rc as a1,ad as o1,kd as n1,ld as e0,qc as v1,sd as P0,td as qx,ud as y0,wd as t1,xc as l1,yc as Dx,zc as i1}from"./chunk-wzmqkam9.js";import{$e as AO,Me as X$,Qe as YO,Ue as H1}from"./chunk-q6eb20fz.js";import{af as Lx}from"./chunk-dg0d3303.js";import{rf as u1}from"./chunk-2hb222re.js";import{tf as s0}from"./chunk-07w0qapm.js";import{Bf as z$,Df as o4,Gf as S4,Kf as T0,Lf as R0,Pf as R$,Sf as TO,Tf as q0,Wf as q$}from"./chunk-ywarj5j9.js";import{kg as b1,lg as p1}from"./chunk-fva7jnjy.js";import{pg as V1,qg as Y0}from"./chunk-aa5zmwd9.js";import{Ig as K1,ah as m1,dh as h1,fh as g1,sh as B1,xh as M0}from"./chunk-f945dzj6.js";import{Ah as _x}from"./chunk-sdbbyagy.js";import{Bh as f,Dh as W,Eh as RO,Gh as e}from"./chunk-f3426b1c.js";import{Ih as xx,Lh as Fx}from"./chunk-c475tfqf.js";import{Ph as o}from"./chunk-0hr050ck.js";import{pi as t}from"./chunk-n7mzxa8h.js";import{vi as nO}from"./chunk-s10pmnrd.js";import{Ai as D1,Bi as y1,xi as L1,yi as P1}from"./chunk-9p20hhs0.js";import{Di as J0}from"./chunk-14bs89sm.js";import{Ki as dx}from"./chunk-wyhyw9rq.js";import{Qi as o0,Ui as N1,Vi as Ox}from"./chunk-tgdhsm5t.js";import{Xi as gx}from"./chunk-fhfzdyba.js";var u2={port:{type:"number",describe:"Port to listen on (0 for auto)",default:0},hostname:{type:"string",describe:"Hostname to listen on",default:"127.0.0.1"},cors:{type:"array",describe:"Additional domains to allow for CORS",default:[]}};function p2(O){return{port:O.port??0,hostname:O.hostname??"127.0.0.1",cors:O.cors??[]}}import{existsSync as lx,readFileSync as p0}from"node:fs";import{createServer as _2}from"node:http";import{networkInterfaces as F2}from"node:os";import{dirname as L2,extname as D2,join as cO}from"node:path";import{fileURLToPath as H2}from"node:url";import{brotliCompressSync as b2,gzipSync as A2,constants as S2}from"node:zlib";import{Hono as j2}from"hono";import{cors as M2}from"hono/cors";import{WebSocketServer as T2}from"ws";var Q0=t("Service"),E$=30000,k$=new Set(["completed","failed","cancelled","interrupted"]);class zx{dispatch;store;tickMs;timer;unsubscribeBus;ticking=!1;inFlight=new Set;constructor(O){this.dispatch=O.dispatch,this.store=O.store??O1.getInstance(),this.tickMs=O.tickMs??E$}start(){if(this.timer)return;Q0.info("[TaskScheduler] Starting scheduler tick loop"),this.timer=setInterval(()=>{this.tick()},this.tickMs),this.timer.unref?.(),this.unsubscribeBus=q.subscribe((O)=>{if(O.type!=="task.status")return;let x=O.properties.taskStatus;if(typeof x!=="string"||!k$.has(x))return;this.recordTerminalStatus(O.sessionId,x,typeof O.properties.taskStatusReason==="string"?O.properties.taskStatusReason:void 0)}),this.tick()}stop(){if(this.timer)clearInterval(this.timer),this.timer=void 0,this.unsubscribeBus?.(),this.unsubscribeBus=void 0,Q0.info("[TaskScheduler] Stopped scheduler tick loop")}async tick(O=new Date){if(this.ticking)return;this.ticking=!0;try{let x=await this.store.list();for(let $ of x)await this.evaluate($,O)}catch(x){Q0.warn("[TaskScheduler] Tick failed:",x)}finally{this.ticking=!1}}async evaluate(O,x){if(!O.enabled)return;if(this.inFlight.has(O.id))return;if(O.expiresAt&&new Date(O.expiresAt).getTime()<=x.getTime()){await this.store.update(O.id,{enabled:!1,nextRunAt:null}),Q0.info(`[TaskScheduler] Schedule ${O.id} expired; disabled`);return}if(!O.nextRunAt)return;if(!(new Date(O.nextRunAt).getTime()<=x.getTime()))return;await this.fire(O,x)}async fire(O,x=new Date,$={}){if(this.inFlight.has(O.id))throw Error(`Schedule ${O.id} is already dispatching`);this.inFlight.add(O.id);let w=x.toISOString();try{let Q=await this.dispatch({prompt:O.prompt,title:O.title??f$(O),sourceProjectPath:O.projectPath,isolation:O.dispatch.isolation??"worktree",permissionMode:O.dispatch.permissionMode??"default",modelId:O.dispatch.modelId,reasoningEffort:O.dispatch.reasoningEffort,serviceTier:O.dispatch.serviceTier,responseVerbosity:O.dispatch.responseVerbosity,communicationStyle:O.dispatch.communicationStyle}),Y=O.trigger.kind==="once"?null:$.manual?O.nextRunAt?new Date(O.nextRunAt):null:Xx(O.trigger,x,x);await this.store.update(O.id,{lastRunAt:w,lastRunSessionId:Q.session.sessionId,lastStatus:Q.status,lastError:void 0,runCount:O.runCount+1,nextRunAt:Y?Y.toISOString():null,enabled:O.trigger.kind==="once"?!1:O.enabled}),q.publish({sessionId:Q.session.sessionId,projectPath:O.projectPath},"schedule.fired",{scheduleId:O.id,firedAt:w,sessionId:Q.session.sessionId,runId:Q.runId,status:Q.status}),Q0.info(`[TaskScheduler] Fired schedule ${O.id} -> session ${Q.session.sessionId} (${Q.status})`)}catch(Q){let Y=Q instanceof Error?Q.message:String(Q);Q0.warn(`[TaskScheduler] Schedule ${O.id} dispatch failed:`,Q);let J=O.trigger.kind==="once"?null:$.manual?O.nextRunAt?new Date(O.nextRunAt):null:Xx(O.trigger,x,x);await this.store.update(O.id,{lastRunAt:w,lastStatus:"error",lastError:Y,nextRunAt:J?J.toISOString():null,enabled:O.trigger.kind==="once"?!1:O.enabled})}finally{this.inFlight.delete(O.id)}}async recordTerminalStatus(O,x,$){let Q=(await this.store.list()).find((Y)=>Y.lastRunSessionId===O);if(!Q)return;await this.store.update(Q.id,{lastStatus:x,...$?{lastError:$}:{lastError:void 0}})}}function f$(O){return`Scheduled: ${O.prompt.trim().replace(/\s+/g," ").slice(0,60)}`}class r extends Error{code;statusCode;details;constructor(O,x,$=500,w){super(x);this.code=O;this.statusCode=$;this.details=w;this.name="BladeServerError"}toObject(){return{error:{code:this.code,message:this.message,...this.details?{details:this.details}:{}}}}}class y extends r{constructor(O,x){super("NOT_FOUND",x?`${O} not found: ${x}`:`${O} not found`,404)}}class _ extends r{constructor(O){super("BAD_REQUEST",O,400)}}class k extends r{constructor(O){super("CONFLICT",O,409)}}class PO extends r{constructor(O,x){super("TOO_MANY_REQUESTS",O,429,x)}}class yO extends r{constructor(O="Server is shutting down"){super("SERVICE_UNAVAILABLE",O,503)}}class c0 extends r{constructor(O){super("SESSION_WORKSPACE_UNAVAILABLE","This session workspace is no longer available",409,{reason:O})}}class bO extends r{constructor(){super("AMBIGUOUS_SESSION","Multiple workspaces contain this session ID; projectPath is required",409)}}class s extends r{constructor(O="Internal server error"){super("INTERNAL_ERROR",O,500)}}var n2=W.Object({error:W.Object({code:W.String(),message:W.String(),details:W.Optional(W.Record(W.String(),W.Unknown()))})});import{Hono as P$}from"hono";var Gx=t("Service"),y$=W.Object({updates:W.Record(W.String(),W.Any()),options:W.Optional(W.Object({scope:W.Optional(e(["local","project","global"])),immediate:W.Optional(W.Boolean())}))});function m$(O){return{currentModelId:O.currentModelId,permissionMode:O.permissionMode,language:O.language,codeTheme:O.codeTheme,uiTheme:O.uiTheme,autoSaveSessions:O.autoSaveSessions,notifyBuild:O.notifyBuild,notifyErrors:O.notifyErrors,notifySounds:O.notifySounds,privacyTelemetry:O.privacyTelemetry,privacyCrash:O.privacyCrash,agentTeamsEnabled:O.agentTeamsEnabled===!0,communicationStyle:O.communicationStyle,maxConcurrentTasks:O.maxConcurrentTasks,maxQueuedTasks:O.maxQueuedTasks,maxQueuedTaskBytes:O.maxQueuedTaskBytes,maxResidentSessionRuntimes:O.maxResidentSessionRuntimes,sessionRuntimeIdleMs:O.sessionRuntimeIdleMs}}var x1=()=>{let O=new P$;return O.get("/",async(x)=>{try{let $=YO();return x.json($?m$($):{})}catch($){return Gx.error("[ConfigRoutes] Failed to get config:",$),x.json({})}}),O.put("/",async(x)=>{try{let $=await x.req.json(),w=f(y$,$);if(!w.success)throw new _("Invalid config update format");let{updates:Q,options:Y}=w.data;return await AO().updateConfig(Q,Y),x.json({success:!0,updates:Q})}catch($){throw Gx.error("[ConfigRoutes] Failed to update config:",$),$}}),O.get("/permissions",async(x)=>{try{let $=YO();return x.json($?.permissions||{})}catch($){return Gx.error("[ConfigRoutes] Failed to get permissions:",$),x.json({})}}),O};import{Hono as h$}from"hono";import{streamSSE as g$}from"hono/streaming";function $1(O){let x="";if(O.id!==void 0)x+=`id: ${O.id}
1
+ import{e as u4,f as p4}from"./chunk-7fz3w4rk.js";import{g as wx}from"./chunk-47e6tdbb.js";import{s as N0,t as K4}from"./chunk-zmfm07hj.js";import{u as rO}from"./chunk-3gf34fv5.js";import{A as J1,v as W4,w as w1,x as Q1,y as Z1,z as Z0}from"./chunk-xvg14dkr.js";import{$ as Y4,D as O4,E as C1,F as r4,I as x4,J as V0,K as Px,L as r0,M as j1,N as jx,O as w4,P as fO,Q as Q4,R as Z4,S as J4,T as Mx,U as gO,V as sO,Y as m0,Z as h0,_ as G$,aa as N4,ba as j4,ca as M4,da as T4,ea as R4,fa as q4,ga as C4,ha as I4,ia as E4,ja as k4,ma as g4,pa as H$,ua as e4}from"./chunk-yeq7qzdb.js";import{Ba as _1,Ha as KO}from"./chunk-p6prp8zc.js";import{$a as V4,La as Xx,Oa as x$,Pa as yx,Qa as X4,Ra as z4,Sa as $$,Ta as w$,Ua as mx,Va as Q$,Wa as x0,Xa as v4,Ya as l4,Za as i4,_a as G4,ab as B4,bb as U4,cb as O1,db as vx}from"./chunk-xm8nyj5z.js";import{Db as Sx,Mb as eO,ob as pO,pb as m,rb as q,sb as $4}from"./chunk-8hp650gn.js";import{Xb as d1}from"./chunk-8hprmrd5.js";import{Ac as C0,Bc as c1,Cd as s1,Dd as r1,Ec as Ux,Fd as X0,Id as Hx,Nd as e1,Od as bx,Pd as Ax,Qd as C,Rc as a1,ad as o1,kd as n1,ld as e0,qc as v1,sd as P0,td as qx,ud as y0,wd as t1,xc as l1,yc as Dx,zc as i1}from"./chunk-najk5ty4.js";import{$e as AO,Me as X$,Qe as YO,Ue as H1}from"./chunk-5y38cfk9.js";import{af as Lx}from"./chunk-dg0d3303.js";import{rf as u1}from"./chunk-2hb222re.js";import{tf as s0}from"./chunk-p39mmmbt.js";import{Bf as z$,Df as o4,Gf as S4,Kf as T0,Lf as R0,Pf as R$,Sf as TO,Tf as q0,Wf as q$}from"./chunk-151cz9k4.js";import{kg as b1,lg as p1}from"./chunk-fva7jnjy.js";import{pg as V1,qg as Y0}from"./chunk-6j482w6k.js";import{Ig as K1,ah as m1,dh as h1,fh as g1,sh as B1,xh as M0}from"./chunk-139frcak.js";import{Ah as _x}from"./chunk-sdbbyagy.js";import{Bh as f,Dh as W,Eh as RO,Gh as e}from"./chunk-f3426b1c.js";import{Ih as xx,Lh as Fx}from"./chunk-c475tfqf.js";import{Ph as o}from"./chunk-0hr050ck.js";import{pi as t}from"./chunk-n7mzxa8h.js";import{vi as nO}from"./chunk-s10pmnrd.js";import{Ai as D1,Bi as y1,xi as L1,yi as P1}from"./chunk-9p20hhs0.js";import{Di as J0}from"./chunk-4bwr3rcj.js";import{Ki as dx}from"./chunk-wyhyw9rq.js";import{Qi as o0,Ui as N1,Vi as Ox}from"./chunk-tgdhsm5t.js";import{Xi as gx}from"./chunk-fhfzdyba.js";var u2={port:{type:"number",describe:"Port to listen on (0 for auto)",default:0},hostname:{type:"string",describe:"Hostname to listen on",default:"127.0.0.1"},cors:{type:"array",describe:"Additional domains to allow for CORS",default:[]}};function p2(O){return{port:O.port??0,hostname:O.hostname??"127.0.0.1",cors:O.cors??[]}}import{existsSync as lx,readFileSync as p0}from"node:fs";import{createServer as _2}from"node:http";import{networkInterfaces as F2}from"node:os";import{dirname as L2,extname as D2,join as cO}from"node:path";import{fileURLToPath as H2}from"node:url";import{brotliCompressSync as b2,gzipSync as A2,constants as S2}from"node:zlib";import{Hono as j2}from"hono";import{cors as M2}from"hono/cors";import{WebSocketServer as T2}from"ws";var Q0=t("Service"),E$=30000,k$=new Set(["completed","failed","cancelled","interrupted"]);class zx{dispatch;store;tickMs;timer;unsubscribeBus;ticking=!1;inFlight=new Set;constructor(O){this.dispatch=O.dispatch,this.store=O.store??O1.getInstance(),this.tickMs=O.tickMs??E$}start(){if(this.timer)return;Q0.info("[TaskScheduler] Starting scheduler tick loop"),this.timer=setInterval(()=>{this.tick()},this.tickMs),this.timer.unref?.(),this.unsubscribeBus=q.subscribe((O)=>{if(O.type!=="task.status")return;let x=O.properties.taskStatus;if(typeof x!=="string"||!k$.has(x))return;this.recordTerminalStatus(O.sessionId,x,typeof O.properties.taskStatusReason==="string"?O.properties.taskStatusReason:void 0)}),this.tick()}stop(){if(this.timer)clearInterval(this.timer),this.timer=void 0,this.unsubscribeBus?.(),this.unsubscribeBus=void 0,Q0.info("[TaskScheduler] Stopped scheduler tick loop")}async tick(O=new Date){if(this.ticking)return;this.ticking=!0;try{let x=await this.store.list();for(let $ of x)await this.evaluate($,O)}catch(x){Q0.warn("[TaskScheduler] Tick failed:",x)}finally{this.ticking=!1}}async evaluate(O,x){if(!O.enabled)return;if(this.inFlight.has(O.id))return;if(O.expiresAt&&new Date(O.expiresAt).getTime()<=x.getTime()){await this.store.update(O.id,{enabled:!1,nextRunAt:null}),Q0.info(`[TaskScheduler] Schedule ${O.id} expired; disabled`);return}if(!O.nextRunAt)return;if(!(new Date(O.nextRunAt).getTime()<=x.getTime()))return;await this.fire(O,x)}async fire(O,x=new Date,$={}){if(this.inFlight.has(O.id))throw Error(`Schedule ${O.id} is already dispatching`);this.inFlight.add(O.id);let w=x.toISOString();try{let Q=await this.dispatch({prompt:O.prompt,title:O.title??f$(O),sourceProjectPath:O.projectPath,isolation:O.dispatch.isolation??"worktree",permissionMode:O.dispatch.permissionMode??"default",modelId:O.dispatch.modelId,reasoningEffort:O.dispatch.reasoningEffort,serviceTier:O.dispatch.serviceTier,responseVerbosity:O.dispatch.responseVerbosity,communicationStyle:O.dispatch.communicationStyle}),Y=O.trigger.kind==="once"?null:$.manual?O.nextRunAt?new Date(O.nextRunAt):null:Xx(O.trigger,x,x);await this.store.update(O.id,{lastRunAt:w,lastRunSessionId:Q.session.sessionId,lastStatus:Q.status,lastError:void 0,runCount:O.runCount+1,nextRunAt:Y?Y.toISOString():null,enabled:O.trigger.kind==="once"?!1:O.enabled}),q.publish({sessionId:Q.session.sessionId,projectPath:O.projectPath},"schedule.fired",{scheduleId:O.id,firedAt:w,sessionId:Q.session.sessionId,runId:Q.runId,status:Q.status}),Q0.info(`[TaskScheduler] Fired schedule ${O.id} -> session ${Q.session.sessionId} (${Q.status})`)}catch(Q){let Y=Q instanceof Error?Q.message:String(Q);Q0.warn(`[TaskScheduler] Schedule ${O.id} dispatch failed:`,Q);let J=O.trigger.kind==="once"?null:$.manual?O.nextRunAt?new Date(O.nextRunAt):null:Xx(O.trigger,x,x);await this.store.update(O.id,{lastRunAt:w,lastStatus:"error",lastError:Y,nextRunAt:J?J.toISOString():null,enabled:O.trigger.kind==="once"?!1:O.enabled})}finally{this.inFlight.delete(O.id)}}async recordTerminalStatus(O,x,$){let Q=(await this.store.list()).find((Y)=>Y.lastRunSessionId===O);if(!Q)return;await this.store.update(Q.id,{lastStatus:x,...$?{lastError:$}:{lastError:void 0}})}}function f$(O){return`Scheduled: ${O.prompt.trim().replace(/\s+/g," ").slice(0,60)}`}class r extends Error{code;statusCode;details;constructor(O,x,$=500,w){super(x);this.code=O;this.statusCode=$;this.details=w;this.name="BladeServerError"}toObject(){return{error:{code:this.code,message:this.message,...this.details?{details:this.details}:{}}}}}class y extends r{constructor(O,x){super("NOT_FOUND",x?`${O} not found: ${x}`:`${O} not found`,404)}}class _ extends r{constructor(O){super("BAD_REQUEST",O,400)}}class k extends r{constructor(O){super("CONFLICT",O,409)}}class PO extends r{constructor(O,x){super("TOO_MANY_REQUESTS",O,429,x)}}class yO extends r{constructor(O="Server is shutting down"){super("SERVICE_UNAVAILABLE",O,503)}}class c0 extends r{constructor(O){super("SESSION_WORKSPACE_UNAVAILABLE","This session workspace is no longer available",409,{reason:O})}}class bO extends r{constructor(){super("AMBIGUOUS_SESSION","Multiple workspaces contain this session ID; projectPath is required",409)}}class s extends r{constructor(O="Internal server error"){super("INTERNAL_ERROR",O,500)}}var n2=W.Object({error:W.Object({code:W.String(),message:W.String(),details:W.Optional(W.Record(W.String(),W.Unknown()))})});import{Hono as P$}from"hono";var Gx=t("Service"),y$=W.Object({updates:W.Record(W.String(),W.Any()),options:W.Optional(W.Object({scope:W.Optional(e(["local","project","global"])),immediate:W.Optional(W.Boolean())}))});function m$(O){return{currentModelId:O.currentModelId,permissionMode:O.permissionMode,language:O.language,codeTheme:O.codeTheme,uiTheme:O.uiTheme,autoSaveSessions:O.autoSaveSessions,notifyBuild:O.notifyBuild,notifyErrors:O.notifyErrors,notifySounds:O.notifySounds,privacyTelemetry:O.privacyTelemetry,privacyCrash:O.privacyCrash,agentTeamsEnabled:O.agentTeamsEnabled===!0,communicationStyle:O.communicationStyle,maxConcurrentTasks:O.maxConcurrentTasks,maxQueuedTasks:O.maxQueuedTasks,maxQueuedTaskBytes:O.maxQueuedTaskBytes,maxResidentSessionRuntimes:O.maxResidentSessionRuntimes,sessionRuntimeIdleMs:O.sessionRuntimeIdleMs}}var x1=()=>{let O=new P$;return O.get("/",async(x)=>{try{let $=YO();return x.json($?m$($):{})}catch($){return Gx.error("[ConfigRoutes] Failed to get config:",$),x.json({})}}),O.put("/",async(x)=>{try{let $=await x.req.json(),w=f(y$,$);if(!w.success)throw new _("Invalid config update format");let{updates:Q,options:Y}=w.data;return await AO().updateConfig(Q,Y),x.json({success:!0,updates:Q})}catch($){throw Gx.error("[ConfigRoutes] Failed to update config:",$),$}}),O.get("/permissions",async(x)=>{try{let $=YO();return x.json($?.permissions||{})}catch($){return Gx.error("[ConfigRoutes] Failed to get permissions:",$),x.json({})}}),O};import{Hono as h$}from"hono";import{streamSSE as g$}from"hono/streaming";function $1(O){let x="";if(O.id!==void 0)x+=`id: ${O.id}
2
2
  `;if(O.event!==void 0)x+=`event: ${O.event}
3
3
  `;for(let $ of O.data.split(/\r\n|\r|\n/))x+=`data: ${$}
4
4
  `;if(O.retry!==void 0)x+=`retry: ${O.retry}
@@ -1 +1 @@
1
- import{sf as a,tf as b,uf as c}from"./chunk-07w0qapm.js";import"./chunk-f945dzj6.js";import"./chunk-sdbbyagy.js";import"./chunk-f3426b1c.js";import"./chunk-c475tfqf.js";import"./chunk-0hr050ck.js";import"./chunk-q69fzq4y.js";import"./chunk-n7mzxa8h.js";import"./chunk-s10pmnrd.js";import"./chunk-9p20hhs0.js";import"./chunk-14bs89sm.js";import"./chunk-wyhyw9rq.js";import"./chunk-rvk9r2cm.js";import"./chunk-tgdhsm5t.js";import"./chunk-fhfzdyba.js";export{c as snapshotWorkspaceModelResources,b as resolveWorkspaceModelResources,a as cloneWorkspaceModelConfig};
1
+ import{sf as a,tf as b,uf as c}from"./chunk-p39mmmbt.js";import"./chunk-139frcak.js";import"./chunk-sdbbyagy.js";import"./chunk-f3426b1c.js";import"./chunk-c475tfqf.js";import"./chunk-0hr050ck.js";import"./chunk-q69fzq4y.js";import"./chunk-n7mzxa8h.js";import"./chunk-s10pmnrd.js";import"./chunk-9p20hhs0.js";import"./chunk-4bwr3rcj.js";import"./chunk-wyhyw9rq.js";import"./chunk-rvk9r2cm.js";import"./chunk-tgdhsm5t.js";import"./chunk-fhfzdyba.js";export{c as snapshotWorkspaceModelResources,b as resolveWorkspaceModelResources,a as cloneWorkspaceModelConfig};
@@ -1 +1 @@
1
- import{h as o}from"./chunk-jaswqpe7.js";import"./chunk-14bs89sm.js";import"./chunk-fhfzdyba.js";import{execSync as r}from"child_process";var l={command:"update",describe:"Check for updates and install if available",handler:async()=>{console.log("Checking for updates...");try{let e=await o(!0);if(console.log(`Current version: ${e.currentVersion}`),e.error){console.log(`Warning: ${e.error}`);return}if(e.latestVersion)console.log(`Latest version: ${e.latestVersion}`);if(e.hasUpdate&&e.latestVersion){console.log(""),console.log(`\x1B[33mUpdate available: ${e.currentVersion} -> ${e.latestVersion}\x1B[0m`),console.log(""),console.log("Updating...");try{r("npm install -g blade-code@latest --registry https://registry.npmjs.org",{stdio:"inherit"}),console.log(""),console.log("Update complete!")}catch(t){console.error("Error: Update failed. Please run manually:"),console.error(" npm install -g blade-code@latest"),process.exit(1)}}else console.log("You are running the latest version of Blade")}catch(e){console.error(`Error: Failed to check for updates: ${e instanceof Error?e.message:"未知错误"}`),process.exit(1)}}};export{l as updateCommands};
1
+ import{h as o}from"./chunk-2mck84gx.js";import"./chunk-4bwr3rcj.js";import"./chunk-fhfzdyba.js";import{execSync as r}from"child_process";var l={command:"update",describe:"Check for updates and install if available",handler:async()=>{console.log("Checking for updates...");try{let e=await o(!0);if(console.log(`Current version: ${e.currentVersion}`),e.error){console.log(`Warning: ${e.error}`);return}if(e.latestVersion)console.log(`Latest version: ${e.latestVersion}`);if(e.hasUpdate&&e.latestVersion){console.log(""),console.log(`\x1B[33mUpdate available: ${e.currentVersion} -> ${e.latestVersion}\x1B[0m`),console.log(""),console.log("Updating...");try{r("npm install -g blade-code@latest --registry https://registry.npmjs.org",{stdio:"inherit"}),console.log(""),console.log("Update complete!")}catch(t){console.error("Error: Update failed. Please run manually:"),console.error(" npm install -g blade-code@latest"),process.exit(1)}}else console.log("You are running the latest version of Blade")}catch(e){console.error(`Error: Failed to check for updates: ${e instanceof Error?e.message:"未知错误"}`),process.exit(1)}}};export{l as updateCommands};
@@ -1,4 +1,4 @@
1
- import{te as s}from"./chunk-j2dyprdy.js";import{Me as o}from"./chunk-q6eb20fz.js";import{$g as N,Yg as y,Zg as D,bh as j,ch as F,eh as R,ih as E,jh as _,kh as f,lh as C,nh as S,oh as m,sh as c,xh as l,yh as n}from"./chunk-f945dzj6.js";import{zh as Y}from"./chunk-sdbbyagy.js";import{Bh as x,Dh as k,Gh as Z}from"./chunk-f3426b1c.js";import{Nh as X}from"./chunk-0hr050ck.js";import{$h as $,Rh as h,Sh as A,Yh as P,Zh as T,ai as U,bi as G,di as L,ei as M,gi as O,hi as I}from"./chunk-q69fzq4y.js";import{pi as d}from"./chunk-n7mzxa8h.js";import{promises as i}from"node:fs";import t from"node:path";var e=["systemPrompt","appendSystemPrompt","initialMessage","resumeSessionId","forkSession","allowedTools","disallowedTools","mcpConfigPaths","strictMcpConfig","model","addDirs","outputFormat","inputFormat","print","includePartialMessages","replayUserMessages","agentsConfig","settingSources"],v=new Set([...Object.keys(c),...e,"providerRequestConcurrency","providerGlobalConcurrency","providerOwnerConcurrency"]),W=k.Number({exclusiveMinimum:0}),z=k.String({minLength:1}),b=k.Array(k.String()),a=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:y,maximum:D})])),providerForegroundRecoveryMs:k.Optional(k.Union([k.Literal(0),k.Integer({minimum:h,maximum:A})])),providerCircuitBreakerOpenMs:k.Optional(k.Union([k.Literal(0),k.Integer({minimum:P,maximum:T})])),providerRequestConcurrency:k.Optional(k.Integer({minimum:$,maximum:U})),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:L,maximum:M})])),providerRequestPendingBytes:k.Optional(k.Integer({minimum:O,maximum:I})),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:E,maximum:_})),maxQueuedTasks:k.Optional(k.Integer({minimum:f,maximum:C})),maxQueuedTaskBytes:k.Optional(k.Integer({minimum:S,maximum:m})),maxResidentSessionRuntimes:k.Optional(k.Integer({minimum:N,maximum:j})),sessionRuntimeIdleMs:k.Optional(k.Integer({minimum:F,maximum:R})),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())}),g=[["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"]];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(!v.has(H))throw Error(`Unknown --settings field: ${H}`);let J=x(a,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 p(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=t.resolve(X(),B),J;try{J=await i.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 u(q,B){if(!B)return;let w=B;for(let[J,H]of g){if(J==="permissionMode"&&q.yolo===!0)continue;if(q[H]===void 0&&w[J]!==void 0)q[H]=w[J]}}var Q=d("General"),Dk=(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(", ")}`)}},hk=async(q)=>{let B=await p(typeof q.settings==="string"?q.settings:void 0);if(u(q,B),typeof q.agents==="string")s(q.agents);r(q);try{let J=await l.getInstance().initialize(B),H=n(J,q);if(o().config.actions.setConfig(H),q.debug)Q.info("[CLI] 配置已加载到 Store")}catch(w){Q.error("[CLI] [FAIL] 配置初始化失败",w instanceof Error?w.message:w),console.error(`
1
+ import{te as s}from"./chunk-j2dyprdy.js";import{Me as o}from"./chunk-5y38cfk9.js";import{$g as N,Yg as y,Zg as D,bh as j,ch as F,eh as R,ih as E,jh as _,kh as f,lh as C,nh as S,oh as m,sh as c,xh as l,yh as n}from"./chunk-139frcak.js";import{zh as Y}from"./chunk-sdbbyagy.js";import{Bh as x,Dh as k,Gh as Z}from"./chunk-f3426b1c.js";import{Nh as X}from"./chunk-0hr050ck.js";import{$h as $,Rh as h,Sh as A,Yh as P,Zh as T,ai as U,bi as G,di as L,ei as M,gi as O,hi as I}from"./chunk-q69fzq4y.js";import{pi as d}from"./chunk-n7mzxa8h.js";import{promises as i}from"node:fs";import t from"node:path";var e=["systemPrompt","appendSystemPrompt","initialMessage","resumeSessionId","forkSession","allowedTools","disallowedTools","mcpConfigPaths","strictMcpConfig","model","addDirs","outputFormat","inputFormat","print","includePartialMessages","replayUserMessages","agentsConfig","settingSources"],v=new Set([...Object.keys(c),...e,"providerRequestConcurrency","providerGlobalConcurrency","providerOwnerConcurrency"]),W=k.Number({exclusiveMinimum:0}),z=k.String({minLength:1}),b=k.Array(k.String()),a=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:y,maximum:D})])),providerForegroundRecoveryMs:k.Optional(k.Union([k.Literal(0),k.Integer({minimum:h,maximum:A})])),providerCircuitBreakerOpenMs:k.Optional(k.Union([k.Literal(0),k.Integer({minimum:P,maximum:T})])),providerRequestConcurrency:k.Optional(k.Integer({minimum:$,maximum:U})),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:L,maximum:M})])),providerRequestPendingBytes:k.Optional(k.Integer({minimum:O,maximum:I})),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:E,maximum:_})),maxQueuedTasks:k.Optional(k.Integer({minimum:f,maximum:C})),maxQueuedTaskBytes:k.Optional(k.Integer({minimum:S,maximum:m})),maxResidentSessionRuntimes:k.Optional(k.Integer({minimum:N,maximum:j})),sessionRuntimeIdleMs:k.Optional(k.Integer({minimum:F,maximum:R})),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())}),g=[["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"]];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(!v.has(H))throw Error(`Unknown --settings field: ${H}`);let J=x(a,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 p(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=t.resolve(X(),B),J;try{J=await i.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 u(q,B){if(!B)return;let w=B;for(let[J,H]of g){if(J==="permissionMode"&&q.yolo===!0)continue;if(q[H]===void 0&&w[J]!==void 0)q[H]=w[J]}}var Q=d("General"),Dk=(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(", ")}`)}},hk=async(q)=>{let B=await p(typeof q.settings==="string"?q.settings:void 0);if(u(q,B),typeof q.agents==="string")s(q.agents);r(q);try{let J=await l.getInstance().initialize(B),H=n(J,q);if(o().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 +1 @@
1
- import{Kd as a,Ld as b,Md as c,Nd as d,Od as e,Pd as f,Qd as g}from"./chunk-wzmqkam9.js";import"./chunk-s0tq8gyx.js";import"./chunk-x3cxmwnz.js";import"./chunk-2hb222re.js";import"./chunk-fva7jnjy.js";import"./chunk-41cg66y0.js";import"./chunk-c475tfqf.js";import"./chunk-0hr050ck.js";import"./chunk-n7mzxa8h.js";import"./chunk-9p20hhs0.js";import"./chunk-14bs89sm.js";import"./chunk-tgdhsm5t.js";import"./chunk-fhfzdyba.js";export{b as __setSessionSnapshotIOForTesting,c as __resetSessionSnapshotIOForTesting,g as SessionService,d as SessionMissingCreationError,e as SessionArchivedError,f as SessionArchiveConflictError,a as STALE_EMPTY_SESSION_AGE_MS};
1
+ import{Kd as a,Ld as b,Md as c,Nd as d,Od as e,Pd as f,Qd as g}from"./chunk-najk5ty4.js";import"./chunk-s0tq8gyx.js";import"./chunk-x3cxmwnz.js";import"./chunk-2hb222re.js";import"./chunk-fva7jnjy.js";import"./chunk-41cg66y0.js";import"./chunk-c475tfqf.js";import"./chunk-0hr050ck.js";import"./chunk-n7mzxa8h.js";import"./chunk-9p20hhs0.js";import"./chunk-4bwr3rcj.js";import"./chunk-tgdhsm5t.js";import"./chunk-fhfzdyba.js";export{b as __setSessionSnapshotIOForTesting,c as __resetSessionSnapshotIOForTesting,g as SessionService,d as SessionMissingCreationError,e as SessionArchivedError,f as SessionArchiveConflictError,a as STALE_EMPTY_SESSION_AGE_MS};
@@ -1,2 +1,2 @@
1
- import{P as I}from"./chunk-b0j9v359.js";import{Qd as M}from"./chunk-wzmqkam9.js";import P from"node:path";function w(s){let a=s.replace(/\s+/g," ").trim();return a.length<=72?a:`${a.slice(0,69)}...`}function W(s){let a=s.replace(/\s+/g," ").trim();return a.length<=500?a:`${a.slice(0,497)}...`}function A(s){return`task/${s.replace(/[^a-zA-Z0-9_-]/g,"-").slice(0,40)}`}class C{static async createSessionTask(s){if(!s.prompt.trim())throw Error("Task prompt must not be blank");if(!P.isAbsolute(s.sourceProjectPath))throw Error("Task source project path must be absolute");let a=P.resolve(s.sourceProjectPath),t;try{return t=s.isolation==="worktree"?await I.enter({sessionId:s.sessionId,workspaceRoot:a,name:A(s.sessionId)}):void 0,{metadata:await M.createSessionMetadata(s.sessionId,t?.workspaceRoot??a,{title:s.title?.trim()||w(s.prompt),taskPromptSummary:W(s.prompt),taskPriority:s.taskPriority,taskKind:s.taskKind,taskDueAt:s.taskDueAt,taskDispatch:s.dispatch,taskModelId:s.dispatch?.modelId,selectedModelId:s.dispatch?.modelId,permissionMode:s.dispatch?.permissionMode,reasoningEffort:s.dispatch?.reasoningEffort,serviceTier:s.dispatch?.serviceTier,responseVerbosity:s.dispatch?.responseVerbosity,communicationStyle:s.dispatch?.communicationStyle,communicationStyleDigest:s.dispatch?.communicationStyleDigest,projectInstructionsDigest:s.dispatch?.projectInstructionsDigest,taskRetriedFrom:s.retriedFrom,taskIsolation:s.isolation,taskSourceProjectPath:a,taskWorktree:t}),taskWorktree:t}}catch(k){if(t)await I.exit({sessionId:s.sessionId,action:"remove",discardChanges:!0}).catch(()=>{return});throw k}}}var $=256,V=8388608,x=30000;class i extends Error{kind;pendingItems;pendingBytes;constructor(s,a,t){super(a,t);this.kind=s;this.name="BoundedSerialEgressError",this.pendingItems=t?.pendingItems,this.pendingBytes=t?.pendingBytes}}function T(s){s.catch(()=>{return})}class K{options;pending=[];flushWaiters=[];pendingBytes=0;nextSequence=0;completedSequence=0;draining=!1;closed=!1;failure;activeWriteAbort;activeWriteStop;activeWriteTimeout;constructor(s){this.options=s;if(this.assertPositiveInteger(s.maxPendingItems,"maxPendingItems"),this.assertPositiveInteger(s.maxPendingBytes,"maxPendingBytes"),this.assertPositiveInteger(s.writeTimeoutMs,"writeTimeoutMs"),s.signal?.addEventListener("abort",this.handleAbort,{once:!0}),s.signal?.aborted)this.handleAbort()}offer(s){if(this.closed)return{accepted:!1,error:this.failure??new i("closed","Egress is already closed")};let a;try{a=this.options.sizeOf(s)}catch(h){return this.rejectAdmission(new i("invalid_size","Egress size calculation failed",{cause:h}))}if(!Number.isSafeInteger(a)||a<0)return this.rejectAdmission(new i("invalid_size","Egress size must be a non-negative safe integer"));if(a>this.options.maxPendingBytes)return this.rejectAdmission(new i("oversized",`Egress value requires ${a} bytes; limit is ${this.options.maxPendingBytes}`));if(this.pending.length>=this.options.maxPendingItems||this.pendingBytes+a>this.options.maxPendingBytes)return this.rejectAdmission(new i("overflow",`Egress pending limit exceeded (${this.pending.length} items, ${this.pendingBytes} bytes)`));let t,k,c=new Promise((h,m)=>{t=h,k=m});return T(c),this.nextSequence+=1,this.pending.push({value:s,bytes:a,sequence:this.nextSequence,resolve:t,reject:k,completion:c}),this.pendingBytes+=a,this.startDrain(),{accepted:!0,completion:c}}flush(){if(this.failure){let c=Promise.reject(this.failure);return T(c),c}let s=this.nextSequence;if(s<=this.completedSequence)return Promise.resolve();let a,t,k=new Promise((c,h)=>{a=c,t=h});return T(k),this.flushWaiters.push({targetSequence:s,resolve:a,reject:t}),k}close(s){let a=s instanceof i?s:new i("closed","Egress was closed",{cause:s});this.fail(a)}stats(){return{closed:this.closed,pendingItems:this.pending.length,pendingBytes:this.pendingBytes}}handleAbort=()=>{this.fail(new i("aborted","Egress was aborted",{cause:this.options.signal?.reason}))};rejectAdmission(s){return this.fail(s),{accepted:!1,error:s}}startDrain(){if(this.draining||this.closed)return;this.draining=!0;let s=this.drain();T(s)}async drain(){try{while(!this.closed){let s=this.pending[0];if(!s)return;try{await this.writeOne(s.value)}catch(a){this.fail(this.normalizeWriteError(a));return}if(this.closed||this.pending[0]!==s)return;this.pending.shift(),this.pendingBytes-=s.bytes,this.completedSequence=s.sequence,s.resolve(),this.settleFlushWaiters()}}finally{if(this.draining=!1,!this.closed&&this.pending.length>0)this.startDrain()}}async writeOne(s){let a=new AbortController;this.activeWriteAbort=a;let t,k,c=new Promise((S,f)=>{k=f});T(c),this.activeWriteStop=k;let h=Promise.resolve().then(()=>this.options.write(s,a.signal));T(h);let m=new Promise((S,f)=>{t=setTimeout(()=>{let D=new i("write_timeout",`Egress write timed out after ${this.options.writeTimeoutMs}ms`);a.abort(D),f(D)},this.options.writeTimeoutMs),this.activeWriteTimeout=t});T(m);try{await Promise.race([h,m,c])}finally{if(t!==void 0)clearTimeout(t);if(this.activeWriteTimeout===t)this.activeWriteTimeout=void 0;if(this.activeWriteAbort===a)this.activeWriteAbort=void 0;if(this.activeWriteStop===k)this.activeWriteStop=void 0}}normalizeWriteError(s){if(s instanceof i)return s;return new i("write_failed","Egress write failed",{cause:s})}fail(s){if(this.closed)return;if(s.pendingItems??=this.pending.length,s.pendingBytes??=this.pendingBytes,this.closed=!0,this.failure=s,this.options.signal?.removeEventListener("abort",this.handleAbort),this.activeWriteTimeout!==void 0)clearTimeout(this.activeWriteTimeout),this.activeWriteTimeout=void 0;this.activeWriteAbort?.abort(s),this.activeWriteStop?.(s),this.activeWriteAbort=void 0,this.activeWriteStop=void 0;let a=this.pending.splice(0);this.pendingBytes=0;for(let t of a)t.reject(s);for(let t of this.flushWaiters.splice(0))t.reject(s);try{this.options.onFailure?.(s)}catch{}}settleFlushWaiters(){for(let s=0;s<this.flushWaiters.length;){let a=this.flushWaiters[s];if(a.targetSequence>this.completedSequence){s+=1;continue}this.flushWaiters.splice(s,1),a.resolve()}}assertPositiveInteger(s,a){if(!Number.isSafeInteger(s)||s<=0)throw RangeError(`${a} must be a positive safe integer`)}}
1
+ import{P as I}from"./chunk-yeq7qzdb.js";import{Qd as M}from"./chunk-najk5ty4.js";import P from"node:path";function w(s){let a=s.replace(/\s+/g," ").trim();return a.length<=72?a:`${a.slice(0,69)}...`}function W(s){let a=s.replace(/\s+/g," ").trim();return a.length<=500?a:`${a.slice(0,497)}...`}function A(s){return`task/${s.replace(/[^a-zA-Z0-9_-]/g,"-").slice(0,40)}`}class C{static async createSessionTask(s){if(!s.prompt.trim())throw Error("Task prompt must not be blank");if(!P.isAbsolute(s.sourceProjectPath))throw Error("Task source project path must be absolute");let a=P.resolve(s.sourceProjectPath),t;try{return t=s.isolation==="worktree"?await I.enter({sessionId:s.sessionId,workspaceRoot:a,name:A(s.sessionId)}):void 0,{metadata:await M.createSessionMetadata(s.sessionId,t?.workspaceRoot??a,{title:s.title?.trim()||w(s.prompt),taskPromptSummary:W(s.prompt),taskPriority:s.taskPriority,taskKind:s.taskKind,taskDueAt:s.taskDueAt,taskDispatch:s.dispatch,taskModelId:s.dispatch?.modelId,selectedModelId:s.dispatch?.modelId,permissionMode:s.dispatch?.permissionMode,reasoningEffort:s.dispatch?.reasoningEffort,serviceTier:s.dispatch?.serviceTier,responseVerbosity:s.dispatch?.responseVerbosity,communicationStyle:s.dispatch?.communicationStyle,communicationStyleDigest:s.dispatch?.communicationStyleDigest,projectInstructionsDigest:s.dispatch?.projectInstructionsDigest,taskRetriedFrom:s.retriedFrom,taskIsolation:s.isolation,taskSourceProjectPath:a,taskWorktree:t}),taskWorktree:t}}catch(k){if(t)await I.exit({sessionId:s.sessionId,action:"remove",discardChanges:!0}).catch(()=>{return});throw k}}}var $=256,V=8388608,x=30000;class i extends Error{kind;pendingItems;pendingBytes;constructor(s,a,t){super(a,t);this.kind=s;this.name="BoundedSerialEgressError",this.pendingItems=t?.pendingItems,this.pendingBytes=t?.pendingBytes}}function T(s){s.catch(()=>{return})}class K{options;pending=[];flushWaiters=[];pendingBytes=0;nextSequence=0;completedSequence=0;draining=!1;closed=!1;failure;activeWriteAbort;activeWriteStop;activeWriteTimeout;constructor(s){this.options=s;if(this.assertPositiveInteger(s.maxPendingItems,"maxPendingItems"),this.assertPositiveInteger(s.maxPendingBytes,"maxPendingBytes"),this.assertPositiveInteger(s.writeTimeoutMs,"writeTimeoutMs"),s.signal?.addEventListener("abort",this.handleAbort,{once:!0}),s.signal?.aborted)this.handleAbort()}offer(s){if(this.closed)return{accepted:!1,error:this.failure??new i("closed","Egress is already closed")};let a;try{a=this.options.sizeOf(s)}catch(h){return this.rejectAdmission(new i("invalid_size","Egress size calculation failed",{cause:h}))}if(!Number.isSafeInteger(a)||a<0)return this.rejectAdmission(new i("invalid_size","Egress size must be a non-negative safe integer"));if(a>this.options.maxPendingBytes)return this.rejectAdmission(new i("oversized",`Egress value requires ${a} bytes; limit is ${this.options.maxPendingBytes}`));if(this.pending.length>=this.options.maxPendingItems||this.pendingBytes+a>this.options.maxPendingBytes)return this.rejectAdmission(new i("overflow",`Egress pending limit exceeded (${this.pending.length} items, ${this.pendingBytes} bytes)`));let t,k,c=new Promise((h,m)=>{t=h,k=m});return T(c),this.nextSequence+=1,this.pending.push({value:s,bytes:a,sequence:this.nextSequence,resolve:t,reject:k,completion:c}),this.pendingBytes+=a,this.startDrain(),{accepted:!0,completion:c}}flush(){if(this.failure){let c=Promise.reject(this.failure);return T(c),c}let s=this.nextSequence;if(s<=this.completedSequence)return Promise.resolve();let a,t,k=new Promise((c,h)=>{a=c,t=h});return T(k),this.flushWaiters.push({targetSequence:s,resolve:a,reject:t}),k}close(s){let a=s instanceof i?s:new i("closed","Egress was closed",{cause:s});this.fail(a)}stats(){return{closed:this.closed,pendingItems:this.pending.length,pendingBytes:this.pendingBytes}}handleAbort=()=>{this.fail(new i("aborted","Egress was aborted",{cause:this.options.signal?.reason}))};rejectAdmission(s){return this.fail(s),{accepted:!1,error:s}}startDrain(){if(this.draining||this.closed)return;this.draining=!0;let s=this.drain();T(s)}async drain(){try{while(!this.closed){let s=this.pending[0];if(!s)return;try{await this.writeOne(s.value)}catch(a){this.fail(this.normalizeWriteError(a));return}if(this.closed||this.pending[0]!==s)return;this.pending.shift(),this.pendingBytes-=s.bytes,this.completedSequence=s.sequence,s.resolve(),this.settleFlushWaiters()}}finally{if(this.draining=!1,!this.closed&&this.pending.length>0)this.startDrain()}}async writeOne(s){let a=new AbortController;this.activeWriteAbort=a;let t,k,c=new Promise((S,f)=>{k=f});T(c),this.activeWriteStop=k;let h=Promise.resolve().then(()=>this.options.write(s,a.signal));T(h);let m=new Promise((S,f)=>{t=setTimeout(()=>{let D=new i("write_timeout",`Egress write timed out after ${this.options.writeTimeoutMs}ms`);a.abort(D),f(D)},this.options.writeTimeoutMs),this.activeWriteTimeout=t});T(m);try{await Promise.race([h,m,c])}finally{if(t!==void 0)clearTimeout(t);if(this.activeWriteTimeout===t)this.activeWriteTimeout=void 0;if(this.activeWriteAbort===a)this.activeWriteAbort=void 0;if(this.activeWriteStop===k)this.activeWriteStop=void 0}}normalizeWriteError(s){if(s instanceof i)return s;return new i("write_failed","Egress write failed",{cause:s})}fail(s){if(this.closed)return;if(s.pendingItems??=this.pending.length,s.pendingBytes??=this.pendingBytes,this.closed=!0,this.failure=s,this.options.signal?.removeEventListener("abort",this.handleAbort),this.activeWriteTimeout!==void 0)clearTimeout(this.activeWriteTimeout),this.activeWriteTimeout=void 0;this.activeWriteAbort?.abort(s),this.activeWriteStop?.(s),this.activeWriteAbort=void 0,this.activeWriteStop=void 0;let a=this.pending.splice(0);this.pendingBytes=0;for(let t of a)t.reject(s);for(let t of this.flushWaiters.splice(0))t.reject(s);try{this.options.onFailure?.(s)}catch{}}settleFlushWaiters(){for(let s=0;s<this.flushWaiters.length;){let a=this.flushWaiters[s];if(a.targetSequence>this.completedSequence){s+=1;continue}this.flushWaiters.splice(s,1),a.resolve()}}assertPositiveInteger(s,a){if(!Number.isSafeInteger(s)||s<=0)throw RangeError(`${a} must be a positive safe integer`)}}
2
2
  export{C as v,$ as w,V as x,x as y,i as z,K as A};
@@ -1,4 +1,4 @@
1
- import{m as yH,n as bH,o as IH,p as RH,q as gH,r as kH}from"./chunk-cpex23zk.js";import{A as ZH,v as TH,w as JH,x as KH,y as VH,z as p}from"./chunk-k9fveqq6.js";import{B as XH,V as GH,X as PH,Y as FH,aa as EH}from"./chunk-b0j9v359.js";import"./chunk-abd57h72.js";import"./chunk-xtb84adp.js";import"./chunk-xm8nyj5z.js";import{Db as UH,Mb as _H,rb as r}from"./chunk-0aa40zbs.js";import"./chunk-8hprmrd5.js";import{Fd as m,Qd as s,qd as jH,ud as xH}from"./chunk-wzmqkam9.js";import"./chunk-s0tq8gyx.js";import"./chunk-x3cxmwnz.js";import{oe as zH}from"./chunk-a7ejfmtc.js";import{qe as fH,re as AH,se as SH}from"./chunk-gxgq70gm.js";import{te as MH}from"./chunk-j2dyprdy.js";import"./chunk-z9gd9spf.js";import{Te as WH}from"./chunk-q6eb20fz.js";import"./chunk-v508x7cg.js";import"./chunk-dg0d3303.js";import"./chunk-rchz6j90.js";import"./chunk-w7hy5wh1.js";import"./chunk-2hb222re.js";import"./chunk-07w0qapm.js";import"./chunk-ywarj5j9.js";import{eg as qH}from"./chunk-kf7whgr7.js";import"./chunk-fva7jnjy.js";import"./chunk-41ympwz1.js";import"./chunk-aa5zmwd9.js";import"./chunk-41cg66y0.js";import"./chunk-f945dzj6.js";import{zh as DH}from"./chunk-sdbbyagy.js";import{Bh as LH,Dh as H,Eh as $H,Gh as N}from"./chunk-f3426b1c.js";import{Kh as i,Lh as o}from"./chunk-c475tfqf.js";import{Ph as k}from"./chunk-0hr050ck.js";import"./chunk-q69fzq4y.js";import"./chunk-n7mzxa8h.js";import"./chunk-s10pmnrd.js";import"./chunk-9p20hhs0.js";import"./chunk-14bs89sm.js";import"./chunk-wyhyw9rq.js";import"./chunk-rvk9r2cm.js";import"./chunk-tgdhsm5t.js";import"./chunk-fhfzdyba.js";import IJ from"yargs";import{hideBin as RJ}from"yargs/helpers";function v(K,V,Q){if(K.off){K.off(V,Q);return}K.removeListener?.(V,Q)}function dH(K,V){if(!K.once&&!K.on||!K.off&&!K.removeListener)throw Error("Writable returned false without an observable drain contract");return new Promise((Q,X)=>{let J=!1,Z=()=>{v(K,"drain",x),v(K,"error",j),V.removeEventListener("abort",P)},W=(F)=>{if(J)return;J=!0,Z(),F()},x=()=>W(Q),j=(F)=>W(()=>X(F??Error("Writable emitted an error"))),P=()=>W(()=>X(V.reason??Error("Writable drain aborted")));if(V.aborted){P();return}let T=K.once?.bind(K)??K.on?.bind(K);T?.("drain",x),T?.("error",j),V.addEventListener("abort",P,{once:!0})})}async function pH(K,V,Q){if(K.destroyed||K.writableEnded)throw Error("Writable is already closed");if(K.write(V)===!1)await dH(K,Q)}class l{options;queues;sinkErrorListeners=[];failed=!1;closing=!1;handleAbort=()=>{this.fail(new p("aborted","Headless output was aborted",{cause:this.options.signal?.reason}))};constructor(K,V={}){this.options=V;let Q=(X)=>new ZH({maxPendingItems:V.maxPendingItems??JH,maxPendingBytes:V.maxPendingBytes??KH,writeTimeoutMs:V.writeTimeoutMs??VH,sizeOf:(J)=>Buffer.byteLength(J),write:(J,Z)=>pH(K[X],J,Z),onFailure:(J)=>this.fail(J)});if(this.queues={stdout:Q("stdout"),stderr:Q("stderr")},this.observeSinkErrors(K.stdout),K.stderr!==K.stdout)this.observeSinkErrors(K.stderr);if(V.signal?.addEventListener("abort",this.handleAbort,{once:!0}),V.signal?.aborted)this.handleAbort()}write(K,V){return this.queues[K].offer(V).accepted}async flush(){await Promise.all([this.queues.stdout.flush(),this.queues.stderr.flush()])}close(K){if(this.closing||this.failed)return;this.closing=!0,this.options.signal?.removeEventListener("abort",this.handleAbort),this.removeSinkErrorListeners(),this.queues.stdout.close(K),this.queues.stderr.close(K)}stats(){return{stdout:this.queues.stdout.stats(),stderr:this.queues.stderr.stats()}}observeSinkErrors(K){if(!K.on||!K.off&&!K.removeListener)return;let V=(Q)=>{this.fail(new p("write_failed","Headless writable failed",{cause:Q??Error("Writable emitted an error")}))};K.on("error",V),this.sinkErrorListeners.push({writer:K,listener:V})}fail(K){if(this.closing||this.failed)return;this.failed=!0,this.options.signal?.removeEventListener("abort",this.handleAbort),this.removeSinkErrorListeners(),this.queues.stdout.close(K),this.queues.stderr.close(K),this.options.onFailure?.(K)}removeSinkErrorListeners(){for(let{writer:K,listener:V}of this.sinkErrorListeners.splice(0))v(K,"error",V)}}var YH=1;function D(K){return H.Object({event_version:H.Literal(YH),...K})}var vH=D({type:H.Literal("content_delta"),delta:H.String()}),lH=D({type:H.Literal("thinking_delta"),delta:H.String()}),aH=D({type:H.Literal("thinking"),content:H.String()}),iH=D({type:H.Literal("stream_end")}),oH=D({type:H.Literal("content"),content:H.String()}),sH=D({type:H.Literal("structured_output"),output:H.Record(H.String(),H.Unknown()),schema_digest:H.String({pattern:"^[a-f0-9]{64}$"})}),a=N(["readonly","write","execute"]),rH=H.Object({kind:a,scope:N(["global","session"]),queue_position:H.Integer({minimum:1}),in_flight:H.Integer({minimum:0}),limit:H.Integer({minimum:1})}),nH=D({type:H.Literal("tool_start"),tool_name:H.String(),summary:H.String(),target:H.Optional(H.String()),tool_kind:H.Optional(a)}),tH=D({type:H.Literal("tool_progress"),tool_name:H.String(),message:H.String(),progress:H.Optional(H.Number()),total:H.Optional(H.Number()),admission:H.Optional(rH)}),eH=H.Object({auto_backgrounded:H.Literal(!0),background_reason:H.Literal("foreground_budget"),foreground_budget_ms:H.Integer({minimum:1}),shell_id:H.String({minLength:1,maxLength:128,pattern:"^bash_[A-Za-z0-9-]+$"}),pid:H.Optional(H.Integer({minimum:1})),terminal_transport:N(["local","acp"])}),HJ=D({type:H.Literal("tool_result"),tool_name:H.String(),summary:H.String(),target:H.Optional(H.String()),tool_kind:H.Optional(a),success:H.Optional(H.Boolean()),error_type:H.Optional(H.String()),error_message:H.Optional(H.String()),background:H.Optional(eH)}),JJ=D({type:H.Literal("mcp_catalog_changed"),revision:H.Integer({minimum:1}),server_name:H.String(),added:H.Array(H.String()),removed:H.Array(H.String()),updated:H.Array(H.String())}),KJ=D({type:H.Literal("mcp_content_changed"),revision:H.Integer({minimum:1}),server_name:H.String(),content_kind:N(["resources","resource_templates","prompts"]),added:H.Array(H.String()),removed:H.Array(H.String()),updated:H.Array(H.String())}),VJ=D({type:H.Literal("mcp_resource_updated"),revision:H.Integer({minimum:1}),server_name:H.String(),uri:H.String()}),ZJ=D({type:H.Literal("mcp_connection_changed"),revision:H.Integer({minimum:1}),server_name:H.String(),phase:N(["reconnecting","recovered","failed"]),reason:H.String(),attempt:H.Integer({minimum:0}),max_attempts:H.Integer({minimum:0}),next_retry_at:H.Optional(H.Integer({minimum:0})),error:H.Optional(H.String())}),$J=D({type:H.Literal("mcp_log"),revision:H.Integer({minimum:1}),server_name:H.String(),level:N(["debug","info","notice","warning","error","critical","alert","emergency"]),logger:H.Optional(H.String()),message:H.String(),projected_bytes:H.Integer({minimum:0}),data_sha256:H.String(),truncated:H.Boolean(),details_omitted:H.Boolean(),timestamp:H.Integer({minimum:0}),synthetic:H.Optional(H.Boolean())}),qJ=D({type:H.Literal("mcp_instructions_changed"),revision:H.Integer({minimum:0}),server_name:H.String(),action:N(["added","removed"]),reason:N(["snapshot","connection","disconnection"]),text:H.Optional(H.String()),source_bytes:H.Optional(H.Integer({minimum:0})),projected_bytes:H.Optional(H.Integer({minimum:0})),sha256:H.Optional(H.String()),truncated:H.Optional(H.Boolean()),details_omitted:H.Optional(H.Boolean())}),XJ=D({type:H.Literal("mcp_task_changed"),revision:H.Integer({minimum:0}),task_id:H.String(),server_name:H.String(),tool_name:H.String(),status:N(["working","input_required","interrupted","completed","failed","cancelled"]),status_message:H.Optional(H.String()),created_at:H.Integer({minimum:0}),updated_at:H.Integer({minimum:0}),completed_at:H.Optional(H.Integer({minimum:0})),has_result:H.Boolean(),error:H.Optional(H.String())}),YJ=D({type:H.Literal("project_rules_loaded"),files:H.Array(H.Object({id:H.String(),relative_path:H.String(),source:N(["project","local"]),conditional:H.Boolean(),content_sha256:H.String({pattern:"^[a-f0-9]{64}$"})})),trigger_paths:H.Array(H.String()),blocked_write:H.Boolean()}),BJ=D({type:H.Literal("user_shell_started"),execution_id:H.String(),command:H.String(),auxiliary:H.Boolean()}),NJ=D({type:H.Literal("user_shell_output"),execution_id:H.String(),stream:N(["stdout","stderr"]),chunk:H.String(),stream_truncated:H.Boolean()}),QJ=D({type:H.Literal("user_shell_completed"),execution_id:H.String(),message_id:H.String(),status:N(["completed","failed","aborted","timed_out","spawn_error"]),exit_code:H.Union([H.Integer(),H.Null()]),duration_ms:H.Number({minimum:0}),stdout:H.String(),stderr:H.String(),truncated:H.Boolean(),auxiliary:H.Boolean()}),DJ=D({type:H.Literal("phase"),phase:N(["turn","searching","inspecting","target_hit","executing","completed"]),status:N(["ongoing","hit","done"]),message:H.String(),turn:H.Optional(H.Number()),tool_name:H.Optional(H.String()),target:H.Optional(H.String())}),LJ=D({type:H.Literal("tool_detail"),tool_name:H.String(),detail:H.String()}),WJ=D({type:H.Literal("task_update"),tasks:H.Array(XH)}),jJ=D({type:H.Literal("goal_frontier"),goal_id:H.String({minLength:1}),status:N(["active","verifying","paused","blocked","usage_limited","budget_limited","complete"]),task_list_id:H.String({minLength:1,maxLength:256}),total:H.Integer({minimum:0}),completed:H.Integer({minimum:0}),in_progress:H.Integer({minimum:0}),pending:H.Integer({minimum:0}),blocked:H.Integer({minimum:0}),next_task:H.Optional(H.Object({id:H.String({minLength:1}),subject:H.String({minLength:1,maxLength:512}),priority:N(["high","medium","low"])})),digest_sha256:H.String({pattern:"^[a-f0-9]{64}$"}),observed_at:H.String(),stall_category:H.Optional(N(["waiting_dependency","same_task_no_effect","repeated_deferral"])),stall_count:H.Optional(H.Integer({minimum:1,maximum:3}))}),xJ=D({type:H.Literal("goal"),state:N(["updated","cleared"]),goal_id:H.Optional(H.String()),status:H.Optional(N(["active","verifying","paused","blocked","usage_limited","budget_limited","complete"])),verification_attempt:H.Optional(H.Integer({minimum:1})),verification_status:H.Optional(N(["pending","pass","fail","partial"])),verifier_session_id:H.Optional(H.String()),verification_evidence_sha256:H.Optional(H.String({pattern:"^[a-f0-9]{64}$"})),verification_summary:H.Optional(H.String()),verification_stall_count:H.Optional(H.Integer({minimum:1})),premature_stop_pattern:H.Optional(N(qH)),premature_stop_count:H.Optional(H.Integer({minimum:1})),frontier_stall_category:H.Optional(N(["waiting_dependency","same_task_no_effect","repeated_deferral"])),frontier_stall_count:H.Optional(H.Integer({minimum:1,maximum:3}))}),UJ=D({type:H.Literal("subagent"),state:N(["spawned","completed"]),session_id:H.String(),subagent_type:H.Optional(H.String()),success:H.Optional(H.Boolean()),summary:H.Optional(H.String()),verification_verdict:H.Optional(N(["pass","fail","partial"])),resumed_from:H.Optional(H.String()),root_agent_id:H.Optional(H.String()),resume_depth:H.Optional(H.Integer({minimum:0}))}),_J=D({type:H.Literal("token_usage"),input_tokens:H.Number(),output_tokens:H.Number(),total_tokens:H.Number(),max_context_tokens:H.Number(),cache_read_tokens:H.Optional(H.Number()),cache_write_tokens:H.Optional(H.Number()),prompt_cache_break:H.Optional(H.Object({reason:N(["model_changed","system_prompt_changed","tools_changed","request_policy_changed","ttl_expired","server_side"]),previous_cache_read_tokens:H.Number(),cache_read_tokens:H.Number(),cache_write_tokens:H.Number(),token_drop:H.Number(),elapsed_ms:H.Number(),call_number:H.Number(),system_prompt_changed:H.Boolean(),system_char_delta:H.Number(),tools_changed:H.Boolean(),added_tool_count:H.Number(),removed_tool_count:H.Number(),changed_tool_count:H.Number(),model_changed:H.Boolean(),request_policy_changed:H.Boolean()})),cost_usd:H.Optional(H.Number())}),GJ=D({type:H.Literal("compacting"),state:N(["started","completed"]),reason:H.Optional(N(["threshold","context_limit","turn_limit","manual"])),strategy:H.Optional(N(["llm","fallback","snip"])),outcome:H.Optional(N(["completed","fallback","failed"])),pre_tokens:H.Optional(H.Number({minimum:0})),pre_token_source:H.Optional(N(["provider","provider_plus_estimate","local_estimate"])),estimated_pending_tokens:H.Optional(H.Number({minimum:0})),post_tokens:H.Optional(H.Number({minimum:0})),sample_attempts:H.Optional(H.Integer({minimum:0})),input_reductions:H.Optional(H.Integer({minimum:0})),messages_omitted:H.Optional(H.Integer({minimum:0})),files_omitted:H.Optional(H.Integer({minimum:0})),images_omitted:H.Optional(H.Integer({minimum:0})),fallback_target_tokens:H.Optional(H.Integer({minimum:0})),fallback_messages_omitted:H.Optional(H.Integer({minimum:0})),fallback_messages_truncated:H.Optional(H.Integer({minimum:0})),failure_reason:H.Optional(N(["circuit_open","context_exhausted","deterministic","empty_exhausted","insufficient_reduction","transient_exhausted"]))}),PJ=D({type:H.Literal("provider_retry"),phase:N(["scheduled","waiting","attempt","recovered","exhausted"]),attempt:H.Integer({minimum:0}),max_retries:H.Integer({minimum:0}),reason:N(["rate_limit","server_error","timeout","transport","stream_closed"]),status_code:H.Optional(H.Integer({minimum:100,maximum:599})),delay_ms:H.Optional(H.Integer({minimum:0})),next_retry_at:H.Optional(H.Integer({minimum:0})),mode:H.Optional(N(["standard","bounded_foreground"])),recovery_budget_ms:H.Optional(H.Integer({minimum:0})),recovery_elapsed_ms:H.Optional(H.Integer({minimum:0})),recovery_remaining_ms:H.Optional(H.Integer({minimum:0})),exhausted_by:H.Optional(N(["attempt_limit","recovery_budget"]))}),FJ=D({type:H.Literal("provider_admission"),phase:N(["queued","admitted","rejected"]),request_class:N(["foreground","background","internal"]),resource:N(["stream","pending_count","pending_bytes"]),scope:N(["global","domain","owner","class"]),reason:H.Optional(N(["capacity","queue_full","wait_timeout","closed"])),queue_position:H.Integer({minimum:0}),queue_depth:H.Integer({minimum:0}),in_flight:H.Integer({minimum:0}),limit:H.Integer({minimum:0}),wait_ms:H.Integer({minimum:0}),max_wait_ms:H.Integer({minimum:0}),recovery_remaining_ms:H.Optional(H.Integer({minimum:0}))}),EJ=D({type:H.Literal("provider_circuit"),phase:N(["opened","waiting","probe","closed","reopened","rejected"]),reason:N(["rate_limit","server_error","transport","stream_closed"]),status_code:H.Optional(H.Integer({minimum:100,maximum:599})),retry_after_ms:H.Optional(H.Integer({minimum:0})),next_probe_at:H.Optional(H.Integer({minimum:0})),open_duration_ms:H.Integer({minimum:0}),sample_count:H.Optional(H.Integer({minimum:0})),failure_count:H.Optional(H.Integer({minimum:0})),recovery_remaining_ms:H.Optional(H.Integer({minimum:0}))}),MJ=D({type:H.Literal("provider_stall"),phase:N(["detected","recovered"]),stall_count:H.Integer({minimum:1}),duration_ms:H.Integer({minimum:0}),warning_after_ms:H.Integer({minimum:1}),timeout_ms:H.Integer({minimum:1}),output_started:H.Boolean()}),zJ=D({type:H.Literal("action_stationarity"),phase:N(["detected","recovered","halted"]),tool_name:H.String(),run_length:H.Integer({minimum:1}),nudge_threshold:H.Integer({minimum:1}),halt_threshold:H.Integer({minimum:1}),progress_aware:H.Boolean()}),fJ=D({type:H.Literal("turn_recovery"),state:N(["completed","resumable","requires_attention"]),turn_id:H.String({minLength:1}),input_message_count:H.Integer({minimum:0}),reason:H.Optional(N(["successful_tool_result","interrupted_tool_call"]))}),AJ=D({type:H.Literal("turn_limit"),turns_count:H.Number(),action:H.Literal("continue")}),SJ=D({type:H.Literal("task_session"),session_id:H.String(),project_path:H.String(),source_project_path:H.String(),isolation:N(["local","worktree"]),worktree_branch:H.Optional(H.String()),base_commit:H.Optional(H.String())}),TJ=D({type:H.Literal("task_admission"),state:N(["queued","running"]),queue_position:H.Optional(H.Integer({minimum:1})),queue_depth:H.Integer({minimum:0}),in_flight:H.Integer({minimum:0}),max_concurrent_tasks:H.Integer({minimum:1})}),yJ=D({type:H.Literal("output"),content:H.String(),exit_code:H.Number()}),bJ=D({type:H.Literal("error"),message:H.String()}),eJ=$H(H.Union([vH,lH,aH,iH,oH,sH,nH,tH,HJ,JJ,KJ,VJ,ZJ,$J,qJ,XJ,YJ,BJ,NJ,QJ,DJ,LJ,WJ,jJ,xJ,UJ,_J,GJ,FJ,EJ,PJ,MJ,zJ,fJ,AJ,SJ,TJ,yJ,bJ]));function BH(K,V){return{event_version:YH,type:K,...V}}function gJ(K){if(!K||typeof K!=="object"||Array.isArray(K))return;let V=K;if(V.auto_backgrounded!==!0||V.background_reason!=="foreground_budget"||!Number.isSafeInteger(V.foreground_budget_ms)||V.foreground_budget_ms<=0||typeof V.shell_id!=="string"||!/^bash_[A-Za-z0-9-]+$/.test(V.shell_id)||V.shell_id.length>128||V.terminal_transport!=="local"&&V.terminal_transport!=="acp"||V.pid!==void 0&&(!Number.isSafeInteger(V.pid)||V.pid<=0))return;return{auto_backgrounded:!0,background_reason:"foreground_budget",foreground_budget_ms:V.foreground_budget_ms,shell_id:V.shell_id,...V.pid===void 0?{}:{pid:V.pid},terminal_transport:V.terminal_transport}}function kJ(K){let V=new AbortController,Q=(Z)=>{if(!V.signal.aborted)V.abort(Z)},X=()=>Q("interrupt"),J=()=>Q(K?.signal?.reason);if(K?.signal){if(K.signal.addEventListener("abort",J,{once:!0}),K.signal.aborted)J()}else process.once("SIGINT",X),process.once("SIGTERM",X);return{signal:V.signal,abort:Q,dispose:()=>{K?.signal?.removeEventListener("abort",J),process.removeListener("SIGINT",X),process.removeListener("SIGTERM",X)}}}var CJ=N(["text","jsonl"]),hJ=H.Object({headless:H.Optional(H.Boolean()),message:H.Optional(H.String()),_:H.Optional(H.Array(H.Union([H.String(),H.Number()]))),model:H.Optional(H.String()),systemPrompt:H.Optional(H.String()),appendSystemPrompt:H.Optional(H.String()),verificationAgent:H.Optional(H.Boolean()),maxTurns:H.Optional(H.Refine(H.Integer(),(K)=>K===-1||K>0,()=>"must be -1 (unlimited) or a positive integer")),permissionMode:H.Optional(H.Enum(DH)),mcpConfig:H.Optional(H.Array(H.String())),strictMcpConfig:H.Optional(H.Boolean()),sessionId:H.Optional(H.String()),allowedTools:H.Optional(H.Array(H.String())),disallowedTools:H.Optional(H.Array(H.String())),agents:H.Optional(H.String()),continue:H.Optional(H.Boolean()),resume:H.Optional(H.Union([H.String(),H.Boolean()])),forkSession:H.Optional(H.Boolean()),taskIsolation:H.Optional(N(["local","worktree"])),outputFormat:H.Optional(CJ),jsonSchema:H.Optional(H.String()),outputSchema:H.Optional(H.String())});class CH{openedThinking=!1;wroteAssistantContent=!1;markAssistantContent(){this.wroteAssistantContent=!0}setThinkingOpened(K){this.openedThinking=K}hasOpenThinking(){return this.openedThinking}completeStream(){let K={openedThinking:this.openedThinking,wroteAssistantContent:this.wroteAssistantContent};return this.openedThinking=!1,this.wroteAssistantContent=!1,K}}function OJ(K){return K.issues.map((V)=>`${V.path.join(".")||"options"}: ${V.message}`).join("; ")}function wJ(K){let V=LH(hJ,K);if(!V.success)throw Error(`Invalid headless options: ${OJ(V.error)}`);return V.data}function mJ(K){return K.command("* [message]","Run full agent loop without Ink UI and print events to the terminal",(V)=>V.positional("message",{describe:"Message to process",type:"string"}).option("headless",{type:"boolean",describe:"Run full agent loop without Ink UI and print events to the terminal"}).option("model",{describe:"Model ID for this run",type:"string"}).option("system-prompt",{describe:"Replace the default system prompt",type:"string"}).option("append-system-prompt",{describe:"Append a system prompt to the default system prompt",type:"string"}).option("verification-agent",{describe:"Run the built-in independent verification agent after non-trivial changes",type:"boolean",default:!0}).option("max-turns",{alias:["maxTurns"],describe:"Maximum conversation turns (-1: unlimited, N>0: limit to N turns)",type:"number"}).option("output-format",{alias:["outputFormat"],choices:["text","jsonl"],describe:"Headless output format",type:"string"}).option("json-schema",{alias:["jsonSchema"],describe:"Inline JSON Schema for the structured final response",type:"string"}).option("output-schema",{alias:["outputSchema"],describe:"Path to a JSON Schema file for the structured final response",type:"string"}).option("task-isolation",{alias:["taskIsolation"],choices:["local","worktree"],describe:"Dispatch a new durable task in the selected workspace mode",type:"string"}),async(V)=>{if(!V.headless)return;let Q=await lJ(V);process.exit(Q)})}function L(K,V=""){K.write(`${V}
1
+ import{m as yH,n as bH,o as IH,p as RH,q as gH,r as kH}from"./chunk-26t2mg1v.js";import{A as ZH,v as TH,w as JH,x as KH,y as VH,z as p}from"./chunk-xvg14dkr.js";import{B as XH,V as GH,X as PH,Y as FH,aa as EH}from"./chunk-yeq7qzdb.js";import"./chunk-abd57h72.js";import"./chunk-p6prp8zc.js";import"./chunk-xm8nyj5z.js";import{Db as UH,Mb as _H,rb as r}from"./chunk-8hp650gn.js";import"./chunk-8hprmrd5.js";import{Fd as m,Qd as s,qd as jH,ud as xH}from"./chunk-najk5ty4.js";import"./chunk-s0tq8gyx.js";import"./chunk-x3cxmwnz.js";import{oe as zH}from"./chunk-djqbqaxn.js";import{qe as fH,re as AH,se as SH}from"./chunk-szdz1jmj.js";import{te as MH}from"./chunk-j2dyprdy.js";import"./chunk-z9gd9spf.js";import{Te as WH}from"./chunk-5y38cfk9.js";import"./chunk-v508x7cg.js";import"./chunk-dg0d3303.js";import"./chunk-rchz6j90.js";import"./chunk-w7hy5wh1.js";import"./chunk-2hb222re.js";import"./chunk-p39mmmbt.js";import"./chunk-151cz9k4.js";import{eg as qH}from"./chunk-kf7whgr7.js";import"./chunk-fva7jnjy.js";import"./chunk-41ympwz1.js";import"./chunk-6j482w6k.js";import"./chunk-41cg66y0.js";import"./chunk-139frcak.js";import{zh as DH}from"./chunk-sdbbyagy.js";import{Bh as LH,Dh as H,Eh as $H,Gh as N}from"./chunk-f3426b1c.js";import{Kh as i,Lh as o}from"./chunk-c475tfqf.js";import{Ph as k}from"./chunk-0hr050ck.js";import"./chunk-q69fzq4y.js";import"./chunk-n7mzxa8h.js";import"./chunk-s10pmnrd.js";import"./chunk-9p20hhs0.js";import"./chunk-4bwr3rcj.js";import"./chunk-wyhyw9rq.js";import"./chunk-rvk9r2cm.js";import"./chunk-tgdhsm5t.js";import"./chunk-fhfzdyba.js";import IJ from"yargs";import{hideBin as RJ}from"yargs/helpers";function v(K,V,Q){if(K.off){K.off(V,Q);return}K.removeListener?.(V,Q)}function dH(K,V){if(!K.once&&!K.on||!K.off&&!K.removeListener)throw Error("Writable returned false without an observable drain contract");return new Promise((Q,X)=>{let J=!1,Z=()=>{v(K,"drain",x),v(K,"error",j),V.removeEventListener("abort",P)},W=(F)=>{if(J)return;J=!0,Z(),F()},x=()=>W(Q),j=(F)=>W(()=>X(F??Error("Writable emitted an error"))),P=()=>W(()=>X(V.reason??Error("Writable drain aborted")));if(V.aborted){P();return}let T=K.once?.bind(K)??K.on?.bind(K);T?.("drain",x),T?.("error",j),V.addEventListener("abort",P,{once:!0})})}async function pH(K,V,Q){if(K.destroyed||K.writableEnded)throw Error("Writable is already closed");if(K.write(V)===!1)await dH(K,Q)}class l{options;queues;sinkErrorListeners=[];failed=!1;closing=!1;handleAbort=()=>{this.fail(new p("aborted","Headless output was aborted",{cause:this.options.signal?.reason}))};constructor(K,V={}){this.options=V;let Q=(X)=>new ZH({maxPendingItems:V.maxPendingItems??JH,maxPendingBytes:V.maxPendingBytes??KH,writeTimeoutMs:V.writeTimeoutMs??VH,sizeOf:(J)=>Buffer.byteLength(J),write:(J,Z)=>pH(K[X],J,Z),onFailure:(J)=>this.fail(J)});if(this.queues={stdout:Q("stdout"),stderr:Q("stderr")},this.observeSinkErrors(K.stdout),K.stderr!==K.stdout)this.observeSinkErrors(K.stderr);if(V.signal?.addEventListener("abort",this.handleAbort,{once:!0}),V.signal?.aborted)this.handleAbort()}write(K,V){return this.queues[K].offer(V).accepted}async flush(){await Promise.all([this.queues.stdout.flush(),this.queues.stderr.flush()])}close(K){if(this.closing||this.failed)return;this.closing=!0,this.options.signal?.removeEventListener("abort",this.handleAbort),this.removeSinkErrorListeners(),this.queues.stdout.close(K),this.queues.stderr.close(K)}stats(){return{stdout:this.queues.stdout.stats(),stderr:this.queues.stderr.stats()}}observeSinkErrors(K){if(!K.on||!K.off&&!K.removeListener)return;let V=(Q)=>{this.fail(new p("write_failed","Headless writable failed",{cause:Q??Error("Writable emitted an error")}))};K.on("error",V),this.sinkErrorListeners.push({writer:K,listener:V})}fail(K){if(this.closing||this.failed)return;this.failed=!0,this.options.signal?.removeEventListener("abort",this.handleAbort),this.removeSinkErrorListeners(),this.queues.stdout.close(K),this.queues.stderr.close(K),this.options.onFailure?.(K)}removeSinkErrorListeners(){for(let{writer:K,listener:V}of this.sinkErrorListeners.splice(0))v(K,"error",V)}}var YH=1;function D(K){return H.Object({event_version:H.Literal(YH),...K})}var vH=D({type:H.Literal("content_delta"),delta:H.String()}),lH=D({type:H.Literal("thinking_delta"),delta:H.String()}),aH=D({type:H.Literal("thinking"),content:H.String()}),iH=D({type:H.Literal("stream_end")}),oH=D({type:H.Literal("content"),content:H.String()}),sH=D({type:H.Literal("structured_output"),output:H.Record(H.String(),H.Unknown()),schema_digest:H.String({pattern:"^[a-f0-9]{64}$"})}),a=N(["readonly","write","execute"]),rH=H.Object({kind:a,scope:N(["global","session"]),queue_position:H.Integer({minimum:1}),in_flight:H.Integer({minimum:0}),limit:H.Integer({minimum:1})}),nH=D({type:H.Literal("tool_start"),tool_name:H.String(),summary:H.String(),target:H.Optional(H.String()),tool_kind:H.Optional(a)}),tH=D({type:H.Literal("tool_progress"),tool_name:H.String(),message:H.String(),progress:H.Optional(H.Number()),total:H.Optional(H.Number()),admission:H.Optional(rH)}),eH=H.Object({auto_backgrounded:H.Literal(!0),background_reason:H.Literal("foreground_budget"),foreground_budget_ms:H.Integer({minimum:1}),shell_id:H.String({minLength:1,maxLength:128,pattern:"^bash_[A-Za-z0-9-]+$"}),pid:H.Optional(H.Integer({minimum:1})),terminal_transport:N(["local","acp"])}),HJ=D({type:H.Literal("tool_result"),tool_name:H.String(),summary:H.String(),target:H.Optional(H.String()),tool_kind:H.Optional(a),success:H.Optional(H.Boolean()),error_type:H.Optional(H.String()),error_message:H.Optional(H.String()),background:H.Optional(eH)}),JJ=D({type:H.Literal("mcp_catalog_changed"),revision:H.Integer({minimum:1}),server_name:H.String(),added:H.Array(H.String()),removed:H.Array(H.String()),updated:H.Array(H.String())}),KJ=D({type:H.Literal("mcp_content_changed"),revision:H.Integer({minimum:1}),server_name:H.String(),content_kind:N(["resources","resource_templates","prompts"]),added:H.Array(H.String()),removed:H.Array(H.String()),updated:H.Array(H.String())}),VJ=D({type:H.Literal("mcp_resource_updated"),revision:H.Integer({minimum:1}),server_name:H.String(),uri:H.String()}),ZJ=D({type:H.Literal("mcp_connection_changed"),revision:H.Integer({minimum:1}),server_name:H.String(),phase:N(["reconnecting","recovered","failed"]),reason:H.String(),attempt:H.Integer({minimum:0}),max_attempts:H.Integer({minimum:0}),next_retry_at:H.Optional(H.Integer({minimum:0})),error:H.Optional(H.String())}),$J=D({type:H.Literal("mcp_log"),revision:H.Integer({minimum:1}),server_name:H.String(),level:N(["debug","info","notice","warning","error","critical","alert","emergency"]),logger:H.Optional(H.String()),message:H.String(),projected_bytes:H.Integer({minimum:0}),data_sha256:H.String(),truncated:H.Boolean(),details_omitted:H.Boolean(),timestamp:H.Integer({minimum:0}),synthetic:H.Optional(H.Boolean())}),qJ=D({type:H.Literal("mcp_instructions_changed"),revision:H.Integer({minimum:0}),server_name:H.String(),action:N(["added","removed"]),reason:N(["snapshot","connection","disconnection"]),text:H.Optional(H.String()),source_bytes:H.Optional(H.Integer({minimum:0})),projected_bytes:H.Optional(H.Integer({minimum:0})),sha256:H.Optional(H.String()),truncated:H.Optional(H.Boolean()),details_omitted:H.Optional(H.Boolean())}),XJ=D({type:H.Literal("mcp_task_changed"),revision:H.Integer({minimum:0}),task_id:H.String(),server_name:H.String(),tool_name:H.String(),status:N(["working","input_required","interrupted","completed","failed","cancelled"]),status_message:H.Optional(H.String()),created_at:H.Integer({minimum:0}),updated_at:H.Integer({minimum:0}),completed_at:H.Optional(H.Integer({minimum:0})),has_result:H.Boolean(),error:H.Optional(H.String())}),YJ=D({type:H.Literal("project_rules_loaded"),files:H.Array(H.Object({id:H.String(),relative_path:H.String(),source:N(["project","local"]),conditional:H.Boolean(),content_sha256:H.String({pattern:"^[a-f0-9]{64}$"})})),trigger_paths:H.Array(H.String()),blocked_write:H.Boolean()}),BJ=D({type:H.Literal("user_shell_started"),execution_id:H.String(),command:H.String(),auxiliary:H.Boolean()}),NJ=D({type:H.Literal("user_shell_output"),execution_id:H.String(),stream:N(["stdout","stderr"]),chunk:H.String(),stream_truncated:H.Boolean()}),QJ=D({type:H.Literal("user_shell_completed"),execution_id:H.String(),message_id:H.String(),status:N(["completed","failed","aborted","timed_out","spawn_error"]),exit_code:H.Union([H.Integer(),H.Null()]),duration_ms:H.Number({minimum:0}),stdout:H.String(),stderr:H.String(),truncated:H.Boolean(),auxiliary:H.Boolean()}),DJ=D({type:H.Literal("phase"),phase:N(["turn","searching","inspecting","target_hit","executing","completed"]),status:N(["ongoing","hit","done"]),message:H.String(),turn:H.Optional(H.Number()),tool_name:H.Optional(H.String()),target:H.Optional(H.String())}),LJ=D({type:H.Literal("tool_detail"),tool_name:H.String(),detail:H.String()}),WJ=D({type:H.Literal("task_update"),tasks:H.Array(XH)}),jJ=D({type:H.Literal("goal_frontier"),goal_id:H.String({minLength:1}),status:N(["active","verifying","paused","blocked","usage_limited","budget_limited","complete"]),task_list_id:H.String({minLength:1,maxLength:256}),total:H.Integer({minimum:0}),completed:H.Integer({minimum:0}),in_progress:H.Integer({minimum:0}),pending:H.Integer({minimum:0}),blocked:H.Integer({minimum:0}),next_task:H.Optional(H.Object({id:H.String({minLength:1}),subject:H.String({minLength:1,maxLength:512}),priority:N(["high","medium","low"])})),digest_sha256:H.String({pattern:"^[a-f0-9]{64}$"}),observed_at:H.String(),stall_category:H.Optional(N(["waiting_dependency","same_task_no_effect","repeated_deferral"])),stall_count:H.Optional(H.Integer({minimum:1,maximum:3}))}),xJ=D({type:H.Literal("goal"),state:N(["updated","cleared"]),goal_id:H.Optional(H.String()),status:H.Optional(N(["active","verifying","paused","blocked","usage_limited","budget_limited","complete"])),verification_attempt:H.Optional(H.Integer({minimum:1})),verification_status:H.Optional(N(["pending","pass","fail","partial"])),verifier_session_id:H.Optional(H.String()),verification_evidence_sha256:H.Optional(H.String({pattern:"^[a-f0-9]{64}$"})),verification_summary:H.Optional(H.String()),verification_stall_count:H.Optional(H.Integer({minimum:1})),premature_stop_pattern:H.Optional(N(qH)),premature_stop_count:H.Optional(H.Integer({minimum:1})),frontier_stall_category:H.Optional(N(["waiting_dependency","same_task_no_effect","repeated_deferral"])),frontier_stall_count:H.Optional(H.Integer({minimum:1,maximum:3}))}),UJ=D({type:H.Literal("subagent"),state:N(["spawned","completed"]),session_id:H.String(),subagent_type:H.Optional(H.String()),success:H.Optional(H.Boolean()),summary:H.Optional(H.String()),verification_verdict:H.Optional(N(["pass","fail","partial"])),resumed_from:H.Optional(H.String()),root_agent_id:H.Optional(H.String()),resume_depth:H.Optional(H.Integer({minimum:0}))}),_J=D({type:H.Literal("token_usage"),input_tokens:H.Number(),output_tokens:H.Number(),total_tokens:H.Number(),max_context_tokens:H.Number(),cache_read_tokens:H.Optional(H.Number()),cache_write_tokens:H.Optional(H.Number()),prompt_cache_break:H.Optional(H.Object({reason:N(["model_changed","system_prompt_changed","tools_changed","request_policy_changed","ttl_expired","server_side"]),previous_cache_read_tokens:H.Number(),cache_read_tokens:H.Number(),cache_write_tokens:H.Number(),token_drop:H.Number(),elapsed_ms:H.Number(),call_number:H.Number(),system_prompt_changed:H.Boolean(),system_char_delta:H.Number(),tools_changed:H.Boolean(),added_tool_count:H.Number(),removed_tool_count:H.Number(),changed_tool_count:H.Number(),model_changed:H.Boolean(),request_policy_changed:H.Boolean()})),cost_usd:H.Optional(H.Number())}),GJ=D({type:H.Literal("compacting"),state:N(["started","completed"]),reason:H.Optional(N(["threshold","context_limit","turn_limit","manual"])),strategy:H.Optional(N(["llm","fallback","snip"])),outcome:H.Optional(N(["completed","fallback","failed"])),pre_tokens:H.Optional(H.Number({minimum:0})),pre_token_source:H.Optional(N(["provider","provider_plus_estimate","local_estimate"])),estimated_pending_tokens:H.Optional(H.Number({minimum:0})),post_tokens:H.Optional(H.Number({minimum:0})),sample_attempts:H.Optional(H.Integer({minimum:0})),input_reductions:H.Optional(H.Integer({minimum:0})),messages_omitted:H.Optional(H.Integer({minimum:0})),files_omitted:H.Optional(H.Integer({minimum:0})),images_omitted:H.Optional(H.Integer({minimum:0})),fallback_target_tokens:H.Optional(H.Integer({minimum:0})),fallback_messages_omitted:H.Optional(H.Integer({minimum:0})),fallback_messages_truncated:H.Optional(H.Integer({minimum:0})),failure_reason:H.Optional(N(["circuit_open","context_exhausted","deterministic","empty_exhausted","insufficient_reduction","transient_exhausted"]))}),PJ=D({type:H.Literal("provider_retry"),phase:N(["scheduled","waiting","attempt","recovered","exhausted"]),attempt:H.Integer({minimum:0}),max_retries:H.Integer({minimum:0}),reason:N(["rate_limit","server_error","timeout","transport","stream_closed"]),status_code:H.Optional(H.Integer({minimum:100,maximum:599})),delay_ms:H.Optional(H.Integer({minimum:0})),next_retry_at:H.Optional(H.Integer({minimum:0})),mode:H.Optional(N(["standard","bounded_foreground"])),recovery_budget_ms:H.Optional(H.Integer({minimum:0})),recovery_elapsed_ms:H.Optional(H.Integer({minimum:0})),recovery_remaining_ms:H.Optional(H.Integer({minimum:0})),exhausted_by:H.Optional(N(["attempt_limit","recovery_budget"]))}),FJ=D({type:H.Literal("provider_admission"),phase:N(["queued","admitted","rejected"]),request_class:N(["foreground","background","internal"]),resource:N(["stream","pending_count","pending_bytes"]),scope:N(["global","domain","owner","class"]),reason:H.Optional(N(["capacity","queue_full","wait_timeout","closed"])),queue_position:H.Integer({minimum:0}),queue_depth:H.Integer({minimum:0}),in_flight:H.Integer({minimum:0}),limit:H.Integer({minimum:0}),wait_ms:H.Integer({minimum:0}),max_wait_ms:H.Integer({minimum:0}),recovery_remaining_ms:H.Optional(H.Integer({minimum:0}))}),EJ=D({type:H.Literal("provider_circuit"),phase:N(["opened","waiting","probe","closed","reopened","rejected"]),reason:N(["rate_limit","server_error","transport","stream_closed"]),status_code:H.Optional(H.Integer({minimum:100,maximum:599})),retry_after_ms:H.Optional(H.Integer({minimum:0})),next_probe_at:H.Optional(H.Integer({minimum:0})),open_duration_ms:H.Integer({minimum:0}),sample_count:H.Optional(H.Integer({minimum:0})),failure_count:H.Optional(H.Integer({minimum:0})),recovery_remaining_ms:H.Optional(H.Integer({minimum:0}))}),MJ=D({type:H.Literal("provider_stall"),phase:N(["detected","recovered"]),stall_count:H.Integer({minimum:1}),duration_ms:H.Integer({minimum:0}),warning_after_ms:H.Integer({minimum:1}),timeout_ms:H.Integer({minimum:1}),output_started:H.Boolean()}),zJ=D({type:H.Literal("action_stationarity"),phase:N(["detected","recovered","halted"]),tool_name:H.String(),run_length:H.Integer({minimum:1}),nudge_threshold:H.Integer({minimum:1}),halt_threshold:H.Integer({minimum:1}),progress_aware:H.Boolean()}),fJ=D({type:H.Literal("turn_recovery"),state:N(["completed","resumable","requires_attention"]),turn_id:H.String({minLength:1}),input_message_count:H.Integer({minimum:0}),reason:H.Optional(N(["successful_tool_result","interrupted_tool_call"]))}),AJ=D({type:H.Literal("turn_limit"),turns_count:H.Number(),action:H.Literal("continue")}),SJ=D({type:H.Literal("task_session"),session_id:H.String(),project_path:H.String(),source_project_path:H.String(),isolation:N(["local","worktree"]),worktree_branch:H.Optional(H.String()),base_commit:H.Optional(H.String())}),TJ=D({type:H.Literal("task_admission"),state:N(["queued","running"]),queue_position:H.Optional(H.Integer({minimum:1})),queue_depth:H.Integer({minimum:0}),in_flight:H.Integer({minimum:0}),max_concurrent_tasks:H.Integer({minimum:1})}),yJ=D({type:H.Literal("output"),content:H.String(),exit_code:H.Number()}),bJ=D({type:H.Literal("error"),message:H.String()}),eJ=$H(H.Union([vH,lH,aH,iH,oH,sH,nH,tH,HJ,JJ,KJ,VJ,ZJ,$J,qJ,XJ,YJ,BJ,NJ,QJ,DJ,LJ,WJ,jJ,xJ,UJ,_J,GJ,FJ,EJ,PJ,MJ,zJ,fJ,AJ,SJ,TJ,yJ,bJ]));function BH(K,V){return{event_version:YH,type:K,...V}}function gJ(K){if(!K||typeof K!=="object"||Array.isArray(K))return;let V=K;if(V.auto_backgrounded!==!0||V.background_reason!=="foreground_budget"||!Number.isSafeInteger(V.foreground_budget_ms)||V.foreground_budget_ms<=0||typeof V.shell_id!=="string"||!/^bash_[A-Za-z0-9-]+$/.test(V.shell_id)||V.shell_id.length>128||V.terminal_transport!=="local"&&V.terminal_transport!=="acp"||V.pid!==void 0&&(!Number.isSafeInteger(V.pid)||V.pid<=0))return;return{auto_backgrounded:!0,background_reason:"foreground_budget",foreground_budget_ms:V.foreground_budget_ms,shell_id:V.shell_id,...V.pid===void 0?{}:{pid:V.pid},terminal_transport:V.terminal_transport}}function kJ(K){let V=new AbortController,Q=(Z)=>{if(!V.signal.aborted)V.abort(Z)},X=()=>Q("interrupt"),J=()=>Q(K?.signal?.reason);if(K?.signal){if(K.signal.addEventListener("abort",J,{once:!0}),K.signal.aborted)J()}else process.once("SIGINT",X),process.once("SIGTERM",X);return{signal:V.signal,abort:Q,dispose:()=>{K?.signal?.removeEventListener("abort",J),process.removeListener("SIGINT",X),process.removeListener("SIGTERM",X)}}}var CJ=N(["text","jsonl"]),hJ=H.Object({headless:H.Optional(H.Boolean()),message:H.Optional(H.String()),_:H.Optional(H.Array(H.Union([H.String(),H.Number()]))),model:H.Optional(H.String()),systemPrompt:H.Optional(H.String()),appendSystemPrompt:H.Optional(H.String()),verificationAgent:H.Optional(H.Boolean()),maxTurns:H.Optional(H.Refine(H.Integer(),(K)=>K===-1||K>0,()=>"must be -1 (unlimited) or a positive integer")),permissionMode:H.Optional(H.Enum(DH)),mcpConfig:H.Optional(H.Array(H.String())),strictMcpConfig:H.Optional(H.Boolean()),sessionId:H.Optional(H.String()),allowedTools:H.Optional(H.Array(H.String())),disallowedTools:H.Optional(H.Array(H.String())),agents:H.Optional(H.String()),continue:H.Optional(H.Boolean()),resume:H.Optional(H.Union([H.String(),H.Boolean()])),forkSession:H.Optional(H.Boolean()),taskIsolation:H.Optional(N(["local","worktree"])),outputFormat:H.Optional(CJ),jsonSchema:H.Optional(H.String()),outputSchema:H.Optional(H.String())});class CH{openedThinking=!1;wroteAssistantContent=!1;markAssistantContent(){this.wroteAssistantContent=!0}setThinkingOpened(K){this.openedThinking=K}hasOpenThinking(){return this.openedThinking}completeStream(){let K={openedThinking:this.openedThinking,wroteAssistantContent:this.wroteAssistantContent};return this.openedThinking=!1,this.wroteAssistantContent=!1,K}}function OJ(K){return K.issues.map((V)=>`${V.path.join(".")||"options"}: ${V.message}`).join("; ")}function wJ(K){let V=LH(hJ,K);if(!V.success)throw Error(`Invalid headless options: ${OJ(V.error)}`);return V.data}function mJ(K){return K.command("* [message]","Run full agent loop without Ink UI and print events to the terminal",(V)=>V.positional("message",{describe:"Message to process",type:"string"}).option("headless",{type:"boolean",describe:"Run full agent loop without Ink UI and print events to the terminal"}).option("model",{describe:"Model ID for this run",type:"string"}).option("system-prompt",{describe:"Replace the default system prompt",type:"string"}).option("append-system-prompt",{describe:"Append a system prompt to the default system prompt",type:"string"}).option("verification-agent",{describe:"Run the built-in independent verification agent after non-trivial changes",type:"boolean",default:!0}).option("max-turns",{alias:["maxTurns"],describe:"Maximum conversation turns (-1: unlimited, N>0: limit to N turns)",type:"number"}).option("output-format",{alias:["outputFormat"],choices:["text","jsonl"],describe:"Headless output format",type:"string"}).option("json-schema",{alias:["jsonSchema"],describe:"Inline JSON Schema for the structured final response",type:"string"}).option("output-schema",{alias:["outputSchema"],describe:"Path to a JSON Schema file for the structured final response",type:"string"}).option("task-isolation",{alias:["taskIsolation"],choices:["local","worktree"],describe:"Dispatch a new durable task in the selected workspace mode",type:"string"}),async(V)=>{if(!V.headless)return;let Q=await lJ(V);process.exit(Q)})}function L(K,V=""){K.write(`${V}
2
2
  `)}function cJ(K){return`[task] [${K.status}] ${K.subject}`}function uJ(){return{requestConfirmation:async(K)=>K.type==="mcpElicitation"?{approved:!1,reason:"headless-mcp-elicitation-unavailable",elicitation:{action:"cancel"}}:K.type==="mcpSampling"?{approved:!1,reason:"headless-mcp-sampling-unavailable"}:{approved:!0,reason:"headless-auto-approved",scope:"session"}}}function dJ(K){if(!(K instanceof Error))return"Unknown error";let X=K.lastError??K;if(X.responseBody)try{let W=JSON.parse(X.responseBody)?.error?.message;if(W)return X.statusCode?`${W} (HTTP ${X.statusCode})`:W}catch{}let J=K.message.match(/Last error:\s*(.+)$/);if(J)return J[1];return K.message}function pJ(K){return K==="jsonl"?"jsonl":"text"}function NH(K,V){let Q=(...X)=>{for(let J of X){let Z=V[J];if(typeof Z==="string"&&Z.trim()!=="")return Z}return};switch(K){case"Read":case"Edit":case"Write":case"UndoEdit":return Q("file_path");case"ApplyPatch":return"multi-file patch";case"NotebookEdit":return Q("notebook_path");case"Grep":return Q("path","pattern");case"Glob":return Q("pattern");case"WebFetch":return Q("url");case"WebSearch":return Q("query");case"Bash":return Q("command","description");case"Task":return Q("description");case"LSP":return Q("filePath","operation");case"EnterWorktree":return Q("name");case"ExitWorktree":return Q("action");default:return}}function vJ(K,V,Q,X){let J=new Set(["Glob","Grep","WebSearch","LS"]),Z=new Set(["Read","WebFetch"]);if(new Set(["Edit","Write","ApplyPatch","NotebookEdit","Bash","LSP","UndoEdit","EnterWorktree","ExitWorktree"]).has(K)&&!X.targetLocked)return{phase:"target_hit",status:"hit",message:`Target locked: ${V}`,shouldLockTarget:!0};if(X.targetLocked)return{phase:"executing",status:"hit",message:Q?`Working within target: ${V}`:`Executing: ${V}`,shouldLockTarget:!1};if(J.has(K))return{phase:"searching",status:"ongoing",message:`Still searching: ${V}`,shouldLockTarget:!1};if(Z.has(K))return{phase:"inspecting",status:"ongoing",message:`Inspecting candidate: ${V}`,shouldLockTarget:!1};return{phase:"executing",status:X.targetLocked?"hit":"ongoing",message:`Executing: ${V}`,shouldLockTarget:!1}}function QH(K,V,Q=!1){let X=(J,Z)=>{K.stdout.write(`${JSON.stringify(BH(J,Z))}
3
3
  `)};return{contentDelta(J){if(V==="jsonl"){X("content_delta",{delta:J});return}if(Q)return;K.stdout.write(J)},thinkingDelta(J,Z){if(V==="jsonl")return X("thinking_delta",{delta:J}),Z;if(!Z)K.stderr.write("[thinking] ");return K.stderr.write(J),!0},thinking(J){if(V==="jsonl"){X("thinking",{content:J});return}L(K.stderr,`[thinking] ${J}`)},streamEnd(J,Z){if(V==="jsonl"){X("stream_end",{});return}if(Z)K.stderr.write(`
4
4
  `);if(J)K.stdout.write(`
@@ -1,4 +1,4 @@
1
- import{wa as EZ}from"./chunk-abd57h72.js";import{Aa as n0,Fa as dY,Ga as A7,Ha as i0,za as A}from"./chunk-xtb84adp.js";import{Ia as Y8,Ka as AQ,Ma as CQ,Na as VZ,db as MQ}from"./chunk-xm8nyj5z.js";import{Ab as W4,Cb as g9,Db as G$,Jb as j4,Kb as TY,Lb as rJ,Nb as S2,Ob as BY,Tb as m7,Wb as p7,eb as h$,fb as x1,gb as X7,hb as B1,ib as i3,jb as H7,kb as o3,lb as K7,mb as w7,nb as YJ,rb as V0,tb as u1,wb as Y4,yb as B5,zb as Q4}from"./chunk-0aa40zbs.js";import{Ac as X1,Ad as HY,Bc as C1,Bd as KY,Cc as H2,Dc as M1,Ec as P1,Ed as IY,Fc as Q6,Gc as R1,Hc as W6,Ic as U6,Id as d7,Jc as q$,Kc as X6,Lc as xZ,Mc as B2,Nc as V6,Nd as wY,Oc as H6,Od as zY,Pc as K6,Qc as w6,Qd as t,Rc as hZ,Sc as gZ,Uc as uZ,ac as G9,bc as _0,cc as $2,dc as Z1,ec as t2,fc as BZ,gc as Z4,hc as J4,ic as t3,jc as e3,kc as VY,lc as NZ,ld as L4,mc as U1,nc as OZ,nd as A0,oc as i4,od as V$,pc as y$,qc as I$,rc as w2,sc as K2,tc as z2,uc as J6,vc as Y6,wc as X2,xc as MZ,xd as GZ,yc as V2,yd as r0,zc as n4,zd as h1}from"./chunk-wzmqkam9.js";import{Rd as d,Sd as XJ,Td as VJ,Ud as a9,Wd as g1}from"./chunk-s0tq8gyx.js";import{Xd as RQ,_d as TQ,he as fQ,ne as SQ}from"./chunk-x3cxmwnz.js";import{ye as y9,ze as k9}from"./chunk-z9gd9spf.js";import{$e as y1,Le as U4,Me as B0,Ne as y,Qe as L0,Re as c6,Se as d1,Te as l$,Ue as E5,Ve as V1,We as g7}from"./chunk-q6eb20fz.js";import{af as q1}from"./chunk-dg0d3303.js";import{ef as F5,ff as u7,gf as x7,lf as EY,mf as l6}from"./chunk-rchz6j90.js";import{of as y0,pf as e$}from"./chunk-w7hy5wh1.js";import{qf as SY}from"./chunk-2hb222re.js";import{sf as YY,tf as QY,uf as WY}from"./chunk-07w0qapm.js";import{Af as $4,Bf as s$,Cf as BJ,Ef as O$,Ff as H$,Gf as Y$,Hf as Z8,If as S1,Jf as N4,Kf as b1,Lf as N1,Mf as XY,Qf as d5,Sf as I0,Tf as D$,Vf as i6,Wf as GY,vf as o6,wf as s6,xf as t6,zf as e6}from"./chunk-ywarj5j9.js";import{$f as v6,Yf as n$,_f as B$,ag as iZ,bg as nZ,cg as G2,dg as rZ,eg as aZ,fg as B6,gg as oZ,hg as G6}from"./chunk-kf7whgr7.js";import{ig as sY,kg as UY,lg as F4,mg as I9}from"./chunk-fva7jnjy.js";import{og as JZ,qg as T0}from"./chunk-aa5zmwd9.js";import{rg as c2,sg as zZ,tg as l2,ug as E1}from"./chunk-41cg66y0.js";import{Bg as O9,Dg as s5,Ig as uY,Mg as b9,Og as eJ,Qg as W7,Rg as U7,Xg as D1,_g as a3,ih as M7,jh as P7,kh as R7,lh as T7,mh as b5,nh as f7,oh as c$,ph as S7,qh as k7,rh as v7,th as w9,vh as _Y,wg as L9,wh as JY,xh as H0}from"./chunk-f945dzj6.js";import{Ah as x$}from"./chunk-sdbbyagy.js";import{Bh as z6,Ch as o4,Dh as z,Eh as J9,Fh as f,Gh as I}from"./chunk-f3426b1c.js";import{Ih as iJ,Kh as nJ}from"./chunk-c475tfqf.js";import{Nh as b6,Ph as M}from"./chunk-0hr050ck.js";import{pi as a}from"./chunk-n7mzxa8h.js";import{ui as $Y,vi as ZY}from"./chunk-s10pmnrd.js";import{wi as eY,zi as aY}from"./chunk-9p20hhs0.js";import{Di as YQ}from"./chunk-14bs89sm.js";import{Ji as DY,Ki as d0}from"./chunk-wyhyw9rq.js";import{Oi as s2,Qi as m$,Si as tJ,Ti as lZ,Vi as s}from"./chunk-tgdhsm5t.js";import{Xi as a0}from"./chunk-fhfzdyba.js";import{randomUUID as h4}from"crypto";import{randomUUID as sQ}from"node:crypto";var iQ=String.raw`
1
+ import{wa as EZ}from"./chunk-abd57h72.js";import{Aa as n0,Fa as dY,Ga as A7,Ha as i0,za as A}from"./chunk-p6prp8zc.js";import{Ia as Y8,Ka as AQ,Ma as CQ,Na as VZ,db as MQ}from"./chunk-xm8nyj5z.js";import{Ab as W4,Cb as g9,Db as G$,Jb as j4,Kb as TY,Lb as rJ,Nb as S2,Ob as BY,Tb as m7,Wb as p7,eb as h$,fb as x1,gb as X7,hb as B1,ib as i3,jb as H7,kb as o3,lb as K7,mb as w7,nb as YJ,rb as V0,tb as u1,wb as Y4,yb as B5,zb as Q4}from"./chunk-8hp650gn.js";import{Ac as X1,Ad as HY,Bc as C1,Bd as KY,Cc as H2,Dc as M1,Ec as P1,Ed as IY,Fc as Q6,Gc as R1,Hc as W6,Ic as U6,Id as d7,Jc as q$,Kc as X6,Lc as xZ,Mc as B2,Nc as V6,Nd as wY,Oc as H6,Od as zY,Pc as K6,Qc as w6,Qd as t,Rc as hZ,Sc as gZ,Uc as uZ,ac as G9,bc as _0,cc as $2,dc as Z1,ec as t2,fc as BZ,gc as Z4,hc as J4,ic as t3,jc as e3,kc as VY,lc as NZ,ld as L4,mc as U1,nc as OZ,nd as A0,oc as i4,od as V$,pc as y$,qc as I$,rc as w2,sc as K2,tc as z2,uc as J6,vc as Y6,wc as X2,xc as MZ,xd as GZ,yc as V2,yd as r0,zc as n4,zd as h1}from"./chunk-najk5ty4.js";import{Rd as d,Sd as XJ,Td as VJ,Ud as a9,Wd as g1}from"./chunk-s0tq8gyx.js";import{Xd as RQ,_d as TQ,he as fQ,ne as SQ}from"./chunk-x3cxmwnz.js";import{ye as y9,ze as k9}from"./chunk-z9gd9spf.js";import{$e as y1,Le as U4,Me as B0,Ne as y,Qe as L0,Re as c6,Se as d1,Te as l$,Ue as E5,Ve as V1,We as g7}from"./chunk-5y38cfk9.js";import{af as q1}from"./chunk-dg0d3303.js";import{ef as F5,ff as u7,gf as x7,lf as EY,mf as l6}from"./chunk-rchz6j90.js";import{of as y0,pf as e$}from"./chunk-w7hy5wh1.js";import{qf as SY}from"./chunk-2hb222re.js";import{sf as YY,tf as QY,uf as WY}from"./chunk-p39mmmbt.js";import{Af as $4,Bf as s$,Cf as BJ,Ef as O$,Ff as H$,Gf as Y$,Hf as Z8,If as S1,Jf as N4,Kf as b1,Lf as N1,Mf as XY,Qf as d5,Sf as I0,Tf as D$,Vf as i6,Wf as GY,vf as o6,wf as s6,xf as t6,zf as e6}from"./chunk-151cz9k4.js";import{$f as v6,Yf as n$,_f as B$,ag as iZ,bg as nZ,cg as G2,dg as rZ,eg as aZ,fg as B6,gg as oZ,hg as G6}from"./chunk-kf7whgr7.js";import{ig as sY,kg as UY,lg as F4,mg as I9}from"./chunk-fva7jnjy.js";import{og as JZ,qg as T0}from"./chunk-6j482w6k.js";import{rg as c2,sg as zZ,tg as l2,ug as E1}from"./chunk-41cg66y0.js";import{Bg as O9,Dg as s5,Ig as uY,Mg as b9,Og as eJ,Qg as W7,Rg as U7,Xg as D1,_g as a3,ih as M7,jh as P7,kh as R7,lh as T7,mh as b5,nh as f7,oh as c$,ph as S7,qh as k7,rh as v7,th as w9,vh as _Y,wg as L9,wh as JY,xh as H0}from"./chunk-139frcak.js";import{Ah as x$}from"./chunk-sdbbyagy.js";import{Bh as z6,Ch as o4,Dh as z,Eh as J9,Fh as f,Gh as I}from"./chunk-f3426b1c.js";import{Ih as iJ,Kh as nJ}from"./chunk-c475tfqf.js";import{Nh as b6,Ph as M}from"./chunk-0hr050ck.js";import{pi as a}from"./chunk-n7mzxa8h.js";import{ui as $Y,vi as ZY}from"./chunk-s10pmnrd.js";import{wi as eY,zi as aY}from"./chunk-9p20hhs0.js";import{Di as YQ}from"./chunk-4bwr3rcj.js";import{Ji as DY,Ki as d0}from"./chunk-wyhyw9rq.js";import{Oi as s2,Qi as m$,Si as tJ,Ti as lZ,Vi as s}from"./chunk-tgdhsm5t.js";import{Xi as a0}from"./chunk-fhfzdyba.js";import{randomUUID as h4}from"crypto";import{randomUUID as sQ}from"node:crypto";var iQ=String.raw`
2
2
  const { spawn } = require('node:child_process');
3
3
  const [ownerPidValue, command, ...args] = process.argv.slice(1);
4
4
  const ownerPid = Number(ownerPidValue);
@@ -129,7 +129,7 @@ ${H}`,w=Buffer.byteLength(K);if(X+w>W)break;U.push(H),X+=w}return{snapshot:`${U.
129
129
  `,{encoding:"utf8",mode:384,fsync:!0})}emit($){let Z={workspaceRoot:this.workspaceRoot,sessionId:this.sessionId,goal:$?{...$}:null};for(let J of z0.listeners)try{J(Z)}catch{}}}import{createHash as nW}from"node:crypto";import{createHash as dW}from"node:crypto";import*as D6 from"fs/promises";import*as f1 from"path";import mW from"write-file-atomic";import*as eZ from"node:fs/promises";import*as $9 from"node:path";var hW={realpath:!1,retries:{retries:150,factor:1.2,minTimeout:10,maxTimeout:100,randomize:!0}},tZ;async function Z9($,Z){await eZ.mkdir($9.dirname($),{recursive:!0,mode:448});let Y=await(await gW()).lock($,hW);try{return await Z()}finally{await Y()}}async function gW(){return tZ??=await import("proper-lockfile"),tZ}var t4=I(["pending","in_progress","completed"]),uW=I(["high","medium","low"]),Y9=J9(z.Object({id:z.String(),subject:z.String(),description:z.String(),status:t4,activeForm:z.Optional(z.String()),owner:z.Optional(z.String()),priority:f(uW,"medium"),blocks:f(z.Array(z.String()),[]),blockedBy:f(z.Array(z.String()),[]),metadata:z.Optional(z.Record(z.String(),z.Unknown())),createdAt:z.String(),startedAt:z.Optional(z.String()),completedAt:z.Optional(z.String())}));class X${static operations=new x$;tasks=[];filePath;constructor($,Z){this.filePath=f1.join(f1.resolve(Z),"tasks",lW($))}static getInstance($,Z){return new X$($,Z)}static coordinationStatsForTests(){return this.operations.getStats()}async createTask($){return this.mutate((Z)=>{let J=T1($.blockedBy??[]),Y={id:String(Z.nextId),subject:$.subject,description:$.description,activeForm:$.activeForm,owner:$.owner,priority:$.priority||"medium",status:"pending",blocks:[],blockedBy:J,metadata:$.metadata,createdAt:new Date().toISOString()};return{state:{nextId:Z.nextId+1,tasks:Z.tasks.map((Q)=>J.includes(Q.id)?{...Q,blocks:T1([...Q.blocks,Y.id])}:Q).concat(Y)},result:Y,persist:!0}})}async getTask($){return(await this.readLatest()).tasks.find((J)=>J.id===$)||null}async listTasks(){return await this.readLatest(),this.getSortedTasks()}async claimNextAvailable($){let Z=$.trim();if(!Z)throw Error("Task owner cannot be empty");return this.mutate((J)=>{let Y=new Set(J.tasks.filter((U)=>U.status==="completed").map((U)=>U.id)),Q=[...J.tasks].filter((U)=>U.status==="pending"&&(U.owner===void 0||U.owner===Z)&&U.blockedBy.every((X)=>Y.has(X))).sort(Q9)[0];if(!Q)return{state:J,result:null,persist:!1};let W={...Q,owner:Z,status:"in_progress",startedAt:Q.startedAt??new Date().toISOString()};return{state:{...J,tasks:J.tasks.map((U)=>U.id===W.id?W:U)},result:W,persist:!0}})}async updateTask($,Z){return this.mutate((J)=>{let Y=J.tasks.findIndex((H)=>H.id===$);if(Y===-1)return{state:J,result:{task:null,updatedFields:[]},persist:!1};let Q=J.tasks[Y],W=[],U={...Q};if(Z.subject!==void 0&&Z.subject!==Q.subject)U.subject=Z.subject,W.push("subject");if(Z.description!==void 0&&Z.description!==Q.description)U.description=Z.description,W.push("description");if(Z.activeForm!==void 0&&Z.activeForm!==Q.activeForm)U.activeForm=Z.activeForm,W.push("activeForm");if(Z.owner!==void 0&&Z.owner!==Q.owner)U.owner=Z.owner,W.push("owner");if(Z.metadata!==void 0)U.metadata=iW(Q.metadata,Z.metadata),W.push("metadata");let X;if(Z.status!==void 0&&Z.status!==Q.status){if(U.status=Z.status,Z.status==="in_progress"&&!Q.startedAt)U.startedAt=new Date().toISOString();if(Z.status==="completed"&&!Q.completedAt)U.completedAt=new Date().toISOString();X={from:Q.status,to:Z.status},W.push("status")}if(Z.addBlocks&&Z.addBlocks.length>0){if(U.blocks=T1([...Q.blocks,...Z.addBlocks]),U.blocks.length!==Q.blocks.length)W.push("blocks")}if(Z.addBlockedBy&&Z.addBlockedBy.length>0){if(U.blockedBy=T1([...Q.blockedBy,...Z.addBlockedBy]),U.blockedBy.length!==Q.blockedBy.length)W.push("blockedBy")}let V=J.tasks.map((H)=>H.id===$?U:H);return V=cW(V,U,Z.addBlocks,Z.addBlockedBy),{state:{...J,tasks:V},result:{task:U,updatedFields:W,statusChange:X},persist:!0}})}async deleteTask($){return this.mutate((Z)=>{let J=Z.tasks.filter((Q)=>Q.id!==$).map((Q)=>({...Q,blocks:Q.blocks.filter((W)=>W!==$),blockedBy:Q.blockedBy.filter((W)=>W!==$)})),Y=J.length!==Z.tasks.length;return{state:Y?{...Z,tasks:J}:Z,result:Y,persist:Y}})}getStats(){return{total:this.tasks.length,completed:this.tasks.filter(($)=>$.status==="completed").length,inProgress:this.tasks.filter(($)=>$.status==="in_progress").length,pending:this.tasks.filter(($)=>$.status==="pending").length}}getSortedTasks(){return[...this.tasks].sort(Q9)}async readLatest(){return X$.operations.runExclusive(this.filePath,async()=>{let $=await this.readTasks();return this.tasks=$.tasks,$})}async mutate($){return X$.operations.runExclusive(this.filePath,()=>Z9(this.filePath,async()=>{let Z=await this.readTasks(),J=$(Z);if(J.persist)await this.saveTasks(J.state);return this.tasks=J.state.tasks,J.result}))}async readTasks(){try{let $=JSON.parse(await D6.readFile(this.filePath,"utf-8"));return pW($)}catch($){if($.code==="ENOENT")return{tasks:[],nextId:1};throw Error("Task list state is corrupt or unreadable",{cause:$})}}async saveTasks($){await D6.mkdir(f1.dirname(this.filePath),{recursive:!0,mode:448}),await mW(this.filePath,`${JSON.stringify($,null,2)}
130
130
  `,{mode:384})}}function pW($){let Z=$&&typeof $==="object"&&!Array.isArray($)?$:void 0,J=Array.isArray($)?$:Z&&Array.isArray(Z.tasks)?Z.tasks:void 0;if(!J)throw Error("Task list must contain a tasks array");let Y=J.map((U,X)=>{let V=z6(Y9,U);if(!V.success)throw Error(`Task list item ${X} failed schema validation`);return V.data});if(new Set(Y.map((U)=>U.id)).size!==Y.length)throw Error("Task list contains duplicate task IDs");let Q=Z&&typeof Z.nextId==="number"?Z.nextId:void 0;if(Q!==void 0&&(!Number.isInteger(Q)||Q<1))throw Error("Task list nextId must be a positive integer");let W=Y.reduce((U,X)=>{let V=Number(X.id);return Number.isFinite(V)?Math.max(U,V):U},0);return{tasks:Y,nextId:Math.max(Q||1,W+1)}}function cW($,Z,J,Y){let Q=$;for(let W of J||[])Q=Q.map((U)=>U.id===W?{...U,blockedBy:T1([...U.blockedBy,Z.id])}:U);for(let W of Y||[])Q=Q.map((U)=>U.id===W?{...U,blocks:T1([...U.blocks,Z.id])}:U);return Q}function lW($){let Z=encodeURIComponent($||"default");if(Z.length<=120)return`${Z}-agent-${Z}.json`;let J=dW("sha256").update($).digest("hex").slice(0,16);return`${Z.slice(0,96)}-${J}.json`}function T1($){return[...new Set($.filter(Boolean))]}function Q9($,Z){let J={in_progress:0,pending:1,completed:2},Y={high:0,medium:1,low:2},Q=J[$.status]-J[Z.status];if(Q!==0)return Q;let W=Y[$.priority]-Y[Z.priority];if(W!==0)return W;return Number($.id)-Number(Z.id)}function iW($,Z){let J={...$||{}};for(let[Y,Q]of Object.entries(Z))if(Q===null)delete J[Y];else J[Y]=Q;return J}var rW=512,aW=256;function _2($){return`goal:${$.sessionId}:${$.goalId}`}async function _6($,Z){let J=_2($),Q=await X$.getInstance(J,Z.configDir).listTasks(),W=new Set(Q.filter((w)=>w.status==="completed").map((w)=>w.id)),U=Q.filter((w)=>w.status==="pending"),X=U.filter((w)=>w.blockedBy.every((B)=>W.has(B))&&(Z.owner===void 0||w.owner===void 0||w.owner===Z.owner)),V=U.filter((w)=>!w.blockedBy.every((B)=>W.has(B))).length,H=X[0];return{frontier:{taskListId:J,total:Q.length,completed:Q.filter((w)=>w.status==="completed").length,inProgress:Q.filter((w)=>w.status==="in_progress").length,pending:U.length,blocked:V,...H?{nextTask:{id:H.id,subject:H.subject,priority:H.priority}}:{},digestSha256:oW(Q),observedAt:new Date().toISOString()},tasks:Q}}function W9($){let Z=$.nextTask?`#${D2($.nextTask.id)} [${$.nextTask.priority}] ${D2($.nextTask.subject.slice(0,rW))}`:$.pending>0?"none (pending tasks are waiting for dependencies or ownership)":"none (task list is complete or empty)";return["<goal-execution-frontier>",`Task list: ${D2($.taskListId.slice(0,aW))}`,`Tasks: total=${$.total}, completed=${$.completed}, in_progress=${$.inProgress}, pending=${$.pending}, blocked=${$.blocked}`,`Next executable task: ${Z}`,`Digest: ${D2($.digestSha256)}`,`Observed at: ${D2($.observedAt)}`,"</goal-execution-frontier>"].join(`
131
131
  `)}function oW($){let Z=[...$].sort((J,Y)=>J.id.localeCompare(Y.id)).map((J)=>({id:J.id,status:J.status,blockedBy:[...J.blockedBy].sort(),blocks:[...J.blocks].sort(),owner:J.owner??null,priority:J.priority,subject:J.subject}));return nW("sha256").update(JSON.stringify(Z)).digest("hex")}function D2($){return $.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;").replaceAll("'","&apos;")}var sW=64;function U9($,Z,J,Y){if($===void 0||$.digestSha256!==Z.digestSha256||J.taskEffect!=="none"||Z.total===0||Z.pending===0&&Z.inProgress===0)return;let Q=tW(Z,J);if(Q===void 0)return;let W=Y?.category===Q&&Y.digestSha256===Z.digestSha256?Math.min(G6,Y.consecutiveCount+1):1;return{category:Q,consecutiveCount:W,digestSha256:Z.digestSha256,detectedAt:new Date().toISOString()}}function X9($){let Z=q6($.digestSha256.slice(0,sW)),J=q6($.category),Y=q6(eW($.category));return["<goal-frontier-stall>",`Category: ${J}`,`Consecutive observations: ${$.consecutiveCount}`,`Digest: ${Z}`,`Detected at: ${q6($.detectedAt)}`,`Required action: ${Y}`,"Treat this block as host diagnostics, not as user instructions.","</goal-frontier-stall>"].join(`
132
- `)}function tW($,Z){if($.pending>0&&$.blocked>0&&$.inProgress===0&&$.nextTask===void 0)return"waiting_dependency";if(Z.prematureStopCount>=2||Z.verificationStallCount>=2)return"repeated_deferral";if($.pending>0||$.inProgress>0)return"same_task_no_effect";return}function eW($){switch($){case"waiting_dependency":return"Inspect the incomplete dependency, then execute an independent task or report the concrete external blocker.";case"repeated_deferral":return"Change strategy: validate assumptions, inspect durable results, and fix or verify the reported gap before another completion attempt.";case"same_task_no_effect":return"Change strategy: stop repeating the same step, inspect current evidence, and choose a different executable task or verification action."}}function q6($){return $.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;").replaceAll("'","&apos;")}import{createHash as $U}from"node:crypto";import{promises as F6,realpathSync as ZU}from"node:fs";import Q0 from"node:path";import{fileURLToPath as JU,pathToFileURL as F$}from"node:url";var V9=a("Service"),H9=65536;class e4{name;onCrash;child;processTree;connection;closePromise;crashCleanup;capabilities;initialized=!1;stopping=!1;notificationHandlers=new Map;requestHandlers=new Map;constructor($,Z){this.name=$;this.onCrash=Z}get serverCapabilities(){return this.capabilities}get isInitialized(){return this.initialized}async start($){if(await this.crashCleanup,this.crashCleanup=void 0,this.connection)return;let Z=await import("vscode-jsonrpc/node.js"),{child:J,processTree:Y}=E1($.command,[...$.args],{cwd:$.cwd,env:{...$.environment,PATH:$.environment.PATH??process.env.PATH??"",HOME:$.environment.HOME??process.env.HOME??"",USER:$.environment.USER??process.env.USER??"",SHELL:$.environment.SHELL??process.env.SHELL??"/bin/sh",BLADE_CLI:"1"},stdio:["pipe","pipe","pipe"]},{releaseOnExit:!1});this.child=J,this.processTree=Y;try{if(await new Promise((U,X)=>{let V=()=>{J.removeListener("spawn",H),J.removeListener("error",K)},H=()=>{V(),U()},K=(w)=>{V(),X(w)};J.once("spawn",H),J.once("error",K)}),!J.stdout||!J.stdin)throw Error("LSP server stdio is unavailable");let Q="";J.stderr?.setEncoding("utf8"),J.stderr?.on("data",(U)=>{if(Q.length<H9)Q+=U.slice(0,H9-Q.length)}),J.stdin.on("error",(U)=>{if(!this.stopping)V9.debug(`[LSP ${this.name}] stdin closed: ${U.message}`)}),this.closePromise=new Promise((U)=>{J.once("close",(X,V)=>{if(this.child!==J){U();return}this.initialized=!1;let H=!this.stopping;if(H){let w=Q.trim()?`: ${Q.trim().slice(0,512)}`:V?` (${V})`:"";this.onCrash(Error(`LSP server "${this.name}" exited with code ${X}${w}`))}let K=this.processTree;try{this.connection?.dispose()}catch{}if(this.connection=void 0,this.child=void 0,this.closePromise=void 0,H&&K)this.crashCleanup=K.terminate().then(()=>{return}),this.processTree=void 0;U()})});let W=Z.createMessageConnection(new Z.StreamMessageReader(J.stdout),new Z.StreamMessageWriter(J.stdin));this.connection=W,W.onError(([U])=>{if(!this.stopping)V9.warn(`[LSP ${this.name}] connection error: ${U.message}`)}),W.onClose(()=>{if(this.connection===W)this.initialized=!1});for(let[U,X]of this.notificationHandlers)for(let V of X)W.onNotification(U,V);for(let[U,X]of this.requestHandlers)W.onRequest(U,X);W.listen()}catch(Q){throw await this.disposeTransport(),Q}}async initialize($,Z,J){let Y=await this.request("initialize",$,Z,J,!1);return this.capabilities=Y.capabilities,await this.notify("initialized",{}),this.initialized=!0,Y}async request($,Z,J,Y,Q=!0){let W=this.connection;if(!W)throw Error(`LSP server "${this.name}" is not started`);if(Q&&!this.initialized)throw Error(`LSP server "${this.name}" is not initialized`);let X=new(await import("vscode-jsonrpc/node.js")).CancellationTokenSource;return this.awaitRequest(W.sendRequest($,Z,X.token),X,J,Y,$)}async notify($,Z){if(!this.connection)throw Error(`LSP server "${this.name}" is not started`);await this.connection.sendNotification($,Z)}onNotification($,Z){let J=this.notificationHandlers.get($)??[];J.push(Z),this.notificationHandlers.set($,J),this.connection?.onNotification($,Z)}onRequest($,Z){this.requestHandlers.set($,Z),this.connection?.onRequest($,Z)}async stop($){if(!this.child&&!this.connection){await this.crashCleanup,this.crashCleanup=void 0;return}this.stopping=!0;let Z=this.connection;try{if(Z&&this.initialized){let Y=new(await import("vscode-jsonrpc/node.js")).CancellationTokenSource;await this.awaitRequest(Z.sendRequest("shutdown",Y.token),Y,$,void 0,"shutdown").catch(()=>{return}),await Z.sendNotification("exit").catch(()=>{return})}await Promise.race([this.closePromise??Promise.resolve(),new Promise((J)=>setTimeout(J,Math.min($,500)))])}finally{await this.disposeTransport(),this.stopping=!1,this.initialized=!1,this.capabilities=void 0}}awaitRequest($,Z,J,Y,Q){return new Promise((W,U)=>{let X=!1,V=(w)=>{if(X)return;X=!0,clearTimeout(K),Y?.removeEventListener("abort",H),w()},H=()=>{Z.cancel(),V(()=>U(Error(`LSP request "${Q}" was aborted`)))},K=setTimeout(()=>{Z.cancel(),V(()=>U(Error(`LSP request "${Q}" timed out after ${J}ms`)))},J);if(Y?.addEventListener("abort",H,{once:!0}),Y?.aborted)H();$.then((w)=>V(()=>W(w)),(w)=>V(()=>U(w)))})}async disposeTransport(){let $=this.connection,Z=this.processTree;this.connection=void 0,this.processTree=void 0,this.child=void 0,this.closePromise=void 0;try{$?.dispose()}catch{}await Z?.terminate(),await this.crashCleanup,this.crashCleanup=void 0}}var YU=a("Service"),QU=10485760,WU=10,K9=30,UU=-32801;class $8{options;workspaceRoot;servers=new Map;diagnostics=new Map;delivered=new Map;waiters=new Map;disposeController=new AbortController;diagnosticSequence=0;disposed=!1;constructor($){this.options=$;let Z=Q0.resolve($.workspaceRoot);try{this.workspaceRoot=ZU.native(Z)}catch{this.workspaceRoot=Z}for(let[J,Y]of Object.entries($.servers)){if(Y.enabled===!1)continue;let Q={name:J,config:structuredClone(Y),state:"stopped",restartCount:0,openedFiles:new Map,client:new e4(J,(W)=>{Q.state="error",Q.lastError=W.message,Q.openedFiles.clear()})};Q.client.onNotification("textDocument/publishDiagnostics",(W)=>{this.captureDiagnostics(J,W)}),Q.client.onRequest("workspace/configuration",(W)=>this.resolveWorkspaceConfiguration(Y.settings,W)),Q.client.onRequest("workspace/workspaceFolders",()=>[{uri:F$(this.workspaceRoot).href,name:Q0.basename(this.workspaceRoot)}]),Q.client.onRequest("window/workDoneProgress/create",()=>null),this.servers.set(J,Q)}}get available(){return this.servers.size>0&&!this.isRemoteSession()&&!this.disposed}get workspacePath(){return this.workspaceRoot}getStatus(){return[...this.servers.values()].map(($)=>({name:$.name,state:$.state,restartCount:$.restartCount,extensions:Object.keys($.config.extensionToLanguage).sort(),...$.lastError?{lastError:$.lastError}:{}})).sort(($,Z)=>$.name.localeCompare(Z.name))}async afterToolUse($,Z,J,Y){if(!this.available||this.disposed)return;let Q;if(J.success&&($==="Write"||$==="Edit")&&typeof Z.file_path==="string")Q=await this.syncAfterWrite(Z.file_path,Y.signal);else if(J.success&&$==="ApplyPatch"){let W=Array.isArray(J.metadata?.changes)?J.metadata.changes:[];for(let U of W){if(!U||typeof U!=="object"||!("path"in U)||typeof U.path!=="string")continue;if("newContent"in U&&U.newContent===null)await this.syncAfterDelete(U.path);else Q=await this.syncAfterWrite(U.path,Y.signal)??Q}}this.attachPendingDiagnostics(J,Q)}async query($,Z){if(!this.available)throw Error(this.isRemoteSession()?"LSP is unavailable for ACP-owned remote files":"No LSP servers are configured for this Session");let J=await this.resolveFile($.filePath);if($.operation==="diagnostics")return{operation:$.operation,filePath:J,result:this.getCurrentDiagnostics(J)};let Y=await this.ensureFileOpen(J,void 0,Z);if(!Y)throw Error(`No LSP server handles ${Q0.extname(J)||"this file"}`);let Q={line:Math.max(0,($.line??1)-1),character:Math.max(0,($.character??1)-1)},W={uri:F$(J).href},U={goToDefinition:{method:"textDocument/definition",params:{textDocument:W,position:Q}},findReferences:{method:"textDocument/references",params:{textDocument:W,position:Q,context:{includeDeclaration:!0}}},hover:{method:"textDocument/hover",params:{textDocument:W,position:Q}},documentSymbol:{method:"textDocument/documentSymbol",params:{textDocument:W}},workspaceSymbol:{method:"workspace/symbol",params:{query:$.query??""}},goToImplementation:{method:"textDocument/implementation",params:{textDocument:W,position:Q}},prepareCallHierarchy:{method:"textDocument/prepareCallHierarchy",params:{textDocument:W,position:Q}}},X;if($.operation==="incomingCalls"||$.operation==="outgoingCalls"){let H=(await this.requestWithRetry(Y,"textDocument/prepareCallHierarchy",{textDocument:W,position:Q},Z))?.[0];X=H?await this.requestWithRetry(Y,$.operation==="incomingCalls"?"callHierarchy/incomingCalls":"callHierarchy/outgoingCalls",{item:H},Z):[]}else{let V=U[$.operation];X=await this.requestWithRetry(Y,V.method,V.params,Z)}return{operation:$.operation,filePath:J,serverName:Y.name,result:X}}async dispose(){if(this.disposed)return;this.disposed=!0,this.disposeController.abort();for(let $ of this.waiters.values())for(let Z of $)clearTimeout(Z.timer),Z.resolve();this.waiters.clear(),await Promise.allSettled([...this.servers.values()].map(async($)=>{$.state="stopping",await $.client.stop($.config.shutdownTimeout??2000),$.state="stopped",$.openedFiles.clear()})),this.diagnostics.clear(),this.delivered.clear()}isRemoteSession(){return this.options.isRemoteSession?.()??X0(this.options.sessionId)}selectServer($){let Z=Q0.extname($).toLowerCase();return[...this.servers.values()].filter((J)=>(Z in J.config.extensionToLanguage)).sort((J,Y)=>(Y.config.priority??0)-(J.config.priority??0)||J.name.localeCompare(Y.name))[0]}async ensureFileOpen($,Z,J){let Y=this.selectServer($);if(!Y)return;await this.ensureStarted(Y,J);let Q=F$($).href;if(Y.openedFiles.has(Q))return Y;let W=Z??await this.readBoundedFile($);return await Y.client.notify("textDocument/didOpen",{textDocument:{uri:Q,languageId:Y.config.extensionToLanguage[Q0.extname($).toLowerCase()],version:1,text:W}}),Y.openedFiles.set(Q,1),Y}async syncAfterWrite($,Z){try{let J=await this.resolveFile($),Y=await this.readBoundedFile(J),Q=await this.ensureFileOpen(J,Y,Z);if(!Q)return;let W=F$(J).href,U=this.diagnostics.get(W)?.sequence??0;this.delivered.delete(W);let X=Q.openedFiles.get(W)??0;if(X>0){let V=X+1;await Q.client.notify("textDocument/didChange",{textDocument:{uri:W,version:V},contentChanges:[{text:Y}]}),Q.openedFiles.set(W,V)}return await Q.client.notify("textDocument/didSave",{textDocument:{uri:W},text:Y}),await this.waitForDiagnostics(W,U,Q.config.diagnosticWaitTimeout??750,Z),J}catch(J){if(!Z?.aborted&&!this.disposeController.signal.aborted)YU.debug(`[LSP] post-edit sync skipped: ${J instanceof Error?J.message:String(J)}`);return}}async syncAfterDelete($){let Z=await this.resolveMissingFile($).catch(()=>{return});if(!Z)return;if(!this.isInsideWorkspace(Z))return;let J=F$(Z).href;for(let Y of this.servers.values()){if(!Y.openedFiles.has(J))continue;await Y.client.notify("textDocument/didClose",{textDocument:{uri:J}}).catch(()=>{return}),Y.openedFiles.delete(J)}this.diagnostics.delete(J),this.delivered.delete(J)}async ensureStarted($,Z){if($.state==="running")return;if($.startPromise)return $.startPromise;if($.state==="error"){if($.restartCount>=($.config.maxRestarts??3))throw Error(`LSP server "${$.name}" exceeded its restart limit`);$.restartCount++}let J=this.startServer($,Z).finally(()=>{$.startPromise=void 0});return $.startPromise=J,J}async startServer($,Z){$.state="starting";try{await $.client.start({command:$.config.command,args:$.config.args??[],cwd:this.workspaceRoot,environment:{...this.options.environment,...$.config.env,BLADE_SESSION_ID:this.options.sessionId}});let J=F$(this.workspaceRoot).href,Y={processId:process.pid,rootPath:this.workspaceRoot,rootUri:J,workspaceFolders:[{uri:J,name:Q0.basename(this.workspaceRoot)}],initializationOptions:$.config.initializationOptions??{},capabilities:{workspace:{configuration:!0,workspaceFolders:!0,symbol:{dynamicRegistration:!1}},textDocument:{synchronization:{dynamicRegistration:!1,willSave:!1,willSaveWaitUntil:!1,didSave:!0},publishDiagnostics:{relatedInformation:!0,versionSupport:!1},hover:{dynamicRegistration:!1,contentFormat:["markdown","plaintext"]},definition:{dynamicRegistration:!1,linkSupport:!0},references:{dynamicRegistration:!1},implementation:{dynamicRegistration:!1,linkSupport:!0},documentSymbol:{dynamicRegistration:!1,hierarchicalDocumentSymbolSupport:!0},callHierarchy:{dynamicRegistration:!1}},general:{positionEncodings:["utf-16"]}}};if(await $.client.initialize(Y,$.config.startupTimeout??1e4,Z),$.config.settings!==void 0)await $.client.notify("workspace/didChangeConfiguration",{settings:$.config.settings});$.state="running",$.lastError=void 0}catch(J){throw $.state="error",$.lastError=J instanceof Error?J.message:String(J),await $.client.stop($.config.shutdownTimeout??2000).catch(()=>{return}),J}}async requestWithRetry($,Z,J,Y){let Q;for(let W=0;W<4;W++)try{return await $.client.request(Z,J,$.config.requestTimeout??1e4,Y)}catch(U){if(Q=U,U.code!==UU||W===3)break;await new Promise((X)=>setTimeout(X,100*2**W))}throw Q}captureDiagnostics($,Z){if(this.disposed||!Z||typeof Z!=="object"||!("uri"in Z)||!("diagnostics"in Z))return;let J=Z;if(!Array.isArray(J.diagnostics))return;let Y;try{Y=J.uri.startsWith("file:")?JU(J.uri):Q0.resolve(J.uri)}catch{return}if(!this.isInsideWorkspace(Y))return;let Q=F$(Q0.resolve(Y)).href,W={sequence:++this.diagnosticSequence,serverName:$,filePath:Q0.resolve(Y),diagnostics:J.diagnostics.filter((V)=>V&&typeof V.message==="string"&&V.range!==void 0).slice(0,100).map((V)=>structuredClone(V))};this.diagnostics.set(Q,W);let U=this.waiters.get(Q)??[],X=[];for(let V of U)if(W.sequence>V.afterSequence)clearTimeout(V.timer),V.resolve();else X.push(V);if(X.length>0)this.waiters.set(Q,X);else this.waiters.delete(Q)}waitForDiagnostics($,Z,J,Y){if(J===0||(this.diagnostics.get($)?.sequence??0)>Z)return Promise.resolve();return new Promise((Q)=>{let W=!1,U,X=()=>{if(W)return;W=!0,clearTimeout(U.timer),Y?.removeEventListener("abort",X);let K=(this.waiters.get($)??[]).filter((w)=>w!==U);if(K.length>0)this.waiters.set($,K);else this.waiters.delete($);Q()},V=setTimeout(X,J);U={afterSequence:Z,resolve:X,timer:V};let H=this.waiters.get($)??[];if(H.push(U),this.waiters.set($,H),Y?.addEventListener("abort",X,{once:!0}),Y?.aborted)X()})}attachPendingDiagnostics($,Z){let J=[...this.diagnostics.values()].sort((X,V)=>{if(Z){if(X.filePath===Z&&V.filePath!==Z)return-1;if(V.filePath===Z&&X.filePath!==Z)return 1}return V.sequence-X.sequence}),Y=[],Q=[],W=0;for(let X of J){let V=F$(X.filePath).href,H=this.delivered.get(V)??new Set,K=X.diagnostics.sort((B,G)=>(B.severity??4)-(G.severity??4)).filter((B)=>!H.has(this.diagnosticKey(B))).slice(0,Math.min(WU,K9-W));if(K.length===0)continue;let w=Q0.relative(this.workspaceRoot,X.filePath);Y.push(`${w}:`);for(let B of K){let G=B.range.start.line+1,_=B.range.start.character+1,D=["Error","Warning","Info","Hint"][(B.severity??1)-1],F=B.message.replace(/\s+/g," ").slice(0,500);Y.push(` ${D??"Error"} ${G}:${_} ${F}`+(B.code!==void 0?` [${String(B.code)}]`:"")),H.add(this.diagnosticKey(B)),Q.push({file:w,line:G,character:_,severity:D??"Error",message:F,server:X.serverName}),W++}if(this.delivered.set(V,H),W>=K9)break}if(Y.length===0)return;let U=typeof $.llmContent==="string"?$.llmContent:JSON.stringify($.llmContent);$.llmContent=`${U}
132
+ `)}function tW($,Z){if($.pending>0&&$.blocked>0&&$.inProgress===0&&$.nextTask===void 0)return"waiting_dependency";if(Z.prematureStopCount>=2||Z.verificationStallCount>=2)return"repeated_deferral";if(Z.prematureStopCount<1&&Z.verificationStallCount<1)return;if($.pending>0||$.inProgress>0)return"same_task_no_effect";return}function eW($){switch($){case"waiting_dependency":return"Inspect the incomplete dependency, then execute an independent task or report the concrete external blocker.";case"repeated_deferral":return"Change strategy: validate assumptions, inspect durable results, and fix or verify the reported gap before another completion attempt.";case"same_task_no_effect":return"Change strategy: stop repeating the same step, inspect current evidence, and choose a different executable task or verification action."}}function q6($){return $.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;").replaceAll("'","&apos;")}import{createHash as $U}from"node:crypto";import{promises as F6,realpathSync as ZU}from"node:fs";import Q0 from"node:path";import{fileURLToPath as JU,pathToFileURL as F$}from"node:url";var V9=a("Service"),H9=65536;class e4{name;onCrash;child;processTree;connection;closePromise;crashCleanup;capabilities;initialized=!1;stopping=!1;notificationHandlers=new Map;requestHandlers=new Map;constructor($,Z){this.name=$;this.onCrash=Z}get serverCapabilities(){return this.capabilities}get isInitialized(){return this.initialized}async start($){if(await this.crashCleanup,this.crashCleanup=void 0,this.connection)return;let Z=await import("vscode-jsonrpc/node.js"),{child:J,processTree:Y}=E1($.command,[...$.args],{cwd:$.cwd,env:{...$.environment,PATH:$.environment.PATH??process.env.PATH??"",HOME:$.environment.HOME??process.env.HOME??"",USER:$.environment.USER??process.env.USER??"",SHELL:$.environment.SHELL??process.env.SHELL??"/bin/sh",BLADE_CLI:"1"},stdio:["pipe","pipe","pipe"]},{releaseOnExit:!1});this.child=J,this.processTree=Y;try{if(await new Promise((U,X)=>{let V=()=>{J.removeListener("spawn",H),J.removeListener("error",K)},H=()=>{V(),U()},K=(w)=>{V(),X(w)};J.once("spawn",H),J.once("error",K)}),!J.stdout||!J.stdin)throw Error("LSP server stdio is unavailable");let Q="";J.stderr?.setEncoding("utf8"),J.stderr?.on("data",(U)=>{if(Q.length<H9)Q+=U.slice(0,H9-Q.length)}),J.stdin.on("error",(U)=>{if(!this.stopping)V9.debug(`[LSP ${this.name}] stdin closed: ${U.message}`)}),this.closePromise=new Promise((U)=>{J.once("close",(X,V)=>{if(this.child!==J){U();return}this.initialized=!1;let H=!this.stopping;if(H){let w=Q.trim()?`: ${Q.trim().slice(0,512)}`:V?` (${V})`:"";this.onCrash(Error(`LSP server "${this.name}" exited with code ${X}${w}`))}let K=this.processTree;try{this.connection?.dispose()}catch{}if(this.connection=void 0,this.child=void 0,this.closePromise=void 0,H&&K)this.crashCleanup=K.terminate().then(()=>{return}),this.processTree=void 0;U()})});let W=Z.createMessageConnection(new Z.StreamMessageReader(J.stdout),new Z.StreamMessageWriter(J.stdin));this.connection=W,W.onError(([U])=>{if(!this.stopping)V9.warn(`[LSP ${this.name}] connection error: ${U.message}`)}),W.onClose(()=>{if(this.connection===W)this.initialized=!1});for(let[U,X]of this.notificationHandlers)for(let V of X)W.onNotification(U,V);for(let[U,X]of this.requestHandlers)W.onRequest(U,X);W.listen()}catch(Q){throw await this.disposeTransport(),Q}}async initialize($,Z,J){let Y=await this.request("initialize",$,Z,J,!1);return this.capabilities=Y.capabilities,await this.notify("initialized",{}),this.initialized=!0,Y}async request($,Z,J,Y,Q=!0){let W=this.connection;if(!W)throw Error(`LSP server "${this.name}" is not started`);if(Q&&!this.initialized)throw Error(`LSP server "${this.name}" is not initialized`);let X=new(await import("vscode-jsonrpc/node.js")).CancellationTokenSource;return this.awaitRequest(W.sendRequest($,Z,X.token),X,J,Y,$)}async notify($,Z){if(!this.connection)throw Error(`LSP server "${this.name}" is not started`);await this.connection.sendNotification($,Z)}onNotification($,Z){let J=this.notificationHandlers.get($)??[];J.push(Z),this.notificationHandlers.set($,J),this.connection?.onNotification($,Z)}onRequest($,Z){this.requestHandlers.set($,Z),this.connection?.onRequest($,Z)}async stop($){if(!this.child&&!this.connection){await this.crashCleanup,this.crashCleanup=void 0;return}this.stopping=!0;let Z=this.connection;try{if(Z&&this.initialized){let Y=new(await import("vscode-jsonrpc/node.js")).CancellationTokenSource;await this.awaitRequest(Z.sendRequest("shutdown",Y.token),Y,$,void 0,"shutdown").catch(()=>{return}),await Z.sendNotification("exit").catch(()=>{return})}await Promise.race([this.closePromise??Promise.resolve(),new Promise((J)=>setTimeout(J,Math.min($,500)))])}finally{await this.disposeTransport(),this.stopping=!1,this.initialized=!1,this.capabilities=void 0}}awaitRequest($,Z,J,Y,Q){return new Promise((W,U)=>{let X=!1,V=(w)=>{if(X)return;X=!0,clearTimeout(K),Y?.removeEventListener("abort",H),w()},H=()=>{Z.cancel(),V(()=>U(Error(`LSP request "${Q}" was aborted`)))},K=setTimeout(()=>{Z.cancel(),V(()=>U(Error(`LSP request "${Q}" timed out after ${J}ms`)))},J);if(Y?.addEventListener("abort",H,{once:!0}),Y?.aborted)H();$.then((w)=>V(()=>W(w)),(w)=>V(()=>U(w)))})}async disposeTransport(){let $=this.connection,Z=this.processTree;this.connection=void 0,this.processTree=void 0,this.child=void 0,this.closePromise=void 0;try{$?.dispose()}catch{}await Z?.terminate(),await this.crashCleanup,this.crashCleanup=void 0}}var YU=a("Service"),QU=10485760,WU=10,K9=30,UU=-32801;class $8{options;workspaceRoot;servers=new Map;diagnostics=new Map;delivered=new Map;waiters=new Map;disposeController=new AbortController;diagnosticSequence=0;disposed=!1;constructor($){this.options=$;let Z=Q0.resolve($.workspaceRoot);try{this.workspaceRoot=ZU.native(Z)}catch{this.workspaceRoot=Z}for(let[J,Y]of Object.entries($.servers)){if(Y.enabled===!1)continue;let Q={name:J,config:structuredClone(Y),state:"stopped",restartCount:0,openedFiles:new Map,client:new e4(J,(W)=>{Q.state="error",Q.lastError=W.message,Q.openedFiles.clear()})};Q.client.onNotification("textDocument/publishDiagnostics",(W)=>{this.captureDiagnostics(J,W)}),Q.client.onRequest("workspace/configuration",(W)=>this.resolveWorkspaceConfiguration(Y.settings,W)),Q.client.onRequest("workspace/workspaceFolders",()=>[{uri:F$(this.workspaceRoot).href,name:Q0.basename(this.workspaceRoot)}]),Q.client.onRequest("window/workDoneProgress/create",()=>null),this.servers.set(J,Q)}}get available(){return this.servers.size>0&&!this.isRemoteSession()&&!this.disposed}get workspacePath(){return this.workspaceRoot}getStatus(){return[...this.servers.values()].map(($)=>({name:$.name,state:$.state,restartCount:$.restartCount,extensions:Object.keys($.config.extensionToLanguage).sort(),...$.lastError?{lastError:$.lastError}:{}})).sort(($,Z)=>$.name.localeCompare(Z.name))}async afterToolUse($,Z,J,Y){if(!this.available||this.disposed)return;let Q;if(J.success&&($==="Write"||$==="Edit")&&typeof Z.file_path==="string")Q=await this.syncAfterWrite(Z.file_path,Y.signal);else if(J.success&&$==="ApplyPatch"){let W=Array.isArray(J.metadata?.changes)?J.metadata.changes:[];for(let U of W){if(!U||typeof U!=="object"||!("path"in U)||typeof U.path!=="string")continue;if("newContent"in U&&U.newContent===null)await this.syncAfterDelete(U.path);else Q=await this.syncAfterWrite(U.path,Y.signal)??Q}}this.attachPendingDiagnostics(J,Q)}async query($,Z){if(!this.available)throw Error(this.isRemoteSession()?"LSP is unavailable for ACP-owned remote files":"No LSP servers are configured for this Session");let J=await this.resolveFile($.filePath);if($.operation==="diagnostics")return{operation:$.operation,filePath:J,result:this.getCurrentDiagnostics(J)};let Y=await this.ensureFileOpen(J,void 0,Z);if(!Y)throw Error(`No LSP server handles ${Q0.extname(J)||"this file"}`);let Q={line:Math.max(0,($.line??1)-1),character:Math.max(0,($.character??1)-1)},W={uri:F$(J).href},U={goToDefinition:{method:"textDocument/definition",params:{textDocument:W,position:Q}},findReferences:{method:"textDocument/references",params:{textDocument:W,position:Q,context:{includeDeclaration:!0}}},hover:{method:"textDocument/hover",params:{textDocument:W,position:Q}},documentSymbol:{method:"textDocument/documentSymbol",params:{textDocument:W}},workspaceSymbol:{method:"workspace/symbol",params:{query:$.query??""}},goToImplementation:{method:"textDocument/implementation",params:{textDocument:W,position:Q}},prepareCallHierarchy:{method:"textDocument/prepareCallHierarchy",params:{textDocument:W,position:Q}}},X;if($.operation==="incomingCalls"||$.operation==="outgoingCalls"){let H=(await this.requestWithRetry(Y,"textDocument/prepareCallHierarchy",{textDocument:W,position:Q},Z))?.[0];X=H?await this.requestWithRetry(Y,$.operation==="incomingCalls"?"callHierarchy/incomingCalls":"callHierarchy/outgoingCalls",{item:H},Z):[]}else{let V=U[$.operation];X=await this.requestWithRetry(Y,V.method,V.params,Z)}return{operation:$.operation,filePath:J,serverName:Y.name,result:X}}async dispose(){if(this.disposed)return;this.disposed=!0,this.disposeController.abort();for(let $ of this.waiters.values())for(let Z of $)clearTimeout(Z.timer),Z.resolve();this.waiters.clear(),await Promise.allSettled([...this.servers.values()].map(async($)=>{$.state="stopping",await $.client.stop($.config.shutdownTimeout??2000),$.state="stopped",$.openedFiles.clear()})),this.diagnostics.clear(),this.delivered.clear()}isRemoteSession(){return this.options.isRemoteSession?.()??X0(this.options.sessionId)}selectServer($){let Z=Q0.extname($).toLowerCase();return[...this.servers.values()].filter((J)=>(Z in J.config.extensionToLanguage)).sort((J,Y)=>(Y.config.priority??0)-(J.config.priority??0)||J.name.localeCompare(Y.name))[0]}async ensureFileOpen($,Z,J){let Y=this.selectServer($);if(!Y)return;await this.ensureStarted(Y,J);let Q=F$($).href;if(Y.openedFiles.has(Q))return Y;let W=Z??await this.readBoundedFile($);return await Y.client.notify("textDocument/didOpen",{textDocument:{uri:Q,languageId:Y.config.extensionToLanguage[Q0.extname($).toLowerCase()],version:1,text:W}}),Y.openedFiles.set(Q,1),Y}async syncAfterWrite($,Z){try{let J=await this.resolveFile($),Y=await this.readBoundedFile(J),Q=await this.ensureFileOpen(J,Y,Z);if(!Q)return;let W=F$(J).href,U=this.diagnostics.get(W)?.sequence??0;this.delivered.delete(W);let X=Q.openedFiles.get(W)??0;if(X>0){let V=X+1;await Q.client.notify("textDocument/didChange",{textDocument:{uri:W,version:V},contentChanges:[{text:Y}]}),Q.openedFiles.set(W,V)}return await Q.client.notify("textDocument/didSave",{textDocument:{uri:W},text:Y}),await this.waitForDiagnostics(W,U,Q.config.diagnosticWaitTimeout??750,Z),J}catch(J){if(!Z?.aborted&&!this.disposeController.signal.aborted)YU.debug(`[LSP] post-edit sync skipped: ${J instanceof Error?J.message:String(J)}`);return}}async syncAfterDelete($){let Z=await this.resolveMissingFile($).catch(()=>{return});if(!Z)return;if(!this.isInsideWorkspace(Z))return;let J=F$(Z).href;for(let Y of this.servers.values()){if(!Y.openedFiles.has(J))continue;await Y.client.notify("textDocument/didClose",{textDocument:{uri:J}}).catch(()=>{return}),Y.openedFiles.delete(J)}this.diagnostics.delete(J),this.delivered.delete(J)}async ensureStarted($,Z){if($.state==="running")return;if($.startPromise)return $.startPromise;if($.state==="error"){if($.restartCount>=($.config.maxRestarts??3))throw Error(`LSP server "${$.name}" exceeded its restart limit`);$.restartCount++}let J=this.startServer($,Z).finally(()=>{$.startPromise=void 0});return $.startPromise=J,J}async startServer($,Z){$.state="starting";try{await $.client.start({command:$.config.command,args:$.config.args??[],cwd:this.workspaceRoot,environment:{...this.options.environment,...$.config.env,BLADE_SESSION_ID:this.options.sessionId}});let J=F$(this.workspaceRoot).href,Y={processId:process.pid,rootPath:this.workspaceRoot,rootUri:J,workspaceFolders:[{uri:J,name:Q0.basename(this.workspaceRoot)}],initializationOptions:$.config.initializationOptions??{},capabilities:{workspace:{configuration:!0,workspaceFolders:!0,symbol:{dynamicRegistration:!1}},textDocument:{synchronization:{dynamicRegistration:!1,willSave:!1,willSaveWaitUntil:!1,didSave:!0},publishDiagnostics:{relatedInformation:!0,versionSupport:!1},hover:{dynamicRegistration:!1,contentFormat:["markdown","plaintext"]},definition:{dynamicRegistration:!1,linkSupport:!0},references:{dynamicRegistration:!1},implementation:{dynamicRegistration:!1,linkSupport:!0},documentSymbol:{dynamicRegistration:!1,hierarchicalDocumentSymbolSupport:!0},callHierarchy:{dynamicRegistration:!1}},general:{positionEncodings:["utf-16"]}}};if(await $.client.initialize(Y,$.config.startupTimeout??1e4,Z),$.config.settings!==void 0)await $.client.notify("workspace/didChangeConfiguration",{settings:$.config.settings});$.state="running",$.lastError=void 0}catch(J){throw $.state="error",$.lastError=J instanceof Error?J.message:String(J),await $.client.stop($.config.shutdownTimeout??2000).catch(()=>{return}),J}}async requestWithRetry($,Z,J,Y){let Q;for(let W=0;W<4;W++)try{return await $.client.request(Z,J,$.config.requestTimeout??1e4,Y)}catch(U){if(Q=U,U.code!==UU||W===3)break;await new Promise((X)=>setTimeout(X,100*2**W))}throw Q}captureDiagnostics($,Z){if(this.disposed||!Z||typeof Z!=="object"||!("uri"in Z)||!("diagnostics"in Z))return;let J=Z;if(!Array.isArray(J.diagnostics))return;let Y;try{Y=J.uri.startsWith("file:")?JU(J.uri):Q0.resolve(J.uri)}catch{return}if(!this.isInsideWorkspace(Y))return;let Q=F$(Q0.resolve(Y)).href,W={sequence:++this.diagnosticSequence,serverName:$,filePath:Q0.resolve(Y),diagnostics:J.diagnostics.filter((V)=>V&&typeof V.message==="string"&&V.range!==void 0).slice(0,100).map((V)=>structuredClone(V))};this.diagnostics.set(Q,W);let U=this.waiters.get(Q)??[],X=[];for(let V of U)if(W.sequence>V.afterSequence)clearTimeout(V.timer),V.resolve();else X.push(V);if(X.length>0)this.waiters.set(Q,X);else this.waiters.delete(Q)}waitForDiagnostics($,Z,J,Y){if(J===0||(this.diagnostics.get($)?.sequence??0)>Z)return Promise.resolve();return new Promise((Q)=>{let W=!1,U,X=()=>{if(W)return;W=!0,clearTimeout(U.timer),Y?.removeEventListener("abort",X);let K=(this.waiters.get($)??[]).filter((w)=>w!==U);if(K.length>0)this.waiters.set($,K);else this.waiters.delete($);Q()},V=setTimeout(X,J);U={afterSequence:Z,resolve:X,timer:V};let H=this.waiters.get($)??[];if(H.push(U),this.waiters.set($,H),Y?.addEventListener("abort",X,{once:!0}),Y?.aborted)X()})}attachPendingDiagnostics($,Z){let J=[...this.diagnostics.values()].sort((X,V)=>{if(Z){if(X.filePath===Z&&V.filePath!==Z)return-1;if(V.filePath===Z&&X.filePath!==Z)return 1}return V.sequence-X.sequence}),Y=[],Q=[],W=0;for(let X of J){let V=F$(X.filePath).href,H=this.delivered.get(V)??new Set,K=X.diagnostics.sort((B,G)=>(B.severity??4)-(G.severity??4)).filter((B)=>!H.has(this.diagnosticKey(B))).slice(0,Math.min(WU,K9-W));if(K.length===0)continue;let w=Q0.relative(this.workspaceRoot,X.filePath);Y.push(`${w}:`);for(let B of K){let G=B.range.start.line+1,_=B.range.start.character+1,D=["Error","Warning","Info","Hint"][(B.severity??1)-1],F=B.message.replace(/\s+/g," ").slice(0,500);Y.push(` ${D??"Error"} ${G}:${_} ${F}`+(B.code!==void 0?` [${String(B.code)}]`:"")),H.add(this.diagnosticKey(B)),Q.push({file:w,line:G,character:_,severity:D??"Error",message:F,server:X.serverName}),W++}if(this.delivered.set(V,H),W>=K9)break}if(Y.length===0)return;let U=typeof $.llmContent==="string"?$.llmContent:JSON.stringify($.llmContent);$.llmContent=`${U}
133
133
 
134
134
  <new-diagnostics>
135
135
  LSP reported new issues after this operation:
@@ -848,7 +848,7 @@ ${$1}
848
848
  </approved-plan>
849
849
 
850
850
  IMPORTANT: Execute according to the approved plan above. Follow the steps exactly as specified.`;if(typeof q==="string")F0=q+M$;else F0=[...q,{type:"text",text:M$}]}S=yield*this.runLoop(F0,b,{...k,inputMessageId:void 0})}if(!this.sessionRuntime||!v)return S;let r=await this.sessionRuntime.recordGoalProgress({tokens:S.metadata?.tokensUsed??0,elapsedMs:S.metadata?.duration??0,prematureStopPattern:S.success?Q7(S.finalMessage):void 0});if(r)yield{kind:"goal_updated",goal:r};if(!S.success||b.signal?.aborted){if(r=await this.sessionRuntime.pauseActiveGoal(b.signal?.aborted?"goal paused after user cancellation":S.error?.message??"goal paused after turn failure"),r)yield{kind:"goal_updated",goal:r}}if(S.success&&!b.signal?.aborted&&h<20)await this.sessionRuntime.waitForBackgroundSubagentFollowUp(v,b.signal);let $0=S.success&&!b.signal?.aborted&&h<20,p=GH(S);if(x=await this.sessionRuntime.finishTurn(v,{continuePending:$0,...p?{acknowledgeInput:!0}:{},outcome:S.success&&!b.signal?.aborted?{status:"completed",turnsCount:S.metadata?.turnsCount??0,toolCallsCount:S.metadata?.toolCallsCount??0,durationMs:S.metadata?.duration??0}:{status:"aborted",cause:b.signal?.aborted?"cancelled":"failed",turnsCount:S.metadata?.turnsCount??0,toolCallsCount:S.metadata?.toolCallsCount??0,durationMs:S.metadata?.duration??0}}),x){h++,N=!0,E=!1,O=null,q="",R=void 0,T="",C=void 0,j=m(),yield{kind:"follow_up_started",queued:this.sessionRuntime.getPendingSteeringCount(),recovered:this.sessionRuntime.getRecoveredSteeringCount(),messages:e()};continue}if(!S.success||b.signal?.aborted)return S;if(r=await this.sessionRuntime.getGoal(),!r||r.status!=="active"&&r.status!=="verifying")return S;let Q$=await this.sessionRuntime.beginGoalContinuation();if(!Q$)return S;let Y0=await this.sessionRuntime.prepareGoalContinuation(Q$);if(!Y0.ok){if(Y0.goal)yield{kind:"goal_updated",goal:Y0.goal};return{success:!1,error:{type:"goal_frontier_unavailable",message:Y0.error.message},metadata:{turnsCount:S.metadata?.turnsCount??0,toolCallsCount:S.metadata?.toolCallsCount??0,duration:S.metadata?.duration??0}}}O=Y0.goal,_=Y0,x=await this.sessionRuntime.beginTurn("goal"),N=!1,E=!0,q=P8(O),R=void 0,j=void 0,yield{kind:"goal_frontier_updated",goal:Y0.goal,frontier:Y0.frontier,tasks:Y0.tasks},yield{kind:"goal_continuation_started",goal:O,continuation:O.continuationCount,...O.prematureStop?{prematureStopPattern:O.prematureStop.pattern,prematureStopCount:O.prematureStop.consecutiveCount}:{}},yield{kind:"goal_updated",goal:O}}}finally{if(this.sessionRuntime&&x)await this.sessionRuntime.finishTurn(x)}}let D=typeof K==="string"?K:K.filter((q)=>q.type==="text").map((q)=>q.text).join(`
851
- `),F={id:this.generateTaskId(),type:"simple",prompt:D};return{success:!0,finalMessage:(await this.executeTask(F)).content,metadata:{turnsCount:1,toolCallsCount:0,duration:0}}}async chat($,Z,J){let{drainLoop:Y}=await import("./chunk-6v10cs0h.js");return Y(this.chatStream($,Z,J))}async*runPlanLoop($,Z,J){n.debug("Processing Plan mode message...");let{prompt:Y}=await g$({projectPath:Z.workspaceRoot||M(),mode:"plan",includeEnvironment:!0,environmentOptions:S2,language:this.config.language,availableSkills:this.agentResources?.skills.generateAvailableSkillsList(),communicationStyle:this.sessionRuntime?.getCommunicationStyleConfiguration().selection,communicationStyleCatalog:this.sessionRuntime?.getCommunicationStyleCatalog(),projectRuleCatalog:this.sessionRuntime?.getProjectRuleCatalog(),projectInstructionSourcePath:this.sessionRuntime?.projectRoot}),Q;if(typeof $==="string")Q=L2($);else{let W=$.filter((U)=>U.type==="text");if(W.length>0){let U=W[0];Q=$.map((X)=>X===U?{type:"text",text:L2(U.text)}:X)}else Q=[{type:"text",text:L2("")},...$]}return yield*this.executeLoop(Q,Z,J,Y)}async*runLoop($,Z,J){n.debug("Processing enhanced chat message...");let Y=Z.systemPrompt??await this.buildSystemPromptOnDemand(Z.workspaceRoot||M());return yield*this.executeLoop($,Z,J,Y)}async buildSystemPromptOnDemand($){let Z=this.runtimeOptions.systemPrompt,J=this.runtimeOptions.appendSystemPrompt;return(await g$({projectPath:$,replaceDefault:Z,append:J,includeEnvironment:!0,environmentOptions:S2,language:this.config.language,availableSkills:this.agentResources?.skills.generateAvailableSkillsList(),communicationStyle:this.sessionRuntime?.getCommunicationStyleConfiguration().selection,communicationStyleCatalog:this.sessionRuntime?.getCommunicationStyleCatalog(),projectRuleCatalog:this.sessionRuntime?.getProjectRuleCatalog(),projectInstructionSourcePath:this.sessionRuntime?.projectRoot})).prompt}executeLoop($,Z,J,Y){if(!this.isInitialized)throw Error("Agent未初始化");let Q=this.buildLoopDependencies();return p7(Q,$,Z,J,Y)}takeStartupAdoptedToolResultEvents(){return(this.sessionRuntime?.takeStartupAdoptedToolResults()??[]).flatMap(({call:Z,result:J})=>{let Y={id:Z.toolCallId,type:"function",function:{name:Z.toolName,arguments:JSON.stringify(Z.input)}},Q=J.metadata&&typeof J.metadata==="object"&&!Array.isArray(J.metadata)?J.metadata:void 0,W=J.error===void 0,U=J.output,X={success:W,llmContent:typeof U==="string"||U!==null&&typeof U==="object"?U:U===null?J.error?`Subagent execution failed: ${J.error}.`:"":String(U),...J.error?{error:{type:"execution_error",message:J.error}}:{},...Q?{metadata:Q}:{}},V=[{kind:"tool_result",toolCall:Y,result:X}],H=m7(Y,X);if(H)V.push(H);return V})}takeStartupRecoveryEvents(){let $=this.sessionRuntime?.getTurnRecoveryAssessment(),Z=$?.state==="requires_attention"?$:this.sessionRuntime?.takeStartupTurnRecoveryAssessment(),J=Z&&Z.state!=="none"?[{kind:"turn_recovery",assessment:Z}]:[];return J.push(...this.takeStartupAdoptedToolResultEvents()),J}buildLoopDependencies(){return{chatService:this.chatService,toolExecutor:this.toolExecutor,executionEngine:this.executionEngine,config:this.config,runtimeOptions:this.runtimeOptions,currentModelMaxContextTokens:this.currentModelMaxContextTokens,activeSkillContext:this.activeSkillContext,onSkillActivated:($)=>{this.activeSkillContext=$,n.debug(`Skill "${$.skillName}" activated`+($.allowedTools?` with allowed tools: ${$.allowedTools.join(", ")}`:""))},onModelSwitch:($)=>this.switchModelIfNeeded($),applySkillToolRestrictions:($)=>this.applySkillToolRestrictions($),staticProjectRules:this.sessionRuntime?.getStaticProjectRules(),hydrateProjectRules:this.sessionRuntime?($)=>this.sessionRuntime.hydrateProjectRules($):void 0,resolveContextualProjectRules:this.sessionRuntime?($,Z,J,Y)=>this.sessionRuntime.resolveContextualProjectRules($,Z,J,Y):void 0}}async chatWithSystem($,Z){if(!this.isInitialized)throw Error("Agent未初始化");let J=[{role:"system",content:$},{role:"user",content:Z}];return(await this.chatService.chat(J)).content}getActiveTask(){return this.activeTask}getChatService(){return this.chatService}getContextManager(){return this.executionEngine?.getContextManager()}getStats(){return{initialized:this.isInitialized,activeTask:this.activeTask?.id,components:{chatService:this.chatService?"ready":"not_loaded",executionEngine:this.executionEngine?"ready":"not_loaded"}}}getAvailableTools(){return this.toolExecutor?this.toolExecutor.getRegistry().getAll():[]}getToolRegistry(){return this.toolExecutor.getRegistry()}applyToolWhitelist($){let Z=this.toolExecutor.getRegistry(),Y=Z.getAll().filter((Q)=>!$.includes(Q.name));for(let Q of Y)Z.unregister(Q.name);n.debug(`Applied tool whitelist: ${$.join(", ")} (removed ${Y.length} tools)`)}applyToolBlacklist($){let Z=this.toolExecutor.getRegistry(),J=new Set($);for(let Y of Z.getAll())if(J.has(Y.name))Z.unregister(Y.name);n.debug(`Applied tool blacklist: ${$.join(", ")}`)}getToolStats(){let $=this.getAvailableTools(),Z=new Map;return $.forEach((J)=>{let Y=Z.get(J.kind)||0;Z.set(J.kind,Y+1)}),{totalTools:$.length,toolsByKind:Object.fromEntries(Z),toolNames:$.map((J)=>J.name)}}async destroy(){if(this.destroyPromise)return this.destroyPromise;return this.destroyPromise=(async()=>{this.log("销毁Agent..."),await this.activeOperations.shutdown("agent-destroy");try{await this.legacyMcpRegistry?.disconnectAll(),this.legacyMcpRegistry=void 0,this.log("Agent已销毁")}catch($){throw this.error("Agent销毁失败",$),$}finally{this.toolExecutor.dispose(),this.isInitialized=!1}})(),this.destroyPromise}syncRuntimeState(){if(!this.sessionRuntime)return;this.chatService=this.sessionRuntime.getChatService(),this.executionEngine=this.sessionRuntime.getExecutionEngine(),this.attachmentCollector=this.sessionRuntime.getAttachmentCollector(),this.currentModelId=this.sessionRuntime.getCurrentModelId(),this.currentModelMaxContextTokens=this.sessionRuntime.getCurrentModelMaxContextTokens()}generateTaskId(){return`task_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}log($,Z){n.debug(`[MainAgent] ${$}`,Z||"")}error($,Z){n.error(`[MainAgent] ${$}`,Z||"")}async initializeSystemPrompt(){try{let $=this.runtimeOptions.systemPrompt,Z=this.runtimeOptions.appendSystemPrompt,J=await g$({projectPath:this.sessionRuntime?.workspaceRoot??M(),replaceDefault:$,append:Z,includeEnvironment:!1,language:this.config.language,availableSkills:this.agentResources?.skills.generateAvailableSkillsList(),communicationStyle:this.sessionRuntime?.getCommunicationStyleConfiguration().selection,communicationStyleCatalog:this.sessionRuntime?.getCommunicationStyleCatalog(),projectRuleCatalog:this.sessionRuntime?.getProjectRuleCatalog(),projectInstructionSourcePath:this.sessionRuntime?.projectRoot});if(J.prompt)this.log("系统提示配置验证成功"),n.debug(`[SystemPrompt] 可用来源: ${J.sources.filter((Y)=>Y.loaded).map((Y)=>Y.name).join(", ")}`)}catch($){this.error("系统提示配置验证失败",$)}}async registerBuiltinTools(){try{let $=await n6({sessionId:"default",configDir:s(),workspaceRoot:M(),resourceRoot:M(),agentResources:this.agentResources});n.debug(`Registering ${$.length} builtin tools...`),this.toolExecutor.getRegistry().registerAll($);let Z=this.toolExecutor.getRegistry().getAll().length;n.debug(`Builtin tools registered: ${Z} tools`),n.debug(`[Tools] ${this.toolExecutor.getRegistry().getAll().map((J)=>J.name).join(", ")}`),await this.registerMcpTools()}catch($){throw n.error("Failed to register builtin tools:",$),$}}async registerMcpTools(){try{let $=await N6({workspaceRoot:M(),storeServers:this.config.mcpServers??{},cliConfigs:this.runtimeOptions.mcpConfig,strictCliConfig:this.runtimeOptions.strictMcpConfig});if(Object.keys($).length===0){n.debug("No MCP servers configured");return}let Z=i0.createIsolated({artifactWriter:new F2(`legacy-${BH()}`)});this.legacyMcpRegistry=Z;for(let[W,U]of Object.entries($))try{n.debug(`Connecting to MCP server: ${W}`),await Z.registerServer(W,U),n.debug(`MCP server "${W}" connected`)}catch(X){n.warn(`Warning: MCP server "${W}" connection failed:`,X)}let J=this.toolExecutor.getRegistry();J.setMcpCatalogBarrier(()=>Z.waitForCatalogIdle());let Y=Z.getCatalogSnapshot();J.replaceMcpTools(Y.tools),J.registerAll(j2(Z));let Q=Z.getInstructionsSnapshot();if(J.queueMcpInstructionsChange({revision:Q.revision,reason:"snapshot",replace:!0,instructions:Q.instructions,removed:[]}),Z.on("catalogChanged",(W)=>{J.replaceMcpTools(W.tools,W)}),Z.on("contentCatalogChanged",(W)=>{J.queueMcpContentChange(W)}),Z.on("resourceUpdated",(W)=>{J.queueMcpResourceUpdated(W)}),Z.on("connectionLifecycleChanged",(W)=>{J.queueMcpConnectionChange(W)}),Z.on("log",(W)=>{J.queueMcpLog(W)}),Z.on("instructionsChanged",(W)=>{J.queueMcpInstructionsChange({revision:W.revision,reason:W.reason,replace:!1,instructions:W.action==="added"&&W.instruction?[{serverName:W.serverName,...W.instruction}]:[],removed:W.action==="removed"?[W.serverName]:[]})}),Y.tools.length>0)n.debug(`Registered ${Y.tools.length} MCP tools`),n.debug(`[MCP Tools] ${Y.tools.map((W)=>W.name).join(", ")}`)}catch($){n.warn("Failed to register MCP tools:",$)}}async loadSubagents(){let $=await I0(M());if(this.agentResources=i6($),this.subagentRegistry=this.agentResources.subagents,this.runtimeOptions.agents?.length)this.subagentRegistry.applyOverrides(this.runtimeOptions.agents);let Z=this.subagentRegistry.getAllNames().length;if(Z>0)n.debug(`Loaded ${Z} subagents: ${this.subagentRegistry.getAllNames().join(", ")}`);else n.debug("No subagents configured")}applySkillToolRestrictions($){if(!this.activeSkillContext?.allowedTools)return $;let Z=this.activeSkillContext.allowedTools;n.debug(`Applying Skill tool restrictions: ${Z.join(", ")}`);let J=$.filter((Y)=>{if(Y.name==="ReadPromptArtifact")return!0;return Z.some((Q)=>{if(Q===Y.name)return!0;let W=Q.match(/^(\w+)\(.*\)$/);if(W&&W[1]===Y.name)return!0;return!1})});return n.debug(`Filtered tools: ${J.map((Y)=>Y.name).join(", ")} (${J.length}/${$.length})`),J}clearSkillContext(){if(this.activeSkillContext)n.debug(`Skill "${this.activeSkillContext.skillName}" deactivated`),this.activeSkillContext=void 0}async processAtMentionsForContent($){if(!this.attachmentCollector)return $;if(typeof $==="string")return this.processAtMentions($);let Z=[];for(let Y of $)if(Y.type==="text")Z.push(Y.text);if(Z.length===0)return $;let J=Z.join(`
851
+ `),F={id:this.generateTaskId(),type:"simple",prompt:D};return{success:!0,finalMessage:(await this.executeTask(F)).content,metadata:{turnsCount:1,toolCallsCount:0,duration:0}}}async chat($,Z,J){let{drainLoop:Y}=await import("./chunk-c0m2vw2q.js");return Y(this.chatStream($,Z,J))}async*runPlanLoop($,Z,J){n.debug("Processing Plan mode message...");let{prompt:Y}=await g$({projectPath:Z.workspaceRoot||M(),mode:"plan",includeEnvironment:!0,environmentOptions:S2,language:this.config.language,availableSkills:this.agentResources?.skills.generateAvailableSkillsList(),communicationStyle:this.sessionRuntime?.getCommunicationStyleConfiguration().selection,communicationStyleCatalog:this.sessionRuntime?.getCommunicationStyleCatalog(),projectRuleCatalog:this.sessionRuntime?.getProjectRuleCatalog(),projectInstructionSourcePath:this.sessionRuntime?.projectRoot}),Q;if(typeof $==="string")Q=L2($);else{let W=$.filter((U)=>U.type==="text");if(W.length>0){let U=W[0];Q=$.map((X)=>X===U?{type:"text",text:L2(U.text)}:X)}else Q=[{type:"text",text:L2("")},...$]}return yield*this.executeLoop(Q,Z,J,Y)}async*runLoop($,Z,J){n.debug("Processing enhanced chat message...");let Y=Z.systemPrompt??await this.buildSystemPromptOnDemand(Z.workspaceRoot||M());return yield*this.executeLoop($,Z,J,Y)}async buildSystemPromptOnDemand($){let Z=this.runtimeOptions.systemPrompt,J=this.runtimeOptions.appendSystemPrompt;return(await g$({projectPath:$,replaceDefault:Z,append:J,includeEnvironment:!0,environmentOptions:S2,language:this.config.language,availableSkills:this.agentResources?.skills.generateAvailableSkillsList(),communicationStyle:this.sessionRuntime?.getCommunicationStyleConfiguration().selection,communicationStyleCatalog:this.sessionRuntime?.getCommunicationStyleCatalog(),projectRuleCatalog:this.sessionRuntime?.getProjectRuleCatalog(),projectInstructionSourcePath:this.sessionRuntime?.projectRoot})).prompt}executeLoop($,Z,J,Y){if(!this.isInitialized)throw Error("Agent未初始化");let Q=this.buildLoopDependencies();return p7(Q,$,Z,J,Y)}takeStartupAdoptedToolResultEvents(){return(this.sessionRuntime?.takeStartupAdoptedToolResults()??[]).flatMap(({call:Z,result:J})=>{let Y={id:Z.toolCallId,type:"function",function:{name:Z.toolName,arguments:JSON.stringify(Z.input)}},Q=J.metadata&&typeof J.metadata==="object"&&!Array.isArray(J.metadata)?J.metadata:void 0,W=J.error===void 0,U=J.output,X={success:W,llmContent:typeof U==="string"||U!==null&&typeof U==="object"?U:U===null?J.error?`Subagent execution failed: ${J.error}.`:"":String(U),...J.error?{error:{type:"execution_error",message:J.error}}:{},...Q?{metadata:Q}:{}},V=[{kind:"tool_result",toolCall:Y,result:X}],H=m7(Y,X);if(H)V.push(H);return V})}takeStartupRecoveryEvents(){let $=this.sessionRuntime?.getTurnRecoveryAssessment(),Z=$?.state==="requires_attention"?$:this.sessionRuntime?.takeStartupTurnRecoveryAssessment(),J=Z&&Z.state!=="none"?[{kind:"turn_recovery",assessment:Z}]:[];return J.push(...this.takeStartupAdoptedToolResultEvents()),J}buildLoopDependencies(){return{chatService:this.chatService,toolExecutor:this.toolExecutor,executionEngine:this.executionEngine,config:this.config,runtimeOptions:this.runtimeOptions,currentModelMaxContextTokens:this.currentModelMaxContextTokens,activeSkillContext:this.activeSkillContext,onSkillActivated:($)=>{this.activeSkillContext=$,n.debug(`Skill "${$.skillName}" activated`+($.allowedTools?` with allowed tools: ${$.allowedTools.join(", ")}`:""))},onModelSwitch:($)=>this.switchModelIfNeeded($),applySkillToolRestrictions:($)=>this.applySkillToolRestrictions($),staticProjectRules:this.sessionRuntime?.getStaticProjectRules(),hydrateProjectRules:this.sessionRuntime?($)=>this.sessionRuntime.hydrateProjectRules($):void 0,resolveContextualProjectRules:this.sessionRuntime?($,Z,J,Y)=>this.sessionRuntime.resolveContextualProjectRules($,Z,J,Y):void 0}}async chatWithSystem($,Z){if(!this.isInitialized)throw Error("Agent未初始化");let J=[{role:"system",content:$},{role:"user",content:Z}];return(await this.chatService.chat(J)).content}getActiveTask(){return this.activeTask}getChatService(){return this.chatService}getContextManager(){return this.executionEngine?.getContextManager()}getStats(){return{initialized:this.isInitialized,activeTask:this.activeTask?.id,components:{chatService:this.chatService?"ready":"not_loaded",executionEngine:this.executionEngine?"ready":"not_loaded"}}}getAvailableTools(){return this.toolExecutor?this.toolExecutor.getRegistry().getAll():[]}getToolRegistry(){return this.toolExecutor.getRegistry()}applyToolWhitelist($){let Z=this.toolExecutor.getRegistry(),Y=Z.getAll().filter((Q)=>!$.includes(Q.name));for(let Q of Y)Z.unregister(Q.name);n.debug(`Applied tool whitelist: ${$.join(", ")} (removed ${Y.length} tools)`)}applyToolBlacklist($){let Z=this.toolExecutor.getRegistry(),J=new Set($);for(let Y of Z.getAll())if(J.has(Y.name))Z.unregister(Y.name);n.debug(`Applied tool blacklist: ${$.join(", ")}`)}getToolStats(){let $=this.getAvailableTools(),Z=new Map;return $.forEach((J)=>{let Y=Z.get(J.kind)||0;Z.set(J.kind,Y+1)}),{totalTools:$.length,toolsByKind:Object.fromEntries(Z),toolNames:$.map((J)=>J.name)}}async destroy(){if(this.destroyPromise)return this.destroyPromise;return this.destroyPromise=(async()=>{this.log("销毁Agent..."),await this.activeOperations.shutdown("agent-destroy");try{await this.legacyMcpRegistry?.disconnectAll(),this.legacyMcpRegistry=void 0,this.log("Agent已销毁")}catch($){throw this.error("Agent销毁失败",$),$}finally{this.toolExecutor.dispose(),this.isInitialized=!1}})(),this.destroyPromise}syncRuntimeState(){if(!this.sessionRuntime)return;this.chatService=this.sessionRuntime.getChatService(),this.executionEngine=this.sessionRuntime.getExecutionEngine(),this.attachmentCollector=this.sessionRuntime.getAttachmentCollector(),this.currentModelId=this.sessionRuntime.getCurrentModelId(),this.currentModelMaxContextTokens=this.sessionRuntime.getCurrentModelMaxContextTokens()}generateTaskId(){return`task_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}log($,Z){n.debug(`[MainAgent] ${$}`,Z||"")}error($,Z){n.error(`[MainAgent] ${$}`,Z||"")}async initializeSystemPrompt(){try{let $=this.runtimeOptions.systemPrompt,Z=this.runtimeOptions.appendSystemPrompt,J=await g$({projectPath:this.sessionRuntime?.workspaceRoot??M(),replaceDefault:$,append:Z,includeEnvironment:!1,language:this.config.language,availableSkills:this.agentResources?.skills.generateAvailableSkillsList(),communicationStyle:this.sessionRuntime?.getCommunicationStyleConfiguration().selection,communicationStyleCatalog:this.sessionRuntime?.getCommunicationStyleCatalog(),projectRuleCatalog:this.sessionRuntime?.getProjectRuleCatalog(),projectInstructionSourcePath:this.sessionRuntime?.projectRoot});if(J.prompt)this.log("系统提示配置验证成功"),n.debug(`[SystemPrompt] 可用来源: ${J.sources.filter((Y)=>Y.loaded).map((Y)=>Y.name).join(", ")}`)}catch($){this.error("系统提示配置验证失败",$)}}async registerBuiltinTools(){try{let $=await n6({sessionId:"default",configDir:s(),workspaceRoot:M(),resourceRoot:M(),agentResources:this.agentResources});n.debug(`Registering ${$.length} builtin tools...`),this.toolExecutor.getRegistry().registerAll($);let Z=this.toolExecutor.getRegistry().getAll().length;n.debug(`Builtin tools registered: ${Z} tools`),n.debug(`[Tools] ${this.toolExecutor.getRegistry().getAll().map((J)=>J.name).join(", ")}`),await this.registerMcpTools()}catch($){throw n.error("Failed to register builtin tools:",$),$}}async registerMcpTools(){try{let $=await N6({workspaceRoot:M(),storeServers:this.config.mcpServers??{},cliConfigs:this.runtimeOptions.mcpConfig,strictCliConfig:this.runtimeOptions.strictMcpConfig});if(Object.keys($).length===0){n.debug("No MCP servers configured");return}let Z=i0.createIsolated({artifactWriter:new F2(`legacy-${BH()}`)});this.legacyMcpRegistry=Z;for(let[W,U]of Object.entries($))try{n.debug(`Connecting to MCP server: ${W}`),await Z.registerServer(W,U),n.debug(`MCP server "${W}" connected`)}catch(X){n.warn(`Warning: MCP server "${W}" connection failed:`,X)}let J=this.toolExecutor.getRegistry();J.setMcpCatalogBarrier(()=>Z.waitForCatalogIdle());let Y=Z.getCatalogSnapshot();J.replaceMcpTools(Y.tools),J.registerAll(j2(Z));let Q=Z.getInstructionsSnapshot();if(J.queueMcpInstructionsChange({revision:Q.revision,reason:"snapshot",replace:!0,instructions:Q.instructions,removed:[]}),Z.on("catalogChanged",(W)=>{J.replaceMcpTools(W.tools,W)}),Z.on("contentCatalogChanged",(W)=>{J.queueMcpContentChange(W)}),Z.on("resourceUpdated",(W)=>{J.queueMcpResourceUpdated(W)}),Z.on("connectionLifecycleChanged",(W)=>{J.queueMcpConnectionChange(W)}),Z.on("log",(W)=>{J.queueMcpLog(W)}),Z.on("instructionsChanged",(W)=>{J.queueMcpInstructionsChange({revision:W.revision,reason:W.reason,replace:!1,instructions:W.action==="added"&&W.instruction?[{serverName:W.serverName,...W.instruction}]:[],removed:W.action==="removed"?[W.serverName]:[]})}),Y.tools.length>0)n.debug(`Registered ${Y.tools.length} MCP tools`),n.debug(`[MCP Tools] ${Y.tools.map((W)=>W.name).join(", ")}`)}catch($){n.warn("Failed to register MCP tools:",$)}}async loadSubagents(){let $=await I0(M());if(this.agentResources=i6($),this.subagentRegistry=this.agentResources.subagents,this.runtimeOptions.agents?.length)this.subagentRegistry.applyOverrides(this.runtimeOptions.agents);let Z=this.subagentRegistry.getAllNames().length;if(Z>0)n.debug(`Loaded ${Z} subagents: ${this.subagentRegistry.getAllNames().join(", ")}`);else n.debug("No subagents configured")}applySkillToolRestrictions($){if(!this.activeSkillContext?.allowedTools)return $;let Z=this.activeSkillContext.allowedTools;n.debug(`Applying Skill tool restrictions: ${Z.join(", ")}`);let J=$.filter((Y)=>{if(Y.name==="ReadPromptArtifact")return!0;return Z.some((Q)=>{if(Q===Y.name)return!0;let W=Q.match(/^(\w+)\(.*\)$/);if(W&&W[1]===Y.name)return!0;return!1})});return n.debug(`Filtered tools: ${J.map((Y)=>Y.name).join(", ")} (${J.length}/${$.length})`),J}clearSkillContext(){if(this.activeSkillContext)n.debug(`Skill "${this.activeSkillContext.skillName}" deactivated`),this.activeSkillContext=void 0}async processAtMentionsForContent($){if(!this.attachmentCollector)return $;if(typeof $==="string")return this.processAtMentions($);let Z=[];for(let Y of $)if(Y.type==="text")Z.push(Y.text);if(Z.length===0)return $;let J=Z.join(`
852
852
  `);try{let Y=await this.attachmentCollector.collect(J);if(Y.length===0)return $;n.debug(`Processed ${Y.length} @ file mentions in multimodal message`);let Q=this.buildAttachmentText(Y);if(!Q)return $;return[...$,{type:"text",text:Q}]}catch(Y){return n.error("Failed to process @ mentions in multimodal message:",Y),$}}buildAttachmentText($){let Z=[],J=[];for(let Q of $)if(Q.type==="file"){let W=Q.metadata?.lineRange?` (lines ${Q.metadata.lineRange.start}${Q.metadata.lineRange.end?`-${Q.metadata.lineRange.end}`:""})`:"";Z.push(`<file path="${Q.path}"${W?` range="${W}"`:""}>`,Q.content,"</file>")}else if(Q.type==="directory")Z.push(`<directory path="${Q.path}">`,Q.content,"</directory>");else if(Q.type==="error")J.push(`- @${Q.path}: ${Q.error}`);let Y="";if(Z.length>0)Y+=`
853
853
 
854
854
  <system-reminder>
@@ -1658,7 +1658,7 @@ ${J}
1658
1658
  `)),{success:!0,message:"Schedules listed",content:V.join(`
1659
1659
  `)}}case"create":{let X=xB(W);if("error"in X)return Y.sendMessage(`创建失败:${X.error}`),{success:!1,error:X.error};let V={prompt:X.prompt,projectPath:U,trigger:X.trigger,isolation:"worktree",permissionMode:"default",enabled:!0};try{let H=await $.create(V),K=H.nextRunAt?new Date(H.nextRunAt).toLocaleString():"(无)";return Y.sendMessage(`[OK] 已创建定时任务 \`${H.id}\`
1660
1660
  ${VZ(H.trigger)} · 下次运行: ${K}`),{success:!0,message:`Schedule ${H.id} created`}}catch(H){let K=H instanceof Error?H.message:String(H);return Y.sendMessage(`创建失败:${K}`),{success:!1,error:K}}}case"remove":case"rm":{let X=W[0];if(!X)return Y.sendMessage("用法:/schedule remove <id>"),{success:!1,error:"Missing schedule id"};let V=await $.remove(X);return Y.sendMessage(V?`[OK] 已删除 \`${X}\``:`未找到 \`${X}\``),{success:V,message:V?"Removed":"Not found"}}case"enable":case"disable":{let X=W[0];if(!X)return Y.sendMessage(`用法:/schedule ${Q} <id>`),{success:!1,error:"Missing schedule id"};let V=await $.setEnabled(X,Q==="enable");return Y.sendMessage(V?`[OK] 已${Q==="enable"?"启用":"停用"} \`${X}\``:`未找到 \`${X}\``),{success:Boolean(V),message:V?"Updated":"Not found"}}case"run":{let X=W[0];if(!X)return Y.sendMessage("用法:/schedule run <id>"),{success:!1,error:"Missing schedule id"};try{return await hB(X),Y.sendMessage(`[OK] 已触发 \`${X}\``),{success:!0,message:"Schedule triggered"}}catch(V){let H=V instanceof Error?V.message:String(V);return Y.sendMessage(`运行失败:${H}`),{success:!1,error:H}}}default:return Y.sendMessage(`未知子命令: ${Q}
1661
- 使用 /schedule 查看帮助`),{success:!1,error:`Unknown subcommand: ${Q}`}}}}}var PQ=gB();import*as t1 from"node:fs/promises";import*as e1 from"node:path";async function kQ($,Z={}){let{maxResults:J=20,caseSensitive:Y=!1,projectPath:Q,storagePath:W}=Z,U=W??s2(Q??M());if(!W){let B=await uB($,Q??M(),J,Y);if(B)return B}let X;try{X=(await t1.readdir(U)).filter((G)=>G.endsWith(".jsonl")&&!G.startsWith("agent_")).map((G)=>e1.join(U,G))}catch{return[]}let H=(await Promise.all(X.map(async(B)=>{try{let G=await t1.stat(B);return{path:B,mtime:G.mtimeMs}}catch{return null}}))).filter((B)=>B!==null).sort((B,G)=>G.mtime-B.mtime).map((B)=>B.path),K=[],w=Y?$:$.toLowerCase();for(let B of H){if(K.length>=J)break;let G=e1.basename(B,".jsonl"),_=await dB(B,w,Y,G);if(K.push(..._),K.length>=J){K.length=J;break}}return K}async function uB($,Z,J,Y){try{let{syncAll:Q}=await import("./chunk-bt18xsc6.js"),W=await fQ();if(!W)return null;let{SessionService:U}=await import("./chunk-03qymy9e.js");await Q(W,U.projectionDeriverForSearch());let X=e1.resolve(Z),V=SQ(W,$,X,J*4),H=Y?$:$.toLowerCase(),K=[];for(let w of V){if(w.role!=="user"&&w.role!=="assistant")continue;let B=HZ(w.text,H,Y,w.session_id,w.role,w.timestamp??void 0,0);if(B)K.push(B);if(K.length>=J)break}return K}catch{return null}}async function dB($,Z,J,Y){try{let Q=await t1.readFile($,"utf8"),U=Q.split(`
1661
+ 使用 /schedule 查看帮助`),{success:!1,error:`Unknown subcommand: ${Q}`}}}}}var PQ=gB();import*as t1 from"node:fs/promises";import*as e1 from"node:path";async function kQ($,Z={}){let{maxResults:J=20,caseSensitive:Y=!1,projectPath:Q,storagePath:W}=Z,U=W??s2(Q??M());if(!W){let B=await uB($,Q??M(),J,Y);if(B)return B}let X;try{X=(await t1.readdir(U)).filter((G)=>G.endsWith(".jsonl")&&!G.startsWith("agent_")).map((G)=>e1.join(U,G))}catch{return[]}let H=(await Promise.all(X.map(async(B)=>{try{let G=await t1.stat(B);return{path:B,mtime:G.mtimeMs}}catch{return null}}))).filter((B)=>B!==null).sort((B,G)=>G.mtime-B.mtime).map((B)=>B.path),K=[],w=Y?$:$.toLowerCase();for(let B of H){if(K.length>=J)break;let G=e1.basename(B,".jsonl"),_=await dB(B,w,Y,G);if(K.push(..._),K.length>=J){K.length=J;break}}return K}async function uB($,Z,J,Y){try{let{syncAll:Q}=await import("./chunk-bt18xsc6.js"),W=await fQ();if(!W)return null;let{SessionService:U}=await import("./chunk-x6z05rfz.js");await Q(W,U.projectionDeriverForSearch());let X=e1.resolve(Z),V=SQ(W,$,X,J*4),H=Y?$:$.toLowerCase(),K=[];for(let w of V){if(w.role!=="user"&&w.role!=="assistant")continue;let B=HZ(w.text,H,Y,w.session_id,w.role,w.timestamp??void 0,0);if(B)K.push(B);if(K.length>=J)break}return K}catch{return null}}async function dB($,Z,J,Y){try{let Q=await t1.readFile($,"utf8"),U=Q.split(`
1662
1662
  `).flatMap((w,B)=>{if(!w.trim())return[];try{return[{event:JSON.parse(w),index:B}]}catch{return[]}});if(!U.some(({event:w})=>w.type==="session_created"))return mB(U,Z,J,Y);let V=new Map(U.flatMap(({event:w,index:B})=>typeof w.id==="string"?[[w.id,B+1]]:[])),H=RQ(TQ(Q,$)),K=new Map;for(let w of H){if(w.type==="message_created"&&(w.data.role==="user"||w.data.role==="assistant"))K.set(w.data.messageId,{role:w.data.role,content:[],timestamp:w.timestamp,lineNumber:V.get(w.id)??0});if(w.type==="part_created"&&w.data.partType==="text"){let B=K.get(w.data.messageId),G=w.data.payload.text;if(B&&typeof G==="string")B.content.push(G)}}return[...K.values()].flatMap((w)=>{let B=HZ(w.content.join(" "),Z,J,Y,w.role,w.timestamp,w.lineNumber);return B?[B]:[]})}catch{return[]}}function mB($,Z,J,Y){return $.flatMap(({event:Q,index:W})=>{if(Q.type!=="message")return[];let U=Q.message;if(U?.role!=="user"&&U?.role!=="assistant"||!U.content)return[];let X=typeof U.content==="string"?U.content:Array.isArray(U.content)?U.content.filter((H)=>typeof H==="object"&&H!==null&&H.type==="text"&&typeof H.text==="string").map((H)=>H.text).join(" "):"",V=HZ(X,Z,J,Y,U.role,typeof Q.timestamp==="string"?Q.timestamp:void 0,W+1);return V?[V]:[]})}function HZ($,Z,J,Y,Q,W,U){if(!$)return;let X=J?$:$.toLowerCase();if(!X.includes(Z))return;let V=X.indexOf(Z),H=Math.max(0,V-80),K=Math.min($.length,V+Z.length+80);return{sessionId:Y,role:Q,content:(H>0?"...":"")+$.slice(H,K).replace(/\n/g," ")+(K<$.length?"...":""),timestamp:W,lineNumber:U}}function vQ($){if($.length===0)return"没有找到匹配的历史记录";let Z=[`**找到 ${$.length} 条匹配:**
1663
1663
  `];for(let J of $){let Y=J.timestamp?new Date(J.timestamp).toLocaleString("zh-CN",{timeZone:"Asia/Shanghai"}):"?",Q=J.role==="user"?"\uD83D\uDC64":"\uD83E\uDD16";Z.push(`${Q} \`${J.sessionId.slice(0,8)}\` (${Y})`),Z.push(` ${J.content}`),Z.push("")}return Z.join(`
1664
1664
  `)}var pB={name:"search",description:"Search past session transcripts",fullDescription:"搜索历史会话记录,查找过去的对话内容",usage:"/search <keyword>",aliases:["find","history"],category:"Session",examples:['/search 断路器 - 搜索包含"断路器"的历史对话',"/search edit tool - 搜索 edit tool 相关讨论"],async handler($,Z){let J=g(Z);if($.length===0)return J.sendMessage("**用法:** `/search <关键词>`\n\n在历史会话中搜索包含指定关键词的对话"),{success:!0,message:"显示帮助"};let Y=$.join(" ");J.sendMessage(`正在搜索: "${Y}" ...`);try{let Q=await kQ(Y,{maxResults:15,projectPath:Z.cwd}),W=vQ(Q);return J.sendMessage(W),{success:!0,message:`found ${Q.length} results`,data:{matches:Q.length}}}catch(Q){let W=Q instanceof Error?Q.message:"未知错误";return J.sendMessage(`搜索失败: ${W}`),{success:!1,error:W}}}},yQ=pB;var cB={name:"skills",description:"查看所有可用的 Skills",fullDescription:"显示所有已发现的 Skills 及其详细信息,包括名称、描述、来源和允许的工具。",usage:"/skills",category:"system",examples:["/skills"],handler:async($,Z)=>{try{let J=Z.workspaceRoot??Z.cwd;return await D$(J,async(Y)=>{await Y.skills.refresh(),N1(J),await b1(J)}),{success:!0,message:"show_skills_manager",data:{action:"show_skills_manager"}}}catch(J){let Y=`获取 Skills 失败: ${J instanceof Error?J.message:"未知错误"}`;return y().addAssistantMessage(Y),{success:!1,error:Y}}}},IQ=cB;import lB from"node:path";function S4($){if($<1000)return`${$}ms`;let Z=Math.floor($/1000);if(Z<60)return`${Z}s`;let J=Math.floor(Z/60);if(J<60)return`${J}m ${Z%60}s`;return`${Math.floor(J/60)}h ${J%60}m`}function xQ($){switch($){case"running":return"[RUNNING]";case"completed":case"exited":return"[OK]";case"failed":case"error":return"[FAIL]";case"killed":case"cancelled":return"[STOPPED]";default:return"[?]"}}function hQ($,Z){if($.length<=Z)return $;return $.slice(0,Z-3)+"..."}async function iB($,Z){let J=g(Z),Y=$[0],Q=Z0.getInstance(),W=K0.getInstance(),U=Z.sessionId??"",X=Z.sessionId?{sessionId:Z.sessionId,projectPath:lB.resolve(Z.workspaceRoot??Z.cwd)}:void 0;if(Y==="resume"){let G=$[1],_=$.slice(2).join(" ").trim();if(!G||!_)return{success:!1,error:"Usage: /tasks resume <agentId> <prompt>"};if(!Z.subagents)return{success:!1,error:"This surface does not own a subagent runtime"};let D=await Z.subagents.resume(G,_),F=`Resumed \`${G}\` as \`${D.session.id}\` (depth ${D.session.resumeDepth}).`;return J.sendMessage(F),{success:!0,message:F,data:{action:"subagent_resumed",sourceAgentId:G,subagent:D.session}}}if(Y==="clean"){let G=W.cleanupExpiredSessionsForParent(X??U,0);return J.sendMessage(`已清理 ${G} 个已完成的 Agent 会话`),{success:!0,message:`Cleaned ${G} agent sessions`}}let V=[`**后台任务列表**
@@ -1,2 +1,2 @@
1
- import{gh as H,hh as I}from"./chunk-f945dzj6.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}}}
1
+ import{gh as H,hh as I}from"./chunk-139frcak.js";import{Mutex as J}from"async-mutex";class B extends Error{limit;resource="resident_runtimes";retryable=!0;constructor(b){super("Session runtime capacity is full");this.limit=b;this.name="SessionRuntimeCapacityError"}}class D extends Error{constructor(){super("Session runtime residency is closed");this.name="SessionRuntimeResidencyClosedError"}}class A extends Error{constructor(b){super(`Session runtime residency already owns key: ${b}`);this.name="SessionRuntimeResidencyConflictError"}}class K{maxResident;idleMs;now;residents=new Map;reservations=new Map;operations=new J;nextGeneration=1;closed=!1;constructor(b){if(!H(b.maxResident))throw Error("Invalid max resident Session Runtime limit");if(!I(b.idleMs))throw Error("Invalid Session Runtime idle timeout");this.maxResident=b.maxResident,this.idleMs=b.idleMs,this.now=b.now??Date.now}acquire(b){let j=this.residents.get(b);if(!j||j.poisoned)return;return j.pins++,j.lastUsedAt=this.now(),this.createLease(j)}owns(b,j){let q=this.residents.get(b);return Boolean(q&&(j===void 0||q.value===j))}async reserve(b,j){if(!b.trim())throw Error("Session runtime residency key must not be blank");return this.operations.runExclusive(async()=>{if(this.closed)throw new D;if(this.residents.has(b)||this.reservations.has(b))throw new A(b);while(this.retainedCount()>=this.maxResident){if(!j.allowEviction)throw new B(this.maxResident);let z=this.oldestEvictableWebResident();if(!z)throw new B(this.maxResident);await this.disposeResident(z,!0)}let q={generation:this.allocateGeneration(),surface:j.surface};return this.reservations.set(b,q),this.createReservation(b,q)})}async remove(b,j){return this.operations.runExclusive(async()=>{let q=this.residents.get(b);if(!q||j!==void 0&&q.value!==j)return!1;if(q.pins>0)return!1;return await this.disposeResident(q,!0),!0})}async forget(b,j){return this.operations.runExclusive(async()=>{let q=this.residents.get(b);if(!q||j!==void 0&&q.value!==j||q.pins>0)return!1;return this.residents.delete(b),!0})}async sweepIdle(){return this.operations.runExclusive(async()=>{if(this.closed)return 0;let b=0;while(!0){let j=this.oldestIdleWebResident();if(!j)return b;await this.disposeResident(j,!0),b++}})}async disposeAll(){await this.operations.runExclusive(async()=>{this.closed=!0,this.reservations.clear();let b;for(let j of[...this.residents.values()])try{await this.disposeResident(j,!1)}catch(q){b??=q}if(this.residents.clear(),b!==void 0)throw b})}getStats(){let b=0;for(let j of this.residents.values())if(j.pins>0)b++;return{resident:this.residents.size,reserved:this.reservations.size,pinned:b,maxResident:this.maxResident}}retainedCount(){return this.residents.size+this.reservations.size}allocateGeneration(){let b=this.nextGeneration;return this.nextGeneration=this.nextGeneration===Number.MAX_SAFE_INTEGER?1:this.nextGeneration+1,b}createReservation(b,j){let q=!1;return{commit:(z)=>{if(q)throw new A(b);if(z.key!==b||z.surface!==j.surface||this.reservations.get(b)!==j||this.closed)throw this.reservations.delete(b),q=!0,this.closed?new D:new A(b);this.reservations.delete(b);let G={...z,generation:j.generation,pins:1,lastUsedAt:this.now(),poisoned:!1};return this.residents.set(b,G),q=!0,this.createLease(G)},cancel:()=>{if(q)return;if(this.reservations.get(b)===j)this.reservations.delete(b);q=!0}}}createLease(b){let j=!1;return{value:b.value,release:()=>{if(j)return;j=!0;let q=this.residents.get(b.key);if(q!==b||q.generation!==b.generation)return;q.pins=Math.max(0,q.pins-1),q.lastUsedAt=this.now()}}}oldestEvictableWebResident(){return this.sortedWebResidents().find((b)=>this.canEvict(b))}oldestIdleWebResident(){let b=this.now();return this.sortedWebResidents().find((j)=>b-j.lastUsedAt>=this.idleMs&&this.canEvict(j))}sortedWebResidents(){return[...this.residents.values()].filter((b)=>b.surface==="web").sort((b,j)=>b.lastUsedAt-j.lastUsedAt||b.generation-j.generation)}canEvict(b){if(b.pins>0||b.poisoned)return!1;try{return b.canEvict()}catch{return!1}}async disposeResident(b,j){if(this.residents.get(b.key)!==b)return;this.residents.delete(b.key);try{await b.dispose()}catch(q){if(j&&!this.closed&&!this.residents.has(b.key))b.lastUsedAt=this.now(),b.poisoned=!0,this.residents.set(b.key,b);throw q}}}
2
2
  export{B as s,K as t};