blade-code 0.10.145 → 0.10.147

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (76) hide show
  1. package/dist/blade.js +2 -2
  2. package/dist/{chunk-txq7gvbq.js → chunk-0k20kd1p.js} +1 -1
  3. package/dist/{chunk-bpxva62c.js → chunk-0vfa7edt.js} +1 -1
  4. package/dist/{chunk-qptj77rz.js → chunk-278zrrmp.js} +1 -1
  5. package/dist/{chunk-h79tc5ms.js → chunk-27tzxp3t.js} +1 -1
  6. package/dist/chunk-3a217980.js +353 -0
  7. package/dist/{chunk-p07wgyps.js → chunk-3p8zv7w9.js} +1 -1
  8. package/dist/{chunk-cydwzqec.js → chunk-3ytb9cvx.js} +1 -1
  9. package/dist/{chunk-1qcz0vdm.js → chunk-4cewebbd.js} +1 -1
  10. package/dist/{chunk-z2365g42.js → chunk-4x43fqza.js} +1 -1
  11. package/dist/{chunk-3ar9yfmy.js → chunk-51yny2tf.js} +1 -1
  12. package/dist/{chunk-e6p55b6q.js → chunk-67jhfbas.js} +1 -1
  13. package/dist/{chunk-9qm410b7.js → chunk-6jjvja7x.js} +2 -2
  14. package/dist/{chunk-yfx9v808.js → chunk-7jzwgffd.js} +1 -1
  15. package/dist/chunk-7kzydh3d.js +1 -0
  16. package/dist/{chunk-phz87ec4.js → chunk-7vqzy8b8.js} +1 -1
  17. package/dist/{chunk-perarfr7.js → chunk-7zcm8h8d.js} +1 -1
  18. package/dist/{chunk-b7b1h83p.js → chunk-87xebr2g.js} +1 -1
  19. package/dist/{chunk-g3qmbwjp.js → chunk-8n6z6n7n.js} +1 -1
  20. package/dist/{chunk-8g4ybwbw.js → chunk-8ndw8qmz.js} +1 -1
  21. package/dist/{chunk-6zh4327p.js → chunk-9gfev1wf.js} +1 -1
  22. package/dist/{chunk-3aprkwm1.js → chunk-c4t3bcwx.js} +1 -1
  23. package/dist/{chunk-m7dbggvr.js → chunk-ded9k1sa.js} +3 -3
  24. package/dist/{chunk-h1ny468k.js → chunk-fjz96vgp.js} +1 -1
  25. package/dist/{chunk-jrc1qd4n.js → chunk-ghq1pq86.js} +1 -1
  26. package/dist/{chunk-ewrqfjcb.js → chunk-hf3b328q.js} +1 -1
  27. package/dist/{chunk-qwq8gt01.js → chunk-jcbma1x5.js} +1 -1
  28. package/dist/{chunk-3kw9fwyc.js → chunk-k1712thr.js} +1 -1
  29. package/dist/{chunk-sb3h9pbc.js → chunk-kd7p65ap.js} +1 -1
  30. package/dist/chunk-ktv00tfp.js +1 -0
  31. package/dist/{chunk-v1980qg4.js → chunk-nk9vyhe8.js} +1 -1
  32. package/dist/{chunk-a7skt1aw.js → chunk-qkgsbrkq.js} +1 -1
  33. package/dist/{chunk-5p5pcdzj.js → chunk-rqs1yx5d.js} +1 -1
  34. package/dist/{chunk-1j24mgyp.js → chunk-sbtxpp23.js} +1 -1
  35. package/dist/{chunk-qnkfm8bj.js → chunk-sq5p49jz.js} +1 -1
  36. package/dist/{chunk-0kqrg1sv.js → chunk-tyzdgz27.js} +1 -1
  37. package/dist/{chunk-g25x285p.js → chunk-v700k3rh.js} +1 -1
  38. package/dist/{chunk-jwab80w1.js → chunk-w08qmjkx.js} +1 -1
  39. package/dist/{chunk-q7hkcmcd.js → chunk-xye5ev77.js} +2 -2
  40. package/dist/{chunk-rv3zap3q.js → chunk-yb09vpp4.js} +1 -1
  41. package/dist/{chunk-b18242pd.js → chunk-yzvkx1ca.js} +1 -1
  42. package/dist/web/assets/{ChatView-B6YVeOpl.js → ChatView-DLeotTix.js} +4 -4
  43. package/dist/web/assets/{CodeBlockHighlighter-p-CwwjLJ.js → CodeBlockHighlighter-D2MTt30W.js} +1 -1
  44. package/dist/web/assets/{FilePreview-C0zjFfLF.js → FilePreview-D4qb2qRW.js} +1 -1
  45. package/dist/web/assets/{KanbanBoard-BTjc3GTe.js → KanbanBoard-Dvu5NFC8.js} +1 -1
  46. package/dist/web/assets/{MarkdownRenderer-BQUL4vI_.js → MarkdownRenderer-zAXzK89t.js} +3 -3
  47. package/dist/web/assets/{ScrollArea-UfoiaWDB.js → ScrollArea-29MZ2QbM.js} +1 -1
  48. package/dist/web/assets/{SessionHistorySurface-B0WHnLst.js → SessionHistorySurface-DLbGIFWV.js} +1 -1
  49. package/dist/web/assets/{SettingsModal-CkF6k9qu.js → SettingsModal-QKgnx_ht.js} +1 -1
  50. package/dist/web/assets/{Sidebar-DmVMsipF.js → Sidebar-C87AkoeB.js} +2 -2
  51. package/dist/web/assets/{TaskSwitcher-DZELXs23.js → TaskSwitcher-CrIB3IDX.js} +1 -1
  52. package/dist/web/assets/{TerminalPanel-kmWnkCMc.js → TerminalPanel-D0qyZArC.js} +1 -1
  53. package/dist/web/assets/{archive-WXotGSXW.js → archive-fuYu79pQ.js} +1 -1
  54. package/dist/web/assets/{arrow-left-Cb-SEc-l.js → arrow-left-DUzYaGcP.js} +1 -1
  55. package/dist/web/assets/{calendar-clock-BRidlYhb.js → calendar-clock-C7k-na5E.js} +1 -1
  56. package/dist/web/assets/{chevron-right-CoRRZROd.js → chevron-right-Dfc3hcIr.js} +1 -1
  57. package/dist/web/assets/{chevrons-up-down-Cv_JOz8A.js → chevrons-up-down-BKhizLLC.js} +1 -1
  58. package/dist/web/assets/{clock-3-CMvLtvtl.js → clock-3-Dw8vaCAe.js} +1 -1
  59. package/dist/web/assets/{copy-DQqX0OQP.js → copy-CiD7aSAP.js} +1 -1
  60. package/dist/web/assets/{download-FP4WtwG3.js → download-BfRdQJrP.js} +1 -1
  61. package/dist/web/assets/{external-link-BTBZEQYA.js → external-link-C6LILT11.js} +1 -1
  62. package/dist/web/assets/{folder-Dd0PwX-t.js → folder-ujhV3f6N.js} +1 -1
  63. package/dist/web/assets/{index-CXHca5Sw.js → index-B8MqrAmN.js} +3 -3
  64. package/dist/web/assets/{pause-C4azsEtU.js → pause-D7B6HaJT.js} +1 -1
  65. package/dist/web/assets/{pencil-BWrfxaIe.js → pencil-Wm8pFC2G.js} +1 -1
  66. package/dist/web/assets/{play-DgOFsd17.js → play-DkUwzZfo.js} +1 -1
  67. package/dist/web/assets/{plus-KK_f8iC4.js → plus-5VMO57q2.js} +1 -1
  68. package/dist/web/assets/{settings-hrYiD_4G.js → settings-Ch7nPg5W.js} +1 -1
  69. package/dist/web/assets/{team-Yr9DBygX.js → team-YTqtROdX.js} +1 -1
  70. package/dist/web/assets/{teamService-CPSMTxV-.js → teamService-CaFc8Ygx.js} +1 -1
  71. package/dist/web/assets/{terminal-CHxuQT2f.js → terminal-DWDIDHjO.js} +1 -1
  72. package/dist/web/index.html +1 -1
  73. package/package.json +1 -1
  74. package/dist/chunk-2t2hceyc.js +0 -1
  75. package/dist/chunk-fd7ez529.js +0 -338
  76. package/dist/chunk-w6eg8b87.js +0 -1
@@ -1,4 +1,4 @@
1
- import{c as e}from"./index-CXHca5Sw.js";/**
1
+ import{c as e}from"./index-B8MqrAmN.js";/**
2
2
  * @license lucide-react v0.300.0 - ISC
3
3
  *
4
4
  * This source code is licensed under the ISC license.
@@ -1,4 +1,4 @@
1
- import{c as e}from"./index-CXHca5Sw.js";/**
1
+ import{c as e}from"./index-B8MqrAmN.js";/**
2
2
  * @license lucide-react v0.300.0 - ISC
3
3
  *
4
4
  * This source code is licensed under the ISC license.
@@ -1,4 +1,4 @@
1
- import{c as o}from"./index-CXHca5Sw.js";/**
1
+ import{c as o}from"./index-B8MqrAmN.js";/**
2
2
  * @license lucide-react v0.300.0 - ISC
3
3
  *
4
4
  * This source code is licensed under the ISC license.
@@ -1,4 +1,4 @@
1
- import{c as e}from"./index-CXHca5Sw.js";/**
1
+ import{c as e}from"./index-B8MqrAmN.js";/**
2
2
  * @license lucide-react v0.300.0 - ISC
3
3
  *
4
4
  * This source code is licensed under the ISC license.
@@ -1,4 +1,4 @@
1
- import{c as a}from"./index-CXHca5Sw.js";/**
1
+ import{c as a}from"./index-B8MqrAmN.js";/**
2
2
  * @license lucide-react v0.300.0 - ISC
3
3
  *
4
4
  * This source code is licensed under the ISC license.
@@ -1,4 +1,4 @@
1
- import{c as s}from"./index-CXHca5Sw.js";/**
1
+ import{c as s}from"./index-B8MqrAmN.js";/**
2
2
  * @license lucide-react v0.300.0 - ISC
3
3
  *
4
4
  * This source code is licensed under the ISC license.
@@ -1 +1 @@
1
- import{a5 as e,T as t,a6 as r,p as m}from"./session-events-CGQa6VXb.js";import{Z as s}from"./index-CXHca5Sw.js";import"./vendor-react-DofNRwfy.js";import"./vendor-radix-D6QrtXqd.js";const p=e(t.Object({id:t.String(),name:t.String(),subagentType:t.String(),description:t.String(),agentId:t.Optional(t.String()),status:r(["leader","running","completed","failed","cancelled","unknown"]),result:t.Optional(t.Unknown()),stats:t.Optional(t.Unknown()),worktreePath:t.Optional(t.String())})),d=e(t.Object({id:t.String(),subject:t.String(),description:t.String(),status:r(["pending","blocked","running","completed"]),owner:t.Optional(t.String()),priority:r(["high","medium","low"]),dependsOn:t.Array(t.String()),blocks:t.Array(t.String()),result:t.Optional(t.String()),createdAt:t.String(),startedAt:t.Optional(t.String()),completedAt:t.Optional(t.String())})),o=e(t.Object({name:t.String(),description:t.Optional(t.String()),status:r(["idle","running","completed","failed","deleted"]),leadAgentId:t.String(),leadSessionId:t.Optional(t.String()),workspaceRoot:t.Optional(t.String()),peerMessagingEnabled:t.Boolean(),createdAt:t.Number(),updatedAt:t.Number(),deletedAt:t.Optional(t.Number()),members:t.Array(p),tasks:t.Array(d)}));e(t.Object({sessionId:t.String({minLength:1}),projectPath:t.String({minLength:1}),name:t.String({minLength:1}),description:t.Optional(t.String()),leadAgentType:t.Optional(t.String()),peerMessagingEnabled:t.Optional(t.Boolean()),members:t.Array(t.Object({name:t.String({minLength:1}),subagentType:t.String({minLength:1}),description:t.Optional(t.String()),prompt:t.String({minLength:10,maxLength:32*1024})}),{maxItems:32}),tasks:t.Optional(t.Array(t.Object({subject:t.String({minLength:1}),description:t.String({minLength:1}),dependsOn:t.Optional(t.Array(t.String())),assignedTo:t.Optional(t.String()),priority:t.Optional(r(["high","medium","low"]))}),{maxItems:256}))}));e(t.Object({sessionId:t.String({minLength:1}),projectPath:t.String({minLength:1}),to:t.String({minLength:1}),message:t.String({minLength:1,maxLength:32*1024})}));e(t.Object({sessionId:t.String({minLength:1}),projectPath:t.String({minLength:1}),memberId:t.String({minLength:1})}));const S=t.Array(o),u={list:async n=>{const i=new URLSearchParams({sessionId:n.sessionId,projectPath:n.projectPath});return m(S,await s(`/teams?${i.toString()}`))},sendMessage:async(n,i,a,g)=>{await s(`/teams/${encodeURIComponent(i)}/messages`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionId:n.sessionId,projectPath:n.projectPath,to:a,message:g})})},delete:async(n,i)=>{const a=new URLSearchParams({sessionId:n.sessionId,projectPath:n.projectPath});return o.parse(await s(`/teams/${encodeURIComponent(i)}?${a.toString()}`,{method:"DELETE"}))}};export{u as teamService};
1
+ import{a5 as e,T as t,a6 as r,p as m}from"./session-events-CGQa6VXb.js";import{Z as s}from"./index-B8MqrAmN.js";import"./vendor-react-DofNRwfy.js";import"./vendor-radix-D6QrtXqd.js";const p=e(t.Object({id:t.String(),name:t.String(),subagentType:t.String(),description:t.String(),agentId:t.Optional(t.String()),status:r(["leader","running","completed","failed","cancelled","unknown"]),result:t.Optional(t.Unknown()),stats:t.Optional(t.Unknown()),worktreePath:t.Optional(t.String())})),d=e(t.Object({id:t.String(),subject:t.String(),description:t.String(),status:r(["pending","blocked","running","completed"]),owner:t.Optional(t.String()),priority:r(["high","medium","low"]),dependsOn:t.Array(t.String()),blocks:t.Array(t.String()),result:t.Optional(t.String()),createdAt:t.String(),startedAt:t.Optional(t.String()),completedAt:t.Optional(t.String())})),o=e(t.Object({name:t.String(),description:t.Optional(t.String()),status:r(["idle","running","completed","failed","deleted"]),leadAgentId:t.String(),leadSessionId:t.Optional(t.String()),workspaceRoot:t.Optional(t.String()),peerMessagingEnabled:t.Boolean(),createdAt:t.Number(),updatedAt:t.Number(),deletedAt:t.Optional(t.Number()),members:t.Array(p),tasks:t.Array(d)}));e(t.Object({sessionId:t.String({minLength:1}),projectPath:t.String({minLength:1}),name:t.String({minLength:1}),description:t.Optional(t.String()),leadAgentType:t.Optional(t.String()),peerMessagingEnabled:t.Optional(t.Boolean()),members:t.Array(t.Object({name:t.String({minLength:1}),subagentType:t.String({minLength:1}),description:t.Optional(t.String()),prompt:t.String({minLength:10,maxLength:32*1024})}),{maxItems:32}),tasks:t.Optional(t.Array(t.Object({subject:t.String({minLength:1}),description:t.String({minLength:1}),dependsOn:t.Optional(t.Array(t.String())),assignedTo:t.Optional(t.String()),priority:t.Optional(r(["high","medium","low"]))}),{maxItems:256}))}));e(t.Object({sessionId:t.String({minLength:1}),projectPath:t.String({minLength:1}),to:t.String({minLength:1}),message:t.String({minLength:1,maxLength:32*1024})}));e(t.Object({sessionId:t.String({minLength:1}),projectPath:t.String({minLength:1}),memberId:t.String({minLength:1})}));const S=t.Array(o),u={list:async n=>{const i=new URLSearchParams({sessionId:n.sessionId,projectPath:n.projectPath});return m(S,await s(`/teams?${i.toString()}`))},sendMessage:async(n,i,a,g)=>{await s(`/teams/${encodeURIComponent(i)}/messages`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionId:n.sessionId,projectPath:n.projectPath,to:a,message:g})})},delete:async(n,i)=>{const a=new URLSearchParams({sessionId:n.sessionId,projectPath:n.projectPath});return o.parse(await s(`/teams/${encodeURIComponent(i)}?${a.toString()}`,{method:"DELETE"}))}};export{u as teamService};
@@ -1,4 +1,4 @@
1
- import{c as e}from"./index-CXHca5Sw.js";/**
1
+ import{c as e}from"./index-B8MqrAmN.js";/**
2
2
  * @license lucide-react v0.300.0 - ISC
3
3
  *
4
4
  * This source code is licensed under the ISC license.
@@ -5,7 +5,7 @@
5
5
  <link rel="icon" type="image/svg+xml" href="/favicon.svg" />
6
6
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
7
7
  <title>BladeCode</title>
8
- <script type="module" crossorigin src="/assets/index-CXHca5Sw.js"></script>
8
+ <script type="module" crossorigin src="/assets/index-B8MqrAmN.js"></script>
9
9
  <link rel="modulepreload" crossorigin href="/assets/vendor-react-DofNRwfy.js">
10
10
  <link rel="modulepreload" crossorigin href="/assets/vendor-radix-D6QrtXqd.js">
11
11
  <link rel="stylesheet" crossorigin href="/assets/index-RGoMvYl5.css">
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "blade-code",
3
- "version": "0.10.145",
3
+ "version": "0.10.147",
4
4
  "private": false,
5
5
  "description": "🗡️ Blade Code - 智能代码助手命令行工具",
6
6
  "type": "module",
@@ -1 +0,0 @@
1
- import{k as a,l as b,m as c,n as d,o as e}from"./chunk-3ar9yfmy.js";import"./chunk-5p5pcdzj.js";import"./chunk-eg3ms291.js";export{b as setSkipUntilVersion,d as performUpgrade,c as getUpgradeCommand,e as checkVersionOnStartup,a as checkVersion};
@@ -1,338 +0,0 @@
1
- import{gf as w0,hf as hT}from"./chunk-mh9nqbwa.js";import{Dh as MT}from"./chunk-3y2x6fb6.js";import{Dj as yT}from"./chunk-2mk914vk.js";import{Ak as k,Ck as D0,Dk as a,Lk as RT,fk as X0,nk as E,pk as D,qk as i,sk as c,tk as j0,uk as bT,vk as ST,wk as fT}from"./chunk-4wx5sya5.js";import{Mk as Z0}from"./chunk-eg3ms291.js";import{createHash as F_}from"node:crypto";import{readdir as k0,stat as A0}from"node:fs/promises";import G0 from"node:path";import{createHash as oT,randomBytes as u0}from"node:crypto";import{chmod as p0,link as rT,lstat as p,mkdir as eT,open as l,readdir as l0,realpath as v0,unlink as U0}from"node:fs/promises";import K from"node:path";function dT(){return typeof globalThis.Bun<"u"}function sT(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 aT(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 tT(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(dT()){let{Database:Y}=await import("bun:sqlite");G=aT(new Y(T))}else{let Q=(await import("better-sqlite3")).default;G=sT(new Q(T))}return G.exec(tT(_)),G}catch{try{G?.close()}catch{}return null}}var T$="surface-workspaces-v1",n0=/^[a-f0-9]{64}$/,$$=/^acp-remote-workspace:[A-Za-z0-9_-]{43}$/,_$=1024,G$=".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),T$)}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 Y$(T,X),X$(X,()=>Q$(X,async()=>{await B$(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=M$();if(U.has(g))continue;return J$(T,X,Z,_,{version:1,exactIdentityDigest:G,workspaceRef:g})}throw new H("session_surface_state_invalid")}))}async function X$(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 Y$(T,$){try{await V0($,String(T))}catch(_){if(x(_)!=="ENOENT"){if(_ instanceof H)throw _;throw new H("session_surface_state_invalid")}try{await eT($,{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 Q$(T,$){await P?.beforeCapacityLockAttempt?.();let _=await Z$(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 U$(_),_.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 Z$(T){let $=K.join(T,G$),_=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 V$($,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 U$(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 V$(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 B$(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 g$(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 g$(T,$){let _;try{await m(T,$),_=await l(T,"r"),await n(_,T,$);let G=await _.readFile({encoding:"utf8"});return H$(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 H$(T){let $;try{$=JSON.parse(T)}catch{throw new H("session_surface_state_invalid")}if(!O$($))throw new H("session_surface_state_invalid");return $}function O$(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"&&$$.test($.workspaceRef)}function a0(T){return oT("sha256").update(`acp-remote-workspace-exact-identity\x00${T}`).digest("hex")}function M$(){return`acp-remote-workspace:${u0(32).toString("base64url")}`}function C$(){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(!F$(process.platform))return;try{if(P?.syncDirectory){await P.syncDirectory(T);return}await L$(T)}catch{throw new H("session_surface_state_invalid")}}function F$(T){return T!=="win32"}async function L$(T){let $=await l(T,"r");try{await $.sync()}finally{await $.close()}}async function J$(T,$,_,G,X){let Y=K.join($,C$()),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 rT(Y,_),U=!0}catch(M){if(x(M)!=="EEXIST")throw M;g=await N$(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 N$(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,z$=new Set(["queued","running","completed","failed","cancelled","interrupted"]),I$=new Set(["high","medium","low"]),GT=/^[A-Za-z0-9_-]+$/,K$=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?(?:Z|[+-]\d{2}:\d{2})$/,W$=/^acp-remote-exact-path:[a-f0-9]{64}$/;function XT(T){return typeof T==="string"&&K$.test(T)&&Number.isFinite(Date.parse(T))}function o0(T){return typeof T==="string"&&f.isAbsolute(T)}function r0(T){return typeof T==="string"&&W$.test(T)}function j$(T){return Buffer.from(JSON.stringify(T),"utf8").toString("base64url")}function k$(T){return Buffer.from(JSON.stringify(T),"utf8").toString("base64url")}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($);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 x$(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 E$(T){if(!T.cursor)return;let $=A$(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 q$(T){if(!T.cursor)return;let $=x$(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 n_(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 i_(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 c_(T={}){let $=e0(T.taskStatus,z$,"task status"),_=e0(T.taskPriority,I$,"task priority"),G=TT(T.taskDueAfter,"taskDueAfter"),X=TT(T.taskDueBefore,"taskDueBefore");return D$(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 D$(T,$){if(T!==void 0&&$!==void 0&&T>$)throw Error("Session task due range is inverted")}function w$(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 d_(T,$){let _=[...T],G=E$($);if(G)_=_.filter((Q)=>w$(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:j$({version:1,kind:"local",cwd:$.cwd,includeSubagents:$.includeSubagents,archived:$.archived,lastMessageTime:Y.lastMessageTime,projectPath:Y.projectPath,sessionId:Y.sessionId})}}function s_(T,$){let _=[...T],G=q$($);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:k$({version:1,kind:"remote",exactIdentity:$.exactIdentity,includeSubagents:$.includeSubagents,archived:$.archived,lastMessageTime:Y.lastMessageTime,workspaceIdentity:Y.workspaceIdentity,sessionId:Y.sessionId})}}function S$(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<_||!S$(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 t_(T){let $=u(T);return $.filter(H0).map((_)=>({messageId:_.data.messageId,preview:YT($,_.data.messageId),createdAt:_.data.createdAt})).reverse()}function o_(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 i$}from"node:crypto";var e_={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 y$}from"node:string_decoder";var $1=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},f$={maxLines:150,maxChars:15000,keepHead:50,keepTail:50,summarize:!0},R$=[{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 R$)if($.test(T))return{config:_,summaryTemplate:G};return{config:f$}}static truncate(T,$){let{config:_,summaryTemplate:G}=this.getConfigForCommand($);return this.truncateWithConfig(T,_,G)}static truncateWithConfig(T,$,_){let G=T.length,X=T.split(`
3
- `),Y=X.length;if(Y<=$.maxLines&&G<=$.maxChars)return{content:T,truncated:!1,originalLines:Y,originalChars:G};let Q=X.slice(0,$.keepHead),Z=X.slice(-$.keepTail),U=Y-$.keepHead-$.keepTail,V=Q.join(`
4
- `);if(V+=`
5
-
6
- ... (${U} lines truncated, showing first ${$.keepHead} and last ${$.keepTail} of ${Y} total) ...
7
-
8
- `,V+=Z.join(`
9
- `),V.length>$.maxChars){let O=Math.floor($.maxChars/2)-50,M=VT(V,0,O),I=VT(V,V.length-O);V=`${M}
10
-
11
- ... (content truncated to ${$.maxChars} chars) ...
12
-
13
- ${I}`}let g=$.summarize&&_?_(Y,G):void 0;if(g)V+=`
14
-
15
- [Summary: ${g}]`;return{content:V,truncated:!0,originalLines:Y,originalChars:G,summary:g}}static truncateForLLM(T,$,_){let G=this.truncate(T,_),X=this.truncate($,_),Y;if(G.truncated||X.truncated){let Q=[];if(G.truncated)Q.push(`stdout: ${G.originalLines} lines -> ${G.content.split(`
16
- `).length} lines`);if(X.truncated)Q.push(`stderr: ${X.originalLines} lines -> ${X.content.split(`
17
- `).length} lines`);Y=`Output truncated: ${Q.join(", ")}`}return{stdout:G.content,stderr:X.content,truncationInfo:Y}}static shouldTruncate(T,$){let{config:_}=this.getConfigForCommand($);return T.split(`
18
- `).length>_.maxLines||T.length>_.maxChars}static getStats(T){return{lines:T.split(`
19
- `).length,chars:T.length,words:T.split(/\s+/).filter(Boolean).length}}}var BT=32768,h$=1048576,P$=65536,m$=3600000,gT=4096,v$=/[\u001B\u009B][[\]()#;?]*(?:(?:(?:[a-zA-Z\d]*(?:;[-a-zA-Z\d/#&.:=?%@~_]+)*)?\u0007)|(?:(?:\d{1,4}(?:[;:]\d{0,4})*)?[\dA-PR-TZcf-nq-uy=><~]))/g;function U1(){return{async execute(){return{exitCode:null,stdout:"",stderr:"",error:"ACP terminal capability is unavailable"}}}}class L0{stream;executionId;onEvent;output=new C0(h$/2);decoder=new y$("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 $=P$-this.streamedBytes;if($<=0){this.streamTruncated=!0;return}let _=u$(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(v$,"")}function u$(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("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;").replaceAll("'","&apos;")}function p$(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 l$(){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 V1(T,$){let _=p$(T),G=$.timeoutMs??m$,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??l$()).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 B1(T){let $=[T.stdout?`stdout:
21
- ${T.stdout}`:"",T.stderr?`stderr:
22
- ${T.stderr}`:""].filter(Boolean).join(`
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
- `)}function CT(T){let $=[T.stdout,T.stderr?`stderr:
26
- ${T.stderr}`:""].filter(Boolean).join(`
27
- `);return[`! ${T.command}`,$||"(no output)"].join(`
28
- `)}function n$(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 n$(T.userShellCommand)}var c$=262144,d$="session-surface-message\x00",IT="[private state path]",e="[content truncated]",LT=`
29
- ${e}`,T0=String.fromCharCode(27),s$=String.fromCharCode(7),a$=String.fromCharCode(157),t$=String.fromCharCode(156),o$=String.fromCharCode(155),r$=new RegExp(`(?:${w(T0)}\\]|${w(a$)})[\\s\\S]*?(?:${w(s$)}|${w(T0)}\\\\|${w(t$)})`,"g"),e$=new RegExp(`(?:${w(T0)}\\[|${w(o$)})[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 _=H_($.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_(g,V)}let U=[];for(let V of Z.values()){let g=$_(V,G,X,Y,_);if(g)U.push(g)}return U}function T_(T){return typeof T==="object"&&T!==null&&!Array.isArray(T)}function w(T){return T.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function $_(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=Q_(T.event.data.createdAt),O=kT($0($0(Z,_,!0),$),G).trim();if(!O)return;let M=B_(O,X),I=Y_(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 G_(T,$){if($.data.partType!=="text"&&$.data.partType!=="image")return;let _=$.data.partType==="text"?{partId:$.data.partId,type:"text",content:X_($.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 X_(T){if(!T_(T))return"";let $=T.text;return typeof $==="string"?$:""}function Y_(T){let $=I0(T.seq);return z0($,T.data.messageId)}function z0(T,$){let _=I0(T),G=i$("sha256").update(d$).update($).digest("hex").slice(0,16);return`surface-message:${_}:${G}`}function Q_(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=Z_(G,X,_);return G}function Z_(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=U_(T,Z,U);if(V===Z){X+=T[Z],G=Z+1;continue}X+=IT,G=V}return X}function U_(T,$,_){let G=$+_;if(G>=T.length)return G;let X=T[G];if(X===void 0)return G;if(!V_(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 V_(T){return T==="/"||T==="\\"}function zT(T){return T===" "||T==="\t"||T===`
30
- `||T==="\r"||T==='"'||T==="'"||T==="`"||T==="<"||T===">"||T==="("||T===")"||T==="["||T==="]"||T==="{"||T==="}"||T===","||T===";"||T===":"||T==="!"||T==="?"}function AT(T){return[...T.replace(/\r\n?/g,`
31
- `).replace(r$,"").replace(e$,"").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 B_(T,$){if(Buffer.byteLength(T,"utf8")<=$)return{content:T,truncated:!1};let _=g_($),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 g_(T){let $=Buffer.byteLength(LT,"utf8");if(T>=$)return LT;let _=Buffer.byteLength(e,"utf8");if(T>=_)return e;return xT(e,T)}function H_(T){let $=T??c$;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 O_}from"node:fs";import*as N from"node:fs/promises";import*as K0 from"node:path";import{createInterface as M_}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 C_(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
- `),G=!T.endsWith(`
33
- `),X=[];for(let[Y,Q]of _.entries())try{let Z=C_(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
- `)}
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
- `)}
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=O_(this.filePath,"utf-8"),X=M_({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
- `)}
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
- `);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
- `}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
- DROP TABLE IF EXISTS parts_fts;
45
- DROP TABLE IF EXISTS surface_messages;
46
- DROP TABLE IF EXISTS parts;
47
- DROP TABLE IF EXISTS sessions;
48
- DROP TABLE IF EXISTS projection_state;
49
- DROP TABLE IF EXISTS surface_projection_meta;
50
- `);T.exec(`
51
- CREATE TABLE IF NOT EXISTS surface_projection_meta (
52
- singleton INTEGER PRIMARY KEY CHECK(singleton = 1),
53
- catalog_revision INTEGER NOT NULL DEFAULT 0 CHECK(catalog_revision >= 0)
54
- );
55
- INSERT OR IGNORE INTO surface_projection_meta (singleton, catalog_revision)
56
- VALUES (1, 0);
57
-
58
- CREATE TABLE IF NOT EXISTS projection_state (
59
- source_kind TEXT NOT NULL CHECK(source_kind IN ('local', 'acp-remote')),
60
- project_path TEXT NOT NULL,
61
- session_id TEXT NOT NULL,
62
- last_seq INTEGER NOT NULL DEFAULT 0,
63
- file_size INTEGER NOT NULL DEFAULT 0,
64
- mtime_ms INTEGER NOT NULL DEFAULT 0,
65
- stat_fingerprint TEXT NOT NULL DEFAULT '',
66
- PRIMARY KEY (source_kind, project_path, session_id)
67
- );
68
-
69
- CREATE TABLE IF NOT EXISTS sessions (
70
- source_kind TEXT NOT NULL CHECK(source_kind IN ('local', 'acp-remote')),
71
- project_path TEXT NOT NULL,
72
- session_id TEXT NOT NULL,
73
- root_id TEXT,
74
- parent_id TEXT,
75
- relation_type TEXT,
76
- title TEXT,
77
- agent_type TEXT,
78
- model TEXT,
79
- task_status TEXT,
80
- task_priority TEXT,
81
- task_kind TEXT,
82
- task_due_at TEXT,
83
- archived_at TEXT,
84
- last_message_time TEXT,
85
- project_sort_key TEXT NOT NULL,
86
- public_workspace_ref TEXT,
87
- public_workspace_sort_key TEXT NOT NULL,
88
- session_sort_key TEXT NOT NULL,
89
- first_message_time TEXT,
90
- message_count INTEGER NOT NULL DEFAULT 0,
91
- has_errors INTEGER NOT NULL DEFAULT 0,
92
- is_subagent INTEGER NOT NULL DEFAULT 0,
93
- -- 完整 StoredSessionMetadata JSON,读回时直接反序列化,保证与 JSONL 路径一致。
94
- metadata_json TEXT NOT NULL,
95
- surface_digest TEXT NOT NULL,
96
- PRIMARY KEY (source_kind, project_path, session_id)
97
- );
98
- CREATE INDEX IF NOT EXISTS idx_sessions_catalog ON sessions(
99
- last_message_time DESC,
100
- source_kind DESC,
101
- public_workspace_sort_key ASC,
102
- session_sort_key ASC
103
- );
104
- CREATE INDEX IF NOT EXISTS idx_sessions_archived ON sessions(
105
- source_kind,
106
- archived_at,
107
- project_path,
108
- parent_id
109
- );
110
- -- 任务看板过滤/排序:按项目锁定后再按状态、优先级、截止时间收敛。
111
- CREATE INDEX IF NOT EXISTS idx_sessions_task_board ON sessions(
112
- project_path,
113
- task_status,
114
- task_priority,
115
- task_due_at,
116
- source_kind
117
- );
118
- CREATE INDEX IF NOT EXISTS idx_sessions_task_status ON sessions(
119
- task_status,
120
- project_path,
121
- source_kind
122
- );
123
- CREATE INDEX IF NOT EXISTS idx_sessions_task_priority ON sessions(
124
- task_priority,
125
- task_due_at,
126
- source_kind
127
- ) WHERE task_priority IS NOT NULL;
128
- CREATE INDEX IF NOT EXISTS idx_sessions_task_due_at ON sessions(
129
- task_due_at,
130
- source_kind
131
- ) WHERE task_due_at IS NOT NULL;
132
-
133
- CREATE TABLE IF NOT EXISTS parts (
134
- source_kind TEXT NOT NULL CHECK(source_kind IN ('local', 'acp-remote')),
135
- project_path TEXT NOT NULL,
136
- session_id TEXT NOT NULL,
137
- part_id TEXT NOT NULL,
138
- message_id TEXT,
139
- part_type TEXT,
140
- role TEXT,
141
- seq INTEGER,
142
- timestamp TEXT,
143
- text TEXT,
144
- PRIMARY KEY (source_kind, project_path, session_id, part_id)
145
- );
146
- CREATE INDEX IF NOT EXISTS idx_parts_session ON parts(
147
- source_kind, project_path, session_id
148
- );
149
-
150
- CREATE TABLE IF NOT EXISTS surface_messages (
151
- source_kind TEXT NOT NULL CHECK(source_kind IN ('local', 'acp-remote')),
152
- project_path TEXT NOT NULL,
153
- session_id TEXT NOT NULL,
154
- message_seq INTEGER NOT NULL CHECK(message_seq >= 0),
155
- message_id TEXT NOT NULL,
156
- message_json TEXT NOT NULL,
157
- byte_count INTEGER NOT NULL CHECK(byte_count >= 0),
158
- PRIMARY KEY (
159
- source_kind, project_path, session_id, message_seq, message_id
160
- )
161
- );
162
- CREATE INDEX IF NOT EXISTS idx_surface_messages_history ON surface_messages(
163
- source_kind, project_path, session_id, message_seq DESC, message_id DESC
164
- );
165
-
166
- CREATE VIRTUAL TABLE IF NOT EXISTS parts_fts USING fts5(
167
- text,
168
- source_kind UNINDEXED,
169
- project_path UNINDEXED,
170
- session_id UNINDEXED,
171
- part_id UNINDEXED,
172
- role UNINDEXED,
173
- timestamp UNINDEXED,
174
- seq UNINDEXED,
175
- tokenize = 'unicode61'
176
- );
177
- `),T.exec("PRAGMA user_version=7;")}var L_=yT("Service"),J_="session-surface-projection-v1\x00",x0=524288,N_=3,z_=new AbortController().signal,I_=/^acp-remote-workspace:[A-Za-z0-9_-]{43}$/,PT=`WITH RECURSIVE archive_members(
178
- source_kind, project_path, public_workspace_ref, session_id, archive_root_id,
179
- effective_archived_at, depth
180
- ) AS (
181
- SELECT source_kind, project_path, public_workspace_ref, session_id, session_id,
182
- archived_at, 0
183
- FROM sessions
184
- WHERE archived_at IS NOT NULL
185
- UNION ALL
186
- SELECT child.source_kind, child.project_path, child.public_workspace_ref,
187
- child.session_id, parent.archive_root_id, parent.effective_archived_at,
188
- parent.depth + 1
189
- FROM sessions child
190
- JOIN archive_members parent
191
- ON child.source_kind = parent.source_kind
192
- AND child.project_path = parent.project_path
193
- AND child.public_workspace_ref IS parent.public_workspace_ref
194
- AND child.parent_id = parent.session_id
195
- WHERE parent.depth < 128
196
- ),
197
- ranked_archive AS (
198
- SELECT source_kind, project_path, public_workspace_ref, session_id,
199
- archive_root_id, effective_archived_at,
200
- ROW_NUMBER() OVER (
201
- PARTITION BY source_kind, project_path, public_workspace_ref, session_id
202
- ORDER BY depth ASC, archive_root_id ASC
203
- ) AS rank
204
- FROM archive_members
205
- )`,mT={readSession(T,$,_){return $?T.readAllValidated({noFollow:!0,signal:_,validateHandle:(G)=>bT($,T.getFilePath(),G)}):T.readAll({signal:_})}},b0=mT;function y1(T){b0=T}function h1(){b0=mT}function P1(){return x0}var s;function vT(){return G0.join(X0(),"index.db")}async function K_(){let T=vT();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 W_(){s=void 0}function j_(T){if(T&&typeof T==="object"){let $=T.text;if(typeof $==="string")return $}return null}function k_(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
- (source_kind, project_path, session_id, part_id, message_id, part_type, role,
207
- seq, timestamp, text)
208
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`),Z=T.prepare(`INSERT INTO parts_fts
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=j_(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 A_(T,$,_,G){let{metadata:X,publicWorkspaceRef:Y}=_,Q=v(Y??X.projectPath);T.prepare(`INSERT INTO sessions
211
- (source_kind, project_path, session_id, root_id, parent_id, relation_type, title,
212
- agent_type, model, task_status, task_priority, task_kind, task_due_at,
213
- archived_at, last_message_time, project_sort_key,
214
- public_workspace_ref, public_workspace_sort_key, session_sort_key,
215
- first_message_time, message_count, has_errors, is_subagent, metadata_json,
216
- surface_digest)
217
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
218
- ON CONFLICT(source_kind, project_path, session_id) DO UPDATE SET
219
- root_id=excluded.root_id, parent_id=excluded.parent_id,
220
- relation_type=excluded.relation_type, title=excluded.title,
221
- agent_type=excluded.agent_type, model=excluded.model,
222
- task_status=excluded.task_status, task_priority=excluded.task_priority,
223
- task_kind=excluded.task_kind, task_due_at=excluded.task_due_at,
224
- archived_at=excluded.archived_at,
225
- last_message_time=excluded.last_message_time,
226
- project_sort_key=excluded.project_sort_key,
227
- public_workspace_ref=excluded.public_workspace_ref,
228
- public_workspace_sort_key=excluded.public_workspace_sort_key,
229
- session_sort_key=excluded.session_sort_key,
230
- first_message_time=excluded.first_message_time, message_count=excluded.message_count,
231
- has_errors=excluded.has_errors, is_subagent=excluded.is_subagent,
232
- metadata_json=excluded.metadata_json, surface_digest=excluded.surface_digest`).run($,X.projectPath,X.sessionId,X.rootId,X.parentId??null,X.relationType??null,X.title??null,X.agentType??null,X.model??null,X.taskStatus,X.taskPriority??null,X.taskKind??null,X.taskDueAt??null,X.archivedAt??null,X.lastMessageTime,v(X.projectPath),Y??null,Q,v(X.sessionId),X.firstMessageTime,X.messageCount,X.hasErrors?1:0,X.relationType==="subagent"?1:0,JSON.stringify(X),G)}function q(T){T.prepare(`UPDATE surface_projection_meta
233
- SET catalog_revision=catalog_revision + 1 WHERE singleton=1`).run()}function x_(T,$,_,G,X,Y){T.prepare(`DELETE FROM surface_messages
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
- (source_kind, project_path, session_id, message_seq, message_id,
236
- message_json, byte_count)
237
- VALUES (?, ?, ?, ?, ?, ?, ?)`);for(let U of Y){let V=w0.parse(U),g=uT(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 uT(T){let $=/^surface-message:([0-9]+):/.exec(T),_=$?Number($[1]):Number.NaN;if(!Number.isSafeInteger(_)||_<0)throw new J;return _}function E_(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}},...pT($,T.publicWorkspaceRef)};return F_("sha256").update(J_).update(JSON.stringify({catalogSummary:_,messages:T.surfaceMessages})).digest("hex")}function pT(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,Q=hT(T.taskCompletedAt);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,...Q!==void 0?{taskCompletedAt:Q}:{},messageCount:T.messageCount,firstMessageTime:T.firstMessageTime,lastMessageTime:T.lastMessageTime,hasErrors:T.hasErrors,...T.archivedAt!==void 0?{archivedAt:T.archivedAt}:{},...T.selectedModelId!==void 0?{selectedModelId:N0(T.selectedModelId,G)}:{}}}function q_(T,$,_,G){return T.prepare(`SELECT EXISTS(
238
- SELECT 1 FROM sessions
239
- WHERE source_kind=? AND project_path=? AND session_id=?
240
- UNION ALL
241
- SELECT 1 FROM surface_messages
242
- WHERE source_kind=? AND project_path=? AND session_id=?
243
- ) AS present`).get($,_,G,$,_,G)?.present===1}function S0(T,$,_,G){let X=q_(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 D_(T,$,_){let G=T.prepare(`SELECT project_path, session_id FROM sessions
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
- (source_kind, project_path, session_id, last_seq, file_size, mtime_ms,
246
- stat_fingerprint)
247
- VALUES (?, ?, ?, ?, ?, ?, ?)
248
- ON CONFLICT(source_kind, project_path, session_id) DO UPDATE SET
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(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<N_;P0+=1){Z?.throwIfAborted();let m0=await b0.readSession(g,Q,Z??z_);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=D_(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=E_(y0),Y0=T.prepare(`SELECT last_message_time FROM sessions
252
- WHERE source_kind=? AND project_path=? AND session_id=?`).get(Y,F.projectPath,F.sessionId),iT=Y==="acp-remote"&&Q?a(Q,F.sessionId):D0(F.projectPath,F.sessionId),cT=G0.resolve(X)===G0.resolve(iT);if(Y0&&!cT&&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(A_(T,Y,y0,h0),k_(T,Y,F.projectPath,F.sessionId,z),x_(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
- WHERE source_kind=? AND project_path=?
255
- UNION
256
- SELECT session_id FROM sessions
257
- WHERE source_kind=? AND project_path=?
258
- UNION
259
- SELECT session_id FROM parts
260
- WHERE source_kind=? AND project_path=?
261
- UNION
262
- SELECT session_id FROM parts_fts
263
- WHERE source_kind=? AND project_path=?
264
- UNION
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(b(T,$,_,Y.session_id))q(T)}}async function w_(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 m1(T,$,_){_?.throwIfAborted();let G=await fT();_?.throwIfAborted();for(let Q of G)_?.throwIfAborted(),await w_(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
- UNION
268
- SELECT project_path FROM sessions WHERE source_kind='acp-remote'
269
- UNION
270
- SELECT project_path FROM parts WHERE source_kind='acp-remote'
271
- UNION
272
- SELECT project_path FROM parts_fts WHERE source_kind='acp-remote'
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 b_(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=S_(T,$);G.inFlight=X;try{await X,G.lastCompletedAt=Date.now()}finally{if(G.inFlight===X)G.inFlight=void 0}}async function S_(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
- 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}),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")L_.warn(`[SessionService] Skipping invalid session transcript: ${B.sessionId}`)}}}));let I=T.prepare(`SELECT source_kind, project_path, session_id FROM projection_state
277
- UNION
278
- SELECT source_kind, project_path, session_id FROM sessions
279
- WHERE source_kind='acp-remote'
280
- UNION
281
- SELECT source_kind, project_path, session_id FROM parts
282
- WHERE source_kind='acp-remote'
283
- UNION
284
- SELECT source_kind, project_path, session_id FROM parts_fts
285
- WHERE source_kind='acp-remote'
286
- UNION
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(b(T,B.source_kind,B.project_path,B.session_id))q(T)})}function v1(T,$,_,G="local"){T.transaction(()=>{if(b(T,G,_,$))q(T)})}async function u1(T){let{rm:$}=await import("node:fs/promises");W_();let _=vT();for(let Y of["","-wal","-shm"])await $(`${_}${Y}`,{force:!0}).catch(()=>{return});let G=await K_();if(!G)return null;return await b_(G,T),G.prepare("SELECT COUNT(*) c FROM sessions").get()?.c??0}function lT(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||!I_.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=pT(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 p1(T,$){if(!k($))throw new J;try{return T.prepare(`${PT}
289
- SELECT s.source_kind, s.project_path, s.session_id, s.root_id, s.parent_id,
290
- s.relation_type, s.task_status, s.first_message_time,
291
- s.last_message_time, s.title, s.archived_at, s.message_count,
292
- s.has_errors,
293
- s.is_subagent, a.archive_root_id, a.effective_archived_at,
294
- s.public_workspace_ref, s.public_workspace_sort_key,
295
- s.session_sort_key, s.surface_digest, p.stat_fingerprint,
296
- s.metadata_json
297
- FROM sessions s
298
- JOIN projection_state p USING (source_kind, project_path, session_id)
299
- LEFT JOIN ranked_archive a
300
- ON a.source_kind=s.source_kind AND a.project_path=s.project_path
301
- AND a.public_workspace_ref IS s.public_workspace_ref
302
- AND a.session_id=s.session_id AND a.rank=1
303
- WHERE s.session_id=?
304
- ORDER BY s.source_kind DESC, s.public_workspace_sort_key ASC,
305
- s.session_sort_key ASC`).all($).map(lT)}catch{throw new J}}function f_(T){let $=T.prepare("SELECT catalog_revision FROM surface_projection_meta WHERE singleton=1").get()?.catalog_revision;if(!Number.isSafeInteger($)||$===void 0||$<0)throw new J;return $}function l1(T,$){return nT($.limit),T.transaction(()=>{let _=[],G=["s.is_subagent=0",$.archived?"a.session_id IS NOT NULL":"a.session_id IS NULL"];if($.workspaceKind!==void 0)G.push("s.source_kind=?"),_.push($.workspaceKind);if($.boundary!==void 0)G.push(`(s.last_message_time < ?
306
- OR (s.last_message_time = ? AND s.source_kind < ?)
307
- OR (s.last_message_time = ? AND s.source_kind = ?
308
- AND s.public_workspace_sort_key > ?)
309
- OR (s.last_message_time = ? AND s.source_kind = ?
310
- AND s.public_workspace_sort_key = ? AND s.session_sort_key > ?))`),_.push($.boundary.lastMessageTime,$.boundary.lastMessageTime,$.boundary.sourceKind,$.boundary.lastMessageTime,$.boundary.sourceKind,$.boundary.publicWorkspaceSortKey,$.boundary.lastMessageTime,$.boundary.sourceKind,$.boundary.publicWorkspaceSortKey,$.boundary.sessionSortKey);_.push($.limit+1);let X=f_(T),Y=T.prepare(`${PT}
311
- SELECT s.source_kind, s.project_path, s.session_id, s.root_id, s.parent_id,
312
- s.relation_type, s.task_status, s.first_message_time,
313
- s.last_message_time, s.title, s.archived_at, s.message_count,
314
- s.has_errors,
315
- s.is_subagent, a.archive_root_id, a.effective_archived_at,
316
- s.public_workspace_ref, s.public_workspace_sort_key,
317
- s.session_sort_key, s.surface_digest, p.stat_fingerprint,
318
- s.metadata_json
319
- FROM sessions s
320
- JOIN projection_state p USING (source_kind, project_path, session_id)
321
- LEFT JOIN ranked_archive a
322
- ON a.source_kind=s.source_kind AND a.project_path=s.project_path
323
- AND a.public_workspace_ref IS s.public_workspace_ref
324
- AND a.session_id=s.session_id AND a.rank=1
325
- WHERE ${G.join(" AND ")}
326
- ORDER BY s.last_message_time DESC, s.source_kind DESC,
327
- s.public_workspace_sort_key ASC, s.session_sort_key ASC
328
- LIMIT ?`).all(..._),Q=Y.slice(0,$.limit),Z=Q.map(lT),U=Y.length>$.limit?Q.at(-1):void 0;return{revision:X,sessions:Z,...U?{nextBoundary:{lastMessageTime:U.last_message_time,sourceKind:U.source_kind,publicWorkspaceSortKey:U.public_workspace_sort_key,sessionSortKey:U.session_sort_key}}:{}}})}function n1(T,$){if(nT($.limit),$.beforeSequence!==void 0&&(!Number.isSafeInteger($.beforeSequence)||$.beforeSequence<0))throw new J;let _=$.maxBytes??x0;if(!Number.isSafeInteger(_)||_<1)throw new J;let G=Math.min(_,x0);return T.transaction(()=>{let X=T.prepare(`SELECT surface_digest, stat_fingerprint FROM sessions
329
- JOIN projection_state USING (source_kind, project_path, session_id)
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
- FROM surface_messages
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 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)=>R_(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 R_(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)||uT($.id)!==T.message_seq)throw new J;return $}catch{throw new J}}function nT(T){if(!Number.isSafeInteger(T)||T<1||T>100)throw new J}function i1(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
- WHERE parts_fts MATCH ? AND source_kind = 'local' AND project_path = ?
335
- ORDER BY timestamp DESC LIMIT ?`:`SELECT session_id, role, timestamp, text FROM parts_fts
336
- WHERE parts_fts MATCH ? AND source_kind = 'local'
337
- ORDER BY timestamp DESC LIMIT ?`,Z=T.prepare(Q);return _?Z.all(Y,_,G):Z.all(Y,G)}
338
- export{d0 as ne,u as oe,t_ as pe,o_ as qe,d as re,j as se,v as te,E$ as ue,q$ as ve,n_ as we,i_ as xe,c_ as ye,w$ as ze,b$ as Ae,d_ as Be,s_ as Ce,e_ as De,ZT as Ee,$1 as Fe,C0 as Ge,F0 as He,U1 as Ie,V1 as Je,B1 as Ke,CT as Le,FT as Me,J0 as Ne,KT as Oe,y1 as Pe,h1 as Qe,P1 as Re,vT as Se,K_ as Te,W_ as Ue,pT as Ve,DT as We,w_ as Xe,m1 as Ye,b_ as Ze,v1 as _e,u1 as $e,p1 as af,f_ as bf,l1 as cf,n1 as df,i1 as ef};
@@ -1 +0,0 @@
1
- import{qf as a,rf as b}from"./chunk-6zh4327p.js";import"./chunk-5p5pcdzj.js";import"./chunk-eg3ms291.js";export{a as globalOptions,b as cliConfig};