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.
- package/dist/blade.js +2 -2
- package/dist/{chunk-z906d5tb.js → chunk-0n04bmta.js} +2 -2
- package/dist/{chunk-drrdzmaa.js → chunk-0xm8hn2h.js} +2 -2
- package/dist/chunk-0z7q89w7.js +2 -0
- package/dist/{chunk-gxmrakrk.js → chunk-1sw9z975.js} +1 -1
- package/dist/{chunk-948qe2pp.js → chunk-1v7hpr34.js} +1 -1
- package/dist/{chunk-fvhc1yj8.js → chunk-3fdyzgpv.js} +1 -1
- package/dist/{chunk-15d49qty.js → chunk-43j2f1b5.js} +1 -1
- package/dist/{chunk-njyvrtje.js → chunk-4hhkbyja.js} +2 -2
- package/dist/{chunk-6eragc74.js → chunk-4rhssb85.js} +2 -2
- package/dist/chunk-598egka3.js +22 -0
- package/dist/chunk-5ak9tw83.js +100 -0
- package/dist/chunk-738pkjf8.js +1 -0
- package/dist/{chunk-xv0maezy.js → chunk-7a200q5g.js} +2 -2
- package/dist/{chunk-5twefby5.js → chunk-7pkrwh10.js} +1 -1
- package/dist/chunk-7xfmzvxp.js +1 -0
- package/dist/{chunk-9ffr01c3.js → chunk-847e0sk9.js} +1 -1
- package/dist/chunk-867rz2ss.js +1 -0
- package/dist/chunk-a3e97syg.js +3 -0
- package/dist/{chunk-0n97186m.js → chunk-ahxc3n3g.js} +2 -2
- package/dist/{chunk-tq52pbde.js → chunk-akev4wsz.js} +1 -1
- package/dist/{chunk-epj56s0n.js → chunk-az4b6106.js} +1 -1
- package/dist/{chunk-63ysxybd.js → chunk-e9ckf8e7.js} +1 -1
- package/dist/chunk-f7854pbx.js +187 -0
- package/dist/chunk-fwt0kje3.js +1 -0
- package/dist/{chunk-1vx4sf1y.js → chunk-g1q27q6q.js} +2 -2
- package/dist/chunk-g3wgzyhx.js +160 -0
- package/dist/chunk-g4snq0dx.js +1 -0
- package/dist/chunk-ggm04adj.js +1 -0
- package/dist/chunk-hpytxsge.js +1 -0
- package/dist/chunk-htr91q9c.js +1 -0
- package/dist/chunk-hwcp940f.js +1 -0
- package/dist/chunk-j5ysjbyr.js +10 -0
- package/dist/{chunk-jza1rsan.js → chunk-jpy61wna.js} +1 -1
- package/dist/chunk-kqpwz9b7.js +8 -0
- package/dist/{chunk-gxzbv67r.js → chunk-m86ekqp0.js} +2 -2
- package/dist/{chunk-51wtvmzn.js → chunk-m8k1mv0j.js} +1 -1
- package/dist/{chunk-ydtcvxsm.js → chunk-mt4328yf.js} +1 -1
- package/dist/{chunk-35yktzm1.js → chunk-ne7zdjrh.js} +1 -1
- package/dist/{chunk-bexgcc2d.js → chunk-p0j8994h.js} +1 -1
- package/dist/{chunk-gb54hc78.js → chunk-p3ahf1fh.js} +1 -1
- package/dist/chunk-pt659n0v.js +1466 -0
- package/dist/chunk-q1gfeadm.js +1 -0
- package/dist/{chunk-vntzy7bc.js → chunk-qk2z6gag.js} +2 -2
- package/dist/{chunk-ea7wsges.js → chunk-qqwgb9ja.js} +2 -2
- package/dist/{chunk-am8dtvff.js → chunk-qycwavck.js} +72 -17
- package/dist/chunk-rk1w5pry.js +2 -0
- package/dist/{chunk-s645azsm.js → chunk-rn908m3v.js} +2 -2
- package/dist/{chunk-dqvcgwhe.js → chunk-rz2ftt6h.js} +2 -2
- package/dist/{chunk-19kg7yvw.js → chunk-rz9yh6e4.js} +2 -2
- package/dist/{chunk-qm11hjd3.js → chunk-tc83e1b0.js} +1 -1
- package/dist/{chunk-v93hcxe7.js → chunk-tcc3v4n2.js} +1 -1
- package/dist/{chunk-g6h6h8xr.js → chunk-tp9zk241.js} +1 -1
- package/dist/chunk-tzh4ahry.js +6 -0
- package/dist/chunk-v0rn831t.js +1 -0
- package/dist/{chunk-fz1vyc15.js → chunk-vafn0spm.js} +1 -1
- package/dist/{chunk-rh7v814a.js → chunk-vcq624qv.js} +2 -2
- package/dist/chunk-vynsgc2g.js +1 -0
- package/dist/{chunk-qda309d9.js → chunk-w01sec4f.js} +2 -2
- package/dist/chunk-w0ena7fe.js +9 -0
- package/dist/{chunk-6tx8k249.js → chunk-wmdgb5pz.js} +2 -2
- package/dist/{chunk-an96c54z.js → chunk-wrbm6rch.js} +8 -8
- package/dist/{chunk-sanhjqpd.js → chunk-x3780wpy.js} +2 -2
- package/dist/{chunk-yc53wz4r.js → chunk-y573s5r8.js} +2 -2
- package/dist/chunk-ydwjttdz.js +1 -0
- package/dist/{chunk-vpj0sv73.js → chunk-yyvx1avz.js} +3 -3
- package/dist/chunk-z9fsh3kn.js +1 -0
- package/dist/{chunk-ygx03mdh.js → chunk-zjf1z27e.js} +1 -1
- package/dist/web/assets/ChatView-BYfHmxKJ.js +7 -0
- package/dist/web/assets/{CodeBlockHighlighter-CFW6qjnA.js → CodeBlockHighlighter-CC4e9nFc.js} +1 -1
- package/dist/web/assets/{FilePreview-CR_XetY0.js → FilePreview-C3HEoLYS.js} +1 -1
- package/dist/web/assets/{MarkdownRenderer-CVrxJswQ.js → MarkdownRenderer-COycrGUX.js} +3 -3
- package/dist/web/assets/{McpModal-BO-85gll.js → McpModal-CDgr9kVq.js} +1 -1
- package/dist/web/assets/{SettingsModal-CW87OnxI.js → SettingsModal-CvdVIbeG.js} +1 -1
- package/dist/web/assets/{SkillsModal-Q8ZFPhys.js → SkillsModal-lSX1ZKTu.js} +1 -1
- package/dist/web/assets/{TaskSwitcher-BzH-0QXr.js → TaskSwitcher-peKi9KvN.js} +1 -1
- package/dist/web/assets/{TerminalPanel-DTqvx8yB.js → TerminalPanel-DqQ-7CTG.js} +1 -1
- package/dist/web/assets/index-BF5HEN_f.js +32 -0
- package/dist/web/assets/index-BrkTYxtS.css +1 -0
- package/dist/web/index.html +2 -2
- package/package.json +1 -1
- package/dist/chunk-069zpw09.js +0 -6
- package/dist/chunk-1m5r6mp2.js +0 -180
- package/dist/chunk-1q21sxhx.js +0 -1
- package/dist/chunk-1r6szcrj.js +0 -1
- package/dist/chunk-1x4fpe47.js +0 -1
- package/dist/chunk-2nkd1kjx.js +0 -1
- package/dist/chunk-417wefq7.js +0 -99
- package/dist/chunk-4ncbd4k0.js +0 -1
- package/dist/chunk-62881c2s.js +0 -1484
- package/dist/chunk-7443b95r.js +0 -1
- package/dist/chunk-79s052sw.js +0 -2
- package/dist/chunk-7jy60gnx.js +0 -1
- package/dist/chunk-c5tds5v0.js +0 -9
- package/dist/chunk-ccwskwb3.js +0 -1
- package/dist/chunk-f6mszdsd.js +0 -1
- package/dist/chunk-hh85pk77.js +0 -160
- package/dist/chunk-nz78b5c5.js +0 -10
- package/dist/chunk-r1764q6f.js +0 -1
- package/dist/chunk-r6mwyg3h.js +0 -3
- package/dist/chunk-rzzt21ef.js +0 -22
- package/dist/chunk-t8x2qpe2.js +0 -1
- package/dist/chunk-tjnfhm9v.js +0 -1
- package/dist/chunk-v0ygsjry.js +0 -1
- package/dist/chunk-zyz82mcd.js +0 -1
- package/dist/web/assets/ChatView-Y-6k-ayR.js +0 -7
- package/dist/web/assets/index-B7etZcne.css +0 -1
- package/dist/web/assets/index-ClOgGy-I.js +0 -32
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
import{Cb as P,Db as n$,Eb as s0,Fb as i$,Gb as I,Hb as e0,Ib as d$,Jb as $$,Kb as q$,Lb as T$,Nb as R0,Qb as G$,Rb as o$}from"./chunk-wrbm6rch.js";import{Qc as x0}from"./chunk-1sw9z975.js";import{pd as B0}from"./chunk-ne7zdjrh.js";import{yd as A$}from"./chunk-tc83e1b0.js";import{Cd as F0}from"./chunk-w01sec4f.js";import{Ae as c$,Be as p$}from"./chunk-rk1w5pry.js";import{Ge as K$}from"./chunk-az4b6106.js";import{Me as Z0,Pe as Q0}from"./chunk-p0j8994h.js";import{Te as c}from"./chunk-g1q27q6q.js";import{$e as K0,_e as l$,bf as M,cf as m,ef as t0,ff as l,gf as L0}from"./chunk-ahxc3n3g.js";import{readdir as y$,readFile as s,rm as D0,stat as yq}from"node:fs/promises";import*as K from"node:path";import{nanoid as j}from"nanoid";import{createHash as e$,randomUUID as $q}from"node:crypto";import*as v from"node:fs/promises";import*as Y0 from"node:path";var Y$=1;function qq($,q){let T=e$("sha256").update(q).digest("hex");return Y0.join(K0($),".locks",`${T}.lock`)}function X0($,q){return $ instanceof Error&&"code"in $&&$.code===q}async function S0($){try{let q=JSON.parse(await v.readFile($,"utf8"));if(q.version!==Y$||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 V$($){let q=await S0($);if(q)return q;return await new Promise((T)=>setTimeout(T,10)),S0($)}function Tq($){try{return process.kill($,0),!0}catch(q){return X0(q,"EPERM")}}async function X$($,q){let T;try{return T=await v.open($,"wx",384),await T.writeFile(`${JSON.stringify(q)}
|
|
2
|
+
`,"utf8"),!0}catch(G){if(X0(G,"EEXIST"))return!1;if(T)await v.unlink($).catch(()=>{return});throw G}finally{await T?.close().catch(()=>{return})}}class n 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 i{filePath;record;released=!1;constructor($,q){this.filePath=$;this.record=q}static async acquire($,q=K$()){let T=qq(q,$),G={version:Y$,sessionId:$,ownerId:$q(),pid:process.pid,acquiredAt:new Date().toISOString()};if(await v.mkdir(Y0.dirname(T),{recursive:!0,mode:448}),await X$(T,G))return new i(T,G);let J=await V$(T);if(J&&Tq(J.pid))throw new n(J.pid);if(await v.unlink(T).catch((L)=>{if(!X0(L,"ENOENT"))throw L}),await X$(T,G))return new i(T,G);throw new n((await V$(T))?.pid)}async release(){if(this.released)return;if(this.released=!0,(await S0(this.filePath))?.ownerId!==this.record.ownerId)return;await v.unlink(this.filePath).catch((q)=>{if(!X0(q,"ENOENT"))throw q})}}function Gq($,q){for(let T of $){if(T.type!=="part_created"||T.data.partType!=="tool_result")continue;let G=T.data.payload;if(!G||typeof G!=="object"||Array.isArray(G))continue;let J=G;if(J.toolCallId===q||T.data.partId===q||T.data.messageId===q)return J}return}function N$($){let q=P($),T=new Map;for(let G of q){if(G.type==="interaction_requested"){T.set(G.data.requestId,{request:G.data,hasToolResult:!1,hasRecoveryToolResult:!1});continue}if(G.type==="interaction_responded"){let J=T.get(G.data.requestId);if(J)J.response=G.data;continue}if(G.type==="interaction_recovered"){let J=T.get(G.data.requestId);if(J)J.recovery=G.data}}for(let G of T.values()){let J=Gq(q,G.request.toolCallId);G.hasToolResult=J!==void 0;let L=J?.metadata&&typeof J.metadata==="object"?J.metadata:void 0;G.hasRecoveryToolResult=L?.interactionRecovery===!0&&L.requestId===G.request.requestId}return[...T.values()]}function U$($){return N$($).reverse().find((q)=>!q.response&&!q.recovery)}function Z1($){let q=new Map;for(let T of N$($))q.set(T.request.toolCallId,T);return[...q.values()].filter((T)=>T.response&&!T.recovery&&(!T.hasToolResult||T.hasRecoveryToolResult))}function F$($){if(!$)return;return{type:$.request.interactionType,requestId:$.request.requestId}}function N0($){let q=new Map,T=[];for(let G of $){if(G.type==="review_started"){if(!q.has(G.data.reviewId))T.push(G.data.reviewId),q.set(G.data.reviewId,{start:G.data});continue}if(G.type!=="review_completed")continue;let J=q.get(G.data.reviewId);if(J&&J.completion===void 0)J.completion=G.data}return T.map((G)=>q.get(G)).filter((G)=>G!==void 0)}function x1($){return N0($).reverse().find((q)=>q.completion===void 0)}function j0($){switch($){case"completed":return"completed";case"stale":return"stale: the review target changed while the reviewer was running";case"aborted":return"aborted";case"interrupted":return"interrupted by process restart";case"failed":return"failed"}}function O$($,q){let T=["## Code Review","",`Target: ${$.target.label}`,`Status: ${j0(q.status)}`,"",q.overallExplanation||"No overall explanation was provided."];if(q.findings.length===0)T.push("","No actionable findings.");else{T.push("","### Findings");for(let[G,J]of q.findings.entries()){let L=J.codeLocation.lineStart===J.codeLocation.lineEnd?`${J.codeLocation.lineStart}`:`${J.codeLocation.lineStart}-${J.codeLocation.lineEnd}`;T.push("",`${G+1}. ${J.title}`,` ${J.codeLocation.path}:L${L} · confidence ${J.confidenceScore.toFixed(2)}`,` ${J.body}`)}}if(q.error)T.push("",`Error: ${q.error}`);return T.join(`
|
|
3
|
+
`)}function W$($,q){return{reviewId:$.reviewId,phase:"completed",status:q.status,target:{kind:$.target.kind,label:$.target.label,...$.target.baseSha?{reference:$.target.baseSha}:{},...$.target.commitSha?{reference:$.target.commitSha}:{}},overallExplanation:q.overallExplanation,findings:q.findings.map((T)=>({title:T.title,body:T.body,priority:T.priority,confidenceScore:T.confidenceScore,codeLocation:{...T.codeLocation}})),...q.error?{error:q.error}:{}}}var m0={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 Lq($){try{if($ instanceof Error)return $.message;if($!==null&&typeof $==="object"&&"message"in $&&typeof $.message==="string")return $.message;return String($)}catch{return"Unknown error"}}function Jq($){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 Zq($){return{code:$,...m0[$]}}function v0($){return Zq(Jq(Lq($)))}function I0($){if(!$||typeof $!=="object")return!1;let q=$;if(typeof q.code!=="string"||!(q.code in m0))return!1;let T=m0[q.code];return q.message===T.message&&q.retryable===T.retryable}import{promises as q0,realpathSync as xq}from"node:fs";import U0 from"node:path";import*as o from"fs/promises";import*as W from"path";var _$=[".git",".claude","node_modules",".env",".env.local",".env.production",".env.development",".env.test"];class d extends Error{code;constructor($,q){super($);this.code=q;this.name="PathSecurityError"}}class u0{static normalize($,q){let T=W.isAbsolute($)?$:W.resolve(q,$),G=W.normalize(T),J=W.normalize(q);if(!this.isWithinWorkspace(G,J))throw new d(`Path outside workspace: ${$} (resolved to ${G}, workspace: ${J})`,"PATH_OUTSIDE_WORKSPACE");return G}static checkRestricted($){let q=$.split(W.sep);for(let T of _$)if(q.includes(T))throw new d(`Access denied: "${T}" is a protected directory`,"RESTRICTED_PATH")}static checkTraversal($){if($.includes(".."))throw new d(`Path traversal not allowed: ${$}`,"PATH_TRAVERSAL")}static async validatePath($,q){this.checkTraversal($);let T=this.normalize($,q);this.checkRestricted(T);try{await o.access(T)}catch(G){throw new d(`Path not found: ${$}`,"PATH_NOT_FOUND")}return T}static async resolveSymlink($,q){try{let T=await o.realpath($),G=await o.realpath(q);if(!this.isWithinWorkspace(T,G))throw new d(`Symlink points outside workspace: ${$} -> ${T}`,"SYMLINK_OUTSIDE_WORKSPACE");return T}catch(T){if(T instanceof d)throw T;return $}}static getRelativePath($,q){return W.relative(q,$)}static isWithinWorkspace($,q){let T=W.resolve($),G=W.resolve(q),J=W.relative(G,T);return J===""||J!==".."&&!J.startsWith(`..${W.sep}`)&&!W.isAbsolute(J)}static async isWithinWorkspaceResolved($,q){let T=W.resolve(q),G=W.isAbsolute($)?W.resolve($):W.resolve(T,$);if(!this.isWithinWorkspace(G,T))return!1;let J;try{J=await o.realpath(T)}catch{return!1}let L=G;while(!0){try{let Q=await o.realpath(L);return this.isWithinWorkspace(Q,J)}catch(Q){let H=Q.code;if(H!=="ENOENT"&&H!=="ENOTDIR")return!1}let Z=W.dirname(L);if(Z===L)return!1;L=Z}}static isRestricted($){let q=$.split(W.sep);return _$.some((T)=>q.includes(T))}}var T0=F0("Tool");class h{static instance=null;accessedFiles=new Map;pathAliases=new Map;constructor(){}static getInstance(){if(!h.instance)h.instance=new h;return h.instance}async recordFileRead($,q){try{let T=await q0.stat($),G={filePath:U0.resolve($),accessTime:Date.now(),mtime:T.mtimeMs,sessionId:q,lastOperation:"read"};this.setRecord(G),await this.recordAliases($,G.filePath),T0.debug(`记录文件读取: ${$}`)}catch(T){T0.warn(`记录文件读取失败: ${$}`,T)}}async recordFileEdit($,q,T="edit"){try{let G=await q0.stat($),J={filePath:U0.resolve($),accessTime:Date.now(),mtime:G.mtimeMs,sessionId:q,lastOperation:T};this.setRecord(J),await this.recordAliases($,J.filePath),T0.debug(`记录文件${T==="edit"?"编辑":"写入"}: ${$}`)}catch(G){T0.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 q0.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 J=G;if(J.code==="ENOENT")return{modified:!0,message:"文件已被删除"};return{modified:!1,message:`无法检查文件状态: ${J.message}`}}}async checkExternalModification($,q){let T=this.getFileRecord($,q);if(!T)return{isExternal:!1,message:"文件未被跟踪"};try{let G=await q0.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 J=G;if(J.code==="ENOENT")return{isExternal:!0,message:"文件已被删除"};return T0.warn(`检查文件外部修改失败: ${$}`,G),{isExternal:!1,message:`无法检查文件状态: ${J.message}`}}}getFileRecord($,q){let T=this.accessedFiles.get(this.resolveTrackedPath($));if(!T)return;if(q)return T.get(q);return[...T.values()].sort((G,J)=>J.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&&!u0.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(){h.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(U0.resolve($),q);let T=await q0.realpath($).catch(()=>{return});if(T)this.pathAliases.set(T,q)}resolveTrackedPath($){let q=U0.resolve($);if(this.accessedFiles.has(q))return q;let T=this.pathAliases.get(q);if(T)return T;try{let G=xq.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 G0 from"node:crypto";import{promises as N}from"node:fs";import*as F from"node:path";import P0 from"write-file-atomic";var C$="missing";class O0{sessionId;workspaceRoot;enableCheckpoints;maxSnapshots;snapshotDir;manifestPath;trackedFileBackups=new Map;snapshots=[];constructor($){if(M($.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=L0();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 N.mkdir(this.snapshotDir,{recursive:!0,mode:493}),await this.loadManifest()}async selectWorkspaceSnapshotDir(){let $=L0(),q=await N.realpath(this.workspaceRoot).catch(()=>this.workspaceRoot),T=G0.createHash("sha256").update(q).digest("hex").slice(0,24),G=F.join($,"file-history",this.sessionId),J=F.join($,"file-history","workspaces",T,this.sessionId),L=F.join(J,"manifest.json");try{await N.access(L)}catch{await this.migrateLegacySnapshotDir(G,J,q)}this.snapshotDir=J,this.manifestPath=L}async migrateLegacySnapshotDir($,q,T){let G;try{G=JSON.parse(await N.readFile(F.join($,"manifest.json"),"utf8"))}catch{return}if(G.schemaVersion!==1||!Array.isArray(G.snapshots)||!G.snapshots.every((J)=>this.isWithinWorkspace(J.filePath,T)))return;await N.mkdir(F.dirname(q),{recursive:!0,mode:493});try{await N.rename($,q)}catch(J){let L=J.code;if(L!=="ENOENT"&&L!=="EEXIST"&&L!=="ENOTEMPTY")throw J}}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 N.access(T)}catch{G=!1}let J=this.trackedFileBackups.get(T),L=J?J.version+1:1,Z=this.generateFileHash(T,L),Q=this.getSnapshotPath(Z,L),H=new Date;if(G){let B=await N.readFile(T);await N.writeFile(Q,B)}let x={backupFileName:Z,version:L,backupTime:H};return this.trackedFileBackups.set(T,x),this.snapshots.push({messageId:q,backupFileName:Z,timestamp:H,filePath:T,version:L,existedBefore:G}),await this.cleanupOldSnapshots(T),await this.persistManifest(),x}async recordPostEditState($,q){if(!this.enableCheckpoints||!q.backupFileName)return;let T=await this.resolveFileIdentity($),G=this.snapshots.find((J)=>J.filePath===T&&J.backupFileName===q.backupFileName&&J.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((J)=>J.filePath===T&&J.backupFileName===q.backupFileName&&J.version===q.version);if(!G)return;this.removeSnapshot(G),await N.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((L)=>L.filePath===q&&L.postEditHash!==void 0);if(!T?.postEditHash)throw Error(`未找到可回退快照: ${q}`);if(await this.hashFile(q)!==T.postEditHash)throw Error(`文件在 Blade 编辑后已被修改,拒绝覆盖: ${q}`);let J=this.getSnapshotPath(T.backupFileName,T.version);if(T.existedBefore){let L=await N.readFile(J);await N.mkdir(F.dirname(q),{recursive:!0}),await N.writeFile(q,L)}else await N.rm(q,{force:!0});return this.removeSnapshot(T),await N.rm(J,{force:!0}),await this.persistManifest(),T}async restoreSnapshot($,q){let T=await this.resolveFileIdentity($),G=this.snapshots.slice().reverse().find((L)=>L.messageId===q&&L.filePath===T);if(!G)throw Error(`未找到快照: messageId=${q}, filePath=${T}`);let J=this.getSnapshotPath(G.backupFileName,G.version);if(G.existedBefore){let L=await N.readFile(J);await N.mkdir(F.dirname(T),{recursive:!0}),await N.writeFile(T,L)}else await N.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 J of q){let L,Z=!0;try{L=await N.readFile(J.filePath)}catch(H){if(H.code!=="ENOENT")throw H;Z=!1}if((L?G0.createHash("sha256").update(L).digest("hex"):C$)!==J.latest.postEditHash)throw Error(`文件在 Blade 编辑后已被修改,拒绝覆盖: ${J.filePath}`);if(T.set(J.filePath,{existed:Z,content:L}),J.target.existedBefore)await N.access(this.getSnapshotPath(J.target.backupFileName,J.target.version))}let G=[...this.snapshots];try{for(let L of q)if(L.target.existedBefore){let Z=await N.readFile(this.getSnapshotPath(L.target.backupFileName,L.target.version));await N.mkdir(F.dirname(L.filePath),{recursive:!0}),await P0(L.filePath,Z)}else await N.rm(L.filePath,{force:!0});let J=new Set(q.flatMap((L)=>L.selected));this.snapshots=this.snapshots.filter((L)=>!J.has(L)),this.rebuildTrackedFileBackups(),await this.persistManifest(),await Promise.all([...J].map((L)=>N.rm(this.getSnapshotPath(L.backupFileName,L.version),{force:!0}).catch(()=>{return})))}catch(J){this.snapshots=G,this.rebuildTrackedFileBackups();let L=[];for(let[Z,Q]of T)try{if(Q.existed&&Q.content)await P0(Z,Q.content);else await N.rm(Z,{force:!0})}catch(H){L.push(H)}if(L.length>0)throw AggregateError([J,...L],"快照回退失败且无法完整恢复回退前状态");throw J}return{files:q.map((J)=>J.filePath),snapshotCount:q.reduce((J,L)=>J+L.selected.length,0)}}async commitSnapshots($){let q=this.buildRewindPlan($),T=new Set(q.flatMap((J)=>J.selected));if(T.size===0)return{files:[],snapshotCount:0};let G=[...this.snapshots];this.snapshots=this.snapshots.filter((J)=>!T.has(J)),this.rebuildTrackedFileBackups();try{await this.persistManifest()}catch(J){throw this.snapshots=G,this.rebuildTrackedFileBackups(),J}return await Promise.all([...T].map((J)=>N.rm(this.getSnapshotPath(J.backupFileName,J.version),{force:!0}).catch(()=>{return}))),{files:q.map((J)=>J.filePath),snapshotCount:T.size}}buildRewindPlan($){let q=new Set($),T=this.snapshots.filter((L)=>L.postEditHash!==void 0),G=T.filter((L)=>q.has(L.messageId));return[...new Set(G.map((L)=>L.filePath))].sort().map((L)=>{let Z=T.filter((B)=>B.filePath===L),Q=Z.filter((B)=>q.has(B.messageId)),H=Z.indexOf(Q[0]),x=Z.slice(H);if(x.length!==Q.length||x.some((B)=>!q.has(B.messageId)))throw Error(`请求的快照不是文件历史的连续后缀: ${L}`);return{filePath:L,selected:Q,target:Q[0],latest:Q.at(-1)}})}async loadManifest(){try{let $=await N.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 N.rm(this.manifestPath,{force:!0});return}let $={schemaVersion:1,snapshots:this.snapshots.map((q)=>({...q,timestamp:q.timestamp.toISOString()}))};await P0(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 N.rm(this.getSnapshotPath(G.backupFileName,G.version),{force:!0}),this.removeSnapshot(G)}async cleanup($=0){let q=this.snapshots.slice().sort((G,J)=>J.timestamp.getTime()-G.timestamp.getTime()),T=new Set(q.slice(0,$));for(let G of this.snapshots)if(!T.has(G))await N.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 L=await N.realpath(G);return F.join(L,...T.reverse())}catch(L){let Z=L.code;if(Z!=="ENOENT"&&Z!=="ENOTDIR")throw L}let J=F.dirname(G);if(J===G)return q;T.push(F.basename(G)),G=J}}async hashFile($){try{let q=await N.readFile($);return G0.createHash("sha256").update(q).digest("hex")}catch(q){if(q.code==="ENOENT")return C$;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=G0.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 Cq}from"node:crypto";import w$ from"node:path";import{StringDecoder as Xq}from"node:string_decoder";function Bq($,q){let T=q;while(T<$.length&&($[T]&192)===128)T+=1;return T}class h0{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=Bq($,q);this.chunks[0]=$.subarray(T),this.retainedBytes-=T,this.omittedBytes+=T}}}var W0={maxLines:30,maxChars:3000,keepHead:10,keepTail:10,summarize:!0},r={maxLines:100,maxChars:1e4,keepHead:40,keepTail:40,summarize:!0},z$={maxLines:200,maxChars:20000,keepHead:80,keepTail:80,summarize:!1},Hq={maxLines:150,maxChars:15000,keepHead:50,keepTail:50,summarize:!0},Vq=[{pattern:/^git\s+(rm|add)\s+(-r|--cached|-rf|-f)?\s*/i,config:W0,summaryTemplate:($)=>`Successfully processed ${$} files`},{pattern:/^(npm|pnpm|yarn|bun)\s+(install|i|add|remove|uninstall)/i,config:W0,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:z$},{pattern:/^git\s+(status|branch|remote)/i,config:r},{pattern:/^git\s+(log|diff|show)/i,config:z$},{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:W0,summaryTemplate:($)=>`Docker operation completed (${$} lines)`},{pattern:/^(pip|pip3|poetry|pipenv)\s+(install|uninstall)/i,config:W0,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 l0{static getConfigForCommand($){for(let{pattern:q,config:T,summaryTemplate:G}of Vq)if(q.test($))return{config:T,summaryTemplate:G};return{config:Hq}}static truncate($,q){let{config:T,summaryTemplate:G}=this.getConfigForCommand(q);return this.truncateWithConfig($,T,G)}static truncateWithConfig($,q,T){let G=$.length,J=$.split(`
|
|
4
|
+
`),L=J.length;if(L<=q.maxLines&&G<=q.maxChars)return{content:$,truncated:!1,originalLines:L,originalChars:G};let Z=J.slice(0,q.keepHead),Q=J.slice(-q.keepTail),H=L-q.keepHead-q.keepTail,x=Z.join(`
|
|
5
|
+
`);if(x+=`
|
|
6
|
+
|
|
7
|
+
... (${H} lines truncated, showing first ${q.keepHead} and last ${q.keepTail} of ${L} total) ...
|
|
8
|
+
|
|
9
|
+
`,x+=Q.join(`
|
|
10
|
+
`),x.length>q.maxChars){let V=Math.floor(q.maxChars/2)-50,X=x.slice(0,V),Y=x.slice(-V);x=`${X}
|
|
11
|
+
|
|
12
|
+
... (content truncated to ${q.maxChars} chars) ...
|
|
13
|
+
|
|
14
|
+
${Y}`}let B=q.summarize&&T?T(L,G):void 0;if(B)x+=`
|
|
15
|
+
|
|
16
|
+
[Summary: ${B}]`;return{content:x,truncated:!0,originalLines:L,originalChars:G,summary:B}}static truncateForLLM($,q,T){let G=this.truncate($,T),J=this.truncate(q,T),L;if(G.truncated||J.truncated){let Z=[];if(G.truncated)Z.push(`stdout: ${G.originalLines} lines -> ${G.content.split(`
|
|
17
|
+
`).length} lines`);if(J.truncated)Z.push(`stderr: ${J.originalLines} lines -> ${J.content.split(`
|
|
18
|
+
`).length} lines`);L=`Output truncated: ${Z.join(", ")}`}return{stdout:G.content,stderr:J.content,truncationInfo:L}}static shouldTruncate($,q){let{config:T}=this.getConfigForCommand(q);return $.split(`
|
|
19
|
+
`).length>T.maxLines||$.length>T.maxChars}static getStats($){return{lines:$.split(`
|
|
20
|
+
`).length,chars:$.length,words:$.split(/\s+/).filter(Boolean).length}}}var D$=32768,Kq=1048576,Yq=65536,Nq=3600000,R$=4096,Uq=/[\u001B\u009B][[\]()#;?]*(?:(?:(?:[a-zA-Z\d]*(?:;[-a-zA-Z\d/#&.:=?%@~_]+)*)?\u0007)|(?:(?:\d{1,4}(?:[;:]\d{0,4})*)?[\dA-PR-TZcf-nq-uy=><~]))/g;class c0{stream;executionId;onEvent;output=new h0(Kq/2);decoder=new Xq("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<R$){let G=q.subarray(0,Math.min(q.length,R$-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=M$(this.decoder.write(q));this.output.append(T),this.emit(T)}finish(){if(this.binary)return;let $=M$(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=Yq-this.streamedBytes;if(q<=0){this.streamTruncated=!0;return}let T=Fq($,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 M$($){return $.replace(Uq,"")}function Fq($,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 f$($){return $.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""").replaceAll("'","'")}function Oq($){let q=$.trim();if(!q)throw Error("User shell command cannot be empty");if(q.length>D$)throw Error(`User shell command exceeds ${D$} characters`);if(q.includes("\x00"))throw Error("User shell command contains a null byte");return q}function Wq(){return{execute($,q){return new Promise((T)=>{let G=process.platform==="win32"?process.env.COMSPEC||"cmd.exe":process.env.SHELL||"/bin/bash",J=process.platform==="win32"?["/d","/s","/c",$]:["-l","-c",$],{child:L,processTree:Z}=A$(G,J,{cwd:q.cwd,env:q.env,stdio:["ignore","pipe","pipe"]}),Q="",H="",x=!1,B=!1,V=!1,X,Y=()=>{return X??=Z.terminate(),X},b=setTimeout(()=>{x=!0,Y()},q.timeoutMs),A=()=>{B=!0,Y()};if(q.signal.addEventListener("abort",A,{once:!0}),q.signal.aborted)A();L.stdout?.on("data",(C)=>{q.onOutput?.("stdout",C)}),L.stderr?.on("data",(C)=>{q.onOutput?.("stderr",C)});let w=async(C)=>{if(V)return;if(V=!0,clearTimeout(b),q.signal.removeEventListener("abort",A),x||B)await Y();T({...C,stdout:"",stderr:"",timedOut:x,aborted:B})};L.once("error",(C)=>{w({exitCode:null,error:C.message})}),L.once("close",(C)=>{w({exitCode:C})})})}}}async function A1($,q){let T=Oq($),G=q.timeoutMs??Nq,J=new c0("stdout",q.executionId,q.onEvent),L=new c0("stderr",q.executionId,q.onEvent),Z=Date.now();await q.onEvent?.({type:"started",executionId:q.executionId,command:T});let Q,H=!1,x=!1;try{Q=await(q.executor??Wq()).execute(T,{cwd:q.cwd,env:q.env,timeoutMs:G,signal:q.signal,onOutput:(A,w)=>{if(A==="stdout")H=!0;else x=!0;(A==="stdout"?J:L).append(w)}})}catch(A){Q={exitCode:null,stdout:"",stderr:"",error:A instanceof Error?A.message:String(A)}}if(!H)J.append(Q.stdout);if(!x)L.append(Q.stderr);J.finish(),L.finish(),await Promise.all([J.flushEvents(),L.flushEvents()]);let B=J.snapshot(),V=L.snapshot(),X=l0.truncateForLLM(B.content.trim(),V.content.trim(),T),Y=Q.aborted||q.signal.aborted?"aborted":Q.timedOut?"timed_out":Q.error?"spawn_error":Q.exitCode===0?"completed":"failed",b={version:1,command:T,status:Y,exitCode:Q.exitCode,durationMs:Math.max(0,Date.now()-Z),stdout:X.stdout,stderr:Q.error?[X.stderr,Q.error].filter(Boolean).join(`
|
|
21
|
+
`):X.stderr,stdoutOmittedBytes:B.omittedBytes,stderrOmittedBytes:V.omittedBytes,binaryOutput:B.binary||V.binary,truncated:Boolean(X.truncationInfo)||B.omittedBytes>0||V.omittedBytes>0};return await q.onEvent?.({type:"completed",executionId:q.executionId,record:b}),b}function E1($){let q=[$.stdout?`stdout:
|
|
22
|
+
${$.stdout}`:"",$.stderr?`stderr:
|
|
23
|
+
${$.stderr}`:""].filter(Boolean).join(`
|
|
24
|
+
`);return["<user_shell_command>",`<command>${f$($.command)}</command>`,"<result>",`Status: ${$.status}`,`Exit code: ${$.exitCode??"null"}`,`Duration: ${($.durationMs/1000).toFixed(3)} seconds`,`Output:
|
|
25
|
+
${f$(q||"(no output)")}`,"</result>","</user_shell_command>"].join(`
|
|
26
|
+
`)}function E$($){let q=[$.stdout,$.stderr?`stderr:
|
|
27
|
+
${$.stderr}`:""].filter(Boolean).join(`
|
|
28
|
+
`);return[`! ${$.command}`,q||"(no output)"].join(`
|
|
29
|
+
`)}function _q($){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 _0($){if(!$||typeof $!=="object"||Array.isArray($))return;return _q($.userShellCommand)}var C0=16777216,b$=65536,S1=1048576,zq=8,z0=200,Dq=/(?:^|[_-])(?:api[_-]?key|authorization|bearer|cookie|credential|password|passwd|private[_-]?key|refresh[_-]?token|secret|session[_-]?token|token)(?:$|[_-])/i,Rq=/(?<![:/A-Za-z0-9._-])\/[^\s"'`<>]+/g,Mq=/(?<![A-Za-z0-9._-])[A-Za-z]:[\\/][^\s"'`<>]+/g,fq=new RegExp("\\u001b(?:\\[[0-?]*[ -/]*[@-~]|\\][^\\u0007]*(?:\\u0007|\\u001b\\\\))","g"),Aq=/-----BEGIN [^-]*PRIVATE KEY-----[\s\S]*?-----END [^-]*PRIVATE KEY-----/g;function g($,q){return $.count+=1,q}function Eq($){return Dq.test($.replace(/[A-Z]/g,(q)=>`_${q.toLowerCase()}`))}function bq($){return[...$].filter((q)=>{if(q===`
|
|
30
|
+
`||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(fq,"");if(G!==T)q.count+=1;T=G,T=T.replace(Aq,()=>g(q,"[redacted-private-key]")),T=T.replace(/\bBearer\s+[^\s"'`]+/gi,()=>g(q,"Bearer [redacted]")).replace(/\bsk-[A-Za-z0-9_-]{8,}\b/g,()=>g(q,"[redacted-key]")).replace(/\bAKIA[0-9A-Z]{16}\b/g,()=>g(q,"[redacted-aws-key]")).replace(/\b(api[_-]?key|access[_-]?token|authorization|cookie|password|passwd|refresh[_-]?token|secret|session[_-]?token)\b(\s*[:=]\s*)([^\s,;]+)/gi,(L,Z,Q)=>`${Z}${Q}${g(q,"[redacted]")}`);let J=bq(T);if(J!==T)q.count+=1;return J.replace(/\r\n?/g,`
|
|
31
|
+
`)}function k$($,q,T){if(/^data:[^;,]+;base64,/i.test($))return g(T,"[binary omitted]");let G=k($,T),J=w$.resolve(q);for(let L of[J,J.startsWith("/private/")?J.slice(8):`/private${J}`])G=G.replaceAll(L,".");return G=G.replace(Rq,(L)=>L.startsWith("./")?L:g(T,"[host-path]")),G=G.replace(Mq,()=>g(T,"[host-path]")),G=G.replace(/\bhttps?:\/\/[^\s"'`]+/gi,(L)=>{try{let Z=new URL(L);if(Z.username||Z.password||Z.search||Z.hash)T.count+=1;return Z.username="",Z.password="",Z.search="",Z.hash="",Z.toString()}catch{return g(T,"[redacted-url]")}}),G}function i0($,q,T,G=0,J){if(J&&Eq(J))return g(T,"[redacted]");if(G>=zq)return g(T,"[depth limit]");if(typeof $==="string")return k$($,q,T);if($===null||typeof $==="boolean"||typeof $==="number"&&Number.isFinite($))return $;if(Array.isArray($)){let L=$.slice(0,z0).map((Z)=>i0(Z,q,T,G+1));if($.length>L.length)L.push(g(T,`[${$.length-L.length} items omitted]`));return L}if($&&typeof $==="object"){let L={},Z=Object.entries($);for(let[Q,H]of Z.slice(0,z0))L[k(Q,T)]=i0(H,q,T,G+1,Q);if(Z.length>z0)L["[entries omitted]"]=Z.length-z0;return L}return String($)}function wq($,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 kq($,q,T){let G=JSON.stringify(i0($,q,T),null,2);if(Buffer.byteLength(G,"utf8")<=b$)return G;T.count+=1;let J=`
|
|
32
|
+
... [activity truncated]`;return wq(G,b$-Buffer.byteLength(J))+J}function d0($,q=""){let T=Math.max(2,...[...$.matchAll(/`+/g)].map((J)=>J[0].length)),G="`".repeat(T+1);return`${G}${q}
|
|
33
|
+
${$}
|
|
34
|
+
${G}`}function p0($){return $.replace(/\s+/g," ").trim()}function gq($){let q=new Map,T=new Map,G=new Map,J=0;for(let L of P($)){if(L.type==="message_created"){let B=T.get(L.data.messageId);if(B)B.role=L.data.role,B.metadata=L.data.metadata,q.set(L.data.messageId,B),T.delete(L.data.messageId);else if(!q.has(L.data.messageId))q.set(L.data.messageId,{order:J++,role:L.data.role,parts:[],metadata:L.data.metadata});continue}if(L.type!=="part_created"&&L.type!=="part_updated")continue;let Z=q.get(L.data.messageId)??T.get(L.data.messageId);if(!Z)Z={order:J++,role:"activity",parts:[]},T.set(L.data.messageId,Z);let Q=`${L.data.messageId}\x00${L.data.partType}\x00${L.data.partId}`,H=G.get(Q);if(H){H.event=L;continue}let x={order:J++,event:L};G.set(Q,x),Z.parts.push(x)}return[...q.values(),...T.values()].sort((L,Z)=>L.order-Z.order)}function n0($,q,T,G){return`## Activity: ${$}
|
|
35
|
+
|
|
36
|
+
${d0(kq(q,T.projectPath,G),"json")}`}function g$($,q,T={}){let G={count:0},J=T.includeReasoning===!0,L=[],Z=0,Q=0,H=0;for(let w of gq($)){let C=_0(w.metadata);if(C){let R=k(C.command,G),D=k([C.stdout,C.stderr?`stderr:
|
|
37
|
+
${C.stderr}`:""].filter(Boolean).join(`
|
|
38
|
+
`)||"(no output)",G);L.push(`## User shell command
|
|
39
|
+
|
|
40
|
+
${d0(`$ ${R}
|
|
41
|
+
${D}`,"console")}`),Z+=1;continue}let a=[],t=[],y=[],S=Number.POSITIVE_INFINITY;for(let R of w.parts.sort((D,f)=>D.order-f.order)){let{partType:D,payload:f}=R.event.data;if(D==="text"){let U=f.text;if(typeof U==="string"&&U.trim())a.push(k(U,G)),S=Math.min(S,R.order)}else if(D==="image"){let U=f.mimeType;t.push(typeof U==="string"?`[Image: ${k(U,G)}]`:"[Image]"),S=Math.min(S,R.order)}else if(D==="reasoning"&&J){let U=f.text;if(typeof U==="string"&&U.trim())y.push({order:R.order,markdown:`## Reasoning
|
|
42
|
+
|
|
43
|
+
${k(U,G).trim()}`}),H+=1}else if(D==="tool_call"){let U=f,E=typeof U.toolName==="string"?k(U.toolName,G):"unknown";y.push({order:R.order,markdown:n0(`${E} call`,U.input??{},q,G)}),Q+=1}else if(D==="tool_result"){let U=f,E=typeof U.toolName==="string"?k(U.toolName,G):"unknown";y.push({order:R.order,markdown:n0(`${E} result`,typeof U.error==="string"?{error:U.error}:{output:U.output??null},q,G)}),Q+=1}else if(D==="summary"){let U=f.text;if(typeof U==="string"&&U.trim())y.push({order:R.order,markdown:`## Summary
|
|
44
|
+
|
|
45
|
+
${k(U,G).trim()}`})}else if(D==="subtask_ref")y.push({order:R.order,markdown:n0("Subagent",f,q,G)}),Q+=1;else if(D==="diff"||D==="patch"){let U=typeof f==="string"?f:JSON.stringify(f,null,2);y.push({order:R.order,markdown:`## File changes
|
|
46
|
+
|
|
47
|
+
${d0(k$(U,q.projectPath,G),"diff")}`}),Q+=1}}if((w.role==="user"||w.role==="assistant")&&(a.length>0||t.length>0))y.push({order:S,markdown:`## ${w.role==="user"?"User":"Assistant"}
|
|
48
|
+
|
|
49
|
+
${[...a,...t].join(`
|
|
50
|
+
|
|
51
|
+
`).trim()}`}),Z+=1;L.push(...y.sort((R,D)=>R.order-D.order).map((R)=>R.markdown))}if(L.length===0)throw Error("No conversation content to export");let x=`${L.join(`
|
|
52
|
+
|
|
53
|
+
`)}
|
|
54
|
+
`,B=Buffer.byteLength(x,"utf8");if(B>C0)throw Error(`Session export exceeds ${C0} bytes`);let V=Cq("sha256").update(x).digest("hex"),X=w$.basename(q.taskSourceProjectPath??q.projectPath),Y=q.selectedModelId??q.taskModelId,A=["# Blade conversation","",`- Session: \`${q.sessionId}\``,...q.title?[`- Title: ${p0(k(q.title,G))}`]:[],`- Project: \`${p0(k(X,G))}\``,...Y?[`- Model: \`${p0(k(Y,G))}\``]:[],...q.permissionMode?[`- Permission mode: ${q.permissionMode}`]:[],`- Created: ${q.firstMessageTime}`,`- Updated: ${q.lastMessageTime}`,`- State: ${q.archivedAt?"archived":"active"}`,`- Reasoning: ${J?"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: \`${V}\``,`- Content bytes: ${B}`,`- Redactions: ${G.count}`,"","---",""].join(`
|
|
55
|
+
`)+`
|
|
56
|
+
`+x;if(Buffer.byteLength(A,"utf8")>C0)throw Error(`Session export exceeds ${C0} bytes`);return{filename:`blade-session-${q.sessionId.slice(0,12)}.md`,markdown:A,contentSha256:V,contentBytes:B,messageCount:Z,activityCount:Q,reasoningIncluded:J,reasoningCount:H,redactionCount:G.count}}var o0=F0("Service"),S$=new Set(["queued","running","completed","failed","cancelled","interrupted"]),L$=new Set(["local","worktree"]),Sq=new Set(["default","autoEdit","yolo","plan"]),jq=new Set(["applied","discarded","conflicted"]);class J$ extends Error{}function j$($){try{return process.kill($,0),!0}catch(q){return q instanceof Error&&"code"in q&&q.code==="EPERM"}}function m$($){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 v$($){if(!$||typeof $!=="object"||Array.isArray($))return;let q=$;if(!jq.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 I$($){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 u$($){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"||!K.isAbsolute(q.sourceProjectPath)||!L$.has(q.isolation)||!M0(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&&!x0(q.reasoningEffort)||q.serviceTier!==void 0&&!Q0(q.serviceTier)||q.responseVerbosity!==void 0&&!Z0(q.responseVerbosity)||q.communicationStyle!==void 0&&!B0(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>c$)return;let G=0;for(let J of q.attachments){if(!J||typeof J!=="object"||Array.isArray(J))return;let L=J;if(!["file","image","url"].includes(String(L.type)))return;for(let Z of["path","url","content","mimeType","name"])if(L[Z]!==void 0&&typeof L[Z]!=="string")return;G+=typeof L.content==="string"?Buffer.byteLength(L.content):0}if(G>p$)return;T=q.attachments.map((J)=>{let L=J;return{type:L.type,...L.path!==void 0?{path:L.path}:{},...L.url!==void 0?{url:L.url}:{},...L.content!==void 0?{content:L.content}:{},...L.mimeType!==void 0?{mimeType:L.mimeType}:{},...L.name!==void 0?{name:L.name}:{}}})}return{version:1,prompt:q.prompt,...typeof q.title==="string"?{title:q.title}:{},sourceProjectPath:K.resolve(q.sourceProjectPath),isolation:q.isolation,permissionMode:q.permissionMode,...typeof q.modelId==="string"?{modelId:q.modelId}:{},...x0(q.reasoningEffort)?{reasoningEffort:q.reasoningEffort}:{},...Q0(q.serviceTier)?{serviceTier:q.serviceTier}:{},...Z0(q.responseVerbosity)?{responseVerbosity:q.responseVerbosity}:{},...B0(q.communicationStyle)?{communicationStyle:q.communicationStyle}:{},...typeof q.communicationStyleDigest==="string"?{communicationStyleDigest:q.communicationStyleDigest}:{},...typeof q.projectInstructionsDigest==="string"?{projectInstructionsDigest:q.projectInstructionsDigest}:{},...T?{attachments:T}:{}}}function M0($){return typeof $==="string"&&Sq.has($)}function P$($){if(!$||typeof $!=="object"||Array.isArray($))return;let q=$;if(typeof q.sessionId!=="string"||!q.sessionId||typeof q.projectPath!=="string"||!K.isAbsolute(q.projectPath))return;return{sessionId:q.sessionId,projectPath:K.resolve(q.projectPath)}}var r$={stat($){return yq($,{bigint:!0})},readFile($){return s($,"utf-8")}},J0=r$;function L2($){J0=$}function J2(){J0=r$}class a$ 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 u extends Error{code="BLADE_SESSION_ARCHIVE_CONFLICT";constructor($){super($);this.name="SessionArchiveConflictError"}}function r0($,q){return`${$}\x00${q}`}function mq($){if($.kind==="base")return`/review base ${$.baseSha??$.label}`;if($.kind==="commit")return`/review commit ${$.commitSha??$.label}`;return"/review uncommitted"}function t$($){return typeof $==="string"&&$.length<=64&&Number.isFinite(Date.parse($))}function vq($){let q=new Map($.map((T)=>[r0(T.projectPath,T.sessionId),T]));return $.map((T)=>{let G=T,J=new Set;while(G){let H=r0(G.projectPath,G.sessionId);if(J.has(H))break;if(J.add(H),t$(G.archivedAt))return{...T,archivedAt:G.archivedAt,archivedBySessionId:G.sessionId};G=G.parentId?q.get(r0(G.projectPath,G.parentId)):void 0}let{archivedAt:L,archivedBySessionId:Z,...Q}=T;return Q})}function a0($,q){let T=vq($);if(q===null)return T;return T.filter((G)=>Boolean(G.archivedAt)===q)}class O{static toUISafeMessages($){let q=Date.now(),T=$.length,G=[];return $.forEach((J,L)=>{if(J.role!=="user"&&J.role!=="assistant")return;let Z;if(typeof J.content==="string")Z=J.content;else if(Array.isArray(J.content))Z=J.content.map((V)=>V.type==="text"?V.text:"[Image]").join("");else Z="";let Q=Z.trim();if(!Q)return;let H=_0(J.metadata),x=H?E$(H):Q,B=G[G.length-1];if(B&&B.role===J.role&&B.content===x)return;G.push({id:`restored-${q}-${L}`,role:J.role,content:x,timestamp:q-(T-L)*1000,metadata:J.metadata&&typeof J.metadata==="object"?J.metadata:void 0})}),G}static async listSessionPage($={}){let q=$$($),T=await this.listSessionPageFromProjection(q);if(T)return T;let J=(await this.scanStoredSessions(q.cwd??void 0,q.includeSubagents,q.cursor?5000:0,q.archived)).sort(q$),L=T$(J,q);return{sessions:L.sessions.map((Z)=>this.toPublicMetadata(Z)),nextCursor:L.nextCursor}}static async listSessionPageFromProjection($){let q=d$($);try{let T=await R0();if(!T)return null;await G$(T,this.projectionDeriver(),$.cursor?5000:0);let G=[],J=[];if($.cwd)G.push("s.project_path = ?"),J.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(`(
|
|
57
|
+
s.last_message_time < ?
|
|
58
|
+
OR (
|
|
59
|
+
s.last_message_time = ?
|
|
60
|
+
AND (
|
|
61
|
+
s.project_sort_key > ?
|
|
62
|
+
OR (s.project_sort_key = ? AND s.session_sort_key > ?)
|
|
63
|
+
)
|
|
64
|
+
)
|
|
65
|
+
)`);let H=e0(q.projectPath);J.push(q.lastMessageTime,q.lastMessageTime,H,H,e0(q.sessionId))}let Z=T.prepare(`WITH RECURSIVE archive_members(
|
|
66
|
+
project_path, session_id, archive_root_id, effective_archived_at, depth
|
|
67
|
+
) AS (
|
|
68
|
+
SELECT project_path, session_id, session_id, archived_at, 0
|
|
69
|
+
FROM sessions
|
|
70
|
+
WHERE archived_at IS NOT NULL
|
|
71
|
+
UNION ALL
|
|
72
|
+
SELECT child.project_path, child.session_id, parent.archive_root_id,
|
|
73
|
+
parent.effective_archived_at, parent.depth + 1
|
|
74
|
+
FROM sessions child
|
|
75
|
+
JOIN archive_members parent
|
|
76
|
+
ON child.project_path = parent.project_path
|
|
77
|
+
AND child.parent_id = parent.session_id
|
|
78
|
+
WHERE parent.depth < 128
|
|
79
|
+
),
|
|
80
|
+
ranked_archive AS (
|
|
81
|
+
SELECT project_path, session_id, archive_root_id,
|
|
82
|
+
effective_archived_at,
|
|
83
|
+
ROW_NUMBER() OVER (
|
|
84
|
+
PARTITION BY project_path, session_id
|
|
85
|
+
ORDER BY depth ASC, archive_root_id ASC
|
|
86
|
+
) AS rank
|
|
87
|
+
FROM archive_members
|
|
88
|
+
)
|
|
89
|
+
SELECT s.metadata_json, a.archive_root_id, a.effective_archived_at
|
|
90
|
+
FROM sessions s
|
|
91
|
+
LEFT JOIN ranked_archive a
|
|
92
|
+
ON a.project_path = s.project_path
|
|
93
|
+
AND a.session_id = s.session_id
|
|
94
|
+
AND a.rank = 1
|
|
95
|
+
${G.length>0?`WHERE ${G.join(" AND ")}`:""}
|
|
96
|
+
ORDER BY s.last_message_time DESC,
|
|
97
|
+
s.project_sort_key ASC,
|
|
98
|
+
s.session_sort_key ASC
|
|
99
|
+
LIMIT ?`).all(...J,$.limit+1).map((H)=>{let x=JSON.parse(H.metadata_json);if(H.archive_root_id&&H.effective_archived_at)return{...x,archivedAt:H.effective_archived_at,archivedBySessionId:H.archive_root_id};let{archivedAt:B,archivedBySessionId:V,...X}=x;return X}),Q=T$(Z,$);return{sessions:Q.sessions.map((H)=>this.toPublicMetadata(H)),nextCursor:Q.nextCursor}}catch{return null}}static async listSessions($={}){let q=$$($),T=await this.scanStoredSessions(q.cwd??void 0,q.includeSubagents,0,q.archived),G=new Set;return T.sort(q$).flatMap((J)=>{let L=`${J.projectPath}\x00${J.sessionId}`;if(G.has(L))return[];return G.add(L),[this.toPublicMetadata(J)]})}static async findSessionMetadata($,q){if(M($),q!==void 0){if(!K.isAbsolute(q))throw Error("Session catalog cwd must be absolute");let G=K.resolve(q),J=this.getSessionFilePath(G,$);try{let L=await this.readStoredSessionMetadata(J,$,G);if(L.projectPath!==G)return;if(!L.parentId||L.archivedAt)return this.toPublicMetadata(a0([L],null)[0]??L);let Z=await this.scanStoredSessions(G,!0,0,null);return this.toPublicMetadata(Z.find((Q)=>Q.sessionId===$)??L)}catch(L){if(L.code==="ENOENT")return;throw L}}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(!K.isAbsolute(q))throw Error("Session catalog cwd must be absolute");let G=K.resolve(q),J=this.getSessionFilePath(G,$);try{return await this.loadSessionFromFile(J,$,G)}catch(L){if(L.code==="ENOENT")throw Error(`未找到会话: ${$}`);throw L}}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 o0.error(`[SessionService] 加载会话失败 (${$}):`,T),T}}static async exportSessionMarkdown($,q,T={}){M($);let G=this.resolveCatalogWorkspace(q),J=m(G,$),L;try{L=await this.readStableSessionSnapshot(J,$)}catch(H){throw this.sanitizeStoredSessionError(H,$)}let Z=this.projectMetadataFromEntries(L,$,G,J);if(Z.projectPath!==G)throw Error(`Session export workspace mismatch: ${$}`);let Q=Z.archivedAt;if(!Q&&Z.parentId)Q=(await this.findArchivedAncestor(Z.parentId,G))?.archivedAt;return g$(L,{...Z,archivedAt:Q},T)}static async listRewindCheckpoints($,q){M($);let T=this.resolveCatalogWorkspace(q),G=m(T,$),J=await this.readStableSessionSnapshot(G,$);this.validateSessionWorkspace(J,$,T);let L=new O0({sessionId:$,workspaceRoot:T});await L.initialize();let Z=n$(J),Q=[];for(let H of Z){let x=s0(J,H.messageId),B=await L.previewRewind(x.snapshotMessageIds);Q.push({...H,fileCount:B.files.length})}return Q}static async rewindSession($,q,T){M($);let G=this.resolveCatalogWorkspace(q);await this.assertSessionWritable($,G);let J=m(G,$),L=new I(J),Z;try{await L.appendValidatedAsync(async(Q)=>{this.validateSessionWorkspace(Q,$,G);let H=s0(Q,T.targetMessageId),x=new O0({sessionId:$,workspaceRoot:G});await x.initialize();let B=await x.previewRewind(H.snapshotMessageIds),V=T.mode==="conversation"?await x.commitSnapshots(H.snapshotMessageIds):await x.rewindSnapshots(H.snapshotMessageIds),X=new Date().toISOString(),Y={id:j(),sessionId:$,timestamp:X,type:"session_rewound",cwd:G,gitBranch:l(G),version:c(),data:{rewindId:j(),targetMessageId:T.targetMessageId,mode:T.mode,restoredFiles:T.mode==="conversation"?[]:V.files,createdAt:X}},b=P([...Q,Y]);return Z={checkpoint:{...H.checkpoint,fileCount:B.files.length},mode:T.mode,removedTurns:H.removedTurns,restoredFiles:Y.data.restoredFiles,messages:this.convertJSONLToMessages(b)},Y})}catch(Q){throw this.sanitizeStoredSessionError(Q,$)}if(!Z)throw Error(`Session rewind did not produce a result: ${$}`);for(let Q of Z.restoredFiles)h.getInstance().clearFileRecord(Q);return Z}static async forkSession($,q){M($);let T=q.newSessionId??`fork-${Date.now()}-${j(8)}`;M(T);let G=this.resolveForkWorkspace(q.sourceProjectPath),J=this.resolveForkWorkspace(q.targetProjectPath);if(G!==J)throw Error("Session forks must stay in the source workspace");let L=m(G,$),Z=await this.readStableSessionSnapshot(L,$),Q=this.getSessionCreatedEntry(Z,$);if(Q.data.sessionId!==$)throw Error("Fork source session_created.data.sessionId must match the requested session ID");if(!K.isAbsolute(Q.cwd)||K.resolve(Q.cwd)!==G)throw Error("Fork source session_created.cwd must resolve to the requested source workspace");let H=this.projectMetadataFromEntries(Z,$,G,L);if(H.archivedAt)throw new e($,$);if(H.parentId){let _=await this.findArchivedAncestor(H.parentId,G);if(_)throw new e($,_.sessionId)}let x=P(Z),B=new Date().toISOString(),V=Q.data.rootId||$,X=l(J),Y=c(),{status:b,taskStatus:A,taskStatusReason:w,taskFailure:C,taskStartedAt:a,taskCompletedAt:t,taskOwnerPid:y,taskPromptSummary:S,taskDispatch:R,taskModelId:D,taskRetriedFrom:f,taskDelivery:U,taskIsolation:E,taskSourceProjectPath:f0,taskWorktree:Z$,taskDiffStat:Q$,taskQueuePosition:x$,taskQueueDepth:B$,taskConcurrencyLimit:H$,pendingInteraction:A0,...E0}=Q.data,b0={id:j(),sessionId:T,timestamp:B,type:"session_created",cwd:J,gitBranch:X,version:Y,data:{...E0,sessionId:T,rootId:V,parentId:$,relationType:"fork",taskStatus:"completed",taskCompletedAt:B,taskIsolation:"local",taskSourceProjectPath:J,createdAt:B,updatedAt:B}},w0=x.filter((_)=>_.type!=="session_created"&&_.type!=="inbox_acknowledged"&&_.type!=="interaction_requested"&&_.type!=="interaction_responded"&&_.type!=="interaction_recovered"&&_.type!=="review_started"&&_.type!=="review_completed").map((_)=>{let p={..._,id:j(),sessionId:T,cwd:J,gitBranch:X,version:Y};if(_.type==="session_updated"){let{status:V0,taskStatus:z,taskStatusReason:y0,taskFailure:Iq,taskStartedAt:uq,taskCompletedAt:Pq,taskOwnerPid:hq,taskPromptSummary:lq,taskDispatch:cq,taskModelId:pq,taskRetriedFrom:nq,taskDelivery:iq,taskIsolation:dq,taskSourceProjectPath:oq,taskWorktree:rq,taskDiffStat:aq,taskQueuePosition:tq,taskQueueDepth:sq,taskConcurrencyLimit:eq,pendingInteraction:$1,...s$}=_.data;return{...p,type:"session_updated",data:{...s$,sessionId:T,rootId:V,parentId:$,relationType:"fork"}}}if(_.type==="message_created"){let{inboxMessageId:V0,...z}=_.data;return{...p,type:"message_created",data:z}}return p}),k0={id:j(),sessionId:T,timestamp:B,type:"session_updated",cwd:J,gitBranch:X,version:Y,data:{sessionId:T,rootId:V,parentId:$,relationType:"fork",taskStatus:"completed",taskStatusReason:null,taskFailure:null,taskStartedAt:null,taskCompletedAt:B,taskOwnerPid:null,taskIsolation:"local",taskSourceProjectPath:J,taskWorktree:null,taskDiffStat:null,taskDelivery:null,taskQueuePosition:null,taskQueueDepth:null,taskConcurrencyLimit:null,updatedAt:B}},$0=[b0,...w0,k0],H0=m(J,T);try{await new I(H0).createExclusive($0)}catch(_){if(_.code==="EEXIST")throw Error(`Fork session already exists: ${T}`,{cause:_});throw _}let g0=this.projectMetadataFromEntries($0,T,J,H0);return{sessionId:T,parentSessionId:$,projectPath:J,messages:this.convertJSONLToMessages($0),metadata:this.toPublicMetadata(g0)}}static async deleteSession($,q){if(M($),q){if(!K.isAbsolute(q))throw Error("Session catalog cwd must be absolute");let G=K.resolve(q),J=this.getSessionFilePath(G,$),L=new I(J),Z;try{Z=await L.deleteValidated((Q)=>{return this.projectMetadataFromEntries(Q,$,G,J).projectPath===G})}catch(Q){if(!this.isCorruptSessionJSONLError(Q))throw Q;Z=await L.delete()}if(!Z)return 0;return await D0(K.join(K.dirname(J),`${$}.inbox.json`),{force:!0}),await D0(t0(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 I(G.filePath).delete(),await D0(K.join(K.dirname(G.filePath),`${G.sessionId}.inbox.json`),{force:!0}),await D0(t0(G.projectPath,G.sessionId),{force:!0}),await this.removeFromProjection(G.sessionId,G.projectPath)})),T.length}static async removeFromProjection($,q){try{let T=await R0();if(T)o$(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&&!I0($.taskFailure))throw Error("Invalid session task failure");if($.taskDispatch!==void 0&&$.taskDispatch!==null&&!u$($.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&&!M0($.permissionMode))throw Error("Invalid session permission mode");if($.reasoningEffort!==void 0&&$.reasoningEffort!==null&&!x0($.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&&!B0($.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&&!P$($.taskRetriedFrom))throw Error("Invalid session task retry source");if($.taskDelivery!==void 0&&$.taskDelivery!==null&&!v$($.taskDelivery))throw Error("Invalid session task delivery");if($.taskIsolation!==void 0&&$.taskIsolation!==null&&!L$.has($.taskIsolation))throw Error(`Invalid session task isolation: ${String($.taskIsolation)}`);if($.taskSourceProjectPath!==void 0&&$.taskSourceProjectPath!==null&&!K.isAbsolute($.taskSourceProjectPath))throw Error("Session task source project path must be absolute");if($.taskWorktree!==void 0&&$.taskWorktree!==null){let T=m$($.taskWorktree);if(!T||T.sessionId!==q||![T.repositoryRoot,T.originalWorkspaceRoot,T.worktreeRoot,T.workspaceRoot].every((G)=>K.isAbsolute(G)))throw Error("Invalid session task worktree metadata")}if($.taskDiffStat!==void 0&&$.taskDiffStat!==null&&!I$($.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={}){M($),O.validateTaskMetadataUpdate(T,$);let G=O.resolveCatalogWorkspace(q);if(T.taskWorktree&&K.resolve(T.taskWorktree.workspaceRoot)!==G)throw Error("Session task worktree must match the catalog workspace");let J=new Date().toISOString(),L={id:j(),sessionId:$,timestamp:J,type:"session_created",cwd:G,gitBranch:l(G),version:c(),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:J,updatedAt:J}},Z=O.getSessionFilePath(G,$);return await new I(Z).createExclusive([L]),O.toPublicMetadata(O.projectMetadataFromEntries([L],$,G,Z))}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),M(G);let J=m(q,G),L;try{L=await s(J,"utf8")}catch(Q){if(Q.code==="ENOENT")return;throw Q}let Z=this.projectMetadataFromEntries(this.parseStoredSession(L,G),G,q,J);if(Z.projectPath!==q)throw Error("Session lineage escapes the requested workspace");if(Z.archivedAt)return{sessionId:Z.sessionId,archivedAt:Z.archivedAt};G=Z.parentId}return}static async listSessionArchiveMembers($,q){M($);let T=this.resolveCatalogWorkspace(q),G=await this.scanStoredSessions(T,!0,0,null);if(!G.some((Z)=>Z.sessionId===$))throw Error(`Session not found: ${$}`);let J=new Set([$]),L=!0;while(L){L=!1;for(let Z of G)if(Z.parentId&&J.has(Z.parentId)&&!J.has(Z.sessionId))J.add(Z.sessionId),L=!0}return G.filter((Z)=>J.has(Z.sessionId)).sort((Z,Q)=>Z.sessionId.localeCompare(Q.sessionId)).map((Z)=>this.toPublicMetadata(Z))}static async archiveSession($,q){M($);let T=this.resolveCatalogWorkspace(q),G=await this.findSessionMetadata($,T);if(!G)throw Error(`Session not found: ${$}`);if(G.archivedAt)return G;let J=await this.listSessionArchiveMembers($,T),L=J.find((Q)=>Q.taskStatus==="queued"||Q.taskStatus==="running");if(L)throw new u(`Stop session ${L.sessionId} before archiving this session tree`);let Z=[];try{for(let B of J)Z.push(await i.acquire(B.sessionId,T));let Q=m(T,$),H=new I(Q),x=[];return await H.appendValidated((B)=>{let V=this.projectMetadataFromEntries(B,$,T,Q);if(V.archivedAt)throw new u(`Session archive state changed concurrently: ${$}`);if(V.taskStatus==="queued"||V.taskStatus==="running")throw new u(`Stop session ${$} before archiving it`);let X=new Date().toISOString(),Y={id:j(),sessionId:$,timestamp:X,type:"session_updated",cwd:T,gitBranch:l(T),version:c(),data:{sessionId:$,archivedAt:X,updatedAt:X}};return x=[...B,Y],Y}),this.toPublicMetadata({...this.projectMetadataFromEntries(x,$,T,Q),archivedBySessionId:$})}catch(Q){if(Q instanceof u)throw Q;if(Q instanceof n)throw new u(Q.message);throw this.sanitizeStoredSessionError(Q,$)}finally{for(let Q of Z.reverse())await Q.release()}}static async unarchiveSession($,q){M($);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 u(`Unarchive ancestor ${G.archivedBySessionId} to restore session ${$}`);let J;try{J=await i.acquire($,T);let L=m(T,$),Z=new I(L),Q=[];return await Z.appendValidated((H)=>{if(!this.projectMetadataFromEntries(H,$,T,L).archivedAt)throw new u(`Session archive state changed concurrently: ${$}`);let B=new Date().toISOString(),V={id:j(),sessionId:$,timestamp:B,type:"session_updated",cwd:T,gitBranch:l(T),version:c(),data:{sessionId:$,archivedAt:null,updatedAt:B}};return Q=[...H,V],V}),this.toPublicMetadata(this.projectMetadataFromEntries(Q,$,T,L))}catch(L){if(L instanceof u)throw L;if(L instanceof n)throw new u(L.message);throw this.sanitizeStoredSessionError(L,$)}finally{await J?.release()}}static async updateSessionMetadata($,q,T){if(M($),O.validateTaskMetadataUpdate(T,$),T.taskStatus!==void 0&&!S$.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=O.resolveCatalogWorkspace(q);if(T.taskWorktree&&K.resolve(T.taskWorktree.workspaceRoot)!==G)throw Error("Session task worktree must match the catalog workspace");let J=O.getSessionFilePath(G,$),L=new I(J),Z=[];try{await L.appendValidatedAsync(async(Q)=>{let H=O.getSessionCreatedEntry(Q,$);if(H.data.sessionId!==$)throw Error(`Session metadata creation record sessionId mismatch: ${$}`);if(!K.isAbsolute(H.cwd)||K.resolve(H.cwd)!==G)throw Error(`Session metadata creation record cwd mismatch: ${$}`);let x=O.projectMetadataFromEntries(Q,$,G,J);if(x.archivedAt)throw new e($,$);if(x.parentId){let X=await O.findArchivedAncestor(x.parentId,G);if(X)throw new e($,X.sessionId)}let B=new Date().toISOString(),V={id:j(),sessionId:$,timestamp:B,type:"session_updated",cwd:G,gitBranch:l(G),version:c(),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 Z=[...Q,V],V})}catch(Q){throw O.sanitizeStoredSessionError(Q,$)}return O.toPublicMetadata(O.projectMetadataFromEntries(Z,$,G,J))}static async setSessionPermissionMode($,q,T){if(M($),!M0(T))throw Error("Invalid session permission mode");let G=O.resolveCatalogWorkspace(q),J=await O.findSessionMetadata($,G);if(J?.permissionMode===T)return J;if(J)return O.updateSessionMetadata($,G,{permissionMode:T});try{return await O.createSessionMetadata($,G,{taskStatus:"completed",permissionMode:T})}catch(L){if(L.code!=="EEXIST")throw L;return O.updateSessionMetadata($,G,{permissionMode:T})}}static async findSessionTaskWorktree($,q){M($);let T=O.resolveCatalogWorkspace(q),G=O.getSessionFilePath(T,$);try{return(await O.readStoredSessionMetadata(G,$,T)).taskWorktree}catch(J){if(J.code==="ENOENT")return;throw O.sanitizeStoredSessionError(J,$)}}static async findSessionTaskDispatch($,q){M($);let T=O.resolveCatalogWorkspace(q),G=O.getSessionFilePath(T,$);try{return(await O.readStoredSessionMetadata(G,$,T)).taskDispatch}catch(J){if(J.code==="ENOENT")return;throw O.sanitizeStoredSessionError(J,$)}}static async loadSessionFromFile($,q,T){let G=await s($,"utf-8"),J=this.parseStoredSession(G,q);if(T!==void 0){if(this.projectMetadataFromEntries(J,q,T,$).projectPath!==T)throw Error(`未找到会话: ${q}`)}return this.convertJSONLToMessages(J)}static convertJSONLToMessages($){let q=[],T=new Map,G=new Map,J=new Map,L=new Map,Z=new Map,Q=P($),H=new Set;for(let x of Q){if(x.type==="message_created"){let B=x.data.metadata&&typeof x.data.metadata==="object"&&!Array.isArray(x.data.metadata)?x.data.metadata:void 0,V=B?.codeReview&&typeof B.codeReview==="object"&&!Array.isArray(B.codeReview)?B.codeReview:void 0;if(V?.phase==="completed"&&typeof V.reviewId==="string")H.add(V.reviewId);let X=x.data.role==="assistant"&&x.data.parentMessageId?J.get(x.data.parentMessageId):void 0,Y=X??{role:x.data.role,content:"",...x.data.metadata||x.data.inboxMessageId?{metadata:{...x.data.metadata&&typeof x.data.metadata==="object"&&!Array.isArray(x.data.metadata)?x.data.metadata:{},...x.data.inboxMessageId?{inboxMessageId:x.data.inboxMessageId}:{}}}:{}};if(T.set(x.data.messageId,Y),G.set(x.data.messageId,[]),!X)q.push(Y)}if(x.type==="part_created"){if(x.data.partType==="reasoning"){let B=T.get(x.data.messageId);if(B){let V=x.data.payload;B.reasoningContent=(B.reasoningContent??"")+(V.text??"")}}if(x.data.partType==="text"){let B=T.get(x.data.messageId);if(B){let V=x.data.payload,X=G.get(x.data.messageId);if(X)X.push({type:"text",text:V.text??""}),B.content=h$(X);else B.content=V.text??""}}if(x.data.partType==="image"){let B=T.get(x.data.messageId);if(B){let V=x.data.payload,X=G.get(x.data.messageId);if(X&&V.dataUrl)X.push({type:"image_url",image_url:{url:V.dataUrl}}),B.content=h$(X)}}if(x.data.partType==="tool_call"){let B=T.get(x.data.messageId);if(B?.role!=="assistant"){if(B=J.get(x.data.messageId),!B)B={role:"assistant",content:"",tool_calls:[]},J.set(x.data.messageId,B),q.push(B)}if(B.role==="assistant"){let V=x.data.payload,X=V.toolCallId??x.data.partId;L.set(x.data.partId,X),Z.set(X,B),B.tool_calls??=[],B.tool_calls.push({id:X,type:"function",function:{name:V.toolName??"unknown",arguments:JSON.stringify(V.input??{})}})}}if(x.data.partType==="tool_result"){let B=x.data.payload,V=typeof B.error==="string"?`Error: ${B.error}`:typeof B.output==="string"?B.output:JSON.stringify(B.output??""),X=B;q.push({role:"tool",content:V,tool_call_id:L.get(x.data.messageId)??B.toolCallId,name:B.toolName,metadata:X})}if(x.data.partType==="summary"){let B=x.data.payload,V=x.data.payload;q.push({role:"system",content:B.text??"",metadata:V})}if(x.data.partType==="subtask_ref"){let B=T.get(x.data.messageId)??Z.get(x.data.messageId);if(B){let V=x.data.payload,X=B.metadata??{};B.metadata={...X,subtaskRef:V}}}}}for(let x of N0(Q)){if(x.completion===void 0||H.has(x.start.reviewId))continue;q.push({role:"assistant",content:O$(x.start,x.completion),metadata:{codeReview:{...W$(x.start,x.completion),synthetic:!0}}})}return q}static projectionDeriver(){return($,q,T)=>{try{let G=m(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 J=await R0();if(!J)return null;await G$(J,this.projectionDeriver(),T);let L=$?J.prepare("SELECT metadata_json, is_subagent FROM sessions WHERE project_path=?").all($):J.prepare("SELECT metadata_json, is_subagent FROM sessions").all(),Z=[];for(let Q of L){if(!q&&Q.is_subagent===1)continue;try{let H=JSON.parse(Q.metadata_json);if($!==void 0&&H.projectPath!==$)continue;Z.push(H)}catch{}}return a0(Z,G)}catch{return null}}static async scanStoredSessions($,q=!1,T=0,G=!1){let J=$?K.resolve($):void 0,L=await this.scanStoredSessionsFromProjection(J,q,T,G);if(L)return L;let Z=J?[{storagePath:K0(J),projectPath:J}]:await this.listAllProjectStorageDirectories(),Q=[];for(let H of Z){let x;try{x=await y$(H.storagePath)}catch(B){if(B.code==="ENOENT")continue;throw B}for(let B of x){if(!B.endsWith(".jsonl"))continue;let V=B.slice(0,-6),X=K.join(H.storagePath,B);try{let Y=await this.readStoredSessionMetadata(X,V,H.projectPath);if(J!==void 0&&Y.projectPath!==J){o0.warn(`[SessionService] Skipping out-of-scope session transcript: ${V}`);continue}if(!q&&Y.relationType==="subagent")continue;Q.push(Y)}catch(Y){let b=Y.code;if(b==="ENOENT")continue;if(b)throw Y;o0.warn(`[SessionService] Skipping invalid session transcript: ${V}`)}}}return a0(Q,G)}static async listAllProjectStorageDirectories(){let $=K.join(L0(),"projects"),q;try{q=await y$($,{withFileTypes:!0,encoding:"utf8"})}catch(T){if(T.code==="ENOENT")return[];throw T}return q.filter((T)=>T.isDirectory()).map((T)=>({storagePath:K.join($,T.name),projectPath:l$(T.name)}))}static async readStoredSessionMetadata($,q,T){let G=await s($,"utf-8"),J=this.parseStoredSession(G,q);return this.reconcileInterruptedTask(this.projectMetadataFromEntries(J,q,T,$))}static async reconcileInterruptedTask($){let q=$.taskOwnerPid;if($.taskStatus!=="running"||q===void 0||j$(q))return $;let T;try{T=await i.acquire($.sessionId,$.projectPath)}catch(L){if(!(L instanceof n))throw L;let Z=await s($.filePath,"utf-8");return this.projectMetadataFromEntries(this.parseStoredSession(Z,$.sessionId),$.sessionId,$.projectPath,$.filePath)}let G=new I($.filePath),J;try{try{await G.appendValidated((L)=>{let Z=this.projectMetadataFromEntries(L,$.sessionId,$.projectPath,$.filePath);if(Z.taskStatus!=="running"||Z.taskOwnerPid!==q||j$(q))throw new J$;let Q=new Date().toISOString(),H={id:j(),sessionId:$.sessionId,timestamp:Q,type:"session_updated",cwd:$.projectPath,gitBranch:l($.projectPath),version:c(),data:{sessionId:$.sessionId,taskStatus:"interrupted",taskStatusReason:"Task owner process exited before completion",taskCompletedAt:Q,taskOwnerPid:null,taskQueuePosition:null,taskQueueDepth:null,updatedAt:Q}};return J=[...L,H],H})}catch(L){if(!(L instanceof J$))throw L}if(!J){let L=await s($.filePath,"utf-8");J=this.parseStoredSession(L,$.sessionId)}return this.projectMetadataFromEntries(J,$.sessionId,$.projectPath,$.filePath)}finally{await T.release()}}static projectMetadataFromEntries($,q,T,G){if($.length===0)throw Error(`Empty session transcript: ${q}`);let J=this.getSessionCreatedEntry($,q),L=$.reduce((z,y0)=>y0.type==="session_updated"?{...z,...y0.data}:z,{...J.data}),Z=P($),Q=F$(U$(Z)),x=N0(Z).at(-1),B=Z.findLastIndex((z)=>z.type==="review_started"&&z.data.reviewId===x?.start.reviewId||z.type==="review_completed"&&z.data.reviewId===x?.start.reviewId),V=Z.findLastIndex((z)=>(z.type==="session_created"||z.type==="session_updated")&&Object.hasOwn(z.data,"taskStatus")),X=x!==void 0&&B>V,Y=X?x.completion===void 0?"running":x.completion.status==="completed"||x.completion.status==="stale"?"completed":x.completion.status==="aborted"?"cancelled":x.completion.status==="interrupted"?"interrupted":"failed":void 0,b=Z.filter((z)=>z.type==="message_created"&&["user","assistant"].includes(z.data.role)).length,A=Z.some((z)=>z.type==="part_created"&&z.data.partType==="tool_result"&&typeof z.data.payload.error==="string"),w=S$.has(L.taskStatus)?L.taskStatus:void 0,C=Y??w??(A?"failed":"completed"),a=typeof L.taskOwnerPid==="number"&&Number.isInteger(L.taskOwnerPid)&&L.taskOwnerPid>0?L.taskOwnerPid:void 0,t=L$.has(L.taskIsolation)?L.taskIsolation:void 0,y=typeof L.taskSourceProjectPath==="string"&&K.isAbsolute(L.taskSourceProjectPath)?K.resolve(L.taskSourceProjectPath):void 0,S=J.cwd;if(S!==void 0&&!K.isAbsolute(S))throw Error(`Session catalog cwd must be absolute: ${q}`);let R=S===void 0?T:K.resolve(S),D=m$(L.taskWorktree),f=D?.sessionId===q&&K.resolve(D.workspaceRoot)===R?D:void 0,U=I$(L.taskDiffStat),E=u$(L.taskDispatch),f0=typeof L.taskModelId==="string"&&L.taskModelId.trim()?L.taskModelId:E?.modelId,Z$=typeof L.selectedModelId==="string"&&L.selectedModelId.trim()?L.selectedModelId:f0,Q$=M0(L.permissionMode)?L.permissionMode:E?.permissionMode,x$=x0(L.reasoningEffort)?L.reasoningEffort:E?.reasoningEffort,B$=Q0(L.serviceTier)?L.serviceTier:E?.serviceTier,H$=Z0(L.responseVerbosity)?L.responseVerbosity:E?.responseVerbosity,A0=B0(L.communicationStyle)?L.communicationStyle:E?.communicationStyle,E0=Object.hasOwn(L,"communicationStyleDigest")?typeof L.communicationStyleDigest==="string"&&/^[a-f0-9]{64}$/.test(L.communicationStyleDigest)?L.communicationStyleDigest:void 0:A0===E?.communicationStyle?E?.communicationStyleDigest:void 0,b0=Object.hasOwn(L,"projectInstructionsDigest")?typeof L.projectInstructionsDigest==="string"&&/^[a-f0-9]{64}$/.test(L.projectInstructionsDigest)?L.projectInstructionsDigest:void 0:E?.projectInstructionsDigest,w0=t$(L.archivedAt)?L.archivedAt:void 0,k0=P$(L.taskRetriedFrom),$0=v$(L.taskDelivery),H0=typeof L.taskQueuePosition==="number"&&Number.isInteger(L.taskQueuePosition)&&L.taskQueuePosition>0?L.taskQueuePosition:void 0,g0=typeof L.taskQueueDepth==="number"&&Number.isInteger(L.taskQueueDepth)&&L.taskQueueDepth>=0?L.taskQueueDepth:void 0,_=typeof L.taskConcurrencyLimit==="number"&&Number.isInteger(L.taskConcurrencyLimit)&&L.taskConcurrencyLimit>0?L.taskConcurrencyLimit:void 0,p=X?x?.completion?x.completion.status==="completed"?void 0:`Code review ${j0(x.completion.status)}`:`Reviewing ${x?.start.target.label??"changes"}`:void 0,V0=X?C==="failed"&&p?v0(p):void 0:I0(L.taskFailure)?L.taskFailure:C==="failed"&&typeof L.taskStatusReason==="string"?v0(L.taskStatusReason):void 0;return{sessionId:q,projectPath:R,gitBranch:J.gitBranch,rootId:L.rootId||q,parentId:L.parentId,relationType:L.relationType,resumedFrom:L.resumedFrom,rootAgentId:L.rootAgentId,resumeDepth:L.resumeDepth,title:L.title,agentType:L.agentType,model:L.model,selectedModelId:Z$,permissionMode:Q$,reasoningEffort:x$,serviceTier:B$,responseVerbosity:H$,communicationStyle:A0,communicationStyleDigest:E0,projectInstructionsDigest:b0,pendingInteraction:Q,taskStatus:C,taskStatusReason:V0?.message??p??(typeof L.taskStatusReason==="string"?L.taskStatusReason:void 0),taskFailure:V0,taskStartedAt:X?x?.start.startedAt:typeof L.taskStartedAt==="string"?L.taskStartedAt:void 0,taskCompletedAt:X?x?.completion?.completedAt:typeof L.taskCompletedAt==="string"?L.taskCompletedAt:void 0,taskPromptSummary:X?x?mq(x.start.target):"/review uncommitted":typeof L.taskPromptSummary==="string"?L.taskPromptSummary:void 0,taskModelId:f0,taskRetryAvailable:E!==void 0,taskRetriedFrom:k0,taskDelivery:$0,taskIsolation:t,taskSourceProjectPath:y,taskWorktreePath:f?.worktreeRoot,taskWorktreeBranch:f?.branch,taskBaseCommit:f?.baseCommit,taskDiffStat:U,taskQueuePosition:H0,taskQueueDepth:g0,taskConcurrencyLimit:_,archivedAt:w0,taskOwnerPid:X?void 0:a,taskWorktree:f,taskDispatch:E,messageCount:b,firstMessageTime:$[0].timestamp,lastMessageTime:$.at(-1).timestamp,hasErrors:A||C==="failed",filePath:G}}static toPublicMetadata($){let{filePath:q,taskOwnerPid:T,taskWorktree:G,taskDispatch:J,...L}=$;return L}static getSessionFilePath($,q){return m($,q)}static getSessionCreatedEntry($,q){let T=$.find((G)=>G.type==="session_created");if(!T)throw new a$(q);return T}static resolveCatalogWorkspace($){if(!K.isAbsolute($))throw Error("Session catalog cwd must be absolute");return K.resolve($)}static validateSessionWorkspace($,q,T){let G=this.getSessionCreatedEntry($,q);if(G.data.sessionId!==q)throw Error(`Session creation record sessionId mismatch: ${q}`);if(!K.isAbsolute(G.cwd)||K.resolve(G.cwd)!==T)throw Error(`Session creation record cwd mismatch: ${q}`)}static resolveForkWorkspace($){if(!K.isAbsolute($))throw Error("Fork workspace paths must be absolute");return K.resolve($)}static parseStoredSession($,q){return i$($,`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 J=await J0.stat($),L=await J0.readFile($),Z=this.parseStoredSession(L,q),Q=await J0.stat($);if(J.size===Q.size&&J.mtimeNs===Q.mtimeNs&&J.dev===Q.dev&&J.ino===Q.ino)return Z}throw Error("Session changed while creating fork; retry the operation")}}function h$($){if($.length===1&&$[0]?.type==="text")return $[0].text;return[...$]}
|
|
100
|
+
export{u0 as cb,n as db,i as eb,U$ as fb,Z1 as gb,N0 as hb,x1 as ib,j0 as jb,O$ as kb,W$ as lb,v0 as mb,h as nb,O0 as ob,h0 as pb,l0 as qb,A1 as rb,E1 as sb,E$ as tb,_0 as ub,S1 as vb,L2 as wb,J2 as xb,a$ as yb,e as zb,u as Ab,O as Bb};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{Mb as a,Nb as b,Ob as c,Pb as d,Qb as e,Rb as f,Sb as g,Tb as h}from"./chunk-wrbm6rch.js";import"./chunk-w01sec4f.js";import"./chunk-ahxc3n3g.js";import"./chunk-847e0sk9.js";export{d as syncSession,e as syncAll,h as searchProjectionText,c as resetProjectionDbCache,f as removeSessionFromProjection,g as rebuildProjectionIndex,b as getProjectionDb,a as getIndexDbPath};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{
|
|
2
|
-
export{m as
|
|
1
|
+
import{B as o}from"./chunk-pt659n0v.js";import{Bb as i}from"./chunk-5ak9tw83.js";import a from"node:path";function n(e){let s=e.replace(/\s+/g," ").trim();return s.length<=72?s:`${s.slice(0,69)}...`}function c(e){let s=e.replace(/\s+/g," ").trim();return s.length<=500?s:`${s.slice(0,497)}...`}function d(e){return`task/${e.replace(/[^a-zA-Z0-9_-]/g,"-").slice(0,40)}`}class m{static async createSessionTask(e){if(!e.prompt.trim())throw Error("Task prompt must not be blank");if(!a.isAbsolute(e.sourceProjectPath))throw Error("Task source project path must be absolute");let s=a.resolve(e.sourceProjectPath),t;try{return t=e.isolation==="worktree"?await o.enter({sessionId:e.sessionId,workspaceRoot:s,name:d(e.sessionId)}):void 0,{metadata:await i.createSessionMetadata(e.sessionId,t?.workspaceRoot??s,{title:e.title?.trim()||n(e.prompt),taskPromptSummary:c(e.prompt),taskDispatch:e.dispatch,taskModelId:e.dispatch?.modelId,selectedModelId:e.dispatch?.modelId,permissionMode:e.dispatch?.permissionMode,reasoningEffort:e.dispatch?.reasoningEffort,serviceTier:e.dispatch?.serviceTier,responseVerbosity:e.dispatch?.responseVerbosity,communicationStyle:e.dispatch?.communicationStyle,communicationStyleDigest:e.dispatch?.communicationStyleDigest,projectInstructionsDigest:e.dispatch?.projectInstructionsDigest,taskRetriedFrom:e.retriedFrom,taskIsolation:e.isolation,taskSourceProjectPath:s,taskWorktree:t}),taskWorktree:t}}catch(r){if(t)await o.exit({sessionId:e.sessionId,action:"remove",discardChanges:!0}).catch(()=>{return});throw r}}}
|
|
2
|
+
export{m as r};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{h as o}from"./chunk-
|
|
1
|
+
import{h as o}from"./chunk-mt4328yf.js";import"./chunk-847e0sk9.js";import{execSync as r}from"child_process";var l={command:"update",describe:"Check for updates and install if available",handler:async()=>{console.log("Checking for updates...");try{let e=await o(!0);if(console.log(`Current version: ${e.currentVersion}`),e.error){console.log(`Warning: ${e.error}`);return}if(e.latestVersion)console.log(`Latest version: ${e.latestVersion}`);if(e.hasUpdate&&e.latestVersion){console.log(""),console.log(`\x1B[33mUpdate available: ${e.currentVersion} -> ${e.latestVersion}\x1B[0m`),console.log(""),console.log("Updating...");try{r("npm install -g blade-code@latest --registry https://registry.npmjs.org",{stdio:"inherit"}),console.log(""),console.log("Update complete!")}catch(t){console.error("Error: Update failed. Please run manually:"),console.error(" npm install -g blade-code@latest"),process.exit(1)}}else console.log("You are running the latest version of Blade")}catch(e){console.error(`Error: Failed to check for updates: ${e instanceof Error?e.message:"未知错误"}`),process.exit(1)}}};export{l as updateCommands};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{Ac as l,Bc as m,Cc as n,Dc as o,Ec as p,Fc as q,pc as a,qc as b,rc as c,sc as d,tc as e,uc as f,vc as g,wc as h,xc as i,yc as j,zc as k}from"./chunk-x3780wpy.js";import"./chunk-tp9zk241.js";import"./chunk-3fdyzgpv.js";import"./chunk-w01sec4f.js";import"./chunk-vcq624qv.js";import"./chunk-akev4wsz.js";import"./chunk-rk1w5pry.js";import"./chunk-az4b6106.js";import"./chunk-m86ekqp0.js";import"./chunk-p0j8994h.js";import"./chunk-g1q27q6q.js";import"./chunk-0n04bmta.js";import"./chunk-1v7hpr34.js";import"./chunk-ahxc3n3g.js";import"./chunk-847e0sk9.js";export{a as vanillaStore,c as sessionActions,l as getThinkingModeEnabled,b as getState,n as getServiceTier,o as getResponseVerbosity,m as getReasoningEffort,j as getModelById,e as getMessages,k as getMcpServers,i as getCurrentModel,f as getConfig,p as getCommunicationStyle,h as getAllModels,g as ensureStoreInitialized,q as configActions,d as appActions};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import{createRequire as a}from"node:module";var c=a(import.meta.url);
|
|
2
|
-
export{c as
|
|
2
|
+
export{c as if};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a as y,b as A,c as C,d as D}from"./chunk-a3e97syg.js";import"./chunk-zjf1z27e.js";import"./chunk-43j2f1b5.js";import"./chunk-kqpwz9b7.js";import"./chunk-7a200q5g.js";import"./chunk-pt659n0v.js";import"./chunk-rn908m3v.js";import"./chunk-f7854pbx.js";import"./chunk-jpy61wna.js";import"./chunk-5ak9tw83.js";import"./chunk-wrbm6rch.js";import"./chunk-0xm8hn2h.js";import{vc as q}from"./chunk-x3780wpy.js";import"./chunk-tp9zk241.js";import"./chunk-3fdyzgpv.js";import"./chunk-rz2ftt6h.js";import"./chunk-qqwgb9ja.js";import"./chunk-1sw9z975.js";import"./chunk-y573s5r8.js";import"./chunk-qycwavck.js";import"./chunk-0z7q89w7.js";import"./chunk-ne7zdjrh.js";import"./chunk-e9ckf8e7.js";import"./chunk-yyvx1avz.js";import"./chunk-tc83e1b0.js";import"./chunk-w01sec4f.js";import"./chunk-vcq624qv.js";import"./chunk-akev4wsz.js";import"./chunk-rk1w5pry.js";import"./chunk-az4b6106.js";import"./chunk-m86ekqp0.js";import"./chunk-p0j8994h.js";import"./chunk-g1q27q6q.js";import"./chunk-0n04bmta.js";import"./chunk-1v7hpr34.js";import"./chunk-ahxc3n3g.js";import"./chunk-847e0sk9.js";import H from"chalk";var R={command:"serve",describe:"Start a headless Blade server (no browser)",builder:y,handler:async(E)=>{let f=A(E);if(await q(),!process.env.BLADE_SERVER_PASSWORD)console.log(H.yellow("Warning: BLADE_SERVER_PASSWORD is not set; server is unsecured."));let b=await D.listenAsync(f);if(console.log(`Blade server listening on http://${b.hostname}:${b.port}`),f.hostname==="0.0.0.0"){let F=C();for(let G of F)console.log(` Network: http://${G}:${b.port}`)}await new Promise(()=>{}),await b.stop()}};export{R as serveCommand};
|