blade-code 0.10.106 → 0.10.108

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 (95) hide show
  1. package/dist/blade.js +2 -2
  2. package/dist/{chunk-v60x3dy1.js → chunk-0734ktp4.js} +1 -1
  3. package/dist/{chunk-xm8nyj5z.js → chunk-23v8c9b8.js} +2 -2
  4. package/dist/chunk-25ps9fxw.js +1 -0
  5. package/dist/{chunk-vqke0a40.js → chunk-37j8v3pq.js} +1 -1
  6. package/dist/{chunk-7fz3w4rk.js → chunk-3pwq56je.js} +1 -1
  7. package/dist/{chunk-wvnw6wfz.js → chunk-408wmns7.js} +2 -2
  8. package/dist/chunk-4k2c1g73.js +1 -0
  9. package/dist/{chunk-sdbbyagy.js → chunk-4w4wjm49.js} +1 -1
  10. package/dist/chunk-50xeb1cz.js +1 -0
  11. package/dist/{chunk-s0tq8gyx.js → chunk-53h87fmt.js} +1 -1
  12. package/dist/chunk-543180gh.js +1 -0
  13. package/dist/{chunk-ykzg875x.js → chunk-5ar697sg.js} +1 -1
  14. package/dist/chunk-5bsn3bsh.js +1 -0
  15. package/dist/chunk-5sbzjxm5.js +1 -0
  16. package/dist/{chunk-f3426b1c.js → chunk-6k5k40p8.js} +1 -1
  17. package/dist/chunk-6z2g9bhy.js +1 -0
  18. package/dist/chunk-70srdp2m.js +23 -0
  19. package/dist/{chunk-szxajr6e.js → chunk-76f8ms39.js} +1 -1
  20. package/dist/{chunk-2a03fwgm.js → chunk-83rn6ezc.js} +2 -2
  21. package/dist/{chunk-v6zjf4jx.js → chunk-8crjkt55.js} +4 -4
  22. package/dist/{chunk-bxrnsq3n.js → chunk-8xcrjnrp.js} +2 -2
  23. package/dist/{chunk-41ympwz1.js → chunk-935v0gpc.js} +1 -1
  24. package/dist/{chunk-fva7jnjy.js → chunk-9g64g1np.js} +1 -1
  25. package/dist/chunk-9q4dvzc0.js +1 -0
  26. package/dist/{chunk-gtznn0fk.js → chunk-a8ak0gkr.js} +1 -1
  27. package/dist/{chunk-xxzdnt4g.js → chunk-asp9yz7j.js} +2 -2
  28. package/dist/chunk-bdgq4k40.js +1 -0
  29. package/dist/{chunk-j2dyprdy.js → chunk-bksfg23m.js} +2 -2
  30. package/dist/{chunk-tyd3bz74.js → chunk-bp7bn0ka.js} +1 -1
  31. package/dist/{chunk-zvawerhj.js → chunk-bycxhv2r.js} +2 -2
  32. package/dist/{chunk-181ef74x.js → chunk-c3jb4xg7.js} +1 -1
  33. package/dist/{chunk-b8q7vjd9.js → chunk-c7r5s02f.js} +2 -2
  34. package/dist/{chunk-8hprmrd5.js → chunk-cnhw5mqv.js} +1 -1
  35. package/dist/{chunk-kf7whgr7.js → chunk-cqqmkwvn.js} +1 -1
  36. package/dist/{chunk-qb7weaz0.js → chunk-cv3yxy1k.js} +1 -1
  37. package/dist/{chunk-s10pmnrd.js → chunk-dgf2xzzd.js} +2 -2
  38. package/dist/{chunk-1b4rh25n.js → chunk-dvsmvk1j.js} +2 -2
  39. package/dist/{chunk-n7mzxa8h.js → chunk-dvv28pkc.js} +2 -2
  40. package/dist/{chunk-0hr050ck.js → chunk-ecd727xh.js} +1 -1
  41. package/dist/{chunk-41cg66y0.js → chunk-eyb9psbc.js} +1 -1
  42. package/dist/chunk-f3x4w3fc.js +1 -0
  43. package/dist/{chunk-51ep7gct.js → chunk-fb44m8vk.js} +3 -3
  44. package/dist/chunk-fqnqeca5.js +1 -0
  45. package/dist/{chunk-2hb222re.js → chunk-hv6hrsnk.js} +1 -1
  46. package/dist/{chunk-wcm4hm35.js → chunk-j4n443dn.js} +2 -2
  47. package/dist/{chunk-xzy7vtdf.js → chunk-jdjaqhby.js} +2 -2
  48. package/dist/chunk-jm794j70.js +10 -0
  49. package/dist/{chunk-6wsvgk20.js → chunk-jp4j9tnn.js} +1 -1
  50. package/dist/{chunk-szkxjpr1.js → chunk-jqtspa26.js} +3 -3
  51. package/dist/{chunk-946wkbmw.js → chunk-mqekerck.js} +1 -1
  52. package/dist/{chunk-z9gd9spf.js → chunk-ng96f4xd.js} +2 -2
  53. package/dist/chunk-nk0egcxh.js +1 -0
  54. package/dist/{chunk-ny2gnbq8.js → chunk-nswm0qtm.js} +1 -1
  55. package/dist/chunk-p3m1jyg5.js +2 -0
  56. package/dist/chunk-ph338zx1.js +1 -0
  57. package/dist/{chunk-dg0d3303.js → chunk-pshyn3yy.js} +1 -1
  58. package/dist/{chunk-rchz6j90.js → chunk-q2exry0f.js} +2 -2
  59. package/dist/{chunk-x3cxmwnz.js → chunk-qdv0n8yt.js} +2 -2
  60. package/dist/{chunk-tgdhsm5t.js → chunk-rkdxqx8m.js} +2 -2
  61. package/dist/{chunk-z0manfyv.js → chunk-se1af4zj.js} +2 -2
  62. package/dist/{chunk-rvk9r2cm.js → chunk-sr10jsjs.js} +1 -1
  63. package/dist/{chunk-fhfzdyba.js → chunk-tf7ezqew.js} +1 -1
  64. package/dist/{chunk-w7hy5wh1.js → chunk-tj2efrs1.js} +2 -2
  65. package/dist/{chunk-wyhyw9rq.js → chunk-vbwvsgs1.js} +2 -2
  66. package/dist/{chunk-w2a5dqg5.js → chunk-vk01pnqk.js} +2 -2
  67. package/dist/{chunk-6hcp4y6z.js → chunk-wxq8kypj.js} +2 -2
  68. package/dist/chunk-wyw17nfy.js +1 -0
  69. package/dist/{chunk-q69fzq4y.js → chunk-x05zyqzf.js} +1 -1
  70. package/dist/chunk-xbpzq84r.js +8 -0
  71. package/dist/{chunk-47e6tdbb.js → chunk-xv3a1se1.js} +1 -1
  72. package/dist/{chunk-abd57h72.js → chunk-ypbnczjp.js} +2 -2
  73. package/dist/{chunk-9p20hhs0.js → chunk-z52s82k7.js} +1 -1
  74. package/dist/chunk-za7zs9fq.js +2 -0
  75. package/dist/{chunk-rtnyzakh.js → chunk-zgnsc2f8.js} +2 -2
  76. package/package.json +1 -1
  77. package/dist/chunk-31c266h5.js +0 -1
  78. package/dist/chunk-4ywjs5fw.js +0 -2
  79. package/dist/chunk-6ywj6p3q.js +0 -1
  80. package/dist/chunk-6yxr3rwf.js +0 -1
  81. package/dist/chunk-95xnc5t8.js +0 -8
  82. package/dist/chunk-amkhz6er.js +0 -1
  83. package/dist/chunk-bt18xsc6.js +0 -1
  84. package/dist/chunk-c475tfqf.js +0 -2
  85. package/dist/chunk-cwjxrz7p.js +0 -23
  86. package/dist/chunk-dpadcz0y.js +0 -1
  87. package/dist/chunk-dy058mrn.js +0 -1
  88. package/dist/chunk-h9yvynzr.js +0 -10
  89. package/dist/chunk-kdjtxpxw.js +0 -1
  90. package/dist/chunk-mfd2nsfd.js +0 -1
  91. package/dist/chunk-sh94x2js.js +0 -1
  92. package/dist/chunk-tze04t3t.js +0 -1
  93. package/dist/chunk-v4w5b2cq.js +0 -1
  94. package/dist/chunk-vk4xbek0.js +0 -1
  95. package/dist/chunk-x6frzhkf.js +0 -1
@@ -1,4 +1,4 @@
1
- import{$d as j,Xd as n,Yd as F$,Zd as h_,_d as D$,ae as c_,be as f$,ce as n_,de as z$,ee as l_,fe as p_,he as d0,ke as i_,le as x$}from"./chunk-x3cxmwnz.js";import{qf as D0}from"./chunk-2hb222re.js";import{ig as f0}from"./chunk-fva7jnjy.js";import{ug as a1}from"./chunk-41cg66y0.js";import{Hh as K$,Ih as M$,Jh as B0,Kh as g0,Lh as W0}from"./chunk-c475tfqf.js";import{Ph as B1}from"./chunk-0hr050ck.js";import{pi as h0}from"./chunk-n7mzxa8h.js";import{wi as M0,zi as F0}from"./chunk-9p20hhs0.js";import{Di as a}from"./chunk-xzy7vtdf.js";import{Ni as q$,Oi as Q0,Pi as A$,Qi as x,Ri as u,Ti as A0,Ui as t,Vi as k}from"./chunk-tgdhsm5t.js";import{readdir as v_,readFile as T0,rm as G0,stat as o0}from"node:fs/promises";import*as Y from"node:path";import{nanoid as P}from"nanoid";import{createHash as u$,randomUUID as h$}from"node:crypto";import*as h from"node:fs/promises";import*as b0 from"node:path";import{execFileSync as j$}from"node:child_process";import{createHash as y$}from"node:crypto";import{readFileSync as I$}from"node:fs";var m$=/^[a-f0-9]{64}$/;function O1(_){if(!_||typeof _!=="object")return!1;let $=_;return($.platform==="linux"||$.platform==="darwin"||$.platform==="win32")&&typeof $.fingerprint==="string"&&m$.test($.fingerprint)}var T1={readFile:(_)=>I$(_,"utf8"),execFile:(_,$)=>j$(_,$,{encoding:"utf8",timeout:_==="powershell.exe"?3000:2000,windowsHide:!0})},v$=(_)=>{try{return process.kill(_,0),!0}catch($){return $ instanceof Error&&"code"in $&&$.code==="EPERM"}};function X_(_,$){return{platform:_,fingerprint:y$("sha256").update(`${_}\x00${$}`).digest("hex")}}function P$(_,$){let R=$.readFile(`/proc/${_}/stat`).trim(),O=R.lastIndexOf(")");if(O<0)throw Error("Invalid /proc process stat");let T=R.slice(O+2).split(/\s+/)[19];if(!T||!/^\d+$/.test(T))throw Error("Missing process start ticks");return T}function x0(_,$=process.platform,R=T1){if(!Number.isInteger(_)||_<=1)return;try{if($==="linux")return X_($,P$(_,R));if($==="darwin"){let O=R.execFile("ps",["-o","lstart=","-p",String(_)]).trim();return O?X_($,O):void 0}if($==="win32"){let O=`(Get-CimInstance Win32_Process -Filter "ProcessId = ${_}").CreationDate.ToUniversalTime().ToString('O')`,X=R.execFile("powershell.exe",["-NoProfile","-NonInteractive","-Command",O]).trim();return X?X_($,X):void 0}}catch{return}return}function X1(_,$){return x0(_,$.platform)?.fingerprint===$.fingerprint}function j2(_,$,R=T1,O=v$){if(!Number.isInteger(_)||_<=1)return!1;let X=x0(_,$.platform,R);if(X)return X.fingerprint===$.fingerprint;return!O(_)}var C1=1;function c$(_,$){let R=u$("sha256").update($).digest("hex");return b0.join(Q0(_),".locks",`${R}.lock`)}function w0(_,$){return _ instanceof Error&&"code"in _&&_.code===$}async function L_(_){try{let $=JSON.parse(await h.readFile(_,"utf8"));if($.version!==C1||typeof $.sessionId!=="string"||typeof $.ownerId!=="string"||!Number.isInteger($.pid)||($.pid??0)<=0||$.processIdentity!==void 0&&!O1($.processIdentity)||typeof $.acquiredAt!=="string")return;return $}catch{return}}async function L1(_){let $=await L_(_);if($)return $;return await new Promise((R)=>setTimeout(R,10)),L_(_)}function n$(_){try{return process.kill(_,0),!0}catch($){return w0($,"EPERM")}}async function W1(_,$){let R;try{return R=await h.open(_,"wx",384),await R.writeFile(`${JSON.stringify($)}
1
+ import{$d as F$,_d as n,ae as h_,be as D$,ce as j,de as c_,ee as f$,fe as n_,ge as z$,he as l_,ie as p_,ke as d0,ne as i_,oe as x$}from"./chunk-qdv0n8yt.js";import{tf as D0}from"./chunk-hv6hrsnk.js";import{lg as f0}from"./chunk-9g64g1np.js";import{xg as a1}from"./chunk-eyb9psbc.js";import{Kh as K$,Lh as M$,Mh as B0,Nh as g0,Oh as W0}from"./chunk-p3m1jyg5.js";import{Sh as B1}from"./chunk-ecd727xh.js";import{si as h0}from"./chunk-dvv28pkc.js";import{Ci as F0,zi as M0}from"./chunk-z52s82k7.js";import{Gi as a}from"./chunk-jdjaqhby.js";import{Qi as q$,Ri as Q0,Si as A$,Ti as x,Ui as u,Wi as A0,Xi as t,Yi as k}from"./chunk-rkdxqx8m.js";import{readdir as v_,readFile as T0,rm as G0,stat as o0}from"node:fs/promises";import*as Y from"node:path";import{nanoid as P}from"nanoid";import{createHash as u$,randomUUID as h$}from"node:crypto";import*as h from"node:fs/promises";import*as b0 from"node:path";import{execFileSync as j$}from"node:child_process";import{createHash as y$}from"node:crypto";import{readFileSync as I$}from"node:fs";var m$=/^[a-f0-9]{64}$/;function O1(_){if(!_||typeof _!=="object")return!1;let $=_;return($.platform==="linux"||$.platform==="darwin"||$.platform==="win32")&&typeof $.fingerprint==="string"&&m$.test($.fingerprint)}var T1={readFile:(_)=>I$(_,"utf8"),execFile:(_,$)=>j$(_,$,{encoding:"utf8",timeout:_==="powershell.exe"?3000:2000,windowsHide:!0})},v$=(_)=>{try{return process.kill(_,0),!0}catch($){return $ instanceof Error&&"code"in $&&$.code==="EPERM"}};function X_(_,$){return{platform:_,fingerprint:y$("sha256").update(`${_}\x00${$}`).digest("hex")}}function P$(_,$){let R=$.readFile(`/proc/${_}/stat`).trim(),O=R.lastIndexOf(")");if(O<0)throw Error("Invalid /proc process stat");let T=R.slice(O+2).split(/\s+/)[19];if(!T||!/^\d+$/.test(T))throw Error("Missing process start ticks");return T}function x0(_,$=process.platform,R=T1){if(!Number.isInteger(_)||_<=1)return;try{if($==="linux")return X_($,P$(_,R));if($==="darwin"){let O=R.execFile("ps",["-o","lstart=","-p",String(_)]).trim();return O?X_($,O):void 0}if($==="win32"){let O=`(Get-CimInstance Win32_Process -Filter "ProcessId = ${_}").CreationDate.ToUniversalTime().ToString('O')`,X=R.execFile("powershell.exe",["-NoProfile","-NonInteractive","-Command",O]).trim();return X?X_($,X):void 0}}catch{return}return}function X1(_,$){return x0(_,$.platform)?.fingerprint===$.fingerprint}function j2(_,$,R=T1,O=v$){if(!Number.isInteger(_)||_<=1)return!1;let X=x0(_,$.platform,R);if(X)return X.fingerprint===$.fingerprint;return!O(_)}var C1=1;function c$(_,$){let R=u$("sha256").update($).digest("hex");return b0.join(Q0(_),".locks",`${R}.lock`)}function w0(_,$){return _ instanceof Error&&"code"in _&&_.code===$}async function L_(_){try{let $=JSON.parse(await h.readFile(_,"utf8"));if($.version!==C1||typeof $.sessionId!=="string"||typeof $.ownerId!=="string"||!Number.isInteger($.pid)||($.pid??0)<=0||$.processIdentity!==void 0&&!O1($.processIdentity)||typeof $.acquiredAt!=="string")return;return $}catch{return}}async function L1(_){let $=await L_(_);if($)return $;return await new Promise((R)=>setTimeout(R,10)),L_(_)}function n$(_){try{return process.kill(_,0),!0}catch($){return w0($,"EPERM")}}async function W1(_,$){let R;try{return R=await h.open(_,"wx",384),await R.writeFile(`${JSON.stringify($)}
2
2
  `,"utf8"),!0}catch(O){if(w0(O,"EEXIST"))return!1;if(R)await h.unlink(_).catch(()=>{return});throw O}finally{await R?.close().catch(()=>{return})}}class d extends Error{code="BLADE_SESSION_IN_USE";constructor(_){super(_?`Session is already active in another Blade process (PID ${_}). Stop that process or choose a different session.`:"Session is already active in another Blade process. Stop that process or choose a different session.");this.name="SessionInUseError"}}class o{filePath;record;released=!1;constructor(_,$){this.filePath=_;this.record=$}static async acquire(_,$=B1()){let R=c$($,_),O={version:C1,sessionId:_,ownerId:h$(),pid:process.pid,processIdentity:x0(process.pid),acquiredAt:new Date().toISOString()};if(await h.mkdir(b0.dirname(R),{recursive:!0,mode:448}),await W1(R,O))return new o(R,O);let X=await L1(R);if(X&&n$(X.pid)&&(!X.processIdentity||X1(X.pid,X.processIdentity)))throw new d(X.pid);if(await h.unlink(R).catch((T)=>{if(!w0(T,"ENOENT"))throw T}),await W1(R,O))return new o(R,O);throw new d((await L1(R))?.pid)}async release(){if(this.released)return;if(this.released=!0,(await L_(this.filePath))?.ownerId!==this.record.ownerId)return;await h.unlink(this.filePath).catch(($)=>{if(!w0($,"ENOENT"))throw $})}}import{createHash as k0}from"node:crypto";import{constants as s,promises as c}from"node:fs";import i from"node:path";import{Mutex as l$}from"async-mutex";var G1=128,V1=67108864,p$=24576,E1=65536,B_=1,H1=/^[a-f0-9]{64}$/,i$=/^[a-f0-9]{64}\.txt$/,U1=64,d$=new Set(["EBUSY","EAGAIN","EMFILE","ENFILE"]),j0=`
3
3
 
4
4
  ...[middle omitted; read the private prompt artifact for the complete request]...
@@ -115,4 +115,4 @@ ${[...X0,...L0].join(`
115
115
  s.project_sort_key ASC,
116
116
  s.session_sort_key ASC
117
117
  LIMIT ?`).all(...X,_.limit+1),L=await Promise.all(T.map(async(C)=>{let G=JSON.parse(C.metadata_json);if(C.archive_root_id&&C.effective_archived_at)return this.reconcileInterruptedTask({...G,archivedAt:C.effective_archived_at,archivedBySessionId:C.archive_root_id});let{archivedAt:E,archivedBySessionId:B,...V}=G;return this.reconcileInterruptedTask(V)})),W=p_(L,_);return{sessions:W.sessions.map((C)=>this.toPublicMetadata(C)),nextCursor:W.nextCursor}}catch{return null}}static async listSessions(_={}){let $=n_(_),R=z$(_),O=await this.scanStoredSessions($.cwd??void 0,$.includeSubagents,0,$.archived,R),X=new Set;return O.sort(l_).flatMap((T)=>{let L=`${T.projectPath}\x00${T.sessionId}`;if(X.has(L))return[];return X.add(L),[this.toPublicMetadata(T)]})}static async collectStaleEmptySessions(_={}){let $=_.now??Date.now(),R=_.olderThanMs??W2;if(!Number.isFinite(R)||R<0)throw Error("Stale empty session age must be a non-negative number");let O=_.projectPath?[{storagePath:Q0(this.resolveCatalogWorkspace(_.projectPath)),projectPath:this.resolveCatalogWorkspace(_.projectPath)}]:await this.listAllProjectStorageDirectories(),X=0;for(let T of O){let L;try{L=await v_(T.storagePath)}catch(W){if(W.code==="ENOENT")continue;throw W}for(let W of L){if(!W.endsWith(".jsonl"))continue;let C=W.slice(0,-6);if(!A$(C))continue;let G=Y.join(T.storagePath,W);try{let B=await o0(G);if($-B.mtimeMs<R)continue;if(await Promise.all([o0(Y.join(T.storagePath,`${C}.inbox.json`)).then(()=>!0).catch(()=>!1),o0(A0(T.projectPath,C)).then(()=>!0).catch(()=>!1)]).then((J)=>J.some(Boolean)))continue}catch(B){if(B.code==="ENOENT")continue;throw B}let E;try{E=await o.acquire(C,T.projectPath)}catch(B){if(B instanceof d)continue;throw B}try{if(!await new j(G).deleteValidated((V)=>V.length===1&&V[0]?.type==="session_created"&&V[0].data.relationType!=="subagent"))continue;X++,await G0(Y.join(T.storagePath,`${C}.inbox.json`),{force:!0}),await G0(A0(T.projectPath,C),{force:!0}),await this.removeFromProjection(C,T.projectPath)}catch(B){q0.warn(`[SessionService] Skipping stale empty session cleanup: ${C}`,B)}finally{await E.release()}}}return X}static async findSessionMetadata(_,$){if(x(_),$!==void 0){if(!Y.isAbsolute($))throw Error("Session catalog cwd must be absolute");let O=Y.resolve($),X=this.getSessionFilePath(O,_);try{let T=await this.readStoredSessionMetadata(X,_,O);if(T.projectPath!==O)return;if(!T.parentId||T.archivedAt)return this.toPublicMetadata(u_([T],null)[0]??T);let L=await this.scanStoredSessions(O,!0,0,null);return this.toPublicMetadata(L.find((W)=>W.sessionId===_)??T)}catch(T){if(T.code==="ENOENT")return;throw T}}let R=(await this.scanStoredSessions(void 0,!0,0,null)).filter((O)=>O.sessionId===_);if(R.length===0)return;if(R.length>1)throw Error(`Ambiguous session ID: ${_}`);return this.toPublicMetadata(R[0])}static async loadSession(_,$){try{if($){if(!Y.isAbsolute($))throw Error("Session catalog cwd must be absolute");let O=Y.resolve($),X=this.getSessionFilePath(O,_);try{return await this.loadSessionFromFile(X,_,O)}catch(T){if(T.code==="ENOENT")throw Error(`未找到会话: ${_}`);throw T}}let R=(await this.scanStoredSessions(void 0,!0,0,null)).find((O)=>O.sessionId===_);if(!R)throw Error(`未找到会话: ${_}`);return await this.loadSessionFromFile(R.filePath,_)}catch(R){throw q0.error(`[SessionService] 加载会话失败 (${_}):`,R),R}}static async loadSessionModelContext(_,$){try{if($){if(!Y.isAbsolute($))throw Error("Session catalog cwd must be absolute");let O=Y.resolve($),X=this.getSessionFilePath(O,_);try{return await this.loadSessionModelContextFromFile(X,_,O)}catch(T){if(T.code==="ENOENT")throw Error(`未找到会话: ${_}`);throw T}}let R=(await this.scanStoredSessions(void 0,!0,0,null)).find((O)=>O.sessionId===_);if(!R)throw Error(`未找到会话: ${_}`);return await this.loadSessionModelContextFromFile(R.filePath,_)}catch(R){throw q0.error(`[SessionService] 加载模型上下文失败 (${_}):`,R),R}}static async exportSessionMarkdown(_,$,R={}){x(_);let O=this.resolveCatalogWorkspace($),X=u(O,_),T;try{T=await this.readStableSessionSnapshot(X,_)}catch(C){throw this.sanitizeStoredSessionError(C,_)}let L=this.projectMetadataFromEntries(T,_,O,X);if(L.projectPath!==O)throw Error(`Session export workspace mismatch: ${_}`);let W=L.archivedAt;if(!W&&L.parentId)W=(await this.findArchivedAncestor(L.parentId,O))?.archivedAt;return R$(T,{...L,archivedAt:W},R)}static async listRewindCheckpoints(_,$){x(_);let R=this.resolveCatalogWorkspace($),O=u(R,_),X=await this.readStableSessionSnapshot(O,_);this.validateSessionWorkspace(X,_,R);let T=new c0({sessionId:_,workspaceRoot:R});await T.initialize();let L=F$(X),W=[];for(let C of L){let G=h_(X,C.messageId),E=await T.previewRewind(G.snapshotMessageIds);W.push({...C,fileCount:E.files.length})}return W}static async rewindSession(_,$,R){x(_);let O=this.resolveCatalogWorkspace($);await this.assertSessionWritable(_,O);let X=u(O,_),T=new j(X),L;try{await T.appendValidatedAsync(async(W)=>{this.validateSessionWorkspace(W,_,O);let C=h_(W,R.targetMessageId),G=new c0({sessionId:_,workspaceRoot:O});await G.initialize();let E=await G.previewRewind(C.snapshotMessageIds),B=R.mode==="conversation"?await G.commitSnapshots(C.snapshotMessageIds):await G.rewindSnapshots(C.snapshotMessageIds),V=new Date().toISOString(),J={id:P(),sessionId:_,timestamp:V,type:"session_rewound",cwd:O,gitBranch:t(O),version:a(),data:{rewindId:P(),targetMessageId:R.targetMessageId,mode:R.mode,restoredFiles:R.mode==="conversation"?[]:B.files,createdAt:V}},Q=n([...W,J]);return L={checkpoint:{...C.checkpoint,fileCount:E.files.length},mode:R.mode,removedTurns:C.removedTurns,restoredFiles:J.data.restoredFiles,messages:this.convertJSONLToMessages(Q)},J})}catch(W){throw this.sanitizeStoredSessionError(W,_)}if(!L)throw Error(`Session rewind did not produce a result: ${_}`);for(let W of L.restoredFiles)r.getInstance().clearFileRecord(W);return L}static async forkSession(_,$){x(_);let R=$.newSessionId??`fork-${Date.now()}-${P(8)}`;x(R);let O=this.resolveForkWorkspace($.sourceProjectPath),X=this.resolveForkWorkspace($.targetProjectPath);if(O!==X)throw Error("Session forks must stay in the source workspace");let T=u(O,_),L=await this.readStableSessionSnapshot(T,_),W=this.getSessionCreatedEntry(L,_);if(W.data.sessionId!==_)throw Error("Fork source session_created.data.sessionId must match the requested session ID");if(!Y.isAbsolute(W.cwd)||Y.resolve(W.cwd)!==O)throw Error("Fork source session_created.cwd must resolve to the requested source workspace");let C=this.projectMetadataFromEntries(L,_,O,T);if(C.archivedAt)throw new V0(_,_);if(C.parentId){let U=await this.findArchivedAncestor(C.parentId,O);if(U)throw new V0(_,U.sessionId)}let G=n(L),E=new Date().toISOString(),B=W.data.rootId||_,V=t(X),J=a(),{status:Q,taskStatus:A,taskStatusReason:b,taskFailure:K,taskStartedAt:X0,taskCompletedAt:L0,taskOwnerPid:y,taskPromptSummary:I,taskPriority:f,taskKind:D,taskDueAt:w,taskDispatch:N,taskModelId:z,taskRetriedFrom:r_,taskDelivery:t_,taskIsolation:a_,taskSourceProjectPath:s0,taskWorktree:s_,taskDiffStat:e_,taskQueuePosition:_1,taskQueueDepth:$1,taskConcurrencyLimit:R1,pendingInteraction:e0,...__}=W.data,$_={id:P(),sessionId:R,timestamp:E,type:"session_created",cwd:X,gitBranch:V,version:J,data:{...__,sessionId:R,rootId:B,parentId:_,relationType:"fork",taskStatus:"completed",taskCompletedAt:E,taskIsolation:"local",taskSourceProjectPath:X,createdAt:E,updatedAt:E}},R_=G.filter((U)=>U.type!=="session_created"&&U.type!=="token_budget_handoff_recorded"&&U.type!=="inbox_acknowledged"&&U.type!=="interaction_requested"&&U.type!=="interaction_responded"&&U.type!=="interaction_recovered"&&U.type!=="review_started"&&U.type!=="review_completed").map((U)=>{let m={...U,id:P(),sessionId:R,cwd:X,gitBranch:V,version:J};if(U.type==="session_updated"){let{status:F,taskStatus:Y0,taskStatusReason:G2,taskFailure:V2,taskStartedAt:E2,taskCompletedAt:J2,taskOwnerPid:Y2,taskPromptSummary:Q2,taskPriority:Z2,taskKind:N2,taskDueAt:H2,taskDispatch:U2,taskModelId:q2,taskRetriedFrom:A2,taskDelivery:K2,taskIsolation:M2,taskSourceProjectPath:F2,taskWorktree:D2,taskDiffStat:f2,taskQueuePosition:z2,taskQueueDepth:x2,taskConcurrencyLimit:w2,pendingInteraction:b2,...g$}=U.data;return{...m,type:"session_updated",data:{...g$,sessionId:R,rootId:B,parentId:_,relationType:"fork"}}}if(U.type==="message_created"){let{inboxMessageId:F,...Y0}=U.data;return{...m,type:"message_created",data:Y0}}return m}),O_={id:P(),sessionId:R,timestamp:E,type:"session_updated",cwd:X,gitBranch:V,version:J,data:{sessionId:R,rootId:B,parentId:_,relationType:"fork",taskStatus:"completed",taskStatusReason:null,taskFailure:null,taskStartedAt:null,taskCompletedAt:E,taskOwnerPid:null,taskIsolation:"local",taskSourceProjectPath:X,taskWorktree:null,taskDiffStat:null,taskDelivery:null,taskQueuePosition:null,taskQueueDepth:null,taskConcurrencyLimit:null,updatedAt:E}},E0=[$_,...R_,O_],J0=u(X,R),z0=!1;try{await new j(J0).createExclusive(E0),z0=!0;let U=q1(G.flatMap((m)=>m.type==="message_created"?[m.data.metadata]:[]));if(U.length>0){let m=new e(O,_,{storageRoot:k()}),F=new e(X,R,{storageRoot:k()});await m.copyReferencedTo(U,F)}}catch(U){if(z0)await new j(J0).delete().catch(()=>{return}),await new e(X,R,{storageRoot:k()}).removeAll().catch(()=>{return});if(U.code==="EEXIST")throw Error(`Fork session already exists: ${R}`,{cause:U});throw U}let T_=this.projectMetadataFromEntries(E0,R,X,J0);return{sessionId:R,parentSessionId:_,projectPath:X,messages:this.convertJSONLToMessages(E0),metadata:this.toPublicMetadata(T_)}}static async deleteSession(_,$){if(x(_),$){if(!Y.isAbsolute($))throw Error("Session catalog cwd must be absolute");let O=Y.resolve($),X=this.getSessionFilePath(O,_),T=new j(X),L;try{L=await T.deleteValidated((W)=>{return this.projectMetadataFromEntries(W,_,O,X).projectPath===O})}catch(W){if(!this.isCorruptSessionJSONLError(W))throw W;L=await T.delete()}if(!L)return 0;return await G0(Y.join(Y.dirname(X),`${_}.inbox.json`),{force:!0}),await G0(A0(O,_),{force:!0}),await new e(O,_,{storageRoot:k()}).removeAll(),await Q_(O,_,k()),await this.removeFromProjection(_,O),1}let R=(await this.scanStoredSessions(void 0,!0)).filter((O)=>O.sessionId===_);if(R.length===0)return 0;return await Promise.all(R.map(async(O)=>{await new j(O.filePath).delete(),await G0(Y.join(Y.dirname(O.filePath),`${O.sessionId}.inbox.json`),{force:!0}),await G0(A0(O.projectPath,O.sessionId),{force:!0}),await new e(O.projectPath,O.sessionId,{storageRoot:k()}).removeAll(),await Q_(O.projectPath,O.sessionId,k()),await this.removeFromProjection(O.sessionId,O.projectPath)})),R.length}static async removeFromProjection(_,$){try{let R=await d0();if(R)x$(R,_,$)}catch{}}static validateTaskMetadataUpdate(_,$){if(_.taskPromptSummary!==void 0&&_.taskPromptSummary!==null&&(!_.taskPromptSummary.trim()||_.taskPromptSummary.length>1000))throw Error("Session task prompt summary must contain 1-1000 characters");if(_.taskPriority!==void 0&&_.taskPriority!==null&&!t0.has(_.taskPriority))throw Error("Invalid session task priority");if(_.taskKind!==void 0&&_.taskKind!==null&&!a0.has(_.taskKind))throw Error("Invalid session task kind");if(_.taskDueAt!==void 0&&_.taskDueAt!==null&&!Number.isFinite(Date.parse(_.taskDueAt)))throw Error("Invalid session task due date");if(_.taskFailure!==void 0&&_.taskFailure!==null&&!D_(_.taskFailure))throw Error("Invalid session task failure");if(_.taskDispatch!==void 0&&_.taskDispatch!==null&&!N$(_.taskDispatch))throw Error("Invalid durable task dispatch");if(_.taskModelId!==void 0&&_.taskModelId!==null&&(!_.taskModelId.trim()||_.taskModelId.length>500))throw Error("Invalid session task model ID");if(_.selectedModelId!==void 0&&_.selectedModelId!==null&&(!_.selectedModelId.trim()||_.selectedModelId.length>500))throw Error("Invalid selected session model ID");if(_.permissionMode!==void 0&&_.permissionMode!==null&&!r0(_.permissionMode))throw Error("Invalid session permission mode");if(_.reasoningEffort!==void 0&&_.reasoningEffort!==null&&!D0(_.reasoningEffort))throw Error("Invalid session reasoning effort");if(_.serviceTier!==void 0&&_.serviceTier!==null&&!F0(_.serviceTier))throw Error("Invalid session service tier");if(_.responseVerbosity!==void 0&&_.responseVerbosity!==null&&!M0(_.responseVerbosity))throw Error("Invalid session response verbosity");if(_.communicationStyle!==void 0&&_.communicationStyle!==null&&!f0(_.communicationStyle))throw Error("Invalid session communication style");if(_.communicationStyleDigest!==void 0&&_.communicationStyleDigest!==null&&!/^[a-f0-9]{64}$/.test(_.communicationStyleDigest))throw Error("Invalid session communication style digest");if(_.projectInstructionsDigest!==void 0&&_.projectInstructionsDigest!==null&&!/^[a-f0-9]{64}$/.test(_.projectInstructionsDigest))throw Error("Invalid session project instructions digest");if(_.taskRetriedFrom!==void 0&&_.taskRetriedFrom!==null&&!H$(_.taskRetriedFrom))throw Error("Invalid session task retry source");if(_.taskDelivery!==void 0&&_.taskDelivery!==null&&!Q$(_.taskDelivery))throw Error("Invalid session task delivery");if(_.taskIsolation!==void 0&&_.taskIsolation!==null&&!d_.has(_.taskIsolation))throw Error(`Invalid session task isolation: ${String(_.taskIsolation)}`);if(_.taskSourceProjectPath!==void 0&&_.taskSourceProjectPath!==null&&!Y.isAbsolute(_.taskSourceProjectPath))throw Error("Session task source project path must be absolute");if(_.taskWorktree!==void 0&&_.taskWorktree!==null){let R=Y$(_.taskWorktree);if(!R||R.sessionId!==$||![R.repositoryRoot,R.originalWorkspaceRoot,R.worktreeRoot,R.workspaceRoot].every((O)=>Y.isAbsolute(O)))throw Error("Invalid session task worktree metadata")}if(_.taskDiffStat!==void 0&&_.taskDiffStat!==null&&!Z$(_.taskDiffStat))throw Error("Invalid session task diff stat");if(_.taskQueuePosition!==void 0&&_.taskQueuePosition!==null&&(!Number.isInteger(_.taskQueuePosition)||_.taskQueuePosition<1))throw Error("Invalid session task queue position");if(_.taskQueueDepth!==void 0&&_.taskQueueDepth!==null&&(!Number.isInteger(_.taskQueueDepth)||_.taskQueueDepth<0))throw Error("Invalid session task queue depth");if(_.taskConcurrencyLimit!==void 0&&_.taskConcurrencyLimit!==null&&(!Number.isInteger(_.taskConcurrencyLimit)||_.taskConcurrencyLimit<1))throw Error("Invalid session task concurrency limit");if(typeof _.taskQueuePosition==="number"&&typeof _.taskQueueDepth==="number"&&_.taskQueuePosition>_.taskQueueDepth)throw Error("Session task queue position exceeds queue depth")}static async createSessionMetadata(_,$,R={}){x(_),q.validateTaskMetadataUpdate(R,_);let O=q.resolveCatalogWorkspace($);if(R.taskWorktree&&Y.resolve(R.taskWorktree.workspaceRoot)!==O)throw Error("Session task worktree must match the catalog workspace");let X=new Date().toISOString(),T={id:P(),sessionId:_,timestamp:X,type:"session_created",cwd:O,gitBranch:t(O),version:a(),data:{sessionId:_,rootId:_,...R.title!==void 0?{title:R.title}:{},taskStatus:R.taskStatus??"queued",...R.taskPromptSummary!==void 0?{taskPromptSummary:R.taskPromptSummary}:{},...R.taskPriority!==void 0?{taskPriority:R.taskPriority}:{},...R.taskKind!==void 0?{taskKind:R.taskKind}:{},...typeof R.taskDueAt==="string"?{taskDueAt:new Date(R.taskDueAt).toISOString()}:{},...R.taskDispatch!==void 0?{taskDispatch:R.taskDispatch}:{},...R.taskModelId!==void 0?{taskModelId:R.taskModelId}:{},...R.taskRetriedFrom!==void 0?{taskRetriedFrom:R.taskRetriedFrom}:{},...R.taskIsolation!==void 0?{taskIsolation:R.taskIsolation}:{},...R.taskSourceProjectPath!==void 0?{taskSourceProjectPath:R.taskSourceProjectPath}:{},...R.taskWorktree!==void 0?{taskWorktree:R.taskWorktree}:{},...R.selectedModelId!==void 0?{selectedModelId:R.selectedModelId}:{},...R.permissionMode!==void 0?{permissionMode:R.permissionMode}:{},...R.reasoningEffort!==void 0?{reasoningEffort:R.reasoningEffort}:{},...R.serviceTier!==void 0?{serviceTier:R.serviceTier}:{},...R.responseVerbosity!==void 0?{responseVerbosity:R.responseVerbosity}:{},...R.communicationStyle!==void 0?{communicationStyle:R.communicationStyle}:{},...R.communicationStyleDigest!==void 0?{communicationStyleDigest:R.communicationStyleDigest}:{},...R.projectInstructionsDigest!==void 0?{projectInstructionsDigest:R.projectInstructionsDigest}:{},createdAt:X,updatedAt:X}},L=q.getSessionFilePath(O,_);return await new j(L).createExclusive([T]),q.toPublicMetadata(q.projectMetadataFromEntries([T],_,O,L))}static async assertSessionWritable(_,$){let R=await this.findSessionMetadata(_,$);if(!R)throw Error(`Session not found: ${_}`);if(R.archivedAt)throw new V0(_,R.archivedBySessionId??_);return R}static async findArchivedAncestor(_,$){let R=new Set,O=_;while(O){if(R.has(O))throw Error("Session lineage contains a cycle");R.add(O),x(O);let X=u($,O),T;try{T=await T0(X,"utf8")}catch(W){if(W.code==="ENOENT")return;throw W}let L=this.projectMetadataFromEntries(this.parseStoredSession(T,O),O,$,X);if(L.projectPath!==$)throw Error("Session lineage escapes the requested workspace");if(L.archivedAt)return{sessionId:L.sessionId,archivedAt:L.archivedAt};O=L.parentId}return}static async listSessionArchiveMembers(_,$){x(_);let R=this.resolveCatalogWorkspace($),O=await this.scanStoredSessions(R,!0,0,null);if(!O.some((L)=>L.sessionId===_))throw Error(`Session not found: ${_}`);let X=new Set([_]),T=!0;while(T){T=!1;for(let L of O)if(L.parentId&&X.has(L.parentId)&&!X.has(L.sessionId))X.add(L.sessionId),T=!0}return O.filter((L)=>X.has(L.sessionId)).sort((L,W)=>L.sessionId.localeCompare(W.sessionId)).map((L)=>this.toPublicMetadata(L))}static async archiveSession(_,$){x(_);let R=this.resolveCatalogWorkspace($),O=await this.findSessionMetadata(_,R);if(!O)throw Error(`Session not found: ${_}`);if(O.archivedAt)return O;let X=await this.listSessionArchiveMembers(_,R),T=X.find((W)=>W.taskStatus==="queued"||W.taskStatus==="running");if(T)throw new p(`Stop session ${T.sessionId} before archiving this session tree`);let L=[];try{for(let E of X)L.push(await o.acquire(E.sessionId,R));let W=u(R,_),C=new j(W),G=[];return await C.appendValidated((E)=>{let B=this.projectMetadataFromEntries(E,_,R,W);if(B.archivedAt)throw new p(`Session archive state changed concurrently: ${_}`);if(B.taskStatus==="queued"||B.taskStatus==="running")throw new p(`Stop session ${_} before archiving it`);let V=new Date().toISOString(),J={id:P(),sessionId:_,timestamp:V,type:"session_updated",cwd:R,gitBranch:t(R),version:a(),data:{sessionId:_,archivedAt:V,updatedAt:V}};return G=[...E,J],J}),this.toPublicMetadata({...this.projectMetadataFromEntries(G,_,R,W),archivedBySessionId:_})}catch(W){if(W instanceof p)throw W;if(W instanceof d)throw new p(W.message);throw this.sanitizeStoredSessionError(W,_)}finally{for(let W of L.reverse())await W.release()}}static async unarchiveSession(_,$){x(_);let R=this.resolveCatalogWorkspace($),O=await this.findSessionMetadata(_,R);if(!O)throw Error(`Session not found: ${_}`);if(!O.archivedAt)return O;if(O.archivedBySessionId&&O.archivedBySessionId!==_)throw new p(`Unarchive ancestor ${O.archivedBySessionId} to restore session ${_}`);let X;try{X=await o.acquire(_,R);let T=u(R,_),L=new j(T),W=[];return await L.appendValidated((C)=>{if(!this.projectMetadataFromEntries(C,_,R,T).archivedAt)throw new p(`Session archive state changed concurrently: ${_}`);let E=new Date().toISOString(),B={id:P(),sessionId:_,timestamp:E,type:"session_updated",cwd:R,gitBranch:t(R),version:a(),data:{sessionId:_,archivedAt:null,updatedAt:E}};return W=[...C,B],B}),this.toPublicMetadata(this.projectMetadataFromEntries(W,_,R,T))}catch(T){if(T instanceof p)throw T;if(T instanceof d)throw new p(T.message);throw this.sanitizeStoredSessionError(T,_)}finally{await X?.release()}}static async updateSessionMetadata(_,$,R){if(x(_),q.validateTaskMetadataUpdate(R,_),R.taskStatus!==void 0&&!E$.has(R.taskStatus))throw Error(`Invalid session task status: ${String(R.taskStatus)}`);if(R.taskOwnerPid!==void 0&&R.taskOwnerPid!==null&&(!Number.isInteger(R.taskOwnerPid)||R.taskOwnerPid<=0))throw Error("Session task owner PID must be a positive integer");let O=q.resolveCatalogWorkspace($);if(R.taskWorktree&&Y.resolve(R.taskWorktree.workspaceRoot)!==O)throw Error("Session task worktree must match the catalog workspace");let X=q.getSessionFilePath(O,_),T=new j(X),L=[];try{await T.appendValidatedAsync(async(W)=>{let C=q.getSessionCreatedEntry(W,_);if(C.data.sessionId!==_)throw Error(`Session metadata creation record sessionId mismatch: ${_}`);if(!Y.isAbsolute(C.cwd)||Y.resolve(C.cwd)!==O)throw Error(`Session metadata creation record cwd mismatch: ${_}`);let G=q.projectMetadataFromEntries(W,_,O,X);if(G.archivedAt)throw new V0(_,_);if(G.parentId){let V=await q.findArchivedAncestor(G.parentId,O);if(V)throw new V0(_,V.sessionId)}let E=new Date().toISOString(),B={id:P(),sessionId:_,timestamp:E,type:"session_updated",cwd:O,gitBranch:t(O),version:a(),data:{sessionId:_,...R.title!==void 0?{title:R.title}:{},...R.taskStatus!==void 0?{taskStatus:R.taskStatus}:{},...R.taskStatusReason!==void 0?{taskStatusReason:R.taskStatusReason}:{},...R.taskFailure!==void 0?{taskFailure:R.taskFailure}:{},...R.taskStartedAt!==void 0?{taskStartedAt:R.taskStartedAt}:{},...R.taskCompletedAt!==void 0?{taskCompletedAt:R.taskCompletedAt}:{},...R.taskOwnerPid!==void 0?{taskOwnerPid:R.taskOwnerPid}:{},...R.taskPromptSummary!==void 0?{taskPromptSummary:R.taskPromptSummary}:{},...R.taskPriority!==void 0?{taskPriority:R.taskPriority}:{},...R.taskKind!==void 0?{taskKind:R.taskKind}:{},...R.taskDueAt!==void 0?{taskDueAt:R.taskDueAt===null?null:new Date(R.taskDueAt).toISOString()}:{},...R.taskDispatch!==void 0?{taskDispatch:R.taskDispatch}:{},...R.taskModelId!==void 0?{taskModelId:R.taskModelId}:{},...R.taskRetriedFrom!==void 0?{taskRetriedFrom:R.taskRetriedFrom}:{},...R.taskDelivery!==void 0?{taskDelivery:R.taskDelivery}:{},...R.taskIsolation!==void 0?{taskIsolation:R.taskIsolation}:{},...R.taskSourceProjectPath!==void 0?{taskSourceProjectPath:R.taskSourceProjectPath}:{},...R.taskWorktree!==void 0?{taskWorktree:R.taskWorktree}:{},...R.taskDiffStat!==void 0?{taskDiffStat:R.taskDiffStat}:{},...R.taskQueuePosition!==void 0?{taskQueuePosition:R.taskQueuePosition}:{},...R.taskQueueDepth!==void 0?{taskQueueDepth:R.taskQueueDepth}:{},...R.taskConcurrencyLimit!==void 0?{taskConcurrencyLimit:R.taskConcurrencyLimit}:{},...R.selectedModelId!==void 0?{selectedModelId:R.selectedModelId}:{},...R.permissionMode!==void 0?{permissionMode:R.permissionMode}:{},...R.reasoningEffort!==void 0?{reasoningEffort:R.reasoningEffort}:{},...R.serviceTier!==void 0?{serviceTier:R.serviceTier}:{},...R.responseVerbosity!==void 0?{responseVerbosity:R.responseVerbosity}:{},...R.communicationStyle!==void 0?{communicationStyle:R.communicationStyle}:{},...R.communicationStyleDigest!==void 0?{communicationStyleDigest:R.communicationStyleDigest}:{},...R.projectInstructionsDigest!==void 0?{projectInstructionsDigest:R.projectInstructionsDigest}:{},updatedAt:E}};return L=[...W,B],B})}catch(W){throw q.sanitizeStoredSessionError(W,_)}return q.toPublicMetadata(q.projectMetadataFromEntries(L,_,O,X))}static async setSessionPermissionMode(_,$,R){if(x(_),!r0(R))throw Error("Invalid session permission mode");let O=q.resolveCatalogWorkspace($),X=await q.findSessionMetadata(_,O);if(X?.permissionMode===R)return X;if(X)return q.updateSessionMetadata(_,O,{permissionMode:R});try{return await q.createSessionMetadata(_,O,{taskStatus:"completed",permissionMode:R})}catch(T){if(T.code!=="EEXIST")throw T;return q.updateSessionMetadata(_,O,{permissionMode:R})}}static async findSessionTaskWorktree(_,$){x(_);let R=q.resolveCatalogWorkspace($),O=q.getSessionFilePath(R,_);try{return(await q.readStoredSessionMetadata(O,_,R)).taskWorktree}catch(X){if(X.code==="ENOENT")return;throw q.sanitizeStoredSessionError(X,_)}}static async findSessionTaskDispatch(_,$){x(_);let R=q.resolveCatalogWorkspace($),O=q.getSessionFilePath(R,_);try{return(await q.readStoredSessionMetadata(O,_,R)).taskDispatch}catch(X){if(X.code==="ENOENT")return;throw q.sanitizeStoredSessionError(X,_)}}static async loadSessionFromFile(_,$,R){let O=await T0(_,"utf-8"),X=this.parseStoredSession(O,$);if(R!==void 0){if(this.projectMetadataFromEntries(X,$,R,_).projectPath!==R)throw Error(`未找到会话: ${$}`)}return this.convertJSONLToMessages(X)}static async loadSessionModelContextFromFile(_,$,R){let O=await T0(_,"utf-8"),X=this.parseStoredSession(O,$);if(R!==void 0){if(this.projectMetadataFromEntries(X,$,R,_).projectPath!==R)throw Error(`未找到会话: ${$}`)}return this.convertJSONLToModelContext(X)}static convertJSONLToModelContext(_){let $=n(_),R=-1,O;for(let T=0;T<$.length;T++){let L=$[T];if(L?.type!=="part_created"||L.data.partType!=="summary")continue;let W=L.data.payload;if(R=T,O=m0(W.replacementMessages),!O)O=[{role:"user",content:W.text??"",metadata:L.data.payload}]}if(R<0||!O)return this.convertJSONLToMessages($,{includeTokenBudgetHandoffs:!0});let X=this.convertJSONLToMessages($.slice(R+1),{includeTokenBudgetHandoffs:!0});return[...O,...X]}static convertJSONLToMessages(_,$={}){let R=[],O=new Map,X=new Map,T=new Map,L=new Map,W=new Map,C=n(_),G=$.includeTokenBudgetHandoffs?I1(C):{kind:"none"},E=new Set;for(let B of C){if(B.type==="token_budget_handoff_recorded"){if(G.kind==="valid"&&G.event.id===B.id){let V=m1(B);if(V)R.push(V)}continue}if(B.type==="message_created"){let V=B.data.metadata&&typeof B.data.metadata==="object"&&!Array.isArray(B.data.metadata)?B.data.metadata:void 0,J=V?.codeReview&&typeof V.codeReview==="object"&&!Array.isArray(V.codeReview)?V.codeReview:void 0;if(J?.phase==="completed"&&typeof J.reviewId==="string")E.add(J.reviewId);let Q=B.data.role==="assistant"&&B.data.parentMessageId?T.get(B.data.parentMessageId):void 0,A=Q??{role:B.data.role,content:"",...B.data.metadata||B.data.inboxMessageId?{metadata:{...B.data.metadata&&typeof B.data.metadata==="object"&&!Array.isArray(B.data.metadata)?B.data.metadata:{},...B.data.inboxMessageId?{inboxMessageId:B.data.inboxMessageId}:{}}}:{}};if(O.set(B.data.messageId,A),X.set(B.data.messageId,[]),!Q)R.push(A)}if(B.type==="part_created"){if(B.data.partType==="reasoning"){let V=O.get(B.data.messageId);if(V){let J=B.data.payload;V.reasoningContent=(V.reasoningContent??"")+(J.text??"")}}if(B.data.partType==="text"){let V=O.get(B.data.messageId);if(V){let J=B.data.payload,Q=X.get(B.data.messageId);if(Q)Q.push({type:"text",text:J.text??""}),V.content=U$(Q);else V.content=J.text??""}}if(B.data.partType==="image"){let V=O.get(B.data.messageId);if(V){let J=B.data.payload,Q=X.get(B.data.messageId);if(Q&&J.dataUrl)Q.push({type:"image_url",image_url:{url:J.dataUrl}}),V.content=U$(Q)}}if(B.data.partType==="tool_call"){let V=O.get(B.data.messageId);if(V?.role!=="assistant"){if(V=T.get(B.data.messageId),!V)V={role:"assistant",content:"",tool_calls:[]},T.set(B.data.messageId,V),R.push(V)}if(V.role==="assistant"){let J=B.data.payload,Q=J.toolCallId??B.data.partId;L.set(B.data.partId,Q),W.set(Q,V),V.tool_calls??=[],V.tool_calls.push({id:Q,type:"function",function:{name:J.toolName??"unknown",arguments:JSON.stringify(J.input??{})}})}}if(B.data.partType==="tool_result"){let V=B.data.payload,J=n1(V),Q=J.error?`Error: ${J.error.message}`:typeof J.llmContent==="string"?J.llmContent:JSON.stringify(J.llmContent),A=V;R.push({role:"tool",content:Q,tool_call_id:L.get(B.data.messageId)??V.toolCallId,name:V.toolName,metadata:A})}if(B.data.partType==="summary"){let V=B.data.payload,J=B.data.payload;R.push({role:"system",content:V.text??"",metadata:J})}if(B.data.partType==="subtask_ref"){let V=O.get(B.data.messageId)??W.get(B.data.messageId);if(V){let J=B.data.payload,Q=V.metadata??{};V.metadata={...Q,subtaskRef:J}}}}}for(let B of v0(C)){if(B.completion===void 0||E.has(B.start.reviewId))continue;R.push({role:"assistant",content:k1(B.start,B.completion),metadata:{codeReview:{...S1(B.start,B.completion),synthetic:!0}}})}return R}static projectionDeriver(){return(_,$,R)=>{try{let O=u(R,$);return this.projectMetadataFromEntries(_,$,R,O)}catch{return null}}}static projectionDeriverForSearch(){return this.projectionDeriver()}static async scanStoredSessionsFromProjection(_,$,R=0,O=!1,X={}){try{let T=await d0();if(!T)return null;await i_(T,this.projectionDeriver(),R);let L=[],W=[];if(_!==void 0)L.push("project_path=?"),W.push(_);O2(X,"",L,W);let C=L.length>0?` WHERE ${L.join(" AND ")}`:"",G=T.prepare(`SELECT metadata_json, is_subagent FROM sessions${C}`).all(...W),E=[];for(let V of G){if(!$&&V.is_subagent===1)continue;try{let J=JSON.parse(V.metadata_json);if(_!==void 0&&J.projectPath!==_)continue;E.push(J)}catch{}}let B=await Promise.all(E.map((V)=>this.reconcileInterruptedTask(V)));return u_(B.filter((V)=>w$(V,X)),O)}catch{return null}}static async scanStoredSessions(_,$=!1,R=0,O=!1,X={}){let T=_?Y.resolve(_):void 0,L=await this.scanStoredSessionsFromProjection(T,$,R,O,X);if(L)return L;let W=T?[{storagePath:Q0(T),projectPath:T}]:await this.listAllProjectStorageDirectories(),C=[];for(let G of W){let E;try{E=await v_(G.storagePath)}catch(B){if(B.code==="ENOENT")continue;throw B}for(let B of E){if(!B.endsWith(".jsonl"))continue;let V=B.slice(0,-6),J=Y.join(G.storagePath,B);try{let Q=await this.readStoredSessionMetadata(J,V,G.projectPath);if(T!==void 0&&Q.projectPath!==T){q0.warn(`[SessionService] Skipping out-of-scope session transcript: ${V}`);continue}if(!$&&Q.relationType==="subagent")continue;if(!T2(Q,X))continue;C.push(Q)}catch(Q){let A=Q.code;if(A==="ENOENT")continue;if(A)throw Q;q0.warn(`[SessionService] Skipping invalid session transcript: ${V}`)}}}return u_(C,O)}static async listAllProjectStorageDirectories(){let _=Y.join(k(),"projects"),$;try{$=await v_(_,{withFileTypes:!0,encoding:"utf8"})}catch(R){if(R.code==="ENOENT")return[];throw R}return $.filter((R)=>R.isDirectory()).map((R)=>({storagePath:Y.join(_,R.name),projectPath:q$(R.name)}))}static async readStoredSessionMetadata(_,$,R){let O=await T0(_,"utf-8"),X=this.parseStoredSession(O,$);return this.reconcileInterruptedTask(this.projectMetadataFromEntries(X,$,R,_))}static async reconcileInterruptedTask(_){let $=_.taskOwnerPid;if(_.taskStatus!=="running"||$===void 0||J$($))return _;let R;try{R=await o.acquire(_.sessionId,_.projectPath)}catch(T){if(!(T instanceof d))throw T;let L=await T0(_.filePath,"utf-8");return this.projectMetadataFromEntries(this.parseStoredSession(L,_.sessionId),_.sessionId,_.projectPath,_.filePath)}let O=new j(_.filePath),X;try{try{await O.appendValidated((T)=>{let L=this.projectMetadataFromEntries(T,_.sessionId,_.projectPath,_.filePath);if(L.taskStatus!=="running"||L.taskOwnerPid!==$||J$($))throw new o_;let W=new Date().toISOString(),C={id:P(),sessionId:_.sessionId,timestamp:W,type:"session_updated",cwd:_.projectPath,gitBranch:t(_.projectPath),version:a(),data:{sessionId:_.sessionId,taskStatus:"interrupted",taskStatusReason:"Task owner process exited before completion",taskCompletedAt:W,taskOwnerPid:null,taskQueuePosition:null,taskQueueDepth:null,updatedAt:W}};return X=[...T,C],C})}catch(T){if(!(T instanceof o_))throw T}if(!X){let T=await T0(_.filePath,"utf-8");X=this.parseStoredSession(T,_.sessionId)}return this.projectMetadataFromEntries(X,_.sessionId,_.projectPath,_.filePath)}finally{await R.release()}}static projectMetadataFromEntries(_,$,R,O){if(_.length===0)throw Error(`Empty session transcript: ${$}`);let X=this.getSessionCreatedEntry(_,$),T=_.reduce((F,Y0)=>Y0.type==="session_updated"?{...F,...Y0.data}:F,{...X.data}),L=n(_),W=b1(w1(L)),G=v0(L).at(-1),E=L.findLastIndex((F)=>F.type==="review_started"&&F.data.reviewId===G?.start.reviewId||F.type==="review_completed"&&F.data.reviewId===G?.start.reviewId),B=L.findLastIndex((F)=>(F.type==="session_created"||F.type==="session_updated")&&Object.hasOwn(F.data,"taskStatus")),V=G!==void 0&&E>B,J=V?G.completion===void 0?"running":G.completion.status==="completed"||G.completion.status==="stale"?"completed":G.completion.status==="aborted"?"cancelled":G.completion.status==="interrupted"?"interrupted":"failed":void 0,Q=L.filter((F)=>F.type==="message_created"&&["user","assistant"].includes(F.data.role)).length,A=L.some((F)=>F.type==="part_created"&&F.data.partType==="tool_result"&&typeof F.data.payload.error==="string"),b=E$.has(T.taskStatus)?T.taskStatus:void 0,K=J??b??(A?"failed":"completed"),X0=typeof T.taskOwnerPid==="number"&&Number.isInteger(T.taskOwnerPid)&&T.taskOwnerPid>0?T.taskOwnerPid:void 0,L0=d_.has(T.taskIsolation)?T.taskIsolation:void 0,y=typeof T.taskSourceProjectPath==="string"&&Y.isAbsolute(T.taskSourceProjectPath)?Y.resolve(T.taskSourceProjectPath):void 0,I=X.cwd;if(I!==void 0&&!Y.isAbsolute(I))throw Error(`Session catalog cwd must be absolute: ${$}`);let f=I===void 0?R:Y.resolve(I),D=Y$(T.taskWorktree),w=D?.sessionId===$&&Y.resolve(D.workspaceRoot)===f?D:void 0,N=Z$(T.taskDiffStat),z=N$(T.taskDispatch),r_=t0.has(T.taskPriority)?T.taskPriority:z?.taskPriority,t_=a0.has(T.taskKind)?T.taskKind:z?.taskKind,a_=typeof T.taskDueAt==="string"&&Number.isFinite(Date.parse(T.taskDueAt))?new Date(T.taskDueAt).toISOString():z?.taskDueAt,s0=typeof T.taskModelId==="string"&&T.taskModelId.trim()?T.taskModelId:z?.modelId,s_=typeof T.selectedModelId==="string"&&T.selectedModelId.trim()?T.selectedModelId:s0,e_=r0(T.permissionMode)?T.permissionMode:z?.permissionMode,_1=D0(T.reasoningEffort)?T.reasoningEffort:z?.reasoningEffort,$1=F0(T.serviceTier)?T.serviceTier:z?.serviceTier,R1=M0(T.responseVerbosity)?T.responseVerbosity:z?.responseVerbosity,e0=f0(T.communicationStyle)?T.communicationStyle:z?.communicationStyle,__=Object.hasOwn(T,"communicationStyleDigest")?typeof T.communicationStyleDigest==="string"&&/^[a-f0-9]{64}$/.test(T.communicationStyleDigest)?T.communicationStyleDigest:void 0:e0===z?.communicationStyle?z?.communicationStyleDigest:void 0,$_=Object.hasOwn(T,"projectInstructionsDigest")?typeof T.projectInstructionsDigest==="string"&&/^[a-f0-9]{64}$/.test(T.projectInstructionsDigest)?T.projectInstructionsDigest:void 0:z?.projectInstructionsDigest,R_=S$(T.archivedAt)?T.archivedAt:void 0,O_=H$(T.taskRetriedFrom),E0=Q$(T.taskDelivery),J0=typeof T.taskQueuePosition==="number"&&Number.isInteger(T.taskQueuePosition)&&T.taskQueuePosition>0?T.taskQueuePosition:void 0,z0=typeof T.taskQueueDepth==="number"&&Number.isInteger(T.taskQueueDepth)&&T.taskQueueDepth>=0?T.taskQueueDepth:void 0,T_=typeof T.taskConcurrencyLimit==="number"&&Number.isInteger(T.taskConcurrencyLimit)&&T.taskConcurrencyLimit>0?T.taskConcurrencyLimit:void 0,U=V?G?.completion?G.completion.status==="completed"?void 0:`Code review ${N_(G.completion.status)}`:`Reviewing ${G?.start.target.label??"changes"}`:void 0,m=V?K==="failed"&&U?F_(U):void 0:D_(T.taskFailure)?T.taskFailure:K==="failed"&&typeof T.taskStatusReason==="string"?F_(T.taskStatusReason):void 0;return{sessionId:$,projectPath:f,gitBranch:X.gitBranch,rootId:T.rootId||$,parentId:T.parentId,relationType:T.relationType,resumedFrom:T.resumedFrom,rootAgentId:T.rootAgentId,resumeDepth:T.resumeDepth,title:T.title,agentType:T.agentType,model:T.model,selectedModelId:s_,permissionMode:e_,reasoningEffort:_1,serviceTier:$1,responseVerbosity:R1,communicationStyle:e0,communicationStyleDigest:__,projectInstructionsDigest:$_,pendingInteraction:W,taskStatus:K,taskStatusReason:m?.message??U??(typeof T.taskStatusReason==="string"?T.taskStatusReason:void 0),taskFailure:m,taskStartedAt:V?G?.start.startedAt:typeof T.taskStartedAt==="string"?T.taskStartedAt:void 0,taskCompletedAt:V?G?.completion?.completedAt:typeof T.taskCompletedAt==="string"?T.taskCompletedAt:void 0,taskPromptSummary:V?G?B2(G.start.target):"/review uncommitted":typeof T.taskPromptSummary==="string"?T.taskPromptSummary:void 0,taskPriority:r_,taskKind:t_,taskDueAt:a_,taskModelId:s0,taskRetryAvailable:z!==void 0,taskRetriedFrom:O_,taskDelivery:E0,taskIsolation:L0,taskSourceProjectPath:y,taskWorktreePath:w?.worktreeRoot,taskWorktreeBranch:w?.branch,taskBaseCommit:w?.baseCommit,taskDiffStat:N,taskQueuePosition:J0,taskQueueDepth:z0,taskConcurrencyLimit:T_,archivedAt:R_,taskOwnerPid:V?void 0:X0,taskWorktree:w,taskDispatch:z,messageCount:Q,firstMessageTime:_[0].timestamp,lastMessageTime:_.at(-1).timestamp,hasErrors:A||K==="failed",filePath:O}}static toPublicMetadata(_){let{filePath:$,taskOwnerPid:R,taskWorktree:O,taskDispatch:X,...T}=_;return T}static getSessionFilePath(_,$){return u(_,$)}static getSessionCreatedEntry(_,$){let R=_.find((O)=>O.type==="session_created");if(!R)throw new k$($);return R}static resolveCatalogWorkspace(_){if(!Y.isAbsolute(_))throw Error("Session catalog cwd must be absolute");return Y.resolve(_)}static validateSessionWorkspace(_,$,R){let O=this.getSessionCreatedEntry(_,$);if(O.data.sessionId!==$)throw Error(`Session creation record sessionId mismatch: ${$}`);if(!Y.isAbsolute(O.cwd)||Y.resolve(O.cwd)!==R)throw Error(`Session creation record cwd mismatch: ${$}`)}static resolveForkWorkspace(_){if(!Y.isAbsolute(_))throw Error("Fork workspace paths must be absolute");return Y.resolve(_)}static parseStoredSession(_,$){return D$(_,`session ${$}`)}static isCorruptSessionJSONLError(_){return _ instanceof Error&&_.message.startsWith("Invalid session JSONL ")}static sanitizeStoredSessionError(_,$){if(!this.isCorruptSessionJSONLError(_)||!(_ instanceof Error))return _;let R=_.message.match(/ at line (\d+)$/)?.[1];return Error(`Invalid session JSONL in session ${$}${R?` at line ${R}`:""}`,{cause:_.cause})}static async readStableSessionSnapshot(_,$,R=3){for(let O=0;O<R;O+=1){let X=await K0.stat(_),T=await K0.readFile(_),L=this.parseStoredSession(T,$),W=await K0.stat(_);if(X.size===W.size&&X.mtimeNs===W.mtimeNs&&X.dev===W.dev&&X.ino===W.ino)return L}throw Error("Session changed while creating fork; retry the operation")}}function U$(_){if(_.length===1&&_[0]?.type==="text")return _[0].text;return[..._]}
118
- export{J_ as ac,f_ as bc,O1 as cc,x0 as dc,X1 as ec,j2 as fc,d as gc,o as hc,p$ as ic,E1 as jc,e as kc,e2 as lc,_O as mc,$O as nc,RO as oc,OO as pc,TO as qc,XO as rc,LO as sc,WO as tc,BO as uc,CO as vc,GO as wc,VO as xc,EO as yc,JO as zc,YO as Ac,QO as Bc,ZO as Cc,NO as Dc,HO as Ec,UO as Fc,qO as Gc,AO as Hc,KO as Ic,MO as Jc,FO as Kc,DO as Lc,fO as Mc,zO as Nc,xO as Oc,wO as Pc,bO as Qc,M1 as Rc,OR as Sc,Q_ as Tc,f1 as Uc,IO as Vc,mO as Wc,w1 as Xc,uO as Yc,v0 as Zc,cO as _c,N_ as $c,k1 as ad,S1 as bd,pO as cd,iO as dd,dO as ed,QR as fd,I1 as gd,m1 as hd,ZR as id,oO as jd,C0 as kd,F_ as ld,D_ as md,r as nd,c0 as od,CT as pd,GT as qd,VT as rd,ET as sd,n1 as td,JT as ud,QT as vd,l1 as wd,NT as xd,k_ as yd,S_ as zd,FT as Ad,DT as Bd,s1 as Cd,l0 as Dd,kT as Ed,G$ as Fd,O$ as Gd,yT as Hd,V$ as Id,IT as Jd,W2 as Kd,J4 as Ld,Y4 as Md,k$ as Nd,V0 as Od,p as Pd,q as Qd};
118
+ export{J_ as dc,f_ as ec,O1 as fc,x0 as gc,X1 as hc,j2 as ic,d as jc,o as kc,p$ as lc,E1 as mc,e as nc,e2 as oc,_O as pc,$O as qc,RO as rc,OO as sc,TO as tc,XO as uc,LO as vc,WO as wc,BO as xc,CO as yc,GO as zc,VO as Ac,EO as Bc,JO as Cc,YO as Dc,QO as Ec,ZO as Fc,NO as Gc,HO as Hc,UO as Ic,qO as Jc,AO as Kc,KO as Lc,MO as Mc,FO as Nc,DO as Oc,fO as Pc,zO as Qc,xO as Rc,wO as Sc,bO as Tc,M1 as Uc,OR as Vc,Q_ as Wc,f1 as Xc,IO as Yc,mO as Zc,w1 as _c,uO as $c,v0 as ad,cO as bd,N_ as cd,k1 as dd,S1 as ed,pO as fd,iO as gd,dO as hd,QR as id,I1 as jd,m1 as kd,ZR as ld,oO as md,C0 as nd,F_ as od,D_ as pd,r as qd,c0 as rd,CT as sd,GT as td,VT as ud,ET as vd,n1 as wd,JT as xd,QT as yd,l1 as zd,NT as Ad,k_ as Bd,S_ as Cd,FT as Dd,DT as Ed,s1 as Fd,l0 as Gd,kT as Hd,G$ as Id,O$ as Jd,yT as Kd,V$ as Ld,IT as Md,W2 as Nd,J4 as Od,Y4 as Pd,k$ as Qd,V0 as Rd,p as Sd,q as Td};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "blade-code",
3
- "version": "0.10.106",
3
+ "version": "0.10.108",
4
4
  "private": false,
5
5
  "description": "🗡️ Blade Code - 智能代码助手命令行工具",
6
6
  "type": "module",
@@ -1 +0,0 @@
1
- import{oe as a,pe as b}from"./chunk-z0manfyv.js";import"./chunk-xzy7vtdf.js";import"./chunk-fhfzdyba.js";export{a as globalOptions,b as cliConfig};
@@ -1,2 +0,0 @@
1
- import{gh as H,hh as I}from"./chunk-wvnw6wfz.js";import{Mutex as J}from"async-mutex";class B extends Error{limit;resource="resident_runtimes";retryable=!0;constructor(b){super("Session runtime capacity is full");this.limit=b;this.name="SessionRuntimeCapacityError"}}class D extends Error{constructor(){super("Session runtime residency is closed");this.name="SessionRuntimeResidencyClosedError"}}class A extends Error{constructor(b){super(`Session runtime residency already owns key: ${b}`);this.name="SessionRuntimeResidencyConflictError"}}class K{maxResident;idleMs;now;residents=new Map;reservations=new Map;operations=new J;nextGeneration=1;closed=!1;constructor(b){if(!H(b.maxResident))throw Error("Invalid max resident Session Runtime limit");if(!I(b.idleMs))throw Error("Invalid Session Runtime idle timeout");this.maxResident=b.maxResident,this.idleMs=b.idleMs,this.now=b.now??Date.now}acquire(b){let j=this.residents.get(b);if(!j||j.poisoned)return;return j.pins++,j.lastUsedAt=this.now(),this.createLease(j)}owns(b,j){let q=this.residents.get(b);return Boolean(q&&(j===void 0||q.value===j))}async reserve(b,j){if(!b.trim())throw Error("Session runtime residency key must not be blank");return this.operations.runExclusive(async()=>{if(this.closed)throw new D;if(this.residents.has(b)||this.reservations.has(b))throw new A(b);while(this.retainedCount()>=this.maxResident){if(!j.allowEviction)throw new B(this.maxResident);let z=this.oldestEvictableWebResident();if(!z)throw new B(this.maxResident);await this.disposeResident(z,!0)}let q={generation:this.allocateGeneration(),surface:j.surface};return this.reservations.set(b,q),this.createReservation(b,q)})}async remove(b,j){return this.operations.runExclusive(async()=>{let q=this.residents.get(b);if(!q||j!==void 0&&q.value!==j)return!1;if(q.pins>0)return!1;return await this.disposeResident(q,!0),!0})}async forget(b,j){return this.operations.runExclusive(async()=>{let q=this.residents.get(b);if(!q||j!==void 0&&q.value!==j||q.pins>0)return!1;return this.residents.delete(b),!0})}async sweepIdle(){return this.operations.runExclusive(async()=>{if(this.closed)return 0;let b=0;while(!0){let j=this.oldestIdleWebResident();if(!j)return b;await this.disposeResident(j,!0),b++}})}async disposeAll(){await this.operations.runExclusive(async()=>{this.closed=!0,this.reservations.clear();let b;for(let j of[...this.residents.values()])try{await this.disposeResident(j,!1)}catch(q){b??=q}if(this.residents.clear(),b!==void 0)throw b})}getStats(){let b=0;for(let j of this.residents.values())if(j.pins>0)b++;return{resident:this.residents.size,reserved:this.reservations.size,pinned:b,maxResident:this.maxResident}}retainedCount(){return this.residents.size+this.reservations.size}allocateGeneration(){let b=this.nextGeneration;return this.nextGeneration=this.nextGeneration===Number.MAX_SAFE_INTEGER?1:this.nextGeneration+1,b}createReservation(b,j){let q=!1;return{commit:(z)=>{if(q)throw new A(b);if(z.key!==b||z.surface!==j.surface||this.reservations.get(b)!==j||this.closed)throw this.reservations.delete(b),q=!0,this.closed?new D:new A(b);this.reservations.delete(b);let G={...z,generation:j.generation,pins:1,lastUsedAt:this.now(),poisoned:!1};return this.residents.set(b,G),q=!0,this.createLease(G)},cancel:()=>{if(q)return;if(this.reservations.get(b)===j)this.reservations.delete(b);q=!0}}}createLease(b){let j=!1;return{value:b.value,release:()=>{if(j)return;j=!0;let q=this.residents.get(b.key);if(q!==b||q.generation!==b.generation)return;q.pins=Math.max(0,q.pins-1),q.lastUsedAt=this.now()}}}oldestEvictableWebResident(){return this.sortedWebResidents().find((b)=>this.canEvict(b))}oldestIdleWebResident(){let b=this.now();return this.sortedWebResidents().find((j)=>b-j.lastUsedAt>=this.idleMs&&this.canEvict(j))}sortedWebResidents(){return[...this.residents.values()].filter((b)=>b.surface==="web").sort((b,j)=>b.lastUsedAt-j.lastUsedAt||b.generation-j.generation)}canEvict(b){if(b.pins>0||b.poisoned)return!1;try{return b.canEvict()}catch{return!1}}async disposeResident(b,j){if(this.residents.get(b.key)!==b)return;this.residents.delete(b.key);try{await b.dispose()}catch(q){if(j&&!this.closed&&!this.residents.has(b.key))b.lastUsedAt=this.now(),b.poisoned=!0,this.residents.set(b.key,b);throw q}}}
2
- export{B as s,K as t};
@@ -1 +0,0 @@
1
- import{Nf as a,Of as b,Pf as c,Qf as d,Rf as e,Sf as f,Tf as g,Uf as h,Vf as i,Wf as j}from"./chunk-bxrnsq3n.js";import"./chunk-kf7whgr7.js";import"./chunk-fva7jnjy.js";import"./chunk-41ympwz1.js";import"./chunk-szkxjpr1.js";import"./chunk-41cg66y0.js";import"./chunk-wvnw6wfz.js";import"./chunk-sdbbyagy.js";import"./chunk-f3426b1c.js";import"./chunk-c475tfqf.js";import"./chunk-0hr050ck.js";import"./chunk-q69fzq4y.js";import"./chunk-n7mzxa8h.js";import"./chunk-s10pmnrd.js";import"./chunk-9p20hhs0.js";import"./chunk-xzy7vtdf.js";import"./chunk-wyhyw9rq.js";import"./chunk-rvk9r2cm.js";import"./chunk-tgdhsm5t.js";import"./chunk-fhfzdyba.js";export{g as withWorkspaceAgentResources,i as snapshotWorkspaceAgentResources,f as resolveWorkspaceAgentResources,j as resetWorkspaceAgentResources,d as refreshWorkspaceCommunicationStyles,h as getWorkspaceAgentResourceCacheStats,e as configureInvocationPluginDirs,c as WorkspaceAgentResourceCapacityError,a as MAX_RESIDENT_WORKSPACE_AGENT_RESOURCES,b as MAX_ACTIVE_WORKSPACE_AGENT_RESOURCES};
@@ -1 +0,0 @@
1
- import{a,b as i,c as l,d as m}from"./chunk-95xnc5t8.js";import"./chunk-7fz3w4rk.js";import"./chunk-47e6tdbb.js";import"./chunk-4ywjs5fw.js";import"./chunk-wcm4hm35.js";import"./chunk-1b4rh25n.js";import"./chunk-v6zjf4jx.js";import"./chunk-abd57h72.js";import"./chunk-zvawerhj.js";import"./chunk-xm8nyj5z.js";import"./chunk-51ep7gct.js";import"./chunk-8hprmrd5.js";import"./chunk-rtnyzakh.js";import"./chunk-s0tq8gyx.js";import"./chunk-x3cxmwnz.js";import{ve as n}from"./chunk-b8q7vjd9.js";import"./chunk-z9gd9spf.js";import{Re as s}from"./chunk-w2a5dqg5.js";import"./chunk-v508x7cg.js";import"./chunk-dg0d3303.js";import"./chunk-rchz6j90.js";import"./chunk-w7hy5wh1.js";import"./chunk-2hb222re.js";import"./chunk-2a03fwgm.js";import"./chunk-bxrnsq3n.js";import"./chunk-kf7whgr7.js";import"./chunk-fva7jnjy.js";import"./chunk-41ympwz1.js";import"./chunk-szkxjpr1.js";import"./chunk-41cg66y0.js";import"./chunk-wvnw6wfz.js";import"./chunk-sdbbyagy.js";import"./chunk-f3426b1c.js";import"./chunk-c475tfqf.js";import"./chunk-0hr050ck.js";import"./chunk-q69fzq4y.js";import"./chunk-n7mzxa8h.js";import"./chunk-s10pmnrd.js";import"./chunk-9p20hhs0.js";import"./chunk-xzy7vtdf.js";import"./chunk-wyhyw9rq.js";import"./chunk-rvk9r2cm.js";import"./chunk-tgdhsm5t.js";import"./chunk-fhfzdyba.js";import v from"chalk";var C={command:"serve",describe:"Start a headless Blade server (no browser)",builder:a,handler:async(p)=>{let r=i(p);if(await s(),!process.env.BLADE_SERVER_PASSWORD)console.log(v.yellow("Warning: BLADE_SERVER_PASSWORD is not set; server is unsecured."));let e=await m.listenAsync(r);if(console.log(`Blade server listening on http://${e.hostname}:${e.port}`),r.hostname==="0.0.0.0"){let o=l();for(let g of o)console.log(` Network: http://${g}:${e.port}`)}let t,c=new Promise((o)=>{t=o}),d=n(async()=>{await e.stop(),t()});try{await c}finally{d(),await e.stop()}}};export{C as serveCommand};