blade-code 0.10.76 → 0.10.77

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 (88) hide show
  1. package/dist/blade.js +2 -2
  2. package/dist/{chunk-9fm80wbr.js → chunk-0141jad7.js} +1 -1
  3. package/dist/{chunk-aq15mcwm.js → chunk-091qx62q.js} +1 -1
  4. package/dist/{chunk-fmkntp49.js → chunk-0a0sj79a.js} +2 -2
  5. package/dist/chunk-0cbr2gs7.js +168 -0
  6. package/dist/{chunk-zvpr8s8r.js → chunk-0hpenwph.js} +1 -1
  7. package/dist/{chunk-9x141v5g.js → chunk-0ra945vt.js} +2 -2
  8. package/dist/{chunk-yg7cacsc.js → chunk-1mc7nfb4.js} +1 -1
  9. package/dist/chunk-28drv25s.js +1 -0
  10. package/dist/{chunk-j67n7v73.js → chunk-2herdn98.js} +1 -1
  11. package/dist/{chunk-wx9zxzgm.js → chunk-33bpwkyk.js} +2 -2
  12. package/dist/chunk-3ekj5azv.js +1 -0
  13. package/dist/chunk-3j0dhewn.js +1 -0
  14. package/dist/{chunk-6h3x4jv0.js → chunk-5e56atqj.js} +26 -26
  15. package/dist/{chunk-68stvfdj.js → chunk-5nezhmnq.js} +2 -2
  16. package/dist/{chunk-zk34d9mm.js → chunk-69s3e453.js} +1 -1
  17. package/dist/chunk-6adxyred.js +1 -0
  18. package/dist/{chunk-9dspha54.js → chunk-72kqnntm.js} +2 -2
  19. package/dist/{chunk-kxgr18gy.js → chunk-7ffdedgc.js} +2 -2
  20. package/dist/{chunk-n5d0d6q7.js → chunk-7nx0pzfk.js} +1 -1
  21. package/dist/chunk-8k4jza38.js +1 -0
  22. package/dist/chunk-9tb7cwem.js +1 -0
  23. package/dist/{chunk-cgd0vjw2.js → chunk-b86m3bpv.js} +1 -1
  24. package/dist/{chunk-ttbq1xmz.js → chunk-b948f9w9.js} +2 -2
  25. package/dist/chunk-b9hdp0n4.js +1 -0
  26. package/dist/{chunk-8bsse16j.js → chunk-b9nhnzaj.js} +1 -1
  27. package/dist/{chunk-z37v80c1.js → chunk-b9vm7gns.js} +2 -2
  28. package/dist/{chunk-vwa2kczj.js → chunk-c8td6vaa.js} +1 -1
  29. package/dist/{chunk-db2v383v.js → chunk-cq5gtwxb.js} +1 -1
  30. package/dist/chunk-cr1xp3re.js +10 -0
  31. package/dist/{chunk-tssmnn37.js → chunk-dj99h8ca.js} +2 -2
  32. package/dist/{chunk-ts96epcd.js → chunk-dshgm836.js} +1 -1
  33. package/dist/{chunk-qnj3dajb.js → chunk-eeb2945p.js} +1 -1
  34. package/dist/{chunk-ehks2r00.js → chunk-fsm3fb2m.js} +1 -1
  35. package/dist/{chunk-h0ys86rn.js → chunk-geam96gd.js} +1 -1
  36. package/dist/chunk-gn6ftvjy.js +1 -0
  37. package/dist/{chunk-tnaxxgje.js → chunk-gre57x9m.js} +1 -1
  38. package/dist/{chunk-bvhbc0wr.js → chunk-h0fh3j9w.js} +1 -1
  39. package/dist/{chunk-zwd5q6dt.js → chunk-h3w814js.js} +1 -1
  40. package/dist/{chunk-vn1r6z64.js → chunk-h6a0nct6.js} +1 -1
  41. package/dist/{chunk-ckvq6z49.js → chunk-h9xayrwp.js} +1 -1
  42. package/dist/chunk-hchn7baz.js +1 -0
  43. package/dist/{chunk-r8ayexxd.js → chunk-jdb2mwbn.js} +1 -1
  44. package/dist/{chunk-9k3tg2hs.js → chunk-je4xvy93.js} +3 -3
  45. package/dist/{chunk-vdtma2yq.js → chunk-jwx10h5z.js} +1 -1
  46. package/dist/{chunk-c80pzvhs.js → chunk-jzvbjn6e.js} +1 -1
  47. package/dist/{chunk-eesa8c5h.js → chunk-ky9q53m7.js} +1 -1
  48. package/dist/{chunk-abzn9eba.js → chunk-mb3htbeh.js} +1 -1
  49. package/dist/{chunk-625krpnt.js → chunk-mctkgv0d.js} +4 -4
  50. package/dist/{chunk-js4vqnds.js → chunk-mygw13zd.js} +1 -1
  51. package/dist/{chunk-8chhdkg2.js → chunk-n3amyjrd.js} +8 -5
  52. package/dist/{chunk-90yjhvjb.js → chunk-nqcpyazv.js} +1 -1
  53. package/dist/chunk-nx4z7pxk.js +1 -0
  54. package/dist/chunk-nxmssc56.js +1 -0
  55. package/dist/{chunk-9ra452yc.js → chunk-pfvgkexe.js} +1 -1
  56. package/dist/{chunk-xmty01x3.js → chunk-phgcgfv1.js} +1 -1
  57. package/dist/{chunk-chmf8s1j.js → chunk-pq4fjmnj.js} +2 -2
  58. package/dist/{chunk-gx1wx7z5.js → chunk-pr8c6qef.js} +1 -1
  59. package/dist/{chunk-js4aekf1.js → chunk-qxn5bg5k.js} +1 -1
  60. package/dist/{chunk-gpxvyxz1.js → chunk-qz5xm4cr.js} +1 -1
  61. package/dist/chunk-rdvm8zvw.js +6 -0
  62. package/dist/chunk-reakyamv.js +2 -0
  63. package/dist/chunk-rpbyc2k4.js +1 -0
  64. package/dist/{chunk-01k69v34.js → chunk-seamt0j3.js} +2 -2
  65. package/dist/{chunk-426sb4tk.js → chunk-shq0pkxq.js} +1 -1
  66. package/dist/{chunk-79cxktz1.js → chunk-sj0k8cdf.js} +1 -1
  67. package/dist/{chunk-vpn2e8tj.js → chunk-xrt796d6.js} +2 -2
  68. package/dist/{chunk-yhyqcmh1.js → chunk-yqkyhp0e.js} +1 -1
  69. package/dist/{chunk-psy247es.js → chunk-zkhb55jz.js} +1 -1
  70. package/dist/chunk-zwbv30np.js +1 -0
  71. package/package.json +1 -1
  72. package/dist/chunk-0z6fn1mt.js +0 -1
  73. package/dist/chunk-25q79gk4.js +0 -6
  74. package/dist/chunk-2nnfx3s7.js +0 -1
  75. package/dist/chunk-5b0tejhz.js +0 -1
  76. package/dist/chunk-66w68q81.js +0 -168
  77. package/dist/chunk-6r150c8y.js +0 -1
  78. package/dist/chunk-9eah1889.js +0 -1
  79. package/dist/chunk-9tcrrjzg.js +0 -1
  80. package/dist/chunk-bpf84msg.js +0 -1
  81. package/dist/chunk-c074qee7.js +0 -1
  82. package/dist/chunk-d8gn6hw5.js +0 -1
  83. package/dist/chunk-egv5k7t5.js +0 -1
  84. package/dist/chunk-et3d69av.js +0 -1
  85. package/dist/chunk-mjq7rrq1.js +0 -1
  86. package/dist/chunk-t1bvxk3s.js +0 -2
  87. package/dist/chunk-tppvhg2n.js +0 -1
  88. package/dist/chunk-zjfdj7be.js +0 -10
@@ -1,2 +1,2 @@
1
1
  import{clampThinkingLevel as t,getSupportedThinkingLevels as i}from"@earendil-works/pi-ai";var f=["auto","off","minimal","low","medium","high","xhigh","max"];function s(e){return typeof e==="string"&&f.includes(e)}function g(e,o){let n=i(e);if(o!=="auto"&&!n.includes(o))throw Error(`Reasoning effort ${o} is not supported by ${e.name}`);return{selection:o,effective:o==="auto"?t(e,"high"):o,supported:n}}
2
- export{s as qe,g as re};
2
+ export{s as te,g as ue};
@@ -1,4 +1,4 @@
1
- import{ra as R,sa as m0,xa as Q3,ya as h9,za as u0}from"./chunk-cgd0vjw2.js";import{Aa as W6,Ca as c3,Ea as l3,Fa as QZ,Xa as i3}from"./chunk-eesa8c5h.js";import{$a as a$,Bb as v5,Cb as aJ,Db as FJ,Fb as Z2,Gb as fJ,Lb as Z7,Ob as J7,Ya as b$,Za as F1,_a as b9,ab as H9,bb as j9,cb as F9,db as M9,eb as C9,fb as B7,jb as W0,lb as $5,ob as O5,qb as K4,rb as F5,sb as D5,ub as Q8,vb as Q$}from"./chunk-66w68q81.js";import{Cc as GZ,Dc as d0,Ec as D1,Fc as TJ,Gc as RJ,Jc as Z3,Nc as $7,Sc as PJ,Tc as SJ,Ub as O0,Vb as f1,Vc as r,Wb as m$,Xb as N2,Yb as KZ,Zb as K5,_b as G5,rc as P5,sc as L0,tc as $$}from"./chunk-6h3x4jv0.js";import{Wc as x,Xc as E7,Yc as w7,Zc as t$}from"./chunk-skw3b17a.js";import{_c as n3,bd as a3,kd as o3,qd as t3}from"./chunk-vdtma2yq.js";import{Bd as J8,Cd as $8}from"./chunk-zwd5q6dt.js";import{Od as B5,Pd as H0,Qd as f,Td as B0,Ud as Z5,Vd as B1,Wd as P$,Xd as E4,Yd as i$,Zd as s9,ce as G1}from"./chunk-yhyqcmh1.js";import{de as $1}from"./chunk-c9e0fbyh.js";import{he as e9,ie as o9,le as dJ,me as J5}from"./chunk-01k69v34.js";import{oe as P0,pe as g$}from"./chunk-wx9zxzgm.js";import{qe as tJ}from"./chunk-js4vqnds.js";import{se as bJ,te as AJ,ue as jJ}from"./chunk-ttbq1xmz.js";import{Ae as H5,Be as I$,Ce as M7,Ee as K$,Fe as Z$,Ge as a0,He as Z6,Ie as H1,Je as k5,Ke as W1,Le as X1,Me as CJ,Qe as g4,Se as S0,Te as U$,Ve as Y5,We as kJ,ve as Q5,we as U5,xe as z5,ze as V5}from"./chunk-vpn2e8tj.js";import{$e as c2,Ye as f$,_e as X$,af as NZ,bf as bZ,cf as g1,df as AZ,ef as jZ,ff as M2}from"./chunk-c80pzvhs.js";import{gf as B3,if as MJ,jf as R5,kf as Y8}from"./chunk-n5d0d6q7.js";import{mf as $Z,of as j0}from"./chunk-9k3tg2hs.js";import{pf as F2,qf as HZ,rf as D2,sf as U1}from"./chunk-psy247es.js";import{Bf as a4,Gf as X3,Kf as pZ,Mf as LJ,Of as w9,Pf as N9,Vf as s$,Yf as O9,gg as u9,hg as m9,ig as d9,jg as p9,kg as q4,lg as c9,mg as R$,ng as l9,og as i9,pg as r9,rg as PZ,tg as vJ,uf as mZ,ug as NJ,vg as Q0,zf as dZ}from"./chunk-tssmnn37.js";import{yg as N$}from"./chunk-9ra452yc.js";import{Ag as t5,Bg as O,Cg as S7,Dg as S,Eg as m,zg as j2}from"./chunk-js4aekf1.js";import{Gg as GJ,Hg as OJ}from"./chunk-t1bvxk3s.js";import{Jg as f2,Lg as T}from"./chunk-9fm80wbr.js";import{lh as l}from"./chunk-z37v80c1.js";import{qh as EJ,rh as wJ}from"./chunk-68stvfdj.js";import{sh as q3,vh as F3}from"./chunk-vn1r6z64.js";import{zh as N3}from"./chunk-kxgr18gy.js";import{Fh as yJ,Gh as v0}from"./chunk-fmkntp49.js";import{Kh as w2,Mh as C$,Oh as qJ,Ph as wZ,Rh as e}from"./chunk-9x141v5g.js";import{Th as t0}from"./chunk-bvhbc0wr.js";import{randomUUID as a5}from"crypto";import{randomUUID as BY}from"node:crypto";var KY=String.raw`
1
+ import{ra as R,sa as m0,xa as Q3,ya as h9,za as u0}from"./chunk-b86m3bpv.js";import{Aa as W6,Ca as c3,Ea as l3,Fa as QZ,Xa as i3}from"./chunk-ky9q53m7.js";import{$a as a$,Bb as v5,Cb as aJ,Db as FJ,Fb as Z2,Gb as fJ,Lb as Z7,Ob as J7,Ya as b$,Za as F1,_a as b9,ab as H9,bb as j9,cb as F9,db as M9,eb as C9,fb as B7,jb as W0,lb as $5,ob as O5,qb as K4,rb as F5,sb as D5,ub as Q8,vb as Q$}from"./chunk-0cbr2gs7.js";import{Cc as GZ,Dc as d0,Ec as D1,Fc as TJ,Gc as RJ,Jc as Z3,Nc as $7,Sc as PJ,Tc as SJ,Ub as O0,Vb as f1,Vc as r,Wb as m$,Xb as N2,Yb as KZ,Zb as K5,_b as G5,rc as P5,sc as L0,tc as $$}from"./chunk-5e56atqj.js";import{Wc as x,Xc as E7,Yc as w7,Zc as t$}from"./chunk-skw3b17a.js";import{_c as n3,bd as a3,kd as o3,qd as t3}from"./chunk-jwx10h5z.js";import{Bd as J8,Cd as $8}from"./chunk-h3w814js.js";import{Od as B5,Pd as H0,Qd as f,Td as B0,Ud as Z5,Vd as B1,Wd as P$,Xd as E4,Yd as i$,Zd as s9,ce as G1}from"./chunk-yqkyhp0e.js";import{de as $1}from"./chunk-c9e0fbyh.js";import{ie as e9,je as o9,oe as dJ,pe as J5}from"./chunk-seamt0j3.js";import{re as P0,se as g$}from"./chunk-33bpwkyk.js";import{te as tJ}from"./chunk-mygw13zd.js";import{ve as bJ,we as AJ,xe as jJ}from"./chunk-b948f9w9.js";import{Ae as z5,Ce as V5,De as H5,Ee as I$,Fe as M7,He as K$,Ie as Z$,Je as a0,Ke as Z6,Le as H1,Me as k5,Ne as W1,Oe as X1,Pe as CJ,Te as g4,Ve as S0,We as U$,Ye as Y5,Ze as kJ,ye as Q5,ze as U5}from"./chunk-xrt796d6.js";import{$e as f$,bf as X$,cf as c2,df as NZ,ef as bZ,ff as g1,gf as AZ,hf as jZ,if as M2}from"./chunk-jzvbjn6e.js";import{jf as B3,lf as MJ,mf as R5,nf as Y8}from"./chunk-7nx0pzfk.js";import{pf as $Z,rf as j0}from"./chunk-je4xvy93.js";import{sf as F2,tf as HZ,uf as D2,vf as U1}from"./chunk-zkhb55jz.js";import{$f as O9,Cf as dZ,Ef as a4,Jf as X3,Nf as pZ,Pf as LJ,Rf as w9,Sf as N9,Yf as s$,jg as u9,kg as m9,lg as d9,mg as p9,ng as q4,og as c9,pg as R$,qg as l9,rg as i9,sg as r9,ug as PZ,wg as vJ,xf as mZ,xg as NJ,yg as Q0}from"./chunk-dj99h8ca.js";import{Bg as N$}from"./chunk-pfvgkexe.js";import{Cg as j2,Dg as t5,Eg as O,Fg as S7,Gg as S,Hg as m}from"./chunk-qxn5bg5k.js";import{Jg as GJ,Kg as OJ}from"./chunk-reakyamv.js";import{Mg as f2,Og as T}from"./chunk-0141jad7.js";import{oh as l}from"./chunk-b9vm7gns.js";import{th as EJ,uh as wJ}from"./chunk-5nezhmnq.js";import{vh as q3,yh as F3}from"./chunk-h6a0nct6.js";import{Ch as N3}from"./chunk-7ffdedgc.js";import{Ih as yJ,Jh as v0}from"./chunk-0a0sj79a.js";import{Nh as w2,Ph as C$,Rh as qJ,Sh as wZ,Uh as e}from"./chunk-0ra945vt.js";import{Wh as t0}from"./chunk-h0fh3j9w.js";import{randomUUID as a5}from"crypto";import{randomUUID as BY}from"node:crypto";var KY=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);
@@ -816,7 +816,7 @@ ${n}
816
816
  </approved-plan>
817
817
 
818
818
  IMPORTANT: Execute according to the approved plan above. Follow the steps exactly as specified.`;if(typeof G==="string")s=G+y;else s=[...G,{type:"text",text:y}]}P=yield*this.runLoop(s,F,{...C,inputMessageId:void 0})}if(!this.sessionRuntime||!b)return P;let k=await this.sessionRuntime.recordGoalProgress({tokens:P.metadata?.tokensUsed??0,elapsedMs:P.metadata?.duration??0,prematureStopPattern:P.success?E9(P.finalMessage):void 0});if(k)yield{kind:"goal_updated",goal:k};if(!P.success||F.signal?.aborted){if(k=await this.sessionRuntime.pauseActiveGoal(F.signal?.aborted?"goal paused after user cancellation":P.error?.message??"goal paused after turn failure"),k)yield{kind:"goal_updated",goal:k}}if(P.success&&!F.signal?.aborted&&w<20)await this.sessionRuntime.waitForBackgroundSubagentFollowUp(b,F.signal);let a=P.success&&!F.signal?.aborted&&w<20,g=uQ(P);if(N=await this.sessionRuntime.finishTurn(b,{continuePending:a,...g?{acknowledgeInput:!0}:{},outcome:P.success&&!F.signal?.aborted?{status:"completed",turnsCount:P.metadata?.turnsCount??0,toolCallsCount:P.metadata?.toolCallsCount??0,durationMs:P.metadata?.duration??0}:{status:"aborted",cause:F.signal?.aborted?"cancelled":"failed",turnsCount:P.metadata?.turnsCount??0,toolCallsCount:P.metadata?.toolCallsCount??0,durationMs:P.metadata?.duration??0}}),N){w++,B=!0,D=!1,L=null,G="",q=void 0,_=M(),yield{kind:"follow_up_started",queued:this.sessionRuntime.getPendingSteeringCount(),recovered:this.sessionRuntime.getRecoveredSteeringCount(),messages:A()};continue}if(!P.success||F.signal?.aborted)return P;if(k=await this.sessionRuntime.getGoal(),!k||k.status!=="active"&&k.status!=="verifying")return P;if(L=await this.sessionRuntime.beginGoalContinuation(),!L)return P;N=await this.sessionRuntime.beginTurn("goal"),B=!1,D=!0,G=C6(L),q=void 0,_=void 0,yield{kind:"goal_continuation_started",goal:L,continuation:L.continuationCount,...L.prematureStop?{prematureStopPattern:L.prematureStop.pattern,prematureStopCount:L.prematureStop.consecutiveCount}:{}},yield{kind:"goal_updated",goal:L}}}finally{if(this.sessionRuntime&&N)await this.sessionRuntime.finishTurn(N)}}let V=typeof U==="string"?U:U.filter((G)=>G.type==="text").map((G)=>G.text).join(`
819
- `),H={id:this.generateTaskId(),type:"simple",prompt:V};return{success:!0,finalMessage:(await this.executeTask(H)).content,metadata:{turnsCount:1,toolCallsCount:0,duration:0}}}async chat($,Z,J){let{drainLoop:Y}=await import("./chunk-0z6fn1mt.js");return Y(this.chatStream($,Z,J))}async*runPlanLoop($,Z,J){p.debug("Processing Plan mode message...");let{prompt:Y}=await A$({projectPath:Z.workspaceRoot||T(),mode:"plan",includeEnvironment:!0,environmentOptions:Z2,language:this.config.language,availableSkills:this.agentResources?.skills.generateAvailableSkillsList(),communicationStyle:this.sessionRuntime?.getCommunicationStyleConfiguration().selection,communicationStyleCatalog:this.sessionRuntime?.getCommunicationStyleCatalog(),projectRuleCatalog:this.sessionRuntime?.getProjectRuleCatalog(),projectInstructionSourcePath:this.sessionRuntime?.projectRoot}),W;if(typeof $==="string")W=d1($);else{let X=$.filter((Q)=>Q.type==="text");if(X.length>0){let Q=X[0];W=$.map((U)=>U===Q?{type:"text",text:d1(Q.text)}:U)}else W=[{type:"text",text:d1("")},...$]}return yield*this.executeLoop(W,Z,J,Y)}async*runLoop($,Z,J){p.debug("Processing enhanced chat message...");let Y=Z.systemPrompt??await this.buildSystemPromptOnDemand(Z.workspaceRoot||T());return yield*this.executeLoop($,Z,J,Y)}async buildSystemPromptOnDemand($){let Z=this.runtimeOptions.systemPrompt,J=this.runtimeOptions.appendSystemPrompt;return(await A$({projectPath:$,replaceDefault:Z,append:J,includeEnvironment:!0,environmentOptions:Z2,language:this.config.language,availableSkills:this.agentResources?.skills.generateAvailableSkillsList(),communicationStyle:this.sessionRuntime?.getCommunicationStyleConfiguration().selection,communicationStyleCatalog:this.sessionRuntime?.getCommunicationStyleCatalog(),projectRuleCatalog:this.sessionRuntime?.getProjectRuleCatalog(),projectInstructionSourcePath:this.sessionRuntime?.projectRoot})).prompt}executeLoop($,Z,J,Y){if(!this.isInitialized)throw Error("Agent未初始化");let W=this.buildLoopDependencies();return J7(W,$,Z,J,Y)}takeStartupAdoptedToolResultEvents(){return(this.sessionRuntime?.takeStartupAdoptedToolResults()??[]).flatMap(({call:Z,result:J})=>{let Y={id:Z.toolCallId,type:"function",function:{name:Z.toolName,arguments:JSON.stringify(Z.input)}},W=J.metadata&&typeof J.metadata==="object"&&!Array.isArray(J.metadata)?J.metadata:void 0,X=J.error===void 0,Q=J.output,U={success:X,llmContent:typeof Q==="string"||Q!==null&&typeof Q==="object"?Q:Q===null?J.error?`Subagent execution failed: ${J.error}.`:"":String(Q),...J.error?{error:{type:"execution_error",message:J.error}}:{},...W?{metadata:W}:{}},z=[{kind:"tool_result",toolCall:Y,result:U}],V=Z7(Y,U);if(V)z.push(V);return z})}buildLoopDependencies(){return{chatService:this.chatService,toolExecutor:this.toolExecutor,executionEngine:this.executionEngine,config:this.config,runtimeOptions:this.runtimeOptions,currentModelMaxContextTokens:this.currentModelMaxContextTokens,activeSkillContext:this.activeSkillContext,onSkillActivated:($)=>{this.activeSkillContext=$,p.debug(`Skill "${$.skillName}" activated`+($.allowedTools?` with allowed tools: ${$.allowedTools.join(", ")}`:""))},onModelSwitch:($)=>this.switchModelIfNeeded($),applySkillToolRestrictions:($)=>this.applySkillToolRestrictions($),staticProjectRules:this.sessionRuntime?.getStaticProjectRules(),hydrateProjectRules:this.sessionRuntime?($)=>this.sessionRuntime.hydrateProjectRules($):void 0,resolveContextualProjectRules:this.sessionRuntime?($,Z,J,Y)=>this.sessionRuntime.resolveContextualProjectRules($,Z,J,Y):void 0}}async chatWithSystem($,Z){if(!this.isInitialized)throw Error("Agent未初始化");let J=[{role:"system",content:$},{role:"user",content:Z}];return(await this.chatService.chat(J)).content}getActiveTask(){return this.activeTask}getChatService(){return this.chatService}getContextManager(){return this.executionEngine?.getContextManager()}getStats(){return{initialized:this.isInitialized,activeTask:this.activeTask?.id,components:{chatService:this.chatService?"ready":"not_loaded",executionEngine:this.executionEngine?"ready":"not_loaded"}}}getAvailableTools(){return this.toolExecutor?this.toolExecutor.getRegistry().getAll():[]}getToolRegistry(){return this.toolExecutor.getRegistry()}applyToolWhitelist($){let Z=this.toolExecutor.getRegistry(),Y=Z.getAll().filter((W)=>!$.includes(W.name));for(let W of Y)Z.unregister(W.name);p.debug(`Applied tool whitelist: ${$.join(", ")} (removed ${Y.length} tools)`)}applyToolBlacklist($){let Z=this.toolExecutor.getRegistry(),J=new Set($);for(let Y of Z.getAll())if(J.has(Y.name))Z.unregister(Y.name);p.debug(`Applied tool blacklist: ${$.join(", ")}`)}getToolStats(){let $=this.getAvailableTools(),Z=new Map;return $.forEach((J)=>{let Y=Z.get(J.kind)||0;Z.set(J.kind,Y+1)}),{totalTools:$.length,toolsByKind:Object.fromEntries(Z),toolNames:$.map((J)=>J.name)}}async destroy(){if(this.destroyPromise)return this.destroyPromise;return this.destroyPromise=(async()=>{this.log("销毁Agent..."),await this.activeOperations.shutdown("agent-destroy");try{await this.legacyMcpRegistry?.disconnectAll(),this.legacyMcpRegistry=void 0,this.log("Agent已销毁")}catch($){throw this.error("Agent销毁失败",$),$}finally{this.toolExecutor.dispose(),this.isInitialized=!1}})(),this.destroyPromise}syncRuntimeState(){if(!this.sessionRuntime)return;this.chatService=this.sessionRuntime.getChatService(),this.executionEngine=this.sessionRuntime.getExecutionEngine(),this.attachmentCollector=this.sessionRuntime.getAttachmentCollector(),this.currentModelId=this.sessionRuntime.getCurrentModelId(),this.currentModelMaxContextTokens=this.sessionRuntime.getCurrentModelMaxContextTokens()}generateTaskId(){return`task_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}log($,Z){p.debug(`[MainAgent] ${$}`,Z||"")}error($,Z){p.error(`[MainAgent] ${$}`,Z||"")}async initializeSystemPrompt(){try{let $=this.runtimeOptions.systemPrompt,Z=this.runtimeOptions.appendSystemPrompt,J=await A$({projectPath:this.sessionRuntime?.workspaceRoot??T(),replaceDefault:$,append:Z,includeEnvironment:!1,language:this.config.language,availableSkills:this.agentResources?.skills.generateAvailableSkillsList(),communicationStyle:this.sessionRuntime?.getCommunicationStyleConfiguration().selection,communicationStyleCatalog:this.sessionRuntime?.getCommunicationStyleCatalog(),projectRuleCatalog:this.sessionRuntime?.getProjectRuleCatalog(),projectInstructionSourcePath:this.sessionRuntime?.projectRoot});if(J.prompt)this.log("系统提示配置验证成功"),p.debug(`[SystemPrompt] 可用来源: ${J.sources.filter((Y)=>Y.loaded).map((Y)=>Y.name).join(", ")}`)}catch($){this.error("系统提示配置验证失败",$)}}async registerBuiltinTools(){try{let $=await W5({sessionId:"default",configDir:e(),workspaceRoot:T(),resourceRoot:T(),agentResources:this.agentResources});p.debug(`Registering ${$.length} builtin tools...`),this.toolExecutor.getRegistry().registerAll($);let Z=this.toolExecutor.getRegistry().getAll().length;p.debug(`Builtin tools registered: ${Z} tools`),p.debug(`[Tools] ${this.toolExecutor.getRegistry().getAll().map((J)=>J.name).join(", ")}`),await this.registerMcpTools()}catch($){throw p.error("Failed to register builtin tools:",$),$}}async registerMcpTools(){try{let $=await k2({workspaceRoot:T(),storeServers:this.config.mcpServers??{},cliConfigs:this.runtimeOptions.mcpConfig,strictCliConfig:this.runtimeOptions.strictMcpConfig});if(Object.keys($).length===0){p.debug("No MCP servers configured");return}let Z=u0.createIsolated({artifactWriter:new m1(`legacy-${gQ()}`)});this.legacyMcpRegistry=Z;for(let[X,Q]of Object.entries($))try{p.debug(`Connecting to MCP server: ${X}`),await Z.registerServer(X,Q),p.debug(`MCP server "${X}" connected`)}catch(U){p.warn(`Warning: MCP server "${X}" connection failed:`,U)}let J=this.toolExecutor.getRegistry();J.setMcpCatalogBarrier(()=>Z.waitForCatalogIdle());let Y=Z.getCatalogSnapshot();J.replaceMcpTools(Y.tools),J.registerAll(r1(Z));let W=Z.getInstructionsSnapshot();if(J.queueMcpInstructionsChange({revision:W.revision,reason:"snapshot",replace:!0,instructions:W.instructions,removed:[]}),Z.on("catalogChanged",(X)=>{J.replaceMcpTools(X.tools,X)}),Z.on("contentCatalogChanged",(X)=>{J.queueMcpContentChange(X)}),Z.on("resourceUpdated",(X)=>{J.queueMcpResourceUpdated(X)}),Z.on("connectionLifecycleChanged",(X)=>{J.queueMcpConnectionChange(X)}),Z.on("log",(X)=>{J.queueMcpLog(X)}),Z.on("instructionsChanged",(X)=>{J.queueMcpInstructionsChange({revision:X.revision,reason:X.reason,replace:!1,instructions:X.action==="added"&&X.instruction?[{serverName:X.serverName,...X.instruction}]:[],removed:X.action==="removed"?[X.serverName]:[]})}),Y.tools.length>0)p.debug(`Registered ${Y.tools.length} MCP tools`),p.debug(`[MCP Tools] ${Y.tools.map((X)=>X.name).join(", ")}`)}catch($){p.warn("Failed to register MCP tools:",$)}}async loadSubagents(){let $=await S0(T());if(this.agentResources=Y5($),this.subagentRegistry=this.agentResources.subagents,this.runtimeOptions.agents?.length)this.subagentRegistry.applyOverrides(this.runtimeOptions.agents);let Z=this.subagentRegistry.getAllNames().length;if(Z>0)p.debug(`Loaded ${Z} subagents: ${this.subagentRegistry.getAllNames().join(", ")}`);else p.debug("No subagents configured")}applySkillToolRestrictions($){if(!this.activeSkillContext?.allowedTools)return $;let Z=this.activeSkillContext.allowedTools;p.debug(`Applying Skill tool restrictions: ${Z.join(", ")}`);let J=$.filter((Y)=>{return Z.some((W)=>{if(W===Y.name)return!0;let X=W.match(/^(\w+)\(.*\)$/);if(X&&X[1]===Y.name)return!0;return!1})});return p.debug(`Filtered tools: ${J.map((Y)=>Y.name).join(", ")} (${J.length}/${$.length})`),J}clearSkillContext(){if(this.activeSkillContext)p.debug(`Skill "${this.activeSkillContext.skillName}" deactivated`),this.activeSkillContext=void 0}async processAtMentionsForContent($){if(!this.attachmentCollector)return $;if(typeof $==="string")return this.processAtMentions($);let Z=[];for(let Y of $)if(Y.type==="text")Z.push(Y.text);if(Z.length===0)return $;let J=Z.join(`
819
+ `),H={id:this.generateTaskId(),type:"simple",prompt:V};return{success:!0,finalMessage:(await this.executeTask(H)).content,metadata:{turnsCount:1,toolCallsCount:0,duration:0}}}async chat($,Z,J){let{drainLoop:Y}=await import("./chunk-hchn7baz.js");return Y(this.chatStream($,Z,J))}async*runPlanLoop($,Z,J){p.debug("Processing Plan mode message...");let{prompt:Y}=await A$({projectPath:Z.workspaceRoot||T(),mode:"plan",includeEnvironment:!0,environmentOptions:Z2,language:this.config.language,availableSkills:this.agentResources?.skills.generateAvailableSkillsList(),communicationStyle:this.sessionRuntime?.getCommunicationStyleConfiguration().selection,communicationStyleCatalog:this.sessionRuntime?.getCommunicationStyleCatalog(),projectRuleCatalog:this.sessionRuntime?.getProjectRuleCatalog(),projectInstructionSourcePath:this.sessionRuntime?.projectRoot}),W;if(typeof $==="string")W=d1($);else{let X=$.filter((Q)=>Q.type==="text");if(X.length>0){let Q=X[0];W=$.map((U)=>U===Q?{type:"text",text:d1(Q.text)}:U)}else W=[{type:"text",text:d1("")},...$]}return yield*this.executeLoop(W,Z,J,Y)}async*runLoop($,Z,J){p.debug("Processing enhanced chat message...");let Y=Z.systemPrompt??await this.buildSystemPromptOnDemand(Z.workspaceRoot||T());return yield*this.executeLoop($,Z,J,Y)}async buildSystemPromptOnDemand($){let Z=this.runtimeOptions.systemPrompt,J=this.runtimeOptions.appendSystemPrompt;return(await A$({projectPath:$,replaceDefault:Z,append:J,includeEnvironment:!0,environmentOptions:Z2,language:this.config.language,availableSkills:this.agentResources?.skills.generateAvailableSkillsList(),communicationStyle:this.sessionRuntime?.getCommunicationStyleConfiguration().selection,communicationStyleCatalog:this.sessionRuntime?.getCommunicationStyleCatalog(),projectRuleCatalog:this.sessionRuntime?.getProjectRuleCatalog(),projectInstructionSourcePath:this.sessionRuntime?.projectRoot})).prompt}executeLoop($,Z,J,Y){if(!this.isInitialized)throw Error("Agent未初始化");let W=this.buildLoopDependencies();return J7(W,$,Z,J,Y)}takeStartupAdoptedToolResultEvents(){return(this.sessionRuntime?.takeStartupAdoptedToolResults()??[]).flatMap(({call:Z,result:J})=>{let Y={id:Z.toolCallId,type:"function",function:{name:Z.toolName,arguments:JSON.stringify(Z.input)}},W=J.metadata&&typeof J.metadata==="object"&&!Array.isArray(J.metadata)?J.metadata:void 0,X=J.error===void 0,Q=J.output,U={success:X,llmContent:typeof Q==="string"||Q!==null&&typeof Q==="object"?Q:Q===null?J.error?`Subagent execution failed: ${J.error}.`:"":String(Q),...J.error?{error:{type:"execution_error",message:J.error}}:{},...W?{metadata:W}:{}},z=[{kind:"tool_result",toolCall:Y,result:U}],V=Z7(Y,U);if(V)z.push(V);return z})}buildLoopDependencies(){return{chatService:this.chatService,toolExecutor:this.toolExecutor,executionEngine:this.executionEngine,config:this.config,runtimeOptions:this.runtimeOptions,currentModelMaxContextTokens:this.currentModelMaxContextTokens,activeSkillContext:this.activeSkillContext,onSkillActivated:($)=>{this.activeSkillContext=$,p.debug(`Skill "${$.skillName}" activated`+($.allowedTools?` with allowed tools: ${$.allowedTools.join(", ")}`:""))},onModelSwitch:($)=>this.switchModelIfNeeded($),applySkillToolRestrictions:($)=>this.applySkillToolRestrictions($),staticProjectRules:this.sessionRuntime?.getStaticProjectRules(),hydrateProjectRules:this.sessionRuntime?($)=>this.sessionRuntime.hydrateProjectRules($):void 0,resolveContextualProjectRules:this.sessionRuntime?($,Z,J,Y)=>this.sessionRuntime.resolveContextualProjectRules($,Z,J,Y):void 0}}async chatWithSystem($,Z){if(!this.isInitialized)throw Error("Agent未初始化");let J=[{role:"system",content:$},{role:"user",content:Z}];return(await this.chatService.chat(J)).content}getActiveTask(){return this.activeTask}getChatService(){return this.chatService}getContextManager(){return this.executionEngine?.getContextManager()}getStats(){return{initialized:this.isInitialized,activeTask:this.activeTask?.id,components:{chatService:this.chatService?"ready":"not_loaded",executionEngine:this.executionEngine?"ready":"not_loaded"}}}getAvailableTools(){return this.toolExecutor?this.toolExecutor.getRegistry().getAll():[]}getToolRegistry(){return this.toolExecutor.getRegistry()}applyToolWhitelist($){let Z=this.toolExecutor.getRegistry(),Y=Z.getAll().filter((W)=>!$.includes(W.name));for(let W of Y)Z.unregister(W.name);p.debug(`Applied tool whitelist: ${$.join(", ")} (removed ${Y.length} tools)`)}applyToolBlacklist($){let Z=this.toolExecutor.getRegistry(),J=new Set($);for(let Y of Z.getAll())if(J.has(Y.name))Z.unregister(Y.name);p.debug(`Applied tool blacklist: ${$.join(", ")}`)}getToolStats(){let $=this.getAvailableTools(),Z=new Map;return $.forEach((J)=>{let Y=Z.get(J.kind)||0;Z.set(J.kind,Y+1)}),{totalTools:$.length,toolsByKind:Object.fromEntries(Z),toolNames:$.map((J)=>J.name)}}async destroy(){if(this.destroyPromise)return this.destroyPromise;return this.destroyPromise=(async()=>{this.log("销毁Agent..."),await this.activeOperations.shutdown("agent-destroy");try{await this.legacyMcpRegistry?.disconnectAll(),this.legacyMcpRegistry=void 0,this.log("Agent已销毁")}catch($){throw this.error("Agent销毁失败",$),$}finally{this.toolExecutor.dispose(),this.isInitialized=!1}})(),this.destroyPromise}syncRuntimeState(){if(!this.sessionRuntime)return;this.chatService=this.sessionRuntime.getChatService(),this.executionEngine=this.sessionRuntime.getExecutionEngine(),this.attachmentCollector=this.sessionRuntime.getAttachmentCollector(),this.currentModelId=this.sessionRuntime.getCurrentModelId(),this.currentModelMaxContextTokens=this.sessionRuntime.getCurrentModelMaxContextTokens()}generateTaskId(){return`task_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}log($,Z){p.debug(`[MainAgent] ${$}`,Z||"")}error($,Z){p.error(`[MainAgent] ${$}`,Z||"")}async initializeSystemPrompt(){try{let $=this.runtimeOptions.systemPrompt,Z=this.runtimeOptions.appendSystemPrompt,J=await A$({projectPath:this.sessionRuntime?.workspaceRoot??T(),replaceDefault:$,append:Z,includeEnvironment:!1,language:this.config.language,availableSkills:this.agentResources?.skills.generateAvailableSkillsList(),communicationStyle:this.sessionRuntime?.getCommunicationStyleConfiguration().selection,communicationStyleCatalog:this.sessionRuntime?.getCommunicationStyleCatalog(),projectRuleCatalog:this.sessionRuntime?.getProjectRuleCatalog(),projectInstructionSourcePath:this.sessionRuntime?.projectRoot});if(J.prompt)this.log("系统提示配置验证成功"),p.debug(`[SystemPrompt] 可用来源: ${J.sources.filter((Y)=>Y.loaded).map((Y)=>Y.name).join(", ")}`)}catch($){this.error("系统提示配置验证失败",$)}}async registerBuiltinTools(){try{let $=await W5({sessionId:"default",configDir:e(),workspaceRoot:T(),resourceRoot:T(),agentResources:this.agentResources});p.debug(`Registering ${$.length} builtin tools...`),this.toolExecutor.getRegistry().registerAll($);let Z=this.toolExecutor.getRegistry().getAll().length;p.debug(`Builtin tools registered: ${Z} tools`),p.debug(`[Tools] ${this.toolExecutor.getRegistry().getAll().map((J)=>J.name).join(", ")}`),await this.registerMcpTools()}catch($){throw p.error("Failed to register builtin tools:",$),$}}async registerMcpTools(){try{let $=await k2({workspaceRoot:T(),storeServers:this.config.mcpServers??{},cliConfigs:this.runtimeOptions.mcpConfig,strictCliConfig:this.runtimeOptions.strictMcpConfig});if(Object.keys($).length===0){p.debug("No MCP servers configured");return}let Z=u0.createIsolated({artifactWriter:new m1(`legacy-${gQ()}`)});this.legacyMcpRegistry=Z;for(let[X,Q]of Object.entries($))try{p.debug(`Connecting to MCP server: ${X}`),await Z.registerServer(X,Q),p.debug(`MCP server "${X}" connected`)}catch(U){p.warn(`Warning: MCP server "${X}" connection failed:`,U)}let J=this.toolExecutor.getRegistry();J.setMcpCatalogBarrier(()=>Z.waitForCatalogIdle());let Y=Z.getCatalogSnapshot();J.replaceMcpTools(Y.tools),J.registerAll(r1(Z));let W=Z.getInstructionsSnapshot();if(J.queueMcpInstructionsChange({revision:W.revision,reason:"snapshot",replace:!0,instructions:W.instructions,removed:[]}),Z.on("catalogChanged",(X)=>{J.replaceMcpTools(X.tools,X)}),Z.on("contentCatalogChanged",(X)=>{J.queueMcpContentChange(X)}),Z.on("resourceUpdated",(X)=>{J.queueMcpResourceUpdated(X)}),Z.on("connectionLifecycleChanged",(X)=>{J.queueMcpConnectionChange(X)}),Z.on("log",(X)=>{J.queueMcpLog(X)}),Z.on("instructionsChanged",(X)=>{J.queueMcpInstructionsChange({revision:X.revision,reason:X.reason,replace:!1,instructions:X.action==="added"&&X.instruction?[{serverName:X.serverName,...X.instruction}]:[],removed:X.action==="removed"?[X.serverName]:[]})}),Y.tools.length>0)p.debug(`Registered ${Y.tools.length} MCP tools`),p.debug(`[MCP Tools] ${Y.tools.map((X)=>X.name).join(", ")}`)}catch($){p.warn("Failed to register MCP tools:",$)}}async loadSubagents(){let $=await S0(T());if(this.agentResources=Y5($),this.subagentRegistry=this.agentResources.subagents,this.runtimeOptions.agents?.length)this.subagentRegistry.applyOverrides(this.runtimeOptions.agents);let Z=this.subagentRegistry.getAllNames().length;if(Z>0)p.debug(`Loaded ${Z} subagents: ${this.subagentRegistry.getAllNames().join(", ")}`);else p.debug("No subagents configured")}applySkillToolRestrictions($){if(!this.activeSkillContext?.allowedTools)return $;let Z=this.activeSkillContext.allowedTools;p.debug(`Applying Skill tool restrictions: ${Z.join(", ")}`);let J=$.filter((Y)=>{return Z.some((W)=>{if(W===Y.name)return!0;let X=W.match(/^(\w+)\(.*\)$/);if(X&&X[1]===Y.name)return!0;return!1})});return p.debug(`Filtered tools: ${J.map((Y)=>Y.name).join(", ")} (${J.length}/${$.length})`),J}clearSkillContext(){if(this.activeSkillContext)p.debug(`Skill "${this.activeSkillContext.skillName}" deactivated`),this.activeSkillContext=void 0}async processAtMentionsForContent($){if(!this.attachmentCollector)return $;if(typeof $==="string")return this.processAtMentions($);let Z=[];for(let Y of $)if(Y.type==="text")Z.push(Y.text);if(Z.length===0)return $;let J=Z.join(`
820
820
  `);try{let Y=await this.attachmentCollector.collect(J);if(Y.length===0)return $;p.debug(`Processed ${Y.length} @ file mentions in multimodal message`);let W=this.buildAttachmentText(Y);if(!W)return $;return[...$,{type:"text",text:W}]}catch(Y){return p.error("Failed to process @ mentions in multimodal message:",Y),$}}buildAttachmentText($){let Z=[],J=[];for(let W of $)if(W.type==="file"){let X=W.metadata?.lineRange?` (lines ${W.metadata.lineRange.start}${W.metadata.lineRange.end?`-${W.metadata.lineRange.end}`:""})`:"";Z.push(`<file path="${W.path}"${X?` range="${X}"`:""}>`,W.content,"</file>")}else if(W.type==="directory")Z.push(`<directory path="${W.path}">`,W.content,"</directory>");else if(W.type==="error")J.push(`- @${W.path}: ${W.error}`);let Y="";if(Z.length>0)Y+=`
821
821
 
822
822
  <system-reminder>
@@ -1118,11 +1118,12 @@ ${Y.response}`,data:{action:"show_side_conversation",question:J,response:Y.respo
1118
1118
  • Token 数量: ${V.toLocaleString()}
1119
1119
  • Token 限制: ${K.toLocaleString()}
1120
1120
  • 使用率: ${G}%`),V<K*0.5)return J.sendMessage(`提示: 当前 token 使用率较低(${G}%),可以暂时不压缩。
1121
- 系统会在达到 80% 时自动触发压缩。`),{success:!0,message:"无需压缩"};J.sendMessage("**正在压缩上下文...**");let F=await aJ.compact(z,{trigger:"manual",modelName:W.model,modelProvider:W.provider,maxContextTokens:K,apiKey:H.chat.apiKey,baseURL:H.chat.baseUrl,workspaceRoot:Z.workspaceRoot??Z.cwd,sessionId:U});if(U)await new t1({projectPath:Z.workspaceRoot??Z.cwd}).saveCompaction(U,F.summary,{trigger:"manual",reason:"manual",strategy:F.success?"llm":"fallback",preTokens:F.preTokens,postTokens:F.postTokens,filesIncluded:F.filesIncluded,replacementMessages:F.compactedMessages},null),console.log("[/compact] 压缩数据已保存到 JSONL");if(F.success){let B=`[OK] **压缩完成!**
1121
+ 系统会在达到 80% 时自动触发压缩。`),{success:!0,message:"无需压缩"};J.sendMessage("**正在压缩上下文...**");let F=await aJ.compact(z,{trigger:"manual",modelName:W.model,modelProvider:W.provider,maxContextTokens:K,apiKey:H.chat.apiKey,baseURL:H.chat.baseUrl,workspaceRoot:Z.workspaceRoot??Z.cwd,sessionId:U});if(U)await new t1({projectPath:Z.workspaceRoot??Z.cwd}).saveCompaction(U,F.summary,{trigger:"manual",reason:"manual",strategy:F.success?"llm":"fallback",preTokens:F.preTokens,postTokens:F.postTokens,sampleAttempts:F.sampleAttempts,failureReason:F.failureReason,filesIncluded:F.filesIncluded,replacementMessages:F.compactedMessages},null),console.log("[/compact] 压缩数据已保存到 JSONL");if(F.success){let B=`[OK] **压缩完成!**
1122
1122
 
1123
1123
  **Token 变化**
1124
1124
  • 压缩前: ${F.preTokens.toLocaleString()} tokens
1125
1125
  • 压缩后: ${F.postTokens.toLocaleString()} tokens
1126
+ • 摘要尝试: ${F.sampleAttempts??0}
1126
1127
  • 压缩率: ${((1-F.postTokens/F.preTokens)*100).toFixed(1)}%`;if(F.filesIncluded.length>0)B+=`
1127
1128
 
1128
1129
  **包含文件** (${F.filesIncluded.length})`,F.filesIncluded.forEach((D,_)=>{B+=`
@@ -1133,9 +1134,11 @@ ${Y.response}`,data:{action:"show_side_conversation",question:J,response:Y.respo
1133
1134
  **Token 变化**
1134
1135
  • 压缩前: ${F.preTokens.toLocaleString()} tokens
1135
1136
  • 压缩后: ${F.postTokens.toLocaleString()} tokens
1137
+ • 摘要尝试: ${F.sampleAttempts??0}
1136
1138
 
1137
1139
  由于压缩过程出现错误,已使用简单截断策略。
1138
- 错误信息: ${F.error}`),{success:!1,message:"compact_fallback",error:F.error,data:{compactedMessages:F.compactedMessages,boundaryMessage:F.boundaryMessage,summaryMessage:F.summaryMessage,preTokens:F.preTokens,postTokens:F.postTokens}}}catch(Y){let W=Y instanceof Error?Y.message:String(Y);return J.sendMessage(`[FAIL] **压缩失败**: ${W}`),{success:!1,error:W}}}var AV={name:"compact",description:"手动压缩当前会话的上下文",fullDescription:"压缩当前对话历史,生成详细的技术总结,保留最近的消息。压缩后的上下文可以节省 token 使用量,同时保留关键信息。",usage:"/compact",examples:["/compact"],category:"context",handler:bV},oJ=AV;function jV($){return`Reasoning effort: ${$.selection===$.effective?$.selection:`${$.selection} (${$.effective})`}
1140
+ 失败分类: ${F.failureReason??"deterministic"}
1141
+ 错误信息: ${F.error}`),{success:!1,message:"compact_fallback",error:F.error,data:{compactedMessages:F.compactedMessages,boundaryMessage:F.boundaryMessage,summaryMessage:F.summaryMessage,preTokens:F.preTokens,postTokens:F.postTokens,sampleAttempts:F.sampleAttempts,failureReason:F.failureReason}}}catch(Y){let W=Y instanceof Error?Y.message:String(Y);return J.sendMessage(`[FAIL] **压缩失败**: ${W}`),{success:!1,error:W}}}var AV={name:"compact",description:"手动压缩当前会话的上下文",fullDescription:"压缩当前对话历史,生成详细的技术总结,保留最近的消息。压缩后的上下文可以节省 token 使用量,同时保留关键信息。",usage:"/compact",examples:["/compact"],category:"context",handler:bV},oJ=AV;function jV($){return`Reasoning effort: ${$.selection===$.effective?$.selection:`${$.selection} (${$.effective})`}
1139
1142
  Supported: auto, ${$.supported.join(", ")}`}var MV={name:"effort",description:"查看或设置当前 Session 的推理强度",fullDescription:"推理强度由当前 Session 持有并持久化。auto 会按模型能力在 high 附近解析;显式不支持的级别会被拒绝。",usage:"/effort [auto|off|minimal|low|medium|high|xhigh|max]",category:"Session",examples:["/effort","/effort low","/effort auto","/effort off"],async handler($,Z){if(!Z.reasoning)return{success:!1,error:"This surface has no active Session reasoning boundary"};if($.length>1)return{success:!1,error:"Usage: /effort [auto|off|minimal|low|medium|high|xhigh|max]"};let J=$[0]?.toLowerCase();if(J!==void 0&&!tJ(J))return{success:!1,error:`Invalid reasoning effort: ${J}`};try{let Y=J?await Z.reasoning.set(J):await Z.reasoning.get();return{success:!0,message:jV(Y),data:{reasoningEffort:Y.selection,effectiveReasoningEffort:Y.effective,supportedReasoningEfforts:Y.supported}}}catch(Y){return{success:!1,error:Y instanceof Error?Y.message:"Failed to update reasoning effort"}}}},sJ=MV;import{mkdir as CV,open as TV,unlink as RV}from"node:fs/promises";import eJ from"node:os";import j1 from"node:path";function PV($,Z,J){let Y=Z?.trim()||J;if(Y.includes("\x00"))throw Error("Session export path contains a null byte");if(Y==="~")return j1.join(eJ.homedir(),J);if(Y.startsWith(`~${j1.sep}`)||Y.startsWith("~/"))return j1.resolve(eJ.homedir(),Y.slice(2));return j1.resolve($,Y)}async function $3($,Z,J){if(!j1.isAbsolute($))throw Error("Session export cwd must be absolute");let Y=PV($,J,Z.filename);await CV(j1.dirname(Y),{recursive:!0,mode:448});let W,X=!1;try{return W=await TV(Y,"wx",384),X=!0,await W.writeFile(Z.markdown,"utf8"),await W.sync(),Y}catch(Q){if(await W?.close().catch(()=>{return}),W=void 0,X)await RV(Y).catch(()=>{return});if(Q.code==="EEXIST")throw Error(`Session export already exists: ${Y}`);throw Q}finally{await W?.close().catch(()=>{return})}}function SV($){let Z=!1,J=[];for(let Y of $){if(Y==="--reasoning"){Z=!0;continue}if(Y.startsWith("--"))throw Error(`Unknown export option: ${Y}`);J.push(Y)}if(J.length>1)throw Error("Usage: /export [path] [--reasoning]");return{includeReasoning:Z,...J[0]?{outputPath:J[0]}:{}}}var fV={name:"export",description:"Export the current durable conversation as safe Markdown",fullDescription:"将当前完整 durable history 导出为 Markdown。工具活动经过凭证、二进制、宿主路径和体积清理;reasoning 仅在显式 --reasoning 时包含。",usage:"/export [path] [--reasoning]",category:"Session",examples:["/export","/export reports/conversation.md","/export --reasoning"],async handler($,Z){if(!Z.sessionId)return{success:!1,error:"No active session to export"};let J=Z.workspaceRoot??Z.cwd;try{let{includeReasoning:Y,outputPath:W}=SV($),X=await r.exportSessionMarkdown(Z.sessionId,J,{includeReasoning:Y});if(Z.surface==="acp"){if(W)return{success:!1,error:"ACP export does not write host paths; omit the path to receive Markdown"};if(Buffer.byteLength(X.markdown,"utf8")>Z3)return{success:!1,error:"Session export exceeds the ACP inline limit; use the Web export endpoint"};return{success:!0,message:"Session export ready",content:X.markdown,data:{action:"session_exported",filename:X.filename,contentSha256:X.contentSha256,contentBytes:X.contentBytes}}}let Q=await $3(J,X,W);return{success:!0,message:`Saved conversation to ${Q}
1140
1143
  SHA-256 ${X.contentSha256}`,data:{action:"session_exported",filePath:Q,filename:X.filename,contentSha256:X.contentSha256,contentBytes:X.contentBytes,redactionCount:X.redactionCount}}}catch(Y){return{success:!1,error:Y instanceof Error?Y.message:"Session export failed"}}}},J3=fV;function kV($){return $.filter((Z)=>Z.relationType!=="subagent")}var yV={name:"fork",description:"Fork a conversation into an independent session branch",fullDescription:"从任意工作区的历史会话创建独立分支。可以指定唯一 sessionId 直接 fork,或不带参数打开会话选择器。",usage:"/fork [sessionId]",category:"Session",examples:["/fork - 打开会话选择器","/fork parent-session - 直接 fork 指定会话"],async handler($,Z){if($.length>1)return{success:!1,error:"Usage: /fork [sessionId]"};try{let J=await r.listSessions({includeSubagents:!1}),Y=kV(J);if($.length===0){if(Y.length===0)return{success:!1,error:"No forkable sessions found"};return{success:!0,data:{action:"select_session",intent:"fork",sessions:Y}}}let W=$[0],X=J.filter((U)=>U.sessionId===W);if(X.length>0&&X.every((U)=>U.relationType==="subagent"))return{success:!1,error:`Cannot fork subagent session: ${W}`};let Q=Y.filter((U)=>U.sessionId===W);if(Q.length===0)return{success:!1,error:`Session not found: ${W}`};if(Q.length>1)return{success:!1,error:`Multiple workspaces contain session ${W}; use /fork to select one`};return{success:!0,data:{action:"activate_session",intent:"fork",session:Q[0]}}}catch(J){return{success:!1,error:J instanceof Error?J.message:"Failed to list sessions"}}}},Y3=yV;function U3($){let Z=Math.floor((Date.now()-$.getTime())/1000);if(Z<60)return`${Z}s ago`;let J=Math.floor(Z/60);if(J<60)return`${J}m ago`;let Y=Math.floor(J/60);if(Y<24)return`${Y}h ago`;return`${Math.floor(Y/24)}d ago`}async function vV($){let Z=u0.getInstance(),J=i$();if(Object.keys(J).length===0){$.sendMessage(`**MCP 服务器状态**
1141
1144
 
@@ -1616,7 +1619,7 @@ ${J}
1616
1619
  `)),{success:!0,message:"Schedules listed",content:z.join(`
1617
1620
  `)}}case"create":{let U=qK(X);if("error"in U)return Y.sendMessage(`创建失败:${U.error}`),{success:!1,error:U.error};let z={prompt:U.prompt,projectPath:Q,trigger:U.trigger,isolation:"worktree",permissionMode:"default",enabled:!0};try{let V=await $.create(z),H=V.nextRunAt?new Date(V.nextRunAt).toLocaleString():"(无)";return Y.sendMessage(`[OK] 已创建定时任务 \`${V.id}\`
1618
1621
  ${QZ(V.trigger)} · 下次运行: ${H}`),{success:!0,message:`Schedule ${V.id} created`}}catch(V){let H=V instanceof Error?V.message:String(V);return Y.sendMessage(`创建失败:${H}`),{success:!1,error:H}}}case"remove":case"rm":{let U=X[0];if(!U)return Y.sendMessage("用法:/schedule remove <id>"),{success:!1,error:"Missing schedule id"};let z=await $.remove(U);return Y.sendMessage(z?`[OK] 已删除 \`${U}\``:`未找到 \`${U}\``),{success:z,message:z?"Removed":"Not found"}}case"enable":case"disable":{let U=X[0];if(!U)return Y.sendMessage(`用法:/schedule ${W} <id>`),{success:!1,error:"Missing schedule id"};let z=await $.setEnabled(U,W==="enable");return Y.sendMessage(z?`[OK] 已${W==="enable"?"启用":"停用"} \`${U}\``:`未找到 \`${U}\``),{success:Boolean(z),message:z?"Updated":"Not found"}}case"run":{let U=X[0];if(!U)return Y.sendMessage("用法:/schedule run <id>"),{success:!1,error:"Missing schedule id"};try{return await LK(U),Y.sendMessage(`[OK] 已触发 \`${U}\``),{success:!0,message:"Schedule triggered"}}catch(z){let V=z instanceof Error?z.message:String(z);return Y.sendMessage(`运行失败:${V}`),{success:!1,error:V}}}default:return Y.sendMessage(`未知子命令: ${W}
1619
- 使用 /schedule 查看帮助`),{success:!1,error:`Unknown subcommand: ${W}`}}}}}var r3=EK();import*as R1 from"node:fs/promises";import*as P1 from"node:path";async function s3($,Z={}){let{maxResults:J=20,caseSensitive:Y=!1,projectPath:W,storagePath:X}=Z,Q=X??w2(W??T());if(!X){let G=await wK($,W??T(),J,Y);if(G)return G}let U;try{U=(await R1.readdir(Q)).filter((F)=>F.endsWith(".jsonl")&&!F.startsWith("agent_")).map((F)=>P1.join(Q,F))}catch{return[]}let V=(await Promise.all(U.map(async(G)=>{try{let F=await R1.stat(G);return{path:G,mtime:F.mtimeMs}}catch{return null}}))).filter((G)=>G!==null).sort((G,F)=>F.mtime-G.mtime).map((G)=>G.path),H=[],K=Y?$:$.toLowerCase();for(let G of V){if(H.length>=J)break;let F=P1.basename(G,".jsonl"),B=await NK(G,K,Y,F);if(H.push(...B),H.length>=J){H.length=J;break}}return H}async function wK($,Z,J,Y){try{let{syncAll:W}=await import("./chunk-ckvq6z49.js"),X=await o3();if(!X)return null;let{SessionService:Q}=await import("./chunk-et3d69av.js");await W(X,Q.projectionDeriverForSearch());let U=P1.resolve(Z),z=t3(X,$,U,J*4),V=Y?$:$.toLowerCase(),H=[];for(let K of z){if(K.role!=="user"&&K.role!=="assistant")continue;let G=UZ(K.text,V,Y,K.session_id,K.role,K.timestamp??void 0,0);if(G)H.push(G);if(H.length>=J)break}return H}catch{return null}}async function NK($,Z,J,Y){try{let W=await R1.readFile($,"utf8"),Q=W.split(`
1622
+ 使用 /schedule 查看帮助`),{success:!1,error:`Unknown subcommand: ${W}`}}}}}var r3=EK();import*as R1 from"node:fs/promises";import*as P1 from"node:path";async function s3($,Z={}){let{maxResults:J=20,caseSensitive:Y=!1,projectPath:W,storagePath:X}=Z,Q=X??w2(W??T());if(!X){let G=await wK($,W??T(),J,Y);if(G)return G}let U;try{U=(await R1.readdir(Q)).filter((F)=>F.endsWith(".jsonl")&&!F.startsWith("agent_")).map((F)=>P1.join(Q,F))}catch{return[]}let V=(await Promise.all(U.map(async(G)=>{try{let F=await R1.stat(G);return{path:G,mtime:F.mtimeMs}}catch{return null}}))).filter((G)=>G!==null).sort((G,F)=>F.mtime-G.mtime).map((G)=>G.path),H=[],K=Y?$:$.toLowerCase();for(let G of V){if(H.length>=J)break;let F=P1.basename(G,".jsonl"),B=await NK(G,K,Y,F);if(H.push(...B),H.length>=J){H.length=J;break}}return H}async function wK($,Z,J,Y){try{let{syncAll:W}=await import("./chunk-h9xayrwp.js"),X=await o3();if(!X)return null;let{SessionService:Q}=await import("./chunk-3j0dhewn.js");await W(X,Q.projectionDeriverForSearch());let U=P1.resolve(Z),z=t3(X,$,U,J*4),V=Y?$:$.toLowerCase(),H=[];for(let K of z){if(K.role!=="user"&&K.role!=="assistant")continue;let G=UZ(K.text,V,Y,K.session_id,K.role,K.timestamp??void 0,0);if(G)H.push(G);if(H.length>=J)break}return H}catch{return null}}async function NK($,Z,J,Y){try{let W=await R1.readFile($,"utf8"),Q=W.split(`
1620
1623
  `).flatMap((K,G)=>{if(!K.trim())return[];try{return[{event:JSON.parse(K),index:G}]}catch{return[]}});if(!Q.some(({event:K})=>K.type==="session_created"))return bK(Q,Z,J,Y);let z=new Map(Q.flatMap(({event:K,index:G})=>typeof K.id==="string"?[[K.id,G+1]]:[])),V=n3(a3(W,$)),H=new Map;for(let K of V){if(K.type==="message_created"&&(K.data.role==="user"||K.data.role==="assistant"))H.set(K.data.messageId,{role:K.data.role,content:[],timestamp:K.timestamp,lineNumber:z.get(K.id)??0});if(K.type==="part_created"&&K.data.partType==="text"){let G=H.get(K.data.messageId),F=K.data.payload.text;if(G&&typeof F==="string")G.content.push(F)}}return[...H.values()].flatMap((K)=>{let G=UZ(K.content.join(" "),Z,J,Y,K.role,K.timestamp,K.lineNumber);return G?[G]:[]})}catch{return[]}}function bK($,Z,J,Y){return $.flatMap(({event:W,index:X})=>{if(W.type!=="message")return[];let Q=W.message;if(Q?.role!=="user"&&Q?.role!=="assistant"||!Q.content)return[];let U=typeof Q.content==="string"?Q.content:Array.isArray(Q.content)?Q.content.filter((V)=>typeof V==="object"&&V!==null&&V.type==="text"&&typeof V.text==="string").map((V)=>V.text).join(" "):"",z=UZ(U,Z,J,Y,Q.role,typeof W.timestamp==="string"?W.timestamp:void 0,X+1);return z?[z]:[]})}function UZ($,Z,J,Y,W,X,Q){if(!$)return;let U=J?$:$.toLowerCase();if(!U.includes(Z))return;let z=U.indexOf(Z),V=Math.max(0,z-80),H=Math.min($.length,z+Z.length+80);return{sessionId:Y,role:W,content:(V>0?"...":"")+$.slice(V,H).replace(/\n/g," ")+(H<$.length?"...":""),timestamp:X,lineNumber:Q}}function e3($){if($.length===0)return"没有找到匹配的历史记录";let Z=[`**找到 ${$.length} 条匹配:**
1621
1624
  `];for(let J of $){let Y=J.timestamp?new Date(J.timestamp).toLocaleString("zh-CN",{timeZone:"Asia/Shanghai"}):"?",W=J.role==="user"?"\uD83D\uDC64":"\uD83E\uDD16";Z.push(`${W} \`${J.sessionId.slice(0,8)}\` (${Y})`),Z.push(` ${J.content}`),Z.push("")}return Z.join(`
1622
1625
  `)}var AK={name:"search",description:"Search past session transcripts",fullDescription:"搜索历史会话记录,查找过去的对话内容",usage:"/search <keyword>",aliases:["find","history"],category:"Session",examples:['/search 断路器 - 搜索包含"断路器"的历史对话',"/search edit tool - 搜索 edit tool 相关讨论"],async handler($,Z){let J=I(Z);if($.length===0)return J.sendMessage("**用法:** `/search <关键词>`\n\n在历史会话中搜索包含指定关键词的对话"),{success:!0,message:"显示帮助"};let Y=$.join(" ");J.sendMessage(`正在搜索: "${Y}" ...`);try{let W=await s3(Y,{maxResults:15,projectPath:Z.cwd}),X=e3(W);return J.sendMessage(X),{success:!0,message:`found ${W.length} results`,data:{matches:W.length}}}catch(W){let X=W instanceof Error?W.message:"未知错误";return J.sendMessage(`搜索失败: ${X}`),{success:!1,error:X}}}},$Y=AK;var jK={name:"skills",description:"查看所有可用的 Skills",fullDescription:"显示所有已发现的 Skills 及其详细信息,包括名称、描述、来源和允许的工具。",usage:"/skills",category:"system",examples:["/skills"],handler:async($,Z)=>{try{let J=Z.workspaceRoot??Z.cwd;return await U$(J,async(Y)=>{await Y.skills.refresh(),X1(J),await W1(J)}),{success:!0,message:"show_skills_manager",data:{action:"show_skills_manager"}}}catch(J){let Y=`获取 Skills 失败: ${J instanceof Error?J.message:"未知错误"}`;return f().addAssistantMessage(Y),{success:!1,error:Y}}}},ZY=jK;import MK from"node:path";function p5($){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 JY($){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 YY($,Z){if($.length<=Z)return $;return $.slice(0,Z-3)+"..."}async function CK($,Z){let J=I(Z),Y=$[0],W=o.getInstance(),X=U0.getInstance(),Q=Z.sessionId??"",U=Z.sessionId?{sessionId:Z.sessionId,projectPath:MK.resolve(Z.workspaceRoot??Z.cwd)}:void 0;if(Y==="resume"){let F=$[1],B=$.slice(2).join(" ").trim();if(!F||!B)return{success:!1,error:"Usage: /tasks resume <agentId> <prompt>"};if(!Z.subagents)return{success:!1,error:"This surface does not own a subagent runtime"};let D=await Z.subagents.resume(F,B),_=`Resumed \`${F}\` as \`${D.session.id}\` (depth ${D.session.resumeDepth}).`;return J.sendMessage(_),{success:!0,message:_,data:{action:"subagent_resumed",sourceAgentId:F,subagent:D.session}}}if(Y==="clean"){let F=X.cleanupExpiredSessionsForParent(U??Q,0);return J.sendMessage(`已清理 ${F} 个已完成的 Agent 会话`),{success:!0,message:`Cleaned ${F} agent sessions`}}let z=[`**后台任务列表**
@@ -1,4 +1,4 @@
1
- import{ma as F,oa as L}from"./chunk-8chhdkg2.js";import{Lc as $,Nc as B,Vc as Q}from"./chunk-6h3x4jv0.js";import{Se as y}from"./chunk-vpn2e8tj.js";import{Lg as V}from"./chunk-9fm80wbr.js";async function j(){await y(V())}async function I(b){let q=b.message||b._?.[0];if(typeof q==="string"&&q.trim())return q;let z=b.stdin??process.stdin;if(!z.isTTY){let G=[];for await(let K of z)G.push(K);return Buffer.concat(G).toString("utf-8").trim()}if(b.defaultMessage!==void 0)return b.defaultMessage;throw Error("No input provided")}async function M(b){let q=b.message||b._?.[0];if(typeof q==="string"&&q.trim())return q;let z=b.stdin??process.stdin;if(z.isTTY)return;let G=[];for await(let Z of z)G.push(Buffer.isBuffer(Z)?Z:Buffer.from(Z));return Buffer.concat(G).toString("utf-8").trim()||void 0}async function R(b){if(!F(b))return{mode:"agent",content:b};let q=await L(b,{cwd:V(),surface:"headless",workspaceRoot:V()});if(!q.success)return{mode:"output",content:`Error: ${q.error||"未知错误"}`,exitCode:1};let z=q.data;if(z?.action==="invoke_skill"){let{skillName:G,skillArgs:K}=z;return{mode:"agent",content:K?`Please use the "${G}" skill to help me with: ${K}`:`Please use the "${G}" skill.`}}if(z?.action==="invoke_custom_command"||z?.action==="invoke_plugin_command"){let G=z.processedContent;return{mode:"agent",content:`# Custom Command: /${z.commandName}
1
+ import{ma as F,oa as L}from"./chunk-n3amyjrd.js";import{Lc as $,Nc as B,Vc as Q}from"./chunk-5e56atqj.js";import{Ve as y}from"./chunk-xrt796d6.js";import{Og as V}from"./chunk-0141jad7.js";async function j(){await y(V())}async function I(b){let q=b.message||b._?.[0];if(typeof q==="string"&&q.trim())return q;let z=b.stdin??process.stdin;if(!z.isTTY){let G=[];for await(let K of z)G.push(K);return Buffer.concat(G).toString("utf-8").trim()}if(b.defaultMessage!==void 0)return b.defaultMessage;throw Error("No input provided")}async function M(b){let q=b.message||b._?.[0];if(typeof q==="string"&&q.trim())return q;let z=b.stdin??process.stdin;if(z.isTTY)return;let G=[];for await(let Z of z)G.push(Buffer.isBuffer(Z)?Z:Buffer.from(Z));return Buffer.concat(G).toString("utf-8").trim()||void 0}async function R(b){if(!F(b))return{mode:"agent",content:b};let q=await L(b,{cwd:V(),surface:"headless",workspaceRoot:V()});if(!q.success)return{mode:"output",content:`Error: ${q.error||"未知错误"}`,exitCode:1};let z=q.data;if(z?.action==="invoke_skill"){let{skillName:G,skillArgs:K}=z;return{mode:"agent",content:K?`Please use the "${G}" skill to help me with: ${K}`:`Please use the "${G}" skill.`}}if(z?.action==="invoke_custom_command"||z?.action==="invoke_plugin_command"){let G=z.processedContent;return{mode:"agent",content:`# Custom Command: /${z.commandName}
2
2
 
3
3
  ${G}`}}return{mode:"output",content:q.content||q.message||"",exitCode:0}}import{readFile as D,stat as H}from"node:fs/promises";import J from"node:path";function x(b,q){let z;try{z=JSON.parse(b)}catch(G){throw Error(`Invalid JSON output schema from ${q}`,{cause:G})}return B(z).schema}async function _(b){if(b.jsonSchema!==void 0&&b.outputSchema!==void 0)throw Error("--json-schema cannot be combined with --output-schema");if(b.jsonSchema!==void 0)return x(b.jsonSchema,"--json-schema");if(b.outputSchema===void 0)return;let q=J.resolve(b.outputSchema),z=await H(q);if(!z.isFile())throw Error(`Output schema path is not a regular file: ${q}`);if(z.size>$)throw Error(`Output schema exceeds ${$} bytes: ${q}`);return x(await D(q,"utf8"),q)}function N(b){if(!(b instanceof Error))return!1;return b.message.includes("未找到会话")||b.message.includes("ENOENT")||b.message.includes("no such file")}async function W(b){try{return await Q.loadSessionModelContext(b,V())}catch(q){if(N(q))return null;throw q}}async function C(b){if(b.resume===!0||b.resume==="true")throw Error("--resume without a session ID is only supported in interactive UI mode");if(typeof b.resume==="string"&&b.resume.length>0){if(b.forkSession){let G=V(),K=await Q.forkSession(b.resume,{newSessionId:b.sessionId,sourceProjectPath:G,targetProjectPath:G});return{...K,messages:await Q.loadSessionModelContext(K.sessionId,G)}}let[q,z]=await Promise.all([Q.loadSessionModelContext(b.resume),Q.findSessionMetadata(b.resume)]);return{sessionId:b.resume,messages:q,metadata:z}}if(b.continue){let q=b.forkSession?await Q.listSessions({cwd:V()}):await Q.listSessions();if(q.length>0){let z=q[0].sessionId;if(b.forkSession){let G=V(),K=await Q.forkSession(z,{newSessionId:b.sessionId,sourceProjectPath:G,targetProjectPath:G});return{...K,messages:await Q.loadSessionModelContext(K.sessionId,G)}}return{sessionId:z,messages:await Q.loadSessionModelContext(z),metadata:q[0]}}if(b.forkSession)throw Error("Cannot fork: no sessions are available to continue")}if(b.sessionId){let q=await W(b.sessionId);return{sessionId:b.sessionId,messages:q??[],...q?{metadata:await Q.findSessionMetadata(b.sessionId,V())}:{}}}return{sessionId:`${b.fallbackSessionPrefix}-${Date.now()}`,messages:[]}}
4
4
  export{j as m,I as n,M as o,R as p,_ as q,C as r};
@@ -0,0 +1 @@
1
+ import{ve as a,we as b,xe as c}from"./chunk-b948f9w9.js";import"./chunk-dj99h8ca.js";import"./chunk-pfvgkexe.js";import"./chunk-qxn5bg5k.js";import"./chunk-reakyamv.js";import"./chunk-0141jad7.js";import"./chunk-eeb2945p.js";import"./chunk-b9vm7gns.js";import"./chunk-5nezhmnq.js";import"./chunk-h6a0nct6.js";import"./chunk-7ffdedgc.js";import"./chunk-0a0sj79a.js";import"./chunk-sj0k8cdf.js";import"./chunk-0ra945vt.js";import"./chunk-h0fh3j9w.js";export{c as snapshotWorkspaceModelResources,b as resolveWorkspaceModelResources,a as cloneWorkspaceModelConfig};
@@ -0,0 +1 @@
1
+ import{rd as a,sd as b}from"./chunk-69s3e453.js";import"./chunk-7ffdedgc.js";import"./chunk-h0fh3j9w.js";export{a as globalOptions,b as cliConfig};
@@ -1,2 +1,2 @@
1
1
  var F;((D)=>{D.DEFAULT="default";D.AUTO_EDIT="autoEdit";D.YOLO="yolo";D.PLAN="plan"})(F||={});import{Mutex as G}from"async-mutex";class H{entries=new Map;async runExclusive(C,E){let B=this.entries.get(C);if(!B)B={mutex:new G,operations:0},this.entries.set(C,B);B.operations++;try{return await B.mutex.runExclusive(E)}finally{if(B.operations--,B.operations===0&&this.entries.get(C)===B)this.entries.delete(C)}}getStats(){let C=0;for(let E of this.entries.values())C+=E.operations;return{keys:this.entries.size,operations:C}}}
2
- export{F as xg,H as yg};
2
+ export{F as Ag,H as Bg};
@@ -1,2 +1,2 @@
1
- import{zh as S}from"./chunk-kxgr18gy.js";import{Th as f}from"./chunk-bvhbc0wr.js";import*as $ from"fs/promises";import*as K from"path";import j from"semver";import{ProxyAgent as H,fetch as I}from"undici";function R(){return process.env.HTTPS_PROXY||process.env.HTTP_PROXY||process.env.https_proxy||process.env.http_proxy}function N(){let q=R();if(q)try{return new H(q)}catch(z){console.warn(`[proxyFetch] Invalid proxy URL: ${q}`)}return}async function M(q,z={}){let{timeout:W=30000,signal:Q,...B}=z;if(Q?.aborted)throw new DOMException("The operation was aborted.","AbortError");let J=N(),X=new AbortController,Y=!1,F=setTimeout(()=>{Y=!0,X.abort()},W),b=()=>X.abort();Q?.addEventListener("abort",b);try{let Z={method:B.method,headers:B.headers,body:B.body,signal:X.signal,dispatcher:J};return await I(q.toString(),Z)}catch(Z){if(Z instanceof Error&&Z.name==="AbortError"){if(Y)throw Error(`Request timeout after ${W}ms`);throw Z}throw Z}finally{clearTimeout(F),Q?.removeEventListener("abort",b)}}var w="blade-code",y="https://cdn.jsdelivr.net/npm/blade-code@latest/CHANGELOG.md",G=K.join(process.env.HOME||process.env.USERPROFILE||".",".blade"),O=K.join(G,"version-cache.json"),P=3600000,k=`https://registry.npmjs.org/${w}/latest`;async function L(){try{if(process.env.BLADE_VERSION)return process.env.BLADE_VERSION;return S()}catch{return"unknown"}}async function T(){try{let q=await $.readFile(O,"utf-8"),z=JSON.parse(q);if(Date.now()-z.checkedAt<P)return z;return{...z,checkedAt:0}}catch{return null}}async function D(q){try{await $.mkdir(G,{recursive:!0,mode:493}),await $.writeFile(O,JSON.stringify(q,null,2))}catch{}}async function x(){try{let q=await M(k,{timeout:5000,headers:{Accept:"application/json"}});if(!q.ok)return null;return(await q.json()).version||null}catch{return null}}async function _(q=!1){let z=await L(),W=y;if(z==="unknown")return{currentVersion:z,latestVersion:null,hasUpdate:!1,shouldPrompt:!1,releaseNotesUrl:W,error:"Unable to determine current version"};let Q=await T(),B=Q?.skipUntilVersion,J=null;if(!q&&Q?.latestVersion&&Q.checkedAt>0)J=Q.latestVersion;else if(J=await x(),J)await D({latestVersion:J,checkedAt:Date.now(),skipUntilVersion:B});else if(Q?.latestVersion)await D({checkedAt:0,skipUntilVersion:B});if(!J||!j.valid(J))return{currentVersion:z,latestVersion:null,hasUpdate:!1,shouldPrompt:!1,releaseNotesUrl:W,error:"Unable to check for updates"};if(j.lt(J,z))J=z,await D({latestVersion:J,checkedAt:Date.now(),skipUntilVersion:B});let X=j.gt(J,z),Y=X;if(X&&B)Y=j.gt(J,B);return{currentVersion:z,latestVersion:J,hasUpdate:X,shouldPrompt:Y,releaseNotesUrl:W}}async function u(q){let z=await T();await D({latestVersion:z?.latestVersion??q,checkedAt:z?.checkedAt||Date.now(),skipUntilVersion:q})}function g(){return`npm install -g ${w}@latest --registry https://registry.npmjs.org`}async function C(){let{spawn:q}=await import("child_process");return new Promise((z)=>{let W=g(),Q=q(W,{stdio:"inherit",shell:!0});Q.on("close",(B)=>{if(B===0)z({success:!0,message:"Upgrade successful! Please restart blade."});else z({success:!1,message:`Upgrade failed (exit code: ${B})`})}),Q.on("error",(B)=>{z({success:!1,message:`Upgrade failed: ${B.message}`})})})}async function V(){try{let q=await _();return q.shouldPrompt?q:null}catch{return null}}
1
+ import{Ch as S}from"./chunk-7ffdedgc.js";import{Wh as f}from"./chunk-h0fh3j9w.js";import*as $ from"fs/promises";import*as K from"path";import j from"semver";import{ProxyAgent as H,fetch as I}from"undici";function R(){return process.env.HTTPS_PROXY||process.env.HTTP_PROXY||process.env.https_proxy||process.env.http_proxy}function N(){let q=R();if(q)try{return new H(q)}catch(z){console.warn(`[proxyFetch] Invalid proxy URL: ${q}`)}return}async function M(q,z={}){let{timeout:W=30000,signal:Q,...B}=z;if(Q?.aborted)throw new DOMException("The operation was aborted.","AbortError");let J=N(),X=new AbortController,Y=!1,F=setTimeout(()=>{Y=!0,X.abort()},W),b=()=>X.abort();Q?.addEventListener("abort",b);try{let Z={method:B.method,headers:B.headers,body:B.body,signal:X.signal,dispatcher:J};return await I(q.toString(),Z)}catch(Z){if(Z instanceof Error&&Z.name==="AbortError"){if(Y)throw Error(`Request timeout after ${W}ms`);throw Z}throw Z}finally{clearTimeout(F),Q?.removeEventListener("abort",b)}}var w="blade-code",y="https://cdn.jsdelivr.net/npm/blade-code@latest/CHANGELOG.md",G=K.join(process.env.HOME||process.env.USERPROFILE||".",".blade"),O=K.join(G,"version-cache.json"),P=3600000,k=`https://registry.npmjs.org/${w}/latest`;async function L(){try{if(process.env.BLADE_VERSION)return process.env.BLADE_VERSION;return S()}catch{return"unknown"}}async function T(){try{let q=await $.readFile(O,"utf-8"),z=JSON.parse(q);if(Date.now()-z.checkedAt<P)return z;return{...z,checkedAt:0}}catch{return null}}async function D(q){try{await $.mkdir(G,{recursive:!0,mode:493}),await $.writeFile(O,JSON.stringify(q,null,2))}catch{}}async function x(){try{let q=await M(k,{timeout:5000,headers:{Accept:"application/json"}});if(!q.ok)return null;return(await q.json()).version||null}catch{return null}}async function _(q=!1){let z=await L(),W=y;if(z==="unknown")return{currentVersion:z,latestVersion:null,hasUpdate:!1,shouldPrompt:!1,releaseNotesUrl:W,error:"Unable to determine current version"};let Q=await T(),B=Q?.skipUntilVersion,J=null;if(!q&&Q?.latestVersion&&Q.checkedAt>0)J=Q.latestVersion;else if(J=await x(),J)await D({latestVersion:J,checkedAt:Date.now(),skipUntilVersion:B});else if(Q?.latestVersion)await D({checkedAt:0,skipUntilVersion:B});if(!J||!j.valid(J))return{currentVersion:z,latestVersion:null,hasUpdate:!1,shouldPrompt:!1,releaseNotesUrl:W,error:"Unable to check for updates"};if(j.lt(J,z))J=z,await D({latestVersion:J,checkedAt:Date.now(),skipUntilVersion:B});let X=j.gt(J,z),Y=X;if(X&&B)Y=j.gt(J,B);return{currentVersion:z,latestVersion:J,hasUpdate:X,shouldPrompt:Y,releaseNotesUrl:W}}async function u(q){let z=await T();await D({latestVersion:z?.latestVersion??q,checkedAt:z?.checkedAt||Date.now(),skipUntilVersion:q})}function g(){return`npm install -g ${w}@latest --registry https://registry.npmjs.org`}async function C(){let{spawn:q}=await import("child_process");return new Promise((z)=>{let W=g(),Q=q(W,{stdio:"inherit",shell:!0});Q.on("close",(B)=>{if(B===0)z({success:!0,message:"Upgrade successful! Please restart blade."});else z({success:!1,message:`Upgrade failed (exit code: ${B})`})}),Q.on("error",(B)=>{z({success:!1,message:`Upgrade failed: ${B.message}`})})})}async function V(){try{let q=await _();return q.shouldPrompt?q:null}catch{return null}}
2
2
  export{_ as a,u as b,g as c,C as d,V as e};
@@ -1,4 +1,4 @@
1
- import"./chunk-v508x7cg.js";import{vg as Q}from"./chunk-tssmnn37.js";import"./chunk-9ra452yc.js";import"./chunk-js4aekf1.js";import"./chunk-t1bvxk3s.js";import{Lg as L}from"./chunk-9fm80wbr.js";import"./chunk-qnj3dajb.js";import"./chunk-z37v80c1.js";import"./chunk-68stvfdj.js";import"./chunk-vn1r6z64.js";import"./chunk-kxgr18gy.js";import"./chunk-fmkntp49.js";import"./chunk-79cxktz1.js";import"./chunk-9x141v5g.js";import{Th as F}from"./chunk-bvhbc0wr.js";var K=[22,19,0];function T(G){let A=/^v?(\d+)\.(\d+)\.(\d+)/.exec(G);if(!A)return!1;let H=A.slice(1).map(Number);for(let z=0;z<K.length;z++){let B=H[z]??0,J=K[z];if(B!==J)return B>J}return!0}var X={command:"doctor",describe:"Check the health of your Blade installation",builder:(G)=>G.option("rebuild-index",{type:"boolean",default:!1,describe:"Rebuild the SQLite session index from JSONL transcripts"}),handler:async(G)=>{if(G.rebuildIndex){console.log(`Rebuilding session index from JSONL transcripts...
2
- `);try{let{rebuildProjectionIndex:z}=await import("./chunk-ckvq6z49.js"),{SessionService:B}=await import("./chunk-et3d69av.js"),J=await z(B.projectionDeriverForSearch());if(J===null)console.log("[WARN] Session index unavailable (SQLite driver missing); reads fall back to JSONL scan.");else console.log(`[OK] Session index rebuilt: ${J} session(s) indexed.`)}catch(z){console.log("[FAIL] Session index rebuild failed"),console.log(` Error: ${z instanceof Error?z.message:"未知错误"}`),process.exit(1)}return}console.log(`Running Blade health check...
1
+ import"./chunk-v508x7cg.js";import{yg as Q}from"./chunk-dj99h8ca.js";import"./chunk-pfvgkexe.js";import"./chunk-qxn5bg5k.js";import"./chunk-reakyamv.js";import{Og as L}from"./chunk-0141jad7.js";import"./chunk-eeb2945p.js";import"./chunk-b9vm7gns.js";import"./chunk-5nezhmnq.js";import"./chunk-h6a0nct6.js";import"./chunk-7ffdedgc.js";import"./chunk-0a0sj79a.js";import"./chunk-sj0k8cdf.js";import"./chunk-0ra945vt.js";import{Wh as F}from"./chunk-h0fh3j9w.js";var K=[22,19,0];function T(G){let A=/^v?(\d+)\.(\d+)\.(\d+)/.exec(G);if(!A)return!1;let H=A.slice(1).map(Number);for(let z=0;z<K.length;z++){let B=H[z]??0,J=K[z];if(B!==J)return B>J}return!0}var X={command:"doctor",describe:"Check the health of your Blade installation",builder:(G)=>G.option("rebuild-index",{type:"boolean",default:!1,describe:"Rebuild the SQLite session index from JSONL transcripts"}),handler:async(G)=>{if(G.rebuildIndex){console.log(`Rebuilding session index from JSONL transcripts...
2
+ `);try{let{rebuildProjectionIndex:z}=await import("./chunk-h9xayrwp.js"),{SessionService:B}=await import("./chunk-3j0dhewn.js"),J=await z(B.projectionDeriverForSearch());if(J===null)console.log("[WARN] Session index unavailable (SQLite driver missing); reads fall back to JSONL scan.");else console.log(`[OK] Session index rebuilt: ${J} session(s) indexed.`)}catch(z){console.log("[FAIL] Session index rebuild failed"),console.log(` Error: ${z instanceof Error?z.message:"未知错误"}`),process.exit(1)}return}console.log(`Running Blade health check...
3
3
  `);let A=0;try{await Q.getInstance().initialize(),console.log("[OK] Configuration: OK")}catch(z){console.log("[FAIL] Configuration: FAILED"),console.log(` Error: ${z instanceof Error?z.message:"未知错误"}`),A++}let H=process.version;if(T(H))console.log(`[OK] Node.js version: ${H}`);else console.log(`[WARN] Node.js version: ${H} (required: >=22.19.0)`),A++;try{let z=await import("fs/promises"),B=L();await z.access(B,(await import("fs")).constants.R_OK|(await import("fs")).constants.W_OK),console.log("[OK] File system permissions: OK")}catch(z){console.log("[FAIL] File system permissions: FAILED"),console.log(" Error: Cannot read/write in current directory"),A++}try{await import("ink"),console.log("[OK] Dependencies: OK")}catch(z){console.log("[FAIL] Dependencies: FAILED"),console.log(" Error: Missing required dependencies"),A++}if(console.log(`
4
4
  Health Check Summary:`),A===0)console.log("All checks passed! Blade is ready to use.");else console.log(`Warning: Found ${A} issue(s). Please resolve them for optimal performance.`),process.exit(1)}};export{T as isSupportedNodeVersion,X as doctorCommands};
@@ -1,4 +1,4 @@
1
- import{m as R,n as c,o as g,p as d,q as m,r as l}from"./chunk-90yjhvjb.js";import{Q as M,Y as y}from"./chunk-8chhdkg2.js";import"./chunk-cgd0vjw2.js";import"./chunk-eesa8c5h.js";import{Eb as A,vb as h}from"./chunk-66w68q81.js";import"./chunk-r8wbvxn7.js";import{Hc as w,Vc as U}from"./chunk-6h3x4jv0.js";import"./chunk-skw3b17a.js";import"./chunk-vdtma2yq.js";import{rd as C}from"./chunk-zk34d9mm.js";import{td as I,ud as S,vd as v}from"./chunk-vwa2kczj.js";import{wd as O}from"./chunk-r8ayexxd.js";import"./chunk-zwd5q6dt.js";import{Td as P}from"./chunk-yhyqcmh1.js";import"./chunk-v508x7cg.js";import"./chunk-c9e0fbyh.js";import"./chunk-01k69v34.js";import"./chunk-wx9zxzgm.js";import"./chunk-js4vqnds.js";import"./chunk-ttbq1xmz.js";import"./chunk-vpn2e8tj.js";import"./chunk-c80pzvhs.js";import"./chunk-n5d0d6q7.js";import"./chunk-8bsse16j.js";import"./chunk-9k3tg2hs.js";import"./chunk-psy247es.js";import"./chunk-tssmnn37.js";import{xg as F}from"./chunk-9ra452yc.js";import"./chunk-js4aekf1.js";import"./chunk-t1bvxk3s.js";import{Lg as z}from"./chunk-9fm80wbr.js";import"./chunk-qnj3dajb.js";import"./chunk-z37v80c1.js";import"./chunk-68stvfdj.js";import"./chunk-vn1r6z64.js";import"./chunk-kxgr18gy.js";import"./chunk-fmkntp49.js";import"./chunk-79cxktz1.js";import"./chunk-9x141v5g.js";import"./chunk-bvhbc0wr.js";import p from"yargs";import{hideBin as e}from"yargs/helpers";var s=new Set(Object.values(F));function t(j){if(j&&s.has(j))return j;return}function x(j){if(j.options.outputFormat==="json")j.io.stdout.write(`${JSON.stringify({response:j.response,...j.structuredOutput?{structured_output:j.structuredOutput,output_schema_digest:j.structuredOutputSchemaDigest}:{},input:j.requestInput,model:j.options.model,timestamp:new Date().toISOString()},null,2)}
1
+ import{m as R,n as c,o as g,p as d,q as m,r as l}from"./chunk-nqcpyazv.js";import{Q as M,Y as y}from"./chunk-n3amyjrd.js";import"./chunk-b86m3bpv.js";import"./chunk-ky9q53m7.js";import{Eb as A,vb as h}from"./chunk-0cbr2gs7.js";import"./chunk-r8wbvxn7.js";import{Hc as w,Vc as U}from"./chunk-5e56atqj.js";import"./chunk-skw3b17a.js";import"./chunk-jwx10h5z.js";import{rd as C}from"./chunk-69s3e453.js";import{td as I,ud as S,vd as v}from"./chunk-c8td6vaa.js";import{wd as O}from"./chunk-jdb2mwbn.js";import"./chunk-h3w814js.js";import{Td as P}from"./chunk-yqkyhp0e.js";import"./chunk-v508x7cg.js";import"./chunk-c9e0fbyh.js";import"./chunk-seamt0j3.js";import"./chunk-33bpwkyk.js";import"./chunk-mygw13zd.js";import"./chunk-b948f9w9.js";import"./chunk-xrt796d6.js";import"./chunk-jzvbjn6e.js";import"./chunk-7nx0pzfk.js";import"./chunk-b9nhnzaj.js";import"./chunk-je4xvy93.js";import"./chunk-zkhb55jz.js";import"./chunk-dj99h8ca.js";import{Ag as F}from"./chunk-pfvgkexe.js";import"./chunk-qxn5bg5k.js";import"./chunk-reakyamv.js";import{Og as z}from"./chunk-0141jad7.js";import"./chunk-eeb2945p.js";import"./chunk-b9vm7gns.js";import"./chunk-5nezhmnq.js";import"./chunk-h6a0nct6.js";import"./chunk-7ffdedgc.js";import"./chunk-0a0sj79a.js";import"./chunk-sj0k8cdf.js";import"./chunk-0ra945vt.js";import"./chunk-h0fh3j9w.js";import p from"yargs";import{hideBin as e}from"yargs/helpers";var s=new Set(Object.values(F));function t(j){if(j&&s.has(j))return j;return}function x(j){if(j.options.outputFormat==="json")j.io.stdout.write(`${JSON.stringify({response:j.response,...j.structuredOutput?{structured_output:j.structuredOutput,output_schema_digest:j.structuredOutputSchemaDigest}:{},input:j.requestInput,model:j.options.model,timestamp:new Date().toISOString()},null,2)}
2
2
  `);else if(j.options.outputFormat==="stream-json")j.io.stdout.write(`${JSON.stringify(j.structuredOutput?{type:"structured_output",output:j.structuredOutput,schema_digest:j.structuredOutputSchemaDigest}:{type:"response",content:j.response})}
3
3
  `);else j.io.stdout.write(`${j.response}
4
4
  `)}function i(j){return j.command("* [message]","Print response and exit (useful for pipes)",(B)=>B.positional("message",{describe:"Message to process",type:"string"}).option("p",{alias:"print",describe:"Print response and exit (useful for pipes)",type:"boolean"}).option("output-format",{describe:'Output format: "text", "json", "stream-json"',type:"string",default:"text"}).option("include-partial-messages",{describe:"Include partial message chunks as they arrive",type:"boolean"}).option("input-format",{describe:'Input format: "text", "stream-json"',type:"string",default:"text"}).option("json-schema",{alias:["jsonSchema"],describe:"Inline JSON Schema for the structured final response",type:"string"}).option("output-schema",{alias:["outputSchema"],describe:"Path to a JSON Schema file for the structured final response",type:"string"}).option("model",{describe:"Model for the current session",type:"string"}).option("append-system-prompt",{describe:"Append a system prompt to the default system prompt",type:"string"}).option("system-prompt",{describe:"Replace the default system prompt",type:"string"}).option("max-turns",{alias:["maxTurns"],describe:"Maximum conversation turns (-1: unlimited, N>0: limit to N turns)",type:"number"}),async(B)=>{if(!B.p)return;let q=await n(B);process.exit(q)})}async function n(j,B=process){let q;try{await R();let _=j.forkSession!==!0&&(j.continue===!0||typeof j.resume==="string"&&j.resume.length>0)?await g({message:j.message,_:j._}):await c({message:j.message,_:j._,defaultMessage:"Hello"}),J=_===void 0,T=J?{mode:"agent",content:""}:await d(_);if(T.mode==="output"){if(T.content)B.stdout.write(`${T.content}
@@ -1,2 +1,2 @@
1
1
  import d from"typebox/schema";import o from"typebox/value";class u extends Error{issues;constructor(r){super(r.map((t)=>{return`${t.path.length>0?t.path.join("."):"root"}: ${t.message}`}).join("; "));this.issues=r;this.name="SchemaValidationError"}}function p(r){if(!r)return[];return r.split("/").slice(1).map((t)=>t.replace(/~1/g,"/").replace(/~0/g,"~")).map((t)=>/^(0|[1-9]\d*)$/.test(t)?Number(t):t)}function g(r,t){let n=r;for(let e of t){if(n===null||typeof n!=="object")return;n=n[e]}return n}function i(r,t){let[,n]=d.Errors(r,t);return n.map((e)=>{let s=p(e.instancePath);return{code:e.keyword,path:s,message:e.message,value:g(t,s)}})}function a(r,t){let n=o.Default(r,o.Clone(t)),e=i(r,n);if(e.length>0)return{success:!1,error:new u(e)};let s=o.Clean(r,n),c=i(r,s);if(c.length>0)return{success:!1,error:new u(c)};return{success:!0,data:s}}function f(r,t){let n=a(r,t);if(!n.success)throw n.error;return n.data}import l from"typebox";function x(r){return Object.defineProperties(r,{parse:{value:(t)=>f(r,t),enumerable:!1},safeParse:{value:(t)=>a(r,t),enumerable:!1}}),r}function b(r,t){return l.Optional({...r,default:t})}function V(r,t={}){return l.Unsafe({type:"string",enum:[...r],...t})}
2
- export{a as zg,f as Ag,l as Bg,x as Cg,b as Dg,V as Eg};
2
+ export{a as Cg,f as Dg,l as Eg,x as Fg,b as Gg,V as Hg};
@@ -1,2 +1,2 @@
1
- import{eg as H,fg as I}from"./chunk-tssmnn37.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{hg as H,ig as I}from"./chunk-dj99h8ca.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};
@@ -0,0 +1,6 @@
1
+ import{m as fH,n as yH,o as SH,p as TH,q as bH,r as RH}from"./chunk-nqcpyazv.js";import{A as JH,v as MH,w as t,x as e,y as HH,z as d}from"./chunk-geam96gd.js";import{Q as xH,S as UH,T as _H,V as ZH,Y as GH}from"./chunk-n3amyjrd.js";import"./chunk-b86m3bpv.js";import"./chunk-ky9q53m7.js";import{Eb as jH,jb as s,vb as WH}from"./chunk-0cbr2gs7.js";import"./chunk-r8wbvxn7.js";import{Kc as O,Vc as a,vc as DH,zc as LH}from"./chunk-5e56atqj.js";import"./chunk-skw3b17a.js";import"./chunk-jwx10h5z.js";import{rd as FH}from"./chunk-69s3e453.js";import{td as EH,ud as zH,vd as AH}from"./chunk-c8td6vaa.js";import{wd as PH}from"./chunk-jdb2mwbn.js";import"./chunk-h3w814js.js";import{Wd as QH}from"./chunk-yqkyhp0e.js";import"./chunk-v508x7cg.js";import"./chunk-c9e0fbyh.js";import"./chunk-seamt0j3.js";import"./chunk-33bpwkyk.js";import"./chunk-mygw13zd.js";import"./chunk-b948f9w9.js";import"./chunk-xrt796d6.js";import{hf as VH}from"./chunk-jzvbjn6e.js";import"./chunk-7nx0pzfk.js";import"./chunk-b9nhnzaj.js";import"./chunk-je4xvy93.js";import"./chunk-zkhb55jz.js";import"./chunk-dj99h8ca.js";import{Ag as BH}from"./chunk-pfvgkexe.js";import{Cg as NH,Eg as H,Fg as KH,Hg as N}from"./chunk-qxn5bg5k.js";import"./chunk-reakyamv.js";import{Og as g}from"./chunk-0141jad7.js";import"./chunk-eeb2945p.js";import"./chunk-b9vm7gns.js";import"./chunk-5nezhmnq.js";import"./chunk-h6a0nct6.js";import"./chunk-7ffdedgc.js";import"./chunk-0a0sj79a.js";import"./chunk-sj0k8cdf.js";import"./chunk-0ra945vt.js";import"./chunk-h0fh3j9w.js";import fJ from"yargs";import{hideBin as yJ}from"yargs/helpers";function p(K,V,Q){if(K.off){K.off(V,Q);return}K.removeListener?.(V,Q)}function mH(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,q)=>{let J=!1,Z=()=>{p(K,"drain",x),p(K,"error",j),V.removeEventListener("abort",G)},W=(F)=>{if(J)return;J=!0,Z(),F()},x=()=>W(Q),j=(F)=>W(()=>q(F??Error("Writable emitted an error"))),G=()=>W(()=>q(V.reason??Error("Writable drain aborted")));if(V.aborted){G();return}let f=K.once?.bind(K)??K.on?.bind(K);f?.("drain",x),f?.("error",j),V.addEventListener("abort",G,{once:!0})})}async function cH(K,V,Q){if(K.destroyed||K.writableEnded)throw Error("Writable is already closed");if(K.write(V)===!1)await mH(K,Q)}class v{options;queues;sinkErrorListeners=[];failed=!1;closing=!1;handleAbort=()=>{this.fail(new d("aborted","Headless output was aborted",{cause:this.options.signal?.reason}))};constructor(K,V={}){this.options=V;let Q=(q)=>new JH({maxPendingItems:V.maxPendingItems??t,maxPendingBytes:V.maxPendingBytes??e,writeTimeoutMs:V.writeTimeoutMs??HH,sizeOf:(J)=>Buffer.byteLength(J),write:(J,Z)=>cH(K[q],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 d("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))p(K,"error",V)}}var $H=1;function D(K){return H.Object({event_version:H.Literal($H),...K})}var uH=D({type:H.Literal("content_delta"),delta:H.String()}),dH=D({type:H.Literal("thinking_delta"),delta:H.String()}),pH=D({type:H.Literal("thinking"),content:H.String()}),vH=D({type:H.Literal("stream_end")}),lH=D({type:H.Literal("content"),content:H.String()}),aH=D({type:H.Literal("structured_output"),output:H.Record(H.String(),H.Unknown()),schema_digest:H.String({pattern:"^[a-f0-9]{64}$"})}),l=N(["readonly","write","execute"]),sH=H.Object({kind:l,scope:N(["global","session"]),queue_position:H.Integer({minimum:1}),in_flight:H.Integer({minimum:0}),limit:H.Integer({minimum:1})}),iH=D({type:H.Literal("tool_start"),tool_name:H.String(),summary:H.String(),target:H.Optional(H.String()),tool_kind:H.Optional(l)}),oH=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(sH)}),rH=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"])}),nH=D({type:H.Literal("tool_result"),tool_name:H.String(),summary:H.String(),target:H.Optional(H.String()),tool_kind:H.Optional(l),success:H.Optional(H.Boolean()),error_type:H.Optional(H.String()),error_message:H.Optional(H.String()),background:H.Optional(rH)}),tH=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())}),eH=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())}),HJ=D({type:H.Literal("mcp_resource_updated"),revision:H.Integer({minimum:1}),server_name:H.String(),uri:H.String()}),JJ=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())}),KJ=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())}),VJ=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())}),ZJ=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())}),$J=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()}),qJ=D({type:H.Literal("user_shell_started"),execution_id:H.String(),command:H.String(),auxiliary:H.Boolean()}),XJ=D({type:H.Literal("user_shell_output"),execution_id:H.String(),stream:N(["stdout","stderr"]),chunk:H.String(),stream_truncated:H.Boolean()}),YJ=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()}),BJ=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())}),NJ=D({type:H.Literal("tool_detail"),tool_name:H.String(),detail:H.String()}),QJ=D({type:H.Literal("task_update"),tasks:H.Array(ZH)}),DJ=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(VH)),premature_stop_count:H.Optional(H.Integer({minimum:1}))}),LJ=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}))}),WJ=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())}),jJ=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})),post_tokens:H.Optional(H.Number({minimum:0})),sample_attempts:H.Optional(H.Integer({minimum:0})),failure_reason:H.Optional(N(["circuit_open","deterministic","empty_exhausted","transient_exhausted"]))}),xJ=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"]))}),UJ=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}))}),_J=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}))}),GJ=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()}),PJ=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_limit"),turns_count:H.Number(),action:H.Literal("continue")}),EJ=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())}),zJ=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})}),AJ=D({type:H.Literal("output"),content:H.String(),exit_code:H.Number()}),MJ=D({type:H.Literal("error"),message:H.String()}),iJ=KH(H.Union([uH,dH,pH,vH,lH,aH,iH,oH,nH,tH,eH,HJ,JJ,KJ,VJ,ZJ,$J,qJ,XJ,YJ,BJ,NJ,QJ,DJ,LJ,WJ,jJ,UJ,_J,xJ,GJ,PJ,FJ,EJ,zJ,AJ,MJ]));function qH(K,V){return{event_version:$H,type:K,...V}}function SJ(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 TJ(K){let V=new AbortController,Q=(Z)=>{if(!V.signal.aborted)V.abort(Z)},q=()=>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",q),process.once("SIGTERM",q);return{signal:V.signal,abort:Q,dispose:()=>{K?.signal?.removeEventListener("abort",J),process.removeListener("SIGINT",q),process.removeListener("SIGTERM",q)}}}var bJ=N(["text","jsonl"]),RJ=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(BH)),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(bJ),jsonSchema:H.Optional(H.String()),outputSchema:H.Optional(H.String())});class IH{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 IJ(K){return K.issues.map((V)=>`${V.path.join(".")||"options"}: ${V.message}`).join("; ")}function gJ(K){let V=NH(RJ,K);if(!V.success)throw Error(`Invalid headless options: ${IJ(V.error)}`);return V.data}function CJ(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 cJ(V);process.exit(Q)})}function L(K,V=""){K.write(`${V}
2
+ `)}function kJ(K){return`[task] [${K.status}] ${K.subject}`}function hJ(){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 OJ(K){if(!(K instanceof Error))return"Unknown error";let q=K.lastError??K;if(q.responseBody)try{let W=JSON.parse(q.responseBody)?.error?.message;if(W)return q.statusCode?`${W} (HTTP ${q.statusCode})`:W}catch{}let J=K.message.match(/Last error:\s*(.+)$/);if(J)return J[1];return K.message}function wJ(K){return K==="jsonl"?"jsonl":"text"}function XH(K,V){let Q=(...q)=>{for(let J of q){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 mJ(K,V,Q,q){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)&&!q.targetLocked)return{phase:"target_hit",status:"hit",message:`Target locked: ${V}`,shouldLockTarget:!0};if(q.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:q.targetLocked?"hit":"ongoing",message:`Executing: ${V}`,shouldLockTarget:!1}}function YH(K,V,Q=!1){let q=(J,Z)=>{K.stdout.write(`${JSON.stringify(qH(J,Z))}
3
+ `)};return{contentDelta(J){if(V==="jsonl"){q("content_delta",{delta:J});return}if(Q)return;K.stdout.write(J)},thinkingDelta(J,Z){if(V==="jsonl")return q("thinking_delta",{delta:J}),Z;if(!Z)K.stderr.write("[thinking] ");return K.stderr.write(J),!0},thinking(J){if(V==="jsonl"){q("thinking",{content:J});return}L(K.stderr,`[thinking] ${J}`)},streamEnd(J,Z){if(V==="jsonl"){q("stream_end",{});return}if(Z)K.stderr.write(`
4
+ `);if(J)K.stdout.write(`
5
+ `)},content(J){if(V==="jsonl"){q("content",{content:J});return}L(K.stdout,J)},structuredOutput(J){if(V==="jsonl"){q("structured_output",{output:J.output,schema_digest:J.schemaDigest});return}L(K.stdout,JSON.stringify(J.output))},toolStart(J,Z,W,x){if(V==="jsonl"){q("tool_start",{tool_name:J,summary:Z,target:W,tool_kind:x});return}L(K.stderr,`[tool:start] ${Z}`)},toolProgress(J,Z,W,x,j){if(V==="jsonl"){q("tool_progress",{tool_name:J,message:Z,progress:W,total:x,admission:j?{kind:j.kind,scope:j.scope,queue_position:j.queuePosition,in_flight:j.inFlight,limit:j.limit}:void 0});return}L(K.stderr,`[tool:progress] ${J}: ${Z}`)},toolResult(J,Z,W,x,j){if(V==="jsonl"){q("tool_result",{tool_name:J,summary:Z,target:W,tool_kind:x,success:j?.success,error_type:j?.errorType,error_message:j?.errorMessage,background:j?.background});return}L(K.stderr,`[tool:result] ${Z}`)},mcpCatalogChanged(J){if(V==="jsonl"){q("mcp_catalog_changed",{revision:J.revision,server_name:J.serverName,added:J.added,removed:J.removed,updated:J.updated});return}L(K.stderr,`[mcp:catalog] r${J.revision} ${J.serverName} +${J.added.length} -${J.removed.length} ~${J.updated.length}`)},mcpContentChanged(J){if(V==="jsonl"){q("mcp_content_changed",{revision:J.revision,server_name:J.serverName,content_kind:J.contentKind==="resourceTemplates"?"resource_templates":J.contentKind,added:J.added,removed:J.removed,updated:J.updated});return}L(K.stderr,`[mcp:${J.contentKind}] r${J.revision} ${J.serverName} +${J.added.length} -${J.removed.length} ~${J.updated.length}`)},mcpResourceUpdated(J){if(V==="jsonl"){q("mcp_resource_updated",{revision:J.revision,server_name:J.serverName,uri:J.uri});return}L(K.stderr,`[mcp:resource] r${J.revision} ${J.serverName} updated ${J.uri}`)},mcpConnectionChanged(J){if(V==="jsonl"){q("mcp_connection_changed",{revision:J.revision,server_name:J.serverName,phase:J.phase,reason:J.reason,attempt:J.attempt,max_attempts:J.maxAttempts,...J.nextRetryAt!==void 0?{next_retry_at:J.nextRetryAt}:{},...J.error?{error:J.error}:{}});return}L(K.stderr,`[mcp:connection] r${J.revision} ${J.serverName} ${J.phase} ${J.attempt}/${J.maxAttempts}`)},mcpLog(J){if(V==="jsonl"){q("mcp_log",{revision:J.revision,server_name:J.serverName,level:J.level,logger:J.logger,message:J.message,projected_bytes:J.projectedBytes,data_sha256:J.dataSha256,truncated:J.truncated,details_omitted:J.detailsOmitted,timestamp:J.timestamp,synthetic:J.synthetic});return}L(K.stderr,`[mcp:log] ${J.level} ${J.serverName}${J.logger?` logger=${J.logger}`:""}: ${J.message}`)},mcpInstructionsChanged(J){if(V==="jsonl"){q("mcp_instructions_changed",{revision:J.revision,server_name:J.serverName,action:J.action,reason:J.reason,text:J.text,source_bytes:J.sourceBytes,projected_bytes:J.projectedBytes,sha256:J.sha256,truncated:J.truncated,details_omitted:J.detailsOmitted});return}L(K.stderr,`[mcp:instructions] ${J.action} ${J.serverName}${J.truncated?" (truncated)":""}`)},mcpTaskChanged(J){if(V==="jsonl"){q("mcp_task_changed",{revision:J.revision,task_id:J.taskId,server_name:J.serverName,tool_name:J.toolName,status:J.status,status_message:J.statusMessage,created_at:J.createdAt,updated_at:J.updatedAt,completed_at:J.completedAt,has_result:J.hasResult,error:J.error});return}L(K.stderr,`[mcp:task] ${J.taskId} ${J.serverName}/${J.toolName} `+J.status)},projectRulesLoaded(J){if(V==="jsonl"){q("project_rules_loaded",{files:J.files.map((Z)=>({id:Z.id,relative_path:Z.relativePath,source:Z.source,conditional:Z.conditional,content_sha256:Z.contentSha256})),trigger_paths:J.triggerPaths,blocked_write:J.blockedWrite});return}L(K.stderr,`[project-rules] loaded ${J.files.length} file(s)${J.blockedWrite?" before write":""}`)},userShellStarted(J,Z,W){if(V==="jsonl"){q("user_shell_started",{execution_id:J,command:Z,auxiliary:W});return}L(K.stderr,`[user-shell:start] ${Z}`)},userShellOutput(J,Z,W,x){if(V==="jsonl"){q("user_shell_output",{execution_id:J,stream:Z,chunk:W,stream_truncated:x});return}(Z==="stderr"?K.stderr:K.stdout).write(W)},userShellCompleted(J){if(V==="jsonl"){q("user_shell_completed",{execution_id:J.executionId,message_id:J.messageId,status:J.record.status,exit_code:J.record.exitCode,duration_ms:J.record.durationMs,stdout:J.record.stdout,stderr:J.record.stderr,truncated:J.record.truncated,auxiliary:J.auxiliary});return}L(K.stderr,`[user-shell:${J.record.status}] exit=${J.record.exitCode??"null"} ${J.record.durationMs}ms`)},phase(J,Z,W,x={}){if(V==="jsonl"){q("phase",{phase:J,status:Z,message:W,turn:x.turn,tool_name:x.toolName,target:x.target});return}L(K.stderr,`[phase:${J}] ${W}`)},toolDetail(J,Z){if(V==="jsonl"){q("tool_detail",{tool_name:J,detail:Z});return}L(K.stderr,Z)},taskUpdate(J){if(V==="jsonl"){q("task_update",{tasks:J});return}for(let Z of J)L(K.stderr,kJ(Z))},goal(J){if(V==="jsonl"){q("goal",{state:J.goal?"updated":"cleared",goal_id:J.goal?.goalId,status:J.goal?.status,verification_attempt:J.goal?.completionVerification?.attempt,verification_status:J.goal?.completionVerification?.status,verifier_session_id:J.goal?.completionVerification?.verifierSessionId,verification_evidence_sha256:J.goal?.completionVerification?.evidenceSha256,verification_summary:J.goal?.completionVerification?.summary,verification_stall_count:J.goal?.verificationStall?.consecutiveCount,premature_stop_pattern:J.goal?.prematureStop?.pattern,premature_stop_count:J.goal?.prematureStop?.consecutiveCount});return}if(J.goal)L(K.stderr,`[goal:${J.goal.status}] ${J.goal.objective}`);else L(K.stderr,"[goal:cleared]")},subagent(J){let Z=J.kind==="subagent_spawned";if(V==="jsonl"){q("subagent",{state:Z?"spawned":"completed",session_id:J.sessionId,subagent_type:J.type,success:Z?void 0:J.success,summary:Z?void 0:J.summary,verification_verdict:Z?void 0:J.verificationVerdict,resumed_from:J.resumedFrom,root_agent_id:J.rootAgentId,resume_depth:J.resumeDepth});return}L(K.stderr,`[subagent:${Z?"spawned":"completed"}] ${J.sessionId}${J.resumedFrom?` resumed from ${J.resumedFrom}`:""}`)},tokenUsage(J){if(V==="jsonl"){q("token_usage",{input_tokens:J.inputTokens,output_tokens:J.outputTokens,total_tokens:J.totalTokens,max_context_tokens:J.maxContextTokens,cache_read_tokens:J.cacheReadTokens,cache_write_tokens:J.cacheWriteTokens,prompt_cache_break:J.cacheBreak?{reason:J.cacheBreak.reason,previous_cache_read_tokens:J.cacheBreak.previousCacheReadTokens,cache_read_tokens:J.cacheBreak.cacheReadTokens,cache_write_tokens:J.cacheBreak.cacheWriteTokens,token_drop:J.cacheBreak.tokenDrop,elapsed_ms:J.cacheBreak.elapsedMs,call_number:J.cacheBreak.callNumber,system_prompt_changed:J.cacheBreak.systemPromptChanged,system_char_delta:J.cacheBreak.systemCharDelta,tools_changed:J.cacheBreak.toolsChanged,added_tool_count:J.cacheBreak.addedToolCount,removed_tool_count:J.cacheBreak.removedToolCount,changed_tool_count:J.cacheBreak.changedToolCount,model_changed:J.cacheBreak.modelChanged,request_policy_changed:J.cacheBreak.requestPolicyChanged}:void 0,cost_usd:J.costUsd});return}L(K.stderr,`[tokens] in=${J.inputTokens} out=${J.outputTokens} total=${J.totalTokens} / ${J.maxContextTokens}`)},compacting(J){let Z=J.phase==="start";if(V==="jsonl"){q("compacting",{state:Z?"started":"completed",reason:J.reason,strategy:J.strategy,outcome:J.outcome,pre_tokens:J.preTokens,post_tokens:J.postTokens,sample_attempts:J.sampleAttempts,failure_reason:J.failureReason});return}L(K.stderr,Z?`[context] compacting started${J.reason?` (${J.reason})`:""}`:`[context] compacting ${J.outcome??"completed"}${J.sampleAttempts!==void 0?` after ${J.sampleAttempts} sample attempt${J.sampleAttempts===1?"":"s"}`:""}`)},providerAdmission(J){if(V==="jsonl"){q("provider_admission",{phase:J.phase,request_class:J.requestClass,resource:J.resource,scope:J.scope,reason:J.reason,queue_position:J.queuePosition,queue_depth:J.queueDepth,in_flight:J.inFlight,limit:J.limit,wait_ms:J.waitMs,max_wait_ms:J.maxWaitMs,recovery_remaining_ms:J.recoveryRemainingMs});return}L(K.stderr,`[provider-admission:${J.phase}] ${J.resource}/${J.scope} ${J.inFlight}/${J.limit} queue=${J.queuePosition}/${J.queueDepth}`)},providerRetry(J){if(V==="jsonl"){q("provider_retry",{phase:J.phase,attempt:J.attempt,max_retries:J.maxRetries,reason:J.reason,status_code:J.statusCode,delay_ms:J.delayMs,next_retry_at:J.nextRetryAt,mode:J.mode,recovery_budget_ms:J.recoveryBudgetMs,recovery_elapsed_ms:J.recoveryElapsedMs,recovery_remaining_ms:J.recoveryRemainingMs,exhausted_by:J.exhaustedBy});return}let Z=J.delayMs!==void 0?` in ${Math.max(0,Math.ceil(J.delayMs/1000))}s`:"";L(K.stderr,`[provider-retry:${J.phase}] ${J.attempt}/${J.maxRetries} ${J.reason}${Z}`)},providerCircuit(J){if(V==="jsonl"){q("provider_circuit",{phase:J.phase,reason:J.reason,status_code:J.statusCode,retry_after_ms:J.retryAfterMs,next_probe_at:J.nextProbeAt,open_duration_ms:J.openDurationMs,sample_count:J.sampleCount,failure_count:J.failureCount,recovery_remaining_ms:J.recoveryRemainingMs});return}let Z=J.retryAfterMs!==void 0?` retry in ${Math.max(0,Math.ceil(J.retryAfterMs/1000))}s`:"";L(K.stderr,`[provider-circuit:${J.phase}] ${J.reason}${Z}`)},providerStall(J){if(V==="jsonl"){q("provider_stall",{phase:J.phase,stall_count:J.stallCount,duration_ms:J.durationMs,warning_after_ms:J.warningAfterMs,timeout_ms:J.timeoutMs,output_started:J.outputStarted});return}L(K.stderr,`[provider-stall:${J.phase}] ${J.durationMs}ms / ${J.timeoutMs}ms`)},actionStationarity(J){if(V==="jsonl"){q("action_stationarity",{phase:J.phase,tool_name:J.toolName,run_length:J.runLength,nudge_threshold:J.nudgeThreshold,halt_threshold:J.haltThreshold,progress_aware:J.progressAware});return}L(K.stderr,`[action-stationarity:${J.phase}] ${J.toolName} ${J.runLength}/${J.haltThreshold}`)},turnLimit(J){if(V==="jsonl"){q("turn_limit",{turns_count:J,action:"continue"});return}L(K.stderr,`[turn-limit] continuing after ${J} turns`)},taskSession(J){if(V==="jsonl"){q("task_session",{session_id:J.sessionId,project_path:J.projectPath,source_project_path:J.sourceProjectPath,isolation:J.isolation,worktree_branch:J.worktreeBranch,base_commit:J.baseCommit});return}L(K.stderr,`[task:${J.isolation}] ${J.sessionId} ${J.sourceProjectPath} -> ${J.projectPath}${J.worktreeBranch?` (${J.worktreeBranch})`:""}`)},taskAdmission(J){if(V==="jsonl"){q("task_admission",{state:J.state,queue_position:J.queuePosition,queue_depth:J.queueDepth,in_flight:J.inFlight,max_concurrent_tasks:J.maxConcurrentTasks});return}L(K.stderr,J.state==="queued"?`[task:queued] position ${J.queuePosition??1}/${J.queueDepth} (running ${J.inFlight}/${J.maxConcurrentTasks})`:`[task:running] admitted (running ${J.inFlight}/${J.maxConcurrentTasks})`)},output(J,Z=0){if(V==="jsonl"){q("output",{content:J,exit_code:Z});return}L(Z===0?K.stdout:K.stderr,J)},error(J){if(V==="jsonl"){q("error",{message:J});return}L(K.stderr,J)}}}async function cJ(K,V={stdout:process.stdout,stderr:process.stderr},Q){let q="text",J=new IH,Z={targetLocked:!1},W,x,j,G=TJ(Q),f=!1,F=new v(V,{signal:G.signal,onFailure:(Y)=>{f=!0,G.abort(Y)}}),w={stdout:{write:(Y)=>F.write("stdout",Y)},stderr:{write:(Y)=>F.write("stderr",Y)}},B=YH(w,q),m=async()=>{try{return await F.flush(),!f}catch{return!1}},y=async(Y)=>{return x?.(),x=void 0,j?.(),j=void 0,await m()?Y:1};try{let Y=gJ(K);q=wJ(Y.outputFormat);let S=await bH(Y);B=YH(w,q,Boolean(S)),await fH();let i=Y.forkSession!==!0&&(Y.continue===!0||typeof Y.resume==="string"&&Y.resume.length>0)?await SH({message:Y.message,_:Y._,stdin:Q?.stdin}):await yH({...Y,stdin:Q?.stdin}),R=i===void 0,P=R?{mode:"agent",content:""}:await TH(i);if(P.mode==="output"){if(P.content)B.output(P.content,P.exitCode??0);return await y(P.exitCode??0)}let C=P.content.trimStart().startsWith("!")?P.content.trimStart().slice(1).trim():void 0;if(C!==void 0&&Y.taskIsolation)throw Error("User shell commands cannot be combined with --task-isolation");if(C!==void 0&&S)throw Error("Output schemas cannot be combined with user shell commands");if(Y.taskIsolation&&(Y.continue||Y.resume||Y.forkSession))throw Error("--task-isolation cannot be combined with --continue, --resume, or --fork-session");let{sessionId:_,messages:o,metadata:r}=await RH({sessionId:Y.sessionId,continue:Y.continue,resume:Y.resume,forkSession:Y.forkSession,fallbackSessionPrefix:"headless"}),I=Y.permissionMode??r?.permissionMode??"yolo",n=Y.model&&Y.model!=="inherit"?Y.model:QH()?.id,U=Y.taskIsolation?await MH.createSessionTask({sessionId:_,prompt:P.content,sourceProjectPath:g(),isolation:Y.taskIsolation,dispatch:{version:1,prompt:P.content,sourceProjectPath:g(),isolation:Y.taskIsolation,permissionMode:I,...n?{modelId:n}:{},...S?{outputSchema:S}:{}}}):void 0,E=U?.metadata.projectPath??r?.projectPath??g();if(j=s.subscribe((X)=>{if(X.type!=="subagent.provider.admission"||X.sessionId!==_||X.projectPath!==E)return;let $=X.properties,z=["queued","admitted","rejected"],A=["foreground","background","internal"],M=["stream","pending_count","pending_bytes"],b=["global","domain","owner","class"],wH=["capacity","queue_full","wait_timeout","closed"];if(!z.includes($.phase)||!A.includes($.requestClass)||!M.includes($.resource)||!b.includes($.scope)||$.reason!==void 0&&!wH.includes($.reason)||typeof $.queuePosition!=="number"||typeof $.queueDepth!=="number"||typeof $.inFlight!=="number"||typeof $.limit!=="number"||typeof $.waitMs!=="number"||typeof $.maxWaitMs!=="number"||$.recoveryRemainingMs!==void 0&&typeof $.recoveryRemainingMs!=="number")return;B.providerAdmission({kind:"provider_admission",phase:$.phase,requestClass:$.requestClass,resource:$.resource,scope:$.scope,...$.reason!==void 0?{reason:$.reason}:{},queuePosition:$.queuePosition,queueDepth:$.queueDepth,inFlight:$.inFlight,limit:$.limit,waitMs:$.waitMs,maxWaitMs:$.maxWaitMs,...$.recoveryRemainingMs!==void 0?{recoveryRemainingMs:$.recoveryRemainingMs}:{}})}),!U)await a.setSessionPermissionMode(_,E,I);let gH=U?!1:await jH.cancelPendingNonInteractive(E,_);if(U)B.taskSession({sessionId:_,projectPath:E,sourceProjectPath:U.metadata.taskSourceProjectPath??g(),isolation:Y.taskIsolation,worktreeBranch:U.metadata.taskWorktreeBranch,baseCommit:U.metadata.taskBaseCommit}),x=s.subscribe((X)=>{if(X.type!=="task.status"||X.sessionId!==_||X.projectPath!==E||!["queued","running"].includes(String(X.properties.taskStatus))||typeof X.properties.taskQueueDepth!=="number"||typeof X.properties.taskInFlight!=="number"||typeof X.properties.taskConcurrencyLimit!=="number")return;B.taskAdmission({state:X.properties.taskStatus,queuePosition:typeof X.properties.taskQueuePosition==="number"?X.properties.taskQueuePosition:void 0,queueDepth:X.properties.taskQueueDepth,inFlight:X.properties.taskInFlight,maxConcurrentTasks:X.properties.taskConcurrencyLimit})});let CH={messages:gH?await a.loadSessionModelContext(_,E):[...o],userId:"cli-user",sessionId:_,workspaceRoot:E,permissionMode:I,signal:G.signal,...U?.taskWorktree?{worktreeActive:!0}:{},confirmationHandler:hJ()};W=await xH.create({sessionId:_,workspaceRoot:E,modelId:Y.model,permissionMode:I,mcpConfig:Y.mcpConfig,strictMcpConfig:Y.strictMcpConfig,agents:Y.agents?PH(Y.agents):void 0,...U?.taskWorktree?{taskWorktree:U.taskWorktree}:{},...U?.metadata.taskIsolation?{taskIsolation:U.metadata.taskIsolation}:{},...o.length>0?{sessionStart:{isResume:!0,resumeSessionId:_}}:{}});let k=R&&W.getPendingSteeringCount()>0,h=R&&!k?await W.getGoal():null,c=h?.status==="active"||h?.status==="verifying",T=R&&!k&&!c?await W.getRecoveredFinalResponse():void 0;if(R&&!k&&!c){if(!T)throw Error("No unfinished turn or active goal to resume");if(h)B.goal({kind:"goal_updated",goal:h});if(T.structuredOutput&&T.structuredOutputSchemaDigest)B.structuredOutput({kind:"structured_output",output:T.structuredOutput,schemaDigest:T.structuredOutputSchemaDigest});else B.content(T.content);return B.phase("completed","done","Recovered headless run completed"),await y(0)}if(C!==void 0){let X=await W.executeUserShellCommand(C,{signal:G.signal,onEvent:async($)=>{if($.type==="started")B.userShellStarted($.executionId,$.command,$.auxiliary);else if($.type==="output")B.userShellOutput($.executionId,$.stream,$.chunk,$.streamTruncated);await m()}});return B.userShellCompleted(X),await y(X.record.status==="completed"?0:X.record.status==="aborted"?130:X.record.exitCode??1)}let kH=Y.maxTurns??W.getConfig().maxTurns,hH=U?.taskWorktree?[...new Set([...Y.disallowedTools??[],"EnterWorktree","ExitWorktree"])]:Y.disallowedTools,OH=await GH.createWithRuntime(W,{sessionId:_,systemPrompt:Y.systemPrompt,appendSystemPrompt:Y.appendSystemPrompt,maxTurns:Y.maxTurns,modelId:Y.model,permissionMode:I,toolWhitelist:Y.allowedTools,toolBlacklist:hH,mcpConfig:Y.mcpConfig,strictMcpConfig:Y.strictMcpConfig}),u=await WH(OH.chatStream(P.content,CH,{stream:!0,signal:G.signal,maxTurns:Y.maxTurns,builtinVerification:Y.verificationAgent!==!1,outputSchema:S,pendingInputOnly:k,goalContinuationOnly:c,...kH===-1?{onTurnLimitReached:async(X)=>{return B.turnLimit(X.turnsCount),{continue:!0,reason:"headless-auto-continue"}}}:{}}),async(X)=>{switch(X.kind){case"content_delta":if(!S||q==="jsonl")J.markAssistantContent();B.contentDelta(X.delta);break;case"thinking_delta":J.setThinkingOpened(B.thinkingDelta(X.delta,J.hasOpenThinking()));break;case"stream_end":{let $=J.completeStream();B.streamEnd($.wroteAssistantContent,$.openedThinking);break}case"tool_start":{let $=X.toolCall;if(!("function"in $))break;if($.function.name===O)break;if(["TaskCreate","TaskUpdate","TaskList"].includes($.function.name))break;try{let z=JSON.parse($.function.arguments),A=UH($.function.name,z),M=XH($.function.name,z),b=mJ($.function.name,A,M,Z);if(b.shouldLockTarget)Z.targetLocked=!0;B.phase(b.phase,b.status,b.message,{toolName:$.function.name,target:M}),B.toolStart($.function.name,A,M,X.toolKind)}catch{B.phase(Z.targetLocked?"executing":"searching",Z.targetLocked?"hit":"ongoing",Z.targetLocked?`Working within target: ${$.function.name}`:`Still searching: ${$.function.name}`,{toolName:$.function.name}),B.toolStart($.function.name,$.function.name,void 0,X.toolKind)}break}case"tool_progress":{let $=X.toolCall;if(!("function"in $))break;if($.function.name===O)break;B.toolProgress($.function.name,X.update.message,X.update.progress,X.update.total,X.update.admission);break}case"tool_result":{let $=X.toolCall;if(!("function"in $))break;if($.function.name===O)break;let z;try{let M=JSON.parse($.function.arguments);z=XH($.function.name,M)}catch{z=void 0}let A=LH(_H($.function.name,X.result),DH);if(B.toolResult($.function.name,A.summary,z,void 0,{success:X.result.success,errorType:X.result.error?.type,errorMessage:X.result.error?.message,background:SJ(X.result.metadata)}),A.detail)B.toolDetail($.function.name,A.detail);break}case"token_usage":B.tokenUsage(X.usage);break;case"compaction":B.compacting(X);break;case"task_update":B.taskUpdate(X.tasks);break;case"structured_output":B.structuredOutput(X);break;case"mcp_catalog_changed":B.mcpCatalogChanged(X);break;case"mcp_content_changed":B.mcpContentChanged(X);break;case"mcp_resource_updated":B.mcpResourceUpdated(X);break;case"mcp_connection_changed":B.mcpConnectionChanged(X);break;case"mcp_log":B.mcpLog(X);break;case"mcp_instructions_changed":B.mcpInstructionsChanged(X);break;case"mcp_task_changed":B.mcpTaskChanged(X);break;case"project_rules_loaded":B.projectRulesLoaded(X);break;case"steering_applied":case"follow_up_started":case"goal_continuation_started":break;case"goal_updated":B.goal(X);break;case"subagent_spawned":case"subagent_completed":B.subagent(X);break;case"model_fallback":break;case"provider_admission":B.providerAdmission(X);break;case"provider_retry":B.providerRetry(X);break;case"provider_circuit":B.providerCircuit(X);break;case"provider_stall":B.providerStall(X);break;case"action_stationarity":B.actionStationarity(X);break;case"turn_start":if(X.turn===1)Z.targetLocked=!1;B.phase("turn",Z.targetLocked?"hit":"ongoing",`Turn ${X.turn} started`,{turn:X.turn});break;default:{let $=X}}await m()});if(u.metadata?.outputTruncated)B.error("[warning] 输出因达到 token 上限被截断,部分内容可能不完整。");if(!u.success)return B.error(`Error: ${u.error?.message??"Agent execution failed"}`),await y(1);return B.phase("completed","done","Headless run completed"),await y(0)}catch(Y){if(!f){if(J.hasOpenThinking()&&q==="text")w.stderr.write(`
6
+ `);B.error(`Error: ${OJ(Y)}`)}return await y(1)}finally{x?.(),j?.();try{await W?.dispose()}finally{F.close(),G.dispose()}}}async function PK(){if(!process.argv.slice(2).includes("--headless"))return!1;let{headless:Q,"output-format":q,"system-prompt":J,"append-system-prompt":Z,"max-turns":W,...x}=FH,j=fJ(yJ(process.argv)).scriptName("blade").strict(!1).options(x).middleware([zH,EH,AH]);return CJ(j),await j.parse(),!0}export{cJ as runHeadless,PK as handleHeadlessMode,RJ as HeadlessOptionsSchema};
@@ -0,0 +1,2 @@
1
+ var _=20,T=5242880,A=32000;
2
+ export{_ as Ig,T as Jg,A as Kg};
@@ -0,0 +1 @@
1
+ import{qe as a,re as b,se as c}from"./chunk-33bpwkyk.js";import"./chunk-mygw13zd.js";import"./chunk-5nezhmnq.js";import"./chunk-h6a0nct6.js";import"./chunk-0ra945vt.js";import"./chunk-h0fh3j9w.js";export{b as resolveModelConfig,c as getModelDisplayName,a as getModelApiKeyEnvironmentVariable};