blade-code 0.10.5 → 0.10.7

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 (108) hide show
  1. package/dist/blade.js +2 -2
  2. package/dist/{chunk-z906d5tb.js → chunk-0n04bmta.js} +2 -2
  3. package/dist/{chunk-drrdzmaa.js → chunk-0xm8hn2h.js} +2 -2
  4. package/dist/chunk-0z7q89w7.js +2 -0
  5. package/dist/{chunk-gxmrakrk.js → chunk-1sw9z975.js} +1 -1
  6. package/dist/{chunk-948qe2pp.js → chunk-1v7hpr34.js} +1 -1
  7. package/dist/{chunk-fvhc1yj8.js → chunk-3fdyzgpv.js} +1 -1
  8. package/dist/{chunk-15d49qty.js → chunk-43j2f1b5.js} +1 -1
  9. package/dist/{chunk-njyvrtje.js → chunk-4hhkbyja.js} +2 -2
  10. package/dist/{chunk-6eragc74.js → chunk-4rhssb85.js} +2 -2
  11. package/dist/chunk-598egka3.js +22 -0
  12. package/dist/chunk-5ak9tw83.js +100 -0
  13. package/dist/chunk-738pkjf8.js +1 -0
  14. package/dist/{chunk-xv0maezy.js → chunk-7a200q5g.js} +2 -2
  15. package/dist/{chunk-5twefby5.js → chunk-7pkrwh10.js} +1 -1
  16. package/dist/chunk-7xfmzvxp.js +1 -0
  17. package/dist/{chunk-9ffr01c3.js → chunk-847e0sk9.js} +1 -1
  18. package/dist/chunk-867rz2ss.js +1 -0
  19. package/dist/chunk-a3e97syg.js +3 -0
  20. package/dist/{chunk-0n97186m.js → chunk-ahxc3n3g.js} +2 -2
  21. package/dist/{chunk-tq52pbde.js → chunk-akev4wsz.js} +1 -1
  22. package/dist/{chunk-epj56s0n.js → chunk-az4b6106.js} +1 -1
  23. package/dist/{chunk-63ysxybd.js → chunk-e9ckf8e7.js} +1 -1
  24. package/dist/chunk-f7854pbx.js +187 -0
  25. package/dist/chunk-fwt0kje3.js +1 -0
  26. package/dist/{chunk-1vx4sf1y.js → chunk-g1q27q6q.js} +2 -2
  27. package/dist/chunk-g3wgzyhx.js +160 -0
  28. package/dist/chunk-g4snq0dx.js +1 -0
  29. package/dist/chunk-ggm04adj.js +1 -0
  30. package/dist/chunk-hpytxsge.js +1 -0
  31. package/dist/chunk-htr91q9c.js +1 -0
  32. package/dist/chunk-hwcp940f.js +1 -0
  33. package/dist/chunk-j5ysjbyr.js +10 -0
  34. package/dist/{chunk-jza1rsan.js → chunk-jpy61wna.js} +1 -1
  35. package/dist/chunk-kqpwz9b7.js +8 -0
  36. package/dist/{chunk-gxzbv67r.js → chunk-m86ekqp0.js} +2 -2
  37. package/dist/{chunk-51wtvmzn.js → chunk-m8k1mv0j.js} +1 -1
  38. package/dist/{chunk-ydtcvxsm.js → chunk-mt4328yf.js} +1 -1
  39. package/dist/{chunk-35yktzm1.js → chunk-ne7zdjrh.js} +1 -1
  40. package/dist/{chunk-bexgcc2d.js → chunk-p0j8994h.js} +1 -1
  41. package/dist/{chunk-gb54hc78.js → chunk-p3ahf1fh.js} +1 -1
  42. package/dist/chunk-pt659n0v.js +1466 -0
  43. package/dist/chunk-q1gfeadm.js +1 -0
  44. package/dist/{chunk-vntzy7bc.js → chunk-qk2z6gag.js} +2 -2
  45. package/dist/{chunk-ea7wsges.js → chunk-qqwgb9ja.js} +2 -2
  46. package/dist/{chunk-am8dtvff.js → chunk-qycwavck.js} +72 -17
  47. package/dist/chunk-rk1w5pry.js +2 -0
  48. package/dist/{chunk-s645azsm.js → chunk-rn908m3v.js} +2 -2
  49. package/dist/{chunk-dqvcgwhe.js → chunk-rz2ftt6h.js} +2 -2
  50. package/dist/{chunk-19kg7yvw.js → chunk-rz9yh6e4.js} +2 -2
  51. package/dist/{chunk-qm11hjd3.js → chunk-tc83e1b0.js} +1 -1
  52. package/dist/{chunk-v93hcxe7.js → chunk-tcc3v4n2.js} +1 -1
  53. package/dist/{chunk-g6h6h8xr.js → chunk-tp9zk241.js} +1 -1
  54. package/dist/chunk-tzh4ahry.js +6 -0
  55. package/dist/chunk-v0rn831t.js +1 -0
  56. package/dist/{chunk-fz1vyc15.js → chunk-vafn0spm.js} +1 -1
  57. package/dist/{chunk-rh7v814a.js → chunk-vcq624qv.js} +2 -2
  58. package/dist/chunk-vynsgc2g.js +1 -0
  59. package/dist/{chunk-qda309d9.js → chunk-w01sec4f.js} +2 -2
  60. package/dist/chunk-w0ena7fe.js +9 -0
  61. package/dist/{chunk-6tx8k249.js → chunk-wmdgb5pz.js} +2 -2
  62. package/dist/{chunk-an96c54z.js → chunk-wrbm6rch.js} +8 -8
  63. package/dist/{chunk-sanhjqpd.js → chunk-x3780wpy.js} +2 -2
  64. package/dist/{chunk-yc53wz4r.js → chunk-y573s5r8.js} +2 -2
  65. package/dist/chunk-ydwjttdz.js +1 -0
  66. package/dist/{chunk-vpj0sv73.js → chunk-yyvx1avz.js} +3 -3
  67. package/dist/chunk-z9fsh3kn.js +1 -0
  68. package/dist/{chunk-ygx03mdh.js → chunk-zjf1z27e.js} +1 -1
  69. package/dist/web/assets/ChatView-BYfHmxKJ.js +7 -0
  70. package/dist/web/assets/{CodeBlockHighlighter-CFW6qjnA.js → CodeBlockHighlighter-CC4e9nFc.js} +1 -1
  71. package/dist/web/assets/{FilePreview-CR_XetY0.js → FilePreview-C3HEoLYS.js} +1 -1
  72. package/dist/web/assets/{MarkdownRenderer-CVrxJswQ.js → MarkdownRenderer-COycrGUX.js} +3 -3
  73. package/dist/web/assets/{McpModal-BO-85gll.js → McpModal-CDgr9kVq.js} +1 -1
  74. package/dist/web/assets/{SettingsModal-CW87OnxI.js → SettingsModal-CvdVIbeG.js} +1 -1
  75. package/dist/web/assets/{SkillsModal-Q8ZFPhys.js → SkillsModal-lSX1ZKTu.js} +1 -1
  76. package/dist/web/assets/{TaskSwitcher-BzH-0QXr.js → TaskSwitcher-peKi9KvN.js} +1 -1
  77. package/dist/web/assets/{TerminalPanel-DTqvx8yB.js → TerminalPanel-DqQ-7CTG.js} +1 -1
  78. package/dist/web/assets/index-BF5HEN_f.js +32 -0
  79. package/dist/web/assets/index-BrkTYxtS.css +1 -0
  80. package/dist/web/index.html +2 -2
  81. package/package.json +1 -1
  82. package/dist/chunk-069zpw09.js +0 -6
  83. package/dist/chunk-1m5r6mp2.js +0 -180
  84. package/dist/chunk-1q21sxhx.js +0 -1
  85. package/dist/chunk-1r6szcrj.js +0 -1
  86. package/dist/chunk-1x4fpe47.js +0 -1
  87. package/dist/chunk-2nkd1kjx.js +0 -1
  88. package/dist/chunk-417wefq7.js +0 -99
  89. package/dist/chunk-4ncbd4k0.js +0 -1
  90. package/dist/chunk-62881c2s.js +0 -1484
  91. package/dist/chunk-7443b95r.js +0 -1
  92. package/dist/chunk-79s052sw.js +0 -2
  93. package/dist/chunk-7jy60gnx.js +0 -1
  94. package/dist/chunk-c5tds5v0.js +0 -9
  95. package/dist/chunk-ccwskwb3.js +0 -1
  96. package/dist/chunk-f6mszdsd.js +0 -1
  97. package/dist/chunk-hh85pk77.js +0 -160
  98. package/dist/chunk-nz78b5c5.js +0 -10
  99. package/dist/chunk-r1764q6f.js +0 -1
  100. package/dist/chunk-r6mwyg3h.js +0 -3
  101. package/dist/chunk-rzzt21ef.js +0 -22
  102. package/dist/chunk-t8x2qpe2.js +0 -1
  103. package/dist/chunk-tjnfhm9v.js +0 -1
  104. package/dist/chunk-v0ygsjry.js +0 -1
  105. package/dist/chunk-zyz82mcd.js +0 -1
  106. package/dist/web/assets/ChatView-Y-6k-ayR.js +0 -7
  107. package/dist/web/assets/index-B7etZcne.css +0 -1
  108. package/dist/web/assets/index-ClOgGy-I.js +0 -32
@@ -1,99 +0,0 @@
1
- import{Ab as i0,Cb as z0,Fb as d0,Gb as v$,rb as j$,sb as v,tb as l0,ub as S$,vb as c0,wb as p0,xb as n0,yb as o,zb as m$}from"./chunk-an96c54z.js";import{Fc as H0}from"./chunk-gxmrakrk.js";import{ad as L0}from"./chunk-35yktzm1.js";import{jd as N$}from"./chunk-qm11hjd3.js";import{nd as Y0}from"./chunk-qda309d9.js";import{le as f$,me as y$}from"./chunk-79s052sw.js";import{re as Q$}from"./chunk-epj56s0n.js";import{Ae as Q0,xe as Z0}from"./chunk-bexgcc2d.js";import{Ee as l}from"./chunk-1vx4sf1y.js";import{Le as g$,Me as V0,Oe as z,Pe as S,Re as h0,Se as h,Te as G0}from"./chunk-0n97186m.js";import{readdir as C$,readFile as s,rm as _0,stat as D1}from"node:fs/promises";import*as V from"node:path";import{nanoid as j}from"nanoid";import{createHash as p$,randomUUID as n$}from"node:crypto";import*as m from"node:fs/promises";import*as X0 from"node:path";var H$=1;function i$($,q){let T=p$("sha256").update(q).digest("hex");return X0.join(V0($),".locks",`${T}.lock`)}function O0($,q){return $ instanceof Error&&"code"in $&&$.code===q}async function A0($){try{let q=JSON.parse(await m.readFile($,"utf8"));if(q.version!==H$||typeof q.sessionId!=="string"||typeof q.ownerId!=="string"||!Number.isInteger(q.pid)||(q.pid??0)<=0||typeof q.acquiredAt!=="string")return;return q}catch{return}}async function J$($){let q=await A0($);if(q)return q;return await new Promise((T)=>setTimeout(T,10)),A0($)}function d$($){try{return process.kill($,0),!0}catch(q){return O0(q,"EPERM")}}async function Z$($,q){let T;try{return T=await m.open($,"wx",384),await T.writeFile(`${JSON.stringify(q)}
2
- `,"utf8"),!0}catch(G){if(O0(G,"EEXIST"))return!1;if(T)await m.unlink($).catch(()=>{return});throw G}finally{await T?.close().catch(()=>{return})}}class p 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 n{filePath;record;released=!1;constructor($,q){this.filePath=$;this.record=q}static async acquire($,q=Q$()){let T=i$(q,$),G={version:H$,sessionId:$,ownerId:n$(),pid:process.pid,acquiredAt:new Date().toISOString()};if(await m.mkdir(X0.dirname(T),{recursive:!0,mode:448}),await Z$(T,G))return new n(T,G);let Z=await J$(T);if(Z&&d$(Z.pid))throw new p(Z.pid);if(await m.unlink(T).catch((J)=>{if(!O0(J,"ENOENT"))throw J}),await Z$(T,G))return new n(T,G);throw new p((await J$(T))?.pid)}async release(){if(this.released)return;if(this.released=!0,(await A0(this.filePath))?.ownerId!==this.record.ownerId)return;await m.unlink(this.filePath).catch((q)=>{if(!O0(q,"ENOENT"))throw q})}}var E0={authentication:{message:"Provider authentication failed. Check model credentials.",retryable:!1},permission:{message:"Provider rejected this request. Check account and model permissions.",retryable:!1},rate_limit:{message:"Provider rate limit or quota exceeded.",retryable:!0},timeout:{message:"Provider request timed out.",retryable:!0},network:{message:"Provider connection failed.",retryable:!0},model_unavailable:{message:"The selected model is unavailable.",retryable:!0},context_limit:{message:"The request exceeded the model context limit.",retryable:!1},unsupported_input:{message:"The selected model does not support this input.",retryable:!1},runtime:{message:"Agent execution failed.",retryable:!0}};function r$($){try{if($ instanceof Error)return $.message;if($!==null&&typeof $==="object"&&"message"in $&&typeof $.message==="string")return $.message;return String($)}catch{return"Unknown error"}}function o$($){let q=$.toLowerCase();if(/\b(401|unauthorized|authentication|invalid (?:api[ _-]?)?key|api[ _-]?key|credential)\b/.test(q))return"authentication";if(/\b(403|forbidden|permission denied|not permitted)\b/.test(q))return"permission";if(/\b(429|rate limit|too many requests|quota)\b/.test(q))return"rate_limit";if(/\b(timeout|timed out|deadline exceeded|etimedout)\b/.test(q))return"timeout";if(/\b(econnreset|econnrefused|enotfound|network|socket|connection)\b/.test(q))return"network";if(/\b(model not found|model unavailable|unsupported model|no such model)\b/.test(q))return"model_unavailable";if(/\b(context (?:length|window)|maximum context|too many tokens|token limit)\b/.test(q))return"context_limit";if(/\b(image|vision|multimodal|unsupported input|does not support)\b/.test(q))return"unsupported_input";return"runtime"}function a$($){return{code:$,...E0[$]}}function L$($){return a$(o$(r$($)))}function w0($){if(!$||typeof $!=="object")return!1;let q=$;if(typeof q.code!=="string"||!(q.code in E0))return!1;let T=E0[q.code];return q.message===T.message&&q.retryable===T.retryable}import{promises as $0,realpathSync as s$}from"node:fs";import K0 from"node:path";import*as d from"fs/promises";import*as x from"path";var B$=[".git",".claude","node_modules",".env",".env.local",".env.production",".env.development",".env.test"];class i extends Error{code;constructor($,q){super($);this.code=q;this.name="PathSecurityError"}}class b0{static normalize($,q){let T=x.isAbsolute($)?$:x.resolve(q,$),G=x.normalize(T),Z=x.normalize(q);if(!this.isWithinWorkspace(G,Z))throw new i(`Path outside workspace: ${$} (resolved to ${G}, workspace: ${Z})`,"PATH_OUTSIDE_WORKSPACE");return G}static checkRestricted($){let q=$.split(x.sep);for(let T of B$)if(q.includes(T))throw new i(`Access denied: "${T}" is a protected directory`,"RESTRICTED_PATH")}static checkTraversal($){if($.includes(".."))throw new i(`Path traversal not allowed: ${$}`,"PATH_TRAVERSAL")}static async validatePath($,q){this.checkTraversal($);let T=this.normalize($,q);this.checkRestricted(T);try{await d.access(T)}catch(G){throw new i(`Path not found: ${$}`,"PATH_NOT_FOUND")}return T}static async resolveSymlink($,q){try{let T=await d.realpath($),G=await d.realpath(q);if(!this.isWithinWorkspace(T,G))throw new i(`Symlink points outside workspace: ${$} -> ${T}`,"SYMLINK_OUTSIDE_WORKSPACE");return T}catch(T){if(T instanceof i)throw T;return $}}static getRelativePath($,q){return x.relative(q,$)}static isWithinWorkspace($,q){let T=x.resolve($),G=x.resolve(q),Z=x.relative(G,T);return Z===""||Z!==".."&&!Z.startsWith(`..${x.sep}`)&&!x.isAbsolute(Z)}static async isWithinWorkspaceResolved($,q){let T=x.resolve(q),G=x.isAbsolute($)?x.resolve($):x.resolve(T,$);if(!this.isWithinWorkspace(G,T))return!1;let Z;try{Z=await d.realpath(T)}catch{return!1}let J=G;while(!0){try{let Q=await d.realpath(J);return this.isWithinWorkspace(Q,Z)}catch(Q){let L=Q.code;if(L!=="ENOENT"&&L!=="ENOTDIR")return!1}let H=x.dirname(J);if(H===J)return!1;J=H}}static isRestricted($){let q=$.split(x.sep);return B$.some((T)=>q.includes(T))}}var q0=Y0("Tool");class u{static instance=null;accessedFiles=new Map;pathAliases=new Map;constructor(){}static getInstance(){if(!u.instance)u.instance=new u;return u.instance}async recordFileRead($,q){try{let T=await $0.stat($),G={filePath:K0.resolve($),accessTime:Date.now(),mtime:T.mtimeMs,sessionId:q,lastOperation:"read"};this.setRecord(G),await this.recordAliases($,G.filePath),q0.debug(`记录文件读取: ${$}`)}catch(T){q0.warn(`记录文件读取失败: ${$}`,T)}}async recordFileEdit($,q,T="edit"){try{let G=await $0.stat($),Z={filePath:K0.resolve($),accessTime:Date.now(),mtime:G.mtimeMs,sessionId:q,lastOperation:T};this.setRecord(Z),await this.recordAliases($,Z.filePath),q0.debug(`记录文件${T==="edit"?"编辑":"写入"}: ${$}`)}catch(G){q0.warn(`记录文件${T==="edit"?"编辑":"写入"}失败: ${$}`,G)}}hasFileBeenRead($,q){let T=this.accessedFiles.get(this.resolveTrackedPath($));if(!T)return!1;return q?T.has(q):T.size>0}async checkFileModification($,q){let T=this.getFileRecord($,q);if(!T)return{modified:!1,message:"文件未被跟踪"};try{let G=await $0.stat($);if(Math.abs(G.mtimeMs-T.mtime)>1)return{modified:!0,message:`文件在访问后被修改(访问时间: ${new Date(T.accessTime).toISOString()}, 当前修改时间: ${G.mtime.toISOString()})`};return{modified:!1}}catch(G){let Z=G;if(Z.code==="ENOENT")return{modified:!0,message:"文件已被删除"};return{modified:!1,message:`无法检查文件状态: ${Z.message}`}}}async checkExternalModification($,q){let T=this.getFileRecord($,q);if(!T)return{isExternal:!1,message:"文件未被跟踪"};try{let G=await $0.stat($);if(G.mtimeMs-T.mtime>2000)return{isExternal:!0,message:`文件在 ${new Date(T.accessTime).toISOString()} (${T.lastOperation}) 之后被外部程序修改(当前修改时间: ${G.mtime.toISOString()})`};return{isExternal:!1}}catch(G){let Z=G;if(Z.code==="ENOENT")return{isExternal:!0,message:"文件已被删除"};return q0.warn(`检查文件外部修改失败: ${$}`,G),{isExternal:!1,message:`无法检查文件状态: ${Z.message}`}}}getFileRecord($,q){let T=this.accessedFiles.get(this.resolveTrackedPath($));if(!T)return;if(q)return T.get(q);return[...T.values()].sort((G,Z)=>Z.accessTime-G.accessTime)[0]}getTrackedRecords(){return[...this.accessedFiles.values()].flatMap(($)=>[...$.values()])}clearFileRecord($,q){let T=this.resolveTrackedPath($);if(!q){this.accessedFiles.delete(T),this.removeAliases(T);return}let G=this.accessedFiles.get(T);if(G?.delete(q),G?.size===0)this.accessedFiles.delete(T),this.removeAliases(T)}clearAll(){this.accessedFiles.clear(),this.pathAliases.clear()}clearSession($,q){for(let[T,G]of this.accessedFiles.entries()){if(q&&!b0.isWithinWorkspace(T,q))continue;if(G.delete($),G.size===0)this.accessedFiles.delete(T),this.removeAliases(T)}}getTrackedFiles(){return Array.from(this.accessedFiles.keys())}getTrackedFileCount(){return this.accessedFiles.size}static resetInstance(){u.instance=null}setRecord($){let q=this.accessedFiles.get($.filePath);if(!q)q=new Map,this.accessedFiles.set($.filePath,q);q.set($.sessionId,$)}async recordAliases($,q){this.pathAliases.set(K0.resolve($),q);let T=await $0.realpath($).catch(()=>{return});if(T)this.pathAliases.set(T,q)}resolveTrackedPath($){let q=K0.resolve($);if(this.accessedFiles.has(q))return q;let T=this.pathAliases.get(q);if(T)return T;try{let G=s$.native(q);return this.pathAliases.get(G)??G}catch{return q}}removeAliases($){for(let[q,T]of this.pathAliases)if(T===$)this.pathAliases.delete(q)}}import*as T0 from"node:crypto";import{promises as K}from"node:fs";import*as F from"node:path";import k0 from"write-file-atomic";var O$="missing";class U0{sessionId;workspaceRoot;enableCheckpoints;maxSnapshots;snapshotDir;manifestPath;trackedFileBackups=new Map;snapshots=[];constructor($){if(z($.sessionId),this.sessionId=$.sessionId,$.workspaceRoot&&!F.isAbsolute($.workspaceRoot))throw Error("Snapshot workspace root must be absolute");this.workspaceRoot=$.workspaceRoot?F.resolve($.workspaceRoot):void 0,this.enableCheckpoints=$.enableCheckpoints??!0,this.maxSnapshots=$.maxSnapshots??10;let q=G0();this.snapshotDir=F.join(q,"file-history",this.sessionId),this.manifestPath=F.join(this.snapshotDir,"manifest.json")}async initialize(){if(!this.enableCheckpoints)return;if(this.workspaceRoot)await this.selectWorkspaceSnapshotDir();await K.mkdir(this.snapshotDir,{recursive:!0,mode:493}),await this.loadManifest()}async selectWorkspaceSnapshotDir(){let $=G0(),q=await K.realpath(this.workspaceRoot).catch(()=>this.workspaceRoot),T=T0.createHash("sha256").update(q).digest("hex").slice(0,24),G=F.join($,"file-history",this.sessionId),Z=F.join($,"file-history","workspaces",T,this.sessionId),J=F.join(Z,"manifest.json");try{await K.access(J)}catch{await this.migrateLegacySnapshotDir(G,Z,q)}this.snapshotDir=Z,this.manifestPath=J}async migrateLegacySnapshotDir($,q,T){let G;try{G=JSON.parse(await K.readFile(F.join($,"manifest.json"),"utf8"))}catch{return}if(G.schemaVersion!==1||!Array.isArray(G.snapshots)||!G.snapshots.every((Z)=>this.isWithinWorkspace(Z.filePath,T)))return;await K.mkdir(F.dirname(q),{recursive:!0,mode:493});try{await K.rename($,q)}catch(Z){let J=Z.code;if(J!=="ENOENT"&&J!=="EEXIST"&&J!=="ENOTEMPTY")throw Z}}isWithinWorkspace($,q){if(!F.isAbsolute($))return!1;let T=F.relative(q,F.resolve($));return T===""||T!==".."&&!T.startsWith(`..${F.sep}`)&&!F.isAbsolute(T)}async createSnapshot($,q){if(!this.enableCheckpoints)return{backupFileName:"",version:0,backupTime:new Date};let T=await this.resolveFileIdentity($),G=!0;try{await K.access(T)}catch{G=!1}let Z=this.trackedFileBackups.get(T),J=Z?Z.version+1:1,H=this.generateFileHash(T,J),Q=this.getSnapshotPath(H,J),L=new Date;if(G){let B=await K.readFile(T);await K.writeFile(Q,B)}let O={backupFileName:H,version:J,backupTime:L};return this.trackedFileBackups.set(T,O),this.snapshots.push({messageId:q,backupFileName:H,timestamp:L,filePath:T,version:J,existedBefore:G}),await this.cleanupOldSnapshots(T),await this.persistManifest(),O}async recordPostEditState($,q){if(!this.enableCheckpoints||!q.backupFileName)return;let T=await this.resolveFileIdentity($),G=this.snapshots.find((Z)=>Z.filePath===T&&Z.backupFileName===q.backupFileName&&Z.version===q.version);if(!G)throw Error(`未找到待完成的快照: ${T}`);G.postEditHash=await this.hashFile(T),await this.persistManifest()}async discardSnapshot($,q){if(!this.enableCheckpoints||!q.backupFileName)return;let T=await this.resolveFileIdentity($),G=this.snapshots.find((Z)=>Z.filePath===T&&Z.backupFileName===q.backupFileName&&Z.version===q.version);if(!G)return;this.removeSnapshot(G),await K.rm(this.getSnapshotPath(G.backupFileName,G.version),{force:!0}),await this.persistManifest()}async rewindLatest($){let q=await this.resolveFileIdentity($),T=this.snapshots.slice().reverse().find((J)=>J.filePath===q&&J.postEditHash!==void 0);if(!T?.postEditHash)throw Error(`未找到可回退快照: ${q}`);if(await this.hashFile(q)!==T.postEditHash)throw Error(`文件在 Blade 编辑后已被修改,拒绝覆盖: ${q}`);let Z=this.getSnapshotPath(T.backupFileName,T.version);if(T.existedBefore){let J=await K.readFile(Z);await K.mkdir(F.dirname(q),{recursive:!0}),await K.writeFile(q,J)}else await K.rm(q,{force:!0});return this.removeSnapshot(T),await K.rm(Z,{force:!0}),await this.persistManifest(),T}async restoreSnapshot($,q){let T=await this.resolveFileIdentity($),G=this.snapshots.slice().reverse().find((J)=>J.messageId===q&&J.filePath===T);if(!G)throw Error(`未找到快照: messageId=${q}, filePath=${T}`);let Z=this.getSnapshotPath(G.backupFileName,G.version);if(G.existedBefore){let J=await K.readFile(Z);await K.mkdir(F.dirname(T),{recursive:!0}),await K.writeFile(T,J)}else await K.rm(T,{force:!0})}async listSnapshots($){let q=await this.resolveFileIdentity($);return this.snapshots.filter((T)=>T.filePath===q)}async listAllSnapshots(){return this.snapshots.filter(($)=>$.postEditHash!==void 0)}async previewRewind($){let q=this.buildRewindPlan($);return{files:q.map((T)=>T.filePath),snapshotCount:q.reduce((T,G)=>T+G.selected.length,0)}}async rewindSnapshots($){let q=this.buildRewindPlan($);if(q.length===0)return{files:[],snapshotCount:0};let T=new Map;for(let Z of q){let J,H=!0;try{J=await K.readFile(Z.filePath)}catch(L){if(L.code!=="ENOENT")throw L;H=!1}if((J?T0.createHash("sha256").update(J).digest("hex"):O$)!==Z.latest.postEditHash)throw Error(`文件在 Blade 编辑后已被修改,拒绝覆盖: ${Z.filePath}`);if(T.set(Z.filePath,{existed:H,content:J}),Z.target.existedBefore)await K.access(this.getSnapshotPath(Z.target.backupFileName,Z.target.version))}let G=[...this.snapshots];try{for(let J of q)if(J.target.existedBefore){let H=await K.readFile(this.getSnapshotPath(J.target.backupFileName,J.target.version));await K.mkdir(F.dirname(J.filePath),{recursive:!0}),await k0(J.filePath,H)}else await K.rm(J.filePath,{force:!0});let Z=new Set(q.flatMap((J)=>J.selected));this.snapshots=this.snapshots.filter((J)=>!Z.has(J)),this.rebuildTrackedFileBackups(),await this.persistManifest(),await Promise.all([...Z].map((J)=>K.rm(this.getSnapshotPath(J.backupFileName,J.version),{force:!0}).catch(()=>{return})))}catch(Z){this.snapshots=G,this.rebuildTrackedFileBackups();let J=[];for(let[H,Q]of T)try{if(Q.existed&&Q.content)await k0(H,Q.content);else await K.rm(H,{force:!0})}catch(L){J.push(L)}if(J.length>0)throw AggregateError([Z,...J],"快照回退失败且无法完整恢复回退前状态");throw Z}return{files:q.map((Z)=>Z.filePath),snapshotCount:q.reduce((Z,J)=>Z+J.selected.length,0)}}async commitSnapshots($){let q=this.buildRewindPlan($),T=new Set(q.flatMap((Z)=>Z.selected));if(T.size===0)return{files:[],snapshotCount:0};let G=[...this.snapshots];this.snapshots=this.snapshots.filter((Z)=>!T.has(Z)),this.rebuildTrackedFileBackups();try{await this.persistManifest()}catch(Z){throw this.snapshots=G,this.rebuildTrackedFileBackups(),Z}return await Promise.all([...T].map((Z)=>K.rm(this.getSnapshotPath(Z.backupFileName,Z.version),{force:!0}).catch(()=>{return}))),{files:q.map((Z)=>Z.filePath),snapshotCount:T.size}}buildRewindPlan($){let q=new Set($),T=this.snapshots.filter((J)=>J.postEditHash!==void 0),G=T.filter((J)=>q.has(J.messageId));return[...new Set(G.map((J)=>J.filePath))].sort().map((J)=>{let H=T.filter((B)=>B.filePath===J),Q=H.filter((B)=>q.has(B.messageId)),L=H.indexOf(Q[0]),O=H.slice(L);if(O.length!==Q.length||O.some((B)=>!q.has(B.messageId)))throw Error(`请求的快照不是文件历史的连续后缀: ${J}`);return{filePath:J,selected:Q,target:Q[0],latest:Q.at(-1)}})}async loadManifest(){try{let $=await K.readFile(this.manifestPath,"utf-8"),q=JSON.parse($);if(q.schemaVersion!==1||!Array.isArray(q.snapshots))throw Error("Unsupported snapshot manifest");this.snapshots=await Promise.all(q.snapshots.map(async(T)=>({...T,filePath:await this.resolveFileIdentity(T.filePath),timestamp:new Date(T.timestamp)}))),this.rebuildTrackedFileBackups()}catch($){if($.code!=="ENOENT")throw $;this.snapshots=[],this.trackedFileBackups.clear()}}async persistManifest(){if(this.snapshots.length===0){await K.rm(this.manifestPath,{force:!0});return}let $={schemaVersion:1,snapshots:this.snapshots.map((q)=>({...q,timestamp:q.timestamp.toISOString()}))};await k0(this.manifestPath,JSON.stringify($,null,2),{encoding:"utf-8",mode:384})}async cleanupOldSnapshots($){let T=this.snapshots.filter((G)=>G.filePath===$).slice(0,-this.maxSnapshots);for(let G of T)await K.rm(this.getSnapshotPath(G.backupFileName,G.version),{force:!0}),this.removeSnapshot(G)}async cleanup($=0){let q=this.snapshots.slice().sort((G,Z)=>Z.timestamp.getTime()-G.timestamp.getTime()),T=new Set(q.slice(0,$));for(let G of this.snapshots)if(!T.has(G))await K.rm(this.getSnapshotPath(G.backupFileName,G.version),{force:!0});this.snapshots=q.slice(0,$).reverse(),this.rebuildTrackedFileBackups(),await this.persistManifest()}getSnapshotPath($,q){return F.join(this.snapshotDir,`${$}@v${q}`)}async resolveFileIdentity($){let q=F.resolve($),T=[],G=q;while(!0){try{let J=await K.realpath(G);return F.join(J,...T.reverse())}catch(J){let H=J.code;if(H!=="ENOENT"&&H!=="ENOTDIR")throw J}let Z=F.dirname(G);if(Z===G)return q;T.push(F.basename(G)),G=Z}}async hashFile($){try{let q=await K.readFile($);return T0.createHash("sha256").update(q).digest("hex")}catch(q){if(q.code==="ENOENT")return O$;throw q}}removeSnapshot($){let q=this.snapshots.indexOf($);if(q>=0)this.snapshots.splice(q,1);this.rebuildTrackedFileBackups()}rebuildTrackedFileBackups(){this.trackedFileBackups.clear();for(let $ of this.snapshots){let q=this.trackedFileBackups.get($.filePath);if(!q||q.version<$.version)this.trackedFileBackups.set($.filePath,{backupFileName:$.backupFileName,version:$.version,backupTime:$.timestamp})}}generateFileHash($,q){let T=T0.createHash("md5");return T.update(`${$}:${q}`),T.digest("hex").substring(0,16)}getSnapshotDir(){return this.snapshotDir}getSessionId(){return this.sessionId}getTrackedFileCount(){return this.trackedFileBackups.size}getSnapshotCount(){return this.snapshots.length}}import{createHash as V1}from"node:crypto";import x$ from"node:path";import{StringDecoder as T1}from"node:string_decoder";function e$($,q){let T=q;while(T<$.length&&($[T]&192)===128)T+=1;return T}class g0{maxBytes;chunks=[];retainedBytes=0;omittedBytes=0;constructor($=1048576){this.maxBytes=$;if(!Number.isSafeInteger($)||$<=0)throw Error("maxBytes must be a positive safe integer")}append($){let q=Buffer.isBuffer($)?Buffer.from($):Buffer.from($);if(q.length===0)return;this.chunks.push(q),this.retainedBytes+=q.length,this.trimToLimit()}peek(){return{content:Buffer.concat(this.chunks,this.retainedBytes).toString("utf8"),omittedBytes:this.omittedBytes}}consume(){let $=this.peek();return this.chunks.length=0,this.retainedBytes=0,this.omittedBytes=0,$}trimToLimit(){while(this.retainedBytes>this.maxBytes){let $=this.chunks[0];if(!$)return;let q=this.retainedBytes-this.maxBytes;if($.length<=q){this.chunks.shift(),this.retainedBytes-=$.length,this.omittedBytes+=$.length;continue}let T=e$($,q);this.chunks[0]=$.subarray(T),this.retainedBytes-=T,this.omittedBytes+=T}}}var N0={maxLines:30,maxChars:3000,keepHead:10,keepTail:10,summarize:!0},r={maxLines:100,maxChars:1e4,keepHead:40,keepTail:40,summarize:!0},V$={maxLines:200,maxChars:20000,keepHead:80,keepTail:80,summarize:!1},$1={maxLines:150,maxChars:15000,keepHead:50,keepTail:50,summarize:!0},q1=[{pattern:/^git\s+(rm|add)\s+(-r|--cached|-rf|-f)?\s*/i,config:N0,summaryTemplate:($)=>`Successfully processed ${$} files`},{pattern:/^(npm|pnpm|yarn|bun)\s+(install|i|add|remove|uninstall)/i,config:N0,summaryTemplate:($)=>`Package operation completed (${$} lines of output)`},{pattern:/^(npm|pnpm|yarn|bun)\s+(run|exec)\s+(build|compile|bundle)/i,config:r,summaryTemplate:($)=>`Build completed (${$} lines of output)`},{pattern:/^(npm|pnpm|yarn|bun)\s+(run|exec)\s+(test|lint|check)/i,config:V$},{pattern:/^git\s+(status|branch|remote)/i,config:r},{pattern:/^git\s+(log|diff|show)/i,config:V$},{pattern:/^(ls|dir|tree)\s+/i,config:r,summaryTemplate:($)=>`Listed ${$} items`},{pattern:/^find\s+/i,config:r,summaryTemplate:($)=>`Found ${$} matches`},{pattern:/^(grep|rg|ag)\s+/i,config:r,summaryTemplate:($)=>`Found ${$} matching lines`},{pattern:/^(docker|podman)\s+(build|pull|push)/i,config:N0,summaryTemplate:($)=>`Docker operation completed (${$} lines)`},{pattern:/^(pip|pip3|poetry|pipenv)\s+(install|uninstall)/i,config:N0,summaryTemplate:($)=>`Python package operation completed (${$} lines)`},{pattern:/^(cargo|rustup)\s+(build|install|update)/i,config:r,summaryTemplate:($)=>`Rust operation completed (${$} lines)`},{pattern:/^(go)\s+(build|get|mod)/i,config:r,summaryTemplate:($)=>`Go operation completed (${$} lines)`}];class f0{static getConfigForCommand($){for(let{pattern:q,config:T,summaryTemplate:G}of q1)if(q.test($))return{config:T,summaryTemplate:G};return{config:$1}}static truncate($,q){let{config:T,summaryTemplate:G}=this.getConfigForCommand(q);return this.truncateWithConfig($,T,G)}static truncateWithConfig($,q,T){let G=$.length,Z=$.split(`
3
- `),J=Z.length;if(J<=q.maxLines&&G<=q.maxChars)return{content:$,truncated:!1,originalLines:J,originalChars:G};let H=Z.slice(0,q.keepHead),Q=Z.slice(-q.keepTail),L=J-q.keepHead-q.keepTail,O=H.join(`
4
- `);if(O+=`
5
-
6
- ... (${L} lines truncated, showing first ${q.keepHead} and last ${q.keepTail} of ${J} total) ...
7
-
8
- `,O+=Q.join(`
9
- `),O.length>q.maxChars){let X=Math.floor(q.maxChars/2)-50,Y=O.slice(0,X),U=O.slice(-X);O=`${Y}
10
-
11
- ... (content truncated to ${q.maxChars} chars) ...
12
-
13
- ${U}`}let B=q.summarize&&T?T(J,G):void 0;if(B)O+=`
14
-
15
- [Summary: ${B}]`;return{content:O,truncated:!0,originalLines:J,originalChars:G,summary:B}}static truncateForLLM($,q,T){let G=this.truncate($,T),Z=this.truncate(q,T),J;if(G.truncated||Z.truncated){let H=[];if(G.truncated)H.push(`stdout: ${G.originalLines} lines -> ${G.content.split(`
16
- `).length} lines`);if(Z.truncated)H.push(`stderr: ${Z.originalLines} lines -> ${Z.content.split(`
17
- `).length} lines`);J=`Output truncated: ${H.join(", ")}`}return{stdout:G.content,stderr:Z.content,truncationInfo:J}}static shouldTruncate($,q){let{config:T}=this.getConfigForCommand(q);return $.split(`
18
- `).length>T.maxLines||$.length>T.maxChars}static getStats($){return{lines:$.split(`
19
- `).length,chars:$.length,words:$.split(/\s+/).filter(Boolean).length}}}var X$=32768,G1=1048576,J1=65536,Z1=3600000,K$=4096,Q1=/[\u001B\u009B][[\]()#;?]*(?:(?:(?:[a-zA-Z\d]*(?:;[-a-zA-Z\d/#&.:=?%@~_]+)*)?\u0007)|(?:(?:\d{1,4}(?:[;:]\d{0,4})*)?[\dA-PR-TZcf-nq-uy=><~]))/g;class y0{stream;executionId;onEvent;output=new g0(G1/2);decoder=new T1("utf8");sniffChunks=[];sniffBytes=0;binary=!1;totalBytes=0;streamedBytes=0;streamTruncated=!1;pendingEvents=[];constructor($,q,T){this.stream=$;this.executionId=q;this.onEvent=T}append($){let q=Buffer.isBuffer($)?$:Buffer.from($);if(q.length===0)return;if(this.totalBytes+=q.length,this.sniffBytes<K$){let G=q.subarray(0,Math.min(q.length,K$-this.sniffBytes));this.sniffChunks.push(G),this.sniffBytes+=G.length,this.binary=this.binary||Buffer.concat(this.sniffChunks).includes(0)}if(this.binary)return;let T=Y$(this.decoder.write(q));this.output.append(T),this.emit(T)}finish(){if(this.binary)return;let $=Y$(this.decoder.end());this.output.append($),this.emit($)}snapshot(){let $=this.output.peek();if(this.binary)return{content:`[binary ${this.stream} omitted: ${this.totalBytes} bytes]`,omittedBytes:this.totalBytes,binary:!0};return{content:$.content,omittedBytes:$.omittedBytes,binary:!1}}async flushEvents(){await Promise.all(this.pendingEvents),this.pendingEvents.length=0}emit($){if(!$||!this.onEvent||this.streamTruncated)return;let q=J1-this.streamedBytes;if(q<=0){this.streamTruncated=!0;return}let T=H1($,q);if(this.streamedBytes+=Buffer.byteLength(T),T.length<$.length)this.streamTruncated=!0;this.pendingEvents.push(Promise.resolve(this.onEvent({type:"output",executionId:this.executionId,stream:this.stream,chunk:T,streamedBytes:this.streamedBytes,streamTruncated:this.streamTruncated})).then(()=>{return}))}}function Y$($){return $.replace(Q1,"")}function H1($,q){let T=Buffer.from($);if(T.length<=q)return $;let G=q;while(G>0&&(T[G]&192)===128)G-=1;return T.subarray(0,G).toString("utf8")}function U$($){return $.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;").replaceAll("'","&apos;")}function L1($){let q=$.trim();if(!q)throw Error("User shell command cannot be empty");if(q.length>X$)throw Error(`User shell command exceeds ${X$} characters`);if(q.includes("\x00"))throw Error("User shell command contains a null byte");return q}function B1(){return{execute($,q){return new Promise((T)=>{let G=process.platform==="win32"?process.env.COMSPEC||"cmd.exe":process.env.SHELL||"/bin/bash",Z=process.platform==="win32"?["/d","/s","/c",$]:["-l","-c",$],{child:J,processTree:H}=N$(G,Z,{cwd:q.cwd,env:q.env,stdio:["ignore","pipe","pipe"]}),Q="",L="",O=!1,B=!1,X=!1,Y,U=()=>{return Y??=H.terminate(),Y},R=setTimeout(()=>{O=!0,U()},q.timeoutMs),M=()=>{B=!0,U()};if(q.signal.addEventListener("abort",M,{once:!0}),q.signal.aborted)M();J.stdout?.on("data",(_)=>{q.onOutput?.("stdout",_)}),J.stderr?.on("data",(_)=>{q.onOutput?.("stderr",_)});let E=async(_)=>{if(X)return;if(X=!0,clearTimeout(R),q.signal.removeEventListener("abort",M),O||B)await U();T({..._,stdout:"",stderr:"",timedOut:O,aborted:B})};J.once("error",(_)=>{E({exitCode:null,error:_.message})}),J.once("close",(_)=>{E({exitCode:_})})})}}}async function V4($,q){let T=L1($),G=q.timeoutMs??Z1,Z=new y0("stdout",q.executionId,q.onEvent),J=new y0("stderr",q.executionId,q.onEvent),H=Date.now();await q.onEvent?.({type:"started",executionId:q.executionId,command:T});let Q,L=!1,O=!1;try{Q=await(q.executor??B1()).execute(T,{cwd:q.cwd,env:q.env,timeoutMs:G,signal:q.signal,onOutput:(M,E)=>{if(M==="stdout")L=!0;else O=!0;(M==="stdout"?Z:J).append(E)}})}catch(M){Q={exitCode:null,stdout:"",stderr:"",error:M instanceof Error?M.message:String(M)}}if(!L)Z.append(Q.stdout);if(!O)J.append(Q.stderr);Z.finish(),J.finish(),await Promise.all([Z.flushEvents(),J.flushEvents()]);let B=Z.snapshot(),X=J.snapshot(),Y=f0.truncateForLLM(B.content.trim(),X.content.trim(),T),U=Q.aborted||q.signal.aborted?"aborted":Q.timedOut?"timed_out":Q.error?"spawn_error":Q.exitCode===0?"completed":"failed",R={version:1,command:T,status:U,exitCode:Q.exitCode,durationMs:Math.max(0,Date.now()-H),stdout:Y.stdout,stderr:Q.error?[Y.stderr,Q.error].filter(Boolean).join(`
20
- `):Y.stderr,stdoutOmittedBytes:B.omittedBytes,stderrOmittedBytes:X.omittedBytes,binaryOutput:B.binary||X.binary,truncated:Boolean(Y.truncationInfo)||B.omittedBytes>0||X.omittedBytes>0};return await q.onEvent?.({type:"completed",executionId:q.executionId,record:R}),R}function X4($){let q=[$.stdout?`stdout:
21
- ${$.stdout}`:"",$.stderr?`stderr:
22
- ${$.stderr}`:""].filter(Boolean).join(`
23
- `);return["<user_shell_command>",`<command>${U$($.command)}</command>`,"<result>",`Status: ${$.status}`,`Exit code: ${$.exitCode??"null"}`,`Duration: ${($.durationMs/1000).toFixed(3)} seconds`,`Output:
24
- ${U$(q||"(no output)")}`,"</result>","</user_shell_command>"].join(`
25
- `)}function F$($){let q=[$.stdout,$.stderr?`stderr:
26
- ${$.stderr}`:""].filter(Boolean).join(`
27
- `);return[`! ${$.command}`,q||"(no output)"].join(`
28
- `)}function O1($){if(!$||typeof $!=="object"||Array.isArray($))return;let q=$;if(q.version!==1||typeof q.command!=="string"||!["completed","failed","aborted","timed_out","spawn_error"].includes(String(q.status))||q.exitCode!==null&&typeof q.exitCode!=="number"||typeof q.durationMs!=="number"||typeof q.stdout!=="string"||typeof q.stderr!=="string"||typeof q.stdoutOmittedBytes!=="number"||typeof q.stderrOmittedBytes!=="number"||typeof q.binaryOutput!=="boolean"||typeof q.truncated!=="boolean")return;return q}function F0($){if(!$||typeof $!=="object"||Array.isArray($))return;return O1($.userShellCommand)}var W0=16777216,W$=65536,W4=1048576,X1=8,x0=200,K1=/(?:^|[_-])(?:api[_-]?key|authorization|bearer|cookie|credential|password|passwd|private[_-]?key|refresh[_-]?token|secret|session[_-]?token|token)(?:$|[_-])/i,Y1=/(?<![:/A-Za-z0-9._-])\/[^\s"'`<>]+/g,U1=/(?<![A-Za-z0-9._-])[A-Za-z]:[\\/][^\s"'`<>]+/g,N1=new RegExp("\\u001b(?:\\[[0-?]*[ -/]*[@-~]|\\][^\\u0007]*(?:\\u0007|\\u001b\\\\))","g"),F1=/-----BEGIN [^-]*PRIVATE KEY-----[\s\S]*?-----END [^-]*PRIVATE KEY-----/g;function f($,q){return $.count+=1,q}function W1($){return K1.test($.replace(/[A-Z]/g,(q)=>`_${q.toLowerCase()}`))}function x1($){return[...$].filter((q)=>{if(q===`
29
- `||q==="\r"||q==="\t")return!0;let T=q.codePointAt(0)??0;if(T<32||T===127)return!1;if(T>=57344&&T<=63743)return!1;if(T>=983040&&T<=1048573)return!1;if(T>=1048576&&T<=1114109)return!1;if(T>=917504&&T<=917631)return!1;return!/[\p{Cf}\p{Cn}]/u.test(q)}).join("")}function k($,q){let T=$.normalize("NFKC"),G=T.replace(N1,"");if(G!==T)q.count+=1;T=G,T=T.replace(F1,()=>f(q,"[redacted-private-key]")),T=T.replace(/\bBearer\s+[^\s"'`]+/gi,()=>f(q,"Bearer [redacted]")).replace(/\bsk-[A-Za-z0-9_-]{8,}\b/g,()=>f(q,"[redacted-key]")).replace(/\bAKIA[0-9A-Z]{16}\b/g,()=>f(q,"[redacted-aws-key]")).replace(/\b(api[_-]?key|access[_-]?token|authorization|cookie|password|passwd|refresh[_-]?token|secret|session[_-]?token)\b(\s*[:=]\s*)([^\s,;]+)/gi,(J,H,Q)=>`${H}${Q}${f(q,"[redacted]")}`);let Z=x1(T);if(Z!==T)q.count+=1;return Z.replace(/\r\n?/g,`
30
- `)}function _$($,q,T){if(/^data:[^;,]+;base64,/i.test($))return f(T,"[binary omitted]");let G=k($,T),Z=x$.resolve(q);for(let J of[Z,Z.startsWith("/private/")?Z.slice(8):`/private${Z}`])G=G.replaceAll(J,".");return G=G.replace(Y1,(J)=>J.startsWith("./")?J:f(T,"[host-path]")),G=G.replace(U1,()=>f(T,"[host-path]")),G=G.replace(/\bhttps?:\/\/[^\s"'`]+/gi,(J)=>{try{let H=new URL(J);if(H.username||H.password||H.search||H.hash)T.count+=1;return H.username="",H.password="",H.search="",H.hash="",H.toString()}catch{return f(T,"[redacted-url]")}}),G}function m0($,q,T,G=0,Z){if(Z&&W1(Z))return f(T,"[redacted]");if(G>=X1)return f(T,"[depth limit]");if(typeof $==="string")return _$($,q,T);if($===null||typeof $==="boolean"||typeof $==="number"&&Number.isFinite($))return $;if(Array.isArray($)){let J=$.slice(0,x0).map((H)=>m0(H,q,T,G+1));if($.length>J.length)J.push(f(T,`[${$.length-J.length} items omitted]`));return J}if($&&typeof $==="object"){let J={},H=Object.entries($);for(let[Q,L]of H.slice(0,x0))J[k(Q,T)]=m0(L,q,T,G+1,Q);if(H.length>x0)J["[entries omitted]"]=H.length-x0;return J}return String($)}function _1($,q){let T=Buffer.from($,"utf8");if(T.length<=q)return $;let G=T.subarray(0,q).toString("utf8");while(Buffer.byteLength(G,"utf8")>q)G=G.slice(0,-1);return G}function z1($,q,T){let G=JSON.stringify(m0($,q,T),null,2);if(Buffer.byteLength(G,"utf8")<=W$)return G;T.count+=1;let Z=`
31
- ... [activity truncated]`;return _1(G,W$-Buffer.byteLength(Z))+Z}function v0($,q=""){let T=Math.max(2,...[...$.matchAll(/`+/g)].map((Z)=>Z[0].length)),G="`".repeat(T+1);return`${G}${q}
32
- ${$}
33
- ${G}`}function j0($){return $.replace(/\s+/g," ").trim()}function C1($){let q=new Map,T=new Map,G=new Map,Z=0;for(let J of o($)){if(J.type==="message_created"){let B=T.get(J.data.messageId);if(B)B.role=J.data.role,B.metadata=J.data.metadata,q.set(J.data.messageId,B),T.delete(J.data.messageId);else if(!q.has(J.data.messageId))q.set(J.data.messageId,{order:Z++,role:J.data.role,parts:[],metadata:J.data.metadata});continue}if(J.type!=="part_created"&&J.type!=="part_updated")continue;let H=q.get(J.data.messageId)??T.get(J.data.messageId);if(!H)H={order:Z++,role:"activity",parts:[]},T.set(J.data.messageId,H);let Q=`${J.data.messageId}\x00${J.data.partType}\x00${J.data.partId}`,L=G.get(Q);if(L){L.event=J;continue}let O={order:Z++,event:J};G.set(Q,O),H.parts.push(O)}return[...q.values(),...T.values()].sort((J,H)=>J.order-H.order)}function S0($,q,T,G){return`## Activity: ${$}
34
-
35
- ${v0(z1(q,T.projectPath,G),"json")}`}function z$($,q,T={}){let G={count:0},Z=T.includeReasoning===!0,J=[],H=0,Q=0,L=0;for(let E of C1($)){let _=F0(E.metadata);if(_){let C=k(_.command,G),D=k([_.stdout,_.stderr?`stderr:
36
- ${_.stderr}`:""].filter(Boolean).join(`
37
- `)||"(no output)",G);J.push(`## User shell command
38
-
39
- ${v0(`$ ${C}
40
- ${D}`,"console")}`),H+=1;continue}let a=[],A=[],g=[],P=Number.POSITIVE_INFINITY;for(let C of E.parts.sort((D,w)=>D.order-w.order)){let{partType:D,payload:w}=C.event.data;if(D==="text"){let N=w.text;if(typeof N==="string"&&N.trim())a.push(k(N,G)),P=Math.min(P,C.order)}else if(D==="image"){let N=w.mimeType;A.push(typeof N==="string"?`[Image: ${k(N,G)}]`:"[Image]"),P=Math.min(P,C.order)}else if(D==="reasoning"&&Z){let N=w.text;if(typeof N==="string"&&N.trim())g.push({order:C.order,markdown:`## Reasoning
41
-
42
- ${k(N,G).trim()}`}),L+=1}else if(D==="tool_call"){let N=w,c=typeof N.toolName==="string"?k(N.toolName,G):"unknown";g.push({order:C.order,markdown:S0(`${c} call`,N.input??{},q,G)}),Q+=1}else if(D==="tool_result"){let N=w,c=typeof N.toolName==="string"?k(N.toolName,G):"unknown";g.push({order:C.order,markdown:S0(`${c} result`,typeof N.error==="string"?{error:N.error}:{output:N.output??null},q,G)}),Q+=1}else if(D==="summary"){let N=w.text;if(typeof N==="string"&&N.trim())g.push({order:C.order,markdown:`## Summary
43
-
44
- ${k(N,G).trim()}`})}else if(D==="subtask_ref")g.push({order:C.order,markdown:S0("Subagent",w,q,G)}),Q+=1;else if(D==="diff"||D==="patch"){let N=typeof w==="string"?w:JSON.stringify(w,null,2);g.push({order:C.order,markdown:`## File changes
45
-
46
- ${v0(_$(N,q.projectPath,G),"diff")}`}),Q+=1}}if((E.role==="user"||E.role==="assistant")&&(a.length>0||A.length>0))g.push({order:P,markdown:`## ${E.role==="user"?"User":"Assistant"}
47
-
48
- ${[...a,...A].join(`
49
-
50
- `).trim()}`}),H+=1;J.push(...g.sort((C,D)=>C.order-D.order).map((C)=>C.markdown))}if(J.length===0)throw Error("No conversation content to export");let O=`${J.join(`
51
-
52
- `)}
53
- `,B=Buffer.byteLength(O,"utf8");if(B>W0)throw Error(`Session export exceeds ${W0} bytes`);let X=V1("sha256").update(O).digest("hex"),Y=x$.basename(q.taskSourceProjectPath??q.projectPath),U=q.selectedModelId??q.taskModelId,M=["# Blade conversation","",`- Session: \`${q.sessionId}\``,...q.title?[`- Title: ${j0(k(q.title,G))}`]:[],`- Project: \`${j0(k(Y,G))}\``,...U?[`- Model: \`${j0(k(U,G))}\``]:[],...q.permissionMode?[`- Permission mode: ${q.permissionMode}`]:[],`- Created: ${q.firstMessageTime}`,`- Updated: ${q.lastMessageTime}`,`- State: ${q.archivedAt?"archived":"active"}`,`- Reasoning: ${Z?"included":"omitted"}`,...q.reasoningEffort?[`- Reasoning effort: ${q.reasoningEffort}`]:[],...q.serviceTier?[`- Service tier: ${q.serviceTier}`]:[],...q.responseVerbosity?[`- Response verbosity: ${q.responseVerbosity}`]:[],...q.communicationStyle?[`- Communication style: ${q.communicationStyle}`]:[],...q.communicationStyleDigest?[`- Communication style SHA-256: \`${q.communicationStyleDigest}\``]:[],...q.projectInstructionsDigest?[`- Project instructions SHA-256: \`${q.projectInstructionsDigest}\``]:[],`- Content SHA-256: \`${X}\``,`- Content bytes: ${B}`,`- Redactions: ${G.count}`,"","---",""].join(`
54
- `)+`
55
- `+O;if(Buffer.byteLength(M,"utf8")>W0)throw Error(`Session export exceeds ${W0} bytes`);return{filename:`blade-session-${q.sessionId.slice(0,12)}.md`,markdown:M,contentSha256:X,contentBytes:B,messageCount:H,activityCount:Q,reasoningIncluded:Z,reasoningCount:L,redactionCount:G.count}}var I0=Y0("Service"),D$=new Set(["queued","running","completed","failed","cancelled","interrupted"]),r0=new Set(["local","worktree"]),M1=new Set(["default","autoEdit","yolo","plan"]),R1=new Set(["applied","discarded","conflicted"]);class o0 extends Error{}function M$($){try{return process.kill($,0),!0}catch(q){return q instanceof Error&&"code"in q&&q.code==="EPERM"}}function R$($){if(!$||typeof $!=="object"||Array.isArray($))return;let q=$;if(["sessionId","name","branch","baseCommit","originalBranch","repositoryRoot","originalWorkspaceRoot","worktreeRoot","workspaceRoot"].some((G)=>typeof q[G]!=="string"||!q[G])||typeof q.sourceHadChanges!=="boolean"||q.sourceStateFingerprint!==void 0&&(typeof q.sourceStateFingerprint!=="string"||!/^[a-f0-9]{64}$/.test(q.sourceStateFingerprint)))return;return q}function A$($){if(!$||typeof $!=="object"||Array.isArray($))return;let q=$;if(!R1.has(String(q.status))||typeof q.updatedAt!=="string"||!Number.isFinite(Date.parse(q.updatedAt))||q.sourceCommit!==void 0&&(typeof q.sourceCommit!=="string"||!/^[a-f0-9]{40,64}$/.test(q.sourceCommit))||q.changedFiles!==void 0&&(typeof q.changedFiles!=="number"||!Number.isInteger(q.changedFiles)||q.changedFiles<0)||q.message!==void 0&&(typeof q.message!=="string"||!q.message.trim()||q.message.length>500))return;return{status:q.status,updatedAt:q.updatedAt,...typeof q.sourceCommit==="string"?{sourceCommit:q.sourceCommit}:{},...typeof q.changedFiles==="number"?{changedFiles:q.changedFiles}:{},...typeof q.message==="string"?{message:q.message}:{}}}function E$($){if(!$||typeof $!=="object"||Array.isArray($))return;let q=$;if(["changedFiles","additions","deletions","commits"].some((G)=>typeof q[G]!=="number"||!Number.isInteger(q[G])||q[G]<0))return;return q}function w$($){if(!$||typeof $!=="object"||Array.isArray($))return;let q=$;if(q.version!==1||typeof q.prompt!=="string"||!q.prompt.trim()||q.prompt.length>32000||typeof q.sourceProjectPath!=="string"||!V.isAbsolute(q.sourceProjectPath)||!r0.has(q.isolation)||!C0(q.permissionMode)||q.title!==void 0&&(typeof q.title!=="string"||!q.title.trim()||q.title.length>200)||q.modelId!==void 0&&(typeof q.modelId!=="string"||!q.modelId.trim()||q.modelId.length>500)||q.reasoningEffort!==void 0&&!H0(q.reasoningEffort)||q.serviceTier!==void 0&&!Q0(q.serviceTier)||q.responseVerbosity!==void 0&&!Z0(q.responseVerbosity)||q.communicationStyle!==void 0&&!L0(q.communicationStyle)||q.communicationStyleDigest!==void 0&&(typeof q.communicationStyleDigest!=="string"||!/^[a-f0-9]{64}$/.test(q.communicationStyleDigest))||q.projectInstructionsDigest!==void 0&&(typeof q.projectInstructionsDigest!=="string"||!/^[a-f0-9]{64}$/.test(q.projectInstructionsDigest)))return;let T;if(q.attachments!==void 0){if(!Array.isArray(q.attachments)||q.attachments.length>f$)return;let G=0;for(let Z of q.attachments){if(!Z||typeof Z!=="object"||Array.isArray(Z))return;let J=Z;if(!["file","image","url"].includes(String(J.type)))return;for(let H of["path","url","content","mimeType","name"])if(J[H]!==void 0&&typeof J[H]!=="string")return;G+=typeof J.content==="string"?Buffer.byteLength(J.content):0}if(G>y$)return;T=q.attachments.map((Z)=>{let J=Z;return{type:J.type,...J.path!==void 0?{path:J.path}:{},...J.url!==void 0?{url:J.url}:{},...J.content!==void 0?{content:J.content}:{},...J.mimeType!==void 0?{mimeType:J.mimeType}:{},...J.name!==void 0?{name:J.name}:{}}})}return{version:1,prompt:q.prompt,...typeof q.title==="string"?{title:q.title}:{},sourceProjectPath:V.resolve(q.sourceProjectPath),isolation:q.isolation,permissionMode:q.permissionMode,...typeof q.modelId==="string"?{modelId:q.modelId}:{},...H0(q.reasoningEffort)?{reasoningEffort:q.reasoningEffort}:{},...Q0(q.serviceTier)?{serviceTier:q.serviceTier}:{},...Z0(q.responseVerbosity)?{responseVerbosity:q.responseVerbosity}:{},...L0(q.communicationStyle)?{communicationStyle:q.communicationStyle}:{},...typeof q.communicationStyleDigest==="string"?{communicationStyleDigest:q.communicationStyleDigest}:{},...typeof q.projectInstructionsDigest==="string"?{projectInstructionsDigest:q.projectInstructionsDigest}:{},...T?{attachments:T}:{}}}function C0($){return typeof $==="string"&&M1.has($)}function b$($){if(!$||typeof $!=="object"||Array.isArray($))return;let q=$;if(typeof q.sessionId!=="string"||!q.sessionId||typeof q.projectPath!=="string"||!V.isAbsolute(q.projectPath))return;return{sessionId:q.sessionId,projectPath:V.resolve(q.projectPath)}}var I$={stat($){return D1($,{bigint:!0})},readFile($){return s($,"utf-8")}},J0=I$;function u4($){J0=$}function h4(){J0=I$}class P$ extends Error{constructor($){super(`Session has no durable creation record: ${$}`);this.name="SessionMissingCreationError"}}class e extends Error{sessionId;archivedBySessionId;code="BLADE_SESSION_ARCHIVED";constructor($,q){super($===q?`Session is archived: ${$}`:`Session is archived by ancestor ${q}: ${$}`);this.sessionId=$;this.archivedBySessionId=q;this.name="SessionArchivedError"}}class I extends Error{code="BLADE_SESSION_ARCHIVE_CONFLICT";constructor($){super($);this.name="SessionArchiveConflictError"}}function P0($,q){return`${$}\x00${q}`}function u$($){return typeof $==="string"&&$.length<=64&&Number.isFinite(Date.parse($))}function A1($){let q=new Map($.map((T)=>[P0(T.projectPath,T.sessionId),T]));return $.map((T)=>{let G=T,Z=new Set;while(G){let L=P0(G.projectPath,G.sessionId);if(Z.has(L))break;if(Z.add(L),u$(G.archivedAt))return{...T,archivedAt:G.archivedAt,archivedBySessionId:G.sessionId};G=G.parentId?q.get(P0(G.projectPath,G.parentId)):void 0}let{archivedAt:J,archivedBySessionId:H,...Q}=T;return Q})}function u0($,q){let T=A1($);if(q===null)return T;return T.filter((G)=>Boolean(G.archivedAt)===q)}class W{static toUISafeMessages($){let q=Date.now(),T=$.length,G=[];return $.forEach((Z,J)=>{if(Z.role!=="user"&&Z.role!=="assistant")return;let H;if(typeof Z.content==="string")H=Z.content;else if(Array.isArray(Z.content))H=Z.content.map((X)=>X.type==="text"?X.text:"[Image]").join("");else H="";let Q=H.trim();if(!Q)return;let L=F0(Z.metadata),O=L?F$(L):Q,B=G[G.length-1];if(B&&B.role===Z.role&&B.content===O)return;G.push({id:`restored-${q}-${J}`,role:Z.role,content:O,timestamp:q-(T-J)*1000,metadata:Z.metadata&&typeof Z.metadata==="object"?Z.metadata:void 0})}),G}static async listSessionPage($={}){let q=c0($),T=await this.listSessionPageFromProjection(q);if(T)return T;let Z=(await this.scanStoredSessions(q.cwd??void 0,q.includeSubagents,q.cursor?5000:0,q.archived)).sort(p0),J=n0(Z,q);return{sessions:J.sessions.map((H)=>this.toPublicMetadata(H)),nextCursor:J.nextCursor}}static async listSessionPageFromProjection($){let q=S$($);try{let T=await z0();if(!T)return null;await d0(T,this.projectionDeriver(),$.cursor?5000:0);let G=[],Z=[];if($.cwd)G.push("s.project_path = ?"),Z.push($.cwd);if(!$.includeSubagents)G.push("s.is_subagent = 0");if(G.push($.archived?"a.session_id IS NOT NULL":"a.session_id IS NULL"),q){G.push(`(
56
- s.last_message_time < ?
57
- OR (
58
- s.last_message_time = ?
59
- AND (
60
- s.project_sort_key > ?
61
- OR (s.project_sort_key = ? AND s.session_sort_key > ?)
62
- )
63
- )
64
- )`);let L=l0(q.projectPath);Z.push(q.lastMessageTime,q.lastMessageTime,L,L,l0(q.sessionId))}let H=T.prepare(`WITH RECURSIVE archive_members(
65
- project_path, session_id, archive_root_id, effective_archived_at, depth
66
- ) AS (
67
- SELECT project_path, session_id, session_id, archived_at, 0
68
- FROM sessions
69
- WHERE archived_at IS NOT NULL
70
- UNION ALL
71
- SELECT child.project_path, child.session_id, parent.archive_root_id,
72
- parent.effective_archived_at, parent.depth + 1
73
- FROM sessions child
74
- JOIN archive_members parent
75
- ON child.project_path = parent.project_path
76
- AND child.parent_id = parent.session_id
77
- WHERE parent.depth < 128
78
- ),
79
- ranked_archive AS (
80
- SELECT project_path, session_id, archive_root_id,
81
- effective_archived_at,
82
- ROW_NUMBER() OVER (
83
- PARTITION BY project_path, session_id
84
- ORDER BY depth ASC, archive_root_id ASC
85
- ) AS rank
86
- FROM archive_members
87
- )
88
- SELECT s.metadata_json, a.archive_root_id, a.effective_archived_at
89
- FROM sessions s
90
- LEFT JOIN ranked_archive a
91
- ON a.project_path = s.project_path
92
- AND a.session_id = s.session_id
93
- AND a.rank = 1
94
- ${G.length>0?`WHERE ${G.join(" AND ")}`:""}
95
- ORDER BY s.last_message_time DESC,
96
- s.project_sort_key ASC,
97
- s.session_sort_key ASC
98
- LIMIT ?`).all(...Z,$.limit+1).map((L)=>{let O=JSON.parse(L.metadata_json);if(L.archive_root_id&&L.effective_archived_at)return{...O,archivedAt:L.effective_archived_at,archivedBySessionId:L.archive_root_id};let{archivedAt:B,archivedBySessionId:X,...Y}=O;return Y}),Q=n0(H,$);return{sessions:Q.sessions.map((L)=>this.toPublicMetadata(L)),nextCursor:Q.nextCursor}}catch{return null}}static async listSessions($={}){let q=c0($),T=await this.scanStoredSessions(q.cwd??void 0,q.includeSubagents,0,q.archived),G=new Set;return T.sort(p0).flatMap((Z)=>{let J=`${Z.projectPath}\x00${Z.sessionId}`;if(G.has(J))return[];return G.add(J),[this.toPublicMetadata(Z)]})}static async findSessionMetadata($,q){if(z($),q!==void 0){if(!V.isAbsolute(q))throw Error("Session catalog cwd must be absolute");let G=V.resolve(q),Z=this.getSessionFilePath(G,$);try{let J=await this.readStoredSessionMetadata(Z,$,G);if(J.projectPath!==G)return;if(!J.parentId||J.archivedAt)return this.toPublicMetadata(u0([J],null)[0]??J);let H=await this.scanStoredSessions(G,!0,0,null);return this.toPublicMetadata(H.find((Q)=>Q.sessionId===$)??J)}catch(J){if(J.code==="ENOENT")return;throw J}}let T=(await this.scanStoredSessions(void 0,!0,0,null)).filter((G)=>G.sessionId===$);if(T.length===0)return;if(T.length>1)throw Error(`Ambiguous session ID: ${$}`);return this.toPublicMetadata(T[0])}static async loadSession($,q){try{if(q){if(!V.isAbsolute(q))throw Error("Session catalog cwd must be absolute");let G=V.resolve(q),Z=this.getSessionFilePath(G,$);try{return await this.loadSessionFromFile(Z,$,G)}catch(J){if(J.code==="ENOENT")throw Error(`未找到会话: ${$}`);throw J}}let T=(await this.scanStoredSessions(void 0,!0,0,null)).find((G)=>G.sessionId===$);if(!T)throw Error(`未找到会话: ${$}`);return await this.loadSessionFromFile(T.filePath,$)}catch(T){throw I0.error(`[SessionService] 加载会话失败 (${$}):`,T),T}}static async exportSessionMarkdown($,q,T={}){z($);let G=this.resolveCatalogWorkspace(q),Z=S(G,$),J;try{J=await this.readStableSessionSnapshot(Z,$)}catch(L){throw this.sanitizeStoredSessionError(L,$)}let H=this.projectMetadataFromEntries(J,$,G,Z);if(H.projectPath!==G)throw Error(`Session export workspace mismatch: ${$}`);let Q=H.archivedAt;if(!Q&&H.parentId)Q=(await this.findArchivedAncestor(H.parentId,G))?.archivedAt;return z$(J,{...H,archivedAt:Q},T)}static async listRewindCheckpoints($,q){z($);let T=this.resolveCatalogWorkspace(q),G=S(T,$),Z=await this.readStableSessionSnapshot(G,$);this.validateSessionWorkspace(Z,$,T);let J=new U0({sessionId:$,workspaceRoot:T});await J.initialize();let H=m$(Z),Q=[];for(let L of H){let O=i0(Z,L.messageId),B=await J.previewRewind(O.snapshotMessageIds);Q.push({...L,fileCount:B.files.length})}return Q}static async rewindSession($,q,T){z($);let G=this.resolveCatalogWorkspace(q);await this.assertSessionWritable($,G);let Z=S(G,$),J=new v(Z),H;try{await J.appendValidatedAsync(async(Q)=>{this.validateSessionWorkspace(Q,$,G);let L=i0(Q,T.targetMessageId),O=new U0({sessionId:$,workspaceRoot:G});await O.initialize();let B=await O.previewRewind(L.snapshotMessageIds),X=T.mode==="conversation"?await O.commitSnapshots(L.snapshotMessageIds):await O.rewindSnapshots(L.snapshotMessageIds),Y=new Date().toISOString(),U={id:j(),sessionId:$,timestamp:Y,type:"session_rewound",cwd:G,gitBranch:h(G),version:l(),data:{rewindId:j(),targetMessageId:T.targetMessageId,mode:T.mode,restoredFiles:T.mode==="conversation"?[]:X.files,createdAt:Y}},R=o([...Q,U]);return H={checkpoint:{...L.checkpoint,fileCount:B.files.length},mode:T.mode,removedTurns:L.removedTurns,restoredFiles:U.data.restoredFiles,messages:this.convertJSONLToMessages(R)},U})}catch(Q){throw this.sanitizeStoredSessionError(Q,$)}if(!H)throw Error(`Session rewind did not produce a result: ${$}`);for(let Q of H.restoredFiles)u.getInstance().clearFileRecord(Q);return H}static async forkSession($,q){z($);let T=q.newSessionId??`fork-${Date.now()}-${j(8)}`;z(T);let G=this.resolveForkWorkspace(q.sourceProjectPath),Z=this.resolveForkWorkspace(q.targetProjectPath);if(G!==Z)throw Error("Session forks must stay in the source workspace");let J=S(G,$),H=await this.readStableSessionSnapshot(J,$),Q=this.getSessionCreatedEntry(H,$);if(Q.data.sessionId!==$)throw Error("Fork source session_created.data.sessionId must match the requested session ID");if(!V.isAbsolute(Q.cwd)||V.resolve(Q.cwd)!==G)throw Error("Fork source session_created.cwd must resolve to the requested source workspace");let L=this.projectMetadataFromEntries(H,$,G,J);if(L.archivedAt)throw new e($,$);if(L.parentId){let b=await this.findArchivedAncestor(L.parentId,G);if(b)throw new e($,b.sessionId)}let O=o(H),B=new Date().toISOString(),X=Q.data.rootId||$,Y=h(Z),U=l(),{status:R,taskStatus:M,taskStatusReason:E,taskFailure:_,taskStartedAt:a,taskCompletedAt:A,taskOwnerPid:g,taskPromptSummary:P,taskDispatch:C,taskModelId:D,taskRetriedFrom:w,taskDelivery:N,taskIsolation:c,taskSourceProjectPath:a0,taskWorktree:t0,taskDiffStat:s0,taskQueuePosition:e0,taskQueueDepth:$$,taskConcurrencyLimit:q$,...D0}=Q.data,M0={id:j(),sessionId:T,timestamp:B,type:"session_created",cwd:Z,gitBranch:Y,version:U,data:{...D0,sessionId:T,rootId:X,parentId:$,relationType:"fork",taskStatus:"completed",taskCompletedAt:B,taskIsolation:"local",taskSourceProjectPath:Z,createdAt:B,updatedAt:B}},B0=O.filter((b)=>b.type!=="session_created"&&b.type!=="inbox_acknowledged").map((b)=>{let R0={...b,id:j(),sessionId:T,cwd:Z,gitBranch:Y,version:U};if(b.type==="session_updated"){let{status:l$,taskStatus:G$,taskStatusReason:E1,taskFailure:w1,taskStartedAt:b1,taskCompletedAt:k1,taskOwnerPid:g1,taskPromptSummary:f1,taskDispatch:y1,taskModelId:j1,taskRetriedFrom:S1,taskDelivery:m1,taskIsolation:v1,taskSourceProjectPath:I1,taskWorktree:P1,taskDiffStat:u1,taskQueuePosition:h1,taskQueueDepth:l1,taskConcurrencyLimit:c1,...c$}=b.data;return{...R0,type:"session_updated",data:{...c$,sessionId:T,rootId:X,parentId:$,relationType:"fork"}}}if(b.type==="message_created"){let{inboxMessageId:l$,...G$}=b.data;return{...R0,type:"message_created",data:G$}}return R0}),y={id:j(),sessionId:T,timestamp:B,type:"session_updated",cwd:Z,gitBranch:Y,version:U,data:{sessionId:T,rootId:X,parentId:$,relationType:"fork",taskStatus:"completed",taskStatusReason:null,taskFailure:null,taskStartedAt:null,taskCompletedAt:B,taskOwnerPid:null,taskIsolation:"local",taskSourceProjectPath:Z,taskWorktree:null,taskDiffStat:null,taskDelivery:null,taskQueuePosition:null,taskQueueDepth:null,taskConcurrencyLimit:null,updatedAt:B}},t=[M0,...B0,y],T$=S(Z,T);try{await new v(T$).createExclusive(t)}catch(b){if(b.code==="EEXIST")throw Error(`Fork session already exists: ${T}`,{cause:b});throw b}let h$=this.projectMetadataFromEntries(t,T,Z,T$);return{sessionId:T,parentSessionId:$,projectPath:Z,messages:this.convertJSONLToMessages(t),metadata:this.toPublicMetadata(h$)}}static async deleteSession($,q){if(z($),q){if(!V.isAbsolute(q))throw Error("Session catalog cwd must be absolute");let G=V.resolve(q),Z=this.getSessionFilePath(G,$),J=new v(Z),H;try{H=await J.deleteValidated((Q)=>{return this.projectMetadataFromEntries(Q,$,G,Z).projectPath===G})}catch(Q){if(!this.isCorruptSessionJSONLError(Q))throw Q;H=await J.delete()}if(!H)return 0;return await _0(V.join(V.dirname(Z),`${$}.inbox.json`),{force:!0}),await _0(h0(G,$),{force:!0}),await this.removeFromProjection($,G),1}let T=(await this.scanStoredSessions(void 0,!0)).filter((G)=>G.sessionId===$);if(T.length===0)return 0;return await Promise.all(T.map(async(G)=>{await new v(G.filePath).delete(),await _0(V.join(V.dirname(G.filePath),`${G.sessionId}.inbox.json`),{force:!0}),await _0(h0(G.projectPath,G.sessionId),{force:!0}),await this.removeFromProjection(G.sessionId,G.projectPath)})),T.length}static async removeFromProjection($,q){try{let T=await z0();if(T)v$(T,$,q)}catch{}}static validateTaskMetadataUpdate($,q){if($.taskPromptSummary!==void 0&&$.taskPromptSummary!==null&&(!$.taskPromptSummary.trim()||$.taskPromptSummary.length>1000))throw Error("Session task prompt summary must contain 1-1000 characters");if($.taskFailure!==void 0&&$.taskFailure!==null&&!w0($.taskFailure))throw Error("Invalid session task failure");if($.taskDispatch!==void 0&&$.taskDispatch!==null&&!w$($.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&&!C0($.permissionMode))throw Error("Invalid session permission mode");if($.reasoningEffort!==void 0&&$.reasoningEffort!==null&&!H0($.reasoningEffort))throw Error("Invalid session reasoning effort");if($.serviceTier!==void 0&&$.serviceTier!==null&&!Q0($.serviceTier))throw Error("Invalid session service tier");if($.responseVerbosity!==void 0&&$.responseVerbosity!==null&&!Z0($.responseVerbosity))throw Error("Invalid session response verbosity");if($.communicationStyle!==void 0&&$.communicationStyle!==null&&!L0($.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&&!b$($.taskRetriedFrom))throw Error("Invalid session task retry source");if($.taskDelivery!==void 0&&$.taskDelivery!==null&&!A$($.taskDelivery))throw Error("Invalid session task delivery");if($.taskIsolation!==void 0&&$.taskIsolation!==null&&!r0.has($.taskIsolation))throw Error(`Invalid session task isolation: ${String($.taskIsolation)}`);if($.taskSourceProjectPath!==void 0&&$.taskSourceProjectPath!==null&&!V.isAbsolute($.taskSourceProjectPath))throw Error("Session task source project path must be absolute");if($.taskWorktree!==void 0&&$.taskWorktree!==null){let T=R$($.taskWorktree);if(!T||T.sessionId!==q||![T.repositoryRoot,T.originalWorkspaceRoot,T.worktreeRoot,T.workspaceRoot].every((G)=>V.isAbsolute(G)))throw Error("Invalid session task worktree metadata")}if($.taskDiffStat!==void 0&&$.taskDiffStat!==null&&!E$($.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($,q,T={}){z($),W.validateTaskMetadataUpdate(T,$);let G=W.resolveCatalogWorkspace(q);if(T.taskWorktree&&V.resolve(T.taskWorktree.workspaceRoot)!==G)throw Error("Session task worktree must match the catalog workspace");let Z=new Date().toISOString(),J={id:j(),sessionId:$,timestamp:Z,type:"session_created",cwd:G,gitBranch:h(G),version:l(),data:{sessionId:$,rootId:$,...T.title!==void 0?{title:T.title}:{},taskStatus:T.taskStatus??"queued",...T.taskPromptSummary!==void 0?{taskPromptSummary:T.taskPromptSummary}:{},...T.taskDispatch!==void 0?{taskDispatch:T.taskDispatch}:{},...T.taskModelId!==void 0?{taskModelId:T.taskModelId}:{},...T.taskRetriedFrom!==void 0?{taskRetriedFrom:T.taskRetriedFrom}:{},...T.taskIsolation!==void 0?{taskIsolation:T.taskIsolation}:{},...T.taskSourceProjectPath!==void 0?{taskSourceProjectPath:T.taskSourceProjectPath}:{},...T.taskWorktree!==void 0?{taskWorktree:T.taskWorktree}:{},...T.selectedModelId!==void 0?{selectedModelId:T.selectedModelId}:{},...T.permissionMode!==void 0?{permissionMode:T.permissionMode}:{},...T.reasoningEffort!==void 0?{reasoningEffort:T.reasoningEffort}:{},...T.serviceTier!==void 0?{serviceTier:T.serviceTier}:{},...T.responseVerbosity!==void 0?{responseVerbosity:T.responseVerbosity}:{},...T.communicationStyle!==void 0?{communicationStyle:T.communicationStyle}:{},...T.communicationStyleDigest!==void 0?{communicationStyleDigest:T.communicationStyleDigest}:{},...T.projectInstructionsDigest!==void 0?{projectInstructionsDigest:T.projectInstructionsDigest}:{},createdAt:Z,updatedAt:Z}},H=W.getSessionFilePath(G,$);return await new v(H).createExclusive([J]),W.toPublicMetadata(W.projectMetadataFromEntries([J],$,G,H))}static async assertSessionWritable($,q){let T=await this.findSessionMetadata($,q);if(!T)throw Error(`Session not found: ${$}`);if(T.archivedAt)throw new e($,T.archivedBySessionId??$);return T}static async findArchivedAncestor($,q){let T=new Set,G=$;while(G){if(T.has(G))throw Error("Session lineage contains a cycle");T.add(G),z(G);let Z=S(q,G),J;try{J=await s(Z,"utf8")}catch(Q){if(Q.code==="ENOENT")return;throw Q}let H=this.projectMetadataFromEntries(this.parseStoredSession(J,G),G,q,Z);if(H.projectPath!==q)throw Error("Session lineage escapes the requested workspace");if(H.archivedAt)return{sessionId:H.sessionId,archivedAt:H.archivedAt};G=H.parentId}return}static async listSessionArchiveMembers($,q){z($);let T=this.resolveCatalogWorkspace(q),G=await this.scanStoredSessions(T,!0,0,null);if(!G.some((H)=>H.sessionId===$))throw Error(`Session not found: ${$}`);let Z=new Set([$]),J=!0;while(J){J=!1;for(let H of G)if(H.parentId&&Z.has(H.parentId)&&!Z.has(H.sessionId))Z.add(H.sessionId),J=!0}return G.filter((H)=>Z.has(H.sessionId)).sort((H,Q)=>H.sessionId.localeCompare(Q.sessionId)).map((H)=>this.toPublicMetadata(H))}static async archiveSession($,q){z($);let T=this.resolveCatalogWorkspace(q),G=await this.findSessionMetadata($,T);if(!G)throw Error(`Session not found: ${$}`);if(G.archivedAt)return G;let Z=await this.listSessionArchiveMembers($,T),J=Z.find((Q)=>Q.taskStatus==="queued"||Q.taskStatus==="running");if(J)throw new I(`Stop session ${J.sessionId} before archiving this session tree`);let H=[];try{for(let B of Z)H.push(await n.acquire(B.sessionId,T));let Q=S(T,$),L=new v(Q),O=[];return await L.appendValidated((B)=>{let X=this.projectMetadataFromEntries(B,$,T,Q);if(X.archivedAt)throw new I(`Session archive state changed concurrently: ${$}`);if(X.taskStatus==="queued"||X.taskStatus==="running")throw new I(`Stop session ${$} before archiving it`);let Y=new Date().toISOString(),U={id:j(),sessionId:$,timestamp:Y,type:"session_updated",cwd:T,gitBranch:h(T),version:l(),data:{sessionId:$,archivedAt:Y,updatedAt:Y}};return O=[...B,U],U}),this.toPublicMetadata({...this.projectMetadataFromEntries(O,$,T,Q),archivedBySessionId:$})}catch(Q){if(Q instanceof I)throw Q;if(Q instanceof p)throw new I(Q.message);throw this.sanitizeStoredSessionError(Q,$)}finally{for(let Q of H.reverse())await Q.release()}}static async unarchiveSession($,q){z($);let T=this.resolveCatalogWorkspace(q),G=await this.findSessionMetadata($,T);if(!G)throw Error(`Session not found: ${$}`);if(!G.archivedAt)return G;if(G.archivedBySessionId&&G.archivedBySessionId!==$)throw new I(`Unarchive ancestor ${G.archivedBySessionId} to restore session ${$}`);let Z;try{Z=await n.acquire($,T);let J=S(T,$),H=new v(J),Q=[];return await H.appendValidated((L)=>{if(!this.projectMetadataFromEntries(L,$,T,J).archivedAt)throw new I(`Session archive state changed concurrently: ${$}`);let B=new Date().toISOString(),X={id:j(),sessionId:$,timestamp:B,type:"session_updated",cwd:T,gitBranch:h(T),version:l(),data:{sessionId:$,archivedAt:null,updatedAt:B}};return Q=[...L,X],X}),this.toPublicMetadata(this.projectMetadataFromEntries(Q,$,T,J))}catch(J){if(J instanceof I)throw J;if(J instanceof p)throw new I(J.message);throw this.sanitizeStoredSessionError(J,$)}finally{await Z?.release()}}static async updateSessionMetadata($,q,T){if(z($),W.validateTaskMetadataUpdate(T,$),T.taskStatus!==void 0&&!D$.has(T.taskStatus))throw Error(`Invalid session task status: ${String(T.taskStatus)}`);if(T.taskOwnerPid!==void 0&&T.taskOwnerPid!==null&&(!Number.isInteger(T.taskOwnerPid)||T.taskOwnerPid<=0))throw Error("Session task owner PID must be a positive integer");let G=W.resolveCatalogWorkspace(q);if(T.taskWorktree&&V.resolve(T.taskWorktree.workspaceRoot)!==G)throw Error("Session task worktree must match the catalog workspace");let Z=W.getSessionFilePath(G,$),J=new v(Z),H=[];try{await J.appendValidatedAsync(async(Q)=>{let L=W.getSessionCreatedEntry(Q,$);if(L.data.sessionId!==$)throw Error(`Session metadata creation record sessionId mismatch: ${$}`);if(!V.isAbsolute(L.cwd)||V.resolve(L.cwd)!==G)throw Error(`Session metadata creation record cwd mismatch: ${$}`);let O=W.projectMetadataFromEntries(Q,$,G,Z);if(O.archivedAt)throw new e($,$);if(O.parentId){let Y=await W.findArchivedAncestor(O.parentId,G);if(Y)throw new e($,Y.sessionId)}let B=new Date().toISOString(),X={id:j(),sessionId:$,timestamp:B,type:"session_updated",cwd:G,gitBranch:h(G),version:l(),data:{sessionId:$,...T.title!==void 0?{title:T.title}:{},...T.taskStatus!==void 0?{taskStatus:T.taskStatus}:{},...T.taskStatusReason!==void 0?{taskStatusReason:T.taskStatusReason}:{},...T.taskFailure!==void 0?{taskFailure:T.taskFailure}:{},...T.taskStartedAt!==void 0?{taskStartedAt:T.taskStartedAt}:{},...T.taskCompletedAt!==void 0?{taskCompletedAt:T.taskCompletedAt}:{},...T.taskOwnerPid!==void 0?{taskOwnerPid:T.taskOwnerPid}:{},...T.taskPromptSummary!==void 0?{taskPromptSummary:T.taskPromptSummary}:{},...T.taskDispatch!==void 0?{taskDispatch:T.taskDispatch}:{},...T.taskModelId!==void 0?{taskModelId:T.taskModelId}:{},...T.taskRetriedFrom!==void 0?{taskRetriedFrom:T.taskRetriedFrom}:{},...T.taskDelivery!==void 0?{taskDelivery:T.taskDelivery}:{},...T.taskIsolation!==void 0?{taskIsolation:T.taskIsolation}:{},...T.taskSourceProjectPath!==void 0?{taskSourceProjectPath:T.taskSourceProjectPath}:{},...T.taskWorktree!==void 0?{taskWorktree:T.taskWorktree}:{},...T.taskDiffStat!==void 0?{taskDiffStat:T.taskDiffStat}:{},...T.taskQueuePosition!==void 0?{taskQueuePosition:T.taskQueuePosition}:{},...T.taskQueueDepth!==void 0?{taskQueueDepth:T.taskQueueDepth}:{},...T.taskConcurrencyLimit!==void 0?{taskConcurrencyLimit:T.taskConcurrencyLimit}:{},...T.selectedModelId!==void 0?{selectedModelId:T.selectedModelId}:{},...T.permissionMode!==void 0?{permissionMode:T.permissionMode}:{},...T.reasoningEffort!==void 0?{reasoningEffort:T.reasoningEffort}:{},...T.serviceTier!==void 0?{serviceTier:T.serviceTier}:{},...T.responseVerbosity!==void 0?{responseVerbosity:T.responseVerbosity}:{},...T.communicationStyle!==void 0?{communicationStyle:T.communicationStyle}:{},...T.communicationStyleDigest!==void 0?{communicationStyleDigest:T.communicationStyleDigest}:{},...T.projectInstructionsDigest!==void 0?{projectInstructionsDigest:T.projectInstructionsDigest}:{},updatedAt:B}};return H=[...Q,X],X})}catch(Q){throw W.sanitizeStoredSessionError(Q,$)}return W.toPublicMetadata(W.projectMetadataFromEntries(H,$,G,Z))}static async setSessionPermissionMode($,q,T){if(z($),!C0(T))throw Error("Invalid session permission mode");let G=W.resolveCatalogWorkspace(q),Z=await W.findSessionMetadata($,G);if(Z?.permissionMode===T)return Z;if(Z)return W.updateSessionMetadata($,G,{permissionMode:T});try{return await W.createSessionMetadata($,G,{taskStatus:"completed",permissionMode:T})}catch(J){if(J.code!=="EEXIST")throw J;return W.updateSessionMetadata($,G,{permissionMode:T})}}static async findSessionTaskWorktree($,q){z($);let T=W.resolveCatalogWorkspace(q),G=W.getSessionFilePath(T,$);try{return(await W.readStoredSessionMetadata(G,$,T)).taskWorktree}catch(Z){if(Z.code==="ENOENT")return;throw W.sanitizeStoredSessionError(Z,$)}}static async findSessionTaskDispatch($,q){z($);let T=W.resolveCatalogWorkspace(q),G=W.getSessionFilePath(T,$);try{return(await W.readStoredSessionMetadata(G,$,T)).taskDispatch}catch(Z){if(Z.code==="ENOENT")return;throw W.sanitizeStoredSessionError(Z,$)}}static async loadSessionFromFile($,q,T){let G=await s($,"utf-8"),Z=this.parseStoredSession(G,q);if(T!==void 0){if(this.projectMetadataFromEntries(Z,q,T,$).projectPath!==T)throw Error(`未找到会话: ${q}`)}return this.convertJSONLToMessages(Z)}static convertJSONLToMessages($){let q=[],T=new Map,G=new Map,Z=new Map,J=new Map,H=new Map;for(let Q of o($)){if(Q.type==="message_created"){let L=Q.data.role==="assistant"&&Q.data.parentMessageId?Z.get(Q.data.parentMessageId):void 0,O=L??{role:Q.data.role,content:"",...Q.data.metadata||Q.data.inboxMessageId?{metadata:{...Q.data.metadata&&typeof Q.data.metadata==="object"&&!Array.isArray(Q.data.metadata)?Q.data.metadata:{},...Q.data.inboxMessageId?{inboxMessageId:Q.data.inboxMessageId}:{}}}:{}};if(T.set(Q.data.messageId,O),G.set(Q.data.messageId,[]),!L)q.push(O)}if(Q.type==="part_created"){if(Q.data.partType==="reasoning"){let L=T.get(Q.data.messageId);if(L){let O=Q.data.payload;L.reasoningContent=(L.reasoningContent??"")+(O.text??"")}}if(Q.data.partType==="text"){let L=T.get(Q.data.messageId);if(L){let O=Q.data.payload,B=G.get(Q.data.messageId);if(B)B.push({type:"text",text:O.text??""}),L.content=k$(B);else L.content=O.text??""}}if(Q.data.partType==="image"){let L=T.get(Q.data.messageId);if(L){let O=Q.data.payload,B=G.get(Q.data.messageId);if(B&&O.dataUrl)B.push({type:"image_url",image_url:{url:O.dataUrl}}),L.content=k$(B)}}if(Q.data.partType==="tool_call"){let L=T.get(Q.data.messageId);if(L?.role!=="assistant"){if(L=Z.get(Q.data.messageId),!L)L={role:"assistant",content:"",tool_calls:[]},Z.set(Q.data.messageId,L),q.push(L)}if(L.role==="assistant"){let O=Q.data.payload,B=O.toolCallId??Q.data.partId;J.set(Q.data.partId,B),H.set(B,L),L.tool_calls??=[],L.tool_calls.push({id:B,type:"function",function:{name:O.toolName??"unknown",arguments:JSON.stringify(O.input??{})}})}}if(Q.data.partType==="tool_result"){let L=Q.data.payload,O=typeof L.error==="string"?`Error: ${L.error}`:typeof L.output==="string"?L.output:JSON.stringify(L.output??""),B=L;q.push({role:"tool",content:O,tool_call_id:J.get(Q.data.messageId)??L.toolCallId,name:L.toolName,metadata:B})}if(Q.data.partType==="summary"){let L=Q.data.payload,O=Q.data.payload;q.push({role:"system",content:L.text??"",metadata:O})}if(Q.data.partType==="subtask_ref"){let L=T.get(Q.data.messageId)??H.get(Q.data.messageId);if(L){let O=Q.data.payload,B=L.metadata??{};L.metadata={...B,subtaskRef:O}}}}}return q}static projectionDeriver(){return($,q,T)=>{try{let G=S(T,q);return this.projectMetadataFromEntries($,q,T,G)}catch{return null}}}static projectionDeriverForSearch(){return this.projectionDeriver()}static async scanStoredSessionsFromProjection($,q,T=0,G=!1){try{let Z=await z0();if(!Z)return null;await d0(Z,this.projectionDeriver(),T);let J=$?Z.prepare("SELECT metadata_json, is_subagent FROM sessions WHERE project_path=?").all($):Z.prepare("SELECT metadata_json, is_subagent FROM sessions").all(),H=[];for(let Q of J){if(!q&&Q.is_subagent===1)continue;try{let L=JSON.parse(Q.metadata_json);if($!==void 0&&L.projectPath!==$)continue;H.push(L)}catch{}}return u0(H,G)}catch{return null}}static async scanStoredSessions($,q=!1,T=0,G=!1){let Z=$?V.resolve($):void 0,J=await this.scanStoredSessionsFromProjection(Z,q,T,G);if(J)return J;let H=Z?[{storagePath:V0(Z),projectPath:Z}]:await this.listAllProjectStorageDirectories(),Q=[];for(let L of H){let O;try{O=await C$(L.storagePath)}catch(B){if(B.code==="ENOENT")continue;throw B}for(let B of O){if(!B.endsWith(".jsonl"))continue;let X=B.slice(0,-6),Y=V.join(L.storagePath,B);try{let U=await this.readStoredSessionMetadata(Y,X,L.projectPath);if(Z!==void 0&&U.projectPath!==Z){I0.warn(`[SessionService] Skipping out-of-scope session transcript: ${X}`);continue}if(!q&&U.relationType==="subagent")continue;Q.push(U)}catch(U){let R=U.code;if(R==="ENOENT")continue;if(R)throw U;I0.warn(`[SessionService] Skipping invalid session transcript: ${X}`)}}}return u0(Q,G)}static async listAllProjectStorageDirectories(){let $=V.join(G0(),"projects"),q;try{q=await C$($,{withFileTypes:!0,encoding:"utf8"})}catch(T){if(T.code==="ENOENT")return[];throw T}return q.filter((T)=>T.isDirectory()).map((T)=>({storagePath:V.join($,T.name),projectPath:g$(T.name)}))}static async readStoredSessionMetadata($,q,T){let G=await s($,"utf-8"),Z=this.parseStoredSession(G,q);return this.reconcileInterruptedTask(this.projectMetadataFromEntries(Z,q,T,$))}static async reconcileInterruptedTask($){let q=$.taskOwnerPid;if($.taskStatus!=="running"||q===void 0||M$(q))return $;let T;try{T=await n.acquire($.sessionId,$.projectPath)}catch(J){if(!(J instanceof p))throw J;let H=await s($.filePath,"utf-8");return this.projectMetadataFromEntries(this.parseStoredSession(H,$.sessionId),$.sessionId,$.projectPath,$.filePath)}let G=new v($.filePath),Z;try{try{await G.appendValidated((J)=>{let H=this.projectMetadataFromEntries(J,$.sessionId,$.projectPath,$.filePath);if(H.taskStatus!=="running"||H.taskOwnerPid!==q||M$(q))throw new o0;let Q=new Date().toISOString(),L={id:j(),sessionId:$.sessionId,timestamp:Q,type:"session_updated",cwd:$.projectPath,gitBranch:h($.projectPath),version:l(),data:{sessionId:$.sessionId,taskStatus:"interrupted",taskStatusReason:"Task owner process exited before completion",taskCompletedAt:Q,taskOwnerPid:null,taskQueuePosition:null,taskQueueDepth:null,updatedAt:Q}};return Z=[...J,L],L})}catch(J){if(!(J instanceof o0))throw J}if(!Z){let J=await s($.filePath,"utf-8");Z=this.parseStoredSession(J,$.sessionId)}return this.projectMetadataFromEntries(Z,$.sessionId,$.projectPath,$.filePath)}finally{await T.release()}}static projectMetadataFromEntries($,q,T,G){if($.length===0)throw Error(`Empty session transcript: ${q}`);let Z=this.getSessionCreatedEntry($,q),J=$.reduce((y,t)=>t.type==="session_updated"?{...y,...t.data}:y,{...Z.data}),H=o($),Q=H.filter((y)=>y.type==="message_created"&&["user","assistant"].includes(y.data.role)).length,L=H.some((y)=>y.type==="part_created"&&y.data.partType==="tool_result"&&typeof y.data.payload.error==="string"),B=(D$.has(J.taskStatus)?J.taskStatus:void 0)??(L?"failed":"completed"),X=typeof J.taskOwnerPid==="number"&&Number.isInteger(J.taskOwnerPid)&&J.taskOwnerPid>0?J.taskOwnerPid:void 0,Y=r0.has(J.taskIsolation)?J.taskIsolation:void 0,U=typeof J.taskSourceProjectPath==="string"&&V.isAbsolute(J.taskSourceProjectPath)?V.resolve(J.taskSourceProjectPath):void 0,R=Z.cwd;if(R!==void 0&&!V.isAbsolute(R))throw Error(`Session catalog cwd must be absolute: ${q}`);let M=R===void 0?T:V.resolve(R),E=R$(J.taskWorktree),_=E?.sessionId===q&&V.resolve(E.workspaceRoot)===M?E:void 0,a=E$(J.taskDiffStat),A=w$(J.taskDispatch),g=typeof J.taskModelId==="string"&&J.taskModelId.trim()?J.taskModelId:A?.modelId,P=typeof J.selectedModelId==="string"&&J.selectedModelId.trim()?J.selectedModelId:g,C=C0(J.permissionMode)?J.permissionMode:A?.permissionMode,D=H0(J.reasoningEffort)?J.reasoningEffort:A?.reasoningEffort,w=Q0(J.serviceTier)?J.serviceTier:A?.serviceTier,N=Z0(J.responseVerbosity)?J.responseVerbosity:A?.responseVerbosity,c=L0(J.communicationStyle)?J.communicationStyle:A?.communicationStyle,a0=Object.hasOwn(J,"communicationStyleDigest")?typeof J.communicationStyleDigest==="string"&&/^[a-f0-9]{64}$/.test(J.communicationStyleDigest)?J.communicationStyleDigest:void 0:c===A?.communicationStyle?A?.communicationStyleDigest:void 0,t0=Object.hasOwn(J,"projectInstructionsDigest")?typeof J.projectInstructionsDigest==="string"&&/^[a-f0-9]{64}$/.test(J.projectInstructionsDigest)?J.projectInstructionsDigest:void 0:A?.projectInstructionsDigest,s0=u$(J.archivedAt)?J.archivedAt:void 0,e0=b$(J.taskRetriedFrom),$$=A$(J.taskDelivery),q$=typeof J.taskQueuePosition==="number"&&Number.isInteger(J.taskQueuePosition)&&J.taskQueuePosition>0?J.taskQueuePosition:void 0,D0=typeof J.taskQueueDepth==="number"&&Number.isInteger(J.taskQueueDepth)&&J.taskQueueDepth>=0?J.taskQueueDepth:void 0,M0=typeof J.taskConcurrencyLimit==="number"&&Number.isInteger(J.taskConcurrencyLimit)&&J.taskConcurrencyLimit>0?J.taskConcurrencyLimit:void 0,B0=w0(J.taskFailure)?J.taskFailure:B==="failed"&&typeof J.taskStatusReason==="string"?L$(J.taskStatusReason):void 0;return{sessionId:q,projectPath:M,gitBranch:Z.gitBranch,rootId:J.rootId||q,parentId:J.parentId,relationType:J.relationType,resumedFrom:J.resumedFrom,rootAgentId:J.rootAgentId,resumeDepth:J.resumeDepth,title:J.title,agentType:J.agentType,model:J.model,selectedModelId:P,permissionMode:C,reasoningEffort:D,serviceTier:w,responseVerbosity:N,communicationStyle:c,communicationStyleDigest:a0,projectInstructionsDigest:t0,taskStatus:B,taskStatusReason:B0?.message??(typeof J.taskStatusReason==="string"?J.taskStatusReason:void 0),taskFailure:B0,taskStartedAt:typeof J.taskStartedAt==="string"?J.taskStartedAt:void 0,taskCompletedAt:typeof J.taskCompletedAt==="string"?J.taskCompletedAt:void 0,taskPromptSummary:typeof J.taskPromptSummary==="string"?J.taskPromptSummary:void 0,taskModelId:g,taskRetryAvailable:A!==void 0,taskRetriedFrom:e0,taskDelivery:$$,taskIsolation:Y,taskSourceProjectPath:U,taskWorktreePath:_?.worktreeRoot,taskWorktreeBranch:_?.branch,taskBaseCommit:_?.baseCommit,taskDiffStat:a,taskQueuePosition:q$,taskQueueDepth:D0,taskConcurrencyLimit:M0,archivedAt:s0,taskOwnerPid:X,taskWorktree:_,taskDispatch:A,messageCount:Q,firstMessageTime:$[0].timestamp,lastMessageTime:$.at(-1).timestamp,hasErrors:L||B==="failed",filePath:G}}static toPublicMetadata($){let{filePath:q,taskOwnerPid:T,taskWorktree:G,taskDispatch:Z,...J}=$;return J}static getSessionFilePath($,q){return S($,q)}static getSessionCreatedEntry($,q){let T=$.find((G)=>G.type==="session_created");if(!T)throw new P$(q);return T}static resolveCatalogWorkspace($){if(!V.isAbsolute($))throw Error("Session catalog cwd must be absolute");return V.resolve($)}static validateSessionWorkspace($,q,T){let G=this.getSessionCreatedEntry($,q);if(G.data.sessionId!==q)throw Error(`Session creation record sessionId mismatch: ${q}`);if(!V.isAbsolute(G.cwd)||V.resolve(G.cwd)!==T)throw Error(`Session creation record cwd mismatch: ${q}`)}static resolveForkWorkspace($){if(!V.isAbsolute($))throw Error("Fork workspace paths must be absolute");return V.resolve($)}static parseStoredSession($,q){return j$($,`session ${q}`)}static isCorruptSessionJSONLError($){return $ instanceof Error&&$.message.startsWith("Invalid session JSONL ")}static sanitizeStoredSessionError($,q){if(!this.isCorruptSessionJSONLError($)||!($ instanceof Error))return $;let T=$.message.match(/ at line (\d+)$/)?.[1];return Error(`Invalid session JSONL in session ${q}${T?` at line ${T}`:""}`,{cause:$.cause})}static async readStableSessionSnapshot($,q,T=3){for(let G=0;G<T;G+=1){let Z=await J0.stat($),J=await J0.readFile($),H=this.parseStoredSession(J,q),Q=await J0.stat($);if(Z.size===Q.size&&Z.mtimeNs===Q.mtimeNs&&Z.dev===Q.dev&&Z.ino===Q.ino)return H}throw Error("Session changed while creating fork; retry the operation")}}function k$($){if($.length===1&&$[0]?.type==="text")return $[0].text;return[...$]}
99
- export{b0 as _a,p as $a,n as ab,L$ as bb,u as cb,U0 as db,g0 as eb,f0 as fb,V4 as gb,X4 as hb,F$ as ib,F0 as jb,W4 as kb,u4 as lb,h4 as mb,P$ as nb,e as ob,I as pb,W as qb};
@@ -1 +0,0 @@
1
- import{h as a,i as b,j as c,k as d,l as e}from"./chunk-ydtcvxsm.js";import"./chunk-9ffr01c3.js";export{b as setSkipUntilVersion,d as performUpgrade,c as getUpgradeCommand,e as checkVersionOnStartup,a as checkVersion};