blade-code 0.10.205 → 0.10.206
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/blade.js +2 -2
- package/dist/chunk-09kqfdpa.js +3 -0
- package/dist/{chunk-efjjkha8.js → chunk-0ef47wgr.js} +2 -2
- package/dist/chunk-1j39te3t.js +23 -0
- package/dist/{chunk-fdr4fcrf.js → chunk-1n4v80hy.js} +1 -1
- package/dist/{chunk-ynd1v33f.js → chunk-28n945me.js} +2 -2
- package/dist/{chunk-ys8gysg8.js → chunk-28tzj187.js} +1 -1
- package/dist/{chunk-qtwgm95z.js → chunk-3crwyd2r.js} +3 -3
- package/dist/{chunk-zfxcef0z.js → chunk-50vwafn5.js} +1 -1
- package/dist/chunk-514va7ce.js +2 -0
- package/dist/{chunk-kkzznz4w.js → chunk-53vh6vpt.js} +1 -1
- package/dist/chunk-5k8k56f2.js +731 -0
- package/dist/{chunk-515yj7mt.js → chunk-65wc1h38.js} +1 -1
- package/dist/{chunk-xbs91jd8.js → chunk-67wy9mm7.js} +2 -2
- package/dist/chunk-6p0hkf4f.js +1 -0
- package/dist/{chunk-qdbbke8f.js → chunk-6xzk4hsg.js} +1 -1
- package/dist/chunk-793wjhvz.js +332 -0
- package/dist/{chunk-rtwd35gd.js → chunk-826xegd8.js} +2 -2
- package/dist/chunk-867bpjzg.js +1 -0
- package/dist/{chunk-zj1g4nbq.js → chunk-870szc6v.js} +1 -1
- package/dist/chunk-983hqzat.js +1 -0
- package/dist/{chunk-0eajnhrj.js → chunk-9kj19a8t.js} +1 -1
- package/dist/{chunk-430b319j.js → chunk-9sf1t8gw.js} +1 -1
- package/dist/chunk-9tpzmy8v.js +4 -0
- package/dist/chunk-af0m5227.js +1 -0
- package/dist/{chunk-f8kjdxz7.js → chunk-asgmmaec.js} +2 -2
- package/dist/{chunk-vz88tqtd.js → chunk-av799ng5.js} +2 -2
- package/dist/{chunk-bwe49m6n.js → chunk-az3rehz9.js} +360 -360
- package/dist/{chunk-p0wyhp5a.js → chunk-dnpkf5mv.js} +2 -2
- package/dist/chunk-dpg006xj.js +1 -0
- package/dist/{chunk-xmymx75h.js → chunk-e0ft3vwg.js} +1 -1
- package/dist/chunk-e45r1a8r.js +25 -0
- package/dist/{chunk-g01mth5d.js → chunk-ebpg1srd.js} +2 -2
- package/dist/{chunk-4wx5sya5.js → chunk-ed2hdrwe.js} +1 -1
- package/dist/{chunk-7ajvrtb3.js → chunk-erhaedch.js} +1 -1
- package/dist/{chunk-kehgewqh.js → chunk-ewwrss2w.js} +1 -1
- package/dist/{chunk-kf9gj2gn.js → chunk-fc1gz532.js} +2 -2
- package/dist/{chunk-9jz1q7bk.js → chunk-fd0a8h55.js} +2 -2
- package/dist/{chunk-qp2qc4p2.js → chunk-fnmqxhv1.js} +2 -2
- package/dist/chunk-g7tphxme.js +6 -0
- package/dist/{chunk-eg3ms291.js → chunk-gmpsfkgg.js} +1 -1
- package/dist/chunk-gpnkxh4c.js +1 -0
- package/dist/{chunk-b8ast0cp.js → chunk-gz84aewr.js} +1 -1
- package/dist/{chunk-xxbxc31z.js → chunk-h4k69z1b.js} +1 -1
- package/dist/{chunk-17d4m89n.js → chunk-h6ahwwpa.js} +2 -2
- package/dist/chunk-hpge30p8.js +8 -0
- package/dist/{chunk-1cy4ab77.js → chunk-hv8nt7wj.js} +1 -1
- package/dist/chunk-mtvbm7xe.js +1 -0
- package/dist/chunk-mys9mmcp.js +1 -0
- package/dist/{chunk-wezr6wfq.js → chunk-n34qsnks.js} +1 -1
- package/dist/chunk-n5jzmwhy.js +25 -0
- package/dist/chunk-new78c3h.js +1 -0
- package/dist/{chunk-8pd1hp4r.js → chunk-nj6kpdte.js} +2 -2
- package/dist/chunk-nng1xbsm.js +10 -0
- package/dist/{chunk-xyypxrad.js → chunk-p2y1zqsb.js} +2 -2
- package/dist/chunk-p8vpvx07.js +12 -0
- package/dist/{chunk-w42j9p3t.js → chunk-pdna2qvv.js} +2 -2
- package/dist/{chunk-gn9er641.js → chunk-pga8gxtf.js} +1 -1
- package/dist/chunk-pt0y4zrg.js +14 -0
- package/dist/{chunk-5zmp7p0n.js → chunk-q6abav45.js} +51 -51
- package/dist/chunk-r4em0ha7.js +1 -0
- package/dist/chunk-rdzbd5vk.js +1 -0
- package/dist/chunk-sbfe9vh3.js +94 -0
- package/dist/chunk-sqk8cnej.js +44 -0
- package/dist/{chunk-5yyp6njq.js → chunk-t0gm0pn1.js} +1 -1
- package/dist/{chunk-egss0m1x.js → chunk-tsm8rhmd.js} +1 -1
- package/dist/chunk-tzvb0nd2.js +2 -0
- package/dist/{chunk-kvp523gt.js → chunk-v4cxk10d.js} +1 -1
- package/dist/{chunk-ak5xvsxr.js → chunk-v5vx6nz9.js} +1 -1
- package/dist/{chunk-qq5y7b2r.js → chunk-vx2g1faw.js} +1 -1
- package/dist/chunk-w6zat4v4.js +1 -0
- package/dist/chunk-wsd3rn0q.js +1 -0
- package/dist/{chunk-c51wwnh2.js → chunk-xcq0cehr.js} +5 -6
- package/dist/chunk-yjjxv7fn.js +352 -0
- package/dist/{chunk-6169xxb4.js → chunk-yzf2jpam.js} +2 -2
- package/dist/web/assets/{ChatView-BF6HUrBw.js → ChatView-lUD-61n0.js} +4 -4
- package/dist/web/assets/{CodeBlockHighlighter-C4CgCiRf.js → CodeBlockHighlighter--TbfcBxW.js} +1 -1
- package/dist/web/assets/FilePreview-R6OKQPf2.js +55 -0
- package/dist/web/assets/{KanbanBoard-DDXB-yq1.js → KanbanBoard-BHOKtiv5.js} +1 -1
- package/dist/web/assets/{MarkdownRenderer-DS7RznBE.js → MarkdownRenderer-DqxNq8pa.js} +3 -3
- package/dist/web/assets/{ScrollArea-BM9NzGZM.js → ScrollArea-Dhu0B-zB.js} +1 -1
- package/dist/web/assets/{SessionHistorySurface-DnRySeLE.js → SessionHistorySurface-aZvoj3ma.js} +1 -1
- package/dist/web/assets/{SettingsModal-D5YLUtIo.js → SettingsModal-C7QBnIqa.js} +1 -1
- package/dist/web/assets/{Sidebar-BZC6OkDJ.js → Sidebar-Bznnq91x.js} +1 -1
- package/dist/web/assets/{TaskSwitcher-WewOkw5m.js → TaskSwitcher-DJczhDRp.js} +1 -1
- package/dist/web/assets/{TerminalPanel-C5SGdRNr.js → TerminalPanel-Vk4p0V3p.js} +1 -1
- package/dist/web/assets/{archive-DkczUU08.js → archive-0hLYBKQf.js} +1 -1
- package/dist/web/assets/{arrow-left-9pBiQwu7.js → arrow-left-CXb6Gqf3.js} +1 -1
- package/dist/web/assets/{calendar-clock-BFnUlxrU.js → calendar-clock-DiaFI9Jk.js} +1 -1
- package/dist/web/assets/{chevron-right-yCVkAEcj.js → chevron-right-CcPXH37D.js} +1 -1
- package/dist/web/assets/{clock-3-CcoWoRQs.js → clock-3-D6VR6gJc.js} +1 -1
- package/dist/web/assets/{copy-HJF0oQBS.js → copy-C3eUAQgp.js} +1 -1
- package/dist/web/assets/{download-DSBCIqk3.js → download-DHvS9tI3.js} +1 -1
- package/dist/web/assets/{external-link-zIgEO0KB.js → external-link-BDVaEuqY.js} +1 -1
- package/dist/web/assets/{folder-BdRo64o3.js → folder-B80Ac6rr.js} +1 -1
- package/dist/web/assets/index-VwIiNjc8.css +1 -0
- package/dist/web/assets/{index-BVDkKudh.js → index-YqughEZk.js} +4 -4
- package/dist/web/assets/{message-square-plus-3klTXO0S.js → message-square-plus-D15quyPH.js} +1 -1
- package/dist/web/assets/{pause-B9Q5JWvH.js → pause-BjMlj6Bx.js} +1 -1
- package/dist/web/assets/{pencil-CbYIz1b1.js → pencil-BMoJvcB7.js} +1 -1
- package/dist/web/assets/{play-CZMTj43e.js → play-BHh4py3p.js} +1 -1
- package/dist/web/assets/{plus-Cc7I8fhb.js → plus-DeFz_gQq.js} +1 -1
- package/dist/web/assets/session-events-DCHBz9We.js +25 -0
- package/dist/web/assets/{settings-DSF3exX2.js → settings-CI8xbId2.js} +1 -1
- package/dist/web/assets/{team-qfeJHL9s.js → team-zZ803hH9.js} +1 -1
- package/dist/web/assets/{teamService-Bs9qBKI8.js → teamService-CgLBXgmv.js} +1 -1
- package/dist/web/assets/{terminal-DQLqe-Ed.js → terminal-1WxSJ47E.js} +1 -1
- package/dist/web/index.html +2 -2
- package/package.json +1 -1
- package/dist/chunk-18swytk4.js +0 -25
- package/dist/chunk-3297ghav.js +0 -1
- package/dist/chunk-33ck9ryb.js +0 -1
- package/dist/chunk-4fa11h6f.js +0 -94
- package/dist/chunk-535s1mm8.js +0 -1
- package/dist/chunk-57939tb3.js +0 -8
- package/dist/chunk-6v0cdqkw.js +0 -1
- package/dist/chunk-8kwj6px8.js +0 -1
- package/dist/chunk-a8z11yd2.js +0 -3
- package/dist/chunk-aatfjx15.js +0 -2
- package/dist/chunk-b2ek44t5.js +0 -12
- package/dist/chunk-b9d0ex8n.js +0 -4
- package/dist/chunk-ccgtbzrz.js +0 -14
- package/dist/chunk-jgxfhk9k.js +0 -733
- package/dist/chunk-jhpwwwjt.js +0 -1
- package/dist/chunk-jjj86dej.js +0 -1
- package/dist/chunk-kejvty9z.js +0 -23
- package/dist/chunk-mhe1zppc.js +0 -1
- package/dist/chunk-pb1q26gw.js +0 -181
- package/dist/chunk-pc5f77qh.js +0 -1
- package/dist/chunk-pkx6kfy6.js +0 -1
- package/dist/chunk-qjptyj18.js +0 -1
- package/dist/chunk-shgxzmdw.js +0 -1
- package/dist/chunk-thytjs86.js +0 -44
- package/dist/chunk-tm3789m3.js +0 -2
- package/dist/chunk-tnmcrvk2.js +0 -25
- package/dist/chunk-wejthch2.js +0 -1
- package/dist/chunk-xv6ejk2z.js +0 -353
- package/dist/chunk-yvgef7rp.js +0 -10
- package/dist/chunk-zj48897e.js +0 -6
- package/dist/web/assets/FilePreview-BS4PgFKb.js +0 -55
- package/dist/web/assets/index-CaCifsSK.css +0 -1
- package/dist/web/assets/session-events-NEjosinC.js +0 -31
package/dist/chunk-xv6ejk2z.js
DELETED
|
@@ -1,353 +0,0 @@
|
|
|
1
|
-
import{if as P0,jf as PT}from"./chunk-efjjkha8.js";import{Eh as FT}from"./chunk-ys8gysg8.js";import{Ej as hT}from"./chunk-a8z11yd2.js";import{Ak as A,Ck as h0,Dk as e,Lk as yT,fk as g0,nk as D,pk as S,qk as s,sk as a,tk as D0,uk as fT,vk as bT,wk as RT}from"./chunk-4wx5sya5.js";import{Mk as H0}from"./chunk-eg3ms291.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
|
-
`),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
|
-
`);if(V+=`
|
|
5
|
-
|
|
6
|
-
... (${U} lines truncated, showing first ${$.keepHead} and last ${$.keepTail} of ${Y} total) ...
|
|
7
|
-
|
|
8
|
-
`,V+=Z.join(`
|
|
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
|
-
|
|
11
|
-
... (content truncated to ${$.maxChars} chars) ...
|
|
12
|
-
|
|
13
|
-
${N}`}let g=$.summarize&&_?_(Y,G):void 0;if(g)V+=`
|
|
14
|
-
|
|
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
|
-
`).length} lines`);if(X.truncated)Q.push(`stderr: ${X.originalLines} lines -> ${X.content.split(`
|
|
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
|
-
`).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 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("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""").replaceAll("'","'")}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
|
-
${T.stdout}`:"",T.stderr?`stderr:
|
|
22
|
-
${T.stderr}`:""].filter(Boolean).join(`
|
|
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
|
-
${T.stderr}`:""].filter(Boolean).join(`
|
|
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 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
|
-
`),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(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
|
-
`)}
|
|
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
|
-
`)}
|
|
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
|
-
`)}
|
|
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
|
-
DROP TABLE IF EXISTS parts_fts;
|
|
45
|
-
DROP TABLE IF EXISTS surface_messages;
|
|
46
|
-
DROP TABLE IF EXISTS parts;
|
|
47
|
-
DROP TABLE IF EXISTS sessions;
|
|
48
|
-
DROP TABLE IF EXISTS projection_state;
|
|
49
|
-
DROP TABLE IF EXISTS surface_projection_meta;
|
|
50
|
-
`);T.exec(`
|
|
51
|
-
CREATE TABLE IF NOT EXISTS surface_projection_meta (
|
|
52
|
-
singleton INTEGER PRIMARY KEY CHECK(singleton = 1),
|
|
53
|
-
catalog_revision INTEGER NOT NULL DEFAULT 0 CHECK(catalog_revision >= 0)
|
|
54
|
-
);
|
|
55
|
-
INSERT OR IGNORE INTO surface_projection_meta (singleton, catalog_revision)
|
|
56
|
-
VALUES (1, 0);
|
|
57
|
-
|
|
58
|
-
CREATE TABLE IF NOT EXISTS projection_state (
|
|
59
|
-
source_kind TEXT NOT NULL CHECK(source_kind IN ('local', 'acp-remote')),
|
|
60
|
-
source_file_path TEXT NOT NULL,
|
|
61
|
-
project_path TEXT,
|
|
62
|
-
session_id TEXT NOT NULL,
|
|
63
|
-
last_seq INTEGER NOT NULL DEFAULT 0,
|
|
64
|
-
file_size INTEGER NOT NULL DEFAULT 0,
|
|
65
|
-
mtime_ms INTEGER NOT NULL DEFAULT 0,
|
|
66
|
-
stat_fingerprint TEXT NOT NULL DEFAULT '',
|
|
67
|
-
PRIMARY KEY (source_kind, source_file_path)
|
|
68
|
-
);
|
|
69
|
-
CREATE INDEX IF NOT EXISTS idx_projection_state_session ON projection_state(
|
|
70
|
-
source_kind, project_path, session_id
|
|
71
|
-
);
|
|
72
|
-
|
|
73
|
-
CREATE TABLE IF NOT EXISTS sessions (
|
|
74
|
-
source_kind TEXT NOT NULL CHECK(source_kind IN ('local', 'acp-remote')),
|
|
75
|
-
source_file_path TEXT NOT NULL,
|
|
76
|
-
project_path TEXT NOT NULL,
|
|
77
|
-
session_id TEXT NOT NULL,
|
|
78
|
-
root_id TEXT,
|
|
79
|
-
parent_id TEXT,
|
|
80
|
-
relation_type TEXT,
|
|
81
|
-
title TEXT,
|
|
82
|
-
agent_type TEXT,
|
|
83
|
-
model TEXT,
|
|
84
|
-
task_status TEXT,
|
|
85
|
-
task_priority TEXT,
|
|
86
|
-
task_kind TEXT,
|
|
87
|
-
task_due_at TEXT,
|
|
88
|
-
archived_at TEXT,
|
|
89
|
-
last_message_time TEXT,
|
|
90
|
-
project_sort_key TEXT NOT NULL,
|
|
91
|
-
public_workspace_ref TEXT,
|
|
92
|
-
public_workspace_sort_key TEXT NOT NULL,
|
|
93
|
-
session_sort_key TEXT NOT NULL,
|
|
94
|
-
first_message_time TEXT,
|
|
95
|
-
message_count INTEGER NOT NULL DEFAULT 0,
|
|
96
|
-
has_errors INTEGER NOT NULL DEFAULT 0,
|
|
97
|
-
is_subagent INTEGER NOT NULL DEFAULT 0,
|
|
98
|
-
-- 完整 StoredSessionMetadata JSON,读回时直接反序列化,保证与 JSONL 路径一致。
|
|
99
|
-
metadata_json TEXT NOT NULL,
|
|
100
|
-
surface_digest TEXT NOT NULL,
|
|
101
|
-
PRIMARY KEY (source_kind, project_path, session_id)
|
|
102
|
-
);
|
|
103
|
-
CREATE INDEX IF NOT EXISTS idx_sessions_source_file ON sessions(
|
|
104
|
-
source_kind, source_file_path
|
|
105
|
-
);
|
|
106
|
-
CREATE INDEX IF NOT EXISTS idx_sessions_catalog ON sessions(
|
|
107
|
-
last_message_time DESC,
|
|
108
|
-
source_kind DESC,
|
|
109
|
-
public_workspace_sort_key ASC,
|
|
110
|
-
session_sort_key ASC
|
|
111
|
-
);
|
|
112
|
-
CREATE INDEX IF NOT EXISTS idx_sessions_archived ON sessions(
|
|
113
|
-
source_kind,
|
|
114
|
-
archived_at,
|
|
115
|
-
project_path,
|
|
116
|
-
parent_id
|
|
117
|
-
);
|
|
118
|
-
-- 任务看板过滤/排序:按项目锁定后再按状态、优先级、截止时间收敛。
|
|
119
|
-
CREATE INDEX IF NOT EXISTS idx_sessions_task_board ON sessions(
|
|
120
|
-
project_path,
|
|
121
|
-
task_status,
|
|
122
|
-
task_priority,
|
|
123
|
-
task_due_at,
|
|
124
|
-
source_kind
|
|
125
|
-
);
|
|
126
|
-
CREATE INDEX IF NOT EXISTS idx_sessions_task_status ON sessions(
|
|
127
|
-
task_status,
|
|
128
|
-
project_path,
|
|
129
|
-
source_kind
|
|
130
|
-
);
|
|
131
|
-
CREATE INDEX IF NOT EXISTS idx_sessions_task_priority ON sessions(
|
|
132
|
-
task_priority,
|
|
133
|
-
task_due_at,
|
|
134
|
-
source_kind
|
|
135
|
-
) WHERE task_priority IS NOT NULL;
|
|
136
|
-
CREATE INDEX IF NOT EXISTS idx_sessions_task_due_at ON sessions(
|
|
137
|
-
task_due_at,
|
|
138
|
-
source_kind
|
|
139
|
-
) WHERE task_due_at IS NOT NULL;
|
|
140
|
-
|
|
141
|
-
CREATE TABLE IF NOT EXISTS parts (
|
|
142
|
-
source_kind TEXT NOT NULL CHECK(source_kind IN ('local', 'acp-remote')),
|
|
143
|
-
project_path TEXT NOT NULL,
|
|
144
|
-
session_id TEXT NOT NULL,
|
|
145
|
-
part_id TEXT NOT NULL,
|
|
146
|
-
message_id TEXT,
|
|
147
|
-
part_type TEXT,
|
|
148
|
-
role TEXT,
|
|
149
|
-
seq INTEGER,
|
|
150
|
-
timestamp TEXT,
|
|
151
|
-
text TEXT,
|
|
152
|
-
PRIMARY KEY (source_kind, project_path, session_id, part_id)
|
|
153
|
-
);
|
|
154
|
-
CREATE INDEX IF NOT EXISTS idx_parts_session ON parts(
|
|
155
|
-
source_kind, project_path, session_id
|
|
156
|
-
);
|
|
157
|
-
|
|
158
|
-
CREATE TABLE IF NOT EXISTS surface_messages (
|
|
159
|
-
source_kind TEXT NOT NULL CHECK(source_kind IN ('local', 'acp-remote')),
|
|
160
|
-
project_path TEXT NOT NULL,
|
|
161
|
-
session_id TEXT NOT NULL,
|
|
162
|
-
message_seq INTEGER NOT NULL CHECK(message_seq >= 0),
|
|
163
|
-
message_id TEXT NOT NULL,
|
|
164
|
-
message_json TEXT NOT NULL,
|
|
165
|
-
byte_count INTEGER NOT NULL CHECK(byte_count >= 0),
|
|
166
|
-
PRIMARY KEY (
|
|
167
|
-
source_kind, project_path, session_id, message_seq, message_id
|
|
168
|
-
)
|
|
169
|
-
);
|
|
170
|
-
CREATE INDEX IF NOT EXISTS idx_surface_messages_history ON surface_messages(
|
|
171
|
-
source_kind, project_path, session_id, message_seq DESC, message_id DESC
|
|
172
|
-
);
|
|
173
|
-
|
|
174
|
-
CREATE VIRTUAL TABLE IF NOT EXISTS parts_fts USING fts5(
|
|
175
|
-
text,
|
|
176
|
-
source_kind UNINDEXED,
|
|
177
|
-
project_path UNINDEXED,
|
|
178
|
-
session_id UNINDEXED,
|
|
179
|
-
part_id UNINDEXED,
|
|
180
|
-
role UNINDEXED,
|
|
181
|
-
timestamp UNINDEXED,
|
|
182
|
-
seq UNINDEXED,
|
|
183
|
-
tokenize = 'unicode61'
|
|
184
|
-
);
|
|
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
|
-
source_kind, project_path, public_workspace_ref, session_id, archive_root_id,
|
|
187
|
-
effective_archived_at, depth
|
|
188
|
-
) AS (
|
|
189
|
-
SELECT source_kind, project_path, public_workspace_ref, session_id, session_id,
|
|
190
|
-
archived_at, 0
|
|
191
|
-
FROM sessions
|
|
192
|
-
WHERE archived_at IS NOT NULL
|
|
193
|
-
UNION ALL
|
|
194
|
-
SELECT child.source_kind, child.project_path, child.public_workspace_ref,
|
|
195
|
-
child.session_id, parent.archive_root_id, parent.effective_archived_at,
|
|
196
|
-
parent.depth + 1
|
|
197
|
-
FROM sessions child
|
|
198
|
-
JOIN archive_members parent
|
|
199
|
-
ON child.source_kind = parent.source_kind
|
|
200
|
-
AND child.project_path = parent.project_path
|
|
201
|
-
AND child.public_workspace_ref IS parent.public_workspace_ref
|
|
202
|
-
AND child.parent_id = parent.session_id
|
|
203
|
-
WHERE parent.depth < 128
|
|
204
|
-
),
|
|
205
|
-
ranked_archive AS (
|
|
206
|
-
SELECT source_kind, project_path, public_workspace_ref, session_id,
|
|
207
|
-
archive_root_id, effective_archived_at,
|
|
208
|
-
ROW_NUMBER() OVER (
|
|
209
|
-
PARTITION BY source_kind, project_path, public_workspace_ref, session_id
|
|
210
|
-
ORDER BY depth ASC, archive_root_id ASC
|
|
211
|
-
) AS rank
|
|
212
|
-
FROM archive_members
|
|
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
|
-
(source_kind, project_path, session_id, part_id, message_id, part_type, role,
|
|
215
|
-
seq, timestamp, text)
|
|
216
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`),Z=T.prepare(`INSERT INTO parts_fts
|
|
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=l(Q??Y.projectPath);T.prepare(`INSERT INTO sessions
|
|
219
|
-
(source_kind, project_path, session_id, root_id, parent_id, relation_type, title,
|
|
220
|
-
agent_type, model, task_status, task_priority, task_kind, task_due_at,
|
|
221
|
-
archived_at, last_message_time, project_sort_key,
|
|
222
|
-
public_workspace_ref, public_workspace_sort_key, session_sort_key,
|
|
223
|
-
first_message_time, message_count, has_errors, is_subagent, metadata_json,
|
|
224
|
-
surface_digest, source_file_path)
|
|
225
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
226
|
-
ON CONFLICT(source_kind, project_path, session_id) DO UPDATE SET
|
|
227
|
-
source_file_path=excluded.source_file_path,
|
|
228
|
-
root_id=excluded.root_id, parent_id=excluded.parent_id,
|
|
229
|
-
relation_type=excluded.relation_type, title=excluded.title,
|
|
230
|
-
agent_type=excluded.agent_type, model=excluded.model,
|
|
231
|
-
task_status=excluded.task_status, task_priority=excluded.task_priority,
|
|
232
|
-
task_kind=excluded.task_kind, task_due_at=excluded.task_due_at,
|
|
233
|
-
archived_at=excluded.archived_at,
|
|
234
|
-
last_message_time=excluded.last_message_time,
|
|
235
|
-
project_sort_key=excluded.project_sort_key,
|
|
236
|
-
public_workspace_ref=excluded.public_workspace_ref,
|
|
237
|
-
public_workspace_sort_key=excluded.public_workspace_sort_key,
|
|
238
|
-
session_sort_key=excluded.session_sort_key,
|
|
239
|
-
first_message_time=excluded.first_message_time, message_count=excluded.message_count,
|
|
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,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
|
-
SET catalog_revision=catalog_revision + 1 WHERE singleton=1`).run()}function D_(T,$,_,G,X,Y){T.prepare(`DELETE FROM surface_messages
|
|
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
|
-
(source_kind, project_path, session_id, message_seq, message_id,
|
|
245
|
-
message_json, byte_count)
|
|
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
|
-
SELECT 1 FROM sessions
|
|
248
|
-
WHERE source_kind=? AND project_path=? AND session_id=?
|
|
249
|
-
UNION ALL
|
|
250
|
-
SELECT 1 FROM surface_messages
|
|
251
|
-
WHERE source_kind=? AND project_path=? AND session_id=?
|
|
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
|
-
(source_kind, source_file_path, project_path, session_id, last_seq, file_size,
|
|
256
|
-
mtime_ms, stat_fingerprint)
|
|
257
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
|
258
|
-
ON CONFLICT(source_kind, source_file_path) DO UPDATE SET
|
|
259
|
-
project_path=excluded.project_path, session_id=excluded.session_id,
|
|
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 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
|
-
WHERE source_kind=? AND project_path=?
|
|
267
|
-
UNION
|
|
268
|
-
SELECT session_id FROM sessions
|
|
269
|
-
WHERE source_kind=? AND project_path=?
|
|
270
|
-
UNION
|
|
271
|
-
SELECT session_id FROM parts
|
|
272
|
-
WHERE source_kind=? AND project_path=?
|
|
273
|
-
UNION
|
|
274
|
-
SELECT session_id FROM parts_fts
|
|
275
|
-
WHERE source_kind=? AND project_path=?
|
|
276
|
-
UNION
|
|
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(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
|
-
UNION
|
|
280
|
-
SELECT project_path FROM sessions WHERE source_kind='acp-remote'
|
|
281
|
-
UNION
|
|
282
|
-
SELECT project_path FROM parts WHERE source_kind='acp-remote'
|
|
283
|
-
UNION
|
|
284
|
-
SELECT project_path FROM parts_fts WHERE source_kind='acp-remote'
|
|
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(()=>{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
|
-
FROM projection_state p
|
|
289
|
-
WHERE p.source_kind='local' AND p.project_path IS NOT NULL
|
|
290
|
-
AND (p.stat_fingerprint='' OR NOT EXISTS (
|
|
291
|
-
SELECT 1 FROM sessions s WHERE s.source_kind=p.source_kind
|
|
292
|
-
AND s.project_path=p.project_path AND s.session_id=p.session_id
|
|
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
|
-
UNION SELECT source_kind, project_path, session_id FROM parts WHERE source_kind='acp-remote'
|
|
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(),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
|
-
SELECT s.source_kind, s.project_path, s.session_id, s.root_id, s.parent_id,
|
|
299
|
-
s.relation_type, s.task_status, s.first_message_time,
|
|
300
|
-
s.last_message_time, s.title, s.archived_at, s.message_count,
|
|
301
|
-
s.has_errors,
|
|
302
|
-
s.is_subagent, a.archive_root_id, a.effective_archived_at,
|
|
303
|
-
s.public_workspace_ref, s.public_workspace_sort_key,
|
|
304
|
-
s.session_sort_key, s.surface_digest, p.stat_fingerprint,
|
|
305
|
-
s.metadata_json
|
|
306
|
-
FROM sessions s
|
|
307
|
-
JOIN projection_state p
|
|
308
|
-
ON p.source_kind=s.source_kind AND p.source_file_path=s.source_file_path
|
|
309
|
-
AND p.project_path=s.project_path AND p.session_id=s.session_id
|
|
310
|
-
LEFT JOIN ranked_archive a
|
|
311
|
-
ON a.source_kind=s.source_kind AND a.project_path=s.project_path
|
|
312
|
-
AND a.public_workspace_ref IS s.public_workspace_ref
|
|
313
|
-
AND a.session_id=s.session_id AND a.rank=1
|
|
314
|
-
WHERE s.session_id=?
|
|
315
|
-
ORDER BY s.source_kind DESC, s.public_workspace_sort_key ASC,
|
|
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
|
-
OR (s.last_message_time = ? AND s.source_kind < ?)
|
|
318
|
-
OR (s.last_message_time = ? AND s.source_kind = ?
|
|
319
|
-
AND s.public_workspace_sort_key > ?)
|
|
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=R_(T),Y=T.prepare(`${mT}
|
|
322
|
-
SELECT s.source_kind, s.project_path, s.session_id, s.root_id, s.parent_id,
|
|
323
|
-
s.relation_type, s.task_status, s.first_message_time,
|
|
324
|
-
s.last_message_time, s.title, s.archived_at, s.message_count,
|
|
325
|
-
s.has_errors,
|
|
326
|
-
s.is_subagent, a.archive_root_id, a.effective_archived_at,
|
|
327
|
-
s.public_workspace_ref, s.public_workspace_sort_key,
|
|
328
|
-
s.session_sort_key, s.surface_digest, p.stat_fingerprint,
|
|
329
|
-
s.metadata_json
|
|
330
|
-
FROM sessions s
|
|
331
|
-
JOIN projection_state p
|
|
332
|
-
ON p.source_kind=s.source_kind AND p.source_file_path=s.source_file_path
|
|
333
|
-
AND p.project_path=s.project_path AND p.session_id=s.session_id
|
|
334
|
-
LEFT JOIN ranked_archive a
|
|
335
|
-
ON a.source_kind=s.source_kind AND a.project_path=s.project_path
|
|
336
|
-
AND a.public_workspace_ref IS s.public_workspace_ref
|
|
337
|
-
AND a.session_id=s.session_id AND a.rank=1
|
|
338
|
-
WHERE ${G.join(" AND ")}
|
|
339
|
-
ORDER BY s.last_message_time DESC, s.source_kind DESC,
|
|
340
|
-
s.public_workspace_sort_key ASC, s.session_sort_key ASC
|
|
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
|
-
JOIN projection_state p
|
|
343
|
-
ON p.source_kind=s.source_kind AND p.source_file_path=s.source_file_path
|
|
344
|
-
AND p.project_path=s.project_path AND p.session_id=s.session_id
|
|
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
|
-
FROM surface_messages
|
|
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 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
|
-
WHERE parts_fts MATCH ? AND source_kind = 'local' AND project_path = ?
|
|
350
|
-
ORDER BY timestamp DESC LIMIT ?`:`SELECT session_id, role, timestamp, text FROM parts_fts
|
|
351
|
-
WHERE parts_fts MATCH ? AND source_kind = 'local'
|
|
352
|
-
ORDER BY timestamp DESC LIMIT ?`,Z=T.prepare(Q);return _?Z.all(Y,_,G):Z.all(Y,G)}
|
|
353
|
-
export{o0 as pe,n as qe,t_ as re,r_ as se,o as te,K as ue,l as ve,w$ as we,S$ as xe,i_ as ye,c_ as ze,d_ as Ae,b$ as Be,R$ as Ce,s_ as De,a_ as Ee,T1 as Fe,VT as Ge,_1 as He,z0 as Ie,I0 as Je,V1 as Ke,B1 as Le,g1 as Me,LT as Ne,JT as Oe,W0 as Pe,KT as Qe,h1 as Re,P1 as Se,m1 as Te,uT as Ue,k_ as Ve,A_ as We,lT as Xe,q0 as Ye,S_ as Ze,v1 as _e,f_ as $e,u1 as af,p1 as bf,l1 as cf,R_ as df,n1 as ef,i1 as ff,c1 as gf};
|
package/dist/chunk-yvgef7rp.js
DELETED
|
@@ -1,10 +0,0 @@
|
|
|
1
|
-
import{a as T,b as W,c as X,d as Y}from"./chunk-ccgtbzrz.js";import"./chunk-b8ast0cp.js";import"./chunk-zj1g4nbq.js";import"./chunk-aatfjx15.js";import"./chunk-qp2qc4p2.js";import"./chunk-17d4m89n.js";import"./chunk-bwe49m6n.js";import"./chunk-g01mth5d.js";import"./chunk-tnmcrvk2.js";import"./chunk-kf9gj2gn.js";import"./chunk-pb1q26gw.js";import"./chunk-fdr4fcrf.js";import"./chunk-4fa11h6f.js";import"./chunk-egss0m1x.js";import"./chunk-xv6ejk2z.js";import"./chunk-efjjkha8.js";import{zf as R}from"./chunk-xbs91jd8.js";import"./chunk-p0wyhp5a.js";import{Vf as Q}from"./chunk-18swytk4.js";import"./chunk-5yyp6njq.js";import"./chunk-v508x7cg.js";import"./chunk-57939tb3.js";import"./chunk-ynd1v33f.js";import"./chunk-w42j9p3t.js";import"./chunk-zfxcef0z.js";import"./chunk-xyypxrad.js";import"./chunk-jgxfhk9k.js";import"./chunk-kehgewqh.js";import"./chunk-kkzznz4w.js";import"./chunk-1cy4ab77.js";import"./chunk-7ajvrtb3.js";import"./chunk-c51wwnh2.js";import"./chunk-ys8gysg8.js";import"./chunk-thytjs86.js";import"./chunk-tm3789m3.js";import"./chunk-qdbbke8f.js";import"./chunk-wezr6wfq.js";import"./chunk-a8z11yd2.js";import"./chunk-qtwgm95z.js";import"./chunk-0eajnhrj.js";import{Yj as M}from"./chunk-6169xxb4.js";import"./chunk-f8kjdxz7.js";import"./chunk-4wx5sya5.js";import"./chunk-eg3ms291.js";import m from"chalk";import K from"open";var A=`
|
|
2
|
-
____ _ _
|
|
3
|
-
| __ )| | __ _ __| | ___
|
|
4
|
-
| _ \\| |/ _\` |/ _\` |/ _ \\
|
|
5
|
-
| |_) | | (_| | (_| | __/
|
|
6
|
-
|____/|_|\\__,_|\\__,_|\\___|
|
|
7
|
-
`,C={command:"web",describe:"Start Blade server and open web interface",builder:T,handler:async(Z)=>{let H=W(Z);if(await Q(),!process.env.BLADE_SERVER_PASSWORD)console.log(m.yellow("[WARN] BLADE_SERVER_PASSWORD is not set; server is unsecured.")),console.log(m.gray(` Set this environment variable to enable Basic Auth.
|
|
8
|
-
`));let F=await Y.listenAsync(H);if(console.log(m.cyan(A)),console.log(m.gray(` v${M()}
|
|
9
|
-
`)),H.hostname==="0.0.0.0"){let q=`http://localhost:${F.port}`;console.log(m.blue.bold(" Local access: "),m.white(q));let x=X();for(let z of x)console.log(m.blue.bold(" Network access: "),m.white(`http://${z}:${F.port}`));K(q).catch(()=>{})}else{let q=F.url.toString();console.log(m.blue.bold(" Web interface: "),m.white(q)),K(q).catch(()=>{})}console.log(""),console.log(m.gray(` Press Ctrl+C to stop the server.
|
|
10
|
-
`));let J,$=new Promise((q)=>{J=q}),b=R(async()=>{await F.stop(),J()});try{await $}finally{b(),await F.stop()}}};export{C as webCommand};
|