blade-code 0.10.157 → 0.10.158

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/dist/blade.js +2 -2
  2. package/dist/{chunk-p1d4ep58.js → chunk-1329rzdd.js} +1 -1
  3. package/dist/{chunk-2nnrrfte.js → chunk-25z7w7jb.js} +1 -1
  4. package/dist/{chunk-7aysjqen.js → chunk-26109k8r.js} +1 -1
  5. package/dist/{chunk-cv4h5c96.js → chunk-42y6ks44.js} +1 -1
  6. package/dist/{chunk-d6x9aqqp.js → chunk-479y73j2.js} +1 -1
  7. package/dist/{chunk-eass9t33.js → chunk-4gsjcz7t.js} +1 -1
  8. package/dist/chunk-5kb1dh44.js +1 -0
  9. package/dist/{chunk-ha8w887r.js → chunk-6htg4eyc.js} +1 -1
  10. package/dist/{chunk-rdvadyyt.js → chunk-6zzet05f.js} +1 -1
  11. package/dist/{chunk-v25d7gze.js → chunk-7h3405ty.js} +1 -1
  12. package/dist/{chunk-7mqmyhfe.js → chunk-7z31ajj4.js} +1 -1
  13. package/dist/{chunk-8brsyfkz.js → chunk-95z104ay.js} +2 -2
  14. package/dist/chunk-9hmjg0k7.js +1 -0
  15. package/dist/{chunk-j5fwzfaj.js → chunk-a9fjtdsh.js} +1 -1
  16. package/dist/{chunk-75n6cr3x.js → chunk-bgc4wts7.js} +2 -2
  17. package/dist/{chunk-1qp826p9.js → chunk-ccsgzyth.js} +1 -1
  18. package/dist/{chunk-nk1kfpz5.js → chunk-ehdsj506.js} +3 -3
  19. package/dist/{chunk-5h9q6jjv.js → chunk-ej0a0s1t.js} +1 -1
  20. package/dist/{chunk-3jqvgxnc.js → chunk-f6wx6sf2.js} +1 -1
  21. package/dist/{chunk-04vy4a4a.js → chunk-fp7ssc21.js} +1 -1
  22. package/dist/{chunk-xqzmm1bf.js → chunk-gnjsdr40.js} +1 -1
  23. package/dist/{chunk-sr61gfha.js → chunk-hamdqef9.js} +1 -1
  24. package/dist/{chunk-tfsmykk5.js → chunk-jcq3tk8c.js} +1 -1
  25. package/dist/{chunk-9cfh48md.js → chunk-jdmm68kd.js} +1 -1
  26. package/dist/{chunk-wax2788t.js → chunk-jxxvc3b0.js} +1 -1
  27. package/dist/{chunk-s9ws4xsz.js → chunk-kxz7j4a3.js} +1 -1
  28. package/dist/{chunk-nmymd2hf.js → chunk-mm5rqxam.js} +1 -1
  29. package/dist/{chunk-9svd1x6q.js → chunk-p5k6x3be.js} +1 -1
  30. package/dist/{chunk-8bm5bpa2.js → chunk-pnfeyw0g.js} +1 -1
  31. package/dist/{chunk-tbg7yrwp.js → chunk-pz0d6ne3.js} +1 -1
  32. package/dist/{chunk-96c1kd2j.js → chunk-tfebp09g.js} +1 -1
  33. package/dist/{chunk-zqn8q1b6.js → chunk-thveee78.js} +1 -1
  34. package/dist/{chunk-ra0y5drh.js → chunk-v7b7dx9j.js} +1 -1
  35. package/dist/{chunk-9rx1axgj.js → chunk-vg6m8ybn.js} +1 -1
  36. package/dist/{chunk-w5awn40e.js → chunk-vq1myd58.js} +1 -1
  37. package/dist/{chunk-pdfdj5rp.js → chunk-vs8ywzme.js} +1 -1
  38. package/dist/{chunk-q1rnvn85.js → chunk-vz13c7fr.js} +45 -45
  39. package/dist/{chunk-7r26xgk4.js → chunk-xh3bm0p0.js} +1 -1
  40. package/dist/{chunk-m268099y.js → chunk-xxd3vx1j.js} +1 -1
  41. package/dist/{chunk-46a6mzfg.js → chunk-y1t2tvmq.js} +1 -1
  42. package/package.json +1 -1
  43. package/dist/chunk-4d6d5xtp.js +0 -1
  44. package/dist/chunk-bfd4yt7c.js +0 -1
@@ -1,46 +1,46 @@
1
- import{gf as h0,hf as mT}from"./chunk-fx9vm1n5.js";import{Ch as LT}from"./chunk-28tzj187.js";import{Cj as PT}from"./chunk-5q4z0sfr.js";import{Bk as y0,Ck as r,Kk as hT,ek as V0,mk as D,ok as S,pk as d,rk as s,sk as q0,tk as RT,uk as bT,vk as yT,zk as A}from"./chunk-7xtxvrh8.js";import{Lk as g0}from"./chunk-sdapqhj0.js";import{createHash as I_}from"node:crypto";import{readdir as D0,stat as w0}from"node:fs/promises";import U0 from"node:path";import{createHash as T$,randomBytes as n0}from"node:crypto";import{chmod as i0,link as $$,lstat as n,mkdir as _$,open as i,readdir as c0,realpath as l0,unlink as C0}from"node:fs/promises";import W from"node:path";function tT(){return typeof globalThis.Bun<"u"}function oT(T){return{exec:($)=>T.exec($),prepare:($)=>{let _=T.prepare($);return{run:(...G)=>{_.run(...G)},get:(...G)=>_.get(...G),all:(...G)=>_.all(...G)}},transaction:($)=>T.transaction($)(),pragma:($)=>T.pragma($,{simple:!0}),close:()=>T.close()}}function rT(T){return{exec:($)=>T.exec($),prepare:($)=>{let _=T.query($);return{run:(...G)=>{_.run(...G)},get:(...G)=>_.get(...G),all:(...G)=>_.all(...G)}},transaction:($)=>T.transaction($)(),pragma:($)=>{let _=T.query(`PRAGMA ${$}`).get();if(!_)return;let G=Object.values(_);return G.length===1?G[0]:_},close:()=>T.close()}}function eT(T){return[`PRAGMA busy_timeout=${T};`,"PRAGMA journal_mode=WAL;","PRAGMA synchronous=NORMAL;","PRAGMA foreign_keys=ON;"].join(`
2
- `)}async function T0(T,$={}){let _=$.busyTimeoutMs??5000;if(!Number.isSafeInteger(_)||_<0)return null;let G=null;try{if(tT()){let{Database:Y}=await import("bun:sqlite");G=rT(new Y(T))}else{let Q=(await import("better-sqlite3")).default;G=oT(new Q(T))}return G.exec(eT(_)),G}catch{try{G?.close()}catch{}return null}}var G$="surface-workspaces-v1",d0=/^[a-f0-9]{64}$/,X$=/^acp-remote-workspace:[A-Za-z0-9_-]{43}$/,Y$=1024,Q$=".surface-workspaces-v1.capacity.sqlite",s0=/^\.tmp-acp-remote-workspace-([1-9][0-9]*)-[a-f0-9]{32}\.pending$/;class H extends Error{name="AcpRemoteWorkspaceReferenceError";code;retryable;constructor(T){let $=T==="session_surface_not_found"?{message:"Session surface was not found",retryable:!1}:T==="session_surface_capacity"?{message:"Session surface capacity is exhausted",retryable:!0}:{message:"Session surface state is invalid",retryable:!1};super($.message);this.code=T,this.retryable=$.retryable,Object.setPrototypeOf(this,new.target.prototype)}}var v,$0=new Map;function a0(T){return W.join(String(T),G$)}async function t0(T,$){let _=S($);if(d(_.collisionIdentity)!==String(T))throw new H("session_surface_state_invalid");let G=r0(_.exactIdentity),X=a0(T);return await U$(T,X),Z$(X,()=>V$(X,async()=>{await H$(X);let Y=await o0(T,X,!0),Q=Y.recordsByDigest.get(G);if(Q)return Q.workspaceRef;if(Y.recordsByDigest.size>=Y$)throw new H("session_surface_capacity");let Z=W.join(X,`${G}.json`),U=new Set(Y.workspaceRefToDigest.keys());for(let V=0;V<32;V+=1){let g=L$();if(U.has(g))continue;return z$(T,X,Z,_,{version:1,exactIdentityDigest:G,workspaceRef:g})}throw new H("session_surface_state_invalid")}))}async function Z$(T,$){let _=$0.get(T)??Promise.resolve(),G=()=>{return},X=new Promise((Q)=>{G=Q}),Y=_.catch(()=>{return}).then(()=>X);$0.set(T,Y),await _.catch(()=>{return});try{return await $()}finally{if(G(),$0.get(T)===Y)$0.delete(T)}}async function U$(T,$){try{await H0($,String(T))}catch(_){if(q(_)!=="ENOENT"){if(_ instanceof H)throw _;throw new H("session_surface_state_invalid")}try{await _$($,{recursive:!1,mode:448})}catch(G){if(q(G)!=="EEXIST")throw new H("session_surface_state_invalid")}await H0($,String(T)),await m(String(T))}}async function V$(T,$){await v?.beforeCapacityLockAttempt?.();let _=await B$(T),G=!1,X,Y,Q;try{_.database.exec("BEGIN IMMEDIATE;"),G=!0,await v?.afterCapacityLockAcquired?.(),Q={value:await $()}}catch(Z){X=Z}if(G)try{await g$(_),_.database.exec("ROLLBACK;")}catch(Z){Y=Z}try{_.database.close()}catch(Z){if(!G)Y=Z}if(await _.identityHandle.close().catch(()=>{return}),Y!==void 0)throw new H("session_surface_state_invalid");if(X instanceof H)throw X;if(X!==void 0||!Q)throw new H("session_surface_state_invalid");return Q.value}async function B$(T){let $=W.join(T,Q$),_=null,G;try{let X=!1;try{let Q=await i($,"wx",384);X=!0,await Q.sync(),await Q.close()}catch(Q){if(q(Q)!=="EEXIST")throw Q}if(await u($,T),X)await m(T);G=await i($,"r"),await c(G,$,T);let Y=await G.stat({bigint:!0});if(_=await T0($,{busyTimeoutMs:30000}),!_)throw new H("session_surface_state_invalid");if(_.exec("PRAGMA locking_mode=NORMAL;"),_.exec("PRAGMA synchronous=FULL;"),_.exec("PRAGMA busy_timeout=30000;"),process.platform!=="win32")await i0($,384);return await c(G,$,T),await C$($,T),{database:_,identity:Y,identityHandle:G,path:$}}catch(X){await G?.close().catch(()=>{return});try{_?.close()}catch{}if(X instanceof H)throw X;throw new H("session_surface_state_invalid")}}async function g$(T){await c(T.identityHandle,T.path,W.dirname(T.path));let $=await T.identityHandle.stat({bigint:!0});if(!O0(T.identity,$))throw new H("session_surface_state_invalid")}async function C$(T,$){for(let _ of["-journal","-shm","-wal"]){let G=`${T}${_}`;try{if(process.platform!=="win32")await i0(G,384);await u(G,$)}catch(X){if(q(X)!=="ENOENT"){if(X instanceof H)throw X;throw new H("session_surface_state_invalid")}}}}async function H$(T){let $=await c0(T,{withFileTypes:!0}),_=!1;for(let G of $){if(!s0.test(G.name))continue;let X=W.join(T,G.name);await u(X,T),await C0(X),_=!0}if(_)await m(T)}async function o0(T,$,_){try{await H0($,String(T))}catch(Q){if(!_&&q(Q)==="ENOENT")return{recordsByDigest:new Map,workspaceRefToDigest:new Map};if(Q instanceof H)throw Q;throw new H("session_surface_state_invalid")}let G;try{G=await c0($,{withFileTypes:!0})}catch(Q){if(!_&&q(Q)==="ENOENT")return{recordsByDigest:new Map,workspaceRefToDigest:new Map};throw new H("session_surface_state_invalid")}let X=new Map,Y=new Map;for(let Q of G){if(s0.test(Q.name)){await u(W.join($,Q.name),$);continue}if(!Q.name.endsWith(".json"))continue;let Z=W.basename(Q.name,".json");if(!d0.test(Z))throw new H("session_surface_state_invalid");let U=W.join($,Q.name),V=await O$(U,$);if(V.exactIdentityDigest!==Z)throw new H("session_surface_state_invalid");if(X.has(Z))throw new H("session_surface_state_invalid");let g=Y.get(V.workspaceRef);if(g&&g!==Z)throw new H("session_surface_state_invalid");X.set(Z,V),Y.set(V.workspaceRef,Z)}return{recordsByDigest:X,workspaceRefToDigest:Y}}async function O$(T,$){let _;try{await u(T,$),_=await i(T,"r"),await c(_,T,$);let G=await _.readFile({encoding:"utf8"});return M$(G)}catch(G){if(G instanceof H&&G.code==="session_surface_not_found")throw G;if(q(G)==="ENOENT")throw new H("session_surface_not_found");throw new H("session_surface_state_invalid")}finally{await _?.close()}}function M$(T){let $;try{$=JSON.parse(T)}catch{throw new H("session_surface_state_invalid")}if(!F$($))throw new H("session_surface_state_invalid");return $}function F$(T){if(!T||typeof T!=="object"||Array.isArray(T))return!1;let $=T,_=Object.keys($).sort();if(_.length!==3||_[0]!=="exactIdentityDigest"||_[1]!=="version"||_[2]!=="workspaceRef")return!1;return $.version===1&&typeof $.exactIdentityDigest==="string"&&d0.test($.exactIdentityDigest)&&typeof $.workspaceRef==="string"&&X$.test($.workspaceRef)}function r0(T){return T$("sha256").update(`acp-remote-workspace-exact-identity\x00${T}`).digest("hex")}function L$(){return`acp-remote-workspace:${n0(32).toString("base64url")}`}function J$(){return`.tmp-acp-remote-workspace-${process.pid}-${n0(16).toString("hex")}.pending`}async function H0(T,$){if(W.dirname(T)!==$)throw new H("session_surface_state_invalid");let _=await n(T);if(_.isSymbolicLink()||!_.isDirectory())throw new H("session_surface_state_invalid");if(typeof process.getuid==="function"&&_.uid!==process.getuid())throw new H("session_surface_state_invalid");let G=e0(_.mode);if(process.platform!=="win32"&&G!==448)throw new H("session_surface_state_invalid");await M0(T,$,W.basename(T))}async function u(T,$){if(W.dirname(T)!==$)throw new H("session_surface_state_invalid");let _=await n(T);if(_.isSymbolicLink()||!_.isFile())throw new H("session_surface_state_invalid");if(typeof process.getuid==="function"&&_.uid!==process.getuid())throw new H("session_surface_state_invalid");let G=e0(_.mode);if(process.platform!=="win32"&&G!==384)throw new H("session_surface_state_invalid");await M0(T,$,W.basename(T))}async function c(T,$,_){let[G,X]=await Promise.all([T.stat({bigint:!0}),n($,{bigint:!0})]);if(W.dirname($)!==_||X.isSymbolicLink()||!X.isFile()||!G.isFile()||X.dev!==G.dev||X.ino!==G.ino)throw new H("session_surface_state_invalid");if(typeof process.getuid==="function"&&(Number(X.uid)!==process.getuid()||Number(G.uid)!==process.getuid()))throw new H("session_surface_state_invalid");let Y=Number(X.mode&BigInt(511)),Q=Number(G.mode&BigInt(511));if(process.platform!=="win32"&&(Y!==384||Q!==384))throw new H("session_surface_state_invalid");await M0($,_,W.basename($))}async function M0(T,$,_){let G=await l0(T),X=await l0($);if(G!==W.join(X,_))throw new H("session_surface_state_invalid")}async function m(T){if(!I$(process.platform))return;try{if(v?.syncDirectory){await v.syncDirectory(T);return}await N$(T)}catch{throw new H("session_surface_state_invalid")}}function I$(T){return T!=="win32"}async function N$(T){let $=await i(T,"r");try{await $.sync()}finally{await $.close()}}async function z$(T,$,_,G,X){let Y=W.join($,J$()),Q,Z,U=!1,V=!1,g,O;try{Q=await i(Y,"wx",384),await Q.writeFile(JSON.stringify(X),"utf8"),await Q.sync(),await c(Q,Y,$),Z=await Q.stat({bigint:!0}),await Q.close(),Q=void 0,await v?.beforePublish?.({finalPath:_,referenceDirectoryPath:$,tempPath:Y});try{await $$(Y,_),U=!0}catch(M){if(q(M)!=="EEXIST")throw M;g=await j$(T,G)}if(U){let M=await n(_,{bigint:!0});if(!Z||!O0(Z,M))throw new H("session_surface_state_invalid");await u(_,$),await m($),V=!0,g=X.workspaceRef;try{await v?.afterPublish?.({finalPath:_,referenceDirectoryPath:$,tempPath:Y})}catch{}}}catch(M){O=M}finally{await Q?.close().catch(()=>{return})}if(O!==void 0&&U&&!V&&Z)try{let M=await n(_,{bigint:!0});if(O0(Z,M))await C0(_),await m($)}catch{}try{if(await C0(Y),!V)await m($)}catch(M){if(q(M)!=="ENOENT"&&O===void 0&&!V)O=M}if(O instanceof H)throw O;if(O!==void 0||g===void 0)throw new H("session_surface_state_invalid");return g}async function j$(T,$){let _=a0(T),G=await o0(T,_,!0),X=r0(S($).exactIdentity),Y=G.recordsByDigest.get(X);if(!Y)throw new H("session_surface_state_invalid");return Y.workspaceRef}function O0(T,$){return BigInt(T.dev)===BigInt($.dev)&&BigInt(T.ino)===BigInt($.ino)}function q(T){return T!==null&&typeof T==="object"&&"code"in T&&typeof T.code==="string"?T.code:void 0}function e0(T){return typeof T==="bigint"?Number(T&BigInt(511)):T&511}import*as b from"node:path";var XT=50,YT=100,W$=new Set(["queued","running","completed","failed","cancelled","interrupted"]),K$=new Set(["high","medium","low"]),QT=/^[A-Za-z0-9_-]+$/,k$=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?(?:Z|[+-]\d{2}:\d{2})$/,A$=/^acp-remote-exact-path:[a-f0-9]{64}$/;function ZT(T){return typeof T==="string"&&k$.test(T)&&Number.isFinite(Date.parse(T))}function TT(T){return typeof T==="string"&&b.isAbsolute(T)}function $T(T){return typeof T==="string"&&A$.test(T)}function x$(T){return Buffer.from(JSON.stringify(T),"utf8").toString("base64url")}function E$(T){return Buffer.from(JSON.stringify(T),"utf8").toString("base64url")}function q$(T){try{if(!QT.test(T))throw Error("invalid");let $=Buffer.from(T,"base64url").toString("utf8");if(Buffer.from($,"utf8").toString("base64url")!==T)throw Error("invalid");let _=JSON.parse($);if(_.version!==1||_.kind!==void 0&&_.kind!=="local"||typeof _.includeSubagents!=="boolean"||_.archived!==void 0&&typeof _.archived!=="boolean"||!(_.cwd===null||TT(_.cwd))||!ZT(_.lastMessageTime)||!TT(_.projectPath)||!A(_.sessionId))throw Error("invalid");return{version:1,kind:"local",cwd:_.cwd===null?null:b.resolve(_.cwd),includeSubagents:_.includeSubagents,archived:_.archived??!1,lastMessageTime:_.lastMessageTime,projectPath:b.resolve(_.projectPath),sessionId:_.sessionId}}catch{throw Error("Invalid session cursor")}}function D$(T){try{if(!QT.test(T))throw Error("invalid");let $=Buffer.from(T,"base64url").toString("utf8");if(Buffer.from($,"utf8").toString("base64url")!==T)throw Error("invalid");let _=JSON.parse($),G=Object.keys(_),X=new Set(["version","kind","exactIdentity","includeSubagents","archived","lastMessageTime","workspaceIdentity","sessionId"]);if(G.some((Y)=>!X.has(Y))||_.version!==1||_.kind!=="remote"||typeof _.includeSubagents!=="boolean"||typeof _.archived!=="boolean"||!(_.exactIdentity===null||$T(_.exactIdentity))||!ZT(_.lastMessageTime)||!$T(_.workspaceIdentity)||!A(_.sessionId))throw Error("invalid");return{version:1,kind:"remote",exactIdentity:_.exactIdentity??null,includeSubagents:_.includeSubagents,archived:_.archived,lastMessageTime:_.lastMessageTime,workspaceIdentity:_.workspaceIdentity,sessionId:_.sessionId}}catch{throw Error("Invalid remote session cursor")}}function p(T){let $="";for(let _=0;_<T.length;_+=1)$+=T.charCodeAt(_).toString(16).padStart(4,"0");return $}function w$(T){if(!T.cursor)return;let $=q$(T.cursor);if($.cwd!==T.cwd||$.includeSubagents!==T.includeSubagents||($.archived??!1)!==T.archived)throw Error("Session cursor scope does not match this query");return $}function S$(T){if(!T.cursor)return;let $=D$(T.cursor);if($.exactIdentity!==T.exactIdentity||T.exactIdentity!==null&&$.workspaceIdentity!==T.exactIdentity||$.includeSubagents!==T.includeSubagents||($.archived??!1)!==T.archived)throw Error("Remote session cursor scope does not match this query");return $}function i_(T={}){let{cwd:$,cursor:_,limit:G,includeSubagents:X=!1,archived:Y=!1}=T;if($!==void 0&&!b.isAbsolute($))throw Error("Session catalog cwd must be absolute");let Q=G===void 0?XT:G;if(!Number.isInteger(Q)||Q<1||Q>YT)throw Error("Session catalog limit must be an integer from 1 to 100");return{cwd:$===void 0?null:b.resolve($),cursor:_??void 0,limit:Q,includeSubagents:X,archived:Y}}function c_(T={}){let{descriptor:$,cursor:_,limit:G,includeSubagents:X=!1,archived:Y=!1}=T,Q=G===void 0?XT:G;if(!Number.isInteger(Q)||Q<1||Q>YT)throw Error("Session catalog limit must be an integer from 1 to 100");return{descriptor:$,exactIdentity:$?.exactIdentity??null,cursor:_??void 0,limit:Q,includeSubagents:X,archived:Y}}function d_(T={}){let $=_T(T.taskStatus,W$,"task status"),_=_T(T.taskPriority,K$,"task priority"),G=GT(T.taskDueAfter,"taskDueAfter"),X=GT(T.taskDueBefore,"taskDueBefore");return f$(G,X),{...$?{taskStatuses:$}:{},..._?{taskPriorities:_}:{},...G?{taskDueAfter:G}:{},...X?{taskDueBefore:X}:{}}}function _T(T,$,_){if(T===void 0)return;let G=Array.isArray(T)?T:[T];if(G.length===0)return;let X=new Set;for(let Y of G){if(typeof Y!=="string"||!$.has(Y))throw Error(`Invalid session ${_} filter`);X.add(Y)}return[...X].sort()}function GT(T,$){if(T===void 0)return;if(typeof T!=="string"||!Number.isFinite(Date.parse(T)))throw Error(`Invalid session ${$} filter`);return new Date(T).toISOString()}function f$(T,$){if(T!==void 0&&$!==void 0&&T>$)throw Error("Session task due range is inverted")}function R$(T,$){if(T.lastMessageTime>$.lastMessageTime)return-1;if(T.lastMessageTime<$.lastMessageTime)return 1;if(T.projectPath<$.projectPath)return-1;if(T.projectPath>$.projectPath)return 1;if(T.sessionId<$.sessionId)return-1;if(T.sessionId>$.sessionId)return 1;return 0}function b$(T,$){if(T.lastMessageTime>$.lastMessageTime)return-1;if(T.lastMessageTime<$.lastMessageTime)return 1;if(T.workspaceIdentity<$.workspaceIdentity)return-1;if(T.workspaceIdentity>$.workspaceIdentity)return 1;if(T.sessionId<$.sessionId)return-1;if(T.sessionId>$.sessionId)return 1;return 0}function s_(T,$){let _=[...T],G=w$($);if(G)_=_.filter((Q)=>R$(Q,{sessionId:G.sessionId,projectPath:G.projectPath,lastMessageTime:G.lastMessageTime})>0);let X=_.slice(0,$.limit);if(X.length===0||_.length<=X.length)return{sessions:X};let Y=X[X.length-1];return{sessions:X,nextCursor:x$({version:1,kind:"local",cwd:$.cwd,includeSubagents:$.includeSubagents,archived:$.archived,lastMessageTime:Y.lastMessageTime,projectPath:Y.projectPath,sessionId:Y.sessionId})}}function a_(T,$){let _=[...T],G=S$($);if(G)_=_.filter((Q)=>b$(Q,{sessionId:G.sessionId,projectPath:Q.projectPath,lastMessageTime:G.lastMessageTime,workspaceIdentity:G.workspaceIdentity})>0);let X=_.slice(0,$.limit);if(X.length===0||_.length<=X.length)return{sessions:X};let Y=X[X.length-1];return{sessions:X,nextCursor:E$({version:1,kind:"remote",exactIdentity:$.exactIdentity,includeSubagents:$.includeSubagents,archived:$.archived,lastMessageTime:Y.lastMessageTime,workspaceIdentity:Y.workspaceIdentity,sessionId:Y.sessionId})}}function y$(T){return T.type==="message_created"||T.type==="token_budget_handoff_recorded"||T.type==="part_created"||T.type==="part_updated"||T.type==="turn_started"||T.type==="turn_completed"||T.type==="turn_aborted"||T.type==="turn_recovery_acknowledged"||T.type==="interaction_requested"||T.type==="interaction_responded"||T.type==="interaction_recovered"||T.type==="review_started"||T.type==="review_completed"}function F0(T){return T.type==="message_created"&&T.data.role==="user"&&(T.data.inboxMessageId!==void 0||T.data.parentMessageId===void 0)}function L0(T,$){let _=T.find((G)=>F0(G)&&G.data.messageId===$);if(!_)throw Error(`Rewind checkpoint not found: ${$}`);return{messageId:$,preview:UT(T,$),createdAt:_.data.createdAt}}function UT(T,$){let _=T.flatMap((G)=>{if(G.type!=="part_created"||G.data.messageId!==$)return[];if(G.data.partType==="text"){let X=G.data.payload;return typeof X.text==="string"?[X.text]:[]}if(G.data.partType==="image")return["[Image]"];return[]}).join("").trim();if(_.length<=160)return _;return`${_.slice(0,160)}...`}function VT(T,$){L0(T,$);let _=T.findIndex((Q)=>Q.type==="message_created"&&Q.data.messageId===$),G=T[_],X=G?.type==="message_created"?G.data.inboxMessageId:void 0,Y=new Set(T.flatMap((Q)=>Q.type==="turn_started"&&X&&Q.data.inputMessageIds?.includes(X)?[Q.data.turnId]:[]));return T.filter((Q,Z)=>{if((Q.type==="turn_started"||Q.type==="turn_completed"||Q.type==="turn_aborted"||Q.type==="turn_recovery_acknowledged")&&Y.has(Q.data.turnId))return!1;return Z<_||!y$(Q)})}function l(T){let $=[];for(let _ of T){if(_.type!=="session_rewound"){$.push(_);continue}if(L0($,_.data.targetMessageId),_.data.mode!=="code")$=VT($,_.data.targetMessageId)}return $}function o_(T){let $=l(T);return $.filter(F0).map((_)=>({messageId:_.data.messageId,preview:UT($,_.data.messageId),createdAt:_.data.createdAt})).reverse()}function r_(T,$){let _=l(T),G=L0(_,$),X=_.findIndex((Q)=>Q.type==="message_created"&&Q.data.messageId===$),Y=_.slice(X);return{checkpoint:G,projectedEntries:VT(_,$),removedTurns:Y.filter(F0).length,snapshotMessageIds:Y.flatMap((Q)=>Q.type==="part_created"&&Q.data.partType==="tool_call"?[Q.data.partId]:[])}}import{createHash as s$}from"node:crypto";var T1={clientVisible:!1};function BT(T){if(T.metadata&&typeof T.metadata==="object"&&!Array.isArray(T.metadata)&&T.metadata.clientVisible===!1)return!1;return!(T.role==="user"&&typeof T.content==="string"&&T.content.startsWith("This turn made a non-trivial implementation. Before finishing, call Task ")&&T.content.endsWith("Only a fresh structured PASS verdict allows completion."))}import{StringDecoder as m$}from"node:string_decoder";var _1=1048576;function J0(T,$){let _=$;while(_<T.length&&(T[_]&192)===128)_+=1;return _}class I0{maxBytes;chunks=[];retainedBytes=0;omittedBytes=0;totalBytes=0;constructor(T=1048576){this.maxBytes=T;if(!Number.isSafeInteger(T)||T<=0)throw Error("maxBytes must be a positive safe integer")}append(T){let $=Buffer.isBuffer(T)?T:Buffer.from(T);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 T=this.peek();return this.chunks.length=0,this.retainedBytes=0,this.omittedBytes=0,T}retainedChunkCountForTests(){return this.chunks.length}retainOversizedChunkTail(T){this.omittedBytes+=this.retainedBytes,this.chunks.length=0,this.retainedBytes=0;let $=J0(T,T.length-this.maxBytes);if(this.omittedBytes+=$,$===T.length)return;let _=Buffer.from(T.subarray($));this.chunks.push(_),this.retainedBytes=_.length}trimToLimit(){let T=!1;while(this.retainedBytes>this.maxBytes){let $=this.chunks[0];if(!$)return;let _=this.retainedBytes-this.maxBytes;if($.length<=_){this.chunks.shift(),this.retainedBytes-=$.length,this.omittedBytes+=$.length,T=!0;continue}let G=J0($,_);this.chunks[0]=$.subarray(G),this.retainedBytes-=G,this.omittedBytes+=G,T=!0}if(T)this.realignRetainedStart()}realignRetainedStart(){while(this.chunks.length>0){let T=this.chunks[0];if(T.length===0){this.chunks.shift();continue}let $=J0(T,0);if($===0)return;if(this.retainedBytes-=$,this.omittedBytes+=$,$===T.length)this.chunks.shift();else{this.chunks[0]=T.subarray($);return}}}compactChunks(){if(this.chunks.length<=32)return;let T=Buffer.concat(this.chunks,this.retainedBytes);if(this.chunks.length=0,T.length>0)this.chunks.push(T)}}var _0={maxLines:30,maxChars:3000,keepHead:10,keepTail:10,summarize:!0},y={maxLines:100,maxChars:1e4,keepHead:40,keepTail:40,summarize:!0},gT={maxLines:200,maxChars:20000,keepHead:80,keepTail:80,summarize:!1},h$={maxLines:150,maxChars:15000,keepHead:50,keepTail:50,summarize:!0},P$=[{pattern:/^git\s+(rm|add)\s+(-r|--cached|-rf|-f)?\s*/i,config:_0,summaryTemplate:(T)=>`Successfully processed ${T} files`},{pattern:/^(npm|pnpm|yarn|bun)\s+(install|i|add|remove|uninstall)/i,config:_0,summaryTemplate:(T)=>`Package operation completed (${T} lines of output)`},{pattern:/^(npm|pnpm|yarn|bun)\s+(run|exec)\s+(build|compile|bundle)/i,config:y,summaryTemplate:(T)=>`Build completed (${T} lines of output)`},{pattern:/^(npm|pnpm|yarn|bun)\s+(run|exec)\s+(test|lint|check)/i,config:gT},{pattern:/^git\s+(status|branch|remote)/i,config:y},{pattern:/^git\s+(log|diff|show)/i,config:gT},{pattern:/^(ls|dir|tree)\s+/i,config:y,summaryTemplate:(T)=>`Listed ${T} items`},{pattern:/^find\s+/i,config:y,summaryTemplate:(T)=>`Found ${T} matches`},{pattern:/^(grep|rg|ag)\s+/i,config:y,summaryTemplate:(T)=>`Found ${T} matching lines`},{pattern:/^(docker|podman)\s+(build|pull|push)/i,config:_0,summaryTemplate:(T)=>`Docker operation completed (${T} lines)`},{pattern:/^(pip|pip3|poetry|pipenv)\s+(install|uninstall)/i,config:_0,summaryTemplate:(T)=>`Python package operation completed (${T} lines)`},{pattern:/^(cargo|rustup)\s+(build|install|update)/i,config:y,summaryTemplate:(T)=>`Rust operation completed (${T} lines)`},{pattern:/^(go)\s+(build|get|mod)/i,config:y,summaryTemplate:(T)=>`Go operation completed (${T} lines)`}];function CT(T,$,_){let G=$,X=_??T.length;if(G>0){let Y=T.charCodeAt(G);if(Y>=56320&&Y<=57343)G+=1}if(X<T.length){let Y=T.charCodeAt(X-1);if(Y>=55296&&Y<=56319)X-=1}return T.slice(G,X)}class N0{static getConfigForCommand(T){for(let{pattern:$,config:_,summaryTemplate:G}of P$)if($.test(T))return{config:_,summaryTemplate:G};return{config:h$}}static truncate(T,$){let{config:_,summaryTemplate:G}=this.getConfigForCommand($);return this.truncateWithConfig(T,_,G)}static truncateWithConfig(T,$,_){let G=T.length,X=T.split(`
1
+ import{gf as P0,hf as PT}from"./chunk-fx9vm1n5.js";import{Ch as FT}from"./chunk-28tzj187.js";import{Cj as hT}from"./chunk-5q4z0sfr.js";import{Bk as h0,Ck as e,Kk as yT,ek as g0,mk as D,ok as S,pk as s,rk as a,sk as D0,tk as fT,uk as bT,vk as RT,zk as A}from"./chunk-7xtxvrh8.js";import{Lk as H0}from"./chunk-sdapqhj0.js";import{createHash as N_}from"node:crypto";import{readdir as w0,stat as S0}from"node:fs/promises";import B0 from"node:path";import{createHash as eT,randomBytes as n0}from"node:crypto";import{chmod as i0,link as T$,lstat as R,mkdir as $$,open as i,readdir as c0,realpath as _$,unlink as O0}from"node:fs/promises";import j from"node:path";function aT(){return typeof globalThis.Bun<"u"}function oT(T){return{exec:($)=>T.exec($),prepare:($)=>{let _=T.prepare($);return{run:(...G)=>{_.run(...G)},get:(...G)=>_.get(...G),all:(...G)=>_.all(...G)}},transaction:($)=>T.transaction($)(),pragma:($)=>T.pragma($,{simple:!0}),close:()=>T.close()}}function tT(T){return{exec:($)=>T.exec($),prepare:($)=>{let _=T.query($);return{run:(...G)=>{_.run(...G)},get:(...G)=>_.get(...G),all:(...G)=>_.all(...G)}},transaction:($)=>T.transaction($)(),pragma:($)=>{let _=T.query(`PRAGMA ${$}`).get();if(!_)return;let G=Object.values(_);return G.length===1?G[0]:_},close:()=>T.close()}}function rT(T){return[`PRAGMA busy_timeout=${T};`,"PRAGMA journal_mode=WAL;","PRAGMA synchronous=NORMAL;","PRAGMA foreign_keys=ON;"].join(`
2
+ `)}async function $0(T,$={}){let _=$.busyTimeoutMs??5000;if(!Number.isSafeInteger(_)||_<0)return null;let G=null;try{if(aT()){let{Database:Y}=await import("bun:sqlite");G=tT(new Y(T))}else{let Q=(await import("better-sqlite3")).default;G=oT(new Q(T))}return G.exec(rT(_)),G}catch{try{G?.close()}catch{}return null}}var G$="surface-workspaces-v1",d0=/^[a-f0-9]{64}$/,X$=/^acp-remote-workspace:[A-Za-z0-9_-]{43}$/,Y$=1024,Q$=".surface-workspaces-v1.capacity.sqlite",s0=/^\.tmp-acp-remote-workspace-([1-9][0-9]*)-[a-f0-9]{32}\.pending$/;class H extends Error{name="AcpRemoteWorkspaceReferenceError";code;retryable;constructor(T){let $=T==="session_surface_not_found"?{message:"Session surface was not found",retryable:!1}:T==="session_surface_capacity"?{message:"Session surface capacity is exhausted",retryable:!0}:{message:"Session surface state is invalid",retryable:!1};super($.message);this.code=T,this.retryable=$.retryable,Object.setPrototypeOf(this,new.target.prototype)}}var y,_0=new Map;function a0(T){return j.join(String(T),G$)}async function o0(T,$){let _=S($);if(s(_.collisionIdentity)!==String(T))throw new H("session_surface_state_invalid");let G=r0(_.exactIdentity),X=a0(T);return await U$(T,X),Z$(X,()=>V$(X,async()=>{await H$(X);let Y=await t0(T,X,!0),Q=Y.recordsByDigest.get(G);if(Q)return Q.workspaceRef;if(Y.recordsByDigest.size>=Y$)throw new H("session_surface_capacity");let Z=j.join(X,`${G}.json`),U=new Set(Y.workspaceRefToDigest.keys());for(let V=0;V<32;V+=1){let g=L$();if(U.has(g))continue;return I$(T,X,Z,_,{version:1,exactIdentityDigest:G,workspaceRef:g})}throw new H("session_surface_state_invalid")}))}async function Z$(T,$){let _=_0.get(T)??Promise.resolve(),G=()=>{return},X=new Promise((Q)=>{G=Q}),Y=_.catch(()=>{return}).then(()=>X);_0.set(T,Y),await _.catch(()=>{return});try{return await $()}finally{if(G(),_0.get(T)===Y)_0.delete(T)}}async function U$(T,$){try{await M0($,String(T))}catch(_){if(q(_)!=="ENOENT"){if(_ instanceof H)throw _;throw new H("session_surface_state_invalid")}try{await $$($,{recursive:!1,mode:448})}catch(G){if(q(G)!=="EEXIST")throw new H("session_surface_state_invalid")}await M0($,String(T)),await u(String(T))}}async function V$(T,$){await y?.beforeCapacityLockAttempt?.();let _=await B$(T),G=!1,X,Y,Q;try{_.database.exec("BEGIN IMMEDIATE;"),G=!0,await y?.afterCapacityLockAcquired?.(),Q={value:await $()}}catch(Z){X=Z}if(G)try{await g$(_),_.database.exec("ROLLBACK;")}catch(Z){Y=Z}try{_.database.close()}catch(Z){if(!G)Y=Z}if(await _.identityHandle.close().catch(()=>{return}),Y!==void 0)throw new H("session_surface_state_invalid");if(X instanceof H)throw X;if(X!==void 0||!Q)throw new H("session_surface_state_invalid");return Q.value}async function B$(T){let $=j.join(T,Q$),_=null,G;try{let X=!1;try{let Q=await i($,"wx",384);X=!0,await Q.sync(),await Q.close()}catch(Q){if(q(Q)!=="EEXIST")throw Q}if(await p($,T),X)await u(T);G=await i($,"r"),await c(G,$,T);let Y=await G.stat({bigint:!0});if(_=await $0($,{busyTimeoutMs:30000}),!_)throw new H("session_surface_state_invalid");if(_.exec("PRAGMA locking_mode=NORMAL;"),_.exec("PRAGMA synchronous=FULL;"),_.exec("PRAGMA busy_timeout=30000;"),process.platform!=="win32")await i0($,384);return await c(G,$,T),await C$($,T),{database:_,identity:Y,identityHandle:G,path:$}}catch(X){await G?.close().catch(()=>{return});try{_?.close()}catch{}if(X instanceof H)throw X;throw new H("session_surface_state_invalid")}}async function g$(T){await c(T.identityHandle,T.path,j.dirname(T.path));let $=await T.identityHandle.stat({bigint:!0});if(!d(T.identity,$))throw new H("session_surface_state_invalid")}async function C$(T,$){for(let _ of["-journal","-shm","-wal"]){let G=`${T}${_}`;try{if(process.platform!=="win32")await i0(G,384);await p(G,$)}catch(X){if(q(X)!=="ENOENT"){if(X instanceof H)throw X;throw new H("session_surface_state_invalid")}}}}async function H$(T){let $=await c0(T,{withFileTypes:!0}),_=!1;for(let G of $){if(!s0.test(G.name))continue;let X=j.join(T,G.name);await p(X,T),await O0(X),_=!0}if(_)await u(T)}async function t0(T,$,_){try{await M0($,String(T))}catch(Q){if(!_&&q(Q)==="ENOENT")return{recordsByDigest:new Map,workspaceRefToDigest:new Map};if(Q instanceof H)throw Q;throw new H("session_surface_state_invalid")}let G;try{G=await c0($,{withFileTypes:!0})}catch(Q){if(!_&&q(Q)==="ENOENT")return{recordsByDigest:new Map,workspaceRefToDigest:new Map};throw new H("session_surface_state_invalid")}let X=new Map,Y=new Map;for(let Q of G){if(s0.test(Q.name)){await p(j.join($,Q.name),$);continue}if(!Q.name.endsWith(".json"))continue;let Z=j.basename(Q.name,".json");if(!d0.test(Z))throw new H("session_surface_state_invalid");let U=j.join($,Q.name),V=await O$(U,$);if(V.exactIdentityDigest!==Z)throw new H("session_surface_state_invalid");if(X.has(Z))throw new H("session_surface_state_invalid");let g=Y.get(V.workspaceRef);if(g&&g!==Z)throw new H("session_surface_state_invalid");X.set(Z,V),Y.set(V.workspaceRef,Z)}return{recordsByDigest:X,workspaceRefToDigest:Y}}async function O$(T,$){let _;try{await p(T,$),_=await i(T,"r"),await c(_,T,$);let G=await _.readFile({encoding:"utf8"});return M$(G)}catch(G){if(G instanceof H&&G.code==="session_surface_not_found")throw G;if(q(G)==="ENOENT")throw new H("session_surface_not_found");throw new H("session_surface_state_invalid")}finally{await _?.close()}}function M$(T){let $;try{$=JSON.parse(T)}catch{throw new H("session_surface_state_invalid")}if(!F$($))throw new H("session_surface_state_invalid");return $}function F$(T){if(!T||typeof T!=="object"||Array.isArray(T))return!1;let $=T,_=Object.keys($).sort();if(_.length!==3||_[0]!=="exactIdentityDigest"||_[1]!=="version"||_[2]!=="workspaceRef")return!1;return $.version===1&&typeof $.exactIdentityDigest==="string"&&d0.test($.exactIdentityDigest)&&typeof $.workspaceRef==="string"&&X$.test($.workspaceRef)}function r0(T){return eT("sha256").update(`acp-remote-workspace-exact-identity\x00${T}`).digest("hex")}function L$(){return`acp-remote-workspace:${n0(32).toString("base64url")}`}function J$(){return`.tmp-acp-remote-workspace-${process.pid}-${n0(16).toString("hex")}.pending`}async function M0(T,$){if(j.dirname(T)!==$)throw new H("session_surface_state_invalid");let _=await R(T);if(_.isSymbolicLink()||!_.isDirectory())throw new H("session_surface_state_invalid");if(typeof process.getuid==="function"&&_.uid!==process.getuid())throw new H("session_surface_state_invalid");let G=G0(_.mode);if(process.platform!=="win32"&&G!==448)throw new H("session_surface_state_invalid");await F0(T,$,j.basename(T))}async function p(T,$){if(j.dirname(T)!==$)throw new H("session_surface_state_invalid");let _=await R(T);if(_.isSymbolicLink()||!_.isFile())throw new H("session_surface_state_invalid");if(typeof process.getuid==="function"&&_.uid!==process.getuid())throw new H("session_surface_state_invalid");let G=G0(_.mode);if(process.platform!=="win32"&&G!==384)throw new H("session_surface_state_invalid");await F0(T,$,j.basename(T),_)}async function c(T,$,_){let[G,X]=await Promise.all([T.stat({bigint:!0}),R($,{bigint:!0})]);if(j.dirname($)!==_||X.isSymbolicLink()||!X.isFile()||!G.isFile()||X.dev!==G.dev||X.ino!==G.ino)throw new H("session_surface_state_invalid");if(typeof process.getuid==="function"&&(Number(X.uid)!==process.getuid()||Number(G.uid)!==process.getuid()))throw new H("session_surface_state_invalid");let Y=Number(X.mode&BigInt(511)),Q=Number(G.mode&BigInt(511));if(process.platform!=="win32"&&(Y!==384||Q!==384))throw new H("session_surface_state_invalid");await F0($,_,j.basename($),G)}async function F0(T,$,_,G){let X=y?.realpath??_$,Y=await X(T),Q=await X($);if(Y===j.join(Q,_))return;if(G&&j.dirname(Y)===Q){let[Z,U]=await Promise.all([R(T,{bigint:!0}),R(Y,{bigint:!0})]);if(Z.isFile()&&!Z.isSymbolicLink()&&U.isFile()&&!U.isSymbolicLink()&&d(G,Z)&&d(Z,U)&&(typeof process.getuid!=="function"||Number(Z.uid)===process.getuid()&&Number(U.uid)===process.getuid())&&(process.platform==="win32"||G0(Z.mode)===384&&G0(U.mode)===384))return}throw new H("session_surface_state_invalid")}async function u(T){if(!N$(process.platform))return;try{if(y?.syncDirectory){await y.syncDirectory(T);return}await z$(T)}catch{throw new H("session_surface_state_invalid")}}function N$(T){return T!=="win32"}async function z$(T){let $=await i(T,"r");try{await $.sync()}finally{await $.close()}}async function I$(T,$,_,G,X){let Y=j.join($,J$()),Q,Z,U=!1,V=!1,g,O;try{Q=await i(Y,"wx",384),await Q.writeFile(JSON.stringify(X),"utf8"),await Q.sync(),await c(Q,Y,$),Z=await Q.stat({bigint:!0}),await Q.close(),Q=void 0,await y?.beforePublish?.({finalPath:_,referenceDirectoryPath:$,tempPath:Y});try{await T$(Y,_),U=!0}catch(M){if(q(M)!=="EEXIST")throw M;g=await j$(T,G)}if(U){let M=await R(_,{bigint:!0});if(!Z||!d(Z,M))throw new H("session_surface_state_invalid");await p(_,$),await u($),V=!0,g=X.workspaceRef;try{await y?.afterPublish?.({finalPath:_,referenceDirectoryPath:$,tempPath:Y})}catch{}}}catch(M){O=M}finally{await Q?.close().catch(()=>{return})}if(O!==void 0&&U&&!V&&Z)try{let M=await R(_,{bigint:!0});if(d(Z,M))await O0(_),await u($)}catch{}try{if(await O0(Y),!V)await u($)}catch(M){if(q(M)!=="ENOENT"&&O===void 0&&!V)O=M}if(O instanceof H)throw O;if(O!==void 0||g===void 0)throw new H("session_surface_state_invalid");return g}async function j$(T,$){let _=a0(T),G=await t0(T,_,!0),X=r0(S($).exactIdentity),Y=G.recordsByDigest.get(X);if(!Y)throw new H("session_surface_state_invalid");return Y.workspaceRef}function d(T,$){return BigInt(T.dev)===BigInt($.dev)&&BigInt(T.ino)===BigInt($.ino)}function q(T){return T!==null&&typeof T==="object"&&"code"in T&&typeof T.code==="string"?T.code:void 0}function G0(T){return typeof T==="bigint"?Number(T&BigInt(511)):T&511}import*as h from"node:path";var GT=50,XT=100,W$=new Set(["queued","running","completed","failed","cancelled","interrupted"]),K$=new Set(["high","medium","low"]),YT=/^[A-Za-z0-9_-]+$/,k$=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?(?:Z|[+-]\d{2}:\d{2})$/,A$=/^acp-remote-exact-path:[a-f0-9]{64}$/;function QT(T){return typeof T==="string"&&k$.test(T)&&Number.isFinite(Date.parse(T))}function e0(T){return typeof T==="string"&&h.isAbsolute(T)}function TT(T){return typeof T==="string"&&A$.test(T)}function x$(T){return Buffer.from(JSON.stringify(T),"utf8").toString("base64url")}function E$(T){return Buffer.from(JSON.stringify(T),"utf8").toString("base64url")}function q$(T){try{if(!YT.test(T))throw Error("invalid");let $=Buffer.from(T,"base64url").toString("utf8");if(Buffer.from($,"utf8").toString("base64url")!==T)throw Error("invalid");let _=JSON.parse($);if(_.version!==1||_.kind!==void 0&&_.kind!=="local"||typeof _.includeSubagents!=="boolean"||_.archived!==void 0&&typeof _.archived!=="boolean"||!(_.cwd===null||e0(_.cwd))||!QT(_.lastMessageTime)||!e0(_.projectPath)||!A(_.sessionId))throw Error("invalid");return{version:1,kind:"local",cwd:_.cwd===null?null:h.resolve(_.cwd),includeSubagents:_.includeSubagents,archived:_.archived??!1,lastMessageTime:_.lastMessageTime,projectPath:h.resolve(_.projectPath),sessionId:_.sessionId}}catch{throw Error("Invalid session cursor")}}function D$(T){try{if(!YT.test(T))throw Error("invalid");let $=Buffer.from(T,"base64url").toString("utf8");if(Buffer.from($,"utf8").toString("base64url")!==T)throw Error("invalid");let _=JSON.parse($),G=Object.keys(_),X=new Set(["version","kind","exactIdentity","includeSubagents","archived","lastMessageTime","workspaceIdentity","sessionId"]);if(G.some((Y)=>!X.has(Y))||_.version!==1||_.kind!=="remote"||typeof _.includeSubagents!=="boolean"||typeof _.archived!=="boolean"||!(_.exactIdentity===null||TT(_.exactIdentity))||!QT(_.lastMessageTime)||!TT(_.workspaceIdentity)||!A(_.sessionId))throw Error("invalid");return{version:1,kind:"remote",exactIdentity:_.exactIdentity??null,includeSubagents:_.includeSubagents,archived:_.archived,lastMessageTime:_.lastMessageTime,workspaceIdentity:_.workspaceIdentity,sessionId:_.sessionId}}catch{throw Error("Invalid remote session cursor")}}function l(T){let $="";for(let _=0;_<T.length;_+=1)$+=T.charCodeAt(_).toString(16).padStart(4,"0");return $}function w$(T){if(!T.cursor)return;let $=q$(T.cursor);if($.cwd!==T.cwd||$.includeSubagents!==T.includeSubagents||($.archived??!1)!==T.archived)throw Error("Session cursor scope does not match this query");return $}function S$(T){if(!T.cursor)return;let $=D$(T.cursor);if($.exactIdentity!==T.exactIdentity||T.exactIdentity!==null&&$.workspaceIdentity!==T.exactIdentity||$.includeSubagents!==T.includeSubagents||($.archived??!1)!==T.archived)throw Error("Remote session cursor scope does not match this query");return $}function i_(T={}){let{cwd:$,cursor:_,limit:G,includeSubagents:X=!1,archived:Y=!1}=T;if($!==void 0&&!h.isAbsolute($))throw Error("Session catalog cwd must be absolute");let Q=G===void 0?GT:G;if(!Number.isInteger(Q)||Q<1||Q>XT)throw Error("Session catalog limit must be an integer from 1 to 100");return{cwd:$===void 0?null:h.resolve($),cursor:_??void 0,limit:Q,includeSubagents:X,archived:Y}}function c_(T={}){let{descriptor:$,cursor:_,limit:G,includeSubagents:X=!1,archived:Y=!1}=T,Q=G===void 0?GT:G;if(!Number.isInteger(Q)||Q<1||Q>XT)throw Error("Session catalog limit must be an integer from 1 to 100");return{descriptor:$,exactIdentity:$?.exactIdentity??null,cursor:_??void 0,limit:Q,includeSubagents:X,archived:Y}}function d_(T={}){let $=$T(T.taskStatus,W$,"task status"),_=$T(T.taskPriority,K$,"task priority"),G=_T(T.taskDueAfter,"taskDueAfter"),X=_T(T.taskDueBefore,"taskDueBefore");return f$(G,X),{...$?{taskStatuses:$}:{},..._?{taskPriorities:_}:{},...G?{taskDueAfter:G}:{},...X?{taskDueBefore:X}:{}}}function $T(T,$,_){if(T===void 0)return;let G=Array.isArray(T)?T:[T];if(G.length===0)return;let X=new Set;for(let Y of G){if(typeof Y!=="string"||!$.has(Y))throw Error(`Invalid session ${_} filter`);X.add(Y)}return[...X].sort()}function _T(T,$){if(T===void 0)return;if(typeof T!=="string"||!Number.isFinite(Date.parse(T)))throw Error(`Invalid session ${$} filter`);return new Date(T).toISOString()}function f$(T,$){if(T!==void 0&&$!==void 0&&T>$)throw Error("Session task due range is inverted")}function b$(T,$){if(T.lastMessageTime>$.lastMessageTime)return-1;if(T.lastMessageTime<$.lastMessageTime)return 1;if(T.projectPath<$.projectPath)return-1;if(T.projectPath>$.projectPath)return 1;if(T.sessionId<$.sessionId)return-1;if(T.sessionId>$.sessionId)return 1;return 0}function R$(T,$){if(T.lastMessageTime>$.lastMessageTime)return-1;if(T.lastMessageTime<$.lastMessageTime)return 1;if(T.workspaceIdentity<$.workspaceIdentity)return-1;if(T.workspaceIdentity>$.workspaceIdentity)return 1;if(T.sessionId<$.sessionId)return-1;if(T.sessionId>$.sessionId)return 1;return 0}function s_(T,$){let _=[...T],G=w$($);if(G)_=_.filter((Q)=>b$(Q,{sessionId:G.sessionId,projectPath:G.projectPath,lastMessageTime:G.lastMessageTime})>0);let X=_.slice(0,$.limit);if(X.length===0||_.length<=X.length)return{sessions:X};let Y=X[X.length-1];return{sessions:X,nextCursor:x$({version:1,kind:"local",cwd:$.cwd,includeSubagents:$.includeSubagents,archived:$.archived,lastMessageTime:Y.lastMessageTime,projectPath:Y.projectPath,sessionId:Y.sessionId})}}function a_(T,$){let _=[...T],G=S$($);if(G)_=_.filter((Q)=>R$(Q,{sessionId:G.sessionId,projectPath:Q.projectPath,lastMessageTime:G.lastMessageTime,workspaceIdentity:G.workspaceIdentity})>0);let X=_.slice(0,$.limit);if(X.length===0||_.length<=X.length)return{sessions:X};let Y=X[X.length-1];return{sessions:X,nextCursor:E$({version:1,kind:"remote",exactIdentity:$.exactIdentity,includeSubagents:$.includeSubagents,archived:$.archived,lastMessageTime:Y.lastMessageTime,workspaceIdentity:Y.workspaceIdentity,sessionId:Y.sessionId})}}function y$(T){return T.type==="message_created"||T.type==="token_budget_handoff_recorded"||T.type==="part_created"||T.type==="part_updated"||T.type==="turn_started"||T.type==="turn_completed"||T.type==="turn_aborted"||T.type==="turn_recovery_acknowledged"||T.type==="interaction_requested"||T.type==="interaction_responded"||T.type==="interaction_recovered"||T.type==="review_started"||T.type==="review_completed"}function L0(T){return T.type==="message_created"&&T.data.role==="user"&&(T.data.inboxMessageId!==void 0||T.data.parentMessageId===void 0)}function J0(T,$){let _=T.find((G)=>L0(G)&&G.data.messageId===$);if(!_)throw Error(`Rewind checkpoint not found: ${$}`);return{messageId:$,preview:ZT(T,$),createdAt:_.data.createdAt}}function ZT(T,$){let _=T.flatMap((G)=>{if(G.type!=="part_created"||G.data.messageId!==$)return[];if(G.data.partType==="text"){let X=G.data.payload;return typeof X.text==="string"?[X.text]:[]}if(G.data.partType==="image")return["[Image]"];return[]}).join("").trim();if(_.length<=160)return _;return`${_.slice(0,160)}...`}function UT(T,$){J0(T,$);let _=T.findIndex((Q)=>Q.type==="message_created"&&Q.data.messageId===$),G=T[_],X=G?.type==="message_created"?G.data.inboxMessageId:void 0,Y=new Set(T.flatMap((Q)=>Q.type==="turn_started"&&X&&Q.data.inputMessageIds?.includes(X)?[Q.data.turnId]:[]));return T.filter((Q,Z)=>{if((Q.type==="turn_started"||Q.type==="turn_completed"||Q.type==="turn_aborted"||Q.type==="turn_recovery_acknowledged")&&Y.has(Q.data.turnId))return!1;return Z<_||!y$(Q)})}function n(T){let $=[];for(let _ of T){if(_.type!=="session_rewound"){$.push(_);continue}if(J0($,_.data.targetMessageId),_.data.mode!=="code")$=UT($,_.data.targetMessageId)}return $}function t_(T){let $=n(T);return $.filter(L0).map((_)=>({messageId:_.data.messageId,preview:ZT($,_.data.messageId),createdAt:_.data.createdAt})).reverse()}function r_(T,$){let _=n(T),G=J0(_,$),X=_.findIndex((Q)=>Q.type==="message_created"&&Q.data.messageId===$),Y=_.slice(X);return{checkpoint:G,projectedEntries:UT(_,$),removedTurns:Y.filter(L0).length,snapshotMessageIds:Y.flatMap((Q)=>Q.type==="part_created"&&Q.data.partType==="tool_call"?[Q.data.partId]:[])}}import{createHash as s$}from"node:crypto";var T1={clientVisible:!1};function VT(T){if(T.metadata&&typeof T.metadata==="object"&&!Array.isArray(T.metadata)&&T.metadata.clientVisible===!1)return!1;return!(T.role==="user"&&typeof T.content==="string"&&T.content.startsWith("This turn made a non-trivial implementation. Before finishing, call Task ")&&T.content.endsWith("Only a fresh structured PASS verdict allows completion."))}import{StringDecoder as m$}from"node:string_decoder";var _1=1048576;function N0(T,$){let _=$;while(_<T.length&&(T[_]&192)===128)_+=1;return _}class z0{maxBytes;chunks=[];retainedBytes=0;omittedBytes=0;totalBytes=0;constructor(T=1048576){this.maxBytes=T;if(!Number.isSafeInteger(T)||T<=0)throw Error("maxBytes must be a positive safe integer")}append(T){let $=Buffer.isBuffer(T)?T:Buffer.from(T);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 T=this.peek();return this.chunks.length=0,this.retainedBytes=0,this.omittedBytes=0,T}retainedChunkCountForTests(){return this.chunks.length}retainOversizedChunkTail(T){this.omittedBytes+=this.retainedBytes,this.chunks.length=0,this.retainedBytes=0;let $=N0(T,T.length-this.maxBytes);if(this.omittedBytes+=$,$===T.length)return;let _=Buffer.from(T.subarray($));this.chunks.push(_),this.retainedBytes=_.length}trimToLimit(){let T=!1;while(this.retainedBytes>this.maxBytes){let $=this.chunks[0];if(!$)return;let _=this.retainedBytes-this.maxBytes;if($.length<=_){this.chunks.shift(),this.retainedBytes-=$.length,this.omittedBytes+=$.length,T=!0;continue}let G=N0($,_);this.chunks[0]=$.subarray(G),this.retainedBytes-=G,this.omittedBytes+=G,T=!0}if(T)this.realignRetainedStart()}realignRetainedStart(){while(this.chunks.length>0){let T=this.chunks[0];if(T.length===0){this.chunks.shift();continue}let $=N0(T,0);if($===0)return;if(this.retainedBytes-=$,this.omittedBytes+=$,$===T.length)this.chunks.shift();else{this.chunks[0]=T.subarray($);return}}}compactChunks(){if(this.chunks.length<=32)return;let T=Buffer.concat(this.chunks,this.retainedBytes);if(this.chunks.length=0,T.length>0)this.chunks.push(T)}}var X0={maxLines:30,maxChars:3000,keepHead:10,keepTail:10,summarize:!0},P={maxLines:100,maxChars:1e4,keepHead:40,keepTail:40,summarize:!0},BT={maxLines:200,maxChars:20000,keepHead:80,keepTail:80,summarize:!1},h$={maxLines:150,maxChars:15000,keepHead:50,keepTail:50,summarize:!0},P$=[{pattern:/^git\s+(rm|add)\s+(-r|--cached|-rf|-f)?\s*/i,config:X0,summaryTemplate:(T)=>`Successfully processed ${T} files`},{pattern:/^(npm|pnpm|yarn|bun)\s+(install|i|add|remove|uninstall)/i,config:X0,summaryTemplate:(T)=>`Package operation completed (${T} lines of output)`},{pattern:/^(npm|pnpm|yarn|bun)\s+(run|exec)\s+(build|compile|bundle)/i,config:P,summaryTemplate:(T)=>`Build completed (${T} lines of output)`},{pattern:/^(npm|pnpm|yarn|bun)\s+(run|exec)\s+(test|lint|check)/i,config:BT},{pattern:/^git\s+(status|branch|remote)/i,config:P},{pattern:/^git\s+(log|diff|show)/i,config:BT},{pattern:/^(ls|dir|tree)\s+/i,config:P,summaryTemplate:(T)=>`Listed ${T} items`},{pattern:/^find\s+/i,config:P,summaryTemplate:(T)=>`Found ${T} matches`},{pattern:/^(grep|rg|ag)\s+/i,config:P,summaryTemplate:(T)=>`Found ${T} matching lines`},{pattern:/^(docker|podman)\s+(build|pull|push)/i,config:X0,summaryTemplate:(T)=>`Docker operation completed (${T} lines)`},{pattern:/^(pip|pip3|poetry|pipenv)\s+(install|uninstall)/i,config:X0,summaryTemplate:(T)=>`Python package operation completed (${T} lines)`},{pattern:/^(cargo|rustup)\s+(build|install|update)/i,config:P,summaryTemplate:(T)=>`Rust operation completed (${T} lines)`},{pattern:/^(go)\s+(build|get|mod)/i,config:P,summaryTemplate:(T)=>`Go operation completed (${T} lines)`}];function gT(T,$,_){let G=$,X=_??T.length;if(G>0){let Y=T.charCodeAt(G);if(Y>=56320&&Y<=57343)G+=1}if(X<T.length){let Y=T.charCodeAt(X-1);if(Y>=55296&&Y<=56319)X-=1}return T.slice(G,X)}class I0{static getConfigForCommand(T){for(let{pattern:$,config:_,summaryTemplate:G}of P$)if($.test(T))return{config:_,summaryTemplate:G};return{config:h$}}static truncate(T,$){let{config:_,summaryTemplate:G}=this.getConfigForCommand($);return this.truncateWithConfig(T,_,G)}static truncateWithConfig(T,$,_){let G=T.length,X=T.split(`
3
3
  `),Y=X.length;if(Y<=$.maxLines&&G<=$.maxChars)return{content:T,truncated:!1,originalLines:Y,originalChars:G};let Q=X.slice(0,$.keepHead),Z=X.slice(-$.keepTail),U=Y-$.keepHead-$.keepTail,V=Q.join(`
4
4
  `);if(V+=`
5
5
 
6
6
  ... (${U} lines truncated, showing first ${$.keepHead} and last ${$.keepTail} of ${Y} total) ...
7
7
 
8
8
  `,V+=Z.join(`
9
- `),V.length>$.maxChars){let O=Math.floor($.maxChars/2)-50,M=CT(V,0,O),I=CT(V,V.length-O);V=`${M}
9
+ `),V.length>$.maxChars){let O=Math.floor($.maxChars/2)-50,M=gT(V,0,O),N=gT(V,V.length-O);V=`${M}
10
10
 
11
11
  ... (content truncated to ${$.maxChars} chars) ...
12
12
 
13
- ${I}`}let g=$.summarize&&_?_(Y,G):void 0;if(g)V+=`
13
+ ${N}`}let g=$.summarize&&_?_(Y,G):void 0;if(g)V+=`
14
14
 
15
15
  [Summary: ${g}]`;return{content:V,truncated:!0,originalLines:Y,originalChars:G,summary:g}}static truncateForLLM(T,$,_){let G=this.truncate(T,_),X=this.truncate($,_),Y;if(G.truncated||X.truncated){let Q=[];if(G.truncated)Q.push(`stdout: ${G.originalLines} lines -> ${G.content.split(`
16
16
  `).length} lines`);if(X.truncated)Q.push(`stderr: ${X.originalLines} lines -> ${X.content.split(`
17
17
  `).length} lines`);Y=`Output truncated: ${Q.join(", ")}`}return{stdout:G.content,stderr:X.content,truncationInfo:Y}}static shouldTruncate(T,$){let{config:_}=this.getConfigForCommand($);return T.split(`
18
18
  `).length>_.maxLines||T.length>_.maxChars}static getStats(T){return{lines:T.split(`
19
- `).length,chars:T.length,words:T.split(/\s+/).filter(Boolean).length}}}var HT=32768,v$=1048576,u$=65536,p$=3600000,OT=4096,l$=/[\u001B\u009B][[\]()#;?]*(?:(?:(?:[a-zA-Z\d]*(?:;[-a-zA-Z\d/#&.:=?%@~_]+)*)?\u0007)|(?:(?:\d{1,4}(?:[;:]\d{0,4})*)?[\dA-PR-TZcf-nq-uy=><~]))/g;function V1(){return{async execute(){return{exitCode:null,stdout:"",stderr:"",error:"ACP terminal capability is unavailable"}}}}class z0{stream;executionId;onEvent;output=new I0(v$/2);decoder=new m$("utf8");sniffChunks=[];sniffBytes=0;binary=!1;totalBytes=0;streamedBytes=0;streamTruncated=!1;pendingEvents=[];constructor(T,$,_){this.stream=T;this.executionId=$;this.onEvent=_}append(T){let $=Buffer.isBuffer(T)?T:Buffer.from(T);if($.length===0)return;if(this.totalBytes+=$.length,this.sniffBytes<OT){let G=$.subarray(0,Math.min($.length,OT-this.sniffBytes));this.sniffChunks.push(G),this.sniffBytes+=G.length,this.binary=this.binary||Buffer.concat(this.sniffChunks).includes(0)}if(this.binary)return;let _=MT(this.decoder.write($));this.output.append(_),this.emit(_)}finish(){if(this.binary)return;let T=MT(this.decoder.end());this.output.append(T),this.emit(T)}snapshot(){let T=this.output.peek();if(this.binary)return{content:`[binary ${this.stream} omitted: ${this.totalBytes} bytes]`,omittedBytes:this.totalBytes,binary:!0};return{content:T.content,omittedBytes:T.omittedBytes,binary:!1}}async flushEvents(){await Promise.all(this.pendingEvents),this.pendingEvents.length=0}emit(T){if(!T||!this.onEvent||this.streamTruncated)return;let $=u$-this.streamedBytes;if($<=0){this.streamTruncated=!0;return}let _=n$(T,$);if(this.streamedBytes+=Buffer.byteLength(_),_.length<T.length)this.streamTruncated=!0;this.pendingEvents.push(Promise.resolve(this.onEvent({type:"output",executionId:this.executionId,stream:this.stream,chunk:_,streamedBytes:this.streamedBytes,streamTruncated:this.streamTruncated})).then(()=>{return}))}}function MT(T){return T.replace(l$,"")}function n$(T,$){let _=Buffer.from(T);if(_.length<=$)return T;let G=$;while(G>0&&(_[G]&192)===128)G-=1;return _.subarray(0,G).toString("utf8")}function FT(T){return T.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;").replaceAll("'","&apos;")}function i$(T){let $=T.trim();if(!$)throw Error("User shell command cannot be empty");if($.length>HT)throw Error(`User shell command exceeds ${HT} characters`);if($.includes("\x00"))throw Error("User shell command contains a null byte");return $}function c$(){return{execute(T,$){return new Promise((_)=>{let G=process.platform==="win32"?process.env.COMSPEC||"cmd.exe":process.env.SHELL||"/bin/bash",X=process.platform==="win32"?["/d","/s","/c",T]:["-l","-c",T],{child:Y,processTree:Q}=LT(G,X,{cwd:$.cwd,env:$.env,stdio:["ignore","pipe","pipe"]}),Z="",U="",V=!1,g=!1,O=!1,M,I=()=>{return M??=Q.terminate(),M},z=setTimeout(()=>{V=!0,I()},$.timeoutMs),j=()=>{g=!0,I()};if($.signal.addEventListener("abort",j,{once:!0}),$.signal.aborted)j();Y.stdout?.on("data",(C)=>{$.onOutput?.("stdout",C)}),Y.stderr?.on("data",(C)=>{$.onOutput?.("stderr",C)});let B=async(C)=>{if(O)return;if(O=!0,clearTimeout(z),$.signal.removeEventListener("abort",j),V||g)await I();_({...C,stdout:"",stderr:"",timedOut:V,aborted:g})};Y.once("error",(C)=>{B({exitCode:null,error:C.message})}),Y.once("close",(C)=>{B({exitCode:C})})})}}}async function B1(T,$){let _=i$(T),G=$.timeoutMs??p$,X=new z0("stdout",$.executionId,$.onEvent),Y=new z0("stderr",$.executionId,$.onEvent),Q=Date.now();await $.onEvent?.({type:"started",executionId:$.executionId,command:_});let Z,U=!1,V=!1;try{Z=await($.executor??c$()).execute(_,{cwd:$.cwd,env:$.env,timeoutMs:G,signal:$.signal,onOutput:(j,B)=>{if(j==="stdout")U=!0;else V=!0;(j==="stdout"?X:Y).append(B)}})}catch(j){Z={exitCode:null,stdout:"",stderr:"",error:j instanceof Error?j.message:String(j)}}if(!U)X.append(Z.stdout);if(!V)Y.append(Z.stderr);X.finish(),Y.finish(),await Promise.all([X.flushEvents(),Y.flushEvents()]);let g=X.snapshot(),O=Y.snapshot(),M=N0.truncateForLLM(g.content.trim(),O.content.trim(),_),I=Z.aborted||$.signal.aborted?"aborted":Z.timedOut?"timed_out":Z.error?"spawn_error":Z.exitCode===0?"completed":"failed",z={version:1,command:_,status:I,exitCode:Z.exitCode,durationMs:Math.max(0,Date.now()-Q),stdout:M.stdout,stderr:Z.error?[M.stderr,Z.error].filter(Boolean).join(`
20
- `):M.stderr,stdoutOmittedBytes:g.omittedBytes,stderrOmittedBytes:O.omittedBytes,binaryOutput:g.binary||O.binary,truncated:Boolean(M.truncationInfo)||g.omittedBytes>0||O.omittedBytes>0};return await $.onEvent?.({type:"completed",executionId:$.executionId,record:z}),z}function g1(T){let $=[T.stdout?`stdout:
19
+ `).length,chars:T.length,words:T.split(/\s+/).filter(Boolean).length}}}var CT=32768,v$=1048576,u$=65536,p$=3600000,HT=4096,l$=/[\u001B\u009B][[\]()#;?]*(?:(?:(?:[a-zA-Z\d]*(?:;[-a-zA-Z\d/#&.:=?%@~_]+)*)?\u0007)|(?:(?:\d{1,4}(?:[;:]\d{0,4})*)?[\dA-PR-TZcf-nq-uy=><~]))/g;function V1(){return{async execute(){return{exitCode:null,stdout:"",stderr:"",error:"ACP terminal capability is unavailable"}}}}class j0{stream;executionId;onEvent;output=new z0(v$/2);decoder=new m$("utf8");sniffChunks=[];sniffBytes=0;binary=!1;totalBytes=0;streamedBytes=0;streamTruncated=!1;pendingEvents=[];constructor(T,$,_){this.stream=T;this.executionId=$;this.onEvent=_}append(T){let $=Buffer.isBuffer(T)?T:Buffer.from(T);if($.length===0)return;if(this.totalBytes+=$.length,this.sniffBytes<HT){let G=$.subarray(0,Math.min($.length,HT-this.sniffBytes));this.sniffChunks.push(G),this.sniffBytes+=G.length,this.binary=this.binary||Buffer.concat(this.sniffChunks).includes(0)}if(this.binary)return;let _=OT(this.decoder.write($));this.output.append(_),this.emit(_)}finish(){if(this.binary)return;let T=OT(this.decoder.end());this.output.append(T),this.emit(T)}snapshot(){let T=this.output.peek();if(this.binary)return{content:`[binary ${this.stream} omitted: ${this.totalBytes} bytes]`,omittedBytes:this.totalBytes,binary:!0};return{content:T.content,omittedBytes:T.omittedBytes,binary:!1}}async flushEvents(){await Promise.all(this.pendingEvents),this.pendingEvents.length=0}emit(T){if(!T||!this.onEvent||this.streamTruncated)return;let $=u$-this.streamedBytes;if($<=0){this.streamTruncated=!0;return}let _=n$(T,$);if(this.streamedBytes+=Buffer.byteLength(_),_.length<T.length)this.streamTruncated=!0;this.pendingEvents.push(Promise.resolve(this.onEvent({type:"output",executionId:this.executionId,stream:this.stream,chunk:_,streamedBytes:this.streamedBytes,streamTruncated:this.streamTruncated})).then(()=>{return}))}}function OT(T){return T.replace(l$,"")}function n$(T,$){let _=Buffer.from(T);if(_.length<=$)return T;let G=$;while(G>0&&(_[G]&192)===128)G-=1;return _.subarray(0,G).toString("utf8")}function MT(T){return T.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;").replaceAll("'","&apos;")}function i$(T){let $=T.trim();if(!$)throw Error("User shell command cannot be empty");if($.length>CT)throw Error(`User shell command exceeds ${CT} characters`);if($.includes("\x00"))throw Error("User shell command contains a null byte");return $}function c$(){return{execute(T,$){return new Promise((_)=>{let G=process.platform==="win32"?process.env.COMSPEC||"cmd.exe":process.env.SHELL||"/bin/bash",X=process.platform==="win32"?["/d","/s","/c",T]:["-l","-c",T],{child:Y,processTree:Q}=FT(G,X,{cwd:$.cwd,env:$.env,stdio:["ignore","pipe","pipe"]}),Z="",U="",V=!1,g=!1,O=!1,M,N=()=>{return M??=Q.terminate(),M},I=setTimeout(()=>{V=!0,N()},$.timeoutMs),W=()=>{g=!0,N()};if($.signal.addEventListener("abort",W,{once:!0}),$.signal.aborted)W();Y.stdout?.on("data",(C)=>{$.onOutput?.("stdout",C)}),Y.stderr?.on("data",(C)=>{$.onOutput?.("stderr",C)});let B=async(C)=>{if(O)return;if(O=!0,clearTimeout(I),$.signal.removeEventListener("abort",W),V||g)await N();_({...C,stdout:"",stderr:"",timedOut:V,aborted:g})};Y.once("error",(C)=>{B({exitCode:null,error:C.message})}),Y.once("close",(C)=>{B({exitCode:C})})})}}}async function B1(T,$){let _=i$(T),G=$.timeoutMs??p$,X=new j0("stdout",$.executionId,$.onEvent),Y=new j0("stderr",$.executionId,$.onEvent),Q=Date.now();await $.onEvent?.({type:"started",executionId:$.executionId,command:_});let Z,U=!1,V=!1;try{Z=await($.executor??c$()).execute(_,{cwd:$.cwd,env:$.env,timeoutMs:G,signal:$.signal,onOutput:(W,B)=>{if(W==="stdout")U=!0;else V=!0;(W==="stdout"?X:Y).append(B)}})}catch(W){Z={exitCode:null,stdout:"",stderr:"",error:W instanceof Error?W.message:String(W)}}if(!U)X.append(Z.stdout);if(!V)Y.append(Z.stderr);X.finish(),Y.finish(),await Promise.all([X.flushEvents(),Y.flushEvents()]);let g=X.snapshot(),O=Y.snapshot(),M=I0.truncateForLLM(g.content.trim(),O.content.trim(),_),N=Z.aborted||$.signal.aborted?"aborted":Z.timedOut?"timed_out":Z.error?"spawn_error":Z.exitCode===0?"completed":"failed",I={version:1,command:_,status:N,exitCode:Z.exitCode,durationMs:Math.max(0,Date.now()-Q),stdout:M.stdout,stderr:Z.error?[M.stderr,Z.error].filter(Boolean).join(`
20
+ `):M.stderr,stdoutOmittedBytes:g.omittedBytes,stderrOmittedBytes:O.omittedBytes,binaryOutput:g.binary||O.binary,truncated:Boolean(M.truncationInfo)||g.omittedBytes>0||O.omittedBytes>0};return await $.onEvent?.({type:"completed",executionId:$.executionId,record:I}),I}function g1(T){let $=[T.stdout?`stdout:
21
21
  ${T.stdout}`:"",T.stderr?`stderr:
22
22
  ${T.stderr}`:""].filter(Boolean).join(`
23
- `);return["<user_shell_command>",`<command>${FT(T.command)}</command>`,"<result>",`Status: ${T.status}`,`Exit code: ${T.exitCode??"null"}`,`Duration: ${(T.durationMs/1000).toFixed(3)} seconds`,`Output:
24
- ${FT($||"(no output)")}`,"</result>","</user_shell_command>"].join(`
25
- `)}function JT(T){let $=[T.stdout,T.stderr?`stderr:
23
+ `);return["<user_shell_command>",`<command>${MT(T.command)}</command>`,"<result>",`Status: ${T.status}`,`Exit code: ${T.exitCode??"null"}`,`Duration: ${(T.durationMs/1000).toFixed(3)} seconds`,`Output:
24
+ ${MT($||"(no output)")}`,"</result>","</user_shell_command>"].join(`
25
+ `)}function LT(T){let $=[T.stdout,T.stderr?`stderr:
26
26
  ${T.stderr}`:""].filter(Boolean).join(`
27
27
  `);return[`! ${T.command}`,$||"(no output)"].join(`
28
- `)}function d$(T){if(!T||typeof T!=="object"||Array.isArray(T))return;let $=T;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 IT(T){if(!T||typeof T!=="object"||Array.isArray(T))return;return d$(T.userShellCommand)}var a$=262144,t$="session-surface-message\x00",KT="[private state path]",G0="[content truncated]",NT=`
29
- ${G0}`,X0=String.fromCharCode(27),o$=String.fromCharCode(7),r$=String.fromCharCode(157),e$=String.fromCharCode(156),T_=String.fromCharCode(155),$_=new RegExp(`(?:${f(X0)}\\]|${f(r$)})[\\s\\S]*?(?:${f(o$)}|${f(X0)}\\\\|${f(e$)})`,"g"),__=new RegExp(`(?:${f(X0)}\\[|${f(T_)})[0-?]*[ -/]*[@-~]`,"g");function j0(T,$){let _={privateRoots:[T],privateValues:[$.exactIdentity,$.collisionIdentity]};if($.style==="win32")_.caseInsensitivePrivateRoots=[$.wirePath];else _.privateRoots=[T,$.wirePath];return _}class L extends Error{code="session_surface_state_invalid";constructor(){super("session surface projection state is invalid");this.name="SessionSurfaceProjectionError"}}function kT(T,$){let _=M_($.maxContentBytes),{privateRoots:G,caseInsensitivePrivateRoots:X}=AT($),Y=xT($.privateValues??[]),Q=l(T),Z=new Map;for(let V of Q){if(k0(V.seq),V.type==="message_created"){Z.set(V.data.messageId,{event:V,orderedPartIds:[],partsById:new Map});continue}if(V.type!=="part_created"&&V.type!=="part_updated")continue;let g=Z.get(V.data.messageId);if(!g)continue;Q_(g,V)}let U=[];for(let V of Z.values()){let g=X_(V,G,X,Y,_);if(g)U.push(g)}return U}function G_(T){return typeof T==="object"&&T!==null&&!Array.isArray(T)}function f(T){return T.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function X_(T,$,_,G,X){let Y=T.event.data.role;if(Y!=="user"&&Y!=="assistant")return;let Q=Y_(T),Z=qT(Q),U={role:Y,content:Z,...T.event.data.metadata!==void 0?{metadata:T.event.data.metadata}:{}};if(!BT(U))return;let V=V_(T.event.data.createdAt),O=ET(Y0(Y0(Z,_,!0),$),G).trim();if(!O)return;let M=H_(O,X),I=U_(T.event);if(M.truncated)return{id:I,role:Y,content:M.content,timestamp:V,truncated:!0};return{id:I,role:Y,content:M.content,timestamp:V}}function W0(T,$){let{privateRoots:_,caseInsensitivePrivateRoots:G}=AT($);return ET(Y0(Y0(qT(T),G,!0),_),xT($.privateValues??[]))}function Y_(T){let $=IT(T.event.data.metadata);if($)return JT($);return T.orderedPartIds.map((_)=>T.partsById.get(_)).flatMap((_)=>_?[_.content]:[]).join("")}function Q_(T,$){if($.data.partType!=="text"&&$.data.partType!=="image")return;let _=$.data.partType==="text"?{partId:$.data.partId,type:"text",content:Z_($.data.payload)}:{partId:$.data.partId,type:"image",content:"[Image]"};if(!T.partsById.has($.data.partId))T.orderedPartIds.push($.data.partId);T.partsById.set($.data.partId,_)}function Z_(T){if(!G_(T))return"";let $=T.text;return typeof $==="string"?$:""}function U_(T){let $=k0(T.seq);return K0($,T.data.messageId)}function K0(T,$){let _=k0(T),G=s$("sha256").update(t$).update($).digest("hex").slice(0,16);return`surface-message:${_}:${G}`}function V_(T){let $=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,9}))?(Z|[+-]\d{2}:\d{2})$/.exec(T);if(!$)throw new L;let _=Number($[1]),G=Number($[2]),X=Number($[3]),Y=Number($[4]),Q=Number($[5]),Z=Number($[6]),U=$[8],V=new Date(Date.UTC(_,G,0)).getUTCDate(),g=U==="Z"||U!==void 0&&Number(U.slice(1,3))<=23&&Number(U.slice(4,6))<=59;if(G<1||G>12||X<1||X>V||Y>23||Q>59||Z>59||!g||!Number.isFinite(Date.parse(T)))throw new L;return T}function zT(T,$){return[...new Set([...T,...$].filter(Boolean))].sort((_,G)=>G.length-_.length)}function jT(T){return/^[A-Za-z]:[\\/]/.test(T)||/^\\\\/.test(T)}function AT(T){let $=zT(T.privateRoots,T.bladeStorageRoots??[]);return{privateRoots:$.filter((_)=>!jT(_)),caseInsensitivePrivateRoots:zT([...T.caseInsensitivePrivateRoots??[],...$.filter(jT)],[])}}function xT(T){return[...new Set(T.filter(Boolean))].sort(($,_)=>_.length-$.length)}function ET(T,$){let _=T;for(let G of $)_=_.split(G).join(KT);return _}function Y0(T,$,_=!1){let G=T;for(let X of $)G=B_(G,X,_);return G}function B_(T,$,_){if(!$)return T;let G=0,X="",Y=_?new RegExp($.split(/[\\/]+/).map((Q)=>f(Q)).join("[\\\\/]+"),"i"):void 0;while(G<T.length){let Q=Y?.exec(T.slice(G)),Z=Y?Q?G+Q.index:-1:T.indexOf($,G);if(Z<0){X+=T.slice(G);break}X+=T.slice(G,Z);let U=Q?.[0].length??$.length,V=g_(T,Z,U);if(V===Z){X+=T[Z],G=Z+1;continue}X+=KT,G=V}return X}function g_(T,$,_){let G=$+_;if(G>=T.length)return G;let X=T[G];if(X===void 0)return G;if(!C_(X)&&!WT(X))return $;let Y=G;while(Y<T.length){let Q=T[Y];if(Q===void 0||WT(Q))break;Y+=1}return Y}function C_(T){return T==="/"||T==="\\"}function WT(T){return T===" "||T==="\t"||T===`
30
- `||T==="\r"||T==='"'||T==="'"||T==="`"||T==="<"||T===">"||T==="("||T===")"||T==="["||T==="]"||T==="{"||T==="}"||T===","||T===";"||T===":"||T==="!"||T==="?"}function qT(T){return[...T.replace(/\r\n?/g,`
31
- `).replace($_,"").replace(__,"").split(`${X0}\\`).join("")].filter((G)=>{let X=G.charCodeAt(0);return!(X===0||X>=1&&X<=8||X===11||X===12||X>=14&&X<=31||X>=127&&X<=159)}).join("")}function H_(T,$){if(Buffer.byteLength(T,"utf8")<=$)return{content:T,truncated:!1};let _=O_($),G=Buffer.byteLength(_,"utf8"),X=Math.max(0,$-G);return{content:`${DT(T,X)}${_}`,truncated:!0}}function DT(T,$){if($<=0)return"";let _=Buffer.from(T,"utf8");if(_.length<=$)return T;let G=_.subarray(0,$).toString("utf8");while(Buffer.byteLength(G,"utf8")>$)G=G.slice(0,-1);return G.replace(/\uFFFD$/,"")}function O_(T){let $=Buffer.byteLength(NT,"utf8");if(T>=$)return NT;let _=Buffer.byteLength(G0,"utf8");if(T>=_)return G0;return DT(G0,T)}function M_(T){let $=T??a$;if(!Number.isSafeInteger($)||$<=0)throw new L;return $}function k0(T){let $=T;if($===void 0||!Number.isSafeInteger($)||$<=0)throw new L;return $}import*as x from"node:fs";import{createReadStream as F_}from"node:fs";import*as J from"node:fs/promises";import*as A0 from"node:path";import{createInterface as L_}from"node:readline";var wT=65536;function Q0(T){let $=T.data;if($===null||typeof $!=="object"||Array.isArray($))throw Error("Session event data must be a JSON object");return JSON.stringify(T)}function J_(T,$,_){let G=T.trim();if(!G)return;try{return JSON.parse(G)}catch(X){throw Error(`Invalid session JSONL in ${_} at line ${$}`,{cause:X})}}function a(T,$="session transcript"){let _=T.split(`
28
+ `)}function d$(T){if(!T||typeof T!=="object"||Array.isArray(T))return;let $=T;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 JT(T){if(!T||typeof T!=="object"||Array.isArray(T))return;return d$(T.userShellCommand)}var a$=262144,o$="session-surface-message\x00",WT="[private state path]",Y0="[content truncated]",NT=`
29
+ ${Y0}`,Q0=String.fromCharCode(27),t$=String.fromCharCode(7),r$=String.fromCharCode(157),e$=String.fromCharCode(156),T_=String.fromCharCode(155),$_=new RegExp(`(?:${f(Q0)}\\]|${f(r$)})[\\s\\S]*?(?:${f(t$)}|${f(Q0)}\\\\|${f(e$)})`,"g"),__=new RegExp(`(?:${f(Q0)}\\[|${f(T_)})[0-?]*[ -/]*[@-~]`,"g");function W0(T,$){let _={privateRoots:[T],privateValues:[$.exactIdentity,$.collisionIdentity]};if($.style==="win32")_.caseInsensitivePrivateRoots=[$.wirePath];else _.privateRoots=[T,$.wirePath];return _}class L extends Error{code="session_surface_state_invalid";constructor(){super("session surface projection state is invalid");this.name="SessionSurfaceProjectionError"}}function KT(T,$){let _=M_($.maxContentBytes),{privateRoots:G,caseInsensitivePrivateRoots:X}=kT($),Y=AT($.privateValues??[]),Q=n(T),Z=new Map;for(let V of Q){if(A0(V.seq),V.type==="message_created"){Z.set(V.data.messageId,{event:V,orderedPartIds:[],partsById:new Map});continue}if(V.type!=="part_created"&&V.type!=="part_updated")continue;let g=Z.get(V.data.messageId);if(!g)continue;Q_(g,V)}let U=[];for(let V of Z.values()){let g=X_(V,G,X,Y,_);if(g)U.push(g)}return U}function G_(T){return typeof T==="object"&&T!==null&&!Array.isArray(T)}function f(T){return T.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function X_(T,$,_,G,X){let Y=T.event.data.role;if(Y!=="user"&&Y!=="assistant")return;let Q=Y_(T),Z=ET(Q),U={role:Y,content:Z,...T.event.data.metadata!==void 0?{metadata:T.event.data.metadata}:{}};if(!VT(U))return;let V=V_(T.event.data.createdAt),O=xT(Z0(Z0(Z,_,!0),$),G).trim();if(!O)return;let M=H_(O,X),N=U_(T.event);if(M.truncated)return{id:N,role:Y,content:M.content,timestamp:V,truncated:!0};return{id:N,role:Y,content:M.content,timestamp:V}}function K0(T,$){let{privateRoots:_,caseInsensitivePrivateRoots:G}=kT($);return xT(Z0(Z0(ET(T),G,!0),_),AT($.privateValues??[]))}function Y_(T){let $=JT(T.event.data.metadata);if($)return LT($);return T.orderedPartIds.map((_)=>T.partsById.get(_)).flatMap((_)=>_?[_.content]:[]).join("")}function Q_(T,$){if($.data.partType!=="text"&&$.data.partType!=="image")return;let _=$.data.partType==="text"?{partId:$.data.partId,type:"text",content:Z_($.data.payload)}:{partId:$.data.partId,type:"image",content:"[Image]"};if(!T.partsById.has($.data.partId))T.orderedPartIds.push($.data.partId);T.partsById.set($.data.partId,_)}function Z_(T){if(!G_(T))return"";let $=T.text;return typeof $==="string"?$:""}function U_(T){let $=A0(T.seq);return k0($,T.data.messageId)}function k0(T,$){let _=A0(T),G=s$("sha256").update(o$).update($).digest("hex").slice(0,16);return`surface-message:${_}:${G}`}function V_(T){let $=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,9}))?(Z|[+-]\d{2}:\d{2})$/.exec(T);if(!$)throw new L;let _=Number($[1]),G=Number($[2]),X=Number($[3]),Y=Number($[4]),Q=Number($[5]),Z=Number($[6]),U=$[8],V=new Date(Date.UTC(_,G,0)).getUTCDate(),g=U==="Z"||U!==void 0&&Number(U.slice(1,3))<=23&&Number(U.slice(4,6))<=59;if(G<1||G>12||X<1||X>V||Y>23||Q>59||Z>59||!g||!Number.isFinite(Date.parse(T)))throw new L;return T}function zT(T,$){return[...new Set([...T,...$].filter(Boolean))].sort((_,G)=>G.length-_.length)}function IT(T){return/^[A-Za-z]:[\\/]/.test(T)||/^\\\\/.test(T)}function kT(T){let $=zT(T.privateRoots,T.bladeStorageRoots??[]);return{privateRoots:$.filter((_)=>!IT(_)),caseInsensitivePrivateRoots:zT([...T.caseInsensitivePrivateRoots??[],...$.filter(IT)],[])}}function AT(T){return[...new Set(T.filter(Boolean))].sort(($,_)=>_.length-$.length)}function xT(T,$){let _=T;for(let G of $)_=_.split(G).join(WT);return _}function Z0(T,$,_=!1){let G=T;for(let X of $)G=B_(G,X,_);return G}function B_(T,$,_){if(!$)return T;let G=0,X="",Y=_?new RegExp($.split(/[\\/]+/).map((Q)=>f(Q)).join("[\\\\/]+"),"i"):void 0;while(G<T.length){let Q=Y?.exec(T.slice(G)),Z=Y?Q?G+Q.index:-1:T.indexOf($,G);if(Z<0){X+=T.slice(G);break}X+=T.slice(G,Z);let U=Q?.[0].length??$.length,V=g_(T,Z,U);if(V===Z){X+=T[Z],G=Z+1;continue}X+=WT,G=V}return X}function g_(T,$,_){let G=$+_;if(G>=T.length)return G;let X=T[G];if(X===void 0)return G;if(!C_(X)&&!jT(X))return $;let Y=G;while(Y<T.length){let Q=T[Y];if(Q===void 0||jT(Q))break;Y+=1}return Y}function C_(T){return T==="/"||T==="\\"}function jT(T){return T===" "||T==="\t"||T===`
30
+ `||T==="\r"||T==='"'||T==="'"||T==="`"||T==="<"||T===">"||T==="("||T===")"||T==="["||T==="]"||T==="{"||T==="}"||T===","||T===";"||T===":"||T==="!"||T==="?"}function ET(T){return[...T.replace(/\r\n?/g,`
31
+ `).replace($_,"").replace(__,"").split(`${Q0}\\`).join("")].filter((G)=>{let X=G.charCodeAt(0);return!(X===0||X>=1&&X<=8||X===11||X===12||X>=14&&X<=31||X>=127&&X<=159)}).join("")}function H_(T,$){if(Buffer.byteLength(T,"utf8")<=$)return{content:T,truncated:!1};let _=O_($),G=Buffer.byteLength(_,"utf8"),X=Math.max(0,$-G);return{content:`${qT(T,X)}${_}`,truncated:!0}}function qT(T,$){if($<=0)return"";let _=Buffer.from(T,"utf8");if(_.length<=$)return T;let G=_.subarray(0,$).toString("utf8");while(Buffer.byteLength(G,"utf8")>$)G=G.slice(0,-1);return G.replace(/\uFFFD$/,"")}function O_(T){let $=Buffer.byteLength(NT,"utf8");if(T>=$)return NT;let _=Buffer.byteLength(Y0,"utf8");if(T>=_)return Y0;return qT(Y0,T)}function M_(T){let $=T??a$;if(!Number.isSafeInteger($)||$<=0)throw new L;return $}function A0(T){let $=T;if($===void 0||!Number.isSafeInteger($)||$<=0)throw new L;return $}import*as x from"node:fs";import{createReadStream as F_}from"node:fs";import*as J from"node:fs/promises";import*as x0 from"node:path";import{createInterface as L_}from"node:readline";var DT=65536;function U0(T){let $=T.data;if($===null||typeof $!=="object"||Array.isArray($))throw Error("Session event data must be a JSON object");return JSON.stringify(T)}function J_(T,$,_){let G=T.trim();if(!G)return;try{return JSON.parse(G)}catch(X){throw Error(`Invalid session JSONL in ${_} at line ${$}`,{cause:X})}}function o(T,$="session transcript"){let _=T.split(`
32
32
  `),G=!T.endsWith(`
33
- `),X=[];for(let[Y,Q]of _.entries())try{let Z=J_(Q,Y+1,$);if(Z){if(typeof Z.seq!=="number")Z.seq=X.length+1;X.push(Z)}}catch(Z){if(G&&Y===_.length-1)break;throw Z}return X}class K{static appendQueues=new Map;filePath;constructor(T){this.filePath=T}static maxSeq(T){let $=0;for(let _ of T)if(typeof _.seq==="number"&&_.seq>$)$=_.seq;return $}static stampSeqFrom(T,$){let _=$;return T.map((G)=>{if(typeof G.seq==="number"){if(G.seq>_)_=G.seq;return G}return _+=1,{...G,seq:_}})}static stampSeq(T,$){return K.stampSeqFrom(T,K.maxSeq($))}async append(T){try{let[$]=await this.appendEntries([T]);return $}catch($){throw console.error(`[JSONLStore] 追加写入失败: ${this.filePath}`,$),$}}async appendBatch(T){try{return await this.appendEntries(T)}catch($){throw console.error(`[JSONLStore] 批量追加写入失败: ${this.filePath}`,$),$}}async appendEntries(T){if(T.length===0)return[];return this.enqueue(async()=>{await J.mkdir(A0.dirname(this.filePath),{recursive:!0,mode:493});let $=await J.open(this.filePath,"a+",384);try{let _=await this.repairIncompleteTail($),G=await this.readTailSeq($),X=K.stampSeqFrom(T,G),Y=`${X.map(Q0).join(`
33
+ `),X=[];for(let[Y,Q]of _.entries())try{let Z=J_(Q,Y+1,$);if(Z){if(typeof Z.seq!=="number")Z.seq=X.length+1;X.push(Z)}}catch(Z){if(G&&Y===_.length-1)break;throw Z}return X}class K{static appendQueues=new Map;filePath;constructor(T){this.filePath=T}static maxSeq(T){let $=0;for(let _ of T)if(typeof _.seq==="number"&&_.seq>$)$=_.seq;return $}static stampSeqFrom(T,$){let _=$;return T.map((G)=>{if(typeof G.seq==="number"){if(G.seq>_)_=G.seq;return G}return _+=1,{...G,seq:_}})}static stampSeq(T,$){return K.stampSeqFrom(T,K.maxSeq($))}async append(T){try{let[$]=await this.appendEntries([T]);return $}catch($){throw console.error(`[JSONLStore] 追加写入失败: ${this.filePath}`,$),$}}async appendBatch(T){try{return await this.appendEntries(T)}catch($){throw console.error(`[JSONLStore] 批量追加写入失败: ${this.filePath}`,$),$}}async appendEntries(T){if(T.length===0)return[];return this.enqueue(async()=>{await J.mkdir(x0.dirname(this.filePath),{recursive:!0,mode:493});let $=await J.open(this.filePath,"a+",384);try{let _=await this.repairIncompleteTail($),G=await this.readTailSeq($),X=K.stampSeqFrom(T,G),Y=`${X.map(U0).join(`
34
34
  `)}
35
- `;return await $.appendFile(_+Y,"utf8"),await $.sync(),X}finally{await $.close()}})}async createExclusive(T){if(T.length===0)throw Error("Cannot create an empty session transcript");await J.mkdir(A0.dirname(this.filePath),{recursive:!0,mode:493});let $;try{$=await J.open(this.filePath,"wx",384);let G=`${K.stampSeq(T,[]).map(Q0).join(`
35
+ `;return await $.appendFile(_+Y,"utf8"),await $.sync(),X}finally{await $.close()}})}async createExclusive(T){if(T.length===0)throw Error("Cannot create an empty session transcript");await J.mkdir(x0.dirname(this.filePath),{recursive:!0,mode:493});let $;try{$=await J.open(this.filePath,"wx",384);let G=`${K.stampSeq(T,[]).map(U0).join(`
36
36
  `)}
37
- `;await $.writeFile(G,"utf-8"),await $.sync()}catch(_){if($)await $.close(),$=void 0,await J.unlink(this.filePath).catch(()=>{return});throw _}finally{await $?.close()}}async readAll(T={}){if(T.signal?.throwIfAborted(),!x.existsSync(this.filePath))return[];let $=await J.readFile(this.filePath,{encoding:"utf-8",signal:T.signal});return a($,this.filePath)}async readStream(T){return new Promise(($,_)=>{if(!x.existsSync(this.filePath)){$();return}let G=F_(this.filePath,"utf-8"),X=L_({input:G,crlfDelay:Number.POSITIVE_INFINITY}),Y=0;X.on("line",async(Q)=>{let Z=Q.trim();if(Z.length===0)return;try{let U=JSON.parse(Z);if(Y+=1,typeof U.seq!=="number")U.seq=Y;await T(U)}catch(U){console.warn(`[JSONLStore] 解析 JSON 行失败: ${Z}`,U)}}),X.on("close",()=>$()),X.on("error",_),G.on("error",_)})}async filter(T){let $=[];return await this.readStream((_)=>{if(T(_))$.push(_)}),$}async readLast(T){return(await this.readAll()).slice(-T)}async readFromSeq(T){return(await this.readAll()).filter((_)=>(_.seq??0)>=T)}async getStats(){try{if(!x.existsSync(this.filePath))return{exists:!1,size:0,lineCount:0};let T=await J.stat(this.filePath),_=(await J.readFile(this.filePath,"utf-8")).split(`
38
- `).filter((G)=>G.trim().length>0).length;return{exists:!0,size:T.size,lineCount:_}}catch(T){return console.error(`[JSONLStore] 获取统计信息失败: ${this.filePath}`,T),{exists:!1,size:0,lineCount:0}}}async exists(){try{return await J.access(this.filePath),!0}catch{return!1}}async delete(){try{return await this.enqueue(async()=>{try{return await J.unlink(this.filePath),!0}catch(T){if(T.code==="ENOENT")return!1;throw T}})}catch(T){throw console.error(`[JSONLStore] 删除文件失败: ${this.filePath}`,T),T}}async deleteValidated(T){return this.enqueue(async()=>{let $;try{$=await J.open(this.filePath,"r")}catch(G){if(G.code==="ENOENT")return!1;throw G}let _;try{_=a(await $.readFile("utf8"),"session transcript")}finally{await $.close()}if(!T(_))return!1;try{return await J.unlink(this.filePath),!0}catch(G){if(G.code==="ENOENT")return!1;throw G}})}async appendValidated(T,$={}){return this.appendValidatedAsync(async(_)=>T(_),$)}async appendValidatedBatch(T,$={}){return this.appendValidatedBatchAsync(async(_)=>T(_),$)}async appendValidatedBatchAsync(T,$={}){return this.enqueue(async()=>{let _=$.noFollow?x.constants.O_RDWR|(x.constants.O_NOFOLLOW??0):"r+",G=await J.open(this.filePath,_);try{await $.validateHandle?.(G);let{entries:X,separator:Y,size:Q}=await this.readCommittedState(G,"session transcript"),Z=await T(X);if(Z.length===0)return[];let U=K.stampSeq(Z,X),V=`${U.map(Q0).join(`
37
+ `;await $.writeFile(G,"utf-8"),await $.sync()}catch(_){if($)await $.close(),$=void 0,await J.unlink(this.filePath).catch(()=>{return});throw _}finally{await $?.close()}}async readAll(T={}){if(T.signal?.throwIfAborted(),!x.existsSync(this.filePath))return[];let $=await J.readFile(this.filePath,{encoding:"utf-8",signal:T.signal});return o($,this.filePath)}async readStream(T){return new Promise(($,_)=>{if(!x.existsSync(this.filePath)){$();return}let G=F_(this.filePath,"utf-8"),X=L_({input:G,crlfDelay:Number.POSITIVE_INFINITY}),Y=0;X.on("line",async(Q)=>{let Z=Q.trim();if(Z.length===0)return;try{let U=JSON.parse(Z);if(Y+=1,typeof U.seq!=="number")U.seq=Y;await T(U)}catch(U){console.warn(`[JSONLStore] 解析 JSON 行失败: ${Z}`,U)}}),X.on("close",()=>$()),X.on("error",_),G.on("error",_)})}async filter(T){let $=[];return await this.readStream((_)=>{if(T(_))$.push(_)}),$}async readLast(T){return(await this.readAll()).slice(-T)}async readFromSeq(T){return(await this.readAll()).filter((_)=>(_.seq??0)>=T)}async getStats(){try{if(!x.existsSync(this.filePath))return{exists:!1,size:0,lineCount:0};let T=await J.stat(this.filePath),_=(await J.readFile(this.filePath,"utf-8")).split(`
38
+ `).filter((G)=>G.trim().length>0).length;return{exists:!0,size:T.size,lineCount:_}}catch(T){return console.error(`[JSONLStore] 获取统计信息失败: ${this.filePath}`,T),{exists:!1,size:0,lineCount:0}}}async exists(){try{return await J.access(this.filePath),!0}catch{return!1}}async delete(){try{return await this.enqueue(async()=>{try{return await J.unlink(this.filePath),!0}catch(T){if(T.code==="ENOENT")return!1;throw T}})}catch(T){throw console.error(`[JSONLStore] 删除文件失败: ${this.filePath}`,T),T}}async deleteValidated(T){return this.enqueue(async()=>{let $;try{$=await J.open(this.filePath,"r")}catch(G){if(G.code==="ENOENT")return!1;throw G}let _;try{_=o(await $.readFile("utf8"),"session transcript")}finally{await $.close()}if(!T(_))return!1;try{return await J.unlink(this.filePath),!0}catch(G){if(G.code==="ENOENT")return!1;throw G}})}async appendValidated(T,$={}){return this.appendValidatedAsync(async(_)=>T(_),$)}async appendValidatedBatch(T,$={}){return this.appendValidatedBatchAsync(async(_)=>T(_),$)}async appendValidatedBatchAsync(T,$={}){return this.enqueue(async()=>{let _=$.noFollow?x.constants.O_RDWR|(x.constants.O_NOFOLLOW??0):"r+",G=await J.open(this.filePath,_);try{await $.validateHandle?.(G);let{entries:X,separator:Y,size:Q}=await this.readCommittedState(G,"session transcript"),Z=await T(X);if(Z.length===0)return[];let U=K.stampSeq(Z,X),V=`${U.map(U0).join(`
39
39
  `)}
40
- `;return await G.write(Y+V,Q,"utf8"),await G.sync(),await $.validateHandle?.(G),U}finally{await G.close()}})}async appendValidatedAsync(T,$={}){return this.enqueue(async()=>{let _=$.noFollow?x.constants.O_RDWR|(x.constants.O_NOFOLLOW??0):"r+",G=await J.open(this.filePath,_);try{await $.validateHandle?.(G);let{entries:X,separator:Y,size:Q}=await this.readCommittedState(G,"session transcript"),Z=await T(X),[U]=K.stampSeq([Z],X),V=`${Y}${Q0(U)}
41
- `;return await G.write(V,Q,"utf8"),await G.sync(),await $.validateHandle?.(G),U}finally{await G.close()}})}async readAllValidated(T={}){T.signal?.throwIfAborted();let $=T.noFollow?x.constants.O_RDONLY|(x.constants.O_NOFOLLOW??0):"r",_;try{_=await J.open(this.filePath,$)}catch(G){if(T.signal?.throwIfAborted(),G.code==="ENOENT")return[];throw G}try{await T.validateHandle?.(_),T.signal?.throwIfAborted();let G=a(await _.readFile({encoding:"utf8",signal:T.signal}),"session transcript");return T.signal?.throwIfAborted(),await T.validateHandle?.(_),T.signal?.throwIfAborted(),G}finally{await _.close()}}getFilePath(){return this.filePath}async enqueue(T){let _=(K.appendQueues.get(this.filePath)??Promise.resolve()).catch(()=>{return}).then(T),G=_.then(()=>{return},()=>{return});K.appendQueues.set(this.filePath,G);try{return await _}finally{if(K.appendQueues.get(this.filePath)===G)K.appendQueues.delete(this.filePath)}}async readCommittedState(T,$=this.filePath){let _=await this.repairIncompleteTail(T),G=await T.readFile("utf8"),X=a(G,$),{size:Y}=await T.stat();return{entries:X,separator:_,size:Y}}async readTailSeq(T){let{size:$}=await T.stat();if($===0)return 0;let _=Math.max(0,$-wT),G=Buffer.allocUnsafe($-_);await T.read(G,0,G.length,_);let X=G.toString("utf8").split(`
42
- `);for(let Q=X.length-1;Q>=0;Q--){let Z=X[Q].trim();if(!Z)continue;if(Q===0&&_>0)break;try{let U=JSON.parse(Z).seq;if(typeof U==="number")return U}catch{}break}let Y=await T.readFile("utf8");return K.maxSeq(a(Y,this.filePath))}async repairIncompleteTail(T){let{size:$}=await T.stat();if($===0)return"";let _=Buffer.allocUnsafe(1);if(await T.read(_,0,1,$-1),_[0]===10)return"";let G=await this.findTailStart(T,$),X=Buffer.allocUnsafe($-G);await T.read(X,0,X.length,G);try{return JSON.parse(X.toString("utf8").trim()),`
43
- `}catch{return await T.truncate(G),""}}async findTailStart(T,$){let _=$;while(_>0){let G=Math.max(0,_-wT),X=Buffer.allocUnsafe(_-G);await T.read(X,0,X.length,G);let Y=X.lastIndexOf(10);if(Y>=0)return G+Y+1;_=G}return 0}}function ST(T){let $=Number(T.pragma("user_version")??0);if($===8)return;if($>0&&$!==8)T.exec(`
40
+ `;return await G.write(Y+V,Q,"utf8"),await G.sync(),await $.validateHandle?.(G),U}finally{await G.close()}})}async appendValidatedAsync(T,$={}){return this.enqueue(async()=>{let _=$.noFollow?x.constants.O_RDWR|(x.constants.O_NOFOLLOW??0):"r+",G=await J.open(this.filePath,_);try{await $.validateHandle?.(G);let{entries:X,separator:Y,size:Q}=await this.readCommittedState(G,"session transcript"),Z=await T(X),[U]=K.stampSeq([Z],X),V=`${Y}${U0(U)}
41
+ `;return await G.write(V,Q,"utf8"),await G.sync(),await $.validateHandle?.(G),U}finally{await G.close()}})}async readAllValidated(T={}){T.signal?.throwIfAborted();let $=T.noFollow?x.constants.O_RDONLY|(x.constants.O_NOFOLLOW??0):"r",_;try{_=await J.open(this.filePath,$)}catch(G){if(T.signal?.throwIfAborted(),G.code==="ENOENT")return[];throw G}try{await T.validateHandle?.(_),T.signal?.throwIfAborted();let G=o(await _.readFile({encoding:"utf8",signal:T.signal}),"session transcript");return T.signal?.throwIfAborted(),await T.validateHandle?.(_),T.signal?.throwIfAborted(),G}finally{await _.close()}}getFilePath(){return this.filePath}async enqueue(T){let _=(K.appendQueues.get(this.filePath)??Promise.resolve()).catch(()=>{return}).then(T),G=_.then(()=>{return},()=>{return});K.appendQueues.set(this.filePath,G);try{return await _}finally{if(K.appendQueues.get(this.filePath)===G)K.appendQueues.delete(this.filePath)}}async readCommittedState(T,$=this.filePath){let _=await this.repairIncompleteTail(T),G=await T.readFile("utf8"),X=o(G,$),{size:Y}=await T.stat();return{entries:X,separator:_,size:Y}}async readTailSeq(T){let{size:$}=await T.stat();if($===0)return 0;let _=Math.max(0,$-DT),G=Buffer.allocUnsafe($-_);await T.read(G,0,G.length,_);let X=G.toString("utf8").split(`
42
+ `);for(let Q=X.length-1;Q>=0;Q--){let Z=X[Q].trim();if(!Z)continue;if(Q===0&&_>0)break;try{let U=JSON.parse(Z).seq;if(typeof U==="number")return U}catch{}break}let Y=await T.readFile("utf8");return K.maxSeq(o(Y,this.filePath))}async repairIncompleteTail(T){let{size:$}=await T.stat();if($===0)return"";let _=Buffer.allocUnsafe(1);if(await T.read(_,0,1,$-1),_[0]===10)return"";let G=await this.findTailStart(T,$),X=Buffer.allocUnsafe($-G);await T.read(X,0,X.length,G);try{return JSON.parse(X.toString("utf8").trim()),`
43
+ `}catch{return await T.truncate(G),""}}async findTailStart(T,$){let _=$;while(_>0){let G=Math.max(0,_-DT),X=Buffer.allocUnsafe(_-G);await T.read(X,0,X.length,G);let Y=X.lastIndexOf(10);if(Y>=0)return G+Y+1;_=G}return 0}}function wT(T){let $=Number(T.pragma("user_version")??0);if($===8)return;if($>0&&$!==8)T.exec(`
44
44
  DROP TABLE IF EXISTS parts_fts;
45
45
  DROP TABLE IF EXISTS surface_messages;
46
46
  DROP TABLE IF EXISTS parts;
@@ -182,7 +182,7 @@ CREATE VIRTUAL TABLE IF NOT EXISTS parts_fts USING fts5(
182
182
  seq UNINDEXED,
183
183
  tokenize = 'unicode61'
184
184
  );
185
- `),T.exec("PRAGMA user_version=8;")}var N_=PT("Service"),z_="session-surface-projection-v1\x00",S0=524288,j_=3,W_=new AbortController().signal,K_=/^acp-remote-workspace:[A-Za-z0-9_-]{43}$/,vT=`WITH RECURSIVE archive_members(
185
+ `),T.exec("PRAGMA user_version=8;")}var z_=hT("Service"),I_="session-surface-projection-v1\x00",f0=524288,j_=3,W_=new AbortController().signal,K_=/^acp-remote-workspace:[A-Za-z0-9_-]{43}$/,mT=`WITH RECURSIVE archive_members(
186
186
  source_kind, project_path, public_workspace_ref, session_id, archive_root_id,
187
187
  effective_archived_at, depth
188
188
  ) AS (
@@ -210,12 +210,12 @@ ranked_archive AS (
210
210
  ORDER BY depth ASC, archive_root_id ASC
211
211
  ) AS rank
212
212
  FROM archive_members
213
- )`,uT={readSession(T,$,_){return $?T.readAllValidated({noFollow:!0,signal:_,validateHandle:(G)=>RT($,T.getFilePath(),G)}):T.readAll({signal:_})}},P0=uT;function h1(T){P0=T}function P1(){P0=uT}function m1(){return S0}var t;function pT(){return U0.join(V0(),"index.db")}async function k_(){let T=pT();if(t&&t.path===T)return t.db;let $=(async()=>{let _=await T0(T);if(!_)return null;try{return ST(_),_}catch{return null}})();return t={path:T,db:$},$}function A_(){t=void 0}function x_(T){if(T&&typeof T==="object"){let $=T.text;if(typeof $==="string")return $}return null}function E_(T,$,_,G,X){T.prepare("DELETE FROM parts WHERE source_kind=? AND project_path=? AND session_id=?").run($,_,G),T.prepare("DELETE FROM parts_fts WHERE source_kind=? AND project_path=? AND session_id=?").run($,_,G);let Y=new Map;for(let U of X)if(U.type==="message_created")Y.set(U.data.messageId,U.data.role);let Q=T.prepare(`INSERT OR REPLACE INTO parts
213
+ )`,vT={readSession(T,$,_){return $?T.readAllValidated({noFollow:!0,signal:_,validateHandle:(G)=>fT($,T.getFilePath(),G)}):T.readAll({signal:_})}},m0=vT;function h1(T){m0=T}function P1(){m0=vT}function m1(){return f0}var t;function uT(){return B0.join(g0(),"index.db")}async function k_(){let T=uT();if(t&&t.path===T)return t.db;let $=(async()=>{let _=await $0(T);if(!_)return null;try{return wT(_),_}catch{return null}})();return t={path:T,db:$},$}function A_(){t=void 0}function x_(T){if(T&&typeof T==="object"){let $=T.text;if(typeof $==="string")return $}return null}function E_(T,$,_,G,X){T.prepare("DELETE FROM parts WHERE source_kind=? AND project_path=? AND session_id=?").run($,_,G),T.prepare("DELETE FROM parts_fts WHERE source_kind=? AND project_path=? AND session_id=?").run($,_,G);let Y=new Map;for(let U of X)if(U.type==="message_created")Y.set(U.data.messageId,U.data.role);let Q=T.prepare(`INSERT OR REPLACE INTO parts
214
214
  (source_kind, project_path, session_id, part_id, message_id, part_type, role,
215
215
  seq, timestamp, text)
216
216
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`),Z=T.prepare(`INSERT INTO parts_fts
217
217
  (text, source_kind, project_path, session_id, part_id, role, timestamp, seq)
218
- VALUES (?, ?, ?, ?, ?, ?, ?, ?)`);for(let U of X){if(U.type!=="part_created"&&U.type!=="part_updated")continue;if(U.data.partType!=="text")continue;let V=x_(U.data.payload);if(V===null)continue;let g=Y.get(U.data.messageId)??"assistant",O=U.seq??0;if(Q.run($,_,G,U.data.partId,U.data.messageId,U.data.partType,g,O,U.timestamp,V),g==="user"||g==="assistant")Z.run(V,$,_,G,U.data.partId,g,U.timestamp,O)}}function q_(T,$,_,G,X){let{metadata:Y,publicWorkspaceRef:Q}=_,Z=p(Q??Y.projectPath);T.prepare(`INSERT INTO sessions
218
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)`);for(let U of X){if(U.type!=="part_created"&&U.type!=="part_updated")continue;if(U.data.partType!=="text")continue;let V=x_(U.data.payload);if(V===null)continue;let g=Y.get(U.data.messageId)??"assistant",O=U.seq??0;if(Q.run($,_,G,U.data.partId,U.data.messageId,U.data.partType,g,O,U.timestamp,V),g==="user"||g==="assistant")Z.run(V,$,_,G,U.data.partId,g,U.timestamp,O)}}function q_(T,$,_,G,X){let{metadata:Y,publicWorkspaceRef:Q}=_,Z=l(Q??Y.projectPath);T.prepare(`INSERT INTO sessions
219
219
  (source_kind, project_path, session_id, root_id, parent_id, relation_type, title,
220
220
  agent_type, model, task_status, task_priority, task_kind, task_due_at,
221
221
  archived_at, last_message_time, project_sort_key,
@@ -238,31 +238,31 @@ ranked_archive AS (
238
238
  session_sort_key=excluded.session_sort_key,
239
239
  first_message_time=excluded.first_message_time, message_count=excluded.message_count,
240
240
  has_errors=excluded.has_errors, is_subagent=excluded.is_subagent,
241
- metadata_json=excluded.metadata_json, surface_digest=excluded.surface_digest`).run($,Y.projectPath,Y.sessionId,Y.rootId,Y.parentId??null,Y.relationType??null,Y.title??null,Y.agentType??null,Y.model??null,Y.taskStatus,Y.taskPriority??null,Y.taskKind??null,Y.taskDueAt??null,Y.archivedAt??null,Y.lastMessageTime,p(Y.projectPath),Q??null,Z,p(Y.sessionId),Y.firstMessageTime,Y.messageCount,Y.hasErrors?1:0,Y.relationType==="subagent"?1:0,JSON.stringify(Y),G,X)}function E(T){T.prepare(`UPDATE surface_projection_meta
241
+ metadata_json=excluded.metadata_json, surface_digest=excluded.surface_digest`).run($,Y.projectPath,Y.sessionId,Y.rootId,Y.parentId??null,Y.relationType??null,Y.title??null,Y.agentType??null,Y.model??null,Y.taskStatus,Y.taskPriority??null,Y.taskKind??null,Y.taskDueAt??null,Y.archivedAt??null,Y.lastMessageTime,l(Y.projectPath),Q??null,Z,l(Y.sessionId),Y.firstMessageTime,Y.messageCount,Y.hasErrors?1:0,Y.relationType==="subagent"?1:0,JSON.stringify(Y),G,X)}function E(T){T.prepare(`UPDATE surface_projection_meta
242
242
  SET catalog_revision=catalog_revision + 1 WHERE singleton=1`).run()}function D_(T,$,_,G,X,Y){T.prepare(`DELETE FROM surface_messages
243
243
  WHERE source_kind=? AND project_path=? AND session_id=?`).run($,_,G);let Q=new Map;for(let U of X)if(U.type==="message_created"&&typeof U.seq==="number")Q.set(U.seq,U.data.messageId);let Z=T.prepare(`INSERT INTO surface_messages
244
244
  (source_kind, project_path, session_id, message_seq, message_id,
245
245
  message_json, byte_count)
246
- VALUES (?, ?, ?, ?, ?, ?, ?)`);for(let U of Y){let V=h0.parse(U),g=lT(V.id),O=Q.get(g);if(!O)throw new L;let M=JSON.stringify(V);Z.run($,_,G,g,O,M,Buffer.byteLength(M))}}function lT(T){let $=/^surface-message:([0-9]+):/.exec(T),_=$?Number($[1]):Number.NaN;if(!Number.isSafeInteger(_)||_<0)throw new L;return _}function w_(T){let{metadata:$}=T,_={locator:T.publicWorkspaceRef===void 0?{version:2,sessionId:$.sessionId,workspace:{kind:"local",projectPath:$.projectPath}}:{version:2,sessionId:$.sessionId,workspace:{kind:"acp-remote",workspaceRef:T.publicWorkspaceRef}},...nT($,T.publicWorkspaceRef)};return I_("sha256").update(z_).update(JSON.stringify({catalogSummary:_,messages:T.surfaceMessages})).digest("hex")}function nT(T,$){let _=T.remoteWorkspace===void 0?void 0:S(T.remoteWorkspace);if(_===void 0!==($===void 0)||_&&d(_.collisionIdentity)!==T.projectPath||!A(T.sessionId)||!A(T.rootId)||T.parentId!==void 0&&!A(T.parentId)||T.relationType!==void 0&&T.relationType!=="subagent"&&T.relationType!=="fork"||!["queued","running","completed","failed","cancelled","interrupted"].includes(T.taskStatus)||!Number.isSafeInteger(T.messageCount)||T.messageCount<0||!T.firstMessageTime||!T.lastMessageTime||T.archivedAt!==void 0&&!T.archivedAt||T.selectedModelId!==void 0&&!T.selectedModelId)throw new L;let G={..._?j0(T.projectPath,_):{privateRoots:[]},bladeStorageRoots:[V0()]},X=T.relationType,Y=T.taskStatus,Q=mT(T.taskCompletedAt);return{displayCwd:_?.wirePath??T.projectPath,..._?{pathStyle:_.style}:{},...T.title!==void 0?{title:W0(T.title,G)}:{},rootId:T.rootId,...T.parentId!==void 0?{parentId:T.parentId}:{},...X!==void 0?{relationType:X}:{},taskStatus:Y,...Q!==void 0?{taskCompletedAt:Q}:{},messageCount:T.messageCount,firstMessageTime:T.firstMessageTime,lastMessageTime:T.lastMessageTime,hasErrors:T.hasErrors,...T.archivedAt!==void 0?{archivedAt:T.archivedAt}:{},...T.selectedModelId!==void 0?{selectedModelId:W0(T.selectedModelId,G)}:{}}}function m0(T,$,_,G){return T.prepare(`SELECT EXISTS(
246
+ VALUES (?, ?, ?, ?, ?, ?, ?)`);for(let U of Y){let V=P0.parse(U),g=pT(V.id),O=Q.get(g);if(!O)throw new L;let M=JSON.stringify(V);Z.run($,_,G,g,O,M,Buffer.byteLength(M))}}function pT(T){let $=/^surface-message:([0-9]+):/.exec(T),_=$?Number($[1]):Number.NaN;if(!Number.isSafeInteger(_)||_<0)throw new L;return _}function w_(T){let{metadata:$}=T,_={locator:T.publicWorkspaceRef===void 0?{version:2,sessionId:$.sessionId,workspace:{kind:"local",projectPath:$.projectPath}}:{version:2,sessionId:$.sessionId,workspace:{kind:"acp-remote",workspaceRef:T.publicWorkspaceRef}},...lT($,T.publicWorkspaceRef)};return N_("sha256").update(I_).update(JSON.stringify({catalogSummary:_,messages:T.surfaceMessages})).digest("hex")}function lT(T,$){let _=T.remoteWorkspace===void 0?void 0:S(T.remoteWorkspace);if(_===void 0!==($===void 0)||_&&s(_.collisionIdentity)!==T.projectPath||!A(T.sessionId)||!A(T.rootId)||T.parentId!==void 0&&!A(T.parentId)||T.relationType!==void 0&&T.relationType!=="subagent"&&T.relationType!=="fork"||!["queued","running","completed","failed","cancelled","interrupted"].includes(T.taskStatus)||!Number.isSafeInteger(T.messageCount)||T.messageCount<0||!T.firstMessageTime||!T.lastMessageTime||T.archivedAt!==void 0&&!T.archivedAt||T.selectedModelId!==void 0&&!T.selectedModelId)throw new L;let G={..._?W0(T.projectPath,_):{privateRoots:[]},bladeStorageRoots:[g0()]},X=T.relationType,Y=T.taskStatus,Q=PT(T.taskCompletedAt);return{displayCwd:_?.wirePath??T.projectPath,..._?{pathStyle:_.style}:{},...T.title!==void 0?{title:K0(T.title,G)}:{},rootId:T.rootId,...T.parentId!==void 0?{parentId:T.parentId}:{},...X!==void 0?{relationType:X}:{},taskStatus:Y,...Q!==void 0?{taskCompletedAt:Q}:{},messageCount:T.messageCount,firstMessageTime:T.firstMessageTime,lastMessageTime:T.lastMessageTime,hasErrors:T.hasErrors,...T.archivedAt!==void 0?{archivedAt:T.archivedAt}:{},...T.selectedModelId!==void 0?{selectedModelId:K0(T.selectedModelId,G)}:{}}}function v0(T,$,_,G){return T.prepare(`SELECT EXISTS(
247
247
  SELECT 1 FROM sessions
248
248
  WHERE source_kind=? AND project_path=? AND session_id=?
249
249
  UNION ALL
250
250
  SELECT 1 FROM surface_messages
251
251
  WHERE source_kind=? AND project_path=? AND session_id=?
252
- ) AS present`).get($,_,G,$,_,G)?.present===1}function iT(T,$,_,G){let X=m0(T,$,_,G);if(X)T.prepare(`UPDATE projection_state SET stat_fingerprint=''
253
- WHERE source_kind=? AND project_path=? AND session_id=?`).run($,_,G);for(let Y of["surface_messages","sessions","parts","parts_fts"])T.prepare(`DELETE FROM ${Y} WHERE source_kind=? AND project_path=? AND session_id=?`).run($,_,G);return X}function o(T,$,_,G){let X=iT(T,$,_,G);return T.prepare("DELETE FROM projection_state WHERE source_kind=? AND project_path=? AND session_id=?").run($,_,G),X}function Z0(T,$,_,G){let X=T.prepare(`SELECT project_path, session_id FROM sessions
254
- WHERE source_kind=? AND source_file_path=?`).all($,_),Y=!1;for(let Q of X){if(Q.project_path===G?.projectPath&&Q.session_id===G.sessionId)continue;Y=iT(T,$,Q.project_path,Q.session_id)||Y}return Y}function f0(T,$,_){let G=Z0(T,$,_);return T.prepare("DELETE FROM projection_state WHERE source_kind=? AND source_file_path=?").run($,_),G}function x0(T,$,_,G,X,Y,Q,Z,U){T.prepare(`INSERT INTO projection_state
252
+ ) AS present`).get($,_,G,$,_,G)?.present===1}function nT(T,$,_,G){let X=v0(T,$,_,G);if(X)T.prepare(`UPDATE projection_state SET stat_fingerprint=''
253
+ WHERE source_kind=? AND project_path=? AND session_id=?`).run($,_,G);for(let Y of["surface_messages","sessions","parts","parts_fts"])T.prepare(`DELETE FROM ${Y} WHERE source_kind=? AND project_path=? AND session_id=?`).run($,_,G);return X}function r(T,$,_,G){let X=nT(T,$,_,G);return T.prepare("DELETE FROM projection_state WHERE source_kind=? AND project_path=? AND session_id=?").run($,_,G),X}function V0(T,$,_,G){let X=T.prepare(`SELECT project_path, session_id FROM sessions
254
+ WHERE source_kind=? AND source_file_path=?`).all($,_),Y=!1;for(let Q of X){if(Q.project_path===G?.projectPath&&Q.session_id===G.sessionId)continue;Y=nT(T,$,Q.project_path,Q.session_id)||Y}return Y}function b0(T,$,_){let G=V0(T,$,_);return T.prepare("DELETE FROM projection_state WHERE source_kind=? AND source_file_path=?").run($,_),G}function E0(T,$,_,G,X,Y,Q,Z,U){T.prepare(`INSERT INTO projection_state
255
255
  (source_kind, source_file_path, project_path, session_id, last_seq, file_size,
256
256
  mtime_ms, stat_fingerprint)
257
257
  VALUES (?, ?, ?, ?, ?, ?, ?, ?)
258
258
  ON CONFLICT(source_kind, source_file_path) DO UPDATE SET
259
259
  project_path=excluded.project_path, session_id=excluded.session_id,
260
260
  last_seq=excluded.last_seq, file_size=excluded.file_size,
261
- mtime_ms=excluded.mtime_ms, stat_fingerprint=excluded.stat_fingerprint`).run($,U,_,G,X,Y,Q,Z)}function h(T){return[T.dev,T.ino,T.size,T.mtimeNs,T.ctimeNs].join(":")}async function E0(T,$,_,G,X,Y="local",Q){if(Q?.throwIfAborted(),Y==="acp-remote")return s(_,async(Z)=>{let U=r(Z,$),V=X??U;if(V!==U)throw new D("remote-session-file-path");return R0(T,$,_,G,V,Y,Z,Q)});return R0(T,$,_,G,X??y0(_,$),Y,void 0,Q)}async function R0(T,$,_,G,X,Y,Q,Z){if(Z?.throwIfAborted(),Y==="acp-remote"){if(!Q)throw new D("remote-session-scope");try{await q0(Q,X),Z?.throwIfAborted()}catch(F){if(Z?.aborted)throw F;if(F.code!=="ENOENT")throw F;return Z?.throwIfAborted(),T.transaction(()=>{if(o(T,Y,_,$))E(T)}),!0}}let U;try{U=await w0(X,{bigint:!0}),Z?.throwIfAborted()}catch(F){if(Z?.aborted)throw F;if(F.code!=="ENOENT")throw F;return T.transaction(()=>{if(f0(T,Y,X))E(T)}),!0}let V=T.prepare(`SELECT project_path, session_id, last_seq, file_size, mtime_ms, stat_fingerprint
262
- FROM projection_state WHERE source_kind=? AND source_file_path=?`).get(Y,X);if(Y==="local"&&V&&V.stat_fingerprint===h(U)&&(V.project_path===null||m0(T,Y,V.project_path,V.session_id)))return!1;let g=new K(X),O;try{let F=U,k;for(let e=0;e<j_;e+=1){Z?.throwIfAborted();let p0=await P0.readSession(g,Q,Z??W_);Z?.throwIfAborted();let B0=await w0(X,{bigint:!0});if(Z?.throwIfAborted(),h(F)===h(B0)){O=p0,U=B0,k=p0;break}F=B0}if(!k)throw new L;O=k}catch(F){if(Z?.aborted)throw F;let k=F.code;if(k!=="ENOENT"){if(Y==="acp-remote"){if(F instanceof D)throw F;if(k!==void 0)throw new D("remote-session-read")}throw F}return T.transaction(()=>{if(f0(T,Y,X))E(T)}),!0}if(Y==="acp-remote"&&O.length===0){try{await q0(Q,X)}catch(F){if(Z?.aborted)throw F;if(F.code==="ENOENT")return T.transaction(()=>{if(o(T,Y,_,$))E(T)}),!0;throw F}throw new D("remote-session-empty")}Z?.throwIfAborted();let M=Y==="local"?O.find((F)=>F.type==="session_created"):void 0,I=Y==="local"&&M!==void 0&&Object.hasOwn(M.data,"remoteWorkspace"),z=null;if(Y==="acp-remote"){let F=bT(O,$,_);z=S(F.data.remoteWorkspace)}else if(I)S(M.data.remoteWorkspace);let j=O.reduce((F,k)=>typeof k.seq==="number"&&k.seq>F?k.seq:F,0),B=l(O),C=I?null:G(O,$,_,Y,X),N=C?.remoteWorkspace;if(Y==="acp-remote"){if(!C||C.sessionId!==$||C.projectPath!==_||N===void 0)throw new D("remote-session-metadata");let F=S(N);if(!z||F.style!==z.style||F.wirePath!==z.wirePath||F.exactIdentity!==z.exactIdentity||F.collisionIdentity!==z.collisionIdentity)throw new D("remote-session-descriptor");if(d(F.collisionIdentity)!==_)throw new D("remote-session-project-path")}if(O.length===0||!C||Y==="local"&&N!==void 0)return Z?.throwIfAborted(),T.transaction(()=>{let F=Z0(T,Y,X);if(x0(T,Y,null,$,j,Number(U.size),Number(U.mtimeMs),h(U),X),F)E(T)}),!0;let w=z&&Q?await t0(Q,z):void 0;Z?.throwIfAborted();let P=kT(O,{...z?j0(_,z):{privateRoots:[]},bladeStorageRoots:[V0()]}),v0={metadata:C,...w!==void 0?{publicWorkspaceRef:w}:{},surfaceMessages:P},u0=w_(v0),R=T.prepare(`SELECT last_message_time, source_file_path FROM sessions
263
- WHERE source_kind=? AND project_path=? AND session_id=?`).get(Y,C.projectPath,C.sessionId),sT=Y==="acp-remote"&&Q?r(Q,C.sessionId):y0(C.projectPath,C.sessionId),aT=U0.resolve(X)===U0.resolve(sT);if(R&&R.source_file_path!==X&&!aT&&typeof R.last_message_time==="string"&&R.last_message_time>C.lastMessageTime)return Z?.throwIfAborted(),T.transaction(()=>{let F=Z0(T,Y,X,C);if(x0(T,Y,C.projectPath,C.sessionId,j,Number(U.size),Number(U.mtimeMs),h(U),X),F)E(T)}),!0;return Z?.throwIfAborted(),T.transaction(()=>{let F=T.prepare(`SELECT surface_digest FROM sessions
264
- WHERE source_kind=? AND project_path=? AND session_id=?`).get(Y,C.projectPath,C.sessionId),e=Z0(T,Y,X,C)||F?.surface_digest!==u0;if(R?.source_file_path===X&&typeof R.last_message_time==="string"&&R.last_message_time>C.lastMessageTime)T.prepare(`UPDATE projection_state SET stat_fingerprint=''
265
- WHERE source_kind=? AND project_path=? AND session_id=?`).run(Y,C.projectPath,C.sessionId);if(q_(T,Y,v0,u0,X),E_(T,Y,C.projectPath,C.sessionId,B),D_(T,Y,C.projectPath,C.sessionId,B,P),x0(T,Y,C.projectPath,C.sessionId,j,Number(U.size),Number(U.mtimeMs),h(U),X),e)E(T)}),!0}var fT=new WeakMap;function b0(T,$,_,G){let X=T.prepare(`SELECT session_id FROM projection_state
261
+ mtime_ms=excluded.mtime_ms, stat_fingerprint=excluded.stat_fingerprint`).run($,U,_,G,X,Y,Q,Z)}function m(T){return[T.dev,T.ino,T.size,T.mtimeNs,T.ctimeNs].join(":")}async function q0(T,$,_,G,X,Y="local",Q){if(Q?.throwIfAborted(),Y==="acp-remote")return a(_,async(Z)=>{let U=e(Z,$),V=X??U;if(V!==U)throw new D("remote-session-file-path");return R0(T,$,_,G,V,Y,Z,Q)});return R0(T,$,_,G,X??h0(_,$),Y,void 0,Q)}async function R0(T,$,_,G,X,Y,Q,Z){if(Z?.throwIfAborted(),Y==="acp-remote"){if(!Q)throw new D("remote-session-scope");try{await D0(Q,X),Z?.throwIfAborted()}catch(F){if(Z?.aborted)throw F;if(F.code!=="ENOENT")throw F;return Z?.throwIfAborted(),T.transaction(()=>{if(r(T,Y,_,$))E(T)}),!0}}let U;try{U=await S0(X,{bigint:!0}),Z?.throwIfAborted()}catch(F){if(Z?.aborted)throw F;if(F.code!=="ENOENT")throw F;return T.transaction(()=>{if(b0(T,Y,X))E(T)}),!0}let V=T.prepare(`SELECT project_path, session_id, last_seq, file_size, mtime_ms, stat_fingerprint
262
+ FROM projection_state WHERE source_kind=? AND source_file_path=?`).get(Y,X);if(Y==="local"&&V&&V.stat_fingerprint===m(U)&&(V.project_path===null||v0(T,Y,V.project_path,V.session_id)))return!1;let g=new K(X),O;try{let F=U,k;for(let T0=0;T0<j_;T0+=1){Z?.throwIfAborted();let l0=await m0.readSession(g,Q,Z??W_);Z?.throwIfAborted();let C0=await S0(X,{bigint:!0});if(Z?.throwIfAborted(),m(F)===m(C0)){O=l0,U=C0,k=l0;break}F=C0}if(!k)throw new L;O=k}catch(F){if(Z?.aborted)throw F;let k=F.code;if(k!=="ENOENT"){if(Y==="acp-remote"){if(F instanceof D)throw F;if(k!==void 0)throw new D("remote-session-read")}throw F}return T.transaction(()=>{if(b0(T,Y,X))E(T)}),!0}if(Y==="acp-remote"&&O.length===0){try{await D0(Q,X)}catch(F){if(Z?.aborted)throw F;if(F.code==="ENOENT")return T.transaction(()=>{if(r(T,Y,_,$))E(T)}),!0;throw F}throw new D("remote-session-empty")}Z?.throwIfAborted();let M=Y==="local"?O.find((F)=>F.type==="session_created"):void 0,N=Y==="local"&&M!==void 0&&Object.hasOwn(M.data,"remoteWorkspace"),I=null;if(Y==="acp-remote"){let F=bT(O,$,_);I=S(F.data.remoteWorkspace)}else if(N)S(M.data.remoteWorkspace);let W=O.reduce((F,k)=>typeof k.seq==="number"&&k.seq>F?k.seq:F,0),B=n(O),C=N?null:G(O,$,_,Y,X),z=C?.remoteWorkspace;if(Y==="acp-remote"){if(!C||C.sessionId!==$||C.projectPath!==_||z===void 0)throw new D("remote-session-metadata");let F=S(z);if(!I||F.style!==I.style||F.wirePath!==I.wirePath||F.exactIdentity!==I.exactIdentity||F.collisionIdentity!==I.collisionIdentity)throw new D("remote-session-descriptor");if(s(F.collisionIdentity)!==_)throw new D("remote-session-project-path")}if(O.length===0||!C||Y==="local"&&z!==void 0)return Z?.throwIfAborted(),T.transaction(()=>{let F=V0(T,Y,X);if(E0(T,Y,null,$,W,Number(U.size),Number(U.mtimeMs),m(U),X),F)E(T)}),!0;let w=I&&Q?await o0(Q,I):void 0;Z?.throwIfAborted();let v=KT(O,{...I?W0(_,I):{privateRoots:[]},bladeStorageRoots:[g0()]}),u0={metadata:C,...w!==void 0?{publicWorkspaceRef:w}:{},surfaceMessages:v},p0=w_(u0),b=T.prepare(`SELECT last_message_time, source_file_path FROM sessions
263
+ WHERE source_kind=? AND project_path=? AND session_id=?`).get(Y,C.projectPath,C.sessionId),dT=Y==="acp-remote"&&Q?e(Q,C.sessionId):h0(C.projectPath,C.sessionId),sT=B0.resolve(X)===B0.resolve(dT);if(b&&b.source_file_path!==X&&!sT&&typeof b.last_message_time==="string"&&b.last_message_time>C.lastMessageTime)return Z?.throwIfAborted(),T.transaction(()=>{let F=V0(T,Y,X,C);if(E0(T,Y,C.projectPath,C.sessionId,W,Number(U.size),Number(U.mtimeMs),m(U),X),F)E(T)}),!0;return Z?.throwIfAborted(),T.transaction(()=>{let F=T.prepare(`SELECT surface_digest FROM sessions
264
+ WHERE source_kind=? AND project_path=? AND session_id=?`).get(Y,C.projectPath,C.sessionId),T0=V0(T,Y,X,C)||F?.surface_digest!==p0;if(b?.source_file_path===X&&typeof b.last_message_time==="string"&&b.last_message_time>C.lastMessageTime)T.prepare(`UPDATE projection_state SET stat_fingerprint=''
265
+ WHERE source_kind=? AND project_path=? AND session_id=?`).run(Y,C.projectPath,C.sessionId);if(q_(T,Y,u0,p0,X),E_(T,Y,C.projectPath,C.sessionId,B),D_(T,Y,C.projectPath,C.sessionId,B,v),E0(T,Y,C.projectPath,C.sessionId,W,Number(U.size),Number(U.mtimeMs),m(U),X),T0)E(T)}),!0}var ST=new WeakMap;function y0(T,$,_,G){let X=T.prepare(`SELECT session_id FROM projection_state
266
266
  WHERE source_kind=? AND project_path=?
267
267
  UNION
268
268
  SELECT session_id FROM sessions
@@ -275,7 +275,7 @@ ranked_archive AS (
275
275
  WHERE source_kind=? AND project_path=?
276
276
  UNION
277
277
  SELECT session_id FROM surface_messages
278
- WHERE source_kind=? AND project_path=?`).all($,_,$,_,$,_,$,_,$,_);for(let Y of X)if(!G.has(Y.session_id)){if(o(T,$,_,Y.session_id))E(T)}}async function S_(T,$,_,G){G?.throwIfAborted();try{await s(_,async(X)=>{let Y=(await D0(String(X))).flatMap((V)=>{if(!V.endsWith(".jsonl"))return[];let g=V.slice(0,-6);if(!A(g))return[];return[{filePath:r(X,g),sessionId:g}]});G?.throwIfAborted();let Q=new Set(Y.map((V)=>V.sessionId)),Z=Math.min(32,Y.length),U=0;await Promise.all(Array.from({length:Z},async()=>{while(U<Y.length){G?.throwIfAborted();let V=Y[U++];if(!V)continue;await R0(T,V.sessionId,_,$,V.filePath,"acp-remote",X,G)}})),G?.throwIfAborted(),T.transaction(()=>{b0(T,"acp-remote",_,Q)})})}catch(X){if(G?.aborted)throw X;if(X.code!=="ENOENT")throw X;T.transaction(()=>{b0(T,"acp-remote",_,new Set)})}}async function v1(T,$,_){_?.throwIfAborted();let G=await yT();_?.throwIfAborted();for(let Q of G)_?.throwIfAborted(),await S_(T,$,String(Q),_);let X=new Set(G.map(String)),Y=T.prepare(`SELECT project_path FROM projection_state WHERE source_kind='acp-remote'
278
+ WHERE source_kind=? AND project_path=?`).all($,_,$,_,$,_,$,_,$,_);for(let Y of X)if(!G.has(Y.session_id)){if(r(T,$,_,Y.session_id))E(T)}}async function S_(T,$,_,G){G?.throwIfAborted();try{await a(_,async(X)=>{let Y=(await w0(String(X))).flatMap((V)=>{if(!V.endsWith(".jsonl"))return[];let g=V.slice(0,-6);if(!A(g))return[];return[{filePath:e(X,g),sessionId:g}]});G?.throwIfAborted();let Q=new Set(Y.map((V)=>V.sessionId)),Z=Math.min(32,Y.length),U=0;await Promise.all(Array.from({length:Z},async()=>{while(U<Y.length){G?.throwIfAborted();let V=Y[U++];if(!V)continue;await R0(T,V.sessionId,_,$,V.filePath,"acp-remote",X,G)}})),G?.throwIfAborted(),T.transaction(()=>{y0(T,"acp-remote",_,Q)})})}catch(X){if(G?.aborted)throw X;if(X.code!=="ENOENT")throw X;T.transaction(()=>{y0(T,"acp-remote",_,new Set)})}}async function v1(T,$,_){_?.throwIfAborted();let G=await RT();_?.throwIfAborted();for(let Q of G)_?.throwIfAborted(),await S_(T,$,String(Q),_);let X=new Set(G.map(String)),Y=T.prepare(`SELECT project_path FROM projection_state WHERE source_kind='acp-remote'
279
279
  UNION
280
280
  SELECT project_path FROM sessions WHERE source_kind='acp-remote'
281
281
  UNION
@@ -283,18 +283,18 @@ ranked_archive AS (
283
283
  UNION
284
284
  SELECT project_path FROM parts_fts WHERE source_kind='acp-remote'
285
285
  UNION
286
- SELECT project_path FROM surface_messages WHERE source_kind='acp-remote'`).all();for(let Q of Y)if(_?.throwIfAborted(),!X.has(Q.project_path))T.transaction(()=>{b0(T,"acp-remote",Q.project_path,new Set)})}async function f_(T,$,_=0){let G=fT.get(T)??{};if(fT.set(T,G),G.inFlight)return G.inFlight;if(_>0&&G.lastCompletedAt!==void 0&&Date.now()-G.lastCompletedAt<=_)return;let X=R_(T,$);G.inFlight=X;try{await X,G.lastCompletedAt=Date.now()}finally{if(G.inFlight===X)G.inFlight=void 0}}async function R_(T,$){let _=new Set,G=await hT(),Y=(await Promise.all(G.map(async(B)=>{if(B.kind==="local")try{return(await D0(B.storagePath)).flatMap((N)=>{if(!N.endsWith(".jsonl"))return[];let w=N.slice(0,-6);if(!A(w))return[];return[{kind:"local",filePath:U0.join(B.storagePath,N),projectPath:B.projectPath,sessionId:w}]})}catch{return[]}return s(B.storagePath,async(C)=>{return(await D0(String(C))).flatMap((w)=>{if(!w.endsWith(".jsonl"))return[];let P=w.slice(0,-6);if(!A(P))return[];return[{kind:"acp-remote",filePath:r(C,P),projectPath:B.projectPath,sessionId:P}]})})}))).flat();for(let B of Y)_.add(`${B.kind}\x00${B.filePath}`);let Q=T.prepare(`SELECT source_kind, source_file_path, project_path, session_id, last_seq,
287
- file_size, mtime_ms, stat_fingerprint FROM projection_state`).all();T.transaction(()=>{for(let B of Q)if(!_.has(`${B.source_kind}\x00${B.source_file_path}`)){if(f0(T,B.source_kind,B.source_file_path))E(T)}});let Z=new Map(Q.map((B)=>[`${B.source_kind}\x00${B.source_file_path}`,B])),U=[],V=Math.min(128,Y.length),g=0;await Promise.all(Array.from({length:V},async()=>{while(g<Y.length){let B=Y[g++];if(!B)continue;if(B.kind==="acp-remote"){U.push(B);continue}try{let C=await w0(B.filePath,{bigint:!0}),N=Z.get(`${B.kind}\x00${B.filePath}`);if(N&&N.stat_fingerprint===h(C)&&(N.project_path===null||m0(T,B.kind,N.project_path,N.session_id)))continue}catch(C){if(C.code!=="ENOENT")throw C}U.push(B)}}));let O=Math.min(32,U.length),M=0;await Promise.all(Array.from({length:O},async()=>{while(M<U.length){let B=U[M++];if(!B)continue;try{if(B.kind==="acp-remote")await E0(T,B.sessionId,B.projectPath,$,B.filePath,"acp-remote");else await E0(T,B.sessionId,B.projectPath,$,B.filePath,"local")}catch(C){let N=C.code;if(B.kind==="acp-remote"){if(N==="ENOENT")continue;throw C}if(N==="acp_remote_workspace_state_invalid")throw C;if(N!=="ENOENT")N_.warn(`[SessionService] Skipping invalid session transcript: ${B.sessionId}`)}}}));let I=T.prepare(`SELECT p.source_file_path, p.project_path, p.session_id
286
+ SELECT project_path FROM surface_messages WHERE source_kind='acp-remote'`).all();for(let Q of Y)if(_?.throwIfAborted(),!X.has(Q.project_path))T.transaction(()=>{y0(T,"acp-remote",Q.project_path,new Set)})}async function f_(T,$,_=0){let G=ST.get(T)??{};if(ST.set(T,G),G.inFlight)return G.inFlight;if(_>0&&G.lastCompletedAt!==void 0&&Date.now()-G.lastCompletedAt<=_)return;let X=b_(T,$);G.inFlight=X;try{await X,G.lastCompletedAt=Date.now()}finally{if(G.inFlight===X)G.inFlight=void 0}}async function b_(T,$){let _=new Set,G=await yT(),Y=(await Promise.all(G.map(async(B)=>{if(B.kind==="local")try{return(await w0(B.storagePath)).flatMap((z)=>{if(!z.endsWith(".jsonl"))return[];let w=z.slice(0,-6);if(!A(w))return[];return[{kind:"local",filePath:B0.join(B.storagePath,z),projectPath:B.projectPath,sessionId:w}]})}catch{return[]}return a(B.storagePath,async(C)=>{return(await w0(String(C))).flatMap((w)=>{if(!w.endsWith(".jsonl"))return[];let v=w.slice(0,-6);if(!A(v))return[];return[{kind:"acp-remote",filePath:e(C,v),projectPath:B.projectPath,sessionId:v}]})})}))).flat();for(let B of Y)_.add(`${B.kind}\x00${B.filePath}`);let Q=T.prepare(`SELECT source_kind, source_file_path, project_path, session_id, last_seq,
287
+ file_size, mtime_ms, stat_fingerprint FROM projection_state`).all();T.transaction(()=>{for(let B of Q)if(!_.has(`${B.source_kind}\x00${B.source_file_path}`)){if(b0(T,B.source_kind,B.source_file_path))E(T)}});let Z=new Map(Q.map((B)=>[`${B.source_kind}\x00${B.source_file_path}`,B])),U=[],V=Math.min(128,Y.length),g=0;await Promise.all(Array.from({length:V},async()=>{while(g<Y.length){let B=Y[g++];if(!B)continue;if(B.kind==="acp-remote"){U.push(B);continue}try{let C=await S0(B.filePath,{bigint:!0}),z=Z.get(`${B.kind}\x00${B.filePath}`);if(z&&z.stat_fingerprint===m(C)&&(z.project_path===null||v0(T,B.kind,z.project_path,z.session_id)))continue}catch(C){if(C.code!=="ENOENT")throw C}U.push(B)}}));let O=Math.min(32,U.length),M=0;await Promise.all(Array.from({length:O},async()=>{while(M<U.length){let B=U[M++];if(!B)continue;try{if(B.kind==="acp-remote")await q0(T,B.sessionId,B.projectPath,$,B.filePath,"acp-remote");else await q0(T,B.sessionId,B.projectPath,$,B.filePath,"local")}catch(C){let z=C.code;if(B.kind==="acp-remote"){if(z==="ENOENT")continue;throw C}if(z==="acp_remote_workspace_state_invalid")throw C;if(z!=="ENOENT")z_.warn(`[SessionService] Skipping invalid session transcript: ${B.sessionId}`)}}}));let N=T.prepare(`SELECT p.source_file_path, p.project_path, p.session_id
288
288
  FROM projection_state p
289
289
  WHERE p.source_kind='local' AND p.project_path IS NOT NULL
290
290
  AND (p.stat_fingerprint='' OR NOT EXISTS (
291
291
  SELECT 1 FROM sessions s WHERE s.source_kind=p.source_kind
292
292
  AND s.project_path=p.project_path AND s.session_id=p.session_id
293
- ))`).all();T.transaction(()=>{for(let B of I)T.prepare(`UPDATE projection_state SET stat_fingerprint=''
294
- WHERE source_kind='local' AND source_file_path=?`).run(B.source_file_path)});for(let B of I)await E0(T,B.session_id,B.project_path,$,B.source_file_path);let z=T.prepare(`SELECT source_kind, project_path, session_id FROM sessions WHERE source_kind='acp-remote'
293
+ ))`).all();T.transaction(()=>{for(let B of N)T.prepare(`UPDATE projection_state SET stat_fingerprint=''
294
+ WHERE source_kind='local' AND source_file_path=?`).run(B.source_file_path)});for(let B of N)await q0(T,B.session_id,B.project_path,$,B.source_file_path);let I=T.prepare(`SELECT source_kind, project_path, session_id FROM sessions WHERE source_kind='acp-remote'
295
295
  UNION SELECT source_kind, project_path, session_id FROM parts WHERE source_kind='acp-remote'
296
296
  UNION SELECT source_kind, project_path, session_id FROM parts_fts WHERE source_kind='acp-remote'
297
- UNION SELECT source_kind, project_path, session_id FROM surface_messages WHERE source_kind='acp-remote'`).all(),j=new Set(Y.filter((B)=>B.kind==="acp-remote").map((B)=>`${B.projectPath}\x00${B.sessionId}`));for(let B of z)if(!j.has(`${B.project_path}\x00${B.session_id}`))T.transaction(()=>{if(o(T,"acp-remote",B.project_path,B.session_id))E(T)})}function u1(T,$,_,G="local"){T.transaction(()=>{if(o(T,G,_,$))E(T)})}async function p1(T){let{rm:$}=await import("node:fs/promises");A_();let _=pT();for(let Y of["","-wal","-shm"])await $(`${_}${Y}`,{force:!0}).catch(()=>{return});let G=await k_();if(!G)return null;return await f_(G,T),G.prepare("SELECT COUNT(*) c FROM sessions").get()?.c??0}function cT(T){try{let $=JSON.parse(T.metadata_json);if(!$||typeof $!=="object"||Array.isArray($))throw new L;let _=$,G=p(T.public_workspace_ref??T.project_path);if(_.sessionId!==T.session_id||_.projectPath!==T.project_path||_.rootId!==T.root_id||(_.parentId??null)!==T.parent_id||(_.relationType??null)!==T.relation_type||_.taskStatus!==T.task_status||T.relation_type!==null&&T.relation_type!=="subagent"&&T.relation_type!=="fork"||!Number.isSafeInteger(T.message_count)||T.message_count<0||T.has_errors!==0&&T.has_errors!==1||T.is_subagent!==0&&T.is_subagent!==1||_.firstMessageTime!==T.first_message_time||_.lastMessageTime!==T.last_message_time||(_.title??null)!==T.title||(_.archivedAt??null)!==T.archived_at||_.messageCount!==T.message_count||Number(_.hasErrors)!==T.has_errors||Number(_.relationType==="subagent")!==T.is_subagent||T.public_workspace_sort_key!==G||T.session_sort_key!==p(T.session_id)||!/^[a-f0-9]{64}$/.test(T.surface_digest)||!T.stat_fingerprint||T.source_kind==="local"&&(T.public_workspace_ref!==null||_.remoteWorkspace!==void 0)||T.source_kind==="acp-remote"&&(T.public_workspace_ref===null||!K_.test(T.public_workspace_ref)||_.remoteWorkspace===void 0))throw new L;let X=T.effective_archived_at?{..._,archivedAt:T.effective_archived_at,archivedBySessionId:T.archive_root_id}:_,Y=nT(X,T.public_workspace_ref??void 0);return{sourceKind:T.source_kind,projectPath:T.project_path,sessionId:T.session_id,...T.public_workspace_ref===null?{}:{publicWorkspaceRef:T.public_workspace_ref},publicWorkspaceSortKey:T.public_workspace_sort_key,surfaceDigest:T.surface_digest,transcriptFingerprint:T.stat_fingerprint,lastMessageTime:T.last_message_time,sessionSortKey:T.session_sort_key,summary:Y}}catch{throw new L}}function l1(T,$){if(!A($))throw new L;try{return T.prepare(`${vT}
297
+ UNION SELECT source_kind, project_path, session_id FROM surface_messages WHERE source_kind='acp-remote'`).all(),W=new Set(Y.filter((B)=>B.kind==="acp-remote").map((B)=>`${B.projectPath}\x00${B.sessionId}`));for(let B of I)if(!W.has(`${B.project_path}\x00${B.session_id}`))T.transaction(()=>{if(r(T,"acp-remote",B.project_path,B.session_id))E(T)})}function u1(T,$,_,G="local"){T.transaction(()=>{if(r(T,G,_,$))E(T)})}async function p1(T){let{rm:$}=await import("node:fs/promises");A_();let _=uT();for(let Y of["","-wal","-shm"])await $(`${_}${Y}`,{force:!0}).catch(()=>{return});let G=await k_();if(!G)return null;return await f_(G,T),G.prepare("SELECT COUNT(*) c FROM sessions").get()?.c??0}function iT(T){try{let $=JSON.parse(T.metadata_json);if(!$||typeof $!=="object"||Array.isArray($))throw new L;let _=$,G=l(T.public_workspace_ref??T.project_path);if(_.sessionId!==T.session_id||_.projectPath!==T.project_path||_.rootId!==T.root_id||(_.parentId??null)!==T.parent_id||(_.relationType??null)!==T.relation_type||_.taskStatus!==T.task_status||T.relation_type!==null&&T.relation_type!=="subagent"&&T.relation_type!=="fork"||!Number.isSafeInteger(T.message_count)||T.message_count<0||T.has_errors!==0&&T.has_errors!==1||T.is_subagent!==0&&T.is_subagent!==1||_.firstMessageTime!==T.first_message_time||_.lastMessageTime!==T.last_message_time||(_.title??null)!==T.title||(_.archivedAt??null)!==T.archived_at||_.messageCount!==T.message_count||Number(_.hasErrors)!==T.has_errors||Number(_.relationType==="subagent")!==T.is_subagent||T.public_workspace_sort_key!==G||T.session_sort_key!==l(T.session_id)||!/^[a-f0-9]{64}$/.test(T.surface_digest)||!T.stat_fingerprint||T.source_kind==="local"&&(T.public_workspace_ref!==null||_.remoteWorkspace!==void 0)||T.source_kind==="acp-remote"&&(T.public_workspace_ref===null||!K_.test(T.public_workspace_ref)||_.remoteWorkspace===void 0))throw new L;let X=T.effective_archived_at?{..._,archivedAt:T.effective_archived_at,archivedBySessionId:T.archive_root_id}:_,Y=lT(X,T.public_workspace_ref??void 0);return{sourceKind:T.source_kind,projectPath:T.project_path,sessionId:T.session_id,...T.public_workspace_ref===null?{}:{publicWorkspaceRef:T.public_workspace_ref},publicWorkspaceSortKey:T.public_workspace_sort_key,surfaceDigest:T.surface_digest,transcriptFingerprint:T.stat_fingerprint,lastMessageTime:T.last_message_time,sessionSortKey:T.session_sort_key,summary:Y}}catch{throw new L}}function l1(T,$){if(!A($))throw new L;try{return T.prepare(`${mT}
298
298
  SELECT s.source_kind, s.project_path, s.session_id, s.root_id, s.parent_id,
299
299
  s.relation_type, s.task_status, s.first_message_time,
300
300
  s.last_message_time, s.title, s.archived_at, s.message_count,
@@ -313,12 +313,12 @@ ranked_archive AS (
313
313
  AND a.session_id=s.session_id AND a.rank=1
314
314
  WHERE s.session_id=?
315
315
  ORDER BY s.source_kind DESC, s.public_workspace_sort_key ASC,
316
- s.session_sort_key ASC`).all($).map(cT)}catch{throw new L}}function b_(T){let $=T.prepare("SELECT catalog_revision FROM surface_projection_meta WHERE singleton=1").get()?.catalog_revision;if(!Number.isSafeInteger($)||$===void 0||$<0)throw new L;return $}function n1(T,$){return dT($.limit),T.transaction(()=>{let _=[],G=["s.is_subagent=0",$.archived?"a.session_id IS NOT NULL":"a.session_id IS NULL"];if($.workspaceKind!==void 0)G.push("s.source_kind=?"),_.push($.workspaceKind);if($.boundary!==void 0)G.push(`(s.last_message_time < ?
316
+ s.session_sort_key ASC`).all($).map(iT)}catch{throw new L}}function R_(T){let $=T.prepare("SELECT catalog_revision FROM surface_projection_meta WHERE singleton=1").get()?.catalog_revision;if(!Number.isSafeInteger($)||$===void 0||$<0)throw new L;return $}function n1(T,$){return cT($.limit),T.transaction(()=>{let _=[],G=["s.is_subagent=0",$.archived?"a.session_id IS NOT NULL":"a.session_id IS NULL"];if($.workspaceKind!==void 0)G.push("s.source_kind=?"),_.push($.workspaceKind);if($.boundary!==void 0)G.push(`(s.last_message_time < ?
317
317
  OR (s.last_message_time = ? AND s.source_kind < ?)
318
318
  OR (s.last_message_time = ? AND s.source_kind = ?
319
319
  AND s.public_workspace_sort_key > ?)
320
320
  OR (s.last_message_time = ? AND s.source_kind = ?
321
- AND s.public_workspace_sort_key = ? AND s.session_sort_key > ?))`),_.push($.boundary.lastMessageTime,$.boundary.lastMessageTime,$.boundary.sourceKind,$.boundary.lastMessageTime,$.boundary.sourceKind,$.boundary.publicWorkspaceSortKey,$.boundary.lastMessageTime,$.boundary.sourceKind,$.boundary.publicWorkspaceSortKey,$.boundary.sessionSortKey);_.push($.limit+1);let X=b_(T),Y=T.prepare(`${vT}
321
+ AND s.public_workspace_sort_key = ? AND s.session_sort_key > ?))`),_.push($.boundary.lastMessageTime,$.boundary.lastMessageTime,$.boundary.sourceKind,$.boundary.lastMessageTime,$.boundary.sourceKind,$.boundary.publicWorkspaceSortKey,$.boundary.lastMessageTime,$.boundary.sourceKind,$.boundary.publicWorkspaceSortKey,$.boundary.sessionSortKey);_.push($.limit+1);let X=R_(T),Y=T.prepare(`${mT}
322
322
  SELECT s.source_kind, s.project_path, s.session_id, s.root_id, s.parent_id,
323
323
  s.relation_type, s.task_status, s.first_message_time,
324
324
  s.last_message_time, s.title, s.archived_at, s.message_count,
@@ -338,16 +338,16 @@ ranked_archive AS (
338
338
  WHERE ${G.join(" AND ")}
339
339
  ORDER BY s.last_message_time DESC, s.source_kind DESC,
340
340
  s.public_workspace_sort_key ASC, s.session_sort_key ASC
341
- LIMIT ?`).all(..._),Q=Y.slice(0,$.limit),Z=Q.map(cT),U=Y.length>$.limit?Q.at(-1):void 0;return{revision:X,sessions:Z,...U?{nextBoundary:{lastMessageTime:U.last_message_time,sourceKind:U.source_kind,publicWorkspaceSortKey:U.public_workspace_sort_key,sessionSortKey:U.session_sort_key}}:{}}})}function i1(T,$){if(dT($.limit),$.beforeSequence!==void 0&&(!Number.isSafeInteger($.beforeSequence)||$.beforeSequence<0))throw new L;let _=$.maxBytes??S0;if(!Number.isSafeInteger(_)||_<1)throw new L;let G=Math.min(_,S0);return T.transaction(()=>{let X=T.prepare(`SELECT s.surface_digest, p.stat_fingerprint FROM sessions s
341
+ LIMIT ?`).all(..._),Q=Y.slice(0,$.limit),Z=Q.map(iT),U=Y.length>$.limit?Q.at(-1):void 0;return{revision:X,sessions:Z,...U?{nextBoundary:{lastMessageTime:U.last_message_time,sourceKind:U.source_kind,publicWorkspaceSortKey:U.public_workspace_sort_key,sessionSortKey:U.session_sort_key}}:{}}})}function i1(T,$){if(cT($.limit),$.beforeSequence!==void 0&&(!Number.isSafeInteger($.beforeSequence)||$.beforeSequence<0))throw new L;let _=$.maxBytes??f0;if(!Number.isSafeInteger(_)||_<1)throw new L;let G=Math.min(_,f0);return T.transaction(()=>{let X=T.prepare(`SELECT s.surface_digest, p.stat_fingerprint FROM sessions s
342
342
  JOIN projection_state p
343
343
  ON p.source_kind=s.source_kind AND p.source_file_path=s.source_file_path
344
344
  AND p.project_path=s.project_path AND p.session_id=s.session_id
345
345
  WHERE s.source_kind=? AND s.project_path=? AND s.session_id=?`).get($.sourceKind,$.projectPath,$.sessionId);if(!X)throw new L;if(!/^[a-f0-9]{64}$/.test(X.surface_digest)||!X.stat_fingerprint)throw new L;let Y=$.beforeSequence===void 0?"":"AND message_seq < ?",Q=[$.sourceKind,$.projectPath,$.sessionId,...$.beforeSequence===void 0?[]:[$.beforeSequence],$.limit+1],Z=T.prepare(`SELECT message_seq, message_id, message_json, byte_count
346
346
  FROM surface_messages
347
347
  WHERE source_kind=? AND project_path=? AND session_id=? ${Y}
348
- ORDER BY message_seq DESC, message_id DESC LIMIT ?`).all(...Q),U=[],V=2;for(let M of Z.slice(0,$.limit)){let I=U.length===0?0:1;if(U.length>0&&V+I+M.byte_count>G)break;U.push(M),V+=I+M.byte_count}let g=U.map((M)=>y_(M)).reverse(),O=Z.length>U.length;return{messages:g,hasOlder:O,...O&&U.length>0?{nextSequence:U.at(-1).message_seq}:{},transcriptFingerprint:X.stat_fingerprint,surfaceDigest:X.surface_digest}})}function y_(T){try{if(Buffer.byteLength(T.message_json)!==T.byte_count)throw new L;let $=h0.parse(JSON.parse(T.message_json));if($.id!==K0(T.message_seq,T.message_id)||lT($.id)!==T.message_seq)throw new L;return $}catch{throw new L}}function dT(T){if(!Number.isSafeInteger(T)||T<1||T>100)throw new L}function c1(T,$,_,G){let X=$.replace(/["*]/g," ").trim().split(/\s+/)[0];if(!X)return[];let Y=`"${X}"*`,Q=_?`SELECT session_id, role, timestamp, text FROM parts_fts
348
+ ORDER BY message_seq DESC, message_id DESC LIMIT ?`).all(...Q),U=[],V=2;for(let M of Z.slice(0,$.limit)){let N=U.length===0?0:1;if(U.length>0&&V+N+M.byte_count>G)break;U.push(M),V+=N+M.byte_count}let g=U.map((M)=>y_(M)).reverse(),O=Z.length>U.length;return{messages:g,hasOlder:O,...O&&U.length>0?{nextSequence:U.at(-1).message_seq}:{},transcriptFingerprint:X.stat_fingerprint,surfaceDigest:X.surface_digest}})}function y_(T){try{if(Buffer.byteLength(T.message_json)!==T.byte_count)throw new L;let $=P0.parse(JSON.parse(T.message_json));if($.id!==k0(T.message_seq,T.message_id)||pT($.id)!==T.message_seq)throw new L;return $}catch{throw new L}}function cT(T){if(!Number.isSafeInteger(T)||T<1||T>100)throw new L}function c1(T,$,_,G){let X=$.replace(/["*]/g," ").trim().split(/\s+/)[0];if(!X)return[];let Y=`"${X}"*`,Q=_?`SELECT session_id, role, timestamp, text FROM parts_fts
349
349
  WHERE parts_fts MATCH ? AND source_kind = 'local' AND project_path = ?
350
350
  ORDER BY timestamp DESC LIMIT ?`:`SELECT session_id, role, timestamp, text FROM parts_fts
351
351
  WHERE parts_fts MATCH ? AND source_kind = 'local'
352
352
  ORDER BY timestamp DESC LIMIT ?`,Z=T.prepare(Q);return _?Z.all(Y,_,G):Z.all(Y,G)}
353
- export{t0 as ne,l as oe,o_ as pe,r_ as qe,a as re,K as se,p as te,w$ as ue,S$ as ve,i_ as we,c_ as xe,d_ as ye,R$ as ze,b$ as Ae,s_ as Be,a_ as Ce,T1 as De,BT as Ee,_1 as Fe,I0 as Ge,N0 as He,V1 as Ie,B1 as Je,g1 as Ke,JT as Le,IT as Me,j0 as Ne,kT as Oe,h1 as Pe,P1 as Qe,m1 as Re,pT as Se,k_ as Te,A_ as Ue,nT as Ve,E0 as We,S_ as Xe,v1 as Ye,f_ as Ze,u1 as _e,p1 as $e,l1 as af,b_ as bf,n1 as cf,i1 as df,c1 as ef};
353
+ export{o0 as ne,n as oe,t_ as pe,r_ as qe,o as re,K as se,l as te,w$ as ue,S$ as ve,i_ as we,c_ as xe,d_ as ye,b$ as ze,R$ as Ae,s_ as Be,a_ as Ce,T1 as De,VT as Ee,_1 as Fe,z0 as Ge,I0 as He,V1 as Ie,B1 as Je,g1 as Ke,LT as Le,JT as Me,W0 as Ne,KT as Oe,h1 as Pe,P1 as Qe,m1 as Re,uT as Se,k_ as Te,A_ as Ue,lT as Ve,q0 as We,S_ as Xe,v1 as Ye,f_ as Ze,u1 as _e,p1 as $e,l1 as af,R_ as bf,n1 as cf,i1 as df,c1 as ef};
@@ -1,2 +1,2 @@
1
- import{readFileSync as l}from"node:fs";import{dirname as o,join as d}from"node:path";import{fileURLToPath as u}from"node:url";var e={name:"blade-code",version:"0.10.157",private:!1,description:"🗡️ Blade Code - 智能代码助手命令行工具",type:"module",bin:{blade:"dist/blade.js"},files:["dist","vendor/ripgrep/**","README.md"],scripts:{dev:"node scripts/run-bun.js --watch src/blade.tsx","dev:serve":"node scripts/run-bun.js --watch src/blade.tsx serve --port 4097",build:"rm -rf dist && node scripts/run-bun.js run scripts/build.ts",start:"node scripts/run-bun.js run dist/blade.js",test:"node scripts/test.js","test:all":"node scripts/test.js all","test:unit":"node scripts/test.js unit","test:integration":"node scripts/test.js integration","test:real-api":"node scripts/test.js realApi","test:real-api:qualification":"node scripts/test.js realApiQualification","test:cli":"node scripts/test.js cli","test:headless-core":"node scripts/test.js headlessCore","test:e2e":"node scripts/test.js e2e","test:performance":"node scripts/test.js performance","test:snapshot":"node scripts/test.js snapshot","test:security":"node scripts/test.js security","browser:install":"playwright install chromium","browser:check":"node scripts/run-bun.js run scripts/browser-check.ts","test:coverage":"node scripts/test.js all --coverage","test:watch":"vitest --watch --config vitest.config.ts","qualify:local":"node scripts/run-bun.js run scripts/qualify.ts local","qualify:production":"node scripts/run-bun.js run scripts/qualify.ts production","benchmark:repo":"node scripts/run-bun.js run scripts/run-real-repo-benchmark.ts","test:update-snapshots":"node scripts/test.js snapshot --update",lint:"biome lint src tests","lint:fix":"biome lint --write src tests","type-check":"tsc --noEmit","format:check":"biome format src tests",ready:"node scripts/run-bun.js run scripts/qualify.ts production","detect-unused":"node scripts/run-bun.js run scripts/detect-unused.ts",prepack:"node scripts/run-bun.js run build",release:"node scripts/release.js","release:dry":"node scripts/release.js --dry-run","release:major":"node scripts/release.js --major","release:minor":"node scripts/release.js --minor","release:patch":"node scripts/release.js --patch"},keywords:["cli","blade","ai","assistant","agent","llm"],author:"echoVic",license:"MIT",repository:{type:"git",url:"git+https://github.com/echoVic/blade-code.git"},homepage:"https://github.com/echoVic/blade-code#readme",bugs:{url:"https://github.com/echoVic/blade-code/issues"},engines:{node:">=22.19.0"},optionalDependencies:{"@vscode/ripgrep":"^1.18.0","better-sqlite3":"^11.8.1","bun-pty":"^0.4.8","node-pty":"1.1.0"},dependencies:{"@agentclientprotocol/sdk":"^1.3.0","@anthropic-ai/sandbox-runtime":"0.0.67","@earendil-works/pi-ai":"0.84.2","@inkjs/ui":"^2.0.0","@modelcontextprotocol/sdk":"^1.30.0",ahooks:"^3.9.7",ajv:"^8.17.1","ansi-escapes":"^7.3.0","async-mutex":"^0.5.0",axios:"^1.19.0",chalk:"^5.4.1",diff:"^8.0.2","fast-glob":"^3.3.3","fuse.js":"^7.5.0","gray-matter":"^4.0.3",hono:"^4.13.0",ink:"npm:@jrichman/ink@6.4.10","ink-big-text":"^2.0.0","ink-gradient":"^3.0.0","ink-select-input":"^6.2.0","ink-spinner":"^5.0.0","ink-text-input":"^6.0.0","js-tiktoken":"^1.0.21","lodash-es":"^4.18.1",lowlight:"^3.3.0","lru-cache":"^11.5.2",nanoid:"^5.1.6",open:"^10.1.2",picomatch:"^4.0.5",playwright:"1.62.1","proper-lockfile":"^4.1.2",react:"19.2.4","react-dom":"19.2.4",semver:"^7.8.5","string-width":"^8.2.2",typebox:"1.3.10",undici:"^7.16.0","vscode-jsonrpc":"8.2.1","vscode-languageserver-protocol":"3.17.5","vscode-languageserver-types":"3.17.5","write-file-atomic":"^7.0.0",ws:"^8.21.2",yaml:"^2.9.0",yargs:"^18.1.0",zustand:"^5.0.14"},devDependencies:{"@biomejs/biome":"2.5.7","@types/bun":"^1.3.14","@types/json-schema":"^7.0.15","@types/lodash-es":"^4.17.12","@types/node":"^22.15.24","@types/picomatch":"^4.0.3","@types/proper-lockfile":"^4.1.4","@types/react":"19.2.10","@types/react-dom":"19.2.3","@types/semver":"^7.8.0","@types/write-file-atomic":"^4.0.3","@types/ws":"^8.18.1","@types/yargs":"^17.0.35","@vitest/coverage-v8":"^4.1.10",jsdom:"^26.0.0",typescript:"^5.9.2",vitest:"^4.1.10"}};var s;function r(){if(s)return s;let i=o(u(import.meta.url));for(let n=0;n<5;n++){try{let t=JSON.parse(l(d(i,"package.json"),"utf8"));if(t.name===e.name&&typeof t.version==="string"&&typeof t.description==="string")return s=t,s}catch{}i=o(i)}return s={name:e.name,version:process.env.BLADE_VERSION??e.version,description:e.description},s}function y(){return{...r()}}function p(){return r().version}function v(){return r().name}function w(){return r().description}function g(){return`v${p()}`}function f(){return`v${p()} © 2025 Blade Code`}
1
+ import{readFileSync as l}from"node:fs";import{dirname as o,join as d}from"node:path";import{fileURLToPath as u}from"node:url";var e={name:"blade-code",version:"0.10.158",private:!1,description:"🗡️ Blade Code - 智能代码助手命令行工具",type:"module",bin:{blade:"dist/blade.js"},files:["dist","vendor/ripgrep/**","README.md"],scripts:{dev:"node scripts/run-bun.js --watch src/blade.tsx","dev:serve":"node scripts/run-bun.js --watch src/blade.tsx serve --port 4097",build:"rm -rf dist && node scripts/run-bun.js run scripts/build.ts",start:"node scripts/run-bun.js run dist/blade.js",test:"node scripts/test.js","test:all":"node scripts/test.js all","test:unit":"node scripts/test.js unit","test:integration":"node scripts/test.js integration","test:real-api":"node scripts/test.js realApi","test:real-api:qualification":"node scripts/test.js realApiQualification","test:cli":"node scripts/test.js cli","test:headless-core":"node scripts/test.js headlessCore","test:e2e":"node scripts/test.js e2e","test:performance":"node scripts/test.js performance","test:snapshot":"node scripts/test.js snapshot","test:security":"node scripts/test.js security","browser:install":"playwright install chromium","browser:check":"node scripts/run-bun.js run scripts/browser-check.ts","test:coverage":"node scripts/test.js all --coverage","test:watch":"vitest --watch --config vitest.config.ts","qualify:local":"node scripts/run-bun.js run scripts/qualify.ts local","qualify:production":"node scripts/run-bun.js run scripts/qualify.ts production","benchmark:repo":"node scripts/run-bun.js run scripts/run-real-repo-benchmark.ts","test:update-snapshots":"node scripts/test.js snapshot --update",lint:"biome lint src tests","lint:fix":"biome lint --write src tests","type-check":"tsc --noEmit","format:check":"biome format src tests",ready:"node scripts/run-bun.js run scripts/qualify.ts production","detect-unused":"node scripts/run-bun.js run scripts/detect-unused.ts",prepack:"node scripts/run-bun.js run build",release:"node scripts/release.js","release:dry":"node scripts/release.js --dry-run","release:major":"node scripts/release.js --major","release:minor":"node scripts/release.js --minor","release:patch":"node scripts/release.js --patch"},keywords:["cli","blade","ai","assistant","agent","llm"],author:"echoVic",license:"MIT",repository:{type:"git",url:"git+https://github.com/echoVic/blade-code.git"},homepage:"https://github.com/echoVic/blade-code#readme",bugs:{url:"https://github.com/echoVic/blade-code/issues"},engines:{node:">=22.19.0"},optionalDependencies:{"@vscode/ripgrep":"^1.18.0","better-sqlite3":"^11.8.1","bun-pty":"^0.4.8","node-pty":"1.1.0"},dependencies:{"@agentclientprotocol/sdk":"^1.3.0","@anthropic-ai/sandbox-runtime":"0.0.67","@earendil-works/pi-ai":"0.84.2","@inkjs/ui":"^2.0.0","@modelcontextprotocol/sdk":"^1.30.0",ahooks:"^3.9.7",ajv:"^8.17.1","ansi-escapes":"^7.3.0","async-mutex":"^0.5.0",axios:"^1.19.0",chalk:"^5.4.1",diff:"^8.0.2","fast-glob":"^3.3.3","fuse.js":"^7.5.0","gray-matter":"^4.0.3",hono:"^4.13.0",ink:"npm:@jrichman/ink@6.4.10","ink-big-text":"^2.0.0","ink-gradient":"^3.0.0","ink-select-input":"^6.2.0","ink-spinner":"^5.0.0","ink-text-input":"^6.0.0","js-tiktoken":"^1.0.21","lodash-es":"^4.18.1",lowlight:"^3.3.0","lru-cache":"^11.5.2",nanoid:"^5.1.6",open:"^10.1.2",picomatch:"^4.0.5",playwright:"1.62.1","proper-lockfile":"^4.1.2",react:"19.2.4","react-dom":"19.2.4",semver:"^7.8.5","string-width":"^8.2.2",typebox:"1.3.10",undici:"^7.16.0","vscode-jsonrpc":"8.2.1","vscode-languageserver-protocol":"3.17.5","vscode-languageserver-types":"3.17.5","write-file-atomic":"^7.0.0",ws:"^8.21.2",yaml:"^2.9.0",yargs:"^18.1.0",zustand:"^5.0.14"},devDependencies:{"@biomejs/biome":"2.5.7","@types/bun":"^1.3.14","@types/json-schema":"^7.0.15","@types/lodash-es":"^4.17.12","@types/node":"^22.15.24","@types/picomatch":"^4.0.3","@types/proper-lockfile":"^4.1.4","@types/react":"19.2.10","@types/react-dom":"19.2.3","@types/semver":"^7.8.0","@types/write-file-atomic":"^4.0.3","@types/ws":"^8.18.1","@types/yargs":"^17.0.35","@vitest/coverage-v8":"^4.1.10",jsdom:"^26.0.0",typescript:"^5.9.2",vitest:"^4.1.10"}};var s;function r(){if(s)return s;let i=o(u(import.meta.url));for(let n=0;n<5;n++){try{let t=JSON.parse(l(d(i,"package.json"),"utf8"));if(t.name===e.name&&typeof t.version==="string"&&typeof t.description==="string")return s=t,s}catch{}i=o(i)}return s={name:e.name,version:process.env.BLADE_VERSION??e.version,description:e.description},s}function y(){return{...r()}}function p(){return r().version}function v(){return r().name}function w(){return r().description}function g(){return`v${p()}`}function f(){return`v${p()} © 2025 Blade Code`}
2
2
  export{y as Vj,p as Wj,v as Xj,w as Yj,g as Zj,f as _j};
@@ -1,4 +1,4 @@
1
- import{da as p}from"./chunk-nk1kfpz5.js";import{Ob as _}from"./chunk-75n6cr3x.js";import{Ad as I,Bd as A,Cd as z,Nd as q,ge as O,yd as N,zd as U}from"./chunk-3jqvgxnc.js";import{se as o}from"./chunk-q1rnvn85.js";import{cg as P}from"./chunk-7xhw74hk.js";import{Dg as e}from"./chunk-xqzmm1bf.js";import{Bk as j}from"./chunk-7xtxvrh8.js";import{createHash as ff}from"node:crypto";var af=4,cf=1000,E=4000,wf=120000,M=0.2;function $f(a){try{return q(a)&&a.retryable}catch{return!1}}function gf(a,c){let f=Number.isSafeInteger(c)&&c>0?c:1,w=f-1,h=Math.min(cf*2**w,E),$=ff("sha256").update(`${a}\x00${f}`).digest().readUInt32BE(0)/4294967295,k=1-M+2*M*$;return Math.min(E,Math.max(0,Math.round(h*k)))}function Tf(a){let c=gf(a.sessionIdentity,a.failedAttempt),f=a.evidence,w=a.workStillPending===!0&&f!==void 0&&$f(f.taskFailure)&&f.outputStarted===!1&&f.toolExecutionStarted===!1&&Number.isInteger(f.toolCallsCount)&&f.toolCallsCount===0,h=Number.isSafeInteger(a.failedAttempt)&&a.failedAttempt>0&&a.failedAttempt<af,g=a.now??Date.now(),$=g-a.recoveryStartedAt,k=Number.isFinite(g)&&Number.isFinite(a.recoveryStartedAt)&&Number.isFinite($)&&$>=0&&$+c<=wf;return{phase:w?h&&k?"retry_scheduled":"exhausted":"failed",delayMs:c,retryable:w,withinAttemptBudget:h,withinTimeBudget:k}}import R from"node:path";import{nanoid as Lf}from"nanoid";import{execFile as hf}from"node:child_process";import{createHash as xf}from"node:crypto";import{lstat as bf,readFile as mf,realpath as i}from"node:fs/promises";import n from"node:path";import{promisify as kf}from"node:util";var lf=kf(hf),T=8388608,s=500,u=200;async function C(a,c){try{return(await lf("git",["-c","core.pager=cat",...c],{cwd:a,encoding:"utf8",timeout:30000,maxBuffer:T+1024,env:{...process.env,GIT_CONFIG_NOSYSTEM:"1",GIT_PAGER:"cat",GIT_OPTIONAL_LOCKS:"0"}})).stdout}catch(f){let w=f instanceof Error&&f.message.includes("maxBuffer")?`Review target exceeds the ${T} byte limit`:f instanceof Error?f.message:String(f);throw Error(`Git review target failed: ${w}`)}}function d(a,c){let f=a?.trim();if(!f||f.length>u||f.includes("\x00")||f.includes(`
1
+ import{da as p}from"./chunk-ehdsj506.js";import{Ob as _}from"./chunk-bgc4wts7.js";import{Ad as I,Bd as A,Cd as z,Nd as q,ge as O,yd as N,zd as U}from"./chunk-f6wx6sf2.js";import{se as o}from"./chunk-vz13c7fr.js";import{cg as P}from"./chunk-7xhw74hk.js";import{Dg as e}from"./chunk-gnjsdr40.js";import{Bk as j}from"./chunk-7xtxvrh8.js";import{createHash as ff}from"node:crypto";var af=4,cf=1000,E=4000,wf=120000,M=0.2;function $f(a){try{return q(a)&&a.retryable}catch{return!1}}function gf(a,c){let f=Number.isSafeInteger(c)&&c>0?c:1,w=f-1,h=Math.min(cf*2**w,E),$=ff("sha256").update(`${a}\x00${f}`).digest().readUInt32BE(0)/4294967295,k=1-M+2*M*$;return Math.min(E,Math.max(0,Math.round(h*k)))}function Tf(a){let c=gf(a.sessionIdentity,a.failedAttempt),f=a.evidence,w=a.workStillPending===!0&&f!==void 0&&$f(f.taskFailure)&&f.outputStarted===!1&&f.toolExecutionStarted===!1&&Number.isInteger(f.toolCallsCount)&&f.toolCallsCount===0,h=Number.isSafeInteger(a.failedAttempt)&&a.failedAttempt>0&&a.failedAttempt<af,g=a.now??Date.now(),$=g-a.recoveryStartedAt,k=Number.isFinite(g)&&Number.isFinite(a.recoveryStartedAt)&&Number.isFinite($)&&$>=0&&$+c<=wf;return{phase:w?h&&k?"retry_scheduled":"exhausted":"failed",delayMs:c,retryable:w,withinAttemptBudget:h,withinTimeBudget:k}}import R from"node:path";import{nanoid as Lf}from"nanoid";import{execFile as hf}from"node:child_process";import{createHash as xf}from"node:crypto";import{lstat as bf,readFile as mf,realpath as i}from"node:fs/promises";import n from"node:path";import{promisify as kf}from"node:util";var lf=kf(hf),T=8388608,s=500,u=200;async function C(a,c){try{return(await lf("git",["-c","core.pager=cat",...c],{cwd:a,encoding:"utf8",timeout:30000,maxBuffer:T+1024,env:{...process.env,GIT_CONFIG_NOSYSTEM:"1",GIT_PAGER:"cat",GIT_OPTIONAL_LOCKS:"0"}})).stdout}catch(f){let w=f instanceof Error&&f.message.includes("maxBuffer")?`Review target exceeds the ${T} byte limit`:f instanceof Error?f.message:String(f);throw Error(`Git review target failed: ${w}`)}}function d(a,c){let f=a?.trim();if(!f||f.length>u||f.includes("\x00")||f.includes(`
2
2
  `)||f.includes("\r"))throw Error(`${c} must contain 1-${u} characters`);return f}function Q(a){return a.split("\x00").filter(Boolean)}async function X(a,c){return(await C(a,["rev-parse","--verify",`${c}^{commit}`])).trim()}async function Ff(a,c,f,w,h){let g=h,$=await i(a);for(let k of c){let l=n.resolve($,k),x=n.relative($,l);if(!x||x.startsWith("..")||n.isAbsolute(x))throw Error(`Untracked review path escapes the workspace: ${k}`);let b=await bf(l);if(!b.isFile()||b.isSymbolicLink())throw Error(`Untracked review target must be a regular file: ${k}`);if(g+=b.size,g>T)throw Error(`Review target exceeds ${T} bytes`);f.update("\x00untracked\x00"),f.update(x.replaceAll(n.sep,"/")),f.update("\x00");let F=await mf(l);f.update(F);let m=Math.max(1,F.toString("utf8").split(`
3
3
  `).length);w.set(x.replaceAll(n.sep,"/"),[{start:1,end:m}])}}function Y(a,c){let f=new Map,w,h,g,$,k=!1,l=(x,b)=>{let F=f.get(x)??[],m=F.at(-1);if(m&&b<=m.end+1)m.end=Math.max(m.end,b);else F.push({start:b,end:b});f.set(x,F)};for(let x of a.split(`
4
4
  `)){if(x.startsWith("--- ")){let b=x.slice(4).split("\t")[0]?.trim();w=b&&b!=="/dev/null"?b.replace(/^a\//,"").replaceAll("\\","/"):void 0;continue}if(x.startsWith("+++ ")){let b=x.slice(4).split("\t")[0]?.trim();k=b==="/dev/null",h=k?w:b?b.replace(/^b\//,"").replaceAll("\\","/"):void 0,g=void 0,$=void 0;continue}if(x.startsWith("@@ ")){let b=/-(\d+)(?:,\d+)? \+(\d+)(?:,\d+)?/.exec(x);g=b?Math.max(1,Number(b[1])):void 0,$=b?Math.max(1,Number(b[2])):void 0;continue}if(!h||g===void 0||$===void 0)continue;if(x.startsWith("+")&&!x.startsWith("+++"))l(h,$),$++;else if(x.startsWith("-")&&!x.startsWith("---"))l(h,k?g:$),g++;else if(!x.startsWith("\\"))g++,$++}for(let x of c)if(!f.has(x))f.set(x,[{start:1,end:1}]);return f}function D(a){if(a.length>s)throw Error(`Review target exceeds the ${s} file limit`)}class K{static async resolve(a,c){let f=await i(a);await C(f,["rev-parse","--is-inside-work-tree"]);let w=await X(f,"HEAD"),h=xf("sha256");h.update(`kind\x00${c.kind}\x00head\x00${w}\x00`);let g="",$=[],k,l,x,b,F=new Map;switch(c.kind){case"uncommitted":{g=await C(f,["diff","--binary","--no-ext-diff","--relative","HEAD","--","."]);let m=Q(await C(f,["diff","--name-only","-z","--relative","HEAD","--","."])),L=Q(await C(f,["ls-files","--others","--exclude-standard","-z","--","."]));if($=[...new Set([...m,...L])].sort(),D($),$.length===0)throw Error("No uncommitted changes to review");h.update(g),F=Y(g,m),await Ff(f,L,h,F,Buffer.byteLength(g)),x="uncommitted changes",b=["Review the uncommitted working tree against HEAD.","Use git status --short, git diff --cached, and git diff, then inspect","every relevant untracked file listed by git status."].join(" ");break}case"base":{let m=d(c.ref,"Base ref");k=await X(f,m);let L=(await C(f,["merge-base",k,w])).trim();if(g=await C(f,["diff","--binary","--no-ext-diff","--relative",`${L}..${w}`,"--","."]),$=Q(await C(f,["diff","--name-only","-z","--relative",`${L}..${w}`,"--","."])),D($),$.length===0)throw Error(`No changes between ${m} and HEAD`);h.update(g),h.update(`\x00merge-base\x00${L}`),F=Y(g,$),x=`changes against ${m}`,b=`Review changes introduced by ${L}..${w}.`;break}case"commit":{let m=d(c.ref,"Commit ref");if(l=await X(f,m),g=await C(f,["show","--format=","--binary","--no-ext-diff","--relative",l,"--","."]),$=Q(await C(f,["diff-tree","--root","--no-commit-id","--name-only","-r","-z",l,"--","."])),D($),$.length===0)throw Error(`Commit has no changes in this workspace: ${m}`);h.update(g),h.update(`\x00commit\x00${l}`),F=Y(g,$),x=`commit ${m}`,b=`Review only the changes introduced by commit ${l}.`;break}}if(Buffer.byteLength(g)>T)throw Error(`Review diff exceeds ${T} bytes`);return{info:{kind:c.kind,label:x,headSha:w,...k?{baseSha:k}:{},...l?{commitSha:l}:{},digest:h.digest("hex"),fileCount:$.length},instruction:b,changedLines:F}}}var Wf=131072,t=50,Z=new Set;function v(a,c){return`${R.resolve(a)}\x00${c}`}function S(a){return`/review ${a.kind}${a.kind==="uncommitted"?"":` ${a.ref?.trim()??""}`}`}function V(a,c,f,w=!1){if(typeof a!=="string")throw Error(`${c} must be a string`);let h=a.trim();if(!w&&!h||h.length>f)throw Error(`${c} exceeds its allowed length`);return h}function Hf(a,c,f){if(!a||typeof a!=="object"||Array.isArray(a))throw Error("Review finding must be an object");let w=a,h=typeof w.line==="number"&&Number.isInteger(w.line)?w.line:void 0,g=w.code_location??(typeof w.file==="string"&&h!==void 0?{path:w.file,line_start:h,line_end:h}:void 0);if(!g||typeof g!=="object"||Array.isArray(g))throw Error("Review finding has no code_location");let $=g,k=V($.path,"Finding path",1000),l=R.posix.normalize(k.replaceAll("\\","/"));if(R.posix.isAbsolute(l)||l===".."||l.startsWith("../"))throw Error("Review finding path must be workspace-relative");let x=R.resolve(c,l),b=R.relative(R.resolve(c),x);if(b.startsWith("..")||R.isAbsolute(b))throw Error("Review finding path escapes the workspace");let F=typeof w.severity==="string"?w.severity.toLowerCase():"",m=F==="critical"?0:F==="high"?1:F==="medium"?2:F==="low"?3:void 0,L=w.priority??m;if(L!==0&&L!==1&&L!==2&&L!==3)throw Error("Review finding priority must be 0-3");let W=w.confidence_score??w.confidence??0.8;if(typeof W!=="number"||!Number.isFinite(W)||W<0||W>1)throw Error("Review finding confidence_score must be between 0 and 1");let{line_start:H,line_end:r}=$;if(!Number.isInteger(H)||!Number.isInteger(r)||H<1||r<H||r-H>=10)throw Error("Review finding line range is invalid");let G=f.changedLines.get(l);if(!G)throw Error("Review finding path is outside the review target");if(!G.some((y)=>H<=y.end&&r>=y.start))throw Error("Review finding line range does not overlap the changed lines");let B=V(w.title??`[P${L}] ${String(w.type??"Review finding").replaceAll("-"," ").replace(/\b\w/g,(y)=>y.toUpperCase())}`,"Finding title",120);if(!B.startsWith(`[P${L}] `))throw Error("Review finding title priority does not match priority");return{title:B,body:V(w.body??w.description,"Finding body",4000),priority:L,confidenceScore:W,codeLocation:{path:l,lineStart:H,lineEnd:r}}}function Rf(a,c,f){if(Buffer.byteLength(a)>Wf)throw Error("Review output exceeds the 128 KiB limit");let w=a.indexOf("{"),h=a.lastIndexOf("}");if(w<0||h<=w)throw Error("Reviewer did not return a JSON object");let g;try{g=JSON.parse(a.slice(w,h+1))}catch{throw Error("Reviewer returned invalid JSON")}if(!g||typeof g!=="object"||Array.isArray(g))throw Error("Reviewer output must be an object");let $=g;if(!Array.isArray($.findings))throw Error("Reviewer output must contain findings");if($.findings.length>t)throw Error(`Reviewer returned more than ${t} findings`);return{overallExplanation:V($.overall_explanation??$.summary,"Review explanation",1e4,!0),findings:$.findings.map((k)=>Hf(k,c,f))}}async function J(a,c){return new o(j(a,c)).readAll()}class rf{static async start(a){let{sessionId:c,projectPath:f,runtime:w,request:h,onEvent:g}=a;if(w.sessionId!==c||R.resolve(w.workspaceRoot)!==R.resolve(f))throw Error("Review runtime does not own the requested Session");if(w.hasTurnOwner())throw Error("Cannot start a review during an active turn");await O.assertSessionWritable(c,f);let $=v(f,c);if(Z.has($))throw Error("Session already has an active review");let k=await J(f,c);if(U(k))throw Error("Session has an interrupted review that must be recovered");let l=h.instructions?.trim();if(l&&l.length>4000)throw Error("Review instructions exceed 4,000 characters");let x=await K.resolve(f,h),b=Lf(16),F=P("review"),m=new Date().toISOString(),L={reviewId:b,reviewerSessionId:F,target:x.info,startedAt:m},W=new _(f);await W.saveReviewStart(c,L),await W.saveMessage(c,"user",S(h),null,{codeReview:{reviewId:b,phase:"started",targetKind:x.info.kind,targetDigest:x.info.digest}}),await O.updateSessionMetadata(c,f,{taskStatus:"running",taskStatusReason:`Reviewing ${x.info.label}`,taskPromptSummary:S(h),taskStartedAt:m,taskCompletedAt:null,taskFailure:null}),Z.add($);let H=this.execute({...a,target:x,reviewId:b,reviewerSessionId:F,instructions:l,store:W,onEvent:g}).finally(()=>{Z.delete($)});return{reviewId:b,completion:H}}static async execute(a){let{sessionId:c,projectPath:f,runtime:w,request:h,signal:g,onEvent:$,target:k,reviewId:l,reviewerSessionId:x,instructions:b,store:F}=a,m;try{let W=[k.instruction,"Bash already starts in the review workspace. Never prefix a command with cd.",`Authoritative target digest: ${k.info.digest}`,`Changed file count: ${k.info.fileCount}`,b?`Additional review instructions: