blade-code 0.10.41 → 0.10.42
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-t80e2bms.js → chunk-020hgyg7.js} +1 -1
- package/dist/{chunk-fxw1q5j5.js → chunk-0jsy9eav.js} +1 -1
- package/dist/{chunk-5sbewyjn.js → chunk-0qf7h4n2.js} +2 -2
- package/dist/{chunk-b5b8fb9y.js → chunk-18wnstzp.js} +1 -1
- package/dist/chunk-1e9866ye.js +5 -0
- package/dist/{chunk-q87nwpsb.js → chunk-1whfdz08.js} +1 -1
- package/dist/{chunk-bdxaz350.js → chunk-1yjzj2d0.js} +2 -2
- package/dist/{chunk-y30kw6gj.js → chunk-3v2sgvzt.js} +2 -2
- package/dist/{chunk-eg5sz4bw.js → chunk-3xx2ebr7.js} +1 -1
- package/dist/{chunk-nhzdkxnx.js → chunk-4k37vmxh.js} +1 -1
- package/dist/{chunk-xs7w13na.js → chunk-4rmdfme3.js} +1 -1
- package/dist/chunk-5hbm5e24.js +44 -0
- package/dist/{chunk-gbbnjzy8.js → chunk-5zr3w30g.js} +1 -1
- package/dist/{chunk-ens8nsge.js → chunk-6d0hphtd.js} +1 -1
- package/dist/chunk-74sxsd1h.js +1 -0
- package/dist/chunk-78jy2kby.js +1 -0
- package/dist/{chunk-djr17h80.js → chunk-7gjb405q.js} +1 -1
- package/dist/{chunk-atsw605q.js → chunk-7pmpm5yq.js} +1 -1
- package/dist/chunk-7qd6xqjs.js +1 -0
- package/dist/{chunk-adgx9vd7.js → chunk-8b2bpfnt.js} +3 -3
- package/dist/{chunk-6dma8han.js → chunk-8csfb83y.js} +2 -2
- package/dist/chunk-8wg7g98v.js +10 -0
- package/dist/{chunk-5zf8204m.js → chunk-anwm8rp3.js} +1 -1
- package/dist/{chunk-yxwargqc.js → chunk-brwdd5kp.js} +1 -1
- package/dist/chunk-c53hc8ze.js +1 -0
- package/dist/{chunk-yhw0pvyt.js → chunk-d2fce0vk.js} +2 -2
- package/dist/chunk-dgs04r04.js +2 -0
- package/dist/{chunk-dp9xzsja.js → chunk-dr4et3gj.js} +1 -1
- package/dist/{chunk-qgez5vw6.js → chunk-dx7xefys.js} +1 -1
- package/dist/{chunk-5ygv33qe.js → chunk-ecw74d2s.js} +2 -2
- package/dist/{chunk-w07gb3h0.js → chunk-ex21hxqf.js} +1 -1
- package/dist/{chunk-tsskar00.js → chunk-f542fh7g.js} +1 -1
- package/dist/{chunk-0hqsdbkr.js → chunk-f90ybvrs.js} +1 -1
- package/dist/{chunk-2bm55evt.js → chunk-fye8eghq.js} +2 -2
- package/dist/chunk-h9fkttf1.js +2 -0
- package/dist/chunk-hkmgrdxc.js +1 -0
- package/dist/{chunk-01jt0mpr.js → chunk-hypq4t4z.js} +1 -1
- package/dist/{chunk-8xfzbv9v.js → chunk-jf6mkx0j.js} +1 -1
- package/dist/{chunk-g9re8v25.js → chunk-jv9zg1fw.js} +1 -1
- package/dist/{chunk-wvc6bx0t.js → chunk-jz2gkqdt.js} +2 -2
- package/dist/chunk-katrmbxc.js +1 -0
- package/dist/{chunk-4ekrbk2w.js → chunk-kfv4mdcm.js} +2 -2
- package/dist/{chunk-9neq5xrb.js → chunk-m3dvta6k.js} +2 -2
- package/dist/chunk-m4ya7qqd.js +1 -0
- package/dist/{chunk-22h5kh4z.js → chunk-m8s208g3.js} +1 -1
- package/dist/{chunk-27w2k6t7.js → chunk-mp637mb6.js} +2 -2
- package/dist/{chunk-npgt73cg.js → chunk-mpymjr7j.js} +1 -1
- package/dist/{chunk-f4bx2n1y.js → chunk-mt7fn8cv.js} +3 -3
- package/dist/chunk-n6c6k87j.js +1 -0
- package/dist/{chunk-x04xb9g3.js → chunk-pm9kt54d.js} +1 -1
- package/dist/chunk-ppxn94za.js +1 -0
- package/dist/{chunk-hjkdc185.js → chunk-q6n6rqzs.js} +2 -2
- package/dist/{chunk-4mdy9d43.js → chunk-qb49rm5q.js} +1 -1
- package/dist/chunk-rf7hdke7.js +1 -0
- package/dist/chunk-rjjjgcw4.js +1 -0
- package/dist/{chunk-wk0vpgwk.js → chunk-sw3p1ygn.js} +396 -396
- package/dist/{chunk-fz55cnws.js → chunk-t2mc97k7.js} +2 -2
- package/dist/{chunk-5cgyevqj.js → chunk-te95z52n.js} +1 -1
- package/dist/{chunk-n0ebpwxd.js → chunk-vc32qrmq.js} +1 -1
- package/dist/chunk-vsaqjbm2.js +6 -0
- package/dist/{chunk-nsawkccy.js → chunk-wcxsm922.js} +1 -1
- package/dist/chunk-wm944thh.js +111 -0
- package/dist/chunk-wn23bvs0.js +1 -0
- package/dist/{chunk-62jaf7ej.js → chunk-wtczk025.js} +1 -1
- package/dist/{chunk-ck8sw2zp.js → chunk-xkg84094.js} +2 -2
- package/dist/{chunk-3p32k12g.js → chunk-y75y911b.js} +2 -2
- package/dist/chunk-yatvtpft.js +1 -0
- package/dist/{chunk-358zaryv.js → chunk-yqxyy3w2.js} +2 -2
- package/dist/{chunk-sfbprf9r.js → chunk-z60w7p8a.js} +1 -1
- package/dist/chunk-za6zyd82.js +8 -0
- package/dist/chunk-zhrc510s.js +1 -0
- package/dist/web/assets/{ChatView-BP89vdT_.js → ChatView-DBgMoUrW.js} +2 -2
- package/dist/web/assets/{CodeBlockHighlighter-UnjC3KVk.js → CodeBlockHighlighter-DLFQUVD6.js} +1 -1
- package/dist/web/assets/{FilePreview-D0BiZowf.js → FilePreview--1qHdJP_.js} +1 -1
- package/dist/web/assets/{MarkdownRenderer-CPu_rkPT.js → MarkdownRenderer-DcVHyjtl.js} +3 -3
- package/dist/web/assets/{SettingsModal-CM9pcJas.js → SettingsModal-BM6SPUXW.js} +1 -1
- package/dist/web/assets/{TaskSwitcher-BOCm7kPO.js → TaskSwitcher-B5VYY_QG.js} +1 -1
- package/dist/web/assets/{TerminalPanel-CUZ4slSS.js → TerminalPanel-XWA1jGs8.js} +1 -1
- package/dist/web/assets/index-B8y5_J0i.js +11 -0
- package/dist/web/assets/{session-events-109FkhOM.js → session-events-DJh6SZcl.js} +5 -5
- package/dist/web/index.html +2 -2
- package/package.json +1 -1
- package/dist/chunk-1j2sf8mc.js +0 -1
- package/dist/chunk-1kwm2m6t.js +0 -1
- package/dist/chunk-5w8edqbt.js +0 -1
- package/dist/chunk-6a3c496e.js +0 -1
- package/dist/chunk-6fe9kq17.js +0 -1
- package/dist/chunk-asnzpfzh.js +0 -10
- package/dist/chunk-atdeg922.js +0 -2
- package/dist/chunk-bw7fgs2n.js +0 -1
- package/dist/chunk-d61673v7.js +0 -5
- package/dist/chunk-f7y4m3y0.js +0 -1
- package/dist/chunk-fnz5g9ac.js +0 -1
- package/dist/chunk-kjn0yaqw.js +0 -1
- package/dist/chunk-m883e8d4.js +0 -1
- package/dist/chunk-mx5s93np.js +0 -6
- package/dist/chunk-p54vmne8.js +0 -1
- package/dist/chunk-qy9qkvwe.js +0 -1
- package/dist/chunk-s8f8amvg.js +0 -1
- package/dist/chunk-v80xem15.js +0 -2
- package/dist/chunk-w1vcjwbx.js +0 -8
- package/dist/chunk-x5s68axq.js +0 -44
- package/dist/chunk-z15h0370.js +0 -1
- package/dist/chunk-zracmha2.js +0 -111
- package/dist/web/assets/index-CthLsVgC.js +0 -11
package/dist/chunk-zracmha2.js
DELETED
|
@@ -1,111 +0,0 @@
|
|
|
1
|
-
import{Cc as u,Dc as Hf,Ec as C$,Fc as Yf,Gc as I,Hc as N$,Ic as Wf,Jc as G$,Kc as _$,Lc as x$,Nc as g0,Qc as J$,Rc as Uf}from"./chunk-bdxaz350.js";import{Sd as V0}from"./chunk-fxw1q5j5.js";import{xe as Z0}from"./chunk-01jt0mpr.js";import{Je as i$}from"./chunk-tsskar00.js";import{If as Qf,Jf as Xf}from"./chunk-atdeg922.js";import{Of as A$}from"./chunk-g9re8v25.js";import{ng as U0}from"./chunk-fz55cnws.js";import{ug as x0,xg as J0}from"./chunk-x04xb9g3.js";import{Bg as p}from"./chunk-358zaryv.js";import{Ig as Ff,Jg as q0,Kg as Kf,Lg as A,Mg as m,Og as G0,Pg as c,Qg as C0}from"./chunk-9neq5xrb.js";import{readdir as L$,readFile as a,rm as $0,stat as E0}from"node:fs/promises";import*as V from"node:path";import{nanoid as j}from"nanoid";import{createHash as yf,randomUUID as Sf}from"node:crypto";import*as v from"node:fs/promises";import*as H0 from"node:path";import{execFileSync as Mf}from"node:child_process";import{createHash as gf}from"node:crypto";import{readFileSync as Ef}from"node:fs";var bf=/^[a-f0-9]{64}$/;function Y$($){if(!$||typeof $!=="object")return!1;let f=$;return(f.platform==="linux"||f.platform==="darwin"||f.platform==="win32")&&typeof f.fingerprint==="string"&&bf.test(f.fingerprint)}var W$={readFile:($)=>Ef($,"utf8"),execFile:($,f)=>Mf($,f,{encoding:"utf8",timeout:$==="powershell.exe"?3000:2000,windowsHide:!0})},wf=($)=>{try{return process.kill($,0),!0}catch(f){return f instanceof Error&&"code"in f&&f.code==="EPERM"}};function u0($,f){return{platform:$,fingerprint:gf("sha256").update(`${$}\x00${f}`).digest("hex")}}function kf($,f){let T=f.readFile(`/proc/${$}/stat`).trim(),q=T.lastIndexOf(")");if(q<0)throw Error("Invalid /proc process stat");let L=T.slice(q+2).split(/\s+/)[19];if(!L||!/^\d+$/.test(L))throw Error("Missing process start ticks");return L}function Q0($,f=process.platform,T=W$){if(!Number.isInteger($)||$<=1)return;try{if(f==="linux")return u0(f,kf($,T));if(f==="darwin"){let q=T.execFile("ps",["-o","lstart=","-p",String($)]).trim();return q?u0(f,q):void 0}if(f==="win32"){let q=`(Get-CimInstance Win32_Process -Filter "ProcessId = ${$}").CreationDate.ToUniversalTime().ToString('O')`,B=T.execFile("powershell.exe",["-NoProfile","-NonInteractive","-Command",q]).trim();return B?u0(f,B):void 0}}catch{return}return}function U$($,f){return Q0($,f.platform)?.fingerprint===f.fingerprint}function o1($,f,T=W$,q=wf){if(!Number.isInteger($)||$<=1)return!1;let B=Q0($,f.platform,T);if(B)return B.fingerprint===f.fingerprint;return!q($)}var z$=1;function jf($,f){let T=yf("sha256").update(f).digest("hex");return H0.join(q0($),".locks",`${T}.lock`)}function X0($,f){return $ instanceof Error&&"code"in $&&$.code===f}async function P0($){try{let f=JSON.parse(await v.readFile($,"utf8"));if(f.version!==z$||typeof f.sessionId!=="string"||typeof f.ownerId!=="string"||!Number.isInteger(f.pid)||(f.pid??0)<=0||f.processIdentity!==void 0&&!Y$(f.processIdentity)||typeof f.acquiredAt!=="string")return;return f}catch{return}}async function D$($){let f=await P0($);if(f)return f;return await new Promise((T)=>setTimeout(T,10)),P0($)}function mf($){try{return process.kill($,0),!0}catch(f){return X0(f,"EPERM")}}async function R$($,f){let T;try{return T=await v.open($,"wx",384),await T.writeFile(`${JSON.stringify(f)}
|
|
2
|
-
`,"utf8"),!0}catch(q){if(X0(q,"EEXIST"))return!1;if(T)await v.unlink($).catch(()=>{return});throw q}finally{await T?.close().catch(()=>{return})}}class h extends Error{code="BLADE_SESSION_IN_USE";constructor($){super($?`Session is already active in another Blade process (PID ${$}). Stop that process or choose a different session.`:"Session is already active in another Blade process. Stop that process or choose a different session.");this.name="SessionInUseError"}}class n{filePath;record;released=!1;constructor($,f){this.filePath=$;this.record=f}static async acquire($,f=A$()){let T=jf(f,$),q={version:z$,sessionId:$,ownerId:Sf(),pid:process.pid,processIdentity:Q0(process.pid),acquiredAt:new Date().toISOString()};if(await v.mkdir(H0.dirname(T),{recursive:!0,mode:448}),await R$(T,q))return new n(T,q);let B=await D$(T);if(B&&mf(B.pid)&&(!B.processIdentity||U$(B.pid,B.processIdentity)))throw new h(B.pid);if(await v.unlink(T).catch((L)=>{if(!X0(L,"ENOENT"))throw L}),await R$(T,q))return new n(T,q);throw new h((await D$(T))?.pid)}async release(){if(this.released)return;if(this.released=!0,(await P0(this.filePath))?.ownerId!==this.record.ownerId)return;await v.unlink(this.filePath).catch((f)=>{if(!X0(f,"ENOENT"))throw f})}}var TT=1;function h0($){return $!==null&&typeof $==="object"&&!Array.isArray($)}function If($){if(!h0($)||typeof $.type!=="string")return!1;if($.type==="text")return typeof $.text==="string";return $.type==="image_url"&&h0($.image_url)&&typeof $.image_url.url==="string"}function vf($){if(!h0($))return!1;if(!["system","user","assistant","tool"].includes(String($.role)))return!1;return typeof $.content==="string"||Array.isArray($.content)&&$.content.every(If)}function M$($){if(!Array.isArray($)||$.length===0||$.length>4096)return;let f=JSON.stringify($);if(Buffer.byteLength(f)>16777216)return;let T=JSON.parse(f);if(!Array.isArray(T)||!T.every(vf))return;return T}function qT($){let f=M$($);if(!f)throw Error("Compaction replacement context is invalid or exceeds limits");return f}function g$($){return M$($)}function uf($,f){for(let T of $){if(T.type!=="part_created"||T.data.partType!=="tool_result")continue;let q=T.data.payload;if(!q||typeof q!=="object"||Array.isArray(q))continue;let B=q;if(B.toolCallId===f||T.data.partId===f||T.data.messageId===f)return B}return}function E$($){let f=u($),T=new Map;for(let q of f){if(q.type==="interaction_requested"){T.set(q.data.requestId,{request:q.data,hasToolResult:!1,hasRecoveryToolResult:!1});continue}if(q.type==="interaction_responded"){let B=T.get(q.data.requestId);if(B)B.response=q.data;continue}if(q.type==="interaction_recovered"){let B=T.get(q.data.requestId);if(B)B.recovery=q.data}}for(let q of T.values()){let B=uf(f,q.request.toolCallId);q.hasToolResult=B!==void 0;let L=B?.metadata&&typeof B.metadata==="object"?B.metadata:void 0;q.hasRecoveryToolResult=L?.interactionRecovery===!0&&L.requestId===q.request.requestId}return[...T.values()]}function b$($){return E$($).reverse().find((f)=>!f.response&&!f.recovery)}function OT($){let f=new Map;for(let T of E$($))f.set(T.request.toolCallId,T);return[...f.values()].filter((T)=>T.response&&!T.recovery&&(!T.hasToolResult||T.hasRecoveryToolResult))}function w$($){if(!$)return;return{type:$.request.interactionType,requestId:$.request.requestId}}function Y0($){let f=new Map,T=[];for(let q of $){if(q.type==="review_started"){if(!f.has(q.data.reviewId))T.push(q.data.reviewId),f.set(q.data.reviewId,{start:q.data});continue}if(q.type!=="review_completed")continue;let B=f.get(q.data.reviewId);if(B&&B.completion===void 0)B.completion=q.data}return T.map((q)=>f.get(q)).filter((q)=>q!==void 0)}function NT($){return Y0($).reverse().find((f)=>f.completion===void 0)}function n0($){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 k$($,f){let T=["## Code Review","",`Target: ${$.target.label}`,`Status: ${n0(f.status)}`,"",f.overallExplanation||"No overall explanation was provided."];if(f.findings.length===0)T.push("","No actionable findings.");else{T.push("","### Findings");for(let[q,B]of f.findings.entries()){let L=B.codeLocation.lineStart===B.codeLocation.lineEnd?`${B.codeLocation.lineStart}`:`${B.codeLocation.lineStart}-${B.codeLocation.lineEnd}`;T.push("",`${q+1}. ${B.title}`,` ${B.codeLocation.path}:L${L} · confidence ${B.confidenceScore.toFixed(2)}`,` ${B.body}`)}}if(f.error)T.push("",`Error: ${f.error}`);return T.join(`
|
|
3
|
-
`)}function y$($,f){return{reviewId:$.reviewId,phase:"completed",status:f.status,target:{kind:$.target.kind,label:$.target.label,...$.target.baseSha?{reference:$.target.baseSha}:{},...$.target.commitSha?{reference:$.target.commitSha}:{}},overallExplanation:f.overallExplanation,findings:f.findings.map((T)=>({title:T.title,body:T.body,priority:T.priority,confidenceScore:T.confidenceScore,codeLocation:{...T.codeLocation}})),...f.error?{error:f.error}:{}}}var l0={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 Pf($){try{if($ instanceof Error)return $.message;if($!==null&&typeof $==="object"&&"message"in $&&typeof $.message==="string")return $.message;return String($)}catch{return"Unknown error"}}function hf($){let f=$.toLowerCase();if(/\b(401|unauthorized|authentication|invalid (?:api[ _-]?)?key|api[ _-]?key|credential)\b/.test(f))return"authentication";if(/\b(403|forbidden|permission denied|not permitted)\b/.test(f))return"permission";if(/\b(429|rate limit|too many requests|quota)\b/.test(f))return"rate_limit";if(/\b(timeout|timed out|deadline exceeded|etimedout)\b/.test(f))return"timeout";if(/\b(econnreset|econnrefused|enotfound|network|socket|connection)\b/.test(f))return"network";if(/\b(model not found|model unavailable|unsupported model|no such model)\b/.test(f))return"model_unavailable";if(/\b(context (?:length|window)|maximum context|too many tokens|token limit)\b/.test(f))return"context_limit";if(/\b(image|vision|multimodal|unsupported input|does not support)\b/.test(f))return"unsupported_input";return"runtime"}function nf($){return{code:$,...l0[$]}}function c0($){return nf(hf(Pf($)))}function p0($){if(!$||typeof $!=="object")return!1;let f=$;if(typeof f.code!=="string"||!(f.code in l0))return!1;let T=l0[f.code];return f.message===T.message&&f.retryable===T.retryable}import{promises as L0,realpathSync as cf}from"node:fs";import W0 from"node:path";import*as r from"fs/promises";import*as H from"path";var S$=[".git",".claude","node_modules",".env",".env.local",".env.production",".env.development",".env.test"];class d extends Error{code;constructor($,f){super($);this.code=f;this.name="PathSecurityError"}}class i0{static normalize($,f){let T=H.isAbsolute($)?$:H.resolve(f,$),q=H.normalize(T),B=H.normalize(f);if(!this.isWithinWorkspace(q,B))throw new d(`Path outside workspace: ${$} (resolved to ${q}, workspace: ${B})`,"PATH_OUTSIDE_WORKSPACE");return q}static checkRestricted($){let f=$.split(H.sep);for(let T of S$)if(f.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($,f){this.checkTraversal($);let T=this.normalize($,f);this.checkRestricted(T);try{await r.access(T)}catch(q){throw new d(`Path not found: ${$}`,"PATH_NOT_FOUND")}return T}static async resolveSymlink($,f){try{let T=await r.realpath($),q=await r.realpath(f);if(!this.isWithinWorkspace(T,q))throw new d(`Symlink points outside workspace: ${$} -> ${T}`,"SYMLINK_OUTSIDE_WORKSPACE");return T}catch(T){if(T instanceof d)throw T;return $}}static getRelativePath($,f){return H.relative(f,$)}static isWithinWorkspace($,f){let T=H.resolve($),q=H.resolve(f),B=H.relative(q,T);return B===""||B!==".."&&!B.startsWith(`..${H.sep}`)&&!H.isAbsolute(B)}static async isWithinWorkspaceResolved($,f){let T=H.resolve(f),q=H.isAbsolute($)?H.resolve($):H.resolve(T,$);if(!this.isWithinWorkspace(q,T))return!1;let B;try{B=await r.realpath(T)}catch{return!1}let L=q;while(!0){try{let C=await r.realpath(L);return this.isWithinWorkspace(C,B)}catch(C){let _=C.code;if(_!=="ENOENT"&&_!=="ENOTDIR")return!1}let O=H.dirname(L);if(O===L)return!1;L=O}}static isRestricted($){let f=$.split(H.sep);return S$.some((T)=>f.includes(T))}}var B0=U0("Tool");class l{static instance=null;accessedFiles=new Map;pathAliases=new Map;constructor(){}static getInstance(){if(!l.instance)l.instance=new l;return l.instance}async recordFileRead($,f){try{let T=await L0.stat($),q={filePath:W0.resolve($),accessTime:Date.now(),mtime:T.mtimeMs,sessionId:f,lastOperation:"read"};this.setRecord(q),await this.recordAliases($,q.filePath),B0.debug(`记录文件读取: ${$}`)}catch(T){B0.warn(`记录文件读取失败: ${$}`,T)}}async recordFileEdit($,f,T="edit"){try{let q=await L0.stat($),B={filePath:W0.resolve($),accessTime:Date.now(),mtime:q.mtimeMs,sessionId:f,lastOperation:T};this.setRecord(B),await this.recordAliases($,B.filePath),B0.debug(`记录文件${T==="edit"?"编辑":"写入"}: ${$}`)}catch(q){B0.warn(`记录文件${T==="edit"?"编辑":"写入"}失败: ${$}`,q)}}hasFileBeenRead($,f){let T=this.accessedFiles.get(this.resolveTrackedPath($));if(!T)return!1;return f?T.has(f):T.size>0}async checkFileModification($,f){let T=this.getFileRecord($,f);if(!T)return{modified:!1,message:"文件未被跟踪"};try{let q=await L0.stat($);if(Math.abs(q.mtimeMs-T.mtime)>1)return{modified:!0,message:`文件在访问后被修改(访问时间: ${new Date(T.accessTime).toISOString()}, 当前修改时间: ${q.mtime.toISOString()})`};return{modified:!1}}catch(q){let B=q;if(B.code==="ENOENT")return{modified:!0,message:"文件已被删除"};return{modified:!1,message:`无法检查文件状态: ${B.message}`}}}async checkExternalModification($,f){let T=this.getFileRecord($,f);if(!T)return{isExternal:!1,message:"文件未被跟踪"};try{let q=await L0.stat($);if(q.mtimeMs-T.mtime>2000)return{isExternal:!0,message:`文件在 ${new Date(T.accessTime).toISOString()} (${T.lastOperation}) 之后被外部程序修改(当前修改时间: ${q.mtime.toISOString()})`};return{isExternal:!1}}catch(q){let B=q;if(B.code==="ENOENT")return{isExternal:!0,message:"文件已被删除"};return B0.warn(`检查文件外部修改失败: ${$}`,q),{isExternal:!1,message:`无法检查文件状态: ${B.message}`}}}getFileRecord($,f){let T=this.accessedFiles.get(this.resolveTrackedPath($));if(!T)return;if(f)return T.get(f);return[...T.values()].sort((q,B)=>B.accessTime-q.accessTime)[0]}getTrackedRecords(){return[...this.accessedFiles.values()].flatMap(($)=>[...$.values()])}clearFileRecord($,f){let T=this.resolveTrackedPath($);if(!f){this.accessedFiles.delete(T),this.removeAliases(T);return}let q=this.accessedFiles.get(T);if(q?.delete(f),q?.size===0)this.accessedFiles.delete(T),this.removeAliases(T)}clearAll(){this.accessedFiles.clear(),this.pathAliases.clear()}clearSession($,f){for(let[T,q]of this.accessedFiles.entries()){if(f&&!i0.isWithinWorkspace(T,f))continue;if(q.delete($),q.size===0)this.accessedFiles.delete(T),this.removeAliases(T)}}getTrackedFiles(){return Array.from(this.accessedFiles.keys())}getTrackedFileCount(){return this.accessedFiles.size}static resetInstance(){l.instance=null}setRecord($){let f=this.accessedFiles.get($.filePath);if(!f)f=new Map,this.accessedFiles.set($.filePath,f);f.set($.sessionId,$)}async recordAliases($,f){this.pathAliases.set(W0.resolve($),f);let T=await L0.realpath($).catch(()=>{return});if(T)this.pathAliases.set(T,f)}resolveTrackedPath($){let f=W0.resolve($);if(this.accessedFiles.has(f))return f;let T=this.pathAliases.get(f);if(T)return T;try{let q=cf.native(f);return this.pathAliases.get(q)??q}catch{return f}}removeAliases($){for(let[f,T]of this.pathAliases)if(T===$)this.pathAliases.delete(f)}}import*as O0 from"node:crypto";import{promises as F}from"node:fs";import*as Q from"node:path";import d0 from"write-file-atomic";var j$="missing";class D0{sessionId;workspaceRoot;enableCheckpoints;maxSnapshots;snapshotDir;manifestPath;trackedFileBackups=new Map;snapshots=[];constructor($){if(A($.sessionId),this.sessionId=$.sessionId,$.workspaceRoot&&!Q.isAbsolute($.workspaceRoot))throw Error("Snapshot workspace root must be absolute");this.workspaceRoot=$.workspaceRoot?Q.resolve($.workspaceRoot):void 0,this.enableCheckpoints=$.enableCheckpoints??!0,this.maxSnapshots=$.maxSnapshots??10;let f=C0();this.snapshotDir=Q.join(f,"file-history",this.sessionId),this.manifestPath=Q.join(this.snapshotDir,"manifest.json")}async initialize(){if(!this.enableCheckpoints)return;if(this.workspaceRoot)await this.selectWorkspaceSnapshotDir();await F.mkdir(this.snapshotDir,{recursive:!0,mode:493}),await this.loadManifest()}async selectWorkspaceSnapshotDir(){let $=C0(),f=await F.realpath(this.workspaceRoot).catch(()=>this.workspaceRoot),T=O0.createHash("sha256").update(f).digest("hex").slice(0,24),q=Q.join($,"file-history",this.sessionId),B=Q.join($,"file-history","workspaces",T,this.sessionId),L=Q.join(B,"manifest.json");try{await F.access(L)}catch{await this.migrateLegacySnapshotDir(q,B,f)}this.snapshotDir=B,this.manifestPath=L}async migrateLegacySnapshotDir($,f,T){let q;try{q=JSON.parse(await F.readFile(Q.join($,"manifest.json"),"utf8"))}catch{return}if(q.schemaVersion!==1||!Array.isArray(q.snapshots)||!q.snapshots.every((B)=>this.isWithinWorkspace(B.filePath,T)))return;await F.mkdir(Q.dirname(f),{recursive:!0,mode:493});try{await F.rename($,f)}catch(B){let L=B.code;if(L!=="ENOENT"&&L!=="EEXIST"&&L!=="ENOTEMPTY")throw B}}isWithinWorkspace($,f){if(!Q.isAbsolute($))return!1;let T=Q.relative(f,Q.resolve($));return T===""||T!==".."&&!T.startsWith(`..${Q.sep}`)&&!Q.isAbsolute(T)}async createSnapshot($,f){if(!this.enableCheckpoints)return{backupFileName:"",version:0,backupTime:new Date};let T=await this.resolveFileIdentity($),q=!0;try{await F.access(T)}catch{q=!1}let B=this.trackedFileBackups.get(T),L=B?B.version+1:1,O=this.generateFileHash(T,L),C=this.getSnapshotPath(O,L),_=new Date;if(q){let G=await F.readFile(T);await F.writeFile(C,G)}let N={backupFileName:O,version:L,backupTime:_};return this.trackedFileBackups.set(T,N),this.snapshots.push({messageId:f,backupFileName:O,timestamp:_,filePath:T,version:L,existedBefore:q}),await this.cleanupOldSnapshots(T),await this.persistManifest(),N}async recordPostEditState($,f){if(!this.enableCheckpoints||!f.backupFileName)return;let T=await this.resolveFileIdentity($),q=this.snapshots.find((B)=>B.filePath===T&&B.backupFileName===f.backupFileName&&B.version===f.version);if(!q)throw Error(`未找到待完成的快照: ${T}`);q.postEditHash=await this.hashFile(T),await this.persistManifest()}async discardSnapshot($,f){if(!this.enableCheckpoints||!f.backupFileName)return;let T=await this.resolveFileIdentity($),q=this.snapshots.find((B)=>B.filePath===T&&B.backupFileName===f.backupFileName&&B.version===f.version);if(!q)return;this.removeSnapshot(q),await F.rm(this.getSnapshotPath(q.backupFileName,q.version),{force:!0}),await this.persistManifest()}async rewindLatest($){let f=await this.resolveFileIdentity($),T=this.snapshots.slice().reverse().find((L)=>L.filePath===f&&L.postEditHash!==void 0);if(!T?.postEditHash)throw Error(`未找到可回退快照: ${f}`);if(await this.hashFile(f)!==T.postEditHash)throw Error(`文件在 Blade 编辑后已被修改,拒绝覆盖: ${f}`);let B=this.getSnapshotPath(T.backupFileName,T.version);if(T.existedBefore){let L=await F.readFile(B);await F.mkdir(Q.dirname(f),{recursive:!0}),await F.writeFile(f,L)}else await F.rm(f,{force:!0});return this.removeSnapshot(T),await F.rm(B,{force:!0}),await this.persistManifest(),T}async restoreSnapshot($,f){let T=await this.resolveFileIdentity($),q=this.snapshots.slice().reverse().find((L)=>L.messageId===f&&L.filePath===T);if(!q)throw Error(`未找到快照: messageId=${f}, filePath=${T}`);let B=this.getSnapshotPath(q.backupFileName,q.version);if(q.existedBefore){let L=await F.readFile(B);await F.mkdir(Q.dirname(T),{recursive:!0}),await F.writeFile(T,L)}else await F.rm(T,{force:!0})}async listSnapshots($){let f=await this.resolveFileIdentity($);return this.snapshots.filter((T)=>T.filePath===f)}async listAllSnapshots(){return this.snapshots.filter(($)=>$.postEditHash!==void 0)}async previewRewind($){let f=this.buildRewindPlan($);return{files:f.map((T)=>T.filePath),snapshotCount:f.reduce((T,q)=>T+q.selected.length,0)}}async rewindSnapshots($){let f=this.buildRewindPlan($);if(f.length===0)return{files:[],snapshotCount:0};let T=new Map;for(let B of f){let L,O=!0;try{L=await F.readFile(B.filePath)}catch(_){if(_.code!=="ENOENT")throw _;O=!1}if((L?O0.createHash("sha256").update(L).digest("hex"):j$)!==B.latest.postEditHash)throw Error(`文件在 Blade 编辑后已被修改,拒绝覆盖: ${B.filePath}`);if(T.set(B.filePath,{existed:O,content:L}),B.target.existedBefore)await F.access(this.getSnapshotPath(B.target.backupFileName,B.target.version))}let q=[...this.snapshots];try{for(let L of f)if(L.target.existedBefore){let O=await F.readFile(this.getSnapshotPath(L.target.backupFileName,L.target.version));await F.mkdir(Q.dirname(L.filePath),{recursive:!0}),await d0(L.filePath,O)}else await F.rm(L.filePath,{force:!0});let B=new Set(f.flatMap((L)=>L.selected));this.snapshots=this.snapshots.filter((L)=>!B.has(L)),this.rebuildTrackedFileBackups(),await this.persistManifest(),await Promise.all([...B].map((L)=>F.rm(this.getSnapshotPath(L.backupFileName,L.version),{force:!0}).catch(()=>{return})))}catch(B){this.snapshots=q,this.rebuildTrackedFileBackups();let L=[];for(let[O,C]of T)try{if(C.existed&&C.content)await d0(O,C.content);else await F.rm(O,{force:!0})}catch(_){L.push(_)}if(L.length>0)throw AggregateError([B,...L],"快照回退失败且无法完整恢复回退前状态");throw B}return{files:f.map((B)=>B.filePath),snapshotCount:f.reduce((B,L)=>B+L.selected.length,0)}}async commitSnapshots($){let f=this.buildRewindPlan($),T=new Set(f.flatMap((B)=>B.selected));if(T.size===0)return{files:[],snapshotCount:0};let q=[...this.snapshots];this.snapshots=this.snapshots.filter((B)=>!T.has(B)),this.rebuildTrackedFileBackups();try{await this.persistManifest()}catch(B){throw this.snapshots=q,this.rebuildTrackedFileBackups(),B}return await Promise.all([...T].map((B)=>F.rm(this.getSnapshotPath(B.backupFileName,B.version),{force:!0}).catch(()=>{return}))),{files:f.map((B)=>B.filePath),snapshotCount:T.size}}buildRewindPlan($){let f=new Set($),T=this.snapshots.filter((L)=>L.postEditHash!==void 0),q=T.filter((L)=>f.has(L.messageId));return[...new Set(q.map((L)=>L.filePath))].sort().map((L)=>{let O=T.filter((G)=>G.filePath===L),C=O.filter((G)=>f.has(G.messageId)),_=O.indexOf(C[0]),N=O.slice(_);if(N.length!==C.length||N.some((G)=>!f.has(G.messageId)))throw Error(`请求的快照不是文件历史的连续后缀: ${L}`);return{filePath:L,selected:C,target:C[0],latest:C.at(-1)}})}async loadManifest(){try{let $=await F.readFile(this.manifestPath,"utf-8"),f=JSON.parse($);if(f.schemaVersion!==1||!Array.isArray(f.snapshots))throw Error("Unsupported snapshot manifest");this.snapshots=await Promise.all(f.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 F.rm(this.manifestPath,{force:!0});return}let $={schemaVersion:1,snapshots:this.snapshots.map((f)=>({...f,timestamp:f.timestamp.toISOString()}))};await d0(this.manifestPath,JSON.stringify($,null,2),{encoding:"utf-8",mode:384})}async cleanupOldSnapshots($){let T=this.snapshots.filter((q)=>q.filePath===$).slice(0,-this.maxSnapshots);for(let q of T)await F.rm(this.getSnapshotPath(q.backupFileName,q.version),{force:!0}),this.removeSnapshot(q)}async cleanup($=0){let f=this.snapshots.slice().sort((q,B)=>B.timestamp.getTime()-q.timestamp.getTime()),T=new Set(f.slice(0,$));for(let q of this.snapshots)if(!T.has(q))await F.rm(this.getSnapshotPath(q.backupFileName,q.version),{force:!0});this.snapshots=f.slice(0,$).reverse(),this.rebuildTrackedFileBackups(),await this.persistManifest()}getSnapshotPath($,f){return Q.join(this.snapshotDir,`${$}@v${f}`)}async resolveFileIdentity($){let f=Q.resolve($),T=[],q=f;while(!0){try{let L=await F.realpath(q);return Q.join(L,...T.reverse())}catch(L){let O=L.code;if(O!=="ENOENT"&&O!=="ENOTDIR")throw L}let B=Q.dirname(q);if(B===q)return f;T.push(Q.basename(q)),q=B}}async hashFile($){try{let f=await F.readFile($);return O0.createHash("sha256").update(f).digest("hex")}catch(f){if(f.code==="ENOENT")return j$;throw f}}removeSnapshot($){let f=this.snapshots.indexOf($);if(f>=0)this.snapshots.splice(f,1);this.rebuildTrackedFileBackups()}rebuildTrackedFileBackups(){this.trackedFileBackups.clear();for(let $ of this.snapshots){let f=this.trackedFileBackups.get($.filePath);if(!f||f.version<$.version)this.trackedFileBackups.set($.filePath,{backupFileName:$.backupFileName,version:$.version,backupTime:$.timestamp})}}generateFileHash($,f){let T=O0.createHash("md5");return T.update(`${$}:${f}`),T.digest("hex").substring(0,16)}getSnapshotDir(){return this.snapshotDir}getSessionId(){return this.sessionId}getTrackedFileCount(){return this.trackedFileBackups.size}getSnapshotCount(){return this.snapshots.length}}var DT=1200,RT=2000,AT=2000,zT=2000;function I$($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function pf($){if(typeof $==="string"&&$.length>0)return $;if(I$($)&&typeof $.message==="string")return $.message;return}function df($,f){if($===null||$===void 0)return f??"";if(typeof $==="string")return $;if(typeof $==="object")return $;return String($)}function v$($){let f=$.error!==null&&$.error!==void 0,T=f?pf($.error)??"Tool execution failed":void 0,q=I$($.metadata)?$.metadata:void 0;return{success:!f,llmContent:df($.output,T),...T?{error:{type:"execution_error",message:T}}:{},...q?{metadata:q}:{}}}function o0($,f){if($.length<=f)return $;let T=Math.max(0,f);if(T>0&&T<$.length&&/[\uD800-\uDBFF]/.test($.charAt(T-1)))T-=1;return $.slice(0,T)}function m$($,f){if($.length<=f)return $;let T=Math.max(0,$.length-f);if(T<$.length&&/[\uDC00-\uDFFF]/.test($.charAt(T)))T+=1;return $.slice(T)}function r0($,f){if($.length<=f)return $;if(f<=0)return"";let T=`
|
|
4
|
-
... (display clipped) ...
|
|
5
|
-
`,q=$.indexOf(`
|
|
6
|
-
`),B=q>=0&&/^(?:stdout|stderr):$/.test($.slice(0,q))?`${$.slice(0,q)}
|
|
7
|
-
`:"",L=B?$.slice(B.length):$,O=f-B.length-T.length;if(O<=0)return m$($,f);let C=Math.min(Math.floor(O/3),L.length),_=Math.max(0,O-C);return B+o0(L,C)+T+m$(L,_)}function rf($){let f=$.split(`
|
|
8
|
-
`),T=f.at(-1);if(!T?.startsWith("Output truncated"))return{body:$};return{body:f.slice(0,-1).join(`
|
|
9
|
-
`),suffix:T}}function of($){let T=$.indexOf(`
|
|
10
|
-
stderr:
|
|
11
|
-
`);if(!$.startsWith(`stdout:
|
|
12
|
-
`)||T<0)return[$];return[$.slice(0,T),$.slice(T+1)]}function MT($,f){if(!Number.isSafeInteger(f)||f<=0)throw Error("maxChars must be a positive safe integer");if(!$.detail||$.detail.length<=f)return $;let{body:T,suffix:q}=rf($.detail),B=q?`
|
|
13
|
-
${o0(q,f)}`:"",L=Math.max(0,f-B.length),O=of(T),C;if(O.length===2){let G=Math.max(0,L-1),x=Math.floor(G/2),J=G-x;C=`${r0(O[0],x)}
|
|
14
|
-
${r0(O[1],J)}`}else C=r0(T,L);let _=o0(`${C}${B}`,f);return{...$,detail:_}}var ET={clientVisible:!1};function u$($){if($.metadata&&typeof $.metadata==="object"&&!Array.isArray($.metadata)&&$.metadata.clientVisible===!1)return!1;return!($.role==="user"&&typeof $.content==="string"&&$.content.startsWith("This turn made a non-trivial implementation. Before finishing, call Task ")&&$.content.endsWith("Only a fresh structured PASS verdict allows completion."))}import{createHash as C1}from"node:crypto";import o$ from"node:path";import{StringDecoder as sf}from"node:string_decoder";var wT=1048576;function t0($,f){let T=f;while(T<$.length&&($[T]&192)===128)T+=1;return T}class a0{maxBytes;chunks=[];retainedBytes=0;omittedBytes=0;totalBytes=0;constructor($=1048576){this.maxBytes=$;if(!Number.isSafeInteger($)||$<=0)throw Error("maxBytes must be a positive safe integer")}append($){let f=Buffer.isBuffer($)?$:Buffer.from($);if(f.length===0)return;if(this.totalBytes+=f.length,f.length>this.maxBytes){this.retainOversizedChunkTail(f);return}this.chunks.push(f),this.retainedBytes+=f.length,this.trimToLimit(),this.compactChunks()}peek(){return{content:Buffer.concat(this.chunks,this.retainedBytes).toString("utf8"),retainedBytes:this.retainedBytes,omittedBytes:this.omittedBytes,totalBytes:this.totalBytes}}consume(){let $=this.peek();return this.chunks.length=0,this.retainedBytes=0,this.omittedBytes=0,$}retainedChunkCountForTests(){return this.chunks.length}retainOversizedChunkTail($){this.omittedBytes+=this.retainedBytes,this.chunks.length=0,this.retainedBytes=0;let f=t0($,$.length-this.maxBytes);if(this.omittedBytes+=f,f===$.length)return;let T=Buffer.from($.subarray(f));this.chunks.push(T),this.retainedBytes=T.length}trimToLimit(){let $=!1;while(this.retainedBytes>this.maxBytes){let f=this.chunks[0];if(!f)return;let T=this.retainedBytes-this.maxBytes;if(f.length<=T){this.chunks.shift(),this.retainedBytes-=f.length,this.omittedBytes+=f.length,$=!0;continue}let q=t0(f,T);this.chunks[0]=f.subarray(q),this.retainedBytes-=q,this.omittedBytes+=q,$=!0}if($)this.realignRetainedStart()}realignRetainedStart(){while(this.chunks.length>0){let $=this.chunks[0];if($.length===0){this.chunks.shift();continue}let f=t0($,0);if(f===0)return;if(this.retainedBytes-=f,this.omittedBytes+=f,f===$.length)this.chunks.shift();else{this.chunks[0]=$.subarray(f);return}}}compactChunks(){if(this.chunks.length<=32)return;let $=Buffer.concat(this.chunks,this.retainedBytes);if(this.chunks.length=0,$.length>0)this.chunks.push($)}}var R0={maxLines:30,maxChars:3000,keepHead:10,keepTail:10,summarize:!0},o={maxLines:100,maxChars:1e4,keepHead:40,keepTail:40,summarize:!0},P$={maxLines:200,maxChars:20000,keepHead:80,keepTail:80,summarize:!1},tf={maxLines:150,maxChars:15000,keepHead:50,keepTail:50,summarize:!0},af=[{pattern:/^git\s+(rm|add)\s+(-r|--cached|-rf|-f)?\s*/i,config:R0,summaryTemplate:($)=>`Successfully processed ${$} files`},{pattern:/^(npm|pnpm|yarn|bun)\s+(install|i|add|remove|uninstall)/i,config:R0,summaryTemplate:($)=>`Package operation completed (${$} lines of output)`},{pattern:/^(npm|pnpm|yarn|bun)\s+(run|exec)\s+(build|compile|bundle)/i,config:o,summaryTemplate:($)=>`Build completed (${$} lines of output)`},{pattern:/^(npm|pnpm|yarn|bun)\s+(run|exec)\s+(test|lint|check)/i,config:P$},{pattern:/^git\s+(status|branch|remote)/i,config:o},{pattern:/^git\s+(log|diff|show)/i,config:P$},{pattern:/^(ls|dir|tree)\s+/i,config:o,summaryTemplate:($)=>`Listed ${$} items`},{pattern:/^find\s+/i,config:o,summaryTemplate:($)=>`Found ${$} matches`},{pattern:/^(grep|rg|ag)\s+/i,config:o,summaryTemplate:($)=>`Found ${$} matching lines`},{pattern:/^(docker|podman)\s+(build|pull|push)/i,config:R0,summaryTemplate:($)=>`Docker operation completed (${$} lines)`},{pattern:/^(pip|pip3|poetry|pipenv)\s+(install|uninstall)/i,config:R0,summaryTemplate:($)=>`Python package operation completed (${$} lines)`},{pattern:/^(cargo|rustup)\s+(build|install|update)/i,config:o,summaryTemplate:($)=>`Rust operation completed (${$} lines)`},{pattern:/^(go)\s+(build|get|mod)/i,config:o,summaryTemplate:($)=>`Go operation completed (${$} lines)`}];function h$($,f,T){let q=f,B=T??$.length;if(q>0){let L=$.charCodeAt(q);if(L>=56320&&L<=57343)q+=1}if(B<$.length){let L=$.charCodeAt(B-1);if(L>=55296&&L<=56319)B-=1}return $.slice(q,B)}class s0{static getConfigForCommand($){for(let{pattern:f,config:T,summaryTemplate:q}of af)if(f.test($))return{config:T,summaryTemplate:q};return{config:tf}}static truncate($,f){let{config:T,summaryTemplate:q}=this.getConfigForCommand(f);return this.truncateWithConfig($,T,q)}static truncateWithConfig($,f,T){let q=$.length,B=$.split(`
|
|
15
|
-
`),L=B.length;if(L<=f.maxLines&&q<=f.maxChars)return{content:$,truncated:!1,originalLines:L,originalChars:q};let O=B.slice(0,f.keepHead),C=B.slice(-f.keepTail),_=L-f.keepHead-f.keepTail,N=O.join(`
|
|
16
|
-
`);if(N+=`
|
|
17
|
-
|
|
18
|
-
... (${_} lines truncated, showing first ${f.keepHead} and last ${f.keepTail} of ${L} total) ...
|
|
19
|
-
|
|
20
|
-
`,N+=C.join(`
|
|
21
|
-
`),N.length>f.maxChars){let x=Math.floor(f.maxChars/2)-50,J=h$(N,0,x),Z=h$(N,N.length-x);N=`${J}
|
|
22
|
-
|
|
23
|
-
... (content truncated to ${f.maxChars} chars) ...
|
|
24
|
-
|
|
25
|
-
${Z}`}let G=f.summarize&&T?T(L,q):void 0;if(G)N+=`
|
|
26
|
-
|
|
27
|
-
[Summary: ${G}]`;return{content:N,truncated:!0,originalLines:L,originalChars:q,summary:G}}static truncateForLLM($,f,T){let q=this.truncate($,T),B=this.truncate(f,T),L;if(q.truncated||B.truncated){let O=[];if(q.truncated)O.push(`stdout: ${q.originalLines} lines -> ${q.content.split(`
|
|
28
|
-
`).length} lines`);if(B.truncated)O.push(`stderr: ${B.originalLines} lines -> ${B.content.split(`
|
|
29
|
-
`).length} lines`);L=`Output truncated: ${O.join(", ")}`}return{stdout:q.content,stderr:B.content,truncationInfo:L}}static shouldTruncate($,f){let{config:T}=this.getConfigForCommand(f);return $.split(`
|
|
30
|
-
`).length>T.maxLines||$.length>T.maxChars}static getStats($){return{lines:$.split(`
|
|
31
|
-
`).length,chars:$.length,words:$.split(/\s+/).filter(Boolean).length}}}var n$=32768,ef=1048576,$1=65536,f1=3600000,l$=4096,T1=/[\u001B\u009B][[\]()#;?]*(?:(?:(?:[a-zA-Z\d]*(?:;[-a-zA-Z\d/#&.:=?%@~_]+)*)?\u0007)|(?:(?:\d{1,4}(?:[;:]\d{0,4})*)?[\dA-PR-TZcf-nq-uy=><~]))/g;class e0{stream;executionId;onEvent;output=new a0(ef/2);decoder=new sf("utf8");sniffChunks=[];sniffBytes=0;binary=!1;totalBytes=0;streamedBytes=0;streamTruncated=!1;pendingEvents=[];constructor($,f,T){this.stream=$;this.executionId=f;this.onEvent=T}append($){let f=Buffer.isBuffer($)?$:Buffer.from($);if(f.length===0)return;if(this.totalBytes+=f.length,this.sniffBytes<l$){let q=f.subarray(0,Math.min(f.length,l$-this.sniffBytes));this.sniffChunks.push(q),this.sniffBytes+=q.length,this.binary=this.binary||Buffer.concat(this.sniffChunks).includes(0)}if(this.binary)return;let T=c$(this.decoder.write(f));this.output.append(T),this.emit(T)}finish(){if(this.binary)return;let $=c$(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 f=$1-this.streamedBytes;if(f<=0){this.streamTruncated=!0;return}let T=q1($,f);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 c$($){return $.replace(T1,"")}function q1($,f){let T=Buffer.from($);if(T.length<=f)return $;let q=f;while(q>0&&(T[q]&192)===128)q-=1;return T.subarray(0,q).toString("utf8")}function p$($){return $.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""").replaceAll("'","'")}function L1($){let f=$.trim();if(!f)throw Error("User shell command cannot be empty");if(f.length>n$)throw Error(`User shell command exceeds ${n$} characters`);if(f.includes("\x00"))throw Error("User shell command contains a null byte");return f}function B1(){return{execute($,f){return new Promise((T)=>{let q=process.platform==="win32"?process.env.COMSPEC||"cmd.exe":process.env.SHELL||"/bin/bash",B=process.platform==="win32"?["/d","/s","/c",$]:["-l","-c",$],{child:L,processTree:O}=i$(q,B,{cwd:f.cwd,env:f.env,stdio:["ignore","pipe","pipe"]}),C="",_="",N=!1,G=!1,x=!1,J,Z=()=>{return J??=O.terminate(),J},E=setTimeout(()=>{N=!0,Z()},f.timeoutMs),M=()=>{G=!0,Z()};if(f.signal.addEventListener("abort",M,{once:!0}),f.signal.aborted)M();L.stdout?.on("data",(W)=>{f.onOutput?.("stdout",W)}),L.stderr?.on("data",(W)=>{f.onOutput?.("stderr",W)});let b=async(W)=>{if(x)return;if(x=!0,clearTimeout(E),f.signal.removeEventListener("abort",M),N||G)await Z();T({...W,stdout:"",stderr:"",timedOut:N,aborted:G})};L.once("error",(W)=>{b({exitCode:null,error:W.message})}),L.once("close",(W)=>{b({exitCode:W})})})}}}async function vT($,f){let T=L1($),q=f.timeoutMs??f1,B=new e0("stdout",f.executionId,f.onEvent),L=new e0("stderr",f.executionId,f.onEvent),O=Date.now();await f.onEvent?.({type:"started",executionId:f.executionId,command:T});let C,_=!1,N=!1;try{C=await(f.executor??B1()).execute(T,{cwd:f.cwd,env:f.env,timeoutMs:q,signal:f.signal,onOutput:(M,b)=>{if(M==="stdout")_=!0;else N=!0;(M==="stdout"?B:L).append(b)}})}catch(M){C={exitCode:null,stdout:"",stderr:"",error:M instanceof Error?M.message:String(M)}}if(!_)B.append(C.stdout);if(!N)L.append(C.stderr);B.finish(),L.finish(),await Promise.all([B.flushEvents(),L.flushEvents()]);let G=B.snapshot(),x=L.snapshot(),J=s0.truncateForLLM(G.content.trim(),x.content.trim(),T),Z=C.aborted||f.signal.aborted?"aborted":C.timedOut?"timed_out":C.error?"spawn_error":C.exitCode===0?"completed":"failed",E={version:1,command:T,status:Z,exitCode:C.exitCode,durationMs:Math.max(0,Date.now()-O),stdout:J.stdout,stderr:C.error?[J.stderr,C.error].filter(Boolean).join(`
|
|
32
|
-
`):J.stderr,stdoutOmittedBytes:G.omittedBytes,stderrOmittedBytes:x.omittedBytes,binaryOutput:G.binary||x.binary,truncated:Boolean(J.truncationInfo)||G.omittedBytes>0||x.omittedBytes>0};return await f.onEvent?.({type:"completed",executionId:f.executionId,record:E}),E}function uT($){let f=[$.stdout?`stdout:
|
|
33
|
-
${$.stdout}`:"",$.stderr?`stderr:
|
|
34
|
-
${$.stderr}`:""].filter(Boolean).join(`
|
|
35
|
-
`);return["<user_shell_command>",`<command>${p$($.command)}</command>`,"<result>",`Status: ${$.status}`,`Exit code: ${$.exitCode??"null"}`,`Duration: ${($.durationMs/1000).toFixed(3)} seconds`,`Output:
|
|
36
|
-
${p$(f||"(no output)")}`,"</result>","</user_shell_command>"].join(`
|
|
37
|
-
`)}function d$($){let f=[$.stdout,$.stderr?`stderr:
|
|
38
|
-
${$.stderr}`:""].filter(Boolean).join(`
|
|
39
|
-
`);return[`! ${$.command}`,f||"(no output)"].join(`
|
|
40
|
-
`)}function O1($){if(!$||typeof $!=="object"||Array.isArray($))return;let f=$;if(f.version!==1||typeof f.command!=="string"||!["completed","failed","aborted","timed_out","spawn_error"].includes(String(f.status))||f.exitCode!==null&&typeof f.exitCode!=="number"||typeof f.durationMs!=="number"||typeof f.stdout!=="string"||typeof f.stderr!=="string"||typeof f.stdoutOmittedBytes!=="number"||typeof f.stderrOmittedBytes!=="number"||typeof f.binaryOutput!=="boolean"||typeof f.truncated!=="boolean")return;return f}function A0($){if(!$||typeof $!=="object"||Array.isArray($))return;return O1($.userShellCommand)}var z0=16777216,r$=65536,pT=1048576,N1=8,M0=200,G1=/(?:^|[_-])(?:api[_-]?key|authorization|bearer|cookie|credential|password|passwd|private[_-]?key|refresh[_-]?token|secret|session[_-]?token|token)(?:$|[_-])/i,_1=/(?<![:/A-Za-z0-9._-])\/[^\s"'`<>]+/g,x1=/(?<![A-Za-z0-9._-])[A-Za-z]:[\\/][^\s"'`<>]+/g,J1=new RegExp("\\u001b(?:\\[[0-?]*[ -/]*[@-~]|\\][^\\u0007]*(?:\\u0007|\\u001b\\\\))","g"),V1=/-----BEGIN [^-]*PRIVATE KEY-----[\s\S]*?-----END [^-]*PRIVATE KEY-----/g;function k($,f){return $.count+=1,f}function Z1($){return G1.test($.replace(/[A-Z]/g,(f)=>`_${f.toLowerCase()}`))}function F1($){return[...$].filter((f)=>{if(f===`
|
|
41
|
-
`||f==="\r"||f==="\t")return!0;let T=f.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(f)}).join("")}function w($,f){let T=$.normalize("NFKC"),q=T.replace(J1,"");if(q!==T)f.count+=1;T=q,T=T.replace(V1,()=>k(f,"[redacted-private-key]")),T=T.replace(/\bBearer\s+[^\s"'`]+/gi,()=>k(f,"Bearer [redacted]")).replace(/\bsk-[A-Za-z0-9_-]{8,}\b/g,()=>k(f,"[redacted-key]")).replace(/\bAKIA[0-9A-Z]{16}\b/g,()=>k(f,"[redacted-aws-key]")).replace(/\b(api[_-]?key|access[_-]?token|authorization|cookie|password|passwd|refresh[_-]?token|secret|session[_-]?token)\b(\s*[:=]\s*)([^\s,;]+)/gi,(L,O,C)=>`${O}${C}${k(f,"[redacted]")}`);let B=F1(T);if(B!==T)f.count+=1;return B.replace(/\r\n?/g,`
|
|
42
|
-
`)}function t$($,f,T){if(/^data:[^;,]+;base64,/i.test($))return k(T,"[binary omitted]");let q=w($,T),B=o$.resolve(f);for(let L of[B,B.startsWith("/private/")?B.slice(8):`/private${B}`])q=q.replaceAll(L,".");return q=q.replace(_1,(L)=>L.startsWith("./")?L:k(T,"[host-path]")),q=q.replace(x1,()=>k(T,"[host-path]")),q=q.replace(/\bhttps?:\/\/[^\s"'`]+/gi,(L)=>{try{let O=new URL(L);if(O.username||O.password||O.search||O.hash)T.count+=1;return O.username="",O.password="",O.search="",O.hash="",O.toString()}catch{return k(T,"[redacted-url]")}}),q}function T$($,f,T,q=0,B){if(B&&Z1(B))return k(T,"[redacted]");if(q>=N1)return k(T,"[depth limit]");if(typeof $==="string")return t$($,f,T);if($===null||typeof $==="boolean"||typeof $==="number"&&Number.isFinite($))return $;if(Array.isArray($)){let L=$.slice(0,M0).map((O)=>T$(O,f,T,q+1));if($.length>L.length)L.push(k(T,`[${$.length-L.length} items omitted]`));return L}if($&&typeof $==="object"){let L={},O=Object.entries($);for(let[C,_]of O.slice(0,M0))L[w(C,T)]=T$(_,f,T,q+1,C);if(O.length>M0)L["[entries omitted]"]=O.length-M0;return L}return String($)}function K1($,f){let T=Buffer.from($,"utf8");if(T.length<=f)return $;let q=T.subarray(0,f).toString("utf8");while(Buffer.byteLength(q,"utf8")>f)q=q.slice(0,-1);return q}function Q1($,f,T){let q=JSON.stringify(T$($,f,T),null,2);if(Buffer.byteLength(q,"utf8")<=r$)return q;T.count+=1;let B=`
|
|
43
|
-
... [activity truncated]`;return K1(q,r$-Buffer.byteLength(B))+B}function q$($,f=""){let T=Math.max(2,...[...$.matchAll(/`+/g)].map((B)=>B[0].length)),q="`".repeat(T+1);return`${q}${f}
|
|
44
|
-
${$}
|
|
45
|
-
${q}`}function $$($){return $.replace(/\s+/g," ").trim()}function X1($){let f=new Map,T=new Map,q=new Map,B=0;for(let L of u($)){if(L.type==="message_created"){let G=T.get(L.data.messageId);if(G)G.role=L.data.role,G.metadata=L.data.metadata,f.set(L.data.messageId,G),T.delete(L.data.messageId);else if(!f.has(L.data.messageId))f.set(L.data.messageId,{order:B++,role:L.data.role,parts:[],metadata:L.data.metadata});continue}if(L.type!=="part_created"&&L.type!=="part_updated")continue;let O=f.get(L.data.messageId)??T.get(L.data.messageId);if(!O)O={order:B++,role:"activity",parts:[]},T.set(L.data.messageId,O);let C=`${L.data.messageId}\x00${L.data.partType}\x00${L.data.partId}`,_=q.get(C);if(_){_.event=L;continue}let N={order:B++,event:L};q.set(C,N),O.parts.push(N)}return[...f.values(),...T.values()].sort((L,O)=>L.order-O.order)}function f$($,f,T,q){return`## Activity: ${$}
|
|
46
|
-
|
|
47
|
-
${q$(Q1(f,T.projectPath,q),"json")}`}function a$($,f,T={}){let q={count:0},B=T.includeReasoning===!0,L=[],O=0,C=0,_=0;for(let b of X1($)){let W=A0(b.metadata);if(W){let R=w(W.command,q),D=w([W.stdout,W.stderr?`stderr:
|
|
48
|
-
${W.stderr}`:""].filter(Boolean).join(`
|
|
49
|
-
`)||"(no output)",q);L.push(`## User shell command
|
|
50
|
-
|
|
51
|
-
${q$(`$ ${R}
|
|
52
|
-
${D}`,"console")}`),O+=1;continue}let s=[],e=[],y=[],S=Number.POSITIVE_INFINITY;for(let R of b.parts.sort((D,z)=>D.order-z.order)){let{partType:D,payload:z}=R.event.data;if(D==="text"){let K=z.text;if(typeof K==="string"&&K.trim())s.push(w(K,q)),S=Math.min(S,R.order)}else if(D==="image"){let K=z.mimeType;e.push(typeof K==="string"?`[Image: ${w(K,q)}]`:"[Image]"),S=Math.min(S,R.order)}else if(D==="reasoning"&&B){let K=z.text;if(typeof K==="string"&&K.trim())y.push({order:R.order,markdown:`## Reasoning
|
|
53
|
-
|
|
54
|
-
${w(K,q).trim()}`}),_+=1}else if(D==="tool_call"){let K=z,g=typeof K.toolName==="string"?w(K.toolName,q):"unknown";y.push({order:R.order,markdown:f$(`${g} call`,K.input??{},f,q)}),C+=1}else if(D==="tool_result"){let K=z,g=typeof K.toolName==="string"?w(K.toolName,q):"unknown";y.push({order:R.order,markdown:f$(`${g} result`,typeof K.error==="string"?{error:K.error}:{output:K.output??null},f,q)}),C+=1}else if(D==="summary"){let K=z.text;if(typeof K==="string"&&K.trim())y.push({order:R.order,markdown:`## Summary
|
|
55
|
-
|
|
56
|
-
${w(K,q).trim()}`})}else if(D==="subtask_ref")y.push({order:R.order,markdown:f$("Subagent",z,f,q)}),C+=1;else if(D==="diff"||D==="patch"){let K=typeof z==="string"?z:JSON.stringify(z,null,2);y.push({order:R.order,markdown:`## File changes
|
|
57
|
-
|
|
58
|
-
${q$(t$(K,f.projectPath,q),"diff")}`}),C+=1}}if((b.role==="user"||b.role==="assistant")&&(s.length>0||e.length>0))y.push({order:S,markdown:`## ${b.role==="user"?"User":"Assistant"}
|
|
59
|
-
|
|
60
|
-
${[...s,...e].join(`
|
|
61
|
-
|
|
62
|
-
`).trim()}`}),O+=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 N=`${L.join(`
|
|
63
|
-
|
|
64
|
-
`)}
|
|
65
|
-
`,G=Buffer.byteLength(N,"utf8");if(G>z0)throw Error(`Session export exceeds ${z0} bytes`);let x=C1("sha256").update(N).digest("hex"),J=o$.basename(f.taskSourceProjectPath??f.projectPath),Z=f.selectedModelId??f.taskModelId,M=["# Blade conversation","",`- Session: \`${f.sessionId}\``,...f.title?[`- Title: ${$$(w(f.title,q))}`]:[],`- Project: \`${$$(w(J,q))}\``,...Z?[`- Model: \`${$$(w(Z,q))}\``]:[],...f.permissionMode?[`- Permission mode: ${f.permissionMode}`]:[],`- Created: ${f.firstMessageTime}`,`- Updated: ${f.lastMessageTime}`,`- State: ${f.archivedAt?"archived":"active"}`,`- Reasoning: ${B?"included":"omitted"}`,...f.reasoningEffort?[`- Reasoning effort: ${f.reasoningEffort}`]:[],...f.serviceTier?[`- Service tier: ${f.serviceTier}`]:[],...f.responseVerbosity?[`- Response verbosity: ${f.responseVerbosity}`]:[],...f.communicationStyle?[`- Communication style: ${f.communicationStyle}`]:[],...f.communicationStyleDigest?[`- Communication style SHA-256: \`${f.communicationStyleDigest}\``]:[],...f.projectInstructionsDigest?[`- Project instructions SHA-256: \`${f.projectInstructionsDigest}\``]:[],`- Content SHA-256: \`${x}\``,`- Content bytes: ${G}`,`- Redactions: ${q.count}`,"","---",""].join(`
|
|
66
|
-
`)+`
|
|
67
|
-
`+N;if(Buffer.byteLength(M,"utf8")>z0)throw Error(`Session export exceeds ${z0} bytes`);return{filename:`blade-session-${f.sessionId.slice(0,12)}.md`,markdown:M,contentSha256:x,contentBytes:G,messageCount:O,activityCount:C,reasoningIncluded:B,reasoningCount:_,redactionCount:q.count}}import{createHash as H1}from"node:crypto";import Y1 from"ajv";var Bf="StructuredOutput",s$=65536,e$=131072,oT=2,$f=20,ff=1000,Tf=200;function t($){return $!==null&&typeof $==="object"&&!Array.isArray($)}function qf($,f){if(!t($))throw Error(`${f} must be a JSON object`);let T;try{T=JSON.stringify($)}catch(B){throw Error(`${f} must be JSON-serializable`,{cause:B})}if(T===void 0)throw Error(`${f} must be JSON-serializable`);let q=JSON.parse(T);if(!t(q))throw Error(`${f} must be a JSON object`);return q}function W1($){let f=0,T=0,q=(B,L)=>{if(f++,f>ff)throw Error(`Output schema exceeds the ${ff} node complexity limit`);if(L>$f)throw Error(`Output schema exceeds the ${$f} level depth limit`);if(Array.isArray(B)){for(let O of B)q(O,L+1);return}if(!t(B))return;if("$ref"in B){let O=B.$ref;if(typeof O!=="string"||!(O==="#"||O.startsWith("#/$defs/")||O.startsWith("#/definitions/")))throw Error("Output schema only supports self-contained local $ref values")}if("properties"in B&&t(B.properties)){if(T+=Object.keys(B.properties).length,T>Tf)throw Error(`Output schema exceeds the ${Tf} property limit`)}for(let O of Object.values(B))q(O,L+1)};q($,0)}function U1($){if(!$||$.length===0)return"Structured output does not match the requested schema";return $.slice(0,8).map((f)=>{return`${f.instancePath||"root"}: ${f.message??f.keyword}`}).join("; ")}function D1($){let f=new Y1({allErrors:!0,strict:!1,allowUnionTypes:!0,validateFormats:!1});try{return f.compile($)}catch(T){throw Error(`Invalid output schema: ${T instanceof Error?T.message:String(T)}`)}}function Of($){let f=qf($,"Output schema"),T=JSON.stringify(f);if(Buffer.byteLength(T)>s$)throw Error(`Output schema exceeds ${s$} bytes`);if(f.type!=="object")throw Error('Output schema root type must be "object"');W1(f);let B=D1(f),L=H1("sha256").update(T).digest("hex");return{schema:f,schemaDigest:L,declaration:{name:Bf,description:"Submit the final response as an object matching the requested JSON Schema. Call this exactly once after all requested work and verification are complete.",parameters:f,constrainedSampling:{type:"json_schema",strict:"prefer"}},validate(O){let C;try{C=qf(O,"Structured output")}catch(N){return{success:!1,message:N instanceof Error?N.message:String(N)}}let _=JSON.stringify(C);if(Buffer.byteLength(_)>e$)return{success:!1,message:`Structured output exceeds ${e$} bytes`};if(!B(C))return{success:!1,message:U1(B.errors)};return{success:!0,output:C}}}}function Lf($,f){if(!t($))return;let T=t($.structuredOutput)?$.structuredOutput:$;if(T.schemaDigest!==f.schemaDigest||!("output"in T))return;let q=f.validate(T.output);return q.success?q.output:void 0}function tT($,f){for(let T=$.length-1;T>=0;T--){let q=$[T];if(!q)continue;if(q.role==="user")return;if(q.role==="assistant"){let O=Lf(q.metadata,f);if(O)return{output:O,completed:!0};continue}if(q.role!=="tool"||q.name!==Bf)continue;let B=t(q.metadata)?q.metadata:void 0,L=Lf(B?.metadata,f);if(L)return{output:L,completed:!1}}return}var N0=U0("Service"),Cf=new Set(["queued","running","completed","failed","cancelled","interrupted"]),V$=new Set(["local","worktree"]),R1=new Set(["default","autoEdit","yolo","plan"]),A1=new Set(["applied","discarded","conflicted"]),z1=86400000;class Z$ extends Error{}function Nf($){try{return process.kill($,0),!0}catch(f){return f instanceof Error&&"code"in f&&f.code==="EPERM"}}function Gf($){if(!$||typeof $!=="object"||Array.isArray($))return;let f=$;if(["sessionId","name","branch","baseCommit","originalBranch","repositoryRoot","originalWorkspaceRoot","worktreeRoot","workspaceRoot"].some((q)=>typeof f[q]!=="string"||!f[q])||typeof f.sourceHadChanges!=="boolean"||f.sourceStateFingerprint!==void 0&&(typeof f.sourceStateFingerprint!=="string"||!/^[a-f0-9]{64}$/.test(f.sourceStateFingerprint)))return;return f}function _f($){if(!$||typeof $!=="object"||Array.isArray($))return;let f=$;if(!A1.has(String(f.status))||typeof f.updatedAt!=="string"||!Number.isFinite(Date.parse(f.updatedAt))||f.sourceCommit!==void 0&&(typeof f.sourceCommit!=="string"||!/^[a-f0-9]{40,64}$/.test(f.sourceCommit))||f.changedFiles!==void 0&&(typeof f.changedFiles!=="number"||!Number.isInteger(f.changedFiles)||f.changedFiles<0)||f.message!==void 0&&(typeof f.message!=="string"||!f.message.trim()||f.message.length>500))return;return{status:f.status,updatedAt:f.updatedAt,...typeof f.sourceCommit==="string"?{sourceCommit:f.sourceCommit}:{},...typeof f.changedFiles==="number"?{changedFiles:f.changedFiles}:{},...typeof f.message==="string"?{message:f.message}:{}}}function xf($){if(!$||typeof $!=="object"||Array.isArray($))return;let f=$;if(["changedFiles","additions","deletions","commits"].some((q)=>typeof f[q]!=="number"||!Number.isInteger(f[q])||f[q]<0))return;return f}function Jf($){if(!$||typeof $!=="object"||Array.isArray($))return;let f=$,T;if(f.outputSchema!==void 0)try{T=Of(f.outputSchema).schema}catch{return}if(f.version!==1||typeof f.prompt!=="string"||!f.prompt.trim()||f.prompt.length>32000||typeof f.sourceProjectPath!=="string"||!V.isAbsolute(f.sourceProjectPath)||!V$.has(f.isolation)||!b0(f.permissionMode)||f.title!==void 0&&(typeof f.title!=="string"||!f.title.trim()||f.title.length>200)||f.modelId!==void 0&&(typeof f.modelId!=="string"||!f.modelId.trim()||f.modelId.length>500)||f.reasoningEffort!==void 0&&!V0(f.reasoningEffort)||f.serviceTier!==void 0&&!J0(f.serviceTier)||f.responseVerbosity!==void 0&&!x0(f.responseVerbosity)||f.communicationStyle!==void 0&&!Z0(f.communicationStyle)||f.communicationStyleDigest!==void 0&&(typeof f.communicationStyleDigest!=="string"||!/^[a-f0-9]{64}$/.test(f.communicationStyleDigest))||f.projectInstructionsDigest!==void 0&&(typeof f.projectInstructionsDigest!=="string"||!/^[a-f0-9]{64}$/.test(f.projectInstructionsDigest)))return;let q;if(f.attachments!==void 0){if(!Array.isArray(f.attachments)||f.attachments.length>Qf)return;let B=0;for(let L of f.attachments){if(!L||typeof L!=="object"||Array.isArray(L))return;let O=L;if(!["file","image","url"].includes(String(O.type)))return;for(let C of["path","url","content","mimeType","name"])if(O[C]!==void 0&&typeof O[C]!=="string")return;B+=typeof O.content==="string"?Buffer.byteLength(O.content):0}if(B>Xf)return;q=f.attachments.map((L)=>{let O=L;return{type:O.type,...O.path!==void 0?{path:O.path}:{},...O.url!==void 0?{url:O.url}:{},...O.content!==void 0?{content:O.content}:{},...O.mimeType!==void 0?{mimeType:O.mimeType}:{},...O.name!==void 0?{name:O.name}:{}}})}return{version:1,prompt:f.prompt,...typeof f.title==="string"?{title:f.title}:{},sourceProjectPath:V.resolve(f.sourceProjectPath),isolation:f.isolation,permissionMode:f.permissionMode,...typeof f.modelId==="string"?{modelId:f.modelId}:{},...V0(f.reasoningEffort)?{reasoningEffort:f.reasoningEffort}:{},...J0(f.serviceTier)?{serviceTier:f.serviceTier}:{},...x0(f.responseVerbosity)?{responseVerbosity:f.responseVerbosity}:{},...Z0(f.communicationStyle)?{communicationStyle:f.communicationStyle}:{},...typeof f.communicationStyleDigest==="string"?{communicationStyleDigest:f.communicationStyleDigest}:{},...typeof f.projectInstructionsDigest==="string"?{projectInstructionsDigest:f.projectInstructionsDigest}:{},...q?{attachments:q}:{},...T?{outputSchema:T}:{}}}function b0($){return typeof $==="string"&&R1.has($)}function Vf($){if(!$||typeof $!=="object"||Array.isArray($))return;let f=$;if(typeof f.sessionId!=="string"||!f.sessionId||typeof f.projectPath!=="string"||!V.isAbsolute(f.projectPath))return;return{sessionId:f.sessionId,projectPath:V.resolve(f.projectPath)}}var Df={stat($){return E0($,{bigint:!0})},readFile($){return a($,"utf-8")}},_0=Df;function Rq($){_0=$}function Aq(){_0=Df}class Rf extends Error{constructor($){super(`Session has no durable creation record: ${$}`);this.name="SessionMissingCreationError"}}class f0 extends Error{sessionId;archivedBySessionId;code="BLADE_SESSION_ARCHIVED";constructor($,f){super($===f?`Session is archived: ${$}`:`Session is archived by ancestor ${f}: ${$}`);this.sessionId=$;this.archivedBySessionId=f;this.name="SessionArchivedError"}}class P extends Error{code="BLADE_SESSION_ARCHIVE_CONFLICT";constructor($){super($);this.name="SessionArchiveConflictError"}}function B$($,f){return`${$}\x00${f}`}function M1($){if($.kind==="base")return`/review base ${$.baseSha??$.label}`;if($.kind==="commit")return`/review commit ${$.commitSha??$.label}`;return"/review uncommitted"}function Af($){return typeof $==="string"&&$.length<=64&&Number.isFinite(Date.parse($))}function g1($){let f=new Map($.map((T)=>[B$(T.projectPath,T.sessionId),T]));return $.map((T)=>{let q=T,B=new Set;while(q){let _=B$(q.projectPath,q.sessionId);if(B.has(_))break;if(B.add(_),Af(q.archivedAt))return{...T,archivedAt:q.archivedAt,archivedBySessionId:q.sessionId};q=q.parentId?f.get(B$(q.projectPath,q.parentId)):void 0}let{archivedAt:L,archivedBySessionId:O,...C}=T;return C})}function O$($,f){let T=g1($);if(f===null)return T;return T.filter((q)=>Boolean(q.archivedAt)===f)}class X{static toUISafeMessages($){let f=Date.now(),T=$.length,q=[];return $.forEach((B,L)=>{if(B.role!=="user"&&B.role!=="assistant"||!u$(B))return;let O;if(typeof B.content==="string")O=B.content;else if(Array.isArray(B.content))O=B.content.map((x)=>x.type==="text"?x.text:"[Image]").join("");else O="";let C=O.trim();if(!C)return;let _=A0(B.metadata),N=_?d$(_):C,G=q[q.length-1];if(G&&G.role===B.role&&G.content===N)return;q.push({id:`restored-${f}-${L}`,role:B.role,content:N,timestamp:f-(T-L)*1000,metadata:B.metadata&&typeof B.metadata==="object"?B.metadata:void 0})}),q}static async listSessionPage($={}){let f=G$($),T=await this.listSessionPageFromProjection(f);if(T)return T;let B=(await this.scanStoredSessions(f.cwd??void 0,f.includeSubagents,f.cursor?5000:0,f.archived)).sort(_$),L=x$(B,f);return{sessions:L.sessions.map((O)=>this.toPublicMetadata(O)),nextCursor:L.nextCursor}}static async listSessionPageFromProjection($){let f=Wf($);try{let T=await g0();if(!T)return null;await J$(T,this.projectionDeriver(),$.cursor?5000:0);let q=[],B=[];if($.cwd)q.push("s.project_path = ?"),B.push($.cwd);if(!$.includeSubagents)q.push("s.is_subagent = 0");if(q.push($.archived?"a.session_id IS NOT NULL":"a.session_id IS NULL"),f){q.push(`(
|
|
68
|
-
s.last_message_time < ?
|
|
69
|
-
OR (
|
|
70
|
-
s.last_message_time = ?
|
|
71
|
-
AND (
|
|
72
|
-
s.project_sort_key > ?
|
|
73
|
-
OR (s.project_sort_key = ? AND s.session_sort_key > ?)
|
|
74
|
-
)
|
|
75
|
-
)
|
|
76
|
-
)`);let _=N$(f.projectPath);B.push(f.lastMessageTime,f.lastMessageTime,_,_,N$(f.sessionId))}let L=T.prepare(`WITH RECURSIVE archive_members(
|
|
77
|
-
project_path, session_id, archive_root_id, effective_archived_at, depth
|
|
78
|
-
) AS (
|
|
79
|
-
SELECT project_path, session_id, session_id, archived_at, 0
|
|
80
|
-
FROM sessions
|
|
81
|
-
WHERE archived_at IS NOT NULL
|
|
82
|
-
UNION ALL
|
|
83
|
-
SELECT child.project_path, child.session_id, parent.archive_root_id,
|
|
84
|
-
parent.effective_archived_at, parent.depth + 1
|
|
85
|
-
FROM sessions child
|
|
86
|
-
JOIN archive_members parent
|
|
87
|
-
ON child.project_path = parent.project_path
|
|
88
|
-
AND child.parent_id = parent.session_id
|
|
89
|
-
WHERE parent.depth < 128
|
|
90
|
-
),
|
|
91
|
-
ranked_archive AS (
|
|
92
|
-
SELECT project_path, session_id, archive_root_id,
|
|
93
|
-
effective_archived_at,
|
|
94
|
-
ROW_NUMBER() OVER (
|
|
95
|
-
PARTITION BY project_path, session_id
|
|
96
|
-
ORDER BY depth ASC, archive_root_id ASC
|
|
97
|
-
) AS rank
|
|
98
|
-
FROM archive_members
|
|
99
|
-
)
|
|
100
|
-
SELECT s.metadata_json, a.archive_root_id, a.effective_archived_at
|
|
101
|
-
FROM sessions s
|
|
102
|
-
LEFT JOIN ranked_archive a
|
|
103
|
-
ON a.project_path = s.project_path
|
|
104
|
-
AND a.session_id = s.session_id
|
|
105
|
-
AND a.rank = 1
|
|
106
|
-
${q.length>0?`WHERE ${q.join(" AND ")}`:""}
|
|
107
|
-
ORDER BY s.last_message_time DESC,
|
|
108
|
-
s.project_sort_key ASC,
|
|
109
|
-
s.session_sort_key ASC
|
|
110
|
-
LIMIT ?`).all(...B,$.limit+1),O=await Promise.all(L.map(async(_)=>{let N=JSON.parse(_.metadata_json);if(_.archive_root_id&&_.effective_archived_at)return this.reconcileInterruptedTask({...N,archivedAt:_.effective_archived_at,archivedBySessionId:_.archive_root_id});let{archivedAt:G,archivedBySessionId:x,...J}=N;return this.reconcileInterruptedTask(J)})),C=x$(O,$);return{sessions:C.sessions.map((_)=>this.toPublicMetadata(_)),nextCursor:C.nextCursor}}catch{return null}}static async listSessions($={}){let f=G$($),T=await this.scanStoredSessions(f.cwd??void 0,f.includeSubagents,0,f.archived),q=new Set;return T.sort(_$).flatMap((B)=>{let L=`${B.projectPath}\x00${B.sessionId}`;if(q.has(L))return[];return q.add(L),[this.toPublicMetadata(B)]})}static async collectStaleEmptySessions($={}){let f=$.now??Date.now(),T=$.olderThanMs??z1;if(!Number.isFinite(T)||T<0)throw Error("Stale empty session age must be a non-negative number");let q=$.projectPath?[{storagePath:q0(this.resolveCatalogWorkspace($.projectPath)),projectPath:this.resolveCatalogWorkspace($.projectPath)}]:await this.listAllProjectStorageDirectories(),B=0;for(let L of q){let O;try{O=await L$(L.storagePath)}catch(C){if(C.code==="ENOENT")continue;throw C}for(let C of O){if(!C.endsWith(".jsonl"))continue;let _=C.slice(0,-6);if(!Kf(_))continue;let N=V.join(L.storagePath,C);try{let x=await E0(N);if(f-x.mtimeMs<T)continue;if(await Promise.all([E0(V.join(L.storagePath,`${_}.inbox.json`)).then(()=>!0).catch(()=>!1),E0(G0(L.projectPath,_)).then(()=>!0).catch(()=>!1)]).then((Z)=>Z.some(Boolean)))continue}catch(x){if(x.code==="ENOENT")continue;throw x}let G;try{G=await n.acquire(_,L.projectPath)}catch(x){if(x instanceof h)continue;throw x}try{if(!await new I(N).deleteValidated((J)=>J.length===1&&J[0]?.type==="session_created"&&J[0].data.relationType!=="subagent"))continue;B++,await $0(V.join(L.storagePath,`${_}.inbox.json`),{force:!0}),await $0(G0(L.projectPath,_),{force:!0}),await this.removeFromProjection(_,L.projectPath)}catch(x){N0.warn(`[SessionService] Skipping stale empty session cleanup: ${_}`,x)}finally{await G.release()}}}return B}static async findSessionMetadata($,f){if(A($),f!==void 0){if(!V.isAbsolute(f))throw Error("Session catalog cwd must be absolute");let q=V.resolve(f),B=this.getSessionFilePath(q,$);try{let L=await this.readStoredSessionMetadata(B,$,q);if(L.projectPath!==q)return;if(!L.parentId||L.archivedAt)return this.toPublicMetadata(O$([L],null)[0]??L);let O=await this.scanStoredSessions(q,!0,0,null);return this.toPublicMetadata(O.find((C)=>C.sessionId===$)??L)}catch(L){if(L.code==="ENOENT")return;throw L}}let T=(await this.scanStoredSessions(void 0,!0,0,null)).filter((q)=>q.sessionId===$);if(T.length===0)return;if(T.length>1)throw Error(`Ambiguous session ID: ${$}`);return this.toPublicMetadata(T[0])}static async loadSession($,f){try{if(f){if(!V.isAbsolute(f))throw Error("Session catalog cwd must be absolute");let q=V.resolve(f),B=this.getSessionFilePath(q,$);try{return await this.loadSessionFromFile(B,$,q)}catch(L){if(L.code==="ENOENT")throw Error(`未找到会话: ${$}`);throw L}}let T=(await this.scanStoredSessions(void 0,!0,0,null)).find((q)=>q.sessionId===$);if(!T)throw Error(`未找到会话: ${$}`);return await this.loadSessionFromFile(T.filePath,$)}catch(T){throw N0.error(`[SessionService] 加载会话失败 (${$}):`,T),T}}static async loadSessionModelContext($,f){try{if(f){if(!V.isAbsolute(f))throw Error("Session catalog cwd must be absolute");let q=V.resolve(f),B=this.getSessionFilePath(q,$);try{return await this.loadSessionModelContextFromFile(B,$,q)}catch(L){if(L.code==="ENOENT")throw Error(`未找到会话: ${$}`);throw L}}let T=(await this.scanStoredSessions(void 0,!0,0,null)).find((q)=>q.sessionId===$);if(!T)throw Error(`未找到会话: ${$}`);return await this.loadSessionModelContextFromFile(T.filePath,$)}catch(T){throw N0.error(`[SessionService] 加载模型上下文失败 (${$}):`,T),T}}static async exportSessionMarkdown($,f,T={}){A($);let q=this.resolveCatalogWorkspace(f),B=m(q,$),L;try{L=await this.readStableSessionSnapshot(B,$)}catch(_){throw this.sanitizeStoredSessionError(_,$)}let O=this.projectMetadataFromEntries(L,$,q,B);if(O.projectPath!==q)throw Error(`Session export workspace mismatch: ${$}`);let C=O.archivedAt;if(!C&&O.parentId)C=(await this.findArchivedAncestor(O.parentId,q))?.archivedAt;return a$(L,{...O,archivedAt:C},T)}static async listRewindCheckpoints($,f){A($);let T=this.resolveCatalogWorkspace(f),q=m(T,$),B=await this.readStableSessionSnapshot(q,$);this.validateSessionWorkspace(B,$,T);let L=new D0({sessionId:$,workspaceRoot:T});await L.initialize();let O=Hf(B),C=[];for(let _ of O){let N=C$(B,_.messageId),G=await L.previewRewind(N.snapshotMessageIds);C.push({..._,fileCount:G.files.length})}return C}static async rewindSession($,f,T){A($);let q=this.resolveCatalogWorkspace(f);await this.assertSessionWritable($,q);let B=m(q,$),L=new I(B),O;try{await L.appendValidatedAsync(async(C)=>{this.validateSessionWorkspace(C,$,q);let _=C$(C,T.targetMessageId),N=new D0({sessionId:$,workspaceRoot:q});await N.initialize();let G=await N.previewRewind(_.snapshotMessageIds),x=T.mode==="conversation"?await N.commitSnapshots(_.snapshotMessageIds):await N.rewindSnapshots(_.snapshotMessageIds),J=new Date().toISOString(),Z={id:j(),sessionId:$,timestamp:J,type:"session_rewound",cwd:q,gitBranch:c(q),version:p(),data:{rewindId:j(),targetMessageId:T.targetMessageId,mode:T.mode,restoredFiles:T.mode==="conversation"?[]:x.files,createdAt:J}},E=u([...C,Z]);return O={checkpoint:{..._.checkpoint,fileCount:G.files.length},mode:T.mode,removedTurns:_.removedTurns,restoredFiles:Z.data.restoredFiles,messages:this.convertJSONLToMessages(E)},Z})}catch(C){throw this.sanitizeStoredSessionError(C,$)}if(!O)throw Error(`Session rewind did not produce a result: ${$}`);for(let C of O.restoredFiles)l.getInstance().clearFileRecord(C);return O}static async forkSession($,f){A($);let T=f.newSessionId??`fork-${Date.now()}-${j(8)}`;A(T);let q=this.resolveForkWorkspace(f.sourceProjectPath),B=this.resolveForkWorkspace(f.targetProjectPath);if(q!==B)throw Error("Session forks must stay in the source workspace");let L=m(q,$),O=await this.readStableSessionSnapshot(L,$),C=this.getSessionCreatedEntry(O,$);if(C.data.sessionId!==$)throw Error("Fork source session_created.data.sessionId must match the requested session ID");if(!V.isAbsolute(C.cwd)||V.resolve(C.cwd)!==q)throw Error("Fork source session_created.cwd must resolve to the requested source workspace");let _=this.projectMetadataFromEntries(O,$,q,L);if(_.archivedAt)throw new f0($,$);if(_.parentId){let Y=await this.findArchivedAncestor(_.parentId,q);if(Y)throw new f0($,Y.sessionId)}let N=u(O),G=new Date().toISOString(),x=C.data.rootId||$,J=c(B),Z=p(),{status:E,taskStatus:M,taskStatusReason:b,taskFailure:W,taskStartedAt:s,taskCompletedAt:e,taskOwnerPid:y,taskPromptSummary:S,taskDispatch:R,taskModelId:D,taskRetriedFrom:z,taskDelivery:K,taskIsolation:g,taskSourceProjectPath:w0,taskWorktree:F$,taskDiffStat:K$,taskQueuePosition:Q$,taskQueueDepth:X$,taskConcurrencyLimit:H$,pendingInteraction:k0,...y0}=C.data,S0={id:j(),sessionId:T,timestamp:G,type:"session_created",cwd:B,gitBranch:J,version:Z,data:{...y0,sessionId:T,rootId:x,parentId:$,relationType:"fork",taskStatus:"completed",taskCompletedAt:G,taskIsolation:"local",taskSourceProjectPath:B,createdAt:G,updatedAt:G}},j0=N.filter((Y)=>Y.type!=="session_created"&&Y.type!=="inbox_acknowledged"&&Y.type!=="interaction_requested"&&Y.type!=="interaction_responded"&&Y.type!=="interaction_recovered"&&Y.type!=="review_started"&&Y.type!=="review_completed").map((Y)=>{let i={...Y,id:j(),sessionId:T,cwd:B,gitBranch:J,version:Z};if(Y.type==="session_updated"){let{status:K0,taskStatus:U,taskStatusReason:v0,taskFailure:E1,taskStartedAt:b1,taskCompletedAt:w1,taskOwnerPid:k1,taskPromptSummary:y1,taskDispatch:S1,taskModelId:j1,taskRetriedFrom:m1,taskDelivery:I1,taskIsolation:v1,taskSourceProjectPath:u1,taskWorktree:P1,taskDiffStat:h1,taskQueuePosition:n1,taskQueueDepth:l1,taskConcurrencyLimit:c1,pendingInteraction:p1,...zf}=Y.data;return{...i,type:"session_updated",data:{...zf,sessionId:T,rootId:x,parentId:$,relationType:"fork"}}}if(Y.type==="message_created"){let{inboxMessageId:K0,...U}=Y.data;return{...i,type:"message_created",data:U}}return i}),m0={id:j(),sessionId:T,timestamp:G,type:"session_updated",cwd:B,gitBranch:J,version:Z,data:{sessionId:T,rootId:x,parentId:$,relationType:"fork",taskStatus:"completed",taskStatusReason:null,taskFailure:null,taskStartedAt:null,taskCompletedAt:G,taskOwnerPid:null,taskIsolation:"local",taskSourceProjectPath:B,taskWorktree:null,taskDiffStat:null,taskDelivery:null,taskQueuePosition:null,taskQueueDepth:null,taskConcurrencyLimit:null,updatedAt:G}},T0=[S0,...j0,m0],F0=m(B,T);try{await new I(F0).createExclusive(T0)}catch(Y){if(Y.code==="EEXIST")throw Error(`Fork session already exists: ${T}`,{cause:Y});throw Y}let I0=this.projectMetadataFromEntries(T0,T,B,F0);return{sessionId:T,parentSessionId:$,projectPath:B,messages:this.convertJSONLToMessages(T0),metadata:this.toPublicMetadata(I0)}}static async deleteSession($,f){if(A($),f){if(!V.isAbsolute(f))throw Error("Session catalog cwd must be absolute");let q=V.resolve(f),B=this.getSessionFilePath(q,$),L=new I(B),O;try{O=await L.deleteValidated((C)=>{return this.projectMetadataFromEntries(C,$,q,B).projectPath===q})}catch(C){if(!this.isCorruptSessionJSONLError(C))throw C;O=await L.delete()}if(!O)return 0;return await $0(V.join(V.dirname(B),`${$}.inbox.json`),{force:!0}),await $0(G0(q,$),{force:!0}),await this.removeFromProjection($,q),1}let T=(await this.scanStoredSessions(void 0,!0)).filter((q)=>q.sessionId===$);if(T.length===0)return 0;return await Promise.all(T.map(async(q)=>{await new I(q.filePath).delete(),await $0(V.join(V.dirname(q.filePath),`${q.sessionId}.inbox.json`),{force:!0}),await $0(G0(q.projectPath,q.sessionId),{force:!0}),await this.removeFromProjection(q.sessionId,q.projectPath)})),T.length}static async removeFromProjection($,f){try{let T=await g0();if(T)Uf(T,$,f)}catch{}}static validateTaskMetadataUpdate($,f){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&&!p0($.taskFailure))throw Error("Invalid session task failure");if($.taskDispatch!==void 0&&$.taskDispatch!==null&&!Jf($.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&&!b0($.permissionMode))throw Error("Invalid session permission mode");if($.reasoningEffort!==void 0&&$.reasoningEffort!==null&&!V0($.reasoningEffort))throw Error("Invalid session reasoning effort");if($.serviceTier!==void 0&&$.serviceTier!==null&&!J0($.serviceTier))throw Error("Invalid session service tier");if($.responseVerbosity!==void 0&&$.responseVerbosity!==null&&!x0($.responseVerbosity))throw Error("Invalid session response verbosity");if($.communicationStyle!==void 0&&$.communicationStyle!==null&&!Z0($.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&&!Vf($.taskRetriedFrom))throw Error("Invalid session task retry source");if($.taskDelivery!==void 0&&$.taskDelivery!==null&&!_f($.taskDelivery))throw Error("Invalid session task delivery");if($.taskIsolation!==void 0&&$.taskIsolation!==null&&!V$.has($.taskIsolation))throw Error(`Invalid session task isolation: ${String($.taskIsolation)}`);if($.taskSourceProjectPath!==void 0&&$.taskSourceProjectPath!==null&&!V.isAbsolute($.taskSourceProjectPath))throw Error("Session task source project path must be absolute");if($.taskWorktree!==void 0&&$.taskWorktree!==null){let T=Gf($.taskWorktree);if(!T||T.sessionId!==f||![T.repositoryRoot,T.originalWorkspaceRoot,T.worktreeRoot,T.workspaceRoot].every((q)=>V.isAbsolute(q)))throw Error("Invalid session task worktree metadata")}if($.taskDiffStat!==void 0&&$.taskDiffStat!==null&&!xf($.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($,f,T={}){A($),X.validateTaskMetadataUpdate(T,$);let q=X.resolveCatalogWorkspace(f);if(T.taskWorktree&&V.resolve(T.taskWorktree.workspaceRoot)!==q)throw Error("Session task worktree must match the catalog workspace");let B=new Date().toISOString(),L={id:j(),sessionId:$,timestamp:B,type:"session_created",cwd:q,gitBranch:c(q),version:p(),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:B,updatedAt:B}},O=X.getSessionFilePath(q,$);return await new I(O).createExclusive([L]),X.toPublicMetadata(X.projectMetadataFromEntries([L],$,q,O))}static async assertSessionWritable($,f){let T=await this.findSessionMetadata($,f);if(!T)throw Error(`Session not found: ${$}`);if(T.archivedAt)throw new f0($,T.archivedBySessionId??$);return T}static async findArchivedAncestor($,f){let T=new Set,q=$;while(q){if(T.has(q))throw Error("Session lineage contains a cycle");T.add(q),A(q);let B=m(f,q),L;try{L=await a(B,"utf8")}catch(C){if(C.code==="ENOENT")return;throw C}let O=this.projectMetadataFromEntries(this.parseStoredSession(L,q),q,f,B);if(O.projectPath!==f)throw Error("Session lineage escapes the requested workspace");if(O.archivedAt)return{sessionId:O.sessionId,archivedAt:O.archivedAt};q=O.parentId}return}static async listSessionArchiveMembers($,f){A($);let T=this.resolveCatalogWorkspace(f),q=await this.scanStoredSessions(T,!0,0,null);if(!q.some((O)=>O.sessionId===$))throw Error(`Session not found: ${$}`);let B=new Set([$]),L=!0;while(L){L=!1;for(let O of q)if(O.parentId&&B.has(O.parentId)&&!B.has(O.sessionId))B.add(O.sessionId),L=!0}return q.filter((O)=>B.has(O.sessionId)).sort((O,C)=>O.sessionId.localeCompare(C.sessionId)).map((O)=>this.toPublicMetadata(O))}static async archiveSession($,f){A($);let T=this.resolveCatalogWorkspace(f),q=await this.findSessionMetadata($,T);if(!q)throw Error(`Session not found: ${$}`);if(q.archivedAt)return q;let B=await this.listSessionArchiveMembers($,T),L=B.find((C)=>C.taskStatus==="queued"||C.taskStatus==="running");if(L)throw new P(`Stop session ${L.sessionId} before archiving this session tree`);let O=[];try{for(let G of B)O.push(await n.acquire(G.sessionId,T));let C=m(T,$),_=new I(C),N=[];return await _.appendValidated((G)=>{let x=this.projectMetadataFromEntries(G,$,T,C);if(x.archivedAt)throw new P(`Session archive state changed concurrently: ${$}`);if(x.taskStatus==="queued"||x.taskStatus==="running")throw new P(`Stop session ${$} before archiving it`);let J=new Date().toISOString(),Z={id:j(),sessionId:$,timestamp:J,type:"session_updated",cwd:T,gitBranch:c(T),version:p(),data:{sessionId:$,archivedAt:J,updatedAt:J}};return N=[...G,Z],Z}),this.toPublicMetadata({...this.projectMetadataFromEntries(N,$,T,C),archivedBySessionId:$})}catch(C){if(C instanceof P)throw C;if(C instanceof h)throw new P(C.message);throw this.sanitizeStoredSessionError(C,$)}finally{for(let C of O.reverse())await C.release()}}static async unarchiveSession($,f){A($);let T=this.resolveCatalogWorkspace(f),q=await this.findSessionMetadata($,T);if(!q)throw Error(`Session not found: ${$}`);if(!q.archivedAt)return q;if(q.archivedBySessionId&&q.archivedBySessionId!==$)throw new P(`Unarchive ancestor ${q.archivedBySessionId} to restore session ${$}`);let B;try{B=await n.acquire($,T);let L=m(T,$),O=new I(L),C=[];return await O.appendValidated((_)=>{if(!this.projectMetadataFromEntries(_,$,T,L).archivedAt)throw new P(`Session archive state changed concurrently: ${$}`);let G=new Date().toISOString(),x={id:j(),sessionId:$,timestamp:G,type:"session_updated",cwd:T,gitBranch:c(T),version:p(),data:{sessionId:$,archivedAt:null,updatedAt:G}};return C=[..._,x],x}),this.toPublicMetadata(this.projectMetadataFromEntries(C,$,T,L))}catch(L){if(L instanceof P)throw L;if(L instanceof h)throw new P(L.message);throw this.sanitizeStoredSessionError(L,$)}finally{await B?.release()}}static async updateSessionMetadata($,f,T){if(A($),X.validateTaskMetadataUpdate(T,$),T.taskStatus!==void 0&&!Cf.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 q=X.resolveCatalogWorkspace(f);if(T.taskWorktree&&V.resolve(T.taskWorktree.workspaceRoot)!==q)throw Error("Session task worktree must match the catalog workspace");let B=X.getSessionFilePath(q,$),L=new I(B),O=[];try{await L.appendValidatedAsync(async(C)=>{let _=X.getSessionCreatedEntry(C,$);if(_.data.sessionId!==$)throw Error(`Session metadata creation record sessionId mismatch: ${$}`);if(!V.isAbsolute(_.cwd)||V.resolve(_.cwd)!==q)throw Error(`Session metadata creation record cwd mismatch: ${$}`);let N=X.projectMetadataFromEntries(C,$,q,B);if(N.archivedAt)throw new f0($,$);if(N.parentId){let J=await X.findArchivedAncestor(N.parentId,q);if(J)throw new f0($,J.sessionId)}let G=new Date().toISOString(),x={id:j(),sessionId:$,timestamp:G,type:"session_updated",cwd:q,gitBranch:c(q),version:p(),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:G}};return O=[...C,x],x})}catch(C){throw X.sanitizeStoredSessionError(C,$)}return X.toPublicMetadata(X.projectMetadataFromEntries(O,$,q,B))}static async setSessionPermissionMode($,f,T){if(A($),!b0(T))throw Error("Invalid session permission mode");let q=X.resolveCatalogWorkspace(f),B=await X.findSessionMetadata($,q);if(B?.permissionMode===T)return B;if(B)return X.updateSessionMetadata($,q,{permissionMode:T});try{return await X.createSessionMetadata($,q,{taskStatus:"completed",permissionMode:T})}catch(L){if(L.code!=="EEXIST")throw L;return X.updateSessionMetadata($,q,{permissionMode:T})}}static async findSessionTaskWorktree($,f){A($);let T=X.resolveCatalogWorkspace(f),q=X.getSessionFilePath(T,$);try{return(await X.readStoredSessionMetadata(q,$,T)).taskWorktree}catch(B){if(B.code==="ENOENT")return;throw X.sanitizeStoredSessionError(B,$)}}static async findSessionTaskDispatch($,f){A($);let T=X.resolveCatalogWorkspace(f),q=X.getSessionFilePath(T,$);try{return(await X.readStoredSessionMetadata(q,$,T)).taskDispatch}catch(B){if(B.code==="ENOENT")return;throw X.sanitizeStoredSessionError(B,$)}}static async loadSessionFromFile($,f,T){let q=await a($,"utf-8"),B=this.parseStoredSession(q,f);if(T!==void 0){if(this.projectMetadataFromEntries(B,f,T,$).projectPath!==T)throw Error(`未找到会话: ${f}`)}return this.convertJSONLToMessages(B)}static async loadSessionModelContextFromFile($,f,T){let q=await a($,"utf-8"),B=this.parseStoredSession(q,f);if(T!==void 0){if(this.projectMetadataFromEntries(B,f,T,$).projectPath!==T)throw Error(`未找到会话: ${f}`)}return this.convertJSONLToModelContext(B)}static convertJSONLToModelContext($){let f=u($),T=-1,q;for(let L=0;L<f.length;L++){let O=f[L];if(O?.type!=="part_created"||O.data.partType!=="summary")continue;let C=O.data.payload;if(T=L,q=g$(C.replacementMessages),!q)q=[{role:"user",content:C.text??"",metadata:O.data.payload}]}if(T<0||!q)return this.convertJSONLToMessages(f);let B=this.convertJSONLToMessages(f.slice(T+1));return[...q,...B]}static convertJSONLToMessages($){let f=[],T=new Map,q=new Map,B=new Map,L=new Map,O=new Map,C=u($),_=new Set;for(let N of C){if(N.type==="message_created"){let G=N.data.metadata&&typeof N.data.metadata==="object"&&!Array.isArray(N.data.metadata)?N.data.metadata:void 0,x=G?.codeReview&&typeof G.codeReview==="object"&&!Array.isArray(G.codeReview)?G.codeReview:void 0;if(x?.phase==="completed"&&typeof x.reviewId==="string")_.add(x.reviewId);let J=N.data.role==="assistant"&&N.data.parentMessageId?B.get(N.data.parentMessageId):void 0,Z=J??{role:N.data.role,content:"",...N.data.metadata||N.data.inboxMessageId?{metadata:{...N.data.metadata&&typeof N.data.metadata==="object"&&!Array.isArray(N.data.metadata)?N.data.metadata:{},...N.data.inboxMessageId?{inboxMessageId:N.data.inboxMessageId}:{}}}:{}};if(T.set(N.data.messageId,Z),q.set(N.data.messageId,[]),!J)f.push(Z)}if(N.type==="part_created"){if(N.data.partType==="reasoning"){let G=T.get(N.data.messageId);if(G){let x=N.data.payload;G.reasoningContent=(G.reasoningContent??"")+(x.text??"")}}if(N.data.partType==="text"){let G=T.get(N.data.messageId);if(G){let x=N.data.payload,J=q.get(N.data.messageId);if(J)J.push({type:"text",text:x.text??""}),G.content=Zf(J);else G.content=x.text??""}}if(N.data.partType==="image"){let G=T.get(N.data.messageId);if(G){let x=N.data.payload,J=q.get(N.data.messageId);if(J&&x.dataUrl)J.push({type:"image_url",image_url:{url:x.dataUrl}}),G.content=Zf(J)}}if(N.data.partType==="tool_call"){let G=T.get(N.data.messageId);if(G?.role!=="assistant"){if(G=B.get(N.data.messageId),!G)G={role:"assistant",content:"",tool_calls:[]},B.set(N.data.messageId,G),f.push(G)}if(G.role==="assistant"){let x=N.data.payload,J=x.toolCallId??N.data.partId;L.set(N.data.partId,J),O.set(J,G),G.tool_calls??=[],G.tool_calls.push({id:J,type:"function",function:{name:x.toolName??"unknown",arguments:JSON.stringify(x.input??{})}})}}if(N.data.partType==="tool_result"){let G=N.data.payload,x=v$(G),J=x.error?`Error: ${x.error.message}`:typeof x.llmContent==="string"?x.llmContent:JSON.stringify(x.llmContent),Z=G;f.push({role:"tool",content:J,tool_call_id:L.get(N.data.messageId)??G.toolCallId,name:G.toolName,metadata:Z})}if(N.data.partType==="summary"){let G=N.data.payload,x=N.data.payload;f.push({role:"system",content:G.text??"",metadata:x})}if(N.data.partType==="subtask_ref"){let G=T.get(N.data.messageId)??O.get(N.data.messageId);if(G){let x=N.data.payload,J=G.metadata??{};G.metadata={...J,subtaskRef:x}}}}}for(let N of Y0(C)){if(N.completion===void 0||_.has(N.start.reviewId))continue;f.push({role:"assistant",content:k$(N.start,N.completion),metadata:{codeReview:{...y$(N.start,N.completion),synthetic:!0}}})}return f}static projectionDeriver(){return($,f,T)=>{try{let q=m(T,f);return this.projectMetadataFromEntries($,f,T,q)}catch{return null}}}static projectionDeriverForSearch(){return this.projectionDeriver()}static async scanStoredSessionsFromProjection($,f,T=0,q=!1){try{let B=await g0();if(!B)return null;await J$(B,this.projectionDeriver(),T);let L=$?B.prepare("SELECT metadata_json, is_subagent FROM sessions WHERE project_path=?").all($):B.prepare("SELECT metadata_json, is_subagent FROM sessions").all(),O=[];for(let C of L){if(!f&&C.is_subagent===1)continue;try{let _=JSON.parse(C.metadata_json);if($!==void 0&&_.projectPath!==$)continue;O.push(_)}catch{}}return O$(await Promise.all(O.map((C)=>this.reconcileInterruptedTask(C))),q)}catch{return null}}static async scanStoredSessions($,f=!1,T=0,q=!1){let B=$?V.resolve($):void 0,L=await this.scanStoredSessionsFromProjection(B,f,T,q);if(L)return L;let O=B?[{storagePath:q0(B),projectPath:B}]:await this.listAllProjectStorageDirectories(),C=[];for(let _ of O){let N;try{N=await L$(_.storagePath)}catch(G){if(G.code==="ENOENT")continue;throw G}for(let G of N){if(!G.endsWith(".jsonl"))continue;let x=G.slice(0,-6),J=V.join(_.storagePath,G);try{let Z=await this.readStoredSessionMetadata(J,x,_.projectPath);if(B!==void 0&&Z.projectPath!==B){N0.warn(`[SessionService] Skipping out-of-scope session transcript: ${x}`);continue}if(!f&&Z.relationType==="subagent")continue;C.push(Z)}catch(Z){let E=Z.code;if(E==="ENOENT")continue;if(E)throw Z;N0.warn(`[SessionService] Skipping invalid session transcript: ${x}`)}}}return O$(C,q)}static async listAllProjectStorageDirectories(){let $=V.join(C0(),"projects"),f;try{f=await L$($,{withFileTypes:!0,encoding:"utf8"})}catch(T){if(T.code==="ENOENT")return[];throw T}return f.filter((T)=>T.isDirectory()).map((T)=>({storagePath:V.join($,T.name),projectPath:Ff(T.name)}))}static async readStoredSessionMetadata($,f,T){let q=await a($,"utf-8"),B=this.parseStoredSession(q,f);return this.reconcileInterruptedTask(this.projectMetadataFromEntries(B,f,T,$))}static async reconcileInterruptedTask($){let f=$.taskOwnerPid;if($.taskStatus!=="running"||f===void 0||Nf(f))return $;let T;try{T=await n.acquire($.sessionId,$.projectPath)}catch(L){if(!(L instanceof h))throw L;let O=await a($.filePath,"utf-8");return this.projectMetadataFromEntries(this.parseStoredSession(O,$.sessionId),$.sessionId,$.projectPath,$.filePath)}let q=new I($.filePath),B;try{try{await q.appendValidated((L)=>{let O=this.projectMetadataFromEntries(L,$.sessionId,$.projectPath,$.filePath);if(O.taskStatus!=="running"||O.taskOwnerPid!==f||Nf(f))throw new Z$;let C=new Date().toISOString(),_={id:j(),sessionId:$.sessionId,timestamp:C,type:"session_updated",cwd:$.projectPath,gitBranch:c($.projectPath),version:p(),data:{sessionId:$.sessionId,taskStatus:"interrupted",taskStatusReason:"Task owner process exited before completion",taskCompletedAt:C,taskOwnerPid:null,taskQueuePosition:null,taskQueueDepth:null,updatedAt:C}};return B=[...L,_],_})}catch(L){if(!(L instanceof Z$))throw L}if(!B){let L=await a($.filePath,"utf-8");B=this.parseStoredSession(L,$.sessionId)}return this.projectMetadataFromEntries(B,$.sessionId,$.projectPath,$.filePath)}finally{await T.release()}}static projectMetadataFromEntries($,f,T,q){if($.length===0)throw Error(`Empty session transcript: ${f}`);let B=this.getSessionCreatedEntry($,f),L=$.reduce((U,v0)=>v0.type==="session_updated"?{...U,...v0.data}:U,{...B.data}),O=u($),C=w$(b$(O)),N=Y0(O).at(-1),G=O.findLastIndex((U)=>U.type==="review_started"&&U.data.reviewId===N?.start.reviewId||U.type==="review_completed"&&U.data.reviewId===N?.start.reviewId),x=O.findLastIndex((U)=>(U.type==="session_created"||U.type==="session_updated")&&Object.hasOwn(U.data,"taskStatus")),J=N!==void 0&&G>x,Z=J?N.completion===void 0?"running":N.completion.status==="completed"||N.completion.status==="stale"?"completed":N.completion.status==="aborted"?"cancelled":N.completion.status==="interrupted"?"interrupted":"failed":void 0,E=O.filter((U)=>U.type==="message_created"&&["user","assistant"].includes(U.data.role)).length,M=O.some((U)=>U.type==="part_created"&&U.data.partType==="tool_result"&&typeof U.data.payload.error==="string"),b=Cf.has(L.taskStatus)?L.taskStatus:void 0,W=Z??b??(M?"failed":"completed"),s=typeof L.taskOwnerPid==="number"&&Number.isInteger(L.taskOwnerPid)&&L.taskOwnerPid>0?L.taskOwnerPid:void 0,e=V$.has(L.taskIsolation)?L.taskIsolation:void 0,y=typeof L.taskSourceProjectPath==="string"&&V.isAbsolute(L.taskSourceProjectPath)?V.resolve(L.taskSourceProjectPath):void 0,S=B.cwd;if(S!==void 0&&!V.isAbsolute(S))throw Error(`Session catalog cwd must be absolute: ${f}`);let R=S===void 0?T:V.resolve(S),D=Gf(L.taskWorktree),z=D?.sessionId===f&&V.resolve(D.workspaceRoot)===R?D:void 0,K=xf(L.taskDiffStat),g=Jf(L.taskDispatch),w0=typeof L.taskModelId==="string"&&L.taskModelId.trim()?L.taskModelId:g?.modelId,F$=typeof L.selectedModelId==="string"&&L.selectedModelId.trim()?L.selectedModelId:w0,K$=b0(L.permissionMode)?L.permissionMode:g?.permissionMode,Q$=V0(L.reasoningEffort)?L.reasoningEffort:g?.reasoningEffort,X$=J0(L.serviceTier)?L.serviceTier:g?.serviceTier,H$=x0(L.responseVerbosity)?L.responseVerbosity:g?.responseVerbosity,k0=Z0(L.communicationStyle)?L.communicationStyle:g?.communicationStyle,y0=Object.hasOwn(L,"communicationStyleDigest")?typeof L.communicationStyleDigest==="string"&&/^[a-f0-9]{64}$/.test(L.communicationStyleDigest)?L.communicationStyleDigest:void 0:k0===g?.communicationStyle?g?.communicationStyleDigest:void 0,S0=Object.hasOwn(L,"projectInstructionsDigest")?typeof L.projectInstructionsDigest==="string"&&/^[a-f0-9]{64}$/.test(L.projectInstructionsDigest)?L.projectInstructionsDigest:void 0:g?.projectInstructionsDigest,j0=Af(L.archivedAt)?L.archivedAt:void 0,m0=Vf(L.taskRetriedFrom),T0=_f(L.taskDelivery),F0=typeof L.taskQueuePosition==="number"&&Number.isInteger(L.taskQueuePosition)&&L.taskQueuePosition>0?L.taskQueuePosition:void 0,I0=typeof L.taskQueueDepth==="number"&&Number.isInteger(L.taskQueueDepth)&&L.taskQueueDepth>=0?L.taskQueueDepth:void 0,Y=typeof L.taskConcurrencyLimit==="number"&&Number.isInteger(L.taskConcurrencyLimit)&&L.taskConcurrencyLimit>0?L.taskConcurrencyLimit:void 0,i=J?N?.completion?N.completion.status==="completed"?void 0:`Code review ${n0(N.completion.status)}`:`Reviewing ${N?.start.target.label??"changes"}`:void 0,K0=J?W==="failed"&&i?c0(i):void 0:p0(L.taskFailure)?L.taskFailure:W==="failed"&&typeof L.taskStatusReason==="string"?c0(L.taskStatusReason):void 0;return{sessionId:f,projectPath:R,gitBranch:B.gitBranch,rootId:L.rootId||f,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:F$,permissionMode:K$,reasoningEffort:Q$,serviceTier:X$,responseVerbosity:H$,communicationStyle:k0,communicationStyleDigest:y0,projectInstructionsDigest:S0,pendingInteraction:C,taskStatus:W,taskStatusReason:K0?.message??i??(typeof L.taskStatusReason==="string"?L.taskStatusReason:void 0),taskFailure:K0,taskStartedAt:J?N?.start.startedAt:typeof L.taskStartedAt==="string"?L.taskStartedAt:void 0,taskCompletedAt:J?N?.completion?.completedAt:typeof L.taskCompletedAt==="string"?L.taskCompletedAt:void 0,taskPromptSummary:J?N?M1(N.start.target):"/review uncommitted":typeof L.taskPromptSummary==="string"?L.taskPromptSummary:void 0,taskModelId:w0,taskRetryAvailable:g!==void 0,taskRetriedFrom:m0,taskDelivery:T0,taskIsolation:e,taskSourceProjectPath:y,taskWorktreePath:z?.worktreeRoot,taskWorktreeBranch:z?.branch,taskBaseCommit:z?.baseCommit,taskDiffStat:K,taskQueuePosition:F0,taskQueueDepth:I0,taskConcurrencyLimit:Y,archivedAt:j0,taskOwnerPid:J?void 0:s,taskWorktree:z,taskDispatch:g,messageCount:E,firstMessageTime:$[0].timestamp,lastMessageTime:$.at(-1).timestamp,hasErrors:M||W==="failed",filePath:q}}static toPublicMetadata($){let{filePath:f,taskOwnerPid:T,taskWorktree:q,taskDispatch:B,...L}=$;return L}static getSessionFilePath($,f){return m($,f)}static getSessionCreatedEntry($,f){let T=$.find((q)=>q.type==="session_created");if(!T)throw new Rf(f);return T}static resolveCatalogWorkspace($){if(!V.isAbsolute($))throw Error("Session catalog cwd must be absolute");return V.resolve($)}static validateSessionWorkspace($,f,T){let q=this.getSessionCreatedEntry($,f);if(q.data.sessionId!==f)throw Error(`Session creation record sessionId mismatch: ${f}`);if(!V.isAbsolute(q.cwd)||V.resolve(q.cwd)!==T)throw Error(`Session creation record cwd mismatch: ${f}`)}static resolveForkWorkspace($){if(!V.isAbsolute($))throw Error("Fork workspace paths must be absolute");return V.resolve($)}static parseStoredSession($,f){return Yf($,`session ${f}`)}static isCorruptSessionJSONLError($){return $ instanceof Error&&$.message.startsWith("Invalid session JSONL ")}static sanitizeStoredSessionError($,f){if(!this.isCorruptSessionJSONLError($)||!($ instanceof Error))return $;let T=$.message.match(/ at line (\d+)$/)?.[1];return Error(`Invalid session JSONL in session ${f}${T?` at line ${T}`:""}`,{cause:$.cause})}static async readStableSessionSnapshot($,f,T=3){for(let q=0;q<T;q+=1){let B=await _0.stat($),L=await _0.readFile($),O=this.parseStoredSession(L,f),C=await _0.stat($);if(B.size===C.size&&B.mtimeNs===C.mtimeNs&&B.dev===C.dev&&B.ino===C.ino)return O}throw Error("Session changed while creating fork; retry the operation")}}function Zf($){if($.length===1&&$[0]?.type==="text")return $[0].text;return[...$]}
|
|
111
|
-
export{i0 as Fb,Y$ as Gb,Q0 as Hb,U$ as Ib,o1 as Jb,h as Kb,n as Lb,TT as Mb,qT as Nb,b$ as Ob,OT as Pb,Y0 as Qb,NT as Rb,n0 as Sb,k$ as Tb,y$ as Ub,c0 as Vb,l as Wb,D0 as Xb,DT as Yb,RT as Zb,AT as _b,zT as $b,v$ as ac,MT as bc,ET as cc,u$ as dc,wT as ec,a0 as fc,s0 as gc,vT as hc,uT as ic,d$ as jc,A0 as kc,pT as lc,Bf as mc,s$ as nc,oT as oc,Of as pc,tT as qc,z1 as rc,Rq as sc,Aq as tc,Rf as uc,f0 as vc,P as wc,X as xc};
|