blade-code 0.10.130 → 0.10.132
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-hhg1zcbq.js → chunk-0bkhpd72.js} +1 -1
- package/dist/{chunk-sn71fsm5.js → chunk-0gmbvtpp.js} +1 -1
- package/dist/{chunk-bcre3557.js → chunk-14z94k0r.js} +1 -1
- package/dist/{chunk-s2atpv23.js → chunk-3e0t25rq.js} +2 -2
- package/dist/{chunk-h1wphqkc.js → chunk-53j6nh8j.js} +1 -1
- package/dist/{chunk-51qc7n8t.js → chunk-64kg5a9r.js} +1 -1
- package/dist/{chunk-9yqadjea.js → chunk-6q3g5e3m.js} +1 -1
- package/dist/{chunk-pk11fexz.js → chunk-749jzrbk.js} +1 -1
- package/dist/{chunk-e1d0e6t6.js → chunk-7dy3mzgz.js} +1 -1
- package/dist/{chunk-ss4sncn3.js → chunk-8y08fytr.js} +1 -1
- package/dist/{chunk-v5hzk7j2.js → chunk-9d49tj9y.js} +1 -1
- package/dist/{chunk-gfbkrk60.js → chunk-b5z1rec4.js} +29 -29
- package/dist/{chunk-xa9k5pjt.js → chunk-bavzm721.js} +1 -1
- package/dist/{chunk-te6203yf.js → chunk-dhzbac1c.js} +1 -1
- package/dist/{chunk-t4apxzp1.js → chunk-dvb89529.js} +1 -1
- package/dist/{chunk-8a6nrqdc.js → chunk-e371f7xk.js} +1 -1
- package/dist/{chunk-p2sp2e0a.js → chunk-fag8rk53.js} +1 -1
- package/dist/{chunk-4sxxvtn4.js → chunk-g12kqs1b.js} +1 -1
- package/dist/{chunk-42h7kj6p.js → chunk-g1bqjdeq.js} +1 -1
- package/dist/{chunk-zc91c7b5.js → chunk-j3nmt09e.js} +1 -1
- package/dist/{chunk-2bnpn8be.js → chunk-mg1s861p.js} +1 -1
- package/dist/{chunk-fjv2vede.js → chunk-pkg1bvzc.js} +1 -1
- package/dist/{chunk-hw1gbr11.js → chunk-pqsvz99n.js} +1 -1
- package/dist/{chunk-kfkvdj49.js → chunk-prt6y5fv.js} +1 -1
- package/dist/chunk-q7m0tvhw.js +1 -0
- package/dist/{chunk-5a17mdjd.js → chunk-qcydkn1n.js} +1 -1
- package/dist/{chunk-r9tawy93.js → chunk-r7kevfd3.js} +1 -1
- package/dist/{chunk-7jj607dg.js → chunk-rj8mmwc6.js} +1 -1
- package/dist/{chunk-tw5fr07c.js → chunk-sbc90z9j.js} +1 -1
- package/dist/{chunk-gzz0gnmv.js → chunk-sf9sbm6y.js} +1 -1
- package/dist/{chunk-qahz5x5c.js → chunk-sm9p1fkf.js} +1 -1
- package/dist/{chunk-a4jetpj8.js → chunk-t8rjxqp2.js} +1 -1
- package/dist/{chunk-55hq1ps4.js → chunk-td2jk2xn.js} +2 -2
- package/dist/{chunk-v94ztjtp.js → chunk-xjrmq0pg.js} +3 -3
- package/dist/{chunk-ss86eq2h.js → chunk-xyxjcehh.js} +1 -1
- package/dist/{chunk-9et78e3v.js → chunk-y0kqkewg.js} +1 -1
- package/dist/{chunk-dkgaxmsp.js → chunk-z28dcrr9.js} +1 -1
- package/dist/chunk-z83xk6jn.js +1 -0
- package/dist/{chunk-b8m7zc7t.js → chunk-znqt5g8v.js} +1 -1
- package/dist/{chunk-agda17kj.js → chunk-zssz8hc4.js} +1 -1
- package/dist/web/assets/{ChatView-Bg36FUaj.js → ChatView-CkmlibKO.js} +4 -4
- package/dist/web/assets/{CodeBlockHighlighter-D5rB73Eo.js → CodeBlockHighlighter-DR5RLA1_.js} +1 -1
- package/dist/web/assets/{FilePreview-BxaBSmap.js → FilePreview-C4tqzUOM.js} +1 -1
- package/dist/web/assets/{KanbanBoard-B4gx3JMo.js → KanbanBoard-D7HJQXE2.js} +1 -1
- package/dist/web/assets/{MarkdownRenderer-BRH7LHhN.js → MarkdownRenderer-Ct8vtONO.js} +3 -3
- package/dist/web/assets/{ScrollArea-DikU3QeQ.js → ScrollArea-CMSE6nO4.js} +1 -1
- package/dist/web/assets/{SessionHistorySurface-DG80d6-F.js → SessionHistorySurface-BPwnF9ND.js} +1 -1
- package/dist/web/assets/{SettingsModal-Bxqkok81.js → SettingsModal-KW5WYAov.js} +1 -1
- package/dist/web/assets/{Sidebar-DGaHGcHx.js → Sidebar-8BUNEHHQ.js} +1 -1
- package/dist/web/assets/{TaskSwitcher-DOnLPurk.js → TaskSwitcher-CZfkp2L_.js} +1 -1
- package/dist/web/assets/{TerminalPanel-BzhCF9vw.js → TerminalPanel-DBBMaU_6.js} +1 -1
- package/dist/web/assets/{archive-BiDGrqry.js → archive-tBd5snSF.js} +1 -1
- package/dist/web/assets/{arrow-left-BY-esOAP.js → arrow-left-Cs_sFMp-.js} +1 -1
- package/dist/web/assets/{calendar-clock-BCyxvfVt.js → calendar-clock-C0ue6XTy.js} +1 -1
- package/dist/web/assets/{chevron-right-Bg-10yuN.js → chevron-right-DZHCUfAH.js} +1 -1
- package/dist/web/assets/{chevrons-up-down-M5SAJq7T.js → chevrons-up-down-BSa16Scz.js} +1 -1
- package/dist/web/assets/{clock-3-v-nHTA0A.js → clock-3-DstAM2AR.js} +1 -1
- package/dist/web/assets/{copy-p1zc_rjZ.js → copy-BfnFXTgG.js} +1 -1
- package/dist/web/assets/{download-D_-kbJXR.js → download-XKyNtMnj.js} +1 -1
- package/dist/web/assets/{external-link-wSGTIqe3.js → external-link-3bcWFMya.js} +1 -1
- package/dist/web/assets/{folder-Ltm9jCS5.js → folder-D7hQLvy7.js} +1 -1
- package/dist/web/assets/index-CCdnLriX.js +210 -0
- package/dist/web/assets/{pause-_LvCZkxM.js → pause-CBR55GXy.js} +1 -1
- package/dist/web/assets/{pencil-DB6ICr_h.js → pencil-8yqeFHC4.js} +1 -1
- package/dist/web/assets/{play-BRXP1rHJ.js → play-F_Spkp4p.js} +1 -1
- package/dist/web/assets/{plus-BqvjEpLw.js → plus-CJCqq3rG.js} +1 -1
- package/dist/web/assets/{session-events-AGMXvPey.js → session-events-C6fPz20c.js} +4 -4
- package/dist/web/assets/{settings-LfQbDvBA.js → settings-G6riyt4S.js} +1 -1
- package/dist/web/assets/{teamService-B5FnUcet.js → teamService-Cixkq48S.js} +1 -1
- package/dist/web/assets/{terminal-By4sO9Gw.js → terminal-_Nebc2yj.js} +1 -1
- package/dist/web/index.html +1 -1
- package/package.json +1 -1
- package/dist/chunk-1bb4h5gf.js +0 -1
- package/dist/chunk-saedy6bj.js +0 -1
- package/dist/web/assets/index-_xnlrekR.js +0 -210
|
@@ -1,12 +1,12 @@
|
|
|
1
|
-
import{Te as
|
|
2
|
-
`);async function t(T){try{let $;if(cT()){let{Database:G}=await import("bun:sqlite");$=sT(new G(T))}else{let X=(await import("better-sqlite3")).default;$=dT(new X(T))}return $.exec(aT),$}catch{return null}}var eT="surface-workspaces-v1",n0=/^[a-f0-9]{64}$/,T$=/^acp-remote-workspace:[A-Za-z0-9_-]{43}$/,$$=1024,_$=".surface-workspaces-v1.capacity.sqlite",i0=/^\.tmp-acp-remote-workspace-([1-9][0-9]*)-[a-f0-9]{32}\.pending$/;class M 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 P,o=new Map;function c0(T){return K.join(String(T),eT)}async function d0(T,$){let _=D($);if(i(_.collisionIdentity)!==String(T))throw new M("session_surface_state_invalid");let G=a0(_.exactIdentity),X=c0(T);return await X$(T,X),G$(X,()=>Y$(X,async()=>{await V$(X);let Y=await s0(T,X,!0),Q=Y.recordsByDigest.get(G);if(Q)return Q.workspaceRef;if(Y.recordsByDigest.size>=$$)throw new M("session_surface_capacity");let Z=K.join(X,`${G}.json`),U=new Set(Y.workspaceRefToDigest.keys());for(let V=0;V<32;V+=1){let g=H$();if(U.has(g))continue;return L$(T,X,Z,_,{version:1,exactIdentityDigest:G,workspaceRef:g})}throw new M("session_surface_state_invalid")}))}async function G$(T,$){let _=o.get(T)??Promise.resolve(),G=()=>{return},X=new Promise((Q)=>{G=Q}),Y=_.catch(()=>{return}).then(()=>X);o.set(T,Y),await _.catch(()=>{return});try{return await $()}finally{if(G(),o.get(T)===Y)o.delete(T)}}async function X$(T,$){try{await V0($,String(T))}catch(_){if(x(_)!=="ENOENT"){if(_ instanceof M)throw _;throw new M("session_surface_state_invalid")}try{await rT($,{recursive:!1,mode:448})}catch(G){if(x(G)!=="EEXIST")throw new M("session_surface_state_invalid")}await V0($,String(T)),await h(String(T))}}async function Y$(T,$){await P?.beforeCapacityLockAttempt?.();let _=await Q$(T),G=!1,X,Y,Q;try{_.database.exec("BEGIN IMMEDIATE;"),G=!0,await P?.afterCapacityLockAcquired?.(),Q={value:await $()}}catch(Z){X=Z}if(G)try{await Z$(_),_.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 M("session_surface_state_invalid");if(X instanceof M)throw X;if(X!==void 0||!Q)throw new M("session_surface_state_invalid");return Q.value}async function Q$(T){let $=K.join(T,_$),_=null,G;try{let X=!1;try{let Q=await l($,"wx",384);X=!0,await Q.sync(),await Q.close()}catch(Q){if(x(Q)!=="EEXIST")throw Q}if(await m($,T),X)await h(T);G=await l($,"r"),await n(G,$,T);let Y=await G.stat({bigint:!0});if(_=await t($),!_)throw new M("session_surface_state_invalid");if(_.exec("PRAGMA locking_mode=NORMAL;"),_.exec("PRAGMA journal_mode=DELETE;"),_.exec("PRAGMA synchronous=FULL;"),_.exec("PRAGMA busy_timeout=30000;"),process.platform!=="win32")await p0($,384);return await n(G,$,T),await U$($,T),{database:_,identity:Y,identityHandle:G,path:$}}catch(X){await G?.close().catch(()=>{return});try{_?.close()}catch{}if(X instanceof M)throw X;throw new M("session_surface_state_invalid")}}async function Z$(T){await n(T.identityHandle,T.path,K.dirname(T.path));let $=await T.identityHandle.stat({bigint:!0});if(!B0(T.identity,$))throw new M("session_surface_state_invalid")}async function U$(T,$){for(let _ of["-journal","-shm","-wal"]){let G=`${T}${_}`;try{if(process.platform!=="win32")await p0(G,384);await m(G,$)}catch(X){if(x(X)!=="ENOENT"){if(X instanceof M)throw X;throw new M("session_surface_state_invalid")}}}}async function V$(T){let $=await l0(T,{withFileTypes:!0}),_=!1;for(let G of $){if(!i0.test(G.name))continue;let X=K.join(T,G.name);await m(X,T),await U0(X),_=!0}if(_)await h(T)}async function s0(T,$,_){try{await V0($,String(T))}catch(Q){if(!_&&x(Q)==="ENOENT")return{recordsByDigest:new Map,workspaceRefToDigest:new Map};if(Q instanceof M)throw Q;throw new M("session_surface_state_invalid")}let G;try{G=await l0($,{withFileTypes:!0})}catch(Q){if(!_&&x(Q)==="ENOENT")return{recordsByDigest:new Map,workspaceRefToDigest:new Map};throw new M("session_surface_state_invalid")}let X=new Map,Y=new Map;for(let Q of G){if(i0.test(Q.name)){await m(K.join($,Q.name),$);continue}if(!Q.name.endsWith(".json"))continue;let Z=K.basename(Q.name,".json");if(!n0.test(Z))throw new M("session_surface_state_invalid");let U=K.join($,Q.name),V=await B$(U,$);if(V.exactIdentityDigest!==Z)throw new M("session_surface_state_invalid");if(X.has(Z))throw new M("session_surface_state_invalid");let g=Y.get(V.workspaceRef);if(g&&g!==Z)throw new M("session_surface_state_invalid");X.set(Z,V),Y.set(V.workspaceRef,Z)}return{recordsByDigest:X,workspaceRefToDigest:Y}}async function B$(T,$){let _;try{await m(T,$),_=await l(T,"r"),await n(_,T,$);let G=await _.readFile({encoding:"utf8"});return g$(G)}catch(G){if(G instanceof M&&G.code==="session_surface_not_found")throw G;if(x(G)==="ENOENT")throw new M("session_surface_not_found");throw new M("session_surface_state_invalid")}finally{await _?.close()}}function g$(T){let $;try{$=JSON.parse(T)}catch{throw new M("session_surface_state_invalid")}if(!M$($))throw new M("session_surface_state_invalid");return $}function M$(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"&&n0.test($.exactIdentityDigest)&&typeof $.workspaceRef==="string"&&T$.test($.workspaceRef)}function a0(T){return tT("sha256").update(`acp-remote-workspace-exact-identity\x00${T}`).digest("hex")}function H$(){return`acp-remote-workspace:${u0(32).toString("base64url")}`}function O$(){return`.tmp-acp-remote-workspace-${process.pid}-${u0(16).toString("hex")}.pending`}async function V0(T,$){if(K.dirname(T)!==$)throw new M("session_surface_state_invalid");let _=await p(T);if(_.isSymbolicLink()||!_.isDirectory())throw new M("session_surface_state_invalid");if(typeof process.getuid==="function"&&_.uid!==process.getuid())throw new M("session_surface_state_invalid");let G=t0(_.mode);if(process.platform!=="win32"&&G!==448)throw new M("session_surface_state_invalid");await g0(T,$,K.basename(T))}async function m(T,$){if(K.dirname(T)!==$)throw new M("session_surface_state_invalid");let _=await p(T);if(_.isSymbolicLink()||!_.isFile())throw new M("session_surface_state_invalid");if(typeof process.getuid==="function"&&_.uid!==process.getuid())throw new M("session_surface_state_invalid");let G=t0(_.mode);if(process.platform!=="win32"&&G!==384)throw new M("session_surface_state_invalid");await g0(T,$,K.basename(T))}async function n(T,$,_){let[G,X]=await Promise.all([T.stat({bigint:!0}),p($,{bigint:!0})]);if(K.dirname($)!==_||X.isSymbolicLink()||!X.isFile()||!G.isFile()||X.dev!==G.dev||X.ino!==G.ino)throw new M("session_surface_state_invalid");if(typeof process.getuid==="function"&&(Number(X.uid)!==process.getuid()||Number(G.uid)!==process.getuid()))throw new M("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 M("session_surface_state_invalid");await g0($,_,K.basename($))}async function g0(T,$,_){let G=await v0(T),X=await v0($);if(G!==K.join(X,_))throw new M("session_surface_state_invalid")}async function h(T){if(!C$(process.platform))return;try{if(P?.syncDirectory){await P.syncDirectory(T);return}await F$(T)}catch{throw new M("session_surface_state_invalid")}}function C$(T){return T!=="win32"}async function F$(T){let $=await l(T,"r");try{await $.sync()}finally{await $.close()}}async function L$(T,$,_,G,X){let Y=K.join($,O$()),Q,Z,U=!1,V=!1,g,H;try{Q=await l(Y,"wx",384),await Q.writeFile(JSON.stringify(X),"utf8"),await Q.sync(),await n(Q,Y,$),Z=await Q.stat({bigint:!0}),await Q.close(),Q=void 0,await P?.beforePublish?.({finalPath:_,referenceDirectoryPath:$,tempPath:Y});try{await oT(Y,_),U=!0}catch(O){if(x(O)!=="EEXIST")throw O;g=await J$(T,G)}if(U){let O=await p(_,{bigint:!0});if(!Z||!B0(Z,O))throw new M("session_surface_state_invalid");await m(_,$),await h($),V=!0,g=X.workspaceRef;try{await P?.afterPublish?.({finalPath:_,referenceDirectoryPath:$,tempPath:Y})}catch{}}}catch(O){H=O}finally{await Q?.close().catch(()=>{return})}if(H!==void 0&&U&&!V&&Z)try{let O=await p(_,{bigint:!0});if(B0(Z,O))await U0(_),await h($)}catch{}try{if(await U0(Y),!V)await h($)}catch(O){if(x(O)!=="ENOENT"&&H===void 0&&!V)H=O}if(H instanceof M)throw H;if(H!==void 0||g===void 0)throw new M("session_surface_state_invalid");return g}async function J$(T,$){let _=c0(T),G=await s0(T,_,!0),X=a0(D($).exactIdentity),Y=G.recordsByDigest.get(X);if(!Y)throw new M("session_surface_state_invalid");return Y.workspaceRef}function B0(T,$){return BigInt(T.dev)===BigInt($.dev)&&BigInt(T.ino)===BigInt($.ino)}function x(T){return T!==null&&typeof T==="object"&&"code"in T&&typeof T.code==="string"?T.code:void 0}function t0(T){return typeof T==="bigint"?Number(T&BigInt(511)):T&511}import*as f from"node:path";var $T=50,_T=100,z$=new Set(["queued","running","completed","failed","cancelled","interrupted"]),N$=new Set(["high","medium","low"]),GT=/^[A-Za-z0-9_-]+$/,I$=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?(?:Z|[+-]\d{2}:\d{2})$/,K$=/^acp-remote-exact-path:[a-f0-9]{64}$/;function XT(T){return typeof T==="string"&&I$.test(T)&&Number.isFinite(Date.parse(T))}function o0(T){return typeof T==="string"&&f.isAbsolute(T)}function r0(T){return typeof T==="string"&&K$.test(T)}function W$(T){return Buffer.from(JSON.stringify(T),"utf8").toString("base64url")}function j$(T){return Buffer.from(JSON.stringify(T),"utf8").toString("base64url")}function k$(T){try{if(!GT.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||o0(_.cwd))||!XT(_.lastMessageTime)||!o0(_.projectPath)||!k(_.sessionId))throw Error("invalid");return{version:1,kind:"local",cwd:_.cwd===null?null:f.resolve(_.cwd),includeSubagents:_.includeSubagents,archived:_.archived??!1,lastMessageTime:_.lastMessageTime,projectPath:f.resolve(_.projectPath),sessionId:_.sessionId}}catch{throw Error("Invalid session cursor")}}function A$(T){try{if(!GT.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||r0(_.exactIdentity))||!XT(_.lastMessageTime)||!r0(_.workspaceIdentity)||!k(_.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 v(T){let $="";for(let _=0;_<T.length;_+=1)$+=T.charCodeAt(_).toString(16).padStart(4,"0");return $}function x$(T){if(!T.cursor)return;let $=k$(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 E$(T){if(!T.cursor)return;let $=A$(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 l_(T={}){let{cwd:$,cursor:_,limit:G,includeSubagents:X=!1,archived:Y=!1}=T;if($!==void 0&&!f.isAbsolute($))throw Error("Session catalog cwd must be absolute");let Q=G===void 0?$T:G;if(!Number.isInteger(Q)||Q<1||Q>_T)throw Error("Session catalog limit must be an integer from 1 to 100");return{cwd:$===void 0?null:f.resolve($),cursor:_??void 0,limit:Q,includeSubagents:X,archived:Y}}function n_(T={}){let{descriptor:$,cursor:_,limit:G,includeSubagents:X=!1,archived:Y=!1}=T,Q=G===void 0?$T:G;if(!Number.isInteger(Q)||Q<1||Q>_T)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 i_(T={}){let $=e0(T.taskStatus,z$,"task status"),_=e0(T.taskPriority,N$,"task priority"),G=TT(T.taskDueAfter,"taskDueAfter"),X=TT(T.taskDueBefore,"taskDueBefore");return q$(G,X),{...$?{taskStatuses:$}:{},..._?{taskPriorities:_}:{},...G?{taskDueAfter:G}:{},...X?{taskDueBefore:X}:{}}}function e0(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 TT(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 q$(T,$){if(T!==void 0&&$!==void 0&&T>$)throw Error("Session task due range is inverted")}function D$(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 c_(T,$){let _=[...T],G=x$($);if(G)_=_.filter((Q)=>D$(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:W$({version:1,kind:"local",cwd:$.cwd,includeSubagents:$.includeSubagents,archived:$.archived,lastMessageTime:Y.lastMessageTime,projectPath:Y.projectPath,sessionId:Y.sessionId})}}function d_(T,$){let _=[...T],G=E$($);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:j$({version:1,kind:"remote",exactIdentity:$.exactIdentity,includeSubagents:$.includeSubagents,archived:$.archived,lastMessageTime:Y.lastMessageTime,workspaceIdentity:Y.workspaceIdentity,sessionId:Y.sessionId})}}function w$(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 M0(T){return T.type==="message_created"&&T.data.role==="user"&&(T.data.inboxMessageId!==void 0||T.data.parentMessageId===void 0)}function H0(T,$){let _=T.find((G)=>M0(G)&&G.data.messageId===$);if(!_)throw Error(`Rewind checkpoint not found: ${$}`);return{messageId:$,preview:YT(T,$),createdAt:_.data.createdAt}}function YT(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 QT(T,$){H0(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<_||!w$(Q)})}function u(T){let $=[];for(let _ of T){if(_.type!=="session_rewound"){$.push(_);continue}if(H0($,_.data.targetMessageId),_.data.mode!=="code")$=QT($,_.data.targetMessageId)}return $}function a_(T){let $=u(T);return $.filter(M0).map((_)=>({messageId:_.data.messageId,preview:YT($,_.data.messageId),createdAt:_.data.createdAt})).reverse()}function t_(T,$){let _=u(T),G=H0(_,$),X=_.findIndex((Q)=>Q.type==="message_created"&&Q.data.messageId===$),Y=_.slice(X);return{checkpoint:G,projectedEntries:QT(_,$),removedTurns:Y.filter(M0).length,snapshotMessageIds:Y.flatMap((Q)=>Q.type==="part_created"&&Q.data.partType==="tool_call"?[Q.data.partId]:[])}}import{createHash as n$}from"node:crypto";var r_={clientVisible:!1};function ZT(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 R$}from"node:string_decoder";var T1=1048576;function O0(T,$){let _=$;while(_<T.length&&(T[_]&192)===128)_+=1;return _}class C0{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 $=O0(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=O0($,_);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 $=O0(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 r={maxLines:30,maxChars:3000,keepHead:10,keepTail:10,summarize:!0},R={maxLines:100,maxChars:1e4,keepHead:40,keepTail:40,summarize:!0},UT={maxLines:200,maxChars:20000,keepHead:80,keepTail:80,summarize:!1},S$={maxLines:150,maxChars:15000,keepHead:50,keepTail:50,summarize:!0},f$=[{pattern:/^git\s+(rm|add)\s+(-r|--cached|-rf|-f)?\s*/i,config:r,summaryTemplate:(T)=>`Successfully processed ${T} files`},{pattern:/^(npm|pnpm|yarn|bun)\s+(install|i|add|remove|uninstall)/i,config:r,summaryTemplate:(T)=>`Package operation completed (${T} lines of output)`},{pattern:/^(npm|pnpm|yarn|bun)\s+(run|exec)\s+(build|compile|bundle)/i,config:R,summaryTemplate:(T)=>`Build completed (${T} lines of output)`},{pattern:/^(npm|pnpm|yarn|bun)\s+(run|exec)\s+(test|lint|check)/i,config:UT},{pattern:/^git\s+(status|branch|remote)/i,config:R},{pattern:/^git\s+(log|diff|show)/i,config:UT},{pattern:/^(ls|dir|tree)\s+/i,config:R,summaryTemplate:(T)=>`Listed ${T} items`},{pattern:/^find\s+/i,config:R,summaryTemplate:(T)=>`Found ${T} matches`},{pattern:/^(grep|rg|ag)\s+/i,config:R,summaryTemplate:(T)=>`Found ${T} matching lines`},{pattern:/^(docker|podman)\s+(build|pull|push)/i,config:r,summaryTemplate:(T)=>`Docker operation completed (${T} lines)`},{pattern:/^(pip|pip3|poetry|pipenv)\s+(install|uninstall)/i,config:r,summaryTemplate:(T)=>`Python package operation completed (${T} lines)`},{pattern:/^(cargo|rustup)\s+(build|install|update)/i,config:R,summaryTemplate:(T)=>`Rust operation completed (${T} lines)`},{pattern:/^(go)\s+(build|get|mod)/i,config:R,summaryTemplate:(T)=>`Go operation completed (${T} lines)`}];function VT(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 F0{static getConfigForCommand(T){for(let{pattern:$,config:_,summaryTemplate:G}of f$)if($.test(T))return{config:_,summaryTemplate:G};return{config:S$}}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{Te as w0}from"./chunk-0z9nqbd0.js";import{ih as MT}from"./chunk-g4xny949.js";import{oj as yT}from"./chunk-ar5np5h5.js";import{$j as bT,Mj as X0,Uj as E,Wj as D,Xj as i,Zj as c,_j as j0,ak as ST,bk as fT,fk as k,hk as D0,ik as a,qk as RT}from"./chunk-pj69j4zp.js";import{rk as Z0}from"./chunk-zkzhm39s.js";import{createHash as C_}from"node:crypto";import{readdir as k0,stat as A0}from"node:fs/promises";import G0 from"node:path";import{createHash as tT,randomBytes as u0}from"node:crypto";import{chmod as p0,link as oT,lstat as p,mkdir as rT,open as l,readdir as l0,realpath as v0,unlink as U0}from"node:fs/promises";import K from"node:path";function cT(){return typeof globalThis.Bun<"u"}function dT(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 sT(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 aT(T){return[`PRAGMA busy_timeout=${T};`,"PRAGMA journal_mode=WAL;","PRAGMA synchronous=NORMAL;","PRAGMA foreign_keys=ON;"].join(`
|
|
2
|
+
`)}async function t(T,$={}){let _=$.busyTimeoutMs??5000;if(!Number.isSafeInteger(_)||_<0)return null;let G=null;try{if(cT()){let{Database:Y}=await import("bun:sqlite");G=sT(new Y(T))}else{let Q=(await import("better-sqlite3")).default;G=dT(new Q(T))}return G.exec(aT(_)),G}catch{try{G?.close()}catch{}return null}}var eT="surface-workspaces-v1",n0=/^[a-f0-9]{64}$/,T$=/^acp-remote-workspace:[A-Za-z0-9_-]{43}$/,$$=1024,_$=".surface-workspaces-v1.capacity.sqlite",i0=/^\.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 P,o=new Map;function c0(T){return K.join(String(T),eT)}async function d0(T,$){let _=D($);if(i(_.collisionIdentity)!==String(T))throw new H("session_surface_state_invalid");let G=a0(_.exactIdentity),X=c0(T);return await X$(T,X),G$(X,()=>Y$(X,async()=>{await V$(X);let Y=await s0(T,X,!0),Q=Y.recordsByDigest.get(G);if(Q)return Q.workspaceRef;if(Y.recordsByDigest.size>=$$)throw new H("session_surface_capacity");let Z=K.join(X,`${G}.json`),U=new Set(Y.workspaceRefToDigest.keys());for(let V=0;V<32;V+=1){let g=O$();if(U.has(g))continue;return L$(T,X,Z,_,{version:1,exactIdentityDigest:G,workspaceRef:g})}throw new H("session_surface_state_invalid")}))}async function G$(T,$){let _=o.get(T)??Promise.resolve(),G=()=>{return},X=new Promise((Q)=>{G=Q}),Y=_.catch(()=>{return}).then(()=>X);o.set(T,Y),await _.catch(()=>{return});try{return await $()}finally{if(G(),o.get(T)===Y)o.delete(T)}}async function X$(T,$){try{await V0($,String(T))}catch(_){if(x(_)!=="ENOENT"){if(_ instanceof H)throw _;throw new H("session_surface_state_invalid")}try{await rT($,{recursive:!1,mode:448})}catch(G){if(x(G)!=="EEXIST")throw new H("session_surface_state_invalid")}await V0($,String(T)),await h(String(T))}}async function Y$(T,$){await P?.beforeCapacityLockAttempt?.();let _=await Q$(T),G=!1,X,Y,Q;try{_.database.exec("BEGIN IMMEDIATE;"),G=!0,await P?.afterCapacityLockAcquired?.(),Q={value:await $()}}catch(Z){X=Z}if(G)try{await Z$(_),_.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 Q$(T){let $=K.join(T,_$),_=null,G;try{let X=!1;try{let Q=await l($,"wx",384);X=!0,await Q.sync(),await Q.close()}catch(Q){if(x(Q)!=="EEXIST")throw Q}if(await m($,T),X)await h(T);G=await l($,"r"),await n(G,$,T);let Y=await G.stat({bigint:!0});if(_=await t($,{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 p0($,384);return await n(G,$,T),await U$($,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 Z$(T){await n(T.identityHandle,T.path,K.dirname(T.path));let $=await T.identityHandle.stat({bigint:!0});if(!B0(T.identity,$))throw new H("session_surface_state_invalid")}async function U$(T,$){for(let _ of["-journal","-shm","-wal"]){let G=`${T}${_}`;try{if(process.platform!=="win32")await p0(G,384);await m(G,$)}catch(X){if(x(X)!=="ENOENT"){if(X instanceof H)throw X;throw new H("session_surface_state_invalid")}}}}async function V$(T){let $=await l0(T,{withFileTypes:!0}),_=!1;for(let G of $){if(!i0.test(G.name))continue;let X=K.join(T,G.name);await m(X,T),await U0(X),_=!0}if(_)await h(T)}async function s0(T,$,_){try{await V0($,String(T))}catch(Q){if(!_&&x(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 l0($,{withFileTypes:!0})}catch(Q){if(!_&&x(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(i0.test(Q.name)){await m(K.join($,Q.name),$);continue}if(!Q.name.endsWith(".json"))continue;let Z=K.basename(Q.name,".json");if(!n0.test(Z))throw new H("session_surface_state_invalid");let U=K.join($,Q.name),V=await B$(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 B$(T,$){let _;try{await m(T,$),_=await l(T,"r"),await n(_,T,$);let G=await _.readFile({encoding:"utf8"});return g$(G)}catch(G){if(G instanceof H&&G.code==="session_surface_not_found")throw G;if(x(G)==="ENOENT")throw new H("session_surface_not_found");throw new H("session_surface_state_invalid")}finally{await _?.close()}}function g$(T){let $;try{$=JSON.parse(T)}catch{throw new H("session_surface_state_invalid")}if(!H$($))throw new H("session_surface_state_invalid");return $}function H$(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"&&n0.test($.exactIdentityDigest)&&typeof $.workspaceRef==="string"&&T$.test($.workspaceRef)}function a0(T){return tT("sha256").update(`acp-remote-workspace-exact-identity\x00${T}`).digest("hex")}function O$(){return`acp-remote-workspace:${u0(32).toString("base64url")}`}function M$(){return`.tmp-acp-remote-workspace-${process.pid}-${u0(16).toString("hex")}.pending`}async function V0(T,$){if(K.dirname(T)!==$)throw new H("session_surface_state_invalid");let _=await p(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=t0(_.mode);if(process.platform!=="win32"&&G!==448)throw new H("session_surface_state_invalid");await g0(T,$,K.basename(T))}async function m(T,$){if(K.dirname(T)!==$)throw new H("session_surface_state_invalid");let _=await p(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=t0(_.mode);if(process.platform!=="win32"&&G!==384)throw new H("session_surface_state_invalid");await g0(T,$,K.basename(T))}async function n(T,$,_){let[G,X]=await Promise.all([T.stat({bigint:!0}),p($,{bigint:!0})]);if(K.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 g0($,_,K.basename($))}async function g0(T,$,_){let G=await v0(T),X=await v0($);if(G!==K.join(X,_))throw new H("session_surface_state_invalid")}async function h(T){if(!C$(process.platform))return;try{if(P?.syncDirectory){await P.syncDirectory(T);return}await F$(T)}catch{throw new H("session_surface_state_invalid")}}function C$(T){return T!=="win32"}async function F$(T){let $=await l(T,"r");try{await $.sync()}finally{await $.close()}}async function L$(T,$,_,G,X){let Y=K.join($,M$()),Q,Z,U=!1,V=!1,g,O;try{Q=await l(Y,"wx",384),await Q.writeFile(JSON.stringify(X),"utf8"),await Q.sync(),await n(Q,Y,$),Z=await Q.stat({bigint:!0}),await Q.close(),Q=void 0,await P?.beforePublish?.({finalPath:_,referenceDirectoryPath:$,tempPath:Y});try{await oT(Y,_),U=!0}catch(M){if(x(M)!=="EEXIST")throw M;g=await J$(T,G)}if(U){let M=await p(_,{bigint:!0});if(!Z||!B0(Z,M))throw new H("session_surface_state_invalid");await m(_,$),await h($),V=!0,g=X.workspaceRef;try{await P?.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 p(_,{bigint:!0});if(B0(Z,M))await U0(_),await h($)}catch{}try{if(await U0(Y),!V)await h($)}catch(M){if(x(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 _=c0(T),G=await s0(T,_,!0),X=a0(D($).exactIdentity),Y=G.recordsByDigest.get(X);if(!Y)throw new H("session_surface_state_invalid");return Y.workspaceRef}function B0(T,$){return BigInt(T.dev)===BigInt($.dev)&&BigInt(T.ino)===BigInt($.ino)}function x(T){return T!==null&&typeof T==="object"&&"code"in T&&typeof T.code==="string"?T.code:void 0}function t0(T){return typeof T==="bigint"?Number(T&BigInt(511)):T&511}import*as f from"node:path";var $T=50,_T=100,N$=new Set(["queued","running","completed","failed","cancelled","interrupted"]),z$=new Set(["high","medium","low"]),GT=/^[A-Za-z0-9_-]+$/,I$=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?(?:Z|[+-]\d{2}:\d{2})$/,K$=/^acp-remote-exact-path:[a-f0-9]{64}$/;function XT(T){return typeof T==="string"&&I$.test(T)&&Number.isFinite(Date.parse(T))}function o0(T){return typeof T==="string"&&f.isAbsolute(T)}function r0(T){return typeof T==="string"&&K$.test(T)}function W$(T){return Buffer.from(JSON.stringify(T),"utf8").toString("base64url")}function j$(T){return Buffer.from(JSON.stringify(T),"utf8").toString("base64url")}function k$(T){try{if(!GT.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||o0(_.cwd))||!XT(_.lastMessageTime)||!o0(_.projectPath)||!k(_.sessionId))throw Error("invalid");return{version:1,kind:"local",cwd:_.cwd===null?null:f.resolve(_.cwd),includeSubagents:_.includeSubagents,archived:_.archived??!1,lastMessageTime:_.lastMessageTime,projectPath:f.resolve(_.projectPath),sessionId:_.sessionId}}catch{throw Error("Invalid session cursor")}}function A$(T){try{if(!GT.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||r0(_.exactIdentity))||!XT(_.lastMessageTime)||!r0(_.workspaceIdentity)||!k(_.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 v(T){let $="";for(let _=0;_<T.length;_+=1)$+=T.charCodeAt(_).toString(16).padStart(4,"0");return $}function x$(T){if(!T.cursor)return;let $=k$(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 E$(T){if(!T.cursor)return;let $=A$(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 l_(T={}){let{cwd:$,cursor:_,limit:G,includeSubagents:X=!1,archived:Y=!1}=T;if($!==void 0&&!f.isAbsolute($))throw Error("Session catalog cwd must be absolute");let Q=G===void 0?$T:G;if(!Number.isInteger(Q)||Q<1||Q>_T)throw Error("Session catalog limit must be an integer from 1 to 100");return{cwd:$===void 0?null:f.resolve($),cursor:_??void 0,limit:Q,includeSubagents:X,archived:Y}}function n_(T={}){let{descriptor:$,cursor:_,limit:G,includeSubagents:X=!1,archived:Y=!1}=T,Q=G===void 0?$T:G;if(!Number.isInteger(Q)||Q<1||Q>_T)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 i_(T={}){let $=e0(T.taskStatus,N$,"task status"),_=e0(T.taskPriority,z$,"task priority"),G=TT(T.taskDueAfter,"taskDueAfter"),X=TT(T.taskDueBefore,"taskDueBefore");return q$(G,X),{...$?{taskStatuses:$}:{},..._?{taskPriorities:_}:{},...G?{taskDueAfter:G}:{},...X?{taskDueBefore:X}:{}}}function e0(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 TT(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 q$(T,$){if(T!==void 0&&$!==void 0&&T>$)throw Error("Session task due range is inverted")}function D$(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 w$(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 c_(T,$){let _=[...T],G=x$($);if(G)_=_.filter((Q)=>D$(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:W$({version:1,kind:"local",cwd:$.cwd,includeSubagents:$.includeSubagents,archived:$.archived,lastMessageTime:Y.lastMessageTime,projectPath:Y.projectPath,sessionId:Y.sessionId})}}function d_(T,$){let _=[...T],G=E$($);if(G)_=_.filter((Q)=>w$(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:j$({version:1,kind:"remote",exactIdentity:$.exactIdentity,includeSubagents:$.includeSubagents,archived:$.archived,lastMessageTime:Y.lastMessageTime,workspaceIdentity:Y.workspaceIdentity,sessionId:Y.sessionId})}}function b$(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 H0(T){return T.type==="message_created"&&T.data.role==="user"&&(T.data.inboxMessageId!==void 0||T.data.parentMessageId===void 0)}function O0(T,$){let _=T.find((G)=>H0(G)&&G.data.messageId===$);if(!_)throw Error(`Rewind checkpoint not found: ${$}`);return{messageId:$,preview:YT(T,$),createdAt:_.data.createdAt}}function YT(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 QT(T,$){O0(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<_||!b$(Q)})}function u(T){let $=[];for(let _ of T){if(_.type!=="session_rewound"){$.push(_);continue}if(O0($,_.data.targetMessageId),_.data.mode!=="code")$=QT($,_.data.targetMessageId)}return $}function a_(T){let $=u(T);return $.filter(H0).map((_)=>({messageId:_.data.messageId,preview:YT($,_.data.messageId),createdAt:_.data.createdAt})).reverse()}function t_(T,$){let _=u(T),G=O0(_,$),X=_.findIndex((Q)=>Q.type==="message_created"&&Q.data.messageId===$),Y=_.slice(X);return{checkpoint:G,projectedEntries:QT(_,$),removedTurns:Y.filter(H0).length,snapshotMessageIds:Y.flatMap((Q)=>Q.type==="part_created"&&Q.data.partType==="tool_call"?[Q.data.partId]:[])}}import{createHash as n$}from"node:crypto";var r_={clientVisible:!1};function ZT(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 R$}from"node:string_decoder";var T1=1048576;function M0(T,$){let _=$;while(_<T.length&&(T[_]&192)===128)_+=1;return _}class C0{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 $=M0(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=M0($,_);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 $=M0(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 r={maxLines:30,maxChars:3000,keepHead:10,keepTail:10,summarize:!0},R={maxLines:100,maxChars:1e4,keepHead:40,keepTail:40,summarize:!0},UT={maxLines:200,maxChars:20000,keepHead:80,keepTail:80,summarize:!1},S$={maxLines:150,maxChars:15000,keepHead:50,keepTail:50,summarize:!0},f$=[{pattern:/^git\s+(rm|add)\s+(-r|--cached|-rf|-f)?\s*/i,config:r,summaryTemplate:(T)=>`Successfully processed ${T} files`},{pattern:/^(npm|pnpm|yarn|bun)\s+(install|i|add|remove|uninstall)/i,config:r,summaryTemplate:(T)=>`Package operation completed (${T} lines of output)`},{pattern:/^(npm|pnpm|yarn|bun)\s+(run|exec)\s+(build|compile|bundle)/i,config:R,summaryTemplate:(T)=>`Build completed (${T} lines of output)`},{pattern:/^(npm|pnpm|yarn|bun)\s+(run|exec)\s+(test|lint|check)/i,config:UT},{pattern:/^git\s+(status|branch|remote)/i,config:R},{pattern:/^git\s+(log|diff|show)/i,config:UT},{pattern:/^(ls|dir|tree)\s+/i,config:R,summaryTemplate:(T)=>`Listed ${T} items`},{pattern:/^find\s+/i,config:R,summaryTemplate:(T)=>`Found ${T} matches`},{pattern:/^(grep|rg|ag)\s+/i,config:R,summaryTemplate:(T)=>`Found ${T} matching lines`},{pattern:/^(docker|podman)\s+(build|pull|push)/i,config:r,summaryTemplate:(T)=>`Docker operation completed (${T} lines)`},{pattern:/^(pip|pip3|poetry|pipenv)\s+(install|uninstall)/i,config:r,summaryTemplate:(T)=>`Python package operation completed (${T} lines)`},{pattern:/^(cargo|rustup)\s+(build|install|update)/i,config:R,summaryTemplate:(T)=>`Rust operation completed (${T} lines)`},{pattern:/^(go)\s+(build|get|mod)/i,config:R,summaryTemplate:(T)=>`Go operation completed (${T} lines)`}];function VT(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 F0{static getConfigForCommand(T){for(let{pattern:$,config:_,summaryTemplate:G}of f$)if($.test(T))return{config:_,summaryTemplate:G};return{config:S$}}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
|
|
9
|
+
`),V.length>$.maxChars){let O=Math.floor($.maxChars/2)-50,M=VT(V,0,O),I=VT(V,V.length-O);V=`${M}
|
|
10
10
|
|
|
11
11
|
... (content truncated to ${$.maxChars} chars) ...
|
|
12
12
|
|
|
@@ -16,29 +16,29 @@ ${I}`}let g=$.summarize&&_?_(Y,G):void 0;if(g)V+=`
|
|
|
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 BT=32768,y$=1048576,h$=65536,P$=3600000,gT=4096,m$=/[\u001B\u009B][[\]()#;?]*(?:(?:(?:[a-zA-Z\d]*(?:;[-a-zA-Z\d/#&.:=?%@~_]+)*)?\u0007)|(?:(?:\d{1,4}(?:[;:]\d{0,4})*)?[\dA-PR-TZcf-nq-uy=><~]))/g;function Z1(){return{async execute(){return{exitCode:null,stdout:"",stderr:"",error:"ACP terminal capability is unavailable"}}}}class L0{stream;executionId;onEvent;output=new C0(y$/2);decoder=new R$("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<gT){let G=$.subarray(0,Math.min($.length,gT-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 _=
|
|
20
|
-
`):
|
|
19
|
+
`).length,chars:T.length,words:T.split(/\s+/).filter(Boolean).length}}}var BT=32768,y$=1048576,h$=65536,P$=3600000,gT=4096,m$=/[\u001B\u009B][[\]()#;?]*(?:(?:(?:[a-zA-Z\d]*(?:;[-a-zA-Z\d/#&.:=?%@~_]+)*)?\u0007)|(?:(?:\d{1,4}(?:[;:]\d{0,4})*)?[\dA-PR-TZcf-nq-uy=><~]))/g;function Z1(){return{async execute(){return{exitCode:null,stdout:"",stderr:"",error:"ACP terminal capability is unavailable"}}}}class L0{stream;executionId;onEvent;output=new C0(y$/2);decoder=new R$("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<gT){let G=$.subarray(0,Math.min($.length,gT-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 _=HT(this.decoder.write($));this.output.append(_),this.emit(_)}finish(){if(this.binary)return;let T=HT(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 $=h$-this.streamedBytes;if($<=0){this.streamTruncated=!0;return}let _=v$(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 HT(T){return T.replace(m$,"")}function v$(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 OT(T){return T.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""").replaceAll("'","'")}function u$(T){let $=T.trim();if(!$)throw Error("User shell command cannot be empty");if($.length>BT)throw Error(`User shell command exceeds ${BT} characters`);if($.includes("\x00"))throw Error("User shell command contains a null byte");return $}function p$(){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}=MT(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},B=setTimeout(()=>{V=!0,I()},$.timeoutMs),L=()=>{g=!0,I()};if($.signal.addEventListener("abort",L,{once:!0}),$.signal.aborted)L();Y.stdout?.on("data",(F)=>{$.onOutput?.("stdout",F)}),Y.stderr?.on("data",(F)=>{$.onOutput?.("stderr",F)});let z=async(F)=>{if(O)return;if(O=!0,clearTimeout(B),$.signal.removeEventListener("abort",L),V||g)await I();_({...F,stdout:"",stderr:"",timedOut:V,aborted:g})};Y.once("error",(F)=>{z({exitCode:null,error:F.message})}),Y.once("close",(F)=>{z({exitCode:F})})})}}}async function U1(T,$){let _=u$(T),G=$.timeoutMs??P$,X=new L0("stdout",$.executionId,$.onEvent),Y=new L0("stderr",$.executionId,$.onEvent),Q=Date.now();await $.onEvent?.({type:"started",executionId:$.executionId,command:_});let Z,U=!1,V=!1;try{Z=await($.executor??p$()).execute(_,{cwd:$.cwd,env:$.env,timeoutMs:G,signal:$.signal,onOutput:(L,z)=>{if(L==="stdout")U=!0;else V=!0;(L==="stdout"?X:Y).append(z)}})}catch(L){Z={exitCode:null,stdout:"",stderr:"",error:L instanceof Error?L.message:String(L)}}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=F0.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",B={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:B}),B}function V1(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>${
|
|
24
|
-
${
|
|
23
|
+
`);return["<user_shell_command>",`<command>${OT(T.command)}</command>`,"<result>",`Status: ${T.status}`,`Exit code: ${T.exitCode??"null"}`,`Duration: ${(T.durationMs/1000).toFixed(3)} seconds`,`Output:
|
|
24
|
+
${OT($||"(no output)")}`,"</result>","</user_shell_command>"].join(`
|
|
25
25
|
`)}function CT(T){let $=[T.stdout,T.stderr?`stderr:
|
|
26
26
|
${T.stderr}`:""].filter(Boolean).join(`
|
|
27
27
|
`);return[`! ${T.command}`,$||"(no output)"].join(`
|
|
28
28
|
`)}function l$(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 FT(T){if(!T||typeof T!=="object"||Array.isArray(T))return;return l$(T.userShellCommand)}var i$=262144,c$="session-surface-message\x00",IT="[private state path]",e="[content truncated]",LT=`
|
|
29
|
-
${e}`,T0=String.fromCharCode(27),d$=String.fromCharCode(7),s$=String.fromCharCode(157),a$=String.fromCharCode(156),t$=String.fromCharCode(155),o$=new RegExp(`(?:${
|
|
29
|
+
${e}`,T0=String.fromCharCode(27),d$=String.fromCharCode(7),s$=String.fromCharCode(157),a$=String.fromCharCode(156),t$=String.fromCharCode(155),o$=new RegExp(`(?:${w(T0)}\\]|${w(s$)})[\\s\\S]*?(?:${w(d$)}|${w(T0)}\\\\|${w(a$)})`,"g"),r$=new RegExp(`(?:${w(T0)}\\[|${w(t$)})[0-?]*[ -/]*[@-~]`,"g");function J0(T,$){let _={privateRoots:[T],privateValues:[$.exactIdentity,$.collisionIdentity]};if($.style==="win32")_.caseInsensitivePrivateRoots=[$.wirePath];else _.privateRoots=[T,$.wirePath];return _}class J extends Error{code="session_surface_state_invalid";constructor(){super("session surface projection state is invalid");this.name="SessionSurfaceProjectionError"}}function KT(T,$){let _=g_($.maxContentBytes),{privateRoots:G,caseInsensitivePrivateRoots:X}=WT($),Y=jT($.privateValues??[]),Q=u(T),Z=new Map;for(let V of Q){if(I0(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;__(g,V)}let U=[];for(let V of Z.values()){let g=T_(V,G,X,Y,_);if(g)U.push(g)}return U}function e$(T){return typeof T==="object"&&T!==null&&!Array.isArray(T)}function w(T){return T.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function T_(T,$,_,G,X){let Y=T.event.data.role;if(Y!=="user"&&Y!=="assistant")return;let Q=$_(T),Z=AT(Q),U={role:Y,content:Z,...T.event.data.metadata!==void 0?{metadata:T.event.data.metadata}:{}};if(!ZT(U))return;let V=Y_(T.event.data.createdAt),O=kT($0($0(Z,_,!0),$),G).trim();if(!O)return;let M=V_(O,X),I=X_(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 N0(T,$){let{privateRoots:_,caseInsensitivePrivateRoots:G}=WT($);return kT($0($0(AT(T),G,!0),_),jT($.privateValues??[]))}function $_(T){let $=FT(T.event.data.metadata);if($)return CT($);return T.orderedPartIds.map((_)=>T.partsById.get(_)).flatMap((_)=>_?[_.content]:[]).join("")}function __(T,$){if($.data.partType!=="text"&&$.data.partType!=="image")return;let _=$.data.partType==="text"?{partId:$.data.partId,type:"text",content:G_($.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 G_(T){if(!e$(T))return"";let $=T.text;return typeof $==="string"?$:""}function X_(T){let $=I0(T.seq);return z0($,T.data.messageId)}function z0(T,$){let _=I0(T),G=n$("sha256").update(c$).update($).digest("hex").slice(0,16);return`surface-message:${_}:${G}`}function Y_(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 J;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 J;return T}function JT(T,$){return[...new Set([...T,...$].filter(Boolean))].sort((_,G)=>G.length-_.length)}function NT(T){return/^[A-Za-z]:[\\/]/.test(T)||/^\\\\/.test(T)}function WT(T){let $=JT(T.privateRoots,T.bladeStorageRoots??[]);return{privateRoots:$.filter((_)=>!NT(_)),caseInsensitivePrivateRoots:JT([...T.caseInsensitivePrivateRoots??[],...$.filter(NT)],[])}}function jT(T){return[...new Set(T.filter(Boolean))].sort(($,_)=>_.length-$.length)}function kT(T,$){let _=T;for(let G of $)_=_.split(G).join(IT);return _}function $0(T,$,_=!1){let G=T;for(let X of $)G=Q_(G,X,_);return G}function Q_(T,$,_){if(!$)return T;let G=0,X="",Y=_?new RegExp($.split(/[\\/]+/).map((Q)=>w(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=Z_(T,Z,U);if(V===Z){X+=T[Z],G=Z+1;continue}X+=IT,G=V}return X}function Z_(T,$,_){let G=$+_;if(G>=T.length)return G;let X=T[G];if(X===void 0)return G;if(!U_(X)&&!zT(X))return $;let Y=G;while(Y<T.length){let Q=T[Y];if(Q===void 0||zT(Q))break;Y+=1}return Y}function U_(T){return T==="/"||T==="\\"}function zT(T){return T===" "||T==="\t"||T===`
|
|
30
30
|
`||T==="\r"||T==='"'||T==="'"||T==="`"||T==="<"||T===">"||T==="("||T===")"||T==="["||T==="]"||T==="{"||T==="}"||T===","||T===";"||T===":"||T==="!"||T==="?"}function AT(T){return[...T.replace(/\r\n?/g,`
|
|
31
|
-
`).replace(o$,"").replace(r$,"").split(`${T0}\\`).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 V_(T,$){if(Buffer.byteLength(T,"utf8")<=$)return{content:T,truncated:!1};let _=B_($),G=Buffer.byteLength(_,"utf8"),X=Math.max(0,$-G);return{content:`${xT(T,X)}${_}`,truncated:!0}}function xT(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 B_(T){let $=Buffer.byteLength(LT,"utf8");if(T>=$)return LT;let _=Buffer.byteLength(e,"utf8");if(T>=_)return e;return xT(e,T)}function g_(T){let $=T??i$;if(!Number.isSafeInteger($)||$<=0)throw new J;return $}function I0(T){let $=T;if($===void 0||!Number.isSafeInteger($)||$<=0)throw new J;return $}import*as A from"node:fs";import{createReadStream as
|
|
31
|
+
`).replace(o$,"").replace(r$,"").split(`${T0}\\`).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 V_(T,$){if(Buffer.byteLength(T,"utf8")<=$)return{content:T,truncated:!1};let _=B_($),G=Buffer.byteLength(_,"utf8"),X=Math.max(0,$-G);return{content:`${xT(T,X)}${_}`,truncated:!0}}function xT(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 B_(T){let $=Buffer.byteLength(LT,"utf8");if(T>=$)return LT;let _=Buffer.byteLength(e,"utf8");if(T>=_)return e;return xT(e,T)}function g_(T){let $=T??i$;if(!Number.isSafeInteger($)||$<=0)throw new J;return $}function I0(T){let $=T;if($===void 0||!Number.isSafeInteger($)||$<=0)throw new J;return $}import*as A from"node:fs";import{createReadStream as H_}from"node:fs";import*as N from"node:fs/promises";import*as K0 from"node:path";import{createInterface as O_}from"node:readline";var ET=65536;function _0(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 M_(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 d(T,$="session transcript"){let _=T.split(`
|
|
32
32
|
`),G=!T.endsWith(`
|
|
33
|
-
`),X=[];for(let[Y,Q]of _.entries())try{let Z=
|
|
33
|
+
`),X=[];for(let[Y,Q]of _.entries())try{let Z=M_(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 j{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 j.stampSeqFrom(T,j.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 N.mkdir(K0.dirname(this.filePath),{recursive:!0,mode:493});let $=await N.open(this.filePath,"a+",384);try{let _=await this.repairIncompleteTail($),G=await this.readTailSeq($),X=j.stampSeqFrom(T,G),Y=`${X.map(_0).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
|
|
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 N.mkdir(K0.dirname(this.filePath),{recursive:!0,mode:493});let $;try{$=await N.open(this.filePath,"wx",384);let G=`${j.stampSeq(T,[]).map(_0).join(`
|
|
36
36
|
`)}
|
|
37
|
-
`;await $.writeFile(G,"utf-8"),await $.sync()}catch(_){if($)await $.close(),$=void 0,await
|
|
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
|
|
37
|
+
`;await $.writeFile(G,"utf-8"),await $.sync()}catch(_){if($)await $.close(),$=void 0,await N.unlink(this.filePath).catch(()=>{return});throw _}finally{await $?.close()}}async readAll(T={}){if(T.signal?.throwIfAborted(),!A.existsSync(this.filePath))return[];let $=await N.readFile(this.filePath,{encoding:"utf-8",signal:T.signal});return d($,this.filePath)}async readStream(T){return new Promise(($,_)=>{if(!A.existsSync(this.filePath)){$();return}let G=H_(this.filePath,"utf-8"),X=O_({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(!A.existsSync(this.filePath))return{exists:!1,size:0,lineCount:0};let T=await N.stat(this.filePath),_=(await N.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 N.access(this.filePath),!0}catch{return!1}}async delete(){try{return await this.enqueue(async()=>{try{return await N.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 N.open(this.filePath,"r")}catch(G){if(G.code==="ENOENT")return!1;throw G}let _;try{_=d(await $.readFile("utf8"),"session transcript")}finally{await $.close()}if(!T(_))return!1;try{return await N.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?A.constants.O_RDWR|(A.constants.O_NOFOLLOW??0):"r+",G=await N.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=j.stampSeq(Z,X),V=`${U.map(_0).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?A.constants.O_RDWR|(A.constants.O_NOFOLLOW??0):"r+",G=await
|
|
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?A.constants.O_RDONLY|(A.constants.O_NOFOLLOW??0):"r",_;try{_=await
|
|
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?A.constants.O_RDWR|(A.constants.O_NOFOLLOW??0):"r+",G=await N.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]=j.stampSeq([Z],X),V=`${Y}${_0(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?A.constants.O_RDONLY|(A.constants.O_NOFOLLOW??0):"r",_;try{_=await N.open(this.filePath,$)}catch(G){if(T.signal?.throwIfAborted(),G.code==="ENOENT")return[];throw G}try{await T.validateHandle?.(_),T.signal?.throwIfAborted();let G=d(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 _=(j.appendQueues.get(this.filePath)??Promise.resolve()).catch(()=>{return}).then(T),G=_.then(()=>{return},()=>{return});j.appendQueues.set(this.filePath,G);try{return await _}finally{if(j.appendQueues.get(this.filePath)===G)j.appendQueues.delete(this.filePath)}}async readCommittedState(T,$=this.filePath){let _=await this.repairIncompleteTail(T),G=await T.readFile("utf8"),X=d(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,$-ET),G=Buffer.allocUnsafe($-_);await T.read(G,0,G.length,_);let X=G.toString("utf8").split(`
|
|
42
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 j.maxSeq(d(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
43
|
`}catch{return await T.truncate(G),""}}async findTailStart(T,$){let _=$;while(_>0){let G=Math.max(0,_-ET),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 qT(T){let $=Number(T.pragma("user_version")??0);if($===7)return;if($>0&&$!==7)T.exec(`
|
|
44
44
|
DROP TABLE IF EXISTS parts_fts;
|
|
@@ -174,7 +174,7 @@ CREATE VIRTUAL TABLE IF NOT EXISTS parts_fts USING fts5(
|
|
|
174
174
|
seq UNINDEXED,
|
|
175
175
|
tokenize = 'unicode61'
|
|
176
176
|
);
|
|
177
|
-
`),T.exec("PRAGMA user_version=7;")}var F_=yT("Service"),L_="session-surface-projection-v1\x00",x0=524288,J_=3,
|
|
177
|
+
`),T.exec("PRAGMA user_version=7;")}var F_=yT("Service"),L_="session-surface-projection-v1\x00",x0=524288,J_=3,N_=new AbortController().signal,z_=/^acp-remote-workspace:[A-Za-z0-9_-]{43}$/,hT=`WITH RECURSIVE archive_members(
|
|
178
178
|
source_kind, project_path, public_workspace_ref, session_id, archive_root_id,
|
|
179
179
|
effective_archived_at, depth
|
|
180
180
|
) AS (
|
|
@@ -202,12 +202,12 @@ ranked_archive AS (
|
|
|
202
202
|
ORDER BY depth ASC, archive_root_id ASC
|
|
203
203
|
) AS rank
|
|
204
204
|
FROM archive_members
|
|
205
|
-
)`,PT={readSession(T,$,_){return $?T.readAllValidated({noFollow:!0,signal:_,validateHandle:(G)=>
|
|
205
|
+
)`,PT={readSession(T,$,_){return $?T.readAllValidated({noFollow:!0,signal:_,validateHandle:(G)=>bT($,T.getFilePath(),G)}):T.readAll({signal:_})}},b0=PT;function R1(T){b0=T}function y1(){b0=PT}function h1(){return x0}var s;function mT(){return G0.join(X0(),"index.db")}async function I_(){let T=mT();if(s&&s.path===T)return s.db;let $=(async()=>{let _=await t(T);if(!_)return null;try{return qT(_),_}catch{return null}})();return s={path:T,db:$},$}function K_(){s=void 0}function W_(T){if(T&&typeof T==="object"){let $=T.text;if(typeof $==="string")return $}return null}function j_(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
|
|
206
206
|
(source_kind, project_path, session_id, part_id, message_id, part_type, role,
|
|
207
207
|
seq, timestamp, text)
|
|
208
208
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`),Z=T.prepare(`INSERT INTO parts_fts
|
|
209
209
|
(text, source_kind, project_path, session_id, part_id, role, timestamp, seq)
|
|
210
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?)`);for(let U of X){if(U.type!=="part_created"&&U.type!=="part_updated")continue;if(U.data.partType!=="text")continue;let V=W_(U.data.payload);if(V===null)continue;let g=Y.get(U.data.messageId)??"assistant",
|
|
210
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?)`);for(let U of X){if(U.type!=="part_created"&&U.type!=="part_updated")continue;if(U.data.partType!=="text")continue;let V=W_(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 k_(T,$,_,G){let{metadata:X,publicWorkspaceRef:Y}=_,Q=v(Y??X.projectPath);T.prepare(`INSERT INTO sessions
|
|
211
211
|
(source_kind, project_path, session_id, root_id, parent_id, relation_type, title,
|
|
212
212
|
agent_type, model, task_status, task_priority, task_kind, task_due_at,
|
|
213
213
|
archived_at, last_message_time, project_sort_key,
|
|
@@ -234,23 +234,23 @@ ranked_archive AS (
|
|
|
234
234
|
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
|
|
235
235
|
(source_kind, project_path, session_id, message_seq, message_id,
|
|
236
236
|
message_json, byte_count)
|
|
237
|
-
VALUES (?, ?, ?, ?, ?, ?, ?)`);for(let U of Y){let V=
|
|
237
|
+
VALUES (?, ?, ?, ?, ?, ?, ?)`);for(let U of Y){let V=w0.parse(U),g=vT(V.id),O=Q.get(g);if(!O)throw new J;let M=JSON.stringify(V);Z.run($,_,G,g,O,M,Buffer.byteLength(M))}}function vT(T){let $=/^surface-message:([0-9]+):/.exec(T),_=$?Number($[1]):Number.NaN;if(!Number.isSafeInteger(_)||_<0)throw new J;return _}function x_(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}},...uT($,T.publicWorkspaceRef)};return C_("sha256").update(L_).update(JSON.stringify({catalogSummary:_,messages:T.surfaceMessages})).digest("hex")}function uT(T,$){let _=T.remoteWorkspace===void 0?void 0:D(T.remoteWorkspace);if(_===void 0!==($===void 0)||_&&i(_.collisionIdentity)!==T.projectPath||!k(T.sessionId)||!k(T.rootId)||T.parentId!==void 0&&!k(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 J;let G={..._?J0(T.projectPath,_):{privateRoots:[]},bladeStorageRoots:[X0()]},X=T.relationType,Y=T.taskStatus;return{displayCwd:_?.wirePath??T.projectPath,..._?{pathStyle:_.style}:{},...T.title!==void 0?{title:N0(T.title,G)}:{},rootId:T.rootId,...T.parentId!==void 0?{parentId:T.parentId}:{},...X!==void 0?{relationType:X}:{},taskStatus:Y,messageCount:T.messageCount,firstMessageTime:T.firstMessageTime,lastMessageTime:T.lastMessageTime,hasErrors:T.hasErrors,...T.archivedAt!==void 0?{archivedAt:T.archivedAt}:{},...T.selectedModelId!==void 0?{selectedModelId:N0(T.selectedModelId,G)}:{}}}function E_(T,$,_,G){return T.prepare(`SELECT EXISTS(
|
|
238
238
|
SELECT 1 FROM sessions
|
|
239
239
|
WHERE source_kind=? AND project_path=? AND session_id=?
|
|
240
240
|
UNION ALL
|
|
241
241
|
SELECT 1 FROM surface_messages
|
|
242
242
|
WHERE source_kind=? AND project_path=? AND session_id=?
|
|
243
|
-
) AS present`).get($,_,G,$,_,G)?.present===1}function S0(T,$,_,G){let X=E_(T,$,_,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
|
|
243
|
+
) AS present`).get($,_,G,$,_,G)?.present===1}function S0(T,$,_,G){let X=E_(T,$,_,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 b(T,$,_,G){let X=S0(T,$,_,G);return T.prepare("DELETE FROM projection_state WHERE source_kind=? AND project_path=? AND session_id=?").run($,_,G),X}function q_(T,$,_){let G=T.prepare(`SELECT project_path, session_id FROM sessions
|
|
244
244
|
WHERE source_kind=? AND json_extract(metadata_json, '$.filePath')=?`).all($,_),X=!1;for(let Y of G)X=S0(T,$,Y.project_path,Y.session_id)||X;return X}function W0(T,$,_,G,X,Y,Q,Z){T.prepare(`INSERT INTO projection_state
|
|
245
245
|
(source_kind, project_path, session_id, last_seq, file_size, mtime_ms,
|
|
246
246
|
stat_fingerprint)
|
|
247
247
|
VALUES (?, ?, ?, ?, ?, ?, ?)
|
|
248
248
|
ON CONFLICT(source_kind, project_path, session_id) DO UPDATE SET
|
|
249
249
|
last_seq=excluded.last_seq, file_size=excluded.file_size,
|
|
250
|
-
mtime_ms=excluded.mtime_ms, stat_fingerprint=excluded.stat_fingerprint`).run($,_,G,X,Y,Q,Z)}function y(T){return[T.dev,T.ino,T.size,T.mtimeNs,T.ctimeNs].join(":")}async function DT(T,$,_,G,X,Y="local",Q){if(Q?.throwIfAborted(),Y==="acp-remote")return c(_,async(Z)=>{let U=a(Z,$),V=X??U;if(V!==U)throw new E("remote-session-file-path");return E0(T,$,_,G,V,Y,Z,Q)});return E0(T,$,_,G,X??D0(_,$),Y,void 0,Q)}async function E0(T,$,_,G,X,Y,Q,Z){if(Z?.throwIfAborted(),Y==="acp-remote"){if(!Q)throw new E("remote-session-scope");try{await j0(Q,X),Z?.throwIfAborted()}catch(C){if(Z?.aborted)throw C;if(C.code!=="ENOENT")throw C;return Z?.throwIfAborted(),T.transaction(()=>{if(
|
|
251
|
-
WHERE source_kind=? AND project_path=? AND session_id=?`).get(Y,_,$);if(Y==="local"&&V&&V.stat_fingerprint===y(U))return!1;let g=new j(X),
|
|
250
|
+
mtime_ms=excluded.mtime_ms, stat_fingerprint=excluded.stat_fingerprint`).run($,_,G,X,Y,Q,Z)}function y(T){return[T.dev,T.ino,T.size,T.mtimeNs,T.ctimeNs].join(":")}async function DT(T,$,_,G,X,Y="local",Q){if(Q?.throwIfAborted(),Y==="acp-remote")return c(_,async(Z)=>{let U=a(Z,$),V=X??U;if(V!==U)throw new E("remote-session-file-path");return E0(T,$,_,G,V,Y,Z,Q)});return E0(T,$,_,G,X??D0(_,$),Y,void 0,Q)}async function E0(T,$,_,G,X,Y,Q,Z){if(Z?.throwIfAborted(),Y==="acp-remote"){if(!Q)throw new E("remote-session-scope");try{await j0(Q,X),Z?.throwIfAborted()}catch(C){if(Z?.aborted)throw C;if(C.code!=="ENOENT")throw C;return Z?.throwIfAborted(),T.transaction(()=>{if(b(T,Y,_,$))q(T)}),!0}}let U;try{U=await A0(X,{bigint:!0}),Z?.throwIfAborted()}catch(C){if(Z?.aborted)throw C;let W=C.code;if(Y==="acp-remote"&&W!=="ENOENT")throw C;return T.transaction(()=>{if(b(T,Y,_,$))q(T)}),!0}let V=T.prepare(`SELECT last_seq, file_size, mtime_ms, stat_fingerprint FROM projection_state
|
|
251
|
+
WHERE source_kind=? AND project_path=? AND session_id=?`).get(Y,_,$);if(Y==="local"&&V&&V.stat_fingerprint===y(U))return!1;let g=new j(X),O;try{let C=U,W;for(let P0=0;P0<J_;P0+=1){Z?.throwIfAborted();let m0=await b0.readSession(g,Q,Z??N_);Z?.throwIfAborted();let Q0=await A0(X,{bigint:!0});if(Z?.throwIfAborted(),y(C)===y(Q0)){O=m0,U=Q0,W=m0;break}C=Q0}if(!W)throw new J;O=W}catch(C){if(Z?.aborted)throw C;let W=C.code;if(W!=="ENOENT"){if(Y==="acp-remote"){if(C instanceof E)throw C;if(W!==void 0)throw new E("remote-session-read")}throw C}return T.transaction(()=>{if(b(T,Y,_,$))q(T)}),!0}if(Y==="acp-remote"&&O.length===0){try{await j0(Q,X)}catch(C){if(Z?.aborted)throw C;if(C.code==="ENOENT")return T.transaction(()=>{if(b(T,Y,_,$))q(T)}),!0;throw C}throw new E("remote-session-empty")}Z?.throwIfAborted();let M=Y==="local"?O.find((C)=>C.type==="session_created"):void 0,I=Y==="local"&&M!==void 0&&Object.hasOwn(M.data,"remoteWorkspace"),B=null;if(Y==="acp-remote"){let C=ST(O,$,_);B=D(C.data.remoteWorkspace)}else if(I)D(M.data.remoteWorkspace);let L=O.reduce((C,W)=>typeof W.seq==="number"&&W.seq>C?W.seq:C,0),z=u(O),F=I?null:G(O,$,_,Y,X),S=F?.remoteWorkspace;if(Y==="acp-remote"){if(!F||F.sessionId!==$||F.projectPath!==_||S===void 0)throw new E("remote-session-metadata");let C=D(S);if(!B||C.style!==B.style||C.wirePath!==B.wirePath||C.exactIdentity!==B.exactIdentity||C.collisionIdentity!==B.collisionIdentity)throw new E("remote-session-descriptor");if(i(C.collisionIdentity)!==_)throw new E("remote-session-project-path")}if(O.length===0||!F||Y==="local"&&S!==void 0)return Z?.throwIfAborted(),T.transaction(()=>{let C;if(I)C=q_(T,Y,X),C=b(T,Y,_,$)||C;else C=S0(T,Y,_,$),W0(T,Y,_,$,L,Number(U.size),Number(U.mtimeMs),y(U));if(C)q(T)}),!0;let f0=B&&Q?await d0(Q,B):void 0;Z?.throwIfAborted();let R0=KT(O,{...B?J0(_,B):{privateRoots:[]},bladeStorageRoots:[X0()]}),y0={metadata:F,...f0!==void 0?{publicWorkspaceRef:f0}:{},surfaceMessages:R0},h0=x_(y0),Y0=T.prepare(`SELECT last_message_time FROM sessions
|
|
252
252
|
WHERE source_kind=? AND project_path=? AND session_id=?`).get(Y,F.projectPath,F.sessionId),nT=Y==="acp-remote"&&Q?a(Q,F.sessionId):D0(F.projectPath,F.sessionId),iT=G0.resolve(X)===G0.resolve(nT);if(Y0&&!iT&&typeof Y0.last_message_time==="string"&&Y0.last_message_time>F.lastMessageTime)return Z?.throwIfAborted(),W0(T,Y,_,$,L,Number(U.size),Number(U.mtimeMs),y(U)),!0;return Z?.throwIfAborted(),T.transaction(()=>{let W=T.prepare(`SELECT surface_digest FROM sessions
|
|
253
|
-
WHERE source_kind=? AND project_path=? AND session_id=?`).get(Y,F.projectPath,F.sessionId)?.surface_digest!==h0;if(k_(T,Y,y0,h0),j_(T,Y,F.projectPath,F.sessionId,
|
|
253
|
+
WHERE source_kind=? AND project_path=? AND session_id=?`).get(Y,F.projectPath,F.sessionId)?.surface_digest!==h0;if(k_(T,Y,y0,h0),j_(T,Y,F.projectPath,F.sessionId,z),A_(T,Y,F.projectPath,F.sessionId,z,R0),W0(T,Y,_,$,L,Number(U.size),Number(U.mtimeMs),y(U)),W)q(T)}),!0}var wT=new WeakMap;function q0(T,$,_,G){let X=T.prepare(`SELECT session_id FROM projection_state
|
|
254
254
|
WHERE source_kind=? AND project_path=?
|
|
255
255
|
UNION
|
|
256
256
|
SELECT session_id FROM sessions
|
|
@@ -263,7 +263,7 @@ ranked_archive AS (
|
|
|
263
263
|
WHERE source_kind=? AND project_path=?
|
|
264
264
|
UNION
|
|
265
265
|
SELECT session_id FROM surface_messages
|
|
266
|
-
WHERE source_kind=? AND project_path=?`).all($,_,$,_,$,_,$,_,$,_);for(let Y of X)if(!G.has(Y.session_id)){if(
|
|
266
|
+
WHERE source_kind=? AND project_path=?`).all($,_,$,_,$,_,$,_,$,_);for(let Y of X)if(!G.has(Y.session_id)){if(b(T,$,_,Y.session_id))q(T)}}async function D_(T,$,_,G){G?.throwIfAborted();try{await c(_,async(X)=>{let Y=(await k0(String(X))).flatMap((V)=>{if(!V.endsWith(".jsonl"))return[];let g=V.slice(0,-6);if(!k(g))return[];return[{filePath:a(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 E0(T,V.sessionId,_,$,V.filePath,"acp-remote",X,G)}})),G?.throwIfAborted(),T.transaction(()=>{q0(T,"acp-remote",_,Q)})})}catch(X){if(G?.aborted)throw X;if(X.code!=="ENOENT")throw X;T.transaction(()=>{q0(T,"acp-remote",_,new Set)})}}async function P1(T,$,_){_?.throwIfAborted();let G=await fT();_?.throwIfAborted();for(let Q of G)_?.throwIfAborted(),await D_(T,$,String(Q),_);let X=new Set(G.map(String)),Y=T.prepare(`SELECT project_path FROM projection_state WHERE source_kind='acp-remote'
|
|
267
267
|
UNION
|
|
268
268
|
SELECT project_path FROM sessions WHERE source_kind='acp-remote'
|
|
269
269
|
UNION
|
|
@@ -271,9 +271,9 @@ ranked_archive AS (
|
|
|
271
271
|
UNION
|
|
272
272
|
SELECT project_path FROM parts_fts WHERE source_kind='acp-remote'
|
|
273
273
|
UNION
|
|
274
|
-
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(()=>{q0(T,"acp-remote",Q.project_path,new Set)})}async function
|
|
274
|
+
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(()=>{q0(T,"acp-remote",Q.project_path,new Set)})}async function w_(T,$,_=0){let G=wT.get(T)??{};if(wT.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 RT(),Y=(await Promise.all(G.map(async(B)=>{if(B.kind==="local")try{return(await k0(B.storagePath)).flatMap((z)=>{if(!z.endsWith(".jsonl"))return[];let F=z.slice(0,-6);if(!k(F))return[];return[{kind:"local",filePath:G0.join(B.storagePath,z),projectPath:B.projectPath,sessionId:F}]})}catch{return[]}return c(B.storagePath,async(L)=>{return(await k0(String(L))).flatMap((F)=>{if(!F.endsWith(".jsonl"))return[];let S=F.slice(0,-6);if(!k(S))return[];return[{kind:"acp-remote",filePath:a(L,S),projectPath:B.projectPath,sessionId:S}]})})}))).flat();for(let B of Y)_.add(`${B.kind}\x00${B.projectPath}\x00${B.sessionId}`);let Q=T.prepare(`SELECT source_kind, project_path, session_id, last_seq, file_size, mtime_ms,
|
|
275
275
|
stat_fingerprint
|
|
276
|
-
FROM projection_state`).all(),Z=new Map(Q.map((B)=>[`${B.source_kind}\x00${B.project_path}\x00${B.session_id}`,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 L=await A0(B.filePath,{bigint:!0}),
|
|
276
|
+
FROM projection_state`).all(),Z=new Map(Q.map((B)=>[`${B.source_kind}\x00${B.project_path}\x00${B.session_id}`,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 L=await A0(B.filePath,{bigint:!0}),z=Z.get(`${B.kind}\x00${B.projectPath}\x00${B.sessionId}`);if(z&&z.stat_fingerprint===y(L))continue}catch(L){if(L.code!=="ENOENT")throw L}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 DT(T,B.sessionId,B.projectPath,$,B.filePath,"acp-remote");else await DT(T,B.sessionId,B.projectPath,$,B.filePath,"local")}catch(L){let z=L.code;if(B.kind==="acp-remote"){if(z==="ENOENT")continue;throw L}if(z==="acp_remote_workspace_state_invalid")throw L;if(z!=="ENOENT")F_.warn(`[SessionService] Skipping invalid session transcript: ${B.sessionId}`)}}}));let I=T.prepare(`SELECT source_kind, project_path, session_id FROM projection_state
|
|
277
277
|
UNION
|
|
278
278
|
SELECT source_kind, project_path, session_id FROM sessions
|
|
279
279
|
WHERE source_kind='acp-remote'
|
|
@@ -285,7 +285,7 @@ ranked_archive AS (
|
|
|
285
285
|
WHERE source_kind='acp-remote'
|
|
286
286
|
UNION
|
|
287
287
|
SELECT source_kind, project_path, session_id FROM surface_messages
|
|
288
|
-
WHERE source_kind='acp-remote'`).all();for(let B of I)if(!_.has(`${B.source_kind}\x00${B.project_path}\x00${B.session_id}`))T.transaction(()=>{if(
|
|
288
|
+
WHERE source_kind='acp-remote'`).all();for(let B of I)if(!_.has(`${B.source_kind}\x00${B.project_path}\x00${B.session_id}`))T.transaction(()=>{if(b(T,B.source_kind,B.project_path,B.session_id))q(T)})}function m1(T,$,_,G="local"){T.transaction(()=>{if(b(T,G,_,$))q(T)})}async function v1(T){let{rm:$}=await import("node:fs/promises");K_();let _=mT();for(let Y of["","-wal","-shm"])await $(`${_}${Y}`,{force:!0}).catch(()=>{return});let G=await I_();if(!G)return null;return await w_(G,T),G.prepare("SELECT COUNT(*) c FROM sessions").get()?.c??0}function pT(T){try{let $=JSON.parse(T.metadata_json);if(!$||typeof $!=="object"||Array.isArray($))throw new J;let _=$,G=v(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!==v(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||!z_.test(T.public_workspace_ref)||_.remoteWorkspace===void 0))throw new J;let X=T.effective_archived_at?{..._,archivedAt:T.effective_archived_at,archivedBySessionId:T.archive_root_id}:_,Y=uT(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 J}}function u1(T,$){if(!k($))throw new J;try{return T.prepare(`${hT}
|
|
289
289
|
SELECT s.source_kind, s.project_path, s.session_id, s.root_id, s.parent_id,
|
|
290
290
|
s.relation_type, s.task_status, s.first_message_time,
|
|
291
291
|
s.last_message_time, s.title, s.archived_at, s.message_count,
|
|
@@ -330,9 +330,9 @@ ranked_archive AS (
|
|
|
330
330
|
WHERE source_kind=? AND project_path=? AND session_id=?`).get($.sourceKind,$.projectPath,$.sessionId);if(!X)throw new J;if(!/^[a-f0-9]{64}$/.test(X.surface_digest)||!X.stat_fingerprint)throw new J;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
|
|
331
331
|
FROM surface_messages
|
|
332
332
|
WHERE source_kind=? AND project_path=? AND session_id=? ${Y}
|
|
333
|
-
ORDER BY message_seq DESC, message_id DESC LIMIT ?`).all(...Q),U=[],V=2;for(let
|
|
333
|
+
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)=>f_(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 f_(T){try{if(Buffer.byteLength(T.message_json)!==T.byte_count)throw new J;let $=w0.parse(JSON.parse(T.message_json));if($.id!==z0(T.message_seq,T.message_id)||vT($.id)!==T.message_seq)throw new J;return $}catch{throw new J}}function lT(T){if(!Number.isSafeInteger(T)||T<1||T>100)throw new J}function n1(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
|
|
334
334
|
WHERE parts_fts MATCH ? AND source_kind = 'local' AND project_path = ?
|
|
335
335
|
ORDER BY timestamp DESC LIMIT ?`:`SELECT session_id, role, timestamp, text FROM parts_fts
|
|
336
336
|
WHERE parts_fts MATCH ? AND source_kind = 'local'
|
|
337
337
|
ORDER BY timestamp DESC LIMIT ?`,Z=T.prepare(Q);return _?Z.all(Y,_,G):Z.all(Y,G)}
|
|
338
|
-
export{d0 as _d,u as $d,a_ as ae,t_ as be,d as ce,j as de,v as ee,x$ as fe,E$ as ge,l_ as he,n_ as ie,i_ as je,D$ as ke,
|
|
338
|
+
export{d0 as _d,u as $d,a_ as ae,t_ as be,d as ce,j as de,v as ee,x$ as fe,E$ as ge,l_ as he,n_ as ie,i_ as je,D$ as ke,w$ as le,c_ as me,d_ as ne,r_ as oe,ZT as pe,T1 as qe,C0 as re,F0 as se,Z1 as te,U1 as ue,V1 as ve,CT as we,FT as xe,J0 as ye,KT as ze,R1 as Ae,y1 as Be,h1 as Ce,mT as De,I_ as Ee,K_ as Fe,uT as Ge,DT as He,D_ as Ie,P1 as Je,w_ as Ke,m1 as Le,v1 as Me,u1 as Ne,S_ as Oe,p1 as Pe,l1 as Qe,n1 as Re};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{fi as H,gi as I}from"./chunk-
|
|
1
|
+
import{fi as H,gi as I}from"./chunk-0bkhpd72.js";import{Mutex as J}from"async-mutex";class B extends Error{limit;resource="resident_runtimes";retryable=!0;constructor(b){super("Session runtime capacity is full");this.limit=b;this.name="SessionRuntimeCapacityError"}}class D extends Error{constructor(){super("Session runtime residency is closed");this.name="SessionRuntimeResidencyClosedError"}}class A extends Error{constructor(b){super(`Session runtime residency already owns key: ${b}`);this.name="SessionRuntimeResidencyConflictError"}}class K{maxResident;idleMs;now;residents=new Map;reservations=new Map;operations=new J;nextGeneration=1;closed=!1;constructor(b){if(!H(b.maxResident))throw Error("Invalid max resident Session Runtime limit");if(!I(b.idleMs))throw Error("Invalid Session Runtime idle timeout");this.maxResident=b.maxResident,this.idleMs=b.idleMs,this.now=b.now??Date.now}acquire(b){let j=this.residents.get(b);if(!j||j.poisoned)return;return j.pins++,j.lastUsedAt=this.now(),this.createLease(j)}owns(b,j){let q=this.residents.get(b);return Boolean(q&&(j===void 0||q.value===j))}async reserve(b,j){if(!b.trim())throw Error("Session runtime residency key must not be blank");return this.operations.runExclusive(async()=>{if(this.closed)throw new D;if(this.residents.has(b)||this.reservations.has(b))throw new A(b);while(this.retainedCount()>=this.maxResident){if(!j.allowEviction)throw new B(this.maxResident);let z=this.oldestEvictableWebResident();if(!z)throw new B(this.maxResident);await this.disposeResident(z,!0)}let q={generation:this.allocateGeneration(),surface:j.surface};return this.reservations.set(b,q),this.createReservation(b,q)})}async remove(b,j){return this.operations.runExclusive(async()=>{let q=this.residents.get(b);if(!q||j!==void 0&&q.value!==j)return!1;if(q.pins>0)return!1;return await this.disposeResident(q,!0),!0})}async forget(b,j){return this.operations.runExclusive(async()=>{let q=this.residents.get(b);if(!q||j!==void 0&&q.value!==j||q.pins>0)return!1;return this.residents.delete(b),!0})}async sweepIdle(){return this.operations.runExclusive(async()=>{if(this.closed)return 0;let b=0;while(!0){let j=this.oldestIdleWebResident();if(!j)return b;await this.disposeResident(j,!0),b++}})}async disposeAll(){await this.operations.runExclusive(async()=>{this.closed=!0,this.reservations.clear();let b;for(let j of[...this.residents.values()])try{await this.disposeResident(j,!1)}catch(q){b??=q}if(this.residents.clear(),b!==void 0)throw b})}getStats(){let b=0;for(let j of this.residents.values())if(j.pins>0)b++;return{resident:this.residents.size,reserved:this.reservations.size,pinned:b,maxResident:this.maxResident}}retainedCount(){return this.residents.size+this.reservations.size}allocateGeneration(){let b=this.nextGeneration;return this.nextGeneration=this.nextGeneration===Number.MAX_SAFE_INTEGER?1:this.nextGeneration+1,b}createReservation(b,j){let q=!1;return{commit:(z)=>{if(q)throw new A(b);if(z.key!==b||z.surface!==j.surface||this.reservations.get(b)!==j||this.closed)throw this.reservations.delete(b),q=!0,this.closed?new D:new A(b);this.reservations.delete(b);let G={...z,generation:j.generation,pins:1,lastUsedAt:this.now(),poisoned:!1};return this.residents.set(b,G),q=!0,this.createLease(G)},cancel:()=>{if(q)return;if(this.reservations.get(b)===j)this.reservations.delete(b);q=!0}}}createLease(b){let j=!1;return{value:b.value,release:()=>{if(j)return;j=!0;let q=this.residents.get(b.key);if(q!==b||q.generation!==b.generation)return;q.pins=Math.max(0,q.pins-1),q.lastUsedAt=this.now()}}}oldestEvictableWebResident(){return this.sortedWebResidents().find((b)=>this.canEvict(b))}oldestIdleWebResident(){let b=this.now();return this.sortedWebResidents().find((j)=>b-j.lastUsedAt>=this.idleMs&&this.canEvict(j))}sortedWebResidents(){return[...this.residents.values()].filter((b)=>b.surface==="web").sort((b,j)=>b.lastUsedAt-j.lastUsedAt||b.generation-j.generation)}canEvict(b){if(b.pins>0||b.poisoned)return!1;try{return b.canEvict()}catch{return!1}}async disposeResident(b,j){if(this.residents.get(b.key)!==b)return;this.residents.delete(b.key);try{await b.dispose()}catch(q){if(j&&!this.closed&&!this.residents.has(b.key))b.lastUsedAt=this.now(),b.poisoned=!0,this.residents.set(b.key,b);throw q}}}
|
|
2
2
|
export{B as v,K as w};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{eg as a,fg as b,gg as c,hg as d}from"./chunk-
|
|
1
|
+
import{eg as a,fg as b,gg as c,hg as d}from"./chunk-e371f7xk.js";import"./chunk-0bkhpd72.js";import"./chunk-jkfkyedn.js";import"./chunk-f8gb685p.js";import"./chunk-44jtpg8y.js";import"./chunk-sj1dzeta.js";import"./chunk-2y1qngw7.js";import"./chunk-ar5np5h5.js";import"./chunk-dfjmvj3d.js";import"./chunk-tkydv9k8.js";import"./chunk-9d49tj9y.js";import"./chunk-qcvxff27.js";import"./chunk-zwjrensv.js";import"./chunk-pj69j4zp.js";import"./chunk-zkzhm39s.js";export{c as snapshotWorkspaceModelResources,b as resolveWorkspaceModelResources,d as createProcessModelResources,a as cloneWorkspaceModelConfig};
|