blade-code 0.10.64 → 0.10.66
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-wy4pn9sk.js → chunk-0j22w4wh.js} +1 -1
- package/dist/chunk-0qtrv97b.js +2 -0
- package/dist/chunk-0scxrkcf.js +1 -0
- package/dist/{chunk-2z3xe3rw.js → chunk-0wxkymqv.js} +1 -1
- package/dist/{chunk-egb457mv.js → chunk-1c69c4rd.js} +1 -1
- package/dist/{chunk-b19f55s7.js → chunk-1z9wct9w.js} +1 -1
- package/dist/chunk-2eq5dyga.js +1 -0
- package/dist/{chunk-0jxh2zq5.js → chunk-2kkpn41a.js} +2 -2
- package/dist/{chunk-pxy15vf3.js → chunk-2xk6m4fc.js} +12 -3
- package/dist/{chunk-81pdgcq7.js → chunk-30kmydfj.js} +2 -2
- package/dist/{chunk-z8heg5qv.js → chunk-4sztphe9.js} +1 -1
- package/dist/{chunk-6rg6mngq.js → chunk-50jthhfq.js} +1 -1
- package/dist/chunk-5147jh26.js +2 -0
- package/dist/{chunk-cm9mph7j.js → chunk-5d2cdvdy.js} +1 -1
- package/dist/chunk-69j98a7j.js +166 -0
- package/dist/{chunk-8ekk8pa7.js → chunk-6pyktfa4.js} +1 -1
- package/dist/chunk-89090tyx.js +1 -0
- package/dist/chunk-8c677xtx.js +1 -0
- package/dist/chunk-8nmwft1y.js +112 -0
- package/dist/{chunk-y8r2knxm.js → chunk-98n2rxmq.js} +2 -2
- package/dist/{chunk-pdys123h.js → chunk-a2594p5r.js} +1 -1
- package/dist/{chunk-2m7at619.js → chunk-a3xnd8cg.js} +2 -2
- package/dist/{chunk-7p0bzza4.js → chunk-abef6dq1.js} +2 -2
- package/dist/chunk-ax9ftraa.js +1 -0
- package/dist/{chunk-d9z0rbz1.js → chunk-b66veqye.js} +2 -2
- package/dist/{chunk-6g3qzz9h.js → chunk-bbcb9jzb.js} +1 -1
- package/dist/{chunk-3tednchw.js → chunk-bjqjdw34.js} +2 -2
- package/dist/chunk-c8zcyvss.js +1 -0
- package/dist/{chunk-detkh4dd.js → chunk-cdy9efgm.js} +1 -1
- package/dist/chunk-dc64v4sa.js +1 -0
- package/dist/{chunk-83wm4akj.js → chunk-dktrankr.js} +1 -1
- package/dist/chunk-e7pssnr9.js +1 -0
- package/dist/chunk-eq99gcj8.js +1 -0
- package/dist/{chunk-j9snkjpe.js → chunk-f99n8812.js} +2 -2
- package/dist/{chunk-gdrqxnzh.js → chunk-gezg1mpa.js} +1 -1
- package/dist/{chunk-khkhsaan.js → chunk-h0ft81a3.js} +1 -1
- package/dist/{chunk-rcv4q8hm.js → chunk-ha50z8dp.js} +1 -1
- package/dist/{chunk-d1t91jgz.js → chunk-hat9v5c5.js} +1 -1
- package/dist/{chunk-av10vmxk.js → chunk-hcv17986.js} +1 -1
- package/dist/{chunk-5g2p1fwn.js → chunk-j38jh128.js} +2 -2
- package/dist/chunk-jmjn6zcc.js +1 -0
- package/dist/{chunk-kjvntyr5.js → chunk-k0pa8874.js} +1 -1
- package/dist/{chunk-6fwh0m6d.js → chunk-k99r5c4v.js} +3 -3
- package/dist/chunk-kmarzy98.js +1 -0
- package/dist/chunk-kv0bkxhd.js +8 -0
- package/dist/{chunk-87jz5600.js → chunk-m57w4p91.js} +1 -1
- package/dist/{chunk-9zdx6jsh.js → chunk-nt55nz8d.js} +40 -40
- package/dist/chunk-p0b4mv7e.js +10 -0
- package/dist/{chunk-cz68x56m.js → chunk-ppsvzgs5.js} +2 -2
- package/dist/{chunk-3m640njb.js → chunk-pzb5sqwd.js} +1 -1
- package/dist/{chunk-wrw5hegj.js → chunk-q3mfescm.js} +2 -2
- package/dist/{chunk-wqewxnez.js → chunk-qdah5kkc.js} +246 -246
- package/dist/{chunk-as5z4m2d.js → chunk-rf01e14b.js} +1 -1
- package/dist/chunk-rhs1dv6w.js +1 -0
- package/dist/{chunk-jk8bqc5b.js → chunk-s7jsadnc.js} +2 -2
- package/dist/{chunk-ej6h16ae.js → chunk-t2gq918a.js} +2 -2
- package/dist/chunk-t89q7d03.js +22 -0
- package/dist/{chunk-fp1h8wdh.js → chunk-t8xmh4w2.js} +1 -1
- package/dist/{chunk-z2hmx0jz.js → chunk-te21eb71.js} +1 -1
- package/dist/{chunk-9r0yebs1.js → chunk-th4jjfgm.js} +1 -1
- package/dist/{chunk-7b467h8k.js → chunk-v0rsz1rt.js} +1 -1
- package/dist/{chunk-wt4wv5rb.js → chunk-w6p2hcfw.js} +1 -1
- package/dist/{chunk-rctbavme.js → chunk-xny9q252.js} +2 -2
- package/dist/chunk-xz6y0w4n.js +2 -0
- package/dist/{chunk-tcga95a4.js → chunk-ybv6stfh.js} +2 -2
- package/dist/{chunk-69rc9hw6.js → chunk-yn51162x.js} +1 -1
- package/dist/{chunk-1jc7d3nt.js → chunk-ypqp368c.js} +2 -2
- package/dist/{chunk-eeac8teg.js → chunk-yvg961q3.js} +1 -1
- package/dist/chunk-yy6h97k0.js +1 -0
- package/dist/chunk-zdxxqchm.js +140 -0
- package/dist/chunk-zk42hrdh.js +1 -0
- package/dist/{chunk-2xbmkyb2.js → chunk-zvz2cnt4.js} +1 -1
- package/dist/web/assets/{ChatView-B6IO9U-D.js → ChatView-BVrhnE2j.js} +6 -6
- package/dist/web/assets/{CodeBlockHighlighter-DVGtFQgX.js → CodeBlockHighlighter-Dy7QpAmC.js} +1 -1
- package/dist/web/assets/{FilePreview-C-8_o7yw.js → FilePreview-BI3nkxz1.js} +2 -2
- package/dist/web/assets/KanbanBoard-D5dYOyPH.js +1 -0
- package/dist/web/assets/{MarkdownRenderer-D04IKQhF.js → MarkdownRenderer-Da1vB81L.js} +12 -12
- package/dist/web/assets/{SettingsModal-BMoZLVEe.js → SettingsModal-jcCFqLqS.js} +2 -2
- package/dist/web/assets/TaskSwitcher-CQ--jOLB.js +1 -0
- package/dist/web/assets/{TerminalPanel-fTk9D5hU.js → TerminalPanel-CWzjEXOb.js} +1 -1
- package/dist/web/assets/index-BOgOL4hG.js +11 -0
- package/dist/web/assets/index-DbWgTuT3.css +1 -0
- package/dist/web/assets/{vendor-icons-ICv1v-tf.js → vendor-icons-B63aW_OM.js} +82 -62
- package/dist/web/index.html +3 -3
- package/package.json +2 -2
- package/dist/chunk-0d1197b9.js +0 -1
- package/dist/chunk-1vw79f30.js +0 -1
- package/dist/chunk-1wr6hrwt.js +0 -1
- package/dist/chunk-7781czcd.js +0 -1
- package/dist/chunk-86gc2mqb.js +0 -1
- package/dist/chunk-9c31jemm.js +0 -1
- package/dist/chunk-9kmtcgm6.js +0 -2
- package/dist/chunk-acfka6w7.js +0 -1
- package/dist/chunk-addsr9hg.js +0 -22
- package/dist/chunk-avhwgbg0.js +0 -1
- package/dist/chunk-bcp7nwwy.js +0 -10
- package/dist/chunk-bjz7t9fe.js +0 -8
- package/dist/chunk-dbs94h44.js +0 -1
- package/dist/chunk-g0n88mhg.js +0 -1
- package/dist/chunk-jy1e6ve5.js +0 -111
- package/dist/chunk-q8zp4je9.js +0 -1
- package/dist/chunk-qs4erqd0.js +0 -2
- package/dist/chunk-vjyysxhx.js +0 -1
- package/dist/chunk-wwsg165p.js +0 -116
- package/dist/chunk-wy2b5hsh.js +0 -2
- package/dist/chunk-xm44tqjb.js +0 -1
- package/dist/chunk-y78m734s.js +0 -204
- package/dist/chunk-y83x0w26.js +0 -1
- package/dist/web/assets/TaskSwitcher-CIuCEbvU.js +0 -1
- package/dist/web/assets/index-CO5sUiJn.js +0 -11
- package/dist/web/assets/index-Dxdnbd79.css +0 -1
package/dist/chunk-jy1e6ve5.js
DELETED
|
@@ -1,111 +0,0 @@
|
|
|
1
|
-
import{Hc as u,Ic as W$,Jc as Of,Kc as U$,Lc as I,Mc as _f,Nc as R$,Oc as Nf,Pc as Gf,Qc as xf,Sc as M0,Vc as Vf,Wc as D$}from"./chunk-wwsg165p.js";import{Yd as J0}from"./chunk-69rc9hw6.js";import{He as Z0}from"./chunk-detkh4dd.js";import{Te as rf}from"./chunk-87jz5600.js";import{eg as H$,fg as Y$}from"./chunk-9kmtcgm6.js";import{kg as Af}from"./chunk-kjvntyr5.js";import{Lg as U0}from"./chunk-y8r2knxm.js";import{Sg as x0,Vg as V0}from"./chunk-fp1h8wdh.js";import{Zg as p}from"./chunk-5g2p1fwn.js";import{fh as K$,gh as q0,hh as X$,ih as A,jh as m,lh as N0,mh as l,nh as O0}from"./chunk-cz68x56m.js";import{readdir as Lf,readFile as a,rm as f0,stat as E0}from"node:fs/promises";import*as J from"node:path";import{nanoid as j}from"nanoid";import{createHash as j$,randomUUID as m$}from"node:crypto";import*as v from"node:fs/promises";import*as H0 from"node:path";import{execFileSync as E$}from"node:child_process";import{createHash as b$}from"node:crypto";import{readFileSync as k$}from"node:fs";var w$=/^[a-f0-9]{64}$/;function Yf(f){if(!f||typeof f!=="object")return!1;let $=f;return($.platform==="linux"||$.platform==="darwin"||$.platform==="win32")&&typeof $.fingerprint==="string"&&w$.test($.fingerprint)}var Wf={readFile:(f)=>k$(f,"utf8"),execFile:(f,$)=>E$(f,$,{encoding:"utf8",timeout:f==="powershell.exe"?3000:2000,windowsHide:!0})},y$=(f)=>{try{return process.kill(f,0),!0}catch($){return $ instanceof Error&&"code"in $&&$.code==="EPERM"}};function u0(f,$){return{platform:f,fingerprint:b$("sha256").update(`${f}\x00${$}`).digest("hex")}}function S$(f,$){let T=$.readFile(`/proc/${f}/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 K0(f,$=process.platform,T=Wf){if(!Number.isInteger(f)||f<=1)return;try{if($==="linux")return u0($,S$(f,T));if($==="darwin"){let q=T.execFile("ps",["-o","lstart=","-p",String(f)]).trim();return q?u0($,q):void 0}if($==="win32"){let q=`(Get-CimInstance Win32_Process -Filter "ProcessId = ${f}").CreationDate.ToUniversalTime().ToString('O')`,B=T.execFile("powershell.exe",["-NoProfile","-NonInteractive","-Command",q]).trim();return B?u0($,B):void 0}}catch{return}return}function Uf(f,$){return K0(f,$.platform)?.fingerprint===$.fingerprint}function tT(f,$,T=Wf,q=y$){if(!Number.isInteger(f)||f<=1)return!1;let B=K0(f,$.platform,T);if(B)return B.fingerprint===$.fingerprint;return!q(f)}var zf=1;function I$(f,$){let T=j$("sha256").update($).digest("hex");return H0.join(q0(f),".locks",`${T}.lock`)}function X0(f,$){return f instanceof Error&&"code"in f&&f.code===$}async function n0(f){try{let $=JSON.parse(await v.readFile(f,"utf8"));if($.version!==zf||typeof $.sessionId!=="string"||typeof $.ownerId!=="string"||!Number.isInteger($.pid)||($.pid??0)<=0||$.processIdentity!==void 0&&!Yf($.processIdentity)||typeof $.acquiredAt!=="string")return;return $}catch{return}}async function Rf(f){let $=await n0(f);if($)return $;return await new Promise((T)=>setTimeout(T,10)),n0(f)}function v$(f){try{return process.kill(f,0),!0}catch($){return X0($,"EPERM")}}async function Df(f,$){let T;try{return T=await v.open(f,"wx",384),await T.writeFile(`${JSON.stringify($)}
|
|
2
|
-
`,"utf8"),!0}catch(q){if(X0(q,"EEXIST"))return!1;if(T)await v.unlink(f).catch(()=>{return});throw q}finally{await T?.close().catch(()=>{return})}}class P extends Error{code="BLADE_SESSION_IN_USE";constructor(f){super(f?`Session is already active in another Blade process (PID ${f}). 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 h{filePath;record;released=!1;constructor(f,$){this.filePath=f;this.record=$}static async acquire(f,$=Af()){let T=I$($,f),q={version:zf,sessionId:f,ownerId:m$(),pid:process.pid,processIdentity:K0(process.pid),acquiredAt:new Date().toISOString()};if(await v.mkdir(H0.dirname(T),{recursive:!0,mode:448}),await Df(T,q))return new h(T,q);let B=await Rf(T);if(B&&v$(B.pid)&&(!B.processIdentity||Uf(B.pid,B.processIdentity)))throw new P(B.pid);if(await v.unlink(T).catch((L)=>{if(!X0(L,"ENOENT"))throw L}),await Df(T,q))return new h(T,q);throw new P((await Rf(T))?.pid)}async release(){if(this.released)return;if(this.released=!0,(await n0(this.filePath))?.ownerId!==this.record.ownerId)return;await v.unlink(this.filePath).catch(($)=>{if(!X0($,"ENOENT"))throw $})}}var q1=1;function P0(f){return f!==null&&typeof f==="object"&&!Array.isArray(f)}function u$(f){if(!P0(f)||typeof f.type!=="string")return!1;if(f.type==="text")return typeof f.text==="string";return f.type==="image_url"&&P0(f.image_url)&&typeof f.image_url.url==="string"}function n$(f){if(!P0(f))return!1;if(!["system","user","assistant","tool"].includes(String(f.role)))return!1;return typeof f.content==="string"||Array.isArray(f.content)&&f.content.every(u$)}function gf(f){if(!Array.isArray(f)||f.length===0||f.length>4096)return;let $=JSON.stringify(f);if(Buffer.byteLength($)>16777216)return;let T=JSON.parse($);if(!Array.isArray(T)||!T.every(n$))return;return T}function L1(f){let $=gf(f);if(!$)throw Error("Compaction replacement context is invalid or exceeds limits");return $}function Mf(f){return gf(f)}function P$(f,$){for(let T of f){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===$||T.data.partId===$||T.data.messageId===$)return B}return}function Ef(f){let $=u(f),T=new Map;for(let q of $){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=P$($,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 bf(f){return Ef(f).reverse().find(($)=>!$.response&&!$.recovery)}function O1(f){let $=new Map;for(let T of Ef(f))$.set(T.request.toolCallId,T);return[...$.values()].filter((T)=>T.response&&!T.recovery&&(!T.hasToolResult||T.hasRecoveryToolResult))}function kf(f){if(!f)return;return{type:f.request.interactionType,requestId:f.request.requestId}}function Y0(f){let $=new Map,T=[];for(let q of f){if(q.type==="review_started"){if(!$.has(q.data.reviewId))T.push(q.data.reviewId),$.set(q.data.reviewId,{start:q.data});continue}if(q.type!=="review_completed")continue;let B=$.get(q.data.reviewId);if(B&&B.completion===void 0)B.completion=q.data}return T.map((q)=>$.get(q)).filter((q)=>q!==void 0)}function N1(f){return Y0(f).reverse().find(($)=>$.completion===void 0)}function h0(f){switch(f){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 wf(f,$){let T=["## Code Review","",`Target: ${f.target.label}`,`Status: ${h0($.status)}`,"",$.overallExplanation||"No overall explanation was provided."];if($.findings.length===0)T.push("","No actionable findings.");else{T.push("","### Findings");for(let[q,B]of $.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($.error)T.push("",`Error: ${$.error}`);return T.join(`
|
|
3
|
-
`)}function yf(f,$){return{reviewId:f.reviewId,phase:"completed",status:$.status,target:{kind:f.target.kind,label:f.target.label,...f.target.baseSha?{reference:f.target.baseSha}:{},...f.target.commitSha?{reference:f.target.commitSha}:{}},overallExplanation:$.overallExplanation,findings:$.findings.map((T)=>({title:T.title,body:T.body,priority:T.priority,confidenceScore:T.confidenceScore,codeLocation:{...T.codeLocation}})),...$.error?{error:$.error}:{}}}var c0={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},capacity:{message:"Task admission capacity is full. Retry after running tasks complete.",retryable:!0},runtime:{message:"Agent execution failed.",retryable:!0}};function h$(f){try{if(f instanceof Error)return f.message;if(f!==null&&typeof f==="object"&&"message"in f&&typeof f.message==="string")return f.message;return String(f)}catch{return"Unknown error"}}function c$(f){let $=f.toLowerCase();if(/\b(401|unauthorized|authentication|invalid (?:api[ _-]?)?key|api[ _-]?key|credential)\b/.test($))return"authentication";if(/\b(403|forbidden|permission denied|not permitted)\b/.test($))return"permission";if(/\b(429|rate limit|too many requests|quota)\b/.test($))return"rate_limit";if(/\b(timeout|timed out|deadline exceeded|etimedout)\b/.test($))return"timeout";if(/\b(econnreset|econnrefused|enotfound|network|socket|connection)\b/.test($))return"network";if(/\b(model not found|model unavailable|unsupported model|no such model)\b/.test($))return"model_unavailable";if(/\b(context (?:length|window)|maximum context|too many tokens|token limit)\b/.test($))return"context_limit";if(/\b(image|vision|multimodal|unsupported input|does not support)\b/.test($))return"unsupported_input";if(/\btask admission\b.*\b(capacity|queue)\b/.test($))return"capacity";return"runtime"}function l$(f){try{if(!f||typeof f!=="object"||!("name"in f)||f.name!=="TaskAdmissionQueueFullError"&&f.name!=="SessionRuntimeCapacityError"||!("resource"in f))return;return f.resource==="pending_count"||f.resource==="pending_bytes"||f.resource==="resident_runtimes"?f.resource:void 0}catch{return}}function Sf(f){return{code:f,...c0[f]}}function l0(f){let $=l$(f);if($)return{...Sf("capacity"),resource:$};return Sf(c$(h$(f)))}function p0(f){if(!f||typeof f!=="object")return!1;let $=f;if(typeof $.code!=="string"||!($.code in c0))return!1;let T=c0[$.code],q=$.resource===void 0||$.resource==="pending_count"||$.resource==="pending_bytes"||$.resource==="resident_runtimes";return $.message===T.message&&$.retryable===T.retryable&&q&&($.code==="capacity"||$.resource===void 0)}import{promises as L0,realpathSync as i$}from"node:fs";import W0 from"node:path";import*as r from"fs/promises";import*as H from"path";var jf=[".git",".claude","node_modules",".env",".env.local",".env.production",".env.development",".env.test"];class d extends Error{code;constructor(f,$){super(f);this.code=$;this.name="PathSecurityError"}}class i0{static normalize(f,$){let T=H.isAbsolute(f)?f:H.resolve($,f),q=H.normalize(T),B=H.normalize($);if(!this.isWithinWorkspace(q,B))throw new d(`Path outside workspace: ${f} (resolved to ${q}, workspace: ${B})`,"PATH_OUTSIDE_WORKSPACE");return q}static checkRestricted(f){let $=f.split(H.sep);for(let T of jf)if($.includes(T))throw new d(`Access denied: "${T}" is a protected directory`,"RESTRICTED_PATH")}static checkTraversal(f){if(f.includes(".."))throw new d(`Path traversal not allowed: ${f}`,"PATH_TRAVERSAL")}static async validatePath(f,$){this.checkTraversal(f);let T=this.normalize(f,$);this.checkRestricted(T);try{await r.access(T)}catch(q){throw new d(`Path not found: ${f}`,"PATH_NOT_FOUND")}return T}static async resolveSymlink(f,$){try{let T=await r.realpath(f),q=await r.realpath($);if(!this.isWithinWorkspace(T,q))throw new d(`Symlink points outside workspace: ${f} -> ${T}`,"SYMLINK_OUTSIDE_WORKSPACE");return T}catch(T){if(T instanceof d)throw T;return f}}static getRelativePath(f,$){return H.relative($,f)}static isWithinWorkspace(f,$){let T=H.resolve(f),q=H.resolve($),B=H.relative(q,T);return B===""||B!==".."&&!B.startsWith(`..${H.sep}`)&&!H.isAbsolute(B)}static async isWithinWorkspaceResolved(f,$){let T=H.resolve($),q=H.isAbsolute(f)?H.resolve(f):H.resolve(T,f);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 O=await r.realpath(L);return this.isWithinWorkspace(O,B)}catch(O){let G=O.code;if(G!=="ENOENT"&&G!=="ENOTDIR")return!1}let C=H.dirname(L);if(C===L)return!1;L=C}}static isRestricted(f){let $=f.split(H.sep);return jf.some((T)=>$.includes(T))}}var B0=U0("Tool");class c{static instance=null;accessedFiles=new Map;pathAliases=new Map;constructor(){}static getInstance(){if(!c.instance)c.instance=new c;return c.instance}async recordFileRead(f,$){try{let T=await L0.stat(f),q={filePath:W0.resolve(f),accessTime:Date.now(),mtime:T.mtimeMs,sessionId:$,lastOperation:"read"};this.setRecord(q),await this.recordAliases(f,q.filePath),B0.debug(`记录文件读取: ${f}`)}catch(T){B0.warn(`记录文件读取失败: ${f}`,T)}}async recordFileEdit(f,$,T="edit"){try{let q=await L0.stat(f),B={filePath:W0.resolve(f),accessTime:Date.now(),mtime:q.mtimeMs,sessionId:$,lastOperation:T};this.setRecord(B),await this.recordAliases(f,B.filePath),B0.debug(`记录文件${T==="edit"?"编辑":"写入"}: ${f}`)}catch(q){B0.warn(`记录文件${T==="edit"?"编辑":"写入"}失败: ${f}`,q)}}hasFileBeenRead(f,$){let T=this.accessedFiles.get(this.resolveTrackedPath(f));if(!T)return!1;return $?T.has($):T.size>0}async checkFileModification(f,$){let T=this.getFileRecord(f,$);if(!T)return{modified:!1,message:"文件未被跟踪"};try{let q=await L0.stat(f);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(f);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(`检查文件外部修改失败: ${f}`,q),{isExternal:!1,message:`无法检查文件状态: ${B.message}`}}}getFileRecord(f,$){let T=this.accessedFiles.get(this.resolveTrackedPath(f));if(!T)return;if($)return T.get($);return[...T.values()].sort((q,B)=>B.accessTime-q.accessTime)[0]}getTrackedRecords(){return[...this.accessedFiles.values()].flatMap((f)=>[...f.values()])}clearFileRecord(f,$){let T=this.resolveTrackedPath(f);if(!$){this.accessedFiles.delete(T),this.removeAliases(T);return}let q=this.accessedFiles.get(T);if(q?.delete($),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($&&!i0.isWithinWorkspace(T,$))continue;if(q.delete(f),q.size===0)this.accessedFiles.delete(T),this.removeAliases(T)}}getTrackedFiles(){return Array.from(this.accessedFiles.keys())}getTrackedFileCount(){return this.accessedFiles.size}static resetInstance(){c.instance=null}setRecord(f){let $=this.accessedFiles.get(f.filePath);if(!$)$=new Map,this.accessedFiles.set(f.filePath,$);$.set(f.sessionId,f)}async recordAliases(f,$){this.pathAliases.set(W0.resolve(f),$);let T=await L0.realpath(f).catch(()=>{return});if(T)this.pathAliases.set(T,$)}resolveTrackedPath(f){let $=W0.resolve(f);if(this.accessedFiles.has($))return $;let T=this.pathAliases.get($);if(T)return T;try{let q=i$.native($);return this.pathAliases.get(q)??q}catch{return $}}removeAliases(f){for(let[$,T]of this.pathAliases)if(T===f)this.pathAliases.delete($)}}import*as C0 from"node:crypto";import{promises as F}from"node:fs";import*as K from"node:path";import d0 from"write-file-atomic";var mf="missing";class R0{sessionId;workspaceRoot;enableCheckpoints;maxSnapshots;snapshotDir;manifestPath;trackedFileBackups=new Map;snapshots=[];constructor(f){if(A(f.sessionId),this.sessionId=f.sessionId,f.workspaceRoot&&!K.isAbsolute(f.workspaceRoot))throw Error("Snapshot workspace root must be absolute");this.workspaceRoot=f.workspaceRoot?K.resolve(f.workspaceRoot):void 0,this.enableCheckpoints=f.enableCheckpoints??!0,this.maxSnapshots=f.maxSnapshots??10;let $=O0();this.snapshotDir=K.join($,"file-history",this.sessionId),this.manifestPath=K.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 f=O0(),$=await F.realpath(this.workspaceRoot).catch(()=>this.workspaceRoot),T=C0.createHash("sha256").update($).digest("hex").slice(0,24),q=K.join(f,"file-history",this.sessionId),B=K.join(f,"file-history","workspaces",T,this.sessionId),L=K.join(B,"manifest.json");try{await F.access(L)}catch{await this.migrateLegacySnapshotDir(q,B,$)}this.snapshotDir=B,this.manifestPath=L}async migrateLegacySnapshotDir(f,$,T){let q;try{q=JSON.parse(await F.readFile(K.join(f,"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(K.dirname($),{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(!K.isAbsolute(f))return!1;let T=K.relative($,K.resolve(f));return T===""||T!==".."&&!T.startsWith(`..${K.sep}`)&&!K.isAbsolute(T)}async createSnapshot(f,$){if(!this.enableCheckpoints)return{backupFileName:"",version:0,backupTime:new Date};let T=await this.resolveFileIdentity(f),q=!0;try{await F.access(T)}catch{q=!1}let B=this.trackedFileBackups.get(T),L=B?B.version+1:1,C=this.generateFileHash(T,L),O=this.getSnapshotPath(C,L),G=new Date;if(q){let N=await F.readFile(T);await F.writeFile(O,N)}let _={backupFileName:C,version:L,backupTime:G};return this.trackedFileBackups.set(T,_),this.snapshots.push({messageId:$,backupFileName:C,timestamp:G,filePath:T,version:L,existedBefore:q}),await this.cleanupOldSnapshots(T),await this.persistManifest(),_}async recordPostEditState(f,$){if(!this.enableCheckpoints||!$.backupFileName)return;let T=await this.resolveFileIdentity(f),q=this.snapshots.find((B)=>B.filePath===T&&B.backupFileName===$.backupFileName&&B.version===$.version);if(!q)throw Error(`未找到待完成的快照: ${T}`);q.postEditHash=await this.hashFile(T),await this.persistManifest()}async discardSnapshot(f,$){if(!this.enableCheckpoints||!$.backupFileName)return;let T=await this.resolveFileIdentity(f),q=this.snapshots.find((B)=>B.filePath===T&&B.backupFileName===$.backupFileName&&B.version===$.version);if(!q)return;this.removeSnapshot(q),await F.rm(this.getSnapshotPath(q.backupFileName,q.version),{force:!0}),await this.persistManifest()}async rewindLatest(f){let $=await this.resolveFileIdentity(f),T=this.snapshots.slice().reverse().find((L)=>L.filePath===$&&L.postEditHash!==void 0);if(!T?.postEditHash)throw Error(`未找到可回退快照: ${$}`);if(await this.hashFile($)!==T.postEditHash)throw Error(`文件在 Blade 编辑后已被修改,拒绝覆盖: ${$}`);let B=this.getSnapshotPath(T.backupFileName,T.version);if(T.existedBefore){let L=await F.readFile(B);await F.mkdir(K.dirname($),{recursive:!0}),await F.writeFile($,L)}else await F.rm($,{force:!0});return this.removeSnapshot(T),await F.rm(B,{force:!0}),await this.persistManifest(),T}async restoreSnapshot(f,$){let T=await this.resolveFileIdentity(f),q=this.snapshots.slice().reverse().find((L)=>L.messageId===$&&L.filePath===T);if(!q)throw Error(`未找到快照: messageId=${$}, filePath=${T}`);let B=this.getSnapshotPath(q.backupFileName,q.version);if(q.existedBefore){let L=await F.readFile(B);await F.mkdir(K.dirname(T),{recursive:!0}),await F.writeFile(T,L)}else await F.rm(T,{force:!0})}async listSnapshots(f){let $=await this.resolveFileIdentity(f);return this.snapshots.filter((T)=>T.filePath===$)}async listAllSnapshots(){return this.snapshots.filter((f)=>f.postEditHash!==void 0)}async previewRewind(f){let $=this.buildRewindPlan(f);return{files:$.map((T)=>T.filePath),snapshotCount:$.reduce((T,q)=>T+q.selected.length,0)}}async rewindSnapshots(f){let $=this.buildRewindPlan(f);if($.length===0)return{files:[],snapshotCount:0};let T=new Map;for(let B of $){let L,C=!0;try{L=await F.readFile(B.filePath)}catch(G){if(G.code!=="ENOENT")throw G;C=!1}if((L?C0.createHash("sha256").update(L).digest("hex"):mf)!==B.latest.postEditHash)throw Error(`文件在 Blade 编辑后已被修改,拒绝覆盖: ${B.filePath}`);if(T.set(B.filePath,{existed:C,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 $)if(L.target.existedBefore){let C=await F.readFile(this.getSnapshotPath(L.target.backupFileName,L.target.version));await F.mkdir(K.dirname(L.filePath),{recursive:!0}),await d0(L.filePath,C)}else await F.rm(L.filePath,{force:!0});let B=new Set($.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[C,O]of T)try{if(O.existed&&O.content)await d0(C,O.content);else await F.rm(C,{force:!0})}catch(G){L.push(G)}if(L.length>0)throw AggregateError([B,...L],"快照回退失败且无法完整恢复回退前状态");throw B}return{files:$.map((B)=>B.filePath),snapshotCount:$.reduce((B,L)=>B+L.selected.length,0)}}async commitSnapshots(f){let $=this.buildRewindPlan(f),T=new Set($.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:$.map((B)=>B.filePath),snapshotCount:T.size}}buildRewindPlan(f){let $=new Set(f),T=this.snapshots.filter((L)=>L.postEditHash!==void 0),q=T.filter((L)=>$.has(L.messageId));return[...new Set(q.map((L)=>L.filePath))].sort().map((L)=>{let C=T.filter((N)=>N.filePath===L),O=C.filter((N)=>$.has(N.messageId)),G=C.indexOf(O[0]),_=C.slice(G);if(_.length!==O.length||_.some((N)=>!$.has(N.messageId)))throw Error(`请求的快照不是文件历史的连续后缀: ${L}`);return{filePath:L,selected:O,target:O[0],latest:O.at(-1)}})}async loadManifest(){try{let f=await F.readFile(this.manifestPath,"utf-8"),$=JSON.parse(f);if($.schemaVersion!==1||!Array.isArray($.snapshots))throw Error("Unsupported snapshot manifest");this.snapshots=await Promise.all($.snapshots.map(async(T)=>({...T,filePath:await this.resolveFileIdentity(T.filePath),timestamp:new Date(T.timestamp)}))),this.rebuildTrackedFileBackups()}catch(f){if(f.code!=="ENOENT")throw f;this.snapshots=[],this.trackedFileBackups.clear()}}async persistManifest(){if(this.snapshots.length===0){await F.rm(this.manifestPath,{force:!0});return}let f={schemaVersion:1,snapshots:this.snapshots.map(($)=>({...$,timestamp:$.timestamp.toISOString()}))};await d0(this.manifestPath,JSON.stringify(f,null,2),{encoding:"utf-8",mode:384})}async cleanupOldSnapshots(f){let T=this.snapshots.filter((q)=>q.filePath===f).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(f=0){let $=this.snapshots.slice().sort((q,B)=>B.timestamp.getTime()-q.timestamp.getTime()),T=new Set($.slice(0,f));for(let q of this.snapshots)if(!T.has(q))await F.rm(this.getSnapshotPath(q.backupFileName,q.version),{force:!0});this.snapshots=$.slice(0,f).reverse(),this.rebuildTrackedFileBackups(),await this.persistManifest()}getSnapshotPath(f,$){return K.join(this.snapshotDir,`${f}@v${$}`)}async resolveFileIdentity(f){let $=K.resolve(f),T=[],q=$;while(!0){try{let L=await F.realpath(q);return K.join(L,...T.reverse())}catch(L){let C=L.code;if(C!=="ENOENT"&&C!=="ENOTDIR")throw L}let B=K.dirname(q);if(B===q)return $;T.push(K.basename(q)),q=B}}async hashFile(f){try{let $=await F.readFile(f);return C0.createHash("sha256").update($).digest("hex")}catch($){if($.code==="ENOENT")return mf;throw $}}removeSnapshot(f){let $=this.snapshots.indexOf(f);if($>=0)this.snapshots.splice($,1);this.rebuildTrackedFileBackups()}rebuildTrackedFileBackups(){this.trackedFileBackups.clear();for(let f of this.snapshots){let $=this.trackedFileBackups.get(f.filePath);if(!$||$.version<f.version)this.trackedFileBackups.set(f.filePath,{backupFileName:f.backupFileName,version:f.version,backupTime:f.timestamp})}}generateFileHash(f,$){let T=C0.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 D1=1200,A1=2000,z1=2000,g1=2000;function vf(f){return typeof f==="object"&&f!==null&&!Array.isArray(f)}function d$(f){if(typeof f==="string"&&f.length>0)return f;if(vf(f)&&typeof f.message==="string")return f.message;return}function r$(f,$){if(f===null||f===void 0)return $??"";if(typeof f==="string")return f;if(typeof f==="object")return f;return String(f)}function uf(f){let $=f.error!==null&&f.error!==void 0,T=$?d$(f.error)??"Tool execution failed":void 0,q=vf(f.metadata)?f.metadata:void 0;return{success:!$,llmContent:r$(f.output,T),...T?{error:{type:"execution_error",message:T}}:{},...q?{metadata:q}:{}}}function o0(f,$){if(f.length<=$)return f;let T=Math.max(0,$);if(T>0&&T<f.length&&/[\uD800-\uDBFF]/.test(f.charAt(T-1)))T-=1;return f.slice(0,T)}function If(f,$){if(f.length<=$)return f;let T=Math.max(0,f.length-$);if(T<f.length&&/[\uDC00-\uDFFF]/.test(f.charAt(T)))T+=1;return f.slice(T)}function r0(f,$){if(f.length<=$)return f;if($<=0)return"";let T=`
|
|
4
|
-
... (display clipped) ...
|
|
5
|
-
`,q=f.indexOf(`
|
|
6
|
-
`),B=q>=0&&/^(?:stdout|stderr):$/.test(f.slice(0,q))?`${f.slice(0,q)}
|
|
7
|
-
`:"",L=B?f.slice(B.length):f,C=$-B.length-T.length;if(C<=0)return If(f,$);let O=Math.min(Math.floor(C/3),L.length),G=Math.max(0,C-O);return B+o0(L,O)+T+If(L,G)}function o$(f){let $=f.split(`
|
|
8
|
-
`),T=$.at(-1);if(!T?.startsWith("Output truncated"))return{body:f};return{body:$.slice(0,-1).join(`
|
|
9
|
-
`),suffix:T}}function t$(f){let T=f.indexOf(`
|
|
10
|
-
stderr:
|
|
11
|
-
`);if(!f.startsWith(`stdout:
|
|
12
|
-
`)||T<0)return[f];return[f.slice(0,T),f.slice(T+1)]}function M1(f,$){if(!Number.isSafeInteger($)||$<=0)throw Error("maxChars must be a positive safe integer");if(!f.detail||f.detail.length<=$)return f;let{body:T,suffix:q}=o$(f.detail),B=q?`
|
|
13
|
-
${o0(q,$)}`:"",L=Math.max(0,$-B.length),C=t$(T),O;if(C.length===2){let N=Math.max(0,L-1),x=Math.floor(N/2),V=N-x;O=`${r0(C[0],x)}
|
|
14
|
-
${r0(C[1],V)}`}else O=r0(T,L);let G=o0(`${O}${B}`,$);return{...f,detail:G}}var b1={clientVisible:!1};function nf(f){if(f.metadata&&typeof f.metadata==="object"&&!Array.isArray(f.metadata)&&f.metadata.clientVisible===!1)return!1;return!(f.role==="user"&&typeof f.content==="string"&&f.content.startsWith("This turn made a non-trivial implementation. Before finishing, call Task ")&&f.content.endsWith("Only a fresh structured PASS verdict allows completion."))}import{createHash as _T}from"node:crypto";import af from"node:path";import{StringDecoder as e$}from"node:string_decoder";var w1=1048576;function t0(f,$){let T=$;while(T<f.length&&(f[T]&192)===128)T+=1;return T}class a0{maxBytes;chunks=[];retainedBytes=0;omittedBytes=0;totalBytes=0;constructor(f=1048576){this.maxBytes=f;if(!Number.isSafeInteger(f)||f<=0)throw Error("maxBytes must be a positive safe integer")}append(f){let $=Buffer.isBuffer(f)?f:Buffer.from(f);if($.length===0)return;if(this.totalBytes+=$.length,$.length>this.maxBytes){this.retainOversizedChunkTail($);return}this.chunks.push($),this.retainedBytes+=$.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 f=this.peek();return this.chunks.length=0,this.retainedBytes=0,this.omittedBytes=0,f}retainedChunkCountForTests(){return this.chunks.length}retainOversizedChunkTail(f){this.omittedBytes+=this.retainedBytes,this.chunks.length=0,this.retainedBytes=0;let $=t0(f,f.length-this.maxBytes);if(this.omittedBytes+=$,$===f.length)return;let T=Buffer.from(f.subarray($));this.chunks.push(T),this.retainedBytes=T.length}trimToLimit(){let f=!1;while(this.retainedBytes>this.maxBytes){let $=this.chunks[0];if(!$)return;let T=this.retainedBytes-this.maxBytes;if($.length<=T){this.chunks.shift(),this.retainedBytes-=$.length,this.omittedBytes+=$.length,f=!0;continue}let q=t0($,T);this.chunks[0]=$.subarray(q),this.retainedBytes-=q,this.omittedBytes+=q,f=!0}if(f)this.realignRetainedStart()}realignRetainedStart(){while(this.chunks.length>0){let f=this.chunks[0];if(f.length===0){this.chunks.shift();continue}let $=t0(f,0);if($===0)return;if(this.retainedBytes-=$,this.omittedBytes+=$,$===f.length)this.chunks.shift();else{this.chunks[0]=f.subarray($);return}}}compactChunks(){if(this.chunks.length<=32)return;let f=Buffer.concat(this.chunks,this.retainedBytes);if(this.chunks.length=0,f.length>0)this.chunks.push(f)}}var D0={maxLines:30,maxChars:3000,keepHead:10,keepTail:10,summarize:!0},o={maxLines:100,maxChars:1e4,keepHead:40,keepTail:40,summarize:!0},Pf={maxLines:200,maxChars:20000,keepHead:80,keepTail:80,summarize:!1},a$={maxLines:150,maxChars:15000,keepHead:50,keepTail:50,summarize:!0},s$=[{pattern:/^git\s+(rm|add)\s+(-r|--cached|-rf|-f)?\s*/i,config:D0,summaryTemplate:(f)=>`Successfully processed ${f} files`},{pattern:/^(npm|pnpm|yarn|bun)\s+(install|i|add|remove|uninstall)/i,config:D0,summaryTemplate:(f)=>`Package operation completed (${f} lines of output)`},{pattern:/^(npm|pnpm|yarn|bun)\s+(run|exec)\s+(build|compile|bundle)/i,config:o,summaryTemplate:(f)=>`Build completed (${f} lines of output)`},{pattern:/^(npm|pnpm|yarn|bun)\s+(run|exec)\s+(test|lint|check)/i,config:Pf},{pattern:/^git\s+(status|branch|remote)/i,config:o},{pattern:/^git\s+(log|diff|show)/i,config:Pf},{pattern:/^(ls|dir|tree)\s+/i,config:o,summaryTemplate:(f)=>`Listed ${f} items`},{pattern:/^find\s+/i,config:o,summaryTemplate:(f)=>`Found ${f} matches`},{pattern:/^(grep|rg|ag)\s+/i,config:o,summaryTemplate:(f)=>`Found ${f} matching lines`},{pattern:/^(docker|podman)\s+(build|pull|push)/i,config:D0,summaryTemplate:(f)=>`Docker operation completed (${f} lines)`},{pattern:/^(pip|pip3|poetry|pipenv)\s+(install|uninstall)/i,config:D0,summaryTemplate:(f)=>`Python package operation completed (${f} lines)`},{pattern:/^(cargo|rustup)\s+(build|install|update)/i,config:o,summaryTemplate:(f)=>`Rust operation completed (${f} lines)`},{pattern:/^(go)\s+(build|get|mod)/i,config:o,summaryTemplate:(f)=>`Go operation completed (${f} lines)`}];function hf(f,$,T){let q=$,B=T??f.length;if(q>0){let L=f.charCodeAt(q);if(L>=56320&&L<=57343)q+=1}if(B<f.length){let L=f.charCodeAt(B-1);if(L>=55296&&L<=56319)B-=1}return f.slice(q,B)}class s0{static getConfigForCommand(f){for(let{pattern:$,config:T,summaryTemplate:q}of s$)if($.test(f))return{config:T,summaryTemplate:q};return{config:a$}}static truncate(f,$){let{config:T,summaryTemplate:q}=this.getConfigForCommand($);return this.truncateWithConfig(f,T,q)}static truncateWithConfig(f,$,T){let q=f.length,B=f.split(`
|
|
15
|
-
`),L=B.length;if(L<=$.maxLines&&q<=$.maxChars)return{content:f,truncated:!1,originalLines:L,originalChars:q};let C=B.slice(0,$.keepHead),O=B.slice(-$.keepTail),G=L-$.keepHead-$.keepTail,_=C.join(`
|
|
16
|
-
`);if(_+=`
|
|
17
|
-
|
|
18
|
-
... (${G} lines truncated, showing first ${$.keepHead} and last ${$.keepTail} of ${L} total) ...
|
|
19
|
-
|
|
20
|
-
`,_+=O.join(`
|
|
21
|
-
`),_.length>$.maxChars){let x=Math.floor($.maxChars/2)-50,V=hf(_,0,x),Z=hf(_,_.length-x);_=`${V}
|
|
22
|
-
|
|
23
|
-
... (content truncated to ${$.maxChars} chars) ...
|
|
24
|
-
|
|
25
|
-
${Z}`}let N=$.summarize&&T?T(L,q):void 0;if(N)_+=`
|
|
26
|
-
|
|
27
|
-
[Summary: ${N}]`;return{content:_,truncated:!0,originalLines:L,originalChars:q,summary:N}}static truncateForLLM(f,$,T){let q=this.truncate(f,T),B=this.truncate($,T),L;if(q.truncated||B.truncated){let C=[];if(q.truncated)C.push(`stdout: ${q.originalLines} lines -> ${q.content.split(`
|
|
28
|
-
`).length} lines`);if(B.truncated)C.push(`stderr: ${B.originalLines} lines -> ${B.content.split(`
|
|
29
|
-
`).length} lines`);L=`Output truncated: ${C.join(", ")}`}return{stdout:q.content,stderr:B.content,truncationInfo:L}}static shouldTruncate(f,$){let{config:T}=this.getConfigForCommand($);return f.split(`
|
|
30
|
-
`).length>T.maxLines||f.length>T.maxChars}static getStats(f){return{lines:f.split(`
|
|
31
|
-
`).length,chars:f.length,words:f.split(/\s+/).filter(Boolean).length}}}var cf=32768,fT=1048576,$T=65536,TT=3600000,lf=4096,qT=/[\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(fT/2);decoder=new e$("utf8");sniffChunks=[];sniffBytes=0;binary=!1;totalBytes=0;streamedBytes=0;streamTruncated=!1;pendingEvents=[];constructor(f,$,T){this.stream=f;this.executionId=$;this.onEvent=T}append(f){let $=Buffer.isBuffer(f)?f:Buffer.from(f);if($.length===0)return;if(this.totalBytes+=$.length,this.sniffBytes<lf){let q=$.subarray(0,Math.min($.length,lf-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=pf(this.decoder.write($));this.output.append(T),this.emit(T)}finish(){if(this.binary)return;let f=pf(this.decoder.end());this.output.append(f),this.emit(f)}snapshot(){let f=this.output.peek();if(this.binary)return{content:`[binary ${this.stream} omitted: ${this.totalBytes} bytes]`,omittedBytes:this.totalBytes,binary:!0};return{content:f.content,omittedBytes:f.omittedBytes,binary:!1}}async flushEvents(){await Promise.all(this.pendingEvents),this.pendingEvents.length=0}emit(f){if(!f||!this.onEvent||this.streamTruncated)return;let $=$T-this.streamedBytes;if($<=0){this.streamTruncated=!0;return}let T=LT(f,$);if(this.streamedBytes+=Buffer.byteLength(T),T.length<f.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 pf(f){return f.replace(qT,"")}function LT(f,$){let T=Buffer.from(f);if(T.length<=$)return f;let q=$;while(q>0&&(T[q]&192)===128)q-=1;return T.subarray(0,q).toString("utf8")}function df(f){return f.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""").replaceAll("'","'")}function BT(f){let $=f.trim();if(!$)throw Error("User shell command cannot be empty");if($.length>cf)throw Error(`User shell command exceeds ${cf} characters`);if($.includes("\x00"))throw Error("User shell command contains a null byte");return $}function CT(){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",f]:["-l","-c",f],{child:L,processTree:C}=rf(q,B,{cwd:$.cwd,env:$.env,stdio:["ignore","pipe","pipe"]}),O="",G="",_=!1,N=!1,x=!1,V,Z=()=>{return V??=C.terminate(),V},E=setTimeout(()=>{_=!0,Z()},$.timeoutMs),g=()=>{N=!0,Z()};if($.signal.addEventListener("abort",g,{once:!0}),$.signal.aborted)g();L.stdout?.on("data",(W)=>{$.onOutput?.("stdout",W)}),L.stderr?.on("data",(W)=>{$.onOutput?.("stderr",W)});let b=async(W)=>{if(x)return;if(x=!0,clearTimeout(E),$.signal.removeEventListener("abort",g),_||N)await Z();T({...W,stdout:"",stderr:"",timedOut:_,aborted:N})};L.once("error",(W)=>{b({exitCode:null,error:W.message})}),L.once("close",(W)=>{b({exitCode:W})})})}}}async function u1(f,$){let T=BT(f),q=$.timeoutMs??TT,B=new e0("stdout",$.executionId,$.onEvent),L=new e0("stderr",$.executionId,$.onEvent),C=Date.now();await $.onEvent?.({type:"started",executionId:$.executionId,command:T});let O,G=!1,_=!1;try{O=await($.executor??CT()).execute(T,{cwd:$.cwd,env:$.env,timeoutMs:q,signal:$.signal,onOutput:(g,b)=>{if(g==="stdout")G=!0;else _=!0;(g==="stdout"?B:L).append(b)}})}catch(g){O={exitCode:null,stdout:"",stderr:"",error:g instanceof Error?g.message:String(g)}}if(!G)B.append(O.stdout);if(!_)L.append(O.stderr);B.finish(),L.finish(),await Promise.all([B.flushEvents(),L.flushEvents()]);let N=B.snapshot(),x=L.snapshot(),V=s0.truncateForLLM(N.content.trim(),x.content.trim(),T),Z=O.aborted||$.signal.aborted?"aborted":O.timedOut?"timed_out":O.error?"spawn_error":O.exitCode===0?"completed":"failed",E={version:1,command:T,status:Z,exitCode:O.exitCode,durationMs:Math.max(0,Date.now()-C),stdout:V.stdout,stderr:O.error?[V.stderr,O.error].filter(Boolean).join(`
|
|
32
|
-
`):V.stderr,stdoutOmittedBytes:N.omittedBytes,stderrOmittedBytes:x.omittedBytes,binaryOutput:N.binary||x.binary,truncated:Boolean(V.truncationInfo)||N.omittedBytes>0||x.omittedBytes>0};return await $.onEvent?.({type:"completed",executionId:$.executionId,record:E}),E}function n1(f){let $=[f.stdout?`stdout:
|
|
33
|
-
${f.stdout}`:"",f.stderr?`stderr:
|
|
34
|
-
${f.stderr}`:""].filter(Boolean).join(`
|
|
35
|
-
`);return["<user_shell_command>",`<command>${df(f.command)}</command>`,"<result>",`Status: ${f.status}`,`Exit code: ${f.exitCode??"null"}`,`Duration: ${(f.durationMs/1000).toFixed(3)} seconds`,`Output:
|
|
36
|
-
${df($||"(no output)")}`,"</result>","</user_shell_command>"].join(`
|
|
37
|
-
`)}function of(f){let $=[f.stdout,f.stderr?`stderr:
|
|
38
|
-
${f.stderr}`:""].filter(Boolean).join(`
|
|
39
|
-
`);return[`! ${f.command}`,$||"(no output)"].join(`
|
|
40
|
-
`)}function OT(f){if(!f||typeof f!=="object"||Array.isArray(f))return;let $=f;if($.version!==1||typeof $.command!=="string"||!["completed","failed","aborted","timed_out","spawn_error"].includes(String($.status))||$.exitCode!==null&&typeof $.exitCode!=="number"||typeof $.durationMs!=="number"||typeof $.stdout!=="string"||typeof $.stderr!=="string"||typeof $.stdoutOmittedBytes!=="number"||typeof $.stderrOmittedBytes!=="number"||typeof $.binaryOutput!=="boolean"||typeof $.truncated!=="boolean")return;return $}function A0(f){if(!f||typeof f!=="object"||Array.isArray(f))return;return OT(f.userShellCommand)}var z0=16777216,tf=65536,i1=1048576,NT=8,g0=200,GT=/(?:^|[_-])(?:api[_-]?key|authorization|bearer|cookie|credential|password|passwd|private[_-]?key|refresh[_-]?token|secret|session[_-]?token|token)(?:$|[_-])/i,xT=/(?<![:/A-Za-z0-9._-])\/[^\s"'`<>]+/g,VT=/(?<![A-Za-z0-9._-])[A-Za-z]:[\\/][^\s"'`<>]+/g,JT=new RegExp("\\u001b(?:\\[[0-?]*[ -/]*[@-~]|\\][^\\u0007]*(?:\\u0007|\\u001b\\\\))","g"),ZT=/-----BEGIN [^-]*PRIVATE KEY-----[\s\S]*?-----END [^-]*PRIVATE KEY-----/g;function w(f,$){return f.count+=1,$}function FT(f){return GT.test(f.replace(/[A-Z]/g,($)=>`_${$.toLowerCase()}`))}function QT(f){return[...f].filter(($)=>{if($===`
|
|
41
|
-
`||$==="\r"||$==="\t")return!0;let T=$.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($)}).join("")}function k(f,$){let T=f.normalize("NFKC"),q=T.replace(JT,"");if(q!==T)$.count+=1;T=q,T=T.replace(ZT,()=>w($,"[redacted-private-key]")),T=T.replace(/\bBearer\s+[^\s"'`]+/gi,()=>w($,"Bearer [redacted]")).replace(/\bsk-[A-Za-z0-9_-]{8,}\b/g,()=>w($,"[redacted-key]")).replace(/\bAKIA[0-9A-Z]{16}\b/g,()=>w($,"[redacted-aws-key]")).replace(/\b(api[_-]?key|access[_-]?token|authorization|cookie|password|passwd|refresh[_-]?token|secret|session[_-]?token)\b(\s*[:=]\s*)([^\s,;]+)/gi,(L,C,O)=>`${C}${O}${w($,"[redacted]")}`);let B=QT(T);if(B!==T)$.count+=1;return B.replace(/\r\n?/g,`
|
|
42
|
-
`)}function sf(f,$,T){if(/^data:[^;,]+;base64,/i.test(f))return w(T,"[binary omitted]");let q=k(f,T),B=af.resolve($);for(let L of[B,B.startsWith("/private/")?B.slice(8):`/private${B}`])q=q.replaceAll(L,".");return q=q.replace(xT,(L)=>L.startsWith("./")?L:w(T,"[host-path]")),q=q.replace(VT,()=>w(T,"[host-path]")),q=q.replace(/\bhttps?:\/\/[^\s"'`]+/gi,(L)=>{try{let C=new URL(L);if(C.username||C.password||C.search||C.hash)T.count+=1;return C.username="",C.password="",C.search="",C.hash="",C.toString()}catch{return w(T,"[redacted-url]")}}),q}function Tf(f,$,T,q=0,B){if(B&&FT(B))return w(T,"[redacted]");if(q>=NT)return w(T,"[depth limit]");if(typeof f==="string")return sf(f,$,T);if(f===null||typeof f==="boolean"||typeof f==="number"&&Number.isFinite(f))return f;if(Array.isArray(f)){let L=f.slice(0,g0).map((C)=>Tf(C,$,T,q+1));if(f.length>L.length)L.push(w(T,`[${f.length-L.length} items omitted]`));return L}if(f&&typeof f==="object"){let L={},C=Object.entries(f);for(let[O,G]of C.slice(0,g0))L[k(O,T)]=Tf(G,$,T,q+1,O);if(C.length>g0)L["[entries omitted]"]=C.length-g0;return L}return String(f)}function KT(f,$){let T=Buffer.from(f,"utf8");if(T.length<=$)return f;let q=T.subarray(0,$).toString("utf8");while(Buffer.byteLength(q,"utf8")>$)q=q.slice(0,-1);return q}function XT(f,$,T){let q=JSON.stringify(Tf(f,$,T),null,2);if(Buffer.byteLength(q,"utf8")<=tf)return q;T.count+=1;let B=`
|
|
43
|
-
... [activity truncated]`;return KT(q,tf-Buffer.byteLength(B))+B}function qf(f,$=""){let T=Math.max(2,...[...f.matchAll(/`+/g)].map((B)=>B[0].length)),q="`".repeat(T+1);return`${q}${$}
|
|
44
|
-
${f}
|
|
45
|
-
${q}`}function ff(f){return f.replace(/\s+/g," ").trim()}function HT(f){let $=new Map,T=new Map,q=new Map,B=0;for(let L of u(f)){if(L.type==="message_created"){let N=T.get(L.data.messageId);if(N)N.role=L.data.role,N.metadata=L.data.metadata,$.set(L.data.messageId,N),T.delete(L.data.messageId);else if(!$.has(L.data.messageId))$.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 C=$.get(L.data.messageId)??T.get(L.data.messageId);if(!C)C={order:B++,role:"activity",parts:[]},T.set(L.data.messageId,C);let O=`${L.data.messageId}\x00${L.data.partType}\x00${L.data.partId}`,G=q.get(O);if(G){G.event=L;continue}let _={order:B++,event:L};q.set(O,_),C.parts.push(_)}return[...$.values(),...T.values()].sort((L,C)=>L.order-C.order)}function $f(f,$,T,q){return`## Activity: ${f}
|
|
46
|
-
|
|
47
|
-
${qf(XT($,T.projectPath,q),"json")}`}function ef(f,$,T={}){let q={count:0},B=T.includeReasoning===!0,L=[],C=0,O=0,G=0;for(let b of HT(f)){let W=A0(b.metadata);if(W){let D=k(W.command,q),R=k([W.stdout,W.stderr?`stderr:
|
|
48
|
-
${W.stderr}`:""].filter(Boolean).join(`
|
|
49
|
-
`)||"(no output)",q);L.push(`## User shell command
|
|
50
|
-
|
|
51
|
-
${qf(`$ ${D}
|
|
52
|
-
${R}`,"console")}`),C+=1;continue}let s=[],e=[],y=[],S=Number.POSITIVE_INFINITY;for(let D of b.parts.sort((R,z)=>R.order-z.order)){let{partType:R,payload:z}=D.event.data;if(R==="text"){let Q=z.text;if(typeof Q==="string"&&Q.trim())s.push(k(Q,q)),S=Math.min(S,D.order)}else if(R==="image"){let Q=z.mimeType;e.push(typeof Q==="string"?`[Image: ${k(Q,q)}]`:"[Image]"),S=Math.min(S,D.order)}else if(R==="reasoning"&&B){let Q=z.text;if(typeof Q==="string"&&Q.trim())y.push({order:D.order,markdown:`## Reasoning
|
|
53
|
-
|
|
54
|
-
${k(Q,q).trim()}`}),G+=1}else if(R==="tool_call"){let Q=z,M=typeof Q.toolName==="string"?k(Q.toolName,q):"unknown";y.push({order:D.order,markdown:$f(`${M} call`,Q.input??{},$,q)}),O+=1}else if(R==="tool_result"){let Q=z,M=typeof Q.toolName==="string"?k(Q.toolName,q):"unknown";y.push({order:D.order,markdown:$f(`${M} result`,typeof Q.error==="string"?{error:Q.error}:{output:Q.output??null},$,q)}),O+=1}else if(R==="summary"){let Q=z.text;if(typeof Q==="string"&&Q.trim())y.push({order:D.order,markdown:`## Summary
|
|
55
|
-
|
|
56
|
-
${k(Q,q).trim()}`})}else if(R==="subtask_ref")y.push({order:D.order,markdown:$f("Subagent",z,$,q)}),O+=1;else if(R==="diff"||R==="patch"){let Q=typeof z==="string"?z:JSON.stringify(z,null,2);y.push({order:D.order,markdown:`## File changes
|
|
57
|
-
|
|
58
|
-
${qf(sf(Q,$.projectPath,q),"diff")}`}),O+=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()}`}),C+=1;L.push(...y.sort((D,R)=>D.order-R.order).map((D)=>D.markdown))}if(L.length===0)throw Error("No conversation content to export");let _=`${L.join(`
|
|
63
|
-
|
|
64
|
-
`)}
|
|
65
|
-
`,N=Buffer.byteLength(_,"utf8");if(N>z0)throw Error(`Session export exceeds ${z0} bytes`);let x=_T("sha256").update(_).digest("hex"),V=af.basename($.taskSourceProjectPath??$.projectPath),Z=$.selectedModelId??$.taskModelId,g=["# Blade conversation","",`- Session: \`${$.sessionId}\``,...$.title?[`- Title: ${ff(k($.title,q))}`]:[],`- Project: \`${ff(k(V,q))}\``,...Z?[`- Model: \`${ff(k(Z,q))}\``]:[],...$.permissionMode?[`- Permission mode: ${$.permissionMode}`]:[],`- Created: ${$.firstMessageTime}`,`- Updated: ${$.lastMessageTime}`,`- State: ${$.archivedAt?"archived":"active"}`,`- Reasoning: ${B?"included":"omitted"}`,...$.reasoningEffort?[`- Reasoning effort: ${$.reasoningEffort}`]:[],...$.serviceTier?[`- Service tier: ${$.serviceTier}`]:[],...$.responseVerbosity?[`- Response verbosity: ${$.responseVerbosity}`]:[],...$.communicationStyle?[`- Communication style: ${$.communicationStyle}`]:[],...$.communicationStyleDigest?[`- Communication style SHA-256: \`${$.communicationStyleDigest}\``]:[],...$.projectInstructionsDigest?[`- Project instructions SHA-256: \`${$.projectInstructionsDigest}\``]:[],`- Content SHA-256: \`${x}\``,`- Content bytes: ${N}`,`- Redactions: ${q.count}`,"","---",""].join(`
|
|
66
|
-
`)+`
|
|
67
|
-
`+_;if(Buffer.byteLength(g,"utf8")>z0)throw Error(`Session export exceeds ${z0} bytes`);return{filename:`blade-session-${$.sessionId.slice(0,12)}.md`,markdown:g,contentSha256:x,contentBytes:N,messageCount:C,activityCount:O,reasoningIncluded:B,reasoningCount:G,redactionCount:q.count}}import{createHash as YT}from"node:crypto";import WT from"ajv";var O$="StructuredOutput",f$=65536,$$=131072,t1=2,T$=20,q$=1000,L$=200;function t(f){return f!==null&&typeof f==="object"&&!Array.isArray(f)}function B$(f,$){if(!t(f))throw Error(`${$} must be a JSON object`);let T;try{T=JSON.stringify(f)}catch(B){throw Error(`${$} must be JSON-serializable`,{cause:B})}if(T===void 0)throw Error(`${$} must be JSON-serializable`);let q=JSON.parse(T);if(!t(q))throw Error(`${$} must be a JSON object`);return q}function UT(f){let $=0,T=0,q=(B,L)=>{if($++,$>q$)throw Error(`Output schema exceeds the ${q$} node complexity limit`);if(L>T$)throw Error(`Output schema exceeds the ${T$} level depth limit`);if(Array.isArray(B)){for(let C of B)q(C,L+1);return}if(!t(B))return;if("$ref"in B){let C=B.$ref;if(typeof C!=="string"||!(C==="#"||C.startsWith("#/$defs/")||C.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>L$)throw Error(`Output schema exceeds the ${L$} property limit`)}for(let C of Object.values(B))q(C,L+1)};q(f,0)}function RT(f){if(!f||f.length===0)return"Structured output does not match the requested schema";return f.slice(0,8).map(($)=>{return`${$.instancePath||"root"}: ${$.message??$.keyword}`}).join("; ")}function DT(f){let $=new WT({allErrors:!0,strict:!1,allowUnionTypes:!0,validateFormats:!1});try{return $.compile(f)}catch(T){throw Error(`Invalid output schema: ${T instanceof Error?T.message:String(T)}`)}}function _$(f){let $=B$(f,"Output schema"),T=JSON.stringify($);if(Buffer.byteLength(T)>f$)throw Error(`Output schema exceeds ${f$} bytes`);if($.type!=="object")throw Error('Output schema root type must be "object"');UT($);let B=DT($),L=YT("sha256").update(T).digest("hex");return{schema:$,schemaDigest:L,declaration:{name:O$,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:$,constrainedSampling:{type:"json_schema",strict:"prefer"}},validate(C){let O;try{O=B$(C,"Structured output")}catch(_){return{success:!1,message:_ instanceof Error?_.message:String(_)}}let G=JSON.stringify(O);if(Buffer.byteLength(G)>$$)return{success:!1,message:`Structured output exceeds ${$$} bytes`};if(!B(O))return{success:!1,message:RT(B.errors)};return{success:!0,output:O}}}}function C$(f,$){if(!t(f))return;let T=t(f.structuredOutput)?f.structuredOutput:f;if(T.schemaDigest!==$.schemaDigest||!("output"in T))return;let q=$.validate(T.output);return q.success?q.output:void 0}function a1(f,$){for(let T=f.length-1;T>=0;T--){let q=f[T];if(!q)continue;if(q.role==="user")return;if(q.role==="assistant"){let C=C$(q.metadata,$);if(C)return{output:C,completed:!0};continue}if(q.role!=="tool"||q.name!==O$)continue;let B=t(q.metadata)?q.metadata:void 0,L=C$(B?.metadata,$);if(L)return{output:L,completed:!1}}return}var _0=U0("Service"),N$=new Set(["queued","running","completed","failed","cancelled","interrupted"]),Jf=new Set(["local","worktree"]),AT=new Set(["default","autoEdit","yolo","plan"]),zT=new Set(["applied","discarded","conflicted"]),gT=86400000;class Zf extends Error{}function G$(f){try{return process.kill(f,0),!0}catch($){return $ instanceof Error&&"code"in $&&$.code==="EPERM"}}function x$(f){if(!f||typeof f!=="object"||Array.isArray(f))return;let $=f;if(["sessionId","name","branch","baseCommit","originalBranch","repositoryRoot","originalWorkspaceRoot","worktreeRoot","workspaceRoot"].some((q)=>typeof $[q]!=="string"||!$[q])||typeof $.sourceHadChanges!=="boolean"||$.sourceStateFingerprint!==void 0&&(typeof $.sourceStateFingerprint!=="string"||!/^[a-f0-9]{64}$/.test($.sourceStateFingerprint)))return;return $}function V$(f){if(!f||typeof f!=="object"||Array.isArray(f))return;let $=f;if(!zT.has(String($.status))||typeof $.updatedAt!=="string"||!Number.isFinite(Date.parse($.updatedAt))||$.sourceCommit!==void 0&&(typeof $.sourceCommit!=="string"||!/^[a-f0-9]{40,64}$/.test($.sourceCommit))||$.changedFiles!==void 0&&(typeof $.changedFiles!=="number"||!Number.isInteger($.changedFiles)||$.changedFiles<0)||$.message!==void 0&&(typeof $.message!=="string"||!$.message.trim()||$.message.length>500))return;return{status:$.status,updatedAt:$.updatedAt,...typeof $.sourceCommit==="string"?{sourceCommit:$.sourceCommit}:{},...typeof $.changedFiles==="number"?{changedFiles:$.changedFiles}:{},...typeof $.message==="string"?{message:$.message}:{}}}function J$(f){if(!f||typeof f!=="object"||Array.isArray(f))return;let $=f;if(["changedFiles","additions","deletions","commits"].some((q)=>typeof $[q]!=="number"||!Number.isInteger($[q])||$[q]<0))return;return $}function Z$(f){if(!f||typeof f!=="object"||Array.isArray(f))return;let $=f,T;if($.outputSchema!==void 0)try{T=_$($.outputSchema).schema}catch{return}if($.version!==1||typeof $.prompt!=="string"||!$.prompt.trim()||$.prompt.length>32000||typeof $.sourceProjectPath!=="string"||!J.isAbsolute($.sourceProjectPath)||!Jf.has($.isolation)||!b0($.permissionMode)||$.title!==void 0&&(typeof $.title!=="string"||!$.title.trim()||$.title.length>200)||$.modelId!==void 0&&(typeof $.modelId!=="string"||!$.modelId.trim()||$.modelId.length>500)||$.reasoningEffort!==void 0&&!J0($.reasoningEffort)||$.serviceTier!==void 0&&!V0($.serviceTier)||$.responseVerbosity!==void 0&&!x0($.responseVerbosity)||$.communicationStyle!==void 0&&!Z0($.communicationStyle)||$.communicationStyleDigest!==void 0&&(typeof $.communicationStyleDigest!=="string"||!/^[a-f0-9]{64}$/.test($.communicationStyleDigest))||$.projectInstructionsDigest!==void 0&&(typeof $.projectInstructionsDigest!=="string"||!/^[a-f0-9]{64}$/.test($.projectInstructionsDigest)))return;let q;if($.attachments!==void 0){if(!Array.isArray($.attachments)||$.attachments.length>H$)return;let B=0;for(let L of $.attachments){if(!L||typeof L!=="object"||Array.isArray(L))return;let C=L;if(!["file","image","url"].includes(String(C.type)))return;for(let O of["path","url","content","mimeType","name"])if(C[O]!==void 0&&typeof C[O]!=="string")return;B+=typeof C.content==="string"?Buffer.byteLength(C.content):0}if(B>Y$)return;q=$.attachments.map((L)=>{let C=L;return{type:C.type,...C.path!==void 0?{path:C.path}:{},...C.url!==void 0?{url:C.url}:{},...C.content!==void 0?{content:C.content}:{},...C.mimeType!==void 0?{mimeType:C.mimeType}:{},...C.name!==void 0?{name:C.name}:{}}})}return{version:1,prompt:$.prompt,...typeof $.title==="string"?{title:$.title}:{},sourceProjectPath:J.resolve($.sourceProjectPath),isolation:$.isolation,permissionMode:$.permissionMode,...typeof $.modelId==="string"?{modelId:$.modelId}:{},...J0($.reasoningEffort)?{reasoningEffort:$.reasoningEffort}:{},...V0($.serviceTier)?{serviceTier:$.serviceTier}:{},...x0($.responseVerbosity)?{responseVerbosity:$.responseVerbosity}:{},...Z0($.communicationStyle)?{communicationStyle:$.communicationStyle}:{},...typeof $.communicationStyleDigest==="string"?{communicationStyleDigest:$.communicationStyleDigest}:{},...typeof $.projectInstructionsDigest==="string"?{projectInstructionsDigest:$.projectInstructionsDigest}:{},...q?{attachments:q}:{},...T?{outputSchema:T}:{}}}function b0(f){return typeof f==="string"&&AT.has(f)}function F$(f){if(!f||typeof f!=="object"||Array.isArray(f))return;let $=f;if(typeof $.sessionId!=="string"||!$.sessionId||typeof $.projectPath!=="string"||!J.isAbsolute($.projectPath))return;return{sessionId:$.sessionId,projectPath:J.resolve($.projectPath)}}var A$={stat(f){return E0(f,{bigint:!0})},readFile(f){return a(f,"utf-8")}},G0=A$;function Aq(f){G0=f}function zq(){G0=A$}class z$ extends Error{constructor(f){super(`Session has no durable creation record: ${f}`);this.name="SessionMissingCreationError"}}class $0 extends Error{sessionId;archivedBySessionId;code="BLADE_SESSION_ARCHIVED";constructor(f,$){super(f===$?`Session is archived: ${f}`:`Session is archived by ancestor ${$}: ${f}`);this.sessionId=f;this.archivedBySessionId=$;this.name="SessionArchivedError"}}class n extends Error{code="BLADE_SESSION_ARCHIVE_CONFLICT";constructor(f){super(f);this.name="SessionArchiveConflictError"}}function Bf(f,$){return`${f}\x00${$}`}function MT(f){if(f.kind==="base")return`/review base ${f.baseSha??f.label}`;if(f.kind==="commit")return`/review commit ${f.commitSha??f.label}`;return"/review uncommitted"}function g$(f){return typeof f==="string"&&f.length<=64&&Number.isFinite(Date.parse(f))}function ET(f){let $=new Map(f.map((T)=>[Bf(T.projectPath,T.sessionId),T]));return f.map((T)=>{let q=T,B=new Set;while(q){let G=Bf(q.projectPath,q.sessionId);if(B.has(G))break;if(B.add(G),g$(q.archivedAt))return{...T,archivedAt:q.archivedAt,archivedBySessionId:q.sessionId};q=q.parentId?$.get(Bf(q.projectPath,q.parentId)):void 0}let{archivedAt:L,archivedBySessionId:C,...O}=T;return O})}function Cf(f,$){let T=ET(f);if($===null)return T;return T.filter((q)=>Boolean(q.archivedAt)===$)}class X{static toUISafeMessages(f){let $=Date.now(),T=f.length,q=[];return f.forEach((B,L)=>{if(B.role!=="user"&&B.role!=="assistant"||!nf(B))return;let C;if(typeof B.content==="string")C=B.content;else if(Array.isArray(B.content))C=B.content.map((x)=>x.type==="text"?x.text:"[Image]").join("");else C="";let O=C.trim();if(!O)return;let G=A0(B.metadata),_=G?of(G):O,N=q[q.length-1];if(N&&N.role===B.role&&N.content===_)return;q.push({id:`restored-${$}-${L}`,role:B.role,content:_,timestamp:$-(T-L)*1000,metadata:B.metadata&&typeof B.metadata==="object"?B.metadata:void 0})}),q}static async listSessionPage(f={}){let $=Nf(f),T=await this.listSessionPageFromProjection($);if(T)return T;let B=(await this.scanStoredSessions($.cwd??void 0,$.includeSubagents,$.cursor?5000:0,$.archived)).sort(Gf),L=xf(B,$);return{sessions:L.sessions.map((C)=>this.toPublicMetadata(C)),nextCursor:L.nextCursor}}static async listSessionPageFromProjection(f){let $=R$(f);try{let T=await M0();if(!T)return null;await Vf(T,this.projectionDeriver(),f.cursor?5000:0);let q=[],B=[];if(f.cwd)q.push("s.project_path = ?"),B.push(f.cwd);if(!f.includeSubagents)q.push("s.is_subagent = 0");if(q.push(f.archived?"a.session_id IS NOT NULL":"a.session_id IS NULL"),$){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 G=_f($.projectPath);B.push($.lastMessageTime,$.lastMessageTime,G,G,_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,f.limit+1),C=await Promise.all(L.map(async(G)=>{let _=JSON.parse(G.metadata_json);if(G.archive_root_id&&G.effective_archived_at)return this.reconcileInterruptedTask({..._,archivedAt:G.effective_archived_at,archivedBySessionId:G.archive_root_id});let{archivedAt:N,archivedBySessionId:x,...V}=_;return this.reconcileInterruptedTask(V)})),O=xf(C,f);return{sessions:O.sessions.map((G)=>this.toPublicMetadata(G)),nextCursor:O.nextCursor}}catch{return null}}static async listSessions(f={}){let $=Nf(f),T=await this.scanStoredSessions($.cwd??void 0,$.includeSubagents,0,$.archived),q=new Set;return T.sort(Gf).flatMap((B)=>{let L=`${B.projectPath}\x00${B.sessionId}`;if(q.has(L))return[];return q.add(L),[this.toPublicMetadata(B)]})}static async collectStaleEmptySessions(f={}){let $=f.now??Date.now(),T=f.olderThanMs??gT;if(!Number.isFinite(T)||T<0)throw Error("Stale empty session age must be a non-negative number");let q=f.projectPath?[{storagePath:q0(this.resolveCatalogWorkspace(f.projectPath)),projectPath:this.resolveCatalogWorkspace(f.projectPath)}]:await this.listAllProjectStorageDirectories(),B=0;for(let L of q){let C;try{C=await Lf(L.storagePath)}catch(O){if(O.code==="ENOENT")continue;throw O}for(let O of C){if(!O.endsWith(".jsonl"))continue;let G=O.slice(0,-6);if(!X$(G))continue;let _=J.join(L.storagePath,O);try{let x=await E0(_);if($-x.mtimeMs<T)continue;if(await Promise.all([E0(J.join(L.storagePath,`${G}.inbox.json`)).then(()=>!0).catch(()=>!1),E0(N0(L.projectPath,G)).then(()=>!0).catch(()=>!1)]).then((Z)=>Z.some(Boolean)))continue}catch(x){if(x.code==="ENOENT")continue;throw x}let N;try{N=await h.acquire(G,L.projectPath)}catch(x){if(x instanceof P)continue;throw x}try{if(!await new I(_).deleteValidated((V)=>V.length===1&&V[0]?.type==="session_created"&&V[0].data.relationType!=="subagent"))continue;B++,await f0(J.join(L.storagePath,`${G}.inbox.json`),{force:!0}),await f0(N0(L.projectPath,G),{force:!0}),await this.removeFromProjection(G,L.projectPath)}catch(x){_0.warn(`[SessionService] Skipping stale empty session cleanup: ${G}`,x)}finally{await N.release()}}}return B}static async findSessionMetadata(f,$){if(A(f),$!==void 0){if(!J.isAbsolute($))throw Error("Session catalog cwd must be absolute");let q=J.resolve($),B=this.getSessionFilePath(q,f);try{let L=await this.readStoredSessionMetadata(B,f,q);if(L.projectPath!==q)return;if(!L.parentId||L.archivedAt)return this.toPublicMetadata(Cf([L],null)[0]??L);let C=await this.scanStoredSessions(q,!0,0,null);return this.toPublicMetadata(C.find((O)=>O.sessionId===f)??L)}catch(L){if(L.code==="ENOENT")return;throw L}}let T=(await this.scanStoredSessions(void 0,!0,0,null)).filter((q)=>q.sessionId===f);if(T.length===0)return;if(T.length>1)throw Error(`Ambiguous session ID: ${f}`);return this.toPublicMetadata(T[0])}static async loadSession(f,$){try{if($){if(!J.isAbsolute($))throw Error("Session catalog cwd must be absolute");let q=J.resolve($),B=this.getSessionFilePath(q,f);try{return await this.loadSessionFromFile(B,f,q)}catch(L){if(L.code==="ENOENT")throw Error(`未找到会话: ${f}`);throw L}}let T=(await this.scanStoredSessions(void 0,!0,0,null)).find((q)=>q.sessionId===f);if(!T)throw Error(`未找到会话: ${f}`);return await this.loadSessionFromFile(T.filePath,f)}catch(T){throw _0.error(`[SessionService] 加载会话失败 (${f}):`,T),T}}static async loadSessionModelContext(f,$){try{if($){if(!J.isAbsolute($))throw Error("Session catalog cwd must be absolute");let q=J.resolve($),B=this.getSessionFilePath(q,f);try{return await this.loadSessionModelContextFromFile(B,f,q)}catch(L){if(L.code==="ENOENT")throw Error(`未找到会话: ${f}`);throw L}}let T=(await this.scanStoredSessions(void 0,!0,0,null)).find((q)=>q.sessionId===f);if(!T)throw Error(`未找到会话: ${f}`);return await this.loadSessionModelContextFromFile(T.filePath,f)}catch(T){throw _0.error(`[SessionService] 加载模型上下文失败 (${f}):`,T),T}}static async exportSessionMarkdown(f,$,T={}){A(f);let q=this.resolveCatalogWorkspace($),B=m(q,f),L;try{L=await this.readStableSessionSnapshot(B,f)}catch(G){throw this.sanitizeStoredSessionError(G,f)}let C=this.projectMetadataFromEntries(L,f,q,B);if(C.projectPath!==q)throw Error(`Session export workspace mismatch: ${f}`);let O=C.archivedAt;if(!O&&C.parentId)O=(await this.findArchivedAncestor(C.parentId,q))?.archivedAt;return ef(L,{...C,archivedAt:O},T)}static async listRewindCheckpoints(f,$){A(f);let T=this.resolveCatalogWorkspace($),q=m(T,f),B=await this.readStableSessionSnapshot(q,f);this.validateSessionWorkspace(B,f,T);let L=new R0({sessionId:f,workspaceRoot:T});await L.initialize();let C=W$(B),O=[];for(let G of C){let _=Of(B,G.messageId),N=await L.previewRewind(_.snapshotMessageIds);O.push({...G,fileCount:N.files.length})}return O}static async rewindSession(f,$,T){A(f);let q=this.resolveCatalogWorkspace($);await this.assertSessionWritable(f,q);let B=m(q,f),L=new I(B),C;try{await L.appendValidatedAsync(async(O)=>{this.validateSessionWorkspace(O,f,q);let G=Of(O,T.targetMessageId),_=new R0({sessionId:f,workspaceRoot:q});await _.initialize();let N=await _.previewRewind(G.snapshotMessageIds),x=T.mode==="conversation"?await _.commitSnapshots(G.snapshotMessageIds):await _.rewindSnapshots(G.snapshotMessageIds),V=new Date().toISOString(),Z={id:j(),sessionId:f,timestamp:V,type:"session_rewound",cwd:q,gitBranch:l(q),version:p(),data:{rewindId:j(),targetMessageId:T.targetMessageId,mode:T.mode,restoredFiles:T.mode==="conversation"?[]:x.files,createdAt:V}},E=u([...O,Z]);return C={checkpoint:{...G.checkpoint,fileCount:N.files.length},mode:T.mode,removedTurns:G.removedTurns,restoredFiles:Z.data.restoredFiles,messages:this.convertJSONLToMessages(E)},Z})}catch(O){throw this.sanitizeStoredSessionError(O,f)}if(!C)throw Error(`Session rewind did not produce a result: ${f}`);for(let O of C.restoredFiles)c.getInstance().clearFileRecord(O);return C}static async forkSession(f,$){A(f);let T=$.newSessionId??`fork-${Date.now()}-${j(8)}`;A(T);let q=this.resolveForkWorkspace($.sourceProjectPath),B=this.resolveForkWorkspace($.targetProjectPath);if(q!==B)throw Error("Session forks must stay in the source workspace");let L=m(q,f),C=await this.readStableSessionSnapshot(L,f),O=this.getSessionCreatedEntry(C,f);if(O.data.sessionId!==f)throw Error("Fork source session_created.data.sessionId must match the requested session ID");if(!J.isAbsolute(O.cwd)||J.resolve(O.cwd)!==q)throw Error("Fork source session_created.cwd must resolve to the requested source workspace");let G=this.projectMetadataFromEntries(C,f,q,L);if(G.archivedAt)throw new $0(f,f);if(G.parentId){let Y=await this.findArchivedAncestor(G.parentId,q);if(Y)throw new $0(f,Y.sessionId)}let _=u(C),N=new Date().toISOString(),x=O.data.rootId||f,V=l(B),Z=p(),{status:E,taskStatus:g,taskStatusReason:b,taskFailure:W,taskStartedAt:s,taskCompletedAt:e,taskOwnerPid:y,taskPromptSummary:S,taskDispatch:D,taskModelId:R,taskRetriedFrom:z,taskDelivery:Q,taskIsolation:M,taskSourceProjectPath:k0,taskWorktree:Ff,taskDiffStat:Qf,taskQueuePosition:Kf,taskQueueDepth:Xf,taskConcurrencyLimit:Hf,pendingInteraction:w0,...y0}=O.data,S0={id:j(),sessionId:T,timestamp:N,type:"session_created",cwd:B,gitBranch:V,version:Z,data:{...y0,sessionId:T,rootId:x,parentId:f,relationType:"fork",taskStatus:"completed",taskCompletedAt:N,taskIsolation:"local",taskSourceProjectPath:B,createdAt:N,updatedAt:N}},j0=_.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:V,version:Z};if(Y.type==="session_updated"){let{status:Q0,taskStatus:U,taskStatusReason:v0,taskFailure:bT,taskStartedAt:kT,taskCompletedAt:wT,taskOwnerPid:yT,taskPromptSummary:ST,taskDispatch:jT,taskModelId:mT,taskRetriedFrom:IT,taskDelivery:vT,taskIsolation:uT,taskSourceProjectPath:nT,taskWorktree:PT,taskDiffStat:hT,taskQueuePosition:cT,taskQueueDepth:lT,taskConcurrencyLimit:pT,pendingInteraction:iT,...M$}=Y.data;return{...i,type:"session_updated",data:{...M$,sessionId:T,rootId:x,parentId:f,relationType:"fork"}}}if(Y.type==="message_created"){let{inboxMessageId:Q0,...U}=Y.data;return{...i,type:"message_created",data:U}}return i}),m0={id:j(),sessionId:T,timestamp:N,type:"session_updated",cwd:B,gitBranch:V,version:Z,data:{sessionId:T,rootId:x,parentId:f,relationType:"fork",taskStatus:"completed",taskStatusReason:null,taskFailure:null,taskStartedAt:null,taskCompletedAt:N,taskOwnerPid:null,taskIsolation:"local",taskSourceProjectPath:B,taskWorktree:null,taskDiffStat:null,taskDelivery:null,taskQueuePosition:null,taskQueueDepth:null,taskConcurrencyLimit:null,updatedAt:N}},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:f,projectPath:B,messages:this.convertJSONLToMessages(T0),metadata:this.toPublicMetadata(I0)}}static async deleteSession(f,$){if(A(f),$){if(!J.isAbsolute($))throw Error("Session catalog cwd must be absolute");let q=J.resolve($),B=this.getSessionFilePath(q,f),L=new I(B),C;try{C=await L.deleteValidated((O)=>{return this.projectMetadataFromEntries(O,f,q,B).projectPath===q})}catch(O){if(!this.isCorruptSessionJSONLError(O))throw O;C=await L.delete()}if(!C)return 0;return await f0(J.join(J.dirname(B),`${f}.inbox.json`),{force:!0}),await f0(N0(q,f),{force:!0}),await this.removeFromProjection(f,q),1}let T=(await this.scanStoredSessions(void 0,!0)).filter((q)=>q.sessionId===f);if(T.length===0)return 0;return await Promise.all(T.map(async(q)=>{await new I(q.filePath).delete(),await f0(J.join(J.dirname(q.filePath),`${q.sessionId}.inbox.json`),{force:!0}),await f0(N0(q.projectPath,q.sessionId),{force:!0}),await this.removeFromProjection(q.sessionId,q.projectPath)})),T.length}static async removeFromProjection(f,$){try{let T=await M0();if(T)D$(T,f,$)}catch{}}static validateTaskMetadataUpdate(f,$){if(f.taskPromptSummary!==void 0&&f.taskPromptSummary!==null&&(!f.taskPromptSummary.trim()||f.taskPromptSummary.length>1000))throw Error("Session task prompt summary must contain 1-1000 characters");if(f.taskFailure!==void 0&&f.taskFailure!==null&&!p0(f.taskFailure))throw Error("Invalid session task failure");if(f.taskDispatch!==void 0&&f.taskDispatch!==null&&!Z$(f.taskDispatch))throw Error("Invalid durable task dispatch");if(f.taskModelId!==void 0&&f.taskModelId!==null&&(!f.taskModelId.trim()||f.taskModelId.length>500))throw Error("Invalid session task model ID");if(f.selectedModelId!==void 0&&f.selectedModelId!==null&&(!f.selectedModelId.trim()||f.selectedModelId.length>500))throw Error("Invalid selected session model ID");if(f.permissionMode!==void 0&&f.permissionMode!==null&&!b0(f.permissionMode))throw Error("Invalid session permission mode");if(f.reasoningEffort!==void 0&&f.reasoningEffort!==null&&!J0(f.reasoningEffort))throw Error("Invalid session reasoning effort");if(f.serviceTier!==void 0&&f.serviceTier!==null&&!V0(f.serviceTier))throw Error("Invalid session service tier");if(f.responseVerbosity!==void 0&&f.responseVerbosity!==null&&!x0(f.responseVerbosity))throw Error("Invalid session response verbosity");if(f.communicationStyle!==void 0&&f.communicationStyle!==null&&!Z0(f.communicationStyle))throw Error("Invalid session communication style");if(f.communicationStyleDigest!==void 0&&f.communicationStyleDigest!==null&&!/^[a-f0-9]{64}$/.test(f.communicationStyleDigest))throw Error("Invalid session communication style digest");if(f.projectInstructionsDigest!==void 0&&f.projectInstructionsDigest!==null&&!/^[a-f0-9]{64}$/.test(f.projectInstructionsDigest))throw Error("Invalid session project instructions digest");if(f.taskRetriedFrom!==void 0&&f.taskRetriedFrom!==null&&!F$(f.taskRetriedFrom))throw Error("Invalid session task retry source");if(f.taskDelivery!==void 0&&f.taskDelivery!==null&&!V$(f.taskDelivery))throw Error("Invalid session task delivery");if(f.taskIsolation!==void 0&&f.taskIsolation!==null&&!Jf.has(f.taskIsolation))throw Error(`Invalid session task isolation: ${String(f.taskIsolation)}`);if(f.taskSourceProjectPath!==void 0&&f.taskSourceProjectPath!==null&&!J.isAbsolute(f.taskSourceProjectPath))throw Error("Session task source project path must be absolute");if(f.taskWorktree!==void 0&&f.taskWorktree!==null){let T=x$(f.taskWorktree);if(!T||T.sessionId!==$||![T.repositoryRoot,T.originalWorkspaceRoot,T.worktreeRoot,T.workspaceRoot].every((q)=>J.isAbsolute(q)))throw Error("Invalid session task worktree metadata")}if(f.taskDiffStat!==void 0&&f.taskDiffStat!==null&&!J$(f.taskDiffStat))throw Error("Invalid session task diff stat");if(f.taskQueuePosition!==void 0&&f.taskQueuePosition!==null&&(!Number.isInteger(f.taskQueuePosition)||f.taskQueuePosition<1))throw Error("Invalid session task queue position");if(f.taskQueueDepth!==void 0&&f.taskQueueDepth!==null&&(!Number.isInteger(f.taskQueueDepth)||f.taskQueueDepth<0))throw Error("Invalid session task queue depth");if(f.taskConcurrencyLimit!==void 0&&f.taskConcurrencyLimit!==null&&(!Number.isInteger(f.taskConcurrencyLimit)||f.taskConcurrencyLimit<1))throw Error("Invalid session task concurrency limit");if(typeof f.taskQueuePosition==="number"&&typeof f.taskQueueDepth==="number"&&f.taskQueuePosition>f.taskQueueDepth)throw Error("Session task queue position exceeds queue depth")}static async createSessionMetadata(f,$,T={}){A(f),X.validateTaskMetadataUpdate(T,f);let q=X.resolveCatalogWorkspace($);if(T.taskWorktree&&J.resolve(T.taskWorktree.workspaceRoot)!==q)throw Error("Session task worktree must match the catalog workspace");let B=new Date().toISOString(),L={id:j(),sessionId:f,timestamp:B,type:"session_created",cwd:q,gitBranch:l(q),version:p(),data:{sessionId:f,rootId:f,...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}},C=X.getSessionFilePath(q,f);return await new I(C).createExclusive([L]),X.toPublicMetadata(X.projectMetadataFromEntries([L],f,q,C))}static async assertSessionWritable(f,$){let T=await this.findSessionMetadata(f,$);if(!T)throw Error(`Session not found: ${f}`);if(T.archivedAt)throw new $0(f,T.archivedBySessionId??f);return T}static async findArchivedAncestor(f,$){let T=new Set,q=f;while(q){if(T.has(q))throw Error("Session lineage contains a cycle");T.add(q),A(q);let B=m($,q),L;try{L=await a(B,"utf8")}catch(O){if(O.code==="ENOENT")return;throw O}let C=this.projectMetadataFromEntries(this.parseStoredSession(L,q),q,$,B);if(C.projectPath!==$)throw Error("Session lineage escapes the requested workspace");if(C.archivedAt)return{sessionId:C.sessionId,archivedAt:C.archivedAt};q=C.parentId}return}static async listSessionArchiveMembers(f,$){A(f);let T=this.resolveCatalogWorkspace($),q=await this.scanStoredSessions(T,!0,0,null);if(!q.some((C)=>C.sessionId===f))throw Error(`Session not found: ${f}`);let B=new Set([f]),L=!0;while(L){L=!1;for(let C of q)if(C.parentId&&B.has(C.parentId)&&!B.has(C.sessionId))B.add(C.sessionId),L=!0}return q.filter((C)=>B.has(C.sessionId)).sort((C,O)=>C.sessionId.localeCompare(O.sessionId)).map((C)=>this.toPublicMetadata(C))}static async archiveSession(f,$){A(f);let T=this.resolveCatalogWorkspace($),q=await this.findSessionMetadata(f,T);if(!q)throw Error(`Session not found: ${f}`);if(q.archivedAt)return q;let B=await this.listSessionArchiveMembers(f,T),L=B.find((O)=>O.taskStatus==="queued"||O.taskStatus==="running");if(L)throw new n(`Stop session ${L.sessionId} before archiving this session tree`);let C=[];try{for(let N of B)C.push(await h.acquire(N.sessionId,T));let O=m(T,f),G=new I(O),_=[];return await G.appendValidated((N)=>{let x=this.projectMetadataFromEntries(N,f,T,O);if(x.archivedAt)throw new n(`Session archive state changed concurrently: ${f}`);if(x.taskStatus==="queued"||x.taskStatus==="running")throw new n(`Stop session ${f} before archiving it`);let V=new Date().toISOString(),Z={id:j(),sessionId:f,timestamp:V,type:"session_updated",cwd:T,gitBranch:l(T),version:p(),data:{sessionId:f,archivedAt:V,updatedAt:V}};return _=[...N,Z],Z}),this.toPublicMetadata({...this.projectMetadataFromEntries(_,f,T,O),archivedBySessionId:f})}catch(O){if(O instanceof n)throw O;if(O instanceof P)throw new n(O.message);throw this.sanitizeStoredSessionError(O,f)}finally{for(let O of C.reverse())await O.release()}}static async unarchiveSession(f,$){A(f);let T=this.resolveCatalogWorkspace($),q=await this.findSessionMetadata(f,T);if(!q)throw Error(`Session not found: ${f}`);if(!q.archivedAt)return q;if(q.archivedBySessionId&&q.archivedBySessionId!==f)throw new n(`Unarchive ancestor ${q.archivedBySessionId} to restore session ${f}`);let B;try{B=await h.acquire(f,T);let L=m(T,f),C=new I(L),O=[];return await C.appendValidated((G)=>{if(!this.projectMetadataFromEntries(G,f,T,L).archivedAt)throw new n(`Session archive state changed concurrently: ${f}`);let N=new Date().toISOString(),x={id:j(),sessionId:f,timestamp:N,type:"session_updated",cwd:T,gitBranch:l(T),version:p(),data:{sessionId:f,archivedAt:null,updatedAt:N}};return O=[...G,x],x}),this.toPublicMetadata(this.projectMetadataFromEntries(O,f,T,L))}catch(L){if(L instanceof n)throw L;if(L instanceof P)throw new n(L.message);throw this.sanitizeStoredSessionError(L,f)}finally{await B?.release()}}static async updateSessionMetadata(f,$,T){if(A(f),X.validateTaskMetadataUpdate(T,f),T.taskStatus!==void 0&&!N$.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($);if(T.taskWorktree&&J.resolve(T.taskWorktree.workspaceRoot)!==q)throw Error("Session task worktree must match the catalog workspace");let B=X.getSessionFilePath(q,f),L=new I(B),C=[];try{await L.appendValidatedAsync(async(O)=>{let G=X.getSessionCreatedEntry(O,f);if(G.data.sessionId!==f)throw Error(`Session metadata creation record sessionId mismatch: ${f}`);if(!J.isAbsolute(G.cwd)||J.resolve(G.cwd)!==q)throw Error(`Session metadata creation record cwd mismatch: ${f}`);let _=X.projectMetadataFromEntries(O,f,q,B);if(_.archivedAt)throw new $0(f,f);if(_.parentId){let V=await X.findArchivedAncestor(_.parentId,q);if(V)throw new $0(f,V.sessionId)}let N=new Date().toISOString(),x={id:j(),sessionId:f,timestamp:N,type:"session_updated",cwd:q,gitBranch:l(q),version:p(),data:{sessionId:f,...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:N}};return C=[...O,x],x})}catch(O){throw X.sanitizeStoredSessionError(O,f)}return X.toPublicMetadata(X.projectMetadataFromEntries(C,f,q,B))}static async setSessionPermissionMode(f,$,T){if(A(f),!b0(T))throw Error("Invalid session permission mode");let q=X.resolveCatalogWorkspace($),B=await X.findSessionMetadata(f,q);if(B?.permissionMode===T)return B;if(B)return X.updateSessionMetadata(f,q,{permissionMode:T});try{return await X.createSessionMetadata(f,q,{taskStatus:"completed",permissionMode:T})}catch(L){if(L.code!=="EEXIST")throw L;return X.updateSessionMetadata(f,q,{permissionMode:T})}}static async findSessionTaskWorktree(f,$){A(f);let T=X.resolveCatalogWorkspace($),q=X.getSessionFilePath(T,f);try{return(await X.readStoredSessionMetadata(q,f,T)).taskWorktree}catch(B){if(B.code==="ENOENT")return;throw X.sanitizeStoredSessionError(B,f)}}static async findSessionTaskDispatch(f,$){A(f);let T=X.resolveCatalogWorkspace($),q=X.getSessionFilePath(T,f);try{return(await X.readStoredSessionMetadata(q,f,T)).taskDispatch}catch(B){if(B.code==="ENOENT")return;throw X.sanitizeStoredSessionError(B,f)}}static async loadSessionFromFile(f,$,T){let q=await a(f,"utf-8"),B=this.parseStoredSession(q,$);if(T!==void 0){if(this.projectMetadataFromEntries(B,$,T,f).projectPath!==T)throw Error(`未找到会话: ${$}`)}return this.convertJSONLToMessages(B)}static async loadSessionModelContextFromFile(f,$,T){let q=await a(f,"utf-8"),B=this.parseStoredSession(q,$);if(T!==void 0){if(this.projectMetadataFromEntries(B,$,T,f).projectPath!==T)throw Error(`未找到会话: ${$}`)}return this.convertJSONLToModelContext(B)}static convertJSONLToModelContext(f){let $=u(f),T=-1,q;for(let L=0;L<$.length;L++){let C=$[L];if(C?.type!=="part_created"||C.data.partType!=="summary")continue;let O=C.data.payload;if(T=L,q=Mf(O.replacementMessages),!q)q=[{role:"user",content:O.text??"",metadata:C.data.payload}]}if(T<0||!q)return this.convertJSONLToMessages($);let B=this.convertJSONLToMessages($.slice(T+1));return[...q,...B]}static convertJSONLToMessages(f){let $=[],T=new Map,q=new Map,B=new Map,L=new Map,C=new Map,O=u(f),G=new Set;for(let _ of O){if(_.type==="message_created"){let N=_.data.metadata&&typeof _.data.metadata==="object"&&!Array.isArray(_.data.metadata)?_.data.metadata:void 0,x=N?.codeReview&&typeof N.codeReview==="object"&&!Array.isArray(N.codeReview)?N.codeReview:void 0;if(x?.phase==="completed"&&typeof x.reviewId==="string")G.add(x.reviewId);let V=_.data.role==="assistant"&&_.data.parentMessageId?B.get(_.data.parentMessageId):void 0,Z=V??{role:_.data.role,content:"",..._.data.metadata||_.data.inboxMessageId?{metadata:{..._.data.metadata&&typeof _.data.metadata==="object"&&!Array.isArray(_.data.metadata)?_.data.metadata:{},..._.data.inboxMessageId?{inboxMessageId:_.data.inboxMessageId}:{}}}:{}};if(T.set(_.data.messageId,Z),q.set(_.data.messageId,[]),!V)$.push(Z)}if(_.type==="part_created"){if(_.data.partType==="reasoning"){let N=T.get(_.data.messageId);if(N){let x=_.data.payload;N.reasoningContent=(N.reasoningContent??"")+(x.text??"")}}if(_.data.partType==="text"){let N=T.get(_.data.messageId);if(N){let x=_.data.payload,V=q.get(_.data.messageId);if(V)V.push({type:"text",text:x.text??""}),N.content=Q$(V);else N.content=x.text??""}}if(_.data.partType==="image"){let N=T.get(_.data.messageId);if(N){let x=_.data.payload,V=q.get(_.data.messageId);if(V&&x.dataUrl)V.push({type:"image_url",image_url:{url:x.dataUrl}}),N.content=Q$(V)}}if(_.data.partType==="tool_call"){let N=T.get(_.data.messageId);if(N?.role!=="assistant"){if(N=B.get(_.data.messageId),!N)N={role:"assistant",content:"",tool_calls:[]},B.set(_.data.messageId,N),$.push(N)}if(N.role==="assistant"){let x=_.data.payload,V=x.toolCallId??_.data.partId;L.set(_.data.partId,V),C.set(V,N),N.tool_calls??=[],N.tool_calls.push({id:V,type:"function",function:{name:x.toolName??"unknown",arguments:JSON.stringify(x.input??{})}})}}if(_.data.partType==="tool_result"){let N=_.data.payload,x=uf(N),V=x.error?`Error: ${x.error.message}`:typeof x.llmContent==="string"?x.llmContent:JSON.stringify(x.llmContent),Z=N;$.push({role:"tool",content:V,tool_call_id:L.get(_.data.messageId)??N.toolCallId,name:N.toolName,metadata:Z})}if(_.data.partType==="summary"){let N=_.data.payload,x=_.data.payload;$.push({role:"system",content:N.text??"",metadata:x})}if(_.data.partType==="subtask_ref"){let N=T.get(_.data.messageId)??C.get(_.data.messageId);if(N){let x=_.data.payload,V=N.metadata??{};N.metadata={...V,subtaskRef:x}}}}}for(let _ of Y0(O)){if(_.completion===void 0||G.has(_.start.reviewId))continue;$.push({role:"assistant",content:wf(_.start,_.completion),metadata:{codeReview:{...yf(_.start,_.completion),synthetic:!0}}})}return $}static projectionDeriver(){return(f,$,T)=>{try{let q=m(T,$);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 M0();if(!B)return null;await Vf(B,this.projectionDeriver(),T);let L=f?B.prepare("SELECT metadata_json, is_subagent FROM sessions WHERE project_path=?").all(f):B.prepare("SELECT metadata_json, is_subagent FROM sessions").all(),C=[];for(let O of L){if(!$&&O.is_subagent===1)continue;try{let G=JSON.parse(O.metadata_json);if(f!==void 0&&G.projectPath!==f)continue;C.push(G)}catch{}}return Cf(await Promise.all(C.map((O)=>this.reconcileInterruptedTask(O))),q)}catch{return null}}static async scanStoredSessions(f,$=!1,T=0,q=!1){let B=f?J.resolve(f):void 0,L=await this.scanStoredSessionsFromProjection(B,$,T,q);if(L)return L;let C=B?[{storagePath:q0(B),projectPath:B}]:await this.listAllProjectStorageDirectories(),O=[];for(let G of C){let _;try{_=await Lf(G.storagePath)}catch(N){if(N.code==="ENOENT")continue;throw N}for(let N of _){if(!N.endsWith(".jsonl"))continue;let x=N.slice(0,-6),V=J.join(G.storagePath,N);try{let Z=await this.readStoredSessionMetadata(V,x,G.projectPath);if(B!==void 0&&Z.projectPath!==B){_0.warn(`[SessionService] Skipping out-of-scope session transcript: ${x}`);continue}if(!$&&Z.relationType==="subagent")continue;O.push(Z)}catch(Z){let E=Z.code;if(E==="ENOENT")continue;if(E)throw Z;_0.warn(`[SessionService] Skipping invalid session transcript: ${x}`)}}}return Cf(O,q)}static async listAllProjectStorageDirectories(){let f=J.join(O0(),"projects"),$;try{$=await Lf(f,{withFileTypes:!0,encoding:"utf8"})}catch(T){if(T.code==="ENOENT")return[];throw T}return $.filter((T)=>T.isDirectory()).map((T)=>({storagePath:J.join(f,T.name),projectPath:K$(T.name)}))}static async readStoredSessionMetadata(f,$,T){let q=await a(f,"utf-8"),B=this.parseStoredSession(q,$);return this.reconcileInterruptedTask(this.projectMetadataFromEntries(B,$,T,f))}static async reconcileInterruptedTask(f){let $=f.taskOwnerPid;if(f.taskStatus!=="running"||$===void 0||G$($))return f;let T;try{T=await h.acquire(f.sessionId,f.projectPath)}catch(L){if(!(L instanceof P))throw L;let C=await a(f.filePath,"utf-8");return this.projectMetadataFromEntries(this.parseStoredSession(C,f.sessionId),f.sessionId,f.projectPath,f.filePath)}let q=new I(f.filePath),B;try{try{await q.appendValidated((L)=>{let C=this.projectMetadataFromEntries(L,f.sessionId,f.projectPath,f.filePath);if(C.taskStatus!=="running"||C.taskOwnerPid!==$||G$($))throw new Zf;let O=new Date().toISOString(),G={id:j(),sessionId:f.sessionId,timestamp:O,type:"session_updated",cwd:f.projectPath,gitBranch:l(f.projectPath),version:p(),data:{sessionId:f.sessionId,taskStatus:"interrupted",taskStatusReason:"Task owner process exited before completion",taskCompletedAt:O,taskOwnerPid:null,taskQueuePosition:null,taskQueueDepth:null,updatedAt:O}};return B=[...L,G],G})}catch(L){if(!(L instanceof Zf))throw L}if(!B){let L=await a(f.filePath,"utf-8");B=this.parseStoredSession(L,f.sessionId)}return this.projectMetadataFromEntries(B,f.sessionId,f.projectPath,f.filePath)}finally{await T.release()}}static projectMetadataFromEntries(f,$,T,q){if(f.length===0)throw Error(`Empty session transcript: ${$}`);let B=this.getSessionCreatedEntry(f,$),L=f.reduce((U,v0)=>v0.type==="session_updated"?{...U,...v0.data}:U,{...B.data}),C=u(f),O=kf(bf(C)),_=Y0(C).at(-1),N=C.findLastIndex((U)=>U.type==="review_started"&&U.data.reviewId===_?.start.reviewId||U.type==="review_completed"&&U.data.reviewId===_?.start.reviewId),x=C.findLastIndex((U)=>(U.type==="session_created"||U.type==="session_updated")&&Object.hasOwn(U.data,"taskStatus")),V=_!==void 0&&N>x,Z=V?_.completion===void 0?"running":_.completion.status==="completed"||_.completion.status==="stale"?"completed":_.completion.status==="aborted"?"cancelled":_.completion.status==="interrupted"?"interrupted":"failed":void 0,E=C.filter((U)=>U.type==="message_created"&&["user","assistant"].includes(U.data.role)).length,g=C.some((U)=>U.type==="part_created"&&U.data.partType==="tool_result"&&typeof U.data.payload.error==="string"),b=N$.has(L.taskStatus)?L.taskStatus:void 0,W=Z??b??(g?"failed":"completed"),s=typeof L.taskOwnerPid==="number"&&Number.isInteger(L.taskOwnerPid)&&L.taskOwnerPid>0?L.taskOwnerPid:void 0,e=Jf.has(L.taskIsolation)?L.taskIsolation:void 0,y=typeof L.taskSourceProjectPath==="string"&&J.isAbsolute(L.taskSourceProjectPath)?J.resolve(L.taskSourceProjectPath):void 0,S=B.cwd;if(S!==void 0&&!J.isAbsolute(S))throw Error(`Session catalog cwd must be absolute: ${$}`);let D=S===void 0?T:J.resolve(S),R=x$(L.taskWorktree),z=R?.sessionId===$&&J.resolve(R.workspaceRoot)===D?R:void 0,Q=J$(L.taskDiffStat),M=Z$(L.taskDispatch),k0=typeof L.taskModelId==="string"&&L.taskModelId.trim()?L.taskModelId:M?.modelId,Ff=typeof L.selectedModelId==="string"&&L.selectedModelId.trim()?L.selectedModelId:k0,Qf=b0(L.permissionMode)?L.permissionMode:M?.permissionMode,Kf=J0(L.reasoningEffort)?L.reasoningEffort:M?.reasoningEffort,Xf=V0(L.serviceTier)?L.serviceTier:M?.serviceTier,Hf=x0(L.responseVerbosity)?L.responseVerbosity:M?.responseVerbosity,w0=Z0(L.communicationStyle)?L.communicationStyle:M?.communicationStyle,y0=Object.hasOwn(L,"communicationStyleDigest")?typeof L.communicationStyleDigest==="string"&&/^[a-f0-9]{64}$/.test(L.communicationStyleDigest)?L.communicationStyleDigest:void 0:w0===M?.communicationStyle?M?.communicationStyleDigest:void 0,S0=Object.hasOwn(L,"projectInstructionsDigest")?typeof L.projectInstructionsDigest==="string"&&/^[a-f0-9]{64}$/.test(L.projectInstructionsDigest)?L.projectInstructionsDigest:void 0:M?.projectInstructionsDigest,j0=g$(L.archivedAt)?L.archivedAt:void 0,m0=F$(L.taskRetriedFrom),T0=V$(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=V?_?.completion?_.completion.status==="completed"?void 0:`Code review ${h0(_.completion.status)}`:`Reviewing ${_?.start.target.label??"changes"}`:void 0,Q0=V?W==="failed"&&i?l0(i):void 0:p0(L.taskFailure)?L.taskFailure:W==="failed"&&typeof L.taskStatusReason==="string"?l0(L.taskStatusReason):void 0;return{sessionId:$,projectPath:D,gitBranch:B.gitBranch,rootId:L.rootId||$,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:Ff,permissionMode:Qf,reasoningEffort:Kf,serviceTier:Xf,responseVerbosity:Hf,communicationStyle:w0,communicationStyleDigest:y0,projectInstructionsDigest:S0,pendingInteraction:O,taskStatus:W,taskStatusReason:Q0?.message??i??(typeof L.taskStatusReason==="string"?L.taskStatusReason:void 0),taskFailure:Q0,taskStartedAt:V?_?.start.startedAt:typeof L.taskStartedAt==="string"?L.taskStartedAt:void 0,taskCompletedAt:V?_?.completion?.completedAt:typeof L.taskCompletedAt==="string"?L.taskCompletedAt:void 0,taskPromptSummary:V?_?MT(_.start.target):"/review uncommitted":typeof L.taskPromptSummary==="string"?L.taskPromptSummary:void 0,taskModelId:k0,taskRetryAvailable:M!==void 0,taskRetriedFrom:m0,taskDelivery:T0,taskIsolation:e,taskSourceProjectPath:y,taskWorktreePath:z?.worktreeRoot,taskWorktreeBranch:z?.branch,taskBaseCommit:z?.baseCommit,taskDiffStat:Q,taskQueuePosition:F0,taskQueueDepth:I0,taskConcurrencyLimit:Y,archivedAt:j0,taskOwnerPid:V?void 0:s,taskWorktree:z,taskDispatch:M,messageCount:E,firstMessageTime:f[0].timestamp,lastMessageTime:f.at(-1).timestamp,hasErrors:g||W==="failed",filePath:q}}static toPublicMetadata(f){let{filePath:$,taskOwnerPid:T,taskWorktree:q,taskDispatch:B,...L}=f;return L}static getSessionFilePath(f,$){return m(f,$)}static getSessionCreatedEntry(f,$){let T=f.find((q)=>q.type==="session_created");if(!T)throw new z$($);return T}static resolveCatalogWorkspace(f){if(!J.isAbsolute(f))throw Error("Session catalog cwd must be absolute");return J.resolve(f)}static validateSessionWorkspace(f,$,T){let q=this.getSessionCreatedEntry(f,$);if(q.data.sessionId!==$)throw Error(`Session creation record sessionId mismatch: ${$}`);if(!J.isAbsolute(q.cwd)||J.resolve(q.cwd)!==T)throw Error(`Session creation record cwd mismatch: ${$}`)}static resolveForkWorkspace(f){if(!J.isAbsolute(f))throw Error("Fork workspace paths must be absolute");return J.resolve(f)}static parseStoredSession(f,$){return U$(f,`session ${$}`)}static isCorruptSessionJSONLError(f){return f instanceof Error&&f.message.startsWith("Invalid session JSONL ")}static sanitizeStoredSessionError(f,$){if(!this.isCorruptSessionJSONLError(f)||!(f instanceof Error))return f;let T=f.message.match(/ at line (\d+)$/)?.[1];return Error(`Invalid session JSONL in session ${$}${T?` at line ${T}`:""}`,{cause:f.cause})}static async readStableSessionSnapshot(f,$,T=3){for(let q=0;q<T;q+=1){let B=await G0.stat(f),L=await G0.readFile(f),C=this.parseStoredSession(L,$),O=await G0.stat(f);if(B.size===O.size&&B.mtimeNs===O.mtimeNs&&B.dev===O.dev&&B.ino===O.ino)return C}throw Error("Session changed while creating fork; retry the operation")}}function Q$(f){if(f.length===1&&f[0]?.type==="text")return f[0].text;return[...f]}
|
|
111
|
-
export{i0 as Kb,Yf as Lb,K0 as Mb,Uf as Nb,tT as Ob,P as Pb,h as Qb,q1 as Rb,L1 as Sb,bf as Tb,O1 as Ub,Y0 as Vb,N1 as Wb,h0 as Xb,wf as Yb,yf as Zb,l0 as _b,c as $b,R0 as ac,D1 as bc,A1 as cc,z1 as dc,g1 as ec,uf as fc,M1 as gc,b1 as hc,nf as ic,w1 as jc,a0 as kc,s0 as lc,u1 as mc,n1 as nc,of as oc,A0 as pc,i1 as qc,O$ as rc,f$ as sc,t1 as tc,_$ as uc,a1 as vc,gT as wc,Aq as xc,zq as yc,z$ as zc,$0 as Ac,n as Bc,X as Cc};
|
package/dist/chunk-q8zp4je9.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{Ad as g,Bd as h,Cd as i,Dd as j,Ed as k,Fd as l,Gd as m,Hd as n,Id as o,Jd as p,Kd as q,ud as a,vd as b,wd as c,xd as d,yd as e,zd as f}from"./chunk-2m7at619.js";import"./chunk-v508x7cg.js";import"./chunk-wy4pn9sk.js";import"./chunk-7p0bzza4.js";import"./chunk-khkhsaan.js";import"./chunk-7b467h8k.js";import"./chunk-9kmtcgm6.js";import"./chunk-kjvntyr5.js";import"./chunk-8ekk8pa7.js";import"./chunk-y8r2knxm.js";import"./chunk-1jc7d3nt.js";import"./chunk-fp1h8wdh.js";import"./chunk-5g2p1fwn.js";import"./chunk-ej6h16ae.js";import"./chunk-cm9mph7j.js";import"./chunk-cz68x56m.js";import"./chunk-av10vmxk.js";export{a as vanillaStore,c as sessionActions,l as getThinkingModeEnabled,b as getState,n as getServiceTier,o as getResponseVerbosity,m as getReasoningEffort,j as getModelById,e as getMessages,k as getMcpServers,i as getCurrentModel,f as getConfig,p as getCommunicationStyle,h as getAllModels,g as ensureStoreInitialized,q as configActions,d as appActions};
|
package/dist/chunk-qs4erqd0.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import{ag as J,bg as $,cg as O,dg as K}from"./chunk-7b467h8k.js";import{eg as v,fg as S,gg as l}from"./chunk-9kmtcgm6.js";import{Lg as o}from"./chunk-y8r2knxm.js";import{nh as n}from"./chunk-cz68x56m.js";var G=[{min:0,max:59},{min:0,max:23},{min:1,max:31},{min:1,max:12},{min:0,max:7}],a={Sun:0,Mon:1,Tue:2,Wed:3,Thu:4,Fri:5,Sat:6},f=new Map;function D(Q,Z,W){let B=new Set;for(let X of Q.split(",")){let[Y,k]=X.split("/"),V=k?Number.parseInt(k,10):1;if(!Number.isInteger(V)||V<1)throw Error(`Invalid cron step in "${Q}"`);let j=Z,H=W;if(Y!=="*"&&Y!=="")if(Y.includes("-")){let[U,i]=Y.split("-");j=Number.parseInt(U,10),H=Number.parseInt(i,10)}else j=Number.parseInt(Y,10),H=j;if(!Number.isInteger(j)||!Number.isInteger(H)||j<Z||H>W||j>H)throw Error(`Invalid cron range "${Y}" in field "${Q}"`);for(let U=j;U<=H;U+=V)B.add(U)}return B}function C(Q){let Z=Q.trim().split(/\s+/);if(Z.length!==5)throw Error(`Cron expression must have 5 fields (min hour dom mon dow), got ${Z.length}`);let[W,B,X,Y,k]=Z,V=D(k,G[4].min,G[4].max),j=new Set([...V].map((H)=>H===7?0:H));return{minutes:D(W,G[0].min,G[0].max),hours:D(B,G[1].min,G[1].max),daysOfMonth:D(X,G[2].min,G[2].max),months:D(Y,G[3].min,G[3].max),daysOfWeek:j,domRestricted:X.trim()!=="*",dowRestricted:k.trim()!=="*"}}function t(Q,Z){if(!Z)return{minute:Q.getMinutes(),hour:Q.getHours(),dayOfMonth:Q.getDate(),month:Q.getMonth()+1,dayOfWeek:Q.getDay()};let W=f.get(Z);if(!W)W=new Intl.DateTimeFormat("en-US",{timeZone:Z,month:"numeric",day:"numeric",hour:"numeric",minute:"numeric",weekday:"short",hourCycle:"h23"}),f.set(Z,W);let B=Object.fromEntries(W.formatToParts(Q).filter((X)=>X.type!=="literal").map((X)=>[X.type,X.value]));return{minute:Number(B.minute),hour:Number(B.hour),dayOfMonth:Number(B.day),month:Number(B.month),dayOfWeek:a[B.weekday]??-1}}function r(Q,Z,W){let B=t(Z,W);if(!Q.minutes.has(B.minute))return!1;if(!Q.hours.has(B.hour))return!1;if(!Q.months.has(B.month))return!1;let X=Q.daysOfMonth.has(B.dayOfMonth),Y=Q.daysOfWeek.has(B.dayOfWeek);if(Q.domRestricted&&Q.dowRestricted)return X||Y;if(Q.domRestricted)return X;if(Q.dowRestricted)return Y;return!0}function T(Q,Z,W){let B=C(Q),X=new Date(Z.getTime());X.setSeconds(0,0),X.setMinutes(X.getMinutes()+1);let Y=new Date(Z.getTime());Y.setFullYear(Y.getFullYear()+4);while(X.getTime()<=Y.getTime()){if(r(B,X,W))return new Date(X.getTime());X.setMinutes(X.getMinutes()+1)}return null}var E={s:1000,m:60000,h:3600000,d:86400000};function DJ(Q){let W=Q.trim().toLowerCase().match(/^(\d+)\s*([smhd]?)$/);if(!W)return null;let B=Number.parseInt(W[1],10);if(!Number.isInteger(B)||B<=0)return null;let X=W[2]||"m";return B*E[X]}function y(Q){for(let Z of["d","h","m","s"]){let W=E[Z];if(Q%W===0)return`${Q/W}${Z}`}return`${Math.round(Q/1000)}s`}function A(Q,Z,W){switch(Q.kind){case"cron":{if(!Q.cron)return null;try{return T(Q.cron,Z,Q.timezone)}catch{return null}}case"interval":{if(!Q.intervalMs||Q.intervalMs<=0)return null;let X=new Date((W??Z).getTime()+Q.intervalMs);return X.getTime()<=Z.getTime()?new Date(Z.getTime()+1000):X}case"once":{if(!Q.runAt)return null;let B=new Date(Q.runAt);if(Number.isNaN(B.getTime()))return null;return B.getTime()>Z.getTime()?B:null}default:return null}}function _(Q){switch(Q.kind){case"cron":if(!Q.cron)return"cron trigger requires a cron expression";try{if(C(Q.cron),Q.timezone)new Intl.DateTimeFormat("en-US",{timeZone:Q.timezone}).format();return null}catch(Z){return Z instanceof Error?Z.message:"invalid cron expression"}case"interval":if(!Q.intervalMs||Q.intervalMs<60000)return"interval trigger requires intervalMs >= 60000 (1 minute)";return null;case"once":{if(!Q.runAt)return"once trigger requires runAt timestamp";let Z=new Date(Q.runAt);if(Number.isNaN(Z.getTime()))return"once trigger runAt is not a valid date";return null}default:return"unknown trigger kind"}}function FJ(Q){switch(Q.kind){case"cron":return`cron: ${Q.cron??"?"}`;case"interval":return`every ${Q.intervalMs?y(Q.intervalMs):"?"}`;case"once":return`once at ${Q.runAt??"?"}`;default:return"unknown"}}import{mkdir as bJ,readFile as wJ}from"node:fs/promises";import s from"node:path";import{nanoid as LJ}from"nanoid";import PJ from"write-file-atomic";var w=$(K(["default","autoEdit","yolo","plan"]));var N=$(K(["user","assistant","system","tool"])),p=$(J.Union([J.Object({type:J.Literal("text"),text:J.String()}),J.Object({type:J.Literal("image_url"),image_url:J.Object({url:J.String()})})])),h=J.Union([J.String(),J.Array(p)]),NJ=$(J.Object({id:J.String(),role:N,content:h,timestamp:J.Number(),metadata:J.Optional(J.Record(J.String(),J.Unknown())),thinkingContent:J.Optional(J.String()),tool_call_id:J.Optional(J.String()),name:J.Optional(J.String()),tool_calls:J.Optional(J.Unknown())})),e=$(K(["queued","running","completed","failed","cancelled","interrupted"])),F=$(K(["local","worktree"])),JJ=$(K(["applied","discarded","conflicted"])),QJ=$(J.Object({status:JJ,updatedAt:J.String(),sourceCommit:J.Optional(J.String()),changedFiles:J.Optional(J.Integer({minimum:0})),message:J.Optional(J.String())})),ZJ=$(J.Object({changedFiles:J.Integer({minimum:0}),additions:J.Integer({minimum:0}),deletions:J.Integer({minimum:0}),commits:J.Integer({minimum:0})})),$J=$(J.Object({path:J.String({minLength:1}),patch:J.String({maxLength:2097152}),additions:J.Integer({minimum:0}),deletions:J.Integer({minimum:0}),binary:J.Boolean(),truncated:J.Boolean()})),qJ=$(J.Object({sessionId:J.String(),projectPath:J.String(),baseCommit:J.String(),files:J.Array($J,{maxItems:100}),truncated:J.Boolean()})),BJ=J.Union([J.String(),J.Number(),J.Boolean(),J.Array(J.String())]),KJ=$(J.Object({name:J.String(),type:K(["string","number","integer","boolean","select","multi-select"]),title:J.String(),description:J.Optional(J.String()),required:J.Boolean(),defaultValue:J.Optional(BJ),options:J.Optional(J.Array(J.Object({value:J.String(),label:J.String()}))),format:J.Optional(K(["date","uri","email","date-time"])),minimum:J.Optional(J.Number()),maximum:J.Optional(J.Number()),minLength:J.Optional(J.Number()),maxLength:J.Optional(J.Number()),minItems:J.Optional(J.Number()),maxItems:J.Optional(J.Number())})),xJ=$(J.Object({serverName:J.String(),mode:K(["form","url"]),message:J.String(),fields:J.Optional(J.Array(KJ)),requestedSchema:J.Optional(J.Record(J.String(),J.Unknown())),url:J.Optional(J.String()),domain:J.Optional(J.String()),elicitationId:J.Optional(J.String())})),WJ=$(J.Object({type:K(["permission","question","elicitation"]),requestId:J.String()})),XJ=$(J.Object({code:K(["authentication","permission","rate_limit","timeout","network","model_unavailable","context_limit","unsupported_input","capacity","runtime"]),message:J.String({minLength:1,maxLength:500}),retryable:J.Boolean(),resource:J.Optional(K(["pending_count","pending_bytes","resident_runtimes"]))})),L=$(K(["auto","off","minimal","low","medium","high","xhigh","max"])),P=$(K(["auto","standard","fast","flex"])),M=$(K(["auto","low","medium","high"])),b=$(J.Union([K(["auto","pragmatic","friendly","explanatory"]),J.String({minLength:7,maxLength:300,pattern:"^(?:(?:user|project):[a-z0-9][a-z0-9._-]{0,63}(?::[a-z0-9][a-z0-9._-]{0,63}){0,3}|plugin:[a-z0-9][a-z0-9._-]{0,63}:[a-z0-9][a-z0-9._-]{0,63}(?::[a-z0-9][a-z0-9._-]{0,63}){0,3})$"})])),z=$(J.Object({sessionId:J.String(),projectPath:J.String(),title:J.Optional(J.String()),gitBranch:J.Optional(J.String()),rootId:J.String(),parentId:J.Optional(J.String()),relationType:J.Optional(K(["subagent","fork"])),resumedFrom:J.Optional(J.String()),rootAgentId:J.Optional(J.String()),resumeDepth:J.Optional(J.Integer({minimum:0})),taskStatus:O(e,"completed"),taskStatusReason:J.Optional(J.String()),taskFailure:J.Optional(XJ),taskStartedAt:J.Optional(J.String()),taskCompletedAt:J.Optional(J.String()),taskPromptSummary:J.Optional(J.String()),taskModelId:J.Optional(J.String()),selectedModelId:J.Optional(J.String()),permissionMode:J.Optional(w),reasoningEffort:J.Optional(L),serviceTier:J.Optional(P),responseVerbosity:J.Optional(M),communicationStyle:J.Optional(b),communicationStyleDigest:J.Optional(J.String({pattern:"^[a-f0-9]{64}$"})),projectInstructionsDigest:J.Optional(J.String({pattern:"^[a-f0-9]{64}$"})),taskRetryAvailable:J.Optional(J.Boolean()),taskRetriedFrom:J.Optional(J.Object({sessionId:J.String(),projectPath:J.String()})),taskDelivery:J.Optional(QJ),taskIsolation:J.Optional(F),taskSourceProjectPath:J.Optional(J.String()),taskWorktreePath:J.Optional(J.String()),taskWorktreeBranch:J.Optional(J.String()),taskBaseCommit:J.Optional(J.String()),taskDiffStat:J.Optional(ZJ),taskQueuePosition:J.Optional(J.Integer({minimum:1})),taskQueueDepth:J.Optional(J.Integer({minimum:0})),taskConcurrencyLimit:J.Optional(J.Integer({minimum:1})),archivedAt:J.Optional(J.String()),archivedBySessionId:J.Optional(J.String()),pendingInteraction:J.Optional(WJ),messageCount:J.Number(),firstMessageTime:J.String(),lastMessageTime:J.String(),hasErrors:J.Boolean()})),fJ=$(J.Object({sessions:J.Array(z),nextCursor:J.Optional(J.String())})),CJ=$(J.Object({session:z,archivedSessionIds:J.Array(J.String())})),EJ=$(J.Object({session:z,restoredSessionIds:J.Array(J.String())})),RJ=$(J.Object({version:J.Literal(1),sessionId:J.String(),goalId:J.String(),objective:J.String(),status:K(["active","verifying","paused","blocked","usage_limited","budget_limited","complete"]),tokenBudget:J.Optional(J.Number()),tokensUsed:J.Number(),timeUsedSeconds:J.Number(),continuationCount:J.Number(),statusReason:J.Optional(J.String()),completionVerification:J.Optional(J.Object({attempt:J.Integer({minimum:1}),status:K(["pending","pass","fail","partial"]),requestedAt:J.String(),completedAt:J.Optional(J.String()),verifierSessionId:J.Optional(J.String()),summary:J.Optional(J.String()),evidenceSha256:J.Optional(J.String({pattern:"^[a-f0-9]{64}$"}))})),createdAt:J.String(),updatedAt:J.String()})),u=$(J.Object({role:N,content:h,metadata:J.Optional(J.Unknown()),reasoningContent:J.Optional(J.String()),thinkingContent:J.Optional(J.String()),tool_call_id:J.Optional(J.String()),name:J.Optional(J.String()),tool_calls:J.Optional(J.Unknown())})),SJ=$(J.Object({session:z,messages:J.Array(u)})),d=$(K(["conversation","code","both"])),YJ=$(J.Object({messageId:J.String(),preview:J.String(),createdAt:J.String(),fileCount:J.Integer({minimum:0})})),lJ=$(J.Object({targetMessageId:J.String({minLength:1}),mode:O(d,"conversation")})),hJ=$(J.Object({checkpoint:YJ,mode:d,removedTurns:J.Integer({minimum:1}),restoredFiles:J.Array(J.String()),messages:J.Array(u)})),HJ=K(["running","completed","failed","cancelled"]),R=$(J.Object({id:J.String(),subagentType:J.String(),description:J.String(),status:HJ,background:J.Boolean(),rootAgentId:J.String(),resumedFrom:J.Optional(J.String()),resumeDepth:J.Integer({minimum:0}),createdAt:J.Number(),lastActiveAt:J.Number(),completedAt:J.Optional(J.Number()),restartRecovery:J.Optional(J.Object({outcome:K(["completed","interrupted","failed"]),recoveredAt:J.Number()})),result:J.Optional(J.Object({success:J.Boolean(),message:J.String(),error:J.Optional(J.String()),verificationCommands:J.Optional(J.Array(J.String())),verificationVerdict:J.Optional(K(["pass","fail","partial"])),modifiedFiles:J.Optional(J.Array(J.String()))})),stats:J.Optional(J.Object({tokens:J.Optional(J.Number()),toolCalls:J.Optional(J.Number()),duration:J.Optional(J.Number())}))})),uJ=$(J.Object({prompt:J.String({minLength:1,maxLength:32000,pattern:"\\S"})})),dJ=$(J.Object({source:R,session:R})),mJ=$(J.Object({sessionId:J.String(),projectPath:J.String()})),cJ=$(J.Object({path:J.String(),name:J.String(),gitBranch:J.Optional(J.String()),available:J.Boolean(),isCurrent:J.Boolean(),boundAt:J.String()})),gJ=$(J.Union([J.Object({cancelled:J.Literal(!0)}),J.Object({cancelled:J.Literal(!1),path:J.String({minLength:1})})])),nJ=$(J.Object({type:J.String(),seq:J.Optional(J.Number()),properties:J.Record(J.String(),J.Unknown())})),m=J.Object({type:K(["file","image","url"]),path:J.Optional(J.String()),url:J.Optional(J.String()),content:J.Optional(J.String({maxLength:S})),mimeType:J.Optional(J.String()),name:J.Optional(J.String())}),c=J.Record(J.String(),J.Unknown()),oJ=$(J.Object({prompt:J.String({minLength:1,maxLength:32000,pattern:"\\S"}),title:J.Optional(J.String({minLength:1,maxLength:200})),projectPath:J.Optional(J.String()),modelId:J.Optional(J.String({minLength:1,maxLength:500})),reasoningEffort:J.Optional(L),serviceTier:J.Optional(P),responseVerbosity:J.Optional(M),communicationStyle:J.Optional(b),isolation:O(F,"worktree"),permissionMode:O(w,"default"),attachments:J.Optional(J.Array(m,{maxItems:v})),outputSchema:J.Optional(c)})),sJ=$(J.Object({session:z,runId:J.String(),messageId:J.String(),status:K(["queued","running"]),queuePosition:J.Optional(J.Integer({minimum:1})),queueDepth:J.Optional(J.Integer({minimum:0})),maxConcurrentTasks:J.Optional(J.Integer({minimum:1}))})),iJ=$(J.Object({action:K(["apply","discard"])})),q=$(J.Object({kind:K(["cron","interval","once"]),cron:J.Optional(J.String({minLength:1,maxLength:120})),intervalMs:J.Optional(J.Integer({minimum:60000})),runAt:J.Optional(J.String({minLength:1,maxLength:40})),timezone:J.Optional(J.String({minLength:1,maxLength:80}))})),jJ=$(J.Object({modelId:J.Optional(J.String({minLength:1,maxLength:500})),reasoningEffort:J.Optional(L),serviceTier:J.Optional(P),responseVerbosity:J.Optional(M),communicationStyle:J.Optional(b),isolation:O(F,"worktree"),permissionMode:O(w,"default")})),x=$(J.Object({id:J.String(),title:J.Optional(J.String({minLength:1,maxLength:200})),prompt:J.String({minLength:1,maxLength:32000,pattern:"\\S"}),projectPath:J.String({minLength:1}),trigger:q,dispatch:jJ,enabled:J.Boolean(),createdAt:J.String(),updatedAt:J.String(),nextRunAt:J.Union([J.String(),J.Null()]),expiresAt:J.Union([J.String(),J.Null()]),lastRunAt:J.Optional(J.String()),lastRunSessionId:J.Optional(J.String()),lastStatus:J.Optional(K(["queued","running","completed","failed","cancelled","interrupted","error"])),lastError:J.Optional(J.String()),runCount:J.Integer({minimum:0})})),aJ=$(J.Object({title:J.Optional(J.String({minLength:1,maxLength:200})),prompt:J.String({minLength:1,maxLength:32000,pattern:"\\S"}),projectPath:J.String({minLength:1}),trigger:q,modelId:J.Optional(J.String({minLength:1,maxLength:500})),reasoningEffort:J.Optional(L),serviceTier:J.Optional(P),responseVerbosity:J.Optional(M),communicationStyle:J.Optional(b),isolation:O(F,"worktree"),permissionMode:O(w,"default"),enabled:O(J.Boolean(),!0)})),tJ=$(J.Object({title:J.Optional(J.String({minLength:1,maxLength:200})),prompt:J.Optional(J.String({minLength:1,maxLength:32000,pattern:"\\S"})),trigger:J.Optional(q),modelId:J.Optional(J.String({minLength:1,maxLength:500})),reasoningEffort:J.Optional(L),serviceTier:J.Optional(P),responseVerbosity:J.Optional(M),communicationStyle:J.Optional(b),isolation:J.Optional(F),permissionMode:J.Optional(w),enabled:J.Optional(J.Boolean())})),rJ=$(J.Object({schedules:J.Array(x)})),TJ=$(J.Object({content:J.String({maxLength:l}),projectPath:J.Optional(J.String()),modelId:J.Optional(J.String({minLength:1,maxLength:500})),reasoningEffort:J.Optional(L),serviceTier:J.Optional(P),responseVerbosity:J.Optional(M),communicationStyle:J.Optional(b),permissionMode:J.Optional(w),attachments:J.Optional(J.Array(m,{maxItems:v})),outputSchema:J.Optional(c)})),UJ=K(["completed","failed","aborted","timed_out","spawn_error"]),kJ=$(J.Object({version:J.Literal(1),command:J.String(),status:UJ,exitCode:J.Union([J.Integer(),J.Null()]),durationMs:J.Number({minimum:0}),stdout:J.String(),stderr:J.String(),stdoutOmittedBytes:J.Integer({minimum:0}),stderrOmittedBytes:J.Integer({minimum:0}),binaryOutput:J.Boolean(),truncated:J.Boolean()})),yJ=$(J.Object({command:J.String({minLength:1,maxLength:32768,pattern:"^(?![\\s\\S]*\\u0000)(?=[\\s\\S]*\\S)[\\s\\S]*$"}),projectPath:J.Optional(J.String())})),pJ=$(J.Object({executionId:J.String(),messageId:J.String(),record:kJ,auxiliary:J.Boolean(),delivery:J.Optional(K(["current_turn","next_turn"])),queued:J.Optional(J.Integer({minimum:0}))})),eJ=$(J.Object({projectPath:J.String(),kind:K(["uncommitted","base","commit"]),ref:J.Optional(J.String({maxLength:200})),instructions:J.Optional(J.String({maxLength:4000})),modelId:J.Optional(J.String({minLength:1,maxLength:200}))})),JQ=$(J.Object({reviewId:J.String(),status:J.Literal("running")})),QQ=$(J.Object({messageId:J.String(),role:N,content:J.String(),timestamp:J.String()})),ZQ=$(J.Object({approved:J.Boolean(),remember:J.Optional(J.Boolean()),scope:J.Optional(K(["once","session","project"])),targetMode:J.Optional(w),feedback:J.Optional(J.String()),answers:J.Optional(J.Record(J.String(),J.Union([J.String(),J.Array(J.String())]))),elicitation:J.Optional(J.Object({action:K(["accept","decline","cancel"]),content:J.Optional(J.Record(J.String(),J.Union([J.String({maxLength:4000}),J.Number(),J.Boolean(),J.Array(J.String({maxLength:1000}),{maxItems:100})]),{maxProperties:32}))}))})),VJ=$(J.Object({id:b,name:J.String({minLength:1,maxLength:80}),description:J.String({minLength:1,maxLength:256}),source:K(["built-in","user","project","plugin"]),contentSha256:J.Optional(J.String({pattern:"^[a-f0-9]{64}$"}))})),$Q=$(J.Object({id:J.String(),displayName:J.Optional(J.String()),provider:J.String(),model:J.String(),contextWindow:J.Optional(J.Number()),maxTokens:J.Optional(J.Number()),reasoning:J.Optional(J.Boolean()),supportedReasoningEfforts:J.Optional(J.Array(K(["off","minimal","low","medium","high","xhigh","max"]))),supportedServiceTiers:J.Optional(J.Array(K(["standard","fast","flex"]))),supportedResponseVerbosities:J.Optional(J.Array(K(["low","medium","high"]))),communicationStyles:J.Optional(J.Array(VJ,{maxItems:36})),input:J.Optional(J.Array(K(["text","image"]))),overrides:J.Optional(J.Object({baseUrl:J.Optional(J.String()),temperature:J.Optional(J.Number()),maxOutputTokens:J.Optional(J.Number()),timeout:J.Optional(J.Number()),streamIdleTimeout:J.Optional(J.Number({minimum:1000}))}))})),BQ=$(K(["vs-dark","vs-light","hc-black"])),GJ=$(K(["light","dark","system"])),OJ=$(J.Object({language:J.String(),codeTheme:J.String(),uiTheme:GJ,autoSaveSessions:J.Boolean(),notifyBuild:J.Boolean(),notifyErrors:J.Boolean(),notifySounds:J.Boolean(),privacyTelemetry:J.Boolean(),privacyCrash:J.Boolean(),communicationStyle:J.Optional(b)})),KQ=$(J.Partial(OJ));var g=o("Service"),MJ=1;function IJ(){return s.join(n(),"schedules.json")}class I{filePath;static instance;static getInstance(){if(!I.instance)I.instance=new I;return I.instance}writeChain=Promise.resolve();constructor(Q=IJ()){this.filePath=Q}async readFile(){try{let Q=await wJ(this.filePath,"utf-8"),Z=JSON.parse(Q);if(!Z||!Array.isArray(Z.schedules))return[];let W=[],B=0;for(let X of Z.schedules){let Y=x.safeParse(X);if(Y.success)W.push(Y.data);else B+=1}if(B>0)g.warn(`[ScheduleStore] Ignored ${B} invalid persisted schedule(s)`);return W}catch(Q){let Z=Q;if(Z.code!=="ENOENT")g.warn("[ScheduleStore] Failed to read schedules; treating as empty:",Z);return[]}}async writeFile(Q){await bJ(s.dirname(this.filePath),{recursive:!0,mode:493});let Z={version:MJ,schedules:Q};await PJ(this.filePath,JSON.stringify(Z,null,2),{mode:384})}serializeWrite(Q){let Z=this.writeChain.then(Q,Q);return this.writeChain=Z.then(()=>{return},()=>{return}),Z}async list(){return this.readFile()}async get(Q){return(await this.readFile()).find((W)=>W.id===Q)}async create(Q){return this.serializeWrite(async()=>{let Z=Q.trigger.kind==="cron"&&!Q.trigger.timezone?{...Q.trigger,timezone:Intl.DateTimeFormat().resolvedOptions().timeZone}:Q.trigger,W=_(Z);if(W)throw Error(W);let B=new Date;if(Z.kind==="once"&&new Date(Z.runAt).getTime()<=B.getTime())throw Error("once trigger runAt must be in the future");let X=B.toISOString(),Y=A(Z,B),k={id:LJ(10),title:Q.title,prompt:Q.prompt,projectPath:Q.projectPath,trigger:Z,dispatch:{modelId:Q.modelId,reasoningEffort:Q.reasoningEffort,serviceTier:Q.serviceTier,responseVerbosity:Q.responseVerbosity,communicationStyle:Q.communicationStyle,isolation:Q.isolation??"worktree",permissionMode:Q.permissionMode??"default"},enabled:Q.enabled??!0,createdAt:X,updatedAt:X,nextRunAt:Y?Y.toISOString():null,expiresAt:null,runCount:0},V=await this.readFile();return V.push(k),await this.writeFile(V),k})}async update(Q,Z){return this.serializeWrite(async()=>{let W=await this.readFile(),B=W.findIndex((H)=>H.id===Q);if(B===-1)return;let X=W[B];if(Z.trigger){let H=Z.trigger.kind==="cron"&&!Z.trigger.timezone?{...Z.trigger,timezone:Intl.DateTimeFormat().resolvedOptions().timeZone}:Z.trigger,U=_(H);if(U)throw Error(U);if(H.kind==="once"&&new Date(H.runAt).getTime()<=Date.now())throw Error("once trigger runAt must be in the future");Z={...Z,trigger:H}}let Y={...X,...Z,dispatch:Z.dispatch?{...X.dispatch,...Z.dispatch}:X.dispatch,updatedAt:new Date().toISOString()},k=!X.enabled,V=Y.enabled,j=Z.trigger!==void 0;if((j||k&&V)&&Z.nextRunAt===void 0){let H=new Date,U=A(Y.trigger,H);if(Y.nextRunAt=U?U.toISOString():null,j)Y.expiresAt=null}return W[B]=Y,await this.writeFile(W),Y})}async remove(Q){return this.serializeWrite(async()=>{let Z=await this.readFile(),W=Z.filter((B)=>B.id!==Q);if(W.length===Z.length)return!1;return await this.writeFile(W),!0})}async setEnabled(Q,Z){return this.update(Q,{enabled:Z})}}var LQ=I.getInstance();
|
|
2
|
-
export{DJ as xa,A as ya,_ as za,FJ as Aa,qJ as Ba,z as Ca,lJ as Da,uJ as Ea,oJ as Fa,sJ as Ga,iJ as Ha,x as Ia,aJ as Ja,tJ as Ka,rJ as La,TJ as Ma,yJ as Na,eJ as Oa,I as Pa,LQ as Qa};
|
package/dist/chunk-vjyysxhx.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{Ac as e,Bc as f,Cc as g,wc as a,xc as b,yc as c,zc as d}from"./chunk-jy1e6ve5.js";import"./chunk-2z3xe3rw.js";import"./chunk-wwsg165p.js";import"./chunk-69rc9hw6.js";import"./chunk-detkh4dd.js";import"./chunk-87jz5600.js";import"./chunk-9kmtcgm6.js";import"./chunk-kjvntyr5.js";import"./chunk-y8r2knxm.js";import"./chunk-fp1h8wdh.js";import"./chunk-5g2p1fwn.js";import"./chunk-cz68x56m.js";import"./chunk-av10vmxk.js";export{b as __setSessionSnapshotIOForTesting,c as __resetSessionSnapshotIOForTesting,g as SessionService,d as SessionMissingCreationError,e as SessionArchivedError,f as SessionArchiveConflictError,a as STALE_EMPTY_SESSION_AGE_MS};
|
package/dist/chunk-wwsg165p.js
DELETED
|
@@ -1,116 +0,0 @@
|
|
|
1
|
-
import{Lg as i}from"./chunk-y8r2knxm.js";import{fh as o,hh as C,jh as L,nh as j,oh as n}from"./chunk-cz68x56m.js";import{ph as I}from"./chunk-av10vmxk.js";import{stat as d}from"node:fs/promises";import B from"node:path";import*as U from"node:path";var s=50,t=100,e=/^[A-Za-z0-9_-]+$/,__=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?(?:Z|[+-]\d{2}:\d{2})$/;function E_(_){return typeof _==="string"&&__.test(_)&&Number.isFinite(Date.parse(_))}function P(_){return typeof _==="string"&&U.isAbsolute(_)}function R_(_){return Buffer.from(JSON.stringify(_),"utf8").toString("base64url")}function W_(_){try{if(!e.test(_))throw Error("invalid");let E=Buffer.from(_,"base64url").toString("utf8");if(Buffer.from(E,"utf8").toString("base64url")!==_)throw Error("invalid");let R=JSON.parse(E);if(R.version!==1||typeof R.includeSubagents!=="boolean"||R.archived!==void 0&&typeof R.archived!=="boolean"||!(R.cwd===null||P(R.cwd))||!E_(R.lastMessageTime)||!P(R.projectPath)||!C(R.sessionId))throw Error("invalid");return{version:1,cwd:R.cwd===null?null:U.resolve(R.cwd),includeSubagents:R.includeSubagents,archived:R.archived??!1,lastMessageTime:R.lastMessageTime,projectPath:U.resolve(R.projectPath),sessionId:R.sessionId}}catch{throw Error("Invalid session cursor")}}function y(_){let E="";for(let R=0;R<_.length;R+=1)E+=_.charCodeAt(R).toString(16).padStart(4,"0");return E}function $_(_){if(!_.cursor)return;let E=W_(_.cursor);if(E.cwd!==_.cwd||E.includeSubagents!==_.includeSubagents||(E.archived??!1)!==_.archived)throw Error("Session cursor scope does not match this query");return E}function z_(_={}){let{cwd:E,cursor:R,limit:W,includeSubagents:$=!1,archived:H=!1}=_;if(E!==void 0&&!U.isAbsolute(E))throw Error("Session catalog cwd must be absolute");let k=W===void 0?s:W;if(!Number.isInteger(k)||k<1||k>t)throw Error("Session catalog limit must be an integer from 1 to 100");return{cwd:E===void 0?null:U.resolve(E),cursor:R??void 0,limit:k,includeSubagents:$,archived:H}}function k_(_,E){if(_.lastMessageTime>E.lastMessageTime)return-1;if(_.lastMessageTime<E.lastMessageTime)return 1;if(_.projectPath<E.projectPath)return-1;if(_.projectPath>E.projectPath)return 1;if(_.sessionId<E.sessionId)return-1;if(_.sessionId>E.sessionId)return 1;return 0}function f_(_,E){let R=[..._],W=$_(E);if(W)R=R.filter((k)=>k_(k,{sessionId:W.sessionId,projectPath:W.projectPath,lastMessageTime:W.lastMessageTime})>0);let $=R.slice(0,E.limit);if($.length===0||R.length<=$.length)return{sessions:$};let H=$[$.length-1];return{sessions:$,nextCursor:R_({version:1,cwd:E.cwd,includeSubagents:E.includeSubagents,archived:E.archived,lastMessageTime:H.lastMessageTime,projectPath:H.projectPath,sessionId:H.sessionId})}}function H_(_){return _.type==="message_created"||_.type==="part_created"||_.type==="part_updated"||_.type==="turn_started"||_.type==="turn_completed"||_.type==="turn_aborted"||_.type==="interaction_requested"||_.type==="interaction_responded"||_.type==="interaction_recovered"||_.type==="review_started"||_.type==="review_completed"}function J(_){return _.type==="message_created"&&_.data.role==="user"&&(_.data.inboxMessageId!==void 0||_.data.parentMessageId===void 0)}function u(_,E){let R=_.find((W)=>J(W)&&W.data.messageId===E);if(!R)throw Error(`Rewind checkpoint not found: ${E}`);return{messageId:E,preview:c(_,E),createdAt:R.data.createdAt}}function c(_,E){let R=_.flatMap((W)=>{if(W.type!=="part_created"||W.data.messageId!==E)return[];if(W.data.partType==="text"){let $=W.data.payload;return typeof $.text==="string"?[$.text]:[]}if(W.data.partType==="image")return["[Image]"];return[]}).join("").trim();if(R.length<=160)return R;return`${R.slice(0,160)}...`}function S(_,E){u(_,E);let R=_.findIndex((k)=>k.type==="message_created"&&k.data.messageId===E),W=_[R],$=W?.type==="message_created"?W.data.inboxMessageId:void 0,H=new Set(_.flatMap((k)=>k.type==="turn_started"&&$&&k.data.inputMessageIds?.includes($)?[k.data.turnId]:[]));return _.filter((k,M)=>{if((k.type==="turn_started"||k.type==="turn_completed"||k.type==="turn_aborted")&&H.has(k.data.turnId))return!1;return M<R||!H_(k)})}function w(_){let E=[];for(let R of _){if(R.type!=="session_rewound"){E.push(R);continue}if(u(E,R.data.targetMessageId),R.data.mode!=="code")E=S(E,R.data.targetMessageId)}return E}function q_(_){let E=w(_);return E.filter(J).map((R)=>({messageId:R.data.messageId,preview:c(E,R.data.messageId),createdAt:R.data.createdAt})).reverse()}function y_(_,E){let R=w(_),W=u(R,E),$=R.findIndex((k)=>k.type==="message_created"&&k.data.messageId===E),H=R.slice($);return{checkpoint:W,projectedEntries:S(R,E),removedTurns:H.filter(J).length,snapshotMessageIds:H.flatMap((k)=>k.type==="part_created"&&k.data.partType==="tool_call"?[k.data.partId]:[])}}import*as f from"node:fs";import{createReadStream as M_}from"node:fs";import*as V from"node:fs/promises";import*as O from"node:path";import{createInterface as Q_}from"node:readline";var m=65536;function x(_){let E=_.data;if(E===null||typeof E!=="object"||Array.isArray(E))throw Error("Session event data must be a JSON object");return JSON.stringify(_)}function V_(_,E,R){let W=_.trim();if(!W)return;try{return JSON.parse(W)}catch($){throw Error(`Invalid session JSONL in ${R} at line ${E}`,{cause:$})}}function z(_,E="session transcript"){let R=_.split(`
|
|
2
|
-
`),W=!_.endsWith(`
|
|
3
|
-
`),$=[];for(let[H,k]of R.entries())try{let M=V_(k,H+1,E);if(M){if(typeof M.seq!=="number")M.seq=$.length+1;$.push(M)}}catch(M){if(W&&H===R.length-1)break;throw M}return $}class Y{static appendQueues=new Map;filePath;constructor(_){this.filePath=_}static maxSeq(_){let E=0;for(let R of _)if(typeof R.seq==="number"&&R.seq>E)E=R.seq;return E}static stampSeqFrom(_,E){let R=E;return _.map((W)=>{if(typeof W.seq==="number"){if(W.seq>R)R=W.seq;return W}return R+=1,{...W,seq:R}})}static stampSeq(_,E){return Y.stampSeqFrom(_,Y.maxSeq(E))}async append(_){try{let[E]=await this.appendEntries([_]);return E}catch(E){throw console.error(`[JSONLStore] 追加写入失败: ${this.filePath}`,E),E}}async appendBatch(_){try{return await this.appendEntries(_)}catch(E){throw console.error(`[JSONLStore] 批量追加写入失败: ${this.filePath}`,E),E}}async appendEntries(_){if(_.length===0)return[];return this.enqueue(async()=>{await V.mkdir(O.dirname(this.filePath),{recursive:!0,mode:493});let E=await V.open(this.filePath,"a+",384);try{let R=await this.repairIncompleteTail(E),W=await this.readTailSeq(E),$=Y.stampSeqFrom(_,W),H=`${$.map(x).join(`
|
|
4
|
-
`)}
|
|
5
|
-
`;return await E.appendFile(R+H,"utf8"),await E.sync(),$}finally{await E.close()}})}async createExclusive(_){if(_.length===0)throw Error("Cannot create an empty session transcript");await V.mkdir(O.dirname(this.filePath),{recursive:!0,mode:493});let E;try{E=await V.open(this.filePath,"wx",384);let W=`${Y.stampSeq(_,[]).map(x).join(`
|
|
6
|
-
`)}
|
|
7
|
-
`;await E.writeFile(W,"utf-8"),await E.sync()}catch(R){if(E)await E.close(),E=void 0,await V.unlink(this.filePath).catch(()=>{return});throw R}finally{await E?.close()}}async readAll(){if(!f.existsSync(this.filePath))return[];let _=await V.readFile(this.filePath,"utf-8");return z(_,this.filePath)}async readStream(_){return new Promise((E,R)=>{if(!f.existsSync(this.filePath)){E();return}let W=M_(this.filePath,"utf-8"),$=Q_({input:W,crlfDelay:Number.POSITIVE_INFINITY}),H=0;$.on("line",async(k)=>{let M=k.trim();if(M.length===0)return;try{let X=JSON.parse(M);if(H+=1,typeof X.seq!=="number")X.seq=H;await _(X)}catch(X){console.warn(`[JSONLStore] 解析 JSON 行失败: ${M}`,X)}}),$.on("close",()=>E()),$.on("error",R),W.on("error",R)})}async filter(_){let E=[];return await this.readStream((R)=>{if(_(R))E.push(R)}),E}async readLast(_){return(await this.readAll()).slice(-_)}async readFromSeq(_){return(await this.readAll()).filter((R)=>(R.seq??0)>=_)}async getStats(){try{if(!f.existsSync(this.filePath))return{exists:!1,size:0,lineCount:0};let _=await V.stat(this.filePath),R=(await V.readFile(this.filePath,"utf-8")).split(`
|
|
8
|
-
`).filter((W)=>W.trim().length>0).length;return{exists:!0,size:_.size,lineCount:R}}catch(_){return console.error(`[JSONLStore] 获取统计信息失败: ${this.filePath}`,_),{exists:!1,size:0,lineCount:0}}}async exists(){try{return await V.access(this.filePath),!0}catch{return!1}}async delete(){try{return await this.enqueue(async()=>{try{return await V.unlink(this.filePath),!0}catch(_){if(_.code==="ENOENT")return!1;throw _}})}catch(_){throw console.error(`[JSONLStore] 删除文件失败: ${this.filePath}`,_),_}}async deleteValidated(_){return this.enqueue(async()=>{let E;try{E=await V.open(this.filePath,"r")}catch(W){if(W.code==="ENOENT")return!1;throw W}let R;try{R=z(await E.readFile("utf8"),"session transcript")}finally{await E.close()}if(!_(R))return!1;try{return await V.unlink(this.filePath),!0}catch(W){if(W.code==="ENOENT")return!1;throw W}})}async appendValidated(_){return this.appendValidatedAsync(async(E)=>_(E))}async appendValidatedBatch(_){return this.appendValidatedBatchAsync(async(E)=>_(E))}async appendValidatedBatchAsync(_){return this.enqueue(async()=>{let E=await V.open(this.filePath,"r+");try{let{entries:R,separator:W,size:$}=await this.readCommittedState(E,"session transcript"),H=await _(R);if(H.length===0)return[];let k=Y.stampSeq(H,R),M=`${k.map(x).join(`
|
|
9
|
-
`)}
|
|
10
|
-
`;return await E.write(W+M,$,"utf8"),await E.sync(),k}finally{await E.close()}})}async appendValidatedAsync(_){return this.enqueue(async()=>{let E=await V.open(this.filePath,"r+");try{let{entries:R,separator:W,size:$}=await this.readCommittedState(E,"session transcript"),H=await _(R),[k]=Y.stampSeq([H],R),M=`${W}${x(k)}
|
|
11
|
-
`;return await E.write(M,$,"utf8"),await E.sync(),k}finally{await E.close()}})}getFilePath(){return this.filePath}async enqueue(_){let R=(Y.appendQueues.get(this.filePath)??Promise.resolve()).catch(()=>{return}).then(_),W=R.then(()=>{return},()=>{return});Y.appendQueues.set(this.filePath,W);try{return await R}finally{if(Y.appendQueues.get(this.filePath)===W)Y.appendQueues.delete(this.filePath)}}async readCommittedState(_,E=this.filePath){let R=await this.repairIncompleteTail(_),W=await _.readFile("utf8"),$=z(W,E),{size:H}=await _.stat();return{entries:$,separator:R,size:H}}async readTailSeq(_){let{size:E}=await _.stat();if(E===0)return 0;let R=Math.max(0,E-m),W=Buffer.allocUnsafe(E-R);await _.read(W,0,W.length,R);let $=W.toString("utf8").split(`
|
|
12
|
-
`);for(let k=$.length-1;k>=0;k--){let M=$[k].trim();if(!M)continue;if(k===0&&R>0)break;try{let X=JSON.parse(M).seq;if(typeof X==="number")return X}catch{}break}let H=await _.readFile("utf8");return Y.maxSeq(z(H,this.filePath))}async repairIncompleteTail(_){let{size:E}=await _.stat();if(E===0)return"";let R=Buffer.allocUnsafe(1);if(await _.read(R,0,1,E-1),R[0]===10)return"";let W=await this.findTailStart(_,E),$=Buffer.allocUnsafe(E-W);await _.read($,0,$.length,W);try{return JSON.parse($.toString("utf8").trim()),`
|
|
13
|
-
`}catch{return await _.truncate(W),""}}async findTailStart(_,E){let R=E;while(R>0){let W=Math.max(0,R-m),$=Buffer.allocUnsafe(R-W);await _.read($,0,$.length,W);let H=$.lastIndexOf(10);if(H>=0)return W+H+1;R=W}return 0}}function X_(){return typeof globalThis.Bun<"u"}function Y_(_){return{exec:(E)=>_.exec(E),prepare:(E)=>{let R=_.prepare(E);return{run:(...W)=>{R.run(...W)},get:(...W)=>R.get(...W),all:(...W)=>R.all(...W)}},transaction:(E)=>_.transaction(E)(),pragma:(E)=>_.pragma(E,{simple:!0}),close:()=>_.close()}}function G_(_){return{exec:(E)=>_.exec(E),prepare:(E)=>{let R=_.query(E);return{run:(...W)=>{R.run(...W)},get:(...W)=>R.get(...W),all:(...W)=>R.all(...W)}},transaction:(E)=>_.transaction(E)(),pragma:(E)=>{let R=_.query(`PRAGMA ${E}`).get();if(!R)return;let W=Object.values(R);return W.length===1?W[0]:R},close:()=>_.close()}}var T_=["PRAGMA journal_mode=WAL;","PRAGMA busy_timeout=5000;","PRAGMA synchronous=NORMAL;","PRAGMA foreign_keys=ON;"].join(`
|
|
14
|
-
`);async function h(_){try{let E;if(X_()){let{Database:W}=await import("bun:sqlite");E=G_(new W(_))}else{let $=(await import("better-sqlite3")).default;E=Y_(new $(_))}return E.exec(T_),E}catch{return null}}function b(_){let E=Number(_.pragma("user_version")??0);if(E===3)return;if(E>0&&E!==3)_.exec(`
|
|
15
|
-
DROP TABLE IF EXISTS parts_fts;
|
|
16
|
-
DROP TABLE IF EXISTS parts;
|
|
17
|
-
DROP TABLE IF EXISTS sessions;
|
|
18
|
-
DROP TABLE IF EXISTS projection_state;
|
|
19
|
-
`);_.exec(`
|
|
20
|
-
CREATE TABLE IF NOT EXISTS projection_state (
|
|
21
|
-
project_path TEXT NOT NULL,
|
|
22
|
-
session_id TEXT NOT NULL,
|
|
23
|
-
last_seq INTEGER NOT NULL DEFAULT 0,
|
|
24
|
-
file_size INTEGER NOT NULL DEFAULT 0,
|
|
25
|
-
mtime_ms INTEGER NOT NULL DEFAULT 0,
|
|
26
|
-
PRIMARY KEY (project_path, session_id)
|
|
27
|
-
);
|
|
28
|
-
|
|
29
|
-
CREATE TABLE IF NOT EXISTS sessions (
|
|
30
|
-
project_path TEXT NOT NULL,
|
|
31
|
-
session_id TEXT NOT NULL,
|
|
32
|
-
root_id TEXT,
|
|
33
|
-
parent_id TEXT,
|
|
34
|
-
relation_type TEXT,
|
|
35
|
-
title TEXT,
|
|
36
|
-
agent_type TEXT,
|
|
37
|
-
model TEXT,
|
|
38
|
-
task_status TEXT,
|
|
39
|
-
archived_at TEXT,
|
|
40
|
-
last_message_time TEXT,
|
|
41
|
-
project_sort_key TEXT NOT NULL,
|
|
42
|
-
session_sort_key TEXT NOT NULL,
|
|
43
|
-
first_message_time TEXT,
|
|
44
|
-
message_count INTEGER NOT NULL DEFAULT 0,
|
|
45
|
-
has_errors INTEGER NOT NULL DEFAULT 0,
|
|
46
|
-
is_subagent INTEGER NOT NULL DEFAULT 0,
|
|
47
|
-
-- 完整 StoredSessionMetadata JSON,读回时直接反序列化,保证与 JSONL 路径一致。
|
|
48
|
-
metadata_json TEXT NOT NULL,
|
|
49
|
-
PRIMARY KEY (project_path, session_id)
|
|
50
|
-
);
|
|
51
|
-
CREATE INDEX IF NOT EXISTS idx_sessions_catalog ON sessions(
|
|
52
|
-
last_message_time DESC,
|
|
53
|
-
project_sort_key ASC,
|
|
54
|
-
session_sort_key ASC
|
|
55
|
-
);
|
|
56
|
-
CREATE INDEX IF NOT EXISTS idx_sessions_archived ON sessions(
|
|
57
|
-
archived_at,
|
|
58
|
-
project_path,
|
|
59
|
-
parent_id
|
|
60
|
-
);
|
|
61
|
-
|
|
62
|
-
CREATE TABLE IF NOT EXISTS parts (
|
|
63
|
-
project_path TEXT NOT NULL,
|
|
64
|
-
session_id TEXT NOT NULL,
|
|
65
|
-
part_id TEXT NOT NULL,
|
|
66
|
-
message_id TEXT,
|
|
67
|
-
part_type TEXT,
|
|
68
|
-
role TEXT,
|
|
69
|
-
seq INTEGER,
|
|
70
|
-
timestamp TEXT,
|
|
71
|
-
text TEXT,
|
|
72
|
-
PRIMARY KEY (project_path, session_id, part_id)
|
|
73
|
-
);
|
|
74
|
-
CREATE INDEX IF NOT EXISTS idx_parts_session ON parts(project_path, session_id);
|
|
75
|
-
|
|
76
|
-
CREATE VIRTUAL TABLE IF NOT EXISTS parts_fts USING fts5(
|
|
77
|
-
text,
|
|
78
|
-
project_path UNINDEXED,
|
|
79
|
-
session_id UNINDEXED,
|
|
80
|
-
part_id UNINDEXED,
|
|
81
|
-
role UNINDEXED,
|
|
82
|
-
timestamp UNINDEXED,
|
|
83
|
-
seq UNINDEXED,
|
|
84
|
-
tokenize = 'unicode61'
|
|
85
|
-
);
|
|
86
|
-
`),_.exec("PRAGMA user_version=3;")}var Z_=i("Service"),D;function r(){return B.join(j(),"index.db")}async function K_(){let _=r();if(D&&D.path===_)return D.db;let E=(async()=>{let R=await h(_);if(!R)return null;try{return b(R),R}catch{return null}})();return D={path:_,db:E},E}function U_(){D=void 0}function g_(_){if(_&&typeof _==="object"){let E=_.text;if(typeof E==="string")return E}return null}function F_(_,E,R,W){_.prepare("DELETE FROM parts WHERE project_path=? AND session_id=?").run(E,R),_.prepare("DELETE FROM parts_fts WHERE project_path=? AND session_id=?").run(E,R);let $=new Map;for(let M of W)if(M.type==="message_created")$.set(M.data.messageId,M.data.role);let H=_.prepare(`INSERT OR REPLACE INTO parts
|
|
87
|
-
(project_path, session_id, part_id, message_id, part_type, role, seq, timestamp, text)
|
|
88
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`),k=_.prepare(`INSERT INTO parts_fts (text, project_path, session_id, part_id, role, timestamp, seq)
|
|
89
|
-
VALUES (?, ?, ?, ?, ?, ?, ?)`);for(let M of W){if(M.type!=="part_created"&&M.type!=="part_updated")continue;if(M.data.partType!=="text")continue;let X=g_(M.data.payload);if(X===null)continue;let G=$.get(M.data.messageId)??"assistant",g=M.seq??0;if(H.run(E,R,M.data.partId,M.data.messageId,M.data.partType,G,g,M.timestamp,X),G==="user"||G==="assistant")k.run(X,E,R,M.data.partId,G,M.timestamp,g)}}function D_(_,E){_.prepare(`INSERT INTO sessions
|
|
90
|
-
(project_path, session_id, root_id, parent_id, relation_type, title,
|
|
91
|
-
agent_type, model, task_status, archived_at, last_message_time, project_sort_key,
|
|
92
|
-
session_sort_key, first_message_time, message_count, has_errors,
|
|
93
|
-
is_subagent, metadata_json)
|
|
94
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
95
|
-
ON CONFLICT(project_path, session_id) DO UPDATE SET
|
|
96
|
-
root_id=excluded.root_id, parent_id=excluded.parent_id,
|
|
97
|
-
relation_type=excluded.relation_type, title=excluded.title,
|
|
98
|
-
agent_type=excluded.agent_type, model=excluded.model,
|
|
99
|
-
task_status=excluded.task_status, archived_at=excluded.archived_at,
|
|
100
|
-
last_message_time=excluded.last_message_time,
|
|
101
|
-
project_sort_key=excluded.project_sort_key,
|
|
102
|
-
session_sort_key=excluded.session_sort_key,
|
|
103
|
-
first_message_time=excluded.first_message_time, message_count=excluded.message_count,
|
|
104
|
-
has_errors=excluded.has_errors, is_subagent=excluded.is_subagent,
|
|
105
|
-
metadata_json=excluded.metadata_json`).run(E.projectPath,E.sessionId,E.rootId,E.parentId??null,E.relationType??null,E.title??null,E.agentType??null,E.model??null,E.taskStatus,E.archivedAt??null,E.lastMessageTime,y(E.projectPath),y(E.sessionId),E.firstMessageTime,E.messageCount,E.hasErrors?1:0,E.relationType==="subagent"?1:0,JSON.stringify(E))}function a(_,E,R){for(let W of["sessions","parts","parts_fts"])_.prepare(`DELETE FROM ${W} WHERE project_path=? AND session_id=?`).run(E,R)}function v(_,E,R){a(_,E,R),_.prepare("DELETE FROM projection_state WHERE project_path=? AND session_id=?").run(E,R)}function N(_,E,R,W,$,H){_.prepare(`INSERT INTO projection_state
|
|
106
|
-
(project_path, session_id, last_seq, file_size, mtime_ms)
|
|
107
|
-
VALUES (?, ?, ?, ?, ?)
|
|
108
|
-
ON CONFLICT(project_path, session_id) DO UPDATE SET
|
|
109
|
-
last_seq=excluded.last_seq, file_size=excluded.file_size,
|
|
110
|
-
mtime_ms=excluded.mtime_ms`).run(E,R,W,$,H)}async function B_(_,E,R,W,$=L(R,E)){let H;try{let Q=await d($);H={size:Q.size,mtimeMs:Q.mtimeMs}}catch{return _.transaction(()=>v(_,R,E)),!0}let k=_.prepare("SELECT last_seq, file_size, mtime_ms FROM projection_state WHERE project_path=? AND session_id=?").get(R,E);if(k&&k.file_size===H.size&&k.mtime_ms===Math.floor(H.mtimeMs))return!1;let X=await new Y($).readAll(),G=X.reduce((Q,Z)=>typeof Z.seq==="number"&&Z.seq>Q?Z.seq:Q,0),g=w(X),T=W(X,E,R);if(X.length===0||!T)return _.transaction(()=>{a(_,R,E),N(_,R,E,G,H.size,Math.floor(H.mtimeMs))}),!0;let F=_.prepare("SELECT last_message_time FROM sessions WHERE project_path=? AND session_id=?").get(T.projectPath,T.sessionId),A=B.resolve($)===B.resolve(L(T.projectPath,T.sessionId));if(F&&!A&&typeof F.last_message_time==="string"&&F.last_message_time>T.lastMessageTime)return N(_,R,E,G,H.size,Math.floor(H.mtimeMs)),!0;return _.transaction(()=>{D_(_,T),F_(_,T.projectPath,T.sessionId,g),N(_,R,E,G,H.size,Math.floor(H.mtimeMs))}),!0}var l=new WeakMap;async function A_(_,E,R=0){let W=l.get(_)??{};if(l.set(_,W),W.inFlight)return W.inFlight;if(R>0&&W.lastCompletedAt!==void 0&&Date.now()-W.lastCompletedAt<=R)return;let $=C_(_,E);W.inFlight=$;try{await $,W.lastCompletedAt=Date.now()}finally{if(W.inFlight===$)W.inFlight=void 0}}async function C_(_,E){let{readdir:R}=await import("node:fs/promises"),W=await n(),$=new Set,k=(await Promise.all(W.map(async(Q)=>{let Z=o(Q),K=B.join(j(),"projects",Q);try{return(await R(K)).flatMap((q)=>{if(!q.endsWith(".jsonl"))return[];let p=q.slice(0,-6);if(!C(p))return[];return[{filePath:B.join(K,q),projectPath:Z,sessionId:p}]})}catch{return[]}}))).flat();for(let Q of k)$.add(`${Q.projectPath}\x00${Q.sessionId}`);let M=_.prepare(`SELECT project_path, session_id, last_seq, file_size, mtime_ms
|
|
111
|
-
FROM projection_state`).all(),X=new Map(M.map((Q)=>[`${Q.project_path}\x00${Q.session_id}`,Q])),G=[],g=Math.min(128,k.length),T=0;await Promise.all(Array.from({length:g},async()=>{while(T<k.length){let Q=k[T++];if(!Q)continue;try{let Z=await d(Q.filePath),K=X.get(`${Q.projectPath}\x00${Q.sessionId}`);if(K&&K.file_size===Z.size&&K.mtime_ms===Math.floor(Z.mtimeMs))continue}catch{}G.push(Q)}}));let F=Math.min(32,G.length),A=0;await Promise.all(Array.from({length:F},async()=>{while(A<G.length){let Q=G[A++];if(!Q)continue;try{await B_(_,Q.sessionId,Q.projectPath,E,Q.filePath)}catch(Z){if(Z.code!=="ENOENT")Z_.warn(`[SessionService] Skipping invalid session transcript: ${Q.sessionId}`)}}}));for(let Q of M)if(!$.has(`${Q.project_path}\x00${Q.session_id}`))_.transaction(()=>v(_,Q.project_path,Q.session_id))}function n_(_,E,R){_.transaction(()=>v(_,R,E))}async function i_(_){let{rm:E}=await import("node:fs/promises");U_();let R=r();for(let H of["","-wal","-shm"])await E(`${R}${H}`,{force:!0}).catch(()=>{return});let W=await K_();if(!W)return null;return await A_(W,_),W.prepare("SELECT COUNT(*) c FROM sessions").get()?.c??0}function d_(_,E,R,W){let $=E.replace(/["*]/g," ").trim().split(/\s+/)[0];if(!$)return[];let H=`"${$}"*`,k=R?`SELECT session_id, role, timestamp, text FROM parts_fts
|
|
112
|
-
WHERE parts_fts MATCH ? AND project_path = ?
|
|
113
|
-
ORDER BY timestamp DESC LIMIT ?`:`SELECT session_id, role, timestamp, text FROM parts_fts
|
|
114
|
-
WHERE parts_fts MATCH ?
|
|
115
|
-
ORDER BY timestamp DESC LIMIT ?`,M=_.prepare(k);return R?M.all(H,R,W):M.all(H,W)}
|
|
116
|
-
export{w as Hc,q_ as Ic,y_ as Jc,z as Kc,Y as Lc,y as Mc,$_ as Nc,z_ as Oc,k_ as Pc,f_ as Qc,r as Rc,K_ as Sc,U_ as Tc,B_ as Uc,A_ as Vc,n_ as Wc,i_ as Xc,d_ as Yc};
|
package/dist/chunk-wy2b5hsh.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import{K as I}from"./chunk-wqewxnez.js";import{Cc as D}from"./chunk-jy1e6ve5.js";import w from"node:path";function C(a){let t=a.replace(/\s+/g," ").trim();return t.length<=72?t:`${t.slice(0,69)}...`}function P(a){let t=a.replace(/\s+/g," ").trim();return t.length<=500?t:`${t.slice(0,497)}...`}function S(a){return`task/${a.replace(/[^a-zA-Z0-9_-]/g,"-").slice(0,40)}`}class z{static async createSessionTask(a){if(!a.prompt.trim())throw Error("Task prompt must not be blank");if(!w.isAbsolute(a.sourceProjectPath))throw Error("Task source project path must be absolute");let t=w.resolve(a.sourceProjectPath),s;try{return s=a.isolation==="worktree"?await I.enter({sessionId:a.sessionId,workspaceRoot:t,name:S(a.sessionId)}):void 0,{metadata:await D.createSessionMetadata(a.sessionId,s?.workspaceRoot??t,{title:a.title?.trim()||C(a.prompt),taskPromptSummary:P(a.prompt),taskDispatch:a.dispatch,taskModelId:a.dispatch?.modelId,selectedModelId:a.dispatch?.modelId,permissionMode:a.dispatch?.permissionMode,reasoningEffort:a.dispatch?.reasoningEffort,serviceTier:a.dispatch?.serviceTier,responseVerbosity:a.dispatch?.responseVerbosity,communicationStyle:a.dispatch?.communicationStyle,communicationStyleDigest:a.dispatch?.communicationStyleDigest,projectInstructionsDigest:a.dispatch?.projectInstructionsDigest,taskRetriedFrom:a.retriedFrom,taskIsolation:a.isolation,taskSourceProjectPath:t,taskWorktree:s}),taskWorktree:s}}catch(k){if(s)await I.exit({sessionId:a.sessionId,action:"remove",discardChanges:!0}).catch(()=>{return});throw k}}}var N=256,Z=8388608,_=30000;class c extends Error{kind;pendingItems;pendingBytes;constructor(a,t,s){super(t,s);this.kind=a;this.name="BoundedSerialEgressError",this.pendingItems=s?.pendingItems,this.pendingBytes=s?.pendingBytes}}function m(a){a.catch(()=>{return})}class F{options;pending=[];flushWaiters=[];pendingBytes=0;nextSequence=0;completedSequence=0;draining=!1;closed=!1;failure;activeWriteAbort;activeWriteStop;activeWriteTimeout;constructor(a){this.options=a;if(this.assertPositiveInteger(a.maxPendingItems,"maxPendingItems"),this.assertPositiveInteger(a.maxPendingBytes,"maxPendingBytes"),this.assertPositiveInteger(a.writeTimeoutMs,"writeTimeoutMs"),a.signal?.addEventListener("abort",this.handleAbort,{once:!0}),a.signal?.aborted)this.handleAbort()}offer(a){if(this.closed)return{accepted:!1,error:this.failure??new c("closed","Egress is already closed")};let t;try{t=this.options.sizeOf(a)}catch(i){return this.rejectAdmission(new c("invalid_size","Egress size calculation failed",{cause:i}))}if(!Number.isSafeInteger(t)||t<0)return this.rejectAdmission(new c("invalid_size","Egress size must be a non-negative safe integer"));if(t>this.options.maxPendingBytes)return this.rejectAdmission(new c("oversized",`Egress value requires ${t} bytes; limit is ${this.options.maxPendingBytes}`));if(this.pending.length>=this.options.maxPendingItems||this.pendingBytes+t>this.options.maxPendingBytes)return this.rejectAdmission(new c("overflow",`Egress pending limit exceeded (${this.pending.length} items, ${this.pendingBytes} bytes)`));let s,k,h=new Promise((i,f)=>{s=i,k=f});return m(h),this.nextSequence+=1,this.pending.push({value:a,bytes:t,sequence:this.nextSequence,resolve:s,reject:k,completion:h}),this.pendingBytes+=t,this.startDrain(),{accepted:!0,completion:h}}flush(){if(this.failure){let h=Promise.reject(this.failure);return m(h),h}let a=this.nextSequence;if(a<=this.completedSequence)return Promise.resolve();let t,s,k=new Promise((h,i)=>{t=h,s=i});return m(k),this.flushWaiters.push({targetSequence:a,resolve:t,reject:s}),k}close(a){let t=a instanceof c?a:new c("closed","Egress was closed",{cause:a});this.fail(t)}stats(){return{closed:this.closed,pendingItems:this.pending.length,pendingBytes:this.pendingBytes}}handleAbort=()=>{this.fail(new c("aborted","Egress was aborted",{cause:this.options.signal?.reason}))};rejectAdmission(a){return this.fail(a),{accepted:!1,error:a}}startDrain(){if(this.draining||this.closed)return;this.draining=!0;let a=this.drain();m(a)}async drain(){try{while(!this.closed){let a=this.pending[0];if(!a)return;try{await this.writeOne(a.value)}catch(t){this.fail(this.normalizeWriteError(t));return}if(this.closed||this.pending[0]!==a)return;this.pending.shift(),this.pendingBytes-=a.bytes,this.completedSequence=a.sequence,a.resolve(),this.settleFlushWaiters()}}finally{if(this.draining=!1,!this.closed&&this.pending.length>0)this.startDrain()}}async writeOne(a){let t=new AbortController;this.activeWriteAbort=t;let s,k,h=new Promise((W,T)=>{k=T});m(h),this.activeWriteStop=k;let i=Promise.resolve().then(()=>this.options.write(a,t.signal));m(i);let f=new Promise((W,T)=>{s=setTimeout(()=>{let M=new c("write_timeout",`Egress write timed out after ${this.options.writeTimeoutMs}ms`);t.abort(M),T(M)},this.options.writeTimeoutMs),this.activeWriteTimeout=s});m(f);try{await Promise.race([i,f,h])}finally{if(s!==void 0)clearTimeout(s);if(this.activeWriteTimeout===s)this.activeWriteTimeout=void 0;if(this.activeWriteAbort===t)this.activeWriteAbort=void 0;if(this.activeWriteStop===k)this.activeWriteStop=void 0}}normalizeWriteError(a){if(a instanceof c)return a;return new c("write_failed","Egress write failed",{cause:a})}fail(a){if(this.closed)return;if(a.pendingItems??=this.pending.length,a.pendingBytes??=this.pendingBytes,this.closed=!0,this.failure=a,this.options.signal?.removeEventListener("abort",this.handleAbort),this.activeWriteTimeout!==void 0)clearTimeout(this.activeWriteTimeout),this.activeWriteTimeout=void 0;this.activeWriteAbort?.abort(a),this.activeWriteStop?.(a),this.activeWriteAbort=void 0,this.activeWriteStop=void 0;let t=this.pending.splice(0);this.pendingBytes=0;for(let s of t)s.reject(a);for(let s of this.flushWaiters.splice(0))s.reject(a);try{this.options.onFailure?.(a)}catch{}}settleFlushWaiters(){for(let a=0;a<this.flushWaiters.length;){let t=this.flushWaiters[a];if(t.targetSequence>this.completedSequence){a+=1;continue}this.flushWaiters.splice(a,1),t.resolve()}}assertPositiveInteger(a,t){if(!Number.isSafeInteger(a)||a<=0)throw RangeError(`${t} must be a positive safe integer`)}}
|
|
2
|
-
export{z as v,N as w,Z as x,_ as y,c as z,F as A};
|
package/dist/chunk-xm44tqjb.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{$g as d,Yg as a,Zg as b,_g as c,ah as e,bh as f}from"./chunk-5g2p1fwn.js";import"./chunk-av10vmxk.js";export{b as getVersion,c as getPackageName,a as getPackageInfo,e as getFormattedVersion,d as getDescription,f as getCopyright};
|