blade-code 0.10.32 → 0.10.33

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 (102) hide show
  1. package/dist/blade.js +2 -2
  2. package/dist/chunk-08fww0yh.js +1 -0
  3. package/dist/{chunk-qgvgd1kq.js → chunk-0k0k5qjr.js} +2 -2
  4. package/dist/{chunk-fb514tmd.js → chunk-189drzww.js} +1 -1
  5. package/dist/{chunk-cjgnf6qy.js → chunk-20qedxrp.js} +1 -1
  6. package/dist/{chunk-jtk2t4wy.js → chunk-23bhwgwm.js} +19 -19
  7. package/dist/{chunk-7xytd1h7.js → chunk-23bkpq26.js} +2 -2
  8. package/dist/chunk-25j7tjr6.js +1 -0
  9. package/dist/{chunk-7fgx7ztz.js → chunk-2rsr3bte.js} +1 -1
  10. package/dist/chunk-2s24zvjm.js +22 -0
  11. package/dist/{chunk-tx77qaz8.js → chunk-3j57nm6f.js} +2 -2
  12. package/dist/{chunk-cdkrdsbw.js → chunk-3r0yfspg.js} +1 -1
  13. package/dist/{chunk-y5rsamex.js → chunk-40654rh3.js} +2 -2
  14. package/dist/{chunk-x0x5e65d.js → chunk-4kratdhc.js} +1 -1
  15. package/dist/{chunk-b0mha3tr.js → chunk-5fm0qywg.js} +2 -2
  16. package/dist/chunk-5hn788xk.js +2 -0
  17. package/dist/{chunk-fp1892aa.js → chunk-6b2w2132.js} +1 -1
  18. package/dist/{chunk-2tb3qm3v.js → chunk-6bqd2hkz.js} +1 -1
  19. package/dist/chunk-74js4dnw.js +1 -0
  20. package/dist/chunk-7dt49b6q.js +8 -0
  21. package/dist/chunk-7ncx3vzw.js +1 -0
  22. package/dist/{chunk-8y2nh9sm.js → chunk-8vxxmdhd.js} +1 -1
  23. package/dist/{chunk-ntmfefxh.js → chunk-91sne4g4.js} +2 -2
  24. package/dist/{chunk-azcjz03h.js → chunk-91vwv4ph.js} +2 -2
  25. package/dist/{chunk-b0en9trj.js → chunk-97mzk53w.js} +1 -1
  26. package/dist/chunk-9c4fvem6.js +1 -0
  27. package/dist/chunk-9qj6y0sj.js +2 -0
  28. package/dist/chunk-agw7bq0h.js +1 -0
  29. package/dist/{chunk-75y3mb0z.js → chunk-amm23yvd.js} +2 -2
  30. package/dist/chunk-bhj7dqe8.js +1 -0
  31. package/dist/{chunk-799zdv81.js → chunk-bvnxztsj.js} +1 -1
  32. package/dist/{chunk-7bpwnpfx.js → chunk-ctn675zn.js} +2 -2
  33. package/dist/{chunk-aspqajv2.js → chunk-d3h8cgs8.js} +1 -1
  34. package/dist/chunk-dkz757cv.js +1 -0
  35. package/dist/{chunk-q4q0r97b.js → chunk-f20mb84y.js} +2 -2
  36. package/dist/{chunk-z1qa6vm5.js → chunk-f5yx8s8t.js} +1 -1
  37. package/dist/{chunk-6gngfvwt.js → chunk-f9graf2n.js} +1 -1
  38. package/dist/{chunk-3bhh4v42.js → chunk-g2yj0chw.js} +1 -1
  39. package/dist/chunk-gmpgmh7s.js +1 -0
  40. package/dist/{chunk-2jr254j7.js → chunk-gw51xyz9.js} +2 -2
  41. package/dist/{chunk-r68y2q62.js → chunk-h9v4tzdt.js} +2 -2
  42. package/dist/{chunk-rakyf5b7.js → chunk-hs3yryjm.js} +2 -2
  43. package/dist/{chunk-mwae107k.js → chunk-k05xt45s.js} +1 -1
  44. package/dist/{chunk-nah8b1gv.js → chunk-k9px24b5.js} +1 -1
  45. package/dist/{chunk-g2gvcp09.js → chunk-kqe9y6ka.js} +1 -1
  46. package/dist/{chunk-t23t9yff.js → chunk-m06gcr4k.js} +1 -1
  47. package/dist/chunk-m6srq209.js +1 -0
  48. package/dist/{chunk-b4xcn24b.js → chunk-mdrdafpa.js} +1 -1
  49. package/dist/{chunk-bmsv08sa.js → chunk-mt3nrz7x.js} +2 -2
  50. package/dist/{chunk-7m4qc5vv.js → chunk-mxyb9hn6.js} +1 -1
  51. package/dist/chunk-np2vrjpc.js +10 -0
  52. package/dist/{chunk-3ck3fxff.js → chunk-qj6gafse.js} +1 -1
  53. package/dist/{chunk-wmsak7d3.js → chunk-sfvt4ef0.js} +5 -5
  54. package/dist/{chunk-14zhd8qs.js → chunk-tzragyzm.js} +1 -1
  55. package/dist/{chunk-774excyf.js → chunk-vm0w0jt9.js} +1 -1
  56. package/dist/{chunk-s61wcay9.js → chunk-vp7n0w9w.js} +2 -2
  57. package/dist/{chunk-xhdm1b4g.js → chunk-vybzvxf9.js} +1 -1
  58. package/dist/{chunk-xh1y705a.js → chunk-vzf17snk.js} +2 -2
  59. package/dist/{chunk-5mszemkz.js → chunk-w45ngpy1.js} +2 -2
  60. package/dist/chunk-wgnzghhc.js +6 -0
  61. package/dist/{chunk-yekzckgm.js → chunk-wzjhwr2p.js} +3 -3
  62. package/dist/chunk-xfpne7cm.js +1 -0
  63. package/dist/{chunk-e66zyvph.js → chunk-y1bb5391.js} +1 -1
  64. package/dist/chunk-ycvwc7hb.js +1 -0
  65. package/dist/{chunk-80r40y6k.js → chunk-z2k6q0k1.js} +2 -2
  66. package/dist/chunk-z7s2138c.js +1 -0
  67. package/dist/chunk-zfezz6ew.js +1 -0
  68. package/dist/{chunk-c7b5wmpm.js → chunk-zftb9s2h.js} +2 -2
  69. package/dist/{chunk-bcs58pet.js → chunk-zhbpatxr.js} +1 -1
  70. package/dist/{chunk-6r89cn2n.js → chunk-ztyt12kf.js} +2 -2
  71. package/dist/{chunk-w49crtzx.js → chunk-zvjvbhc4.js} +2 -2
  72. package/dist/web/assets/{ChatView-D2g5ADlO.js → ChatView-B7_Um8KR.js} +2 -2
  73. package/dist/web/assets/{CodeBlockHighlighter-CheLBzlr.js → CodeBlockHighlighter-JzE91vkT.js} +1 -1
  74. package/dist/web/assets/{FilePreview-DWiuoQOM.js → FilePreview-BTbtoUBJ.js} +1 -1
  75. package/dist/web/assets/{MarkdownRenderer-C8h_WRI9.js → MarkdownRenderer-IaPtOh2w.js} +3 -3
  76. package/dist/web/assets/{SettingsModal-CKIKFL6a.js → SettingsModal-CPgWPfZ2.js} +1 -1
  77. package/dist/web/assets/{TaskSwitcher-DMaOLa_m.js → TaskSwitcher-D4RZxQKp.js} +1 -1
  78. package/dist/web/assets/{TerminalPanel-BXLKU2zU.js → TerminalPanel-yWbQfbYa.js} +1 -1
  79. package/dist/web/assets/{index-CxwsVMYL.js → index-BnCT8SxR.js} +8 -8
  80. package/dist/web/assets/{session-events-BZdQ71sF.js → session-events-BZao_jMQ.js} +20 -20
  81. package/dist/web/index.html +2 -2
  82. package/package.json +1 -1
  83. package/dist/chunk-191xtaca.js +0 -1
  84. package/dist/chunk-273ak5v8.js +0 -10
  85. package/dist/chunk-2969c7yb.js +0 -22
  86. package/dist/chunk-42ns4a92.js +0 -1
  87. package/dist/chunk-758hxypj.js +0 -2
  88. package/dist/chunk-9r0fxre0.js +0 -1
  89. package/dist/chunk-fd5dzcht.js +0 -1
  90. package/dist/chunk-gs18nx4h.js +0 -1
  91. package/dist/chunk-gy51z423.js +0 -1
  92. package/dist/chunk-hdje6ywy.js +0 -1
  93. package/dist/chunk-jdq05trf.js +0 -3
  94. package/dist/chunk-mspp2qpn.js +0 -1
  95. package/dist/chunk-qe49h8e0.js +0 -6
  96. package/dist/chunk-rzxk60wq.js +0 -1
  97. package/dist/chunk-sfhevsq1.js +0 -1
  98. package/dist/chunk-t23a5yvk.js +0 -1
  99. package/dist/chunk-txqctnca.js +0 -1
  100. package/dist/chunk-w0wzx47n.js +0 -1
  101. package/dist/chunk-x1r4b7pt.js +0 -2
  102. package/dist/chunk-yvwmfddz.js +0 -1
@@ -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 qf,f as rf,l as sf,x as tf,b as uf,V as vf};
2
+ export{a as vf,f as wf,l as xf,x as yf,b as zf,V as Af};
@@ -1,4 +1,4 @@
1
- import{da as M,ea as p0,ja as VJ,ka as o8,la as u0}from"./chunk-7bpwnpfx.js";import{Fa as aJ,ma as nJ,oa as rJ,pa as A4}from"./chunk-6r89cn2n.js";import{Ga as F$,Ha as w2,Ia as v8,Ja as N1,Ka as T9,Oa as V0,Qa as M2,Ra as x8,Sa as h8,Ta as u8,Wa as u2,Ya as C6,Za as d2,_a as m2,bb as s0,hb as J5,ib as s7,jb as N7,pb as V9,sb as z9}from"./chunk-jtk2t4wy.js";import{$b as e$,Ab as R$,Bb as o1,Cb as k4,Db as x2,Eb as h2,Ob as t2,Pb as F0,Qb as n0,Zb as v4,_b as O1,ac as y7,bc as x7,ec as YJ,ic as H9,nc as h7,oc as u7,qc as n,yb as B0,zb as B1}from"./chunk-ntmfefxh.js";import{rc as R9,sc as k9,tc as j2}from"./chunk-fp1892aa.js";import{Fc as eJ,Lc as $3,uc as tJ,xc as sJ}from"./chunk-s61wcay9.js";import{Wc as NZ,Xc as DZ}from"./chunk-r68y2q62.js";import{hd as g2,id as G0,jd as S,md as O0,nd as f2,od as Z1,pd as D$,qd as u6,rd as v$,sd as Q9,xd as t$}from"./chunk-tx77qaz8.js";import{yd as Q$}from"./chunk-xhdm1b4g.js";import{Ed as i7,Fd as C2}from"./chunk-5mszemkz.js";import{Hd as C0,Id as f$}from"./chunk-c7b5wmpm.js";import{Jd as $J}from"./chunk-e66zyvph.js";import{Ld as k7,Md as P7,Nd as S7}from"./chunk-bmsv08sa.js";import{$d as s2,Od as S2,Pd as I2,Rd as v2,Sd as y2,Td as j$,Ud as y9,Wd as v0,Xd as z3,Yd as x0,Zd as c0,_d as A5,ae as J$,be as l$,ce as n$,de as v7,ee as Y4,ge as X0,he as R2,ie as m7}from"./chunk-80r40y6k.js";import{ke as J1,me as t0,ne as q2}from"./chunk-t23t9yff.js";import{oe as wJ,qe as I7,re as o2,se as bZ}from"./chunk-fb514tmd.js";import{ue as q4,we as b0}from"./chunk-yekzckgm.js";import{Ae as r$,xe as g1,ye as R4,ze as p1}from"./chunk-799zdv81.js";import{Ce as QZ,He as HZ,Je as G4,Oe as HJ,Se as VZ,Ue as M7,We as S8,Xe as I8,bf as m$,df as o4,ff as g7,gf as R7,hf as s8,if as e8,jf as $9,kf as Z9,lf as J9,mf as U9,nf as Y0}from"./chunk-xh1y705a.js";import{qf as Z2,rf as D5,sf as G,tf as x9,uf as k,vf as c}from"./chunk-3ck3fxff.js";import{xf as D7,yf as L7}from"./chunk-x1r4b7pt.js";import{Af as Q2,Cf as A}from"./chunk-7fgx7ztz.js";import{Gf as l}from"./chunk-75y3mb0z.js";import{Lf as f7,Mf as C7}from"./chunk-y5rsamex.js";import{Nf as LJ,Qf as EJ}from"./chunk-nah8b1gv.js";import{Uf as jJ}from"./chunk-azcjz03h.js";import{Zf as S0}from"./chunk-7xytd1h7.js";import{ag as a1,cg as u$,eg as T7,fg as c4,hg as D0}from"./chunk-q4q0r97b.js";import{jg as $$}from"./chunk-aspqajv2.js";import{randomUUID as b3}from"crypto";var K3=String.raw`
1
+ import{ia as M,ja as p0,oa as VJ,pa as o8,qa as u0}from"./chunk-ctn675zn.js";import{Ka as aJ,ra as nJ,ta as rJ,ua as A4}from"./chunk-ztyt12kf.js";import{$a as u2,La as F$,Ma as w2,Na as v8,Oa as N1,Pa as T9,Ta as V0,Va as M2,Wa as x8,Xa as h8,Ya as u8,bb as C6,cb as d2,db as m2,gb as s0,mb as J5,nb as s7,ob as N7,ub as V9,xb as z9}from"./chunk-23bhwgwm.js";import{Db as B0,Eb as B1,Fb as R$,Gb as o1,Hb as k4,Ib as x2,Jb as h2,Tb as t2,Ub as F0,Vb as n0,cc as v4,dc as O1,ec as e$,fc as y7,gc as x7,jc as YJ,nc as H9,sc as h7,tc as u7,vc as n}from"./chunk-91sne4g4.js";import{wc as R9,xc as k9,yc as j2}from"./chunk-6b2w2132.js";import{Cc as sJ,Kc as eJ,Qc as $3,zc as tJ}from"./chunk-vp7n0w9w.js";import{$c as NZ,ad as DZ}from"./chunk-h9v4tzdt.js";import{Cd as t$,md as g2,nd as G0,od as S,rd as O0,sd as f2,td as Z1,ud as D$,vd as u6,wd as v$,xd as Q9}from"./chunk-3j57nm6f.js";import{Dd as Q$}from"./chunk-vybzvxf9.js";import{Jd as i7,Kd as C2}from"./chunk-w45ngpy1.js";import{Md as C0,Nd as f$}from"./chunk-zftb9s2h.js";import{Od as $J}from"./chunk-y1bb5391.js";import{Qd as k7,Rd as P7,Sd as S7}from"./chunk-mt3nrz7x.js";import{$d as v0,Td as S2,Ud as I2,Wd as v2,Xd as y2,Yd as j$,Zd as y9,ae as z3,be as x0,ce as c0,de as A5,ee as s2,fe as J$,ge as l$,he as n$,ie as v7,je as Y4,le as X0,me as R2,ne as m7}from"./chunk-z2k6q0k1.js";import{pe as J1,re as t0,se as q2}from"./chunk-m06gcr4k.js";import{te as wJ,ve as I7,we as o2,xe as bZ}from"./chunk-189drzww.js";import{Be as b0,ze as q4}from"./chunk-wzjhwr2p.js";import{Ce as g1,De as R4,Ee as p1,Fe as r$}from"./chunk-bvnxztsj.js";import{$e as S8,He as QZ,Me as HZ,Oe as G4,Te as HJ,Xe as VZ,Ze as M7,af as I8,gf as m$,if as o4,kf as g7,lf as R7,mf as s8,nf as e8,of as $9,pf as Z9,qf as J9,rf as U9,sf as Y0}from"./chunk-vzf17snk.js";import{Af as c,vf as Z2,wf as D5,xf as G,yf as x9,zf as k}from"./chunk-qj6gafse.js";import{Cf as D7,Df as L7}from"./chunk-5hn788xk.js";import{Ff as Q2,Hf as A}from"./chunk-2rsr3bte.js";import{Lf as l}from"./chunk-amm23yvd.js";import{Qf as f7,Rf as C7}from"./chunk-40654rh3.js";import{Sf as LJ,Vf as EJ}from"./chunk-k9px24b5.js";import{Zf as jJ}from"./chunk-91vwv4ph.js";import{cg as S0}from"./chunk-23bkpq26.js";import{fg as a1,hg as u$,jg as T7,kg as c4,mg as D0}from"./chunk-f20mb84y.js";import{og as $$}from"./chunk-d3h8cgs8.js";import{randomUUID as b3}from"crypto";var K3=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);
@@ -110,7 +110,7 @@ process.stdin.once('data', (chunk) => {
110
110
  });
111
111
  `;function c1($,Z,J,U={}){return r$(process.execPath,["-e",K3,String(process.pid),$,...Z],J,{releaseOnExit:!1,...U})}async function i1($){let Z=$.stdin;if(!Z||Z.destroyed||Z.writableEnded)throw Error("Command admission gate stdin is unavailable");await new Promise((J,U)=>{let Y=(X)=>{Z.off("error",Y),U(X)};Z.once("error",Y),Z.write(Buffer.from([1]),(X)=>{if(Z.off("error",Y),X)U(X);else J()})})}function G3($){try{return process.kill($,0),!0}catch(Z){return Z instanceof Error&&"code"in Z&&Z.code==="EPERM"}}async function l1($,Z){let J=$.pid;if(process.platform==="win32"||!J||!g1(J))return Z.release(),{success:!0,alreadyExited:!0,forced:!1};let U=await p1(J,{validatePidOwnership:()=>!G3(J)});if(U.success)Z.release();return U}import{createHash as O3}from"node:crypto";import*as k0 from"node:fs";import*as r1 from"node:path";import _3 from"write-file-atomic";var K5=1,F3=16384;function C4($){return O3("sha256").update($).digest("hex")}function n1($){try{return process.kill($,0),!0}catch(Z){return Z instanceof Error&&"code"in Z&&Z.code==="EPERM"}}class K1{sessionId;options;directory;constructor($,Z,J){this.sessionId=Z;this.options=J;this.directory=r1.join(a1($),J.directoryName,C4(Z))}register($,Z){let J=R$(Z),U=R$(process.pid);if(!J||!U)throw Error(`Unable to capture ${this.options.label} process identity`);let Y={version:K5,processId:$,sessionId:this.sessionId,ownerPid:process.pid,ownerIdentity:U,rootPid:Z,identity:J,startedAt:new Date().toISOString()},X={version:Y.version,[this.options.idField]:Y.processId,sessionId:Y.sessionId,ownerPid:Y.ownerPid,ownerIdentity:Y.ownerIdentity,rootPid:Y.rootPid,identity:Y.identity,startedAt:Y.startedAt};return k0.mkdirSync(this.directory,{recursive:!0,mode:448}),k0.chmodSync(this.directory,448),_3.sync(this.filePath($),`${JSON.stringify(X)}
112
112
  `,{encoding:"utf8",mode:384,fsync:!0}),Y}remove($){k0.rmSync(this.filePath($),{force:!0})}async reapOrphans(){let $=0,Z=0,J=0,U=0;for(let Y of this.readAll()){if(n1(Y.ownerPid)&&o1(Y.ownerPid,Y.ownerIdentity)){J++;continue}if(!n1(Y.rootPid)){if(process.platform!=="win32"&&g1(Y.rootPid)){let Q=await p1(Y.rootPid,{validatePidOwnership:()=>!n1(Y.rootPid)});if(n1(Y.rootPid)){U++;continue}if(!Q.success)throw Error(`Failed to reap leaderless ${this.options.label} ${Y.processId}`);$++}else Z++;this.remove(Y.processId);continue}let X=()=>k4(Y.rootPid,Y.identity);if(!X()){U++;continue}if(!(await R4(Y.rootPid,{validatePidOwnership:X})).success)throw Error(`Failed to reap ${this.options.label} ${Y.processId}`);$++,this.remove(Y.processId)}return{reaped:$,stale:Z,active:J,protected:U}}readAll(){let $;try{$=k0.readdirSync(this.directory)}catch(J){if(J.code==="ENOENT")return[];throw Error(`Unable to read durable ${this.options.label} leases`)}let Z=[];for(let J of $){if(!J.endsWith(".json"))continue;try{let U=r1.join(this.directory,J);if(k0.statSync(U).size>F3)throw Error("lease exceeds size limit");let Y=JSON.parse(k0.readFileSync(U,"utf8")),X=this.normalizeLease(Y);if(!X)throw Error("lease schema is invalid");Z.push(X)}catch{throw Error(`Invalid durable ${this.options.label} lease: ${J}`)}}return Z}normalizeLease($){if(!$||typeof $!=="object")return;let Z=$,J=new Set(["version",this.options.idField,"sessionId","ownerPid","ownerIdentity","rootPid","identity","startedAt"]),U=Z[this.options.idField];if(Object.keys(Z).some((Y)=>!J.has(Y))||Z.version!==K5||Z.sessionId!==this.sessionId||typeof U!=="string"||!U.startsWith(this.options.idPrefix)||U.length>128||!Number.isSafeInteger(Z.ownerPid)||Number(Z.ownerPid)<=1||!B1(Z.ownerIdentity)||!Number.isSafeInteger(Z.rootPid)||Number(Z.rootPid)<=1||!B1(Z.identity)||typeof Z.startedAt!=="string"||!Number.isFinite(Date.parse(Z.startedAt)))return;return{version:K5,processId:U,sessionId:this.sessionId,ownerPid:Number(Z.ownerPid),ownerIdentity:Z.ownerIdentity,rootPid:Number(Z.rootPid),identity:Z.identity,startedAt:Z.startedAt}}filePath($){return r1.join(this.directory,`${C4($)}.json`)}}class t1{store;constructor($,Z){this.store=new K1($,Z,{directoryName:".background-shells",idField:"shellId",idPrefix:"bash_",label:"background shell"})}register($,Z){let J=this.store.register($,Z);return{version:J.version,shellId:$,sessionId:J.sessionId,ownerPid:J.ownerPid,ownerIdentity:J.ownerIdentity,rootPid:J.rootPid,identity:J.identity,startedAt:J.startedAt}}remove($){this.store.remove($)}reapOrphans(){return this.store.reapOrphans()}}import{mkdir as s1,realpath as _5}from"node:fs/promises";import E3 from"node:os";import B$ from"node:path";import{Mutex as q3}from"async-mutex";var P4=new q3,K$,G5;function w3(){return import("@anthropic-ai/sandbox-runtime")}async function G1(){if(K$)return K$;if(!G5)G5=w3();return K$=await G5,K$}var D3={isSupportedPlatform:async()=>(await G1()).SandboxManager.isSupportedPlatform(),checkDependencies:async()=>(await G1()).SandboxManager.checkDependencies(),getDefaultWritePaths:async()=>(await G1()).getDefaultWritePaths(),initialize:async($)=>(await G1()).SandboxManager.initialize($),updateConfig:($)=>{if(!K$)throw Error("Sandbox runtime is not initialized");K$.SandboxManager.updateConfig($)},wrapWithSandboxArgv:async($,Z,J,U,Y)=>(await G1()).SandboxManager.wrapWithSandboxArgv($,Z,J,U,Y),cleanupAfterCommand:()=>K$?.SandboxManager.cleanupAfterCommand(),reset:async()=>{await K$?.SandboxManager.reset()}};function O5($){return{network:{allowedDomains:$,deniedDomains:[],strictAllowlist:!0},filesystem:{denyRead:[],allowRead:[],allowWrite:[],denyWrite:[]},enableWeakerNestedSandbox:!0}}class k$ extends Error{constructor($){super($);this.name="WorkspaceSandboxUnavailableError"}}class a$ extends Error{constructor($){super($);this.name="WorkspaceSandboxBoundaryError"}}class S4{backend;constructor($){this.backend=$}async prepare($){let Z=B$.resolve($.workspaceRoot),J=B$.resolve($.cwd);if(!B0.isWithinWorkspace(J,Z))throw new a$(`Bash cwd is outside the workspace sandbox: ${$.cwd}`);let U,Y;try{[U,Y]=await Promise.all([_5(Z),_5(J)])}catch(X){throw new a$(`Workspace sandbox path cannot be resolved: ${X instanceof Error?X.message:String(X)}`)}if(!B0.isWithinWorkspace(Y,U))throw new a$(`Bash cwd resolves outside the workspace sandbox: ${$.cwd}`);return this.backend.prepare({...$,cwd:Y,workspaceRoot:U})}}class I4{runtime;tempRoot;defaultWritePaths;initialization;constructor($={}){this.runtime=$.runtime??D3,this.tempRoot=$.tempRoot??B$.join(D0(),"sandbox-tmp"),this.defaultWritePaths=$.defaultWritePaths}async prepare($){await this.ensureInitialized();let Z=await this.prepareTempRoot(),J=B$.join(Z,"tmp"),U=B$.join(Z,"cache"),Y=B$.join(U,"npm"),X=B$.join(U,"bun");await Promise.all([s1(J,{recursive:!0}),s1(Y,{recursive:!0}),s1(X,{recursive:!0})]);let Q=(this.defaultWritePaths??await this.runtime.getDefaultWritePaths()).filter((E)=>!E.startsWith("/dev/")),H=$.access==="workspace-read-only",V=H?[E3.homedir(),D0(),process.env.BLADE_REAL_API_CREDENTIALS_FILE].filter((E)=>typeof E==="string"&&E.trim().length>0).map((E)=>B$.resolve(E)).filter((E,w,q)=>q.indexOf(E)===w):[],z=process.platform==="win32"?"bash":"/bin/bash",B,K,O=()=>{if(!K)return;let E=K;K=void 0;try{this.runtime.updateConfig(O5(["*"]))}finally{E()}},F=async()=>{let E=process.env.CLAUDE_CODE_TMPDIR;process.env.CLAUDE_CODE_TMPDIR=J;try{return await this.runtime.wrapWithSandboxArgv($.command,z,{network:H?{allowedDomains:[],deniedDomains:[],strictAllowlist:!0}:{allowedDomains:["*"],deniedDomains:[],strictAllowlist:!0},filesystem:{denyRead:V,allowRead:H?[$.workspaceRoot]:[],allowWrite:H?[Z]:[$.workspaceRoot,Z],denyWrite:H?[$.workspaceRoot,...Q]:Q},git:{safeDirectories:[$.workspaceRoot]}},$.signal,$.cwd)}finally{if(E===void 0)delete process.env.CLAUDE_CODE_TMPDIR;else process.env.CLAUDE_CODE_TMPDIR=E}};try{if(H)K=await P4.acquire(),this.runtime.updateConfig(O5([])),B=await F();else B=await P4.runExclusive(F)}catch(E){if(O(),E instanceof Error&&E.name==="AbortError")throw E;throw new k$(`Workspace sandbox failed to prepare the command: ${E instanceof Error?E.message:String(E)}`)}let _=!1;return{executable:B.argv[0]??z,args:B.argv.slice(1),env:{...B.env,TMPDIR:J,TMP:J,TEMP:J,XDG_CACHE_HOME:U,npm_config_cache:Y,BUN_INSTALL_CACHE_DIR:X},sandboxed:!0,inheritProcessEnv:!H,cleanup:()=>{if(_)return;_=!0;try{this.runtime.cleanupAfterCommand()}finally{O()}}}}async dispose(){this.initialization=void 0,await this.runtime.reset()}async ensureInitialized(){if(!this.initialization)this.initialization=this.initializeRuntime().catch(($)=>{throw this.initialization=void 0,$});return this.initialization}async initializeRuntime(){if(!await this.runtime.isSupportedPlatform())throw new k$(`Workspace sandbox is unsupported on ${process.platform}`);let $=await this.runtime.checkDependencies();if($.errors.length>0)throw new k$(`Workspace sandbox dependencies are unavailable: ${$.errors.join("; ")}`);try{await this.runtime.initialize(O5(["*"]))}catch(Z){throw new k$(`Workspace sandbox failed to initialize: ${Z instanceof Error?Z.message:String(Z)}`)}}async prepareTempRoot(){return await s1(this.tempRoot,{recursive:!0}),_5(this.tempRoot)}}function e1($,Z){let J=Z.toLowerCase();return $===71&&J.includes("sandbox-exec")||J.includes("sandbox_apply: operation not permitted")||J.includes("bwrap: creating new namespace failed")||J.includes("failed to create new user namespace")||J.includes("srt-win sandbox failed")}var L3=new I4,N3={prepare:($)=>L3.prepare($)},F5=new S4(N3);class e{static instance=null;processes=new Map;static getInstance(){if(!e.instance)e.instance=new e;return e.instance}async startBackgroundProcess($){let Z=`bash_${b3()}`,J={};for(let[K,O]of Object.entries({...process.env,...$.env,...$.sandboxedCommand?.env,BLADE_CLI:"1"}))if(O!==void 0)J[K]=O;let U=$.sandboxedCommand?.executable??"bash",Y=$.sandboxedCommand?.args??["-c",$.command],{child:X,processTree:W}=c1(U,Y,{cwd:$.cwd||A(),env:J,stdio:["pipe","pipe","pipe"]});if(!X.pid)throw W.terminate(),Error("Background process did not expose a PID");let Q=new t1($.projectPath??$.cwd??A(),$.sessionId);try{Q.register(Z,X.pid)}catch(K){let O=!0;try{process.kill(X.pid,0)}catch(F){O=F instanceof Error&&"code"in F&&F.code==="EPERM"}if(O)throw X.kill("SIGKILL"),W.terminate(),$.sandboxedCommand?.cleanup(),K}let H={id:Z,command:$.command,sessionId:$.sessionId,cwd:$.cwd,env:$.env,process:X,processTree:W,pid:X.pid,status:"running",startTime:Date.now(),pendingStdout:new O1,pendingStderr:new O1,sandboxed:Boolean($.sandboxedCommand),leaseStore:Q};X.stdout?.on("data",(K)=>{H.pendingStdout.append(K)}),X.stderr?.on("data",(K)=>{H.pendingStderr.append(K)});let V=!1,z,B=()=>{return z??=l1(X,W).then((K)=>{if(K.success)return H.leaseStore?.remove(H.id),!0;return!1}).catch(()=>!1),z};X.on("close",(K,O)=>{(async()=>{let F=await B();if(V)return;V=!0,$.sandboxedCommand?.cleanup();let _=H.sandboxed&&e1(K,H.pendingStderr.peek().content);if(H.status=H.status==="killed"?"killed":_||!F?"error":"exited",H.exitCode=K,H.signal=O,_)H.errorMessage="Workspace sandbox failed to start; command was not executed";else if(!F)H.errorMessage="Background command process group could not be finalized";H.endTime=Date.now(),H.process=void 0})()}),X.on("error",(K)=>{(async()=>{let O=await B();if(V)return;V=!0,$.sandboxedCommand?.cleanup(),H.status="error",H.errorMessage=O?K.message:"Background command process group could not be finalized",H.endTime=Date.now(),H.process=void 0,H.pendingStderr.append(`
113
- [error] ${K.message}`)})()}),this.processes.set(Z,H);try{await i1(X)}catch(K){throw H.status="killed",H.endTime=Date.now(),await W.terminate(),H.leaseStore?.remove(H.id),this.processes.delete(Z),Error("Failed to release durable background command gate",{cause:K})}return H}consumeOutput($,Z){let J=this.getProcess($,Z);if(!J)return;let U=J.pendingStdout.consume(),Y=J.pendingStderr.consume();return{id:J.id,command:J.command,status:J.status,stdout:U.content,stderr:Y.content,stdoutOmittedBytes:U.omittedBytes,stderrOmittedBytes:Y.omittedBytes,stdoutTotalBytes:U.totalBytes,stderrTotalBytes:Y.totalBytes,exitCode:J.exitCode,signal:J.signal,pid:J.pid,startedAt:J.startTime,endedAt:J.endTime,errorMessage:J.errorMessage,sandboxed:J.sandboxed}}getProcess($,Z){let J=this.processes.get($);return J?.sessionId===Z?J:void 0}listForSession($){return Array.from(this.processes.values()).filter((Z)=>Z.sessionId===$)}async writeInput($,Z,J,U=!1){let Y=this.getProcess($,Z);if(!Y)return;let X=Y.process?.stdin;if(Y.status!=="running"||!X||X.destroyed||X.writableEnded)return{success:!1,status:Y.status,bytesWritten:0,stdinClosed:!X||X.destroyed||X.writableEnded,errorMessage:"Shell stdin is not writable"};try{return await new Promise((W,Q)=>{let H=(z)=>{X.off("error",H),Q(z)},V=(z)=>{if(X.off("error",H),z)Q(z);else W()};if(X.once("error",H),U)X.end(J,V);else X.write(J,V)}),{success:!0,status:Y.status,bytesWritten:Buffer.byteLength(J),stdinClosed:U}}catch(W){return{success:!1,status:Y.status,bytesWritten:0,stdinClosed:X.destroyed||X.writableEnded,errorMessage:W instanceof Error?W.message:"Failed to write stdin"}}}async kill($,Z){let J=this.getProcess($,Z);if(!J)return;return this.terminateProcess(J)}async killSession($){let Z=this.listForSession($);await Promise.all(Z.map((J)=>this.terminateProcess(J)));for(let J of Z)this.processes.delete(J.id)}reapOrphanedSession($,Z){return new t1(Z,$).reapOrphans()}async terminateProcess($){if($.status!=="running"||!$.process)return{success:!1,alreadyExited:!0,status:$.status,pid:$.pid,exitCode:$.exitCode,signal:$.signal};$.status="killed",$.endTime=Date.now();let Z=await $.processTree?.terminate();if(!Z?.success)return $.status="error",$.errorMessage="Failed to terminate owned process tree",{success:!1,alreadyExited:Z?.alreadyExited??!1,status:$.status,pid:$.pid,exitCode:$.exitCode,signal:$.signal};return $.leaseStore?.remove($.id),{success:!0,alreadyExited:Z.alreadyExited,status:$.status,pid:$.pid,exitCode:$.exitCode,signal:$.signal}}async killAll(){await Promise.all(Array.from(this.processes.values()).map(($)=>this.terminateProcess($))),this.processes.clear()}}import{stat as dQ}from"node:fs/promises";import{Mutex as b7}from"async-mutex";import{nanoid as mQ}from"nanoid";import*as d7 from"os";import*as z0 from"path";import{randomUUID as A3}from"node:crypto";class P${store;constructor($,Z){this.store=new K1($,Z,{directoryName:".foreground-processes",idField:"processId",idPrefix:"foreground_",label:"foreground process"})}register($,Z){this.store.register($,Z)}remove($){this.store.remove($)}reapOrphans(){return this.store.reapOrphans()}}async function $2($,Z,J,U){let Y=`foreground_${A3()}`,{child:X,processTree:W}=c1($,Z,J);if(!X.pid)throw await W.terminate(),Error("Foreground command gate did not expose a PID");let Q=U?new P$(U.projectPath,U.sessionId):void 0;try{Q?.register(Y,X.pid)}catch(z){throw await W.terminate(),z}let H,V;return{child:X,processTree:W,processId:Y,release(){return H??=i1(X).catch((z)=>{throw W.terminate(),Error("Failed to release durable foreground command gate",{cause:z})}),H},finalize(){return V??=(async()=>{if(!(await l1(X,W)).success)throw Error("Failed to finalize foreground command process group");Q?.remove(Y)})(),V}}}import*as d0 from"fs/promises";class S${async readTextFile($){return d0.readFile($,"utf-8")}async writeTextFile($,Z){await d0.writeFile($,Z,"utf-8")}async exists($){try{return await d0.access($),!0}catch{return!1}}async readBinaryFile($){return d0.readFile($)}async stat($){try{let Z=await d0.stat($);return{size:Z.size,isDirectory:Z.isDirectory(),isFile:Z.isFile(),mtime:Z.mtime}}catch{return null}}async mkdir($,Z){await d0.mkdir($,{recursive:Z?.recursive??!1,mode:Z?.mode??493})}}var j3=new S$;function G$(){return j3}import{StringDecoder as T3}from"node:string_decoder";class E5{buffer;decoder=new T3("utf8");totalChars=0;accountingComplete=!0;finished=!1;constructor($){this.buffer=new O1($)}append($){if(this.finished)return;let Z=typeof $==="string"?Buffer.from($):$;this.buffer.append(Z),this.totalChars+=this.decoder.write(Z).length}markAccountingIncomplete(){this.accountingComplete=!1}finish(){if(this.finished)return;this.totalChars+=this.decoder.end().length,this.finished=!0}snapshot(){let $=this.buffer.peek();return{content:$.content,totalBytes:$.totalBytes,retainedBytes:$.retainedBytes,omittedBytes:$.omittedBytes,totalChars:this.totalChars,accountingComplete:this.accountingComplete}}}class O${terminalOutputMerged;stdout;stderr;constructor($=v4,Z=!1){this.terminalOutputMerged=Z;this.stdout=new E5($),this.stderr=new E5($)}append($,Z){this.streamFor($).append(Z)}markAccountingIncomplete(){this.stdout.markAccountingIncomplete(),this.stderr.markAccountingIncomplete()}finish(){this.stdout.finish(),this.stderr.finish()}snapshot(){return{stdout:this.stdout.snapshot(),stderr:this.stderr.snapshot(),terminalOutputMerged:this.terminalOutputMerged}}streamFor($){return $==="stdout"?this.stdout:this.stderr}}var T0=l("Agent");class _1{connection;sessionId;capabilities;fallback;constructor($,Z,J,U=new S$){this.connection=$;this.sessionId=Z;this.capabilities=J;this.fallback=U}async readTextFile($){if(!this.capabilities.readTextFile)return T0.debug(`[AcpFileSystem] readTextFile fallback: ${$}`),this.fallback.readTextFile($);try{return T0.debug(`[AcpFileSystem] readTextFile via ACP: ${$}`),(await this.connection.readTextFile({path:$,sessionId:this.sessionId})).content}catch(Z){throw T0.warn(`[AcpFileSystem] readTextFile ACP failed: ${Z}`),Z}}async writeTextFile($,Z){if(!this.capabilities.writeTextFile)return T0.debug(`[AcpFileSystem] writeTextFile fallback: ${$}`),this.fallback.writeTextFile($,Z);try{T0.debug(`[AcpFileSystem] writeTextFile via ACP: ${$}`),await this.connection.writeTextFile({path:$,content:Z,sessionId:this.sessionId})}catch(J){throw T0.warn(`[AcpFileSystem] writeTextFile ACP failed: ${J}`),J}}async exists($){if(!this.capabilities.readTextFile)return T0.debug(`[AcpFileSystem] exists fallback to local: ${$}`),this.fallback.exists($);try{return await this.connection.readTextFile({path:$,sessionId:this.sessionId}),T0.debug(`[AcpFileSystem] exists(${$}): true (ACP read success)`),!0}catch(Z){let J=String(Z).toLowerCase();if(["not found","no such file","enoent","does not exist","file not found","path not found"].some((W)=>J.includes(W)))return T0.debug(`[AcpFileSystem] exists(${$}): false (ACP: not found)`),!1;let X=M3(J);return T0.warn(`[AcpFileSystem] exists(${$}): assuming exists due to ${X} error`,{error:String(Z),errorType:X,filePath:$}),!0}}async readBinaryFile($){return T0.debug(`[AcpFileSystem] readBinaryFile fallback: ${$}`),this.fallback.readBinaryFile($)}async stat($){return T0.debug(`[AcpFileSystem] stat fallback: ${$}`),this.fallback.stat($)}async mkdir($,Z){return T0.debug(`[AcpFileSystem] mkdir fallback: ${$}`),this.fallback.mkdir($,Z)}getCapabilities(){return this.capabilities}canReadTextFile(){return this.capabilities.readTextFile??!1}canWriteTextFile(){return this.capabilities.writeTextFile??!1}usesRemoteFiles(){return this.canReadTextFile()||this.canWriteTextFile()}}function M3($){if($.includes("permission")||$.includes("access denied"))return"permission";if($.includes("timeout")||$.includes("timed out"))return"timeout";if($.includes("binary")||$.includes("encoding"))return"binary";if($.includes("too large")||$.includes("size"))return"size";if($.includes("connection")||$.includes("network"))return"network";return"unknown"}var I$=l("Agent"),f3=5000;class q5{async execute($,Z){let J=process.platform==="win32"?"cmd.exe":"/bin/bash",U=process.platform==="win32"?["/c",$]:["-c",$],Y;try{Y=await $2(J,U,{cwd:Z?.cwd||A(),env:{...process.env,...Z?.env},stdio:["pipe","pipe","pipe"]},Z?.durableOwnership)}catch(X){return{success:!1,stdout:"",stderr:"",exitCode:null,error:X instanceof Error?X.message:"Foreground command admission failed",failureKind:"admission",transport:"local"}}return new Promise((X)=>{let{child:W,processTree:Q}=Y,H,V=()=>{return H??=Q.terminate(),H},z=new O$,B,K=!1,O=!1,F=!1,_=!1,E,w,q=Z?.timeout?setTimeout(()=>{if(_)return;if(!B)B="timeout";V()},Z.timeout):null,L=null,D=()=>{if(q)clearTimeout(q);if(L&&Z?.signal)Z.signal.removeEventListener("abort",L),L=null},b=(T)=>{if(F)return;F=!0,D(),X(T)};if(Z?.signal){if(L=()=>{if(_)return;if(!B)B="aborted";V()},Z.signal.addEventListener("abort",L),Z.signal.aborted)L()}W.stdout?.on("data",(T)=>{z.append("stdout",T);let C=T.toString();Z?.onOutput?.(C)}),W.stderr?.on("data",(T)=>{z.append("stderr",T);let C=T.toString();Z?.onOutput?.(C)});let N=(T,C)=>{_=!0,D(),E??=(async()=>{if(await w,B||K)await V();try{await Y.finalize()}catch{O=!0}z.finish();let j=z.snapshot(),f=B==="timeout"?"timeout":B==="aborted"?"aborted":K?"admission":O?"finalization":C?"spawn":void 0;b({success:T===0&&!f,stdout:j.stdout.content,stderr:j.stderr.content,exitCode:T,error:f==="timeout"||f==="aborted"?"Command was terminated":f==="admission"?"Foreground command admission failed":f==="finalization"?"Foreground command finalization failed":C?.message,failureKind:f,transport:"local",capture:j})})()};if(W.once("close",(T)=>N(T)),W.once("error",(T)=>N(null,T)),Z?.signal?.aborted)B="aborted",w=Promise.resolve(),V();else w=Y.release().catch(async()=>{if(K=!0,!B)B="admission";await V()})})}isAvailable(){return!0}}class y4{connection;sessionId;fallback;constructor($,Z,J=new q5){this.connection=$;this.sessionId=Z;this.fallback=J}async execute($,Z){let J;try{I$.debug(`[AcpTerminal] Executing command via ACP: ${$}`),J=await this.connection.createTerminal({sessionId:this.sessionId,command:$,cwd:Z?.cwd,env:Z?.env?Object.entries(Z.env).map(([q,L])=>({name:q,value:L})):void 0});let U=J,Y=new O$(void 0,!0),X=0,W=0,Q=!1,H=!1,V,z=async()=>{let q,L=U.currentOutput().then((b)=>({type:"output",response:b})).catch(()=>({type:"error"})),D=new Promise((b)=>{q=setTimeout(()=>b({type:"timeout"}),f3)});return await Promise.race([L,D]).finally(()=>{if(q)clearTimeout(q)})},B=(q)=>{let L=q.length;if(L>=W){let D=q.slice(W);if(D)Z?.onOutput?.(D);W=L}},K=(q)=>{let L=q.output.length;if(!q.truncated&&L>=X){let D=q.output.slice(X);if(D)Y.append("stdout",D);B(q.output),X=L;return}Y=new O$(void 0,!0),Y.append("stdout",q.output),Y.markAccountingIncomplete(),W=L,X=L},O=(async()=>{while(!Q){let q=await z();if(q.type==="output")K(q.response);else if(Y.markAccountingIncomplete(),q.type==="timeout"){H=!0,Q=!0;break}if(Q)break;await new Promise((L)=>{let D=setTimeout(L,100);V=()=>{clearTimeout(D),L()}}),V=void 0}})(),F=async()=>{Q=!0,V?.(),await O},_=await new Promise((q)=>{let L=!1,D=(T)=>{if(L)return;if(L=!0,b)clearTimeout(b);Z?.signal?.removeEventListener("abort",N),q(T)},b=Z?.timeout?setTimeout(()=>D({type:"timeout"}),Z.timeout):void 0,N=()=>D({type:"aborted"});if(Z?.signal?.aborted)N();else Z?.signal?.addEventListener("abort",N,{once:!0});U.waitForExit().then((T)=>D({type:"completed",exitCode:T.exitCode??null})).catch((T)=>D({type:"failed",error:T}))});if(_.type!=="completed")await U.kill().catch(()=>{return});await F();let E=H?{type:"timeout"}:await z();if(E.type==="output"){let q=E.response;if(q.output.length>=W)B(q.output);if(Y=new O$(void 0,!0),Y.append("stdout",q.output),q.truncated)Y.markAccountingIncomplete()}else Y.markAccountingIncomplete();await U.release().catch(()=>{return}),Y.finish();let w=Y.snapshot();return{success:_.type==="completed"&&_.exitCode===0,stdout:w.stdout.content,stderr:"",exitCode:_.type==="completed"?_.exitCode:null,error:_.type==="timeout"?"Command timed out":_.type==="aborted"?"Command was aborted":_.type==="failed"?_.error instanceof Error?`ACP terminal unavailable: ${_.error.message}`:"ACP terminal unavailable":void 0,failureKind:_.type==="timeout"?"timeout":_.type==="aborted"?"aborted":_.type==="failed"?"unavailable":void 0,transport:"acp",capture:w}}catch(U){if(J)await J.release().catch(()=>{return});if(Z?.allowLocalFallback!==!0)return{success:!1,stdout:"",stderr:"",exitCode:null,error:U instanceof Error?`ACP terminal unavailable: ${U.message}`:"ACP terminal unavailable",failureKind:"unavailable",transport:"acp"};return I$.warn("[AcpTerminal] ACP terminal failed, using fallback:",U),{...await this.fallback.execute($,Z),transport:"local_fallback"}}}isAvailable(){return!0}}class h{static sessions=new Map;static currentSessionId=null;constructor(){}static getInstance(){return new h}static initializeSession($,Z,J,U){let Y=J?.fs?new _1($,Z,J.fs):new S$;if(J?.fs)I$.debug(`[AcpServiceContext:${Z}] Using ACP file system service`);let X=new y4($,Z);I$.debug(`[AcpServiceContext:${Z}] Using ACP terminal service`),h.sessions.set(Z,{fileSystemService:Y,terminalService:X,connection:$,clientCapabilities:J||null,cwd:U}),h.currentSessionId=Z,I$.debug(`[AcpServiceContext:${Z}] Initialized with capabilities:`,{fs:!!J?.fs,readTextFile:J?.fs?.readTextFile,writeTextFile:J?.fs?.writeTextFile,cwd:U})}static destroySession($){if(h.sessions.delete($),h.currentSessionId===$){let Z=Array.from(h.sessions.keys());h.currentSessionId=Z[0]||null}I$.debug(`[AcpServiceContext:${$}] Session destroyed`)}static getSessionServices($){return h.sessions.get($)||null}static setCurrentSession($){if(h.sessions.has($))h.currentSessionId=$}static getCurrentSessionId(){return h.currentSessionId}initialize($,Z,J,U){h.initializeSession($,Z,J,U||A())}reset(){if(h.currentSessionId)h.destroySession(h.currentSessionId)}isAcpMode(){return h.currentSessionId!==null}getFileSystemService($){let Z=$??h.currentSessionId;if(Z){let J=h.sessions.get(Z);if(J)return J.fileSystemService}return new S$}getTerminalService($){let Z=$??h.currentSessionId;if(Z){let J=h.sessions.get(Z);if(J)return J.terminalService}return new q5}getConnection(){if(h.currentSessionId){let $=h.sessions.get(h.currentSessionId);if($)return $.connection}return null}getSessionId(){return h.currentSessionId}getClientCapabilities(){if(h.currentSessionId){let $=h.sessions.get(h.currentSessionId);if($)return $.clientCapabilities}return null}async sendToolUpdate($,Z,J,U,Y){let X=h.currentSessionId;if(!X)return;let W=h.sessions.get(X);if(!W)return;try{await W.connection.sessionUpdate({sessionId:X,update:{sessionUpdate:"tool_call",toolCallId:$,status:Z,title:J,content:U||[],kind:Y||"other"}})}catch(Q){I$.warn("[AcpServiceContext] Failed to send tool update:",Q)}}}function _$($){return h.getInstance().getFileSystemService($)}function x4($){return h.getInstance().getTerminalService($)}function U0($){return $?h.getSessionServices($)!==null:h.getInstance().isAcpMode()}import*as i0 from"node:fs/promises";import*as i4 from"node:path";import{Mutex as C3}from"async-mutex";import{nanoid as R3}from"nanoid";import k3 from"write-file-atomic";var h4=["active","verifying","paused","blocked","usage_limited","budget_limited","complete"],u4=["pending","pass","fail","partial"];var d4=1048576,L5=1e5,l4=4000,P3=G.Object({attempt:G.Integer({minimum:1}),status:c(u4),requestedAt:G.String({format:"date-time"}),completedAt:G.Optional(G.String({format:"date-time"})),verifierSessionId:G.Optional(G.String({minLength:1})),summary:G.Optional(G.String({maxLength:l4})),evidenceSha256:G.Optional(G.String({pattern:"^[a-f0-9]{64}$"}))}),w5=G.Object({version:G.Literal(1),sessionId:G.String({minLength:1}),goalId:G.String({minLength:1}),objective:G.String({minLength:1,maxLength:L5}),status:c(h4),tokenBudget:G.Optional(G.Integer({minimum:1})),tokensUsed:G.Integer({minimum:0}),timeUsedSeconds:G.Integer({minimum:0}),continuationCount:G.Integer({minimum:0}),statusReason:G.Optional(G.String()),completionVerification:G.Optional(P3),createdAt:G.String({format:"date-time"}),updatedAt:G.String({format:"date-time"})});function m4($,Z){return $ instanceof Error&&"code"in $&&$.code===Z}function g4($){let Z=$.trim();if(!Z)throw Error("Goal objective must not be empty");if(Z.length>L5)throw Error(`Goal objective exceeds ${L5} characters`);return Z}function S3($){if($===void 0)return;if(!Number.isInteger($)||$<=0)throw Error("Goal token budget must be a positive integer");return $}function p4($){let Z=$?.trim();if(!Z)return;return Z.slice(0,l4)}class P0{workspaceRoot;sessionId;static mutexes=new Map;static listeners=new Set;filePath;mutex;constructor($,Z){this.workspaceRoot=$;this.sessionId=Z;this.filePath=c4($,Z);let J=P0.mutexes.get(this.filePath);if(!J)J=new C3,P0.mutexes.set(this.filePath,J);this.mutex=J}static subscribe($){return this.listeners.add($),()=>this.listeners.delete($)}static async hasActiveGoal($,Z){let J=(await new P0($,Z).get())?.status;return J==="active"||J==="verifying"}async get(){return this.mutex.runExclusive(()=>this.readUnlocked())}async create($){return this.mutex.runExclusive(async()=>{let Z=await this.readUnlocked();if(Z&&Z.status!=="complete")throw Error(`Session already has an unfinished goal (${Z.status}); clear or complete it first`);let J=new Date().toISOString(),U=S3($.tokenBudget),Y={version:1,sessionId:this.sessionId,goalId:R3(12),objective:g4($.objective),status:"active",...U===void 0?{}:{tokenBudget:U},tokensUsed:0,timeUsedSeconds:0,continuationCount:0,createdAt:J,updatedAt:J};return await this.persistUnlocked(Y),this.emit(Y),Y})}async edit($){return this.updateExisting((Z)=>{if(!["active","verifying","paused","blocked"].includes(Z.status))throw Error(`Cannot edit goal while status is ${Z.status}`);return{...Z,objective:g4($),completionVerification:void 0,status:Z.status==="verifying"?"active":Z.status,statusReason:Z.status==="verifying"?void 0:Z.statusReason,updatedAt:new Date().toISOString()}})}async pause($="paused by user"){return this.updateExisting((Z)=>{if(Z.status!=="active"&&Z.status!=="verifying"&&Z.status!=="blocked")throw Error(`Cannot pause goal while status is ${Z.status}`);return{...Z,status:"paused",statusReason:$,updatedAt:new Date().toISOString()}})}async pauseIfActive($){return this.mutex.runExclusive(async()=>{let Z=await this.readUnlocked();if(!Z||Z.status!=="active"&&Z.status!=="verifying")return Z;let J={...Z,status:"paused",statusReason:$,updatedAt:new Date().toISOString()};return await this.persistUnlocked(J),this.emit(J),J})}async resume(){return this.updateExisting(($)=>{if($.status!=="paused"&&$.status!=="blocked")throw Error(`Cannot resume goal while status is ${$.status}`);let Z=$.completionVerification?.status==="pending"||$.completionVerification?.status==="pass";return{...$,status:Z?"verifying":"active",statusReason:void 0,updatedAt:new Date().toISOString()}})}async requestCompletion(){return this.updateExisting(($)=>{if($.status!=="active"&&$.status!=="verifying")throw Error(`Cannot request goal completion while status is ${$.status}`);if($.status==="verifying"&&($.completionVerification?.status==="pending"||$.completionVerification?.status==="pass"))return $;let Z=new Date().toISOString();return{...$,status:"verifying",statusReason:"awaiting independent completion verification",completionVerification:{attempt:($.completionVerification?.attempt??0)+1,status:"pending",requestedAt:Z},updatedAt:Z}})}async recordCompletionVerification($){let Z=$.verifierSessionId?.trim();if(!Z)throw Error("Goal verification requires a verifier Session identity");if(!/^[a-f0-9]{64}$/.test($.evidenceSha256??""))throw Error("Goal verification requires a SHA-256 evidence digest");return this.updateExisting((J)=>{if(J.status!=="verifying"||!J.completionVerification)throw Error(`Cannot record goal verification while status is ${J.status}`);let U=new Date().toISOString();return{...J,statusReason:$.verdict==="pass"?"independent completion verification passed":`independent completion verification returned ${$.verdict}`,completionVerification:{...J.completionVerification,status:$.verdict,completedAt:U,verifierSessionId:Z,...p4($.summary)?{summary:p4($.summary)}:{},evidenceSha256:$.evidenceSha256},updatedAt:U}})}async invalidateCompletionVerification($){return this.updateExisting((Z)=>{if(Z.status!=="verifying"||!Z.completionVerification)return Z;let J=$.trim()||"goal completion evidence became stale";return{...Z,statusReason:J,completionVerification:{attempt:Z.completionVerification.attempt,status:"pending",requestedAt:Z.completionVerification.requestedAt},updatedAt:new Date().toISOString()}})}async finalizeVerifiedCompletion(){return this.updateExisting(($)=>{if($.status!=="verifying"||$.completionVerification?.status!=="pass"||!$.completionVerification.verifierSessionId||!$.completionVerification.evidenceSha256)throw Error("Goal completion requires a persisted independent PASS verdict");return{...$,status:"complete",statusReason:void 0,updatedAt:new Date().toISOString()}})}async reconcileFinalizationReceipt($){return this.mutex.runExclusive(async()=>{let Z=await this.readUnlocked();if(!Z||Z.goalId!==$.goalId)return null;let J=Z.completionVerification;if(!(J?.status==="pass"&&J.attempt===$.verificationAttempt&&J.verifierSessionId===$.verifierSessionId&&J.evidenceSha256===$.evidenceSha256))return null;if(Z.status==="complete")return{goal:Z,finalized:!1};if(Z.status!=="verifying"||Z.updatedAt!==$.goalUpdatedAt)return null;let Y=D5(w5,{...Z,status:"complete",statusReason:void 0,updatedAt:new Date().toISOString()});return await this.persistUnlocked(Y),this.emit(Y),{goal:Y,finalized:!0}})}async block($){return this.updateExisting((Z)=>{if(Z.status!=="active"&&Z.status!=="verifying")throw Error(`Cannot block goal while status is ${Z.status}`);let J=$.trim();if(!J)throw Error("Blocked goal requires a reason");return{...Z,status:"blocked",statusReason:J,completionVerification:void 0,updatedAt:new Date().toISOString()}})}async recordProgress($){return this.mutex.runExclusive(async()=>{let Z=await this.readUnlocked();if(!Z||Z.status!=="active"&&Z.status!=="verifying")return Z;let J=Math.max(0,Math.round($.tokens)),U=Math.max(0,Math.round($.elapsedMs/1000)),Y=Z.tokensUsed+J,X=Z.tokenBudget!==void 0&&Y>=Z.tokenBudget,W={...Z,tokensUsed:Y,timeUsedSeconds:Z.timeUsedSeconds+U,status:X?"budget_limited":Z.status,statusReason:X?"token budget exhausted":Z.statusReason,updatedAt:new Date().toISOString()};return await this.persistUnlocked(W),this.emit(W),W})}async beginContinuation(){return this.updateExisting(($)=>{if($.status!=="active"&&$.status!=="verifying")throw Error(`Cannot continue goal while status is ${$.status}`);return{...$,continuationCount:$.continuationCount+1,updatedAt:new Date().toISOString()}})}async tryBeginContinuation(){return this.mutex.runExclusive(async()=>{let $=await this.readUnlocked();if(!$||$.status!=="active"&&$.status!=="verifying")return null;let Z={...$,continuationCount:$.continuationCount+1,updatedAt:new Date().toISOString()};return await this.persistUnlocked(Z),this.emit(Z),Z})}async clear(){return this.mutex.runExclusive(async()=>{try{await i0.unlink(this.filePath)}catch($){if(m4($,"ENOENT"))return!1;throw $}return this.emit(null),!0})}async updateExisting($){return this.mutex.runExclusive(async()=>{let Z=await this.readUnlocked();if(!Z)throw Error("Session has no goal");let J=D5(w5,$(Z));return await this.persistUnlocked(J),this.emit(J),J})}async readUnlocked(){try{if((await i0.stat(this.filePath)).size>d4)throw Error(`Goal state exceeds ${d4} bytes`);await i0.chmod(this.filePath,384);let Z=Z2(w5,JSON.parse(await i0.readFile(this.filePath,"utf8")));if(!Z.success||Z.data.sessionId!==this.sessionId)throw Error(`Invalid goal state: ${this.filePath}`);return Z.data}catch($){if(m4($,"ENOENT"))return null;if($ instanceof SyntaxError)throw Error(`Invalid goal state JSON: ${this.filePath}`,{cause:$});throw $}}async persistUnlocked($){await i0.mkdir(i4.dirname(this.filePath),{recursive:!0,mode:448}),await k3(this.filePath,`${JSON.stringify($)}
113
+ [error] ${K.message}`)})()}),this.processes.set(Z,H);try{await i1(X)}catch(K){throw H.status="killed",H.endTime=Date.now(),await W.terminate(),H.leaseStore?.remove(H.id),this.processes.delete(Z),Error("Failed to release durable background command gate",{cause:K})}return H}consumeOutput($,Z){let J=this.getProcess($,Z);if(!J)return;let U=J.pendingStdout.consume(),Y=J.pendingStderr.consume();return{id:J.id,command:J.command,status:J.status,stdout:U.content,stderr:Y.content,stdoutOmittedBytes:U.omittedBytes,stderrOmittedBytes:Y.omittedBytes,stdoutTotalBytes:U.totalBytes,stderrTotalBytes:Y.totalBytes,exitCode:J.exitCode,signal:J.signal,pid:J.pid,startedAt:J.startTime,endedAt:J.endTime,errorMessage:J.errorMessage,sandboxed:J.sandboxed}}getProcess($,Z){let J=this.processes.get($);return J?.sessionId===Z?J:void 0}listForSession($){return Array.from(this.processes.values()).filter((Z)=>Z.sessionId===$)}async writeInput($,Z,J,U=!1){let Y=this.getProcess($,Z);if(!Y)return;let X=Y.process?.stdin;if(Y.status!=="running"||!X||X.destroyed||X.writableEnded)return{success:!1,status:Y.status,bytesWritten:0,stdinClosed:!X||X.destroyed||X.writableEnded,errorMessage:"Shell stdin is not writable"};try{return await new Promise((W,Q)=>{let H=(z)=>{X.off("error",H),Q(z)},V=(z)=>{if(X.off("error",H),z)Q(z);else W()};if(X.once("error",H),U)X.end(J,V);else X.write(J,V)}),{success:!0,status:Y.status,bytesWritten:Buffer.byteLength(J),stdinClosed:U}}catch(W){return{success:!1,status:Y.status,bytesWritten:0,stdinClosed:X.destroyed||X.writableEnded,errorMessage:W instanceof Error?W.message:"Failed to write stdin"}}}async kill($,Z){let J=this.getProcess($,Z);if(!J)return;return this.terminateProcess(J)}async killSession($){let Z=this.listForSession($);await Promise.all(Z.map((J)=>this.terminateProcess(J)));for(let J of Z)this.processes.delete(J.id)}reapOrphanedSession($,Z){return new t1(Z,$).reapOrphans()}async terminateProcess($){if($.status!=="running"||!$.process)return{success:!1,alreadyExited:!0,status:$.status,pid:$.pid,exitCode:$.exitCode,signal:$.signal};$.status="killed",$.endTime=Date.now();let Z=await $.processTree?.terminate();if(!Z?.success)return $.status="error",$.errorMessage="Failed to terminate owned process tree",{success:!1,alreadyExited:Z?.alreadyExited??!1,status:$.status,pid:$.pid,exitCode:$.exitCode,signal:$.signal};return $.leaseStore?.remove($.id),{success:!0,alreadyExited:Z.alreadyExited,status:$.status,pid:$.pid,exitCode:$.exitCode,signal:$.signal}}async killAll(){await Promise.all(Array.from(this.processes.values()).map(($)=>this.terminateProcess($))),this.processes.clear()}}import{stat as dQ}from"node:fs/promises";import{Mutex as b7}from"async-mutex";import{nanoid as mQ}from"nanoid";import*as d7 from"os";import*as z0 from"path";import{randomUUID as A3}from"node:crypto";class P${store;constructor($,Z){this.store=new K1($,Z,{directoryName:".foreground-processes",idField:"processId",idPrefix:"foreground_",label:"foreground process"})}register($,Z){this.store.register($,Z)}remove($){this.store.remove($)}reapOrphans(){return this.store.reapOrphans()}}async function $2($,Z,J,U){let Y=`foreground_${A3()}`,{child:X,processTree:W}=c1($,Z,J);if(!X.pid)throw await W.terminate(),Error("Foreground command gate did not expose a PID");let Q=U?new P$(U.projectPath,U.sessionId):void 0;try{Q?.register(Y,X.pid)}catch(z){throw await W.terminate(),z}let H,V;return{child:X,processTree:W,processId:Y,release(){return H??=i1(X).catch((z)=>{throw W.terminate(),Error("Failed to release durable foreground command gate",{cause:z})}),H},finalize(){return V??=(async()=>{if(!(await l1(X,W)).success)throw Error("Failed to finalize foreground command process group");Q?.remove(Y)})(),V}}}import*as d0 from"fs/promises";class S${async readTextFile($){return d0.readFile($,"utf-8")}async writeTextFile($,Z){await d0.writeFile($,Z,"utf-8")}async exists($){try{return await d0.access($),!0}catch{return!1}}async readBinaryFile($){return d0.readFile($)}async stat($){try{let Z=await d0.stat($);return{size:Z.size,isDirectory:Z.isDirectory(),isFile:Z.isFile(),mtime:Z.mtime}}catch{return null}}async mkdir($,Z){await d0.mkdir($,{recursive:Z?.recursive??!1,mode:Z?.mode??493})}}var j3=new S$;function G$(){return j3}import{StringDecoder as T3}from"node:string_decoder";class E5{buffer;decoder=new T3("utf8");totalChars=0;accountingComplete=!0;finished=!1;constructor($){this.buffer=new O1($)}append($){if(this.finished)return;let Z=typeof $==="string"?Buffer.from($):$;this.buffer.append(Z),this.totalChars+=this.decoder.write(Z).length}markAccountingIncomplete(){this.accountingComplete=!1}finish(){if(this.finished)return;this.totalChars+=this.decoder.end().length,this.finished=!0}snapshot(){let $=this.buffer.peek();return{content:$.content,totalBytes:$.totalBytes,retainedBytes:$.retainedBytes,omittedBytes:$.omittedBytes,totalChars:this.totalChars,accountingComplete:this.accountingComplete}}}class O${terminalOutputMerged;stdout;stderr;constructor($=v4,Z=!1){this.terminalOutputMerged=Z;this.stdout=new E5($),this.stderr=new E5($)}append($,Z){this.streamFor($).append(Z)}markAccountingIncomplete(){this.stdout.markAccountingIncomplete(),this.stderr.markAccountingIncomplete()}finish(){this.stdout.finish(),this.stderr.finish()}snapshot(){return{stdout:this.stdout.snapshot(),stderr:this.stderr.snapshot(),terminalOutputMerged:this.terminalOutputMerged}}streamFor($){return $==="stdout"?this.stdout:this.stderr}}var T0=l("Agent");class _1{connection;sessionId;capabilities;fallback;constructor($,Z,J,U=new S$){this.connection=$;this.sessionId=Z;this.capabilities=J;this.fallback=U}async readTextFile($){if(!this.capabilities.readTextFile)return T0.debug(`[AcpFileSystem] readTextFile fallback: ${$}`),this.fallback.readTextFile($);try{return T0.debug(`[AcpFileSystem] readTextFile via ACP: ${$}`),(await this.connection.readTextFile({path:$,sessionId:this.sessionId})).content}catch(Z){throw T0.warn(`[AcpFileSystem] readTextFile ACP failed: ${Z}`),Z}}async writeTextFile($,Z){if(!this.capabilities.writeTextFile)return T0.debug(`[AcpFileSystem] writeTextFile fallback: ${$}`),this.fallback.writeTextFile($,Z);try{T0.debug(`[AcpFileSystem] writeTextFile via ACP: ${$}`),await this.connection.writeTextFile({path:$,content:Z,sessionId:this.sessionId})}catch(J){throw T0.warn(`[AcpFileSystem] writeTextFile ACP failed: ${J}`),J}}async exists($){if(!this.capabilities.readTextFile)return T0.debug(`[AcpFileSystem] exists fallback to local: ${$}`),this.fallback.exists($);try{return await this.connection.readTextFile({path:$,sessionId:this.sessionId}),T0.debug(`[AcpFileSystem] exists(${$}): true (ACP read success)`),!0}catch(Z){let J=String(Z).toLowerCase();if(["not found","no such file","enoent","does not exist","file not found","path not found"].some((W)=>J.includes(W)))return T0.debug(`[AcpFileSystem] exists(${$}): false (ACP: not found)`),!1;let X=M3(J);return T0.warn(`[AcpFileSystem] exists(${$}): assuming exists due to ${X} error`,{error:String(Z),errorType:X,filePath:$}),!0}}async readBinaryFile($){return T0.debug(`[AcpFileSystem] readBinaryFile fallback: ${$}`),this.fallback.readBinaryFile($)}async stat($){return T0.debug(`[AcpFileSystem] stat fallback: ${$}`),this.fallback.stat($)}async mkdir($,Z){return T0.debug(`[AcpFileSystem] mkdir fallback: ${$}`),this.fallback.mkdir($,Z)}getCapabilities(){return this.capabilities}canReadTextFile(){return this.capabilities.readTextFile??!1}canWriteTextFile(){return this.capabilities.writeTextFile??!1}usesRemoteFiles(){return this.canReadTextFile()||this.canWriteTextFile()}}function M3($){if($.includes("permission")||$.includes("access denied"))return"permission";if($.includes("timeout")||$.includes("timed out"))return"timeout";if($.includes("binary")||$.includes("encoding"))return"binary";if($.includes("too large")||$.includes("size"))return"size";if($.includes("connection")||$.includes("network"))return"network";return"unknown"}var I$=l("Agent"),f3=5000;class q5{async execute($,Z){let J=process.platform==="win32"?"cmd.exe":"/bin/bash",U=process.platform==="win32"?["/c",$]:["-c",$],Y;try{Y=await $2(J,U,{cwd:Z?.cwd||A(),env:{...process.env,...Z?.env},stdio:["pipe","pipe","pipe"]},Z?.durableOwnership)}catch(X){return{success:!1,stdout:"",stderr:"",exitCode:null,error:X instanceof Error?X.message:"Foreground command admission failed",failureKind:"admission",transport:"local"}}return new Promise((X)=>{let{child:W,processTree:Q}=Y,H,V=()=>{return H??=Q.terminate(),H},z=new O$,B,K=!1,O=!1,F=!1,_=!1,E,w,q=Z?.timeout?setTimeout(()=>{if(_)return;if(!B)B="timeout";V()},Z.timeout):null,L=null,D=()=>{if(q)clearTimeout(q);if(L&&Z?.signal)Z.signal.removeEventListener("abort",L),L=null},b=(T)=>{if(F)return;F=!0,D(),X(T)};if(Z?.signal){if(L=()=>{if(_)return;if(!B)B="aborted";V()},Z.signal.addEventListener("abort",L),Z.signal.aborted)L()}W.stdout?.on("data",(T)=>{z.append("stdout",T);let C=T.toString();Z?.onOutput?.(C)}),W.stderr?.on("data",(T)=>{z.append("stderr",T);let C=T.toString();Z?.onOutput?.(C)});let N=(T,C)=>{_=!0,D(),E??=(async()=>{if(await w,B||K)await V();try{await Y.finalize()}catch{O=!0}z.finish();let j=z.snapshot(),f=B==="timeout"?"timeout":B==="aborted"?"aborted":K?"admission":O?"finalization":C?"spawn":void 0;b({success:T===0&&!f,stdout:j.stdout.content,stderr:j.stderr.content,exitCode:T,error:f==="timeout"||f==="aborted"?"Command was terminated":f==="admission"?"Foreground command admission failed":f==="finalization"?"Foreground command finalization failed":C?.message,failureKind:f,transport:"local",capture:j})})()};if(W.once("close",(T)=>N(T)),W.once("error",(T)=>N(null,T)),Z?.signal?.aborted)B="aborted",w=Promise.resolve(),V();else w=Y.release().catch(async()=>{if(K=!0,!B)B="admission";await V()})})}isAvailable(){return!0}}class y4{connection;sessionId;fallback;constructor($,Z,J=new q5){this.connection=$;this.sessionId=Z;this.fallback=J}async execute($,Z){let J;try{I$.debug(`[AcpTerminal] Executing command via ACP: ${$}`),J=await this.connection.createTerminal({sessionId:this.sessionId,command:$,cwd:Z?.cwd,env:Z?.env?Object.entries(Z.env).map(([q,L])=>({name:q,value:L})):void 0});let U=J,Y=new O$(void 0,!0),X=0,W=0,Q=!1,H=!1,V,z=async()=>{let q,L=U.currentOutput().then((b)=>({type:"output",response:b})).catch(()=>({type:"error"})),D=new Promise((b)=>{q=setTimeout(()=>b({type:"timeout"}),f3)});return await Promise.race([L,D]).finally(()=>{if(q)clearTimeout(q)})},B=(q)=>{let L=q.length;if(L>=W){let D=q.slice(W);if(D)Z?.onOutput?.(D);W=L}},K=(q)=>{let L=q.output.length;if(!q.truncated&&L>=X){let D=q.output.slice(X);if(D)Y.append("stdout",D);B(q.output),X=L;return}Y=new O$(void 0,!0),Y.append("stdout",q.output),Y.markAccountingIncomplete(),W=L,X=L},O=(async()=>{while(!Q){let q=await z();if(q.type==="output")K(q.response);else if(Y.markAccountingIncomplete(),q.type==="timeout"){H=!0,Q=!0;break}if(Q)break;await new Promise((L)=>{let D=setTimeout(L,100);V=()=>{clearTimeout(D),L()}}),V=void 0}})(),F=async()=>{Q=!0,V?.(),await O},_=await new Promise((q)=>{let L=!1,D=(T)=>{if(L)return;if(L=!0,b)clearTimeout(b);Z?.signal?.removeEventListener("abort",N),q(T)},b=Z?.timeout?setTimeout(()=>D({type:"timeout"}),Z.timeout):void 0,N=()=>D({type:"aborted"});if(Z?.signal?.aborted)N();else Z?.signal?.addEventListener("abort",N,{once:!0});U.waitForExit().then((T)=>D({type:"completed",exitCode:T.exitCode??null})).catch((T)=>D({type:"failed",error:T}))});if(_.type!=="completed")await U.kill().catch(()=>{return});await F();let E=H?{type:"timeout"}:await z();if(E.type==="output"){let q=E.response;if(q.output.length>=W)B(q.output);if(Y=new O$(void 0,!0),Y.append("stdout",q.output),q.truncated)Y.markAccountingIncomplete()}else Y.markAccountingIncomplete();await U.release().catch(()=>{return}),Y.finish();let w=Y.snapshot();return{success:_.type==="completed"&&_.exitCode===0,stdout:w.stdout.content,stderr:"",exitCode:_.type==="completed"?_.exitCode:null,error:_.type==="timeout"?"Command timed out":_.type==="aborted"?"Command was aborted":_.type==="failed"?_.error instanceof Error?`ACP terminal unavailable: ${_.error.message}`:"ACP terminal unavailable":void 0,failureKind:_.type==="timeout"?"timeout":_.type==="aborted"?"aborted":_.type==="failed"?"unavailable":void 0,transport:"acp",capture:w}}catch(U){if(J)await J.release().catch(()=>{return});if(Z?.allowLocalFallback!==!0)return{success:!1,stdout:"",stderr:"",exitCode:null,error:U instanceof Error?`ACP terminal unavailable: ${U.message}`:"ACP terminal unavailable",failureKind:"unavailable",transport:"acp"};return I$.warn("[AcpTerminal] ACP terminal failed, using fallback:",U),{...await this.fallback.execute($,Z),transport:"local_fallback"}}}isAvailable(){return!0}}class h{static sessions=new Map;static currentSessionId=null;constructor(){}static getInstance(){return new h}static initializeSession($,Z,J,U,Y){let X=J?.fs?new _1($,Z,J.fs):new S$;if(J?.fs)I$.debug(`[AcpServiceContext:${Z}] Using ACP file system service`);let W=new y4($,Z);I$.debug(`[AcpServiceContext:${Z}] Using ACP terminal service`),h.sessions.set(Z,{fileSystemService:X,terminalService:W,connection:$,sendUpdate:Y,clientCapabilities:J||null,cwd:U}),h.currentSessionId=Z,I$.debug(`[AcpServiceContext:${Z}] Initialized with capabilities:`,{fs:!!J?.fs,readTextFile:J?.fs?.readTextFile,writeTextFile:J?.fs?.writeTextFile,cwd:U})}static destroySession($){if(h.sessions.delete($),h.currentSessionId===$){let Z=Array.from(h.sessions.keys());h.currentSessionId=Z[0]||null}I$.debug(`[AcpServiceContext:${$}] Session destroyed`)}static getSessionServices($){return h.sessions.get($)||null}static setCurrentSession($){if(h.sessions.has($))h.currentSessionId=$}static getCurrentSessionId(){return h.currentSessionId}initialize($,Z,J,U){h.initializeSession($,Z,J,U||A())}reset(){if(h.currentSessionId)h.destroySession(h.currentSessionId)}isAcpMode(){return h.currentSessionId!==null}getFileSystemService($){let Z=$??h.currentSessionId;if(Z){let J=h.sessions.get(Z);if(J)return J.fileSystemService}return new S$}getTerminalService($){let Z=$??h.currentSessionId;if(Z){let J=h.sessions.get(Z);if(J)return J.terminalService}return new q5}getConnection(){if(h.currentSessionId){let $=h.sessions.get(h.currentSessionId);if($)return $.connection}return null}getSessionId(){return h.currentSessionId}getClientCapabilities(){if(h.currentSessionId){let $=h.sessions.get(h.currentSessionId);if($)return $.clientCapabilities}return null}async sendToolUpdate($,Z,J,U,Y){let X=h.currentSessionId;if(!X)return;let W=h.sessions.get(X);if(!W)return;if(!W.sendUpdate)return;try{await W.sendUpdate({sessionUpdate:"tool_call",toolCallId:$,status:Z,title:J,content:U||[],kind:Y||"other"})}catch(Q){I$.warn("[AcpServiceContext] Failed to send tool update:",Q)}}}function _$($){return h.getInstance().getFileSystemService($)}function x4($){return h.getInstance().getTerminalService($)}function U0($){return $?h.getSessionServices($)!==null:h.getInstance().isAcpMode()}import*as i0 from"node:fs/promises";import*as i4 from"node:path";import{Mutex as C3}from"async-mutex";import{nanoid as R3}from"nanoid";import k3 from"write-file-atomic";var h4=["active","verifying","paused","blocked","usage_limited","budget_limited","complete"],u4=["pending","pass","fail","partial"];var d4=1048576,L5=1e5,l4=4000,P3=G.Object({attempt:G.Integer({minimum:1}),status:c(u4),requestedAt:G.String({format:"date-time"}),completedAt:G.Optional(G.String({format:"date-time"})),verifierSessionId:G.Optional(G.String({minLength:1})),summary:G.Optional(G.String({maxLength:l4})),evidenceSha256:G.Optional(G.String({pattern:"^[a-f0-9]{64}$"}))}),w5=G.Object({version:G.Literal(1),sessionId:G.String({minLength:1}),goalId:G.String({minLength:1}),objective:G.String({minLength:1,maxLength:L5}),status:c(h4),tokenBudget:G.Optional(G.Integer({minimum:1})),tokensUsed:G.Integer({minimum:0}),timeUsedSeconds:G.Integer({minimum:0}),continuationCount:G.Integer({minimum:0}),statusReason:G.Optional(G.String()),completionVerification:G.Optional(P3),createdAt:G.String({format:"date-time"}),updatedAt:G.String({format:"date-time"})});function m4($,Z){return $ instanceof Error&&"code"in $&&$.code===Z}function g4($){let Z=$.trim();if(!Z)throw Error("Goal objective must not be empty");if(Z.length>L5)throw Error(`Goal objective exceeds ${L5} characters`);return Z}function S3($){if($===void 0)return;if(!Number.isInteger($)||$<=0)throw Error("Goal token budget must be a positive integer");return $}function p4($){let Z=$?.trim();if(!Z)return;return Z.slice(0,l4)}class P0{workspaceRoot;sessionId;static mutexes=new Map;static listeners=new Set;filePath;mutex;constructor($,Z){this.workspaceRoot=$;this.sessionId=Z;this.filePath=c4($,Z);let J=P0.mutexes.get(this.filePath);if(!J)J=new C3,P0.mutexes.set(this.filePath,J);this.mutex=J}static subscribe($){return this.listeners.add($),()=>this.listeners.delete($)}static async hasActiveGoal($,Z){let J=(await new P0($,Z).get())?.status;return J==="active"||J==="verifying"}async get(){return this.mutex.runExclusive(()=>this.readUnlocked())}async create($){return this.mutex.runExclusive(async()=>{let Z=await this.readUnlocked();if(Z&&Z.status!=="complete")throw Error(`Session already has an unfinished goal (${Z.status}); clear or complete it first`);let J=new Date().toISOString(),U=S3($.tokenBudget),Y={version:1,sessionId:this.sessionId,goalId:R3(12),objective:g4($.objective),status:"active",...U===void 0?{}:{tokenBudget:U},tokensUsed:0,timeUsedSeconds:0,continuationCount:0,createdAt:J,updatedAt:J};return await this.persistUnlocked(Y),this.emit(Y),Y})}async edit($){return this.updateExisting((Z)=>{if(!["active","verifying","paused","blocked"].includes(Z.status))throw Error(`Cannot edit goal while status is ${Z.status}`);return{...Z,objective:g4($),completionVerification:void 0,status:Z.status==="verifying"?"active":Z.status,statusReason:Z.status==="verifying"?void 0:Z.statusReason,updatedAt:new Date().toISOString()}})}async pause($="paused by user"){return this.updateExisting((Z)=>{if(Z.status!=="active"&&Z.status!=="verifying"&&Z.status!=="blocked")throw Error(`Cannot pause goal while status is ${Z.status}`);return{...Z,status:"paused",statusReason:$,updatedAt:new Date().toISOString()}})}async pauseIfActive($){return this.mutex.runExclusive(async()=>{let Z=await this.readUnlocked();if(!Z||Z.status!=="active"&&Z.status!=="verifying")return Z;let J={...Z,status:"paused",statusReason:$,updatedAt:new Date().toISOString()};return await this.persistUnlocked(J),this.emit(J),J})}async resume(){return this.updateExisting(($)=>{if($.status!=="paused"&&$.status!=="blocked")throw Error(`Cannot resume goal while status is ${$.status}`);let Z=$.completionVerification?.status==="pending"||$.completionVerification?.status==="pass";return{...$,status:Z?"verifying":"active",statusReason:void 0,updatedAt:new Date().toISOString()}})}async requestCompletion(){return this.updateExisting(($)=>{if($.status!=="active"&&$.status!=="verifying")throw Error(`Cannot request goal completion while status is ${$.status}`);if($.status==="verifying"&&($.completionVerification?.status==="pending"||$.completionVerification?.status==="pass"))return $;let Z=new Date().toISOString();return{...$,status:"verifying",statusReason:"awaiting independent completion verification",completionVerification:{attempt:($.completionVerification?.attempt??0)+1,status:"pending",requestedAt:Z},updatedAt:Z}})}async recordCompletionVerification($){let Z=$.verifierSessionId?.trim();if(!Z)throw Error("Goal verification requires a verifier Session identity");if(!/^[a-f0-9]{64}$/.test($.evidenceSha256??""))throw Error("Goal verification requires a SHA-256 evidence digest");return this.updateExisting((J)=>{if(J.status!=="verifying"||!J.completionVerification)throw Error(`Cannot record goal verification while status is ${J.status}`);let U=new Date().toISOString();return{...J,statusReason:$.verdict==="pass"?"independent completion verification passed":`independent completion verification returned ${$.verdict}`,completionVerification:{...J.completionVerification,status:$.verdict,completedAt:U,verifierSessionId:Z,...p4($.summary)?{summary:p4($.summary)}:{},evidenceSha256:$.evidenceSha256},updatedAt:U}})}async invalidateCompletionVerification($){return this.updateExisting((Z)=>{if(Z.status!=="verifying"||!Z.completionVerification)return Z;let J=$.trim()||"goal completion evidence became stale";return{...Z,statusReason:J,completionVerification:{attempt:Z.completionVerification.attempt,status:"pending",requestedAt:Z.completionVerification.requestedAt},updatedAt:new Date().toISOString()}})}async finalizeVerifiedCompletion(){return this.updateExisting(($)=>{if($.status!=="verifying"||$.completionVerification?.status!=="pass"||!$.completionVerification.verifierSessionId||!$.completionVerification.evidenceSha256)throw Error("Goal completion requires a persisted independent PASS verdict");return{...$,status:"complete",statusReason:void 0,updatedAt:new Date().toISOString()}})}async reconcileFinalizationReceipt($){return this.mutex.runExclusive(async()=>{let Z=await this.readUnlocked();if(!Z||Z.goalId!==$.goalId)return null;let J=Z.completionVerification;if(!(J?.status==="pass"&&J.attempt===$.verificationAttempt&&J.verifierSessionId===$.verifierSessionId&&J.evidenceSha256===$.evidenceSha256))return null;if(Z.status==="complete")return{goal:Z,finalized:!1};if(Z.status!=="verifying"||Z.updatedAt!==$.goalUpdatedAt)return null;let Y=D5(w5,{...Z,status:"complete",statusReason:void 0,updatedAt:new Date().toISOString()});return await this.persistUnlocked(Y),this.emit(Y),{goal:Y,finalized:!0}})}async block($){return this.updateExisting((Z)=>{if(Z.status!=="active"&&Z.status!=="verifying")throw Error(`Cannot block goal while status is ${Z.status}`);let J=$.trim();if(!J)throw Error("Blocked goal requires a reason");return{...Z,status:"blocked",statusReason:J,completionVerification:void 0,updatedAt:new Date().toISOString()}})}async recordProgress($){return this.mutex.runExclusive(async()=>{let Z=await this.readUnlocked();if(!Z||Z.status!=="active"&&Z.status!=="verifying")return Z;let J=Math.max(0,Math.round($.tokens)),U=Math.max(0,Math.round($.elapsedMs/1000)),Y=Z.tokensUsed+J,X=Z.tokenBudget!==void 0&&Y>=Z.tokenBudget,W={...Z,tokensUsed:Y,timeUsedSeconds:Z.timeUsedSeconds+U,status:X?"budget_limited":Z.status,statusReason:X?"token budget exhausted":Z.statusReason,updatedAt:new Date().toISOString()};return await this.persistUnlocked(W),this.emit(W),W})}async beginContinuation(){return this.updateExisting(($)=>{if($.status!=="active"&&$.status!=="verifying")throw Error(`Cannot continue goal while status is ${$.status}`);return{...$,continuationCount:$.continuationCount+1,updatedAt:new Date().toISOString()}})}async tryBeginContinuation(){return this.mutex.runExclusive(async()=>{let $=await this.readUnlocked();if(!$||$.status!=="active"&&$.status!=="verifying")return null;let Z={...$,continuationCount:$.continuationCount+1,updatedAt:new Date().toISOString()};return await this.persistUnlocked(Z),this.emit(Z),Z})}async clear(){return this.mutex.runExclusive(async()=>{try{await i0.unlink(this.filePath)}catch($){if(m4($,"ENOENT"))return!1;throw $}return this.emit(null),!0})}async updateExisting($){return this.mutex.runExclusive(async()=>{let Z=await this.readUnlocked();if(!Z)throw Error("Session has no goal");let J=D5(w5,$(Z));return await this.persistUnlocked(J),this.emit(J),J})}async readUnlocked(){try{if((await i0.stat(this.filePath)).size>d4)throw Error(`Goal state exceeds ${d4} bytes`);await i0.chmod(this.filePath,384);let Z=Z2(w5,JSON.parse(await i0.readFile(this.filePath,"utf8")));if(!Z.success||Z.data.sessionId!==this.sessionId)throw Error(`Invalid goal state: ${this.filePath}`);return Z.data}catch($){if(m4($,"ENOENT"))return null;if($ instanceof SyntaxError)throw Error(`Invalid goal state JSON: ${this.filePath}`,{cause:$});throw $}}async persistUnlocked($){await i0.mkdir(i4.dirname(this.filePath),{recursive:!0,mode:448}),await k3(this.filePath,`${JSON.stringify($)}
114
114
  `,{encoding:"utf8",mode:384,fsync:!0})}emit($){let Z={workspaceRoot:this.workspaceRoot,sessionId:this.sessionId,goal:$?{...$}:null};for(let J of P0.listeners)try{J(Z)}catch{}}}import{createHash as I3}from"node:crypto";import{promises as J2,realpathSync as v3}from"node:fs";import o from"node:path";import{fileURLToPath as y3,pathToFileURL as Z$}from"node:url";var n4=l("Service"),r4=65536;class N5{name;onCrash;child;processTree;connection;closePromise;crashCleanup;capabilities;initialized=!1;stopping=!1;notificationHandlers=new Map;requestHandlers=new Map;constructor($,Z){this.name=$;this.onCrash=Z}get serverCapabilities(){return this.capabilities}get isInitialized(){return this.initialized}async start($){if(await this.crashCleanup,this.crashCleanup=void 0,this.connection)return;let Z=await import("vscode-jsonrpc/node.js"),{child:J,processTree:U}=r$($.command,[...$.args],{cwd:$.cwd,env:{...$.environment,PATH:$.environment.PATH??process.env.PATH??"",HOME:$.environment.HOME??process.env.HOME??"",USER:$.environment.USER??process.env.USER??"",SHELL:$.environment.SHELL??process.env.SHELL??"/bin/sh",BLADE_CLI:"1"},stdio:["pipe","pipe","pipe"]},{releaseOnExit:!1});this.child=J,this.processTree=U;try{if(await new Promise((W,Q)=>{let H=()=>{J.removeListener("spawn",V),J.removeListener("error",z)},V=()=>{H(),W()},z=(B)=>{H(),Q(B)};J.once("spawn",V),J.once("error",z)}),!J.stdout||!J.stdin)throw Error("LSP server stdio is unavailable");let Y="";J.stderr?.setEncoding("utf8"),J.stderr?.on("data",(W)=>{if(Y.length<r4)Y+=W.slice(0,r4-Y.length)}),J.stdin.on("error",(W)=>{if(!this.stopping)n4.debug(`[LSP ${this.name}] stdin closed: ${W.message}`)}),this.closePromise=new Promise((W)=>{J.once("close",(Q,H)=>{this.initialized=!1;let V=!this.stopping;if(!this.stopping){let z=Y.trim()?`: ${Y.trim().slice(0,512)}`:H?` (${H})`:"";this.onCrash(Error(`LSP server "${this.name}" exited with code ${Q}${z}`))}if(this.child===J){let z=this.processTree;try{this.connection?.dispose()}catch{}if(this.connection=void 0,this.child=void 0,this.closePromise=void 0,V&&z)this.crashCleanup=z.terminate().then(()=>{return}),this.processTree=void 0}W()})});let X=Z.createMessageConnection(new Z.StreamMessageReader(J.stdout),new Z.StreamMessageWriter(J.stdin));this.connection=X,X.onError(([W])=>{if(!this.stopping)n4.warn(`[LSP ${this.name}] connection error: ${W.message}`)}),X.onClose(()=>{this.initialized=!1});for(let[W,Q]of this.notificationHandlers)for(let H of Q)X.onNotification(W,H);for(let[W,Q]of this.requestHandlers)X.onRequest(W,Q);X.listen()}catch(Y){throw await this.disposeTransport(),Y}}async initialize($,Z,J){let U=await this.request("initialize",$,Z,J,!1);return this.capabilities=U.capabilities,await this.notify("initialized",{}),this.initialized=!0,U}async request($,Z,J,U,Y=!0){let X=this.connection;if(!X)throw Error(`LSP server "${this.name}" is not started`);if(Y&&!this.initialized)throw Error(`LSP server "${this.name}" is not initialized`);let Q=new(await import("vscode-jsonrpc/node.js")).CancellationTokenSource;return this.awaitRequest(X.sendRequest($,Z,Q.token),Q,J,U,$)}async notify($,Z){if(!this.connection)throw Error(`LSP server "${this.name}" is not started`);await this.connection.sendNotification($,Z)}onNotification($,Z){let J=this.notificationHandlers.get($)??[];J.push(Z),this.notificationHandlers.set($,J),this.connection?.onNotification($,Z)}onRequest($,Z){this.requestHandlers.set($,Z),this.connection?.onRequest($,Z)}async stop($){if(!this.child&&!this.connection){await this.crashCleanup,this.crashCleanup=void 0;return}this.stopping=!0;let Z=this.connection;try{if(Z&&this.initialized){let U=new(await import("vscode-jsonrpc/node.js")).CancellationTokenSource;await this.awaitRequest(Z.sendRequest("shutdown",U.token),U,$,void 0,"shutdown").catch(()=>{return}),await Z.sendNotification("exit").catch(()=>{return})}await Promise.race([this.closePromise??Promise.resolve(),new Promise((J)=>setTimeout(J,Math.min($,500)))])}finally{await this.disposeTransport(),this.stopping=!1,this.initialized=!1,this.capabilities=void 0}}awaitRequest($,Z,J,U,Y){return new Promise((X,W)=>{let Q=!1,H=(B)=>{if(Q)return;Q=!0,clearTimeout(z),U?.removeEventListener("abort",V),B()},V=()=>{Z.cancel(),H(()=>W(Error(`LSP request "${Y}" was aborted`)))},z=setTimeout(()=>{Z.cancel(),H(()=>W(Error(`LSP request "${Y}" timed out after ${J}ms`)))},J);if(U?.addEventListener("abort",V,{once:!0}),U?.aborted)V();$.then((B)=>H(()=>X(B)),(B)=>H(()=>W(B)))})}async disposeTransport(){let $=this.connection,Z=this.processTree;this.connection=void 0,this.processTree=void 0,this.child=void 0,this.closePromise=void 0;try{$?.dispose()}catch{}await Z?.terminate(),await this.crashCleanup,this.crashCleanup=void 0}}var x3=l("Service"),h3=10485760,u3=10,a4=30,d3=-32801;class b5{options;workspaceRoot;servers=new Map;diagnostics=new Map;delivered=new Map;waiters=new Map;disposeController=new AbortController;diagnosticSequence=0;disposed=!1;constructor($){this.options=$;let Z=o.resolve($.workspaceRoot);try{this.workspaceRoot=v3.native(Z)}catch{this.workspaceRoot=Z}for(let[J,U]of Object.entries($.servers)){if(U.enabled===!1)continue;let Y={name:J,config:structuredClone(U),state:"stopped",restartCount:0,openedFiles:new Map,client:new N5(J,(X)=>{Y.state="error",Y.lastError=X.message,Y.openedFiles.clear()})};Y.client.onNotification("textDocument/publishDiagnostics",(X)=>{this.captureDiagnostics(J,X)}),Y.client.onRequest("workspace/configuration",(X)=>this.resolveWorkspaceConfiguration(U.settings,X)),Y.client.onRequest("workspace/workspaceFolders",()=>[{uri:Z$(this.workspaceRoot).href,name:o.basename(this.workspaceRoot)}]),Y.client.onRequest("window/workDoneProgress/create",()=>null),this.servers.set(J,Y)}}get available(){return this.servers.size>0&&!this.isRemoteSession()&&!this.disposed}get workspacePath(){return this.workspaceRoot}getStatus(){return[...this.servers.values()].map(($)=>({name:$.name,state:$.state,restartCount:$.restartCount,extensions:Object.keys($.config.extensionToLanguage).sort(),...$.lastError?{lastError:$.lastError}:{}})).sort(($,Z)=>$.name.localeCompare(Z.name))}async afterToolUse($,Z,J,U){if(!this.available||this.disposed)return;let Y;if(J.success&&($==="Write"||$==="Edit")&&typeof Z.file_path==="string")Y=await this.syncAfterWrite(Z.file_path,U.signal);else if(J.success&&$==="ApplyPatch"){let X=Array.isArray(J.metadata?.changes)?J.metadata.changes:[];for(let W of X){if(!W||typeof W!=="object"||!("path"in W)||typeof W.path!=="string")continue;if("newContent"in W&&W.newContent===null)await this.syncAfterDelete(W.path);else Y=await this.syncAfterWrite(W.path,U.signal)??Y}}this.attachPendingDiagnostics(J,Y)}async query($,Z){if(!this.available)throw Error(this.isRemoteSession()?"LSP is unavailable for ACP-owned remote files":"No LSP servers are configured for this Session");let J=await this.resolveFile($.filePath);if($.operation==="diagnostics")return{operation:$.operation,filePath:J,result:this.getCurrentDiagnostics(J)};let U=await this.ensureFileOpen(J,void 0,Z);if(!U)throw Error(`No LSP server handles ${o.extname(J)||"this file"}`);let Y={line:Math.max(0,($.line??1)-1),character:Math.max(0,($.character??1)-1)},X={uri:Z$(J).href},W={goToDefinition:{method:"textDocument/definition",params:{textDocument:X,position:Y}},findReferences:{method:"textDocument/references",params:{textDocument:X,position:Y,context:{includeDeclaration:!0}}},hover:{method:"textDocument/hover",params:{textDocument:X,position:Y}},documentSymbol:{method:"textDocument/documentSymbol",params:{textDocument:X}},workspaceSymbol:{method:"workspace/symbol",params:{query:$.query??""}},goToImplementation:{method:"textDocument/implementation",params:{textDocument:X,position:Y}},prepareCallHierarchy:{method:"textDocument/prepareCallHierarchy",params:{textDocument:X,position:Y}}},Q;if($.operation==="incomingCalls"||$.operation==="outgoingCalls"){let V=(await this.requestWithRetry(U,"textDocument/prepareCallHierarchy",{textDocument:X,position:Y},Z))?.[0];Q=V?await this.requestWithRetry(U,$.operation==="incomingCalls"?"callHierarchy/incomingCalls":"callHierarchy/outgoingCalls",{item:V},Z):[]}else{let H=W[$.operation];Q=await this.requestWithRetry(U,H.method,H.params,Z)}return{operation:$.operation,filePath:J,serverName:U.name,result:Q}}async dispose(){if(this.disposed)return;this.disposed=!0,this.disposeController.abort();for(let $ of this.waiters.values())for(let Z of $)clearTimeout(Z.timer),Z.resolve();this.waiters.clear(),await Promise.allSettled([...this.servers.values()].map(async($)=>{$.state="stopping",await $.client.stop($.config.shutdownTimeout??2000),$.state="stopped",$.openedFiles.clear()})),this.diagnostics.clear(),this.delivered.clear()}isRemoteSession(){return this.options.isRemoteSession?.()??U0(this.options.sessionId)}selectServer($){let Z=o.extname($).toLowerCase();return[...this.servers.values()].filter((J)=>(Z in J.config.extensionToLanguage)).sort((J,U)=>(U.config.priority??0)-(J.config.priority??0)||J.name.localeCompare(U.name))[0]}async ensureFileOpen($,Z,J){let U=this.selectServer($);if(!U)return;await this.ensureStarted(U,J);let Y=Z$($).href;if(U.openedFiles.has(Y))return U;let X=Z??await this.readBoundedFile($);return await U.client.notify("textDocument/didOpen",{textDocument:{uri:Y,languageId:U.config.extensionToLanguage[o.extname($).toLowerCase()],version:1,text:X}}),U.openedFiles.set(Y,1),U}async syncAfterWrite($,Z){try{let J=await this.resolveFile($),U=await this.readBoundedFile(J),Y=await this.ensureFileOpen(J,U,Z);if(!Y)return;let X=Z$(J).href,W=this.diagnostics.get(X)?.sequence??0;this.delivered.delete(X);let Q=Y.openedFiles.get(X)??0;if(Q>0){let H=Q+1;await Y.client.notify("textDocument/didChange",{textDocument:{uri:X,version:H},contentChanges:[{text:U}]}),Y.openedFiles.set(X,H)}return await Y.client.notify("textDocument/didSave",{textDocument:{uri:X},text:U}),await this.waitForDiagnostics(X,W,Y.config.diagnosticWaitTimeout??750,Z),J}catch(J){if(!Z?.aborted&&!this.disposeController.signal.aborted)x3.debug(`[LSP] post-edit sync skipped: ${J instanceof Error?J.message:String(J)}`);return}}async syncAfterDelete($){let Z=await this.resolveMissingFile($).catch(()=>{return});if(!Z)return;if(!this.isInsideWorkspace(Z))return;let J=Z$(Z).href;for(let U of this.servers.values()){if(!U.openedFiles.has(J))continue;await U.client.notify("textDocument/didClose",{textDocument:{uri:J}}).catch(()=>{return}),U.openedFiles.delete(J)}this.diagnostics.delete(J),this.delivered.delete(J)}async ensureStarted($,Z){if($.state==="running")return;if($.startPromise)return $.startPromise;if($.state==="error"){if($.restartCount>=($.config.maxRestarts??3))throw Error(`LSP server "${$.name}" exceeded its restart limit`);$.restartCount++}let J=this.startServer($,Z).finally(()=>{$.startPromise=void 0});return $.startPromise=J,J}async startServer($,Z){$.state="starting";try{await $.client.start({command:$.config.command,args:$.config.args??[],cwd:this.workspaceRoot,environment:{...this.options.environment,...$.config.env,BLADE_SESSION_ID:this.options.sessionId}});let J=Z$(this.workspaceRoot).href,U={processId:process.pid,rootPath:this.workspaceRoot,rootUri:J,workspaceFolders:[{uri:J,name:o.basename(this.workspaceRoot)}],initializationOptions:$.config.initializationOptions??{},capabilities:{workspace:{configuration:!0,workspaceFolders:!0,symbol:{dynamicRegistration:!1}},textDocument:{synchronization:{dynamicRegistration:!1,willSave:!1,willSaveWaitUntil:!1,didSave:!0},publishDiagnostics:{relatedInformation:!0,versionSupport:!1},hover:{dynamicRegistration:!1,contentFormat:["markdown","plaintext"]},definition:{dynamicRegistration:!1,linkSupport:!0},references:{dynamicRegistration:!1},implementation:{dynamicRegistration:!1,linkSupport:!0},documentSymbol:{dynamicRegistration:!1,hierarchicalDocumentSymbolSupport:!0},callHierarchy:{dynamicRegistration:!1}},general:{positionEncodings:["utf-16"]}}};if(await $.client.initialize(U,$.config.startupTimeout??1e4,Z),$.config.settings!==void 0)await $.client.notify("workspace/didChangeConfiguration",{settings:$.config.settings});$.state="running",$.lastError=void 0}catch(J){throw $.state="error",$.lastError=J instanceof Error?J.message:String(J),await $.client.stop($.config.shutdownTimeout??2000).catch(()=>{return}),J}}async requestWithRetry($,Z,J,U){let Y;for(let X=0;X<4;X++)try{return await $.client.request(Z,J,$.config.requestTimeout??1e4,U)}catch(W){if(Y=W,W.code!==d3||X===3)break;await new Promise((Q)=>setTimeout(Q,100*2**X))}throw Y}captureDiagnostics($,Z){if(this.disposed||!Z||typeof Z!=="object"||!("uri"in Z)||!("diagnostics"in Z))return;let J=Z;if(!Array.isArray(J.diagnostics))return;let U;try{U=J.uri.startsWith("file:")?y3(J.uri):o.resolve(J.uri)}catch{return}if(!this.isInsideWorkspace(U))return;let Y=Z$(o.resolve(U)).href,X={sequence:++this.diagnosticSequence,serverName:$,filePath:o.resolve(U),diagnostics:J.diagnostics.filter((H)=>H&&typeof H.message==="string"&&H.range!==void 0).slice(0,100).map((H)=>structuredClone(H))};this.diagnostics.set(Y,X);let W=this.waiters.get(Y)??[],Q=[];for(let H of W)if(X.sequence>H.afterSequence)clearTimeout(H.timer),H.resolve();else Q.push(H);if(Q.length>0)this.waiters.set(Y,Q);else this.waiters.delete(Y)}waitForDiagnostics($,Z,J,U){if(J===0||(this.diagnostics.get($)?.sequence??0)>Z)return Promise.resolve();return new Promise((Y)=>{let X=!1,W,Q=()=>{if(X)return;X=!0,clearTimeout(W.timer),U?.removeEventListener("abort",Q);let z=(this.waiters.get($)??[]).filter((B)=>B!==W);if(z.length>0)this.waiters.set($,z);else this.waiters.delete($);Y()},H=setTimeout(Q,J);W={afterSequence:Z,resolve:Q,timer:H};let V=this.waiters.get($)??[];if(V.push(W),this.waiters.set($,V),U?.addEventListener("abort",Q,{once:!0}),U?.aborted)Q()})}attachPendingDiagnostics($,Z){let J=[...this.diagnostics.values()].sort((Q,H)=>{if(Z){if(Q.filePath===Z&&H.filePath!==Z)return-1;if(H.filePath===Z&&Q.filePath!==Z)return 1}return H.sequence-Q.sequence}),U=[],Y=[],X=0;for(let Q of J){let H=Z$(Q.filePath).href,V=this.delivered.get(H)??new Set,z=Q.diagnostics.sort((K,O)=>(K.severity??4)-(O.severity??4)).filter((K)=>!V.has(this.diagnosticKey(K))).slice(0,Math.min(u3,a4-X));if(z.length===0)continue;let B=o.relative(this.workspaceRoot,Q.filePath);U.push(`${B}:`);for(let K of z){let O=K.range.start.line+1,F=K.range.start.character+1,_=["Error","Warning","Info","Hint"][(K.severity??1)-1],E=K.message.replace(/\s+/g," ").slice(0,500);U.push(` ${_??"Error"} ${O}:${F} ${E}`+(K.code!==void 0?` [${String(K.code)}]`:"")),V.add(this.diagnosticKey(K)),Y.push({file:B,line:O,character:F,severity:_??"Error",message:E,server:Q.serverName}),X++}if(this.delivered.set(H,V),X>=a4)break}if(U.length===0)return;let W=typeof $.llmContent==="string"?$.llmContent:JSON.stringify($.llmContent);$.llmContent=`${W}
115
115
 
116
116
  <new-diagnostics>
@@ -774,7 +774,7 @@ ${$0}
774
774
  </approved-plan>
775
775
 
776
776
  IMPORTANT: Execute according to the approved plan above. Follow the steps exactly as specified.`;if(typeof K==="string")J0=K+I;else J0=[...K,{type:"text",text:I}]}R=yield*this.runLoop(J0,O,{...f,inputMessageId:void 0})}if(!this.sessionRuntime||!C)return R;let g=await this.sessionRuntime.recordGoalProgress({tokens:R.metadata?.tokensUsed??0,elapsedMs:R.metadata?.duration??0});if(g)yield{kind:"goal_updated",goal:g};if(!R.success||O.signal?.aborted){if(g=await this.sessionRuntime.pauseActiveGoal(O.signal?.aborted?"goal paused after user cancellation":R.error?.message??"goal paused after turn failure"),g)yield{kind:"goal_updated",goal:g}}if(R.success&&!O.signal?.aborted&&D<20)await this.sessionRuntime.waitForBackgroundSubagentFollowUp(C,O.signal);let r=R.success&&!O.signal?.aborted&&D<20;if(L=await this.sessionRuntime.finishTurn(C,{continuePending:r,outcome:R.success&&!O.signal?.aborted?{status:"completed",turnsCount:R.metadata?.turnsCount??0,toolCallsCount:R.metadata?.toolCallsCount??0,durationMs:R.metadata?.duration??0}:{status:"aborted",cause:O.signal?.aborted?"cancelled":"failed",turnsCount:R.metadata?.turnsCount??0,toolCallsCount:R.metadata?.toolCallsCount??0,durationMs:R.metadata?.duration??0}}),L){D++,F=!0,_=!1,w=null,K="",q=void 0,E=N(),yield{kind:"follow_up_started",queued:this.sessionRuntime.getPendingSteeringCount(),recovered:this.sessionRuntime.getRecoveredSteeringCount(),messages:b()};continue}if(!R.success||O.signal?.aborted)return R;if(g=await this.sessionRuntime.getGoal(),!g||g.status!=="active"&&g.status!=="verifying")return R;if(w=await this.sessionRuntime.beginGoalContinuation(),!w)return R;L=await this.sessionRuntime.beginTurn("goal"),F=!1,_=!0,K=a5(w),q=void 0,E=void 0,yield{kind:"goal_continuation_started",goal:w,continuation:w.continuationCount},yield{kind:"goal_updated",goal:w}}}finally{if(this.sessionRuntime&&L)await this.sessionRuntime.finishTurn(L)}}let V=typeof Q==="string"?Q:Q.filter((K)=>K.type==="text").map((K)=>K.text).join(`
777
- `),z={id:this.generateTaskId(),type:"simple",prompt:V};return{success:!0,finalMessage:(await this.executeTask(z)).content,metadata:{turnsCount:1,toolCallsCount:0,duration:0}}}async chat($,Z,J){let{drainLoop:U}=await import("./chunk-t23a5yvk.js");return U(this.chatStream($,Z,J))}async*runPlanLoop($,Z,J){m.debug("Processing Plan mode message...");let{prompt:U}=await y$({projectPath:Z.workspaceRoot||A(),mode:"plan",includeEnvironment:!0,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}),Y;if(typeof $==="string")Y=q1($);else{let X=$.filter((W)=>W.type==="text");if(X.length>0){let W=X[0];Y=$.map((Q)=>Q===W?{type:"text",text:q1(W.text)}:Q)}else Y=[{type:"text",text:q1("")},...$]}return yield*this.executeLoop(Y,Z,J,U)}async*runLoop($,Z,J){m.debug("Processing enhanced chat message...");let U=Z.systemPrompt??await this.buildSystemPromptOnDemand(Z.workspaceRoot||A());return yield*this.executeLoop($,Z,J,U)}async buildSystemPromptOnDemand($){let Z=this.runtimeOptions.systemPrompt,J=this.runtimeOptions.appendSystemPrompt;return(await y$({projectPath:$,replaceDefault:Z,append:J,includeEnvironment:!0,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,U){if(!this.isInitialized)throw Error("Agent未初始化");let Y=this.buildLoopDependencies();return z9(Y,$,Z,J,U)}takeStartupAdoptedToolResultEvents(){return(this.sessionRuntime?.takeStartupAdoptedToolResults()??[]).flatMap(({call:Z,result:J})=>{let U={id:Z.toolCallId,type:"function",function:{name:Z.toolName,arguments:JSON.stringify(Z.input)}},Y=J.metadata&&typeof J.metadata==="object"&&!Array.isArray(J.metadata)?J.metadata:void 0,X=J.error===void 0,W=J.output,Q={success:X,llmContent:typeof W==="string"||W!==null&&typeof W==="object"?W:W===null?J.error?`Subagent execution failed: ${J.error}.`:"":String(W),...J.error?{error:{type:"execution_error",message:J.error}}:{},...Y?{metadata:Y}:{}},H=[{kind:"tool_result",toolCall:U,result:Q}],V=V9(U,Q);if(V)H.push(V);return H})}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=$,m.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,U)=>this.sessionRuntime.resolveContextualProjectRules($,Z,J,U):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(),U=Z.getAll().filter((Y)=>!$.includes(Y.name));for(let Y of U)Z.unregister(Y.name);m.debug(`Applied tool whitelist: ${$.join(", ")} (removed ${U.length} tools)`)}applyToolBlacklist($){let Z=this.toolExecutor.getRegistry(),J=new Set($);for(let U of Z.getAll())if(J.has(U.name))Z.unregister(U.name);m.debug(`Applied tool blacklist: ${$.join(", ")}`)}getToolStats(){let $=this.getAvailableTools(),Z=new Map;return $.forEach((J)=>{let U=Z.get(J.kind)||0;Z.set(J.kind,U+1)}),{totalTools:$.length,toolsByKind:Object.fromEntries(Z),toolNames:$.map((J)=>J.name)}}async destroy(){this.log("销毁Agent...");try{await this.legacyMcpRegistry?.disconnectAll(),this.legacyMcpRegistry=void 0,this.log("Agent已销毁")}catch($){throw this.error("Agent销毁失败",$),$}finally{this.toolExecutor.dispose(),this.isInitialized=!1}}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){m.debug(`[MainAgent] ${$}`,Z||"")}error($,Z){m.error(`[MainAgent] ${$}`,Z||"")}async initializeSystemPrompt(){try{let $=this.runtimeOptions.systemPrompt,Z=this.runtimeOptions.appendSystemPrompt,J=await y$({projectPath:this.sessionRuntime?.workspaceRoot??A(),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("系统提示配置验证成功"),m.debug(`[SystemPrompt] 可用来源: ${J.sources.filter((U)=>U.loaded).map((U)=>U.name).join(", ")}`)}catch($){this.error("系统提示配置验证失败",$)}}async registerBuiltinTools(){try{let $=await k2({sessionId:"default",configDir:K9.join(B9.homedir(),".blade"),workspaceRoot:A(),resourceRoot:A(),agentResources:this.agentResources});m.debug(`Registering ${$.length} builtin tools...`),this.toolExecutor.getRegistry().registerAll($);let Z=this.toolExecutor.getRegistry().getAll().length;m.debug(`Builtin tools registered: ${Z} tools`),m.debug(`[Tools] ${this.toolExecutor.getRegistry().getAll().map((J)=>J.name).join(", ")}`),await this.registerMcpTools()}catch($){throw m.error("Failed to register builtin tools:",$),$}}async registerMcpTools(){try{let $=await H2({workspaceRoot:A(),storeServers:this.config.mcpServers??{},cliConfigs:this.runtimeOptions.mcpConfig,strictCliConfig:this.runtimeOptions.strictMcpConfig});if(Object.keys($).length===0){m.debug("No MCP servers configured");return}let Z=u0.createIsolated({artifactWriter:new E1(`legacy-${MX()}`)});this.legacyMcpRegistry=Z;for(let[X,W]of Object.entries($))try{m.debug(`Connecting to MCP server: ${X}`),await Z.registerServer(X,W),m.debug(`MCP server "${X}" connected`)}catch(Q){m.warn(`Warning: MCP server "${X}" connection failed:`,Q)}let J=this.toolExecutor.getRegistry();J.setMcpCatalogBarrier(()=>Z.waitForCatalogIdle());let U=Z.getCatalogSnapshot();J.replaceMcpTools(U.tools),J.registerAll(A1(Z));let Y=Z.getInstructionsSnapshot();if(J.queueMcpInstructionsChange({revision:Y.revision,reason:"snapshot",replace:!0,instructions:Y.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]:[]})}),U.tools.length>0)m.debug(`Registered ${U.tools.length} MCP tools`),m.debug(`[MCP Tools] ${U.tools.map((X)=>X.name).join(", ")}`)}catch($){m.warn("Failed to register MCP tools:",$)}}async loadSubagents(){let $=await X0(A());if(this.agentResources=R2($),this.subagentRegistry=this.agentResources.subagents,this.runtimeOptions.agents?.length)this.subagentRegistry.applyOverrides(this.runtimeOptions.agents);let Z=this.subagentRegistry.getAllNames().length;if(Z>0)m.debug(`Loaded ${Z} subagents: ${this.subagentRegistry.getAllNames().join(", ")}`);else m.debug("No subagents configured")}applySkillToolRestrictions($){if(!this.activeSkillContext?.allowedTools)return $;let Z=this.activeSkillContext.allowedTools;m.debug(`Applying Skill tool restrictions: ${Z.join(", ")}`);let J=$.filter((U)=>{return Z.some((Y)=>{if(Y===U.name)return!0;let X=Y.match(/^(\w+)\(.*\)$/);if(X&&X[1]===U.name)return!0;return!1})});return m.debug(`Filtered tools: ${J.map((U)=>U.name).join(", ")} (${J.length}/${$.length})`),J}clearSkillContext(){if(this.activeSkillContext)m.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 U of $)if(U.type==="text")Z.push(U.text);if(Z.length===0)return $;let J=Z.join(`
777
+ `),z={id:this.generateTaskId(),type:"simple",prompt:V};return{success:!0,finalMessage:(await this.executeTask(z)).content,metadata:{turnsCount:1,toolCallsCount:0,duration:0}}}async chat($,Z,J){let{drainLoop:U}=await import("./chunk-25j7tjr6.js");return U(this.chatStream($,Z,J))}async*runPlanLoop($,Z,J){m.debug("Processing Plan mode message...");let{prompt:U}=await y$({projectPath:Z.workspaceRoot||A(),mode:"plan",includeEnvironment:!0,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}),Y;if(typeof $==="string")Y=q1($);else{let X=$.filter((W)=>W.type==="text");if(X.length>0){let W=X[0];Y=$.map((Q)=>Q===W?{type:"text",text:q1(W.text)}:Q)}else Y=[{type:"text",text:q1("")},...$]}return yield*this.executeLoop(Y,Z,J,U)}async*runLoop($,Z,J){m.debug("Processing enhanced chat message...");let U=Z.systemPrompt??await this.buildSystemPromptOnDemand(Z.workspaceRoot||A());return yield*this.executeLoop($,Z,J,U)}async buildSystemPromptOnDemand($){let Z=this.runtimeOptions.systemPrompt,J=this.runtimeOptions.appendSystemPrompt;return(await y$({projectPath:$,replaceDefault:Z,append:J,includeEnvironment:!0,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,U){if(!this.isInitialized)throw Error("Agent未初始化");let Y=this.buildLoopDependencies();return z9(Y,$,Z,J,U)}takeStartupAdoptedToolResultEvents(){return(this.sessionRuntime?.takeStartupAdoptedToolResults()??[]).flatMap(({call:Z,result:J})=>{let U={id:Z.toolCallId,type:"function",function:{name:Z.toolName,arguments:JSON.stringify(Z.input)}},Y=J.metadata&&typeof J.metadata==="object"&&!Array.isArray(J.metadata)?J.metadata:void 0,X=J.error===void 0,W=J.output,Q={success:X,llmContent:typeof W==="string"||W!==null&&typeof W==="object"?W:W===null?J.error?`Subagent execution failed: ${J.error}.`:"":String(W),...J.error?{error:{type:"execution_error",message:J.error}}:{},...Y?{metadata:Y}:{}},H=[{kind:"tool_result",toolCall:U,result:Q}],V=V9(U,Q);if(V)H.push(V);return H})}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=$,m.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,U)=>this.sessionRuntime.resolveContextualProjectRules($,Z,J,U):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(),U=Z.getAll().filter((Y)=>!$.includes(Y.name));for(let Y of U)Z.unregister(Y.name);m.debug(`Applied tool whitelist: ${$.join(", ")} (removed ${U.length} tools)`)}applyToolBlacklist($){let Z=this.toolExecutor.getRegistry(),J=new Set($);for(let U of Z.getAll())if(J.has(U.name))Z.unregister(U.name);m.debug(`Applied tool blacklist: ${$.join(", ")}`)}getToolStats(){let $=this.getAvailableTools(),Z=new Map;return $.forEach((J)=>{let U=Z.get(J.kind)||0;Z.set(J.kind,U+1)}),{totalTools:$.length,toolsByKind:Object.fromEntries(Z),toolNames:$.map((J)=>J.name)}}async destroy(){this.log("销毁Agent...");try{await this.legacyMcpRegistry?.disconnectAll(),this.legacyMcpRegistry=void 0,this.log("Agent已销毁")}catch($){throw this.error("Agent销毁失败",$),$}finally{this.toolExecutor.dispose(),this.isInitialized=!1}}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){m.debug(`[MainAgent] ${$}`,Z||"")}error($,Z){m.error(`[MainAgent] ${$}`,Z||"")}async initializeSystemPrompt(){try{let $=this.runtimeOptions.systemPrompt,Z=this.runtimeOptions.appendSystemPrompt,J=await y$({projectPath:this.sessionRuntime?.workspaceRoot??A(),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("系统提示配置验证成功"),m.debug(`[SystemPrompt] 可用来源: ${J.sources.filter((U)=>U.loaded).map((U)=>U.name).join(", ")}`)}catch($){this.error("系统提示配置验证失败",$)}}async registerBuiltinTools(){try{let $=await k2({sessionId:"default",configDir:K9.join(B9.homedir(),".blade"),workspaceRoot:A(),resourceRoot:A(),agentResources:this.agentResources});m.debug(`Registering ${$.length} builtin tools...`),this.toolExecutor.getRegistry().registerAll($);let Z=this.toolExecutor.getRegistry().getAll().length;m.debug(`Builtin tools registered: ${Z} tools`),m.debug(`[Tools] ${this.toolExecutor.getRegistry().getAll().map((J)=>J.name).join(", ")}`),await this.registerMcpTools()}catch($){throw m.error("Failed to register builtin tools:",$),$}}async registerMcpTools(){try{let $=await H2({workspaceRoot:A(),storeServers:this.config.mcpServers??{},cliConfigs:this.runtimeOptions.mcpConfig,strictCliConfig:this.runtimeOptions.strictMcpConfig});if(Object.keys($).length===0){m.debug("No MCP servers configured");return}let Z=u0.createIsolated({artifactWriter:new E1(`legacy-${MX()}`)});this.legacyMcpRegistry=Z;for(let[X,W]of Object.entries($))try{m.debug(`Connecting to MCP server: ${X}`),await Z.registerServer(X,W),m.debug(`MCP server "${X}" connected`)}catch(Q){m.warn(`Warning: MCP server "${X}" connection failed:`,Q)}let J=this.toolExecutor.getRegistry();J.setMcpCatalogBarrier(()=>Z.waitForCatalogIdle());let U=Z.getCatalogSnapshot();J.replaceMcpTools(U.tools),J.registerAll(A1(Z));let Y=Z.getInstructionsSnapshot();if(J.queueMcpInstructionsChange({revision:Y.revision,reason:"snapshot",replace:!0,instructions:Y.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]:[]})}),U.tools.length>0)m.debug(`Registered ${U.tools.length} MCP tools`),m.debug(`[MCP Tools] ${U.tools.map((X)=>X.name).join(", ")}`)}catch($){m.warn("Failed to register MCP tools:",$)}}async loadSubagents(){let $=await X0(A());if(this.agentResources=R2($),this.subagentRegistry=this.agentResources.subagents,this.runtimeOptions.agents?.length)this.subagentRegistry.applyOverrides(this.runtimeOptions.agents);let Z=this.subagentRegistry.getAllNames().length;if(Z>0)m.debug(`Loaded ${Z} subagents: ${this.subagentRegistry.getAllNames().join(", ")}`);else m.debug("No subagents configured")}applySkillToolRestrictions($){if(!this.activeSkillContext?.allowedTools)return $;let Z=this.activeSkillContext.allowedTools;m.debug(`Applying Skill tool restrictions: ${Z.join(", ")}`);let J=$.filter((U)=>{return Z.some((Y)=>{if(Y===U.name)return!0;let X=Y.match(/^(\w+)\(.*\)$/);if(X&&X[1]===U.name)return!0;return!1})});return m.debug(`Filtered tools: ${J.map((U)=>U.name).join(", ")} (${J.length}/${$.length})`),J}clearSkillContext(){if(this.activeSkillContext)m.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 U of $)if(U.type==="text")Z.push(U.text);if(Z.length===0)return $;let J=Z.join(`
778
778
  `);try{let U=await this.attachmentCollector.collect(J);if(U.length===0)return $;m.debug(`Processed ${U.length} @ file mentions in multimodal message`);let Y=this.buildAttachmentText(U);if(!Y)return $;return[...$,{type:"text",text:Y}]}catch(U){return m.error("Failed to process @ mentions in multimodal message:",U),$}}buildAttachmentText($){let Z=[],J=[];for(let Y of $)if(Y.type==="file"){let X=Y.metadata?.lineRange?` (lines ${Y.metadata.lineRange.start}${Y.metadata.lineRange.end?`-${Y.metadata.lineRange.end}`:""})`:"";Z.push(`<file path="${Y.path}"${X?` range="${X}"`:""}>`,Y.content,"</file>")}else if(Y.type==="directory")Z.push(`<directory path="${Y.path}">`,Y.content,"</directory>");else if(Y.type==="error")J.push(`- @${Y.path}: ${Y.error}`);let U="";if(Z.length>0)U+=`
779
779
 
780
780
  <system-reminder>
@@ -1572,7 +1572,7 @@ ${J}
1572
1572
  `)),{success:!0,message:"Schedules listed",content:H.join(`
1573
1573
  `)}}case"create":{let Q=iV(X);if("error"in Q)return U.sendMessage(`创建失败:${Q.error}`),{success:!1,error:Q.error};let H={prompt:Q.prompt,projectPath:W,trigger:Q.trigger,isolation:"worktree",permissionMode:"default",enabled:!0};try{let V=await $.create(H),z=V.nextRunAt?new Date(V.nextRunAt).toLocaleString():"(无)";return U.sendMessage(`[OK] 已创建定时任务 \`${V.id}\`
1574
1574
  ${A4(V.trigger)} · 下次运行: ${z}`),{success:!0,message:`Schedule ${V.id} created`}}catch(V){let z=V instanceof Error?V.message:String(V);return U.sendMessage(`创建失败:${z}`),{success:!1,error:z}}}case"remove":case"rm":{let Q=X[0];if(!Q)return U.sendMessage("用法:/schedule remove <id>"),{success:!1,error:"Missing schedule id"};let H=await $.remove(Q);return U.sendMessage(H?`[OK] 已删除 \`${Q}\``:`未找到 \`${Q}\``),{success:H,message:H?"Removed":"Not found"}}case"enable":case"disable":{let Q=X[0];if(!Q)return U.sendMessage(`用法:/schedule ${Y} <id>`),{success:!1,error:"Missing schedule id"};let H=await $.setEnabled(Q,Y==="enable");return U.sendMessage(H?`[OK] 已${Y==="enable"?"启用":"停用"} \`${Q}\``:`未找到 \`${Q}\``),{success:Boolean(H),message:H?"Updated":"Not found"}}case"run":{let Q=X[0];if(!Q)return U.sendMessage("用法:/schedule run <id>"),{success:!1,error:"Missing schedule id"};try{return await lV(Q),U.sendMessage(`[OK] 已触发 \`${Q}\``),{success:!0,message:"Schedule triggered"}}catch(H){let V=H instanceof Error?H.message:String(H);return U.sendMessage(`运行失败:${V}`),{success:!1,error:V}}}default:return U.sendMessage(`未知子命令: ${Y}
1575
- 使用 /schedule 查看帮助`),{success:!1,error:`Unknown subcommand: ${Y}`}}}}}var oJ=nV();import*as V1 from"node:fs/promises";import*as z1 from"node:path";async function Z3($,Z={}){let{maxResults:J=20,caseSensitive:U=!1,projectPath:Y,storagePath:X}=Z,W=X??a1(Y??A());if(!X){let K=await rV($,Y??A(),J,U);if(K)return K}let Q;try{Q=(await V1.readdir(W)).filter((O)=>O.endsWith(".jsonl")&&!O.startsWith("agent_")).map((O)=>z1.join(W,O))}catch{return[]}let V=(await Promise.all(Q.map(async(K)=>{try{let O=await V1.stat(K);return{path:K,mtime:O.mtimeMs}}catch{return null}}))).filter((K)=>K!==null).sort((K,O)=>O.mtime-K.mtime).map((K)=>K.path),z=[],B=U?$:$.toLowerCase();for(let K of V){if(z.length>=J)break;let O=z1.basename(K,".jsonl"),F=await aV(K,B,U,O);if(z.push(...F),z.length>=J){z.length=J;break}}return z}async function rV($,Z,J,U){try{let{syncAll:Y}=await import("./chunk-rzxk60wq.js"),X=await eJ();if(!X)return null;let{SessionService:W}=await import("./chunk-sfhevsq1.js");await Y(X,W.projectionDeriverForSearch());let Q=z1.resolve(Z),H=$3(X,$,Q,J*4),V=U?$:$.toLowerCase(),z=[];for(let B of H){if(B.role!=="user"&&B.role!=="assistant")continue;let K=j4(B.text,V,U,B.session_id,B.role,B.timestamp??void 0,0);if(K)z.push(K);if(z.length>=J)break}return z}catch{return null}}async function aV($,Z,J,U){try{let Y=await V1.readFile($,"utf8"),W=Y.split(`
1575
+ 使用 /schedule 查看帮助`),{success:!1,error:`Unknown subcommand: ${Y}`}}}}}var oJ=nV();import*as V1 from"node:fs/promises";import*as z1 from"node:path";async function Z3($,Z={}){let{maxResults:J=20,caseSensitive:U=!1,projectPath:Y,storagePath:X}=Z,W=X??a1(Y??A());if(!X){let K=await rV($,Y??A(),J,U);if(K)return K}let Q;try{Q=(await V1.readdir(W)).filter((O)=>O.endsWith(".jsonl")&&!O.startsWith("agent_")).map((O)=>z1.join(W,O))}catch{return[]}let V=(await Promise.all(Q.map(async(K)=>{try{let O=await V1.stat(K);return{path:K,mtime:O.mtimeMs}}catch{return null}}))).filter((K)=>K!==null).sort((K,O)=>O.mtime-K.mtime).map((K)=>K.path),z=[],B=U?$:$.toLowerCase();for(let K of V){if(z.length>=J)break;let O=z1.basename(K,".jsonl"),F=await aV(K,B,U,O);if(z.push(...F),z.length>=J){z.length=J;break}}return z}async function rV($,Z,J,U){try{let{syncAll:Y}=await import("./chunk-7ncx3vzw.js"),X=await eJ();if(!X)return null;let{SessionService:W}=await import("./chunk-ycvwc7hb.js");await Y(X,W.projectionDeriverForSearch());let Q=z1.resolve(Z),H=$3(X,$,Q,J*4),V=U?$:$.toLowerCase(),z=[];for(let B of H){if(B.role!=="user"&&B.role!=="assistant")continue;let K=j4(B.text,V,U,B.session_id,B.role,B.timestamp??void 0,0);if(K)z.push(K);if(z.length>=J)break}return z}catch{return null}}async function aV($,Z,J,U){try{let Y=await V1.readFile($,"utf8"),W=Y.split(`
1576
1576
  `).flatMap((B,K)=>{if(!B.trim())return[];try{return[{event:JSON.parse(B),index:K}]}catch{return[]}});if(!W.some(({event:B})=>B.type==="session_created"))return oV(W,Z,J,U);let H=new Map(W.flatMap(({event:B,index:K})=>typeof B.id==="string"?[[B.id,K+1]]:[])),V=tJ(sJ(Y,$)),z=new Map;for(let B of V){if(B.type==="message_created"&&(B.data.role==="user"||B.data.role==="assistant"))z.set(B.data.messageId,{role:B.data.role,content:[],timestamp:B.timestamp,lineNumber:H.get(B.id)??0});if(B.type==="part_created"&&B.data.partType==="text"){let K=z.get(B.data.messageId),O=B.data.payload.text;if(K&&typeof O==="string")K.content.push(O)}}return[...z.values()].flatMap((B)=>{let K=j4(B.content.join(" "),Z,J,U,B.role,B.timestamp,B.lineNumber);return K?[K]:[]})}catch{return[]}}function oV($,Z,J,U){return $.flatMap(({event:Y,index:X})=>{if(Y.type!=="message")return[];let W=Y.message;if(W?.role!=="user"&&W?.role!=="assistant"||!W.content)return[];let Q=typeof W.content==="string"?W.content:Array.isArray(W.content)?W.content.filter((V)=>typeof V==="object"&&V!==null&&V.type==="text"&&typeof V.text==="string").map((V)=>V.text).join(" "):"",H=j4(Q,Z,J,U,W.role,typeof Y.timestamp==="string"?Y.timestamp:void 0,X+1);return H?[H]:[]})}function j4($,Z,J,U,Y,X,W){if(!$)return;let Q=J?$:$.toLowerCase();if(!Q.includes(Z))return;let H=Q.indexOf(Z),V=Math.max(0,H-80),z=Math.min($.length,H+Z.length+80);return{sessionId:U,role:Y,content:(V>0?"...":"")+$.slice(V,z).replace(/\n/g," ")+(z<$.length?"...":""),timestamp:X,lineNumber:W}}function J3($){if($.length===0)return"没有找到匹配的历史记录";let Z=[`**找到 ${$.length} 条匹配:**
1577
1577
  `];for(let J of $){let U=J.timestamp?new Date(J.timestamp).toLocaleString("zh-CN",{timeZone:"Asia/Shanghai"}):"?",Y=J.role==="user"?"\uD83D\uDC64":"\uD83E\uDD16";Z.push(`${Y} \`${J.sessionId.slice(0,8)}\` (${U})`),Z.push(` ${J.content}`),Z.push("")}return Z.join(`
1578
1578
  `)}var tV={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=v(Z);if($.length===0)return J.sendMessage("**用法:** `/search <关键词>`\n\n在历史会话中搜索包含指定关键词的对话"),{success:!0,message:"显示帮助"};let U=$.join(" ");J.sendMessage(`正在搜索: "${U}" ...`);try{let Y=await Z3(U,{maxResults:15,projectPath:Z.cwd}),X=J3(Y);return J.sendMessage(X),{success:!0,message:`found ${Y.length} results`,data:{matches:Y.length}}}catch(Y){let X=Y instanceof Error?Y.message:"未知错误";return J.sendMessage(`搜索失败: ${X}`),{success:!1,error:X}}}},U3=tV;var sV={name:"skills",description:"查看所有可用的 Skills",fullDescription:"显示所有已发现的 Skills 及其详细信息,包括名称、描述、来源和允许的工具。",usage:"/skills",category:"system",examples:["/skills"],handler:async($,Z)=>{try{return await v0({cwd:Z.workspaceRoot??Z.cwd}).refresh(),n$(Z.workspaceRoot??Z.cwd),await l$(Z.workspaceRoot??Z.cwd),{success:!0,message:"show_skills_manager",data:{action:"show_skills_manager"}}}catch(J){let U=`获取 Skills 失败: ${J instanceof Error?J.message:"未知错误"}`;return S().addAssistantMessage(U),{success:!1,error:U}}}},Y3=sV;import eV from"node:path";function z5($){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 X3($){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 W3($,Z){if($.length<=Z)return $;return $.slice(0,Z-3)+"..."}async function $z($,Z){let J=v(Z),U=$[0],Y=e.getInstance(),X=Z0.getInstance(),W=Z.sessionId??"",Q=Z.sessionId?{sessionId:Z.sessionId,projectPath:eV.resolve(Z.workspaceRoot??Z.cwd)}:void 0;if(U==="resume"){let O=$[1],F=$.slice(2).join(" ").trim();if(!O||!F)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 _=await Z.subagents.resume(O,F),E=`Resumed \`${O}\` as \`${_.session.id}\` (depth ${_.session.resumeDepth}).`;return J.sendMessage(E),{success:!0,message:E,data:{action:"subagent_resumed",sourceAgentId:O,subagent:_.session}}}if(U==="clean"){let O=X.cleanupExpiredSessionsForParent(Q??W,0);return J.sendMessage(`已清理 ${O} 个已完成的 Agent 会话`),{success:!0,message:`Cleaned ${O} agent sessions`}}let H=[`**后台任务列表**
@@ -1607,4 +1607,4 @@ ${A4(V.trigger)} · 下次运行: ${z}`),{success:!0,message:`Schedule ${V.id} c
1607
1607
 
1608
1608
  **When to use:** ${$.whenToUse}`:""}`,usage:Z,category:"skill",examples:[Z],handler:async(J,U)=>{return{success:!0,message:`Invoking skill: ${$.name}`,data:{action:"invoke_skill",skillName:$.name,skillArgs:J.join(" ")}}}}}function Vz($,Z){return v0({cwd:Z}).getUserInvocableSkills().find((Y)=>Y.name===$)}async function zz($){await z3({cwd:$})}async function Bz($){let Z=x0.getInstance($),J=Z.getLastDiscoveryResult();if(Z.isInitialized()&&J)return J;return await Z.initialize($)}async function hM($,Z){try{let{command:J,args:U}=Qz($),Y=Hz(J);if(Y)return await Y.handler(U,Z);let X=Z.workspaceRoot||Z.cwd||A();await X0(X);let W=x0.getInstance(X);if(!W.isInitialized())await Bz(X);if(W.hasCommand(J)){let z=W.getCommand(J);if(z){let B=await W.executeCommand(J,{args:U,workspaceRoot:X,signal:Z.signal});if(B)return{success:!0,message:`执行自定义命令: /${J}`,data:{action:"invoke_custom_command",commandName:J,processedContent:B,config:z.config}}}}let H=J$(X).findCommand(J);if(H){let z=await W.executePluginCommand(H.namespacedName,{args:U,workspaceRoot:X,signal:Z.signal});if(z)return{success:!0,message:`执行插件命令: /${H.namespacedName}`,data:{action:"invoke_plugin_command",commandName:H.namespacedName,pluginName:H.pluginName,processedContent:z,config:H.config}}}await zz(X);let V=Vz(J,X);if(V)return await B3(V).handler(U,Z);return{success:!1,error:`未知命令: /${J}
1609
1609
  使用 /help 查看可用命令`}}catch(J){return{success:!1,error:`命令执行失败: ${J instanceof Error?J.message:"未知错误"}`}}}function uM($=A()){let Z=Object.values(d1),U=x0.getInstance($).getAllCommands().map((H)=>({name:H.name,description:H.config.description||H.content.slice(0,50),usage:H.config.argumentHint?`/${H.name} ${H.config.argumentHint}`:`/${H.name}`,category:"custom",handler:async()=>({success:!0})})),X=J$($).getAllCommands().map((H)=>({name:H.namespacedName,description:H.config.description||H.content.slice(0,50),usage:H.config.argumentHint?`/${H.namespacedName} ${H.config.argumentHint}`:`/${H.namespacedName}`,category:"plugin",handler:async()=>({success:!0})})),Q=v0({cwd:$}).getUserInvocableSkills().map(B3);return[...Z,...U,...X,...Q]}function dM($,Z=A()){let J=($.startsWith("/")?$.slice(1):$).trim(),U=Object.values(d1).map((F)=>({name:F.name,description:F.description,aliases:F.aliases||[],label:void 0,argumentHint:void 0,isCustom:!1,isSkill:!1,isPlugin:!1})),Y=x0.getInstance(Z),X=Y.getAllCommands().map((F)=>({name:F.name,description:F.config.description||F.content.slice(0,50),aliases:[],label:Y.getCommandLabel(F),argumentHint:F.config.argumentHint,isCustom:!0,isSkill:!1,isPlugin:!1})),Q=J$(Z).getAllCommands().map((F)=>({name:F.namespacedName,description:F.config.description||F.content.slice(0,50),aliases:[F.originalName],label:`(plugin: ${F.pluginName})`,argumentHint:F.config.argumentHint,isCustom:!1,isSkill:!1,isPlugin:!0})),V=v0({cwd:Z}).getUserInvocableSkills().map((F)=>({name:F.name,description:F.description,aliases:[],label:"(skill)",argumentHint:F.argumentHint,isCustom:!1,isSkill:!0,isPlugin:!1})),z=[...U,...X,...Q,...V];if(!J)return z.map((F)=>({command:`/${F.name}`,description:F.label?`${F.description} ${F.label}`:F.description,argumentHint:F.argumentHint,matchScore:50}));return new Wz(z,{keys:[{name:"name",weight:3},{name:"aliases",weight:2.5},{name:"description",weight:0.5}],threshold:0.4,includeScore:!0,ignoreLocation:!0,minMatchCharLength:1}).search(J).map((F)=>{let _=F.score??1,E=Math.round((1-_)*100),w=F.item;return{command:`/${w.name}`,description:w.label?`${w.description} ${w.label}`:w.description,argumentHint:w.argumentHint,matchScore:E}}).filter((F)=>(F.matchScore||0)>=40)}
1610
- export{qK as u,G$ as v,h as w,P0 as x,h$ as y,EY as z,e as A,HE as B,A0 as C,o0 as D,Y9 as E,$1 as F,N$ as G,m6 as H,p6 as I,P9 as J,S9 as K,h9 as L,f0 as M,e2 as N,$5 as O,W4 as P,Q4 as Q,H4 as R,V4 as S,z4 as T,B4 as U,K4 as V,Z5 as W,_4 as X,oj as Y,U4 as Z,xM as _,Bz as $,hM as aa,uM as ba,dM as ca};
1610
+ export{qK as z,G$ as A,h as B,P0 as C,h$ as D,EY as E,e as F,HE as G,A0 as H,o0 as I,Y9 as J,$1 as K,N$ as L,m6 as M,p6 as N,P9 as O,S9 as P,h9 as Q,f0 as R,e2 as S,$5 as T,W4 as U,Q4 as V,H4 as W,V4 as X,z4 as Y,B4 as Z,K4 as _,Z5 as $,_4 as aa,oj as ba,U4 as ca,xM as da,Bz as ea,hM as fa,uM as ga,dM as ha};
@@ -1,3 +1,3 @@
1
- import{l as i}from"./chunk-3bhh4v42.js";import{Cf as s}from"./chunk-7fgx7ztz.js";import"./chunk-q4q0r97b.js";import"./chunk-aspqajv2.js";import m from"node:path";var r={registry:i,currentWorkspace:s,inputCwd:()=>process.cwd(),write:console.log};function c(t,e){return m.resolve(e.inputCwd(),t)}function p(t){return t.map((e)=>{let o=e.isCurrent?"*":" ",n=e.gitBranch?` · ${e.gitBranch}`:"",d=e.available?"":" · unavailable";return`${o} ${e.name}${n}${d}
1
+ import{l as i}from"./chunk-g2yj0chw.js";import{Hf as s}from"./chunk-2rsr3bte.js";import"./chunk-f20mb84y.js";import"./chunk-d3h8cgs8.js";import m from"node:path";var r={registry:i,currentWorkspace:s,inputCwd:()=>process.cwd(),write:console.log};function c(t,e){return m.resolve(e.inputCwd(),t)}function p(t){return t.map((e)=>{let o=e.isCurrent?"*":" ",n=e.gitBranch?` · ${e.gitBranch}`:"",d=e.available?"":" · unavailable";return`${o} ${e.name}${n}${d}
2
2
  ${e.path}`}).join(`
3
3
  `)}async function l(t,e=r){let o=await e.registry.list(e.currentWorkspace());return e.write(t.json?JSON.stringify(o,null,2):p(o)),o}async function u(t,e=r){let o=await e.registry.bind(c(t.path,e),e.currentWorkspace());return e.write(t.json?JSON.stringify(o,null,2):`Bound project: ${o.path}`),o}async function j(t,e=r){let o=c(t.path,e),n=await e.registry.unbind(o);return e.write(t.json?JSON.stringify({path:o,removed:n},null,2):n?`Unbound project: ${o}`:`Project was not bound: ${o}`),n}var a={type:"boolean",default:!1,describe:"Print machine-readable JSON"},P={command:"list",aliases:["ls"],describe:"List bound projects",builder:(t)=>t.option("json",a),handler:async(t)=>{await l(t)}},b={command:"add <path>",aliases:["bind"],describe:"Bind a project folder",builder:(t)=>t.positional("path",{type:"string",demandOption:!0,describe:"Absolute or relative project folder"}).option("json",a),handler:async(t)=>{await u(t)}},h={command:"remove <path>",aliases:["rm","unbind"],describe:"Unbind a project folder",builder:(t)=>t.positional("path",{type:"string",demandOption:!0,describe:"Absolute or relative project folder"}).option("json",a),handler:async(t)=>{await j(t)}},y={command:"projects",aliases:["project"],describe:"Manage project bindings shared with Blade Web",builder:(t)=>t.command(P).command(b).command(h).demandCommand(1,"Choose list, add, or remove"),handler:()=>{return}};export{j as runProjectsRemove,l as runProjectsList,u as runProjectsAdd,y as projectsCommands,p as formatProjectList};
@@ -1 +1 @@
1
- import"./chunk-aspqajv2.js";var d={command:"install [target]",describe:"Install Blade native build. Use [target] to specify version (stable, latest, or specific version)",builder:(b)=>{return b.positional("target",{describe:"Version to install",type:"string",default:"stable",choices:["stable","latest"]}).option("force",{type:"boolean",describe:"Force reinstall",default:!1}).example([["$0 install","Install stable version"],["$0 install latest","Install latest version"],["$0 install --force","Force reinstall stable version"]])},handler:async(b)=>{console.log(`Installing Blade ${b.target}...`);try{if(b.force)console.log("Force reinstall enabled");console.log("Downloading..."),console.log("Installing..."),console.log("Installation completed successfully")}catch(c){console.error(`Error: Installation failed: ${c instanceof Error?c.message:"未知错误"}`),process.exit(1)}}};export{d as installCommands};
1
+ import"./chunk-d3h8cgs8.js";var d={command:"install [target]",describe:"Install Blade native build. Use [target] to specify version (stable, latest, or specific version)",builder:(b)=>{return b.positional("target",{describe:"Version to install",type:"string",default:"stable",choices:["stable","latest"]}).option("force",{type:"boolean",describe:"Force reinstall",default:!1}).example([["$0 install","Install stable version"],["$0 install latest","Install latest version"],["$0 install --force","Force reinstall stable version"]])},handler:async(b)=>{console.log(`Installing Blade ${b.target}...`);try{if(b.force)console.log("Force reinstall enabled");console.log("Downloading..."),console.log("Installing..."),console.log("Installation completed successfully")}catch(c){console.error(`Error: Installation failed: ${c instanceof Error?c.message:"未知错误"}`),process.exit(1)}}};export{d as installCommands};
@@ -1,4 +1,4 @@
1
- import{Gf as i}from"./chunk-75y3mb0z.js";import{$f as o,bg as C,dg as L,hg as j,ig as n}from"./chunk-q4q0r97b.js";import{jg as I}from"./chunk-aspqajv2.js";import{stat as d}from"node:fs/promises";import B from"node:path";import*as U from"node:path";var s=50,t=100,e=/^[A-Za-z0-9_-]+$/,__=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?(?:Z|[+-]\d{2}:\d{2})$/;function E_(_){return typeof _==="string"&&__.test(_)&&Number.isFinite(Date.parse(_))}function P(_){return typeof _==="string"&&U.isAbsolute(_)}function R_(_){return Buffer.from(JSON.stringify(_),"utf8").toString("base64url")}function W_(_){try{if(!e.test(_))throw Error("invalid");let E=Buffer.from(_,"base64url").toString("utf8");if(Buffer.from(E,"utf8").toString("base64url")!==_)throw Error("invalid");let R=JSON.parse(E);if(R.version!==1||typeof R.includeSubagents!=="boolean"||R.archived!==void 0&&typeof R.archived!=="boolean"||!(R.cwd===null||P(R.cwd))||!E_(R.lastMessageTime)||!P(R.projectPath)||!C(R.sessionId))throw Error("invalid");return{version:1,cwd:R.cwd===null?null:U.resolve(R.cwd),includeSubagents:R.includeSubagents,archived:R.archived??!1,lastMessageTime:R.lastMessageTime,projectPath:U.resolve(R.projectPath),sessionId:R.sessionId}}catch{throw Error("Invalid session cursor")}}function y(_){let E="";for(let R=0;R<_.length;R+=1)E+=_.charCodeAt(R).toString(16).padStart(4,"0");return E}function $_(_){if(!_.cursor)return;let E=W_(_.cursor);if(E.cwd!==_.cwd||E.includeSubagents!==_.includeSubagents||(E.archived??!1)!==_.archived)throw Error("Session cursor scope does not match this query");return E}function z_(_={}){let{cwd:E,cursor:R,limit:W,includeSubagents:$=!1,archived:H=!1}=_;if(E!==void 0&&!U.isAbsolute(E))throw Error("Session catalog cwd must be absolute");let k=W===void 0?s:W;if(!Number.isInteger(k)||k<1||k>t)throw Error("Session catalog limit must be an integer from 1 to 100");return{cwd:E===void 0?null:U.resolve(E),cursor:R??void 0,limit:k,includeSubagents:$,archived:H}}function k_(_,E){if(_.lastMessageTime>E.lastMessageTime)return-1;if(_.lastMessageTime<E.lastMessageTime)return 1;if(_.projectPath<E.projectPath)return-1;if(_.projectPath>E.projectPath)return 1;if(_.sessionId<E.sessionId)return-1;if(_.sessionId>E.sessionId)return 1;return 0}function f_(_,E){let R=[..._],W=$_(E);if(W)R=R.filter((k)=>k_(k,{sessionId:W.sessionId,projectPath:W.projectPath,lastMessageTime:W.lastMessageTime})>0);let $=R.slice(0,E.limit);if($.length===0||R.length<=$.length)return{sessions:$};let H=$[$.length-1];return{sessions:$,nextCursor:R_({version:1,cwd:E.cwd,includeSubagents:E.includeSubagents,archived:E.archived,lastMessageTime:H.lastMessageTime,projectPath:H.projectPath,sessionId:H.sessionId})}}function H_(_){return _.type==="message_created"||_.type==="part_created"||_.type==="part_updated"||_.type==="turn_started"||_.type==="turn_completed"||_.type==="turn_aborted"||_.type==="interaction_requested"||_.type==="interaction_responded"||_.type==="interaction_recovered"||_.type==="review_started"||_.type==="review_completed"}function J(_){return _.type==="message_created"&&_.data.role==="user"&&(_.data.inboxMessageId!==void 0||_.data.parentMessageId===void 0)}function u(_,E){let R=_.find((W)=>J(W)&&W.data.messageId===E);if(!R)throw Error(`Rewind checkpoint not found: ${E}`);return{messageId:E,preview:c(_,E),createdAt:R.data.createdAt}}function c(_,E){let R=_.flatMap((W)=>{if(W.type!=="part_created"||W.data.messageId!==E)return[];if(W.data.partType==="text"){let $=W.data.payload;return typeof $.text==="string"?[$.text]:[]}if(W.data.partType==="image")return["[Image]"];return[]}).join("").trim();if(R.length<=160)return R;return`${R.slice(0,160)}...`}function S(_,E){u(_,E);let R=_.findIndex((k)=>k.type==="message_created"&&k.data.messageId===E),W=_[R],$=W?.type==="message_created"?W.data.inboxMessageId:void 0,H=new Set(_.flatMap((k)=>k.type==="turn_started"&&$&&k.data.inputMessageIds?.includes($)?[k.data.turnId]:[]));return _.filter((k,M)=>{if((k.type==="turn_started"||k.type==="turn_completed"||k.type==="turn_aborted")&&H.has(k.data.turnId))return!1;return M<R||!H_(k)})}function w(_){let E=[];for(let R of _){if(R.type!=="session_rewound"){E.push(R);continue}if(u(E,R.data.targetMessageId),R.data.mode!=="code")E=S(E,R.data.targetMessageId)}return E}function q_(_){let E=w(_);return E.filter(J).map((R)=>({messageId:R.data.messageId,preview:c(E,R.data.messageId),createdAt:R.data.createdAt})).reverse()}function y_(_,E){let R=w(_),W=u(R,E),$=R.findIndex((k)=>k.type==="message_created"&&k.data.messageId===E),H=R.slice($);return{checkpoint:W,projectedEntries:S(R,E),removedTurns:H.filter(J).length,snapshotMessageIds:H.flatMap((k)=>k.type==="part_created"&&k.data.partType==="tool_call"?[k.data.partId]:[])}}import*as f from"node:fs";import{createReadStream as M_}from"node:fs";import*as V from"node:fs/promises";import*as O from"node:path";import{createInterface as Q_}from"node:readline";var m=65536;function x(_){let E=_.data;if(E===null||typeof E!=="object"||Array.isArray(E))throw Error("Session event data must be a JSON object");return JSON.stringify(_)}function V_(_,E,R){let W=_.trim();if(!W)return;try{return JSON.parse(W)}catch($){throw Error(`Invalid session JSONL in ${R} at line ${E}`,{cause:$})}}function z(_,E="session transcript"){let R=_.split(`
1
+ import{Lf as i}from"./chunk-amm23yvd.js";import{eg as o,gg as C,ig as L,mg as j,ng as n}from"./chunk-f20mb84y.js";import{og as I}from"./chunk-d3h8cgs8.js";import{stat as d}from"node:fs/promises";import B from"node:path";import*as U from"node:path";var s=50,t=100,e=/^[A-Za-z0-9_-]+$/,__=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?(?:Z|[+-]\d{2}:\d{2})$/;function E_(_){return typeof _==="string"&&__.test(_)&&Number.isFinite(Date.parse(_))}function P(_){return typeof _==="string"&&U.isAbsolute(_)}function R_(_){return Buffer.from(JSON.stringify(_),"utf8").toString("base64url")}function W_(_){try{if(!e.test(_))throw Error("invalid");let E=Buffer.from(_,"base64url").toString("utf8");if(Buffer.from(E,"utf8").toString("base64url")!==_)throw Error("invalid");let R=JSON.parse(E);if(R.version!==1||typeof R.includeSubagents!=="boolean"||R.archived!==void 0&&typeof R.archived!=="boolean"||!(R.cwd===null||P(R.cwd))||!E_(R.lastMessageTime)||!P(R.projectPath)||!C(R.sessionId))throw Error("invalid");return{version:1,cwd:R.cwd===null?null:U.resolve(R.cwd),includeSubagents:R.includeSubagents,archived:R.archived??!1,lastMessageTime:R.lastMessageTime,projectPath:U.resolve(R.projectPath),sessionId:R.sessionId}}catch{throw Error("Invalid session cursor")}}function y(_){let E="";for(let R=0;R<_.length;R+=1)E+=_.charCodeAt(R).toString(16).padStart(4,"0");return E}function $_(_){if(!_.cursor)return;let E=W_(_.cursor);if(E.cwd!==_.cwd||E.includeSubagents!==_.includeSubagents||(E.archived??!1)!==_.archived)throw Error("Session cursor scope does not match this query");return E}function z_(_={}){let{cwd:E,cursor:R,limit:W,includeSubagents:$=!1,archived:H=!1}=_;if(E!==void 0&&!U.isAbsolute(E))throw Error("Session catalog cwd must be absolute");let k=W===void 0?s:W;if(!Number.isInteger(k)||k<1||k>t)throw Error("Session catalog limit must be an integer from 1 to 100");return{cwd:E===void 0?null:U.resolve(E),cursor:R??void 0,limit:k,includeSubagents:$,archived:H}}function k_(_,E){if(_.lastMessageTime>E.lastMessageTime)return-1;if(_.lastMessageTime<E.lastMessageTime)return 1;if(_.projectPath<E.projectPath)return-1;if(_.projectPath>E.projectPath)return 1;if(_.sessionId<E.sessionId)return-1;if(_.sessionId>E.sessionId)return 1;return 0}function f_(_,E){let R=[..._],W=$_(E);if(W)R=R.filter((k)=>k_(k,{sessionId:W.sessionId,projectPath:W.projectPath,lastMessageTime:W.lastMessageTime})>0);let $=R.slice(0,E.limit);if($.length===0||R.length<=$.length)return{sessions:$};let H=$[$.length-1];return{sessions:$,nextCursor:R_({version:1,cwd:E.cwd,includeSubagents:E.includeSubagents,archived:E.archived,lastMessageTime:H.lastMessageTime,projectPath:H.projectPath,sessionId:H.sessionId})}}function H_(_){return _.type==="message_created"||_.type==="part_created"||_.type==="part_updated"||_.type==="turn_started"||_.type==="turn_completed"||_.type==="turn_aborted"||_.type==="interaction_requested"||_.type==="interaction_responded"||_.type==="interaction_recovered"||_.type==="review_started"||_.type==="review_completed"}function J(_){return _.type==="message_created"&&_.data.role==="user"&&(_.data.inboxMessageId!==void 0||_.data.parentMessageId===void 0)}function u(_,E){let R=_.find((W)=>J(W)&&W.data.messageId===E);if(!R)throw Error(`Rewind checkpoint not found: ${E}`);return{messageId:E,preview:c(_,E),createdAt:R.data.createdAt}}function c(_,E){let R=_.flatMap((W)=>{if(W.type!=="part_created"||W.data.messageId!==E)return[];if(W.data.partType==="text"){let $=W.data.payload;return typeof $.text==="string"?[$.text]:[]}if(W.data.partType==="image")return["[Image]"];return[]}).join("").trim();if(R.length<=160)return R;return`${R.slice(0,160)}...`}function S(_,E){u(_,E);let R=_.findIndex((k)=>k.type==="message_created"&&k.data.messageId===E),W=_[R],$=W?.type==="message_created"?W.data.inboxMessageId:void 0,H=new Set(_.flatMap((k)=>k.type==="turn_started"&&$&&k.data.inputMessageIds?.includes($)?[k.data.turnId]:[]));return _.filter((k,M)=>{if((k.type==="turn_started"||k.type==="turn_completed"||k.type==="turn_aborted")&&H.has(k.data.turnId))return!1;return M<R||!H_(k)})}function w(_){let E=[];for(let R of _){if(R.type!=="session_rewound"){E.push(R);continue}if(u(E,R.data.targetMessageId),R.data.mode!=="code")E=S(E,R.data.targetMessageId)}return E}function q_(_){let E=w(_);return E.filter(J).map((R)=>({messageId:R.data.messageId,preview:c(E,R.data.messageId),createdAt:R.data.createdAt})).reverse()}function y_(_,E){let R=w(_),W=u(R,E),$=R.findIndex((k)=>k.type==="message_created"&&k.data.messageId===E),H=R.slice($);return{checkpoint:W,projectedEntries:S(R,E),removedTurns:H.filter(J).length,snapshotMessageIds:H.flatMap((k)=>k.type==="part_created"&&k.data.partType==="tool_call"?[k.data.partId]:[])}}import*as f from"node:fs";import{createReadStream as M_}from"node:fs";import*as V from"node:fs/promises";import*as O from"node:path";import{createInterface as Q_}from"node:readline";var m=65536;function x(_){let E=_.data;if(E===null||typeof E!=="object"||Array.isArray(E))throw Error("Session event data must be a JSON object");return JSON.stringify(_)}function V_(_,E,R){let W=_.trim();if(!W)return;try{return JSON.parse(W)}catch($){throw Error(`Invalid session JSONL in ${R} at line ${E}`,{cause:$})}}function z(_,E="session transcript"){let R=_.split(`
2
2
  `),W=!_.endsWith(`
3
3
  `),$=[];for(let[H,k]of R.entries())try{let M=V_(k,H+1,E);if(M){if(typeof M.seq!=="number")M.seq=$.length+1;$.push(M)}}catch(M){if(W&&H===R.length-1)break;throw M}return $}class Y{static appendQueues=new Map;filePath;constructor(_){this.filePath=_}static maxSeq(_){let E=0;for(let R of _)if(typeof R.seq==="number"&&R.seq>E)E=R.seq;return E}static stampSeqFrom(_,E){let R=E;return _.map((W)=>{if(typeof W.seq==="number"){if(W.seq>R)R=W.seq;return W}return R+=1,{...W,seq:R}})}static stampSeq(_,E){return Y.stampSeqFrom(_,Y.maxSeq(E))}async append(_){try{let[E]=await this.appendEntries([_]);return E}catch(E){throw console.error(`[JSONLStore] 追加写入失败: ${this.filePath}`,E),E}}async appendBatch(_){try{return await this.appendEntries(_)}catch(E){throw console.error(`[JSONLStore] 批量追加写入失败: ${this.filePath}`,E),E}}async appendEntries(_){if(_.length===0)return[];return this.enqueue(async()=>{await V.mkdir(O.dirname(this.filePath),{recursive:!0,mode:493});let E=await V.open(this.filePath,"a+",384);try{let R=await this.repairIncompleteTail(E),W=await this.readTailSeq(E),$=Y.stampSeqFrom(_,W),H=`${$.map(x).join(`
4
4
  `)}
@@ -113,4 +113,4 @@ CREATE VIRTUAL TABLE IF NOT EXISTS parts_fts USING fts5(
113
113
  ORDER BY timestamp DESC LIMIT ?`:`SELECT session_id, role, timestamp, text FROM parts_fts
114
114
  WHERE parts_fts MATCH ?
115
115
  ORDER BY timestamp DESC LIMIT ?`,M=_.prepare(k);return R?M.all(H,R,W):M.all(H,W)}
116
- export{w as uc,q_ as vc,y_ as wc,z as xc,Y as yc,y as zc,$_ as Ac,z_ as Bc,k_ as Cc,f_ as Dc,r as Ec,K_ as Fc,U_ as Gc,B_ as Hc,A_ as Ic,n_ as Jc,i_ as Kc,d_ as Lc};
116
+ export{w as zc,q_ as Ac,y_ as Bc,z as Cc,Y as Dc,y as Ec,$_ as Fc,z_ as Gc,k_ as Hc,f_ as Ic,r as Jc,K_ as Kc,U_ as Lc,B_ as Mc,A_ as Nc,n_ as Oc,i_ as Pc,d_ as Qc};
@@ -1,2 +1,2 @@
1
1
  import{nanoid as q}from"nanoid";var u=/^[A-Za-z0-9][A-Za-z0-9._-]*$/;function B(j="session",m=21){if(!u.test(j))throw Error(`Invalid session ID prefix: ${j}`);return`${j}-${q(m)}`}
2
- export{B as yd};
2
+ export{B as Dd};
@@ -1,4 +1,4 @@
1
- import{qf as En,rf as j,sf as T}from"./chunk-3ck3fxff.js";import{wf as On,xf as Zn}from"./chunk-x1r4b7pt.js";import{Cf as L}from"./chunk-7fgx7ztz.js";import{Gf as $n}from"./chunk-75y3mb0z.js";import{Jf as rt,Mf as p}from"./chunk-y5rsamex.js";import{Uf as sn,Vf as wn}from"./chunk-azcjz03h.js";import{Zf as $}from"./chunk-7xytd1h7.js";import{hg as Sn}from"./chunk-q4q0r97b.js";var et=/^[\x21\x23-\x5b\x5d-\x7e]+$/;function St(n){return n==="127.0.0.1"||n==="[::1]"||n.toLowerCase()==="localhost"}function B(n,t="MCP OAuth URL"){let M=new URL(n);if(M.username||M.password)throw Error(`${t} must not contain credentials`);if(M.protocol!=="https:"&&!(M.protocol==="http:"&&St(M.hostname)))throw Error(`${t} requires HTTPS; HTTP is allowed only for loopback servers`);return M}var U=async(n,t)=>{B(n,"MCP OAuth request URL");let M=await fetch(n,{...t,redirect:"manual"});if(M.status>=300&&M.status<400)throw await M.body?.cancel(),Error("MCP OAuth network requests must not follow redirects");return M};function y(n){let t=n.oauth;if(!t)return;let M=t;for(let S of["clientSecret","authorizationUrl","tokenUrl","redirectUri"])if(M[S]!==void 0)throw Error(`MCP OAuth "${S}" is not supported; use standards-based discovery`);if(t.enabled!==!0)return{enabled:!1};if(n.type!=="http"&&n.type!=="sse")throw Error("MCP OAuth is supported only for HTTP and SSE transports");if(!n.url)throw Error("MCP OAuth requires an MCP server URL");if(B(n.url,"MCP OAuth server URL"),Object.keys(n.headers??{}).find((S)=>S.toLowerCase()==="authorization"))throw Error("MCP OAuth cannot be combined with a configured Authorization header");let _=t.clientId?.trim();if(_&&_.length>4096)throw Error("MCP OAuth clientId exceeds 4096 characters");let e=t.scopes?.map((S)=>S.trim());if(e){if(e.length>32)throw Error("MCP OAuth supports at most 32 scopes");if(e.some((S)=>!S||S.length>128||!et.test(S)))throw Error("MCP OAuth scopes contain an invalid value");if(new Set(e).size!==e.length)throw Error("MCP OAuth scopes must not contain duplicates")}let r=t.callbackPort;if(r!==void 0&&(!Number.isInteger(r)||r<1024||r>65535))throw Error("MCP OAuth callbackPort must be between 1024 and 65535");return{enabled:!0,..._?{clientId:_}:{},...e?.length?{scopes:e}:{},...r!==void 0?{callbackPort:r}:{}}}import{randomUUID as l}from"node:crypto";import xt from"node:http";import{auth as Tn}from"@modelcontextprotocol/sdk/client/auth.js";import $t from"open";import{createHash as Et,randomUUID as mt}from"node:crypto";import{constants as D,promises as P}from"node:fs";import W from"node:path";import{Mutex as At}from"async-mutex";import Tt from"write-file-atomic";var mn=1,bt=1048576,ct=5000,ot=50,st=/^[a-f0-9]{64}$/,wt=T.Object({client_id:T.String({minLength:1,maxLength:4096})},{additionalProperties:!0}),Lt=T.Object({access_token:T.String({minLength:1,maxLength:65536}),token_type:T.String({minLength:1,maxLength:64}),expires_in:T.Optional(T.Number({minimum:0})),refresh_token:T.Optional(T.String({minLength:1,maxLength:65536})),scope:T.Optional(T.String({maxLength:16384})),id_token:T.Optional(T.String({minLength:1,maxLength:262144}))},{additionalProperties:!1}),ft=T.Unsafe({type:"object",properties:{authorizationServerUrl:T.String({format:"uri"}),resourceMetadataUrl:T.Optional(T.String({format:"uri"})),resourceMetadata:T.Optional(T.Unknown()),authorizationServerMetadata:T.Optional(T.Unknown())},required:["authorizationServerUrl"],additionalProperties:!1}),An=T.Object({serverUrl:T.String({format:"uri"}),clientId:T.Optional(T.String({minLength:1,maxLength:4096})),clientInformation:T.Optional(wt),tokens:T.Optional(Lt),tokenExpiresAt:T.Optional(T.Number({minimum:0})),discoveryState:T.Optional(ft),updatedAt:T.String({format:"date-time"})},{additionalProperties:!1}),rn=T.Object({version:T.Literal(mn),credentials:T.Record(T.String(),An)},{additionalProperties:!1});function q(n,t){return n instanceof Error&&"code"in n&&n.code===t}function Pt(n){if(!Number.isInteger(n)||n<=0)return!1;try{return process.kill(n,0),!0}catch(t){return q(t,"EPERM")}}function k(n){return structuredClone(n)}function en(n){if(Object.keys(n.credentials).some((t)=>!st.test(t)))throw Error("MCP OAuth credential store contains an invalid identity")}function G(n){let t=new URL(n);return t.hash="",t.toString()}function F(n,t,M=[]){return Et("sha256").update(JSON.stringify({serverUrl:G(n),clientId:t?.trim()||null,scopes:[...M].sort()})).digest("hex")}class I{static mutexes=new Map;stateRoot;tokenFilePath;mutex;constructor(n=Sn()){this.stateRoot=W.join(n,"mcp"),this.tokenFilePath=W.join(this.stateRoot,"oauth-credentials.json");let t=I.mutexes.get(this.tokenFilePath);if(!t)t=new At,I.mutexes.set(this.tokenFilePath,t);this.mutex=t}async getCredential(n){return this.mutex.runExclusive(async()=>{let M=(await this.readStore()).credentials[n];return M?k(M):null})}async updateCredential(n,t){return this.runMutation(async(M)=>{let u=M.credentials[n],_=await t(u?k(u):null);if(_)M.credentials[n]=j(An,_);else delete M.credentials[n];return _?k(M.credentials[n]):null})}async deleteCredential(n){await this.updateCredential(n,()=>null)}async listCredentialIds(){return this.mutex.runExclusive(async()=>Object.keys((await this.readStore()).credentials).sort())}async runMutation(n){return this.mutex.runExclusive(async()=>{let t=await this.acquireStoreLock();try{let M=await this.readStore(),u=await n(M);return await this.writeStore(M),u}finally{await t()}})}async ensureStateRoot(){await P.mkdir(this.stateRoot,{recursive:!0,mode:448});let n=await P.lstat(this.stateRoot);if(!n.isDirectory()||n.isSymbolicLink())throw Error("MCP OAuth credential root must be a regular directory");if(process.getuid&&n.uid!==process.getuid())throw Error("MCP OAuth credential root must be owned by the current user");if((n.mode&63)!==0)throw Error("MCP OAuth credential root permissions must not allow group access")}async readStore(){try{let n=await P.lstat(this.tokenFilePath);if(!n.isFile()||n.isSymbolicLink())throw Error("MCP OAuth credential store must be a regular file");if(process.getuid&&n.uid!==process.getuid())throw Error("MCP OAuth credential store must be owned by the current user");if((n.mode&511)!==384)throw Error("MCP OAuth credential store permissions must be 0600");if(n.size>bt)throw Error("MCP OAuth credential store exceeds the 1 MiB limit");let t=JSON.parse(await P.readFile(this.tokenFilePath,"utf8")),M=En(rn,t);if(!M.success)throw Error("MCP OAuth credential store has an invalid schema");return en(M.data),M.data}catch(n){if(q(n,"ENOENT"))return{version:mn,credentials:{}};throw n}}async writeStore(n){await this.ensureStateRoot();let t=j(rn,n);en(t),await Tt(this.tokenFilePath,`${JSON.stringify(t,null,2)}
1
+ import{vf as En,wf as j,xf as T}from"./chunk-qj6gafse.js";import{Bf as On,Cf as Zn}from"./chunk-5hn788xk.js";import{Hf as L}from"./chunk-2rsr3bte.js";import{Lf as $n}from"./chunk-amm23yvd.js";import{Of as rt,Rf as p}from"./chunk-40654rh3.js";import{Zf as sn,_f as wn}from"./chunk-91vwv4ph.js";import{cg as $}from"./chunk-23bkpq26.js";import{mg as Sn}from"./chunk-f20mb84y.js";var et=/^[\x21\x23-\x5b\x5d-\x7e]+$/;function St(n){return n==="127.0.0.1"||n==="[::1]"||n.toLowerCase()==="localhost"}function B(n,t="MCP OAuth URL"){let M=new URL(n);if(M.username||M.password)throw Error(`${t} must not contain credentials`);if(M.protocol!=="https:"&&!(M.protocol==="http:"&&St(M.hostname)))throw Error(`${t} requires HTTPS; HTTP is allowed only for loopback servers`);return M}var U=async(n,t)=>{B(n,"MCP OAuth request URL");let M=await fetch(n,{...t,redirect:"manual"});if(M.status>=300&&M.status<400)throw await M.body?.cancel(),Error("MCP OAuth network requests must not follow redirects");return M};function y(n){let t=n.oauth;if(!t)return;let M=t;for(let S of["clientSecret","authorizationUrl","tokenUrl","redirectUri"])if(M[S]!==void 0)throw Error(`MCP OAuth "${S}" is not supported; use standards-based discovery`);if(t.enabled!==!0)return{enabled:!1};if(n.type!=="http"&&n.type!=="sse")throw Error("MCP OAuth is supported only for HTTP and SSE transports");if(!n.url)throw Error("MCP OAuth requires an MCP server URL");if(B(n.url,"MCP OAuth server URL"),Object.keys(n.headers??{}).find((S)=>S.toLowerCase()==="authorization"))throw Error("MCP OAuth cannot be combined with a configured Authorization header");let _=t.clientId?.trim();if(_&&_.length>4096)throw Error("MCP OAuth clientId exceeds 4096 characters");let e=t.scopes?.map((S)=>S.trim());if(e){if(e.length>32)throw Error("MCP OAuth supports at most 32 scopes");if(e.some((S)=>!S||S.length>128||!et.test(S)))throw Error("MCP OAuth scopes contain an invalid value");if(new Set(e).size!==e.length)throw Error("MCP OAuth scopes must not contain duplicates")}let r=t.callbackPort;if(r!==void 0&&(!Number.isInteger(r)||r<1024||r>65535))throw Error("MCP OAuth callbackPort must be between 1024 and 65535");return{enabled:!0,..._?{clientId:_}:{},...e?.length?{scopes:e}:{},...r!==void 0?{callbackPort:r}:{}}}import{randomUUID as l}from"node:crypto";import xt from"node:http";import{auth as Tn}from"@modelcontextprotocol/sdk/client/auth.js";import $t from"open";import{createHash as Et,randomUUID as mt}from"node:crypto";import{constants as D,promises as P}from"node:fs";import W from"node:path";import{Mutex as At}from"async-mutex";import Tt from"write-file-atomic";var mn=1,bt=1048576,ct=5000,ot=50,st=/^[a-f0-9]{64}$/,wt=T.Object({client_id:T.String({minLength:1,maxLength:4096})},{additionalProperties:!0}),Lt=T.Object({access_token:T.String({minLength:1,maxLength:65536}),token_type:T.String({minLength:1,maxLength:64}),expires_in:T.Optional(T.Number({minimum:0})),refresh_token:T.Optional(T.String({minLength:1,maxLength:65536})),scope:T.Optional(T.String({maxLength:16384})),id_token:T.Optional(T.String({minLength:1,maxLength:262144}))},{additionalProperties:!1}),ft=T.Unsafe({type:"object",properties:{authorizationServerUrl:T.String({format:"uri"}),resourceMetadataUrl:T.Optional(T.String({format:"uri"})),resourceMetadata:T.Optional(T.Unknown()),authorizationServerMetadata:T.Optional(T.Unknown())},required:["authorizationServerUrl"],additionalProperties:!1}),An=T.Object({serverUrl:T.String({format:"uri"}),clientId:T.Optional(T.String({minLength:1,maxLength:4096})),clientInformation:T.Optional(wt),tokens:T.Optional(Lt),tokenExpiresAt:T.Optional(T.Number({minimum:0})),discoveryState:T.Optional(ft),updatedAt:T.String({format:"date-time"})},{additionalProperties:!1}),rn=T.Object({version:T.Literal(mn),credentials:T.Record(T.String(),An)},{additionalProperties:!1});function q(n,t){return n instanceof Error&&"code"in n&&n.code===t}function Pt(n){if(!Number.isInteger(n)||n<=0)return!1;try{return process.kill(n,0),!0}catch(t){return q(t,"EPERM")}}function k(n){return structuredClone(n)}function en(n){if(Object.keys(n.credentials).some((t)=>!st.test(t)))throw Error("MCP OAuth credential store contains an invalid identity")}function G(n){let t=new URL(n);return t.hash="",t.toString()}function F(n,t,M=[]){return Et("sha256").update(JSON.stringify({serverUrl:G(n),clientId:t?.trim()||null,scopes:[...M].sort()})).digest("hex")}class I{static mutexes=new Map;stateRoot;tokenFilePath;mutex;constructor(n=Sn()){this.stateRoot=W.join(n,"mcp"),this.tokenFilePath=W.join(this.stateRoot,"oauth-credentials.json");let t=I.mutexes.get(this.tokenFilePath);if(!t)t=new At,I.mutexes.set(this.tokenFilePath,t);this.mutex=t}async getCredential(n){return this.mutex.runExclusive(async()=>{let M=(await this.readStore()).credentials[n];return M?k(M):null})}async updateCredential(n,t){return this.runMutation(async(M)=>{let u=M.credentials[n],_=await t(u?k(u):null);if(_)M.credentials[n]=j(An,_);else delete M.credentials[n];return _?k(M.credentials[n]):null})}async deleteCredential(n){await this.updateCredential(n,()=>null)}async listCredentialIds(){return this.mutex.runExclusive(async()=>Object.keys((await this.readStore()).credentials).sort())}async runMutation(n){return this.mutex.runExclusive(async()=>{let t=await this.acquireStoreLock();try{let M=await this.readStore(),u=await n(M);return await this.writeStore(M),u}finally{await t()}})}async ensureStateRoot(){await P.mkdir(this.stateRoot,{recursive:!0,mode:448});let n=await P.lstat(this.stateRoot);if(!n.isDirectory()||n.isSymbolicLink())throw Error("MCP OAuth credential root must be a regular directory");if(process.getuid&&n.uid!==process.getuid())throw Error("MCP OAuth credential root must be owned by the current user");if((n.mode&63)!==0)throw Error("MCP OAuth credential root permissions must not allow group access")}async readStore(){try{let n=await P.lstat(this.tokenFilePath);if(!n.isFile()||n.isSymbolicLink())throw Error("MCP OAuth credential store must be a regular file");if(process.getuid&&n.uid!==process.getuid())throw Error("MCP OAuth credential store must be owned by the current user");if((n.mode&511)!==384)throw Error("MCP OAuth credential store permissions must be 0600");if(n.size>bt)throw Error("MCP OAuth credential store exceeds the 1 MiB limit");let t=JSON.parse(await P.readFile(this.tokenFilePath,"utf8")),M=En(rn,t);if(!M.success)throw Error("MCP OAuth credential store has an invalid schema");return en(M.data),M.data}catch(n){if(q(n,"ENOENT"))return{version:mn,credentials:{}};throw n}}async writeStore(n){await this.ensureStateRoot();let t=j(rn,n);en(t),await Tt(this.tokenFilePath,`${JSON.stringify(t,null,2)}
2
2
  `,{mode:384,encoding:"utf8"}),await P.chmod(this.tokenFilePath,384)}async acquireStoreLock(){await this.ensureStateRoot();let n=W.join(this.stateRoot,".oauth-credentials.lock"),t=mt(),M=Date.now()+ct;while(Date.now()<M)try{let u=await P.open(n,D.O_CREAT|D.O_EXCL|D.O_WRONLY,384);return await u.writeFile(`${JSON.stringify({version:1,pid:process.pid,token:t,createdAt:new Date().toISOString()})}
3
3
  `,"utf8"),await u.close(),async()=>{try{if(JSON.parse(await P.readFile(n,"utf8")).token===t)await P.unlink(n)}catch(_){if(!q(_,"ENOENT"))throw _}}}catch(u){if(!q(u,"EEXIST"))throw u;await this.removeDeadLock(n),await new Promise((_)=>setTimeout(_,ot))}throw Error("MCP OAuth credential store is busy; retry the operation")}async removeDeadLock(n){let t=await P.lstat(n);if(!t.isFile()||t.isSymbolicLink())throw Error("MCP OAuth credential lock must be a regular file");if(process.getuid&&t.uid!==process.getuid()||(t.mode&511)!==384)throw Error("MCP OAuth credential lock ownership or permissions are invalid");let M=JSON.parse(await P.readFile(n,"utf8"));if(typeof M.pid!=="number"||!Number.isInteger(M.pid)||M.pid<=0)throw Error("MCP OAuth credential lock owner is invalid");if(!Pt(M.pid))await P.unlink(n)}}var bn="127.0.0.1",cn=7777,on="/oauth/callback",dt=300000;class v extends Error{constructor(n){super(`MCP server "${n}" requires OAuth authorization; run "blade mcp login ${n}" or use the Web MCP panel`);this.name="McpOAuthAuthorizationRequiredError"}}class Ln extends Error{constructor(n){super(`MCP OAuth credentials are unavailable in this runtime for server "${n}"`);this.name="McpOAuthUnavailableError"}}function Xt(n){let t=n?"Authentication complete":"Authentication failed";return`<!doctype html>
4
4
  <html lang="en">
@@ -41,4 +41,4 @@ ${M.map((u)=>` - ${u}`).join(`
41
41
  ]
42
42
  }
43
43
  `)}}function Uu(n,t={}){let M={...n};if(t.debug!==void 0)M.debug=t.debug===""?!0:t.debug;if(t.model){if(!n.models.some((_)=>_.id===t.model))throw Error(`模型配置未找到: ${t.model}`);M.currentModelId=t.model}if(t.yolo===!0)M.permissionMode="yolo";else if(t.permissionMode!==void 0)M.permissionMode=t.permissionMode;if(t.maxTurns!==void 0)M.maxTurns=t.maxTurns;if(t.maxConcurrentTasks!==void 0)M.maxConcurrentTasks=t.maxConcurrentTasks;if(t.maxQueuedTasks!==void 0)M.maxQueuedTasks=t.maxQueuedTasks;return M.systemPrompt=t.systemPrompt,M.appendSystemPrompt=t.appendSystemPrompt,M.model=t.model,M.resumeSessionId=t.sessionId,M.forkSession=t.forkSession,M.allowedTools=t.allowedTools,M.disallowedTools=t.disallowedTools,M.mcpConfigPaths=t.mcpConfig,M.strictMcpConfig=t.strictMcpConfig,M.addDirs=t.addDir,M.outputFormat=t.outputFormat,M.inputFormat=t.inputFormat,M.print=t.print,M.includePartialMessages=t.includePartialMessages,M.replayUserMessages=t.replayUserMessages,M.agentsConfig=t.agents,M.settingSources=t.settingSources,M}
44
- export{U as Be,y as Ce,I as De,v as Ee,Ln as Fe,N as Ge,Nn as He,qM as Ie,V as Je,VM as Ke,OM as Le,ZM as Me,Bn as Ne,Ut as Oe,JM as Pe,qt as Qe,QM as Re,Jn as Se,DM as Te,WM as Ue,jM as Ve,FM as We,lM as Xe,pn as Ye,vM as Ze,nu as _e,tu as $e,Mu as af,BM as bf,b as cf,d as df,gt as ef,i as ff,Q as gf,ln as hf,vn as if,nt as jf,tt as kf,Mt as lf,ut as mf,R as nf,Uu as of};
44
+ export{U as Ge,y as He,I as Ie,v as Je,Ln as Ke,N as Le,Nn as Me,qM as Ne,V as Oe,VM as Pe,OM as Qe,ZM as Re,Bn as Se,Ut as Te,JM as Ue,qt as Ve,QM as We,Jn as Xe,DM as Ye,WM as Ze,jM as _e,FM as $e,lM as af,pn as bf,vM as cf,nu as df,tu as ef,Mu as ff,BM as gf,b as hf,d as if,gt as jf,i as kf,Q as lf,ln as mf,vn as nf,nt as of,tt as pf,Mt as qf,ut as rf,R as sf,Uu as tf};
@@ -1,5 +1,5 @@
1
- import{Gf as R}from"./chunk-75y3mb0z.js";import{Kf as q,Mf as _}from"./chunk-y5rsamex.js";import{Pf as K}from"./chunk-nah8b1gv.js";var ie={openrouter:{"HTTP-Referer":"https://github.com/echoVic/blade-code","X-Title":"Blade"},cerebras:{"X-Cerebras-3rd-Party-Integration":"blade"}},N=(e)=>ie[e]||{};var se=new Set(["user-cancel","interrupt","sibling-error","timeout"]);function A(e){return typeof e==="string"&&se.has(e)}function Ne(e){if(!e.aborted)return;if(A(e.reason))return e.reason;return"user-cancel"}function je(e){if(A(e))return!0;if(!(e instanceof Error))return!1;if(e.name==="AbortError")return!0;if(e instanceof DOMException&&e.name==="AbortError")return!0;if(e.message.includes("aborted"))return!0;return!1}function U(...e){let t=e.filter(Boolean);if(t.length===0)return new AbortController().signal;if(t.length===1)return t[0];let o=AbortSignal;if(typeof o.any==="function")return o.any(t);for(let i of t)if(i.aborted)return i;let r=new AbortController,n=new Map;for(let i of t){let a=()=>{r.abort(i.reason);for(let[u,s]of n)u.removeEventListener("abort",s)};n.set(i,a)}for(let[i,a]of n)i.addEventListener("abort",a,{once:!0});return r.signal}function P(e,t,o){let r=o?.throwOnAbort??!1;if(t?.aborted){if(r)return Promise.reject(new DOMException("Aborted","AbortError"));return Promise.resolve()}return new Promise((n,i)=>{let a,u=setTimeout(()=>{if(t&&a)t.removeEventListener("abort",a);n()},e);if(t)a=()=>{if(clearTimeout(u),r)i(new DOMException("Aborted","AbortError"));else n()},t.addEventListener("abort",a,{once:!0})})}var ae=R("Chat"),ue={input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}};function E(e){if(typeof e==="string")return e;return e.filter((t)=>t.type==="text").map((t)=>t.text).join(`
1
+ import{Lf as R}from"./chunk-amm23yvd.js";import{Pf as q,Rf as _}from"./chunk-40654rh3.js";import{Uf as K}from"./chunk-k9px24b5.js";var ie={openrouter:{"HTTP-Referer":"https://github.com/echoVic/blade-code","X-Title":"Blade"},cerebras:{"X-Cerebras-3rd-Party-Integration":"blade"}},N=(e)=>ie[e]||{};var se=new Set(["user-cancel","interrupt","sibling-error","timeout"]);function A(e){return typeof e==="string"&&se.has(e)}function Ne(e){if(!e.aborted)return;if(A(e.reason))return e.reason;return"user-cancel"}function je(e){if(A(e))return!0;if(!(e instanceof Error))return!1;if(e.name==="AbortError")return!0;if(e instanceof DOMException&&e.name==="AbortError")return!0;if(e.message.includes("aborted"))return!0;return!1}function U(...e){let t=e.filter(Boolean);if(t.length===0)return new AbortController().signal;if(t.length===1)return t[0];let o=AbortSignal;if(typeof o.any==="function")return o.any(t);for(let i of t)if(i.aborted)return i;let r=new AbortController,n=new Map;for(let i of t){let a=()=>{r.abort(i.reason);for(let[u,s]of n)u.removeEventListener("abort",s)};n.set(i,a)}for(let[i,a]of n)i.addEventListener("abort",a,{once:!0});return r.signal}function P(e,t,o){let r=o?.throwOnAbort??!1;if(t?.aborted){if(r)return Promise.reject(new DOMException("Aborted","AbortError"));return Promise.resolve()}return new Promise((n,i)=>{let a,u=setTimeout(()=>{if(t&&a)t.removeEventListener("abort",a);n()},e);if(t)a=()=>{if(clearTimeout(u),r)i(new DOMException("Aborted","AbortError"));else n()},t.addEventListener("abort",a,{once:!0})})}var ae=R("Chat"),ue={input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}};function E(e){if(typeof e==="string")return e;return e.filter((t)=>t.type==="text").map((t)=>t.text).join(`
2
2
  `)}function de(e){if(!e)return{};try{let t=JSON.parse(e);return t&&typeof t==="object"&&!Array.isArray(t)?t:{}}catch{return ae.warn("[PiAIChatService] Invalid historical tool arguments",{value:e}),{}}}function ce(e){let t=e.match(/^data:([^;,]+);base64,(.+)$/s);return t?{mimeType:t[1],data:t[2]}:void 0}async function le(e,t){let o=ce(e);if(o)return{type:"image",...o};if(!/^https?:\/\//i.test(e))return{type:"text",text:`[Unsupported image source: ${e}]`};let r=await fetch(e,{signal:t});if(!r.ok)throw Error(`Failed to load image ${e}: HTTP ${r.status}`);return{type:"image",mimeType:r.headers.get("content-type")?.split(";")[0]??"image/png",data:Buffer.from(await r.arrayBuffer()).toString("base64")}}async function j(e,t,o,r,n){let i=e.filter((s)=>s.role==="system").map((s)=>E(s.content)).filter(Boolean).join(`
3
3
 
4
4
  `),a=[];for(let s of e){if(s.role==="system")continue;if(s.role==="user"){let c=t.input.includes("image"),d=typeof s.content==="string"?s.content:await Promise.all(s.content.map((l)=>l.type==="text"?Promise.resolve({type:"text",text:l.text}):c?le(l.image_url.url,r):Promise.resolve({type:"text",text:"[Image omitted: current model does not support image input]"})));a.push({role:"user",content:d,timestamp:Date.now()});continue}if(s.role==="assistant"){let c=[];if(s.reasoningContent?.trim())c.push({type:"thinking",thinking:s.reasoningContent});let d=E(s.content);if(d)c.push({type:"text",text:d});for(let l of s.tool_calls??[]){if(!("function"in l))continue;c.push({type:"toolCall",id:l.id,name:l.function.name,arguments:de(l.function.arguments)})}a.push({role:"assistant",content:c,api:t.api,provider:t.provider,model:t.id,usage:ue,stopReason:s.tool_calls?.length?"toolUse":"stop",timestamp:Date.now()});continue}a.push({role:"toolResult",toolCallId:s.tool_call_id??"",toolName:s.name??"unknown",content:[{type:"text",text:E(s.content)}],isError:!1,timestamp:Date.now()})}let u=o?.filter((s)=>!n||s.name===n).map((s)=>({name:s.name,description:s.description,parameters:s.parameters,constrainedSampling:s.constrainedSampling}));return{...i?{systemPrompt:i}:{},messages:a,...u?.length?{tools:u}:{}}}function B(e){let t=[];for(let o=0;o<e.length;o++){let r=e[o];if(r.role==="tool")continue;let n=r.role==="assistant"&&r.tool_calls?.length?r.tool_calls:void 0;if(!n){t.push(r);continue}let i=[],a=o+1;while(a<e.length&&e[a].role==="tool")i.push(e[a++]);let u=new Set(n.map((d)=>d.id)),s=i.filter((d)=>d.tool_call_id&&u.has(d.tool_call_id)),c=new Set(s.map((d)=>d.tool_call_id));if(u.size===n.length&&s.length===u.size&&c.size===u.size)t.push(r,...s);o=a-1}return t}function F(e){return e.some((t)=>t.role==="assistant"&&Boolean(t.tool_calls?.length)&&!t.reasoningContent?.trim())}function z(e,t){return{...e,...t.baseUrl?{baseUrl:q(e.api,t.baseUrl)}:{},...t.maxOutputTokens?{maxTokens:t.maxOutputTokens}:{}}}function S(e){let t=e.modelCatalog??_();return{models:t.models,model:z(t.getModel(e.provider,e.model),e)}}function V(e,t){let o=e.modelCatalog??_();return z(o.getModel(t.provider,t.model),e)}var Y=new WeakSet,me=["gousagelimiterror","freeusagelimiterror","monthly usage limit reached","available balance","insufficient_quota","out of budget","quota exceeded","billing"],pe=["prompt_too_long","prompt is too long","maximum context length","context length exceeded","context_length_exceeded","request too large"],fe=["econnreset","econnrefused","enotfound","eai_again","etimedout","fetch failed","network error","connection error","connection refused","connection lost","other side closed","socket hang up","socket connection was closed","upstream connect","reset before headers","websocket closed","websocket error","http2 request did not get a response"];function H(e){return(e instanceof Error?e.message:String(e)).toLowerCase()}function he(e){let t=H(e);return pe.some((o)=>t.includes(o))}function X(e){if(e!==null&&typeof e==="object")Y.add(e)}function Xe(e){return e!==null&&typeof e==="object"&&Y.has(e)}function ye(e){return e!==null&&typeof e==="object"&&"code"in e?e.code:void 0}function ge(e){if(e===null||typeof e!=="object")return;let t=e;for(let o of["status","statusCode"]){let r=t[o];if(typeof r==="number"&&Number.isInteger(r))return r}return}function be(e){let t=e.match(/^(?:error:\s*)?(\d{3})\b/),o=e.match(/\b(?:status(?:\s+code)?|http)[:\s]+(\d{3})\b/),r=Number(t?.[1]??o?.[1]);return Number.isInteger(r)?r:void 0}function T(e,t){let o=H(e),r=ye(e);if(r==="STREAM_IDLE_TIMEOUT"||e instanceof Error&&e.name==="AbortError"||o.includes("request aborted")||o==="aborted")return{retryable:!1};if(me.some((i)=>o.includes(i))||he(e))return{retryable:!1};if(t?.shouldRetry==="false")return{retryable:!1,statusCode:t.statusCode};let n=t?.statusCode??ge(e)??be(o);if(t?.shouldRetry==="true")return{retryable:!0,reason:n===429?"rate_limit":n===408||n===409?"timeout":"server_error",statusCode:n};if(n===429)return{retryable:!0,reason:"rate_limit",statusCode:n};if(n===408||n===409)return{retryable:!0,reason:"timeout",statusCode:n};if(n!==void 0&&n>=500&&n<=599)return{retryable:!0,reason:"server_error",statusCode:n};if(r==="PROVIDER_STREAM_CLOSED"||o.includes("stream closed before completion")||o.includes("ended without")||o.includes("stream ended before"))return{retryable:!0,reason:"stream_closed",statusCode:n};if(fe.some((i)=>o.includes(i)))return{retryable:!0,reason:"transport",statusCode:n};if(o.includes("timeout")||o.includes("timed out")||o.includes("temporarily unavailable")||o.includes("upstream_error")||o.includes("overloaded")||o.includes("rate limit")||o.includes("too many requests")||o.includes("service unavailable")||o.includes("server error")||o.includes("internal error")||o.includes("please retry")||o.includes("try your request again"))return{retryable:!0,reason:o.includes("rate")||o.includes("too many")?"rate_limit":o.includes("timeout")||o.includes("timed out")?"timeout":"server_error",statusCode:n};return{retryable:!1,statusCode:n}}function Ce(e,t){if(!e)return;if(e.retryAfterMs!==void 0){let n=Number.parseFloat(e.retryAfterMs);if(Number.isFinite(n))return Math.max(0,n)}if(e.retryAfter===void 0)return;let o=Number.parseFloat(e.retryAfter);if(Number.isFinite(o))return Math.max(0,o*1000);let r=Date.parse(e.retryAfter);return Number.isFinite(r)?Math.max(0,r-t):void 0}function G(e,t,o={}){let r=o.now??Date.now(),n=o.maxDelayMs??60000,i=Ce(t,r);if(i!==void 0)return Math.min(Math.ceil(i),n);let a=Math.max(0,e-1),u=Math.min(500*2**a,8000),s=Math.max(0,Math.min(1,o.random??Math.random())),c=u*(0.75+s*0.25);return Math.min(Math.round(c),n)}function J(e,t){let o=e.onPayload;e.onPayload=async(r,n)=>{let i=o?await o(r,n):r;return t(i===void 0?r:i,n)}}function Me(e){if(!e.reasoningEnabled)return;return e.reasoningEffort??e.reasoningLevel??"high"}function Re(e){switch(e){case"minimal":return"MINIMAL";case"low":return"LOW";case"medium":return"MEDIUM";default:return"HIGH"}}function xe(e,t,o,r){let n=r?void 0:Me(o);if(!n){if(t.api==="anthropic-messages")e.thinkingEnabled=!1;if(t.api==="google-generative-ai"||t.api==="google-vertex")e.thinking={enabled:!1};return}switch(t.api){case"anthropic-messages":e.thinkingEnabled=!0,e.effort=n;break;case"google-generative-ai":case"google-vertex":e.thinking={enabled:!0,level:Re(n)};break;case"mistral-conversations":e.reasoningEffort="high";break;case"bedrock-converse-stream":case"pi-messages":e.reasoning=n;break;default:e.reasoningEffort=n}}function ve(e,t,o){if(!o)return;switch(t){case"anthropic-messages":case"bedrock-converse-stream":e.toolChoice={type:"tool",name:o};break;case"openai-completions":case"mistral-conversations":case"pi-messages":e.toolChoice={type:"function",function:{name:o}};break;case"openai-responses":case"openai-codex-responses":case"azure-openai-responses":e.toolChoice={type:"function",name:o};break;case"google-generative-ai":case"google-vertex":e.toolChoice="any";break}}function Te(e,t,o){let r=o.serviceTier;if(!r)return;if(t.api==="openai-responses"||t.api==="openai-codex-responses"||t.api==="azure-openai-responses"){e.serviceTier=r;return}if(t.api!=="openai-completions"&&!(t.api==="anthropic-messages"&&r==="fast"))return;J(e,(n)=>{if(!n||typeof n!=="object"||Array.isArray(n))return n;return t.api==="anthropic-messages"?{...n,speed:"fast"}:{...n,service_tier:r}})}function ke(e,t,o){let r=o.responseVerbosity;if(!r)return;if(K(t,r),t.api==="openai-codex-responses"){e.textVerbosity=r;return}J(e,(n)=>{if(!n||typeof n!=="object"||Array.isArray(n))return n;if(t.api==="openai-completions")return{...n,verbosity:r};let i="text"in n&&n.text&&typeof n.text==="object"&&!Array.isArray(n.text)?n.text:{};return{...n,text:{...i,verbosity:r}}})}function Z(e,t,o,r,n=!1){let i={apiKey:e.apiKey,headers:e.customHeaders,signal:o,temperature:r?.temperature??e.temperature??0,maxTokens:r?.maxOutputTokens??e.maxOutputTokens,timeoutMs:e.timeout,maxRetries:0,cacheRetention:e.enablePromptCaching?"short":"none"};if(xe(i,t,e,n),ve(i,t.api,r?.toolChoice?.toolName),Te(i,t,e),ke(i,t,e),t.api==="azure-openai-responses")i.azureBaseUrl=e.baseUrl,i.azureApiVersion=e.apiVersion,i.azureDeploymentName=t.id;return i}function $(e,t){let o=t.get("x-should-retry");return{statusCode:e,...t.get("retry-after")!==null?{retryAfter:t.get("retry-after")??void 0}:{},...t.get("retry-after-ms")!==null?{retryAfterMs:t.get("retry-after-ms")??void 0}:{},...o==="true"||o==="false"?{shouldRetry:o}:{}}}var we=new Set(["anthropic-messages","openai-completions","openai-responses","openai-codex-responses","azure-openai-responses","pi-messages"]);function Q(e,t,o){let r=e.onResponse;if(e.onResponse=async(i,a)=>{let u=new Headers(i.headers);o($(i.status,u)),await r?.(i,a)},!we.has(t.api)||typeof globalThis.fetch!=="function")return;let n=typeof e.fetch==="function"?e.fetch:globalThis.fetch.bind(globalThis);e.fetch=async(i,a)=>{let u=await n(i,a);return o($(u.status,u.headers)),u}}function ee(e){return{promptTokens:e.input+e.cacheRead+e.cacheWrite,completionTokens:e.output,totalTokens:e.totalTokens,costUsd:e.cost.total,...e.reasoning!==void 0?{reasoningTokens:e.reasoning}:{},...e.cacheWrite>0?{cacheCreationInputTokens:e.cacheWrite}:{},...e.cacheRead>0?{cacheReadInputTokens:e.cacheRead}:{}}}var O=300000,Ae=30000;class te extends Error{timeoutMs;code="STREAM_IDLE_TIMEOUT";constructor(e){super(`Provider stream idle timeout after ${e}ms without an event`);this.timeoutMs=e;this.name="StreamIdleTimeoutError"}}class oe extends Error{code="PROVIDER_STREAM_CLOSED";constructor(){super("Provider stream closed before completion");this.name="ProviderStreamClosedError"}}function I(e){return e.reason instanceof Error?e.reason:new DOMException("Aborted","AbortError")}function Pe(e){return e.idleTimeoutMs&&e.idleTimeoutMs>0?e.idleTimeoutMs:O}function Ee(e,t){if(t===0)return;let o=t!==void 0&&t>0?t:Ae;return Math.max(1,Math.min(o,Math.floor(e/2)))}function _e(e,t,o){if(o?.aborted)return Promise.reject(I(o));return new Promise((r,n)=>{let i=!1,a=()=>{clearTimeout(d),o?.removeEventListener("abort",c)},u=(l)=>{if(i)return;i=!0,a(),r(l)},s=(l)=>{if(i)return;i=!0,a(),n(l instanceof Error?l:Error(String(l)))},c=()=>{if(o)s(I(o))},d=setTimeout(()=>u({kind:"timer"}),Math.max(0,t));if(o?.addEventListener("abort",c,{once:!0}),o?.aborted){c();return}e.then((l)=>u({kind:"next",result:l}),s)})}async function*Se(e,t,o){let r=Pe(t),n=Ee(r,t.stallWarningMs);if(t.signal?.aborted)throw I(t.signal);let i=Date.now(),a=Promise.resolve().then(()=>e.next()),u;for(;;){let c=await _e(a,(u?r:n??r)-(Date.now()-i),t.signal);if(c.kind==="next"){if(u)yield{...u,phase:"recovered",durationMs:Math.max(u.durationMs,Date.now()-i)};return c.result}if(!u&&n!==void 0){o.stallCount++,u={phase:"detected",stallCount:o.stallCount,durationMs:n,warningAfterMs:n,timeoutMs:r,outputStarted:o.outputStarted},yield u;continue}let d=new te(r);throw t.abort?.(d),d}}async function*ne(e,t,o,r,n={}){let a=e.stream(t,o,r)[Symbol.asyncIterator](),u=0,s=!1,c={stallCount:0,outputStarted:!1};try{while(!0){let d=Se(a,n,c),l=await d.next();while(!l.done)yield{providerStall:l.value},l=await d.next();let x=l.value;if(x.done)throw new oe;let f=x.value;switch(f.type){case"text_delta":c.outputStarted=!0,yield{content:f.delta};break;case"thinking_delta":c.outputStarted=!0,yield{reasoningContent:f.delta};break;case"toolcall_end":c.outputStarted=!0,yield{toolCalls:[{index:u++,id:f.toolCall.id,type:"function",function:{name:f.toolCall.name,arguments:JSON.stringify(f.toolCall.arguments)}}]};break;case"done":s=!0,yield{finishReason:f.reason,usage:ee(f.message.usage)};return;case"error":throw Error(f.error.errorMessage??`Request ${f.reason==="aborted"?"aborted":"failed"}`)}}}finally{if(!s)Promise.resolve(a.return?.()).catch(()=>{return})}}var re=R("Chat");function Ie(e){return Boolean(e&&e.role==="user"&&Array.isArray(e.content)&&e.content.some((t)=>t.type==="image_url"))}class D{config;models;model;constructor(e){let t=S(e);this.config={...e,maxContextTokens:t.model.contextWindow,maxOutputTokens:e.maxOutputTokens??t.model.maxTokens},this.models=t.models,this.model=t.model,re.debug("[PiAIChatService] Initialized",{provider:this.model.provider,model:this.model.id,api:this.model.api})}async chat(e,t,o,r){let n="",i="",a=[],u,s;for await(let c of this.streamChat(e,t,o,r)){n+=c.content??"",i+=c.reasoningContent??"";for(let d of c.toolCalls??[])if(d.id&&d.type==="function"&&d.function?.name)a.push(d);u=c.usage??u,s=c.finishReason??s}return{content:n,...i?{reasoningContent:i}:{},...a.length>0?{toolCalls:a}:{},usage:u,finishReason:s}}async*streamChat(e,t,o,r){let n=r?.toolChoice?.toolName;if(n&&!t?.some((m)=>m.name===n))throw Error(`Required tool is unavailable: ${n}`);let i=B(e);if(i.some((m)=>Ie(m))&&!this.model.input.includes("image"))throw Error(`${this.model.name} does not support image input`);let a=Boolean(n)||F(i),u=await j(i,this.model,t,o,n),s,c=(m)=>{s=void 0;let C=new AbortController,h=o?U(o,C.signal):C.signal,M=Z(this.config,m,h,r,a);return Q(M,m,(y)=>{s=y}),ne(this.models,m,u,M,{idleTimeoutMs:this.config.streamIdleTimeout??O,signal:h,abort:(y)=>C.abort(y)})},d=this.config.maxRetries??2,l=this,x=async function*(m,C){let h,M=!1,y,v;for(let g=0;g<=d;g++)try{let b=!1;for await(let p of c(m)){if(p.providerStall){yield p;continue}if(g>0&&y&&!b)b=!0,yield{providerRetry:{phase:"recovered",attempt:g,maxRetries:d,reason:y,...v!==void 0?{statusCode:v}:{}}};M=!0,C(),yield p}return}catch(b){h=b,l.logIdleTimeout(b,M,m),await l.handleAbort(o);let p=T(b,s);if(M)throw X(b),b;if(!p.retryable||!p.reason){if(g>0&&y)yield{providerRetry:{phase:"exhausted",attempt:g,maxRetries:d,reason:y,...v!==void 0?{statusCode:v}:{}}};throw b}if(y=p.reason,v=p.statusCode,g<d){let k=g+1,w=G(k,s);yield{providerRetry:{phase:"scheduled",attempt:k,maxRetries:d,reason:p.reason,...p.statusCode!==void 0?{statusCode:p.statusCode}:{},delayMs:w,nextRetryAt:Date.now()+w}},await P(w,o,{throwOnAbort:!0}),yield{providerRetry:{phase:"attempt",attempt:k,maxRetries:d,reason:p.reason,...p.statusCode!==void 0?{statusCode:p.statusCode}:{}}}}else yield{providerRetry:{phase:"exhausted",attempt:g,maxRetries:d,reason:p.reason,...p.statusCode!==void 0?{statusCode:p.statusCode}:{}}}}throw h},f,L=!1;try{for await(let m of x(this.model,()=>{L=!0}))yield m;return}catch(m){if(f=m,L||!T(m,s).retryable)throw m}for(let m of this.config.fallbackModels??[]){yield{modelFallback:!0};let C=!1;try{let h=V(this.config,m);for await(let M of x(h,()=>{C=!0}))yield M;return}catch(h){if(f=h,C||!T(h,s).retryable)throw h}}throw f}async handleAbort(e){if(e?.aborted)await P(0,e,{throwOnAbort:!0})}logIdleTimeout(e,t,o){if(e===null||typeof e!=="object"||!("code"in e)||e.code!=="STREAM_IDLE_TIMEOUT"||!("timeoutMs"in e)||typeof e.timeoutMs!=="number")return;re.warn("[PiAIChatService] Provider stream idle timeout",{provider:o.provider,model:o.id,timeoutMs:e.timeoutMs,replayBoundaryCrossed:t})}getConfig(){return{...this.config}}updateConfig(e){let t={...this.config,...e},o=S(t);this.config={...t,maxContextTokens:o.model.contextWindow,maxOutputTokens:t.maxOutputTokens??o.model.maxTokens},this.models=o.models,this.model=o.model}}var Oe=R("Service");async function mt(e){let t=e;if(t.provider){let o=N(t.provider);if(Object.keys(o).length>0)t={...t,customHeaders:{...o,...t.customHeaders}},Oe.debug(`Injected ${t.provider} specific headers:`,Object.keys(o))}return De(t)}function De(e){return new D(e)}
5
- export{Ne as zd,je as Ad,U as Bd,he as Cd,Xe as Dd,D as Ed,mt as Fd};
5
+ export{Ne as Ed,je as Fd,U as Gd,he as Hd,Xe as Id,D as Jd,mt as Kd};